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