@dinachi/cli 1.0.0 → 1.3.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 (105) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/dist/index.js +244 -72
  3. package/package.json +5 -1
  4. package/templates/accordion/accordion.tsx +5 -1
  5. package/templates/agent/agent.tsx +35 -18
  6. package/templates/alert/alert.tsx +345 -0
  7. package/templates/alert/index.ts +16 -0
  8. package/templates/alert-dialog/alert-dialog.tsx +14 -3
  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 +4 -0
  12. package/templates/ask-bar/ask-bar.tsx +1061 -0
  13. package/templates/ask-bar/index.ts +1 -0
  14. package/templates/autocomplete/autocomplete.tsx +14 -4
  15. package/templates/avatar/avatar.tsx +3 -0
  16. package/templates/badge/badge.tsx +1 -0
  17. package/templates/breadcrumb/breadcrumb.tsx +606 -0
  18. package/templates/breadcrumb/index.ts +9 -0
  19. package/templates/button/button.tsx +1 -0
  20. package/templates/calendar/calendar.tsx +1155 -0
  21. package/templates/calendar/index.ts +15 -0
  22. package/templates/card/card.tsx +6 -1
  23. package/templates/carousel/carousel.tsx +7 -0
  24. package/templates/checkbox/checkbox.tsx +1 -0
  25. package/templates/checkbox-group/checkbox-group.tsx +1 -0
  26. package/templates/collapsible/collapsible.tsx +3 -1
  27. package/templates/combobox/combobox.tsx +15 -4
  28. package/templates/command-items/command-items.tsx +69 -0
  29. package/templates/command-items/index.ts +1 -0
  30. package/templates/command-palette/command-palette.tsx +954 -0
  31. package/templates/command-palette/index.ts +1 -0
  32. package/templates/compare-slider/compare-slider.tsx +1 -0
  33. package/templates/comparison-table/comparison-table.tsx +540 -0
  34. package/templates/comparison-table/index.ts +15 -0
  35. package/templates/context-menu/context-menu.tsx +61 -14
  36. package/templates/data-table/data-table.tsx +2077 -0
  37. package/templates/data-table/index.ts +14 -0
  38. package/templates/date-picker/date-picker.tsx +527 -0
  39. package/templates/date-picker/index.ts +2 -0
  40. package/templates/date-range-picker/date-range-picker.tsx +504 -0
  41. package/templates/date-range-picker/index.ts +2 -0
  42. package/templates/detail-list/detail-list.tsx +419 -0
  43. package/templates/detail-list/index.ts +12 -0
  44. package/templates/dialog/dialog.tsx +13 -3
  45. package/templates/drawer/drawer.tsx +19 -6
  46. package/templates/expandable-card/expandable-card.tsx +5 -1
  47. package/templates/field/field.tsx +5 -1
  48. package/templates/fieldset/fieldset.tsx +2 -0
  49. package/templates/form/form.tsx +1 -0
  50. package/templates/heat-table/heat-table.tsx +613 -0
  51. package/templates/heat-table/index.ts +9 -0
  52. package/templates/hold-to-confirm/hold-to-confirm.tsx +1 -0
  53. package/templates/input/input.tsx +1 -0
  54. package/templates/label/label.tsx +1 -0
  55. package/templates/link/link.tsx +1 -0
  56. package/templates/load-transition/load-transition.tsx +1 -0
  57. package/templates/marquee/marquee.tsx +1 -0
  58. package/templates/menu/menu.tsx +27 -6
  59. package/templates/menubar/menubar.tsx +15 -3
  60. package/templates/meter/meter.tsx +5 -1
  61. package/templates/month-picker/index.ts +1 -0
  62. package/templates/month-picker/month-picker.tsx +351 -0
  63. package/templates/navigation-menu/navigation-menu.tsx +13 -2
  64. package/templates/number-field/number-field.tsx +7 -1
  65. package/templates/number-ticker/number-ticker.tsx +3 -0
  66. package/templates/omnibar/index.ts +1 -0
  67. package/templates/omnibar/omnibar.tsx +1009 -0
  68. package/templates/otp-field/otp-field.tsx +4 -0
  69. package/templates/pagination/index.ts +8 -0
  70. package/templates/pagination/pagination.tsx +389 -0
  71. package/templates/popover/popover.tsx +19 -5
  72. package/templates/preview-card/preview-card.tsx +11 -3
  73. package/templates/progress/progress.tsx +5 -1
  74. package/templates/progress-ring/progress-ring.tsx +1 -0
  75. package/templates/radio/radio.tsx +3 -0
  76. package/templates/scroll-area/scroll-area.tsx +14 -4
  77. package/templates/scroll-progress/scroll-progress.tsx +1 -0
  78. package/templates/scroll-reveal/scroll-reveal.tsx +1 -0
  79. package/templates/select/select.tsx +18 -2
  80. package/templates/separator/separator.tsx +1 -0
  81. package/templates/skeleton/skeleton.tsx +1 -0
  82. package/templates/slider/slider.tsx +7 -0
  83. package/templates/sortable/sortable.tsx +3 -0
  84. package/templates/stagger-list/stagger-list.tsx +2 -0
  85. package/templates/streaming-text/streaming-text.tsx +1 -0
  86. package/templates/swipeable-row/swipeable-row.tsx +1 -0
  87. package/templates/switch/switch.tsx +2 -0
  88. package/templates/table/index.ts +13 -0
  89. package/templates/table/table.tsx +265 -0
  90. package/templates/tabs/tabs.tsx +5 -0
  91. package/templates/text/text.tsx +1 -0
  92. package/templates/text-morph/text-morph.tsx +2 -0
  93. package/templates/text-shimmer/text-shimmer.tsx +1 -0
  94. package/templates/textarea/textarea.tsx +1 -0
  95. package/templates/time-slots/index.ts +1 -0
  96. package/templates/time-slots/time-slots.tsx +589 -0
  97. package/templates/toast/toast.tsx +10 -1
  98. package/templates/toggle/toggle.tsx +1 -0
  99. package/templates/toggle-group/toggle-group.tsx +2 -0
  100. package/templates/toolbar/toolbar.tsx +6 -0
  101. package/templates/tooltip/tooltip.tsx +9 -3
  102. package/templates/week-strip/index.ts +1 -0
  103. package/templates/week-strip/week-strip.tsx +329 -0
  104. package/templates/year-view/index.ts +1 -0
  105. package/templates/year-view/year-view.tsx +362 -0
@@ -0,0 +1,1061 @@
1
+ "use client"
2
+
3
+ import * as React from "react"
4
+ import { createPortal } from "react-dom"
5
+ import { Drawer as DrawerPrimitive } from "@base-ui/react/drawer"
6
+ import { ArrowUp, Check, Sparkles } from "lucide-react"
7
+ import { cn } from "@/lib/utils"
8
+ import {
9
+ agentNodeText,
10
+ changeAsAgent,
11
+ createAgentChangeDetails,
12
+ matchAgentChoice,
13
+ useAgentControl,
14
+ useAgentLatest,
15
+ useAgentState,
16
+ useHasAgent,
17
+ useMergedRef,
18
+ waitForAgent,
19
+ } from "@/components/ui/agent"
20
+ // The command shape and matching the Command Palette uses, so one list serves both.
21
+ import { filterCommands, type CommandAction, type CommandItem } from "@/components/ui/command-items"
22
+
23
+ /** What the person typed values into, keyed by field id. */
24
+ export type AskValues = Record<string, string>
25
+
26
+ /** One value in a plan. */
27
+ export interface AskField {
28
+ /** Referenced from the plan's `sentence`, and the key in `AskValues`. */
29
+ id: string
30
+ /** Names the input. A phone shows it beside the value. */
31
+ label: string
32
+ /** What the app read from the request. */
33
+ value: string
34
+ /** Read back as plain text, not an input. */
35
+ fixed?: boolean
36
+ inputMode?: React.HTMLAttributes<HTMLInputElement>["inputMode"]
37
+ }
38
+
39
+ /** What running a plan did. */
40
+ export interface AskResult {
41
+ /** The done line, such as "Archived 12 orders." */
42
+ message: string
43
+ /** Puts it back. Without it, the done line has no Undo. Return a line to announce, or "Undone." is read. */
44
+ undo?: () => void | string | Promise<void | string>
45
+ }
46
+
47
+ /** The change a request resolves to. Nothing runs until the person presses its button or Enter. */
48
+ export interface AskPlan {
49
+ /** Names the plan for screen readers and the agent; the heading on a phone. */
50
+ title: string
51
+ /** The plan as one sentence: text, with `{ field: id }` where a field's value goes. */
52
+ sentence: (string | { field: string })[]
53
+ fields: AskField[]
54
+ /** One line on what it touches, or a function of the values when it depends on them. */
55
+ touches?: React.ReactNode | ((values: AskValues) => React.ReactNode)
56
+ /** The exact call it makes with these values, shown on request. */
57
+ call?: string | ((values: AskValues) => string)
58
+ /** The button's label for these values, such as "Archive 12 orders". */
59
+ verb: (values: AskValues) => string
60
+ /** Makes the change. Throwing shows the message and keeps the plan. */
61
+ run: (values: AskValues) => AskResult | Promise<AskResult>
62
+ /** Why an agent's run needs a person's approval. Overrides the bar's `confirm`. */
63
+ confirm?: string | false
64
+ }
65
+
66
+ /** How a change was reached. `cancel()` refuses it. */
67
+ export interface AskBarChangeDetails {
68
+ reason: string
69
+ event: Event | undefined
70
+ isCanceled: boolean
71
+ cancel(): void
72
+ }
73
+
74
+ function details(reason: string, event?: Event): AskBarChangeDetails {
75
+ const d = { reason, event, isCanceled: false, cancel: () => void (d.isCanceled = true) }
76
+ return d
77
+ }
78
+
79
+ /** Every word, as the Command Palette matches. If no command has them all, any one word. One pass, up to `limit`. */
80
+ function matchCommands(commands: CommandItem[], query: string, limit: number): CommandItem[] {
81
+ const words = query.split(/\s+/).filter((w) => w.length > 2)
82
+ const all: CommandItem[] = []
83
+ const any: CommandItem[] = []
84
+ for (const c of commands) {
85
+ if (all.length >= limit) break
86
+ if (filterCommands(c, query)) all.push(c)
87
+ else if (!all.length && any.length < limit && words.some((w) => filterCommands(c, w))) any.push(c)
88
+ }
89
+ return all.length ? all : any
90
+ }
91
+
92
+ function firstMatches(commands: CommandItem[], query: string, limit: number, filter: (c: CommandItem, q: string) => boolean) {
93
+ const out: CommandItem[] = []
94
+ for (const c of commands) {
95
+ if (out.length >= limit) break
96
+ if (filter(c, query)) out.push(c)
97
+ }
98
+ return out
99
+ }
100
+
101
+ const valuesOf = (plan: AskPlan | null): AskValues =>
102
+ Object.fromEntries((plan?.fields ?? []).map((f) => [f.id, f.value]))
103
+
104
+ /** The sentence with the values in, as a person reads it. */
105
+ const sentenceOf = (plan: AskPlan, values: AskValues) =>
106
+ plan.sentence.map((p) => (typeof p === "string" ? p : (values[p.field] ?? ""))).join("")
107
+
108
+ const callOf = (plan: AskPlan, values: AskValues) => (typeof plan.call === "function" ? plan.call(values) : plan.call)
109
+
110
+ const touchesOf = (plan: AskPlan, values: AskValues) => (typeof plan.touches === "function" ? plan.touches(values) : plan.touches)
111
+
112
+ /** How long the text stays still before its plan is announced: past a pause between keys, short of a wait. */
113
+ const SETTLE_MS = 700
114
+
115
+ const noSubscribe = () => () => {}
116
+
117
+ const PHONE = "(max-width: 639px)"
118
+
119
+ function usePhone(): boolean {
120
+ return React.useSyncExternalStore(
121
+ (onChange) => {
122
+ const query = window.matchMedia?.(PHONE)
123
+ query?.addEventListener?.("change", onChange)
124
+ return () => query?.removeEventListener?.("change", onChange)
125
+ },
126
+ () => Boolean(window.matchMedia?.(PHONE).matches),
127
+ () => false
128
+ )
129
+ }
130
+
131
+ const useIsomorphicLayoutEffect = typeof window === "undefined" ? React.useEffect : React.useLayoutEffect
132
+
133
+ /** Values the person can still change: tinted, and dark enough to read on the tint. */
134
+ const TINT = "text-[color-mix(in_oklab,var(--info)_70%,var(--foreground))]"
135
+
136
+ type View = "bar" | "typing" | "plan" | "done"
137
+
138
+ interface AskContext {
139
+ part: "" | undefined
140
+ label: string
141
+ disabled: boolean
142
+ phone: boolean
143
+ view: View
144
+ open: boolean
145
+ setOpen: (open: boolean) => void
146
+ setTyping: (typing: boolean) => void
147
+ query: string
148
+ change: (query: string, details: AskBarChangeDetails) => void
149
+ plan: AskPlan | null
150
+ pending: boolean
151
+ values: AskValues
152
+ setValue: (id: string, value: string) => void
153
+ running: boolean
154
+ error: string | undefined
155
+ done: AskResult | null
156
+ undoing: boolean
157
+ undoError: string | undefined
158
+ undoButton: React.MutableRefObject<HTMLButtonElement | null>
159
+ commands: CommandItem[]
160
+ highlight: number
161
+ setHighlight: (index: number) => void
162
+ suggestions: string[]
163
+ suggestion: (text: string, event?: Event) => void
164
+ above: boolean
165
+ focused: boolean
166
+ setFocused: (focused: boolean) => void
167
+ confirm: string | undefined
168
+ send: (event?: Event) => void
169
+ run: (event?: Event) => Promise<string | AskResult>
170
+ undo: () => void
171
+ command: (command: CommandItem, action?: CommandAction, details?: AskBarChangeDetails) => string | undefined
172
+ input: React.MutableRefObject<HTMLInputElement | null>
173
+ content: React.MutableRefObject<HTMLElement | null>
174
+ trigger: React.MutableRefObject<HTMLButtonElement | null>
175
+ }
176
+
177
+ const AskContext = React.createContext<AskContext | null>(null)
178
+
179
+ function useAsk(part: string): AskContext {
180
+ const context = React.useContext(AskContext)
181
+ if (!context) throw new Error(`${part} must be inside <AskBar>.`)
182
+ return context
183
+ }
184
+
185
+ export interface AskBarProps {
186
+ /**
187
+ * Turns the text into a plan, or `null` when it is not one. Sync or async; only the
188
+ * answer for the latest text is kept, and `signal` aborts once the text moves on.
189
+ * Called as the text changes, never to run.
190
+ */
191
+ resolve?: (
192
+ query: string,
193
+ options: { signal: AbortSignal }
194
+ ) => AskPlan | null | undefined | Promise<AskPlan | null | undefined>
195
+ /** Listed when the text resolves to no plan. */
196
+ commands?: CommandItem[]
197
+ /** Runs a picked command with its first action, or the one an agent asked for. */
198
+ onCommand?: (command: CommandItem, action: CommandAction | undefined, details: AskBarChangeDetails) => void
199
+ /** Decides which commands match. Defaults to every word, then any word. */
200
+ filter?: (command: CommandItem, query: string) => boolean
201
+ /** How many commands to list. */
202
+ limit?: number
203
+ /** Requests to offer as chips. */
204
+ suggestions?: string[]
205
+ /** `"focus"`: every chip while the empty field has focus. `"typing"`: only chips that contain the text. */
206
+ suggest?: "focus" | "typing"
207
+ value?: string
208
+ defaultValue?: string
209
+ onValueChange?: (value: string, details: AskBarChangeDetails) => void
210
+ /** The letter that focuses it with Cmd or Ctrl. `false` turns the shortcut off. */
211
+ shortcut?: string | false
212
+ /** Names the bar and its field, and is what an agent finds it by. */
213
+ label?: string
214
+ /** Why an agent's run needs a person's approval. `false` lets an agent run plans unasked. */
215
+ confirm?: string | false
216
+ disabled?: boolean
217
+ children?: React.ReactNode
218
+ }
219
+
220
+ /**
221
+ * A bar docked at the bottom of the page that takes a request or a command name. The app
222
+ * resolves the text to a plan, which reads back as a sentence with its values editable.
223
+ */
224
+ function AskBar({
225
+ resolve,
226
+ commands = [],
227
+ onCommand,
228
+ filter,
229
+ limit = 5,
230
+ suggestions = [],
231
+ suggest = "focus",
232
+ value,
233
+ defaultValue = "",
234
+ onValueChange,
235
+ shortcut = "k",
236
+ label = "Ask",
237
+ confirm = "Changes many records at once.",
238
+ disabled = false,
239
+ children,
240
+ }: AskBarProps) {
241
+ const [query, setQuery] = useAgentState(value, defaultValue, onValueChange)
242
+ const [resolved, setResolved] = React.useState<{ query: string; plan: AskPlan | null }>({ query: "", plan: null })
243
+ const [values, setValues] = React.useState<AskValues>({})
244
+ const [done, setDone] = React.useState<AskResult | null>(null)
245
+ const [running, setRunning] = React.useState(false)
246
+ const [error, setError] = React.useState<string>()
247
+ const [undoing, setUndoing] = React.useState(false)
248
+ const [undoError, setUndoError] = React.useState<string>()
249
+ const [said, setSaid] = React.useState("")
250
+ const undoButton = React.useRef<HTMLButtonElement | null>(null)
251
+ const [focused, setFocused] = React.useState(false)
252
+ const [open, setOpenState] = React.useState(false)
253
+ const [typing, setTyping] = React.useState(true)
254
+ const [highlight, setHighlight] = React.useState(-1)
255
+ const phone = usePhone()
256
+ const input = React.useRef<HTMLInputElement | null>(null)
257
+ const content = React.useRef<HTMLElement | null>(null)
258
+ const trigger = React.useRef<HTMLButtonElement | null>(null)
259
+ const resolver = useAgentLatest(resolve)
260
+
261
+ // Only the answer for the latest text is kept; a stale plan stays on screen, unrunnable, meanwhile.
262
+ // Before paint, so a sync answer never shows as pending.
263
+ const [asking, setAsking] = React.useState<string | null>(null)
264
+ useIsomorphicLayoutEffect(() => {
265
+ const controller = new AbortController()
266
+ const { signal } = controller
267
+ const apply = (plan: AskPlan | null | undefined) => {
268
+ if (signal.aborted) return
269
+ setResolved({ query, plan: plan ?? null })
270
+ setValues(valuesOf(plan ?? null))
271
+ setError(undefined)
272
+ setAsking(null)
273
+ }
274
+ const out = query.trim() ? resolver.current?.(query, { signal }) : null
275
+ if (out instanceof Promise) {
276
+ setAsking(query)
277
+ out.then(apply, () => apply(null))
278
+ } else if (out || resolved.plan || resolved.query !== query || asking !== null) apply(out)
279
+ return () => controller.abort()
280
+ }, [query])
281
+
282
+ const pending = asking === query && resolved.query !== query
283
+ const plan = done ? null : resolved.plan
284
+ const shownCommands = React.useMemo(() => {
285
+ if (!query.trim() || plan || done) return []
286
+ return filter ? firstMatches(commands, query, limit, filter) : matchCommands(commands, query, limit)
287
+ }, [commands, filter, limit, query, plan, done])
288
+ const shownSuggestions =
289
+ plan || done
290
+ ? []
291
+ : suggest === "focus"
292
+ ? (phone ? open : focused) && !query
293
+ ? suggestions
294
+ : []
295
+ : query.trim()
296
+ ? suggestions.filter((s) => s.toLowerCase().includes(query.toLowerCase().trim()) && s !== query)
297
+ : []
298
+
299
+ // One highlight runs across the commands, then the chips. A command is ready by default; a chip only once the keys reach it.
300
+ const total = shownCommands.length + shownSuggestions.length
301
+ const active = highlight >= 0 && highlight < total ? highlight : shownCommands.length ? 0 : -1
302
+
303
+ const view: View = !phone ? "bar" : done ? "done" : plan && !typing ? "plan" : "typing"
304
+
305
+ const change = React.useCallback(
306
+ (next: string, d: AskBarChangeDetails) => {
307
+ setQuery(next, d)
308
+ if (d.isCanceled) return
309
+ setDone(null)
310
+ setHighlight(-1)
311
+ },
312
+ [setQuery]
313
+ )
314
+
315
+ const setOpen = (next: boolean) => {
316
+ setOpenState(next)
317
+ setTyping(true)
318
+ if (!next) {
319
+ setDone(null)
320
+ change("", details("close"))
321
+ }
322
+ }
323
+
324
+ // Focus follows the bar's own outcome, but never leaves something the person moved to.
325
+ const ours = () => {
326
+ const active = document.activeElement
327
+ return !active || active === document.body || Boolean(content.current?.contains(active))
328
+ }
329
+
330
+ const run = async (event?: Event): Promise<string | AskResult> => {
331
+ if (!plan || pending || running) return "There is no plan to run."
332
+ const asked = query
333
+ const focus = ours()
334
+ setRunning(true)
335
+ setError(undefined)
336
+ setUndoError(undefined)
337
+ try {
338
+ const result = await plan.run(values)
339
+ if (now.current.query === asked) change("", details("run", event))
340
+ setDone(result)
341
+ if (focus) requestAnimationFrame(() => (undoButton.current ?? input.current)?.focus())
342
+ return result
343
+ } catch (e) {
344
+ const message = e instanceof Error ? e.message : String(e)
345
+ setError(message)
346
+ return message
347
+ } finally {
348
+ setRunning(false)
349
+ }
350
+ }
351
+
352
+ const undo = async () => {
353
+ if (!done?.undo || undoing) return
354
+ const focus = ours()
355
+ setUndoing(true)
356
+ setUndoError(undefined)
357
+ try {
358
+ const line = await done.undo()
359
+ setSaid(typeof line === "string" && line ? line : "Undone.")
360
+ setDone(null)
361
+ if (phone) setOpen(false)
362
+ else if (focus) input.current?.focus()
363
+ } catch (e) {
364
+ setUndoError(e instanceof Error ? e.message : String(e))
365
+ } finally {
366
+ setUndoing(false)
367
+ }
368
+ }
369
+
370
+ const command = (item: CommandItem, action = item.actions?.[0], d = details("command")) => {
371
+ onCommand?.(item, action, d)
372
+ if (d.isCanceled) return "The app refused the command."
373
+ change("", d)
374
+ if (phone) setOpen(false)
375
+ return undefined
376
+ }
377
+
378
+ const suggestion = (text: string, event?: Event) => {
379
+ change(text, details("suggestion", event))
380
+ if (phone) setTyping(false)
381
+ }
382
+
383
+ // On a phone, sending drops the keyboard so the plan gets the sheet. On a desktop it runs.
384
+ const send = (event?: Event) => {
385
+ if (plan) {
386
+ if (phone) setTyping(false)
387
+ else void run(event)
388
+ } else if (active >= shownCommands.length && shownSuggestions[active - shownCommands.length]) {
389
+ suggestion(shownSuggestions[active - shownCommands.length], event)
390
+ } else if (shownCommands[active]) command(shownCommands[active], undefined, details("command", event))
391
+ }
392
+
393
+ const latest = useAgentLatest({ phone, disabled })
394
+ const now = useAgentLatest({ query, values })
395
+
396
+ // One polite region per bar reads the plan once the text settles, then the result, then the undo.
397
+ const settled = pending ? null : plan
398
+ React.useEffect(() => {
399
+ if (done) return setSaid(done.message)
400
+ if (!settled) return
401
+ const timer = setTimeout(() => setSaid(`${sentenceOf(settled, now.current.values)} ${settled.verb(now.current.values)}`), SETTLE_MS)
402
+ return () => clearTimeout(timer)
403
+ }, [settled, done, query])
404
+ // On the body, so a modal sheet can hide the rest of the page while it still speaks.
405
+ const body = React.useSyncExternalStore(
406
+ noSubscribe,
407
+ () => document.body,
408
+ () => null
409
+ )
410
+ React.useEffect(() => {
411
+ if (shortcut === false || disabled) return
412
+ const mac = /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent)
413
+ const onKeyDown = (event: KeyboardEvent) => {
414
+ // On a Mac only Cmd: Ctrl+K deletes to the end of the line.
415
+ const mod = mac ? event.metaKey && !event.ctrlKey : event.ctrlKey && !event.metaKey
416
+ if (event.defaultPrevented || event.repeat || !mod || event.altKey || event.shiftKey || event.key.toLowerCase() !== shortcut.toLowerCase()) return
417
+ event.preventDefault()
418
+ if (latest.current.phone) setOpenState(true)
419
+ else input.current?.focus()
420
+ }
421
+ document.addEventListener("keydown", onKeyDown)
422
+ return () => document.removeEventListener("keydown", onKeyDown)
423
+ }, [shortcut, disabled])
424
+
425
+ const context: AskContext = {
426
+ part: useHasAgent() ? "" : undefined,
427
+ label,
428
+ disabled,
429
+ phone,
430
+ view,
431
+ open,
432
+ setOpen,
433
+ setTyping,
434
+ query,
435
+ change,
436
+ plan,
437
+ pending,
438
+ values,
439
+ setValue: (id, v) => setValues((prev) => ({ ...prev, [id]: v })),
440
+ running,
441
+ error,
442
+ done,
443
+ undoing,
444
+ undoError,
445
+ undoButton,
446
+ commands: shownCommands,
447
+ highlight: active,
448
+ setHighlight,
449
+ suggestions: shownSuggestions,
450
+ suggestion,
451
+ above: Boolean(done || plan || shownCommands.length || shownSuggestions.length),
452
+ focused,
453
+ setFocused,
454
+ confirm: approval(plan?.confirm ?? confirm),
455
+ send,
456
+ run,
457
+ undo,
458
+ command,
459
+ input,
460
+ content,
461
+ trigger,
462
+ }
463
+
464
+ useAskAgent(context, commands, suggestions, setOpenState, setTyping)
465
+
466
+ return (
467
+ <AskContext.Provider value={context}>
468
+ {children}
469
+ {body &&
470
+ createPortal(
471
+ <span aria-live="polite" aria-atomic className="sr-only">
472
+ {said}
473
+ </span>,
474
+ body
475
+ )}
476
+ </AskContext.Provider>
477
+ )
478
+ }
479
+
480
+ /** The reason an agent's run waits for a person. Only `false` lifts it. */
481
+ const approval = (confirm: string | false) => (confirm === false ? undefined : confirm || "Needs a person's approval.")
482
+
483
+ /**
484
+ * The bar is one combobox: `search` types a request and returns the plan it resolved to,
485
+ * or the commands it matched. The plan's fields are inputs and its button a control of its own.
486
+ */
487
+ function useAskAgent(c: AskContext, commands: CommandItem[], examples: string[], setOpen: (open: boolean) => void, setTyping: (typing: boolean) => void) {
488
+ const latest = useAgentLatest(c)
489
+ useAgentControl(() => ({
490
+ kind: "combobox",
491
+ element: c.input.current ?? c.content.current ?? c.trigger.current,
492
+ label: c.label,
493
+ hint: `Takes a request in plain words${examples.length ? `, such as ${examples.map((e) => JSON.stringify(e)).join(", ")}` : ""}. search returns a plan; press its run button to do it.`,
494
+ disabled: c.disabled,
495
+ value: c.query,
496
+ items: c.commands.map((i) => i.label),
497
+ actions: {
498
+ search: async (text: unknown) => {
499
+ const q = String(text ?? "")
500
+ const refused = changeAsAgent(c.change, q)
501
+ if (refused) return refused
502
+ setOpen(true)
503
+ setTyping(false)
504
+ await waitForAgent(() => latest.current.query === q && !latest.current.pending, 30_000)
505
+ const { plan, values } = latest.current
506
+ return {
507
+ result: plan
508
+ ? {
509
+ plan: plan.title,
510
+ sentence: sentenceOf(plan, values),
511
+ fields: plan.fields.map((f) => ({ label: f.label, value: values[f.id], ...(f.fixed ? { fixed: true } : {}) })),
512
+ touches: agentNodeText(touchesOf(plan, values)),
513
+ call: callOf(plan, values),
514
+ run: plan.verb(values),
515
+ }
516
+ : { commands: latest.current.commands.map((i) => i.label) },
517
+ }
518
+ },
519
+ select: (wanted: unknown, actionName?: unknown) => {
520
+ const match = matchAgentChoice(commands.map((i) => ({ value: i, label: i.label, disabled: i.disabled })), wanted)
521
+ if (typeof match === "string") return match
522
+ const actions = match.value.actions ?? []
523
+ const found = actionName == null ? { value: actions[0] } : matchAgentChoice(actions.map((a) => ({ value: a, label: a.label })), actionName)
524
+ if (typeof found === "string") return found
525
+ return c.command(match.value, found.value, createAgentChangeDetails("command"))
526
+ },
527
+ },
528
+ }))
529
+ }
530
+
531
+ /** The floating Ask button that opens the bar on a phone. Renders nothing on a desktop. */
532
+ const AskBarTrigger = React.forwardRef<HTMLButtonElement, React.ButtonHTMLAttributes<HTMLButtonElement>>(
533
+ ({ className, children, onClick, ...props }, ref) => {
534
+ const c = useAsk("AskBarTrigger")
535
+ const merged = useMergedRef(ref, c.trigger)
536
+ if (!c.phone) return null
537
+ return (
538
+ <button
539
+ ref={merged}
540
+ type="button"
541
+ data-agent-part={c.part}
542
+ disabled={c.disabled}
543
+ data-slot="ask-bar-trigger"
544
+ onClick={(event) => {
545
+ onClick?.(event)
546
+ c.setOpen(true)
547
+ }}
548
+ className={cn(
549
+ "fixed bottom-[max(28px,env(safe-area-inset-bottom))] left-1/2 z-40 flex h-12 -translate-x-1/2 items-center gap-2 rounded-full bg-primary pl-[18px] pr-[22px] text-base font-medium text-primary-foreground",
550
+ "shadow-[0_14px_30px_-12px_rgb(0_0_0/0.45)] disabled:opacity-50",
551
+ className
552
+ )}
553
+ {...props}
554
+ >
555
+ {children ?? (
556
+ <>
557
+ <Sparkles className="h-4 w-4 text-[color-mix(in_oklab,var(--info)_60%,var(--primary-foreground))]" aria-hidden />
558
+ {c.label}
559
+ </>
560
+ )}
561
+ </button>
562
+ )
563
+ }
564
+ )
565
+ AskBarTrigger.displayName = "AskBarTrigger"
566
+
567
+ /**
568
+ * The dock: centred at the bottom of the page on a desktop, a sheet on a phone. With no
569
+ * children it holds the done line, plan, commands, suggestions and field, in that order.
570
+ */
571
+ const AskBarContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
572
+ ({ className, children, ...props }, ref) => {
573
+ const c = useAsk("AskBarContent")
574
+ const merged = useMergedRef(ref, c.content)
575
+ const body = children ?? (
576
+ <>
577
+ <AskBarDone />
578
+ <AskBarPlan />
579
+ <AskBarCommands />
580
+ <AskBarSuggestions />
581
+ <AskBarInput />
582
+ </>
583
+ )
584
+ if (!c.phone) {
585
+ return (
586
+ <div
587
+ ref={merged}
588
+ role="region"
589
+ aria-label={c.label}
590
+ data-slot="ask-bar-content"
591
+ className={cn(
592
+ "fixed bottom-[18px] left-1/2 z-40 w-[640px] max-w-[calc(100%-32px)] -translate-x-1/2 overflow-hidden",
593
+ "rounded-[18px] border bg-popover text-popover-foreground shadow-[0_24px_60px_-20px_rgb(0_0_0/0.4)]",
594
+ "focus-within:border-[color:color-mix(in_oklab,var(--muted-foreground)_70%,var(--border))]",
595
+ className
596
+ )}
597
+ {...props}
598
+ >
599
+ {body}
600
+ </div>
601
+ )
602
+ }
603
+ const sheet = c.view === "plan" || c.view === "done"
604
+ return (
605
+ <DrawerPrimitive.Root open={c.open} onOpenChange={(next) => c.setOpen(next)}>
606
+ <DrawerPrimitive.Portal>
607
+ <DrawerPrimitive.VirtualKeyboardProvider>
608
+ <DrawerPrimitive.Backdrop
609
+ className={cn(
610
+ "fixed inset-0 z-50 bg-black/30 opacity-[calc(1_-_var(--drawer-swipe-progress,0))] dark:bg-black/55",
611
+ "transition-opacity duration-[var(--motion-duration-base,200ms)] ease-[var(--motion-ease-drawer,cubic-bezier(0.32,0.72,0,1))]",
612
+ "data-[ending-style]:duration-[calc(var(--motion-duration-fast,150ms)_*_var(--drawer-swipe-strength,1))]",
613
+ "data-[starting-style]:opacity-0 data-[ending-style]:opacity-0 data-[swiping]:transition-none"
614
+ )}
615
+ />
616
+ <DrawerPrimitive.Viewport>
617
+ <DrawerPrimitive.Popup
618
+ ref={merged}
619
+ aria-label={c.label}
620
+ aria-modal="true"
621
+ initialFocus={c.input}
622
+ data-slot="ask-bar-content"
623
+ className={cn(
624
+ "fixed inset-x-0 bottom-[var(--drawer-keyboard-inset,0px)] z-50 flex max-h-[calc(100dvh-60px)] flex-col rounded-t-[20px] bg-popover pt-2.5 text-popover-foreground outline-none",
625
+ "shadow-[0_-20px_50px_-20px_rgb(0_0_0/0.3)]",
626
+ "transition-transform duration-[var(--motion-duration-base,200ms)] ease-[var(--motion-ease-drawer,cubic-bezier(0.32,0.72,0,1))]",
627
+ "data-[ending-style]:duration-[calc(var(--motion-duration-fast,150ms)_*_var(--drawer-swipe-strength,1))]",
628
+ "data-[starting-style]:translate-y-full data-[ending-style]:translate-y-full",
629
+ "motion-reduce:transition-opacity motion-reduce:data-[starting-style]:translate-y-0 motion-reduce:data-[starting-style]:opacity-0",
630
+ "motion-reduce:data-[ending-style]:translate-y-0 motion-reduce:data-[ending-style]:opacity-0",
631
+ sheet && "max-h-[calc(100dvh-40px)] pb-[max(26px,env(safe-area-inset-bottom))] pt-0",
632
+ className
633
+ )}
634
+ {...props}
635
+ >
636
+ <DrawerPrimitive.Content className="flex min-h-0 flex-col overflow-y-auto">
637
+ {sheet && <div aria-hidden className="mx-auto mb-2.5 mt-2 h-[5px] w-9 flex-none rounded-full bg-accent" />}
638
+ {body}
639
+ </DrawerPrimitive.Content>
640
+ </DrawerPrimitive.Popup>
641
+ </DrawerPrimitive.Viewport>
642
+ </DrawerPrimitive.VirtualKeyboardProvider>
643
+ </DrawerPrimitive.Portal>
644
+ </DrawerPrimitive.Root>
645
+ )
646
+ }
647
+ )
648
+ AskBarContent.displayName = "AskBarContent"
649
+
650
+ interface AskBarPlanProps extends React.HTMLAttributes<HTMLDivElement> {
651
+ showCallLabel?: string
652
+ hideCallLabel?: string
653
+ /** The phone's button back to the request. */
654
+ editLabel?: string
655
+ }
656
+
657
+ /**
658
+ * The plan as one sentence, with the values you can still change as inputs that grow with
659
+ * their text. On a phone, the fields are rows and the button sits at the bottom.
660
+ */
661
+ const AskBarPlan = React.forwardRef<HTMLDivElement, AskBarPlanProps>(
662
+ ({ className, showCallLabel = "Show call", hideCallLabel = "Hide call", editLabel = "Edit", ...props }, ref) => {
663
+ const c = useAsk("AskBarPlan")
664
+ const [call, setCall] = React.useState(false)
665
+ const group = React.useRef<HTMLDivElement | null>(null)
666
+ const button = React.useRef<HTMLButtonElement | null>(null)
667
+ const merged = useMergedRef(ref, group)
668
+ const callId = React.useId()
669
+ const { plan, values } = c
670
+ const shown = plan && (c.view === "bar" || c.view === "plan")
671
+ const verb = plan ? plan.verb(values) : ""
672
+ const callText = plan && callOf(plan, values)
673
+ const blocked = c.disabled || c.pending || c.running
674
+ const touches = plan && touchesOf(plan, values)
675
+
676
+ // Sent from a phone, focus moves off the field so the keyboard drops.
677
+ React.useEffect(() => {
678
+ if (shown && c.phone) group.current?.focus()
679
+ }, [shown, c.phone])
680
+
681
+ useAgentControl(() =>
682
+ shown && button.current
683
+ ? {
684
+ kind: "button",
685
+ element: button.current,
686
+ label: verb,
687
+ disabled: blocked,
688
+ confirm: c.confirm,
689
+ actions: {
690
+ press: async () => {
691
+ const result = await c.run(new Event("agent"))
692
+ return typeof result === "string" ? result : { result: result.message }
693
+ },
694
+ },
695
+ }
696
+ : null
697
+ )
698
+
699
+ if (!shown || !plan) return null
700
+ const field = (f: AskField) => (
701
+ <input
702
+ key={f.id}
703
+ aria-label={f.label}
704
+ value={values[f.id] ?? ""}
705
+ readOnly={f.fixed || c.running}
706
+ inputMode={f.inputMode}
707
+ size={Math.max(1, (values[f.id] ?? "").length)}
708
+ disabled={c.disabled}
709
+ onChange={(event) => c.setValue(f.id, event.target.value)}
710
+ onKeyDown={(event) => {
711
+ if (event.key !== "Enter" || event.nativeEvent.isComposing) return
712
+ event.preventDefault()
713
+ if (c.phone) event.currentTarget.blur()
714
+ else void c.run(event.nativeEvent)
715
+ }}
716
+ className={cn(
717
+ c.phone
718
+ ? cn("min-w-0 flex-1 bg-transparent text-right text-base tabular-nums outline-none", f.fixed ? "text-muted-foreground" : TINT)
719
+ : cn(
720
+ "mx-px min-w-[24px] rounded-md border-0 bg-[color-mix(in_oklab,var(--info)_10%,transparent)] px-[5px] py-0 text-center tabular-nums outline-none [field-sizing:content] [font:inherit]",
721
+ "shadow-[inset_0_-1.5px_0_color-mix(in_oklab,var(--info)_45%,transparent)] focus:shadow-[0_0_0_2px_color-mix(in_oklab,var(--info)_45%,transparent)]",
722
+ TINT
723
+ )
724
+ )}
725
+ />
726
+ )
727
+ const runButton = (
728
+ <button
729
+ ref={button}
730
+ type="button"
731
+ disabled={blocked}
732
+ aria-busy={c.running || undefined}
733
+ onClick={(event) => void c.run(event.nativeEvent)}
734
+ className={cn(
735
+ "rounded-[10px] bg-primary px-4 py-2.5 text-sm font-medium text-primary-foreground disabled:opacity-50",
736
+ c.phone ? "w-full rounded-[13px] p-[15px] text-base" : "ml-auto"
737
+ )}
738
+ >
739
+ {verb}
740
+ </button>
741
+ )
742
+ const note = c.error ? (
743
+ <p role="alert" className="mt-1.5 text-[13.5px] leading-normal text-destructive">
744
+ {c.error}
745
+ </p>
746
+ ) : (
747
+ touches && <p className="mt-1.5 text-[13.5px] leading-normal text-muted-foreground sm:mt-1.5 max-sm:mt-3 max-sm:text-sm">{touches}</p>
748
+ )
749
+ return (
750
+ <>
751
+ {c.phone && (
752
+ <button
753
+ type="button"
754
+ data-agent-part={c.part}
755
+ onClick={() => c.setTyping(true)}
756
+ className="mx-3 flex w-[calc(100%-24px)] flex-none items-center gap-2 rounded-xl bg-muted px-3 py-[11px] text-left text-[15px]"
757
+ >
758
+ <Sparkles className={cn("h-4 w-4 flex-none", TINT)} aria-hidden />
759
+ <span className="min-w-0 truncate">{c.query}</span>
760
+ <span className="ml-auto flex-none text-sm text-muted-foreground">{editLabel}</span>
761
+ </button>
762
+ )}
763
+ <div
764
+ ref={merged}
765
+ role="group"
766
+ aria-label={plan.title}
767
+ aria-busy={c.pending || undefined}
768
+ data-agent-in={plan.title}
769
+ tabIndex={-1}
770
+ data-slot="ask-bar-plan"
771
+ className={cn(c.phone ? "px-[18px] pt-4" : "px-[22px] pb-4 pt-5", "outline-none", className)}
772
+ {...props}
773
+ >
774
+ {c.phone ? (
775
+ <>
776
+ <div className="text-xl font-semibold tracking-[-0.015em]">{plan.title}</div>
777
+ <div className="mt-2.5 border-t">
778
+ {plan.fields.map((f) => (
779
+ <label key={f.id} className="flex min-h-[50px] items-center gap-3 border-b text-base focus-within:border-[color:var(--info)]">
780
+ <span aria-hidden className="flex-none text-muted-foreground">
781
+ {f.label}
782
+ </span>
783
+ {field(f)}
784
+ </label>
785
+ ))}
786
+ </div>
787
+ {note}
788
+ <div className="mt-4">{runButton}</div>
789
+ </>
790
+ ) : (
791
+ <>
792
+ <p className="m-0 text-lg font-medium leading-normal tracking-[-0.01em]">
793
+ {plan.sentence.map((p, i) => {
794
+ if (typeof p === "string") return p
795
+ const f = plan.fields.find((x) => x.id === p.field)
796
+ if (!f) return null
797
+ return f.fixed ? <React.Fragment key={i}>{values[f.id]}</React.Fragment> : field(f)
798
+ })}
799
+ </p>
800
+ {note}
801
+ <div className="mt-[18px] flex flex-wrap items-center gap-3">
802
+ {callText && (
803
+ <button
804
+ type="button"
805
+ data-agent-part={c.part}
806
+ aria-expanded={call}
807
+ aria-controls={callId}
808
+ onClick={() => setCall(!call)}
809
+ className="relative text-[12.5px] text-muted-foreground underline decoration-border underline-offset-[3px] after:absolute after:-inset-x-1 after:-inset-y-1 after:content-[''] hover:text-foreground"
810
+ >
811
+ {call ? hideCallLabel : showCallLabel}
812
+ </button>
813
+ )}
814
+ {runButton}
815
+ {callText && call && (
816
+ <code id={callId} className="order-3 basis-full break-all font-mono text-xs text-muted-foreground">
817
+ {callText}
818
+ </code>
819
+ )}
820
+ </div>
821
+ </>
822
+ )}
823
+ </div>
824
+ </>
825
+ )
826
+ }
827
+ )
828
+ AskBarPlan.displayName = "AskBarPlan"
829
+
830
+ /** What ran, with Undo when the plan can be put back. Fades in. */
831
+ const AskBarDone = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement> & { undoLabel?: string }>(
832
+ ({ className, undoLabel = "Undo", ...props }, ref) => {
833
+ const c = useAsk("AskBarDone")
834
+ const [shown, setShown] = React.useState(false)
835
+ const { done } = c
836
+ React.useEffect(() => {
837
+ setShown(false)
838
+ if (!done) return
839
+ const frame = requestAnimationFrame(() => setShown(true))
840
+ return () => cancelAnimationFrame(frame)
841
+ }, [done])
842
+ if (!done) return null
843
+ return (
844
+ <div
845
+ ref={ref}
846
+ data-slot="ask-bar-done"
847
+ className={cn(
848
+ "m-2.5 flex items-center gap-2.5 rounded-[13px] bg-[color-mix(in_oklab,var(--success)_9%,var(--background))] px-3.5 py-3 text-[13.5px] max-sm:mx-3 max-sm:text-[15px]",
849
+ "transition-opacity duration-[var(--motion-duration-base,200ms)] ease-[var(--motion-ease-out,cubic-bezier(0.23,1,0.32,1))]",
850
+ shown ? "opacity-100" : "opacity-0",
851
+ className
852
+ )}
853
+ {...props}
854
+ >
855
+ <Check className="h-4 w-4 flex-none text-success" aria-hidden />
856
+ <span className="min-w-0 flex-1">
857
+ {done.message}
858
+ {c.undoError && (
859
+ <span role="alert" className="block text-destructive">
860
+ {c.undoError}
861
+ </span>
862
+ )}
863
+ </span>
864
+ {done.undo && (
865
+ <button
866
+ ref={c.undoButton}
867
+ type="button"
868
+ aria-busy={c.undoing || undefined}
869
+ disabled={c.undoing}
870
+ onClick={() => void c.undo()}
871
+ className="relative flex-none font-medium underline underline-offset-[3px] after:absolute after:-inset-1 after:content-[''] disabled:opacity-50 max-sm:min-h-11 max-sm:px-1.5 max-sm:text-[15px]"
872
+ >
873
+ {undoLabel}
874
+ </button>
875
+ )}
876
+ </div>
877
+ )
878
+ }
879
+ )
880
+ AskBarDone.displayName = "AskBarDone"
881
+
882
+ const listId = (label: string) => `ask-bar-${label.replace(/\W+/g, "-").toLowerCase()}`
883
+
884
+ /** The commands the text matched when it resolved to no plan. */
885
+ const AskBarCommands = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(({ className, ...props }, ref) => {
886
+ const c = useAsk("AskBarCommands")
887
+ if (!c.commands.length || (c.view !== "bar" && c.view !== "typing")) return null
888
+ const id = listId(c.label)
889
+ return (
890
+ <div
891
+ ref={ref}
892
+ id={id}
893
+ role="listbox"
894
+ aria-label={c.label}
895
+ data-slot="ask-bar-commands"
896
+ className={cn("max-h-[210px] flex-none overflow-y-auto px-1.5 py-1.5 max-sm:max-h-none max-sm:px-2", className)}
897
+ {...props}
898
+ >
899
+ {c.commands.map((item, i) => (
900
+ <div
901
+ key={item.id}
902
+ id={`${id}-${i}`}
903
+ role="option"
904
+ aria-selected={i === c.highlight}
905
+ aria-disabled={item.disabled || undefined}
906
+ data-highlighted={i === c.highlight ? "" : undefined}
907
+ onMouseDown={(event) => event.preventDefault()}
908
+ onPointerMove={() => c.setHighlight(i)}
909
+ onClick={(event) => !item.disabled && c.command(item, undefined, details("command", event.nativeEvent))}
910
+ // The highlight follows the keys and the pointer, so it moves with no transition.
911
+ className={cn(
912
+ "group flex cursor-default select-none items-center gap-2.5 rounded-[9px] px-2.5 py-2 text-[13.5px] max-sm:px-2 max-sm:py-2.5 max-sm:text-[15px]",
913
+ "data-[highlighted]:bg-muted aria-disabled:opacity-50"
914
+ )}
915
+ >
916
+ {item.icon && (
917
+ <span className="grid h-[26px] w-[26px] flex-none place-items-center rounded-[7px] bg-muted text-muted-foreground group-data-[highlighted]:bg-background group-data-[highlighted]:text-foreground max-sm:h-8 max-sm:w-8 max-sm:rounded-[9px] [&_svg]:h-4 [&_svg]:w-4">
918
+ {item.icon}
919
+ </span>
920
+ )}
921
+ <span className="min-w-0 flex-1">
922
+ {item.label}
923
+ {item.description && (
924
+ <span className="ml-1.5 text-[12.5px] text-muted-foreground max-sm:ml-0 max-sm:block max-sm:text-[13px]">{item.description}</span>
925
+ )}
926
+ </span>
927
+ {item.meta && <span className="ml-auto flex-none text-xs tabular-nums text-muted-foreground">{item.meta}</span>}
928
+ </div>
929
+ ))}
930
+ </div>
931
+ )
932
+ })
933
+ AskBarCommands.displayName = "AskBarCommands"
934
+
935
+ /** Requests to try, as chips. Picking one keeps focus in the field; on a phone it sends. */
936
+ const AskBarSuggestions = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(({ className, ...props }, ref) => {
937
+ const c = useAsk("AskBarSuggestions")
938
+ if (!c.suggestions.length || (c.view !== "bar" && c.view !== "typing")) return null
939
+ const id = listId(c.label)
940
+ const first = c.commands.length
941
+ return (
942
+ <div
943
+ ref={ref}
944
+ id={`${id}-suggestions`}
945
+ role="listbox"
946
+ aria-label="Suggestions"
947
+ aria-orientation="horizontal"
948
+ data-slot="ask-bar-suggestions"
949
+ className={cn(
950
+ "flex flex-wrap gap-1.5 px-3 pb-2.5 pt-3",
951
+ "max-sm:flex-none max-sm:flex-nowrap max-sm:gap-2 max-sm:overflow-x-auto max-sm:px-2.5 max-sm:pt-1.5 max-sm:[scrollbar-width:none]",
952
+ className
953
+ )}
954
+ {...props}
955
+ >
956
+ {c.suggestions.map((s, i) => (
957
+ <button
958
+ key={s}
959
+ id={`${id}-${first + i}`}
960
+ type="button"
961
+ role="option"
962
+ tabIndex={-1}
963
+ aria-selected={first + i === c.highlight}
964
+ data-highlighted={first + i === c.highlight ? "" : undefined}
965
+ data-agent-part={c.part}
966
+ disabled={c.disabled || c.running}
967
+ onMouseDown={(event) => event.preventDefault()}
968
+ onPointerMove={() => c.setHighlight(first + i)}
969
+ onClick={(event) => c.suggestion(s, event.nativeEvent)}
970
+ className="relative flex-none rounded-full border bg-background px-[11px] py-[5px] text-[13px] data-[highlighted]:bg-muted max-sm:px-[13px] max-sm:py-2 max-sm:text-sm max-sm:after:absolute max-sm:after:inset-x-0 max-sm:after:-inset-y-[4px] max-sm:after:content-['']"
971
+ >
972
+ {s}
973
+ </button>
974
+ ))}
975
+ </div>
976
+ )
977
+ })
978
+ AskBarSuggestions.displayName = "AskBarSuggestions"
979
+
980
+ /** The field and its send button. Enter runs the plan, the highlighted command or the highlighted chip. */
981
+ const AskBarInput = React.forwardRef<HTMLInputElement, React.InputHTMLAttributes<HTMLInputElement> & { sendLabel?: string }>(
982
+ ({ className, placeholder = "Ask or type a command", sendLabel = "Send", onKeyDown, ...props }, ref) => {
983
+ const c = useAsk("AskBarInput")
984
+ const assign = useMergedRef(ref, c.input)
985
+ if (c.view === "plan" || c.view === "done") return null
986
+ const id = listId(c.label)
987
+ const controls = [c.commands.length && id, c.suggestions.length && `${id}-suggestions`].filter(Boolean).join(" ")
988
+ const n = c.commands.length + c.suggestions.length
989
+ return (
990
+ <div
991
+ className={cn(
992
+ "flex flex-none items-center gap-2.5 px-3.5 py-3",
993
+ c.above && "border-t",
994
+ "max-sm:mx-2.5 max-sm:mb-[max(10px,env(safe-area-inset-bottom))] max-sm:rounded-[22px] max-sm:border-t-0 max-sm:bg-muted max-sm:px-3 max-sm:py-2.5",
995
+ "max-sm:focus-within:shadow-[inset_0_0_0_1px_color-mix(in_oklab,var(--muted-foreground)_70%,var(--border))]"
996
+ )}
997
+ >
998
+ <Sparkles className={cn("h-4 w-4 flex-none", TINT)} aria-hidden />
999
+ <input
1000
+ ref={assign}
1001
+ role="combobox"
1002
+ aria-label={c.label}
1003
+ aria-expanded={n > 0}
1004
+ aria-controls={controls || undefined}
1005
+ aria-activedescendant={c.highlight >= 0 ? `${id}-${c.highlight}` : undefined}
1006
+ aria-autocomplete="list"
1007
+ autoComplete="off"
1008
+ enterKeyHint="send"
1009
+ placeholder={placeholder}
1010
+ disabled={c.disabled}
1011
+ readOnly={c.running}
1012
+ value={c.query}
1013
+ data-slot="ask-bar-input"
1014
+ onChange={(event) => c.change(event.target.value, details("input-change", event.nativeEvent))}
1015
+ onFocus={() => c.setFocused(true)}
1016
+ onBlur={() => c.setFocused(false)}
1017
+ onKeyDown={(event) => {
1018
+ onKeyDown?.(event)
1019
+ if (event.defaultPrevented || event.nativeEvent.isComposing) return
1020
+ const h = c.highlight
1021
+ const command = c.commands[h]
1022
+ const chip = c.suggestions[h - c.commands.length]
1023
+ // Tab completes the highlighted entry into the field. Once the field reads it, Tab moves on.
1024
+ const completion = command && !command.disabled ? command.label : chip
1025
+ if (event.key === "Enter") {
1026
+ event.preventDefault()
1027
+ c.send(event.nativeEvent)
1028
+ } else if (event.key === "Tab" && !event.shiftKey && completion && completion !== c.query) {
1029
+ event.preventDefault()
1030
+ c.change(completion, details(chip ? "suggestion" : "complete", event.nativeEvent))
1031
+ } else if ((event.key === "ArrowDown" || event.key === "ArrowUp") && n) {
1032
+ event.preventDefault()
1033
+ const down = event.key === "ArrowDown"
1034
+ c.setHighlight(h < 0 ? (down ? 0 : n - 1) : (h + (down ? 1 : n - 1)) % n)
1035
+ } else if (event.key === "Escape" && !c.phone) {
1036
+ c.change("", details("escape-key", event.nativeEvent))
1037
+ event.currentTarget.blur()
1038
+ }
1039
+ }}
1040
+ className={cn("min-w-0 flex-1 bg-transparent text-base outline-none placeholder:text-muted-foreground sm:text-[15px]", className)}
1041
+ {...props}
1042
+ />
1043
+ <button
1044
+ type="button"
1045
+ aria-label={sendLabel}
1046
+ data-agent-part={c.part}
1047
+ disabled={c.disabled || !c.query.trim()}
1048
+ onMouseDown={(event) => event.preventDefault()}
1049
+ onClick={(event) => c.send(event.nativeEvent)}
1050
+ className="relative grid h-[30px] w-[30px] flex-none place-items-center rounded-[9px] bg-primary text-primary-foreground after:absolute after:-inset-1.5 after:content-[''] disabled:opacity-50 max-sm:h-8 max-sm:w-8 max-sm:rounded-full"
1051
+ >
1052
+ <ArrowUp className="h-4 w-4" aria-hidden />
1053
+ </button>
1054
+ </div>
1055
+ )
1056
+ }
1057
+ )
1058
+ AskBarInput.displayName = "AskBarInput"
1059
+
1060
+ export { AskBar, AskBarTrigger, AskBarContent, AskBarPlan, AskBarDone, AskBarCommands, AskBarSuggestions, AskBarInput }
1061
+ export type { AskBarPlanProps }