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
'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'exportinterfaceColorPickerLabels{/** 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}exportinterfaceColorPickerPropsextendsOmit<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?:stringdefaultValue?:stringonValueChange?:(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?:booleandisabled?: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. */exportfunctionColorPicker({ 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)asElementTypeconst column = trigger ?{id:`${id}popover`,popover:'auto',className:'popover color-picker-popover'}:{}return(<divclassName={className ?`color-picker ${className}`:'color-picker'}ref={ref}style={{...first.properties,...style }asCSSProperties}{...root}>{trigger?.({popoverTarget:`${id}popover`})}<Column{...column}><divclassName="color-picker-area"><divclassName="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><spanclassName="swatch swatch-lg color-picker-swatch"/><inputtype="range"className="slider color-picker-hue"min={0}max={360}defaultValue={first.hue}aria-label={labels.hue??'Hue'}disabled={disabled}/>{alpha &&<inputtype="range"className="slider color-picker-alpha"min={0}max={100}defaultValue={first.alpha*100}aria-label={labels.alpha??'Opacity'}disabled={disabled}/>}<divclassName="color-picker-fields"><selectclassName="select select-sm color-picker-format"defaultValue={first.format}aria-label={labels.format??'Format'}disabled={disabled}><optionvalue="hex">Hex</option><optionvalue="rgb">RGB</option><optionvalue="oklch">OKLCH</option></select><inputclassName="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
<scriptlang="ts"module>importtype{ Snippet }from'svelte'importtype{ HTMLAttributes }from'svelte/elements'exportinterfaceColorPickerLabels{/** 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}exportinterfaceColorPickerPropsextendsOmit<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?:stringonValueChange?:(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?:booleandisabled?: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><scriptlang="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)constread=()=>{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>{#snippetpanel()}<divclass="color-picker-area"><divclass="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><spanclass="swatch swatch-lg color-picker-swatch"></span><inputtype="range"class="slider color-picker-hue"min="0"max="360"value={first.hue}aria-label={labels.hue??'Hue'}{disabled}/>{#if alpha}<inputtype="range"class="slider color-picker-alpha"min="0"max="100"value={first.alpha*100}aria-label={labels.alpha??'Opacity'}{disabled}/>{/if}<divclass="color-picker-fields"><selectclass="select select-sm color-picker-format"aria-label={labels.format??'Format'}{disabled}><optionvalue="hex"selected={first.format==='hex'}>Hex</option><optionvalue="rgb"selected={first.format==='rgb'}>RGB</option><optionvalue="oklch"selected={first.format==='oklch'}>OKLCH</option></select><inputclass="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.--><divclass={['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}{@rendertrigger({popovertarget:`${id}-popover`})}<divid="{id}-popover"popover="auto"class="popover color-picker-popover">{@renderpanel()}</div>{:else}{@renderpanel()}{/if}</div>
ui/ColorPicker.vue
<scriptsetuplang="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?:booleandisabled?: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.constproperties=()=> Object.fromEntries(Object.entries(first.properties).map(([property, number])=>[property, root.value?.style.getPropertyValue(property)|| number]))useBehavior(root, colorPicker,()=>({ valueText }), model)</script><template><divclass="color-picker"ref="root"v-bind="$attrs":style="properties()"><templatev-if="slots.trigger"><slotname="trigger"v-bind="{popovertarget:`${id}-popover`}" /><div:id="`${id}-popover`"popover="auto"class="popover color-picker-popover"><divclass="color-picker-area"><divclass="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><spanclass="swatch swatch-lg color-picker-swatch" /><inputtype="range"class="slider color-picker-hue"min="0"max="360":value.attr="first.hue":aria-label="labels.hue??'Hue'":disabled="disabled"><inputv-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"><divclass="color-picker-fields"><selectclass="select select-sm color-picker-format":aria-label="labels.format??'Format'":disabled="disabled"><optionvalue="hex":selected="first.format==='hex'">Hex</option><optionvalue="rgb":selected="first.format==='rgb'">RGB</option><optionvalue="oklch":selected="first.format==='oklch'">OKLCH</option></select><inputclass="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. --><templatev-else><divclass="color-picker-area"><divclass="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><spanclass="swatch swatch-lg color-picker-swatch" /><inputtype="range"class="slider color-picker-hue"min="0"max="360":value.attr="first.hue":aria-label="labels.hue??'Hue'":disabled="disabled"><inputv-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"><divclass="color-picker-fields"><selectclass="select select-sm color-picker-format":aria-label="labels.format??'Format'":disabled="disabled"><optionvalue="hex":selected="first.format==='hex'">Hex</option><optionvalue="rgb":selected="first.format==='rgb'">RGB</option><optionvalue="oklch":selected="first.format==='oklch'">OKLCH</option></select><inputclass="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: 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)025%,transparent050%)00/.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:autominmax(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:autominmax(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,black6.25%,transparent12.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:inset000.5pxvar(--color-line-on-color);pointer-events:none;}&:has(.color-picker-thumb[aria-disabled="true"]){opacity:.5;cursor:not-allowed;}@media(forced-colors:active){outline:1pxsolid 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:inset0003pxvar(--color-thumb-high),inset0003.5pxvar(--color-line-on-color),000.5pxvar(--color-line-strong),01px2px-.5pxvar(--color-shade-1),02px4px-1pxvar(--color-shade-2),04px8px-4pxvar(--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:inset0001px 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)00),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;}}