Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useTheme.ts

194 lines5.8 KB

1import { useCallback, useEffect, useSyncExternalStore } from "react";
2​
3type Theme = "light" | "dark" | "system";
4type ThemeSnapshot = {
5 theme: Theme;
6 systemDark: boolean;
7};
8​
9const STORAGE_KEY = "t3code:theme";
10const MEDIA_QUERY = "(prefers-color-scheme: dark)";
11const DEFAULT_THEME_SNAPSHOT: ThemeSnapshot = {
12 theme: "system",
13 systemDark: false,
14};
15const THEME_COLOR_META_NAME = "theme-color";
16const DYNAMIC_THEME_COLOR_SELECTOR = `meta[name="${THEME_COLOR_META_NAME}"][data-dynamic-theme-color="true"]`;
17​
18let listeners: Array<() => void> = [];
19let lastSnapshot: ThemeSnapshot | null = null;
20let lastDesktopTheme: Theme | null = null;
21​
22function emitChange() {
23 for (const listener of listeners) listener();
25​
26function hasThemeStorage() {
27 return typeof window !== "undefined" && typeof localStorage !== "undefined";
29​
30function getSystemDark() {
31 return typeof window !== "undefined" && window.matchMedia(MEDIA_QUERY).matches;
33​
34function getStored(): Theme {
35 if (!hasThemeStorage()) return DEFAULT_THEME_SNAPSHOT.theme;
36 const raw = localStorage.getItem(STORAGE_KEY);
37 if (raw === "light" || raw === "dark" || raw === "system") return raw;
38 return DEFAULT_THEME_SNAPSHOT.theme;
40​
41function ensureThemeColorMetaTag(): HTMLMetaElement {
42 let element = document.querySelector<HTMLMetaElement>(DYNAMIC_THEME_COLOR_SELECTOR);
43 if (element) {
44 return element;
45 }
46​
47 element = document.createElement("meta");
48 element.name = THEME_COLOR_META_NAME;
49 element.setAttribute("data-dynamic-theme-color", "true");
50 document.head.append(element);
51 return element;
53​
54function normalizeThemeColor(value: string | null | undefined): string | null {
55 const normalizedValue = value?.trim().toLowerCase();
56 if (
57 !normalizedValue ||
58 normalizedValue === "transparent" ||
59 normalizedValue === "rgba(0, 0, 0, 0)" ||
60 normalizedValue === "rgba(0 0 0 / 0)"
61 ) {
62 return null;
63 }
64​
65 return value?.trim() ?? null;
67​
68function resolveBrowserChromeSurface(): HTMLElement {
69 return (
70 document.querySelector<HTMLElement>("main[data-slot='sidebar-inset']") ??
71 document.querySelector<HTMLElement>("[data-slot='sidebar-inner']") ??
72 document.body
73 );
75​
76export function syncBrowserChromeTheme() {
77 if (typeof document === "undefined" || typeof getComputedStyle === "undefined") return;
78 const surfaceColor = normalizeThemeColor(
79 getComputedStyle(resolveBrowserChromeSurface()).backgroundColor,
80 );
81 const fallbackColor = normalizeThemeColor(getComputedStyle(document.body).backgroundColor);
82 const backgroundColor = surfaceColor ?? fallbackColor;
83 if (!backgroundColor) return;
84​
85 document.documentElement.style.backgroundColor = backgroundColor;
86 document.body.style.backgroundColor = backgroundColor;
87 ensureThemeColorMetaTag().setAttribute("content", backgroundColor);
89​
90function applyTheme(theme: Theme, suppressTransitions = false) {
91 if (typeof document === "undefined" || typeof window === "undefined") return;
92 if (suppressTransitions) {
93 document.documentElement.classList.add("no-transitions");
94 }
95 const isDark = theme === "dark" || (theme === "system" && getSystemDark());
96 document.documentElement.classList.toggle("dark", isDark);
97 syncBrowserChromeTheme();
98 syncDesktopTheme(theme);
99 if (suppressTransitions) {
100 // Force a reflow so the no-transitions class takes effect before removal
101 // oxlint-disable-next-line no-unused-expressions
102 document.documentElement.offsetHeight;
103 requestAnimationFrame(() => {
104 document.documentElement.classList.remove("no-transitions");
105 });
106 }
108​
109function syncDesktopTheme(theme: Theme) {
110 if (typeof window === "undefined") return;
111 const bridge = window.desktopBridge;
112 if (!bridge || lastDesktopTheme === theme) {
113 return;
114 }
115​
116 lastDesktopTheme = theme;
117 void bridge.setTheme(theme).catch(() => {
118 if (lastDesktopTheme === theme) {
119 lastDesktopTheme = null;
120 }
121 });
123​
124// Apply immediately on module load to prevent flash
125if (typeof document !== "undefined" && hasThemeStorage()) {
126 applyTheme(getStored());
128​
129function getSnapshot(): ThemeSnapshot {
130 if (!hasThemeStorage()) return DEFAULT_THEME_SNAPSHOT;
131 const theme = getStored();
132 const systemDark = theme === "system" ? getSystemDark() : false;
133​
134 if (lastSnapshot && lastSnapshot.theme === theme && lastSnapshot.systemDark === systemDark) {
135 return lastSnapshot;
136 }
137​
138 lastSnapshot = { theme, systemDark };
139 return lastSnapshot;
141​
142function getServerSnapshot() {
143 return DEFAULT_THEME_SNAPSHOT;
145​
146function subscribe(listener: () => void): () => void {
147 if (typeof window === "undefined") return () => {};
148 listeners.push(listener);
149​
150 // Listen for system preference changes
151 const mq = window.matchMedia(MEDIA_QUERY);
152 const handleChange = () => {
153 if (getStored() === "system") applyTheme("system", true);
154 emitChange();
155 };
156 mq.addEventListener("change", handleChange);
157​
158 // Listen for storage changes from other tabs
159 const handleStorage = (e: StorageEvent) => {
160 if (e.key === STORAGE_KEY) {
161 applyTheme(getStored(), true);
162 emitChange();
163 }
164 };
165 window.addEventListener("storage", handleStorage);
166​
167 return () => {
168 listeners = listeners.filter((l) => l !== listener);
169 mq.removeEventListener("change", handleChange);
170 window.removeEventListener("storage", handleStorage);
171 };
173​
174export function useTheme() {
175 const snapshot = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
176 const theme = snapshot.theme;
177​
178 const resolvedTheme: "light" | "dark" =
179 theme === "system" ? (snapshot.systemDark ? "dark" : "light") : theme;
180​
181 const setTheme = useCallback((next: Theme) => {
182 if (!hasThemeStorage()) return;
183 localStorage.setItem(STORAGE_KEY, next);
184 applyTheme(next, true);
185 emitChange();
186 }, []);
187​
188 // Keep DOM in sync on mount/change
189 useEffect(() => {
190 applyTheme(theme);
191 }, [theme]);
192​
193 return { theme, setTheme, resolvedTheme } as const;