sard-uniapp
Version:
sard-uniapp 是一套基于 Uniapp + Vue3 框架开发的兼容多端的 UI 组件库
95 lines (94 loc) • 2.63 kB
JavaScript
export function walkDescendant(node, callback) {
if (!callback(node) && node.children) {
node.children.forEach((node) => {
walkDescendant(node, callback);
});
}
}
export function walkAncestor(node, callback) {
if (node) {
callback(node);
walkAncestor(node.parent, callback);
}
}
export function walkNodes(nodes, callback) {
nodes.forEach((node) => {
callback(node);
if (node.children) {
walkNodes(node.children, callback);
}
});
}
export function getNodeLevel(node) {
let level = 0;
while (node.parent) {
level++;
node = node.parent;
}
return level;
}
export function setCheckedRecursively(node, checked, strictly) {
if (strictly) {
node.checked = checked;
}
else {
walkDescendant(node, (node) => {
node.checked = checked;
node.indeterminate = false;
});
updateAncestorsChecked(node.parent);
}
}
export function updateAncestorsChecked(parentNode, strictly) {
if (!strictly) {
walkAncestor(parentNode, (node) => {
const children = node.children || [];
const numChecked = children.filter((node) => node.checked).length;
node.checked = numChecked > 0 && numChecked === children.length;
node.indeterminate =
!node.checked &&
(numChecked > 0 || children.some((node) => node.indeterminate));
});
}
}
export function initializeCheckNodes(nodes, treeMap, keys, strictly) {
if (strictly) {
const mapKeys = keys.reduce((map, key) => {
map[key] = true;
return map;
}, {});
walkNodes(nodes, (node) => {
node.checked = mapKeys[node.key] ? true : false;
});
}
else {
walkNodes(nodes, (node) => {
node.checked = false;
node.indeterminate = false;
});
keys.forEach((key) => {
const node = treeMap[key];
if (node && !node.checked) {
setCheckedRecursively(node, true, strictly);
}
});
}
}
export function getTreeCheckedKeys(nodes) {
const checkedKeys = [];
walkNodes(nodes, (node) => {
if (node.checked) {
checkedKeys.push(node.key);
}
});
return checkedKeys;
}
export function getTreeHalfCheckedKeys(nodes) {
const halfCheckedKeys = [];
walkNodes(nodes, (node) => {
if (node.indeterminate) {
halfCheckedKeys.push(node.key);
}
});
return halfCheckedKeys;
}