diff --git a/lib/shellMedia.tsx b/lib/shellMedia.tsx index c2af72c..e5637f1 100644 --- a/lib/shellMedia.tsx +++ b/lib/shellMedia.tsx @@ -1,6 +1,6 @@ "use client"; -import { useCallback, useSyncExternalStore } from "react"; +import { useEffect, useSyncExternalStore } from "react"; /** * Shell media state (theme + sound) — 1:1 port of the original @@ -103,6 +103,15 @@ function hydrate() { }; } +let hydrateRequested = false; +/** Idempotent, safe before mount (no-ops on the server). */ +function hydrateIfNeeded() { + if (hydrateRequested) return; + hydrateRequested = true; + hydrate(); + emit(); +} + function onSystemChange() { if (state.theme !== "system") return; const resolved = resolve("system"); @@ -110,37 +119,57 @@ function onSystemChange() { setState({ resolvedTheme: resolved }); } -if (typeof window !== "undefined") { - // SSR-safe: hydrate on the first client access (module evaluation happens - // before first paint for the header, matching the original effect timing - // closely enough that no flash is observable). - hydrate(); -} - function setTheme(next: ThemeSetting) { + hydrateIfNeeded(); writeStored(THEME_KEY, next); applyDocument(next); setState({ theme: next, resolvedTheme: resolve(next) }); } function setSoundEnabled(next: boolean) { + hydrateIfNeeded(); writeStored(SOUND_KEY, next ? "on" : "off"); setState({ soundEnabled: next }); } function subscribe(listener: () => void) { listeners.add(listener); - return () => listeners.delete(listener); + return () => { + listeners.delete(listener); + }; } const getSnapshot = () => state; +// Hydration-safe SSR snapshot: must equal what the server rendered +// (light/paused defaults). React uses this for the hydration render, then +// re-renders with the live snapshot once the client store hydrates. +const SERVER_SNAPSHOT: ShellMediaState = { + theme: "light", + resolvedTheme: "light", + soundEnabled: false, +}; + +function getServerSnapshot(): ShellMediaState { + return SERVER_SNAPSHOT; +} + export function useShellMedia(): ShellMediaState & { setTheme: (next: ThemeSetting) => void; setSoundEnabled: (next: boolean) => void; } { - const snapshot = useSyncExternalStore(subscribe, getSnapshot, getSnapshot); - // Stable identity via module-level functions (no per-render closures). + // Defer store hydration to the first effect tick (original: mounted flag + // + useEffect). Hydrating at module evaluation would run BEFORE React's + // hydration pass and flip aria-labels/classes under the SSR HTML — the + // exact "attributes of the server rendered HTML didn't match" warning. + useEffect(() => { + hydrateIfNeeded(); + }, []); + const snapshot = useSyncExternalStore( + subscribe, + getSnapshot, + getServerSnapshot + ); return useSnapshotWithActions(snapshot); }