Files
materials/knowledge/Go/tools/build-nav.js

179 lines
8.6 KiB
JavaScript
Raw Normal View History

#!/usr/bin/env node
/* ==========================================================================
Go 八股 · 页面骨架生成器
用法:node tools/build-nav.js [站点根目录,默认本文件的上一级]
作用:扫描站点根目录下的 NN-*.html,采集「章标题(h2)+ 小节(h3)」与
每章的 <meta name="description">,然后重写页面里的占位区块:
章节页:<nav id="chapters"></nav> 侧栏目录树(当前章展开小节)
<p class="chapnav"></p> 「第 N / 14 章」定位条
<nav class="pager"></nav> 上一章 / 下一章
<p class="foot"></p> 页脚
目录页:<nav id="chapters"></nav> 全部章节(不展开小节)
<!-- AUTO:kpis --> 章节 / 小节 / 代码示例 / 字数 四块指标
<!-- AUTO:cards --> 章节卡片(勾选已读 + 展开小节链接)
<nav class="pager"></nav> 「开始阅读」
<p class="foot"></p>
写章节时只写正文,骨架由本脚本统一生成;新增/重排章节后重新执行即可,
幂等、可重复运行。
========================================================================== */
const fs = require("fs");
const path = require("path");
const root = process.argv[2] || path.resolve(__dirname, "..");
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 stripNo = s => s.replace(/^\s*\d+(?:\.\d+)*\s*[\.、]?\s*/, "").trim();
/* ---------------------------- 1. 采集 ---------------------------- */
const files = fs.readdirSync(root, { withFileTypes: true })
.filter(e => e.isFile() && /^\d\d-.*\.html$/.test(e.name))
.map(e => e.name).sort();
if (!files.length) {
console.error("没有找到 NN-*.html 章节页,请检查目录:" + root);
process.exit(1);
}
const chapters = files.map(file => {
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) throw new Error(`${file}: 找不到 <h2 id="...">章标题</h2>`);
const title = plain(h2[1].replace(/<span class="n">\d+<\/span>/, ""));
const sections = [...html.matchAll(/<h3 id="([^"]+)">([\s\S]*?)<\/h3>/g)]
.map(m => ({ id: m[1], label: plain(m[2]) }));
const metaDesc = (html.match(/<meta name="description" content="([^"]*)"/) || [, ""])[1];
const metaKeys = (html.match(/<meta name="keywords" content="([^"]*)"/) || [, ""])[1];
const article = (html.match(/<article>([\s\S]*)<\/article>/) || [, ""])[1];
// 正文字数不含代码块(代码块单独统计段数)
const bodyText = article.replace(/<pre[\s\S]*?<\/pre>/g, " ");
return {
num, file, title, sections,
desc: plain(metaDesc),
keywords: plain(metaKeys),
pres: (html.match(/<pre[\s\S]*?<\/pre>/g) || []).length,
chars: plain(bodyText).replace(/\s+/g, "").length
};
});
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);
/* ---------------------------- 2. 区块生成 ---------------------------- */
function navTree(curNum) {
return chapters.map(c => {
const isCur = c.num === curNum;
const row = isCur
? `<span class="toc-a active" aria-current="page"><i class="cn">${c.num}</i>${esc(c.title)}</span>`
: `<a class="toc-a" href="${c.file}"><i class="cn">${c.num}</i>${esc(c.title)}</a>`;
if (!isCur || !c.sections.length) return row;
const sub = c.sections.map(s =>
`<a class="toc-a lv3" href="#${s.id}">${esc(s.label)}</a>`).join("");
return row + `<div class="subnav current">${sub}</div>`;
}).join("");
}
function chapnav(c) {
return ` <a href="index.html">Go 八股</a>\n` +
` <span>·</span>\n` +
` <span>第 <b class="pos">${c.num}</b> / ${chapters.length} 章</span>`;
}
function pager(c) {
const i = chapters.indexOf(c);
const a = (ch, cls, k) => ch
? ` <a class="${cls}" href="${ch.file}"><span class="k">${k}</span><span class="v">第 ${ch.num} 章 · ${esc(ch.title)}</span></a>`
: ` <a class="${cls} disabled"><span class="k">${k}</span><span class="v">没有更多了</span></a>`;
return a(chapters[i - 1], "prev", "← 上一章") + "\n" + a(chapters[i + 1], "next", "下一章 →");
}
function foot(c) {
return ` Go 八股 · 第 ${c.num} 章 ${esc(c.title)}<br>\n` +
` <a href="index.html">总目录</a> · <a href="../../SRE工程师/sre-learning-path/index.html">SRE 学习路径</a>`;
}
function kpis() {
const wan = (totalChars / 10000).toFixed(1);
return [
`<div class="kpi"><b>${chapters.length}</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 cards() {
return chapters.map(c => {
const search = [c.title, c.desc, c.keywords, c.sections.map(s => s.label).join(" ")]
.join(" ").toLowerCase();
const secs = c.sections.map(s =>
`<a href="${c.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="${c.num}" aria-label="标记第 ${c.num} 章已读">
<span class="cc-no">${c.num}</span>
<a class="cc-title" href="${c.file}">${esc(c.title)}</a>
<a class="cc-go" href="${c.file}">进入 →</a>
</div>
<p class="cc-desc">${esc(c.desc)}</p>
<details class="cc-secs">
<summary>${c.sections.length} 个小节 · 展开看知识点</summary>
<div>${secs}</div>
</details>
</div>`;
}).join("\n");
}
/* ---------------------------- 3. 写回 ---------------------------- */
const Z = (re, gen, only) => ({ re, gen, only }); // only: "index" | "chapter" | undefined
const zones = [
Z(/<nav id="chapters">[\s\S]*?<\/nav>/, (c, idx) => `<nav id="chapters">${navTree(idx ? 0 : c.num)}</nav>`),
Z(/<p class="chapnav">[\s\S]*?<\/p>/, c => `<p class="chapnav">\n${chapnav(c)}\n </p>`, "chapter"),
Z(/<!-- AUTO:kpis -->[\s\S]*?<!-- \/AUTO:kpis -->/, () => `<!-- AUTO:kpis -->\n ${kpis()}\n <!-- /AUTO:kpis -->`, "index"),
Z(/<!-- AUTO:cards -->[\s\S]*?<!-- \/AUTO:cards -->/, () => `<!-- AUTO:cards -->\n${cards()}\n <!-- /AUTO:cards -->`, "index"),
Z(/<nav class="pager">[\s\S]*?<\/nav>/, (c, idx) => idx
? `<nav class="pager">\n <a class="next" href="${chapters[0].file}"><span class="k">开始阅读 →</span><span class="v">第 1 章 · ${esc(chapters[0].title)}</span></a>\n </nav>`
: `<nav class="pager">\n${pager(c)}\n </nav>`),
Z(/<p class="foot">[\s\S]*?<\/p>/, (c, idx) => idx
? `<p class="foot">\n Go 八股知识库 · 共 ${chapters.length} 章 ${totalSecs} 个小节 · ${totalPres} 段代码<br>\n <a href="index.html">总目录</a> · <a href="../../SRE工程师/sre-learning-path/index.html">SRE 学习路径</a>\n </p>`
: `<p class="foot">\n${foot(c)}\n </p>`)
];
let pages = 0;
const targets = chapters.map(c => ({ c, file: c.file, idx: false }));
if (fs.existsSync(path.join(root, "index.html"))) {
targets.push({ c: chapters[0], file: "index.html", idx: true });
}
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 === "index" && !t.idx) continue;
if (z.only === "chapter" && t.idx) continue;
if (!z.re.test(html)) throw new Error(`${t.file}: 缺少占位区块 ${z.re}`);
html = html.replace(z.re, z.gen(t.c, t.idx));
}
fs.writeFileSync(p, html, "utf8");
pages++;
}
chapters.forEach(c => console.log(
`${c.file.padEnd(20)} 第 ${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共 ${chapters.length} 章 / ${totalSecs} 小节 / ${totalPres} 段代码 / ${(totalChars / 10000).toFixed(1)} 万字,已同步 ${pages} 个页面。`);