@dinachi/cli 0.12.0 → 1.1.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 (74) hide show
  1. package/CHANGELOG.md +131 -0
  2. package/dist/index.js +73 -7
  3. package/package.json +1 -1
  4. package/templates/accordion/accordion.tsx +70 -12
  5. package/templates/agent/agent.tsx +1865 -0
  6. package/templates/agent/index.ts +52 -0
  7. package/templates/alert-dialog/alert-dialog.tsx +59 -19
  8. package/templates/alert-dialog/index.ts +2 -0
  9. package/templates/animated-icon/animated-icon.tsx +1 -0
  10. package/templates/animated-list/animated-list.tsx +2 -1
  11. package/templates/animated-tabs/animated-tabs.tsx +69 -5
  12. package/templates/autocomplete/autocomplete.tsx +188 -21
  13. package/templates/avatar/avatar.tsx +3 -0
  14. package/templates/badge/badge.tsx +1 -0
  15. package/templates/button/button.tsx +1 -0
  16. package/templates/card/card.tsx +6 -1
  17. package/templates/carousel/carousel.tsx +109 -24
  18. package/templates/checkbox/checkbox.tsx +61 -4
  19. package/templates/checkbox-group/checkbox-group.tsx +83 -8
  20. package/templates/collapsible/collapsible.tsx +15 -4
  21. package/templates/combobox/combobox.tsx +312 -26
  22. package/templates/compare-slider/compare-slider.tsx +104 -28
  23. package/templates/compare-slider/index.ts +1 -1
  24. package/templates/context-menu/context-menu.tsx +93 -24
  25. package/templates/dialog/dialog.tsx +53 -14
  26. package/templates/drawer/drawer.tsx +36 -8
  27. package/templates/expandable-card/expandable-card.tsx +70 -43
  28. package/templates/field/field.tsx +7 -1
  29. package/templates/fieldset/fieldset.tsx +2 -0
  30. package/templates/form/form.tsx +1 -0
  31. package/templates/hold-to-confirm/hold-to-confirm.tsx +100 -16
  32. package/templates/hold-to-confirm/index.ts +1 -1
  33. package/templates/input/input.tsx +60 -1
  34. package/templates/label/label.tsx +1 -0
  35. package/templates/link/link.tsx +1 -0
  36. package/templates/load-transition/load-transition.tsx +1 -0
  37. package/templates/marquee/marquee.tsx +1 -0
  38. package/templates/menu/menu.tsx +45 -12
  39. package/templates/menubar/menubar.tsx +41 -11
  40. package/templates/meter/meter.tsx +5 -1
  41. package/templates/navigation-menu/navigation-menu.tsx +79 -24
  42. package/templates/number-field/index.ts +1 -0
  43. package/templates/number-field/number-field.tsx +77 -2
  44. package/templates/number-ticker/number-ticker.tsx +3 -0
  45. package/templates/otp-field/otp-field.tsx +61 -11
  46. package/templates/popover/popover.tsx +36 -7
  47. package/templates/preview-card/preview-card.tsx +27 -5
  48. package/templates/progress/progress.tsx +5 -1
  49. package/templates/progress-ring/progress-ring.tsx +1 -0
  50. package/templates/radio/radio.tsx +74 -6
  51. package/templates/scroll-area/scroll-area.tsx +14 -4
  52. package/templates/scroll-progress/scroll-progress.tsx +1 -0
  53. package/templates/scroll-reveal/scroll-reveal.tsx +1 -0
  54. package/templates/select/select.tsx +241 -12
  55. package/templates/separator/separator.tsx +1 -0
  56. package/templates/skeleton/skeleton.tsx +1 -0
  57. package/templates/slider/slider.tsx +84 -8
  58. package/templates/sortable/sortable.tsx +79 -9
  59. package/templates/stagger-list/stagger-list.tsx +2 -0
  60. package/templates/streaming-text/streaming-text.tsx +1 -0
  61. package/templates/swipeable-row/index.ts +1 -1
  62. package/templates/swipeable-row/swipeable-row.tsx +126 -41
  63. package/templates/switch/switch.tsx +43 -4
  64. package/templates/tabs/tabs.tsx +79 -10
  65. package/templates/text/text.tsx +1 -0
  66. package/templates/text-morph/text-morph.tsx +2 -0
  67. package/templates/text-shimmer/text-shimmer.tsx +1 -0
  68. package/templates/textarea/index.ts +1 -1
  69. package/templates/textarea/textarea.tsx +71 -4
  70. package/templates/toast/toast.tsx +13 -2
  71. package/templates/toggle/toggle.tsx +40 -7
  72. package/templates/toggle-group/toggle-group.tsx +98 -18
  73. package/templates/toolbar/toolbar.tsx +6 -0
  74. package/templates/tooltip/tooltip.tsx +9 -3
@@ -4,12 +4,273 @@ import * as React from "react"
4
4
  import { Combobox as ComboboxPrimitive } from "@base-ui/react/combobox"
5
5
  import { Check, ChevronDown, X } from "lucide-react"
6
6
  import { cn } from "@/lib/utils"
7
+ import {
8
+ agentNodeText,
9
+ changeAsAgent,
10
+ createAgentChangeDetails,
11
+ matchAgentChoice,
12
+ sameAgentValue,
13
+ useAgentControl,
14
+ useAgentState,
15
+ useHasAgent,
16
+ useMergedRef,
17
+ waitForAgent,
18
+ type AgentChoice,
19
+ type AgentControl,
20
+ } from "@/components/ui/agent"
7
21
 
8
- const Combobox = ComboboxPrimitive.Root
22
+ type ElementRef = React.MutableRefObject<HTMLElement | null>
23
+
24
+ interface ComboboxAgent {
25
+ input: ElementRef
26
+ list: ElementRef
27
+ /** Items in the open list, by element. */
28
+ items: Map<HTMLElement, unknown>
29
+ /** Set while the agent types, so the callbacks it causes carry the agent's details. */
30
+ typing?: boolean
31
+ refused?: boolean
32
+ }
33
+
34
+ const ComboboxAgentContext = React.createContext<ComboboxAgent | null>(null)
35
+
36
+ type Choice = AgentChoice<string> & { item: unknown }
37
+ type ToLabel = ((item: never) => string) | undefined
38
+
39
+ type Item = { label?: unknown; value?: unknown } | null | undefined
40
+
41
+ /** Base UI's own label for an item: `itemToStringLabel`, then `label`, then `value`. */
42
+ function labelOf(item: unknown, toLabel?: ToLabel): string {
43
+ const o = item as Item
44
+ if (toLabel && o != null) return (toLabel as (i: unknown) => string)(o) ?? ""
45
+ return String(o?.label ?? o?.value ?? o ?? "")
46
+ }
47
+
48
+ const choiceOf = (item: unknown, label: string): Choice => ({
49
+ item,
50
+ label,
51
+ value: String((item as Item)?.value ?? item),
52
+ })
53
+
54
+ const leavesOf = (data: readonly unknown[] = []) =>
55
+ data.flatMap((e) => ((e as { items?: unknown })?.items instanceof Array ? (e as { items: unknown[] }).items : [e]))
56
+
57
+ /** Every choice the `items` prop lists, filtered or not, so the agent can choose while closed. */
58
+ function catalogOf(items: unknown, toLabel: ToLabel): Choice[] {
59
+ const c = (
60
+ Array.isArray(items)
61
+ ? {
62
+ data: items,
63
+ value: (i: unknown) => i,
64
+ itemLabel: (i: unknown) => labelOf(i, toLabel),
65
+ }
66
+ : items
67
+ ) as
68
+ | {
69
+ data?: unknown[]
70
+ value(i: unknown): unknown
71
+ itemLabel(i: unknown): string
72
+ }
73
+ | undefined
74
+ return c ? leavesOf(c.data).map((i) => choiceOf(c.value(i), c.itemLabel(i))) : []
75
+ }
76
+
77
+ const liveOf = (items: Map<HTMLElement, unknown>): Choice[] =>
78
+ Array.from(items, ([el, item]) => ({
79
+ ...choiceOf(item, agentNodeText(el.textContent)),
80
+ disabled: el.hasAttribute("data-disabled"),
81
+ }))
82
+
83
+ /** Hands Base UI's callback the agent's details while the agent types, and its refusal back. */
84
+ function relay<V, D extends { cancel(): void }>(s: ComboboxAgent, handler?: (value: V, details: D) => void) {
85
+ return (value: V, details: D) => {
86
+ if (!s.typing) return handler?.(value, details)
87
+ const mine = createAgentChangeDetails<D & { isCanceled: boolean }>()
88
+ handler?.(value, mine)
89
+ if (mine.isCanceled) {
90
+ s.refused = true
91
+ details.cancel()
92
+ }
93
+ }
94
+ }
95
+
96
+ /** Types into the input the way a person would, so Base UI filters exactly as it does for them. */
97
+ function typeInto(s: ComboboxAgent, input: HTMLInputElement, text: string) {
98
+ s.typing = true
99
+ s.refused = false
100
+ try {
101
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set?.call(input, text)
102
+ input.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertText" }))
103
+ return s.refused ? "The app refused the change." : undefined
104
+ } finally {
105
+ s.typing = false
106
+ }
107
+ }
108
+
109
+ /** Waits a turn for React to filter, then for the list to be open with every item registered. */
110
+ async function settled({ list, items }: ComboboxAgent) {
111
+ await new Promise((resolve) => setTimeout(resolve))
112
+ await waitForAgent(
113
+ () => list.current?.isConnected && list.current.querySelectorAll('[role="option"]').length === items.size
114
+ )
115
+ }
116
+
117
+ interface ComboboxState {
118
+ s: ComboboxAgent
119
+ catalog: Choice[]
120
+ value: unknown
121
+ open: boolean
122
+ props: RootProps
123
+ change: (value: unknown) => string | undefined
124
+ setOpen: (open: boolean) => string | undefined
125
+ }
126
+
127
+ const READ_ONLY = "The combobox is read-only."
128
+
129
+ /** Searches as a person would by typing, and returns what the list then offers. */
130
+ async function search(c: ComboboxState, text: unknown) {
131
+ const query = String(text ?? "")
132
+ if (c.props.readOnly) return READ_ONLY
133
+ const notOpened = c.open ? undefined : c.setOpen(true)
134
+ if (notOpened) return notOpened
135
+ const refused = typeInto(c.s, c.s.input.current as HTMLInputElement, query)
136
+ if (refused) {
137
+ // Leave the list as the agent found it.
138
+ if (!c.open) c.setOpen(false)
139
+ return refused
140
+ }
141
+ await settled(c.s)
142
+ return { result: liveOf(c.s.items).map((i) => i.label) }
143
+ }
144
+
145
+ function comboboxActions(c: ComboboxState, choices: () => Choice[]): AgentControl["actions"] {
146
+ // Without an `items` prop, the choices are only known once the list renders them.
147
+ // Returns whether it opened the list, so the action closes it again.
148
+ const load = async () => {
149
+ const opening = !c.open && !choices().length
150
+ if (opening) c.setOpen(true)
151
+ await waitForAgent(() => choices().length)
152
+ return opening
153
+ }
154
+ const find = (wanted: unknown) => matchAgentChoice(choices(), wanted) as Choice | string
155
+ const current: unknown[] = Array.isArray(c.value) ? c.value : []
156
+ return {
157
+ select: async (wanted: unknown) => {
158
+ const opened = await load()
159
+ const match = find(wanted)
160
+ const close = (result: string | undefined) => {
161
+ if (opened || (c.open && !c.props.multiple)) c.setOpen(false)
162
+ return result
163
+ }
164
+ if (typeof match === "string") return close(match)
165
+ if (c.props.multiple)
166
+ return close(current.some((v) => sameAgentValue(v, match.item)) ? undefined : c.change([...current, match.item]))
167
+ return close(c.change(match.item))
168
+ },
169
+ ...(c.props.multiple && {
170
+ setValue: async (wanted: unknown) => {
171
+ const opened = await load()
172
+ const found = [wanted].flat().map(find)
173
+ const result = found.find((m) => typeof m === "string") ?? c.change(found.map((m) => (m as Choice).item))
174
+ if (opened) c.setOpen(false)
175
+ return result
176
+ },
177
+ }),
178
+ search: (text: unknown) => search(c, text),
179
+ [c.open ? "close" : "open"]: () => c.setOpen(!c.open),
180
+ }
181
+ }
182
+
183
+ function comboboxControl(c: ComboboxState): AgentControl {
184
+ const { multiple, disabled, itemToStringLabel } = c.props
185
+ const choices = () => (c.catalog.length ? c.catalog : liveOf(c.s.items))
186
+ const labelFor = (v: unknown) =>
187
+ choices().find((i) => sameAgentValue(i.item, v))?.label ?? labelOf(v, itemToStringLabel)
188
+ const items = choices().map((i) => i.label)
189
+ return {
190
+ kind: "combobox",
191
+ element: c.s.input.current,
192
+ value: multiple ? (c.value as unknown[]).map(labelFor) : labelFor(c.value),
193
+ open: c.open,
194
+ disabled,
195
+ multiple,
196
+ items: items.length ? items : undefined,
197
+ actions: comboboxActions(c, choices),
198
+ }
199
+ }
200
+
201
+ type RootProps = ComboboxPrimitive.Root.Props<unknown, boolean | undefined> & {
202
+ itemToStringLabel?: ToLabel
203
+ }
204
+ type Details = ComboboxPrimitive.Root.ChangeEventDetails
205
+ type OpenDetails = ComboboxPrimitive.Root.OpenChangeEventDetails
206
+
207
+ /**
208
+ * Base UI's root, holding its value and open state inside AgentProvider so an agent can
209
+ * set them the way a parent would. The input text stays Base UI's: the agent types it, so
210
+ * filtering and the selected label behave as they do for a person. Every change, the
211
+ * agent's included, goes through the matching callback first, which can cancel it.
212
+ */
213
+ function AgentCombobox({
214
+ value: valueProp,
215
+ defaultValue,
216
+ onValueChange,
217
+ onInputValueChange,
218
+ open: openProp,
219
+ defaultOpen = false,
220
+ onOpenChange,
221
+ ...props
222
+ }: RootProps) {
223
+ const [value, changeValue] = useAgentState<unknown, Details>(
224
+ valueProp,
225
+ defaultValue ?? (props.multiple ? [] : null),
226
+ onValueChange as (v: unknown, d: Details) => void
227
+ )
228
+ const [open, changeOpen] = useAgentState<boolean, OpenDetails>(openProp, defaultOpen, onOpenChange)
229
+ const [s] = React.useState<ComboboxAgent>(() => ({
230
+ input: { current: null },
231
+ list: { current: null },
232
+ items: new Map(),
233
+ }))
234
+
235
+ useAgentControl(() =>
236
+ comboboxControl({
237
+ s,
238
+ catalog: catalogOf(props.items, props.itemToStringLabel),
239
+ value,
240
+ open,
241
+ props,
242
+ change: (next) => (props.readOnly ? READ_ONLY : changeAsAgent(changeValue, next)),
243
+ setOpen: (next) => changeAsAgent(changeOpen, next),
244
+ })
245
+ )
246
+
247
+ return (
248
+ <ComboboxAgentContext.Provider value={s}>
249
+ <ComboboxPrimitive.Root
250
+ {...(props as ComboboxPrimitive.Root.Props<unknown>)}
251
+ value={value}
252
+ onValueChange={relay(s, changeValue)}
253
+ onInputValueChange={relay(s, onInputValueChange)}
254
+ open={open}
255
+ onOpenChange={relay(s, changeOpen)}
256
+ />
257
+ </ComboboxAgentContext.Provider>
258
+ )
259
+ }
260
+
261
+ /** Base UI's root as it is, until an AgentProvider is around it. */
262
+ function ComboboxRoot(props: RootProps) {
263
+ if (!useHasAgent()) return <ComboboxPrimitive.Root {...(props as ComboboxPrimitive.Root.Props<unknown>)} />
264
+ return <AgentCombobox {...props} />
265
+ }
266
+
267
+ const Combobox = ComboboxRoot as unknown as typeof ComboboxPrimitive.Root
9
268
  const ComboboxValue = ComboboxPrimitive.Value
10
269
  const ComboboxCollection = ComboboxPrimitive.Collection
11
270
  const ComboboxPortal = ComboboxPrimitive.Portal
12
- const ComboboxInputGroup = ComboboxPrimitive.InputGroup
271
+ function ComboboxInputGroup(props: React.ComponentProps<typeof ComboboxPrimitive.InputGroup>) {
272
+ return <ComboboxPrimitive.InputGroup data-slot="combobox-input-group" {...props} />
273
+ }
13
274
  const createComboboxItems = ComboboxPrimitive.createItems
14
275
 
15
276
  const ComboboxInput = React.forwardRef<
@@ -17,7 +278,8 @@ const ComboboxInput = React.forwardRef<
17
278
  React.ComponentPropsWithoutRef<typeof ComboboxPrimitive.Input>
18
279
  >(({ className, ...props }, ref) => (
19
280
  <ComboboxPrimitive.Input
20
- ref={ref}
281
+ data-slot="combobox-input"
282
+ ref={useMergedRef(ref, React.useContext(ComboboxAgentContext)?.input)}
21
283
  className={cn(
22
284
  "flex h-10 w-full bg-transparent px-3 py-2 text-sm",
23
285
  "placeholder:text-muted-foreground",
@@ -35,6 +297,7 @@ const ComboboxTrigger = React.forwardRef<
35
297
  React.ComponentPropsWithoutRef<typeof ComboboxPrimitive.Trigger>
36
298
  >(({ className, children, ...props }, ref) => (
37
299
  <ComboboxPrimitive.Trigger
300
+ data-slot="combobox-trigger"
38
301
  ref={ref}
39
302
  className={cn(
40
303
  "inline-flex h-10 items-center justify-center px-3",
@@ -58,6 +321,7 @@ const ComboboxClear = React.forwardRef<
58
321
  React.ComponentPropsWithoutRef<typeof ComboboxPrimitive.Clear>
59
322
  >(({ className, children, ...props }, ref) => (
60
323
  <ComboboxPrimitive.Clear
324
+ data-slot="combobox-clear"
61
325
  ref={ref}
62
326
  className={cn(
63
327
  "inline-flex h-8 w-8 items-center justify-center rounded-sm text-muted-foreground",
@@ -80,6 +344,7 @@ const ComboboxContent = React.forwardRef<
80
344
  const content = (
81
345
  <ComboboxPrimitive.Positioner sideOffset={4}>
82
346
  <ComboboxPrimitive.Popup
347
+ data-slot="combobox-content"
83
348
  ref={ref}
84
349
  className={cn(
85
350
  "relative z-50 min-w-[var(--anchor-width)] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md",
@@ -106,7 +371,8 @@ const ComboboxList = React.forwardRef<
106
371
  React.ComponentPropsWithoutRef<typeof ComboboxPrimitive.List>
107
372
  >(({ className, ...props }, ref) => (
108
373
  <ComboboxPrimitive.List
109
- ref={ref}
374
+ data-slot="combobox-list"
375
+ ref={useMergedRef(ref, React.useContext(ComboboxAgentContext)?.list)}
110
376
  className={cn("max-h-80 overflow-y-auto p-1", className)}
111
377
  {...props}
112
378
  />
@@ -118,33 +384,49 @@ const ComboboxItem = React.forwardRef<
118
384
  React.ComponentPropsWithoutRef<typeof ComboboxPrimitive.Item> & {
119
385
  inset?: boolean
120
386
  }
121
- >(({ className, children, inset, ...props }, ref) => (
122
- <ComboboxPrimitive.Item
123
- ref={ref}
124
- className={cn(
125
- "relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none",
126
- "data-highlighted:bg-accent data-highlighted:text-accent-foreground",
127
- "data-disabled:pointer-events-none data-disabled:opacity-50",
128
- inset && "pl-10",
129
- className
130
- )}
131
- {...props}
132
- >
133
- <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
134
- <ComboboxPrimitive.ItemIndicator>
135
- <Check className="h-4 w-4" />
136
- </ComboboxPrimitive.ItemIndicator>
137
- </span>
138
- {children}
139
- </ComboboxPrimitive.Item>
140
- ))
387
+ >(({ className, children, inset, ...props }, ref) => {
388
+ const combobox = React.useContext(ComboboxAgentContext)
389
+ const element = React.useRef<HTMLDivElement | null>(null)
390
+ const { value } = props
391
+
392
+ React.useEffect(() => {
393
+ const el = element.current
394
+ if (!combobox || !el) return
395
+ combobox.items.set(el, value)
396
+ return () => {
397
+ combobox.items.delete(el)
398
+ }
399
+ }, [combobox, value])
400
+
401
+ return (
402
+ <ComboboxPrimitive.Item
403
+ data-slot="combobox-item"
404
+ ref={useMergedRef(ref, element)}
405
+ className={cn(
406
+ "relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none",
407
+ "data-highlighted:bg-accent data-highlighted:text-accent-foreground",
408
+ "data-disabled:pointer-events-none data-disabled:opacity-50",
409
+ inset && "pl-10",
410
+ className
411
+ )}
412
+ {...props}
413
+ >
414
+ <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
415
+ <ComboboxPrimitive.ItemIndicator>
416
+ <Check className="h-4 w-4" />
417
+ </ComboboxPrimitive.ItemIndicator>
418
+ </span>
419
+ {children}
420
+ </ComboboxPrimitive.Item>
421
+ )
422
+ })
141
423
  ComboboxItem.displayName = "ComboboxItem"
142
424
 
143
425
  const ComboboxGroup = React.forwardRef<
144
426
  React.ComponentRef<typeof ComboboxPrimitive.Group>,
145
427
  React.ComponentPropsWithoutRef<typeof ComboboxPrimitive.Group>
146
428
  >(({ className, ...props }, ref) => (
147
- <ComboboxPrimitive.Group ref={ref} className={cn(className)} {...props} />
429
+ <ComboboxPrimitive.Group data-slot="combobox-group" ref={ref} className={cn(className)} {...props} />
148
430
  ))
149
431
  ComboboxGroup.displayName = "ComboboxGroup"
150
432
 
@@ -153,6 +435,7 @@ const ComboboxGroupLabel = React.forwardRef<
153
435
  React.ComponentPropsWithoutRef<typeof ComboboxPrimitive.GroupLabel>
154
436
  >(({ className, ...props }, ref) => (
155
437
  <ComboboxPrimitive.GroupLabel
438
+ data-slot="combobox-group-label"
156
439
  ref={ref}
157
440
  className={cn("px-2 py-1.5 text-xs font-medium text-muted-foreground", className)}
158
441
  {...props}
@@ -165,6 +448,7 @@ const ComboboxEmpty = React.forwardRef<
165
448
  React.ComponentPropsWithoutRef<typeof ComboboxPrimitive.Empty>
166
449
  >(({ className, ...props }, ref) => (
167
450
  <ComboboxPrimitive.Empty
451
+ data-slot="combobox-empty"
168
452
  ref={ref}
169
453
  className={cn("p-2 text-center text-sm text-muted-foreground", className)}
170
454
  {...props}
@@ -176,7 +460,7 @@ const ComboboxStatus = React.forwardRef<
176
460
  React.ComponentRef<typeof ComboboxPrimitive.Status>,
177
461
  React.ComponentPropsWithoutRef<typeof ComboboxPrimitive.Status>
178
462
  >(({ className, ...props }, ref) => (
179
- <ComboboxPrimitive.Status ref={ref} className={cn("sr-only", className)} {...props} />
463
+ <ComboboxPrimitive.Status data-slot="combobox-status" ref={ref} className={cn("sr-only", className)} {...props} />
180
464
  ))
181
465
  ComboboxStatus.displayName = "ComboboxStatus"
182
466
 
@@ -185,6 +469,7 @@ const ComboboxLabel = React.forwardRef<
185
469
  React.ComponentPropsWithoutRef<typeof ComboboxPrimitive.Label>
186
470
  >(({ className, ...props }, ref) => (
187
471
  <ComboboxPrimitive.Label
472
+ data-slot="combobox-label"
188
473
  ref={ref}
189
474
  className={cn("block text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70", className)}
190
475
  {...props}
@@ -197,6 +482,7 @@ const ComboboxSeparator = React.forwardRef<
197
482
  React.ComponentPropsWithoutRef<typeof ComboboxPrimitive.Separator>
198
483
  >(({ className, ...props }, ref) => (
199
484
  <ComboboxPrimitive.Separator
485
+ data-slot="combobox-separator"
200
486
  ref={ref}
201
487
  className={cn("-mx-1 my-1 h-px bg-border", className)}
202
488
  {...props}
@@ -11,6 +11,7 @@ import {
11
11
  useTransform,
12
12
  } from "motion/react"
13
13
  import { cn } from "@/lib/utils"
14
+ import { changeAsAgent, useAgentControl } from "@/components/ui/agent"
14
15
 
15
16
  /** `useReducedMotion` reads the OS setting only, and only at mount. Also honour an
16
17
  * app-level `<MotionConfig reducedMotion>`, so a user preference in the host app
@@ -39,6 +40,53 @@ function compose<E>(
39
40
 
40
41
  const clamp = (n: number) => Math.min(100, Math.max(0, n))
41
42
 
43
+ /** What moved the divider. Cancel one from `onPositionChange` and the divider goes back. */
44
+ export interface CompareSliderChangeDetails {
45
+ reason: "drag" | "keyboard" | "imperative-action"
46
+ isCanceled: boolean
47
+ cancel: () => void
48
+ }
49
+
50
+ function personChange(reason: "drag" | "keyboard"): CompareSliderChangeDetails {
51
+ const details: CompareSliderChangeDetails = {
52
+ reason,
53
+ isCanceled: false,
54
+ cancel: () => {
55
+ details.isCanceled = true
56
+ },
57
+ }
58
+ return details
59
+ }
60
+
61
+ /** A position an agent sent, rounded, or what is wrong with it. */
62
+ function agentPosition(wanted: unknown): number | string {
63
+ const n = Number(wanted)
64
+ if (wanted === "" || wanted === null || !Number.isFinite(n)) return `"${String(wanted)}" is not a number.`
65
+ if (n < 0 || n > 100) return `${n} is out of range: 0 to 100.`
66
+ return Math.round(n)
67
+ }
68
+
69
+ /** The classes a sticky handle changes. */
70
+ const stickyClasses = (sticky: boolean) =>
71
+ sticky
72
+ ? // A panel taller than the screen still has to scroll vertically, so only the
73
+ // horizontal axis is claimed there. `overflow: clip` still trims to the radius but
74
+ // does not open a scrollport, which `overflow: hidden` does, and a sticky knob
75
+ // resolves against the nearest scrollport, so `hidden` would pin it to a box that
76
+ // never scrolls.
77
+ { touch: "touch-pan-y", overflow: "overflow-clip" }
78
+ : { touch: "touch-none", overflow: "overflow-hidden" }
79
+
80
+ /** Panel and handle attributes: locked, or focusable. */
81
+ const lockAttrs = (disabled: boolean) =>
82
+ disabled
83
+ ? { panel: { "data-disabled": "" }, handle: { tabIndex: -1, "aria-disabled": true } }
84
+ : { panel: {}, handle: { tabIndex: 0 } }
85
+
86
+ /** An agent's position, or the message saying why it cannot have it. */
87
+ const placeAsAgent = (next: number | string, place: (next: number, details: CompareSliderChangeDetails) => void) =>
88
+ typeof next === "string" ? next : changeAsAgent(place, next)
89
+
42
90
  export interface CompareSliderProps
43
91
  extends Omit<React.ComponentProps<"div">, "children" | "onChange"> {
44
92
  /** Content shown on the left of the divider. */
@@ -65,8 +113,10 @@ export interface CompareSliderProps
65
113
  * the panel. Set this when the panel is taller than the screen, or the knob spends
66
114
  * most of the page off-screen. */
67
115
  stickyHandle?: boolean
68
- /** Fired on release and on each keyboard step. */
69
- onPositionChange?: (position: number) => void
116
+ /** Stops the divider from moving. */
117
+ disabled?: boolean
118
+ /** Fired on release and on each keyboard step. Cancel `details` to put the divider back. */
119
+ onPositionChange?: (position: number, details: CompareSliderChangeDetails) => void
70
120
  }
71
121
 
72
122
  /**
@@ -96,6 +146,7 @@ const CompareSlider = React.forwardRef<HTMLDivElement, CompareSliderProps>(
96
146
  drag = "handle",
97
147
  label = "Compare position",
98
148
  stickyHandle = false,
149
+ disabled = false,
99
150
  onPositionChange,
100
151
  className,
101
152
  ...props
@@ -163,27 +214,23 @@ const CompareSlider = React.forwardRef<HTMLDivElement, CompareSliderProps>(
163
214
  // change event for an unchanged value is noise the caller has to filter.
164
215
  const emitted = React.useRef(clamp(defaultPosition))
165
216
 
217
+ /** Reports the change, and says whether it stands. A canceled one leaves the old value announced. */
166
218
  const emit = React.useCallback(
167
- (next: number) => {
168
- setAnnounced(next)
169
- if (next === emitted.current) return
170
- emitted.current = next
171
- onPositionChange?.(next)
219
+ (next: number, details: CompareSliderChangeDetails) => {
220
+ if (next !== emitted.current) onPositionChange?.(next, details)
221
+ const stands = !details.isCanceled
222
+ if (stands) emitted.current = next
223
+ setAnnounced(emitted.current)
224
+ announceNow(emitted.current)
225
+ return stands
172
226
  },
173
- [onPositionChange]
227
+ [onPositionChange, announceNow]
174
228
  )
175
229
 
176
- const commit = React.useCallback(() => {
177
- emit(Math.round(position.get()))
178
- }, [position, emit])
179
-
180
- const stepBy = React.useCallback(
181
- (delta: number) => {
230
+ const moveTo = React.useCallback(
231
+ (next: number) => {
182
232
  stepAnimation.current?.stop()
183
- const next = clamp(settled.current + delta)
184
233
  settled.current = next
185
- const rounded = Math.round(next)
186
- emit(rounded)
187
234
  if (reducedMotion) {
188
235
  position.set(next)
189
236
  return
@@ -193,10 +240,40 @@ const CompareSlider = React.forwardRef<HTMLDivElement, CompareSliderProps>(
193
240
  ease: EASE_OUT,
194
241
  })
195
242
  },
196
- [position, emit, reducedMotion]
243
+ [position, reducedMotion]
244
+ )
245
+
246
+ const commit = React.useCallback(() => {
247
+ if (!emit(Math.round(position.get()), personChange("drag"))) moveTo(emitted.current)
248
+ }, [position, emit, moveTo])
249
+
250
+ /** Moves the divider to `next` unless the app cancels the change. */
251
+ const place = React.useCallback(
252
+ (next: number, details: CompareSliderChangeDetails) => {
253
+ if (emit(Math.round(next), details)) moveTo(next)
254
+ },
255
+ [emit, moveTo]
197
256
  )
198
257
 
258
+ const stepBy = React.useCallback(
259
+ (delta: number) => place(clamp(settled.current + delta), personChange("keyboard")),
260
+ [place]
261
+ )
262
+
263
+ useAgentControl(() => ({
264
+ kind: "slider",
265
+ element: handleRef.current,
266
+ value: emitted.current,
267
+ min: 0,
268
+ max: 100,
269
+ disabled,
270
+ actions: {
271
+ setValue: (wanted: unknown) => placeAsAgent(agentPosition(wanted), place),
272
+ },
273
+ }))
274
+
199
275
  const handleKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
276
+ if (disabled) return
200
277
  const large = event.shiftKey ? 5 : 1
201
278
  switch (event.key) {
202
279
  case "ArrowLeft":
@@ -222,10 +299,9 @@ const CompareSlider = React.forwardRef<HTMLDivElement, CompareSliderProps>(
222
299
  }
223
300
  }
224
301
 
302
+ const lock = lockAttrs(disabled)
225
303
  const onHandle = drag === "handle"
226
- // A panel taller than the screen still has to scroll vertically, so only the
227
- // horizontal axis is claimed there.
228
- const touch = stickyHandle ? "touch-pan-y" : "touch-none"
304
+ const { touch, overflow } = stickyClasses(stickyHandle)
229
305
 
230
306
  const endDrag = (event: React.PointerEvent<HTMLDivElement>) => {
231
307
  if (event.pointerId !== activePointer.current) return
@@ -236,7 +312,7 @@ const CompareSlider = React.forwardRef<HTMLDivElement, CompareSliderProps>(
236
312
 
237
313
  const dragHandlers = {
238
314
  onPointerDown: (event: React.PointerEvent<HTMLDivElement>) => {
239
- if (activePointer.current !== null) return
315
+ if (disabled || activePointer.current !== null) return
240
316
  const rect = containerRef.current?.getBoundingClientRect()
241
317
  if (!rect || rect.width === 0) return
242
318
  // A step still in flight has to be dropped here rather than left to finish,
@@ -289,12 +365,12 @@ const CompareSlider = React.forwardRef<HTMLDivElement, CompareSliderProps>(
289
365
  // In handle mode the layers stay live, so taking either off the container
290
366
  // would break selecting text and scrolling the page under it.
291
367
  onHandle ? "select-auto" : cn("select-none", touch),
292
- // `overflow: clip` still trims to the radius but does not open a scrollport,
293
- // which `overflow: hidden` does — and a sticky knob resolves against the
294
- // nearest scrollport, so `hidden` would pin it to a box that never scrolls.
295
- stickyHandle ? "overflow-clip" : "overflow-hidden",
368
+ overflow,
369
+ "data-[disabled]:opacity-50",
296
370
  className
297
371
  )}
372
+ data-slot="compare-slider"
373
+ {...lock.panel}
298
374
  {...props}
299
375
  {...panelHandlers}
300
376
  >
@@ -322,7 +398,8 @@ const CompareSlider = React.forwardRef<HTMLDivElement, CompareSliderProps>(
322
398
  <div
323
399
  ref={handleRef}
324
400
  role="slider"
325
- tabIndex={0}
401
+ {...lock.handle}
402
+ onKeyDown={handleKeyDown}
326
403
  aria-label={label}
327
404
  aria-valuemin={0}
328
405
  aria-valuemax={100}
@@ -331,7 +408,6 @@ const CompareSlider = React.forwardRef<HTMLDivElement, CompareSliderProps>(
331
408
  // being compared; this supplies the unit.
332
409
  aria-valuetext={`${announced}%`}
333
410
  aria-orientation="horizontal"
334
- onKeyDown={handleKeyDown}
335
411
  {...(onHandle ? dragHandlers : {})}
336
412
  className={cn(
337
413
  "pointer-events-auto absolute inset-y-0 left-0 w-0.5 -translate-x-1/2 cursor-ew-resize bg-background",
@@ -1,2 +1,2 @@
1
1
  export { CompareSlider } from './compare-slider'
2
- export type { CompareSliderProps } from './compare-slider'
2
+ export type { CompareSliderProps, CompareSliderChangeDetails } from './compare-slider'