-
Notifications
You must be signed in to change notification settings - Fork 107
Expand file tree
/
Copy pathThemeContext.tsx
More file actions
264 lines (221 loc) · 8.03 KB
/
ThemeContext.tsx
File metadata and controls
264 lines (221 loc) · 8.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
import React, {
createContext,
useCallback,
useContext,
useEffect,
useLayoutEffect,
useMemo,
useState,
type ReactNode,
} from "react";
import { readPersistedString, usePersistedState } from "@/browser/hooks/usePersistedState";
import { UI_THEME_KEY } from "@/common/constants/storage";
import { isLightThemeMode } from "@/browser/utils/highlighting/shiki-shared";
export type ThemeMode = "light" | "dark" | "flexoki-light" | "flexoki-dark";
export type ThemePreference = ThemeMode | "auto";
export const THEME_OPTIONS: Array<{ value: ThemePreference; label: string }> = [
{ value: "auto", label: "Auto" },
{ value: "light", label: "Light" },
{ value: "dark", label: "Dark" },
{ value: "flexoki-light", label: "Flexoki Light" },
{ value: "flexoki-dark", label: "Flexoki Dark" },
];
const MANUAL_THEME_VALUES: ThemeMode[] = ["light", "dark", "flexoki-light", "flexoki-dark"];
const THEME_PREFERENCE_VALUES = THEME_OPTIONS.map((theme) => theme.value);
function normalizeThemePreference(value: unknown): ThemePreference | undefined {
if (typeof value !== "string") {
return undefined;
}
if (THEME_PREFERENCE_VALUES.includes(value as ThemePreference)) {
return value as ThemePreference;
}
// Preserve intent for removed themes (e.g. legacy solarized-light/dark).
if (value.endsWith("-light")) {
return "light";
}
if (value.endsWith("-dark")) {
return "dark";
}
return undefined;
}
interface ThemeContextValue {
/** Concrete theme consumed by existing components (`auto` resolves to light/dark). */
theme: ThemeMode;
/** Persisted user preference shown in settings/selector (includes explicit `auto`). */
themePreference: ThemePreference;
setTheme: React.Dispatch<React.SetStateAction<ThemePreference>>;
toggleTheme: () => void;
/** True if this provider has a forcedTheme - nested providers should not override */
isForced: boolean;
}
const ThemeContext = createContext<ThemeContextValue | null>(null);
const THEME_COLORS: Record<ThemeMode, string> = {
dark: "#1e1e1e",
light: "#f5f6f8",
"flexoki-light": "#fffcf0",
"flexoki-dark": "#100f0f",
};
// Keep hrefs relative so a server-injected <base> preserves path-app prefixes.
const FAVICON_BY_SCHEME: Record<"light" | "dark", string> = {
light: "favicon.ico",
dark: "favicon-dark.ico",
};
/** Map theme mode to CSS color-scheme value */
function getColorScheme(theme: ThemeMode): "light" | "dark" {
// Reuse the shared `-light` suffix convention so we have one source of truth for the light/dark mapping.
return isLightThemeMode(theme) ? "light" : "dark";
}
function applyThemeFavicon(theme: ThemeMode) {
if (typeof document === "undefined") {
return;
}
const favicon = document.querySelector<HTMLLinkElement>('link[rel="icon"][data-theme-icon]');
if (!favicon) {
return;
}
const scheme = getColorScheme(theme);
const nextHref = FAVICON_BY_SCHEME[scheme];
if (favicon.getAttribute("href") !== nextHref) {
favicon.setAttribute("href", nextHref);
}
}
function resolveSystemTheme(): "light" | "dark" {
if (typeof window === "undefined" || !window.matchMedia) {
return "dark";
}
return window.matchMedia("(prefers-color-scheme: light)").matches ? "light" : "dark";
}
function applyThemeToDocument(theme: ThemeMode) {
if (typeof document === "undefined") {
return;
}
const root = document.documentElement;
root.dataset.theme = theme;
root.style.colorScheme = getColorScheme(theme);
const themeColor = THEME_COLORS[theme];
const meta = document.querySelector<HTMLMetaElement>('meta[name="theme-color"]');
if (meta) {
meta.setAttribute("content", themeColor);
}
const body = document.body;
if (body) {
body.style.backgroundColor = "var(--color-background)";
}
applyThemeFavicon(theme);
}
export function ThemeProvider({
children,
forcedTheme,
}: {
children: ReactNode;
forcedTheme?: ThemeMode;
}) {
// Check if we're nested inside a forced theme provider
const parentContext = useContext(ThemeContext);
const isNestedUnderForcedProvider = parentContext?.isForced ?? false;
const [persistedThemePreference, setTheme] = usePersistedState<ThemePreference>(
UI_THEME_KEY,
"auto",
{
listener: true,
}
);
// Keep the explicit user preference (`auto`/manual) separate from the concrete theme we apply.
// This lets existing UI consumers keep using a resolved theme while settings can still show `auto`.
const storedThemePreference = readPersistedString(UI_THEME_KEY) ?? persistedThemePreference;
const parsedPersistedThemePreference = normalizeThemePreference(storedThemePreference);
const normalizedThemePreference = parsedPersistedThemePreference ?? "auto";
const [systemTheme, setSystemTheme] = useState<"light" | "dark">(() => resolveSystemTheme());
useEffect(() => {
if (
typeof window === "undefined" ||
!window.matchMedia ||
forcedTheme !== undefined ||
isNestedUnderForcedProvider ||
normalizedThemePreference !== "auto"
) {
return;
}
const mediaQuery = window.matchMedia("(prefers-color-scheme: light)");
setSystemTheme(mediaQuery.matches ? "light" : "dark");
const handleChange = (event: MediaQueryListEvent) => {
setSystemTheme(event.matches ? "light" : "dark");
};
if (typeof mediaQuery.addEventListener === "function") {
mediaQuery.addEventListener("change", handleChange);
return () => {
mediaQuery.removeEventListener("change", handleChange);
};
}
mediaQuery.addListener(handleChange);
return () => {
mediaQuery.removeListener(handleChange);
};
}, [forcedTheme, isNestedUnderForcedProvider, normalizedThemePreference]);
const resolvedPersistedTheme =
normalizedThemePreference === "auto"
? // Resolve directly from matchMedia so manual -> auto reads the current OS theme in the same render.
typeof window !== "undefined"
? resolveSystemTheme()
: systemTheme
: normalizedThemePreference;
// If nested under a forced provider, use parent's resolved theme
// Otherwise, use forcedTheme (if provided) or resolved persisted theme
const theme =
isNestedUnderForcedProvider && parentContext
? parentContext.theme
: (forcedTheme ?? resolvedPersistedTheme);
const themePreference =
isNestedUnderForcedProvider && parentContext
? parentContext.themePreference
: normalizedThemePreference;
const isForced = forcedTheme !== undefined || isNestedUnderForcedProvider;
// Only apply to document if we're the authoritative provider
useLayoutEffect(() => {
if (isNestedUnderForcedProvider) {
return;
}
// Self-heal legacy or invalid theme preferences persisted in localStorage.
if (forcedTheme === undefined && parsedPersistedThemePreference !== storedThemePreference) {
setTheme(normalizedThemePreference);
}
applyThemeToDocument(theme);
}, [
forcedTheme,
isNestedUnderForcedProvider,
normalizedThemePreference,
parsedPersistedThemePreference,
setTheme,
storedThemePreference,
theme,
]);
const toggleTheme = useCallback(() => {
if (!isNestedUnderForcedProvider) {
setTheme((currentPreference) => {
const currentTheme = currentPreference === "auto" ? theme : currentPreference;
const currentIndex = MANUAL_THEME_VALUES.indexOf(currentTheme);
const safeCurrentIndex = currentIndex >= 0 ? currentIndex : 0;
const nextIndex = (safeCurrentIndex + 1) % MANUAL_THEME_VALUES.length;
return MANUAL_THEME_VALUES[nextIndex];
});
}
}, [isNestedUnderForcedProvider, setTheme, theme]);
const value = useMemo<ThemeContextValue>(
() => ({
theme,
themePreference,
setTheme,
toggleTheme,
isForced,
}),
[isForced, setTheme, theme, themePreference, toggleTheme]
);
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
}
export function useTheme(): ThemeContextValue {
const context = useContext(ThemeContext);
if (!context) {
throw new Error("useTheme must be used within a ThemeProvider");
}
return context;
}