@codefast/theme 0.3.13-canary.3 → 0.3.13

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 +34 -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
@@ -1,77 +0,0 @@
1
- import type { JSX, ReactNode } from "react";
2
- import type { ResolvedTheme, Theme } from "#types";
3
- interface ThemeProviderProps {
4
- children: ReactNode;
5
- /**
6
- * When true, temporarily disables CSS transitions during theme changes.
7
- * Prevents jarring color animations when switching themes.
8
- * Default: false
9
- */
10
- disableTransitionOnChange?: boolean;
11
- /**
12
- * CSP nonce for inline styles when `disableTransitionOnChange` is enabled.
13
- */
14
- nonce?: string;
15
- /**
16
- * Async function to persist theme changes to server/storage.
17
- *
18
- * For TanStack Start: use `setThemeServerFn` from `@codefast/theme/start`
19
- * For Next.js: implement a server action
20
- */
21
- persistTheme?: (value: Theme) => Promise<void>;
22
- /**
23
- * Initial theme from server (typically from cookie via loader).
24
- */
25
- theme: Theme;
26
- /**
27
- * OS light/dark guess from the SSR request (e.g. `Sec-CH-Prefers-Color-Scheme`).
28
- *
29
- * When the stored preference is `system`, {@link useSyncExternalStore} uses this for
30
- * `getServerSnapshot` so the first client snapshot matches `matchMedia` and avoids a
31
- * dark → light flip after hydration.
32
- */
33
- ssrSystemTheme?: ResolvedTheme;
34
- /**
35
- * After mount, re-read the canonical theme from the server (e.g. httpOnly cookie).
36
- *
37
- * Fixes **stale HTML / disk cache** on “Duplicate tab” or back-forward cache where the
38
- * document was saved with an old `ThemeScript` / loader value while the cookie was already updated
39
- * in another tab. Use a stable reference (e.g. `getThemeServerFn` from `@codefast/theme/start`).
40
- */
41
- syncThemeFromServer?: () => Promise<Theme>;
42
- }
43
- /**
44
- * Provider component for theme state management.
45
- *
46
- * **React 19 Features Used:**
47
- * - `useOptimistic` - Immediate UI feedback while persisting theme
48
- * - `useSyncExternalStore` - SSR-safe subscription to OS theme preference
49
- * - `useEffectEvent` - Stable callback for cross-tab sync without effect re-runs
50
- *
51
- * @param props - Component props
52
- * @param props.children - React tree to provide context for
53
- * @param props.theme - Initial preference from the server (cookie, loader, etc.)
54
- * @param props.ssrSystemTheme - Best-effort `light` or `dark` from the SSR request
55
- * (e.g. `Sec-CH-Prefers-Color-Scheme`). When preference is `system`, this value is used as
56
- * `useSyncExternalStore`'s server snapshot so the first client snapshot matches `matchMedia`
57
- * and avoids a post-hydration flip. Omit if unavailable; falls back to {@link DEFAULT_RESOLVED_THEME}.
58
- * @param props.syncThemeFromServer - Optional one-shot RPC after mount to align with the cookie when SSR/HTML was stale.
59
- * @param props.persistTheme - Optional async handler to persist preference (cookie, server action, …)
60
- * @param props.disableTransitionOnChange - Temporarily disable CSS transitions on theme change
61
- * @param props.nonce - CSP nonce for inline transition-blocking styles when `disableTransitionOnChange` is set
62
- * @returns Provider element wrapping `children`
63
- *
64
- * @example
65
- * ```tsx
66
- * // In your root layout
67
- * <ThemeProvider
68
- * theme={theme}
69
- * persistTheme={(value) => setThemeServerFn({ data: value })}
70
- * >
71
- * {children}
72
- * </ThemeProvider>
73
- * ```
74
- */
75
- export declare function ThemeProvider({ children, disableTransitionOnChange, nonce, persistTheme, ssrSystemTheme, syncThemeFromServer, theme: initialTheme }: ThemeProviderProps): JSX.Element;
76
- export {};
77
- //# sourceMappingURL=provider.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../../src/core/provider.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAc5C,OAAO,KAAK,EAAE,aAAa,EAAE,KAAK,EAAoB,MAAM,QAAQ,CAAC;AAwCrE,UAAU,kBAAkB;IAC1B,QAAQ,EAAE,SAAS,CAAC;IACpB;;;;OAIG;IACH,yBAAyB,CAAC,EAAE,OAAO,CAAC;IACpC;;OAEG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;IACf;;;;;OAKG;IACH,YAAY,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAC/C;;OAEG;IACH,KAAK,EAAE,KAAK,CAAC;IACb;;;;;;OAMG;IACH,cAAc,CAAC,EAAE,aAAa,CAAC;IAC/B;;;;;;OAMG;IACH,mBAAmB,CAAC,EAAE,MAAM,OAAO,CAAC,KAAK,CAAC,CAAC;CAC5C;AAMD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,wBAAgB,aAAa,CAAC,EAC5B,QAAQ,EACR,yBAAiC,EACjC,KAAK,EACL,YAAY,EACZ,cAAc,EACd,mBAAmB,EACnB,KAAK,EAAE,YAAY,EACpB,EAAE,kBAAkB,GAAG,GAAG,CAAC,OAAO,CA4IlC"}
@@ -1,165 +0,0 @@
1
- import { jsx as _jsx } from "react/jsx-runtime";
2
- import { startTransition, useCallback, useEffect, useEffectEvent, useMemo, useOptimistic, useRef, useState, useSyncExternalStore, } from "react";
3
- import { DEFAULT_RESOLVED_THEME, MEDIA, THEME_CHANNEL } from "#constants";
4
- import { ThemeContext } from "#core/context";
5
- import { applyTheme, disableAnimation, getSystemTheme } from "#utils";
6
- /* -----------------------------------------------------------------------------
7
- * System Theme Subscription
8
- *
9
- * These functions power `useSyncExternalStore` for reactive system theme detection.
10
- * This pattern ensures SSR safety and efficient re-renders on OS preference changes.
11
- * -------------------------------------------------------------------------- */
12
- /**
13
- * Subscribe to OS theme preference changes.
14
- *
15
- * @param callback - Function to call when system theme changes
16
- * @returns Cleanup function to remove the listener
17
- */
18
- function subscribeToSystemTheme(callback) {
19
- const mediaQuery = window.matchMedia(MEDIA);
20
- mediaQuery.addEventListener("change", callback);
21
- return () => {
22
- mediaQuery.removeEventListener("change", callback);
23
- };
24
- }
25
- /**
26
- * Get current system theme on the client.
27
- */
28
- function getSystemThemeSnapshot() {
29
- return getSystemTheme();
30
- }
31
- /* -----------------------------------------------------------------------------
32
- * Component
33
- * -------------------------------------------------------------------------- */
34
- /**
35
- * Provider component for theme state management.
36
- *
37
- * **React 19 Features Used:**
38
- * - `useOptimistic` - Immediate UI feedback while persisting theme
39
- * - `useSyncExternalStore` - SSR-safe subscription to OS theme preference
40
- * - `useEffectEvent` - Stable callback for cross-tab sync without effect re-runs
41
- *
42
- * @param props - Component props
43
- * @param props.children - React tree to provide context for
44
- * @param props.theme - Initial preference from the server (cookie, loader, etc.)
45
- * @param props.ssrSystemTheme - Best-effort `light` or `dark` from the SSR request
46
- * (e.g. `Sec-CH-Prefers-Color-Scheme`). When preference is `system`, this value is used as
47
- * `useSyncExternalStore`'s server snapshot so the first client snapshot matches `matchMedia`
48
- * and avoids a post-hydration flip. Omit if unavailable; falls back to {@link DEFAULT_RESOLVED_THEME}.
49
- * @param props.syncThemeFromServer - Optional one-shot RPC after mount to align with the cookie when SSR/HTML was stale.
50
- * @param props.persistTheme - Optional async handler to persist preference (cookie, server action, …)
51
- * @param props.disableTransitionOnChange - Temporarily disable CSS transitions on theme change
52
- * @param props.nonce - CSP nonce for inline transition-blocking styles when `disableTransitionOnChange` is set
53
- * @returns Provider element wrapping `children`
54
- *
55
- * @example
56
- * ```tsx
57
- * // In your root layout
58
- * <ThemeProvider
59
- * theme={theme}
60
- * persistTheme={(value) => setThemeServerFn({ data: value })}
61
- * >
62
- * {children}
63
- * </ThemeProvider>
64
- * ```
65
- */
66
- export function ThemeProvider({ children, disableTransitionOnChange = false, nonce, persistTheme, ssrSystemTheme, syncThemeFromServer, theme: initialTheme, }) {
67
- // Actual persisted theme (source of truth after server confirms)
68
- const [theme, setThemeState] = useState(initialTheme);
69
- // Optimistic theme - immediately reflects user's intent while async operation runs
70
- // Automatically reverts to `theme` if the transition fails
71
- const [optimisticTheme, setOptimisticTheme] = useOptimistic(theme);
72
- // True when there's a pending theme change (optimistic !== actual)
73
- const isPending = optimisticTheme !== theme;
74
- const syncThemeFromServerRef = useRef(syncThemeFromServer);
75
- syncThemeFromServerRef.current = syncThemeFromServer;
76
- useEffect(() => {
77
- const sync = syncThemeFromServerRef.current;
78
- if (!sync) {
79
- return;
80
- }
81
- let cancelled = false;
82
- void (async () => {
83
- try {
84
- const serverTheme = await sync();
85
- if (cancelled) {
86
- return;
87
- }
88
- startTransition(() => {
89
- setThemeState((prev) => (prev === serverTheme ? prev : serverTheme));
90
- });
91
- }
92
- catch {
93
- /* keep SSR / loader state */
94
- }
95
- })();
96
- return () => {
97
- cancelled = true;
98
- };
99
- }, []);
100
- const getServerSnapshot = useCallback(() => {
101
- return ssrSystemTheme ?? DEFAULT_RESOLVED_THEME;
102
- }, [ssrSystemTheme]);
103
- // Subscribe to OS preference changes (SSR-safe via useSyncExternalStore)
104
- const systemTheme = useSyncExternalStore(subscribeToSystemTheme, getSystemThemeSnapshot, getServerSnapshot);
105
- // Compute the actual theme to apply: resolve 'system' to light/dark
106
- const resolvedTheme = useMemo(() => (optimisticTheme === "system" ? systemTheme : optimisticTheme), [optimisticTheme, systemTheme]);
107
- // Apply theme class and color-scheme to <html> when resolved theme changes
108
- useEffect(() => {
109
- applyTheme(resolvedTheme);
110
- }, [resolvedTheme]);
111
- // Handle cross-tab theme sync via BroadcastChannel
112
- const handleCrossTabMessage = useEffectEvent((event) => {
113
- const newTheme = event.data;
114
- if (newTheme === theme) {
115
- return;
116
- }
117
- startTransition(() => {
118
- setThemeState(newTheme);
119
- });
120
- });
121
- useEffect(() => {
122
- const channel = new BroadcastChannel(THEME_CHANNEL);
123
- channel.addEventListener("message", handleCrossTabMessage);
124
- return () => {
125
- channel.removeEventListener("message", handleCrossTabMessage);
126
- channel.close();
127
- };
128
- }, []);
129
- const setTheme = useCallback(async (value) => {
130
- await Promise.resolve();
131
- if (value === theme) {
132
- return;
133
- }
134
- // Optionally disable animations during theme switch
135
- const enable = disableTransitionOnChange ? disableAnimation(nonce) : null;
136
- // Wrap in startTransition for proper concurrent mode handling
137
- startTransition(async () => {
138
- // Show new theme immediately (optimistic update)
139
- setOptimisticTheme(value);
140
- try {
141
- // Persist to server/storage
142
- if (persistTheme) {
143
- await persistTheme(value);
144
- }
145
- // Server confirmed - commit to actual state
146
- setThemeState(value);
147
- // Notify other tabs
148
- const channel = new BroadcastChannel(THEME_CHANNEL);
149
- channel.postMessage(value);
150
- channel.close();
151
- }
152
- catch (error) {
153
- // On failure, useOptimistic automatically reverts to `theme`
154
- console.error("Failed to set theme:", error);
155
- }
156
- finally {
157
- // Re-enable animations
158
- enable?.();
159
- }
160
- });
161
- }, [theme, disableTransitionOnChange, nonce, setOptimisticTheme, persistTheme]);
162
- // Expose optimistic theme so consumers see immediate updates
163
- const value = useMemo(() => ({ isPending, resolvedTheme, setTheme, theme: optimisticTheme }), [optimisticTheme, resolvedTheme, setTheme, isPending]);
164
- return _jsx(ThemeContext, { value: value, children: children });
165
- }
@@ -1 +0,0 @@
1
- {"version":3,"file":"use-theme.d.ts","sourceRoot":"","sources":["../../src/core/use-theme.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,QAAQ,CAAC;AAQ/C;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAgB,QAAQ,IAAI,gBAAgB,CAQ3C"}
@@ -1,38 +0,0 @@
1
- import { use } from "react";
2
- import { ThemeContext } from "#core/context";
3
- /* -----------------------------------------------------------------------------
4
- * Hook
5
- * -------------------------------------------------------------------------- */
6
- /**
7
- * Hook to access theme context.
8
- *
9
- * Uses React 19's `use()` API for context consumption, enabling:
10
- * - Conditional context reading
11
- * - Better Suspense boundary integration
12
- *
13
- * @returns Theme context with `theme`, `resolvedTheme`, `setTheme`, and `isPending`
14
- * @throws Error if called outside of ThemeProvider
15
- *
16
- * @example
17
- * ```tsx
18
- * function ThemeToggle() {
19
- * const { theme, setTheme, isPending } = useTheme();
20
- *
21
- * return (
22
- * <button
23
- * onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}
24
- * disabled={isPending}
25
- * >
26
- * {theme}
27
- * </button>
28
- * );
29
- * }
30
- * ```
31
- */
32
- export function useTheme() {
33
- const value = use(ThemeContext);
34
- if (!value) {
35
- throw new Error("useTheme must be used within a ThemeProvider");
36
- }
37
- return value;
38
- }
package/dist/index.d.ts DELETED
@@ -1,17 +0,0 @@
1
- /**
2
- * \@codefast/theme
3
- *
4
- * React 19 theme management: SSR-friendly `system` resolution, cross-tab sync, optimistic updates.
5
- *
6
- * - **Root** (this module): `ThemeProvider`, `useTheme`, `ThemeScript`, `resolveTheme`, types, defaults.
7
- * - **`@codefast/theme/start`**: TanStack Start server functions + `persistThemeCookie`.
8
- * - **`@codefast/theme/utils`**: `getSystemTheme`, `applyTheme`, `disableAnimation`.
9
- * - **`@codefast/theme/core`**: `ThemeContext` for rare custom wiring.
10
- */
11
- export type { ResolvedTheme, Theme, ThemeContextType } from "#types";
12
- export { themes, themeSchema } from "#types";
13
- export { DEFAULT_RESOLVED_THEME, DEFAULT_THEME } from "#constants";
14
- export { ThemeProvider, useTheme } from "#core";
15
- export { ThemeScript } from "#script";
16
- export { resolveTheme } from "#utils/system";
17
- //# sourceMappingURL=index.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAGH,YAAY,EAAE,aAAa,EAAE,KAAK,EAAE,gBAAgB,EAAE,MAAM,QAAQ,CAAC;AACrE,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,QAAQ,CAAC;AAG7C,OAAO,EAAE,sBAAsB,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAGnE,OAAO,EAAE,aAAa,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAGhD,OAAO,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAGtC,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC"}
package/dist/index.js DELETED
@@ -1,19 +0,0 @@
1
- /**
2
- * \@codefast/theme
3
- *
4
- * React 19 theme management: SSR-friendly `system` resolution, cross-tab sync, optimistic updates.
5
- *
6
- * - **Root** (this module): `ThemeProvider`, `useTheme`, `ThemeScript`, `resolveTheme`, types, defaults.
7
- * - **`@codefast/theme/start`**: TanStack Start server functions + `persistThemeCookie`.
8
- * - **`@codefast/theme/utils`**: `getSystemTheme`, `applyTheme`, `disableAnimation`.
9
- * - **`@codefast/theme/core`**: `ThemeContext` for rare custom wiring.
10
- */
11
- export { themes, themeSchema } from "#types";
12
- // Constants
13
- export { DEFAULT_RESOLVED_THEME, DEFAULT_THEME } from "#constants";
14
- // Core (Provider, Hook — use `@codefast/theme/core` for `ThemeContext`)
15
- export { ThemeProvider, useTheme } from "#core";
16
- // Script (FOUC prevention)
17
- export { ThemeScript } from "#script";
18
- // Utilities: DOM + `getSystemTheme` live under `@codefast/theme/utils`
19
- export { resolveTheme } from "#utils/system";
@@ -1,2 +0,0 @@
1
- export { ThemeScript } from "#script/theme-script";
2
- //# sourceMappingURL=index.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/script/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC"}
@@ -1 +0,0 @@
1
- export { ThemeScript } from "#script/theme-script";
@@ -1 +0,0 @@
1
- {"version":3,"file":"theme-script.d.ts","sourceRoot":"","sources":["../../src/script/theme-script.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,OAAO,CAAC;AAEjC,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,QAAQ,CAAC;AAMpC,UAAU,gBAAgB;IACxB;;OAEG;IACH,KAAK,EAAE,KAAK,CAAC;CACd;AAMD;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,WAAW,CAAC,EAAE,KAAK,EAAE,EAAE,gBAAgB,GAAG,GAAG,CAAC,OAAO,CAKpE"}
@@ -1,32 +0,0 @@
1
- import { jsx as _jsx } from "react/jsx-runtime";
2
- /* -----------------------------------------------------------------------------
3
- * Component
4
- * -------------------------------------------------------------------------- */
5
- /**
6
- * Inline script that prevents Flash of Unstyled Content (FOUC).
7
- *
8
- * **Why this is needed:**
9
- * React hydration occurs after the browser has already painted the page.
10
- * Without this script, users would briefly see the wrong theme before
11
- * React takes over and applies the correct one.
12
- *
13
- * **How it works:**
14
- * This script runs synchronously in the `<head>` before first paint:
15
- * 1. Resolves 'system' to 'light' or 'dark' using `matchMedia()`
16
- * 2. Removes prior `light` / `dark` / `system` classes on `<html>` (SSR may
17
- * have applied the wrong resolved class for `system`, e.g. default `dark`)
18
- * 3. Adds the resolved theme class and sets `color-scheme` for native controls
19
- *
20
- * @example
21
- * ```tsx
22
- * // In __root.tsx (TanStack Start)
23
- * <head>
24
- * <ThemeScript theme={theme} />
25
- * </head>
26
- * ```
27
- */
28
- export function ThemeScript({ theme }) {
29
- // Minified FOUC prevention script
30
- const themeScript = `(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){}})()`;
31
- return _jsx("script", { dangerouslySetInnerHTML: { __html: themeScript } });
32
- }
package/dist/start.d.ts DELETED
@@ -1,47 +0,0 @@
1
- /**
2
- * TanStack Start integration: HTTP-only theme cookie + server functions.
3
- *
4
- * Peer: `@tanstack/react-start`. The app keeps full control of `<html>`, `<head>`, and `<body>`.
5
- * Use {@link getRootThemeServerFn} in the root loader, then wire `@codefast/theme` primitives
6
- * (`ThemeProvider`, `ThemeScript`, `resolveTheme`).
7
- *
8
- * @example
9
- * ```tsx
10
- * // __root.tsx
11
- * import { HeadContent, Scripts, createRootRouteWithContext } from "@tanstack/react-router";
12
- * import { getRootThemeServerFn, getThemeServerFn, persistThemeCookie } from "@codefast/theme/start";
13
- * import { ThemeProvider, ThemeScript, resolveTheme } from "@codefast/theme";
14
- *
15
- * export const Route = createRootRouteWithContext<RootRouterContext>()({
16
- * loader: async () => getRootThemeServerFn(),
17
- * shellComponent: RootShellComponent,
18
- * });
19
- *
20
- * function RootShellComponent({ children }: PropsWithChildren) {
21
- * const { theme, ssrSystemTheme } = Route.useLoaderData();
22
- * const resolvedTheme = resolveTheme(theme, ssrSystemTheme);
23
- *
24
- * return (
25
- * <html className={resolvedTheme} lang="en" style={{ colorScheme: resolvedTheme }} suppressHydrationWarning>
26
- * <head>
27
- * <HeadContent />
28
- * <ThemeScript theme={theme} />
29
- * </head>
30
- * <body>
31
- * <ThemeProvider
32
- * theme={theme}
33
- * ssrSystemTheme={ssrSystemTheme}
34
- * persistTheme={persistThemeCookie}
35
- * syncThemeFromServer={getThemeServerFn}
36
- * >
37
- * {children}
38
- * </ThemeProvider>
39
- * <Scripts />
40
- * </body>
41
- * </html>
42
- * );
43
- * }
44
- * ```
45
- */
46
- export { getRootThemeServerFn, getSsrSystemThemeServerFn, getThemeServerFn, persistThemeCookie, setThemeServerFn, type RootThemeLoaderData, } from "#adapters/tanstack-start/server";
47
- //# sourceMappingURL=start.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"start.d.ts","sourceRoot":"","sources":["../src/start.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4CG;AAEH,OAAO,EACL,oBAAoB,EACpB,yBAAyB,EACzB,gBAAgB,EAChB,kBAAkB,EAClB,gBAAgB,EAChB,KAAK,mBAAmB,GACzB,MAAM,iCAAiC,CAAC"}
package/dist/start.js DELETED
@@ -1,46 +0,0 @@
1
- /**
2
- * TanStack Start integration: HTTP-only theme cookie + server functions.
3
- *
4
- * Peer: `@tanstack/react-start`. The app keeps full control of `<html>`, `<head>`, and `<body>`.
5
- * Use {@link getRootThemeServerFn} in the root loader, then wire `@codefast/theme` primitives
6
- * (`ThemeProvider`, `ThemeScript`, `resolveTheme`).
7
- *
8
- * @example
9
- * ```tsx
10
- * // __root.tsx
11
- * import { HeadContent, Scripts, createRootRouteWithContext } from "@tanstack/react-router";
12
- * import { getRootThemeServerFn, getThemeServerFn, persistThemeCookie } from "@codefast/theme/start";
13
- * import { ThemeProvider, ThemeScript, resolveTheme } from "@codefast/theme";
14
- *
15
- * export const Route = createRootRouteWithContext<RootRouterContext>()({
16
- * loader: async () => getRootThemeServerFn(),
17
- * shellComponent: RootShellComponent,
18
- * });
19
- *
20
- * function RootShellComponent({ children }: PropsWithChildren) {
21
- * const { theme, ssrSystemTheme } = Route.useLoaderData();
22
- * const resolvedTheme = resolveTheme(theme, ssrSystemTheme);
23
- *
24
- * return (
25
- * <html className={resolvedTheme} lang="en" style={{ colorScheme: resolvedTheme }} suppressHydrationWarning>
26
- * <head>
27
- * <HeadContent />
28
- * <ThemeScript theme={theme} />
29
- * </head>
30
- * <body>
31
- * <ThemeProvider
32
- * theme={theme}
33
- * ssrSystemTheme={ssrSystemTheme}
34
- * persistTheme={persistThemeCookie}
35
- * syncThemeFromServer={getThemeServerFn}
36
- * >
37
- * {children}
38
- * </ThemeProvider>
39
- * <Scripts />
40
- * </body>
41
- * </html>
42
- * );
43
- * }
44
- * ```
45
- */
46
- export { getRootThemeServerFn, getSsrSystemThemeServerFn, getThemeServerFn, persistThemeCookie, setThemeServerFn, } from "#adapters/tanstack-start/server";
@@ -1 +0,0 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAMxB;;;;;GAKG;AACH,eAAO,MAAM,WAAW;;;;EAAsC,CAAC;AAE/D;;;;;;GAMG;AACH,MAAM,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,WAAW,CAAC,CAAC;AAEhD;;;;GAIG;AACH,MAAM,MAAM,aAAa,GAAG,OAAO,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;AAErD;;;;GAIG;AACH,eAAO,MAAM,MAAM,iCAAsB,CAAC;AAE1C;;;;;;;GAOG;AACH,MAAM,WAAW,gBAAgB;IAC/B,SAAS,EAAE,OAAO,CAAC;IACnB,aAAa,EAAE,aAAa,CAAC;IAC7B,QAAQ,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAC1C,KAAK,EAAE,KAAK,CAAC;CACd"}
package/dist/types.js DELETED
@@ -1,17 +0,0 @@
1
- import { z } from "zod";
2
- /* -----------------------------------------------------------------------------
3
- * Schema & Types
4
- * -------------------------------------------------------------------------- */
5
- /**
6
- * Zod schema for theme validation.
7
- *
8
- * Acts as the single source of truth for all theme-related types.
9
- * Valid values: 'light', 'dark', 'system'.
10
- */
11
- export const themeSchema = z.enum(["light", "dark", "system"]);
12
- /**
13
- * Array of all available theme options: `['light', 'dark', 'system']`.
14
- *
15
- * Useful for rendering theme selectors in UI components.
16
- */
17
- export const themes = themeSchema.options;
@@ -1 +0,0 @@
1
- {"version":3,"file":"dom.d.ts","sourceRoot":"","sources":["../../src/utils/dom.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AAM5C;;;;;;;;GAQG;AACH,wBAAgB,UAAU,CAAC,QAAQ,EAAE,aAAa,GAAG,IAAI,CAMxD;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM,IAAI,CA8C3D"}
package/dist/utils/dom.js DELETED
@@ -1,67 +0,0 @@
1
- /* -----------------------------------------------------------------------------
2
- * DOM Utilities
3
- * -------------------------------------------------------------------------- */
4
- /**
5
- * Apply theme to the DOM by updating `<html>` element.
6
- *
7
- * Updates both:
8
- * - CSS class (for Tailwind's `dark:` variants)
9
- * - `color-scheme` style (for native form controls and scrollbars)
10
- *
11
- * @param resolved - The resolved theme to apply ('light' or 'dark')
12
- */
13
- export function applyTheme(resolved) {
14
- const root = window.document.documentElement;
15
- root.classList.remove("light", "dark", "system");
16
- root.classList.add(resolved);
17
- root.style.colorScheme = resolved;
18
- }
19
- /**
20
- * Temporarily disable all CSS transitions during theme changes.
21
- *
22
- * Prevents jarring color animations when switching between light/dark themes.
23
- * Respects user's `prefers-reduced-motion` preference (does nothing if enabled).
24
- *
25
- * @param nonce - Optional CSP nonce for the injected style element
26
- * @returns Cleanup function to re-enable transitions. Call after theme is applied.
27
- *
28
- * @example
29
- * ```tsx
30
- * const enableTransitions = disableAnimation();
31
- * applyTheme('dark');
32
- * enableTransitions(); // Re-enables CSS transitions
33
- * ```
34
- */
35
- export function disableAnimation(nonce) {
36
- if (typeof globalThis.window === "undefined") {
37
- return () => {
38
- /* noop */
39
- };
40
- }
41
- // Respect user's motion preferences
42
- const prefersReducedMotion = globalThis.window.matchMedia("(prefers-reduced-motion: reduce)").matches;
43
- if (prefersReducedMotion) {
44
- return () => {
45
- /* noop */
46
- };
47
- }
48
- // Inject style to disable all transitions
49
- const css = document.createElement("style");
50
- if (nonce) {
51
- css.setAttribute("nonce", nonce);
52
- }
53
- css.append(document.createTextNode(`*,*::before,*::after{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}`));
54
- document.head.append(css);
55
- return () => {
56
- // Force reflow to ensure styles are applied before removing
57
- (() => window.getComputedStyle(document.body))();
58
- // Use double RAF to ensure paint happens before removing style
59
- requestAnimationFrame(() => {
60
- requestAnimationFrame(() => {
61
- if (css.parentNode) {
62
- css.remove();
63
- }
64
- });
65
- });
66
- };
67
- }
@@ -1,3 +0,0 @@
1
- export { applyTheme, disableAnimation } from "#utils/dom";
2
- export { getSystemTheme, resolveTheme } from "#utils/system";
3
- //# sourceMappingURL=index.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/utils/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAC1D,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC"}
@@ -1,2 +0,0 @@
1
- export { applyTheme, disableAnimation } from "#utils/dom";
2
- export { getSystemTheme, resolveTheme } from "#utils/system";
@@ -1 +0,0 @@
1
- {"version":3,"file":"system.d.ts","sourceRoot":"","sources":["../../src/utils/system.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,KAAK,EAAE,MAAM,QAAQ,CAAC;AAQnD;;;;;;;GAOG;AACH,wBAAgB,cAAc,IAAI,aAAa,CAM9C;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,KAAK,EAAE,cAAc,CAAC,EAAE,aAAa,GAAG,aAAa,CAUxF"}
@@ -1,42 +0,0 @@
1
- import { DEFAULT_RESOLVED_THEME, MEDIA } from "#constants";
2
- /* -----------------------------------------------------------------------------
3
- * System Theme Detection
4
- * -------------------------------------------------------------------------- */
5
- /**
6
- * Detect the user's OS theme preference.
7
- *
8
- * Uses `matchMedia()` to query the `prefers-color-scheme` media feature.
9
- * Returns {@link DEFAULT_RESOLVED_THEME} during SSR since `window` is unavailable.
10
- *
11
- * @returns 'light' or 'dark' based on OS preference
12
- */
13
- export function getSystemTheme() {
14
- if (typeof globalThis.window === "undefined") {
15
- return DEFAULT_RESOLVED_THEME;
16
- }
17
- return globalThis.window.matchMedia(MEDIA).matches ? "dark" : "light";
18
- }
19
- /**
20
- * Resolve theme preference to actual light/dark value.
21
- *
22
- * - 'light' → 'light'
23
- * - 'dark' → 'dark'
24
- * - 'system' → on the client, result of {@link getSystemTheme}; on the server,
25
- * `ssrSystemTheme` when provided, otherwise {@link DEFAULT_RESOLVED_THEME}
26
- *
27
- * @param theme - User's theme preference (`light`, `dark`, or `system`)
28
- * @param ssrSystemTheme - When `theme` is `system` and this runs during SSR (no `window`),
29
- * uses this as the resolved appearance—typically from Client Hints
30
- * (`Sec-CH-Prefers-Color-Scheme`) so `<html class>` matches the real OS preference.
31
- * Ignored for non-`system` themes and on the client (where {@link getSystemTheme} wins).
32
- * @returns The resolved theme to apply (`light` or `dark`)
33
- */
34
- export function resolveTheme(theme, ssrSystemTheme) {
35
- if (theme !== "system") {
36
- return theme;
37
- }
38
- if (typeof globalThis.window === "undefined") {
39
- return ssrSystemTheme ?? DEFAULT_RESOLVED_THEME;
40
- }
41
- return getSystemTheme();
42
- }