{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"color-swatches","type":"registry:component","title":"Color swatches","description":"The ring glides to the color you pick and the color floods the preview from that side.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/color-swatches.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useId, useRef, useState } from \"react\";\nimport { LayoutGroup, motion } from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\n\nexport type Swatch = {\n  name: string;\n  color: string;\n  // Color of the check drawn on the swatch.\n  ink: string;\n};\n\nconst LIGHT_INK = \"oklch(0.99 0 0)\";\nconst DARK_INK = \"oklch(0.22 0.01 260)\";\n\n// The one place raw colors are allowed: these swatches are the data. Muted\n// mid-tones (chroma 0.08 to 0.13) so none shouts next to the monochrome UI,\n// and all hold their own on either theme's background. Above about L 0.65 a\n// white check drops under 3:1, so those swatches take the dark ink instead.\nexport const THEME_SWATCHES: Swatch[] = [\n  { name: \"Graphite\", color: \"oklch(0.42 0.02 260)\", ink: LIGHT_INK },\n  { name: \"Clay\", color: \"oklch(0.6 0.13 35)\", ink: LIGHT_INK },\n  { name: \"Ochre\", color: \"oklch(0.78 0.12 80)\", ink: DARK_INK },\n  { name: \"Sage\", color: \"oklch(0.72 0.08 145)\", ink: DARK_INK },\n  { name: \"Teal\", color: \"oklch(0.58 0.08 210)\", ink: LIGHT_INK },\n  { name: \"Iris\", color: \"oklch(0.56 0.13 280)\", ink: LIGHT_INK },\n  { name: \"Rose\", color: \"oklch(0.7 0.1 0)\", ink: DARK_INK },\n];\n\n// No bounce: a ring that overshoots would briefly circle the wrong color.\nconst RING = { type: \"spring\", duration: 0.3, bounce: 0 } as const;\nconst ICON_SWAP = { type: \"spring\", duration: 0.3, bounce: 0 } as const;\nconst INSTANT = { duration: 0 } as const;\n\nexport function ColorSwatches({\n  swatches,\n  value,\n  onChange,\n  label,\n  className,\n}: {\n  swatches: Swatch[];\n  value: string;\n  onChange: (name: string) => void;\n  label: string;\n  className?: string;\n}) {\n  const reduceMotion = useReducedMotion();\n  // Scopes the ring's layoutId, so two pickers on a page never trade rings.\n  const group = useId();\n  const buttons = useRef<(HTMLButtonElement | null)[]>([]);\n  const selected = Math.max(\n    swatches.findIndex((s) => s.name === value),\n    0,\n  );\n\n  // Radio pattern: arrows move focus and selection together, wrapping.\n  const onKeyDown = (event: React.KeyboardEvent) => {\n    const last = swatches.length - 1;\n    const forward = selected === last ? 0 : selected + 1;\n    const back = selected === 0 ? last : selected - 1;\n    const next: Record<string, number> = {\n      ArrowRight: forward,\n      ArrowDown: forward,\n      ArrowLeft: back,\n      ArrowUp: back,\n      Home: 0,\n      End: last,\n    };\n    const index = next[event.key];\n    if (index === undefined) return;\n    event.preventDefault();\n    onChange(swatches[index].name);\n    buttons.current[index]?.focus();\n  };\n\n  return (\n    <LayoutGroup id={group}>\n      <div\n        role=\"radiogroup\"\n        aria-label={label}\n        onKeyDown={onKeyDown}\n        className={cn(\"flex items-center gap-3\", className)}\n      >\n        {swatches.map((swatch, index) => {\n          const checked = index === selected;\n          return (\n            <button\n              key={swatch.name}\n              ref={(node) => {\n                buttons.current[index] = node;\n              }}\n              type=\"button\"\n              role=\"radio\"\n              aria-checked={checked}\n              aria-label={swatch.name}\n              tabIndex={checked ? 0 : -1}\n              onClick={() => onChange(swatch.name)}\n              style={{ backgroundColor: swatch.color, color: swatch.ink }}\n              className={cn(\n                \"relative flex size-8 touch-manipulation items-center justify-center rounded-full outline-hidden transition-[scale] duration-150 ease-out select-none active:scale-[0.96] motion-reduce:transition-none\",\n                // The image outline recipe, so a light swatch keeps its edge\n                // on a light background and a dark one on a dark background.\n                \"shadow-[inset_0_0_0_1px_oklch(0_0_0/0.1)] dark:shadow-[inset_0_0_0_1px_oklch(1_0_0/0.1)]\",\n                // Clears the 4px ring with a 2px gap.\n                \"focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-[6px] focus-visible:outline-foreground\",\n                // Grows the hit area to 40px without growing the circle.\n                \"after:absolute after:-inset-1 after:rounded-full\",\n              )}\n            >\n              {checked && (\n                <motion.span\n                  layoutId=\"ring\"\n                  aria-hidden\n                  transition={reduceMotion ? INSTANT : RING}\n                  // 2px gap, then a 2px ring: a 32px swatch in a 40px ring.\n                  className=\"pointer-events-none absolute -inset-1 rounded-full border-2 border-foreground\"\n                />\n              )}\n              <motion.svg\n                aria-hidden\n                viewBox=\"0 0 16 16\"\n                className=\"size-4\"\n                fill=\"none\"\n                stroke=\"currentColor\"\n                // Heavier than the lab's usual 1.5: it sits alone on\n                // saturated color, with no text beside it to match.\n                strokeWidth={2}\n                strokeLinecap=\"round\"\n                strokeLinejoin=\"round\"\n                initial={false}\n                animate={\n                  checked\n                    ? { scale: 1, opacity: 1, filter: \"blur(0px)\" }\n                    : reduceMotion\n                      ? { scale: 1, opacity: 0, filter: \"blur(0px)\" }\n                      : { scale: 0.25, opacity: 0, filter: \"blur(4px)\" }\n                }\n                transition={ICON_SWAP}\n              >\n                <path d=\"m3.5 8.5 3 3 6-7\" />\n              </motion.svg>\n            </button>\n          );\n        })}\n      </div>\n    </LayoutGroup>\n  );\n}\n\nconst EASE_OUT = [0.23, 1, 0.32, 1] as const;\n// Each accent surface floods in 300ms. They start 45ms apart, so the color\n// runs through the preview in the order you read it (about 435ms end to\n// end); decorative, and nothing waits on it.\nconst FLOOD_MS = 300;\nconst FLOOD_STAGGER = 45;\n\ntype Layer = { id: number; color: string; origin: number };\n\n// Paints a surface in the chosen color by spreading it as a circle from the\n// side the swatch sits on: pick Graphite and it pours in from the left,\n// Rose from the right. The old color stays underneath until covered.\nfunction Flood({\n  color,\n  origin,\n  order,\n  className,\n  children,\n}: {\n  color: string;\n  origin: number;\n  order: number;\n  className?: string;\n  children?: React.ReactNode;\n}) {\n  const reduceMotion = useReducedMotion();\n  const [layers, setLayers] = useState<Layer[]>([{ id: 0, color, origin }]);\n  const [shown, setShown] = useState(color);\n  if (color !== shown) {\n    setShown(color);\n    // Three is enough for rapid picks: the newest spreads over the previous\n    // one, which may itself still be spreading over the settled color.\n    setLayers((l) => [...l.slice(-2), { id: l[l.length - 1].id + 1, color, origin }]);\n  }\n  const delay = (order * FLOOD_STAGGER) / 1000;\n\n  return (\n    <span className={cn(\"relative isolate overflow-hidden\", className)}>\n      {layers.map((layer) => {\n        const at = `${layer.origin * 100}% 50%`;\n        return (\n          <motion.span\n            key={layer.id}\n            aria-hidden\n            className=\"absolute inset-0\"\n            style={{ backgroundColor: layer.color }}\n            initial={\n              layer.id === 0\n                ? false\n                : reduceMotion\n                  ? { opacity: 0 }\n                  : { clipPath: `circle(0% at ${at})` }\n            }\n            // 150% of a circle's reference radius clears the far corner of\n            // any of these shapes, even from an edge origin.\n            animate={\n              reduceMotion ? { opacity: 1 } : { clipPath: `circle(150% at ${at})` }\n            }\n            transition={{ duration: FLOOD_MS / 1000, ease: EASE_OUT, delay }}\n          />\n        );\n      })}\n      {children}\n    </span>\n  );\n}\n\nexport default function ColorSwatchesDemo() {\n  const [value, setValue] = useState(\"Clay\");\n  const index = Math.max(\n    THEME_SWATCHES.findIndex((s) => s.name === value),\n    0,\n  );\n  const swatch = THEME_SWATCHES[index];\n  const origin = index / (THEME_SWATCHES.length - 1);\n  const flood = { color: swatch.color, origin };\n\n  return (\n    <div className=\"flex w-[min(380px,100%)] flex-col items-center gap-6\">\n      <ColorSwatches\n        swatches={THEME_SWATCHES}\n        value={value}\n        onChange={setValue}\n        label=\"Theme color\"\n      />\n      {/* A preview, not a real control: the chosen color applied to a small\n          settings card. Screen readers already hear the choice from the\n          radio, so the whole card is hidden from them. */}\n      <div\n        aria-hidden\n        className=\"flex w-full flex-col gap-5 rounded-[20px] bg-background p-5 shadow-raised\"\n      >\n        <div className=\"flex items-center justify-between\">\n          <span className=\"flex h-7 items-center gap-2 rounded-full bg-muted pr-3 pl-2.5 text-[13px] font-medium text-foreground\">\n            <Flood {...flood} order={0} className=\"size-2.5 rounded-full\" />\n            {/* Every name shares one grid cell, so the tag keeps the width of\n                the longest and never jumps; the new one blurs in. */}\n            <span className=\"grid\">\n              {THEME_SWATCHES.map((s) => (\n                <span\n                  key={s.name}\n                  className={cn(\n                    \"col-start-1 row-start-1 transition-[opacity,filter,translate] ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-[opacity]\",\n                    s.name === value\n                      ? \"translate-y-0 opacity-100 blur-[0px] duration-200\"\n                      : \"translate-y-0.5 opacity-0 blur-[4px] duration-150 motion-reduce:translate-y-0\",\n                  )}\n                >\n                  {s.name}\n                </span>\n              ))}\n            </span>\n          </span>\n          {/* An \"on\" switch: 40 by 24 track, 18px knob with a 3px inset. The\n              knob is raw white on purpose: it sits on the swatch color, not\n              on the page, so it must not flip with the theme. */}\n          <Flood {...flood} order={1} className=\"flex h-6 w-10 items-center rounded-full p-[3px]\">\n            <span className=\"relative ml-auto size-[18px] rounded-full bg-[oklch(0.99_0_0)] shadow-[0_1px_2px_oklch(0_0_0/0.2)]\" />\n          </Flood>\n        </div>\n\n        <div className=\"flex flex-col gap-2\">\n          <div className=\"flex justify-between text-[13px]\">\n            <span className=\"text-muted-foreground\">Storage</span>\n            <span className=\"font-medium text-foreground tabular-nums\">64%</span>\n          </div>\n          <span className=\"h-1.5 w-full overflow-hidden rounded-full bg-muted\">\n            <Flood {...flood} order={2} className=\"block h-full w-[64%] rounded-full\" />\n          </span>\n        </div>\n\n        <div className=\"flex justify-end gap-2\">\n          <span className=\"flex h-9 items-center rounded-full px-4 text-sm font-medium text-muted-foreground\">\n            Cancel\n          </span>\n          <Flood\n            {...flood}\n            order={3}\n            className=\"flex h-9 items-center rounded-full px-4 text-sm font-medium\"\n          >\n            {/* The ink changes as the flood arrives, not before it. */}\n            <span\n              style={{\n                color: swatch.ink,\n                transitionDelay: `${3 * FLOOD_STAGGER + 60}ms`,\n              }}\n              className=\"relative transition-[color] duration-200 ease-out motion-reduce:transition-none\"\n            >\n              Save changes\n            </span>\n          </Flood>\n        </div>\n      </div>\n    </div>\n  );\n}\n"},{"path":"hooks/use-reduced-motion.ts","type":"registry:hook","target":"hooks/use-reduced-motion.ts","content":"\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\n\n// Motion's useReducedMotion reads the media query on the very first client\n// render, but the server can't know it, so every component that renders\n// differently under reduced motion broke hydration for those users. This\n// reports false during hydration, matching the server HTML, then the real\n// preference straight after, and follows it if it changes.\nconst query = \"(prefers-reduced-motion: reduce)\";\n\nfunction subscribe(onChange: () => void) {\n  const media = window.matchMedia(query);\n  media.addEventListener(\"change\", onChange);\n  return () => media.removeEventListener(\"change\", onChange);\n}\n\nexport function useReducedMotion() {\n  return useSyncExternalStore(\n    subscribe,\n    () => window.matchMedia(query).matches,\n    () => false,\n  );\n}\n"}],"cssVars":{"light":{"shadow-raised":"0 0 0 1px oklch(0 0 0 / 0.06), 0 1px 2px oklch(0 0 0 / 0.06), 0 6px 16px -6px oklch(0 0 0 / 0.12)"},"dark":{"shadow-raised":"0 0 0 1px oklch(1 0 0 / 0.08), 0 1px 2px oklch(0 0 0 / 0.4), 0 6px 16px -6px oklch(0 0 0 / 0.6)"},"theme":{"shadow-raised":"var(--shadow-raised)"}},"categories":["inputs"],"docs":"From ui lab: https://lab.xevrion.dev/lab/color-swatches"}