This repository has been archived by the owner on Aug 8, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.tsx
378 lines (329 loc) · 10.7 KB
/
index.tsx
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
import React, {
Fragment,
createContext,
useCallback,
useContext,
useEffect,
useState,
useMemo,
memo,
} from "react";
interface ValueObject {
[themeName: string]: string;
}
export interface UseThemeProps {
/** List of all available theme names */
themes: string[];
/** Forced theme name for the current page */
forcedTheme?: string;
/** Update the theme */
setTheme: (theme: string) => void;
/** Active theme name */
theme?: string;
/** If `enableSystem` is true and the active theme is "system", this returns whether the system preference resolved to "dark" or "light". Otherwise, identical to `theme` */
resolvedTheme?: string;
/** If enableSystem is true, returns the System theme preference ("dark" or "light"), regardless what the active theme is */
systemTheme?: "dark" | "light";
}
export interface ThemeProviderProps {
/** List of all available theme names */
themes?: string[];
/** Forced theme name for the current page */
forcedTheme?: string;
/** Whether to switch between dark and light themes based on prefers-color-scheme */
enableSystem?: boolean;
/** Disable all CSS transitions when switching themes */
disableTransitionOnChange?: boolean;
/** Whether to indicate to browsers which color scheme is used (dark or light) for built-in UI like inputs and buttons */
enableColorScheme?: boolean;
/** Key used to store theme setting in localStorage */
storageKey?: string;
/** Default theme name (for v0.0.12 and lower the default was light). If `enableSystem` is false, the default theme is light */
defaultTheme?: string;
/** HTML attribute modified based on the active theme. Accepts `class` and `data-*` (meaning any data attribute, `data-mode`, `data-color`, etc.) */
attribute?: string | "class";
/** Mapping of theme name to HTML attribute value. Object where key is the theme name and value is the attribute value */
value?: ValueObject;
/** Nonce string to pass to the inline script for CSP headers */
nonce?: string;
children?: React.ReactNode;
}
const colorSchemes = ["light", "dark"];
const MEDIA = "(prefers-color-scheme: dark)";
const isServer = typeof window === "undefined";
const ThemeContext = createContext<UseThemeProps | undefined>(undefined);
const defaultContext: UseThemeProps = { setTheme: (_) => {}, themes: [] };
export const useTheme = () => useContext(ThemeContext) ?? defaultContext;
export const ThemeProvider: React.FC<ThemeProviderProps> = (props) => {
const context = useContext(ThemeContext);
// Ignore nested context providers, just passthrough children
if (context) return <Fragment>{props.children}</Fragment>;
return <Theme {...props} />;
};
const defaultThemes = ["light", "dark"];
const Theme: React.FC<ThemeProviderProps> = ({
forcedTheme,
disableTransitionOnChange = false,
enableSystem = true,
enableColorScheme = true,
storageKey = "theme",
themes = defaultThemes,
defaultTheme = enableSystem ? "system" : "light",
attribute = "data-theme",
value,
children,
nonce,
}) => {
const [theme, setThemeState] = useState(() =>
getTheme(storageKey, defaultTheme)
);
const [resolvedTheme, setResolvedTheme] = useState(() =>
getTheme(storageKey)
);
const attrs = !value ? themes : Object.values(value);
const applyTheme = useCallback((theme: any) => {
let resolved = theme;
if (!resolved) return;
// If theme is system, resolve it before setting theme
if (theme === "system" && enableSystem) {
resolved = getSystemTheme();
}
const name = value ? value[resolved] : resolved;
const enable = disableTransitionOnChange ? disableAnimation() : null;
const d = document.documentElement;
if (attribute === "class") {
d.classList.remove(...attrs);
if (name) d.classList.add(name);
} else {
if (name) {
d.setAttribute(attribute, name);
} else {
d.removeAttribute(attribute);
}
}
if (enableColorScheme) {
const fallback = colorSchemes.includes(defaultTheme)
? defaultTheme
: null;
const colorScheme = colorSchemes.includes(resolved) ? resolved : fallback;
// @ts-ignore
d.style.colorScheme = colorScheme;
}
enable?.();
}, []);
const setTheme = useCallback(
(theme: any) => {
setThemeState(theme);
// Save to storage
try {
localStorage.setItem(storageKey, theme);
} catch (e) {
// Unsupported
}
},
[forcedTheme]
);
const handleMediaQuery = useCallback(
(e: MediaQueryListEvent | MediaQueryList) => {
const resolved = getSystemTheme(e);
setResolvedTheme(resolved);
if (theme === "system" && enableSystem && !forcedTheme) {
applyTheme("system");
}
},
[theme, forcedTheme]
);
// Always listen to System preference
useEffect(() => {
const media = window.matchMedia(MEDIA);
// Intentionally use deprecated listener methods to support iOS & old browsers
media.addListener(handleMediaQuery);
handleMediaQuery(media);
return () => media.removeListener(handleMediaQuery);
}, [handleMediaQuery]);
// localStorage event handling
useEffect(() => {
const handleStorage = (e: StorageEvent) => {
if (e.key !== storageKey) {
return;
}
// If default theme set, use it if localstorage === null (happens on local storage manual deletion)
const theme = e.newValue || defaultTheme;
setTheme(theme);
};
window.addEventListener("storage", handleStorage);
return () => window.removeEventListener("storage", handleStorage);
}, [setTheme]);
// Whenever theme or forcedTheme changes, apply it
useEffect(() => {
applyTheme(forcedTheme ?? theme);
}, [forcedTheme, theme]);
const providerValue = useMemo(
() => ({
theme,
setTheme,
forcedTheme,
resolvedTheme: theme === "system" ? resolvedTheme : theme,
themes: enableSystem ? [...themes, "system"] : themes,
systemTheme: (enableSystem ? resolvedTheme : undefined) as
| "light"
| "dark"
| undefined,
}),
[theme, setTheme, forcedTheme, resolvedTheme, enableSystem, themes]
);
return (
<ThemeContext.Provider value={providerValue}>
<ThemeScript
{...{
forcedTheme,
disableTransitionOnChange,
enableSystem,
enableColorScheme,
storageKey,
themes,
defaultTheme,
attribute,
value,
children,
attrs,
nonce,
}}
/>
{children}
</ThemeContext.Provider>
);
};
const ThemeScript = memo(
({
forcedTheme,
storageKey,
attribute,
enableSystem,
enableColorScheme,
defaultTheme,
value,
attrs,
nonce,
}: ThemeProviderProps & { attrs: string[]; defaultTheme: string }) => {
const defaultSystem = defaultTheme === "system";
// Code-golfing the amount of characters in the script
const optimization = (() => {
if (attribute === "class") {
const removeClasses = `c.remove(${attrs
.map((t: string) => `'${t}'`)
.join(",")})`;
return `var d=document.documentElement,c=d.classList;${removeClasses};`;
} else {
return `var d=document.documentElement,n='${attribute}',s='setAttribute';`;
}
})();
const fallbackColorScheme = (() => {
if (!enableColorScheme) {
return "";
}
const fallback = colorSchemes.includes(defaultTheme)
? defaultTheme
: null;
if (fallback) {
return `if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${defaultTheme}'`;
} else {
return `if(e==='light'||e==='dark')d.style.colorScheme=e`;
}
})();
const updateDOM = (
name: string,
literal: boolean = false,
setColorScheme = true
) => {
const resolvedName = value ? value[name] : name;
const val = literal ? name + `|| ''` : `'${resolvedName}'`;
let text = "";
// MUCH faster to set colorScheme alongside HTML attribute/class
// as it only incurs 1 style recalculation rather than 2
// This can save over 250ms of work for pages with big DOM
if (
enableColorScheme &&
setColorScheme &&
!literal &&
colorSchemes.includes(name)
) {
text += `d.style.colorScheme = '${name}';`;
}
if (attribute === "class") {
if (literal || resolvedName) {
text += `c.add(${val})`;
} else {
text += `null`;
}
} else {
if (resolvedName) {
text += `d[s](n,${val})`;
}
}
return text;
};
const scriptSrc = (() => {
if (forcedTheme) {
return `!function(){${optimization}${updateDOM(forcedTheme)}}()`;
}
if (enableSystem) {
return `!function(){try{${optimization}var e=localStorage.getItem('${storageKey}');if('system'===e||(!e&&${defaultSystem})){var t='${MEDIA}',m=window.matchMedia(t);if(m.media!==t||m.matches){${updateDOM(
"dark"
)}}else{${updateDOM("light")}}}else if(e){${
value ? `var x=${JSON.stringify(value)};` : ""
}${updateDOM(value ? `x[e]` : "e", true)}}${
!defaultSystem
? `else{` + updateDOM(defaultTheme, false, false) + "}"
: ""
}${fallbackColorScheme}}catch(e){}}()`;
}
return `!function(){try{${optimization}var e=localStorage.getItem('${storageKey}');if(e){${
value ? `var x=${JSON.stringify(value)};` : ""
}${updateDOM(value ? `x[e]` : "e", true)}}else{${updateDOM(
defaultTheme,
false,
false
)};}${fallbackColorScheme}}catch(t){}}();`;
})();
return (
<script nonce={nonce} dangerouslySetInnerHTML={{ __html: scriptSrc }} />
);
},
// Never re-render this component
() => true
);
// Helpers
const getTheme = (key: string, fallback?: string) => {
if (isServer) return undefined;
let theme;
try {
theme = localStorage.getItem(key) || undefined;
} catch (e) {
// Unsupported
}
return theme || fallback;
};
const disableAnimation = () => {
const css = document.createElement("style");
css.appendChild(
document.createTextNode(
`*{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}`
)
);
document.head.appendChild(css);
return () => {
// Force restyle
(() => window.getComputedStyle(document.body))();
// Wait for next tick before removing
setTimeout(() => {
document.head.removeChild(css);
}, 1);
};
};
const getSystemTheme = (e?: MediaQueryList | MediaQueryListEvent) => {
if (!e) e = window.matchMedia(MEDIA);
const isDark = e.matches;
const systemTheme = isDark ? "dark" : "light";
return systemTheme;
};