@codefast/theme 0.5.0-canary.1 → 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 +31 -0
  2. package/README.md +107 -178
  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 -63
  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 -118
  38. package/dist/core/provider.mjs +0 -231
  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 -68
  42. package/dist/script/theme-script.mjs +0 -45
  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 -470
  53. package/src/core/use-theme.ts +0 -46
  54. package/src/script/theme-script.tsx +0 -92
  55. package/src/start.ts +0 -54
  56. package/src/types.ts +0 -61
  57. package/src/utils/system.ts +0 -56
@@ -1,146 +0,0 @@
1
- import { createServerFn } from "@tanstack/react-start";
2
- import { getCookie, getRequestHeader, setCookie } from "@tanstack/react-start/server";
3
-
4
- import { DEFAULT_RESOLVED_COLOR_SCHEME, DEFAULT_COLOR_SCHEME, STORAGE_KEY } from "#/constants";
5
- import type { ResolvedColorScheme, ColorScheme } from "#/types";
6
- import { colorSchemeSchema } from "#/types";
7
-
8
- /* -----------------------------------------------------------------------------
9
- * Request helpers (one round-trip when composed)
10
- * -------------------------------------------------------------------------- */
11
-
12
- function readColorSchemeFromCookie(): ColorScheme {
13
- const cookieValue = getCookie(STORAGE_KEY);
14
- const validationResult = colorSchemeSchema.safeParse(cookieValue);
15
-
16
- if (validationResult.success) {
17
- return validationResult.data;
18
- }
19
-
20
- return DEFAULT_COLOR_SCHEME;
21
- }
22
-
23
- function readSsrColorSchemeFromHeaders(): ResolvedColorScheme {
24
- const hint = getRequestHeader("Sec-CH-Prefers-Color-Scheme") ?? getRequestHeader("Prefers-Color-Scheme");
25
-
26
- if (hint === "dark") {
27
- return "dark";
28
- }
29
-
30
- if (hint === "light") {
31
- return "light";
32
- }
33
-
34
- return DEFAULT_RESOLVED_COLOR_SCHEME;
35
- }
36
-
37
- /**
38
- * Data shape returned from {@link getRootColorSchemeServerFn} for the root route loader.
39
- *
40
- * @since 0.3.16-canary.0
41
- */
42
- export type RootColorSchemeLoaderData = {
43
- /**
44
- * Resolved `light` or `dark` from the incoming request when detectable
45
- * (e.g. `Sec-CH-Prefers-Color-Scheme`). Pass to `AppearanceProvider` as `ssrColorScheme` and to
46
- * `resolveColorScheme(colorScheme, ssrColorScheme)` on `<html>`. When the hint is absent, matches
47
- * {@link DEFAULT_RESOLVED_COLOR_SCHEME}.
48
- */
49
- readonly ssrColorScheme: ResolvedColorScheme;
50
- /**
51
- * User preference from the httpOnly cookie: `light`, `dark`, or `automatic`.
52
- */
53
- readonly colorScheme: ColorScheme;
54
- };
55
-
56
- /* -----------------------------------------------------------------------------
57
- * Server Functions
58
- *
59
- * These functions run on the server and handle cookie-based color scheme persistence.
60
- * Cookies are httpOnly for security - the client cannot read them directly.
61
- * -------------------------------------------------------------------------- */
62
-
63
- /**
64
- * Everything needed for the root shell in **one** server call (fewer loader awaits).
65
- *
66
- * In your shell: `resolveColorScheme(colorScheme, ssrColorScheme)` on `<html>`, plus `AppearanceScript` and `AppearanceProvider`.
67
- *
68
- * @since 0.3.16-canary.0
69
- */
70
- export const getRootColorSchemeServerFn = createServerFn().handler(
71
- (): RootColorSchemeLoaderData => ({
72
- colorScheme: readColorSchemeFromCookie(),
73
- ssrColorScheme: readSsrColorSchemeFromHeaders(),
74
- }),
75
- );
76
-
77
- /**
78
- * Read the user's color scheme preference from cookies.
79
- *
80
- * Validates the cookie value using Zod schema for type safety.
81
- * Returns {@link DEFAULT_COLOR_SCHEME} if cookie is missing or invalid.
82
- *
83
- * @returns User's stored color scheme preference or default
84
- *
85
- * @example
86
- * ```tsx
87
- * const colorScheme = await getColorSchemeServerFn();
88
- * ```
89
- *
90
- * @since 0.3.16-canary.0
91
- */
92
- export const getColorSchemeServerFn = createServerFn().handler((): ColorScheme => readColorSchemeFromCookie());
93
-
94
- /**
95
- * Resolved OS color scheme for SSR / hydration, from Client Hints when the browser sends them.
96
- *
97
- * Mirrors client `matchMedia("(prefers-color-scheme: dark)")` when hints are present.
98
- * Prefer {@link getRootColorSchemeServerFn} for root loaders.
99
- *
100
- * Send `Accept-CH: Sec-CH-Prefers-Color-Scheme` (and `Vary`) so navigations include the hint.
101
- *
102
- * @since 0.3.16-canary.0
103
- */
104
- export const getSsrColorSchemeServerFn = createServerFn().handler(
105
- (): ResolvedColorScheme => readSsrColorSchemeFromHeaders(),
106
- );
107
-
108
- /**
109
- * Persist color scheme preference to an HTTP-only cookie.
110
- *
111
- * **Security:**
112
- * - `httpOnly: true` - Cookie cannot be accessed from JavaScript (XSS protection)
113
- * - `secure: true` in production - Cookie only sent over HTTPS
114
- * - `sameSite: 'lax'` - Prevents CSRF while allowing navigation
115
- *
116
- * **Cookie Settings:**
117
- * - `maxAge: 1 year` - Preference persists across sessions
118
- * - `path: '/'` - Available to all routes
119
- *
120
- * @param data - Color scheme to persist ('light', 'dark', or 'automatic')
121
- *
122
- * @see [TanStack Start Server Functions](https://tanstack.com/start/latest/docs/framework/react/server-functions)
123
- *
124
- * @since 0.3.16-canary.0
125
- */
126
- export const setColorSchemeServerFn = createServerFn({ method: "POST" })
127
- .validator(colorSchemeSchema)
128
- .handler(({ data }: { data: ColorScheme }): void => {
129
- setCookie(STORAGE_KEY, data, {
130
- httpOnly: true,
131
- maxAge: 60 * 60 * 24 * 365, // 1 year
132
- path: "/",
133
- sameSite: "lax",
134
- secure: process.env.NODE_ENV === "production",
135
- });
136
- });
137
-
138
- /**
139
- * Default {@link AppearanceProvider} `persistColorScheme` for the Start adapter: writes the httpOnly
140
- * color scheme cookie via {@link setColorSchemeServerFn}.
141
- *
142
- * @since 0.3.16-canary.0
143
- */
144
- export async function persistColorSchemeCookie(value: ColorScheme): Promise<void> {
145
- await setColorSchemeServerFn({ data: value });
146
- }
@@ -1,50 +0,0 @@
1
- /**
2
- * Vite plugin that wires `@codefast/theme`'s TanStack Start server functions into a consumer build.
3
- *
4
- * `@codefast/theme/start` ships `createServerFn()` calls inside its published `dist`. TanStack
5
- * Start registers each server function's RPC endpoint at **build time, in the consuming app**.
6
- * For that transform to run over this package, it must not be externalized for SSR nor
7
- * pre-bundled for the client — otherwise the endpoints never register and calls fail at runtime.
8
- *
9
- * This plugin applies exactly that, so consumers don't have to hand-write `ssr.noExternal` and
10
- * `optimizeDeps.exclude` themselves.
11
- *
12
- * @example
13
- * ```ts
14
- * // vite.config.ts
15
- * import { codefastTheme } from "@codefast/theme/vite";
16
- * import { tanstackStart } from "@tanstack/react-start/plugin/vite";
17
- * import viteReact from "@vitejs/plugin-react";
18
- * import { defineConfig } from "vite";
19
- *
20
- * export default defineConfig({
21
- * plugins: [codefastTheme(), tanstackStart(), viteReact()],
22
- * });
23
- * ```
24
- */
25
-
26
- import type { Plugin } from "vite";
27
-
28
- const PACKAGE_NAME = "@codefast/theme";
29
-
30
- /**
31
- * Create the Vite plugin that lets a TanStack Start app consume `@codefast/theme`'s server
32
- * functions from npm without manual `ssr.noExternal` / `optimizeDeps.exclude` configuration.
33
- *
34
- * @since 0.5.0-canary.0
35
- */
36
- export function codefastTheme(): Plugin {
37
- return {
38
- name: "codefast:theme",
39
- config() {
40
- return {
41
- ssr: {
42
- noExternal: [PACKAGE_NAME],
43
- },
44
- optimizeDeps: {
45
- exclude: [PACKAGE_NAME],
46
- },
47
- };
48
- },
49
- };
50
- }
@@ -1,22 +0,0 @@
1
- import { createContext } from "react";
2
-
3
- import type { ColorSchemeContextType } from "#/types";
4
-
5
- /* -----------------------------------------------------------------------------
6
- * Context
7
- * -------------------------------------------------------------------------- */
8
-
9
- type ColorSchemeContextValue = null | ColorSchemeContextType;
10
-
11
- /**
12
- * React context for color scheme state management.
13
- *
14
- * Provides access to current color scheme, resolved color scheme, setter function, and pending state.
15
- * Use {@link useColorScheme} hook instead of consuming this context directly.
16
- *
17
- * @see {@link AppearanceProvider} - Provider component
18
- * @see {@link useColorScheme} - Consumer hook
19
- *
20
- * @since 0.3.16-canary.0
21
- */
22
- export const ColorSchemeContext = createContext<ColorSchemeContextValue>(null);
@@ -1,470 +0,0 @@
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 { DEFAULT_RESOLVED_COLOR_SCHEME, DEFAULT_COLOR_SCHEME, MEDIA, SYNC_CHANNEL } from "#/constants";
15
- import { ColorSchemeContext } from "#/core/context";
16
- import type { ResolvedColorScheme, ColorScheme, ColorSchemeContextType } from "#/types";
17
- import { colorSchemeSchema } from "#/types";
18
- import { applyColorScheme, suppressTransitions } from "#/utils/dom";
19
- import { getSystemColorScheme } from "#/utils/system";
20
-
21
- /* -----------------------------------------------------------------------------
22
- * System Color Scheme Subscription
23
- *
24
- * These functions power `useSyncExternalStore` for reactive system color scheme 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 system 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
- /**
45
- * Safely create a color scheme BroadcastChannel when supported by the environment.
46
- */
47
- function createColorSchemeChannel(): BroadcastChannel | null {
48
- if (typeof BroadcastChannel === "undefined") {
49
- return null;
50
- }
51
-
52
- try {
53
- return new BroadcastChannel(SYNC_CHANNEL);
54
- } catch {
55
- return null;
56
- }
57
- }
58
-
59
- /**
60
- * Read + validate the persisted preference from localStorage. Returns null when unavailable
61
- * (SSR, private mode) or when the stored value is not a recognised scheme.
62
- */
63
- function readColorSchemeFromStorage(storageKey: string): ColorScheme | null {
64
- if (typeof globalThis.window === "undefined") {
65
- return null;
66
- }
67
-
68
- try {
69
- const result = colorSchemeSchema.safeParse(globalThis.window.localStorage.getItem(storageKey));
70
-
71
- return result.success ? result.data : null;
72
- } catch {
73
- return null;
74
- }
75
- }
76
-
77
- /* -----------------------------------------------------------------------------
78
- * Props
79
- * -------------------------------------------------------------------------- */
80
-
81
- /**
82
- * @since 0.3.16-canary.3
83
- */
84
- export type AppearanceProviderProps = {
85
- readonly children: ReactNode;
86
- /**
87
- * When true, temporarily suppresses CSS transitions during color scheme changes.
88
- * Prevents jarring color animations when switching appearances.
89
- * Default: false
90
- */
91
- readonly disableTransition?: boolean;
92
- /**
93
- * CSP nonce for inline styles when `disableTransition` is enabled.
94
- */
95
- readonly nonce?: string;
96
- /**
97
- * Async function to persist color scheme changes to server/storage.
98
- *
99
- * For TanStack Start: use `persistColorSchemeCookie` from `@codefast/theme/start`
100
- * For Next.js: implement a server action
101
- */
102
- readonly persistColorScheme?: (value: ColorScheme) => Promise<void>;
103
- /**
104
- * Callback invoked when `persistColorScheme` rejects.
105
- */
106
- readonly onPersistError?: (error: unknown, attemptedColorScheme: ColorScheme) => void;
107
- /**
108
- * Initial color scheme preference from the server (cookie, loader, etc.).
109
- *
110
- * After mount, `AppearanceProvider` re-syncs whenever this prop changes — for example, when
111
- * the router re-runs the root loader after navigation. The server value is authoritative:
112
- * a new prop value will override any local optimistic state.
113
- */
114
- readonly colorScheme: ColorScheme;
115
- /**
116
- * OS light/dark guess from the SSR request (e.g. `Sec-CH-Prefers-Color-Scheme`).
117
- *
118
- * When the stored preference is `automatic`, {@link useSyncExternalStore} uses this for
119
- * `getServerSnapshot` so the first client snapshot matches `matchMedia` and avoids a
120
- * dark → light flip after hydration.
121
- */
122
- readonly ssrColorScheme?: ResolvedColorScheme;
123
- /**
124
- * After mount, re-read the canonical color scheme from the server (e.g. httpOnly cookie).
125
- *
126
- * Fixes **stale HTML / disk cache** on "Duplicate tab" or back-forward cache where the
127
- * document was saved with an old `AppearanceScript` / loader value while the cookie was already updated
128
- * in another tab. Use a stable reference (e.g. `getColorSchemeServerFn` from `@codefast/theme/start`).
129
- */
130
- readonly syncFromServer?: () => Promise<ColorScheme>;
131
- /**
132
- * Persist + restore the preference in `localStorage` under this key — the client-only path
133
- * (no server framework, no cookie, no loader).
134
- *
135
- * When set, the provider reads the stored value in its initial client render (so the first paint
136
- * already matches the preference — no flash, no post-mount settle), auto-persists changes to
137
- * `localStorage` (unless {@link persistColorScheme} is also given, which then wins), and syncs across
138
- * tabs via the `storage` event. Pair with `<AppearanceScript storageKey={…} />` using the **same key**.
139
- *
140
- * @remarks SSR has no `localStorage`, so the server renders the {@link AppearanceProviderProps.colorScheme}
141
- * prop. For a returning visitor whose stored preference differs, components that render
142
- * preference-dependent markup hydrate-reconcile once; gate them behind a mounted flag to avoid that.
143
- */
144
- readonly storageKey?: string;
145
- };
146
-
147
- /* -----------------------------------------------------------------------------
148
- * Component
149
- * -------------------------------------------------------------------------- */
150
-
151
- /**
152
- * Provider component for color scheme state management.
153
- *
154
- * **React 19 Features Used:**
155
- * - `useOptimistic` - Immediate UI feedback while persisting color scheme
156
- * - `useSyncExternalStore` - SSR-safe subscription to OS color scheme preference
157
- * - `useEffectEvent` - Stable callback for cross-tab sync without effect re-runs
158
- *
159
- * @param props - Component props
160
- * @param props.children - React tree to provide context for
161
- * @param props.colorScheme - Initial preference from the server (cookie, loader, etc.)
162
- * @param props.ssrColorScheme - Best-effort `light` or `dark` from the SSR request
163
- * (e.g. `Sec-CH-Prefers-Color-Scheme`). When preference is `automatic`, this value is used as
164
- * `useSyncExternalStore`'s server snapshot so the first client snapshot matches `matchMedia`
165
- * and avoids a post-hydration flip. Omit if unavailable; falls back to {@link DEFAULT_RESOLVED_COLOR_SCHEME}.
166
- * @param props.syncFromServer - Optional one-shot RPC after mount to align with the cookie when SSR/HTML was stale.
167
- * @param props.storageKey - Optional localStorage key for the client-only path: restore in the initial render, auto-persist, cross-tab sync.
168
- * @param props.persistColorScheme - Optional async handler to persist preference (cookie, server action, …)
169
- * @param props.onPersistError - Optional callback for persistence failures
170
- * @param props.disableTransition - Temporarily suppress CSS transitions on color scheme change
171
- * @param props.nonce - CSP nonce for inline transition-blocking styles when `disableTransition` is set
172
- * @returns Provider element wrapping `children`
173
- *
174
- * @example
175
- * ```tsx
176
- * // In your root layout
177
- * <AppearanceProvider
178
- * colorScheme={colorScheme}
179
- * persistColorScheme={(value) => setColorSchemeServerFn({ data: value })}
180
- * >
181
- * {children}
182
- * </AppearanceProvider>
183
- * ```
184
- *
185
- * @since 0.3.16-canary.0
186
- */
187
- export function AppearanceProvider({
188
- children,
189
- disableTransition = false,
190
- nonce,
191
- onPersistError,
192
- persistColorScheme,
193
- ssrColorScheme,
194
- storageKey,
195
- syncFromServer,
196
- colorScheme: initialColorScheme,
197
- }: AppearanceProviderProps): JSX.Element {
198
- // F2: Runtime guard against invalid values bypassing TypeScript (e.g. raw API strings)
199
- const safeInitialColorScheme = colorSchemeSchema.safeParse(initialColorScheme).success
200
- ? initialColorScheme
201
- : DEFAULT_COLOR_SCHEME;
202
-
203
- // Actual persisted color scheme. Storage path: read localStorage in the initializer so the first client
204
- // render already matches what AppearanceScript applied pre-paint (no flash, no post-mount settle). SSR has
205
- // no localStorage, so the server renders the prop.
206
- const [colorScheme, setColorSchemeState] = useState<ColorScheme>(() => {
207
- if (storageKey !== undefined) {
208
- const stored = readColorSchemeFromStorage(storageKey);
209
-
210
- if (stored !== null) {
211
- return stored;
212
- }
213
- }
214
-
215
- return safeInitialColorScheme;
216
- });
217
-
218
- // Optimistic color scheme - immediately reflects user's intent while async operation runs
219
- // Automatically reverts to `colorScheme` if the transition fails
220
- const [optimisticColorScheme, setOptimisticColorScheme] = useOptimistic(colorScheme);
221
-
222
- // True when there's a pending color scheme change (optimistic !== actual)
223
- const isPending = optimisticColorScheme !== colorScheme;
224
-
225
- // P1: Stable ref so setColorScheme does not re-create every time the committed color scheme changes
226
- const committedColorSchemeRef = useRef(colorScheme);
227
-
228
- committedColorSchemeRef.current = colorScheme;
229
-
230
- // P2: Shared BroadcastChannel — reused by setColorScheme sender instead of opening a new one per call
231
- const channelRef = useRef<BroadcastChannel | null>(null);
232
-
233
- // C2: suppressTransitions cleanup stored here and called after applyColorScheme commits to the DOM
234
- const enableTransitionsRef = useRef<(() => void) | null>(null);
235
-
236
- // C3: Last-write-wins intent — prevents stale async commits from overriding newer setColorScheme calls
237
- const intentRef = useRef<ColorScheme | null>(null);
238
-
239
- // Effective persistence: an explicit persistColorScheme wins; otherwise storageKey auto-persists to localStorage.
240
- const persist = useMemo<((value: ColorScheme) => Promise<void>) | undefined>(() => {
241
- if (persistColorScheme) {
242
- return persistColorScheme;
243
- }
244
-
245
- if (storageKey === undefined) {
246
- return undefined;
247
- }
248
-
249
- return async (value: ColorScheme): Promise<void> => {
250
- try {
251
- globalThis.window.localStorage.setItem(storageKey, value);
252
- } catch {
253
- /* storage blocked (private mode / quota) — optimistic UI already reflects the change */
254
- }
255
- };
256
- }, [persistColorScheme, storageKey]);
257
-
258
- // C1: Re-sync state when the server (loader) provides a new color scheme value after mount.
259
- // Storage path owns the preference client-side; the prop is only a static default — don't clobber it.
260
- useEffect(() => {
261
- if (storageKey !== undefined) {
262
- return;
263
- }
264
-
265
- startTransition(() => {
266
- setColorSchemeState((prev) => (prev === safeInitialColorScheme ? prev : safeInitialColorScheme));
267
- });
268
- }, [safeInitialColorScheme, storageKey]);
269
-
270
- const syncFromServerRef = useRef(syncFromServer);
271
-
272
- syncFromServerRef.current = syncFromServer;
273
-
274
- useEffect(() => {
275
- const sync = syncFromServerRef.current;
276
-
277
- if (!sync) {
278
- return;
279
- }
280
-
281
- let cancelled = false;
282
-
283
- void (async () => {
284
- try {
285
- const serverColorScheme = await sync();
286
-
287
- if (cancelled) {
288
- return;
289
- }
290
-
291
- startTransition(() => {
292
- setColorSchemeState((prev) => (prev === serverColorScheme ? prev : serverColorScheme));
293
- });
294
- } catch {
295
- /* keep SSR / loader state */
296
- }
297
- })();
298
-
299
- return (): void => {
300
- cancelled = true;
301
- };
302
- }, []);
303
-
304
- const getServerSnapshot = useCallback((): ResolvedColorScheme => {
305
- return ssrColorScheme ?? DEFAULT_RESOLVED_COLOR_SCHEME;
306
- }, [ssrColorScheme]);
307
-
308
- // Subscribe to OS preference changes (SSR-safe via useSyncExternalStore)
309
- const systemColorScheme = useSyncExternalStore(subscribeToSystemColorScheme, getSystemColorScheme, getServerSnapshot);
310
-
311
- // Compute the actual color scheme to apply: resolve 'automatic' to light/dark
312
- const resolvedColorScheme = useMemo<ResolvedColorScheme>(
313
- () => (optimisticColorScheme === "automatic" ? systemColorScheme : optimisticColorScheme),
314
- [optimisticColorScheme, systemColorScheme],
315
- );
316
-
317
- // C2: Apply color scheme to DOM then call transition cleanup — ensures enable() fires after
318
- // applyColorScheme has committed, not prematurely in the async persist finally block
319
- useEffect(() => {
320
- applyColorScheme(resolvedColorScheme);
321
-
322
- const enable = enableTransitionsRef.current;
323
-
324
- if (enable) {
325
- enableTransitionsRef.current = null;
326
- enable();
327
- }
328
- }, [resolvedColorScheme]);
329
-
330
- // Mirror the *preference* (not the resolved value) to `data-appearance` so preference-aware UI
331
- // (e.g. a 3-state toggle) renders from CSS — matching what AppearanceScript set pre-paint. Tracks the
332
- // optimistic value so the attribute flips immediately on change and stays in sync across tabs.
333
- useEffect(() => {
334
- globalThis.window.document.documentElement.dataset.appearance = optimisticColorScheme;
335
- }, [optimisticColorScheme]);
336
-
337
- // S1: Validate cross-tab message before applying to prevent injection from extensions/scripts
338
- const handleCrossTabMessage = useEffectEvent((event: MessageEvent) => {
339
- const result = colorSchemeSchema.safeParse(event.data);
340
-
341
- if (!result.success || result.data === colorScheme) {
342
- return;
343
- }
344
-
345
- startTransition(() => {
346
- setColorSchemeState(result.data);
347
- });
348
- });
349
-
350
- // Storage path cross-tab sync: the `storage` event fires in OTHER tabs when this key changes.
351
- const handleStorageEvent = useEffectEvent((event: StorageEvent) => {
352
- if (event.key !== storageKey) {
353
- return;
354
- }
355
-
356
- const result = colorSchemeSchema.safeParse(event.newValue);
357
-
358
- if (!result.success || result.data === colorScheme) {
359
- return;
360
- }
361
-
362
- startTransition(() => {
363
- setColorSchemeState(result.data);
364
- });
365
- });
366
-
367
- // P2: Keep channel in ref so setColorScheme can broadcast without opening a new channel each time
368
- useEffect(() => {
369
- const channel = createColorSchemeChannel();
370
-
371
- if (!channel) {
372
- return;
373
- }
374
-
375
- channelRef.current = channel;
376
- channel.addEventListener("message", handleCrossTabMessage);
377
-
378
- return (): void => {
379
- channelRef.current = null;
380
- channel.removeEventListener("message", handleCrossTabMessage);
381
- channel.close();
382
- };
383
- }, []);
384
-
385
- useEffect(() => {
386
- if (storageKey === undefined) {
387
- return;
388
- }
389
-
390
- globalThis.window.addEventListener("storage", handleStorageEvent);
391
-
392
- return (): void => {
393
- globalThis.window.removeEventListener("storage", handleStorageEvent);
394
- };
395
- }, [storageKey]);
396
-
397
- const setColorScheme = useCallback(
398
- async (value: ColorScheme): Promise<void> => {
399
- await Promise.resolve();
400
-
401
- // P1: Read from ref so this callback stays stable across color scheme commits
402
- if (value === committedColorSchemeRef.current) {
403
- return;
404
- }
405
-
406
- // C2: Store cleanup here; it will be called after applyColorScheme runs in the resolvedColorScheme effect
407
- if (disableTransition) {
408
- enableTransitionsRef.current = suppressTransitions(nonce);
409
- }
410
-
411
- startTransition(async () => {
412
- // C3: Track intent; only the latest setColorScheme call commits its value
413
- intentRef.current = value;
414
-
415
- // Show new color scheme immediately (optimistic update)
416
- setOptimisticColorScheme(value);
417
-
418
- try {
419
- // Persist to server/storage
420
- if (persist) {
421
- await persist(value);
422
- }
423
-
424
- // Only commit if no newer setColorScheme call has since taken over
425
- if (intentRef.current === value) {
426
- setColorSchemeState(value);
427
-
428
- // P2: Notify other tabs via shared channel
429
- channelRef.current?.postMessage(value);
430
- }
431
- } catch (error) {
432
- // On failure, useOptimistic automatically reverts to `colorScheme`
433
- if (onPersistError) {
434
- try {
435
- onPersistError(error, value);
436
- } catch (callbackError) {
437
- console.error("Failed to handle color scheme persist error:", callbackError);
438
- }
439
- } else {
440
- console.error("Failed to set color scheme:", error);
441
- }
442
- } finally {
443
- // C2 safety net: fires when resolvedColorScheme did not change (e.g. automatic→dark while
444
- // OS is already dark) so the applyColorScheme effect never runs. No-op if the effect
445
- // already called enable().
446
- const enable = enableTransitionsRef.current;
447
-
448
- if (enable) {
449
- enableTransitionsRef.current = null;
450
- enable();
451
- }
452
- }
453
- });
454
- },
455
- [disableTransition, nonce, setOptimisticColorScheme, persist, onPersistError],
456
- );
457
-
458
- // Expose optimistic color scheme so consumers see immediate updates
459
- const value = useMemo<ColorSchemeContextType>(
460
- () => ({
461
- isPending,
462
- resolvedColorScheme,
463
- setColorScheme,
464
- colorScheme: optimisticColorScheme,
465
- }),
466
- [optimisticColorScheme, resolvedColorScheme, setColorScheme, isPending],
467
- );
468
-
469
- return <ColorSchemeContext value={value}>{children}</ColorSchemeContext>;
470
- }