Files
WT-Offline/scripts/build-mod-docs-html.ts
T

412 lines
12 KiB
TypeScript

/**
* Generate self-contained offline HTML mod authoring guides (zh-CN.html and en.html)
* from `mod-dev-docs/<lang>/01..07.md`. Supports built-in sidebar navigation, copyable code
* blocks, language switching, and clean print-to-PDF styling with zero external dependencies.
*/
import { mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join, resolve } from 'node:path';
interface Chapter {
readonly slug: string;
readonly title: string;
readonly html: string;
}
export function buildOfflineModDocs(docsRoot: string, outputDir: string): { readonly zh: string; readonly en: string } {
mkdirSync(outputDir, { recursive: true });
const zhPath = join(outputDir, 'zh-CN.html');
const enPath = join(outputDir, 'en.html');
writeFileSync(zhPath, renderHandbook(docsRoot, 'zh-CN'), 'utf8');
writeFileSync(enPath, renderHandbook(docsRoot, 'en'), 'utf8');
return { zh: zhPath, en: enPath };
}
function renderHandbook(docsRoot: string, lang: 'zh-CN' | 'en'): string {
const dir = join(docsRoot, lang);
const files = readdirSync(dir)
.filter((name) => name.endsWith('.md'))
.sort((a, b) => a.localeCompare(b));
const chapters: Chapter[] = files.map((file) => {
const markdown = readFileSync(join(dir, file), 'utf8');
const titleMatch = /^#\s+(.+)$/m.exec(markdown);
const title = titleMatch ? titleMatch[1]!.trim() : file.replace(/\.md$/, '');
const slug = file.replace(/\.md$/, '');
return { slug, title, html: renderMarkdown(markdown) };
});
const isZh = lang === 'zh-CN';
const pageTitle = isZh ? 'WTOffline 模组开发手册(离线版)' : 'WTOffline Mod Development Handbook (Offline)';
const subtitle = isZh ? 'API 0.1-experimental · 实验期随时可能变动' : 'API 0.1-experimental · Subject to breaking changes';
const switchHref = isZh ? 'en.html' : 'zh-CN.html';
const switchLabel = isZh ? 'English' : '简体中文';
const printLabel = isZh ? '打印 / 另存为 PDF' : 'Print / Save as PDF';
const copyLabel = isZh ? '复制' : 'Copy';
const copiedLabel = isZh ? '已复制' : 'Copied';
const navLinks = chapters
.map((ch) => `<a class="nav-link" href="#${escapeHtml(ch.slug)}">${escapeHtml(ch.title)}</a>`)
.join('\n');
const sections = chapters
.map((ch) => `<article class="chapter" id="${escapeHtml(ch.slug)}">${ch.html}</article>`)
.join('\n<hr class="chapter-sep" />\n');
return `<!DOCTYPE html>
<html lang="${lang}">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>${escapeHtml(pageTitle)}</title>
<style>
:root {
--bg: #12161a;
--panel: #1a2026;
--panel-alt: #212830;
--border: rgba(255, 255, 255, 0.12);
--text: #e6edf3;
--dim: #9aa7b4;
--accent: #d9463e;
--warn: #e0a63b;
--code-bg: #0d1115;
}
* { box-sizing: border-box; }
body {
margin: 0;
font: 14px/1.68 -apple-system, BlinkMacSystemFont, "Segoe UI", "Microsoft YaHei", sans-serif;
color: var(--text);
background: var(--bg);
display: flex;
min-height: 100vh;
}
aside.sidebar {
position: sticky;
top: 0;
align-self: flex-start;
width: 280px;
height: 100vh;
overflow-y: auto;
padding: 20px 16px;
background: var(--panel);
border-right: 1px solid var(--border);
flex: none;
}
.brand {
font-size: 16px;
font-weight: 700;
margin-bottom: 4px;
color: #fff;
}
.brand-sub {
font-size: 11.5px;
color: var(--warn);
margin-bottom: 14px;
}
.toolbar {
display: flex;
gap: 8px;
margin-bottom: 16px;
}
.toolbar a, .toolbar button {
flex: 1;
padding: 6px 8px;
font-size: 12px;
text-align: center;
text-decoration: none;
color: var(--text);
background: var(--panel-alt);
border: 1px solid var(--border);
border-radius: 4px;
cursor: pointer;
}
.toolbar a:hover, .toolbar button:hover {
border-color: rgba(255, 255, 255, 0.35);
background: #2a333d;
}
nav.toc {
display: flex;
flex-direction: column;
gap: 4px;
}
a.nav-link {
display: block;
padding: 7px 10px;
font-size: 13px;
color: var(--dim);
text-decoration: none;
border-radius: 4px;
border-left: 2px solid transparent;
}
a.nav-link:hover {
color: #fff;
background: rgba(255, 255, 255, 0.05);
border-left-color: var(--accent);
}
main.content {
flex: 1;
min-width: 0;
max-width: 960px;
padding: 32px 42px 64px;
}
.chapter { margin-bottom: 44px; }
.chapter-sep { border: 0; border-top: 1px solid var(--border); margin: 40px 0; }
h1 { font-size: 26px; margin: 0 0 14px; padding-bottom: 8px; border-bottom: 2px solid var(--accent); color: #fff; }
h2 { font-size: 19px; margin: 28px 0 10px; color: #fff; }
h3 { font-size: 15.5px; margin: 20px 0 8px; color: #f0f6fc; }
h4 { font-size: 14px; margin: 16px 0 6px; color: #dce6f0; }
p { margin: 8px 0 12px; }
ul, ol { margin: 8px 0 14px; padding-left: 22px; }
li { margin: 4px 0; }
blockquote {
margin: 12px 0;
padding: 10px 14px;
background: rgba(224, 166, 59, 0.11);
border-left: 3px solid var(--warn);
border-radius: 0 4px 4px 0;
color: #f9e6be;
}
blockquote p { margin: 0; }
code {
font-family: Consolas, "Cascadia Code", monospace;
font-size: 12.5px;
padding: 1px 5px;
background: rgba(255, 255, 255, 0.08);
border-radius: 3px;
}
.code-wrap {
position: relative;
margin: 12px 0 16px;
}
pre {
margin: 0;
padding: 12px 14px;
overflow-x: auto;
background: var(--code-bg);
border: 1px solid var(--border);
border-radius: 5px;
}
pre code {
padding: 0;
background: none;
font-size: 12.5px;
line-height: 1.55;
}
.copy-btn {
position: absolute;
top: 6px;
right: 6px;
padding: 2px 8px;
font-size: 11px;
color: var(--dim);
background: var(--panel-alt);
border: 1px solid var(--border);
border-radius: 3px;
cursor: pointer;
}
.copy-btn:hover { color: #fff; border-color: rgba(255, 255, 255, 0.35); }
table {
width: 100%;
border-collapse: collapse;
margin: 12px 0 18px;
font-size: 13px;
}
th, td {
padding: 8px 10px;
text-align: left;
border: 1px solid var(--border);
vertical-align: top;
}
th { background: var(--panel-alt); color: #fff; font-weight: 600; }
hr { border: 0; border-top: 1px solid var(--border); margin: 20px 0; }
a { color: #79b8ff; }
@media print {
body { display: block; background: #fff; color: #111; }
aside.sidebar, .copy-btn { display: none !important; }
main.content { max-width: none; padding: 0; }
h1, h2, h3, h4, th { color: #000; }
h1 { border-bottom-color: #333; page-break-before: always; }
.chapter:first-child h1 { page-break-before: auto; }
pre, blockquote, th { background: #f6f8fa !important; color: #111 !important; border-color: #ccc !important; }
code { background: #f0f2f5; }
td, th { border-color: #ccc; }
}
</style>
</head>
<body>
<aside class="sidebar">
<div class="brand">${escapeHtml(pageTitle)}</div>
<div class="brand-sub">${escapeHtml(subtitle)}</div>
<div class="toolbar">
<a href="${switchHref}">${switchLabel}</a>
<button type="button" onclick="window.print()">${printLabel}</button>
</div>
<nav class="toc">
${navLinks}
</nav>
</aside>
<main class="content">
${sections}
</main>
<script>
for (const pre of document.querySelectorAll('pre')) {
const wrap = document.createElement('div');
wrap.className = 'code-wrap';
pre.parentNode.insertBefore(wrap, pre);
wrap.appendChild(pre);
const btn = document.createElement('button');
btn.type = 'button';
btn.className = 'copy-btn';
btn.textContent = ${JSON.stringify(copyLabel)};
btn.addEventListener('click', () => {
navigator.clipboard?.writeText(pre.innerText).then(() => {
btn.textContent = ${JSON.stringify(copiedLabel)};
setTimeout(() => { btn.textContent = ${JSON.stringify(copyLabel)}; }, 1200);
});
});
wrap.appendChild(btn);
}
</script>
</body>
</html>
`;
}
function renderMarkdown(source: string): string {
const lines = source.replace(/\r\n/g, '\n').split('\n');
const out: string[] = [];
let i = 0;
while (i < lines.length) {
const line = lines[i]!;
if (line.trim() === '') {
i += 1;
continue;
}
// Fenced code block.
const fence = /^```([A-Za-z0-9_-]*)/.exec(line);
if (fence) {
const codeLines: string[] = [];
i += 1;
while (i < lines.length && !lines[i]!.startsWith('```')) {
codeLines.push(lines[i]!);
i += 1;
}
if (i < lines.length) i += 1;
out.push(`<pre><code>${escapeHtml(codeLines.join('\n'))}</code></pre>`);
continue;
}
// Horizontal rule.
if (/^---+$/.test(line.trim())) {
out.push('<hr />');
i += 1;
continue;
}
// Headings.
const heading = /^(#{1,4})\s+(.+)$/.exec(line);
if (heading) {
const level = heading[1]!.length;
out.push(`<h${level}>${renderInline(heading[2]!)}</h${level}>`);
i += 1;
continue;
}
// Blockquote.
if (line.startsWith('>')) {
const quoteLines: string[] = [];
while (i < lines.length && lines[i]!.startsWith('>')) {
quoteLines.push(lines[i]!.replace(/^>\s?/, ''));
i += 1;
}
out.push(`<blockquote><p>${quoteLines.map(renderInline).join('<br />')}</p></blockquote>`);
continue;
}
// GFM table.
if (line.includes('|') && i + 1 < lines.length && /^\s*\|?[\s:-]+\|[\s|:-]*$/.test(lines[i + 1]!)) {
const headers = splitTableRow(line);
i += 2;
const rows: string[][] = [];
while (i < lines.length && lines[i]!.includes('|') && lines[i]!.trim() !== '') {
rows.push(splitTableRow(lines[i]!));
i += 1;
}
const thead = `<thead><tr>${headers.map((cell) => `<th>${renderInline(cell)}</th>`).join('')}</tr></thead>`;
const tbody = `<tbody>${rows.map((row) => `<tr>${row.map((cell) => `<td>${renderInline(cell)}</td>`).join('')}</tr>`).join('')}</tbody>`;
out.push(`<table>${thead}${tbody}</table>`);
continue;
}
// Unordered or ordered list.
if (/^\s*[-*]\s+/.test(line) || /^\s*\d+\.\s+/.test(line)) {
const ordered = /^\s*\d+\.\s+/.test(line);
const tag = ordered ? 'ol' : 'ul';
const items: string[] = [];
while (i < lines.length && (ordered ? /^\s*\d+\.\s+/.test(lines[i]!) : /^\s*[-*]\s+/.test(lines[i]!))) {
items.push(lines[i]!.replace(ordered ? /^\s*\d+\.\s+/ : /^\s*[-*]\s+/, ''));
i += 1;
}
out.push(`<${tag}>${items.map((item) => `<li>${renderInline(item)}</li>`).join('')}</${tag}>`);
continue;
}
// Paragraph.
const para: string[] = [];
while (
i < lines.length
&& lines[i]!.trim() !== ''
&& !lines[i]!.startsWith('#')
&& !lines[i]!.startsWith('```')
&& !lines[i]!.startsWith('>')
&& !/^---+$/.test(lines[i]!.trim())
&& !/^\s*[-*]\s+/.test(lines[i]!)
&& !/^\s*\d+\.\s+/.test(lines[i]!)
) {
para.push(lines[i]!);
i += 1;
}
out.push(`<p>${para.map(renderInline).join(' ')}</p>`);
}
return out.join('\n');
}
function splitTableRow(line: string): string[] {
return line.trim().replace(/^\|/, '').replace(/\|$/, '').split('|').map((cell) => cell.trim());
}
function renderInline(text: string): string {
const tokens: string[] = [];
let work = text.replace(/`([^`]+)`/g, (_m, code: string) => {
const idx = tokens.length;
tokens.push(`<code>${escapeHtml(code)}</code>`);
return `\u0000T${idx}\u0000`;
});
work = escapeHtml(work);
work = work.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2">$1</a>');
work = work.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
work = work.replace(/\u0000T(\d+)\u0000/g, (_m, idx: string) => tokens[Number(idx)] ?? '');
return work;
}
function escapeHtml(text: string): string {
return text
.replaceAll('&', '&amp;')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;')
.replaceAll('"', '&quot;');
}
if (process.argv[1] && resolve(process.argv[1]) === resolve(import.meta.filename)) {
const repo = resolve(import.meta.dirname, '..');
const outArgIdx = process.argv.indexOf('--out');
const outDir = outArgIdx >= 0 && process.argv[outArgIdx + 1]
? resolve(process.argv[outArgIdx + 1]!)
: join(repo, 'build', 'mod-dev-docs');
const result = buildOfflineModDocs(join(repo, 'mod-dev-docs'), outDir);
console.log('Generated offline mod docs:', result.zh, result.en);
}