ナビゲーション

v2.1.0
フォーム

カラーピッカー

明度とクロマのフィールド、色相、不透明度で選ぶか、入力して指定する任意の色。

このページの内容

カラーピッカーは任意の色を選ぶコントロールです。明度とクロマは 1 つのつまみでフィールド上から選び、色相と不透明度は 2 本のスライダーで選びます。色そのものは hex、rgb()、oklch() のテキストとしても扱えます。色はテーマのすべての色が記述されている色空間 OKLCH で選ぶため、明度を 1 段階変えたときの見た目の変化は、どの色相でも同じになります。フィールドはサーフェスにはめ込まれた画像、つまみは真珠調のリングで囲んだ現在の色、トラックはネイティブの範囲入力です。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 のような色を入力したりもできます。

#ボタンから開く

色は多くの場合、ほかの設定と並ぶ設定の 1 つです。そのため、ピッカーは現在の色を表示するボタンから開くのが一般的です。ボタンと、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)の正方形にすることもできます。sRGB に白と黒を混ぜるだけなので描画は簡単です。しかし、パレットを選ぶフィールドとしては不向きです。同じ明度の値でも青なら暗く、黄色ならまぶしく見え、同じ彩度のまま色相を動かすと色の明るさの見え方が変わります。OKLCH は等しい段階が等しく見えるように設計されています。テーマが色を OKLCH で記述しているのはそのためで、テーマのためのピッカーも OKLCH で選ぶべき理由もそこにあります。

  • 明度は、フィールドの上端の 100% から下端の 0 まで変化し、どの色相でも同じ明度を表します。
  • クロマは、フィールドの始端の無彩色(グレー)から、Display P3 が届く範囲の終端 .37 まで変化します。色は常にクロマの指定どおりに鮮やかになるとは限りません。画面は表示できる最も近い色を表示し、フィールドとつまみも同じ規則でその色を表示します。
  • 色相は専用のスライダーで円周上を一周します。どの色相も見分けられるように、トラックは 1 つの明度とクロマで描かれます。

値はセレクトで選んだ形式で書き出されます。oklch() は保持している値をそのまま書き出します。hex と rgb() は sRGB しか表せないため、その範囲を超える色は、CSS Color 4 が色を画面に収めるのと同じ方法で収めます。明度と色相を保ったまま、sRGB で表せる色との差が知覚できる最小の差に収まるまでクロマを下げます。形式を切り替えても保持している色は変わらないため、hex から oklch() に変えて hex に戻すと、元と同じ hex になります。

グラデーションは 1 つの軸にしか沿わないため、フィールドは行ごとに描画します。各行は、その行の明度でグレーから .37 までを結ぶグラデーションで、線上では正確です。行と行の中間にある行は、ある行から次の行へフェードするマスクの下でほかの行に重なります。色はテーマのミックスインで、ビヘイビアが公開する色相の関数です。そのため、コンポーネントは独自の色を一切記述しません。

#ビヘイビア

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
  • 色 初期値はテキストフィールドの値から取得します。3 つの形式のいずれでもよく、形式もその値に合わせます。ビヘイビアは色を 4 つの数値 --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カラーフィールドのつまみ上で、1 ステップの 10 倍、つまり明度 10% またはクロマ .05 ずつ変更します。
PageUp, PageDownカラーフィールドのつまみ上で、明度を 10% ずつ上げ下げして色を明るく、または暗くします。
Home, Endカラーフィールドのつまみを操作し、クロマを 0(グレー)またはフィールドの終端に当たる値に設定します。
ArrowLeft, ArrowRight, ArrowUp, ArrowDown, Home, End, PageUp, PageDown色相と不透明度では、ネイティブの range 入力と同じ動作をします。
Enterテキストフィールドの入力を確定し、色の値を選択中の形式で表示し直します。入力を色として解釈できない場合は、元の値に戻します。

#アクセシビリティ

  • フィールドのつまみは 1 つのスライダーです。ArrowUp と ArrowDown で明度が動くため、値は明度です。aria-valuetext は明度とクロマをあわせて示すので、どちらが動いてもスクリーンリーダーは両方を読み上げます。「Lightness and chroma」のように、選ぶ対象を表す名前を付けます。
  • テキストフィールドは、フィールドを使わずに正確な色を指定する手段です。「Brand color」のように、色の名前はテキストフィールドに付けます。フォーム送信時は、テキストフィールドの name を項目名として色の値が送信されます。
  • 色相と不透明度のスライダー、形式のセレクトにも名前を付けます。これらのキー操作はプラットフォーム標準のものです。
  • 強制カラーモードでも、フィールドの色は維持されます。読者が見たいのはその色だからです。フィールドの縁とつまみのフォーカスはシステムカラーで描画されます。

#React、Svelte、Vue

color-picker コンポーネントは、ルートの 4 つの数値を含めて最初の値を初回の描画に反映し、ビヘイビアを適用します。それ以降は、ビヘイビアがすべての部分を動かします。値は選択中の形式で表した色のテキストで、変更のたびに出力されます。ページ独自のボタンからピッカーを開くには、trigger(Svelte ではスニペット、Vue ではスロット)を渡します。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カラーフィールドにある唯一のつまみで、ルートの数値から位置が決まります。値が明度のスライダーで、aria-valuetext で明度とクロマを伝えます。
color-picker-hue0 から 360 のスライダーに指定します。色相環の色で塗ったトラック上で色相を選びます。
color-picker-alpha0 から 100 のスライダーに指定します。市松模様の上で色が徐々に現れるトラック上で不透明度を選びます。不透明な色だけを扱う場合は省きます。
color-picker-swatchスウォッチに指定します。保持している色を市松模様の上に表示します。列の中では2本のトラックの先頭に置き、ポップオーバーを開くボタンの中では、ピッカーが閉じている間の色を示します。
color-picker-fields形式とテキストを並べる行
color-picker-format小さな select に指定します。テキストを書き出す形式を選び、選択肢は hex、rgb、oklch です。
color-picker-text小さなテキストフィールドに指定します。選んだ形式で色を表示します。3 つの形式のどれで入力された色も受け付け、フォームが送信する 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-color4 つの数値から作られる、保持している色です。ルート内で色を表示するほかの要素はこの値を参照します。

#ソース

@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;  }}