Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions packages/@adobe/react-spectrum/test/combobox/ComboBox.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1593,6 +1593,32 @@ describe('ComboBox', function () {
expect(queryByRole('listbox')).toBeFalsy();
});

it('does not close when pressing the popover outside of an option', async function () {
let {getByRole, getByTestId} = renderComboBox();
let combobox = getByRole('combobox');
await user.click(combobox);
await user.keyboard('{ArrowDown}');
act(() => {
jest.runAllTimers();
});
expect(getByRole('listbox')).toBeVisible();
onOpenChange.mockClear();

let popover = getByTestId('popover');
let notPrevented = fireEvent.mouseDown(popover);
fireEvent.mouseUp(popover);
expect(notPrevented).toBe(false);

await user.click(popover);
act(() => {
jest.runAllTimers();
});
expect(getByRole('listbox')).toBeVisible();
expect(combobox).toHaveFocus();
expect(onOpenChange).not.toHaveBeenCalled();
expect(onBlur).not.toHaveBeenCalled();
});

it('closes and commits custom value', async function () {
let {getByRole, queryByRole} = render(
<Provider theme={theme}>
Expand Down
42 changes: 42 additions & 0 deletions packages/react-aria-components/stories/ComboBox.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {ComboBox, ComboBoxProps, ComboBoxStateContext} from '../src/ComboBox';
import {Dialog, DialogTrigger} from '../src/Dialog';
import {Group} from '../src/Group';
import {Input} from '../src/Input';
import {Key} from '@react-types/shared';
import {Label} from '../src/Label';
import {ListBox} from '../src/ListBox';
import {ListBoxLoadMoreItem} from '../src/ListBox';
Expand Down Expand Up @@ -416,6 +417,47 @@ export const WithCreateOption = {
}
};

export const WithPopoverContent = {
render: function WithPopoverContent() {
let [selectedKey, setSelectedKey] = useState<Key | null>(null);

return (
<ComboBox selectedKey={selectedKey} onSelectionChange={setSelectedKey}>
<Label style={{display: 'block'}}>Favorite Animal</Label>
<div style={{display: 'flex'}}>
<Input />
<Button>
<span aria-hidden="true" style={{padding: '0 2px'}}>
▼
</span>
</Button>
</div>
<Popover
placement="bottom start"
style={{padding: 12, background: 'Canvas', border: '1px solid gray'}}>
<div style={{display: 'flex', gap: 24, marginBottom: 8}}>
<Button onPress={() => setSelectedKey(null)}>Reset selection</Button>
<button type="button">Native button</button>
</div>
<p style={{margin: '0 0 8px'}}>
Pressing the padding, this text, or the buttons keeps the popover open.
</p>
<input
aria-label="Note"
placeholder="A field that takes focus"
style={{marginBottom: 8}}
/>
<ListBox data-testid="combo-box-list-box" className={styles.menu}>
<MyListBoxItem id="cat">Cat</MyListBoxItem>
<MyListBoxItem id="dog">Dog</MyListBoxItem>
<MyListBoxItem id="kangaroo">Kangaroo</MyListBoxItem>
</ListBox>
</Popover>
</ComboBox>
);
}
};

export const ComboBoxListBoxItemWithAriaLabel: ComboBoxStory = {
render: () => (
<ComboBox name="combo-box-example" data-testid="combo-box-example" allowsEmptyCollection>
Expand Down
61 changes: 61 additions & 0 deletions packages/react-aria-components/test/ComboBox.browser.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
// Uses ComboBox which sets isNonModal: true so its Popover registers a
// document.addEventListener('scroll', ...) via useCloseOnScroll.

import {userEvent as browserUserEvent} from 'vitest/browser';
import {Button} from '../src/Button';
import {ComboBox} from '../src/ComboBox';
import {createRoot} from 'react-dom/client';
Expand Down Expand Up @@ -84,6 +85,66 @@ it('overlay closes when a scrollable light DOM ancestor scrolls', async () => {
document.body.removeChild(scrollable);
});

it('keeps the popover open when pressing a non-field part of it', async () => {
let container = document.createElement('div');
document.body.appendChild(container);
let root = createRoot(container);
root.render(
<>
<ComboBox>
<Label>Favorite Animal</Label>
<Input />
<Button>▼</Button>
<Popover data-testid="popover" style={{padding: 16}}>
<div data-testid="toolbar" style={{display: 'flex', gap: 40}}>
<Button>Reset selection</Button>
<button type="button">Another action</button>
</div>
<span>Some text</span>
<ListBox>
<ListBoxItem id="cat">Cat</ListBoxItem>
<ListBoxItem id="dog">Dog</ListBoxItem>
</ListBox>
</Popover>
</ComboBox>
<div>Outside</div>
</>
);
await new Promise<void>(resolve => setTimeout(resolve, 100));

let screen = within(container);
let input = screen.getByRole('combobox');
await browserUserEvent.click(input);
await browserUserEvent.keyboard('{ArrowDown}');
let popover = document.querySelector<HTMLElement>('[data-testid="popover"]')!;
let toolbar = popover.querySelector<HTMLElement>('[data-testid="toolbar"]')!;
let popoverScreen = within(popover);
let firstButton = popoverScreen.getByRole('button', {name: 'Reset selection'});
let gapX = firstButton.getBoundingClientRect().right - toolbar.getBoundingClientRect().left + 20;

let presses: Array<[Element, Parameters<typeof browserUserEvent.click>[1]]> = [
[popover, {position: {x: 4, y: 4}, force: true}],
[toolbar, {position: {x: gapX, y: toolbar.offsetHeight / 2}}],
[popoverScreen.getByText('Some text'), {}],
// WebKit doesn't focus a pressed native button.
[popoverScreen.getByRole('button', {name: 'Another action'}), {}],
[firstButton, {}]
];
for (let [target, options] of presses) {
await browserUserEvent.click(target, options);
await new Promise<void>(resolve => setTimeout(resolve, 50));
expect(document.querySelector('[role="listbox"]')).not.toBeNull();
expect(document.activeElement).toBe(input);
}

await browserUserEvent.click(screen.getByText('Outside'));
await new Promise<void>(resolve => setTimeout(resolve, 50));
expect(document.querySelector('[role="listbox"]')).toBeNull();

root.unmount();
document.body.removeChild(container);
});

describe('Shadow DOM', () => {
/**
* EnableShadowDOM must be called before mounting.
Expand Down
90 changes: 90 additions & 0 deletions packages/react-aria-components/test/ComboBox.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -753,6 +753,96 @@ describe('ComboBox', () => {
expect(comboboxTester.getCombobox()).toHaveValue('Apple');
});

describe('pressing inside the popover', () => {
let onPress = jest.fn();
let PopoverContentComboBox = props => (
<>
<ComboBox {...props}>
<Label>Favorite Animal</Label>
<Input />
<Button />
<Popover data-testid="popover">
<div data-testid="toolbar">
<Button onPress={onPress}>Reset selection</Button>
<Button>Another action</Button>
</div>
<span>Some text</span>
<input aria-label="Filter" />
<select aria-label="Sort">
<option>Name</option>
</select>
<input aria-label="Size" type="range" />
<ListBox>
<ListBoxItem id="1">Cat</ListBoxItem>
<ListBoxItem id="2">Dog</ListBoxItem>
</ListBox>
</Popover>
</ComboBox>
<span>Outside</span>
</>
);

it('should keep the popover open and focus in the input when pressing a non-field part', async () => {
let onBlur = jest.fn();
let {container, getByTestId, getByRole, getByText} = render(
<PopoverContentComboBox onBlur={onBlur} />
);
let comboboxTester = testUtilUser.createTester('ComboBox', {root: container});
let input = comboboxTester.getCombobox();
await user.click(input);
await user.keyboard('Ca');
expect(comboboxTester.getListbox()).toBeVisible();

let targets = [
getByTestId('popover'),
getByTestId('toolbar'),
getByRole('button', {name: 'Reset selection'}),
getByText('Some text')
];
for (let target of targets) {
let notPrevented = fireEvent.mouseDown(target);
fireEvent.mouseUp(target);
expect(notPrevented).toBe(false);

await user.click(target);
act(() => jest.runAllTimers());
expect(comboboxTester.getListbox()).toBeVisible();
expect(input).toHaveFocus();
expect(input).toHaveValue('Ca');
}

expect(onPress).toHaveBeenCalledTimes(1);
expect(onBlur).not.toHaveBeenCalled();

// Pressing outside still commits (resets the input since custom values aren't allowed) and closes.
await user.click(getByText('Outside'));
act(() => jest.runAllTimers());
expect(comboboxTester.getListbox()).toBeNull();
expect(onBlur).toHaveBeenCalledTimes(1);
expect(input).toHaveValue('');
});

it('should let fields inside the popover take focus', async () => {
let {container, getByLabelText} = render(<PopoverContentComboBox />);
let comboboxTester = testUtilUser.createTester('ComboBox', {root: container});
await comboboxTester.open();
expect(comboboxTester.getListbox()).toBeVisible();

for (let label of ['Filter', 'Sort', 'Size']) {
let field = getByLabelText(label);
let notPrevented = fireEvent.mouseDown(field);
fireEvent.mouseUp(field);
expect(notPrevented).toBe(true);
}

let filter = getByLabelText('Filter');
await user.click(filter);
act(() => jest.runAllTimers());
expect(filter).toHaveFocus();
expect(comboboxTester.getListbox()).toBeVisible();
});
});

it('should support multiple selection', async () => {
let onChange = jest.fn();
let {container, getByTestId} = render(
Expand Down
42 changes: 41 additions & 1 deletion packages/react-aria/src/combobox/useComboBox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,12 @@ import {
useRef,
useState
} from 'react';
import {getActiveElement, getEventTarget, nodeContains} from '../utils/shadowdom/DOMFunctions';
import {
getActiveElement,
getEventTarget,
getParentElement,
nodeContains
} from '../utils/shadowdom/DOMFunctions';
import {getChildNodes} from 'react-stately/private/collections/getChildNodes';
import {getItemCount} from 'react-stately/private/collections/getItemCount';
import {getItemId, listData} from '../listbox/utils';
Expand All @@ -61,6 +66,7 @@ import {useRouter} from '../utils/openLink';
import {useSelectableCollection} from '../selection/useSelectableCollection';
import {useTextField} from '../textfield/useTextField';
import {useUpdateEffect} from '../utils/useUpdateEffect';
import {willOpenKeyboard} from '../utils/keyboard';

export interface AriaComboBoxProps<T, M extends SelectionMode = 'single'>
extends ComboBoxProps<T, M>, DOMProps, InputDOMProps, AriaLabelingProps {
Expand Down Expand Up @@ -504,6 +510,26 @@ export function useComboBox<T, M extends SelectionMode = 'single'>(
: undefined
);

// Pressing a part of the popover that can't take focus (padding, text, or a native button in
// Safari) moves focus to the body, and the input's blur would commit and close the popover.
// Keep focus in the input, except for fields that need it. This is a native listener because
// usePress stops mousedown propagation. Skipped when the input is inside the popover (mobile trays).
useEvent(
popoverRef,
'mousedown',

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this wouldn't work for touch

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Which touch case do you mean? From what I understand, a tap still fires mousedown after touchend.
I made a codepen to test in real device (Google pixel 7a, chrome) (https://codepen.io/zecka/full/vEmLwzw) and with Playwright touch emulation, but I may be missing something.

state.isOpen
? e => {
let popover = popoverRef.current;
if (
!nodeContains(popover, inputRef.current) &&
!isFieldTarget(getEventTarget(e) as Element, popover)
) {
e.preventDefault();
}
}
: undefined
);

return {
labelProps: {
...labelProps,
Expand Down Expand Up @@ -559,6 +585,20 @@ export function useComboBox<T, M extends SelectionMode = 'single'>(
};
}

function isFieldTarget(target: Element | null, popover: Element | null): boolean {
for (let element = target; element && element !== popover; element = getParentElement(element)) {
if (

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i don't understand this if, why does it look for willOpenKeyboard? I'm imagining this is covering the same case as https://react-aria.adobe.com/ComboBox#item-actions but inside the popover there'd probably be some accessibility problems

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are two cases:

  1. Pressing the popover padding. It closes even without custom content, in S2 and v3 too.
  2. Pressing extra buttons outside the ListBox. I keep them out of keyboard navigation on purpose. I get that this may not be a valid pattern, but mouse and touch only is fine for my use case.

willOpenKeyboard only lets a text field in the popover take focus. Happy to drop it, or limit the PR to case 1.

willOpenKeyboard(element) ||
element instanceof HTMLSelectElement ||
(element instanceof HTMLInputElement && element.type === 'range')
) {
return true;
}
}

return false;
}

// This is a modified version of useSlotId that uses useEffect instead of useLayoutEffect.
// Triggering re-renders from useLayoutEffect breaks useComboBoxState's useEffect logic in React 18.
// These re-renders preempt async state updates in the useEffect, which ends up running multiple times
Expand Down