function transformLinkNode()

in docs-sdk/markdown-renderer/src/index.tsx [151:185]


function transformLinkNode() {
  return (tree, vfile) => {
    visit(
      tree,
      ((node) => node.type === "element" && node.tagName === "a") as any,
      (node: any, ancestors: any[]) => {
        if (Array.isArray(node.children) && node.children.length === 1) {
          const linkTextNode = node.children[0];
          if (
            linkTextNode.type === "text" &&
            (linkTextNode.value.startsWith("$XView") ||
              linkTextNode.value.startsWith("$XDemo"))
          ) {
            const parent = ancestors[ancestors.length - 1];
            parent.children.splice(parent.children.indexOf(node), 1);
            // 先将找到的内联demo按顺序存到【顶层祖先元素】的数组中,
            // 最后一起将内联demo加到【顶层祖先元素】后面
            // (如果找到一个demo马上append,会造成当一个段落包含多个demo时,最终append的顺序逆转)
            ancestors[1]._toBeAppended = ancestors[1]._toBeAppended ?? [];
            ancestors[1]._toBeAppended.push(node);
          }
        }
        return visit.CONTINUE;
      }
    );

    for (let i = 0; i < tree.children.length; ++i) {
      const node = tree.children[i];
      if (Array.isArray(node._toBeAppended)) {
        tree.children.splice(i + 1, 0, ...node._toBeAppended);
      }
      delete node._toBeAppended;
    }
  };
}