File size: 4,757 Bytes
96dd062 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 | ---
import { siteConfig } from "@/config";
const { font: fontConfig } = siteConfig;
// 获取选中的字体
const getSelectedFonts = () => {
if (!fontConfig.enable || !fontConfig.selected) return [];
const selectedIds = Array.isArray(fontConfig.selected)
? fontConfig.selected
: [fontConfig.selected];
return selectedIds
.map((id) => fontConfig.fonts[id])
.filter((font) => font?.src); // 过滤掉系统字体和不存在的字体
};
const selectedFonts = getSelectedFonts();
// 生成字体CSS类名
const generateFontClasses = () => {
if (!fontConfig.enable) return [];
const selectedIds = Array.isArray(fontConfig.selected)
? fontConfig.selected
: [fontConfig.selected];
return selectedIds.map((id) => `font-${id}-enabled`);
};
const fontClasses = generateFontClasses();
// 生成font-family回退样式
const generateFontFamilyStyle = () => {
if (!fontConfig.enable || !fontConfig.selected) return "";
const selectedIds = Array.isArray(fontConfig.selected)
? fontConfig.selected
: [fontConfig.selected];
const selectedFontFamilies = selectedIds
.map((id) => fontConfig.fonts[id])
.filter((font) => font)
.map((font) => `"${font.family}"`);
if (selectedFontFamilies.length === 0) return "";
const fallbacks = fontConfig.fallback || [];
const allFonts = [...selectedFontFamilies, ...fallbacks];
return `font-family: ${allFonts.join(", ")};`;
};
const fontFamilyStyle = generateFontFamilyStyle();
---
<!-- 字体样式表链接 -->{
selectedFonts.map((font) => {
// 判断是否为外部链接
const isExternalUrl =
font.src.startsWith("http://") ||
font.src.startsWith("https://") ||
font.src.startsWith("//");
if (isExternalUrl) {
// 外部字体链接 (如 Google Fonts, CDN等)
return <link rel="stylesheet" href={font.src} />;
} else {
// 本地字体文件
return (
<style
set:html={`
@font-face {
font-family: "${font.family}";
src: url("${font.src}") ${font.format ? `format("${font.format}")` : ""};
${font.weight ? `font-weight: ${font.weight};` : ""}
${font.style ? `font-style: ${font.style};` : ""}
${font.display ? `font-display: ${font.display};` : ""}
${font.unicodeRange ? `unicode-range: ${font.unicodeRange};` : ""}
}
`}
/>
);
}
})
}
<!-- 字体预加载链接 -->
{
fontConfig.enable &&
fontConfig.preload &&
selectedFonts
.filter((font) => !font.src.startsWith("http"))
.map((font) => (
<link
rel="preload"
href={font.src}
as="font"
type={`font/${font.format || "woff2"}`}
crossorigin
/>
))
}
<!-- 全局字体样式 -->
{
fontConfig.enable && fontFamilyStyle && (
<style
set:html={`
:root {
--font-family-custom: ${selectedFonts.map((font) => `"${font.family}"`).join(", ")};
--font-family-fallback: ${(fontConfig.fallback || []).join(", ")};
}
/* 应用自定义字体到body */
body {
${fontFamilyStyle}
}
/* 为每个选中的字体生成对应的CSS类 */
${selectedFonts
.map((font) => {
return `
.font-${font.id},
.font-${font.id} * {
font-family: "${font.family}", var(--font-family-fallback) !important;
}
`;
})
.join("\n")}
/* 为整体启用字体的body添加类名 */
${fontClasses.map((className) => `.${className}`).join(",\n")} {
/* 字体相关的全局样式可以在这里添加 */
}
`}
/>
)
}
<script>
// 字体加载优化和错误处理
if (document.fonts && typeof document.fonts.ready !== "undefined") {
document.fonts.ready
.then(() => {
console.log("All fonts have been loaded");
// 触发自定义事件,通知字体加载完成
document.dispatchEvent(new CustomEvent("fontsLoaded"));
})
.catch((error: Error) => {
console.warn("Font loading failed:", error);
});
}
// 字体加载性能监控
if (typeof PerformanceObserver !== "undefined") {
const observer = new PerformanceObserver((list) => {
list.getEntries().forEach((entry) => {
if (entry.entryType === "resource") {
// console.log(`Font resource loaded: ${entry.name} (${entry.duration.toFixed(2)}ms)`);
}
});
});
try {
observer.observe({ entryTypes: ["resource"] });
} catch (e) {
// 浏览器不支持时静默失败
}
}
</script>
|