@codefast/theme 0.5.0-canary.1 → 0.5.0-canary.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +33 -0
- package/README.md +107 -178
- package/dist/appearance-context.d.mts +18 -0
- package/dist/appearance-context.mjs +16 -0
- package/dist/appearance-provider.d.mts +74 -0
- package/dist/appearance-provider.mjs +180 -0
- package/dist/appearance-script.d.mts +59 -0
- package/dist/appearance-script.mjs +46 -0
- package/dist/appearance.d.mts +60 -0
- package/dist/appearance.mjs +25 -0
- package/dist/color-scheme.d.mts +27 -0
- package/dist/color-scheme.mjs +32 -0
- package/dist/constants.d.mts +15 -14
- package/dist/constants.mjs +14 -13
- package/dist/{utils/dom.d.mts → dom.d.mts} +6 -8
- package/dist/{utils/dom.mjs → dom.mjs} +7 -9
- package/dist/index.d.mts +7 -7
- package/dist/index.mjs +7 -7
- package/dist/use-appearance.d.mts +34 -0
- package/dist/use-appearance.mjs +38 -0
- package/package.json +39 -63
- package/src/appearance-context.ts +22 -0
- package/src/appearance-provider.tsx +363 -0
- package/src/appearance-script.tsx +86 -0
- package/src/appearance.ts +66 -0
- package/src/color-scheme.ts +42 -0
- package/src/constants.ts +14 -13
- package/src/{utils/dom.ts → dom.ts} +8 -10
- package/src/index.ts +19 -16
- package/src/use-appearance.ts +46 -0
- package/dist/adapters/tanstack-start/server.d.mts +0 -88
- package/dist/adapters/tanstack-start/server.mjs +0 -93
- package/dist/adapters/tanstack-start/vite.d.mts +0 -12
- package/dist/adapters/tanstack-start/vite.mjs +0 -21
- package/dist/core/context.d.mts +0 -18
- package/dist/core/context.mjs +0 -16
- package/dist/core/provider.d.mts +0 -118
- package/dist/core/provider.mjs +0 -231
- package/dist/core/use-theme.d.mts +0 -34
- package/dist/core/use-theme.mjs +0 -38
- package/dist/script/theme-script.d.mts +0 -68
- package/dist/script/theme-script.mjs +0 -45
- package/dist/start.d.mts +0 -2
- package/dist/start.mjs +0 -2
- package/dist/types.d.mts +0 -60
- package/dist/types.mjs +0 -25
- package/dist/utils/system.d.mts +0 -34
- package/dist/utils/system.mjs +0 -40
- package/src/adapters/tanstack-start/server.ts +0 -146
- package/src/adapters/tanstack-start/vite.ts +0 -50
- package/src/core/context.tsx +0 -22
- package/src/core/provider.tsx +0 -470
- package/src/core/use-theme.ts +0 -46
- package/src/script/theme-script.tsx +0 -92
- package/src/start.ts +0 -54
- package/src/types.ts +0 -61
- package/src/utils/system.ts +0 -56
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,38 @@
|
|
|
1
1
|
# @codefast/theme
|
|
2
2
|
|
|
3
|
+
## 0.5.0-canary.3
|
|
4
|
+
|
|
5
|
+
## 0.5.0-canary.2
|
|
6
|
+
|
|
7
|
+
### Patch Changes
|
|
8
|
+
|
|
9
|
+
- [#550](https://github.com/codefastlabs/codefast/pull/550) [`0feb8cd`](https://github.com/codefastlabs/codefast/commit/0feb8cd747cf3831dbba9bc9ed0fb819ec4c9a2b) Thanks [@thevuong](https://github.com/thevuong)! - Rename the public API to follow Apple's Human Interface Guidelines vocabulary: **appearance** is the user's preference (`"light" | "dark" | "automatic"`, like macOS System Settings → Appearance), **color scheme** is the resolved light-or-dark value actually applied (like SwiftUI `ColorScheme` and CSS `color-scheme`). Source files are also flattened so each subpath names what it exports.
|
|
10
|
+
|
|
11
|
+
**Breaking renames:**
|
|
12
|
+
|
|
13
|
+
- Types: `ColorScheme` → `Appearance`; `ResolvedColorScheme` → `ColorScheme`; `ColorSchemeContextType` → `AppearanceContextType`; `colorSchemeSchema` → `appearanceSchema`; `colorSchemes` → `appearances`.
|
|
14
|
+
- Hook: `useColorScheme()` → `useAppearance()`, returning `{ appearance, colorScheme, setAppearance, isPending }` (was `{ colorScheme, resolvedColorScheme, setColorScheme, isPending }`).
|
|
15
|
+
- Provider props: `colorScheme` → `appearance`; `persistColorScheme` → `persistAppearance`. Script prop: `colorScheme` → `appearance`. Context: `ColorSchemeContext` → `AppearanceContext`.
|
|
16
|
+
- Constants: `DEFAULT_COLOR_SCHEME` → `DEFAULT_APPEARANCE` (`"automatic"`); `DEFAULT_RESOLVED_COLOR_SCHEME` → `DEFAULT_COLOR_SCHEME` (`"dark"`). ⚠️ `DEFAULT_COLOR_SCHEME` still exists but now means the resolved fallback — the prop renames make stale usage a compile error.
|
|
17
|
+
- Subpaths: `./types` → `./appearance`; `./core/provider` → `./appearance-provider`; `./core/use-theme` → `./use-appearance`; `./core/context` → `./appearance-context`; `./script/theme-script` → `./appearance-script`; `./utils/system` → `./color-scheme`; `./utils/dom` → `./dom`.
|
|
18
|
+
|
|
19
|
+
- Persisted values: the default `STORAGE_KEY` is now `"ui-appearance"` (was `"ui-theme"`) — returning visitors fall back to `"automatic"` once. The internal `BroadcastChannel` is now `"appearance-sync"` (was `"color-scheme-sync"`).
|
|
20
|
+
|
|
21
|
+
Unchanged: `AppearanceProvider` / `AppearanceScript` component names, the `data-appearance` attribute, `resolveColorScheme()` / `getSystemColorScheme()` / `applyColorScheme()` / `suppressTransitions()`.
|
|
22
|
+
|
|
23
|
+
- [#549](https://github.com/codefastlabs/codefast/pull/549) [`2d16644`](https://github.com/codefastlabs/codefast/commit/2d16644c22f1ad45bb6803ae086caa40e7323576) Thanks [@thevuong](https://github.com/thevuong)! - Remove all server-side handling — the color scheme preference now lives entirely on the client in `localStorage`.
|
|
24
|
+
|
|
25
|
+
**Breaking:**
|
|
26
|
+
|
|
27
|
+
- Removed `@codefast/theme/start`, `@codefast/theme/vite`, and `@codefast/theme/adapters/tanstack-start/server` — the TanStack Start server functions, httpOnly cookie persistence, and the Vite plugin that wired them into consumer builds.
|
|
28
|
+
- Removed `AppearanceProvider`'s `ssrColorScheme` and `syncFromServer` props; the provider also no longer re-syncs from a changed `colorScheme` prop after mount (it is a static fallback now).
|
|
29
|
+
- `resolveColorScheme()` no longer takes an `ssrColorScheme` argument; on the server, `"automatic"` resolves to `DEFAULT_RESOLVED_COLOR_SCHEME`.
|
|
30
|
+
- Dropped the optional `@tanstack/react-start` and `vite` peer dependencies.
|
|
31
|
+
|
|
32
|
+
**Changed defaults:** `storageKey` now defaults to `STORAGE_KEY` (`"ui-appearance"`) and `colorScheme` to `DEFAULT_COLOR_SCHEME` (`"automatic"`) on both `AppearanceScript` and `AppearanceProvider`, so `<AppearanceScript />` + `<AppearanceProvider>` work with zero configuration. `persistColorScheme` / `onPersistError` remain for custom persistence.
|
|
33
|
+
|
|
34
|
+
Migration: drop the root loader and the `codefastTheme()` Vite plugin, render the defaults on `<html>` with `suppressHydrationWarning`, and let the inline script correct the class before paint — see the README's TanStack Start recipe.
|
|
35
|
+
|
|
3
36
|
## 0.5.0-canary.1
|
|
4
37
|
|
|
5
38
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @codefast/theme
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Appearance management for React 19, with vocabulary borrowed from Apple's Human Interface Guidelines: **appearance** is the user's preference (Light / Dark / Auto), **color scheme** is the resolved light-or-dark value actually applied. `localStorage` persistence, FOUC-free first paint, SSR-safe `automatic` resolution, optimistic updates, and cross-tab sync.
|
|
4
4
|
|
|
5
5
|
[](https://github.com/codefastlabs/codefast/actions/workflows/release.yml)
|
|
6
6
|
[](https://www.npmjs.com/package/@codefast/theme)
|
|
@@ -13,22 +13,21 @@ Color-scheme management for React 19 — SSR-safe `automatic` resolution, optimi
|
|
|
13
13
|
## Table of Contents
|
|
14
14
|
|
|
15
15
|
- [Why @codefast/theme](#why-codefasttheme)
|
|
16
|
+
- [Vocabulary](#vocabulary)
|
|
16
17
|
- [Requirements](#requirements)
|
|
17
18
|
- [Installation](#installation)
|
|
18
19
|
- [Quick Start](#quick-start)
|
|
19
20
|
- [Recipes](#recipes)
|
|
20
21
|
- [TanStack Start](#tanstack-start)
|
|
21
|
-
- [
|
|
22
|
-
- [Color scheme toggle](#color-scheme-toggle)
|
|
22
|
+
- [Appearance toggle](#appearance-toggle)
|
|
23
23
|
- [SSR and FOUC prevention](#ssr-and-fouc-prevention)
|
|
24
24
|
- [API Reference](#api-reference)
|
|
25
25
|
- [`<AppearanceProvider>`](#appearanceprovider)
|
|
26
|
-
- [`
|
|
26
|
+
- [`useAppearance()`](#useappearance)
|
|
27
27
|
- [`<AppearanceScript>`](#appearancescript)
|
|
28
28
|
- [`resolveColorScheme()`](#resolvecolorscheme)
|
|
29
29
|
- [`getSystemColorScheme()` / `applyColorScheme()` / `suppressTransitions()`](#getsystemcolorscheme--applycolorscheme--suppresstransitions)
|
|
30
|
-
- [`
|
|
31
|
-
- [TanStack Start adapter (`@codefast/theme/start`)](#tanstack-start-adapter-codefastthemestart)
|
|
30
|
+
- [`appearances`, `appearanceSchema`, and defaults](#appearances-appearanceschema-and-defaults)
|
|
32
31
|
- [Package exports](#package-exports)
|
|
33
32
|
- [Contributing](#contributing)
|
|
34
33
|
- [License](#license)
|
|
@@ -38,25 +37,34 @@ Color-scheme management for React 19 — SSR-safe `automatic` resolution, optimi
|
|
|
38
37
|
|
|
39
38
|
## Why @codefast/theme
|
|
40
39
|
|
|
41
|
-
`@codefast/theme` is a focused
|
|
40
|
+
`@codefast/theme` is a focused appearance state primitive built around the React 19 concurrent APIs. Drop it at the root of your app and let the hook and inline script keep the DOM in sync — the preference lives entirely on the client, in `localStorage`, so no server round-trip is ever needed.
|
|
42
41
|
|
|
43
|
-
- **React 19 first.** Uses `useOptimistic`, `useSyncExternalStore`, and `useEffectEvent` to keep
|
|
44
|
-
- **
|
|
45
|
-
- **
|
|
46
|
-
- **
|
|
47
|
-
- **
|
|
42
|
+
- **React 19 first.** Uses `useOptimistic`, `useSyncExternalStore`, and `useEffectEvent` to keep appearance changes immediate, hydration-safe, and free of needless re-renders.
|
|
43
|
+
- **No flash, anywhere.** A tiny inline `<AppearanceScript>` reads `localStorage` and applies the right class before first paint — including on statically prerendered / CDN-served HTML.
|
|
44
|
+
- **Zero server wiring.** No cookies, loaders, or server functions. Works the same in any React framework, SSR or not.
|
|
45
|
+
- **Cross-tab sync.** Appearance changes propagate between tabs over `BroadcastChannel`, with the `storage` event as fallback.
|
|
46
|
+
- **Optimistic setters.** `setAppearance(value)` updates the UI immediately and reverts automatically if persistence fails.
|
|
48
47
|
- **Tree-shakeable.** Side-effect-free ESM with granular subpaths; bring in only the pieces you use.
|
|
49
48
|
|
|
50
49
|
---
|
|
51
50
|
|
|
51
|
+
## Vocabulary
|
|
52
|
+
|
|
53
|
+
The API follows Apple's Human Interface Guidelines, which map cleanly onto the web platform:
|
|
54
|
+
|
|
55
|
+
| Term | Type | Meaning |
|
|
56
|
+
| ------------- | ---------------------------------- | ---------------------------------------------------------------------------------------------------------- |
|
|
57
|
+
| `Appearance` | `"light" \| "dark" \| "automatic"` | The user's _preference_ — macOS System Settings → Appearance: Light / Dark / Auto. |
|
|
58
|
+
| `ColorScheme` | `"light" \| "dark"` | The _resolved_ value actually applied — SwiftUI `ColorScheme`, CSS `color-scheme`, `prefers-color-scheme`. |
|
|
59
|
+
|
|
60
|
+
`useAppearance()` exposes both: `appearance` (what the user picked) and `colorScheme` (what the page shows).
|
|
61
|
+
|
|
62
|
+
---
|
|
63
|
+
|
|
52
64
|
## Requirements
|
|
53
65
|
|
|
54
66
|
- React `>=19.0.0` (and `react-dom`)
|
|
55
67
|
- TypeScript `>= 5.9` (recommended; the published types target ES2022)
|
|
56
|
-
- TanStack Start `^1` — only if you use `@codefast/theme/start`
|
|
57
|
-
- Vite `>=6` — only if you use `@codefast/theme/vite`
|
|
58
|
-
|
|
59
|
-
All peers except `react` / `react-dom` are optional.
|
|
60
68
|
|
|
61
69
|
---
|
|
62
70
|
|
|
@@ -74,7 +82,6 @@ Peer dependencies:
|
|
|
74
82
|
|
|
75
83
|
```bash
|
|
76
84
|
pnpm add react react-dom
|
|
77
|
-
pnpm add @tanstack/react-start # only if using @codefast/theme/start
|
|
78
85
|
```
|
|
79
86
|
|
|
80
87
|
---
|
|
@@ -82,28 +89,28 @@ pnpm add @tanstack/react-start # only if using @codefast/theme/start
|
|
|
82
89
|
## Quick Start
|
|
83
90
|
|
|
84
91
|
```tsx
|
|
85
|
-
import { AppearanceProvider,
|
|
92
|
+
import { AppearanceProvider, useAppearance } from "@codefast/theme";
|
|
86
93
|
|
|
87
94
|
function App() {
|
|
88
95
|
return (
|
|
89
|
-
<AppearanceProvider
|
|
96
|
+
<AppearanceProvider>
|
|
90
97
|
<Page />
|
|
91
98
|
</AppearanceProvider>
|
|
92
99
|
);
|
|
93
100
|
}
|
|
94
101
|
|
|
95
102
|
function Page() {
|
|
96
|
-
const {
|
|
103
|
+
const { appearance, setAppearance } = useAppearance();
|
|
97
104
|
|
|
98
105
|
return (
|
|
99
|
-
<button onClick={() =>
|
|
100
|
-
Current
|
|
106
|
+
<button onClick={() => setAppearance(appearance === "dark" ? "light" : "dark")}>
|
|
107
|
+
Current appearance: {appearance}
|
|
101
108
|
</button>
|
|
102
109
|
);
|
|
103
110
|
}
|
|
104
111
|
```
|
|
105
112
|
|
|
106
|
-
`
|
|
113
|
+
`appearance` accepts `"light"`, `"dark"`, or `"automatic"`. `colorScheme` from `useAppearance()` always narrows to `"light" | "dark"`. The preference is persisted in `localStorage` under `STORAGE_KEY` (`"ui-appearance"`) by default; pass a custom `storageKey` to both `<AppearanceScript>` and `<AppearanceProvider>` to change it.
|
|
107
114
|
|
|
108
115
|
---
|
|
109
116
|
|
|
@@ -111,54 +118,34 @@ function Page() {
|
|
|
111
118
|
|
|
112
119
|
### TanStack Start
|
|
113
120
|
|
|
114
|
-
|
|
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:
|
|
121
|
+
The shell keeps full control over `<html>` / `<head>` / `<body>`. Server-rendered HTML can't know the preference at request time, so render the defaults and let `<AppearanceScript>` correct the class before paint — `suppressHydrationWarning` absorbs the mismatch. No loader, no server function:
|
|
131
122
|
|
|
132
123
|
```tsx
|
|
133
124
|
// routes/__root.tsx (adjust to your router setup)
|
|
134
|
-
import { AppearanceProvider, AppearanceScript,
|
|
135
|
-
import { getColorSchemeServerFn, getRootColorSchemeServerFn, persistColorSchemeCookie } from "@codefast/theme/start";
|
|
125
|
+
import { AppearanceProvider, AppearanceScript, DEFAULT_APPEARANCE, DEFAULT_COLOR_SCHEME } from "@codefast/theme";
|
|
136
126
|
import { HeadContent, Scripts, createRootRoute } from "@tanstack/react-router";
|
|
137
127
|
|
|
138
128
|
export const Route = createRootRoute({
|
|
139
|
-
loader: () => getRootColorSchemeServerFn(),
|
|
140
129
|
shellComponent: RootShell,
|
|
141
130
|
});
|
|
142
131
|
|
|
143
132
|
function RootShell({ children }: { children: React.ReactNode }) {
|
|
144
|
-
const { colorScheme, ssrColorScheme } = Route.useLoaderData();
|
|
145
|
-
const resolved = resolveColorScheme(colorScheme, ssrColorScheme);
|
|
146
|
-
|
|
147
133
|
return (
|
|
148
|
-
<html
|
|
134
|
+
<html
|
|
135
|
+
className={DEFAULT_COLOR_SCHEME}
|
|
136
|
+
lang="en"
|
|
137
|
+
// "light dark": the pre-paint blank frame follows the OS instead of flashing a hardcoded
|
|
138
|
+
// color on reload; AppearanceScript overwrites this with the resolved value before paint.
|
|
139
|
+
style={{ colorScheme: "light dark" }}
|
|
140
|
+
data-appearance={DEFAULT_APPEARANCE}
|
|
141
|
+
suppressHydrationWarning
|
|
142
|
+
>
|
|
149
143
|
<head>
|
|
144
|
+
<AppearanceScript />
|
|
150
145
|
<HeadContent />
|
|
151
|
-
<AppearanceScript colorScheme={colorScheme} />
|
|
152
146
|
</head>
|
|
153
147
|
<body>
|
|
154
|
-
<AppearanceProvider
|
|
155
|
-
colorScheme={colorScheme}
|
|
156
|
-
ssrColorScheme={ssrColorScheme}
|
|
157
|
-
persistColorScheme={persistColorSchemeCookie}
|
|
158
|
-
syncFromServer={getColorSchemeServerFn}
|
|
159
|
-
>
|
|
160
|
-
{children}
|
|
161
|
-
</AppearanceProvider>
|
|
148
|
+
<AppearanceProvider>{children}</AppearanceProvider>
|
|
162
149
|
<Scripts />
|
|
163
150
|
</body>
|
|
164
151
|
</html>
|
|
@@ -166,55 +153,25 @@ function RootShell({ children }: { children: React.ReactNode }) {
|
|
|
166
153
|
}
|
|
167
154
|
```
|
|
168
155
|
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
```
|
|
172
|
-
Accept-CH: Sec-CH-Prefers-Color-Scheme
|
|
173
|
-
Vary: Sec-CH-Prefers-Color-Scheme, Cookie
|
|
174
|
-
```
|
|
175
|
-
|
|
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.
|
|
177
|
-
|
|
178
|
-
### Client-only React (localStorage)
|
|
179
|
-
|
|
180
|
-
For apps without a server framework — or **statically prerendered / CDN-served** apps where the server can't inject the preference at request time — drive the whole thing from `localStorage`. Pass `storageKey` to both `<AppearanceScript>` and `<AppearanceProvider>`:
|
|
181
|
-
|
|
182
|
-
```tsx
|
|
183
|
-
import { AppearanceProvider, AppearanceScript } from "@codefast/theme";
|
|
184
|
-
|
|
185
|
-
const STORAGE_KEY = "color-scheme";
|
|
186
|
-
|
|
187
|
-
// In the document head — reads localStorage before first paint:
|
|
188
|
-
// <AppearanceScript colorScheme="automatic" storageKey={STORAGE_KEY} />
|
|
189
|
-
|
|
190
|
-
function App() {
|
|
191
|
-
return (
|
|
192
|
-
<AppearanceProvider colorScheme="automatic" storageKey={STORAGE_KEY}>
|
|
193
|
-
<YourApp />
|
|
194
|
-
</AppearanceProvider>
|
|
195
|
-
);
|
|
196
|
-
}
|
|
197
|
-
```
|
|
198
|
-
|
|
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.
|
|
156
|
+
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, and syncs across tabs via the `storage` event. Because the script runs before first paint, this works unchanged for **statically prerendered / CDN-served** pages.
|
|
200
157
|
|
|
201
|
-
> SSR has no `localStorage`, so the server renders the `
|
|
158
|
+
> SSR has no `localStorage`, so the server renders the `appearance` prop (default `"automatic"`). 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
159
|
|
|
203
|
-
###
|
|
160
|
+
### Appearance toggle
|
|
204
161
|
|
|
205
162
|
```tsx
|
|
206
|
-
import {
|
|
163
|
+
import { appearances, useAppearance } from "@codefast/theme";
|
|
207
164
|
|
|
208
|
-
export function
|
|
209
|
-
const {
|
|
165
|
+
export function AppearanceSelect() {
|
|
166
|
+
const { appearance, setAppearance, isPending } = useAppearance();
|
|
210
167
|
|
|
211
168
|
return (
|
|
212
169
|
<select
|
|
213
|
-
value={
|
|
170
|
+
value={appearance}
|
|
214
171
|
disabled={isPending}
|
|
215
|
-
onChange={(event) =>
|
|
172
|
+
onChange={(event) => setAppearance(event.target.value as (typeof appearances)[number])}
|
|
216
173
|
>
|
|
217
|
-
{
|
|
174
|
+
{appearances.map((value) => (
|
|
218
175
|
<option key={value} value={value}>
|
|
219
176
|
{value[0].toUpperCase() + value.slice(1)}
|
|
220
177
|
</option>
|
|
@@ -224,17 +181,17 @@ export function ColorSchemeSelect() {
|
|
|
224
181
|
}
|
|
225
182
|
```
|
|
226
183
|
|
|
227
|
-
`
|
|
184
|
+
`appearances` is `["light", "dark", "automatic"]`, so this renders every option without hard-coding the list.
|
|
228
185
|
|
|
229
186
|
---
|
|
230
187
|
|
|
231
188
|
## SSR and FOUC prevention
|
|
232
189
|
|
|
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>`:
|
|
190
|
+
`<AppearanceScript>` injects a tiny synchronous `<script>` into the document head. It runs before first paint, reads the stored preference from `localStorage`, resolves `automatic` via `matchMedia`, and adds the appropriate class + `color-scheme` to `<html>`:
|
|
234
191
|
|
|
235
192
|
```tsx
|
|
236
193
|
<head>
|
|
237
|
-
<AppearanceScript
|
|
194
|
+
<AppearanceScript />
|
|
238
195
|
</head>
|
|
239
196
|
```
|
|
240
197
|
|
|
@@ -257,54 +214,43 @@ html[data-appearance="automatic"] .icon-system {
|
|
|
257
214
|
|
|
258
215
|
### `<AppearanceProvider>`
|
|
259
216
|
|
|
260
|
-
Root provider that wires together
|
|
217
|
+
Root provider that wires together appearance state, `localStorage` persistence, OS subscription, optimistic updates, and cross-tab broadcast.
|
|
261
218
|
|
|
262
219
|
```tsx
|
|
263
|
-
<AppearanceProvider
|
|
264
|
-
colorScheme={initialColorScheme}
|
|
265
|
-
ssrColorScheme="light"
|
|
266
|
-
persistColorScheme={async (value) => {
|
|
267
|
-
/* … */
|
|
268
|
-
}}
|
|
269
|
-
syncFromServer={getColorSchemeServerFn}
|
|
270
|
-
disableTransition
|
|
271
|
-
nonce={cspNonce}
|
|
272
|
-
>
|
|
220
|
+
<AppearanceProvider disableTransition nonce={cspNonce}>
|
|
273
221
|
{children}
|
|
274
222
|
</AppearanceProvider>
|
|
275
223
|
```
|
|
276
224
|
|
|
277
|
-
| Prop
|
|
278
|
-
|
|
|
279
|
-
| `
|
|
280
|
-
| `
|
|
281
|
-
| `
|
|
282
|
-
| `onPersistError`
|
|
283
|
-
| `
|
|
284
|
-
| `
|
|
285
|
-
| `
|
|
286
|
-
| `nonce` | `string` | — | CSP nonce attached to the inline `<style>` element when `disableTransition` is enabled. |
|
|
287
|
-
| `children` | `ReactNode` | — | Application content. |
|
|
225
|
+
| Prop | Type | Default | Description |
|
|
226
|
+
| ------------------- | ----------------------------------------------------------- | ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
227
|
+
| `appearance` | `Appearance` | `"automatic"` | Fallback preference when storage has no valid entry; also what SSR renders. |
|
|
228
|
+
| `storageKey` | `string` | `"ui-appearance"` | `localStorage` key to restore from, auto-persist under, and sync across tabs via the `storage` event. Use the same key as `<AppearanceScript>`. |
|
|
229
|
+
| `persistAppearance` | `(value: Appearance) => Promise<void>` | — | Custom persistence; replaces the `localStorage` auto-persist. Rejects → optimistic update reverts automatically. |
|
|
230
|
+
| `onPersistError` | `(error: unknown, attemptedAppearance: Appearance) => void` | — | Optional hook called when `persistAppearance` rejects; use for custom logging/telemetry/UI feedback. |
|
|
231
|
+
| `disableTransition` | `boolean` | `false` | Temporarily injects a style rule that disables CSS transitions while the color scheme swaps. Respects `prefers-reduced-motion`. |
|
|
232
|
+
| `nonce` | `string` | — | CSP nonce attached to the inline `<style>` element when `disableTransition` is enabled. |
|
|
233
|
+
| `children` | `ReactNode` | — | Application content. |
|
|
288
234
|
|
|
289
235
|
`<AppearanceProvider>` internally:
|
|
290
236
|
|
|
291
|
-
1.
|
|
292
|
-
2. Subscribes to `(prefers-color-scheme: dark)` through `useSyncExternalStore`
|
|
237
|
+
1. Restores the persisted preference from `localStorage` in its initial client render, and tracks an optimistic value for immediate feedback.
|
|
238
|
+
2. Subscribes to `(prefers-color-scheme: dark)` through `useSyncExternalStore` (server snapshot: `DEFAULT_COLOR_SCHEME`).
|
|
293
239
|
3. Applies the resolved class + `color-scheme` to `<html>` whenever it changes.
|
|
294
|
-
4. Broadcasts the new value over `BroadcastChannel("
|
|
240
|
+
4. Broadcasts the new value over `BroadcastChannel("appearance-sync")` so other tabs stay in sync.
|
|
295
241
|
|
|
296
|
-
### `
|
|
242
|
+
### `useAppearance()`
|
|
297
243
|
|
|
298
244
|
```tsx
|
|
299
|
-
const {
|
|
245
|
+
const { appearance, colorScheme, setAppearance, isPending } = useAppearance();
|
|
300
246
|
```
|
|
301
247
|
|
|
302
|
-
| Field
|
|
303
|
-
|
|
|
304
|
-
| `
|
|
305
|
-
| `
|
|
306
|
-
| `
|
|
307
|
-
| `isPending`
|
|
248
|
+
| Field | Type | Description |
|
|
249
|
+
| --------------- | -------------------------------------- | ------------------------------------------------------------------------------------ |
|
|
250
|
+
| `appearance` | `Appearance` | Current preference (reflects the optimistic value while a change is pending). |
|
|
251
|
+
| `colorScheme` | `ColorScheme` | `"light"` or `"dark"` — the value actually applied to `<html>`. |
|
|
252
|
+
| `setAppearance` | `(value: Appearance) => Promise<void>` | Update + persist. Resolves once persistence settles; on failure the UI reverts. |
|
|
253
|
+
| `isPending` | `boolean` | `true` while the optimistic value differs from the persisted one (change in flight). |
|
|
308
254
|
|
|
309
255
|
Throws if called outside of an `<AppearanceProvider>`.
|
|
310
256
|
|
|
@@ -313,14 +259,14 @@ Throws if called outside of an `<AppearanceProvider>`.
|
|
|
313
259
|
Inline script for the document head that prevents FOUC.
|
|
314
260
|
|
|
315
261
|
```tsx
|
|
316
|
-
<AppearanceScript
|
|
262
|
+
<AppearanceScript nonce={cspNonce} />
|
|
317
263
|
```
|
|
318
264
|
|
|
319
|
-
| Prop
|
|
320
|
-
|
|
|
321
|
-
| `
|
|
322
|
-
| `
|
|
323
|
-
| `
|
|
265
|
+
| Prop | Type | Default | Description |
|
|
266
|
+
| ------------ | ------------ | ----------------- | --------------------------------------------------------------------------------------------------- |
|
|
267
|
+
| `appearance` | `Appearance` | `"automatic"` | Fallback when the storage entry is absent or unrecognised. `"automatic"` resolves via `matchMedia`. |
|
|
268
|
+
| `storageKey` | `string` | `"ui-appearance"` | `localStorage` key the script reads before first paint. Use the same key as `<AppearanceProvider>`. |
|
|
269
|
+
| `nonce` | `string` | — | Optional CSP nonce attached to the inline `<script>`. |
|
|
324
270
|
|
|
325
271
|
The component emits a `<script>` with `dangerouslySetInnerHTML` and forwards `nonce` when provided.
|
|
326
272
|
|
|
@@ -331,68 +277,51 @@ import { resolveColorScheme } from "@codefast/theme";
|
|
|
331
277
|
|
|
332
278
|
resolveColorScheme("dark"); // → "dark"
|
|
333
279
|
resolveColorScheme("automatic"); // client: OS preference via matchMedia
|
|
334
|
-
resolveColorScheme("automatic", "light"); // server: use Client Hints fallback
|
|
335
280
|
```
|
|
336
281
|
|
|
337
|
-
|
|
282
|
+
Resolves an `Appearance` to the `ColorScheme` to apply (`"light" | "dark"`). On the server, `"automatic"` falls back to `DEFAULT_COLOR_SCHEME` (`"dark"`).
|
|
338
283
|
|
|
339
284
|
### `getSystemColorScheme()` / `applyColorScheme()` / `suppressTransitions()`
|
|
340
285
|
|
|
341
|
-
Granular helpers from `@codefast/theme/
|
|
286
|
+
Granular helpers from `@codefast/theme/color-scheme` and `@codefast/theme/dom` for custom integrations:
|
|
342
287
|
|
|
343
|
-
| Function
|
|
344
|
-
|
|
|
345
|
-
| `getSystemColorScheme()`
|
|
346
|
-
| `applyColorScheme(
|
|
347
|
-
| `suppressTransitions(nonce?)`
|
|
288
|
+
| Function | Summary |
|
|
289
|
+
| ------------------------------- | ------------------------------------------------------------------------------------------------------ |
|
|
290
|
+
| `getSystemColorScheme()` | Returns `"light"` or `"dark"` using `matchMedia("(prefers-color-scheme: dark)")`. SSR-safe. |
|
|
291
|
+
| `applyColorScheme(colorScheme)` | Toggles `light` / `dark` / `automatic` classes on `<html>` and sets `color-scheme`. |
|
|
292
|
+
| `suppressTransitions(nonce?)` | Returns a cleanup that re-enables CSS transitions. No-op when `prefers-reduced-motion: reduce` is set. |
|
|
348
293
|
|
|
349
|
-
### `
|
|
294
|
+
### `appearances`, `appearanceSchema`, and defaults
|
|
350
295
|
|
|
351
296
|
```tsx
|
|
352
297
|
import {
|
|
353
|
-
|
|
354
|
-
DEFAULT_COLOR_SCHEME, // "
|
|
355
|
-
|
|
356
|
-
|
|
298
|
+
DEFAULT_APPEARANCE, // "automatic"
|
|
299
|
+
DEFAULT_COLOR_SCHEME, // "dark"
|
|
300
|
+
appearanceSchema, // Zod: z.enum(["light", "dark", "automatic"])
|
|
301
|
+
appearances, // readonly ["light", "dark", "automatic"]
|
|
357
302
|
} from "@codefast/theme";
|
|
358
303
|
|
|
359
304
|
// STORAGE_KEY lives in the /constants subpath (intentionally not re-exported from root)
|
|
360
|
-
import { STORAGE_KEY } from "@codefast/theme/constants"; // "ui-
|
|
305
|
+
import { STORAGE_KEY } from "@codefast/theme/constants"; // "ui-appearance"
|
|
361
306
|
```
|
|
362
307
|
|
|
363
|
-
### TanStack Start adapter (`@codefast/theme/start`)
|
|
364
|
-
|
|
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)).
|
|
366
|
-
|
|
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`. |
|
|
375
|
-
|
|
376
308
|
---
|
|
377
309
|
|
|
378
310
|
## Package exports
|
|
379
311
|
|
|
380
312
|
The root `@codefast/theme` entry re-exports the common surface. Granular subpaths are available for bundler-aware tree-shaking.
|
|
381
313
|
|
|
382
|
-
| Subpath
|
|
383
|
-
|
|
|
384
|
-
| `@codefast/theme`
|
|
385
|
-
| `@codefast/theme/
|
|
386
|
-
| `@codefast/theme/
|
|
387
|
-
| `@codefast/theme/
|
|
388
|
-
| `@codefast/theme/
|
|
389
|
-
| `@codefast/theme/
|
|
390
|
-
| `@codefast/theme/
|
|
391
|
-
| `@codefast/theme/
|
|
392
|
-
| `@codefast/theme/
|
|
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` |
|
|
314
|
+
| Subpath | Contents |
|
|
315
|
+
| ------------------------------------- | ------------------------------------------------------------------------------------------------ |
|
|
316
|
+
| `@codefast/theme` | `AppearanceProvider`, `useAppearance`, `AppearanceScript`, `resolveColorScheme`, types, defaults |
|
|
317
|
+
| `@codefast/theme/appearance` | `Appearance`, `ColorScheme`, `AppearanceContextType`, `appearances`, `appearanceSchema` |
|
|
318
|
+
| `@codefast/theme/appearance-provider` | `AppearanceProvider` |
|
|
319
|
+
| `@codefast/theme/appearance-script` | `AppearanceScript` |
|
|
320
|
+
| `@codefast/theme/appearance-context` | Raw `AppearanceContext` for custom providers |
|
|
321
|
+
| `@codefast/theme/use-appearance` | `useAppearance` |
|
|
322
|
+
| `@codefast/theme/color-scheme` | `getSystemColorScheme`, `resolveColorScheme` |
|
|
323
|
+
| `@codefast/theme/dom` | `applyColorScheme`, `suppressTransitions` |
|
|
324
|
+
| `@codefast/theme/constants` | `DEFAULT_APPEARANCE`, `DEFAULT_COLOR_SCHEME`, `STORAGE_KEY` |
|
|
396
325
|
|
|
397
326
|
See `package.json → exports` for the authoritative list.
|
|
398
327
|
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { AppearanceContextType } from "./appearance.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/appearance-context.d.ts
|
|
4
|
+
type AppearanceContextValue = null | AppearanceContextType;
|
|
5
|
+
/**
|
|
6
|
+
* React context for appearance state management.
|
|
7
|
+
*
|
|
8
|
+
* Provides access to the current appearance, resolved color scheme, setter function, and pending state.
|
|
9
|
+
* Use {@link useAppearance} hook instead of consuming this context directly.
|
|
10
|
+
*
|
|
11
|
+
* @see {@link AppearanceProvider} - Provider component
|
|
12
|
+
* @see {@link useAppearance} - Consumer hook
|
|
13
|
+
*
|
|
14
|
+
* @since 0.5.0-canary.2
|
|
15
|
+
*/
|
|
16
|
+
declare const AppearanceContext: import("react").Context<AppearanceContextValue>;
|
|
17
|
+
//#endregion
|
|
18
|
+
export { AppearanceContext };
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { createContext } from "react";
|
|
2
|
+
//#region src/appearance-context.ts
|
|
3
|
+
/**
|
|
4
|
+
* React context for appearance state management.
|
|
5
|
+
*
|
|
6
|
+
* Provides access to the current appearance, resolved color scheme, setter function, and pending state.
|
|
7
|
+
* Use {@link useAppearance} hook instead of consuming this context directly.
|
|
8
|
+
*
|
|
9
|
+
* @see {@link AppearanceProvider} - Provider component
|
|
10
|
+
* @see {@link useAppearance} - Consumer hook
|
|
11
|
+
*
|
|
12
|
+
* @since 0.5.0-canary.2
|
|
13
|
+
*/
|
|
14
|
+
const AppearanceContext = createContext(null);
|
|
15
|
+
//#endregion
|
|
16
|
+
export { AppearanceContext };
|