From dfb763c1d9662dbfad7afbea025b04b86e3225dd Mon Sep 17 00:00:00 2001 From: hypercross Date: Thu, 26 Feb 2026 09:37:28 +0800 Subject: [PATCH] fix: path relative --- src/components/md-link.tsx | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/src/components/md-link.tsx b/src/components/md-link.tsx index 316bdbb..c79a615 100644 --- a/src/components/md-link.tsx +++ b/src/components/md-link.tsx @@ -11,7 +11,22 @@ customElement("md-link", {}, (props, { element }) => { let disposeArticle: (() => void) | null = null; // 从 element 的 textContent 获取链接目标 - const linkSrc = element?.textContent?.trim() || ""; + const rawLinkSrc = element?.textContent?.trim() || ""; + + // 从父节点 article 的 data-src 获取当前 markdown 文件完整路径 + const articleEl = element?.closest('article[data-src]'); + const articlePath = articleEl?.getAttribute('data-src') || ''; + + // 解析相对路径(相对于 markdown 文件所在目录) + const resolvePath = (base: string, relative: string): string => { + if (relative.startsWith('/')) { + return relative; + } + const baseDir = base.substring(0, base.lastIndexOf('/') + 1); + return baseDir + relative; + }; + + const linkSrc = resolvePath(articlePath, rawLinkSrc); // 查找包含此元素的 p 标签 const parentP = element?.closest("p"); @@ -39,7 +54,7 @@ customElement("md-link", {}, (props, { element }) => { // 渲染 Article 组件 disposeArticle = render(() => ( -
console.log("Article loaded:", linkSrc)} onError={(err) => console.error("Article error:", err)} @@ -66,7 +81,7 @@ customElement("md-link", {}, (props, { element }) => { }} class="text-blue-600 hover:text-blue-800 hover:underline" > - {linkSrc} + {rawLinkSrc} ); });