refactor: remove words prop from md-emfont

Removes the `words` property from `EmfontProps` and simplifies the
URL construction by removing the font subsetting logic.
This commit is contained in:
hypercross 2026-05-11 11:56:22 +08:00
parent 4038d67ea0
commit a19d848456
1 changed files with 34 additions and 40 deletions

View File

@ -3,57 +3,51 @@ import { createEffect, onCleanup } from "solid-js";
export interface EmfontProps { export interface EmfontProps {
weight?: string; weight?: string;
words?: string;
} }
customElement( customElement("md-emfont", { weight: "400" }, (props, { element }) => {
"md-emfont", noShadowDOM();
{ weight: "400", words: "" },
(props, { element }) => {
noShadowDOM();
// 从 element 的 textContent 获取字体名称 // 从 element 的 textContent 获取字体名称
const font = element?.textContent?.trim() || ""; const font = element?.textContent?.trim() || "";
// 隐藏原始文本内容 // 隐藏原始文本内容
if (element) { if (element) {
element.textContent = ""; element.textContent = "";
} }
// 从父节点 article 获取当前 article 元素 // 从父节点 article 获取当前 article 元素
const articleEl = element?.closest("article") as HTMLElement; const articleEl = element?.closest("article") as HTMLElement;
// 构建 emfont CSS URL // 构建 emfont CSS URL
const weight = props.weight || "400"; const weight = props.weight || "400";
// 从 article 文本内容中提取唯一字符作为 words用于字体子集化 const linkHref = `https://font.emtech.cc/css/${font}?weight=${weight}`;
const words =
props.words || [...new Set(articleEl?.textContent || "")].join("");
const linkHref = `https://font.emtech.cc/css/${font}?weight=${weight}&words=${encodeURIComponent(words)}`;
// 创建 <link> 元素并注入 <head> // 避免重复加载:检查是否已有相同字体的 <link>
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.rel = "stylesheet";
linkEl.href = linkHref; linkEl.href = linkHref;
linkEl.dataset.mdEmfont = font; linkEl.dataset.mdEmfont = font;
document.head.appendChild(linkEl); document.head.appendChild(linkEl);
}
createEffect(() => { createEffect(() => {
if (!articleEl) return; if (!articleEl) return;
articleEl.dataset.mdEmfont = font; articleEl.dataset.mdEmfont = font;
articleEl.style.fontFamily = font; articleEl.style.fontFamily = font;
}); });
onCleanup(() => { onCleanup(() => {
// 清理 article 上的样式 // 清理 article 上的样式
if (articleEl?.dataset?.mdEmfont === font) { if (articleEl?.dataset?.mdEmfont === font) {
articleEl.style.fontFamily = ""; delete articleEl.dataset.mdEmFont;
} }
// 移除注入的 <link> });
if (linkEl.parentNode) {
linkEl.parentNode.removeChild(linkEl);
}
});
return null; return null;
}, });
);