forked from gitgitgadget/gitgitgadget.github.io
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraphviz-ssr.js
More file actions
executable file
·48 lines (45 loc) · 1.88 KB
/
graphviz-ssr.js
File metadata and controls
executable file
·48 lines (45 loc) · 1.88 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
#!/usr/bin/env node
import { readFileSync, writeFileSync } from "node:fs"
import { parse } from "node-html-parser"
import Viz from "../static/js/viz-global.js"
/*
* This script post-processes the site as generated via Hugo, replacing the
* `<pre class="graphviz">` elements with inline `<svg>` ones, pre-rendered
* via `viz-js`.
*/
;(async () => {
for (const { Path: pathInPublic } of JSON.parse(readFileSync("public/diagram-list.json", "utf-8"))) {
const path = `public${pathInPublic}.html`
const contents = readFileSync(path, "utf-8")
// `node-html-parser` can misparse unquoted URLs ending in `/` (e.g. `href=../architecture/`)
// and rewrite links as empty anchors. Quote these attribute values before parsing.
const normalized = contents.replace(/\b(href|src)=([^"'`\s>]+)/g, '$1="$2"')
const html = parse(normalized)
const vizImport = html.querySelector('script[src$="viz-global.js"]')
if (!vizImport) {
console.error(`No 'viz-global.js' import found in ${path}; skipping`)
continue
}
vizImport.nextElementSibling.remove() // remove the inline script
vizImport.remove() // remove the import
for (const pre of html.querySelectorAll("pre.graphviz")) {
const engine = pre.getAttribute("engine") || "dot"
const svg = (await Viz.instance()).renderString(pre.textContent, {
format: "svg",
graphAttributes: {
bgcolor: "transparent",
},
engine,
})
const alt = pre.getAttribute("alt")
const altAttr = !alt ? '' : ` alt='${alt.replaceAll("&", "&").replaceAll("'", "'")}'`
const dataURL = `data:image/svg+xml;base64,${Buffer.from(svg).toString("base64")}`
pre.replaceWith(`<img${altAttr} src="${dataURL}" />`)
}
console.log(`Rewriting ${path}`)
writeFileSync(`${path}`, html.toString())
}
})().catch((e) => {
console.error(e)
process.exitCode = 1
})