@behavioral-agentic-design-system/core 0.39.1 → 0.42.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 (115) hide show
  1. package/README.md +2 -0
  2. package/package.json +26 -5
  3. package/scripts/a11y-lint.cjs +88 -8
  4. package/scripts/bads-components.mjs +118 -0
  5. package/scripts/build-tokens.cjs +133 -12
  6. package/scripts/check-stories.mjs +1 -1
  7. package/scripts/health-report.mjs +16 -2
  8. package/scripts/lint-component-source.mjs +100 -0
  9. package/scripts/lint-microanimation.mjs +267 -0
  10. package/scripts/lint-slop.mjs +25 -1
  11. package/scripts/size-audit.cjs +79 -0
  12. package/scripts/source-of-truth.cjs +58 -0
  13. package/scripts/ux-smoke.mjs +438 -0
  14. package/scripts/wcag-audit.cjs +121 -6
  15. package/src/api/layers/file.ts +1 -0
  16. package/src/app/opengraph-image.tsx +5 -0
  17. package/src/app/preview/components/page.tsx +2237 -2
  18. package/src/app/shell.tsx +17 -16
  19. package/src/components/Foundations/Motion.stories.tsx +1 -0
  20. package/src/components/customize/brand-mark-section.tsx +4 -2
  21. package/src/components/customize/design-controls.tsx +17 -2
  22. package/src/components/customize/discipline-section.tsx +3 -6
  23. package/src/components/customize/font-pickers.tsx +1 -1
  24. package/src/components/customize/letter-spacing.tsx +1 -1
  25. package/src/components/customize/save-bar.tsx +2 -2
  26. package/src/components/customize/theme-io.tsx +7 -7
  27. package/src/components/customize/type-scale.tsx +1 -1
  28. package/src/components/customize-tab.tsx +7 -4
  29. package/src/components/home-tab.tsx +3 -0
  30. package/src/components/studio/studio.tsx +153 -0
  31. package/src/components/ui/accordion.tsx +7 -0
  32. package/src/components/ui/alert.tsx +1 -0
  33. package/src/components/ui/anchor.tsx +37 -3
  34. package/src/components/ui/announcement-bar.tsx +256 -0
  35. package/src/components/ui/attachment.tsx +211 -0
  36. package/src/components/ui/badge.tsx +1 -0
  37. package/src/components/ui/callout.tsx +218 -0
  38. package/src/components/ui/chart.tsx +5 -14
  39. package/src/components/ui/code.tsx +1 -1
  40. package/src/components/ui/color-picker.tsx +2 -2
  41. package/src/components/ui/format-relative-time.tsx +139 -0
  42. package/src/components/ui/gauge-chart.tsx +238 -0
  43. package/src/components/ui/grid.tsx +255 -0
  44. package/src/components/ui/heatmap.tsx +256 -0
  45. package/src/components/ui/icon.tsx +108 -0
  46. package/src/components/ui/index.ts +17 -0
  47. package/src/components/ui/infinite-scroll.tsx +103 -0
  48. package/src/components/ui/json-input.tsx +351 -0
  49. package/src/components/ui/navigation-progress.tsx +281 -0
  50. package/src/components/ui/number-input.tsx +1 -4
  51. package/src/components/ui/page-header.tsx +63 -0
  52. package/src/components/ui/password-input.tsx +2 -1
  53. package/src/components/ui/password-strength-input.tsx +288 -0
  54. package/src/components/ui/pill.tsx +140 -0
  55. package/src/components/ui/popover.tsx +27 -4
  56. package/src/components/ui/portal.tsx +111 -0
  57. package/src/components/ui/presence.tsx +172 -0
  58. package/src/components/ui/progress-stack.tsx +258 -0
  59. package/src/components/ui/scroll-progress.tsx +100 -0
  60. package/src/components/ui/select.tsx +89 -4
  61. package/src/components/ui/separator.tsx +1 -0
  62. package/src/components/ui/slider.tsx +83 -3
  63. package/src/components/ui/snackbar.tsx +393 -0
  64. package/src/components/ui/sortable-list.tsx +342 -0
  65. package/src/components/ui/sparkline.tsx +2 -14
  66. package/src/components/ui/squircle.tsx +1 -1
  67. package/src/components/ui/table.tsx +1 -1
  68. package/src/components/ui/textarea.tsx +28 -1
  69. package/src/components/ui/tour.tsx +1 -3
  70. package/src/data/docs-index.ts +25 -0
  71. package/src/hooks/use-reduced-motion.ts +6 -0
  72. package/src/lib/clamp.ts +2 -0
  73. package/src/stories/Accordion.stories.tsx +59 -0
  74. package/src/stories/Alert.stories.tsx +3 -1
  75. package/src/stories/Anchor.stories.tsx +54 -0
  76. package/src/stories/AnnouncementBar.stories.tsx +261 -0
  77. package/src/stories/Attachment.stories.tsx +189 -0
  78. package/src/stories/Badge.stories.tsx +3 -0
  79. package/src/stories/Calendar.stories.tsx +1 -1
  80. package/src/stories/Callout.stories.tsx +219 -0
  81. package/src/stories/Chart.stories.tsx +8 -0
  82. package/src/stories/Code.stories.tsx +1 -0
  83. package/src/stories/ColorPicker.stories.tsx +24 -0
  84. package/src/stories/FormatRelativeTime.stories.tsx +116 -0
  85. package/src/stories/GaugeChart.stories.tsx +163 -0
  86. package/src/stories/Grid.stories.tsx +197 -0
  87. package/src/stories/Heatmap.stories.tsx +172 -0
  88. package/src/stories/Icon.stories.tsx +175 -0
  89. package/src/stories/InfiniteScroll.stories.tsx +225 -0
  90. package/src/stories/JsonInput.stories.tsx +212 -0
  91. package/src/stories/MultiSelect.stories.tsx +1 -1
  92. package/src/stories/NavigationProgress.stories.tsx +159 -0
  93. package/src/stories/NumberInput.stories.tsx +1 -0
  94. package/src/stories/PageHeader.stories.tsx +102 -0
  95. package/src/stories/PasswordInput.stories.tsx +4 -0
  96. package/src/stories/PasswordStrengthInput.stories.tsx +211 -0
  97. package/src/stories/Pill.stories.tsx +201 -0
  98. package/src/stories/Popover.stories.tsx +29 -1
  99. package/src/stories/Portal.stories.tsx +191 -0
  100. package/src/stories/Presence.stories.tsx +228 -0
  101. package/src/stories/ProgressStack.stories.tsx +287 -0
  102. package/src/stories/ScrollProgress.stories.tsx +117 -0
  103. package/src/stories/Select.stories.tsx +25 -0
  104. package/src/stories/Separator.stories.tsx +3 -0
  105. package/src/stories/Slider.stories.tsx +54 -5
  106. package/src/stories/Snackbar.stories.tsx +315 -0
  107. package/src/stories/SortableList.stories.tsx +263 -0
  108. package/src/stories/Sparkline.stories.tsx +3 -0
  109. package/src/stories/Squircle.stories.tsx +1 -0
  110. package/src/stories/Table.stories.tsx +1 -0
  111. package/src/stories/Textarea.stories.tsx +18 -0
  112. package/src/stories/Tour.stories.tsx +1 -0
  113. package/src/stories/story-groups.json +26 -6
  114. package/src/styles.css +133 -12
  115. package/LICENSE +0 -21
@@ -0,0 +1,342 @@
1
+ "use client";
2
+
3
+ import * as React from "react";
4
+ import {
5
+ DndContext,
6
+ closestCenter,
7
+ KeyboardSensor,
8
+ PointerSensor,
9
+ useSensor,
10
+ useSensors,
11
+ DragEndEvent,
12
+ DragStartEvent,
13
+ DragOverlay,
14
+ UniqueIdentifier,
15
+ } from "@dnd-kit/core";
16
+ import {
17
+ arrayMove,
18
+ SortableContext,
19
+ sortableKeyboardCoordinates,
20
+ useSortable,
21
+ verticalListSortingStrategy,
22
+ horizontalListSortingStrategy,
23
+ } from "@dnd-kit/sortable";
24
+ import { CSS } from "@dnd-kit/utilities";
25
+ import { cva, type VariantProps } from "class-variance-authority";
26
+ import { GripVertical, GripHorizontal } from "lucide-react";
27
+ import { cn } from "../../lib/utils";
28
+
29
+ /**
30
+ * Drag-and-drop reorderable list.
31
+ *
32
+ * Uses @dnd-kit/core + @dnd-kit/sortable for pointer and keyboard drag.
33
+ * Fully accessible: keyboard sensor handles Space/Enter to lift, arrow keys
34
+ * to move, and Space/Enter/Escape to drop/cancel. Screen-reader announcements
35
+ * are generated by dnd-kit's built-in accessibility provider.
36
+ *
37
+ * Items must have a stable `id` string or number. Order state is managed by
38
+ * the parent — provide `items` + `onReorder` for controlled use.
39
+ *
40
+ * @example
41
+ * // Controlled vertical list
42
+ * const [items, setItems] = React.useState(initialItems)
43
+ * <SortableList items={items} onReorder={setItems} renderItem={(item) => item.label} />
44
+ *
45
+ * @example
46
+ * // Without drag handle (whole row is draggable)
47
+ * <SortableList items={items} onReorder={setItems} handle={false} renderItem={(item) => item.label} />
48
+ */
49
+
50
+ // ── Variants ──────────────────────────────────────────────────────────────────
51
+
52
+ const sortableListVariants = cva("flex w-full", {
53
+ variants: {
54
+ orientation: {
55
+ vertical: "flex-col",
56
+ horizontal: "flex-row flex-wrap",
57
+ },
58
+ size: {
59
+ sm: "gap-1",
60
+ default: "gap-2",
61
+ lg: "gap-3",
62
+ },
63
+ },
64
+ defaultVariants: {
65
+ orientation: "vertical",
66
+ size: "default",
67
+ },
68
+ });
69
+
70
+ const sortableItemVariants = cva(
71
+ [
72
+ "group flex items-center rounded-md border border-border bg-card text-card-foreground",
73
+ "outline-hidden ring-ring focus-visible:ring-2 focus-visible:ring-offset-2",
74
+ "select-none touch-none",
75
+ ].join(" "),
76
+ {
77
+ variants: {
78
+ size: {
79
+ sm: "gap-2 px-2 py-1.5 text-sm",
80
+ default: "gap-3 px-3 py-2.5 text-sm",
81
+ lg: "gap-3 px-4 py-3 text-base",
82
+ },
83
+ isDragging: {
84
+ true: "opacity-50",
85
+ false: "",
86
+ },
87
+ },
88
+ defaultVariants: {
89
+ size: "default",
90
+ isDragging: false,
91
+ },
92
+ },
93
+ );
94
+
95
+ // ── Types ─────────────────────────────────────────────────────────────────────
96
+
97
+ export interface SortableItem {
98
+ id: UniqueIdentifier;
99
+ [key: string]: unknown;
100
+ }
101
+
102
+ export interface SortableListProps<T extends SortableItem>
103
+ extends VariantProps<typeof sortableListVariants> {
104
+ /** The ordered list of items. Each item must have a stable `id`. */
105
+ items: T[];
106
+ /** Called after a drag-drop reorder with the new item order. */
107
+ onReorder: (newItems: T[]) => void;
108
+ /** Render function for each item's content. */
109
+ renderItem: (item: T, index: number) => React.ReactNode;
110
+ /** Show a drag-handle icon (default: true). When false, the whole row drags. */
111
+ handle?: boolean;
112
+ /** Disables all drag interactions. */
113
+ disabled?: boolean;
114
+ /** Extra classes on the list wrapper. */
115
+ className?: string;
116
+ /** A11y: label for the sortable list (read by screen readers). */
117
+ "aria-label"?: string;
118
+ }
119
+
120
+ // ── SortableItem (inner) ──────────────────────────────────────────────────────
121
+
122
+ interface SortableItemInnerProps {
123
+ id: UniqueIdentifier;
124
+ children: React.ReactNode;
125
+ size: "sm" | "default" | "lg";
126
+ handle: boolean;
127
+ disabled: boolean;
128
+ orientation: "vertical" | "horizontal";
129
+ isOverlay?: boolean;
130
+ }
131
+
132
+ function SortableItemInner({
133
+ id,
134
+ children,
135
+ size,
136
+ handle,
137
+ disabled,
138
+ isOverlay = false,
139
+ }: SortableItemInnerProps) {
140
+ const {
141
+ attributes,
142
+ listeners,
143
+ setNodeRef,
144
+ setActivatorNodeRef,
145
+ transform,
146
+ transition,
147
+ isDragging,
148
+ } = useSortable({ id, disabled });
149
+
150
+ const style: React.CSSProperties = {
151
+ transform: CSS.Transform.toString(transform),
152
+ transition,
153
+ // Overlay is rendered separately via DragOverlay; the source gets opacity:50
154
+ };
155
+
156
+ const HandleIcon = size === "lg" ? GripVertical : GripVertical;
157
+
158
+ // When handle=false the whole row acts as the drag activator
159
+ const rowListeners = handle ? {} : listeners;
160
+ const rowAttributes = handle ? {} : attributes;
161
+
162
+ return (
163
+ <div
164
+ ref={setNodeRef}
165
+ style={style}
166
+ className={sortableItemVariants({
167
+ size,
168
+ isDragging: isDragging && !isOverlay,
169
+ })}
170
+ {...rowAttributes}
171
+ {...rowListeners}
172
+ >
173
+ {handle && !disabled && (
174
+ <button
175
+ ref={setActivatorNodeRef}
176
+ type="button"
177
+ aria-label="Drag to reorder"
178
+ className={cn(
179
+ "shrink-0 cursor-grab rounded text-muted-foreground",
180
+ "active:cursor-grabbing",
181
+ "focus-visible:ring-ring outline-hidden focus-visible:ring-2 focus-visible:ring-offset-1",
182
+ "transition-colors",
183
+ "hover:text-foreground",
184
+ )}
185
+ style={{
186
+ transitionDuration: "var(--duration-fast)",
187
+ transitionTimingFunction: "var(--ease-out)",
188
+ }}
189
+ {...attributes}
190
+ {...listeners}
191
+ >
192
+ {size === "sm" ? (
193
+ <HandleIcon
194
+ className="size-3.5"
195
+ strokeWidth={1.5}
196
+ aria-hidden="true"
197
+ />
198
+ ) : size === "lg" ? (
199
+ <HandleIcon
200
+ className="size-5"
201
+ strokeWidth={1.5}
202
+ aria-hidden="true"
203
+ />
204
+ ) : (
205
+ <HandleIcon
206
+ className="size-4"
207
+ strokeWidth={1.5}
208
+ aria-hidden="true"
209
+ />
210
+ )}
211
+ </button>
212
+ )}
213
+ <div className="min-w-0 flex-1">{children}</div>
214
+ </div>
215
+ );
216
+ }
217
+
218
+ // ── SortableList ──────────────────────────────────────────────────────────────
219
+
220
+ function SortableListInner<T extends SortableItem>(
221
+ {
222
+ items,
223
+ onReorder,
224
+ renderItem,
225
+ handle = true,
226
+ disabled = false,
227
+ orientation = "vertical",
228
+ size = "default",
229
+ className,
230
+ "aria-label": ariaLabel,
231
+ }: SortableListProps<T>,
232
+ ref: React.Ref<HTMLDivElement>,
233
+ ) {
234
+ const [activeId, setActiveId] = React.useState<UniqueIdentifier | null>(null);
235
+
236
+ const sensors = useSensors(
237
+ useSensor(PointerSensor, {
238
+ activationConstraint: { distance: 4 },
239
+ }),
240
+ useSensor(KeyboardSensor, {
241
+ coordinateGetter: sortableKeyboardCoordinates,
242
+ }),
243
+ );
244
+
245
+ const strategy =
246
+ orientation === "horizontal"
247
+ ? horizontalListSortingStrategy
248
+ : verticalListSortingStrategy;
249
+
250
+ function handleDragStart({ active }: DragStartEvent) {
251
+ setActiveId(active.id);
252
+ }
253
+
254
+ function handleDragEnd({ active, over }: DragEndEvent) {
255
+ setActiveId(null);
256
+ if (!over || active.id === over.id) return;
257
+ const oldIndex = items.findIndex((item) => item.id === active.id);
258
+ const newIndex = items.findIndex((item) => item.id === over.id);
259
+ if (oldIndex !== -1 && newIndex !== -1) {
260
+ onReorder(arrayMove(items, oldIndex, newIndex));
261
+ }
262
+ }
263
+
264
+ function handleDragCancel() {
265
+ setActiveId(null);
266
+ }
267
+
268
+ const activeItem = activeId != null
269
+ ? items.find((item) => item.id === activeId) ?? null
270
+ : null;
271
+ const activeIndex = activeItem
272
+ ? items.findIndex((item) => item.id === activeId)
273
+ : -1;
274
+
275
+ return (
276
+ <DndContext
277
+ sensors={sensors}
278
+ collisionDetection={closestCenter}
279
+ onDragStart={handleDragStart}
280
+ onDragEnd={handleDragEnd}
281
+ onDragCancel={handleDragCancel}
282
+ >
283
+ <SortableContext items={items.map((i) => i.id)} strategy={strategy}>
284
+ <div
285
+ ref={ref}
286
+ role="list"
287
+ aria-label={ariaLabel}
288
+ className={cn(sortableListVariants({ orientation, size }), className)}
289
+ >
290
+ {items.map((item, index) => (
291
+ <div key={item.id} role="listitem">
292
+ <SortableItemInner
293
+ id={item.id}
294
+ size={size ?? "default"}
295
+ handle={handle}
296
+ disabled={disabled}
297
+ orientation={orientation ?? "vertical"}
298
+ >
299
+ {renderItem(item, index)}
300
+ </SortableItemInner>
301
+ </div>
302
+ ))}
303
+ </div>
304
+ </SortableContext>
305
+
306
+ {/* Drag overlay — renders the "floating" item while dragging */}
307
+ <DragOverlay>
308
+ {activeItem ? (
309
+ <div
310
+ style={{
311
+ opacity: 1,
312
+ transitionDuration: "var(--duration-fast)",
313
+ transitionTimingFunction: "var(--ease-out)",
314
+ boxShadow:
315
+ "0 4px 16px -4px rgb(0 0 0 / 0.16), 0 1px 4px -1px rgb(0 0 0 / 0.08)",
316
+ }}
317
+ >
318
+ <SortableItemInner
319
+ id={activeItem.id}
320
+ size={size ?? "default"}
321
+ handle={handle}
322
+ disabled={false}
323
+ orientation={orientation ?? "vertical"}
324
+ isOverlay
325
+ >
326
+ {renderItem(activeItem, activeIndex)}
327
+ </SortableItemInner>
328
+ </div>
329
+ ) : null}
330
+ </DragOverlay>
331
+ </DndContext>
332
+ );
333
+ }
334
+
335
+ // Use generic forwardRef workaround (TypeScript limitation with generics + forwardRef)
336
+ const SortableList = React.forwardRef(SortableListInner) as <
337
+ T extends SortableItem,
338
+ >(
339
+ props: SortableListProps<T> & { ref?: React.Ref<HTMLDivElement> },
340
+ ) => React.ReactElement;
341
+
342
+ export { SortableList };
@@ -12,6 +12,7 @@ import {
12
12
  } from "recharts"
13
13
 
14
14
  import { cn } from "../../lib/utils"
15
+ import { useReducedMotion } from "../../hooks/use-reduced-motion"
15
16
 
16
17
  export interface SparklineProps extends React.ComponentProps<"span"> {
17
18
  /**
@@ -49,19 +50,6 @@ export interface SparklineProps extends React.ComponentProps<"span"> {
49
50
  // Each Sparkline instance gets its own gradient so multiple sparklines on
50
51
  // the same page don't share gradient ids and create incorrect fill colors.
51
52
 
52
- function usePrefersReducedMotion(): boolean {
53
- const [reduced, setReduced] = React.useState(false)
54
- React.useEffect(() => {
55
- if (typeof window === "undefined" || !window.matchMedia) return
56
- const mql = window.matchMedia("(prefers-reduced-motion: reduce)")
57
- setReduced(mql.matches)
58
- const onChange = (e: MediaQueryListEvent) => setReduced(e.matches)
59
- mql.addEventListener("change", onChange)
60
- return () => mql.removeEventListener("change", onChange)
61
- }, [])
62
- return reduced
63
- }
64
-
65
53
  /**
66
54
  * Compact inline sparkline for trend visualization. Renders a mini area or
67
55
  * line chart with no axes, no labels, and no tooltip — just the data shape.
@@ -91,7 +79,7 @@ function Sparkline({
91
79
  const uniqueId = React.useId()
92
80
  const gradientId = `sparkline-grad-${uniqueId.replace(/:/g, "")}`
93
81
 
94
- const prefersReducedMotion = usePrefersReducedMotion()
82
+ const prefersReducedMotion = useReducedMotion()
95
83
  const animate = !prefersReducedMotion
96
84
 
97
85
  // ResizeObserver gate — same pattern as ChartContainer.
@@ -3,6 +3,7 @@
3
3
  import * as React from "react"
4
4
 
5
5
  import { cn } from "../../lib/utils"
6
+ import { clamp } from "../../lib/clamp"
6
7
 
7
8
  /* -------------------------------------------------------------------------------------------------
8
9
  * Superellipse path math — Figma's corner-smoothing model
@@ -21,7 +22,6 @@ const toRadians = (deg: number) => (deg * Math.PI) / 180
21
22
  /** Trim float noise so identical sizes produce identical cache keys / paths. */
22
23
  const n = (v: number) => Number(v.toFixed(4))
23
24
 
24
- const clamp = (v: number, min: number, max: number) => Math.min(max, Math.max(min, v))
25
25
 
26
26
  interface CornerParams {
27
27
  a: number
@@ -35,7 +35,7 @@ function Table({ className, wrapperClassName, wrapperStyle, striped = false, bor
35
35
  <TableVariantContext.Provider value={variants}>
36
36
  <div data-slot="table-container" tabIndex={0}
37
37
  className={cn(
38
- "relative w-full overflow-x-auto scrollbar-thin scrollbar-thumb-border scrollbar-track-transparent",
38
+ "relative w-full overflow-x-auto [scrollbar-width:thin] [scrollbar-color:theme(colors.border)_transparent]",
39
39
  bordered && "rounded-md border",
40
40
  wrapperClassName
41
41
  )}
@@ -36,6 +36,17 @@ interface TextareaProps
36
36
  maxLength?: number
37
37
  /** Label id for the character count `<output>` element. Auto-derived when omitted. */
38
38
  countId?: string
39
+ /**
40
+ * Cap auto-grow height at this many text rows. Works in tandem with
41
+ * `field-sizing-content` (the CSS auto-resize baseline): the textarea
42
+ * still grows freely up to this limit, then scrolls.
43
+ *
44
+ * Uses 1lh (line height) units for precision. 1lh resolves to the
45
+ * element's computed line-height so the cap tracks the font size.
46
+ *
47
+ * Peer parity: Mantine autosize maxRows, MUI maxRows, Ant Design autoSize.maxRows.
48
+ */
49
+ maxRows?: number
39
50
  }
40
51
 
41
52
  function Textarea({
@@ -44,6 +55,7 @@ function Textarea({
44
55
  showCount = false,
45
56
  maxLength,
46
57
  countId,
58
+ maxRows,
47
59
  onChange,
48
60
  defaultValue,
49
61
  value,
@@ -69,7 +81,22 @@ function Textarea({
69
81
  data-slot="textarea"
70
82
  maxLength={maxLength}
71
83
  aria-describedby={showCount ? resolvedCountId : undefined}
72
- className={cn(textareaVariants({ size }), className)}
84
+ className={cn(
85
+ textareaVariants({ size }),
86
+ // When maxRows is set, cap the auto-grow height and let excess scroll.
87
+ maxRows != null && "overflow-y-auto",
88
+ className
89
+ )}
90
+ style={
91
+ maxRows != null
92
+ ? {
93
+ // 1lh = computed line-height (Chrome 109+, Safari 16.4+).
94
+ // totalPy accounts for the top + bottom padding of each size tier.
95
+ // 2px covers the 1px border on each side.
96
+ maxHeight: `calc(${maxRows} * 1lh + ${{ sm: "0.75rem", default: "1rem", lg: "1.25rem", xl: "1.5rem" }[String(size ?? "default")] ?? "1rem"} + 2px)`,
97
+ }
98
+ : undefined
99
+ }
73
100
  value={value}
74
101
  defaultValue={defaultValue}
75
102
  onChange={handleChange}
@@ -5,6 +5,7 @@ import * as DialogPrimitive from "@radix-ui/react-dialog"
5
5
  import { XIcon } from "lucide-react"
6
6
 
7
7
  import { cn } from "../../lib/utils"
8
+ import { clamp } from "../../lib/clamp"
8
9
  import { usePortalThemeClass } from "../../hooks/use-portal-theme-class"
9
10
  import { Button } from "./button"
10
11
 
@@ -88,9 +89,6 @@ function measureTarget(selector: string | null | undefined): TargetRect | null {
88
89
  return { top: r.top, left: r.left, width: r.width, height: r.height }
89
90
  }
90
91
 
91
- function clamp(value: number, min: number, max: number) {
92
- return Math.min(Math.max(value, min), Math.max(min, max))
93
- }
94
92
 
95
93
  function computePanelPosition(
96
94
  target: TargetRect,
@@ -39,6 +39,7 @@ export const DOCS_INDEX: DocGroup[] = [
39
39
  entries: [
40
40
  { title: "README", path: "README.md", summary: "The first thing to read — what BADS is, how to run it, where to look next." },
41
41
  { title: "Brief", path: "BRIEF.md", summary: "The one-pager — what BADS is, who it's for, what it refuses." },
42
+ { title: "Product record", path: "PRODUCT.md", summary: "Durable product truth for the design skills: users, positioning, constraints, principles, and what must never be fabricated." },
42
43
  { title: "Design system stack", path: "DESIGN_SYSTEM_STACK.md", summary: "The 10-layer architecture in one document." },
43
44
  { title: "Tech stack", path: "docs/tech-stack.md", summary: "What BADS is built on and why — framework, tokens, testing, AI layer — plus the 30-second spoken answer." },
44
45
  { title: "Sync model", path: "BADS_SYNC.md", summary: "How forks pull upstream BADS improvements." },
@@ -107,6 +108,9 @@ export const DOCS_INDEX: DocGroup[] = [
107
108
  { title: "Skill — persona-pressure-test", path: ".claude/skills/persona-pressure-test/SKILL.md" },
108
109
  { title: "Skill — promote-prototype", path: ".claude/skills/promote-prototype/SKILL.md" },
109
110
  { title: "Skill — visual-verify", path: ".claude/skills/visual-verify/SKILL.md" },
111
+ { title: "Skill — verify", path: ".claude/skills/verify/SKILL.md", summary: "One command (pnpm verify) to look at Storybook in a real browser: start it on a free port, prove the server is this checkout's, screenshot a story in light and dark with console and network errors. Use before handing anyone a localhost URL." },
112
+ { title: "Skill — parity-check", path: ".claude/skills/parity-check/SKILL.md", summary: "Strict, measured pixel parity against a specific external reference (Figma export, client HTML, competitor screenshot) — zero differing pixels, not a judgment call. Complements visual-verify (reference-free, qualitative) rather than overlapping it." },
113
+ { title: "Skill — figma-to-code", path: ".claude/skills/figma-to-code/SKILL.md", summary: "Structured, gated workflow for building FROM a Figma node via live Figma MCP tooling — enumerate the real node tree (never a screenshot), map onto existing primitives/tokens, resolve gaps for real, then hand off to component-builder. Logs every unresolved mismatch to ledgers/divergence.jsonl instead of shipping it silently. Natural upstream companion to parity-check." },
110
114
  { title: "Skill — motion-review", path: ".claude/skills/motion-review/SKILL.md" },
111
115
  { title: "Skill — redesign", path: ".claude/skills/redesign/SKILL.md", summary: "Re-skin an existing surface WITHOUT changing what it does — preserve copy / IA / routes / brand, rebuild only the visual + interaction layer with a fresh (diversified) fingerprint. Distinct from design-exploration (new surface) and component-builder (one component). Adapted BADS-native from Hallmark's redesign verb." },
112
116
  { title: "Prompt — conceptual model", path: "prompts/conceptual-model.md", summary: "Before sketching a product surface, name its domain objects, states, relationships, and vocabulary — Jamie Mill's 'most neglected layer,' wired into Path B as design-exploration step 3.5. Feeds the real-content pool, state patterns, and primitive selection." },
@@ -120,6 +124,8 @@ export const DOCS_INDEX: DocGroup[] = [
120
124
  { title: "Prompt — independent critique", path: "prompts/independent-critique.md" },
121
125
  { title: "Prompt — futures check", path: "prompts/futures-check.md" },
122
126
  { title: "Prompt — persona pressure test", path: "prompts/persona-pressure-test.md" },
127
+ { title: "Prompt — parity check", path: "prompts/parity-check.md", summary: "Deep playbook for the parity-check skill: capture methodology, the pixel-parity.mjs comparison tool, fix order, and the strict zero-diff acceptance bar." },
128
+ { title: "Prompt — figma-to-code", path: "prompts/figma-to-code.md", summary: "Deep playbook for the figma-to-code skill: node-tree enumeration via get_metadata/get_design_context/get_variable_defs, the mapping-table shape, the token-gap resolution decision tree (fix the system, not the instance — parity-check's §4 philosophy applied one trigger earlier), the divergence-ledger entry format, and the conditional Code Connect final step." },
123
129
  ],
124
130
  },
125
131
  {
@@ -137,6 +143,12 @@ export const DOCS_INDEX: DocGroup[] = [
137
143
  { title: "HumanLayer skills evaluation", path: "docs/humanlayer-skills-evaluation.md", summary: "Scouting note (MIT — no adoption blocker): humanlayer/skills. design-control-loop's sensor/controller/actuator vocabulary maps 1:1 onto the Night Shift crew (borrowed as docs/control-loop.md); improve-claude-md's <important if> technique complements the de-blobbing (proposal filed); narrow-react-prop-types wired into Carl. build-iterated-agentic-loop + show-me skipped as redundant." },
138
144
  { title: "jakubkrehel/skills evaluation", path: "docs/jakubkrehel-skills-evaluation.md", summary: "Scouting note (MIT, nothing adopted): a design-engineering skill collection on BADS's home turf — every dimension (UI, type, color, a11y, layout, writing) is already covered by BADS with enforcement (lints/tokens/contracts), not just review prompts. The one real borrow is the source, not a skill: Jakub Krehel's Interfaces magazine added to the Friday research rotation." },
139
145
  { title: "HIGAgentSkills evaluation", path: "docs/hig-agent-skills-evaluation.md", summary: "Scouting note (content not vendored): justinwetch/HIGAgentSkills, a distilled Apple HIG corpus. Blockers — no license + Apple IP, web-vs-native mismatch, and BADS deliberately diverges from Apple. But its tiered routing-index architecture validates BADS's manifest approach and surfaces one real gap (a unified keyword→file lookup), filed as a proposal." },
146
+ { title: "arla6ka/skills (design.how) evaluation", path: "docs/arla6ka-skills-evaluation.md", summary: "Scouting note (MIT, partially adopted): six Claude Code skills that extract a design system FROM an existing shipped app, then migrate every screen onto it — the opposite entry point from BADS's fork-first CLIENT_ONBOARDING.md. Mostly redundant (component-docs, ui-review, design-system-boss all map onto existing BADS mechanisms, several more thoroughly), but checking token-mapping's 'match by purpose, not number' claim against token-nearest.mjs surfaced a real gap: borderRadius was resolved correctly at the resolver level since 2026-09-03 but lint-tokens.js never had a rule querying it. Shipped tailwind-arbitrary-radius + hardcoded-px-radius — 8 real hits in BADS's own primitives. build-design-system's extract-from-existing-app onboarding path and migrate-design-system's coordinator/worker shape are named as real, unscoped gaps." },
147
+ { title: "spec-kit-design-system evaluation", path: "docs/spec-kit-design-system-evaluation.md", summary: "Scouting note (MIT, not adopted as a tool): a GitHub Spec Kit extension arguing agentic design systems solve consumption, not contribution, via a 'Recall→Reuse→Compose→Extend→Create' ladder. Ground-truthed as mostly redundant — BADS's Bucket A/B/C/D + 13-question readiness audit, independent critique + verifier panel + red-team, and intent-driven-context framework already cover it, more thoroughly in most cases. Two real gaps it surfaced: 'fails closed' was only prose convention, not a gate (shipped 2026-09-29 as check:component-audit-trail); Night Shift's Bucket-D builds have no probationary stage before joining the shared registry (filed as a roadmap item)." },
148
+ { title: "shadcn/lint evaluation", path: "docs/shadcn-lint-evaluation.md", summary: "Scouting note (MIT, adopted in full): shadcn/ui's new agent-first Tailwind linter. Ground-truthed all 6 rules against BADS's existing lint suite — 2 partial gaps extended into lint-tokens.js, 4 genuinely novel rules built from scratch (no-restyle, unknown-classes via the real Tailwind compiler, static-classes, inline-styles with BADS's own sanctioned exceptions). Found and fixed a real production bug (a silently-broken dynamic Tailwind class) and several real lint-implementation bugs (comment-scanning false positives, brace-extraction) along the way." },
149
+ { title: "Paper.design evaluation", path: "docs/paper-design-evaluation.md", summary: "Scouting note (proprietary, open alpha — not adopted): a code-native design canvas whose elements are real HTML/CSS/Tailwind, with a bidirectional MCP server (sync tokens, export to React/Tailwind, commit to GitHub). Structurally a better-fitting mechanism than Figma Variables sync for the already-deferred 'Bidirectional Figma ↔ code sync' roadmap item (its 40+ component activation signal has already fired), but blocked from adoption today by alpha instability, proprietary vendor lock-in (tension with BADS's portability principle), and a local-desktop-only MCP server that can never be wired into Night Shift's autonomous pipeline. Revisit after a manual trial and a stable release." },
150
+ { title: "Dessn evaluation", path: "docs/dessn-evaluation.md", summary: "Scouting note (proprietary, early-stage — not adopted): reads a GitHub/GitLab repo read-only, runs the real codebase in the cloud, and lets a designer prototype against the actual components — no separate canvas to sync. Compared directly against paper.design (different half of the same gap: Dessn targets the 'Prototype to production loop' fidelity-capture problem in roadmap-closedloop-import.md item #11, not Path B direction-sketching). Blocked by early-stage maturity, per-seat cost, no agent/MCP surface, and a real per-client trust ask (repo read access, even with SOC2/no-storage assurances). Motivated a new roadmap entry on whether BADS could build a cheaper native equivalent." },
151
+ { title: "Open Design System Bench evaluation", path: "docs/open-design-system-bench-evaluation.md", summary: "Trial note (MIT, adopted as a manual tool, not wired into CI): a harness that runs Claude Code against a component library and grades the output. About $13 of runs found an undeclared peer dependency and an import-path gap in the agent docs; both fixed. After the fix, full context compiled in every run and cut hard-gate failures from 4 of 15 to 1 of 15, with no change in judged design quality." },
140
152
  { title: "Token migration", path: "docs/token-migration.md", summary: "The pattern for renaming/restructuring tokens in a fork without a heroic all-at-once PR: a token-migration.json old→new mapping enforced diff-aware (changed files held to new names, legacy tolerated in untouched files) via pnpm check:token-migration, plus a copy-pasteable mapping table. Adapted from web-common." },
141
153
  { 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." },
142
154
  { title: "Chart design", path: "docs/chart-design.md", summary: "Chart composition rules — grid, axes, labels, legend, tooltip, number formatting, states, motion. The 'data is the only saturated thing' register; companion to the color palette." },
@@ -144,6 +156,12 @@ export const DOCS_INDEX: DocGroup[] = [
144
156
  { title: "Distress & reduced capacity", path: "layer-2-ethics-responsibility/distress-and-capacity.md", summary: "Designing critical flows for users in reduced-capacity states (stress, anxiety, grief, overwhelm) — a STATE, not a persona. The Low-Capacity Test release gate for high-stakes flows, plus the situational-distress persona and shame-free / no-silent-inference rules. Adapted from Matthew Stephens' 2026 mental-health-UX framework." },
145
157
  { 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." },
146
158
  { title: "Corrections log", path: "corrections.md", summary: "Per-fork anti-pattern log. Read before every Path B build." },
159
+ {
160
+ title: "Decision log",
161
+ path: "docs/decision-log.md",
162
+ summary:
163
+ "Generated fast-scan index of decisions already made — tooling/scouting verdicts, anti-pattern corrections, and prototype build verdicts in one place, so an agent can check 'has this been decided before?' without grepping three sources. Never hand-edit; regenerate with `pnpm build:decision-log`.",
164
+ },
147
165
  { title: "Anti-defaults refresh", path: "prompts/anti-defaults-refresh.md", summary: "Quarterly pressure-test of the current anti-defaults." },
148
166
  { title: "Promote corrections", path: "prompts/promote-corrections.md", summary: "Monthly: corrections → lint promotion candidates." },
149
167
  { title: "Recipe miner", path: "prompts/recipe-miner.md", summary: "Monthly: ship-first vs bounce-recipe ranking." },
@@ -164,6 +182,12 @@ export const DOCS_INDEX: DocGroup[] = [
164
182
  { title: "Client onboarding", path: "CLIENT_ONBOARDING.md", summary: "Canonical fork-to-client flow." },
165
183
  { title: "0 · Brand context", path: "prompts/0-brand-context.md" },
166
184
  { title: "0 · Personas", path: "prompts/0-personas.md" },
185
+ {
186
+ title: "0c · Design principles",
187
+ path: "prompts/0c-design-principles.md",
188
+ summary:
189
+ "Writes BRIEF.md's Design principles section — a short, falsifiable decision-making compass, grounded against real-world precedent from principles.design.",
190
+ },
167
191
  { title: "0 · Research", path: "prompts/0-research.md" },
168
192
  { title: "1 · Brand voice", path: "prompts/1-brand-voice.md" },
169
193
  { title: "2 · Microcopy", path: "prompts/2-microcopy.md" },
@@ -227,6 +251,7 @@ export const DOCS_INDEX: DocGroup[] = [
227
251
  { title: "Plan — Best-of-N", path: "docs/plans/2026-09-10-best-of-n.md", summary: "Run one judgment N times and treat disagreement as the signal. Two uses: a three-verifier unanimity panel before Code Review Carl can force-merge a fix, and an eval agreement score that finds the rules repeated runs resolve differently. Rejects a merge agent and majority vote for the gate, and says why." },
228
252
  { title: "Spec — Best-of-N", path: "docs/specs/2026-09-10-best-of-n.md", summary: "The contract for scripts/verifier-panel.mjs (unanimous, fail-closed, distinct lenses, evidence-backed approvals) and scripts/eval-agreement.mjs (check stability, primitive choice, import path, drift rows only from the with-context arm). Records the first measurement: a skill rule sending agents to the package root, 3 of 15 before the fix and 0 of 15 after." },
229
253
  { title: "Roadmap — ClosedLoop import candidates", path: "docs/roadmap-closedloop-import.md", summary: "Fourteen production patterns surfaced by auditing the closedloop-ai GitHub org (40 repos, 17 cloned, 2026-09-03). Three shipped immediately; the rest carry activation signals matching the standard roadmap format." },
254
+ { title: "Spec — Prototype role views", path: "docs/specs/2026-09-28-prototype-role-views.md", summary: "Pre-activation contract for the roadmap's visual-prototyping-surface item: five views (designer canvas, engineer diff, PM flow map, researcher participant mode, QA gate) over one shared state tree, with the load-bearing rule that every edit in every view must resolve to a value tokens.json/component-registry.json already declares legal — no view can produce an off-system state. The QA view makes the constraint's own deliberate-violation test runnable on demand, reusing ux-smoke.mjs and the ux-tests.jsonl findings shape. Not being built yet; written to scope what building it would mean." },
230
255
  ],
231
256
  },
232
257
  ];
@@ -17,10 +17,16 @@ export function prefersReducedMotion(): boolean {
17
17
  );
18
18
  }
19
19
 
20
+ /**
21
+ * Reactive reduced-motion preference. Starts `false` (SSR and first client
22
+ * render agree), then tracks the media query. Guarded on `matchMedia` for
23
+ * environments that don't implement it, matching `prefersReducedMotion()`.
24
+ */
20
25
  export function useReducedMotion(): boolean {
21
26
  const [reduced, setReduced] = React.useState(false);
22
27
 
23
28
  React.useEffect(() => {
29
+ if (typeof window.matchMedia !== "function") return;
24
30
  const mql = window.matchMedia(QUERY);
25
31
  const update = () => setReduced(mql.matches);
26
32
  update();
@@ -0,0 +1,2 @@
1
+ export const clamp = (value: number, min: number, max: number): number =>
2
+ Math.min(max, Math.max(min, value));
@@ -112,6 +112,19 @@ export const Variant_Contained: Story = {
112
112
  </AccordionItem>
113
113
  </Accordion>
114
114
  ),
115
+ // The contained variant's card surface lives on Radix's own Root, which is
116
+ // why accordion.tsx carries a `lint-disable: card-bypass` there instead of
117
+ // composing Card. That escape is a claim, so this is the control group for
118
+ // it: if the surface ever stops being drawn, the reason for the escape is
119
+ // gone and this fails.
120
+ play: async ({ canvasElement }) => {
121
+ const root = canvasElement.querySelector('[data-slot="accordion"]');
122
+ await expect(root).not.toBeNull();
123
+ const cs = getComputedStyle(root as Element);
124
+ await expect(parseFloat(cs.borderTopWidth)).toBeGreaterThan(0);
125
+ await expect(cs.backgroundColor).not.toBe("rgba(0, 0, 0, 0)");
126
+ await expect(parseFloat(cs.borderTopLeftRadius)).toBeGreaterThan(0);
127
+ },
115
128
  };
116
129
 
117
130
  export const Variant_Separated: Story = {
@@ -142,6 +155,52 @@ export const Variant_Separated: Story = {
142
155
  </AccordionItem>
143
156
  </Accordion>
144
157
  ),
158
+ // Same control group as Variant_Contained, for the second card-bypass
159
+ // escape: here the surface is per item, not on the root.
160
+ play: async ({ canvasElement }) => {
161
+ const items = canvasElement.querySelectorAll('[data-slot="accordion-item"]');
162
+ await expect(items.length).toBe(3);
163
+ for (const item of items) {
164
+ const cs = getComputedStyle(item);
165
+ await expect(parseFloat(cs.borderTopWidth)).toBeGreaterThan(0);
166
+ await expect(cs.backgroundColor).not.toBe("rgba(0, 0, 0, 0)");
167
+ await expect(parseFloat(cs.borderTopLeftRadius)).toBeGreaterThan(0);
168
+ }
169
+ },
170
+ };
171
+
172
+ export const Size_Full: Story = {
173
+ parameters: { controls: { disable: true } },
174
+ render: () => (
175
+ <div className="w-full max-w-2xl">
176
+ <Accordion type="single" collapsible className="w-full">
177
+ <AccordionItem value="item-1">
178
+ <AccordionTrigger>Getting started</AccordionTrigger>
179
+ <AccordionContent className="text-muted-foreground">
180
+ Fork the repo, run <code>pnpm install</code>, then{" "}
181
+ <code>pnpm dev</code>. The preview app starts on localhost:3000 and
182
+ the Storybook on localhost:6006.
183
+ </AccordionContent>
184
+ </AccordionItem>
185
+ <AccordionItem value="item-2">
186
+ <AccordionTrigger>Token customization</AccordionTrigger>
187
+ <AccordionContent className="text-muted-foreground">
188
+ All visual decisions live in <code>tokens.json</code>. Edit the
189
+ file and run <code>pnpm build:tokens</code> — the generated CSS
190
+ updates both the preview app and the published package.
191
+ </AccordionContent>
192
+ </AccordionItem>
193
+ <AccordionItem value="item-3">
194
+ <AccordionTrigger>Contributing components</AccordionTrigger>
195
+ <AccordionContent className="text-muted-foreground">
196
+ Run the Component Readiness Audit before building anything new.
197
+ Every primitive needs an accessibility contract, a story matrix, and
198
+ a registry entry before it can ship.
199
+ </AccordionContent>
200
+ </AccordionItem>
201
+ </Accordion>
202
+ </div>
203
+ ),
145
204
  };
146
205
 
147
206
  export const Disabled: Story = {
@@ -5,7 +5,9 @@
5
5
  // left-accent language matches the Sonner toasts so alerts and notifications
6
6
  // read as one family. (Accent/border colors use arbitrary `border-[var(--token)]!`
7
7
  // because the named border-color utilities don't emit a rule in this Tailwind v4
8
- // setup.) Any change to alertVariants should re-snapshot here in Chromatic.
8
+ // setup — an override needs the same `!` importance, e.g. `border-l-transparent!`,
9
+ // see the recipe-note in alert.tsx.) Any change to alertVariants should re-snapshot
10
+ // here in Chromatic.
9
11
  // Dismissible + WithAction: onDismiss renders a top-right × button; action
10
12
  // renders a row below AlertDescription. Both are optional and compose freely.
11
13
  import type { Meta, StoryObj } from "@storybook/react";