导航

v2.1.0
表单

颜色选择器

可选择任意颜色:在明度与色度平面上选取,调整色相和不透明度,或直接输入。

本页内容

颜色选择器可以选择任意颜色:在选色区域内用一个滑钮同时选取明度和色度,用两个滑块调整色相和不透明度,颜色本身则以 hex、rgb() 或 oklch() 文本表示。它在 OKLCH 中选色,主题的所有颜色都用这个色彩空间书写,因此无论色相如何,同样幅度的明度变化看起来都一样。选色区域是嵌入表面的一幅画面;滑钮是套在珍珠质感圆环里的当前颜色;轨道是原生范围输入控件。color-picker 行为脚本让各部分保持同步。

颜色选择器

<div class="sheet p-md">  <div class="color-picker" style="--color-picker-lightness: .62; --color-picker-chroma: .19; --color-picker-hue: 260">    <div class="color-picker-area">      <div class="color-picker-thumb" role="slider" tabindex="0" aria-label="Lightness and chroma" aria-valuemin="0" aria-valuemax="100" aria-valuenow="62" aria-valuetext="Lightness 62%, chroma 0.19"></div>    </div>    <span class="swatch swatch-lg color-picker-swatch"></span>    <input type="range" class="slider color-picker-hue" min="0" max="360" value="260" aria-label="Hue">    <input type="range" class="slider color-picker-alpha" min="0" max="100" value="100" aria-label="Opacity">    <div class="color-picker-fields">      <select class="select select-sm color-picker-format" aria-label="Format">        <option value="hex">Hex</option>        <option value="rgb">RGB</option>        <option value="oklch" selected>OKLCH</option>      </select>      <input class="input input-sm color-picker-text" name="accent" value="oklch(62% 0.19 260)" aria-label="Accent color" spellcheck="false" autocomplete="off">    </div>  </div></div><script type="module">  import { attach } from '@master/ui/behaviors'  attach()</script>
import { useEffect, useRef } from 'react'import { attach } from '@master/ui/behaviors'export function Example() {  const root = useRef<HTMLDivElement>(null)  useEffect(() => attach(root.current!), [])  return (    <div ref={root} className="sheet p-md">      <div className="color-picker" style={{ '--color-picker-lightness': '.62', '--color-picker-chroma': '.19', '--color-picker-hue': '260' } as React.CSSProperties}>        <div className="color-picker-area">          <div className="color-picker-thumb" role="slider" tabIndex={0} aria-label="Lightness and chroma" aria-valuemin={0} aria-valuemax={100} aria-valuenow={62} aria-valuetext="Lightness 62%, chroma 0.19"></div>        </div>        <span className="swatch swatch-lg color-picker-swatch"></span>        <input type="range" className="slider color-picker-hue" min="0" max="360" defaultValue="260" aria-label="Hue" />        <input type="range" className="slider color-picker-alpha" min="0" max="100" defaultValue="100" aria-label="Opacity" />        <div className="color-picker-fields">          <select className="select select-sm color-picker-format" aria-label="Format" defaultValue="oklch">            <option value="hex">Hex</option>            <option value="rgb">RGB</option>            <option value="oklch">OKLCH</option>          </select>          <input className="input input-sm color-picker-text" name="accent" defaultValue="oklch(62% 0.19 260)" aria-label="Accent color" spellCheck="false" autoComplete="off" />        </div>      </div>    </div>  )}
<script>  import { attach } from '@master/ui/behaviors'</script><div class="sheet p-md" {@attach attach}>  <div class="color-picker" style="--color-picker-lightness: .62; --color-picker-chroma: .19; --color-picker-hue: 260">    <div class="color-picker-area">      <div class="color-picker-thumb" role="slider" tabindex="0" aria-label="Lightness and chroma" aria-valuemin="0" aria-valuemax="100" aria-valuenow="62" aria-valuetext="Lightness 62%, chroma 0.19"></div>    </div>    <span class="swatch swatch-lg color-picker-swatch"></span>    <input type="range" class="slider color-picker-hue" min="0" max="360" value="260" aria-label="Hue">    <input type="range" class="slider color-picker-alpha" min="0" max="100" value="100" aria-label="Opacity">    <div class="color-picker-fields">      <select class="select select-sm color-picker-format" aria-label="Format">        <option value="hex">Hex</option>        <option value="rgb">RGB</option>        <option value="oklch" selected>OKLCH</option>      </select>      <input class="input input-sm color-picker-text" name="accent" value="oklch(62% 0.19 260)" aria-label="Accent color" spellcheck="false" autocomplete="off">    </div>  </div></div>
<script setup>import { onMounted, onUnmounted, ref } from 'vue'import { attach } from '@master/ui/behaviors'const root = ref(null)let detachonMounted(() => { detach = attach(root.value) })onUnmounted(() => detach?.())</script><template>  <div ref="root" class="sheet p-md">    <div class="color-picker" style="--color-picker-lightness: .62; --color-picker-chroma: .19; --color-picker-hue: 260">      <div class="color-picker-area">        <div class="color-picker-thumb" role="slider" tabindex="0" aria-label="Lightness and chroma" aria-valuemin="0" aria-valuemax="100" aria-valuenow="62" aria-valuetext="Lightness 62%, chroma 0.19"></div>      </div>      <span class="swatch swatch-lg color-picker-swatch"></span>      <input type="range" class="slider color-picker-hue" min="0" max="360" value="260" aria-label="Hue">      <input type="range" class="slider color-picker-alpha" min="0" max="100" value="100" aria-label="Opacity">      <div class="color-picker-fields">        <select class="select select-sm color-picker-format" aria-label="Format">          <option value="hex">Hex</option>          <option value="rgb">RGB</option>          <option value="oklch" selected>OKLCH</option>        </select>        <input class="input input-sm color-picker-text" name="accent" value="oklch(62% 0.19 260)" aria-label="Accent color" spellcheck="false" autocomplete="off">      </div>    </div>  </div></template>
在选色区域内拖动,或在其滑钮上使用方向键;调整色相,切换格式,或输入 #e5484d 这样的颜色。

#从按钮打开

颜色通常只是多项设置中的一项,此时选择器从一个显示该颜色的按钮打开。把按钮和带有 color-picker-popover 的弹出层放在根元素内:弹出层成为纵向排列的容器,按钮中带有 color-picker-swatch 的色样在选择器关闭时显示当前颜色,因为两者都位于保存颜色的根元素之内。弹出层的打开、定位和关闭由浏览器负责;行为脚本的行为不变。

从按钮打开

<div class="color-picker" style="--color-picker-lightness: .6256; --color-picker-chroma: .1933; --color-picker-hue: 23.03">  <button type="button" class="btn" popovertarget="brand-picker">    <span class="swatch swatch-sm color-picker-swatch"></span> Brand color  </button>  <div id="brand-picker" popover class="popover color-picker-popover">    <div class="color-picker-area">      <div class="color-picker-thumb" role="slider" tabindex="0" aria-label="Lightness and chroma" aria-valuemin="0" aria-valuemax="100" aria-valuenow="62.6" aria-valuetext="Lightness 62.6%, chroma 0.193"></div>    </div>    <span class="swatch swatch-lg color-picker-swatch"></span>    <input type="range" class="slider color-picker-hue" min="0" max="360" value="23" aria-label="Hue">    <input type="range" class="slider color-picker-alpha" min="0" max="100" value="100" aria-label="Opacity">    <div class="color-picker-fields">      <select class="select select-sm color-picker-format" aria-label="Format">        <option value="hex" selected>Hex</option>        <option value="rgb">RGB</option>        <option value="oklch">OKLCH</option>      </select>      <input class="input input-sm color-picker-text" name="brand" value="#e5484d" aria-label="Brand color" spellcheck="false" autocomplete="off">    </div>  </div></div><script type="module">  import { attach } from '@master/ui/behaviors'  attach()</script>
import { useEffect, useRef } from 'react'import { attach } from '@master/ui/behaviors'export function Example() {  const root = useRef<HTMLDivElement>(null)  useEffect(() => attach(root.current!), [])  return (    <div ref={root} className="color-picker" style={{ '--color-picker-lightness': '.6256', '--color-picker-chroma': '.1933', '--color-picker-hue': '23.03' } as React.CSSProperties}>      <button type="button" className="btn" popoverTarget="brand-picker">        <span className="swatch swatch-sm color-picker-swatch"></span> Brand color      </button>      <div id="brand-picker" popover="" className="popover color-picker-popover">        <div className="color-picker-area">          <div className="color-picker-thumb" role="slider" tabIndex={0} aria-label="Lightness and chroma" aria-valuemin={0} aria-valuemax={100} aria-valuenow={62.6} aria-valuetext="Lightness 62.6%, chroma 0.193"></div>        </div>        <span className="swatch swatch-lg color-picker-swatch"></span>        <input type="range" className="slider color-picker-hue" min="0" max="360" defaultValue="23" aria-label="Hue" />        <input type="range" className="slider color-picker-alpha" min="0" max="100" defaultValue="100" aria-label="Opacity" />        <div className="color-picker-fields">          <select className="select select-sm color-picker-format" aria-label="Format" defaultValue="hex">            <option value="hex">Hex</option>            <option value="rgb">RGB</option>            <option value="oklch">OKLCH</option>          </select>          <input className="input input-sm color-picker-text" name="brand" defaultValue="#e5484d" aria-label="Brand color" spellCheck="false" autoComplete="off" />        </div>      </div>    </div>  )}
<script>  import { attach } from '@master/ui/behaviors'</script><div class="color-picker" style="--color-picker-lightness: .6256; --color-picker-chroma: .1933; --color-picker-hue: 23.03" {@attach attach}>  <button type="button" class="btn" popovertarget="brand-picker">    <span class="swatch swatch-sm color-picker-swatch"></span> Brand color  </button>  <div id="brand-picker" popover class="popover color-picker-popover">    <div class="color-picker-area">      <div class="color-picker-thumb" role="slider" tabindex="0" aria-label="Lightness and chroma" aria-valuemin="0" aria-valuemax="100" aria-valuenow="62.6" aria-valuetext="Lightness 62.6%, chroma 0.193"></div>    </div>    <span class="swatch swatch-lg color-picker-swatch"></span>    <input type="range" class="slider color-picker-hue" min="0" max="360" value="23" aria-label="Hue">    <input type="range" class="slider color-picker-alpha" min="0" max="100" value="100" aria-label="Opacity">    <div class="color-picker-fields">      <select class="select select-sm color-picker-format" aria-label="Format">        <option value="hex" selected>Hex</option>        <option value="rgb">RGB</option>        <option value="oklch">OKLCH</option>      </select>      <input class="input input-sm color-picker-text" name="brand" value="#e5484d" aria-label="Brand color" spellcheck="false" autocomplete="off">    </div>  </div></div>
<script setup>import { onMounted, onUnmounted, ref } from 'vue'import { attach } from '@master/ui/behaviors'const root = ref(null)let detachonMounted(() => { detach = attach(root.value) })onUnmounted(() => detach?.())</script><template>  <div ref="root" class="color-picker" style="--color-picker-lightness: .6256; --color-picker-chroma: .1933; --color-picker-hue: 23.03">    <button type="button" class="btn" popovertarget="brand-picker">      <span class="swatch swatch-sm color-picker-swatch"></span> Brand color    </button>    <div id="brand-picker" popover class="popover color-picker-popover">      <div class="color-picker-area">        <div class="color-picker-thumb" role="slider" tabindex="0" aria-label="Lightness and chroma" aria-valuemin="0" aria-valuemax="100" aria-valuenow="62.6" aria-valuetext="Lightness 62.6%, chroma 0.193"></div>      </div>      <span class="swatch swatch-lg color-picker-swatch"></span>      <input type="range" class="slider color-picker-hue" min="0" max="360" value="23" aria-label="Hue">      <input type="range" class="slider color-picker-alpha" min="0" max="100" value="100" aria-label="Opacity">      <div class="color-picker-fields">        <select class="select select-sm color-picker-format" aria-label="Format">          <option value="hex" selected>Hex</option>          <option value="rgb">RGB</option>          <option value="oklch">OKLCH</option>        </select>        <input class="input input-sm color-picker-text" name="brand" value="#e5484d" aria-label="Brand color" spellcheck="false" autocomplete="off">      </div>    </div>  </div></template>
打开选择器并调整颜色:按钮中的色样会随之变化。

颜色必须不透明时(例如需要印刷的品牌色),省去 color-picker-alpha:此时色样只与色相滑块并排,输入的带不透明度的颜色会被去掉不透明度后采用。如果连色样也省去,轨道会占满整个宽度。

#为什么用 OKLCH

选色区域也可以用 HSV 中的 S 和 V 作为两轴,也就是大多数选择器绘制的那种方块。它很容易绘制,因为只是 sRGB 与白色和黑色的混合。但在这种平面上很难挑选调色板:同一个 V 值,可能是深蓝色,也可能是刺眼的黄色;在相同饱和度下改变色相,颜色看起来的明暗也会改变。OKLCH 的设计让相同的步长看起来相同,所以主题用它书写颜色,为主题服务的选择器也应该在其中选色。

  • 明度从平面顶端的 100% 到底端的 0,并且在任何色相下都是相同的明度。
  • 色度从平面起始端的无色度(灰色)到末端的 .37,达到 Display P3 的范围上限。颜色并不总能像其色度要求的那样鲜艳:屏幕会显示它能显示的最接近的颜色,选色区域和滑钮也按同一规则显示。
  • 色相在自己的滑块上绕色环一周,以同一明度和色度绘制,以便区分每个色相。

值按下拉选择框所示的格式写出。oklch() 按保存的值原样写出。Hex 和 rgb() 只能表示 sRGB,因此超出 sRGB 的颜色会按 CSS Color 4 将颜色适配到屏幕的方式处理:在保持明度和色相不变的前提下降低色度,直到颜色与某个 sRGB 可表示的颜色之间的差异在最小可觉差之内。切换格式绝不会改变保存的颜色,因此一个颜色从 hex 转为 oklch() 再转回来,仍是同一个 hex 值。

渐变只能沿一个轴变化,所以选色区域按行绘制:每一行都是在该行明度下从灰色到 .37 的渐变,沿这条线是精确的;位于两行中间的各行叠在其他行之上,并带有从一行渐隐到下一行的遮罩。这些颜色是主题的 mixin,即以行为脚本发布的色相为参数的函数,因此组件本身不写入任何颜色。

#行为脚本

colorPicker 接收根元素,即带有 color-picker 类的元素,并返回用于解除绑定的函数。

app.js
import { colorPicker } from '@master/ui/behaviors/color-picker.js'const accent = colorPicker(document.querySelector('.color-picker'))accent.value // 'oklch(62% 0.19 260)'accent.value = '#e5484d' // choose a color, and hex as its format
  • 颜色取自文本框的值,可以是三种格式中的任意一种,格式也随之确定。行为脚本把颜色以四个数值写在根元素上:--color-picker-lightness、--color-picker-chroma、--color-picker-hue 和 --color-picker-alpha,它们决定滑钮的位置,并用于绘制选色区域、轨道和色样。请同时把初始颜色的数值写在根元素的 style 中,这样在脚本运行前选色区域就能正确显示。
  • 选色区域。 按下时,滑钮移到指针下方并获得焦点;拖动时滑钮跟随指针,即使指针越过平面边缘也是如此,此时颜色停在边缘。按键见下表。
  • 文本一旦输入的内容构成有效颜色就会立即采用,文本保持输入时的样子。按 Enter 或离开文本框提交时,颜色会按所选格式重新写出;不是有效颜色的文本会被还原。
  • 事件。 颜色移动时滑钮派发 input,拖动结束或通过按键移动后派发 change;滑块、下拉选择框和文本框各自派发自己的事件。在根元素上监听事件时,可以从派发事件的控件读取新的 value。
  • 滑钮的描述文字。 其 aria-valuetext 为 Lightness 62%, chroma 0.19;传入 valueText: (lightness, chroma) => … 可用页面的语言表述。

未绑定行为脚本时,选色区域显示标记中写入的颜色,滑块、下拉选择框和文本框都是互不联动的普通控件。

#键盘操作

按键操作
ArrowUp, ArrowDown焦点在选色区的滑钮上时,将明度增减 1 个百分点,使颜色变亮或变暗
ArrowRight, ArrowLeft焦点在选色区的滑钮上时,朝水平方向的末端移动会将色度增加 .005,朝起始端移动会减少 .005(从右到左书写时方向对调)
Shift with an arrow焦点在选色区的滑钮上时,以十倍步长调整明度或色度,分别为 10 个百分点和 .05
PageUp, PageDown焦点在选色区的滑钮上时,将明度增减 10 个百分点,使颜色变亮或变暗
Home, End焦点在选色区的滑钮上时,将色度设为零(灰色)或选色区的最大值
ArrowLeft, ArrowRight, ArrowUp, ArrowDown, Home, End, PageUp, PageDown在色相和不透明度滑块上,行为与原生 range input 一致
Enter在文本框中,接受输入的内容;文本框会改用所选格式重新写出颜色,若输入的不是颜色则恢复原值

#无障碍

  • 选色区域内的滑钮本身就是一个滑块控件。它的值是明度,因为 ArrowUp 和 ArrowDown 调整的是明度;它的 aria-valuetext 同时说明明度和色度,因此无论哪个值变化,屏幕阅读器都会播报两者。请按它所选择的内容命名,例如“明度和色度”。
  • 可以直接在文本框中输入精确的颜色值,颜色的名称应放在文本框上,例如“品牌色”。表单以文本框的 name 为字段名提交颜色值。
  • 为色相和不透明度滑块以及格式下拉选择框命名;它们的按键操作由平台提供。
  • 强制颜色模式下保留选色区域的颜色,因为那正是读者要选择的内容;平面的边缘和滑钮的焦点使用系统颜色绘制。

#React、Svelte 和 Vue

color-picker 组件在首次渲染时就绘制初始值(包括根元素上的四个数值),并绑定行为脚本,之后各部分都由行为脚本更新。它的值是以所选格式表示的颜色文本,每次变化时都会传出;传入 trigger(在 Svelte 中是 snippet,在 Vue 中是 slot)即可从页面自己的按钮打开选择器。使用 npx master-ui add color-picker 将组件复制到项目中。有关这些组件的实现和用法,请参阅 React、Svelte 和 Vue。

ui/color-picker.tsx
'use client'import { Fragment, useId, useState, type ComponentProps, type CSSProperties, type ElementType, type ReactNode } from 'react'import { colorPicker, colorPickerState } from '@master/ui/behaviors/color-picker.js'import { useBehavior } from './use-behavior'export interface ColorPickerLabels {  /** The field's thumb. `Lightness and chroma` by default. */  field?: string  /** `Hue` by default. */  hue?: string  /** `Opacity` by default. */  alpha?: string  /** The select of the format. `Format` by default. */  format?: string}export interface ColorPickerProps extends Omit<ComponentProps<'div'>, 'defaultValue' | 'children' | 'ref'> {  /** The color, in hex, rgb() or oklch(); the format it is written in is the one the picker writes. */  value?: string  defaultValue?: string  onValueChange?: (value: string) => void  /** What the color is: the name of the text field. */  label: string  /** The name the text field submits with a form. */  name?: string  /** An opacity slider. Without it the color is opaque. True by default. */  alpha?: boolean  disabled?: boolean  /**   * The button that opens the picker in a popover: spread what it is given on a button of your own, and put a   * `swatch color-picker-swatch` in it to show the color. Leave it out and the picker stands inline.   */  trigger?: (attributes: { popoverTarget: string }) => ReactNode  /** What the controls are called, in the page's words. */  labels?: ColorPickerLabels  /** What the field's thumb says it holds, from the lightness in percent and the chroma. */  valueText?: (lightness: number, chroma: number) => string}/** * A color picker. The behavior holds the color and moves every part; this component draws the first value * into the first render and passes the value in and out. */export function ColorPicker({ value, defaultValue, onValueChange, label, name, alpha = true, disabled, trigger, labels = {}, valueText, className, style, ...root }: ColorPickerProps) {  const id = useId()  // The first value is drawn into the first render; after that the behavior writes every part.  const [first] = useState(() => colorPickerState(value ?? defaultValue ?? '', { valueText, opaque: !alpha }) ?? colorPickerState('#000000')!)  const ref = useBehavior(colorPicker, { valueText }, { value, defaultValue, onValueChange })  // Opened from a button, the parts stand in a popover beside it; inline, they stand in the root.  const Column = (trigger ? 'div' : Fragment) as ElementType  const column = trigger ? { id: `${id}popover`, popover: 'auto', className: 'popover color-picker-popover' } : {}  return (    <div className={className ? `color-picker ${className}` : 'color-picker'} ref={ref} style={{ ...first.properties, ...style } as CSSProperties} {...root}>      {trigger?.({ popoverTarget: `${id}popover` })}      <Column {...column}>        <div className="color-picker-area">          <div className="color-picker-thumb" role="slider" tabIndex={disabled ? -1 : 0} aria-label={labels.field ?? 'Lightness and chroma'} aria-valuemin={0} aria-valuemax={100} aria-valuenow={first.valueNow} aria-valuetext={first.valueText} aria-disabled={disabled || undefined} />        </div>        <span className="swatch swatch-lg color-picker-swatch" />        <input type="range" className="slider color-picker-hue" min={0} max={360} defaultValue={first.hue} aria-label={labels.hue ?? 'Hue'} disabled={disabled} />        {alpha && <input type="range" className="slider color-picker-alpha" min={0} max={100} defaultValue={first.alpha * 100} aria-label={labels.alpha ?? 'Opacity'} disabled={disabled} />}        <div className="color-picker-fields">          <select className="select select-sm color-picker-format" defaultValue={first.format} aria-label={labels.format ?? 'Format'} disabled={disabled}>            <option value="hex">Hex</option>            <option value="rgb">RGB</option>            <option value="oklch">OKLCH</option>          </select>          <input className="input input-sm color-picker-text" name={name} defaultValue={first.value} aria-label={label} spellCheck={false} autoComplete="off" disabled={disabled} />        </div>      </Column>    </div>  )}
ui/ColorPicker.svelte
<script lang="ts" module>  import type { Snippet } from 'svelte'  import type { HTMLAttributes } from 'svelte/elements'  export interface ColorPickerLabels {    /** The field's thumb. `Lightness and chroma` by default. */    field?: string    /** `Hue` by default. */    hue?: string    /** `Opacity` by default. */    alpha?: string    /** The select of the format. `Format` by default. */    format?: string  }  export interface ColorPickerProps extends Omit<HTMLAttributes<HTMLDivElement>, 'children'> {    /** The color, in hex, rgb() or oklch(); the format it is written in is the one the picker writes. Bind it, or leave it out. */    value?: string    onValueChange?: (value: string) => void    /** What the color is: the name of the text field. */    label: string    /** The name the text field submits with a form. */    name?: string    /** An opacity slider. Without it the color is opaque. True by default. */    alpha?: boolean    disabled?: boolean    /**     * The button that opens the picker in a popover: spread what it is given on a button of your own, and put     * a `swatch color-picker-swatch` in it to show the color. Leave it out and the picker stands inline.     */    trigger?: Snippet<[{ popovertarget: string }]>    /** What the controls are called, in the page's words. */    labels?: ColorPickerLabels    /** What the field's thumb says it holds, from the lightness in percent and the chroma. */    valueText?: (lightness: number, chroma: number) => string  }</script><script lang="ts">  import { untrack } from 'svelte'  import { colorPicker, colorPickerState } from '@master/ui/behaviors/color-picker.js'  import { behavior } from './behavior.svelte.js'  let { value = $bindable(), onValueChange, label, name, alpha = true, disabled, trigger, labels = {}, valueText, class: className, ...root }: ColorPickerProps = $props()  const id = $props.id()  // The first value is drawn into the first render; after that the behavior writes every part.  const first = untrack(() => colorPickerState(value ?? '', { valueText, opaque: !alpha }) ?? colorPickerState('#000000')!)  // Svelte writes a style again whenever its owner changes it, so it writes the numbers the behavior holds.  let element = $state<HTMLDivElement>()  let held = $state(first.properties)  const read = () => {    if (element) held = Object.fromEntries(Object.entries(held).map(([property, number]) => [property, element!.style.getPropertyValue(property) || number]))  }  const attach = behavior(colorPicker, () => ({ valueText }), {    value: () => value,    change: (next) => { value = next; onValueChange?.(next) },    settled: read,    on: { input: read },  })</script>{#snippet panel()}  <div class="color-picker-area">    <div class="color-picker-thumb" role="slider" tabindex={disabled ? -1 : 0} aria-label={labels.field ?? 'Lightness and chroma'} aria-valuemin={0} aria-valuemax={100} aria-valuenow={first.valueNow} aria-valuetext={first.valueText} aria-disabled={disabled || undefined}></div>  </div>  <span class="swatch swatch-lg color-picker-swatch"></span>  <input type="range" class="slider color-picker-hue" min="0" max="360" value={first.hue} aria-label={labels.hue ?? 'Hue'} {disabled} />  {#if alpha}    <input type="range" class="slider color-picker-alpha" min="0" max="100" value={first.alpha * 100} aria-label={labels.alpha ?? 'Opacity'} {disabled} />  {/if}  <div class="color-picker-fields">    <select class="select select-sm color-picker-format" aria-label={labels.format ?? 'Format'} {disabled}>      <option value="hex" selected={first.format === 'hex'}>Hex</option>      <option value="rgb" selected={first.format === 'rgb'}>RGB</option>      <option value="oklch" selected={first.format === 'oklch'}>OKLCH</option>    </select>    <input class="input input-sm color-picker-text" {name} value={first.value} aria-label={label} spellcheck="false" autocomplete="off" {disabled} />  </div>{/snippet}<!--  @component  A color picker. The behavior holds the color and moves every part; this component draws the first value  into the first render and passes the value in and out.--><div  class={['color-picker', className]}  style:--color-picker-lightness={held['--color-picker-lightness']}  style:--color-picker-chroma={held['--color-picker-chroma']}  style:--color-picker-hue={held['--color-picker-hue']}  style:--color-picker-alpha={held['--color-picker-alpha']}  bind:this={element}  {@attach attach}  {...root}>  {#if trigger}    {@render trigger({ popovertarget: `${id}-popover` })}    <div id="{id}-popover" popover="auto" class="popover color-picker-popover">{@render panel()}</div>  {:else}    {@render panel()}  {/if}</div>
ui/ColorPicker.vue
<script setup lang="ts">import { useId, useTemplateRef } from 'vue'import { colorPicker, colorPickerState } from '@master/ui/behaviors/color-picker.js'import { useBehavior } from './use-behavior'defineOptions({ inheritAttrs: false })const { alpha = true, labels = {}, valueText } = defineProps<{  /** What the color is: the name of the text field. */  label: string  /** The name the text field submits with a form. */  name?: string  /** An opacity slider. Without it the color is opaque. True by default. */  alpha?: boolean  disabled?: boolean  /** What the controls are called, in the page's words: `field` (the thumb), `hue`, `alpha` and `format`. */  labels?: { field?: string, hue?: string, alpha?: string, format?: string }  /** What the field's thumb says it holds, from the lightness in percent and the chroma. */  valueText?: (lightness: number, chroma: number) => string}>()/** The color, in hex, rgb() or oklch(): `v-model`. The format it is written in is the one the picker writes. */const model = defineModel<string>()const slots = defineSlots<{  /**   * The button that opens the picker in a popover: bind what it is given on a button of your own, and put a   * `swatch color-picker-swatch` in it to show the color. Leave it out and the picker stands inline.   */  trigger?: (attributes: { popovertarget: string }) => unknown}>()/* * A color picker. The behavior holds the color and moves every part; this component draws the first value * into the first render and passes the value in and out. */const id = useId()// The first value is drawn into the first render; after that the behavior writes every part.const first = colorPickerState(model.value ?? '', { valueText, opaque: !alpha }) ?? colorPickerState('#000000')!const root = useTemplateRef<HTMLDivElement>('root')// Vue writes a style again each time it renders, so it writes the numbers the behavior holds, not the first ones.const properties = () => Object.fromEntries(Object.entries(first.properties).map(([property, number]) => [property, root.value?.style.getPropertyValue(property) || number]))useBehavior(root, colorPicker, () => ({ valueText }), model)</script><template>  <div class="color-picker" ref="root" v-bind="$attrs" :style="properties()">    <template v-if="slots.trigger">      <slot name="trigger" v-bind="{ popovertarget: `${id}-popover` }" />      <div :id="`${id}-popover`" popover="auto" class="popover color-picker-popover">        <div class="color-picker-area">          <div class="color-picker-thumb" role="slider" :tabindex="disabled ? -1 : 0" :aria-label="labels.field ?? 'Lightness and chroma'" aria-valuemin="0" aria-valuemax="100" :aria-valuenow="first.valueNow" :aria-valuetext="first.valueText" :aria-disabled="disabled || undefined" />        </div>        <span class="swatch swatch-lg color-picker-swatch" />        <input type="range" class="slider color-picker-hue" min="0" max="360" :value.attr="first.hue" :aria-label="labels.hue ?? 'Hue'" :disabled="disabled">        <input v-if="alpha" type="range" class="slider color-picker-alpha" min="0" max="100" :value.attr="first.alpha * 100" :aria-label="labels.alpha ?? 'Opacity'" :disabled="disabled">        <div class="color-picker-fields">          <select class="select select-sm color-picker-format" :aria-label="labels.format ?? 'Format'" :disabled="disabled">            <option value="hex" :selected="first.format === 'hex'">Hex</option>            <option value="rgb" :selected="first.format === 'rgb'">RGB</option>            <option value="oklch" :selected="first.format === 'oklch'">OKLCH</option>          </select>          <input class="input input-sm color-picker-text" :name="name" :value.attr="first.value" :aria-label="label" spellcheck="false" autocomplete="off" :disabled="disabled">        </div>      </div>    </template>    <!-- Inline, the same parts stand in the root's column. -->    <template v-else>      <div class="color-picker-area">        <div class="color-picker-thumb" role="slider" :tabindex="disabled ? -1 : 0" :aria-label="labels.field ?? 'Lightness and chroma'" aria-valuemin="0" aria-valuemax="100" :aria-valuenow="first.valueNow" :aria-valuetext="first.valueText" :aria-disabled="disabled || undefined" />      </div>      <span class="swatch swatch-lg color-picker-swatch" />      <input type="range" class="slider color-picker-hue" min="0" max="360" :value.attr="first.hue" :aria-label="labels.hue ?? 'Hue'" :disabled="disabled">      <input v-if="alpha" type="range" class="slider color-picker-alpha" min="0" max="100" :value.attr="first.alpha * 100" :aria-label="labels.alpha ?? 'Opacity'" :disabled="disabled">      <div class="color-picker-fields">        <select class="select select-sm color-picker-format" :aria-label="labels.format ?? 'Format'" :disabled="disabled">          <option value="hex" :selected="first.format === 'hex'">Hex</option>          <option value="rgb" :selected="first.format === 'rgb'">RGB</option>          <option value="oklch" :selected="first.format === 'oklch'">OKLCH</option>        </select>        <input class="input input-sm color-picker-text" :name="name" :value.attr="first.value" :aria-label="label" spellcheck="false" autocomplete="off" :disabled="disabled">      </div>    </template>  </div></template>

#类名

类名说明
color-picker选择器本体为 16rem 宽的单列布局,依次放置选色区、滑轨和文本。包含 color-picker-popover 时,本体只容纳按钮和 popover,整列内容放在 popover 内
color-picker-area选色区使用当前色相。明度从顶部的 100% 降到底部的 0,色度沿水平方向从 0 增至 .37。选色区包含滑钮并接收指针操作
color-picker-thumb选色区中唯一的滑钮,位置由根元素上的数值决定。它是一个 slider,值为明度,aria-valuetext 同时说明明度和色度
color-picker-hue用于 0 到 360 的 slider:色相,轨道绘有色相环的全部色相
color-picker-alpha用于 0 到 100 的 slider,调节不透明度,轨道上的颜色在棋盘格上逐渐显现。只需选择不透明颜色时,可省略此滑块
color-picker-swatch用于色样:在棋盘格上显示当前颜色。在栏中位于两条滑轨的起始侧;在打开 popover 的按钮中,选择器关闭时也能显示颜色
color-picker-fields格式选择与文本框所在的一行
color-picker-format用于小号 select:文本的书写格式,选项为 hex、rgb 和 oklch
color-picker-text用于小号文本框:以所选格式写出的颜色。可接受三种格式中任意一种的输入,并带有表单提交时使用的 name
color-picker-popover用于根元素内的 popover:即由旁边按钮打开的栏,按钮中的色样显示当前颜色

#自定义属性

属性默认值说明
--color-picker-width16rem栏的宽度
--color-picker-lightness0颜色的明度,范围为 0 到 1。行为脚本将其写在根元素上;初始值写在标记的 style 中
--color-picker-chroma0颜色的色度从 0 起,选色区内最高可调至 .37
--color-picker-hue0颜色的色相,数值按角度计算,省略单位符号
--color-picker-alpha1颜色的不透明度,范围为 0 到 1
--color-picker-color由四个数值组成的当前颜色:根元素内其他需要显示该颜色的元素可读取它

#源码

@master/ui/components/color-picker.css
/* * Color picker: a color chosen in OKLCH, the space the theme's own colors are written in. A field of the hue held, * lightness from top to bottom and chroma from start to end, under one thumb; the hue and the opacity on two * sliders; a swatch of the color; and the color as text in hex, rgb() or oklch(), beside the select that picks * which. Its behavior publishes the color as four numbers on the root (--color-picker-lightness, -chroma, -hue * and -alpha); the stylesheet places the thumb from them and the theme's mixins turn them into colors. * * Material: the field is a picture set into the surface, with a control's corner and a half-pixel ring of the * line on color inside its edge, so a white field reads on a white sheet. The thumb is the color itself in a * ring of pearl, as large as a slider's thumb, with the same fading shadow. The two tracks are sliders twice as * thick, one painted with the hues, the other with the color fading in over a checker. Inline, the root is a * column 16rem wide; opened from a button, the root holds the button and a popover, and the popover is the column. * * Without the script the field shows the color the markup was written with, and the sliders and the text field * are plain controls that do not follow one another. */@layer components.ui {  .color-picker {    --color-picker-width: 16rem;    --color-picker-lightness: 0;    --color-picker-chroma: 0;    --color-picker-hue: 0;    --color-picker-alpha: 1;    /* Which way chroma and hue run: toward the end of the line. */    --color-picker-run: 90deg;    /* The ground under a color that is not opaque. */    /* The checker's tone is the gradient's, so a picker inside a gradient shows one checkerboard, not two. */    --color-picker-checker: repeating-conic-gradient(color-mix(in oklab, var(--color-text-strong) 9%, transparent) 0 25%, transparent 0 50%) 0 0 / .5rem .5rem;    @apply --color-picker-color;    display: grid;    grid-template-columns: minmax(0, 1fr);    gap: .75rem;    inline-size: var(--color-picker-width);    max-inline-size: 100%;    &:dir(rtl) {      --color-picker-run: 270deg;    }    /* A swatch in the column stands at the start of the two sliders. */    &:has(.color-picker-swatch) {      grid-template-columns: auto minmax(0, 1fr);    }    /* Opened from a button: the root only holds the button, and the popover is the column. */    &:has(.color-picker-popover) {      display: inline-block;      inline-size: auto;      max-inline-size: none;    }  }  .color-picker-popover {    --popover-padding: .75rem;    grid-template-columns: minmax(0, 1fr);    gap: .75rem;    box-sizing: content-box;    width: var(--color-picker-width);    /* The holder's corner is the field's corner plus the padding between them, so the two curves are concentric. */    border-radius: calc(var(--radius-control) * var(--corner-scale) + var(--popover-padding));    /* The thumb and its focus ring stand half outside the field at its edges. */    overflow: visible;    &:popover-open {      display: grid;    }    &:has(.color-picker-swatch) {      grid-template-columns: auto minmax(0, 1fr);    }  }  /*   * The field. Its rows are the theme's: nine on the element, and the eight between them on a layer above,   * whose mask is whole on each of its rows and gone on the rows around it, so one row fades into the next.   */  .color-picker-area {    position: relative;    /* The thumb stands over the field's edge within the field, never over the page around it. */    isolation: isolate;    grid-column: 1 / -1;    aspect-ratio: 3 / 2;    border-radius: calc(var(--radius-control) * var(--corner-scale));    corner-shape: var(--corner-shape);    @apply --color-picker-field;    cursor: crosshair;    touch-action: none;    -webkit-user-select: none;    user-select: none;    -webkit-tap-highlight-color: transparent;    /* The colors are what the reader came for: forced colors keep them. */    forced-color-adjust: none;    &::before {      content: '';      position: absolute;      inset: 0;      border-radius: inherit;      corner-shape: inherit;      @apply --color-picker-field-between;      mask: repeating-linear-gradient(transparent, black 6.25%, transparent 12.5%);      pointer-events: none;    }    /* The edge, over both layers of rows. */    &::after {      content: '';      position: absolute;      inset: 0;      border-radius: inherit;      corner-shape: inherit;      box-shadow: inset 0 0 0 .5px var(--color-line-on-color);      pointer-events: none;    }    &:has(.color-picker-thumb[aria-disabled="true"]) {      opacity: .5;      cursor: not-allowed;    }    @media (forced-colors: active) {      outline: 1px solid CanvasText;      &:has(.color-picker-thumb[aria-disabled="true"]) {        outline-color: GrayText;      }    }  }  /*   * The thumb: placed by its middle, from the numbers on the root. Chroma past the end of the field (a color   * typed with more than .37) stands at the end.   */  .color-picker-thumb {    --color-picker-thumb: 1.125rem;    position: absolute;    z-index: 1;    inset-inline-start: calc(clamp(0, var(--color-picker-chroma) / .37, 1) * 100%);    top: calc((1 - clamp(0, var(--color-picker-lightness), 1)) * 100%);    box-sizing: border-box;    width: var(--color-picker-thumb);    height: var(--color-picker-thumb);    margin-block-start: calc(var(--color-picker-thumb) / -2);    margin-inline-start: calc(var(--color-picker-thumb) / -2);    border-radius: 999px;    corner-shape: round;    background: var(--color-picker-solid);    box-shadow:      inset 0 0 0 3px var(--color-thumb-high), inset 0 0 0 3.5px var(--color-line-on-color),      0 0 0 .5px var(--color-line-strong), 0 1px 2px -.5px var(--color-shade-1), 0 2px 4px -1px var(--color-shade-2), 0 4px 8px -4px var(--color-shade-3);    transition: scale var(--duration-quick) var(--easing-glide);    &:focus-visible {      @apply --focus-ring;    }    /* On touch the target reaches 44px around the thumb, which keeps its size. */    @media (pointer: coarse) {      &::after {        @apply --touch-target;      }    }    @media (forced-colors: active) {      &:focus-visible {        outline-color: Highlight;      }    }  }  /* Held, the thumb grows a little under the finger, as a slider's does. */  .color-picker-area:active .color-picker-thumb:not([aria-disabled="true"]) {    scale: 1.08;    @media (prefers-reduced-motion: reduce) {      scale: none;    }  }  /* The two tracks: sliders twice as thick, painted with what they choose, with no fill over it. */  .color-picker-hue,  .color-picker-alpha {    --slider-track: .75rem;    --slider-color: transparent;    grid-column: -2;    @media (forced-colors: active) {      &::-webkit-slider-runnable-track {        background: var(--slider-background);        box-shadow: inset 0 0 0 1px CanvasText;      }      &::-moz-range-track {        background: var(--slider-background);      }      /* A disabled slider fills with the system's disabled ink; these tracks have no fill to draw. */      &:disabled {        --slider-color: transparent;      }    }  }  .color-picker-hue {    @apply --color-picker-hues;  }  .color-picker-alpha {    --slider-background: linear-gradient(var(--color-picker-run), transparent, var(--color-picker-solid)), var(--color-picker-checker), var(--color-surface-raised);  }  /* The swatch: the color over the checker, so an opacity under 100% shows. In the column it spans both tracks. */  .color-picker-swatch {    --swatch: linear-gradient(var(--color-picker-color) 0 0), var(--color-picker-checker), var(--color-surface-raised);    grid-row: span 2;    align-self: center;  }  .color-picker:not(:has(.color-picker-alpha)) .color-picker-swatch {    grid-row: auto;  }  /* The text: the format, then the color written in it. */  .color-picker-fields {    display: flex;    grid-column: 1 / -1;    align-items: center;    gap: .5rem;    min-width: 0;  }  .color-picker-format {    flex: none;    width: auto;  }  .color-picker-text {    flex: 1;    min-width: 0;    font-variant-numeric: tabular-nums;  }}