@voidmix/themes 0.0.0-stage → 0.1.1

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/LICENSE ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Zack (https://github.com/loyep)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,150 @@
1
- # Temporary Holding Version
1
+ # @voidmix/themes
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Zero-FOUC theming for **React**, **TanStack Start**, and **TanStack Router** — zero runtime dependencies, native `<ScriptOnce>` adapter, Cookie SSR helpers, multi-attribute sync, custom storage adapters, `BroadcastChannel` cross-tab sync, and CSS `@scope` themed subtrees.
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@voidmix/themes)](https://www.npmjs.com/package/@voidmix/themes)
6
+ [![CI](https://github.com/voidmix/themes/actions/workflows/ci.yml/badge.svg)](https://github.com/voidmix/themes/actions/workflows/ci.yml)
7
+ [![license](https://img.shields.io/npm/l/@voidmix/themes)](./LICENSE)
8
+
9
+ ---
10
+
11
+ ## Features
12
+
13
+ - **Zero runtime dependencies** — pure ESM + strict `.d.ts` built with `tsdown` (Rolldown). Works in any React 18/19 app without requiring `@tanstack/react-router`.
14
+ - **Dedicated TanStack adapter (`@voidmix/themes/tanstack`)** — injects an XSS-safe blocking script via TanStack Router's `<ScriptOnce>` during SSR with automatic CSP nonce pickup and self-cleanup before React 19 hydration.
15
+ - **Drop-in `next-themes` ergonomics** — `ThemeProvider`, typed `useTheme<T>()`, `systemTheme`, `resolvedTheme`, `forcedTheme`, `disableTransitionOnChange`, `enableColorScheme`, `onThemeChange`, and optional View Transitions API.
16
+ - **Multi-attribute & custom storage support** — target `"class"`, `"data-theme"`, any `data-*`, or an array like `["class", "data-theme"]`; persist via `localStorage`, `cookie`, `"both"`, or a custom `storageAdapter` (Tauri, Electron, tests).
17
+ - **Cross-tab synchronization** — keeps tabs in sync via both `StorageEvent` and `BroadcastChannel` (including `storage="cookie"` mode).
18
+ - **Cookie SSR helpers (`@voidmix/themes/server`)** — runtime-agnostic `parseThemeCookie`, `resolveRequestTheme`, `serializeThemeCookie`, `getHtmlThemeProps`, and `getThemeScript` (zero React, zero DOM).
19
+ - **Scoped themes (`<ThemeScope>`, `observeTheme`, `@voidmix/themes/tailwind.css`)** — nest light cards inside dark pages (or vice versa, including `theme="system"`) with CSS `@scope`-aware Tailwind v4 `dark:` variants and Canvas/chart theme observation.
20
+
21
+ ---
22
+
23
+ ## Install
24
+
25
+ ```bash
26
+ npm install @voidmix/themes
27
+ # or
28
+ pnpm add @voidmix/themes
29
+ # or
30
+ bun add @voidmix/themes
31
+ ```
32
+
33
+ Peer dependencies: `react >= 18` (and optional `@tanstack/react-router >= 1` when importing `@voidmix/themes/tanstack`).
34
+
35
+ ---
36
+
37
+ ## Entrypoints
38
+
39
+ | Entrypoint | Purpose |
40
+ | --- | --- |
41
+ | `@voidmix/themes` | React 18/19 core (`ThemeProvider`, `useTheme`, `ThemeScope`, `useThemeScope`, `observeTheme`, plus SSR helpers). Zero router dependency. |
42
+ | `@voidmix/themes/tanstack` | TanStack Start / TanStack Router `ThemeProvider` using `<ScriptOnce>` (re-exports everything from `@voidmix/themes`). |
43
+ | `@voidmix/themes/server` | Pure server/runtime-agnostic helpers (`parseThemeCookie`, `resolveRequestTheme`, `serializeThemeCookie`, `getHtmlThemeProps`, `getThemeScript`). |
44
+ | `@voidmix/themes/tailwind.css` | Tailwind CSS v4 `@custom-variant dark` with `@scope` boundary support for `<ThemeScope>`. |
45
+
46
+ ---
47
+
48
+ ## Quick Start (React / Vite / Tauri)
49
+
50
+ ```tsx
51
+ import { ThemeProvider, useTheme } from "@voidmix/themes";
52
+
53
+ export function App() {
54
+ return (
55
+ <ThemeProvider attribute={["class", "data-theme"]} defaultTheme="system">
56
+ <ThemeToggle />
57
+ </ThemeProvider>
58
+ );
59
+ }
60
+
61
+ function ThemeToggle() {
62
+ const { theme, resolvedTheme, setTheme } = useTheme();
63
+ return (
64
+ <button
65
+ type="button"
66
+ onClick={() => setTheme(resolvedTheme === "dark" ? "light" : "dark")}
67
+ >
68
+ Current: {theme ?? "…"}
69
+ </button>
70
+ );
71
+ }
72
+ ```
73
+
74
+ ---
75
+
76
+ ## Quick Start (TanStack Start & Cookie SSR)
77
+
78
+ ```tsx
79
+ import { createRootRoute, HeadContent, Outlet, Scripts } from "@tanstack/react-router";
80
+ import { createServerFn } from "@tanstack/react-start";
81
+ import { getRequest } from "@tanstack/react-start/server";
82
+ import { ThemeProvider } from "@voidmix/themes/tanstack";
83
+ import { getHtmlThemeProps, resolveRequestTheme } from "@voidmix/themes/server";
84
+
85
+ const getInitialTheme = createServerFn({ method: "GET" }).handler(() => {
86
+ return resolveRequestTheme(getRequest(), { storageKey: "theme" }).theme;
87
+ });
88
+
89
+ export const Route = createRootRoute({
90
+ loader: () => getInitialTheme(),
91
+ component: RootDocument,
92
+ });
93
+
94
+ function RootDocument() {
95
+ const initialTheme = Route.useLoaderData();
96
+ const htmlProps = getHtmlThemeProps(initialTheme, {
97
+ attribute: ["class", "data-theme"],
98
+ });
99
+
100
+ return (
101
+ <html lang="en" {...htmlProps} suppressHydrationWarning>
102
+ <head>
103
+ <HeadContent />
104
+ </head>
105
+ <body>
106
+ <ThemeProvider
107
+ initialTheme={initialTheme}
108
+ storage="both"
109
+ storageKey="theme"
110
+ attribute={["class", "data-theme"]}
111
+ >
112
+ <Outlet />
113
+ </ThemeProvider>
114
+ <Scripts />
115
+ </body>
116
+ </html>
117
+ );
118
+ }
119
+ ```
120
+
121
+ ---
122
+
123
+ ## Scoped Themes & Tailwind CSS v4
124
+
125
+ Import the `@scope`-aware dark variant in your CSS entry:
126
+
127
+ ```css
128
+ @import "tailwindcss";
129
+ @import "@voidmix/themes/tailwind.css";
130
+ ```
131
+
132
+ Then render isolated subtrees anywhere:
133
+
134
+ ```tsx
135
+ import { ThemeScope } from "@voidmix/themes";
136
+
137
+ export function PreviewCard() {
138
+ return (
139
+ <ThemeScope theme="light" className="rounded-xl border p-4">
140
+ Always renders with light tokens, even inside a dark page.
141
+ </ThemeScope>
142
+ );
143
+ }
144
+ ```
145
+
146
+ ---
147
+
148
+ ## License
149
+
150
+ MIT © [Zack](https://github.com/loyep)
@@ -0,0 +1,176 @@
1
+
2
+ import * as React from "react";
3
+ import { CSSProperties, ComponentPropsWithoutRef, ReactNode } from "react";
4
+ type DataAttribute = `data-${string}`;
5
+ type Attribute = DataAttribute | "class";
6
+ type StorageMode = "localStorage" | "cookie" | "both";
7
+ type ResolvedSystemTheme = "light" | "dark";
8
+ interface CookieOptions {
9
+ /** Cookie max-age in seconds. Defaults to 1 year (31536000). */
10
+ maxAge?: number;
11
+ /** Cookie path. Defaults to "/". */
12
+ path?: string;
13
+ /** Optional cookie domain. */
14
+ domain?: string;
15
+ /** SameSite policy. Defaults to "Lax". */
16
+ sameSite?: "Lax" | "Strict" | "None";
17
+ /** Whether to include the Secure flag. Defaults to auto (true on HTTPS). */
18
+ secure?: boolean;
19
+ }
20
+ interface ThemeStorageAdapter {
21
+ read: (key: string) => string | null | undefined;
22
+ write: (key: string, value: string) => void;
23
+ }
24
+ interface ThemeScriptOptions {
25
+ /** HTML attribute(s) updated on `document.documentElement`. Defaults to `"class"`. */
26
+ attribute?: Attribute | Attribute[];
27
+ /** Storage key / cookie name. Defaults to `"theme"`. */
28
+ storageKey?: string;
29
+ /** Storage backend(s) to read from. Defaults to `"localStorage"`. */
30
+ storage?: StorageMode;
31
+ /** Default theme when no persisted preference exists. Defaults to `"system"` if `enableSystem` is true, else `"light"`. */
32
+ defaultTheme?: string;
33
+ /** Forced theme that overrides stored preference for this view. */
34
+ forcedTheme?: string;
35
+ /** List of valid theme names (excluding `"system"`). Defaults to `["light", "dark"]`. */
36
+ themes?: readonly string[];
37
+ /** Enable `"system"` theme resolution via `prefers-color-scheme`. Defaults to `true`. */
38
+ enableSystem?: boolean;
39
+ /** Sync `document.documentElement.style.colorScheme`. Defaults to `true`. */
40
+ enableColorScheme?: boolean;
41
+ /** Optional mapping from theme name to DOM attribute/class value. */
42
+ value?: Record<string, string>;
43
+ }
44
+ interface ThemeProviderProps extends ThemeScriptOptions {
45
+ children?: ReactNode;
46
+ /**
47
+ * Optional theme resolved on the server (e.g. via `parseThemeCookie` or `resolveRequestTheme`).
48
+ * Eliminates hydration delay and makes `theme` immediately defined on the first render.
49
+ */
50
+ initialTheme?: string;
51
+ /** Cookie serialization options when `storage` is `"cookie"` or `"both"`. */
52
+ cookieOptions?: CookieOptions;
53
+ /** Optional custom storage adapter (e.g. Tauri store, Electron store, or in-memory test store). */
54
+ storageAdapter?: ThemeStorageAdapter;
55
+ /** Synchronize theme changes across browser tabs via `StorageEvent` and `BroadcastChannel`. Defaults to `true`. */
56
+ syncTabs?: boolean;
57
+ /** Callback invoked when the user updates the theme via `setTheme`. */
58
+ onThemeChange?: (theme: string) => void;
59
+ /** Temporarily disable CSS transitions during theme swaps to avoid mixed-speed flashes. Defaults to `false`. */
60
+ disableTransitionOnChange?: boolean;
61
+ /** Wrap DOM theme swaps in `document.startViewTransition()` when supported and motion is not reduced. Defaults to `false`. */
62
+ viewTransition?: boolean;
63
+ /** Inject the anti-FOUC inline script during SSR. Defaults to `true`. */
64
+ enableScript?: boolean;
65
+ /** Optional CSP nonce applied to injected `<script>` / `<style>` elements. */
66
+ nonce?: string;
67
+ /**
68
+ * Optional custom renderer for the anti-FOUC script (used by `@voidmix/themes/tanstack`
69
+ * to emit TanStack Router's `<ScriptOnce>`).
70
+ */
71
+ renderScript?: (script: string, nonce?: string) => ReactNode;
72
+ }
73
+ interface UseThemeProps<T extends string = string> {
74
+ /** Available theme names (includes `"system"` when `enableSystem` is true). */
75
+ themes: T[];
76
+ /** Active forced theme for the current route/provider, if any. */
77
+ forcedTheme?: T;
78
+ /** Update the active theme preference. */
79
+ setTheme: (theme: T | ((prev: T) => T)) => void;
80
+ /** Active user theme preference (`"light"`, `"dark"`, `"system"`, or a custom theme). */
81
+ theme?: T;
82
+ /** Resolved concrete theme applied to the DOM (`"light"`, `"dark"`, or custom theme). */
83
+ resolvedTheme?: T;
84
+ /** Current OS preference when `enableSystem` is enabled. */
85
+ systemTheme?: ResolvedSystemTheme;
86
+ }
87
+ interface HtmlThemeProps {
88
+ className?: string;
89
+ style?: CSSProperties;
90
+ [key: DataAttribute]: string | undefined;
91
+ }
92
+ interface ResolveRequestThemeOptions {
93
+ /** Cookie name to read. Defaults to `"theme"`. */
94
+ storageKey?: string;
95
+ /** List of valid theme names (excluding `"system"`). Defaults to `["light", "dark"]`. */
96
+ themes?: readonly string[];
97
+ /** Whether `"system"` is accepted as a valid theme. Defaults to `true`. */
98
+ enableSystem?: boolean;
99
+ }
100
+ interface ResolvedRequestTheme {
101
+ /** Validated theme read from the request Cookie header, or `undefined` if absent/invalid. */
102
+ theme: string | undefined;
103
+ /** Whether a valid theme cookie was present on the request. */
104
+ hasCookie: boolean;
105
+ /** Recommended `Vary` header value for cookie-dependent SSR responses. */
106
+ vary: "Cookie";
107
+ }
108
+ interface ThemeScopeProps extends ComponentPropsWithoutRef<"div"> {
109
+ /** Scoped theme for this subtree (`"light"`, `"dark"`, `"system"`, or a custom theme). */
110
+ theme: string;
111
+ /** HTML attribute(s) applied to the scope element. Defaults to `["class", "data-theme"]`. */
112
+ attribute?: Attribute | Attribute[];
113
+ /** Sync `style.colorScheme` on the scope element. Defaults to `true`. */
114
+ enableColorScheme?: boolean;
115
+ /** Optional mapping from theme name to DOM attribute/class value. */
116
+ value?: Record<string, string>;
117
+ }
118
+ interface ObserveThemeOptions {
119
+ /** DOM attributes to watch on ancestor elements. Defaults to `["class", "data-theme", "style"]`. */
120
+ attributes?: string[];
121
+ }
122
+ /**
123
+ * Read and update the active theme inside a `<ThemeProvider>`.
124
+ */
125
+ declare function useTheme<T extends string = string>(): UseThemeProps<T>;
126
+ /**
127
+ * Root theme provider for React 18/19 (zero router coupling).
128
+ * Emits a zero-FOUC self-removing blocking script during SSR, synchronizes DOM attributes,
129
+ * OS preferences, storage/cookies/custom adapters, and cross-tab updates.
130
+ */
131
+ declare function ThemeProvider(props: ThemeProviderProps): React.JSX.Element;
132
+ /**
133
+ * Returns the nearest enclosing `<ThemeScope theme="...">` value, if any.
134
+ */
135
+ declare function useThemeScope(): string | undefined;
136
+ /**
137
+ * Creates an isolated theme scope for a subtree (e.g. a light preview card inside a dark app).
138
+ * Pairs with `@voidmix/themes/tailwind.css` so Tailwind `dark:` utilities stop at the scope boundary.
139
+ */
140
+ declare const ThemeScope: React.ForwardRefExoticComponent<ThemeScopeProps & React.RefAttributes<HTMLDivElement>>;
141
+ /**
142
+ * Observe theme changes affecting `element` — including ancestor attribute mutations
143
+ * (crossing ShadowRoot boundaries) as well as OS `prefers-color-scheme` changes.
144
+ * Useful for redrawing Canvas, WebGL, SVG, or chart components when the effective palette changes.
145
+ */
146
+ 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
+ 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 };
@@ -0,0 +1,3 @@
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";
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 ADDED
@@ -0,0 +1,2 @@
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";
@@ -0,0 +1,91 @@
1
+ import { CSSProperties } from "react";
2
+ type DataAttribute = `data-${string}`;
3
+ type Attribute = DataAttribute | "class";
4
+ type StorageMode = "localStorage" | "cookie" | "both";
5
+ interface CookieOptions {
6
+ /** Cookie max-age in seconds. Defaults to 1 year (31536000). */
7
+ maxAge?: number;
8
+ /** Cookie path. Defaults to "/". */
9
+ path?: string;
10
+ /** Optional cookie domain. */
11
+ domain?: string;
12
+ /** SameSite policy. Defaults to "Lax". */
13
+ sameSite?: "Lax" | "Strict" | "None";
14
+ /** Whether to include the Secure flag. Defaults to auto (true on HTTPS). */
15
+ secure?: boolean;
16
+ }
17
+ interface ThemeScriptOptions {
18
+ /** HTML attribute(s) updated on `document.documentElement`. Defaults to `"class"`. */
19
+ attribute?: Attribute | Attribute[];
20
+ /** Storage key / cookie name. Defaults to `"theme"`. */
21
+ storageKey?: string;
22
+ /** Storage backend(s) to read from. Defaults to `"localStorage"`. */
23
+ storage?: StorageMode;
24
+ /** Default theme when no persisted preference exists. Defaults to `"system"` if `enableSystem` is true, else `"light"`. */
25
+ defaultTheme?: string;
26
+ /** Forced theme that overrides stored preference for this view. */
27
+ forcedTheme?: string;
28
+ /** List of valid theme names (excluding `"system"`). Defaults to `["light", "dark"]`. */
29
+ themes?: readonly string[];
30
+ /** Enable `"system"` theme resolution via `prefers-color-scheme`. Defaults to `true`. */
31
+ enableSystem?: boolean;
32
+ /** Sync `document.documentElement.style.colorScheme`. Defaults to `true`. */
33
+ enableColorScheme?: boolean;
34
+ /** Optional mapping from theme name to DOM attribute/class value. */
35
+ value?: Record<string, string>;
36
+ }
37
+ interface HtmlThemeProps {
38
+ className?: string;
39
+ style?: CSSProperties;
40
+ [key: DataAttribute]: string | undefined;
41
+ }
42
+ interface ResolveRequestThemeOptions {
43
+ /** Cookie name to read. Defaults to `"theme"`. */
44
+ storageKey?: string;
45
+ /** List of valid theme names (excluding `"system"`). Defaults to `["light", "dark"]`. */
46
+ themes?: readonly string[];
47
+ /** Whether `"system"` is accepted as a valid theme. Defaults to `true`. */
48
+ enableSystem?: boolean;
49
+ }
50
+ interface ResolvedRequestTheme {
51
+ /** Validated theme read from the request Cookie header, or `undefined` if absent/invalid. */
52
+ theme: string | undefined;
53
+ /** Whether a valid theme cookie was present on the request. */
54
+ hasCookie: boolean;
55
+ /** Recommended `Vary` header value for cookie-dependent SSR responses. */
56
+ vary: "Cookie";
57
+ }
58
+ export declare const COLOR_SCHEME_MEDIA = "(prefers-color-scheme: dark)";
59
+ export declare const DEFAULT_THEMES: readonly ["light", "dark"];
60
+ export declare const COLOR_SCHEMES: readonly ["light", "dark"];
61
+ export declare const DEFAULT_STORAGE_KEY = "theme";
62
+ export declare function isValidTheme(candidate: string | null | undefined, themes?: readonly string[], enableSystem?: boolean): candidate is string;
63
+ /**
64
+ * Parse a persisted theme preference from a Cookie header string.
65
+ */
66
+ export declare function parseThemeCookie(cookieHeader: string | null | undefined, options?: ResolveRequestThemeOptions): string | undefined;
67
+ /**
68
+ * Resolve a persisted theme preference from a `Request`, `Headers`, or raw Cookie header string.
69
+ */
70
+ export declare function resolveRequestTheme(source: Request | Headers | string | null | undefined, options?: ResolveRequestThemeOptions): ResolvedRequestTheme;
71
+ /**
72
+ * Serialize a Set-Cookie / `document.cookie` string for persisting the theme preference.
73
+ */
74
+ export declare function serializeThemeCookie(theme: string, options?: CookieOptions & {
75
+ storageKey?: string;
76
+ }): string;
77
+ /**
78
+ * Build SSR props for `<html {...props} suppressHydrationWarning>` when rendering from a server-read theme cookie.
79
+ * Returns an empty object when `theme` is `"system"` or `undefined` (letting the inline script resolve OS preference).
80
+ */
81
+ export declare function getHtmlThemeProps(theme: string | undefined, options?: {
82
+ attribute?: Attribute | Attribute[];
83
+ enableColorScheme?: boolean;
84
+ value?: Record<string, string>;
85
+ }): HtmlThemeProps;
86
+ /**
87
+ * Generate a minimal, XSS-safe inline JavaScript snippet that resolves and applies the theme
88
+ * synchronously before first paint (for SSR `<head>` injection or TanStack Router `<ScriptOnce>`).
89
+ */
90
+ export declare function getThemeScript(options?: ThemeScriptOptions): string;
91
+ export {};
package/dist/server.js ADDED
@@ -0,0 +1,114 @@
1
+ // src/server.ts
2
+ const COLOR_SCHEME_MEDIA = "(prefers-color-scheme: dark)";
3
+ const DEFAULT_THEMES = ["light", "dark"];
4
+ const COLOR_SCHEMES = ["light", "dark"];
5
+ const DEFAULT_STORAGE_KEY = "theme";
6
+ const DEFAULT_COOKIE_MAX_AGE = 31536e3;
7
+ function escapeScriptJson(value) {
8
+ return JSON.stringify(value).replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
9
+ }
10
+ function normalizeAttributes(attribute) {
11
+ if (!attribute) return ["class"];
12
+ return Array.isArray(attribute) ? attribute : [attribute];
13
+ }
14
+ function isValidTheme(candidate, themes = DEFAULT_THEMES, enableSystem = true) {
15
+ if (!candidate) return false;
16
+ if (enableSystem && candidate === "system") return true;
17
+ return themes.includes(candidate);
18
+ }
19
+ /**
20
+ * Parse a persisted theme preference from a Cookie header string.
21
+ */
22
+ function parseThemeCookie(cookieHeader, options) {
23
+ if (!cookieHeader) return void 0;
24
+ const key = options?.storageKey ?? "theme";
25
+ const themes = options?.themes ?? DEFAULT_THEMES;
26
+ const enableSystem = options?.enableSystem ?? true;
27
+ const prefix = `${encodeURIComponent(key)}=`;
28
+ const parts = cookieHeader.split(";");
29
+ for (const part of parts) {
30
+ const trimmed = part.trim();
31
+ if (!trimmed.startsWith(prefix)) continue;
32
+ const raw = trimmed.slice(prefix.length);
33
+ try {
34
+ const decoded = decodeURIComponent(raw);
35
+ return isValidTheme(decoded, themes, enableSystem) ? decoded : void 0;
36
+ } catch {
37
+ return;
38
+ }
39
+ }
40
+ }
41
+ /**
42
+ * Resolve a persisted theme preference from a `Request`, `Headers`, or raw Cookie header string.
43
+ */
44
+ function resolveRequestTheme(source, options) {
45
+ const theme = parseThemeCookie(typeof source === "string" ? source : source instanceof Headers ? source.get("cookie") : source?.headers?.get("cookie"), options);
46
+ return {
47
+ theme,
48
+ hasCookie: theme !== void 0,
49
+ vary: "Cookie"
50
+ };
51
+ }
52
+ /**
53
+ * Serialize a Set-Cookie / `document.cookie` string for persisting the theme preference.
54
+ */
55
+ function serializeThemeCookie(theme, options) {
56
+ const key = encodeURIComponent(options?.storageKey ?? "theme");
57
+ const val = encodeURIComponent(theme);
58
+ const maxAge = options?.maxAge ?? DEFAULT_COOKIE_MAX_AGE;
59
+ const path = options?.path ?? "/";
60
+ const sameSite = options?.sameSite ?? "Lax";
61
+ const segments = [
62
+ `${key}=${val}`,
63
+ `Max-Age=${maxAge}`,
64
+ `Path=${path}`,
65
+ `SameSite=${sameSite}`
66
+ ];
67
+ if (options?.domain) segments.push(`Domain=${options.domain}`);
68
+ if (options?.secure) segments.push("Secure");
69
+ return segments.join("; ");
70
+ }
71
+ /**
72
+ * Build SSR props for `<html {...props} suppressHydrationWarning>` when rendering from a server-read theme cookie.
73
+ * Returns an empty object when `theme` is `"system"` or `undefined` (letting the inline script resolve OS preference).
74
+ */
75
+ function getHtmlThemeProps(theme, options) {
76
+ if (!theme || theme === "system") return {};
77
+ const attrs = normalizeAttributes(options?.attribute);
78
+ const enableColorScheme = options?.enableColorScheme ?? true;
79
+ const mapped = options?.value?.[theme] ?? theme;
80
+ const props = {};
81
+ for (const attr of attrs) if (attr === "class") props.className = props.className ? `${props.className} ${mapped}` : mapped;
82
+ else props[attr] = mapped;
83
+ if (enableColorScheme && (theme === "light" || theme === "dark")) props.style = { colorScheme: theme };
84
+ return props;
85
+ }
86
+ /**
87
+ * Generate a minimal, XSS-safe inline JavaScript snippet that resolves and applies the theme
88
+ * synchronously before first paint (for SSR `<head>` injection or TanStack Router `<ScriptOnce>`).
89
+ */
90
+ function getThemeScript(options = {}) {
91
+ const attrs = normalizeAttributes(options.attribute);
92
+ const storageKey = options.storageKey ?? "theme";
93
+ const storage = options.storage ?? "localStorage";
94
+ const enableSystem = options.enableSystem ?? true;
95
+ const enableColorScheme = options.enableColorScheme ?? true;
96
+ const themes = options.themes ? [...options.themes] : [...DEFAULT_THEMES];
97
+ const defaultTheme = options.defaultTheme ?? (enableSystem ? "system" : themes[0] ?? "light");
98
+ const forcedTheme = options.forcedTheme ?? null;
99
+ const valueMap = options.value ?? null;
100
+ const args = escapeScriptJson([
101
+ attrs,
102
+ storageKey,
103
+ storage,
104
+ defaultTheme,
105
+ forcedTheme,
106
+ themes,
107
+ valueMap ? Object.values(valueMap) : themes,
108
+ enableSystem,
109
+ enableColorScheme,
110
+ valueMap
111
+ ]);
112
+ 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})`;
113
+ }
114
+ export { COLOR_SCHEMES, COLOR_SCHEME_MEDIA, DEFAULT_STORAGE_KEY, DEFAULT_THEMES, getHtmlThemeProps, getThemeScript, isValidTheme, parseThemeCookie, resolveRequestTheme, serializeThemeCookie };
@@ -0,0 +1,475 @@
1
+ "use client";
2
+ import * as React from "react";
3
+ 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
+ // src/theme-provider.tsx
118
+ const ThemeContext = React.createContext(void 0);
119
+ const DEFAULT_THEME_LIST = [...DEFAULT_THEMES];
120
+ const isServer = typeof window === "undefined";
121
+ function getSystemTheme(media) {
122
+ return (media ?? (isServer ? void 0 : window.matchMedia("(prefers-color-scheme: dark)")))?.matches ? "dark" : "light";
123
+ }
124
+ function readStoredTheme(storage, storageKey, themes, enableSystem, storageAdapter) {
125
+ if (storageAdapter) {
126
+ try {
127
+ const fromAdapter = storageAdapter.read(storageKey);
128
+ if (isValidTheme(fromAdapter, themes, enableSystem)) return fromAdapter;
129
+ } catch {}
130
+ return;
131
+ }
132
+ if (isServer) return void 0;
133
+ if (storage === "cookie" || storage === "both") {
134
+ const fromCookie = parseThemeCookie(document.cookie, {
135
+ storageKey,
136
+ themes,
137
+ enableSystem
138
+ });
139
+ if (fromCookie) return fromCookie;
140
+ }
141
+ if (storage === "localStorage" || storage === "both") try {
142
+ const fromStorage = window.localStorage.getItem(storageKey);
143
+ if (isValidTheme(fromStorage, themes, enableSystem)) return fromStorage;
144
+ } catch {}
145
+ }
146
+ function writeStoredTheme(theme, storage, storageKey, cookieOptions, storageAdapter) {
147
+ if (storageAdapter) {
148
+ try {
149
+ storageAdapter.write(storageKey, theme);
150
+ } catch {}
151
+ return;
152
+ }
153
+ if (isServer) return;
154
+ if (storage === "localStorage" || storage === "both") try {
155
+ window.localStorage.setItem(storageKey, theme);
156
+ } catch {}
157
+ if (storage === "cookie" || storage === "both") try {
158
+ const secure = cookieOptions?.secure ?? (typeof location !== "undefined" && location.protocol === "https:");
159
+ document.cookie = serializeThemeCookie(theme, {
160
+ ...cookieOptions,
161
+ secure,
162
+ storageKey
163
+ });
164
+ } catch {}
165
+ }
166
+ function disableTransitions(nonce) {
167
+ const style = document.createElement("style");
168
+ if (nonce) style.setAttribute("nonce", nonce);
169
+ style.appendChild(document.createTextNode("*,*::before,*::after{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}"));
170
+ document.head.appendChild(style);
171
+ return () => {
172
+ window.getComputedStyle(document.body).opacity;
173
+ requestAnimationFrame(() => {
174
+ style.remove();
175
+ });
176
+ };
177
+ }
178
+ const ThemeScript = React.memo(function ThemeScript({ script, nonce, renderScript }) {
179
+ if (renderScript) return /* @__PURE__ */ jsx(Fragment, { children: renderScript(script, nonce) });
180
+ if (!isServer) return null;
181
+ return /* @__PURE__ */ jsx("script", {
182
+ nonce,
183
+ dangerouslySetInnerHTML: { __html: `${script};document.currentScript?.remove()` }
184
+ });
185
+ });
186
+ const defaultContext = {
187
+ setTheme: () => {},
188
+ themes: []
189
+ };
190
+ /**
191
+ * Read and update the active theme inside a `<ThemeProvider>`.
192
+ */
193
+ function useTheme() {
194
+ return React.useContext(ThemeContext) ?? defaultContext;
195
+ }
196
+ /**
197
+ * Root theme provider for React 18/19 (zero router coupling).
198
+ * Emits a zero-FOUC self-removing blocking script during SSR, synchronizes DOM attributes,
199
+ * OS preferences, storage/cookies/custom adapters, and cross-tab updates.
200
+ */
201
+ function ThemeProvider(props) {
202
+ if (React.useContext(ThemeContext)) return /* @__PURE__ */ jsx(Fragment, { children: props.children });
203
+ return /* @__PURE__ */ jsx(ThemeProviderInner, { ...props });
204
+ }
205
+ function ThemeProviderInner({ children, themes: themesProp = DEFAULT_THEME_LIST, defaultTheme: defaultThemeProp, forcedTheme, initialTheme, enableSystem = true, enableColorScheme = true, disableTransitionOnChange = false, viewTransition = false, enableScript = true, storageKey = DEFAULT_STORAGE_KEY, storage = "localStorage", cookieOptions, storageAdapter, syncTabs = true, onThemeChange, attribute = "class", value, nonce, renderScript }) {
206
+ const themesKey = themesProp.join("\0");
207
+ const themes = React.useMemo(() => [...themesProp], [themesKey]);
208
+ const attrsKey = Array.isArray(attribute) ? attribute.join("\0") : attribute;
209
+ const attrs = React.useMemo(() => Array.isArray(attribute) ? attribute : [attribute], [attrsKey]);
210
+ const valueKey = value ? JSON.stringify(value) : "";
211
+ const valueMap = React.useMemo(() => value, [valueKey]);
212
+ const attrValues = React.useMemo(() => valueMap ? Object.values(valueMap) : themes, [valueMap, themes]);
213
+ const cookieKey = cookieOptions ? JSON.stringify(cookieOptions) : "";
214
+ const stableCookieOptions = React.useMemo(() => cookieOptions, [cookieKey]);
215
+ const defaultTheme = defaultThemeProp ?? (enableSystem ? "system" : themes[0] ?? "light");
216
+ const normalizedInitial = isValidTheme(initialTheme, themes, enableSystem) ? initialTheme : void 0;
217
+ const [theme, setThemeState] = React.useState(normalizedInitial);
218
+ const [systemTheme, setSystemTheme] = React.useState(void 0);
219
+ const themeRef = React.useRef(theme);
220
+ themeRef.current = theme;
221
+ const onThemeChangeRef = React.useRef(onThemeChange);
222
+ onThemeChangeRef.current = onThemeChange;
223
+ const storageAdapterRef = React.useRef(storageAdapter);
224
+ storageAdapterRef.current = storageAdapter;
225
+ const channelRef = React.useRef(null);
226
+ const applyThemeToDom = React.useCallback((nextTheme, useViewTransition = false) => {
227
+ if (isServer || !nextTheme) return;
228
+ let resolved = nextTheme;
229
+ if (nextTheme === "system" && enableSystem) resolved = getSystemTheme();
230
+ const mapped = valueMap?.[resolved] ?? resolved;
231
+ const mutate = () => {
232
+ const cleanup = disableTransitionOnChange ? disableTransitions(nonce) : void 0;
233
+ const root = document.documentElement;
234
+ for (const attr of attrs) if (attr === "class") {
235
+ root.classList.remove(...attrValues);
236
+ if (mapped) root.classList.add(mapped);
237
+ } else if (mapped) root.setAttribute(attr, mapped);
238
+ else root.removeAttribute(attr);
239
+ if (enableColorScheme) {
240
+ const scheme = COLOR_SCHEMES.includes(resolved) ? resolved : COLOR_SCHEMES.includes(defaultTheme) ? defaultTheme : null;
241
+ if (scheme) root.style.colorScheme = scheme;
242
+ else root.style.removeProperty("color-scheme");
243
+ }
244
+ cleanup?.();
245
+ };
246
+ const prefersReducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
247
+ const docWithVT = document;
248
+ if (useViewTransition && !prefersReducedMotion && typeof docWithVT.startViewTransition === "function") docWithVT.startViewTransition(mutate);
249
+ else mutate();
250
+ }, [
251
+ attrs,
252
+ attrValues,
253
+ defaultTheme,
254
+ disableTransitionOnChange,
255
+ enableColorScheme,
256
+ enableSystem,
257
+ nonce,
258
+ valueMap
259
+ ]);
260
+ React.useEffect(() => {
261
+ const hydrated = readStoredTheme(storage, storageKey, themes, enableSystem, storageAdapterRef.current) ?? normalizedInitial ?? defaultTheme;
262
+ themeRef.current = hydrated;
263
+ setThemeState(hydrated);
264
+ if (enableSystem) setSystemTheme(getSystemTheme());
265
+ }, [
266
+ defaultTheme,
267
+ enableSystem,
268
+ normalizedInitial,
269
+ storage,
270
+ storageKey,
271
+ themes,
272
+ storageAdapter
273
+ ]);
274
+ const activeTheme = forcedTheme ?? theme;
275
+ React.useEffect(() => {
276
+ applyThemeToDom(activeTheme, false);
277
+ }, [activeTheme, applyThemeToDom]);
278
+ React.useEffect(() => {
279
+ if (!enableSystem) return;
280
+ const media = window.matchMedia(COLOR_SCHEME_MEDIA);
281
+ const handleMediaChange = (event) => {
282
+ const nextSystem = getSystemTheme(event);
283
+ setSystemTheme(nextSystem);
284
+ if ((forcedTheme ?? themeRef.current) === "system") applyThemeToDom("system", false);
285
+ };
286
+ media.addEventListener("change", handleMediaChange);
287
+ return () => media.removeEventListener("change", handleMediaChange);
288
+ }, [
289
+ applyThemeToDom,
290
+ enableSystem,
291
+ forcedTheme
292
+ ]);
293
+ React.useEffect(() => {
294
+ if (isServer || !syncTabs) return;
295
+ const cleanups = [];
296
+ if (!storageAdapterRef.current && (storage === "localStorage" || storage === "both")) {
297
+ const handleStorage = (event) => {
298
+ if (event.key !== storageKey) return;
299
+ const next = isValidTheme(event.newValue, themes, enableSystem) ? event.newValue : defaultTheme;
300
+ themeRef.current = next;
301
+ setThemeState(next);
302
+ };
303
+ window.addEventListener("storage", handleStorage);
304
+ cleanups.push(() => window.removeEventListener("storage", handleStorage));
305
+ }
306
+ if (typeof BroadcastChannel !== "undefined") try {
307
+ const channel = new BroadcastChannel(`voidmix-themes:${storageKey}`);
308
+ channelRef.current = channel;
309
+ const handleMessage = (event) => {
310
+ const candidate = typeof event.data === "string" ? event.data : void 0;
311
+ if (!isValidTheme(candidate, themes, enableSystem)) return;
312
+ themeRef.current = candidate;
313
+ setThemeState(candidate);
314
+ };
315
+ channel.addEventListener("message", handleMessage);
316
+ cleanups.push(() => {
317
+ channel.removeEventListener("message", handleMessage);
318
+ channel.close();
319
+ if (channelRef.current === channel) channelRef.current = null;
320
+ });
321
+ } catch {}
322
+ return () => {
323
+ for (const cleanup of cleanups) cleanup();
324
+ };
325
+ }, [
326
+ defaultTheme,
327
+ enableSystem,
328
+ storage,
329
+ storageKey,
330
+ syncTabs,
331
+ themes
332
+ ]);
333
+ const setTheme = React.useCallback((next) => {
334
+ const base = themeRef.current ?? defaultTheme;
335
+ const resolvedNext = typeof next === "function" ? next(base) : next;
336
+ if (!isValidTheme(resolvedNext, themes, enableSystem)) return;
337
+ themeRef.current = resolvedNext;
338
+ setThemeState(resolvedNext);
339
+ writeStoredTheme(resolvedNext, storage, storageKey, stableCookieOptions, storageAdapterRef.current);
340
+ if (syncTabs) try {
341
+ channelRef.current?.postMessage(resolvedNext);
342
+ } catch {}
343
+ if (!forcedTheme) applyThemeToDom(resolvedNext, viewTransition);
344
+ onThemeChangeRef.current?.(resolvedNext);
345
+ }, [
346
+ applyThemeToDom,
347
+ defaultTheme,
348
+ enableSystem,
349
+ forcedTheme,
350
+ stableCookieOptions,
351
+ storage,
352
+ storageKey,
353
+ syncTabs,
354
+ themes,
355
+ viewTransition
356
+ ]);
357
+ const script = React.useMemo(() => enableScript ? getThemeScript({
358
+ attribute: attrs,
359
+ storageKey,
360
+ storage,
361
+ defaultTheme,
362
+ forcedTheme,
363
+ themes,
364
+ enableSystem,
365
+ enableColorScheme,
366
+ value: valueMap
367
+ }) : "", [
368
+ attrs,
369
+ defaultTheme,
370
+ enableColorScheme,
371
+ enableScript,
372
+ enableSystem,
373
+ forcedTheme,
374
+ storage,
375
+ storageKey,
376
+ themes,
377
+ valueMap
378
+ ]);
379
+ const providerValue = React.useMemo(() => {
380
+ return {
381
+ theme,
382
+ setTheme,
383
+ forcedTheme,
384
+ resolvedTheme: activeTheme === "system" ? enableSystem ? systemTheme : void 0 : activeTheme,
385
+ themes: enableSystem ? [...themes, "system"] : themes,
386
+ systemTheme: enableSystem ? systemTheme : void 0
387
+ };
388
+ }, [
389
+ activeTheme,
390
+ enableSystem,
391
+ forcedTheme,
392
+ setTheme,
393
+ systemTheme,
394
+ theme,
395
+ themes
396
+ ]);
397
+ return /* @__PURE__ */ jsxs(ThemeContext.Provider, {
398
+ value: providerValue,
399
+ children: [enableScript ? /* @__PURE__ */ jsx(ThemeScript, {
400
+ script,
401
+ nonce,
402
+ renderScript
403
+ }) : null, children]
404
+ });
405
+ }
406
+ // src/theme-scope.tsx
407
+ const ThemeScopeContext = React.createContext(void 0);
408
+ /**
409
+ * Returns the nearest enclosing `<ThemeScope theme="...">` value, if any.
410
+ */
411
+ function useThemeScope() {
412
+ return React.useContext(ThemeScopeContext);
413
+ }
414
+ const DEFAULT_SCOPE_ATTRIBUTES = ["class", "data-theme"];
415
+ /**
416
+ * Creates an isolated theme scope for a subtree (e.g. a light preview card inside a dark app).
417
+ * Pairs with `@voidmix/themes/tailwind.css` so Tailwind `dark:` utilities stop at the scope boundary.
418
+ */
419
+ const ThemeScope = React.forwardRef(function ThemeScope({ theme, attribute = DEFAULT_SCOPE_ATTRIBUTES, enableColorScheme = true, value, className, style, children, ...rest }, forwardedRef) {
420
+ const { systemTheme } = useTheme();
421
+ const attrs = Array.isArray(attribute) ? attribute : [attribute];
422
+ const effectiveTheme = theme === "system" ? systemTheme : theme;
423
+ const resolved = effectiveTheme ? value?.[effectiveTheme] ?? effectiveTheme : void 0;
424
+ const classes = [];
425
+ const dataProps = {};
426
+ for (const attr of attrs) if (attr === "class") {
427
+ if (resolved) classes.push(resolved);
428
+ } else dataProps[attr] = resolved;
429
+ if (className) classes.push(className);
430
+ const mergedStyle = enableColorScheme && (effectiveTheme === "light" || effectiveTheme === "dark") ? {
431
+ colorScheme: effectiveTheme,
432
+ ...style
433
+ } : style;
434
+ return /* @__PURE__ */ jsx(ThemeScopeContext.Provider, {
435
+ value: theme,
436
+ children: /* @__PURE__ */ jsx("div", {
437
+ ref: forwardedRef,
438
+ ...rest,
439
+ ...dataProps,
440
+ className: classes.length ? classes.join(" ") : void 0,
441
+ style: mergedStyle,
442
+ children
443
+ })
444
+ });
445
+ });
446
+ // src/observe-theme.ts
447
+ const DEFAULT_OBSERVED_ATTRIBUTES = [
448
+ "class",
449
+ "data-theme",
450
+ "style"
451
+ ];
452
+ /**
453
+ * Observe theme changes affecting `element` — including ancestor attribute mutations
454
+ * (crossing ShadowRoot boundaries) as well as OS `prefers-color-scheme` changes.
455
+ * Useful for redrawing Canvas, WebGL, SVG, or chart components when the effective palette changes.
456
+ */
457
+ function observeTheme(element, onChange, options) {
458
+ const attributeFilter = options?.attributes ?? DEFAULT_OBSERVED_ATTRIBUTES;
459
+ const observer = new MutationObserver(onChange);
460
+ for (let node = element; node;) {
461
+ observer.observe(node, {
462
+ attributes: true,
463
+ attributeFilter
464
+ });
465
+ const root = node.getRootNode();
466
+ node = node.parentElement ?? (root instanceof ShadowRoot ? root.host : null);
467
+ }
468
+ const media = element.ownerDocument.defaultView?.matchMedia(COLOR_SCHEME_MEDIA);
469
+ media?.addEventListener("change", onChange);
470
+ return () => {
471
+ media?.removeEventListener("change", onChange);
472
+ observer.disconnect();
473
+ };
474
+ }
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 };
@@ -0,0 +1,12 @@
1
+ /* Scoped dark variant for Tailwind CSS v4.
2
+ * Stops at the next explicit light scope; nested dark scopes restart their own palette. */
3
+ @custom-variant dark {
4
+ @scope (.dark:not([data-theme="light"]), [data-theme="dark"]) to (.light:not([data-theme="dark"]), [data-theme="light"]) {
5
+ @slot;
6
+ }
7
+ @media (prefers-color-scheme: dark) {
8
+ @scope (:root:not(.light, .dark, [data-theme="light"], [data-theme="dark"])) to (.light, .dark, [data-theme="light"], [data-theme="dark"]) {
9
+ @slot;
10
+ }
11
+ }
12
+ }
@@ -0,0 +1,10 @@
1
+
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";
4
+ /**
5
+ * TanStack Start & TanStack Router `<ThemeProvider>`.
6
+ * Uses TanStack Router's `<ScriptOnce>` during SSR for automatic CSP nonce pickup and self-cleanup,
7
+ * falling back cleanly to a self-removing inline `<script>` if rendered outside a `RouterProvider`.
8
+ */
9
+ export declare function ThemeProvider(props: ThemeProviderProps): React.JSX.Element;
10
+ export { type Attribute, type CookieOptions, type DataAttribute, type HtmlThemeProps, type ObserveThemeOptions, type ResolveRequestThemeOptions, type ResolvedRequestTheme, type ResolvedSystemTheme, type StorageMode, type ThemeProviderProps, ThemeScope, type ThemeScopeProps, type ThemeScriptOptions, type ThemeStorageAdapter, type UseThemeProps, getHtmlThemeProps, getThemeScript, isValidTheme, observeTheme, parseThemeCookie, resolveRequestTheme, serializeThemeCookie, useTheme, useThemeScope };
@@ -0,0 +1,33 @@
1
+ "use client";
2
+ import "react";
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";
5
+ import { jsx } from "react/jsx-runtime";
6
+ // src/tanstack.tsx
7
+ const isServer = typeof window === "undefined";
8
+ function TanStackThemeScript({ script, nonce }) {
9
+ if (useRouter({ warn: false })) return /* @__PURE__ */ jsx(ScriptOnce, { children: script });
10
+ if (!isServer) return null;
11
+ return /* @__PURE__ */ jsx("script", {
12
+ nonce,
13
+ dangerouslySetInnerHTML: { __html: `${script};document.currentScript?.remove()` }
14
+ });
15
+ }
16
+ function renderTanStackScript(script, nonce) {
17
+ return /* @__PURE__ */ jsx(TanStackThemeScript, {
18
+ script,
19
+ nonce
20
+ });
21
+ }
22
+ /**
23
+ * TanStack Start & TanStack Router `<ThemeProvider>`.
24
+ * Uses TanStack Router's `<ScriptOnce>` during SSR for automatic CSP nonce pickup and self-cleanup,
25
+ * falling back cleanly to a self-removing inline `<script>` if rendered outside a `RouterProvider`.
26
+ */
27
+ function ThemeProvider(props) {
28
+ return /* @__PURE__ */ jsx(ThemeProvider$1, {
29
+ ...props,
30
+ renderScript: props.renderScript ?? renderTanStackScript
31
+ });
32
+ }
33
+ export { ThemeProvider, ThemeScope, getHtmlThemeProps, getThemeScript, isValidTheme, observeTheme, parseThemeCookie, resolveRequestTheme, serializeThemeCookie, useTheme, useThemeScope };
package/package.json CHANGED
@@ -1,6 +1,96 @@
1
1
  {
2
2
  "name": "@voidmix/themes",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
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
+ "license": "MIT",
6
+ "author": "Zack <heyloyep@gmail.com> (https://github.com/loyep)",
7
+ "homepage": "https://github.com/voidmix/themes#readme",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/voidmix/themes.git"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/voidmix/themes/issues"
14
+ },
15
+ "keywords": [
16
+ "voidmix",
17
+ "themes",
18
+ "dark-mode",
19
+ "next-themes",
20
+ "tanstack-start",
21
+ "tanstack-router",
22
+ "react",
23
+ "react-19",
24
+ "ssr",
25
+ "fouc",
26
+ "tailwind",
27
+ "scoped-theme"
28
+ ],
29
+ "publishConfig": {
30
+ "access": "public"
31
+ },
32
+ "files": [
33
+ "dist",
34
+ "LICENSE",
35
+ "README.md"
36
+ ],
37
+ "type": "module",
38
+ "sideEffects": [
39
+ "**/*.css"
40
+ ],
41
+ "types": "./dist/index.d.ts",
42
+ "exports": {
43
+ ".": {
44
+ "types": "./dist/index.d.ts",
45
+ "import": "./dist/index.js"
46
+ },
47
+ "./tanstack": {
48
+ "types": "./dist/tanstack.d.ts",
49
+ "import": "./dist/tanstack.js"
50
+ },
51
+ "./server": {
52
+ "types": "./dist/server.d.ts",
53
+ "import": "./dist/server.js"
54
+ },
55
+ "./tailwind.css": "./dist/tailwind.css"
56
+ },
57
+ "engines": {
58
+ "node": ">=20"
59
+ },
60
+ "scripts": {
61
+ "dev": "vite",
62
+ "build": "tsdown && cp src/tailwind.css dist/tailwind.css",
63
+ "build:playground": "vite build",
64
+ "typecheck": "tsc -p tsconfig.json --noEmit",
65
+ "test": "bun run build && bun tests/package.mjs",
66
+ "check": "bun run typecheck && bun run build && bun run build:playground && bun run test",
67
+ "release": "node scripts/release.mjs",
68
+ "prepack": "bun run build"
69
+ },
70
+ "peerDependencies": {
71
+ "@tanstack/react-router": "^1.0.0",
72
+ "react": ">=18.0.0",
73
+ "react-dom": ">=18.0.0"
74
+ },
75
+ "peerDependenciesMeta": {
76
+ "@tanstack/react-router": {
77
+ "optional": true
78
+ },
79
+ "react-dom": {
80
+ "optional": true
81
+ }
82
+ },
83
+ "devDependencies": {
84
+ "@tanstack/react-router": "1.170.46",
85
+ "@types/node": "^22.0.0",
86
+ "@types/react": "19.3.3",
87
+ "@types/react-dom": "19.3.0",
88
+ "@vitejs/plugin-react": "6.3.1",
89
+ "playwright": "1.65.1",
90
+ "react": "19.3.0",
91
+ "react-dom": "19.3.0",
92
+ "tsdown": "0.23.8",
93
+ "typescript": "7.0.2",
94
+ "vite": "8.4.1"
95
+ }
96
+ }