網站導覽

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 的飽和度與亮度(V)作為方形區域的兩軸,也就是大多數選擇器繪製的那種,它很容易繪製,因為只是 sRGB 混合白色與黑色。但在這種平面上很難挑選配色:即使 HSV 的 V 值相同,藍色仍顯得深暗,黃色卻刺眼;在飽和度不變的情況下調整色相,顏色看起來的明暗也會改變。OKLCH 的設計讓相等的變化幅度看起來也相等,這正是主題用它來寫顏色的原因,也是為主題選色的選擇器應該在其中選色的原因。

  • 明度從選色區頂端的 100% 到底部的 0,而且在每個色相上都是相同的明度。
  • 彩度從選色區起點的零(也就是灰色)到終點的 .37,涵蓋 Display P3 能到達的範圍。顏色不一定像它的彩度所要求的那樣鮮豔:螢幕會顯示它能呈現的最接近顏色,選色區和滑塊也依照同一套規則顯示。
  • 色相在自己的滑桿上沿著色環變化,以固定的明度和彩度繪製,讓每個色相都能分辨。

值會以下拉選單指定的格式寫出。oklch() 會完全照保存的值寫出。hex 和 rgb() 只能表示 sRGB,因此超出 sRGB 的顏色會依照 CSS Color 4 將顏色對應到螢幕的方式調整:在明度與色相不變的情況下逐步降低彩度,直到顏色與 sRGB 能寫出的某個顏色相差不到一個恰辨差(just noticeable difference)。切換格式不會改變保存的顏色,因此顏色從 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,分別朝選色區的末端或起點移動(文字從右向左排列時左右對調)
Shift with an arrow在選色區的滑塊上,以十倍步幅調整明度或彩度,分別為 10 個百分點或 .05。
PageUp, PageDown在選色區的滑塊上,將明度調高或調低 10 個百分點。
Home, End在選色區的滑塊上,將彩度降到零(灰色)或調到選色區的末端
ArrowLeft, ArrowRight, ArrowUp, ArrowDown, Home, End, PageUp, PageDown在色相與不透明度滑桿上,行為與原生範圍輸入控制項相同
Enter在文字欄位中套用輸入的內容。欄位會以所選格式重新寫入;若輸入的不是顏色,則還原為原本的值

#無障礙

  • 選色區的滑塊是一個滑桿。由於 ArrowUp 和 ArrowDown 會調整明度,它的值就是明度;它的 aria-valuetext 則同時說出明度與彩度,因此無論哪一項改變,螢幕閱讀器都會讀出兩者。請依它所選擇的內容命名,例如「Lightness and chroma」(明度與彩度)。
  • 文字欄位是不使用選色區就能指定精確顏色的方式,顏色的名稱也應加在它上面,例如「Brand color」(品牌色)。表單會以它的 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,則只放按鈕和彈出面板,由彈出面板承載這一欄
color-picker-area選色區的色相固定為目前的值,明度從頂端的 100% 降至底部的 0,彩度沿橫軸從起點的 0 增至末端的 .37。選色區內含滑塊,並接收指標操作。
color-picker-thumb選色區上唯一的滑塊,依根元素上的數值定位。它是一個 slider,值為明度,aria-valuetext 會說明明度與彩度
color-picker-hue套用於 0 到 360 的滑桿:代表色相,軌道上繪有完整的色相環
color-picker-alpha數值從 0 到 100 的滑桿用於調整不透明度,軌道上的顏色會在棋盤格上逐漸顯現。顏色固定為完全不透明時,可省略這個滑桿。
color-picker-swatch套用於色票:在棋盤格上顯示目前的顏色。在直欄中位於兩條軌道的開頭;在開啟彈出面板的按鈕中,則在選擇器關閉時顯示目前的顏色
color-picker-fields放置格式選單與文字欄位的一列
color-picker-format套用於小型 select:文字所用的格式,選項為 hex、rgb 和 oklch
color-picker-text套用於小型文字欄位:以所選格式寫出的顏色。可接受以三種格式任一種輸入的顏色,並帶有表單送出時使用的 name
color-picker-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;  }}