'use client' import { useCallback, useSyncExternalStore } from 'react' import { isTheme, type Theme, THEME_ATTRIBUTE, THEME_STORAGE_KEY, THEME_SWITCHING_ATTRIBUTE } from './theme.js' /** The theme on (after ThemeScript); null before it ran / without a theme. */ export function readDocumentTheme(): null | Theme { if (typeof document === 'undefined') {return null} const value = document.documentElement.getAttribute(THEME_ATTRIBUTE) return isTheme(value) ? value : null } /** * Puts a theme on and remembers the choice. `transitionMs` keeps * `data-theme-switching` on for that long — style a colour transition * with it, so normal hovers stay instant. */ export function applyTheme(theme: Theme, { persist = true, transitionMs = 300 }: { persist?: boolean; transitionMs?: number } = {}): void { const root = document.documentElement if (transitionMs > 0) { root.setAttribute(THEME_SWITCHING_ATTRIBUTE, '') window.setTimeout(() => root.removeAttribute(THEME_SWITCHING_ATTRIBUTE), transitionMs) } root.setAttribute(THEME_ATTRIBUTE, theme) root.style.colorScheme = theme if (!persist) {return} try { localStorage.setItem(THEME_STORAGE_KEY, theme) } catch { // private mode / blocked storage: the theme works until reload, the choice isn't kept } } // is external state: ThemeScript sets it, another tab changes it (storage event). function subscribe(onChange: () => void): () => void { const observer = new MutationObserver(onChange) observer.observe(document.documentElement, { attributeFilter: [THEME_ATTRIBUTE], attributes: true }) const onStorage = (event: StorageEvent) => { if (event.key === THEME_STORAGE_KEY && isTheme(event.newValue)) {applyTheme(event.newValue, { persist: false, transitionMs: 0 })} } window.addEventListener('storage', onStorage) return () => { observer.disconnect() window.removeEventListener('storage', onStorage) } } const serverSnapshot = (): null | Theme => null /** * The current theme and a setter. `theme` is null on the server and during * hydration of a page without a theme — style the switch from CSS * (`[data-theme=dark] …`, Tailwind `dark:`), not from this value, so nothing * jumps after hydration. */ export function useTheme(): { setTheme: (theme: Theme) => void; theme: null | Theme; toggle: () => void } { const theme = useSyncExternalStore(subscribe, readDocumentTheme, serverSnapshot) const setTheme = useCallback((next: Theme) => applyTheme(next), []) const toggle = useCallback(() => applyTheme(readDocumentTheme() === 'dark' ? 'light' : 'dark'), []) return { setTheme, theme, toggle } }