Skip to content

chore: Use inert in ariaHideOutside #8317

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jun 6, 2025
Merged
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
2 changes: 1 addition & 1 deletion packages/@react-aria/dnd/src/DragManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,7 @@ class DragSession {
this.dragTarget.element,
...validDropItems.flatMap(item => item.activateButtonRef?.current ? [item.element, item.activateButtonRef?.current] : [item.element]),
...visibleDropTargets.flatMap(target => target.activateButtonRef?.current ? [target.element, target.activateButtonRef?.current] : [target.element])
]);
], {shouldUseInert: true});

this.mutationObserver.observe(document.body, {subtree: true, attributes: true, attributeFilter: ['aria-hidden']});
}
Expand Down
2 changes: 0 additions & 2 deletions packages/@react-aria/focus/src/FocusScope.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ import {
} from '@react-aria/utils';
import {FocusableElement, RefObject} from '@react-types/shared';
import {focusSafely, getInteractionModality} from '@react-aria/interactions';
import {isElementVisible} from './isElementVisible';
import React, {JSX, ReactNode, useContext, useEffect, useMemo, useRef} from 'react';

export interface FocusScopeProps {
Expand Down Expand Up @@ -758,7 +757,6 @@ export function getFocusableTreeWalker(root: Element, opts?: FocusManagerOptions
}

if (filter(node as Element)
&& isElementVisible(node as Element)
&& (!scope || isElementInScope(node as Element, scope))
&& (!opts?.accept || opts.accept(node as Element))
) {
Expand Down
35 changes: 31 additions & 4 deletions packages/@react-aria/overlays/src/ariaHideOutside.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,15 @@
* governing permissions and limitations under the License.
*/

import {getOwnerWindow} from '@react-aria/utils';

const supportsInert = typeof HTMLElement !== 'undefined' && 'inert' in HTMLElement.prototype;

interface AriaHideOutsideOptions {
root?: Element,
shouldUseInert?: boolean
}

// Keeps a ref count of all hidden elements. Added to when hiding an element, and
// subtracted from when showing it again. When it reaches zero, aria-hidden is removed.
let refCountMap = new WeakMap<Element, number>();
Expand All @@ -29,10 +38,28 @@ let observerStack: Array<ObserverWrapper> = [];
* @param root - Nothing will be hidden above this element.
* @returns - A function to restore all hidden elements.
*/
export function ariaHideOutside(targets: Element[], root = document.body) {
export function ariaHideOutside(targets: Element[], options?: AriaHideOutsideOptions | Element) {
let windowObj = getOwnerWindow(targets?.[0]);
let opts = options instanceof windowObj.Element ? {root: options} : options;
let root = opts?.root ?? document.body;
let shouldUseInert = opts?.shouldUseInert && supportsInert;
let visibleNodes = new Set<Element>(targets);
let hiddenNodes = new Set<Element>();

let getHidden = (element: Element) => {
return shouldUseInert && element instanceof windowObj.HTMLElement ? element.inert : element.getAttribute('aria-hidden') === 'true';
};

let setHidden = (element: Element, hidden: boolean) => {
if (shouldUseInert && element instanceof windowObj.HTMLElement) {
element.inert = hidden;
} else if (hidden) {
element.setAttribute('aria-hidden', 'true');
} else {
element.removeAttribute('aria-hidden');
}
};

let walk = (root: Element) => {
// Keep live announcer and top layer elements (e.g. toasts) visible.
for (let element of root.querySelectorAll('[data-live-announcer], [data-react-aria-top-layer]')) {
Expand Down Expand Up @@ -87,12 +114,12 @@ export function ariaHideOutside(targets: Element[], root = document.body) {

// If already aria-hidden, and the ref count is zero, then this element
// was already hidden and there's nothing for us to do.
if (node.getAttribute('aria-hidden') === 'true' && refCount === 0) {
if (getHidden(node) && refCount === 0) {
return;
}

if (refCount === 0) {
node.setAttribute('aria-hidden', 'true');
setHidden(node, true);
}

hiddenNodes.add(node);
Expand Down Expand Up @@ -161,7 +188,7 @@ export function ariaHideOutside(targets: Element[], root = document.body) {
continue;
}
if (count === 1) {
node.removeAttribute('aria-hidden');
setHidden(node, false);
refCountMap.delete(node);
} else {
refCountMap.set(node, count - 1);
Expand Down
2 changes: 1 addition & 1 deletion packages/@react-aria/overlays/src/useModalOverlay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ export function useModalOverlay(props: AriaModalOverlayProps, state: OverlayTrig

useEffect(() => {
if (state.isOpen && ref.current) {
return ariaHideOutside([ref.current]);
return ariaHideOutside([ref.current], {shouldUseInert: true});
}
}, [state.isOpen, ref]);

Expand Down
7 changes: 4 additions & 3 deletions packages/@react-aria/overlays/src/usePopover.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,10 @@
import {ariaHideOutside, keepVisible} from './ariaHideOutside';
import {AriaPositionProps, useOverlayPosition} from './useOverlayPosition';
import {DOMAttributes, RefObject} from '@react-types/shared';
import {mergeProps, useLayoutEffect} from '@react-aria/utils';
import {mergeProps} from '@react-aria/utils';
import {OverlayTriggerState} from '@react-stately/overlays';
import {PlacementAxis} from '@react-types/overlays';
import {useEffect} from 'react';
import {useOverlay} from './useOverlay';
import {usePreventScroll} from './usePreventScroll';

Expand Down Expand Up @@ -113,12 +114,12 @@ export function usePopover(props: AriaPopoverProps, state: OverlayTriggerState):
isDisabled: isNonModal || !state.isOpen
});

useLayoutEffect(() => {
useEffect(() => {
if (state.isOpen && popoverRef.current) {
if (isNonModal) {
return keepVisible(groupRef?.current ?? popoverRef.current);
} else {
return ariaHideOutside([groupRef?.current ?? popoverRef.current]);
return ariaHideOutside([groupRef?.current ?? popoverRef.current], {shouldUseInert: true});
}
}
}, [isNonModal, state.isOpen, popoverRef, groupRef]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@
* governing permissions and limitations under the License.
*/

import {getOwnerWindow} from '@react-aria/utils';
import {getOwnerWindow} from './domHelpers';

const supportsCheckVisibility = typeof Element !== 'undefined' && 'checkVisibility' in Element.prototype;

function isStyleVisible(element: Element) {
const windowObject = getOwnerWindow(element);
Expand Down Expand Up @@ -60,6 +62,10 @@ function isAttributeVisible(element: Element, childElement?: Element) {
* @param element - Element to evaluate for display or visibility.
*/
export function isElementVisible(element: Element, childElement?: Element): boolean {
if (supportsCheckVisibility) {
return element.checkVisibility();
}

return (
element.nodeName !== '#comment' &&
isStyleVisible(element) &&
Expand Down
31 changes: 29 additions & 2 deletions packages/@react-aria/utils/src/isFocusable.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,17 @@
/*
* Copyright 2025 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/

import {isElementVisible} from './isElementVisible';

const focusableElements = [
'input:not([disabled]):not([type=hidden])',
'select:not([disabled])',
Expand All @@ -20,9 +34,22 @@ focusableElements.push('[tabindex]:not([tabindex="-1"]):not([disabled])');
const TABBABLE_ELEMENT_SELECTOR = focusableElements.join(':not([hidden]):not([tabindex="-1"]),');

export function isFocusable(element: Element): boolean {
return element.matches(FOCUSABLE_ELEMENT_SELECTOR);
return element.matches(FOCUSABLE_ELEMENT_SELECTOR) && isElementVisible(element) && !isInert(element);
}

export function isTabbable(element: Element): boolean {
return element.matches(TABBABLE_ELEMENT_SELECTOR);
return element.matches(TABBABLE_ELEMENT_SELECTOR) && isElementVisible(element) && !isInert(element);
}

function isInert(element: Element): boolean {
let node: Element | null = element;
while (node != null) {
if (node instanceof node.ownerDocument.defaultView!.HTMLElement && node.inert) {
return true;
}

node = node.parentElement;
}

return false;
}
50 changes: 0 additions & 50 deletions packages/@react-spectrum/dialog/test/DialogTrigger.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import {ActionButton, Button} from '@react-spectrum/button';
import {ButtonGroup} from '@react-spectrum/buttongroup';
import {Content} from '@react-spectrum/view';
import {Dialog, DialogTrigger} from '../';
import {Heading} from '@react-spectrum/text';
import {Item, Menu, MenuTrigger} from '@react-spectrum/menu';
import {Provider} from '@react-spectrum/provider';
import React from 'react';
Expand Down Expand Up @@ -977,55 +976,6 @@ describe('DialogTrigger', function () {
expect(document.activeElement).toBe(innerInput);
});

it('will not lose focus to body', async () => {
let {getByRole, getByTestId} = render(
<Provider theme={theme}>
<DialogTrigger type="popover">
<ActionButton>Trigger</ActionButton>
<Dialog>
<Heading>The Heading</Heading>
<Content>
<MenuTrigger>
<ActionButton data-testid="innerButton">Test</ActionButton>
<Menu autoFocus="first">
<Item>Item 1</Item>
<Item>Item 2</Item>
<Item>Item 3</Item>
</Menu>
</MenuTrigger>
</Content>
</Dialog>
</DialogTrigger>
</Provider>
);
let button = getByRole('button');
await user.click(button);

act(() => {
jest.runAllTimers();
});

let outerDialog = getByRole('dialog');

await waitFor(() => {
expect(outerDialog).toBeVisible();
}); // wait for animation
let innerButton = getByTestId('innerButton');
await user.tab();
fireEvent.keyDown(document.activeElement, {key: 'Enter'});
fireEvent.keyUp(document.activeElement, {key: 'Enter'});

act(() => {
jest.runAllTimers();
});
await user.tab();
act(() => {
jest.runAllTimers();
});

expect(document.activeElement).toBe(innerButton);
});

describe('portalContainer', () => {
function InfoDialog(props) {
let {container} = props;
Expand Down
3 changes: 2 additions & 1 deletion packages/@react-spectrum/menu/src/MenuTrigger.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,8 @@ export const MenuTrigger = forwardRef(function MenuTrigger(props: SpectrumMenuTr
scrollRef={menuRef}
placement={initialPlacement}
hideArrow
shouldFlip={shouldFlip}>
shouldFlip={shouldFlip}
shouldContainFocus>
{menu}
</Popover>
);
Expand Down
40 changes: 3 additions & 37 deletions packages/@react-spectrum/menu/test/MenuTrigger.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -809,7 +809,7 @@ describe('MenuTrigger', function () {
});
});

it('closes if menu is tabbed away from', async function () {
it('does not close if menu is tabbed away from', async function () {
let tree = render(
<Provider theme={theme}>
<MenuTrigger>
Expand All @@ -835,8 +835,8 @@ describe('MenuTrigger', function () {
await user.tab();
act(() => {jest.runAllTimers();});
act(() => {jest.runAllTimers();});
expect(menu).not.toBeInTheDocument();
expect(document.activeElement).toBe(menuTester.trigger);
expect(menu).toBeInTheDocument();
expect(document.activeElement).toBe(menuTester.options()[0]);
});
});

Expand Down Expand Up @@ -930,22 +930,6 @@ AriaMenuTests({
multipleSelection: () => render(
<SelectionStatic selectionMode="multiple" />
),
siblingFocusableElement: () => render(
<Provider theme={theme}>
<input aria-label="before" />
<MenuTrigger>
<Button variant="primary">
{triggerText}
</Button>
<Menu>
<Item id="1">One</Item>
<Item id="2">Two</Item>
<Item id="3">Three</Item>
</Menu>
</MenuTrigger>
<input aria-label="after" />
</Provider>
),
multipleMenus: () => render(
<Provider theme={theme}>
<MenuTrigger>
Expand Down Expand Up @@ -1082,24 +1066,6 @@ AriaMenuTests({
multipleSelection: () => render(
<SelectionStatic selectionMode="multiple" />
),
siblingFocusableElement: () => render(
<Provider theme={theme}>
<input aria-label="before" />
<MenuTrigger>
<Button variant="primary">
{triggerText}
</Button>
<Menu items={ariaWithSection}>
{item => (
<Section key={item.name} items={item.children} title={item.name}>
{item => <Item key={item.name} childItems={item.children}>{item.name}</Item>}
</Section>
)}
</Menu>
</MenuTrigger>
<input aria-label="after" />
</Provider>
),
multipleMenus: () => render(
<Provider theme={theme}>
<MenuTrigger>
Expand Down
3 changes: 2 additions & 1 deletion packages/@react-spectrum/overlays/src/Overlay.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export const Overlay = React.forwardRef(function Overlay(props: OverlayProps, re
children,
isOpen,
disableFocusManagement,
shouldContainFocus,
container,
onEnter,
onEntering,
Expand Down Expand Up @@ -56,7 +57,7 @@ export const Overlay = React.forwardRef(function Overlay(props: OverlayProps, re
}

return (
<ReactAriaOverlay portalContainer={container} disableFocusManagement={disableFocusManagement} isExiting={!isOpen}>
<ReactAriaOverlay portalContainer={container} disableFocusManagement={disableFocusManagement} shouldContainFocus={shouldContainFocus} isExiting={!isOpen}>
<Provider ref={ref} UNSAFE_style={{background: 'transparent', isolation: 'isolate'}} isDisabled={false}>
<OpenTransition
in={isOpen}
Expand Down
3 changes: 2 additions & 1 deletion packages/@react-spectrum/picker/src/Picker.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,8 @@ export const Picker = React.forwardRef(function Picker<T extends object>(props:
hideArrow
state={state}
triggerRef={unwrappedTriggerRef}
scrollRef={listboxRef}>
scrollRef={listboxRef}
shouldContainFocus>
{listbox}
</Popover>
);
Expand Down
Loading