@codefast/theme 0.5.0-canary.1 → 0.5.0-canary.3

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 +33 -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
@@ -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
+ }
@@ -0,0 +1,86 @@
1
+ import type { JSX } from "react";
2
+
3
+ import { appearances } from "#/appearance";
4
+ import type { Appearance } from "#/appearance";
5
+ import { DEFAULT_APPEARANCE, MEDIA, STORAGE_KEY } from "#/constants";
6
+
7
+ /* JSON.stringify does not escape </script>, so we replace the three characters that
8
+ * can form a closing tag: < > /. Unicode escapes are valid JS and safe in HTML. */
9
+ function toScriptSafe(value: unknown): string {
10
+ return JSON.stringify(value).replaceAll("<", "\\u003C").replaceAll(">", "\\u003E").replaceAll("/", "\\u002F");
11
+ }
12
+
13
+ /* Derived once from schema + constants — the inline script uses these to stay in sync */
14
+ const APPEARANCE_REMOVE_ARGS = appearances.map((s) => toScriptSafe(s)).join(",");
15
+ const APPEARANCE_VALID_CHECK = appearances.map((s) => `s===${toScriptSafe(s)}`).join("||");
16
+
17
+ /* -----------------------------------------------------------------------------
18
+ * Props
19
+ * -------------------------------------------------------------------------- */
20
+
21
+ /**
22
+ * @since 0.5.0-canary.2
23
+ */
24
+ export type AppearanceScriptProps = {
25
+ /**
26
+ * Fallback preference when the storage entry is absent or unrecognised.
27
+ * Defaults to {@link DEFAULT_APPEARANCE}.
28
+ */
29
+ readonly appearance?: Appearance;
30
+ /**
31
+ * CSP nonce applied to the inline script element.
32
+ */
33
+ readonly nonce?: string;
34
+ /**
35
+ * `localStorage` key the script reads before first paint — a recognised value (`"light"`,
36
+ * `"dark"`, or `"automatic"`) wins over `appearance`.
37
+ * Defaults to {@link STORAGE_KEY}; pair with `<AppearanceProvider>` using the **same key**.
38
+ */
39
+ readonly storageKey?: string;
40
+ };
41
+
42
+ /* -----------------------------------------------------------------------------
43
+ * Component
44
+ * -------------------------------------------------------------------------- */
45
+
46
+ /**
47
+ * Inline script that prevents Flash of Unstyled Content (FOUC).
48
+ *
49
+ * **Why this is needed:**
50
+ * React hydration occurs after the browser has already painted the page.
51
+ * Without this script, users would briefly see the wrong appearance before
52
+ * React takes over and applies the correct one.
53
+ *
54
+ * **How it works:**
55
+ * This script runs synchronously in the `<head>` before first paint:
56
+ * 1. Reads the stored preference from `localStorage`, falling back to `appearance`
57
+ * 2. Resolves 'automatic' to 'light' or 'dark' using `matchMedia()`
58
+ * 3. Removes prior `light` / `dark` / `automatic` classes on `<html>` (SSR may
59
+ * have applied the wrong resolved class for `automatic`, e.g. default `dark`)
60
+ * 4. Adds the resolved color scheme class and sets `color-scheme` for native controls
61
+ * 5. Writes the *preference* to `data-appearance` so preference-aware UI (e.g. a 3-state toggle)
62
+ * can render the right state from CSS on first paint, without a hydration flash
63
+ *
64
+ * @example
65
+ * ```tsx
66
+ * // In __root.tsx (TanStack Start)
67
+ * <head>
68
+ * <AppearanceScript />
69
+ * </head>
70
+ * ```
71
+ *
72
+ * @since 0.5.0-canary.2
73
+ */
74
+ export function AppearanceScript({
75
+ nonce,
76
+ storageKey = STORAGE_KEY,
77
+ appearance = DEFAULT_APPEARANCE,
78
+ }: AppearanceScriptProps): JSX.Element {
79
+ // toScriptSafe = JSON.stringify + escape <>/ so </script> cannot break out of the tag.
80
+ // The script reads localStorage before first paint so the stored preference applies
81
+ // without FOUC; an absent or invalid entry falls back to fb.
82
+ const appearanceScript = `(function(){try{var sk=${toScriptSafe(storageKey)},fb=${toScriptSafe(appearance)},s=localStorage.getItem(sk),appearance=(${APPEARANCE_VALID_CHECK})?s:fb,colorScheme=appearance;"automatic"===appearance&&(colorScheme=window.matchMedia(${toScriptSafe(MEDIA)}).matches?"dark":"light"),document.documentElement.classList.remove(${APPEARANCE_REMOVE_ARGS}),document.documentElement.classList.add(colorScheme),document.documentElement.style.colorScheme=colorScheme,document.documentElement.dataset.appearance=appearance}catch(e){}})()`;
83
+ const nonceProps = nonce === undefined ? {} : { nonce };
84
+
85
+ return <script dangerouslySetInnerHTML={{ __html: appearanceScript }} suppressHydrationWarning {...nonceProps} />;
86
+ }
@@ -0,0 +1,66 @@
1
+ import { z } from "zod";
2
+
3
+ /* -----------------------------------------------------------------------------
4
+ * Schema & Types
5
+ *
6
+ * Vocabulary follows Apple's Human Interface Guidelines: "appearance" is the
7
+ * user's preference (Light / Dark / Auto), "color scheme" is the resolved
8
+ * light-or-dark value actually applied (matching CSS `color-scheme` and
9
+ * `prefers-color-scheme`).
10
+ * -------------------------------------------------------------------------- */
11
+
12
+ /**
13
+ * Zod schema for appearance validation.
14
+ *
15
+ * Acts as the single source of truth for all appearance-related types.
16
+ * Valid values: 'light', 'dark', 'automatic'.
17
+ *
18
+ * @since 0.5.0-canary.2
19
+ */
20
+ export const appearanceSchema = z.enum(["light", "dark", "automatic"]);
21
+
22
+ /**
23
+ * User's appearance preference.
24
+ *
25
+ * - `'light'` - Force light appearance
26
+ * - `'dark'` - Force dark appearance
27
+ * - `'automatic'` - Follow OS preference
28
+ *
29
+ * @since 0.5.0-canary.2
30
+ */
31
+ export type Appearance = z.infer<typeof appearanceSchema>;
32
+
33
+ /**
34
+ * Color scheme actually applied to the UI after resolving 'automatic'.
35
+ *
36
+ * When the appearance is 'automatic', this reflects the OS preference (light/dark).
37
+ *
38
+ * @since 0.5.0-canary.2
39
+ */
40
+ export type ColorScheme = Exclude<Appearance, "automatic">;
41
+
42
+ /**
43
+ * Array of all available appearance options: `['light', 'dark', 'automatic']`.
44
+ *
45
+ * Useful for rendering appearance selectors in UI components.
46
+ *
47
+ * @since 0.5.0-canary.2
48
+ */
49
+ export const appearances = appearanceSchema.options;
50
+
51
+ /**
52
+ * Shape of the context value provided by AppearanceProvider.
53
+ *
54
+ * - `appearance` - Current appearance preference
55
+ * - `colorScheme` - Color scheme actually applied (automatic resolved to light/dark)
56
+ * - `setAppearance` - Async function to update the preference (triggers optimistic update)
57
+ * - `isPending` - True while an appearance change is being persisted
58
+ *
59
+ * @since 0.5.0-canary.2
60
+ */
61
+ export type AppearanceContextType = {
62
+ readonly isPending: boolean;
63
+ readonly colorScheme: ColorScheme;
64
+ readonly setAppearance: (value: Appearance) => Promise<void>;
65
+ readonly appearance: Appearance;
66
+ };
@@ -0,0 +1,42 @@
1
+ import type { Appearance, ColorScheme } from "#/appearance";
2
+ import { DEFAULT_COLOR_SCHEME, MEDIA } from "#/constants";
3
+
4
+ /* -----------------------------------------------------------------------------
5
+ * Color Scheme Resolution
6
+ * -------------------------------------------------------------------------- */
7
+
8
+ /**
9
+ * Detect the OS color scheme preference.
10
+ *
11
+ * Uses `matchMedia()` to query the `prefers-color-scheme` media feature.
12
+ * Returns {@link DEFAULT_COLOR_SCHEME} during SSR since `window` is unavailable.
13
+ *
14
+ * @returns 'light' or 'dark' based on OS preference
15
+ *
16
+ * @since 0.3.16-canary.0
17
+ */
18
+ export function getSystemColorScheme(): ColorScheme {
19
+ if (typeof globalThis.window === "undefined") {
20
+ return DEFAULT_COLOR_SCHEME;
21
+ }
22
+
23
+ return globalThis.window.matchMedia(MEDIA).matches ? "dark" : "light";
24
+ }
25
+
26
+ /**
27
+ * Resolve an appearance preference to the color scheme to apply.
28
+ *
29
+ * - 'light' → 'light'
30
+ * - 'dark' → 'dark'
31
+ * - 'automatic' → on the client, result of {@link getSystemColorScheme};
32
+ * on the server, {@link DEFAULT_COLOR_SCHEME}
33
+ *
34
+ * @since 0.3.16-canary.0
35
+ */
36
+ export function resolveColorScheme(appearance: Appearance): ColorScheme {
37
+ if (appearance !== "automatic") {
38
+ return appearance;
39
+ }
40
+
41
+ return getSystemColorScheme();
42
+ }
package/src/constants.ts CHANGED
@@ -1,35 +1,36 @@
1
- import type { ResolvedColorScheme, ColorScheme } from "#/types";
1
+ import type { Appearance, ColorScheme } from "#/appearance";
2
2
 
3
3
  /* -----------------------------------------------------------------------------
4
4
  * Public Constants
5
5
  * -------------------------------------------------------------------------- */
6
6
 
7
7
  /**
8
- * Default color scheme when no user preference exists.
8
+ * Default appearance preference when no stored value exists.
9
9
  *
10
10
  * Set to 'automatic' to respect OS preference by default.
11
11
  *
12
- * @since 0.3.16-canary.0
12
+ * @since 0.5.0-canary.2
13
13
  */
14
- export const DEFAULT_COLOR_SCHEME: ColorScheme = "automatic";
14
+ export const DEFAULT_APPEARANCE: Appearance = "automatic";
15
15
 
16
16
  /**
17
- * Fallback color scheme for SSR when system preference cannot be detected.
17
+ * Fallback color scheme when the system color scheme cannot be detected.
18
18
  *
19
- * Used during server-side rendering since `window.matchMedia()` is unavailable.
19
+ * Applies wherever `window.matchMedia()` is unavailable, e.g. during server render.
20
20
  *
21
- * @since 0.3.16-canary.0
21
+ * @since 0.5.0-canary.2
22
22
  */
23
- export const DEFAULT_RESOLVED_COLOR_SCHEME: ResolvedColorScheme = "dark";
23
+ export const DEFAULT_COLOR_SCHEME: ColorScheme = "dark";
24
24
 
25
25
  /**
26
- * Cookie name for the httpOnly color scheme preference (`@codefast/theme/start`).
26
+ * Default `localStorage` key for the appearance preference, shared by
27
+ * `AppearanceScript` and `AppearanceProvider`.
27
28
  *
28
- * Re-exported only from `@codefast/theme/constants` so custom middleware matches the adapter.
29
+ * Re-exported only from `@codefast/theme/constants` so custom integrations can match it exactly.
29
30
  *
30
31
  * @since 0.3.16-canary.0
31
32
  */
32
- export const STORAGE_KEY = "ui-theme";
33
+ export const STORAGE_KEY = "ui-appearance";
33
34
 
34
35
  /* -----------------------------------------------------------------------------
35
36
  * Internal Constants
@@ -44,9 +45,9 @@ export const STORAGE_KEY = "ui-theme";
44
45
  export const MEDIA = "(prefers-color-scheme: dark)";
45
46
 
46
47
  /**
47
- * BroadcastChannel name for cross-tab color scheme synchronization.
48
+ * BroadcastChannel name for cross-tab appearance synchronization.
48
49
  * @internal
49
50
  *
50
51
  * @since 0.3.16-canary.0
51
52
  */
52
- export const SYNC_CHANNEL = "color-scheme-sync";
53
+ export const SYNC_CHANNEL = "appearance-sync";
@@ -1,36 +1,34 @@
1
- import type { ResolvedColorScheme } from "#/types";
1
+ import type { ColorScheme } from "#/appearance";
2
2
 
3
3
  /* -----------------------------------------------------------------------------
4
4
  * DOM Utilities
5
5
  * -------------------------------------------------------------------------- */
6
6
 
7
7
  /**
8
- * Apply color scheme to the DOM by updating `<html>` element.
8
+ * Apply a color scheme to the DOM by updating the `<html>` element.
9
9
  *
10
10
  * Updates both:
11
11
  * - CSS class (for Tailwind's `dark:` variants)
12
12
  * - `color-scheme` style (for native form controls and scrollbars)
13
13
  *
14
- * @param resolved - The resolved color scheme to apply ('light' or 'dark')
15
- *
16
14
  * @since 0.3.16-canary.0
17
15
  */
18
- export function applyColorScheme(resolved: ResolvedColorScheme): void {
16
+ export function applyColorScheme(colorScheme: ColorScheme): void {
19
17
  const root = window.document.documentElement;
20
18
 
21
19
  root.classList.remove("light", "dark", "automatic");
22
- root.classList.add(resolved);
23
- root.style.colorScheme = resolved;
20
+ root.classList.add(colorScheme);
21
+ root.style.colorScheme = colorScheme;
24
22
  }
25
23
 
26
24
  /**
27
- * Temporarily suppress all CSS transitions during color scheme changes.
25
+ * Temporarily suppress all CSS transitions during appearance changes.
28
26
  *
29
27
  * Prevents jarring color animations when switching between light/dark appearances.
30
28
  * Respects user's `prefers-reduced-motion` preference (does nothing if enabled).
31
29
  *
32
30
  * @param nonce - Optional CSP nonce for the injected style element
33
- * @returns Cleanup function to re-enable transitions. Call after color scheme is applied.
31
+ * @returns Cleanup function to re-enable transitions. Call after the color scheme is applied.
34
32
  *
35
33
  * @example
36
34
  * ```tsx
@@ -64,7 +62,7 @@ export function suppressTransitions(nonce?: string): () => void {
64
62
  css.setAttribute("nonce", nonce);
65
63
  }
66
64
 
67
- // P3: Only the unprefixed property is needed — all modern browsers support it
65
+ // Only the unprefixed property is needed — all modern browsers support it
68
66
  css.append(document.createTextNode(`*,*::before,*::after{transition:none!important}`));
69
67
 
70
68
  document.head.append(css);