An open source design system that's fully customizable and agent ready
TypeScript
fix(TreeList): focus inside a collapsing branch moves to its row (#9251)
Cindy Zhang356e9a8ab689
diff --git a/.changeset/treelist-collapse-keeps-focus.md b/.changeset/treelist-collapse-keeps-focus.mdnew file mode 100644index 0000000000..6a9199aa36--- /dev/null+++ b/.changeset/treelist-collapse-keeps-focus.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] When a `TreeList` row collapses while keyboard focus is inside its children, for example from an `items` change, focus moves to that row (the outermost one when nested rows collapse together), which then holds the tree's Tab stop unless it is disabled (a disabled row takes focus, and the stop goes to the tree's first enabled row if the collapse removed the row that held it). Before, the focused row disappeared and nothing held focus, so a keyboard or screen-reader user lost their place (WCAG 2.2 SC 2.4.3). Focus anywhere else is not moved.++@cixzhang @duytbpdiff --git a/apps/storybook/stories/TreeList.stories.tsx b/apps/storybook/stories/TreeList.stories.tsxindex 9d542ec7a5..2a7e4e47e0 100644--- a/apps/storybook/stories/TreeList.stories.tsx+++ b/apps/storybook/stories/TreeList.stories.tsx@@ -1,6 +1,9 @@// Copyright (c) Meta Platforms, Inc. and affiliates.+import {useEffect, useState} from 'react';import type {Meta, StoryObj} from '@storybook/react';+import {Button} from '@astryxdesign/core/Button';+import {VStack} from '@astryxdesign/core/Layout';import {TreeList} from '@astryxdesign/core/TreeList';import type {TreeListItemData} from '@astryxdesign/core/TreeList';import {Icon} from '@astryxdesign/core/Icon';@@ -535,3 +538,46 @@ export const NoGuides: Story = {variant: 'noGuides',},};++// =============================================================================+// Collapse with focus inside the branch (AR2)+// =============================================================================++/**+ * The app collapses "src" from a keyboard shortcut (`[`), which leaves focus+ * where it was. Focus on "index.ts" moves to "src"; focus elsewhere stays put.+ */+function CollapseFocusDemo() {+ const [isExpanded, setIsExpanded] = useState(true);+ useEffect(() => {+ const onKeyDown = (event: KeyboardEvent) => {+ if (event.key === '[') {+ setIsExpanded(expanded => !expanded);+ }+ };+ document.addEventListener('keydown', onKeyDown);+ return () => document.removeEventListener('keydown', onKeyDown);+ }, []);+ return (+ <VStack gap={2}>+ <TreeList+ aria-label="Files"+ items={[+ {id: 'readme', label: 'README.md'},+ {+ id: 'src',+ label: 'src',+ isExpanded,+ children: [{id: 'index', label: 'index.ts'}],+ },+ ]}+ />+ <Button label="Elsewhere" variant="secondary" />+ </VStack>+ );+}++export const CollapseFocus: Story = {+ name: 'Collapse Focus',+ render: () => <CollapseFocusDemo />,+};diff --git a/docs/specs/components/TreeList/TreeList.spec.md b/docs/specs/components/TreeList/TreeList.spec.mdindex c4489ea458..f84ff88664 100644--- a/docs/specs/components/TreeList/TreeList.spec.md+++ b/docs/specs/components/TreeList/TreeList.spec.md@@ -176,6 +176,14 @@ replace component-owned semantic or interaction props.moves to the next row whose label starts with them. Selection is caller-owned:callers mark at most one row selected (`isSelected`); the tree does notenforce it, claims no `aria-multiselectable`, and has no selection keyboard.+- **AR2 — Focus leaves a collapsing branch.** When a row collapses while focus+ is inside its child group, however it collapses (an `items` change, an+ ancestor collapsing), focus moves to that row, the outermost one when nested+ rows collapse together, including while the group plays its exit (FR9). The+ row then holds the Tab stop unless it is disabled; a disabled row takes focus,+ and the Tab stop stays with the enabled row that holds it or, when the+ collapse removed that row, goes to the tree's first enabled row (AR1). Focus+ anywhere else is not moved (WCAG 2.2 SC 2.4.3).## Design relationships@@ -269,19 +277,20 @@ authorize or prohibit a future target.## Verification map-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |-| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------ |-| FR1 | `TreeList.test.tsx` rendering, hierarchy, slot, and accessibility suites plus source inspection | Flat, nested, described, headed, and slotted items | Removing asserted Tree list, Header, Item, Chevron, Item label, Item description, Start content, End content, or Guide behavior fails existing role, content, hierarchy, or state assertions; Chevron glyph presence remains source-inspected only. | `audit:TreeList/anatomy` |-| FR2 | `TreeList.test.tsx` and `themingTargets.test.ts` | Five local targets and their documented states | Removing or moving any current local target fails focused class assertions or the global inventory. | `audit:TreeList/theming` |-| FR3 | Source inspection plus Icon public target metadata | Expandable rows and caller-provided slots | Existing focused tests do not assert the composed Icon instance; changing glyph or slot ownership requires this map and the relevant owner metadata to change. | `audit:TreeList/theming` |-| FR4 | `TreeList.test.tsx` description rendering test and source inspection | Item with description | Removing description fails content coverage; adding a target requires an explicit map update. | `audit:TreeList/anatomy` |-| AR1 | Tree View accessibility contract (`internal/a11y-spec`, pending) bound to TreeList, in jsdom and Chromium; `TreeList.test.tsx` row-naming cases ("names a parent row by its label alone, not the chevron toggle", "names a plain row by its label and describes it with its description", "names and describes link and action rows themselves, not only their inner control", "keeps start and end content, including controls, out of the row name", "typeahead matches the label, not the description or start content") and `TreeListRowNames.a11y.chromium.spec.ts` for the browser-computed names; `TreeList.test.tsx` structural ARIA cases ("sets aria-level, aria-posinset, and aria-setsize at the top level", "sets aria-level/posinset/setsize correctly at deeper levels", "sets aria-level across three depths"); `TreeList.test.tsx` and `useTreeFocus.test.tsx` keyboard suites | Flat and nested trees; expanded/collapsed; selected/unselected; LTR and RTL; typeahead | A row loses its role, label name, state or position, two rows hold a Tab stop, an arrow key stops moving or stops mirroring under RTL, Home/End or typeahead stop working, or the tree claims multi-select | `audit:TreeList/accessibility` |-| FR5, FR6, ORD1 | Focused `TreeList.test.tsx` row-identity and styling-composition coverage, required with implementation | One input at a time; all three together; sibling rows | Dropping any mechanism, applying mechanisms to different elements, targeting the `<li>`, changing the merge order, or styling a sibling row fails. | `audit:TreeList/api` |-| FR7 | Focused `TreeList.test.tsx` row-click coverage, required with implementation | Action, parent, link, and disabled rows; clicks in the indent and padding, on the Chevron, and on Start and End content controls; plain, modified, and middle clicks | A click outside the label does nothing or runs the wrong action, a link-row click reaches ancestors twice, the Chevron or a Start or End content control activates the row, or a disabled row acts. | `audit:TreeList/behavior` |-| FR8 | Real-browser frame evidence under a finger and a mouse | expand and collapse; a toggle mid-motion; reduced motion; rows after the group, with and without an `animatedLayout` handle | Rows inside the group that jump, travel under a fine pointer without a handle or under reduced motion, an animated property under a fine pointer with reduced motion, a fade under a mouse without a handle, collapsing rows still in the accessibility tree during the slide, layout or paint per frame, or rows after the group moving without a handle fails | `audit:TreeList/behavior` |-| FR9 | `animatedLayoutAdopters.test.tsx` (with and without a handle; `isExpanded` changed in `items` glides; the collapsing group kept inert and out of the keyboard order until its exit ends) and `animatedLayoutAdopters.interaction.browser.spec.ts` (the `Core/Animated layout` story through a ScrollableArea ref, expanding and collapsing) | No handle; a handle; click, keyboard, and `items`-driven changes; expanding and collapsing | The rows after a row jump with a handle, an `items` change lands at once, a collapsing group vanishes before its exit or its rows stay focusable during it, or anything changes without a handle | `audit:TreeList/behavior` |-| DD4 | `TreeListGuideAlignment.interaction.browser.spec.ts` measures Chevron logical-start placement and Guide/Chevron center alignment in the built Fully Expanded story. | `lineGuides` and `noGuides`; LTR and RTL | Reintroducing Chevron edge margins, moving a Chevron when guides are hidden, or placing a Guide off the Chevron center fails the browser geometry assertions. | `audit:TreeList/anatomy` |-| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and five current local targets | Missing, extra, duplicated, prefixed, or stale mappings fail repository validation. | `audit:TreeList/theming` |+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------ |+| FR1 | `TreeList.test.tsx` rendering, hierarchy, slot, and accessibility suites plus source inspection | Flat, nested, described, headed, and slotted items | Removing asserted Tree list, Header, Item, Chevron, Item label, Item description, Start content, End content, or Guide behavior fails existing role, content, hierarchy, or state assertions; Chevron glyph presence remains source-inspected only. | `audit:TreeList/anatomy` |+| FR2 | `TreeList.test.tsx` and `themingTargets.test.ts` | Five local targets and their documented states | Removing or moving any current local target fails focused class assertions or the global inventory. | `audit:TreeList/theming` |+| FR3 | Source inspection plus Icon public target metadata | Expandable rows and caller-provided slots | Existing focused tests do not assert the composed Icon instance; changing glyph or slot ownership requires this map and the relevant owner metadata to change. | `audit:TreeList/theming` |+| FR4 | `TreeList.test.tsx` description rendering test and source inspection | Item with description | Removing description fails content coverage; adding a target requires an explicit map update. | `audit:TreeList/anatomy` |+| AR1 | Tree View accessibility contract (`internal/a11y-spec`, pending) bound to TreeList, in jsdom and Chromium; `TreeList.test.tsx` row-naming cases ("names a parent row by its label alone, not the chevron toggle", "names a plain row by its label and describes it with its description", "names and describes link and action rows themselves, not only their inner control", "keeps start and end content, including controls, out of the row name", "typeahead matches the label, not the description or start content") and `TreeListRowNames.a11y.chromium.spec.ts` for the browser-computed names; `TreeList.test.tsx` structural ARIA cases ("sets aria-level, aria-posinset, and aria-setsize at the top level", "sets aria-level/posinset/setsize correctly at deeper levels", "sets aria-level across three depths"); `TreeList.test.tsx` and `useTreeFocus.test.tsx` keyboard suites | Flat and nested trees; expanded/collapsed; selected/unselected; LTR and RTL; typeahead | A row loses its role, label name, state or position, two rows hold a Tab stop, an arrow key stops moving or stops mirroring under RTL, Home/End or typeahead stop working, or the tree claims multi-select | `audit:TreeList/accessibility` |+| FR5, FR6, ORD1 | Focused `TreeList.test.tsx` row-identity and styling-composition coverage, required with implementation | One input at a time; all three together; sibling rows | Dropping any mechanism, applying mechanisms to different elements, targeting the `<li>`, changing the merge order, or styling a sibling row fails. | `audit:TreeList/api` |+| FR7 | Focused `TreeList.test.tsx` row-click coverage, required with implementation | Action, parent, link, and disabled rows; clicks in the indent and padding, on the Chevron, and on Start and End content controls; plain, modified, and middle clicks | A click outside the label does nothing or runs the wrong action, a link-row click reaches ancestors twice, the Chevron or a Start or End content control activates the row, or a disabled row acts. | `audit:TreeList/behavior` |+| FR8 | Real-browser frame evidence under a finger and a mouse | expand and collapse; a toggle mid-motion; reduced motion; rows after the group, with and without an `animatedLayout` handle | Rows inside the group that jump, travel under a fine pointer without a handle or under reduced motion, an animated property under a fine pointer with reduced motion, a fade under a mouse without a handle, collapsing rows still in the accessibility tree during the slide, layout or paint per frame, or rows after the group moving without a handle fails | `audit:TreeList/behavior` |+| FR9 | `animatedLayoutAdopters.test.tsx` (with and without a handle; `isExpanded` changed in `items` glides; the collapsing group kept inert and out of the keyboard order until its exit ends) and `animatedLayoutAdopters.interaction.browser.spec.ts` (the `Core/Animated layout` story through a ScrollableArea ref, expanding and collapsing) | No handle; a handle; click, keyboard, and `items`-driven changes; expanding and collapsing | The rows after a row jump with a handle, an `items` change lands at once, a collapsing group vanishes before its exit or its rows stay focusable during it, or anything changes without a handle | `audit:TreeList/behavior` |+| AR2 | `TreeList.test.tsx` collapse-focus suite; `animatedLayoutAdopters.test.tsx` collapse with focus inside during the exit; `TreeListCollapseFocus.a11y.chromium.spec.ts` | Focus on a child row, `items`-driven collapse, with and without a handle; nested outer and inner collapse; a disabled collapsing row; focus on another row or outside | Focus left in the removed or inert group, on the page body, or moved when it was not inside the group fails. | `audit:TreeList/accessibility` |+| DD4 | `TreeListGuideAlignment.interaction.browser.spec.ts` measures Chevron logical-start placement and Guide/Chevron center alignment in the built Fully Expanded story. | `lineGuides` and `noGuides`; LTR and RTL | Reintroducing Chevron edge margins, moving a Chevron when guides are hidden, or placing a Guide off the Chevron center fails the browser geometry assertions. | `audit:TreeList/anatomy` |+| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and five current local targets | Missing, extra, duplicated, prefixed, or stale mappings fail repository validation. | `audit:TreeList/theming` |Focused target-placement assertions cover all five local targets. Runtime supportand mutation-sensitive coverage for the item styling seam may land separately,diff --git a/packages/core/src/TreeList/TreeList.test.tsx b/packages/core/src/TreeList/TreeList.test.tsxindex 3c70724c52..048cc9fce9 100644--- a/packages/core/src/TreeList/TreeList.test.tsx+++ b/packages/core/src/TreeList/TreeList.test.tsx@@ -1828,3 +1828,135 @@ describe('TreeList empty slots', () => {expect(screen.getByRole('tree')).toHaveAttribute('aria-labelledby');});});++describe('TreeList collapse focus (AR2)', () => {+ function Example({isExpanded}: {isExpanded: boolean}) {+ return (+ <>+ <TreeList+ aria-label="Files"+ items={[+ {id: 'readme', label: 'README.md'},+ {+ id: 'src',+ label: 'src',+ isExpanded,+ children: [{id: 'index', label: 'index.ts'}],+ },+ ]}+ />+ <button type="button">Elsewhere</button>+ </>+ );+ }+ const row = (id: string) =>+ document.querySelector<HTMLElement>(`[data-tree-id="${id}"]`);++ it('moves focus inside a collapsing branch to its row', () => {+ const {rerender} = render(<Example isExpanded />);+ expect(row('readme')).toHaveAttribute('tabindex', '0');+ row('index')?.focus();+ expect(row('index')).toHaveFocus();+ rerender(<Example isExpanded={false} />);+ expect(row('index')).toBeNull();+ expect(row('src')).toHaveFocus();+ // It holds the one Tab stop, which was on README.md.+ expect(row('src')).toHaveAttribute('tabindex', '0');+ expect(row('readme')).toHaveAttribute('tabindex', '-1');+ });++ it('moves focus in a nested group to the outermost row that collapsed, and to the inner row when only it collapses', () => {+ const Nested = ({outer, inner}: {outer: boolean; inner: boolean}) => (+ <TreeList+ aria-label="Files"+ items={[+ {+ id: 'src',+ label: 'src',+ isExpanded: outer,+ children: [+ {+ id: 'lib',+ label: 'lib',+ isExpanded: inner,+ children: [{id: 'util', label: 'util.ts'}],+ },+ ],+ },+ ]}+ />+ );+ const {rerender} = render(<Nested outer inner />);+ row('util')?.focus();+ rerender(<Nested outer={false} inner />);+ expect(row('src')).toHaveFocus();+ rerender(<Nested outer inner />);+ row('util')?.focus();+ rerender(<Nested outer inner={false} />);+ expect(row('lib')).toHaveFocus();+ });++ it('moves focus to a disabled collapsing row, which leaves the Tab stop where it is', () => {+ const Disabled = ({isExpanded}: {isExpanded: boolean}) => (+ <TreeList+ aria-label="Files"+ items={[+ {id: 'readme', label: 'README.md'},+ {+ id: 'src',+ label: 'src',+ isDisabled: true,+ isExpanded,+ children: [{id: 'index', label: 'index.ts'}],+ },+ ]}+ />+ );+ const {rerender} = render(<Disabled isExpanded />);+ row('index')?.focus();+ rerender(<Disabled isExpanded={false} />);+ expect(row('src')).toHaveFocus();+ expect(row('src')).toHaveAttribute('tabindex', '-1');+ expect(row('readme')).toHaveAttribute('tabindex', '0');+ });++ it('hands the Tab stop to the first enabled row when a disabled row collapses away the child that held it', () => {+ const Disabled = ({isExpanded}: {isExpanded: boolean}) => (+ <TreeList+ aria-label="Files"+ items={[+ {id: 'readme', label: 'README.md'},+ {+ id: 'src',+ label: 'src',+ isDisabled: true,+ isExpanded,+ children: [{id: 'index', label: 'index.ts'}],+ },+ ]}+ />+ );+ const {rerender} = render(<Disabled isExpanded />);+ // The keyboard path: arrowing past the disabled row onto its child gives+ // the child the stop.+ row('readme')?.focus();+ fireEvent.keyDown(row('readme') as HTMLElement, {key: 'ArrowDown'});+ expect(row('index')).toHaveFocus();+ expect(row('index')).toHaveAttribute('tabindex', '0');+ rerender(<Disabled isExpanded={false} />);+ expect(row('src')).toHaveFocus();+ expect(row('src')).toHaveAttribute('tabindex', '-1');+ expect(row('readme')).toHaveAttribute('tabindex', '0');+ });++ it('moves no focus that is outside the collapsing branch', () => {+ const {rerender} = render(<Example isExpanded />);+ row('readme')?.focus();+ rerender(<Example isExpanded={false} />);+ expect(row('readme')).toHaveFocus();+ screen.getByRole('button', {name: 'Elsewhere'}).focus();+ rerender(<Example isExpanded />);+ rerender(<Example isExpanded={false} />);+ expect(screen.getByRole('button', {name: 'Elsewhere'})).toHaveFocus();+ });+});diff --git a/packages/core/src/TreeList/TreeList.tsx b/packages/core/src/TreeList/TreeList.tsxindex fa2eb9602c..681308aa2c 100644--- a/packages/core/src/TreeList/TreeList.tsx+++ b/packages/core/src/TreeList/TreeList.tsx@@ -38,6 +38,14 @@ import type {import {themeProps} from '../utils/themeProps';import {useTreeFocusInternal} from '../hooks/useTreeFocus';import {LayoutChangeSnapshot} from '../motion/LayoutChangeSnapshot';+import {+ moveFocusLeftBehind,+ noteFocusWithin,+ type FocusWithin,+} from '../utils/focusReturn';+import {useInteractionModalityTracking} from '../utils/interactionModality';+import {useFocusLeavingChange} from '../utils/useFocusLeavingChange';+import {useMergedRefs} from '../hooks/useMergedRefs';import {applyLayoutChangeTransition,holdLayoutExit,@@ -383,6 +391,76 @@ export function TreeList({},[animatedLayout, expandedIds],);+ // Focus inside a branch's child group when it collapses would be lost once+ // the group goes (or turns inert for its exit). It moves to the collapsing+ // row itself (AR2); focus anywhere else is not moved. The shared sequence+ // notes it in the commit before the DOM changes and moves it once the+ // collapse has committed.+ // The tree's own document's last input decides the moved focus's ring.+ const {ref: modalityRef} = useInteractionModalityTracking();+ const noteCollapsingFocus = useFocusLeavingChange<+ ReadonlySet<string>,+ {focus: FocusWithin; ids: string[]}+ >(+ expandedIds,+ // Every expanded row whose group holds focus, outermost first, found by+ // walking up from the focused element: which of them collapsed is known+ // only after the commit.+ (previous: ReadonlySet<string>) => {+ const tree = treeElementRef.current;+ const active = tree?.ownerDocument.activeElement;+ if (tree == null || active == null || !tree.contains(active)) {+ return null;+ }+ let focus: FocusWithin | null = null;+ const ids: string[] = [];+ for (+ let element = active.parentElement;+ element != null && element !== tree;+ element = element.parentElement+ ) {+ const id = element.parentElement?.dataset.treeId;+ if (+ element.getAttribute('role') === 'group' &&+ id != null &&+ previous.has(id)+ ) {+ focus = noteFocusWithin(element);+ ids.unshift(id);+ }+ }+ return focus == null ? null : {focus, ids};+ },+ (noted, expanded) => {+ // The outermost row that collapsed: a row inside it goes with it.+ const id = noted.ids.find(candidate => !expanded.has(candidate));+ if (id == null) {+ return;+ }+ const row = treeElementRef.current?.querySelector<HTMLElement>(+ `[data-tree-id="${CSS.escape(id)}"]`,+ );+ const moved = moveFocusLeftBehind(+ noted.focus,+ row,+ row?.querySelector(':scope > [role="group"]') ?? null,+ );+ // The row focus moved to holds the tree's one Tab stop, unless it is+ // disabled (AR1, AR2).+ if (moved && row != null) {+ takeTabStop(row);+ }+ },+ );+ const beforeExpansionChange = useCallback(+ (previous: ReadonlySet<string>) => {+ noteCollapsingFocus(previous);+ if (animatedLayout != null) {+ measureChanges(previous);+ }+ },+ [animatedLayout, measureChanges, noteCollapsingFocus],+ );// Without a handle the chevrons keep the theme's own turn: a spring a// handle set stays only while it is passed (`spec:AST-105` FR2).useLayoutEffect(() => {@@ -481,7 +559,7 @@ export function TreeList({}}, [expandedIds, animatedLayout, endExit]);- const {treeRef, handleKeyDown, handleFocus} =+ const {treeRef, handleKeyDown, handleFocus, takeTabStop} =useTreeFocusInternal<HTMLUListElement>({onToggleExpand: handleToggle,onActivate: activateItem,@@ -495,6 +573,7 @@ export function TreeList({useLayoutEffect(() => {treeElementRef.current = treeRef.current;});+ const mergedTreeRef = useMergedRefs(treeRef, modalityRef);const handleRootKeyDown = useCallback((e: React.KeyboardEvent<HTMLDivElement>) => {@@ -605,14 +684,12 @@ export function TreeList({{header}</div>)}- {animatedLayout != null && (- <LayoutChangeSnapshot- value={expandedIds}- onBeforeChange={measureChanges}- />- )}+ <LayoutChangeSnapshot+ value={expandedIds}+ onBeforeChange={beforeExpansionChange}+ /><ul- ref={treeRef}+ ref={mergedTreeRef}role="tree"aria-label={hasHeader ? undefined : ariaLabel}aria-labelledby={hasHeader ? headerId : ariaLabelledby}diff --git a/packages/core/src/TreeList/__tests__/TreeListCollapseFocus.a11y.chromium.spec.ts b/packages/core/src/TreeList/__tests__/TreeListCollapseFocus.a11y.chromium.spec.tsnew file mode 100644index 0000000000..78d2d4e1aa--- /dev/null+++ b/packages/core/src/TreeList/__tests__/TreeListCollapseFocus.a11y.chromium.spec.ts@@ -0,0 +1,65 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file TreeListCollapseFocus.a11y.chromium.spec.ts+ * @input The built Storybook's `Core/TreeList` "Collapse Focus" story: a tree+ * whose app collapses its "src" branch from a `[` shortcut, and a button+ * outside it+ * @output Real-Chromium proof of `component:TreeList` AR2: focus inside a+ * collapsing branch moves to its row; focus elsewhere is not moved+ * @position Testing; the unit cases are in TreeList.test.tsx and+ * motion/animatedLayoutAdopters.test.tsx+ *+ * SYNC: When modified, update the AR2 Verification row in TreeList.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): Promise<void> {+ await page.goto(+ `${storybook.origin}/iframe.html?id=core-treelist--collapse-focus&viewMode=story`,+ );+ await page.getByRole('treeitem', {name: 'index.ts'}).waitFor();+}++test('focus inside a collapsing branch moves to its row', async ({page}) => {+ await openStory(page);+ const child = page.getByRole('treeitem', {name: 'index.ts'});+ await child.focus();+ await page.keyboard.press('[');++ await expect(child).toHaveCount(0);+ const src = page.getByRole('treeitem', {name: 'src'});+ await expect(src).toBeFocused();+ // It holds the tree's one Tab stop, which started on README.md.+ await expect(src).toHaveAttribute('tabindex', '0');+ await expect(page.getByRole('treeitem', {name: 'README.md'})).toHaveAttribute(+ 'tabindex',+ '-1',+ );+});++test('focus outside the collapsing branch is not moved', async ({page}) => {+ await openStory(page);+ const elsewhere = page.getByRole('button', {name: 'Elsewhere'});+ await elsewhere.focus();+ await page.keyboard.press('[');++ await expect(page.getByRole('treeitem', {name: 'index.ts'})).toHaveCount(0);+ await expect(elsewhere).toBeFocused();+});diff --git a/packages/core/src/hooks/useTreeFocus.ts b/packages/core/src/hooks/useTreeFocus.tsindex 42bcad699d..61e169681e 100644--- a/packages/core/src/hooks/useTreeFocus.ts+++ b/packages/core/src/hooks/useTreeFocus.ts@@ -236,8 +236,12 @@ export function useTreeFocus<T extends HTMLElement = HTMLElement>(options: UseTreeFocusOptions = {},): UseTreeFocusReturn<T> {// The flag is pinned off here so an untyped options object cannot smuggle- // it through the public hook.- return useTreeFocusInternal<T>({...options, matchLabelledBy: false});+ // it through the public hook, and the internal stop move stays internal.+ const {takeTabStop: _takeTabStop, ...result} = useTreeFocusInternal<T>({+ ...options,+ matchLabelledBy: false,+ });+ return result;}/**@@ -257,13 +261,25 @@ export type UseTreeFocusInternalOptions = UseTreeFocusOptions & {matchLabelledBy?: boolean;};+/** What the package's own components get beyond the public hook. */+export type UseTreeFocusInternalReturn<T extends HTMLElement = HTMLElement> =+ UseTreeFocusReturn<T> & {+ /**+ * With `hasRovingTabIndex`, makes `item` the tree's one Tab stop, by the+ * same rule the hook's own moves follow: a disabled or hidden row never+ * takes it, and the stop stays where it is. TreeList calls it when it+ * moves focus to a collapsing row (`component:TreeList` AR2).+ */+ takeTabStop: (item: HTMLElement) => void;+ };+/*** The implementation behind {@link useTreeFocus}. Not exported from the* package; the public hook calls it without the internal options.*/export function useTreeFocusInternal<T extends HTMLElement = HTMLElement>(options: UseTreeFocusInternalOptions = {},-): UseTreeFocusReturn<T> {+): UseTreeFocusInternalReturn<T> {const {itemSelector = '[role="treeitem"]',isItemDisabled,@@ -630,11 +646,25 @@ export function useTreeFocusInternal<T extends HTMLElement = HTMLElement>(}}, [hasRovingTabIndex, syncTabStops]);+ const takeTabStop = useCallback(+ (item: HTMLElement) => {+ if (!hasRovingTabIndex || itemDisabled(item)) {+ return;+ }+ const items = getItems();+ if (items.includes(item)) {+ moveTabStop(items, item);+ }+ },+ [getItems, hasRovingTabIndex, itemDisabled, moveTabStop],+ );+return {treeRef,handleKeyDown,handleFocus,focusFirst,focusLast,+ takeTabStop,};}diff --git a/packages/core/src/motion/animatedLayoutAdopters.test.tsx b/packages/core/src/motion/animatedLayoutAdopters.test.tsxindex 1a2a4f4314..bb7847c40d 100644--- a/packages/core/src/motion/animatedLayoutAdopters.test.tsx+++ b/packages/core/src/motion/animatedLayoutAdopters.test.tsx@@ -428,6 +428,41 @@ describe("a close plays the content's exit (spec:AST-105 FR4)", () => {expect(groupOf()).toBeNull();});+ it('moves focus inside a collapsing TreeList branch to its row while the group plays its exit (component:TreeList AR2)', async () => {+ const example = (isExpanded: boolean) => (+ <Area withHandle>+ {layout => (+ <TreeList+ items={[+ {+ id: 'src',+ label: 'src',+ isExpanded,+ children: [{id: 'index', label: 'index.ts'}],+ },+ ]}+ animatedLayout={layout}+ />+ )}+ </Area>+ );+ const {rerender} = render(example(true));+ stubGeometry();+ const groupOf = () =>+ document.querySelector<HTMLElement>(+ '[data-tree-id="src"] > [role="group"]',+ );+ vi.spyOn(groupOf() as HTMLElement, 'getBoundingClientRect').mockReturnValue(+ new DOMRect(0, 40, 400, 40),+ );+ document.querySelector<HTMLElement>('[data-tree-id="index"]')?.focus();+ rerender(example(false));+ await flush();+ // The group is still there for its exit, inert, so focus left it.+ expect(groupOf()).toHaveAttribute('inert');+ expect(document.querySelector('[data-tree-id="src"]')).toHaveFocus();+ });+it('collapses a row with an expanded child as one change: only the outer group exits, and the child goes with it', async () => {const user = userEvent.setup();render(