crootfast
Version:
大前端工程化命令行脚手架
94 lines (80 loc) • 2.75 kB
JavaScript
// 业务处理,数据拉平
export function flattenMenus(list = [], cb = () => { }) {
let result = [];
// 递归函数,用于处理每一项
function processItem(item) {
// 如果存在 menuInfoDtoList,递归处理里面的每一项
if (item.menuInfoDtoList && !!item.menuInfoDtoList.length) {
item.menuInfoDtoList.forEach((subItem) => processItem(subItem));
}
// 创建一个不包含 menuInfoDtoList 的新对象
const { ...newItem } = item;
Reflect.deleteProperty(newItem, "menuInfoDtoList");
result.push(cb && cb(newItem));
}
// 处理数组中的每一项
list.forEach((item) => processItem(item));
return result;
}
// 通过id查找对应item。
export function queryItem(id, key, data = []) {
return data.find((it) => it[key] === id);
}
// 暴露的组件对应interface信息
export function handlerComponentListFormatData(opts = {}) {
return Object.entries(opts)?.map(([key, item], idx) => {
return {
comIndex: idx,
component: item,
componentRegisterName: key,
// resourceCode: item?.ResourceCode ?? '',
...item?.Interface
};
});
}
// 遍历 DOM 树,查找所有具有指定属性的元素
export function findElementsWithAttribute(rootRef, attrName, attrValues = []) {
// 确保传入的 ref 和属性都是有效的
if (!rootRef.current || !attrName) return [];
// 获取要匹配的属性名和值
// const [attrName, attrValue] = Object.entries(attribute)[0];
const elements = [];
// 递归函数来遍历 DOM 树
function searchInDom(node) {
if (isElementNode(node)) {
// console.log(node, node.getAttribute(attrName), attrName, attrValue);
// 检查当前节点是否匹配属性
if (node?.getAttribute && attrValues.includes(node?.getAttribute(attrName))) {
elements.push(node);
}
// 递归检查子节点
node?.childNodes.forEach((child) => searchInDom(child));
}
}
// 从根节点开始搜索
searchInDom(rootRef.current);
return elements;
}
// 判断是否为DOM元素
export function isElementNode(node) {
// Node.ELEMENT_NODE (1): 一个元素节点,如 <p> 或 <div>。
// Node.TEXT_NODE(3): 文本节点,包含元素或属性中的文本内容。
// Node.COMMENT_NODE(8): 注释节点。
// Node.DOCUMENT_NODE(9): 一个文档节点,代表整个 HTML 或 XML 文档。
return node.nodeType === Node.ELEMENT_NODE;
}
// 刷新ast结构字段的值
export function hanlderItemToValue(data = [], layout) {
if (!layout) {
return;
}
function loop(data, pid) {
data?.forEach((it) => {
it.pid = pid;
if (it.children?.length) {
loop(it.children, it.id);
}
});
}
loop(data, layout.id);
}