@codefast/theme 0.5.0-canary.5 → 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.
Files changed (50) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/README.md +86 -270
  3. package/dist/{appearance-context.d.mts → appearance-context.d.ts} +3 -6
  4. package/dist/appearance-context.d.ts.map +1 -0
  5. package/dist/appearance-context.js +17 -0
  6. package/dist/appearance-context.js.map +1 -0
  7. package/dist/appearance-provider.d.ts +63 -0
  8. package/dist/appearance-provider.d.ts.map +1 -0
  9. package/dist/appearance-provider.js +240 -0
  10. package/dist/appearance-provider.js.map +1 -0
  11. package/dist/{appearance-script.d.mts → appearance-script.d.ts} +20 -27
  12. package/dist/appearance-script.d.ts.map +1 -0
  13. package/dist/appearance-script.js +51 -0
  14. package/dist/appearance-script.js.map +1 -0
  15. package/dist/{appearance.d.mts → appearance.d.ts} +13 -16
  16. package/dist/appearance.d.ts.map +1 -0
  17. package/dist/appearance.js +27 -0
  18. package/dist/appearance.js.map +1 -0
  19. package/dist/{color-scheme.d.mts → color-scheme.d.ts} +4 -7
  20. package/dist/color-scheme.d.ts.map +1 -0
  21. package/dist/color-scheme.js +37 -0
  22. package/dist/color-scheme.js.map +1 -0
  23. package/dist/{constants.d.mts → constants.d.ts} +7 -10
  24. package/dist/constants.d.ts.map +1 -0
  25. package/dist/constants.js +46 -0
  26. package/dist/constants.js.map +1 -0
  27. package/dist/{dom.d.mts → dom.d.ts} +4 -7
  28. package/dist/dom.d.ts.map +1 -0
  29. package/dist/dom.js +71 -0
  30. package/dist/dom.js.map +1 -0
  31. package/dist/index.d.ts +23 -0
  32. package/dist/index.d.ts.map +1 -0
  33. package/dist/index.js +24 -0
  34. package/dist/index.js.map +1 -0
  35. package/dist/{use-appearance.d.mts → use-appearance.d.ts} +3 -6
  36. package/dist/use-appearance.d.ts.map +1 -0
  37. package/dist/use-appearance.js +41 -0
  38. package/dist/use-appearance.js.map +1 -0
  39. package/package.json +47 -39
  40. package/dist/appearance-context.mjs +0 -16
  41. package/dist/appearance-provider.d.mts +0 -74
  42. package/dist/appearance-provider.mjs +0 -180
  43. package/dist/appearance-script.mjs +0 -46
  44. package/dist/appearance.mjs +0 -25
  45. package/dist/color-scheme.mjs +0 -32
  46. package/dist/constants.mjs +0 -42
  47. package/dist/dom.mjs +0 -52
  48. package/dist/index.d.mts +0 -7
  49. package/dist/index.mjs +0 -7
  50. package/dist/use-appearance.mjs +0 -38
package/CHANGELOG.md CHANGED
@@ -1,5 +1,50 @@
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
+
3
48
  ## 0.5.0-canary.5
4
49
 
5
50
  ## 0.5.0-canary.4
package/README.md CHANGED
@@ -1,93 +1,33 @@
1
1
  # @codefast/theme
2
2
 
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.
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
- [![CI](https://github.com/codefastlabs/codefast/actions/workflows/release.yml/badge.svg)](https://github.com/codefastlabs/codefast/actions/workflows/release.yml)
6
- [![npm version](https://img.shields.io/npm/v/@codefast/theme.svg)](https://www.npmjs.com/package/@codefast/theme)
7
- [![npm downloads](https://img.shields.io/npm/dm/@codefast/theme.svg)](https://www.npmjs.com/package/@codefast/theme)
8
- [![bundle size](https://img.shields.io/bundlephobia/minzip/@codefast/theme)](https://bundlephobia.com/package/@codefast/theme)
9
- [![license](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
+ [![npm version](https://img.shields.io/npm/v/@codefast/theme)](https://www.npmjs.com/package/@codefast/theme)
6
+ [![license](https://img.shields.io/npm/l/@codefast/theme)](https://github.com/codefastlabs/codefast/blob/main/LICENSE)
10
7
 
11
- ---
8
+ Two words, two meanings, kept apart throughout the API:
12
9
 
13
- ## Table of Contents
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
- - [Why @codefast/theme](#why-codefasttheme)
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
- # or
76
- npm install @codefast/theme
77
- # or
78
- yarn add @codefast/theme
21
+ # npm install @codefast/theme
22
+ # yarn add @codefast/theme
79
23
  ```
80
24
 
81
- Peer dependencies:
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
- Current appearance: {appearance}
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
- `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.
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
- ## Recipes
57
+ ```tsx
58
+ import { appearances, useAppearance } from "@codefast/theme";
118
59
 
119
- ### TanStack Start
60
+ function AppearanceSelect() {
61
+ const { appearance, setAppearance, isPending } = useAppearance();
120
62
 
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:
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 RootShell({ children }: { children: React.ReactNode }) {
92
+ function RootDocument({ children }: { children: ReactNode }) {
133
93
  return (
134
94
  <html
135
- className={DEFAULT_COLOR_SCHEME}
136
95
  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.
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 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.
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
- /* show the matching trigger icon based on the stored preference */
204
- html[data-appearance="automatic"] .icon-system {
205
- display: block;
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
- > **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`.
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
- ## API Reference
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
- ### `<AppearanceProvider>`
131
+ ## API
216
132
 
217
- Root provider that wires together appearance state, `localStorage` persistence, OS subscription, optimistic updates, and cross-tab broadcast.
133
+ Everything below ships from the root entry unless a subpath is noted.
218
134
 
219
- ```tsx
220
- <AppearanceProvider disableTransition nonce={cspNonce}>
221
- {children}
222
- </AppearanceProvider>
223
- ```
224
-
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. |
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
- Inline script for the document head that prevents FOUC.
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
- | 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>`. |
154
+ ### AppearanceProvider props
270
155
 
271
- The component emits a `<script>` with `dangerouslySetInnerHTML` and forwards `nonce` when provided.
272
-
273
- ### `resolveColorScheme()`
274
-
275
- ```tsx
276
- import { resolveColorScheme } from "@codefast/theme";
277
-
278
- resolveColorScheme("dark"); // → "dark"
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://opensource.org/licenses/MIT) — see [`package.json`](./package.json).
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 "./appearance.mjs";
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
- //#endregion
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"}