Skip to content

Commit

Permalink
feat: refactor getNodeSelectorText for improved readability and maint…
Browse files Browse the repository at this point in the history
…ainability
  • Loading branch information
lisonge committed Nov 21, 2024
1 parent 742bb3e commit 91f749f
Showing 1 changed file with 17 additions and 26 deletions.
43 changes: 17 additions & 26 deletions src/utils/node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ const getShortName = (fullName: string): string => {
return fullName.slice(lstIndex + 1);
};

const getConnectOperator = (operator: string, index: number): string => {
return operator + (index === 1 ? '' : index);
};

export const getNodeSelectorText = (
curNode: RawNode /* 当前节点 */,
isFirst: boolean = true /* 调用时须省略 */,
Expand All @@ -27,7 +31,7 @@ export const getNodeSelectorText = (
if (isFirst) {
return '[parent=null]';
} else {
return ' <' + lastIndex + ' [parent=null]';
return [getConnectOperator('<', lastIndex), '[parent=null]'].join(' ');
}
}
if (curNode.idQf) {
Expand All @@ -38,35 +42,22 @@ export const getNodeSelectorText = (
if (isFirst) {
return `[${key}="${value}"]`;
} else {
return ' <' + lastIndex + ` [${key}="${value}"]`;
return [getConnectOperator('<', lastIndex), `[${key}="${value}"]`].join(
' ',
);
}
}
// 处理一般的递归情况
if (isFirst) {
// 第一次调用,当前节点即为目标节点
// 返回完整的选择器,假设getSelector会返回后面应该拼接的文本
// (递归基在前面已经处理掉了,所以说这里一定会有后缀)
return (
'@' +
getShortName(curNode.attr.name) +
getNodeSelectorText(curNode.parent, false, curNode.attr.index + 1)
/* 当前节点的index转序号后传递给下一层函数调用
* 否则下一层函数不知道现在的节点是父节点的第几个儿子 */
);
return [
'@' + getShortName(curNode.attr.name),
getNodeSelectorText(curNode.parent, false, curNode.attr.index + 1),
].join(' ');
}
// 不是第一次调用,所以说函数的目标是拼接返回选择器的后缀部分
return (
' <' +
lastIndex /* 当前处理的是目标节点的(间接)父节点
* 所以说这里取子节点(也就是上一层函数的节点)的index */ +
' ' +
getShortName(curNode.attr.name) +
getNodeSelectorText(
curNode.parent,
false,
curNode.attr.index + 1,
) /* 递归构造后缀 */
);
return [
getConnectOperator('<', lastIndex),
getShortName(curNode.attr.name),
getNodeSelectorText(curNode.parent, false, curNode.attr.index + 1),
].join(' ');
};

export const listToTree = (nodes: RawNode[]) => {
Expand Down

0 comments on commit 91f749f

Please sign in to comment.