@codefast/theme 0.8.1 → 0.8.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +24 -0
- package/LICENSE +1 -1
- package/README.md +110 -34
- package/dist/appearance-context.d.ts +1 -2
- package/dist/appearance-context.js +1 -2
- package/dist/appearance-provider.d.ts +1 -2
- package/dist/appearance-provider.js +1 -2
- package/dist/appearance-script.d.ts +1 -2
- package/dist/appearance-script.js +1 -2
- package/dist/appearance.d.ts +2 -3
- package/dist/appearance.js +2 -3
- package/dist/color-scheme.d.ts +1 -2
- package/dist/color-scheme.js +1 -2
- package/dist/constants.d.ts +1 -2
- package/dist/constants.js +1 -2
- package/dist/dom.d.ts +1 -2
- package/dist/dom.js +1 -2
- package/dist/index.d.ts +1 -2
- package/dist/index.js +1 -2
- package/dist/use-appearance.d.ts +1 -2
- package/dist/use-appearance.js +1 -2
- package/package.json +3 -53
- package/dist/appearance-context.d.ts.map +0 -1
- package/dist/appearance-context.js.map +0 -1
- package/dist/appearance-provider.d.ts.map +0 -1
- package/dist/appearance-provider.js.map +0 -1
- package/dist/appearance-script.d.ts.map +0 -1
- package/dist/appearance-script.js.map +0 -1
- package/dist/appearance.d.ts.map +0 -1
- package/dist/appearance.js.map +0 -1
- package/dist/color-scheme.d.ts.map +0 -1
- package/dist/color-scheme.js.map +0 -1
- package/dist/constants.d.ts.map +0 -1
- package/dist/constants.js.map +0 -1
- package/dist/dom.d.ts.map +0 -1
- package/dist/dom.js.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/use-appearance.d.ts.map +0 -1
- package/dist/use-appearance.js.map +0 -1
- package/src/appearance-context.ts +0 -21
- package/src/appearance-provider.tsx +0 -368
- package/src/appearance-script.tsx +0 -87
- package/src/appearance.ts +0 -70
- package/src/color-scheme.ts +0 -40
- package/src/constants.ts +0 -49
- package/src/dom.ts +0 -85
- package/src/index.ts +0 -32
- package/src/use-appearance.ts +0 -44
package/dist/dom.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"dom.d.ts","sourceRoot":"","sources":["../src/dom.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAIhD;;;;;;;;GAQG;AACH,wBAAgB,gBAAgB,CAAC,WAAW,EAAE,WAAW,GAAG,IAAI,CAU/D;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM,IAAI,CAyC9D"}
|
package/dist/dom.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"dom.js","sourceRoot":"","sources":["../src/dom.ts"],"names":[],"mappings":"AAEA,wHAAwH;AAExH;;;;;;;;GAQG;AACH,MAAM,UAAU,gBAAgB,CAAC,WAAwB;IACvD,IAAI,OAAO,UAAU,CAAC,MAAM,KAAK,WAAW,EAAE,CAAC;QAC7C,OAAO;IACT,CAAC;IAED,MAAM,IAAI,GAAG,MAAM,CAAC,QAAQ,CAAC,eAAe,CAAC;IAE7C,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,OAAO,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC;IACpD,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;IAChC,IAAI,CAAC,KAAK,CAAC,WAAW,GAAG,WAAW,CAAC;AACvC,CAAC;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,UAAU,mBAAmB,CAAC,KAAc;IAChD,IAAI,OAAO,UAAU,CAAC,MAAM,KAAK,WAAW,EAAE,CAAC;QAC7C,OAAO,GAAG,EAAE;YACV,UAAU;QACZ,CAAC,CAAC;IACJ,CAAC;IAED,oCAAoC;IACpC,MAAM,oBAAoB,GAAG,UAAU,CAAC,MAAM,CAAC,UAAU,CAAC,kCAAkC,CAAC,CAAC,OAAO,CAAC;IAEtG,IAAI,oBAAoB,EAAE,CAAC;QACzB,OAAO,GAAG,EAAE;YACV,UAAU;QACZ,CAAC,CAAC;IACJ,CAAC;IAED,2CAA2C;IAC3C,MAAM,GAAG,GAAG,QAAQ,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC;IAE5C,IAAI,KAAK,EAAE,CAAC;QACV,GAAG,CAAC,YAAY,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IACnC,CAAC;IAED,0EAA0E;IAC1E,GAAG,CAAC,MAAM,CAAC,QAAQ,CAAC,cAAc,CAAC,iDAAiD,CAAC,CAAC,CAAC;IAEvF,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;IAE1B,OAAO,GAAG,EAAE;QACV,4DAA4D;QAC5D,KAAK,MAAM,CAAC,gBAAgB,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;QAE5C,+DAA+D;QAC/D,qBAAqB,CAAC,GAAG,EAAE;YACzB,qBAAqB,CAAC,GAAG,EAAE;gBACzB,IAAI,GAAG,CAAC,UAAU,EAAE,CAAC;oBACnB,GAAG,CAAC,MAAM,EAAE,CAAC;gBACf,CAAC;YACH,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC,CAAC;AACJ,CAAC"}
|
package/dist/index.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAGH,YAAY,EAAE,UAAU,EAAE,sBAAsB,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AACpF,OAAO,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAG7D,OAAO,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAGvE,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC3D,YAAY,EAAE,uBAAuB,EAAE,MAAM,uBAAuB,CAAC;AACrE,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAGjD,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,YAAY,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AAGjE,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC"}
|
package/dist/index.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAIH,OAAO,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAE7D,YAAY;AACZ,OAAO,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAEvE,qFAAqF;AACrF,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAE3D,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAEjD,2BAA2B;AAC3B,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAGvD,gFAAgF;AAChF,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"use-appearance.d.ts","sourceRoot":"","sources":["../src/use-appearance.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAC;AAK3D;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,wBAAgB,aAAa,IAAI,sBAAsB,CAQtD"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"use-appearance.js","sourceRoot":"","sources":["../src/use-appearance.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,OAAO,CAAC;AAG5B,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAEzD,wHAAwH;AAExH;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,MAAM,UAAU,aAAa;IAC3B,MAAM,KAAK,GAAG,GAAG,CAAC,iBAAiB,CAAC,CAAC;IAErC,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,MAAM,IAAI,KAAK,CAAC,yDAAyD,CAAC,CAAC;IAC7E,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC"}
|
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
import type { Context } from "react";
|
|
2
|
-
import { createContext } from "react";
|
|
3
|
-
|
|
4
|
-
import type { AppearanceContextValue } from "#/appearance";
|
|
5
|
-
|
|
6
|
-
// ── Context ──────────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
* React context for appearance state management.
|
|
10
|
-
*
|
|
11
|
-
* Provides access to the current appearance, resolved color scheme, setter function, and pending state.
|
|
12
|
-
* Use {@link useAppearance} hook instead of consuming this context directly.
|
|
13
|
-
*
|
|
14
|
-
* @see {@link AppearanceProvider} - Provider component
|
|
15
|
-
* @see {@link useAppearance} - Consumer hook
|
|
16
|
-
*
|
|
17
|
-
* @since 0.5.0-canary.2
|
|
18
|
-
*/
|
|
19
|
-
export const AppearanceContext: Context<null | AppearanceContextValue> = createContext<null | AppearanceContextValue>(
|
|
20
|
-
null,
|
|
21
|
-
);
|
|
@@ -1,368 +0,0 @@
|
|
|
1
|
-
import type { JSX, ReactNode } from "react";
|
|
2
|
-
import {
|
|
3
|
-
startTransition,
|
|
4
|
-
useCallback,
|
|
5
|
-
useEffect,
|
|
6
|
-
useEffectEvent,
|
|
7
|
-
useLayoutEffect,
|
|
8
|
-
useMemo,
|
|
9
|
-
useOptimistic,
|
|
10
|
-
useRef,
|
|
11
|
-
useState,
|
|
12
|
-
useSyncExternalStore,
|
|
13
|
-
} from "react";
|
|
14
|
-
|
|
15
|
-
import type { Appearance, AppearanceContextValue, ColorScheme } from "#/appearance";
|
|
16
|
-
import { appearanceSchema } from "#/appearance";
|
|
17
|
-
import { AppearanceContext } from "#/appearance-context";
|
|
18
|
-
import { getSystemColorScheme } from "#/color-scheme";
|
|
19
|
-
import { DEFAULT_APPEARANCE, DEFAULT_COLOR_SCHEME, MEDIA, STORAGE_KEY, SYNC_CHANNEL } from "#/constants";
|
|
20
|
-
import { applyColorScheme, suppressTransitions } from "#/dom";
|
|
21
|
-
|
|
22
|
-
/* -----------------------------------------------------------------------------
|
|
23
|
-
* System Color Scheme Subscription
|
|
24
|
-
*
|
|
25
|
-
* These functions power `useSyncExternalStore` for reactive OS preference detection.
|
|
26
|
-
* This pattern ensures SSR safety and efficient re-renders on OS preference changes.
|
|
27
|
-
* -------------------------------------------------------------------------- */
|
|
28
|
-
|
|
29
|
-
/**
|
|
30
|
-
* Subscribe to OS color scheme preference changes.
|
|
31
|
-
*
|
|
32
|
-
* @param callback - Function to call when the OS color scheme changes
|
|
33
|
-
* @returns Cleanup function to remove the listener
|
|
34
|
-
*/
|
|
35
|
-
function subscribeToSystemColorScheme(callback: () => void): () => void {
|
|
36
|
-
const mediaQuery = window.matchMedia(MEDIA);
|
|
37
|
-
|
|
38
|
-
mediaQuery.addEventListener("change", callback);
|
|
39
|
-
|
|
40
|
-
return () => {
|
|
41
|
-
mediaQuery.removeEventListener("change", callback);
|
|
42
|
-
};
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
/** SSR has no `matchMedia`; render the default until the first client snapshot takes over. */
|
|
46
|
-
function getServerSnapshot(): ColorScheme {
|
|
47
|
-
return DEFAULT_COLOR_SCHEME;
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
/**
|
|
51
|
-
* Safely create an appearance BroadcastChannel when supported by the environment.
|
|
52
|
-
*/
|
|
53
|
-
function createAppearanceChannel(): BroadcastChannel | null {
|
|
54
|
-
if (typeof BroadcastChannel === "undefined") {
|
|
55
|
-
return null;
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
try {
|
|
59
|
-
return new BroadcastChannel(SYNC_CHANNEL);
|
|
60
|
-
} catch {
|
|
61
|
-
return null;
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
/**
|
|
66
|
-
* Reads and validates the persisted preference from localStorage. Returns null when unavailable
|
|
67
|
-
* (SSR, private mode) or when the stored value is not a recognised appearance.
|
|
68
|
-
*/
|
|
69
|
-
function readAppearanceFromStorage(storageKey: string): Appearance | null {
|
|
70
|
-
if (typeof globalThis.window === "undefined") {
|
|
71
|
-
return null;
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
try {
|
|
75
|
-
const result = appearanceSchema.safeParse(globalThis.window.localStorage.getItem(storageKey));
|
|
76
|
-
|
|
77
|
-
return result.success ? result.data : null;
|
|
78
|
-
} catch {
|
|
79
|
-
return null;
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
// ── Props ────────────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
84
|
-
|
|
85
|
-
/**
|
|
86
|
-
* Props for {@link AppearanceProvider}.
|
|
87
|
-
*
|
|
88
|
-
* @since 0.5.0-canary.2
|
|
89
|
-
*/
|
|
90
|
-
export type AppearanceProviderProps = {
|
|
91
|
-
readonly children: ReactNode;
|
|
92
|
-
/**
|
|
93
|
-
* When true, temporarily suppresses CSS transitions during appearance changes.
|
|
94
|
-
* Prevents jarring color animations when switching appearances.
|
|
95
|
-
* Default: false
|
|
96
|
-
*/
|
|
97
|
-
readonly disableTransition?: boolean | undefined;
|
|
98
|
-
/**
|
|
99
|
-
* CSP nonce for inline styles when `disableTransition` is enabled.
|
|
100
|
-
*/
|
|
101
|
-
readonly nonce?: string | undefined;
|
|
102
|
-
/**
|
|
103
|
-
* Custom async persistence for appearance changes; replaces the `localStorage` auto-persist.
|
|
104
|
-
*/
|
|
105
|
-
readonly persistAppearance?: ((value: Appearance) => Promise<void>) | undefined;
|
|
106
|
-
/**
|
|
107
|
-
* Callback invoked when `persistAppearance` rejects.
|
|
108
|
-
*/
|
|
109
|
-
readonly onPersistError?: ((error: unknown, attemptedAppearance: Appearance) => void) | undefined;
|
|
110
|
-
/**
|
|
111
|
-
* Fallback preference when storage has no valid entry — also what SSR renders.
|
|
112
|
-
* Defaults to {@link DEFAULT_APPEARANCE}.
|
|
113
|
-
*/
|
|
114
|
-
readonly appearance?: Appearance | undefined;
|
|
115
|
-
/**
|
|
116
|
-
* `localStorage` key the preference is restored from and persisted under.
|
|
117
|
-
* Defaults to {@link STORAGE_KEY}; pair with `<AppearanceScript>` using the **same key**.
|
|
118
|
-
*
|
|
119
|
-
* The provider reads the stored value in its initial client render (so the first paint already
|
|
120
|
-
* matches the preference — no flash, no post-mount settle), auto-persists changes to
|
|
121
|
-
* `localStorage` (unless {@link persistAppearance} is also given, which then wins), and syncs
|
|
122
|
-
* across tabs via the `storage` event.
|
|
123
|
-
*
|
|
124
|
-
* @remarks SSR has no `localStorage`, so the server renders the {@link AppearanceProviderProps.appearance}
|
|
125
|
-
* prop. For a returning visitor whose stored preference differs, components that render
|
|
126
|
-
* preference-dependent markup hydrate-reconcile once; gate them behind a mounted flag to avoid that.
|
|
127
|
-
*/
|
|
128
|
-
readonly storageKey?: string | undefined;
|
|
129
|
-
};
|
|
130
|
-
|
|
131
|
-
// ── Component ────────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
132
|
-
|
|
133
|
-
/**
|
|
134
|
-
* Provider component for appearance state management.
|
|
135
|
-
*
|
|
136
|
-
* **React 19 Features Used:**
|
|
137
|
-
* - `useOptimistic` - Immediate UI feedback while persisting the preference
|
|
138
|
-
* - `useSyncExternalStore` - SSR-safe subscription to the OS color scheme preference
|
|
139
|
-
* - `useEffectEvent` - Stable callback for cross-tab sync without effect re-runs
|
|
140
|
-
*
|
|
141
|
-
* @example
|
|
142
|
-
* ```tsx
|
|
143
|
-
* // In your root layout — pair with <AppearanceScript /> using the same storage key
|
|
144
|
-
* <AppearanceProvider>{children}</AppearanceProvider>
|
|
145
|
-
* ```
|
|
146
|
-
*
|
|
147
|
-
* @since 0.5.0-canary.2
|
|
148
|
-
*/
|
|
149
|
-
export function AppearanceProvider({
|
|
150
|
-
children,
|
|
151
|
-
disableTransition = false,
|
|
152
|
-
nonce,
|
|
153
|
-
onPersistError,
|
|
154
|
-
persistAppearance,
|
|
155
|
-
storageKey = STORAGE_KEY,
|
|
156
|
-
appearance: initialAppearance = DEFAULT_APPEARANCE,
|
|
157
|
-
}: AppearanceProviderProps): JSX.Element {
|
|
158
|
-
// Runtime guard against invalid values bypassing TypeScript (e.g. raw API strings)
|
|
159
|
-
const safeInitialAppearance = appearanceSchema.safeParse(initialAppearance).success
|
|
160
|
-
? initialAppearance
|
|
161
|
-
: DEFAULT_APPEARANCE;
|
|
162
|
-
|
|
163
|
-
// Actual persisted appearance. Read localStorage in the initializer so the first client render
|
|
164
|
-
// already matches what AppearanceScript applied pre-paint (no flash, no post-mount settle). SSR has
|
|
165
|
-
// no localStorage, so the server renders the prop.
|
|
166
|
-
const [appearance, setAppearanceState] = useState<Appearance>(
|
|
167
|
-
() => readAppearanceFromStorage(storageKey) ?? safeInitialAppearance,
|
|
168
|
-
);
|
|
169
|
-
|
|
170
|
-
// Optimistic appearance - immediately reflects user's intent while async operation runs
|
|
171
|
-
// Automatically reverts to `appearance` if the transition fails
|
|
172
|
-
const [optimisticAppearance, setOptimisticAppearance] = useOptimistic(appearance);
|
|
173
|
-
|
|
174
|
-
// True when there's a pending appearance change (optimistic !== actual)
|
|
175
|
-
const isPending = optimisticAppearance !== appearance;
|
|
176
|
-
|
|
177
|
-
// Stable ref so setAppearance does not re-create every time the committed appearance changes
|
|
178
|
-
const committedAppearanceRef = useRef(appearance);
|
|
179
|
-
|
|
180
|
-
// Layout effect, not passive: a setAppearance call can land before the passive flush and
|
|
181
|
-
// must compare against the just-committed appearance, not the previous one.
|
|
182
|
-
useLayoutEffect(() => {
|
|
183
|
-
committedAppearanceRef.current = appearance;
|
|
184
|
-
}, [appearance]);
|
|
185
|
-
|
|
186
|
-
// Shared BroadcastChannel — reused by the setAppearance sender instead of opening a new one per call
|
|
187
|
-
const channelRef = useRef<BroadcastChannel | null>(null);
|
|
188
|
-
|
|
189
|
-
// suppressTransitions cleanup stored here and called after applyColorScheme commits to the DOM
|
|
190
|
-
const enableTransitionsRef = useRef<(() => void) | null>(null);
|
|
191
|
-
|
|
192
|
-
// Last-write-wins intent — prevents stale async commits from overriding newer setAppearance calls
|
|
193
|
-
const intentRef = useRef<Appearance | null>(null);
|
|
194
|
-
|
|
195
|
-
// Effective persistence: an explicit persistAppearance wins; otherwise auto-persist to localStorage.
|
|
196
|
-
const persist = useMemo<(value: Appearance) => Promise<void>>(() => {
|
|
197
|
-
if (persistAppearance) {
|
|
198
|
-
return persistAppearance;
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
return async (value: Appearance): Promise<void> => {
|
|
202
|
-
try {
|
|
203
|
-
globalThis.window.localStorage.setItem(storageKey, value);
|
|
204
|
-
} catch {
|
|
205
|
-
/* storage blocked (private mode / quota) — optimistic UI already reflects the change */
|
|
206
|
-
}
|
|
207
|
-
};
|
|
208
|
-
}, [persistAppearance, storageKey]);
|
|
209
|
-
|
|
210
|
-
// Subscribe to OS preference changes (SSR-safe via useSyncExternalStore)
|
|
211
|
-
const systemColorScheme = useSyncExternalStore(subscribeToSystemColorScheme, getSystemColorScheme, getServerSnapshot);
|
|
212
|
-
|
|
213
|
-
// Compute the color scheme to apply: resolve 'automatic' to light/dark
|
|
214
|
-
const colorScheme = useMemo<ColorScheme>(
|
|
215
|
-
() => (optimisticAppearance === "automatic" ? systemColorScheme : optimisticAppearance),
|
|
216
|
-
[optimisticAppearance, systemColorScheme],
|
|
217
|
-
);
|
|
218
|
-
|
|
219
|
-
// Apply the color scheme to the DOM then call the transition cleanup — ensures enable() fires
|
|
220
|
-
// after applyColorScheme has committed, not prematurely in the async persist finally block
|
|
221
|
-
useEffect(() => {
|
|
222
|
-
applyColorScheme(colorScheme);
|
|
223
|
-
|
|
224
|
-
const enable = enableTransitionsRef.current;
|
|
225
|
-
|
|
226
|
-
if (enable) {
|
|
227
|
-
enableTransitionsRef.current = null;
|
|
228
|
-
enable();
|
|
229
|
-
}
|
|
230
|
-
}, [colorScheme]);
|
|
231
|
-
|
|
232
|
-
// Mirror the *preference* (not the resolved value) to `data-appearance` so preference-aware UI
|
|
233
|
-
// (e.g. a 3-state toggle) renders from CSS — matching what AppearanceScript set pre-paint. Tracks the
|
|
234
|
-
// optimistic value so the attribute flips immediately on change and stays in sync across tabs.
|
|
235
|
-
useEffect(() => {
|
|
236
|
-
globalThis.window.document.documentElement.dataset.appearance = optimisticAppearance;
|
|
237
|
-
}, [optimisticAppearance]);
|
|
238
|
-
|
|
239
|
-
// Validate cross-tab messages before applying to prevent injection from extensions/scripts
|
|
240
|
-
const handleCrossTabMessage = useEffectEvent((event: MessageEvent) => {
|
|
241
|
-
const result = appearanceSchema.safeParse(event.data);
|
|
242
|
-
|
|
243
|
-
if (!result.success || result.data === appearance) {
|
|
244
|
-
return;
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
startTransition(() => {
|
|
248
|
-
setAppearanceState(result.data);
|
|
249
|
-
});
|
|
250
|
-
});
|
|
251
|
-
|
|
252
|
-
// Cross-tab sync fallback: the `storage` event fires in OTHER tabs when this key changes.
|
|
253
|
-
const handleStorageEvent = useEffectEvent((event: StorageEvent) => {
|
|
254
|
-
if (event.key !== storageKey) {
|
|
255
|
-
return;
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
const result = appearanceSchema.safeParse(event.newValue);
|
|
259
|
-
|
|
260
|
-
if (!result.success || result.data === appearance) {
|
|
261
|
-
return;
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
startTransition(() => {
|
|
265
|
-
setAppearanceState(result.data);
|
|
266
|
-
});
|
|
267
|
-
});
|
|
268
|
-
|
|
269
|
-
// Keep the channel in a ref so setAppearance can broadcast without opening a new channel each time
|
|
270
|
-
useEffect(() => {
|
|
271
|
-
const channel = createAppearanceChannel();
|
|
272
|
-
|
|
273
|
-
if (!channel) {
|
|
274
|
-
return;
|
|
275
|
-
}
|
|
276
|
-
|
|
277
|
-
channelRef.current = channel;
|
|
278
|
-
channel.addEventListener("message", handleCrossTabMessage);
|
|
279
|
-
|
|
280
|
-
return (): void => {
|
|
281
|
-
channelRef.current = null;
|
|
282
|
-
channel.removeEventListener("message", handleCrossTabMessage);
|
|
283
|
-
channel.close();
|
|
284
|
-
};
|
|
285
|
-
}, []);
|
|
286
|
-
|
|
287
|
-
useEffect(() => {
|
|
288
|
-
globalThis.window.addEventListener("storage", handleStorageEvent);
|
|
289
|
-
|
|
290
|
-
return (): void => {
|
|
291
|
-
globalThis.window.removeEventListener("storage", handleStorageEvent);
|
|
292
|
-
};
|
|
293
|
-
}, []);
|
|
294
|
-
|
|
295
|
-
const setAppearance = useCallback(
|
|
296
|
-
async (value: Appearance): Promise<void> => {
|
|
297
|
-
await Promise.resolve();
|
|
298
|
-
|
|
299
|
-
// Read from ref so this callback stays stable across appearance commits
|
|
300
|
-
if (value === committedAppearanceRef.current) {
|
|
301
|
-
return;
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
// Store the cleanup; it will be called after applyColorScheme runs in the colorScheme effect.
|
|
305
|
-
// Flush any pending suppression first so an overlapping call cannot orphan its injected <style>.
|
|
306
|
-
if (disableTransition) {
|
|
307
|
-
enableTransitionsRef.current?.();
|
|
308
|
-
enableTransitionsRef.current = suppressTransitions(nonce);
|
|
309
|
-
}
|
|
310
|
-
|
|
311
|
-
startTransition(async () => {
|
|
312
|
-
// Track intent; only the latest setAppearance call commits its value
|
|
313
|
-
intentRef.current = value;
|
|
314
|
-
|
|
315
|
-
// Show the new appearance immediately (optimistic update)
|
|
316
|
-
setOptimisticAppearance(value);
|
|
317
|
-
|
|
318
|
-
try {
|
|
319
|
-
// Persist to storage
|
|
320
|
-
await persist(value);
|
|
321
|
-
|
|
322
|
-
// Only commit if no newer setAppearance call has since taken over
|
|
323
|
-
if (intentRef.current === value) {
|
|
324
|
-
setAppearanceState(value);
|
|
325
|
-
|
|
326
|
-
// Notify other tabs via the shared channel
|
|
327
|
-
channelRef.current?.postMessage(value);
|
|
328
|
-
}
|
|
329
|
-
} catch (error) {
|
|
330
|
-
// On failure, useOptimistic automatically reverts to `appearance`
|
|
331
|
-
if (onPersistError) {
|
|
332
|
-
try {
|
|
333
|
-
onPersistError(error, value);
|
|
334
|
-
} catch (callbackError) {
|
|
335
|
-
console.error("Failed to handle appearance persist error:", callbackError);
|
|
336
|
-
}
|
|
337
|
-
} else {
|
|
338
|
-
console.error("Failed to set appearance:", error);
|
|
339
|
-
}
|
|
340
|
-
} finally {
|
|
341
|
-
// Safety net: fires when the color scheme did not change (e.g. automatic→dark while
|
|
342
|
-
// the OS is already dark) so the applyColorScheme effect never runs. No-op if the effect
|
|
343
|
-
// already called enable().
|
|
344
|
-
const enable = enableTransitionsRef.current;
|
|
345
|
-
|
|
346
|
-
if (enable) {
|
|
347
|
-
enableTransitionsRef.current = null;
|
|
348
|
-
enable();
|
|
349
|
-
}
|
|
350
|
-
}
|
|
351
|
-
});
|
|
352
|
-
},
|
|
353
|
-
[disableTransition, nonce, setOptimisticAppearance, persist, onPersistError],
|
|
354
|
-
);
|
|
355
|
-
|
|
356
|
-
// Expose the optimistic appearance so consumers see immediate updates
|
|
357
|
-
const value = useMemo<AppearanceContextValue>(
|
|
358
|
-
() => ({
|
|
359
|
-
isPending,
|
|
360
|
-
colorScheme,
|
|
361
|
-
setAppearance,
|
|
362
|
-
appearance: optimisticAppearance,
|
|
363
|
-
}),
|
|
364
|
-
[optimisticAppearance, colorScheme, setAppearance, isPending],
|
|
365
|
-
);
|
|
366
|
-
|
|
367
|
-
return <AppearanceContext value={value}>{children}</AppearanceContext>;
|
|
368
|
-
}
|
|
@@ -1,87 +0,0 @@
|
|
|
1
|
-
import type { JSX } from "react";
|
|
2
|
-
|
|
3
|
-
import { appearances, appearanceSchema } from "#/appearance";
|
|
4
|
-
import type { Appearance } from "#/appearance";
|
|
5
|
-
import { DEFAULT_APPEARANCE, MEDIA, STORAGE_KEY } from "#/constants";
|
|
6
|
-
|
|
7
|
-
/* JSON.stringify does not escape </script>, so we replace the three characters that
|
|
8
|
-
* can form a closing tag: < > /. Unicode escapes are valid JS and safe in HTML. */
|
|
9
|
-
function toScriptSafe(value: unknown): string {
|
|
10
|
-
return JSON.stringify(value).replaceAll("<", "\\u003C").replaceAll(">", "\\u003E").replaceAll("/", "\\u002F");
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
/* Derived once from schema + constants — the inline script uses these to stay in sync */
|
|
14
|
-
const APPEARANCE_REMOVE_ARGS = appearances.map((s) => toScriptSafe(s)).join(",");
|
|
15
|
-
const APPEARANCE_VALID_CHECK = appearances.map((s) => `s===${toScriptSafe(s)}`).join("||");
|
|
16
|
-
|
|
17
|
-
// ── Props ────────────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
18
|
-
|
|
19
|
-
/**
|
|
20
|
-
* Props for {@link AppearanceScript}.
|
|
21
|
-
*
|
|
22
|
-
* @since 0.5.0-canary.2
|
|
23
|
-
*/
|
|
24
|
-
export type AppearanceScriptProps = {
|
|
25
|
-
/**
|
|
26
|
-
* Fallback preference when the storage entry is absent or unrecognised.
|
|
27
|
-
* Defaults to {@link DEFAULT_APPEARANCE}.
|
|
28
|
-
*/
|
|
29
|
-
readonly appearance?: Appearance | undefined;
|
|
30
|
-
/**
|
|
31
|
-
* CSP nonce applied to the inline script element.
|
|
32
|
-
*/
|
|
33
|
-
readonly nonce?: string | undefined;
|
|
34
|
-
/**
|
|
35
|
-
* `localStorage` key the script reads before first paint — a recognised value (`"light"`,
|
|
36
|
-
* `"dark"`, or `"automatic"`) wins over `appearance`.
|
|
37
|
-
* Defaults to {@link STORAGE_KEY}; pair with `<AppearanceProvider>` using the **same key**.
|
|
38
|
-
*/
|
|
39
|
-
readonly storageKey?: string | undefined;
|
|
40
|
-
};
|
|
41
|
-
|
|
42
|
-
// ── Component ────────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
43
|
-
|
|
44
|
-
/**
|
|
45
|
-
* Inline script that prevents Flash of Unstyled Content (FOUC).
|
|
46
|
-
*
|
|
47
|
-
* **Why this is needed:**
|
|
48
|
-
* React hydration occurs after the browser has already painted the page.
|
|
49
|
-
* Without this script, users would briefly see the wrong appearance before
|
|
50
|
-
* React takes over and applies the correct one.
|
|
51
|
-
*
|
|
52
|
-
* **How it works:**
|
|
53
|
-
* This script runs synchronously in the `<head>` before first paint:
|
|
54
|
-
* 1. Reads the stored preference from `localStorage`, falling back to `appearance`
|
|
55
|
-
* 2. Resolves 'automatic' to 'light' or 'dark' using `matchMedia()`
|
|
56
|
-
* 3. Removes prior `light` / `dark` / `automatic` classes on `<html>` (SSR may
|
|
57
|
-
* have applied the wrong resolved class for `automatic`, e.g. default `dark`)
|
|
58
|
-
* 4. Adds the resolved color scheme class and sets `color-scheme` for native controls
|
|
59
|
-
* 5. Writes the *preference* to `data-appearance` so preference-aware UI (e.g. a 3-state toggle)
|
|
60
|
-
* can render the right state from CSS on first paint, without a hydration flash
|
|
61
|
-
*
|
|
62
|
-
* @example
|
|
63
|
-
* ```tsx
|
|
64
|
-
* // In __root.tsx (TanStack Start)
|
|
65
|
-
* <head>
|
|
66
|
-
* <AppearanceScript />
|
|
67
|
-
* </head>
|
|
68
|
-
* ```
|
|
69
|
-
*
|
|
70
|
-
* @since 0.5.0-canary.2
|
|
71
|
-
*/
|
|
72
|
-
export function AppearanceScript({
|
|
73
|
-
nonce,
|
|
74
|
-
storageKey = STORAGE_KEY,
|
|
75
|
-
appearance = DEFAULT_APPEARANCE,
|
|
76
|
-
}: AppearanceScriptProps): JSX.Element {
|
|
77
|
-
// Guard against invalid values bypassing TypeScript so the fallback matches AppearanceProvider.
|
|
78
|
-
const safeAppearance = appearanceSchema.safeParse(appearance).success ? appearance : DEFAULT_APPEARANCE;
|
|
79
|
-
|
|
80
|
-
// toScriptSafe = JSON.stringify + escape <>/ so </script> cannot break out of the tag.
|
|
81
|
-
// The script reads localStorage before first paint so the stored preference applies
|
|
82
|
-
// without FOUC; an absent or invalid entry falls back to fb.
|
|
83
|
-
const appearanceScript = `(function(){try{var sk=${toScriptSafe(storageKey)},fb=${toScriptSafe(safeAppearance)},s=localStorage.getItem(sk),appearance=(${APPEARANCE_VALID_CHECK})?s:fb,colorScheme=appearance;"automatic"===appearance&&(colorScheme=window.matchMedia(${toScriptSafe(MEDIA)}).matches?"dark":"light"),document.documentElement.classList.remove(${APPEARANCE_REMOVE_ARGS}),document.documentElement.classList.add(colorScheme),document.documentElement.style.colorScheme=colorScheme,document.documentElement.dataset.appearance=appearance}catch(e){}})()`;
|
|
84
|
-
const nonceProps = nonce === undefined ? {} : { nonce };
|
|
85
|
-
|
|
86
|
-
return <script dangerouslySetInnerHTML={{ __html: appearanceScript }} suppressHydrationWarning {...nonceProps} />;
|
|
87
|
-
}
|
package/src/appearance.ts
DELETED
|
@@ -1,70 +0,0 @@
|
|
|
1
|
-
import { z } from "zod";
|
|
2
|
-
|
|
3
|
-
/* -----------------------------------------------------------------------------
|
|
4
|
-
* Schema & Types
|
|
5
|
-
*
|
|
6
|
-
* Vocabulary follows Apple's Human Interface Guidelines: "appearance" is the
|
|
7
|
-
* user's preference (Light / Dark / Auto), "color scheme" is the resolved
|
|
8
|
-
* light-or-dark value actually applied (matching CSS `color-scheme` and
|
|
9
|
-
* `prefers-color-scheme`).
|
|
10
|
-
* -------------------------------------------------------------------------- */
|
|
11
|
-
|
|
12
|
-
/**
|
|
13
|
-
* Zod schema for appearance validation.
|
|
14
|
-
*
|
|
15
|
-
* Acts as the single source of truth for all appearance-related types.
|
|
16
|
-
* Valid values: 'light', 'dark', 'automatic'.
|
|
17
|
-
*
|
|
18
|
-
* @since 0.5.0-canary.2
|
|
19
|
-
*/
|
|
20
|
-
export const appearanceSchema: z.ZodEnum<{ light: "light"; dark: "dark"; automatic: "automatic" }> = z.enum([
|
|
21
|
-
"light",
|
|
22
|
-
"dark",
|
|
23
|
-
"automatic",
|
|
24
|
-
]);
|
|
25
|
-
|
|
26
|
-
/**
|
|
27
|
-
* User's appearance preference.
|
|
28
|
-
*
|
|
29
|
-
* - `'light'` - Force light appearance
|
|
30
|
-
* - `'dark'` - Force dark appearance
|
|
31
|
-
* - `'automatic'` - Follow OS preference
|
|
32
|
-
*
|
|
33
|
-
* @since 0.5.0-canary.2
|
|
34
|
-
*/
|
|
35
|
-
export type Appearance = z.infer<typeof appearanceSchema>;
|
|
36
|
-
|
|
37
|
-
/**
|
|
38
|
-
* Color scheme actually applied to the UI after resolving 'automatic'.
|
|
39
|
-
*
|
|
40
|
-
* When the appearance is 'automatic', this reflects the OS preference (light/dark).
|
|
41
|
-
*
|
|
42
|
-
* @since 0.5.0-canary.2
|
|
43
|
-
*/
|
|
44
|
-
export type ColorScheme = Exclude<Appearance, "automatic">;
|
|
45
|
-
|
|
46
|
-
/**
|
|
47
|
-
* Array of all available appearance options: `['light', 'dark', 'automatic']`.
|
|
48
|
-
*
|
|
49
|
-
* Useful for rendering appearance selectors in UI components.
|
|
50
|
-
*
|
|
51
|
-
* @since 0.5.0-canary.2
|
|
52
|
-
*/
|
|
53
|
-
export const appearances: ReadonlyArray<Appearance> = appearanceSchema.options;
|
|
54
|
-
|
|
55
|
-
/**
|
|
56
|
-
* Shape of the context value provided by AppearanceProvider.
|
|
57
|
-
*
|
|
58
|
-
* - `appearance` - Current appearance preference
|
|
59
|
-
* - `colorScheme` - Color scheme actually applied (automatic resolved to light/dark)
|
|
60
|
-
* - `setAppearance` - Async function to update the preference (triggers optimistic update)
|
|
61
|
-
* - `isPending` - True while an appearance change is being persisted
|
|
62
|
-
*
|
|
63
|
-
* @since 0.5.0-canary.2
|
|
64
|
-
*/
|
|
65
|
-
export type AppearanceContextValue = {
|
|
66
|
-
readonly isPending: boolean;
|
|
67
|
-
readonly colorScheme: ColorScheme;
|
|
68
|
-
readonly setAppearance: (value: Appearance) => Promise<void>;
|
|
69
|
-
readonly appearance: Appearance;
|
|
70
|
-
};
|
package/src/color-scheme.ts
DELETED
|
@@ -1,40 +0,0 @@
|
|
|
1
|
-
import type { Appearance, ColorScheme } from "#/appearance";
|
|
2
|
-
import { DEFAULT_COLOR_SCHEME, MEDIA } from "#/constants";
|
|
3
|
-
|
|
4
|
-
// ── Color Scheme Resolution ──────────────────────────────────────────────────────────────────────────────────────────
|
|
5
|
-
|
|
6
|
-
/**
|
|
7
|
-
* Detects the OS color scheme preference.
|
|
8
|
-
*
|
|
9
|
-
* Uses `matchMedia()` to query the `prefers-color-scheme` media feature.
|
|
10
|
-
* Returns {@link DEFAULT_COLOR_SCHEME} during SSR since `window` is unavailable.
|
|
11
|
-
*
|
|
12
|
-
* @returns 'light' or 'dark' based on OS preference
|
|
13
|
-
*
|
|
14
|
-
* @since 0.3.16-canary.0
|
|
15
|
-
*/
|
|
16
|
-
export function getSystemColorScheme(): ColorScheme {
|
|
17
|
-
if (typeof globalThis.window === "undefined") {
|
|
18
|
-
return DEFAULT_COLOR_SCHEME;
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
return globalThis.window.matchMedia(MEDIA).matches ? "dark" : "light";
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
/**
|
|
25
|
-
* Resolves an appearance preference to the color scheme to apply.
|
|
26
|
-
*
|
|
27
|
-
* - 'light' → 'light'
|
|
28
|
-
* - 'dark' → 'dark'
|
|
29
|
-
* - 'automatic' → on the client, result of {@link getSystemColorScheme};
|
|
30
|
-
* on the server, {@link DEFAULT_COLOR_SCHEME}
|
|
31
|
-
*
|
|
32
|
-
* @since 0.3.16-canary.0
|
|
33
|
-
*/
|
|
34
|
-
export function resolveColorScheme(appearance: Appearance): ColorScheme {
|
|
35
|
-
if (appearance !== "automatic") {
|
|
36
|
-
return appearance;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
return getSystemColorScheme();
|
|
40
|
-
}
|
package/src/constants.ts
DELETED
|
@@ -1,49 +0,0 @@
|
|
|
1
|
-
import type { Appearance, ColorScheme } from "#/appearance";
|
|
2
|
-
|
|
3
|
-
// ── Public Constants ─────────────────────────────────────────────────────────────────────────────────────────────────
|
|
4
|
-
|
|
5
|
-
/**
|
|
6
|
-
* Default appearance preference when no stored value exists.
|
|
7
|
-
*
|
|
8
|
-
* Set to 'automatic' to respect OS preference by default.
|
|
9
|
-
*
|
|
10
|
-
* @since 0.5.0-canary.2
|
|
11
|
-
*/
|
|
12
|
-
export const DEFAULT_APPEARANCE: Appearance = "automatic";
|
|
13
|
-
|
|
14
|
-
/**
|
|
15
|
-
* Fallback color scheme when the system color scheme cannot be detected.
|
|
16
|
-
*
|
|
17
|
-
* Applies wherever `window.matchMedia()` is unavailable, e.g. during server render.
|
|
18
|
-
*
|
|
19
|
-
* @since 0.5.0-canary.2
|
|
20
|
-
*/
|
|
21
|
-
export const DEFAULT_COLOR_SCHEME: ColorScheme = "dark";
|
|
22
|
-
|
|
23
|
-
/**
|
|
24
|
-
* Default `localStorage` key for the appearance preference, shared by
|
|
25
|
-
* `AppearanceScript` and `AppearanceProvider`.
|
|
26
|
-
*
|
|
27
|
-
* Re-exported only from `@codefast/theme/constants` so custom integrations can match it exactly.
|
|
28
|
-
*
|
|
29
|
-
* @since 0.3.16-canary.0
|
|
30
|
-
*/
|
|
31
|
-
export const STORAGE_KEY = "ui-appearance";
|
|
32
|
-
|
|
33
|
-
// ── Internal Constants ───────────────────────────────────────────────────────────────────────────────────────────────
|
|
34
|
-
|
|
35
|
-
/**
|
|
36
|
-
* CSS media query for detecting dark mode preference.
|
|
37
|
-
* @internal
|
|
38
|
-
*
|
|
39
|
-
* @since 0.3.16-canary.0
|
|
40
|
-
*/
|
|
41
|
-
export const MEDIA = "(prefers-color-scheme: dark)";
|
|
42
|
-
|
|
43
|
-
/**
|
|
44
|
-
* BroadcastChannel name for cross-tab appearance synchronization.
|
|
45
|
-
* @internal
|
|
46
|
-
*
|
|
47
|
-
* @since 0.3.16-canary.0
|
|
48
|
-
*/
|
|
49
|
-
export const SYNC_CHANNEL = "appearance-sync";
|