-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathnext-themes.tsx
327 lines (289 loc) · 10.1 KB
/
next-themes.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
import React, { createContext, useCallback, useContext, useEffect, useState, useRef, memo } from "react";
import NextHead from "next/head";
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;
}
const ThemeContext = createContext<UseThemeProps>({
setTheme: (_) => {},
themes: []
});
export const useTheme = () => useContext(ThemeContext);
const colorSchemes = ["light", "dark"];
const MEDIA = "(prefers-color-scheme: dark)";
interface ValueObject {
[themeName: string]: string;
}
export const ThemeProvider: React.FC<ThemeProviderProps> = ({
forcedTheme,
disableTransitionOnChange = false,
enableSystem = true,
enableColorScheme = true,
storageKey = "theme",
themes = ["light", "dark"],
defaultTheme = enableSystem ? "system" : "light",
attribute = "data-theme",
value,
children
}) => {
const [theme, setThemeState] = useState(() => getTheme(storageKey, defaultTheme));
const [resolvedTheme, setResolvedTheme] = useState(() => getTheme(storageKey));
console.log({ getThemeBeforeMount: getTheme(storageKey) });
const attrs = !value ? themes : Object.values(value);
const handleMediaQuery = useCallback(
(e?) => {
const systemTheme = getSystemTheme(e);
setResolvedTheme(systemTheme);
if (theme === "system" && !forcedTheme) changeTheme(systemTheme, false);
},
[theme, forcedTheme]
);
// Ref hack to avoid adding handleMediaQuery as a dep
const mediaListener = useRef(handleMediaQuery);
mediaListener.current = handleMediaQuery;
const changeTheme = useCallback((theme, updateStorage = true, updateDOM = true) => {
console.log("changeTheme");
let name = value?.[theme] || theme;
const enable = disableTransitionOnChange && updateDOM ? disableAnimation() : null;
if (updateStorage) {
try {
localStorage.setItem(storageKey, theme);
} catch (e) {
// Unsupported
}
}
if (theme === "system" && enableSystem) {
const resolved = getSystemTheme();
name = value?.[resolved] || resolved;
}
if (updateDOM) {
const d = document.documentElement;
if (attribute === "class") {
d.classList.remove(...attrs);
d.classList.add(name);
} else {
d.setAttribute(attribute, name);
}
enable?.();
}
}, []);
useEffect(() => {
const handler = (...args: any) => mediaListener.current(...args);
// Always listen to System preference
const media = window.matchMedia(MEDIA);
// Intentionally use deprecated listener methods to support iOS & old browsers
media.addListener(handler);
handler(media);
return () => media.removeListener(handler);
}, []);
const setTheme = useCallback(
(newTheme) => {
if (forcedTheme) {
changeTheme(newTheme, true, false);
changeTheme(newTheme);
}
setThemeState(newTheme);
},
[forcedTheme]
);
// 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);
};
console.log("onWindow");
window.addEventListener("storage", handleStorage);
return () => window.removeEventListener("storage", handleStorage);
}, [setTheme]);
// color-scheme handling
useEffect(() => {
if (!enableColorScheme) return;
console.log("enableColorScheme");
let colorScheme =
// If theme is forced to light or dark, use that
forcedTheme && colorSchemes.includes(forcedTheme)
? forcedTheme
: // If regular theme is light or dark
theme && colorSchemes.includes(theme)
? theme
: // If theme is system, use the resolved version
theme === "system"
? resolvedTheme || null
: null;
// color-scheme tells browser how to render built-in elements like forms, scrollbars, etc.
// if color-scheme is null, this will remove the property
document.documentElement.style.setProperty("color-scheme", colorScheme);
}, [enableColorScheme, theme, resolvedTheme, forcedTheme]);
return (
<ThemeContext.Provider
value={{
theme,
setTheme,
forcedTheme,
resolvedTheme: theme === "system" ? resolvedTheme : theme,
themes: enableSystem ? [...themes, "system"] : themes,
systemTheme: (enableSystem ? resolvedTheme : undefined) as "light" | "dark" | undefined
}}
>
<ThemeScript
{...{
forcedTheme,
storageKey,
attribute,
value,
enableSystem,
defaultTheme,
attrs
}}
/>
{children}
</ThemeContext.Provider>
);
};
const ThemeScript = memo(
({
forcedTheme,
storageKey,
attribute,
enableSystem,
defaultTheme,
value,
attrs
}: {
forcedTheme?: string;
storageKey: string;
attribute?: string;
enableSystem?: boolean;
defaultTheme: string;
value?: ValueObject;
attrs: any;
}) => {
// Code-golfing the amount of characters in the script
const optimization = (() => {
if (attribute === "class") {
const removeClasses = `d.remove(${attrs.map((t: string) => `'${t}'`).join(",")})`;
return `var d=document.documentElement.classList;${removeClasses};`;
} else {
return `var d=document.documentElement;`;
}
})();
const updateDOM = (name: string, literal?: boolean) => {
name = value?.[name] || name;
const val = literal ? name : `'${name}'`;
if (attribute === "class") {
return `d.add(${val})`;
}
return `d.setAttribute('${attribute}', ${val})`;
};
const defaultSystem = defaultTheme === "system";
// return null;
console.log("themescript");
return (
<NextHead>
{forcedTheme ? (
<script
key="next-themes-script"
dangerouslySetInnerHTML={{
// These are minified via Terser and then updated by hand, don't recommend
// prettier-ignore
__html: `!function(){${optimization}${updateDOM(forcedTheme)}}()`
}}
/>
) : enableSystem ? (
<script
key="next-themes-script"
dangerouslySetInnerHTML={{
// prettier-ignore
__html: `!function(){try {${optimization}var e=localStorage.getItem('${storageKey}');${!defaultSystem ? updateDOM(defaultTheme) + ';' : ''}if("system"===e||(!e&&${defaultSystem})){var t="${MEDIA}",m=window.matchMedia(t);m.media!==t||m.matches?${updateDOM('dark')}:${updateDOM('light')}}else if(e) ${value ? `var x=${JSON.stringify(value)};` : ''}${updateDOM(value ? 'x[e]' : 'e', true)}}catch(e){}}()`
}}
/>
) : (
<script
key="next-themes-script"
dangerouslySetInnerHTML={{
// prettier-ignore
__html: `!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)};}}catch(t){}}();`
}}
/>
)}
</NextHead>
);
},
(prevProps, nextProps) => {
// Only re-render when forcedTheme changes
// the rest of the props should be completely stable
if (prevProps.forcedTheme !== nextProps.forcedTheme) return false;
return true;
}
);
// Helpers
const getTheme = (key: string, fallback?: string) => {
if (typeof window === "undefined") 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) => {
if (!e) {
e = window.matchMedia(MEDIA);
}
const isDark = e.matches;
const systemTheme = isDark ? "dark" : "light";
return systemTheme;
};