{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"theme-toggle","type":"registry:ui","title":"Theme Toggle","description":"A sun/moon button that flips the whole page between dark and light with a View Transition reveal from the button, as a circle or staggered slats.","author":"GetUrUI <hello@geturui.dev>","dependencies":["motion","lucide-react"],"registryDependencies":[],"files":[{"path":"registry/geturui/ui/theme-toggle.tsx","type":"registry:ui","target":"components/ui/theme-toggle.tsx","content":"\"use client\";\n\nimport * as React from \"react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport { Moon, Sun } from \"lucide-react\";\nimport { cn } from \"@/lib/utils\";\n\nexport type Theme = \"dark\" | \"light\";\n\nconst STORAGE_KEY = \"theme\";\n\n/**\n * Inline this in <head> (e.g. `<script dangerouslySetInnerHTML={{ __html: themeInitScript }} />`)\n * so the saved theme applies before first paint.\n */\nexport const themeInitScript = `try{var t=localStorage.getItem(\"${STORAGE_KEY}\");if(t===\"light\"||t===\"dark\")document.documentElement.setAttribute(\"data-theme\",t)}catch(e){}`;\n\nfunction read(): Theme {\n  return document.documentElement.getAttribute(\"data-theme\") === \"light\" ? \"light\" : \"dark\";\n}\n\nfunction subscribe(cb: () => void) {\n  const mo = new MutationObserver(cb);\n  mo.observe(document.documentElement, { attributes: true, attributeFilter: [\"data-theme\"] });\n  const onStorage = (e: StorageEvent) => {\n    if (e.key === STORAGE_KEY && (e.newValue === \"light\" || e.newValue === \"dark\")) apply(e.newValue);\n  };\n  window.addEventListener(\"storage\", onStorage);\n  return () => {\n    mo.disconnect();\n    window.removeEventListener(\"storage\", onStorage);\n  };\n}\n\nfunction apply(theme: Theme) {\n  document.documentElement.setAttribute(\"data-theme\", theme);\n  try {\n    localStorage.setItem(STORAGE_KEY, theme);\n  } catch {\n    /* storage blocked — the attribute still switches */\n  }\n}\n\nlet restored = false;\nfunction restore() {\n  if (restored || typeof window === \"undefined\") return;\n  restored = true;\n  try {\n    const saved = localStorage.getItem(STORAGE_KEY);\n    if ((saved === \"light\" || saved === \"dark\") && saved !== read()) document.documentElement.setAttribute(\"data-theme\", saved);\n  } catch {\n    /* ignore */\n  }\n}\n\n/** Current theme from <html data-theme>, kept in sync across components and tabs. Persists to localStorage(\"theme\"). */\nexport function useTheme() {\n  const theme = React.useSyncExternalStore<Theme>(subscribe, read, () => \"dark\");\n  React.useEffect(restore, []);\n  const setTheme = React.useCallback((t: Theme) => apply(t), []);\n  const toggle = React.useCallback(() => apply(read() === \"dark\" ? \"light\" : \"dark\"), []);\n  return { theme, setTheme, toggle };\n}\n\nexport interface ThemeToggleProps {\n  /** circle: a circular reveal from the button. shutter: vertical slats sweep across from the button's side. */\n  variant?: \"circle\" | \"shutter\";\n  /** Length of the reveal, ms. */\n  duration?: number;\n  /** Number of slats for the shutter variant. */\n  slats?: number;\n  onThemeChange?: (theme: Theme) => void;\n  className?: string;\n}\n\ntype DocWithVT = Document & {\n  startViewTransition?: (cb: () => void) => { ready: Promise<void>; finished: Promise<void> };\n};\n\n/** Turns off the default crossfade only while this component's reveal runs. */\nconst VT_CSS =\n  \":root.theme-reveal::view-transition-old(root),:root.theme-reveal::view-transition-new(root){animation:none;mix-blend-mode:normal}\";\n\nconst ease = (t: number) => 1 - Math.pow(1 - t, 3);\n\nfunction shutterFrames(count: number, fromRight: boolean, steps = 24): Keyframe[] {\n  const stagger = 0.45; // share of the timeline spent staggering starts\n  const frames: Keyframe[] = [];\n  for (let s = 0; s <= steps; s++) {\n    const t = s / steps;\n    const pts: string[] = [];\n    for (let k = 0; k < count; k++) {\n      const order = fromRight ? count - 1 - k : k;\n      const start = (order / Math.max(1, count - 1)) * stagger;\n      const local = Math.min(1, Math.max(0, (t - start) / (1 - stagger)));\n      const p = ease(local);\n      const w = 100 / count;\n      const cx = w * k + w / 2;\n      const half = (w / 2) * p + (p > 0 ? 0.01 : 0);\n      const l = Math.max(0, cx - half).toFixed(3);\n      const r = Math.min(100, cx + half).toFixed(3);\n      pts.push(`${l}% 0%`, `${r}% 0%`, `${r}% 100%`, `${l}% 100%`, `${l}% 0%`);\n    }\n    frames.push({ clipPath: `polygon(${pts.join(\",\")})`, offset: t });\n  }\n  return frames;\n}\n\n/** Sun/moon button that flips <html data-theme> with a View Transition reveal from the button (circle or shutter slats). */\nexport function ThemeToggle({ variant = \"circle\", duration = 650, slats = 8, onThemeChange, className }: ThemeToggleProps) {\n  const { theme } = useTheme();\n  const reduce = useReducedMotion();\n  const ref = React.useRef<HTMLButtonElement>(null);\n  const busy = React.useRef(false);\n\n  async function toggle() {\n    if (busy.current) return;\n    const next: Theme = read() === \"dark\" ? \"light\" : \"dark\";\n    const doc = document as DocWithVT;\n    if (!doc.startViewTransition || reduce) {\n      apply(next);\n      onThemeChange?.(next);\n      return;\n    }\n    busy.current = true;\n    const r = ref.current?.getBoundingClientRect();\n    const x = r ? r.left + r.width / 2 : window.innerWidth / 2;\n    const y = r ? r.top + r.height / 2 : 0;\n    const root = document.documentElement;\n    root.classList.add(\"theme-reveal\");\n    try {\n      const vt = doc.startViewTransition(() => apply(next));\n      await vt.ready;\n      if (variant === \"shutter\") {\n        root.animate(shutterFrames(slats, x > window.innerWidth / 2), {\n          duration: duration * 1.15,\n          easing: \"linear\",\n          pseudoElement: \"::view-transition-new(root)\",\n        });\n      } else {\n        const radius = Math.hypot(Math.max(x, window.innerWidth - x), Math.max(y, window.innerHeight - y));\n        root.animate(\n          { clipPath: [`circle(0px at ${x}px ${y}px)`, `circle(${radius}px at ${x}px ${y}px)`] },\n          { duration, easing: \"cubic-bezier(.22,1,.36,1)\", pseudoElement: \"::view-transition-new(root)\" },\n        );\n      }\n      onThemeChange?.(next);\n      await vt.finished;\n    } catch {\n      apply(next);\n    } finally {\n      root.classList.remove(\"theme-reveal\");\n      busy.current = false;\n    }\n  }\n\n  const dark = theme === \"dark\";\n  return (\n    <>\n      <style href=\"geturui-theme-reveal\" precedence=\"default\">\n        {VT_CSS}\n      </style>\n      <motion.button\n        ref={ref}\n        type=\"button\"\n        onClick={toggle}\n        whileTap={{ scale: 0.92 }}\n        transition={{ type: \"spring\", stiffness: 520, damping: 26 }}\n        aria-label={dark ? \"Switch to light theme\" : \"Switch to dark theme\"}\n        className={cn(\n          \"relative inline-grid size-10 shrink-0 place-items-center overflow-hidden rounded-full border border-border bg-surface text-ink outline-none transition-colors duration-150 hover:border-border-strong hover:bg-surface-raised focus-visible:shadow-[var(--focus-ring)]\",\n          className,\n        )}\n      >\n        <AnimatePresence mode=\"popLayout\" initial={false}>\n          <motion.span\n            key={theme}\n            className=\"col-start-1 row-start-1 grid place-items-center\"\n            initial={reduce ? { opacity: 0 } : { opacity: 0, rotate: dark ? -90 : 90, scale: 0.4, y: 10 }}\n            animate={{ opacity: 1, rotate: 0, scale: 1, y: 0 }}\n            exit={reduce ? { opacity: 0 } : { opacity: 0, rotate: dark ? 90 : -90, scale: 0.4, y: -10 }}\n            transition={{ type: \"spring\", stiffness: 420, damping: 24 }}\n          >\n            {dark ? <Moon className=\"size-[18px]\" aria-hidden /> : <Sun className=\"size-[18px]\" aria-hidden />}\n          </motion.span>\n        </AnimatePresence>\n      </motion.button>\n    </>\n  );\n}\n"},{"path":"LICENSE-geturui.md","type":"registry:file","target":"LICENSE-geturui.md","content":"MIT License\n\nCopyright (c) 2026 geturui.com\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"}],"categories":["components","theme","dark mode","light mode","view transitions","toggle","clip-path","hook"],"meta":{"tier":"free","license":"MIT","docs":"https://geturui.com/docs/theme-toggle"}}