@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
@@ -1,7 +1,7 @@
1
1
  "use client";
2
2
 
3
- import { useState } from "react";
4
- import { Check, Plus, Pencil, Trash2, MoreHorizontal } from "lucide-react";
3
+ import { useState, useMemo, createContext, useContext } from "react";
4
+ import { Check, Plus, Pencil, Trash2, MoreHorizontal, AlertCircle, RotateCcw } from "lucide-react";
5
5
  import { HexColorPicker } from "react-colorful";
6
6
  import { ScrollArea } from "@behavioral-agentic-design-system/core/components/ui/scroll-area";
7
7
  import { Button } from "@behavioral-agentic-design-system/core/components/ui/button";
@@ -19,11 +19,14 @@ import {
19
19
  } from "@behavioral-agentic-design-system/core/components/ui/dropdown-menu";
20
20
  import {
21
21
  useGlobalPrimaryColor,
22
+ reapplyChartRamp,
22
23
  type PrimaryColorKey,
23
24
  type PrimaryColorOption,
24
25
  type WcagGrade,
25
26
  } from "@behavioral-agentic-design-system/core/hooks/use-global-primary-color";
27
+ import { useTokenOverrides } from "@behavioral-agentic-design-system/core/hooks/use-token-overrides";
26
28
  import { ThemeIO } from "@behavioral-agentic-design-system/core/components/customize/theme-io";
29
+ import { BrandMarkSection } from "@behavioral-agentic-design-system/core/components/customize/brand-mark-section";
27
30
  import { DesignControlsPanel } from "@behavioral-agentic-design-system/core/components/customize/design-controls";
28
31
  import {
29
32
  SansFontPicker,
@@ -35,6 +38,23 @@ import { LetterSpacingPanel } from "@behavioral-agentic-design-system/core/compo
35
38
  import { SaveBar } from "@behavioral-agentic-design-system/core/components/customize/save-bar";
36
39
  import { nameFromHex } from "@behavioral-agentic-design-system/core/lib/color-name";
37
40
 
41
+ type TokenSwatchPickerCtx = {
42
+ options: Record<string, PrimaryColorOption>;
43
+ overrides: Record<string, string>;
44
+ setToken: (variable: string, value: string) => void;
45
+ resetToken: (variable: string) => void;
46
+ /**
47
+ * Add a new color to the brand palette WITHOUT making it the active
48
+ * primary. The "+" tile inside ColorSwatch's popover uses this so a
49
+ * one-off color picked for a single token (e.g. --background) lands in
50
+ * the brand list for reuse but never hijacks --primary, --ring, --accent-
51
+ * foreground, etc. Token-scoped picks stay token-scoped.
52
+ */
53
+ addCustomSilent: (hex: string, label?: string) => string | null;
54
+ };
55
+
56
+ const TokenSwatchPicker = createContext<TokenSwatchPickerCtx | null>(null);
57
+
38
58
  function ColorSwatch({
39
59
  name,
40
60
  className,
@@ -46,20 +66,217 @@ function ColorSwatch({
46
66
  variable: string;
47
67
  textClassName?: string;
48
68
  }) {
49
- return (
50
- <div>
51
- <div className={`h-20 rounded-lg border ${className} flex items-end p-2.5`}>
52
- <span className={`text-xs font-medium truncate ${textClassName ?? ""}`}>{name}</span>
69
+ const ctx = useContext(TokenSwatchPicker);
70
+ // Defensive fallback — if mounted without provider, still render the swatch
71
+ // so the section degrades gracefully instead of throwing in storybook etc.
72
+ if (!ctx) {
73
+ return (
74
+ <div>
75
+ <div className={`h-20 rounded-lg border ${className} flex items-end p-2.5`}>
76
+ <span className={`text-xs font-medium truncate ${textClassName ?? ""}`}>{name}</span>
77
+ </div>
78
+ <p className="text-xs text-muted-foreground font-mono mt-1.5 truncate">{variable}</p>
53
79
  </div>
54
- <p className="text-xs text-muted-foreground font-mono mt-1.5 truncate">{variable}</p>
55
- </div>
80
+ );
81
+ }
82
+ const { options, overrides, setToken, resetToken, addCustomSilent } = ctx;
83
+ const isOverridden = variable in overrides;
84
+ const currentHex = overrides[variable]?.toUpperCase();
85
+ const entries = Object.entries(options);
86
+
87
+ // Inline "+ add color" state. When showAdd is true the popover swaps the
88
+ // brand-color grid for a HexColorPicker so designers can introduce a new
89
+ // brand color without leaving the per-token swatch picker. Save pushes
90
+ // the color to the brand palette (via addCustomSilent — does NOT change
91
+ // --primary or any brand-derived var) AND applies it ONLY to the current
92
+ // token via setToken. Token-scoped picks stay token-scoped.
93
+ const [showAdd, setShowAdd] = useState(false);
94
+ const [newHex, setNewHex] = useState("#1F1F1F");
95
+ const [newLabel, setNewLabel] = useState("");
96
+ const [addError, setAddError] = useState<string | null>(null);
97
+
98
+ const resetAddState = () => {
99
+ setShowAdd(false);
100
+ setNewHex("#1F1F1F");
101
+ setNewLabel("");
102
+ setAddError(null);
103
+ };
104
+
105
+ const handleAddAndApply = () => {
106
+ const value = newHex.trim();
107
+ if (!isValidHex(value)) {
108
+ setAddError("Enter a valid hex like #1F1F1F");
109
+ return;
110
+ }
111
+ const id = addCustomSilent(value, newLabel.trim() || undefined);
112
+ if (!id) {
113
+ setAddError("Could not add color");
114
+ return;
115
+ }
116
+ setToken(variable, value.toUpperCase());
117
+ resetAddState();
118
+ };
119
+
120
+ return (
121
+ <Popover>
122
+ <PopoverTrigger asChild>
123
+ <button
124
+ type="button"
125
+ aria-label={`Edit ${variable}`}
126
+ className="group block w-full text-left rounded-lg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
127
+ >
128
+ <div
129
+ className={`h-20 rounded-lg border ${className} flex items-end p-2.5 transition-all group-hover:border-foreground/40 ${
130
+ isOverridden ? "ring-2 ring-primary/30" : ""
131
+ }`}
132
+ >
133
+ <span className={`text-xs font-medium truncate ${textClassName ?? ""}`}>{name}</span>
134
+ </div>
135
+ <p className="text-xs text-muted-foreground font-mono mt-1.5 truncate">{variable}</p>
136
+ </button>
137
+ </PopoverTrigger>
138
+ <PopoverContent align="start" className="w-72 p-3">
139
+ <div className="flex items-center justify-between gap-2 mb-3">
140
+ <p className="text-xs font-mono text-muted-foreground truncate">{variable}</p>
141
+ {!showAdd && isOverridden && (
142
+ <button
143
+ type="button"
144
+ onClick={() => {
145
+ resetToken(variable);
146
+ // Chart tokens need an explicit re-apply after reset because
147
+ // Lightning CSS bakes a static lab() fallback that wins over
148
+ // the relative-color CSS rule. reapplyChartRamp writes the
149
+ // brand-derived value back inline so the cascade doesn't
150
+ // fall through to the frozen build-time value.
151
+ if (variable.startsWith("--chart-")) reapplyChartRamp();
152
+ }}
153
+ className="inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors"
154
+ >
155
+ <RotateCcw className="h-3 w-3" strokeWidth={1.5} />
156
+ Reset
157
+ </button>
158
+ )}
159
+ {showAdd && (
160
+ <button
161
+ type="button"
162
+ onClick={resetAddState}
163
+ className="text-xs text-muted-foreground hover:text-foreground transition-colors"
164
+ >
165
+ Back
166
+ </button>
167
+ )}
168
+ </div>
169
+
170
+ {showAdd ? (
171
+ <div className="flex flex-col gap-3">
172
+ <HexColorPicker
173
+ style={{ width: "100%", height: "180px" }}
174
+ color={isValidHex(newHex) ? newHex : "#1F1F1F"}
175
+ onChange={(c) => {
176
+ setNewHex(c.toUpperCase());
177
+ if (addError) setAddError(null);
178
+ }}
179
+ />
180
+ <Input
181
+ value={newLabel}
182
+ onChange={(e) => setNewLabel(e.target.value)}
183
+ placeholder={`Label — auto: ${isValidHex(newHex) ? nameFromHex(newHex) : "—"}`}
184
+ className="h-9"
185
+ />
186
+ <div className="flex items-center gap-2">
187
+ <Input
188
+ value={newHex}
189
+ onChange={(e) => {
190
+ setNewHex(e.target.value);
191
+ if (addError) setAddError(null);
192
+ }}
193
+ onKeyDown={(e) => {
194
+ if (e.key === "Enter") handleAddAndApply();
195
+ }}
196
+ placeholder="#1F1F1F"
197
+ className="h-9 flex-1 min-w-0 font-mono text-sm"
198
+ />
199
+ <Button size="sm" onClick={handleAddAndApply}>
200
+ Add
201
+ </Button>
202
+ </div>
203
+ {addError && <span className="text-xs text-destructive">{addError}</span>}
204
+ <p className="text-xs text-muted-foreground">
205
+ Saved to your brand colors and applied here.
206
+ </p>
207
+ </div>
208
+ ) : (
209
+ <div className="grid grid-cols-4 gap-2">
210
+ {entries.map(([key, opt]) => {
211
+ const swatch = opt.swatch ?? opt.primary;
212
+ const isActive =
213
+ currentHex !== undefined &&
214
+ currentHex === (swatch ?? "").toUpperCase();
215
+ return (
216
+ <button
217
+ key={key}
218
+ type="button"
219
+ onClick={() => setToken(variable, swatch)}
220
+ title={`${opt.label} · ${swatch}`}
221
+ className={`group/sw flex flex-col items-center gap-1.5 rounded-md border p-2 transition-all ${
222
+ isActive
223
+ ? "border-primary ring-2 ring-primary/30"
224
+ : "border-border hover:border-foreground/40"
225
+ }`}
226
+ >
227
+ <div
228
+ className="relative h-7 w-7 rounded-full border border-border/50"
229
+ style={{ backgroundColor: swatch }}
230
+ >
231
+ {isActive && (
232
+ <Check
233
+ className="absolute inset-0 m-auto h-3.5 w-3.5"
234
+ style={{ color: opt.swatchForeground ?? opt.primaryForeground }}
235
+ strokeWidth={1.5}
236
+ />
237
+ )}
238
+ </div>
239
+ <span className="text-xs leading-tight truncate w-full text-center">
240
+ {opt.label}
241
+ </span>
242
+ </button>
243
+ );
244
+ })}
245
+ <button
246
+ type="button"
247
+ onClick={() => setShowAdd(true)}
248
+ title="Add a new brand color and apply it here"
249
+ className="group/sw flex flex-col items-center gap-1.5 rounded-md border border-dashed border-border p-2 transition-all hover:border-foreground/40"
250
+ >
251
+ <div className="flex h-7 w-7 items-center justify-center rounded-full border border-dashed border-border/60 text-muted-foreground group-hover/sw:text-foreground">
252
+ <Plus className="h-3.5 w-3.5" strokeWidth={1.5} />
253
+ </div>
254
+ <span className="text-xs leading-tight text-muted-foreground group-hover/sw:text-foreground truncate w-full text-center">
255
+ Add
256
+ </span>
257
+ </button>
258
+ </div>
259
+ )}
260
+ </PopoverContent>
261
+ </Popover>
56
262
  );
57
263
  }
58
264
 
59
- function ColorSection({ title, children }: { title: string; children: React.ReactNode }) {
265
+ function ColorSection({
266
+ title,
267
+ action,
268
+ children,
269
+ }: {
270
+ title: string;
271
+ action?: React.ReactNode;
272
+ children: React.ReactNode;
273
+ }) {
60
274
  return (
61
275
  <div>
62
- <h4 className="text-base font-semibold mb-4">{title}</h4>
276
+ <div className="flex items-center justify-between mb-4">
277
+ <h4 className="text-base font-semibold">{title}</h4>
278
+ {action}
279
+ </div>
63
280
  <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3">
64
281
  {children}
65
282
  </div>
@@ -67,6 +284,32 @@ function ColorSection({ title, children }: { title: string; children: React.Reac
67
284
  );
68
285
  }
69
286
 
287
+ function ResetChartTokensButton() {
288
+ const ctx = useContext(TokenSwatchPicker);
289
+ if (!ctx) return null;
290
+ const overridden = ["--chart-1", "--chart-2", "--chart-3", "--chart-4", "--chart-5"].filter(
291
+ (v) => v in ctx.overrides,
292
+ );
293
+ if (overridden.length === 0) return null;
294
+ return (
295
+ <Button
296
+ variant="outline"
297
+ size="sm"
298
+ onClick={() => {
299
+ overridden.forEach((v) => ctx.resetToken(v));
300
+ // resetToken removes the inline value. Without this, the cascade
301
+ // would fall through to Lightning CSS's precomputed lab() rule
302
+ // (frozen at build-time --primary) instead of the brand ramp.
303
+ reapplyChartRamp();
304
+ }}
305
+ className="text-xs gap-1.5"
306
+ >
307
+ <RotateCcw className="h-3 w-3" strokeWidth={1.5} />
308
+ Reset {overridden.length === 5 ? "all" : `${overridden.length}`}
309
+ </Button>
310
+ );
311
+ }
312
+
70
313
  function isValidHex(v: string) {
71
314
  return /^#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})$/.test(v.trim());
72
315
  }
@@ -241,6 +484,18 @@ function BrandColorCard({
241
484
  // trigger is a sibling of the card button, so it needs the group on a
242
485
  // shared ancestor for `group-hover:opacity-100` to fire on card hover.
243
486
  <div className="group relative">
487
+ {opt.grade !== "AAA" && (
488
+ <span
489
+ className="pointer-events-none absolute -top-2 -left-2 z-10 inline-flex h-7 w-7 items-center justify-center rounded-full bg-amber-50 dark:bg-amber-950 border border-amber-300 dark:border-amber-700 shadow-sm"
490
+ title={`Below WCAG AAA — current ${opt.contrast}:1 (${opt.grade}), required 7:1`}
491
+ aria-label={`${opt.label} is below WCAG AAA contrast`}
492
+ >
493
+ <AlertCircle
494
+ className="h-4 w-4 text-amber-600 dark:text-amber-500"
495
+ strokeWidth={1.5}
496
+ />
497
+ </span>
498
+ )}
244
499
  <button
245
500
  type="button"
246
501
  onClick={onSelect}
@@ -339,9 +594,6 @@ function BrandColorCard({
339
594
  }
340
595
 
341
596
  function PrimaryColorPicker() {
342
- // Note: the hook still exports pinCustom but the Save Bar's Save-to-
343
- // tokens.json flow handles "promote custom to built-in" automatically,
344
- // so we don't surface a separate Pin action here.
345
597
  const {
346
598
  color,
347
599
  setColor,
@@ -352,27 +604,70 @@ function PrimaryColorPicker() {
352
604
  renameCustom,
353
605
  removeBuiltin,
354
606
  renameBuiltin,
607
+ resetToDefaults,
608
+ isCustomized,
355
609
  } = useGlobalPrimaryColor();
356
610
  const keys = Object.keys(options) as PrimaryColorKey[];
611
+ const activeOption = options[color];
612
+
613
+ const hasContrast = useMemo(() => {
614
+ return activeOption && activeOption.grade !== "Fail";
615
+ }, [activeOption]);
616
+
617
+ const contrastWarning = useMemo(() => {
618
+ if (!activeOption || activeOption.grade === "AAA") return null;
619
+ return {
620
+ ratio: activeOption.contrast,
621
+ current: activeOption.grade,
622
+ };
623
+ }, [activeOption]);
624
+
357
625
  return (
358
626
  <div>
359
- <h2 className="text-2xl font-semibold tracking-tight mb-2">Brand Color</h2>
627
+ <div className="flex items-center justify-between mb-2">
628
+ <h2 className="text-2xl font-semibold tracking-tight">Brand Color</h2>
629
+ {isCustomized && (
630
+ <Button
631
+ variant="outline"
632
+ size="sm"
633
+ onClick={resetToDefaults}
634
+ className="text-xs"
635
+ >
636
+ Reset to Defaults
637
+ </Button>
638
+ )}
639
+ </div>
640
+
360
641
  <p className="text-sm text-muted-foreground mb-6 max-w-prose">
361
- Switch the primary brand color across every preview screen. Add a one-off with{" "}
362
- <span className="font-medium text-foreground">+ Add color</span> — it stays in
363
- your browser only. Hit <span className="font-medium text-foreground">Save to
364
- tokens.json</span> at the bottom and the active color is promoted to a built-in
365
- in <code className="font-mono text-xs">brand-colors.json</code> for everyone on
366
- the repo. Built-ins can be renamed or deleted directly from each card.
642
+ Change the primary brand color used across every preview.{" "}
643
+ <span className="font-medium text-foreground">+ Add color</span> lets you try a
644
+ one-off in your browser. Hit{" "}
645
+ <span className="font-medium text-foreground">Save</span> to make it a built-in
646
+ for the whole team. Rename or delete built-ins from each card.
367
647
  </p>
648
+
649
+ {contrastWarning && (
650
+ <div className="flex items-start gap-3 p-3 mb-4 rounded-lg bg-amber-50 dark:bg-amber-950/30 border border-amber-200 dark:border-amber-900/50">
651
+ <AlertCircle className="h-4 w-4 text-amber-900 dark:text-amber-100 flex-shrink-0 mt-0.5" strokeWidth={1.5} />
652
+ <div className="flex-1 text-sm text-amber-900 dark:text-amber-100">
653
+ <p className="font-medium">
654
+ Warning: {activeOption?.label ?? "This color"} doesn't meet WCAG AAA contrast
655
+ </p>
656
+ <p className="text-xs mt-1">
657
+ Current: {contrastWarning.ratio}:1 (grade: {contrastWarning.current}) · Required: 7:1 (AAA)
658
+ </p>
659
+ <p className="text-xs mt-2">
660
+ You can keep this color anyway. The warning is informational only.
661
+ </p>
662
+ </div>
663
+ </div>
664
+ )}
665
+
368
666
  <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-4 xl:grid-cols-8 gap-3">
369
667
  {keys.map((key) => {
370
668
  const opt = options[key];
371
669
  const isCustom = key in customs;
372
670
  const isNeutral = key === "neutral";
373
- // Customs: local rename / delete (no Pin — Save Bar handles that).
374
- // Built-ins (except shadcn neutral): server-backed rename / delete.
375
- // Neutral: read-only — it's the system fallback.
376
671
  const actions: BrandCardActions = isCustom
377
672
  ? {
378
673
  rename: (label) => renameCustom(key, label),
@@ -402,10 +697,19 @@ function PrimaryColorPicker() {
402
697
  }
403
698
 
404
699
  function ColorPalette() {
700
+ const { options, addCustomSilent } = useGlobalPrimaryColor();
701
+ const { overrides, updateOverride, remove } = useTokenOverrides();
702
+ const swatchCtx = useMemo<TokenSwatchPickerCtx>(
703
+ () => ({ options, overrides, setToken: updateOverride, resetToken: remove, addCustomSilent }),
704
+ [options, overrides, updateOverride, remove, addCustomSilent],
705
+ );
706
+
405
707
  return (
708
+ <TokenSwatchPicker.Provider value={swatchCtx}>
406
709
  <div className="p-8 pb-32 max-w-7xl mx-auto space-y-20">
407
710
  <ThemeIO />
408
711
  <PrimaryColorPicker />
712
+ <BrandMarkSection />
409
713
 
410
714
  <section>
411
715
  <h2 className="text-2xl font-semibold tracking-tight mb-2">Typography</h2>
@@ -465,9 +769,9 @@ function ColorPalette() {
465
769
  <ColorSwatch name="Destructive Foreground" className="bg-destructive-foreground text-destructive" variable="--destructive-foreground" />
466
770
  </ColorSection>
467
771
 
468
- <ColorSection title="Charts">
469
- <ColorSwatch name="Chart 1" className="bg-chart-1" textClassName="text-neutral-900" variable="--chart-1" />
470
- <ColorSwatch name="Chart 2" className="bg-chart-2" textClassName="text-neutral-900" variable="--chart-2" />
772
+ <ColorSection title="Charts" action={<ResetChartTokensButton />}>
773
+ <ColorSwatch name="Chart 1" className="bg-chart-1" textClassName="text-white" variable="--chart-1" />
774
+ <ColorSwatch name="Chart 2" className="bg-chart-2" textClassName="text-white" variable="--chart-2" />
471
775
  <ColorSwatch name="Chart 3" className="bg-chart-3" textClassName="text-white" variable="--chart-3" />
472
776
  <ColorSwatch name="Chart 4" className="bg-chart-4" textClassName="text-white" variable="--chart-4" />
473
777
  <ColorSwatch name="Chart 5" className="bg-chart-5" textClassName="text-white" variable="--chart-5" />
@@ -488,6 +792,7 @@ function ColorPalette() {
488
792
 
489
793
  <SaveBar />
490
794
  </div>
795
+ </TokenSwatchPicker.Provider>
491
796
  );
492
797
  }
493
798
 
@@ -0,0 +1,92 @@
1
+ "use client";
2
+
3
+ import { useEffect, useState } from "react";
4
+
5
+ /**
6
+ * Tiny fixed-position chip pinned to the bottom-right corner in development.
7
+ * Renders the app name, current port, and a "mounted X ago" relative time
8
+ * stamp so the tab clearly identifies itself. Designed for the common
9
+ * confusion case: six Next dev servers running across different repos all
10
+ * fighting over ports, and you can't tell which tab is which.
11
+ *
12
+ * Auto-hides in production (`process.env.NODE_ENV === 'production'`). Mounts
13
+ * client-side so it can read `window.location.port` and the live "ago"
14
+ * counter. Click-through is preserved everywhere except the chip itself.
15
+ *
16
+ * Usage in a root layout:
17
+ *
18
+ * import { DevIdentityBadge } from "@behavioral-agentic-design-system/core/components/dev-identity-badge";
19
+ *
20
+ * export default function RootLayout({ children }) {
21
+ * return (
22
+ * <html>
23
+ * <body>
24
+ * {children}
25
+ * <DevIdentityBadge name="swimtopia-prototypes" />
26
+ * </body>
27
+ * </html>
28
+ * );
29
+ * }
30
+ *
31
+ * The `name` prop is the only required input. If unset, the badge shows the
32
+ * port + relative time only — still useful, just less specific.
33
+ */
34
+ export function DevIdentityBadge({
35
+ name,
36
+ /** Optional extra label rendered after the name, e.g. branch or env. */
37
+ context,
38
+ /** Override visibility manually. Defaults to dev-mode only. */
39
+ visible,
40
+ }: {
41
+ name?: string;
42
+ context?: string;
43
+ visible?: boolean;
44
+ }) {
45
+ const [mounted, setMounted] = useState(false);
46
+ const [port, setPort] = useState<string | null>(null);
47
+ const [mountedAt] = useState(() => Date.now());
48
+ const [, force] = useState(0);
49
+
50
+ useEffect(() => {
51
+ setMounted(true);
52
+ if (typeof window !== "undefined") {
53
+ setPort(window.location.port || "—");
54
+ }
55
+ // Re-render every 10s to refresh the relative time. Cheaper than every
56
+ // tick — the badge is meant to be glanceable, not a stopwatch.
57
+ const id = window.setInterval(() => force((n) => n + 1), 10_000);
58
+ return () => window.clearInterval(id);
59
+ }, []);
60
+
61
+ const show =
62
+ typeof visible === "boolean"
63
+ ? visible
64
+ : process.env.NODE_ENV !== "production";
65
+
66
+ if (!show || !mounted) return null;
67
+
68
+ return (
69
+ <div
70
+ role="status"
71
+ aria-label="Development build identifier"
72
+ className="fixed bottom-3 right-3 z-[2147483647] pointer-events-auto select-none"
73
+ >
74
+ <div className="flex items-center gap-2 rounded-full border border-border bg-card/95 backdrop-blur-md shadow-sm px-3 py-1.5 text-xs font-mono text-muted-foreground">
75
+ <span className="flex h-1.5 w-1.5 rounded-full bg-primary animate-pulse" />
76
+ {name && <span className="text-foreground font-semibold">{name}</span>}
77
+ {context && <span>· {context}</span>}
78
+ {port && <span>:{port}</span>}
79
+ <span>· {relativeTime(mountedAt)}</span>
80
+ </div>
81
+ </div>
82
+ );
83
+ }
84
+
85
+ function relativeTime(from: number): string {
86
+ const seconds = Math.max(1, Math.floor((Date.now() - from) / 1000));
87
+ if (seconds < 60) return `${seconds}s ago`;
88
+ const minutes = Math.floor(seconds / 60);
89
+ if (minutes < 60) return `${minutes}m ago`;
90
+ const hours = Math.floor(minutes / 60);
91
+ return `${hours}h ago`;
92
+ }