@codefast/theme 0.5.0-canary.4 → 0.5.0-canary.6
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 +47 -0
- package/README.md +86 -270
- package/dist/{appearance-context.d.mts → appearance-context.d.ts} +3 -6
- package/dist/appearance-context.d.ts.map +1 -0
- package/dist/appearance-context.js +17 -0
- package/dist/appearance-context.js.map +1 -0
- package/dist/appearance-provider.d.ts +63 -0
- package/dist/appearance-provider.d.ts.map +1 -0
- package/dist/appearance-provider.js +240 -0
- package/dist/appearance-provider.js.map +1 -0
- package/dist/{appearance-script.d.mts → appearance-script.d.ts} +20 -27
- package/dist/appearance-script.d.ts.map +1 -0
- package/dist/appearance-script.js +51 -0
- package/dist/appearance-script.js.map +1 -0
- package/dist/{appearance.d.mts → appearance.d.ts} +13 -16
- package/dist/appearance.d.ts.map +1 -0
- package/dist/appearance.js +27 -0
- package/dist/appearance.js.map +1 -0
- package/dist/{color-scheme.d.mts → color-scheme.d.ts} +4 -7
- package/dist/color-scheme.d.ts.map +1 -0
- package/dist/color-scheme.js +37 -0
- package/dist/color-scheme.js.map +1 -0
- package/dist/{constants.d.mts → constants.d.ts} +7 -10
- package/dist/constants.d.ts.map +1 -0
- package/dist/constants.js +46 -0
- package/dist/constants.js.map +1 -0
- package/dist/{dom.d.mts → dom.d.ts} +4 -7
- package/dist/dom.d.ts.map +1 -0
- package/dist/dom.js +71 -0
- package/dist/dom.js.map +1 -0
- package/dist/index.d.ts +23 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +24 -0
- package/dist/index.js.map +1 -0
- package/dist/{use-appearance.d.mts → use-appearance.d.ts} +3 -6
- package/dist/use-appearance.d.ts.map +1 -0
- package/dist/use-appearance.js +41 -0
- package/dist/use-appearance.js.map +1 -0
- package/package.json +47 -39
- package/dist/appearance-context.mjs +0 -16
- package/dist/appearance-provider.d.mts +0 -74
- package/dist/appearance-provider.mjs +0 -180
- package/dist/appearance-script.mjs +0 -46
- package/dist/appearance.mjs +0 -25
- package/dist/color-scheme.mjs +0 -32
- package/dist/constants.mjs +0 -42
- package/dist/dom.mjs +0 -52
- package/dist/index.d.mts +0 -7
- package/dist/index.mjs +0 -7
- package/dist/use-appearance.mjs +0 -38
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,52 @@
|
|
|
1
1
|
# @codefast/theme
|
|
2
2
|
|
|
3
|
+
## 0.5.0-canary.6
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- [`c634b17`](https://github.com/codefastlabs/codefast/commit/c634b17e6a8d742cbc54e4074408eea51fb55d40) Thanks [@thevuong](https://github.com/thevuong)! - Rename `AppearanceContextType` to `AppearanceContextValue` — the "Type" suffix carried no information (every exported type is a type), while "Value" states the role: the payload provided through `AppearanceContext` and returned by `useAppearance`.
|
|
8
|
+
|
|
9
|
+
- [#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.
|
|
10
|
+
|
|
11
|
+
`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.
|
|
12
|
+
|
|
13
|
+
- [#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`.
|
|
14
|
+
|
|
15
|
+
### Patch Changes
|
|
16
|
+
|
|
17
|
+
- [#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.
|
|
18
|
+
|
|
19
|
+
**Breaking renames:**
|
|
20
|
+
|
|
21
|
+
- Types: `ColorScheme` → `Appearance`; `ResolvedColorScheme` → `ColorScheme`; `ColorSchemeContextType` → `AppearanceContextType`; `colorSchemeSchema` → `appearanceSchema`; `colorSchemes` → `appearances`.
|
|
22
|
+
- Hook: `useColorScheme()` → `useAppearance()`, returning `{ appearance, colorScheme, setAppearance, isPending }` (was `{ colorScheme, resolvedColorScheme, setColorScheme, isPending }`).
|
|
23
|
+
- Provider props: `colorScheme` → `appearance`; `persistColorScheme` → `persistAppearance`. Script prop: `colorScheme` → `appearance`. Context: `ColorSchemeContext` → `AppearanceContext`.
|
|
24
|
+
- 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.
|
|
25
|
+
- 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`.
|
|
26
|
+
|
|
27
|
+
- 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"`).
|
|
28
|
+
|
|
29
|
+
Unchanged: `AppearanceProvider` / `AppearanceScript` component names, the `data-appearance` attribute, `resolveColorScheme()` / `getSystemColorScheme()` / `applyColorScheme()` / `suppressTransitions()`.
|
|
30
|
+
|
|
31
|
+
- [#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`.
|
|
32
|
+
|
|
33
|
+
**Breaking:**
|
|
34
|
+
|
|
35
|
+
- 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.
|
|
36
|
+
- 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).
|
|
37
|
+
- `resolveColorScheme()` no longer takes an `ssrColorScheme` argument; on the server, `"automatic"` resolves to `DEFAULT_RESOLVED_COLOR_SCHEME`.
|
|
38
|
+
- Dropped the optional `@tanstack/react-start` and `vite` peer dependencies.
|
|
39
|
+
|
|
40
|
+
**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.
|
|
41
|
+
|
|
42
|
+
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.
|
|
43
|
+
|
|
44
|
+
## 1.0.0-canary.7
|
|
45
|
+
|
|
46
|
+
## 1.0.0-canary.6
|
|
47
|
+
|
|
48
|
+
## 0.5.0-canary.5
|
|
49
|
+
|
|
3
50
|
## 0.5.0-canary.4
|
|
4
51
|
|
|
5
52
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -1,93 +1,33 @@
|
|
|
1
1
|
# @codefast/theme
|
|
2
2
|
|
|
3
|
-
Appearance management for React 19
|
|
3
|
+
Appearance management for React 19 — optimistic updates, cross-tab sync, and FOUC-free SSR, with vocabulary borrowed from Apple's Human Interface Guidelines.
|
|
4
4
|
|
|
5
|
-
[](https://www.npmjs.com/package/@codefast/theme)
|
|
8
|
-
[](https://bundlephobia.com/package/@codefast/theme)
|
|
9
|
-
[](https://opensource.org/licenses/MIT)
|
|
5
|
+
[](https://www.npmjs.com/package/@codefast/theme)
|
|
6
|
+
[](https://github.com/codefastlabs/codefast/blob/main/LICENSE)
|
|
10
7
|
|
|
11
|
-
|
|
8
|
+
Two words, two meanings, kept apart throughout the API:
|
|
12
9
|
|
|
13
|
-
|
|
10
|
+
| Term | Type | Meaning |
|
|
11
|
+
| ------------- | ---------------------------------- | ------------------------------------------------------------------------------- |
|
|
12
|
+
| `Appearance` | `"light" \| "dark" \| "automatic"` | The user's preference — think macOS System Settings: Light / Dark / Auto. |
|
|
13
|
+
| `ColorScheme` | `"light" \| "dark"` | The resolved value actually applied to the page, after `automatic` is resolved. |
|
|
14
14
|
|
|
15
|
-
|
|
16
|
-
- [Vocabulary](#vocabulary)
|
|
17
|
-
- [Requirements](#requirements)
|
|
18
|
-
- [Installation](#installation)
|
|
19
|
-
- [Quick Start](#quick-start)
|
|
20
|
-
- [Recipes](#recipes)
|
|
21
|
-
- [TanStack Start](#tanstack-start)
|
|
22
|
-
- [Appearance toggle](#appearance-toggle)
|
|
23
|
-
- [SSR and FOUC prevention](#ssr-and-fouc-prevention)
|
|
24
|
-
- [API Reference](#api-reference)
|
|
25
|
-
- [`<AppearanceProvider>`](#appearanceprovider)
|
|
26
|
-
- [`useAppearance()`](#useappearance)
|
|
27
|
-
- [`<AppearanceScript>`](#appearancescript)
|
|
28
|
-
- [`resolveColorScheme()`](#resolvecolorscheme)
|
|
29
|
-
- [`getSystemColorScheme()` / `applyColorScheme()` / `suppressTransitions()`](#getsystemcolorscheme--applycolorscheme--suppresstransitions)
|
|
30
|
-
- [`appearances`, `appearanceSchema`, and defaults](#appearances-appearanceschema-and-defaults)
|
|
31
|
-
- [Package exports](#package-exports)
|
|
32
|
-
- [Contributing](#contributing)
|
|
33
|
-
- [License](#license)
|
|
34
|
-
- [Changelog](#changelog)
|
|
35
|
-
|
|
36
|
-
---
|
|
37
|
-
|
|
38
|
-
## Why @codefast/theme
|
|
39
|
-
|
|
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.
|
|
41
|
-
|
|
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.
|
|
47
|
-
- **Tree-shakeable.** Side-effect-free ESM with granular subpaths; bring in only the pieces you use.
|
|
48
|
-
|
|
49
|
-
---
|
|
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
|
-
|
|
64
|
-
## Requirements
|
|
65
|
-
|
|
66
|
-
- React `>=19.0.0` (and `react-dom`)
|
|
67
|
-
- TypeScript `>= 5.9` (recommended; the published types target ES2022)
|
|
68
|
-
|
|
69
|
-
---
|
|
15
|
+
The preference lives entirely on the client in `localStorage` — no cookies, loaders, or server functions. Built on React 19's `useOptimistic`, `useSyncExternalStore`, and `useEffectEvent`.
|
|
70
16
|
|
|
71
17
|
## Installation
|
|
72
18
|
|
|
73
19
|
```bash
|
|
74
20
|
pnpm add @codefast/theme
|
|
75
|
-
#
|
|
76
|
-
|
|
77
|
-
# or
|
|
78
|
-
yarn add @codefast/theme
|
|
21
|
+
# npm install @codefast/theme
|
|
22
|
+
# yarn add @codefast/theme
|
|
79
23
|
```
|
|
80
24
|
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
```bash
|
|
84
|
-
pnpm add react react-dom
|
|
85
|
-
```
|
|
86
|
-
|
|
87
|
-
---
|
|
25
|
+
Requires `react` and `react-dom` version 19 or later as peer dependencies. Published as `1.0.0-canary.*` pre-releases on the way to a stable 1.0.
|
|
88
26
|
|
|
89
27
|
## Quick Start
|
|
90
28
|
|
|
29
|
+
Wrap your app in the provider, then read and set the appearance from any component:
|
|
30
|
+
|
|
91
31
|
```tsx
|
|
92
32
|
import { AppearanceProvider, useAppearance } from "@codefast/theme";
|
|
93
33
|
|
|
@@ -100,42 +40,62 @@ function App() {
|
|
|
100
40
|
}
|
|
101
41
|
|
|
102
42
|
function Page() {
|
|
103
|
-
const { appearance, setAppearance } = useAppearance();
|
|
43
|
+
const { appearance, colorScheme, setAppearance, isPending } = useAppearance();
|
|
104
44
|
|
|
105
45
|
return (
|
|
106
|
-
<button onClick={() => setAppearance(appearance === "dark" ? "light" : "dark")}>
|
|
107
|
-
|
|
46
|
+
<button disabled={isPending} onClick={() => setAppearance(appearance === "dark" ? "light" : "dark")}>
|
|
47
|
+
Preference: {appearance} — showing: {colorScheme}
|
|
108
48
|
</button>
|
|
109
49
|
);
|
|
110
50
|
}
|
|
111
51
|
```
|
|
112
52
|
|
|
113
|
-
`
|
|
53
|
+
`setAppearance` updates the UI immediately (optimistic), persists to `localStorage`, and reverts automatically if persistence fails. The resolved color scheme is applied to `<html>` as a `light` / `dark` class plus the CSS `color-scheme` property, so Tailwind `dark:` variants and native controls both follow along.
|
|
114
54
|
|
|
115
|
-
|
|
55
|
+
A three-state selector needs no hard-coded list — `appearances` is `["light", "dark", "automatic"]`:
|
|
116
56
|
|
|
117
|
-
|
|
57
|
+
```tsx
|
|
58
|
+
import { appearances, useAppearance } from "@codefast/theme";
|
|
118
59
|
|
|
119
|
-
|
|
60
|
+
function AppearanceSelect() {
|
|
61
|
+
const { appearance, setAppearance, isPending } = useAppearance();
|
|
120
62
|
|
|
121
|
-
|
|
63
|
+
return (
|
|
64
|
+
<select
|
|
65
|
+
disabled={isPending}
|
|
66
|
+
value={appearance}
|
|
67
|
+
onChange={(event) => setAppearance(event.target.value as (typeof appearances)[number])}
|
|
68
|
+
>
|
|
69
|
+
{appearances.map((value) => (
|
|
70
|
+
<option key={value} value={value}>
|
|
71
|
+
{value}
|
|
72
|
+
</option>
|
|
73
|
+
))}
|
|
74
|
+
</select>
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
## FOUC-free SSR
|
|
80
|
+
|
|
81
|
+
React hydrates after first paint, so server-rendered HTML alone would flash the wrong colors for returning visitors. `<AppearanceScript>` fixes this: a tiny inline script in `<head>` that reads `localStorage`, resolves `automatic` via `matchMedia`, and applies the correct class before anything paints — including on statically prerendered, CDN-served pages.
|
|
82
|
+
|
|
83
|
+
A TanStack Start root shell (works the same in any framework that lets you render into the document head):
|
|
122
84
|
|
|
123
85
|
```tsx
|
|
124
|
-
// routes/__root.tsx (adjust to your router setup)
|
|
125
86
|
import { AppearanceProvider, AppearanceScript, DEFAULT_APPEARANCE, DEFAULT_COLOR_SCHEME } from "@codefast/theme";
|
|
126
87
|
import { HeadContent, Scripts, createRootRoute } from "@tanstack/react-router";
|
|
88
|
+
import type { ReactNode } from "react";
|
|
127
89
|
|
|
128
|
-
export const Route = createRootRoute({
|
|
129
|
-
shellComponent: RootShell,
|
|
130
|
-
});
|
|
90
|
+
export const Route = createRootRoute({ shellComponent: RootDocument });
|
|
131
91
|
|
|
132
|
-
function
|
|
92
|
+
function RootDocument({ children }: { children: ReactNode }) {
|
|
133
93
|
return (
|
|
134
94
|
<html
|
|
135
|
-
className={DEFAULT_COLOR_SCHEME}
|
|
136
95
|
lang="en"
|
|
137
|
-
|
|
138
|
-
//
|
|
96
|
+
className={DEFAULT_COLOR_SCHEME}
|
|
97
|
+
// "light dark": the pre-paint frame follows the OS instead of flashing a
|
|
98
|
+
// hardcoded color; AppearanceScript sets the resolved value before paint.
|
|
139
99
|
style={{ colorScheme: "light dark" }}
|
|
140
100
|
data-appearance={DEFAULT_APPEARANCE}
|
|
141
101
|
suppressHydrationWarning
|
|
@@ -153,199 +113,55 @@ function RootShell({ children }: { children: React.ReactNode }) {
|
|
|
153
113
|
}
|
|
154
114
|
```
|
|
155
115
|
|
|
156
|
-
The
|
|
157
|
-
|
|
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.
|
|
159
|
-
|
|
160
|
-
### Appearance toggle
|
|
161
|
-
|
|
162
|
-
```tsx
|
|
163
|
-
import { appearances, useAppearance } from "@codefast/theme";
|
|
164
|
-
|
|
165
|
-
export function AppearanceSelect() {
|
|
166
|
-
const { appearance, setAppearance, isPending } = useAppearance();
|
|
167
|
-
|
|
168
|
-
return (
|
|
169
|
-
<select
|
|
170
|
-
value={appearance}
|
|
171
|
-
disabled={isPending}
|
|
172
|
-
onChange={(event) => setAppearance(event.target.value as (typeof appearances)[number])}
|
|
173
|
-
>
|
|
174
|
-
{appearances.map((value) => (
|
|
175
|
-
<option key={value} value={value}>
|
|
176
|
-
{value[0].toUpperCase() + value.slice(1)}
|
|
177
|
-
</option>
|
|
178
|
-
))}
|
|
179
|
-
</select>
|
|
180
|
-
);
|
|
181
|
-
}
|
|
182
|
-
```
|
|
183
|
-
|
|
184
|
-
`appearances` is `["light", "dark", "automatic"]`, so this renders every option without hard-coding the list.
|
|
185
|
-
|
|
186
|
-
---
|
|
187
|
-
|
|
188
|
-
## SSR and FOUC prevention
|
|
189
|
-
|
|
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>`:
|
|
191
|
-
|
|
192
|
-
```tsx
|
|
193
|
-
<head>
|
|
194
|
-
<AppearanceScript />
|
|
195
|
-
</head>
|
|
196
|
-
```
|
|
197
|
-
|
|
198
|
-
The script removes any prior `light` / `dark` / `automatic` class on `<html>`, so it is safe to pre-render the markup with `suppressHydrationWarning`.
|
|
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:
|
|
116
|
+
The server renders the defaults; the script corrects `<html>` before first paint and `suppressHydrationWarning` absorbs the mismatch. The script also mirrors the preference (not the resolved value) to a `data-appearance` attribute, so preference-aware UI can render correctly from pure CSS on the very first frame:
|
|
201
117
|
|
|
202
118
|
```css
|
|
203
|
-
/*
|
|
204
|
-
html[data-appearance="automatic"] .
|
|
205
|
-
|
|
119
|
+
/* highlight the "Auto" option when the stored preference is automatic */
|
|
120
|
+
html[data-appearance="automatic"] .option-auto {
|
|
121
|
+
background: var(--active);
|
|
206
122
|
}
|
|
207
123
|
```
|
|
208
124
|
|
|
209
|
-
|
|
125
|
+
If your Content Security Policy requires nonces for inline scripts, pass one: `<AppearanceScript nonce={cspNonce} />`. The same prop exists on `<AppearanceProvider>` for the temporary inline style used by `disableTransition`.
|
|
210
126
|
|
|
211
|
-
|
|
127
|
+
## Cross-tab sync
|
|
212
128
|
|
|
213
|
-
|
|
129
|
+
Appearance changes propagate to every open tab: the provider broadcasts over a `BroadcastChannel` and falls back to the `storage` event where the channel is unavailable. Incoming messages are schema-validated before being applied, and each tab re-resolves `automatic` against its own OS preference. No configuration needed — it works out of the box with the default `localStorage` persistence.
|
|
214
130
|
|
|
215
|
-
|
|
131
|
+
## API
|
|
216
132
|
|
|
217
|
-
|
|
133
|
+
Everything below ships from the root entry unless a subpath is noted.
|
|
218
134
|
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
|
226
|
-
|
|
|
227
|
-
| `
|
|
228
|
-
| `
|
|
229
|
-
| `
|
|
230
|
-
| `
|
|
231
|
-
| `
|
|
232
|
-
| `
|
|
233
|
-
| `
|
|
234
|
-
|
|
235
|
-
`<AppearanceProvider>` internally:
|
|
236
|
-
|
|
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`).
|
|
239
|
-
3. Applies the resolved class + `color-scheme` to `<html>` whenever it changes.
|
|
240
|
-
4. Broadcasts the new value over `BroadcastChannel("appearance-sync")` so other tabs stay in sync.
|
|
241
|
-
|
|
242
|
-
### `useAppearance()`
|
|
243
|
-
|
|
244
|
-
```tsx
|
|
245
|
-
const { appearance, colorScheme, setAppearance, isPending } = useAppearance();
|
|
246
|
-
```
|
|
247
|
-
|
|
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). |
|
|
254
|
-
|
|
255
|
-
Throws if called outside of an `<AppearanceProvider>`.
|
|
256
|
-
|
|
257
|
-
### `<AppearanceScript>`
|
|
135
|
+
| Export | Kind | Summary |
|
|
136
|
+
| ---------------------------------------------------------------------------- | --------- | --------------------------------------------------------------------------------------------- |
|
|
137
|
+
| `AppearanceProvider` | component | Owns appearance state: persistence, OS subscription, optimistic updates, cross-tab sync. |
|
|
138
|
+
| `useAppearance()` | hook | Returns `{ appearance, colorScheme, setAppearance, isPending }`; throws outside the provider. |
|
|
139
|
+
| `AppearanceScript` | component | Inline head script that applies the stored preference before first paint. |
|
|
140
|
+
| `resolveColorScheme(appearance)` | function | Resolves an `Appearance` to a `ColorScheme`; `automatic` uses `matchMedia` on the client. |
|
|
141
|
+
| `appearances` | constant | `["light", "dark", "automatic"]` — handy for rendering selectors. |
|
|
142
|
+
| `appearanceSchema` | schema | Zod enum validating appearance values. |
|
|
143
|
+
| `DEFAULT_APPEARANCE` | constant | `"automatic"` — fallback preference. |
|
|
144
|
+
| `DEFAULT_COLOR_SCHEME` | constant | `"dark"` — fallback when `matchMedia` is unavailable (SSR). |
|
|
145
|
+
| `Appearance`, `ColorScheme` | types | The preference and resolved-value unions. |
|
|
146
|
+
| `AppearanceProviderProps`, `AppearanceScriptProps`, `AppearanceContextValue` | types | Prop and context shapes. |
|
|
147
|
+
| `STORAGE_KEY` (`@codefast/theme/constants`) | constant | `"ui-appearance"` — the default `localStorage` key. |
|
|
148
|
+
| `getSystemColorScheme()` (`@codefast/theme/color-scheme`) | function | Reads the OS preference via `matchMedia`; SSR-safe. |
|
|
149
|
+
| `applyColorScheme()`, `suppressTransitions()` (`@codefast/theme/dom`) | functions | DOM helpers for custom integrations. |
|
|
150
|
+
| `AppearanceContext` (`@codefast/theme/appearance-context`) | context | Raw context for custom providers. |
|
|
258
151
|
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
```tsx
|
|
262
|
-
<AppearanceScript nonce={cspNonce} />
|
|
263
|
-
```
|
|
152
|
+
Granular subpaths (`./appearance`, `./appearance-provider`, `./use-appearance`, ...) mirror the source modules for bundler-aware imports — see the `exports` field in `package.json` for the full list.
|
|
264
153
|
|
|
265
|
-
|
|
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>`. |
|
|
154
|
+
### AppearanceProvider props
|
|
270
155
|
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
resolveColorScheme("automatic"); // client: OS preference via matchMedia
|
|
280
|
-
```
|
|
281
|
-
|
|
282
|
-
Resolves an `Appearance` to the `ColorScheme` to apply (`"light" | "dark"`). On the server, `"automatic"` falls back to `DEFAULT_COLOR_SCHEME` (`"dark"`).
|
|
283
|
-
|
|
284
|
-
### `getSystemColorScheme()` / `applyColorScheme()` / `suppressTransitions()`
|
|
285
|
-
|
|
286
|
-
Granular helpers from `@codefast/theme/color-scheme` and `@codefast/theme/dom` for custom integrations:
|
|
287
|
-
|
|
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. |
|
|
293
|
-
|
|
294
|
-
### `appearances`, `appearanceSchema`, and defaults
|
|
295
|
-
|
|
296
|
-
```tsx
|
|
297
|
-
import {
|
|
298
|
-
DEFAULT_APPEARANCE, // "automatic"
|
|
299
|
-
DEFAULT_COLOR_SCHEME, // "dark"
|
|
300
|
-
appearanceSchema, // Zod: z.enum(["light", "dark", "automatic"])
|
|
301
|
-
appearances, // readonly ["light", "dark", "automatic"]
|
|
302
|
-
} from "@codefast/theme";
|
|
303
|
-
|
|
304
|
-
// STORAGE_KEY lives in the /constants subpath (intentionally not re-exported from root)
|
|
305
|
-
import { STORAGE_KEY } from "@codefast/theme/constants"; // "ui-appearance"
|
|
306
|
-
```
|
|
307
|
-
|
|
308
|
-
---
|
|
309
|
-
|
|
310
|
-
## Package exports
|
|
311
|
-
|
|
312
|
-
The root `@codefast/theme` entry re-exports the common surface. Granular subpaths are available for bundler-aware tree-shaking.
|
|
313
|
-
|
|
314
|
-
| Subpath | Contents |
|
|
315
|
-
| ------------------------------------- | ------------------------------------------------------------------------------------------------ |
|
|
316
|
-
| `@codefast/theme` | `AppearanceProvider`, `useAppearance`, `AppearanceScript`, `resolveColorScheme`, types, defaults |
|
|
317
|
-
| `@codefast/theme/appearance` | `Appearance`, `ColorScheme`, `AppearanceContextValue`, `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` |
|
|
325
|
-
|
|
326
|
-
See `package.json → exports` for the authoritative list.
|
|
327
|
-
|
|
328
|
-
---
|
|
329
|
-
|
|
330
|
-
## Contributing
|
|
331
|
-
|
|
332
|
-
This package lives in the [Codefast monorepo](https://github.com/codefastlabs/codefast). From the repo root:
|
|
333
|
-
|
|
334
|
-
```bash
|
|
335
|
-
pnpm --filter @codefast/theme build
|
|
336
|
-
pnpm --filter @codefast/theme test
|
|
337
|
-
pnpm --filter @codefast/theme check-types
|
|
338
|
-
pnpm --filter @codefast/theme dev # watch-mode build
|
|
339
|
-
```
|
|
340
|
-
|
|
341
|
-
---
|
|
156
|
+
| Prop | Default | Description |
|
|
157
|
+
| ------------------- | ----------------- | --------------------------------------------------------------------------------------------- |
|
|
158
|
+
| `appearance` | `"automatic"` | Fallback preference when storage has no valid entry; also what SSR renders. |
|
|
159
|
+
| `storageKey` | `"ui-appearance"` | `localStorage` key — must match the one passed to `<AppearanceScript>`. |
|
|
160
|
+
| `persistAppearance` | — | Custom async persistence replacing the `localStorage` auto-persist; rejection reverts the UI. |
|
|
161
|
+
| `onPersistError` | — | Called with `(error, attemptedAppearance)` when `persistAppearance` rejects. |
|
|
162
|
+
| `disableTransition` | `false` | Suppress CSS transitions while the color scheme swaps; respects `prefers-reduced-motion`. |
|
|
163
|
+
| `nonce` | — | CSP nonce for the inline style injected by `disableTransition`. |
|
|
342
164
|
|
|
343
165
|
## License
|
|
344
166
|
|
|
345
|
-
[MIT](https://
|
|
346
|
-
|
|
347
|
-
---
|
|
348
|
-
|
|
349
|
-
## Changelog
|
|
350
|
-
|
|
351
|
-
See [CHANGELOG.md](./CHANGELOG.md) for the full version history. Releases are also published on [npm](https://www.npmjs.com/package/@codefast/theme?activeTab=versions).
|
|
167
|
+
[MIT](https://github.com/codefastlabs/codefast/blob/main/LICENSE)
|
|
@@ -1,6 +1,4 @@
|
|
|
1
|
-
import { AppearanceContextValue } from "
|
|
2
|
-
|
|
3
|
-
//#region src/appearance-context.d.ts
|
|
1
|
+
import type { AppearanceContextValue } from "#/appearance";
|
|
4
2
|
/**
|
|
5
3
|
* React context for appearance state management.
|
|
6
4
|
*
|
|
@@ -12,6 +10,5 @@ import { AppearanceContextValue } from "./appearance.mjs";
|
|
|
12
10
|
*
|
|
13
11
|
* @since 0.5.0-canary.2
|
|
14
12
|
*/
|
|
15
|
-
declare const AppearanceContext: import("react").Context<AppearanceContextValue | null>;
|
|
16
|
-
//#
|
|
17
|
-
export { AppearanceContext };
|
|
13
|
+
export declare const AppearanceContext: import("react").Context<AppearanceContextValue | null>;
|
|
14
|
+
//# sourceMappingURL=appearance-context.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"appearance-context.d.ts","sourceRoot":"","sources":["../src/appearance-context.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AAM3D;;;;;;;;;;GAUG;AACH,eAAO,MAAM,iBAAiB,wDAAqD,CAAC"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { createContext } from "react";
|
|
2
|
+
/* -----------------------------------------------------------------------------
|
|
3
|
+
* Context
|
|
4
|
+
* -------------------------------------------------------------------------- */
|
|
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
|
+
export const AppearanceContext = createContext(null);
|
|
17
|
+
//# sourceMappingURL=appearance-context.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"appearance-context.js","sourceRoot":"","sources":["../src/appearance-context.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,OAAO,CAAC;AAItC;;gFAEgF;AAEhF;;;;;;;;;;GAUG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,aAAa,CAAgC,IAAI,CAAC,CAAC"}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { JSX, ReactNode } from "react";
|
|
2
|
+
import type { Appearance } from "#/appearance";
|
|
3
|
+
/**
|
|
4
|
+
* @since 0.5.0-canary.2
|
|
5
|
+
*/
|
|
6
|
+
export type AppearanceProviderProps = {
|
|
7
|
+
readonly children: ReactNode;
|
|
8
|
+
/**
|
|
9
|
+
* When true, temporarily suppresses CSS transitions during appearance changes.
|
|
10
|
+
* Prevents jarring color animations when switching appearances.
|
|
11
|
+
* Default: false
|
|
12
|
+
*/
|
|
13
|
+
readonly disableTransition?: boolean;
|
|
14
|
+
/**
|
|
15
|
+
* CSP nonce for inline styles when `disableTransition` is enabled.
|
|
16
|
+
*/
|
|
17
|
+
readonly nonce?: string;
|
|
18
|
+
/**
|
|
19
|
+
* Custom async persistence for appearance changes; replaces the `localStorage` auto-persist.
|
|
20
|
+
*/
|
|
21
|
+
readonly persistAppearance?: (value: Appearance) => Promise<void>;
|
|
22
|
+
/**
|
|
23
|
+
* Callback invoked when `persistAppearance` rejects.
|
|
24
|
+
*/
|
|
25
|
+
readonly onPersistError?: (error: unknown, attemptedAppearance: Appearance) => void;
|
|
26
|
+
/**
|
|
27
|
+
* Fallback preference when storage has no valid entry — also what SSR renders.
|
|
28
|
+
* Defaults to {@link DEFAULT_APPEARANCE}.
|
|
29
|
+
*/
|
|
30
|
+
readonly appearance?: Appearance;
|
|
31
|
+
/**
|
|
32
|
+
* `localStorage` key the preference is restored from and persisted under.
|
|
33
|
+
* Defaults to {@link STORAGE_KEY}; pair with `<AppearanceScript>` using the **same key**.
|
|
34
|
+
*
|
|
35
|
+
* The provider reads the stored value in its initial client render (so the first paint already
|
|
36
|
+
* matches the preference — no flash, no post-mount settle), auto-persists changes to
|
|
37
|
+
* `localStorage` (unless {@link persistAppearance} is also given, which then wins), and syncs
|
|
38
|
+
* across tabs via the `storage` event.
|
|
39
|
+
*
|
|
40
|
+
* @remarks SSR has no `localStorage`, so the server renders the {@link AppearanceProviderProps.appearance}
|
|
41
|
+
* prop. For a returning visitor whose stored preference differs, components that render
|
|
42
|
+
* preference-dependent markup hydrate-reconcile once; gate them behind a mounted flag to avoid that.
|
|
43
|
+
*/
|
|
44
|
+
readonly storageKey?: string;
|
|
45
|
+
};
|
|
46
|
+
/**
|
|
47
|
+
* Provider component for appearance state management.
|
|
48
|
+
*
|
|
49
|
+
* **React 19 Features Used:**
|
|
50
|
+
* - `useOptimistic` - Immediate UI feedback while persisting the preference
|
|
51
|
+
* - `useSyncExternalStore` - SSR-safe subscription to the OS color scheme preference
|
|
52
|
+
* - `useEffectEvent` - Stable callback for cross-tab sync without effect re-runs
|
|
53
|
+
*
|
|
54
|
+
* @example
|
|
55
|
+
* ```tsx
|
|
56
|
+
* // In your root layout — pair with <AppearanceScript /> using the same storage key
|
|
57
|
+
* <AppearanceProvider>{children}</AppearanceProvider>
|
|
58
|
+
* ```
|
|
59
|
+
*
|
|
60
|
+
* @since 0.5.0-canary.2
|
|
61
|
+
*/
|
|
62
|
+
export declare function AppearanceProvider({ children, disableTransition, nonce, onPersistError, persistAppearance, storageKey, appearance: initialAppearance, }: AppearanceProviderProps): JSX.Element;
|
|
63
|
+
//# sourceMappingURL=appearance-provider.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"appearance-provider.d.ts","sourceRoot":"","sources":["../src/appearance-provider.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAa5C,OAAO,KAAK,EAAE,UAAU,EAAuC,MAAM,cAAc,CAAC;AAwEpF;;GAEG;AACH,MAAM,MAAM,uBAAuB,GAAG;IACpC,QAAQ,CAAC,QAAQ,EAAE,SAAS,CAAC;IAC7B;;;;OAIG;IACH,QAAQ,CAAC,iBAAiB,CAAC,EAAE,OAAO,CAAC;IACrC;;OAEG;IACH,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IACxB;;OAEG;IACH,QAAQ,CAAC,iBAAiB,CAAC,EAAE,CAAC,KAAK,EAAE,UAAU,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAClE;;OAEG;IACH,QAAQ,CAAC,cAAc,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,mBAAmB,EAAE,UAAU,KAAK,IAAI,CAAC;IACpF;;;OAGG;IACH,QAAQ,CAAC,UAAU,CAAC,EAAE,UAAU,CAAC;IACjC;;;;;;;;;;;;OAYG;IACH,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;CAC9B,CAAC;AAMF;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,kBAAkB,CAAC,EACjC,QAAQ,EACR,iBAAyB,EACzB,KAAK,EACL,cAAc,EACd,iBAAiB,EACjB,UAAwB,EACxB,UAAU,EAAE,iBAAsC,GACnD,EAAE,uBAAuB,GAAG,GAAG,CAAC,OAAO,CA6MvC"}
|