Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 67 additions & 5 deletions src/OptionList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ type ScrollTo = NonNullable<React.ComponentRef<typeof Tree>['scrollTo']>;
type ReviseRefOptionListProps = Omit<RefOptionListProps, 'scrollTo'> & { scrollTo: ScrollTo };

const OptionList: React.ForwardRefRenderFunction<ReviseRefOptionListProps> = (_, ref) => {
const { prefixCls, multiple, searchValue, toggleOpen, open, notFoundContent } = useBaseProps();
const { id, prefixCls, multiple, searchValue, toggleOpen, open, notFoundContent, components } =
useBaseProps();

const {
virtual,
Expand All @@ -48,6 +49,7 @@ const OptionList: React.ForwardRefRenderFunction<ReviseRefOptionListProps> = (_,
treeData,
fieldNames,
onSelect,
getInput,
popupMatchSelectWidth,
treeExpandAction,
treeTitleRender,
Expand Down Expand Up @@ -80,6 +82,8 @@ const OptionList: React.ForwardRefRenderFunction<ReviseRefOptionListProps> = (_,
} = React.useContext(LegacyContext);

const treeRef = React.useRef<Tree | null>(null);
const popupRef = React.useRef<HTMLDivElement>(null);
const liveRef = React.useRef<HTMLSpanElement>(null);

const memoTreeData = useMemo(
() => treeData,
Expand Down Expand Up @@ -251,6 +255,58 @@ const OptionList: React.ForwardRefRenderFunction<ReviseRefOptionListProps> = (_,
const [activeKey, setActiveKey] = React.useState<Key>(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;
Expand All @@ -261,7 +317,8 @@ const OptionList: React.ForwardRefRenderFunction<ReviseRefOptionListProps> = (_,
};

// 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
Expand Down Expand Up @@ -318,7 +375,12 @@ const OptionList: React.ForwardRefRenderFunction<ReviseRefOptionListProps> = (_,
// ========================== Render ==========================
if (memoTreeData.length === 0) {
return (
<div role="listbox" className={`${prefixCls}-empty`} onMouseDown={onListMouseDown}>
<div
id={`${id}_list`}
role="tree"
className={`${prefixCls}-empty`}
onMouseDown={onListMouseDown}
>
{notFoundContent}
</div>
);
Expand All @@ -335,9 +397,9 @@ const OptionList: React.ForwardRefRenderFunction<ReviseRefOptionListProps> = (_,
}

return (
<div onMouseDown={onListMouseDown}>
<div onMouseDown={onListMouseDown} ref={popupRef}>
{activeEntity && open && (
<span style={HIDDEN_STYLE} aria-live="assertive">
<span ref={liveRef} style={HIDDEN_STYLE} aria-live="assertive">
{activeEntity.node.value}
</span>
)}
Expand Down
42 changes: 40 additions & 2 deletions src/TreeSelect.tsx
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -129,6 +129,8 @@ function isRawValue(value: SafeKey | LabeledValueType): value is SafeKey {
return !value || typeof value !== 'object';
}

const defaultTreeInput = <input aria-haspopup="tree" />;

const TreeSelect = React.forwardRef<BaseSelectRef, TreeSelectProps>((props, ref) => {
const {
id,
Expand Down Expand Up @@ -198,11 +200,44 @@ const TreeSelect = React.forwardRef<BaseSelectRef, TreeSelectProps>((props, ref)
onPopupScroll,

classNames: treeSelectClassNames,
components,
styles,
...restProps
} = props;

const mergedId = useId(id);
const selectRef = React.useRef<BaseSelectRef>(null);
const mergedRef = useComposeRef(selectRef, ref);

const getInput = React.useCallback(
() => selectRef.current?.nativeElement?.querySelector<HTMLElement>('[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<React.AriaAttributes>(inputComponent)) {
return React.cloneElement(inputComponent, popupProps);
}

const Input = inputComponent as React.ElementType;

return React.forwardRef<HTMLInputElement, React.InputHTMLAttributes<HTMLInputElement>>(
(inputProps, inputRef) => <Input {...inputProps} {...popupProps} ref={inputRef} />,
);
}, [inputComponent]);

const treeComponents = React.useMemo(
() => ({ ...components, input: treeInput }),
[components, treeInput],
);
const treeConduction = treeCheckable && !treeCheckStrictly;
const mergedCheckable = treeCheckable || treeCheckStrictly;
const mergedLabelInValue = treeCheckStrictly || labelInValue;
Expand Down Expand Up @@ -656,6 +691,7 @@ const TreeSelect = React.forwardRef<BaseSelectRef, TreeSelectProps>((props, ref)
treeData: filteredTreeData,
fieldNames: mergedFieldNames,
onSelect: onOptionSelect,
getInput,
treeExpandAction,
treeTitleRender,
onPopupScroll,
Expand All @@ -675,6 +711,7 @@ const TreeSelect = React.forwardRef<BaseSelectRef, TreeSelectProps>((props, ref)
filteredTreeData,
mergedFieldNames,
onOptionSelect,
getInput,
treeExpandAction,
treeTitleRender,
onPopupScroll,
Expand Down Expand Up @@ -735,8 +772,9 @@ const TreeSelect = React.forwardRef<BaseSelectRef, TreeSelectProps>((props, ref)
<TreeSelectContext.Provider value={treeSelectContext}>
<LegacyContext.Provider value={legacyContext}>
<BaseSelect
ref={ref}
ref={mergedRef}
{...restProps}
components={treeComponents}
classNames={treeSelectClassNames}
styles={styles}
// >>> MISC
Expand Down
1 change: 1 addition & 0 deletions src/TreeSelectContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<HTMLDivElement>;
Expand Down
147 changes: 146 additions & 1 deletion tests/Select.spec.tsx
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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(
<TreeSelect
virtual={virtual}
onChange={onChange}
treeData={[{ value: 0, title: 'Parent', children: [{ value: 1, title: 'Child' }] }]}
/>,
);
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(
<TreeSelect open showSearch treeData={[{ value: 'first', title: 'First' }]} />,
);
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<HTMLInputElement>();
const inputComponent = React.forwardRef<HTMLInputElement, React.ComponentProps<'input'>>(
(props, ref) => <input {...props} data-custom-input ref={ref} />,
);
const treeData = [
{ value: 'one', title: 'First' },
{ value: 'two', title: 'Second' },
];
const { container, getByRole, rerender } = render(
<TreeSelect components={{ input: inputComponent }} treeData={treeData} open />,
);
const input = getInput(container);
act(() => input.focus());
keyDown(input, KeyCode.DOWN);
await waitFor(() =>
expect(input).toHaveAttribute(
'aria-activedescendant',
getByRole('treeitem', { name: 'Second' }).id,
),
);
rerender(<TreeSelect components={{ input: inputComponent }} treeData={treeData} open />);
expect(input).toHaveFocus();
expect(input).toHaveAttribute('data-custom-input');
expect(input).toHaveAttribute('aria-haspopup', 'tree');
rerender(
<TreeSelect components={{ input: <input ref={inputRef} /> }} 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(
<TreeSelect
open
treeExpandedKeys={[]}
onTreeExpand={onTreeExpand}
treeData={[
{ value: 'root', title: 'Parent', children: [{ value: 'child', title: 'Child' }] },
]}
/>,
);
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(
<TreeSelect
open
treeData={[
{ value: '東京', title: 'Tokyo' },
{ value: '大阪', title: 'Osaka' },
]}
/>,
);
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(
<TreeSelect
Expand Down
Loading