Files
materials/project/VLoop/tools/build-nav.js

360 lines
17 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/build-nav.js
本站分三级页面:
目录页 index.html 学习地图 + 六个篇章入口卡片
篇章页 part-N.html 一篇的导语 + 该篇的章节卡片(六个篇)
章节页 NN-slug.html 一章正文(二十二章)
数据来源:
tools/outline.json ← 篇 / 章 / 小节 的声明(骨架的唯一来源)
各页面的 <h3 id> ← 只用来核对「页面是否与大纲一致」,不反向覆盖大纲
重写的占位区块:
所有页面:<nav class="partnav"> 顶栏篇章导航(当前篇高亮)
<nav id="chapters"> 侧栏目录树(按篇分组,当前章展开小节)
篇章页: <!-- AUTO:hero --> 篇章导语(篇号 / 篇名 / 篇导语 / 章数小节数)
<!-- AUTO:cards --> 该篇的章节卡片
<!-- AUTO:prog --> 本篇已读进度条
<p class="chapnav"> 「篇 N / 6」定位条
<nav class="pager"> 上一篇 / 下一篇
目录页: <!-- AUTO:kpis --> 篇 / 章 / 小节 / 代码 / 字数
<!-- AUTO:partcards --> 六个篇章入口卡片
<!-- AUTO:prog --> 总体已读进度条
<nav class="pager"> 「开始阅读」
页脚: <p class="foot"> 三种页面各自的页脚
写正文时只写 <article> 里的内容,骨架由本脚本统一生成;调整大纲先改 outline.json
与页面标题,再执行本脚本。幂等、可重复运行。
========================================================================== */
"use strict";
const fs = require("fs");
const path = require("path");
const ROOT = path.resolve(__dirname, "..");
const PLAN = JSON.parse(fs.readFileSync(path.join(__dirname, "outline.json"), "utf8"));
const S = PLAN.site;
const TOTAL = PLAN.parts.reduce((n, p) => n + p.chapters.length, 0);
const PART_PAGE = (no) => `part-${no}.html`;
const esc = (s) => String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;")
.replace(/>/g, "&gt;").replace(/"/g, "&quot;");
const stripTags = (s) => s.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim();
const decode = (s) => s.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"')
.replace(/&#39;/g, "'").replace(/&nbsp;/g, " ").replace(/&amp;/g, "&");
const plain = (s) => decode(stripTags(s));
const shortPart = (name) => name.split("·")[0].trim();
/* ---------------------------- 1. 采集与核对 ---------------------------- */
const chapters = [];
const problems = [];
for (const part of PLAN.parts) {
const pf = PART_PAGE(part.no);
if (!fs.existsSync(path.join(ROOT, pf))) problems.push(`${pf}: 篇章页不存在`);
for (const c of part.chapters) {
const file = c.file;
if (!fs.existsSync(path.join(ROOT, file))) { problems.push(`${file}: 文件不存在`); continue; }
const html = fs.readFileSync(path.join(ROOT, file), "utf8");
const num = parseInt(file.slice(0, 2), 10);
const h2 = html.match(/<h2 id="([^"]+)">([\s\S]*?)<\/h2>/);
if (!h2) { problems.push(`${file}: 找不到 <h2 id="...">章标题</h2>`); continue; }
const title = plain(h2[2].replace(/<span class="n">\d+<\/span>/, ""));
if (title !== c.title) {
problems.push(`${file}: 章标题与 outline.json 不一致\n 页面:${title}\n 大纲:${c.title}`);
}
/* 小节以页面 h3 为准,但必须与大纲逐条对齐(数量 + id + 标题) */
const secs = [...html.matchAll(/<h3 id="([^"]+)">([\s\S]*?)<\/h3>/g)]
.map((m) => ({ id: m[1], label: plain(m[2]) }));
if (secs.length !== c.sections.length) {
problems.push(`${file}: 小节数 ${secs.length} ≠ 大纲 ${c.sections.length}`);
} else {
c.sections.forEach((s, i) => {
if (secs[i].id !== s.id) problems.push(`${file}: 第 ${i + 1} 个小节 id "${secs[i].id}" ≠ 大纲 "${s.id}"`);
if (secs[i].label !== s.title) {
problems.push(`${file}: 小节 "${s.id}" 标题与大纲不一致\n 页面:${secs[i].label}\n 大纲:${s.title}`);
}
});
}
const article = (html.match(/<article>([\s\S]*)<\/article>/) || [, ""])[1];
/* 正文字数:排除代码块,也排除本脚本生成的导航(翻页 / 页脚 / 章位条) */
const bodyText = article
.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, " ");
chapters.push({
num, file, title, part, sections: secs,
desc: plain((html.match(/<meta name="description" content="([^"]*)"/) || [, ""])[1]),
level: c.level || "",
pres: (html.match(/<pre[\s\S]*?<\/pre>/g) || []).length,
chars: plain(bodyText).replace(/\s+/g, "").length,
todo: (html.match(/class="tbd"/g) || []).length
});
}
}
if (problems.length) {
console.error(`大纲与页面不一致(${problems.length} 处),已停止改写:`);
problems.forEach((p) => console.error(" - " + p));
process.exit(1);
}
const parts = PLAN.parts.map((p) => ({
...p,
chapters: p.chapters.map((c) => chapters.find((x) => x.file === c.file)).filter(Boolean)
}));
/* 章的 part 必须指回「富化后」的篇对象,否则 ctx.part.chapters 拿到的是大纲里的
原始章节(没有 num / pres / chars),渲染出来章号会是 undefined。 */
for (const p of parts) for (const ch of p.chapters) ch.part = p;
const totalSecs = chapters.reduce((n, c) => n + c.sections.length, 0);
const totalPres = chapters.reduce((n, c) => n + c.pres, 0);
const totalChars = chapters.reduce((n, c) => n + c.chars, 0);
const totalTodo = chapters.reduce((n, c) => n + c.todo, 0);
const allNums = chapters.map((c) => c.num).join(",");
/* ---------------------------- 2. 区块生成 ---------------------------- */
function partnav(ctx) {
const rows = [`<a class="home${ctx.kind === "index" ? " on" : ""}" href="index.html">学习地图</a>`,
`<span class="pn-sep"></span>`];
for (const p of parts) {
const on = ctx.part && String(ctx.part.no) === String(p.no);
rows.push(`<a href="${PART_PAGE(p.no)}"${on ? ' class="on"' : ""}>篇 ${p.no} ${esc(shortPart(p.name))}</a>`);
}
return `<nav class="partnav" id="partnav">${rows.join("")}</nav>`;
}
function chapterRow(ch, ctx) {
const isCur = ctx.kind === "chapter" && ch.num === ctx.chapter.num;
if (!isCur) {
return `<a class="toc-a" href="${ch.file}"><i class="cn">${ch.num}</i>${esc(ch.title)}</a>`;
}
const sub = ch.sections.length
? `<div class="subnav current">${ch.sections
.map((s) => `<a class="toc-a lv3" href="#${s.id}">${esc(s.label)}</a>`).join("")}</div>`
: "";
return `<span class="toc-a active" aria-current="page"><i class="cn">${ch.num}</i>${esc(ch.title)}</span>` + sub;
}
function navTree(ctx) {
/* 学习地图:全站目录,六个篇分组列出全部章节——它是唯一「看得见全貌」的地方 */
if (ctx.kind === "index") {
const rows = [];
for (const p of parts) {
rows.push(`<div class="toc-part"><a href="${PART_PAGE(p.no)}">篇 ${p.no} · ${esc(shortPart(p.name))}</a></div>`);
for (const ch of p.chapters) rows.push(chapterRow(ch, ctx));
}
return `<nav id="chapters">${rows.join("")}</nav>`;
}
/* 篇章页与章节页:侧栏只列本篇自己的章,顶部一条「本篇 / 全部篇章」的范围条 */
const p = ctx.part;
const rows = [
`<div class="toc-scope">` +
`<span class="ts-label">篇 ${p.no}</span><span class="ts-name">${esc(shortPart(p.name))}</span>` +
`<a class="ts-all" href="index.html">全部篇章 →</a>` +
`</div>`
];
for (const ch of p.chapters) rows.push(chapterRow(ch, ctx));
return `<nav id="chapters">${rows.join("")}</nav>`;
}
function chapnav(ctx) {
if (ctx.kind === "part") {
return ` <a href="index.html">${esc(S.name)}</a>\n` +
` <span>·</span>\n` +
` <span>篇 <b class="pos">${ctx.part.no}</b> / ${parts.length}</span>`;
}
const p = ctx.chapter.part;
return ` <a href="index.html">${esc(S.name)}</a>\n` +
` <span>·</span>\n` +
` <a href="${PART_PAGE(p.no)}">篇 ${p.no} ${esc(shortPart(p.name))}</a>\n` +
` <span>·</span>\n` +
` <span>第 <b class="pos">${ctx.chapter.num}</b> / ${TOTAL} 章</span>`;
}
function pagerLinks(prev, next, kPrev, kNext, doneText) {
const a = (item, cls, k) => item
? ` <a class="${cls}" href="${item.href}"><span class="k">${k}</span><span class="v">${item.label}</span></a>`
: ` <a class="${cls} disabled"><span class="k">${k}</span><span class="v">${doneText}</span></a>`;
return a(prev, "prev", kPrev) + "\n" + a(next, "next", kNext);
}
function pager(ctx) {
if (ctx.kind === "index") {
const first = chapters[0];
return ` <a class="next" href="${first.file}"><span class="k">开始阅读 →</span><span class="v">第 ${first.num} 章 · ${esc(first.title)}</span></a>`;
}
if (ctx.kind === "part") {
const i = parts.indexOf(ctx.part);
const mk = (p) => p && { href: PART_PAGE(p.no), label: `篇 ${p.no} · ${esc(shortPart(p.name))}` };
return pagerLinks(mk(parts[i - 1]), mk(parts[i + 1]), "← 上一篇", "下一篇 →", "没有更多了");
}
const i = chapters.indexOf(ctx.chapter);
const mk = (c) => c && { href: c.file, label: `第 ${c.num} 章 · ${esc(c.title)}` };
return pagerLinks(mk(chapters[i - 1]), mk(chapters[i + 1]), "← 上一章", "下一章 →", "没有更多了");
}
function foot(ctx) {
if (ctx.kind === "index") {
return ` ${esc(S.name)} · 共 ${parts.length} 篇 ${TOTAL} 章 ${totalSecs} 个小节` +
`${totalTodo ? ` · 其中 ${totalTodo} 个小节待撰写` : ` · ${totalPres} 段代码`}<br>\n` +
` <a href="${esc(S.repoUrl)}">${esc(S.repo)}</a> · <a href="index.html">学习地图</a>`;
}
if (ctx.kind === "part") {
return ` ${esc(S.name)} · 篇 ${ctx.part.no} ${esc(ctx.part.name)}<br>\n` +
` <a href="index.html">学习地图</a> · ${ctx.part.chapters.length} 章 · ` +
`${ctx.part.chapters.reduce((n, c) => n + c.sections.length, 0)} 个小节`;
}
const c = ctx.chapter;
return ` ${esc(S.name)} · 第 ${c.num} 章 ${esc(c.title)}<br>\n` +
` <a href="index.html">学习地图</a> · <a href="${PART_PAGE(c.part.no)}">篇 ${c.part.no} ${esc(shortPart(c.part.name))}</a>` +
` · <a href="22-cheatsheet.html">速查与自测</a>`;
}
function kpis() {
const wan = (totalChars / 10000).toFixed(1);
return [
`<div class="kpi"><b>${parts.length}</b><span>个篇章 · 递进式学习路径</span></div>`,
`<div class="kpi"><b>${TOTAL}</b><span>章 · 从全景到速查</span></div>`,
`<div class="kpi"><b>${totalSecs}</b><span>个小节骨架</span></div>`,
`<div class="kpi"><b>${totalPres}</b><span>段可复制代码</span></div>`,
`<div class="kpi"><b>${wan} 万</b><span>字正文</span></div>`
].join("\n ");
}
function partcards() {
return parts.map((p) => {
const nums = p.chapters.map((c) => c.num);
const secs = p.chapters.reduce((n, c) => n + c.sections.length, 0);
const lv = [...new Set(p.chapters.map((c) => c.level).filter(Boolean))].sort();
return ` <div class="partcard" data-chapters="${nums.join(",")}">
<div class="pc-head">
<span class="pc-no">篇 ${p.no}</span>
<a class="pc-name" href="${PART_PAGE(p.no)}">${esc(p.name)}</a>
</div>
<p class="pc-note">${esc(p.note || "")}</p>
<div class="pc-meta">
<span><b>${nums.length}</b> 章</span>
<span><b>${secs}</b> 小节</span>
${lv.length ? `<span>${lv.join(" / ")}</span>` : ""}
<span data-partprog>已读 0 / ${nums.length}</span>
</div>
<a class="pc-go" href="${PART_PAGE(p.no)}">进入本篇 →</a>
</div>`;
}).join("\n");
}
function cardsOf(part) {
return part.chapters.map((ch) => {
const search = [ch.title, ch.desc, ch.level, ch.sections.map((s) => s.label).join(" ")]
.join(" ").toLowerCase();
const secs = ch.sections.map((s) =>
`<a href="${ch.file}#${s.id}">${esc(s.label)}</a>`).join("");
return ` <div class="chapcard" data-search="${esc(search)}">
<div class="cc-head">
<input type="checkbox" data-ch="${ch.num}" aria-label="标记第 ${ch.num} 章已读">
<span class="cc-no">${ch.num}</span>
<a class="cc-title" href="${ch.file}">${esc(ch.title)}</a>
${ch.level ? `<span class="cc-lv">${esc(ch.level)}</span>` : ""}
<a class="cc-go" href="${ch.file}">进入 →</a>
</div>
<p class="cc-desc">${esc(ch.desc)}</p>
<details class="cc-secs">
<summary>${ch.sections.length} 个小节${ch.todo ? " · 待撰写" : ""} · 展开看知识点</summary>
<div>${secs}</div>
</details>
</div>`;
}).join("\n");
}
function hero(part) {
const nums = part.chapters.map((c) => c.num);
const secs = part.chapters.reduce((n, c) => n + c.sections.length, 0);
const lv = [...new Set(part.chapters.map((c) => c.level).filter(Boolean))].sort();
return ` <!-- AUTO:hero -->
<div class="modhero">
<span class="mh-no">篇 ${part.no} / ${parts.length}</span>
<h1>${esc(part.name)}</h1>
<p class="mh-sub">${esc(part.note || "")}</p>
<div class="mh-meta">
<span>第 <b>${nums[0]}</b>–<b>${nums[nums.length - 1]}</b> 章</span>
<span><b>${nums.length}</b> 章 · <b>${secs}</b> 个小节</span>
${lv.length ? `<span>能力等级 <b>${lv.join(" / ")}</b></span>` : ""}
</div>
</div>
<!-- /AUTO:hero -->`;
}
function prog(nums) {
return ` <!-- AUTO:prog -->
<div class="progwrap" data-chapters="${nums}">
<span>已读</span><div class="bar"><i></i></div><b>0%</b>
</div>
<!-- /AUTO:prog -->`;
}
/* ---------------------------- 3. 写回 ---------------------------- */
const Z = (re, gen, only) => ({ re, gen, only });
const zones = [
Z(/<nav class="partnav"[^>]*>[\s\S]*?<\/nav>/, (ctx) => partnav(ctx)),
Z(/<nav id="chapters">[\s\S]*?<\/nav>/, (ctx) => navTree(ctx)),
Z(/<p class="chapnav">[\s\S]*?<\/p>/, (ctx) => `<p class="chapnav">\n${chapnav(ctx)}\n </p>`, "part|chapter"),
Z(/<!-- AUTO:hero -->[\s\S]*?<!-- \/AUTO:hero -->/, (ctx) => hero(ctx.part), "part"),
Z(/<!-- AUTO:kpis -->[\s\S]*?<!-- \/AUTO:kpis -->/, () => `<!-- AUTO:kpis -->\n ${kpis()}\n <!-- /AUTO:kpis -->`, "index"),
Z(/<!-- AUTO:partcards -->[\s\S]*?<!-- \/AUTO:partcards -->/, () => `<!-- AUTO:partcards -->\n${partcards()}\n <!-- /AUTO:partcards -->`, "index"),
Z(/<!-- AUTO:cards -->[\s\S]*?<!-- \/AUTO:cards -->/, (ctx) => `<!-- AUTO:cards -->\n${cardsOf(ctx.part)}\n <!-- /AUTO:cards -->`, "part"),
Z(/<!-- AUTO:prog -->[\s\S]*?<!-- \/AUTO:prog -->/, (ctx) => prog(ctx.kind === "index"
? allNums : ctx.part.chapters.map((c) => c.num).join(",")), "index|part"),
Z(/<nav class="pager">[\s\S]*?<\/nav>/, (ctx) => `<nav class="pager">\n${pager(ctx)}\n </nav>`),
Z(/<p class="foot">[\s\S]*?<\/p>/, (ctx) => `<p class="foot">\n${foot(ctx)}\n </p>`)
];
const targets = [];
if (fs.existsSync(path.join(ROOT, "index.html"))) {
targets.push({ file: "index.html", ctx: { kind: "index" } });
}
for (const p of parts) {
targets.push({ file: PART_PAGE(p.no), ctx: { kind: "part", part: p } });
}
for (const c of chapters) {
targets.push({ file: c.file, ctx: { kind: "chapter", chapter: c, part: c.part } });
}
for (const t of targets) {
const p = path.join(ROOT, t.file);
let html = fs.readFileSync(p, "utf8");
for (const z of zones) {
if (z.only && !z.only.split("|").includes(t.ctx.kind)) continue;
if (!z.re.test(html)) {
console.error(`${t.file}: 缺少占位区块 ${z.re}`);
process.exit(1);
}
html = html.replace(z.re, z.gen(t.ctx));
}
fs.writeFileSync(p, html, "utf8");
}
/* ---------------------------- 4. 报告 ---------------------------- */
for (const p of parts) {
const secs = p.chapters.reduce((n, c) => n + c.sections.length, 0);
console.log(`${PART_PAGE(p.no).padEnd(12)} 篇 ${p.no} · ${String(p.chapters.length).padStart(2)} 章 · ` +
`${String(secs).padStart(3)} 小节 · ${p.name}`);
}
console.log("");
chapters.forEach((c) => console.log(
`${c.file.padEnd(26)} 第 ${String(c.num).padStart(2)} 章 · ${String(c.sections.length).padStart(2)} 小节 · ` +
`${String(c.pres).padStart(2)} 段代码 · ${String(c.chars).padStart(6)} 字 · ${c.title}`));
console.log(`\n篇 ${parts.length} / 章 ${TOTAL} / 小节 ${totalSecs} / 代码 ${totalPres} 段 / ${(totalChars / 10000).toFixed(1)} 万字` +
`${totalTodo ? `(待撰写 ${totalTodo} 个小节)` : ""},已同步 ${targets.length} 个页面。`);