@behavioral-agentic-design-system/core 0.23.0 → 0.26.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 (139) hide show
  1. package/package.json +8 -4
  2. package/scripts/build-tokens.cjs +79 -5
  3. package/src/app/preview/components/page.tsx +4760 -213
  4. package/src/app/shell.tsx +18 -6
  5. package/src/components/customize/brand-mark-section.tsx +1 -1
  6. package/src/components/customize-tab.tsx +2 -2
  7. package/src/components/home-tab.tsx +2 -2
  8. package/src/components/ui/action-bar.tsx +142 -0
  9. package/src/components/ui/affix.tsx +109 -0
  10. package/src/components/ui/alert.tsx +37 -3
  11. package/src/components/ui/anchor.tsx +136 -0
  12. package/src/components/ui/angle-slider.tsx +265 -0
  13. package/src/components/ui/autocomplete.tsx +223 -0
  14. package/src/components/ui/avatar.tsx +8 -2
  15. package/src/components/ui/blockquote.tsx +112 -0
  16. package/src/components/ui/bottom-navigation.tsx +144 -0
  17. package/src/components/ui/burger.tsx +117 -0
  18. package/src/components/ui/button.tsx +101 -3
  19. package/src/components/ui/calendar.tsx +1 -1
  20. package/src/components/ui/card.tsx +43 -5
  21. package/src/components/ui/carousel.tsx +10 -5
  22. package/src/components/ui/cascader.tsx +253 -0
  23. package/src/components/ui/checkbox-card.tsx +176 -0
  24. package/src/components/ui/checkbox-group.tsx +231 -0
  25. package/src/components/ui/checkbox.tsx +14 -3
  26. package/src/components/ui/chip.tsx +143 -0
  27. package/src/components/ui/circular-progress.tsx +2 -2
  28. package/src/components/ui/color-swatch.tsx +73 -0
  29. package/src/components/ui/copy-button.tsx +21 -4
  30. package/src/components/ui/data-list.tsx +169 -0
  31. package/src/components/ui/date-picker.tsx +6 -3
  32. package/src/components/ui/date-range-picker.tsx +6 -3
  33. package/src/components/ui/fieldset.tsx +8 -2
  34. package/src/components/ui/float-label.tsx +114 -0
  35. package/src/components/ui/floating-panel.tsx +129 -0
  36. package/src/components/ui/format-number.tsx +122 -0
  37. package/src/components/ui/highlight.tsx +85 -0
  38. package/src/components/ui/image.tsx +195 -0
  39. package/src/components/ui/index.ts +52 -0
  40. package/src/components/ui/indicator.tsx +2 -2
  41. package/src/components/ui/input-group.tsx +11 -1
  42. package/src/components/ui/input.tsx +48 -4
  43. package/src/components/ui/kbd.tsx +1 -1
  44. package/src/components/ui/link.tsx +158 -0
  45. package/src/components/ui/listbox.tsx +426 -0
  46. package/src/components/ui/loading-overlay.tsx +80 -0
  47. package/src/components/ui/marquee.tsx +193 -0
  48. package/src/components/ui/masonry.tsx +164 -0
  49. package/src/components/ui/meter.tsx +186 -0
  50. package/src/components/ui/motion-toggle.tsx +170 -0
  51. package/src/components/ui/notification.tsx +175 -0
  52. package/src/components/ui/overlay.tsx +63 -0
  53. package/src/components/ui/progress.tsx +95 -4
  54. package/src/components/ui/qr-code.tsx +107 -0
  55. package/src/components/ui/rating-group.tsx +1 -0
  56. package/src/components/ui/separator.tsx +57 -1
  57. package/src/components/ui/sidebar.tsx +1 -1
  58. package/src/components/ui/signature-pad.tsx +381 -0
  59. package/src/components/ui/skeleton.tsx +59 -2
  60. package/src/components/ui/skip-link.tsx +117 -0
  61. package/src/components/ui/slider.tsx +86 -1
  62. package/src/components/ui/spoiler.tsx +131 -0
  63. package/src/components/ui/tabs.tsx +1 -1
  64. package/src/components/ui/text.tsx +135 -0
  65. package/src/components/ui/textarea.tsx +66 -2
  66. package/src/components/ui/timeline.tsx +71 -14
  67. package/src/components/ui/timer.tsx +183 -0
  68. package/src/components/ui/tour.tsx +332 -0
  69. package/src/components/ui/transfer-list.tsx +308 -0
  70. package/src/components/ui/visually-hidden.tsx +42 -0
  71. package/src/components/ui/watermark.tsx +0 -0
  72. package/src/data/docs-index.ts +10 -2
  73. package/src/stories/ActionBar.stories.tsx +201 -0
  74. package/src/stories/Affix.stories.tsx +165 -0
  75. package/src/stories/Alert.stories.tsx +58 -0
  76. package/src/stories/Anchor.stories.tsx +236 -0
  77. package/src/stories/AngleSlider.stories.tsx +128 -0
  78. package/src/stories/Autocomplete.stories.tsx +216 -0
  79. package/src/stories/Avatar.stories.tsx +73 -1
  80. package/src/stories/Blockquote.stories.tsx +148 -0
  81. package/src/stories/BottomNavigation.stories.tsx +195 -0
  82. package/src/stories/Burger.stories.tsx +79 -0
  83. package/src/stories/Button.stories.tsx +103 -2
  84. package/src/stories/Calendar.stories.tsx +4 -0
  85. package/src/stories/Card.stories.tsx +30 -0
  86. package/src/stories/Carousel.stories.tsx +2 -1
  87. package/src/stories/Cascader.stories.tsx +285 -0
  88. package/src/stories/Checkbox.stories.tsx +13 -0
  89. package/src/stories/CheckboxCard.stories.tsx +210 -0
  90. package/src/stories/CheckboxGroup.stories.tsx +186 -0
  91. package/src/stories/Chip.stories.tsx +173 -0
  92. package/src/stories/CircularProgress.stories.tsx +3 -0
  93. package/src/stories/ColorSwatch.stories.tsx +81 -0
  94. package/src/stories/CopyButton.stories.tsx +3 -3
  95. package/src/stories/DataList.stories.tsx +160 -0
  96. package/src/stories/DatePicker.stories.tsx +3 -0
  97. package/src/stories/DateRangePicker.stories.tsx +3 -0
  98. package/src/stories/Editable.stories.tsx +14 -0
  99. package/src/stories/Fieldset.stories.tsx +4 -0
  100. package/src/stories/FloatLabel.stories.tsx +148 -0
  101. package/src/stories/FloatingPanel.stories.tsx +176 -0
  102. package/src/stories/FormatNumber.stories.tsx +308 -0
  103. package/src/stories/Highlight.stories.tsx +140 -0
  104. package/src/stories/Image.stories.tsx +141 -0
  105. package/src/stories/Indicator.stories.tsx +3 -0
  106. package/src/stories/Input.stories.tsx +33 -0
  107. package/src/stories/InputGroup.stories.tsx +39 -41
  108. package/src/stories/Kbd.stories.tsx +3 -0
  109. package/src/stories/Link.stories.tsx +198 -0
  110. package/src/stories/Listbox.stories.tsx +240 -0
  111. package/src/stories/LoadingOverlay.stories.tsx +148 -0
  112. package/src/stories/Marquee.stories.tsx +170 -0
  113. package/src/stories/Masonry.stories.tsx +227 -0
  114. package/src/stories/Meter.stories.tsx +143 -0
  115. package/src/stories/MotionToggle.stories.tsx +85 -0
  116. package/src/stories/Notification.stories.tsx +264 -0
  117. package/src/stories/Overlay.stories.tsx +169 -0
  118. package/src/stories/PasswordInput.stories.tsx +4 -0
  119. package/src/stories/Progress.stories.tsx +70 -27
  120. package/src/stories/QrCode.stories.tsx +146 -0
  121. package/src/stories/RatingGroup.stories.tsx +5 -0
  122. package/src/stories/Separator.stories.tsx +41 -5
  123. package/src/stories/Sidebar.stories.tsx +2 -1
  124. package/src/stories/SignaturePad.stories.tsx +112 -0
  125. package/src/stories/Skeleton.stories.tsx +23 -4
  126. package/src/stories/SkipLink.stories.tsx +137 -0
  127. package/src/stories/Slider.stories.tsx +28 -0
  128. package/src/stories/Spoiler.stories.tsx +122 -0
  129. package/src/stories/Tabs.stories.tsx +2 -1
  130. package/src/stories/Text.stories.tsx +191 -0
  131. package/src/stories/Textarea.stories.tsx +58 -6
  132. package/src/stories/Timeline.stories.tsx +82 -0
  133. package/src/stories/Timer.stories.tsx +160 -0
  134. package/src/stories/Tour.stories.tsx +191 -0
  135. package/src/stories/TransferList.stories.tsx +169 -0
  136. package/src/stories/VisuallyHidden.stories.tsx +105 -0
  137. package/src/stories/Watermark.stories.tsx +212 -0
  138. package/src/styles.css +80 -6
  139. package/src/tokens.json +2 -2
@@ -1,5 +1,6 @@
1
1
  import * as React from "react"
2
2
  import { cva, type VariantProps } from "class-variance-authority"
3
+ import { XIcon } from "lucide-react"
3
4
 
4
5
  import { cn } from "../../lib/utils"
5
6
 
@@ -21,22 +22,65 @@ const inputVariants = cva(
21
22
  }
22
23
  )
23
24
 
25
+ type InputProps = Omit<React.ComponentProps<"input">, "size"> &
26
+ VariantProps<typeof inputVariants> & {
27
+ /** When true, shows a dismiss (×) button on the right when the input has a value.
28
+ * Calls onChange with an empty string on click. Only meaningful for controlled inputs. */
29
+ clearable?: boolean
30
+ }
31
+
24
32
  function Input({
25
33
  className,
26
34
  type,
27
35
  size,
36
+ clearable,
37
+ value,
38
+ onChange,
39
+ disabled,
28
40
  ...props
29
- }: Omit<React.ComponentProps<"input">, "size"> &
30
- VariantProps<typeof inputVariants>) {
31
- return (
41
+ }: InputProps) {
42
+ const showClear = clearable && !disabled && value !== undefined && value !== ""
43
+
44
+ const inputEl = (
32
45
  <input
33
46
  type={type}
34
47
  data-slot="input"
35
48
  data-size={size ?? "default"}
36
- className={cn(inputVariants({ size, className }))}
49
+ className={cn(inputVariants({ size, className }), clearable && "pr-8")}
50
+ value={value}
51
+ onChange={onChange}
52
+ disabled={disabled}
37
53
  {...props}
38
54
  />
39
55
  )
56
+
57
+ if (!clearable) {
58
+ return inputEl
59
+ }
60
+
61
+ return (
62
+ <div className="relative">
63
+ {inputEl}
64
+ {showClear && (
65
+ <button
66
+ type="button"
67
+ aria-label="Clear input"
68
+ className="absolute right-1.5 top-1/2 -translate-y-1/2 inline-flex items-center justify-center size-6 rounded text-muted-foreground hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1"
69
+ style={{
70
+ transitionDuration: "var(--duration-fast)",
71
+ transitionTimingFunction: "var(--ease-out)",
72
+ }}
73
+ onClick={() => {
74
+ onChange?.({
75
+ target: { value: "" },
76
+ } as React.ChangeEvent<HTMLInputElement>)
77
+ }}
78
+ >
79
+ <XIcon size={14} strokeWidth={1.5} aria-hidden="true" />
80
+ </button>
81
+ )}
82
+ </div>
83
+ )
40
84
  }
41
85
 
42
86
  export { Input, inputVariants }
@@ -14,7 +14,7 @@ const kbdVariants = cva(
14
14
  {
15
15
  variants: {
16
16
  variant: {
17
- default: "border-border bg-muted shadow-[0_1px_0_1px_hsl(var(--border))]",
17
+ default: "border-border bg-muted shadow-[0_1px_0_1px_var(--border)]",
18
18
  outline: "border-border bg-background",
19
19
  },
20
20
  size: {
@@ -0,0 +1,158 @@
1
+ "use client";
2
+
3
+ import * as React from "react";
4
+ import { Slot } from "@radix-ui/react-slot";
5
+ import { cva, type VariantProps } from "class-variance-authority";
6
+ import { ExternalLinkIcon } from "lucide-react";
7
+
8
+ import { cn } from "../../lib/utils";
9
+
10
+ /**
11
+ * Navigation anchor primitive — a semantic `<a href>` with BADS' link
12
+ * discipline built in. Sources: MUI Link (the underline axis), Chakra UI
13
+ * Link (the external affordance), Mantine Anchor (inherit-the-context
14
+ * sizing). Distinct from `Button variant="link"`, which is a `<button>`
15
+ * for ACTIONS styled as links — `Link` is for navigation, stays
16
+ * `display: inline` so it wraps mid-sentence in prose, and inherits its
17
+ * font size from the surrounding text.
18
+ *
19
+ * <Text>
20
+ * Read the <Link href="/docs/getting-started">getting started guide</Link>
21
+ * before customizing tokens.
22
+ * </Text>
23
+ *
24
+ * <Link href="https://design.bads.com" external>design.bads.com</Link>
25
+ *
26
+ * <Link asChild><NextLink href="/customize">Customize</NextLink></Link>
27
+ *
28
+ * AAA notes baked into the defaults:
29
+ * - `underline="always"` is the default because color alone cannot mark a
30
+ * link inside prose (SC 1.4.1). `hover`/`none` are for chrome where
31
+ * position identifies the link (nav lists, footers, breadcrumb-likes).
32
+ * - The underline renders at 40% strength and solidifies on hover — the
33
+ * hover state-change, animated via `transition-colors` (which covers
34
+ * `text-decoration-color`) on `--duration-fast` + `--ease-out`.
35
+ * - `external` appends an aria-hidden ExternalLink icon (strokeWidth 1.5)
36
+ * plus sr-only "(opens in new tab)" (SC 3.2.5 advance warning) and sets
37
+ * `target="_blank" rel="noopener noreferrer"`. With `asChild`, target/rel
38
+ * still forward through Slot but the icon/sr-only affordance is skipped
39
+ * (Slot requires exactly one child — same contract as Button's loading).
40
+ * - Inline links take the SC 2.5.8 inline target-size exception. A
41
+ * standalone flow-changing CTA styled as a link is still a CTA — use
42
+ * `Button` (min-h-11 CTA contract), not `Link`.
43
+ * - There is NO disabled state: links are removed or rendered as plain
44
+ * text, never disabled.
45
+ *
46
+ * `[overflow-wrap:anywhere]` ships in the base so a raw URL used as link
47
+ * text wraps instead of bleeding out of its container (corrections.md
48
+ * #001; `min-w-0` is omitted — meaningless on `display: inline`).
49
+ * Cursor pointer comes from the base layer's `a[href]` rule.
50
+ */
51
+
52
+ const linkVariants = cva(
53
+ // rounded-sm gives the focus ring a soft corner; ring appears instantly
54
+ // (only color properties are transitioned — never transition-all, so the
55
+ // focus indicator is not faded in; see CLAUDE.md → microanimation rule).
56
+ "rounded-sm underline-offset-4 outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 [overflow-wrap:anywhere]",
57
+ {
58
+ variants: {
59
+ underline: {
60
+ always: "underline",
61
+ hover: "no-underline hover:underline",
62
+ none: "no-underline",
63
+ },
64
+ tone: {
65
+ // --link defaults to --primary (fork-overridable in tokens.json);
66
+ // decoration solidifies from 40% on hover.
67
+ default: "text-link decoration-link/40 hover:decoration-link",
68
+ foreground:
69
+ "text-foreground decoration-foreground/40 hover:decoration-foreground",
70
+ // muted lifts to foreground on hover — both pairs are
71
+ // wcag:audit-enforced AAA.
72
+ muted:
73
+ "text-muted-foreground decoration-muted-foreground/40 hover:text-foreground hover:decoration-foreground",
74
+ },
75
+ },
76
+ defaultVariants: {
77
+ underline: "always",
78
+ tone: "default",
79
+ },
80
+ }
81
+ );
82
+
83
+ export interface LinkProps
84
+ extends React.ComponentProps<"a">,
85
+ VariantProps<typeof linkVariants> {
86
+ /**
87
+ * Marks the destination as outside this product: sets
88
+ * `target="_blank" rel="noopener noreferrer"` (explicit `target`/`rel`
89
+ * props win) and appends the external-link icon + sr-only
90
+ * "(opens in new tab)". Icon/sr-only are skipped with `asChild`.
91
+ */
92
+ external?: boolean;
93
+ /**
94
+ * Radix Slot idiom (same as Button) — merge the link styles and props
95
+ * onto the single child element, e.g. a Next.js `<Link>`.
96
+ */
97
+ asChild?: boolean;
98
+ }
99
+
100
+ function Link({
101
+ className,
102
+ underline,
103
+ tone,
104
+ external = false,
105
+ asChild = false,
106
+ target,
107
+ rel,
108
+ style,
109
+ children,
110
+ ...props
111
+ }: LinkProps) {
112
+ const Comp = asChild ? Slot : "a";
113
+
114
+ return (
115
+ <Comp
116
+ data-slot="link"
117
+ data-underline={underline ?? "always"}
118
+ data-tone={tone ?? "default"}
119
+ target={external ? (target ?? "_blank") : target}
120
+ rel={external ? (rel ?? "noopener noreferrer") : rel}
121
+ className={cn(linkVariants({ underline, tone }), className)}
122
+ // Motion pattern (c): token-driven one-off transition — inline var()
123
+ // resolves at runtime against :root; never duration-* classes or
124
+ // literal ms values. Reduced-motion is handled by the base layer.
125
+ style={{
126
+ transitionDuration: "var(--duration-fast)",
127
+ transitionTimingFunction: "var(--ease-out)",
128
+ ...style,
129
+ }}
130
+ {...props}
131
+ >
132
+ {asChild ? (
133
+ // Slot calls React.Children.only — it must receive exactly ONE
134
+ // child, so the external icon/sr-only affordance cannot be injected
135
+ // here (documented no-op, mirroring Button's loading contract).
136
+ children
137
+ ) : (
138
+ <>
139
+ {children}
140
+ {external ? (
141
+ <>
142
+ {/* size-3.5 (14px) reads correctly against both text-sm and
143
+ text-base contexts; align tucks it onto the baseline. */}
144
+ <ExternalLinkIcon
145
+ strokeWidth={1.5}
146
+ aria-hidden="true"
147
+ className="ml-1 inline-block size-3.5 shrink-0 align-[-0.125em]"
148
+ />
149
+ <span className="sr-only"> (opens in new tab)</span>
150
+ </>
151
+ ) : null}
152
+ </>
153
+ )}
154
+ </Comp>
155
+ );
156
+ }
157
+
158
+ export { Link, linkVariants };
@@ -0,0 +1,426 @@
1
+ "use client";
2
+
3
+ import * as React from "react";
4
+
5
+ import { cn } from "../../lib/utils";
6
+
7
+ /**
8
+ * Listbox — a controlled, always-visible listbox widget for single or
9
+ * multi-select. Renders with role="listbox" and role="option" children,
10
+ * following the ARIA Listbox pattern with aria-activedescendant keyboard
11
+ * navigation (focus stays on the container; the logical cursor is tracked
12
+ * via aria-activedescendant, not DOM focus movement between options).
13
+ *
14
+ * Use for: filter sidebars, settings panels, language/locale pickers — any
15
+ * surface where the list stays open and the selection is immediately visible.
16
+ *
17
+ * Do NOT use for:
18
+ * - Navigation (use NavigationMenu)
19
+ * - Popup/trigger-activated selection (use Select, Combobox, DropdownMenu)
20
+ *
21
+ * Sources: Ark UI (Listbox), Chakra UI v3 (Listbox).
22
+ *
23
+ * @example Single-select
24
+ * ```tsx
25
+ * <ListboxRoot value={status} onValueChange={setStatus} aria-label="Filter by status">
26
+ * <ListboxOption value="active">Active</ListboxOption>
27
+ * <ListboxOption value="in-review">In Review</ListboxOption>
28
+ * <ListboxOption value="archived" disabled>Archived</ListboxOption>
29
+ * </ListboxRoot>
30
+ * ```
31
+ *
32
+ * @example Multi-select
33
+ * ```tsx
34
+ * <ListboxRoot multiple value={tags} onValueChange={setTags} aria-label="Filter by tag">
35
+ * <ListboxOption value="design">Design</ListboxOption>
36
+ * <ListboxOption value="tokens">Tokens</ListboxOption>
37
+ * <ListboxOption value="a11y">Accessibility</ListboxOption>
38
+ * </ListboxRoot>
39
+ * ```
40
+ */
41
+
42
+ // ---------------------------------------------------------------------------
43
+ // Context
44
+ // ---------------------------------------------------------------------------
45
+
46
+ type ListboxContextValue = {
47
+ value: string[];
48
+ activeId: string | undefined;
49
+ setActiveId: (id: string | undefined) => void;
50
+ multiple: boolean;
51
+ disabled: boolean;
52
+ toggleOption: (optionValue: string, withShift?: boolean) => void;
53
+ isSelected: (optionValue: string) => boolean;
54
+ };
55
+
56
+ const ListboxContext = React.createContext<ListboxContextValue | null>(null);
57
+
58
+ function useListboxContext(caller: string) {
59
+ const ctx = React.useContext(ListboxContext);
60
+ if (!ctx) {
61
+ throw new Error(`${caller} must be rendered inside a <ListboxRoot>.`);
62
+ }
63
+ return ctx;
64
+ }
65
+
66
+ // ---------------------------------------------------------------------------
67
+ // ListboxRoot
68
+ // ---------------------------------------------------------------------------
69
+
70
+ export interface ListboxRootProps
71
+ extends Omit<React.ComponentProps<"div">, "value" | "onChange"> {
72
+ /**
73
+ * When false (default): `value` is a string, `onValueChange` receives a string.
74
+ * When true: `value` is a string[], `onValueChange` receives a string[].
75
+ */
76
+ multiple?: boolean;
77
+ /**
78
+ * Controlled selected value(s). In single mode, a string; in multi mode, a
79
+ * string[]. If omitted, the component manages its own selection state.
80
+ */
81
+ value?: string | string[];
82
+ /** Called with the new value on every selection change. */
83
+ onValueChange?: (value: string | string[]) => void;
84
+ /** Disables the entire listbox and all options. */
85
+ disabled?: boolean;
86
+ }
87
+
88
+ function ListboxRoot({
89
+ className,
90
+ multiple = false,
91
+ value: valueProp,
92
+ onValueChange,
93
+ disabled = false,
94
+ children,
95
+ onFocus,
96
+ onKeyDown,
97
+ ...props
98
+ }: ListboxRootProps) {
99
+ const containerRef = React.useRef<HTMLDivElement>(null);
100
+ const [activeId, setActiveId] = React.useState<string | undefined>();
101
+
102
+ // Anchor for Shift+click / Shift+Arrow range extension (multi mode)
103
+ const anchorValueRef = React.useRef<string | undefined>(undefined);
104
+
105
+ // Normalize value prop → string[]
106
+ const normalizeValue = (v: string | string[] | undefined): string[] => {
107
+ if (v === undefined) return [];
108
+ return Array.isArray(v) ? v : [v];
109
+ };
110
+
111
+ const [internalValue, setInternalValue] = React.useState<string[]>(() =>
112
+ normalizeValue(valueProp),
113
+ );
114
+
115
+ const isControlled = valueProp !== undefined;
116
+ const value = isControlled ? normalizeValue(valueProp) : internalValue;
117
+
118
+ // Stable ref to avoid stale-closure in toggleOption
119
+ const onValueChangeRef = React.useRef(onValueChange);
120
+ React.useEffect(() => {
121
+ onValueChangeRef.current = onValueChange;
122
+ });
123
+
124
+ const valueRef = React.useRef(value);
125
+ valueRef.current = value;
126
+
127
+ // Helper: query navigable (non-disabled) option elements in DOM order
128
+ const getNavigableOptions = React.useCallback((): HTMLElement[] => {
129
+ if (!containerRef.current) return [];
130
+ return Array.from(
131
+ containerRef.current.querySelectorAll<HTMLElement>(
132
+ '[role="option"]:not([aria-disabled="true"])',
133
+ ),
134
+ );
135
+ }, []);
136
+
137
+ const toggleOption = React.useCallback(
138
+ (optionValue: string, withShift = false) => {
139
+ if (disabled) return;
140
+
141
+ let next: string[];
142
+
143
+ if (!multiple) {
144
+ // Single select: replace
145
+ next = [optionValue];
146
+ anchorValueRef.current = optionValue;
147
+ } else if (withShift && anchorValueRef.current) {
148
+ // Shift: select the contiguous range from anchor to target
149
+ const options = getNavigableOptions();
150
+ const optionValues = options.map(
151
+ (el) => el.getAttribute("data-value") ?? "",
152
+ );
153
+ const anchorIdx = optionValues.indexOf(anchorValueRef.current);
154
+ const targetIdx = optionValues.indexOf(optionValue);
155
+
156
+ if (anchorIdx !== -1 && targetIdx !== -1) {
157
+ const [start, end] =
158
+ anchorIdx <= targetIdx
159
+ ? [anchorIdx, targetIdx]
160
+ : [targetIdx, anchorIdx];
161
+ const rangeValues = optionValues
162
+ .slice(start, end + 1)
163
+ .filter(Boolean);
164
+ // Merge range into existing selection (preserving anything outside)
165
+ const outsideRange = valueRef.current.filter(
166
+ (v) => !optionValues.includes(v),
167
+ );
168
+ next = [...new Set([...outsideRange, ...rangeValues])];
169
+ } else {
170
+ // Fallback: toggle
171
+ next = valueRef.current.includes(optionValue)
172
+ ? valueRef.current.filter((v) => v !== optionValue)
173
+ : [...valueRef.current, optionValue];
174
+ }
175
+ } else {
176
+ // Multi-select: toggle individual option
177
+ next = valueRef.current.includes(optionValue)
178
+ ? valueRef.current.filter((v) => v !== optionValue)
179
+ : [...valueRef.current, optionValue];
180
+ anchorValueRef.current = optionValue;
181
+ }
182
+
183
+ if (!isControlled) setInternalValue(next);
184
+
185
+ // Emit the correct shape for single vs multi
186
+ onValueChangeRef.current?.(multiple ? next : (next[0] ?? ""));
187
+ },
188
+ [disabled, getNavigableOptions, isControlled, multiple],
189
+ );
190
+
191
+ const handleKeyDown = React.useCallback(
192
+ (e: React.KeyboardEvent<HTMLDivElement>) => {
193
+ onKeyDown?.(e);
194
+ if (disabled || e.defaultPrevented) return;
195
+
196
+ const options = getNavigableOptions();
197
+ if (options.length === 0) return;
198
+
199
+ const currentIndex = activeId
200
+ ? options.findIndex((el) => el.id === activeId)
201
+ : -1;
202
+
203
+ switch (e.key) {
204
+ case "ArrowDown": {
205
+ e.preventDefault();
206
+ const nextIdx =
207
+ currentIndex < options.length - 1 ? currentIndex + 1 : 0;
208
+ const nextEl = options[nextIdx];
209
+ if (nextEl) {
210
+ setActiveId(nextEl.id);
211
+ if (multiple && e.shiftKey) {
212
+ const optValue = nextEl.getAttribute("data-value");
213
+ if (optValue) toggleOption(optValue, true);
214
+ }
215
+ }
216
+ break;
217
+ }
218
+ case "ArrowUp": {
219
+ e.preventDefault();
220
+ const prevIdx =
221
+ currentIndex > 0 ? currentIndex - 1 : options.length - 1;
222
+ const prevEl = options[prevIdx];
223
+ if (prevEl) {
224
+ setActiveId(prevEl.id);
225
+ if (multiple && e.shiftKey) {
226
+ const optValue = prevEl.getAttribute("data-value");
227
+ if (optValue) toggleOption(optValue, true);
228
+ }
229
+ }
230
+ break;
231
+ }
232
+ case "Home": {
233
+ e.preventDefault();
234
+ const firstEl = options[0];
235
+ if (firstEl) setActiveId(firstEl.id);
236
+ break;
237
+ }
238
+ case "End": {
239
+ e.preventDefault();
240
+ const lastEl = options[options.length - 1];
241
+ if (lastEl) setActiveId(lastEl.id);
242
+ break;
243
+ }
244
+ case " ":
245
+ case "Enter": {
246
+ e.preventDefault();
247
+ if (activeId) {
248
+ const activeEl = options.find((el) => el.id === activeId);
249
+ if (activeEl) {
250
+ const optValue = activeEl.getAttribute("data-value");
251
+ if (optValue) toggleOption(optValue);
252
+ }
253
+ } else {
254
+ // No active item yet — activate + select the first option
255
+ const firstEl = options[0];
256
+ if (firstEl) {
257
+ setActiveId(firstEl.id);
258
+ const optValue = firstEl.getAttribute("data-value");
259
+ if (optValue) toggleOption(optValue);
260
+ }
261
+ }
262
+ break;
263
+ }
264
+ }
265
+ },
266
+ [activeId, disabled, getNavigableOptions, multiple, onKeyDown, toggleOption],
267
+ );
268
+
269
+ const handleFocus = React.useCallback(
270
+ (e: React.FocusEvent<HTMLDivElement>) => {
271
+ onFocus?.(e);
272
+ // Set an initial active descendant on focus if none is set yet
273
+ if (!activeId) {
274
+ const options = getNavigableOptions();
275
+ // Prefer the first selected option, fall back to first option
276
+ const firstSelected = valueRef.current[0];
277
+ if (firstSelected) {
278
+ const selectedEl = options.find(
279
+ (el) => el.getAttribute("data-value") === firstSelected,
280
+ );
281
+ if (selectedEl) {
282
+ setActiveId(selectedEl.id);
283
+ return;
284
+ }
285
+ }
286
+ if (options[0]) setActiveId(options[0].id);
287
+ }
288
+ },
289
+ [activeId, getNavigableOptions, onFocus],
290
+ );
291
+
292
+ const isSelected = React.useCallback(
293
+ (optionValue: string) => value.includes(optionValue),
294
+ [value],
295
+ );
296
+
297
+ const ctx = React.useMemo<ListboxContextValue>(
298
+ () => ({
299
+ value,
300
+ activeId,
301
+ setActiveId,
302
+ multiple,
303
+ disabled,
304
+ toggleOption,
305
+ isSelected,
306
+ }),
307
+ [value, activeId, multiple, disabled, toggleOption, isSelected],
308
+ );
309
+
310
+ return (
311
+ <ListboxContext.Provider value={ctx}>
312
+ <div
313
+ ref={containerRef}
314
+ role="listbox"
315
+ data-slot="listbox"
316
+ aria-multiselectable={multiple || undefined}
317
+ aria-disabled={disabled || undefined}
318
+ aria-activedescendant={activeId}
319
+ tabIndex={disabled ? -1 : 0}
320
+ onKeyDown={handleKeyDown}
321
+ onFocus={handleFocus}
322
+ className={cn(
323
+ "flex flex-col rounded-md border border-border bg-background py-1 text-foreground outline-none",
324
+ // Focus ring — visible when the container itself is keyboard-focused
325
+ "focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:border-ring",
326
+ disabled && "pointer-events-none opacity-50",
327
+ className,
328
+ )}
329
+ {...props}
330
+ >
331
+ {children}
332
+ </div>
333
+ </ListboxContext.Provider>
334
+ );
335
+ }
336
+
337
+ // ---------------------------------------------------------------------------
338
+ // ListboxOption
339
+ // ---------------------------------------------------------------------------
340
+
341
+ export interface ListboxOptionProps
342
+ extends Omit<React.ComponentProps<"div">, "value"> {
343
+ /** The value this option represents. */
344
+ value: string;
345
+ /** Prevents this option from being selected or navigated to. */
346
+ disabled?: boolean;
347
+ }
348
+
349
+ function ListboxOption({
350
+ className,
351
+ value: optionValue,
352
+ disabled: optionDisabled = false,
353
+ children,
354
+ onClick,
355
+ ...props
356
+ }: ListboxOptionProps) {
357
+ const ctx = useListboxContext("ListboxOption");
358
+
359
+ // Stable ID for aria-activedescendant linkage
360
+ const rawId = React.useId();
361
+ // useId returns strings like ":ra:" — strip colons for a clean HTML id
362
+ const optionId = `listbox-option-${rawId.replace(/:/g, "")}`;
363
+
364
+ const selected = ctx.isSelected(optionValue);
365
+ const isActive = ctx.activeId === optionId;
366
+ const isDisabled = ctx.disabled || optionDisabled;
367
+
368
+ const handleClick = (e: React.MouseEvent<HTMLDivElement>) => {
369
+ if (isDisabled) return;
370
+ ctx.setActiveId(optionId);
371
+ ctx.toggleOption(optionValue, e.shiftKey && ctx.multiple);
372
+ onClick?.(e);
373
+ };
374
+
375
+ return (
376
+ <div
377
+ id={optionId}
378
+ role="option"
379
+ data-slot="listbox-option"
380
+ data-value={optionValue}
381
+ data-state={selected ? "selected" : "unselected"}
382
+ data-active={isActive || undefined}
383
+ data-disabled={isDisabled || undefined}
384
+ aria-selected={selected}
385
+ aria-disabled={isDisabled || undefined}
386
+ onClick={handleClick}
387
+ className={cn(
388
+ // Base — layout, type, sizing
389
+ "relative flex cursor-pointer select-none items-center px-3 py-2 text-sm",
390
+ // 44px minimum touch target (SC 2.5.5 Enhanced)
391
+ "min-h-11",
392
+ // Default (unselected, non-active) hover
393
+ !isDisabled && !selected && "hover:bg-accent/50 hover:text-accent-foreground",
394
+ // Selected state
395
+ selected && "bg-accent text-accent-foreground",
396
+ // Active-descendant cursor when not selected — subtle accent tint
397
+ isActive && !selected && "bg-accent/30",
398
+ // Disabled
399
+ isDisabled && "pointer-events-none cursor-not-allowed opacity-50",
400
+ className,
401
+ )}
402
+ // Microanimation: pattern-c — inline style with BADS motion tokens.
403
+ // transitionProperty lists only the properties we animate (SC 2.4.13 safe).
404
+ // var(--duration-fast) + var(--ease-out) resolve from styles.css via
405
+ // pnpm build:tokens. Reduced-motion is auto-killed by the base layer's
406
+ // @media (prefers-reduced-motion: reduce) rule in styles.css.
407
+ style={{
408
+ transitionProperty: "background-color, color",
409
+ transitionDuration: "var(--duration-fast)",
410
+ transitionTimingFunction: "var(--ease-out)",
411
+ }}
412
+ {...props}
413
+ >
414
+ {children}
415
+ </div>
416
+ );
417
+ }
418
+
419
+ // ---------------------------------------------------------------------------
420
+ // Exports
421
+ // ---------------------------------------------------------------------------
422
+
423
+ /** Convenience alias for single-select usage: const Listbox = ListboxRoot */
424
+ const Listbox = ListboxRoot;
425
+
426
+ export { Listbox, ListboxRoot, ListboxOption };