Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[TreeView] Correctly select items in deeply nested trees #26413

Merged
merged 1 commit into from
May 22, 2021
Merged
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
22 changes: 10 additions & 12 deletions packages/material-ui-lab/src/TreeView/TreeView.js
Original file line number Diff line number Diff line change
Expand Up @@ -198,22 +198,20 @@ const TreeView = React.forwardRef(function TreeView(inProps, ref) {
return getNavigableChildrenIds(id)[0];
}

// Try to get next sibling
const node = nodeMap.current[id];
const siblings = getNavigableChildrenIds(node.parentId);
let node = nodeMap.current[id];
while (node != null) {
// Try to get next sibling
const siblings = getNavigableChildrenIds(node.parentId);
const nextSibling = siblings[siblings.indexOf(node.id) + 1];

const nextSibling = siblings[siblings.indexOf(id) + 1];
if (nextSibling) {
return nextSibling;
}

if (nextSibling) {
return nextSibling;
// If the sibling does not exist, go up a level to the parent and try again.
node = nodeMap.current[node.parentId];
}

// try to get parent's next sibling
const parent = nodeMap.current[node.parentId];
if (parent) {
const parentSiblings = getNavigableChildrenIds(parent.parentId);
return parentSiblings[parentSiblings.indexOf(parent.id) + 1];
}
return null;
};

Expand Down
18 changes: 18 additions & 0 deletions packages/material-ui-lab/src/TreeView/TreeView.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,24 @@ describe('<TreeView />', () => {
fireEvent.click(screen.getByText('one'), { shiftKey: true });
});

it('should not crash when selecting multiple items in a deeply nested tree', () => {
render(
<TreeView multiSelect defaultExpanded={['1', '1.1', '2']}>
<TreeItem nodeId="1" label="Item 1">
<TreeItem nodeId="1.1" label="Item 1.1">
<TreeItem nodeId="1.1.1" data-testid="item-1.1.1" label="Item 1.1.1" />
</TreeItem>
</TreeItem>
<TreeItem nodeId="2" data-testid="item-2" label="Item 2" />
</TreeView>,
);
fireEvent.click(screen.getByText('Item 1.1.1'));
fireEvent.click(screen.getByText('Item 2'), { shiftKey: true });

expect(screen.getByTestId('item-1.1.1')).to.have.attribute('aria-selected', 'true');
expect(screen.getByTestId('item-2')).to.have.attribute('aria-selected', 'true');
});

it('should not crash on keydown on an empty tree', () => {
render(<TreeView />);

Expand Down