@codefast/theme 0.5.0-canary.0 → 0.5.0-canary.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/README.md +116 -183
  3. package/dist/appearance-context.d.mts +18 -0
  4. package/dist/appearance-context.mjs +16 -0
  5. package/dist/appearance-provider.d.mts +74 -0
  6. package/dist/appearance-provider.mjs +180 -0
  7. package/dist/appearance-script.d.mts +59 -0
  8. package/dist/appearance-script.mjs +46 -0
  9. package/dist/appearance.d.mts +60 -0
  10. package/dist/appearance.mjs +25 -0
  11. package/dist/color-scheme.d.mts +27 -0
  12. package/dist/color-scheme.mjs +32 -0
  13. package/dist/constants.d.mts +15 -14
  14. package/dist/constants.mjs +14 -13
  15. package/dist/{utils/dom.d.mts → dom.d.mts} +6 -8
  16. package/dist/{utils/dom.mjs → dom.mjs} +7 -9
  17. package/dist/index.d.mts +7 -7
  18. package/dist/index.mjs +7 -7
  19. package/dist/use-appearance.d.mts +34 -0
  20. package/dist/use-appearance.mjs +38 -0
  21. package/package.json +39 -59
  22. package/src/appearance-context.ts +22 -0
  23. package/src/appearance-provider.tsx +363 -0
  24. package/src/appearance-script.tsx +86 -0
  25. package/src/appearance.ts +66 -0
  26. package/src/color-scheme.ts +42 -0
  27. package/src/constants.ts +14 -13
  28. package/src/{utils/dom.ts → dom.ts} +8 -10
  29. package/src/index.ts +19 -16
  30. package/src/use-appearance.ts +46 -0
  31. package/dist/adapters/tanstack-start/server.d.mts +0 -88
  32. package/dist/adapters/tanstack-start/server.mjs +0 -93
  33. package/dist/adapters/tanstack-start/vite.d.mts +0 -12
  34. package/dist/adapters/tanstack-start/vite.mjs +0 -21
  35. package/dist/core/context.d.mts +0 -18
  36. package/dist/core/context.mjs +0 -16
  37. package/dist/core/provider.d.mts +0 -102
  38. package/dist/core/provider.mjs +0 -183
  39. package/dist/core/use-theme.d.mts +0 -34
  40. package/dist/core/use-theme.mjs +0 -38
  41. package/dist/script/theme-script.d.mts +0 -66
  42. package/dist/script/theme-script.mjs +0 -43
  43. package/dist/start.d.mts +0 -2
  44. package/dist/start.mjs +0 -2
  45. package/dist/types.d.mts +0 -60
  46. package/dist/types.mjs +0 -25
  47. package/dist/utils/system.d.mts +0 -34
  48. package/dist/utils/system.mjs +0 -40
  49. package/src/adapters/tanstack-start/server.ts +0 -146
  50. package/src/adapters/tanstack-start/vite.ts +0 -50
  51. package/src/core/context.tsx +0 -22
  52. package/src/core/provider.tsx +0 -364
  53. package/src/core/use-theme.ts +0 -46
  54. package/src/script/theme-script.tsx +0 -90
  55. package/src/start.ts +0 -54
  56. package/src/types.ts +0 -61
  57. package/src/utils/system.ts +0 -56
@@ -1,29 +1,27 @@
1
- //#region src/utils/dom.ts
1
+ //#region src/dom.ts
2
2
  /**
3
- * Apply color scheme to the DOM by updating `<html>` element.
3
+ * Apply a color scheme to the DOM by updating the `<html>` element.
4
4
  *
5
5
  * Updates both:
6
6
  * - CSS class (for Tailwind's `dark:` variants)
7
7
  * - `color-scheme` style (for native form controls and scrollbars)
8
8
  *
9
- * @param resolved - The resolved color scheme to apply ('light' or 'dark')
10
- *
11
9
  * @since 0.3.16-canary.0
12
10
  */
13
- function applyColorScheme(resolved) {
11
+ function applyColorScheme(colorScheme) {
14
12
  const root = window.document.documentElement;
15
13
  root.classList.remove("light", "dark", "automatic");
16
- root.classList.add(resolved);
17
- root.style.colorScheme = resolved;
14
+ root.classList.add(colorScheme);
15
+ root.style.colorScheme = colorScheme;
18
16
  }
19
17
  /**
20
- * Temporarily suppress all CSS transitions during color scheme changes.
18
+ * Temporarily suppress all CSS transitions during appearance changes.
21
19
  *
22
20
  * Prevents jarring color animations when switching between light/dark appearances.
23
21
  * Respects user's `prefers-reduced-motion` preference (does nothing if enabled).
24
22
  *
25
23
  * @param nonce - Optional CSP nonce for the injected style element
26
- * @returns Cleanup function to re-enable transitions. Call after color scheme is applied.
24
+ * @returns Cleanup function to re-enable transitions. Call after the color scheme is applied.
27
25
  *
28
26
  * @example
29
27
  * ```tsx
package/dist/index.d.mts CHANGED
@@ -1,7 +1,7 @@
1
- import { ColorScheme, ColorSchemeContextType, ResolvedColorScheme, colorSchemeSchema, colorSchemes } from "./types.mjs";
2
- import { DEFAULT_COLOR_SCHEME, DEFAULT_RESOLVED_COLOR_SCHEME } from "./constants.mjs";
3
- import { AppearanceProvider, AppearanceProviderProps } from "./core/provider.mjs";
4
- import { useColorScheme } from "./core/use-theme.mjs";
5
- import { AppearanceScript, AppearanceScriptProps } from "./script/theme-script.mjs";
6
- import { resolveColorScheme } from "./utils/system.mjs";
7
- export { AppearanceProvider, type AppearanceProviderProps, AppearanceScript, type AppearanceScriptProps, type ColorScheme, type ColorSchemeContextType, DEFAULT_COLOR_SCHEME, DEFAULT_RESOLVED_COLOR_SCHEME, type ResolvedColorScheme, colorSchemeSchema, colorSchemes, resolveColorScheme, useColorScheme };
1
+ import { Appearance, AppearanceContextType, ColorScheme, appearanceSchema, appearances } from "./appearance.mjs";
2
+ import { AppearanceProvider, AppearanceProviderProps } from "./appearance-provider.mjs";
3
+ import { AppearanceScript, AppearanceScriptProps } from "./appearance-script.mjs";
4
+ import { resolveColorScheme } from "./color-scheme.mjs";
5
+ import { DEFAULT_APPEARANCE, DEFAULT_COLOR_SCHEME } from "./constants.mjs";
6
+ import { useAppearance } from "./use-appearance.mjs";
7
+ export { type Appearance, type AppearanceContextType, AppearanceProvider, type AppearanceProviderProps, AppearanceScript, type AppearanceScriptProps, type ColorScheme, DEFAULT_APPEARANCE, DEFAULT_COLOR_SCHEME, appearanceSchema, appearances, resolveColorScheme, useAppearance };
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
- import { DEFAULT_COLOR_SCHEME, DEFAULT_RESOLVED_COLOR_SCHEME } from "./constants.mjs";
2
- import { colorSchemeSchema, colorSchemes } from "./types.mjs";
3
- import { resolveColorScheme } from "./utils/system.mjs";
4
- import { AppearanceProvider } from "./core/provider.mjs";
5
- import { useColorScheme } from "./core/use-theme.mjs";
6
- import { AppearanceScript } from "./script/theme-script.mjs";
7
- export { AppearanceProvider, AppearanceScript, DEFAULT_COLOR_SCHEME, DEFAULT_RESOLVED_COLOR_SCHEME, colorSchemeSchema, colorSchemes, resolveColorScheme, useColorScheme };
1
+ import { appearanceSchema, appearances } from "./appearance.mjs";
2
+ import { DEFAULT_APPEARANCE, DEFAULT_COLOR_SCHEME } from "./constants.mjs";
3
+ import { resolveColorScheme } from "./color-scheme.mjs";
4
+ import { AppearanceProvider } from "./appearance-provider.mjs";
5
+ import { AppearanceScript } from "./appearance-script.mjs";
6
+ import { useAppearance } from "./use-appearance.mjs";
7
+ export { AppearanceProvider, AppearanceScript, DEFAULT_APPEARANCE, DEFAULT_COLOR_SCHEME, appearanceSchema, appearances, resolveColorScheme, useAppearance };
@@ -0,0 +1,34 @@
1
+ import { AppearanceContextType } from "./appearance.mjs";
2
+
3
+ //#region src/use-appearance.d.ts
4
+ /**
5
+ * Hook to access appearance 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 Appearance context with `appearance`, `colorScheme`, `setAppearance`, and `isPending`
12
+ * @throws Error if called outside of AppearanceProvider
13
+ *
14
+ * @example
15
+ * ```tsx
16
+ * function AppearanceToggle() {
17
+ * const { appearance, setAppearance, isPending } = useAppearance();
18
+ *
19
+ * return (
20
+ * <button
21
+ * onClick={() => setAppearance(appearance === 'dark' ? 'light' : 'dark')}
22
+ * disabled={isPending}
23
+ * >
24
+ * {appearance}
25
+ * </button>
26
+ * );
27
+ * }
28
+ * ```
29
+ *
30
+ * @since 0.5.0-canary.2
31
+ */
32
+ declare function useAppearance(): AppearanceContextType;
33
+ //#endregion
34
+ export { useAppearance };
@@ -0,0 +1,38 @@
1
+ import { AppearanceContext } from "./appearance-context.mjs";
2
+ import { use } from "react";
3
+ //#region src/use-appearance.ts
4
+ /**
5
+ * Hook to access appearance 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 Appearance context with `appearance`, `colorScheme`, `setAppearance`, and `isPending`
12
+ * @throws Error if called outside of AppearanceProvider
13
+ *
14
+ * @example
15
+ * ```tsx
16
+ * function AppearanceToggle() {
17
+ * const { appearance, setAppearance, isPending } = useAppearance();
18
+ *
19
+ * return (
20
+ * <button
21
+ * onClick={() => setAppearance(appearance === 'dark' ? 'light' : 'dark')}
22
+ * disabled={isPending}
23
+ * >
24
+ * {appearance}
25
+ * </button>
26
+ * );
27
+ * }
28
+ * ```
29
+ *
30
+ * @since 0.5.0-canary.2
31
+ */
32
+ function useAppearance() {
33
+ const value = use(AppearanceContext);
34
+ if (!value) throw new Error("useAppearance must be used within an AppearanceProvider");
35
+ return value;
36
+ }
37
+ //#endregion
38
+ export { useAppearance };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@codefast/theme",
3
- "version": "0.5.0-canary.0",
4
- "description": "Theme management with React 19 features - optimistic updates, cross-tab sync, and SSR support",
3
+ "version": "0.5.0-canary.2",
4
+ "description": "Appearance management for React 19 with HIG-inspired vocabulary - optimistic updates, cross-tab sync, and FOUC-free SSR",
5
5
  "keywords": [
6
6
  "dark-mode",
7
7
  "light-mode",
@@ -56,60 +56,45 @@
56
56
  "types": "./dist/index.d.mts",
57
57
  "import": "./dist/index.mjs"
58
58
  },
59
- "./adapters/tanstack-start/server": {
60
- "source": "./src/adapters/tanstack-start/server.ts",
61
- "types": "./dist/adapters/tanstack-start/server.d.mts",
62
- "import": "./dist/adapters/tanstack-start/server.mjs"
59
+ "./appearance": {
60
+ "source": "./src/appearance.ts",
61
+ "types": "./dist/appearance.d.mts",
62
+ "import": "./dist/appearance.mjs"
63
63
  },
64
- "./constants": {
65
- "source": "./src/constants.ts",
66
- "types": "./dist/constants.d.mts",
67
- "import": "./dist/constants.mjs"
68
- },
69
- "./core/context": {
70
- "source": "./src/core/context.tsx",
71
- "types": "./dist/core/context.d.mts",
72
- "import": "./dist/core/context.mjs"
73
- },
74
- "./core/provider": {
75
- "source": "./src/core/provider.tsx",
76
- "types": "./dist/core/provider.d.mts",
77
- "import": "./dist/core/provider.mjs"
78
- },
79
- "./core/use-theme": {
80
- "source": "./src/core/use-theme.ts",
81
- "types": "./dist/core/use-theme.d.mts",
82
- "import": "./dist/core/use-theme.mjs"
64
+ "./appearance-context": {
65
+ "source": "./src/appearance-context.ts",
66
+ "types": "./dist/appearance-context.d.mts",
67
+ "import": "./dist/appearance-context.mjs"
83
68
  },
84
- "./script/theme-script": {
85
- "source": "./src/script/theme-script.tsx",
86
- "types": "./dist/script/theme-script.d.mts",
87
- "import": "./dist/script/theme-script.mjs"
69
+ "./appearance-provider": {
70
+ "source": "./src/appearance-provider.tsx",
71
+ "types": "./dist/appearance-provider.d.mts",
72
+ "import": "./dist/appearance-provider.mjs"
88
73
  },
89
- "./start": {
90
- "source": "./src/start.ts",
91
- "types": "./dist/start.d.mts",
92
- "import": "./dist/start.mjs"
74
+ "./appearance-script": {
75
+ "source": "./src/appearance-script.tsx",
76
+ "types": "./dist/appearance-script.d.mts",
77
+ "import": "./dist/appearance-script.mjs"
93
78
  },
94
- "./types": {
95
- "source": "./src/types.ts",
96
- "types": "./dist/types.d.mts",
97
- "import": "./dist/types.mjs"
79
+ "./color-scheme": {
80
+ "source": "./src/color-scheme.ts",
81
+ "types": "./dist/color-scheme.d.mts",
82
+ "import": "./dist/color-scheme.mjs"
98
83
  },
99
- "./utils/dom": {
100
- "source": "./src/utils/dom.ts",
101
- "types": "./dist/utils/dom.d.mts",
102
- "import": "./dist/utils/dom.mjs"
84
+ "./constants": {
85
+ "source": "./src/constants.ts",
86
+ "types": "./dist/constants.d.mts",
87
+ "import": "./dist/constants.mjs"
103
88
  },
104
- "./utils/system": {
105
- "source": "./src/utils/system.ts",
106
- "types": "./dist/utils/system.d.mts",
107
- "import": "./dist/utils/system.mjs"
89
+ "./dom": {
90
+ "source": "./src/dom.ts",
91
+ "types": "./dist/dom.d.mts",
92
+ "import": "./dist/dom.mjs"
108
93
  },
109
- "./vite": {
110
- "source": "./src/adapters/tanstack-start/vite.ts",
111
- "types": "./dist/adapters/tanstack-start/vite.d.mts",
112
- "import": "./dist/adapters/tanstack-start/vite.mjs"
94
+ "./use-appearance": {
95
+ "source": "./src/use-appearance.ts",
96
+ "types": "./dist/use-appearance.d.mts",
97
+ "import": "./dist/use-appearance.mjs"
113
98
  },
114
99
  "./package.json": "./package.json"
115
100
  },
@@ -120,28 +105,26 @@
120
105
  "zod": "^4.4.3"
121
106
  },
122
107
  "devDependencies": {
123
- "@tanstack/react-start": "^1.168.26",
124
108
  "@testing-library/dom": "^10.4.1",
125
109
  "@testing-library/jest-dom": "^6.9.1",
126
110
  "@testing-library/react": "^16.3.2",
127
111
  "@testing-library/user-event": "^14.6.1",
128
- "@types/node": "^26.0.1",
129
- "@typescript/native-preview": "7.0.0-dev.20260624.1",
112
+ "@types/node": "^26.1.0",
113
+ "@typescript/native-preview": "7.0.0-dev.20260702.3",
130
114
  "@vitejs/plugin-react": "^6.0.3",
131
115
  "@vitest/coverage-v8": "^4.1.9",
132
116
  "jsdom": "^29.1.1",
133
117
  "tsdown": "^0.22.3",
134
118
  "typescript": "^6.0.3",
135
- "vite": "~8.0.16",
119
+ "vite": "^8.1.3",
136
120
  "vitest": "^4.1.9",
137
- "@codefast/typescript-config": "0.5.0-canary.0"
121
+ "@codefast/typescript-config": "0.5.0-canary.2"
138
122
  },
139
123
  "peerDependencies": {
140
124
  "@types/react": ">=19.0.0",
141
125
  "@types/react-dom": ">=19.0.0",
142
126
  "react": ">=19.0.0",
143
- "react-dom": ">=19.0.0",
144
- "vite": ">=6.0.0"
127
+ "react-dom": ">=19.0.0"
145
128
  },
146
129
  "peerDependenciesMeta": {
147
130
  "@types/react": {
@@ -149,9 +132,6 @@
149
132
  },
150
133
  "@types/react-dom": {
151
134
  "optional": true
152
- },
153
- "vite": {
154
- "optional": true
155
135
  }
156
136
  },
157
137
  "engines": {
@@ -0,0 +1,22 @@
1
+ import { createContext } from "react";
2
+
3
+ import type { AppearanceContextType } from "#/appearance";
4
+
5
+ /* -----------------------------------------------------------------------------
6
+ * Context
7
+ * -------------------------------------------------------------------------- */
8
+
9
+ type AppearanceContextValue = null | AppearanceContextType;
10
+
11
+ /**
12
+ * React context for appearance state management.
13
+ *
14
+ * Provides access to the current appearance, resolved color scheme, setter function, and pending state.
15
+ * Use {@link useAppearance} hook instead of consuming this context directly.
16
+ *
17
+ * @see {@link AppearanceProvider} - Provider component
18
+ * @see {@link useAppearance} - Consumer hook
19
+ *
20
+ * @since 0.5.0-canary.2
21
+ */
22
+ export const AppearanceContext = createContext<AppearanceContextValue>(null);
@@ -0,0 +1,363 @@
1
+ import type { JSX, ReactNode } from "react";
2
+ import {
3
+ startTransition,
4
+ useCallback,
5
+ useEffect,
6
+ useEffectEvent,
7
+ useMemo,
8
+ useOptimistic,
9
+ useRef,
10
+ useState,
11
+ useSyncExternalStore,
12
+ } from "react";
13
+
14
+ import type { Appearance, AppearanceContextType, ColorScheme } from "#/appearance";
15
+ import { appearanceSchema } from "#/appearance";
16
+ import { AppearanceContext } from "#/appearance-context";
17
+ import { getSystemColorScheme } from "#/color-scheme";
18
+ import { DEFAULT_APPEARANCE, DEFAULT_COLOR_SCHEME, MEDIA, STORAGE_KEY, SYNC_CHANNEL } from "#/constants";
19
+ import { applyColorScheme, suppressTransitions } from "#/dom";
20
+
21
+ /* -----------------------------------------------------------------------------
22
+ * System Color Scheme Subscription
23
+ *
24
+ * These functions power `useSyncExternalStore` for reactive OS preference detection.
25
+ * This pattern ensures SSR safety and efficient re-renders on OS preference changes.
26
+ * -------------------------------------------------------------------------- */
27
+
28
+ /**
29
+ * Subscribe to OS color scheme preference changes.
30
+ *
31
+ * @param callback - Function to call when the OS color scheme changes
32
+ * @returns Cleanup function to remove the listener
33
+ */
34
+ function subscribeToSystemColorScheme(callback: () => void): () => void {
35
+ const mediaQuery = window.matchMedia(MEDIA);
36
+
37
+ mediaQuery.addEventListener("change", callback);
38
+
39
+ return () => {
40
+ mediaQuery.removeEventListener("change", callback);
41
+ };
42
+ }
43
+
44
+ /** SSR has no `matchMedia`; render the default until the first client snapshot takes over. */
45
+ function getServerSnapshot(): ColorScheme {
46
+ return DEFAULT_COLOR_SCHEME;
47
+ }
48
+
49
+ /**
50
+ * Safely create an appearance BroadcastChannel when supported by the environment.
51
+ */
52
+ function createAppearanceChannel(): BroadcastChannel | null {
53
+ if (typeof BroadcastChannel === "undefined") {
54
+ return null;
55
+ }
56
+
57
+ try {
58
+ return new BroadcastChannel(SYNC_CHANNEL);
59
+ } catch {
60
+ return null;
61
+ }
62
+ }
63
+
64
+ /**
65
+ * Read + validate the persisted preference from localStorage. Returns null when unavailable
66
+ * (SSR, private mode) or when the stored value is not a recognised appearance.
67
+ */
68
+ function readAppearanceFromStorage(storageKey: string): Appearance | null {
69
+ if (typeof globalThis.window === "undefined") {
70
+ return null;
71
+ }
72
+
73
+ try {
74
+ const result = appearanceSchema.safeParse(globalThis.window.localStorage.getItem(storageKey));
75
+
76
+ return result.success ? result.data : null;
77
+ } catch {
78
+ return null;
79
+ }
80
+ }
81
+
82
+ /* -----------------------------------------------------------------------------
83
+ * Props
84
+ * -------------------------------------------------------------------------- */
85
+
86
+ /**
87
+ * @since 0.5.0-canary.2
88
+ */
89
+ export type AppearanceProviderProps = {
90
+ readonly children: ReactNode;
91
+ /**
92
+ * When true, temporarily suppresses CSS transitions during appearance changes.
93
+ * Prevents jarring color animations when switching appearances.
94
+ * Default: false
95
+ */
96
+ readonly disableTransition?: boolean;
97
+ /**
98
+ * CSP nonce for inline styles when `disableTransition` is enabled.
99
+ */
100
+ readonly nonce?: string;
101
+ /**
102
+ * Custom async persistence for appearance changes; replaces the `localStorage` auto-persist.
103
+ */
104
+ readonly persistAppearance?: (value: Appearance) => Promise<void>;
105
+ /**
106
+ * Callback invoked when `persistAppearance` rejects.
107
+ */
108
+ readonly onPersistError?: (error: unknown, attemptedAppearance: Appearance) => void;
109
+ /**
110
+ * Fallback preference when storage has no valid entry — also what SSR renders.
111
+ * Defaults to {@link DEFAULT_APPEARANCE}.
112
+ */
113
+ readonly appearance?: Appearance;
114
+ /**
115
+ * `localStorage` key the preference is restored from and persisted under.
116
+ * Defaults to {@link STORAGE_KEY}; pair with `<AppearanceScript>` using the **same key**.
117
+ *
118
+ * The provider reads the stored value in its initial client render (so the first paint already
119
+ * matches the preference — no flash, no post-mount settle), auto-persists changes to
120
+ * `localStorage` (unless {@link persistAppearance} is also given, which then wins), and syncs
121
+ * across tabs via the `storage` event.
122
+ *
123
+ * @remarks SSR has no `localStorage`, so the server renders the {@link AppearanceProviderProps.appearance}
124
+ * prop. For a returning visitor whose stored preference differs, components that render
125
+ * preference-dependent markup hydrate-reconcile once; gate them behind a mounted flag to avoid that.
126
+ */
127
+ readonly storageKey?: string;
128
+ };
129
+
130
+ /* -----------------------------------------------------------------------------
131
+ * Component
132
+ * -------------------------------------------------------------------------- */
133
+
134
+ /**
135
+ * Provider component for appearance state management.
136
+ *
137
+ * **React 19 Features Used:**
138
+ * - `useOptimistic` - Immediate UI feedback while persisting the preference
139
+ * - `useSyncExternalStore` - SSR-safe subscription to the OS color scheme preference
140
+ * - `useEffectEvent` - Stable callback for cross-tab sync without effect re-runs
141
+ *
142
+ * @example
143
+ * ```tsx
144
+ * // In your root layout — pair with <AppearanceScript /> using the same storage key
145
+ * <AppearanceProvider>{children}</AppearanceProvider>
146
+ * ```
147
+ *
148
+ * @since 0.5.0-canary.2
149
+ */
150
+ export function AppearanceProvider({
151
+ children,
152
+ disableTransition = false,
153
+ nonce,
154
+ onPersistError,
155
+ persistAppearance,
156
+ storageKey = STORAGE_KEY,
157
+ appearance: initialAppearance = DEFAULT_APPEARANCE,
158
+ }: AppearanceProviderProps): JSX.Element {
159
+ // Runtime guard against invalid values bypassing TypeScript (e.g. raw API strings)
160
+ const safeInitialAppearance = appearanceSchema.safeParse(initialAppearance).success
161
+ ? initialAppearance
162
+ : DEFAULT_APPEARANCE;
163
+
164
+ // Actual persisted appearance. Read localStorage in the initializer so the first client render
165
+ // already matches what AppearanceScript applied pre-paint (no flash, no post-mount settle). SSR has
166
+ // no localStorage, so the server renders the prop.
167
+ const [appearance, setAppearanceState] = useState<Appearance>(
168
+ () => readAppearanceFromStorage(storageKey) ?? safeInitialAppearance,
169
+ );
170
+
171
+ // Optimistic appearance - immediately reflects user's intent while async operation runs
172
+ // Automatically reverts to `appearance` if the transition fails
173
+ const [optimisticAppearance, setOptimisticAppearance] = useOptimistic(appearance);
174
+
175
+ // True when there's a pending appearance change (optimistic !== actual)
176
+ const isPending = optimisticAppearance !== appearance;
177
+
178
+ // Stable ref so setAppearance does not re-create every time the committed appearance changes
179
+ const committedAppearanceRef = useRef(appearance);
180
+
181
+ committedAppearanceRef.current = appearance;
182
+
183
+ // Shared BroadcastChannel — reused by the setAppearance sender instead of opening a new one per call
184
+ const channelRef = useRef<BroadcastChannel | null>(null);
185
+
186
+ // suppressTransitions cleanup stored here and called after applyColorScheme commits to the DOM
187
+ const enableTransitionsRef = useRef<(() => void) | null>(null);
188
+
189
+ // Last-write-wins intent — prevents stale async commits from overriding newer setAppearance calls
190
+ const intentRef = useRef<Appearance | null>(null);
191
+
192
+ // Effective persistence: an explicit persistAppearance wins; otherwise auto-persist to localStorage.
193
+ const persist = useMemo<(value: Appearance) => Promise<void>>(() => {
194
+ if (persistAppearance) {
195
+ return persistAppearance;
196
+ }
197
+
198
+ return async (value: Appearance): Promise<void> => {
199
+ try {
200
+ globalThis.window.localStorage.setItem(storageKey, value);
201
+ } catch {
202
+ /* storage blocked (private mode / quota) — optimistic UI already reflects the change */
203
+ }
204
+ };
205
+ }, [persistAppearance, storageKey]);
206
+
207
+ // Subscribe to OS preference changes (SSR-safe via useSyncExternalStore)
208
+ const systemColorScheme = useSyncExternalStore(subscribeToSystemColorScheme, getSystemColorScheme, getServerSnapshot);
209
+
210
+ // Compute the color scheme to apply: resolve 'automatic' to light/dark
211
+ const colorScheme = useMemo<ColorScheme>(
212
+ () => (optimisticAppearance === "automatic" ? systemColorScheme : optimisticAppearance),
213
+ [optimisticAppearance, systemColorScheme],
214
+ );
215
+
216
+ // Apply the color scheme to the DOM then call the transition cleanup — ensures enable() fires
217
+ // after applyColorScheme has committed, not prematurely in the async persist finally block
218
+ useEffect(() => {
219
+ applyColorScheme(colorScheme);
220
+
221
+ const enable = enableTransitionsRef.current;
222
+
223
+ if (enable) {
224
+ enableTransitionsRef.current = null;
225
+ enable();
226
+ }
227
+ }, [colorScheme]);
228
+
229
+ // Mirror the *preference* (not the resolved value) to `data-appearance` so preference-aware UI
230
+ // (e.g. a 3-state toggle) renders from CSS — matching what AppearanceScript set pre-paint. Tracks the
231
+ // optimistic value so the attribute flips immediately on change and stays in sync across tabs.
232
+ useEffect(() => {
233
+ globalThis.window.document.documentElement.dataset.appearance = optimisticAppearance;
234
+ }, [optimisticAppearance]);
235
+
236
+ // Validate cross-tab messages before applying to prevent injection from extensions/scripts
237
+ const handleCrossTabMessage = useEffectEvent((event: MessageEvent) => {
238
+ const result = appearanceSchema.safeParse(event.data);
239
+
240
+ if (!result.success || result.data === appearance) {
241
+ return;
242
+ }
243
+
244
+ startTransition(() => {
245
+ setAppearanceState(result.data);
246
+ });
247
+ });
248
+
249
+ // Cross-tab sync fallback: the `storage` event fires in OTHER tabs when this key changes.
250
+ const handleStorageEvent = useEffectEvent((event: StorageEvent) => {
251
+ if (event.key !== storageKey) {
252
+ return;
253
+ }
254
+
255
+ const result = appearanceSchema.safeParse(event.newValue);
256
+
257
+ if (!result.success || result.data === appearance) {
258
+ return;
259
+ }
260
+
261
+ startTransition(() => {
262
+ setAppearanceState(result.data);
263
+ });
264
+ });
265
+
266
+ // Keep the channel in a ref so setAppearance can broadcast without opening a new channel each time
267
+ useEffect(() => {
268
+ const channel = createAppearanceChannel();
269
+
270
+ if (!channel) {
271
+ return;
272
+ }
273
+
274
+ channelRef.current = channel;
275
+ channel.addEventListener("message", handleCrossTabMessage);
276
+
277
+ return (): void => {
278
+ channelRef.current = null;
279
+ channel.removeEventListener("message", handleCrossTabMessage);
280
+ channel.close();
281
+ };
282
+ }, []);
283
+
284
+ useEffect(() => {
285
+ globalThis.window.addEventListener("storage", handleStorageEvent);
286
+
287
+ return (): void => {
288
+ globalThis.window.removeEventListener("storage", handleStorageEvent);
289
+ };
290
+ }, []);
291
+
292
+ const setAppearance = useCallback(
293
+ async (value: Appearance): Promise<void> => {
294
+ await Promise.resolve();
295
+
296
+ // Read from ref so this callback stays stable across appearance commits
297
+ if (value === committedAppearanceRef.current) {
298
+ return;
299
+ }
300
+
301
+ // Store the cleanup; it will be called after applyColorScheme runs in the colorScheme effect
302
+ if (disableTransition) {
303
+ enableTransitionsRef.current = suppressTransitions(nonce);
304
+ }
305
+
306
+ startTransition(async () => {
307
+ // Track intent; only the latest setAppearance call commits its value
308
+ intentRef.current = value;
309
+
310
+ // Show the new appearance immediately (optimistic update)
311
+ setOptimisticAppearance(value);
312
+
313
+ try {
314
+ // Persist to storage
315
+ await persist(value);
316
+
317
+ // Only commit if no newer setAppearance call has since taken over
318
+ if (intentRef.current === value) {
319
+ setAppearanceState(value);
320
+
321
+ // Notify other tabs via the shared channel
322
+ channelRef.current?.postMessage(value);
323
+ }
324
+ } catch (error) {
325
+ // On failure, useOptimistic automatically reverts to `appearance`
326
+ if (onPersistError) {
327
+ try {
328
+ onPersistError(error, value);
329
+ } catch (callbackError) {
330
+ console.error("Failed to handle appearance persist error:", callbackError);
331
+ }
332
+ } else {
333
+ console.error("Failed to set appearance:", error);
334
+ }
335
+ } finally {
336
+ // Safety net: fires when the color scheme did not change (e.g. automatic→dark while
337
+ // the OS is already dark) so the applyColorScheme effect never runs. No-op if the effect
338
+ // already called enable().
339
+ const enable = enableTransitionsRef.current;
340
+
341
+ if (enable) {
342
+ enableTransitionsRef.current = null;
343
+ enable();
344
+ }
345
+ }
346
+ });
347
+ },
348
+ [disableTransition, nonce, setOptimisticAppearance, persist, onPersistError],
349
+ );
350
+
351
+ // Expose the optimistic appearance so consumers see immediate updates
352
+ const value = useMemo<AppearanceContextType>(
353
+ () => ({
354
+ isPending,
355
+ colorScheme,
356
+ setAppearance,
357
+ appearance: optimisticAppearance,
358
+ }),
359
+ [optimisticAppearance, colorScheme, setAppearance, isPending],
360
+ );
361
+
362
+ return <AppearanceContext value={value}>{children}</AppearanceContext>;
363
+ }