Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(treelist): full APG tree keyboard pattern + aria-level/posinset/setsize (#3409)

Cindy Zhangf57fb72dfa97
diff --git a/.changeset/treelist-apg-keyboard.md b/.changeset/treelist-apg-keyboard.md
new file mode 100644
index 0000000000..aa25579157
--- /dev/null
+++ b/.changeset/treelist-apg-keyboard.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] TreeList now implements the full WAI-ARIA APG Tree View keyboard pattern. Roving tabindex places a single tab stop on the treeitem rows (defaulting to the selected item or the first enabled row), and arrow keys move focus in visible order: ArrowDown/ArrowUp step between visible rows (skipping disabled), ArrowRight expands a collapsed parent then enters its first child, ArrowLeft collapses an expanded parent or moves to the parent row, and Home/End jump to the first/last visible row. Enter and Space activate the row's action (or toggle a parent without its own action), and typeahead moves focus to the next row whose label matches the typed characters. Each treeitem now also exposes `aria-level`, `aria-posinset`, and `aria-setsize`. Builds on the interim keyboard-expandable toggle in (#3344). Part of the accessibility & keyboard-management program (#3343).
+@cixzhang
diff --git a/packages/core/src/TreeList/TreeList.test.tsx b/packages/core/src/TreeList/TreeList.test.tsx
index 9c0527d420..4247a4759b 100644
--- a/packages/core/src/TreeList/TreeList.test.tsx
+++ b/packages/core/src/TreeList/TreeList.test.tsx
@@ -61,6 +61,44 @@ const deepItems: TreeListItemData[] = [
},
];
+// APG keyboard fixtures (module-level to satisfy no-unstable-default-props).
+const flatItems: TreeListItemData[] = [
+ {id: 'a', label: 'Apple'},
+ {id: 'b', label: 'Banana'},
+ {id: 'c', label: 'Cherry'},
+];
+
+const withDisabledItems: TreeListItemData[] = [
+ {id: 'a', label: 'Apple'},
+ {id: 'b', label: 'Banana', isDisabled: true},
+ {id: 'c', label: 'Cherry'},
+];
+
+const collapsedParentItems: TreeListItemData[] = [
+ {
+ id: 'parent',
+ label: 'Parent',
+ children: [
+ {id: 'child-1', label: 'Child 1'},
+ {id: 'child-2', label: 'Child 2'},
+ ],
+ },
+ {id: 'sibling', label: 'Sibling'},
+];
+
+const expandedParentItems: TreeListItemData[] = [
+ {
+ id: 'parent',
+ label: 'Parent',
+ isExpanded: true,
+ children: [
+ {id: 'child-1', label: 'Child 1'},
+ {id: 'child-2', label: 'Child 2'},
+ ],
+ },
+ {id: 'sibling', label: 'Sibling'},
+];
+
describe('TreeList', () => {
// ===========================================================================
// Basic rendering
@@ -333,4 +371,239 @@ describe('TreeList', () => {
const root = screen.getByTestId('tree');
expect(root.className).toContain('astryx-tree-list');
});
+
+ // ===========================================================================
+ // APG structural ARIA (aria-level / aria-posinset / aria-setsize)
+ // ===========================================================================
+
+ it('sets aria-level, aria-posinset, and aria-setsize at the top level', () => {
+ render(<TreeList items={flatItems} />);
+ const apple = screen.getByText('Apple').closest('li');
+ expect(apple).toHaveAttribute('aria-level', '1');
+ expect(apple).toHaveAttribute('aria-posinset', '1');
+ expect(apple).toHaveAttribute('aria-setsize', '3');
+
+ const cherry = screen.getByText('Cherry').closest('li');
+ expect(cherry).toHaveAttribute('aria-posinset', '3');
+ expect(cherry).toHaveAttribute('aria-setsize', '3');
+ });
+
+ it('sets aria-level/posinset/setsize correctly at deeper levels', () => {
+ render(<TreeList items={expandedParentItems} />);
+ const parent = screen.getByText('Parent').closest('li');
+ expect(parent).toHaveAttribute('aria-level', '1');
+ expect(parent).toHaveAttribute('aria-setsize', '2');
+
+ const child1 = screen.getByText('Child 1').closest('li');
+ expect(child1).toHaveAttribute('aria-level', '2');
+ expect(child1).toHaveAttribute('aria-posinset', '1');
+ expect(child1).toHaveAttribute('aria-setsize', '2');
+
+ const child2 = screen.getByText('Child 2').closest('li');
+ expect(child2).toHaveAttribute('aria-level', '2');
+ expect(child2).toHaveAttribute('aria-posinset', '2');
+ });
+
+ it('sets aria-level across three depths', () => {
+ render(<TreeList items={deepItems} />);
+ expect(screen.getByText('Root').closest('li')).toHaveAttribute(
+ 'aria-level',
+ '1',
+ );
+ expect(screen.getByText('Mid').closest('li')).toHaveAttribute(
+ 'aria-level',
+ '2',
+ );
+ expect(screen.getByText('Leaf').closest('li')).toHaveAttribute(
+ 'aria-level',
+ '3',
+ );
+ });
+
+ // ===========================================================================
+ // Roving tabindex
+ // ===========================================================================
+
+ it('makes exactly one treeitem tabbable by default (the first enabled)', () => {
+ render(<TreeList items={flatItems} />);
+ const treeitems = screen.getAllByRole('treeitem');
+ const tabbable = treeitems.filter(
+ el => el.getAttribute('tabindex') === '0',
+ );
+ expect(tabbable).toHaveLength(1);
+ expect(tabbable[0]).toBe(screen.getByText('Apple').closest('li'));
+ expect(screen.getByText('Banana').closest('li')).toHaveAttribute(
+ 'tabindex',
+ '-1',
+ );
+ });
+
+ it('defaults the tab stop to the selected item when one is selected', () => {
+ const items: TreeListItemData[] = [
+ {id: 'a', label: 'Apple'},
+ {id: 'b', label: 'Banana', isSelected: true},
+ {id: 'c', label: 'Cherry'},
+ ];
+ render(<TreeList items={items} />);
+ expect(screen.getByText('Banana').closest('li')).toHaveAttribute(
+ 'tabindex',
+ '0',
+ );
+ expect(screen.getByText('Apple').closest('li')).toHaveAttribute(
+ 'tabindex',
+ '-1',
+ );
+ });
+
+ it('moves the single tab stop when focus moves via keyboard', async () => {
+ const user = userEvent.setup();
+ render(<TreeList items={flatItems} />);
+ const apple = screen.getByText('Apple').closest('li')!;
+ apple.focus();
+ await user.keyboard('{ArrowDown}');
+ const treeitems = screen.getAllByRole('treeitem');
+ const tabbable = treeitems.filter(
+ el => el.getAttribute('tabindex') === '0',
+ );
+ expect(tabbable).toHaveLength(1);
+ expect(tabbable[0]).toBe(screen.getByText('Banana').closest('li'));
+ });
+
+ // ===========================================================================
+ // APG keyboard navigation
+ // ===========================================================================
+
+ it('ArrowDown / ArrowUp move focus between visible treeitems', async () => {
+ const user = userEvent.setup();
+ render(<TreeList items={flatItems} />);
+ const apple = screen.getByText('Apple').closest('li')!;
+ apple.focus();
+ await user.keyboard('{ArrowDown}');
+ expect(document.activeElement).toBe(
+ screen.getByText('Banana').closest('li'),
+ );
+ await user.keyboard('{ArrowDown}');
+ expect(document.activeElement).toBe(
+ screen.getByText('Cherry').closest('li'),
+ );
+ await user.keyboard('{ArrowUp}');
+ expect(document.activeElement).toBe(
+ screen.getByText('Banana').closest('li'),
+ );
+ });
+
+ it('ArrowDown / ArrowUp skip disabled treeitems', async () => {
+ const user = userEvent.setup();
+ render(<TreeList items={withDisabledItems} />);
+ const apple = screen.getByText('Apple').closest('li')!;
+ apple.focus();
+ await user.keyboard('{ArrowDown}');
+ // Banana is disabled → skipped, lands on Cherry.
+ expect(document.activeElement).toBe(
+ screen.getByText('Cherry').closest('li'),
+ );
+ await user.keyboard('{ArrowUp}');
+ expect(document.activeElement).toBe(
+ screen.getByText('Apple').closest('li'),
+ );
+ });
+
+ it('ArrowRight expands a collapsed parent, then enters the first child', async () => {
+ const user = userEvent.setup();
+ render(<TreeList items={collapsedParentItems} />);
+ const parent = screen.getByText('Parent').closest('li')!;
+ parent.focus();
+ expect(screen.queryByText('Child 1')).not.toBeInTheDocument();
+ await user.keyboard('{ArrowRight}');
+ // First ArrowRight expands.
+ expect(screen.getByText('Child 1')).toBeInTheDocument();
+ expect(document.activeElement).toBe(parent);
+ await user.keyboard('{ArrowRight}');
+ // Second ArrowRight moves into first child.
+ expect(document.activeElement).toBe(
+ screen.getByText('Child 1').closest('li'),
+ );
+ });
+
+ it('ArrowRight on a leaf is a no-op', async () => {
+ const user = userEvent.setup();
+ render(<TreeList items={flatItems} />);
+ const apple = screen.getByText('Apple').closest('li')!;
+ apple.focus();
+ await user.keyboard('{ArrowRight}');
+ expect(document.activeElement).toBe(apple);
+ });
+
+ it('ArrowLeft collapses an expanded parent, then moves to parent', async () => {
+ const user = userEvent.setup();
+ render(<TreeList items={expandedParentItems} />);
+ const parent = screen.getByText('Parent').closest('li')!;
+ // Focus a child first.
+ const child1 = screen.getByText('Child 1').closest('li')!;
+ child1.focus();
+ await user.keyboard('{ArrowLeft}');
+ // Child is a leaf → ArrowLeft moves to parent.
+ expect(document.activeElement).toBe(parent);
+ await user.keyboard('{ArrowLeft}');
+ // Parent is expanded → ArrowLeft collapses it.
+ expect(screen.queryByText('Child 1')).not.toBeInTheDocument();
+ });
+
+ it('Home and End move to the first and last visible treeitems', async () => {
+ const user = userEvent.setup();
+ render(<TreeList items={flatItems} />);
+ const banana = screen.getByText('Banana').closest('li')!;
+ banana.focus();
+ await user.keyboard('{End}');
+ expect(document.activeElement).toBe(
+ screen.getByText('Cherry').closest('li'),
+ );
+ await user.keyboard('{Home}');
+ expect(document.activeElement).toBe(
+ screen.getByText('Apple').closest('li'),
+ );
+ });
+
+ it('Enter activates the item onClick', async () => {
+ const user = userEvent.setup();
+ const onClick = vi.fn();
+ const items: TreeListItemData[] = [{id: 'a', label: 'Apple', onClick}];
+ render(<TreeList items={items} />);
+ const apple = screen.getByText('Apple').closest('li')!;
+ apple.focus();
+ await user.keyboard('{Enter}');
+ expect(onClick).toHaveBeenCalledTimes(1);
+ });
+
+ it('Space activates the item onClick', async () => {
+ const user = userEvent.setup();
+ const onClick = vi.fn();
+ const items: TreeListItemData[] = [{id: 'a', label: 'Apple', onClick}];
+ render(<TreeList items={items} />);
+ const apple = screen.getByText('Apple').closest('li')!;
+ apple.focus();
+ await user.keyboard(' ');
+ expect(onClick).toHaveBeenCalledTimes(1);
+ });
+
+ it('Enter toggles expansion for a parent without its own action', async () => {
+ const user = userEvent.setup();
+ render(<TreeList items={collapsedParentItems} />);
+ const parent = screen.getByText('Parent').closest('li')!;
+ parent.focus();
+ expect(screen.queryByText('Child 1')).not.toBeInTheDocument();
+ await user.keyboard('{Enter}');
+ expect(screen.getByText('Child 1')).toBeInTheDocument();
+ });
+
+ it('typeahead moves focus to the next item matching typed characters', async () => {
+ const user = userEvent.setup();
+ render(<TreeList items={flatItems} />);
+ const apple = screen.getByText('Apple').closest('li')!;
+ apple.focus();
+ await user.keyboard('c');
+ expect(document.activeElement).toBe(
+ screen.getByText('Cherry').closest('li'),
+ );
+ });
});
diff --git a/packages/core/src/TreeList/TreeList.tsx b/packages/core/src/TreeList/TreeList.tsx
index 388980971b..2f83949252 100644
--- a/packages/core/src/TreeList/TreeList.tsx
+++ b/packages/core/src/TreeList/TreeList.tsx
@@ -4,7 +4,7 @@
/**
* @file TreeList.tsx
- * @input Uses React, StyleX, theme tokens, TreeListItem, TreeListTypes
+ * @input Uses React, StyleX, theme tokens, TreeListItem, TreeListTypes, useTreeFocus
* @output Exports TreeList component, TreeListProps type
* @position Core implementation; consumed by index.ts
*
@@ -23,6 +23,7 @@ import type {BaseProps} from '../BaseProps';
import {TreeListItem} from './TreeListItem';
import type {TreeListItemData, TreeListDensity} from './TreeListTypes';
import {themeProps} from '../utils/themeProps';
+import {useTreeFocus} from '../hooks/useTreeFocus';
// =============================================================================
// Types
@@ -97,6 +98,34 @@ function collectExpandedKeys(items: TreeListItemData[]): string[] {
return keys;
}
+/**
+ * Compute the initial roving-tabindex owner: the first selected enabled item
+ * in document order, else the first enabled item, else the first item.
+ * Only the top-level candidates are considered for the default so the tab stop
+ * is reachable even when the tree is fully collapsed.
+ */
+function findDefaultActiveId(items: TreeListItemData[]): string | undefined {
+ let firstEnabled: string | undefined;
+ const walk = (list: TreeListItemData[]): string | undefined => {
+ for (const item of list) {
+ if (item.isSelected && item.isDisabled !== true) {
+ return item.id;
+ }
+ if (firstEnabled == null && item.isDisabled !== true) {
+ firstEnabled = item.id;
+ }
+ if (item.children != null && item.children.length > 0) {
+ const selected = walk(item.children);
+ if (selected != null) {
+ return selected;
+ }
+ }
+ }
+ return undefined;
+ };
+ return walk(items) ?? firstEnabled ?? items[0]?.id;
+}
+
// =============================================================================
// Component
// =============================================================================
@@ -160,6 +189,55 @@ export function TreeList({
[expandedKeysFromProps],
);
+ // ---------------------------------------------------------------------------
+ // Roving tabindex + APG tree keyboard model (via useTreeFocus)
+ // ---------------------------------------------------------------------------
+
+ // The treeitem that currently owns the tree's single tab stop. The hook moves
+ // it around via onActiveChange; a data-driven default seeds it (selected item
+ // or first enabled).
+ const [activeId, setActiveId] = useState<string | undefined>(() =>
+ findDefaultActiveId(items),
+ );
+
+ // If the seed id is no longer present (items changed), fall back to a valid
+ // default so the tree always has exactly one reachable tab stop.
+ const resolvedActiveId = useMemo(() => {
+ if (activeId == null) {
+ return findDefaultActiveId(items);
+ }
+ const exists = (list: TreeListItemData[]): boolean =>
+ list.some(
+ item =>
+ item.id === activeId ||
+ (item.children != null && exists(item.children)),
+ );
+ return exists(items) ? activeId : findDefaultActiveId(items);
+ }, [activeId, items]);
+
+ // Enter/Space activation: prefer the treeitem's own inner action (link or
+ // button); return true when handled so the hook does not also toggle. Scoped
+ // to this treeitem's own row — never a descendant treeitem's action inside an
+ // expanded group.
+ const activateItem = useCallback((current: HTMLElement): boolean => {
+ const candidates = current.querySelectorAll<HTMLElement>(
+ 'a[href], button:not([aria-label="Toggle children"])',
+ );
+ for (const candidate of candidates) {
+ if (candidate.closest('[role="treeitem"]') === current) {
+ candidate.click();
+ return true;
+ }
+ }
+ return false;
+ }, []);
+
+ const {treeRef, handleKeyDown} = useTreeFocus<HTMLUListElement>({
+ onToggleExpand: handleToggle,
+ onActivate: activateItem,
+ onActiveChange: setActiveId,
+ });
+
function renderItems(
items: TreeListItemData[],
nestedLevel: number,
@@ -206,6 +284,9 @@ export function TreeList({
onToggle={handleToggle}
density={density}
renderedChildren={renderedChildren}
+ posInSet={index + 1}
+ setSize={items.length}
+ isTabbable={item.id === resolvedActiveId}
/>
);
});
@@ -227,8 +308,10 @@ export function TreeList({
</div>
)}
<ul
+ ref={treeRef}
role="tree"
aria-labelledby={header != null ? headerId : undefined}
+ onKeyDown={handleKeyDown}
{...stylex.props(styles.list)}>
{renderItems(items, 0, [])}
</ul>
diff --git a/packages/core/src/TreeList/TreeListItem.tsx b/packages/core/src/TreeList/TreeListItem.tsx
index 4b8da4cc89..818c484e3d 100644
--- a/packages/core/src/TreeList/TreeListItem.tsx
+++ b/packages/core/src/TreeList/TreeListItem.tsx
@@ -29,6 +29,7 @@ import {mergeProps} from '../utils';
import {useLinkComponent} from '../Link/useLinkComponent';
import {TreeListBranches} from './TreeListBranches';
import type {TreeListDensity} from './TreeListTypes';
+import {treeItemScope} from './treeListItem.markers.stylex';
import {themeProps} from '../utils/themeProps';
// =============================================================================
@@ -42,6 +43,9 @@ const styles = stylex.create({
padding: 0,
position: 'relative',
width: '100%',
+ // The treeitem row is the roving-tabindex focus owner; suppress the
+ // native focus ring in favor of the row's :focus-visible outline below.
+ outline: 'none',
},
childGroup: {
margin: 0,
@@ -82,10 +86,16 @@ const styles = stylex.create({
focusVisibleOutline: {
outline: {
default: 'none',
+ // Focus lives on the treeitem row (the <li>) via roving tabindex.
+ // Scoped to the row's OWN treeitem so focusing a parent does not leak
+ // the ring onto descendant rows. Also support inner focusable actions.
+ [stylex.when.ancestor(':focus-visible', treeItemScope)]:
+ `2px solid ${colorVars['--color-accent']}`,
':has(:focus-visible)': `2px solid ${colorVars['--color-accent']}`,
},
outlineOffset: {
default: '0',
+ [stylex.when.ancestor(':focus-visible', treeItemScope)]: '2px',
':has(:focus-visible)': '2px',
},
},
@@ -250,6 +260,15 @@ export interface TreeListItemInternalProps {
density: TreeListDensity;
/** Pre-rendered children subtree (rendered by the parent recursion) */
renderedChildren?: ReactNode;
+ /** 1-based position of this item among its siblings (aria-posinset). */
+ posInSet: number;
+ /** Number of siblings at this level (aria-setsize). */
+ setSize: number;
+ /**
+ * Whether this treeitem currently owns the tree's single tab stop
+ * (roving tabindex). Exactly one visible treeitem is tabbable at a time.
+ */
+ isTabbable: boolean;
}
// =============================================================================
@@ -275,6 +294,9 @@ export function TreeListItem({
onToggle,
density,
renderedChildren,
+ posInSet,
+ setSize,
+ isTabbable,
}: TreeListItemInternalProps) {
const labelId = useId();
const descriptionId = useId();
@@ -353,6 +375,9 @@ export function TreeListItem({
aria-expanded={isExpanded}
aria-label="Toggle children"
disabled={isDisabled}
+ // Roving tabindex lives on the treeitem row; the chevron toggle is not
+ // a separate tab stop. Row-level Enter/Space forwards to this button.
+ tabIndex={-1}
onClick={handleToggle}
{...stylex.props(styles.chevronButton)}>
{chevronIcon}
@@ -376,7 +401,9 @@ export function TreeListItem({
aria-disabled={isDisabled || undefined}
aria-labelledby={labelId}
aria-describedby={description != null ? descriptionId : undefined}
- tabIndex={isDisabled ? -1 : undefined}
+ // Roving tabindex lives on the treeitem row; inner action is not a
+ // separate tab stop. Activation is forwarded from the row.
+ tabIndex={-1}
{...stylex.props(styles.invisibleAnchor)}>
{labelAndDescription}
</LinkComponent>
@@ -387,6 +414,9 @@ export function TreeListItem({
disabled={isDisabled}
aria-labelledby={labelId}
aria-describedby={description != null ? descriptionId : undefined}
+ // Roving tabindex lives on the treeitem row; inner action is not a
+ // separate tab stop. Activation is forwarded from the row.
+ tabIndex={-1}
{...stylex.props(styles.invisibleButton)}>
{labelAndDescription}
</button>
@@ -405,7 +435,17 @@ export function TreeListItem({
aria-expanded={hasChildren ? isExpanded : undefined}
aria-selected={isSelected || undefined}
aria-disabled={isDisabled || undefined}
- {...stylex.props(styles.wrapper)}>
+ aria-level={nestedLevel + 1}
+ aria-posinset={posInSet}
+ aria-setsize={setSize}
+ // Roving tabindex: exactly one visible treeitem is tabbable at a time.
+ // Disabled items are skipped by the tree keyboard handler but remain
+ // in the accessibility tree.
+ tabIndex={isDisabled ? -1 : isTabbable ? 0 : -1}
+ data-tree-id={id}
+ data-tree-level={nestedLevel + 1}
+ data-tree-disabled={isDisabled || undefined}
+ {...stylex.props(styles.wrapper, treeItemScope)}>
<div {...stylex.props(styles.treeBranches)}>
<TreeListBranches
ancestorsIsLast={ancestorsIsLast}
diff --git a/packages/core/src/TreeList/treeListItem.markers.stylex.ts b/packages/core/src/TreeList/treeListItem.markers.stylex.ts
new file mode 100644
index 0000000000..1f47036fa7
--- /dev/null
+++ b/packages/core/src/TreeList/treeListItem.markers.stylex.ts
@@ -0,0 +1,20 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file treeListItem.markers.stylex.ts
+ * @input Uses StyleX defineMarker
+ * @output Exports treeItemScope marker
+ * @position Scoped marker; consumed by TreeListItem.tsx
+ *
+ * SYNC: When modified, update /packages/core/src/TreeList/TreeListItem.tsx
+ */
+
+import * as stylex from '@stylexjs/stylex';
+
+/**
+ * Scoped marker placed on each treeitem row (`<li role="treeitem">`).
+ * Binds the row's `:focus-visible` outline to its OWN treeitem, so focusing
+ * a parent treeitem does not leak the focus ring onto descendant rows.
+ */
+export const treeItemScope: ReturnType<typeof stylex.defineMarker> =
+ stylex.defineMarker();
diff --git a/packages/core/src/hooks/index.ts b/packages/core/src/hooks/index.ts
index 05113d7790..85eadfddfc 100644
--- a/packages/core/src/hooks/index.ts
+++ b/packages/core/src/hooks/index.ts
@@ -27,6 +27,9 @@ export type {
ListFocusOrientation,
} from './useListFocus';
+export {useTreeFocus} from './useTreeFocus';
+export type {UseTreeFocusOptions, UseTreeFocusReturn} from './useTreeFocus';
+
export {useTypeahead} from './useTypeahead';
export type {UseTypeaheadOptions, UseTypeaheadReturn} from './useTypeahead';
diff --git a/packages/core/src/hooks/useTreeFocus.doc.mjs b/packages/core/src/hooks/useTreeFocus.doc.mjs
new file mode 100644
index 0000000000..e6df8e8dab
--- /dev/null
+++ b/packages/core/src/hooks/useTreeFocus.doc.mjs
@@ -0,0 +1,126 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('../docs-types').HookDoc} */
+export const docs = {
+ name: 'useTreeFocus',
+ displayName: 'useTreeFocus',
+ keywords: ['tree', 'treeview', 'focus', 'keyboard', 'navigation', 'arrow', 'expand', 'collapse', 'roving', 'tabindex', 'a11y', 'wai-aria', 'apg'],
+ params: [
+ {
+ name: 'options',
+ type: 'UseTreeFocusOptions',
+ description: 'Configuration object for tree focus behavior.',
+ required: false,
+ },
+ {
+ name: 'options.itemSelector',
+ type: 'string',
+ description: 'Selector for visible treeitems within the tree, in DOM order.',
+ default: "'[role=\"treeitem\"]'",
+ required: false,
+ },
+ {
+ name: 'options.isItemDisabled',
+ type: '(item: HTMLElement) => boolean',
+ description: 'Predicate for whether a treeitem is disabled and must be skipped during navigation. Defaults to reading `data-tree-disabled` / `aria-disabled`.',
+ required: false,
+ },
+ {
+ name: 'options.getLevel',
+ type: '(item: HTMLElement) => number',
+ description: 'Reads the 1-based nesting level of a treeitem. Defaults to the `aria-level` attribute.',
+ required: false,
+ },
+ {
+ name: 'options.onToggleExpand',
+ type: '(id: string) => void',
+ description: 'Called to expand/collapse the treeitem with the given id (ArrowRight on a collapsed parent, ArrowLeft on an expanded parent, Enter/Space on a parent without its own action).',
+ required: false,
+ },
+ {
+ name: 'options.onActivate',
+ type: '(item: HTMLElement, id: string | undefined) => boolean | void',
+ description: 'Called when Enter/Space activates a treeitem. Return true when handled; return false/undefined to let the hook fall back to toggling expansion.',
+ required: false,
+ },
+ {
+ name: 'options.onActiveChange',
+ type: '(id: string | undefined) => void',
+ description: 'Notified when the hook moves focus to a treeitem. Consumers use this to move a single roving tab stop.',
+ required: false,
+ },
+ {
+ name: 'options.typeahead',
+ type: 'boolean',
+ description: 'Whether typeahead (jump to next item whose text starts with the typed characters) is enabled.',
+ default: 'true',
+ required: false,
+ },
+ ],
+ returns: [
+ {
+ name: 'treeRef',
+ type: 'React.RefObject<HTMLElement | null>',
+ description: 'Ref to attach to the tree container element (role="tree").',
+ },
+ {
+ name: 'handleKeyDown',
+ type: '(e: React.KeyboardEvent) => void',
+ description: 'Key down handler to attach to the tree container.',
+ },
+ {
+ name: 'focusFirst',
+ type: '() => void',
+ description: 'Focus the first enabled visible treeitem.',
+ },
+ {
+ name: 'focusLast',
+ type: '() => void',
+ description: 'Focus the last enabled visible treeitem.',
+ },
+ ],
+ usage: {
+ description:
+ 'Manages roving-tabindex focus and the WAI-ARIA tree keyboard model. ArrowUp/ArrowDown/Home/End roam linearly over the visible treeitems (skipping disabled ones), while ArrowRight/ArrowLeft carry tree semantics (expand/collapse, move to first-child/parent). Enter/Space activate, and printable characters trigger typeahead.',
+ bestPractices: [
+ { guidance: true, description: 'Use for hierarchical tree widgets: wire onToggleExpand to your expansion state and onActiveChange to a single roving tab stop.' },
+ { guidance: true, description: 'Attach both treeRef and handleKeyDown to the role="tree" container element.' },
+ { guidance: false, description: 'Use for linear lists (prefer useListFocus) or 2D grids (prefer useGridFocus) — those traversals differ from a tree.' },
+ ],
+ },
+ relatedComponents: ['TreeList'],
+ relatedHooks: ['useListFocus', 'useGridFocus', 'useFocusTrap'],
+ importPath: '@astryxdesign/core/hooks',
+ category: 'focus',
+};
+
+/** @type {import('../docs-types').HookTranslationDoc} */
+export const docsDense = {
+ description:
+ 'Manages roving-tabindex focus + WAI-ARIA tree keyboard model. ArrowUp/Down/Home/End roam linearly over visible treeitems (skip disabled); ArrowRight/Left carry tree semantics (expand/collapse, move to first-child/parent). Enter/Space activate; printable chars trigger typeahead.',
+ paramDescriptions: {
+ options: 'config for tree focus behavior.',
+ 'options.itemSelector': 'selector for visible treeitems in DOM order.',
+ 'options.isItemDisabled': 'predicate: is treeitem disabled (skipped in nav). Defaults to data-tree-disabled / aria-disabled.',
+ 'options.getLevel': 'reads 1-based nesting level. Defaults to aria-level attr.',
+ 'options.onToggleExpand': 'expand/collapse treeitem by id (ArrowRight collapsed parent, ArrowLeft expanded parent, Enter/Space parent w/o own action).',
+ 'options.onActivate': 'called on Enter/Space activation. Return true when handled; else hook falls back to toggling expansion.',
+ 'options.onActiveChange': 'notified when focus moves to a treeitem. Use to move a single roving tab stop.',
+ 'options.typeahead': 'enable typeahead (jump to next item whose text starts with typed chars).',
+ },
+ returnDescriptions: {
+ treeRef: 'ref to attach to tree container (role="tree").',
+ handleKeyDown: 'key down handler for tree container.',
+ focusFirst: 'focus first enabled visible treeitem.',
+ focusLast: 'focus last enabled visible treeitem.',
+ },
+ usage: {
+ description:
+ 'Manages roving-tabindex focus + WAI-ARIA tree keyboard model. ArrowUp/Down/Home/End roam linearly over visible treeitems (skip disabled); ArrowRight/Left carry tree semantics (expand/collapse, move to first-child/parent). Enter/Space activate; printable chars trigger typeahead.',
+ bestPractices: [
+ { guidance: true, description: 'Use for hierarchical tree widgets: wire onToggleExpand to expansion state + onActiveChange to a single roving tab stop.' },
+ { guidance: true, description: 'Attach both treeRef + handleKeyDown to role="tree" container.' },
+ { guidance: false, description: 'Use for linear lists (prefer useListFocus) or 2D grids (prefer useGridFocus).' },
+ ],
+ },
+};
diff --git a/packages/core/src/hooks/useTreeFocus.test.tsx b/packages/core/src/hooks/useTreeFocus.test.tsx
new file mode 100644
index 0000000000..cc697f84b6
--- /dev/null
+++ b/packages/core/src/hooks/useTreeFocus.test.tsx
@@ -0,0 +1,214 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useTreeFocus.test.tsx
+ * @input Uses vitest, @testing-library/react, useTreeFocus hook
+ * @output Unit tests for useTreeFocus APG tree keyboard navigation
+ * @position Testing; validates useTreeFocus.ts keyboard model
+ *
+ * SYNC: When useTreeFocus.ts changes, update tests to match new behavior
+ */
+
+import {describe, it, expect, vi} from 'vitest';
+import {useState} from 'react';
+import {render, screen, fireEvent} from '@testing-library/react';
+import {useTreeFocus} from './useTreeFocus';
+
+interface Node {
+ id: string;
+ label: string;
+ level: number;
+ disabled?: boolean;
+ /** 'expanded' | 'collapsed' | undefined (leaf) */
+ expanded?: boolean;
+}
+
+const NO_NODES: Node[] = [];
+
+/**
+ * Minimal generic tree harness driven by a flat list of visible nodes. Mirrors
+ * the DOM contract TreeList exposes: role="treeitem", aria-level, aria-expanded,
+ * data-tree-id, data-tree-disabled. Expansion is faked by swapping the visible
+ * node list on toggle so ArrowRight/ArrowLeft can be exercised.
+ */
+function Tree({
+ collapsed = NO_NODES,
+ expanded = NO_NODES,
+ onActivate,
+}: {
+ collapsed?: Node[];
+ expanded?: Node[];
+ onActivate?: (id: string | undefined) => boolean | undefined;
+}) {
+ const [isOpen, setIsOpen] = useState(false);
+ const nodes = isOpen && expanded.length > 0 ? expanded : collapsed;
+ const {treeRef, handleKeyDown} = useTreeFocus<HTMLUListElement>({
+ onToggleExpand: () => setIsOpen(o => !o),
+ onActivate: onActivate
+ ? (_item, id) => onActivate(id)
+ : undefined,
+ });
+ return (
+ <ul ref={treeRef} role="tree" onKeyDown={handleKeyDown}>
+ {nodes.map(n => (
+ <li
+ key={n.id}
+ role="treeitem"
+ aria-level={n.level}
+ aria-expanded={n.expanded}
+ data-tree-id={n.id}
+ data-tree-disabled={n.disabled || undefined}
+ tabIndex={-1}
+ data-testid={n.id}>
+ {n.label}
+ </li>
+ ))}
+ </ul>
+ );
+}
+
+const FLAT: Node[] = [
+ {id: 'a', label: 'Apple', level: 1},
+ {id: 'b', label: 'Banana', level: 1},
+ {id: 'c', label: 'Cherry', level: 1},
+];
+
+describe('useTreeFocus linear navigation', () => {
+ it('ArrowDown / ArrowUp move between visible treeitems', () => {
+ render(<Tree collapsed={FLAT} />);
+ const tree = screen.getByRole('tree');
+ screen.getByTestId('a').focus();
+
+ fireEvent.keyDown(tree, {key: 'ArrowDown'});
+ expect(screen.getByTestId('b')).toHaveFocus();
+ fireEvent.keyDown(tree, {key: 'ArrowDown'});
+ expect(screen.getByTestId('c')).toHaveFocus();
+ fireEvent.keyDown(tree, {key: 'ArrowUp'});
+ expect(screen.getByTestId('b')).toHaveFocus();
+ });
+
+ it('ArrowDown / ArrowUp skip disabled treeitems', () => {
+ const nodes: Node[] = [
+ {id: 'a', label: 'Apple', level: 1},
+ {id: 'b', label: 'Banana', level: 1, disabled: true},
+ {id: 'c', label: 'Cherry', level: 1},
+ ];
+ render(<Tree collapsed={nodes} />);
+ const tree = screen.getByRole('tree');
+ screen.getByTestId('a').focus();
+
+ fireEvent.keyDown(tree, {key: 'ArrowDown'});
+ expect(screen.getByTestId('c')).toHaveFocus();
+ fireEvent.keyDown(tree, {key: 'ArrowUp'});
+ expect(screen.getByTestId('a')).toHaveFocus();
+ });
+
+ it('Home / End move to the first and last visible treeitems', () => {
+ render(<Tree collapsed={FLAT} />);
+ const tree = screen.getByRole('tree');
+ screen.getByTestId('b').focus();
+
+ fireEvent.keyDown(tree, {key: 'End'});
+ expect(screen.getByTestId('c')).toHaveFocus();
+ fireEvent.keyDown(tree, {key: 'Home'});
+ expect(screen.getByTestId('a')).toHaveFocus();
+ });
+
+ it('ArrowDown does not wrap past the last item', () => {
+ render(<Tree collapsed={FLAT} />);
+ const tree = screen.getByRole('tree');
+ screen.getByTestId('c').focus();
+ fireEvent.keyDown(tree, {key: 'ArrowDown'});
+ expect(screen.getByTestId('c')).toHaveFocus();
+ });
+});
+
+describe('useTreeFocus tree semantics (Arrow Left/Right)', () => {
+ const COLLAPSED: Node[] = [
+ {id: 'p', label: 'Parent', level: 1, expanded: false},
+ ];
+ const EXPANDED: Node[] = [
+ {id: 'p', label: 'Parent', level: 1, expanded: true},
+ {id: 'c1', label: 'Child 1', level: 2},
+ {id: 'c2', label: 'Child 2', level: 2},
+ ];
+
+ it('ArrowRight expands a collapsed parent, then enters the first child', () => {
+ render(<Tree collapsed={COLLAPSED} expanded={EXPANDED} />);
+ const tree = screen.getByRole('tree');
+ screen.getByTestId('p').focus();
+
+ expect(screen.queryByTestId('c1')).not.toBeInTheDocument();
+ fireEvent.keyDown(tree, {key: 'ArrowRight'});
+ // Expanded now.
+ expect(screen.getByTestId('c1')).toBeInTheDocument();
+ // Focus stayed on parent.
+ expect(screen.getByTestId('p')).toHaveFocus();
+
+ fireEvent.keyDown(tree, {key: 'ArrowRight'});
+ expect(screen.getByTestId('c1')).toHaveFocus();
+ });
+
+ it('ArrowRight on a leaf is a no-op', () => {
+ render(<Tree collapsed={FLAT} />);
+ const tree = screen.getByRole('tree');
+ screen.getByTestId('a').focus();
+ fireEvent.keyDown(tree, {key: 'ArrowRight'});
+ expect(screen.getByTestId('a')).toHaveFocus();
+ });
+
+ it('ArrowLeft on a child moves to the parent; on an expanded parent collapses', () => {
+ render(<Tree collapsed={COLLAPSED} expanded={EXPANDED} />);
+ const tree = screen.getByRole('tree');
+ // Start expanded.
+ screen.getByTestId('p').focus();
+ fireEvent.keyDown(tree, {key: 'ArrowRight'}); // expand
+ fireEvent.keyDown(tree, {key: 'ArrowRight'}); // into child 1
+ expect(screen.getByTestId('c1')).toHaveFocus();
+
+ fireEvent.keyDown(tree, {key: 'ArrowLeft'}); // child leaf → parent
+ expect(screen.getByTestId('p')).toHaveFocus();
+
+ fireEvent.keyDown(tree, {key: 'ArrowLeft'}); // expanded parent → collapse
+ expect(screen.queryByTestId('c1')).not.toBeInTheDocument();
+ });
+});
+
+describe('useTreeFocus activation + typeahead', () => {
+ it('Enter/Space call onActivate for the focused item', () => {
+ const onActivate = vi.fn(() => true);
+ render(<Tree collapsed={FLAT} onActivate={onActivate} />);
+ const tree = screen.getByRole('tree');
+ screen.getByTestId('a').focus();
+
+ fireEvent.keyDown(tree, {key: 'Enter'});
+ expect(onActivate).toHaveBeenCalledWith('a');
+
+ fireEvent.keyDown(tree, {key: ' '});
+ expect(onActivate).toHaveBeenCalledTimes(2);
+ });
+
+ it('Enter toggles expansion when onActivate does not handle it', () => {
+ const COLLAPSED: Node[] = [
+ {id: 'p', label: 'Parent', level: 1, expanded: false},
+ ];
+ const EXPANDED: Node[] = [
+ {id: 'p', label: 'Parent', level: 1, expanded: true},
+ {id: 'c1', label: 'Child 1', level: 2},
+ ];
+ render(<Tree collapsed={COLLAPSED} expanded={EXPANDED} />);
+ const tree = screen.getByRole('tree');
+ screen.getByTestId('p').focus();
+ expect(screen.queryByTestId('c1')).not.toBeInTheDocument();
+ fireEvent.keyDown(tree, {key: 'Enter'});
+ expect(screen.getByTestId('c1')).toBeInTheDocument();
+ });
+
+ it('typeahead moves focus to the next item matching typed characters', () => {
+ render(<Tree collapsed={FLAT} />);
+ const tree = screen.getByRole('tree');
+ screen.getByTestId('a').focus();
+ fireEvent.keyDown(tree, {key: 'c'});
+ expect(screen.getByTestId('c')).toHaveFocus();
+ });
+});
diff --git a/packages/core/src/hooks/useTreeFocus.ts b/packages/core/src/hooks/useTreeFocus.ts
new file mode 100644
index 0000000000..5e4b1b5064
--- /dev/null
+++ b/packages/core/src/hooks/useTreeFocus.ts
@@ -0,0 +1,464 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file useTreeFocus.ts
+ * @input Uses React useCallback, useRef
+ * @output Exports useTreeFocus hook for WAI-ARIA tree keyboard navigation
+ * @position Core hook; used by TreeList for roving tabindex + APG tree keyboard model
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/hooks/index.ts
+ * - /packages/core/src/hooks/useTreeFocus.doc.mjs
+ * - /packages/core/src/hooks/useTreeFocus.test.tsx
+ */
+
+import {useCallback, useRef} from 'react';
+
+/** Keys handled by the tree keyboard model (used to gate typeahead). */
+const NAVIGATION_KEYS = new Set([
+ 'ArrowDown',
+ 'ArrowUp',
+ 'ArrowRight',
+ 'ArrowLeft',
+ 'Home',
+ 'End',
+ 'Enter',
+ ' ',
+]);
+
+/** Default reset delay for the typeahead buffer. */
+const DEFAULT_TYPEAHEAD_RESET_MS = 500;
+
+/**
+ * Configuration for tree focus behavior.
+ *
+ * The tree keyboard model differs from a linear list (useListFocus): while
+ * ArrowUp/ArrowDown/Home/End roam linearly over the *visible* treeitems,
+ * ArrowRight/ArrowLeft carry tree semantics (expand/collapse, move to
+ * first-child / parent). The hook stays generic by taking callbacks for the
+ * tree-specific bits (expansion toggling, activation) — mirroring how
+ * useGridFocus takes `isCellFocusable` rather than hardcoding disabled logic.
+ */
+export interface UseTreeFocusOptions {
+ /**
+ * Selector for treeitems within the tree. Matches ALL visible treeitems in
+ * DOM order (collapsed subtrees are not rendered, so they are naturally
+ * excluded). Disabled treeitems are still matched and then skipped via
+ * {@link UseTreeFocusOptions.isItemDisabled}.
+ * @default '[role="treeitem"]'
+ */
+ itemSelector?: string;
+
+ /**
+ * Predicate determining whether a treeitem matched by `itemSelector` is
+ * disabled and must be skipped during arrow/Home/End navigation. A `.focus()`
+ * on a disabled item silently no-ops, so navigation would otherwise stall.
+ *
+ * @default reads `data-tree-disabled` (present ⇒ disabled)
+ */
+ isItemDisabled?: (item: HTMLElement) => boolean;
+
+ /**
+ * Reads the nesting level (aria-level style, 1-based) of a treeitem. Used to
+ * resolve first-child (ArrowRight) and parent (ArrowLeft) targets from the
+ * flat visible-item list.
+ *
+ * @default reads the `aria-level` attribute (falling back to `1`)
+ */
+ getLevel?: (item: HTMLElement) => number;
+
+ /**
+ * Whether a treeitem is an expanded parent. Read DOM-side (aria-expanded)
+ * by default so it reflects the rendered tree without prop plumbing.
+ *
+ * @default `aria-expanded === 'true'`
+ */
+ isExpanded?: (item: HTMLElement) => boolean;
+
+ /**
+ * Whether a treeitem is a collapsed parent (has children but is closed).
+ *
+ * @default `aria-expanded === 'false'`
+ */
+ isCollapsed?: (item: HTMLElement) => boolean;
+
+ /**
+ * Resolve the stable id for a treeitem, passed to `onToggleExpand` /
+ * `onActivate`. Returns `undefined` when the element carries no id.
+ *
+ * @default reads the `data-tree-id` attribute
+ */
+ getItemId?: (item: HTMLElement) => string | undefined;
+
+ /**
+ * Called to expand/collapse the treeitem with the given id (ArrowRight on a
+ * collapsed parent, ArrowLeft on an expanded parent, and Enter/Space on a
+ * parent that has no inner action).
+ */
+ onToggleExpand?: (id: string) => void;
+
+ /**
+ * Called when Enter/Space activates a treeitem. Return `true` if the
+ * activation was handled (e.g. an inner link/button was clicked); return
+ * `false`/`undefined` to let the hook fall back to toggling expansion for a
+ * parent. When omitted, the hook falls straight through to expansion
+ * toggling for parents.
+ *
+ * @param item The focused treeitem element.
+ * @param id The treeitem's id (per `getItemId`), if any.
+ */
+ onActivate?: (item: HTMLElement, id: string | undefined) => boolean | undefined;
+
+ /**
+ * Whether typeahead (jump to next item whose text starts with the typed
+ * characters) is enabled.
+ * @default true
+ */
+ typeahead?: boolean;
+
+ /** Reset delay for the typeahead buffer, in ms. @default 500 */
+ typeaheadResetMs?: number;
+
+ /**
+ * Notified whenever the hook moves focus to a treeitem, with its id (if any).
+ * TreeList uses this to move its single roving tab stop.
+ */
+ onActiveChange?: (id: string | undefined) => void;
+}
+
+/**
+ * Return type for useTreeFocus hook.
+ */
+export interface UseTreeFocusReturn<T extends HTMLElement = HTMLElement> {
+ /** Ref to attach to the tree container element (role="tree"). */
+ treeRef: React.RefObject<T | null>;
+
+ /** Key down handler to attach to the tree container. */
+ handleKeyDown: (e: React.KeyboardEvent) => void;
+
+ /** Focus the first enabled visible treeitem. */
+ focusFirst: () => void;
+
+ /** Focus the last enabled visible treeitem. */
+ focusLast: () => void;
+}
+
+/**
+ * Hook for managing roving-tabindex focus + the WAI-ARIA tree keyboard model.
+ *
+ * A tree is not a linear list: ArrowUp/ArrowDown/Home/End roam linearly over
+ * the *visible* treeitems (skipping disabled ones), but ArrowRight/ArrowLeft
+ * carry tree semantics. This is why a tree needs its own hook rather than
+ * reusing `useListFocus` — the same reason 2D grids get `useGridFocus`.
+ *
+ * - ArrowDown / ArrowUp: move to next/previous visible treeitem (skip disabled)
+ * - ArrowRight: collapsed parent → expand; expanded parent → first child;
+ * leaf → no-op
+ * - ArrowLeft: expanded parent → collapse; otherwise → move to parent treeitem
+ * - Home / End: first / last visible treeitem
+ * - Enter / Space: activate (`onActivate`), falling back to expansion toggle
+ * - Printable characters: typeahead to the next matching treeitem
+ *
+ * The hook is DOM-query based (reads aria-expanded/aria-level and data-*
+ * attributes) and stays generic via option callbacks for the tree-specific
+ * bits (`onToggleExpand`, `onActivate`, `getLevel`, `isItemDisabled`, …).
+ *
+ * @example
+ * ```
+ * const {treeRef, handleKeyDown} = useTreeFocus<HTMLUListElement>({
+ * onToggleExpand: id => toggle(id),
+ * onActiveChange: id => setActiveId(id),
+ * });
+ *
+ * <ul ref={treeRef} role="tree" onKeyDown={handleKeyDown}>
+ * {items.map(item => <li role="treeitem" tabIndex={-1}>{item.label}</li>)}
+ * </ul>
+ * ```
+ */
+export function useTreeFocus<T extends HTMLElement = HTMLElement>(
+ options: UseTreeFocusOptions = {},
+): UseTreeFocusReturn<T> {
+ const {
+ itemSelector = '[role="treeitem"]',
+ isItemDisabled,
+ getLevel,
+ isExpanded,
+ isCollapsed,
+ getItemId,
+ onToggleExpand,
+ onActivate,
+ typeahead = true,
+ typeaheadResetMs = DEFAULT_TYPEAHEAD_RESET_MS,
+ onActiveChange,
+ } = options;
+
+ const treeRef = useRef<T>(null);
+
+ const typeaheadRef = useRef<{buffer: string; timer: number | null}>({
+ buffer: '',
+ timer: null,
+ });
+
+ /** Visible treeitems in DOM order (collapsed subtrees are not rendered). */
+ const getItems = useCallback((): HTMLElement[] => {
+ const root = treeRef.current;
+ if (root == null) {
+ return [];
+ }
+ return Array.from(root.querySelectorAll<HTMLElement>(itemSelector));
+ }, [itemSelector]);
+
+ const itemDisabled = useCallback(
+ (el: HTMLElement): boolean =>
+ isItemDisabled
+ ? isItemDisabled(el)
+ : el.dataset.treeDisabled != null ||
+ el.getAttribute('aria-disabled') === 'true',
+ [isItemDisabled],
+ );
+
+ const levelOf = useCallback(
+ (el: HTMLElement): number =>
+ getLevel ? getLevel(el) : Number(el.getAttribute('aria-level') ?? '1'),
+ [getLevel],
+ );
+
+ const expandedOf = useCallback(
+ (el: HTMLElement): boolean =>
+ isExpanded ? isExpanded(el) : el.getAttribute('aria-expanded') === 'true',
+ [isExpanded],
+ );
+
+ const collapsedOf = useCallback(
+ (el: HTMLElement): boolean =>
+ isCollapsed
+ ? isCollapsed(el)
+ : el.getAttribute('aria-expanded') === 'false',
+ [isCollapsed],
+ );
+
+ const idOf = useCallback(
+ (el: HTMLElement): string | undefined =>
+ getItemId ? getItemId(el) : el.dataset.treeId,
+ [getItemId],
+ );
+
+ /** Move focus to a treeitem and notify the active-change listener. */
+ const focusItem = useCallback(
+ (el: HTMLElement | undefined) => {
+ if (el == null) {
+ return;
+ }
+ onActiveChange?.(idOf(el));
+ el.focus();
+ },
+ [idOf, onActiveChange],
+ );
+
+ /**
+ * Focus the first enabled treeitem from `start`, moving by `dir`. No wrap —
+ * a tree's linear roam clamps at the ends.
+ */
+ const focusEnabledFrom = useCallback(
+ (items: HTMLElement[], start: number, dir: 1 | -1) => {
+ for (let i = start; i >= 0 && i < items.length; i += dir) {
+ const candidate = items[i];
+ if (candidate != null && !itemDisabled(candidate)) {
+ focusItem(candidate);
+ return;
+ }
+ }
+ },
+ [itemDisabled, focusItem],
+ );
+
+ const focusFirst = useCallback(() => {
+ focusEnabledFrom(getItems(), 0, 1);
+ }, [getItems, focusEnabledFrom]);
+
+ const focusLast = useCallback(() => {
+ const items = getItems();
+ focusEnabledFrom(items, items.length - 1, -1);
+ }, [getItems, focusEnabledFrom]);
+
+ const runTypeahead = useCallback(
+ (
+ e: React.KeyboardEvent,
+ items: HTMLElement[],
+ currentIndex: number,
+ ): void => {
+ const state = typeaheadRef.current;
+ if (state.timer != null) {
+ clearTimeout(state.timer);
+ }
+ state.buffer += e.key.toLowerCase();
+ state.timer = setTimeout(() => {
+ typeaheadRef.current.buffer = '';
+ }, typeaheadResetMs) as unknown as number;
+
+ const query = state.buffer;
+ const start = currentIndex < 0 ? 0 : currentIndex;
+ const ordered = [...items.slice(start + 1), ...items.slice(0, start + 1)];
+ const match = ordered.find(
+ item =>
+ !itemDisabled(item) &&
+ (item.textContent ?? '').trim().toLowerCase().startsWith(query),
+ );
+ if (match != null) {
+ e.preventDefault();
+ focusItem(match);
+ }
+ },
+ [typeaheadResetMs, itemDisabled, focusItem],
+ );
+
+ const handleKeyDown = useCallback(
+ (e: React.KeyboardEvent) => {
+ const items = getItems();
+ if (items.length === 0) {
+ return;
+ }
+
+ const active = document.activeElement;
+ // Resolve the treeitem that owns focus: the nearest treeitem ancestor of
+ // the active element (never an outer treeitem that merely contains it).
+ const activeItem =
+ active instanceof Element ? active.closest('[role="treeitem"]') : null;
+ const currentIndex = items.findIndex(item => item === activeItem);
+ const current = currentIndex >= 0 ? items[currentIndex] : undefined;
+
+ // Typeahead: printable single characters jump to the next matching item.
+ if (
+ typeahead &&
+ e.key.length === 1 &&
+ !e.ctrlKey &&
+ !e.metaKey &&
+ !e.altKey &&
+ NAVIGATION_KEYS.has(e.key) === false
+ ) {
+ runTypeahead(e, items, currentIndex);
+ return;
+ }
+
+ if (!NAVIGATION_KEYS.has(e.key)) {
+ return;
+ }
+
+ switch (e.key) {
+ case 'ArrowDown': {
+ e.preventDefault();
+ focusEnabledFrom(items, currentIndex < 0 ? 0 : currentIndex + 1, 1);
+ break;
+ }
+ case 'ArrowUp': {
+ e.preventDefault();
+ focusEnabledFrom(
+ items,
+ currentIndex < 0 ? items.length - 1 : currentIndex - 1,
+ -1,
+ );
+ break;
+ }
+ case 'ArrowRight': {
+ if (current == null) {
+ break;
+ }
+ e.preventDefault();
+ if (collapsedOf(current)) {
+ // Collapsed parent → expand.
+ const id = idOf(current);
+ if (id != null) {
+ onToggleExpand?.(id);
+ }
+ } else if (expandedOf(current)) {
+ // Expanded parent → move to first child.
+ const next = items[currentIndex + 1];
+ if (next != null && levelOf(next) > levelOf(current)) {
+ focusItem(next);
+ }
+ }
+ // Leaf → no-op.
+ break;
+ }
+ case 'ArrowLeft': {
+ if (current == null) {
+ break;
+ }
+ e.preventDefault();
+ if (expandedOf(current)) {
+ // Expanded parent → collapse.
+ const id = idOf(current);
+ if (id != null) {
+ onToggleExpand?.(id);
+ }
+ } else {
+ // Otherwise → move to parent treeitem (nearest shallower item
+ // scanning upward in visible order).
+ const currentLevel = levelOf(current);
+ for (let i = currentIndex - 1; i >= 0; i--) {
+ const candidate = items[i];
+ if (candidate != null && levelOf(candidate) < currentLevel) {
+ focusItem(candidate);
+ break;
+ }
+ }
+ }
+ break;
+ }
+ case 'Home': {
+ e.preventDefault();
+ focusEnabledFrom(items, 0, 1);
+ break;
+ }
+ case 'End': {
+ e.preventDefault();
+ focusEnabledFrom(items, items.length - 1, -1);
+ break;
+ }
+ case 'Enter':
+ case ' ': {
+ if (current == null || itemDisabled(current)) {
+ break;
+ }
+ e.preventDefault();
+ const id = idOf(current);
+ // Activate the item: prefer the consumer's onActivate (e.g. click an
+ // inner link/button). Fall back to toggling expansion for a parent
+ // without its own action.
+ const handled = onActivate ? onActivate(current, id) === true : false;
+ if (!handled && current.getAttribute('aria-expanded') != null) {
+ if (id != null) {
+ onToggleExpand?.(id);
+ }
+ }
+ break;
+ }
+ default:
+ break;
+ }
+ },
+ [
+ getItems,
+ typeahead,
+ runTypeahead,
+ focusEnabledFrom,
+ focusItem,
+ collapsedOf,
+ expandedOf,
+ idOf,
+ levelOf,
+ itemDisabled,
+ onToggleExpand,
+ onActivate,
+ ],
+ );
+
+ return {
+ treeRef,
+ handleKeyDown,
+ focusFirst,
+ focusLast,
+ };
+}