@behavioral-agentic-design-system/core 0.27.0 → 0.28.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,388 @@
1
+ "use client"
2
+
3
+ import * as React from "react"
4
+ import {
5
+ type ColumnDef,
6
+ type SortingState,
7
+ type RowSelectionState,
8
+ flexRender,
9
+ getCoreRowModel,
10
+ getSortedRowModel,
11
+ getPaginationRowModel,
12
+ useReactTable,
13
+ } from "@tanstack/react-table"
14
+ import { ChevronUpIcon, ChevronDownIcon, ChevronsUpDownIcon } from "lucide-react"
15
+ import { cva, type VariantProps } from "class-variance-authority"
16
+
17
+ import { cn } from "../../lib/utils"
18
+ import { Button } from "./button"
19
+ import { Checkbox } from "./checkbox"
20
+ import {
21
+ Table,
22
+ TableHeader,
23
+ TableBody,
24
+ TableRow,
25
+ TableHead,
26
+ TableCell,
27
+ } from "./table"
28
+
29
+ // Re-export ColumnDef so consumers don't need a direct @tanstack/react-table import
30
+ export type { ColumnDef }
31
+
32
+ // ---------------------------------------------------------------------------
33
+ // Density variant
34
+ // ---------------------------------------------------------------------------
35
+
36
+ const cellVariants = cva("", {
37
+ variants: {
38
+ density: {
39
+ comfortable: "px-4 py-3",
40
+ dense: "px-3 py-2",
41
+ },
42
+ },
43
+ defaultVariants: {
44
+ density: "comfortable",
45
+ },
46
+ })
47
+
48
+ // ---------------------------------------------------------------------------
49
+ // Props
50
+ // ---------------------------------------------------------------------------
51
+
52
+ export interface DataTablePaginationOptions {
53
+ /** Number of rows per page. Defaults to 10. */
54
+ pageSize?: number
55
+ }
56
+
57
+ export interface DataTableProps<TData> extends VariantProps<typeof cellVariants> {
58
+ columns: ColumnDef<TData>[]
59
+ data: TData[]
60
+ /**
61
+ * Enable column header sorting. Defaults to true.
62
+ */
63
+ sorting?: boolean
64
+ /**
65
+ * When provided, enables built-in pagination. Pass `{}` to use the default
66
+ * pageSize of 10, or `{ pageSize: N }` to override.
67
+ */
68
+ pagination?: DataTablePaginationOptions
69
+ /**
70
+ * When true, prepends a checkbox column for row selection. Tracks selection
71
+ * internally; expose controlled selection by lifting state via a columns
72
+ * definition if needed.
73
+ */
74
+ rowSelection?: boolean
75
+ /**
76
+ * Callback fired when a data row is clicked. Does NOT constitute a
77
+ * selection — pair with rowSelection for accessible multi-select. When
78
+ * provided, rows receive `cursor-pointer` and `data-clickable`.
79
+ */
80
+ onRowClick?: (row: TData) => void
81
+ /**
82
+ * Content to display when the data array is empty.
83
+ * Defaults to the text "No results."
84
+ */
85
+ emptyMessage?: React.ReactNode
86
+ className?: string
87
+ }
88
+
89
+ // ---------------------------------------------------------------------------
90
+ // Sort icon
91
+ // ---------------------------------------------------------------------------
92
+
93
+ function SortIcon({
94
+ direction,
95
+ }: {
96
+ direction: "asc" | "desc" | false
97
+ }) {
98
+ const iconProps = {
99
+ strokeWidth: 1.5 as const,
100
+ className: "size-4 shrink-0",
101
+ }
102
+
103
+ // Wrapper carries the motion transition so the icon itself gets the effect
104
+ const wrapperStyle: React.CSSProperties = {
105
+ transitionDuration: "var(--duration-fast)",
106
+ transitionTimingFunction: "var(--ease-out)",
107
+ transitionProperty: "opacity, transform",
108
+ }
109
+
110
+ if (direction === "asc") {
111
+ return (
112
+ <span
113
+ aria-hidden="true"
114
+ className="inline-flex text-foreground"
115
+ style={wrapperStyle}
116
+ >
117
+ <ChevronUpIcon {...iconProps} />
118
+ </span>
119
+ )
120
+ }
121
+ if (direction === "desc") {
122
+ return (
123
+ <span
124
+ aria-hidden="true"
125
+ className="inline-flex text-foreground"
126
+ style={wrapperStyle}
127
+ >
128
+ <ChevronDownIcon {...iconProps} />
129
+ </span>
130
+ )
131
+ }
132
+ return (
133
+ <span
134
+ aria-hidden="true"
135
+ className="inline-flex text-muted-foreground/60"
136
+ style={wrapperStyle}
137
+ >
138
+ <ChevronsUpDownIcon {...iconProps} />
139
+ </span>
140
+ )
141
+ }
142
+
143
+ // ---------------------------------------------------------------------------
144
+ // SELECT_ALL_COLUMN_ID
145
+ // ---------------------------------------------------------------------------
146
+
147
+ const SELECT_COLUMN_ID = "__select__"
148
+
149
+ function buildSelectionColumn<TData>(): ColumnDef<TData> {
150
+ return {
151
+ id: SELECT_COLUMN_ID,
152
+ header: ({ table }) => (
153
+ <Checkbox
154
+ checked={
155
+ table.getIsAllPageRowsSelected()
156
+ ? true
157
+ : table.getIsSomePageRowsSelected()
158
+ ? "indeterminate"
159
+ : false
160
+ }
161
+ onCheckedChange={(value) =>
162
+ table.toggleAllPageRowsSelected(Boolean(value))
163
+ }
164
+ aria-label="Select all rows on this page"
165
+ className="size-4"
166
+ />
167
+ ),
168
+ cell: ({ row }) => (
169
+ <Checkbox
170
+ checked={row.getIsSelected()}
171
+ onCheckedChange={(value) => row.toggleSelected(Boolean(value))}
172
+ aria-label={`Select row ${row.index + 1}`}
173
+ className="size-4"
174
+ />
175
+ ),
176
+ enableSorting: false,
177
+ enableHiding: false,
178
+ size: 40,
179
+ }
180
+ }
181
+
182
+ // ---------------------------------------------------------------------------
183
+ // DataTable
184
+ // ---------------------------------------------------------------------------
185
+
186
+ function DataTable<TData>({
187
+ columns,
188
+ data,
189
+ sorting: sortingEnabled = true,
190
+ pagination: paginationOptions,
191
+ rowSelection: rowSelectionEnabled = false,
192
+ onRowClick,
193
+ emptyMessage = "No results.",
194
+ density = "comfortable",
195
+ className,
196
+ }: DataTableProps<TData>) {
197
+ const [sortingState, setSortingState] = React.useState<SortingState>([])
198
+ const [rowSelectionState, setRowSelectionState] =
199
+ React.useState<RowSelectionState>({})
200
+
201
+ const resolvedColumns = React.useMemo(() => {
202
+ if (rowSelectionEnabled) {
203
+ return [buildSelectionColumn<TData>(), ...columns]
204
+ }
205
+ return columns
206
+ }, [columns, rowSelectionEnabled])
207
+
208
+ const paginationEnabled = paginationOptions !== undefined
209
+ const pageSize = paginationOptions?.pageSize ?? 10
210
+
211
+ const table = useReactTable<TData>({
212
+ data,
213
+ columns: resolvedColumns,
214
+ state: {
215
+ sorting: sortingState,
216
+ rowSelection: rowSelectionState,
217
+ },
218
+ enableSorting: sortingEnabled,
219
+ enableRowSelection: rowSelectionEnabled,
220
+ onSortingChange: setSortingState,
221
+ onRowSelectionChange: setRowSelectionState,
222
+ getCoreRowModel: getCoreRowModel(),
223
+ getSortedRowModel: sortingEnabled ? getSortedRowModel() : undefined,
224
+ getPaginationRowModel: paginationEnabled
225
+ ? getPaginationRowModel()
226
+ : undefined,
227
+ initialState: {
228
+ pagination: {
229
+ pageSize,
230
+ },
231
+ },
232
+ })
233
+
234
+ const cellClass = cellVariants({ density })
235
+
236
+ return (
237
+ <div
238
+ data-slot="data-table"
239
+ className={cn("rounded-md border bg-card overflow-hidden", className)}
240
+ >
241
+ {/* Scrollable table wrapper */}
242
+ <div className="overflow-x-auto">
243
+ <Table role="grid">
244
+ <TableHeader>
245
+ {table.getHeaderGroups().map((headerGroup) => (
246
+ <TableRow key={headerGroup.id}>
247
+ {headerGroup.headers.map((header) => {
248
+ const isSortable =
249
+ sortingEnabled && header.column.getCanSort()
250
+ const sortDir = header.column.getIsSorted()
251
+ const ariaSortMap = {
252
+ asc: "ascending",
253
+ desc: "descending",
254
+ } as const
255
+
256
+ return (
257
+ <TableHead
258
+ key={header.id}
259
+ style={
260
+ header.column.columnDef.size !== undefined
261
+ ? { width: header.column.columnDef.size }
262
+ : undefined
263
+ }
264
+ className={cn(
265
+ cellClass,
266
+ isSortable &&
267
+ "cursor-pointer select-none hover:text-foreground",
268
+ "text-muted-foreground font-medium text-sm"
269
+ )}
270
+ aria-sort={
271
+ isSortable
272
+ ? sortDir
273
+ ? ariaSortMap[sortDir]
274
+ : "none"
275
+ : undefined
276
+ }
277
+ onClick={
278
+ isSortable
279
+ ? header.column.getToggleSortingHandler()
280
+ : undefined
281
+ }
282
+ tabIndex={isSortable ? 0 : undefined}
283
+ onKeyDown={
284
+ isSortable
285
+ ? (e) => {
286
+ if (e.key === "Enter" || e.key === " ") {
287
+ e.preventDefault()
288
+ header.column.getToggleSortingHandler()?.(e)
289
+ }
290
+ }
291
+ : undefined
292
+ }
293
+ >
294
+ {header.isPlaceholder ? null : (
295
+ <span className="inline-flex items-center gap-1.5">
296
+ {flexRender(
297
+ header.column.columnDef.header,
298
+ header.getContext()
299
+ )}
300
+ {isSortable && <SortIcon direction={sortDir} />}
301
+ </span>
302
+ )}
303
+ </TableHead>
304
+ )
305
+ })}
306
+ </TableRow>
307
+ ))}
308
+ </TableHeader>
309
+
310
+ <TableBody>
311
+ {table.getRowModel().rows.length > 0 ? (
312
+ table.getRowModel().rows.map((row) => (
313
+ <TableRow
314
+ key={row.id}
315
+ data-state={row.getIsSelected() ? "selected" : undefined}
316
+ data-clickable={onRowClick ? true : undefined}
317
+ className={cn(
318
+ onRowClick && "cursor-pointer",
319
+ row.getIsSelected() && "bg-muted"
320
+ )}
321
+ onClick={onRowClick ? () => onRowClick(row.original) : undefined}
322
+ >
323
+ {row.getVisibleCells().map((cell) => (
324
+ <TableCell
325
+ key={cell.id}
326
+ className={cn(cellClass)}
327
+ >
328
+ {flexRender(
329
+ cell.column.columnDef.cell,
330
+ cell.getContext()
331
+ )}
332
+ </TableCell>
333
+ ))}
334
+ </TableRow>
335
+ ))
336
+ ) : (
337
+ <tr>
338
+ <td
339
+ colSpan={resolvedColumns.length}
340
+ className="py-12 text-center text-sm text-muted-foreground"
341
+ >
342
+ {emptyMessage}
343
+ </td>
344
+ </tr>
345
+ )}
346
+ </TableBody>
347
+ </Table>
348
+ </div>
349
+
350
+ {/* Pagination footer */}
351
+ {paginationEnabled && (
352
+ <div className="flex items-center justify-between border-t px-4 py-3">
353
+ <p className="text-sm text-muted-foreground tabular-nums">
354
+ {(() => {
355
+ const { pageIndex, pageSize: ps } = table.getState().pagination
356
+ const total = table.getFilteredRowModel().rows.length
357
+ const from = total === 0 ? 0 : pageIndex * ps + 1
358
+ const to = Math.min((pageIndex + 1) * ps, total)
359
+ return `${from}–${to} of ${total} row${total !== 1 ? "s" : ""}`
360
+ })()}
361
+ </p>
362
+ <div className="flex items-center gap-2">
363
+ <Button
364
+ variant="outline"
365
+ size="sm"
366
+ onClick={() => table.previousPage()}
367
+ disabled={!table.getCanPreviousPage()}
368
+ aria-label="Go to previous page"
369
+ >
370
+ Previous
371
+ </Button>
372
+ <Button
373
+ variant="outline"
374
+ size="sm"
375
+ onClick={() => table.nextPage()}
376
+ disabled={!table.getCanNextPage()}
377
+ aria-label="Go to next page"
378
+ >
379
+ Next
380
+ </Button>
381
+ </div>
382
+ </div>
383
+ )}
384
+ </div>
385
+ )
386
+ }
387
+
388
+ export { DataTable }
@@ -0,0 +1,184 @@
1
+ "use client";
2
+
3
+ import * as React from "react";
4
+
5
+ import { cn } from "../../lib/utils";
6
+
7
+ /**
8
+ * Standalone focus-containment utility. Traps Tab/Shift+Tab cycling within
9
+ * its children while `active` is true, and calls `onEscapeKeyDown` when
10
+ * Escape is pressed.
11
+ *
12
+ * Use this when a custom overlay, inline drawer, or panel needs focus
13
+ * containment but doesn't warrant the full Dialog or Sheet weight. All
14
+ * BADS Radix-based components (Dialog, Sheet) trap focus internally — this
15
+ * is for the cases that fall between.
16
+ *
17
+ * WCAG 2.1.2 No Keyboard Trap: trapping focus alone is compliant only when
18
+ * an escape mechanism exists. Wire `onEscapeKeyDown` to close the container
19
+ * so keyboard users can always leave.
20
+ *
21
+ * <FocusTrap active={open} onEscapeKeyDown={() => setOpen(false)}>
22
+ * <div role="dialog" aria-modal="true" aria-labelledby="dlg-title">
23
+ * <FocusTrapInitialFocus />
24
+ * <h2 id="dlg-title">Confirm</h2>
25
+ * <button>OK</button>
26
+ * <button onClick={() => setOpen(false)}>Cancel</button>
27
+ * </div>
28
+ * </FocusTrap>
29
+ *
30
+ * Focus cycling: on Tab from the last focusable element, cycles back to the
31
+ * first; on Shift+Tab from the first, cycles to the last. The cycle includes
32
+ * all focusable elements: <button>, <a href>, <input>, <select>, <textarea>,
33
+ * and any element with tabIndex >= 0.
34
+ *
35
+ * FocusTrapInitialFocus: place anywhere inside FocusTrap. When the trap
36
+ * activates, focus moves to the nearest [data-focus-trap-initial] element
37
+ * instead of the first focusable element in DOM order. Useful when the
38
+ * visually primary action isn't the first tabbable in the DOM.
39
+ *
40
+ * Zero dependencies. Reduced-motion safety: no animation — the focus ring
41
+ * uses the existing CSS base layer (SC 2.4.7 + 2.4.13 enforced).
42
+ * Microanimation: no interactive state changes on this wrapper; rule
43
+ * vacuously satisfied (same exemption as VisuallyHidden, SkipLink).
44
+ */
45
+
46
+ const FOCUSABLE_SELECTORS = [
47
+ "button:not([disabled])",
48
+ "a[href]",
49
+ "input:not([disabled])",
50
+ "select:not([disabled])",
51
+ "textarea:not([disabled])",
52
+ "[tabindex]:not([tabindex='-1'])",
53
+ "details > summary:not([disabled])",
54
+ ].join(",");
55
+
56
+ export interface FocusTrapProps extends React.ComponentProps<"div"> {
57
+ /** Whether the trap is active. When false the component renders its
58
+ * children unchanged with no keyboard interception. */
59
+ active?: boolean;
60
+ /** Whether Tab cycles back to the first focusable after reaching the last
61
+ * (and vice versa for Shift+Tab). Default: true. */
62
+ loop?: boolean;
63
+ /** Called when Escape is pressed while the trap is active.
64
+ * Required for WCAG 2.1.2 compliance: always wire this to close the
65
+ * containing overlay so keyboard users can leave. */
66
+ onEscapeKeyDown?: (event: KeyboardEvent) => void;
67
+ }
68
+
69
+ function FocusTrap({
70
+ active = true,
71
+ loop = true,
72
+ onEscapeKeyDown,
73
+ className,
74
+ children,
75
+ ...props
76
+ }: FocusTrapProps) {
77
+ const containerRef = React.useRef<HTMLDivElement>(null);
78
+
79
+ // On activation, move focus to the first focusable element (or the
80
+ // FocusTrapInitialFocus marker if one is present).
81
+ React.useEffect(() => {
82
+ if (!active || !containerRef.current) return;
83
+
84
+ const container = containerRef.current;
85
+
86
+ // Prefer the explicit initial-focus marker if present.
87
+ const initialTarget = container.querySelector<HTMLElement>(
88
+ "[data-focus-trap-initial]"
89
+ );
90
+ const firstFocusable = container.querySelectorAll<HTMLElement>(
91
+ FOCUSABLE_SELECTORS
92
+ )[0];
93
+
94
+ const target = initialTarget ?? firstFocusable;
95
+ // Defer by one tick so the container is in the DOM before focusing.
96
+ const id = setTimeout(() => target?.focus(), 0);
97
+ return () => clearTimeout(id);
98
+ }, [active]);
99
+
100
+ // Handle Tab and Escape keydown events.
101
+ React.useEffect(() => {
102
+ if (!active || !containerRef.current) return;
103
+
104
+ const container = containerRef.current;
105
+
106
+ function handleKeyDown(event: KeyboardEvent) {
107
+ if (event.key === "Escape") {
108
+ onEscapeKeyDown?.(event);
109
+ return;
110
+ }
111
+
112
+ if (event.key !== "Tab") return;
113
+
114
+ const focusable = Array.from(
115
+ container.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTORS)
116
+ ).filter((el) => !el.closest("[inert]") && !el.closest("[hidden]"));
117
+
118
+ if (focusable.length === 0) {
119
+ event.preventDefault();
120
+ return;
121
+ }
122
+
123
+ const first = focusable[0];
124
+ const last = focusable[focusable.length - 1];
125
+ const active = document.activeElement as HTMLElement | null;
126
+
127
+ if (event.shiftKey) {
128
+ // Shift+Tab: if focus is on the first element, cycle to the last.
129
+ if (loop && active === first) {
130
+ event.preventDefault();
131
+ last.focus();
132
+ }
133
+ } else {
134
+ // Tab: if focus is on the last element, cycle to the first.
135
+ if (loop && active === last) {
136
+ event.preventDefault();
137
+ first.focus();
138
+ }
139
+ }
140
+ }
141
+
142
+ container.addEventListener("keydown", handleKeyDown);
143
+ return () => container.removeEventListener("keydown", handleKeyDown);
144
+ }, [active, loop, onEscapeKeyDown]);
145
+
146
+ return (
147
+ <div
148
+ data-slot="focus-trap"
149
+ data-state={active ? "active" : "inactive"}
150
+ className={cn(className)}
151
+ ref={containerRef}
152
+ {...props}
153
+ >
154
+ {children}
155
+ </div>
156
+ );
157
+ }
158
+
159
+ /**
160
+ * Place this element anywhere inside a FocusTrap. When the trap activates,
161
+ * focus moves here instead of to the first focusable in DOM order.
162
+ *
163
+ * The element itself is not focusable (tabIndex=-1, not in the Tab cycle)
164
+ * — it is only a focus-target marker that FocusTrap finds at activation.
165
+ * Its purpose is to ensure the visually primary element gets initial focus
166
+ * regardless of its DOM position.
167
+ */
168
+ function FocusTrapInitialFocus({
169
+ className,
170
+ ...props
171
+ }: React.ComponentProps<"span">) {
172
+ return (
173
+ <span
174
+ data-slot="focus-trap-initial-focus"
175
+ data-focus-trap-initial
176
+ tabIndex={-1}
177
+ className={cn("sr-only", className)}
178
+ aria-hidden
179
+ {...props}
180
+ />
181
+ );
182
+ }
183
+
184
+ export { FocusTrap, FocusTrapInitialFocus };
@@ -115,3 +115,10 @@ export * from "./skip-link";
115
115
  export * from "./timer";
116
116
  export * from "./signature-pad";
117
117
  export * from "./floating-action-button";
118
+ export * from "./clipboard";
119
+ export * from "./chat-bubble";
120
+ export * from "./data-table";
121
+ export * from "./focus-trap";
122
+ export * from "./mark";
123
+ export * from "./rolling-number";
124
+ export * from "./ai-badge";
@@ -0,0 +1,69 @@
1
+ "use client";
2
+
3
+ import * as React from "react";
4
+ import { cva, type VariantProps } from "class-variance-authority";
5
+
6
+ import { cn } from "../../lib/utils";
7
+
8
+ /**
9
+ * Semantic <mark> wrapper for editorial inline emphasis — the static
10
+ * counterpart to Highlight (which dynamically marks search-query matches).
11
+ *
12
+ * Use Mark when an author intentionally annotates a phrase as relevant:
13
+ *
14
+ * <p>
15
+ * The key constraint is <Mark>token discipline</Mark> — every color,
16
+ * spacing, and radius traces back to a single authoritative source.
17
+ * </p>
18
+ *
19
+ * Display-only: <mark> carries no interactive role, no focus contract, and
20
+ * no keyboard target. Most screen readers do not announce it as highlighted —
21
+ * never make the mark the sole carrier of meaning. Pair it with surrounding
22
+ * prose context.
23
+ *
24
+ * Microanimation: no interactive states; rule vacuously satisfied (same
25
+ * exemption as Blockquote, Code). No motion declarations needed.
26
+ *
27
+ * The `default` variant uses bg-warning/25 — a pale amber wash that reads
28
+ * as a physical highlighter across both light and dark themes. The
29
+ * foreground color is always `text-foreground` (the computed near-black or
30
+ * near-white), so WCAG contrast depends on the surrounding text, not the
31
+ * mark background.
32
+ */
33
+
34
+ const markVariants = cva(
35
+ "rounded-[2px] px-[0.2em] py-[0.05em]",
36
+ {
37
+ variants: {
38
+ variant: {
39
+ /** Pale amber/warning wash — the physical-highlighter register. */
40
+ default: "bg-warning/25 text-foreground",
41
+ /** Pale primary tint — use for branded or navigational emphasis. */
42
+ primary: "bg-primary/20 text-foreground",
43
+ /** Muted secondary surface — use for neutral, non-semantic callout. */
44
+ secondary: "bg-secondary text-secondary-foreground",
45
+ },
46
+ },
47
+ defaultVariants: {
48
+ variant: "default",
49
+ },
50
+ }
51
+ );
52
+
53
+ export interface MarkProps
54
+ extends React.ComponentProps<"mark">,
55
+ VariantProps<typeof markVariants> {}
56
+
57
+ function Mark({ className, variant, children, ...props }: MarkProps) {
58
+ return (
59
+ <mark
60
+ data-slot="mark"
61
+ className={cn(markVariants({ variant }), className)}
62
+ {...props}
63
+ >
64
+ {children}
65
+ </mark>
66
+ );
67
+ }
68
+
69
+ export { Mark, markVariants };