Color Picker for Astro
A full-featured color picker for Astro. Built with the popover component, with support for hex, hsl, rgb, and oklch - plus alpha control, swatches, and more.
---import { ColorPicker, ColorPickerContent, ColorPickerTrigger,} from "@/components/ui/color-picker"---
<ColorPicker id="accent-color" defaultValue="#007aff" label="Accent color" name="accent" class="w-72"> <ColorPickerTrigger /> <ColorPickerContent /></ColorPicker>Installation
bunx --bun shadcn@latest add @gnostic/color-pickernpx shadcn@latest add @gnostic/color-pickerpnpm dlx shadcn@latest add @gnostic/color-pickerInstall component packages
bun add @data-slot/core @data-slot/popovernpm install @data-slot/core @data-slot/popoverpnpm add @data-slot/core @data-slot/popoverCopy the files
src/components/ui/color-picker/color-picker-area.astro---import type { HTMLAttributes } from "astro/types"import { cn } from "cn"type Props = HTMLAttributes<"div">const { class: className, ...props } = Astro.props--- <div data-slot="color-picker-area" role="group" tabindex="0" aria-label="Saturation and brightness. Use Left and Right for saturation, Up and Down for brightness." class={cn("relative h-40 w-full cursor-crosshair touch-none rounded-lg select-none outline-none focus-visible:ring-2 focus-visible:ring-ring aria-disabled:pointer-events-none aria-disabled:opacity-50 forced-color-adjust-none", className)} {...props}> <span data-slot="color-picker-area-thumb" class="pointer-events-none absolute size-4 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white shadow-md ring-1 ring-black/40" ></span></div>src/components/ui/color-picker/color-picker-channel-input.astro---import type { HTMLAttributes } from "astro/types"import { cn } from "cn"import { InputGroupInput } from "@/components/ui/input-group"import type { ColorPickerChannelInputProps } from "./types.ts"type Props = Omit<HTMLAttributes<"input">, "type" | "value" | "name"> & ColorPickerChannelInputPropsconst { class: className, channel = "hex", colorSpace, ...props } = Astro.props--- <InputGroupInput data-slot="color-picker-channel-input" data-channel={channel} data-color-space={colorSpace} type="text" inputmode={channel === "hex" ? "text" : "decimal"} aria-label={channel === "alpha" ? "Opacity" : channel} autocomplete="off" autocapitalize="none" spellcheck="false" class={cn("min-w-0 flex-1 px-2 tabular-nums not-first:border-s not-first:border-border data-[channel=hex]:uppercase", className)} {...props}/>src/components/ui/color-picker/color-picker-eye-dropper.astro---import PipetteIcon from "@lucide/astro/icons/pipette"import { buttonVariants } from "@/components/ui/button"import type { ButtonProps } from "@/components/ui/button/types"import { cn } from "cn"import type { HTMLAttributes } from "astro/types" type Props = HTMLAttributes<"button"> & ButtonProps const { class: className, size = "icon-xs", variant = "ghost", ...props} = Astro.props--- <button data-slot="color-picker-eye-dropper" class={cn(buttonVariants({ size, variant }), "[hidden]:hidden", className)} title="Pick a color from the screen" {...props} hidden> <PipetteIcon aria-hidden="true" /></button><script> declare class EyeDropper { open: (options?: { signal?: AbortSignal }) => Promise<{ sRGBHex: string }> } function init() { const isSupported = "EyeDropper" in window const button = document.querySelector( "[data-slot='color-picker-eye-dropper']", ) if (!isSupported || !button) { return } button.removeAttribute("hidden") const eyeDropper = new EyeDropper() button.addEventListener("click", async () => { const colorPicker = button.closest("[data-slot='color-picker']") if (!colorPicker) { return } const color = await eyeDropper.open() colorPicker.dispatchEvent( new CustomEvent("color-picker:set-color", { detail: color.sRGBHex }), ) }) }</script>src/components/ui/color-picker/color-picker-color.ts/** Color parsing and conversion adapted from the ReUI source supplied for this port. * Channels stay in their source color space until a control changes them. */import type { ColorPickerColor, ColorPickerColorSpace, ColorPickerChannel, ColorPickerFormat,} from './types.ts' type Triple = [number, number, number] const SPACE_CHANNELS: Record< ColorPickerColorSpace, [ColorPickerChannel, ColorPickerChannel, ColorPickerChannel]> = { rgb: ['red', 'green', 'blue'], hsl: ['hue', 'saturation', 'lightness'], hsv: ['hue', 'saturation', 'brightness'], oklch: ['lightness', 'chroma', 'hue'],} export const COLOR_PICKER_FORMATS: ColorPickerFormat[] = [ 'hex', 'rgb', 'hsl', 'hsb', 'oklch',] export const FORMAT_LABELS: Record<ColorPickerFormat, string> = { hex: 'HEX', rgb: 'RGB', hsl: 'HSL', hsb: 'HSB', oklch: 'OKLCH',} /* -------------------------------------------------------------------------- *//* Color math *//* -------------------------------------------------------------------------- */ export const clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value)) export const wrapHue = (hue: number) => ((hue % 360) + 360) % 360 /* Round output only. Drop trailing zeros and never write "-0". */export const fixed = (value: number, digits = 3) => String(Number(value.toFixed(digits)) + 0) function rgbToHsv([red, green, blue]: Triple, fallbackHue = 0): Triple { const r = red / 255 const g = green / 255 const b = blue / 255 const max = Math.max(r, g, b) const delta = max - Math.min(r, g, b) let hue = fallbackHue if (delta > 1e-9) { hue = max === r ? ((g - b) / delta) % 6 : max === g ? (b - r) / delta + 2 : (r - g) / delta + 4 hue = wrapHue(hue * 60) } return [hue, max === 0 ? 0 : (delta / max) * 100, max * 100]} function hsvToRgb([hue, saturation, brightness]: Triple): Triple { const s = saturation / 100 const v = brightness / 100 const channel = (n: number) => { const k = (n + hue / 60) % 6 return (v - v * s * Math.max(0, Math.min(k, 4 - k, 1))) * 255 } return [channel(5), channel(3), channel(1)]} /* HSL and HSB share a hue, carried over as is, so a gray keeps it. */function hsvToHsl([hue, saturation, brightness]: Triple): Triple { const s = saturation / 100 const v = brightness / 100 const l = v * (1 - s / 2) const sl = l === 0 || l === 1 ? 0 : (v - l) / Math.min(l, 1 - l) return [hue, sl * 100, l * 100]} function hslToHsv([hue, saturation, lightness]: Triple): Triple { const s = saturation / 100 const l = lightness / 100 const v = l + s * Math.min(l, 1 - l) return [hue, v === 0 ? 0 : 2 * (1 - l / v) * 100, v * 100]} const toLinear = (channel: number) => { const c = channel / 255 return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4} const fromLinear = (channel: number) => 255 * (channel <= 0.0031308 ? 12.92 * channel : 1.055 * channel ** (1 / 2.4) - 0.055) /* OKLab by Björn Ottosson, the matrices CSS Color 4 uses. Linear sRGB in, unbounded, so a wide-gamut color converts without clipping. */function linearToOklab([r, g, b]: Triple): Triple { const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b) const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b) const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b) return [ 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s, 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s, 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s, ]} /* OKLab, or polar a and b, to OKLCH in the picker's units: L 0 to 100. */function oklabToOklch([lightness, a, b]: Triple, fallbackHue = 0): Triple { const chroma = Math.sqrt(a * a + b * b) const hue = chroma < 1e-4 ? fallbackHue : wrapHue((Math.atan2(b, a) * 180) / Math.PI) return [lightness * 100, chroma, hue]} function rgbToOklch(rgb: Triple, fallbackHue = 0): Triple { return oklabToOklch(linearToOklab(rgb.map(toLinear) as Triple), fallbackHue)} function oklchToLinear([lightness, chroma, hue]: Triple): Triple { const angle = (hue * Math.PI) / 180 const L = lightness / 100 const a = chroma * Math.cos(angle) const b = chroma * Math.sin(angle) const l = (L + 0.3963377774 * a + 0.2158037573 * b) ** 3 const m = (L - 0.1055613458 * a - 0.0638541728 * b) ** 3 const s = (L - 0.0894841775 * a - 1.291485548 * b) ** 3 return [ 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s, -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s, -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s, ]} const inSrgb = (linear: Triple) => linear.every((channel) => channel >= -1e-4 && channel <= 1 + 1e-4) const clipLinear = (linear: Triple) => linear.map((channel) => clamp(channel, 0, 1)) as Triple /* How far a clipped color lands from the OKLCH it stands for, in OKLab. */function clipError(clipped: Triple, [lightness, chroma, hue]: Triple) { const [l, a, b] = linearToOklab(clipped) const angle = (hue * Math.PI) / 180 return Math.hypot( l - lightness / 100, a - chroma * Math.cos(angle), b - chroma * Math.sin(angle), )} /* CSS Color 4 gamut mapping: lower chroma at the same lightness and hue until clipping the rest moves the color less than a just-noticeable difference (0.02 in OKLab), then clip. Pure chroma reduction drifted up to 27 units in hex from what a browser paints for Tailwind's P3 shades. */function oklchToRgb([lightness, chroma, hue]: Triple): Triple { const encode = (linear: Triple) => linear.map((channel) => fromLinear(channel)) as Triple if (lightness >= 100) return [255, 255, 255] if (lightness <= 0) return [0, 0, 0] const target: Triple = [lightness, Math.max(0, chroma), hue] const origin = oklchToLinear(target) if (inSrgb(origin)) return encode(clipLinear(origin)) let clipped = clipLinear(origin) if (clipError(clipped, target) < 0.02) return encode(clipped) let low = 0 let high = target[1] let lowInGamut = true while (high - low > 1e-4) { const mid = (low + high) / 2 const current: Triple = [lightness, mid, hue] const linear = oklchToLinear(current) if (lowInGamut && inSrgb(linear)) { low = mid continue } clipped = clipLinear(linear) const error = clipError(clipped, current) if (error < 0.02) { if (0.02 - error < 1e-4) break lowInGamut = false low = mid } else { high = mid } } return encode(clipped)} function toRgb(color: ColorPickerColor): Triple { const { space, channels } = color if (space === 'rgb') return channels if (space === 'hsv') return hsvToRgb(channels) if (space === 'hsl') return hsvToRgb(hslToHsv(channels)) return oklchToRgb(channels)} /** A color's channels in another space. */export function toSpace( color: ColorPickerColor, space: ColorPickerColorSpace,): Triple { const { space: from, channels } = color if (from === space) return channels if (from === 'hsv' && space === 'hsl') return hsvToHsl(channels) if (from === 'hsl' && space === 'hsv') return hslToHsv(channels) const rgb = toRgb(color) const hue = from === 'rgb' ? 0 : channels[from === 'oklch' ? 2 : 0] if (space === 'rgb') return rgb if (space === 'hsv') return rgbToHsv(rgb, hue) if (space === 'hsl') return hsvToHsl(rgbToHsv(rgb, hue)) return rgbToOklch(rgb, hue)} /** Whether a color fits sRGB. OKLCH can reach past it; the picker then maps it into sRGB the way CSS does. */export function isColorInSrgb(color: ColorPickerColor) { return color.space !== 'oklch' || inSrgb(oklchToLinear(color.channels))} const HEX_PATTERN = /^#?([\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})$//* [\s\S], not ".", so a function pretty-printed over several lines reads. */const FUNCTION_PATTERN = /^([a-z][a-z\d-]*)\(([\s\S]*)\)$/const NUMBER_PATTERN = /^([+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?)(%|deg|rad|grad|turn)?$/ /* The 148 CSS named colors, each name then its hex: about 2.3 KB, checked against Chrome, and safe to read on the server unlike a canvas. */const NAMED_COLORS = 'alicebluef0f8ff antiquewhitefaebd7 aqua00ffff aquamarine7fffd4 ' + 'azuref0ffff beigef5f5dc bisqueffe4c4 black000000 blanchedalmondffebcd ' + 'blue0000ff blueviolet8a2be2 browna52a2a burlywooddeb887 ' + 'cadetblue5f9ea0 chartreuse7fff00 chocolated2691e coralff7f50 ' + 'cornflowerblue6495ed cornsilkfff8dc crimsondc143c cyan00ffff ' + 'darkblue00008b darkcyan008b8b darkgoldenrodb8860b darkgraya9a9a9 ' + 'darkgreen006400 darkgreya9a9a9 darkkhakibdb76b darkmagenta8b008b ' + 'darkolivegreen556b2f darkorangeff8c00 darkorchid9932cc darkred8b0000 ' + 'darksalmone9967a darkseagreen8fbc8f darkslateblue483d8b ' + 'darkslategray2f4f4f darkslategrey2f4f4f darkturquoise00ced1 ' + 'darkviolet9400d3 deeppinkff1493 deepskyblue00bfff dimgray696969 ' + 'dimgrey696969 dodgerblue1e90ff firebrickb22222 floralwhitefffaf0 ' + 'forestgreen228b22 fuchsiaff00ff gainsborodcdcdc ghostwhitef8f8ff ' + 'goldffd700 goldenroddaa520 gray808080 green008000 greenyellowadff2f ' + 'grey808080 honeydewf0fff0 hotpinkff69b4 indianredcd5c5c indigo4b0082 ' + 'ivoryfffff0 khakif0e68c lavendere6e6fa lavenderblushfff0f5 ' + 'lawngreen7cfc00 lemonchiffonfffacd lightblueadd8e6 lightcoralf08080 ' + 'lightcyane0ffff lightgoldenrodyellowfafad2 lightgrayd3d3d3 ' + 'lightgreen90ee90 lightgreyd3d3d3 lightpinkffb6c1 lightsalmonffa07a ' + 'lightseagreen20b2aa lightskyblue87cefa lightslategray778899 ' + 'lightslategrey778899 lightsteelblueb0c4de lightyellowffffe0 lime00ff00 ' + 'limegreen32cd32 linenfaf0e6 magentaff00ff maroon800000 ' + 'mediumaquamarine66cdaa mediumblue0000cd mediumorchidba55d3 ' + 'mediumpurple9370db mediumseagreen3cb371 mediumslateblue7b68ee ' + 'mediumspringgreen00fa9a mediumturquoise48d1cc mediumvioletredc71585 ' + 'midnightblue191970 mintcreamf5fffa mistyroseffe4e1 moccasinffe4b5 ' + 'navajowhiteffdead navy000080 oldlacefdf5e6 olive808000 olivedrab6b8e23 ' + 'orangeffa500 orangeredff4500 orchidda70d6 palegoldenrodeee8aa ' + 'palegreen98fb98 paleturquoiseafeeee palevioletreddb7093 ' + 'papayawhipffefd5 peachpuffffdab9 perucd853f pinkffc0cb plumdda0dd ' + 'powderblueb0e0e6 purple800080 rebeccapurple663399 redff0000 ' + 'rosybrownbc8f8f royalblue4169e1 saddlebrown8b4513 salmonfa8072 ' + 'sandybrownf4a460 seagreen2e8b57 seashellfff5ee siennaa0522d ' + 'silverc0c0c0 skyblue87ceeb slateblue6a5acd slategray708090 ' + 'slategrey708090 snowfffafa springgreen00ff7f steelblue4682b4 tand2b48c ' + 'teal008080 thistled8bfd8 tomatoff6347 turquoise40e0d0 violetee82ee ' + 'wheatf5deb3 whiteffffff whitesmokef5f5f5 yellowffff00 ' + 'yellowgreen9acd32' let namedColors: Map<string, string> | null = null function namedColor(name: string) { namedColors ??= new Map( NAMED_COLORS.split(' ').map((entry) => [ entry.slice(0, -6), entry.slice(-6), ]), ) return namedColors.get(name)} /* One CSS number: 100% is worth `percentOf`, computed as value * percentOf / 100 so 50% of 255 is exactly 127.5; angles only where allowed. */function readNumber(token: string, percentOf: number, angle = false) { if (token === 'none') return 0 const match = NUMBER_PATTERN.exec(token) if (!match) return null const value = Number(match[1]) if (!Number.isFinite(value)) return null const unit = match[2] if (!unit) return value if (unit === '%') return angle ? null : (value * percentOf) / 100 if (!angle) return null if (unit === 'rad') return (value * 180) / Math.PI if (unit === 'grad') return value * 0.9 if (unit === 'turn') return value * 360 return value} type Matrix = [Triple, Triple, Triple] const multiply = (matrix: Matrix, [x, y, z]: Triple): Triple => matrix.map((row) => row[0] * x + row[1] * y + row[2] * z) as Triple const compose = (outer: Matrix, inner: Matrix): Matrix => outer.map((row) => [0, 1, 2].map( (column) => row[0] * inner[0][column] + row[1] * inner[1][column] + row[2] * inner[2][column], ), ) as Matrix /* CSS Color 4's matrices: XYZ D65 to linear sRGB, each RGB space to XYZ, and Bradford from D50, the white of lab(), lch() and ProPhoto. */const XYZ_TO_SRGB: Matrix = [ [12831 / 3959, -329 / 214, -1974 / 3959], [-851781 / 878810, 1648619 / 878810, 36519 / 878810], [705 / 12673, -2585 / 12673, 705 / 667],]const D50_TO_D65: Matrix = [ [0.955473421488075, -0.02309845494876471, 0.06325924320057072], [-0.0283697093338637, 1.0099953980813041, 0.021041441191917323], [0.012314014864481998, -0.020507649298898964, 1.330365926242124],]const D50_TO_SRGB = compose(XYZ_TO_SRGB, D50_TO_D65) /* sRGB's curve, carried past 0 and 1 by symmetry, as color() allows. */const decodeSrgb = (value: number) => { const size = Math.abs(value) return ( Math.sign(value) * (size <= 0.04045 ? size / 12.92 : ((size + 0.055) / 1.055) ** 2.4) )} const RGB_SPACES: Record< string, { decode: (value: number) => number; toSrgb: Matrix | null }> = { srgb: { decode: decodeSrgb, toSrgb: null }, 'srgb-linear': { decode: (value) => value, toSrgb: null }, 'display-p3': { decode: decodeSrgb, toSrgb: compose(XYZ_TO_SRGB, [ [0.4865709486482162, 0.26566769316909306, 0.1982172852343625], [0.2289745640697488, 0.6917385218365064, 0.079286914093745], [0, 0.04511338185890264, 1.043944368900976], ]), }, 'a98-rgb': { decode: (value) => Math.sign(value) * Math.abs(value) ** (563 / 256), toSrgb: compose(XYZ_TO_SRGB, [ [573536 / 994567, 263643 / 1420810, 187206 / 994567], [591459 / 1989134, 6239551 / 9945670, 374412 / 4972835], [53769 / 1989134, 351524 / 4972835, 4929758 / 4972835], ]), }, 'prophoto-rgb': { decode: (value) => { const size = Math.abs(value) return size <= 16 / 512 ? value / 16 : Math.sign(value) * size ** 1.8 }, toSrgb: compose(D50_TO_SRGB, [ [0.7977666449006423, 0.13518129740053308, 0.0313477341283922], [0.2880748288194013, 0.711835234241873, 0.00008993693872564], [0, 0, 0.8251046025104602], ]), }, rec2020: { decode: (value) => { const size = Math.abs(value) return size < 0.018053968510807 * 4.5 ? value / 4.5 : Math.sign(value) * ((size + 0.09929682680944) / 1.09929682680944) ** (1 / 0.45) }, toSrgb: compose(XYZ_TO_SRGB, [ [0.6369580483012914, 0.14461690358620832, 0.1688809751641721], [0.2627002120112671, 0.6779980715188708, 0.05930171646986196], [0, 0.028072693049087428, 1.060985057710791], ]), }, xyz: { decode: (value) => value, toSrgb: XYZ_TO_SRGB }, 'xyz-d65': { decode: (value) => value, toSrgb: XYZ_TO_SRGB }, 'xyz-d50': { decode: (value) => value, toSrgb: D50_TO_SRGB },} /* CIE Lab, D50 white, to XYZ D50, as CSS Color 4 writes it. */function labToXyz([lightness, a, b]: Triple): Triple { const kappa = 24389 / 27 const epsilon = 216 / 24389 const fy = (lightness + 16) / 116 const fx = a / 500 + fy const fz = fy - b / 200 const x = fx ** 3 > epsilon ? fx ** 3 : (116 * fx - 16) / kappa const y = lightness > kappa * epsilon ? fy ** 3 : lightness / kappa const z = fz ** 3 > epsilon ? fz ** 3 : (116 * fz - 16) / kappa return [x * (0.3457 / 0.3585), y, z * ((1 - 0.3457 - 0.3585) / 0.3585)]} /* A color that can reach past sRGB is kept as OKLCH, so nothing is clipped until a format or a screen needs sRGB. */const fromLinearSrgb = (linear: Triple): Triple => oklabToOklch(linearToOklab(linear)) const isUnit = (channels: Triple) => channels.every((channel) => channel >= -1e-6 && channel <= 1 + 1e-6) /* The channels of one function, as a color in the picker's spaces. */export function readChannels( name: string, parts: string[],): { space: ColorPickerColorSpace; channels: Triple } | null { if (name === 'rgb') { const rgb = parts.map((part) => readNumber(part, 255)) if (rgb.some((value) => value === null)) return null return { space: 'rgb', channels: rgb.map((value) => clamp(value!, 0, 255)) as Triple, } } if (name === 'hsl' || name === 'hsv' || name === 'hsb' || name === 'hwb') { const hue = readNumber(parts[0], 1, true) const first = readNumber(parts[1], 100) const second = readNumber(parts[2], 100) if (hue === null || first === null || second === null) return null const x = clamp(first, 0, 100) const y = clamp(second, 0, 100) if (name === 'hsl') return { space: 'hsl', channels: [hue, x, y] } if (name !== 'hwb') return { space: 'hsv', channels: [hue, x, y] } /* hwb(): whiteness and blackness are HSB's saturation and brightness read from the other end; summing past 100% gives their gray. */ const total = x + y if (total >= 100) { return { space: 'hsv', channels: [hue, 0, (x / total) * 100] } } const brightness = 100 - y return { space: 'hsv', channels: [hue, (1 - x / brightness) * 100, brightness], } } if (name === 'oklch' || name === 'oklab') { const lightness = readNumber(parts[0], 1) const second = readNumber(parts[1], 0.4) const third = name === 'oklch' ? readNumber(parts[2], 1, true) : readNumber(parts[2], 0.4) if (lightness === null || second === null || third === null) return null const l = clamp(lightness, 0, 1) if (name === 'oklch') { return { space: 'oklch', channels: [l * 100, Math.max(0, second), third], } } return { space: 'oklch', channels: oklabToOklch([l, second, third]), } } if (name === 'lab' || name === 'lch') { const lightness = readNumber(parts[0], 100) const second = readNumber(parts[1], name === 'lab' ? 125 : 150) const third = name === 'lch' ? readNumber(parts[2], 1, true) : readNumber(parts[2], 125) if (lightness === null || second === null || third === null) return null const l = clamp(lightness, 0, 100) const angle = (third * Math.PI) / 180 const [a, b] = name === 'lab' ? [second, third] : [ Math.max(0, second) * Math.cos(angle), Math.max(0, second) * Math.sin(angle), ] return { space: 'oklch', channels: fromLinearSrgb( multiply(D50_TO_SRGB, labToXyz([l, a, b])), ), } } if (name === 'color') { if (!Object.hasOwn(RGB_SPACES, parts[0])) return null const target = RGB_SPACES[parts[0]] if (!target || parts.length !== 4) return null const values = parts.slice(1).map((part) => readNumber(part, 1)) if (values.some((value) => value === null)) return null const channels = values as Triple if (parts[0] === 'srgb' && isUnit(channels)) { return { space: 'rgb', channels: channels.map( (value) => clamp(value, 0, 1) * 255, ) as Triple, } } const linear = channels.map(target.decode) as Triple return { space: 'oklch', channels: fromLinearSrgb( target.toSrgb ? multiply(target.toSrgb, linear) : linear, ), } } return null} /** * Reads a CSS color: hex with 3, 4, 6 or 8 digits, `#` optional; the 148 * named colors and `transparent`; `rgb()`, `hsl()`, `hwb()`, `lab()`, * `lch()`, `oklab()`, `oklch()` and `color()` in any of CSS Color 4's RGB * and XYZ spaces, plus `hsb()` or `hsv()`; modern or comma syntax, with or * without alpha. A color that can fall outside sRGB is kept as OKLCH. * Anything else, `var()` and `currentColor` included, is `null`. */export function parseColor( input: string | null | undefined,): ColorPickerColor | null { if (typeof input !== 'string') return null const text = input.trim().toLowerCase() if (!text) return null if (text === 'transparent') { return { space: 'rgb', channels: [0, 0, 0], alpha: 0 } } const hex = HEX_PATTERN.exec(namedColor(text) ?? text) if (hex) { let digits = hex[1] if (digits.length <= 4) { digits = [...digits].map((digit) => digit + digit).join('') } const byte = (index: number) => parseInt(digits.slice(index, index + 2), 16) return { space: 'rgb', channels: [byte(0), byte(2), byte(4)], alpha: digits.length === 8 ? byte(6) / 255 : 1, } } const call = FUNCTION_PATTERN.exec(text) if (!call) return null const name = call[1].replace(/a$/, '') const [main, slash, ...rest] = call[2].split('/') if (rest.length > 0) return null const parts = main.split(/[\s,]+/).filter(Boolean) /* color() names its space first, and takes alpha only after a slash. */ const count = name === 'color' ? 4 : 3 /* Alpha follows a slash, or is the fourth value of the comma syntax. */ const alphaToken = slash?.trim() ?? (name === 'color' ? undefined : parts[3]) if ( parts.length !== count && !(name !== 'color' && parts.length === 4 && slash === undefined) ) { return null } const alpha = alphaToken === undefined ? 1 : readNumber(alphaToken, 1) const read = readChannels(name, parts.slice(0, count)) if (alpha === null || !read) return null const channels = read.channels if (channels.some((channel) => !Number.isFinite(channel))) return null if (read.space !== 'rgb') { const hueIndex = read.space === 'oklch' ? 2 : 0 channels[hueIndex] = wrapHue(channels[hueIndex]) } return { space: read.space, channels, alpha: clamp(alpha, 0, 1) }} const CSS_WIDE = /^(inherit|initial|unset|revert|revert-layer|currentcolor)$/ /* Whatever else the browser paints (color-mix(), relative colors, light-dark(), system colors), resolved by its computed style, which serializes as a function parseColor reads. Two parents of different colors expose anything that inherits (var() with no value, a CSS-wide keyword); a canvas would have read those as black. Only typing reaches this, never a render. */export function parseWithBrowser(text: string): ColorPickerColor | null { if ( typeof document === 'undefined' || CSS_WIDE.test(text.toLowerCase()) || !CSS.supports?.('color', text) ) { return null } const parent = document.createElement('div') const probe = document.createElement('div') parent.style.display = 'none' probe.style.color = text parent.append(probe) document.body.append(parent) parent.style.color = 'rgb(1, 2, 3)' const first = getComputedStyle(probe).color parent.style.color = 'rgb(4, 5, 6)' const second = getComputedStyle(probe).color parent.remove() return first === second ? parseColor(first) : null} /** * Writes a color in a format. HEX gains a fourth byte and the others a * `/ alpha` only when the color is translucent; OKLCH keeps channels outside * sRGB, every other format maps the color into sRGB the way CSS does. */export function formatColor( color: ColorPickerColor, format: ColorPickerFormat,): string { const alpha = clamp(color.alpha, 0, 1) const opacityText = fixed(alpha) const tail = opacityText !== '1' ? ` / ${opacityText}` : '' if (format === 'hex' || format === 'rgb') { const rgb = toRgb(color).map((channel) => Math.round(clamp(channel, 0, 255)), ) if (format === 'rgb') return `rgb(${rgb.join(' ')}${tail})` const opacity = Math.round(alpha * 255) const bytes = opacity < 255 ? [...rgb, opacity] : rgb return `#${bytes.map((byte) => byte.toString(16).padStart(2, '0')).join('')}` } if (format === 'oklch') { const [l, c, h] = toSpace(color, 'oklch') /* Chroma is never below 0, and a hue that rounds to 360 is 0. */ const hue = fixed(wrapHue(Number(fixed(h)))) return `oklch(${fixed(l)}% ${fixed(Math.max(0, c))} ${hue}${tail})` } const [h, s, third] = toSpace(color, format === 'hsl' ? 'hsl' : 'hsv') return `${format}(${fixed(wrapHue(Number(fixed(h))))} ${fixed(s)}% ${fixed(third)}%${tail})`} /* What CSS paints: OKLCH as itself, so a wide-gamut screen shows it. */export const toCss = (color: ColorPickerColor) => formatColor(color, color.space === 'oklch' ? 'oklch' : 'rgb') const DEFAULT_SPACE: Record<ColorPickerChannel, ColorPickerColorSpace> = { hue: 'hsv', saturation: 'hsv', brightness: 'hsv', lightness: 'hsl', chroma: 'oklch', red: 'rgb', green: 'rgb', blue: 'rgb', alpha: 'rgb',} /* A space that has no such channel falls back to the channel's own. */export const resolveSpace = ( channel: ColorPickerChannel, space: ColorPickerColorSpace | undefined,) => channel !== 'alpha' && space && SPACE_CHANNELS[space].includes(channel) ? space : DEFAULT_SPACE[channel] /** * Get the range and step for a given channel and space. */export function channelRange( space: ColorPickerColorSpace, channel: ColorPickerChannel,) { if (channel === 'alpha') return { max: 1, step: 0.01 } if (channel === 'hue') return { max: 360, step: 1 } if (channel === 'chroma') return { max: 0.4, step: 0.004 } return { max: space === 'rgb' ? 255 : 100, step: 1 }} export function readChannel( color: ColorPickerColor, space: ColorPickerColorSpace, channel: ColorPickerChannel,) { if (channel === 'alpha') return color.alpha return toSpace(color, space)[SPACE_CHANNELS[space].indexOf(channel)]} export function withChannel( color: ColorPickerColor, space: ColorPickerColorSpace, channel: ColorPickerChannel, value: number,): ColorPickerColor { if (channel === 'alpha') return { ...color, alpha: clamp(value, 0, 1) } const channels = [...toSpace(color, space)] as Triple channels[SPACE_CHANNELS[space].indexOf(channel)] = value return { space, channels, alpha: color.alpha }} /* The colors a track runs through: the full spectrum for hue, so a gray still shows where it would go, and sampled stops elsewhere, since OKLCH and HSL lightness do not run straight in sRGB. */export function trackStops( color: ColorPickerColor, space: ColorPickerColorSpace, channel: ColorPickerChannel,) { const opaque = { ...color, alpha: 1 } if (channel === 'alpha') return ['transparent', toCss(opaque)] let base = opaque if (channel === 'hue') { base = space === 'oklch' ? withChannel( opaque, 'oklch', 'chroma', Math.max(readChannel(opaque, 'oklch', 'chroma'), 0.12), ) : { space: 'hsv', channels: [0, 100, 100], alpha: 1 } } const count = channel === 'hue' || space === 'oklch' ? 13 : space === 'hsl' && channel === 'lightness' ? 3 : 2 const { max } = channelRange(space, channel) const target = channel === 'hue' && space !== 'oklch' ? 'hsv' : space return Array.from({ length: count }, (_, index) => formatColor( withChannel(base, target, channel, (max * index) / (count - 1)), 'rgb', ), )} type FieldChannel = ColorPickerChannel | 'hex' export const FORMAT_FIELDS: Record< ColorPickerFormat, { space: ColorPickerColorSpace; channels: FieldChannel[] }> = { hex: { space: 'rgb', channels: ['hex'] }, rgb: { space: 'rgb', channels: ['red', 'green', 'blue'] }, hsl: { space: 'hsl', channels: ['hue', 'saturation', 'lightness'] }, hsb: { space: 'hsv', channels: ['hue', 'saturation', 'brightness'] }, oklch: { space: 'oklch', channels: ['lightness', 'chroma', 'hue'] },} export function channelText( color: ColorPickerColor, space: ColorPickerColorSpace, channel: FieldChannel,) { if (channel === 'hex') { return formatColor({ ...color, alpha: 1 }, 'hex') .slice(1) .toUpperCase() } if (channel === 'alpha') return `${Math.round(color.alpha * 100)}%` const value = readChannel(color, space, channel) if (channel === 'chroma') return fixed(value, 3) return space === 'oklch' ? fixed(value, 1) : String(Math.round(value))} const FIELD_NUMBER = /^([+-]?(?:\d+(?:[.,]\d*)?|[.,]\d+))\s*(%|°|deg|grad|rad|turn)?$/ /* A typed channel. Hex keeps the current opacity unless it carries its own. A number takes a comma decimal; % is a share of the channel's range, as in CSS (50% red is 127.5, 50% chroma 0.2), and a hue takes an angle unit and wraps, so -30 is 330. Anything else is rejected. */export function readChannelText( text: string, color: ColorPickerColor, space: ColorPickerColorSpace, channel: FieldChannel,): ColorPickerColor | null { if (channel === 'hex') { const digits = text.trim().replace(/^#/, '') const parsed = /^[\da-f]+$/i.test(digits) ? parseColor(digits) : null if (!parsed) return null return digits.length === 4 || digits.length === 8 ? parsed : { ...parsed, alpha: color.alpha } } const match = FIELD_NUMBER.exec(text.trim().toLowerCase()) if (!match) return null const value = Number(match[1].replace(',', '.')) const unit = match[2] if (!Number.isFinite(value)) return null if (channel === 'hue') { if (unit === '%') return null const degrees = unit === 'rad' ? (value * 180) / Math.PI : unit === 'grad' ? value * 0.9 : unit === 'turn' ? value * 360 : value return withChannel(color, space, channel, wrapHue(degrees)) } if (unit && unit !== '%') return null if (channel === 'alpha') return { ...color, alpha: clamp(value / 100, 0, 1) } const { max } = channelRange(space, channel) const scaled = unit === '%' ? (value * max) / 100 : value return withChannel(color, space, channel, clamp(scaled, 0, max))} export const CHECKER = 'repeating-conic-gradient(var(--color-muted) 0 25%, var(--color-background) 0 50%) 50% / 8px 8px'export const EMPTY_COLOR: ColorPickerColor = { space: 'hsv', channels: [0, 0, 0], alpha: 1,}src/components/ui/color-picker/color-picker-content.astro---import type { HTMLAttributes } from "astro/types"import { cn } from "cn"import { PopoverContent } from "@/components/ui/popover"import ColorPickerPanel from "./color-picker-panel.astro"import type { ColorPickerContentProps } from "./types.ts"type Props = HTMLAttributes<"div"> & ColorPickerContentPropsconst { class: className, align = "start", ...props } = Astro.props--- <PopoverContent data-color-picker-content align={align} aria-label="Choose a color" class={cn("w-80 max-w-[calc(100vw-1.5rem)] p-3", className)} {...props}> <slot> <ColorPickerPanel /> </slot></PopoverContent>src/components/ui/color-picker/color-picker-fields.astro---import type { HTMLAttributes } from "astro/types"import ChevronDownIcon from "@lucide/astro/icons/chevron-down"import { cn } from "cn"import { InputGroup } from "@/components/ui/input-group"import ColorPickerChannelInput from "./color-picker-channel-input.astro"import { COLOR_PICKER_FORMATS, FORMAT_FIELDS, FORMAT_LABELS,} from "./color-picker-color.ts"import type { ColorPickerFieldsProps } from "./types.ts" type Props = HTMLAttributes<"div"> & ColorPickerFieldsProps const { class: className, defaultFormat = "hex", formats = COLOR_PICKER_FORMATS, ...props} = Astro.props const available = formats.length ? [...new Set(formats)] : [defaultFormat]const selected = available.includes(defaultFormat) ? defaultFormat : available[0]!--- <div data-slot="color-picker-fields" data-format={selected} class={cn("min-w-0", className)} {...props}> <InputGroup dir="ltr"> {available.length > 1 && ( <div data-slot="color-picker-format" class="relative flex shrink-0 self-stretch rounded-s-[inherit] border-e border-input"> <select data-slot="color-picker-format-trigger" data-color-picker-format aria-label="Color format" class="h-full w-full cursor-pointer appearance-none rounded-s-[inherit] bg-transparent py-0 ps-2 pe-5 text-xs font-medium text-foreground outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50" > {available.map((format) => ( <option value={format} selected={format === selected}> {FORMAT_LABELS[format]} </option> ))} </select> <ChevronDownIcon data-slot="color-picker-format-icon" class="pointer-events-none absolute end-1 top-1/2 size-3 -translate-y-1/2 text-muted-foreground" aria-hidden="true" /> </div> )} {available.map((format) => ( <div data-slot="color-picker-channels" data-color-picker-channels data-format={format} class="flex min-w-0 flex-1 self-stretch [&>input]:px-1.5 [&>input]:text-xs [&>input[data-channel=alpha]]:w-[calc(4.8ch+0.75rem)] [&>input[data-channel=alpha]]:flex-none" hidden={format !== selected} > {FORMAT_FIELDS[format].channels.map((channel) => ( <ColorPickerChannelInput channel={channel} colorSpace={FORMAT_FIELDS[format].space} /> ))} <ColorPickerChannelInput channel="alpha" hidden /> </div> ))} </InputGroup></div>src/components/ui/color-picker/color-picker-input.astro---import type { HTMLAttributes } from "astro/types"import { cn } from "cn"import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput,} from "@/components/ui/input-group"import ColorPickerSwatch from "./color-picker-swatch.astro"type Props = Omit<HTMLAttributes<"input">, "value" | "type" | "name">const { class: className, ...props } = Astro.props--- <div data-slot="color-picker-input" class={cn("w-full", className)}> <InputGroup> <InputGroupAddon align="inline-start"> <InputGroupButton data-slot="popover-trigger" data-color-picker-trigger size="icon-xs" aria-label="Open color picker" > <ColorPickerSwatch /> </InputGroupButton> </InputGroupAddon> <InputGroupInput data-slot="color-picker-text" type="text" autocomplete="off" autocapitalize="none" spellcheck="false" aria-keyshortcuts="Alt+ArrowDown" {...props} /> </InputGroup></div>src/components/ui/color-picker/color-picker-panel.astro---import type { HTMLAttributes } from "astro/types"import { cn } from "cn"import ColorPickerArea from "./color-picker-area.astro"import ColorPickerSlider from "./color-picker-slider.astro"import ColorPickerFields from "./color-picker-fields.astro"type Props = HTMLAttributes<"div">const { class: className, ...props } = Astro.props--- <div data-slot="color-picker-panel" role="group" aria-label="Color controls" class={cn("flex w-full min-w-0 flex-col gap-3", className)} {...props}> <slot> <ColorPickerArea /> <ColorPickerSlider channel="hue" /> <ColorPickerSlider channel="alpha" /> <ColorPickerFields /> </slot></div>src/components/ui/color-picker/color-picker-slider.astro---import type { HTMLAttributes } from "astro/types"import { cn } from "cn"import { channelRange, resolveSpace } from "./color-picker-color.ts"import type { ColorPickerSliderProps } from "./types.ts"type Props = Omit< HTMLAttributes<"input">, "type" | "min" | "max" | "step" | "value"> & ColorPickerSliderPropsconst { class: className, channel = "hue", colorSpace, ...props } = Astro.propsconst { max, step } = channelRange(resolveSpace(channel, colorSpace), channel)--- <input data-slot="color-picker-slider" data-channel={channel} data-color-space={colorSpace} type="range" min="0" max={max} step={step} value="0" aria-label={channel === "alpha" ? "Opacity" : channel} hidden={channel === "alpha"} class={cn("h-3 w-full cursor-pointer appearance-none rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 forced-color-adjust-none [&::-moz-range-thumb]:size-4 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:border-2 [&::-moz-range-thumb]:border-white [&::-moz-range-thumb]:bg-white [&::-moz-range-thumb]:shadow-md [&::-moz-range-track]:h-3 [&::-moz-range-track]:bg-transparent [&::-webkit-slider-runnable-track]:h-3 [&::-webkit-slider-runnable-track]:bg-transparent [&::-webkit-slider-thumb]:-mt-0.5 [&::-webkit-slider-thumb]:size-4 [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:border-2 [&::-webkit-slider-thumb]:border-white [&::-webkit-slider-thumb]:bg-white [&::-webkit-slider-thumb]:shadow-md", className)} {...props}/>src/components/ui/color-picker/color-picker-swatch-item.astro---import type { HTMLAttributes } from "astro/types"import { cn } from "cn"import CheckIcon from "@lucide/astro/icons/check"import { CHECKER, parseColor, toCss } from "./color-picker-color.ts"import type { ColorPickerSwatchItemProps } from "./types.ts"type Props = Omit<HTMLAttributes<"button">, "value"> & ColorPickerSwatchItemPropsconst { class: className, value, label = value, disabled = false, style, ...props} = Astro.propsconst color = parseColor(value)const css = color ? toCss(color) : "transparent"const background = `linear-gradient(${css}, ${css}), ${CHECKER}`--- <button data-slot="color-picker-swatch-item" data-value={value} type="button" aria-label={label} aria-pressed="false" disabled={disabled || !color} class={cn("relative flex size-8 shrink-0 items-center justify-center rounded-md border border-foreground/15 outline-none aria-pressed:ring-2 aria-pressed:ring-ring aria-pressed:ring-offset-2 aria-pressed:ring-offset-background focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-50 forced-color-adjust-none", className)} style={ typeof style === "string" ? `background: ${background}; ${style}` : { background, ...style } } {...props}> <span data-slot="color-picker-swatch-check" aria-hidden="true" hidden> <CheckIcon class="size-4 text-white mix-blend-color-dodge" /> </span></button>src/components/ui/color-picker/color-picker-swatch.astro---import type { HTMLAttributes } from "astro/types"import { cn } from "cn"type Props = HTMLAttributes<"span">const { class: className, ...props } = Astro.props--- <span data-slot="color-picker-swatch" aria-hidden="true" class={cn("inline-block size-5 shrink-0 rounded-sm border border-foreground/15 forced-color-adjust-none", className)} {...props}></span>src/components/ui/color-picker/color-picker-swatches.astro---import type { HTMLAttributes } from "astro/types"import { cn } from "cn"import ColorPickerSwatchItem from "./color-picker-swatch-item.astro"import type { ColorPickerSwatchesProps } from "./types.ts"type Props = HTMLAttributes<"div"> & ColorPickerSwatchesPropsconst { class: className, colors = [], ...props } = Astro.props--- <div data-slot="color-picker-swatches" role="group" aria-label="Color swatches" class={cn("flex flex-wrap gap-2", className)} {...props}> <slot> {colors.map((value) => ( <ColorPickerSwatchItem value={value} /> ))} </slot></div>src/components/ui/color-picker/color-picker-trigger.astro---import type { ComponentProps } from "astro/types"import { cn } from "cn"import ChevronDownIcon from "@lucide/astro/icons/chevron-down"import { Button } from "@/components/ui/button"import ColorPickerSwatch from "./color-picker-swatch.astro"import ColorPickerValue from "./color-picker-value.astro"type Props = ComponentProps<typeof Button>const { class: className, variant = "outline", ...props } = Astro.props--- <Button data-slot="popover-trigger" data-color-picker-trigger variant={variant} class={cn("w-full min-w-0 justify-start font-normal", className)} {...props}> <slot> <ColorPickerSwatch /> <ColorPickerValue /> <ChevronDownIcon data-icon="inline-end" /> </slot></Button>src/components/ui/color-picker/color-picker-value.astro---import type { HTMLAttributes } from "astro/types"import { cn } from "cn"type Props = HTMLAttributes<"span">const { class: className, ...props } = Astro.props--- <span data-slot="color-picker-value" class={cn("min-w-0 flex-1 truncate text-start font-mono text-sm", className)} {...props}></span>src/components/ui/color-picker/color-picker.astro---import type { HTMLAttributes } from "astro/types"import { cn } from "cn"import ColorPickerTrigger from "./color-picker-trigger.astro"import ColorPickerContent from "./color-picker-content.astro"import { EMPTY_COLOR, formatColor, parseColor } from "./color-picker-color.ts"import type { ColorPickerProps } from "./types.ts" type Props = HTMLAttributes<"div"> & ColorPickerPropsconst { class: className, id = `color-${crypto.randomUUID()}`, defaultValue = "#000000", format = "hex", alpha = false, disabled = false, readOnly = false, label = "Choose a color", name, form, ...props} = Astro.propsconst parsed = parseColor(defaultValue) ?? EMPTY_COLORconst color = alpha ? parsed : { ...parsed, alpha: 1 }--- <div data-slot="color-picker" id={id} data-default-value={formatColor( color, color.space === "oklch" ? "oklch" : "rgb", )} data-format={format} data-alpha={alpha} data-disabled={disabled} data-readonly={readOnly} data-label={label} class={cn("inline-flex min-w-0 flex-col", className)} {...props}> <slot> <ColorPickerTrigger /> <ColorPickerContent /> </slot> <input data-slot="color-picker-form-input" type="hidden" name={name} form={form} value={formatColor(color, format)} disabled={disabled} /> <span data-slot="color-picker-status" role="status" class="sr-only"></span></div> <script> import { create, type ColorPickerController } from "./color-picker.ts" const controllers: ColorPickerController[] = [] const initialize = () => controllers.push(...create()) initialize() document.addEventListener("astro:page-load", initialize) document.addEventListener("astro:before-swap", () => { for (const controller of controllers) controller.destroy() controllers.length = 0 })</script>src/components/ui/color-picker/color-picker.tsimport { clearRootBinding, emit, ensureId, getOwnedElements, getPart, getParts, getRootBinding, getRoots, hasRootBinding, observeFormReset, on, onRoot, setRootBinding,} from '@data-slot/core'import { createPopover, type PopoverController } from '@data-slot/popover' import { CHECKER, EMPTY_COLOR, channelRange, channelText, clamp, fixed, formatColor, parseColor, parseWithBrowser, readChannel, readChannelText, resolveSpace, toCss, toSpace, trackStops, withChannel, wrapHue,} from './color-picker-color.ts' import type { ColorPickerChangeDetail, ColorPickerChannel, ColorPickerColor, ColorPickerColorSpace, ColorPickerFormat,} from './types.ts' const ROOT_SLOT = 'color-picker' /** Browser controller for one composed picker. */export interface ColorPickerController { /** Remove listeners and restore the popup and root ID. */ destroy(): void /** Current value in the root's output format. */ getValue(): string /** Set a CSS color. Returns false for invalid text. Silent updates prevent feedback loops. */ setColor(value: string, options?: { silent?: boolean }): boolean} /** Bind each unbound picker in the scope. */export function create(scope: ParentNode = document) { return getRoots<HTMLElement>(scope, ROOT_SLOT) .filter((root) => !hasRootBinding(root, ROOT_SLOT)) .map(createColorPicker)} /** Parts are optional. Capture them before the popover moves its content. */export function createColorPicker(root: HTMLElement): ColorPickerController { const existing = getRootBinding<ColorPickerController>(root, ROOT_SLOT) if (existing) return existing const parts = <T extends HTMLElement = HTMLElement>(slot: string) => getParts<T>(root, slot) const formInput = getPart<HTMLInputElement>(root, 'color-picker-form-input') const texts = parts<HTMLInputElement>('color-picker-text') const channels = parts<HTMLInputElement>('color-picker-channel-input') const sliders = parts<HTMLInputElement>('color-picker-slider') const areas = parts('color-picker-area') const thumbs = areas.map((area) => area.querySelector<HTMLElement>( '[data-slot="color-picker-area-thumb"]', ), ) const swatches = parts('color-picker-swatch') const items = parts<HTMLButtonElement>('color-picker-swatch-item') const values = parts('color-picker-value') const fields = parts('color-picker-fields') const status = getPart(root, 'color-picker-status') const trigger = getPart<HTMLButtonElement>(root, 'popover-trigger') const content = getPart<HTMLElement>(root, 'popover-content') const controls = getOwnedElements< HTMLInputElement | HTMLButtonElement | HTMLSelectElement >(root, root, 'input, button, select') const ownDisabled = new Map( controls.map((control) => [control, control.disabled]), ) const ownReadOnly = new Map( [...texts, ...channels].map((input) => [input, input.readOnly]), ) const output = (root.dataset.format ?? 'hex') as ColorPickerFormat const alpha = root.dataset.alpha === 'true' const normalize = (color: ColorPickerColor): ColorPickerColor => alpha ? color : { ...color, alpha: 1 } const initial = normalize( parseColor(root.dataset.defaultValue) ?? EMPTY_COLOR, ) let color = initial let value = formatColor(color, output) let destroyed = false let interaction: string | null = null let popover: PopoverController | undefined const cleanups: Array<() => void> = [] const disabled = () => root.dataset.disabled === 'true' const readOnly = () => root.dataset.readonly === 'true' const editable = () => !destroyed && !disabled() && !readOnly() const fieldId = ensureId(root, 'color-picker') const focusTarget = texts[0] ?? trigger const oldTargetId = focusTarget?.id // Labels can target the root ID in Astro markup. Move it to the actual control. // This runs after the docs preview has applied its unique ID prefix. if (focusTarget) { root.id = `${fieldId}-root` focusTarget.id = fieldId if ( !focusTarget.getAttribute('aria-label') && !focusTarget.getAttribute('aria-labelledby') && !focusTarget.labels?.length ) { focusTarget.setAttribute( 'aria-label', root.dataset.label ?? 'Choose a color', ) } } if (content) content.setAttribute( 'aria-label', root.dataset.label ?? 'Choose a color', ) const formats = new Map( fields.map((field) => [field, field.dataset.format ?? 'hex']), ) const channelOf = (input: HTMLElement) => input.dataset.channel as ColorPickerChannel const spaceOf = (input: HTMLElement) => resolveSpace( channelOf(input), input.dataset.colorSpace as ColorPickerColorSpace | undefined, ) const textFor = (input: HTMLInputElement) => channelText( color, spaceOf(input), input.dataset.channel as ColorPickerChannel | 'hex', ) const detail = (): ColorPickerChangeDetail => ({ id: fieldId, name: formInput?.name ?? '', value, hex: formatColor(color, 'hex'), oklch: formatColor(color, 'oklch'), hsl: [...toSpace(color, 'hsl')], }) const announce = () => { if (status) status.textContent = `Selected ${value}` } const paint = () => { if (destroyed) return value = formatColor(color, output) root.dataset.value = value if (formInput) formInput.value = value for (const input of texts) input.value = value for (const node of values) { node.textContent = value node.title = value } const css = toCss(color) for (const node of swatches) node.style.background = `linear-gradient(${css}, ${css}), ${CHECKER}` const [h, s, v] = toSpace(color, 'hsv') areas.forEach((area, index) => { area.style.background = `linear-gradient(to top, #000, transparent), linear-gradient(to right, #fff, transparent), hsl(${fixed(h)} 100% 50%)` area.setAttribute( 'aria-description', `Saturation ${Math.round(s)}%, brightness ${Math.round(v)}%`, ) area.setAttribute('aria-disabled', String(disabled())) area.tabIndex = disabled() ? -1 : 0 const thumb = thumbs[index] if (thumb) { thumb.style.left = `${s}%` thumb.style.top = `${100 - v}%` thumb.style.backgroundColor = css } }) for (const slider of sliders) { const channel = channelOf(slider), space = spaceOf(slider) slider.value = String(readChannel(color, space, channel)) slider.style.background = `linear-gradient(to right, ${trackStops(color, space, channel).join(', ')}), ${CHECKER}` if (channel === 'alpha') slider.hidden = !alpha slider.setAttribute( 'aria-valuetext', channel === 'alpha' ? `${Math.round(color.alpha * 100)}%` : fixed(readChannel(color, space, channel)), ) } for (const input of channels) { input.value = textFor(input) if (input.dataset.channel === 'alpha') input.hidden = !alpha if (input.dataset.channel !== 'hex') { const channel = channelOf(input), space = spaceOf(input) input.setAttribute('role', 'spinbutton') input.setAttribute('aria-valuemin', '0') input.setAttribute( 'aria-valuemax', String( channel === 'alpha' ? 100 : channelRange(space, channel).max, ), ) input.setAttribute( 'aria-valuenow', String( channel === 'alpha' ? color.alpha * 100 : readChannel(color, space, channel), ), ) input.setAttribute('aria-valuetext', input.value) } } for (const item of items) { const parsed = parseColor(item.dataset.value) const selected = !!parsed && formatColor(normalize(parsed), 'hex') === formatColor(color, 'hex') item.setAttribute('aria-pressed', String(selected)) const check = item.querySelector<HTMLElement>( '[data-slot="color-picker-swatch-check"]', ) check?.toggleAttribute('hidden', !selected) } for (const control of controls) { control.disabled = !!ownDisabled.get(control) || disabled() || (readOnly() && !texts.includes(control as HTMLInputElement) && control !== trigger && control !== formInput) } for (const input of [...texts, ...channels]) input.readOnly = readOnly() || !!ownReadOnly.get(input) } const set = (next: ColorPickerColor, silent = false) => { if (destroyed) return const previous = value color = normalize(next) paint() if (silent || previous === value) return announce() formInput?.dispatchEvent(new Event('input', { bubbles: true })) emit(root, 'color-picker:change', detail()) } const finish = () => { if (interaction !== null && interaction !== value) { formInput?.dispatchEvent(new Event('change', { bubbles: true })) emit(root, 'color-picker:commit', detail()) } interaction = null } const change = (next: ColorPickerColor) => { interaction = value set(next) finish() } const listen = ( target: EventTarget, type: string, handler: (event: Event) => void, ) => cleanups.push(on(target, type, handler)) const restoreField = (input: HTMLInputElement) => { input.value = texts.includes(input) ? value : textFor(input) } for (const input of [...texts, ...channels]) { const read = () => { if (!editable() || input.disabled || input.readOnly) { restoreField(input) return } if ( input.value === (texts.includes(input) ? value : textFor(input)) ) return const next = texts.includes(input) ? (parseColor(input.value) ?? parseWithBrowser(input.value.trim())) : readChannelText( input.value, color, spaceOf(input), input.dataset.channel as ColorPickerChannel | 'hex', ) if (next) change(next) else restoreField(input) } listen(input, 'blur', read) listen(input, 'keydown', (event) => { const key = event as KeyboardEvent if (key.defaultPrevented) return if (key.key === 'Escape') { if ( input.value !== (texts.includes(input) ? value : textFor(input)) ) { key.preventDefault() key.stopPropagation() restoreField(input) } } else if (key.key === 'Enter') read() else if ( key.altKey && key.key === 'ArrowDown' && texts.includes(input) ) { key.preventDefault() read() if (!disabled()) popover?.open() } else if ( channels.includes(input) && input.dataset.channel !== 'hex' && editable() && !input.disabled && !input.readOnly ) { const step = ( { ArrowUp: 1, ArrowDown: -1, PageUp: 10, PageDown: -10, } as Record<string, number> )[key.key] if (!step) return key.preventDefault() const channel = channelOf(input), space = spaceOf(input) const from = readChannelText(input.value, color, space, channel) if (!from) return const unit = channel === 'alpha' ? 0.01 : channel === 'chroma' ? 0.001 : 1 const next = readChannel(from, space, channel) + step * unit * (key.shiftKey ? 10 : 1) change( withChannel( from, space, channel, channel === 'hue' ? wrapHue(next) : clamp(next, 0, channelRange(space, channel).max), ), ) } }) } for (const field of fields) { const menu = field.querySelector<HTMLSelectElement>( '[data-color-picker-format]', ) if (!menu) continue const show = () => { field.dataset.format = menu.value for (const group of field.querySelectorAll<HTMLElement>( '[data-color-picker-channels]', )) group.hidden = group.dataset.format !== menu.value } listen(menu, 'change', show) } for (const slider of sliders) { listen(slider, 'input', () => { if (!editable() || slider.disabled) { paint() return } interaction ??= value const number = Number(slider.value) if (Number.isFinite(number)) set( withChannel( color, spaceOf(slider), channelOf(slider), number, ), ) }) listen(slider, 'change', finish) } for (const area of areas) { let pointer: number | null = null const apply = (event: PointerEvent) => { const rect = area.getBoundingClientRect() if (!rect.width || !rect.height) return const hue = toSpace(color, 'hsv')[0] set({ space: 'hsv', channels: [ hue, clamp( ((event.clientX - rect.left) / rect.width) * 100, 0, 100, ), clamp( 100 - ((event.clientY - rect.top) / rect.height) * 100, 0, 100, ), ], alpha: color.alpha, }) } const release = () => { if (pointer === null) return const id = pointer pointer = null if (area.hasPointerCapture(id)) area.releasePointerCapture(id) finish() } listen(area, 'pointerdown', (event) => { const e = event as PointerEvent if ( !editable() || e.defaultPrevented || e.button !== 0 || !e.isPrimary ) return e.preventDefault() area.focus() interaction = value pointer = e.pointerId area.setPointerCapture(pointer) apply(e) }) listen(area, 'pointermove', (event) => { const e = event as PointerEvent if (editable() && e.pointerId === pointer) apply(e) }) for (const type of ['pointerup', 'pointercancel', 'lostpointercapture']) listen(area, type, (event) => { if ((event as PointerEvent).pointerId === pointer) release() }) cleanups.push(() => { interaction = null release() }) listen(area, 'keydown', (event) => { const e = event as KeyboardEvent if (!editable() || e.defaultPrevented) return const [h, oldS, oldV] = toSpace(color, 'hsv') let s = oldS, v = oldV const step = e.shiftKey ? 10 : 1 if (e.key === 'ArrowLeft') s -= step else if (e.key === 'ArrowRight') s += step else if (e.key === 'ArrowUp') v += step else if (e.key === 'ArrowDown') v -= step else if (e.key === 'Home') s = 0 else if (e.key === 'End') s = 100 else if (e.key === 'PageUp') v = 100 else if (e.key === 'PageDown') v = 0 else return e.preventDefault() change({ space: 'hsv', channels: [h, clamp(s, 0, 100), clamp(v, 0, 100)], alpha: color.alpha, }) }) } for (const item of items) listen(item, 'click', (event) => { if (!editable() || item.disabled || event.defaultPrevented) return const next = parseColor(item.dataset.value) if (next) change(next) }) for (const group of parts('color-picker-swatches')) { const buttons = items.filter((item) => group.contains(item)) listen(group, 'keydown', (event) => { const e = event as KeyboardEvent const available = buttons.filter((button) => !button.disabled) const index = available.indexOf(e.target as HTMLButtonElement) if (index < 0 || e.defaultPrevented) return const rtl = getComputedStyle(group).direction === 'rtl' let target: HTMLButtonElement | undefined if (e.key === 'Home') target = available[0] else if (e.key === 'End') target = available.at(-1) else if ( e.key === 'ArrowDown' || e.key === (rtl ? 'ArrowLeft' : 'ArrowRight') ) target = available[index + 1] else if ( e.key === 'ArrowUp' || e.key === (rtl ? 'ArrowRight' : 'ArrowLeft') ) target = available[index - 1] else return e.preventDefault() target?.focus() }) } const reset = observeFormReset({ root, getForm: () => formInput?.form ?? null, onReset: () => { interaction = null for (const [field, format] of formats) { field.dataset.format = format const menu = field.querySelector<HTMLSelectElement>( '[data-color-picker-format]', ) if (menu) menu.value = format for (const group of field.querySelectorAll<HTMLElement>( '[data-color-picker-channels]', )) group.hidden = group.dataset.format !== format } set(initial, true) if (status) status.textContent = '' }, }) cleanups.push(() => reset.destroy()) paint() // Reuse the data-slot popup behavior without adding another root wrapper. if (trigger && content) popover = createPopover(root) const controller: ColorPickerController = { getValue: () => value, setColor(text, options) { const next = parseColor(text) if (!next || destroyed) return false if (options?.silent) set(next, true) else change(next) return true }, destroy() { if (destroyed) return destroyed = true popover?.destroy() for (const cleanup of cleanups) cleanup() if (focusTarget) { focusTarget.id = oldTargetId ?? '' root.id = fieldId } clearRootBinding(root, ROOT_SLOT, controller) }, } cleanups.push( onRoot(root, 'color-picker:set', (event) => { const command = (event as CustomEvent<{ value?: unknown }>).detail if (typeof command?.value === 'string') controller.setColor(command.value, { silent: true }) }), ) return setRootBinding(root, ROOT_SLOT, controller)}src/components/ui/color-picker/index.tsexport { default as ColorPicker } from './color-picker.astro'export { default as ColorPickerTrigger } from './color-picker-trigger.astro'export { default as ColorPickerInput } from './color-picker-input.astro'export { default as ColorPickerContent } from './color-picker-content.astro'export { default as ColorPickerPanel } from './color-picker-panel.astro'export { default as ColorPickerArea } from './color-picker-area.astro'export { default as ColorPickerSlider } from './color-picker-slider.astro'export { default as ColorPickerChannelInput } from './color-picker-channel-input.astro'export { default as ColorPickerFields } from './color-picker-fields.astro'export { default as ColorPickerSwatch } from './color-picker-swatch.astro'export { default as ColorPickerValue } from './color-picker-value.astro'export { default as ColorPickerSwatches } from './color-picker-swatches.astro'export { default as ColorPickerSwatchItem } from './color-picker-swatch-item.astro' export { create, createColorPicker } from './color-picker.ts'export type { ColorPickerController } from './color-picker.ts'export { parseColor, formatColor, isColorInSrgb } from './color-picker-color.ts'export type * from './types.ts'src/components/ui/color-picker/types.tsimport type { PopoverContentProps } from '@/components/ui/popover/types.ts' /** The output color format. */export type ColorPickerFormat = 'hex' | 'rgb' | 'hsl' | 'hsb' | 'oklch' /** Where channels live. HSB is `hsv` here, after the math. */export type ColorPickerColorSpace = 'rgb' | 'hsl' | 'hsv' | 'oklch' /** A channel that a slider can change. */export type ColorPickerChannel = | 'hue' | 'saturation' | 'brightness' | 'lightness' | 'chroma' | 'red' | 'green' | 'blue' | 'alpha' /** * A parsed color. Channels stay in the space they were given or edited in, * so the hue of a gray and an OKLCH color outside sRGB survive a round trip. * rgb runs 0 to 255; hsl and hsv take hue 0 to 360 and the rest 0 to 100; * oklch takes lightness 0 to 100, chroma 0 to 0.4 and hue 0 to 360. Alpha is * 0 to 1. */export type ColorPickerColor = { space: ColorPickerColorSpace channels: [number, number, number] alpha: number} /** Shared state for composed color picker parts. HTML attributes pass through. */export interface ColorPickerProps { /** Initial CSS color. @default "#000000" */ defaultValue?: string /** Output format for events and form submission. @default "hex" */ format?: ColorPickerFormat /** Permit transparency. @default false */ alpha?: boolean /** Disable all controls. @default false */ disabled?: boolean /** Show the color without permitting changes. @default false */ readOnly?: boolean /** Accessible name for the picker. @default "Choose a color" */ label?: string /** Name of the hidden form field. */ name?: string /** ID of an external form. */ form?: string} /** Placement options for the popup. */export type ColorPickerContentProps = PopoverContentProps /** Options for a color channel slider. */export interface ColorPickerSliderProps { /** Channel to change. @default "hue" */ channel?: ColorPickerChannel /** Color space for the channel. Defaults to the channel's native space. */ colorSpace?: ColorPickerColorSpace} /** Options for a single channel field. */export interface ColorPickerChannelInputProps { /** Channel to change, or the hex digits. @default "hex" */ channel?: ColorPickerChannel | 'hex' /** Color space for the channel. Defaults to the channel's native space. */ colorSpace?: ColorPickerColorSpace} /** Options for the joined channel fields. */export interface ColorPickerFieldsProps { /** Initial display format. Independent of the output format. @default "hex" */ defaultFormat?: ColorPickerFormat /** Formats available in the menu. @default ["hex", "rgb", "hsl", "hsb", "oklch"] */ formats?: readonly ColorPickerFormat[]} /** One color in a swatch group. */export interface ColorPickerSwatchItemProps { /** CSS color to select. */ value: string /** Accessible name. Defaults to the color value. */ label?: string} /** Optional colors for the swatch group. A slot can supply individual items. */export interface ColorPickerSwatchesProps { /** CSS colors to show. @default [] */ colors?: readonly string[]} /** Detail for bubbling color-picker:change and color-picker:commit events. */export interface ColorPickerChangeDetail { /** ID of the main input or trigger. */ id: string /** Form field name, or an empty string. */ name: string /** Color in the root's output format. */ value: string /** Equivalent hex color, with alpha when needed. */ hex: string /** Equivalent OKLCH color. Preserves wide-gamut values. */ oklch: string /** Hue, saturation, and lightness. */ hsl: [number, number, number]}
Usage
---
import {
ColorPicker,
ColorPickerContent,
ColorPickerInput,
} from "@/components/ui/color-picker"
---
<ColorPicker id="canvas-background" name="background" defaultValue="#f8fafc">
<ColorPickerInput aria-label="Canvas background" />
<ColorPickerContent />
</ColorPicker>
ColorPicker owns the color and a hidden form field. Each child part is optional. Without a slot, the root supplies a trigger and content. ColorPickerContent supplies a panel when its slot is empty. ColorPickerPanel supplies an area, hue and optional opacity sliders, and fields when its slot is empty.
The root id moves to the main text input or trigger when the browser binds the picker. A FieldLabel can use that ID. Other HTML attributes belong on the part that needs them. Use ColorPickerInput for a text field with a swatch button, or compose ColorPickerTrigger, ColorPickerSwatch, and ColorPickerValue.
Examples
Text input
Enter a CSS color. Enter or blur applies the value. Escape restores an unfinished edit. Invalid text restores the current value. Alt+ArrowDown opens the popup.
Enter a hex code, rgb(), hsl(), oklch(), or a name such as tomato.
---import { ColorPicker, ColorPickerContent, ColorPickerInput,} from "@/components/ui/color-picker"import { Field, FieldDescription, FieldLabel } from "@/components/ui/field"---
<div class="w-full max-w-xs"> <Field> <FieldLabel for="canvas-background">Canvas background</FieldLabel> <ColorPicker id="canvas-background" defaultValue="#f8fafc" name="background" > <ColorPickerInput aria-describedby="canvas-background-description" /> <ColorPickerContent /> </ColorPicker> <FieldDescription id="canvas-background-description"> Enter a hex code, rgb(), hsl(), oklch(), or a name such as tomato. </FieldDescription> </Field></div>Inline panel and opacity
Place ColorPickerPanel directly in the root for an inline picker. Set alpha on the root to permit transparency. The root format controls form values and events. ColorPickerFields joins a compact native format selector, the channels, and optional opacity in one row. The format selector changes only the displayed channels.
---import { ColorPicker, ColorPickerPanel, ColorPickerArea, ColorPickerSlider, ColorPickerFields, ColorPickerSwatches,} from "@/components/ui/color-picker"---
<ColorPicker id="inline-color" defaultValue="oklch(0.7 0.15 250 / 0.8)" format="oklch" alpha class="w-80 max-w-full"> <ColorPickerPanel> <ColorPickerArea /> <ColorPickerSlider channel="hue" /> <ColorPickerSlider channel="alpha" /> <ColorPickerFields defaultFormat="oklch" /> <ColorPickerSwatches colors={["#007aff", "tomato", "rebeccapurple", "#4cd964"]} /> </ColorPickerPanel></ColorPicker>Individual channels
Combine channel sliders and inputs with other primitives. Channel inputs apply on Enter or blur. Arrow keys change their value; Shift changes it by ten steps.
---import { ColorPicker, ColorPickerPanel, ColorPickerSlider, ColorPickerChannelInput, ColorPickerSwatch,} from "@/components/ui/color-picker"import { InputGroup } from "@/components/ui/input-group"import { Field, FieldLabel } from "@/components/ui/field"---
<ColorPicker id="rgb-color" defaultValue="#6699cc" format="rgb" class="w-72"> <ColorPickerPanel> <ColorPickerSwatch class="size-12" /> {["red", "green", "blue"].map((channel) => ( <Field> <FieldLabel for={`rgb-${channel}`}>{channel}</FieldLabel> <ColorPickerSlider id={`rgb-${channel}`} channel={channel as "red" | "green" | "blue"} /> </Field> ))} <InputGroup> <ColorPickerChannelInput channel="red" /> <ColorPickerChannelInput channel="green" /> <ColorPickerChannelInput channel="blue" /> </InputGroup> </ColorPickerPanel></ColorPicker>Swatches only
A picker does not require an area or popup. Use colors on ColorPickerSwatches, or supply named ColorPickerSwatchItem parts. Each item is a native toggle button. Arrow keys, Home, and End move focus within the group. Enter or Space selects the color.
---import { ColorPicker, ColorPickerSwatches, ColorPickerSwatchItem, ColorPickerValue,} from "@/components/ui/color-picker"---
<ColorPicker id="surface-color" defaultValue="#c4a484" name="surface" class="gap-4"> <ColorPickerSwatches> <ColorPickerSwatchItem value="#c4a484" label="Sand" /> <ColorPickerSwatchItem value="#8c9a6a" label="Sage" /> <ColorPickerSwatchItem value="#4f6f6a" label="Pine" /> <ColorPickerSwatchItem value="#2c3a47" label="Slate" /> <ColorPickerSwatchItem value="#e7e1d6" label="Stone" /> <ColorPickerSwatchItem value="#1f1a17" label="Earth" /> </ColorPickerSwatches> <ColorPickerValue /></ColorPicker>Events and external updates
color-picker:change bubbles from the root for each changed value, including a drag. color-picker:commit bubbles when an edit ends: pointer release, a slider change, a channel key, text entry, or a swatch selection. Both events carry id, name, value, hex, oklch, and hsl.
Use change for a live preview. Use commit to save the result. The design menu uses commit to update the complete preset after an edit.
import type { ColorPickerChangeDetail } from "@/components/ui/color-picker"
const picker = document.querySelector<HTMLElement>('[data-slot="color-picker"]')!
picker.addEventListener("color-picker:change", (event) => {
const { id, value } = (event as CustomEvent<ColorPickerChangeDetail>).detail
console.log(id, value)
})
// Silent updates do not send another change event.
picker.dispatchEvent(
new CustomEvent("color-picker:set", {
detail: { value: "oklch(0.7 0.15 250)" },
}),
)
createColorPicker(root) returns getValue(), setColor(value, { silent }), and destroy(). A repeated call returns the existing controller. Native form reset restores the initial color and field formats. Disabled fields are not submitted. readOnly prevents user edits.
Color formats and styling
The output formats are HEX, RGB, HSL, HSB, and OKLCH. Parsing supports CSS named colors, transparency, and CSS Color 4 color functions. Context-dependent browser colors are resolved only for text input. HEX, RGB, HSL, and HSB output map colors into sRGB. Use OKLCH output to retain wider color values. With alpha={false}, output is opaque.
This Astro adaptation uses the supplied ReUI color model and part structure. It uses the existing data-slot Popover for popup behavior and native range inputs for channel sliders. It has no React or Motion dependency. Popup trigger and content parts retain the data-slot names required by Popover. All picker styling uses central recipes in registry/styles/gnostic/default/color-picker.css, along with the shared Button, InputGroup, and Popover recipes.
API reference
ColorPickerProps
defaultValue?string
Initial CSS color.
string"#000000"format?ColorPickerFormat
Output format for events and form submission.
ColorPickerFormat"hex"alpha?boolean
Permit transparency.
booleanfalsedisabled?boolean
Disable all controls.
booleanfalsereadOnly?boolean
Show the color without permitting changes.
booleanfalselabel?string
Accessible name for the picker.
string"Choose a color"name?string
Name of the hidden form field.
stringform?string
ID of an external form.
stringColorPickerContentProps
ColorPickerSliderProps
channel?ColorPickerChannel
Channel to change.
ColorPickerChannel"hue"colorSpace?ColorPickerColorSpace
Color space for the channel. Defaults to the channel's native space.
ColorPickerColorSpaceColorPickerChannelInputProps
channel?ColorPickerChannel | 'hex'
Channel to change, or the hex digits.
ColorPickerChannel | 'hex'"hex"colorSpace?ColorPickerColorSpace
Color space for the channel. Defaults to the channel's native space.
ColorPickerColorSpaceColorPickerFieldsProps
defaultFormat?ColorPickerFormat
Initial display format. Independent of the output format.
ColorPickerFormat"hex"formats?readonly ColorPickerFormat[]
Formats available in the menu.
readonly ColorPickerFormat[]["hex", "rgb", "hsl", "hsb", "oklch"]ColorPickerSwatchesProps
colors?readonly string[]
CSS colors to show.
readonly string[][]ColorPickerSwatchItemProps
valuestring
CSS color to select.
stringlabel?string
Accessible name. Defaults to the color value.
stringColorPickerChangeDetail
idstring
ID of the main input or trigger.
stringnamestring
Form field name, or an empty string.
stringvaluestring
Color in the root's output format.
stringhexstring
Equivalent hex color, with alpha when needed.
stringoklchstring
Equivalent OKLCH color. Preserves wide-gamut values.
stringhsl[number, number, number]
Hue, saturation, and lightness.
[number, number, number]Read the installed source for the complete prop types.
Theme and layout
The controls inherit the selected project preset. Swatches show their supplied colors. Check that the popup and channel fields fit a narrow screen and that labels stay readable in light and dark mode.