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
This commit is contained in:
@@ -1,32 +1,34 @@
|
||||
import { flatten } from "lodash";
|
||||
import { NavigationNode } from "@shared/types";
|
||||
|
||||
export const flattenTree = (root: any) => {
|
||||
const flattened: any[] = [];
|
||||
export const flattenTree = (root: NavigationNode) => {
|
||||
const flattened: NavigationNode[] = [];
|
||||
if (!root) {
|
||||
return flattened;
|
||||
}
|
||||
|
||||
flattened.push(root);
|
||||
|
||||
root.children.forEach((child: any) => {
|
||||
flattened.push(flattenTree(child));
|
||||
root.children.forEach((child) => {
|
||||
flattened.push(...flattenTree(child));
|
||||
});
|
||||
|
||||
return flatten(flattened);
|
||||
return flattened;
|
||||
};
|
||||
|
||||
export const ancestors = (node: any) => {
|
||||
const ancestors: any[] = [];
|
||||
export const ancestors = (node: NavigationNode) => {
|
||||
const ancestors: NavigationNode[] = [];
|
||||
while (node.parent !== null) {
|
||||
ancestors.unshift(node);
|
||||
node = node.parent;
|
||||
node = node.parent as NavigationNode;
|
||||
}
|
||||
return ancestors;
|
||||
};
|
||||
|
||||
export const descendants = (node: any, depth = 0) => {
|
||||
export const descendants = (node: NavigationNode, depth = 0) => {
|
||||
const allDescendants = flattenTree(node).slice(1);
|
||||
return depth === 0
|
||||
? allDescendants
|
||||
: allDescendants.filter((d) => d.depth <= node.depth + depth);
|
||||
: allDescendants.filter(
|
||||
(d) => (d.depth as number) <= (node.depth as number) + depth
|
||||
);
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user