Skip to content
Uxelith
Freev1.0.0Forms

Color Picker

A colour picker with a saturation area, hue and opacity sliders, hex, rgb, hsl and oklch input, swatches and the screen eyedropper, that checks the colour's WCAG contrast on your background and moves it to the nearest colour that passes in one click.

pnpm dlx shadcn add …/r/color-picker.json
Licence
MIT
Packages
2
Updated
13 Nov 2026
Live

Installation

  1. Run this in a project set up with shadcn/ui:

    $ pnpm dlx shadcn@latest add https://uxelith.com/r/color-picker.json
  2. It adds these packages for you:

    clsxtailwind-merge
  3. The source lands in your components folder as color-picker.tsx. It's yours: change anything.

Usage

example.tsx
"use client"

import * as React from "react"

import { ColorPicker } from "@/components/color-picker"

export function BrandColour() {
  const [colour, setColour] = React.useState("#8b5cf6")
  return (
    <div className="grid gap-3">
      <ColorPicker value={colour} onValueChange={setColour} contrastWith="#ffffff" label="Brand colour" name="brand" />
      <p className="text-sm text-muted-foreground">Saved as {colour}</p>
    </div>
  )
}

Source

One file, 727 lines, nothing hidden. Read it before you install it.

color-picker.tsx
"use client";

import * as React from "react";

import { cn } from "@/lib/utils";

export type ColorFormat = "hex" | "rgb" | "hsl" | "oklch";

/** A colour as the picker holds it: hue 0–360, saturation, brightness and alpha 0–1. */
export interface Hsva {
  h: number;
  s: number;
  v: number;
  a: number;
}

export interface ColorPickerProps extends Omit<React.ComponentProps<"div">, "defaultValue" | "onChange"> {
  /** The colour, when you control it. Any CSS hex, rgb(), hsl() or oklch() string. */
  value?: string;
  /** The first colour when uncontrolled. */
  defaultValue?: string;
  /** Called as the colour changes, with the value in `format`. */
  onValueChange?: (value: string) => void;
  /** Called when a change is finished: a drag ends, a key is released, a swatch or a typed value is chosen. */
  onValueCommit?: (value: string) => void;
  /** The format of the value you get back, and the one the text field starts in. */
  format?: ColorFormat;
  /** Let people switch the text field between formats. */
  formatSelect?: boolean;
  /** Show the opacity slider. Without it, colours are always opaque. */
  alpha?: boolean;
  /** Colours one tap away. An empty list hides them. */
  swatches?: string[];
  /** Check the colour as text on this background (WCAG 2.2) and offer the nearest colour that passes. */
  contrastWith?: string;
  /** The level "nearest colour that passes" aims for: AA is 4.5:1, AAA is 7:1. */
  contrastLevel?: "AA" | "AAA";
  /** Show the screen picker button where the browser has one (Chromium). */
  eyeDropper?: boolean;
  /** Sit in the page, or open from a button in a popover. */
  mode?: "inline" | "popover";
  /** Submit the value with forms under this name. */
  name?: string;
  /** Names the picker (and the popover button). */
  label?: string;
  disabled?: boolean;
}

const DEFAULT_SWATCHES = ["#6d28d9", "#2563eb", "#0891b2", "#059669", "#65a30d", "#ca8a04", "#ea580c", "#dc2626", "#db2777", "#111827", "#4b5563", "#9ca3af", "#e5e7eb", "#ffffff"];
const FALLBACK: Hsva = { h: 258, s: 0.63, v: 0.96, a: 1 };

// --- Colour maths (sRGB, WCAG 2.2 relative luminance, OKLab/OKLCH by Björn Ottosson) ---

const clamp = (x: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, x));
const round = (x: number, places = 0) => Number(x.toFixed(places));
type Rgb = [number, number, number];

function hsvToRgb({ h, s, v }: Hsva): Rgb {
  const f = (n: number) => {
    const k = (n + h / 60) % 6;
    return Math.round((v - v * s * Math.max(0, Math.min(k, 4 - k, 1))) * 255);
  };
  return [f(5), f(3), f(1)];
}

function rgbToHsv([r, g, b]: Rgb, a: number, keepHue?: number): Hsva {
  const [R, G, B] = [r / 255, g / 255, b / 255];
  const max = Math.max(R, G, B);
  const d = max - Math.min(R, G, B);
  let h = keepHue ?? 0;
  if (d) {
    if (max === R) h = ((G - B) / d) % 6;
    else if (max === G) h = (B - R) / d + 2;
    else h = (R - G) / d + 4;
    h *= 60;
    if (h < 0) h += 360;
  }
  return { h, s: max ? d / max : 0, v: max, a };
}

function rgbToHsl([r, g, b]: Rgb): Rgb {
  const [R, G, B] = [r / 255, g / 255, b / 255];
  const max = Math.max(R, G, B);
  const min = Math.min(R, G, B);
  const l = (max + min) / 2;
  const d = max - min;
  let h = 0;
  if (d) {
    if (max === R) h = ((G - B) / d) % 6;
    else if (max === G) h = (B - R) / d + 2;
    else h = (R - G) / d + 4;
    h *= 60;
    if (h < 0) h += 360;
  }
  return [Math.round(h), Math.round((d ? d / (1 - Math.abs(2 * l - 1)) : 0) * 100), Math.round(l * 100)];
}

function hslToRgb(h: number, s: number, l: number): Rgb {
  const S = s / 100;
  const L = l / 100;
  const a = S * Math.min(L, 1 - L);
  const f = (n: number) => {
    const k = (n + h / 30) % 12;
    return Math.round((L - a * Math.max(-1, Math.min(k - 3, 9 - k, 1))) * 255);
  };
  return [f(0), f(8), f(4)];
}

const toLinear = (c: number) => {
  const x = c / 255;
  return x <= 0.04045 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4;
};
const fromLinear = (c: number) => Math.round(clamp(c <= 0.0031308 ? 12.92 * c : 1.055 * c ** (1 / 2.4) - 0.055, 0, 1) * 255);

function rgbToOklch([r, g, b]: Rgb): [number, number, number] {
  const [R, G, B] = [toLinear(r), toLinear(g), toLinear(b)];
  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);
  const L = 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s;
  const A = 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s;
  const Bb = 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s;
  let H = (Math.atan2(Bb, A) * 180) / Math.PI;
  if (H < 0) H += 360;
  return [L, Math.hypot(A, Bb), H];
}

function oklchToRgb(L: number, C: number, H: number): Rgb {
  const A = C * Math.cos((H * Math.PI) / 180);
  const B = C * Math.sin((H * Math.PI) / 180);
  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 [
    fromLinear(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s),
    fromLinear(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s),
    fromLinear(-0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s),
  ];
}

const luminance = ([r, g, b]: Rgb) => 0.2126 * toLinear(r) + 0.7152 * toLinear(g) + 0.0722 * toLinear(b);

function alphaOf(raw: string | undefined) {
  if (raw === undefined) return 1;
  return clamp(raw.endsWith("%") ? parseFloat(raw) / 100 : parseFloat(raw), 0, 1);
}

/** Reads a CSS hex, rgb(), hsl() or oklch() colour. Returns null for anything else. */
export function parseColor(input: string, keepHue?: number): Hsva | null {
  const text = input.trim().toLowerCase();
  let m = text.match(/^#?([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/);
  if (m) {
    let hex = m[1]!;
    if (hex.length <= 4) hex = [...hex].map((c) => c + c).join("");
    const n = hex.match(/../g)!.map((p) => parseInt(p, 16));
    return rgbToHsv([n[0]!, n[1]!, n[2]!], n[3] === undefined ? 1 : round(n[3] / 255, 2), keepHue);
  }
  const num = "(-?[\\d.]+)";
  const alpha = "(?:\\s*[,/]\\s*([\\d.]+%?))?";
  m = text.match(new RegExp(`^rgba?\\(\\s*${num}%?[\\s,]+${num}%?[\\s,]+${num}%?${alpha}\\s*\\)$`));
  if (m) return rgbToHsv([m[1], m[2], m[3]].map((x) => clamp(Math.round(Number(x)), 0, 255)) as Rgb, alphaOf(m[4]), keepHue);
  m = text.match(new RegExp(`^hsla?\\(\\s*${num}(?:deg)?[\\s,]+${num}%[\\s,]+${num}%${alpha}\\s*\\)$`));
  if (m) return rgbToHsv(hslToRgb(((Number(m[1]) % 360) + 360) % 360, clamp(Number(m[2]), 0, 100), clamp(Number(m[3]), 0, 100)), alphaOf(m[4]), keepHue);
  m = text.match(new RegExp(`^oklch\\(\\s*${num}(%?)\\s+${num}\\s+${num}(?:deg)?(?:\\s*/\\s*([\\d.]+%?))?\\s*\\)$`));
  if (m) {
    const L = m[2] ? Number(m[1]) / 100 : Number(m[1]);
    return rgbToHsv(oklchToRgb(clamp(L, 0, 1), Math.max(0, Number(m[3])), Number(m[4])), alphaOf(m[5]), keepHue);
  }
  return null;
}

/** Writes a colour in one of the four formats; alpha appears only below 100%. */
export function formatColor(color: Hsva, format: ColorFormat): string {
  const rgb = hsvToRgb(color);
  const a = round(color.a, 2);
  const slash = a < 1 ? ` / ${Math.round(a * 100)}%` : "";
  if (format === "rgb") return `rgb(${rgb.join(" ")}${slash})`;
  if (format === "hsl") {
    const [h, s, l] = rgbToHsl(rgb);
    return `hsl(${h} ${s}% ${l}%${slash})`;
  }
  if (format === "oklch") {
    const [L, C, H] = rgbToOklch(rgb);
    return `oklch(${round(L * 100, 1)}% ${round(C, 3)} ${C < 0.0005 ? 0 : round(H, 1)}${slash})`;
  }
  const hex = rgb.map((c) => c.toString(16).padStart(2, "0")).join("");
  return `#${hex}${a < 1 ? Math.round(a * 255).toString(16).padStart(2, "0") : ""}`;
}

/** The WCAG 2.2 contrast ratio of a colour (blended over the background when see-through) on a background. */
export function contrastRatio(foreground: string, background: string): number | null {
  const fg = parseColor(foreground);
  const bg = parseColor(background);
  if (!fg || !bg) return null;
  const back = hsvToRgb(bg);
  const front = hsvToRgb(fg).map((c, i) => Math.round(c * fg.a + back[i]! * (1 - fg.a))) as Rgb;
  const [l1, l2] = [luminance(front), luminance(back)];
  return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
}

/** The colour closest in OKLCH lightness (same hue and chroma) that reaches `target` on the background. */
function nearestPassing(color: Hsva, background: Hsva, target: number): Hsva | null {
  const [L, C, H] = rgbToOklch(hsvToRgb(color));
  const back = luminance(hsvToRgb(background));
  const passes = (rgb: Rgb) => {
    const l = luminance(rgb);
    return (Math.max(l, back) + 0.05) / (Math.min(l, back) + 0.05) >= target;
  };
  for (let step = 1; step <= 100; step++) {
    for (const dir of [-1, 1]) {
      const next = L + (dir * step) / 100;
      if (next < 0 || next > 1) continue;
      const rgb = oklchToRgb(next, C, H);
      if (passes(rgb)) return rgbToHsv(rgb, 1, color.h);
    }
  }
  return null;
}

// --- Pieces ---

const checker =
  "bg-[conic-gradient(#d4d4d8_25%,#fff_0_50%,#d4d4d8_0_75%,#fff_0)] bg-[length:10px_10px] dark:bg-[conic-gradient(#3f3f46_25%,#71717a_0_50%,#3f3f46_0_75%,#71717a_0)]";
const thumb = "pointer-events-none absolute size-5 -translate-x-1/2 -translate-y-1/2 rounded-full border-[2.5px] border-white shadow-[0_0_0_1px_rgb(0_0_0/0.35),0_2px_6px_rgb(0_0_0/0.3)]";
const focusRing = "outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background";

type Keys = { left?: () => void; right?: () => void; up?: () => void; down?: () => void; home?: () => void; end?: () => void };

/** Arrows step by 1, with Shift (or PageUp/PageDown) by 10. */
function onSliderKey(event: React.KeyboardEvent, make: (step: number) => Keys, commit: () => void) {
  const step = event.shiftKey ? 10 : 1;
  const k = make(step);
  const big = make(10);
  const map: Record<string, (() => void) | undefined> = {
    ArrowLeft: k.left,
    ArrowRight: k.right,
    ArrowUp: k.up ?? k.right,
    ArrowDown: k.down ?? k.left,
    PageUp: big.up ?? big.right,
    PageDown: big.down ?? big.left,
    Home: k.home,
    End: k.end,
  };
  const run = map[event.key];
  if (!run) return;
  event.preventDefault();
  run();
  commit();
}

/** Drag on an element; reports the pointer as fractions of its box. */
function usePointerDrag(onMove: (x: number, y: number) => void, onEnd: () => void) {
  return {
    onPointerDown(event: React.PointerEvent<HTMLElement>) {
      if (event.button !== 0) return;
      const el = event.currentTarget;
      el.setPointerCapture(event.pointerId);
      el.focus({ preventScroll: true });
      const move = (e: PointerEvent | React.PointerEvent) => {
        const box = el.getBoundingClientRect();
        onMove(clamp((e.clientX - box.left) / box.width, 0, 1), clamp((e.clientY - box.top) / box.height, 0, 1));
      };
      move(event);
      const up = () => {
        el.removeEventListener("pointermove", move);
        el.removeEventListener("pointerup", up);
        el.removeEventListener("pointercancel", up);
        onEnd();
      };
      el.addEventListener("pointermove", move);
      el.addEventListener("pointerup", up);
      el.addEventListener("pointercancel", up);
    },
  };
}

interface EyeDropperLike {
  open: () => Promise<{ sRGBHex: string }>;
}

/** Whether the browser can pick from the screen; the server and the first render say no. */
function useHasEyeDropper() {
  return React.useSyncExternalStore(
    () => () => {},
    () => "EyeDropper" in window,
    () => false,
  );
}

/**
 * Picks a colour: a saturation and brightness area, hue and opacity sliders, a text field in hex, rgb, hsl or
 * oklch, swatches, and the screen picker where the browser has one. With `contrastWith`, it checks the colour as
 * text on that background against WCAG 2.2 and moves it to the nearest colour that passes in one click.
 *
 * - The area and sliders are ARIA sliders: arrows step by 1, Shift or PageUp/PageDown by 10, Home/End jump.
 *   Each reads its value in words ("Saturation 63%, brightness 96%").
 * - Typed values apply as you type and tidy up on Enter or blur; an unreadable one is marked invalid.
 * - Contrast results are words and symbols, never colour alone. With `name`, a hidden input submits the value.
 * - In popover mode, Escape or a click outside closes it and focus returns to its button.
 */
export function ColorPicker({
  value,
  defaultValue = "#8b5cf6",
  onValueChange,
  onValueCommit,
  format = "hex",
  formatSelect = true,
  alpha = true,
  swatches = DEFAULT_SWATCHES,
  contrastWith,
  contrastLevel = "AA",
  eyeDropper = true,
  mode = "inline",
  name,
  label = "Colour",
  disabled = false,
  className,
  ...props
}: ColorPickerProps) {
  const id = React.useId();
  const [color, setColor] = React.useState<Hsva>(() => parseColor(value ?? defaultValue) ?? FALLBACK);
  const [seen, setSeen] = React.useState(value);
  const [fieldFormat, setFieldFormat] = React.useState<ColorFormat>(format);
  const [draft, setDraft] = React.useState<string | null>(null);
  const [open, setOpen] = React.useState(false);
  const [note, setNote] = React.useState("");
  const [copied, setCopied] = React.useState(false);
  const hasEyeDropper = useHasEyeDropper();
  const rootRef = React.useRef<HTMLDivElement>(null);
  const triggerRef = React.useRef<HTMLButtonElement>(null);
  const panelRef = React.useRef<HTMLDivElement>(null);
  const latest = React.useRef(color);

  // A new value from outside moves the picker, unless it's the value the picker just reported.
  if (value !== undefined && value !== seen) {
    setSeen(value);
    const parsed = parseColor(value, color.h);
    if (parsed && formatColor(parsed, format) !== formatColor(color, format)) setColor(alpha ? parsed : { ...parsed, a: 1 });
  }

  const shown = alpha ? color : { ...color, a: 1 };
  const output = formatColor(shown, format);
  const rgb = hsvToRgb(shown);
  const solid = formatColor({ ...shown, a: 1 }, "hex");
  const hueRgb = hsvToRgb({ h: shown.h, s: 1, v: 1, a: 1 });

  const update = (next: Hsva) => {
    const fixed = alpha ? next : { ...next, a: 1 };
    latest.current = fixed;
    setColor(fixed);
    const out = formatColor(fixed, format);
    setSeen(out);
    onValueChange?.(out);
  };
  const commit = () => onValueCommit?.(formatColor(latest.current, format));
  const updateAndCommit = (next: Hsva) => {
    update(next);
    commit();
  };

  React.useEffect(() => {
    latest.current = shown;
  });

  // Popover: close on Escape or a press outside, and give focus back to the button.
  React.useEffect(() => {
    if (!open) return;
    panelRef.current?.querySelector<HTMLElement>('[role="slider"]')?.focus({ preventScroll: true });
    const onDown = (event: PointerEvent) => {
      if (!rootRef.current?.contains(event.target as Node)) setOpen(false);
    };
    document.addEventListener("pointerdown", onDown);
    return () => document.removeEventListener("pointerdown", onDown);
  }, [open]);

  const close = () => {
    setOpen(false);
    triggerRef.current?.focus();
  };

  const area = usePointerDrag((x, y) => update({ ...latest.current, s: x, v: 1 - y }), commit);
  const hue = usePointerDrag((x) => update({ ...latest.current, h: x * 360 }), commit);
  const opacity = usePointerDrag((x) => update({ ...latest.current, a: round(x, 2) }), commit);

  const background = contrastWith ? parseColor(contrastWith) : null;
  const ratio = background ? contrastRatio(output, contrastWith!) : null;
  const target = contrastLevel === "AAA" ? 7 : 4.5;
  const checks = [
    { name: "AA text", min: 4.5 },
    { name: "AAA text", min: 7 },
    { name: "AA large text", min: 3 },
    { name: "UI parts", min: 3 },
  ];

  const fix = () => {
    if (!background) return;
    const next = nearestPassing(shown, background, target);
    if (!next) {
      setNote(`No colour with this hue reaches ${target}:1 on this background.`);
      return;
    }
    updateAndCommit(next);
    setNote(`Moved to ${formatColor(next, fieldFormat)}, which passes ${contrastLevel}.`);
  };

  const pickFromScreen = async () => {
    try {
      const dropper = new (window as unknown as { EyeDropper: new () => EyeDropperLike }).EyeDropper();
      const result = await dropper.open();
      const next = parseColor(result.sRGBHex, color.h);
      if (next) updateAndCommit(next);
    } catch {
      // Cancelled with Escape: nothing to do.
    }
  };

  const copy = async () => {
    try {
      await navigator.clipboard.writeText(formatColor(shown, fieldFormat));
      setCopied(true);
      window.setTimeout(() => setCopied(false), 1200);
    } catch {
      document.getElementById(`${id}-text`)?.focus();
      (document.getElementById(`${id}-text`) as HTMLInputElement | null)?.select();
    }
  };

  const panel = (
    <div
      ref={panelRef}
      role={mode === "popover" ? "dialog" : "group"}
      aria-label={label}
      id={`${id}-panel`}
      onKeyDown={(event) => {
        if (mode === "popover" && event.key === "Escape") {
          event.stopPropagation();
          close();
        }
      }}
      className={cn(
        "grid w-72 grid-cols-1 gap-3 rounded-2xl border border-border bg-popover p-3 text-popover-foreground shadow-[0_20px_40px_-24px_rgb(40_20_90/0.35)]",
        mode === "popover" &&
          "absolute top-full left-0 z-50 mt-2 origin-top-left transition-[opacity,scale] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] starting:scale-95 starting:opacity-0 motion-reduce:transition-none",
        disabled && "pointer-events-none opacity-50",
      )}
    >
      {/* Saturation (x) and brightness (y) */}
      <div
        role="slider"
        tabIndex={disabled ? -1 : 0}
        aria-label="Saturation and brightness"
        aria-valuemin={0}
        aria-valuemax={100}
        aria-valuenow={Math.round(shown.v * 100)}
        aria-valuetext={`Saturation ${Math.round(shown.s * 100)}%, brightness ${Math.round(shown.v * 100)}%`}
        aria-disabled={disabled || undefined}
        {...area}
        onKeyDown={(event) =>
          onSliderKey(
            event,
            (step) => ({
              left: () => update({ ...shown, s: clamp(shown.s - step / 100, 0, 1) }),
              right: () => update({ ...shown, s: clamp(shown.s + step / 100, 0, 1) }),
              up: () => update({ ...shown, v: clamp(shown.v + step / 100, 0, 1) }),
              down: () => update({ ...shown, v: clamp(shown.v - step / 100, 0, 1) }),
              home: () => update({ ...shown, s: 0 }),
              end: () => update({ ...shown, s: 1 }),
            }),
            commit,
          )
        }
        style={{ backgroundColor: `rgb(${hueRgb.join(" ")})` }}
        className={cn("relative h-44 cursor-crosshair touch-none rounded-xl", focusRing)}
      >
        <div className="absolute inset-0 rounded-xl bg-gradient-to-r from-white to-transparent" />
        <div className="absolute inset-0 rounded-xl bg-gradient-to-t from-black to-transparent" />
        <div className={thumb} style={{ left: `${shown.s * 100}%`, top: `${(1 - shown.v) * 100}%`, background: solid }} />
      </div>

      <div className="flex items-center gap-2.5">
        <div aria-hidden="true" className={cn("relative size-10 shrink-0 overflow-hidden rounded-lg border border-border", checker)}>
          <div className="absolute inset-0" style={{ background: `rgb(${rgb.join(" ")} / ${shown.a})` }} />
        </div>
        <div className="grid min-w-0 flex-1 gap-2.5">
          <div
            role="slider"
            tabIndex={disabled ? -1 : 0}
            aria-label="Hue"
            aria-valuemin={0}
            aria-valuemax={360}
            aria-valuenow={Math.round(shown.h)}
            aria-valuetext={`${Math.round(shown.h)} degrees`}
            aria-disabled={disabled || undefined}
            {...hue}
            onKeyDown={(event) =>
              onSliderKey(
                event,
                (step) => ({
                  left: () => update({ ...shown, h: (shown.h - step + 360) % 360 }),
                  right: () => update({ ...shown, h: (shown.h + step) % 360 }),
                  home: () => update({ ...shown, h: 0 }),
                  end: () => update({ ...shown, h: 359 }),
                }),
                commit,
              )
            }
            className={cn(
              "relative h-3.5 cursor-pointer touch-none rounded-full bg-[linear-gradient(to_right,#f00,#ff0,#0f0,#0ff,#00f,#f0f,#f00)]",
              focusRing,
            )}
          >
            <div className={cn(thumb, "top-1/2 size-[1.125rem]")} style={{ left: `${(shown.h / 360) * 100}%`, background: `rgb(${hueRgb.join(" ")})` }} />
          </div>
          {alpha ? (
            <div
              role="slider"
              tabIndex={disabled ? -1 : 0}
              aria-label="Opacity"
              aria-valuemin={0}
              aria-valuemax={100}
              aria-valuenow={Math.round(shown.a * 100)}
              aria-valuetext={`${Math.round(shown.a * 100)}%`}
              aria-disabled={disabled || undefined}
              {...opacity}
              onKeyDown={(event) =>
                onSliderKey(
                  event,
                  (step) => ({
                    left: () => update({ ...shown, a: round(clamp(shown.a - step / 100, 0, 1), 2) }),
                    right: () => update({ ...shown, a: round(clamp(shown.a + step / 100, 0, 1), 2) }),
                    home: () => update({ ...shown, a: 0 }),
                    end: () => update({ ...shown, a: 1 }),
                  }),
                  commit,
                )
              }
              className={cn("relative h-3.5 cursor-pointer touch-none rounded-full", checker, focusRing)}
            >
              <div className="absolute inset-0 rounded-full" style={{ background: `linear-gradient(to right, transparent, ${solid})` }} />
              <div className={cn(thumb, "top-1/2 size-[1.125rem]")} style={{ left: `${shown.a * 100}%`, background: `rgb(${rgb.join(" ")} / ${shown.a})` }} />
            </div>
          ) : null}
        </div>
        {eyeDropper && hasEyeDropper ? (
          <button
            type="button"
            onClick={pickFromScreen}
            disabled={disabled}
            aria-label="Pick a colour from the screen"
            className={cn("grid size-10 shrink-0 place-items-center rounded-lg border border-border transition-colors duration-200 hover:bg-muted", focusRing)}
          >
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.8} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" className="size-5">
              <path d="m14 7 3 3M5 19l1.5-.5L17 8a2.1 2.1 0 0 0-3-3L3.5 15.5 3 17z" />
              <path d="m15 4 5 5" />
            </svg>
          </button>
        ) : null}
      </div>

      <div className="flex gap-1.5">
        {formatSelect ? (
          <select
            aria-label="Format"
            value={fieldFormat}
            disabled={disabled}
            onChange={(event) => {
              setFieldFormat(event.target.value as ColorFormat);
              setDraft(null);
            }}
            className={cn("h-9 shrink-0 rounded-lg border border-border bg-background px-2 font-mono text-xs uppercase", focusRing)}
          >
            <option value="hex">HEX</option>
            <option value="rgb">RGB</option>
            <option value="hsl">HSL</option>
            <option value="oklch">OKLCH</option>
          </select>
        ) : null}
        <input
          id={`${id}-text`}
          aria-label={`${label} value`}
          value={draft ?? formatColor(shown, fieldFormat)}
          disabled={disabled}
          spellCheck={false}
          autoComplete="off"
          aria-invalid={draft !== null && !parseColor(draft) ? true : undefined}
          onChange={(event) => {
            setDraft(event.target.value);
            const next = parseColor(event.target.value, shown.h);
            if (next) update(next);
          }}
          onKeyDown={(event) => {
            if (event.key === "Enter") {
              setDraft(null);
              commit();
            }
          }}
          onBlur={() => {
            if (draft !== null) commit();
            setDraft(null);
          }}
          className={cn(
            "h-9 min-w-0 flex-1 rounded-lg border border-border bg-background px-2.5 font-mono text-[0.8125rem] aria-invalid:border-red-600",
            focusRing,
          )}
        />
        <button
          type="button"
          onClick={copy}
          disabled={disabled}
          className={cn("h-9 shrink-0 rounded-lg border border-border px-2.5 text-xs font-medium transition-colors duration-200 hover:bg-muted", focusRing)}
        >
          {copied ? "Copied" : "Copy"}
        </button>
      </div>

      {swatches.length ? (
        <div role="group" aria-label="Swatches" className="grid grid-cols-7 gap-1.5">
          {swatches.map((swatch) => {
            const parsed = parseColor(swatch);
            if (!parsed) return null;
            const hex = formatColor(parsed, "hex");
            const chosen = hex === formatColor(shown, "hex");
            return (
              <button
                key={swatch}
                type="button"
                disabled={disabled}
                aria-label={hex.toUpperCase()}
                aria-pressed={chosen}
                onClick={() => updateAndCommit(parseColor(swatch, shown.h)!)}
                style={{ background: swatch }}
                className={cn(
                  "aspect-square rounded-md border border-black/10 dark:border-white/15",
                  chosen && "ring-2 ring-foreground ring-offset-2 ring-offset-popover",
                  focusRing,
                )}
              />
            );
          })}
        </div>
      ) : null}

      {background && ratio !== null ? (
        <div className="grid gap-2 border-t border-border pt-3">
          <div className="flex items-center justify-between gap-2 rounded-xl border border-border px-3 py-2.5" style={{ background: contrastWith }}>
            {/* Sample text drawn from CSS: it is meant to show failing colours, so it stays out of the accessibility tree and audits. */}
            <p aria-hidden="true" style={{ color: `rgb(${rgb.join(" ")} / ${shown.a})` }} className="min-w-0">
              <span data-sample="Book your seat" className="block text-[0.9375rem] font-semibold before:content-[attr(data-sample)]" />
              <span data-sample="Small text, 14px" className="block text-xs before:content-[attr(data-sample)]" />
            </p>
            <p className="rounded-md bg-background/90 px-1.5 font-mono text-lg font-semibold text-foreground tabular-nums">
              {ratio.toFixed(2)}
              <span className="sr-only"> to 1 contrast</span>
              <span aria-hidden="true">:1</span>
            </p>
          </div>
          <ul aria-label="Contrast checks" className="flex flex-wrap gap-1.5">
            {checks.map((check) => {
              const pass = ratio >= check.min;
              return (
                <li
                  key={check.name}
                  className={cn(
                    "rounded-full px-2 py-0.5 text-[0.6875rem] font-semibold",
                    pass ? "bg-emerald-500/12 text-emerald-800 dark:text-emerald-300" : "bg-red-500/12 text-red-800 dark:text-red-300",
                  )}
                >
                  <span aria-hidden="true">{pass ? "✓ " : "✕ "}</span>
                  {check.name}
                  <span className="sr-only">{pass ? ": passes" : ": fails"}</span>
                </li>
              );
            })}
          </ul>
          {ratio < target ? (
            <button
              type="button"
              onClick={fix}
              disabled={disabled}
              className={cn(
                "justify-self-start rounded-lg bg-primary/10 px-2.5 py-1.5 text-xs font-semibold text-primary transition-colors duration-200 hover:bg-primary/15",
                focusRing,
              )}
            >
              Use the nearest colour that passes {contrastLevel}
            </button>
          ) : null}
          <p role="status" className="text-xs text-muted-foreground empty:hidden">
            {note}
          </p>
        </div>
      ) : null}
    </div>
  );

  return (
    <div ref={rootRef} className={cn("relative inline-block", className)} {...props}>
      {name ? <input type="hidden" name={name} value={output} disabled={disabled} /> : null}
      {mode === "popover" ? (
        <>
          <button
            ref={triggerRef}
            type="button"
            disabled={disabled}
            aria-haspopup="dialog"
            aria-expanded={open}
            aria-controls={open ? `${id}-panel` : undefined}
            onClick={() => setOpen((o) => !o)}
            className={cn(
              "inline-flex h-10 items-center gap-2.5 rounded-lg border border-border bg-background py-1.5 pr-3 pl-1.5 font-mono text-sm transition-colors duration-200 hover:bg-muted disabled:opacity-50",
              focusRing,
            )}
          >
            <span aria-hidden="true" className={cn("relative size-7 overflow-hidden rounded-md border border-black/10 dark:border-white/15", checker)}>
              <span className="absolute inset-0" style={{ background: `rgb(${rgb.join(" ")} / ${shown.a})` }} />
            </span>
            <span className="sr-only">{label}: </span>
            {output}
          </button>
          {open ? panel : null}
        </>
      ) : (
        panel
      )}
    </div>
  );
}

Props

PropTypeDefaultDescription
valuestring—The colour, when you control it: any hex, rgb(), hsl() or oklch() string.
defaultValuestring"#8b5cf6"The first colour when uncontrolled.
onValueChange(value: string) => void—Called as the colour changes, with the value in format.
onValueCommit(value: string) => void—Called when a change is finished: a drag ends, a key press, a swatch, Enter in the field.
format"hex" | "rgb" | "hsl" | "oklch""hex"The format of the value you get back, and the one the field starts in.
formatSelectbooleantrueLet people switch the field between formats.
alphabooleantrueShow the opacity slider. Without it colours stay opaque.
swatchesstring[]14 coloursColours one tap away; an empty list hides them.
contrastWithstring—Check the colour as text on this background (WCAG 2.2) and offer the nearest colour that passes.
contrastLevel"AA" | "AAA""AA"What the fix aims for: 4.5:1 or 7:1.
eyeDropperbooleantrueShow the screen picker where the browser has one.
mode"inline" | "popover""inline"Sit in the page, or open from a button.
namestring—Submit the value with forms.
labelstring"Colour"Names the picker and its button.
disabledbooleanfalseTurns every control off.
parseColor / formatColor / contrastRatiofunctions—The colour maths, exported for your own use.

Accessibility

  • The area, hue and opacity are ARIA sliders: arrows step by 1, Shift or PageUp/PageDown by 10, Home/End jump; each reads its value in words.
  • Typed values apply as you type; an unreadable one is marked aria-invalid and the last good colour stays.
  • Contrast results are words and symbols ("AA text: fails"), never colour alone; the fix announces the new colour in a status message.
  • In popover mode the button has aria-expanded and names the current colour; Escape or a click outside closes it and focus returns.

Changelog

  1. v1.0.0Latest

    First release.

More in Forms

All 12 in Forms
  • FormsFree

    Animated Input

    A text field whose label floats out of the way, with examples that take turns while it's empty, an error that shakes once, a tick for a valid value and sent text that drifts away.

  • FormsPro

    Date Picker

    Single dates and ranges in a keyboard-first calendar, with one-tap presets ("Last 7 days"), months that slide the way you go, min/max, unavailable days and ISO strings for forms.

  • FormsPro

    Date Time Picker

    One field for a date, a time or both that you can simply type into: it reads "tomorrow 3pm" or "dec 25 9:30", and the calendar and time wheels move to match.