@greenharness/greenrack-ui 7.1.1 → 7.2.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 (29) hide show
  1. package/dist/components/Button/Button.stories.d.ts +7 -0
  2. package/dist/components/Button/Button.stories.d.ts.map +1 -1
  3. package/dist/components/Button/styles.css.d.ts +1 -0
  4. package/dist/components/Button/styles.css.d.ts.map +1 -1
  5. package/dist/components/Combobox/Combobox.d.ts +6 -2
  6. package/dist/components/Combobox/Combobox.d.ts.map +1 -1
  7. package/dist/components/Combobox/Combobox.stories.d.ts +23 -0
  8. package/dist/components/Combobox/Combobox.stories.d.ts.map +1 -1
  9. package/dist/components/Combobox/ComboboxContext.d.ts +4 -0
  10. package/dist/components/Combobox/ComboboxContext.d.ts.map +1 -1
  11. package/dist/components/Combobox/comboboxState.d.ts +4 -2
  12. package/dist/components/Combobox/comboboxState.d.ts.map +1 -1
  13. package/dist/components/Combobox/useComboboxRoot.d.ts.map +1 -1
  14. package/dist/components/LinkButton/styles.css.d.ts +1 -0
  15. package/dist/components/LinkButton/styles.css.d.ts.map +1 -1
  16. package/dist/index.css +1 -1
  17. package/dist/index.js +3025 -3003
  18. package/dist/index.js.map +1 -1
  19. package/package.json +2 -2
  20. package/src/components/Button/Button.stories.tsx +37 -0
  21. package/src/components/Button/styles.css.ts +4 -0
  22. package/src/components/Combobox/Combobox.meta.ts +1 -1
  23. package/src/components/Combobox/Combobox.native.tsx +18 -4
  24. package/src/components/Combobox/Combobox.stories.tsx +355 -2
  25. package/src/components/Combobox/Combobox.tsx +54 -11
  26. package/src/components/Combobox/ComboboxContext.ts +4 -0
  27. package/src/components/Combobox/comboboxState.ts +19 -3
  28. package/src/components/Combobox/useComboboxRoot.ts +128 -47
  29. package/src/components/LinkButton/styles.css.ts +2 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@greenharness/greenrack-ui",
3
- "version": "7.1.1",
3
+ "version": "7.2.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -92,7 +92,7 @@
92
92
  "dependencies": {
93
93
  "@tanstack/react-virtual": "^3.14.13",
94
94
  "qrcode": "^1.5.4",
95
- "@greenharness/greenrack-tokens": "^7.1.1"
95
+ "@greenharness/greenrack-tokens": "^7.2.0"
96
96
  },
97
97
  "devDependencies": {
98
98
  "@babel/preset-typescript": "^7.28.0",
@@ -6,6 +6,11 @@ import {Button} from './Button'
6
6
  import {Icon} from '../Icon/Icon'
7
7
  import {RADII_PX} from '@greenharness/greenrack-tokens/keys'
8
8
  import {spacing} from '@greenharness/greenrack-tokens/tokens/spacing.css'
9
+ import {sizes} from '@greenharness/greenrack-tokens/tokens/sizes.css'
10
+ import {Inline} from '../Inline/Inline'
11
+ import {Input} from '../Input/Input'
12
+ import {Field} from '../Field/Field'
13
+ import {withCoarsePointer, withFinePointer} from '../../docs/coarsePointer'
9
14
 
10
15
  const meta: Meta<typeof Button> = {
11
16
  title: 'Components/Button',
@@ -196,3 +201,35 @@ export const Ghost: Story = {
196
201
  await expect(getComputedStyle(button).borderTopWidth).toBe('0px')
197
202
  },
198
203
  }
204
+
205
+ const crowded = css.create({row: {width: sizes.gridColSm}})
206
+
207
+ /**
208
+ * A Button beside a long field in a narrow row keeps its label inside its
209
+ * padding, with a mouse and under a coarse pointer. The touch target's
210
+ * `min-width` replaces the flex item's `min-width: auto`, so without
211
+ * `flexShrink: 0` the row squeezed the button below its label (5.45 to 7.1.0).
212
+ */
213
+ export const CrowdedRow: Story = {
214
+ render: () => (
215
+ <html.div style={crowded.row}>
216
+ <Inline gap="sm" align="end">
217
+ <Field.Root name="title">
218
+ <Field.Label>Task title</Field.Label>
219
+ <Input name="title" defaultValue="feat/a-very-long-branch-name-to-check-wrapping" />
220
+ <Field.Description>
221
+ Future sessions on feat/a-very-long-branch-name-to-check-wrapping attach automatically.
222
+ </Field.Description>
223
+ </Field.Root>
224
+ <Button type="submit">New task</Button>
225
+ </Inline>
226
+ </html.div>
227
+ ),
228
+ play: async ({canvas}) => {
229
+ const button = canvas.getByRole('button', {name: 'New task'})
230
+ const fits = () => expect(button.scrollWidth).toBeLessThanOrEqual(button.clientWidth)
231
+ await withFinePointer()
232
+ await fits()
233
+ await withCoarsePointer(fits)
234
+ },
235
+ }
@@ -28,6 +28,10 @@ export const styles = css.create({
28
28
  // A touch screen gets the 44px target, as Toggle and the triggers do; a
29
29
  // mouse keeps the compact control (5.6, the person's decision).
30
30
  minWidth: {default: null, '@media (pointer: coarse)': sizes.touchTarget},
31
+ // That min-width replaces the flex item's `min-width: auto`, so in a
32
+ // crowded row the button would shrink below its nowrap label. It never
33
+ // shrinks: the row wraps or the field gives way.
34
+ flexShrink: 0,
31
35
  // Tactile press feedback. The scale is suppressed under reduced motion (and
32
36
  // duration.fast collapses to 0ms there too), so it's inert for those users.
33
37
  transform: {
@@ -2,7 +2,7 @@ import type {ComponentMeta} from '../component-meta'
2
2
 
3
3
  export const meta: ComponentMeta = {
4
4
  description:
5
- "Searchable dropdown for selecting a value from a filterable list. Combines a text input with a popup listbox. Compound component — Root is required. Combobox.Popup takes label (the list's accessible name). On React Native the field opens a bottom sheet at its large detent, above the keyboard, titled by label with a Cancel text button (cancelLabel): a search field is pinned under the header and focused, the list below filters as you type, Combobox.Empty shows when nothing matches, and a press picks an option and closes the sheet. The sheet's search text starts empty each time; Combobox.Trigger renders nothing on native. An Item takes description (a muted second line) and leading (an icon or small preview, decorative), laid out as Select.Item's are: the option's accessible name, its filtering and the text committed to the field stay its label, and the description is its accessible description.",
5
+ "Searchable dropdown for selecting a value from a filterable list. Combines a text input with a popup listbox. Compound component — Root is required. Combobox.Popup takes label (the list's accessible name). On React Native the field opens a bottom sheet at its large detent, above the keyboard, titled by label with a Cancel text button (cancelLabel): a search field is pinned under the header and focused, the list below filters as you type, Combobox.Empty shows when nothing matches, and a press picks an option and closes the sheet. The sheet's search text starts empty each time; Combobox.Trigger renders nothing on native. An Item takes description (a muted second line) and leading (an icon or small preview, decorative), laid out as Select.Item's are: the option's accessible name, its filtering and the text committed to the field stay its label, and the description is its accessible description. Root takes onOpenChange, called once each time the list (web) or sheet (native) opens or closes; there is no controlled open, as on Select, and it is not called when the Root unmounts while open. On the web the list opens with every option while the field shows its chosen option's label, and filters only once the text is edited; opening by focus selects the text. Combobox.Input is named by aria-label, or inside Field.Root by Field.Label. On native the field's accessibility label is aria-label, else the shown value, else the placeholder, and the shown value is its accessibility value when aria-label is given; native does not read Field.Label, so a native field inside Field.Root needs aria-label.",
6
6
  whenToUse: [
7
7
  'Large option lists where users benefit from typing to filter (e.g. country, city, user picker)',
8
8
  'Autocomplete or typeahead scenarios',
@@ -24,8 +24,8 @@ import {sheetStyles} from '../Listbox/native.css'
24
24
  import {Button} from '../Button/Button'
25
25
  import {Icon} from '../Icon/Icon'
26
26
  import {Chevron} from '../SideNav/Chevron'
27
- import {focusForAccessibility} from '../../shared/accessibilityFocus'
28
- import {focusInput} from '../../shared/focusInput'
27
+ import {focusForAccessibility} from '../../shared/accessibilityFocus.native'
28
+ import {focusInput} from '../../shared/focusInput.native'
29
29
  import {textOf} from '../../shared/textOf'
30
30
 
31
31
  /** The picker sheet's detents (plan N0, Decision 5); a Combobox opens at large. */
@@ -71,6 +71,8 @@ interface RootProps {
71
71
  /** The field's text: the chosen option's label on native */
72
72
  inputValue?: string
73
73
  onInputChange?: (value: string) => void
74
+ /** Called once each time the sheet opens or closes. There is no controlled `open`, as on Select. */
75
+ onOpenChange?: (open: boolean) => void
74
76
  initialLabels?: Record<string, string>
75
77
  children: ReactNode
76
78
  }
@@ -88,6 +90,7 @@ function Root({
88
90
  onValueChange,
89
91
  inputValue,
90
92
  onInputChange,
93
+ onOpenChange,
91
94
  initialLabels,
92
95
  children,
93
96
  }: RootProps) {
@@ -97,6 +100,7 @@ function Root({
97
100
  onValueChange,
98
101
  inputValue,
99
102
  onInputChange,
103
+ onOpenChange,
100
104
  initialLabels,
101
105
  })
102
106
  const {open, setOpen, chooseValue} = state
@@ -158,7 +162,16 @@ function Root({
158
162
  * The closed field: the chosen option's label, or the placeholder. A press
159
163
  * opens the sheet, where the typing happens.
160
164
  */
161
- function Input({placeholder, children}: {placeholder?: string; children?: ReactNode}) {
165
+ function Input({
166
+ placeholder,
167
+ 'aria-label': ariaLabel,
168
+ children,
169
+ }: {
170
+ placeholder?: string
171
+ /** The field's accessible name; the shown value then rides in its accessibility value. */
172
+ 'aria-label'?: string
173
+ children?: ReactNode
174
+ }) {
162
175
  const {value, labels, open, setOpen, setPlaceholder, triggerRef} = useCombobox()
163
176
  const display = value ? (labels[value] ?? value) : null
164
177
 
@@ -171,7 +184,8 @@ function Input({placeholder, children}: {placeholder?: string; children?: ReactN
171
184
  ref={triggerRef as RefObject<never>}
172
185
  onPress={() => setOpen(true)}
173
186
  accessibilityRole="combobox"
174
- accessibilityLabel={display ?? placeholder}
187
+ accessibilityLabel={ariaLabel ?? display ?? placeholder}
188
+ accessibilityValue={ariaLabel && display ? {text: display} : undefined}
175
189
  accessibilityState={{expanded: open}}
176
190
  >
177
191
  <html.div style={[styles.inputWrapper, nativeStyles.field]}>
@@ -1,9 +1,10 @@
1
- import {useState} from 'react'
1
+ import {StrictMode, useState} from 'react'
2
2
  import type {Meta, StoryObj} from '@storybook/react'
3
- import {expect, screen, waitFor} from 'storybook/test'
3
+ import {expect, fn, screen, waitFor} from 'storybook/test'
4
4
  import {Combobox} from './Combobox'
5
5
  import {Stack} from '../Stack/Stack'
6
6
  import {Text} from '../Text/Text'
7
+ import {Field} from '../Field/Field'
7
8
 
8
9
  const meta: Meta = {
9
10
  title: 'Components/Combobox',
@@ -12,6 +13,9 @@ const meta: Meta = {
12
13
  export default meta
13
14
  type Story = StoryObj
14
15
 
16
+ // Edge-case harnesses: run in CI, hidden from the sidebar and the docs page.
17
+ const TEST_ONLY = ['!dev', '!autodocs']
18
+
15
19
  const fruits = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry', 'Fig', 'Grape', 'Honeydew']
16
20
 
17
21
  export const Default: Story = {
@@ -192,3 +196,352 @@ export const DescriptionAndLeading: Story = {
192
196
  await waitFor(() => expect(input).toHaveValue('Deep'))
193
197
  },
194
198
  }
199
+
200
+ const fruitLabels = Object.fromEntries(fruits.map((f) => [f.toLowerCase(), f]))
201
+
202
+ function FruitList() {
203
+ return (
204
+ <Combobox.Popup label="Fruit">
205
+ {fruits.map((fruit) => (
206
+ <Combobox.Item key={fruit} value={fruit.toLowerCase()}>
207
+ <Combobox.ItemText>{fruit}</Combobox.ItemText>
208
+ </Combobox.Item>
209
+ ))}
210
+ <Combobox.Empty>No fruits found</Combobox.Empty>
211
+ </Combobox.Popup>
212
+ )
213
+ }
214
+
215
+ const optionCount = () => screen.queryAllByRole('option').length
216
+ const pause = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
217
+ // Past the input's 150 ms blur close, so a close that was going to fire has.
218
+ // Real time on purpose: these run in a browser, where fake timers would also
219
+ // freeze userEvent's own delays.
220
+ const AFTER_BLUR_CLOSE_MS = 300
221
+
222
+ export const OpensWithEveryOption: Story = {
223
+ tags: TEST_ONLY,
224
+ render: () => (
225
+ <Combobox.Root defaultValue="cherry" initialLabels={fruitLabels}>
226
+ <Combobox.Input aria-label="Fruit" />
227
+ <FruitList />
228
+ </Combobox.Root>
229
+ ),
230
+ play: async ({canvas, userEvent}) => {
231
+ const input = canvas.getByRole('combobox')
232
+ input.focus()
233
+ await waitFor(() => expect(optionCount()).toBe(fruits.length))
234
+ await expect(screen.getByRole('option', {name: 'Cherry'})).toHaveAttribute(
235
+ 'aria-selected',
236
+ 'true',
237
+ )
238
+ await expect(input).toHaveAttribute('aria-activedescendant')
239
+ // ArrowDown on the unfiltered list reaches every option.
240
+ for (let step = 0; step < fruits.length - 3; step++) await userEvent.keyboard('{ArrowDown}')
241
+ await expect(input.getAttribute('aria-activedescendant')).toBe(
242
+ screen.getByRole('option', {name: 'Honeydew'}).id,
243
+ )
244
+ // Open then close without typing keeps the value and its label.
245
+ await userEvent.keyboard('{Escape}')
246
+ await waitFor(() => expect(optionCount()).toBe(0))
247
+ await expect(input).toHaveValue('Cherry')
248
+ },
249
+ }
250
+
251
+ export const PointerClickThenType: Story = {
252
+ tags: TEST_ONLY,
253
+ render: () => (
254
+ <Combobox.Root defaultValue="cherry" initialLabels={fruitLabels}>
255
+ <Combobox.Input aria-label="Fruit" />
256
+ <FruitList />
257
+ </Combobox.Root>
258
+ ),
259
+ play: async ({canvas, userEvent}) => {
260
+ const input = canvas.getByRole('combobox')
261
+ await userEvent.click(input)
262
+ await waitFor(() => expect(optionCount()).toBe(fruits.length))
263
+ await userEvent.keyboard('b')
264
+ await expect(input).toHaveValue('b')
265
+ await waitFor(() => expect(screen.getAllByRole('option').length).toBeLessThan(fruits.length))
266
+ await expect(screen.getByRole('option', {name: 'Banana'})).toBeInTheDocument()
267
+ },
268
+ }
269
+
270
+ const languages = Array.from({length: 120}, (_, i) => `Language ${String(i + 1).padStart(3, '0')}`)
271
+ const languageLabels = Object.fromEntries(languages.map((name) => [name.toLowerCase(), name]))
272
+
273
+ /**
274
+ * A long list whose chosen option sits near its end (a language picker): the
275
+ * list opens with every option, the chosen one highlighted and scrolled into
276
+ * view, and typing narrows it down to `Empty`.
277
+ */
278
+ export const LongListChosenNearTheEnd: Story = {
279
+ render: () => (
280
+ <Combobox.Root defaultValue="language 110" initialLabels={languageLabels}>
281
+ <Combobox.Input aria-label="Language" />
282
+ <Combobox.Popup label="Language">
283
+ {languages.map((name) => (
284
+ <Combobox.Item key={name} value={name.toLowerCase()}>
285
+ <Combobox.ItemText>{name}</Combobox.ItemText>
286
+ </Combobox.Item>
287
+ ))}
288
+ <Combobox.Empty>No language found</Combobox.Empty>
289
+ </Combobox.Popup>
290
+ </Combobox.Root>
291
+ ),
292
+ play: async ({canvas, userEvent}) => {
293
+ const input = canvas.getByRole('combobox')
294
+ await userEvent.click(input)
295
+ await waitFor(() => expect(optionCount()).toBe(languages.length))
296
+ const chosen = screen.getByRole('option', {name: 'Language 110'})
297
+ await waitFor(() => expect(input.getAttribute('aria-activedescendant')).toBe(chosen.id))
298
+ const chosenInView = () =>
299
+ waitFor(() => {
300
+ const list = screen.getByRole('listbox').getBoundingClientRect()
301
+ const box = screen.getByRole('option', {name: 'Language 110'}).getBoundingClientRect()
302
+ expect(box.top).toBeGreaterThanOrEqual(list.top)
303
+ expect(box.bottom).toBeLessThanOrEqual(list.bottom)
304
+ })
305
+ await chosenInView()
306
+ await userEvent.keyboard('Language 11')
307
+ await waitFor(() => expect(optionCount()).toBe(10))
308
+ // Typing the label back widens the list again: the chosen option stays in view.
309
+ await userEvent.keyboard('0')
310
+ await waitFor(() => expect(optionCount()).toBe(languages.length))
311
+ await chosenInView()
312
+ await userEvent.keyboard('x')
313
+ await waitFor(() => expect(optionCount()).toBe(0))
314
+ await expect(screen.getByText('No language found')).toBeInTheDocument()
315
+ // The filter hid the highlighted option: the input no longer points at it.
316
+ await waitFor(() => expect(input).not.toHaveAttribute('aria-activedescendant'))
317
+ await userEvent.keyboard('{Escape}')
318
+ await waitFor(() => expect(optionCount()).toBe(0))
319
+ await expect(input).toHaveValue('Language 110')
320
+ },
321
+ }
322
+
323
+ /**
324
+ * The edges of the unfiltered open: typing the chosen label back exactly shows
325
+ * every option again, and clearing the field then closing removes the value.
326
+ */
327
+ export const TypedBackToTheLabelThenCleared: Story = {
328
+ tags: TEST_ONLY,
329
+ render: () => (
330
+ <Combobox.Root defaultValue="cherry" initialLabels={fruitLabels}>
331
+ <Combobox.Input aria-label="Fruit" />
332
+ <FruitList />
333
+ </Combobox.Root>
334
+ ),
335
+ play: async ({canvas, userEvent}) => {
336
+ const input = canvas.getByRole('combobox')
337
+ await userEvent.click(input)
338
+ await userEvent.keyboard('Cherr')
339
+ await waitFor(() => expect(optionCount()).toBe(1))
340
+ await userEvent.keyboard('y')
341
+ await waitFor(() => expect(optionCount()).toBe(fruits.length))
342
+ await userEvent.clear(input)
343
+ await userEvent.keyboard('{Escape}')
344
+ await waitFor(() => expect(optionCount()).toBe(0))
345
+ await expect(input).toHaveValue('')
346
+ input.blur()
347
+ input.focus()
348
+ await waitFor(() => expect(optionCount()).toBe(fruits.length))
349
+ await expect(screen.queryByRole('option', {selected: true})).toBeNull()
350
+ },
351
+ }
352
+
353
+ export const TypedTextSurvivesBlurWithoutValue: Story = {
354
+ tags: TEST_ONLY,
355
+ render: () => (
356
+ <Combobox.Root>
357
+ <Combobox.Input aria-label="Fruit" />
358
+ <FruitList />
359
+ </Combobox.Root>
360
+ ),
361
+ play: async ({canvas, userEvent}) => {
362
+ const input = canvas.getByRole('combobox')
363
+ await userEvent.click(input)
364
+ await userEvent.keyboard('an')
365
+ await userEvent.tab()
366
+ await waitFor(() => expect(optionCount()).toBe(0))
367
+ await userEvent.click(input)
368
+ await waitFor(() => expect(optionCount()).toBeGreaterThan(0))
369
+ await expect(optionCount()).toBeLessThan(fruits.length)
370
+ await expect(input).toHaveValue('an')
371
+ },
372
+ }
373
+
374
+ function OpenChangeDemo({onOpen}: {onOpen: (open: boolean) => void}) {
375
+ const [open, setOpen] = useState(false)
376
+ return (
377
+ <StrictMode>
378
+ <Stack gap="sm">
379
+ <Combobox.Root
380
+ onOpenChange={(next) => {
381
+ setOpen(next)
382
+ onOpen(next)
383
+ }}
384
+ >
385
+ <Combobox.Input aria-label="Fruit" />
386
+ <FruitList />
387
+ </Combobox.Root>
388
+ <Text variant="bodySm" color="muted">
389
+ List {open ? 'open' : 'closed'}
390
+ </Text>
391
+ </Stack>
392
+ </StrictMode>
393
+ )
394
+ }
395
+
396
+ export const OpenChangeFiresOncePerTransition: StoryObj<{onOpen: (open: boolean) => void}> = {
397
+ args: {onOpen: fn()},
398
+ render: (args) => <OpenChangeDemo onOpen={args.onOpen} />,
399
+ play: async ({args, canvas, userEvent}) => {
400
+ const onOpen = args.onOpen as ReturnType<typeof fn>
401
+ const sequence = () => onOpen.mock.calls.map((call: unknown[]) => call[0])
402
+ // React reports a parent update made during render on console.error.
403
+ const consoleError = console.error
404
+ const errors: string[] = []
405
+ console.error = (...parts: unknown[]) => {
406
+ errors.push(parts.map(String).join(' '))
407
+ consoleError(...parts)
408
+ }
409
+ try {
410
+ await runOpenChangeSequence({onOpen, sequence, canvas, userEvent})
411
+ } finally {
412
+ console.error = consoleError
413
+ }
414
+ await expect(
415
+ errors.filter((line) => /Cannot update a component|while rendering/.test(line)),
416
+ ).toEqual([])
417
+ },
418
+ }
419
+
420
+ async function runOpenChangeSequence({
421
+ onOpen,
422
+ sequence,
423
+ canvas,
424
+ userEvent,
425
+ }: {
426
+ onOpen: ReturnType<typeof fn>
427
+ sequence: () => unknown[]
428
+ canvas: {getByRole: (role: string) => HTMLElement}
429
+ userEvent: {
430
+ click: (el: Element) => Promise<void>
431
+ clear: (el: Element) => Promise<void>
432
+ keyboard: (text: string) => Promise<void>
433
+ }
434
+ }) {
435
+ {
436
+ const input = canvas.getByRole('combobox')
437
+ input.focus()
438
+ await waitFor(() => expect(onOpen).toHaveBeenCalledTimes(1))
439
+ await userEvent.keyboard('{Escape}')
440
+ await waitFor(() => expect(onOpen).toHaveBeenCalledTimes(2))
441
+ // A blur while closed does not fire it.
442
+ input.blur()
443
+ await pause(AFTER_BLUR_CLOSE_MS)
444
+ await expect(onOpen).toHaveBeenCalledTimes(2)
445
+ // Focus then blur: one open, one close.
446
+ onOpen.mockClear()
447
+ input.focus()
448
+ await waitFor(() => expect(onOpen).toHaveBeenCalledTimes(1))
449
+ input.blur()
450
+ await waitFor(() => expect(onOpen).toHaveBeenCalledTimes(2))
451
+ await expect(sequence()).toEqual([true, false])
452
+ // A pointer pick closes once, with no close-open-close.
453
+ onOpen.mockClear()
454
+ await userEvent.click(input)
455
+ await userEvent.click(await screen.findByRole('option', {name: 'Fig'}))
456
+ await pause(AFTER_BLUR_CLOSE_MS)
457
+ await expect(sequence()).toEqual([true, false])
458
+ await expect(input).toHaveValue('Fig')
459
+ // An Enter pick whose handler updates parent state.
460
+ onOpen.mockClear()
461
+ await userEvent.clear(input)
462
+ await userEvent.keyboard('gr{ArrowDown}{Enter}')
463
+ await waitFor(() => expect(input).toHaveValue('Grape'))
464
+ await pause(AFTER_BLUR_CLOSE_MS)
465
+ await expect(sequence()).toEqual([true, false])
466
+ }
467
+ }
468
+
469
+ function ControlledInputDemo({onInput}: {onInput: (text: string) => void}) {
470
+ const [text, setText] = useState('Cherry')
471
+ return (
472
+ <Combobox.Root
473
+ defaultValue="cherry"
474
+ initialLabels={fruitLabels}
475
+ inputValue={text}
476
+ onInputChange={(next) => {
477
+ onInput(next)
478
+ setText(next)
479
+ }}
480
+ >
481
+ <Combobox.Input aria-label="Fruit" />
482
+ <FruitList />
483
+ </Combobox.Root>
484
+ )
485
+ }
486
+
487
+ export const ControlledInputValue: StoryObj<{onInput: (text: string) => void}> = {
488
+ args: {onInput: fn()},
489
+ render: (args) => <ControlledInputDemo onInput={args.onInput} />,
490
+ play: async ({args, canvas, userEvent}) => {
491
+ const onInput = args.onInput as ReturnType<typeof fn>
492
+ const input = canvas.getByRole('combobox')
493
+ await userEvent.click(input)
494
+ await waitFor(() => expect(optionCount()).toBe(fruits.length))
495
+ await expect(onInput).not.toHaveBeenCalled()
496
+ await userEvent.click(await screen.findByRole('option', {name: 'Date'}))
497
+ await waitFor(() => expect(onInput).toHaveBeenLastCalledWith('Date'))
498
+ await userEvent.keyboard('{Control>}a{/Control}x')
499
+ await userEvent.tab()
500
+ await waitFor(() => expect(onInput).toHaveBeenLastCalledWith('Date'))
501
+ },
502
+ }
503
+
504
+ export const NamedByAriaLabel: Story = {
505
+ render: () => (
506
+ <Combobox.Root>
507
+ <Combobox.Input aria-label="Favourite fruit" />
508
+ <FruitList />
509
+ </Combobox.Root>
510
+ ),
511
+ play: async ({canvas}) => {
512
+ await expect(canvas.getByRole('combobox', {name: 'Favourite fruit'})).toBeInTheDocument()
513
+ },
514
+ }
515
+
516
+ export const NamedByFieldLabel: Story = {
517
+ render: () => (
518
+ <Field.Root>
519
+ <Field.Label>Pick a fruit</Field.Label>
520
+ <Combobox.Root>
521
+ <Combobox.Input />
522
+ <FruitList />
523
+ </Combobox.Root>
524
+ </Field.Root>
525
+ ),
526
+ play: async ({canvas}) => {
527
+ await expect(canvas.getByRole('combobox', {name: 'Pick a fruit'})).toBeInTheDocument()
528
+ },
529
+ }
530
+
531
+ export const InvalidInsideField: Story = {
532
+ render: () => (
533
+ <Field.Root invalid>
534
+ <Field.Label>Pick a fruit</Field.Label>
535
+ <Combobox.Root>
536
+ <Combobox.Input />
537
+ <FruitList />
538
+ </Combobox.Root>
539
+ <Field.Error>Choose a fruit from the list.</Field.Error>
540
+ </Field.Root>
541
+ ),
542
+ play: async ({canvas}) => {
543
+ const input = canvas.getByRole('combobox', {name: 'Pick a fruit'})
544
+ await expect(input).toHaveAttribute('aria-invalid', 'true')
545
+ await expect(input).toHaveAccessibleDescription('Choose a fruit from the list.')
546
+ },
547
+ }
@@ -6,6 +6,7 @@ import {ComboboxContext, useCombobox} from './ComboboxContext'
6
6
  import {useComboboxRoot} from './useComboboxRoot'
7
7
  import {matchesQuery} from './comboboxState'
8
8
  import {Listbox, getAnchorProps} from '../Listbox/Listbox'
9
+ import {useFieldContext} from '../Field/FieldContext'
9
10
 
10
11
  // --- Root ---
11
12
  interface RootProps {
@@ -15,6 +16,8 @@ interface RootProps {
15
16
  onValueChange?: (value: string | null) => void
16
17
  inputValue?: string
17
18
  onInputChange?: (value: string) => void
19
+ /** Called once each time the list opens or closes. There is no controlled `open`, as on Select. */
20
+ onOpenChange?: (open: boolean) => void
18
21
  initialLabels?: Record<string, string>
19
22
  children: ReactNode
20
23
  }
@@ -26,6 +29,7 @@ function Root({
26
29
  onValueChange,
27
30
  inputValue,
28
31
  onInputChange,
32
+ onOpenChange,
29
33
  initialLabels,
30
34
  children,
31
35
  }: RootProps) {
@@ -35,6 +39,7 @@ function Root({
35
39
  onValueChange,
36
40
  inputValue,
37
41
  onInputChange,
42
+ onOpenChange,
38
43
  initialLabels,
39
44
  })
40
45
 
@@ -49,9 +54,32 @@ function Root({
49
54
  }
50
55
 
51
56
  // --- Input ---
52
- function Input({placeholder, children}: {placeholder?: string; children?: ReactNode}) {
53
- const {open, openPopup, close, inputValue, setInputValue, listboxId, highlightedId, inputRef} =
54
- useCombobox()
57
+ function Input({
58
+ placeholder,
59
+ 'aria-label': ariaLabel,
60
+ children,
61
+ }: {
62
+ placeholder?: string
63
+ /** The input's accessible name; inside a Field.Root the Field.Label names it. */
64
+ 'aria-label'?: string
65
+ children?: ReactNode
66
+ }) {
67
+ const {
68
+ open,
69
+ openPopup,
70
+ inputValue,
71
+ setInputValue,
72
+ onInputFocus,
73
+ onInputBlur,
74
+ listboxId,
75
+ highlightedId,
76
+ inputRef,
77
+ } = useCombobox()
78
+ const fieldCtx = useFieldContext()
79
+ const describedBy = fieldCtx
80
+ ? `${fieldCtx.descriptionId} ${fieldCtx.invalid ? fieldCtx.errorId : ''}`.trim()
81
+ : undefined
82
+ const pointerFocusRef = useRef(false)
55
83
  const localRef = useRef<HTMLInputElement>(null)
56
84
  const [focused, setFocused] = useState(false)
57
85
  const anchor = getAnchorProps({id: listboxId, open, highlightedId})
@@ -64,10 +92,14 @@ function Input({placeholder, children}: {placeholder?: string; children?: ReactN
64
92
  <html.div style={[styles.inputWrapper, focused && styles.inputWrapperFocused]}>
65
93
  <html.input
66
94
  ref={localRef}
95
+ id={fieldCtx?.controlId}
67
96
  type="text"
68
97
  role={'combobox' as 'listbox'}
69
98
  value={inputValue}
70
99
  placeholder={placeholder}
100
+ aria-label={ariaLabel}
101
+ aria-describedby={describedBy || undefined}
102
+ aria-invalid={fieldCtx?.invalid || undefined}
71
103
  aria-expanded={anchor['aria-expanded']}
72
104
  aria-haspopup="listbox"
73
105
  aria-controls={anchor['aria-controls']}
@@ -75,14 +107,22 @@ function Input({placeholder, children}: {placeholder?: string; children?: ReactN
75
107
  aria-autocomplete={'list' as 'none'}
76
108
  autoComplete="off"
77
109
  style={styles.input}
110
+ onMouseDown={() => {
111
+ pointerFocusRef.current = document.activeElement !== localRef.current
112
+ }}
113
+ onMouseUp={() => {
114
+ // The pointer that focused the field would collapse the selection.
115
+ if (pointerFocusRef.current) localRef.current?.select()
116
+ pointerFocusRef.current = false
117
+ }}
78
118
  onFocus={() => {
79
119
  setFocused(true)
80
- openPopup()
120
+ localRef.current?.select()
121
+ onInputFocus()
81
122
  }}
82
123
  onBlur={() => {
83
124
  setFocused(false)
84
- // Delay close to allow item click to register
85
- setTimeout(close, 150)
125
+ onInputBlur()
86
126
  }}
87
127
  onChange={(e: any) => {
88
128
  setInputValue(e.target.value)
@@ -176,7 +216,7 @@ interface ItemProps {
176
216
  }
177
217
 
178
218
  function Item({value: itemValue, description, leading, children}: ItemProps) {
179
- const {value: selectedValue, inputValue, labels, registerLabel, registerItem} = useCombobox()
219
+ const {value: selectedValue, query, labels, registerLabel, registerItem} = useCombobox()
180
220
  const id = useId()
181
221
  const textId = useId()
182
222
  const descriptionId = useId()
@@ -187,7 +227,7 @@ function Item({value: itemValue, description, leading, children}: ItemProps) {
187
227
  const hasDescription = description != null
188
228
 
189
229
  // Filter: check if this item matches the input (the label, never the description)
190
- const isVisible = matchesQuery(labels[itemValue] ?? itemValue, inputValue)
230
+ const isVisible = matchesQuery(labels[itemValue] ?? itemValue, query)
191
231
 
192
232
  useEffect(() => {
193
233
  const el = textRef.current
@@ -196,11 +236,14 @@ function Item({value: itemValue, description, leading, children}: ItemProps) {
196
236
  if (text) registerLabel(itemValue, text)
197
237
  }, [itemValue, registerLabel])
198
238
 
239
+ // An option the filter hides unmounts its element, so it registers again when
240
+ // it shows again (`isVisible`): that is also how a pending open highlight
241
+ // settles on it after a filter change.
199
242
  useEffect(() => {
200
243
  const el = ref.current
201
244
  if (!el) return
202
245
  return registerItem(id, itemValue, el)
203
- }, [id, itemValue, registerItem])
246
+ }, [id, itemValue, registerItem, isVisible])
204
247
 
205
248
  // Listbox.Option owns the option element and takes no aria props, so the
206
249
  // name (the label text alone) and the description are set on it here.
@@ -248,13 +291,13 @@ function ItemText({children}: {children: ReactNode}) {
248
291
 
249
292
  // --- Empty ---
250
293
  function Empty({children}: {children: ReactNode}) {
251
- const {open, inputValue, labels} = useCombobox()
294
+ const {open, query, labels} = useCombobox()
252
295
 
253
296
  if (!open) return null
254
297
 
255
298
  // Check if any items are visible
256
299
  const hasVisibleItems =
257
- !inputValue || Object.values(labels).some((label) => matchesQuery(label, inputValue))
300
+ !query || Object.values(labels).some((label) => matchesQuery(label, query))
258
301
 
259
302
  if (hasVisibleItems) return null
260
303