An open source design system that's fully customizable and agent ready
TypeScript
fix(SideNav): focus on a row the collapsed rail removes moves to the collapse toggle or the nearest rail row (#9249)
Cindy Zhang372a0eae2c80
diff --git a/.changeset/sidenav-collapse-keeps-focus.md b/.changeset/sidenav-collapse-keeps-focus.mdnew file mode 100644index 0000000000..c8793971ec--- /dev/null+++ b/.changeset/sidenav-collapse-keeps-focus.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] When a collapsible `SideNav` collapses and takes the keyboard focus with it, focus now moves instead of falling to the page, where a keyboard or screen-reader user lost their place (WCAG 2.2 SC 2.4.3). From a row the collapsed rail does not render, such as an item without an icon, focus moves to the collapse toggle, or, with no toggle in the SideNav, to the nearest row still in the rail. On a row the rail keeps, focus stays on that row, and a header or footer control the collapse re-renders under the same name keeps it. From a header or footer control the collapse removes or renames, or the resize handle of a `resizable` SideNav, focus moves to the collapse toggle, or, with none, to the first row. Focus the collapse does not take is not moved.++@cixzhang @duytbpdiff --git a/apps/storybook/stories/SideNav.stories.tsx b/apps/storybook/stories/SideNav.stories.tsxindex 8e3772b50c..9bec8f05ee 100644--- a/apps/storybook/stories/SideNav.stories.tsx+++ b/apps/storybook/stories/SideNav.stories.tsx@@ -1,5 +1,6 @@// Copyright (c) Meta Platforms, Inc. and affiliates.+import {useEffect, useState} from 'react';import type {Meta, StoryObj} from '@storybook/react';import {AppShell} from '@astryxdesign/core/AppShell';import {@@ -845,3 +846,53 @@ export const IconlessNestedItems: Story = {</SideNav>),};++// =============================================================================+// Collapse with focus on a row the rail does not render (AR3)+// =============================================================================++/**+ * The app collapses the rail from a keyboard shortcut (`[`), which leaves+ * focus where it was. Focus on "Reports", which has no icon and so is not in+ * the collapsed rail, moves to the collapse toggle, or, with none, to the+ * nearest row still in the rail; focus elsewhere stays put.+ */+function CollapseFocusDemo({hasButton}: {hasButton: boolean}) {+ const [isCollapsed, setIsCollapsed] = useState(false);+ useEffect(() => {+ const onKeyDown = (event: KeyboardEvent) => {+ if (event.key === '[') {+ setIsCollapsed(collapsed => !collapsed);+ }+ };+ document.addEventListener('keydown', onKeyDown);+ return () => document.removeEventListener('keydown', onKeyDown);+ }, []);+ return (+ <div style={{display: 'flex', gap: 16, height: 360}}>+ <SideNav+ collapsible={{+ isCollapsed,+ onCollapsedChange: setIsCollapsed,+ hasButton,+ }}>+ <SideNavSection title="Main">+ <SideNavItem label="Dashboard" icon={HomeIcon} href="/dashboard" />+ <SideNavItem label="Reports" href="/reports" />+ <SideNavItem label="Team" icon={UserGroupIcon} href="/team" />+ </SideNavSection>+ </SideNav>+ <Button label="Elsewhere" variant="secondary" />+ </div>+ );+}++export const CollapseFocus: Story = {+ name: 'Collapse Focus',+ render: () => <CollapseFocusDemo hasButton />,+};++export const CollapseFocusWithoutToggle: Story = {+ name: 'Collapse Focus Without Toggle',+ render: () => <CollapseFocusDemo hasButton={false} />,+};diff --git a/docs/specs/components/SideNav/SideNav.spec.md b/docs/specs/components/SideNav/SideNav.spec.mdindex a9b0505ea8..8ec777de32 100644--- a/docs/specs/components/SideNav/SideNav.spec.md+++ b/docs/specs/components/SideNav/SideNav.spec.md@@ -101,7 +101,8 @@ Consumer migration instructions belong in consumer docs and release notes.SideNavItem — owned by the product callsite.- SideNavHeading — owned by `component:SideNavHeading`; SideNavCollapseButton —owned by `component:SideNavCollapseButton`.-- The SideNav header, footer, and resize zones.+- The layout of the SideNav header, footer, and resize zones (their focus+ across a collapse is AR3).## Public concepts@@ -160,6 +161,18 @@ Consumer migration instructions belong in consumer docs and release notes.accessible name, state, DOM order, or tab order.- **AR2 — Visible focus.** A nested row's focus indicator MUST paint in full atevery depth (FR5).+- **AR3 — Focus leaves what the collapsed rail removes.** When the rail+ collapses and the focused element goes with it, focus moves. On a row the+ rail keeps (its link replaced, its expand toggle or row actions gone), it+ moves to that row's control. From a row the rail does not render (a row+ without an icon or a nested row, FR2), it moves to the collapse toggle+ rendered inside the SideNav, or, with none, to the nearest row the rail+ keeps, the preceding one first. A header or footer control the collapse+ re-renders under the same accessible name keeps focus. From a header or+ footer control the collapse removes or renames (a heading link whose+ subheading the rail drops), or the resize handle, focus moves to the+ collapse toggle, or, with none, to the first row the rail keeps. Focus the collapse does not take is not moved (WCAG 2.2+ SC 2.4.3).## Design relationships@@ -195,16 +208,17 @@ Consumer migration instructions belong in consumer docs and release notes.## Verification map-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |-| --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------ |-| FR1, FR2 | `SideNav.test.tsx` nesting, collapsible, and collapsed-rail suites | Nested, collapsible, collapsed rail, flyout | Removing the labelled group, its collapsed inert state, or the collapsed icon-only and flyout paths fails. | `audit:SideNav/anatomy` |-| FR3, ORD1 | Focused `SideNav.test.tsx` indent coverage, required with implementation | Depth 1 and 2; `sm` and `md`; split and actions rows; caller `style`; flyout | A group inset, a missing or wrong indent, a dropped caller `style`, an indent that overrides a caller-set inline-start padding, or an indented flyout top level fails. | `audit:SideNav/layout` |-| FR3, DD1 | Real-browser geometry over the SideNav nested stories | Depths 1–3; `sm`, `md`, `lg`; light and dark; right-to-left; mobile drawer | A nested row's box narrower than a top-level row's, or a label moved from its per-depth position, fails. | `audit:SideNav/layout` |-| FR4 | Real-browser click in the indent area of plain, split, and actions rows | Link and button rows; plain, modified, and middle clicks; nested rows with toggle and actions | A click in the indent that does nothing or differs from the same click on the primary element, or a toggle or action that activates the row, fails. | `audit:SideNav/behavior` |-| FR5, AR2 | `SideNav.test.tsx` group clipping case and real-browser keyboard focus on nested rows | Only-child and last nested rows; after opening; collapsed | A focus ring cut at any edge of an expanded group, or an expanded group that still clips, fails. | `audit:SideNav/a11y` |-| FR2, FR3 | Real-browser collapsed rail and flyout | Collapsed rail with nested children | Any change to the collapsed rail, or an indent on the flyout's top level, fails. | `audit:SideNav/layout` |-| AR1 | Accessibility-tree comparison of nested rows | Plain, split, and actions rows | Any change in role, name, state, or order fails. | `audit:SideNav/a11y` |-| FR6 | `SideNavRailMotion.test.tsx`; `SideNavRailMotion.interaction.browser.spec.ts` frames of a collapse and an expand under a finger and a mouse (the `reducedMotion: 'always'` theme case pending) | collapse and expand; a mouse and a finger; Reduce Motion under a coarse and under a fine primary pointer; a theme with `reducedMotion: 'always'`; a second toggle while the motion runs | an animated width, a collapse that does not end icons-only, an expand that does not end with its labels, a rail copy reachable by assistive technology or left after the motion ends, travel under Reduce Motion, anything but an opacity-only change of 200 ms or less under Reduce Motion on a coarse pointer (DR2), or any animated property under Reduce Motion on a fine pointer (DR3) fails | `audit:SideNav/behavior` |+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------ |+| FR1, FR2 | `SideNav.test.tsx` nesting, collapsible, and collapsed-rail suites | Nested, collapsible, collapsed rail, flyout | Removing the labelled group, its collapsed inert state, or the collapsed icon-only and flyout paths fails. | `audit:SideNav/anatomy` |+| FR3, ORD1 | Focused `SideNav.test.tsx` indent coverage, required with implementation | Depth 1 and 2; `sm` and `md`; split and actions rows; caller `style`; flyout | A group inset, a missing or wrong indent, a dropped caller `style`, an indent that overrides a caller-set inline-start padding, or an indented flyout top level fails. | `audit:SideNav/layout` |+| FR3, DD1 | Real-browser geometry over the SideNav nested stories | Depths 1–3; `sm`, `md`, `lg`; light and dark; right-to-left; mobile drawer | A nested row's box narrower than a top-level row's, or a label moved from its per-depth position, fails. | `audit:SideNav/layout` |+| FR4 | Real-browser click in the indent area of plain, split, and actions rows | Link and button rows; plain, modified, and middle clicks; nested rows with toggle and actions | A click in the indent that does nothing or differs from the same click on the primary element, or a toggle or action that activates the row, fails. | `audit:SideNav/behavior` |+| FR5, AR2 | `SideNav.test.tsx` group clipping case and real-browser keyboard focus on nested rows | Only-child and last nested rows; after opening; collapsed | A focus ring cut at any edge of an expanded group, or an expanded group that still clips, fails. | `audit:SideNav/a11y` |+| FR2, FR3 | Real-browser collapsed rail and flyout | Collapsed rail with nested children | Any change to the collapsed rail, or an indent on the flyout's top level, fails. | `audit:SideNav/layout` |+| AR1 | Accessibility-tree comparison of nested rows | Plain, split, and actions rows | Any change in role, name, state, or order fails. | `audit:SideNav/a11y` |+| FR6 | `SideNavRailMotion.test.tsx`; `SideNavRailMotion.interaction.browser.spec.ts` frames of a collapse and an expand under a finger and a mouse (the `reducedMotion: 'always'` theme case pending) | collapse and expand; a mouse and a finger; Reduce Motion under a coarse and under a fine primary pointer; a theme with `reducedMotion: 'always'`; a second toggle while the motion runs | an animated width, a collapse that does not end icons-only, an expand that does not end with its labels, a rail copy reachable by assistive technology or left after the motion ends, travel under Reduce Motion, anything but an opacity-only change of 200 ms or less under Reduce Motion on a coarse pointer (DR2), or any animated property under Reduce Motion on a fine pointer (DR3) fails | `audit:SideNav/behavior` |+| AR3 | `SideNav.test.tsx` collapse-focus suite; `SideNavCollapseFocus.a11y.chromium.spec.ts` | Focus on an icon-less row with and without a toggle, also in a resizable SideNav; a nested row and a kept row's action without a toggle; a kept row's replaced link with a toggle; a footer control, the toggle and Enter on the resize handle in a resizable SideNav; an icon-less heading link the collapse removes; a heading link with a subheading in a resizable SideNav; focus outside the nav; focus on a row the rail keeps; expanding | Focus left on the page body, a move to anything but the kept row's own control, the same header or footer control under the same name, the in-nav toggle, or the nearest kept row (preceding first; the first from a removed header or footer control or the resize handle), or a move of focus the collapse did not take, fails. | `audit:SideNav/a11y` |## Decision logdiff --git a/packages/core/src/DropdownMenu/DropdownMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenu.tsxindex e9075c67ef..abfdc88eb4 100644--- a/packages/core/src/DropdownMenu/DropdownMenu.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenu.tsx@@ -44,6 +44,7 @@ import React, {useState,type ReactNode,} from 'react';+import {readAccessibleName} from '../utils/accessibleName';import * as stylex from '@stylexjs/stylex';import {usePopover} from '../Popover/usePopover';import {Button, type ButtonProps} from '../Button';@@ -526,77 +527,6 @@ function holdInvokerThroughPress(doc.addEventListener('pointercancel', onPressEnd, true);}-/** Text an assistive technology reads from `element`, `aria-hidden` left out. */-function visibleText(element: Element): string {- const copy = element.cloneNode(true) as Element;- for (const hidden of copy.querySelectorAll('[aria-hidden="true"]')) {- hidden.remove();- }- // An icon-only control is named by its image's alt, an inner aria-label, or- // an svg title rather than by text, so those count as its contents too.- for (const named of copy.querySelectorAll('img[alt], [aria-label]')) {- const name =- named.getAttribute(named.tagName === 'IMG' ? 'alt' : 'aria-label') ?? '';- named.replaceWith(copy.ownerDocument.createTextNode(` ${name} `));- }- for (const svg of copy.querySelectorAll('svg')) {- const title = svg.querySelector('title')?.textContent ?? '';- svg.replaceWith(copy.ownerDocument.createTextNode(` ${title} `));- }- return (copy.textContent ?? '').replace(/\s+/g, ' ').trim();-}--/**- * The name a custom trigger gives the menu it labels (`aria-labelledby` on- * the menu points at it): its own `aria-labelledby` targets, its- * `aria-label`, its text, or its `title`, in that order.- */-function readAccessibleName(element: HTMLElement | null): string | undefined {- if (element == null) {- return undefined;- }- const labelledBy = element.getAttribute('aria-labelledby');- if (labelledBy != null && labelledBy.trim() !== '') {- const text = labelledBy- .split(/\s+/)- .map(id => element.ownerDocument.getElementById(id))- .filter((node): node is HTMLElement => node != null)- .map(visibleText)- .join(' ')- .trim();- if (text !== '') {- return text;- }- }- const label = element.getAttribute('aria-label')?.trim();- if (label) {- return label;- }- // A form control is named by its own <label>s; an input button by its value.- const labels =- 'labels' in element- ? Array.from((element as HTMLInputElement).labels ?? [])- : [];- const labelText = labels.map(visibleText).join(' ').trim();- if (labelText !== '') {- return labelText;- }- if (- element instanceof HTMLInputElement &&- ['button', 'submit', 'reset'].includes(element.getAttribute('type') ?? '')- ) {- const value = element.value.trim();- if (value !== '') {- return value;- }- }- const text = visibleText(element);- if (text !== '') {- return text;- }- return element.getAttribute('title')?.trim() || undefined;-}-function DropdownMenuBottomSheet({button: buttonFromProps,renderTrigger,diff --git a/packages/core/src/SideNav/SideNav.test.tsx b/packages/core/src/SideNav/SideNav.test.tsxindex 86d2702b07..e0b2bd6306 100644--- a/packages/core/src/SideNav/SideNav.test.tsx+++ b/packages/core/src/SideNav/SideNav.test.tsx@@ -4273,3 +4273,287 @@ describe('SideNavItem collapsed-from-mount rail tooltip', () => {expect(spy).not.toHaveBeenCalled();});});++// =============================================================================+// Collapse with focus on a row the rail does not render (AR3)+// =============================================================================++describe('SideNav collapse focus (AR3)', () => {+ function Rail({+ isCollapsed,+ hasButton = true,+ }: {+ isCollapsed: boolean;+ hasButton?: boolean;+ }) {+ return (+ <>+ <SideNav+ collapsible={{isCollapsed, onCollapsedChange: () => {}, hasButton}}>+ <SideNavSection title="Main">+ <SideNavItem label="Dashboard" icon={StubIcon} href="/dashboard" />+ <SideNavItem label="Reports" href="/reports" />+ <SideNavItem label="Team" icon={StubIcon} href="/team" />+ </SideNavSection>+ </SideNav>+ <button type="button">Elsewhere</button>+ </>+ );+ }++ it('moves focus from a row the collapsed rail removes to the collapse toggle', () => {+ const {rerender} = render(<Rail isCollapsed={false} />);+ screen.getByRole('link', {name: 'Reports'}).focus();+ rerender(<Rail isCollapsed />);+ expect(screen.queryByRole('link', {name: 'Reports'})).toBeNull();+ expect(screen.getByRole('button', {name: 'Expand sidebar'})).toHaveFocus();+ });++ it('moves focus to the nearest row still in the rail when there is no toggle', () => {+ const {rerender} = render(<Rail isCollapsed={false} hasButton={false} />);+ screen.getByRole('link', {name: 'Reports'}).focus();+ rerender(<Rail isCollapsed hasButton={false} />);+ expect(screen.getByRole('link', {name: 'Dashboard'})).toHaveFocus();+ });++ it('moves no focus that is outside the removed rows', () => {+ const {rerender} = render(<Rail isCollapsed={false} />);+ const elsewhere = screen.getByRole('button', {name: 'Elsewhere'});+ elsewhere.focus();+ rerender(<Rail isCollapsed />);+ expect(elsewhere).toHaveFocus();+ });++ it('moves no focus from a row the collapsed rail keeps', () => {+ const {rerender} = render(<Rail isCollapsed={false} />);+ const team = screen.getByRole('link', {name: 'Team'});+ team.focus();+ rerender(<Rail isCollapsed />);+ expect(screen.getByRole('link', {name: 'Team'})).toHaveFocus();+ });++ it("moves focus from a nested row to its parent's trigger, which the rail keeps, when there is no toggle", () => {+ const nested = (isCollapsed: boolean) => (+ <SideNav+ collapsible={{+ isCollapsed,+ onCollapsedChange: () => {},+ hasButton: false,+ }}>+ <SideNavItem label="Dashboard" icon={StubIcon} href="/dashboard" />+ <SideNavItem label="Settings" icon={StubIcon} collapsible>+ <SideNavItem label="Billing" href="/settings/billing" />+ </SideNavItem>+ </SideNav>+ );+ const {rerender} = render(nested(false));+ screen.getByRole('link', {name: 'Billing'}).focus();+ rerender(nested(true));+ expect(screen.queryByRole('link', {name: 'Billing'})).toBeNull();+ expect(screen.getByRole('button', {name: 'Settings'})).toHaveFocus();+ });++ it("moves focus from a kept row's action, which the rail drops, to that row when there is no toggle", () => {+ const withAction = (isCollapsed: boolean) => (+ <SideNav+ collapsible={{+ isCollapsed,+ onCollapsedChange: () => {},+ hasButton: false,+ }}>+ <SideNavItem label="Dashboard" icon={StubIcon} href="/dashboard" />+ <SideNavItem+ label="Project"+ icon={StubIcon}+ href="/project"+ actions={+ <button type="button" aria-label="Project actions">+ ⋯+ </button>+ }+ />+ </SideNav>+ );+ const {rerender} = render(withAction(false));+ screen.getByRole('button', {name: 'Project actions'}).focus();+ rerender(withAction(true));+ expect(screen.queryByRole('button', {name: 'Project actions'})).toBeNull();+ expect(screen.getByRole('link', {name: 'Project'})).toHaveFocus();+ });++ it('moves focus to the nearest kept row in a resizable SideNav with no toggle, whose nav remounts as it collapses', () => {+ const resizable = (isCollapsed: boolean) => (+ <SideNav+ resizable+ collapsible={{+ isCollapsed,+ onCollapsedChange: () => {},+ hasButton: false,+ }}>+ <SideNavItem label="Dashboard" icon={StubIcon} href="/dashboard" />+ <SideNavItem label="Reports" href="/reports" />+ <SideNavItem label="Team" icon={StubIcon} href="/team" />+ </SideNav>+ );+ const {rerender} = render(resizable(false));+ screen.getByRole('link', {name: 'Reports'}).focus();+ rerender(resizable(true));+ expect(screen.getByRole('link', {name: 'Dashboard'})).toHaveFocus();+ });++ it('keeps focus on a kept row whose link the collapsed rail replaces, even with a toggle', () => {+ const withAction = (isCollapsed: boolean) => (+ <SideNav collapsible={{isCollapsed, onCollapsedChange: () => {}}}>+ <SideNavItem label="Dashboard" icon={StubIcon} href="/dashboard" />+ <SideNavItem+ label="Project"+ icon={StubIcon}+ href="/project"+ actions={+ <button type="button" aria-label="Project actions">+ ⋯+ </button>+ }+ />+ </SideNav>+ );+ const {rerender} = render(withAction(false));+ screen.getByRole('link', {name: 'Project'}).focus();+ rerender(withAction(true));+ expect(screen.getByRole('link', {name: 'Project'})).toHaveFocus();+ });++ it('keeps focus on a footer control or the toggle that a resizable collapse re-renders', () => {+ const resizable = (isCollapsed: boolean) => (+ <SideNav+ resizable+ collapsible={{isCollapsed, onCollapsedChange: () => {}}}+ footerIcons={+ <button type="button" aria-label="Help">+ ?+ </button>+ }>+ <SideNavItem label="Dashboard" icon={StubIcon} href="/dashboard" />+ <SideNavItem label="Reports" href="/reports" />+ </SideNav>+ );+ const {rerender} = render(resizable(false));+ screen.getByRole('button', {name: 'Help'}).focus();+ rerender(resizable(true));+ expect(screen.getByRole('button', {name: 'Help'})).toHaveFocus();+ rerender(resizable(false));+ screen.getByRole('button', {name: 'Collapse sidebar'}).focus();+ rerender(resizable(true));+ expect(screen.getByRole('button', {name: 'Expand sidebar'})).toHaveFocus();+ });++ it.each([+ {+ toggle: true,+ lands: () => screen.getByRole('button', {name: 'Expand sidebar'}),+ },+ {toggle: false, lands: () => screen.getByRole('link', {name: 'Dashboard'})},+ ])(+ 'moves focus from the resize handle that Enter collapses, toggle $toggle',+ async ({toggle, lands}) => {+ const user = userEvent.setup();+ render(+ <SideNav resizable collapsible={{hasButton: toggle}}>+ <SideNavItem label="Dashboard" icon={StubIcon} href="/dashboard" />+ <SideNavItem label="Reports" href="/reports" />+ </SideNav>,+ );+ screen.getByTestId('astryx-sidenav-resize-handle').focus();+ await user.keyboard('{Enter}');+ expect(screen.queryByTestId('astryx-sidenav-resize-handle')).toBeNull();+ expect(lands()).toHaveFocus();+ },+ );++ it.each([+ {+ toggle: true,+ lands: () => screen.getByRole('button', {name: 'Expand sidebar'}),+ },+ {toggle: false, lands: () => screen.getByRole('link', {name: 'Dashboard'})},+ ])(+ 'moves focus from an icon-less heading link the collapse removes, never to the control that takes its place, toggle $toggle',+ ({toggle, lands}) => {+ const rail = (isCollapsed: boolean) => (+ <SideNav+ collapsible={{+ isCollapsed,+ onCollapsedChange: () => {},+ hasButton: toggle,+ }}+ header={<SideNavHeading heading="My App" headingHref="/" />}+ topContent={<button type="button">New project</button>}+ footer={<a href="/help">Help</a>}>+ <SideNavItem label="Dashboard" icon={StubIcon} href="/dashboard" />+ </SideNav>+ );+ const {rerender} = render(rail(false));+ screen.getByRole('link', {name: 'My App'}).focus();+ rerender(rail(true));+ expect(screen.queryByRole('link', {name: 'My App'})).toBeNull();+ expect(lands()).toHaveFocus();+ },+ );++ it('moves focus from a heading link the collapse renames (its subheading dropped) to the toggle in a resizable SideNav', () => {+ const rail = (isCollapsed: boolean) => (+ <SideNav+ resizable+ collapsible={{isCollapsed, onCollapsedChange: () => {}}}+ header={+ <SideNavHeading+ icon={<span>A</span>}+ heading="Acme"+ subheading="Workspace"+ headingHref="/"+ />+ }>+ <SideNavItem label="Dashboard" icon={StubIcon} href="/dashboard" />+ </SideNav>+ );+ const {rerender} = render(rail(false));+ const heading = screen+ .getAllByRole('link')+ .find(link => link.getAttribute('href') === '/');+ heading?.focus();+ expect(heading).toHaveFocus();+ rerender(rail(true));+ expect(screen.getByRole('button', {name: 'Expand sidebar'})).toHaveFocus();+ });++ it('keeps focus on a heading link the resizable collapse re-renders under the same accessible name, aria-hidden icon text left out', () => {+ const rail = (isCollapsed: boolean) => (+ <SideNav+ resizable+ collapsible={{isCollapsed, onCollapsedChange: () => {}}}+ header={+ <SideNavHeading+ icon={<span aria-hidden="true">A</span>}+ heading="Acme"+ headingHref="/"+ />+ }>+ <SideNavItem label="Dashboard" icon={StubIcon} href="/dashboard" />+ </SideNav>+ );+ const {rerender} = render(rail(false));+ screen.getByRole('link', {name: 'Acme'}).focus();+ rerender(rail(true));+ expect(screen.getByRole('link', {name: 'Acme'})).toHaveFocus();+ });++ it('moves no focus when the rail expands', () => {+ const {rerender} = render(<Rail isCollapsed />);+ const toggle = screen.getByRole('button', {name: 'Expand sidebar'});+ toggle.focus();+ rerender(<Rail isCollapsed={false} />);+ expect(+ screen.getByRole('button', {name: 'Collapse sidebar'}),+ ).toHaveFocus();+ });+});diff --git a/packages/core/src/SideNav/SideNav.tsx b/packages/core/src/SideNav/SideNav.tsxindex 8057b051f9..31cb77302b 100644--- a/packages/core/src/SideNav/SideNav.tsx+++ b/packages/core/src/SideNav/SideNav.tsx@@ -56,6 +56,18 @@ import {useTranslator} from '../i18n';import {useMergedRefs} from '../hooks/useMergedRefs';import {LayoutChangeSnapshot} from '../motion/LayoutChangeSnapshot';+import {getFocusableElements} from '../hooks/useFocusTrap';+import {readAccessibleName} from '../utils/accessibleName';+import {+ moveFocusLeftBehind,+ noteFocusWithin,+ type FocusWithin,+} from '../utils/focusReturn';+import {useInteractionModalityTracking} from '../utils/interactionModality';+import {+ SideNavFocusTargetsContext,+ type SideNavFocusTargets,+} from './SideNavFocusTargetsContext';import {createRailLayout,playRail,@@ -462,7 +474,10 @@ export function SideNav({// nav needs an id; a consumer's own id wins.const generatedNavId = useId();const navId = props.id ?? generatedNavId;- const mergedNavRef = useMergedRefs(ref, navRef);+ // The nav's own document's last input decides the moved focus's ring+ // (AR3), so a SideNav in a second document tracks input there.+ const {ref: modalityRef} = useInteractionModalityTracking();+ const mergedNavRef = useMergedRefs(ref, navRef, modalityRef);const collapseStateRef = useRef<SideNavCollapseState>({isCollapsed: false,toggle: () => {},@@ -550,6 +565,127 @@ export function SideNav({[],);+ // Focus on something the collapsed rail does not render would fall to the+ // page when the rail collapses (`component:SideNav` AR3). On a row the rail+ // keeps (its link replaced, its expand toggle or row actions gone), focus+ // stays on that row's control; from a row the rail drops (no icon, or+ // nested), it moves to the rail's collapse toggle, or, with none, to the+ // nearest row the rail keeps. Rows and the toggle register through their+ // callback refs. Rows are matched across the commit by their place among+ // the rows the rail keeps, not by element: a resizable SideNav remounts its+ // nav when it collapses. Focus on a header or footer control that a+ // resizable collapse remounts goes back to the control with the same+ // accessible name. From one the collapse removes or renames, or the resize+ // handle, focus goes to the toggle, or, with none, to the first kept row.+ // Focus moves only if the collapse lost it.+ const rowsRef = useRef(new Map<HTMLElement, boolean>());+ const togglesRef = useRef(new Set<HTMLElement>());+ const focusTargets = useMemo<SideNavFocusTargets>(+ () => ({+ registerRow: (element, isKeptInRail) => {+ rowsRef.current.set(element, isKeptInRail);+ return () => {+ rowsRef.current.delete(element);+ };+ },+ registerToggle: element => {+ togglesRef.current.add(element);+ return () => {+ togglesRef.current.delete(element);+ };+ },+ }),+ [],+ );+ const resizeWrapperRef = useRef<HTMLDivElement>(null);+ const pendingFocusRef = useRef<{+ focus: FocusWithin;+ /** Whether the rail keeps the row that held focus. */+ isRowKept: boolean;+ /** Kept rows before the row that held focus. */+ keptBefore: number;+ /** The name of the control outside the rows that held focus. */+ outside: {name: string} | null;+ /** Whether focus was on the collapse toggle. */+ wasOnToggle: boolean;+ } | null>(null);+ const noteRailFocus = useCallback((wasCollapsed: boolean) => {+ pendingFocusRef.current = null;+ const nav = navRef.current;+ // The resize handle sits beside the nav, in the resize wrapper, and goes+ // with a collapse its Enter starts.+ const focus = wasCollapsed+ ? null+ : (noteFocusWithin(nav) ?? noteFocusWithin(resizeWrapperRef.current));+ if (focus == null || nav == null) {+ return;+ }+ const rows = railRows(nav, rowsRef.current);+ // The innermost row holding focus, the last in document order: a nested+ // row's parent holds it too.+ let index = -1;+ rows.forEach((row, at) => {+ if (row.contains(focus.element)) {+ index = at;+ }+ });+ let outside = null;+ if (index < 0) {+ const controls = controlsOutsideRows(nav, rows);+ const at = controls.findIndex(control => control.contains(focus.element));+ outside = at < 0 ? null : {name: controlName(controls[at])};+ }+ pendingFocusRef.current = {+ focus,+ outside,+ wasOnToggle: [...togglesRef.current].some(toggle =>+ toggle.contains(focus.element),+ ),+ isRowKept: index >= 0 && rowsRef.current.get(rows[index]) === true,+ keptBefore: rows+ .slice(0, Math.max(index, 0))+ .filter(row => rowsRef.current.get(row) === true).length,+ };+ }, []);+ useLayoutEffect(() => {+ const pending = pendingFocusRef.current;+ pendingFocusRef.current = null;+ const nav = navRef.current;+ if (pending == null || !collapsed || nav == null) {+ return;+ }+ // Collapsed, every row the nav renders is one the rail keeps, in order.+ const kept = railRows(nav, rowsRef.current);+ const controlOf = (row: HTMLElement | undefined) =>+ row == null ? undefined : getFocusableElements(row)[0];+ const toggle = [...togglesRef.current].find(element =>+ nav.contains(element),+ );+ let sameOutside: HTMLElement | undefined;+ if (pending.wasOnToggle) {+ sameOutside = toggle;+ } else if (pending.outside != null) {+ const controls = controlsOutsideRows(nav, kept);+ sameOutside = controls.find(+ control => controlName(control) === pending.outside?.name,+ );+ }+ const target = pending.isRowKept+ ? controlOf(kept[pending.keptBefore])+ : (sameOutside ??+ toggle ??+ controlOf(kept[pending.keptBefore - 1]) ??+ controlOf(kept[pending.keptBefore]));+ moveFocusLeftBehind(pending.focus, target);+ }, [collapsed]);+ const beforeRailChange = useCallback(+ (wasCollapsed: boolean) => {+ noteRailFocus(wasCollapsed);+ measureRail(wasCollapsed);+ },+ [noteRailFocus, measureRail],+ );+const toggle = useCallback(() => {const next = !collapsed;@@ -750,7 +886,7 @@ export function SideNav({// Uses ResizeHandle in overlay mode so the handle sits inside// the panel's overflow: clip bounds.const rail = showResizeHandle ? (- <div {...stylex.props(styles.resizableContainer)}>+ <div ref={resizeWrapperRef} {...stylex.props(styles.resizableContainer)}>{navElement}<ResizeHandledata-testid="astryx-sidenav-resize-handle"@@ -771,20 +907,55 @@ export function SideNav({// goes with the collapse it measures.const content = (<>- <LayoutChangeSnapshot value={collapsed} onBeforeChange={measureRail} />+ <LayoutChangeSnapshot+ value={collapsed}+ onBeforeChange={beforeRailChange}+ />{rail}</>);if (isCollapsible) {return (- <SideNavCollapseContext value={collapseContext}>- {content}- </SideNavCollapseContext>+ <SideNavFocusTargetsContext value={focusTargets}>+ <SideNavCollapseContext value={collapseContext}>+ {content}+ </SideNavCollapseContext>+ </SideNavFocusTargetsContext>);}return content;}+/** The focusable controls in `nav` outside every row: header and footer. */+function controlsOutsideRows(+ nav: HTMLElement,+ rows: HTMLElement[],+): HTMLElement[] {+ return getFocusableElements(nav).filter(+ control => !rows.some(row => row.contains(control)),+ );+}++/** A control's accessible name, so a re-rendered control is found again. */+function controlName(control: HTMLElement): string {+ return readAccessibleName(control) ?? '';+}++/**+ * The registered rows inside `nav`, in document order, leaving out rows in a+ * collapsed item's flyout, which is a layer of its own.+ */+function railRows(+ nav: HTMLElement,+ rows: ReadonlyMap<HTMLElement, boolean>,+): HTMLElement[] {+ return [...rows.keys()]+ .filter(row => nav.contains(row) && row.closest('[popover]') == null)+ .sort((a, b) =>+ a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1,+ );+}+SideNav.displayName = 'SideNav';diff --git a/packages/core/src/SideNav/SideNavCollapseButton.tsx b/packages/core/src/SideNav/SideNavCollapseButton.tsxindex 01612794a7..39cb2f5c12 100644--- a/packages/core/src/SideNav/SideNavCollapseButton.tsx+++ b/packages/core/src/SideNav/SideNavCollapseButton.tsx@@ -17,7 +17,7 @@* - /packages/cli/assets/templates/blocks/components/SideNav/ (showcase blocks)*/-import React, {useCallback, type ReactNode} from 'react';+import React, {use, useCallback, type ReactNode} from 'react';import * as stylex from '@stylexjs/stylex';import {durationVars, easeVars} from '../theme/tokens.stylex';import {Icon} from '../Icon';@@ -32,6 +32,8 @@ import {} from './SideNavCollapseContext';import {useAppShellMobile} from '../AppShell/AppShellMobileContext';import {useTranslator} from '../i18n';+import {useMergedRefs} from '../hooks/useMergedRefs';+import {SideNavFocusTargetsContext} from './SideNavFocusTargetsContext';import type {ElementSize} from '../SizeContext/SizeContext';// =============================================================================@@ -144,6 +146,20 @@ export function SideNavCollapseButton({handleRef,);const {isMobile} = useAppShellMobile();+ // A toggle inside its SideNav registers there, so a collapse that removes+ // the focused row can hand focus to it (`component:SideNav` AR3). One wired+ // to state outside the SideNav (`collapsible`, `handleRef`) does not.+ const focusTargets = use(SideNavFocusTargetsContext);+ const isInSideNav =+ focusTargets != null && collapsible == null && handleRef == null;+ const registerToggle = useCallback(+ (element: HTMLButtonElement | null) =>+ element == null || !isInSideNav || focusTargets == null+ ? undefined+ : focusTargets.registerToggle(element),+ [focusTargets, isInSideNav],+ );+ const mergedRef = useMergedRefs(ref, registerToggle);// Hide when not collapsible, or when in mobile mode (sidenav is in// the mobile drawer — collapse doesn't apply there)@@ -153,7 +169,7 @@ export function SideNavCollapseButton({return (<Button- ref={ref}+ ref={mergedRef}label={label ??(isCollapseddiff --git a/packages/core/src/SideNav/SideNavFocusTargetsContext.ts b/packages/core/src/SideNav/SideNavFocusTargetsContext.tsnew file mode 100644index 0000000000..090e71590a--- /dev/null+++ b/packages/core/src/SideNav/SideNavFocusTargetsContext.ts@@ -0,0 +1,29 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file SideNavFocusTargetsContext.ts+ * @input The SideNav rail's rows and its collapse toggle, registered by their+ * callback refs+ * @output Where focus goes when collapsing the rail removes the focused row+ * @position Internal to SideNav: not exported from the SideNav entry. SideNav+ * provides it; SideNavItem registers its row and SideNavCollapseButton,+ * rendered inside the SideNav, registers itself (`component:SideNav` AR3).+ */++import {createContext} from 'react';++export interface SideNavFocusTargets {+ /**+ * Registers a row's root element, and whether the collapsed rail renders+ * the row (it has an icon and is not nested); returns its unregister.+ */+ registerRow: (element: HTMLElement, isKeptInRail: boolean) => () => void;+ /** Registers a collapse toggle rendered inside the SideNav. */+ registerToggle: (element: HTMLElement) => () => void;+}++export const SideNavFocusTargetsContext =+ createContext<SideNavFocusTargets | null>(null);+SideNavFocusTargetsContext.displayName = 'SideNavFocusTargetsContext';diff --git a/packages/core/src/SideNav/SideNavItem.tsx b/packages/core/src/SideNav/SideNavItem.tsxindex 2bbebc6490..da66ca0f4a 100644--- a/packages/core/src/SideNav/SideNavItem.tsx+++ b/packages/core/src/SideNav/SideNavItem.tsx@@ -78,6 +78,7 @@ import {disabledInteractionProps} from '../utils/disabledInteraction';import {useTranslator} from '../i18n';import {useMergedRefs} from '../hooks/useMergedRefs';+import {SideNavFocusTargetsContext} from './SideNavFocusTargetsContext';// =============================================================================// Styles// =============================================================================@@ -559,6 +560,21 @@ export function SideNavItem({});const railLeafRef = useMergedRefs(ref, railTooltip.ref);+ // The row's root registers with its SideNav, so a collapse that removes the+ // focused row can hand focus to the toggle or the nearest row still in the+ // rail (`component:SideNav` AR3).+ const focusTargets = use(SideNavFocusTargetsContext);+ // The collapsed rail renders a top-level row with an icon (FR2).+ const isKeptInRail = !!icon && depth === 0;+ const rowRef = useCallback(+ (element: HTMLDivElement | null) =>+ element == null || focusTargets == null+ ? undefined+ : focusTargets.registerRow(element, isKeptInRail),+ [focusTargets, isKeptInRail],+ );+ const rowTooltipRef = useMergedRefs(rowRef, railTooltip.ref);+// Collapse state for items with childrenconst itemCollapsibleConfig = useMemo(() => (typeof itemCollapsible === 'object' ? itemCollapsible : {}),@@ -684,7 +700,7 @@ export function SideNavItem({// Items with children: popover trigger + popoverif (hasChildren) {return (- <div {...stylex.props(styles.root, xstyle)}>+ <div ref={rowRef} {...stylex.props(styles.root, xstyle)}><buttonref={mergedTriggerRef}type="button"@@ -749,7 +765,7 @@ export function SideNavItem({return (<div- ref={isRowTrigger ? railTooltip.ref : undefined}+ ref={isRowTrigger ? rowTooltipRef : rowRef}{...stylex.props(styles.root, xstyle)}>{collapsedElement}{railTooltip.renderTooltip(label)}@@ -942,7 +958,7 @@ export function SideNavItem({}const item = (- <div {...stylex.props(styles.root, xstyle)}>+ <div ref={rowRef} {...stylex.props(styles.root, xstyle)}>{itemElement}{hasChildren && !isCollapsed && (<divdiff --git a/packages/core/src/SideNav/__tests__/SideNavCollapseFocus.a11y.chromium.spec.ts b/packages/core/src/SideNav/__tests__/SideNavCollapseFocus.a11y.chromium.spec.tsnew file mode 100644index 0000000000..dac9d65593--- /dev/null+++ b/packages/core/src/SideNav/__tests__/SideNavCollapseFocus.a11y.chromium.spec.ts@@ -0,0 +1,79 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file SideNavCollapseFocus.a11y.chromium.spec.ts+ * @input The built Storybook's `Core/SideNav` collapse-focus stories: a+ * collapsible SideNav whose app collapses it from a `[` shortcut, with an+ * icon-less "Reports" row the collapsed rail does not render, and a button+ * outside the nav+ * @output Real-Chromium proof of `component:SideNav` AR3: focus on a row the+ * collapsed rail removes moves to the collapse toggle, or, with no toggle,+ * to the nearest row still in the rail; focus elsewhere is not moved+ * @position Testing; the unit cases are in SideNav.test.tsx+ *+ * SYNC: When modified, update the AR3 Verification row in SideNav.spec.md.+ */++import {expect, test, type Page} from '@playwright/test';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';++let storybook: StaticServer;++test.beforeAll(async () => {+ storybook = await serveStorybook(DEFAULT_STORYBOOK_DIR);+});++test.afterAll(async () => {+ await storybook?.close();+});++async function openStory(page: Page, story: string): Promise<void> {+ await page.goto(`${storybook.origin}/iframe.html?id=${story}&viewMode=story`);+ await page.getByRole('link', {name: 'Reports'}).waitFor();+}++test('focus on a row the collapsed rail removes moves to the collapse toggle', async ({+ page,+}) => {+ await openStory(page, 'core-sidenav--collapse-focus');+ const reports = page.getByRole('link', {name: 'Reports'});+ await reports.focus();+ await page.keyboard.press('[');++ await expect(reports).toHaveCount(0);+ await expect(+ page.getByRole('button', {name: 'Expand sidebar'}),+ ).toBeFocused();+});++test('without a toggle, focus moves to the nearest row still in the rail', async ({+ page,+}) => {+ await openStory(page, 'core-sidenav--collapse-focus-without-toggle');+ await page.getByRole('link', {name: 'Reports'}).focus();+ await page.keyboard.press('[');++ // Dashboard precedes Reports and keeps an icon-only row in the rail.+ await expect(page.getByRole('link', {name: 'Dashboard'})).toBeFocused();+});++test('focus outside the removed rows is not moved', async ({page}) => {+ await openStory(page, 'core-sidenav--collapse-focus');+ const elsewhere = page.getByRole('button', {name: 'Elsewhere'});+ await elsewhere.focus();+ await page.keyboard.press('[');++ await expect(page.getByRole('link', {name: 'Reports'})).toHaveCount(0);+ await expect(elsewhere).toBeFocused();++ // A row the rail keeps keeps its focus too.+ await page.keyboard.press('[');+ const team = page.getByRole('link', {name: 'Team'});+ await team.focus();+ await page.keyboard.press('[');+ await expect(team).toBeFocused();+});diff --git a/packages/core/src/hooks/useFocusTrap.ts b/packages/core/src/hooks/useFocusTrap.tsindex fb0a22df24..5a82d4e40f 100644--- a/packages/core/src/hooks/useFocusTrap.ts+++ b/packages/core/src/hooks/useFocusTrap.ts@@ -17,6 +17,7 @@*/import {useCallback, useEffect, useRef} from 'react';+import {isFocusLost} from '../utils/focusReturn';import {FOCUSABLE_SELECTOR} from './focusableSelector';import {useLayerDismissal} from '../Layer/useLayerDismissal';@@ -324,14 +325,7 @@ export function useFocusTrap<T extends HTMLElement = HTMLElement>(return;}- const active = doc.activeElement;- const focusWasLost =- active == null ||- active === doc.body ||- active === doc.documentElement ||- (container != null && container.contains(active));-- if (!focusWasLost) {+ if (!isFocusLost(container, doc)) {return;}diff --git a/packages/core/src/utils/accessibleName.ts b/packages/core/src/utils/accessibleName.tsnew file mode 100644index 0000000000..f403960be5--- /dev/null+++ b/packages/core/src/utils/accessibleName.ts@@ -0,0 +1,87 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file accessibleName.ts+ * @input A rendered element+ * @output The name an assistive technology reads for it, as far as the DOM+ * gives it: `aria-labelledby` targets, `aria-label`, its own labels, an+ * input button's value, its visible text (`aria-hidden` left out, an inner+ * image's alt, `aria-label` or svg title counted), then `title`+ * @position Internal utility, not exported from the package: DropdownMenu+ * names a menu after a custom trigger, and SideNav finds a re-rendered+ * header or footer control again by name (`component:SideNav` AR3)+ */++/** Text an assistive technology reads from `element`, `aria-hidden` left out. */+function visibleText(element: Element): string {+ const copy = element.cloneNode(true) as Element;+ for (const hidden of copy.querySelectorAll('[aria-hidden="true"]')) {+ hidden.remove();+ }+ // An icon-only control is named by its image's alt, an inner aria-label, or+ // an svg title rather than by text, so those count as its contents too.+ for (const named of copy.querySelectorAll('img[alt], [aria-label]')) {+ const name =+ named.getAttribute(named.tagName === 'IMG' ? 'alt' : 'aria-label') ?? '';+ named.replaceWith(copy.ownerDocument.createTextNode(` ${name} `));+ }+ for (const svg of copy.querySelectorAll('svg')) {+ const title = svg.querySelector('title')?.textContent ?? '';+ svg.replaceWith(copy.ownerDocument.createTextNode(` ${title} `));+ }+ return (copy.textContent ?? '').replace(/\s+/g, ' ').trim();+}++/**+ * The accessible name of `element`: its own `aria-labelledby` targets, its+ * `aria-label`, its labels, an input button's value, its text, or its+ * `title`, in that order. A custom DropdownMenu trigger names the menu it+ * labels this way.+ */+export function readAccessibleName(+ element: HTMLElement | null,+): string | undefined {+ if (element == null) {+ return undefined;+ }+ const labelledBy = element.getAttribute('aria-labelledby');+ if (labelledBy != null && labelledBy.trim() !== '') {+ const text = labelledBy+ .split(/\s+/)+ .map(id => element.ownerDocument.getElementById(id))+ .filter((node): node is HTMLElement => node != null)+ .map(visibleText)+ .join(' ')+ .trim();+ if (text !== '') {+ return text;+ }+ }+ const label = element.getAttribute('aria-label')?.trim();+ if (label) {+ return label;+ }+ // A form control is named by its own <label>s; an input button by its value.+ const labels =+ 'labels' in element+ ? Array.from((element as HTMLInputElement).labels ?? [])+ : [];+ const labelText = labels.map(visibleText).join(' ').trim();+ if (labelText !== '') {+ return labelText;+ }+ if (+ element instanceof HTMLInputElement &&+ ['button', 'submit', 'reset'].includes(element.getAttribute('type') ?? '')+ ) {+ const value = element.value.trim();+ if (value !== '') {+ return value;+ }+ }+ const text = visibleText(element);+ if (text !== '') {+ return text;+ }+ return element.getAttribute('title')?.trim() || undefined;+}diff --git a/packages/core/src/utils/focusReturn.test.ts b/packages/core/src/utils/focusReturn.test.tsindex 1807d02078..13e7738927 100644--- a/packages/core/src/utils/focusReturn.test.ts+++ b/packages/core/src/utils/focusReturn.test.ts@@ -1,7 +1,13 @@// Copyright (c) Meta Platforms, Inc. and affiliates.import {describe, it, expect, afterEach, beforeEach, vi} from 'vitest';-import {focusForLastInput, isFocusDetached} from './focusReturn';+import {+ focusForLastInput,+ isFocusDetached,+ isFocusLost,+ moveFocusLeftBehind,+ noteFocusWithin,+} from './focusReturn';import {__resetInteractionModalityForTest,__startInteractionModalityTrackingForTest,@@ -143,3 +149,76 @@ describe('focusForLastInput in a second document', () => {release();});});++describe('isFocusLost', () => {+ afterEach(() => {+ document.body.innerHTML = '';+ });++ it('is true when nothing is focused, or focus is inside the surface', () => {+ document.body.innerHTML =+ '<div id="surface"><button id="inside">In</button></div><button id="outside">Out</button>';+ const surface = document.getElementById('surface');+ expect(isFocusLost(surface)).toBe(true);+ document.getElementById('inside')?.focus();+ expect(isFocusLost(surface)).toBe(true);+ document.getElementById('outside')?.focus();+ expect(isFocusLost(surface)).toBe(false);+ expect(isFocusLost(null)).toBe(false);+ });+});++describe('noteFocusWithin and moveFocusLeftBehind', () => {+ afterEach(() => {+ document.body.innerHTML = '';+ });++ function setUp() {+ document.body.innerHTML =+ '<div id="container"><div id="content"><button id="inside">In</button></div><button id="target">Target</button></div><button id="outside">Out</button>';+ const byId = (id: string) => document.getElementById(id) as HTMLElement;+ return {+ container: byId('container'),+ content: byId('content'),+ inside: byId('inside'),+ target: byId('target'),+ outside: byId('outside'),+ };+ }++ it('notes focus only inside the container', () => {+ const {container, inside, outside} = setUp();+ inside.focus();+ expect(noteFocusWithin(container)?.element).toBe(inside);+ outside.focus();+ expect(noteFocusWithin(container)).toBeNull();+ });++ it('moves focus that fell to the page when its element was removed', () => {+ const {container, inside, target} = setUp();+ inside.focus();+ const note = noteFocusWithin(container);+ inside.remove();+ expect(moveFocusLeftBehind(note, target)).toBe(true);+ expect(target).toHaveFocus();+ });++ it('moves focus left on content the change hid but kept', () => {+ const {container, content, inside, target} = setUp();+ inside.focus();+ const note = noteFocusWithin(container);+ content.style.display = 'none';+ expect(moveFocusLeftBehind(note, target, content)).toBe(true);+ expect(target).toHaveFocus();+ });++ it('moves no focus that survived the change or was never inside', () => {+ const {container, inside, target, outside} = setUp();+ inside.focus();+ expect(moveFocusLeftBehind(noteFocusWithin(container), target)).toBe(false);+ expect(inside).toHaveFocus();+ outside.focus();+ expect(moveFocusLeftBehind(noteFocusWithin(container), target)).toBe(false);+ expect(outside).toHaveFocus();+ });+});diff --git a/packages/core/src/utils/focusReturn.ts b/packages/core/src/utils/focusReturn.tsindex bcb0477475..7dbf32c7b3 100644--- a/packages/core/src/utils/focusReturn.ts+++ b/packages/core/src/utils/focusReturn.ts@@ -5,11 +5,15 @@* @input The document's current active element and the shared interaction* modality.* @output Whether focus is currently "detached" — on nothing in particular —- * and a focus move whose ring follows the last input.+ * or would be lost if a surface hid now; a focus move whose ring follows the+ * last input; and the one path that moves focus out of content a change+ * removed or hid (`noteFocusWithin`, `moveFocusLeftBehind`).* @position Utility; used by overlay triggers (e.g. DateInput, DateTimeInput)* that return focus to their control when the overlay closes, but only when* the dismiss did not already move focus somewhere the user chose, and by- * overlays (Dialog, DropdownMenu) that move focus programmatically.+ * overlays (Dialog, DropdownMenu) that move focus programmatically, and by+ * disclosures that hide focused content (`component:SideNav` AR3). Only+ * `isFocusDetached` is exported from the utils entry; the rest is internal.*/import {@@ -38,6 +42,67 @@ export function isFocusDetached(doc: Document = document): boolean {);}+/**+ * True when focus would be lost if `surface` hid now: nothing is focused (see+ * isFocusDetached) or focus sits inside `surface`. Reads `surface`'s own+ * document, so a surface in an iframe or Picture-in-Picture window is+ * answered there. Internal: not exported from the utils barrel.+ */+export function isFocusLost(surface: Element | null, doc?: Document): boolean {+ const ownerDocument = doc ?? surface?.ownerDocument ?? document;+ return (+ isFocusDetached(ownerDocument) ||+ (surface != null && surface.contains(ownerDocument.activeElement))+ );+}++/** Where focus was, inside a container, before a change removed or hid content. */+export interface FocusWithin {+ readonly element: Element;+ readonly container: HTMLElement;+}++/**+ * The focused element, if it is inside `container`. A disclosure calls this+ * in the commit before the DOM changes (`LayoutChangeSnapshot`'s+ * `onBeforeChange`), and passes the result to `moveFocusLeftBehind` from a+ * layout effect of the same commit. Internal.+ */+export function noteFocusWithin(+ container: HTMLElement | null | undefined,+): FocusWithin | null {+ const active = container?.ownerDocument.activeElement;+ if (container == null || active == null || !container.contains(active)) {+ return null;+ }+ return {element: active, container};+}++/**+ * Moves focus noted by `noteFocusWithin` to `target` when the change lost it+ * (`isFocusLost`): it fell to the page because its element was removed, or+ * it is still inside `hidden`, content the change hid but kept, which the+ * browser is about to blur. Focus that survived the change, or that was never+ * inside, is not moved. The ring follows the last input, so the calling+ * component keeps modality tracking active+ * (`useInteractionModalityTracking()`). Returns whether focus moved. Internal.+ */+export function moveFocusLeftBehind(+ note: FocusWithin | null,+ target: HTMLElement | null | undefined,+ hidden: Element | null = null,+): boolean {+ if (+ note == null ||+ target == null ||+ !isFocusLost(hidden, note.container.ownerDocument)+ ) {+ return false;+ }+ focusForLastInput(target);+ return true;+}+/*** Move focus programmatically so its ring follows the last input* (`architecture:interaction-modality` INV1). After pointer input the browser's