From 017fbc1e1f9919441272df996e30e25bbaab71f7 Mon Sep 17 00:00:00 2001 From: zernonia Date: Thu, 14 Mar 2024 18:22:57 +0800 Subject: [PATCH] chore: improve crawling logic --- .../theme/components/CodeWrapper.ts | 34 +++++++++++-------- 1 file changed, 19 insertions(+), 15 deletions(-) diff --git a/apps/www/.vitepress/theme/components/CodeWrapper.ts b/apps/www/.vitepress/theme/components/CodeWrapper.ts index 906c8a2e..4b9a4b37 100644 --- a/apps/www/.vitepress/theme/components/CodeWrapper.ts +++ b/apps/www/.vitepress/theme/components/CodeWrapper.ts @@ -1,6 +1,17 @@ -import { type VNode, cloneVNode, defineComponent } from 'vue' +import { type VNode, type VNodeArrayChildren, cloneVNode, defineComponent } from 'vue' import { useConfigStore } from '@/stores/config' +function crawlSpan(children: VNodeArrayChildren, cb: (vnode: VNode) => void) { + children.forEach((childNode) => { + if (!Array.isArray(childNode) && typeof childNode === 'object') { + if (typeof childNode?.children === 'string') + cb(childNode) + else + crawlSpan(childNode?.children as VNodeArrayChildren ?? [], cb) + } + }) +} + export default defineComponent( (props, { slots }) => { const { codeConfig } = useConfigStore() @@ -16,21 +27,14 @@ export default defineComponent( const preVNode = [...clonedVNode?.children].find((node: VNode) => node.type === 'pre') as VNode // @ts-expect-error cloneVNode const codeVNode = preVNode.children?.at(0) as VNode + if (codeVNode) { - // @ts-expect-error cloneVNode - [...codeVNode.children] - .filter((node: VNode) => node.type === 'span') - .forEach((node: VNode) => { - if (node.children) { - // @ts-expect-error cloneVNode - [...node.children].forEach((childNode: VNode) => { - if (typeof childNode.children === 'string') { - childNode.children = childNode.children.replaceAll('@/components', codeConfig.value.componentsPath) - childNode.children = childNode.children.replaceAll('@/libs', codeConfig.value.utilsPath) - } - }) - } - }) + crawlSpan(codeVNode.children as VNodeArrayChildren, (vnode) => { + if (typeof vnode.children === 'string') { + vnode.children = vnode.children.replaceAll('@/components', codeConfig.value.componentsPath) + vnode.children = vnode.children.replaceAll('@/libs', codeConfig.value.utilsPath) + } + }) return clonedVNode }