@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,231 +0,0 @@
1
- import { DEFAULT_COLOR_SCHEME, MEDIA, SYNC_CHANNEL } from "../constants.mjs";
2
- import { colorSchemeSchema } from "../types.mjs";
3
- import { ColorSchemeContext } from "./context.mjs";
4
- import { applyColorScheme, suppressTransitions } from "../utils/dom.mjs";
5
- import { getSystemColorScheme } from "../utils/system.mjs";
6
- import { startTransition, useCallback, useEffect, useEffectEvent, useMemo, useOptimistic, useRef, useState, useSyncExternalStore } from "react";
7
- import { jsx } from "react/jsx-runtime";
8
- //#region src/core/provider.tsx
9
- /**
10
- * Subscribe to OS color scheme preference changes.
11
- *
12
- * @param callback - Function to call when system 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
- /**
23
- * Safely create a color scheme BroadcastChannel when supported by the environment.
24
- */
25
- function createColorSchemeChannel() {
26
- if (typeof BroadcastChannel === "undefined") return null;
27
- try {
28
- return new BroadcastChannel(SYNC_CHANNEL);
29
- } catch {
30
- return null;
31
- }
32
- }
33
- /**
34
- * Read + validate the persisted preference from localStorage. Returns null when unavailable
35
- * (SSR, private mode) or when the stored value is not a recognised scheme.
36
- */
37
- function readColorSchemeFromStorage(storageKey) {
38
- if (typeof globalThis.window === "undefined") return null;
39
- try {
40
- const result = colorSchemeSchema.safeParse(globalThis.window.localStorage.getItem(storageKey));
41
- return result.success ? result.data : null;
42
- } catch {
43
- return null;
44
- }
45
- }
46
- /**
47
- * Provider component for color scheme state management.
48
- *
49
- * **React 19 Features Used:**
50
- * - `useOptimistic` - Immediate UI feedback while persisting color scheme
51
- * - `useSyncExternalStore` - SSR-safe subscription to OS color scheme preference
52
- * - `useEffectEvent` - Stable callback for cross-tab sync without effect re-runs
53
- *
54
- * @param props - Component props
55
- * @param props.children - React tree to provide context for
56
- * @param props.colorScheme - Initial preference from the server (cookie, loader, etc.)
57
- * @param props.ssrColorScheme - Best-effort `light` or `dark` from the SSR request
58
- * (e.g. `Sec-CH-Prefers-Color-Scheme`). When preference is `automatic`, this value is used as
59
- * `useSyncExternalStore`'s server snapshot so the first client snapshot matches `matchMedia`
60
- * and avoids a post-hydration flip. Omit if unavailable; falls back to {@link DEFAULT_RESOLVED_COLOR_SCHEME}.
61
- * @param props.syncFromServer - Optional one-shot RPC after mount to align with the cookie when SSR/HTML was stale.
62
- * @param props.storageKey - Optional localStorage key for the client-only path: restore in the initial render, auto-persist, cross-tab sync.
63
- * @param props.persistColorScheme - Optional async handler to persist preference (cookie, server action, …)
64
- * @param props.onPersistError - Optional callback for persistence failures
65
- * @param props.disableTransition - Temporarily suppress CSS transitions on color scheme change
66
- * @param props.nonce - CSP nonce for inline transition-blocking styles when `disableTransition` is set
67
- * @returns Provider element wrapping `children`
68
- *
69
- * @example
70
- * ```tsx
71
- * // In your root layout
72
- * <AppearanceProvider
73
- * colorScheme={colorScheme}
74
- * persistColorScheme={(value) => setColorSchemeServerFn({ data: value })}
75
- * >
76
- * {children}
77
- * </AppearanceProvider>
78
- * ```
79
- *
80
- * @since 0.3.16-canary.0
81
- */
82
- function AppearanceProvider({ children, disableTransition = false, nonce, onPersistError, persistColorScheme, ssrColorScheme, storageKey, syncFromServer, colorScheme: initialColorScheme }) {
83
- const safeInitialColorScheme = colorSchemeSchema.safeParse(initialColorScheme).success ? initialColorScheme : DEFAULT_COLOR_SCHEME;
84
- const [colorScheme, setColorSchemeState] = useState(() => {
85
- if (storageKey !== void 0) {
86
- const stored = readColorSchemeFromStorage(storageKey);
87
- if (stored !== null) return stored;
88
- }
89
- return safeInitialColorScheme;
90
- });
91
- const [optimisticColorScheme, setOptimisticColorScheme] = useOptimistic(colorScheme);
92
- const isPending = optimisticColorScheme !== colorScheme;
93
- const committedColorSchemeRef = useRef(colorScheme);
94
- committedColorSchemeRef.current = colorScheme;
95
- const channelRef = useRef(null);
96
- const enableTransitionsRef = useRef(null);
97
- const intentRef = useRef(null);
98
- const persist = useMemo(() => {
99
- if (persistColorScheme) return persistColorScheme;
100
- if (storageKey === void 0) return;
101
- return async (value) => {
102
- try {
103
- globalThis.window.localStorage.setItem(storageKey, value);
104
- } catch {}
105
- };
106
- }, [persistColorScheme, storageKey]);
107
- useEffect(() => {
108
- if (storageKey !== void 0) return;
109
- startTransition(() => {
110
- setColorSchemeState((prev) => prev === safeInitialColorScheme ? prev : safeInitialColorScheme);
111
- });
112
- }, [safeInitialColorScheme, storageKey]);
113
- const syncFromServerRef = useRef(syncFromServer);
114
- syncFromServerRef.current = syncFromServer;
115
- useEffect(() => {
116
- const sync = syncFromServerRef.current;
117
- if (!sync) return;
118
- let cancelled = false;
119
- (async () => {
120
- try {
121
- const serverColorScheme = await sync();
122
- if (cancelled) return;
123
- startTransition(() => {
124
- setColorSchemeState((prev) => prev === serverColorScheme ? prev : serverColorScheme);
125
- });
126
- } catch {}
127
- })();
128
- return () => {
129
- cancelled = true;
130
- };
131
- }, []);
132
- const systemColorScheme = useSyncExternalStore(subscribeToSystemColorScheme, getSystemColorScheme, useCallback(() => {
133
- return ssrColorScheme ?? "dark";
134
- }, [ssrColorScheme]));
135
- const resolvedColorScheme = useMemo(() => optimisticColorScheme === "automatic" ? systemColorScheme : optimisticColorScheme, [optimisticColorScheme, systemColorScheme]);
136
- useEffect(() => {
137
- applyColorScheme(resolvedColorScheme);
138
- const enable = enableTransitionsRef.current;
139
- if (enable) {
140
- enableTransitionsRef.current = null;
141
- enable();
142
- }
143
- }, [resolvedColorScheme]);
144
- useEffect(() => {
145
- globalThis.window.document.documentElement.dataset.appearance = optimisticColorScheme;
146
- }, [optimisticColorScheme]);
147
- const handleCrossTabMessage = useEffectEvent((event) => {
148
- const result = colorSchemeSchema.safeParse(event.data);
149
- if (!result.success || result.data === colorScheme) return;
150
- startTransition(() => {
151
- setColorSchemeState(result.data);
152
- });
153
- });
154
- const handleStorageEvent = useEffectEvent((event) => {
155
- if (event.key !== storageKey) return;
156
- const result = colorSchemeSchema.safeParse(event.newValue);
157
- if (!result.success || result.data === colorScheme) return;
158
- startTransition(() => {
159
- setColorSchemeState(result.data);
160
- });
161
- });
162
- useEffect(() => {
163
- const channel = createColorSchemeChannel();
164
- if (!channel) return;
165
- channelRef.current = channel;
166
- channel.addEventListener("message", handleCrossTabMessage);
167
- return () => {
168
- channelRef.current = null;
169
- channel.removeEventListener("message", handleCrossTabMessage);
170
- channel.close();
171
- };
172
- }, []);
173
- useEffect(() => {
174
- if (storageKey === void 0) return;
175
- globalThis.window.addEventListener("storage", handleStorageEvent);
176
- return () => {
177
- globalThis.window.removeEventListener("storage", handleStorageEvent);
178
- };
179
- }, [storageKey]);
180
- const setColorScheme = useCallback(async (value) => {
181
- await Promise.resolve();
182
- if (value === committedColorSchemeRef.current) return;
183
- if (disableTransition) enableTransitionsRef.current = suppressTransitions(nonce);
184
- startTransition(async () => {
185
- intentRef.current = value;
186
- setOptimisticColorScheme(value);
187
- try {
188
- if (persist) await persist(value);
189
- if (intentRef.current === value) {
190
- setColorSchemeState(value);
191
- channelRef.current?.postMessage(value);
192
- }
193
- } catch (error) {
194
- if (onPersistError) try {
195
- onPersistError(error, value);
196
- } catch (callbackError) {
197
- console.error("Failed to handle color scheme persist error:", callbackError);
198
- }
199
- else console.error("Failed to set color scheme:", error);
200
- } finally {
201
- const enable = enableTransitionsRef.current;
202
- if (enable) {
203
- enableTransitionsRef.current = null;
204
- enable();
205
- }
206
- }
207
- });
208
- }, [
209
- disableTransition,
210
- nonce,
211
- setOptimisticColorScheme,
212
- persist,
213
- onPersistError
214
- ]);
215
- return /* @__PURE__ */ jsx(ColorSchemeContext, {
216
- value: useMemo(() => ({
217
- isPending,
218
- resolvedColorScheme,
219
- setColorScheme,
220
- colorScheme: optimisticColorScheme
221
- }), [
222
- optimisticColorScheme,
223
- resolvedColorScheme,
224
- setColorScheme,
225
- isPending
226
- ]),
227
- children
228
- });
229
- }
230
- //#endregion
231
- export { AppearanceProvider };
@@ -1,34 +0,0 @@
1
- import { ColorSchemeContextType } from "../types.mjs";
2
-
3
- //#region src/core/use-theme.d.ts
4
- /**
5
- * Hook to access color scheme context.
6
- *
7
- * Uses React 19's `use()` API for context consumption, enabling:
8
- * - Conditional context reading
9
- * - Better Suspense boundary integration
10
- *
11
- * @returns Color scheme context with `colorScheme`, `resolvedColorScheme`, `setPreferredColorScheme`, and `isPending`
12
- * @throws Error if called outside of AppearanceProvider
13
- *
14
- * @example
15
- * ```tsx
16
- * function AppearanceToggle() {
17
- * const { colorScheme, setPreferredColorScheme, isPending } = useColorScheme();
18
- *
19
- * return (
20
- * <button
21
- * onClick={() => setPreferredColorScheme(colorScheme === 'dark' ? 'light' : 'dark')}
22
- * disabled={isPending}
23
- * >
24
- * {colorScheme}
25
- * </button>
26
- * );
27
- * }
28
- * ```
29
- *
30
- * @since 0.3.16-canary.0
31
- */
32
- declare function useColorScheme(): ColorSchemeContextType;
33
- //#endregion
34
- export { useColorScheme };
@@ -1,38 +0,0 @@
1
- import { ColorSchemeContext } from "./context.mjs";
2
- import { use } from "react";
3
- //#region src/core/use-theme.ts
4
- /**
5
- * Hook to access color scheme context.
6
- *
7
- * Uses React 19's `use()` API for context consumption, enabling:
8
- * - Conditional context reading
9
- * - Better Suspense boundary integration
10
- *
11
- * @returns Color scheme context with `colorScheme`, `resolvedColorScheme`, `setPreferredColorScheme`, and `isPending`
12
- * @throws Error if called outside of AppearanceProvider
13
- *
14
- * @example
15
- * ```tsx
16
- * function AppearanceToggle() {
17
- * const { colorScheme, setPreferredColorScheme, isPending } = useColorScheme();
18
- *
19
- * return (
20
- * <button
21
- * onClick={() => setPreferredColorScheme(colorScheme === 'dark' ? 'light' : 'dark')}
22
- * disabled={isPending}
23
- * >
24
- * {colorScheme}
25
- * </button>
26
- * );
27
- * }
28
- * ```
29
- *
30
- * @since 0.3.16-canary.0
31
- */
32
- function useColorScheme() {
33
- const value = use(ColorSchemeContext);
34
- if (!value) throw new Error("useColorScheme must be used within an AppearanceProvider");
35
- return value;
36
- }
37
- //#endregion
38
- export { useColorScheme };
@@ -1,68 +0,0 @@
1
- import { ColorScheme } from "../types.mjs";
2
- import { JSX } from "react";
3
-
4
- //#region src/script/theme-script.d.ts
5
- /**
6
- * @since 0.3.16-canary.3
7
- */
8
- type AppearanceScriptProps = {
9
- /**
10
- * Initial color scheme from server (e.g., from cookie via loader).
11
- *
12
- * When `storageKey` is provided, this acts as a fallback if the storage entry is absent
13
- * or contains an unrecognised value.
14
- */
15
- readonly colorScheme: ColorScheme;
16
- /**
17
- * CSP nonce applied to the inline script element.
18
- */
19
- readonly nonce?: string;
20
- /**
21
- * When provided, the inline script reads `localStorage.getItem(storageKey)` before
22
- * first paint and uses that value if it is a recognised color scheme (`"light"`, `"dark"`,
23
- * or `"automatic"`). Falls back to `colorScheme` when the key is absent or invalid.
24
- *
25
- * Use this for client-only React apps that persist the color scheme in `localStorage` instead
26
- * of an HTTP cookie to prevent FOUC.
27
- *
28
- * @example
29
- * ```tsx
30
- * <AppearanceScript colorScheme="automatic" storageKey="my-app-color-scheme" />
31
- * ```
32
- */
33
- readonly storageKey?: string;
34
- };
35
- /**
36
- * Inline script that prevents Flash of Unstyled Content (FOUC).
37
- *
38
- * **Why this is needed:**
39
- * React hydration occurs after the browser has already painted the page.
40
- * Without this script, users would briefly see the wrong appearance before
41
- * React takes over and applies the correct one.
42
- *
43
- * **How it works:**
44
- * This script runs synchronously in the `<head>` before first paint:
45
- * 1. Resolves 'automatic' to 'light' or 'dark' using `matchMedia()`
46
- * 2. Removes prior `light` / `dark` / `automatic` classes on `<html>` (SSR may
47
- * have applied the wrong resolved class for `automatic`, e.g. default `dark`)
48
- * 3. Adds the resolved color scheme class and sets `color-scheme` for native controls
49
- * 4. Writes the *preference* to `data-appearance` so preference-aware UI (e.g. a 3-state toggle)
50
- * can render the right state from CSS on first paint, without a hydration flash
51
- *
52
- * @example
53
- * ```tsx
54
- * // In __root.tsx (TanStack Start)
55
- * <head>
56
- * <AppearanceScript colorScheme={colorScheme} />
57
- * </head>
58
- * ```
59
- *
60
- * @since 0.3.16-canary.0
61
- */
62
- declare function AppearanceScript({
63
- nonce,
64
- storageKey,
65
- colorScheme
66
- }: AppearanceScriptProps): JSX.Element;
67
- //#endregion
68
- export { AppearanceScript, AppearanceScriptProps };
@@ -1,45 +0,0 @@
1
- import { MEDIA } from "../constants.mjs";
2
- import { colorSchemes } from "../types.mjs";
3
- import { jsx } from "react/jsx-runtime";
4
- //#region src/script/theme-script.tsx
5
- function toScriptSafe(value) {
6
- return JSON.stringify(value).replaceAll("<", "\\u003C").replaceAll(">", "\\u003E").replaceAll("/", "\\u002F");
7
- }
8
- const COLOR_SCHEME_REMOVE_ARGS = colorSchemes.map((s) => toScriptSafe(s)).join(",");
9
- const COLOR_SCHEME_VALID_CHECK = colorSchemes.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. Resolves 'automatic' to 'light' or 'dark' using `matchMedia()`
21
- * 2. Removes prior `light` / `dark` / `automatic` classes on `<html>` (SSR may
22
- * have applied the wrong resolved class for `automatic`, e.g. default `dark`)
23
- * 3. Adds the resolved color scheme class and sets `color-scheme` for native controls
24
- * 4. Writes the *preference* to `data-appearance` so preference-aware UI (e.g. a 3-state toggle)
25
- * can render the right state from CSS on first paint, without a hydration flash
26
- *
27
- * @example
28
- * ```tsx
29
- * // In __root.tsx (TanStack Start)
30
- * <head>
31
- * <AppearanceScript colorScheme={colorScheme} />
32
- * </head>
33
- * ```
34
- *
35
- * @since 0.3.16-canary.0
36
- */
37
- function AppearanceScript({ nonce, storageKey, colorScheme }) {
38
- return /* @__PURE__ */ jsx("script", {
39
- dangerouslySetInnerHTML: { __html: `(function(){try{var sk=${toScriptSafe(storageKey ?? null)},fbt=${toScriptSafe(colorScheme)},s=sk&&localStorage.getItem(sk),theme=(${COLOR_SCHEME_VALID_CHECK})?s:fbt,resolvedTheme=theme;"automatic"===theme&&(resolvedTheme=window.matchMedia(${toScriptSafe(MEDIA)}).matches?"dark":"light"),document.documentElement.classList.remove(${COLOR_SCHEME_REMOVE_ARGS}),document.documentElement.classList.add(resolvedTheme),document.documentElement.style.colorScheme=resolvedTheme,document.documentElement.dataset.appearance=theme}catch(e){}})()` },
40
- suppressHydrationWarning: true,
41
- ...nonce === void 0 ? {} : { nonce }
42
- });
43
- }
44
- //#endregion
45
- export { AppearanceScript };
package/dist/start.d.mts DELETED
@@ -1,2 +0,0 @@
1
- import { RootColorSchemeLoaderData, getColorSchemeServerFn, getRootColorSchemeServerFn, getSsrColorSchemeServerFn, persistColorSchemeCookie, setColorSchemeServerFn } from "./adapters/tanstack-start/server.mjs";
2
- export { type RootColorSchemeLoaderData, getColorSchemeServerFn, getRootColorSchemeServerFn, getSsrColorSchemeServerFn, persistColorSchemeCookie, setColorSchemeServerFn };
package/dist/start.mjs DELETED
@@ -1,2 +0,0 @@
1
- import { getColorSchemeServerFn, getRootColorSchemeServerFn, getSsrColorSchemeServerFn, persistColorSchemeCookie, setColorSchemeServerFn } from "./adapters/tanstack-start/server.mjs";
2
- export { getColorSchemeServerFn, getRootColorSchemeServerFn, getSsrColorSchemeServerFn, persistColorSchemeCookie, setColorSchemeServerFn };
package/dist/types.d.mts DELETED
@@ -1,60 +0,0 @@
1
- import { z } from "zod";
2
-
3
- //#region src/types.d.ts
4
- /**
5
- * Zod schema for color scheme validation.
6
- *
7
- * Acts as the single source of truth for all color-scheme-related types.
8
- * Valid values: 'light', 'dark', 'automatic'.
9
- *
10
- * @since 0.3.16-canary.0
11
- */
12
- declare const colorSchemeSchema: z.ZodEnum<{
13
- light: "light";
14
- dark: "dark";
15
- automatic: "automatic";
16
- }>;
17
- /**
18
- * User's color scheme preference.
19
- *
20
- * - `'light'` - Force light appearance
21
- * - `'dark'` - Force dark appearance
22
- * - `'automatic'` - Follow OS preference
23
- *
24
- * @since 0.3.16-canary.0
25
- */
26
- type ColorScheme = z.infer<typeof colorSchemeSchema>;
27
- /**
28
- * Actual color scheme applied to the UI after resolving 'automatic'.
29
- *
30
- * When color scheme is 'automatic', this reflects the OS preference (light/dark).
31
- *
32
- * @since 0.3.16-canary.0
33
- */
34
- type ResolvedColorScheme = Exclude<ColorScheme, "automatic">;
35
- /**
36
- * Array of all available color scheme options: `['light', 'dark', 'automatic']`.
37
- *
38
- * Useful for rendering appearance selectors in UI components.
39
- *
40
- * @since 0.3.16-canary.0
41
- */
42
- declare const colorSchemes: ("light" | "dark" | "automatic")[];
43
- /**
44
- * Shape of the color scheme context value provided by AppearanceProvider.
45
- *
46
- * - `colorScheme` - Current color scheme preference
47
- * - `resolvedColorScheme` - Actual color scheme applied (automatic resolved to light/dark)
48
- * - `setPreferredColorScheme` - Async function to update color scheme (triggers optimistic update)
49
- * - `isPending` - True while color scheme change is being persisted
50
- *
51
- * @since 0.3.16-canary.0
52
- */
53
- type ColorSchemeContextType = {
54
- readonly isPending: boolean;
55
- readonly resolvedColorScheme: ResolvedColorScheme;
56
- readonly setColorScheme: (value: ColorScheme) => Promise<void>;
57
- readonly colorScheme: ColorScheme;
58
- };
59
- //#endregion
60
- export { ColorScheme, ColorSchemeContextType, ResolvedColorScheme, colorSchemeSchema, colorSchemes };
package/dist/types.mjs DELETED
@@ -1,25 +0,0 @@
1
- import { z } from "zod";
2
- //#region src/types.ts
3
- /**
4
- * Zod schema for color scheme validation.
5
- *
6
- * Acts as the single source of truth for all color-scheme-related types.
7
- * Valid values: 'light', 'dark', 'automatic'.
8
- *
9
- * @since 0.3.16-canary.0
10
- */
11
- const colorSchemeSchema = z.enum([
12
- "light",
13
- "dark",
14
- "automatic"
15
- ]);
16
- /**
17
- * Array of all available color scheme options: `['light', 'dark', 'automatic']`.
18
- *
19
- * Useful for rendering appearance selectors in UI components.
20
- *
21
- * @since 0.3.16-canary.0
22
- */
23
- const colorSchemes = colorSchemeSchema.options;
24
- //#endregion
25
- export { colorSchemeSchema, colorSchemes };
@@ -1,34 +0,0 @@
1
- import { ColorScheme, ResolvedColorScheme } from "../types.mjs";
2
-
3
- //#region src/utils/system.d.ts
4
- /**
5
- * Detect the user's OS color scheme preference.
6
- *
7
- * Uses `matchMedia()` to query the `prefers-color-scheme` media feature.
8
- * Returns {@link DEFAULT_RESOLVED_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(): ResolvedColorScheme;
15
- /**
16
- * Resolve color scheme preference to actual light/dark value.
17
- *
18
- * - 'light' → 'light'
19
- * - 'dark' → 'dark'
20
- * - 'automatic' → on the client, result of {@link getSystemColorScheme}; on the server,
21
- * `ssrColorScheme` when provided, otherwise {@link DEFAULT_RESOLVED_COLOR_SCHEME}
22
- *
23
- * @param colorScheme - User's color scheme preference (`light`, `dark`, or `automatic`)
24
- * @param ssrColorScheme - When `colorScheme` is `automatic` and this runs during SSR (no `window`),
25
- * uses this as the resolved appearance—typically from Client Hints
26
- * (`Sec-CH-Prefers-Color-Scheme`) so `<html class>` matches the real OS preference.
27
- * Ignored for non-`automatic` schemes and on the client (where {@link getSystemColorScheme} wins).
28
- * @returns The resolved color scheme to apply (`light` or `dark`)
29
- *
30
- * @since 0.3.16-canary.0
31
- */
32
- declare function resolveColorScheme(colorScheme: ColorScheme, ssrColorScheme?: ResolvedColorScheme): ResolvedColorScheme;
33
- //#endregion
34
- export { getSystemColorScheme, resolveColorScheme };
@@ -1,40 +0,0 @@
1
- import { DEFAULT_RESOLVED_COLOR_SCHEME } from "../constants.mjs";
2
- //#region src/utils/system.ts
3
- /**
4
- * Detect the user's OS color scheme preference.
5
- *
6
- * Uses `matchMedia()` to query the `prefers-color-scheme` media feature.
7
- * Returns {@link DEFAULT_RESOLVED_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_RESOLVED_COLOR_SCHEME;
15
- return globalThis.window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
16
- }
17
- /**
18
- * Resolve color scheme preference to actual light/dark value.
19
- *
20
- * - 'light' → 'light'
21
- * - 'dark' → 'dark'
22
- * - 'automatic' → on the client, result of {@link getSystemColorScheme}; on the server,
23
- * `ssrColorScheme` when provided, otherwise {@link DEFAULT_RESOLVED_COLOR_SCHEME}
24
- *
25
- * @param colorScheme - User's color scheme preference (`light`, `dark`, or `automatic`)
26
- * @param ssrColorScheme - When `colorScheme` is `automatic` and this runs during SSR (no `window`),
27
- * uses this as the resolved appearance—typically from Client Hints
28
- * (`Sec-CH-Prefers-Color-Scheme`) so `<html class>` matches the real OS preference.
29
- * Ignored for non-`automatic` schemes and on the client (where {@link getSystemColorScheme} wins).
30
- * @returns The resolved color scheme to apply (`light` or `dark`)
31
- *
32
- * @since 0.3.16-canary.0
33
- */
34
- function resolveColorScheme(colorScheme, ssrColorScheme) {
35
- if (colorScheme !== "automatic") return colorScheme;
36
- if (typeof globalThis.window === "undefined") return ssrColorScheme ?? "dark";
37
- return getSystemColorScheme();
38
- }
39
- //#endregion
40
- export { getSystemColorScheme, resolveColorScheme };