Skip to content

Commit d0c50e1

Browse files
fix(mosaic): keep combobox active option references valid after filtering
1 parent 3f701c6 commit d0c50e1

7 files changed

Lines changed: 173 additions & 7 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@clerk/mosaic': patch
3+
---
4+
5+
Fix screen readers announcing the wrong option, or no option, after typing in a Combobox search, such as the PhoneInput country picker. The search input now always points to the highlighted option, and points to nothing when no options match.

‎packages/mosaic/src/components/phone-input/phone-input.test.tsx‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,60 @@ describe('Mosaic PhoneInput', () => {
209209
expect(screen.getByRole('textbox', { name: 'Phone number' })).toHaveFocus();
210210
});
211211

212+
describe('active country reference while searching', () => {
213+
function expectActiveCountry(name: RegExp) {
214+
const reference = screen
215+
.getByRole('combobox', { name: 'Search countries' })
216+
.getAttribute('aria-activedescendant');
217+
expect(reference === null ? null : document.getElementById(reference)).toBe(screen.getByRole('option', { name }));
218+
}
219+
220+
it('references the only matching country through navigation and selection', async () => {
221+
const user = userEvent.setup();
222+
render(<PhoneInput aria-label='Phone number' />);
223+
224+
await user.click(screen.getByRole('button', { name: 'Country, United States' }));
225+
expectActiveCountry(/United States/);
226+
227+
await user.type(screen.getByRole('combobox', { name: 'Search countries' }), 'Greece');
228+
expect(screen.getAllByRole('option')).toHaveLength(1);
229+
expectActiveCountry(/Greece/);
230+
231+
await user.keyboard('{ArrowDown}');
232+
expectActiveCountry(/Greece/);
233+
await user.keyboard('{ArrowDown}');
234+
expectActiveCountry(/Greece/);
235+
236+
await user.keyboard('{Enter}');
237+
expect(screen.getByRole('button', { name: 'Country, Greece' })).toBeInTheDocument();
238+
expect(screen.getByRole('textbox', { name: 'Phone number' })).toHaveFocus();
239+
240+
await user.click(screen.getByRole('button', { name: 'Country, Greece' }));
241+
expectActiveCountry(/Greece/);
242+
});
243+
244+
it('drops the reference when no country matches, and references the selection on reopen', async () => {
245+
const user = userEvent.setup();
246+
render(<PhoneInput aria-label='Phone number' />);
247+
248+
await user.click(screen.getByRole('button', { name: 'Country, United States' }));
249+
const searchInput = screen.getByRole('combobox', { name: 'Search countries' });
250+
await user.type(searchInput, 'Greece');
251+
expectActiveCountry(/Greece/);
252+
253+
await user.type(searchInput, 'x');
254+
expect(screen.queryAllByRole('option')).toHaveLength(0);
255+
expect(searchInput).not.toHaveAttribute('aria-activedescendant');
256+
await user.keyboard('{ArrowDown}');
257+
expect(searchInput).not.toHaveAttribute('aria-activedescendant');
258+
259+
await user.keyboard('{Escape}');
260+
await waitFor(() => expect(screen.queryByRole('combobox', { name: 'Search countries' })).not.toBeInTheDocument());
261+
await user.click(screen.getByRole('button', { name: 'Country, United States' }));
262+
expectActiveCountry(/United States/);
263+
});
264+
});
265+
212266
it('clears the country search when the popup is dismissed', async () => {
213267
const user = userEvent.setup();
214268
render(<PhoneInput aria-label='Phone number' />);

‎packages/mosaic/src/primitives/combobox/combobox-context.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ export interface ComboboxContextValue {
3434
setOpen: (open: boolean) => void;
3535
focusInput: () => void;
3636
popupId: string | undefined;
37+
activeOptionId: string | undefined;
3738
mounted: boolean;
3839
transitionProps: TransitionProps;
3940
}
@@ -54,7 +55,8 @@ export interface ComboboxOptionsContextValue {
5455
refs: ExtendedRefs<ReferenceType>;
5556
valuesByIndexRef: React.MutableRefObject<Map<number, string>>;
5657
registerSelectedIndex: (index: number, value: string, label: string, selected: boolean) => (() => void) | undefined;
57-
registerOption: (index: number) => void;
58+
registerOption: (index: number) => () => void;
59+
popupId: string | undefined;
5860
}
5961

6062
export interface ComboboxHighlightContextValue {

‎packages/mosaic/src/primitives/combobox/combobox-input.tsx‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ export const ComboboxInput = React.forwardRef<HTMLInputElement, ComboboxInputPro
1313
open,
1414
inputValue,
1515
activeIndex,
16+
activeOptionId,
1617
refs,
1718
getReferenceProps,
1819
handleInputChange,
@@ -43,6 +44,9 @@ export const ComboboxInput = React.forwardRef<HTMLInputElement, ComboboxInputPro
4344
}),
4445
};
4546

47+
const merged = mergeProps<'input'>(defaultProps, otherProps);
48+
merged['aria-activedescendant'] = activeOptionId;
49+
4650
return useRender({
4751
defaultTagName: 'input',
4852
render,
@@ -52,6 +56,6 @@ export const ComboboxInput = React.forwardRef<HTMLInputElement, ComboboxInputPro
5256
stateAttributesMapping: {
5357
open: (v: boolean): Record<string, string> | null => (v ? { 'data-open': '' } : { 'data-closed': '' }),
5458
},
55-
props: mergeProps<'input'>(defaultProps, otherProps),
59+
props: merged,
5660
});
5761
});

‎packages/mosaic/src/primitives/combobox/combobox-option.tsx‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
'use client';
22

33
import { useListItem } from '@floating-ui/react';
4-
import React, { useEffect, useId } from 'react';
4+
import React, { useEffect } from 'react';
55

66
import { type ComponentProps, type DefaultProps, isHTMLElement, mergeProps, useRender } from '../utils';
77
import { useComboboxHighlightContext, useComboboxOptionsContext } from './combobox-context';
@@ -41,10 +41,10 @@ interface ComboboxOptionBodyProps extends ComboboxOptionProps {
4141
const ComboboxOptionBody = React.memo(function ComboboxOptionBody(bodyProps: ComboboxOptionBodyProps) {
4242
const { forwardedRef: ref, listItemRef: itemRef, index, isActive, isSelected, ...props } = bodyProps;
4343
const { render, value, label, disabled, ...otherProps } = props;
44-
const { getItemProps, handleSelect, valuesByIndexRef, registerSelectedIndex, registerOption, refs } =
44+
const { getItemProps, handleSelect, valuesByIndexRef, registerSelectedIndex, registerOption, refs, popupId } =
4545
useComboboxOptionsContext();
4646

47-
const id = useId();
47+
const id = popupId === undefined || index === -1 ? undefined : `${popupId}-${index}`;
4848
const displayLabel = label ?? value;
4949

5050
useEffect(() => {
@@ -53,10 +53,11 @@ const ComboboxOptionBody = React.memo(function ComboboxOptionBody(bodyProps: Com
5353
map.set(index, value);
5454
}
5555
const unregisterSelectedIndex = registerSelectedIndex(index, value, displayLabel, isSelected);
56-
registerOption(index);
56+
const unregisterOption = registerOption(index);
5757
return () => {
5858
map.delete(index);
5959
unregisterSelectedIndex?.();
60+
unregisterOption();
6061
};
6162
}, [index, value, displayLabel, disabled, isSelected, valuesByIndexRef, registerSelectedIndex, registerOption]);
6263

‎packages/mosaic/src/primitives/combobox/combobox-root.tsx‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@ function ComboboxInner(props: ComboboxProps) {
7373
const [selectedIndex, setSelectedIndex] = useState<number | null>(null);
7474
const [inlineMode, setInlineMode] = useState(false);
7575
const [queryChanged, setQueryChanged] = useState(false);
76+
const [optionCount, setOptionCount] = useState(0);
7677
const initialValue = props.value ?? props.defaultValue;
7778
const labelsByValueRef = useRef(
7879
new Map<string, string>(
@@ -117,10 +118,12 @@ function ComboboxInner(props: ComboboxProps) {
117118
const triggerRef = useRef<HTMLButtonElement | null>(null);
118119
const valuesByIndexRef = useRef<Map<number, string>>(new Map());
119120
const registerOption = useCallback((index: number) => {
121+
setOptionCount(count => count + 1);
120122
if (index === 0 && highlightFirstRef.current) {
121123
highlightFirstRef.current = false;
122124
setActiveIndex(0);
123125
}
126+
return () => setOptionCount(count => count - 1);
124127
}, []);
125128
const registerSelectedIndex = useCallback((index: number, value: string, label: string, selected: boolean) => {
126129
labelsByValueRef.current.set(value, label);
@@ -204,6 +207,10 @@ function ComboboxInner(props: ComboboxProps) {
204207
const { getReferenceProps, getFloatingProps, getItemProps } = useInteractions([dismiss, role, listNav]);
205208
const referenceProps = getReferenceProps();
206209
const popupId = typeof referenceProps['aria-controls'] === 'string' ? referenceProps['aria-controls'] : undefined;
210+
const activeOptionId =
211+
open && popupId !== undefined && activeIndex !== null && activeIndex < optionCount
212+
? `${popupId}-${activeIndex}`
213+
: undefined;
207214

208215
const focusInput = useCallback(() => {
209216
const input = refs.domReference.current;
@@ -269,6 +276,7 @@ function ComboboxInner(props: ComboboxProps) {
269276
setOpen,
270277
focusInput,
271278
popupId,
279+
activeOptionId,
272280
mounted,
273281
transitionProps,
274282
}),
@@ -290,6 +298,7 @@ function ComboboxInner(props: ComboboxProps) {
290298
setOpen,
291299
focusInput,
292300
popupId,
301+
activeOptionId,
293302
mounted,
294303
transitionProps,
295304
],
@@ -303,8 +312,9 @@ function ComboboxInner(props: ComboboxProps) {
303312
valuesByIndexRef,
304313
registerSelectedIndex,
305314
registerOption,
315+
popupId,
306316
}),
307-
[getItemProps, handleSelect, refs, registerSelectedIndex, registerOption],
317+
[getItemProps, handleSelect, refs, registerSelectedIndex, registerOption, popupId],
308318
);
309319

310320
const highlightContextValue = useMemo<ComboboxHighlightContextValue>(

‎packages/mosaic/src/primitives/combobox/combobox.test.tsx‎

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -529,6 +529,96 @@ describe('Combobox', () => {
529529
expect(screen.getByRole('option', { name: 'Banana' })).toHaveAttribute('data-selected');
530530
});
531531

532+
describe('active option reference while filtering a selection', () => {
533+
function FilteredPicker() {
534+
const [open, setOpen] = useState(false);
535+
const [value, setValue] = useState<string | null>('apple');
536+
return (
537+
<Combobox.Root
538+
inline
539+
open={open}
540+
onOpenChange={setOpen}
541+
value={value}
542+
onValueChange={setValue}
543+
>
544+
<button
545+
type='button'
546+
onClick={() => setOpen(!open)}
547+
>
548+
{value}
549+
</button>
550+
{open && (
551+
<>
552+
<Combobox.Input aria-label='Search fruit' />
553+
<Combobox.List>
554+
<Combobox.Collection
555+
items={fruits}
556+
itemToStringLabel={fruit => fruit.label}
557+
>
558+
{fruit => (
559+
<Combobox.Option
560+
key={fruit.value}
561+
value={fruit.value}
562+
label={fruit.label}
563+
>
564+
{fruit.label}
565+
</Combobox.Option>
566+
)}
567+
</Combobox.Collection>
568+
</Combobox.List>
569+
</>
570+
)}
571+
</Combobox.Root>
572+
);
573+
}
574+
575+
function expectActiveOption(name: string) {
576+
const reference = screen.getByRole('combobox').getAttribute('aria-activedescendant');
577+
expect(reference === null ? null : document.getElementById(reference)).toBe(
578+
screen.getByRole('option', { name }),
579+
);
580+
}
581+
582+
it('references the filtered option the input highlights, then selects it', async () => {
583+
const user = userEvent.setup();
584+
render(<FilteredPicker />);
585+
await user.click(screen.getByRole('button', { name: 'apple' }));
586+
expectActiveOption('Apple');
587+
588+
await user.type(screen.getByRole('combobox'), 'Ban');
589+
expect(screen.getAllByRole('option')).toHaveLength(1);
590+
expectActiveOption('Banana');
591+
592+
await user.keyboard('{ArrowDown}');
593+
expectActiveOption('Banana');
594+
await user.keyboard('{ArrowDown}');
595+
expectActiveOption('Banana');
596+
597+
await user.keyboard('{Enter}');
598+
expect(screen.getByRole('button', { name: 'banana' })).toBeInTheDocument();
599+
expect(screen.queryByRole('combobox')).not.toBeInTheDocument();
600+
});
601+
602+
it('drops the reference when filtering leaves no options, and references the selection on reopen', async () => {
603+
const user = userEvent.setup();
604+
render(<FilteredPicker />);
605+
await user.click(screen.getByRole('button', { name: 'apple' }));
606+
await user.type(screen.getByRole('combobox'), 'Ban');
607+
expectActiveOption('Banana');
608+
609+
await user.type(screen.getByRole('combobox'), 'x');
610+
expect(screen.queryAllByRole('option')).toHaveLength(0);
611+
expect(screen.getByRole('combobox')).not.toHaveAttribute('aria-activedescendant');
612+
await user.keyboard('{ArrowDown}');
613+
expect(screen.getByRole('combobox')).not.toHaveAttribute('aria-activedescendant');
614+
615+
await user.click(screen.getByRole('button', { name: 'apple' }));
616+
await user.click(screen.getByRole('button', { name: 'apple' }));
617+
expect(screen.getByRole('combobox')).toHaveValue('');
618+
expectActiveOption('Apple');
619+
});
620+
});
621+
532622
it.each([true, false])('respects a controlled clearing request when accepted=%s', async accept => {
533623
const user = userEvent.setup();
534624
const onValueChange = vi.fn();

0 commit comments

Comments
 (0)