@behavioral-agentic-design-system/core 0.14.0 → 0.16.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.
@@ -0,0 +1,405 @@
1
+ "use client";
2
+
3
+ import * as React from "react";
4
+ import { ChevronRight } from "lucide-react";
5
+ import { cn } from "../../lib/utils";
6
+
7
+ /* -------------------------------------------------------------------------- */
8
+ /* Tree context */
9
+ /* -------------------------------------------------------------------------- */
10
+
11
+ interface TreeCtxValue {
12
+ expandedIds: Set<string>;
13
+ selectedId: string | undefined;
14
+ hasChildrenMap: Map<string, boolean>;
15
+ onToggle: (id: string) => void;
16
+ onSelect: (id: string) => void;
17
+ registerTrigger: (id: string, el: HTMLButtonElement | null) => void;
18
+ setHasChildren: (id: string, has: boolean) => void;
19
+ }
20
+
21
+ const TreeCtx = React.createContext<TreeCtxValue | null>(null);
22
+
23
+ function useTree() {
24
+ const ctx = React.useContext(TreeCtx);
25
+ if (!ctx) throw new Error("TreeItem must be inside <Tree>");
26
+ return ctx;
27
+ }
28
+
29
+ /* -------------------------------------------------------------------------- */
30
+ /* TreeItem context */
31
+ /* -------------------------------------------------------------------------- */
32
+
33
+ interface ItemCtxValue {
34
+ id: string;
35
+ level: number;
36
+ isExpanded: boolean;
37
+ }
38
+
39
+ const ItemCtx = React.createContext<ItemCtxValue | null>(null);
40
+
41
+ function useItem() {
42
+ const ctx = React.useContext(ItemCtx);
43
+ if (!ctx) throw new Error("TreeItemTrigger/TreeItemContent must be inside <TreeItem>");
44
+ return ctx;
45
+ }
46
+
47
+ /* -------------------------------------------------------------------------- */
48
+ /* Helpers */
49
+ /* -------------------------------------------------------------------------- */
50
+
51
+ function getVisibleTriggers(treeEl: Element): HTMLButtonElement[] {
52
+ return Array.from(
53
+ treeEl.querySelectorAll<HTMLButtonElement>('li[role="treeitem"] > button')
54
+ );
55
+ }
56
+
57
+ /* -------------------------------------------------------------------------- */
58
+ /* Tree */
59
+ /* -------------------------------------------------------------------------- */
60
+
61
+ export interface TreeProps extends Omit<React.ComponentProps<"ul">, "onSelect"> {
62
+ /** IDs to be expanded on first render (uncontrolled) */
63
+ defaultExpanded?: string[];
64
+ /** Controlled expanded IDs */
65
+ expanded?: string[];
66
+ onExpandedChange?: (ids: string[]) => void;
67
+ /** Controlled selected ID */
68
+ selectedId?: string;
69
+ onSelect?: (id: string) => void;
70
+ }
71
+
72
+ function Tree({
73
+ children,
74
+ className,
75
+ defaultExpanded = [],
76
+ expanded: expandedProp,
77
+ onExpandedChange,
78
+ selectedId: selectedProp,
79
+ onSelect,
80
+ "aria-label": ariaLabel,
81
+ ...props
82
+ }: TreeProps) {
83
+ const isCtrlExpand = expandedProp !== undefined;
84
+ const [expandedState, setExpandedState] = React.useState(
85
+ () => new Set<string>(defaultExpanded)
86
+ );
87
+ const expandedIds = isCtrlExpand ? new Set(expandedProp) : expandedState;
88
+
89
+ const [selectedState, setSelectedState] = React.useState<string | undefined>();
90
+ const isCtrlSelect = selectedProp !== undefined;
91
+ const selectedId = isCtrlSelect ? selectedProp : selectedState;
92
+
93
+ const [hasChildrenMap, setHasChildrenMapState] = React.useState<Map<string, boolean>>(
94
+ () => new Map()
95
+ );
96
+
97
+ const triggerRegistry = React.useRef<Map<string, HTMLButtonElement>>(new Map());
98
+ const treeRef = React.useRef<HTMLUListElement>(null);
99
+ const lastFocusedIdRef = React.useRef<string | undefined>(undefined);
100
+
101
+ const registerTrigger = React.useCallback(
102
+ (id: string, el: HTMLButtonElement | null) => {
103
+ if (el) triggerRegistry.current.set(id, el);
104
+ else triggerRegistry.current.delete(id);
105
+ },
106
+ []
107
+ );
108
+
109
+ const setHasChildren = React.useCallback((id: string, has: boolean) => {
110
+ setHasChildrenMapState((prev) => {
111
+ const next = new Map(prev);
112
+ has ? next.set(id, true) : next.delete(id);
113
+ return next;
114
+ });
115
+ }, []);
116
+
117
+ const onToggle = React.useCallback(
118
+ (id: string) => {
119
+ if (isCtrlExpand) {
120
+ const next = new Set(expandedProp!);
121
+ next.has(id) ? next.delete(id) : next.add(id);
122
+ onExpandedChange?.(Array.from(next));
123
+ } else {
124
+ setExpandedState((prev) => {
125
+ const next = new Set(prev);
126
+ next.has(id) ? next.delete(id) : next.add(id);
127
+ return next;
128
+ });
129
+ }
130
+ },
131
+ [isCtrlExpand, expandedProp, onExpandedChange]
132
+ );
133
+
134
+ const handleSelect = React.useCallback(
135
+ (id: string) => {
136
+ if (!isCtrlSelect) setSelectedState(id);
137
+ onSelect?.(id);
138
+ },
139
+ [isCtrlSelect, onSelect]
140
+ );
141
+
142
+ // Attach focusin listener to manage roving tabindex
143
+ React.useEffect(() => {
144
+ const tree = treeRef.current;
145
+ if (!tree) return;
146
+
147
+ const onFocusIn = (e: FocusEvent) => {
148
+ const target = e.target as HTMLElement;
149
+ if (target.tagName !== "BUTTON" || target.closest('[role="tree"]') !== tree) return;
150
+ const triggers = getVisibleTriggers(tree);
151
+ triggers.forEach((t) => (t.tabIndex = t === target ? 0 : -1));
152
+ };
153
+
154
+ tree.addEventListener("focusin", onFocusIn);
155
+ return () => tree.removeEventListener("focusin", onFocusIn);
156
+ }, []);
157
+
158
+ // After expand/collapse changes, ensure a trigger has tabIndex=0
159
+ React.useEffect(() => {
160
+ const tree = treeRef.current;
161
+ if (!tree) return;
162
+ const triggers = getVisibleTriggers(tree);
163
+ if (!triggers.length) return;
164
+ const hasZero = triggers.some((t) => t.tabIndex === 0);
165
+ if (!hasZero) triggers[0].tabIndex = 0;
166
+ });
167
+
168
+ const ctx = React.useMemo<TreeCtxValue>(
169
+ () => ({
170
+ expandedIds,
171
+ selectedId,
172
+ hasChildrenMap,
173
+ onToggle,
174
+ onSelect: handleSelect,
175
+ registerTrigger,
176
+ setHasChildren,
177
+ }),
178
+ // eslint-disable-next-line react-hooks/exhaustive-deps
179
+ [expandedIds, selectedId, hasChildrenMap, onToggle, handleSelect, registerTrigger, setHasChildren]
180
+ );
181
+
182
+ return (
183
+ <TreeCtx.Provider value={ctx}>
184
+ <ul
185
+ ref={treeRef}
186
+ role="tree"
187
+ aria-label={ariaLabel ?? "Tree navigation"}
188
+ className={cn("space-y-0.5", className)}
189
+ {...props}
190
+ >
191
+ {children}
192
+ </ul>
193
+ </TreeCtx.Provider>
194
+ );
195
+ }
196
+
197
+ /* -------------------------------------------------------------------------- */
198
+ /* TreeItem */
199
+ /* -------------------------------------------------------------------------- */
200
+
201
+ export interface TreeItemProps extends React.ComponentProps<"li"> {
202
+ /** Unique ID for expand/select state */
203
+ id: string;
204
+ }
205
+
206
+ function TreeItem({ id, children, className, ...props }: TreeItemProps) {
207
+ const tree = useTree();
208
+ const parent = React.useContext(ItemCtx);
209
+ const level = parent ? parent.level + 1 : 1;
210
+ const isExpanded = tree.expandedIds.has(id);
211
+ const isSelected = tree.selectedId === id;
212
+ const hasChildren = tree.hasChildrenMap.get(id) ?? false;
213
+
214
+ return (
215
+ <ItemCtx.Provider value={{ id, level, isExpanded }}>
216
+ <li
217
+ role="treeitem"
218
+ aria-expanded={hasChildren ? isExpanded : undefined}
219
+ aria-selected={isSelected}
220
+ aria-level={level}
221
+ className={cn("list-none", className)}
222
+ {...props}
223
+ >
224
+ {children}
225
+ </li>
226
+ </ItemCtx.Provider>
227
+ );
228
+ }
229
+
230
+ /* -------------------------------------------------------------------------- */
231
+ /* TreeItemTrigger */
232
+ /* -------------------------------------------------------------------------- */
233
+
234
+ export interface TreeItemTriggerProps
235
+ extends Omit<React.ComponentProps<"button">, "id"> {
236
+ /** Optional icon rendered between the chevron and label text */
237
+ icon?: React.ReactNode;
238
+ }
239
+
240
+ function TreeItemTrigger({
241
+ children,
242
+ className,
243
+ icon,
244
+ onClick,
245
+ onKeyDown,
246
+ ...props
247
+ }: TreeItemTriggerProps) {
248
+ const { id, level, isExpanded } = useItem();
249
+ const tree = useTree();
250
+ const btnRef = React.useRef<HTMLButtonElement>(null);
251
+ const hasChildren = tree.hasChildrenMap.get(id) ?? false;
252
+ const isSelected = tree.selectedId === id;
253
+
254
+ React.useEffect(() => {
255
+ tree.registerTrigger(id, btnRef.current);
256
+ return () => tree.registerTrigger(id, null);
257
+ }, [id, tree.registerTrigger]);
258
+
259
+ const getTriggers = (): HTMLButtonElement[] => {
260
+ const treeEl = btnRef.current?.closest('[role="tree"]');
261
+ return treeEl ? getVisibleTriggers(treeEl) : [];
262
+ };
263
+
264
+ const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {
265
+ if (hasChildren) tree.onToggle(id);
266
+ tree.onSelect(id);
267
+ onClick?.(e);
268
+ };
269
+
270
+ const handleKeyDown = (e: React.KeyboardEvent<HTMLButtonElement>) => {
271
+ const triggers = getTriggers();
272
+ const idx = triggers.indexOf(btnRef.current!);
273
+
274
+ switch (e.key) {
275
+ case "ArrowDown":
276
+ e.preventDefault();
277
+ triggers[idx + 1]?.focus();
278
+ break;
279
+ case "ArrowUp":
280
+ e.preventDefault();
281
+ triggers[idx - 1]?.focus();
282
+ break;
283
+ case "ArrowRight":
284
+ e.preventDefault();
285
+ if (hasChildren && !isExpanded) tree.onToggle(id);
286
+ else if (hasChildren && isExpanded) triggers[idx + 1]?.focus();
287
+ break;
288
+ case "ArrowLeft":
289
+ e.preventDefault();
290
+ if (hasChildren && isExpanded) {
291
+ tree.onToggle(id);
292
+ } else {
293
+ // Move focus to closest ancestor trigger (lower aria-level)
294
+ for (let i = idx - 1; i >= 0; i--) {
295
+ const li = triggers[i].closest('li[role="treeitem"]');
296
+ const parentLevel = parseInt(li?.getAttribute("aria-level") ?? "1");
297
+ if (parentLevel < level) {
298
+ triggers[i].focus();
299
+ break;
300
+ }
301
+ }
302
+ }
303
+ break;
304
+ case "Home":
305
+ e.preventDefault();
306
+ triggers[0]?.focus();
307
+ break;
308
+ case "End":
309
+ e.preventDefault();
310
+ triggers[triggers.length - 1]?.focus();
311
+ break;
312
+ case "Enter":
313
+ case " ":
314
+ e.preventDefault();
315
+ if (hasChildren) tree.onToggle(id);
316
+ tree.onSelect(id);
317
+ break;
318
+ }
319
+
320
+ onKeyDown?.(e);
321
+ };
322
+
323
+ const indent = (level - 1) * 16;
324
+
325
+ return (
326
+ <button
327
+ ref={btnRef}
328
+ type="button"
329
+ tabIndex={-1}
330
+ data-state={isExpanded ? "open" : "closed"}
331
+ data-selected={isSelected || undefined}
332
+ className={cn(
333
+ "flex w-full items-center gap-1.5 rounded-md py-1.5 pr-2",
334
+ "text-sm font-medium text-foreground",
335
+ "hover:bg-accent hover:text-accent-foreground",
336
+ "focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50",
337
+ "data-[selected]:bg-accent data-[selected]:text-accent-foreground",
338
+ "disabled:pointer-events-none disabled:opacity-50",
339
+ "transition-colors",
340
+ className
341
+ )}
342
+ style={{
343
+ paddingLeft: `${indent + 8}px`,
344
+ transitionDuration: "var(--duration-fast)",
345
+ transitionTimingFunction: "var(--ease-out)",
346
+ }}
347
+ onClick={handleClick}
348
+ onKeyDown={handleKeyDown}
349
+ {...props}
350
+ >
351
+ <ChevronRight
352
+ className={cn(
353
+ "size-4 shrink-0 transition-transform",
354
+ !hasChildren && "opacity-0 pointer-events-none",
355
+ isExpanded && "rotate-90"
356
+ )}
357
+ style={{
358
+ transitionDuration: "var(--duration-fast)",
359
+ transitionTimingFunction: "var(--ease-out)",
360
+ }}
361
+ strokeWidth={1.5}
362
+ aria-hidden
363
+ />
364
+ {icon && (
365
+ <span
366
+ className="shrink-0 text-muted-foreground [&_svg]:size-4 [&_svg]:stroke-[1.5]"
367
+ aria-hidden
368
+ >
369
+ {icon}
370
+ </span>
371
+ )}
372
+ <span className="min-w-0 flex-1 truncate text-left">{children}</span>
373
+ </button>
374
+ );
375
+ }
376
+
377
+ /* -------------------------------------------------------------------------- */
378
+ /* TreeItemContent */
379
+ /* -------------------------------------------------------------------------- */
380
+
381
+ export interface TreeItemContentProps extends React.ComponentProps<"ul"> {}
382
+
383
+ function TreeItemContent({ children, className, ...props }: TreeItemContentProps) {
384
+ const { id, isExpanded } = useItem();
385
+ const tree = useTree();
386
+
387
+ React.useEffect(() => {
388
+ tree.setHasChildren(id, true);
389
+ return () => tree.setHasChildren(id, false);
390
+ }, [id, tree.setHasChildren]);
391
+
392
+ if (!isExpanded) return null;
393
+
394
+ return (
395
+ <ul role="group" className={cn("space-y-0.5", className)} {...props}>
396
+ {children}
397
+ </ul>
398
+ );
399
+ }
400
+
401
+ /* -------------------------------------------------------------------------- */
402
+ /* Exports */
403
+ /* -------------------------------------------------------------------------- */
404
+
405
+ export { Tree, TreeItem, TreeItemTrigger, TreeItemContent };
@@ -101,6 +101,7 @@ export const DOCS_INDEX: DocGroup[] = [
101
101
  description: "How the system stays honest — anti-patterns, the corrections log, the ethics floor.",
102
102
  entries: [
103
103
  { title: "Design rules", path: "DESIGN.md", summary: "Visual system + accessibility baseline." },
104
+ { title: "Chart color palette", path: "docs/chart-color-palette.md", summary: "Accessible 5-color categorical palette for data viz — Okabe-Ito-derived, reviewed against WCAG 1.4.11 non-text contrast." },
104
105
  { title: "Gamification — responsible vs. manipulative", path: "layer-2-ethics-responsibility/gamification.md", summary: "Sir's 10 Core Drives (Octalysis 8 + Exploration & Discovery + Challenge & Competition) + the test gates that decide when Black Hat ships and when it refuses." },
105
106
  { title: "Corrections log", path: "corrections.md", summary: "Per-fork anti-pattern log. Read before every Path B build." },
106
107
  { title: "Anti-defaults refresh", path: "prompts/anti-defaults-refresh.md", summary: "Quarterly pressure-test of the current anti-defaults." },
@@ -24,7 +24,7 @@ export type PrimaryColorOption = {
24
24
  custom?: boolean;
25
25
  /**
26
26
  * Optional override for the picker swatch when the displayed color should
27
- * differ from the applied primary. Carried over from the swimtopia customize
27
+ * differ from the applied primary. Carried over from a client fork's customize
28
28
  * tab (e.g. an "Off White" option that applies dark in light mode but the
29
29
  * picker still reads off-white). BADS' built-in palette doesn't set these.
30
30
  */
package/src/styles.css CHANGED
@@ -480,7 +480,7 @@
480
480
  * role. Disabled state → cursor: not-allowed so "off" reads as
481
481
  * intentional rather than broken.
482
482
  *
483
- * Promoted from swimtopia-prototypes globals.css (2026-06-10) per
483
+ * Promoted from a client fork's globals.css (2026-06-10) per
484
484
  * Sir's "if it's clickable, the cursor says so" rule. */
485
485
  button:not(:disabled),
486
486
  a[href]:not([aria-disabled="true"]),
@@ -524,7 +524,7 @@ html, body {
524
524
  written to --x / --y on <html> before startViewTransition fires (see
525
525
  app/page.tsx toggleDark).
526
526
 
527
- Two deliberate choices, both learned the hard way (swimtopia, 2026-06):
527
+ Two deliberate choices, both learned the hard way (a client fork, 2026-06):
528
528
  1. Radius is a VIEWPORT unit (150vmax), not a percentage. circle(150%)
529
529
  resolves against the snapshot box, so on a large/wide desktop the wipe
530
530
  can finish before it has covered the viewport — a glitch at the END of