cookie-prefs 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,95 @@
1
+ 'use client';
2
+ import { createContext, useContext, useSyncExternalStore, useEffect, useMemo, useState, useLayoutEffect } from 'react';
3
+ import { jsxs, jsx } from 'react/jsx-runtime';
4
+
5
+ // src/react/index.tsx
6
+
7
+ // src/react/reapply.ts
8
+ var reapply = (script) => {
9
+ try {
10
+ const config = JSON.parse(JSON.parse(script.slice(script.indexOf('})("') + 3, -1)));
11
+ const h = document.documentElement;
12
+ const cookies = "; " + document.cookie;
13
+ for (let i = 0, p; p = config[i++]; )
14
+ try {
15
+ const m = p[2];
16
+ let v = cookies.split("; " + p[0] + "=")[1];
17
+ if (v != null)
18
+ try {
19
+ v = decodeURIComponent(v.split(";")[0].replace(/^"(.*)"$/, "$1"));
20
+ if (m === 1) {
21
+ const n = parseFloat(v);
22
+ v = n === +v && isFinite(n) ? "" + n : null;
23
+ } else if (m) v = Object.prototype.hasOwnProperty.call(m, v) ? m[v] : null;
24
+ } catch {
25
+ v = null;
26
+ }
27
+ v ??= p[3];
28
+ for (let j = 0, t; t = p[1][j++]; )
29
+ if (t == "class") {
30
+ for (const k in m) h.classList.remove(m[k]);
31
+ if (v != null) h.classList.add(v);
32
+ } else if (t[0] == "-") {
33
+ if (v == null) h.style.removeProperty(t);
34
+ else h.style.setProperty(t, v);
35
+ } else if (v == null) h.removeAttribute(t);
36
+ else h.setAttribute(t, v);
37
+ } catch {
38
+ }
39
+ } catch {
40
+ }
41
+ };
42
+ var Snapshot = createContext(void 0);
43
+ var useLayout = typeof document == "undefined" ? useEffect : useLayoutEffect;
44
+ var seen = /* @__PURE__ */ new WeakSet();
45
+ function usePref(pref) {
46
+ const snapshot = useContext(Snapshot);
47
+ const value = useSyncExternalStore(
48
+ pref.subscribe,
49
+ pref.get,
50
+ () => snapshot ? pref.read(snapshot) : pref.defaultValue
51
+ );
52
+ useEffect(() => {
53
+ if (seen.has(pref)) return;
54
+ seen.add(pref);
55
+ try {
56
+ const current = pref.get();
57
+ if (current !== void 0 && pref.toCookie(current).maxAge > 604800 && ("; " + document.cookie).indexOf("; " + pref.name + "=") >= 0 && pref.read({ [pref.name]: pref.toCookie(current).value }) === current)
58
+ pref.set(() => current);
59
+ } catch {
60
+ }
61
+ }, [pref]);
62
+ return [value, pref.set];
63
+ }
64
+ function PrefsProvider({ children, snapshot, script, nonce }) {
65
+ const outer = useContext(Snapshot);
66
+ const merged = useMemo(
67
+ () => outer && snapshot ? { ...outer, ...snapshot } : snapshot ?? outer,
68
+ [outer, snapshot]
69
+ );
70
+ useLayout(() => {
71
+ if (!script) return;
72
+ const onVisible = () => {
73
+ if (document.visibilityState == "visible") reapply(script);
74
+ };
75
+ reapply(script);
76
+ document.addEventListener("visibilitychange", onVisible);
77
+ return () => document.removeEventListener("visibilitychange", onVisible);
78
+ }, [script]);
79
+ const [first] = useState(script && { __html: script });
80
+ const server = typeof document == "undefined";
81
+ return /* @__PURE__ */ jsxs(Snapshot.Provider, { value: merged, children: [
82
+ first ? /* @__PURE__ */ jsx(
83
+ "script",
84
+ {
85
+ type: server ? "text/javascript" : "text/plain",
86
+ nonce: server ? nonce : void 0,
87
+ suppressHydrationWarning: true,
88
+ dangerouslySetInnerHTML: first
89
+ }
90
+ ) : null,
91
+ children
92
+ ] });
93
+ }
94
+
95
+ export { PrefsProvider, usePref };
@@ -0,0 +1,169 @@
1
+ 'use client';
2
+ 'use strict';
3
+
4
+ var cookiePrefs = require('cookie-prefs');
5
+ var react = require('react');
6
+ var jsxRuntime = require('react/jsx-runtime');
7
+
8
+ // src/theme/index.tsx
9
+
10
+ // src/theme/script.ts
11
+ var MEDIA = "(prefers-color-scheme: dark)";
12
+ var SOURCE = `(function(k,l,a,m,d,f,s,c){var D=document,h=D.documentElement,o={}.hasOwnProperty,x,i,j;if(!f){x=('; '+D.cookie).split('; '+k+'=')[1];try{x=x!=null?decodeURIComponent(x.split(';')[0].replace(/^"(.*)"$/,'$1')):localStorage.getItem(l)}catch(e){x=null}f=x!=null&&o.call(m,x)?x:d}if(f=='system'&&s)f=matchMedia('` + MEDIA + "').matches?'dark':'light';x=o.call(m,f)?m[f]:f;for(i=0;i<a.length;i++)try{if(a[i]=='class'){for(j in m)h.classList.remove(m[j]);h.classList.add(x)}else h.setAttribute(a[i],x)}catch(e){}if(c!=null)h.style.colorScheme=/^(light|dark)$/.test(f)?f:c})";
13
+ var themeScript = (config) => SOURCE + ".apply(0," + JSON.stringify(config).replace(
14
+ /[<>&\u2028\u2029]/g,
15
+ (c) => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0")
16
+ ) + ")";
17
+ var has = (map, key) => Object.prototype.hasOwnProperty.call(map, key);
18
+ var media = () => globalThis.matchMedia?.(MEDIA);
19
+ var system = () => media()?.matches ? "dark" : "light";
20
+ var LIGHT_DARK = /^(light|dark)$/;
21
+ var paint = ([, , attributes, dom, , forced, enableSystem, colorScheme], theme) => {
22
+ const h = document.documentElement;
23
+ let t = forced || theme;
24
+ if (t == "system" && enableSystem) t = system();
25
+ const name = has(dom, t) ? dom[t] : t;
26
+ for (const attribute of attributes)
27
+ try {
28
+ if (attribute == "class") {
29
+ for (const k in dom) h.classList.remove(dom[k]);
30
+ h.classList.add(name);
31
+ } else h.setAttribute(attribute, name);
32
+ } catch {
33
+ }
34
+ if (colorScheme != null) h.style.colorScheme = LIGHT_DARK.test(t) ? t : colorScheme;
35
+ };
36
+ var pauseTransitions = (nonce) => {
37
+ const css = document.createElement("style");
38
+ if (nonce) css.setAttribute("nonce", nonce);
39
+ css.appendChild(document.createTextNode("*,*::before,*::after{transition:none!important}"));
40
+ document.head.appendChild(css);
41
+ return () => {
42
+ restyle();
43
+ setTimeout(() => css.remove(), 1);
44
+ };
45
+ };
46
+ var restyle = () => getComputedStyle(document.documentElement).opacity;
47
+ var Context = react.createContext(void 0);
48
+ var outside = { setTheme: () => {
49
+ }, themes: [] };
50
+ var DEFAULT_THEMES = ["light", "dark"];
51
+ var useLayout = typeof document == "undefined" ? react.useEffect : react.useLayoutEffect;
52
+ var subscribeSystem = (onChange) => {
53
+ const query = media();
54
+ if (query?.addEventListener) query.addEventListener("change", onChange);
55
+ else query?.addListener(onChange);
56
+ return () => {
57
+ if (query?.removeEventListener) query.removeEventListener("change", onChange);
58
+ else query?.removeListener(onChange);
59
+ };
60
+ };
61
+ var none = () => void 0;
62
+ var exists = (name) => ("; " + document.cookie).indexOf("; " + name + "=") >= 0;
63
+ var seen = /* @__PURE__ */ new Set();
64
+ function ThemeProvider(props) {
65
+ return react.useContext(Context) ? /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: props.children }) : /* @__PURE__ */ jsxRuntime.jsx(Theme, { ...props });
66
+ }
67
+ function Theme({
68
+ children,
69
+ themes = DEFAULT_THEMES,
70
+ forcedTheme,
71
+ enableSystem = true,
72
+ disableTransitionOnChange = false,
73
+ enableColorScheme = true,
74
+ storageKey = "theme",
75
+ defaultTheme = enableSystem ? "system" : "light",
76
+ attribute = "data-theme",
77
+ value,
78
+ nonce,
79
+ scriptProps,
80
+ cookie
81
+ }) {
82
+ const listed = enableSystem ? [...themes, "system"] : themes;
83
+ const dom = Object.fromEntries(listed.map((t) => [t, t]).concat(Object.entries(value || {})));
84
+ const fresh = [
85
+ encodeURIComponent(storageKey),
86
+ // the core's cookie name for `name: storageKey`
87
+ storageKey,
88
+ [].concat(attribute),
89
+ dom,
90
+ defaultTheme,
91
+ forcedTheme || null,
92
+ enableSystem ? 1 : 0,
93
+ // `color-scheme` for other themes: the default when it is light or dark, as in next-themes
94
+ enableColorScheme ? LIGHT_DARK.test(defaultTheme) ? defaultTheme : "" : null
95
+ ];
96
+ const script = themeScript(fresh);
97
+ const [first] = react.useState({ __html: script });
98
+ const [handle, config, themeList, setTheme] = react.useMemo(() => {
99
+ const handle2 = cookiePrefs.definePrefs({
100
+ theme: cookiePrefs.pref.enum(Object.keys(dom)).default(defaultTheme).options({ ...cookie, name: storageKey })
101
+ }).theme;
102
+ const setTheme2 = (next) => {
103
+ const name = typeof next == "function" ? next(handle2.get()) : next;
104
+ if (has(dom, name)) handle2.set(name);
105
+ };
106
+ return [handle2, fresh, listed, setTheme2];
107
+ }, [script, JSON.stringify(cookie)]);
108
+ const theme = react.useSyncExternalStore(handle.subscribe, handle.get, none);
109
+ const systemTheme = react.useSyncExternalStore(subscribeSystem, system, none);
110
+ const resolvedTheme = theme == "system" && enableSystem ? systemTheme : theme;
111
+ const [, refresh] = react.useReducer((n) => n + 1, 0);
112
+ useLayout(() => {
113
+ const once = !seen.has(handle.name);
114
+ seen.add(handle.name);
115
+ try {
116
+ if (!exists(handle.name)) {
117
+ const stored = localStorage.getItem(config[1]);
118
+ if (stored != null) {
119
+ const valid = has(config[3], stored);
120
+ if (valid) handle.set(stored);
121
+ if (!valid || exists(handle.name)) localStorage.removeItem(config[1]);
122
+ }
123
+ } else if (once && handle.toCookie(handle.get()).maxAge > 604800) handle.set(handle.get());
124
+ } catch {
125
+ }
126
+ const resume = disableTransitionOnChange && pauseTransitions(nonce);
127
+ paint(config, handle.get());
128
+ if (resume) resume();
129
+ const onVisible = () => {
130
+ if (document.visibilityState == "visible") {
131
+ paint(config, handle.get());
132
+ refresh();
133
+ }
134
+ };
135
+ document.addEventListener("visibilitychange", onVisible);
136
+ return () => document.removeEventListener("visibilitychange", onVisible);
137
+ }, [config, handle, theme, systemTheme, disableTransitionOnChange, nonce]);
138
+ const context = react.useMemo(
139
+ () => ({
140
+ theme,
141
+ setTheme,
142
+ forcedTheme,
143
+ resolvedTheme,
144
+ themes: themeList,
145
+ systemTheme: enableSystem ? systemTheme : void 0
146
+ }),
147
+ [theme, setTheme, forcedTheme, resolvedTheme, themeList, enableSystem, systemTheme]
148
+ );
149
+ const server = typeof document == "undefined";
150
+ return /* @__PURE__ */ jsxRuntime.jsxs(Context.Provider, { value: context, children: [
151
+ /* @__PURE__ */ jsxRuntime.jsx(
152
+ "script",
153
+ {
154
+ ...scriptProps,
155
+ type: server ? "text/javascript" : "text/plain",
156
+ nonce: server ? nonce : void 0,
157
+ suppressHydrationWarning: true,
158
+ dangerouslySetInnerHTML: first
159
+ }
160
+ ),
161
+ children
162
+ ] });
163
+ }
164
+ function useTheme() {
165
+ return react.useContext(Context) ?? outside;
166
+ }
167
+
168
+ exports.ThemeProvider = ThemeProvider;
169
+ exports.useTheme = useTheme;
@@ -0,0 +1,97 @@
1
+ import { CookieOptions } from 'cookie-prefs';
2
+ import { DetailedHTMLProps, ScriptHTMLAttributes, ReactNode, ReactElement, Dispatch, SetStateAction } from 'react';
3
+
4
+ /** `class` or any `data-*` attribute on `<html>`. */
5
+ type Attribute = `data-${string}` | 'class';
6
+ /** Props for the inline script element, as in next-themes. */
7
+ interface ScriptProps extends DetailedHTMLProps<ScriptHTMLAttributes<HTMLScriptElement>, HTMLScriptElement> {
8
+ [dataAttribute: `data-${string}`]: unknown;
9
+ }
10
+ /** Same props and defaults as next-themes `ThemeProvider`, plus `cookie`. */
11
+ interface ThemeProviderProps {
12
+ children?: ReactNode;
13
+ /** All theme names. `'system'` is added when `enableSystem` is on. @default ['light', 'dark'] */
14
+ themes?: string[] | undefined;
15
+ /** Theme used on this page regardless of the stored choice; the choice is kept. */
16
+ forcedTheme?: string | undefined;
17
+ /** Resolve `'system'` from `prefers-color-scheme`. @default true */
18
+ enableSystem?: boolean | undefined;
19
+ /** Disable CSS transitions while the theme switches. @default false */
20
+ disableTransitionOnChange?: boolean | undefined;
21
+ /** Set `color-scheme` on `<html>` for built-in UI (inputs, scrollbars). @default true */
22
+ enableColorScheme?: boolean | undefined;
23
+ /**
24
+ * Cookie name that stores the choice. A value left in `localStorage` under the same
25
+ * key by next-themes is moved to the cookie once and removed from `localStorage`, so
26
+ * rolling back to next-themes starts from its default. @default 'theme'
27
+ */
28
+ storageKey?: string | undefined;
29
+ /** Theme when nothing is stored. @default enableSystem ? 'system' : 'light' */
30
+ defaultTheme?: string | undefined;
31
+ /** Where the theme is written on `<html>`; accepts a list. @default 'data-theme' */
32
+ attribute?: Attribute | Attribute[] | undefined;
33
+ /** Theme name to the value written to the DOM. */
34
+ value?: Record<string, string> | undefined;
35
+ /** CSP nonce for the inline script and the transition-disabling style. */
36
+ nonce?: string | undefined;
37
+ /** Extra props for the inline script element. */
38
+ scriptProps?: ScriptProps | undefined;
39
+ /**
40
+ * Attributes of the theme cookie, as for any pref (not in next-themes). Defaults:
41
+ * `Path=/`, `SameSite=Lax`, 400 days, current host only, `Secure` on `https:`.
42
+ * @example
43
+ * // one theme for app.example.com and www.example.com
44
+ * <ThemeProvider cookie={{ domain: 'example.com' }}>
45
+ * // inside a cross-site iframe
46
+ * <ThemeProvider cookie={{ sameSite: 'none', secure: true, partitioned: true }}>
47
+ */
48
+ cookie?: CookieOptions | undefined;
49
+ }
50
+ /**
51
+ * Return type of `useTheme()`, same fields as next-themes. `T` narrows theme names;
52
+ * the default `string` matches next-themes exactly.
53
+ */
54
+ interface UseThemeProps<T extends string = string> {
55
+ /** All theme names, including `'system'` when `enableSystem` is on. */
56
+ themes: (T | 'system')[];
57
+ /** Forced theme of the current page, if any. */
58
+ forcedTheme?: T | undefined;
59
+ /** Store a theme; accepts a value or an updater. */
60
+ setTheme: Dispatch<SetStateAction<T | 'system'>>;
61
+ /** Stored theme, possibly `'system'`. `undefined` during SSR and hydration. */
62
+ theme?: T | 'system' | undefined;
63
+ /** Theme actually shown (`'system'` resolved). `undefined` during SSR and hydration. */
64
+ resolvedTheme?: T | undefined;
65
+ /** OS preference when `enableSystem` is on. `undefined` during SSR and hydration. */
66
+ systemTheme?: 'light' | 'dark' | undefined;
67
+ }
68
+ /**
69
+ * Drop-in replacement for next-themes `ThemeProvider`, stored in a cookie so the
70
+ * server can read it. Migration is an import swap. Its inline script never triggers
71
+ * the React 19 script warning and needs no `cookies()` read, so pages stay static.
72
+ * Add `suppressHydrationWarning` to `<html>`.
73
+ *
74
+ * Safari caps cookies written by scripts at 7 days, so once per page load the
75
+ * provider re-writes an existing theme cookie: the choice lasts 7 days after the
76
+ * last visit there, not after the last change. Only when `cookie.maxAge` is longer
77
+ * than 7 days, so a shorter lifetime still ends on time. A cookie set by the server
78
+ * (`Set-Cookie`, e.g. middleware) is not capped until the provider re-writes it.
79
+ * @example
80
+ * <html lang="en" suppressHydrationWarning>
81
+ * <body>
82
+ * <ThemeProvider attribute="class" defaultTheme="system">{children}</ThemeProvider>
83
+ * </body>
84
+ * </html>
85
+ */
86
+ declare function ThemeProvider(props: ThemeProviderProps): ReactElement;
87
+ /**
88
+ * Current theme and setter, same shape as next-themes `useTheme()`. Works without a
89
+ * provider (returns `themes: []` and a no-op setter), like next-themes.
90
+ * @example
91
+ * const { resolvedTheme, setTheme } = useTheme()
92
+ * <button onClick={() => setTheme(resolvedTheme === 'dark' ? 'light' : 'dark')}>Toggle</button>
93
+ */
94
+ declare function useTheme<T extends string = string>(): UseThemeProps<T>;
95
+
96
+ export { ThemeProvider, useTheme };
97
+ export type { Attribute, ScriptProps, ThemeProviderProps, UseThemeProps };
@@ -0,0 +1,97 @@
1
+ import { CookieOptions } from 'cookie-prefs';
2
+ import { DetailedHTMLProps, ScriptHTMLAttributes, ReactNode, ReactElement, Dispatch, SetStateAction } from 'react';
3
+
4
+ /** `class` or any `data-*` attribute on `<html>`. */
5
+ type Attribute = `data-${string}` | 'class';
6
+ /** Props for the inline script element, as in next-themes. */
7
+ interface ScriptProps extends DetailedHTMLProps<ScriptHTMLAttributes<HTMLScriptElement>, HTMLScriptElement> {
8
+ [dataAttribute: `data-${string}`]: unknown;
9
+ }
10
+ /** Same props and defaults as next-themes `ThemeProvider`, plus `cookie`. */
11
+ interface ThemeProviderProps {
12
+ children?: ReactNode;
13
+ /** All theme names. `'system'` is added when `enableSystem` is on. @default ['light', 'dark'] */
14
+ themes?: string[] | undefined;
15
+ /** Theme used on this page regardless of the stored choice; the choice is kept. */
16
+ forcedTheme?: string | undefined;
17
+ /** Resolve `'system'` from `prefers-color-scheme`. @default true */
18
+ enableSystem?: boolean | undefined;
19
+ /** Disable CSS transitions while the theme switches. @default false */
20
+ disableTransitionOnChange?: boolean | undefined;
21
+ /** Set `color-scheme` on `<html>` for built-in UI (inputs, scrollbars). @default true */
22
+ enableColorScheme?: boolean | undefined;
23
+ /**
24
+ * Cookie name that stores the choice. A value left in `localStorage` under the same
25
+ * key by next-themes is moved to the cookie once and removed from `localStorage`, so
26
+ * rolling back to next-themes starts from its default. @default 'theme'
27
+ */
28
+ storageKey?: string | undefined;
29
+ /** Theme when nothing is stored. @default enableSystem ? 'system' : 'light' */
30
+ defaultTheme?: string | undefined;
31
+ /** Where the theme is written on `<html>`; accepts a list. @default 'data-theme' */
32
+ attribute?: Attribute | Attribute[] | undefined;
33
+ /** Theme name to the value written to the DOM. */
34
+ value?: Record<string, string> | undefined;
35
+ /** CSP nonce for the inline script and the transition-disabling style. */
36
+ nonce?: string | undefined;
37
+ /** Extra props for the inline script element. */
38
+ scriptProps?: ScriptProps | undefined;
39
+ /**
40
+ * Attributes of the theme cookie, as for any pref (not in next-themes). Defaults:
41
+ * `Path=/`, `SameSite=Lax`, 400 days, current host only, `Secure` on `https:`.
42
+ * @example
43
+ * // one theme for app.example.com and www.example.com
44
+ * <ThemeProvider cookie={{ domain: 'example.com' }}>
45
+ * // inside a cross-site iframe
46
+ * <ThemeProvider cookie={{ sameSite: 'none', secure: true, partitioned: true }}>
47
+ */
48
+ cookie?: CookieOptions | undefined;
49
+ }
50
+ /**
51
+ * Return type of `useTheme()`, same fields as next-themes. `T` narrows theme names;
52
+ * the default `string` matches next-themes exactly.
53
+ */
54
+ interface UseThemeProps<T extends string = string> {
55
+ /** All theme names, including `'system'` when `enableSystem` is on. */
56
+ themes: (T | 'system')[];
57
+ /** Forced theme of the current page, if any. */
58
+ forcedTheme?: T | undefined;
59
+ /** Store a theme; accepts a value or an updater. */
60
+ setTheme: Dispatch<SetStateAction<T | 'system'>>;
61
+ /** Stored theme, possibly `'system'`. `undefined` during SSR and hydration. */
62
+ theme?: T | 'system' | undefined;
63
+ /** Theme actually shown (`'system'` resolved). `undefined` during SSR and hydration. */
64
+ resolvedTheme?: T | undefined;
65
+ /** OS preference when `enableSystem` is on. `undefined` during SSR and hydration. */
66
+ systemTheme?: 'light' | 'dark' | undefined;
67
+ }
68
+ /**
69
+ * Drop-in replacement for next-themes `ThemeProvider`, stored in a cookie so the
70
+ * server can read it. Migration is an import swap. Its inline script never triggers
71
+ * the React 19 script warning and needs no `cookies()` read, so pages stay static.
72
+ * Add `suppressHydrationWarning` to `<html>`.
73
+ *
74
+ * Safari caps cookies written by scripts at 7 days, so once per page load the
75
+ * provider re-writes an existing theme cookie: the choice lasts 7 days after the
76
+ * last visit there, not after the last change. Only when `cookie.maxAge` is longer
77
+ * than 7 days, so a shorter lifetime still ends on time. A cookie set by the server
78
+ * (`Set-Cookie`, e.g. middleware) is not capped until the provider re-writes it.
79
+ * @example
80
+ * <html lang="en" suppressHydrationWarning>
81
+ * <body>
82
+ * <ThemeProvider attribute="class" defaultTheme="system">{children}</ThemeProvider>
83
+ * </body>
84
+ * </html>
85
+ */
86
+ declare function ThemeProvider(props: ThemeProviderProps): ReactElement;
87
+ /**
88
+ * Current theme and setter, same shape as next-themes `useTheme()`. Works without a
89
+ * provider (returns `themes: []` and a no-op setter), like next-themes.
90
+ * @example
91
+ * const { resolvedTheme, setTheme } = useTheme()
92
+ * <button onClick={() => setTheme(resolvedTheme === 'dark' ? 'light' : 'dark')}>Toggle</button>
93
+ */
94
+ declare function useTheme<T extends string = string>(): UseThemeProps<T>;
95
+
96
+ export { ThemeProvider, useTheme };
97
+ export type { Attribute, ScriptProps, ThemeProviderProps, UseThemeProps };
@@ -0,0 +1,166 @@
1
+ 'use client';
2
+ import { definePrefs, pref } from 'cookie-prefs';
3
+ import { createContext, useContext, useState, useMemo, useSyncExternalStore, useReducer, useEffect, useLayoutEffect } from 'react';
4
+ import { jsx, Fragment, jsxs } from 'react/jsx-runtime';
5
+
6
+ // src/theme/index.tsx
7
+
8
+ // src/theme/script.ts
9
+ var MEDIA = "(prefers-color-scheme: dark)";
10
+ var SOURCE = `(function(k,l,a,m,d,f,s,c){var D=document,h=D.documentElement,o={}.hasOwnProperty,x,i,j;if(!f){x=('; '+D.cookie).split('; '+k+'=')[1];try{x=x!=null?decodeURIComponent(x.split(';')[0].replace(/^"(.*)"$/,'$1')):localStorage.getItem(l)}catch(e){x=null}f=x!=null&&o.call(m,x)?x:d}if(f=='system'&&s)f=matchMedia('` + MEDIA + "').matches?'dark':'light';x=o.call(m,f)?m[f]:f;for(i=0;i<a.length;i++)try{if(a[i]=='class'){for(j in m)h.classList.remove(m[j]);h.classList.add(x)}else h.setAttribute(a[i],x)}catch(e){}if(c!=null)h.style.colorScheme=/^(light|dark)$/.test(f)?f:c})";
11
+ var themeScript = (config) => SOURCE + ".apply(0," + JSON.stringify(config).replace(
12
+ /[<>&\u2028\u2029]/g,
13
+ (c) => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0")
14
+ ) + ")";
15
+ var has = (map, key) => Object.prototype.hasOwnProperty.call(map, key);
16
+ var media = () => globalThis.matchMedia?.(MEDIA);
17
+ var system = () => media()?.matches ? "dark" : "light";
18
+ var LIGHT_DARK = /^(light|dark)$/;
19
+ var paint = ([, , attributes, dom, , forced, enableSystem, colorScheme], theme) => {
20
+ const h = document.documentElement;
21
+ let t = forced || theme;
22
+ if (t == "system" && enableSystem) t = system();
23
+ const name = has(dom, t) ? dom[t] : t;
24
+ for (const attribute of attributes)
25
+ try {
26
+ if (attribute == "class") {
27
+ for (const k in dom) h.classList.remove(dom[k]);
28
+ h.classList.add(name);
29
+ } else h.setAttribute(attribute, name);
30
+ } catch {
31
+ }
32
+ if (colorScheme != null) h.style.colorScheme = LIGHT_DARK.test(t) ? t : colorScheme;
33
+ };
34
+ var pauseTransitions = (nonce) => {
35
+ const css = document.createElement("style");
36
+ if (nonce) css.setAttribute("nonce", nonce);
37
+ css.appendChild(document.createTextNode("*,*::before,*::after{transition:none!important}"));
38
+ document.head.appendChild(css);
39
+ return () => {
40
+ restyle();
41
+ setTimeout(() => css.remove(), 1);
42
+ };
43
+ };
44
+ var restyle = () => getComputedStyle(document.documentElement).opacity;
45
+ var Context = createContext(void 0);
46
+ var outside = { setTheme: () => {
47
+ }, themes: [] };
48
+ var DEFAULT_THEMES = ["light", "dark"];
49
+ var useLayout = typeof document == "undefined" ? useEffect : useLayoutEffect;
50
+ var subscribeSystem = (onChange) => {
51
+ const query = media();
52
+ if (query?.addEventListener) query.addEventListener("change", onChange);
53
+ else query?.addListener(onChange);
54
+ return () => {
55
+ if (query?.removeEventListener) query.removeEventListener("change", onChange);
56
+ else query?.removeListener(onChange);
57
+ };
58
+ };
59
+ var none = () => void 0;
60
+ var exists = (name) => ("; " + document.cookie).indexOf("; " + name + "=") >= 0;
61
+ var seen = /* @__PURE__ */ new Set();
62
+ function ThemeProvider(props) {
63
+ return useContext(Context) ? /* @__PURE__ */ jsx(Fragment, { children: props.children }) : /* @__PURE__ */ jsx(Theme, { ...props });
64
+ }
65
+ function Theme({
66
+ children,
67
+ themes = DEFAULT_THEMES,
68
+ forcedTheme,
69
+ enableSystem = true,
70
+ disableTransitionOnChange = false,
71
+ enableColorScheme = true,
72
+ storageKey = "theme",
73
+ defaultTheme = enableSystem ? "system" : "light",
74
+ attribute = "data-theme",
75
+ value,
76
+ nonce,
77
+ scriptProps,
78
+ cookie
79
+ }) {
80
+ const listed = enableSystem ? [...themes, "system"] : themes;
81
+ const dom = Object.fromEntries(listed.map((t) => [t, t]).concat(Object.entries(value || {})));
82
+ const fresh = [
83
+ encodeURIComponent(storageKey),
84
+ // the core's cookie name for `name: storageKey`
85
+ storageKey,
86
+ [].concat(attribute),
87
+ dom,
88
+ defaultTheme,
89
+ forcedTheme || null,
90
+ enableSystem ? 1 : 0,
91
+ // `color-scheme` for other themes: the default when it is light or dark, as in next-themes
92
+ enableColorScheme ? LIGHT_DARK.test(defaultTheme) ? defaultTheme : "" : null
93
+ ];
94
+ const script = themeScript(fresh);
95
+ const [first] = useState({ __html: script });
96
+ const [handle, config, themeList, setTheme] = useMemo(() => {
97
+ const handle2 = definePrefs({
98
+ theme: pref.enum(Object.keys(dom)).default(defaultTheme).options({ ...cookie, name: storageKey })
99
+ }).theme;
100
+ const setTheme2 = (next) => {
101
+ const name = typeof next == "function" ? next(handle2.get()) : next;
102
+ if (has(dom, name)) handle2.set(name);
103
+ };
104
+ return [handle2, fresh, listed, setTheme2];
105
+ }, [script, JSON.stringify(cookie)]);
106
+ const theme = useSyncExternalStore(handle.subscribe, handle.get, none);
107
+ const systemTheme = useSyncExternalStore(subscribeSystem, system, none);
108
+ const resolvedTheme = theme == "system" && enableSystem ? systemTheme : theme;
109
+ const [, refresh] = useReducer((n) => n + 1, 0);
110
+ useLayout(() => {
111
+ const once = !seen.has(handle.name);
112
+ seen.add(handle.name);
113
+ try {
114
+ if (!exists(handle.name)) {
115
+ const stored = localStorage.getItem(config[1]);
116
+ if (stored != null) {
117
+ const valid = has(config[3], stored);
118
+ if (valid) handle.set(stored);
119
+ if (!valid || exists(handle.name)) localStorage.removeItem(config[1]);
120
+ }
121
+ } else if (once && handle.toCookie(handle.get()).maxAge > 604800) handle.set(handle.get());
122
+ } catch {
123
+ }
124
+ const resume = disableTransitionOnChange && pauseTransitions(nonce);
125
+ paint(config, handle.get());
126
+ if (resume) resume();
127
+ const onVisible = () => {
128
+ if (document.visibilityState == "visible") {
129
+ paint(config, handle.get());
130
+ refresh();
131
+ }
132
+ };
133
+ document.addEventListener("visibilitychange", onVisible);
134
+ return () => document.removeEventListener("visibilitychange", onVisible);
135
+ }, [config, handle, theme, systemTheme, disableTransitionOnChange, nonce]);
136
+ const context = useMemo(
137
+ () => ({
138
+ theme,
139
+ setTheme,
140
+ forcedTheme,
141
+ resolvedTheme,
142
+ themes: themeList,
143
+ systemTheme: enableSystem ? systemTheme : void 0
144
+ }),
145
+ [theme, setTheme, forcedTheme, resolvedTheme, themeList, enableSystem, systemTheme]
146
+ );
147
+ const server = typeof document == "undefined";
148
+ return /* @__PURE__ */ jsxs(Context.Provider, { value: context, children: [
149
+ /* @__PURE__ */ jsx(
150
+ "script",
151
+ {
152
+ ...scriptProps,
153
+ type: server ? "text/javascript" : "text/plain",
154
+ nonce: server ? nonce : void 0,
155
+ suppressHydrationWarning: true,
156
+ dangerouslySetInnerHTML: first
157
+ }
158
+ ),
159
+ children
160
+ ] });
161
+ }
162
+ function useTheme() {
163
+ return useContext(Context) ?? outside;
164
+ }
165
+
166
+ export { ThemeProvider, useTheme };