Skip to content

Commit

Permalink
[TreeView] correct visibleNodes on re-render
Browse files Browse the repository at this point in the history
  • Loading branch information
tonyhallett committed Mar 17, 2020
1 parent 701e3ad commit d2eb0d2
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
34 changes: 34 additions & 0 deletions packages/material-ui-lab/src/TreeItem/TreeItem.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -436,6 +436,40 @@ describe('<TreeItem />', () => {
expect(getByTestId('two')).to.have.focus;
});

it('moves focus to a sibling node after conditional rendering', () => {
function TestComponent() {
const [hide, setState] = React.useState(false);

return (
<React.Fragment>
<button type="button" onClick={() => setState(value => !value)}>
Hide
</button>
<TreeView defaultExpanded={['one']}>
{!hide && (
<TreeItem nodeId="one" label="one" data-testid="one">
<TreeItem nodeId="two" label="two" data-testid="two" />
</TreeItem>
)}
<TreeItem nodeId="three" label="three" />
</TreeView>
</React.Fragment>
);
}

const { getByText, queryByText, getByTestId } = render(<TestComponent />);

expect(getByText('one')).to.not.be.null;
fireEvent.click(getByText('Hide'));
expect(queryByText('one')).to.be.null;
fireEvent.click(getByText('Hide'));
expect(getByText('one')).to.not.be.null;
getByTestId('one').focus();
fireEvent.keyDown(document.activeElement, { key: 'ArrowDown' });

expect(getByTestId('two')).to.have.focus;
});

it('moves focus to a child node', () => {
const { getByTestId } = render(
<TreeView defaultExpanded={['one']}>
Expand Down
3 changes: 1 addition & 2 deletions packages/material-ui-lab/src/TreeView/TreeView.js
Original file line number Diff line number Diff line change
Expand Up @@ -455,7 +455,6 @@ const TreeView = React.forwardRef(function TreeView(props, ref) {
if (index === 0) {
setTabbable(id);
}
nodeMap.current[id] = { parent: null };
});
visibleNodes.current = nodeMap.current[-1].children;
prevChildIds.current = childIds;
Expand All @@ -480,7 +479,7 @@ const TreeView = React.forwardRef(function TreeView(props, ref) {
if (childrenCalculated) {
visibleNodes.current = buildVisible(nodeMap.current[-1].children);
}
}, [expanded, childrenCalculated, isExpanded]);
}, [expanded, childrenCalculated, isExpanded, children]);

return (
<TreeViewContext.Provider
Expand Down

0 comments on commit d2eb0d2

Please sign in to comment.