@behavioral-agentic-design-system/core 0.4.0 → 0.6.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 (43) hide show
  1. package/package.json +16 -8
  2. package/scripts/build-fonts.cjs +90 -0
  3. package/scripts/build-tokens.cjs +99 -8
  4. package/src/api/brand-fonts.ts +280 -0
  5. package/src/api/brand-mark.ts +146 -0
  6. package/src/api/layers/file.ts +4 -2
  7. package/src/api/layers.ts +23 -1
  8. package/src/app/font-ready.tsx +1 -1
  9. package/src/app/layout.tsx +3 -9
  10. package/src/app/page.tsx +9 -263
  11. package/src/app/preview/cards/page.tsx +1 -1
  12. package/src/app/preview/login/page.tsx +5 -0
  13. package/src/app/shell.tsx +354 -0
  14. package/src/components/admin-menu.stories.tsx +68 -0
  15. package/src/components/admin-menu.tsx +59 -0
  16. package/src/components/brand-mark.tsx +64 -0
  17. package/src/components/customize/brand-mark-section.tsx +265 -0
  18. package/src/components/customize/font-pickers.tsx +293 -0
  19. package/src/components/customize/save-bar.tsx +11 -5
  20. package/src/components/customize-tab.tsx +331 -26
  21. package/src/components/dev-identity-badge.tsx +92 -0
  22. package/src/components/home-tab.tsx +1022 -374
  23. package/src/components/layers-tab.tsx +38 -9
  24. package/src/components/ui/alert.tsx +10 -2
  25. package/src/components/ui/button.tsx +1 -1
  26. package/src/components/ui/calendar.tsx +1 -1
  27. package/src/components/ui/chart.tsx +13 -3
  28. package/src/components/ui/checkbox.tsx +1 -1
  29. package/src/components/ui/radio-group.tsx +1 -1
  30. package/src/components/ui/sidebar.tsx +6 -1
  31. package/src/components/ui/sonner.tsx +18 -0
  32. package/src/components/ui/switch.tsx +7 -1
  33. package/src/components/ui/tabs.tsx +1 -1
  34. package/src/hooks/use-global-brand-mark.ts +64 -0
  35. package/src/hooks/use-global-mono-font.ts +13 -3
  36. package/src/hooks/use-global-primary-color.ts +145 -8
  37. package/src/hooks/use-global-sans-font.ts +5 -3
  38. package/src/hooks/use-global-serif-font.ts +14 -4
  39. package/src/lib/storage.ts +31 -2
  40. package/src/lib/svg-sanitize.ts +272 -0
  41. package/src/styles.css +91 -46
  42. package/src/tokens.default.json +4 -4
  43. package/src/tokens.json +172 -78
@@ -9,11 +9,31 @@ import { ScrollArea } from "@behavioral-agentic-design-system/core/components/ui
9
9
 
10
10
  type LayerEntry = { slug: string; label: string; files: string[] };
11
11
  type SaveStatus = "idle" | "saving" | "success" | "error";
12
+ type FileType = "editable" | "read-only";
13
+
14
+ function getFileType(path: string): FileType {
15
+ if (path.endsWith("tokens.json")) return "read-only";
16
+ return "editable";
17
+ }
18
+
19
+ // fileType is set synchronously when activePath changes, but `content` only
20
+ // updates after the fetch resolves. That tick of stale content briefly
21
+ // renders inside the read-only branch, crashing JSON.parse if the previous
22
+ // file was markdown. Fall back to raw text on any parse error.
23
+ function prettyJsonOrRaw(content: string): string {
24
+ if (!content) return "";
25
+ try {
26
+ return JSON.stringify(JSON.parse(content), null, 2);
27
+ } catch {
28
+ return content;
29
+ }
30
+ }
12
31
 
13
32
  export function LayersTab() {
14
33
  const [layers, setLayers] = useState<LayerEntry[]>([]);
15
34
  const [openLayers, setOpenLayers] = useState<Set<string>>(new Set());
16
35
  const [activePath, setActivePath] = useState<string | null>(null);
36
+ const [fileType, setFileType] = useState<FileType>("editable");
17
37
  const [content, setContent] = useState<string>("");
18
38
  const [originalContent, setOriginalContent] = useState<string>("");
19
39
  const [commitMessage, setCommitMessage] = useState<string>("");
@@ -38,6 +58,7 @@ export function LayersTab() {
38
58
  if (!activePath) return;
39
59
  setStatus("idle");
40
60
  setStatusMessage("");
61
+ setFileType(getFileType(activePath));
41
62
  fetch(`/api/layers/file?path=${encodeURIComponent(activePath)}`)
42
63
  .then((r) => r.json())
43
64
  .then((data) => {
@@ -168,16 +189,24 @@ export function LayersTab() {
168
189
  )}
169
190
  </header>
170
191
 
171
- <Textarea
172
- value={content}
173
- onChange={(e) => setContent(e.target.value)}
174
- className={`flex-1 rounded-none border-0 font-mono text-sm leading-relaxed resize-none focus-visible:ring-0 ${
175
- dirty || status !== "idle" ? "pb-32" : ""
176
- }`}
177
- spellCheck={false}
178
- />
192
+ {fileType === "read-only" ? (
193
+ <div className="flex-1 rounded-none border-0 font-mono text-sm leading-relaxed overflow-auto bg-muted/30 p-6">
194
+ <pre className="whitespace-pre-wrap break-words text-foreground/80">
195
+ {prettyJsonOrRaw(content)}
196
+ </pre>
197
+ </div>
198
+ ) : (
199
+ <Textarea
200
+ value={content}
201
+ onChange={(e) => setContent(e.target.value)}
202
+ className={`flex-1 rounded-none border-0 font-mono text-sm leading-relaxed resize-none focus-visible:ring-0 ${
203
+ dirty || status !== "idle" ? "pb-32" : ""
204
+ }`}
205
+ spellCheck={false}
206
+ />
207
+ )}
179
208
 
180
- {(dirty || status !== "idle") && (
209
+ {fileType === "editable" && (dirty || status !== "idle") && (
181
210
  <div className="fixed bottom-0 left-0 right-0 z-50 border-t bg-card/95 backdrop-blur supports-[backdrop-filter]:bg-card/80 shadow-lg">
182
211
  <div className="max-w-7xl mx-auto px-8 py-8 flex items-center gap-4">
183
212
  <GitCommit className="h-4 w-4 text-muted-foreground shrink-0" />
@@ -12,9 +12,17 @@ const alertVariants = cva(
12
12
  {
13
13
  variants: {
14
14
  variant: {
15
- default: "bg-card text-card-foreground",
15
+ // bg-muted gives default alerts a subtle surface bump so they read as
16
+ // a callout even when nested inside a Card (which is also bg-card).
17
+ // Without this, default alert + card = identical surfaces, no hierarchy.
18
+ default: "bg-muted text-foreground",
19
+ // bg-destructive/10 gives destructive alerts a soft red tint without
20
+ // overwhelming the surface. Composite contrast (destructive on
21
+ // destructive/10 over card) stays above AA 4.5:1 across the default
22
+ // BADS palette; forks with very saturated destructive tokens should
23
+ // re-check with `pnpm wcag:audit` after token edits.
16
24
  destructive:
17
- "bg-card text-destructive *:data-[slot=alert-description]:text-destructive/90 [&>svg]:text-current",
25
+ "bg-destructive/10 text-destructive *:data-[slot=alert-description]:text-destructive/90 [&>svg]:text-current",
18
26
  },
19
27
  },
20
28
  defaultVariants: {
@@ -18,7 +18,7 @@ const buttonVariants = cva(
18
18
  "bg-secondary text-secondary-foreground hover:bg-secondary/80",
19
19
  ghost:
20
20
  "hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
21
- link: "text-primary underline-offset-4 hover:underline",
21
+ link: "text-link underline-offset-4 hover:underline",
22
22
  accent: "bg-accent text-accent-foreground shadow-sm hover:bg-accent/80",
23
23
  },
24
24
  size: {
@@ -205,7 +205,7 @@ function CalendarDayButton({
205
205
  data-range-end={modifiers.range_end}
206
206
  data-range-middle={modifiers.range_middle}
207
207
  className={cn(
208
- "flex aspect-square size-auto w-full min-w-(--cell-size) flex-col gap-1 leading-none font-normal group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-[3px] group-data-[focused=true]/day:ring-ring/50 data-[range-end=true]:rounded-md data-[range-end=true]:rounded-r-md data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground data-[range-middle=true]:rounded-none data-[range-middle=true]:bg-accent data-[range-middle=true]:text-accent-foreground data-[range-start=true]:rounded-md data-[range-start=true]:rounded-l-md data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground dark:hover:text-accent-foreground [&>span]:text-xs [&>span]:opacity-70",
208
+ "flex aspect-square size-auto w-full min-w-(--cell-size) flex-col gap-1 leading-none font-normal group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-[3px] group-data-[focused=true]/day:ring-ring/50 data-[range-end=true]:rounded-md data-[range-end=true]:rounded-r-md data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground data-[range-middle=true]:rounded-none data-[range-middle=true]:bg-accent data-[range-middle=true]:text-foreground data-[range-start=true]:rounded-md data-[range-start=true]:rounded-l-md data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground dark:hover:text-accent-foreground [&>span]:text-xs [&>span]:opacity-70",
209
209
  defaultClassNames.day,
210
210
  className
211
211
  )}
@@ -50,6 +50,14 @@ function ChartContainer({
50
50
  const uniqueId = React.useId()
51
51
  const chartId = `chart-${id || uniqueId.replace(/:/g, "")}`
52
52
 
53
+ // Recharts' ResponsiveContainer can't measure during SSR (no DOM), so it
54
+ // logs a "width(-1) and height(-1)" warning to the dev terminal on every
55
+ // request. Gating render until after mount keeps the chart a client-only
56
+ // tree — the wrapping div still SSRs and reserves layout, only the chart
57
+ // itself waits one tick to mount once the container is measurable.
58
+ const [mounted, setMounted] = React.useState(false)
59
+ React.useEffect(() => setMounted(true), [])
60
+
53
61
  return (
54
62
  <ChartContext.Provider value={{ config }}>
55
63
  <div
@@ -66,9 +74,11 @@ function ChartContainer({
66
74
  {...props}
67
75
  >
68
76
  <ChartStyle id={chartId} config={config} />
69
- <RechartsPrimitive.ResponsiveContainer width="100%" height="100%">
70
- {children}
71
- </RechartsPrimitive.ResponsiveContainer>
77
+ {mounted ? (
78
+ <RechartsPrimitive.ResponsiveContainer width="100%" height="100%">
79
+ {children}
80
+ </RechartsPrimitive.ResponsiveContainer>
81
+ ) : null}
72
82
  </div>
73
83
  </ChartContext.Provider>
74
84
  )
@@ -14,7 +14,7 @@ function Checkbox({
14
14
  <CheckboxPrimitive.Root
15
15
  data-slot="checkbox"
16
16
  className={cn(
17
- "peer size-8 shrink-0 rounded-[4px] border-2 border-muted-foreground/60 bg-white shadow-xs transition-shadow outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[state=checked]:border-primary data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:aria-invalid:ring-destructive/40",
17
+ "peer inline-flex size-8 shrink-0 items-center justify-center rounded-[4px] bg-muted leading-none outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:ring-2 aria-invalid:ring-destructive/60 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",
18
18
  className
19
19
  )}
20
20
  {...props}
@@ -27,7 +27,7 @@ function RadioGroupItem({
27
27
  <RadioGroupPrimitive.Item
28
28
  data-slot="radio-group-item"
29
29
  className={cn(
30
- "aspect-square size-9 shrink-0 rounded-full border-2 border-muted-foreground/60 bg-white text-primary shadow-xs transition-[color,box-shadow] outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 data-[state=checked]:bg-primary data-[state=checked]:border-primary",
30
+ "aspect-square size-9 shrink-0 rounded-full bg-muted text-primary outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:ring-2 aria-invalid:ring-destructive/60 data-[state=checked]:bg-primary",
31
31
  className
32
32
  )}
33
33
  {...props}
@@ -214,7 +214,12 @@ const Sidebar = React.forwardRef<
214
214
  >
215
215
  <div
216
216
  className={cn(
217
- "sticky top-0 hidden w-[var(--sidebar-width)] transition-[width,transform] duration-200 ease-linear md:flex",
217
+ // h-svh forces the sticky container to span the viewport even
218
+ // when the sidebar's contents are shorter than the screen.
219
+ // Without it, the bg-sidebar collapses to content height and the
220
+ // area below the footer reads as empty white space — looks like
221
+ // the sidebar "didn't fill" the panel.
222
+ "sticky top-0 hidden h-svh w-[var(--sidebar-width)] transition-[width,transform] duration-200 ease-linear md:flex",
218
223
  side === "left"
219
224
  ? "group-data-[collapsible=offcanvas]:-translate-x-full"
220
225
  : "right-0 group-data-[collapsible=offcanvas]:translate-x-full",
@@ -32,6 +32,24 @@ const Toaster = ({ ...props }: ToasterProps) => {
32
32
  "--border-radius": "var(--radius)",
33
33
  } as React.CSSProperties
34
34
  }
35
+ toastOptions={{
36
+ classNames: {
37
+ // border-foreground/10 + shadow-lg gives the toast a visible edge
38
+ // regardless of where --border lands on the fork's palette. Sonner's
39
+ // default leans on --border, which can be invisible on tonal forks.
40
+ toast:
41
+ "group toast group-[.toaster]:bg-popover group-[.toaster]:text-popover-foreground group-[.toaster]:border group-[.toaster]:border-foreground/10 group-[.toaster]:shadow-lg",
42
+ title: "text-base font-semibold",
43
+ // Sonner sets description opacity low by default — override with an
44
+ // explicit muted-foreground token so it reads at every brightness.
45
+ description:
46
+ "text-sm text-muted-foreground leading-relaxed group-[.toast]:text-muted-foreground",
47
+ actionButton:
48
+ "group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",
49
+ cancelButton:
50
+ "group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",
51
+ },
52
+ }}
35
53
  {...props}
36
54
  />
37
55
  )
@@ -30,7 +30,13 @@ function Switch({
30
30
  <SwitchPrimitive.Thumb
31
31
  data-slot="switch-thumb"
32
32
  className={cn(
33
- "pointer-events-none block rounded-full bg-white ring-0 transition-transform group-data-[size=default]/switch:size-8 group-data-[size=sm]/switch:size-6 data-[state=checked]:translate-x-[calc(100%-4px)] data-[state=unchecked]:translate-x-[2px]"
33
+ // bg-white works against the gray unchecked track in both modes,
34
+ // but fails against the near-white --primary track in dark-mode
35
+ // checked state. Switch to bg-primary-foreground when checked so
36
+ // the thumb always contrasts the track: near-white thumb on
37
+ // near-black track in light, near-black thumb on near-white
38
+ // track in dark.
39
+ "pointer-events-none block rounded-full bg-white data-[state=checked]:bg-primary-foreground ring-0 transition-[transform,background-color] duration-200 group-data-[size=default]/switch:size-8 group-data-[size=sm]/switch:size-6 data-[state=checked]:translate-x-[calc(100%-4px)] data-[state=unchecked]:translate-x-[2px]"
34
40
  )}
35
41
  />
36
42
  </SwitchPrimitive.Root>
@@ -64,7 +64,7 @@ function TabsTrigger({
64
64
  <TabsPrimitive.Trigger
65
65
  data-slot="tabs-trigger"
66
66
  className={cn(
67
- "inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-xs font-medium text-muted-foreground hover:text-foreground ring-offset-background transition-all focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-accent data-[state=active]:text-accent-foreground data-[state=active]:shadow-xs",
67
+ "inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-xs font-medium text-muted-foreground hover:text-foreground ring-offset-background transition-all focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-accent data-[state=active]:text-foreground data-[state=active]:shadow-xs",
68
68
  className
69
69
  )}
70
70
  {...props}
@@ -0,0 +1,64 @@
1
+ "use client";
2
+
3
+ import { useSyncExternalStore } from "react";
4
+ import { brand } from "@/brand.config";
5
+ import { storageKey } from "@behavioral-agentic-design-system/core/lib/storage";
6
+
7
+ const STORAGE_KEY = storageKey("brandMarkSvg");
8
+ const CLEAR_SENTINEL = "__NONE__";
9
+ const CHANGE_EVENT = "bads-brand-mark-change";
10
+
11
+ function readStoredSvg(): string | null {
12
+ if (typeof window === "undefined") {
13
+ return brand.logo?.svg ?? null;
14
+ }
15
+
16
+ const raw = window.localStorage.getItem(STORAGE_KEY);
17
+ if (raw === CLEAR_SENTINEL) return null;
18
+ if (raw !== null) return raw;
19
+ return brand.logo?.svg ?? null;
20
+ }
21
+
22
+ function subscribe(callback: () => void) {
23
+ if (typeof window === "undefined") {
24
+ return () => {};
25
+ }
26
+
27
+ const onStorage = (event: StorageEvent) => {
28
+ if (event.key === STORAGE_KEY) callback();
29
+ };
30
+
31
+ const onChange = () => callback();
32
+
33
+ window.addEventListener("storage", onStorage);
34
+ window.addEventListener(CHANGE_EVENT, onChange);
35
+
36
+ return () => {
37
+ window.removeEventListener("storage", onStorage);
38
+ window.removeEventListener(CHANGE_EVENT, onChange);
39
+ };
40
+ }
41
+
42
+ function setStoredSvg(value: string | null) {
43
+ if (typeof window === "undefined") return;
44
+
45
+ if (value === null) {
46
+ window.localStorage.setItem(STORAGE_KEY, CLEAR_SENTINEL);
47
+ } else {
48
+ window.localStorage.setItem(STORAGE_KEY, value);
49
+ }
50
+
51
+ window.dispatchEvent(new Event(CHANGE_EVENT));
52
+ }
53
+
54
+ export function useGlobalBrandMarkSvg() {
55
+ return useSyncExternalStore(subscribe, readStoredSvg, () => brand.logo?.svg ?? null);
56
+ }
57
+
58
+ export function setGlobalBrandMarkSvg(svg: string | null) {
59
+ setStoredSvg(svg);
60
+ }
61
+
62
+ export function clearGlobalBrandMarkSvg() {
63
+ setStoredSvg(null);
64
+ }
@@ -1,8 +1,11 @@
1
1
  "use client";
2
2
 
3
3
  import { useCallback, useEffect, useState } from "react";
4
+ import { brand } from "@/brand.config";
4
5
 
5
- export const MONO_FONT_OPTIONS = {
6
+ export type MonoFontOption = { label: string; stack: string };
7
+
8
+ const BASE_MONO_FONTS: Record<string, MonoFontOption> = {
6
9
  jetbrains: {
7
10
  label: "JetBrains Mono",
8
11
  stack: "var(--font-jetbrains), 'JetBrains Mono', ui-monospace, monospace",
@@ -19,9 +22,16 @@ export const MONO_FONT_OPTIONS = {
19
22
  label: "System Mono",
20
23
  stack: "ui-monospace, SFMono-Regular, Menlo, Consolas, 'Liberation Mono', monospace",
21
24
  },
22
- } as const;
25
+ };
26
+
27
+ // Brand fonts marked `kind: "mono"` come first.
28
+ const MONO_BRAND_FONTS = brand.fonts.filter((f) => f.kind === "mono");
29
+ export const MONO_FONT_OPTIONS: Record<string, MonoFontOption> = {
30
+ ...Object.fromEntries(MONO_BRAND_FONTS.map((f) => [f.id, { label: f.label, stack: f.stack }])),
31
+ ...BASE_MONO_FONTS,
32
+ };
23
33
 
24
- export type MonoFontKey = keyof typeof MONO_FONT_OPTIONS;
34
+ export type MonoFontKey = string;
25
35
 
26
36
  import { storageKey, readMigrated } from "@behavioral-agentic-design-system/core/lib/storage";
27
37
 
@@ -163,13 +163,77 @@ const PRIMARY_OVERRIDE_VARIABLES = [
163
163
  "--sidebar-primary",
164
164
  "--sidebar-primary-foreground",
165
165
  "--sidebar-ring",
166
- // Chart vars are NOT listed here. They derive from --primary in CSS
167
- // (see scripts/build-tokens.js → chartDerivationLight). The picker only
168
- // needs to set --primary; charts cascade automatically. This also keeps
169
- // per-chart user overrides (set inline via documentElement.style on
170
- // --chart-N) intact across primary changes.
166
+ "--chart-1",
167
+ "--chart-2",
168
+ "--chart-3",
169
+ "--chart-4",
170
+ "--chart-5",
171
171
  ];
172
172
 
173
+ // Chart ramp config — must stay in sync with tokens.json chart.lightnessSteps
174
+ // and chart.chromaSteps. Build-tokens.cjs reads the same values to emit the
175
+ // CSS derivation block, but we also write the ramp inline at runtime because
176
+ // Lightning CSS precomputes oklch(from var(--primary) ...) into a static
177
+ // lab() fallback inside @supports — which wins over the relative-color rule
178
+ // and freezes the chart palette to the build-time --primary. Writing inline
179
+ // bypasses the bundler and lets the browser resolve the relative color at
180
+ // runtime against whatever --primary the brand picker just set.
181
+ const CHART_RAMP = [
182
+ { l: "0.58", c: "1.00" },
183
+ { l: "0.50", c: "0.95" },
184
+ { l: "0.42", c: "0.80" },
185
+ { l: "0.34", c: "0.60" },
186
+ { l: "0.27", c: "0.40" },
187
+ ] as const;
188
+ const CHART_RAMP_DARK = [
189
+ { l: "0.78", c: "1.00" },
190
+ { l: "0.70", c: "0.95" },
191
+ { l: "0.62", c: "0.80" },
192
+ { l: "0.56", c: "0.60" },
193
+ { l: "0.52", c: "0.40" },
194
+ ] as const;
195
+
196
+ // Variables managed elsewhere (Customize tab token swatch picker) that we
197
+ // should NOT overwrite on a brand change. Read fresh from localStorage so
198
+ // the brand picker honors them without needing a hook subscription.
199
+ function readUserTokenOverrides(): Set<string> {
200
+ if (typeof window === "undefined") return new Set();
201
+ try {
202
+ const raw =
203
+ window.localStorage.getItem(storageKey("tokenOverrides")) ??
204
+ window.localStorage.getItem("tokenOverrides");
205
+ if (!raw) return new Set();
206
+ const parsed = JSON.parse(raw) as Record<string, string>;
207
+ return new Set(Object.keys(parsed ?? {}));
208
+ } catch {
209
+ return new Set();
210
+ }
211
+ }
212
+
213
+ function chartRampValue(index: 0 | 1 | 2 | 3 | 4, dark: boolean): string {
214
+ const step = (dark ? CHART_RAMP_DARK : CHART_RAMP)[index];
215
+ const c = step.c === "1.00" ? "c" : `calc(c * ${step.c})`;
216
+ return `oklch(from var(--primary) ${step.l} ${c} h)`;
217
+ }
218
+
219
+ /**
220
+ * Re-apply the chart ramp inline based on the current --primary and dark
221
+ * mode. Use after clearing a chart-N user override so the cascade doesn't
222
+ * fall through to the Lightning CSS lab() precomputation. Skips any chart
223
+ * variable still listed in user token overrides.
224
+ */
225
+ export function reapplyChartRamp() {
226
+ if (typeof document === "undefined") return;
227
+ const root = document.documentElement.style;
228
+ const userOverrides = readUserTokenOverrides();
229
+ const isDark = document.documentElement.classList.contains("dark");
230
+ for (let i = 0; i < 5; i++) {
231
+ const varName = `--chart-${i + 1}`;
232
+ if (userOverrides.has(varName)) continue;
233
+ root.setProperty(varName, chartRampValue(i as 0 | 1 | 2 | 3 | 4, isDark));
234
+ }
235
+ }
236
+
173
237
  function buildCustom(hex: string, label?: string): PrimaryColorOption {
174
238
  const requested = normalizeHex(hex);
175
239
  // No more contrast-adjusting. Apply the color as-is and surface a WCAG
@@ -236,9 +300,19 @@ function applyColor(opt: PrimaryColorOption) {
236
300
  root.setProperty("--sidebar-primary", opt.primary);
237
301
  root.setProperty("--sidebar-primary-foreground", opt.primaryForeground);
238
302
  root.setProperty("--sidebar-ring", opt.primary);
239
- // Charts derive from --primary in CSS (see styles/globals.css chart block).
240
- // No JS overrides here — that way per-chart user customizations (set inline
241
- // on documentElement.style) survive every primary change.
303
+
304
+ // Apply the chart ramp inline. This duplicates the CSS derivation but is
305
+ // necessary because Lightning CSS bakes the CSS rule into a static lab()
306
+ // fallback that wins over the relative-color form. Inline values escape
307
+ // that precomputation. Per-chart user overrides (token swatch picker) are
308
+ // preserved by reading the tokenOverrides map and skipping those keys.
309
+ const userOverrides = readUserTokenOverrides();
310
+ const isDark = document.documentElement.classList.contains("dark");
311
+ for (let i = 0; i < 5; i++) {
312
+ const varName = `--chart-${i + 1}`;
313
+ if (userOverrides.has(varName)) continue;
314
+ root.setProperty(varName, chartRampValue(i as 0 | 1 | 2 | 3 | 4, isDark));
315
+ }
242
316
  }
243
317
 
244
318
  function applySelectedColor(color: string, options: Record<string, PrimaryColorOption>) {
@@ -321,6 +395,18 @@ function bootstrap() {
321
395
  applySelectedColor(next, merged);
322
396
  }
323
397
  });
398
+
399
+ // Re-apply the chart ramp when dark mode toggles. The ramp values differ
400
+ // between light (L=0.58 → 0.27) and dark (L=0.78 → 0.52) because the AAA
401
+ // contrast floor against the card background is mode-dependent.
402
+ const darkObserver = new MutationObserver(() => {
403
+ const merged = { ...BUILTIN_PRIMARY_COLORS, ...snapshot.customs };
404
+ applySelectedColor(snapshot.color, merged);
405
+ });
406
+ darkObserver.observe(document.documentElement, {
407
+ attributes: true,
408
+ attributeFilter: ["class"],
409
+ });
324
410
  }
325
411
 
326
412
  /**
@@ -388,6 +474,43 @@ export function useGlobalPrimaryColor() {
388
474
  [],
389
475
  );
390
476
 
477
+ /**
478
+ * Library-only sibling of addCustom. Adds the color to the brand palette
479
+ * so it's available to every swatch picker, but does NOT make it the
480
+ * active primary or apply any brand variables. Used by the per-token
481
+ * swatch popover ("+" tile) where the designer wants a one-off color
482
+ * scoped to a single token without taking over the global theme.
483
+ *
484
+ * Dedup matches addCustom: if the hex is already in the palette, returns
485
+ * the existing id without changing selection state.
486
+ */
487
+ const addCustomSilent = useCallback(
488
+ (hex: string, label?: string): string | null => {
489
+ if (!isValidHex(hex)) return null;
490
+ const normalized = normalizeHex(hex);
491
+
492
+ const merged: Record<string, PrimaryColorOption> = {
493
+ ...BUILTIN_PRIMARY_COLORS,
494
+ ...snapshot.customs,
495
+ };
496
+ for (const [existingId, opt] of Object.entries(merged)) {
497
+ if (normalizeHex(opt.primary) === normalized) {
498
+ return existingId;
499
+ }
500
+ }
501
+
502
+ const id = `custom-${normalized.slice(1).toLowerCase()}`;
503
+ const opt = buildCustom(normalized, label);
504
+ const customs = { ...snapshot.customs, [id]: opt };
505
+ commit({ ...snapshot, customs });
506
+ if (typeof window !== "undefined") {
507
+ window.localStorage.setItem(CUSTOMS_KEY, JSON.stringify(customs));
508
+ }
509
+ return id;
510
+ },
511
+ [],
512
+ );
513
+
391
514
  const removeCustom = useCallback(
392
515
  (id: string) => {
393
516
  if (!(id in snapshot.customs)) return;
@@ -535,15 +658,29 @@ export function useGlobalPrimaryColor() {
535
658
  [],
536
659
  );
537
660
 
661
+ const resetToDefaults = useCallback(() => {
662
+ if (typeof window === "undefined") return;
663
+ window.localStorage.removeItem(COLOR_KEY);
664
+ window.localStorage.removeItem(CUSTOMS_KEY);
665
+ commit({ customs: {}, color: DEFAULT });
666
+ applySelectedColor(DEFAULT, BUILTIN_PRIMARY_COLORS);
667
+ window.location.reload();
668
+ }, []);
669
+
670
+ const isCustomized = state.color !== DEFAULT || Object.keys(state.customs).length > 0;
671
+
538
672
  return {
539
673
  color: state.color,
540
674
  setColor,
541
675
  addCustom,
676
+ addCustomSilent,
542
677
  removeCustom,
543
678
  renameCustom,
544
679
  pinCustom,
545
680
  removeBuiltin,
546
681
  renameBuiltin,
682
+ resetToDefaults,
683
+ isCustomized,
547
684
  options,
548
685
  customs: state.customs,
549
686
  builtins: BUILTIN_PRIMARY_COLORS,
@@ -32,9 +32,11 @@ const BASE_SANS_FONTS: Record<string, SansFontOption> = {
32
32
  };
33
33
 
34
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.
35
+ // client's font is the default and most prominent option. We filter on
36
+ // `kind === "sans"` (default when omitted, for backward-compat).
37
+ const SANS_BRAND_FONTS = brand.fonts.filter((f) => (f.kind ?? "sans") === "sans");
36
38
  export const SANS_FONT_OPTIONS: Record<string, SansFontOption> = {
37
- ...Object.fromEntries(brand.fonts.map((f) => [f.id, { label: f.label, stack: f.stack }])),
39
+ ...Object.fromEntries(SANS_BRAND_FONTS.map((f) => [f.id, { label: f.label, stack: f.stack }])),
38
40
  ...BASE_SANS_FONTS,
39
41
  };
40
42
 
@@ -44,7 +46,7 @@ import { storageKey, readMigrated } from "@behavioral-agentic-design-system/core
44
46
 
45
47
  const STORAGE_KEY = storageKey("sansFont");
46
48
  // First brand font (if any) wins as the default; otherwise Hyperlegible.
47
- const DEFAULT: SansFontKey = brand.fonts[0]?.id ?? "hyperlegible";
49
+ const DEFAULT: SansFontKey = SANS_BRAND_FONTS[0]?.id ?? "hyperlegible";
48
50
 
49
51
  function isValidKey(value: string | null): value is SansFontKey {
50
52
  return !!value && value in SANS_FONT_OPTIONS;
@@ -1,8 +1,11 @@
1
1
  "use client";
2
2
 
3
3
  import { useCallback, useEffect, useState } from "react";
4
+ import { brand } from "@/brand.config";
4
5
 
5
- export const SERIF_FONT_OPTIONS = {
6
+ export type SerifFontOption = { label: string; stack: string };
7
+
8
+ const BASE_SERIF_FONTS: Record<string, SerifFontOption> = {
6
9
  georgia: {
7
10
  label: "Georgia",
8
11
  stack: "Georgia, ui-serif, serif",
@@ -19,14 +22,21 @@ export const SERIF_FONT_OPTIONS = {
19
22
  label: "System Serif",
20
23
  stack: "ui-serif, Georgia, Cambria, 'Times New Roman', Times, serif",
21
24
  },
22
- } as const;
25
+ };
26
+
27
+ // Brand fonts marked `kind: "serif"` come first.
28
+ const SERIF_BRAND_FONTS = brand.fonts.filter((f) => f.kind === "serif");
29
+ export const SERIF_FONT_OPTIONS: Record<string, SerifFontOption> = {
30
+ ...Object.fromEntries(SERIF_BRAND_FONTS.map((f) => [f.id, { label: f.label, stack: f.stack }])),
31
+ ...BASE_SERIF_FONTS,
32
+ };
23
33
 
24
- export type SerifFontKey = keyof typeof SERIF_FONT_OPTIONS;
34
+ export type SerifFontKey = string;
25
35
 
26
36
  import { storageKey, readMigrated } from "@behavioral-agentic-design-system/core/lib/storage";
27
37
 
28
38
  const STORAGE_KEY = storageKey("serifFont");
29
- const DEFAULT: SerifFontKey = "georgia";
39
+ const DEFAULT: SerifFontKey = "season-serif";
30
40
 
31
41
  function isValidKey(value: string | null): value is SerifFontKey {
32
42
  return !!value && value in SERIF_FONT_OPTIONS;
@@ -4,13 +4,13 @@
4
4
  *
5
5
  * Why this exists
6
6
  * ----------------
7
- * Before 0.4.0, every hook had `const STORAGE_KEY = "BADS.sansFont"` (and
7
+ * Before 0.4.0, every hook had `const STORAGE_KEY = "SWIMTOPIA-AGENTIC-DESIGN-SYSTEM.sansFont"` (and
8
8
  * similar) inlined. `scripts/rename.mjs` rewrote those strings at fork time
9
9
  * so a renamed fork stored data under "<SLUG_UPPER>.sansFont" instead.
10
10
  *
11
11
  * Once @core started shipping the hooks via npm (0.3.0), rename.mjs could no
12
12
  * longer reach the hook source — it lives in node_modules, not the consumer
13
- * tree. Forks ended up reading "BADS.sansFont" from localStorage even though
13
+ * tree. Forks ended up reading "SWIMTOPIA-AGENTIC-DESIGN-SYSTEM.sansFont" from localStorage even though
14
14
  * their saved customizations were under "<SLUG_UPPER>.sansFont", silently
15
15
  * losing every Customize-tab edit they had made.
16
16
  *
@@ -41,6 +41,35 @@ export function storageKey(suffix: string): string {
41
41
  return `${getPrefix()}.${suffix}`;
42
42
  }
43
43
 
44
+ /**
45
+ * Wipe every customization key under the runtime prefix (e.g. "BADS.*",
46
+ * "CLAP.*"). The Customize tab's "Reset all" button uses this so a fresh
47
+ * hook adding a new storage key doesn't need to be remembered in a
48
+ * hand-maintained list — anything written via `storageKey()` auto-resets.
49
+ *
50
+ * Pass `keep` to preserve specific suffixes (not full keys). Default keeps
51
+ * the light/dark `theme` key because that's a UI preference, not a
52
+ * tokens.json customization — wiping it on "Reset all" would feel wrong.
53
+ *
54
+ * Returns the count of removed keys, mostly for tests/debugging.
55
+ */
56
+ export function clearAllCustomization(opts: { keep?: string[] } = {}): number {
57
+ if (typeof window === "undefined") return 0;
58
+ const prefix = `${getPrefix()}.`;
59
+ const keepKeys = new Set((opts.keep ?? ["theme"]).map((s) => storageKey(s)));
60
+ const toRemove: string[] = [];
61
+ for (let i = 0; i < window.localStorage.length; i++) {
62
+ const key = window.localStorage.key(i);
63
+ if (key && key.startsWith(prefix) && !keepKeys.has(key)) {
64
+ toRemove.push(key);
65
+ }
66
+ }
67
+ for (const key of toRemove) {
68
+ window.localStorage.removeItem(key);
69
+ }
70
+ return toRemove.length;
71
+ }
72
+
44
73
  const MIGRATED = new Set<string>();
45
74
 
46
75
  /**