@codefast/theme 0.3.13-canary.3 → 0.3.13-canary.4

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.
Files changed (58) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/adapters/tanstack-start/{server.d.ts → server.d.mts} +25 -20
  3. package/dist/adapters/tanstack-start/server.mjs +83 -0
  4. package/dist/{constants.d.ts → constants.d.mts} +10 -7
  5. package/dist/constants.mjs +33 -0
  6. package/dist/core/{context.d.ts → context.d.mts} +7 -4
  7. package/dist/core/context.mjs +14 -0
  8. package/dist/core/provider.d.mts +87 -0
  9. package/dist/core/provider.mjs +145 -0
  10. package/dist/core/{use-theme.d.ts → use-theme.d.mts} +6 -3
  11. package/dist/core/use-theme.mjs +36 -0
  12. package/dist/index.d.mts +7 -0
  13. package/dist/index.mjs +7 -0
  14. package/dist/script/{theme-script.d.ts → theme-script.d.mts} +13 -9
  15. package/dist/script/theme-script.mjs +30 -0
  16. package/dist/start.d.mts +2 -0
  17. package/dist/start.mjs +2 -0
  18. package/dist/{types.d.ts → types.d.mts} +16 -13
  19. package/dist/types.mjs +21 -0
  20. package/dist/utils/{dom.d.ts → dom.d.mts} +7 -4
  21. package/dist/utils/dom.mjs +50 -0
  22. package/dist/utils/{system.d.ts → system.d.mts} +7 -4
  23. package/dist/utils/system.mjs +36 -0
  24. package/package.json +37 -53
  25. package/dist/adapters/tanstack-start/server.d.ts.map +0 -1
  26. package/dist/adapters/tanstack-start/server.js +0 -97
  27. package/dist/constants.d.ts.map +0 -1
  28. package/dist/constants.js +0 -36
  29. package/dist/core/context.d.ts.map +0 -1
  30. package/dist/core/context.js +0 -11
  31. package/dist/core/index.d.ts +0 -4
  32. package/dist/core/index.d.ts.map +0 -1
  33. package/dist/core/index.js +0 -3
  34. package/dist/core/provider.d.ts +0 -77
  35. package/dist/core/provider.d.ts.map +0 -1
  36. package/dist/core/provider.js +0 -165
  37. package/dist/core/use-theme.d.ts.map +0 -1
  38. package/dist/core/use-theme.js +0 -38
  39. package/dist/index.d.ts +0 -17
  40. package/dist/index.d.ts.map +0 -1
  41. package/dist/index.js +0 -19
  42. package/dist/script/index.d.ts +0 -2
  43. package/dist/script/index.d.ts.map +0 -1
  44. package/dist/script/index.js +0 -1
  45. package/dist/script/theme-script.d.ts.map +0 -1
  46. package/dist/script/theme-script.js +0 -32
  47. package/dist/start.d.ts +0 -47
  48. package/dist/start.d.ts.map +0 -1
  49. package/dist/start.js +0 -46
  50. package/dist/types.d.ts.map +0 -1
  51. package/dist/types.js +0 -17
  52. package/dist/utils/dom.d.ts.map +0 -1
  53. package/dist/utils/dom.js +0 -67
  54. package/dist/utils/index.d.ts +0 -3
  55. package/dist/utils/index.d.ts.map +0 -1
  56. package/dist/utils/index.js +0 -2
  57. package/dist/utils/system.d.ts.map +0 -1
  58. package/dist/utils/system.js +0 -42
package/CHANGELOG.md CHANGED
@@ -1,5 +1,19 @@
1
1
  # @codefast/theme
2
2
 
3
+ ## 0.3.13-canary.4
4
+
5
+ ### Patch Changes
6
+
7
+ - [`93b7399`](https://github.com/codefastlabs/codefast/commit/93b7399737eb2220866338da31023f95665021a0) Thanks [@thevuong](https://github.com/thevuong)! - feat(cli): enhance CLI structure and update dependencies
8
+
9
+ - [`4248d75`](https://github.com/codefastlabs/codefast/commit/4248d75f2d547247dde937c322c2ed48d484f9e0) Thanks [@thevuong](https://github.com/thevuong)! - chore(tests): streamline test coverage commands and configurations
10
+
11
+ - [`2340231`](https://github.com/codefastlabs/codefast/commit/23402311084871d238ec50aa23061afd4b14e61e) Thanks [@thevuong](https://github.com/thevuong)! - refactor(imports): standardize import paths across applications and benchmarks
12
+
13
+ - [`35329d5`](https://github.com/codefastlabs/codefast/commit/35329d5f17682542e3ef0907d4936fa513346a72) Thanks [@thevuong](https://github.com/thevuong)! - feat(tsconfig): enforce module detection in TypeScript configuration
14
+
15
+ - [`dea6bbc`](https://github.com/codefastlabs/codefast/commit/dea6bbcebaaecc09808c42b3f93e0fbf2296eb5b) Thanks [@thevuong](https://github.com/thevuong)! - refactor(di, theme): streamline imports and remove unused files
16
+
3
17
  ## 0.3.13-canary.3
4
18
 
5
19
  ## 0.3.13-canary.2
@@ -1,24 +1,28 @@
1
- import type { ResolvedTheme, Theme } from "#types";
1
+ import { ResolvedTheme, Theme } from "../../types.mjs";
2
+ import * as _$zod from "zod";
3
+ import * as _$_tanstack_react_start0 from "@tanstack/react-start";
4
+
5
+ //#region src/adapters/tanstack-start/server.d.ts
2
6
  /**
3
7
  * Data shape returned from {@link getRootThemeServerFn} for the root route loader.
4
8
  */
5
- export interface RootThemeLoaderData {
6
- /**
7
- * Resolved `light` or `dark` from the incoming request when detectable
8
- * (e.g. `Sec-CH-Prefers-Color-Scheme`). Pass to `ThemeProvider` as `ssrSystemTheme` and to
9
- * `resolveTheme(theme, ssrSystemTheme)` on `<html>`. When the hint is absent, matches
10
- * {@link DEFAULT_RESOLVED_THEME}.
11
- */
12
- ssrSystemTheme: ResolvedTheme;
13
- /** User preference from the httpOnly cookie: `light`, `dark`, or `system`. */
14
- theme: Theme;
9
+ interface RootThemeLoaderData {
10
+ /**
11
+ * Resolved `light` or `dark` from the incoming request when detectable
12
+ * (e.g. `Sec-CH-Prefers-Color-Scheme`). Pass to `ThemeProvider` as `ssrSystemTheme` and to
13
+ * `resolveTheme(theme, ssrSystemTheme)` on `<html>`. When the hint is absent, matches
14
+ * {@link DEFAULT_RESOLVED_THEME}.
15
+ */
16
+ ssrSystemTheme: ResolvedTheme;
17
+ /** User preference from the httpOnly cookie: `light`, `dark`, or `system`. */
18
+ theme: Theme;
15
19
  }
16
20
  /**
17
21
  * Everything needed for the root shell in **one** server call (fewer loader awaits).
18
22
  *
19
23
  * In your shell: `resolveTheme(theme, ssrSystemTheme)` on `<html>`, plus `ThemeScript` and `ThemeProvider`.
20
24
  */
21
- export declare const getRootThemeServerFn: import("@tanstack/react-start").OptionalFetcher<undefined, undefined, RootThemeLoaderData>;
25
+ declare const getRootThemeServerFn: _$_tanstack_react_start0.OptionalFetcher<undefined, undefined, RootThemeLoaderData>;
22
26
  /**
23
27
  * Read the user's theme preference from cookies.
24
28
  *
@@ -32,7 +36,7 @@ export declare const getRootThemeServerFn: import("@tanstack/react-start").Optio
32
36
  * const theme = await getThemeServerFn();
33
37
  * ```
34
38
  */
35
- export declare const getThemeServerFn: import("@tanstack/react-start").OptionalFetcher<undefined, undefined, "dark" | "light" | "system">;
39
+ declare const getThemeServerFn: _$_tanstack_react_start0.OptionalFetcher<undefined, undefined, "light" | "dark" | "system">;
36
40
  /**
37
41
  * Resolved OS theme for SSR / hydration, from Client Hints when the browser sends them.
38
42
  *
@@ -41,7 +45,7 @@ export declare const getThemeServerFn: import("@tanstack/react-start").OptionalF
41
45
  *
42
46
  * Send `Accept-CH: Sec-CH-Prefers-Color-Scheme` (and `Vary`) so navigations include the hint.
43
47
  */
44
- export declare const getSsrSystemThemeServerFn: import("@tanstack/react-start").OptionalFetcher<undefined, undefined, ResolvedTheme>;
48
+ declare const getSsrSystemThemeServerFn: _$_tanstack_react_start0.OptionalFetcher<undefined, undefined, ResolvedTheme>;
45
49
  /**
46
50
  * Persist theme preference to an HTTP-only cookie.
47
51
  *
@@ -58,14 +62,15 @@ export declare const getSsrSystemThemeServerFn: import("@tanstack/react-start").
58
62
  *
59
63
  * @see [TanStack Start Server Functions](https://tanstack.com/start/latest/docs/framework/react/server-functions)
60
64
  */
61
- export declare const setThemeServerFn: import("@tanstack/react-start").RequiredFetcher<undefined, import("zod").ZodEnum<{
62
- dark: "dark";
63
- light: "light";
64
- system: "system";
65
+ declare const setThemeServerFn: _$_tanstack_react_start0.RequiredFetcher<undefined, _$zod.ZodEnum<{
66
+ light: "light";
67
+ dark: "dark";
68
+ system: "system";
65
69
  }>, void>;
66
70
  /**
67
71
  * Default {@link ThemeProvider} `persistTheme` for the Start adapter: writes the httpOnly
68
72
  * theme cookie via {@link setThemeServerFn}.
69
73
  */
70
- export declare function persistThemeCookie(value: Theme): Promise<void>;
71
- //# sourceMappingURL=server.d.ts.map
74
+ declare function persistThemeCookie(value: Theme): Promise<void>;
75
+ //#endregion
76
+ export { RootThemeLoaderData, getRootThemeServerFn, getSsrSystemThemeServerFn, getThemeServerFn, persistThemeCookie, setThemeServerFn };
@@ -0,0 +1,83 @@
1
+ import { DEFAULT_RESOLVED_THEME, DEFAULT_THEME, THEME_STORAGE_KEY } from "../../constants.mjs";
2
+ import { themeSchema } from "../../types.mjs";
3
+ import { createServerFn } from "@tanstack/react-start";
4
+ import { getCookie, getRequestHeader, setCookie } from "@tanstack/react-start/server";
5
+ //#region src/adapters/tanstack-start/server.ts
6
+ function readThemeFromCookie() {
7
+ const cookieTheme = getCookie(THEME_STORAGE_KEY);
8
+ const validationResult = themeSchema.safeParse(cookieTheme);
9
+ if (validationResult.success) return validationResult.data;
10
+ return DEFAULT_THEME;
11
+ }
12
+ function readSsrSystemThemeFromHeaders() {
13
+ const hint = getRequestHeader("Sec-CH-Prefers-Color-Scheme") ?? getRequestHeader("Prefers-Color-Scheme");
14
+ if (hint === "dark") return "dark";
15
+ if (hint === "light") return "light";
16
+ return DEFAULT_RESOLVED_THEME;
17
+ }
18
+ /**
19
+ * Everything needed for the root shell in **one** server call (fewer loader awaits).
20
+ *
21
+ * In your shell: `resolveTheme(theme, ssrSystemTheme)` on `<html>`, plus `ThemeScript` and `ThemeProvider`.
22
+ */
23
+ const getRootThemeServerFn = createServerFn().handler(() => ({
24
+ theme: readThemeFromCookie(),
25
+ ssrSystemTheme: readSsrSystemThemeFromHeaders()
26
+ }));
27
+ /**
28
+ * Read the user's theme preference from cookies.
29
+ *
30
+ * Validates the cookie value using Zod schema for type safety.
31
+ * Returns {@link DEFAULT_THEME} if cookie is missing or invalid.
32
+ *
33
+ * @returns User's stored theme preference or default
34
+ *
35
+ * @example
36
+ * ```tsx
37
+ * const theme = await getThemeServerFn();
38
+ * ```
39
+ */
40
+ const getThemeServerFn = createServerFn().handler(() => readThemeFromCookie());
41
+ /**
42
+ * Resolved OS theme for SSR / hydration, from Client Hints when the browser sends them.
43
+ *
44
+ * Mirrors client `matchMedia("(prefers-color-scheme: dark)")` when hints are present.
45
+ * Prefer {@link getRootThemeServerFn} for root loaders.
46
+ *
47
+ * Send `Accept-CH: Sec-CH-Prefers-Color-Scheme` (and `Vary`) so navigations include the hint.
48
+ */
49
+ const getSsrSystemThemeServerFn = createServerFn().handler(() => readSsrSystemThemeFromHeaders());
50
+ /**
51
+ * Persist theme preference to an HTTP-only cookie.
52
+ *
53
+ * **Security:**
54
+ * - `httpOnly: true` - Cookie cannot be accessed from JavaScript (XSS protection)
55
+ * - `secure: true` in production - Cookie only sent over HTTPS
56
+ * - `sameSite: 'lax'` - Prevents CSRF while allowing navigation
57
+ *
58
+ * **Cookie Settings:**
59
+ * - `maxAge: 1 year` - Preference persists across sessions
60
+ * - `path: '/'` - Available to all routes
61
+ *
62
+ * @param data - Theme to persist ('light', 'dark', or 'system')
63
+ *
64
+ * @see [TanStack Start Server Functions](https://tanstack.com/start/latest/docs/framework/react/server-functions)
65
+ */
66
+ const setThemeServerFn = createServerFn({ method: "POST" }).inputValidator(themeSchema).handler(({ data }) => {
67
+ setCookie(THEME_STORAGE_KEY, data, {
68
+ httpOnly: true,
69
+ maxAge: 3600 * 24 * 365,
70
+ path: "/",
71
+ sameSite: "lax",
72
+ secure: process.env.NODE_ENV === "production"
73
+ });
74
+ });
75
+ /**
76
+ * Default {@link ThemeProvider} `persistTheme` for the Start adapter: writes the httpOnly
77
+ * theme cookie via {@link setThemeServerFn}.
78
+ */
79
+ async function persistThemeCookie(value) {
80
+ await setThemeServerFn({ data: value });
81
+ }
82
+ //#endregion
83
+ export { getRootThemeServerFn, getSsrSystemThemeServerFn, getThemeServerFn, persistThemeCookie, setThemeServerFn };
@@ -1,32 +1,35 @@
1
- import type { ResolvedTheme, Theme } from "#types";
1
+ import { ResolvedTheme, Theme } from "./types.mjs";
2
+
3
+ //#region src/constants.d.ts
2
4
  /**
3
5
  * Default theme when no user preference exists.
4
6
  *
5
7
  * Set to 'system' to respect OS preference by default.
6
8
  */
7
- export declare const DEFAULT_THEME: Theme;
9
+ declare const DEFAULT_THEME: Theme;
8
10
  /**
9
11
  * Fallback theme for SSR when system preference cannot be detected.
10
12
  *
11
13
  * Used during server-side rendering since `window.matchMedia()` is unavailable.
12
14
  */
13
- export declare const DEFAULT_RESOLVED_THEME: ResolvedTheme;
15
+ declare const DEFAULT_RESOLVED_THEME: ResolvedTheme;
14
16
  /**
15
17
  * Cookie name for the httpOnly theme preference (`@codefast/theme/start`).
16
18
  *
17
19
  * Re-exported only from `@codefast/theme/constants` so custom middleware matches the adapter.
18
20
  */
19
- export declare const THEME_STORAGE_KEY = "ui-theme";
21
+ declare const THEME_STORAGE_KEY = "ui-theme";
20
22
  /**
21
23
  * CSS media query for detecting dark mode preference.
22
24
  * @internal
23
25
  */
24
- export declare const MEDIA = "(prefers-color-scheme: dark)";
26
+ declare const MEDIA = "(prefers-color-scheme: dark)";
25
27
  /**
26
28
  * BroadcastChannel name for cross-tab theme synchronization.
27
29
  *
28
30
  * Enables instant theme updates across all open browser tabs.
29
31
  * @internal
30
32
  */
31
- export declare const THEME_CHANNEL = "theme-sync";
32
- //# sourceMappingURL=constants.d.ts.map
33
+ declare const THEME_CHANNEL = "theme-sync";
34
+ //#endregion
35
+ export { DEFAULT_RESOLVED_THEME, DEFAULT_THEME, MEDIA, THEME_CHANNEL, THEME_STORAGE_KEY };
@@ -0,0 +1,33 @@
1
+ //#region src/constants.ts
2
+ /**
3
+ * Default theme when no user preference exists.
4
+ *
5
+ * Set to 'system' to respect OS preference by default.
6
+ */
7
+ const DEFAULT_THEME = "system";
8
+ /**
9
+ * Fallback theme for SSR when system preference cannot be detected.
10
+ *
11
+ * Used during server-side rendering since `window.matchMedia()` is unavailable.
12
+ */
13
+ const DEFAULT_RESOLVED_THEME = "dark";
14
+ /**
15
+ * Cookie name for the httpOnly theme preference (`@codefast/theme/start`).
16
+ *
17
+ * Re-exported only from `@codefast/theme/constants` so custom middleware matches the adapter.
18
+ */
19
+ const THEME_STORAGE_KEY = "ui-theme";
20
+ /**
21
+ * CSS media query for detecting dark mode preference.
22
+ * @internal
23
+ */
24
+ const MEDIA = "(prefers-color-scheme: dark)";
25
+ /**
26
+ * BroadcastChannel name for cross-tab theme synchronization.
27
+ *
28
+ * Enables instant theme updates across all open browser tabs.
29
+ * @internal
30
+ */
31
+ const THEME_CHANNEL = "theme-sync";
32
+ //#endregion
33
+ export { DEFAULT_RESOLVED_THEME, DEFAULT_THEME, MEDIA, THEME_CHANNEL, THEME_STORAGE_KEY };
@@ -1,4 +1,7 @@
1
- import type { ThemeContextType } from "#types";
1
+ import { ThemeContextType } from "../types.mjs";
2
+ import * as _$react from "react";
3
+
4
+ //#region src/core/context.d.ts
2
5
  type ThemeContextValue = null | ThemeContextType;
3
6
  /**
4
7
  * React context for theme state management.
@@ -9,6 +12,6 @@ type ThemeContextValue = null | ThemeContextType;
9
12
  * @see {@link ThemeProvider} - Provider component
10
13
  * @see {@link useTheme} - Consumer hook
11
14
  */
12
- export declare const ThemeContext: import("react").Context<ThemeContextValue>;
13
- export {};
14
- //# sourceMappingURL=context.d.ts.map
15
+ declare const ThemeContext: _$react.Context<ThemeContextValue>;
16
+ //#endregion
17
+ export { ThemeContext };
@@ -0,0 +1,14 @@
1
+ import { createContext } from "react";
2
+ //#region src/core/context.tsx
3
+ /**
4
+ * React context for theme state management.
5
+ *
6
+ * Provides access to current theme, resolved theme, setter function, and pending state.
7
+ * Use {@link useTheme} hook instead of consuming this context directly.
8
+ *
9
+ * @see {@link ThemeProvider} - Provider component
10
+ * @see {@link useTheme} - Consumer hook
11
+ */
12
+ const ThemeContext = createContext(null);
13
+ //#endregion
14
+ export { ThemeContext };
@@ -0,0 +1,87 @@
1
+ import { ResolvedTheme, Theme } from "../types.mjs";
2
+ import { JSX, ReactNode } from "react";
3
+
4
+ //#region src/core/provider.d.ts
5
+ interface ThemeProviderProps {
6
+ children: ReactNode;
7
+ /**
8
+ * When true, temporarily disables CSS transitions during theme changes.
9
+ * Prevents jarring color animations when switching themes.
10
+ * Default: false
11
+ */
12
+ disableTransitionOnChange?: boolean;
13
+ /**
14
+ * CSP nonce for inline styles when `disableTransitionOnChange` is enabled.
15
+ */
16
+ nonce?: string;
17
+ /**
18
+ * Async function to persist theme changes to server/storage.
19
+ *
20
+ * For TanStack Start: use `setThemeServerFn` from `@codefast/theme/start`
21
+ * For Next.js: implement a server action
22
+ */
23
+ persistTheme?: (value: Theme) => Promise<void>;
24
+ /**
25
+ * Initial theme from server (typically from cookie via loader).
26
+ */
27
+ theme: Theme;
28
+ /**
29
+ * OS light/dark guess from the SSR request (e.g. `Sec-CH-Prefers-Color-Scheme`).
30
+ *
31
+ * When the stored preference is `system`, {@link useSyncExternalStore} uses this for
32
+ * `getServerSnapshot` so the first client snapshot matches `matchMedia` and avoids a
33
+ * dark → light flip after hydration.
34
+ */
35
+ ssrSystemTheme?: ResolvedTheme;
36
+ /**
37
+ * After mount, re-read the canonical theme from the server (e.g. httpOnly cookie).
38
+ *
39
+ * Fixes **stale HTML / disk cache** on “Duplicate tab” or back-forward cache where the
40
+ * document was saved with an old `ThemeScript` / loader value while the cookie was already updated
41
+ * in another tab. Use a stable reference (e.g. `getThemeServerFn` from `@codefast/theme/start`).
42
+ */
43
+ syncThemeFromServer?: () => Promise<Theme>;
44
+ }
45
+ /**
46
+ * Provider component for theme state management.
47
+ *
48
+ * **React 19 Features Used:**
49
+ * - `useOptimistic` - Immediate UI feedback while persisting theme
50
+ * - `useSyncExternalStore` - SSR-safe subscription to OS theme preference
51
+ * - `useEffectEvent` - Stable callback for cross-tab sync without effect re-runs
52
+ *
53
+ * @param props - Component props
54
+ * @param props.children - React tree to provide context for
55
+ * @param props.theme - Initial preference from the server (cookie, loader, etc.)
56
+ * @param props.ssrSystemTheme - Best-effort `light` or `dark` from the SSR request
57
+ * (e.g. `Sec-CH-Prefers-Color-Scheme`). When preference is `system`, this value is used as
58
+ * `useSyncExternalStore`'s server snapshot so the first client snapshot matches `matchMedia`
59
+ * and avoids a post-hydration flip. Omit if unavailable; falls back to {@link DEFAULT_RESOLVED_THEME}.
60
+ * @param props.syncThemeFromServer - Optional one-shot RPC after mount to align with the cookie when SSR/HTML was stale.
61
+ * @param props.persistTheme - Optional async handler to persist preference (cookie, server action, …)
62
+ * @param props.disableTransitionOnChange - Temporarily disable CSS transitions on theme change
63
+ * @param props.nonce - CSP nonce for inline transition-blocking styles when `disableTransitionOnChange` is set
64
+ * @returns Provider element wrapping `children`
65
+ *
66
+ * @example
67
+ * ```tsx
68
+ * // In your root layout
69
+ * <ThemeProvider
70
+ * theme={theme}
71
+ * persistTheme={(value) => setThemeServerFn({ data: value })}
72
+ * >
73
+ * {children}
74
+ * </ThemeProvider>
75
+ * ```
76
+ */
77
+ declare function ThemeProvider({
78
+ children,
79
+ disableTransitionOnChange,
80
+ nonce,
81
+ persistTheme,
82
+ ssrSystemTheme,
83
+ syncThemeFromServer,
84
+ theme: initialTheme
85
+ }: ThemeProviderProps): JSX.Element;
86
+ //#endregion
87
+ export { ThemeProvider };
@@ -0,0 +1,145 @@
1
+ import { MEDIA, THEME_CHANNEL } from "../constants.mjs";
2
+ import { ThemeContext } from "./context.mjs";
3
+ import { applyTheme, disableAnimation } from "../utils/dom.mjs";
4
+ import { getSystemTheme } from "../utils/system.mjs";
5
+ import { startTransition, useCallback, useEffect, useEffectEvent, useMemo, useOptimistic, useRef, useState, useSyncExternalStore } from "react";
6
+ import { jsx } from "react/jsx-runtime";
7
+ //#region src/core/provider.tsx
8
+ /**
9
+ * Subscribe to OS theme preference changes.
10
+ *
11
+ * @param callback - Function to call when system theme changes
12
+ * @returns Cleanup function to remove the listener
13
+ */
14
+ function subscribeToSystemTheme(callback) {
15
+ const mediaQuery = window.matchMedia(MEDIA);
16
+ mediaQuery.addEventListener("change", callback);
17
+ return () => {
18
+ mediaQuery.removeEventListener("change", callback);
19
+ };
20
+ }
21
+ /**
22
+ * Get current system theme on the client.
23
+ */
24
+ function getSystemThemeSnapshot() {
25
+ return getSystemTheme();
26
+ }
27
+ /**
28
+ * Provider component for theme state management.
29
+ *
30
+ * **React 19 Features Used:**
31
+ * - `useOptimistic` - Immediate UI feedback while persisting theme
32
+ * - `useSyncExternalStore` - SSR-safe subscription to OS theme preference
33
+ * - `useEffectEvent` - Stable callback for cross-tab sync without effect re-runs
34
+ *
35
+ * @param props - Component props
36
+ * @param props.children - React tree to provide context for
37
+ * @param props.theme - Initial preference from the server (cookie, loader, etc.)
38
+ * @param props.ssrSystemTheme - Best-effort `light` or `dark` from the SSR request
39
+ * (e.g. `Sec-CH-Prefers-Color-Scheme`). When preference is `system`, this value is used as
40
+ * `useSyncExternalStore`'s server snapshot so the first client snapshot matches `matchMedia`
41
+ * and avoids a post-hydration flip. Omit if unavailable; falls back to {@link DEFAULT_RESOLVED_THEME}.
42
+ * @param props.syncThemeFromServer - Optional one-shot RPC after mount to align with the cookie when SSR/HTML was stale.
43
+ * @param props.persistTheme - Optional async handler to persist preference (cookie, server action, …)
44
+ * @param props.disableTransitionOnChange - Temporarily disable CSS transitions on theme change
45
+ * @param props.nonce - CSP nonce for inline transition-blocking styles when `disableTransitionOnChange` is set
46
+ * @returns Provider element wrapping `children`
47
+ *
48
+ * @example
49
+ * ```tsx
50
+ * // In your root layout
51
+ * <ThemeProvider
52
+ * theme={theme}
53
+ * persistTheme={(value) => setThemeServerFn({ data: value })}
54
+ * >
55
+ * {children}
56
+ * </ThemeProvider>
57
+ * ```
58
+ */
59
+ function ThemeProvider({ children, disableTransitionOnChange = false, nonce, persistTheme, ssrSystemTheme, syncThemeFromServer, theme: initialTheme }) {
60
+ const [theme, setThemeState] = useState(initialTheme);
61
+ const [optimisticTheme, setOptimisticTheme] = useOptimistic(theme);
62
+ const isPending = optimisticTheme !== theme;
63
+ const syncThemeFromServerRef = useRef(syncThemeFromServer);
64
+ syncThemeFromServerRef.current = syncThemeFromServer;
65
+ useEffect(() => {
66
+ const sync = syncThemeFromServerRef.current;
67
+ if (!sync) return;
68
+ let cancelled = false;
69
+ (async () => {
70
+ try {
71
+ const serverTheme = await sync();
72
+ if (cancelled) return;
73
+ startTransition(() => {
74
+ setThemeState((prev) => prev === serverTheme ? prev : serverTheme);
75
+ });
76
+ } catch {}
77
+ })();
78
+ return () => {
79
+ cancelled = true;
80
+ };
81
+ }, []);
82
+ const systemTheme = useSyncExternalStore(subscribeToSystemTheme, getSystemThemeSnapshot, useCallback(() => {
83
+ return ssrSystemTheme ?? "dark";
84
+ }, [ssrSystemTheme]));
85
+ const resolvedTheme = useMemo(() => optimisticTheme === "system" ? systemTheme : optimisticTheme, [optimisticTheme, systemTheme]);
86
+ useEffect(() => {
87
+ applyTheme(resolvedTheme);
88
+ }, [resolvedTheme]);
89
+ const handleCrossTabMessage = useEffectEvent((event) => {
90
+ const newTheme = event.data;
91
+ if (newTheme === theme) return;
92
+ startTransition(() => {
93
+ setThemeState(newTheme);
94
+ });
95
+ });
96
+ useEffect(() => {
97
+ const channel = new BroadcastChannel(THEME_CHANNEL);
98
+ channel.addEventListener("message", handleCrossTabMessage);
99
+ return () => {
100
+ channel.removeEventListener("message", handleCrossTabMessage);
101
+ channel.close();
102
+ };
103
+ }, []);
104
+ const setTheme = useCallback(async (value) => {
105
+ await Promise.resolve();
106
+ if (value === theme) return;
107
+ const enable = disableTransitionOnChange ? disableAnimation(nonce) : null;
108
+ startTransition(async () => {
109
+ setOptimisticTheme(value);
110
+ try {
111
+ if (persistTheme) await persistTheme(value);
112
+ setThemeState(value);
113
+ const channel = new BroadcastChannel(THEME_CHANNEL);
114
+ channel.postMessage(value);
115
+ channel.close();
116
+ } catch (error) {
117
+ console.error("Failed to set theme:", error);
118
+ } finally {
119
+ enable?.();
120
+ }
121
+ });
122
+ }, [
123
+ theme,
124
+ disableTransitionOnChange,
125
+ nonce,
126
+ setOptimisticTheme,
127
+ persistTheme
128
+ ]);
129
+ return /* @__PURE__ */ jsx(ThemeContext, {
130
+ value: useMemo(() => ({
131
+ isPending,
132
+ resolvedTheme,
133
+ setTheme,
134
+ theme: optimisticTheme
135
+ }), [
136
+ optimisticTheme,
137
+ resolvedTheme,
138
+ setTheme,
139
+ isPending
140
+ ]),
141
+ children
142
+ });
143
+ }
144
+ //#endregion
145
+ export { ThemeProvider };
@@ -1,4 +1,6 @@
1
- import type { ThemeContextType } from "#types";
1
+ import { ThemeContextType } from "../types.mjs";
2
+
3
+ //#region src/core/use-theme.d.ts
2
4
  /**
3
5
  * Hook to access theme context.
4
6
  *
@@ -25,5 +27,6 @@ import type { ThemeContextType } from "#types";
25
27
  * }
26
28
  * ```
27
29
  */
28
- export declare function useTheme(): ThemeContextType;
29
- //# sourceMappingURL=use-theme.d.ts.map
30
+ declare function useTheme(): ThemeContextType;
31
+ //#endregion
32
+ export { useTheme };
@@ -0,0 +1,36 @@
1
+ import { ThemeContext } from "./context.mjs";
2
+ import { use } from "react";
3
+ //#region src/core/use-theme.ts
4
+ /**
5
+ * Hook to access theme context.
6
+ *
7
+ * Uses React 19's `use()` API for context consumption, enabling:
8
+ * - Conditional context reading
9
+ * - Better Suspense boundary integration
10
+ *
11
+ * @returns Theme context with `theme`, `resolvedTheme`, `setTheme`, and `isPending`
12
+ * @throws Error if called outside of ThemeProvider
13
+ *
14
+ * @example
15
+ * ```tsx
16
+ * function ThemeToggle() {
17
+ * const { theme, setTheme, isPending } = useTheme();
18
+ *
19
+ * return (
20
+ * <button
21
+ * onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}
22
+ * disabled={isPending}
23
+ * >
24
+ * {theme}
25
+ * </button>
26
+ * );
27
+ * }
28
+ * ```
29
+ */
30
+ function useTheme() {
31
+ const value = use(ThemeContext);
32
+ if (!value) throw new Error("useTheme must be used within a ThemeProvider");
33
+ return value;
34
+ }
35
+ //#endregion
36
+ export { useTheme };
@@ -0,0 +1,7 @@
1
+ import { ResolvedTheme, Theme, ThemeContextType, themeSchema, themes } from "./types.mjs";
2
+ import { DEFAULT_RESOLVED_THEME, DEFAULT_THEME } from "./constants.mjs";
3
+ import { ThemeProvider } from "./core/provider.mjs";
4
+ import { useTheme } from "./core/use-theme.mjs";
5
+ import { ThemeScript } from "./script/theme-script.mjs";
6
+ import { resolveTheme } from "./utils/system.mjs";
7
+ export { DEFAULT_RESOLVED_THEME, DEFAULT_THEME, type ResolvedTheme, type Theme, type ThemeContextType, ThemeProvider, ThemeScript, resolveTheme, themeSchema, themes, useTheme };
package/dist/index.mjs ADDED
@@ -0,0 +1,7 @@
1
+ import { DEFAULT_RESOLVED_THEME, DEFAULT_THEME } from "./constants.mjs";
2
+ import { themeSchema, themes } from "./types.mjs";
3
+ import { resolveTheme } from "./utils/system.mjs";
4
+ import { ThemeProvider } from "./core/provider.mjs";
5
+ import { useTheme } from "./core/use-theme.mjs";
6
+ import { ThemeScript } from "./script/theme-script.mjs";
7
+ export { DEFAULT_RESOLVED_THEME, DEFAULT_THEME, ThemeProvider, ThemeScript, resolveTheme, themeSchema, themes, useTheme };
@@ -1,10 +1,12 @@
1
- import type { JSX } from "react";
2
- import type { Theme } from "#types";
1
+ import { Theme } from "../types.mjs";
2
+ import { JSX } from "react";
3
+
4
+ //#region src/script/theme-script.d.ts
3
5
  interface ThemeScriptProps {
4
- /**
5
- * Initial theme from server (e.g., from cookie via loader).
6
- */
7
- theme: Theme;
6
+ /**
7
+ * Initial theme from server (e.g., from cookie via loader).
8
+ */
9
+ theme: Theme;
8
10
  }
9
11
  /**
10
12
  * Inline script that prevents Flash of Unstyled Content (FOUC).
@@ -29,6 +31,8 @@ interface ThemeScriptProps {
29
31
  * </head>
30
32
  * ```
31
33
  */
32
- export declare function ThemeScript({ theme }: ThemeScriptProps): JSX.Element;
33
- export {};
34
- //# sourceMappingURL=theme-script.d.ts.map
34
+ declare function ThemeScript({
35
+ theme
36
+ }: ThemeScriptProps): JSX.Element;
37
+ //#endregion
38
+ export { ThemeScript };
@@ -0,0 +1,30 @@
1
+ import { jsx } from "react/jsx-runtime";
2
+ //#region src/script/theme-script.tsx
3
+ /**
4
+ * Inline script that prevents Flash of Unstyled Content (FOUC).
5
+ *
6
+ * **Why this is needed:**
7
+ * React hydration occurs after the browser has already painted the page.
8
+ * Without this script, users would briefly see the wrong theme before
9
+ * React takes over and applies the correct one.
10
+ *
11
+ * **How it works:**
12
+ * This script runs synchronously in the `<head>` before first paint:
13
+ * 1. Resolves 'system' to 'light' or 'dark' using `matchMedia()`
14
+ * 2. Removes prior `light` / `dark` / `system` classes on `<html>` (SSR may
15
+ * have applied the wrong resolved class for `system`, e.g. default `dark`)
16
+ * 3. Adds the resolved theme class and sets `color-scheme` for native controls
17
+ *
18
+ * @example
19
+ * ```tsx
20
+ * // In __root.tsx (TanStack Start)
21
+ * <head>
22
+ * <ThemeScript theme={theme} />
23
+ * </head>
24
+ * ```
25
+ */
26
+ function ThemeScript({ theme }) {
27
+ return /* @__PURE__ */ jsx("script", { dangerouslySetInnerHTML: { __html: `(function(){try{var theme="${theme}",resolvedTheme=theme;"system"===theme&&(resolvedTheme=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),document.documentElement.classList.remove("light","dark","system"),document.documentElement.classList.add(resolvedTheme),document.documentElement.style.colorScheme=resolvedTheme}catch(error){}})()` } });
28
+ }
29
+ //#endregion
30
+ export { ThemeScript };
@@ -0,0 +1,2 @@
1
+ import { RootThemeLoaderData, getRootThemeServerFn, getSsrSystemThemeServerFn, getThemeServerFn, persistThemeCookie, setThemeServerFn } from "./adapters/tanstack-start/server.mjs";
2
+ export { type RootThemeLoaderData, getRootThemeServerFn, getSsrSystemThemeServerFn, getThemeServerFn, persistThemeCookie, setThemeServerFn };