diff --git a/src/TreeView/index.tsx b/src/TreeView/index.tsx index cb622c3..5c3d3c2 100644 --- a/src/TreeView/index.tsx +++ b/src/TreeView/index.tsx @@ -289,33 +289,37 @@ const useTree = ({ //controlled collapsing if (diffCollapseIds.size) { for (const id of diffCollapseIds) { - if (isBranchNode(data, id) || getTreeNode(data, id).isBranch) { - const ids = [id, ...getDescendants(data, id, new Set())]; - dispatch({ - type: treeTypes.collapseMany, - ids: ids, - lastInteractedWith: id, - }); + if (data.find((n) => n.id === id)) { + if (isBranchNode(data, id) || getTreeNode(data, id).isBranch) { + const ids = [id, ...getDescendants(data, id, new Set())]; + dispatch({ + type: treeTypes.collapseMany, + ids: ids, + lastInteractedWith: id, + }); + } } } } //controlled expanding if (diffExpandedIds.size) { for (const id of diffExpandedIds) { - if (isBranchNode(data, id) || getTreeNode(data, id).isBranch) { - const parentId = getParent(data, id); - if (parentId) { - dispatch({ - type: treeTypes.expandMany, - ids: [id, parentId], - lastInteractedWith: id, - }); - } else { - dispatch({ - type: treeTypes.expand, - id: id, - lastInteractedWith: id, - }); + if (data.find((n) => n.id === id)) { + if (isBranchNode(data, id) || getTreeNode(data, id).isBranch) { + const parentId = getParent(data, id); + if (parentId) { + dispatch({ + type: treeTypes.expandMany, + ids: [id, parentId], + lastInteractedWith: id, + }); + } else { + dispatch({ + type: treeTypes.expand, + id: id, + lastInteractedWith: id, + }); + } } } } diff --git a/src/__tests__/ControlledExpandedNode.test.tsx b/src/__tests__/ControlledExpandedNode.test.tsx index 1f17125..a70f208 100644 --- a/src/__tests__/ControlledExpandedNode.test.tsx +++ b/src/__tests__/ControlledExpandedNode.test.tsx @@ -206,6 +206,37 @@ describe("Without node ids", () => { expect(nodesAfterExpandedAll[6]).toHaveAttribute("aria-expanded", "true"); expect(nodesAfterExpandedAll[11]).toHaveAttribute("aria-expanded", "true"); }); + test("Should rerender when the data and expanded nodes change", () => { + const expandedIds = [1, 7, 11]; + + const { queryAllByRole, rerender } = render( + + ); + + let nodes = queryAllByRole("treeitem"); + expect(nodes.length).toBe(16); + + // remove the fruits directory from both data and expandedIds + rerender( + node.id !== 1) + .map((node) => ({ + ...node, + children: node.children.filter((child) => child !== 1), + }))} + /> + ); + + nodes = queryAllByRole("treeitem"); + // six nodes were removed (everything in fruits) + expect(nodes.length).toBe(10); + + expect(nodes[0]).toHaveAttribute("aria-expanded", "true"); + expect(nodes[1]).not.toHaveAttribute("aria-expanded"); + expect(nodes[4]).toHaveAttribute("aria-expanded", "true"); + }); }); describe("With node ids", () => {