@dinachi/cli 0.12.0 → 1.0.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 (46) hide show
  1. package/CHANGELOG.md +117 -0
  2. package/dist/index.js +73 -7
  3. package/package.json +1 -1
  4. package/templates/accordion/accordion.tsx +66 -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 +46 -17
  8. package/templates/alert-dialog/index.ts +2 -0
  9. package/templates/animated-tabs/animated-tabs.tsx +65 -5
  10. package/templates/autocomplete/autocomplete.tsx +174 -18
  11. package/templates/carousel/carousel.tsx +102 -24
  12. package/templates/checkbox/checkbox.tsx +60 -4
  13. package/templates/checkbox-group/checkbox-group.tsx +82 -8
  14. package/templates/collapsible/collapsible.tsx +13 -4
  15. package/templates/combobox/combobox.tsx +297 -23
  16. package/templates/compare-slider/compare-slider.tsx +103 -28
  17. package/templates/compare-slider/index.ts +1 -1
  18. package/templates/context-menu/context-menu.tsx +37 -15
  19. package/templates/dialog/dialog.tsx +41 -12
  20. package/templates/drawer/drawer.tsx +18 -3
  21. package/templates/expandable-card/expandable-card.tsx +65 -42
  22. package/templates/field/field.tsx +2 -0
  23. package/templates/hold-to-confirm/hold-to-confirm.tsx +99 -16
  24. package/templates/hold-to-confirm/index.ts +1 -1
  25. package/templates/input/input.tsx +59 -1
  26. package/templates/menu/menu.tsx +26 -9
  27. package/templates/menubar/menubar.tsx +26 -8
  28. package/templates/navigation-menu/navigation-menu.tsx +67 -23
  29. package/templates/number-field/index.ts +1 -0
  30. package/templates/number-field/number-field.tsx +71 -2
  31. package/templates/otp-field/otp-field.tsx +57 -11
  32. package/templates/popover/popover.tsx +18 -3
  33. package/templates/preview-card/preview-card.tsx +16 -2
  34. package/templates/radio/radio.tsx +71 -6
  35. package/templates/select/select.tsx +223 -10
  36. package/templates/slider/slider.tsx +77 -8
  37. package/templates/sortable/sortable.tsx +76 -9
  38. package/templates/swipeable-row/index.ts +1 -1
  39. package/templates/swipeable-row/swipeable-row.tsx +125 -41
  40. package/templates/switch/switch.tsx +41 -4
  41. package/templates/tabs/tabs.tsx +74 -10
  42. package/templates/textarea/index.ts +1 -1
  43. package/templates/textarea/textarea.tsx +70 -4
  44. package/templates/toast/toast.tsx +3 -1
  45. package/templates/toggle/toggle.tsx +39 -7
  46. package/templates/toggle-group/toggle-group.tsx +96 -18
@@ -4,8 +4,267 @@ 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
@@ -17,7 +276,7 @@ const ComboboxInput = React.forwardRef<
17
276
  React.ComponentPropsWithoutRef<typeof ComboboxPrimitive.Input>
18
277
  >(({ className, ...props }, ref) => (
19
278
  <ComboboxPrimitive.Input
20
- ref={ref}
279
+ ref={useMergedRef(ref, React.useContext(ComboboxAgentContext)?.input)}
21
280
  className={cn(
22
281
  "flex h-10 w-full bg-transparent px-3 py-2 text-sm",
23
282
  "placeholder:text-muted-foreground",
@@ -106,7 +365,7 @@ const ComboboxList = React.forwardRef<
106
365
  React.ComponentPropsWithoutRef<typeof ComboboxPrimitive.List>
107
366
  >(({ className, ...props }, ref) => (
108
367
  <ComboboxPrimitive.List
109
- ref={ref}
368
+ ref={useMergedRef(ref, React.useContext(ComboboxAgentContext)?.list)}
110
369
  className={cn("max-h-80 overflow-y-auto p-1", className)}
111
370
  {...props}
112
371
  />
@@ -118,26 +377,41 @@ const ComboboxItem = React.forwardRef<
118
377
  React.ComponentPropsWithoutRef<typeof ComboboxPrimitive.Item> & {
119
378
  inset?: boolean
120
379
  }
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
- ))
380
+ >(({ className, children, inset, ...props }, ref) => {
381
+ const combobox = React.useContext(ComboboxAgentContext)
382
+ const element = React.useRef<HTMLDivElement | null>(null)
383
+ const { value } = props
384
+
385
+ React.useEffect(() => {
386
+ const el = element.current
387
+ if (!combobox || !el) return
388
+ combobox.items.set(el, value)
389
+ return () => {
390
+ combobox.items.delete(el)
391
+ }
392
+ }, [combobox, value])
393
+
394
+ return (
395
+ <ComboboxPrimitive.Item
396
+ ref={useMergedRef(ref, element)}
397
+ className={cn(
398
+ "relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none",
399
+ "data-highlighted:bg-accent data-highlighted:text-accent-foreground",
400
+ "data-disabled:pointer-events-none data-disabled:opacity-50",
401
+ inset && "pl-10",
402
+ className
403
+ )}
404
+ {...props}
405
+ >
406
+ <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
407
+ <ComboboxPrimitive.ItemIndicator>
408
+ <Check className="h-4 w-4" />
409
+ </ComboboxPrimitive.ItemIndicator>
410
+ </span>
411
+ {children}
412
+ </ComboboxPrimitive.Item>
413
+ )
414
+ })
141
415
  ComboboxItem.displayName = "ComboboxItem"
142
416
 
143
417
  const ComboboxGroup = React.forwardRef<
@@ -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,11 @@ 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
+ {...lock.panel}
298
373
  {...props}
299
374
  {...panelHandlers}
300
375
  >
@@ -322,7 +397,8 @@ const CompareSlider = React.forwardRef<HTMLDivElement, CompareSliderProps>(
322
397
  <div
323
398
  ref={handleRef}
324
399
  role="slider"
325
- tabIndex={0}
400
+ {...lock.handle}
401
+ onKeyDown={handleKeyDown}
326
402
  aria-label={label}
327
403
  aria-valuemin={0}
328
404
  aria-valuemax={100}
@@ -331,7 +407,6 @@ const CompareSlider = React.forwardRef<HTMLDivElement, CompareSliderProps>(
331
407
  // being compared; this supplies the unit.
332
408
  aria-valuetext={`${announced}%`}
333
409
  aria-orientation="horizontal"
334
- onKeyDown={handleKeyDown}
335
410
  {...(onHandle ? dragHandlers : {})}
336
411
  className={cn(
337
412
  "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'
@@ -4,22 +4,44 @@ import * as React from "react"
4
4
  import { ContextMenu as BaseContextMenu } from "@base-ui/react/context-menu"
5
5
  import { cn } from "@/lib/utils"
6
6
  import { Check, ChevronRight, Circle } from "lucide-react"
7
+ import { type AgentOpenParts, useAgentOpen, useHasAgent, useMergedRef } from "@/components/ui/agent"
7
8
 
8
- const ContextMenu: React.FC<React.ComponentProps<typeof BaseContextMenu.Root>> = (props) => (
9
- <BaseContextMenu.Root {...props} />
10
- )
9
+ const ContextMenuAgentContext = React.createContext<(AgentOpenParts & { disabled?: boolean }) | null>(null)
10
+
11
+ /**
12
+ * Base UI's root, holding its own open state so an agent can open and close it. Closed,
13
+ * the agent sees the trigger area, named by its `aria-label` or text; open, the popup.
14
+ * The trigger area carries the root's `disabled`, which Base UI does not mark on it.
15
+ */
16
+ const ContextMenu: React.FC<React.ComponentProps<typeof BaseContextMenu.Root>> = ({
17
+ open,
18
+ defaultOpen,
19
+ onOpenChange,
20
+ ...props
21
+ }) => {
22
+ const [state, change, parts] = useAgentOpen("menu", open, defaultOpen, onOpenChange)
23
+ return (
24
+ <ContextMenuAgentContext.Provider value={useHasAgent() ? { ...parts, disabled: props.disabled } : null}>
25
+ <BaseContextMenu.Root {...props} open={state} onOpenChange={change} />
26
+ </ContextMenuAgentContext.Provider>
27
+ )
28
+ }
11
29
  ContextMenu.displayName = "ContextMenu"
12
30
 
13
31
  const ContextMenuTrigger = React.forwardRef<
14
32
  React.ComponentRef<typeof BaseContextMenu.Trigger>,
15
33
  React.ComponentProps<typeof BaseContextMenu.Trigger>
16
- >(({ className, ...props }, ref) => (
17
- <BaseContextMenu.Trigger
18
- ref={ref}
19
- className={cn("select-none", className)}
20
- {...props}
21
- />
22
- ))
34
+ >(({ className, ...props }, ref) => {
35
+ const agent = React.useContext(ContextMenuAgentContext)
36
+ return (
37
+ <BaseContextMenu.Trigger
38
+ ref={useMergedRef(ref, agent?.trigger)}
39
+ data-disabled={agent?.disabled ? "" : undefined}
40
+ className={cn("select-none", className)}
41
+ {...props}
42
+ />
43
+ )
44
+ })
23
45
  ContextMenuTrigger.displayName = "ContextMenuTrigger"
24
46
 
25
47
  const ContextMenuPortal: React.FC<
@@ -33,7 +55,7 @@ const ContextMenuPositioner = React.forwardRef<
33
55
  >(({ className, ...props }, ref) => (
34
56
  <BaseContextMenu.Positioner
35
57
  ref={ref}
36
- className={cn("outline-none", className)}
58
+ className={cn("z-50 outline-none", className)}
37
59
  {...props}
38
60
  />
39
61
  ))
@@ -46,9 +68,9 @@ const ContextMenuContent = React.forwardRef<
46
68
  <ContextMenuPortal>
47
69
  <ContextMenuPositioner>
48
70
  <BaseContextMenu.Popup
49
- ref={ref}
71
+ ref={useMergedRef(ref, React.useContext(ContextMenuAgentContext)?.popup)}
50
72
  className={cn(
51
- "z-50 min-w-48 overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg",
73
+ "min-w-48 overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg",
52
74
  "origin-[var(--transform-origin)]",
53
75
  "outline-none focus:outline-none focus-visible:outline-none",
54
76
  "transition-[transform,scale,opacity] duration-[var(--motion-duration-fast,150ms)] ease-[var(--motion-ease-out,cubic-bezier(0.23,1,0.32,1))]",
@@ -243,11 +265,11 @@ const ContextMenuSubContent = React.forwardRef<
243
265
  React.ComponentProps<typeof BaseContextMenu.Popup>
244
266
  >(({ className, ...props }, ref) => (
245
267
  <BaseContextMenu.Portal>
246
- <BaseContextMenu.Positioner className="outline-none" alignOffset={-4} sideOffset={8}>
268
+ <BaseContextMenu.Positioner className="z-50 outline-none" alignOffset={-4} sideOffset={8}>
247
269
  <BaseContextMenu.Popup
248
270
  ref={ref}
249
271
  className={cn(
250
- "z-50 min-w-32 overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg",
272
+ "min-w-32 overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg",
251
273
  "origin-[var(--transform-origin)]",
252
274
  "outline-none focus:outline-none focus-visible:outline-none",
253
275
  "transition-[transform,scale,opacity] duration-[var(--motion-duration-fast,150ms)] ease-[var(--motion-ease-out,cubic-bezier(0.23,1,0.32,1))]",