@codefast/theme 0.5.0-canary.0 → 0.5.0-canary.2
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 +39 -0
- package/README.md +116 -183
- 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 -59
- 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 -102
- package/dist/core/provider.mjs +0 -183
- 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 -66
- package/dist/script/theme-script.mjs +0 -43
- 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 -364
- package/src/core/use-theme.ts +0 -46
- package/src/script/theme-script.tsx +0 -90
- 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,44 @@
|
|
|
1
1
|
# @codefast/theme
|
|
2
2
|
|
|
3
|
+
## 0.5.0-canary.2
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [#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.
|
|
8
|
+
|
|
9
|
+
**Breaking renames:**
|
|
10
|
+
|
|
11
|
+
- Types: `ColorScheme` → `Appearance`; `ResolvedColorScheme` → `ColorScheme`; `ColorSchemeContextType` → `AppearanceContextType`; `colorSchemeSchema` → `appearanceSchema`; `colorSchemes` → `appearances`.
|
|
12
|
+
- Hook: `useColorScheme()` → `useAppearance()`, returning `{ appearance, colorScheme, setAppearance, isPending }` (was `{ colorScheme, resolvedColorScheme, setColorScheme, isPending }`).
|
|
13
|
+
- Provider props: `colorScheme` → `appearance`; `persistColorScheme` → `persistAppearance`. Script prop: `colorScheme` → `appearance`. Context: `ColorSchemeContext` → `AppearanceContext`.
|
|
14
|
+
- 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.
|
|
15
|
+
- 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`.
|
|
16
|
+
|
|
17
|
+
- 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"`).
|
|
18
|
+
|
|
19
|
+
Unchanged: `AppearanceProvider` / `AppearanceScript` component names, the `data-appearance` attribute, `resolveColorScheme()` / `getSystemColorScheme()` / `applyColorScheme()` / `suppressTransitions()`.
|
|
20
|
+
|
|
21
|
+
- [#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`.
|
|
22
|
+
|
|
23
|
+
**Breaking:**
|
|
24
|
+
|
|
25
|
+
- 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.
|
|
26
|
+
- 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).
|
|
27
|
+
- `resolveColorScheme()` no longer takes an `ssrColorScheme` argument; on the server, `"automatic"` resolves to `DEFAULT_RESOLVED_COLOR_SCHEME`.
|
|
28
|
+
- Dropped the optional `@tanstack/react-start` and `vite` peer dependencies.
|
|
29
|
+
|
|
30
|
+
**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.
|
|
31
|
+
|
|
32
|
+
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.
|
|
33
|
+
|
|
34
|
+
## 0.5.0-canary.1
|
|
35
|
+
|
|
36
|
+
### Minor Changes
|
|
37
|
+
|
|
38
|
+
- [#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.
|
|
39
|
+
|
|
40
|
+
`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.
|
|
41
|
+
|
|
3
42
|
## 0.5.0-canary.0
|
|
4
43
|
|
|
5
44
|
### 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,61 +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)
|
|
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.
|
|
179
157
|
|
|
180
|
-
|
|
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.
|
|
181
159
|
|
|
182
|
-
|
|
183
|
-
import { AppearanceProvider } from "@codefast/theme";
|
|
184
|
-
import type { ColorScheme } from "@codefast/theme";
|
|
185
|
-
|
|
186
|
-
const STORAGE_KEY = "color-scheme";
|
|
187
|
-
|
|
188
|
-
function App() {
|
|
189
|
-
const initial =
|
|
190
|
-
typeof window === "undefined"
|
|
191
|
-
? "automatic"
|
|
192
|
-
: ((localStorage.getItem(STORAGE_KEY) as ColorScheme | null) ?? "automatic");
|
|
193
|
-
|
|
194
|
-
return (
|
|
195
|
-
<AppearanceProvider
|
|
196
|
-
colorScheme={initial}
|
|
197
|
-
persistColorScheme={async (value) => {
|
|
198
|
-
localStorage.setItem(STORAGE_KEY, value);
|
|
199
|
-
}}
|
|
200
|
-
>
|
|
201
|
-
<YourApp />
|
|
202
|
-
</AppearanceProvider>
|
|
203
|
-
);
|
|
204
|
-
}
|
|
205
|
-
```
|
|
206
|
-
|
|
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
|
|
160
|
+
### Appearance toggle
|
|
210
161
|
|
|
211
162
|
```tsx
|
|
212
|
-
import {
|
|
163
|
+
import { appearances, useAppearance } from "@codefast/theme";
|
|
213
164
|
|
|
214
|
-
export function
|
|
215
|
-
const {
|
|
165
|
+
export function AppearanceSelect() {
|
|
166
|
+
const { appearance, setAppearance, isPending } = useAppearance();
|
|
216
167
|
|
|
217
168
|
return (
|
|
218
169
|
<select
|
|
219
|
-
value={
|
|
170
|
+
value={appearance}
|
|
220
171
|
disabled={isPending}
|
|
221
|
-
onChange={(event) =>
|
|
172
|
+
onChange={(event) => setAppearance(event.target.value as (typeof appearances)[number])}
|
|
222
173
|
>
|
|
223
|
-
{
|
|
174
|
+
{appearances.map((value) => (
|
|
224
175
|
<option key={value} value={value}>
|
|
225
176
|
{value[0].toUpperCase() + value.slice(1)}
|
|
226
177
|
</option>
|
|
@@ -230,22 +181,31 @@ export function ColorSchemeSelect() {
|
|
|
230
181
|
}
|
|
231
182
|
```
|
|
232
183
|
|
|
233
|
-
`
|
|
184
|
+
`appearances` is `["light", "dark", "automatic"]`, so this renders every option without hard-coding the list.
|
|
234
185
|
|
|
235
186
|
---
|
|
236
187
|
|
|
237
188
|
## SSR and FOUC prevention
|
|
238
189
|
|
|
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>`:
|
|
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>`:
|
|
240
191
|
|
|
241
192
|
```tsx
|
|
242
193
|
<head>
|
|
243
|
-
<AppearanceScript
|
|
194
|
+
<AppearanceScript />
|
|
244
195
|
</head>
|
|
245
196
|
```
|
|
246
197
|
|
|
247
198
|
The script removes any prior `light` / `dark` / `automatic` class on `<html>`, so it is safe to pre-render the markup with `suppressHydrationWarning`.
|
|
248
199
|
|
|
200
|
+
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:
|
|
201
|
+
|
|
202
|
+
```css
|
|
203
|
+
/* show the matching trigger icon based on the stored preference */
|
|
204
|
+
html[data-appearance="automatic"] .icon-system {
|
|
205
|
+
display: block;
|
|
206
|
+
}
|
|
207
|
+
```
|
|
208
|
+
|
|
249
209
|
> **CSP note.** Pass a `nonce` to `<AppearanceScript nonce={...} />` when your policy requires it for inline scripts. The same nonce can also be passed to `<AppearanceProvider nonce={...} />` for the temporary inline `<style>` used by `disableTransition`.
|
|
250
210
|
|
|
251
211
|
---
|
|
@@ -254,53 +214,43 @@ The script removes any prior `light` / `dark` / `automatic` class on `<html>`, s
|
|
|
254
214
|
|
|
255
215
|
### `<AppearanceProvider>`
|
|
256
216
|
|
|
257
|
-
Root provider that wires together
|
|
217
|
+
Root provider that wires together appearance state, `localStorage` persistence, OS subscription, optimistic updates, and cross-tab broadcast.
|
|
258
218
|
|
|
259
219
|
```tsx
|
|
260
|
-
<AppearanceProvider
|
|
261
|
-
colorScheme={initialColorScheme}
|
|
262
|
-
ssrColorScheme="light"
|
|
263
|
-
persistColorScheme={async (value) => {
|
|
264
|
-
/* … */
|
|
265
|
-
}}
|
|
266
|
-
syncFromServer={getColorSchemeServerFn}
|
|
267
|
-
disableTransition
|
|
268
|
-
nonce={cspNonce}
|
|
269
|
-
>
|
|
220
|
+
<AppearanceProvider disableTransition nonce={cspNonce}>
|
|
270
221
|
{children}
|
|
271
222
|
</AppearanceProvider>
|
|
272
223
|
```
|
|
273
224
|
|
|
274
|
-
| Prop
|
|
275
|
-
|
|
|
276
|
-
| `
|
|
277
|
-
| `
|
|
278
|
-
| `
|
|
279
|
-
| `onPersistError`
|
|
280
|
-
| `
|
|
281
|
-
| `
|
|
282
|
-
| `
|
|
283
|
-
| `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. |
|
|
284
234
|
|
|
285
235
|
`<AppearanceProvider>` internally:
|
|
286
236
|
|
|
287
|
-
1.
|
|
288
|
-
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`).
|
|
289
239
|
3. Applies the resolved class + `color-scheme` to `<html>` whenever it changes.
|
|
290
|
-
4. Broadcasts the new value over `BroadcastChannel("
|
|
240
|
+
4. Broadcasts the new value over `BroadcastChannel("appearance-sync")` so other tabs stay in sync.
|
|
291
241
|
|
|
292
|
-
### `
|
|
242
|
+
### `useAppearance()`
|
|
293
243
|
|
|
294
244
|
```tsx
|
|
295
|
-
const {
|
|
245
|
+
const { appearance, colorScheme, setAppearance, isPending } = useAppearance();
|
|
296
246
|
```
|
|
297
247
|
|
|
298
|
-
| Field
|
|
299
|
-
|
|
|
300
|
-
| `
|
|
301
|
-
| `
|
|
302
|
-
| `
|
|
303
|
-
| `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). |
|
|
304
254
|
|
|
305
255
|
Throws if called outside of an `<AppearanceProvider>`.
|
|
306
256
|
|
|
@@ -309,14 +259,14 @@ Throws if called outside of an `<AppearanceProvider>`.
|
|
|
309
259
|
Inline script for the document head that prevents FOUC.
|
|
310
260
|
|
|
311
261
|
```tsx
|
|
312
|
-
<AppearanceScript
|
|
262
|
+
<AppearanceScript nonce={cspNonce} />
|
|
313
263
|
```
|
|
314
264
|
|
|
315
|
-
| Prop
|
|
316
|
-
|
|
|
317
|
-
| `
|
|
318
|
-
| `
|
|
319
|
-
| `
|
|
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>`. |
|
|
320
270
|
|
|
321
271
|
The component emits a `<script>` with `dangerouslySetInnerHTML` and forwards `nonce` when provided.
|
|
322
272
|
|
|
@@ -327,68 +277,51 @@ import { resolveColorScheme } from "@codefast/theme";
|
|
|
327
277
|
|
|
328
278
|
resolveColorScheme("dark"); // → "dark"
|
|
329
279
|
resolveColorScheme("automatic"); // client: OS preference via matchMedia
|
|
330
|
-
resolveColorScheme("automatic", "light"); // server: use Client Hints fallback
|
|
331
280
|
```
|
|
332
281
|
|
|
333
|
-
|
|
282
|
+
Resolves an `Appearance` to the `ColorScheme` to apply (`"light" | "dark"`). On the server, `"automatic"` falls back to `DEFAULT_COLOR_SCHEME` (`"dark"`).
|
|
334
283
|
|
|
335
284
|
### `getSystemColorScheme()` / `applyColorScheme()` / `suppressTransitions()`
|
|
336
285
|
|
|
337
|
-
Granular helpers from `@codefast/theme/
|
|
286
|
+
Granular helpers from `@codefast/theme/color-scheme` and `@codefast/theme/dom` for custom integrations:
|
|
338
287
|
|
|
339
|
-
| Function
|
|
340
|
-
|
|
|
341
|
-
| `getSystemColorScheme()`
|
|
342
|
-
| `applyColorScheme(
|
|
343
|
-
| `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. |
|
|
344
293
|
|
|
345
|
-
### `
|
|
294
|
+
### `appearances`, `appearanceSchema`, and defaults
|
|
346
295
|
|
|
347
296
|
```tsx
|
|
348
297
|
import {
|
|
349
|
-
|
|
350
|
-
DEFAULT_COLOR_SCHEME, // "
|
|
351
|
-
|
|
352
|
-
|
|
298
|
+
DEFAULT_APPEARANCE, // "automatic"
|
|
299
|
+
DEFAULT_COLOR_SCHEME, // "dark"
|
|
300
|
+
appearanceSchema, // Zod: z.enum(["light", "dark", "automatic"])
|
|
301
|
+
appearances, // readonly ["light", "dark", "automatic"]
|
|
353
302
|
} from "@codefast/theme";
|
|
354
303
|
|
|
355
304
|
// STORAGE_KEY lives in the /constants subpath (intentionally not re-exported from root)
|
|
356
|
-
import { STORAGE_KEY } from "@codefast/theme/constants"; // "ui-
|
|
305
|
+
import { STORAGE_KEY } from "@codefast/theme/constants"; // "ui-appearance"
|
|
357
306
|
```
|
|
358
307
|
|
|
359
|
-
### TanStack Start adapter (`@codefast/theme/start`)
|
|
360
|
-
|
|
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)).
|
|
362
|
-
|
|
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`. |
|
|
371
|
-
|
|
372
308
|
---
|
|
373
309
|
|
|
374
310
|
## Package exports
|
|
375
311
|
|
|
376
312
|
The root `@codefast/theme` entry re-exports the common surface. Granular subpaths are available for bundler-aware tree-shaking.
|
|
377
313
|
|
|
378
|
-
| Subpath
|
|
379
|
-
|
|
|
380
|
-
| `@codefast/theme`
|
|
381
|
-
| `@codefast/theme/
|
|
382
|
-
| `@codefast/theme/
|
|
383
|
-
| `@codefast/theme/
|
|
384
|
-
| `@codefast/theme/
|
|
385
|
-
| `@codefast/theme/
|
|
386
|
-
| `@codefast/theme/
|
|
387
|
-
| `@codefast/theme/
|
|
388
|
-
| `@codefast/theme/
|
|
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` |
|
|
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` |
|
|
392
325
|
|
|
393
326
|
See `package.json → exports` for the authoritative list.
|
|
394
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 };
|