Color Picker
A native color field with named preset swatches and a readable color value.
pnpm dlx shadcn@latest add @haze/color-picker---
import { Check, ChevronDown } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
interface Swatch {
label: string;
color: string;
}
interface Props {
id: string;
name?: string;
label?: string;
value?: string;
swatches?: Swatch[];
disabled?: boolean;
class?: string;
[key: string]: unknown;
}
const { id, name = id, label = "Color", value, disabled, class: className, swatches = [], ...rest } = Astro.props;
const panelId = `${id}-color-popover`;
---
<div data-haze-color-picker class={cn("grid min-w-0 gap-2", className)}>
<label for={id} class="text-[0.8125rem]/5 font-medium text-foreground">{label}</label>
<div class="flex min-w-0 flex-wrap items-center gap-2" style={`anchor-name: --${panelId}`}>
<input
{...rest}
id={id}
name={name}
type="color"
value={value}
disabled={disabled}
data-color-input
class="m-0 h-10 w-16 shrink-0 cursor-pointer rounded-lg border border-frame-input bg-field p-1.5 transition-colors duration-150 ease-snappy hover:border-frame-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring disabled:cursor-not-allowed disabled:opacity-50 [&::-moz-color-swatch]:rounded-xs [&::-moz-color-swatch]:border-0 [&::-webkit-color-swatch]:rounded-xs [&::-webkit-color-swatch]:border-0 [&::-webkit-color-swatch-wrapper]:p-0 [[data-haze-color-picker][data-enhanced]_&]:sr-only"
/>
<button
type="button"
hidden
disabled={disabled}
popovertarget={panelId}
aria-haspopup="dialog"
data-color-trigger
class="hidden h-10 cursor-pointer items-center gap-2.5 rounded-lg border border-frame bg-field px-2.5 transition-[border-color,background-color,box-shadow] duration-150 ease-snappy hover:border-frame-strong hover:bg-accent focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/24 focus-visible:outline-hidden [[data-haze-color-picker][data-enhanced]_&]:inline-flex"
>
<span data-color-chip aria-hidden="true" style={value ? `background-color: ${value}` : undefined} class="size-5 rounded-sm border border-frame"></span>
<output for={id} data-color-value class="font-mono text-xs tracking-wide text-foreground uppercase">{value}</output>
<ChevronDown class="size-3.5 text-muted-foreground" aria-hidden="true" />
</button>
<output for={id} data-color-value-fallback class="font-mono text-[0.8125rem]/5 tracking-wide text-muted-foreground uppercase [[data-haze-color-picker][data-enhanced]_&]:hidden">{value}</output>
</div>
<!-- Stylized Haze Color Spectrum Popover -->
<div
id={panelId}
popover="auto"
role="dialog"
aria-label={`Choose ${label.toLowerCase()}`}
data-color-popover
style={`position-anchor: --${panelId}`}
class="m-auto w-60 max-w-[calc(100vw-1rem)] -translate-y-1 scale-[0.97] rounded-xl border border-border bg-popover p-3 text-popover-foreground opacity-0 shadow-float transition-[opacity,scale,translate,overlay,display] transition-discrete duration-150 ease-snappy open:translate-y-0 open:scale-100 open:opacity-100 backdrop:bg-background/60 starting:open:-translate-y-1 starting:open:scale-[0.97] starting:open:opacity-0 supports-[position-area:block-end]:m-0 supports-[position-area:block-end]:my-1.5 supports-[position-area:block-end]:backdrop:bg-transparent supports-[position-area:block-end]:[position-area:block-end_span-inline-end] supports-[position-area:block-end]:[position-try-fallbacks:flip-block,flip-inline]"
>
<div class="grid gap-3">
<!-- 2D Saturation / Brightness Canvas -->
<div class="relative h-32 w-full overflow-hidden rounded-lg border border-frame">
<canvas data-cp-sv width="200" height="128" class="block size-full cursor-crosshair touch-none"></canvas>
<span data-cp-thumb aria-hidden="true" class="pointer-events-none absolute top-1/2 left-1/2 size-3.5 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-foreground shadow-key"></span>
</div>
<!-- Hue Bar Canvas -->
<div class="relative h-3.5 w-full overflow-hidden rounded-full border border-frame">
<canvas data-cp-hue width="200" height="14" class="block size-full cursor-ew-resize touch-none"></canvas>
<span data-cp-hue-thumb aria-hidden="true" class="pointer-events-none absolute top-1/2 left-0 size-3.5 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-foreground bg-card shadow-key"></span>
</div>
<!-- Direct Hex Field -->
<div class="flex items-center gap-2">
<span data-cp-preview class="size-8 shrink-0 rounded-md border border-frame" aria-hidden="true"></span>
<label for={`${id}-hex`} class="sr-only">Hex value</label>
<input
id={`${id}-hex`}
type="text"
maxlength="7"
data-cp-hex
class="h-8 min-w-0 flex-1 rounded-md border border-frame-input bg-field px-2.5 font-mono text-xs text-foreground uppercase transition-[color,background-color,border-color,box-shadow] hover:border-frame-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/24 focus:outline-hidden"
/>
</div>
{
swatches.length > 0 && (
<div role="group" aria-label="Preset colors" class="flex flex-wrap items-center gap-1.5 border-t border-border pt-2.5">
{swatches.map(({ label: swatchLabel, color }) => (
<button
type="button"
aria-label={swatchLabel}
aria-pressed="false"
disabled={disabled}
data-color-preset
class="group grid size-7 cursor-pointer place-items-center rounded-full border border-frame bg-field transition-[scale,border-color] duration-150 ease-snappy hover:border-frame-strong focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-90 motion-reduce:active:scale-100 aria-pressed:border-foreground disabled:cursor-not-allowed disabled:opacity-50"
>
<span aria-hidden="true" data-color-sample style={`background-color: ${color}`} class="col-start-1 row-start-1 size-5 rounded-full"></span>
<span aria-hidden="true" class="col-start-1 row-start-1 hidden size-3.5 place-items-center rounded-full bg-card text-card-foreground group-aria-pressed:grid">
<Check class="size-2.5" />
</span>
</button>
))}
</div>
)
}
</div>
</div>
</div>
<script>
function hsvToRgb(h: number, s: number, v: number): [number, number, number] {
const f = (n: number, k = (n + h / 60) % 6) => v - v * s * Math.max(Math.min(k, 4 - k, 1), 0);
return [Math.round(f(5) * 255), Math.round(f(3) * 255), Math.round(f(1) * 255)];
}
function rgbToHsv(r: number, g: number, b: number): [number, number, number] {
r /= 255; g /= 255; b /= 255;
const max = Math.max(r, g, b), min = Math.min(r, g, b), d = max - min;
let h = 0;
if (d) {
if (max === r) h = 60 * (((g - b) / d) % 6);
else if (max === g) h = 60 * ((b - r) / d + 2);
else h = 60 * ((r - g) / d + 4);
}
if (h < 0) h += 360;
return [h, max === 0 ? 0 : d / max, max];
}
function rgbToHex(r: number, g: number, b: number) {
const p = (n: number) => n.toString(16).padStart(2, "0");
return `#${p(r)}${p(g)}${p(b)}`;
}
function enhanceColorPickers() {
document.querySelectorAll<HTMLElement>("[data-haze-color-picker]:not([data-enhanced])").forEach((root) => {
const input = root.querySelector<HTMLInputElement>("[data-color-input]");
const trigger = root.querySelector<HTMLButtonElement>("[data-color-trigger]");
const chip = root.querySelector<HTMLElement>("[data-color-chip]");
const output = root.querySelector<HTMLOutputElement>("[data-color-value]");
const fallbackOut = root.querySelector<HTMLOutputElement>("[data-color-value-fallback]");
const popup = root.querySelector<HTMLElement>("[data-color-popover]");
const svCanvas = root.querySelector<HTMLCanvasElement>("[data-cp-sv]");
const hueCanvas = root.querySelector<HTMLCanvasElement>("[data-cp-hue]");
const svThumb = root.querySelector<HTMLElement>("[data-cp-thumb]");
const hueThumb = root.querySelector<HTMLElement>("[data-cp-hue-thumb]");
const hexIn = root.querySelector<HTMLInputElement>("[data-cp-hex]");
const preview = root.querySelector<HTMLElement>("[data-cp-preview]");
if (!input || !trigger || !output || !popup || !svCanvas || !hueCanvas || typeof popup.showPopover !== "function") return;
const presets = Array.from(root.querySelectorAll<HTMLButtonElement>("[data-color-preset]"));
const probe = document.createElement("canvas");
probe.width = 1; probe.height = 1;
const pctx = probe.getContext("2d", { willReadFrequently: true });
const valueFor = (preset: HTMLButtonElement) => {
const swatch = preset.querySelector("[data-color-sample]");
if (!swatch || !pctx) return undefined;
pctx.clearRect(0, 0, 1, 1);
pctx.fillStyle = getComputedStyle(swatch).backgroundColor;
pctx.fillRect(0, 0, 1, 1);
const [r, g, b, a] = pctx.getImageData(0, 0, 1, 1).data;
return a === 255 ? rgbToHex(r, g, b) : undefined;
};
const svCtx = svCanvas.getContext("2d")!;
const hueCtx = hueCanvas.getContext("2d")!;
let hue = 216, sat = 0.56, val = 1;
const drawHue = () => {
const img = hueCtx.createImageData(hueCanvas.width, hueCanvas.height);
for (let x = 0; x < hueCanvas.width; x++) {
const [r, g, b] = hsvToRgb((x / hueCanvas.width) * 360, 1, 1);
for (let y = 0; y < hueCanvas.height; y++) {
const idx = (y * hueCanvas.width + x) * 4;
img.data[idx] = r; img.data[idx + 1] = g; img.data[idx + 2] = b; img.data[idx + 3] = 255;
}
}
hueCtx.putImageData(img, 0, 0);
};
const drawSV = () => {
const w = svCanvas.width, h = svCanvas.height;
const img = svCtx.createImageData(w, h);
const [hr, hg, hb] = hsvToRgb(hue, 1, 1);
for (let y = 0; y < h; y++) {
const v = 1 - y / (h - 1);
for (let x = 0; x < w; x++) {
const s = x / (w - 1);
const idx = (y * w + x) * 4;
img.data[idx] = Math.round(((1 - s) * 255 + s * hr) * v);
img.data[idx + 1] = Math.round(((1 - s) * 255 + s * hg) * v);
img.data[idx + 2] = Math.round(((1 - s) * 255 + s * hb) * v);
img.data[idx + 3] = 255;
}
}
svCtx.putImageData(img, 0, 0);
};
const parseHexToHsv = (hex: string) => {
const clean = hex.replace(/[^0-9a-fA-F]/g, "");
if (clean.length !== 6) return;
const n = parseInt(clean, 16);
[hue, sat, val] = rgbToHsv((n >> 16) & 255, (n >> 8) & 255, n & 255);
};
const syncUI = (redraw = true) => {
const cur = input.value;
output.value = cur;
if (fallbackOut) fallbackOut.value = cur;
if (chip) chip.style.backgroundColor = cur;
if (preview) preview.style.backgroundColor = cur;
if (hexIn && document.activeElement !== hexIn) hexIn.value = cur;
if (svThumb) {
svThumb.style.left = `${sat * 100}%`;
svThumb.style.top = `${(1 - val) * 100}%`;
}
if (hueThumb) hueThumb.style.left = `${(hue / 360) * 100}%`;
if (redraw) drawSV();
presets.forEach((preset) => preset.setAttribute("aria-pressed", String(valueFor(preset) === cur)));
};
const commitHsv = () => {
const [r, g, b] = hsvToRgb(hue, sat, val);
input.value = rgbToHex(r, g, b);
syncUI(false);
input.dispatchEvent(new Event("input", { bubbles: true }));
input.dispatchEvent(new Event("change", { bubbles: true }));
};
const bindDrag = (el: HTMLCanvasElement, onMove: (rx: number, ry: number) => void) => {
const handle = (ev: PointerEvent) => {
const r = el.getBoundingClientRect();
if (!r.width || !r.height) return;
onMove(Math.max(0, Math.min(1, (ev.clientX - r.left) / r.width)), Math.max(0, Math.min(1, (ev.clientY - r.top) / r.height)));
};
el.addEventListener("pointerdown", (ev) => {
el.setPointerCapture(ev.pointerId);
handle(ev);
});
el.addEventListener("pointermove", (ev) => {
if (ev.buttons) handle(ev);
});
};
bindDrag(svCanvas, (rx, ry) => {
sat = rx; val = 1 - ry;
commitHsv();
});
bindDrag(hueCanvas, (rx) => {
hue = rx * 360;
drawSV();
commitHsv();
});
hexIn?.addEventListener("input", () => {
const cleaned = hexIn.value.trim();
if (/^#[0-9a-fA-F]{6}$/.test(cleaned)) {
input.value = cleaned.toLowerCase();
parseHexToHsv(input.value);
syncUI(true);
input.dispatchEvent(new Event("input", { bubbles: true }));
input.dispatchEvent(new Event("change", { bubbles: true }));
}
});
input.addEventListener("click", (ev) => {
ev.preventDefault();
if (input.disabled) return;
if (!popup.matches(":popover-open")) popup.showPopover();
});
input.addEventListener("input", () => { parseHexToHsv(input.value); syncUI(true); });
input.form?.addEventListener("reset", () => queueMicrotask(() => { parseHexToHsv(input.value); syncUI(true); }));
for (const preset of presets) {
preset.addEventListener("click", () => {
if (input.disabled) return;
const v = valueFor(preset);
if (!v) return;
input.value = v;
parseHexToHsv(v);
syncUI(true);
input.dispatchEvent(new Event("input", { bubbles: true }));
input.dispatchEvent(new Event("change", { bubbles: true }));
});
}
drawHue();
if (input.value) parseHexToHsv(input.value);
trigger.hidden = false;
root.setAttribute("data-enhanced", "");
syncUI(true);
});
}
enhanceColorPickers();
if (!document.documentElement.hasAttribute("data-haze-color-picker-listener")) {
document.documentElement.setAttribute("data-haze-color-picker-listener", "");
document.addEventListener("astro:page-load", enhanceColorPickers);
}
</script>When to use
- A form collects an accent or label color.
- A preset palette helps users choose quickly while still allowing custom colors.
When not to use
- The application needs color profiles or transparency editing.
Installation
Add the Haze registry to components.json once, then install Color Picker with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/color-pickernpx shadcn@latest add @haze/color-pickeryarn dlx shadcn@latest add @haze/color-pickerbunx --bun shadcn@latest add @haze/color-pickerFirst time? Registry and theme setup
1. Add to components.json:
{
"registries": {
"@haze": "http://localhost:4329/r/{name}.json"
}
}2. Install the theme once: npx shadcn@latest add @haze/theme, then import it after Tailwind in your global CSS:@import "./haze.css";
API reference
| Prop | Type | Default | Description |
|---|---|---|---|
| id* | string | – | Unique color field ID. |
| name | string | id | Submitted field name. |
| label | string | Color | Visible and accessible label. |
| value | string | – | Initial hexadecimal sRGB color. |
| swatches | Swatch[] | – | Named opaque CSS colors or custom properties. |
| disabled | boolean | – | Disables the picker and its presets. |
| class | string | – | Classes for the field wrapper. |
Keyboard interactions
- Tab
- Move to the native picker and preset colors.
- EnterSpace
- Choose a preset or open the native color picker.
Accessibility
- Presets expose accessible names and a pressed state.
- The selected color value and the native picker are available without relying on swatch color alone.
Notes for AI
Copy into Claude Code, Cursor, Codex or any coding agent. Agents can also read the Markdown version of this page.
Install and use
Install the Haze UI component "Color Picker" with `npx shadcn@latest add @haze/color-picker`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "http://localhost:4329/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import ColorPicker from "@/components/haze/ui/color-picker.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: http://localhost:4329/ui/color-picker.md
Customize with real content
Adapt the Haze color-picker ui for our product. Replace the demo values of these props with our real content: id, name, label, value, swatches, disabled, class. Keep the layout, the heading level rules and these accessibility details: Presets expose accessible names and a pressed state. The selected color value and the native picker are available without relying on swatch color alone. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using color-picker, check it fits: use it when a form collects an accent or label color.; a preset palette helps users choose quickly while still allowing custom colors.. Avoid it when the application needs color profiles or transparency editing.. Alternatives: @haze/radio-group, @haze/chip, @haze/input.
Dependencies
- npm: @lucide/astro
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.