Files
personal/lib/shellMedia.tsx
T
virtheart 1860bc9f41 fix: 主题/声音水合错位 — store 水合移入 effect + getServerSnapshot 固定 SSR 快照
- 模块求值时立即读 localStorage/matchMedia 并把实时快照同时当
  getServerSnapshot 用,导致水合首帧 aria-label(Theme: dark /
  Sound playing)与 SSR 渲染的 light/paused 属性不一致
- 改为 useShellMedia 内 useEffect 首帧后才 hydrateIfNeeded()(对齐原站
  mounted flag 模式),getServerSnapshot 返回固定的 light/paused 快照;
  setTheme/setSoundEnabled 前补 hydrateIfNeeded 防止未挂载就写入
- CDP 双场景验证:预存 dark+sound=on 刷新、无存储全新加载均 0 console 错误,
  水合后 aria/class/背景全部落到正确值
2026-09-02 15:36:18 +08:00

204 lines
5.5 KiB
TypeScript

"use client";
import { useEffect, useSyncExternalStore } from "react";
/**
* Shell media state (theme + sound) — 1:1 port of the original
* ThemeModeProvider (chunk 2689132c4e070b68.js module 90975) + ShellMedia
* sound store (module 23525):
*
* - theme ∈ {light, dark, system}, persisted to localStorage "theme"
* (original key, kept verbatim for parity); default "light".
* - resolvedTheme = theme === "system"
* ? (matchMedia("(prefers-color-scheme: dark)").matches ? dark : light)
* : theme;
* <html> gets BOTH the resolved class (light/dark) and the setting, so
* CSS tokens flip via the .dark block in globals.css.
* - "system" follows OS changes live (original matchMedia change listener).
* - soundEnabled persisted to localStorage "sound" ("on"/"off", original
* keys).
*
* Implemented as a module-singleton external store (useSyncExternalStore)
* instead of the original context: the header and the canvas components
* (DotOverlay, LoadingCurtain, GlassModels) live in different trees and the
* canvas reads theme without re-mounting.
*/
export type ThemeSetting = "light" | "dark" | "system";
export type ResolvedTheme = "light" | "dark";
const THEME_KEY = "theme";
const SOUND_KEY = "sound";
const SETTINGS: ThemeSetting[] = ["light", "dark", "system"];
type ShellMediaState = {
theme: ThemeSetting;
resolvedTheme: ResolvedTheme;
soundEnabled: boolean;
};
let state: ShellMediaState = {
theme: "light",
resolvedTheme: "light",
soundEnabled: false,
};
const listeners = new Set<() => void>();
let hydrated = false;
let mediaQuery: MediaQueryList | null = null;
function emit() {
for (const l of listeners) l();
}
function setState(patch: Partial<ShellMediaState>) {
state = { ...state, ...patch };
emit();
}
function resolve(theme: ThemeSetting): ResolvedTheme {
if (theme !== "system") return theme;
return window.matchMedia("(prefers-color-scheme: dark)").matches
? "dark"
: "light";
}
/** Mirror the resolved theme onto <html> (original: classList + remove/add). */
function applyDocument(theme: ThemeSetting) {
const el = document.documentElement;
const resolved = resolve(theme);
el.classList.remove("light", "dark");
el.classList.add(resolved);
el.dataset.themeSetting = theme;
}
function readStored(key: string): string | null {
try {
return window.localStorage.getItem(key);
} catch {
return null;
}
}
function writeStored(key: string, value: string) {
try {
window.localStorage.setItem(key, value);
} catch {}
}
function hydrate() {
if (hydrated || typeof window === "undefined") return;
hydrated = true;
const stored = readStored(THEME_KEY);
const theme: ThemeSetting = SETTINGS.includes(stored as ThemeSetting)
? (stored as ThemeSetting)
: "light";
mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
mediaQuery.addEventListener("change", onSystemChange);
state = { ...state, theme, resolvedTheme: resolve(theme) };
applyDocument(theme);
state = {
...state,
soundEnabled: readStored(SOUND_KEY) === "on",
};
}
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");
applyDocument("system");
setState({ resolvedTheme: resolved });
}
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);
};
}
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;
} {
// 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);
}
// Keep the actions on the same object shape as the original hook return.
function useSnapshotWithActions(
snapshot: ShellMediaState
): ShellMediaState & {
setTheme: (next: ThemeSetting) => void;
setSoundEnabled: (next: boolean) => void;
} {
return {
...snapshot,
setTheme,
setSoundEnabled,
};
}
export function getResolvedTheme(): ResolvedTheme {
return state.resolvedTheme;
}
export function subscribeShellMedia(listener: () => void) {
return subscribe(listener);
}
export function useResolvedTheme(): ResolvedTheme {
const s = useShellMedia();
return s.resolvedTheme;
}
export type ShellMedia = ReturnType<typeof useShellMedia>;