Open History to see the last commit
1import type { DesktopBridge } from "@v12/contracts";
2import { safeErrorLogAttributes } from "@v12/client-runtime/errors";
3import * as Schema from "effect/Schema";
4import { useCallback, useEffect, useSyncExternalStore } from "react";
5
6const ThemePreference = Schema.Literals(["light", "dark", "system"]);
7type Theme = typeof ThemePreference.Type;
8type ThemeSnapshot = {
9 theme: Theme;
10 systemDark: boolean;
11};
12
13type DesktopThemeBridge = Pick<DesktopBridge, "setTheme">;
14
15const STORAGE_KEY = "v12:theme";
16const MEDIA_QUERY = "(prefers-color-scheme: dark)";
17const DEFAULT_THEME_SNAPSHOT: ThemeSnapshot = {
18 theme: "system",
19 systemDark: false,
20};
21const THEME_COLOR_META_NAME = "theme-color";
22const DYNAMIC_THEME_COLOR_SELECTOR = `meta[name="${THEME_COLOR_META_NAME}"][data-dynamic-theme-color="true"]`;
23
24export class ThemeStorageError extends Schema.TaggedErrorClass<ThemeStorageError>()(
25 "ThemeStorageError",
26 {
27 operation: Schema.Literals(["read", "write"]),
28 storageKey: Schema.String,
29 theme: Schema.optional(ThemePreference),
30 cause: Schema.Defect(),
31 },
32) {
33 override get message(): string {
34 return `Failed to ${this.operation} theme preference for ${this.storageKey}.`;
35 }
36}
37
38export const isThemeStorageError = Schema.is(ThemeStorageError);
39
40export class DesktopThemeSyncError extends Schema.TaggedErrorClass<DesktopThemeSyncError>()(
41 "DesktopThemeSyncError",
42 {
43 theme: ThemePreference,
44 cause: Schema.Defect(),
45 },
46) {
47 override get message(): string {
48 return `Failed to sync the ${this.theme} theme to the desktop shell.`;
49 }
50}
51
52export const isDesktopThemeSyncError = Schema.is(DesktopThemeSyncError);
53
54let listeners: Array<() => void> = [];
55let lastSnapshot: ThemeSnapshot | null = null;
56let lastDesktopTheme: Theme | null = null;
57let lastAppliedTheme: ThemeSnapshot | null = null;
58let themeStorageReadFailure: ThemeStorageError | null = null;
59
60function emitChange() {
61 for (const listener of listeners) listener();
62}
63
64function getSystemDark() {
65 return (
66 typeof window !== "undefined" &&
67 typeof window.matchMedia === "function" &&
68 window.matchMedia(MEDIA_QUERY).matches
69 );
70}
71
72export function readThemePreference(): Theme {
73 if (typeof window === "undefined") return DEFAULT_THEME_SNAPSHOT.theme;
74 let raw: string | null;
75 try {
76 raw = window.localStorage.getItem(STORAGE_KEY);
77 } catch (cause) {
78 throw new ThemeStorageError({
79 operation: "read",
80 storageKey: STORAGE_KEY,
81 cause,
82 });
83 }
84 if (raw === "light" || raw === "dark" || raw === "system") return raw;
85 return DEFAULT_THEME_SNAPSHOT.theme;
86}
87
88export function writeThemePreference(theme: Theme): void {
89 if (typeof window === "undefined") return;
90 try {
91 window.localStorage.setItem(STORAGE_KEY, theme);
92 themeStorageReadFailure = null;
93 } catch (cause) {
94 throw new ThemeStorageError({
95 operation: "write",
96 storageKey: STORAGE_KEY,
97 theme,
98 cause,
99 });
100 }
101}
102
103function getStored(): Theme {
104 if (themeStorageReadFailure !== null) {
105 return DEFAULT_THEME_SNAPSHOT.theme;
106 }
107 try {
108 return readThemePreference();
109 } catch (cause) {
110 const error = isThemeStorageError(cause)
111 ? cause
112 : new ThemeStorageError({
113 operation: "read",
114 storageKey: STORAGE_KEY,
115 cause,
116 });
117 themeStorageReadFailure = error;
118 console.error(error.message, {
119 operation: error.operation,
120 storageKey: error.storageKey,
121 ...safeErrorLogAttributes(error),
122 });
123 return DEFAULT_THEME_SNAPSHOT.theme;
124 }
125}
126
127function ensureThemeColorMetaTag(): HTMLMetaElement {
128 let element = document.querySelector<HTMLMetaElement>(DYNAMIC_THEME_COLOR_SELECTOR);
129 if (element) {
130 return element;
131 }
132
133 element = document.createElement("meta");
134 element.name = THEME_COLOR_META_NAME;
135 element.setAttribute("data-dynamic-theme-color", "true");
136 document.head.append(element);
137 return element;
138}
139
140function normalizeThemeColor(value: string | null | undefined): string | null {
141 const normalizedValue = value?.trim().toLowerCase();
142 if (
143 !normalizedValue ||
144 normalizedValue === "transparent" ||
145 normalizedValue === "rgba(0, 0, 0, 0)" ||
146 normalizedValue === "rgba(0 0 0 / 0)"
147 ) {
148 return null;
149 }
150
151 return value?.trim() ?? null;
152}
153
154function resolveBrowserChromeSurface(): HTMLElement {
155 return (
156 document.querySelector<HTMLElement>("main[data-slot='sidebar-inset']") ??
157 document.querySelector<HTMLElement>("[data-slot='sidebar-inner']") ??
158 document.body
159 );
160}
161
162export function syncBrowserChromeTheme() {
163 if (typeof document === "undefined" || typeof getComputedStyle === "undefined") return;
164 const surfaceColor = normalizeThemeColor(
165 getComputedStyle(resolveBrowserChromeSurface()).backgroundColor,
166 );
167 const fallbackColor = normalizeThemeColor(getComputedStyle(document.body).backgroundColor);
168 const backgroundColor = surfaceColor ?? fallbackColor;
169 if (!backgroundColor) return;
170
171 document.documentElement.style.backgroundColor = backgroundColor;
172 document.body.style.backgroundColor = backgroundColor;
173 ensureThemeColorMetaTag().setAttribute("content", backgroundColor);
174}
175
176function applyTheme(theme: Theme, suppressTransitions = false) {
177 if (typeof document === "undefined" || typeof window === "undefined") return;
178 const systemDark = theme === "system" ? getSystemDark() : false;
179 if (lastAppliedTheme?.theme === theme && lastAppliedTheme.systemDark === systemDark) {
180 syncDesktopTheme(theme);
181 return;
182 }
183
184 if (suppressTransitions) {
185 document.documentElement.classList.add("no-transitions");
186 }
187 const isDark = theme === "dark" || (theme === "system" && systemDark);
188 document.documentElement.classList.toggle("dark", isDark);
189 lastAppliedTheme = { theme, systemDark };
190 syncBrowserChromeTheme();
191 syncDesktopTheme(theme);
192 if (suppressTransitions) {
193 // Force a reflow so the no-transitions class takes effect before removal
194 // oxlint-disable-next-line no-unused-expressions
195 document.documentElement.offsetHeight;
196 requestAnimationFrame(() => {
197 document.documentElement.classList.remove("no-transitions");
198 });
199 }
200}
201
202export async function syncDesktopThemePreference(
203 bridge: DesktopThemeBridge,
204 theme: Theme,
205): Promise<void> {
206 try {
207 await bridge.setTheme(theme);
208 } catch (cause) {
209 throw new DesktopThemeSyncError({ theme, cause });
210 }
211}
212
213export function syncDesktopTheme(theme: Theme) {
214 if (typeof window === "undefined") return;
215 const bridge = window.desktopBridge;
216 if (!bridge || typeof bridge.setTheme !== "function" || lastDesktopTheme === theme) {
217 return;
218 }
219
220 lastDesktopTheme = theme;
221 void syncDesktopThemePreference(bridge, theme).catch((cause: unknown) => {
222 const error = isDesktopThemeSyncError(cause)
223 ? cause
224 : new DesktopThemeSyncError({ theme, cause });
225 console.error(error.message, {
226 theme: error.theme,
227 ...safeErrorLogAttributes(error),
228 });
229 if (lastDesktopTheme === theme) {
230 lastDesktopTheme = null;
231 }
232 });
233}
234
235// Apply immediately on module load to prevent flash
236if (typeof document !== "undefined" && typeof window !== "undefined") {
237 applyTheme(getStored());
238}
239
240function getSnapshot(): ThemeSnapshot {
241 if (typeof window === "undefined") return DEFAULT_THEME_SNAPSHOT;
242 const theme = getStored();
243 const systemDark = theme === "system" ? getSystemDark() : false;
244
245 if (lastSnapshot && lastSnapshot.theme === theme && lastSnapshot.systemDark === systemDark) {
246 return lastSnapshot;
247 }
248
249 lastSnapshot = { theme, systemDark };
250 return lastSnapshot;
251}
252
253function getServerSnapshot() {
254 return DEFAULT_THEME_SNAPSHOT;
255}
256
257function subscribe(listener: () => void): () => void {
258 if (typeof window === "undefined") return () => {};
259 listeners.push(listener);
260
261 // Listen for system preference changes
262 const mq = typeof window.matchMedia === "function" ? window.matchMedia(MEDIA_QUERY) : null;
263 const handleChange = () => {
264 if (getStored() === "system") applyTheme("system", true);
265 emitChange();
266 };
267 mq?.addEventListener("change", handleChange);
268
269 // Listen for storage changes from other tabs
270 const handleStorage = (e: StorageEvent) => {
271 if (e.key === STORAGE_KEY) {
272 themeStorageReadFailure = null;
273 applyTheme(getStored(), true);
274 emitChange();
275 }
276 };
277 window.addEventListener("storage", handleStorage);
278
279 return () => {
280 listeners = listeners.filter((l) => l !== listener);
281 mq?.removeEventListener("change", handleChange);
282 window.removeEventListener("storage", handleStorage);
283 };
284}
285
286export function useTheme() {
287 const snapshot = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
288 const theme = snapshot.theme;
289
290 const resolvedTheme: "light" | "dark" =
291 theme === "system" ? (snapshot.systemDark ? "dark" : "light") : theme;
292
293 const setTheme = useCallback((next: Theme) => {
294 if (typeof window === "undefined") return;
295 try {
296 writeThemePreference(next);
297 } catch (cause) {
298 const error = isThemeStorageError(cause)
299 ? cause
300 : new ThemeStorageError({
301 operation: "write",
302 storageKey: STORAGE_KEY,
303 theme: next,
304 cause,
305 });
306 console.error(error.message, {
307 operation: error.operation,
308 storageKey: error.storageKey,
309 theme: next,
310 ...safeErrorLogAttributes(error),
311 });
312 return;
313 }
314 applyTheme(next, true);
315 emitChange();
316 }, []);
317
318 // Keep DOM in sync on mount/change
319 useEffect(() => {
320 applyTheme(theme);
321 }, [theme]);
322
323 return { theme, setTheme, resolvedTheme } as const;
324}