@voidmix/themes 0.1.0 → 0.1.2

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.
@@ -1,6 +1,7 @@
1
1
 
2
2
  import * as React from "react";
3
3
  import { CSSProperties, ComponentPropsWithoutRef, ReactNode } from "react";
4
+ import { getHtmlThemeProps, getThemeScript, isValidTheme, parseThemeCookie, resolveRequestTheme, serializeThemeCookie } from "./server.js";
4
5
  type DataAttribute = `data-${string}`;
5
6
  type Attribute = DataAttribute | "class";
6
7
  type StorageMode = "localStorage" | "cookie" | "both";
@@ -144,33 +145,4 @@ declare const ThemeScope: React.ForwardRefExoticComponent<ThemeScopeProps & Reac
144
145
  * Useful for redrawing Canvas, WebGL, SVG, or chart components when the effective palette changes.
145
146
  */
146
147
  declare function observeTheme(element: Element, onChange: () => void, options?: ObserveThemeOptions): () => void;
147
- declare function isValidTheme(candidate: string | null | undefined, themes?: readonly string[], enableSystem?: boolean): candidate is string;
148
- /**
149
- * Parse a persisted theme preference from a Cookie header string.
150
- */
151
- declare function parseThemeCookie(cookieHeader: string | null | undefined, options?: ResolveRequestThemeOptions): string | undefined;
152
- /**
153
- * Resolve a persisted theme preference from a `Request`, `Headers`, or raw Cookie header string.
154
- */
155
- declare function resolveRequestTheme(source: Request | Headers | string | null | undefined, options?: ResolveRequestThemeOptions): ResolvedRequestTheme;
156
- /**
157
- * Serialize a Set-Cookie / `document.cookie` string for persisting the theme preference.
158
- */
159
- declare function serializeThemeCookie(theme: string, options?: CookieOptions & {
160
- storageKey?: string;
161
- }): string;
162
- /**
163
- * Build SSR props for `<html {...props} suppressHydrationWarning>` when rendering from a server-read theme cookie.
164
- * Returns an empty object when `theme` is `"system"` or `undefined` (letting the inline script resolve OS preference).
165
- */
166
- declare function getHtmlThemeProps(theme: string | undefined, options?: {
167
- attribute?: Attribute | Attribute[];
168
- enableColorScheme?: boolean;
169
- value?: Record<string, string>;
170
- }): HtmlThemeProps;
171
- /**
172
- * Generate a minimal, XSS-safe inline JavaScript snippet that resolves and applies the theme
173
- * synchronously before first paint (for SSR `<head>` injection or TanStack Router `<ScriptOnce>`).
174
- */
175
- declare function getThemeScript(options?: ThemeScriptOptions): string;
176
148
  export { ThemeScriptOptions as C, ThemeScopeProps as S, UseThemeProps as T, ResolveRequestThemeOptions as _, resolveRequestTheme as a, StorageMode as b, ThemeScope as c, useTheme as d, Attribute as f, ObserveThemeOptions as g, HtmlThemeProps as h, parseThemeCookie as i, useThemeScope as l, DataAttribute as m, getThemeScript as n, serializeThemeCookie as o, CookieOptions as p, isValidTheme as r, observeTheme as s, getHtmlThemeProps as t, ThemeProvider as u, ResolvedRequestTheme as v, ThemeStorageAdapter as w, ThemeProviderProps as x, ResolvedSystemTheme as y };
package/dist/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
 
2
- import { C as ThemeScriptOptions, S as ThemeScopeProps, T as UseThemeProps, _ as ResolveRequestThemeOptions, a as resolveRequestTheme, b as StorageMode, c as ThemeScope, d as useTheme, f as Attribute, g as ObserveThemeOptions, h as HtmlThemeProps, i as parseThemeCookie, l as useThemeScope, m as DataAttribute, n as getThemeScript, o as serializeThemeCookie, p as CookieOptions, r as isValidTheme, s as observeTheme, t as getHtmlThemeProps, u as ThemeProvider, v as ResolvedRequestTheme, w as ThemeStorageAdapter, x as ThemeProviderProps, y as ResolvedSystemTheme } from "./index-BWpp6AHJ.js";
2
+ import { C as ThemeScriptOptions, S as ThemeScopeProps, T as UseThemeProps, _ as ResolveRequestThemeOptions, a as resolveRequestTheme, b as StorageMode, c as ThemeScope, d as useTheme, f as Attribute, g as ObserveThemeOptions, h as HtmlThemeProps, i as parseThemeCookie, l as useThemeScope, m as DataAttribute, n as getThemeScript, o as serializeThemeCookie, p as CookieOptions, r as isValidTheme, s as observeTheme, t as getHtmlThemeProps, u as ThemeProvider, v as ResolvedRequestTheme, w as ThemeStorageAdapter, x as ThemeProviderProps, y as ResolvedSystemTheme } from "./index-Cn84UWgS.js";
3
3
  export { type Attribute, type CookieOptions, type DataAttribute, type HtmlThemeProps, type ObserveThemeOptions, type ResolveRequestThemeOptions, type ResolvedRequestTheme, type ResolvedSystemTheme, type StorageMode, ThemeProvider, type ThemeProviderProps, ThemeScope, type ThemeScopeProps, type ThemeScriptOptions, type ThemeStorageAdapter, type UseThemeProps, getHtmlThemeProps, getThemeScript, isValidTheme, observeTheme, parseThemeCookie, resolveRequestTheme, serializeThemeCookie, useTheme, useThemeScope };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- export { i as ThemeProvider, n as ThemeScope, o as getHtmlThemeProps, s as getThemeScript, c as isValidTheme, t as observeTheme, l as parseThemeCookie, u as resolveRequestTheme, d as serializeThemeCookie, a as useTheme, r as useThemeScope } from "./src-CwGSyikM.js";
2
+ export { u as ThemeProvider, c as ThemeScope, t as getHtmlThemeProps, n as getThemeScript, r as isValidTheme, s as observeTheme, i as parseThemeCookie, a as resolveRequestTheme, o as serializeThemeCookie, d as useTheme, l as useThemeScope } from "./src-DUNwyqLc.js";
@@ -1,137 +1,25 @@
1
1
  "use client";
2
2
  import * as React from "react";
3
+ import { COLOR_SCHEMES, COLOR_SCHEME_MEDIA, DEFAULT_STORAGE_KEY, DEFAULT_THEMES, getHtmlThemeProps, getThemeScript, getThemeScript as getThemeScript$1, isValidTheme, isValidTheme as isValidTheme$1, parseThemeCookie, parseThemeCookie as parseThemeCookie$1, resolveRequestTheme, serializeThemeCookie, serializeThemeCookie as serializeThemeCookie$1 } from "./server.js";
3
4
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
4
- // src/server.ts
5
- const COLOR_SCHEME_MEDIA = "(prefers-color-scheme: dark)";
6
- const DEFAULT_THEMES = ["light", "dark"];
7
- const COLOR_SCHEMES = ["light", "dark"];
8
- const DEFAULT_STORAGE_KEY = "theme";
9
- const DEFAULT_COOKIE_MAX_AGE = 31536e3;
10
- function escapeScriptJson(value) {
11
- return JSON.stringify(value).replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
12
- }
13
- function normalizeAttributes(attribute) {
14
- if (!attribute) return ["class"];
15
- return Array.isArray(attribute) ? attribute : [attribute];
16
- }
17
- function isValidTheme(candidate, themes = DEFAULT_THEMES, enableSystem = true) {
18
- if (!candidate) return false;
19
- if (enableSystem && candidate === "system") return true;
20
- return themes.includes(candidate);
21
- }
22
- /**
23
- * Parse a persisted theme preference from a Cookie header string.
24
- */
25
- function parseThemeCookie(cookieHeader, options) {
26
- if (!cookieHeader) return void 0;
27
- const key = options?.storageKey ?? "theme";
28
- const themes = options?.themes ?? DEFAULT_THEMES;
29
- const enableSystem = options?.enableSystem ?? true;
30
- const prefix = `${encodeURIComponent(key)}=`;
31
- const parts = cookieHeader.split(";");
32
- for (const part of parts) {
33
- const trimmed = part.trim();
34
- if (!trimmed.startsWith(prefix)) continue;
35
- const raw = trimmed.slice(prefix.length);
36
- try {
37
- const decoded = decodeURIComponent(raw);
38
- return isValidTheme(decoded, themes, enableSystem) ? decoded : void 0;
39
- } catch {
40
- return;
41
- }
42
- }
43
- }
44
- /**
45
- * Resolve a persisted theme preference from a `Request`, `Headers`, or raw Cookie header string.
46
- */
47
- function resolveRequestTheme(source, options) {
48
- const theme = parseThemeCookie(typeof source === "string" ? source : source instanceof Headers ? source.get("cookie") : source?.headers?.get("cookie"), options);
49
- return {
50
- theme,
51
- hasCookie: theme !== void 0,
52
- vary: "Cookie"
53
- };
54
- }
55
- /**
56
- * Serialize a Set-Cookie / `document.cookie` string for persisting the theme preference.
57
- */
58
- function serializeThemeCookie(theme, options) {
59
- const key = encodeURIComponent(options?.storageKey ?? "theme");
60
- const val = encodeURIComponent(theme);
61
- const maxAge = options?.maxAge ?? DEFAULT_COOKIE_MAX_AGE;
62
- const path = options?.path ?? "/";
63
- const sameSite = options?.sameSite ?? "Lax";
64
- const segments = [
65
- `${key}=${val}`,
66
- `Max-Age=${maxAge}`,
67
- `Path=${path}`,
68
- `SameSite=${sameSite}`
69
- ];
70
- if (options?.domain) segments.push(`Domain=${options.domain}`);
71
- if (options?.secure) segments.push("Secure");
72
- return segments.join("; ");
73
- }
74
- /**
75
- * Build SSR props for `<html {...props} suppressHydrationWarning>` when rendering from a server-read theme cookie.
76
- * Returns an empty object when `theme` is `"system"` or `undefined` (letting the inline script resolve OS preference).
77
- */
78
- function getHtmlThemeProps(theme, options) {
79
- if (!theme || theme === "system") return {};
80
- const attrs = normalizeAttributes(options?.attribute);
81
- const enableColorScheme = options?.enableColorScheme ?? true;
82
- const mapped = options?.value?.[theme] ?? theme;
83
- const props = {};
84
- for (const attr of attrs) if (attr === "class") props.className = props.className ? `${props.className} ${mapped}` : mapped;
85
- else props[attr] = mapped;
86
- if (enableColorScheme && (theme === "light" || theme === "dark")) props.style = { colorScheme: theme };
87
- return props;
88
- }
89
- /**
90
- * Generate a minimal, XSS-safe inline JavaScript snippet that resolves and applies the theme
91
- * synchronously before first paint (for SSR `<head>` injection or TanStack Router `<ScriptOnce>`).
92
- */
93
- function getThemeScript(options = {}) {
94
- const attrs = normalizeAttributes(options.attribute);
95
- const storageKey = options.storageKey ?? "theme";
96
- const storage = options.storage ?? "localStorage";
97
- const enableSystem = options.enableSystem ?? true;
98
- const enableColorScheme = options.enableColorScheme ?? true;
99
- const themes = options.themes ? [...options.themes] : [...DEFAULT_THEMES];
100
- const defaultTheme = options.defaultTheme ?? (enableSystem ? "system" : themes[0] ?? "light");
101
- const forcedTheme = options.forcedTheme ?? null;
102
- const valueMap = options.value ?? null;
103
- const args = escapeScriptJson([
104
- attrs,
105
- storageKey,
106
- storage,
107
- defaultTheme,
108
- forcedTheme,
109
- themes,
110
- valueMap ? Object.values(valueMap) : themes,
111
- enableSystem,
112
- enableColorScheme,
113
- valueMap
114
- ]);
115
- return `(function(a,k,st,dt,ft,ts,cv,es,ec,vm){try{var d=document.documentElement,c=d.classList,t=ft;if(!t){if(st==='cookie'||st==='both'){var p=encodeURIComponent(k)+'=',m=document.cookie.split(';');for(var i=0;i<m.length;i++){var s=m[i].trim();if(s.indexOf(p)===0){t=decodeURIComponent(s.slice(p.length));break}}}if(!t&&(st==='localStorage'||st==='both')){try{t=localStorage.getItem(k)}catch(e){}}if(!t||(ts.indexOf(t)===-1&&!(es&&t==='system'))){t=dt}}var r=t==='system'?(window.matchMedia('${COLOR_SCHEME_MEDIA}').matches?'dark':'light'):t;var v=vm&&vm[r]?vm[r]:r;for(var j=0;j<a.length;j++){var x=a[j];if(x==='class'){for(var n=0;n<cv.length;n++)c.remove(cv[n]);if(v)c.add(v)}else if(v){d.setAttribute(x,v)}else{d.removeAttribute(x)}}if(ec&&(r==='light'||r==='dark'))d.style.colorScheme=r}catch(e){}}).apply(null,${args})`;
116
- }
117
5
  // src/theme-provider.tsx
118
6
  const ThemeContext = React.createContext(void 0);
119
7
  const DEFAULT_THEME_LIST = [...DEFAULT_THEMES];
120
8
  const isServer = typeof window === "undefined";
121
9
  function getSystemTheme(media) {
122
- return (media ?? (isServer ? void 0 : window.matchMedia("(prefers-color-scheme: dark)")))?.matches ? "dark" : "light";
10
+ return (media ?? (isServer ? void 0 : window.matchMedia(COLOR_SCHEME_MEDIA)))?.matches ? "dark" : "light";
123
11
  }
124
12
  function readStoredTheme(storage, storageKey, themes, enableSystem, storageAdapter) {
125
13
  if (storageAdapter) {
126
14
  try {
127
15
  const fromAdapter = storageAdapter.read(storageKey);
128
- if (isValidTheme(fromAdapter, themes, enableSystem)) return fromAdapter;
16
+ if (isValidTheme$1(fromAdapter, themes, enableSystem)) return fromAdapter;
129
17
  } catch {}
130
18
  return;
131
19
  }
132
20
  if (isServer) return void 0;
133
21
  if (storage === "cookie" || storage === "both") {
134
- const fromCookie = parseThemeCookie(document.cookie, {
22
+ const fromCookie = parseThemeCookie$1(document.cookie, {
135
23
  storageKey,
136
24
  themes,
137
25
  enableSystem
@@ -140,7 +28,7 @@ function readStoredTheme(storage, storageKey, themes, enableSystem, storageAdapt
140
28
  }
141
29
  if (storage === "localStorage" || storage === "both") try {
142
30
  const fromStorage = window.localStorage.getItem(storageKey);
143
- if (isValidTheme(fromStorage, themes, enableSystem)) return fromStorage;
31
+ if (isValidTheme$1(fromStorage, themes, enableSystem)) return fromStorage;
144
32
  } catch {}
145
33
  }
146
34
  function writeStoredTheme(theme, storage, storageKey, cookieOptions, storageAdapter) {
@@ -156,7 +44,7 @@ function writeStoredTheme(theme, storage, storageKey, cookieOptions, storageAdap
156
44
  } catch {}
157
45
  if (storage === "cookie" || storage === "both") try {
158
46
  const secure = cookieOptions?.secure ?? (typeof location !== "undefined" && location.protocol === "https:");
159
- document.cookie = serializeThemeCookie(theme, {
47
+ document.cookie = serializeThemeCookie$1(theme, {
160
48
  ...cookieOptions,
161
49
  secure,
162
50
  storageKey
@@ -213,7 +101,7 @@ function ThemeProviderInner({ children, themes: themesProp = DEFAULT_THEME_LIST,
213
101
  const cookieKey = cookieOptions ? JSON.stringify(cookieOptions) : "";
214
102
  const stableCookieOptions = React.useMemo(() => cookieOptions, [cookieKey]);
215
103
  const defaultTheme = defaultThemeProp ?? (enableSystem ? "system" : themes[0] ?? "light");
216
- const normalizedInitial = isValidTheme(initialTheme, themes, enableSystem) ? initialTheme : void 0;
104
+ const normalizedInitial = isValidTheme$1(initialTheme, themes, enableSystem) ? initialTheme : void 0;
217
105
  const [theme, setThemeState] = React.useState(normalizedInitial);
218
106
  const [systemTheme, setSystemTheme] = React.useState(void 0);
219
107
  const themeRef = React.useRef(theme);
@@ -296,7 +184,7 @@ function ThemeProviderInner({ children, themes: themesProp = DEFAULT_THEME_LIST,
296
184
  if (!storageAdapterRef.current && (storage === "localStorage" || storage === "both")) {
297
185
  const handleStorage = (event) => {
298
186
  if (event.key !== storageKey) return;
299
- const next = isValidTheme(event.newValue, themes, enableSystem) ? event.newValue : defaultTheme;
187
+ const next = isValidTheme$1(event.newValue, themes, enableSystem) ? event.newValue : defaultTheme;
300
188
  themeRef.current = next;
301
189
  setThemeState(next);
302
190
  };
@@ -308,7 +196,7 @@ function ThemeProviderInner({ children, themes: themesProp = DEFAULT_THEME_LIST,
308
196
  channelRef.current = channel;
309
197
  const handleMessage = (event) => {
310
198
  const candidate = typeof event.data === "string" ? event.data : void 0;
311
- if (!isValidTheme(candidate, themes, enableSystem)) return;
199
+ if (!isValidTheme$1(candidate, themes, enableSystem)) return;
312
200
  themeRef.current = candidate;
313
201
  setThemeState(candidate);
314
202
  };
@@ -333,7 +221,7 @@ function ThemeProviderInner({ children, themes: themesProp = DEFAULT_THEME_LIST,
333
221
  const setTheme = React.useCallback((next) => {
334
222
  const base = themeRef.current ?? defaultTheme;
335
223
  const resolvedNext = typeof next === "function" ? next(base) : next;
336
- if (!isValidTheme(resolvedNext, themes, enableSystem)) return;
224
+ if (!isValidTheme$1(resolvedNext, themes, enableSystem)) return;
337
225
  themeRef.current = resolvedNext;
338
226
  setThemeState(resolvedNext);
339
227
  writeStoredTheme(resolvedNext, storage, storageKey, stableCookieOptions, storageAdapterRef.current);
@@ -354,7 +242,7 @@ function ThemeProviderInner({ children, themes: themesProp = DEFAULT_THEME_LIST,
354
242
  themes,
355
243
  viewTransition
356
244
  ]);
357
- const script = React.useMemo(() => enableScript ? getThemeScript({
245
+ const script = React.useMemo(() => enableScript ? getThemeScript$1({
358
246
  attribute: attrs,
359
247
  storageKey,
360
248
  storage,
@@ -472,4 +360,4 @@ function observeTheme(element, onChange, options) {
472
360
  observer.disconnect();
473
361
  };
474
362
  }
475
- export { useTheme as a, isValidTheme as c, serializeThemeCookie as d, ThemeProvider as i, parseThemeCookie as l, ThemeScope as n, getHtmlThemeProps as o, useThemeScope as r, getThemeScript as s, observeTheme as t, resolveRequestTheme as u };
363
+ export { resolveRequestTheme as a, ThemeScope as c, useTheme as d, parseThemeCookie as i, useThemeScope as l, getThemeScript as n, serializeThemeCookie as o, isValidTheme as r, observeTheme as s, getHtmlThemeProps as t, ThemeProvider as u };
@@ -1,6 +1,6 @@
1
1
 
2
2
  import * as React from "react";
3
- import { C as ThemeScriptOptions, S as ThemeScopeProps, T as UseThemeProps, _ as ResolveRequestThemeOptions, a as resolveRequestTheme, b as StorageMode, c as ThemeScope, d as useTheme, f as Attribute, g as ObserveThemeOptions, h as HtmlThemeProps, i as parseThemeCookie, l as useThemeScope, m as DataAttribute, n as getThemeScript, o as serializeThemeCookie, p as CookieOptions, r as isValidTheme, s as observeTheme, t as getHtmlThemeProps, v as ResolvedRequestTheme, w as ThemeStorageAdapter, x as ThemeProviderProps, y as ResolvedSystemTheme } from "./index-BWpp6AHJ.js";
3
+ import { C as ThemeScriptOptions, S as ThemeScopeProps, T as UseThemeProps, _ as ResolveRequestThemeOptions, a as resolveRequestTheme, b as StorageMode, c as ThemeScope, d as useTheme, f as Attribute, g as ObserveThemeOptions, h as HtmlThemeProps, i as parseThemeCookie, l as useThemeScope, m as DataAttribute, n as getThemeScript, o as serializeThemeCookie, p as CookieOptions, r as isValidTheme, s as observeTheme, t as getHtmlThemeProps, v as ResolvedRequestTheme, w as ThemeStorageAdapter, x as ThemeProviderProps, y as ResolvedSystemTheme } from "./index-Cn84UWgS.js";
4
4
  /**
5
5
  * TanStack Start & TanStack Router `<ThemeProvider>`.
6
6
  * Uses TanStack Router's `<ScriptOnce>` during SSR for automatic CSP nonce pickup and self-cleanup,
package/dist/tanstack.js CHANGED
@@ -1,7 +1,7 @@
1
1
  "use client";
2
2
  import "react";
3
3
  import { ScriptOnce, useRouter } from "@tanstack/react-router";
4
- import { a as useTheme, c as isValidTheme, d as serializeThemeCookie, i as ThemeProvider$1, l as parseThemeCookie, n as ThemeScope, o as getHtmlThemeProps, r as useThemeScope, s as getThemeScript, t as observeTheme, u as resolveRequestTheme } from "./src-CwGSyikM.js";
4
+ import { a as resolveRequestTheme, c as ThemeScope, d as useTheme, i as parseThemeCookie, l as useThemeScope, n as getThemeScript, o as serializeThemeCookie, r as isValidTheme, s as observeTheme, t as getHtmlThemeProps, u as ThemeProvider$1 } from "./src-DUNwyqLc.js";
5
5
  import { jsx } from "react/jsx-runtime";
6
6
  // src/tanstack.tsx
7
7
  const isServer = typeof window === "undefined";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@voidmix/themes",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Zero-FOUC theming for React, TanStack Start, and TanStack Router — SSR script injection, Cookie SSR helpers, multi-attribute sync, custom storage adapters, cross-tab BroadcastChannel sync, and scoped themes.",
5
5
  "license": "MIT",
6
6
  "author": "Zack <heyloyep@gmail.com> (https://github.com/loyep)",