Restructure code
This commit is contained in:
38
mixins/tree-flatten.js
Normal file
38
mixins/tree-flatten.js
Normal file
@@ -0,0 +1,38 @@
|
||||
export const TreeFlattenMixin = (superClass) => class TreeFlattenMixin extends superClass {
|
||||
_flattenNodes() {
|
||||
const results = [];
|
||||
const roots = Array.isArray(this.roots) ? this.roots : [];
|
||||
|
||||
const walk = (nodes, depth, path) => {
|
||||
if (!Array.isArray(nodes)) return;
|
||||
nodes.forEach((node, index) => {
|
||||
const slug = node?.slug ?? `${index}`;
|
||||
const nextPath = [...path, slug];
|
||||
const states = Array.isArray(node?.states) ? node.states : [];
|
||||
const hasChildren = this._isExpandableNode(node);
|
||||
const expanded = states.includes('expanded');
|
||||
|
||||
results.push({
|
||||
node,
|
||||
depth,
|
||||
path: nextPath,
|
||||
hasChildren,
|
||||
expanded,
|
||||
key: nextPath.join('/'),
|
||||
});
|
||||
|
||||
if (hasChildren && expanded && Array.isArray(node?.children) && node.children.length > 0) {
|
||||
walk(node.children, depth + 1, nextPath);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
walk(roots, 0, []);
|
||||
return results;
|
||||
}
|
||||
|
||||
_findFlatIndexByKey(key) {
|
||||
const items = Array.isArray(this._flatItems) ? this._flatItems : [];
|
||||
return items.findIndex((it) => it?.key === key);
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user