@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,74 @@
1
+ import { Appearance } from "./appearance.mjs";
2
+ import { JSX, ReactNode } from "react";
3
+
4
+ //#region src/appearance-provider.d.ts
5
+ /**
6
+ * @since 0.5.0-canary.2
7
+ */
8
+ type AppearanceProviderProps = {
9
+ readonly children: ReactNode;
10
+ /**
11
+ * When true, temporarily suppresses CSS transitions during appearance changes.
12
+ * Prevents jarring color animations when switching appearances.
13
+ * Default: false
14
+ */
15
+ readonly disableTransition?: boolean;
16
+ /**
17
+ * CSP nonce for inline styles when `disableTransition` is enabled.
18
+ */
19
+ readonly nonce?: string;
20
+ /**
21
+ * Custom async persistence for appearance changes; replaces the `localStorage` auto-persist.
22
+ */
23
+ readonly persistAppearance?: (value: Appearance) => Promise<void>;
24
+ /**
25
+ * Callback invoked when `persistAppearance` rejects.
26
+ */
27
+ readonly onPersistError?: (error: unknown, attemptedAppearance: Appearance) => void;
28
+ /**
29
+ * Fallback preference when storage has no valid entry — also what SSR renders.
30
+ * Defaults to {@link DEFAULT_APPEARANCE}.
31
+ */
32
+ readonly appearance?: Appearance;
33
+ /**
34
+ * `localStorage` key the preference is restored from and persisted under.
35
+ * Defaults to {@link STORAGE_KEY}; pair with `<AppearanceScript>` using the **same key**.
36
+ *
37
+ * The provider reads the stored value in its initial client render (so the first paint already
38
+ * matches the preference — no flash, no post-mount settle), auto-persists changes to
39
+ * `localStorage` (unless {@link persistAppearance} is also given, which then wins), and syncs
40
+ * across tabs via the `storage` event.
41
+ *
42
+ * @remarks SSR has no `localStorage`, so the server renders the {@link AppearanceProviderProps.appearance}
43
+ * prop. For a returning visitor whose stored preference differs, components that render
44
+ * preference-dependent markup hydrate-reconcile once; gate them behind a mounted flag to avoid that.
45
+ */
46
+ readonly storageKey?: string;
47
+ };
48
+ /**
49
+ * Provider component for appearance state management.
50
+ *
51
+ * **React 19 Features Used:**
52
+ * - `useOptimistic` - Immediate UI feedback while persisting the preference
53
+ * - `useSyncExternalStore` - SSR-safe subscription to the OS color scheme preference
54
+ * - `useEffectEvent` - Stable callback for cross-tab sync without effect re-runs
55
+ *
56
+ * @example
57
+ * ```tsx
58
+ * // In your root layout — pair with <AppearanceScript /> using the same storage key
59
+ * <AppearanceProvider>{children}</AppearanceProvider>
60
+ * ```
61
+ *
62
+ * @since 0.5.0-canary.2
63
+ */
64
+ declare function AppearanceProvider({
65
+ children,
66
+ disableTransition,
67
+ nonce,
68
+ onPersistError,
69
+ persistAppearance,
70
+ storageKey,
71
+ appearance: initialAppearance
72
+ }: AppearanceProviderProps): JSX.Element;
73
+ //#endregion
74
+ export { AppearanceProvider, AppearanceProviderProps };
@@ -0,0 +1,180 @@
1
+ import { AppearanceContext } from "./appearance-context.mjs";
2
+ import { appearanceSchema } from "./appearance.mjs";
3
+ import { DEFAULT_APPEARANCE, DEFAULT_COLOR_SCHEME, MEDIA, STORAGE_KEY, SYNC_CHANNEL } from "./constants.mjs";
4
+ import { getSystemColorScheme } from "./color-scheme.mjs";
5
+ import { applyColorScheme, suppressTransitions } from "./dom.mjs";
6
+ import { startTransition, useCallback, useEffect, useEffectEvent, useMemo, useOptimistic, useRef, useState, useSyncExternalStore } from "react";
7
+ import { jsx } from "react/jsx-runtime";
8
+ //#region src/appearance-provider.tsx
9
+ /**
10
+ * Subscribe to OS color scheme preference changes.
11
+ *
12
+ * @param callback - Function to call when the OS color scheme changes
13
+ * @returns Cleanup function to remove the listener
14
+ */
15
+ function subscribeToSystemColorScheme(callback) {
16
+ const mediaQuery = window.matchMedia(MEDIA);
17
+ mediaQuery.addEventListener("change", callback);
18
+ return () => {
19
+ mediaQuery.removeEventListener("change", callback);
20
+ };
21
+ }
22
+ /** SSR has no `matchMedia`; render the default until the first client snapshot takes over. */
23
+ function getServerSnapshot() {
24
+ return DEFAULT_COLOR_SCHEME;
25
+ }
26
+ /**
27
+ * Safely create an appearance BroadcastChannel when supported by the environment.
28
+ */
29
+ function createAppearanceChannel() {
30
+ if (typeof BroadcastChannel === "undefined") return null;
31
+ try {
32
+ return new BroadcastChannel(SYNC_CHANNEL);
33
+ } catch {
34
+ return null;
35
+ }
36
+ }
37
+ /**
38
+ * Read + validate the persisted preference from localStorage. Returns null when unavailable
39
+ * (SSR, private mode) or when the stored value is not a recognised appearance.
40
+ */
41
+ function readAppearanceFromStorage(storageKey) {
42
+ if (typeof globalThis.window === "undefined") return null;
43
+ try {
44
+ const result = appearanceSchema.safeParse(globalThis.window.localStorage.getItem(storageKey));
45
+ return result.success ? result.data : null;
46
+ } catch {
47
+ return null;
48
+ }
49
+ }
50
+ /**
51
+ * Provider component for appearance state management.
52
+ *
53
+ * **React 19 Features Used:**
54
+ * - `useOptimistic` - Immediate UI feedback while persisting the preference
55
+ * - `useSyncExternalStore` - SSR-safe subscription to the OS color scheme preference
56
+ * - `useEffectEvent` - Stable callback for cross-tab sync without effect re-runs
57
+ *
58
+ * @example
59
+ * ```tsx
60
+ * // In your root layout — pair with <AppearanceScript /> using the same storage key
61
+ * <AppearanceProvider>{children}</AppearanceProvider>
62
+ * ```
63
+ *
64
+ * @since 0.5.0-canary.2
65
+ */
66
+ function AppearanceProvider({ children, disableTransition = false, nonce, onPersistError, persistAppearance, storageKey = STORAGE_KEY, appearance: initialAppearance = DEFAULT_APPEARANCE }) {
67
+ const safeInitialAppearance = appearanceSchema.safeParse(initialAppearance).success ? initialAppearance : DEFAULT_APPEARANCE;
68
+ const [appearance, setAppearanceState] = useState(() => readAppearanceFromStorage(storageKey) ?? safeInitialAppearance);
69
+ const [optimisticAppearance, setOptimisticAppearance] = useOptimistic(appearance);
70
+ const isPending = optimisticAppearance !== appearance;
71
+ const committedAppearanceRef = useRef(appearance);
72
+ committedAppearanceRef.current = appearance;
73
+ const channelRef = useRef(null);
74
+ const enableTransitionsRef = useRef(null);
75
+ const intentRef = useRef(null);
76
+ const persist = useMemo(() => {
77
+ if (persistAppearance) return persistAppearance;
78
+ return async (value) => {
79
+ try {
80
+ globalThis.window.localStorage.setItem(storageKey, value);
81
+ } catch {}
82
+ };
83
+ }, [persistAppearance, storageKey]);
84
+ const systemColorScheme = useSyncExternalStore(subscribeToSystemColorScheme, getSystemColorScheme, getServerSnapshot);
85
+ const colorScheme = useMemo(() => optimisticAppearance === "automatic" ? systemColorScheme : optimisticAppearance, [optimisticAppearance, systemColorScheme]);
86
+ useEffect(() => {
87
+ applyColorScheme(colorScheme);
88
+ const enable = enableTransitionsRef.current;
89
+ if (enable) {
90
+ enableTransitionsRef.current = null;
91
+ enable();
92
+ }
93
+ }, [colorScheme]);
94
+ useEffect(() => {
95
+ globalThis.window.document.documentElement.dataset.appearance = optimisticAppearance;
96
+ }, [optimisticAppearance]);
97
+ const handleCrossTabMessage = useEffectEvent((event) => {
98
+ const result = appearanceSchema.safeParse(event.data);
99
+ if (!result.success || result.data === appearance) return;
100
+ startTransition(() => {
101
+ setAppearanceState(result.data);
102
+ });
103
+ });
104
+ const handleStorageEvent = useEffectEvent((event) => {
105
+ if (event.key !== storageKey) return;
106
+ const result = appearanceSchema.safeParse(event.newValue);
107
+ if (!result.success || result.data === appearance) return;
108
+ startTransition(() => {
109
+ setAppearanceState(result.data);
110
+ });
111
+ });
112
+ useEffect(() => {
113
+ const channel = createAppearanceChannel();
114
+ if (!channel) return;
115
+ channelRef.current = channel;
116
+ channel.addEventListener("message", handleCrossTabMessage);
117
+ return () => {
118
+ channelRef.current = null;
119
+ channel.removeEventListener("message", handleCrossTabMessage);
120
+ channel.close();
121
+ };
122
+ }, []);
123
+ useEffect(() => {
124
+ globalThis.window.addEventListener("storage", handleStorageEvent);
125
+ return () => {
126
+ globalThis.window.removeEventListener("storage", handleStorageEvent);
127
+ };
128
+ }, []);
129
+ const setAppearance = useCallback(async (value) => {
130
+ await Promise.resolve();
131
+ if (value === committedAppearanceRef.current) return;
132
+ if (disableTransition) enableTransitionsRef.current = suppressTransitions(nonce);
133
+ startTransition(async () => {
134
+ intentRef.current = value;
135
+ setOptimisticAppearance(value);
136
+ try {
137
+ await persist(value);
138
+ if (intentRef.current === value) {
139
+ setAppearanceState(value);
140
+ channelRef.current?.postMessage(value);
141
+ }
142
+ } catch (error) {
143
+ if (onPersistError) try {
144
+ onPersistError(error, value);
145
+ } catch (callbackError) {
146
+ console.error("Failed to handle appearance persist error:", callbackError);
147
+ }
148
+ else console.error("Failed to set appearance:", error);
149
+ } finally {
150
+ const enable = enableTransitionsRef.current;
151
+ if (enable) {
152
+ enableTransitionsRef.current = null;
153
+ enable();
154
+ }
155
+ }
156
+ });
157
+ }, [
158
+ disableTransition,
159
+ nonce,
160
+ setOptimisticAppearance,
161
+ persist,
162
+ onPersistError
163
+ ]);
164
+ return /* @__PURE__ */ jsx(AppearanceContext, {
165
+ value: useMemo(() => ({
166
+ isPending,
167
+ colorScheme,
168
+ setAppearance,
169
+ appearance: optimisticAppearance
170
+ }), [
171
+ optimisticAppearance,
172
+ colorScheme,
173
+ setAppearance,
174
+ isPending
175
+ ]),
176
+ children
177
+ });
178
+ }
179
+ //#endregion
180
+ export { AppearanceProvider };
@@ -0,0 +1,59 @@
1
+ import { Appearance } from "./appearance.mjs";
2
+ import { JSX } from "react";
3
+
4
+ //#region src/appearance-script.d.ts
5
+ /**
6
+ * @since 0.5.0-canary.2
7
+ */
8
+ type AppearanceScriptProps = {
9
+ /**
10
+ * Fallback preference when the storage entry is absent or unrecognised.
11
+ * Defaults to {@link DEFAULT_APPEARANCE}.
12
+ */
13
+ readonly appearance?: Appearance;
14
+ /**
15
+ * CSP nonce applied to the inline script element.
16
+ */
17
+ readonly nonce?: string;
18
+ /**
19
+ * `localStorage` key the script reads before first paint — a recognised value (`"light"`,
20
+ * `"dark"`, or `"automatic"`) wins over `appearance`.
21
+ * Defaults to {@link STORAGE_KEY}; pair with `<AppearanceProvider>` using the **same key**.
22
+ */
23
+ readonly storageKey?: string;
24
+ };
25
+ /**
26
+ * Inline script that prevents Flash of Unstyled Content (FOUC).
27
+ *
28
+ * **Why this is needed:**
29
+ * React hydration occurs after the browser has already painted the page.
30
+ * Without this script, users would briefly see the wrong appearance before
31
+ * React takes over and applies the correct one.
32
+ *
33
+ * **How it works:**
34
+ * This script runs synchronously in the `<head>` before first paint:
35
+ * 1. Reads the stored preference from `localStorage`, falling back to `appearance`
36
+ * 2. Resolves 'automatic' to 'light' or 'dark' using `matchMedia()`
37
+ * 3. Removes prior `light` / `dark` / `automatic` classes on `<html>` (SSR may
38
+ * have applied the wrong resolved class for `automatic`, e.g. default `dark`)
39
+ * 4. Adds the resolved color scheme class and sets `color-scheme` for native controls
40
+ * 5. Writes the *preference* to `data-appearance` so preference-aware UI (e.g. a 3-state toggle)
41
+ * can render the right state from CSS on first paint, without a hydration flash
42
+ *
43
+ * @example
44
+ * ```tsx
45
+ * // In __root.tsx (TanStack Start)
46
+ * <head>
47
+ * <AppearanceScript />
48
+ * </head>
49
+ * ```
50
+ *
51
+ * @since 0.5.0-canary.2
52
+ */
53
+ declare function AppearanceScript({
54
+ nonce,
55
+ storageKey,
56
+ appearance
57
+ }: AppearanceScriptProps): JSX.Element;
58
+ //#endregion
59
+ export { AppearanceScript, AppearanceScriptProps };
@@ -0,0 +1,46 @@
1
+ import { appearances } from "./appearance.mjs";
2
+ import { DEFAULT_APPEARANCE, MEDIA, STORAGE_KEY } from "./constants.mjs";
3
+ import { jsx } from "react/jsx-runtime";
4
+ //#region src/appearance-script.tsx
5
+ function toScriptSafe(value) {
6
+ return JSON.stringify(value).replaceAll("<", "\\u003C").replaceAll(">", "\\u003E").replaceAll("/", "\\u002F");
7
+ }
8
+ const APPEARANCE_REMOVE_ARGS = appearances.map((s) => toScriptSafe(s)).join(",");
9
+ const APPEARANCE_VALID_CHECK = appearances.map((s) => `s===${toScriptSafe(s)}`).join("||");
10
+ /**
11
+ * Inline script that prevents Flash of Unstyled Content (FOUC).
12
+ *
13
+ * **Why this is needed:**
14
+ * React hydration occurs after the browser has already painted the page.
15
+ * Without this script, users would briefly see the wrong appearance before
16
+ * React takes over and applies the correct one.
17
+ *
18
+ * **How it works:**
19
+ * This script runs synchronously in the `<head>` before first paint:
20
+ * 1. Reads the stored preference from `localStorage`, falling back to `appearance`
21
+ * 2. Resolves 'automatic' to 'light' or 'dark' using `matchMedia()`
22
+ * 3. Removes prior `light` / `dark` / `automatic` classes on `<html>` (SSR may
23
+ * have applied the wrong resolved class for `automatic`, e.g. default `dark`)
24
+ * 4. Adds the resolved color scheme class and sets `color-scheme` for native controls
25
+ * 5. Writes the *preference* to `data-appearance` so preference-aware UI (e.g. a 3-state toggle)
26
+ * can render the right state from CSS on first paint, without a hydration flash
27
+ *
28
+ * @example
29
+ * ```tsx
30
+ * // In __root.tsx (TanStack Start)
31
+ * <head>
32
+ * <AppearanceScript />
33
+ * </head>
34
+ * ```
35
+ *
36
+ * @since 0.5.0-canary.2
37
+ */
38
+ function AppearanceScript({ nonce, storageKey = STORAGE_KEY, appearance = DEFAULT_APPEARANCE }) {
39
+ return /* @__PURE__ */ jsx("script", {
40
+ dangerouslySetInnerHTML: { __html: `(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){}})()` },
41
+ suppressHydrationWarning: true,
42
+ ...nonce === void 0 ? {} : { nonce }
43
+ });
44
+ }
45
+ //#endregion
46
+ export { AppearanceScript };
@@ -0,0 +1,60 @@
1
+ import { z } from "zod";
2
+
3
+ //#region src/appearance.d.ts
4
+ /**
5
+ * Zod schema for appearance validation.
6
+ *
7
+ * Acts as the single source of truth for all appearance-related types.
8
+ * Valid values: 'light', 'dark', 'automatic'.
9
+ *
10
+ * @since 0.5.0-canary.2
11
+ */
12
+ declare const appearanceSchema: z.ZodEnum<{
13
+ light: "light";
14
+ dark: "dark";
15
+ automatic: "automatic";
16
+ }>;
17
+ /**
18
+ * User's appearance preference.
19
+ *
20
+ * - `'light'` - Force light appearance
21
+ * - `'dark'` - Force dark appearance
22
+ * - `'automatic'` - Follow OS preference
23
+ *
24
+ * @since 0.5.0-canary.2
25
+ */
26
+ type Appearance = z.infer<typeof appearanceSchema>;
27
+ /**
28
+ * Color scheme actually applied to the UI after resolving 'automatic'.
29
+ *
30
+ * When the appearance is 'automatic', this reflects the OS preference (light/dark).
31
+ *
32
+ * @since 0.5.0-canary.2
33
+ */
34
+ type ColorScheme = Exclude<Appearance, "automatic">;
35
+ /**
36
+ * Array of all available appearance options: `['light', 'dark', 'automatic']`.
37
+ *
38
+ * Useful for rendering appearance selectors in UI components.
39
+ *
40
+ * @since 0.5.0-canary.2
41
+ */
42
+ declare const appearances: ("light" | "dark" | "automatic")[];
43
+ /**
44
+ * Shape of the context value provided by AppearanceProvider.
45
+ *
46
+ * - `appearance` - Current appearance preference
47
+ * - `colorScheme` - Color scheme actually applied (automatic resolved to light/dark)
48
+ * - `setAppearance` - Async function to update the preference (triggers optimistic update)
49
+ * - `isPending` - True while an appearance change is being persisted
50
+ *
51
+ * @since 0.5.0-canary.2
52
+ */
53
+ type AppearanceContextType = {
54
+ readonly isPending: boolean;
55
+ readonly colorScheme: ColorScheme;
56
+ readonly setAppearance: (value: Appearance) => Promise<void>;
57
+ readonly appearance: Appearance;
58
+ };
59
+ //#endregion
60
+ export { Appearance, AppearanceContextType, ColorScheme, appearanceSchema, appearances };
@@ -0,0 +1,25 @@
1
+ import { z } from "zod";
2
+ //#region src/appearance.ts
3
+ /**
4
+ * Zod schema for appearance validation.
5
+ *
6
+ * Acts as the single source of truth for all appearance-related types.
7
+ * Valid values: 'light', 'dark', 'automatic'.
8
+ *
9
+ * @since 0.5.0-canary.2
10
+ */
11
+ const appearanceSchema = z.enum([
12
+ "light",
13
+ "dark",
14
+ "automatic"
15
+ ]);
16
+ /**
17
+ * Array of all available appearance options: `['light', 'dark', 'automatic']`.
18
+ *
19
+ * Useful for rendering appearance selectors in UI components.
20
+ *
21
+ * @since 0.5.0-canary.2
22
+ */
23
+ const appearances = appearanceSchema.options;
24
+ //#endregion
25
+ export { appearanceSchema, appearances };
@@ -0,0 +1,27 @@
1
+ import { Appearance, ColorScheme } from "./appearance.mjs";
2
+
3
+ //#region src/color-scheme.d.ts
4
+ /**
5
+ * Detect the OS color scheme preference.
6
+ *
7
+ * Uses `matchMedia()` to query the `prefers-color-scheme` media feature.
8
+ * Returns {@link DEFAULT_COLOR_SCHEME} during SSR since `window` is unavailable.
9
+ *
10
+ * @returns 'light' or 'dark' based on OS preference
11
+ *
12
+ * @since 0.3.16-canary.0
13
+ */
14
+ declare function getSystemColorScheme(): ColorScheme;
15
+ /**
16
+ * Resolve an appearance preference to the color scheme to apply.
17
+ *
18
+ * - 'light' → 'light'
19
+ * - 'dark' → 'dark'
20
+ * - 'automatic' → on the client, result of {@link getSystemColorScheme};
21
+ * on the server, {@link DEFAULT_COLOR_SCHEME}
22
+ *
23
+ * @since 0.3.16-canary.0
24
+ */
25
+ declare function resolveColorScheme(appearance: Appearance): ColorScheme;
26
+ //#endregion
27
+ export { getSystemColorScheme, resolveColorScheme };
@@ -0,0 +1,32 @@
1
+ import { DEFAULT_COLOR_SCHEME } from "./constants.mjs";
2
+ //#region src/color-scheme.ts
3
+ /**
4
+ * Detect the OS color scheme preference.
5
+ *
6
+ * Uses `matchMedia()` to query the `prefers-color-scheme` media feature.
7
+ * Returns {@link DEFAULT_COLOR_SCHEME} during SSR since `window` is unavailable.
8
+ *
9
+ * @returns 'light' or 'dark' based on OS preference
10
+ *
11
+ * @since 0.3.16-canary.0
12
+ */
13
+ function getSystemColorScheme() {
14
+ if (typeof globalThis.window === "undefined") return DEFAULT_COLOR_SCHEME;
15
+ return globalThis.window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
16
+ }
17
+ /**
18
+ * Resolve an appearance preference to the color scheme to apply.
19
+ *
20
+ * - 'light' → 'light'
21
+ * - 'dark' → 'dark'
22
+ * - 'automatic' → on the client, result of {@link getSystemColorScheme};
23
+ * on the server, {@link DEFAULT_COLOR_SCHEME}
24
+ *
25
+ * @since 0.3.16-canary.0
26
+ */
27
+ function resolveColorScheme(appearance) {
28
+ if (appearance !== "automatic") return appearance;
29
+ return getSystemColorScheme();
30
+ }
31
+ //#endregion
32
+ export { getSystemColorScheme, resolveColorScheme };
@@ -1,30 +1,31 @@
1
- import { ColorScheme, ResolvedColorScheme } from "./types.mjs";
1
+ import { Appearance, ColorScheme } from "./appearance.mjs";
2
2
 
3
3
  //#region src/constants.d.ts
4
4
  /**
5
- * Default color scheme when no user preference exists.
5
+ * Default appearance preference when no stored value exists.
6
6
  *
7
7
  * Set to 'automatic' to respect OS preference by default.
8
8
  *
9
- * @since 0.3.16-canary.0
9
+ * @since 0.5.0-canary.2
10
10
  */
11
- declare const DEFAULT_COLOR_SCHEME: ColorScheme;
11
+ declare const DEFAULT_APPEARANCE: Appearance;
12
12
  /**
13
- * Fallback color scheme for SSR when system preference cannot be detected.
13
+ * Fallback color scheme when the system color scheme cannot be detected.
14
14
  *
15
- * Used during server-side rendering since `window.matchMedia()` is unavailable.
15
+ * Applies wherever `window.matchMedia()` is unavailable, e.g. during server render.
16
16
  *
17
- * @since 0.3.16-canary.0
17
+ * @since 0.5.0-canary.2
18
18
  */
19
- declare const DEFAULT_RESOLVED_COLOR_SCHEME: ResolvedColorScheme;
19
+ declare const DEFAULT_COLOR_SCHEME: ColorScheme;
20
20
  /**
21
- * Cookie name for the httpOnly color scheme preference (`@codefast/theme/start`).
21
+ * Default `localStorage` key for the appearance preference, shared by
22
+ * `AppearanceScript` and `AppearanceProvider`.
22
23
  *
23
- * Re-exported only from `@codefast/theme/constants` so custom middleware matches the adapter.
24
+ * Re-exported only from `@codefast/theme/constants` so custom integrations can match it exactly.
24
25
  *
25
26
  * @since 0.3.16-canary.0
26
27
  */
27
- declare const STORAGE_KEY = "ui-theme";
28
+ declare const STORAGE_KEY = "ui-appearance";
28
29
  /**
29
30
  * CSS media query for detecting dark mode preference.
30
31
  * @internal
@@ -33,11 +34,11 @@ declare const STORAGE_KEY = "ui-theme";
33
34
  */
34
35
  declare const MEDIA = "(prefers-color-scheme: dark)";
35
36
  /**
36
- * BroadcastChannel name for cross-tab color scheme synchronization.
37
+ * BroadcastChannel name for cross-tab appearance synchronization.
37
38
  * @internal
38
39
  *
39
40
  * @since 0.3.16-canary.0
40
41
  */
41
- declare const SYNC_CHANNEL = "color-scheme-sync";
42
+ declare const SYNC_CHANNEL = "appearance-sync";
42
43
  //#endregion
43
- export { DEFAULT_COLOR_SCHEME, DEFAULT_RESOLVED_COLOR_SCHEME, MEDIA, STORAGE_KEY, SYNC_CHANNEL };
44
+ export { DEFAULT_APPEARANCE, DEFAULT_COLOR_SCHEME, MEDIA, STORAGE_KEY, SYNC_CHANNEL };
@@ -1,28 +1,29 @@
1
1
  //#region src/constants.ts
2
2
  /**
3
- * Default color scheme when no user preference exists.
3
+ * Default appearance preference when no stored value exists.
4
4
  *
5
5
  * Set to 'automatic' to respect OS preference by default.
6
6
  *
7
- * @since 0.3.16-canary.0
7
+ * @since 0.5.0-canary.2
8
8
  */
9
- const DEFAULT_COLOR_SCHEME = "automatic";
9
+ const DEFAULT_APPEARANCE = "automatic";
10
10
  /**
11
- * Fallback color scheme for SSR when system preference cannot be detected.
11
+ * Fallback color scheme when the system color scheme cannot be detected.
12
12
  *
13
- * Used during server-side rendering since `window.matchMedia()` is unavailable.
13
+ * Applies wherever `window.matchMedia()` is unavailable, e.g. during server render.
14
14
  *
15
- * @since 0.3.16-canary.0
15
+ * @since 0.5.0-canary.2
16
16
  */
17
- const DEFAULT_RESOLVED_COLOR_SCHEME = "dark";
17
+ const DEFAULT_COLOR_SCHEME = "dark";
18
18
  /**
19
- * Cookie name for the httpOnly color scheme preference (`@codefast/theme/start`).
19
+ * Default `localStorage` key for the appearance preference, shared by
20
+ * `AppearanceScript` and `AppearanceProvider`.
20
21
  *
21
- * Re-exported only from `@codefast/theme/constants` so custom middleware matches the adapter.
22
+ * Re-exported only from `@codefast/theme/constants` so custom integrations can match it exactly.
22
23
  *
23
24
  * @since 0.3.16-canary.0
24
25
  */
25
- const STORAGE_KEY = "ui-theme";
26
+ const STORAGE_KEY = "ui-appearance";
26
27
  /**
27
28
  * CSS media query for detecting dark mode preference.
28
29
  * @internal
@@ -31,11 +32,11 @@ const STORAGE_KEY = "ui-theme";
31
32
  */
32
33
  const MEDIA = "(prefers-color-scheme: dark)";
33
34
  /**
34
- * BroadcastChannel name for cross-tab color scheme synchronization.
35
+ * BroadcastChannel name for cross-tab appearance synchronization.
35
36
  * @internal
36
37
  *
37
38
  * @since 0.3.16-canary.0
38
39
  */
39
- const SYNC_CHANNEL = "color-scheme-sync";
40
+ const SYNC_CHANNEL = "appearance-sync";
40
41
  //#endregion
41
- export { DEFAULT_COLOR_SCHEME, DEFAULT_RESOLVED_COLOR_SCHEME, MEDIA, STORAGE_KEY, SYNC_CHANNEL };
42
+ export { DEFAULT_APPEARANCE, DEFAULT_COLOR_SCHEME, MEDIA, STORAGE_KEY, SYNC_CHANNEL };
@@ -1,26 +1,24 @@
1
- import { ResolvedColorScheme } from "../types.mjs";
1
+ import { ColorScheme } from "./appearance.mjs";
2
2
 
3
- //#region src/utils/dom.d.ts
3
+ //#region src/dom.d.ts
4
4
  /**
5
- * Apply color scheme to the DOM by updating `<html>` element.
5
+ * Apply a color scheme to the DOM by updating the `<html>` element.
6
6
  *
7
7
  * Updates both:
8
8
  * - CSS class (for Tailwind's `dark:` variants)
9
9
  * - `color-scheme` style (for native form controls and scrollbars)
10
10
  *
11
- * @param resolved - The resolved color scheme to apply ('light' or 'dark')
12
- *
13
11
  * @since 0.3.16-canary.0
14
12
  */
15
- declare function applyColorScheme(resolved: ResolvedColorScheme): void;
13
+ declare function applyColorScheme(colorScheme: ColorScheme): void;
16
14
  /**
17
- * Temporarily suppress all CSS transitions during color scheme changes.
15
+ * Temporarily suppress all CSS transitions during appearance changes.
18
16
  *
19
17
  * Prevents jarring color animations when switching between light/dark appearances.
20
18
  * Respects user's `prefers-reduced-motion` preference (does nothing if enabled).
21
19
  *
22
20
  * @param nonce - Optional CSP nonce for the injected style element
23
- * @returns Cleanup function to re-enable transitions. Call after color scheme is applied.
21
+ * @returns Cleanup function to re-enable transitions. Call after the color scheme is applied.
24
22
  *
25
23
  * @example
26
24
  * ```tsx