Navigation

v2.1.0
Forms

Color picker

Any color, chosen on a field of lightness and chroma, a hue and an opacity, or typed.

On this page

A color picker chooses any color: lightness and chroma on a field under one thumb, the hue and the opacity on two sliders, and the color itself as text in hex, rgb() or oklch(). It chooses in OKLCH, the space every color of the theme is written in, so a step of lightness looks like the same step at every hue. The field is a picture set into the surface; the thumb is the color in a pearl ring; the tracks are native range inputs. The color-picker behavior keeps the parts in step.

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>
Drag on the field or use the arrow keys on its thumb, move the hue, switch the format, or type a color such as #e5484d.

#Opened from a button

Most of the time a color is one setting among others, and the picker opens from a button that shows it. Put the button and a popover with color-picker-popover inside the root: the popover becomes the column, and a swatch with color-picker-swatch in the button shows the color while the picker is closed, since both stand in the root that holds it. The browser opens, places and dismisses the popover; the behavior is the same.

Opened from a button

<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>
Open the picker and move the color: the swatch in the button follows it.

Leave out color-picker-alpha for a color that has to be opaque, such as a brand color that is printed: the swatch then stands beside the hue alone, and a color typed with an opacity is taken without it. Leave out the swatch too, and the tracks take the whole width.

#Why OKLCH

The field could be saturation and value, the square most pickers draw, which is easy to paint because it is only sRGB mixed with white and black. It is a poor field to choose a palette on: the same value is a dark blue and a glaring yellow, and a hue moved at the same saturation changes how light the color looks. OKLCH is built so that equal steps look equal, which is why the theme writes its colors in it, and why a picker for a theme should choose in it too.

  • Lightness runs from 100% at the top of the field to 0 at the bottom, and is the same lightness at every hue.
  • Chroma runs from none, a grey, at the start of the field to .37 at its end, as far as Display P3 reaches. A color is not always as vivid as its chroma asks: the screen shows the nearest one it can, and so do the field and the thumb, through the same rule.
  • Hue runs round the circle on its own slider, painted at one lightness and chroma so every hue can be told apart.

The value is written in the format the select says. oklch() is written exactly as it is held. Hex and rgb() can hold only sRGB, so a color past it is fitted as CSS Color 4 fits a color to a screen: chroma is taken away, at the same lightness and hue, until the color is within a just noticeable difference of one sRGB can write. Switching the format never moves the color held, so a color goes from hex to oklch() and back to the same hex.

A gradient runs along one axis only, so the field is drawn in rows: each row is a gradient from grey to .37 at its own lightness, exact along the line, and the rows halfway between them lie over the others under a mask that fades from one row to the next. The colors are the theme's mixins, functions of the hue the behavior publishes, so the component writes no color of its own.

#The behavior

colorPicker takes the root, the element with the color-picker class, and returns the function that detaches it.

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
  • The color starts from the text field's value, in any of the three formats, and the format with it. The behavior writes it on the root as four numbers, --color-picker-lightness, --color-picker-chroma, --color-picker-hue and --color-picker-alpha, which place the thumb and paint the field, the tracks and the swatches. Write the first color's numbers in the root's style too, so the field is right before the script runs.
  • The field. A press puts the thumb under the pointer and gives it focus; a drag follows, even past the edge of the field, where the color stops. The keys are in the table below.
  • The text takes a color as soon as what is typed is one, and leaves the text as it is typed. When the field is committed, with Enter or by leaving it, the color is written again in the format chosen; text that is not a color is put back.
  • Events. The thumb dispatches input while the color moves and change when a drag ends or a key moved it; the sliders, the select and the text field dispatch their own. Whoever listens on the root reads the new value in each of them.
  • The thumb's words. Its aria-valuetext says Lightness 62%, chroma 0.19; pass valueText: (lightness, chroma) => … to say it in the page's language.

Without the behavior the field shows the color written in the markup, and the sliders, the select and the text field are plain controls that do not follow one another.

#Keyboard

KeysAction
ArrowUp, ArrowDownOn the field's thumb, make the color lighter or darker by 1% of lightness
ArrowRight, ArrowLeftOn the field's thumb, add or take away .005 of chroma, toward the end of the line or its start (mirrored right to left)
Shift with an arrowOn the field's thumb, ten times the step: 10% of lightness or .05 of chroma
PageUp, PageDownOn the field's thumb, make the color lighter or darker by 10% of lightness
Home, EndOn the field's thumb, take the chroma to none (a grey) or to the end of the field
ArrowLeft, ArrowRight, ArrowUp, ArrowDown, Home, End, PageUp, PageDownOn the hue and the opacity, what the native range input does
EnterIn the text field, take what is typed; the field is written again in the format chosen, or put back when it is not a color

#Accessibility

  • The field's thumb is one slider. Its value is the lightness, since ArrowUp and ArrowDown move it, and its aria-valuetext names the lightness and the chroma together, so a screen reader says both whichever moved. Name it for what it chooses, such as "Lightness and chroma".
  • The text field is the way to give an exact color without the field, and the name of the color goes on it: "Brand color". Its name is what a form submits.
  • Name the hue and the opacity sliders and the format select; their keys are the platform's.
  • Forced colors keep the field's colors, since they are what the reader came for; its edge and the thumb's focus are drawn in system colors.

#React, Svelte and Vue

The color-picker component draws the first value into the first render, the four numbers on the root included, and attaches the behavior, which moves every part after that. Its value is the color as text, in the format chosen, and it comes out on every change; give trigger (a snippet in Svelte, a slot in Vue) to open the picker from a button of the page's. Copy it into the project with npx master-ui add color-picker; React, Svelte and Vue says how the components are built and used.

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>

#Classes

ClassDescription
color-pickerThe picker: a column 16rem wide of the field, the tracks and the text. When it holds a color-picker-popover it holds only the button and the popover, which takes the column
color-picker-areaThe field: lightness from 100% at the top to 0 at the bottom, chroma from 0 to .37 along the line, at the hue held. It holds the thumb and takes the pointer
color-picker-thumbThe one thumb of the field, placed from the numbers on the root: a slider whose value is the lightness and whose aria-valuetext names the lightness and the chroma
color-picker-hueOn a slider from 0 to 360: the hue, on a track painted with the circle of hues
color-picker-alphaOn a slider from 0 to 100: the opacity, on a track where the color fades in over a checker. Leave it out for an opaque color
color-picker-swatchOn a swatch: the color held, over a checker. In the column it stands at the start of the two tracks; in the button that opens a popover it shows the color while the picker is closed
color-picker-fieldsThe row of the format and the text
color-picker-formatOn a small select: the format the text is written in, with the options hex, rgb and oklch
color-picker-textOn a small text field: the color, written in the format chosen. It takes a color typed in any of the three, and carries the name a form submits
color-picker-popoverOn a popover inside the root: the column, opened from a button beside it, whose swatch shows the color

#Custom properties

PropertyDefaultDescription
--color-picker-width16remWidth of the column
--color-picker-lightness0The color's lightness, from 0 to 1. The behavior writes it on the root; write the first value in the markup's style
--color-picker-chroma0The color's chroma, from 0; the field reaches .37
--color-picker-hue0The color's hue, in degrees without a unit
--color-picker-alpha1The color's opacity, from 0 to 1
--color-picker-colorThe color held, made from the four numbers: read it for anything else inside the root that shows the color

#Source

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