@behavioral-agentic-design-system/core 0.29.0 → 0.30.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,334 @@
1
+ "use client"
2
+
3
+ import * as React from "react"
4
+ import { ChevronLeftIcon, ChevronRightIcon, ChevronsRightIcon } from "lucide-react"
5
+ import { cn } from "../../lib/utils"
6
+ import { Button } from "./button"
7
+ import { Checkbox } from "./checkbox"
8
+ import { RadioGroup, RadioGroupItem } from "./radio-group"
9
+ import { Textarea } from "./textarea"
10
+
11
+ // ─── Types ────────────────────────────────────────────────────────────────────
12
+
13
+ export type QuestionType = "single" | "multiple" | "freeform"
14
+
15
+ export interface QuestionnaireOption {
16
+ value: string
17
+ label: string
18
+ }
19
+
20
+ export interface QuestionnaireQuestion {
21
+ /** Unique identifier — used as the key in the answers record. */
22
+ id: string
23
+ /** The question text shown to the user. */
24
+ prompt: string
25
+ /** Input type: radio, multi-checkbox, or freeform textarea. */
26
+ type: QuestionType
27
+ /** Required for type="single" and type="multiple". */
28
+ options?: QuestionnaireOption[]
29
+ /** When true, a Skip button appears alongside Next. */
30
+ skippable?: boolean
31
+ /** Override the Skip button label. Defaults to "Skip". */
32
+ skipLabel?: string
33
+ }
34
+
35
+ export type QuestionnaireAnswers = Record<string, string | string[] | null>
36
+
37
+ export interface QuestionnaireProps {
38
+ /** Ordered list of questions. The component steps through them one at a time. */
39
+ questions: QuestionnaireQuestion[]
40
+ /** Called when every question has been answered or skipped. */
41
+ onComplete?: (answers: QuestionnaireAnswers) => void
42
+ /** Called when a question is skipped — answer is recorded as null. */
43
+ onSkip?: (questionId: string) => void
44
+ className?: string
45
+ }
46
+
47
+ // ─── Internal QuestionStep ────────────────────────────────────────────────────
48
+
49
+ function QuestionStep({
50
+ question,
51
+ answer,
52
+ direction,
53
+ onAnswerChange,
54
+ onAdvance,
55
+ }: {
56
+ question: QuestionnaireQuestion
57
+ answer: string | string[] | null
58
+ direction: "forward" | "backward"
59
+ onAnswerChange: (answer: string | string[] | null) => void
60
+ onAdvance: () => void
61
+ }) {
62
+ const [visible, setVisible] = React.useState(false)
63
+ const stepId = React.useId()
64
+
65
+ // Fade + slide in from the travel direction on mount
66
+ React.useEffect(() => {
67
+ const id = requestAnimationFrame(() => setVisible(true))
68
+ return () => cancelAnimationFrame(id)
69
+ }, [])
70
+
71
+ return (
72
+ <div
73
+ role="group"
74
+ aria-labelledby={`${stepId}-prompt`}
75
+ style={{
76
+ opacity: visible ? 1 : 0,
77
+ transform: visible
78
+ ? "translateX(0)"
79
+ : direction === "forward"
80
+ ? "translateX(16px)"
81
+ : "translateX(-16px)",
82
+ transitionProperty: "opacity, transform",
83
+ transitionDuration: "var(--duration-base)",
84
+ transitionTimingFunction: "var(--ease-out)",
85
+ }}
86
+ >
87
+ <p id={`${stepId}-prompt`} className="mb-4 text-base font-medium text-foreground">
88
+ {question.prompt}
89
+ </p>
90
+
91
+ {/* Single choice — radio group */}
92
+ {question.type === "single" && question.options && (
93
+ <RadioGroup
94
+ value={(answer as string) ?? ""}
95
+ onValueChange={(v) => onAnswerChange(v)}
96
+ className="space-y-2"
97
+ >
98
+ {question.options.map((opt) => (
99
+ <label
100
+ key={opt.value}
101
+ htmlFor={`${stepId}-${opt.value}`}
102
+ className={cn(
103
+ "flex cursor-pointer items-center gap-3 rounded-md border px-3 py-2.5 transition-colors",
104
+ (answer as string) === opt.value
105
+ ? "border-ring bg-primary/5"
106
+ : "border-border hover:bg-accent/50"
107
+ )}
108
+ style={{
109
+ transitionDuration: "var(--duration-fast)",
110
+ transitionTimingFunction: "var(--ease-out)",
111
+ }}
112
+ >
113
+ <RadioGroupItem value={opt.value} id={`${stepId}-${opt.value}`} />
114
+ <span className="text-sm font-medium leading-snug">{opt.label}</span>
115
+ </label>
116
+ ))}
117
+ </RadioGroup>
118
+ )}
119
+
120
+ {/* Multiple choice — checkboxes */}
121
+ {question.type === "multiple" && question.options && (
122
+ <div className="space-y-2">
123
+ {question.options.map((opt) => {
124
+ const selected = Array.isArray(answer) && answer.includes(opt.value)
125
+ return (
126
+ <label
127
+ key={opt.value}
128
+ htmlFor={`${stepId}-${opt.value}`}
129
+ className={cn(
130
+ "flex cursor-pointer items-center gap-3 rounded-md border px-3 py-2.5 transition-colors",
131
+ selected ? "border-ring bg-primary/5" : "border-border hover:bg-accent/50"
132
+ )}
133
+ style={{
134
+ transitionDuration: "var(--duration-fast)",
135
+ transitionTimingFunction: "var(--ease-out)",
136
+ }}
137
+ >
138
+ <Checkbox
139
+ id={`${stepId}-${opt.value}`}
140
+ checked={selected}
141
+ onCheckedChange={(checked) => {
142
+ const current = Array.isArray(answer) ? answer : []
143
+ const next = checked
144
+ ? [...current, opt.value]
145
+ : current.filter((v) => v !== opt.value)
146
+ onAnswerChange(next.length > 0 ? next : null)
147
+ }}
148
+ />
149
+ <span className="text-sm font-medium leading-snug">{opt.label}</span>
150
+ </label>
151
+ )
152
+ })}
153
+ </div>
154
+ )}
155
+
156
+ {/* Freeform — textarea; ⌘/Ctrl+Enter advances */}
157
+ {question.type === "freeform" && (
158
+ <Textarea
159
+ value={(answer as string) ?? ""}
160
+ onChange={(e) => onAnswerChange(e.target.value || null)}
161
+ onKeyDown={(e) => {
162
+ if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
163
+ e.preventDefault()
164
+ onAdvance()
165
+ }
166
+ }}
167
+ placeholder="Your answer…"
168
+ rows={4}
169
+ className="resize-none"
170
+ />
171
+ )}
172
+ </div>
173
+ )
174
+ }
175
+
176
+ // ─── Questionnaire ────────────────────────────────────────────────────────────
177
+
178
+ /**
179
+ * Questionnaire — one-question-at-a-time form primitive.
180
+ *
181
+ * Designed for agentic clarification prompts, onboarding flows, intake forms,
182
+ * and configuration wizards. Supports single-choice (radio), multiple-choice
183
+ * (checkboxes), freeform (textarea), and skippable questions in any combination.
184
+ * Questions animate in from the travel direction on each step change.
185
+ */
186
+ export function Questionnaire({
187
+ questions,
188
+ onComplete,
189
+ onSkip,
190
+ className,
191
+ }: QuestionnaireProps) {
192
+ const [step, setStep] = React.useState(0)
193
+ const [direction, setDirection] = React.useState<"forward" | "backward">("forward")
194
+ const [answers, setAnswers] = React.useState<QuestionnaireAnswers>({})
195
+ const [done, setDone] = React.useState(false)
196
+
197
+ if (questions.length === 0) return null
198
+
199
+ const question = questions[step]
200
+ const currentAnswer = answers[question.id] ?? null
201
+
202
+ const canAdvance =
203
+ question.type === "freeform"
204
+ ? Boolean((currentAnswer as string)?.trim())
205
+ : question.type === "multiple"
206
+ ? Array.isArray(currentAnswer) && currentAnswer.length > 0
207
+ : Boolean(currentAnswer)
208
+
209
+ const handleAnswerChange = (answer: string | string[] | null) => {
210
+ setAnswers((prev) => ({ ...prev, [question.id]: answer }))
211
+ }
212
+
213
+ const advance = (skip = false) => {
214
+ const nextAnswers = skip ? { ...answers, [question.id]: null } : answers
215
+ if (skip) {
216
+ setAnswers(nextAnswers)
217
+ onSkip?.(question.id)
218
+ }
219
+ if (step < questions.length - 1) {
220
+ setDirection("forward")
221
+ setStep((s) => s + 1)
222
+ } else {
223
+ setDone(true)
224
+ onComplete?.(nextAnswers)
225
+ }
226
+ }
227
+
228
+ const goBack = () => {
229
+ setDirection("backward")
230
+ setStep((s) => s - 1)
231
+ }
232
+
233
+ if (done) {
234
+ return (
235
+ <div
236
+ data-slot="questionnaire"
237
+ data-state="complete"
238
+ role="status"
239
+ aria-live="polite"
240
+ className={cn(
241
+ "flex flex-col items-center justify-center gap-2 py-10 text-center",
242
+ className
243
+ )}
244
+ >
245
+ <p className="text-base font-semibold text-foreground">All done!</p>
246
+ <p className="text-sm text-muted-foreground">Your answers have been recorded.</p>
247
+ </div>
248
+ )
249
+ }
250
+
251
+ return (
252
+ <div data-slot="questionnaire" className={cn("flex flex-col gap-5", className)}>
253
+ {/* Progress bar */}
254
+ <div className="flex items-center gap-3">
255
+ <div
256
+ className="h-1 flex-1 overflow-hidden rounded-full bg-muted"
257
+ role="progressbar"
258
+ aria-valuenow={step}
259
+ aria-valuemin={0}
260
+ aria-valuemax={questions.length}
261
+ aria-label="Question progress"
262
+ >
263
+ <div
264
+ className="h-full rounded-full bg-primary"
265
+ style={{
266
+ width: `${(step / questions.length) * 100}%`,
267
+ transitionProperty: "width",
268
+ transitionDuration: "var(--duration-base)",
269
+ transitionTimingFunction: "var(--ease-out)",
270
+ }}
271
+ />
272
+ </div>
273
+ <span
274
+ className="shrink-0 text-xs tabular-nums text-muted-foreground"
275
+ aria-hidden="true"
276
+ >
277
+ {step + 1} / {questions.length}
278
+ </span>
279
+ </div>
280
+
281
+ {/* Question — keyed so the mount animation fires on every step change */}
282
+ <QuestionStep
283
+ key={`q-${step}`}
284
+ question={question}
285
+ answer={currentAnswer}
286
+ direction={direction}
287
+ onAnswerChange={handleAnswerChange}
288
+ onAdvance={() => canAdvance && advance(false)}
289
+ />
290
+
291
+ {/* Navigation */}
292
+ <div className="flex items-center gap-2 pt-1">
293
+ {step > 0 ? (
294
+ <Button
295
+ variant="ghost"
296
+ size="xl"
297
+ onClick={goBack}
298
+ aria-label="Previous question"
299
+ >
300
+ <ChevronLeftIcon className="size-4" strokeWidth={1.5} />
301
+ Back
302
+ </Button>
303
+ ) : (
304
+ <div />
305
+ )}
306
+ <div className="flex-1" />
307
+ {question.skippable && (
308
+ <Button
309
+ variant="ghost"
310
+ size="xl"
311
+ onClick={() => advance(true)}
312
+ >
313
+ {question.skipLabel ?? "Skip"}
314
+ <ChevronsRightIcon className="size-4" strokeWidth={1.5} />
315
+ </Button>
316
+ )}
317
+ <Button
318
+ size="xl"
319
+ disabled={!canAdvance}
320
+ onClick={() => advance(false)}
321
+ >
322
+ {step < questions.length - 1 ? (
323
+ <>
324
+ Next
325
+ <ChevronRightIcon className="size-4" strokeWidth={1.5} />
326
+ </>
327
+ ) : (
328
+ "Finish"
329
+ )}
330
+ </Button>
331
+ </div>
332
+ </div>
333
+ )
334
+ }
@@ -1,3 +1,8 @@
1
+ "use client";
2
+
3
+ // Sidebar builds a React context (createContext) and drives open/collapsed
4
+ // state through useState/useEffect, none of which exist in a server component.
5
+ // See the note in button.tsx for the boundary rule this follows.
1
6
  import * as React from "react";
2
7
  import * as SlotPrimitive from "@radix-ui/react-slot";
3
8
  import { VariantProps, cva } from "class-variance-authority";
@@ -1,3 +1,8 @@
1
+ "use client"
2
+
3
+ // Textarea holds the character-count in React.useState, so it cannot render in
4
+ // a server component at all. See the note in button.tsx for why the components
5
+ // that merely forward an optional callback are left server-renderable.
1
6
  import * as React from "react"
2
7
 
3
8
  import { cn } from "../../lib/utils"
@@ -187,6 +187,8 @@ export const DOCS_INDEX: DocGroup[] = [
187
187
  { title: "Roadmap", path: "docs/roadmap.md", summary: "Layer 2/6/8/9/10 deferred work with the signal that should activate each one." },
188
188
  { title: "Plan — skill package", path: "docs/plans/2026-08-21-skill-package.md", summary: "Approved plan: generate a per-fork, npx-installable agent skill — SKILL.md + drift-proof component recipes + token CSS — so the design system's rules travel into the client product repos where components are consumed. Phase A shipped; see the spec." },
189
189
  { title: "Spec — skill package", path: "docs/specs/2026-08-21-skill-package.md", summary: "The durable contract for packages/skill: generated-only output, usage-focused recipes, ≤2k-word SKILL.md, deterministic builds, the check:skill staleness gate, and the eval --context=skill acceptance instrument." },
190
+ { title: "Plan — self-healing layer", path: "docs/plans/2026-08-21-self-healing-layer.md", summary: "Approved plan: the watch-half of the system — drift ledger, token intent validator, component health score, and a Health surface, assembled from signals BADS already owns; runtime telemetry deliberately deferred behind consent + futures-check." },
191
+ { title: "Spec — self-healing layer", path: "docs/specs/2026-08-21-self-healing-layer.md", summary: "Phase A contract: informational-only health score (Goodhart guard), no runtime telemetry, deterministic visible-copy intent rules, drift-ledger status convention, and the calibration record (6→0 false positives; two scoring bugs caught by face-checking)." },
190
192
  ],
191
193
  },
192
194
  ];
@@ -0,0 +1,66 @@
1
+ /**
2
+ * getIconColor — map a semantic icon *role* to the Tailwind class bound to the
3
+ * matching `--icon-*` token. This is the pattern for giving a custom icon set
4
+ * semantic colors instead of leaving everything to `currentColor`
5
+ * (see CLAUDE.md → Icons, and the `icon-*` token family in tokens.json).
6
+ *
7
+ * Adapted from web-common's `get-icon-color.ts`. Their failure mode: passing a
8
+ * token name (`"icon-brand-primary"`) or a raw Tailwind class (`"text-brand-…"`)
9
+ * instead of a semantic role falls through the map and renders the icon
10
+ * UNSTYLED — three call sites did exactly that and nothing caught it. Two guards
11
+ * here close that gap:
12
+ * 1. The input is the typed `IconRole` union, so a wrong string literal fails
13
+ * to type-check at compile time (better than a runtime fallthrough).
14
+ * 2. `pnpm lint:icon-color` catches the any-typed / prop-forwarded call sites a
15
+ * fork might add where the type can't see the value.
16
+ */
17
+ export const ICON_ROLES = [
18
+ "default",
19
+ "muted",
20
+ "primary",
21
+ "success",
22
+ "warning",
23
+ "error",
24
+ "info",
25
+ "inverse",
26
+ "disabled",
27
+ ] as const;
28
+
29
+ export type IconRole = (typeof ICON_ROLES)[number];
30
+
31
+ const ICON_COLOR_CLASS: Record<IconRole, string> = {
32
+ default: "text-icon-default",
33
+ muted: "text-icon-muted",
34
+ primary: "text-icon-primary",
35
+ success: "text-icon-success",
36
+ warning: "text-icon-warning",
37
+ error: "text-icon-error",
38
+ info: "text-icon-info",
39
+ inverse: "text-icon-inverse",
40
+ disabled: "text-icon-disabled",
41
+ };
42
+
43
+ /** Runtime guard for the any-typed boundary (a prop from JSON, a CMS field, etc.). */
44
+ export function isIconRole(value: unknown): value is IconRole {
45
+ return typeof value === "string" && (ICON_ROLES as readonly string[]).includes(value);
46
+ }
47
+
48
+ /**
49
+ * Returns the `text-icon-*` class for a semantic role. Pass a ROLE (`"error"`),
50
+ * never a token name (`"icon-error"`) or a class (`"text-icon-error"`). An
51
+ * unrecognized value logs a dev warning and falls back to `"default"` so the
52
+ * icon is never rendered invisibly; in production it falls back silently.
53
+ */
54
+ export function getIconColor(role: IconRole): string {
55
+ const cls = ICON_COLOR_CLASS[role];
56
+ if (!cls) {
57
+ if (typeof process !== "undefined" && process.env?.NODE_ENV !== "production") {
58
+ // eslint-disable-next-line no-console
59
+ console.warn(
60
+ `getIconColor: "${String(role)}" is not an icon role. Pass one of: ${ICON_ROLES.join(", ")}. Falling back to "default".`,
61
+ );
62
+ }
63
+ return ICON_COLOR_CLASS.default;
64
+ }
65
+ return cls;
66
+ }
@@ -1,3 +1,6 @@
1
+ // Button is a client component: it always attaches its own onClick/onKeyDown to
2
+ // guard the aria-disabled pattern, so it cannot be rendered from a React Server
3
+ // Component. See the note at the top of components/ui/button.tsx.
1
4
  // Motion: base transition narrowed transition-all → transition-colors (Vercel/Rauno "list only the properties you animate" + BADS microanimation rule). Focus ring now appears instantly rather than fading — strictly better for a11y.
2
5
  import { Meta, StoryObj } from "@storybook/react"
3
6
  import { userEvent, within, expect, fn } from "storybook/test"
@@ -1,3 +1,6 @@
1
+ // Input itself is server-renderable: it attaches no handler of its own and only
2
+ // forwards the caller's onChange. The clear affordance is the client half, split
3
+ // into components/ui/input-clear-button.tsx — see the Clearable stories below.
1
4
  import * as React from "react";
2
5
  import { Meta, StoryObj } from "@storybook/react";
3
6
  import { CalendarIcon, MailIcon, SearchIcon } from "lucide-react";
@@ -0,0 +1,53 @@
1
+ // The client half of Input's clearable affordance. It lives in its own module so
2
+ // that a plain <Input /> stays renderable from a React Server Component and
3
+ // costs a consumer nothing on the client — only <Input clearable /> pulls this
4
+ // in. Storied separately so visual regression covers the button on its own,
5
+ // including the offset variant used when Input also has a rightSection.
6
+ import type { Meta, StoryObj } from "@storybook/react";
7
+ import { InputClearButton } from "@behavioral-agentic-design-system/core/components/ui/input-clear-button";
8
+ import { Input } from "@behavioral-agentic-design-system/core/components/ui/input";
9
+ import { Label } from "@behavioral-agentic-design-system/core/components/ui/label";
10
+
11
+ const meta: Meta<typeof InputClearButton> = {
12
+ title: "Components/InputClearButton",
13
+ component: InputClearButton,
14
+ parameters: { layout: "centered" },
15
+ tags: ["autodocs"],
16
+ };
17
+
18
+ export default meta;
19
+ type Story = StoryObj<typeof meta>;
20
+
21
+ export const Default: Story = {
22
+ render: () => (
23
+ // Positioned absolutely against its input, so it needs a relative box to
24
+ // sit in even when shown in isolation.
25
+ <div className="relative h-9 w-[240px] rounded-md border border-input">
26
+ <InputClearButton className="right-1.5" />
27
+ </div>
28
+ ),
29
+ };
30
+
31
+ export const OffsetForRightSection: Story = {
32
+ name: "Offset (input has a rightSection)",
33
+ render: () => (
34
+ <div className="relative h-9 w-[240px] rounded-md border border-input">
35
+ <InputClearButton className="right-8" />
36
+ <span className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3 text-sm text-muted-foreground">
37
+ USD
38
+ </span>
39
+ </div>
40
+ ),
41
+ };
42
+
43
+ export const RealisticUse: Story = {
44
+ render: () => (
45
+ <div className="flex w-[320px] flex-col gap-3">
46
+ <Label htmlFor="search-city">Search by city</Label>
47
+ <Input id="search-city" clearable value="Nashville, TN" readOnly />
48
+ <p className="text-sm text-muted-foreground">
49
+ The clear button appears once the field has a value.
50
+ </p>
51
+ </div>
52
+ ),
53
+ };
@@ -25,8 +25,12 @@ const meta: Meta<typeof MultiSelect> = {
25
25
  // <button> (valid per ARIA). X-remove pill buttons live in a sibling z-10 span —
26
26
  // not nested inside the trigger button — so axe nested-interactive never fires.
27
27
  // When disabled=true the X buttons are not rendered (disabled form controls must
28
- // not contain interactive elements that are still reachable).
29
- component: "Multi-value combobox. Transparent full-area trigger <button> ensures aria-expanded is ARIA-valid; pill X-remove buttons are siblings (not nested) so no axe nested-interactive violation. Pill badges use py-0 min-h-6 so the content area is exactly 24px; X buttons use h-6 w-6 to meet the 24×24 WCAG 2.2 SC 2.5.8 target-size minimum (self-stretch would only fill the inner content-box, which is 20px when py-0.5 is present). When disabled, X-remove buttons are hidden — a disabled field cannot have interactive children.",
28
+ // not contain interactive elements that are still reachable). The container gets
29
+ // aria-disabled="true" so axe exempts its children from contrast checks (WCAG
30
+ // 1.4.3 inactive UI component exception). The trigger is NOT wrapped in
31
+ // PopoverTrigger when disabled — this prevents Radix from adding aria-controls
32
+ // pointing to an unmounted PopoverContent (axe aria-valid-attr-value).
33
+ component: "Multi-value combobox. Transparent full-area trigger <button> ensures aria-expanded is ARIA-valid; pill X-remove buttons are siblings (not nested) so no axe nested-interactive violation. Pill badges use py-0 min-h-6 so the content area is exactly 24px; X buttons use h-6 w-6 to meet the 24×24 WCAG 2.2 SC 2.5.8 target-size minimum (self-stretch would only fill the inner content-box, which is 20px when py-0.5 is present). When disabled, X-remove buttons are hidden and the trigger skips PopoverTrigger so Radix does not add aria-controls to a non-existent popover element.",
30
34
  },
31
35
  },
32
36
  },