{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "theme-color",
  "type": "registry:lib",
  "title": "Theme Color",
  "description": "Resolves a theme CSS variable such as \"--highlight\" to an rgb() string that three.js and canvas code can parse, and re-reads it when the theme changes.",
  "categories": [
    "lib"
  ],
  "dependencies": [],
  "registryDependencies": [
    "@rivier-ui/theme"
  ],
  "files": [
    {
      "path": "registry/lib/theme-color.ts",
      "type": "registry:lib",
      "target": "lib/theme-color.ts",
      "content": "\"use client\";\n/**\n * @name theme-color\n * @category lib\n * @description Resolves a theme CSS variable such as \"--highlight\" to an rgb() string that three.js and canvas code can parse, and re-reads it when the theme changes.\n * @when Anything that cannot use a Tailwind class or `var()`: three.js materials, canvas drawing. In markup use the token classes (`bg-primary`, `fill-chart-1`) instead.\n * @example\n * const { \"--highlight\": highlight, \"--foreground\": ink } = useThemeColors([\"--highlight\", \"--foreground\"]);\n * material.color.set(highlight);\n *\n * // Outside React:\n * const border = readThemeColor(\"--border\");\n */\nimport { useEffect, useState } from \"react\";\n\n/** What is returned on the server, and when a variable does not exist or the browser cannot resolve it. */\nconst NEUTRAL = \"rgb(128, 128, 128)\";\n/** The canvas keeps this when it is handed a colour it cannot parse; it is how a failed parse is detected. */\nconst SENTINEL = \"rgb(1, 2, 3)\";\nconst WATCHED = [\"class\", \"data-theme\", \"data-accent\", \"style\"];\n\nlet pixel: CanvasRenderingContext2D | null | undefined;\n\n/** Any CSS colour the browser understands (oklch included) to \"rgb(r, g, b)\", by painting one pixel and reading it back. */\nfunction toRgb(css: string): string | null {\n  if (pixel === undefined) {\n    const canvas = document.createElement(\"canvas\");\n    canvas.width = 1;\n    canvas.height = 1;\n    pixel = canvas.getContext(\"2d\", { willReadFrequently: true });\n  }\n  if (!pixel) return null;\n  pixel.fillStyle = SENTINEL;\n  const before = pixel.fillStyle;\n  pixel.fillStyle = css;\n  if (pixel.fillStyle === before && css !== SENTINEL) return null;\n  pixel.clearRect(0, 0, 1, 1);\n  pixel.fillRect(0, 0, 1, 1);\n  const data = pixel.getImageData(0, 0, 1, 1).data;\n  const alpha = (data[3] ?? 0) / 255;\n  if (alpha === 0) return null;\n  // The canvas stores premultiplied colour: divide the alpha back out. The alpha itself is dropped,\n  // because THREE.Color has no alpha channel.\n  const channel = (index: number): number => Math.min(255, Math.round((data[index] ?? 0) / alpha));\n  return `rgb(${channel(0)}, ${channel(1)}, ${channel(2)})`;\n}\n\n/**\n * Resolves a CSS variable (\"--highlight\") to \"rgb(r, g, b)\" as it applies to `element` (default: <html>), so\n * a part of the page themed with its own `data-accent` resolves to its own colour. A value that is not a\n * variable name is treated as a CSS colour and converted the same way. Alpha is dropped.\n */\nexport function readThemeColor(name: string, element?: Element): string {\n  if (typeof document === \"undefined\") return NEUTRAL;\n  const target = element ?? document.documentElement;\n  // A probe needs a parent that renders children: not a canvas, and <body> rather than <html>.\n  const host = target instanceof HTMLCanvasElement ? (target.parentElement ?? document.body) : target === document.documentElement ? (document.body ?? target) : target;\n  const isVariable = name.startsWith(\"--\");\n  if (isVariable && getComputedStyle(host).getPropertyValue(name).trim() === \"\") return NEUTRAL;\n  // The browser, not this code, works out var() and calc() inside the token: a hidden element takes the\n  // colour and its computed value is what gets painted.\n  const probe = document.createElement(\"span\");\n  probe.setAttribute(\"aria-hidden\", \"true\");\n  probe.style.cssText = \"position:absolute;width:0;height:0;visibility:hidden;pointer-events:none\";\n  probe.style.color = isVariable ? `var(${name})` : name;\n  host.appendChild(probe);\n  const computed = getComputedStyle(probe).color;\n  probe.remove();\n  return toRgb(computed) ?? NEUTRAL;\n}\n\nfunction readAll<const T extends readonly string[]>(names: T, element?: Element | null): Record<T[number], string> {\n  const colors: Record<string, string> = {};\n  for (const name of names) colors[name] = readThemeColor(name, element ?? undefined);\n  return colors as Record<T[number], string>;\n}\n\n/**\n * The resolved colours for a list of variables, keyed by name, read again whenever the theme changes\n * (`class`, `data-theme`, `data-accent` or `style` on <html>, and on `element` when one is given).\n * On the server every colour is a neutral grey: do not print these values into server-rendered markup.\n */\nexport function useThemeColors<const T extends readonly string[]>(names: T, element?: Element | null): Record<T[number], string> {\n  const key = names.join(\"|\");\n  const [state, setState] = useState(() => ({ key, element, colors: readAll(names, element) }));\n  let current = state;\n  // Asked for other variables, or for another element: read at once, so no render sees a missing colour.\n  if (state.key !== key || state.element !== element) {\n    current = { key, element, colors: readAll(names, element) };\n    setState(current);\n  }\n\n  useEffect(() => {\n    const list = key.split(\"|\") as unknown as T;\n    const update = (): void =>\n      setState((previous) => {\n        const next = readAll(list, element);\n        return previous.key === key && previous.element === element && list.every((name: T[number]) => previous.colors[name] === next[name]) ? previous : { key, element, colors: next };\n      });\n    update();\n    const observer = new MutationObserver(update);\n    observer.observe(document.documentElement, { attributes: true, attributeFilter: WATCHED });\n    // A themed part of the page: watch the elements between it and <html> too.\n    for (let node = element?.parentElement; node && node !== document.documentElement; node = node.parentElement) {\n      observer.observe(node, { attributes: true, attributeFilter: WATCHED });\n    }\n    return () => observer.disconnect();\n  }, [key, element]);\n\n  return current.colors;\n}\n"
    }
  ],
  "meta": {
    "category": "lib",
    "when": "Anything that cannot use a Tailwind class or `var()`: three.js materials, canvas drawing. In markup use the token classes (`bg-primary`, `fill-chart-1`) instead.",
    "example": "const { \"--highlight\": highlight, \"--foreground\": ink } = useThemeColors([\"--highlight\", \"--foreground\"]);\nmaterial.color.set(highlight);\n\n// Outside React:\nconst border = readThemeColor(\"--border\");",
    "client": true
  }
}
