Files
materials/project/VLoop/tools/check-pages.js

273 lines
15 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env node
/* ==========================================================================
VLoop 项目学习 · 页面自检
用法:node tools/check-pages.js [--allow-empty]
--allow-empty(骨架期):内容量相关的要求(正文字数、代码块数量、提示框、
表格/卡片、meta 描述长度)降级为提示,只强制结构与链接正确。
内容补齐后去掉该参数,恢复为与其它站点一致的严格模式。
站点分三级页面,检查项按级别区分:
所有页面:title / article / #chapters 侧栏 / partnav 顶栏篇章导航 /
doc.css / doc.js / themeBtn / 站内链接不跑出本站
目录页 index.html:AUTO:kpis / AUTO:partcards(6 张)/ AUTO:prog /
「开始阅读」/ 目录页页脚
篇章页 part-N.html:AUTO:hero / AUTO:cards(张数 = 本篇章数)/ AUTO:prog /
「篇 N / 6」定位条 / 上一篇下一篇 / 篇章页页脚
章节页 NN-*.html:h2 / 小节 id 前缀 / 章位条 / 上一章下一章 / 章节页页脚 /
当前章 active / 侧栏小节数 = 正文 h3 数
通用:标签配对、死链、锚点、目录树列全 22 章并按篇分组、
顶栏篇章导航 6 个链接且当前篇高亮
========================================================================== */
"use strict";
const fs = require("fs");
const path = require("path");
const ALLOW_EMPTY = process.argv.includes("--allow-empty");
const root = path.resolve(__dirname, "..");
const problems = [];
const info = [];
const must = (c, m) => { if (!c) problems.push(m); };
const soft = (m) => { if (ALLOW_EMPTY) info.push("○ " + m); else problems.push(m); };
const read = (p) => fs.readFileSync(p, "utf8");
const stripTags = (s) => s.replace(/<[^>]+>/g, "");
const norm = (s) => s.replace(/\s+/g, "").length;
/* 正文字数:只看 <article> 内的手写内容——排除代码块,也排除 build-nav 生成的
导航(翻页 / 页脚 / 章位条),否则生成出来的文字会把篇幅算进去。 */
const bodyChars = (html) => {
const art = (html.match(/<article>([\s\S]*)<\/article>/) || [, ""])[1]
.replace(/<pre[\s\S]*?<\/pre>/g, " ")
.replace(/<nav class="pager">[\s\S]*?<\/nav>/g, " ")
.replace(/<p class="foot">[\s\S]*?<\/p>/g, " ")
.replace(/<p class="chapnav">[\s\S]*?<\/p>/g, " ");
return norm(stripTags(art));
};
/* ------------------------------------------------------------ 页面清点 */
const chapterFiles = fs.readdirSync(root).filter((f) => /^\d\d-.*\.html$/.test(f)).sort();
const partFiles = fs.readdirSync(root).filter((f) => /^part-\d+\.html$/.test(f))
.sort((a, b) => parseInt(a.slice(5), 10) - parseInt(b.slice(5), 10));
const hasIndex = fs.existsSync(path.join(root, "index.html"));
const pages = (hasIndex ? ["index.html"] : []).concat(partFiles, chapterFiles);
must(chapterFiles.length >= 5, "章节页数量异常:" + chapterFiles.length);
must(partFiles.length >= 2, "篇章页数量异常:" + partFiles.length);
/* 大纲:用于核对「篇章页里的卡片张数 = 该篇章数」 */
const outlineFile = path.join(__dirname, "outline.json");
const PLAN = fs.existsSync(outlineFile) ? JSON.parse(read(outlineFile)) : null;
must(!!PLAN, "tools/outline.json 不存在或解析失败");
const partChapters = new Map(); // 'part-0.html' -> ['01-overview.html', ...]
const chapterPart = new Map(); // '01-overview.html' -> ['01-overview.html', ...](本篇全部章)
if (PLAN) {
for (const p of PLAN.parts) {
const files = p.chapters.map((c) => c.file);
partChapters.set(`part-${p.no}.html`, files);
for (const cf of files) chapterPart.set(cf, files);
}
must(PLAN.parts.length === partFiles.length,
`outline.json 声明 ${PLAN.parts.length} 篇,磁盘上有 ${partFiles.length} 个篇章页`);
}
/* id 索引,供锚点校验 */
const idIndex = new Map();
for (const f of pages) {
const html = read(path.join(root, f));
idIndex.set(f, new Set([...html.matchAll(/\sid="([^"]+)"/g)].map((m) => m[1])));
}
const partFileSet = new Set(partFiles);
for (const f of pages) {
const html = read(path.join(root, f));
const markup = html.replace(/<script[\s\S]*?<\/script>/g, "");
const kind = f === "index.html" ? "index" : (partFileSet.has(f) ? "part" : "chapter");
must(/<title>[^<]+<\/title>/.test(html), `${f}: 缺少 title`);
must(html.includes("<article>"), `${f}: 缺少 <article>`);
must(html.includes('id="chapters"'), `${f}: 缺少侧栏 #chapters`);
must(html.includes('href="assets/doc.css"'), `${f}: doc.css 路径不对`);
must(html.includes('src="assets/doc.js"'), `${f}: doc.js 路径不对`);
must(html.includes('id="themeBtn"'), `${f}: 缺少主题切换按钮`);
must(!/href="\.\.\//.test(markup), `${f}: 站内链接不应跑出本资料目录`);
/* ---------------- 顶栏篇章导航 ---------------- */
const pnav = markup.match(/<nav class="partnav"[^>]*>([\s\S]*?)<\/nav>/);
must(!!pnav, `${f}: 缺少顶栏篇章导航 .partnav`);
if (pnav) {
const links = (pnav[1].match(/<a [^>]*href="part-\d+\.html"/g) || []).length;
must(links === partFiles.length, `${f}: 顶栏篇章导航有 ${links} 个篇章链接 ≠ ${partFiles.length}`);
must(/href="index\.html"/.test(pnav[1]), `${f}: 顶栏篇章导航缺少返回学习地图的入口`);
const onCount = (pnav[1].match(/\bclass="[^"]*\bon\b[^"]*"/g) || []).length;
must(onCount === 1, `${f}: 顶栏篇章导航应有且只有 1 个高亮项(当前为 ${onCount} 个)`);
if (kind === "index") {
must(/<a class="home on" href="index\.html"/.test(pnav[1]), "index.html: 顶栏「学习地图」未高亮");
} else if (kind === "part") {
const no = f.slice(5, -5);
must(new RegExp(`<a href="part-${no}\\.html" class="on"`).test(pnav[1]),
`${f}: 顶栏未把本篇(篇 ${no})标为高亮`);
}
}
/* 代码块结构(骨架期还没有代码块,data-lang 只在有时校验) */
const pres = markup.match(/<pre[\s\S]*?<\/pre>/g) || [];
pres.forEach((blk, i) => {
must(/data-lang=/.test(blk), `${f}: 第 ${i + 1} 个 <pre> 未标注 data-lang`);
const body = blk.replace(/^<pre[^>]*>/, "").replace(/<\/pre>$/, "");
must(!/</.test(body), `${f}: 第 ${i + 1} 个 <pre> 内有未转义的 <`);
});
/* 标签配对 */
for (const t of ["div", "section", "article", "aside", "nav", "main", "details", "table", "ul", "ol", "li"]) {
const o = (markup.match(new RegExp("<" + t + "(?=[\\s>])", "g")) || []).length;
const c = (markup.match(new RegExp("</" + t + ">", "g")) || []).length;
if (o !== c) problems.push(`${f}: <${t}> 开合不匹配 ${o}/${c}`);
}
/* 链接与锚点 */
for (const l of new Set([...markup.matchAll(/href="(?!https?:|mailto:|#)([^"]+)"/g)].map((m) => m[1]))) {
const [file, hash] = l.split("#");
const target = path.resolve(root, file || f);
if (file && !fs.existsSync(target)) { problems.push(`${f}: 死链 ${l}`); continue; }
const key = file ? path.basename(file) : f;
if (hash && idIndex.has(key) && !idIndex.get(key).has(hash)) problems.push(`${f}: 锚点不存在 ${l}`);
}
for (const l of new Set([...markup.matchAll(/href="#([^"]+)"/g)].map((m) => m[1]))) {
if (!idIndex.get(f).has(l)) problems.push(`${f}: 页内锚点不存在 #${l}`);
}
/* ---------------- 按页面级别检查 ---------------- */
if (kind === "index") {
must(/<!-- AUTO:kpis -->/.test(html), "index.html: 缺少 AUTO:kpis 区块");
must(/<!-- AUTO:partcards -->/.test(html), "index.html: 缺少 AUTO:partcards 区块");
must(/<!-- AUTO:prog -->/.test(html), "index.html: 缺少 AUTO:prog 区块");
const pc = (markup.match(/class="partcard"/g) || []).length;
must(pc === partFiles.length, `index.html: 篇章入口卡片 ${pc} 张 ≠ ${partFiles.length}`);
must(/data-partprog/.test(markup), "index.html: 篇章卡片缺少已读进度位 data-partprog");
const pg = markup.match(/<nav class="pager">([\s\S]*?)<\/nav>/);
must(!!pg && /开始阅读/.test(pg[1]), "index.html: .pager 缺少「开始阅读」入口");
must(!!pg && !/上一章|下一章|上一篇|下一篇/.test(pg[1]), "index.html: .pager 误用了翻页导航");
must(/class="foot">\s*VLoop 项目学习 · 共 \d+ 篇/.test(html.replace(/\n/g, "")), "index.html: 页脚不是目录页页脚");
must(/class="hero"/.test(markup), "index.html: 缺少 .hero 站点标题区");
}
if (kind === "part") {
const no = f.slice(5, -5);
must(/<!-- AUTO:hero -->/.test(html), `${f}: 缺少 AUTO:hero 区块`);
must(/<!-- AUTO:cards -->/.test(html), `${f}: 缺少 AUTO:cards 区块`);
must(/<!-- AUTO:prog -->/.test(html), `${f}: 缺少 AUTO:prog 区块`);
must(/class="modhero"/.test(markup), `${f}: 缺少篇章导语 .modhero`);
must(/data-chapters="[\d,]+"/.test(markup), `${f}: 缺少进度条 data-chapters`);
const expect = partChapters.get(f) || [];
const cards = [...markup.matchAll(/<div class="chapcard"[^>]*>([\s\S]*?)<details/g)]
.map((m) => (m[1].match(/href="([^"]+)"/) || [, ""])[1]);
must(cards.length === expect.length, `${f}: 章节卡片 ${cards.length} 张 ≠ 本篇 ${expect.length} 章`);
for (const cf of expect) {
must(cards.includes(cf), `${f}: 章节卡片缺少 ${cf}`);
}
const cn = markup.match(/<p class="chapnav">([\s\S]*?)<\/p>/);
must(!!cn && new RegExp(`篇 <b class="pos">${no}</b>`).test(cn[1]), `${f}: 定位条不是「篇 ${no} / N」`);
const pg = markup.match(/<nav class="pager">([\s\S]*?)<\/nav>/);
must(!!pg && /上一篇|下一篇/.test(pg[1]), `${f}: .pager 不是篇章页的上一篇/下一篇`);
must(!!pg && !/开始阅读/.test(pg[1]), `${f}: .pager 误用了目录页的「开始阅读」`);
must(new RegExp(`class="foot">\\s*VLoop 项目学习 · 篇 ${no}`).test(html.replace(/\n/g, "")),
`${f}: 页脚不是本篇页脚`);
}
if (kind === "chapter") {
const num = parseInt(f.slice(0, 2), 10);
const h2 = html.match(/<h2 id="([^"]+)">([\s\S]*?)<\/h2>/);
must(!!h2, `${f}: 缺少 h2 章节标题`);
must(html.includes('class="chapnav"'), `${f}: 缺少章节定位条 .chapnav`);
must(html.includes('class="pager"'), `${f}: 缺少上一/下一章 .pager`);
must(html.includes('class="foot"'), `${f}: 缺少页脚 .foot`);
must(html.includes('href="index.html"'), `${f}: 缺少返回学习地图链接`);
must(/class="toc-a active"[^>]*aria-current="page"/.test(html), `${f}: 当前章未标记 active`);
const h3 = [...html.matchAll(/<h3 id="([^"]+)">([\s\S]*?)<\/h3>/g)];
const h3any = (html.match(/<h3[ >]/g) || []).length;
must(h3.length === h3any, `${f}: 有 h3 未补 id(${h3.length}/${h3any})`);
must(h3.length >= 3, `${f}: 小节过少(${h3.length}),至少 3 个`);
for (const m of h3) {
if (!m[1].startsWith(`sec-${num}-`)) problems.push(`${f}: 小节 id "${m[1]}" 应以 sec-${num}- 开头`);
}
const pager = markup.match(/<nav class="pager">([\s\S]*?)<\/nav>/);
must(!!pager && /上一章|下一章/.test(pager[1]), `${f}: .pager 不是章节页的上一/下一章导航`);
must(!!pager && !/开始阅读|上一篇|下一篇/.test(pager[1]), `${f}: .pager 用了别的页面的翻页样式`);
must(new RegExp(`class="foot">\\s*VLoop 项目学习 · 第 ${num} 章`).test(html.replace(/\n/g, "")),
`${f}: 页脚不是本章标题`);
const sub = html.match(/<div class="subnav current">([\s\S]*?)<\/div>/);
must(!!sub, `${f}: 侧栏缺少当前章小节`);
if (sub) {
const n = (sub[1].match(/class="toc-a lv3"/g) || []).length;
must(n === h3.length, `${f}: 侧栏小节数 ${n} ≠ 正文 h3 数 ${h3.length}`);
}
/* 内容量(骨架期降级为提示) */
const desc = (html.match(/<meta name="description" content="([^"]*)"/) || [, ""])[1];
if (desc.trim().length < 20) soft(`${f}: meta description 太短或缺失(${desc.length} 字)`);
if (!/class="box /.test(html)) soft(`${f}: 没有任何 .box 提示框`);
if (!/class="tablewrap"/.test(html) && !/class="cards"/.test(html)) {
soft(`${f}: 既没有表格也没有卡片组`);
}
if (pres.length < 2) soft(`${f}: 代码块过少(${pres.length}),至少 2 个`);
if (bodyChars(html) < 2200) soft(`${f}: 正文过短(约 ${bodyChars(html)} 字),内容需要补充`);
const tbd = (html.match(/class="tbd"/g) || []).length;
if (tbd && tbd !== h3.length) {
soft(`${f}: ${h3.length} 个小节里有 ${tbd} 个仍标记待补充`);
}
}
/* ---------------- 侧栏目录树 ----------------
学习地图:按篇分组列全 22 章,是唯一能看到全貌的目录。
篇章页 / 章节页:只列本篇的章(顶栏负责跨篇跳转),并带一条范围条。 */
const nav = markup.match(/<nav id="chapters">([\s\S]*?)<\/nav>/);
must(!!nav, `${f}: 缺少 #chapters 目录树`);
if (nav) {
const rows = (nav[1].match(/class="toc-a( active)?"/g) || []).length;
if (kind === "index") {
must(rows === chapterFiles.length, `${f}: 目录树章节数 ${rows} ≠ ${chapterFiles.length}`);
const groups = (nav[1].match(/class="toc-part/g) || []).length;
must(groups === partFiles.length, `${f}: 目录树「篇」分组 ${groups} ≠ ${partFiles.length}`);
for (const cf of chapterFiles) {
must(nav[1].includes(`href="${cf}"`), `${f}: 目录树缺少章节 ${cf}`);
}
must(!/class="subnav/.test(nav[1]), `${f}: 目录页不应展开任何章的小节`);
must(!/class="toc-scope/.test(nav[1]), `${f}: 目录页不应有本篇范围条`);
} else {
const expect = kind === "part" ? (partChapters.get(f) || []) : (chapterPart.get(f) || []);
must(rows === expect.length, `${f}: 侧栏只应列本篇 ${expect.length} 章,实际 ${rows}`);
for (const cf of expect) {
if (cf === f) continue;
must(nav[1].includes(`href="${cf}"`), `${f}: 侧栏缺少本篇章节 ${cf}`);
}
for (const cf of chapterFiles) {
if (cf === f || expect.includes(cf)) continue;
must(!nav[1].includes(`href="${cf}"`), `${f}: 侧栏出现了其它篇的章节 ${cf}`);
}
must(/class="toc-scope"/.test(nav[1]), `${f}: 侧栏缺少本篇范围条 .toc-scope`);
must(/href="index\.html"/.test(nav[1]), `${f}: 侧栏缺少「全部篇章」入口`);
must(!/class="toc-part/.test(nav[1]), `${f}: 侧栏不应再按篇分组`);
}
}
info.push(`${f.padEnd(26)} ~${bodyChars(html)} 字 · 代码块 ${pres.length}`);
}
info.sort((a, b) => a.replace(/^○ /, "").localeCompare(b.replace(/^○ /, "")));
console.log(info.join("\n"));
if (problems.length) {
console.error(`\n✗ 发现 ${problems.length} 个问题:`);
problems.slice(0, 60).forEach((x) => console.error(" - " + x));
process.exit(1);
}
console.log(`\n✓ 结构与链接全部通过(目录页 + ${partFiles.length} 个篇章页 + ${chapterFiles.length} 章,共 ${pages.length} 个页面)` +
(ALLOW_EMPTY ? "\n○ 当前为骨架期(--allow-empty):正文、代码块、提示框与表格尚未撰写,补齐内容后请去掉该参数重跑。"
: "\n 严格模式:内容量与组件构成均已达标。"));