@behavioral-agentic-design-system/core 0.2.1 → 0.3.1

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 (49) hide show
  1. package/package.json +37 -4
  2. package/scripts/bads-sync.mjs +81 -0
  3. package/scripts/build-tokens.cjs +487 -0
  4. package/src/api/bads-update-check.ts +151 -0
  5. package/src/api/brand-colors.ts +180 -0
  6. package/src/api/layers/file.ts +71 -0
  7. package/src/api/layers.ts +49 -0
  8. package/src/api/save-tokens.ts +280 -0
  9. package/src/app/font-ready.tsx +51 -0
  10. package/src/app/layout.tsx +152 -0
  11. package/src/app/page.tsx +267 -0
  12. package/src/app/preview/cards/page.tsx +8 -0
  13. package/src/app/preview/components/page.tsx +232 -0
  14. package/src/app/preview/dark-mode-client.tsx +24 -0
  15. package/src/app/preview/dashboard/page.tsx +4 -0
  16. package/src/app/preview/global-font-client.tsx +36 -0
  17. package/src/app/preview/layout.tsx +13 -0
  18. package/src/app/preview/mail/page.tsx +4 -0
  19. package/src/app/preview/pricing/page.tsx +4 -0
  20. package/src/app/preview/typography/page.tsx +11 -0
  21. package/src/app/providers.tsx +49 -0
  22. package/src/components/Foundations/Colors.stories.tsx +85 -0
  23. package/src/components/Foundations/Motion.stories.tsx +169 -0
  24. package/src/components/Foundations/Radius.stories.tsx +36 -0
  25. package/src/components/Foundations/Shadows.stories.tsx +30 -0
  26. package/src/components/Foundations/Spacing.stories.tsx +35 -0
  27. package/src/components/Foundations/Typography.stories.tsx +68 -0
  28. package/src/components/bads-update-banner.tsx +120 -0
  29. package/src/components/customize/design-controls.tsx +165 -0
  30. package/src/components/customize/font-pickers.tsx +118 -0
  31. package/src/components/customize/letter-spacing.tsx +105 -0
  32. package/src/components/customize/save-bar.tsx +379 -0
  33. package/src/components/customize/theme-io.tsx +245 -0
  34. package/src/components/customize/type-scale.tsx +134 -0
  35. package/src/components/customize-tab.tsx +502 -0
  36. package/src/components/home-tab.tsx +1227 -0
  37. package/src/components/layers-tab.tsx +225 -0
  38. package/src/components/ui/alert.tsx +5 -1
  39. package/src/hooks/use-global-design-controls.ts +117 -0
  40. package/src/hooks/use-global-mono-font.ts +73 -0
  41. package/src/hooks/use-global-primary-color.ts +544 -0
  42. package/src/hooks/use-global-sans-font.ts +98 -0
  43. package/src/hooks/use-global-serif-font.ts +77 -0
  44. package/src/hooks/use-global-theme.ts +259 -0
  45. package/src/hooks/use-global-type-scale.ts +141 -0
  46. package/src/hooks/use-sync-type-scale.ts +51 -0
  47. package/src/hooks/use-token-overrides.ts +98 -0
  48. package/src/styles.css +40 -6
  49. package/src/tokens.json +86 -5
@@ -0,0 +1,77 @@
1
+ "use client";
2
+
3
+ import { useCallback, useEffect, useState } from "react";
4
+
5
+ export const SERIF_FONT_OPTIONS = {
6
+ georgia: {
7
+ label: "Georgia",
8
+ stack: "Georgia, ui-serif, serif",
9
+ },
10
+ lora: {
11
+ label: "Lora",
12
+ stack: "var(--font-lora), 'Lora', Georgia, ui-serif, serif",
13
+ },
14
+ "source-serif": {
15
+ label: "Source Serif",
16
+ stack: "var(--font-source-serif), 'Source Serif 4', Georgia, ui-serif, serif",
17
+ },
18
+ system: {
19
+ label: "System Serif",
20
+ stack: "ui-serif, Georgia, Cambria, 'Times New Roman', Times, serif",
21
+ },
22
+ } as const;
23
+
24
+ export type SerifFontKey = keyof typeof SERIF_FONT_OPTIONS;
25
+
26
+ const STORAGE_KEY = "BADS.serifFont";
27
+ const DEFAULT: SerifFontKey = "georgia";
28
+
29
+ function isValidKey(value: string | null): value is SerifFontKey {
30
+ return !!value && value in SERIF_FONT_OPTIONS;
31
+ }
32
+
33
+ function applyFont(key: SerifFontKey) {
34
+ if (typeof document === "undefined") return;
35
+ document.documentElement.style.setProperty(
36
+ "--font-serif",
37
+ SERIF_FONT_OPTIONS[key].stack,
38
+ );
39
+ }
40
+
41
+ /**
42
+ * Cross-iframe serif font selector. Mirrors useGlobalSansFont — same
43
+ * localStorage + storage-event sync pattern.
44
+ */
45
+ export function useGlobalSerifFont() {
46
+ const [font, setFontState] = useState<SerifFontKey>(DEFAULT);
47
+
48
+ useEffect(() => {
49
+ if (typeof window === "undefined") return;
50
+ const stored = window.localStorage.getItem(STORAGE_KEY);
51
+ const next = isValidKey(stored) ? stored : DEFAULT;
52
+ setFontState(next);
53
+ applyFont(next);
54
+ }, []);
55
+
56
+ useEffect(() => {
57
+ if (typeof window === "undefined") return;
58
+ const onStorage = (e: StorageEvent) => {
59
+ if (e.key !== STORAGE_KEY) return;
60
+ const next = isValidKey(e.newValue) ? e.newValue : DEFAULT;
61
+ setFontState(next);
62
+ applyFont(next);
63
+ };
64
+ window.addEventListener("storage", onStorage);
65
+ return () => window.removeEventListener("storage", onStorage);
66
+ }, []);
67
+
68
+ const setFont = useCallback((next: SerifFontKey) => {
69
+ setFontState(next);
70
+ applyFont(next);
71
+ if (typeof window !== "undefined") {
72
+ window.localStorage.setItem(STORAGE_KEY, next);
73
+ }
74
+ }, []);
75
+
76
+ return { font, setFont };
77
+ }
@@ -0,0 +1,259 @@
1
+ "use client";
2
+
3
+ import { useCallback, useEffect, useState } from "react";
4
+
5
+ /**
6
+ * The full set of shadcn / tweakcn theme variables. Used for both export
7
+ * (snapshotting documentElement) and import (applying parsed values).
8
+ */
9
+ export const THEME_VARS = [
10
+ "background",
11
+ "foreground",
12
+ "card",
13
+ "card-foreground",
14
+ "popover",
15
+ "popover-foreground",
16
+ "primary",
17
+ "primary-foreground",
18
+ "secondary",
19
+ "secondary-foreground",
20
+ "muted",
21
+ "muted-foreground",
22
+ "accent",
23
+ "accent-foreground",
24
+ "destructive",
25
+ "destructive-foreground",
26
+ "border",
27
+ "input",
28
+ "ring",
29
+ "chart-1",
30
+ "chart-2",
31
+ "chart-3",
32
+ "chart-4",
33
+ "chart-5",
34
+ "sidebar",
35
+ "sidebar-foreground",
36
+ "sidebar-primary",
37
+ "sidebar-primary-foreground",
38
+ "sidebar-accent",
39
+ "sidebar-accent-foreground",
40
+ "sidebar-border",
41
+ "sidebar-ring",
42
+ "radius",
43
+ "font-sans",
44
+ "font-serif",
45
+ "font-mono",
46
+ ] as const;
47
+
48
+ export type ThemeVars = Record<string, string>;
49
+ export type ThemePayload = {
50
+ light: ThemeVars;
51
+ dark: ThemeVars;
52
+ };
53
+
54
+ const STORAGE_KEY = "BADS.theme";
55
+
56
+ function isDarkMode(): boolean {
57
+ if (typeof document === "undefined") return false;
58
+ return document.documentElement.classList.contains("dark");
59
+ }
60
+
61
+ /**
62
+ * Parse a tweakcn-style CSS string. Pulls variables out of `:root { ... }`
63
+ * (light mode) and `.dark { ... }` (dark mode) blocks. Anything else is
64
+ * ignored. Robust to extra whitespace, comments, and trailing semicolons.
65
+ */
66
+ export function parseThemeCss(css: string): ThemePayload {
67
+ const stripped = css.replace(/\/\*[\s\S]*?\*\//g, "");
68
+
69
+ const block = (selector: string): ThemeVars => {
70
+ const re = new RegExp(`${selector}\\s*\\{([\\s\\S]*?)\\}`, "i");
71
+ const match = stripped.match(re);
72
+ if (!match) return {};
73
+ const out: ThemeVars = {};
74
+ match[1].split(";").forEach((line) => {
75
+ const trimmed = line.trim();
76
+ if (!trimmed.startsWith("--")) return;
77
+ const idx = trimmed.indexOf(":");
78
+ if (idx === -1) return;
79
+ const name = trimmed.slice(2, idx).trim();
80
+ const value = trimmed.slice(idx + 1).trim();
81
+ if (name && value) out[name] = value;
82
+ });
83
+ return out;
84
+ };
85
+
86
+ return {
87
+ light: block(":root"),
88
+ dark: block("\\.dark"),
89
+ };
90
+ }
91
+
92
+ /**
93
+ * Apply a parsed theme payload to documentElement. Picks the light or dark
94
+ * variable set based on the current `dark` class on documentElement.
95
+ */
96
+ function applyTheme(payload: ThemePayload | null) {
97
+ if (!payload || typeof document === "undefined") return;
98
+ const vars = isDarkMode() ? payload.dark : payload.light;
99
+ const root = document.documentElement.style;
100
+ Object.entries(vars).forEach(([name, value]) => {
101
+ root.setProperty(`--${name}`, value);
102
+ });
103
+ }
104
+
105
+ /**
106
+ * Snapshot the theme as a tweakcn-compatible CSS string with `:root` and
107
+ * `.dark` blocks.
108
+ *
109
+ * Reads source values directly from the matched stylesheet rules (preserves
110
+ * `oklch()` instead of getComputedStyle's `lab()` conversion), then layers
111
+ * runtime inline overrides on top of whichever mode is currently active.
112
+ *
113
+ * Limitation: inline overrides for the *inactive* mode aren't captured —
114
+ * they'd require toggling .dark and waiting for hooks to re-apply
115
+ * asynchronously. The inactive mode falls back to stylesheet source values.
116
+ */
117
+ export function exportThemeCss(): string {
118
+ if (typeof document === "undefined") return "";
119
+
120
+ const lightVars: ThemeVars = {};
121
+ const darkVars: ThemeVars = {};
122
+
123
+ // Read the actual source declarations from every matched stylesheet rule.
124
+ // CSSStyleRule.style.getPropertyValue returns the value as authored (oklch
125
+ // stays oklch), unlike getComputedStyle which resolves to lab/rgb.
126
+ for (const sheet of Array.from(document.styleSheets)) {
127
+ let rules: CSSRuleList | null = null;
128
+ try {
129
+ rules = sheet.cssRules;
130
+ } catch {
131
+ continue; // cross-origin sheet, skip
132
+ }
133
+ if (!rules) continue;
134
+ for (const rule of Array.from(rules)) {
135
+ if (!(rule instanceof CSSStyleRule)) continue;
136
+ const selector = rule.selectorText;
137
+ const target =
138
+ selector === ":root"
139
+ ? lightVars
140
+ : selector === ".dark"
141
+ ? darkVars
142
+ : null;
143
+ if (!target) continue;
144
+ THEME_VARS.forEach((name) => {
145
+ const value = rule.style.getPropertyValue(`--${name}`).trim();
146
+ if (value) target[name] = value;
147
+ });
148
+ }
149
+ }
150
+
151
+ // Layer current inline overrides (from picker hooks) onto the active mode.
152
+ const root = document.documentElement;
153
+ const activeTarget = isDarkMode() ? darkVars : lightVars;
154
+ THEME_VARS.forEach((name) => {
155
+ const inline = root.style.getPropertyValue(`--${name}`).trim();
156
+ if (inline) activeTarget[name] = inline;
157
+ });
158
+
159
+ const formatBlock = (selector: string, vars: ThemeVars) => {
160
+ const lines = Object.entries(vars)
161
+ .map(([name, value]) => ` --${name}: ${value};`)
162
+ .join("\n");
163
+ return `${selector} {\n${lines}\n}`;
164
+ };
165
+
166
+ return `${formatBlock(":root", lightVars)}\n\n${formatBlock(".dark", darkVars)}\n`;
167
+ }
168
+
169
+ function readStored(): ThemePayload | null {
170
+ if (typeof window === "undefined") return null;
171
+ const raw = window.localStorage.getItem(STORAGE_KEY);
172
+ if (!raw) return null;
173
+ try {
174
+ const parsed = JSON.parse(raw);
175
+ if (parsed && typeof parsed === "object" && "light" in parsed && "dark" in parsed) {
176
+ return parsed as ThemePayload;
177
+ }
178
+ } catch {
179
+ // ignore
180
+ }
181
+ return null;
182
+ }
183
+
184
+ /**
185
+ * Cross-iframe theme sync. Persists imported themes in localStorage and
186
+ * re-applies on dark/light toggle and on storage events from sibling iframes.
187
+ */
188
+ export function useGlobalTheme() {
189
+ const [hasTheme, setHasTheme] = useState(false);
190
+
191
+ // Initial read + apply
192
+ useEffect(() => {
193
+ if (typeof window === "undefined") return;
194
+ const stored = readStored();
195
+ if (stored) {
196
+ applyTheme(stored);
197
+ setHasTheme(true);
198
+ }
199
+ }, []);
200
+
201
+ // Cross-iframe sync
202
+ useEffect(() => {
203
+ if (typeof window === "undefined") return;
204
+ const onStorage = (e: StorageEvent) => {
205
+ if (e.key !== STORAGE_KEY) return;
206
+ const stored = readStored();
207
+ applyTheme(stored);
208
+ setHasTheme(!!stored);
209
+ };
210
+ window.addEventListener("storage", onStorage);
211
+ return () => window.removeEventListener("storage", onStorage);
212
+ }, []);
213
+
214
+ // Re-apply on dark mode toggle so the right block (light/dark) gets used.
215
+ useEffect(() => {
216
+ if (typeof document === "undefined") return;
217
+ const observer = new MutationObserver(() => {
218
+ const stored = readStored();
219
+ if (stored) applyTheme(stored);
220
+ });
221
+ observer.observe(document.documentElement, {
222
+ attributes: true,
223
+ attributeFilter: ["class"],
224
+ });
225
+ return () => observer.disconnect();
226
+ }, []);
227
+
228
+ const importTheme = useCallback((css: string) => {
229
+ const parsed = parseThemeCss(css);
230
+ if (
231
+ Object.keys(parsed.light).length === 0 &&
232
+ Object.keys(parsed.dark).length === 0
233
+ ) {
234
+ throw new Error(
235
+ "No CSS variables found. Paste a theme with :root and/or .dark blocks containing --var declarations.",
236
+ );
237
+ }
238
+ if (typeof window !== "undefined") {
239
+ window.localStorage.setItem(STORAGE_KEY, JSON.stringify(parsed));
240
+ }
241
+ applyTheme(parsed);
242
+ setHasTheme(true);
243
+ }, []);
244
+
245
+ const clearTheme = useCallback(() => {
246
+ if (typeof window !== "undefined") {
247
+ window.localStorage.removeItem(STORAGE_KEY);
248
+ }
249
+ // Best-effort revert: remove the variables we set inline so the stylesheet
250
+ // values take over again.
251
+ if (typeof document !== "undefined") {
252
+ const root = document.documentElement.style;
253
+ THEME_VARS.forEach((name) => root.removeProperty(`--${name}`));
254
+ }
255
+ setHasTheme(false);
256
+ }, []);
257
+
258
+ return { hasTheme, importTheme, clearTheme };
259
+ }
@@ -0,0 +1,141 @@
1
+ "use client";
2
+
3
+ import { useCallback, useEffect, useState } from "react";
4
+
5
+ export type TypeScale = {
6
+ /** Base font size in px (drives text-base). */
7
+ base: number;
8
+ /** Modular scale ratio. Each step multiplies/divides by this value. */
9
+ ratio: number;
10
+ };
11
+
12
+ export const TYPE_SCALE_DEFAULTS: TypeScale = {
13
+ base: 18,
14
+ ratio: 1.125,
15
+ };
16
+
17
+ export const TYPE_SCALE_RANGES = {
18
+ base: { min: 14, max: 22, step: 0.5, unit: "px" },
19
+ ratio: { min: 1.05, max: 1.4, step: 0.005, unit: "" },
20
+ } as const;
21
+
22
+ /** Common modular scale ratios. Surfacing as labels under the slider helps
23
+ * designers anchor on familiar typographic systems. */
24
+ export const RATIO_PRESETS = [
25
+ { value: 1.067, label: "Minor Second" },
26
+ { value: 1.125, label: "Major Second" },
27
+ { value: 1.2, label: "Minor Third" },
28
+ { value: 1.25, label: "Major Third" },
29
+ { value: 1.333, label: "Perfect Fourth" },
30
+ ] as const;
31
+
32
+ const STORAGE_KEY = "BADS.typeScale";
33
+
34
+ /** The Tailwind text-* utilities this design system exposes, mapped to their
35
+ * step offset from base. Steps are exponents on the ratio. */
36
+ const STEPS: Record<string, number> = {
37
+ "text-xs": -2,
38
+ "text-sm": -1,
39
+ "text-base": 0,
40
+ "text-lg": 1,
41
+ "text-xl": 2,
42
+ "text-2xl": 3,
43
+ "text-3xl": 4,
44
+ };
45
+
46
+ export function computeSizes(scale: TypeScale): Record<string, number> {
47
+ const out: Record<string, number> = {};
48
+ for (const [name, step] of Object.entries(STEPS)) {
49
+ out[name] = scale.base * Math.pow(scale.ratio, step);
50
+ }
51
+ return out;
52
+ }
53
+
54
+ function applyScale(scale: TypeScale) {
55
+ if (typeof document === "undefined") return;
56
+ const sizes = computeSizes(scale);
57
+ const root = document.documentElement.style;
58
+ // The CSS variables that Tailwind's text-* utilities resolve to are named
59
+ // --text-{size}-size in :root (see styles/globals.css). The @theme block
60
+ // points --text-{size} at these via var(), so overriding here propagates
61
+ // through every text-xs / text-sm / etc. utility on the page.
62
+ for (const [name, value] of Object.entries(sizes)) {
63
+ // 'name' is e.g. 'text-xs' — append '-size' to match the runtime var.
64
+ root.setProperty(`--${name}-size`, `${value.toFixed(2)}px`);
65
+ }
66
+ }
67
+
68
+ function readStored(): TypeScale {
69
+ if (typeof window === "undefined") return TYPE_SCALE_DEFAULTS;
70
+ const raw = window.localStorage.getItem(STORAGE_KEY);
71
+ if (!raw) return TYPE_SCALE_DEFAULTS;
72
+ try {
73
+ const parsed = JSON.parse(raw);
74
+ return {
75
+ base:
76
+ typeof parsed.base === "number" ? parsed.base : TYPE_SCALE_DEFAULTS.base,
77
+ ratio:
78
+ typeof parsed.ratio === "number"
79
+ ? parsed.ratio
80
+ : TYPE_SCALE_DEFAULTS.ratio,
81
+ };
82
+ } catch {
83
+ return TYPE_SCALE_DEFAULTS;
84
+ }
85
+ }
86
+
87
+ /**
88
+ * Cross-iframe type scale. Persists base size + ratio in localStorage and
89
+ * computes 7 text-* CSS variables (xs..3xl) on documentElement.
90
+ *
91
+ * IMPORTANT: This hook does NOT apply CSS on initial mount. The layout.tsx
92
+ * inline script (running in <head> before hydration) handles initial
93
+ * application from localStorage. The hook only reads stored values into
94
+ * local React state for the slider UI, and only applies CSS when setScale
95
+ * or reset is called. This prevents the navigation flash that occurred when
96
+ * multiple instances of the hook (Providers + TypeScalePanel) re-applied
97
+ * variables on mount, briefly recomputing values with default ratio before
98
+ * the stored ratio took effect.
99
+ */
100
+ export function useGlobalTypeScale() {
101
+ const [scale, setScaleState] = useState<TypeScale>(TYPE_SCALE_DEFAULTS);
102
+
103
+ useEffect(() => {
104
+ if (typeof window === "undefined") return;
105
+ // Only read into state for slider UI — CSS already applied by layout script.
106
+ setScaleState(readStored());
107
+ }, []);
108
+
109
+ useEffect(() => {
110
+ if (typeof window === "undefined") return;
111
+ const onStorage = (e: StorageEvent) => {
112
+ if (e.key !== STORAGE_KEY) return;
113
+ const stored = readStored();
114
+ setScaleState(stored);
115
+ applyScale(stored);
116
+ };
117
+ window.addEventListener("storage", onStorage);
118
+ return () => window.removeEventListener("storage", onStorage);
119
+ }, []);
120
+
121
+ const setScale = useCallback(<K extends keyof TypeScale>(key: K, value: TypeScale[K]) => {
122
+ setScaleState((prev) => {
123
+ const next = { ...prev, [key]: value };
124
+ applyScale(next);
125
+ if (typeof window !== "undefined") {
126
+ window.localStorage.setItem(STORAGE_KEY, JSON.stringify(next));
127
+ }
128
+ return next;
129
+ });
130
+ }, []);
131
+
132
+ const reset = useCallback(() => {
133
+ setScaleState(TYPE_SCALE_DEFAULTS);
134
+ applyScale(TYPE_SCALE_DEFAULTS);
135
+ if (typeof window !== "undefined") {
136
+ window.localStorage.removeItem(STORAGE_KEY);
137
+ }
138
+ }, []);
139
+
140
+ return { scale, setScale, reset };
141
+ }
@@ -0,0 +1,51 @@
1
+ "use client";
2
+
3
+ import { useLayoutEffect } from "react";
4
+ import { TYPE_SCALE_DEFAULTS } from "./use-global-type-scale";
5
+
6
+ const STEPS = {
7
+ "text-xs": -2,
8
+ "text-sm": -1,
9
+ "text-base": 0,
10
+ "text-lg": 1,
11
+ "text-xl": 2,
12
+ "text-2xl": 3,
13
+ "text-3xl": 4,
14
+ } as const;
15
+
16
+ function applyTypeScale() {
17
+ if (typeof window === "undefined" || typeof document === "undefined") return;
18
+
19
+ const root = document.documentElement.style;
20
+ let base = TYPE_SCALE_DEFAULTS.base;
21
+ let ratio = TYPE_SCALE_DEFAULTS.ratio;
22
+
23
+ // Try to read from localStorage, fall back to defaults
24
+ try {
25
+ const stored = localStorage.getItem("BADS.typeScale");
26
+ if (stored) {
27
+ const parsed = JSON.parse(stored);
28
+ if (typeof parsed.base === "number") base = parsed.base;
29
+ if (typeof parsed.ratio === "number") ratio = parsed.ratio;
30
+ }
31
+ } catch (e) {
32
+ // Use defaults
33
+ }
34
+
35
+ // Apply computed sizes as CSS variables
36
+ for (const [name, step] of Object.entries(STEPS)) {
37
+ const size = base * Math.pow(ratio, step);
38
+ root.setProperty(`--${name}-size`, `${size.toFixed(2)}px`);
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Synchronously apply type scale CSS variables using useLayoutEffect.
44
+ * This runs before first render and before the main useGlobalTypeScale hook,
45
+ * ensuring font sizes are set from the start.
46
+ */
47
+ export function useSyncTypeScale() {
48
+ useLayoutEffect(() => {
49
+ applyTypeScale();
50
+ }, []);
51
+ }
@@ -0,0 +1,98 @@
1
+ "use client";
2
+
3
+ import { useCallback, useEffect, useState } from "react";
4
+ import {
5
+ applyThemeEditorState,
6
+ readStoredThemeEditorState,
7
+ THEME_EDITOR_STORAGE_KEY,
8
+ } from "@behavioral-agentic-design-system/core/lib/theme-editor";
9
+
10
+ const STORAGE_KEY = "BADS.tokenOverrides";
11
+
12
+ type Overrides = Record<string, string>;
13
+
14
+ function read(): Overrides {
15
+ if (typeof window === "undefined") return {};
16
+ try {
17
+ const raw = window.localStorage.getItem(STORAGE_KEY);
18
+ if (!raw) return {};
19
+ const parsed = JSON.parse(raw) as Overrides;
20
+ return parsed && typeof parsed === "object" ? parsed : {};
21
+ } catch {
22
+ return {};
23
+ }
24
+ }
25
+
26
+ function write(overrides: Overrides) {
27
+ if (typeof window === "undefined") return;
28
+ window.localStorage.setItem(STORAGE_KEY, JSON.stringify(overrides));
29
+ }
30
+
31
+ function applyAll(overrides: Overrides) {
32
+ if (typeof document === "undefined") return;
33
+ applyThemeEditorState(readStoredThemeEditorState());
34
+ const style = document.documentElement.style;
35
+ for (const [variable, value] of Object.entries(overrides)) {
36
+ style.setProperty(variable, value);
37
+ }
38
+ }
39
+
40
+ /**
41
+ * Cross-iframe token override map. Lets any swatch in the Customize tab edit
42
+ * a CSS variable on :root directly. Persists in localStorage and syncs across
43
+ * preview iframes via the storage event.
44
+ */
45
+ export function useTokenOverrides() {
46
+ const [overrides, setOverrides] = useState<Overrides>({});
47
+
48
+ useEffect(() => {
49
+ if (typeof window === "undefined") return;
50
+ const initial = read();
51
+ setOverrides(initial);
52
+ applyAll(initial);
53
+ }, []);
54
+
55
+ useEffect(() => {
56
+ if (typeof window === "undefined") return;
57
+ const onStorage = (e: StorageEvent) => {
58
+ if (e.key === THEME_EDITOR_STORAGE_KEY) {
59
+ applyThemeEditorState(readStoredThemeEditorState());
60
+ return;
61
+ }
62
+
63
+ if (e.key !== STORAGE_KEY) return;
64
+ const next = read();
65
+ setOverrides(next);
66
+ applyAll(next);
67
+ };
68
+ window.addEventListener("storage", onStorage);
69
+ return () => window.removeEventListener("storage", onStorage);
70
+ }, []);
71
+
72
+ const set = useCallback((variable: string, value: string) => {
73
+ setOverrides((prev) => {
74
+ const next = { ...prev, [variable]: value };
75
+ write(next);
76
+ if (typeof document !== "undefined") {
77
+ document.documentElement.style.setProperty(variable, value);
78
+ }
79
+ return next;
80
+ });
81
+ }, []);
82
+
83
+ const remove = useCallback((variable: string) => {
84
+ setOverrides((prev) => {
85
+ const next = { ...prev };
86
+ delete next[variable];
87
+ write(next);
88
+ // can't actually unset back to stylesheet default without a reload, but
89
+ // we can clear the inline override so the cascade resumes.
90
+ if (typeof document !== "undefined") {
91
+ document.documentElement.style.removeProperty(variable);
92
+ }
93
+ return next;
94
+ });
95
+ }, []);
96
+
97
+ return { overrides, updateOverride: set, remove };
98
+ }