Skip to content
Open
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
Comment thread
petdud marked this conversation as resolved.
"type": "patch",
"comment": "fix: close Popover when focus escapes outside while trapFocus is enabled",
"packageName": "@fluentui/react-popover",
"email": "petrduda@microsoft.com",
"dependentChangeType": "patch"
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export type OnOpenChangeData = {
};

// @public
export type OpenPopoverEvents = MouseEvent | TouchEvent | React_2.FocusEvent<HTMLElement> | React_2.KeyboardEvent<HTMLElement> | React_2.MouseEvent<HTMLElement>;
export type OpenPopoverEvents = MouseEvent | TouchEvent | FocusEvent | React_2.FocusEvent<HTMLElement> | React_2.KeyboardEvent<HTMLElement> | React_2.MouseEvent<HTMLElement>;

// @public
export const Popover: React_2.FC<PopoverProps>;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -453,6 +453,108 @@ describe('Popover', () => {
cy.contains('Two').should('have.focus');
});
});

describe('close on focus escape', () => {
it('should close when focus is programmatically moved outside', () => {
mount(
<>
<button id="outside">Outside</button>
<Popover trapFocus>
<PopoverTrigger disableButtonEnhancement>
<button>Popover trigger</button>
</PopoverTrigger>
<PopoverSurface>
<button>Inside</button>
</PopoverSurface>
</Popover>
</>,
);

cy.get(popoverTriggerSelector).click();
cy.get(popoverInteractiveContentSelector).should('be.visible');
cy.get('#outside').focus();
cy.get(popoverInteractiveContentSelector).should('not.exist');
});

it('should close with inertTrapFocus when focus is programmatically moved outside', () => {
mount(
<>
<button id="outside">Outside</button>
<Popover trapFocus inertTrapFocus>
<PopoverTrigger disableButtonEnhancement>
<button>Popover trigger</button>
</PopoverTrigger>
<PopoverSurface>
<button>Inside</button>
</PopoverSurface>
</Popover>
</>,
);

cy.get(popoverTriggerSelector).click();
cy.get(popoverInteractiveContentSelector).should('be.visible');
cy.get('#outside').focus();
cy.get(popoverInteractiveContentSelector).should('not.exist');
});

it('should not close without trapFocus when focus moves outside', () => {
mount(
<>
<button id="outside">Outside</button>
<Popover>
<PopoverTrigger disableButtonEnhancement>
<button>Popover trigger</button>
</PopoverTrigger>
<PopoverSurface>This is a popover</PopoverSurface>
</Popover>
</>,
);

cy.get(popoverTriggerSelector).click();
cy.get(popoverContentSelector).should('be.visible');
cy.get('#outside').focus();
cy.get(popoverContentSelector).should('be.visible');
});

it('should not close when closeOnFocusOutside is false', () => {
mount(
<>
<button id="outside">Outside</button>
<Popover trapFocus {...({ closeOnFocusOutside: false } as unknown as PopoverProps)}>
<PopoverTrigger disableButtonEnhancement>
<button>Popover trigger</button>
</PopoverTrigger>
<PopoverSurface>
<button>Inside</button>
</PopoverSurface>
</Popover>
</>,
);

cy.get(popoverTriggerSelector).click();
cy.get(popoverInteractiveContentSelector).should('be.visible');
cy.get('#outside').focus();
cy.get(popoverInteractiveContentSelector).should('be.visible');
});

it('should not close when focus moves to the trigger', () => {
mount(
<Popover trapFocus>
<PopoverTrigger disableButtonEnhancement>
<button>Popover trigger</button>
</PopoverTrigger>
<PopoverSurface>
<button>Inside</button>
</PopoverSurface>
</Popover>,
);

cy.get(popoverTriggerSelector).click();
cy.get(popoverInteractiveContentSelector).should('be.visible');
cy.get(popoverTriggerSelector).focus();
cy.get(popoverInteractiveContentSelector).should('be.visible');
});
});
});

describe('with Iframe', () => {
Expand Down
Comment thread
petdud marked this conversation as resolved.
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import * as React from 'react';
import { Popover } from './Popover';
import { renderHook } from '@testing-library/react-hooks';
import { renderHook, act } from '@testing-library/react-hooks';
import { usePopover_unstable } from './usePopover';
import { isConformant } from '../../testing/isConformant';
import type { PopoverProps } from './Popover.types';

describe('Popover', () => {
isConformant({
Expand Down Expand Up @@ -37,4 +38,182 @@ describe('Popover', () => {
// Assert
expect(result.current.withArrow).toBe(false);
});

describe('close on focus outside', () => {
it('should close when trapFocus is enabled and focus moves outside', () => {
const onOpenChange = jest.fn();
const outsideButton = document.createElement('button');
const popoverContent = document.createElement('div');
document.body.appendChild(outsideButton);
document.body.appendChild(popoverContent);

const { result } = renderHook(
({ open }) =>
usePopover_unstable({
open,
trapFocus: true,
onOpenChange,
children: <div />,
}),
{ initialProps: { open: true } },
);

// Set the contentRef to simulate mounted popover content
act(() => {
(result.current.contentRef as React.RefObject<HTMLElement | null>).current = popoverContent;
});

act(() => {
outsideButton.dispatchEvent(new FocusEvent('focusin', { bubbles: true }));
});

expect(onOpenChange).toHaveBeenCalledWith(expect.anything(), { open: false });

document.body.removeChild(outsideButton);
document.body.removeChild(popoverContent);
});

it('should not close when trapFocus is not enabled and focus moves outside', () => {
const onOpenChange = jest.fn();
const outsideButton = document.createElement('button');
document.body.appendChild(outsideButton);

renderHook(() =>
usePopover_unstable({
open: true,
trapFocus: false,
onOpenChange,
children: <div />,
}),
);

act(() => {
outsideButton.dispatchEvent(new FocusEvent('focusin', { bubbles: true }));
});

expect(onOpenChange).not.toHaveBeenCalled();

document.body.removeChild(outsideButton);
});

it('should not close when popover is not open', () => {
const onOpenChange = jest.fn();
const outsideButton = document.createElement('button');
document.body.appendChild(outsideButton);

renderHook(() =>
usePopover_unstable({
open: false,
trapFocus: true,
onOpenChange,
children: <div />,
}),
);

act(() => {
outsideButton.dispatchEvent(new FocusEvent('focusin', { bubbles: true }));
});

expect(onOpenChange).not.toHaveBeenCalled();

document.body.removeChild(outsideButton);
});

it('should also close when inertTrapFocus is enabled and focus moves to a page element outside', () => {
const onOpenChange = jest.fn();
const outsideButton = document.createElement('button');
const popoverContent = document.createElement('div');
document.body.appendChild(outsideButton);
document.body.appendChild(popoverContent);

const { result } = renderHook(() =>
usePopover_unstable({
open: true,
trapFocus: true,
inertTrapFocus: true,
onOpenChange,
children: <div />,
}),
);

act(() => {
(result.current.contentRef as React.RefObject<HTMLElement | null>).current = popoverContent;
});

act(() => {
outsideButton.dispatchEvent(new FocusEvent('focusin', { bubbles: true }));
});

expect(onOpenChange).toHaveBeenCalledWith(expect.anything(), { open: false });

document.body.removeChild(outsideButton);
document.body.removeChild(popoverContent);
});

it('should not close when closeOnFocusOutside is false', () => {
const onOpenChange = jest.fn();
const outsideButton = document.createElement('button');
const popoverContent = document.createElement('div');
document.body.appendChild(outsideButton);
document.body.appendChild(popoverContent);

const { result } = renderHook(
({ open }) =>
usePopover_unstable({
open,
trapFocus: true,
closeOnFocusOutside: false,
onOpenChange,
children: <div />,
} as unknown as PopoverProps),
{ initialProps: { open: true } },
);

act(() => {
(result.current.contentRef as React.RefObject<HTMLElement | null>).current = popoverContent;
});

act(() => {
outsideButton.dispatchEvent(new FocusEvent('focusin', { bubbles: true }));
});

expect(onOpenChange).not.toHaveBeenCalled();

document.body.removeChild(outsideButton);
document.body.removeChild(popoverContent);
});

it('should not close when focus moves to the trigger element', () => {
const onOpenChange = jest.fn();
const triggerButton = document.createElement('button');
const popoverContent = document.createElement('div');
document.body.appendChild(triggerButton);
document.body.appendChild(popoverContent);

const { result } = renderHook(
({ open }) =>
usePopover_unstable({
open,
trapFocus: true,
onOpenChange,
children: <div />,
}),
{ initialProps: { open: true } },
);

act(() => {
(result.current.contentRef as React.RefObject<HTMLElement | null>).current = popoverContent;
(result.current.triggerRef as React.RefObject<HTMLElement | null>).current = triggerButton;
});

act(() => {
triggerButton.dispatchEvent(new FocusEvent('focusin', { bubbles: true }));
});

expect(onOpenChange).not.toHaveBeenCalled();

document.body.removeChild(triggerButton);
document.body.removeChild(popoverContent);
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,7 @@ export type OnOpenChangeData = { open: boolean };
export type OpenPopoverEvents =
| MouseEvent
| TouchEvent
| FocusEvent
| React.FocusEvent<HTMLElement>
| React.KeyboardEvent<HTMLElement>
| React.MouseEvent<HTMLElement>;
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,39 @@ export const usePopoverBase_unstable = (props: PopoverBaseProps): PopoverBaseSta
disabled: !open || !closeOnScroll,
});

// When trapFocus is enabled, close the popover if focus is programmatically moved outside
// (e.g. via element.focus()), which doesn't trigger click or scroll dismiss handlers.
// Internal `closeOnFocusOutside` prop allows consumers to opt out during gradual rollout.
const closeOnFocusOutside =
(props as PopoverBaseProps & { closeOnFocusOutside?: boolean }).closeOnFocusOutside ?? true;

const closeOnFocusOutCallback = useEventCallback((ev: FocusEvent) => {
const target = (ev.composedPath()[0] ?? ev.target) as HTMLElement;
const contentElement = positioningRefs.contentRef.current;
const triggerElement = positioningRefs.triggerRef.current ?? null;

if (!contentElement) {
return;
}

const isOutside = !elementContains(contentElement, target) && !elementContains(triggerElement, target);

if (isOutside) {
setOpen(ev, false);
}
});

React.useEffect(() => {
if (!open || !props.trapFocus || !closeOnFocusOutside) {
return;
}

targetDocument?.addEventListener('focusin', closeOnFocusOutCallback, true);
return () => {
targetDocument?.removeEventListener('focusin', closeOnFocusOutCallback, true);
};
}, [open, props.trapFocus, closeOnFocusOutside, targetDocument, closeOnFocusOutCallback]);

const { findFirstFocusable } = useFocusFinders();
const activateModal = useActivateModal();

Expand Down
Loading