diff --git a/packages/@adobe/react-spectrum/test/combobox/ComboBox.test.js b/packages/@adobe/react-spectrum/test/combobox/ComboBox.test.js index 8d448ca1ec1..7286ba9fb26 100644 --- a/packages/@adobe/react-spectrum/test/combobox/ComboBox.test.js +++ b/packages/@adobe/react-spectrum/test/combobox/ComboBox.test.js @@ -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( diff --git a/packages/react-aria-components/stories/ComboBox.stories.tsx b/packages/react-aria-components/stories/ComboBox.stories.tsx index 5aad7ecb568..ef1ec4e5484 100644 --- a/packages/react-aria-components/stories/ComboBox.stories.tsx +++ b/packages/react-aria-components/stories/ComboBox.stories.tsx @@ -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'; @@ -416,6 +417,47 @@ export const WithCreateOption = { } }; +export const WithPopoverContent = { + render: function WithPopoverContent() { + let [selectedKey, setSelectedKey] = useState(null); + + return ( + + +
+ + +
+ +
+ + +
+

+ Pressing the padding, this text, or the buttons keeps the popover open. +

+ + + Cat + Dog + Kangaroo + +
+
+ ); + } +}; + export const ComboBoxListBoxItemWithAriaLabel: ComboBoxStory = { render: () => ( diff --git a/packages/react-aria-components/test/ComboBox.browser.test.tsx b/packages/react-aria-components/test/ComboBox.browser.test.tsx index 60f3f7e1adf..5dae80bdd50 100644 --- a/packages/react-aria-components/test/ComboBox.browser.test.tsx +++ b/packages/react-aria-components/test/ComboBox.browser.test.tsx @@ -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'; @@ -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( + <> + + + + + +
+ + +
+ Some text + + Cat + Dog + +
+
+
Outside
+ + ); + await new Promise(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('[data-testid="popover"]')!; + let toolbar = popover.querySelector('[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[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(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(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. diff --git a/packages/react-aria-components/test/ComboBox.test.js b/packages/react-aria-components/test/ComboBox.test.js index 8e2a6281e08..eabdaff33c2 100644 --- a/packages/react-aria-components/test/ComboBox.test.js +++ b/packages/react-aria-components/test/ComboBox.test.js @@ -753,6 +753,96 @@ describe('ComboBox', () => { expect(comboboxTester.getCombobox()).toHaveValue('Apple'); }); + describe('pressing inside the popover', () => { + let onPress = jest.fn(); + let PopoverContentComboBox = props => ( + <> + + + + + + + Some text + + + + + Cat + Dog + + + + Outside + + ); + + 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( + + ); + 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(); + 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( diff --git a/packages/react-aria/src/combobox/useComboBox.ts b/packages/react-aria/src/combobox/useComboBox.ts index cf23afd50ab..60fb6f0a003 100644 --- a/packages/react-aria/src/combobox/useComboBox.ts +++ b/packages/react-aria/src/combobox/useComboBox.ts @@ -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'; @@ -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 extends ComboBoxProps, DOMProps, InputDOMProps, AriaLabelingProps { @@ -504,6 +510,26 @@ export function useComboBox( : 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', + state.isOpen + ? e => { + let popover = popoverRef.current; + if ( + !nodeContains(popover, inputRef.current) && + !isFieldTarget(getEventTarget(e) as Element, popover) + ) { + e.preventDefault(); + } + } + : undefined + ); + return { labelProps: { ...labelProps, @@ -559,6 +585,20 @@ export function useComboBox( }; } +function isFieldTarget(target: Element | null, popover: Element | null): boolean { + for (let element = target; element && element !== popover; element = getParentElement(element)) { + if ( + 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