@codefast/theme 0.3.16-canary.2 → 0.4.0-canary.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,146 @@
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
+ .inputValidator(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
+ }
@@ -0,0 +1,52 @@
1
+ import type { ResolvedColorScheme, ColorScheme } from "#/types";
2
+
3
+ /* -----------------------------------------------------------------------------
4
+ * Public Constants
5
+ * -------------------------------------------------------------------------- */
6
+
7
+ /**
8
+ * Default color scheme when no user preference exists.
9
+ *
10
+ * Set to 'automatic' to respect OS preference by default.
11
+ *
12
+ * @since 0.3.16-canary.0
13
+ */
14
+ export const DEFAULT_COLOR_SCHEME: ColorScheme = "automatic";
15
+
16
+ /**
17
+ * Fallback color scheme for SSR when system preference cannot be detected.
18
+ *
19
+ * Used during server-side rendering since `window.matchMedia()` is unavailable.
20
+ *
21
+ * @since 0.3.16-canary.0
22
+ */
23
+ export const DEFAULT_RESOLVED_COLOR_SCHEME: ResolvedColorScheme = "dark";
24
+
25
+ /**
26
+ * Cookie name for the httpOnly color scheme preference (`@codefast/theme/start`).
27
+ *
28
+ * Re-exported only from `@codefast/theme/constants` so custom middleware matches the adapter.
29
+ *
30
+ * @since 0.3.16-canary.0
31
+ */
32
+ export const STORAGE_KEY = "ui-theme";
33
+
34
+ /* -----------------------------------------------------------------------------
35
+ * Internal Constants
36
+ * -------------------------------------------------------------------------- */
37
+
38
+ /**
39
+ * CSS media query for detecting dark mode preference.
40
+ * @internal
41
+ *
42
+ * @since 0.3.16-canary.0
43
+ */
44
+ export const MEDIA = "(prefers-color-scheme: dark)";
45
+
46
+ /**
47
+ * BroadcastChannel name for cross-tab color scheme synchronization.
48
+ * @internal
49
+ *
50
+ * @since 0.3.16-canary.0
51
+ */
52
+ export const SYNC_CHANNEL = "color-scheme-sync";
@@ -0,0 +1,22 @@
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);
@@ -0,0 +1,364 @@
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
+ * Props
61
+ * -------------------------------------------------------------------------- */
62
+
63
+ /**
64
+ * @since 0.3.16-canary.3
65
+ */
66
+ export type AppearanceProviderProps = {
67
+ readonly children: ReactNode;
68
+ /**
69
+ * When true, temporarily suppresses CSS transitions during color scheme changes.
70
+ * Prevents jarring color animations when switching appearances.
71
+ * Default: false
72
+ */
73
+ readonly disableTransition?: boolean;
74
+ /**
75
+ * CSP nonce for inline styles when `disableTransition` is enabled.
76
+ */
77
+ readonly nonce?: string;
78
+ /**
79
+ * Async function to persist color scheme changes to server/storage.
80
+ *
81
+ * For TanStack Start: use `persistColorSchemeCookie` from `@codefast/theme/start`
82
+ * For Next.js: implement a server action
83
+ */
84
+ readonly persistColorScheme?: (value: ColorScheme) => Promise<void>;
85
+ /**
86
+ * Callback invoked when `persistColorScheme` rejects.
87
+ */
88
+ readonly onPersistError?: (error: unknown, attemptedColorScheme: ColorScheme) => void;
89
+ /**
90
+ * Initial color scheme preference from the server (cookie, loader, etc.).
91
+ *
92
+ * After mount, `AppearanceProvider` re-syncs whenever this prop changes — for example, when
93
+ * the router re-runs the root loader after navigation. The server value is authoritative:
94
+ * a new prop value will override any local optimistic state.
95
+ */
96
+ readonly colorScheme: ColorScheme;
97
+ /**
98
+ * OS light/dark guess from the SSR request (e.g. `Sec-CH-Prefers-Color-Scheme`).
99
+ *
100
+ * When the stored preference is `automatic`, {@link useSyncExternalStore} uses this for
101
+ * `getServerSnapshot` so the first client snapshot matches `matchMedia` and avoids a
102
+ * dark → light flip after hydration.
103
+ */
104
+ readonly ssrColorScheme?: ResolvedColorScheme;
105
+ /**
106
+ * After mount, re-read the canonical color scheme from the server (e.g. httpOnly cookie).
107
+ *
108
+ * Fixes **stale HTML / disk cache** on "Duplicate tab" or back-forward cache where the
109
+ * document was saved with an old `AppearanceScript` / loader value while the cookie was already updated
110
+ * in another tab. Use a stable reference (e.g. `getColorSchemeServerFn` from `@codefast/theme/start`).
111
+ */
112
+ readonly syncFromServer?: () => Promise<ColorScheme>;
113
+ };
114
+
115
+ /* -----------------------------------------------------------------------------
116
+ * Component
117
+ * -------------------------------------------------------------------------- */
118
+
119
+ /**
120
+ * Provider component for color scheme state management.
121
+ *
122
+ * **React 19 Features Used:**
123
+ * - `useOptimistic` - Immediate UI feedback while persisting color scheme
124
+ * - `useSyncExternalStore` - SSR-safe subscription to OS color scheme preference
125
+ * - `useEffectEvent` - Stable callback for cross-tab sync without effect re-runs
126
+ *
127
+ * @param props - Component props
128
+ * @param props.children - React tree to provide context for
129
+ * @param props.colorScheme - Initial preference from the server (cookie, loader, etc.)
130
+ * @param props.ssrColorScheme - Best-effort `light` or `dark` from the SSR request
131
+ * (e.g. `Sec-CH-Prefers-Color-Scheme`). When preference is `automatic`, this value is used as
132
+ * `useSyncExternalStore`'s server snapshot so the first client snapshot matches `matchMedia`
133
+ * and avoids a post-hydration flip. Omit if unavailable; falls back to {@link DEFAULT_RESOLVED_COLOR_SCHEME}.
134
+ * @param props.syncFromServer - Optional one-shot RPC after mount to align with the cookie when SSR/HTML was stale.
135
+ * @param props.persistColorScheme - Optional async handler to persist preference (cookie, server action, …)
136
+ * @param props.onPersistError - Optional callback for persistence failures
137
+ * @param props.disableTransition - Temporarily suppress CSS transitions on color scheme change
138
+ * @param props.nonce - CSP nonce for inline transition-blocking styles when `disableTransition` is set
139
+ * @returns Provider element wrapping `children`
140
+ *
141
+ * @example
142
+ * ```tsx
143
+ * // In your root layout
144
+ * <AppearanceProvider
145
+ * colorScheme={colorScheme}
146
+ * persistColorScheme={(value) => setColorSchemeServerFn({ data: value })}
147
+ * >
148
+ * {children}
149
+ * </AppearanceProvider>
150
+ * ```
151
+ *
152
+ * @since 0.3.16-canary.0
153
+ */
154
+ export function AppearanceProvider({
155
+ children,
156
+ disableTransition = false,
157
+ nonce,
158
+ onPersistError,
159
+ persistColorScheme,
160
+ ssrColorScheme,
161
+ syncFromServer,
162
+ colorScheme: initialColorScheme,
163
+ }: AppearanceProviderProps): JSX.Element {
164
+ // F2: Runtime guard against invalid values bypassing TypeScript (e.g. raw API strings)
165
+ const safeInitialColorScheme = colorSchemeSchema.safeParse(initialColorScheme).success
166
+ ? initialColorScheme
167
+ : DEFAULT_COLOR_SCHEME;
168
+
169
+ // Actual persisted color scheme (source of truth after server confirms)
170
+ const [colorScheme, setColorSchemeState] = useState<ColorScheme>(safeInitialColorScheme);
171
+
172
+ // Optimistic color scheme - immediately reflects user's intent while async operation runs
173
+ // Automatically reverts to `colorScheme` if the transition fails
174
+ const [optimisticColorScheme, setOptimisticColorScheme] = useOptimistic(colorScheme);
175
+
176
+ // True when there's a pending color scheme change (optimistic !== actual)
177
+ const isPending = optimisticColorScheme !== colorScheme;
178
+
179
+ // P1: Stable ref so setColorScheme does not re-create every time the committed color scheme changes
180
+ const committedColorSchemeRef = useRef(colorScheme);
181
+
182
+ committedColorSchemeRef.current = colorScheme;
183
+
184
+ // P2: Shared BroadcastChannel — reused by setColorScheme sender instead of opening a new one per call
185
+ const channelRef = useRef<BroadcastChannel | null>(null);
186
+
187
+ // C2: suppressTransitions cleanup stored here and called after applyColorScheme commits to the DOM
188
+ const enableTransitionsRef = useRef<(() => void) | null>(null);
189
+
190
+ // C3: Last-write-wins intent — prevents stale async commits from overriding newer setColorScheme calls
191
+ const intentRef = useRef<ColorScheme | null>(null);
192
+
193
+ // C1: Re-sync state when the server (loader) provides a new color scheme value after mount
194
+ useEffect(() => {
195
+ startTransition(() => {
196
+ setColorSchemeState((prev) => (prev === safeInitialColorScheme ? prev : safeInitialColorScheme));
197
+ });
198
+ }, [safeInitialColorScheme]);
199
+
200
+ const syncFromServerRef = useRef(syncFromServer);
201
+
202
+ syncFromServerRef.current = syncFromServer;
203
+
204
+ useEffect(() => {
205
+ const sync = syncFromServerRef.current;
206
+
207
+ if (!sync) {
208
+ return;
209
+ }
210
+
211
+ let cancelled = false;
212
+
213
+ void (async () => {
214
+ try {
215
+ const serverColorScheme = await sync();
216
+
217
+ if (cancelled) {
218
+ return;
219
+ }
220
+
221
+ startTransition(() => {
222
+ setColorSchemeState((prev) => (prev === serverColorScheme ? prev : serverColorScheme));
223
+ });
224
+ } catch {
225
+ /* keep SSR / loader state */
226
+ }
227
+ })();
228
+
229
+ return (): void => {
230
+ cancelled = true;
231
+ };
232
+ }, []);
233
+
234
+ const getServerSnapshot = useCallback((): ResolvedColorScheme => {
235
+ return ssrColorScheme ?? DEFAULT_RESOLVED_COLOR_SCHEME;
236
+ }, [ssrColorScheme]);
237
+
238
+ // Subscribe to OS preference changes (SSR-safe via useSyncExternalStore)
239
+ const systemColorScheme = useSyncExternalStore(subscribeToSystemColorScheme, getSystemColorScheme, getServerSnapshot);
240
+
241
+ // Compute the actual color scheme to apply: resolve 'automatic' to light/dark
242
+ const resolvedColorScheme = useMemo<ResolvedColorScheme>(
243
+ () => (optimisticColorScheme === "automatic" ? systemColorScheme : optimisticColorScheme),
244
+ [optimisticColorScheme, systemColorScheme],
245
+ );
246
+
247
+ // C2: Apply color scheme to DOM then call transition cleanup — ensures enable() fires after
248
+ // applyColorScheme has committed, not prematurely in the async persist finally block
249
+ useEffect(() => {
250
+ applyColorScheme(resolvedColorScheme);
251
+
252
+ const enable = enableTransitionsRef.current;
253
+
254
+ if (enable) {
255
+ enableTransitionsRef.current = null;
256
+ enable();
257
+ }
258
+ }, [resolvedColorScheme]);
259
+
260
+ // S1: Validate cross-tab message before applying to prevent injection from extensions/scripts
261
+ const handleCrossTabMessage = useEffectEvent((event: MessageEvent) => {
262
+ const result = colorSchemeSchema.safeParse(event.data);
263
+
264
+ if (!result.success || result.data === colorScheme) {
265
+ return;
266
+ }
267
+
268
+ startTransition(() => {
269
+ setColorSchemeState(result.data);
270
+ });
271
+ });
272
+
273
+ // P2: Keep channel in ref so setColorScheme can broadcast without opening a new channel each time
274
+ useEffect(() => {
275
+ const channel = createColorSchemeChannel();
276
+
277
+ if (!channel) {
278
+ return;
279
+ }
280
+
281
+ channelRef.current = channel;
282
+ channel.addEventListener("message", handleCrossTabMessage);
283
+
284
+ return (): void => {
285
+ channelRef.current = null;
286
+ channel.removeEventListener("message", handleCrossTabMessage);
287
+ channel.close();
288
+ };
289
+ }, []);
290
+
291
+ const setColorScheme = useCallback(
292
+ async (value: ColorScheme): Promise<void> => {
293
+ await Promise.resolve();
294
+
295
+ // P1: Read from ref so this callback stays stable across color scheme commits
296
+ if (value === committedColorSchemeRef.current) {
297
+ return;
298
+ }
299
+
300
+ // C2: Store cleanup here; it will be called after applyColorScheme runs in the resolvedColorScheme effect
301
+ if (disableTransition) {
302
+ enableTransitionsRef.current = suppressTransitions(nonce);
303
+ }
304
+
305
+ startTransition(async () => {
306
+ // C3: Track intent; only the latest setColorScheme call commits its value
307
+ intentRef.current = value;
308
+
309
+ // Show new color scheme immediately (optimistic update)
310
+ setOptimisticColorScheme(value);
311
+
312
+ try {
313
+ // Persist to server/storage
314
+ if (persistColorScheme) {
315
+ await persistColorScheme(value);
316
+ }
317
+
318
+ // Only commit if no newer setColorScheme call has since taken over
319
+ if (intentRef.current === value) {
320
+ setColorSchemeState(value);
321
+
322
+ // P2: Notify other tabs via shared channel
323
+ channelRef.current?.postMessage(value);
324
+ }
325
+ } catch (error) {
326
+ // On failure, useOptimistic automatically reverts to `colorScheme`
327
+ if (onPersistError) {
328
+ try {
329
+ onPersistError(error, value);
330
+ } catch (callbackError) {
331
+ console.error("Failed to handle color scheme persist error:", callbackError);
332
+ }
333
+ } else {
334
+ console.error("Failed to set color scheme:", error);
335
+ }
336
+ } finally {
337
+ // C2 safety net: fires when resolvedColorScheme did not change (e.g. automatic→dark while
338
+ // OS is already dark) so the applyColorScheme effect never runs. No-op if the effect
339
+ // already called enable().
340
+ const enable = enableTransitionsRef.current;
341
+
342
+ if (enable) {
343
+ enableTransitionsRef.current = null;
344
+ enable();
345
+ }
346
+ }
347
+ });
348
+ },
349
+ [disableTransition, nonce, setOptimisticColorScheme, persistColorScheme, onPersistError],
350
+ );
351
+
352
+ // Expose optimistic color scheme so consumers see immediate updates
353
+ const value = useMemo<ColorSchemeContextType>(
354
+ () => ({
355
+ isPending,
356
+ resolvedColorScheme,
357
+ setColorScheme,
358
+ colorScheme: optimisticColorScheme,
359
+ }),
360
+ [optimisticColorScheme, resolvedColorScheme, setColorScheme, isPending],
361
+ );
362
+
363
+ return <ColorSchemeContext value={value}>{children}</ColorSchemeContext>;
364
+ }
@@ -0,0 +1,46 @@
1
+ import { use } from "react";
2
+
3
+ import { ColorSchemeContext } from "#/core/context";
4
+ import type { ColorSchemeContextType } from "#/types";
5
+
6
+ /* -----------------------------------------------------------------------------
7
+ * Hook
8
+ * -------------------------------------------------------------------------- */
9
+
10
+ /**
11
+ * Hook to access color scheme context.
12
+ *
13
+ * Uses React 19's `use()` API for context consumption, enabling:
14
+ * - Conditional context reading
15
+ * - Better Suspense boundary integration
16
+ *
17
+ * @returns Color scheme context with `colorScheme`, `resolvedColorScheme`, `setPreferredColorScheme`, and `isPending`
18
+ * @throws Error if called outside of AppearanceProvider
19
+ *
20
+ * @example
21
+ * ```tsx
22
+ * function AppearanceToggle() {
23
+ * const { colorScheme, setPreferredColorScheme, isPending } = useColorScheme();
24
+ *
25
+ * return (
26
+ * <button
27
+ * onClick={() => setPreferredColorScheme(colorScheme === 'dark' ? 'light' : 'dark')}
28
+ * disabled={isPending}
29
+ * >
30
+ * {colorScheme}
31
+ * </button>
32
+ * );
33
+ * }
34
+ * ```
35
+ *
36
+ * @since 0.3.16-canary.0
37
+ */
38
+ export function useColorScheme(): ColorSchemeContextType {
39
+ const value = use(ColorSchemeContext);
40
+
41
+ if (!value) {
42
+ throw new Error("useColorScheme must be used within an AppearanceProvider");
43
+ }
44
+
45
+ return value;
46
+ }
package/src/index.ts ADDED
@@ -0,0 +1,29 @@
1
+ /**
2
+ * \@codefast/theme
3
+ *
4
+ * React 19 color scheme management: SSR-friendly `automatic` resolution, cross-tab sync, optimistic updates.
5
+ *
6
+ * - **Root** (this module): `AppearanceProvider`, `useColorScheme`, `AppearanceScript`, `resolveColorScheme`, types, defaults.
7
+ * - **`@codefast/theme/start`**: TanStack Start server functions + `persistColorSchemeCookie`.
8
+ * - **`@codefast/theme/utils`**: `getSystemColorScheme`, `applyColorScheme`, `suppressTransitions`.
9
+ * - **`@codefast/theme/core`**: `ColorSchemeContext` for rare custom wiring.
10
+ */
11
+
12
+ // Types & Schema
13
+ export type { ResolvedColorScheme, ColorScheme, ColorSchemeContextType } from "#/types";
14
+ export { colorSchemes, colorSchemeSchema } from "#/types";
15
+
16
+ // Constants
17
+ export { DEFAULT_RESOLVED_COLOR_SCHEME, DEFAULT_COLOR_SCHEME } from "#/constants";
18
+
19
+ // Core (Provider, Hook — use `@codefast/theme/core` for `ColorSchemeContext`)
20
+ export { AppearanceProvider } from "#/core/provider";
21
+ export type { AppearanceProviderProps } from "#/core/provider";
22
+ export { useColorScheme } from "#/core/use-theme";
23
+
24
+ // Script (FOUC prevention)
25
+ export { AppearanceScript } from "#/script/theme-script";
26
+ export type { AppearanceScriptProps } from "#/script/theme-script";
27
+
28
+ // Utilities: DOM + `getSystemColorScheme` live under `@codefast/theme/utils`
29
+ export { resolveColorScheme } from "#/utils/system";