From a19d84845668ca6b155febc873cface0fbc3f120 Mon Sep 17 00:00:00 2001 From: hypercross Date: Mon, 11 May 2026 11:56:22 +0800 Subject: [PATCH] refactor: remove words prop from md-emfont Removes the `words` property from `EmfontProps` and simplifies the URL construction by removing the font subsetting logic. --- src/components/md-emfont.tsx | 74 +++++++++++++++++------------------- 1 file changed, 34 insertions(+), 40 deletions(-) diff --git a/src/components/md-emfont.tsx b/src/components/md-emfont.tsx index d7d7e12..649326b 100644 --- a/src/components/md-emfont.tsx +++ b/src/components/md-emfont.tsx @@ -3,57 +3,51 @@ import { createEffect, onCleanup } from "solid-js"; export interface EmfontProps { weight?: string; - words?: string; } -customElement( - "md-emfont", - { weight: "400", words: "" }, - (props, { element }) => { - noShadowDOM(); +customElement("md-emfont", { weight: "400" }, (props, { element }) => { + noShadowDOM(); - // 从 element 的 textContent 获取字体名称 - const font = element?.textContent?.trim() || ""; + // 从 element 的 textContent 获取字体名称 + const font = element?.textContent?.trim() || ""; - // 隐藏原始文本内容 - if (element) { - element.textContent = ""; - } + // 隐藏原始文本内容 + if (element) { + element.textContent = ""; + } - // 从父节点 article 获取当前 article 元素 - const articleEl = element?.closest("article") as HTMLElement; + // 从父节点 article 获取当前 article 元素 + const articleEl = element?.closest("article") as HTMLElement; - // 构建 emfont CSS URL - const weight = props.weight || "400"; - // 从 article 文本内容中提取唯一字符作为 words,用于字体子集化 - const words = - props.words || [...new Set(articleEl?.textContent || "")].join(""); - const linkHref = `https://font.emtech.cc/css/${font}?weight=${weight}&words=${encodeURIComponent(words)}`; + // 构建 emfont CSS URL + const weight = props.weight || "400"; + const linkHref = `https://font.emtech.cc/css/${font}?weight=${weight}`; - // 创建 元素并注入 - const linkEl = document.createElement("link"); + // 避免重复加载:检查是否已有相同字体的 + let linkEl = document.head.querySelector( + `link[data-md-emfont="${font}"]`, + ) as HTMLLinkElement | null; + + if (!linkEl) { + linkEl = document.createElement("link"); linkEl.rel = "stylesheet"; linkEl.href = linkHref; linkEl.dataset.mdEmfont = font; document.head.appendChild(linkEl); + } - createEffect(() => { - if (!articleEl) return; - articleEl.dataset.mdEmfont = font; - articleEl.style.fontFamily = font; - }); + createEffect(() => { + if (!articleEl) return; + articleEl.dataset.mdEmfont = font; + articleEl.style.fontFamily = font; + }); - onCleanup(() => { - // 清理 article 上的样式 - if (articleEl?.dataset?.mdEmfont === font) { - articleEl.style.fontFamily = ""; - } - // 移除注入的 - if (linkEl.parentNode) { - linkEl.parentNode.removeChild(linkEl); - } - }); + onCleanup(() => { + // 清理 article 上的样式 + if (articleEl?.dataset?.mdEmfont === font) { + delete articleEl.dataset.mdEmFont; + } + }); - return null; - }, -); + return null; +});