@codefast/theme 0.3.11-canary.1 → 0.3.11

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/CHANGELOG.md CHANGED
@@ -1,5 +1,31 @@
1
1
  # @codefast/theme
2
2
 
3
+ ## 0.3.11
4
+
5
+ ### Patch Changes
6
+
7
+ - [`dd5130a`](https://github.com/codefastlabs/codefast/commit/dd5130adb5649dca6773614ffda262cdde732d8f) Thanks [@thevuong](https://github.com/thevuong)! - chore(deps): downgrade @rslib/core to 0.19.1 in package.json and pnpm-lock.yaml
8
+
9
+ - [`135c6be`](https://github.com/codefastlabs/codefast/commit/135c6bed9d1bc1e96bad3173adab1bf32d74322f) Thanks [@thevuong](https://github.com/thevuong)! - chore: update linting and formatting scripts in package.json
10
+
11
+ - [`610cf7a`](https://github.com/codefastlabs/codefast/commit/610cf7a7f9b6e5b37be21e7675ea363ef1020639) Thanks [@thevuong](https://github.com/thevuong)! - fix(hooks): handle missing `navigator.clipboard.writeText` gracefully
12
+
13
+ - [`42758ab`](https://github.com/codefastlabs/codefast/commit/42758ab9d8f548ea9f4a806a7dbb7ed295fe2390) Thanks [@thevuong](https://github.com/thevuong)! - chore: update package configurations and TypeScript settings
14
+
15
+ - [`d2abc63`](https://github.com/codefastlabs/codefast/commit/d2abc636245526ec402811d8585d93684865dde6) Thanks [@thevuong](https://github.com/thevuong)! - chore(deps): update package versions and configurations
16
+
17
+ - [`3e90474`](https://github.com/codefastlabs/codefast/commit/3e90474fbbb9f8ac626c5949bfdbac2eaf1cb3e8) Thanks [@thevuong](https://github.com/thevuong)! - chore: update project configuration and dependencies
18
+
19
+ - [`92d1ed7`](https://github.com/codefastlabs/codefast/commit/92d1ed7650b19f91824cfb38ec238857a3d95876) Thanks [@thevuong](https://github.com/thevuong)! - build: replace rslib with tsdown in library packages
20
+
21
+ - [`5c09d4c`](https://github.com/codefastlabs/codefast/commit/5c09d4ce2df564dc7ac6727b00cfa668164a1af4) Thanks [@thevuong](https://github.com/thevuong)! - refactor(config): rename `check-types` to `typecheck` and update usage
22
+
23
+ ## 0.3.11-canary.2
24
+
25
+ ### Patch Changes
26
+
27
+ - [`92d1ed7`](https://github.com/codefastlabs/codefast/commit/92d1ed7650b19f91824cfb38ec238857a3d95876) Thanks [@thevuong](https://github.com/thevuong)! - build: replace rslib with tsdown in library packages
28
+
3
29
  ## 0.3.11-canary.1
4
30
 
5
31
  ### Patch Changes
@@ -1,39 +1,2 @@
1
- /**
2
- * TanStack Start adapter for theme persistence via HTTP-only cookies.
3
- *
4
- * @example
5
- * ```tsx
6
- * // __root.tsx
7
- * import { getThemeServerFn, setThemeServerFn } from '@codefast/theme/adapters/tanstack-start';
8
- * import { ThemeProvider, ThemeScript, resolveTheme } from '@codefast/theme';
9
- *
10
- * export const Route = createRootRouteWithContext<RootRouterContext>()({
11
- * loader: async () => {
12
- * const theme = await getThemeServerFn();
13
- * return { theme, resolvedTheme: resolveTheme(theme) };
14
- * },
15
- * shellComponent: RootShellComponent,
16
- * });
17
- *
18
- * function RootShellComponent({ children }: PropsWithChildren) {
19
- * const { theme, resolvedTheme } = Route.useLoaderData();
20
- *
21
- * return (
22
- * <html className={resolvedTheme} style={{ colorScheme: resolvedTheme }}>
23
- * <head>
24
- * <ThemeScript theme={theme} />
25
- * </head>
26
- * <body>
27
- * <ThemeProvider
28
- * theme={theme}
29
- * persistTheme={(value) => setThemeServerFn({ data: value })}
30
- * >
31
- * {children}
32
- * </ThemeProvider>
33
- * </body>
34
- * </html>
35
- * );
36
- * }
37
- * ```
38
- */
39
- export { createPersistTheme, getThemeServerFn, setThemeServerFn, } from "./server";
1
+ import { createPersistTheme, getThemeServerFn, setThemeServerFn } from "./server.js";
2
+ export { createPersistTheme, getThemeServerFn, setThemeServerFn };
@@ -1,4 +1,8 @@
1
- import type { Theme } from "../../types";
1
+ import { Theme } from "../../types.js";
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
  * Read the user's theme preference from cookies.
4
8
  *
@@ -12,7 +16,7 @@ import type { Theme } from "../../types";
12
16
  * const theme = await getThemeServerFn();
13
17
  * ```
14
18
  */
15
- export declare const getThemeServerFn: import("@tanstack/react-start").OptionalFetcher<undefined, undefined, "light" | "dark" | "system">;
19
+ declare const getThemeServerFn: _$_tanstack_react_start0.OptionalFetcher<undefined, undefined, "light" | "dark" | "system">;
16
20
  /**
17
21
  * Persist theme preference to an HTTP-only cookie.
18
22
  *
@@ -29,9 +33,11 @@ export declare const getThemeServerFn: import("@tanstack/react-start").OptionalF
29
33
  *
30
34
  * @see [TanStack Start Server Functions](https://tanstack.com/start/latest/docs/framework/react/server-functions)
31
35
  */
32
- export declare const setThemeServerFn: import("@tanstack/react-start").RequiredFetcher<undefined, import("zod").ZodEnum<{
33
- light: "light";
34
- dark: "dark";
35
- system: "system";
36
+ declare const setThemeServerFn: _$_tanstack_react_start0.RequiredFetcher<undefined, _$zod.ZodEnum<{
37
+ light: "light";
38
+ dark: "dark";
39
+ system: "system";
36
40
  }>, void>;
37
- export declare function createPersistTheme(): (value: Theme) => Promise<void>;
41
+ declare function createPersistTheme(): (value: Theme) => Promise<void>;
42
+ //#endregion
43
+ export { createPersistTheme, getThemeServerFn, setThemeServerFn };
@@ -1,30 +1,70 @@
1
- import { createServerFn } from "@tanstack/react-start";
2
- import { getCookie, setCookie } from "@tanstack/react-start/server";
3
1
  import { DEFAULT_THEME, THEME_STORAGE_KEY } from "../../constants.js";
4
2
  import { themeSchema } from "../../types.js";
5
- const getThemeServerFn = createServerFn().handler(()=>{
6
- const cookieTheme = getCookie(THEME_STORAGE_KEY);
7
- const validationResult = themeSchema.safeParse(cookieTheme);
8
- if (validationResult.success) return validationResult.data;
9
- return DEFAULT_THEME;
3
+ import { createServerFn } from "@tanstack/react-start";
4
+ import { getCookie, setCookie } from "@tanstack/react-start/server";
5
+ //#region src/adapters/tanstack-start/server.ts
6
+ /**
7
+ * Read the user's theme preference from cookies.
8
+ *
9
+ * Validates the cookie value using Zod schema for type safety.
10
+ * Returns {@link DEFAULT_THEME} if cookie is missing or invalid.
11
+ *
12
+ * @returns User's stored theme preference or default
13
+ *
14
+ * @example
15
+ * ```tsx
16
+ * const theme = await getThemeServerFn();
17
+ * ```
18
+ */
19
+ const getThemeServerFn = createServerFn().handler(() => {
20
+ const cookieTheme = getCookie(THEME_STORAGE_KEY);
21
+ const validationResult = themeSchema.safeParse(cookieTheme);
22
+ if (validationResult.success) return validationResult.data;
23
+ return DEFAULT_THEME;
10
24
  });
11
- const setThemeServerFn = createServerFn({
12
- method: "POST"
13
- }).inputValidator(themeSchema).handler(({ data })=>{
14
- setCookie(THEME_STORAGE_KEY, data, {
15
- httpOnly: true,
16
- maxAge: 31536000,
17
- path: "/",
18
- sameSite: "lax",
19
- secure: "production" === process.env.NODE_ENV
20
- });
25
+ /**
26
+ * Persist theme preference to an HTTP-only cookie.
27
+ *
28
+ * **Security:**
29
+ * - `httpOnly: true` - Cookie cannot be accessed from JavaScript (XSS protection)
30
+ * - `secure: true` in production - Cookie only sent over HTTPS
31
+ * - `sameSite: 'lax'` - Prevents CSRF while allowing navigation
32
+ *
33
+ * **Cookie Settings:**
34
+ * - `maxAge: 1 year` - Preference persists across sessions
35
+ * - `path: '/'` - Available to all routes
36
+ *
37
+ * @param data - Theme to persist ('light', 'dark', or 'system')
38
+ *
39
+ * @see [TanStack Start Server Functions](https://tanstack.com/start/latest/docs/framework/react/server-functions)
40
+ */
41
+ const setThemeServerFn = createServerFn({ method: "POST" }).inputValidator(themeSchema).handler(({ data }) => {
42
+ setCookie(THEME_STORAGE_KEY, data, {
43
+ httpOnly: true,
44
+ maxAge: 3600 * 24 * 365,
45
+ path: "/",
46
+ sameSite: "lax",
47
+ secure: process.env.NODE_ENV === "production"
48
+ });
21
49
  });
22
- const persistThemeHandler = async (value)=>{
23
- await setThemeServerFn({
24
- data: value
25
- });
50
+ /**
51
+ * Create a `persistTheme` function for {@link ThemeProvider}.
52
+ *
53
+ * Convenience wrapper that adapts `setThemeServerFn` to the signature
54
+ * expected by ThemeProvider's `persistTheme` prop.
55
+ *
56
+ * @returns Async function compatible with ThemeProvider's persistTheme prop
57
+ *
58
+ * @example
59
+ * ```tsx
60
+ * <ThemeProvider persistTheme={(value) => setThemeServerFn({ data: value })}>
61
+ * ```
62
+ */
63
+ const persistThemeHandler = async (value) => {
64
+ await setThemeServerFn({ data: value });
26
65
  };
27
66
  function createPersistTheme() {
28
- return persistThemeHandler;
67
+ return persistThemeHandler;
29
68
  }
69
+ //#endregion
30
70
  export { createPersistTheme, getThemeServerFn, setThemeServerFn };
@@ -1,31 +1,35 @@
1
- import type { ResolvedTheme, Theme } from "./types";
1
+ import { ResolvedTheme, Theme } from "./types.js";
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 key for persisting user's theme preference.
16
18
  *
17
19
  * The cookie is httpOnly for security (only server can read it).
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";
33
+ declare const THEME_CHANNEL = "theme-sync";
34
+ //#endregion
35
+ export { DEFAULT_RESOLVED_THEME, DEFAULT_THEME, MEDIA, THEME_CHANNEL, THEME_STORAGE_KEY };
package/dist/constants.js CHANGED
@@ -1,6 +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
+ */
1
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
+ */
2
13
  const DEFAULT_RESOLVED_THEME = "dark";
14
+ /**
15
+ * Cookie key for persisting user's theme preference.
16
+ *
17
+ * The cookie is httpOnly for security (only server can read it).
18
+ */
3
19
  const THEME_STORAGE_KEY = "ui-theme";
20
+ /**
21
+ * CSS media query for detecting dark mode preference.
22
+ * @internal
23
+ */
4
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
+ */
5
31
  const THEME_CHANNEL = "theme-sync";
32
+ //#endregion
6
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.js";
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,5 +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 {};
15
+ declare const ThemeContext: _$react.Context<ThemeContextValue>;
16
+ //#endregion
17
+ export { ThemeContext };
@@ -1,3 +1,14 @@
1
1
  import { createContext } from "react";
2
- const ThemeContext = /*#__PURE__*/ createContext(null);
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
3
14
  export { ThemeContext };
@@ -1,3 +1,4 @@
1
- export { ThemeContext } from "./context";
2
- export { ThemeProvider } from "./provider";
3
- export { useTheme } from "./use-theme";
1
+ import { ThemeContext } from "./context.js";
2
+ import { ThemeProvider } from "./provider.js";
3
+ import { useTheme } from "./use-theme.js";
4
+ export { ThemeContext, ThemeProvider, useTheme };
@@ -1,28 +1,30 @@
1
- import type { JSX, ReactNode } from "react";
2
- import type { Theme } from "../types";
1
+ import { Theme } from "../types.js";
2
+ import { JSX, ReactNode } from "react";
3
+
4
+ //#region src/core/provider.d.ts
3
5
  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/tanstack-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;
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/tanstack-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;
26
28
  }
27
29
  /**
28
30
  * Provider component for theme state management.
@@ -43,5 +45,12 @@ interface ThemeProviderProps {
43
45
  * </ThemeProvider>
44
46
  * ```
45
47
  */
46
- export declare function ThemeProvider({ children, disableTransitionOnChange, nonce, persistTheme, theme: initialTheme, }: ThemeProviderProps): JSX.Element;
47
- export {};
48
+ declare function ThemeProvider({
49
+ children,
50
+ disableTransitionOnChange,
51
+ nonce,
52
+ persistTheme,
53
+ theme: initialTheme
54
+ }: ThemeProviderProps): JSX.Element;
55
+ //#endregion
56
+ export { ThemeProvider };
@@ -1,89 +1,117 @@
1
- import { jsx } from "react/jsx-runtime";
2
- import { startTransition, useCallback, useEffect, useEffectEvent, useMemo, useOptimistic, useState, useSyncExternalStore } from "react";
3
1
  import { DEFAULT_RESOLVED_THEME, MEDIA, THEME_CHANNEL } from "../constants.js";
4
2
  import { ThemeContext } from "./context.js";
5
- import { applyTheme, disableAnimation, getSystemTheme } from "../utils/index.js";
3
+ import { applyTheme, disableAnimation } from "../utils/dom.js";
4
+ import { getSystemTheme } from "../utils/system.js";
5
+ import { startTransition, useCallback, useEffect, useEffectEvent, useMemo, useOptimistic, 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
+ */
6
14
  function subscribeToSystemTheme(callback) {
7
- const mediaQuery = window.matchMedia(MEDIA);
8
- mediaQuery.addEventListener("change", callback);
9
- return ()=>{
10
- mediaQuery.removeEventListener("change", callback);
11
- };
15
+ const mediaQuery = window.matchMedia(MEDIA);
16
+ mediaQuery.addEventListener("change", callback);
17
+ return () => {
18
+ mediaQuery.removeEventListener("change", callback);
19
+ };
12
20
  }
21
+ /**
22
+ * Get current system theme on the client.
23
+ */
13
24
  function getSystemThemeSnapshot() {
14
- return getSystemTheme();
25
+ return getSystemTheme();
15
26
  }
27
+ /**
28
+ * Server snapshot returns default theme since `matchMedia` is unavailable during SSR.
29
+ */
16
30
  function getServerSnapshot() {
17
- return DEFAULT_RESOLVED_THEME;
31
+ return DEFAULT_RESOLVED_THEME;
18
32
  }
33
+ /**
34
+ * Provider component for theme state management.
35
+ *
36
+ * **React 19 Features Used:**
37
+ * - `useOptimistic` - Immediate UI feedback while persisting theme
38
+ * - `useSyncExternalStore` - SSR-safe subscription to OS theme preference
39
+ * - `useEffectEvent` - Stable callback for cross-tab sync without effect re-runs
40
+ *
41
+ * @example
42
+ * ```tsx
43
+ * // In your root layout
44
+ * <ThemeProvider
45
+ * theme={theme}
46
+ * persistTheme={(value) => setThemeServerFn({ data: value })}
47
+ * >
48
+ * {children}
49
+ * </ThemeProvider>
50
+ * ```
51
+ */
19
52
  function ThemeProvider({ children, disableTransitionOnChange = false, nonce, persistTheme, theme: initialTheme }) {
20
- const [theme, setThemeState] = useState(initialTheme);
21
- const [optimisticTheme, setOptimisticTheme] = useOptimistic(theme);
22
- const isPending = optimisticTheme !== theme;
23
- const systemTheme = useSyncExternalStore(subscribeToSystemTheme, getSystemThemeSnapshot, getServerSnapshot);
24
- const resolvedTheme = useMemo(()=>"system" === optimisticTheme ? systemTheme : optimisticTheme, [
25
- optimisticTheme,
26
- systemTheme
27
- ]);
28
- useEffect(()=>{
29
- applyTheme(resolvedTheme);
30
- }, [
31
- resolvedTheme
32
- ]);
33
- const handleCrossTabMessage = useEffectEvent((event)=>{
34
- const newTheme = event.data;
35
- if (newTheme === theme) return;
36
- startTransition(()=>{
37
- setThemeState(newTheme);
38
- });
39
- });
40
- useEffect(()=>{
41
- const channel = new BroadcastChannel(THEME_CHANNEL);
42
- channel.addEventListener("message", handleCrossTabMessage);
43
- return ()=>{
44
- channel.removeEventListener("message", handleCrossTabMessage);
45
- channel.close();
46
- };
47
- }, []);
48
- const setTheme = useCallback(async (value)=>{
49
- await Promise.resolve();
50
- if (value === theme) return;
51
- const enable = disableTransitionOnChange ? disableAnimation(nonce) : null;
52
- startTransition(async ()=>{
53
- setOptimisticTheme(value);
54
- try {
55
- if (persistTheme) await persistTheme(value);
56
- setThemeState(value);
57
- const channel = new BroadcastChannel(THEME_CHANNEL);
58
- channel.postMessage(value);
59
- channel.close();
60
- } catch (error) {
61
- console.error("Failed to set theme:", error);
62
- } finally{
63
- enable?.();
64
- }
65
- });
66
- }, [
67
- theme,
68
- disableTransitionOnChange,
69
- nonce,
70
- setOptimisticTheme,
71
- persistTheme
72
- ]);
73
- const value = useMemo(()=>({
74
- isPending,
75
- resolvedTheme,
76
- setTheme,
77
- theme: optimisticTheme
78
- }), [
79
- optimisticTheme,
80
- resolvedTheme,
81
- setTheme,
82
- isPending
83
- ]);
84
- return /*#__PURE__*/ jsx(ThemeContext, {
85
- value: value,
86
- children: children
87
- });
53
+ const [theme, setThemeState] = useState(initialTheme);
54
+ const [optimisticTheme, setOptimisticTheme] = useOptimistic(theme);
55
+ const isPending = optimisticTheme !== theme;
56
+ const systemTheme = useSyncExternalStore(subscribeToSystemTheme, getSystemThemeSnapshot, getServerSnapshot);
57
+ const resolvedTheme = useMemo(() => optimisticTheme === "system" ? systemTheme : optimisticTheme, [optimisticTheme, systemTheme]);
58
+ useEffect(() => {
59
+ applyTheme(resolvedTheme);
60
+ }, [resolvedTheme]);
61
+ const handleCrossTabMessage = useEffectEvent((event) => {
62
+ const newTheme = event.data;
63
+ if (newTheme === theme) return;
64
+ startTransition(() => {
65
+ setThemeState(newTheme);
66
+ });
67
+ });
68
+ useEffect(() => {
69
+ const channel = new BroadcastChannel(THEME_CHANNEL);
70
+ channel.addEventListener("message", handleCrossTabMessage);
71
+ return () => {
72
+ channel.removeEventListener("message", handleCrossTabMessage);
73
+ channel.close();
74
+ };
75
+ }, []);
76
+ const setTheme = useCallback(async (value) => {
77
+ await Promise.resolve();
78
+ if (value === theme) return;
79
+ const enable = disableTransitionOnChange ? disableAnimation(nonce) : null;
80
+ startTransition(async () => {
81
+ setOptimisticTheme(value);
82
+ try {
83
+ if (persistTheme) await persistTheme(value);
84
+ setThemeState(value);
85
+ const channel = new BroadcastChannel(THEME_CHANNEL);
86
+ channel.postMessage(value);
87
+ channel.close();
88
+ } catch (error) {
89
+ console.error("Failed to set theme:", error);
90
+ } finally {
91
+ enable?.();
92
+ }
93
+ });
94
+ }, [
95
+ theme,
96
+ disableTransitionOnChange,
97
+ nonce,
98
+ setOptimisticTheme,
99
+ persistTheme
100
+ ]);
101
+ return /* @__PURE__ */ jsx(ThemeContext, {
102
+ value: useMemo(() => ({
103
+ isPending,
104
+ resolvedTheme,
105
+ setTheme,
106
+ theme: optimisticTheme
107
+ }), [
108
+ optimisticTheme,
109
+ resolvedTheme,
110
+ setTheme,
111
+ isPending
112
+ ]),
113
+ children
114
+ });
88
115
  }
116
+ //#endregion
89
117
  export { ThemeProvider };
@@ -1,4 +1,6 @@
1
- import type { ThemeContextType } from "../types";
1
+ import { ThemeContextType } from "../types.js";
2
+
3
+ //#region src/core/use-theme.d.ts
2
4
  /**
3
5
  * Hook to access theme context.
4
6
  *
@@ -25,4 +27,6 @@ import type { ThemeContextType } from "../types";
25
27
  * }
26
28
  * ```
27
29
  */
28
- export declare function useTheme(): ThemeContextType;
30
+ declare function useTheme(): ThemeContextType;
31
+ //#endregion
32
+ export { useTheme };
@@ -1,8 +1,36 @@
1
- import { use } from "react";
2
1
  import { ThemeContext } from "./context.js";
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
+ */
3
30
  function useTheme() {
4
- const value = use(ThemeContext);
5
- if (!value) throw new Error("useTheme must be used within a ThemeProvider");
6
- return value;
31
+ const value = use(ThemeContext);
32
+ if (!value) throw new Error("useTheme must be used within a ThemeProvider");
33
+ return value;
7
34
  }
35
+ //#endregion
8
36
  export { useTheme };
package/dist/index.d.ts CHANGED
@@ -1,16 +1,9 @@
1
- /**
2
- * \@codefast/theme
3
- *
4
- * React 19 theme management library with SSR support, cross-tab synchronization,
5
- * and optimistic UI updates. Supports light, dark, and system theme preferences.
6
- *
7
- * @see {@link ThemeProvider} - Main provider component
8
- * @see {@link useTheme} - Hook for consuming theme context
9
- * @see {@link ThemeScript} - FOUC prevention script
10
- */
11
- export type { ResolvedTheme, Theme, ThemeContextType } from "./types";
12
- export { themes, themeSchema } from "./types";
13
- export { DEFAULT_RESOLVED_THEME, DEFAULT_THEME, THEME_STORAGE_KEY } from "./constants";
14
- export { ThemeContext, ThemeProvider, useTheme } from "./core";
15
- export { ThemeScript } from "./script";
16
- export { applyTheme, disableAnimation, getSystemTheme, resolveTheme } from "./utils";
1
+ import { ResolvedTheme, Theme, ThemeContextType, themeSchema, themes } from "./types.js";
2
+ import { DEFAULT_RESOLVED_THEME, DEFAULT_THEME, THEME_STORAGE_KEY } from "./constants.js";
3
+ import { ThemeContext } from "./core/context.js";
4
+ import { ThemeProvider } from "./core/provider.js";
5
+ import { useTheme } from "./core/use-theme.js";
6
+ import { ThemeScript } from "./script/theme-script.js";
7
+ import { applyTheme, disableAnimation } from "./utils/dom.js";
8
+ import { getSystemTheme, resolveTheme } from "./utils/system.js";
9
+ export { DEFAULT_RESOLVED_THEME, DEFAULT_THEME, type ResolvedTheme, THEME_STORAGE_KEY, type Theme, ThemeContext, type ThemeContextType, ThemeProvider, ThemeScript, applyTheme, disableAnimation, getSystemTheme, resolveTheme, themeSchema, themes, useTheme };
package/dist/index.js CHANGED
@@ -1,6 +1,9 @@
1
- import { themeSchema, themes } from "./types.js";
2
1
  import { DEFAULT_RESOLVED_THEME, DEFAULT_THEME, THEME_STORAGE_KEY } from "./constants.js";
3
- import { ThemeContext, ThemeProvider, useTheme } from "./core/index.js";
4
- import { ThemeScript } from "./script/index.js";
5
- import { applyTheme, disableAnimation, getSystemTheme, resolveTheme } from "./utils/index.js";
2
+ import { themeSchema, themes } from "./types.js";
3
+ import { ThemeContext } from "./core/context.js";
4
+ import { applyTheme, disableAnimation } from "./utils/dom.js";
5
+ import { getSystemTheme, resolveTheme } from "./utils/system.js";
6
+ import { ThemeProvider } from "./core/provider.js";
7
+ import { useTheme } from "./core/use-theme.js";
8
+ import { ThemeScript } from "./script/theme-script.js";
6
9
  export { DEFAULT_RESOLVED_THEME, DEFAULT_THEME, THEME_STORAGE_KEY, ThemeContext, ThemeProvider, ThemeScript, applyTheme, disableAnimation, getSystemTheme, resolveTheme, themeSchema, themes, useTheme };
@@ -1 +1,2 @@
1
- export { ThemeScript } from "./theme-script";
1
+ import { ThemeScript } from "./theme-script.js";
2
+ export { ThemeScript };
@@ -1,10 +1,12 @@
1
- import type { JSX } from "react";
2
- import type { Theme } from "../types";
1
+ import { Theme } from "../types.js";
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).
@@ -28,5 +30,8 @@ interface ThemeScriptProps {
28
30
  * </head>
29
31
  * ```
30
32
  */
31
- export declare function ThemeScript({ theme }: ThemeScriptProps): JSX.Element;
32
- export {};
33
+ declare function ThemeScript({
34
+ theme
35
+ }: ThemeScriptProps): JSX.Element;
36
+ //#endregion
37
+ export { ThemeScript };
@@ -1,10 +1,29 @@
1
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. Adds the theme class to `<html>` immediately
15
+ * 3. Sets `color-scheme` for native form controls and scrollbars
16
+ *
17
+ * @example
18
+ * ```tsx
19
+ * // In __root.tsx (TanStack Start)
20
+ * <head>
21
+ * <ThemeScript theme={theme} />
22
+ * </head>
23
+ * ```
24
+ */
2
25
  function ThemeScript({ theme }) {
3
- const themeScript = `(function(){try{var theme="${theme}",resolvedTheme=theme;"system"===theme&&(resolvedTheme=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),document.documentElement.classList.add(resolvedTheme),document.documentElement.style.colorScheme=resolvedTheme}catch(error){}})()`;
4
- return /*#__PURE__*/ jsx("script", {
5
- dangerouslySetInnerHTML: {
6
- __html: themeScript
7
- }
8
- });
26
+ 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.add(resolvedTheme),document.documentElement.style.colorScheme=resolvedTheme}catch(error){}})()` } });
9
27
  }
28
+ //#endregion
10
29
  export { ThemeScript };
package/dist/types.d.ts CHANGED
@@ -1,14 +1,16 @@
1
1
  import { z } from "zod";
2
+
3
+ //#region src/types.d.ts
2
4
  /**
3
5
  * Zod schema for theme validation.
4
6
  *
5
7
  * Acts as the single source of truth for all theme-related types.
6
8
  * Valid values: 'light', 'dark', 'system'.
7
9
  */
8
- export declare const themeSchema: z.ZodEnum<{
9
- light: "light";
10
- dark: "dark";
11
- system: "system";
10
+ declare const themeSchema: z.ZodEnum<{
11
+ light: "light";
12
+ dark: "dark";
13
+ system: "system";
12
14
  }>;
13
15
  /**
14
16
  * User's theme preference.
@@ -17,19 +19,19 @@ export declare const themeSchema: z.ZodEnum<{
17
19
  * - `'dark'` - Force dark mode
18
20
  * - `'system'` - Follow OS preference
19
21
  */
20
- export type Theme = z.infer<typeof themeSchema>;
22
+ type Theme = z.infer<typeof themeSchema>;
21
23
  /**
22
24
  * Actual theme applied to the UI after resolving 'system'.
23
25
  *
24
26
  * When theme is 'system', this reflects the OS preference (light/dark).
25
27
  */
26
- export type ResolvedTheme = Exclude<Theme, "system">;
28
+ type ResolvedTheme = Exclude<Theme, "system">;
27
29
  /**
28
30
  * Array of all available theme options: `['light', 'dark', 'system']`.
29
31
  *
30
32
  * Useful for rendering theme selectors in UI components.
31
33
  */
32
- export declare const themes: ("light" | "dark" | "system")[];
34
+ declare const themes: ("light" | "dark" | "system")[];
33
35
  /**
34
36
  * Shape of the theme context value provided by ThemeProvider.
35
37
  *
@@ -38,9 +40,11 @@ export declare const themes: ("light" | "dark" | "system")[];
38
40
  * - `setTheme` - Async function to update theme (triggers optimistic update)
39
41
  * - `isPending` - True while theme change is being persisted
40
42
  */
41
- export interface ThemeContextType {
42
- isPending: boolean;
43
- resolvedTheme: ResolvedTheme;
44
- setTheme: (value: Theme) => Promise<void>;
45
- theme: Theme;
43
+ interface ThemeContextType {
44
+ isPending: boolean;
45
+ resolvedTheme: ResolvedTheme;
46
+ setTheme: (value: Theme) => Promise<void>;
47
+ theme: Theme;
46
48
  }
49
+ //#endregion
50
+ export { ResolvedTheme, Theme, ThemeContextType, themeSchema, themes };
package/dist/types.js CHANGED
@@ -1,8 +1,21 @@
1
1
  import { z } from "zod";
2
- const themeSchema = z["enum"]([
3
- "light",
4
- "dark",
5
- "system"
2
+ //#region src/types.ts
3
+ /**
4
+ * Zod schema for theme validation.
5
+ *
6
+ * Acts as the single source of truth for all theme-related types.
7
+ * Valid values: 'light', 'dark', 'system'.
8
+ */
9
+ const themeSchema = z.enum([
10
+ "light",
11
+ "dark",
12
+ "system"
6
13
  ]);
14
+ /**
15
+ * Array of all available theme options: `['light', 'dark', 'system']`.
16
+ *
17
+ * Useful for rendering theme selectors in UI components.
18
+ */
7
19
  const themes = themeSchema.options;
20
+ //#endregion
8
21
  export { themeSchema, themes };
@@ -1,4 +1,6 @@
1
- import type { ResolvedTheme } from "../types";
1
+ import { ResolvedTheme } from "../types.js";
2
+
3
+ //#region src/utils/dom.d.ts
2
4
  /**
3
5
  * Apply theme to the DOM by updating `<html>` element.
4
6
  *
@@ -8,7 +10,7 @@ import type { ResolvedTheme } from "../types";
8
10
  *
9
11
  * @param resolved - The resolved theme to apply ('light' or 'dark')
10
12
  */
11
- export declare function applyTheme(resolved: ResolvedTheme): void;
13
+ declare function applyTheme(resolved: ResolvedTheme): void;
12
14
  /**
13
15
  * Temporarily disable all CSS transitions during theme changes.
14
16
  *
@@ -25,4 +27,6 @@ export declare function applyTheme(resolved: ResolvedTheme): void;
25
27
  * enableTransitions(); // Re-enables CSS transitions
26
28
  * ```
27
29
  */
28
- export declare function disableAnimation(nonce?: string): () => void;
30
+ declare function disableAnimation(nonce?: string): () => void;
31
+ //#endregion
32
+ export { applyTheme, disableAnimation };
package/dist/utils/dom.js CHANGED
@@ -1,24 +1,50 @@
1
+ //#region src/utils/dom.ts
2
+ /**
3
+ * Apply theme to the DOM by updating `<html>` element.
4
+ *
5
+ * Updates both:
6
+ * - CSS class (for Tailwind's `dark:` variants)
7
+ * - `color-scheme` style (for native form controls and scrollbars)
8
+ *
9
+ * @param resolved - The resolved theme to apply ('light' or 'dark')
10
+ */
1
11
  function applyTheme(resolved) {
2
- const root = window.document.documentElement;
3
- root.classList.remove("light", "dark", "system");
4
- root.classList.add(resolved);
5
- root.style.colorScheme = resolved;
12
+ const root = window.document.documentElement;
13
+ root.classList.remove("light", "dark", "system");
14
+ root.classList.add(resolved);
15
+ root.style.colorScheme = resolved;
6
16
  }
17
+ /**
18
+ * Temporarily disable all CSS transitions during theme changes.
19
+ *
20
+ * Prevents jarring color animations when switching between light/dark themes.
21
+ * Respects user's `prefers-reduced-motion` preference (does nothing if enabled).
22
+ *
23
+ * @param nonce - Optional CSP nonce for the injected style element
24
+ * @returns Cleanup function to re-enable transitions. Call after theme is applied.
25
+ *
26
+ * @example
27
+ * ```tsx
28
+ * const enableTransitions = disableAnimation();
29
+ * applyTheme('dark');
30
+ * enableTransitions(); // Re-enables CSS transitions
31
+ * ```
32
+ */
7
33
  function disableAnimation(nonce) {
8
- if ("u" < typeof window) return ()=>{};
9
- const prefersReducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
10
- if (prefersReducedMotion) return ()=>{};
11
- const css = document.createElement("style");
12
- if (nonce) css.setAttribute("nonce", nonce);
13
- 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}"));
14
- document.head.append(css);
15
- return ()=>{
16
- (()=>window.getComputedStyle(document.body))();
17
- requestAnimationFrame(()=>{
18
- requestAnimationFrame(()=>{
19
- if (css.parentNode) css.remove();
20
- });
21
- });
22
- };
34
+ if (typeof window === "undefined") return () => {};
35
+ if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return () => {};
36
+ const css = document.createElement("style");
37
+ if (nonce) css.setAttribute("nonce", nonce);
38
+ 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}`));
39
+ document.head.append(css);
40
+ return () => {
41
+ window.getComputedStyle(document.body);
42
+ requestAnimationFrame(() => {
43
+ requestAnimationFrame(() => {
44
+ if (css.parentNode) css.remove();
45
+ });
46
+ });
47
+ };
23
48
  }
49
+ //#endregion
24
50
  export { applyTheme, disableAnimation };
@@ -1,2 +1,3 @@
1
- export { applyTheme, disableAnimation } from "./dom";
2
- export { getSystemTheme, resolveTheme } from "./system";
1
+ import { applyTheme, disableAnimation } from "./dom.js";
2
+ import { getSystemTheme, resolveTheme } from "./system.js";
3
+ export { applyTheme, disableAnimation, getSystemTheme, resolveTheme };
@@ -1,4 +1,6 @@
1
- import type { ResolvedTheme, Theme } from "../types";
1
+ import { ResolvedTheme, Theme } from "../types.js";
2
+
3
+ //#region src/utils/system.d.ts
2
4
  /**
3
5
  * Detect the user's OS theme preference.
4
6
  *
@@ -7,7 +9,7 @@ import type { ResolvedTheme, Theme } from "../types";
7
9
  *
8
10
  * @returns 'light' or 'dark' based on OS preference
9
11
  */
10
- export declare function getSystemTheme(): ResolvedTheme;
12
+ declare function getSystemTheme(): ResolvedTheme;
11
13
  /**
12
14
  * Resolve theme preference to actual light/dark value.
13
15
  *
@@ -18,4 +20,6 @@ export declare function getSystemTheme(): ResolvedTheme;
18
20
  * @param theme - User's theme preference
19
21
  * @returns The resolved theme to apply
20
22
  */
21
- export declare function resolveTheme(theme: Theme): ResolvedTheme;
23
+ declare function resolveTheme(theme: Theme): ResolvedTheme;
24
+ //#endregion
25
+ export { getSystemTheme, resolveTheme };
@@ -1,9 +1,29 @@
1
- import { DEFAULT_RESOLVED_THEME, MEDIA } from "../constants.js";
1
+ import { DEFAULT_RESOLVED_THEME } from "../constants.js";
2
+ //#region src/utils/system.ts
3
+ /**
4
+ * Detect the user's OS theme preference.
5
+ *
6
+ * Uses `matchMedia()` to query the `prefers-color-scheme` media feature.
7
+ * Returns {@link DEFAULT_RESOLVED_THEME} during SSR since `window` is unavailable.
8
+ *
9
+ * @returns 'light' or 'dark' based on OS preference
10
+ */
2
11
  function getSystemTheme() {
3
- if ("u" < typeof window) return DEFAULT_RESOLVED_THEME;
4
- return window.matchMedia(MEDIA).matches ? "dark" : "light";
12
+ if (typeof window === "undefined") return DEFAULT_RESOLVED_THEME;
13
+ return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
5
14
  }
15
+ /**
16
+ * Resolve theme preference to actual light/dark value.
17
+ *
18
+ * - 'light' → 'light'
19
+ * - 'dark' → 'dark'
20
+ * - 'system' → result of {@link getSystemTheme}
21
+ *
22
+ * @param theme - User's theme preference
23
+ * @returns The resolved theme to apply
24
+ */
6
25
  function resolveTheme(theme) {
7
- return "system" === theme ? getSystemTheme() : theme;
26
+ return theme === "system" ? getSystemTheme() : theme;
8
27
  }
28
+ //#endregion
9
29
  export { getSystemTheme, resolveTheme };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codefast/theme",
3
- "version": "0.3.11-canary.1",
3
+ "version": "0.3.11",
4
4
  "description": "Theme management with React 19 features - optimistic updates, cross-tab sync, and SSR support",
5
5
  "keywords": [
6
6
  "dark-mode",
@@ -98,8 +98,6 @@
98
98
  "zod": "^4.3.6"
99
99
  },
100
100
  "devDependencies": {
101
- "@rsbuild/plugin-react": "^1.4.6",
102
- "@rslib/core": "0.19.1",
103
101
  "@swc/core": "^1.15.21",
104
102
  "@swc/jest": "^0.2.39",
105
103
  "@tanstack/react-start": "^1.167.12",
@@ -111,8 +109,9 @@
111
109
  "@types/node": "^25.5.0",
112
110
  "jest": "^30.3.0",
113
111
  "jest-environment-jsdom": "^30.3.0",
112
+ "tsdown": "^0.21.7",
114
113
  "typescript": "^6.0.2",
115
- "@codefast/typescript-config": "0.3.11-canary.1"
114
+ "@codefast/typescript-config": "0.3.11"
116
115
  },
117
116
  "peerDependencies": {
118
117
  "@tanstack/react-start": "^1.0",
@@ -133,9 +132,9 @@
133
132
  }
134
133
  },
135
134
  "scripts": {
136
- "build": "rslib build",
135
+ "build": "tsdown",
137
136
  "clean": "rm -rf dist",
138
- "dev": "rslib build --watch",
137
+ "dev": "tsdown --watch --no-clean",
139
138
  "test": "jest",
140
139
  "test:coverage": "jest --coverage",
141
140
  "test:coverage:ci": "jest --coverage --ci",