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

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 CHANGED
@@ -1,5 +1,13 @@
1
1
  # @codefast/theme
2
2
 
3
+ ## 0.5.0-canary.1
4
+
5
+ ### Minor Changes
6
+
7
+ - [#547](https://github.com/codefastlabs/codefast/pull/547) [`c7d6818`](https://github.com/codefastlabs/codefast/commit/c7d68182f875040993c1cec8f34914dc37f5237d) Thanks [@thevuong](https://github.com/thevuong)! - Add a `storageKey` prop to `AppearanceProvider` for a fully client-side color scheme path (no server framework, cookie, or loader). When set, the provider reads the persisted preference from `localStorage` in its initial client render, auto-persists changes there (unless an explicit `persistColorScheme` is given), and syncs across tabs via the `storage` event. Paired with `<AppearanceScript storageKey>` using the same key, the inline script applies the stored value before first paint — so there is **no flash even on statically prerendered / CDN-served pages**, where an httpOnly cookie can't reach the pre-paint script and a post-mount server round-trip would otherwise flip the appearance.
8
+
9
+ `AppearanceScript` and `AppearanceProvider` now also mirror the **preference** (`light` / `dark` / `automatic`) to a `data-appearance` attribute on `<html>` — set by the inline script before first paint and kept in sync by the provider. This lets preference-aware UI (e.g. a 3-state theme toggle that shows a distinct "system" icon) render the correct state purely from CSS, with no hydration flash from reading client-only state.
10
+
3
11
  ## 0.5.0-canary.0
4
12
 
5
13
  ### Minor Changes
package/README.md CHANGED
@@ -177,34 +177,28 @@ Vary: Sec-CH-Prefers-Color-Scheme, Cookie
177
177
 
178
178
  ### Client-only React (localStorage)
179
179
 
180
- For apps without a server framework, persist the preference in `localStorage`:
180
+ For apps without a server framework — or **statically prerendered / CDN-served** apps where the server can't inject the preference at request time — drive the whole thing from `localStorage`. Pass `storageKey` to both `<AppearanceScript>` and `<AppearanceProvider>`:
181
181
 
182
182
  ```tsx
183
- import { AppearanceProvider } from "@codefast/theme";
184
- import type { ColorScheme } from "@codefast/theme";
183
+ import { AppearanceProvider, AppearanceScript } from "@codefast/theme";
185
184
 
186
185
  const STORAGE_KEY = "color-scheme";
187
186
 
188
- function App() {
189
- const initial =
190
- typeof window === "undefined"
191
- ? "automatic"
192
- : ((localStorage.getItem(STORAGE_KEY) as ColorScheme | null) ?? "automatic");
187
+ // In the document head — reads localStorage before first paint:
188
+ // <AppearanceScript colorScheme="automatic" storageKey={STORAGE_KEY} />
193
189
 
190
+ function App() {
194
191
  return (
195
- <AppearanceProvider
196
- colorScheme={initial}
197
- persistColorScheme={async (value) => {
198
- localStorage.setItem(STORAGE_KEY, value);
199
- }}
200
- >
192
+ <AppearanceProvider colorScheme="automatic" storageKey={STORAGE_KEY}>
201
193
  <YourApp />
202
194
  </AppearanceProvider>
203
195
  );
204
196
  }
205
197
  ```
206
198
 
207
- Pair it with `<AppearanceScript colorScheme="automatic" storageKey="color-scheme" />` in the document head so the right appearance is applied before first paint (no FOUC).
199
+ With `storageKey`, the provider reads the preference from `localStorage` in its initial client render (so the first paint already matches it — no flash, no post-mount settle), auto-persists changes there (no hand-rolled `persistColorScheme`), and syncs across tabs via the `storage` event. The inline `<AppearanceScript>` applies the stored value to `<html>` **before first paint**, so there is no flash even on prerendered HTML — the real preference never has to round-trip a server after paint. Use the **same key** in both places.
200
+
201
+ > SSR has no `localStorage`, so the server renders the `colorScheme` prop. For a returning visitor whose stored preference differs, components that render preference-dependent markup hydrate-reconcile once; gate them behind a mounted flag if you need to avoid that.
208
202
 
209
203
  ### Color scheme toggle
210
204
 
@@ -246,6 +240,15 @@ export function ColorSchemeSelect() {
246
240
 
247
241
  The script removes any prior `light` / `dark` / `automatic` class on `<html>`, so it is safe to pre-render the markup with `suppressHydrationWarning`.
248
242
 
243
+ It also writes the **preference** (`light` / `dark` / `automatic`, before resolving `automatic`) to a `data-appearance` attribute on `<html>` — and `<AppearanceProvider>` keeps it in sync. Preference-aware UI can then render purely from CSS (e.g. a 3-state toggle that shows a distinct "system" icon), correct on the first frame with no hydration flash:
244
+
245
+ ```css
246
+ /* show the matching trigger icon based on the stored preference */
247
+ html[data-appearance="automatic"] .icon-system {
248
+ display: block;
249
+ }
250
+ ```
251
+
249
252
  > **CSP note.** Pass a `nonce` to `<AppearanceScript nonce={...} />` when your policy requires it for inline scripts. The same nonce can also be passed to `<AppearanceProvider nonce={...} />` for the temporary inline `<style>` used by `disableTransition`.
250
253
 
251
254
  ---
@@ -271,16 +274,17 @@ Root provider that wires together color scheme state, OS subscription, optimisti
271
274
  </AppearanceProvider>
272
275
  ```
273
276
 
274
- | Prop | Type | Default | Description |
275
- | -------------------- | ------------------------------------------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------- |
276
- | `colorScheme` | `ColorScheme` | — | Initial preference (`"light"` / `"dark"` / `"automatic"`). Required. |
277
- | `ssrColorScheme` | `ResolvedColorScheme` | — | `"light"` or `"dark"` from the SSR request (e.g. Client Hints). Used as the server snapshot when preference is `automatic`. |
278
- | `persistColorScheme` | `(value: ColorScheme) => Promise<void>` | — | Runs whenever the user changes the color scheme. Rejects → optimistic update reverts automatically. |
279
- | `onPersistError` | `(error: unknown, attemptedColorScheme: ColorScheme) => void` | — | Optional hook called when `persistColorScheme` rejects; use for custom logging/telemetry/UI feedback. |
280
- | `syncFromServer` | `() => Promise<ColorScheme>` | — | Called once after mount to reconcile with the canonical source (e.g. cookie). Useful for stale HTML / duplicate-tab. |
281
- | `disableTransition` | `boolean` | `false` | Temporarily injects a style rule that disables CSS transitions while the color scheme swaps. Respects `prefers-reduced-motion`. |
282
- | `nonce` | `string` | — | CSP nonce attached to the inline `<style>` element when `disableTransition` is enabled. |
283
- | `children` | `ReactNode` | — | Application content. |
277
+ | Prop | Type | Default | Description |
278
+ | -------------------- | ------------------------------------------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
279
+ | `colorScheme` | `ColorScheme` | — | Initial preference (`"light"` / `"dark"` / `"automatic"`). Required. |
280
+ | `ssrColorScheme` | `ResolvedColorScheme` | — | `"light"` or `"dark"` from the SSR request (e.g. Client Hints). Used as the server snapshot when preference is `automatic`. |
281
+ | `persistColorScheme` | `(value: ColorScheme) => Promise<void>` | — | Runs whenever the user changes the color scheme. Rejects → optimistic update reverts automatically. |
282
+ | `onPersistError` | `(error: unknown, attemptedColorScheme: ColorScheme) => void` | — | Optional hook called when `persistColorScheme` rejects; use for custom logging/telemetry/UI feedback. |
283
+ | `syncFromServer` | `() => Promise<ColorScheme>` | — | Called once after mount to reconcile with the canonical source (e.g. cookie). Useful for stale HTML / duplicate-tab. |
284
+ | `storageKey` | `string` | — | Client-only path: restore from `localStorage` after mount, auto-persist there, and sync across tabs via the `storage` event. Pair with `<AppearanceScript storageKey>` using the same key. |
285
+ | `disableTransition` | `boolean` | `false` | Temporarily injects a style rule that disables CSS transitions while the color scheme swaps. Respects `prefers-reduced-motion`. |
286
+ | `nonce` | `string` | — | CSP nonce attached to the inline `<style>` element when `disableTransition` is enabled. |
287
+ | `children` | `ReactNode` | — | Application content. |
284
288
 
285
289
  `<AppearanceProvider>` internally:
286
290
 
@@ -52,6 +52,20 @@ type AppearanceProviderProps = {
52
52
  * in another tab. Use a stable reference (e.g. `getColorSchemeServerFn` from `@codefast/theme/start`).
53
53
  */
54
54
  readonly syncFromServer?: () => Promise<ColorScheme>;
55
+ /**
56
+ * Persist + restore the preference in `localStorage` under this key — the client-only path
57
+ * (no server framework, no cookie, no loader).
58
+ *
59
+ * When set, the provider reads the stored value in its initial client render (so the first paint
60
+ * already matches the preference — no flash, no post-mount settle), auto-persists changes to
61
+ * `localStorage` (unless {@link persistColorScheme} is also given, which then wins), and syncs across
62
+ * tabs via the `storage` event. Pair with `<AppearanceScript storageKey={…} />` using the **same key**.
63
+ *
64
+ * @remarks SSR has no `localStorage`, so the server renders the {@link AppearanceProviderProps.colorScheme}
65
+ * prop. For a returning visitor whose stored preference differs, components that render
66
+ * preference-dependent markup hydrate-reconcile once; gate them behind a mounted flag to avoid that.
67
+ */
68
+ readonly storageKey?: string;
55
69
  };
56
70
  /**
57
71
  * Provider component for color scheme state management.
@@ -69,6 +83,7 @@ type AppearanceProviderProps = {
69
83
  * `useSyncExternalStore`'s server snapshot so the first client snapshot matches `matchMedia`
70
84
  * and avoids a post-hydration flip. Omit if unavailable; falls back to {@link DEFAULT_RESOLVED_COLOR_SCHEME}.
71
85
  * @param props.syncFromServer - Optional one-shot RPC after mount to align with the cookie when SSR/HTML was stale.
86
+ * @param props.storageKey - Optional localStorage key for the client-only path: restore in the initial render, auto-persist, cross-tab sync.
72
87
  * @param props.persistColorScheme - Optional async handler to persist preference (cookie, server action, …)
73
88
  * @param props.onPersistError - Optional callback for persistence failures
74
89
  * @param props.disableTransition - Temporarily suppress CSS transitions on color scheme change
@@ -95,6 +110,7 @@ declare function AppearanceProvider({
95
110
  onPersistError,
96
111
  persistColorScheme,
97
112
  ssrColorScheme,
113
+ storageKey,
98
114
  syncFromServer,
99
115
  colorScheme: initialColorScheme
100
116
  }: AppearanceProviderProps): JSX.Element;
@@ -31,6 +31,19 @@ function createColorSchemeChannel() {
31
31
  }
32
32
  }
33
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
+ /**
34
47
  * Provider component for color scheme state management.
35
48
  *
36
49
  * **React 19 Features Used:**
@@ -46,6 +59,7 @@ function createColorSchemeChannel() {
46
59
  * `useSyncExternalStore`'s server snapshot so the first client snapshot matches `matchMedia`
47
60
  * and avoids a post-hydration flip. Omit if unavailable; falls back to {@link DEFAULT_RESOLVED_COLOR_SCHEME}.
48
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.
49
63
  * @param props.persistColorScheme - Optional async handler to persist preference (cookie, server action, …)
50
64
  * @param props.onPersistError - Optional callback for persistence failures
51
65
  * @param props.disableTransition - Temporarily suppress CSS transitions on color scheme change
@@ -65,9 +79,15 @@ function createColorSchemeChannel() {
65
79
  *
66
80
  * @since 0.3.16-canary.0
67
81
  */
68
- function AppearanceProvider({ children, disableTransition = false, nonce, onPersistError, persistColorScheme, ssrColorScheme, syncFromServer, colorScheme: initialColorScheme }) {
82
+ function AppearanceProvider({ children, disableTransition = false, nonce, onPersistError, persistColorScheme, ssrColorScheme, storageKey, syncFromServer, colorScheme: initialColorScheme }) {
69
83
  const safeInitialColorScheme = colorSchemeSchema.safeParse(initialColorScheme).success ? initialColorScheme : DEFAULT_COLOR_SCHEME;
70
- const [colorScheme, setColorSchemeState] = useState(safeInitialColorScheme);
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
+ });
71
91
  const [optimisticColorScheme, setOptimisticColorScheme] = useOptimistic(colorScheme);
72
92
  const isPending = optimisticColorScheme !== colorScheme;
73
93
  const committedColorSchemeRef = useRef(colorScheme);
@@ -75,11 +95,21 @@ function AppearanceProvider({ children, disableTransition = false, nonce, onPers
75
95
  const channelRef = useRef(null);
76
96
  const enableTransitionsRef = useRef(null);
77
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]);
78
107
  useEffect(() => {
108
+ if (storageKey !== void 0) return;
79
109
  startTransition(() => {
80
110
  setColorSchemeState((prev) => prev === safeInitialColorScheme ? prev : safeInitialColorScheme);
81
111
  });
82
- }, [safeInitialColorScheme]);
112
+ }, [safeInitialColorScheme, storageKey]);
83
113
  const syncFromServerRef = useRef(syncFromServer);
84
114
  syncFromServerRef.current = syncFromServer;
85
115
  useEffect(() => {
@@ -111,6 +141,9 @@ function AppearanceProvider({ children, disableTransition = false, nonce, onPers
111
141
  enable();
112
142
  }
113
143
  }, [resolvedColorScheme]);
144
+ useEffect(() => {
145
+ globalThis.window.document.documentElement.dataset.appearance = optimisticColorScheme;
146
+ }, [optimisticColorScheme]);
114
147
  const handleCrossTabMessage = useEffectEvent((event) => {
115
148
  const result = colorSchemeSchema.safeParse(event.data);
116
149
  if (!result.success || result.data === colorScheme) return;
@@ -118,6 +151,14 @@ function AppearanceProvider({ children, disableTransition = false, nonce, onPers
118
151
  setColorSchemeState(result.data);
119
152
  });
120
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
+ });
121
162
  useEffect(() => {
122
163
  const channel = createColorSchemeChannel();
123
164
  if (!channel) return;
@@ -129,6 +170,13 @@ function AppearanceProvider({ children, disableTransition = false, nonce, onPers
129
170
  channel.close();
130
171
  };
131
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]);
132
180
  const setColorScheme = useCallback(async (value) => {
133
181
  await Promise.resolve();
134
182
  if (value === committedColorSchemeRef.current) return;
@@ -137,7 +185,7 @@ function AppearanceProvider({ children, disableTransition = false, nonce, onPers
137
185
  intentRef.current = value;
138
186
  setOptimisticColorScheme(value);
139
187
  try {
140
- if (persistColorScheme) await persistColorScheme(value);
188
+ if (persist) await persist(value);
141
189
  if (intentRef.current === value) {
142
190
  setColorSchemeState(value);
143
191
  channelRef.current?.postMessage(value);
@@ -161,7 +209,7 @@ function AppearanceProvider({ children, disableTransition = false, nonce, onPers
161
209
  disableTransition,
162
210
  nonce,
163
211
  setOptimisticColorScheme,
164
- persistColorScheme,
212
+ persist,
165
213
  onPersistError
166
214
  ]);
167
215
  return /* @__PURE__ */ jsx(ColorSchemeContext, {
@@ -46,6 +46,8 @@ type AppearanceScriptProps = {
46
46
  * 2. Removes prior `light` / `dark` / `automatic` classes on `<html>` (SSR may
47
47
  * have applied the wrong resolved class for `automatic`, e.g. default `dark`)
48
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
49
51
  *
50
52
  * @example
51
53
  * ```tsx
@@ -21,6 +21,8 @@ const COLOR_SCHEME_VALID_CHECK = colorSchemes.map((s) => `s===${toScriptSafe(s)}
21
21
  * 2. Removes prior `light` / `dark` / `automatic` classes on `<html>` (SSR may
22
22
  * have applied the wrong resolved class for `automatic`, e.g. default `dark`)
23
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
24
26
  *
25
27
  * @example
26
28
  * ```tsx
@@ -34,7 +36,7 @@ const COLOR_SCHEME_VALID_CHECK = colorSchemes.map((s) => `s===${toScriptSafe(s)}
34
36
  */
35
37
  function AppearanceScript({ nonce, storageKey, colorScheme }) {
36
38
  return /* @__PURE__ */ jsx("script", {
37
- 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}catch(e){}})()` },
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){}})()` },
38
40
  suppressHydrationWarning: true,
39
41
  ...nonce === void 0 ? {} : { nonce }
40
42
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codefast/theme",
3
- "version": "0.5.0-canary.0",
3
+ "version": "0.5.0-canary.1",
4
4
  "description": "Theme management with React 19 features - optimistic updates, cross-tab sync, and SSR support",
5
5
  "keywords": [
6
6
  "dark-mode",
@@ -132,11 +132,12 @@
132
132
  "jsdom": "^29.1.1",
133
133
  "tsdown": "^0.22.3",
134
134
  "typescript": "^6.0.3",
135
- "vite": "~8.0.16",
135
+ "vite": "^8.1.0",
136
136
  "vitest": "^4.1.9",
137
- "@codefast/typescript-config": "0.5.0-canary.0"
137
+ "@codefast/typescript-config": "0.5.0-canary.1"
138
138
  },
139
139
  "peerDependencies": {
140
+ "@tanstack/react-start": ">=1.168.0",
140
141
  "@types/react": ">=19.0.0",
141
142
  "@types/react-dom": ">=19.0.0",
142
143
  "react": ">=19.0.0",
@@ -144,6 +145,9 @@
144
145
  "vite": ">=6.0.0"
145
146
  },
146
147
  "peerDependenciesMeta": {
148
+ "@tanstack/react-start": {
149
+ "optional": true
150
+ },
147
151
  "@types/react": {
148
152
  "optional": true
149
153
  },
@@ -56,6 +56,24 @@ function createColorSchemeChannel(): BroadcastChannel | null {
56
56
  }
57
57
  }
58
58
 
59
+ /**
60
+ * Read + validate the persisted preference from localStorage. Returns null when unavailable
61
+ * (SSR, private mode) or when the stored value is not a recognised scheme.
62
+ */
63
+ function readColorSchemeFromStorage(storageKey: string): ColorScheme | null {
64
+ if (typeof globalThis.window === "undefined") {
65
+ return null;
66
+ }
67
+
68
+ try {
69
+ const result = colorSchemeSchema.safeParse(globalThis.window.localStorage.getItem(storageKey));
70
+
71
+ return result.success ? result.data : null;
72
+ } catch {
73
+ return null;
74
+ }
75
+ }
76
+
59
77
  /* -----------------------------------------------------------------------------
60
78
  * Props
61
79
  * -------------------------------------------------------------------------- */
@@ -110,6 +128,20 @@ export type AppearanceProviderProps = {
110
128
  * in another tab. Use a stable reference (e.g. `getColorSchemeServerFn` from `@codefast/theme/start`).
111
129
  */
112
130
  readonly syncFromServer?: () => Promise<ColorScheme>;
131
+ /**
132
+ * Persist + restore the preference in `localStorage` under this key — the client-only path
133
+ * (no server framework, no cookie, no loader).
134
+ *
135
+ * When set, the provider reads the stored value in its initial client render (so the first paint
136
+ * already matches the preference — no flash, no post-mount settle), auto-persists changes to
137
+ * `localStorage` (unless {@link persistColorScheme} is also given, which then wins), and syncs across
138
+ * tabs via the `storage` event. Pair with `<AppearanceScript storageKey={…} />` using the **same key**.
139
+ *
140
+ * @remarks SSR has no `localStorage`, so the server renders the {@link AppearanceProviderProps.colorScheme}
141
+ * prop. For a returning visitor whose stored preference differs, components that render
142
+ * preference-dependent markup hydrate-reconcile once; gate them behind a mounted flag to avoid that.
143
+ */
144
+ readonly storageKey?: string;
113
145
  };
114
146
 
115
147
  /* -----------------------------------------------------------------------------
@@ -132,6 +164,7 @@ export type AppearanceProviderProps = {
132
164
  * `useSyncExternalStore`'s server snapshot so the first client snapshot matches `matchMedia`
133
165
  * and avoids a post-hydration flip. Omit if unavailable; falls back to {@link DEFAULT_RESOLVED_COLOR_SCHEME}.
134
166
  * @param props.syncFromServer - Optional one-shot RPC after mount to align with the cookie when SSR/HTML was stale.
167
+ * @param props.storageKey - Optional localStorage key for the client-only path: restore in the initial render, auto-persist, cross-tab sync.
135
168
  * @param props.persistColorScheme - Optional async handler to persist preference (cookie, server action, …)
136
169
  * @param props.onPersistError - Optional callback for persistence failures
137
170
  * @param props.disableTransition - Temporarily suppress CSS transitions on color scheme change
@@ -158,6 +191,7 @@ export function AppearanceProvider({
158
191
  onPersistError,
159
192
  persistColorScheme,
160
193
  ssrColorScheme,
194
+ storageKey,
161
195
  syncFromServer,
162
196
  colorScheme: initialColorScheme,
163
197
  }: AppearanceProviderProps): JSX.Element {
@@ -166,8 +200,20 @@ export function AppearanceProvider({
166
200
  ? initialColorScheme
167
201
  : DEFAULT_COLOR_SCHEME;
168
202
 
169
- // Actual persisted color scheme (source of truth after server confirms)
170
- const [colorScheme, setColorSchemeState] = useState<ColorScheme>(safeInitialColorScheme);
203
+ // Actual persisted color scheme. Storage path: read localStorage in the initializer so the first client
204
+ // render already matches what AppearanceScript applied pre-paint (no flash, no post-mount settle). SSR has
205
+ // no localStorage, so the server renders the prop.
206
+ const [colorScheme, setColorSchemeState] = useState<ColorScheme>(() => {
207
+ if (storageKey !== undefined) {
208
+ const stored = readColorSchemeFromStorage(storageKey);
209
+
210
+ if (stored !== null) {
211
+ return stored;
212
+ }
213
+ }
214
+
215
+ return safeInitialColorScheme;
216
+ });
171
217
 
172
218
  // Optimistic color scheme - immediately reflects user's intent while async operation runs
173
219
  // Automatically reverts to `colorScheme` if the transition fails
@@ -190,12 +236,36 @@ export function AppearanceProvider({
190
236
  // C3: Last-write-wins intent — prevents stale async commits from overriding newer setColorScheme calls
191
237
  const intentRef = useRef<ColorScheme | null>(null);
192
238
 
193
- // C1: Re-sync state when the server (loader) provides a new color scheme value after mount
239
+ // Effective persistence: an explicit persistColorScheme wins; otherwise storageKey auto-persists to localStorage.
240
+ const persist = useMemo<((value: ColorScheme) => Promise<void>) | undefined>(() => {
241
+ if (persistColorScheme) {
242
+ return persistColorScheme;
243
+ }
244
+
245
+ if (storageKey === undefined) {
246
+ return undefined;
247
+ }
248
+
249
+ return async (value: ColorScheme): Promise<void> => {
250
+ try {
251
+ globalThis.window.localStorage.setItem(storageKey, value);
252
+ } catch {
253
+ /* storage blocked (private mode / quota) — optimistic UI already reflects the change */
254
+ }
255
+ };
256
+ }, [persistColorScheme, storageKey]);
257
+
258
+ // C1: Re-sync state when the server (loader) provides a new color scheme value after mount.
259
+ // Storage path owns the preference client-side; the prop is only a static default — don't clobber it.
194
260
  useEffect(() => {
261
+ if (storageKey !== undefined) {
262
+ return;
263
+ }
264
+
195
265
  startTransition(() => {
196
266
  setColorSchemeState((prev) => (prev === safeInitialColorScheme ? prev : safeInitialColorScheme));
197
267
  });
198
- }, [safeInitialColorScheme]);
268
+ }, [safeInitialColorScheme, storageKey]);
199
269
 
200
270
  const syncFromServerRef = useRef(syncFromServer);
201
271
 
@@ -257,6 +327,13 @@ export function AppearanceProvider({
257
327
  }
258
328
  }, [resolvedColorScheme]);
259
329
 
330
+ // Mirror the *preference* (not the resolved value) to `data-appearance` so preference-aware UI
331
+ // (e.g. a 3-state toggle) renders from CSS — matching what AppearanceScript set pre-paint. Tracks the
332
+ // optimistic value so the attribute flips immediately on change and stays in sync across tabs.
333
+ useEffect(() => {
334
+ globalThis.window.document.documentElement.dataset.appearance = optimisticColorScheme;
335
+ }, [optimisticColorScheme]);
336
+
260
337
  // S1: Validate cross-tab message before applying to prevent injection from extensions/scripts
261
338
  const handleCrossTabMessage = useEffectEvent((event: MessageEvent) => {
262
339
  const result = colorSchemeSchema.safeParse(event.data);
@@ -270,6 +347,23 @@ export function AppearanceProvider({
270
347
  });
271
348
  });
272
349
 
350
+ // Storage path cross-tab sync: the `storage` event fires in OTHER tabs when this key changes.
351
+ const handleStorageEvent = useEffectEvent((event: StorageEvent) => {
352
+ if (event.key !== storageKey) {
353
+ return;
354
+ }
355
+
356
+ const result = colorSchemeSchema.safeParse(event.newValue);
357
+
358
+ if (!result.success || result.data === colorScheme) {
359
+ return;
360
+ }
361
+
362
+ startTransition(() => {
363
+ setColorSchemeState(result.data);
364
+ });
365
+ });
366
+
273
367
  // P2: Keep channel in ref so setColorScheme can broadcast without opening a new channel each time
274
368
  useEffect(() => {
275
369
  const channel = createColorSchemeChannel();
@@ -288,6 +382,18 @@ export function AppearanceProvider({
288
382
  };
289
383
  }, []);
290
384
 
385
+ useEffect(() => {
386
+ if (storageKey === undefined) {
387
+ return;
388
+ }
389
+
390
+ globalThis.window.addEventListener("storage", handleStorageEvent);
391
+
392
+ return (): void => {
393
+ globalThis.window.removeEventListener("storage", handleStorageEvent);
394
+ };
395
+ }, [storageKey]);
396
+
291
397
  const setColorScheme = useCallback(
292
398
  async (value: ColorScheme): Promise<void> => {
293
399
  await Promise.resolve();
@@ -311,8 +417,8 @@ export function AppearanceProvider({
311
417
 
312
418
  try {
313
419
  // Persist to server/storage
314
- if (persistColorScheme) {
315
- await persistColorScheme(value);
420
+ if (persist) {
421
+ await persist(value);
316
422
  }
317
423
 
318
424
  // Only commit if no newer setColorScheme call has since taken over
@@ -346,7 +452,7 @@ export function AppearanceProvider({
346
452
  }
347
453
  });
348
454
  },
349
- [disableTransition, nonce, setOptimisticColorScheme, persistColorScheme, onPersistError],
455
+ [disableTransition, nonce, setOptimisticColorScheme, persist, onPersistError],
350
456
  );
351
457
 
352
458
  // Expose optimistic color scheme so consumers see immediate updates
@@ -67,6 +67,8 @@ export type AppearanceScriptProps = {
67
67
  * 2. Removes prior `light` / `dark` / `automatic` classes on `<html>` (SSR may
68
68
  * have applied the wrong resolved class for `automatic`, e.g. default `dark`)
69
69
  * 3. Adds the resolved color scheme class and sets `color-scheme` for native controls
70
+ * 4. Writes the *preference* to `data-appearance` so preference-aware UI (e.g. a 3-state toggle)
71
+ * can render the right state from CSS on first paint, without a hydration flash
70
72
  *
71
73
  * @example
72
74
  * ```tsx
@@ -83,7 +85,7 @@ export function AppearanceScript({ nonce, storageKey, colorScheme }: AppearanceS
83
85
  // F1: When storageKey is provided, the script reads localStorage before first paint so
84
86
  // client-only apps (no SSR cookie) get the right color scheme without FOUC.
85
87
  // sk=null short-circuits to s=null so color scheme falls back to fbt — backward-compatible.
86
- const appearanceScript = `(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}catch(e){}})()`;
88
+ const appearanceScript = `(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){}})()`;
87
89
  const nonceProps = nonce === undefined ? {} : { nonce };
88
90
 
89
91
  return <script dangerouslySetInnerHTML={{ __html: appearanceScript }} suppressHydrationWarning {...nonceProps} />;