@greenharness/greenrack-ui 7.1.2 → 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.
- package/dist/components/Combobox/Combobox.d.ts +6 -2
- package/dist/components/Combobox/Combobox.d.ts.map +1 -1
- package/dist/components/Combobox/Combobox.stories.d.ts +23 -0
- package/dist/components/Combobox/Combobox.stories.d.ts.map +1 -1
- package/dist/components/Combobox/ComboboxContext.d.ts +4 -0
- package/dist/components/Combobox/ComboboxContext.d.ts.map +1 -1
- package/dist/components/Combobox/comboboxState.d.ts +4 -2
- package/dist/components/Combobox/comboboxState.d.ts.map +1 -1
- package/dist/components/Combobox/useComboboxRoot.d.ts.map +1 -1
- package/dist/index.js +3003 -2983
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/src/components/Combobox/Combobox.meta.ts +1 -1
- package/src/components/Combobox/Combobox.native.tsx +18 -4
- package/src/components/Combobox/Combobox.stories.tsx +355 -2
- package/src/components/Combobox/Combobox.tsx +54 -11
- package/src/components/Combobox/ComboboxContext.ts +4 -0
- package/src/components/Combobox/comboboxState.ts +19 -3
- package/src/components/Combobox/useComboboxRoot.ts +128 -47
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@greenharness/greenrack-ui",
|
|
3
|
-
"version": "7.
|
|
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.
|
|
95
|
+
"@greenharness/greenrack-tokens": "^7.2.0"
|
|
96
96
|
},
|
|
97
97
|
"devDependencies": {
|
|
98
98
|
"@babel/preset-typescript": "^7.28.0",
|
|
@@ -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({
|
|
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({
|
|
53
|
-
|
|
54
|
-
|
|
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
|
-
|
|
120
|
+
localRef.current?.select()
|
|
121
|
+
onInputFocus()
|
|
81
122
|
}}
|
|
82
123
|
onBlur={() => {
|
|
83
124
|
setFocused(false)
|
|
84
|
-
|
|
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,
|
|
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,
|
|
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,
|
|
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
|
-
!
|
|
300
|
+
!query || Object.values(labels).some((label) => matchesQuery(label, query))
|
|
258
301
|
|
|
259
302
|
if (hasVisibleItems) return null
|
|
260
303
|
|
|
@@ -7,7 +7,11 @@ export interface ComboboxContextValue {
|
|
|
7
7
|
value: string | null
|
|
8
8
|
setValue: (value: string) => void
|
|
9
9
|
inputValue: string
|
|
10
|
+
/** What filters the list: empty while the field shows the chosen option's label. */
|
|
11
|
+
query: string
|
|
10
12
|
setInputValue: (value: string) => void
|
|
13
|
+
onInputFocus: () => void
|
|
14
|
+
onInputBlur: () => void
|
|
11
15
|
labels: Record<string, string>
|
|
12
16
|
registerLabel: (value: string, label: string) => void
|
|
13
17
|
listboxId: string
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {useCallback, useEffect, useState} from 'react'
|
|
1
|
+
import {useCallback, useEffect, useRef, useState} from 'react'
|
|
2
2
|
import {useControllableValue} from '../../hooks/useControllableValue'
|
|
3
3
|
|
|
4
4
|
export interface ComboboxStateOptions {
|
|
@@ -7,6 +7,8 @@ export interface ComboboxStateOptions {
|
|
|
7
7
|
onValueChange?: (value: string | null) => void
|
|
8
8
|
inputValue?: string
|
|
9
9
|
onInputChange?: (value: string) => void
|
|
10
|
+
/** Called once per real open/close transition, never inside a state updater. */
|
|
11
|
+
onOpenChange?: (open: boolean) => void
|
|
10
12
|
initialLabels?: Record<string, string>
|
|
11
13
|
}
|
|
12
14
|
|
|
@@ -28,6 +30,7 @@ export function useComboboxState({
|
|
|
28
30
|
onValueChange,
|
|
29
31
|
inputValue: controlledInputValue,
|
|
30
32
|
onInputChange,
|
|
33
|
+
onOpenChange,
|
|
31
34
|
initialLabels,
|
|
32
35
|
}: ComboboxStateOptions) {
|
|
33
36
|
const [value, setValue] = useControllableValue<string | null>(
|
|
@@ -51,7 +54,20 @@ export function useComboboxState({
|
|
|
51
54
|
[controlledInputValue, onInputChange],
|
|
52
55
|
)
|
|
53
56
|
|
|
54
|
-
const [open,
|
|
57
|
+
const [open, setOpenState] = useState(false)
|
|
58
|
+
// The latest open, written before the state setter so two calls in one
|
|
59
|
+
// event see each other; onOpenChange fires only when it changes.
|
|
60
|
+
const openRef = useRef(false)
|
|
61
|
+
const onOpenChangeRef = useRef(onOpenChange)
|
|
62
|
+
useEffect(() => {
|
|
63
|
+
onOpenChangeRef.current = onOpenChange
|
|
64
|
+
})
|
|
65
|
+
const setOpen = useCallback((next: boolean) => {
|
|
66
|
+
if (openRef.current === next) return
|
|
67
|
+
openRef.current = next
|
|
68
|
+
setOpenState(next)
|
|
69
|
+
onOpenChangeRef.current?.(next)
|
|
70
|
+
}, [])
|
|
55
71
|
const [labels, setLabels] = useState<Record<string, string>>(initialLabels ?? {})
|
|
56
72
|
|
|
57
73
|
const registerLabel = useCallback((v: string, label: string) => {
|
|
@@ -65,7 +81,7 @@ export function useComboboxState({
|
|
|
65
81
|
setInputValue(labels[itemValue] ?? itemValue)
|
|
66
82
|
setOpen(false)
|
|
67
83
|
},
|
|
68
|
-
[setValue, labels, setInputValue],
|
|
84
|
+
[setValue, labels, setInputValue, setOpen],
|
|
69
85
|
)
|
|
70
86
|
|
|
71
87
|
// Reconcile input text with the committed value once the popup closes.
|