Skip to content

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

TypeScript

fix(TreeList): rows are named by their label and described by their description (#7472)

Cindy Zhang12ad57a90ed1
diff --git a/.changeset/treelist-row-name.md b/.changeset/treelist-row-name.md
new file mode 100644
index 0000000000..380f101354
--- /dev/null
+++ b/.changeset/treelist-row-name.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] `TreeList`: each row is now named by its label alone and described by its description (`aria-labelledby`/`aria-describedby` on the `treeitem`), so screen readers no longer read the chevron toggle's label or the description as part of a row's name, and link and action rows are named as rows, not only through their inner control. Typeahead matches the label rather than the row's whole text.
+
+@cixzhang
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index bec74c69c0..ae5b44bad5 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -1676,6 +1676,50 @@ jobs:
retention-days: 30
if-no-files-found: warn
+ # A treeitem's computed name and description are accessibility-tree facts
+ # jsdom approximates but a browser decides. Run the TreeList row-naming
+ # evidence whenever TreeList, its focus hook, or the story changes.
+ - name: Run TreeList row-naming evidence
+ id: treelist-row-names
+ if: ${{ !cancelled() && github.event_name == 'pull_request' }}
+ env:
+ BASE_SHA: ${{ github.event.pull_request.base.sha }}
+ PLAYWRIGHT_JSON_OUTPUT_FILE: treelist-row-names/report.json
+ run: |
+ should_run=false
+ # The helper comes from the base, since an older PR head lacks it.
+ # Exit 1 means out of scope; 0 in scope; 2 unknown, so run.
+ scope=2
+ helper="$(mktemp)"
+ if git fetch --quiet --no-tags --depth=1 origin "$BASE_SHA" \
+ && git show "$BASE_SHA:.github/scripts/pr-scope-touches.sh" > "$helper"; then
+ scope=0
+ bash "$helper" "$BASE_SHA" \
+ '^(packages/core/src/TreeList/|packages/core/src/hooks/useTreeFocus|apps/storybook/stories/TreeListA11y)' || scope=$?
+ fi
+ if [ "$scope" != 1 ]; then
+ should_run=true
+ fi
+ echo "should_run=${should_run}" >> "$GITHUB_OUTPUT"
+ if [ "$should_run" != true ]; then
+ echo "TreeList is not in PR scope; skipping row-naming evidence."
+ exit 0
+ fi
+ pnpm exec playwright test \
+ packages/core/src/TreeList/__tests__/TreeListRowNames.a11y.chromium.spec.ts \
+ --project chromium \
+ --reporter list,json \
+ --output treelist-row-names-output
+
+ - name: Upload TreeList row-naming evidence
+ if: ${{ !cancelled() && steps.treelist-row-names.outputs.should_run == 'true' }}
+ uses: actions/upload-artifact@v7
+ with:
+ name: treelist-row-names-evidence-${{ needs.build-storybook.outputs.short_hash }}
+ path: treelist-row-names/
+ retention-days: 30
+ if-no-files-found: warn
+
# The link contract's role, name, Tab, Enter, and pointer-release outcomes
# are accessibility-tree and real-browser facts that jsdom cannot observe.
# Run the contract's own fixture proof and the Link binding whenever Link
diff --git a/apps/storybook/stories/TreeListA11y.stories.tsx b/apps/storybook/stories/TreeListA11y.stories.tsx
new file mode 100644
index 0000000000..02c36598cf
--- /dev/null
+++ b/apps/storybook/stories/TreeListA11y.stories.tsx
@@ -0,0 +1,55 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file TreeListA11y.stories.tsx
+ * @input A TreeList whose rows exercise every way a row can be named: a parent with a chevron, a plain row with a description, a link row, and an action row
+ * @output One checked-in story for the Chromium row-naming evidence; excluded from the visual matrix
+ * @position Browser fixture for component:TreeList AR1 (rows named by their label and described by their description)
+ */
+
+import type {Meta, StoryObj} from '@storybook/react';
+import {TreeList} from '@astryxdesign/core/TreeList';
+
+const meta = {
+ title: 'A11y/TreeList Row Names',
+ tags: ['no-visual'],
+ parameters: {layout: 'padded'},
+} satisfies Meta;
+
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+export const RowNames: Story = {
+ render: () => (
+ <TreeList
+ aria-label="Files"
+ items={[
+ {
+ id: 'docs',
+ label: 'Documents',
+ description: 'Shared with the team',
+ children: [{id: 'annual', label: 'Annual report'}],
+ },
+ {
+ id: 'budget',
+ label: 'Budget',
+ description: 'Updated yesterday',
+ startContent: <span>3</span>,
+ endContent: <button type="button">Pin</button>,
+ },
+ {
+ id: 'report',
+ label: 'Report',
+ description: 'Opens the report',
+ href: '#report',
+ },
+ {
+ id: 'export',
+ label: 'Export',
+ description: 'Downloads a file',
+ onClick: () => {},
+ },
+ ]}
+ />
+ ),
+};
diff --git a/packages/core/src/TreeList/TreeList.spec.md b/packages/core/src/TreeList/TreeList.spec.md
index 90752b774c..11ad25c114 100644
--- a/packages/core/src/TreeList/TreeList.spec.md
+++ b/packages/core/src/TreeList/TreeList.spec.md
@@ -161,13 +161,7 @@ replace component-owned semantic or interaction props.
and last visible rows; Enter and Space activate the focused row; typing letters
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 not
- enforce it, claims no `aria-multiselectable`, and has no selection keyboard. Implementation gap until
- its fix ships: a parent row's name reads "Toggle children <label>" because the
- chevron button sits inside the `treeitem`; a plain row folds its description
- into its name; a row with `href` or `onClick` names and describes its inner
- control rather than the row; start and end content add their text and
- control names to the row's name; and typeahead matches the row's whole text
- rather than its label.
+ enforce it, claims no `aria-multiselectable`, and has no selection keyboard.
## Design relationships
@@ -248,15 +242,15 @@ 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` 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` |
-| 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` 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` |
+| 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 support
and 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.tsx
index 9c1543b9c3..907c29307c 100644
--- a/packages/core/src/TreeList/TreeList.test.tsx
+++ b/packages/core/src/TreeList/TreeList.test.tsx
@@ -170,6 +170,78 @@ describe('TreeList', () => {
expect(screen.getByText('Description text')).toBeInTheDocument();
});
+ // ===========================================================================
+ // Row accessible name and description (APG tree view: named by the label)
+ // ===========================================================================
+
+ it('names a parent row by its label alone, not the chevron toggle', () => {
+ const items: TreeListItemData[] = [
+ {id: 'docs', label: 'Documents', children: [{id: 'a', label: 'Annual'}]},
+ ];
+ render(<TreeList items={items} />);
+ const row = screen.getByText('Documents').closest('li')!;
+ expect(row).toHaveAccessibleName('Documents');
+ });
+
+ it('names a plain row by its label and describes it with its description', () => {
+ const items: TreeListItemData[] = [
+ {id: 'a', label: 'Budget', description: 'Updated yesterday'},
+ ];
+ render(<TreeList items={items} />);
+ const row = screen.getByText('Budget').closest('li')!;
+ expect(row).toHaveAccessibleName('Budget');
+ expect(row).toHaveAccessibleDescription('Updated yesterday');
+ });
+
+ it('names and describes link and action rows themselves, not only their inner control', () => {
+ const items: TreeListItemData[] = [
+ {id: 'l', label: 'Report', description: 'Opens the report', href: '#'},
+ {
+ id: 'b',
+ label: 'Export',
+ description: 'Downloads a file',
+ onClick: () => {},
+ },
+ ];
+ render(<TreeList items={items} />);
+ const link = screen.getByText('Report').closest('li')!;
+ expect(link).toHaveAccessibleName('Report');
+ expect(link).toHaveAccessibleDescription('Opens the report');
+ const action = screen.getByText('Export').closest('li')!;
+ expect(action).toHaveAccessibleName('Export');
+ expect(action).toHaveAccessibleDescription('Downloads a file');
+ });
+
+ it('keeps start and end content, including controls, out of the row name', () => {
+ const items: TreeListItemData[] = [
+ {
+ id: 'a',
+ label: 'Invoices',
+ startContent: <span>12</span>,
+ endContent: <button type="button">Pin folder</button>,
+ },
+ ];
+ render(<TreeList items={items} />);
+ const row = screen.getByText('Invoices').closest('li')!;
+ expect(row).toHaveAccessibleName('Invoices');
+ });
+
+ it('typeahead matches the label, not the description or start content', async () => {
+ const user = userEvent.setup();
+ const items: TreeListItemData[] = [
+ {id: 'a', label: 'Apple', description: 'Cherry-red fruit'},
+ {id: 'b', label: 'Banana', startContent: <span>Curved</span>},
+ {id: 'c', label: 'Cherry'},
+ ];
+ render(<TreeList items={items} />);
+ const apple = screen.getByText('Apple').closest('li')!;
+ apple.focus();
+ await user.keyboard('c');
+ expect(document.activeElement).toBe(
+ screen.getByText('Cherry').closest('li'),
+ );
+ });
+
// ===========================================================================
// Semantic HTML
// ===========================================================================
diff --git a/packages/core/src/TreeList/TreeList.tsx b/packages/core/src/TreeList/TreeList.tsx
index 9fd700a6ee..17ca2b068a 100644
--- a/packages/core/src/TreeList/TreeList.tsx
+++ b/packages/core/src/TreeList/TreeList.tsx
@@ -27,7 +27,7 @@ import type {
TreeListVariant,
} from './TreeListTypes';
import {themeProps} from '../utils/themeProps';
-import {useTreeFocus} from '../hooks/useTreeFocus';
+import {useTreeFocusInternal} from '../hooks/useTreeFocus';
// =============================================================================
// Types
@@ -255,11 +255,15 @@ export function TreeList({
return false;
}, []);
- const {treeRef, handleKeyDown, handleFocus} = useTreeFocus<HTMLUListElement>({
- onToggleExpand: handleToggle,
- onActivate: activateItem,
- hasRovingTabIndex: true,
- });
+ const {treeRef, handleKeyDown, handleFocus} =
+ useTreeFocusInternal<HTMLUListElement>({
+ onToggleExpand: handleToggle,
+ onActivate: activateItem,
+ hasRovingTabIndex: true,
+ // Rows are named by their label (AR1); typeahead matches that label, not
+ // the chevron toggle, start content or description.
+ matchLabelledBy: true,
+ });
const handleRootKeyDown = useCallback(
(e: React.KeyboardEvent<HTMLDivElement>) => {
diff --git a/packages/core/src/TreeList/TreeListItem.tsx b/packages/core/src/TreeList/TreeListItem.tsx
index 0a5acb2263..d1e4327e5e 100644
--- a/packages/core/src/TreeList/TreeListItem.tsx
+++ b/packages/core/src/TreeList/TreeListItem.tsx
@@ -557,6 +557,11 @@ export function TreeListItem({
return (
<li
role="treeitem"
+ // The row is named by its label alone and described by its description
+ // (APG tree view): without these the name would be the row's whole text,
+ // chevron button label and description included.
+ aria-labelledby={labelId}
+ aria-describedby={description != null ? descriptionId : undefined}
aria-expanded={hasChildren ? isExpanded : undefined}
aria-selected={isSelected || undefined}
aria-disabled={isDisabled || undefined}
diff --git a/packages/core/src/TreeList/__tests__/TreeListRowNames.a11y.chromium.spec.ts b/packages/core/src/TreeList/__tests__/TreeListRowNames.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..047b11bed8
--- /dev/null
+++ b/packages/core/src/TreeList/__tests__/TreeListRowNames.a11y.chromium.spec.ts
@@ -0,0 +1,82 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file TreeListRowNames.a11y.chromium.spec.ts
+ * @input The built TreeList row-names story in real Chromium
+ * @output Proof that the browser names every treeitem by its label alone and describes it by its description — the chevron toggle and inner link/button do not leak into the row's name
+ * @position Chromium evidence for component:TreeList AR1 (component:TreeList's row-naming implementation gap, closed)
+ */
+
+import {expect, test, type Page} from '@playwright/test';
+import {
+ createChromiumHarness,
+ holdMotionStill,
+} from '@astryxdesign/a11y-spec/chromium';
+import {
+ DEFAULT_STORYBOOK_DIR,
+ serveStorybook,
+ type StaticServer,
+} from '@astryxdesign/a11y-spec/storybook';
+
+const STORY_ID = 'a11y-treelist-row-names--row-names';
+
+const ROWS = [
+ {id: 'docs', name: 'Documents', description: 'Shared with the team'},
+ // Carries start content and an end-content button: neither joins the name.
+ {id: 'budget', name: 'Budget', description: 'Updated yesterday'},
+ {id: 'report', name: 'Report', description: 'Opens the report'},
+ {id: 'export', name: 'Export', description: 'Downloads a file'},
+] as const;
+
+let storybook: StaticServer;
+
+test.beforeAll(async () => {
+ storybook = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+});
+
+test.afterAll(async () => {
+ await storybook?.close();
+});
+
+async function mount(page: Page): Promise<void> {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=${STORY_ID}&viewMode=story`,
+ {waitUntil: 'load'},
+ );
+ await holdMotionStill(page);
+ await page.locator('[role="tree"]').waitFor({state: 'attached'});
+}
+
+for (const row of ROWS) {
+ test(`the browser names the "${row.name}" row by its label and describes it by its description`, async ({
+ page,
+ }) => {
+ await mount(page);
+ const cdp = await page.context().newCDPSession(page);
+ const harness = createChromiumHarness({
+ page,
+ cdp,
+ subject: page.locator(`[role="treeitem"][data-tree-id="${row.id}"]`),
+ });
+ const computed = await (await harness.subject()).computed();
+ expect(computed.role).toBe('treeitem');
+ expect(computed.name).toBe(row.name);
+ expect(computed.description).toBe(row.description);
+ });
+}
+
+test('typing a letter matches the label, so a row whose text begins with start content is reachable', async ({
+ page,
+}) => {
+ await mount(page);
+ const docsRow = page.locator('[role="treeitem"][data-tree-id="docs"]');
+ await docsRow.focus();
+ // The Budget row's text begins with its start content ("3"), so a
+ // whole-text match never finds it under "b"; the label match does.
+ await page.keyboard.press('b');
+ await expect(
+ page.locator('[role="treeitem"][data-tree-id="budget"]'),
+ ).toBeFocused();
+});
diff --git a/packages/core/src/hooks/useTreeFocus.test.tsx b/packages/core/src/hooks/useTreeFocus.test.tsx
index 7d607633b3..92d366df58 100644
--- a/packages/core/src/hooks/useTreeFocus.test.tsx
+++ b/packages/core/src/hooks/useTreeFocus.test.tsx
@@ -262,6 +262,43 @@ describe('useTreeFocus activation + typeahead', () => {
expect(screen.getByTestId('c')).toHaveFocus();
});
+ it('typeahead matches whole text for a direct caller, even when an item carries aria-labelledby and the options smuggle the internal flag', () => {
+ function LabelledTree() {
+ // An untyped options object trying to reach the internal flag through
+ // the public hook: it must have no effect.
+ const smuggled = {
+ hasRovingTabIndex: true,
+ matchLabelledBy: true,
+ } as Record<string, unknown>;
+ const {treeRef, handleKeyDown, handleFocus} =
+ useTreeFocus<HTMLUListElement>(smuggled);
+ return (
+ <ul
+ ref={treeRef}
+ role="tree"
+ onKeyDown={handleKeyDown}
+ onFocus={handleFocus}>
+ <li role="treeitem" tabIndex={0} data-testid="first">
+ First
+ </li>
+ <li
+ role="treeitem"
+ tabIndex={-1}
+ aria-labelledby="lbl"
+ data-testid="labelled">
+ <span>zz</span> <span id="lbl">Budget</span>
+ </li>
+ </ul>
+ );
+ }
+ render(<LabelledTree />);
+ const tree = screen.getByRole('tree');
+ screen.getByTestId('first').focus();
+ // Released behavior: the text content ("zz Budget") is what matches.
+ fireEvent.keyDown(tree, {key: 'z'});
+ expect(screen.getByTestId('labelled')).toHaveFocus();
+ });
+
it('typeahead cycles through same-letter matches on repeated presses', () => {
const nodes: Node[] = [
{id: 'apple', label: 'Apple', level: 1},
diff --git a/packages/core/src/hooks/useTreeFocus.ts b/packages/core/src/hooks/useTreeFocus.ts
index 1fd44116a2..c9310b144a 100644
--- a/packages/core/src/hooks/useTreeFocus.ts
+++ b/packages/core/src/hooks/useTreeFocus.ts
@@ -176,6 +176,28 @@ export interface UseTreeFocusReturn<T extends HTMLElement = HTMLElement> {
focusLast: () => void;
}
+/**
+ * The text typeahead matches against. With `matchLabelledBy`, the row's
+ * `aria-labelledby` text (the label alone) when it has one; otherwise, and by
+ * default, its text content.
+ */
+function itemLabelText(item: HTMLElement, matchLabelledBy: boolean): string {
+ const labelledBy = matchLabelledBy
+ ? item.getAttribute('aria-labelledby')
+ : null;
+ if (labelledBy != null) {
+ const label = labelledBy
+ .split(/\s+/)
+ .map(id => item.ownerDocument.getElementById(id)?.textContent ?? '')
+ .join(' ')
+ .trim();
+ if (label !== '') {
+ return label;
+ }
+ }
+ return (item.textContent ?? '').trim();
+}
+
/**
* Hook for managing roving-tabindex focus + the WAI-ARIA tree keyboard model.
*
@@ -208,8 +230,38 @@ export interface UseTreeFocusReturn<T extends HTMLElement = HTMLElement> {
* </ul>
* ```
*/
+
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});
+}
+
+/**
+ * Options the package's own components can pass beyond the public hook.
+ *
+ * Not exported from the package: TreeList imports this module directly, so
+ * `UseTreeFocusOptions` stays exactly as released.
+ */
+export type UseTreeFocusInternalOptions = UseTreeFocusOptions & {
+ /**
+ * Match typeahead against the item's `aria-labelledby` text (its label
+ * alone) instead of its whole text content, so start content, a chevron
+ * toggle or a description never takes part. TreeList passes this; the
+ * released text match stays the default for direct callers.
+ * @default false
+ */
+ matchLabelledBy?: boolean;
+};
+
+/**
+ * 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> {
const {
itemSelector = '[role="treeitem"]',
@@ -222,6 +274,7 @@ export function useTreeFocus<T extends HTMLElement = HTMLElement>(
onActivate,
typeahead = true,
typeaheadResetMs = DEFAULT_TYPEAHEAD_RESET_MS,
+ matchLabelledBy = false,
onActiveChange,
hasRovingTabIndex = false,
} = options;
@@ -399,14 +452,14 @@ export function useTreeFocus<T extends HTMLElement = HTMLElement>(
const match = ordered.find(
item =>
!itemDisabled(item) &&
- (item.textContent ?? '').trim().toLowerCase().startsWith(query),
+ itemLabelText(item, matchLabelledBy).toLowerCase().startsWith(query),
);
if (match != null) {
e.preventDefault();
focusItem(match);
}
},
- [typeaheadResetMs, itemDisabled, focusItem],
+ [typeaheadResetMs, itemDisabled, focusItem, matchLabelledBy],
);
const handleKeyDown = useCallback(