refactor: path handling

This commit is contained in:
2026-02-26 15:40:58 +08:00
parent 2ab6ed9687
commit e4bdd06182
4 changed files with 41 additions and 19 deletions
+3 -10
View File
@@ -2,6 +2,7 @@ import { customElement, noShadowDOM } from "solid-element";
import { createSignal, onCleanup } from "solid-js";
import { render } from "solid-js/web";
import { Article } from "./Article";
import { resolvePath } from "../utils/path";
customElement("md-link", {}, (props, { element }) => {
noShadowDOM();
@@ -12,7 +13,7 @@ customElement("md-link", {}, (props, { element }) => {
// 从 element 的 textContent 获取链接目标(支持 path#section 语法)
const rawLinkSrc = element?.textContent?.trim() || "";
// 解析 section(支持 path#section 语法)
const hashIndex = rawLinkSrc.indexOf('#');
const path = hashIndex >= 0 ? rawLinkSrc.slice(0, hashIndex) : rawLinkSrc;
@@ -27,15 +28,7 @@ customElement("md-link", {}, (props, { element }) => {
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, path);
// 查找包含此元素的 p 标签