From 3ae813c30b18f498e4ec3ec0d8a98dc9bb8842d8 Mon Sep 17 00:00:00 2001 From: sviat-barbutsa Date: Tue, 24 Nov 2026 12:28:58 -0600 Subject: [PATCH 1/2] fix: expose the active TreeSelect branch to screen readers --- src/OptionList.tsx | 72 ++++++++- src/TreeSelect.tsx | 42 ++++- src/TreeSelectContext.ts | 1 + tests/Select.spec.tsx | 147 +++++++++++++++++- .../Select.checkable.spec.tsx.snap | 12 +- .../Select.multiple.spec.js.snap | 2 +- tests/__snapshots__/Select.spec.tsx.snap | 25 +-- 7 files changed, 278 insertions(+), 23 deletions(-) diff --git a/src/OptionList.tsx b/src/OptionList.tsx index 75ae9bf3..7f326ca0 100644 --- a/src/OptionList.tsx +++ b/src/OptionList.tsx @@ -38,7 +38,8 @@ type ScrollTo = NonNullable['scrollTo']>; type ReviseRefOptionListProps = Omit & { scrollTo: ScrollTo }; const OptionList: React.ForwardRefRenderFunction = (_, ref) => { - const { prefixCls, multiple, searchValue, toggleOpen, open, notFoundContent } = useBaseProps(); + const { id, prefixCls, multiple, searchValue, toggleOpen, open, notFoundContent, components } = + useBaseProps(); const { virtual, @@ -48,6 +49,7 @@ const OptionList: React.ForwardRefRenderFunction = (_, treeData, fieldNames, onSelect, + getInput, popupMatchSelectWidth, treeExpandAction, treeTitleRender, @@ -80,6 +82,8 @@ const OptionList: React.ForwardRefRenderFunction = (_, } = React.useContext(LegacyContext); const treeRef = React.useRef(null); + const popupRef = React.useRef(null); + const liveRef = React.useRef(null); const memoTreeData = useMemo( () => treeData, @@ -251,6 +255,58 @@ const OptionList: React.ForwardRefRenderFunction = (_, const [activeKey, setActiveKey] = React.useState(null); const activeEntity = keyEntities[activeKey as SafeKey]; + const hasTree = memoTreeData.length > 0; + // Tree owns the item IDs and can update its active item after it has scrolled. + // Expose that same item on the combobox, where keyboard focus stays. + React.useEffect(() => { + const tree = popupRef.current?.querySelector('[role="tree"]'); + const input = getInput(); + + if (!open || !tree || !input) return; + + tree.id = `${id}_list`; + const root = input.getRootNode() as Document | ShadowRoot; + + const syncActiveItem = () => { + const activeId = tree.getAttribute('aria-activedescendant'); + const item = activeId && root.getElementById?.(activeId); + + // Virtual scrolling can unmount a row. Different keys can also produce + // the same DOM ID. Only reference the row the tree actually highlights. + if ( + item && + tree.contains(item) && + item.classList.contains(`${prefixCls}-tree-treenode-active`) + ) { + if (input.getAttribute('aria-activedescendant') !== activeId) { + input.setAttribute('aria-activedescendant', activeId); + } + + if (liveRef.current?.getAttribute('aria-hidden') !== 'true') { + liveRef.current?.setAttribute('aria-hidden', 'true'); + } + } else { + input.removeAttribute('aria-activedescendant'); + liveRef.current?.removeAttribute('aria-hidden'); + } + }; + + syncActiveItem(); + + const observer = new MutationObserver(syncActiveItem); + + observer.observe(tree, { + childList: true, + subtree: true, + attributeFilter: ['aria-activedescendant', 'class'], + }); + + return () => { + observer.disconnect(); + input.removeAttribute('aria-activedescendant'); + }; + }, [open, hasTree, id, getInput, components, multiple, prefixCls]); + React.useEffect(() => { if (!open) { return; @@ -261,7 +317,8 @@ const OptionList: React.ForwardRefRenderFunction = (_, }; // single mode active first checked node - const nextActiveKey = !multiple && checkedKeys.length && !searchValue ? checkedKeys[0] : getFirstNode(); + const nextActiveKey = + !multiple && checkedKeys.length && !searchValue ? checkedKeys[0] : getFirstNode(); setActiveKey(nextActiveKey); // eslint-disable-next-line react-hooks/exhaustive-deps @@ -318,7 +375,12 @@ const OptionList: React.ForwardRefRenderFunction = (_, // ========================== Render ========================== if (memoTreeData.length === 0) { return ( -
+
{notFoundContent}
); @@ -335,9 +397,9 @@ const OptionList: React.ForwardRefRenderFunction = (_, } return ( -
+
{activeEntity && open && ( - + {activeEntity.node.value} )} diff --git a/src/TreeSelect.tsx b/src/TreeSelect.tsx index 75d88f8c..aa2346a8 100644 --- a/src/TreeSelect.tsx +++ b/src/TreeSelect.tsx @@ -1,7 +1,7 @@ import type { BaseSelectPropsWithoutPrivate, BaseSelectRef } from '@rc-component/select'; import { BaseSelect } from '@rc-component/select'; import { conductCheck } from '@rc-component/tree'; -import { useControlledState, useId } from '@rc-component/util'; +import { useComposeRef, useControlledState, useId } from '@rc-component/util'; import * as React from 'react'; import useCache from './hooks/useCache'; import useCheckedKeys from './hooks/useCheckedKeys'; @@ -129,6 +129,8 @@ function isRawValue(value: SafeKey | LabeledValueType): value is SafeKey { return !value || typeof value !== 'object'; } +const defaultTreeInput = ; + const TreeSelect = React.forwardRef((props, ref) => { const { id, @@ -198,11 +200,44 @@ const TreeSelect = React.forwardRef((props, ref) onPopupScroll, classNames: treeSelectClassNames, + components, styles, ...restProps } = props; const mergedId = useId(id); + const selectRef = React.useRef(null); + const mergedRef = useComposeRef(selectRef, ref); + + const getInput = React.useCallback( + () => selectRef.current?.nativeElement?.querySelector('[role="combobox"]') ?? null, + [], + ); + + const inputComponent = components?.input; + + const treeInput = React.useMemo(() => { + if (!inputComponent) { + return defaultTreeInput; + } + + const popupProps = { 'aria-haspopup': 'tree' } as const; + + if (React.isValidElement(inputComponent)) { + return React.cloneElement(inputComponent, popupProps); + } + + const Input = inputComponent as React.ElementType; + + return React.forwardRef>( + (inputProps, inputRef) => , + ); + }, [inputComponent]); + + const treeComponents = React.useMemo( + () => ({ ...components, input: treeInput }), + [components, treeInput], + ); const treeConduction = treeCheckable && !treeCheckStrictly; const mergedCheckable = treeCheckable || treeCheckStrictly; const mergedLabelInValue = treeCheckStrictly || labelInValue; @@ -656,6 +691,7 @@ const TreeSelect = React.forwardRef((props, ref) treeData: filteredTreeData, fieldNames: mergedFieldNames, onSelect: onOptionSelect, + getInput, treeExpandAction, treeTitleRender, onPopupScroll, @@ -675,6 +711,7 @@ const TreeSelect = React.forwardRef((props, ref) filteredTreeData, mergedFieldNames, onOptionSelect, + getInput, treeExpandAction, treeTitleRender, onPopupScroll, @@ -735,8 +772,9 @@ const TreeSelect = React.forwardRef((props, ref) >> MISC diff --git a/src/TreeSelectContext.ts b/src/TreeSelectContext.ts index 617c62f2..338e52af 100644 --- a/src/TreeSelectContext.ts +++ b/src/TreeSelectContext.ts @@ -12,6 +12,7 @@ export interface TreeSelectContextProps { treeData: DataNode[]; fieldNames: FieldNames; onSelect: (value: Key, info: { selected: boolean }) => void; + getInput: () => HTMLElement | null; treeExpandAction?: ExpandAction; treeTitleRender?: (node: any) => React.ReactNode; onPopupScroll?: React.UIEventHandler; diff --git a/tests/Select.spec.tsx b/tests/Select.spec.tsx index e1352b09..b35c6c08 100644 --- a/tests/Select.spec.tsx +++ b/tests/Select.spec.tsx @@ -1,4 +1,4 @@ -import { act, createEvent, render, fireEvent } from '@testing-library/react'; +import { act, createEvent, render, fireEvent, waitFor } from '@testing-library/react'; import { KeyCode } from '@rc-component/util'; import React from 'react'; import TreeSelect, { TreeNode } from '../src'; @@ -521,6 +521,151 @@ describe('TreeSelect.basic', () => { expect(onChange).not.toHaveBeenCalled(); }); + it.each([true, false])( + 'exposes the active branch state to the combobox (virtual=%s)', + async virtual => { + const onChange = jest.fn(); + const { container, getByRole } = render( + , + ); + const input = getInput(container); + act(() => input.focus()); + triggerOpen(container); + const parent = getByRole('treeitem', { name: 'Parent' }); + expect(input).toHaveAttribute('aria-haspopup', 'tree'); + expect(input).toHaveAttribute('aria-controls', getByRole('tree').id); + await waitFor(() => expect(input).toHaveAttribute('aria-activedescendant', parent.id)); + expect(parent).toHaveAttribute('aria-expanded', 'false'); + + keyDown(input, KeyCode.RIGHT); + expect(parent).toHaveAttribute('aria-expanded', 'true'); + expect(input).toHaveAttribute('aria-activedescendant', parent.id); + keyDown(input, KeyCode.LEFT); + expect(parent).toHaveAttribute('aria-expanded', 'false'); + expect(input).toHaveAttribute('aria-activedescendant', parent.id); + keyDown(input, KeyCode.RIGHT); + keyDown(input, KeyCode.DOWN); + const child = getByRole('treeitem', { name: 'Child' }); + await waitFor(() => expect(input).toHaveAttribute('aria-activedescendant', child.id)); + expect(child).not.toHaveAttribute('aria-expanded'); + expect(input).toHaveFocus(); + expect(onChange).not.toHaveBeenCalled(); + fireEvent.keyDown(input, { key: 'Escape', keyCode: KeyCode.ESC, which: KeyCode.ESC }); + await waitFor(() => expect(input).not.toHaveAttribute('aria-activedescendant')); + }, + ); + + it('clears the active descendant when a search has no matches', async () => { + const { container, getByRole } = render( + , + ); + const input = getInput(container); + await waitFor(() => + expect(input).toHaveAttribute('aria-activedescendant', getByRole('treeitem').id), + ); + search(container, 'missing'); + expect(input).not.toHaveAttribute('aria-activedescendant'); + expect(input).toHaveAttribute('aria-controls', getByRole('tree').id); + search(container, ''); + await waitFor(() => + expect(input).toHaveAttribute('aria-activedescendant', getByRole('treeitem').id), + ); + }); + + it('keeps the custom input focused when the active tree item changes', async () => { + const inputRef = React.createRef(); + const inputComponent = React.forwardRef>( + (props, ref) => , + ); + const treeData = [ + { value: 'one', title: 'First' }, + { value: 'two', title: 'Second' }, + ]; + const { container, getByRole, rerender } = render( + , + ); + const input = getInput(container); + act(() => input.focus()); + keyDown(input, KeyCode.DOWN); + await waitFor(() => + expect(input).toHaveAttribute( + 'aria-activedescendant', + getByRole('treeitem', { name: 'Second' }).id, + ), + ); + rerender(); + expect(input).toHaveFocus(); + expect(input).toHaveAttribute('data-custom-input'); + expect(input).toHaveAttribute('aria-haspopup', 'tree'); + rerender( + }} treeData={treeData} open />, + ); + expect(inputRef.current).toBe(getInput(container)); + expect(inputRef.current).toHaveAttribute('aria-haspopup', 'tree'); + await waitFor(() => + expect(inputRef.current).toHaveAttribute( + 'aria-activedescendant', + getByRole('treeitem', { name: 'Second' }).id, + ), + ); + }); + + it('keeps the controlled branch state when expansion is declined', async () => { + const onTreeExpand = jest.fn(); + const { container, getByRole } = render( + , + ); + const input = getInput(container); + const parent = getByRole('treeitem', { name: 'Parent' }); + await waitFor(() => expect(input).toHaveAttribute('aria-activedescendant', parent.id)); + keyDown(input, KeyCode.RIGHT); + expect(onTreeExpand).toHaveBeenCalledWith(['root']); + expect(input).toHaveAttribute('aria-activedescendant', parent.id); + expect(parent).toHaveAttribute('aria-expanded', 'false'); + }); + + it('does not point to a different row when keys produce the same DOM ID', async () => { + const { container, getByRole } = render( + , + ); + const input = getInput(container); + await waitFor(() => + expect(input).toHaveAttribute( + 'aria-activedescendant', + getByRole('treeitem', { name: 'Tokyo' }).id, + ), + ); + keyDown(input, KeyCode.DOWN); + await waitFor(() => expect(input).not.toHaveAttribute('aria-activedescendant')); + const fallback = document.querySelector('[aria-live="assertive"]'); + expect(fallback).toHaveTextContent('大阪'); + expect(fallback).not.toHaveAttribute('aria-hidden', 'true'); + keyDown(input, KeyCode.UP); + await waitFor(() => + expect(input).toHaveAttribute( + 'aria-activedescendant', + getByRole('treeitem', { name: 'Tokyo' }).id, + ), + ); + }); + it('active index matches value', () => { const { container } = render( @@ -298,7 +299,7 @@ exports[`TreeSelect.checkable uncheck remove by selector not treeCheckStrictly 2 aria-autocomplete="list" aria-controls="test-id_list" aria-expanded="true" - aria-haspopup="listbox" + aria-haspopup="tree" aria-owns="test-id_list" autocomplete="new-password" class="rc-tree-select-input" @@ -343,6 +344,7 @@ exports[`TreeSelect.checkable uncheck remove by selector not treeCheckStrictly 2
@@ -572,7 +574,7 @@ exports[`TreeSelect.checkable uncheck remove by tree check 1`] = ` aria-autocomplete="list" aria-controls="test-id_list" aria-expanded="true" - aria-haspopup="listbox" + aria-haspopup="tree" aria-owns="test-id_list" autocomplete="new-password" class="rc-tree-select-input" @@ -617,6 +619,7 @@ exports[`TreeSelect.checkable uncheck remove by tree check 1`] = `
@@ -785,7 +788,7 @@ exports[`TreeSelect.checkable uncheck remove by tree check 2`] = ` aria-autocomplete="list" aria-controls="test-id_list" aria-expanded="true" - aria-haspopup="listbox" + aria-haspopup="tree" aria-owns="test-id_list" autocomplete="new-password" class="rc-tree-select-input" @@ -830,6 +833,7 @@ exports[`TreeSelect.checkable uncheck remove by tree check 2`] = `
diff --git a/tests/__snapshots__/Select.multiple.spec.js.snap b/tests/__snapshots__/Select.multiple.spec.js.snap index 5ff83e57..526eb573 100644 --- a/tests/__snapshots__/Select.multiple.spec.js.snap +++ b/tests/__snapshots__/Select.multiple.spec.js.snap @@ -22,7 +22,7 @@ exports[`TreeSelect.multiple can hide search box by showSearch = false 1`] = ` @@ -381,7 +382,7 @@ exports[`TreeSelect.basic render renders treeDataSimpleMode correctly 1`] = ` aria-autocomplete="list" aria-controls="test-id_list" aria-expanded="true" - aria-haspopup="listbox" + aria-haspopup="tree" aria-owns="test-id_list" autocomplete="new-password" class="rc-tree-select-input" @@ -424,6 +425,7 @@ exports[`TreeSelect.basic render renders treeDataSimpleMode correctly 1`] = `
@@ -526,7 +528,7 @@ exports[`TreeSelect.basic search nodes check tree changed by filter 1`] = ` aria-autocomplete="list" aria-controls="test-id_list" aria-expanded="true" - aria-haspopup="listbox" + aria-haspopup="tree" aria-owns="test-id_list" autocomplete="new-password" class="rc-tree-select-input" @@ -568,6 +570,7 @@ exports[`TreeSelect.basic search nodes check tree changed by filter 1`] = `
@@ -636,7 +639,7 @@ exports[`TreeSelect.basic search nodes check tree changed by filter 2`] = ` aria-autocomplete="list" aria-controls="test-id_list" aria-expanded="true" - aria-haspopup="listbox" + aria-haspopup="tree" aria-owns="test-id_list" autocomplete="new-password" class="rc-tree-select-input" @@ -678,6 +681,7 @@ exports[`TreeSelect.basic search nodes check tree changed by filter 2`] = `
@@ -775,7 +779,7 @@ exports[`TreeSelect.basic search nodes filter node but not remove then 1`] = ` aria-autocomplete="list" aria-controls="test-id_list" aria-expanded="true" - aria-haspopup="listbox" + aria-haspopup="tree" aria-owns="test-id_list" autocomplete="new-password" class="rc-tree-select-input" @@ -817,6 +821,7 @@ exports[`TreeSelect.basic search nodes filter node but not remove then 1`] = `
@@ -912,7 +917,7 @@ exports[`TreeSelect.basic search nodes renders search input 1`] = ` aria-autocomplete="list" aria-controls="test-id_list" aria-expanded="true" - aria-haspopup="listbox" + aria-haspopup="tree" aria-owns="test-id_list" autocomplete="new-password" class="rc-tree-select-input" From e8ff51c7c5481d10de19d5caa1a0ad8b00700b23 Mon Sep 17 00:00:00 2001 From: sviat-barbutsa Date: Tue, 24 Nov 2026 12:55:10 -0600 Subject: [PATCH 2/2] test: cover active branch restoration after virtual scrolling --- tests/Select.virtual.spec.tsx | 38 +++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 tests/Select.virtual.spec.tsx diff --git a/tests/Select.virtual.spec.tsx b/tests/Select.virtual.spec.tsx new file mode 100644 index 00000000..2d4809e5 --- /dev/null +++ b/tests/Select.virtual.spec.tsx @@ -0,0 +1,38 @@ +import { act, fireEvent, render, waitFor } from '@testing-library/react'; +import React from 'react'; +import TreeSelect from '../src'; + +jest.unmock('@rc-component/virtual-list'); + +it('restores the active descendant when its branch scrolls back into view', async () => { + const treeData = [ + { value: 'parent', title: 'Parent', children: [{ value: 'child', title: 'Child' }] }, + ...Array.from({ length: 30 }, (_, index) => ({ value: index, title: `Row ${index}` })), + ]; + const { getByRole, getByText, queryByRole } = render( + , + ); + const input = getByRole('combobox'); + act(() => input.focus()); + const parent = getByRole('treeitem', { name: 'Parent' }); + const getFallback = () => getByText('parent', { selector: '[aria-live="assertive"]' }); + const holder = getByRole('tree').querySelector('.rc-tree-select-tree-list-holder')!; + + await waitFor(() => expect(input).toHaveAttribute('aria-activedescendant', parent.id)); + expect(getFallback()).toHaveAttribute('aria-hidden', 'true'); + + fireEvent.scroll(holder, { target: { scrollTop: 200 } }); + await waitFor(() => expect(input).not.toHaveAttribute('aria-activedescendant')); + expect(queryByRole('treeitem', { name: 'Parent' })).not.toBeInTheDocument(); + expect(getFallback()).not.toHaveAttribute('aria-hidden', 'true'); + + fireEvent.scroll(holder, { target: { scrollTop: 0 } }); + await waitFor(() => + expect(input).toHaveAttribute( + 'aria-activedescendant', + getByRole('treeitem', { name: 'Parent' }).id, + ), + ); + expect(getFallback()).toHaveAttribute('aria-hidden', 'true'); + expect(input).toHaveFocus(); +});