拖动区域和滑块、输入任何 CSS 颜色或选择预设,来挑选一个颜色。

用取色器挑一个颜色,比如品牌色或主题色。值是 CSS 颜色字符串,每个部件都在编辑它:一个同时编辑两个通道的区域、每个通道一个滑块、一个能读取任何 CSS 颜色的文本输入框,以及预设。

import { formatColor, parseColor, type ColorFormat } from "@ui-sdk/solid/color"
import {
  ColorPicker,
  ColorPickerArea,
  ColorPickerAreaThumb,
  ColorPickerEyeDropper,
  ColorPickerInput,
  ColorPickerSlider,
  ColorPickerSliderThumb,
  ColorPickerSwatch,
  ColorPickerSwatches,
  ColorPickerSwatchItem,
} from "@ui-sdk/solid/color-picker"
import { createSignal, For } from "solid-js"

const formats: { label: string; value: ColorFormat }[] = [
  { label: "Hex", value: "hex" },
  { label: "RGB", value: "srgb" },
  { label: "HSL", value: "hsl" },
  { label: "OKLCH", value: "oklch" },
]

const presets = [
  "#ef4444",
  "#f97316",
  "#eab308",
  "#22c55e",
  "#0ea5e9",
  "#6366f1",
  "#a855f7",
  "#ec4899",
]

function Example() {
  const [format, setFormat] = createSignal<ColorFormat>("hex")
  const [value, setValue] = createSignal("#0ea5e9")

  function changeFormat(next: ColorFormat) {
    setFormat(next)
    setValue(formatColor(parseColor(value())!, next))
  }

  return (
    <ColorPicker
      aria-label="Brand color"
      format={format()}
      value={value()}
      onValueChange={(next) => setValue(next)}
    >
      <ColorPickerArea>
        <ColorPickerAreaThumb />
      </ColorPickerArea>
      <div data-slot="row">
        <ColorPickerEyeDropper aria-label="Pick from screen">
          <svg
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
            aria-hidden="true"
          >
            <path d="m12 9-8.414 8.414A2 2 0 0 0 3 18.828v1.344a2 2 0 0 1-.586 1.414A2 2 0 0 1 3.828 21h1.344a2 2 0 0 0 1.414-.586L15 12" />
            <path d="m18 9 .4.4a1 1 0 1 1-3 3l-3.8-3.8a1 1 0 1 1 3-3l.4.4 3.4-3.4a1 1 0 1 1 3 3z" />
            <path d="m2 22 .414-.414" />
          </svg>
        </ColorPickerEyeDropper>
        <div data-slot="color-picker-sliders">
          <ColorPickerSlider channel="hue">
            <ColorPickerSliderThumb />
          </ColorPickerSlider>
          <ColorPickerSlider channel="alpha">
            <ColorPickerSliderThumb />
          </ColorPickerSlider>
        </div>
        <ColorPickerSwatch />
      </div>
      <div data-slot="row">
        <select
          aria-label="Format"
          value={format()}
          onChange={(event) =>
            changeFormat(event.currentTarget.value as ColorFormat)
          }
        >
          <For each={formats}>
            {(option) => <option value={option.value}>{option.label}</option>}
          </For>
        </select>
        <ColorPickerInput aria-label="Color" />
      </div>
      <ColorPickerSwatches aria-label="Presets">
        <For each={presets}>
          {(preset) => <ColorPickerSwatchItem value={preset} />}
        </For>
      </ColorPickerSwatches>
    </ColorPicker>
  )
}

export { Example }
拖动区域或滑块,或者选择一个预设。选择 HSL 换一种方式写颜色,或者输入 rebeccapurple 这样的颜色并按 Enter。

安装

npm install @ui-sdk/solid @ui-sdk/core

组合

用下面的组合构建 ColorPicker:

ColorPicker
├── ColorPickerArea
│   ├── ColorPickerAreaCanvas
│   └── ColorPickerAreaThumb
├── ColorPickerSlider
│   └── ColorPickerSliderThumb
├── ColorPickerSlider
│   └── ColorPickerSliderThumb
├── ColorPickerSwatch
├── ColorPickerInput
├── ColorPickerChannelInput
├── ColorPickerEyeDropper
└── ColorPickerSwatches
    ├── ColorPickerSwatchItem
    └── ColorPickerSwatchItem

每个部件都是可选的,按你的取色器需要选用。

  • ColorPicker 持有值,是包住各部件的一组。
  • ColorPickerArea 一次编辑两个通道,比如横向是饱和度、纵向是亮度。按压会把手柄移到那里并开始拖动。它的背景是 --color-area-background,所以要给它尺寸和这个背景。
  • ColorPickerAreaCanvas 逐像素绘制区域,用于渐变画不出来的通道,比如 OKLCH 的色度和明度。
  • ColorPickerAreaThumb 显示颜色在区域里的位置。它是一个滑块,屏幕阅读器会把它听成这两个通道。
  • ColorPickerSlider 编辑一个 channel,比如 hue 或 alpha,由 --color-slider-background 绘制。
  • ColorPickerSliderThumb 显示该通道在滑块上的位置。
  • ColorPickerSwatch 显示颜色,并由屏幕阅读器读出名称,比如“vivid blue”。
  • ColorPickerInput 在你按 Enter 或离开它时读取任何 CSS 颜色。不是颜色的文本会退回到原来的值。
  • ColorPickerChannelInput 把一个 channel 当作数字编辑,用人们平时读它的单位,比如红色是 0 到 255。
  • ColorPickerEyeDropper 在浏览器支持的地方,从屏幕上的任何位置取色。
  • ColorPickerSwatches 和 ColorPickerSwatchItem 是预设颜色的列表。

每个部件都把颜色写成 --color-picker-color,所以手柄或色块可以用 background: var(--color-picker-color) 给自己上色。取色器还渲染一个隐藏输入框,供表单提交。

用法

导入部件并把它们组合起来:

import {
  ColorPicker,
  ColorPickerArea,
  ColorPickerAreaThumb,
  ColorPickerInput,
  ColorPickerSlider,
  ColorPickerSliderThumb,
} from "@ui-sdk/solid/color-picker"

function BrandColor() {
  return (
    <ColorPicker aria-label="Brand color" defaultValue="#0ea5e9">
      <ColorPickerArea>
        <ColorPickerAreaThumb />
      </ColorPickerArea>
      <ColorPickerSlider channel="hue">
        <ColorPickerSliderThumb />
      </ColorPickerSlider>
      <ColorPickerInput aria-label="Hex" />
    </ColorPicker>
  )
}

export { BrandColor }

用 aria-label 给取色器命名,或者把它放进 Field 里,由字段的标签给它命名。没有 defaultValue 时,它从黑色开始。

色彩空间与通道

space 决定部件编辑哪些通道,以及值用什么写法:

space区域,横向与纵向滑块值的写法
hsv饱和度、亮度色相十六进制,比如 #0ea5e9
hsl饱和度、明度色相hsl(198.63 88.66% 48.43%)
srgb红、绿蓝rgb(14 165 233)
oklch色度、明度色相oklch(0.6847 0.1479 237.32)

设置 format 换一种方式写值,比如在任何空间里写 format="hex"。每个空间也都有一个 alpha 通道。在区域上设置 x 和 y,或者在滑块上设置 channel,来编辑其他通道:

<ColorPicker
  aria-label="Background"
  space="hsl"
  defaultValue="hsl(220 60% 50%)"
>
  <ColorPickerArea x="hue" y="lightness">
    <ColorPickerAreaCanvas />
    <ColorPickerAreaThumb />
  </ColorPickerArea>
  <ColorPickerSlider channel="saturation" orientation="vertical">
    <ColorPickerSliderThumb />
  </ColorPickerSlider>
</ColorPicker>

颜色变灰或变黑时,部件会记住色相,所以从角落拖回来,还是同一个色相。

OKLCH

OKLCH 按人眼的感觉均匀地排布颜色,所以明度相同的两种颜色看起来一样亮。它与屏幕能显示的颜色之间的边界是一条曲线,任何渐变都画不出来。给区域加上 ColorPickerAreaCanvas,它会画出边界以内的颜色,其余部分留空。

import {
  ColorPicker,
  ColorPickerArea,
  ColorPickerAreaCanvas,
  ColorPickerAreaThumb,
  ColorPickerInput,
  ColorPickerSlider,
  ColorPickerSliderThumb,
  ColorPickerSwatch,
} from "@ui-sdk/solid/color-picker"

function Example() {
  return (
    <ColorPicker
      aria-label="Accent"
      space="oklch"
      defaultValue="oklch(0.62 0.19 259)"
    >
      <ColorPickerArea>
        <ColorPickerAreaCanvas />
        <ColorPickerAreaThumb />
      </ColorPickerArea>
      <ColorPickerSlider channel="hue">
        <ColorPickerSliderThumb />
      </ColorPickerSlider>
      <ColorPickerSlider channel="alpha">
        <ColorPickerSliderThumb />
      </ColorPickerSlider>
      <div data-slot="row">
        <ColorPickerSwatch />
        <ColorPickerInput aria-label="OKLCH" />
      </div>
    </ColorPicker>
  )
}

export { Example }
把滑块手柄向右拖过画出的边界,然后松开。手柄会退回到边界内最接近的颜色。

拖动把颜色带到边界之外时,值已经是边界内最接近的颜色,每个部件都带有 data-out-of-gamut。拖动结束后,手柄会移到那个颜色。默认情况下颜色保持在 sRGB 之内。为广色域屏幕设置 gamut="p3",或者用 gamut={false} 允许任何颜色:

<ColorPicker
  aria-label="Accent"
  space="oklch"
  gamut="p3"
  defaultValue="oklch(0.7 0.25 150)"
>
  {/* … */}
</ColorPicker>

预设与通道输入

把 ColorPickerSwatchItem 放进 ColorPickerSwatches,作为预设颜色。当值是它的颜色时,它就会被选中,不管两者各自怎么写,所以 #0000ff 会选中 rgb(0 0 255)。列表是一个 Tab 停靠点,方向键在预设之间移动。

ColorPickerChannelInput 把一个通道当作数字编辑,按 Enter、离开它或者用它的箭头时设置。ColorPickerEyeDropper 在支持的浏览器里从屏幕上取色。在其他地方它是禁用的,带有 data-unsupported,所以你可以把它隐藏。

import {
  ColorPicker,
  ColorPickerChannelInput,
  ColorPickerEyeDropper,
  ColorPickerSwatches,
  ColorPickerSwatchItem,
} from "@ui-sdk/solid/color-picker"
import { For } from "solid-js"

const presets = [
  "#ef4444",
  "#f97316",
  "#eab308",
  "#22c55e",
  "#0ea5e9",
  "#6366f1",
  "#a855f7",
  "#ec4899",
]

function Example() {
  return (
    <ColorPicker
      aria-label="Label color"
      space="srgb"
      format="hex"
      defaultValue="#0ea5e9"
    >
      <ColorPickerSwatches aria-label="Presets">
        <For each={presets}>
          {(preset) => <ColorPickerSwatchItem value={preset} />}
        </For>
      </ColorPickerSwatches>
      <div data-slot="row">
        <ColorPickerChannelInput channel="red" />
        <ColorPickerChannelInput channel="green" />
        <ColorPickerChannelInput channel="blue" />
        <ColorPickerEyeDropper aria-label="Pick from screen">
          <svg
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
            aria-hidden="true"
          >
            <path d="m12 9-8.414 8.414A2 2 0 0 0 3 18.828v1.344a2 2 0 0 1-.586 1.414A2 2 0 0 1 3.828 21h1.344a2 2 0 0 0 1.414-.586L15 12" />
            <path d="m18 9 .4.4a1 1 0 1 1-3 3l-3.8-3.8a1 1 0 1 1 3-3l.4.4 3.4-3.4a1 1 0 1 1 3 3z" />
            <path d="m2 22 .414-.414" />
          </svg>
        </ColorPickerEyeDropper>
      </div>
    </ColorPicker>
  )
}

export { Example }
选择一个预设,或者在它们之间使用方向键。在第一个数字里输入 255 来设置红色。

Popover

把 Popover 放进取色器,从色块打开它。浮层里的部件编辑同一个颜色,触发器里的色块显示它。

import {
  ColorPicker,
  ColorPickerArea,
  ColorPickerAreaThumb,
  ColorPickerInput,
  ColorPickerSlider,
  ColorPickerSliderThumb,
  ColorPickerSwatch,
} from "@ui-sdk/solid/color-picker"
import { Popover, PopoverContent, PopoverTrigger } from "@ui-sdk/solid/popover"

function Example() {
  return (
    <ColorPicker aria-label="Background" defaultValue="#22c55e">
      <Popover>
        <PopoverTrigger aria-label="Background">
          <ColorPickerSwatch />
        </PopoverTrigger>
        <PopoverContent>
          <ColorPickerArea>
            <ColorPickerAreaThumb />
          </ColorPickerArea>
          <ColorPickerSlider channel="hue">
            <ColorPickerSliderThumb />
          </ColorPickerSlider>
          <ColorPickerInput aria-label="Hex" />
        </PopoverContent>
      </Popover>
    </ColorPicker>
  )
}

export { Example }
按压 Background 色块打开取色器,然后拖动来改变颜色。

禁用

设置 disabled。禁用的取色器不能获得焦点,也不能修改,并且不会被提交。包住它的禁用 <fieldset> 也会禁用它。

import {
  ColorPicker,
  ColorPickerArea,
  ColorPickerAreaThumb,
  ColorPickerInput,
  ColorPickerSlider,
  ColorPickerSliderThumb,
} from "@ui-sdk/solid/color-picker"

function Example() {
  return (
    <ColorPicker aria-label="Brand color" defaultValue="#0ea5e9" disabled>
      <ColorPickerArea>
        <ColorPickerAreaThumb />
      </ColorPickerArea>
      <ColorPickerSlider channel="hue">
        <ColorPickerSliderThumb />
      </ColorPickerSlider>
      <ColorPickerInput aria-label="Hex" />
    </ColorPicker>
  )
}

export { Example }
手柄不能获得焦点,也不能拖动。

设置 readOnly,让部件保持可聚焦、值仍会被提交,同时拖动、按键和输入都不会改变颜色:

<ColorPicker aria-label="Theme color" defaultValue="#0ea5e9" readOnly>
  <ColorPickerSwatch />
  <ColorPickerInput aria-label="Hex" />
</ColorPicker>

受控

传入 value,并在 onValueChange 里更新它。每次变更都带一个原因,比如 drag、step-key 或 input-commit,以及 details.color,也就是部件持有的颜色,它会在值变灰时保留色相。在回调里调用 details.cancel() 保留当前值。

onValueChange 在拖动的每一步运行。onValueCommit 只运行一次,在拖动、按键或输入颜色结束时,所以用它来保存。来自 createColorPickerController() 的控制器可以从任何地方用 setValue() 设置颜色,比如下面的 Use Purple 按钮。

控制台
import {
  ColorPicker,
  ColorPickerArea,
  ColorPickerAreaThumb,
  ColorPickerInput,
  ColorPickerSlider,
  ColorPickerSliderThumb,
  createColorPickerController,
} from "@ui-sdk/solid/color-picker"
import { createSignal } from "solid-js"
import { useLog } from "./log"

function Example() {
  const log = useLog()
  const picker = createColorPickerController()
  const [value, setValue] = createSignal("#0ea5e9")

  return (
    <div>
      <div data-slot="controls">
        <button type="button" onClick={() => picker.setValue("#663399")}>
          Use Purple
        </button>
      </div>
      <ColorPicker
        aria-label="Theme color"
        value={value()}
        onValueChange={(next) => setValue(next)}
        onValueCommit={(next, details) =>
          log(`committed: ${next} (${details.reason})`)
        }
        controller={picker}
      >
        <ColorPickerArea>
          <ColorPickerAreaThumb />
        </ColorPickerArea>
        <ColorPickerSlider channel="hue">
          <ColorPickerSliderThumb />
        </ColorPickerSlider>
        <ColorPickerInput aria-label="Hex" />
      </ColorPicker>
    </div>
  )
}

export { Example }
拖动区域再松开,或者按 Use Purple。控制台记录每次提交的颜色和它的原因。

受控状态、取消和调试见状态与事件。

表单

隐藏输入框在 name 下提交值,比如 #f97316,禁用的取色器不提交任何东西。表单重置把它恢复到 defaultValue。设置 form 按 id 加入某个表单。

控制台
import {
  ColorPicker,
  ColorPickerArea,
  ColorPickerAreaThumb,
  ColorPickerSlider,
  ColorPickerSliderThumb,
  ColorPickerSwatch,
} from "@ui-sdk/solid/color-picker"
import { Field, FieldLabel } from "@ui-sdk/solid/field"
import { useLog } from "./log"

function Example() {
  const log = useLog()

  return (
    <form
      data-slot="stack"
      onSubmit={(event) => {
        event.preventDefault()
        log(`Submitted brand=${new FormData(event.currentTarget).get("brand")}`)
      }}
    >
      <Field>
        <FieldLabel>Brand color</FieldLabel>
        <ColorPicker name="brand" defaultValue="#f97316">
          <ColorPickerArea>
            <ColorPickerAreaThumb />
          </ColorPickerArea>
          <div data-slot="row">
            <ColorPickerSwatch />
            <ColorPickerSlider channel="hue">
              <ColorPickerSliderThumb />
            </ColorPickerSlider>
          </div>
        </ColorPicker>
      </Field>
      <div data-slot="row">
        <button type="submit" data-variant="solid">
          Save
        </button>
        <button type="reset">Reset</button>
      </div>
    </form>
  )
}

export { Example }
改变颜色并按 Save,记录提交的值。Reset 恢复橙色。

取色器总是有值,所以 required 只会加上 data-required。

自定义渲染

每个部件都接受 render,用来在它的位置渲染不同的元素或组件。render、class 和 children 可以是部件状态的函数。滑块手柄的状态有它的 channelValue,预设的状态有它是否 selected,每个部件都有 color 以及它是否 outOfGamut:

<ColorPickerSlider channel="alpha">
  <ColorPickerSliderThumb class={(state) => (state.outOfGamut ? "dashed" : undefined)}>
    {(state) => <span>{Math.round(state.channelValue)}%</span>}
  </ColorPickerSliderThumb>
</ColorPickerSlider>
<ColorPickerSwatch>
  {(state) => (
    <Show when={state.color.alpha < 1}>
      <span>Transparent</span>
    </Show>
  )}
</ColorPickerSwatch>

渲染约定见部件与组合,每个部件的字段见状态。

样式

部件没有样式,除了它们需要的位置:手柄会以内联样式获得 position: absolute 和它的百分比位置。给区域和滑块设置尺寸和它们的背景变量,并用 translate: -50% -50% 把每个手柄居中到它的点上。

每个部件都有一个 data-slot,比如 color-picker-area,它的状态属性列在数据属性下。

ColorPicker

变量内容
--color-picker-colorThe color as CSS, inside the gamut. On a swatch item, its own color. Use it to fill a thumb or a swatch.

ColorPickerArea

变量内容
--color-area-backgroundGradients that draw the area, when its channels are saturation and brightness or lightness. Unset for others, which a canvas paints.

ColorPickerAreaThumb

变量内容
--area-xWhere the thumb is across the area, from 0 to 1.
--area-yWhere the thumb is up the area, from 0 at the bottom to 1 at the top.

ColorPickerSlider

变量内容
--color-slider-backgroundA gradient through the slider's channel, with the other channels as they are.

ColorPickerSliderThumb

变量内容
--color-slider-thumb-positionWhere the thumb is along the slider, as a percentage.

ColorPickerSwatch

变量内容
--color-picker-colorThe color as CSS, inside the gamut. On a swatch item, its own color. Use it to fill a thumb or a swatch.

ColorPickerSwatchItem

变量内容
--color-picker-colorThe color as CSS, inside the gamut. On a swatch item, its own color. Use it to fill a thumb or a swatch.

数据属性

ColorPicker

[data-slot="color-picker"]

属性含义
data-disabledPresent when the picker is disabled, by its own prop or a <fieldset>.
data-readonlyPresent when the picker shows its color but can't change it.
data-requiredPresent when the picker is required.
data-out-of-gamutPresent while a drag or a key holds a color outside the gamut. The value is the closest color inside, and the parts move there once the change commits.

ColorPickerArea

[data-slot="color-picker-area"]

属性含义
data-disabledPresent when the picker is disabled, by its own prop or a <fieldset>.
data-readonlyPresent when the picker shows its color but can't change it.
data-requiredPresent when the picker is required.
data-out-of-gamutPresent while a drag or a key holds a color outside the gamut. The value is the closest color inside, and the parts move there once the change commits.

ColorPickerAreaThumb

[data-slot="color-picker-area-thumb"]

属性含义
data-area-thumbPresent on the area's thumb, which a press on the area moves and focuses.
data-disabledPresent when the picker is disabled, by its own prop or a <fieldset>.
data-readonlyPresent when the picker shows its color but can't change it.
data-requiredPresent when the picker is required.
data-out-of-gamutPresent while a drag or a key holds a color outside the gamut. The value is the closest color inside, and the parts move there once the change commits.

ColorPickerSlider

[data-slot="color-picker-slider"]

属性含义
data-disabledPresent when the picker is disabled, by its own prop or a <fieldset>.
data-readonlyPresent when the picker shows its color but can't change it.
data-requiredPresent when the picker is required.
data-orientationhorizontalverticalThe slider's axis.
data-channelhuesaturationbrightnesslightnesschromaredgreenbluealphaThe channel the part edits.
data-out-of-gamutPresent while a drag or a key holds a color outside the gamut. The value is the closest color inside, and the parts move there once the change commits.

ColorPickerSliderThumb

[data-slot="color-picker-slider-thumb"]

属性含义
data-disabledPresent when the picker is disabled, by its own prop or a <fieldset>.
data-readonlyPresent when the picker shows its color but can't change it.
data-requiredPresent when the picker is required.
data-orientationhorizontalverticalThe slider's axis.
data-channelhuesaturationbrightnesslightnesschromaredgreenbluealphaThe channel the part edits.
data-out-of-gamutPresent while a drag or a key holds a color outside the gamut. The value is the closest color inside, and the parts move there once the change commits.

ColorPickerInput

[data-slot="color-picker-input"]

属性含义
data-disabledPresent when the picker is disabled, by its own prop or a <fieldset>.
data-readonlyPresent when the picker shows its color but can't change it.
data-requiredPresent when the picker is required.
data-out-of-gamutPresent while a drag or a key holds a color outside the gamut. The value is the closest color inside, and the parts move there once the change commits.

ColorPickerChannelInput

[data-slot="color-picker-channel-input"]

属性含义
data-disabledPresent when the picker is disabled, by its own prop or a <fieldset>.
data-readonlyPresent when the picker shows its color but can't change it.
data-requiredPresent when the picker is required.
data-channelhuesaturationbrightnesslightnesschromaredgreenbluealphaThe channel the part edits.
data-out-of-gamutPresent while a drag or a key holds a color outside the gamut. The value is the closest color inside, and the parts move there once the change commits.

ColorPickerSwatch

[data-slot="color-picker-swatch"]

属性含义
data-disabledPresent when the picker is disabled, by its own prop or a <fieldset>.
data-readonlyPresent when the picker shows its color but can't change it.
data-requiredPresent when the picker is required.
data-out-of-gamutPresent while a drag or a key holds a color outside the gamut. The value is the closest color inside, and the parts move there once the change commits.

ColorPickerEyeDropper

[data-slot="color-picker-eye-dropper"]

属性含义
data-disabledPresent when the picker is disabled, by its own prop or a <fieldset>.
data-readonlyPresent when the picker shows its color but can't change it.
data-requiredPresent when the picker is required.
data-out-of-gamutPresent while a drag or a key holds a color outside the gamut. The value is the closest color inside, and the parts move there once the change commits.
data-unsupportedPresent when the browser can't pick a color from the screen.

ColorPickerSwatches

[data-slot="color-picker-swatches"]

属性含义
data-disabledPresent when the picker is disabled, by its own prop or a <fieldset>.
data-readonlyPresent when the picker shows its color but can't change it.
data-requiredPresent when the picker is required.
data-out-of-gamutPresent while a drag or a key holds a color outside the gamut. The value is the closest color inside, and the parts move there once the change commits.

ColorPickerSwatchItem

[data-slot="color-picker-swatch-item"]

属性含义
data-selectedPresent on the swatch item whose color is the value.
data-disabledPresent when the picker is disabled, by its own prop or a <fieldset>.
data-readonlyPresent when the picker shows its color but can't change it.

API 参考

属性和回调与下面相同,都作为 Solid props。

ColorPicker

value?string
The value, as a CSS color, like "#0ea5e9" or "oklch(0.62 0.19 259)". Pass it to control the picker.
defaultValue?string
The value at first, when uncontrolled. A form reset returns to it.
onValueChange?((value: string, details: ColorPickerValueChangeDetails) => void)
Runs while the value changes: on every step of a drag or a key. details.color is the color, and details.cancel() stops it.
onValueCommit?((value: string, details: ColorPickerValueCommitDetails) => void)
Runs once an interaction that changed the value ends: the pointer lifts, a key is pressed, a swatch is picked. For saving.
space?ColorPickerSpace
The space the parts edit in, which decides their channels: "hsv" has hue, saturation and brightness, "hsl" hue, saturation and lightness, "srgb" red, green and blue, "oklch" lightness, chroma and hue.
format?ColorFormat
How the value is written: "hex", or a space in its CSS syntax, like "oklch".
gamut?false | ColorGamut
The colors the value can hold. A drag can go past the edge, and the value is the closest color inside it; once the drag ends, the picker moves there too. "p3" allows wide-gamut screens' colors, and false any color.
disabled?boolean
Disables every part: they can't be focused or changed, and the value isn't submitted.
readOnly?boolean
Keeps the parts focusable and the value submitted, but stops changes.
required?boolean
Marks it required, with data-required. A color picker always has a value, so it never blocks a form.
name?string
The name the value submits under. Without one, the picker submits nothing.
form?string
The id of a form to belong to, when it isn't inside that form.
controller?{ getValue: () => string; setValue: (value: string, options?: ColorPickerChangeOptions) => boolean; focus: () => void; }
Sets the value from anywhere. Create one with createColorPickerController().
debug?boolean
Logs every state change with its reason to the console, in development builds.

ColorPickerArea

x?ColorChannel
The channel across, left to right.
y?ColorChannel
The channel up, bottom to top.

ColorPickerSlider

channel?ColorChannel
The channel the slider edits, like "hue" or "alpha".
orientation?"horizontal" | "vertical"
The slider's axis. Vertical sliders grow upward.

ColorPickerChannelInput

channel?ColorChannel
The channel the input edits, like "hue" or "alpha".

ColorPickerSwatchItem

valuestring
The color it picks, as any CSS color.

状态

渲染函数、基于状态的 class、style 和 children 会收到什么。每个部件都会收到取色器的状态。

valuestring
The value, as a CSS color.
colorColor
The color the parts show, in the picker's space. During a drag it can be outside the gamut.
spaceColorPickerSpace
The space the parts edit in.
disabledboolean
Whether it's disabled, by itself or by a <fieldset>.
readOnlyboolean
Whether it's read-only: the parts stay focusable, but nothing changes the value.
requiredboolean
Whether it's marked required.
outOfGamutboolean
Whether the color the parts show is outside the gamut, so the value is the closest one inside.

滑块和它们的手柄会增加自己的通道:

valuestring
The value, as a CSS color.
colorColor
The color the parts show, in the picker's space. During a drag it can be outside the gamut.
spaceColorPickerSpace
The space the parts edit in.
disabledboolean
Whether it's disabled, by itself or by a <fieldset>.
readOnlyboolean
Whether it's read-only: the parts stay focusable, but nothing changes the value.
requiredboolean
Whether it's marked required.
outOfGamutboolean
Whether the color the parts show is outside the gamut, so the value is the closest one inside.
channelColorChannel
The channel the slider edits.
channelValuenumber
The channel's value, in the units people read it in: degrees, percentages, 0 to 255 for red.
orientation"horizontal" | "vertical"
The slider's axis.

预设项有自己的状态:

selectedboolean
Whether the picker's color looks the same as this swatch's, whatever each is written in.
disabledboolean
Whether pressing it changes nothing, since the picker is disabled or read-only.

原因

details.reason 说明值为什么变化。

track-pressPointerEvent
A press on a slider's track or an area's surface moved the nearest thumb there.
dragPointerEvent
A slider thumb or a resize handle was dragged, or an item was dragged to a new place in a list.
step-keyKeyboardEvent
Arrow, Page Up, Page Down, Home or End stepped a slider or a number input.
input-commitKeyboardEvent | FocusEvent
Enter, or leaving a number input, committed what was typed: a number input parses, clamps and snaps it to the step, and an autocomplete closes its suggestions on it.
item-pressMouseEvent | KeyboardEvent
A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
eye-dropper-pick
resetnone
A form reset.
restorenone
The browser restored state, like after going back, or a saved value was read back from storage.
imperativenone
A controller or api call.

控制器

用 createColorPickerController() 创建一个,并作为 controller 传入。

setValue() 接受任何 CSS 颜色和可选的 { reason, event },像拖动一样运行变更回调,并在颜色无法读取或变更被取消时返回 false。

getValue()() => string
The value, as a CSS color.
setValue(value, options?)(value: string, options?: ColorPickerChangeOptions | undefined) => boolean
Sets the value from any CSS color, as a user would. Returns false for text that isn't one.
focus()() => void
Moves focus to the area's thumb, or the first slider's.

事件

回调先收到新值,然后收到详情。

属性所属收到
onValueChangeColorPicker(value, details):新值、原因和 details.color
onValueCommitColorPicker(value, details):交互结束时的值、它的原因和 details.color

无障碍

没有 WAI-ARIA 模式直接覆盖取色器,所以它由能覆盖它的模式搭成。取色器是一个分组。区域的手柄和每个滑块的手柄遵循 WAI-ARIA 滑块模式,区域手柄的名称包含它的两个通道,比如“Saturation 76%, Brightness 96%”。预设遵循列表框模式,每个预设由它的颜色命名,比如“vivid red”,ColorPickerSwatch 也是如此。

手柄、输入框和预设默认用英语命名。传入 aria-label 来用其他语言命名它们。

键盘

按键作用
Arrow keys把手柄移动一个步进。在区域上,Left 和 Right 横向移动,Up 和 Down 纵向移动。
Shift with an arrow移动十个步进
Page Up or Page Down移动范围的十分之一,沿区域的纵向或沿滑块
Home or End移到起点或终点,沿区域的横向或沿滑块
Enter读取输入框里的文本,或者选择聚焦的预设
Escape把输入框的文本恢复成当前值

每次按键都会提交,就像一次拖动结束。

经过测试的行为

下面每一行都是一个自动化测试。

Value
  • The parts show the default value.
  • A press on the area moves the color there, and commits when it lifts.
  • A drag along a slider follows the pointer and commits once.
  • The text input reads any CSS color on Enter, and text that isn't one goes back.
  • A channel input sets its channel in its own units.
  • A controller sets the value, and a canceled change keeps it.
Keyboard
  • Arrows step a slider, Shift ten steps, and each press commits.
  • Arrows move the area's thumb on both axes.
  • Swatches are one tab stop, arrows move between them, and a press picks one.
Forms
  • The value submits under its name, and a reset returns to the default.
  • A disabled picker can't be focused or changed, and submits nothing.
Gamut
  • In OKLCH, a color past the sRGB edge writes the closest one inside, and the thumb moves there once it lifts.
  • The canvas paints the area, with the colors outside the gamut left clear.

运行于 React、Vue 和 web components。