Initial Commit

This commit is contained in:
2026-07-15 05:49:11 +08:00
parent b978f92d03
commit 0505d2586c
392 changed files with 64138 additions and 7379 deletions
+269
View File
@@ -0,0 +1,269 @@
/**
* 图标预处理脚本
* 在构建时自动扫描 Svelte 组件中使用的图标,并生成内联 SVG 数据
*
* 使用方法:node scripts/generate-icons.js
*/
import { readFileSync, writeFileSync, readdirSync, statSync } from "fs";
import { join, dirname } from "path";
import { fileURLToPath } from "url";
import { getIconData, iconToSVG, iconToHTML, replaceIDs } from "@iconify/utils";
const __dirname = dirname(fileURLToPath(import.meta.url));
const ROOT_DIR = join(__dirname, "..");
const SRC_DIR = join(ROOT_DIR, "src");
const OUTPUT_FILE = join(SRC_DIR, "constants", "icons.ts");
// 支持的图标集及其包名
const ICON_SETS = {
"material-symbols": "@iconify-json/material-symbols",
"fa7-solid": "@iconify-json/fa7-solid",
"fa7-brands": "@iconify-json/fa7-brands",
"fa7-regular": "@iconify-json/fa7-regular",
mdi: "@iconify-json/mdi",
"simple-icons": "@iconify-json/simple-icons",
mingcute: "@iconify-json/mingcute",
"svg-spinners": "@iconify-json/svg-spinners",
};
// 图标集数据缓存
const iconSetCache = new Map();
/**
* 递归获取目录下所有文件
*/
function getAllFiles(dir, extensions = [".svelte"]) {
const files = [];
function walk(currentDir) {
const items = readdirSync(currentDir);
for (const item of items) {
const fullPath = join(currentDir, item);
const stat = statSync(fullPath);
if (stat.isDirectory()) {
// 跳过 node_modules 和隐藏目录
if (!item.startsWith(".") && item !== "node_modules") {
walk(fullPath);
}
} else if (extensions.some((ext) => item.endsWith(ext))) {
files.push(fullPath);
}
}
}
walk(dir);
return files;
}
/**
* 从文件内容中提取图标名称
*/
function extractIconNames(content) {
const icons = new Set();
// 匹配各种图标使用模式
const patterns = [
// icon="xxx:yyy" 或 icon='xxx:yyy'
/icon=["']([a-z0-9-]+:[a-z0-9-]+)["']/gi,
// icon={`xxx:yyy`}
/icon=\{[`"']([a-z0-9-]+:[a-z0-9-]+)[`"']\}/gi,
// getIconSvg("xxx:yyy") 或 getIconSvg('xxx:yyy')
/getIconSvg\(["']([a-z0-9-]+:[a-z0-9-]+)["']\)/gi,
// hasIcon("xxx:yyy")
/hasIcon\(["']([a-z0-9-]+:[a-z0-9-]+)["']\)/gi,
];
for (const pattern of patterns) {
let match;
while ((match = pattern.exec(content)) !== null) {
icons.add(match[1]);
}
}
return icons;
}
/**
* 加载图标集数据
*/
async function loadIconSet(prefix) {
if (iconSetCache.has(prefix)) {
return iconSetCache.get(prefix);
}
const packageName = ICON_SETS[prefix];
if (!packageName) {
console.warn(`⚠️ 未知图标集: ${prefix}`);
return null;
}
try {
// 动态导入图标集 JSON
const iconSetPath = join(ROOT_DIR, "node_modules", packageName, "icons.json");
const data = JSON.parse(readFileSync(iconSetPath, "utf-8"));
iconSetCache.set(prefix, data);
return data;
} catch (error) {
console.warn(`⚠️ 无法加载图标集 ${packageName}: ${error.message}`);
return null;
}
}
/**
* 获取单个图标的 SVG
*/
async function getIconSvg(iconName) {
const [prefix, name] = iconName.split(":");
if (!prefix || !name) {
console.warn(`⚠️ 无效的图标名称: ${iconName}`);
return null;
}
const iconSet = await loadIconSet(prefix);
if (!iconSet) {
return null;
}
const iconData = getIconData(iconSet, name);
if (!iconData) {
console.warn(`⚠️ 图标未找到: ${iconName}`);
return null;
}
// 转换为 SVG
const renderData = iconToSVG(iconData, {
height: "1em",
width: "1em",
});
let svg = iconToHTML(replaceIDs(renderData.body), renderData.attributes);
// 确保支持 currentColor
if (!svg.includes("currentColor")) {
svg = svg.replace("<svg", '<svg fill="currentColor"');
}
return svg;
}
/**
* 生成 icons.ts 文件
*/
function generateIconsFile(iconsMap) {
const iconEntries = Array.from(iconsMap.entries())
.sort(([a], [b]) => a.localeCompare(b))
.map(([name, svg]) => `\t"${name}":\n\t\t'${svg.replace(/'/g, "\\'")}'`)
.join(",\n");
const content = `/**
* 自动生成的图标数据文件
* 由 scripts/generate-icons.js 在构建时生成
* 请勿手动编辑此文件
*/
const iconSvgData: Record<string, string> = {
${iconEntries}
};
/**
* 根据 iconify 格式的图标名获取内联 SVG HTML
* @param iconName 图标名称,如 "material-symbols:search"
* @returns SVG HTML 字符串
*/
export function getIconSvg(iconName: string): string {
return iconSvgData[iconName] || "";
}
/**
* 检查图标是否可用
*/
export function hasIcon(iconName: string): boolean {
return iconName in iconSvgData;
}
/**
* 获取所有可用图标名称
*/
export function getAvailableIcons(): string[] {
return Object.keys(iconSvgData);
}
export default iconSvgData;
`;
return content;
}
/**
* 主函数
*/
async function main() {
console.log("🔍 扫描源文件中的图标使用...\n");
// 获取所有源文件
const files = getAllFiles(SRC_DIR);
console.log(`📁 找到 ${files.length} 个源文件\n`);
// 收集所有使用的图标
const allIcons = new Set();
for (const file of files) {
// 跳过 icons.ts 文件本身
if (file.endsWith("icons.ts")) continue;
const content = readFileSync(file, "utf-8");
const icons = extractIconNames(content);
for (const icon of icons) {
allIcons.add(icon);
}
}
console.log(`🎨 发现 ${allIcons.size} 个不同的图标:\n`);
// 按图标集分组显示
const iconsBySet = {};
for (const icon of allIcons) {
const [prefix] = icon.split(":");
if (!iconsBySet[prefix]) {
iconsBySet[prefix] = [];
}
iconsBySet[prefix].push(icon);
}
for (const [prefix, icons] of Object.entries(iconsBySet)) {
console.log(` ${prefix}: ${icons.length} 个图标`);
}
console.log("");
// 获取所有图标的 SVG
const iconsMap = new Map();
let successCount = 0;
let failCount = 0;
for (const iconName of allIcons) {
const svg = await getIconSvg(iconName);
if (svg) {
iconsMap.set(iconName, svg);
successCount++;
} else {
failCount++;
}
}
console.log(`✅ 成功加载 ${successCount} 个图标`);
if (failCount > 0) {
console.log(`❌ 失败 ${failCount} 个图标`);
}
// 生成输出文件
const output = generateIconsFile(iconsMap);
writeFileSync(OUTPUT_FILE, output, "utf-8");
console.log(`\n📝 已生成: ${OUTPUT_FILE}`);
console.log(`📦 文件大小: ${(Buffer.byteLength(output, "utf-8") / 1024).toFixed(2)} KB\n`);
}
main().catch(console.error);
+140
View File
@@ -0,0 +1,140 @@
// LQIP 方案来源: https://blog.cosine.ren/post/astro-lqip-implementation
import sharp from "sharp";
import { glob } from "glob";
import fs from "fs/promises";
import path from "path";
const SRC_DIR = "src";
const PUBLIC_DIR = "public";
const OUTPUT_FILE = "src/constants/lqips.json";
// 需要忽略的目录(相对于项目根目录)
const IGNORE_DIRS = [
"public/favicon/**",
"public/pio/**",
"public/assets/images/effects/**",
"public/assets/music/**",
];
interface RgbColor {
r: number;
g: number;
b: number;
}
type LqipMap = Record<string, string>;
function rgbToHex(color: RgbColor): string {
const hex = (n: number) => n.toString(16).padStart(2, "0");
return `#${hex(color.r)}${hex(color.g)}${hex(color.b)}`;
}
async function processImage(imagePath: string): Promise<string | null> {
try {
const { data, info } = await sharp(imagePath)
.resize(2, 2, { fit: "fill" })
.raw()
.toBuffer({ resolveWithObject: true });
const channels = info.channels;
const colors: RgbColor[] = [];
for (let i = 0; i < 4; i++) {
const offset = i * channels;
colors.push({
r: data[offset],
g: data[offset + 1],
b: data[offset + 2],
});
}
// 使用 corners[0], [1], [3] 生成 135deg 斜向渐变
const compact = `${rgbToHex(colors[0]).slice(1)}${rgbToHex(colors[1]).slice(1)}${rgbToHex(colors[3]).slice(1)}`;
return compact;
} catch (error) {
console.error(`Error processing ${imagePath}:`, error);
return null;
}
}
function filePathToKey(filePath: string): string {
if (filePath.startsWith(PUBLIC_DIR)) {
return `public:${path.relative(PUBLIC_DIR, filePath).replace(/\\/g, "/")}`;
}
return `src:${path.relative(SRC_DIR, filePath).replace(/\\/g, "/")}`;
}
async function main() {
// 读取已有的 lqips.json
let existingLqips: LqipMap = {};
try {
const content = await fs.readFile(OUTPUT_FILE, "utf-8");
existingLqips = JSON.parse(content);
console.log(
`Loaded ${Object.keys(existingLqips).length} existing entries from ${OUTPUT_FILE}`,
);
} catch {
console.log(`No existing ${OUTPUT_FILE} found, will create new.`);
}
const files = await glob("{src,public}/**/*.{png,jpg,jpeg,webp,avif}", {
ignore: IGNORE_DIRS,
});
if (files.length === 0) {
console.log("No image files found.");
return;
}
// 移除已不存在的图片数据
const currentKeys = new Set(files.map((file) => filePathToKey(file)));
const removedKeys = Object.keys(existingLqips).filter(
(key) => !currentKeys.has(key),
);
for (const key of removedKeys) {
delete existingLqips[key];
}
if (removedKeys.length > 0) {
console.log(
`Removed ${removedKeys.length} stale entries: ${removedKeys.join(", ")}`,
);
}
// 过滤掉已有数据的图片
const newFiles = files.filter((file) => {
const key = filePathToKey(file);
return !(key in existingLqips);
});
console.log(
`Found ${files.length} images, ${newFiles.length} new to process.`,
);
const lqips: LqipMap = { ...existingLqips };
let processed = 0;
if (newFiles.length > 0) {
for (const file of newFiles) {
const filePath = path.resolve(file);
process.stdout.write(
`\rProcessing ${processed + 1}/${newFiles.length}...`,
);
const compact = await processImage(filePath);
if (compact !== null) {
const key = filePathToKey(file);
lqips[key] = compact;
processed++;
}
}
}
const dir = path.dirname(OUTPUT_FILE);
await fs.mkdir(dir, { recursive: true });
await fs.writeFile(OUTPUT_FILE, JSON.stringify(lqips, null, 2), "utf-8");
console.log(
`\nDone! Processed ${processed}/${newFiles.length} new images. Total: ${Object.keys(lqips).length}. Output: ${OUTPUT_FILE}`,
);
}
main();
+59
View File
@@ -0,0 +1,59 @@
/* This is a script to create a new post markdown file with front-matter */
import fs from "fs"
import path from "path"
function getDate() {
const today = new Date()
const year = today.getFullYear()
const month = String(today.getMonth() + 1).padStart(2, "0")
const day = String(today.getDate()).padStart(2, "0")
return `${year}-${month}-${day}`
}
const args = process.argv.slice(2)
if (args.length === 0) {
console.error(`Error: No filename argument provided
Usage: npm run new-post -- <filename>`)
process.exit(1) // Terminate the script and return error code 1
}
let fileName = args[0]
// Add .md extension if not present
const fileExtensionRegex = /\.(md|mdx)$/i
if (!fileExtensionRegex.test(fileName)) {
fileName += ".md"
}
const targetDir = "./src/content/posts/"
const fullPath = path.join(targetDir, fileName)
if (fs.existsSync(fullPath)) {
console.error(`Error: File ${fullPath} already exists `)
process.exit(1)
}
// recursive mode creates multi-level directories
const dirPath = path.dirname(fullPath)
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath, { recursive: true })
}
const content = `---
title: ${args[0]}
published: ${getDate()}
description: ''
image: ''
tags: []
category: ''
draft: false
lang: ''
---
`
fs.writeFileSync(path.join(targetDir, fileName), content)
console.log(`Post ${fullPath} created`)
+71
View File
@@ -0,0 +1,71 @@
/**
* 隔离引用了不存在图片的文章
* 把这些文章移到 src/content/posts/_quarantine/
* Astro 不会构建 _quarantine 里的文章
*/
import fs from 'node:fs';
import path from 'node:path';
import matter from 'gray-matter';
const POSTS_DIR = 'src/content/posts';
const QUARANTINE_DIR = 'src/content/_quarantine';
if (!fs.existsSync(QUARANTINE_DIR)) {
fs.mkdirSync(QUARANTINE_DIR, { recursive: true });
}
function walk(dir) {
return fs.readdirSync(dir).flatMap(f => {
const p = path.join(dir, f);
return fs.statSync(p).isDirectory()
? walk(p)
: f === 'index.md' ? [p] : [];
});
}
function hasMissingImage(file) {
const raw = fs.readFileSync(file, 'utf8');
const { data, content } = matter(raw);
const images = new Set();
// frontmatter 里的 image
if (typeof data.image === 'string') {
images.add(data.image);
}
// markdown 里的 ![alt](path)
const mdImages = [...content.matchAll(/!\[.*?\]\((.+?)\)/g)]
.map(m => m[1])
.filter(p => !p.startsWith('http'));
mdImages.forEach(p => images.add(p));
return [...images].some(img => {
const abs = img.startsWith('/')
? path.join('public', img)
: path.resolve(path.dirname(file), img);
return !fs.existsSync(abs);
});
}
function main() {
const files = walk(POSTS_DIR);
let moved = 0;
for (const file of files) {
if (hasMissingImage(file)) {
const target = file.replace(POSTS_DIR, QUARANTINE_DIR);
fs.mkdirSync(path.dirname(target), { recursive: true });
fs.renameSync(file, target);
console.log(`🚫 Quarantined: ${file}`);
moved++;
}
}
console.log(`\n✅ Done. Quarantined ${moved} broken posts.`);
}
main();
+329
View File
@@ -0,0 +1,329 @@
// 字体子集化构建后脚本
// 在 astro build 之后运行,扫描 dist/ 中所有 HTML 页面,收集实际使用的字符,
// 为标记了 subset: true 的本地字体生成轻量 woff2 子集文件。
import crypto from "node:crypto";
import fs from "node:fs/promises";
import path from "node:path";
import { glob } from "glob";
import subsetFont from "subset-font";
import { fontConfig, fontsList } from "../src/config";
import { collectUsedFontCssVars, toPublicPath } from "../src/utils/fontHelper";
// ─── 配置 ───────────────────────────────────────────────
const DIST_DIR = "dist";
const OUTPUT_DIR = "dist/_astro/fonts";
// ─── 字体配置解析 ────────────────────────────────────────
type LocalSubsetFont = {
id: string;
family: string;
src: string;
weight?: string | number;
style?: string;
display?: string;
subsetExtraChars?: string;
};
/**
* 从 fontConfig.subsetFonts 获取需要子集化的本地字体,
* 交叉引用 fonts 数组获取字体文件路径。
* 仅处理实际被使用的字体(在 selected、bannerTitleFont 等区域字段中引用的)。
*/
function getLocalSubsetFonts(): LocalSubsetFont[] {
if (!fontConfig.enable || !fontConfig.subsetFonts) return [];
const subsetEntries = Object.entries(fontConfig.subsetFonts);
if (subsetEntries.length === 0) return [];
// 构建实际使用的字体 CSS 变量集合(与 astro.config.mjs 共享同一逻辑)
const used = collectUsedFontCssVars(fontConfig);
// 建立 cssVariable → fontsList 条目的映射
const fontByCssVar = new Map<string, typeof fontsList[number]>();
for (const f of fontsList) {
if (f.cssVariable) fontByCssVar.set(f.cssVariable, f);
}
const result: LocalSubsetFont[] = [];
for (const [cssVar, opts] of subsetEntries) {
// 跳过未被使用的字体,避免生成无用的子集文件
if (!used.has(cssVar)) {
console.log(` ⏭ Skipping '${cssVar}' — not referenced in selected or any font region.`);
continue;
}
const f = fontByCssVar.get(cssVar);
if (!f?.options?.variants) continue;
for (const v of f.options.variants) {
if (!v.src?.length) continue;
const rawSrc = v.src[0];
// 将本地路径(如 "./public/assets/fonts/MyFont.woff2")转换为访问路径
const publicPath = toPublicPath(rawSrc);
if (publicPath === null) {
console.warn(
` ⚠ Skipping variant with unexpected src path: "${rawSrc}".\n` +
` Expected a path under public/ (e.g. "./public/assets/fonts/MyFont.woff2") or an absolute path (e.g. "/assets/fonts/MyFont.woff2").`
);
continue;
}
result.push({
id: `${f.name}-${v.weight || "default"}`.toLowerCase().replace(/\s+/g, "-"),
family: f.name,
src: publicPath,
weight: v.weight,
style: v.style,
subsetExtraChars: opts.extraChars,
});
}
}
return result;
}
// ─── 字符收集 ────────────────────────────────────────────
/**
* 从 HTML 字符串中提取纯文本内容(比 JSDOM 轻量得多)
*/
function extractTextFromHtml(html: string): string {
// 移除 script 和 style 标签及其内容
let text = html.replace(/<(script|style)[^>]*>[\s\S]*?<\/\1>/gi, " ");
// 移除所有 HTML 标签
text = text.replace(/<[^>]+>/g, " ");
// 解码常见 HTML 实体
text = text
.replace(/&amp;/g, "&")
.replace(/&lt;/g, "<")
.replace(/&gt;/g, ">")
.replace(/&quot;/g, '"')
.replace(/&#39;/g, "'")
.replace(/&nbsp;/g, " ");
// 提取 alt、title、aria-label、placeholder 属性值
const attrMatches = html.matchAll(/(?:alt|title|aria-label|placeholder)=["']([^"']+)["']/gi);
for (const match of attrMatches) {
text += match[1];
}
return text;
}
/**
* 扫描 dist/ 中所有 HTML 文件,提取页面中实际使用的所有字符
*/
async function collectChars(): Promise<string> {
const htmlFiles = await glob(`${DIST_DIR}/**/*.html`);
const charSet = new Set<string>();
for (const file of htmlFiles) {
const html = await fs.readFile(file, "utf-8");
const text = extractTextFromHtml(html);
for (const c of text) charSet.add(c);
}
return [...charSet].join("");
}
// ─── 子集生成 ────────────────────────────────────────────
function contentHash(buffer: Buffer): string {
return crypto
.createHash("sha256")
.update(buffer)
.digest("hex")
.slice(0, 16);
}
/**
* 将本地 src 路径解析为 public/ 下的绝对文件路径
*/
function resolveFontPath(src: string): string {
const relativePath = src.startsWith("/") ? src.slice(1) : src;
return path.resolve("public", relativePath);
}
/**
* 检测字体文件的实际格式
*/
function detectFontFormat(
filePath: string,
): "woff2" | "woff" | "truetype" | "opentype" {
const ext = path.extname(filePath).toLowerCase();
switch (ext) {
case ".woff2":
return "woff2";
case ".woff":
return "woff";
case ".otf":
return "opentype";
case ".ttf":
default:
return "truetype";
}
}
// ─── 主流程 ──────────────────────────────────────────────
interface SubsetResult {
id: string;
family: string;
weight?: string | number;
style?: string;
display?: string;
hash: string;
format: string;
originalSrc: string;
}
async function main() {
console.log("🔤 Font subsetting started...");
// 1. 从配置中获取需要子集化的本地字体
const localSubsetFonts = getLocalSubsetFonts();
if (localSubsetFonts.length === 0) {
console.log(" No local fonts with subset: true found. Skipping.");
return;
}
console.log(
` Found ${localSubsetFonts.length} font(s) to subset: ${localSubsetFonts.map((f) => f.id).join(", ")}`,
);
// 2. 收集页面字符
console.log("🔍 Collecting characters from dist/...");
const pageChars = await collectChars();
console.log(` Collected ${pageChars.length} unique characters.`);
if (pageChars.length === 0) {
console.warn("⚠ No characters found in dist/. Skipping subsetting.");
return;
}
// 3. 确保输出目录存在
await fs.mkdir(OUTPUT_DIR, { recursive: true });
// 4. 为每个字体生成子集
const results: SubsetResult[] = [];
for (const font of localSubsetFonts) {
const fontPath = resolveFontPath(font.src);
// 检查字体文件是否存在
try {
await fs.access(fontPath);
} catch {
console.error(
`❌ Font file not found: ${fontPath} (src: ${font.src})`,
);
continue;
}
// 合并页面字符和额外字符
let chars = pageChars;
if (font.subsetExtraChars) {
const extraSet = new Set<string>([
...pageChars,
...font.subsetExtraChars,
]);
chars = [...extraSet].join("");
}
console.log(
`⏳ Generating subset for '${font.id}' (${font.family})...`,
);
const fontBuffer = await fs.readFile(fontPath);
const originalFormat = detectFontFormat(fontPath);
try {
const subsetBuffer = await subsetFont(fontBuffer, chars, {
targetFormat: "woff2",
preserveNameTable: true,
});
const hash = contentHash(subsetBuffer);
const outFile = path.join(OUTPUT_DIR, `${hash}.woff2`);
await fs.writeFile(outFile, subsetBuffer);
const sizeKB = (subsetBuffer.length / 1024).toFixed(1);
const originalSizeKB = (fontBuffer.length / 1024).toFixed(1);
const ratio = (
((fontBuffer.length - subsetBuffer.length) / fontBuffer.length) *
100
).toFixed(1);
console.log(
` ✔ ${hash}.woff2 (${sizeKB} KB, original: ${originalSizeKB} KB, saved ${ratio}%)`,
);
results.push({
id: font.id,
family: font.family,
weight: font.weight,
style: font.style,
display: font.display,
hash,
format: originalFormat,
originalSrc: font.src,
});
} catch (err) {
console.error(` ❌ Failed to subset '${font.id}':`, err);
}
}
if (results.length === 0) {
console.warn("⚠ No subsets were generated.");
return;
}
// 5. 替换 dist/ 中 CSS 和 HTML 的字体引用
// @font-face 可能在独立 CSS 文件中,也可能在 HTML 内联 <style> 中
console.log("🔄 Replacing font URLs in dist/ CSS and HTML files...");
const filesToReplace = await glob(`${DIST_DIR}/**/*.{css,html}`);
for (const file of filesToReplace) {
let content = await fs.readFile(file, "utf-8");
let replaced = false;
for (const result of results) {
const placeholder = `__SUBSET_FONT_${result.id}__`;
if (content.includes(placeholder)) {
const subsetUrl = `/_astro/fonts/${result.hash}.woff2`;
content = content.replaceAll(placeholder, subsetUrl);
replaced = true;
}
}
if (replaced) {
await fs.writeFile(file, content);
console.log(` ✔ Updated: ${file}`);
}
}
// 6. 清理 dist/ 中的原始字体文件
console.log("🗑 Cleaning up original font files from dist/...");
for (const result of results) {
const originalInDist = path.join(
DIST_DIR,
result.originalSrc.startsWith("/")
? result.originalSrc.slice(1)
: result.originalSrc,
);
try {
await fs.access(originalInDist);
await fs.unlink(originalInDist);
console.log(` ✔ Removed: ${originalInDist}`);
} catch {
// 文件可能不存在,忽略
}
}
console.log("✨ Font subsetting completed!");
}
main().catch((err) => {
console.error("❌ Font subsetting failed:", err);
process.exit(1);
});