| 1 | "use client"; |
| 2 | |
| 3 | import { useTheme } from "next-themes"; |
| 4 | import { useEffect, useState |
| 5 | |
| 6 | import { |
| 7 | applyCustomThemeVars, |
| 8 | clearCustomThemeVars, |
| 9 | CUSTOM_THEME_KEY, |
| 10 | DEFAULT_CUSTOM_THEME, |
| 11 | loadCustomTheme, |
| 12 | themeKind, |
| 13 | type CustomThemeVars, |
| 14 | } from "@/lib/themes"; |
| 15 | |
| 16 | export const CUSTOM_THEME_UPDATED_EVENT = |
| 17 | |
| 18 | export function useCustomTheme() |
| 19 | const [custom, |
| 20 | const [hydrated, |
| 21 | |
| 22 | useEffect(() => |
| 23 | // hydration-safe: localStorage only exists in the browser, so the stored |
| 24 | // custom theme has to be synced after mount. |
| 25 | // eslint-disable-next-line react-hooks/set-state-in-effect |
| 26 | setCustom(loadCustomTheme()); |
| 27 | setHydrated(true); |
| 28 | }, []); |
| 29 | |
| 30 | useEffect(() => |
| 31 | const reload = |
| 32 | const onStorage = |
| 33 | if (e.key |
| 34 | }; |
| 35 | window.addEventListener("storage |
| 36 | window.addEventListener(CUSTOM_THEME_UPDATED_EVENT |
| 37 | return () => |
| 38 | window.removeEventListener("storage |
| 39 | window.removeEventListener(CUSTOM_THEME_UPDATED_EVENT |
| 40 | }; |
| 41 | }, []); |
| 42 | |
| 43 | return { custom, |
| 44 | } |
| 45 | |
| 46 | /** Keeps Tailwind `dark:` utilities working for every dark-kind theme by mirroring the `dark` class, and applies user custom-theme variables. */ |
| 47 | export function ThemeEffects() |
| 48 | const { theme, |
| 49 | const { custom |
| 50 | |
| 51 | useEffect(() => |
| 52 | const active = |
| 53 | const kind = |
| 54 | const root = |
| 55 | |
| 56 | if (active === |
| 57 | applyCustomThemeVars(custom); |
| 58 | } else { |
| 59 | clearCustomThemeVars(); |
| 60 | } |
| 61 | |
| 62 | // next-themes owns the theme class itself; we only mirror `dark` so `dark:` variants keep working on dark-kind themes like vesper. |
| 63 | if (active !== |
| 64 | if (kind === |
| 65 | else root.classList. |
| 66 | } |
| 67 | }, [theme, |
| 68 | |
| 69 | return null; |
| 70 | } |
| 71 | |
| 72 | export function useActiveThemeKind() |
| 73 | const { theme, |
| 74 | const { custom |
| 75 | const active = |
| 76 | return themeKind(active |
| 77 | } |