Files
outline/app/utils/tree.ts
Apoorv Mishra ad902af52c Move tree implementation out of collections store (#4763)
* refactor: attaching emoji in tree node is unnecessary

* refactor: pass depth and hasChildren as separate props

* refactor: move tree impl into a separate hook

* refactor: separate out as DocumentExplorer for reuse

* fix: separate search and node

* fix: review comments

* fix: tsc
2023-01-27 11:33:51 +05:30

35 lines
822 B
TypeScript

import { NavigationNode } from "@shared/types";
export const flattenTree = (root: NavigationNode) => {
const flattened: NavigationNode[] = [];
if (!root) {
return flattened;
}
flattened.push(root);
root.children.forEach((child) => {
flattened.push(...flattenTree(child));
});
return flattened;
};
export const ancestors = (node: NavigationNode) => {
const ancestors: NavigationNode[] = [];
while (node.parent !== null) {
ancestors.unshift(node);
node = node.parent as NavigationNode;
}
return ancestors;
};
export const descendants = (node: NavigationNode, depth = 0) => {
const allDescendants = flattenTree(node).slice(1);
return depth === 0
? allDescendants
: allDescendants.filter(
(d) => (d.depth as number) <= (node.depth as number) + depth
);
};