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

useTheme.ts

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