@lobehub/ui
Version:
Lobe UI is an open-source UI component library for building AIGC web apps
73 lines (72 loc) • 2.36 kB
JavaScript
//#region src/base-ui/Tree/utils.ts
const hasChildren = (node) => !node.isLeaf && !!node.children && node.children.length > 0;
const flattenVisible = (data, expanded, depth = 0, parentKey = null, trail = [], out = []) => {
data.forEach((node, i) => {
const isLast = i === data.length - 1;
const expandable = hasChildren(node);
out.push({
depth,
hasChildren: expandable,
index: out.length,
isLast,
node,
parentKey,
trail
});
if (expandable && expanded.has(node.key)) flattenVisible(node.children, expanded, depth + 1, node.key, [...trail, !isLast], out);
});
return out;
};
const getAllKeys = (data, out = []) => {
for (const node of data) {
out.push(node.key);
if (node.children) getAllKeys(node.children, out);
}
return out;
};
const isCheckable = (node) => node.checkable !== false && !node.disabled;
const getSubtreeKeys = (node, out = []) => {
if (isCheckable(node)) out.push(node.key);
node.children?.forEach((child) => getSubtreeKeys(child, out));
return out;
};
const conductCheck = (data, checkedKeys) => {
const checked = new Set(checkedKeys);
const halfChecked = /* @__PURE__ */ new Set();
const down = (node, inherited) => {
const on = inherited || checked.has(node.key);
if (on && isCheckable(node)) checked.add(node.key);
node.children?.forEach((child) => down(child, on && isCheckable(node)));
};
data.forEach((node) => down(node, false));
const walk = (node) => {
const kids = (node.children ?? []).filter(isCheckable);
if (kids.length === 0) return checked.has(node.key);
const results = kids.map(walk);
if (results.every(Boolean)) {
checked.add(node.key);
return true;
}
checked.delete(node.key);
if (results.some(Boolean) || kids.some((kid) => halfChecked.has(kid.key))) halfChecked.add(node.key);
return false;
};
data.forEach(walk);
return {
checked,
halfChecked
};
};
const getAncestorKeys = (data, key, path = []) => {
for (const node of data) {
if (node.key === key) return [...path].reverse();
if (node.children) {
const found = getAncestorKeys(node.children, key, [...path, node.key]);
if (found.length > 0 || node.children.some((c) => c.key === key)) return found;
}
}
return [];
};
//#endregion
export { conductCheck, flattenVisible, getAllKeys, getAncestorKeys, getSubtreeKeys, hasChildren };
//# sourceMappingURL=utils.mjs.map