@codefast/theme 0.4.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 +14 -0
- package/README.md +175 -141
- package/dist/adapters/tanstack-start/vite.d.mts +12 -0
- package/dist/adapters/tanstack-start/vite.mjs +21 -0
- package/dist/core/provider.d.mts +16 -0
- package/dist/core/provider.mjs +53 -5
- package/dist/script/theme-script.d.mts +2 -0
- package/dist/script/theme-script.mjs +3 -1
- package/package.json +20 -6
- package/src/adapters/tanstack-start/vite.ts +50 -0
- package/src/core/provider.tsx +113 -7
- package/src/script/theme-script.tsx +3 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,19 @@
|
|
|
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
|
+
|
|
11
|
+
## 0.5.0-canary.0
|
|
12
|
+
|
|
13
|
+
### Minor Changes
|
|
14
|
+
|
|
15
|
+
- [#526](https://github.com/codefastlabs/codefast/pull/526) [`fad5a21`](https://github.com/codefastlabs/codefast/commit/fad5a21a8b60d9dafc1efc00addf146608bfbb89) Thanks [@thevuong](https://github.com/thevuong)! - Add the `@codefast/theme/vite` plugin. TanStack Start registers the server functions shipped in `@codefast/theme/start` at the consumer's build time, so the package must not be externalized for SSR nor pre-bundled for the client. The new `codefastTheme()` plugin applies that configuration automatically, so consumers no longer need to hand-write `ssr.noExternal` / `optimizeDeps.exclude`.
|
|
16
|
+
|
|
3
17
|
## 0.4.0
|
|
4
18
|
|
|
5
19
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @codefast/theme
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Color-scheme management for React 19 — SSR-safe `automatic` resolution, optimistic updates, cross-tab sync, and a drop-in TanStack Start adapter.
|
|
4
4
|
|
|
5
5
|
[](https://github.com/codefastlabs/codefast/actions/workflows/release.yml)
|
|
6
6
|
[](https://www.npmjs.com/package/@codefast/theme)
|
|
@@ -19,15 +19,15 @@ Theme management for React 19 — SSR-safe `system` resolution, optimistic updat
|
|
|
19
19
|
- [Recipes](#recipes)
|
|
20
20
|
- [TanStack Start](#tanstack-start)
|
|
21
21
|
- [Client-only React (localStorage)](#client-only-react-localstorage)
|
|
22
|
-
- [
|
|
22
|
+
- [Color scheme toggle](#color-scheme-toggle)
|
|
23
23
|
- [SSR and FOUC prevention](#ssr-and-fouc-prevention)
|
|
24
24
|
- [API Reference](#api-reference)
|
|
25
|
-
- [`<
|
|
26
|
-
- [`
|
|
27
|
-
- [`<
|
|
28
|
-
- [`
|
|
29
|
-
- [`
|
|
30
|
-
- [`
|
|
25
|
+
- [`<AppearanceProvider>`](#appearanceprovider)
|
|
26
|
+
- [`useColorScheme()`](#usecolorscheme)
|
|
27
|
+
- [`<AppearanceScript>`](#appearancescript)
|
|
28
|
+
- [`resolveColorScheme()`](#resolvecolorscheme)
|
|
29
|
+
- [`getSystemColorScheme()` / `applyColorScheme()` / `suppressTransitions()`](#getsystemcolorscheme--applycolorscheme--suppresstransitions)
|
|
30
|
+
- [`colorSchemes`, `colorSchemeSchema`, and defaults](#colorschemes-colorschemeschema-and-defaults)
|
|
31
31
|
- [TanStack Start adapter (`@codefast/theme/start`)](#tanstack-start-adapter-codefastthemestart)
|
|
32
32
|
- [Package exports](#package-exports)
|
|
33
33
|
- [Contributing](#contributing)
|
|
@@ -38,13 +38,13 @@ Theme management for React 19 — SSR-safe `system` resolution, optimistic updat
|
|
|
38
38
|
|
|
39
39
|
## Why @codefast/theme
|
|
40
40
|
|
|
41
|
-
`@codefast/theme` is a focused
|
|
41
|
+
`@codefast/theme` is a focused color-scheme state primitive built around the React 19 concurrent APIs. Drop it at the root of your app, persist the user's preference however you want, and let the hook and inline script keep the DOM in sync.
|
|
42
42
|
|
|
43
|
-
- **React 19 first.** Uses `useOptimistic`, `useSyncExternalStore`, and `useEffectEvent` to keep
|
|
44
|
-
- **SSR-friendly.** A tiny inline `<
|
|
45
|
-
- **Cross-tab sync.**
|
|
46
|
-
- **Optimistic setters.** `
|
|
47
|
-
- **TanStack Start adapter.** `@codefast/theme/start` ships cookie-based persistence plus loader/server helpers. Everything else stays vanilla.
|
|
43
|
+
- **React 19 first.** Uses `useOptimistic`, `useSyncExternalStore`, and `useEffectEvent` to keep color scheme changes immediate, hydration-safe, and free of needless re-renders.
|
|
44
|
+
- **SSR-friendly.** A tiny inline `<AppearanceScript>` runs before first paint so `automatic` never flashes the wrong appearance. Works with Client Hints (`Sec-CH-Prefers-Color-Scheme`) when you have them.
|
|
45
|
+
- **Cross-tab sync.** Color scheme changes propagate between tabs over `BroadcastChannel`.
|
|
46
|
+
- **Optimistic setters.** `setColorScheme(value)` updates the UI immediately and reverts automatically if persistence fails.
|
|
47
|
+
- **TanStack Start adapter.** `@codefast/theme/start` ships cookie-based persistence plus loader/server helpers, and `@codefast/theme/vite` wires them into your build. Everything else stays vanilla.
|
|
48
48
|
- **Tree-shakeable.** Side-effect-free ESM with granular subpaths; bring in only the pieces you use.
|
|
49
49
|
|
|
50
50
|
---
|
|
@@ -54,6 +54,7 @@ Theme management for React 19 — SSR-safe `system` resolution, optimistic updat
|
|
|
54
54
|
- React `>=19.0.0` (and `react-dom`)
|
|
55
55
|
- TypeScript `>= 5.9` (recommended; the published types target ES2022)
|
|
56
56
|
- TanStack Start `^1` — only if you use `@codefast/theme/start`
|
|
57
|
+
- Vite `>=6` — only if you use `@codefast/theme/vite`
|
|
57
58
|
|
|
58
59
|
All peers except `react` / `react-dom` are optional.
|
|
59
60
|
|
|
@@ -81,24 +82,28 @@ pnpm add @tanstack/react-start # only if using @codefast/theme/start
|
|
|
81
82
|
## Quick Start
|
|
82
83
|
|
|
83
84
|
```tsx
|
|
84
|
-
import {
|
|
85
|
+
import { AppearanceProvider, useColorScheme } from "@codefast/theme";
|
|
85
86
|
|
|
86
87
|
function App() {
|
|
87
88
|
return (
|
|
88
|
-
<
|
|
89
|
+
<AppearanceProvider colorScheme="automatic">
|
|
89
90
|
<Page />
|
|
90
|
-
</
|
|
91
|
+
</AppearanceProvider>
|
|
91
92
|
);
|
|
92
93
|
}
|
|
93
94
|
|
|
94
95
|
function Page() {
|
|
95
|
-
const {
|
|
96
|
+
const { colorScheme, setColorScheme } = useColorScheme();
|
|
96
97
|
|
|
97
|
-
return
|
|
98
|
+
return (
|
|
99
|
+
<button onClick={() => setColorScheme(colorScheme === "dark" ? "light" : "dark")}>
|
|
100
|
+
Current color scheme: {colorScheme}
|
|
101
|
+
</button>
|
|
102
|
+
);
|
|
98
103
|
}
|
|
99
104
|
```
|
|
100
105
|
|
|
101
|
-
`
|
|
106
|
+
`colorScheme` accepts `"light"`, `"dark"`, or `"automatic"`. `resolvedColorScheme` from `useColorScheme()` always narrows to `"light" | "dark"`.
|
|
102
107
|
|
|
103
108
|
---
|
|
104
109
|
|
|
@@ -108,36 +113,52 @@ function Page() {
|
|
|
108
113
|
|
|
109
114
|
Server-side persistence lives in `@codefast/theme/start`. The shell keeps full control over `<html>` / `<head>` / `<body>` — the adapter only provides the loader data and cookie helpers.
|
|
110
115
|
|
|
116
|
+
**Vite setup.** TanStack Start registers `@codefast/theme/start`'s server functions at build time, in your app's build. For that to happen the package must not be externalized for SSR nor pre-bundled for the client. The bundled `@codefast/theme/vite` plugin applies exactly that — so you don't hand-write `ssr.noExternal` / `optimizeDeps.exclude`:
|
|
117
|
+
|
|
118
|
+
```ts
|
|
119
|
+
// vite.config.ts
|
|
120
|
+
import { codefastTheme } from "@codefast/theme/vite";
|
|
121
|
+
import { tanstackStart } from "@tanstack/react-start/plugin/vite";
|
|
122
|
+
import viteReact from "@vitejs/plugin-react";
|
|
123
|
+
import { defineConfig } from "vite";
|
|
124
|
+
|
|
125
|
+
export default defineConfig({
|
|
126
|
+
plugins: [codefastTheme(), tanstackStart(), viteReact()],
|
|
127
|
+
});
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
Then wire the root shell:
|
|
131
|
+
|
|
111
132
|
```tsx
|
|
112
133
|
// routes/__root.tsx (adjust to your router setup)
|
|
113
|
-
import {
|
|
114
|
-
import {
|
|
115
|
-
import {
|
|
134
|
+
import { AppearanceProvider, AppearanceScript, resolveColorScheme } from "@codefast/theme";
|
|
135
|
+
import { getColorSchemeServerFn, getRootColorSchemeServerFn, persistColorSchemeCookie } from "@codefast/theme/start";
|
|
136
|
+
import { HeadContent, Scripts, createRootRoute } from "@tanstack/react-router";
|
|
116
137
|
|
|
117
|
-
export const Route =
|
|
118
|
-
loader:
|
|
138
|
+
export const Route = createRootRoute({
|
|
139
|
+
loader: () => getRootColorSchemeServerFn(),
|
|
119
140
|
shellComponent: RootShell,
|
|
120
141
|
});
|
|
121
142
|
|
|
122
143
|
function RootShell({ children }: { children: React.ReactNode }) {
|
|
123
|
-
const {
|
|
124
|
-
const resolved =
|
|
144
|
+
const { colorScheme, ssrColorScheme } = Route.useLoaderData();
|
|
145
|
+
const resolved = resolveColorScheme(colorScheme, ssrColorScheme);
|
|
125
146
|
|
|
126
147
|
return (
|
|
127
148
|
<html className={resolved} lang="en" style={{ colorScheme: resolved }} suppressHydrationWarning>
|
|
128
149
|
<head>
|
|
129
150
|
<HeadContent />
|
|
130
|
-
<
|
|
151
|
+
<AppearanceScript colorScheme={colorScheme} />
|
|
131
152
|
</head>
|
|
132
153
|
<body>
|
|
133
|
-
<
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
154
|
+
<AppearanceProvider
|
|
155
|
+
colorScheme={colorScheme}
|
|
156
|
+
ssrColorScheme={ssrColorScheme}
|
|
157
|
+
persistColorScheme={persistColorSchemeCookie}
|
|
158
|
+
syncFromServer={getColorSchemeServerFn}
|
|
138
159
|
>
|
|
139
160
|
{children}
|
|
140
|
-
</
|
|
161
|
+
</AppearanceProvider>
|
|
141
162
|
<Scripts />
|
|
142
163
|
</body>
|
|
143
164
|
</html>
|
|
@@ -145,53 +166,55 @@ function RootShell({ children }: { children: React.ReactNode }) {
|
|
|
145
166
|
}
|
|
146
167
|
```
|
|
147
168
|
|
|
148
|
-
To keep cached HTML honest when serving `
|
|
169
|
+
To keep cached HTML honest when serving `automatic`, advertise the Client Hint and add the right `Vary` header:
|
|
149
170
|
|
|
150
171
|
```
|
|
151
172
|
Accept-CH: Sec-CH-Prefers-Color-Scheme
|
|
152
173
|
Vary: Sec-CH-Prefers-Color-Scheme, Cookie
|
|
153
174
|
```
|
|
154
175
|
|
|
155
|
-
`
|
|
176
|
+
`syncFromServer` re-reads the cookie once after mount and covers edge cases like duplicate-tab restores where the HTML is older than the cookie.
|
|
156
177
|
|
|
157
178
|
### Client-only React (localStorage)
|
|
158
179
|
|
|
159
|
-
For apps without a server framework
|
|
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>`:
|
|
160
181
|
|
|
161
182
|
```tsx
|
|
162
|
-
import {
|
|
183
|
+
import { AppearanceProvider, AppearanceScript } from "@codefast/theme";
|
|
163
184
|
|
|
164
|
-
|
|
165
|
-
const saved = typeof window !== "undefined" ? (localStorage.getItem("theme") ?? "system") : "system";
|
|
185
|
+
const STORAGE_KEY = "color-scheme";
|
|
166
186
|
|
|
187
|
+
// In the document head — reads localStorage before first paint:
|
|
188
|
+
// <AppearanceScript colorScheme="automatic" storageKey={STORAGE_KEY} />
|
|
189
|
+
|
|
190
|
+
function App() {
|
|
167
191
|
return (
|
|
168
|
-
<
|
|
169
|
-
theme={saved}
|
|
170
|
-
persistTheme={async (value) => {
|
|
171
|
-
localStorage.setItem("theme", value);
|
|
172
|
-
}}
|
|
173
|
-
>
|
|
192
|
+
<AppearanceProvider colorScheme="automatic" storageKey={STORAGE_KEY}>
|
|
174
193
|
<YourApp />
|
|
175
|
-
</
|
|
194
|
+
</AppearanceProvider>
|
|
176
195
|
);
|
|
177
196
|
}
|
|
178
197
|
```
|
|
179
198
|
|
|
180
|
-
|
|
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.
|
|
202
|
+
|
|
203
|
+
### Color scheme toggle
|
|
181
204
|
|
|
182
205
|
```tsx
|
|
183
|
-
import {
|
|
206
|
+
import { colorSchemes, useColorScheme } from "@codefast/theme";
|
|
184
207
|
|
|
185
|
-
export function
|
|
186
|
-
const {
|
|
208
|
+
export function ColorSchemeSelect() {
|
|
209
|
+
const { colorScheme, setColorScheme, isPending } = useColorScheme();
|
|
187
210
|
|
|
188
211
|
return (
|
|
189
212
|
<select
|
|
190
|
-
value={
|
|
213
|
+
value={colorScheme}
|
|
191
214
|
disabled={isPending}
|
|
192
|
-
onChange={(event) =>
|
|
215
|
+
onChange={(event) => setColorScheme(event.target.value as (typeof colorSchemes)[number])}
|
|
193
216
|
>
|
|
194
|
-
{
|
|
217
|
+
{colorSchemes.map((value) => (
|
|
195
218
|
<option key={value} value={value}>
|
|
196
219
|
{value[0].toUpperCase() + value.slice(1)}
|
|
197
220
|
</option>
|
|
@@ -201,144 +224,154 @@ export function ThemeSelect() {
|
|
|
201
224
|
}
|
|
202
225
|
```
|
|
203
226
|
|
|
204
|
-
`
|
|
227
|
+
`colorSchemes` is `["light", "dark", "automatic"]`, so this renders every option without hard-coding the list.
|
|
205
228
|
|
|
206
229
|
---
|
|
207
230
|
|
|
208
231
|
## SSR and FOUC prevention
|
|
209
232
|
|
|
210
|
-
`<
|
|
233
|
+
`<AppearanceScript>` injects a tiny synchronous `<script>` into the document head. It runs before first paint, resolves `automatic` via `matchMedia`, and adds the appropriate class + `color-scheme` to `<html>`:
|
|
211
234
|
|
|
212
235
|
```tsx
|
|
213
236
|
<head>
|
|
214
|
-
<
|
|
237
|
+
<AppearanceScript colorScheme="automatic" />
|
|
215
238
|
</head>
|
|
216
239
|
```
|
|
217
240
|
|
|
218
|
-
The script removes any prior `light` / `dark` / `
|
|
241
|
+
The script removes any prior `light` / `dark` / `automatic` class on `<html>`, so it is safe to pre-render the markup with `suppressHydrationWarning`.
|
|
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
|
+
```
|
|
219
251
|
|
|
220
|
-
> **CSP note.** Pass a `nonce` to `<
|
|
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`.
|
|
221
253
|
|
|
222
254
|
---
|
|
223
255
|
|
|
224
256
|
## API Reference
|
|
225
257
|
|
|
226
|
-
### `<
|
|
258
|
+
### `<AppearanceProvider>`
|
|
227
259
|
|
|
228
|
-
Root provider that wires together
|
|
260
|
+
Root provider that wires together color scheme state, OS subscription, optimistic updates, and cross-tab broadcast.
|
|
229
261
|
|
|
230
262
|
```tsx
|
|
231
|
-
<
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
263
|
+
<AppearanceProvider
|
|
264
|
+
colorScheme={initialColorScheme}
|
|
265
|
+
ssrColorScheme="light"
|
|
266
|
+
persistColorScheme={async (value) => {
|
|
235
267
|
/* … */
|
|
236
268
|
}}
|
|
237
|
-
|
|
238
|
-
|
|
269
|
+
syncFromServer={getColorSchemeServerFn}
|
|
270
|
+
disableTransition
|
|
239
271
|
nonce={cspNonce}
|
|
240
272
|
>
|
|
241
273
|
{children}
|
|
242
|
-
</
|
|
274
|
+
</AppearanceProvider>
|
|
243
275
|
```
|
|
244
276
|
|
|
245
|
-
| Prop
|
|
246
|
-
|
|
|
247
|
-
| `
|
|
248
|
-
| `
|
|
249
|
-
| `
|
|
250
|
-
| `
|
|
251
|
-
| `
|
|
252
|
-
| `
|
|
253
|
-
| `
|
|
254
|
-
| `
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
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. |
|
|
288
|
+
|
|
289
|
+
`<AppearanceProvider>` internally:
|
|
290
|
+
|
|
291
|
+
1. Tracks the persisted `colorScheme` and an optimistic value for immediate feedback.
|
|
292
|
+
2. Subscribes to `(prefers-color-scheme: dark)` through `useSyncExternalStore` with a server snapshot backed by `ssrColorScheme`.
|
|
260
293
|
3. Applies the resolved class + `color-scheme` to `<html>` whenever it changes.
|
|
261
|
-
4. Broadcasts the new value over `BroadcastChannel("
|
|
294
|
+
4. Broadcasts the new value over `BroadcastChannel("color-scheme-sync")` so other tabs stay in sync.
|
|
262
295
|
|
|
263
|
-
### `
|
|
296
|
+
### `useColorScheme()`
|
|
264
297
|
|
|
265
298
|
```tsx
|
|
266
|
-
const {
|
|
299
|
+
const { colorScheme, resolvedColorScheme, setColorScheme, isPending } = useColorScheme();
|
|
267
300
|
```
|
|
268
301
|
|
|
269
|
-
| Field
|
|
270
|
-
|
|
|
271
|
-
| `
|
|
272
|
-
| `
|
|
273
|
-
| `
|
|
274
|
-
| `isPending`
|
|
302
|
+
| Field | Type | Description |
|
|
303
|
+
| --------------------- | --------------------------------------- | ------------------------------------------------------------------------------------ |
|
|
304
|
+
| `colorScheme` | `ColorScheme` | Current preference (reflects the optimistic value while a change is pending). |
|
|
305
|
+
| `resolvedColorScheme` | `ResolvedColorScheme` | `"light"` or `"dark"` — the value actually applied to `<html>`. |
|
|
306
|
+
| `setColorScheme` | `(value: ColorScheme) => Promise<void>` | Update + persist. Resolves once persistence settles; on failure the UI reverts. |
|
|
307
|
+
| `isPending` | `boolean` | `true` while the optimistic value differs from the persisted one (change in flight). |
|
|
275
308
|
|
|
276
|
-
Throws if called outside of
|
|
309
|
+
Throws if called outside of an `<AppearanceProvider>`.
|
|
277
310
|
|
|
278
|
-
### `<
|
|
311
|
+
### `<AppearanceScript>`
|
|
279
312
|
|
|
280
313
|
Inline script for the document head that prevents FOUC.
|
|
281
314
|
|
|
282
315
|
```tsx
|
|
283
|
-
<
|
|
316
|
+
<AppearanceScript colorScheme={colorScheme} nonce={cspNonce} />
|
|
284
317
|
```
|
|
285
318
|
|
|
286
|
-
| Prop
|
|
287
|
-
|
|
|
288
|
-
| `
|
|
289
|
-
| `nonce`
|
|
290
|
-
| `storageKey`
|
|
319
|
+
| Prop | Type | Description |
|
|
320
|
+
| ------------- | ------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
|
|
321
|
+
| `colorScheme` | `ColorScheme` | The preference to apply on initial render. `"automatic"` resolves via `matchMedia`. Acts as fallback when `storageKey` is provided. |
|
|
322
|
+
| `nonce` | `string` | Optional CSP nonce attached to the inline `<script>`. |
|
|
323
|
+
| `storageKey` | `string` | When set, the script reads `localStorage.getItem(storageKey)` before first paint. Use for client-only apps without an SSR cookie. |
|
|
291
324
|
|
|
292
325
|
The component emits a `<script>` with `dangerouslySetInnerHTML` and forwards `nonce` when provided.
|
|
293
326
|
|
|
294
|
-
### `
|
|
327
|
+
### `resolveColorScheme()`
|
|
295
328
|
|
|
296
329
|
```tsx
|
|
297
|
-
import {
|
|
330
|
+
import { resolveColorScheme } from "@codefast/theme";
|
|
298
331
|
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
332
|
+
resolveColorScheme("dark"); // → "dark"
|
|
333
|
+
resolveColorScheme("automatic"); // client: OS preference via matchMedia
|
|
334
|
+
resolveColorScheme("automatic", "light"); // server: use Client Hints fallback
|
|
302
335
|
```
|
|
303
336
|
|
|
304
|
-
Returns a `
|
|
337
|
+
Returns a `ResolvedColorScheme` (`"light" | "dark"`). On the server without an `ssrColorScheme`, falls back to `DEFAULT_RESOLVED_COLOR_SCHEME` (`"dark"`).
|
|
305
338
|
|
|
306
|
-
### `
|
|
339
|
+
### `getSystemColorScheme()` / `applyColorScheme()` / `suppressTransitions()`
|
|
307
340
|
|
|
308
341
|
Granular helpers from `@codefast/theme/utils/system` and `@codefast/theme/utils/dom` for custom integrations:
|
|
309
342
|
|
|
310
|
-
| Function
|
|
311
|
-
|
|
|
312
|
-
| `
|
|
313
|
-
| `
|
|
314
|
-
| `
|
|
343
|
+
| Function | Summary |
|
|
344
|
+
| ----------------------------- | ------------------------------------------------------------------------------------------------------ |
|
|
345
|
+
| `getSystemColorScheme()` | Returns `"light"` or `"dark"` using `matchMedia("(prefers-color-scheme: dark)")`. SSR-safe. |
|
|
346
|
+
| `applyColorScheme(resolved)` | Toggles `light` / `dark` / `automatic` classes on `<html>` and sets `color-scheme`. |
|
|
347
|
+
| `suppressTransitions(nonce?)` | Returns a cleanup that re-enables CSS transitions. No-op when `prefers-reduced-motion: reduce` is set. |
|
|
315
348
|
|
|
316
|
-
### `
|
|
349
|
+
### `colorSchemes`, `colorSchemeSchema`, and defaults
|
|
317
350
|
|
|
318
351
|
```tsx
|
|
319
352
|
import {
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
353
|
+
DEFAULT_RESOLVED_COLOR_SCHEME, // "dark"
|
|
354
|
+
DEFAULT_COLOR_SCHEME, // "automatic"
|
|
355
|
+
colorSchemeSchema, // Zod: z.enum(["light", "dark", "automatic"])
|
|
356
|
+
colorSchemes, // readonly ["light", "dark", "automatic"]
|
|
324
357
|
} from "@codefast/theme";
|
|
325
358
|
|
|
326
|
-
//
|
|
327
|
-
import {
|
|
359
|
+
// STORAGE_KEY lives in the /constants subpath (intentionally not re-exported from root)
|
|
360
|
+
import { STORAGE_KEY } from "@codefast/theme/constants"; // "ui-theme"
|
|
328
361
|
```
|
|
329
362
|
|
|
330
363
|
### TanStack Start adapter (`@codefast/theme/start`)
|
|
331
364
|
|
|
332
|
-
Server functions and helpers for cookie-backed persistence.
|
|
365
|
+
Server functions and helpers for cookie-backed persistence. They run only on the server; the client calls them as RPC. Wire `@codefast/theme/vite` into your Vite config so they are registered (see [TanStack Start](#tanstack-start)).
|
|
333
366
|
|
|
334
|
-
| Export
|
|
335
|
-
|
|
|
336
|
-
| `
|
|
337
|
-
| `
|
|
338
|
-
| `
|
|
339
|
-
| `
|
|
340
|
-
| `
|
|
341
|
-
| `
|
|
367
|
+
| Export | Signature | Use |
|
|
368
|
+
| ---------------------------- | ------------------------------------------------------------------- | -------------------------------------------------------------------- |
|
|
369
|
+
| `getRootColorSchemeServerFn` | `() => Promise<RootColorSchemeLoaderData>` | One call for the root loader: `{ colorScheme, ssrColorScheme }`. |
|
|
370
|
+
| `getColorSchemeServerFn` | `() => Promise<ColorScheme>` | Re-read the cookie; pass as `AppearanceProvider`'s `syncFromServer`. |
|
|
371
|
+
| `getSsrColorSchemeServerFn` | `() => Promise<ResolvedColorScheme>` | Resolved OS appearance from Client Hints only. |
|
|
372
|
+
| `setColorSchemeServerFn` | `(opts: { data: ColorScheme }) => Promise<void>` | `POST` server fn (Zod-validated) that writes the httpOnly cookie. |
|
|
373
|
+
| `persistColorSchemeCookie` | `(value: ColorScheme) => Promise<void>` | Default `persistColorScheme` — wraps `setColorSchemeServerFn`. |
|
|
374
|
+
| `RootColorSchemeLoaderData` | `{ colorScheme: ColorScheme; ssrColorScheme: ResolvedColorScheme }` | Return type of `getRootColorSchemeServerFn`. |
|
|
342
375
|
|
|
343
376
|
---
|
|
344
377
|
|
|
@@ -346,19 +379,20 @@ Server functions and helpers for cookie-backed persistence. All helpers are safe
|
|
|
346
379
|
|
|
347
380
|
The root `@codefast/theme` entry re-exports the common surface. Granular subpaths are available for bundler-aware tree-shaking.
|
|
348
381
|
|
|
349
|
-
| Subpath | Contents
|
|
350
|
-
| ------------------------------------------------ |
|
|
351
|
-
| `@codefast/theme` | `
|
|
352
|
-
| `@codefast/theme/start` | TanStack Start server functions + `
|
|
353
|
-
| `@codefast/theme/
|
|
354
|
-
| `@codefast/theme/
|
|
355
|
-
| `@codefast/theme/core/
|
|
356
|
-
| `@codefast/theme/core/
|
|
357
|
-
| `@codefast/theme/
|
|
358
|
-
| `@codefast/theme/
|
|
359
|
-
| `@codefast/theme/utils/
|
|
360
|
-
| `@codefast/theme/
|
|
361
|
-
| `@codefast/theme/
|
|
382
|
+
| Subpath | Contents |
|
|
383
|
+
| ------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------- |
|
|
384
|
+
| `@codefast/theme` | `AppearanceProvider`, `useColorScheme`, `AppearanceScript`, `resolveColorScheme`, types, `colorSchemes`, defaults |
|
|
385
|
+
| `@codefast/theme/start` | TanStack Start server functions + `persistColorSchemeCookie`, `RootColorSchemeLoaderData` |
|
|
386
|
+
| `@codefast/theme/vite` | `codefastTheme` — Vite plugin so a TanStack Start app can consume `/start` from npm |
|
|
387
|
+
| `@codefast/theme/adapters/tanstack-start/server` | Same exports as `/start`, reached via the full adapter path |
|
|
388
|
+
| `@codefast/theme/core/provider` | `AppearanceProvider` |
|
|
389
|
+
| `@codefast/theme/core/use-theme` | `useColorScheme` |
|
|
390
|
+
| `@codefast/theme/core/context` | Raw `ColorSchemeContext` for custom providers |
|
|
391
|
+
| `@codefast/theme/script/theme-script` | `AppearanceScript` |
|
|
392
|
+
| `@codefast/theme/utils/system` | `getSystemColorScheme`, `resolveColorScheme` |
|
|
393
|
+
| `@codefast/theme/utils/dom` | `applyColorScheme`, `suppressTransitions` |
|
|
394
|
+
| `@codefast/theme/constants` | `DEFAULT_COLOR_SCHEME`, `DEFAULT_RESOLVED_COLOR_SCHEME`, `STORAGE_KEY` |
|
|
395
|
+
| `@codefast/theme/types` | `ColorScheme`, `ResolvedColorScheme`, `ColorSchemeContextType`, `colorSchemes`, `colorSchemeSchema` |
|
|
362
396
|
|
|
363
397
|
See `package.json → exports` for the authoritative list.
|
|
364
398
|
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { Plugin } from "vite";
|
|
2
|
+
|
|
3
|
+
//#region src/adapters/tanstack-start/vite.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Create the Vite plugin that lets a TanStack Start app consume `@codefast/theme`'s server
|
|
6
|
+
* functions from npm without manual `ssr.noExternal` / `optimizeDeps.exclude` configuration.
|
|
7
|
+
*
|
|
8
|
+
* @since 0.5.0-canary.0
|
|
9
|
+
*/
|
|
10
|
+
declare function codefastTheme(): Plugin;
|
|
11
|
+
//#endregion
|
|
12
|
+
export { codefastTheme };
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
//#region src/adapters/tanstack-start/vite.ts
|
|
2
|
+
const PACKAGE_NAME = "@codefast/theme";
|
|
3
|
+
/**
|
|
4
|
+
* Create the Vite plugin that lets a TanStack Start app consume `@codefast/theme`'s server
|
|
5
|
+
* functions from npm without manual `ssr.noExternal` / `optimizeDeps.exclude` configuration.
|
|
6
|
+
*
|
|
7
|
+
* @since 0.5.0-canary.0
|
|
8
|
+
*/
|
|
9
|
+
function codefastTheme() {
|
|
10
|
+
return {
|
|
11
|
+
name: "codefast:theme",
|
|
12
|
+
config() {
|
|
13
|
+
return {
|
|
14
|
+
ssr: { noExternal: [PACKAGE_NAME] },
|
|
15
|
+
optimizeDeps: { exclude: [PACKAGE_NAME] }
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
//#endregion
|
|
21
|
+
export { codefastTheme };
|
package/dist/core/provider.d.mts
CHANGED
|
@@ -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;
|
package/dist/core/provider.mjs
CHANGED
|
@@ -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(
|
|
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 (
|
|
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
|
-
|
|
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.
|
|
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",
|
|
@@ -106,6 +106,11 @@
|
|
|
106
106
|
"types": "./dist/utils/system.d.mts",
|
|
107
107
|
"import": "./dist/utils/system.mjs"
|
|
108
108
|
},
|
|
109
|
+
"./vite": {
|
|
110
|
+
"source": "./src/adapters/tanstack-start/vite.ts",
|
|
111
|
+
"types": "./dist/adapters/tanstack-start/vite.d.mts",
|
|
112
|
+
"import": "./dist/adapters/tanstack-start/vite.mjs"
|
|
113
|
+
},
|
|
109
114
|
"./package.json": "./package.json"
|
|
110
115
|
},
|
|
111
116
|
"publishConfig": {
|
|
@@ -120,28 +125,37 @@
|
|
|
120
125
|
"@testing-library/jest-dom": "^6.9.1",
|
|
121
126
|
"@testing-library/react": "^16.3.2",
|
|
122
127
|
"@testing-library/user-event": "^14.6.1",
|
|
123
|
-
"@types/node": "^26.0.
|
|
124
|
-
"@typescript/native-preview": "7.0.0-dev.
|
|
125
|
-
"@vitejs/plugin-react": "^6.0.
|
|
128
|
+
"@types/node": "^26.0.1",
|
|
129
|
+
"@typescript/native-preview": "7.0.0-dev.20260624.1",
|
|
130
|
+
"@vitejs/plugin-react": "^6.0.3",
|
|
126
131
|
"@vitest/coverage-v8": "^4.1.9",
|
|
127
132
|
"jsdom": "^29.1.1",
|
|
128
133
|
"tsdown": "^0.22.3",
|
|
129
134
|
"typescript": "^6.0.3",
|
|
135
|
+
"vite": "^8.1.0",
|
|
130
136
|
"vitest": "^4.1.9",
|
|
131
|
-
"@codefast/typescript-config": "0.
|
|
137
|
+
"@codefast/typescript-config": "0.5.0-canary.1"
|
|
132
138
|
},
|
|
133
139
|
"peerDependencies": {
|
|
140
|
+
"@tanstack/react-start": ">=1.168.0",
|
|
134
141
|
"@types/react": ">=19.0.0",
|
|
135
142
|
"@types/react-dom": ">=19.0.0",
|
|
136
143
|
"react": ">=19.0.0",
|
|
137
|
-
"react-dom": ">=19.0.0"
|
|
144
|
+
"react-dom": ">=19.0.0",
|
|
145
|
+
"vite": ">=6.0.0"
|
|
138
146
|
},
|
|
139
147
|
"peerDependenciesMeta": {
|
|
148
|
+
"@tanstack/react-start": {
|
|
149
|
+
"optional": true
|
|
150
|
+
},
|
|
140
151
|
"@types/react": {
|
|
141
152
|
"optional": true
|
|
142
153
|
},
|
|
143
154
|
"@types/react-dom": {
|
|
144
155
|
"optional": true
|
|
156
|
+
},
|
|
157
|
+
"vite": {
|
|
158
|
+
"optional": true
|
|
145
159
|
}
|
|
146
160
|
},
|
|
147
161
|
"engines": {
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Vite plugin that wires `@codefast/theme`'s TanStack Start server functions into a consumer build.
|
|
3
|
+
*
|
|
4
|
+
* `@codefast/theme/start` ships `createServerFn()` calls inside its published `dist`. TanStack
|
|
5
|
+
* Start registers each server function's RPC endpoint at **build time, in the consuming app**.
|
|
6
|
+
* For that transform to run over this package, it must not be externalized for SSR nor
|
|
7
|
+
* pre-bundled for the client — otherwise the endpoints never register and calls fail at runtime.
|
|
8
|
+
*
|
|
9
|
+
* This plugin applies exactly that, so consumers don't have to hand-write `ssr.noExternal` and
|
|
10
|
+
* `optimizeDeps.exclude` themselves.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```ts
|
|
14
|
+
* // vite.config.ts
|
|
15
|
+
* import { codefastTheme } from "@codefast/theme/vite";
|
|
16
|
+
* import { tanstackStart } from "@tanstack/react-start/plugin/vite";
|
|
17
|
+
* import viteReact from "@vitejs/plugin-react";
|
|
18
|
+
* import { defineConfig } from "vite";
|
|
19
|
+
*
|
|
20
|
+
* export default defineConfig({
|
|
21
|
+
* plugins: [codefastTheme(), tanstackStart(), viteReact()],
|
|
22
|
+
* });
|
|
23
|
+
* ```
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
import type { Plugin } from "vite";
|
|
27
|
+
|
|
28
|
+
const PACKAGE_NAME = "@codefast/theme";
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Create the Vite plugin that lets a TanStack Start app consume `@codefast/theme`'s server
|
|
32
|
+
* functions from npm without manual `ssr.noExternal` / `optimizeDeps.exclude` configuration.
|
|
33
|
+
*
|
|
34
|
+
* @since 0.5.0-canary.0
|
|
35
|
+
*/
|
|
36
|
+
export function codefastTheme(): Plugin {
|
|
37
|
+
return {
|
|
38
|
+
name: "codefast:theme",
|
|
39
|
+
config() {
|
|
40
|
+
return {
|
|
41
|
+
ssr: {
|
|
42
|
+
noExternal: [PACKAGE_NAME],
|
|
43
|
+
},
|
|
44
|
+
optimizeDeps: {
|
|
45
|
+
exclude: [PACKAGE_NAME],
|
|
46
|
+
},
|
|
47
|
+
};
|
|
48
|
+
},
|
|
49
|
+
};
|
|
50
|
+
}
|
package/src/core/provider.tsx
CHANGED
|
@@ -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
|
|
170
|
-
|
|
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
|
-
//
|
|
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 (
|
|
315
|
-
await
|
|
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,
|
|
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} />;
|