An open source design system that's fully customizable and agent ready
TypeScript
feat(useCombobox): a combobox over a text field the caller renders (#7732)
Christopher Chedeau6162917e82b8
diff --git a/.changeset/use-combobox-caller-field.md b/.changeset/use-combobox-caller-field.mdnew file mode 100644index 0000000000..1126db7fe3--- /dev/null+++ b/.changeset/use-combobox-caller-field.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[feat] `useCombobox` (from `@astryxdesign/core/Selector`) now builds a combobox over a single-line text field you render yourself, such as a search field whose results replace a page section or an “add people” field in a dialog. Spread `getFieldProps` on your `input`, `getListboxProps` on your listbox wherever it renders, and `getOptionProps` on each option. Focus stays in the field; the field and the list carry the combobox roles and relationships; while the list shows, the arrows move the active option, Enter picks it and Escape hides the list without closing a surrounding dialog; while it is hidden, ArrowDown reopens it; while an input method is composing, keys reach the field untouched; a pointer picks without taking focus. Announce each new result count yourself through `useAnnounce`, with the words the field shows when nothing matches. Options may be any type with a string `value`. Existing options, return fields and `onKeyDown` behave as before.++@vjeuxdiff --git a/apps/storybook/stories/useCombobox.stories.tsx b/apps/storybook/stories/useCombobox.stories.tsxnew file mode 100644index 0000000000..76abd36dae--- /dev/null+++ b/apps/storybook/stories/useCombobox.stories.tsx@@ -0,0 +1,445 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file useCombobox.stories.tsx+ * @input Uses useCombobox from @astryxdesign/core/Selector, useAnnounce,+ * usePopover, Dialog, Layout, and Button+ * @output Comboboxes over single-line fields the story renders itself: a+ * search field whose results replace a page section, an assignee field+ * whose matches open in a layer, and a field in a dialog; each shows an+ * empty message when nothing matches and announces each new result count+ * through useAnnounce+ * @position Storybook stories for useCombobox's field props;+ * ComboboxField.a11y.chromium.spec.ts drives these stories in Chromium+ */++import type {Meta, StoryObj} from '@storybook/react';+import {useId, useState} from 'react';+import * as stylex from '@stylexjs/stylex';+import {useCombobox} from '@astryxdesign/core/Selector';+import {useAnnounce} from '@astryxdesign/core/hooks';+import {usePopover} from '@astryxdesign/core/Popover';+import {Button} from '@astryxdesign/core/Button';+import {Dialog, DialogHeader} from '@astryxdesign/core/Dialog';+import {Layout, LayoutContent} from '@astryxdesign/core/Layout';+import {+ colorVars,+ radiusVars,+ spacingVars,+} from '@astryxdesign/core/theme/tokens.stylex';++const meta: Meta = {+ title: 'Core/Hooks/useCombobox',+ parameters: {+ docs: {+ description: {+ component:+ 'useCombobox over a single-line text field the product renders itself. The story owns the field, the rows and where the list renders; the hook owns the roles, the keys and the pointer model. Each story announces each new query’s result count through useAnnounce, as AST-075 leaves to the caller. Focus never leaves the field: arrows move the active option, Enter picks it, Escape hides the list.',+ },+ },+ },+};++export default meta;+type Story = StoryObj;++type Option = {value: string; label: string; disabled?: boolean};++const PEOPLE: Option[] = [+ {value: 'ada', label: 'Ada Lovelace'},+ {value: 'alan', label: 'Alan Turing'},+ {value: 'barbara', label: 'Barbara Liskov'},+ {value: 'edsger', label: 'Edsger Dijkstra'},+ {value: 'grace', label: 'Grace Hopper (away)', disabled: true},+ {value: 'katherine', label: 'Katherine Johnson'},+ {value: 'margaret', label: 'Margaret Hamilton'},+];++const SETTINGS: Option[] = [+ {value: 'notifications', label: 'Notifications'},+ {value: 'notification-sound', label: 'Notification sound'},+ {value: 'appearance', label: 'Appearance'},+ {value: 'language', label: 'Language and region'},+ {value: 'shortcuts', label: 'Keyboard shortcuts'},+ {value: 'password', label: 'Password'},+ {value: 'two-factor', label: 'Two-factor authentication'},+];++function matching(options: Option[], query: string): Option[] {+ const needle = query.trim().toLowerCase();+ return options.filter(option => option.label.toLowerCase().includes(needle));+}++function firstEnabled(options: Option[]): number {+ return options.findIndex(option => !option.disabled);+}++/** The words announced for a new query: its count, or the words shown for none. */+function resultWords(count: number, none: string): string {+ return count === 0 ? none : count === 1 ? '1 result' : `${count} results`;+}++const styles = stylex.create({+ stack: {+ display: 'flex',+ flexDirection: 'column',+ gap: spacingVars['--spacing-2'],+ width: 360,+ fontFamily: 'inherit',+ },+ field: {+ boxSizing: 'border-box',+ width: '100%',+ minHeight: 36,+ paddingBlock: spacingVars['--spacing-2'],+ paddingInline: spacingVars['--spacing-3'],+ borderWidth: 1,+ borderStyle: 'solid',+ borderColor: colorVars['--color-border-emphasized'],+ borderRadius: radiusVars['--radius-element'],+ backgroundColor: colorVars['--color-background-surface'],+ color: colorVars['--color-text-primary'],+ font: 'inherit',+ },+ listbox: {+ boxSizing: 'border-box',+ display: 'flex',+ flexDirection: 'column',+ maxHeight: 224,+ overflowY: 'auto',+ padding: spacingVars['--spacing-1'],+ borderWidth: 1,+ borderStyle: 'solid',+ borderColor: colorVars['--color-border'],+ borderRadius: radiusVars['--radius-container'],+ backgroundColor: colorVars['--color-background-popover'],+ },+ option: {+ paddingBlock: spacingVars['--spacing-2'],+ paddingInline: spacingVars['--spacing-3'],+ borderRadius: radiusVars['--radius-element'],+ color: colorVars['--color-text-primary'],+ cursor: 'pointer',+ userSelect: 'none',+ },+ active: {+ backgroundColor: colorVars['--color-overlay-hover'],+ },+ disabled: {+ color: colorVars['--color-text-disabled'],+ cursor: 'default',+ },+ layerListbox: {+ minWidth: 240,+ borderStyle: 'none',+ },+ muted: {+ margin: 0,+ color: colorVars['--color-text-secondary'],+ },+});++type Combobox = ReturnType<typeof useCombobox<Option>>;++/** The caller's rows: plain elements carrying the hook's option props. */+function Rows({combobox, options}: {combobox: Combobox; options: Option[]}) {+ return options.map((option, index) => (+ <div+ key={option.value}+ {...combobox.getOptionProps(index)}+ {...stylex.props(+ styles.option,+ index === combobox.highlightedIndex && styles.active,+ option.disabled && styles.disabled,+ )}>+ {option.label}+ </div>+ ));+}++// ---------------------------------------------------------------------------+// A search field: an input whose results replace a page section in flow.+// ---------------------------------------------------------------------------++function SearchFieldExample() {+ const listboxId = useId();+ const announce = useAnnounce();+ const [query, setQuery] = useState('');+ const [isOpen, setIsOpen] = useState(false);+ const [picked, setPicked] = useState<string>();+ const options = query.trim() === '' ? [] : matching(SETTINGS, query);+ const isShown = isOpen && query.trim() !== '';++ const combobox = useCombobox({+ selectableItems: options,+ isOpen: isShown,+ onOpen: () => {+ if (query.trim() === '') {+ return false;+ }+ setIsOpen(true);+ },+ onClose: () => setIsOpen(false),+ onSelect: value => {+ setPicked(SETTINGS.find(setting => setting.value === value)?.label);+ setQuery('');+ },+ listboxId,+ });++ return (+ <div {...stylex.props(styles.stack)}>+ <input+ aria-label="Search settings"+ type="text"+ value={query}+ placeholder="Search settings"+ onChange={event => {+ const next = event.currentTarget.value;+ setQuery(next);+ setIsOpen(true);+ // The results answer a new query, so nothing is active until an+ // arrow or the pointer picks a row; Enter stays the field's.+ combobox.setHighlightedIndex(-1);+ // The caller announces each new query's count (AST-075 FR7, DEC-2),+ // with the words it shows for none.+ if (next.trim() !== '' && next.trim() !== query.trim()) {+ const count = matching(SETTINGS, next).length;+ announce(resultWords(count, 'No settings match'));+ }+ }}+ onBlur={() => setIsOpen(false)}+ {...combobox.getFieldProps()}+ {...stylex.props(styles.field)}+ />+ {isShown ? (+ options.length > 0 ? (+ <div+ aria-label="Settings"+ {...combobox.getListboxProps()}+ {...stylex.props(styles.listbox)}>+ <Rows combobox={combobox} options={options} />+ </div>+ ) : (+ <p {...stylex.props(styles.muted)}>No settings match</p>+ )+ ) : (+ <p {...stylex.props(styles.muted)}>+ {picked == null+ ? 'Recent: Notifications, Appearance'+ : `Opened ${picked}`}+ </p>+ )}+ </div>+ );+}++/**+ * A single-line search field whose results replace a page section, in the+ * page's flow rather than a layer. ArrowDown brings back hidden results; a+ * press on a result picks it while focus stays in the field.+ */+export const SearchField: Story = {+ render: () => <SearchFieldExample />,+};++// ---------------------------------------------------------------------------+// An assignee field: an input whose matches open in a layer.+// ---------------------------------------------------------------------------++function AssigneeFieldExample() {+ const listboxId = useId();+ const announce = useAnnounce();+ const [query, setQuery] = useState('');+ const [assignee, setAssignee] = useState<string>();+ const options = query.trim() === '' ? [] : matching(PEOPLE, query);+ const popover = usePopover({+ hasLightDismiss: true,+ hasCloseButton: false,+ hasAutoFocus: false,+ role: 'none',+ });+ const isShown = popover.isOpen && query.trim() !== '';++ const combobox = useCombobox({+ selectableItems: options,+ isOpen: isShown,+ onOpen: () => {+ if (query.trim() === '') {+ return false;+ }+ popover.show();+ },+ onClose: () => popover.hide(),+ onSelect: value => {+ setAssignee(PEOPLE.find(person => person.value === value)?.label);+ setQuery('');+ popover.hide();+ },+ listboxId,+ });++ return (+ <div {...stylex.props(styles.stack)}>+ <input+ ref={popover.triggerRef}+ aria-label="Assignee"+ type="text"+ value={query}+ placeholder="Assign to"+ onChange={event => {+ const next = event.currentTarget.value;+ setQuery(next);+ if (next.trim() === '') {+ popover.hide();+ return;+ }+ popover.show();+ const matches = matching(PEOPLE, next);+ // A new query makes its first match active, so Enter picks it.+ combobox.setHighlightedIndex(firstEnabled(matches));+ if (next.trim() !== query.trim()) {+ announce(resultWords(matches.length, 'No one matches'));+ }+ }}+ {...combobox.getFieldProps()}+ {...stylex.props(styles.field)}+ />+ {popover.render(+ options.length > 0 ? (+ <div+ aria-label="People"+ {...combobox.getListboxProps()}+ {...stylex.props(styles.listbox, styles.layerListbox)}>+ <Rows combobox={combobox} options={options} />+ </div>+ ) : (+ <p {...stylex.props(styles.muted)}>No one matches</p>+ ),+ )}+ <p {...stylex.props(styles.muted)}>+ {assignee == null ? 'Unassigned' : `Assigned to ${assignee}`}+ </p>+ </div>+ );+}++/**+ * An input whose matches open in a layer anchored to it. Focus stays in the+ * field: the arrows move between matches, Enter picks the active one, and+ * Escape hides the layer.+ */+export const AssigneeField: Story = {+ render: () => <AssigneeFieldExample />,+};++// ---------------------------------------------------------------------------+// A field inside a dialog: Escape hides the list before it closes the dialog.+// ---------------------------------------------------------------------------++/**+ * The dialog's field and its list, rendered inside the Dialog. An announcement+ * follows where useAnnounce is called, so the count reaches the dialog's own+ * live region.+ */+function SharePeopleField() {+ const listboxId = useId();+ const announce = useAnnounce();+ const [query, setQuery] = useState('');+ const [isOpen, setIsOpen] = useState(false);+ const [shared, setShared] = useState<string[]>([]);+ const options = query.trim() === '' ? [] : matching(PEOPLE, query);+ const isShown = isOpen && query.trim() !== '';++ const combobox = useCombobox({+ selectableItems: options,+ isOpen: isShown,+ onOpen: () => {+ if (query.trim() === '') {+ return false;+ }+ setIsOpen(true);+ },+ onClose: () => setIsOpen(false),+ onSelect: value => {+ const person = PEOPLE.find(candidate => candidate.value === value);+ if (person != null) {+ setShared([...shared, person.label]);+ }+ setQuery('');+ },+ listboxId,+ });++ return (+ <div {...stylex.props(styles.stack)}>+ <input+ aria-label="Add people"+ type="text"+ value={query}+ onChange={event => {+ const next = event.currentTarget.value;+ setQuery(next);+ setIsOpen(true);+ const matches = matching(PEOPLE, next);+ combobox.setHighlightedIndex(firstEnabled(matches));+ if (next.trim() !== '' && next.trim() !== query.trim()) {+ announce(resultWords(matches.length, 'No one matches'));+ }+ }}+ {...combobox.getFieldProps()}+ {...stylex.props(styles.field)}+ />+ {isShown ? (+ options.length > 0 ? (+ <div+ aria-label="People"+ {...combobox.getListboxProps()}+ {...stylex.props(styles.listbox)}>+ <Rows combobox={combobox} options={options} />+ </div>+ ) : (+ <p {...stylex.props(styles.muted)}>No one matches</p>+ )+ ) : null}+ <p {...stylex.props(styles.muted)}>+ {shared.length > 0+ ? `Shared with ${shared.join(', ')}`+ : 'Not shared yet'}+ </p>+ </div>+ );+}++function InDialogExample() {+ const [isDialogOpen, setIsDialogOpen] = useState(true);++ return (+ <>+ <Button+ label="Share"+ variant="secondary"+ onClick={() => setIsDialogOpen(true)}+ />+ <Dialog isOpen={isDialogOpen} onOpenChange={setIsDialogOpen}>+ <Layout+ header={<DialogHeader title="Share" onOpenChange={setIsDialogOpen} />}+ content={+ <LayoutContent>+ <SharePeopleField />+ </LayoutContent>+ }+ />+ </Dialog>+ </>+ );+}++/**+ * A field inside a dialog, its matches listed in the dialog's flow and an+ * empty message shown when nothing matches. With either shown, the first+ * Escape hides it and the dialog stays; the next Escape closes the dialog.+ */+export const InDialog: Story = {+ render: () => <InDialogExample />,+};diff --git a/docs/specs/AST-075-owned-field-combobox/spec.md b/docs/specs/AST-075-owned-field-combobox/spec.mdindex a197f61a7e..14ea25be2e 100644--- a/docs/specs/AST-075-owned-field-combobox/spec.md+++ b/docs/specs/AST-075-owned-field-combobox/spec.md@@ -104,16 +104,22 @@ the behavior from hooks; every such field behaves and announces the same way.contract carries the same obligations to a field the caller renders.- `component:ChatComposerInput` exposes combobox semantics for its trigger menuinside its own contenteditable field only, through an internal hook.-- `useCombobox` (exported from `@astryxdesign/core/Selector`) already tracks the- active option, opens and closes, and handles the keys for Selector and- CommandPalette; `useMultiCombobox` (exported from- `@astryxdesign/core/MultiSelector`) does the same for MultiSelector. Both take- their own component's option type, leave the ARIA wiring to the caller, and do- not yet guard keys during an input-method composition (FR5).+- `useCombobox` (exported from `@astryxdesign/core/Selector`) tracks the active+ option, opens and closes, and handles the keys for Selector and CommandPalette.+ For a single-line `input` the caller renders, over any option type with a+ string `value`, its `getFieldProps`, `getListboxProps`, and `getOptionProps`+ carry FR1–FR6. It does not yet take a multi-line field (DEC-3), and the+ caller announces the result count through `useAnnounce` (FR7), as DEC-2+ describes.+- `useMultiCombobox` (exported from `@astryxdesign/core/MultiSelector`) does the+ same for MultiSelector's own control. It takes MultiSelector's option type,+ leaves the ARIA wiring to the caller, and does not guard keys during an+ input-method composition.- `useTypeahead` already ignores keys during an input-method composition, and`useAnnounce` is the shared announcer FR7 names.- Both combobox hooks ship hook docs that `astryx hook` and `astryx search`- return, but neither yet names the requirements above it satisfies (FR8).+ return. The `useCombobox` doc names the requirements above it satisfies (FR8);+ the `useMultiCombobox` doc covers no caller-rendered field and names none.## Verificationdiff --git a/packages/cli/api/hook/detail/detail.test.mjs b/packages/cli/api/hook/detail/detail.test.mjsindex 2f75915d8a..00ca8854ea 100644--- a/packages/cli/api/hook/detail/detail.test.mjs+++ b/packages/cli/api/hook/detail/detail.test.mjs@@ -27,6 +27,17 @@ describe('hook.detail leaf', () => {expect(Array.isArray(res.data.returns)).toBe(true);}, SLOW);+ it('resolves useCombobox from the Selector entry point with its field props and the requirements it names', async () => {+ const res = await detail('useCombobox', {cwd: REPO});+ expect(res.data.importPath).toBe('@astryxdesign/core/Selector');+ expect(res.data.returns.map(entry => entry.name)).toEqual(+ expect.arrayContaining(['getFieldProps', 'getListboxProps', 'getOptionProps']),+ );+ expect(res.data.usage.accessibility?.map(entry => entry.requirement)).toEqual(+ [1, 2, 3, 4, 5, 6, 7].map(n => `AST-075 FR${n}`),+ );+ }, SLOW);+it('throws ERR_UNKNOWN_HOOK with fuzzy suggestions for an unknown hook', async () => {let err;try {diff --git a/packages/cli/test/__golden__/no-icon-set/search-icon-set.json b/packages/cli/test/__golden__/no-icon-set/search-icon-set.jsonindex e81065eb2b..b184f0ba67 100644--- a/packages/cli/test/__golden__/no-icon-set/search-icon-set.json+++ b/packages/cli/test/__golden__/no-icon-set/search-icon-set.json@@ -3,7 +3,7 @@"type": "search","data": {"query": "icon set",- "matchCount": 370,+ "matchCount": 369,"results": [{"domain": "doc",diff --git a/packages/cli/test/__golden__/no-icon-set/search-icon-set.txt b/packages/cli/test/__golden__/no-icon-set/search-icon-set.txtindex fb62b92896..72beb71e54 100644--- a/packages/cli/test/__golden__/no-icon-set/search-icon-set.txt+++ b/packages/cli/test/__golden__/no-icon-set/search-icon-set.txt@@ -1,4 +1,4 @@-Results for "icon set" (20 of 370)+Results for "icon set" (20 of 369)name: authoring/building-blocks/templates/build-the-template/template-assets/template-iconssection: use-astryx-icondomain: docdiff --git a/packages/cli/test/__golden__/no-icon-set/search-search.json b/packages/cli/test/__golden__/no-icon-set/search-search.jsonindex 2573fa1bb2..c3e974f297 100644--- a/packages/cli/test/__golden__/no-icon-set/search-search.json+++ b/packages/cli/test/__golden__/no-icon-set/search-search.json@@ -3,7 +3,7 @@"type": "search","data": {"query": "search",- "matchCount": 113,+ "matchCount": 114,"results": [{"domain": "doc",diff --git a/packages/cli/test/__golden__/no-icon-set/search-search.txt b/packages/cli/test/__golden__/no-icon-set/search-search.txtindex abe619e828..180a04f4d9 100644--- a/packages/cli/test/__golden__/no-icon-set/search-search.txt+++ b/packages/cli/test/__golden__/no-icon-set/search-search.txt@@ -1,4 +1,4 @@-Results for "search" (20 of 113)+Results for "search" (20 of 114)name: cli/api/functions/searchdomain: docpackage: @astryxdesign/clidiff --git a/packages/core/src/Selector/__tests__/ComboboxField.a11y.chromium.spec.ts b/packages/core/src/Selector/__tests__/ComboboxField.a11y.chromium.spec.tsnew file mode 100644index 0000000000..9094e044a4--- /dev/null+++ b/packages/core/src/Selector/__tests__/ComboboxField.a11y.chromium.spec.ts@@ -0,0 +1,458 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file ComboboxField.a11y.chromium.spec.ts+ * @input The `Core/Hooks/useCombobox` stories in a built Storybook, the+ * reusable Combobox contract, axe, and real keyboard and pointer input+ * @output Chromium proof that a combobox over a field the story renders itself+ * keeps focus in the field, exposes its roles and relationships, and takes+ * the keys and presses spec:AST-075 assigns to it+ * @position Run with `pnpm test:a11y-contract`. The unit suite in+ * useCombobox.test.tsx covers the same requirements without an engine.+ */++import AxeBuilder from '@axe-core/playwright';+import {expect, test, type Locator, type Page} from '@playwright/test';+import {+ COMBOBOX_PATTERN,+ blockingResults,+ checkAccessibilitySpec,+ formatFailures,+ type ComboboxStateFacts,+} from '@astryxdesign/a11y-spec';+import {createChromiumHarness} from '@astryxdesign/a11y-spec/chromium';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';++let storybook: StaticServer;++test.beforeAll(async () => {+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});++test.afterAll(async () => {+ await storybook?.close();+});++const STORY = {+ search: 'core-hooks-usecombobox--search-field',+ layer: 'core-hooks-usecombobox--assignee-field',+ dialog: 'core-hooks-usecombobox--in-dialog',+} as const;++async function openStory(page: Page, story: string): Promise<void> {+ await page.goto(+ `${storybook.origin}/iframe.html?id=${story}&viewMode=story`,+ {waitUntil: 'load'},+ );+}++/** Whether DOM focus is on exactly this element. */+async function hasFocus(locator: Locator): Promise<boolean> {+ return locator.evaluate(el => el === el.ownerDocument.activeElement);+}++/** The id the field names as its active option, which must be rendered. */+async function activeOptionName(page: Page, field: Locator): Promise<string> {+ const id = await field.getAttribute('aria-activedescendant');+ expect(id).not.toBeNull();+ const option = page.locator(`[id="${id}"]`);+ await expect(option).toHaveAttribute('role', 'option');+ await expect(option).toHaveAttribute('aria-selected', 'true');+ return (await option.textContent()) ?? '';+}++const AXE_DISABLED_RULES = [+ // A story is a fragment, not a page.+ 'landmark-one-main',+ 'page-has-heading-one',+ 'region',+ // A long list scrolls without a Tab stop of its own by design: focus stays+ // in the field, whose arrows reach every option and scroll it into view.+ 'scrollable-region-focusable',+];++async function axeViolations(page: Page): Promise<string[]> {+ const results = await new AxeBuilder({page})+ .disableRules(AXE_DISABLED_RULES)+ .analyze();+ return results.violations.map(+ violation =>+ `${violation.id}: ${violation.nodes.map(node => node.target.join(' ')).join(', ')}`,+ );+}++const closedFacts: ComboboxStateFacts = {+ name: '',+ expanded: false,+ popupRole: 'listbox',+ popupVisible: false,+ activeDescendant: false,+ readOnly: false,+ busy: false,+ inertUnderOwnModal: false,+};++interface Scenario {+ readonly id: string;+ readonly story: string;+ readonly name: string;+ readonly open: boolean;+ /** Puts the story in the state, starting from a focused field. */+ readonly arrange: (page: Page, field: Locator) => Promise<void>;+}++const SCENARIOS: ReadonlyArray<Scenario> = [+ {+ id: 'input-hidden',+ story: STORY.search,+ name: 'Search settings',+ open: false,+ arrange: async () => {},+ },+ {+ id: 'input-shown-in-flow',+ story: STORY.search,+ name: 'Search settings',+ open: true,+ arrange: async page => {+ await page.keyboard.type('no');+ await page.keyboard.press('ArrowDown');+ },+ },+ {+ id: 'input-shown-in-layer',+ story: STORY.layer,+ name: 'Assignee',+ open: true,+ arrange: async page => {+ await page.keyboard.type('ar');+ },+ },+ {+ id: 'input-shown-in-dialog',+ story: STORY.dialog,+ name: 'Add people',+ open: true,+ arrange: async page => {+ await page.keyboard.type('a');+ },+ },+];++for (const scenario of SCENARIOS) {+ test(`Combobox contract over a caller-rendered field — ${scenario.id}`, async ({+ page,+ }) => {+ await openStory(page, scenario.story);+ const field = page.getByRole('combobox', {name: scenario.name});+ await field.click();+ await scenario.arrange(page, field);+ const listbox = page.getByRole('listbox');+ if (scenario.open) {+ await expect(listbox).toBeVisible();+ } else {+ await expect(listbox).toHaveCount(0);+ }++ const related: Record<string, Locator> = {};+ if (scenario.open) {+ related.popup = listbox;+ const id = await field.getAttribute('aria-activedescendant');+ expect(id).not.toBeNull();+ related['active-descendant'] = page.locator(`[id="${id}"]`);+ }+ const cdp = await page.context().newCDPSession(page);+ const run = await checkAccessibilitySpec({+ spec: COMBOBOX_PATTERN,+ binding: 'useCombobox.field',+ state: scenario.id,+ facts: {+ ...closedFacts,+ name: scenario.name,+ expanded: scenario.open,+ popupVisible: scenario.open,+ activeDescendant: scenario.open,+ },+ mount: async () =>+ createChromiumHarness({page, cdp, subject: field, related}),+ });+ expect(formatFailures(blockingResults([run]))).toBe('');+ expect(+ run.results+ .filter(result => result.status === 'unrun')+ .map(result => `${result.expectation}: ${result.detail ?? ''}`),+ ).toEqual([]);+ // Arranging the state never moved focus out of the field (FR1).+ expect(await hasFocus(field)).toBe(true);+ expect(await axeViolations(page)).toEqual([]);+ });+}++test('arrows move the active option and Enter picks it, with focus kept in the field', async ({+ page,+}) => {+ await openStory(page, STORY.search);+ const field = page.getByRole('combobox', {name: 'Search settings'});+ await field.click();+ await page.keyboard.type('no');+ await expect(page.getByRole('option')).toHaveText([+ 'Notifications',+ 'Notification sound',+ ]);+ // A new query activates nothing, so Enter would stay the field's.+ await expect(field).not.toHaveAttribute('aria-activedescendant');++ await page.keyboard.press('ArrowDown');+ expect(await activeOptionName(page, field)).toBe('Notifications');+ await page.keyboard.press('ArrowDown');+ expect(await activeOptionName(page, field)).toBe('Notification sound');+ await page.keyboard.press('ArrowDown');+ expect(await activeOptionName(page, field)).toBe('Notifications');+ await page.keyboard.press('ArrowUp');+ expect(await activeOptionName(page, field)).toBe('Notification sound');+ expect(await hasFocus(field)).toBe(true);++ await page.keyboard.press('Enter');+ await expect(page.getByRole('listbox')).toHaveCount(0);+ await expect(page.getByText('Opened Notification sound')).toBeVisible();+ await expect(field).toHaveAttribute('aria-expanded', 'false');+ expect(await hasFocus(field)).toBe(true);+});++test('ArrowDown brings back a hidden list in a single-line field', async ({+ page,+}) => {+ await openStory(page, STORY.search);+ const field = page.getByRole('combobox', {name: 'Search settings'});+ await field.click();+ await page.keyboard.type('pass');+ await expect(page.getByRole('listbox')).toBeVisible();+ await page.keyboard.press('Escape');+ await expect(page.getByRole('listbox')).toHaveCount(0);+ await expect(field).toHaveValue('pass');++ await page.keyboard.press('ArrowDown');+ await expect(page.getByRole('listbox')).toBeVisible();+ expect(await activeOptionName(page, field)).toBe('Password');+});++test('Escape hides the list before it closes the dialog around the field', async ({+ page,+}) => {+ await openStory(page, STORY.dialog);+ const dialog = page.getByRole('dialog', {name: 'Share'});+ await expect(dialog).toBeVisible();+ const field = page.getByRole('combobox', {name: 'Add people'});+ await field.click();+ await page.keyboard.type('al');+ await expect(page.getByRole('listbox')).toBeVisible();++ await page.keyboard.press('Escape');+ await expect(page.getByRole('listbox')).toHaveCount(0);+ await expect(dialog).toBeVisible();+ expect(await hasFocus(field)).toBe(true);++ await page.keyboard.press('Escape');+ await expect(dialog).toHaveCount(0);+});++test('Shift+Escape also hides the list before it closes the dialog around the field', async ({+ page,+}) => {+ await openStory(page, STORY.dialog);+ const dialog = page.getByRole('dialog', {name: 'Share'});+ const field = page.getByRole('combobox', {name: 'Add people'});+ await field.click();+ await page.keyboard.type('al');+ await expect(page.getByRole('listbox')).toBeVisible();++ await page.keyboard.press('Shift+Escape');+ await expect(page.getByRole('listbox')).toHaveCount(0);+ // Give a close request time to land if the press had reached the dialog.+ await page.waitForTimeout(300);+ await expect(dialog).toBeVisible();+ expect(await hasFocus(field)).toBe(true);++ await page.keyboard.press('Shift+Escape');+ await expect(dialog).toHaveCount(0);+});++test('with no matches in the dialog, the first Escape hides the empty message and the dialog stays', async ({+ page,+}) => {+ await openStory(page, STORY.dialog);+ const dialog = page.getByRole('dialog', {name: 'Share'});+ const field = page.getByRole('combobox', {name: 'Add people'});+ await field.click();+ await page.keyboard.type('zz');+ // The shown paragraph, not the dialog's live region, which announces the+ // same words for a moment.+ const empty = dialog.locator('p').filter({hasText: /^No one matches$/});+ await expect(empty).toBeVisible();+ await expect(page.getByRole('listbox')).toHaveCount(0);+ await expect(field).toHaveAttribute('aria-expanded', 'false');++ await page.keyboard.press('Escape');+ await expect(empty).toHaveCount(0);+ await expect(dialog).toBeVisible();+ expect(await hasFocus(field)).toBe(true);++ await page.keyboard.press('Escape');+ await expect(dialog).toHaveCount(0);+});++test('hovering makes an option active and a press picks it, with focus kept in the field', async ({+ page,+}) => {+ await openStory(page, STORY.dialog);+ const field = page.getByRole('combobox', {name: 'Add people'});+ await field.click();+ await page.keyboard.type('a');+ const grace = page.getByRole('option', {name: 'Grace Hopper (away)'});+ await expect(grace).toHaveAttribute('aria-disabled', 'true');++ await page.getByRole('option', {name: 'Katherine Johnson'}).hover();+ expect(await activeOptionName(page, field)).toBe('Katherine Johnson');+ await grace.hover();+ expect(await activeOptionName(page, field)).toBe('Katherine Johnson');+ // Playwright waits for an aria-disabled element to enable; press it anyway.+ await grace.click({force: true});+ await expect(page.getByRole('listbox')).toBeVisible();+ await expect(page.getByText('Not shared yet')).toBeVisible();+ expect(await hasFocus(field)).toBe(true);++ await page.getByRole('option', {name: 'Margaret Hamilton'}).click();+ await expect(page.getByText('Shared with Margaret Hamilton')).toBeVisible();+ await expect(page.getByRole('listbox')).toHaveCount(0);+ expect(await hasFocus(field)).toBe(true);+});++/**+ * Records every non-empty text written to a polite region, by where it is:+ * the page body's shared region, or an open dialog's own.+ */+async function recordPoliteWrites(+ page: Page,+): Promise<() => Promise<{body: string[]; dialog: string[]}>> {+ await page.addInitScript(() => {+ const writes = {body: [] as string[], dialog: [] as string[]};+ (window as unknown as {__writes: typeof writes}).__writes = writes;+ new MutationObserver(records => {+ for (const record of records) {+ const target = record.target;+ if (!(target instanceof Element)) {+ continue;+ }+ const where = target.matches('[data-astryx-live-region="polite"]')+ ? 'body'+ : target.matches('[data-astryx-modal-live-region="polite"]')+ ? 'dialog'+ : null;+ for (const node of where == null ? [] : record.addedNodes) {+ if (node.textContent) {+ writes[where as 'body' | 'dialog'].push(node.textContent);+ }+ }+ }+ }).observe(document, {childList: true, subtree: true});+ });+ return async () =>+ page.evaluate(() => {+ const writes = (+ window as unknown as {__writes: {body: string[]; dialog: string[]}}+ ).__writes;+ return {body: [...writes.body], dialog: [...writes.dialog]};+ });+}++/** Two frames: the shared channel joins messages written within one (AST-086 FR9). */+async function nextFrames(page: Page): Promise<void> {+ await page.evaluate(+ async () =>+ new Promise(resolve =>+ requestAnimationFrame(() => requestAnimationFrame(resolve)),+ ),+ );+}++test('the search story announces each new query’s count, and the words it shows for none', async ({+ page,+}) => {+ const writes = await recordPoliteWrites(page);+ await openStory(page, STORY.search);+ await page.getByRole('combobox', {name: 'Search settings'}).click();+ // Nothing is announced on mount.+ await nextFrames(page);+ await page.waitForTimeout(300);+ expect(await writes()).toEqual({body: [], dialog: []});+ const expected: string[] = [];+ for (const [key, words] of [+ ['n', '5 results'],+ ['o', '2 results'],+ ['z', 'No settings match'],+ ] as const) {+ await page.keyboard.press(key);+ expected.push(words);+ await expect.poll(writes).toEqual({body: expected, dialog: []});+ await nextFrames(page);+ }+ await expect(+ page.locator('p').filter({hasText: /^No settings match$/}),+ ).toBeVisible();+ // A trailing space leaves the query unchanged, so nothing new is announced.+ await page.keyboard.press(' ');+ await nextFrames(page);+ await page.waitForTimeout(300);+ expect(await writes()).toEqual({body: expected, dialog: []});+});++test('in a layer, the active option crosses into it, focus stays in the input, and Escape hides only the layer', async ({+ page,+}) => {+ await openStory(page, STORY.layer);+ const field = page.getByRole('combobox', {name: 'Assignee'});+ await field.click();+ await page.keyboard.type('ar');+ const listbox = page.getByRole('listbox', {name: 'People'});+ await expect(listbox).toBeVisible();+ await expect(field).toHaveAttribute('aria-expanded', 'true');+ await expect(field).toHaveAttribute(+ 'aria-controls',+ (await listbox.getAttribute('id')) ?? '',+ );+ expect(await activeOptionName(page, field)).toBe('Barbara Liskov');+ await page.keyboard.press('ArrowDown');+ expect(await activeOptionName(page, field)).toBe('Margaret Hamilton');+ expect(await hasFocus(field)).toBe(true);++ await page.keyboard.press('Escape');+ await expect(listbox).toHaveCount(0);+ await expect(field).toHaveAttribute('aria-expanded', 'false');+ expect(await hasFocus(field)).toBe(true);+ await expect(page.getByText('Unassigned', {exact: true})).toBeVisible();+});++test('the dialog story announces in the dialog’s own live region, never the page body’s', async ({+ page,+}) => {+ const writes = await recordPoliteWrites(page);+ await openStory(page, STORY.dialog);+ await page.getByRole('combobox', {name: 'Add people'}).click();+ const expected: string[] = [];+ for (const [key, words] of [+ ['a', '7 results'],+ ['l', '1 result'],+ ['z', 'No one matches'],+ ] as const) {+ await page.keyboard.press(key);+ expected.push(words);+ await expect.poll(writes).toEqual({body: [], dialog: expected});+ await nextFrames(page);+ }+});diff --git a/packages/core/src/Selector/hooks.ts b/packages/core/src/Selector/hooks.tsindex acc1cb141c..5f19b8e412 100644--- a/packages/core/src/Selector/hooks.ts+++ b/packages/core/src/Selector/hooks.ts@@ -7,7 +7,8 @@* @input Uses untransformed DOM layout geometry from the Selector's outer* anchor, listbox, and selected option* @output Hooks for Selector: useSelectedItemOffset, and useCombobox (public,- * exported from the Selector entry point; also used by CommandPalette)+ * exported from the Selector entry point; also used by CommandPalette, and+ * by products for a combobox over a text field they render, spec:AST-075)* @position Selector hooks; used by Selector.tsx and CommandPalette** SYNC: When useCombobox's options or return change, update:@@ -17,6 +18,7 @@import {useCallback, useState} from 'react';import {useHighlightedOptionScroll} from '../hooks/useHighlightedOptionScroll';import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';+import {isImeKeyEvent} from '../utils/ime';import type {RefObject} from 'react';import type {SelectorOptionData} from './types';@@ -158,8 +160,18 @@ export function useSelectedItemOffset({// useCombobox - Keyboard navigation and selection// =============================================================================-interface UseComboboxOptions {- selectableItems: SelectorOptionData[];+/**+ * What useCombobox reads from an option: its value, and whether it can be+ * picked. Any option type that carries these works; Selector's+ * `SelectorOptionData` is the default.+ */+interface ComboboxOption {+ value: string;+ disabled?: boolean;+}++interface UseComboboxOptions<T extends ComboboxOption> {+ selectableItems: ReadonlyArray<T>;value?: string;isDisabled?: boolean;isOpen: boolean;@@ -184,14 +196,58 @@ interface UseComboboxOptions {listboxId: string;}-interface UseComboboxResult {+/** Spread onto the caller's field. */+interface ComboboxFieldProps {+ role: 'combobox';+ 'aria-autocomplete': 'list';+ 'aria-expanded': boolean;+ 'aria-controls'?: string;+ 'aria-activedescendant'?: string;+ onKeyDown: (event: React.KeyboardEvent) => void;+}++/** Spread onto the caller's listbox, which the caller names. */+interface ComboboxListboxProps {+ id: string;+ role: 'listbox';+ onMouseDown: (event: React.MouseEvent) => void;+}++/** Spread onto the caller's option at one index. */+interface ComboboxOptionProps {+ id: string;+ role: 'option';+ 'aria-selected': boolean;+ 'aria-disabled'?: true;+ onMouseMove: () => void;+ onClick: () => void;+}++/** The caller's own handlers for its field, run after the hook's. */+interface ComboboxFieldHandlers {+ // Method syntax keeps the parameter bivariant, so a handler typed for its+ // own element, such as an input, is accepted.+ onKeyDown?(event: React.KeyboardEvent): void;+}++interface UseComboboxResult<T extends ComboboxOption> {highlightedIndex: number;setHighlightedIndex: (index: number) => void;getItemId: (index: number) => string;onTriggerClick: () => void;onKeyDown: (e: React.KeyboardEvent) => void;- onItemSelect: (item: SelectorOptionData) => void;- onItemMouseEnter: (item: SelectorOptionData, index: number) => void;+ // Method syntax keeps a result built over a richer option type assignable+ // to `ReturnType<typeof useCombobox>`, the name released callers use.+ onItemSelect(item: T): void;+ onItemMouseEnter(item: T, index: number): void;+ getFieldProps: (props?: ComboboxFieldHandlers) => ComboboxFieldProps;+ getListboxProps: () => ComboboxListboxProps;+ getOptionProps: (index: number) => ComboboxOptionProps;+}++/** Whether a key is chorded with a modifier, such as Shift+Enter. */+function hasModifier(e: React.KeyboardEvent): boolean {+ return e.altKey || e.ctrlKey || e.metaKey || e.shiftKey;}/**@@ -201,8 +257,14 @@ interface UseComboboxResult {* `useTypeahead` hook and run it ahead of this handler (see Selector). That* keeps matching consistent with the other collections and leaves consumers* whose own input already filters the items (CommandPalette) untouched.+ *+ * For a single-line text field the caller renders (spec:AST-075), `getFieldProps`,+ * `getListboxProps` and `getOptionProps` carry the combobox semantics, the+ * field's keys and the pointer model, while the caller keeps the field, the+ * rows and where the list renders. The caller announces each new result count+ * through useAnnounce (spec:AST-075 DEC-2), with the words the field shows.*/-export function useCombobox({+export function useCombobox<T extends ComboboxOption = SelectorOptionData>({selectableItems,value,isDisabled = false,@@ -214,7 +276,7 @@ export function useCombobox({onClear,onSearchSeed,listboxId,-}: UseComboboxOptions): UseComboboxResult {+}: UseComboboxOptions<T>): UseComboboxResult<T> {const [highlightedIndex, setHighlightedIndex] = useState<number>(-1);const getItemId = useCallback(@@ -238,7 +300,7 @@ export function useCombobox({}, [onClose]);const selectItem = useCallback(- (item: SelectorOptionData) => {+ (item: T) => {if (item.disabled) {return;}@@ -273,7 +335,7 @@ export function useCombobox({});const onItemMouseEnter = useCallback(- (item: SelectorOptionData, index: number) => {+ (item: T, index: number) => {if (!item.disabled) {highlightOnHover(index);}@@ -434,6 +496,165 @@ export function useCombobox({],);+ // ---------------------------------------------------------------------------+ // A field the caller renders (spec:AST-075). Focus never leaves it: the+ // active option is named through aria-activedescendant, and the field keeps+ // every key the list does not need.+ // ---------------------------------------------------------------------------++ // The listbox renders only while it has options; an open list with none+ // shows the caller's empty state instead, which is not a listbox.+ const isListboxShown = isOpen && selectableItems.length > 0;+ const activeDescendant =+ isListboxShown &&+ highlightedIndex >= 0 &&+ highlightedIndex < selectableItems.length+ ? getItemId(highlightedIndex)+ : undefined;++ const onFieldKeyDown = useCallback(+ (e: React.KeyboardEvent): void => {+ // A chord is the field's own command, such as Shift+Enter, except+ // Escape: whatever modifier is held, it hides a shown list first, so an+ // enclosing layer never closes on the same press. An input method+ // composing text owns every key, Escape included, until it commits or+ // cancels.+ if (+ isDisabled ||+ isImeKeyEvent(e.nativeEvent) ||+ (hasModifier(e) && e.key !== 'Escape')+ ) {+ return;+ }+ const enabledIndices = getEnabledIndices();+ if (!isOpen) {+ // A single-line field has no caret work for ArrowDown, so it shows the+ // hidden list.+ if (+ e.key === 'ArrowDown' &&+ selectableItems.length > 0 &&+ onOpen() !== false+ ) {+ e.preventDefault();+ setHighlightedIndex(enabledIndices[0] ?? -1);+ }+ return;+ }+ switch (e.key) {+ case 'ArrowDown':+ case 'ArrowUp': {+ // The list keeps the arrows even with nothing to move to, so they+ // never move the caret under an open list.+ e.preventDefault();+ if (enabledIndices.length === 0) {+ break;+ }+ // Wraps at either end, as the typeahead input does; with nothing+ // active, ArrowDown starts at the first option and ArrowUp at the+ // last.+ const count = enabledIndices.length;+ const position = enabledIndices.indexOf(highlightedIndex);+ const next =+ e.key === 'ArrowDown'+ ? (position + 1) % count+ : position < 0+ ? count - 1+ : (position - 1 + count) % count;+ setHighlightedIndex(enabledIndices[next]);+ break;+ }+ case 'Enter': {+ // Only a pick stops the field's own Enter (a send, a newline).+ const item =+ highlightedIndex >= 0 ? selectableItems[highlightedIndex] : null;+ if (item != null && !item.disabled) {+ e.preventDefault();+ selectItem(item);+ }+ break;+ }+ case 'Escape':+ // Claimed, so an enclosing layer stays open on this press.+ e.preventDefault();+ closeAndReset();+ break;+ default:+ // Every other key reaches the field unchanged. Home and End stay+ // with the caret until their behavior is decided (AST-075 OQ2).+ break;+ }+ },+ [+ isDisabled,+ getEnabledIndices,+ isOpen,+ selectableItems,+ onOpen,+ highlightedIndex,+ selectItem,+ closeAndReset,+ ],+ );++ const getFieldProps = useCallback(+ (props: ComboboxFieldHandlers = {}): ComboboxFieldProps => {+ return {+ role: 'combobox',+ 'aria-expanded': isListboxShown,+ 'aria-autocomplete': 'list',+ 'aria-controls': isListboxShown ? listboxId : undefined,+ 'aria-activedescendant': activeDescendant,+ onKeyDown: event => {+ onFieldKeyDown(event);+ if (!event.defaultPrevented) {+ props.onKeyDown?.(event);+ }+ },+ };+ },+ [isListboxShown, listboxId, activeDescendant, onFieldKeyDown],+ );++ const getListboxProps = useCallback(+ (): ComboboxListboxProps => ({+ id: listboxId,+ role: 'listbox',+ // A press anywhere in the list keeps focus in the field (FR6).+ onMouseDown: event => event.preventDefault(),+ }),+ [listboxId],+ );++ const getOptionProps = useCallback(+ (index: number): ComboboxOptionProps => {+ const item = selectableItems[index];+ const isOptionDisabled = item?.disabled === true;+ return {+ id: getItemId(index),+ role: 'option',+ 'aria-selected': index === highlightedIndex,+ ...(isOptionDisabled ? {'aria-disabled': true as const} : {}),+ onMouseMove: () => {+ if (item != null && !isOptionDisabled && index !== highlightedIndex) {+ highlightOnHover(index);+ }+ },+ onClick: () => {+ if (item != null) {+ selectItem(item);+ }+ },+ };+ },+ [+ selectableItems,+ getItemId,+ highlightedIndex,+ highlightOnHover,+ selectItem,+ ],+ );+return {highlightedIndex,setHighlightedIndex,@@ -442,5 +663,8 @@ export function useCombobox({onKeyDown,onItemSelect: selectItem,onItemMouseEnter,+ getFieldProps,+ getListboxProps,+ getOptionProps,};}diff --git a/packages/core/src/Selector/useCombobox.doc.mjs b/packages/core/src/Selector/useCombobox.doc.mjsindex 882b50ec5e..52d62129ff 100644--- a/packages/core/src/Selector/useCombobox.doc.mjs+++ b/packages/core/src/Selector/useCombobox.doc.mjs@@ -16,6 +16,7 @@ export const docs = {'keyboard','arrow keys','headless',+ 'autocomplete','apg','accessibility','a11y',@@ -29,9 +30,9 @@ export const docs = {},{name: 'options.selectableItems',- type: 'SelectorOptionData[]',+ type: 'ReadonlyArray<T extends {value: string; disabled?: boolean}>',description:- 'The options in the same order as they render. Options with `disabled` cannot be picked and are skipped while moving through the open list; ArrowDown or ArrowUp that opens the list still lands on the first or last option.',+ 'The options in the same order as they render: `SelectorOptionData`, or any option type with a string `value` and an optional `disabled`. Options with `disabled` cannot be picked and are skipped while moving through the open list; ArrowDown or ArrowUp that opens the list from `onKeyDown` still lands on the first or last option.',required: true,},{@@ -131,19 +132,37 @@ export const docs = {},{name: 'onItemSelect',- type: '(item: SelectorOptionData) => void',+ type: '(item: T) => void',description: 'Picks an option from a press on it, then closes the list.',},{name: 'onItemMouseEnter',- type: '(item: SelectorOptionData, index: number) => void',+ type: '(item: T, index: number) => void',description:'Makes the hovered option active without scrolling the list or moving focus.',},+ {+ name: 'getFieldProps',+ type: '(props?: {onKeyDown?(event: React.KeyboardEvent): void}) => object',+ description:+ 'Props for a single-line `input` you render: `role="combobox"`, `aria-expanded`, `aria-autocomplete="list"`, `aria-controls` only while the listbox renders (`isOpen` with at least one option), `aria-activedescendant` only while an option is active, and the field\u2019s key handler. Pass your own `onKeyDown` here rather than beside the spread: it runs after the hook\u2019s handler unless that handler claimed the key, and it may be typed for its element.',+ },+ {+ name: 'getListboxProps',+ type: '() => object',+ description:+ 'Props for the listbox you render, anywhere in the document, including the page\u2019s flow: its `id` and `role`, and a press handler that keeps focus in the field. Render it while `isOpen` and there are options, and name it with `aria-label` or `aria-labelledby`.',+ },+ {+ name: 'getOptionProps',+ type: '(index: number) => object',+ description:+ 'Props for the option at `index`: its `id`, `role`, `aria-selected` (true on the active option), `aria-disabled` on a disabled one, a pointer move that makes it active without moving focus, and a press that picks it.',+ },],usage: {description:- 'Tracks the active option of a single-select combobox and handles its keys, while DOM focus stays on the control. It powers Selector and CommandPalette; use it to build a combobox those components do not cover. It renders nothing and sets no attributes: the caller renders the control, the listbox and the options, and wires `role`, `aria-expanded`, `aria-controls` and `aria-activedescendant` from what it returns.',+ 'Tracks the active option of a single-select combobox and handles its keys, while DOM focus stays on the control. It powers Selector and CommandPalette; use it to build a combobox those components do not cover, including one over a single-line text field you render yourself, such as a search field whose results replace a page section, or an \u201cadd people\u201d field in a dialog. It renders nothing: you render the field, the listbox and the options, and spread `getFieldProps`, `getListboxProps` and `getOptionProps` onto them, or wire `role`, `aria-expanded`, `aria-controls` and `aria-activedescendant` yourself from `onKeyDown` and `getItemId` for a control such as a button.',bestPractices: [{guidance: true,@@ -158,7 +177,17 @@ export const docs = {{guidance: true,description:- 'Announce the number of results through useAnnounce when the options change for a new query.',+ 'For a field you render, spread the prop getters, and set the active option yourself when a new query changes the options: the first option so Enter picks it, or -1 so Enter stays the field\u2019s.',+ },+ {+ guidance: true,+ description:+ 'Announce the number of results through useAnnounce when the options change for a new query (AST-075 DEC-2). When nothing matches, announce the words the field shows for it.',+ },+ {+ guidance: false,+ description:+ 'Render controls that are not options, such as a create button or an empty message, inside the listbox; render them beside it.',},{guidance: false,@@ -166,6 +195,57 @@ export const docs = {'Move DOM focus onto the options; the active option is announced through `aria-activedescendant` while focus stays on the control.',},],+ accessibility: [+ {+ name: 'Focus stays in the field',+ category: 'Semantics',+ requirement: 'AST-075 FR1',+ description:+ 'With the prop getters, moving the active option never moves focus out of the field. The field names the active option through `aria-activedescendant` and carries none while no option is active.',+ },+ {+ name: 'Expanded state follows the list',+ category: 'Semantics',+ requirement: 'AST-075 FR2',+ description:+ 'While the listbox renders, the field exposes `aria-expanded="true"` and `aria-controls` naming it. Otherwise it exposes `aria-expanded="false"` and references nothing.',+ },+ {+ name: 'Roles',+ category: 'Semantics',+ requirement: 'AST-075 FR3',+ description:+ 'The field is a `combobox` with `aria-autocomplete="list"`. The list is a `listbox` of `option`s with `aria-selected="true"` on the active one. You name the field and the listbox.',+ },+ {+ name: 'Keys',+ category: 'Keyboard',+ requirement: 'AST-075 FR4',+ description:+ 'While the list shows, ArrowDown and ArrowUp move the active option and wrap; Enter picks an active option and only then stops the field\u2019s own Enter; Escape, whatever modifier is held, hides the list without closing an enclosing dialog or popover on the same press. While it is hidden, ArrowDown shows it when there are options. An open field with no options still takes Escape, which closes the list, so render an empty message while it is open. Home, End, other chords such as Shift+Enter, and every other key reach the field.',+ },+ {+ name: 'Input method',+ category: 'Keyboard',+ requirement: 'AST-075 FR5',+ description:+ 'No key moves, picks or hides while an input method is composing text.',+ },+ {+ name: 'Pointer',+ category: 'Semantics',+ requirement: 'AST-075 FR6',+ description:+ 'Moving the pointer over an option makes it active without moving focus; pressing an option picks it, and the field keeps focus through the press.',+ },+ {+ name: 'Result count',+ category: 'Content',+ requirement: 'AST-075 FR7',+ description:+ 'Yours to announce: compose useAnnounce (AST-075 DEC-2) so each new query announces the number of options, or that there are none, once and politely. For none, announce the words the field shows.',+ },+ ],},relatedComponents: ['Selector', 'CommandPalette'],relatedHooks: ['useMultiCombobox', 'useTypeahead', 'useAnnounce'],@@ -176,11 +256,11 @@ export const docs = {/** @type {import('@astryxdesign/cli/authoring').HookTranslationDoc} */export const docsDense = {description:- 'Single-select combobox state + keys; focus stays on control. Powers Selector / CommandPalette. Renders nothing, sets no attrs: caller renders control / listbox / options and wires role, aria-expanded, aria-controls, aria-activedescendant.',+ 'Single-select combobox state + keys; focus stays on control. Powers Selector / CommandPalette, and comboboxes over a single-line field you render (search whose results replace a section, an add-people field). Renders nothing: spread getFieldProps / getListboxProps / getOptionProps, or wire role, aria-expanded, aria-controls, aria-activedescendant yourself.',paramDescriptions: {options: 'config.','options.selectableItems':- 'options in render order; disabled ones not pickable, skipped while moving in open list (ArrowDown/Up opening still lands first / last).',+ 'options in render order: SelectorOptionData or any type w/ string value + optional disabled; disabled ones not pickable, skipped while moving in open list (onKeyDown ArrowDown/Up opening still lands first / last).','options.isOpen': 'list shown; caller owns state.','options.onOpen':'show list; return false to refuse (highlight untouched).',@@ -209,6 +289,12 @@ export const docsDense = {'control keydown: ArrowDown/Up open or move; Enter (Space w/o search) picks or opens; Escape / Tab close; Home / End / PageUp / PageDown jump. editable control keeping Home / End for caret: do not pass them.',onItemSelect: 'pick from a press, then close.',onItemMouseEnter: 'hover makes option active; no scroll, no focus move.',+ getFieldProps:+ 'input props: role=combobox, aria-expanded, aria-autocomplete=list, aria-controls only while listbox renders (isOpen + options), aria-activedescendant only while an option is active, key handler. pass own onKeyDown here (may be typed for its element): runs after hook unless hook claimed key.',+ getListboxProps:+ 'listbox props (id, role, press keeps focus in field); render anywhere incl. page flow while isOpen + options; name it (aria-label / aria-labelledby).',+ getOptionProps:+ 'option props at index: id, role, aria-selected on active, aria-disabled, pointer move activates w/o focus move, press picks.',},usage: {description:@@ -226,12 +312,73 @@ export const docsDense = {},{guidance: true,- description: 'Announce result count via useAnnounce on new query.',+ description:+ 'Own field: spread the getters, set active option on new query (first: Enter picks; -1: Enter stays the field\u2019s).',+ },+ {+ guidance: true,+ description:+ 'Announce result count via useAnnounce on new query (AST-075 DEC-2); for none, the words the field shows.',+ },+ {+ guidance: false,+ description:+ 'Non-option controls (create button, empty message) inside listbox; render beside it.',},{guidance: false,description: 'Move DOM focus onto options; use aria-activedescendant.',},],+ accessibility: [+ {+ name: 'Focus stays in the field',+ category: 'Semantics',+ requirement: 'AST-075 FR1',+ description:+ 'moving active option never moves focus; aria-activedescendant names it, none while nothing active.',+ },+ {+ name: 'Expanded state follows the list',+ category: 'Semantics',+ requirement: 'AST-075 FR2',+ description:+ 'listbox renders -> aria-expanded=true + aria-controls; else false + no reference.',+ },+ {+ name: 'Roles',+ category: 'Semantics',+ requirement: 'AST-075 FR3',+ description:+ 'field = combobox + aria-autocomplete=list. listbox of options, aria-selected=true on active. you name field + listbox.',+ },+ {+ name: 'Keys',+ category: 'Keyboard',+ requirement: 'AST-075 FR4',+ description:+ 'shown: ArrowDown/Up move (wrap), Enter picks active option then stops field Enter, Escape (any modifier) hides w/o closing enclosing dialog / popover same press. hidden: ArrowDown shows it w/ options. open field w/ no options still takes Escape (closes list): render an empty message while open. Home / End / other chords (Shift+Enter) / others reach field.',+ },+ {+ name: 'Input method',+ category: 'Keyboard',+ requirement: 'AST-075 FR5',+ description: 'no key moves / picks / hides during IME composition.',+ },+ {+ name: 'Pointer',+ category: 'Semantics',+ requirement: 'AST-075 FR6',+ description:+ 'pointer move over option activates w/o focus move; press picks, field keeps focus.',+ },+ {+ name: 'Result count',+ category: 'Content',+ requirement: 'AST-075 FR7',+ description:+ 'yours: compose useAnnounce (DEC-2), each new query announces count or none once, politely; none = the words the field shows.',+ },+ ],},};diff --git a/packages/core/src/Selector/useCombobox.public.test.tsx b/packages/core/src/Selector/useCombobox.public.test.tsxnew file mode 100644index 0000000000..294f572e93--- /dev/null+++ b/packages/core/src/Selector/useCombobox.public.test.tsx@@ -0,0 +1,89 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file useCombobox.public.test.tsx+ * @input useCombobox and SelectorOptionData from the public Selector barrel+ * @output Compile-time compatibility coverage: a caller that names the result+ * `ReturnType<typeof useCombobox>` over an option type of its own, and a+ * key handler typed for an input, passed to getFieldProps and spread back+ * onto it+ * @position Public API test guarding @astryxdesign/core/Selector; the core+ * typecheck compiles it, so a type regression fails there+ */++import {render, screen} from '@testing-library/react';+import type {KeyboardEvent} from 'react';+import {describe, expect, it} from 'vitest';+import {useCombobox} from './index';+import type {SelectorOptionData} from './index';++/** An option type of the caller's own, richer than SelectorOptionData. */+type Person = {value: string; label: string; email: string};++const PEOPLE: Person[] = [+ {value: 'ada', label: 'Ada', email: '[email protected]'},+ {value: 'cy', label: 'Cy', email: '[email protected]'},+];++/**+ * The released shape: the result named after the hook, the only name a+ * caller has for it, over the caller's own option type.+ */+function useNamedResult(): ReturnType<typeof useCombobox> {+ return useCombobox({+ selectableItems: PEOPLE,+ isOpen: true,+ onOpen: () => {},+ onClose: () => {},+ listboxId: 'people',+ });+}++function NamedResult() {+ const combobox = useNamedResult();+ // The released handlers still take a Selector option, or the caller's own.+ const onSelect: (item: SelectorOptionData) => void = combobox.onItemSelect;+ const onHover: (item: SelectorOptionData, index: number) => void =+ combobox.onItemMouseEnter;+ return (+ <button+ type="button"+ onClick={() => {+ combobox.onItemSelect(PEOPLE[0]);+ combobox.onItemMouseEnter(PEOPLE[1], 1);+ onSelect({value: 'cy'});+ onHover({value: 'cy'}, 1);+ }}>+ Pick+ </button>+ );+}++function FieldTypedHandlers() {+ const closed = {+ selectableItems: PEOPLE,+ isOpen: false,+ onOpen: () => {},+ onClose: () => {},+ };+ const to = useCombobox({...closed, listboxId: 'to'});+ // The handler reads a member only its own element has.+ const onInputKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {+ event.currentTarget.select();+ };+ return (+ <input aria-label="To" {...to.getFieldProps({onKeyDown: onInputKeyDown})} />+ );+}++describe('useCombobox public types', () => {+ it('keeps a result named ReturnType<typeof useCombobox> over a richer option type', () => {+ render(<NamedResult />);+ expect(screen.getByRole('button', {name: 'Pick'})).toBeTruthy();+ });++ it('takes a key handler typed for an input', () => {+ render(<FieldTypedHandlers />);+ expect(screen.getByRole('combobox', {name: 'To'})).toBeTruthy();+ });+});diff --git a/packages/core/src/Selector/useCombobox.test.tsx b/packages/core/src/Selector/useCombobox.test.tsxnew file mode 100644index 0000000000..4754170a3f--- /dev/null+++ b/packages/core/src/Selector/useCombobox.test.tsx@@ -0,0 +1,444 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file useCombobox.test.tsx+ * @input Uses vitest, @testing-library/react, @testing-library/user-event,+ * useCombobox and the layer dismissal stack+ * @output Unit tests for useCombobox over a single-line field the caller renders+ * @position Tests; validates the field props, keys and pointer model of+ * hooks.ts against spec:AST-075 FR1–FR6+ *+ * SYNC: When useCombobox's field props or keys change, update these tests.+ */++import {cleanup, fireEvent, render, screen} from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import {useRef, useState, type ReactNode} from 'react';+import {afterEach, describe, expect, it, vi} from 'vitest';+import {+ COMBOBOX_PATTERN,+ expectAccessibilitySpec,+ type ComboboxStateFacts,+} from '@astryxdesign/a11y-spec';+import {LayerDepthProvider} from '../Layer/LayerDepthContext';+import {resetLayerStackForTests} from '../Layer/layerStack';+import {useLayerDismissal} from '../Layer/useLayerDismissal';+import {useCombobox} from './hooks';++type Person = {value: string; label: string; disabled?: boolean};++const PEOPLE: Person[] = [+ {value: 'ada', label: 'Ada'},+ {value: 'bea', label: 'Bea', disabled: true},+ {value: 'cy', label: 'Cy'},+];++afterEach(() => {+ resetLayerStackForTests();+});++interface PickerProps {+ options?: Person[];+ isInitiallyOpen?: boolean;+ onSelect?: (value: string) => void;+ onOpen?: () => void;+ onClose?: () => void;+ onFieldKeyDown?: (event: React.KeyboardEvent) => void;+}++/** A field the test renders itself, with its list in the page's flow. */+function Picker({+ options = PEOPLE,+ isInitiallyOpen = true,+ onSelect,+ onOpen,+ onClose,+ onFieldKeyDown,+}: PickerProps) {+ const [isOpen, setIsOpen] = useState(isInitiallyOpen);+ const combobox = useCombobox({+ selectableItems: options,+ isOpen,+ onOpen: () => {+ onOpen?.();+ setIsOpen(true);+ },+ onClose: () => {+ onClose?.();+ setIsOpen(false);+ },+ onSelect,+ listboxId: 'people',+ });+ const fieldProps = combobox.getFieldProps({onKeyDown: onFieldKeyDown});+ return (+ <>+ <input aria-label="To" {...fieldProps} />+ {isOpen && options.length > 0 ? (+ <div aria-label="People" {...combobox.getListboxProps()}>+ {options.map((person, index) => (+ <div key={person.value} {...combobox.getOptionProps(index)}>+ {person.label}+ </div>+ ))}+ </div>+ ) : null}+ </>+ );+}++/** A registered layer, like a Dialog or Popover, around the field. */+function Layer({+ onDismiss,+ children,+}: {+ onDismiss: () => void;+ children: ReactNode;+}) {+ const containerRef = useRef<HTMLDivElement>(null);+ useLayerDismissal({+ isActive: true,+ onDismiss,+ getContainer: () => containerRef.current,+ });+ return (+ <div ref={containerRef}>+ <LayerDepthProvider>{children}</LayerDepthProvider>+ </div>+ );+}++function toField(): HTMLElement {+ return screen.getByRole('combobox', {name: 'To'});+}++function option(name: string): HTMLElement {+ return screen.getByRole('option', {name});+}++describe('useCombobox field props — roles and state (FR1–FR3)', () => {+ it('a hidden list leaves the field collapsed with nothing to reference', () => {+ render(<Picker isInitiallyOpen={false} />);+ const box = toField();+ expect(box).toHaveAttribute('role', 'combobox');+ expect(box).toHaveAttribute('aria-autocomplete', 'list');+ expect(box).toHaveAttribute('aria-expanded', 'false');+ expect(box).not.toHaveAttribute('aria-controls');+ expect(box).not.toHaveAttribute('aria-activedescendant');+ });++ it('a shown list expands the field and names the listbox', () => {+ render(<Picker />);+ const box = toField();+ const listbox = screen.getByRole('listbox', {name: 'People'});+ expect(box).toHaveAttribute('aria-expanded', 'true');+ expect(box).toHaveAttribute('aria-controls', listbox.id);+ expect(screen.getAllByRole('option')).toHaveLength(3);+ // No option is active until the person moves to one.+ expect(box).not.toHaveAttribute('aria-activedescendant');+ });++ it('an open list with no options renders no listbox, so the field stays collapsed', () => {+ render(<Picker options={[]} />);+ const box = toField();+ expect(screen.queryByRole('listbox')).toBeNull();+ expect(box).toHaveAttribute('aria-expanded', 'false');+ expect(box).not.toHaveAttribute('aria-controls');+ });++ it('moving the active option keeps focus in the field and names it (FR1)', async () => {+ const user = userEvent.setup();+ render(<Picker />);+ const box = toField();+ await user.click(box);++ await user.keyboard('{ArrowDown}');+ expect(box).toHaveFocus();+ expect(box).toHaveAttribute('aria-activedescendant', option('Ada').id);+ expect(option('Ada')).toHaveAttribute('aria-selected', 'true');+ expect(option('Cy')).toHaveAttribute('aria-selected', 'false');++ // The disabled option is skipped, and the arrows wrap at either end.+ await user.keyboard('{ArrowDown}');+ expect(box).toHaveAttribute('aria-activedescendant', option('Cy').id);+ await user.keyboard('{ArrowDown}');+ expect(box).toHaveAttribute('aria-activedescendant', option('Ada').id);+ await user.keyboard('{ArrowUp}');+ expect(box).toHaveAttribute('aria-activedescendant', option('Cy').id);+ expect(box).toHaveFocus();+ expect(option('Bea')).toHaveAttribute('aria-disabled', 'true');+ });++ it('ArrowUp with nothing active starts at the last option', async () => {+ const user = userEvent.setup();+ render(<Picker />);+ const box = toField();+ await user.click(box);+ await user.keyboard('{ArrowUp}');+ expect(box).toHaveAttribute('aria-activedescendant', option('Cy').id);+ });+});++describe('useCombobox field props — the reusable Combobox contract', () => {+ const closed: ComboboxStateFacts = {+ name: 'To',+ expanded: false,+ popupRole: 'listbox',+ popupVisible: false,+ activeDescendant: false,+ readOnly: false,+ busy: false,+ inertUnderOwnModal: false,+ };++ it.each([+ {open: false, facts: closed},+ {+ open: true,+ facts: {+ ...closed,+ expanded: true,+ popupVisible: true,+ activeDescendant: true,+ },+ },+ ] as const)('input, list shown: $open', async ({open, facts}) => {+ await expectAccessibilitySpec({+ spec: COMBOBOX_PATTERN,+ binding: 'useCombobox.field',+ state: `input-${open ? 'shown' : 'hidden'}`,+ facts,+ render: async () => {+ render(<Picker isInitiallyOpen={open} />);+ if (open) {+ toField().focus();+ fireEvent.keyDown(toField(), {key: 'ArrowDown'});+ }+ },+ subject: () => toField(),+ related: (): Record<string, Element> =>+ open+ ? {+ popup: screen.getByRole('listbox'),+ 'active-descendant': option('Ada'),+ }+ : {},+ cleanup,+ });+ });+});++describe('useCombobox field props — keys (FR4)', () => {+ it('Enter picks only an active option, and only then stops the field’s own Enter', async () => {+ const user = userEvent.setup();+ const onSelect = vi.fn();+ const onFieldKeyDown = vi.fn();+ render(<Picker onSelect={onSelect} onFieldKeyDown={onFieldKeyDown} />);+ const box = toField();+ await user.click(box);++ // Nothing active: Enter is the field's own, such as a submit.+ expect(fireEvent.keyDown(box, {key: 'Enter'})).toBe(true);+ expect(onSelect).not.toHaveBeenCalled();+ expect(onFieldKeyDown).toHaveBeenCalledTimes(1);++ await user.keyboard('{ArrowDown}');+ expect(fireEvent.keyDown(box, {key: 'Enter'})).toBe(false);+ expect(onSelect).toHaveBeenCalledWith('ada');+ // The arrow and the pick never reached the field's handler.+ expect(onFieldKeyDown).toHaveBeenCalledTimes(1);+ // Picking hides the list; focus never left the field.+ expect(screen.queryByRole('listbox')).toBeNull();+ expect(box).toHaveFocus();+ });++ it('Escape hides the list without dismissing the enclosing layer on the same press', async () => {+ const user = userEvent.setup();+ const onDismiss = vi.fn();+ render(+ <Layer onDismiss={onDismiss}>+ <Picker />+ </Layer>,+ );+ await user.click(toField());++ await user.keyboard('{Escape}');+ expect(screen.queryByRole('listbox')).toBeNull();+ expect(onDismiss).not.toHaveBeenCalled();++ // With the list hidden, Escape belongs to the layer again.+ await user.keyboard('{Escape}');+ expect(onDismiss).toHaveBeenCalledTimes(1);+ });++ it('Escape also hides an open list that has no options', () => {+ const onClose = vi.fn();+ render(<Picker options={[]} onClose={onClose} />);+ expect(fireEvent.keyDown(toField(), {key: 'Escape'})).toBe(false);+ expect(onClose).toHaveBeenCalledTimes(1);+ });++ it.each(['shiftKey', 'ctrlKey', 'altKey', 'metaKey'] as const)(+ 'Escape held with %s still hides the list first and leaves the enclosing layer open',+ modifier => {+ const onDismiss = vi.fn();+ render(+ <Layer onDismiss={onDismiss}>+ <Picker />+ </Layer>,+ );+ const box = toField();+ box.focus();+ expect(fireEvent.keyDown(box, {key: 'Escape', [modifier]: true})).toBe(+ false,+ );+ expect(screen.queryByRole('listbox')).toBeNull();+ expect(onDismiss).not.toHaveBeenCalled();++ // With the list hidden, the same chord belongs to the layer again.+ fireEvent.keyDown(box, {key: 'Escape', [modifier]: true});+ expect(onDismiss).toHaveBeenCalledTimes(1);+ },+ );++ it('ArrowDown shows a hidden list in a single-line field', async () => {+ const user = userEvent.setup();+ render(<Picker isInitiallyOpen={false} />);+ const box = toField();+ await user.click(box);+ await user.keyboard('{ArrowDown}');+ expect(screen.getByRole('listbox')).toBeInTheDocument();+ expect(box).toHaveAttribute('aria-expanded', 'true');+ expect(box).toHaveAttribute('aria-activedescendant', option('Ada').id);+ });++ it('ArrowDown leaves a hidden list alone when there is nothing to show', () => {+ const onOpen = vi.fn();+ render(<Picker options={[]} isInitiallyOpen={false} onOpen={onOpen} />);+ expect(fireEvent.keyDown(toField(), {key: 'ArrowDown'})).toBe(true);+ expect(onOpen).not.toHaveBeenCalled();+ });++ it('keys other than the arrows, Enter and Escape reach the field while the list is shown', async () => {+ const user = userEvent.setup();+ const onFieldKeyDown = vi.fn();+ render(<Picker onFieldKeyDown={onFieldKeyDown} />);+ const box = toField();+ await user.click(box);+ await user.keyboard('{ArrowDown}');+ const active = box.getAttribute('aria-activedescendant');++ // Home and End stay with the caret: their combobox meaning is undecided.+ for (const key of ['Home', 'End', 'PageDown', 'Tab', ' ', 'a']) {+ expect(fireEvent.keyDown(box, {key})).toBe(true);+ }+ expect(onFieldKeyDown).toHaveBeenCalledTimes(6);+ expect(box).toHaveAttribute('aria-activedescendant', active);+ expect(screen.getByRole('listbox')).toBeInTheDocument();+ });++ it('a chord such as Shift+Enter is the field’s own command', async () => {+ const user = userEvent.setup();+ const onSelect = vi.fn();+ render(<Picker onSelect={onSelect} />);+ const box = toField();+ await user.click(box);+ await user.keyboard('{ArrowDown}');+ expect(fireEvent.keyDown(box, {key: 'Enter', shiftKey: true})).toBe(true);+ expect(onSelect).not.toHaveBeenCalled();+ });++ it('leaves onKeyDown with the trigger model it already had', async () => {+ const user = userEvent.setup();+ function Trigger() {+ const [isOpen, setIsOpen] = useState(true);+ const combobox = useCombobox({+ selectableItems: PEOPLE,+ isOpen,+ onOpen: () => setIsOpen(true),+ onClose: () => setIsOpen(false),+ listboxId: 'trigger',+ });+ return (+ <button+ type="button"+ aria-activedescendant={+ combobox.highlightedIndex >= 0+ ? combobox.getItemId(combobox.highlightedIndex)+ : undefined+ }+ onKeyDown={combobox.onKeyDown}>+ Pick+ </button>+ );+ }+ render(<Trigger />);+ const button = screen.getByRole('button', {name: 'Pick'});+ button.focus();+ await user.keyboard('{End}');+ expect(button).toHaveAttribute('aria-activedescendant', 'trigger-item-2');+ });+});++describe('useCombobox field props — input-method composition (FR5)', () => {+ it('a composing key neither moves, picks nor hides', async () => {+ const user = userEvent.setup();+ const onSelect = vi.fn();+ const onClose = vi.fn();+ render(<Picker onSelect={onSelect} onClose={onClose} />);+ const box = toField();+ await user.click(box);+ await user.keyboard('{ArrowDown}');+ const active = option('Ada').id;++ for (const init of [+ {key: 'ArrowDown', isComposing: true},+ {key: 'Enter', isComposing: true},+ {key: 'Escape', isComposing: true},+ {key: 'Enter', keyCode: 229},+ ]) {+ expect(fireEvent.keyDown(box, init)).toBe(true);+ }+ expect(box).toHaveAttribute('aria-activedescendant', active);+ expect(onSelect).not.toHaveBeenCalled();+ expect(onClose).not.toHaveBeenCalled();++ // Once the composition ends, Enter picks again.+ fireEvent.keyDown(box, {key: 'Enter'});+ expect(onSelect).toHaveBeenCalledWith('ada');+ });+});++describe('useCombobox field props — pointer (FR6)', () => {+ it('hovering makes an option active and pressing picks it, with focus kept in the field', async () => {+ const user = userEvent.setup();+ const onSelect = vi.fn();+ render(<Picker onSelect={onSelect} />);+ const box = toField();+ await user.click(box);++ await user.hover(option('Cy'));+ expect(box).toHaveAttribute('aria-activedescendant', option('Cy').id);+ expect(box).toHaveFocus();++ // A disabled option never becomes active and cannot be picked.+ await user.hover(option('Bea'));+ expect(box).toHaveAttribute('aria-activedescendant', option('Cy').id);+ await user.click(option('Bea'));+ expect(onSelect).not.toHaveBeenCalled();+ expect(box).toHaveFocus();++ await user.click(option('Cy'));+ expect(onSelect).toHaveBeenCalledWith('cy');+ expect(box).toHaveFocus();+ expect(screen.queryByRole('listbox')).toBeNull();+ });++ it('a press on the listbox itself keeps focus in the field', () => {+ render(<Picker />);+ const box = toField();+ box.focus();+ expect(fireEvent.mouseDown(screen.getByRole('listbox'))).toBe(false);+ expect(fireEvent.mouseDown(option('Ada'))).toBe(false);+ });+});