{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "theme-provider",
  "type": "registry:ui",
  "title": "Theme Provider",
  "description": "Holds the theme (light or dark, roundness, highlight colour), applies it to the page, remembers the visitor's choice, and avoids a flash of the wrong theme.",
  "categories": [
    "ui"
  ],
  "dependencies": [],
  "registryDependencies": [
    "@rivier-ui/theme"
  ],
  "files": [
    {
      "path": "registry/ui/theme-provider.tsx",
      "type": "registry:ui",
      "target": "components/ui/theme-provider.tsx",
      "content": "\"use client\";\n/**\n * @name theme-provider\n * @category ui\n * @description Holds the theme (light or dark, roundness, highlight colour), applies it to the page, remembers the visitor's choice, and avoids a flash of the wrong theme.\n * @when Once, around the app in the root layout, when visitors or the product can change the theme. For a fixed theme, skip it and set the attributes on <html> by hand.\n * @example\n * // app/layout.tsx\n * <html lang=\"en\" suppressHydrationWarning>\n *   <head><ThemeScript defaults={{ mode: \"system\", radius: \"md\", accent: \"blue\" }} /></head>\n *   <body>\n *     <ThemeProvider defaults={{ mode: \"system\", radius: \"md\", accent: \"blue\" }}>{children}</ThemeProvider>\n *   </body>\n * </html>\n *\n * // anywhere below\n * const { theme, setTheme } = useTheme();\n * setTheme({ mode: \"dark\" });\n * setTheme({ accent: { hue: 262, chroma: 0.19 } });\n */\nimport { createContext, useCallback, useContext, useEffect, useMemo, useState, useSyncExternalStore, type ReactNode } from \"react\";\n\nexport const THEME_MODES = [\"light\", \"dark\", \"system\"] as const;\nexport const THEME_RADII = [\"none\", \"sm\", \"md\", \"lg\", \"full\"] as const;\nexport const THEME_ACCENTS = [\"teal\", \"blue\", \"violet\", \"pink\", \"red\", \"orange\", \"amber\", \"green\", \"ink\"] as const;\n\nexport type ThemeMode = (typeof THEME_MODES)[number];\nexport type ThemeRadius = (typeof THEME_RADII)[number];\nexport type ThemeAccentName = (typeof THEME_ACCENTS)[number];\n/** A named highlight colour, or any colour as an OKLCH hue (0 to 360) and chroma (0 to about 0.25). */\nexport type ThemeAccent = ThemeAccentName | { hue: number; chroma: number };\n\nexport type Theme = { mode: ThemeMode; radius: ThemeRadius; accent: ThemeAccent };\n\nconst STORAGE_KEY = \"rivier-ui:theme\";\nconst BASE: Theme = { mode: \"system\", radius: \"sm\", accent: \"teal\" };\n\ntype ThemeContextValue = {\n  theme: Theme;\n  /** The mode in effect: \"system\" resolved to what the device asks for. */\n  resolvedMode: \"light\" | \"dark\";\n  setTheme: (change: Partial<Theme>) => void;\n  /** Forget the visitor's choice and go back to the defaults. */\n  resetTheme: () => void;\n};\n\nconst ThemeContext = createContext<ThemeContextValue | null>(null);\n\n/** Applies a theme to an element by setting the attributes and variables the stylesheet reads. */\nfunction apply(element: HTMLElement, theme: Theme, systemDark: boolean): void {\n  const dark = theme.mode === \"dark\" || (theme.mode === \"system\" && systemDark);\n  element.dataset[\"theme\"] = dark ? \"dark\" : \"light\";\n  element.classList.toggle(\"dark\", dark);\n  element.dataset[\"radius\"] = theme.radius;\n  if (typeof theme.accent === \"string\") {\n    element.dataset[\"accent\"] = theme.accent;\n    element.style.removeProperty(\"--accent-hue\");\n    element.style.removeProperty(\"--accent-chroma\");\n  } else {\n    delete element.dataset[\"accent\"];\n    element.style.setProperty(\"--accent-hue\", String(theme.accent.hue));\n    element.style.setProperty(\"--accent-chroma\", String(theme.accent.chroma));\n  }\n}\n\n/** The stored choice, as text. Read through useSyncExternalStore, so it is compared by value and never set in an effect. */\nfunction readStored(): string | null {\n  try {\n    return localStorage.getItem(STORAGE_KEY);\n  } catch {\n    // Storage can be unavailable (private mode, a sandboxed frame).\n    return null;\n  }\n}\n\nfunction parseStored(raw: string | null): Partial<Theme> {\n  if (!raw) return {};\n  try {\n    const value: unknown = JSON.parse(raw);\n    return value !== null && typeof value === \"object\" ? (value as Partial<Theme>) : {};\n  } catch {\n    return {};\n  }\n}\n\n/** Providers on this page that follow the stored choice. Another tab's change arrives as a \"storage\" event. */\nconst storedListeners = new Set<() => void>();\n\nfunction subscribeStored(onChange: () => void): () => void {\n  const onStorage = (event: StorageEvent): void => {\n    if (event.key === null || event.key === STORAGE_KEY) onChange();\n  };\n  storedListeners.add(onChange);\n  window.addEventListener(\"storage\", onStorage);\n  return () => {\n    storedListeners.delete(onChange);\n    window.removeEventListener(\"storage\", onStorage);\n  };\n}\n\n/** Writes (or, with null, forgets) the choice and tells every provider. False when storage is unavailable. */\nfunction writeStored(theme: Theme | null): boolean {\n  try {\n    if (theme) localStorage.setItem(STORAGE_KEY, JSON.stringify(theme));\n    else localStorage.removeItem(STORAGE_KEY);\n  } catch {\n    return false;\n  }\n  for (const listener of storedListeners) listener();\n  return true;\n}\n\nconst DARK_QUERY = \"(prefers-color-scheme: dark)\";\n\nfunction subscribeSystemDark(onChange: () => void): () => void {\n  const media = window.matchMedia(DARK_QUERY);\n  media.addEventListener(\"change\", onChange);\n  return () => media.removeEventListener(\"change\", onChange);\n}\n\nconst systemDarkOnClient = (): boolean => window.matchMedia(DARK_QUERY).matches;\nconst systemDarkOnServer = (): boolean => false;\nconst noSubscription = (): (() => void) => () => {};\nconst nothingStored = (): null => null;\n\nexport type ThemeProviderProps = {\n  children: ReactNode;\n  /** The theme before the visitor chooses. Give ThemeScript the same value. */\n  defaults?: Partial<Theme>;\n  /** Set false to keep the theme for this visit only. */\n  persist?: boolean;\n};\n\nexport function ThemeProvider({ children, defaults, persist = true }: ThemeProviderProps) {\n  const initial = useMemo<Theme>(() => ({ ...BASE, ...defaults }), [defaults]);\n\n  // The device's preference and the stored choice live outside React and are only known in the browser:\n  // they are read as external stores. The server and the hydration render see the defaults, then the page\n  // renders again with the real values (ThemeScript has already set the attributes, so nothing flashes).\n  const systemDark = useSyncExternalStore(subscribeSystemDark, systemDarkOnClient, systemDarkOnServer);\n  const storedRaw = useSyncExternalStore(persist ? subscribeStored : noSubscription, persist ? readStored : nothingStored, nothingStored);\n  // The choice for this visit only: used when persist is false, or when storage is unavailable.\n  const [session, setSession] = useState<Partial<Theme>>({});\n\n  const theme = useMemo<Theme>(() => ({ ...initial, ...parseStored(storedRaw), ...session }), [initial, storedRaw, session]);\n\n  useEffect(() => {\n    apply(document.documentElement, theme, systemDark);\n  }, [theme, systemDark]);\n\n  const setTheme = useCallback(\n    (change: Partial<Theme>): void => {\n      if (persist && writeStored({ ...initial, ...parseStored(readStored()), ...change })) return;\n      setSession((current) => ({ ...current, ...change }));\n    },\n    [initial, persist],\n  );\n\n  const resetTheme = useCallback((): void => {\n    writeStored(null);\n    setSession({});\n  }, []);\n\n  const value = useMemo<ThemeContextValue>(\n    () => ({ theme, resolvedMode: theme.mode === \"dark\" || (theme.mode === \"system\" && systemDark) ? \"dark\" : \"light\", setTheme, resetTheme }),\n    [theme, systemDark, setTheme, resetTheme],\n  );\n\n  return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;\n}\n\nexport function useTheme(): ThemeContextValue {\n  const value = useContext(ThemeContext);\n  if (!value) throw new Error(\"useTheme must be used inside <ThemeProvider>.\");\n  return value;\n}\n\n/**\n * Put in <head>. Applies the stored (or default) theme before the page paints, so there is no flash.\n * It is a small inline script; it reads only this library's own storage key.\n */\nexport function ThemeScript({ defaults }: { defaults?: Partial<Theme> }) {\n  const code = `(function(){try{var d=${JSON.stringify({ ...BASE, ...defaults })},s={};try{s=JSON.parse(localStorage.getItem(${JSON.stringify(STORAGE_KEY)})||\"{}\")}catch(e){}var t=Object.assign({},d,s),e=document.documentElement,k=t.mode===\"dark\"||(t.mode===\"system\"&&matchMedia(\"(prefers-color-scheme: dark)\").matches);e.dataset.theme=k?\"dark\":\"light\";e.classList.toggle(\"dark\",k);e.dataset.radius=t.radius;if(typeof t.accent===\"string\"){e.dataset.accent=t.accent}else if(t.accent){e.style.setProperty(\"--accent-hue\",t.accent.hue);e.style.setProperty(\"--accent-chroma\",t.accent.chroma)}}catch(e){}})()`;\n  // \"<\" is escaped so that nothing in the defaults can close the script element.\n  return <script dangerouslySetInnerHTML={{ __html: code.replace(/</g, \"\\\\u003c\") }} />;\n}\n"
    }
  ],
  "meta": {
    "category": "ui",
    "when": "Once, around the app in the root layout, when visitors or the product can change the theme. For a fixed theme, skip it and set the attributes on <html> by hand.",
    "example": "// app/layout.tsx\n<html lang=\"en\" suppressHydrationWarning>\n  <head><ThemeScript defaults={{ mode: \"system\", radius: \"md\", accent: \"blue\" }} /></head>\n  <body>\n    <ThemeProvider defaults={{ mode: \"system\", radius: \"md\", accent: \"blue\" }}>{children}</ThemeProvider>\n  </body>\n</html>\n\n// anywhere below\nconst { theme, setTheme } = useTheme();\nsetTheme({ mode: \"dark\" });\nsetTheme({ accent: { hue: 262, chroma: 0.19 } });",
    "client": true
  }
}
