-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathgen-docs.ts
More file actions
394 lines (344 loc) · 12 KB
/
gen-docs.ts
File metadata and controls
394 lines (344 loc) · 12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
// markdown-it 14.1.0 - https://github.com/markdown-it/markdown-it (MIT license)
// vendored in cmd/markdown-it.min.js from https://cdn.jsdelivr.net/npm/markdown-it@14.1.0/dist/markdown-it.min.js
// @ts-ignore
import MarkdownIt from "./markdown-it.min.js";
import {
readFileSync,
writeFileSync,
existsSync,
readdirSync,
mkdirSync,
rmSync,
statSync,
copyFileSync,
} from "node:fs";
import { join, resolve, extname } from "node:path";
import { commands as commandsDef } from "./gen-commands";
import { copyFileNormalized } from "./util.js";
const docsDir = "docs";
const mdDir = join(docsDir, "md");
const wwwOutDir = "docs-www";
const mdProcessed = new Map<string, string>();
const mdToProcess: string[] = [];
const searchJS = `<script>${readFileSync(join(docsDir, "gen_docs.search.js"), "utf-8")}</script>`;
const searchHTML = readFileSync(join(docsDir, "gen_docs.search.html"), "utf-8");
const tmplManual = readFileSync(join(docsDir, "manual.tmpl.html"), "utf-8");
const h1BreadcrumbsStart = `
<div class="breadcrumbs">
<div><a href="SumatraPDF-documentation.html">SumatraPDF documentation</a></div>
<div>/</div>
<div>`;
const h1BreadcrumbsEnd = `</div>
</div>
`;
function slugify(text: string): string {
return text
.toLowerCase()
.replace(/[^\w -]/g, "")
.replace(/ /g, "-");
}
function removeNotionId(s: string): string {
if (s.length <= 32) return s;
if (/^[0-9a-fA-F]{32}$/.test(s.slice(-32))) return s.slice(0, -32);
return s;
}
function getHTMLFileName(mdName: string): string {
const name = mdName.split("#")[0];
const base = name.replace(/\.md$/, "");
return removeNotionId(base).trim().replace(/ /g, "-") + ".html";
}
function parseCsv(text: string): string[][] {
const lines = text.trim().split("\n");
return lines.map((line) => {
const fields: string[] = [];
let cur = "";
let inQ = false;
for (let i = 0; i < line.length; i++) {
const ch = line[i];
if (inQ) {
if (ch === '"' && line[i + 1] === '"') {
cur += '"';
i++;
} else if (ch === '"') {
inQ = false;
} else {
cur += ch;
}
} else if (ch === '"') {
inQ = true;
} else if (ch === ",") {
fields.push(cur);
cur = "";
} else {
cur += ch;
}
}
fields.push(cur);
return fields;
});
}
function genCsvTableHTML(records: string[][]): string {
if (!records.length) return "";
const out: string[] = ['<table class="collection-content">'];
const hdr = records[0];
out.push("<thead>", "<tr>");
for (const c of hdr) out.push(`<th>${c}</th>`);
out.push("</tr>", "</thead>", "<tbody>");
for (let r = 1; r < records.length; r++) {
out.push("<tr>");
for (let i = 0; i < records[r].length; i++) {
const cell = records[r][i].trim();
if (!cell) {
out.push("<td>", "</td>");
continue;
}
out.push("<td>");
out.push(i <= 1 ? `<code>${cell}</code>` : cell);
out.push("</td>");
}
out.push("</tr>");
}
out.push("</tbody>", "</table>");
return out.join("\n");
}
// Replace :columns markers with HTML div tags.
// markdown-it with html:true will pass the divs through and parse
// the markdown between them normally.
function preProcess(text: string): string {
const lines = text.split("\n");
let inCols = false;
return lines
.map((line) => {
if (line.trim() === ":columns") {
if (!inCols) {
inCols = true;
return '\n<div class="doc-columns">\n';
} else {
inCols = false;
return "\n</div>\n";
}
}
return line;
})
.join("\n");
}
function getInlineText(token: MarkdownIt.Token): string {
if (!token.children) return token.content || "";
return token.children.map((t: MarkdownIt.Token) => t.content || "").join("");
}
function mdToHTML(name: string): string {
if (mdProcessed.has(name)) return mdProcessed.get(name)!;
const isMainPage = name === "SumatraPDF-documentation.md";
let text = readFileSync(join(mdDir, name), "utf-8");
// extract and remove first H1 line before conversion
let h1Text = "";
const h1Match = text.match(/^# (.+)$/m);
if (h1Match) {
h1Text = h1Match[1];
text = text.replace(/^# .+\n?/, "");
}
text = preProcess(text);
const md = new MarkdownIt({ html: true, typographer: true });
// use <div> for paragraphs (matching Go code's ParagraphTag: "div")
md.renderer.rules.paragraph_open = () => "<div>";
md.renderer.rules.paragraph_close = () => "</div>\n";
// render ```commands fenced blocks as CSV tables
md.renderer.rules.fence = (tokens: MarkdownIt.Token[], idx: number) => {
const t = tokens[idx];
if (t.info.trim() === "commands") return genCsvTableHTML(parseCsv(t.content));
return `<pre><code>${md.utils.escapeHtml(t.content)}</code></pre>\n`;
};
md.renderer.rules.heading_open = (tokens: MarkdownIt.Token[], idx: number) => {
const tok = tokens[idx];
const text = getInlineText(tokens[idx + 1]);
const id = slugify(text);
return `<${tok.tag} id="${id}">`;
};
md.renderer.rules.heading_close = (tokens: MarkdownIt.Token[], idx: number) => {
const tok = tokens[idx];
const text = getInlineText(tokens[idx - 1]);
const id = slugify(text);
return `<a class="hlink" href="#${id}"> # </a></${tok.tag}>\n`;
};
// rewrite links: .md → .html, external links get target="_blank"
md.renderer.rules.link_open = (tokens: MarkdownIt.Token[], idx: number, options: any, _env: any, self: any) => {
const tok = tokens[idx];
let href = tok.attrGet("href") ?? "";
const isExternal =
(href.startsWith("https://") || href.startsWith("http://")) && !href.includes("sumatrapdfreader.org");
if (isExternal) {
tok.attrSet("target", "_blank");
}
if (!href.startsWith("https://") && !href.startsWith("http://") && !href.startsWith("mailto:")) {
const decoded = href.replace(/%20/g, " ");
const hashIdx = decoded.indexOf("#");
const fileName = hashIdx >= 0 ? decoded.slice(0, hashIdx) : decoded;
const hash = hashIdx >= 0 ? decoded.slice(hashIdx + 1) : "";
const ext = extname(fileName).toLowerCase();
if (ext === ".md") {
if (!existsSync(join(mdDir, fileName))) {
throw new Error(`linked markdown file '${fileName}' not found`);
}
mdToProcess.push(fileName);
let dest = getHTMLFileName(fileName);
if (hash) dest += "#" + hash;
tok.attrSet("href", dest);
}
}
return self.renderToken(tokens, idx, options);
};
// validate image references exist
md.renderer.rules.image = (tokens: MarkdownIt.Token[], idx: number, options: any, _env: any, self: any) => {
const tok = tokens[idx];
const src = tok.attrGet("src") ?? "";
if (!src.startsWith("https://") && !src.startsWith("http://")) {
const decoded = src.replace(/%20/g, " ");
if (!existsSync(join(mdDir, decoded))) {
throw new Error(`image '${decoded}' not found in ${mdDir}`);
}
tok.attrSet("src", decoded);
}
return self.renderToken(tokens, idx, options);
};
let innerHTML = md.render(text);
// add breadcrumbs at start and end for non-main pages
if (h1Text && !isMainPage) {
const bc = h1BreadcrumbsStart + h1Text + h1BreadcrumbsEnd;
innerHTML = bc + innerHTML + `<div> </div>` + bc;
}
innerHTML = `<div class="notion-page">${innerHTML}</div>`;
let html = tmplManual.replace("{{InnerHTML}}", innerHTML);
const title = getHTMLFileName(name).replace(".html", "").replace(/-/g, " ");
html = html.replace("{{Title}}", title);
if (name === "Commands.md") {
html = html.replace("<div>:search:</div>", searchHTML);
html = html.replace("</body>", searchJS + "</body>");
}
mdProcessed.set(name, html);
return html;
}
function removeHTMLFiles(dir: string): void {
if (!existsSync(dir)) return;
for (const entry of readdirSync(dir)) {
if (entry.endsWith(".html")) {
rmSync(join(dir, entry));
}
}
}
function copyDirRecursive(dst: string, src: string): void {
mkdirSync(dst, { recursive: true });
for (const entry of readdirSync(src, { withFileTypes: true })) {
const s = join(src, entry.name);
const d = join(dst, entry.name);
if (entry.isDirectory()) {
copyDirRecursive(d, s);
} else {
copyFileSync(s, d);
}
}
}
function writeDocsHtmlFiles(): void {
const imgOutDir = join(wwwOutDir, "img");
rmSync(imgOutDir, { recursive: true, force: true });
mkdirSync(imgOutDir, { recursive: true });
removeHTMLFiles(wwwOutDir);
for (const [name, html] of mdProcessed) {
const htmlName = name.replace(".md", ".html");
const path = join(wwwOutDir, htmlName);
writeFileSync(path, html);
//console.log(`wrote '${path}'`);
}
copyDirRecursive(join(wwwOutDir, "img"), join(mdDir, "img"));
const htmlFiles = ["sumatra.css", "gen_toc.js", "favicon.ico"];
for (const name of htmlFiles) {
const srcPath = join("docs", name);
const dstPath = join(wwwOutDir, name);
copyFileNormalized(dstPath, srcPath);
}
}
function extractCommandsFromMarkdown(): string[] {
const lines = readFileSync(join(mdDir, "Commands.md"), "utf-8").split("\n");
const cmds: string[] = [];
for (const line of lines) {
if (!line.startsWith("Cmd")) continue;
const idx = line.indexOf(",");
if (idx >= 0) cmds.push(line.slice(0, idx));
}
if (cmds.length < 20) throw new Error(`too few commands in Commands.md: ${cmds.length}`);
return cmds;
}
function getCommandNames(): string[] {
const names: string[] = [];
for (let i = 0; i < commandsDef.length; i += 2) {
names.push(commandsDef[i]);
}
return names;
}
function checkCommandsAreDocumented(): void {
console.log("checkCommandsAreDocumented");
const srcCmds = getCommandNames();
console.log(`${srcCmds.length} commands in gen-commands.ts`);
const docCmds = extractCommandsFromMarkdown();
// special-case: remove old name which is still documented but not present in code
let idx = docCmds.indexOf("CmdOpen");
docCmds.splice(idx, 1);
console.log(`${docCmds.length} commands in Commands.md`);
const docSet = new Set(docCmds);
const onlyInSrc: string[] = [];
for (const cmd of srcCmds) {
if (docSet.has(cmd)) {
docSet.delete(cmd);
} else {
onlyInSrc.push(cmd);
}
}
if (onlyInSrc.length > 0) {
console.log(`${onlyInSrc.length} in gen-commands.ts but not Commands.md:`);
for (const c of onlyInSrc) console.log(` ${c}`);
}
if (docSet.size > 0) {
console.log(`${docSet.size} in Commands.md but not in gen-commands.ts:`);
for (const c of docSet) console.log(` ${c}`);
}
}
function formatSize(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
export async function main() {
const timeStart = performance.now();
console.log("genHTMLDocsFromMarkdown starting");
// process starting from the main page, following links
mdToHTML("SumatraPDF-documentation.md");
while (mdToProcess.length > 0) {
const name = mdToProcess.shift()!;
mdToHTML(name);
}
writeDocsHtmlFiles();
// create lzsa archive
const makeLzsa = resolve(join("bin", "MakeLZSA.exe"));
if (!existsSync(makeLzsa)) {
throw new Error(`'${makeLzsa}' doesn't exist`);
}
const archive = join("docs", "manual.dat");
rmSync(archive, { force: true });
const proc = Bun.spawn([makeLzsa, archive, wwwOutDir], {
stdout: "inherit",
stderr: "inherit",
});
const exitCode = await proc.exited;
if (exitCode !== 0) {
throw new Error(`MakeLZSA failed with exit code ${exitCode}`);
}
const size = statSync(archive).size;
console.log(`size of '${archive}': ${formatSize(size)}`);
const absDir = resolve(wwwOutDir);
console.log(`To view, open: file://${join(absDir, "SumatraPDF-documentation.html")}`);
checkCommandsAreDocumented();
const elapsed = ((performance.now() - timeStart) / 1000).toFixed(1);
console.log(`genHTMLDocsFromMarkdown finished in ${elapsed}s`);
}
if (import.meta.main) {
await main();
}