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

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 (44) hide show
  1. package/package.json +32 -4
  2. package/scripts/bads-sync.mjs +81 -0
  3. package/scripts/build-tokens.cjs +430 -0
  4. package/src/app/font-ready.tsx +51 -0
  5. package/src/app/layout.tsx +152 -0
  6. package/src/app/page.tsx +267 -0
  7. package/src/app/preview/cards/page.tsx +8 -0
  8. package/src/app/preview/components/page.tsx +232 -0
  9. package/src/app/preview/dark-mode-client.tsx +24 -0
  10. package/src/app/preview/dashboard/page.tsx +4 -0
  11. package/src/app/preview/global-font-client.tsx +36 -0
  12. package/src/app/preview/layout.tsx +13 -0
  13. package/src/app/preview/mail/page.tsx +4 -0
  14. package/src/app/preview/pricing/page.tsx +4 -0
  15. package/src/app/preview/typography/page.tsx +11 -0
  16. package/src/app/providers.tsx +49 -0
  17. package/src/components/Foundations/Colors.stories.tsx +85 -0
  18. package/src/components/Foundations/Motion.stories.tsx +169 -0
  19. package/src/components/Foundations/Radius.stories.tsx +36 -0
  20. package/src/components/Foundations/Shadows.stories.tsx +30 -0
  21. package/src/components/Foundations/Spacing.stories.tsx +35 -0
  22. package/src/components/Foundations/Typography.stories.tsx +68 -0
  23. package/src/components/bads-update-banner.tsx +120 -0
  24. package/src/components/customize/design-controls.tsx +165 -0
  25. package/src/components/customize/font-pickers.tsx +118 -0
  26. package/src/components/customize/letter-spacing.tsx +105 -0
  27. package/src/components/customize/save-bar.tsx +379 -0
  28. package/src/components/customize/theme-io.tsx +245 -0
  29. package/src/components/customize/type-scale.tsx +134 -0
  30. package/src/components/customize-tab.tsx +502 -0
  31. package/src/components/home-tab.tsx +1227 -0
  32. package/src/components/layers-tab.tsx +225 -0
  33. package/src/components/ui/alert.tsx +5 -1
  34. package/src/hooks/use-global-design-controls.ts +117 -0
  35. package/src/hooks/use-global-mono-font.ts +73 -0
  36. package/src/hooks/use-global-primary-color.ts +544 -0
  37. package/src/hooks/use-global-sans-font.ts +98 -0
  38. package/src/hooks/use-global-serif-font.ts +77 -0
  39. package/src/hooks/use-global-theme.ts +259 -0
  40. package/src/hooks/use-global-type-scale.ts +141 -0
  41. package/src/hooks/use-sync-type-scale.ts +51 -0
  42. package/src/hooks/use-token-overrides.ts +98 -0
  43. package/src/styles.css +20 -5
  44. package/src/tokens.json +5 -5
@@ -0,0 +1,544 @@
1
+ "use client";
2
+
3
+ import { useCallback, useEffect, useMemo, useSyncExternalStore } from "react";
4
+ import { brand, type BrandColor } from "@/brand.config";
5
+ import { nameFromHex } from "@behavioral-agentic-design-system/core/lib/color-name";
6
+
7
+ export type WcagGrade = "AAA" | "AA" | "AA Large" | "Fail";
8
+
9
+ export type PrimaryColorOption = {
10
+ label: string;
11
+ primary: string;
12
+ primaryHover: string;
13
+ primaryForeground: string;
14
+ /**
15
+ * Optional designer-authored note carried in from brand.config. The picker
16
+ * no longer auto-generates contrast-adjustment notes (we don't adjust
17
+ * colors anymore — see grade below for the contrast verdict).
18
+ */
19
+ note: string | null;
20
+ /** WCAG contrast grade vs the chosen foreground. Surfaced as a pill in the picker. */
21
+ grade: WcagGrade;
22
+ /** Numeric contrast ratio (rounded to 1 decimal). Useful for tooltips. */
23
+ contrast: number;
24
+ custom?: boolean;
25
+ /**
26
+ * Optional override for the picker swatch when the displayed color should
27
+ * differ from the applied primary. Carried over from the swimtopia customize
28
+ * tab (e.g. an "Off White" option that applies dark in light mode but the
29
+ * picker still reads off-white). BADS' built-in palette doesn't set these.
30
+ */
31
+ swatch?: string;
32
+ swatchForeground?: string;
33
+ };
34
+
35
+ function isValidHex(hex: string): boolean {
36
+ return /^#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})$/.test(hex.trim());
37
+ }
38
+
39
+ function normalizeHex(hex: string): string {
40
+ const trimmed = hex.trim().toUpperCase();
41
+ if (/^#[0-9A-F]{3}$/.test(trimmed)) {
42
+ return "#" + trimmed.slice(1).split("").map(c => c + c).join("");
43
+ }
44
+ return trimmed;
45
+ }
46
+
47
+ function rgbFromHex(hex: string): [number, number, number] {
48
+ const h = normalizeHex(hex).slice(1);
49
+ return [
50
+ parseInt(h.slice(0, 2), 16) / 255,
51
+ parseInt(h.slice(2, 4), 16) / 255,
52
+ parseInt(h.slice(4, 6), 16) / 255,
53
+ ];
54
+ }
55
+
56
+ function relLuminance([r, g, b]: [number, number, number]): number {
57
+ const lin = (c: number) => (c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4));
58
+ return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b);
59
+ }
60
+
61
+ function contrastRatio(a: [number, number, number], b: [number, number, number]): number {
62
+ const la = relLuminance(a);
63
+ const lb = relLuminance(b);
64
+ const [hi, lo] = la > lb ? [la, lb] : [lb, la];
65
+ return (hi + 0.05) / (lo + 0.05);
66
+ }
67
+
68
+ // All constants and helper functions live above the data-initialization
69
+ // block (SHADCN_NEUTRAL, BUILTIN_PRIMARY_COLORS) so module-init code never
70
+ // dereferences a not-yet-bound binding. Function declarations are technically
71
+ // hoisted in ES modules, but some transpile / bundler combos (esp. SWC with
72
+ // `target: es2022`) emit `const`-style bindings that DO hit TDZ. Keeping
73
+ // declarations above usage is the defensive shape.
74
+ const NEAR_WHITE: [number, number, number] = [0xfa / 255, 0xfa / 255, 0xfa / 255];
75
+ const NEAR_BLACK: [number, number, number] = [0x0a / 255, 0x0a / 255, 0x0a / 255];
76
+
77
+ /** Pick whichever of near-white / near-black hits the higher contrast against
78
+ * the given color. We no longer adjust the primary to force AAA — instead
79
+ * the picker shows a WCAG grade pill so the user can see whether their pick
80
+ * meets AAA / AA / AA Large or fails outright. */
81
+ function deriveForeground(hex: string): string {
82
+ const rgb = rgbFromHex(hex);
83
+ const ratioWhite = contrastRatio(rgb, NEAR_WHITE);
84
+ const ratioBlack = contrastRatio(rgb, NEAR_BLACK);
85
+ return ratioBlack >= ratioWhite ? "#0A0A0A" : "#FAFAFA";
86
+ }
87
+
88
+ function darkenHex(hex: string, amount = 0.15): string {
89
+ const h = normalizeHex(hex).slice(1);
90
+ const r = Math.max(0, Math.round(parseInt(h.slice(0, 2), 16) * (1 - amount)));
91
+ const g = Math.max(0, Math.round(parseInt(h.slice(2, 4), 16) * (1 - amount)));
92
+ const b = Math.max(0, Math.round(parseInt(h.slice(4, 6), 16) * (1 - amount)));
93
+ return "#" + [r, g, b].map(v => v.toString(16).padStart(2, "0")).join("").toUpperCase();
94
+ }
95
+
96
+ function gradeFromRatio(ratio: number): WcagGrade {
97
+ if (ratio >= 7) return "AAA";
98
+ if (ratio >= 4.5) return "AA";
99
+ if (ratio >= 3) return "AA Large";
100
+ return "Fail";
101
+ }
102
+
103
+ function makeOption(args: {
104
+ label: string;
105
+ primary: string;
106
+ primaryForeground?: string;
107
+ note?: string | null;
108
+ custom?: boolean;
109
+ }): PrimaryColorOption {
110
+ const primary = normalizeHex(args.primary);
111
+ const fg = args.primaryForeground
112
+ ? normalizeHex(args.primaryForeground)
113
+ : deriveForeground(primary);
114
+ const ratio = contrastRatio(rgbFromHex(primary), rgbFromHex(fg));
115
+ return {
116
+ label: args.label,
117
+ primary,
118
+ primaryHover: darkenHex(primary),
119
+ primaryForeground: fg,
120
+ note: args.note ?? null,
121
+ grade: gradeFromRatio(ratio),
122
+ contrast: Math.round(ratio * 10) / 10,
123
+ custom: args.custom,
124
+ };
125
+ }
126
+
127
+ function brandColorToOption(c: BrandColor): PrimaryColorOption {
128
+ return makeOption({
129
+ label: c.label,
130
+ primary: c.primary,
131
+ primaryForeground: c.primaryForeground,
132
+ note: c.note ?? null,
133
+ });
134
+ }
135
+
136
+ // ─── Data init (depends on every helper above) ────────────────────────────
137
+ const SHADCN_NEUTRAL: PrimaryColorOption = makeOption({
138
+ label: "Neutral (shadcn)",
139
+ primary: "#1F1F1F",
140
+ primaryForeground: "#FAFAFA",
141
+ note: "Default shadcn neutral. Near-black primary, off-white foreground.",
142
+ });
143
+
144
+ // Built-ins = shadcn neutral + anything declared in brand.config.ts.
145
+ // Brand colors come first so they're prioritized in the picker.
146
+ export const BUILTIN_PRIMARY_COLORS: Record<string, PrimaryColorOption> = {
147
+ ...Object.fromEntries(brand.colors.map((c) => [c.id, brandColorToOption(c)])),
148
+ neutral: SHADCN_NEUTRAL,
149
+ };
150
+
151
+ const COLOR_KEY = "BADS.primaryColor";
152
+ const CUSTOMS_KEY = "BADS.customPrimaryColors";
153
+ // First brand color (if any) wins as the default; otherwise fall back to shadcn neutral.
154
+ const DEFAULT = brand.colors[0]?.id ?? "neutral";
155
+
156
+ const PRIMARY_OVERRIDE_VARIABLES = [
157
+ "--primary",
158
+ "--primary-foreground",
159
+ "--ring",
160
+ "--accent-foreground",
161
+ "--sidebar-primary",
162
+ "--sidebar-primary-foreground",
163
+ "--sidebar-ring",
164
+ // Chart vars are NOT listed here. They derive from --primary in CSS
165
+ // (see scripts/build-tokens.js → chartDerivationLight). The picker only
166
+ // needs to set --primary; charts cascade automatically. This also keeps
167
+ // per-chart user overrides (set inline via documentElement.style on
168
+ // --chart-N) intact across primary changes.
169
+ ];
170
+
171
+ function buildCustom(hex: string, label?: string): PrimaryColorOption {
172
+ const requested = normalizeHex(hex);
173
+ // No more contrast-adjusting. Apply the color as-is and surface a WCAG
174
+ // grade pill (AAA / AA / AA Large / Fail) so the user can see where it
175
+ // sits without us silently changing their pick. Auto-name the color from
176
+ // the closest CSS named color when no label is provided.
177
+ return makeOption({
178
+ label: label?.trim() || nameFromHex(requested),
179
+ primary: requested,
180
+ custom: true,
181
+ });
182
+ }
183
+
184
+ function readCustoms(): Record<string, PrimaryColorOption> {
185
+ if (typeof window === "undefined") return {};
186
+ try {
187
+ const raw = window.localStorage.getItem(CUSTOMS_KEY);
188
+ if (!raw) return {};
189
+ const parsed = JSON.parse(raw) as Record<string, PrimaryColorOption>;
190
+ if (!parsed || typeof parsed !== "object") return {};
191
+ // Backfill grade + contrast on legacy entries that were saved before the
192
+ // contrast-grade pill existed. Re-derive from the stored primary so the
193
+ // pill renders correctly without forcing the user to re-add their colors.
194
+ const normalized: Record<string, PrimaryColorOption> = {};
195
+ for (const [id, opt] of Object.entries(parsed)) {
196
+ if (opt.grade && typeof opt.contrast === "number") {
197
+ normalized[id] = opt;
198
+ } else {
199
+ normalized[id] = makeOption({
200
+ label: opt.label,
201
+ primary: opt.primary,
202
+ primaryForeground: opt.primaryForeground,
203
+ note: opt.note ?? null,
204
+ custom: true,
205
+ });
206
+ }
207
+ }
208
+ return normalized;
209
+ } catch {
210
+ return {};
211
+ }
212
+ }
213
+
214
+ function readColorKey(): string {
215
+ if (typeof window === "undefined") return DEFAULT;
216
+ return window.localStorage.getItem(COLOR_KEY) || DEFAULT;
217
+ }
218
+
219
+ function clearPrimaryColor() {
220
+ if (typeof document === "undefined") return;
221
+ const root = document.documentElement.style;
222
+ for (const variable of PRIMARY_OVERRIDE_VARIABLES) {
223
+ root.removeProperty(variable);
224
+ }
225
+ }
226
+
227
+ function applyColor(opt: PrimaryColorOption) {
228
+ if (typeof document === "undefined") return;
229
+ const root = document.documentElement.style;
230
+ root.setProperty("--primary", opt.primary);
231
+ root.setProperty("--primary-foreground", opt.primaryForeground);
232
+ root.setProperty("--ring", opt.primary);
233
+ root.setProperty("--accent-foreground", opt.primary);
234
+ root.setProperty("--sidebar-primary", opt.primary);
235
+ root.setProperty("--sidebar-primary-foreground", opt.primaryForeground);
236
+ root.setProperty("--sidebar-ring", opt.primary);
237
+ // Charts derive from --primary in CSS (see styles/globals.css chart block).
238
+ // No JS overrides here — that way per-chart user customizations (set inline
239
+ // on documentElement.style) survive every primary change.
240
+ }
241
+
242
+ function applySelectedColor(color: string, options: Record<string, PrimaryColorOption>) {
243
+ if (color === "neutral") {
244
+ clearPrimaryColor();
245
+ return;
246
+ }
247
+
248
+ const option = options[color];
249
+ if (option) {
250
+ applyColor(option);
251
+ } else {
252
+ clearPrimaryColor();
253
+ }
254
+ }
255
+
256
+ // ---- Module-level shared store -------------------------------------------
257
+ // Hook instances within the same window share customs + active color via
258
+ // useSyncExternalStore. Cross-window/iframe still routed through the
259
+ // localStorage `storage` event below.
260
+
261
+ type Snapshot = {
262
+ customs: Record<string, PrimaryColorOption>;
263
+ color: string;
264
+ };
265
+
266
+ const SERVER_SNAPSHOT: Snapshot = { customs: {}, color: DEFAULT };
267
+ let snapshot: Snapshot = { customs: {}, color: DEFAULT };
268
+ const subscribers = new Set<() => void>();
269
+
270
+ function commit(next: Snapshot) {
271
+ snapshot = next;
272
+ subscribers.forEach((fn) => fn());
273
+ }
274
+
275
+ function subscribe(fn: () => void) {
276
+ subscribers.add(fn);
277
+ return () => subscribers.delete(fn);
278
+ }
279
+
280
+ function getSnapshot(): Snapshot {
281
+ return snapshot;
282
+ }
283
+
284
+ function getServerSnapshot(): Snapshot {
285
+ return SERVER_SNAPSHOT;
286
+ }
287
+
288
+ let bootstrapped = false;
289
+ function bootstrap() {
290
+ if (bootstrapped || typeof window === "undefined") return;
291
+ bootstrapped = true;
292
+ const customs = readCustoms();
293
+ const merged = { ...BUILTIN_PRIMARY_COLORS, ...customs };
294
+ const stored = readColorKey();
295
+ const color = stored in merged ? stored : DEFAULT;
296
+ snapshot = { customs, color };
297
+ applySelectedColor(color, merged);
298
+
299
+ window.addEventListener("storage", (e) => {
300
+ if (e.key === CUSTOMS_KEY) {
301
+ const customs = readCustoms();
302
+ const merged = { ...BUILTIN_PRIMARY_COLORS, ...customs };
303
+ const color = snapshot.color in merged ? snapshot.color : DEFAULT;
304
+ commit({ customs, color });
305
+ applySelectedColor(color, merged);
306
+ } else if (e.key === COLOR_KEY) {
307
+ const merged = { ...BUILTIN_PRIMARY_COLORS, ...snapshot.customs };
308
+ const next = e.newValue && e.newValue in merged ? e.newValue : DEFAULT;
309
+ commit({ ...snapshot, color: next });
310
+ applySelectedColor(next, merged);
311
+ }
312
+ });
313
+ }
314
+
315
+ /**
316
+ * Cross-iframe primary color selector. Built-in palette is shadcn neutral;
317
+ * additional colors are added by the user. Same-window hook instances share
318
+ * state via useSyncExternalStore; cross-window via localStorage events.
319
+ */
320
+ export function useGlobalPrimaryColor() {
321
+ useEffect(() => { bootstrap(); }, []);
322
+ const state = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
323
+
324
+ const options = useMemo<Record<string, PrimaryColorOption>>(
325
+ () => ({ ...BUILTIN_PRIMARY_COLORS, ...state.customs }),
326
+ [state.customs],
327
+ );
328
+
329
+ const setColor = useCallback(
330
+ (next: string) => {
331
+ const merged = { ...BUILTIN_PRIMARY_COLORS, ...snapshot.customs };
332
+ if (!(next in merged)) return;
333
+ commit({ ...snapshot, color: next });
334
+ applySelectedColor(next, merged);
335
+ if (typeof window !== "undefined") {
336
+ window.localStorage.setItem(COLOR_KEY, next);
337
+ }
338
+ },
339
+ [],
340
+ );
341
+
342
+ const addCustom = useCallback(
343
+ (hex: string, label?: string): string | null => {
344
+ if (!isValidHex(hex)) return null;
345
+ const normalized = normalizeHex(hex);
346
+
347
+ // Dedup against built-ins AND existing customs. If this hex is already
348
+ // in the picker, just select that swatch — don't create a duplicate
349
+ // card. Matches case-insensitive on the normalized hex; primaries that
350
+ // come in as 3-char or lowercase hex still resolve to the same option.
351
+ const merged: Record<string, PrimaryColorOption> = {
352
+ ...BUILTIN_PRIMARY_COLORS,
353
+ ...snapshot.customs,
354
+ };
355
+ for (const [existingId, opt] of Object.entries(merged)) {
356
+ if (normalizeHex(opt.primary) === normalized) {
357
+ commit({ ...snapshot, color: existingId });
358
+ applySelectedColor(existingId, merged);
359
+ if (typeof window !== "undefined") {
360
+ window.localStorage.setItem(COLOR_KEY, existingId);
361
+ }
362
+ return existingId;
363
+ }
364
+ }
365
+
366
+ const id = `custom-${normalized.slice(1).toLowerCase()}`;
367
+ const opt = buildCustom(normalized, label);
368
+ const customs = { ...snapshot.customs, [id]: opt };
369
+ commit({ customs, color: id });
370
+ applyColor(opt);
371
+ if (typeof window !== "undefined") {
372
+ window.localStorage.setItem(CUSTOMS_KEY, JSON.stringify(customs));
373
+ window.localStorage.setItem(COLOR_KEY, id);
374
+ }
375
+ return id;
376
+ },
377
+ [],
378
+ );
379
+
380
+ const removeCustom = useCallback(
381
+ (id: string) => {
382
+ if (!(id in snapshot.customs)) return;
383
+ const customs = { ...snapshot.customs };
384
+ delete customs[id];
385
+ let color = snapshot.color;
386
+ if (color === id) {
387
+ color = DEFAULT;
388
+ applySelectedColor(color, BUILTIN_PRIMARY_COLORS);
389
+ if (typeof window !== "undefined") {
390
+ window.localStorage.setItem(COLOR_KEY, DEFAULT);
391
+ }
392
+ }
393
+ commit({ customs, color });
394
+ if (typeof window !== "undefined") {
395
+ window.localStorage.setItem(CUSTOMS_KEY, JSON.stringify(customs));
396
+ }
397
+ },
398
+ [],
399
+ );
400
+
401
+ const renameCustom = useCallback(
402
+ (id: string, label: string) => {
403
+ if (!(id in snapshot.customs)) return;
404
+ const trimmed = label.trim();
405
+ if (!trimmed) return;
406
+ const existing = snapshot.customs[id];
407
+ const customs: Record<string, PrimaryColorOption> = {
408
+ ...snapshot.customs,
409
+ [id]: { ...existing, label: trimmed },
410
+ };
411
+ commit({ ...snapshot, customs });
412
+ if (typeof window !== "undefined") {
413
+ window.localStorage.setItem(CUSTOMS_KEY, JSON.stringify(customs));
414
+ }
415
+ },
416
+ [],
417
+ );
418
+
419
+ // ─── Server-backed actions on brand-colors.json (built-ins) ──────────────
420
+ // These hit /api/brand-colors which writes to disk. In dev the JSON file
421
+ // change triggers a Fast Refresh of brand.config.ts → BUILTIN_PRIMARY_COLORS
422
+ // re-imports → picker re-renders. Falls back to a soft reload after 600ms
423
+ // in case Fast Refresh misses the import boundary (rare).
424
+ const pinCustom = useCallback(
425
+ async (id: string): Promise<{ ok: boolean; error?: string }> => {
426
+ const opt = snapshot.customs[id];
427
+ if (!opt) return { ok: false, error: "Color not found" };
428
+ const trimmedLabel = opt.label.trim();
429
+ const slug = trimmedLabel
430
+ .toLowerCase()
431
+ .replace(/[^a-z0-9]+/g, "-")
432
+ .replace(/^-+|-+$/g, "")
433
+ .slice(0, 48) || id.replace(/^custom-/, "c-");
434
+ try {
435
+ const res = await fetch("/api/brand-colors", {
436
+ method: "POST",
437
+ headers: { "Content-Type": "application/json" },
438
+ body: JSON.stringify({
439
+ action: "pin",
440
+ entry: {
441
+ id: slug,
442
+ label: trimmedLabel,
443
+ primary: opt.primary,
444
+ primaryForeground: opt.primaryForeground,
445
+ note: opt.note ?? undefined,
446
+ },
447
+ }),
448
+ });
449
+ const data = await res.json();
450
+ if (!res.ok || !data.ok) {
451
+ return { ok: false, error: data.error ?? "Pin failed" };
452
+ }
453
+ // Drop the localStorage custom so the picker doesn't show duplicates.
454
+ // Switch the active color to the new built-in id so the user keeps
455
+ // looking at the same color.
456
+ const customs = { ...snapshot.customs };
457
+ delete customs[id];
458
+ commit({ customs, color: slug });
459
+ if (typeof window !== "undefined") {
460
+ window.localStorage.setItem(CUSTOMS_KEY, JSON.stringify(customs));
461
+ window.localStorage.setItem(COLOR_KEY, slug);
462
+ // Soft reload — Fast Refresh on JSON imports is unreliable.
463
+ window.setTimeout(() => window.location.reload(), 350);
464
+ }
465
+ return { ok: true };
466
+ } catch (e) {
467
+ return { ok: false, error: e instanceof Error ? e.message : "Pin failed" };
468
+ }
469
+ },
470
+ [],
471
+ );
472
+
473
+ const removeBuiltin = useCallback(
474
+ async (id: string): Promise<{ ok: boolean; error?: string }> => {
475
+ try {
476
+ const res = await fetch("/api/brand-colors", {
477
+ method: "POST",
478
+ headers: { "Content-Type": "application/json" },
479
+ body: JSON.stringify({ action: "remove", id }),
480
+ });
481
+ const data = await res.json();
482
+ if (!res.ok || !data.ok) {
483
+ return { ok: false, error: data.error ?? "Remove failed" };
484
+ }
485
+ // If the removed color was active, fall back to neutral and reload.
486
+ if (snapshot.color === id) {
487
+ if (typeof window !== "undefined") {
488
+ window.localStorage.setItem(COLOR_KEY, "neutral");
489
+ }
490
+ }
491
+ if (typeof window !== "undefined") {
492
+ window.setTimeout(() => window.location.reload(), 350);
493
+ }
494
+ return { ok: true };
495
+ } catch (e) {
496
+ return { ok: false, error: e instanceof Error ? e.message : "Remove failed" };
497
+ }
498
+ },
499
+ [],
500
+ );
501
+
502
+ const renameBuiltin = useCallback(
503
+ async (id: string, label: string): Promise<{ ok: boolean; error?: string }> => {
504
+ const trimmed = label.trim();
505
+ if (!trimmed) return { ok: false, error: "Label can't be empty" };
506
+ try {
507
+ const res = await fetch("/api/brand-colors", {
508
+ method: "POST",
509
+ headers: { "Content-Type": "application/json" },
510
+ body: JSON.stringify({ action: "rename", id, label: trimmed }),
511
+ });
512
+ const data = await res.json();
513
+ if (!res.ok || !data.ok) {
514
+ return { ok: false, error: data.error ?? "Rename failed" };
515
+ }
516
+ if (typeof window !== "undefined") {
517
+ window.setTimeout(() => window.location.reload(), 350);
518
+ }
519
+ return { ok: true };
520
+ } catch (e) {
521
+ return { ok: false, error: e instanceof Error ? e.message : "Rename failed" };
522
+ }
523
+ },
524
+ [],
525
+ );
526
+
527
+ return {
528
+ color: state.color,
529
+ setColor,
530
+ addCustom,
531
+ removeCustom,
532
+ renameCustom,
533
+ pinCustom,
534
+ removeBuiltin,
535
+ renameBuiltin,
536
+ options,
537
+ customs: state.customs,
538
+ builtins: BUILTIN_PRIMARY_COLORS,
539
+ };
540
+ }
541
+
542
+ // Back-compat
543
+ export const PRIMARY_COLOR_OPTIONS = BUILTIN_PRIMARY_COLORS;
544
+ export type PrimaryColorKey = string;
@@ -0,0 +1,98 @@
1
+ "use client";
2
+
3
+ import { useCallback, useEffect, useState } from "react";
4
+ import { brand } from "@/brand.config";
5
+
6
+ type SansFontOption = {
7
+ label: string;
8
+ stack: string;
9
+ };
10
+
11
+ // Stacks lead with next/font's preloaded variables (--font-atkinson, --font-inter)
12
+ // so the showcase app uses the self-hosted woff2 set up in app/layout.tsx,
13
+ // which kills FOUT. The literal family names stay as fallbacks for environments
14
+ // where next/font isn't loaded (e.g. consumers of the npm package).
15
+ const BASE_SANS_FONTS: Record<string, SansFontOption> = {
16
+ hyperlegible: {
17
+ label: "Hyperlegible Sans",
18
+ stack: "'Hyperlegible Sans', ui-sans-serif, sans-serif, system-ui",
19
+ },
20
+ atkinson: {
21
+ label: "Atkinson Hyperlegible",
22
+ stack: "var(--font-atkinson), 'Atkinson Hyperlegible', ui-sans-serif, sans-serif, system-ui",
23
+ },
24
+ inter: {
25
+ label: "Inter",
26
+ stack: "var(--font-inter), 'Inter', ui-sans-serif, sans-serif, system-ui",
27
+ },
28
+ system: {
29
+ label: "System UI",
30
+ stack: "ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",
31
+ },
32
+ };
33
+
34
+ // Brand fonts (declared in brand.config.ts) come first in the picker so the
35
+ // client's font is the default and most prominent option.
36
+ export const SANS_FONT_OPTIONS: Record<string, SansFontOption> = {
37
+ ...Object.fromEntries(brand.fonts.map((f) => [f.id, { label: f.label, stack: f.stack }])),
38
+ ...BASE_SANS_FONTS,
39
+ };
40
+
41
+ export type SansFontKey = string;
42
+
43
+ const STORAGE_KEY = "BADS.sansFont";
44
+ // First brand font (if any) wins as the default; otherwise Hyperlegible.
45
+ const DEFAULT: SansFontKey = brand.fonts[0]?.id ?? "hyperlegible";
46
+
47
+ function isValidKey(value: string | null): value is SansFontKey {
48
+ return !!value && value in SANS_FONT_OPTIONS;
49
+ }
50
+
51
+ function applyFont(key: SansFontKey) {
52
+ if (typeof document === "undefined") return;
53
+ document.documentElement.style.setProperty(
54
+ "--font-sans",
55
+ SANS_FONT_OPTIONS[key].stack,
56
+ );
57
+ }
58
+
59
+ /**
60
+ * Cross-iframe sans font selector. Persists the choice in localStorage so all
61
+ * preview iframes (same origin) stay in sync via the `storage` event. Sets the
62
+ * --font-sans CSS variable on :root so every component using the token updates
63
+ * immediately, design-system-wide.
64
+ */
65
+ export function useGlobalSansFont() {
66
+ const [font, setFontState] = useState<SansFontKey>(DEFAULT);
67
+
68
+ useEffect(() => {
69
+ if (typeof window === "undefined") return;
70
+ const stored = window.localStorage.getItem(STORAGE_KEY);
71
+ const next = isValidKey(stored) ? stored : DEFAULT;
72
+ setFontState(next);
73
+ applyFont(next);
74
+ }, []);
75
+
76
+ useEffect(() => {
77
+ if (typeof window === "undefined") return;
78
+ const onStorage = (e: StorageEvent) => {
79
+ if (e.key !== STORAGE_KEY) return;
80
+ const next = isValidKey(e.newValue) ? e.newValue : DEFAULT;
81
+ setFontState(next);
82
+ applyFont(next);
83
+ };
84
+ window.addEventListener("storage", onStorage);
85
+ return () => window.removeEventListener("storage", onStorage);
86
+ }, []);
87
+
88
+ const setFont = useCallback((next: SansFontKey) => {
89
+ if (!isValidKey(next)) return;
90
+ setFontState(next);
91
+ applyFont(next);
92
+ if (typeof window !== "undefined") {
93
+ window.localStorage.setItem(STORAGE_KEY, next);
94
+ }
95
+ }, []);
96
+
97
+ return { font, setFont };
98
+ }