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
function contentUrl(contentBase, path) {
const clean = String(path || "").replace(/^\/+/, "");
return contentBase.replace(/\/?$/, "/") + clean;
}
function sortNum(a, b) {
return a - b;
}
function renderGraphs(root) {
if (typeof Viz !== "function") {
return;
}
for (const c of root.querySelectorAll("code.graphviz")) {
const p = document.createElement("p");
p.innerHTML = Viz(c.innerText, { format: "svg" });
p.className = "graph";
const pre = c.parentElement;
if (pre) {
pre.replaceWith(p);
}
}
}
function isRelativeResource(href) {
if (!href || href.charAt(0) === "#") {
return false;
}
if (href.charAt(0) === "/") {
return false;
}
if (/^[a-z][a-z0-9+.-]*:/i.test(href)) {
return false;
}
if (href.indexOf("//") === 0) {
return false;
}
if (href.charAt(0) === "?") {
return false;
}
return true;
}
function rewriteRelativeResources(root, contentBase) {
for (const img of root.querySelectorAll("img[src]")) {
const src = img.getAttribute("src");
if (src && isRelativeResource(src)) {
img.setAttribute("src", contentUrl(contentBase, src.replace(/^\.\//, "")));
}
}
}
function addLineNumbers(root) {
for (const block of root.querySelectorAll("code:not(.graphviz)")) {
const len = block.textContent.split("\n").length;
if (len <= 1) {
continue;
}
const lineref = [...Array(len).keys()].slice(1).join("\n");
const lineno = document.createElement("code");
lineno.className = "lineno";
lineno.textContent = lineref;
if (block.parentElement) {
block.parentElement.prepend(lineno);
}
}
}
function runWhenReady(tryFn, scriptId) {
try {
tryFn();
} catch (_ex) {
const script = document.querySelector("#" + scriptId);
if (script) {
script.addEventListener("load", tryFn);
}
}
}
async function loadmd(articleEl, contentBase, path) {
const converter = new showdown.Converter();
const resp = await fetch(contentUrl(contentBase, path));
if (!resp.ok) {
articleEl.innerHTML = "<p class=\"text-danger\">Failed to load article.</p>";
return;
}
const md = await resp.text();
articleEl.innerHTML = converter.makeHtml(md);
rewriteRelativeResources(articleEl, contentBase);
addLineNumbers(articleEl);
if (window.location.hash !== "") {
const target = articleEl.querySelector(window.location.hash);
if (target) {
target.scrollIntoView();
}
}
runWhenReady(() => {
if (typeof MathJax !== "undefined" && MathJax.typeset) {
MathJax.typeset();
}
}, "MathJax-script");
runWhenReady(() => {
if (typeof hljs !== "undefined" && hljs.highlightAll) {
hljs.highlightAll();
}
}, "Highlight-script");
runWhenReady(() => renderGraphs(articleEl), "GraphViz-script");
}
function archive(articleEl, manifest) {
const nestedByDate = {};
for (const item of manifest) {
const cdate = new Date(item.created);
const y = cdate.getFullYear();
const m = cdate.getMonth();
const d = cdate.getDate();
if (!nestedByDate[y]) {
nestedByDate[y] = {};
}
if (!nestedByDate[y][m]) {
nestedByDate[y][m] = {};
}
nestedByDate[y][m][d] = item;
}
let htmlStr = "";
let suffix = " open";
const dateOpts = { weekday: "long", year: "numeric", month: "long", day: "numeric" };
Object.keys(nestedByDate)
.sort(sortNum)
.reverse()
.forEach(function (y) {
htmlStr += `<blockquote><details${suffix}><summary>${y}</summary>`;
Object.keys(nestedByDate[y])
.sort(sortNum)
.reverse()
.forEach(function (m) {
const mName = new Date(2000, m, 1).toLocaleString("default", { month: "long" });
htmlStr += `<blockquote><details${suffix}><summary>${mName}</summary>`;
Object.keys(nestedByDate[y][m])
.sort(sortNum)
.reverse()
.forEach(function (d) {
const item = nestedByDate[y][m][d];
const dateStr = new Date(item.created).toLocaleString("default", dateOpts);
htmlStr += `<p>${dateStr}: <a href="${item.url}">${item.name}</a></p>`;
});
htmlStr += "</details></blockquote>";
suffix = "";
});
htmlStr += "</details></blockquote>";
});
articleEl.insertAdjacentHTML("beforeend", htmlStr);
}
function hideSearchResults(resultsEl) {
resultsEl.classList.remove("show");
}
function searchChange(searchEl, resultsEl, searchManifest) {
const s = searchEl.value;
resultsEl.innerHTML = "";
const q = s.toLowerCase();
for (const item of searchManifest) {
const name = String(item.name || "");
const tags = String(item.tags || "");
if (name.toLowerCase().includes(q) || tags.toLowerCase().includes(q)) {
const row = document.createElement("div");
row.className = "blog-search-result";
row.setAttribute("role", "option");
row.innerHTML =
`<div class="blog-search-result-title">${name}</div>` +
`<div class="blog-search-result-snippet">${tags}</div>` +
`<div class="blog-search-result-date">${item.created || ""}</div>`;
row.addEventListener("click", () => {
window.location.href = item.url;
});
resultsEl.appendChild(row);
}
}
resultsEl.classList.add("show");
}
async function populateManifest(contentBase, path) {
const resp = await fetch(contentUrl(contentBase, path));
if (!resp.ok) {
return [];
}
return await resp.json();
}
async function loadManifest(articleEl, contentBase, path) {
const manifest = await populateManifest(contentBase, path);
archive(articleEl, manifest);
return manifest;
}
function bindSearch(root, searchManifest) {
const searchEl = root.querySelector(".blog-search");
const resultsEl = root.querySelector(".blog-search-results");
const container = root.querySelector(".blog-search-container");
if (!searchEl || !resultsEl || !container) {
return;
}
searchEl.addEventListener("input", () => searchChange(searchEl, resultsEl, searchManifest));
document.addEventListener("keydown", (event) => {
if (event.key === "Escape") {
hideSearchResults(resultsEl);
}
});
document.addEventListener("click", (event) => {
if (!container.contains(event.target) && !resultsEl.contains(event.target)) {
hideSearchResults(resultsEl);
}
});
}
async function boot() {
const root = document.getElementById("blog-root");
const articleEl = document.getElementById("article");
if (!root || !articleEl) {
return;
}
const contentBase = root.dataset.contentBase || "";
const manifestPath = root.dataset.manifest || "articles/manifest.json";
const u = new URL(window.location.href);
const article = u.searchParams.get("article");
let searchManifest = [];
if (article) {
await loadmd(articleEl, contentBase, article);
searchManifest = await populateManifest(contentBase, manifestPath);
} else {
searchManifest = await loadManifest(articleEl, contentBase, manifestPath);
}
bindSearch(root, searchManifest);
}
boot();