@codefast/theme 0.4.0-canary.6 → 0.5.0-canary.0
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 +52 -0
- package/README.md +168 -138
- package/dist/adapters/tanstack-start/vite.d.mts +12 -0
- package/dist/adapters/tanstack-start/vite.mjs +21 -0
- package/package.json +18 -8
- package/src/adapters/tanstack-start/vite.ts +50 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,57 @@
|
|
|
1
1
|
# @codefast/theme
|
|
2
2
|
|
|
3
|
+
## 0.5.0-canary.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- [#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`.
|
|
8
|
+
|
|
9
|
+
## 0.4.0
|
|
10
|
+
|
|
11
|
+
### Patch Changes
|
|
12
|
+
|
|
13
|
+
- [`2397801`](https://github.com/codefastlabs/codefast/commit/239780172d7a71c3426382ec66309ec7f39bd883) Thanks [@thevuong](https://github.com/thevuong)! - chore: align package config globs
|
|
14
|
+
|
|
15
|
+
- [`17c6445`](https://github.com/codefastlabs/codefast/commit/17c6445017ed3ffcc3a04db128362329669124e3) Thanks [@thevuong](https://github.com/thevuong)! - Security, correctness, and performance improvements to `ThemeProvider` and `ThemeScript`.
|
|
16
|
+
|
|
17
|
+
**Security**
|
|
18
|
+
|
|
19
|
+
- Validate `BroadcastChannel` messages with `themeSchema.safeParse` before applying — prevents injection from browser extensions or other same-origin scripts
|
|
20
|
+
- Use `JSON.stringify` in `ThemeScript` inline script to safely serialise the theme value
|
|
21
|
+
|
|
22
|
+
**Correctness**
|
|
23
|
+
|
|
24
|
+
- `ThemeProvider` now re-syncs internal state when the `theme` prop changes after mount (e.g. router re-runs the root loader), making the server the authoritative source of truth
|
|
25
|
+
- Fixed `disableTransitionOnChange` timing: animation cleanup now fires after `applyTheme` commits to the DOM instead of prematurely in the async persist `finally` block
|
|
26
|
+
- Added last-write-wins guard (`intentRef`) so rapid `setTheme` calls only commit the most recent intent
|
|
27
|
+
|
|
28
|
+
**Performance**
|
|
29
|
+
|
|
30
|
+
- `setTheme` callback is now stable across theme commits (reads `committedThemeRef` instead of capturing `theme` in deps) — prevents unnecessary re-renders in consumers
|
|
31
|
+
- `BroadcastChannel` is reused from a shared ref instead of opening a new channel on every `setTheme` call
|
|
32
|
+
- Removed obsolete `-moz-`, `-o-`, `-ms-` vendor prefixes from the `disableAnimation` CSS injection
|
|
33
|
+
|
|
34
|
+
**Features**
|
|
35
|
+
|
|
36
|
+
- `ThemeScript` accepts a new `storageKey` prop: when set, the inline script reads `localStorage` before first paint for FOUC-free client-only apps
|
|
37
|
+
- Runtime Zod validation of the `theme` prop in `ThemeProvider` guards against invalid values bypassing TypeScript
|
|
38
|
+
|
|
39
|
+
**Docs / Tests**
|
|
40
|
+
|
|
41
|
+
- Fixed README: `THEME_STORAGE_KEY` import example now correctly points to `@codefast/theme/constants`
|
|
42
|
+
- Added integration tests for the TanStack Start adapter server functions
|
|
43
|
+
- New test coverage for all security and correctness fixes above
|
|
44
|
+
|
|
45
|
+
- [`f79b333`](https://github.com/codefastlabs/codefast/commit/f79b333d0599c19028f29b9889afcbfb99db91a1) Thanks [@thevuong](https://github.com/thevuong)! - feat(dev): enable source condition for zero-rebuild HMR in apps/docs
|
|
46
|
+
|
|
47
|
+
- [`5c82b5e`](https://github.com/codefastlabs/codefast/commit/5c82b5ea742701ac7836ffa8bb4bf4135e069d1d) Thanks [@thevuong](https://github.com/thevuong)! - Use minimum `>=` ranges in peerDependencies instead of `^` caret ranges.
|
|
48
|
+
|
|
49
|
+
- [`ebdf9e3`](https://github.com/codefastlabs/codefast/commit/ebdf9e396d3c3a826f05f278c93d391a0ae5ca45) Thanks [@thevuong](https://github.com/thevuong)! - feat(web): refactor theme management to color scheme system
|
|
50
|
+
|
|
51
|
+
- [`6c3ac44`](https://github.com/codefastlabs/codefast/commit/6c3ac44b7ddb9e5bcf3fbe0757e00ef86f27b513) Thanks [@thevuong](https://github.com/thevuong)! - Normalize import statement order and package.json key order repo-wide via the new oxfmt `sortImports`/`sortPackageJson` settings — purely mechanical, no runtime behavior change.
|
|
52
|
+
|
|
53
|
+
- [`b2cad2e`](https://github.com/codefastlabs/codefast/commit/b2cad2e180977106accbc978131a32d50ef91f9f) Thanks [@thevuong](https://github.com/thevuong)! - fix(theme): migrate `setColorSchemeServerFn` to TanStack Start `.validator` API
|
|
54
|
+
|
|
3
55
|
## 0.4.0-canary.6
|
|
4
56
|
|
|
5
57
|
## 0.4.0-canary.5
|
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,61 @@ 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, persist the
|
|
180
|
+
For apps without a server framework, persist the preference in `localStorage`:
|
|
160
181
|
|
|
161
182
|
```tsx
|
|
162
|
-
import {
|
|
183
|
+
import { AppearanceProvider } from "@codefast/theme";
|
|
184
|
+
import type { ColorScheme } from "@codefast/theme";
|
|
185
|
+
|
|
186
|
+
const STORAGE_KEY = "color-scheme";
|
|
163
187
|
|
|
164
188
|
function App() {
|
|
165
|
-
const
|
|
189
|
+
const initial =
|
|
190
|
+
typeof window === "undefined"
|
|
191
|
+
? "automatic"
|
|
192
|
+
: ((localStorage.getItem(STORAGE_KEY) as ColorScheme | null) ?? "automatic");
|
|
166
193
|
|
|
167
194
|
return (
|
|
168
|
-
<
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
localStorage.setItem(
|
|
195
|
+
<AppearanceProvider
|
|
196
|
+
colorScheme={initial}
|
|
197
|
+
persistColorScheme={async (value) => {
|
|
198
|
+
localStorage.setItem(STORAGE_KEY, value);
|
|
172
199
|
}}
|
|
173
200
|
>
|
|
174
201
|
<YourApp />
|
|
175
|
-
</
|
|
202
|
+
</AppearanceProvider>
|
|
176
203
|
);
|
|
177
204
|
}
|
|
178
205
|
```
|
|
179
206
|
|
|
180
|
-
|
|
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).
|
|
208
|
+
|
|
209
|
+
### Color scheme toggle
|
|
181
210
|
|
|
182
211
|
```tsx
|
|
183
|
-
import {
|
|
212
|
+
import { colorSchemes, useColorScheme } from "@codefast/theme";
|
|
184
213
|
|
|
185
|
-
export function
|
|
186
|
-
const {
|
|
214
|
+
export function ColorSchemeSelect() {
|
|
215
|
+
const { colorScheme, setColorScheme, isPending } = useColorScheme();
|
|
187
216
|
|
|
188
217
|
return (
|
|
189
218
|
<select
|
|
190
|
-
value={
|
|
219
|
+
value={colorScheme}
|
|
191
220
|
disabled={isPending}
|
|
192
|
-
onChange={(event) =>
|
|
221
|
+
onChange={(event) => setColorScheme(event.target.value as (typeof colorSchemes)[number])}
|
|
193
222
|
>
|
|
194
|
-
{
|
|
223
|
+
{colorSchemes.map((value) => (
|
|
195
224
|
<option key={value} value={value}>
|
|
196
225
|
{value[0].toUpperCase() + value.slice(1)}
|
|
197
226
|
</option>
|
|
@@ -201,144 +230,144 @@ export function ThemeSelect() {
|
|
|
201
230
|
}
|
|
202
231
|
```
|
|
203
232
|
|
|
204
|
-
`
|
|
233
|
+
`colorSchemes` is `["light", "dark", "automatic"]`, so this renders every option without hard-coding the list.
|
|
205
234
|
|
|
206
235
|
---
|
|
207
236
|
|
|
208
237
|
## SSR and FOUC prevention
|
|
209
238
|
|
|
210
|
-
`<
|
|
239
|
+
`<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
240
|
|
|
212
241
|
```tsx
|
|
213
242
|
<head>
|
|
214
|
-
<
|
|
243
|
+
<AppearanceScript colorScheme="automatic" />
|
|
215
244
|
</head>
|
|
216
245
|
```
|
|
217
246
|
|
|
218
|
-
The script removes any prior `light` / `dark` / `
|
|
247
|
+
The script removes any prior `light` / `dark` / `automatic` class on `<html>`, so it is safe to pre-render the markup with `suppressHydrationWarning`.
|
|
219
248
|
|
|
220
|
-
> **CSP note.** Pass a `nonce` to `<
|
|
249
|
+
> **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
250
|
|
|
222
251
|
---
|
|
223
252
|
|
|
224
253
|
## API Reference
|
|
225
254
|
|
|
226
|
-
### `<
|
|
255
|
+
### `<AppearanceProvider>`
|
|
227
256
|
|
|
228
|
-
Root provider that wires together
|
|
257
|
+
Root provider that wires together color scheme state, OS subscription, optimistic updates, and cross-tab broadcast.
|
|
229
258
|
|
|
230
259
|
```tsx
|
|
231
|
-
<
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
260
|
+
<AppearanceProvider
|
|
261
|
+
colorScheme={initialColorScheme}
|
|
262
|
+
ssrColorScheme="light"
|
|
263
|
+
persistColorScheme={async (value) => {
|
|
235
264
|
/* … */
|
|
236
265
|
}}
|
|
237
|
-
|
|
238
|
-
|
|
266
|
+
syncFromServer={getColorSchemeServerFn}
|
|
267
|
+
disableTransition
|
|
239
268
|
nonce={cspNonce}
|
|
240
269
|
>
|
|
241
270
|
{children}
|
|
242
|
-
</
|
|
271
|
+
</AppearanceProvider>
|
|
243
272
|
```
|
|
244
273
|
|
|
245
|
-
| Prop
|
|
246
|
-
|
|
|
247
|
-
| `
|
|
248
|
-
| `
|
|
249
|
-
| `
|
|
250
|
-
| `
|
|
251
|
-
| `
|
|
252
|
-
| `
|
|
253
|
-
| `nonce`
|
|
254
|
-
| `children`
|
|
255
|
-
|
|
256
|
-
`<
|
|
257
|
-
|
|
258
|
-
1. Tracks the persisted `
|
|
259
|
-
2. Subscribes to `(prefers-color-scheme: dark)` through `useSyncExternalStore` with a server snapshot backed by `
|
|
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. |
|
|
284
|
+
|
|
285
|
+
`<AppearanceProvider>` internally:
|
|
286
|
+
|
|
287
|
+
1. Tracks the persisted `colorScheme` and an optimistic value for immediate feedback.
|
|
288
|
+
2. Subscribes to `(prefers-color-scheme: dark)` through `useSyncExternalStore` with a server snapshot backed by `ssrColorScheme`.
|
|
260
289
|
3. Applies the resolved class + `color-scheme` to `<html>` whenever it changes.
|
|
261
|
-
4. Broadcasts the new value over `BroadcastChannel("
|
|
290
|
+
4. Broadcasts the new value over `BroadcastChannel("color-scheme-sync")` so other tabs stay in sync.
|
|
262
291
|
|
|
263
|
-
### `
|
|
292
|
+
### `useColorScheme()`
|
|
264
293
|
|
|
265
294
|
```tsx
|
|
266
|
-
const {
|
|
295
|
+
const { colorScheme, resolvedColorScheme, setColorScheme, isPending } = useColorScheme();
|
|
267
296
|
```
|
|
268
297
|
|
|
269
|
-
| Field
|
|
270
|
-
|
|
|
271
|
-
| `
|
|
272
|
-
| `
|
|
273
|
-
| `
|
|
274
|
-
| `isPending`
|
|
298
|
+
| Field | Type | Description |
|
|
299
|
+
| --------------------- | --------------------------------------- | ------------------------------------------------------------------------------------ |
|
|
300
|
+
| `colorScheme` | `ColorScheme` | Current preference (reflects the optimistic value while a change is pending). |
|
|
301
|
+
| `resolvedColorScheme` | `ResolvedColorScheme` | `"light"` or `"dark"` — the value actually applied to `<html>`. |
|
|
302
|
+
| `setColorScheme` | `(value: ColorScheme) => Promise<void>` | Update + persist. Resolves once persistence settles; on failure the UI reverts. |
|
|
303
|
+
| `isPending` | `boolean` | `true` while the optimistic value differs from the persisted one (change in flight). |
|
|
275
304
|
|
|
276
|
-
Throws if called outside of
|
|
305
|
+
Throws if called outside of an `<AppearanceProvider>`.
|
|
277
306
|
|
|
278
|
-
### `<
|
|
307
|
+
### `<AppearanceScript>`
|
|
279
308
|
|
|
280
309
|
Inline script for the document head that prevents FOUC.
|
|
281
310
|
|
|
282
311
|
```tsx
|
|
283
|
-
<
|
|
312
|
+
<AppearanceScript colorScheme={colorScheme} nonce={cspNonce} />
|
|
284
313
|
```
|
|
285
314
|
|
|
286
|
-
| Prop
|
|
287
|
-
|
|
|
288
|
-
| `
|
|
289
|
-
| `nonce`
|
|
290
|
-
| `storageKey`
|
|
315
|
+
| Prop | Type | Description |
|
|
316
|
+
| ------------- | ------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
|
|
317
|
+
| `colorScheme` | `ColorScheme` | The preference to apply on initial render. `"automatic"` resolves via `matchMedia`. Acts as fallback when `storageKey` is provided. |
|
|
318
|
+
| `nonce` | `string` | Optional CSP nonce attached to the inline `<script>`. |
|
|
319
|
+
| `storageKey` | `string` | When set, the script reads `localStorage.getItem(storageKey)` before first paint. Use for client-only apps without an SSR cookie. |
|
|
291
320
|
|
|
292
321
|
The component emits a `<script>` with `dangerouslySetInnerHTML` and forwards `nonce` when provided.
|
|
293
322
|
|
|
294
|
-
### `
|
|
323
|
+
### `resolveColorScheme()`
|
|
295
324
|
|
|
296
325
|
```tsx
|
|
297
|
-
import {
|
|
326
|
+
import { resolveColorScheme } from "@codefast/theme";
|
|
298
327
|
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
328
|
+
resolveColorScheme("dark"); // → "dark"
|
|
329
|
+
resolveColorScheme("automatic"); // client: OS preference via matchMedia
|
|
330
|
+
resolveColorScheme("automatic", "light"); // server: use Client Hints fallback
|
|
302
331
|
```
|
|
303
332
|
|
|
304
|
-
Returns a `
|
|
333
|
+
Returns a `ResolvedColorScheme` (`"light" | "dark"`). On the server without an `ssrColorScheme`, falls back to `DEFAULT_RESOLVED_COLOR_SCHEME` (`"dark"`).
|
|
305
334
|
|
|
306
|
-
### `
|
|
335
|
+
### `getSystemColorScheme()` / `applyColorScheme()` / `suppressTransitions()`
|
|
307
336
|
|
|
308
337
|
Granular helpers from `@codefast/theme/utils/system` and `@codefast/theme/utils/dom` for custom integrations:
|
|
309
338
|
|
|
310
|
-
| Function
|
|
311
|
-
|
|
|
312
|
-
| `
|
|
313
|
-
| `
|
|
314
|
-
| `
|
|
339
|
+
| Function | Summary |
|
|
340
|
+
| ----------------------------- | ------------------------------------------------------------------------------------------------------ |
|
|
341
|
+
| `getSystemColorScheme()` | Returns `"light"` or `"dark"` using `matchMedia("(prefers-color-scheme: dark)")`. SSR-safe. |
|
|
342
|
+
| `applyColorScheme(resolved)` | Toggles `light` / `dark` / `automatic` classes on `<html>` and sets `color-scheme`. |
|
|
343
|
+
| `suppressTransitions(nonce?)` | Returns a cleanup that re-enables CSS transitions. No-op when `prefers-reduced-motion: reduce` is set. |
|
|
315
344
|
|
|
316
|
-
### `
|
|
345
|
+
### `colorSchemes`, `colorSchemeSchema`, and defaults
|
|
317
346
|
|
|
318
347
|
```tsx
|
|
319
348
|
import {
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
349
|
+
DEFAULT_RESOLVED_COLOR_SCHEME, // "dark"
|
|
350
|
+
DEFAULT_COLOR_SCHEME, // "automatic"
|
|
351
|
+
colorSchemeSchema, // Zod: z.enum(["light", "dark", "automatic"])
|
|
352
|
+
colorSchemes, // readonly ["light", "dark", "automatic"]
|
|
324
353
|
} from "@codefast/theme";
|
|
325
354
|
|
|
326
|
-
//
|
|
327
|
-
import {
|
|
355
|
+
// STORAGE_KEY lives in the /constants subpath (intentionally not re-exported from root)
|
|
356
|
+
import { STORAGE_KEY } from "@codefast/theme/constants"; // "ui-theme"
|
|
328
357
|
```
|
|
329
358
|
|
|
330
359
|
### TanStack Start adapter (`@codefast/theme/start`)
|
|
331
360
|
|
|
332
|
-
Server functions and helpers for cookie-backed persistence.
|
|
361
|
+
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
362
|
|
|
334
|
-
| Export
|
|
335
|
-
|
|
|
336
|
-
| `
|
|
337
|
-
| `
|
|
338
|
-
| `
|
|
339
|
-
| `
|
|
340
|
-
| `
|
|
341
|
-
| `
|
|
363
|
+
| Export | Signature | Use |
|
|
364
|
+
| ---------------------------- | ------------------------------------------------------------------- | -------------------------------------------------------------------- |
|
|
365
|
+
| `getRootColorSchemeServerFn` | `() => Promise<RootColorSchemeLoaderData>` | One call for the root loader: `{ colorScheme, ssrColorScheme }`. |
|
|
366
|
+
| `getColorSchemeServerFn` | `() => Promise<ColorScheme>` | Re-read the cookie; pass as `AppearanceProvider`'s `syncFromServer`. |
|
|
367
|
+
| `getSsrColorSchemeServerFn` | `() => Promise<ResolvedColorScheme>` | Resolved OS appearance from Client Hints only. |
|
|
368
|
+
| `setColorSchemeServerFn` | `(opts: { data: ColorScheme }) => Promise<void>` | `POST` server fn (Zod-validated) that writes the httpOnly cookie. |
|
|
369
|
+
| `persistColorSchemeCookie` | `(value: ColorScheme) => Promise<void>` | Default `persistColorScheme` — wraps `setColorSchemeServerFn`. |
|
|
370
|
+
| `RootColorSchemeLoaderData` | `{ colorScheme: ColorScheme; ssrColorScheme: ResolvedColorScheme }` | Return type of `getRootColorSchemeServerFn`. |
|
|
342
371
|
|
|
343
372
|
---
|
|
344
373
|
|
|
@@ -346,19 +375,20 @@ Server functions and helpers for cookie-backed persistence. All helpers are safe
|
|
|
346
375
|
|
|
347
376
|
The root `@codefast/theme` entry re-exports the common surface. Granular subpaths are available for bundler-aware tree-shaking.
|
|
348
377
|
|
|
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/
|
|
378
|
+
| Subpath | Contents |
|
|
379
|
+
| ------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------- |
|
|
380
|
+
| `@codefast/theme` | `AppearanceProvider`, `useColorScheme`, `AppearanceScript`, `resolveColorScheme`, types, `colorSchemes`, defaults |
|
|
381
|
+
| `@codefast/theme/start` | TanStack Start server functions + `persistColorSchemeCookie`, `RootColorSchemeLoaderData` |
|
|
382
|
+
| `@codefast/theme/vite` | `codefastTheme` — Vite plugin so a TanStack Start app can consume `/start` from npm |
|
|
383
|
+
| `@codefast/theme/adapters/tanstack-start/server` | Same exports as `/start`, reached via the full adapter path |
|
|
384
|
+
| `@codefast/theme/core/provider` | `AppearanceProvider` |
|
|
385
|
+
| `@codefast/theme/core/use-theme` | `useColorScheme` |
|
|
386
|
+
| `@codefast/theme/core/context` | Raw `ColorSchemeContext` for custom providers |
|
|
387
|
+
| `@codefast/theme/script/theme-script` | `AppearanceScript` |
|
|
388
|
+
| `@codefast/theme/utils/system` | `getSystemColorScheme`, `resolveColorScheme` |
|
|
389
|
+
| `@codefast/theme/utils/dom` | `applyColorScheme`, `suppressTransitions` |
|
|
390
|
+
| `@codefast/theme/constants` | `DEFAULT_COLOR_SCHEME`, `DEFAULT_RESOLVED_COLOR_SCHEME`, `STORAGE_KEY` |
|
|
391
|
+
| `@codefast/theme/types` | `ColorScheme`, `ResolvedColorScheme`, `ColorSchemeContextType`, `colorSchemes`, `colorSchemeSchema` |
|
|
362
392
|
|
|
363
393
|
See `package.json → exports` for the authoritative list.
|
|
364
394
|
|
|
@@ -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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@codefast/theme",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0-canary.0",
|
|
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": {
|
|
@@ -115,26 +120,28 @@
|
|
|
115
120
|
"zod": "^4.4.3"
|
|
116
121
|
},
|
|
117
122
|
"devDependencies": {
|
|
118
|
-
"@tanstack/react-start": "^1.168.
|
|
123
|
+
"@tanstack/react-start": "^1.168.26",
|
|
119
124
|
"@testing-library/dom": "^10.4.1",
|
|
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": "^
|
|
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
|
-
"tsdown": "^0.22.
|
|
133
|
+
"tsdown": "^0.22.3",
|
|
129
134
|
"typescript": "^6.0.3",
|
|
135
|
+
"vite": "~8.0.16",
|
|
130
136
|
"vitest": "^4.1.9",
|
|
131
|
-
"@codefast/typescript-config": "0.
|
|
137
|
+
"@codefast/typescript-config": "0.5.0-canary.0"
|
|
132
138
|
},
|
|
133
139
|
"peerDependencies": {
|
|
134
140
|
"@types/react": ">=19.0.0",
|
|
135
141
|
"@types/react-dom": ">=19.0.0",
|
|
136
142
|
"react": ">=19.0.0",
|
|
137
|
-
"react-dom": ">=19.0.0"
|
|
143
|
+
"react-dom": ">=19.0.0",
|
|
144
|
+
"vite": ">=6.0.0"
|
|
138
145
|
},
|
|
139
146
|
"peerDependenciesMeta": {
|
|
140
147
|
"@types/react": {
|
|
@@ -142,6 +149,9 @@
|
|
|
142
149
|
},
|
|
143
150
|
"@types/react-dom": {
|
|
144
151
|
"optional": true
|
|
152
|
+
},
|
|
153
|
+
"vite": {
|
|
154
|
+
"optional": true
|
|
145
155
|
}
|
|
146
156
|
},
|
|
147
157
|
"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
|
+
}
|