@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
@@ -10,6 +10,7 @@ import {
10
10
  type HTMLMotionProps,
11
11
  } from "motion/react"
12
12
  import { cn } from "@/lib/utils"
13
+ import { changeAsAgent, matchAgentChoice, useAgentControl, useHasAgent, useMergedRef } from "@/components/ui/agent"
13
14
 
14
15
  /** `useReducedMotion` reads the OS setting only, and only at mount. Also honour an
15
16
  * app-level `<MotionConfig reducedMotion>`, so a user preference in the host app
@@ -32,6 +33,9 @@ interface SortableContextValue {
32
33
  cancel: (id: string, label: string) => void
33
34
  move: (id: string, delta: number, label: string) => void
34
35
  reducedMotion: boolean
36
+ disabled: boolean
37
+ /** Row labels by id, kept only inside an AgentProvider. */
38
+ labels: Map<string, string> | null
35
39
  }
36
40
 
37
41
  const SortableContext = React.createContext<SortableContextValue | null>(null)
@@ -51,10 +55,32 @@ export interface SortableProps
51
55
  /** The current order, as stable ids. Ids rather than objects because identity is what a
52
56
  * reorder is about, and it is what React's keys need anyway. */
53
57
  value: string[]
54
- onValueChange: (next: string[]) => void
58
+ onValueChange: (next: string[], details: SortableChangeDetails) => void
59
+ /** Turns off the handles, so no row can be moved. */
60
+ disabled?: boolean
55
61
  children?: React.ReactNode
56
62
  }
57
63
 
64
+ export interface SortableChangeDetails {
65
+ reason: "drag" | "keyboard" | "escape-key" | "imperative-action"
66
+ event: Event | undefined
67
+ isCanceled: boolean
68
+ /** Marks the change as refused. The order is yours, so this only tells an agent it failed. */
69
+ cancel: () => void
70
+ }
71
+
72
+ function personChange(reason: Exclude<SortableChangeDetails["reason"], "imperative-action">): SortableChangeDetails {
73
+ const details: SortableChangeDetails = {
74
+ reason,
75
+ event: undefined,
76
+ isCanceled: false,
77
+ cancel: () => {
78
+ details.isCanceled = true
79
+ },
80
+ }
81
+ return details
82
+ }
83
+
58
84
  /**
59
85
  * A list the reader can reorder.
60
86
  *
@@ -68,7 +94,7 @@ export interface SortableProps
68
94
  * reads as having been pushed rather than repainted somewhere else.
69
95
  */
70
96
  const Sortable = React.forwardRef<HTMLUListElement, SortableProps>(
71
- ({ value, onValueChange, className, children, ...props }, ref) => {
97
+ ({ value, onValueChange, disabled = false, className, children, ...props }, ref) => {
72
98
  const reducedMotion = useReducedMotionConfig()
73
99
  const [grabbed, setGrabbed] = React.useState<string | null>(null)
74
100
  const [announcement, setAnnouncement] = React.useState("")
@@ -112,7 +138,7 @@ const Sortable = React.forwardRef<HTMLUListElement, SortableProps>(
112
138
  const original = snapshot.current
113
139
  snapshot.current = null
114
140
  setGrabbed(null)
115
- if (original) onValueChange(original)
141
+ if (original) onValueChange(original, personChange("escape-key"))
116
142
  setAnnouncement(
117
143
  `Cancelled. ${label} back at position ${positionOf(original ?? value, id)} of ${value.length}.`
118
144
  )
@@ -128,25 +154,61 @@ const Sortable = React.forwardRef<HTMLUListElement, SortableProps>(
128
154
 
129
155
  const next = [...value]
130
156
  ;[next[from], next[to]] = [next[to], next[from]]
131
- onValueChange(next)
157
+ const details = personChange("keyboard")
158
+ onValueChange(next, details)
159
+ if (details.isCanceled) return
132
160
  setAnnouncement(`${label}, position ${to + 1} of ${value.length}`)
133
161
  },
134
162
  [value, onValueChange]
135
163
  )
136
164
 
165
+ const hasAgent = useHasAgent()
166
+ const [labelMap] = React.useState(() => new Map<string, string>())
167
+ const labels = hasAgent ? labelMap : null
168
+ const root = React.useRef<HTMLUListElement>(null)
169
+ useAgentControl(() => {
170
+ const choices = value.map((id) => ({ value: id, label: labelMap.get(id) ?? id }))
171
+ return {
172
+ kind: "list",
173
+ element: root.current,
174
+ value: choices.map((c) => c.label).join(", "),
175
+ items: choices.map((c) => c.label),
176
+ disabled,
177
+ actions: {
178
+ move: (wanted: unknown, position: unknown) => {
179
+ if (wanted === null || typeof wanted === "object") {
180
+ return `move takes an item and a position from 1 as two args, e.g. ["${choices[0]?.label ?? "Item"}", 1].`
181
+ }
182
+ const match = matchAgentChoice(choices, wanted)
183
+ if (typeof match === "string") return match
184
+ const to = Number(position)
185
+ if (!Number.isInteger(to) || to < 1 || to > value.length) {
186
+ return `Position must be a whole number from 1 to ${value.length}.`
187
+ }
188
+ if (value[to - 1] === match.value) return
189
+ const next = value.filter((id) => id !== match.value)
190
+ next.splice(to - 1, 0, match.value)
191
+ return changeAsAgent<string[], SortableChangeDetails>(onValueChange, next)
192
+ },
193
+ },
194
+ }
195
+ })
196
+
137
197
  const context = React.useMemo(
138
- () => ({ value, grabbed, grab, drop, cancel, move, reducedMotion }),
139
- [value, grabbed, grab, drop, cancel, move, reducedMotion]
198
+ () => ({ value, grabbed, grab, drop, cancel, move, reducedMotion, disabled, labels }),
199
+ [value, grabbed, grab, drop, cancel, move, reducedMotion, disabled, labels]
140
200
  )
141
201
 
142
202
  return (
143
203
  <SortableContext.Provider value={context}>
144
204
  <Reorder.Group
145
- ref={ref}
205
+ ref={useMergedRef(ref, root)}
146
206
  as="ul"
147
207
  axis="y"
148
208
  values={value}
149
- onReorder={onValueChange}
209
+ onReorder={(next: string[]) => onValueChange(next, personChange("drag"))}
210
+ data-disabled={disabled ? "" : undefined}
211
+ data-slot="sortable"
150
212
  className={cn("list-none space-y-2", className)}
151
213
  {...props}
152
214
  >
@@ -193,6 +255,10 @@ const SortableItem = React.forwardRef<HTMLLIElement, SortableItemProps>(
193
255
  const [dragging, setDragging] = React.useState(false)
194
256
  const grabbed = list.grabbed === id
195
257
  const lifted = dragging || grabbed
258
+ const labels = list.labels
259
+ React.useEffect(() => {
260
+ labels?.set(id, label)
261
+ }, [labels, id, label])
196
262
 
197
263
  const item = React.useMemo(
198
264
  () => ({ id, label, grabbed, dragControls, setDragging }),
@@ -213,6 +279,7 @@ const SortableItem = React.forwardRef<HTMLLIElement, SortableItemProps>(
213
279
  onDragEnd={() => setDragging(false)}
214
280
  animate={{ scale: lifted && !list.reducedMotion ? 1.02 : 1 }}
215
281
  transition={{ type: "spring", bounce: 0.2, duration: 0.3 }}
282
+ data-slot="sortable-item"
216
283
  className={cn(
217
284
  "relative flex items-center gap-3 rounded-xl border bg-background px-3 py-3",
218
285
  lifted ? "z-10 border-primary/50" : "border-border",
@@ -303,9 +370,12 @@ const SortableHandle = React.forwardRef<HTMLButtonElement, SortableHandleProps>(
303
370
  type="button"
304
371
  aria-label={`Reorder ${label}`}
305
372
  aria-pressed={grabbed}
373
+ disabled={list.disabled}
374
+ data-agent-part={list.labels ? "" : undefined}
375
+ data-slot="sortable-handle"
306
376
  onPointerDown={(event) => {
307
377
  onPointerDown?.(event)
308
- if (event.defaultPrevented) return
378
+ if (event.defaultPrevented || list.disabled) return
309
379
  dragControls.start(event)
310
380
  }}
311
381
  onKeyDown={handleKeyDown}
@@ -155,6 +155,7 @@ const StaggerList = React.forwardRef<HTMLUListElement, StaggerListProps>(
155
155
  <StaggerContext.Provider value={contextValue}>
156
156
  <motion.ul
157
157
  ref={ref}
158
+ data-slot="stagger-list"
158
159
  className={cn("list-none", className)}
159
160
  variants={containerVariants}
160
161
  initial="hidden"
@@ -190,6 +191,7 @@ const StaggerListItem = React.forwardRef<HTMLLIElement, StaggerListItemProps>(
190
191
  return (
191
192
  <motion.li
192
193
  ref={ref}
194
+ data-slot="stagger-list-item"
193
195
  className={cn(className)}
194
196
  variants={context.itemVariants}
195
197
  {...props}
@@ -142,6 +142,7 @@ const StreamingText = React.forwardRef<HTMLDivElement, StreamingTextProps>(
142
142
  return (
143
143
  <div
144
144
  ref={ref}
145
+ data-slot="streaming-text"
145
146
  className={cn("text-sm leading-relaxed text-foreground", className)}
146
147
  {...props}
147
148
  >
@@ -1,2 +1,2 @@
1
1
  export { SwipeableRow, SwipeableRowGroup } from './swipeable-row'
2
- export type { SwipeableRowProps, SwipeableRowAction } from './swipeable-row'
2
+ export type { SwipeableRowProps, SwipeableRowAction, SwipeableRowChangeDetails } from './swipeable-row'
@@ -13,6 +13,7 @@ import {
13
13
  type PanInfo,
14
14
  } from "motion/react"
15
15
  import { cn } from "@/lib/utils"
16
+ import { changeAsAgent, useAgentControl, useMergedRef } from "@/components/ui/agent"
16
17
 
17
18
  /** `useReducedMotion` reads the OS setting only, and only at mount. Also honour an
18
19
  * app-level `<MotionConfig reducedMotion>`, so a user preference in the host app
@@ -62,11 +63,33 @@ function SwipeableRowGroup({ children }: { children: React.ReactNode }) {
62
63
  )
63
64
  }
64
65
 
66
+ /** Passed to `onSelect` and `onDismiss`. `cancel()` refuses an agent's press, and keeps a
67
+ * swiped row in place. */
68
+ export interface SwipeableRowChangeDetails {
69
+ reason: "trigger-press" | "swipe" | "imperative-action"
70
+ event: Event | undefined
71
+ isCanceled: boolean
72
+ cancel: () => void
73
+ }
74
+
75
+ function personChange(reason: "trigger-press" | "swipe", event?: Event): SwipeableRowChangeDetails {
76
+ const details: SwipeableRowChangeDetails = {
77
+ reason,
78
+ event,
79
+ isCanceled: false,
80
+ cancel: () => {
81
+ details.isCanceled = true
82
+ },
83
+ }
84
+ return details
85
+ }
86
+
65
87
  export interface SwipeableRowAction {
66
88
  /** Accessible name for the button. It has only an icon, so this is the only name. */
67
89
  label: string
68
90
  icon: React.ReactNode
69
- onSelect: () => void
91
+ onSelect: (details: SwipeableRowChangeDetails) => void
92
+ disabled?: boolean
70
93
  /** Styles the button as destructive, and lends its icon to the full-swipe layer. */
71
94
  destructive?: boolean
72
95
  className?: string
@@ -81,7 +104,7 @@ export interface SwipeableRowProps
81
104
  * Committing a full swipe. Omit it and the row only ever opens — there is no
82
105
  * threshold, and no destructive layer.
83
106
  */
84
- onDismiss?: () => void
107
+ onDismiss?: (details: SwipeableRowChangeDetails) => void
85
108
  /** Fraction of the row's width past which releasing commits `onDismiss`. */
86
109
  dismissAt?: number
87
110
  /** Width of each action button in px. */
@@ -105,6 +128,18 @@ export interface SwipeableRowProps
105
128
  * The projection is measured from where the row *is*, not from how far the finger moved.
106
129
  * Under drag elasticity those two disagree, and the eye is following the row.
107
130
  */
131
+ /** The row's text with its pieces kept apart, so a title, badge and name read as words. */
132
+ function wordsOf(el: Element | null): string | undefined {
133
+ if (!el) return undefined
134
+ const words: string[] = []
135
+ const walker = el.ownerDocument.createTreeWalker(el, NodeFilter.SHOW_TEXT)
136
+ while (walker.nextNode()) {
137
+ const text = walker.currentNode.nodeValue?.trim()
138
+ if (text) words.push(text)
139
+ }
140
+ return words.join(" ") || undefined
141
+ }
142
+
108
143
  const SwipeableRow = React.forwardRef<HTMLDivElement, SwipeableRowProps>(
109
144
  // The gesture is already out in `useSwipeGesture`. What is left is four layers that
110
145
  // each exist only under some condition — actions, the committed wash, the armed icon,
@@ -125,6 +160,7 @@ const SwipeableRow = React.forwardRef<HTMLDivElement, SwipeableRowProps>(
125
160
  const reducedMotion = useReducedMotionConfig()
126
161
  const x = useMotionValue(0)
127
162
  const rowRef = React.useRef<HTMLDivElement>(null)
163
+ const contentRef = React.useRef<HTMLDivElement>(null)
128
164
 
129
165
  /** Where the row rests with its actions showing. Derived, so adding an action moves
130
166
  * the resting point instead of leaving a button off the edge. */
@@ -174,6 +210,25 @@ const SwipeableRow = React.forwardRef<HTMLDivElement, SwipeableRowProps>(
174
210
  onDismiss,
175
211
  })
176
212
 
213
+ // The row is a region its action buttons sit in, named by its content.
214
+ useAgentControl(() => {
215
+ const row = rowRef.current
216
+ return {
217
+ kind: "region",
218
+ element: row,
219
+ label: row?.matches("[aria-label], [aria-labelledby]")
220
+ ? undefined
221
+ : wordsOf(contentRef.current),
222
+ actions: {
223
+ ...(onDismiss && {
224
+ dismiss: () =>
225
+ changeAsAgent((_: undefined, d: SwipeableRowChangeDetails) => onDismiss(d), undefined) ??
226
+ void animate(x, -width, SETTLE),
227
+ }),
228
+ },
229
+ }
230
+ })
231
+
177
232
  const destructive = actions.find((action) => action.destructive)
178
233
  const snap = reducedMotion
179
234
  ? { duration: 0 }
@@ -181,40 +236,21 @@ const SwipeableRow = React.forwardRef<HTMLDivElement, SwipeableRowProps>(
181
236
 
182
237
  return (
183
238
  <div
184
- ref={mergeRefs(ref, rowRef)}
239
+ ref={useMergedRef(ref, rowRef)}
240
+ data-slot="swipeable-row"
185
241
  className={cn("relative overflow-hidden rounded-xl", className)}
186
242
  {...props}
187
243
  >
188
244
  <div className="absolute inset-y-0 right-0 flex items-stretch">
189
245
  {actions.map((action) => (
190
- // Real buttons, always focusable. A swipe is not an accessible affordance on
191
- // its own, so the keyboard path is the same set of controls — focusing one
192
- // opens the row so the reader can see what they are on.
193
- <motion.button
246
+ <ActionButton
194
247
  key={action.label}
195
- type="button"
196
- aria-label={action.label}
248
+ action={action}
249
+ width={actionWidth}
250
+ motionStyle={reducedMotion ? null : { scale: actionScale, opacity: actionOpacity }}
197
251
  onFocus={() => settle(openAt)}
198
252
  onBlur={() => settle(0)}
199
- onClick={action.onSelect}
200
- // Width inline rather than as a class, so `actionWidth` cannot drift out of
201
- // step with a Tailwind arbitrary value.
202
- style={{
203
- width: actionWidth,
204
- ...(reducedMotion
205
- ? null
206
- : { scale: actionScale, opacity: actionOpacity }),
207
- }}
208
- className={cn(
209
- "flex shrink-0 items-center justify-center focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",
210
- action.destructive
211
- ? "bg-destructive text-destructive-foreground"
212
- : "bg-muted text-foreground",
213
- action.className
214
- )}
215
- >
216
- {action.icon}
217
- </motion.button>
253
+ />
218
254
  ))}
219
255
  </div>
220
256
 
@@ -269,6 +305,7 @@ const SwipeableRow = React.forwardRef<HTMLDivElement, SwipeableRowProps>(
269
305
  )}
270
306
  >
271
307
  <div
308
+ ref={contentRef}
272
309
  className="min-w-0 flex-1 px-4 py-3.5"
273
310
  // Under reduced motion the row never moves, so the actions have to be given
274
311
  // room rather than revealed.
@@ -283,6 +320,59 @@ const SwipeableRow = React.forwardRef<HTMLDivElement, SwipeableRowProps>(
283
320
  )
284
321
  SwipeableRow.displayName = "SwipeableRow"
285
322
 
323
+ /**
324
+ * One action under the row. Real buttons, always focusable: a swipe is not an accessible
325
+ * affordance on its own, so the keyboard path is the same set of controls, and focusing
326
+ * one opens the row so the reader can see what they are on. An agent presses them too,
327
+ * hidden or not.
328
+ */
329
+ function ActionButton({
330
+ action,
331
+ width,
332
+ motionStyle,
333
+ onFocus,
334
+ onBlur,
335
+ }: {
336
+ action: SwipeableRowAction
337
+ width: number
338
+ motionStyle: { scale: MotionValue<number>; opacity: MotionValue<number> } | null
339
+ onFocus: () => void
340
+ onBlur: () => void
341
+ }) {
342
+ const element = React.useRef<HTMLButtonElement>(null)
343
+ useAgentControl(() => ({
344
+ kind: "button",
345
+ element: element.current,
346
+ label: action.label,
347
+ disabled: action.disabled,
348
+ actions: {
349
+ press: () => changeAsAgent((_: undefined, d: SwipeableRowChangeDetails) => action.onSelect(d), undefined),
350
+ },
351
+ }))
352
+ return (
353
+ <motion.button
354
+ ref={element}
355
+ type="button"
356
+ aria-label={action.label}
357
+ disabled={action.disabled}
358
+ onFocus={onFocus}
359
+ onBlur={onBlur}
360
+ onClick={(event) => action.onSelect(personChange("trigger-press", event.nativeEvent))}
361
+ // Width inline rather than as a class, so `actionWidth` cannot drift out of step
362
+ // with a Tailwind arbitrary value.
363
+ style={{ width, ...motionStyle }}
364
+ className={cn(
365
+ "flex shrink-0 items-center justify-center focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",
366
+ "disabled:opacity-50",
367
+ action.destructive ? "bg-destructive text-destructive-foreground" : "bg-muted text-foreground",
368
+ action.className
369
+ )}
370
+ >
371
+ {action.icon}
372
+ </motion.button>
373
+ )
374
+ }
375
+
286
376
  /**
287
377
  * Everything the release decides: where the row lands, and whether it lands at all.
288
378
  *
@@ -300,7 +390,7 @@ function useSwipeGesture({
300
390
  openAt: number
301
391
  width: number
302
392
  dismissAt: number
303
- onDismiss?: () => void
393
+ onDismiss?: (details: SwipeableRowChangeDetails) => void
304
394
  }) {
305
395
  const groupRef = React.useContext(SwipeableRowGroupContext)
306
396
 
@@ -330,7 +420,7 @@ function useSwipeGesture({
330
420
  )
331
421
 
332
422
  const onDragEnd = React.useCallback(
333
- (_: unknown, info: PanInfo) => {
423
+ (event: unknown, info: PanInfo) => {
334
424
  const projected = x.get() + info.velocity.x * PROJECTION
335
425
 
336
426
  if (onDismiss && width && projected < -width * dismissAt) {
@@ -342,7 +432,12 @@ function useSwipeGesture({
342
432
  velocity: info.velocity.x,
343
433
  stiffness: 420,
344
434
  damping: 46,
345
- onComplete: onDismiss,
435
+ // Refused, the row comes back rather than leaving a gap where it was.
436
+ onComplete: () => {
437
+ const details = personChange("swipe", event instanceof Event ? event : undefined)
438
+ onDismiss(details)
439
+ if (details.isCanceled) animate(x, 0, SETTLE)
440
+ },
346
441
  })
347
442
  return
348
443
  }
@@ -355,14 +450,4 @@ function useSwipeGesture({
355
450
  return { settle, onDragEnd }
356
451
  }
357
452
 
358
- /** The row needs its own measurement and the caller may want the node too. */
359
- function mergeRefs<T>(...refs: (React.Ref<T> | undefined)[]): React.RefCallback<T> {
360
- return (value) => {
361
- for (const ref of refs) {
362
- if (typeof ref === "function") ref(value)
363
- else if (ref) (ref as React.RefObject<T | null>).current = value
364
- }
365
- }
366
- }
367
-
368
453
  export { SwipeableRow, SwipeableRowGroup }
@@ -3,14 +3,49 @@
3
3
  import * as React from "react"
4
4
  import { Switch as SwitchPrimitive } from "@base-ui/react/switch"
5
5
  import { cn } from "@/lib/utils"
6
+ import { agentChecked, changeAsAgent, useAgentControl, useAgentState, useMergedRef } from "@/components/ui/agent"
6
7
 
8
+ type SwitchProps = React.ComponentPropsWithoutRef<typeof SwitchPrimitive.Root>
9
+
10
+ /**
11
+ * Base UI's switch, holding its own checked state so an agent can flip it the way a parent
12
+ * would. Controlled use is unchanged, and `onCheckedChange` sees the agent's changes first
13
+ * and can cancel them.
14
+ */
7
15
  const Switch = React.forwardRef<
8
16
  React.ComponentRef<typeof SwitchPrimitive.Root>,
9
- React.ComponentPropsWithoutRef<typeof SwitchPrimitive.Root>
10
- >(({ className, ...props }, ref) => (
17
+ SwitchProps
18
+ >(({ className, checked: checkedProp, defaultChecked = false, onCheckedChange, ...props }, ref) => {
19
+ const [checked, change] = useAgentState<boolean, SwitchPrimitive.Root.ChangeEventDetails>(
20
+ checkedProp,
21
+ defaultChecked,
22
+ onCheckedChange
23
+ )
24
+ const element = React.useRef<HTMLElement | null>(null)
25
+ const mergedRef = useMergedRef(ref, element)
26
+
27
+ useAgentControl(() => {
28
+ const set = (next: boolean) => {
29
+ if (props.readOnly) return "The switch is read-only."
30
+ return next === checked ? undefined : changeAsAgent(change, next)
31
+ }
32
+ return {
33
+ kind: "switch",
34
+ element: element.current,
35
+ checked,
36
+ disabled: props.disabled,
37
+ actions: {
38
+ toggle: () => set(!checked),
39
+ setChecked: (value: unknown) => set(agentChecked(value)),
40
+ },
41
+ }
42
+ })
43
+
44
+ return (
11
45
  <span className="relative inline-flex [&>input]:!absolute">
12
46
  <SwitchPrimitive.Root
13
- ref={ref}
47
+ ref={mergedRef}
48
+ data-slot="switch"
14
49
  className={cn(
15
50
  "inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors duration-[var(--motion-duration-fast,150ms)]",
16
51
  "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
@@ -20,9 +55,12 @@ const Switch = React.forwardRef<
20
55
  className
21
56
  )}
22
57
  {...props}
58
+ checked={checked}
59
+ onCheckedChange={change}
23
60
  />
24
61
  </span>
25
- ))
62
+ )
63
+ })
26
64
  Switch.displayName = "Switch"
27
65
 
28
66
  const SwitchThumb = React.forwardRef<
@@ -31,6 +69,7 @@ const SwitchThumb = React.forwardRef<
31
69
  >(({ className, ...props }, ref) => (
32
70
  <SwitchPrimitive.Thumb
33
71
  ref={ref}
72
+ data-slot="switch-thumb"
34
73
  className={cn(
35
74
  "pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0",
36
75
  "transition-transform duration-[var(--motion-duration-fast,150ms)] ease-[var(--motion-ease-out,cubic-bezier(0.23,1,0.32,1))]",
@@ -1,17 +1,76 @@
1
1
  import * as React from "react";
2
2
  import { Tabs as BaseTabs } from "@base-ui/react/tabs";
3
3
  import { cn } from "@/lib/utils";
4
+ import {
5
+ agentChoicesOf,
6
+ changeAsAgent,
7
+ matchAgentChoice,
8
+ useAgentControl,
9
+ useAgentItem,
10
+ useHasAgent,
11
+ useMergedRef,
12
+ type AgentItems,
13
+ } from "@/components/ui/agent";
4
14
 
15
+ type Details = BaseTabs.Root.ChangeEventDetails;
16
+
17
+ const TabsAgentContext = React.createContext<AgentItems | null>(null);
18
+
19
+ /**
20
+ * Base UI keeps the value, so its fallbacks for a missing or disabled tab still apply.
21
+ * The agent selects a tab by clicking it, and the app sees that change with the agent's
22
+ * details, which it can cancel.
23
+ */
5
24
  const Tabs = React.forwardRef<
6
25
  React.ComponentRef<typeof BaseTabs.Root>,
7
26
  React.ComponentProps<typeof BaseTabs.Root>
8
- >(({ className, ...props }, ref) => (
9
- <BaseTabs.Root
10
- ref={ref}
11
- className={cn("w-full", className)}
12
- {...props}
13
- />
14
- ));
27
+ >(({ className, onValueChange, ...props }, ref) => {
28
+ const element = React.useRef<HTMLDivElement | null>(null);
29
+ const [items] = React.useState<AgentItems>(() => new Map());
30
+ const pending = React.useRef<Details | null>(null);
31
+
32
+ const change = (value: unknown, details: Details) => {
33
+ const agent = pending.current;
34
+ pending.current = null;
35
+ onValueChange?.(value, agent ?? details);
36
+ if (agent?.isCanceled) details.cancel();
37
+ };
38
+
39
+ useAgentControl(() => {
40
+ const choices = agentChoicesOf(items);
41
+ const active = [...items].find(([el]) => el.getAttribute("aria-selected") === "true")?.[1];
42
+ const select = (wanted: unknown) => {
43
+ const match = matchAgentChoice(choices, wanted);
44
+ if (typeof match === "string") return match;
45
+ const tab = [...items].find(([, v]) => v === match.value)?.[0];
46
+ return changeAsAgent<unknown, Details>((_, details) => {
47
+ pending.current = details;
48
+ tab?.click();
49
+ pending.current = null;
50
+ }, match.value);
51
+ };
52
+ return {
53
+ kind: "tabs",
54
+ element: choices.length ? element.current : null,
55
+ value: choices.find((c) => c.value === active)?.label ?? "",
56
+ items: choices.map((c) => c.label),
57
+ disabled: choices.length > 0 && choices.every((c) => c.disabled),
58
+ actions: { select },
59
+ };
60
+ });
61
+
62
+ return (
63
+ <TabsAgentContext.Provider value={useHasAgent() ? items : null}>
64
+ <BaseTabs.Root
65
+ ref={useMergedRef(ref, element)}
66
+ className={cn("w-full", className)}
67
+ onValueChange={change}
68
+ data-slot="tabs"
69
+ {...props}
70
+ />
71
+ </TabsAgentContext.Provider>
72
+ );
73
+ });
15
74
  Tabs.displayName = "Tabs";
16
75
 
17
76
  const TabsList = React.forwardRef<
@@ -24,6 +83,7 @@ const TabsList = React.forwardRef<
24
83
  "inline-flex h-10 items-center justify-center rounded-md p-1 text-muted-foreground z-0",
25
84
  className
26
85
  )}
86
+ data-slot="tabs-list"
27
87
  {...props}
28
88
  />
29
89
  ));
@@ -32,9 +92,14 @@ TabsList.displayName = "TabsList";
32
92
  const TabsTrigger = React.forwardRef<
33
93
  React.ComponentRef<typeof BaseTabs.Tab>,
34
94
  React.ComponentProps<typeof BaseTabs.Tab>
35
- >(({ className, ...props }, ref) => (
95
+ >(({ className, ...props }, ref) => {
96
+ const items = React.useContext(TabsAgentContext);
97
+ const element = React.useRef<HTMLButtonElement | null>(null);
98
+ useAgentItem(items, element, props.value);
99
+ return (
36
100
  <BaseTabs.Tab
37
- ref={ref}
101
+ ref={useMergedRef(ref, element)}
102
+ data-agent-part={items ? "" : undefined}
38
103
  className={cn(
39
104
  "inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background",
40
105
  "transition-[color,background-color,box-shadow] duration-[var(--motion-duration-fast,150ms)]",
@@ -44,9 +109,11 @@ const TabsTrigger = React.forwardRef<
44
109
  "hover:text-foreground",
45
110
  className
46
111
  )}
112
+ data-slot="tabs-trigger"
47
113
  {...props}
48
114
  />
49
- ));
115
+ );
116
+ });
50
117
  TabsTrigger.displayName = "TabsTrigger";
51
118
 
52
119
  const TabsContent = React.forwardRef<
@@ -60,6 +127,7 @@ const TabsContent = React.forwardRef<
60
127
  "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
61
128
  className
62
129
  )}
130
+ data-slot="tabs-content"
63
131
  {...props}
64
132
  />
65
133
  ));
@@ -82,6 +150,7 @@ const TabsIndicator = React.forwardRef<
82
150
  "motion-reduce:transition-none",
83
151
  className
84
152
  )}
153
+ data-slot="tabs-indicator"
85
154
  {...props}
86
155
  />
87
156
  ));
@@ -55,6 +55,7 @@ const Text = React.forwardRef<HTMLElement, TextProps>(
55
55
 
56
56
  return (
57
57
  <Component
58
+ data-slot="text"
58
59
  ref={ref}
59
60
  className={cn(textVariants({ variant }), className)}
60
61
  {...props}