@whity/ui 0.5.0 → 1.0.1

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 (208) hide show
  1. package/README.md +107 -107
  2. package/package.json +223 -192
  3. package/src/access-denied.stories.tsx +179 -179
  4. package/src/access-denied.tsx +305 -305
  5. package/src/action-proposal.tsx +338 -302
  6. package/src/actor-chip.tsx +71 -71
  7. package/src/agent-activity.tsx +163 -163
  8. package/src/agent-collaboration.stories.tsx +156 -156
  9. package/src/agent-run-status.tsx +196 -196
  10. package/src/alert-dialog.stories.tsx +45 -45
  11. package/src/alert-dialog.tsx +147 -147
  12. package/src/alert.stories.tsx +91 -91
  13. package/src/alert.tsx +89 -89
  14. package/src/app-sidebar.stories.tsx +195 -195
  15. package/src/app-sidebar.tsx +604 -500
  16. package/src/approval-queue.tsx +109 -108
  17. package/src/audience-group-picker.stories.tsx +198 -198
  18. package/src/audience-group-picker.tsx +362 -362
  19. package/src/audience-people-picker.stories.tsx +102 -102
  20. package/src/audience-people-picker.tsx +279 -279
  21. package/src/avatar-pattern.ts +138 -0
  22. package/src/avatar.tsx +125 -83
  23. package/src/badge.stories.tsx +105 -105
  24. package/src/badge.tsx +68 -68
  25. package/src/beta-warning.stories.tsx +79 -79
  26. package/src/beta-warning.tsx +189 -189
  27. package/src/bilingual-input.stories.tsx +82 -82
  28. package/src/bilingual-input.tsx +188 -183
  29. package/src/board.tsx +216 -0
  30. package/src/breadcrumb.stories.tsx +51 -51
  31. package/src/breadcrumb.tsx +90 -90
  32. package/src/built-on-whity.tsx +52 -0
  33. package/src/button.stories.tsx +87 -87
  34. package/src/button.tsx +125 -118
  35. package/src/card.stories.tsx +423 -423
  36. package/src/card.tsx +180 -180
  37. package/src/chart.stories.tsx +66 -66
  38. package/src/chart.tsx +228 -228
  39. package/src/checkbox.stories.tsx +62 -62
  40. package/src/checkbox.tsx +54 -54
  41. package/src/collapsible.stories.tsx +48 -48
  42. package/src/collapsible.tsx +34 -34
  43. package/src/color-card.stories.tsx +61 -61
  44. package/src/color-card.tsx +270 -270
  45. package/src/color-picker.stories.tsx +65 -65
  46. package/src/color-picker.tsx +425 -425
  47. package/src/column-matcher.tsx +84 -0
  48. package/src/command-palette.tsx +399 -306
  49. package/src/confirm-action.tsx +98 -0
  50. package/src/copy-block.stories.tsx +38 -38
  51. package/src/copy-block.tsx +85 -85
  52. package/src/data-table.stories.tsx +200 -200
  53. package/src/data-table.tsx +1687 -1106
  54. package/src/date-picker.stories.tsx +61 -61
  55. package/src/date-picker.tsx +457 -422
  56. package/src/design-cards.stories.tsx +551 -458
  57. package/src/dialog.stories.tsx +48 -48
  58. package/src/dialog.tsx +179 -166
  59. package/src/display-preferences.tsx +59 -0
  60. package/src/documents/barcode-svg.stories.tsx +72 -72
  61. package/src/documents/barcode-svg.tsx +79 -79
  62. package/src/dropdown-menu.stories.tsx +77 -77
  63. package/src/dropdown-menu.tsx +271 -271
  64. package/src/editor/agent-panel.tsx +222 -0
  65. package/src/editor/agents.stories.tsx +81 -0
  66. package/src/editor/agents.ts +55 -0
  67. package/src/editor/behaviour.ts +279 -279
  68. package/src/editor/block-ids.ts +44 -44
  69. package/src/editor/block-list.tsx +104 -101
  70. package/src/editor/block-toolbar.tsx +490 -477
  71. package/src/editor/bubble.tsx +119 -93
  72. package/src/editor/catalogue.ts +169 -103
  73. package/src/editor/collab-rail.tsx +746 -746
  74. package/src/editor/collab.stories.tsx +207 -207
  75. package/src/editor/collab.ts +87 -87
  76. package/src/editor/contract.ts +476 -408
  77. package/src/editor/convert.ts +414 -362
  78. package/src/editor/doc-editor.stories.tsx +98 -98
  79. package/src/editor/doc-editor.tsx +1492 -1287
  80. package/src/editor/editor.css +636 -536
  81. package/src/editor/extensions.ts +86 -86
  82. package/src/editor/field-bar.tsx +154 -0
  83. package/src/editor/field-picker.tsx +109 -107
  84. package/src/editor/fields.ts +100 -100
  85. package/src/editor/gutter.tsx +443 -367
  86. package/src/editor/index.ts +23 -22
  87. package/src/editor/label-sheet.tsx +289 -289
  88. package/src/editor/labels.ts +394 -310
  89. package/src/editor/link-tools.tsx +141 -141
  90. package/src/editor/node-views.tsx +461 -450
  91. package/src/editor/page-view.tsx +372 -353
  92. package/src/editor/phone.tsx +310 -0
  93. package/src/editor/plugin-block-view.tsx +230 -0
  94. package/src/editor/plugin-blocks.stories.tsx +96 -0
  95. package/src/editor/plugin-blocks.ts +52 -0
  96. package/src/editor/publish-check.tsx +201 -182
  97. package/src/editor/rich-blocks.stories.tsx +146 -146
  98. package/src/editor/sample.ts +40 -40
  99. package/src/editor/save-block-dialog.tsx +141 -0
  100. package/src/editor/saved-block-view.tsx +205 -0
  101. package/src/editor/saved-blocks.stories.tsx +105 -0
  102. package/src/editor/saved-parts.ts +192 -0
  103. package/src/editor/schema-rich.ts +156 -150
  104. package/src/editor/schema.ts +368 -315
  105. package/src/editor/services.tsx +205 -127
  106. package/src/editor/slash.ts +64 -64
  107. package/src/editor/suggesting.ts +372 -372
  108. package/src/editor/suggestions.ts +763 -763
  109. package/src/editor/table-keys.ts +66 -66
  110. package/src/editor/templates.stories.tsx +324 -324
  111. package/src/editor/toolbar.tsx +364 -358
  112. package/src/empty-state.stories.tsx +51 -51
  113. package/src/empty-state.tsx +126 -100
  114. package/src/empty-state.usage-notes.md +30 -30
  115. package/src/form.stories.tsx +112 -112
  116. package/src/form.tsx +176 -176
  117. package/src/globals.css +20 -20
  118. package/src/icon-button.tsx +85 -85
  119. package/src/icon-map.ts +335 -244
  120. package/src/icon.tsx +41 -41
  121. package/src/index.ts +92 -67
  122. package/src/input.stories.tsx +157 -157
  123. package/src/input.tsx +768 -759
  124. package/src/kpi-strip.tsx +47 -0
  125. package/src/localized-text.ts +76 -0
  126. package/src/locked-screen.stories.tsx +29 -29
  127. package/src/locked-screen.tsx +75 -61
  128. package/src/lockup.tsx +42 -0
  129. package/src/lottie.tsx +441 -0
  130. package/src/mark.tsx +62 -62
  131. package/src/math-text.stories.tsx +33 -33
  132. package/src/math-text.tsx +43 -43
  133. package/src/menu-bar.stories.tsx +198 -198
  134. package/src/menu-bar.tsx +373 -373
  135. package/src/message-thread.tsx +181 -0
  136. package/src/money/currency.ts +244 -230
  137. package/src/money/money-input.tsx +131 -0
  138. package/src/money/money.tsx +33 -0
  139. package/src/open-on-computer.tsx +150 -0
  140. package/src/otp-input.tsx +161 -0
  141. package/src/page-header.stories.tsx +95 -95
  142. package/src/page-header.tsx +122 -122
  143. package/src/page-shell.stories.tsx +42 -42
  144. package/src/page-shell.tsx +32 -32
  145. package/src/page-states.tsx +277 -0
  146. package/src/pagination.stories.tsx +45 -45
  147. package/src/pagination.tsx +98 -98
  148. package/src/paper-sheet.stories.tsx +88 -0
  149. package/src/paper-sheet.tsx +85 -0
  150. package/src/phone-input.tsx +252 -0
  151. package/src/phone-tab-bar.tsx +152 -0
  152. package/src/plugin-card.stories.tsx +208 -180
  153. package/src/plugin-card.tsx +931 -848
  154. package/src/popover.stories.tsx +48 -48
  155. package/src/popover.tsx +55 -55
  156. package/src/radio-group.stories.tsx +26 -26
  157. package/src/radio-group.tsx +44 -44
  158. package/src/role-summary.stories.tsx +143 -0
  159. package/src/role-summary.tsx +120 -0
  160. package/src/route-flow/editor.tsx +1087 -1014
  161. package/src/route-flow/model.ts +771 -716
  162. package/src/save-bar.tsx +94 -0
  163. package/src/scope-grant.tsx +139 -139
  164. package/src/screen-too-small.stories.tsx +61 -61
  165. package/src/screen-too-small.tsx +104 -104
  166. package/src/search-field.tsx +65 -0
  167. package/src/select.stories.tsx +44 -44
  168. package/src/select.tsx +197 -197
  169. package/src/separator.stories.tsx +34 -34
  170. package/src/separator.tsx +34 -34
  171. package/src/sheet.stories.tsx +49 -49
  172. package/src/sheet.tsx +168 -168
  173. package/src/skeleton.stories.tsx +28 -28
  174. package/src/skeleton.tsx +19 -19
  175. package/src/slider.stories.tsx +78 -78
  176. package/src/slider.tsx +300 -300
  177. package/src/spinner.stories.tsx +33 -33
  178. package/src/spinner.tsx +55 -55
  179. package/src/stepper.tsx +85 -0
  180. package/src/switch.stories.tsx +42 -42
  181. package/src/switch.tsx +41 -41
  182. package/src/switcher.stories.tsx +111 -111
  183. package/src/switcher.tsx +131 -131
  184. package/src/system-state.tsx +55 -0
  185. package/src/table.stories.tsx +48 -48
  186. package/src/table.tsx +121 -121
  187. package/src/tabs.stories.tsx +74 -74
  188. package/src/tabs.tsx +90 -90
  189. package/src/tag-input.stories.tsx +67 -67
  190. package/src/tag-input.tsx +117 -117
  191. package/src/tenant-logo.tsx +63 -63
  192. package/src/tenant-switcher.stories.tsx +38 -38
  193. package/src/tenant-switcher.tsx +185 -164
  194. package/src/textarea.stories.tsx +27 -27
  195. package/src/textarea.tsx +18 -18
  196. package/src/theme-mode.ts +74 -52
  197. package/src/time-grid.tsx +163 -0
  198. package/src/time-picker.stories.tsx +62 -62
  199. package/src/time-picker.tsx +616 -615
  200. package/src/toggle-group.tsx +139 -138
  201. package/src/tooltip.stories.tsx +43 -43
  202. package/src/tooltip.tsx +73 -73
  203. package/src/top-nav.stories.tsx +58 -58
  204. package/src/top-nav.tsx +324 -324
  205. package/src/undo-bar.tsx +107 -107
  206. package/src/utils.ts +45 -45
  207. package/src/view-toggle.stories.tsx +84 -84
  208. package/src/view-toggle.tsx +111 -110
@@ -1,306 +1,399 @@
1
- "use client"
2
-
3
- import * as React from "react"
4
-
5
- import { cn } from "./utils"
6
-
7
- /**
8
- * A searchable, keyboard-driven command list — the `/` or Ctrl-K surface.
9
- *
10
- * BUILT FROM PRIMITIVES RATHER THAN `cmdk`. The platform's stated selling
11
- * point is a lean, near-zero-dependency stack (ADR 0003), and what a palette
12
- * actually needs — filter a list, move a cursor, run a callback — is less code
13
- * than the wiring a dependency would take. Nothing here is novel; the value is
14
- * in not owing anyone an upgrade for it.
15
- *
16
- * PRESENTATIONAL AND CONTROLLED. It holds the query and the cursor, because
17
- * those die with the dialog; it holds no notion of what a command IS. The
18
- * caller supplies items and decides what running one means, which is what lets
19
- * the document designer feed it a flattened menu registry while another screen
20
- * feeds it something else entirely.
21
- *
22
- * COPY ARRIVES AS PROPS, with English defaults, for the reason every component
23
- * in this package does: `@whity/ui` is published standalone and may not
24
- * depend on the i18n feature (#758). Translating is the consumer's job.
25
- */
26
-
27
- export interface CommandPaletteItem {
28
- id: string
29
- label: string
30
- /** Heading this item sits under. Items are shown in the order given, grouped by first appearance. */
31
- group?: string
32
- /** Rendered right-aligned, e.g. "Ctrl+S". Never used for matching. */
33
- shortcut?: string
34
- icon?: React.ReactNode
35
- /**
36
- * Extra words that should MATCH but need not be shown — a block's scope, an
37
- * element's other name ("picture" finding "image").
38
- */
39
- keywords?: string
40
- /**
41
- * Shown greyed and skipped by the cursor, never hidden.
42
- *
43
- * A command absent from the list reads as "this editor cannot do that"; a
44
- * command present and greyed reads as "not right now", which is the true
45
- * statement and the one that stops somebody hunting through menus for
46
- * something that was never going to be available.
47
- */
48
- disabled?: boolean
49
- /**
50
- * Secondary words after the label, never matched against ("JOD 301.600 ·
51
- * overdue"): what tells two records with similar names apart.
52
- */
53
- hint?: string
54
- /**
55
- * Shown whatever the query, and not filtered by it: the "Ask an agent" row,
56
- * which takes the words as they are (register 2.1c).
57
- */
58
- always?: boolean
59
- /** An agent row: dashed, because nothing has happened until a person approves. */
60
- agent?: boolean
61
- onSelect: () => void
62
- }
63
-
64
- export interface CommandPaletteProps {
65
- open: boolean
66
- onOpenChange: (open: boolean) => void
67
- items: CommandPaletteItem[]
68
- placeholder?: string
69
- emptyLabel?: string
70
- /** Accessible name for the dialog. */
71
- label?: string
72
- /**
73
- * Called as the query changes, so the caller can fetch results (records
74
- * from search) and pass them back in `items`. Items the caller supplies
75
- * this way are still filtered here, so return what the server matched.
76
- */
77
- onQueryChange?: (query: string) => void
78
- /** The keys row at the foot. Omit to hide it. */
79
- footer?: { move: string; open: string; close: string }
80
- }
81
-
82
- /** Case-insensitive subsequence-free substring match over label + keywords. */
83
- function matches(item: CommandPaletteItem, query: string): boolean {
84
- if (query === "" || item.always === true) return true
85
- const q = query.toLowerCase()
86
- return (
87
- item.label.toLowerCase().includes(q) ||
88
- (item.group?.toLowerCase().includes(q) ?? false) ||
89
- (item.keywords?.toLowerCase().includes(q) ?? false)
90
- )
91
- }
92
-
93
- export function CommandPalette({
94
- open,
95
- onOpenChange,
96
- items,
97
- placeholder = "Type a command…",
98
- emptyLabel = "No matching command",
99
- label = "Command palette",
100
- onQueryChange,
101
- footer,
102
- }: CommandPaletteProps) {
103
- const [query, setQuery] = React.useState("")
104
- const [cursor, setCursor] = React.useState(0)
105
- const inputRef = React.useRef<HTMLInputElement>(null)
106
- const listRef = React.useRef<HTMLDivElement>(null)
107
-
108
- const shown = React.useMemo(() => items.filter((i) => matches(i, query)), [items, query])
109
-
110
- // The indices the cursor may land on. A disabled item is displayed but never
111
- // selected, so navigation skips it rather than stopping on something Enter
112
- // would silently ignore.
113
- const selectable = React.useMemo(
114
- () => shown.map((item, index) => (item.disabled === true ? -1 : index)).filter((i) => i >= 0),
115
- [shown]
116
- )
117
-
118
- // Reset on open, and whenever the query changes the previous cursor is
119
- // meaningless — it pointed into a different list.
120
- React.useEffect(() => {
121
- if (open) {
122
- setQuery("")
123
- setCursor(0)
124
- // Focus after paint; the input does not exist until this renders.
125
- const id = requestAnimationFrame(() => inputRef.current?.focus())
126
- return () => cancelAnimationFrame(id)
127
- }
128
- return undefined
129
- }, [open])
130
-
131
- React.useEffect(() => {
132
- setCursor(selectable[0] ?? 0)
133
- }, [query, selectable])
134
-
135
- // Escape at the DOCUMENT level, not only on the dialog.
136
- //
137
- // Focus arrives a frame late (the input does not exist until this renders),
138
- // so an Escape pressed in that gap would reach whatever had focus before —
139
- // in the document designer, a window handler that deselects the canvas — and
140
- // the palette would stay open having eaten the keystroke. Rare, and exactly
141
- // the kind of race that shows up as a flaky test rather than a bug report.
142
- React.useEffect(() => {
143
- if (!open) return undefined;
144
- const onEscape = (e: KeyboardEvent) => {
145
- if (e.key !== 'Escape') return
146
- e.preventDefault()
147
- e.stopPropagation()
148
- onOpenChange(false)
149
- }
150
- // Capture phase: ahead of any window listener the host already has.
151
- document.addEventListener('keydown', onEscape, true)
152
- return () => document.removeEventListener('keydown', onEscape, true)
153
- }, [open, onOpenChange])
154
-
155
- // Keep the highlighted row in view when arrowing past the fold.
156
- React.useEffect(() => {
157
- if (!open) return
158
- const el = listRef.current?.querySelector<HTMLElement>(`[data-index="${cursor}"]`)
159
- el?.scrollIntoView({ block: "nearest" })
160
- }, [cursor, open])
161
-
162
- if (!open) return null
163
-
164
- const step = (delta: number) => {
165
- if (selectable.length === 0) return
166
- const at = selectable.indexOf(cursor)
167
- const next = at === -1 ? 0 : (at + delta + selectable.length) % selectable.length
168
- setCursor(selectable[next])
169
- }
170
-
171
- const run = (item: CommandPaletteItem | undefined) => {
172
- if (!item || item.disabled === true) return
173
- // Close FIRST. A command that opens a dialog of its own would otherwise
174
- // find this one still mounted and fighting it for focus.
175
- onOpenChange(false)
176
- item.onSelect()
177
- }
178
-
179
- const onKeyDown = (e: React.KeyboardEvent) => {
180
- if (e.key === "ArrowDown") {
181
- e.preventDefault()
182
- step(1)
183
- return
184
- }
185
- if (e.key === "ArrowUp") {
186
- e.preventDefault()
187
- step(-1)
188
- return
189
- }
190
- if (e.key === "Enter") {
191
- e.preventDefault()
192
- run(shown[cursor])
193
- return
194
- }
195
- if (e.key === "Escape") {
196
- e.preventDefault()
197
- onOpenChange(false)
198
- }
199
- // Everything else falls through to the input, including "/" — a palette
200
- // you cannot type a slash into would be unable to search for anything
201
- // named with one.
202
- }
203
-
204
- let lastGroup: string | undefined
205
-
206
- return (
207
- <div
208
- className="fixed inset-0 z-50 flex items-start justify-center bg-foreground/30 px-4 pt-[12vh]"
209
- // A backdrop click closes, matching every other dismissible surface. The
210
- // dialog itself stops propagation below.
211
- onMouseDown={() => onOpenChange(false)}
212
- data-testid="command-palette-backdrop"
213
- >
214
- <div
215
- role="dialog"
216
- aria-modal="true"
217
- aria-label={label}
218
- className="w-full max-w-xl overflow-hidden rounded-2xl border border-border bg-popover text-popover-foreground shadow-float"
219
- onMouseDown={(e) => e.stopPropagation()}
220
- onKeyDown={onKeyDown}
221
- data-testid="command-palette"
222
- >
223
- <input
224
- ref={inputRef}
225
- value={query}
226
- onChange={(e) => {
227
- setQuery(e.target.value)
228
- onQueryChange?.(e.target.value)
229
- }}
230
- placeholder={placeholder}
231
- aria-label={label}
232
- role="combobox"
233
- aria-expanded
234
- aria-controls="command-palette-list"
235
- aria-activedescendant={shown[cursor] ? `command-item-${shown[cursor].id}` : undefined}
236
- className="w-full border-b border-border bg-transparent px-4 py-3.5 text-base outline-none placeholder:text-muted-foreground"
237
- data-testid="command-palette-input"
238
- />
239
-
240
- <div
241
- ref={listRef}
242
- id="command-palette-list"
243
- role="listbox"
244
- aria-label={label}
245
- className="max-h-80 overflow-y-auto p-1"
246
- >
247
- {shown.length === 0 && (
248
- <p className="px-3 py-6 text-center text-sm text-muted-foreground" data-testid="command-palette-empty">
249
- {emptyLabel}
250
- </p>
251
- )}
252
-
253
- {shown.map((item, index) => {
254
- const header = item.group !== undefined && item.group !== lastGroup ? item.group : null
255
- lastGroup = item.group
256
-
257
- return (
258
- <React.Fragment key={item.id}>
259
- {header !== null && (
260
- <div className="px-3 pt-3 pb-1 text-[0.8125rem] font-medium text-muted-foreground">
261
- {header}
262
- </div>
263
- )}
264
- <div
265
- id={`command-item-${item.id}`}
266
- role="option"
267
- aria-selected={index === cursor}
268
- aria-disabled={item.disabled === true}
269
- data-index={index}
270
- data-testid={`command-item-${item.id}`}
271
- onMouseEnter={() => item.disabled !== true && setCursor(index)}
272
- onClick={() => run(item)}
273
- className={cn(
274
- "flex cursor-pointer items-center gap-2 rounded-md px-3 py-2 text-sm",
275
- // The selected row is the tint with text in the main colour (7.3).
276
- index === cursor && item.disabled !== true && "bg-primary-tint text-primary-tint-foreground",
277
- item.agent === true && "border border-dashed border-input",
278
- item.disabled === true && "cursor-not-allowed opacity-45"
279
- )}
280
- >
281
- {item.icon !== undefined && <span className="shrink-0 text-muted-foreground">{item.icon}</span>}
282
- <span className="min-w-0 flex-1 truncate">
283
- {item.label}
284
- {item.hint !== undefined && (
285
- <span className="ms-2 text-[0.8125rem] text-muted-foreground">{item.hint}</span>
286
- )}
287
- </span>
288
- {item.shortcut !== undefined && (
289
- <span className="shrink-0 text-xs text-muted-foreground">{item.shortcut}</span>
290
- )}
291
- </div>
292
- </React.Fragment>
293
- )
294
- })}
295
- </div>
296
- {footer !== undefined && (
297
- <div className="flex gap-4 border-t border-border px-4 py-2 text-[0.8125rem] text-muted-foreground">
298
- <span><kbd className="me-1 rounded border border-border px-1 font-mono text-[0.6875rem]">↑↓</kbd>{footer.move}</span>
299
- <span><kbd className="me-1 rounded border border-border px-1 font-mono text-[0.6875rem]">Enter</kbd>{footer.open}</span>
300
- <span><kbd className="me-1 rounded border border-border px-1 font-mono text-[0.6875rem]">Esc</kbd>{footer.close}</span>
301
- </div>
302
- )}
303
- </div>
304
- </div>
305
- )
306
- }
1
+ "use client"
2
+
3
+ import * as React from "react"
4
+
5
+ import { cn } from "./utils"
6
+
7
+ /**
8
+ * A searchable, keyboard-driven command list — the `/` or Ctrl-K surface.
9
+ *
10
+ * BUILT FROM PRIMITIVES RATHER THAN `cmdk`. The platform's stated selling
11
+ * point is a lean, near-zero-dependency stack (ADR 0003), and what a palette
12
+ * actually needs — filter a list, move a cursor, run a callback — is less code
13
+ * than the wiring a dependency would take. Nothing here is novel; the value is
14
+ * in not owing anyone an upgrade for it.
15
+ *
16
+ * PRESENTATIONAL AND CONTROLLED. It holds the query and the cursor, because
17
+ * those die with the dialog; it holds no notion of what a command IS. The
18
+ * caller supplies items and decides what running one means, which is what lets
19
+ * the document designer feed it a flattened menu registry while another screen
20
+ * feeds it something else entirely.
21
+ *
22
+ * COPY ARRIVES AS PROPS, with English defaults, for the reason every component
23
+ * in this package does: `@whity/ui` is published standalone and may not
24
+ * depend on the i18n feature (#758). Translating is the consumer's job.
25
+ */
26
+
27
+ export interface CommandPaletteItem {
28
+ id: string
29
+ label: string
30
+ /** Heading this item sits under. Items are shown in the order given, grouped by first appearance. */
31
+ group?: string
32
+ /** Rendered right-aligned, e.g. "Ctrl+S". Never used for matching. */
33
+ shortcut?: string
34
+ icon?: React.ReactNode
35
+ /**
36
+ * Extra words that should MATCH but need not be shown — a block's scope, an
37
+ * element's other name ("picture" finding "image").
38
+ */
39
+ keywords?: string
40
+ /**
41
+ * Shown greyed and skipped by the cursor, never hidden.
42
+ *
43
+ * A command absent from the list reads as "this editor cannot do that"; a
44
+ * command present and greyed reads as "not right now", which is the true
45
+ * statement and the one that stops somebody hunting through menus for
46
+ * something that was never going to be available.
47
+ */
48
+ disabled?: boolean
49
+ /**
50
+ * Secondary words after the label, never matched against ("$301.60 ·
51
+ * overdue"): what tells two records with similar names apart.
52
+ */
53
+ hint?: string
54
+ /**
55
+ * Shown whatever the query, and not filtered by it: the "Ask an agent" row,
56
+ * which takes the words as they are (register 2.1c).
57
+ */
58
+ always?: boolean
59
+ /** An agent row: dashed, because nothing has happened until a person approves. */
60
+ agent?: boolean
61
+ /**
62
+ * Keep the palette open after `onSelect`: picking a command that still needs
63
+ * its details (`/go` then a screen) only changes the query.
64
+ */
65
+ keepOpen?: boolean
66
+ /**
67
+ * What Tab does on this row: complete it into the query (`/ne` becomes
68
+ * `/new `). Without it, Tab leaves the palette's own keys alone.
69
+ */
70
+ onComplete?: () => void
71
+ onSelect: () => void
72
+ }
73
+
74
+ export interface CommandPaletteProps {
75
+ open: boolean
76
+ onOpenChange: (open: boolean) => void
77
+ items: CommandPaletteItem[]
78
+ placeholder?: string
79
+ emptyLabel?: string
80
+ /** Accessible name for the dialog. */
81
+ label?: string
82
+ /**
83
+ * Called as the query changes, so the caller can fetch results (records
84
+ * from search) and pass them back in `items`. Items the caller supplies
85
+ * this way are still filtered here, so return what the server matched.
86
+ */
87
+ onQueryChange?: (query: string) => void
88
+ /** The keys row at the foot. Omit to hide it. */
89
+ footer?: { move: string; open: string; close: string; complete?: string }
90
+ /**
91
+ * The query, when the caller owns it (commands rewrite it: Tab completes
92
+ * `/ne` into `/new `). Omit to let the palette keep its own. A controlled
93
+ * caller resets it on open itself.
94
+ */
95
+ query?: string
96
+ /**
97
+ * False when the caller has already chosen what matches (command mode
98
+ * parses the query itself, so a substring test here would hide `/new
99
+ * document` behind the words after it).
100
+ */
101
+ filter?: boolean
102
+ /** A chip before the input naming the mode, e.g. "Commands". */
103
+ mode?: string
104
+ /**
105
+ * Read out after the list changes ("6 results"), so a screen-reader user
106
+ * hears that typing did something. Omit for silence.
107
+ */
108
+ countLabel?: (count: number) => string
109
+ /**
110
+ * Type a slash for the person when they press the slash KEY on an empty
111
+ * box, whatever their layout: on the Arabic layout that key types "ظ", and
112
+ * `/` is how commands start.
113
+ */
114
+ slashKey?: boolean
115
+ }
116
+
117
+ /** Case-insensitive subsequence-free substring match over label + keywords. */
118
+ function matches(item: CommandPaletteItem, query: string): boolean {
119
+ if (query === "" || item.always === true) return true
120
+ const q = query.toLowerCase()
121
+ return (
122
+ item.label.toLowerCase().includes(q) ||
123
+ (item.group?.toLowerCase().includes(q) ?? false) ||
124
+ (item.keywords?.toLowerCase().includes(q) ?? false)
125
+ )
126
+ }
127
+
128
+ export function CommandPalette({
129
+ open,
130
+ onOpenChange,
131
+ items,
132
+ placeholder = "Type a command…",
133
+ emptyLabel = "No matching command",
134
+ label = "Command palette",
135
+ onQueryChange,
136
+ footer,
137
+ query: controlledQuery,
138
+ filter = true,
139
+ mode,
140
+ countLabel,
141
+ slashKey = false,
142
+ }: CommandPaletteProps) {
143
+ const [ownQuery, setOwnQuery] = React.useState("")
144
+ const query = controlledQuery ?? ownQuery
145
+ const setQuery = (next: string) => {
146
+ if (controlledQuery === undefined) setOwnQuery(next)
147
+ onQueryChange?.(next)
148
+ }
149
+ const [cursor, setCursor] = React.useState(0)
150
+ const inputRef = React.useRef<HTMLInputElement>(null)
151
+ const listRef = React.useRef<HTMLDivElement>(null)
152
+
153
+ const shown = React.useMemo(
154
+ () => (filter ? items.filter((i) => matches(i, query)) : items),
155
+ [items, query, filter]
156
+ )
157
+
158
+ // The indices the cursor may land on. A disabled item is displayed but never
159
+ // selected, so navigation skips it rather than stopping on something Enter
160
+ // would silently ignore.
161
+ const selectable = React.useMemo(
162
+ () => shown.map((item, index) => (item.disabled === true ? -1 : index)).filter((i) => i >= 0),
163
+ [shown]
164
+ )
165
+
166
+ // Reset on open, and whenever the query changes the previous cursor is
167
+ // meaningless — it pointed into a different list.
168
+ React.useEffect(() => {
169
+ if (open) {
170
+ setOwnQuery("")
171
+ setCursor(0)
172
+ // Focus after paint; the input does not exist until this renders.
173
+ const id = requestAnimationFrame(() => inputRef.current?.focus())
174
+ return () => cancelAnimationFrame(id)
175
+ }
176
+ return undefined
177
+ }, [open])
178
+
179
+ React.useEffect(() => {
180
+ setCursor(selectable[0] ?? 0)
181
+ }, [query, selectable])
182
+
183
+ // Escape at the DOCUMENT level, not only on the dialog.
184
+ //
185
+ // Focus arrives a frame late (the input does not exist until this renders),
186
+ // so an Escape pressed in that gap would reach whatever had focus before —
187
+ // in the document designer, a window handler that deselects the canvas — and
188
+ // the palette would stay open having eaten the keystroke. Rare, and exactly
189
+ // the kind of race that shows up as a flaky test rather than a bug report.
190
+ React.useEffect(() => {
191
+ if (!open) return undefined;
192
+ const onEscape = (e: KeyboardEvent) => {
193
+ if (e.key !== 'Escape') return
194
+ e.preventDefault()
195
+ e.stopPropagation()
196
+ onOpenChange(false)
197
+ }
198
+ // Capture phase: ahead of any window listener the host already has.
199
+ document.addEventListener('keydown', onEscape, true)
200
+ return () => document.removeEventListener('keydown', onEscape, true)
201
+ }, [open, onOpenChange])
202
+
203
+ // Keep the highlighted row in view when arrowing past the fold.
204
+ React.useEffect(() => {
205
+ if (!open) return
206
+ const el = listRef.current?.querySelector<HTMLElement>(`[data-index="${cursor}"]`)
207
+ el?.scrollIntoView({ block: "nearest" })
208
+ }, [cursor, open])
209
+
210
+ if (!open) return null
211
+
212
+ const step = (delta: number) => {
213
+ if (selectable.length === 0) return
214
+ const at = selectable.indexOf(cursor)
215
+ const next = at === -1 ? 0 : (at + delta + selectable.length) % selectable.length
216
+ setCursor(selectable[next])
217
+ }
218
+
219
+ const run = (item: CommandPaletteItem | undefined) => {
220
+ if (!item || item.disabled === true) return
221
+ // Close FIRST. A command that opens a dialog of its own would otherwise
222
+ // find this one still mounted and fighting it for focus.
223
+ if (item.keepOpen !== true) onOpenChange(false)
224
+ item.onSelect()
225
+ if (item.keepOpen === true) inputRef.current?.focus()
226
+ }
227
+
228
+ const onKeyDown = (e: React.KeyboardEvent) => {
229
+ if (e.key === "ArrowDown") {
230
+ e.preventDefault()
231
+ step(1)
232
+ return
233
+ }
234
+ if (e.key === "ArrowUp") {
235
+ e.preventDefault()
236
+ step(-1)
237
+ return
238
+ }
239
+ if (e.key === "Enter") {
240
+ e.preventDefault()
241
+ run(shown[cursor])
242
+ return
243
+ }
244
+ if (e.key === "Tab" && !e.shiftKey) {
245
+ const item = shown[cursor]
246
+ if (item?.onComplete !== undefined && item.disabled !== true) {
247
+ e.preventDefault()
248
+ item.onComplete()
249
+ inputRef.current?.focus()
250
+ }
251
+ return
252
+ }
253
+ if (e.key === "Home" || e.key === "End") {
254
+ if (selectable.length === 0 || query !== "") return
255
+ e.preventDefault()
256
+ setCursor(e.key === "Home" ? selectable[0] : selectable[selectable.length - 1])
257
+ return
258
+ }
259
+ if (
260
+ slashKey &&
261
+ query === "" &&
262
+ e.code === "Slash" &&
263
+ e.key !== "/" &&
264
+ !e.ctrlKey &&
265
+ !e.metaKey &&
266
+ !e.altKey
267
+ ) {
268
+ e.preventDefault()
269
+ setQuery("/")
270
+ return
271
+ }
272
+ if (e.key === "Escape") {
273
+ e.preventDefault()
274
+ onOpenChange(false)
275
+ }
276
+ // Everything else falls through to the input, including "/" — a palette
277
+ // you cannot type a slash into would be unable to search for anything
278
+ // named with one.
279
+ }
280
+
281
+ let lastGroup: string | undefined
282
+
283
+ return (
284
+ <div
285
+ className="fixed inset-0 z-50 flex items-start justify-center bg-foreground/30 px-4 pt-[12vh]"
286
+ // A backdrop click closes, matching every other dismissible surface. The
287
+ // dialog itself stops propagation below.
288
+ onMouseDown={() => onOpenChange(false)}
289
+ data-testid="command-palette-backdrop"
290
+ >
291
+ <div
292
+ role="dialog"
293
+ aria-modal="true"
294
+ aria-label={label}
295
+ data-slot="command-palette"
296
+ className="w-full max-w-xl overflow-hidden rounded-2xl border border-border bg-popover text-popover-foreground shadow-float"
297
+ onMouseDown={(e) => e.stopPropagation()}
298
+ onKeyDown={onKeyDown}
299
+ data-testid="command-palette"
300
+ >
301
+ <div className="flex items-center gap-2 border-b border-border px-4">
302
+ {mode !== undefined && (
303
+ <span
304
+ className="shrink-0 rounded-md bg-primary-tint px-2 py-0.5 text-xs font-medium text-primary-tint-foreground"
305
+ data-testid="command-palette-mode"
306
+ >
307
+ {mode}
308
+ </span>
309
+ )}
310
+ <input
311
+ ref={inputRef}
312
+ value={query}
313
+ onChange={(e) => setQuery(e.target.value)}
314
+ placeholder={placeholder}
315
+ aria-label={label}
316
+ role="combobox"
317
+ aria-expanded
318
+ aria-controls="command-palette-list"
319
+ aria-activedescendant={shown[cursor] ? `command-item-${shown[cursor].id}` : undefined}
320
+ className="min-w-0 flex-1 bg-transparent py-3.5 text-base outline-none placeholder:text-muted-foreground"
321
+ data-testid="command-palette-input"
322
+ />
323
+ </div>
324
+ {countLabel !== undefined && (
325
+ <span className="sr-only" aria-live="polite" data-testid="command-palette-count">
326
+ {countLabel(selectable.length)}
327
+ </span>
328
+ )}
329
+
330
+ <div
331
+ ref={listRef}
332
+ id="command-palette-list"
333
+ role="listbox"
334
+ aria-label={label}
335
+ className="max-h-80 overflow-y-auto p-1"
336
+ >
337
+ {shown.length === 0 && (
338
+ <p className="px-3 py-6 text-center text-sm text-muted-foreground" data-testid="command-palette-empty">
339
+ {emptyLabel}
340
+ </p>
341
+ )}
342
+
343
+ {shown.map((item, index) => {
344
+ const header = item.group !== undefined && item.group !== lastGroup ? item.group : null
345
+ lastGroup = item.group
346
+
347
+ return (
348
+ <React.Fragment key={item.id}>
349
+ {header !== null && (
350
+ <div className="px-3 pt-3 pb-1 text-[0.8125rem] font-medium text-muted-foreground">
351
+ {header}
352
+ </div>
353
+ )}
354
+ <div
355
+ id={`command-item-${item.id}`}
356
+ role="option"
357
+ aria-selected={index === cursor}
358
+ aria-disabled={item.disabled === true}
359
+ data-index={index}
360
+ data-testid={`command-item-${item.id}`}
361
+ onMouseEnter={() => item.disabled !== true && setCursor(index)}
362
+ onClick={() => run(item)}
363
+ className={cn(
364
+ "flex cursor-pointer items-center gap-2 rounded-md px-3 py-2 text-sm",
365
+ // The selected row is the tint with text in the main colour (7.3).
366
+ index === cursor && item.disabled !== true && "bg-primary-tint text-primary-tint-foreground",
367
+ item.agent === true && "border border-dashed border-input",
368
+ item.disabled === true && "cursor-not-allowed opacity-45"
369
+ )}
370
+ >
371
+ {item.icon !== undefined && <span className="shrink-0 text-muted-foreground">{item.icon}</span>}
372
+ <span className="min-w-0 flex-1 truncate">
373
+ {item.label}
374
+ {item.hint !== undefined && (
375
+ <span className="ms-2 text-[0.8125rem] text-muted-foreground">{item.hint}</span>
376
+ )}
377
+ </span>
378
+ {item.shortcut !== undefined && (
379
+ <span className="shrink-0 text-xs text-muted-foreground">{item.shortcut}</span>
380
+ )}
381
+ </div>
382
+ </React.Fragment>
383
+ )
384
+ })}
385
+ </div>
386
+ {footer !== undefined && (
387
+ <div className="flex gap-4 border-t border-border px-4 py-2 text-[0.8125rem] text-muted-foreground">
388
+ <span><kbd className="me-1 rounded border border-border px-1 font-mono text-xs">↑↓</kbd>{footer.move}</span>
389
+ <span><kbd className="me-1 rounded border border-border px-1 font-mono text-xs">Enter</kbd>{footer.open}</span>
390
+ {footer.complete !== undefined && (
391
+ <span><kbd className="me-1 rounded border border-border px-1 font-mono text-xs">Tab</kbd>{footer.complete}</span>
392
+ )}
393
+ <span><kbd className="me-1 rounded border border-border px-1 font-mono text-xs">Esc</kbd>{footer.close}</span>
394
+ </div>
395
+ )}
396
+ </div>
397
+ </div>
398
+ )
399
+ }