@tamagui/next-theme 1.0.1-beta.100
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/NextTheme.js +264 -0
- package/dist/cjs/NextTheme.js.map +7 -0
- package/dist/cjs/index.js +18 -0
- package/dist/cjs/index.js.map +7 -0
- package/dist/esm/NextTheme.js +248 -0
- package/dist/esm/NextTheme.js.map +7 -0
- package/dist/esm/index.js +2 -0
- package/dist/esm/index.js.map +7 -0
- package/dist/jsx/NextTheme.js +219 -0
- package/dist/jsx/index.js +1 -0
- package/package.json +31 -0
- package/src/NextTheme.tsx +371 -0
- package/src/index.ts +1 -0
- package/types/NextTheme.d.ts +32 -0
- package/types/NextTheme.d.ts.map +1 -0
- package/types/index.d.ts +2 -0
- package/types/index.d.ts.map +1 -0
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
var __create = Object.create;
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __propIsEnum = Object.prototype.propertyIsEnumerable;
|
|
9
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
10
|
+
var __spreadValues = (a, b) => {
|
|
11
|
+
for (var prop in b || (b = {}))
|
|
12
|
+
if (__hasOwnProp.call(b, prop))
|
|
13
|
+
__defNormalProp(a, prop, b[prop]);
|
|
14
|
+
if (__getOwnPropSymbols)
|
|
15
|
+
for (var prop of __getOwnPropSymbols(b)) {
|
|
16
|
+
if (__propIsEnum.call(b, prop))
|
|
17
|
+
__defNormalProp(a, prop, b[prop]);
|
|
18
|
+
}
|
|
19
|
+
return a;
|
|
20
|
+
};
|
|
21
|
+
var __export = (target, all) => {
|
|
22
|
+
for (var name in all)
|
|
23
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
24
|
+
};
|
|
25
|
+
var __copyProps = (to, from, except, desc) => {
|
|
26
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
27
|
+
for (let key of __getOwnPropNames(from))
|
|
28
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
29
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
30
|
+
}
|
|
31
|
+
return to;
|
|
32
|
+
};
|
|
33
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod));
|
|
34
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
35
|
+
var NextTheme_exports = {};
|
|
36
|
+
__export(NextTheme_exports, {
|
|
37
|
+
NextThemeProvider: () => NextThemeProvider,
|
|
38
|
+
useRootTheme: () => useRootTheme,
|
|
39
|
+
useTheme: () => useTheme
|
|
40
|
+
});
|
|
41
|
+
module.exports = __toCommonJS(NextTheme_exports);
|
|
42
|
+
var import_head = __toESM(require("next/head"));
|
|
43
|
+
var React = __toESM(require("react"));
|
|
44
|
+
var import_react = require("react");
|
|
45
|
+
const useIsomorphicLayoutEffect = typeof window !== "undefined" ? import_react.useLayoutEffect : import_react.useEffect;
|
|
46
|
+
const ThemeContext = (0, import_react.createContext)({
|
|
47
|
+
toggleTheme: () => {
|
|
48
|
+
},
|
|
49
|
+
setTheme: (_) => {
|
|
50
|
+
},
|
|
51
|
+
themes: []
|
|
52
|
+
});
|
|
53
|
+
const useTheme = () => (0, import_react.useContext)(ThemeContext);
|
|
54
|
+
const colorSchemes = ["light", "dark"];
|
|
55
|
+
const MEDIA = "(prefers-color-scheme: dark)";
|
|
56
|
+
const useRootTheme = () => {
|
|
57
|
+
const isClient = typeof document !== "undefined";
|
|
58
|
+
const classes = isClient ? [...document.documentElement.classList] : [];
|
|
59
|
+
const isDark = classes.includes("t_dark");
|
|
60
|
+
return (0, import_react.useState)(isDark ? "dark" : "light");
|
|
61
|
+
};
|
|
62
|
+
const startTransition = React.startTransition || ((cb) => cb());
|
|
63
|
+
const NextThemeProvider = ({
|
|
64
|
+
forcedTheme,
|
|
65
|
+
disableTransitionOnChange = true,
|
|
66
|
+
enableSystem = true,
|
|
67
|
+
enableColorScheme = true,
|
|
68
|
+
storageKey = "theme",
|
|
69
|
+
themes = ["light", "dark"],
|
|
70
|
+
defaultTheme = enableSystem ? "system" : "light",
|
|
71
|
+
attribute = "class",
|
|
72
|
+
onChangeTheme,
|
|
73
|
+
value = {
|
|
74
|
+
dark: "t_dark",
|
|
75
|
+
light: "t_light"
|
|
76
|
+
},
|
|
77
|
+
children
|
|
78
|
+
}) => {
|
|
79
|
+
const [theme, setThemeState] = (0, import_react.useState)(() => getTheme(storageKey, defaultTheme));
|
|
80
|
+
const [resolvedTheme, setResolvedTheme] = (0, import_react.useState)(() => getTheme(storageKey));
|
|
81
|
+
const attrs = !value ? themes : Object.values(value);
|
|
82
|
+
const handleMediaQuery = (0, import_react.useCallback)((e) => {
|
|
83
|
+
const systemTheme = getSystemTheme(e);
|
|
84
|
+
startTransition(() => {
|
|
85
|
+
setResolvedTheme(systemTheme);
|
|
86
|
+
});
|
|
87
|
+
if (theme === "system" && !forcedTheme)
|
|
88
|
+
handleChangeTheme(systemTheme, false);
|
|
89
|
+
}, [theme, forcedTheme]);
|
|
90
|
+
const mediaListener = (0, import_react.useRef)(handleMediaQuery);
|
|
91
|
+
mediaListener.current = handleMediaQuery;
|
|
92
|
+
const handleChangeTheme = (0, import_react.useCallback)((theme2, updateStorage = true, updateDOM = true) => {
|
|
93
|
+
let name = (value == null ? void 0 : value[theme2]) || theme2;
|
|
94
|
+
const enable = disableTransitionOnChange && updateDOM ? disableAnimation() : null;
|
|
95
|
+
if (updateStorage) {
|
|
96
|
+
try {
|
|
97
|
+
localStorage.setItem(storageKey, theme2);
|
|
98
|
+
} catch (e) {
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
if (theme2 === "system" && enableSystem) {
|
|
102
|
+
const resolved = getSystemTheme();
|
|
103
|
+
name = (value == null ? void 0 : value[resolved]) || resolved;
|
|
104
|
+
}
|
|
105
|
+
onChangeTheme == null ? void 0 : onChangeTheme(name.replace("t_", ""));
|
|
106
|
+
if (updateDOM) {
|
|
107
|
+
const d = document.documentElement;
|
|
108
|
+
if (attribute === "class") {
|
|
109
|
+
d.classList.remove(...attrs);
|
|
110
|
+
d.classList.add(name);
|
|
111
|
+
} else {
|
|
112
|
+
d.setAttribute(attribute, name);
|
|
113
|
+
}
|
|
114
|
+
enable == null ? void 0 : enable();
|
|
115
|
+
}
|
|
116
|
+
}, []);
|
|
117
|
+
useIsomorphicLayoutEffect(() => {
|
|
118
|
+
const handler = (...args) => mediaListener.current(...args);
|
|
119
|
+
const media = window.matchMedia(MEDIA);
|
|
120
|
+
media.addListener(handler);
|
|
121
|
+
handler(media);
|
|
122
|
+
return () => {
|
|
123
|
+
media.removeListener(handler);
|
|
124
|
+
};
|
|
125
|
+
}, []);
|
|
126
|
+
const setTheme = (0, import_react.useCallback)((newTheme) => {
|
|
127
|
+
if (forcedTheme) {
|
|
128
|
+
handleChangeTheme(newTheme, true, false);
|
|
129
|
+
} else {
|
|
130
|
+
handleChangeTheme(newTheme);
|
|
131
|
+
}
|
|
132
|
+
setThemeState(newTheme);
|
|
133
|
+
}, [forcedTheme]);
|
|
134
|
+
(0, import_react.useEffect)(() => {
|
|
135
|
+
const handleStorage = (e) => {
|
|
136
|
+
if (e.key !== storageKey) {
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
const theme2 = e.newValue || defaultTheme;
|
|
140
|
+
setTheme(theme2);
|
|
141
|
+
};
|
|
142
|
+
window.addEventListener("storage", handleStorage);
|
|
143
|
+
return () => {
|
|
144
|
+
window.removeEventListener("storage", handleStorage);
|
|
145
|
+
};
|
|
146
|
+
}, []);
|
|
147
|
+
useIsomorphicLayoutEffect(() => {
|
|
148
|
+
if (!enableColorScheme)
|
|
149
|
+
return;
|
|
150
|
+
const colorScheme = forcedTheme && colorSchemes.includes(forcedTheme) ? forcedTheme : theme && colorSchemes.includes(theme) ? theme : theme === "system" ? resolvedTheme || null : null;
|
|
151
|
+
document.documentElement.style.setProperty("color-scheme", colorScheme);
|
|
152
|
+
}, [enableColorScheme, theme, resolvedTheme, forcedTheme]);
|
|
153
|
+
const contextValue = (0, import_react.useMemo)(() => {
|
|
154
|
+
return {
|
|
155
|
+
theme,
|
|
156
|
+
setTheme,
|
|
157
|
+
toggleTheme() {
|
|
158
|
+
const order = resolvedTheme === "dark" ? ["system", "light", "dark"] : ["system", "dark", "light"];
|
|
159
|
+
const next = order[(order.indexOf(theme) + 1) % order.length];
|
|
160
|
+
setTheme(next);
|
|
161
|
+
},
|
|
162
|
+
forcedTheme,
|
|
163
|
+
resolvedTheme: theme === "system" ? resolvedTheme : theme,
|
|
164
|
+
themes: enableSystem ? [...themes, "system"] : themes,
|
|
165
|
+
systemTheme: enableSystem ? resolvedTheme : void 0
|
|
166
|
+
};
|
|
167
|
+
}, [theme, forcedTheme, resolvedTheme, enableSystem]);
|
|
168
|
+
return /* @__PURE__ */ React.createElement(ThemeContext.Provider, {
|
|
169
|
+
value: contextValue
|
|
170
|
+
}, /* @__PURE__ */ React.createElement(ThemeScript, __spreadValues({}, {
|
|
171
|
+
forcedTheme,
|
|
172
|
+
storageKey,
|
|
173
|
+
systemTheme: resolvedTheme,
|
|
174
|
+
attribute,
|
|
175
|
+
value,
|
|
176
|
+
enableSystem,
|
|
177
|
+
defaultTheme,
|
|
178
|
+
attrs
|
|
179
|
+
})), children);
|
|
180
|
+
};
|
|
181
|
+
const ThemeScript = (0, import_react.memo)(({
|
|
182
|
+
forcedTheme,
|
|
183
|
+
storageKey,
|
|
184
|
+
attribute,
|
|
185
|
+
enableSystem,
|
|
186
|
+
defaultTheme,
|
|
187
|
+
value,
|
|
188
|
+
attrs
|
|
189
|
+
}) => {
|
|
190
|
+
const optimization = (() => {
|
|
191
|
+
if (attribute === "class") {
|
|
192
|
+
const removeClasses = attrs.map((t) => `d.remove('${t}')`).join(";");
|
|
193
|
+
return `var d=document.documentElement.classList;${removeClasses};`;
|
|
194
|
+
} else {
|
|
195
|
+
return `var d=document.documentElement;`;
|
|
196
|
+
}
|
|
197
|
+
})();
|
|
198
|
+
const updateDOM = (name, literal) => {
|
|
199
|
+
name = (value == null ? void 0 : value[name]) || name;
|
|
200
|
+
const val = literal ? name : `'${name}'`;
|
|
201
|
+
if (attribute === "class") {
|
|
202
|
+
return `d.add(${val})`;
|
|
203
|
+
}
|
|
204
|
+
return `d.setAttribute('${attribute}', ${val})`;
|
|
205
|
+
};
|
|
206
|
+
const defaultSystem = defaultTheme === "system";
|
|
207
|
+
return /* @__PURE__ */ React.createElement(import_head.default, null, forcedTheme ? /* @__PURE__ */ React.createElement("script", {
|
|
208
|
+
key: "next-themes-script",
|
|
209
|
+
dangerouslySetInnerHTML: {
|
|
210
|
+
__html: `!function(){${optimization}${updateDOM(forcedTheme)}}()`
|
|
211
|
+
}
|
|
212
|
+
}) : enableSystem ? /* @__PURE__ */ React.createElement("script", {
|
|
213
|
+
key: "next-themes-script",
|
|
214
|
+
dangerouslySetInnerHTML: {
|
|
215
|
+
__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){}}()`
|
|
216
|
+
}
|
|
217
|
+
}) : /* @__PURE__ */ React.createElement("script", {
|
|
218
|
+
key: "next-themes-script",
|
|
219
|
+
dangerouslySetInnerHTML: {
|
|
220
|
+
__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){}}();`
|
|
221
|
+
}
|
|
222
|
+
}));
|
|
223
|
+
}, (prevProps, nextProps) => {
|
|
224
|
+
if (prevProps.forcedTheme !== nextProps.forcedTheme)
|
|
225
|
+
return false;
|
|
226
|
+
return true;
|
|
227
|
+
});
|
|
228
|
+
const getTheme = (key, fallback) => {
|
|
229
|
+
if (typeof window === "undefined")
|
|
230
|
+
return void 0;
|
|
231
|
+
let theme;
|
|
232
|
+
try {
|
|
233
|
+
theme = localStorage.getItem(key) || void 0;
|
|
234
|
+
} catch (e) {
|
|
235
|
+
}
|
|
236
|
+
return theme || fallback;
|
|
237
|
+
};
|
|
238
|
+
const disableAnimation = () => {
|
|
239
|
+
const css = document.createElement("style");
|
|
240
|
+
css.appendChild(document.createTextNode(`*{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}`));
|
|
241
|
+
document.head.appendChild(css);
|
|
242
|
+
return () => {
|
|
243
|
+
;
|
|
244
|
+
(() => window.getComputedStyle(document.body))();
|
|
245
|
+
setTimeout(() => {
|
|
246
|
+
document.head.removeChild(css);
|
|
247
|
+
}, 1);
|
|
248
|
+
};
|
|
249
|
+
};
|
|
250
|
+
const getSystemTheme = (e) => {
|
|
251
|
+
if (!e) {
|
|
252
|
+
e = window.matchMedia(MEDIA);
|
|
253
|
+
}
|
|
254
|
+
const isDark = e.matches;
|
|
255
|
+
const systemTheme = isDark ? "dark" : "light";
|
|
256
|
+
return systemTheme;
|
|
257
|
+
};
|
|
258
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
259
|
+
0 && (module.exports = {
|
|
260
|
+
NextThemeProvider,
|
|
261
|
+
useRootTheme,
|
|
262
|
+
useTheme
|
|
263
|
+
});
|
|
264
|
+
//# sourceMappingURL=NextTheme.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/NextTheme.tsx"],
|
|
4
|
+
"sourcesContent": ["// https://raw.githubusercontent.com/pacocoursey/next-themes/master/index.tsx\n// forked temporarily due to buggy theme change\n\nimport NextHead from 'next/head'\nimport * as React from 'react'\nimport {\n createContext,\n memo,\n useCallback,\n useContext,\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n} from 'react'\n\nconst useIsomorphicLayoutEffect = typeof window !== 'undefined' ? useLayoutEffect : useEffect\n\nexport interface UseThemeProps {\n /** List of all available theme names */\n themes: string[]\n /** Forced theme name for the current page */\n forcedTheme?: string\n /** Update the theme */\n setTheme: (theme: string) => void\n toggleTheme: () => void\n /** Active theme name */\n theme?: string\n /** 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` */\n resolvedTheme?: string\n /** If enableSystem is true, returns the System theme preference (\"dark\" or \"light\"), regardless what the active theme is */\n systemTheme?: 'dark' | 'light'\n}\n\nexport interface ThemeProviderProps {\n children?: any\n /** List of all available theme names */\n themes?: string[]\n /** Forced theme name for the current page */\n forcedTheme?: string\n /** Whether to switch between dark and light themes based on prefers-color-scheme */\n enableSystem?: boolean\n systemTheme?: string\n /** Disable all CSS transitions when switching themes */\n disableTransitionOnChange?: boolean\n /** Whether to indicate to browsers which color scheme is used (dark or light) for built-in UI like inputs and buttons */\n enableColorScheme?: boolean\n /** Key used to store theme setting in localStorage */\n storageKey?: string\n /** Default theme name (for v0.0.12 and lower the default was light). If `enableSystem` is false, the default theme is light */\n defaultTheme?: string\n /** HTML attribute modified based on the active theme. Accepts `class` and `data-*` (meaning any data attribute, `data-mode`, `data-color`, etc.) */\n attribute?: string | 'class'\n /** Mapping of theme name to HTML attribute value. Object where key is the theme name and value is the attribute value */\n value?: ValueObject\n onChangeTheme?: (name: string) => void\n}\n\nconst ThemeContext = createContext<UseThemeProps>({\n toggleTheme: () => {},\n setTheme: (_) => {},\n themes: [],\n})\nexport const useTheme = () => useContext(ThemeContext)\n\nconst colorSchemes = ['light', 'dark']\nconst MEDIA = '(prefers-color-scheme: dark)'\n\ninterface ValueObject {\n [themeName: string]: string\n}\n\nexport const useRootTheme = () => {\n const isClient = typeof document !== 'undefined'\n // @ts-ignore\n const classes = isClient ? [...document.documentElement.classList] : []\n const isDark = classes.includes('t_dark')\n return useState(isDark ? 'dark' : 'light')\n}\n\n// backwards compat\nconst startTransition = React.startTransition || ((cb) => cb())\n\nexport const NextThemeProvider: React.FC<ThemeProviderProps> = ({\n forcedTheme,\n disableTransitionOnChange = true,\n enableSystem = true,\n enableColorScheme = true,\n storageKey = 'theme',\n themes = ['light', 'dark'],\n defaultTheme = enableSystem ? 'system' : 'light',\n attribute = 'class',\n onChangeTheme,\n value = {\n dark: 't_dark',\n light: 't_light',\n },\n children,\n}) => {\n const [theme, setThemeState] = useState(() => getTheme(storageKey, defaultTheme))\n const [resolvedTheme, setResolvedTheme] = useState(() => getTheme(storageKey))\n // const resolvedTheme = React.useDeferredValue(resolvedThemeFast)\n const attrs = !value ? themes : Object.values(value)\n\n const handleMediaQuery = useCallback(\n (e?) => {\n const systemTheme = getSystemTheme(e)\n startTransition(() => {\n setResolvedTheme(systemTheme)\n })\n if (theme === 'system' && !forcedTheme) handleChangeTheme(systemTheme, false)\n },\n [theme, forcedTheme]\n )\n\n // Ref hack to avoid adding handleMediaQuery as a dep\n const mediaListener = useRef(handleMediaQuery)\n mediaListener.current = handleMediaQuery\n\n const handleChangeTheme = useCallback((theme, updateStorage = true, updateDOM = true) => {\n let name = value?.[theme] || theme\n\n const enable = disableTransitionOnChange && updateDOM ? disableAnimation() : null\n\n if (updateStorage) {\n try {\n localStorage.setItem(storageKey, theme)\n } catch (e) {\n // Unsupported\n }\n }\n\n if (theme === 'system' && enableSystem) {\n const resolved = getSystemTheme()\n name = value?.[resolved] || resolved\n }\n\n onChangeTheme?.(name.replace('t_', ''))\n\n if (updateDOM) {\n const d = document.documentElement\n\n if (attribute === 'class') {\n d.classList.remove(...attrs)\n d.classList.add(name)\n } else {\n d.setAttribute(attribute, name)\n }\n enable?.()\n }\n }, [])\n\n useIsomorphicLayoutEffect(() => {\n const handler = (...args: any) => mediaListener.current(...args)\n // Always listen to System preference\n const media = window.matchMedia(MEDIA)\n // Intentionally use deprecated listener methods to support iOS & old browsers\n media.addListener(handler)\n handler(media)\n return () => {\n media.removeListener(handler)\n }\n }, [])\n\n const setTheme = useCallback(\n (newTheme) => {\n if (forcedTheme) {\n handleChangeTheme(newTheme, true, false)\n } else {\n handleChangeTheme(newTheme)\n }\n setThemeState(newTheme)\n },\n [forcedTheme]\n )\n\n // localStorage event handling\n useEffect(() => {\n const handleStorage = (e: StorageEvent) => {\n if (e.key !== storageKey) {\n return\n }\n // If default theme set, use it if localstorage === null (happens on local storage manual deletion)\n const theme = e.newValue || defaultTheme\n setTheme(theme)\n }\n window.addEventListener('storage', handleStorage)\n return () => {\n window.removeEventListener('storage', handleStorage)\n }\n }, [])\n\n // color-scheme handling\n useIsomorphicLayoutEffect(() => {\n if (!enableColorScheme) return\n\n const colorScheme =\n // If theme is forced to light or dark, use that\n forcedTheme && colorSchemes.includes(forcedTheme)\n ? forcedTheme\n : // If regular theme is light or dark\n theme && colorSchemes.includes(theme)\n ? theme\n : // If theme is system, use the resolved version\n theme === 'system'\n ? resolvedTheme || null\n : null\n\n // color-scheme tells browser how to render built-in elements like forms, scrollbars, etc.\n // if color-scheme is null, this will remove the property\n document.documentElement.style.setProperty('color-scheme', colorScheme)\n }, [enableColorScheme, theme, resolvedTheme, forcedTheme])\n\n const contextValue = useMemo(() => {\n return {\n theme,\n setTheme,\n toggleTheme() {\n const order =\n resolvedTheme === 'dark' ? ['system', 'light', 'dark'] : ['system', 'dark', 'light']\n const next = order[(order.indexOf(theme) + 1) % order.length]\n setTheme(next)\n },\n forcedTheme,\n resolvedTheme: theme === 'system' ? resolvedTheme : theme,\n themes: enableSystem ? [...themes, 'system'] : themes,\n systemTheme: (enableSystem ? resolvedTheme : undefined) as 'light' | 'dark' | undefined,\n } as const\n }, [theme, forcedTheme, resolvedTheme, enableSystem])\n\n return (\n <ThemeContext.Provider value={contextValue}>\n <ThemeScript\n {...{\n forcedTheme,\n storageKey,\n systemTheme: resolvedTheme,\n attribute,\n value,\n enableSystem,\n defaultTheme,\n attrs,\n }}\n />\n {children}\n </ThemeContext.Provider>\n )\n}\n\nconst ThemeScript = memo(\n ({\n forcedTheme,\n storageKey,\n attribute,\n enableSystem,\n defaultTheme,\n value,\n attrs,\n }: {\n forcedTheme?: string\n storageKey: string\n attribute?: string\n enableSystem?: boolean\n defaultTheme: string\n value?: ValueObject\n attrs: any\n }) => {\n // Code-golfing the amount of characters in the script\n const optimization = (() => {\n if (attribute === 'class') {\n const removeClasses = attrs.map((t: string) => `d.remove('${t}')`).join(';')\n return `var d=document.documentElement.classList;${removeClasses};`\n } else {\n return `var d=document.documentElement;`\n }\n })()\n\n const updateDOM = (name: string, literal?: boolean) => {\n name = value?.[name] || name\n const val = literal ? name : `'${name}'`\n\n if (attribute === 'class') {\n return `d.add(${val})`\n }\n\n return `d.setAttribute('${attribute}', ${val})`\n }\n\n const defaultSystem = defaultTheme === 'system'\n\n return (\n <NextHead>\n {forcedTheme ? (\n <script\n key=\"next-themes-script\"\n dangerouslySetInnerHTML={{\n // These are minified via Terser and then updated by hand, don't recommend\n // prettier-ignore\n __html: `!function(){${optimization}${updateDOM(forcedTheme)}}()`,\n }}\n />\n ) : enableSystem ? (\n <script\n key=\"next-themes-script\"\n dangerouslySetInnerHTML={{\n // prettier-ignore\n __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){}}()`,\n }}\n />\n ) : (\n <script\n key=\"next-themes-script\"\n dangerouslySetInnerHTML={{\n // prettier-ignore\n __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){}}();`,\n }}\n />\n )}\n </NextHead>\n )\n },\n (prevProps, nextProps) => {\n // Only re-render when forcedTheme changes\n // the rest of the props should be completely stable\n if (prevProps.forcedTheme !== nextProps.forcedTheme) return false\n return true\n }\n)\n\n// Helpers\nconst getTheme = (key: string, fallback?: string) => {\n if (typeof window === 'undefined') return undefined\n let theme\n try {\n theme = localStorage.getItem(key) || undefined\n } catch (e) {\n // Unsupported\n }\n return theme || fallback\n}\n\nconst disableAnimation = () => {\n const css = document.createElement('style')\n css.appendChild(\n document.createTextNode(\n `*{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}`\n )\n )\n document.head.appendChild(css)\n\n return () => {\n // Force restyle\n ;(() => window.getComputedStyle(document.body))()\n\n // Wait for next tick before removing\n setTimeout(() => {\n document.head.removeChild(css)\n }, 1)\n }\n}\n\nconst getSystemTheme = (e?: MediaQueryList) => {\n if (!e) {\n e = window.matchMedia(MEDIA)\n }\n\n const isDark = e.matches\n const systemTheme = isDark ? 'dark' : 'light'\n return systemTheme\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,kBAAqB;AACrB,YAAuB;AACvB,mBAUO;AAEP,MAAM,4BAA4B,OAAO,WAAW,cAAc,+BAAkB;A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1C,MAAI;AACJ,MAAI;AACF,YAAQ,aAAa,QAAQ,GAAG,KAAK;AAAA,EACvC,SAAS,GAAP;AAAA,EAEF;AACA,SAAO,SAAS;AAClB;AAEA,MAAM,mBAAmB,MAAM;AAC7B,QAAM,MAAM,SAAS,cAAc,OAAO;AAC1C,MAAI,YACF,SAAS,eACP,0JACF,CACF;AACA,WAAS,KAAK,YAAY,GAAG;AAE7B,SAAO,MAAM;AAEX;AAAC,IAAC,OAAM,OAAO,iBAAiB,SAAS,IAAI,GAAG;AAGhD,eAAW,MAAM;AACf,eAAS,KAAK,YAAY,GAAG;AAAA,IAC/B,GAAG,CAAC;AAAA,EACN;AACF;AAEA,MAAM,iBAAiB,CAAC,MAAuB;AAC7C,MAAI,CAAC,GAAG;AACN,QAAI,OAAO,WAAW,KAAK;AAAA,EAC7B;AAEA,QAAM,SAAS,EAAE;AACjB,QAAM,cAAc,SAAS,SAAS;AACtC,SAAO;AACT;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
3
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
5
|
+
var __copyProps = (to, from, except, desc) => {
|
|
6
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
7
|
+
for (let key of __getOwnPropNames(from))
|
|
8
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
9
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
10
|
+
}
|
|
11
|
+
return to;
|
|
12
|
+
};
|
|
13
|
+
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
|
|
14
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
15
|
+
var src_exports = {};
|
|
16
|
+
module.exports = __toCommonJS(src_exports);
|
|
17
|
+
__reExport(src_exports, require("./NextTheme"), module.exports);
|
|
18
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
|
3
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
4
|
+
var __propIsEnum = Object.prototype.propertyIsEnumerable;
|
|
5
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
6
|
+
var __spreadValues = (a, b) => {
|
|
7
|
+
for (var prop in b || (b = {}))
|
|
8
|
+
if (__hasOwnProp.call(b, prop))
|
|
9
|
+
__defNormalProp(a, prop, b[prop]);
|
|
10
|
+
if (__getOwnPropSymbols)
|
|
11
|
+
for (var prop of __getOwnPropSymbols(b)) {
|
|
12
|
+
if (__propIsEnum.call(b, prop))
|
|
13
|
+
__defNormalProp(a, prop, b[prop]);
|
|
14
|
+
}
|
|
15
|
+
return a;
|
|
16
|
+
};
|
|
17
|
+
import NextHead from "next/head";
|
|
18
|
+
import * as React from "react";
|
|
19
|
+
import {
|
|
20
|
+
createContext,
|
|
21
|
+
memo,
|
|
22
|
+
useCallback,
|
|
23
|
+
useContext,
|
|
24
|
+
useEffect,
|
|
25
|
+
useLayoutEffect,
|
|
26
|
+
useMemo,
|
|
27
|
+
useRef,
|
|
28
|
+
useState
|
|
29
|
+
} from "react";
|
|
30
|
+
const useIsomorphicLayoutEffect = typeof window !== "undefined" ? useLayoutEffect : useEffect;
|
|
31
|
+
const ThemeContext = createContext({
|
|
32
|
+
toggleTheme: () => {
|
|
33
|
+
},
|
|
34
|
+
setTheme: (_) => {
|
|
35
|
+
},
|
|
36
|
+
themes: []
|
|
37
|
+
});
|
|
38
|
+
const useTheme = () => useContext(ThemeContext);
|
|
39
|
+
const colorSchemes = ["light", "dark"];
|
|
40
|
+
const MEDIA = "(prefers-color-scheme: dark)";
|
|
41
|
+
const useRootTheme = () => {
|
|
42
|
+
const isClient = typeof document !== "undefined";
|
|
43
|
+
const classes = isClient ? [...document.documentElement.classList] : [];
|
|
44
|
+
const isDark = classes.includes("t_dark");
|
|
45
|
+
return useState(isDark ? "dark" : "light");
|
|
46
|
+
};
|
|
47
|
+
const startTransition = React.startTransition || ((cb) => cb());
|
|
48
|
+
const NextThemeProvider = ({
|
|
49
|
+
forcedTheme,
|
|
50
|
+
disableTransitionOnChange = true,
|
|
51
|
+
enableSystem = true,
|
|
52
|
+
enableColorScheme = true,
|
|
53
|
+
storageKey = "theme",
|
|
54
|
+
themes = ["light", "dark"],
|
|
55
|
+
defaultTheme = enableSystem ? "system" : "light",
|
|
56
|
+
attribute = "class",
|
|
57
|
+
onChangeTheme,
|
|
58
|
+
value = {
|
|
59
|
+
dark: "t_dark",
|
|
60
|
+
light: "t_light"
|
|
61
|
+
},
|
|
62
|
+
children
|
|
63
|
+
}) => {
|
|
64
|
+
const [theme, setThemeState] = useState(() => getTheme(storageKey, defaultTheme));
|
|
65
|
+
const [resolvedTheme, setResolvedTheme] = useState(() => getTheme(storageKey));
|
|
66
|
+
const attrs = !value ? themes : Object.values(value);
|
|
67
|
+
const handleMediaQuery = useCallback((e) => {
|
|
68
|
+
const systemTheme = getSystemTheme(e);
|
|
69
|
+
startTransition(() => {
|
|
70
|
+
setResolvedTheme(systemTheme);
|
|
71
|
+
});
|
|
72
|
+
if (theme === "system" && !forcedTheme)
|
|
73
|
+
handleChangeTheme(systemTheme, false);
|
|
74
|
+
}, [theme, forcedTheme]);
|
|
75
|
+
const mediaListener = useRef(handleMediaQuery);
|
|
76
|
+
mediaListener.current = handleMediaQuery;
|
|
77
|
+
const handleChangeTheme = useCallback((theme2, updateStorage = true, updateDOM = true) => {
|
|
78
|
+
let name = (value == null ? void 0 : value[theme2]) || theme2;
|
|
79
|
+
const enable = disableTransitionOnChange && updateDOM ? disableAnimation() : null;
|
|
80
|
+
if (updateStorage) {
|
|
81
|
+
try {
|
|
82
|
+
localStorage.setItem(storageKey, theme2);
|
|
83
|
+
} catch (e) {
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
if (theme2 === "system" && enableSystem) {
|
|
87
|
+
const resolved = getSystemTheme();
|
|
88
|
+
name = (value == null ? void 0 : value[resolved]) || resolved;
|
|
89
|
+
}
|
|
90
|
+
onChangeTheme == null ? void 0 : onChangeTheme(name.replace("t_", ""));
|
|
91
|
+
if (updateDOM) {
|
|
92
|
+
const d = document.documentElement;
|
|
93
|
+
if (attribute === "class") {
|
|
94
|
+
d.classList.remove(...attrs);
|
|
95
|
+
d.classList.add(name);
|
|
96
|
+
} else {
|
|
97
|
+
d.setAttribute(attribute, name);
|
|
98
|
+
}
|
|
99
|
+
enable == null ? void 0 : enable();
|
|
100
|
+
}
|
|
101
|
+
}, []);
|
|
102
|
+
useIsomorphicLayoutEffect(() => {
|
|
103
|
+
const handler = (...args) => mediaListener.current(...args);
|
|
104
|
+
const media = window.matchMedia(MEDIA);
|
|
105
|
+
media.addListener(handler);
|
|
106
|
+
handler(media);
|
|
107
|
+
return () => {
|
|
108
|
+
media.removeListener(handler);
|
|
109
|
+
};
|
|
110
|
+
}, []);
|
|
111
|
+
const setTheme = useCallback((newTheme) => {
|
|
112
|
+
if (forcedTheme) {
|
|
113
|
+
handleChangeTheme(newTheme, true, false);
|
|
114
|
+
} else {
|
|
115
|
+
handleChangeTheme(newTheme);
|
|
116
|
+
}
|
|
117
|
+
setThemeState(newTheme);
|
|
118
|
+
}, [forcedTheme]);
|
|
119
|
+
useEffect(() => {
|
|
120
|
+
const handleStorage = (e) => {
|
|
121
|
+
if (e.key !== storageKey) {
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
const theme2 = e.newValue || defaultTheme;
|
|
125
|
+
setTheme(theme2);
|
|
126
|
+
};
|
|
127
|
+
window.addEventListener("storage", handleStorage);
|
|
128
|
+
return () => {
|
|
129
|
+
window.removeEventListener("storage", handleStorage);
|
|
130
|
+
};
|
|
131
|
+
}, []);
|
|
132
|
+
useIsomorphicLayoutEffect(() => {
|
|
133
|
+
if (!enableColorScheme)
|
|
134
|
+
return;
|
|
135
|
+
const colorScheme = forcedTheme && colorSchemes.includes(forcedTheme) ? forcedTheme : theme && colorSchemes.includes(theme) ? theme : theme === "system" ? resolvedTheme || null : null;
|
|
136
|
+
document.documentElement.style.setProperty("color-scheme", colorScheme);
|
|
137
|
+
}, [enableColorScheme, theme, resolvedTheme, forcedTheme]);
|
|
138
|
+
const contextValue = useMemo(() => {
|
|
139
|
+
return {
|
|
140
|
+
theme,
|
|
141
|
+
setTheme,
|
|
142
|
+
toggleTheme() {
|
|
143
|
+
const order = resolvedTheme === "dark" ? ["system", "light", "dark"] : ["system", "dark", "light"];
|
|
144
|
+
const next = order[(order.indexOf(theme) + 1) % order.length];
|
|
145
|
+
setTheme(next);
|
|
146
|
+
},
|
|
147
|
+
forcedTheme,
|
|
148
|
+
resolvedTheme: theme === "system" ? resolvedTheme : theme,
|
|
149
|
+
themes: enableSystem ? [...themes, "system"] : themes,
|
|
150
|
+
systemTheme: enableSystem ? resolvedTheme : void 0
|
|
151
|
+
};
|
|
152
|
+
}, [theme, forcedTheme, resolvedTheme, enableSystem]);
|
|
153
|
+
return /* @__PURE__ */ React.createElement(ThemeContext.Provider, {
|
|
154
|
+
value: contextValue
|
|
155
|
+
}, /* @__PURE__ */ React.createElement(ThemeScript, __spreadValues({}, {
|
|
156
|
+
forcedTheme,
|
|
157
|
+
storageKey,
|
|
158
|
+
systemTheme: resolvedTheme,
|
|
159
|
+
attribute,
|
|
160
|
+
value,
|
|
161
|
+
enableSystem,
|
|
162
|
+
defaultTheme,
|
|
163
|
+
attrs
|
|
164
|
+
})), children);
|
|
165
|
+
};
|
|
166
|
+
const ThemeScript = memo(({
|
|
167
|
+
forcedTheme,
|
|
168
|
+
storageKey,
|
|
169
|
+
attribute,
|
|
170
|
+
enableSystem,
|
|
171
|
+
defaultTheme,
|
|
172
|
+
value,
|
|
173
|
+
attrs
|
|
174
|
+
}) => {
|
|
175
|
+
const optimization = (() => {
|
|
176
|
+
if (attribute === "class") {
|
|
177
|
+
const removeClasses = attrs.map((t) => `d.remove('${t}')`).join(";");
|
|
178
|
+
return `var d=document.documentElement.classList;${removeClasses};`;
|
|
179
|
+
} else {
|
|
180
|
+
return `var d=document.documentElement;`;
|
|
181
|
+
}
|
|
182
|
+
})();
|
|
183
|
+
const updateDOM = (name, literal) => {
|
|
184
|
+
name = (value == null ? void 0 : value[name]) || name;
|
|
185
|
+
const val = literal ? name : `'${name}'`;
|
|
186
|
+
if (attribute === "class") {
|
|
187
|
+
return `d.add(${val})`;
|
|
188
|
+
}
|
|
189
|
+
return `d.setAttribute('${attribute}', ${val})`;
|
|
190
|
+
};
|
|
191
|
+
const defaultSystem = defaultTheme === "system";
|
|
192
|
+
return /* @__PURE__ */ React.createElement(NextHead, null, forcedTheme ? /* @__PURE__ */ React.createElement("script", {
|
|
193
|
+
key: "next-themes-script",
|
|
194
|
+
dangerouslySetInnerHTML: {
|
|
195
|
+
__html: `!function(){${optimization}${updateDOM(forcedTheme)}}()`
|
|
196
|
+
}
|
|
197
|
+
}) : enableSystem ? /* @__PURE__ */ React.createElement("script", {
|
|
198
|
+
key: "next-themes-script",
|
|
199
|
+
dangerouslySetInnerHTML: {
|
|
200
|
+
__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){}}()`
|
|
201
|
+
}
|
|
202
|
+
}) : /* @__PURE__ */ React.createElement("script", {
|
|
203
|
+
key: "next-themes-script",
|
|
204
|
+
dangerouslySetInnerHTML: {
|
|
205
|
+
__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){}}();`
|
|
206
|
+
}
|
|
207
|
+
}));
|
|
208
|
+
}, (prevProps, nextProps) => {
|
|
209
|
+
if (prevProps.forcedTheme !== nextProps.forcedTheme)
|
|
210
|
+
return false;
|
|
211
|
+
return true;
|
|
212
|
+
});
|
|
213
|
+
const getTheme = (key, fallback) => {
|
|
214
|
+
if (typeof window === "undefined")
|
|
215
|
+
return void 0;
|
|
216
|
+
let theme;
|
|
217
|
+
try {
|
|
218
|
+
theme = localStorage.getItem(key) || void 0;
|
|
219
|
+
} catch (e) {
|
|
220
|
+
}
|
|
221
|
+
return theme || fallback;
|
|
222
|
+
};
|
|
223
|
+
const disableAnimation = () => {
|
|
224
|
+
const css = document.createElement("style");
|
|
225
|
+
css.appendChild(document.createTextNode(`*{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}`));
|
|
226
|
+
document.head.appendChild(css);
|
|
227
|
+
return () => {
|
|
228
|
+
;
|
|
229
|
+
(() => window.getComputedStyle(document.body))();
|
|
230
|
+
setTimeout(() => {
|
|
231
|
+
document.head.removeChild(css);
|
|
232
|
+
}, 1);
|
|
233
|
+
};
|
|
234
|
+
};
|
|
235
|
+
const getSystemTheme = (e) => {
|
|
236
|
+
if (!e) {
|
|
237
|
+
e = window.matchMedia(MEDIA);
|
|
238
|
+
}
|
|
239
|
+
const isDark = e.matches;
|
|
240
|
+
const systemTheme = isDark ? "dark" : "light";
|
|
241
|
+
return systemTheme;
|
|
242
|
+
};
|
|
243
|
+
export {
|
|
244
|
+
NextThemeProvider,
|
|
245
|
+
useRootTheme,
|
|
246
|
+
useTheme
|
|
247
|
+
};
|
|
248
|
+
//# sourceMappingURL=NextTheme.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/NextTheme.tsx"],
|
|
4
|
+
"sourcesContent": ["// https://raw.githubusercontent.com/pacocoursey/next-themes/master/index.tsx\n// forked temporarily due to buggy theme change\n\nimport NextHead from 'next/head'\nimport * as React from 'react'\nimport {\n createContext,\n memo,\n useCallback,\n useContext,\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n} from 'react'\n\nconst useIsomorphicLayoutEffect = typeof window !== 'undefined' ? useLayoutEffect : useEffect\n\nexport interface UseThemeProps {\n /** List of all available theme names */\n themes: string[]\n /** Forced theme name for the current page */\n forcedTheme?: string\n /** Update the theme */\n setTheme: (theme: string) => void\n toggleTheme: () => void\n /** Active theme name */\n theme?: string\n /** 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` */\n resolvedTheme?: string\n /** If enableSystem is true, returns the System theme preference (\"dark\" or \"light\"), regardless what the active theme is */\n systemTheme?: 'dark' | 'light'\n}\n\nexport interface ThemeProviderProps {\n children?: any\n /** List of all available theme names */\n themes?: string[]\n /** Forced theme name for the current page */\n forcedTheme?: string\n /** Whether to switch between dark and light themes based on prefers-color-scheme */\n enableSystem?: boolean\n systemTheme?: string\n /** Disable all CSS transitions when switching themes */\n disableTransitionOnChange?: boolean\n /** Whether to indicate to browsers which color scheme is used (dark or light) for built-in UI like inputs and buttons */\n enableColorScheme?: boolean\n /** Key used to store theme setting in localStorage */\n storageKey?: string\n /** Default theme name (for v0.0.12 and lower the default was light). If `enableSystem` is false, the default theme is light */\n defaultTheme?: string\n /** HTML attribute modified based on the active theme. Accepts `class` and `data-*` (meaning any data attribute, `data-mode`, `data-color`, etc.) */\n attribute?: string | 'class'\n /** Mapping of theme name to HTML attribute value. Object where key is the theme name and value is the attribute value */\n value?: ValueObject\n onChangeTheme?: (name: string) => void\n}\n\nconst ThemeContext = createContext<UseThemeProps>({\n toggleTheme: () => {},\n setTheme: (_) => {},\n themes: [],\n})\nexport const useTheme = () => useContext(ThemeContext)\n\nconst colorSchemes = ['light', 'dark']\nconst MEDIA = '(prefers-color-scheme: dark)'\n\ninterface ValueObject {\n [themeName: string]: string\n}\n\nexport const useRootTheme = () => {\n const isClient = typeof document !== 'undefined'\n // @ts-ignore\n const classes = isClient ? [...document.documentElement.classList] : []\n const isDark = classes.includes('t_dark')\n return useState(isDark ? 'dark' : 'light')\n}\n\n// backwards compat\nconst startTransition = React.startTransition || ((cb) => cb())\n\nexport const NextThemeProvider: React.FC<ThemeProviderProps> = ({\n forcedTheme,\n disableTransitionOnChange = true,\n enableSystem = true,\n enableColorScheme = true,\n storageKey = 'theme',\n themes = ['light', 'dark'],\n defaultTheme = enableSystem ? 'system' : 'light',\n attribute = 'class',\n onChangeTheme,\n value = {\n dark: 't_dark',\n light: 't_light',\n },\n children,\n}) => {\n const [theme, setThemeState] = useState(() => getTheme(storageKey, defaultTheme))\n const [resolvedTheme, setResolvedTheme] = useState(() => getTheme(storageKey))\n // const resolvedTheme = React.useDeferredValue(resolvedThemeFast)\n const attrs = !value ? themes : Object.values(value)\n\n const handleMediaQuery = useCallback(\n (e?) => {\n const systemTheme = getSystemTheme(e)\n startTransition(() => {\n setResolvedTheme(systemTheme)\n })\n if (theme === 'system' && !forcedTheme) handleChangeTheme(systemTheme, false)\n },\n [theme, forcedTheme]\n )\n\n // Ref hack to avoid adding handleMediaQuery as a dep\n const mediaListener = useRef(handleMediaQuery)\n mediaListener.current = handleMediaQuery\n\n const handleChangeTheme = useCallback((theme, updateStorage = true, updateDOM = true) => {\n let name = value?.[theme] || theme\n\n const enable = disableTransitionOnChange && updateDOM ? disableAnimation() : null\n\n if (updateStorage) {\n try {\n localStorage.setItem(storageKey, theme)\n } catch (e) {\n // Unsupported\n }\n }\n\n if (theme === 'system' && enableSystem) {\n const resolved = getSystemTheme()\n name = value?.[resolved] || resolved\n }\n\n onChangeTheme?.(name.replace('t_', ''))\n\n if (updateDOM) {\n const d = document.documentElement\n\n if (attribute === 'class') {\n d.classList.remove(...attrs)\n d.classList.add(name)\n } else {\n d.setAttribute(attribute, name)\n }\n enable?.()\n }\n }, [])\n\n useIsomorphicLayoutEffect(() => {\n const handler = (...args: any) => mediaListener.current(...args)\n // Always listen to System preference\n const media = window.matchMedia(MEDIA)\n // Intentionally use deprecated listener methods to support iOS & old browsers\n media.addListener(handler)\n handler(media)\n return () => {\n media.removeListener(handler)\n }\n }, [])\n\n const setTheme = useCallback(\n (newTheme) => {\n if (forcedTheme) {\n handleChangeTheme(newTheme, true, false)\n } else {\n handleChangeTheme(newTheme)\n }\n setThemeState(newTheme)\n },\n [forcedTheme]\n )\n\n // localStorage event handling\n useEffect(() => {\n const handleStorage = (e: StorageEvent) => {\n if (e.key !== storageKey) {\n return\n }\n // If default theme set, use it if localstorage === null (happens on local storage manual deletion)\n const theme = e.newValue || defaultTheme\n setTheme(theme)\n }\n window.addEventListener('storage', handleStorage)\n return () => {\n window.removeEventListener('storage', handleStorage)\n }\n }, [])\n\n // color-scheme handling\n useIsomorphicLayoutEffect(() => {\n if (!enableColorScheme) return\n\n const colorScheme =\n // If theme is forced to light or dark, use that\n forcedTheme && colorSchemes.includes(forcedTheme)\n ? forcedTheme\n : // If regular theme is light or dark\n theme && colorSchemes.includes(theme)\n ? theme\n : // If theme is system, use the resolved version\n theme === 'system'\n ? resolvedTheme || null\n : null\n\n // color-scheme tells browser how to render built-in elements like forms, scrollbars, etc.\n // if color-scheme is null, this will remove the property\n document.documentElement.style.setProperty('color-scheme', colorScheme)\n }, [enableColorScheme, theme, resolvedTheme, forcedTheme])\n\n const contextValue = useMemo(() => {\n return {\n theme,\n setTheme,\n toggleTheme() {\n const order =\n resolvedTheme === 'dark' ? ['system', 'light', 'dark'] : ['system', 'dark', 'light']\n const next = order[(order.indexOf(theme) + 1) % order.length]\n setTheme(next)\n },\n forcedTheme,\n resolvedTheme: theme === 'system' ? resolvedTheme : theme,\n themes: enableSystem ? [...themes, 'system'] : themes,\n systemTheme: (enableSystem ? resolvedTheme : undefined) as 'light' | 'dark' | undefined,\n } as const\n }, [theme, forcedTheme, resolvedTheme, enableSystem])\n\n return (\n <ThemeContext.Provider value={contextValue}>\n <ThemeScript\n {...{\n forcedTheme,\n storageKey,\n systemTheme: resolvedTheme,\n attribute,\n value,\n enableSystem,\n defaultTheme,\n attrs,\n }}\n />\n {children}\n </ThemeContext.Provider>\n )\n}\n\nconst ThemeScript = memo(\n ({\n forcedTheme,\n storageKey,\n attribute,\n enableSystem,\n defaultTheme,\n value,\n attrs,\n }: {\n forcedTheme?: string\n storageKey: string\n attribute?: string\n enableSystem?: boolean\n defaultTheme: string\n value?: ValueObject\n attrs: any\n }) => {\n // Code-golfing the amount of characters in the script\n const optimization = (() => {\n if (attribute === 'class') {\n const removeClasses = attrs.map((t: string) => `d.remove('${t}')`).join(';')\n return `var d=document.documentElement.classList;${removeClasses};`\n } else {\n return `var d=document.documentElement;`\n }\n })()\n\n const updateDOM = (name: string, literal?: boolean) => {\n name = value?.[name] || name\n const val = literal ? name : `'${name}'`\n\n if (attribute === 'class') {\n return `d.add(${val})`\n }\n\n return `d.setAttribute('${attribute}', ${val})`\n }\n\n const defaultSystem = defaultTheme === 'system'\n\n return (\n <NextHead>\n {forcedTheme ? (\n <script\n key=\"next-themes-script\"\n dangerouslySetInnerHTML={{\n // These are minified via Terser and then updated by hand, don't recommend\n // prettier-ignore\n __html: `!function(){${optimization}${updateDOM(forcedTheme)}}()`,\n }}\n />\n ) : enableSystem ? (\n <script\n key=\"next-themes-script\"\n dangerouslySetInnerHTML={{\n // prettier-ignore\n __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){}}()`,\n }}\n />\n ) : (\n <script\n key=\"next-themes-script\"\n dangerouslySetInnerHTML={{\n // prettier-ignore\n __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){}}();`,\n }}\n />\n )}\n </NextHead>\n )\n },\n (prevProps, nextProps) => {\n // Only re-render when forcedTheme changes\n // the rest of the props should be completely stable\n if (prevProps.forcedTheme !== nextProps.forcedTheme) return false\n return true\n }\n)\n\n// Helpers\nconst getTheme = (key: string, fallback?: string) => {\n if (typeof window === 'undefined') return undefined\n let theme\n try {\n theme = localStorage.getItem(key) || undefined\n } catch (e) {\n // Unsupported\n }\n return theme || fallback\n}\n\nconst disableAnimation = () => {\n const css = document.createElement('style')\n css.appendChild(\n document.createTextNode(\n `*{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}`\n )\n )\n document.head.appendChild(css)\n\n return () => {\n // Force restyle\n ;(() => window.getComputedStyle(document.body))()\n\n // Wait for next tick before removing\n setTimeout(() => {\n document.head.removeChild(css)\n }, 1)\n }\n}\n\nconst getSystemTheme = (e?: MediaQueryList) => {\n if (!e) {\n e = window.matchMedia(MEDIA)\n }\n\n const isDark = e.matches\n const systemTheme = isDark ? 'dark' : 'light'\n return systemTheme\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;AAGA;AACA;AACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAYA,MAAM,4BAA4B,OAAO,WAAW,cAAc,kBAAkB;AA0CpF,MAAM,eAAe,cAA6B;AAAA,EAChD,aAAa,MAAM;AAAA,EAAC;AAAA,EACpB,UAAU,CAAC,MAAM;AAAA,EAAC;AAAA,EAClB,QAAQ,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MAAM;AAC7B,QAAM,MAAM,SAAS,cAAc,OAAO;AAC1C,MAAI,YACF,SAAS,eACP,0JACF,CACF;AACA,WAAS,KAAK,YAAY,GAAG;AAE7B,SAAO,MAAM;AAEX;AAAC,IAAC,OAAM,OAAO,iBAAiB,SAAS,IAAI,GAAG;AAGhD,eAAW,MAAM;AACf,eAAS,KAAK,YAAY,GAAG;AAAA,IAC/B,GAAG,CAAC;AAAA,EACN;AACF;AAEA,MAAM,iBAAiB,CAAC,MAAuB;AAC7C,MAAI,CAAC,GAAG;AACN,QAAI,OAAO,WAAW,KAAK;AAAA,EAC7B;AAEA,QAAM,SAAS,EAAE;AACjB,QAAM,cAAc,SAAS,SAAS;AACtC,SAAO;AACT;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
import NextHead from "next/head";
|
|
2
|
+
import {
|
|
3
|
+
createContext,
|
|
4
|
+
memo,
|
|
5
|
+
useCallback,
|
|
6
|
+
useContext,
|
|
7
|
+
useEffect,
|
|
8
|
+
useLayoutEffect,
|
|
9
|
+
useMemo,
|
|
10
|
+
useRef,
|
|
11
|
+
useState
|
|
12
|
+
} from "react";
|
|
13
|
+
const useIsomorphicLayoutEffect = typeof window !== "undefined" ? useLayoutEffect : useEffect;
|
|
14
|
+
const ThemeContext = createContext({
|
|
15
|
+
toggleTheme: () => {
|
|
16
|
+
},
|
|
17
|
+
setTheme: (_) => {
|
|
18
|
+
},
|
|
19
|
+
themes: []
|
|
20
|
+
});
|
|
21
|
+
const useTheme = () => useContext(ThemeContext);
|
|
22
|
+
const colorSchemes = ["light", "dark"];
|
|
23
|
+
const MEDIA = "(prefers-color-scheme: dark)";
|
|
24
|
+
const useRootTheme = () => {
|
|
25
|
+
const isClient = typeof document !== "undefined";
|
|
26
|
+
const classes = isClient ? [...document.documentElement.classList] : [];
|
|
27
|
+
const isDark = classes.includes("t_dark");
|
|
28
|
+
return useState(isDark ? "dark" : "light");
|
|
29
|
+
};
|
|
30
|
+
const NextThemeProvider = ({
|
|
31
|
+
forcedTheme,
|
|
32
|
+
disableTransitionOnChange = true,
|
|
33
|
+
enableSystem = true,
|
|
34
|
+
enableColorScheme = true,
|
|
35
|
+
storageKey = "theme",
|
|
36
|
+
themes = ["light", "dark"],
|
|
37
|
+
defaultTheme = enableSystem ? "system" : "light",
|
|
38
|
+
attribute = "class",
|
|
39
|
+
onChangeTheme,
|
|
40
|
+
value = {
|
|
41
|
+
dark: "t_dark",
|
|
42
|
+
light: "t_light"
|
|
43
|
+
},
|
|
44
|
+
children
|
|
45
|
+
}) => {
|
|
46
|
+
const [theme, setThemeState] = useState(() => getTheme(storageKey, defaultTheme));
|
|
47
|
+
const [resolvedTheme, setResolvedTheme] = useState(() => getTheme(storageKey));
|
|
48
|
+
const attrs = !value ? themes : Object.values(value);
|
|
49
|
+
const handleMediaQuery = useCallback((e) => {
|
|
50
|
+
const systemTheme = getSystemTheme(e);
|
|
51
|
+
setResolvedTheme(systemTheme);
|
|
52
|
+
if (theme === "system" && !forcedTheme)
|
|
53
|
+
handleChangeTheme(systemTheme, false);
|
|
54
|
+
}, [theme, forcedTheme]);
|
|
55
|
+
const mediaListener = useRef(handleMediaQuery);
|
|
56
|
+
mediaListener.current = handleMediaQuery;
|
|
57
|
+
const handleChangeTheme = useCallback((theme2, updateStorage = true, updateDOM = true) => {
|
|
58
|
+
let name = (value == null ? void 0 : value[theme2]) || theme2;
|
|
59
|
+
const enable = disableTransitionOnChange && updateDOM ? disableAnimation() : null;
|
|
60
|
+
if (updateStorage) {
|
|
61
|
+
try {
|
|
62
|
+
localStorage.setItem(storageKey, theme2);
|
|
63
|
+
} catch (e) {
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
if (theme2 === "system" && enableSystem) {
|
|
67
|
+
const resolved = getSystemTheme();
|
|
68
|
+
name = (value == null ? void 0 : value[resolved]) || resolved;
|
|
69
|
+
}
|
|
70
|
+
onChangeTheme == null ? void 0 : onChangeTheme(name.replace("t_", ""));
|
|
71
|
+
if (updateDOM) {
|
|
72
|
+
const d = document.documentElement;
|
|
73
|
+
if (attribute === "class") {
|
|
74
|
+
d.classList.remove(...attrs);
|
|
75
|
+
d.classList.add(name);
|
|
76
|
+
} else {
|
|
77
|
+
d.setAttribute(attribute, name);
|
|
78
|
+
}
|
|
79
|
+
enable == null ? void 0 : enable();
|
|
80
|
+
}
|
|
81
|
+
}, []);
|
|
82
|
+
useIsomorphicLayoutEffect(() => {
|
|
83
|
+
const handler = (...args) => mediaListener.current(...args);
|
|
84
|
+
const media = window.matchMedia(MEDIA);
|
|
85
|
+
media.addListener(handler);
|
|
86
|
+
handler(media);
|
|
87
|
+
return () => {
|
|
88
|
+
media.removeListener(handler);
|
|
89
|
+
};
|
|
90
|
+
}, []);
|
|
91
|
+
const setTheme = useCallback((newTheme) => {
|
|
92
|
+
if (forcedTheme) {
|
|
93
|
+
handleChangeTheme(newTheme, true, false);
|
|
94
|
+
} else {
|
|
95
|
+
handleChangeTheme(newTheme);
|
|
96
|
+
}
|
|
97
|
+
setThemeState(newTheme);
|
|
98
|
+
}, [forcedTheme]);
|
|
99
|
+
useEffect(() => {
|
|
100
|
+
const handleStorage = (e) => {
|
|
101
|
+
if (e.key !== storageKey) {
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
const theme2 = e.newValue || defaultTheme;
|
|
105
|
+
setTheme(theme2);
|
|
106
|
+
};
|
|
107
|
+
window.addEventListener("storage", handleStorage);
|
|
108
|
+
return () => {
|
|
109
|
+
window.removeEventListener("storage", handleStorage);
|
|
110
|
+
};
|
|
111
|
+
}, []);
|
|
112
|
+
useIsomorphicLayoutEffect(() => {
|
|
113
|
+
if (!enableColorScheme)
|
|
114
|
+
return;
|
|
115
|
+
let colorScheme = forcedTheme && colorSchemes.includes(forcedTheme) ? forcedTheme : theme && colorSchemes.includes(theme) ? theme : theme === "system" ? resolvedTheme || null : null;
|
|
116
|
+
document.documentElement.style.setProperty("color-scheme", colorScheme);
|
|
117
|
+
}, [enableColorScheme, theme, resolvedTheme, forcedTheme]);
|
|
118
|
+
const contextValue = useMemo(() => {
|
|
119
|
+
return {
|
|
120
|
+
theme,
|
|
121
|
+
setTheme,
|
|
122
|
+
toggleTheme() {
|
|
123
|
+
const order = resolvedTheme === "dark" ? ["system", "light", "dark"] : ["system", "dark", "light"];
|
|
124
|
+
const next = order[(order.indexOf(theme) + 1) % order.length];
|
|
125
|
+
setTheme(next);
|
|
126
|
+
},
|
|
127
|
+
forcedTheme,
|
|
128
|
+
resolvedTheme: theme === "system" ? resolvedTheme : theme,
|
|
129
|
+
themes: enableSystem ? [...themes, "system"] : themes,
|
|
130
|
+
systemTheme: enableSystem ? resolvedTheme : void 0
|
|
131
|
+
};
|
|
132
|
+
}, [theme, forcedTheme, resolvedTheme, enableSystem]);
|
|
133
|
+
return <ThemeContext.Provider value={contextValue}>
|
|
134
|
+
<ThemeScript {...{
|
|
135
|
+
forcedTheme,
|
|
136
|
+
storageKey,
|
|
137
|
+
systemTheme: resolvedTheme,
|
|
138
|
+
attribute,
|
|
139
|
+
value,
|
|
140
|
+
enableSystem,
|
|
141
|
+
defaultTheme,
|
|
142
|
+
attrs
|
|
143
|
+
}} />
|
|
144
|
+
{children}
|
|
145
|
+
</ThemeContext.Provider>;
|
|
146
|
+
};
|
|
147
|
+
const ThemeScript = memo(({
|
|
148
|
+
forcedTheme,
|
|
149
|
+
storageKey,
|
|
150
|
+
attribute,
|
|
151
|
+
enableSystem,
|
|
152
|
+
defaultTheme,
|
|
153
|
+
value,
|
|
154
|
+
attrs
|
|
155
|
+
}) => {
|
|
156
|
+
const optimization = (() => {
|
|
157
|
+
if (attribute === "class") {
|
|
158
|
+
const removeClasses = attrs.map((t) => `d.remove('${t}')`).join(";");
|
|
159
|
+
return `var d=document.documentElement.classList;${removeClasses};`;
|
|
160
|
+
} else {
|
|
161
|
+
return `var d=document.documentElement;`;
|
|
162
|
+
}
|
|
163
|
+
})();
|
|
164
|
+
const updateDOM = (name, literal) => {
|
|
165
|
+
name = (value == null ? void 0 : value[name]) || name;
|
|
166
|
+
const val = literal ? name : `'${name}'`;
|
|
167
|
+
if (attribute === "class") {
|
|
168
|
+
return `d.add(${val})`;
|
|
169
|
+
}
|
|
170
|
+
return `d.setAttribute('${attribute}', ${val})`;
|
|
171
|
+
};
|
|
172
|
+
const defaultSystem = defaultTheme === "system";
|
|
173
|
+
return <NextHead>{forcedTheme ? <script key="next-themes-script" dangerouslySetInnerHTML={{
|
|
174
|
+
__html: `!function(){${optimization}${updateDOM(forcedTheme)}}()`
|
|
175
|
+
}} /> : enableSystem ? <script key="next-themes-script" dangerouslySetInnerHTML={{
|
|
176
|
+
__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){}}()`
|
|
177
|
+
}} /> : <script key="next-themes-script" dangerouslySetInnerHTML={{
|
|
178
|
+
__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){}}();`
|
|
179
|
+
}} />}</NextHead>;
|
|
180
|
+
}, (prevProps, nextProps) => {
|
|
181
|
+
if (prevProps.forcedTheme !== nextProps.forcedTheme)
|
|
182
|
+
return false;
|
|
183
|
+
return true;
|
|
184
|
+
});
|
|
185
|
+
const getTheme = (key, fallback) => {
|
|
186
|
+
if (typeof window === "undefined")
|
|
187
|
+
return void 0;
|
|
188
|
+
let theme;
|
|
189
|
+
try {
|
|
190
|
+
theme = localStorage.getItem(key) || void 0;
|
|
191
|
+
} catch (e) {
|
|
192
|
+
}
|
|
193
|
+
return theme || fallback;
|
|
194
|
+
};
|
|
195
|
+
const disableAnimation = () => {
|
|
196
|
+
const css = document.createElement("style");
|
|
197
|
+
css.appendChild(document.createTextNode(`*{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}`));
|
|
198
|
+
document.head.appendChild(css);
|
|
199
|
+
return () => {
|
|
200
|
+
;
|
|
201
|
+
(() => window.getComputedStyle(document.body))();
|
|
202
|
+
setTimeout(() => {
|
|
203
|
+
document.head.removeChild(css);
|
|
204
|
+
}, 1);
|
|
205
|
+
};
|
|
206
|
+
};
|
|
207
|
+
const getSystemTheme = (e) => {
|
|
208
|
+
if (!e) {
|
|
209
|
+
e = window.matchMedia(MEDIA);
|
|
210
|
+
}
|
|
211
|
+
const isDark = e.matches;
|
|
212
|
+
const systemTheme = isDark ? "dark" : "light";
|
|
213
|
+
return systemTheme;
|
|
214
|
+
};
|
|
215
|
+
export {
|
|
216
|
+
NextThemeProvider,
|
|
217
|
+
useRootTheme,
|
|
218
|
+
useTheme
|
|
219
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./NextTheme";
|
package/package.json
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@tamagui/next-theme",
|
|
3
|
+
"version": "1.0.1-beta.100",
|
|
4
|
+
"sideEffects": false,
|
|
5
|
+
"source": "src/index.ts",
|
|
6
|
+
"types": "./types/index.d.ts",
|
|
7
|
+
"main": "dist/cjs",
|
|
8
|
+
"module": "dist/esm",
|
|
9
|
+
"files": [
|
|
10
|
+
"src",
|
|
11
|
+
"types",
|
|
12
|
+
"dist"
|
|
13
|
+
],
|
|
14
|
+
"scripts": {
|
|
15
|
+
"build": "tamagui-build",
|
|
16
|
+
"watch": "tamagui-build --watch"
|
|
17
|
+
},
|
|
18
|
+
"dependencies": {
|
|
19
|
+
"@tamagui/core": "^1.0.1-beta.100"
|
|
20
|
+
},
|
|
21
|
+
"peerDependencies": {
|
|
22
|
+
"react": "*"
|
|
23
|
+
},
|
|
24
|
+
"devDependencies": {
|
|
25
|
+
"@tamagui/build": "^1.0.1-beta.100",
|
|
26
|
+
"react": "*"
|
|
27
|
+
},
|
|
28
|
+
"publishConfig": {
|
|
29
|
+
"access": "public"
|
|
30
|
+
}
|
|
31
|
+
}
|
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
// https://raw.githubusercontent.com/pacocoursey/next-themes/master/index.tsx
|
|
2
|
+
// forked temporarily due to buggy theme change
|
|
3
|
+
|
|
4
|
+
import NextHead from 'next/head'
|
|
5
|
+
import * as React from 'react'
|
|
6
|
+
import {
|
|
7
|
+
createContext,
|
|
8
|
+
memo,
|
|
9
|
+
useCallback,
|
|
10
|
+
useContext,
|
|
11
|
+
useEffect,
|
|
12
|
+
useLayoutEffect,
|
|
13
|
+
useMemo,
|
|
14
|
+
useRef,
|
|
15
|
+
useState,
|
|
16
|
+
} from 'react'
|
|
17
|
+
|
|
18
|
+
const useIsomorphicLayoutEffect = typeof window !== 'undefined' ? useLayoutEffect : useEffect
|
|
19
|
+
|
|
20
|
+
export interface UseThemeProps {
|
|
21
|
+
/** List of all available theme names */
|
|
22
|
+
themes: string[]
|
|
23
|
+
/** Forced theme name for the current page */
|
|
24
|
+
forcedTheme?: string
|
|
25
|
+
/** Update the theme */
|
|
26
|
+
setTheme: (theme: string) => void
|
|
27
|
+
toggleTheme: () => void
|
|
28
|
+
/** Active theme name */
|
|
29
|
+
theme?: string
|
|
30
|
+
/** 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` */
|
|
31
|
+
resolvedTheme?: string
|
|
32
|
+
/** If enableSystem is true, returns the System theme preference ("dark" or "light"), regardless what the active theme is */
|
|
33
|
+
systemTheme?: 'dark' | 'light'
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface ThemeProviderProps {
|
|
37
|
+
children?: any
|
|
38
|
+
/** List of all available theme names */
|
|
39
|
+
themes?: string[]
|
|
40
|
+
/** Forced theme name for the current page */
|
|
41
|
+
forcedTheme?: string
|
|
42
|
+
/** Whether to switch between dark and light themes based on prefers-color-scheme */
|
|
43
|
+
enableSystem?: boolean
|
|
44
|
+
systemTheme?: string
|
|
45
|
+
/** Disable all CSS transitions when switching themes */
|
|
46
|
+
disableTransitionOnChange?: boolean
|
|
47
|
+
/** Whether to indicate to browsers which color scheme is used (dark or light) for built-in UI like inputs and buttons */
|
|
48
|
+
enableColorScheme?: boolean
|
|
49
|
+
/** Key used to store theme setting in localStorage */
|
|
50
|
+
storageKey?: string
|
|
51
|
+
/** Default theme name (for v0.0.12 and lower the default was light). If `enableSystem` is false, the default theme is light */
|
|
52
|
+
defaultTheme?: string
|
|
53
|
+
/** HTML attribute modified based on the active theme. Accepts `class` and `data-*` (meaning any data attribute, `data-mode`, `data-color`, etc.) */
|
|
54
|
+
attribute?: string | 'class'
|
|
55
|
+
/** Mapping of theme name to HTML attribute value. Object where key is the theme name and value is the attribute value */
|
|
56
|
+
value?: ValueObject
|
|
57
|
+
onChangeTheme?: (name: string) => void
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const ThemeContext = createContext<UseThemeProps>({
|
|
61
|
+
toggleTheme: () => {},
|
|
62
|
+
setTheme: (_) => {},
|
|
63
|
+
themes: [],
|
|
64
|
+
})
|
|
65
|
+
export const useTheme = () => useContext(ThemeContext)
|
|
66
|
+
|
|
67
|
+
const colorSchemes = ['light', 'dark']
|
|
68
|
+
const MEDIA = '(prefers-color-scheme: dark)'
|
|
69
|
+
|
|
70
|
+
interface ValueObject {
|
|
71
|
+
[themeName: string]: string
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export const useRootTheme = () => {
|
|
75
|
+
const isClient = typeof document !== 'undefined'
|
|
76
|
+
// @ts-ignore
|
|
77
|
+
const classes = isClient ? [...document.documentElement.classList] : []
|
|
78
|
+
const isDark = classes.includes('t_dark')
|
|
79
|
+
return useState(isDark ? 'dark' : 'light')
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// backwards compat
|
|
83
|
+
const startTransition = React.startTransition || ((cb) => cb())
|
|
84
|
+
|
|
85
|
+
export const NextThemeProvider: React.FC<ThemeProviderProps> = ({
|
|
86
|
+
forcedTheme,
|
|
87
|
+
disableTransitionOnChange = true,
|
|
88
|
+
enableSystem = true,
|
|
89
|
+
enableColorScheme = true,
|
|
90
|
+
storageKey = 'theme',
|
|
91
|
+
themes = ['light', 'dark'],
|
|
92
|
+
defaultTheme = enableSystem ? 'system' : 'light',
|
|
93
|
+
attribute = 'class',
|
|
94
|
+
onChangeTheme,
|
|
95
|
+
value = {
|
|
96
|
+
dark: 't_dark',
|
|
97
|
+
light: 't_light',
|
|
98
|
+
},
|
|
99
|
+
children,
|
|
100
|
+
}) => {
|
|
101
|
+
const [theme, setThemeState] = useState(() => getTheme(storageKey, defaultTheme))
|
|
102
|
+
const [resolvedTheme, setResolvedTheme] = useState(() => getTheme(storageKey))
|
|
103
|
+
// const resolvedTheme = React.useDeferredValue(resolvedThemeFast)
|
|
104
|
+
const attrs = !value ? themes : Object.values(value)
|
|
105
|
+
|
|
106
|
+
const handleMediaQuery = useCallback(
|
|
107
|
+
(e?) => {
|
|
108
|
+
const systemTheme = getSystemTheme(e)
|
|
109
|
+
startTransition(() => {
|
|
110
|
+
setResolvedTheme(systemTheme)
|
|
111
|
+
})
|
|
112
|
+
if (theme === 'system' && !forcedTheme) handleChangeTheme(systemTheme, false)
|
|
113
|
+
},
|
|
114
|
+
[theme, forcedTheme]
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
// Ref hack to avoid adding handleMediaQuery as a dep
|
|
118
|
+
const mediaListener = useRef(handleMediaQuery)
|
|
119
|
+
mediaListener.current = handleMediaQuery
|
|
120
|
+
|
|
121
|
+
const handleChangeTheme = useCallback((theme, updateStorage = true, updateDOM = true) => {
|
|
122
|
+
let name = value?.[theme] || theme
|
|
123
|
+
|
|
124
|
+
const enable = disableTransitionOnChange && updateDOM ? disableAnimation() : null
|
|
125
|
+
|
|
126
|
+
if (updateStorage) {
|
|
127
|
+
try {
|
|
128
|
+
localStorage.setItem(storageKey, theme)
|
|
129
|
+
} catch (e) {
|
|
130
|
+
// Unsupported
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
if (theme === 'system' && enableSystem) {
|
|
135
|
+
const resolved = getSystemTheme()
|
|
136
|
+
name = value?.[resolved] || resolved
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
onChangeTheme?.(name.replace('t_', ''))
|
|
140
|
+
|
|
141
|
+
if (updateDOM) {
|
|
142
|
+
const d = document.documentElement
|
|
143
|
+
|
|
144
|
+
if (attribute === 'class') {
|
|
145
|
+
d.classList.remove(...attrs)
|
|
146
|
+
d.classList.add(name)
|
|
147
|
+
} else {
|
|
148
|
+
d.setAttribute(attribute, name)
|
|
149
|
+
}
|
|
150
|
+
enable?.()
|
|
151
|
+
}
|
|
152
|
+
}, [])
|
|
153
|
+
|
|
154
|
+
useIsomorphicLayoutEffect(() => {
|
|
155
|
+
const handler = (...args: any) => mediaListener.current(...args)
|
|
156
|
+
// Always listen to System preference
|
|
157
|
+
const media = window.matchMedia(MEDIA)
|
|
158
|
+
// Intentionally use deprecated listener methods to support iOS & old browsers
|
|
159
|
+
media.addListener(handler)
|
|
160
|
+
handler(media)
|
|
161
|
+
return () => {
|
|
162
|
+
media.removeListener(handler)
|
|
163
|
+
}
|
|
164
|
+
}, [])
|
|
165
|
+
|
|
166
|
+
const setTheme = useCallback(
|
|
167
|
+
(newTheme) => {
|
|
168
|
+
if (forcedTheme) {
|
|
169
|
+
handleChangeTheme(newTheme, true, false)
|
|
170
|
+
} else {
|
|
171
|
+
handleChangeTheme(newTheme)
|
|
172
|
+
}
|
|
173
|
+
setThemeState(newTheme)
|
|
174
|
+
},
|
|
175
|
+
[forcedTheme]
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
// localStorage event handling
|
|
179
|
+
useEffect(() => {
|
|
180
|
+
const handleStorage = (e: StorageEvent) => {
|
|
181
|
+
if (e.key !== storageKey) {
|
|
182
|
+
return
|
|
183
|
+
}
|
|
184
|
+
// If default theme set, use it if localstorage === null (happens on local storage manual deletion)
|
|
185
|
+
const theme = e.newValue || defaultTheme
|
|
186
|
+
setTheme(theme)
|
|
187
|
+
}
|
|
188
|
+
window.addEventListener('storage', handleStorage)
|
|
189
|
+
return () => {
|
|
190
|
+
window.removeEventListener('storage', handleStorage)
|
|
191
|
+
}
|
|
192
|
+
}, [])
|
|
193
|
+
|
|
194
|
+
// color-scheme handling
|
|
195
|
+
useIsomorphicLayoutEffect(() => {
|
|
196
|
+
if (!enableColorScheme) return
|
|
197
|
+
|
|
198
|
+
const colorScheme =
|
|
199
|
+
// If theme is forced to light or dark, use that
|
|
200
|
+
forcedTheme && colorSchemes.includes(forcedTheme)
|
|
201
|
+
? forcedTheme
|
|
202
|
+
: // If regular theme is light or dark
|
|
203
|
+
theme && colorSchemes.includes(theme)
|
|
204
|
+
? theme
|
|
205
|
+
: // If theme is system, use the resolved version
|
|
206
|
+
theme === 'system'
|
|
207
|
+
? resolvedTheme || null
|
|
208
|
+
: null
|
|
209
|
+
|
|
210
|
+
// color-scheme tells browser how to render built-in elements like forms, scrollbars, etc.
|
|
211
|
+
// if color-scheme is null, this will remove the property
|
|
212
|
+
document.documentElement.style.setProperty('color-scheme', colorScheme)
|
|
213
|
+
}, [enableColorScheme, theme, resolvedTheme, forcedTheme])
|
|
214
|
+
|
|
215
|
+
const contextValue = useMemo(() => {
|
|
216
|
+
return {
|
|
217
|
+
theme,
|
|
218
|
+
setTheme,
|
|
219
|
+
toggleTheme() {
|
|
220
|
+
const order =
|
|
221
|
+
resolvedTheme === 'dark' ? ['system', 'light', 'dark'] : ['system', 'dark', 'light']
|
|
222
|
+
const next = order[(order.indexOf(theme) + 1) % order.length]
|
|
223
|
+
setTheme(next)
|
|
224
|
+
},
|
|
225
|
+
forcedTheme,
|
|
226
|
+
resolvedTheme: theme === 'system' ? resolvedTheme : theme,
|
|
227
|
+
themes: enableSystem ? [...themes, 'system'] : themes,
|
|
228
|
+
systemTheme: (enableSystem ? resolvedTheme : undefined) as 'light' | 'dark' | undefined,
|
|
229
|
+
} as const
|
|
230
|
+
}, [theme, forcedTheme, resolvedTheme, enableSystem])
|
|
231
|
+
|
|
232
|
+
return (
|
|
233
|
+
<ThemeContext.Provider value={contextValue}>
|
|
234
|
+
<ThemeScript
|
|
235
|
+
{...{
|
|
236
|
+
forcedTheme,
|
|
237
|
+
storageKey,
|
|
238
|
+
systemTheme: resolvedTheme,
|
|
239
|
+
attribute,
|
|
240
|
+
value,
|
|
241
|
+
enableSystem,
|
|
242
|
+
defaultTheme,
|
|
243
|
+
attrs,
|
|
244
|
+
}}
|
|
245
|
+
/>
|
|
246
|
+
{children}
|
|
247
|
+
</ThemeContext.Provider>
|
|
248
|
+
)
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
const ThemeScript = memo(
|
|
252
|
+
({
|
|
253
|
+
forcedTheme,
|
|
254
|
+
storageKey,
|
|
255
|
+
attribute,
|
|
256
|
+
enableSystem,
|
|
257
|
+
defaultTheme,
|
|
258
|
+
value,
|
|
259
|
+
attrs,
|
|
260
|
+
}: {
|
|
261
|
+
forcedTheme?: string
|
|
262
|
+
storageKey: string
|
|
263
|
+
attribute?: string
|
|
264
|
+
enableSystem?: boolean
|
|
265
|
+
defaultTheme: string
|
|
266
|
+
value?: ValueObject
|
|
267
|
+
attrs: any
|
|
268
|
+
}) => {
|
|
269
|
+
// Code-golfing the amount of characters in the script
|
|
270
|
+
const optimization = (() => {
|
|
271
|
+
if (attribute === 'class') {
|
|
272
|
+
const removeClasses = attrs.map((t: string) => `d.remove('${t}')`).join(';')
|
|
273
|
+
return `var d=document.documentElement.classList;${removeClasses};`
|
|
274
|
+
} else {
|
|
275
|
+
return `var d=document.documentElement;`
|
|
276
|
+
}
|
|
277
|
+
})()
|
|
278
|
+
|
|
279
|
+
const updateDOM = (name: string, literal?: boolean) => {
|
|
280
|
+
name = value?.[name] || name
|
|
281
|
+
const val = literal ? name : `'${name}'`
|
|
282
|
+
|
|
283
|
+
if (attribute === 'class') {
|
|
284
|
+
return `d.add(${val})`
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
return `d.setAttribute('${attribute}', ${val})`
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
const defaultSystem = defaultTheme === 'system'
|
|
291
|
+
|
|
292
|
+
return (
|
|
293
|
+
<NextHead>
|
|
294
|
+
{forcedTheme ? (
|
|
295
|
+
<script
|
|
296
|
+
key="next-themes-script"
|
|
297
|
+
dangerouslySetInnerHTML={{
|
|
298
|
+
// These are minified via Terser and then updated by hand, don't recommend
|
|
299
|
+
// prettier-ignore
|
|
300
|
+
__html: `!function(){${optimization}${updateDOM(forcedTheme)}}()`,
|
|
301
|
+
}}
|
|
302
|
+
/>
|
|
303
|
+
) : enableSystem ? (
|
|
304
|
+
<script
|
|
305
|
+
key="next-themes-script"
|
|
306
|
+
dangerouslySetInnerHTML={{
|
|
307
|
+
// prettier-ignore
|
|
308
|
+
__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){}}()`,
|
|
309
|
+
}}
|
|
310
|
+
/>
|
|
311
|
+
) : (
|
|
312
|
+
<script
|
|
313
|
+
key="next-themes-script"
|
|
314
|
+
dangerouslySetInnerHTML={{
|
|
315
|
+
// prettier-ignore
|
|
316
|
+
__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){}}();`,
|
|
317
|
+
}}
|
|
318
|
+
/>
|
|
319
|
+
)}
|
|
320
|
+
</NextHead>
|
|
321
|
+
)
|
|
322
|
+
},
|
|
323
|
+
(prevProps, nextProps) => {
|
|
324
|
+
// Only re-render when forcedTheme changes
|
|
325
|
+
// the rest of the props should be completely stable
|
|
326
|
+
if (prevProps.forcedTheme !== nextProps.forcedTheme) return false
|
|
327
|
+
return true
|
|
328
|
+
}
|
|
329
|
+
)
|
|
330
|
+
|
|
331
|
+
// Helpers
|
|
332
|
+
const getTheme = (key: string, fallback?: string) => {
|
|
333
|
+
if (typeof window === 'undefined') return undefined
|
|
334
|
+
let theme
|
|
335
|
+
try {
|
|
336
|
+
theme = localStorage.getItem(key) || undefined
|
|
337
|
+
} catch (e) {
|
|
338
|
+
// Unsupported
|
|
339
|
+
}
|
|
340
|
+
return theme || fallback
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
const disableAnimation = () => {
|
|
344
|
+
const css = document.createElement('style')
|
|
345
|
+
css.appendChild(
|
|
346
|
+
document.createTextNode(
|
|
347
|
+
`*{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}`
|
|
348
|
+
)
|
|
349
|
+
)
|
|
350
|
+
document.head.appendChild(css)
|
|
351
|
+
|
|
352
|
+
return () => {
|
|
353
|
+
// Force restyle
|
|
354
|
+
;(() => window.getComputedStyle(document.body))()
|
|
355
|
+
|
|
356
|
+
// Wait for next tick before removing
|
|
357
|
+
setTimeout(() => {
|
|
358
|
+
document.head.removeChild(css)
|
|
359
|
+
}, 1)
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
const getSystemTheme = (e?: MediaQueryList) => {
|
|
364
|
+
if (!e) {
|
|
365
|
+
e = window.matchMedia(MEDIA)
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
const isDark = e.matches
|
|
369
|
+
const systemTheme = isDark ? 'dark' : 'light'
|
|
370
|
+
return systemTheme
|
|
371
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './NextTheme'
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import * as React from 'react';
|
|
2
|
+
export interface UseThemeProps {
|
|
3
|
+
themes: string[];
|
|
4
|
+
forcedTheme?: string;
|
|
5
|
+
setTheme: (theme: string) => void;
|
|
6
|
+
toggleTheme: () => void;
|
|
7
|
+
theme?: string;
|
|
8
|
+
resolvedTheme?: string;
|
|
9
|
+
systemTheme?: 'dark' | 'light';
|
|
10
|
+
}
|
|
11
|
+
export interface ThemeProviderProps {
|
|
12
|
+
children?: any;
|
|
13
|
+
themes?: string[];
|
|
14
|
+
forcedTheme?: string;
|
|
15
|
+
enableSystem?: boolean;
|
|
16
|
+
systemTheme?: string;
|
|
17
|
+
disableTransitionOnChange?: boolean;
|
|
18
|
+
enableColorScheme?: boolean;
|
|
19
|
+
storageKey?: string;
|
|
20
|
+
defaultTheme?: string;
|
|
21
|
+
attribute?: string | 'class';
|
|
22
|
+
value?: ValueObject;
|
|
23
|
+
onChangeTheme?: (name: string) => void;
|
|
24
|
+
}
|
|
25
|
+
export declare const useTheme: () => UseThemeProps;
|
|
26
|
+
interface ValueObject {
|
|
27
|
+
[themeName: string]: string;
|
|
28
|
+
}
|
|
29
|
+
export declare const useRootTheme: () => [string, React.Dispatch<React.SetStateAction<string>>];
|
|
30
|
+
export declare const NextThemeProvider: React.FC<ThemeProviderProps>;
|
|
31
|
+
export {};
|
|
32
|
+
//# sourceMappingURL=NextTheme.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"NextTheme.d.ts","sourceRoot":"","sources":["../src/NextTheme.tsx"],"names":[],"mappings":"AAIA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAe9B,MAAM,WAAW,aAAa;IAE5B,MAAM,EAAE,MAAM,EAAE,CAAA;IAEhB,WAAW,CAAC,EAAE,MAAM,CAAA;IAEp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