72 lines
2.6 KiB
TypeScript
72 lines
2.6 KiB
TypeScript
"use client";
|
||
|
||
// 控制台的两套配色:dark(默认,AgentTown 的夜景像素 HUD)与 light(白天的纸面 HUD)。
|
||
//
|
||
// 主题只有一个真源:<html data-theme="..."> 属性 + localStorage 里的记录。
|
||
// CSS 的全部颜色都走 --pixel-* 变量,所以换属性就是换整套配色;办公室画布不读 CSS
|
||
// 变量(它是 canvas),由 lib/office-palette.ts 按同一个主题名给出像素调色板。
|
||
//
|
||
// 首屏不闪:app/layout.tsx 里有一段内联脚本,在浏览器画出第一帧之前就把属性写好;
|
||
// 这里负责的是"改主题"和"订阅主题",两边用的是同一个 storage key。
|
||
|
||
import { useSyncExternalStore } from "react";
|
||
|
||
import { DEFAULT_THEME, isTheme, THEME_STORE, type Theme } from "./theme-keys";
|
||
|
||
export { DEFAULT_THEME, isTheme, THEME_STORE };
|
||
export type { Theme };
|
||
|
||
const listeners = new Set<() => void>();
|
||
|
||
function normalize(value: string | null | undefined): Theme | null {
|
||
return isTheme(value) ? value : null;
|
||
}
|
||
|
||
/** 当前主题:以 <html data-theme> 为准(内联脚本已按 localStorage 写好它)。 */
|
||
export function getTheme(): Theme {
|
||
if (typeof document !== "undefined") {
|
||
const fromDom = normalize(document.documentElement.dataset.theme);
|
||
if (fromDom) return fromDom;
|
||
}
|
||
if (typeof window !== "undefined") {
|
||
return normalize(window.localStorage.getItem(THEME_STORE)) ?? DEFAULT_THEME;
|
||
}
|
||
return DEFAULT_THEME;
|
||
}
|
||
|
||
/** 把主题写到 DOM、localStorage,并通知订阅者。 */
|
||
export function setTheme(theme: Theme): void {
|
||
if (typeof document !== "undefined") document.documentElement.dataset.theme = theme;
|
||
try {
|
||
window.localStorage.setItem(THEME_STORE, theme);
|
||
} catch {
|
||
/* 隐私模式下写不进去,不影响这次切换 */
|
||
}
|
||
listeners.forEach((notify) => notify());
|
||
}
|
||
|
||
export function onThemeChange(notify: () => void): () => void {
|
||
listeners.add(notify);
|
||
return () => listeners.delete(notify);
|
||
}
|
||
|
||
/**
|
||
* 订阅当前主题。服务端(以及 hydration 的第一遍)按默认主题渲染,挂载后立刻跟随
|
||
* DOM 上的真实值——所以切换按钮的图标可能在 hydrated 后一跳,页面本身不会闪。
|
||
*/
|
||
export function useTheme(): Theme {
|
||
return useSyncExternalStore(
|
||
(notify) => {
|
||
// 本标签页内是自己改的(setTheme 已通知),别的标签页改了就走 storage 事件。
|
||
const off = onThemeChange(notify);
|
||
window.addEventListener("storage", notify);
|
||
return () => {
|
||
off();
|
||
window.removeEventListener("storage", notify);
|
||
};
|
||
},
|
||
getTheme,
|
||
() => DEFAULT_THEME,
|
||
);
|
||
}
|