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
import { docPathFromPathname, normalizeDocPath } from "./route.js";
const navEl = document.getElementById("nav");
const sidebarEl = document.getElementById("sidebar");
const contentEl = document.getElementById("content");
const themeToggle = document.querySelector(".theme-toggle");
// Theme toggle
function getPreferredTheme() {
const stored = localStorage.getItem("theme");
if (stored) return stored;
return window.matchMedia("(prefers-color-scheme: light)").matches ? "light" : "dark";
}
function applyTheme(theme) {
document.documentElement.setAttribute("data-theme", theme);
localStorage.setItem("theme", theme);
themeToggle?.setAttribute(
"aria-label",
theme === "dark" ? "Switch to light theme" : "Switch to dark theme",
);
}
applyTheme(getPreferredTheme());
themeToggle?.addEventListener("click", () => {
const current = document.documentElement.getAttribute("data-theme") || getPreferredTheme();
applyTheme(current === "dark" ? "light" : "dark");
});
const buildId = new URL(import.meta.url).searchParams.get("v") || "";
function withBuild(url) {
if (!buildId) return url;
const sep = url.includes("?") ? "&" : "?";
return `${url}${sep}v=${encodeURIComponent(buildId)}`;
}
function escapeHtml(text) {
return text
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('"', """)
.replaceAll("'", "'");
}
function getSelectedPath() {
const hash = (location.hash || "").replace(/^#/, "");
if (!hash) return null;
// Decode defensively so both literal (examples/index.md) and legacy
// percent-encoded (examples%2Findex.md) hashes resolve to the same doc.
let decoded = hash;
try {
decoded = decodeURIComponent(hash);
} catch {
// malformed escape — fall back to the raw hash
}
return normalizeDocPath(decoded);
}
function setSelectedPath(docPath) {
location.hash = normalizeDocPath(docPath);
}
async function fetchJson(path) {
const res = await fetch(withBuild(path), { cache: "no-store" });
if (!res.ok) throw new Error(`Failed to fetch ${path}: ${res.status}`);
return res.json();
}
async function fetchText(path) {
const res = await fetch(withBuild(path), { cache: "no-store" });
if (!res.ok) throw new Error(`Failed to fetch ${path}: ${res.status}`);
return res.text();
}
function renderNav(pages, activePath) {
if (!pages.length) {
navEl.innerHTML = "";
return;
}
navEl.innerHTML = pages
.filter((p) => normalizeDocPath(p.path) !== "index.md")
.map((p) => {
const path = normalizeDocPath(p.path);
const title = escapeHtml(p.title || path);
const current = activePath === path ? ` aria-current="page"` : "";
// Encode each path segment but keep the "/" separators literal, so
// subpath docs (examples/index.md) route correctly.
const href = path.split("/").map(encodeURIComponent).join("/");
return `<a href="#${href}"${current}>${title}</a>`;
})
.join("");
}
function slugify(text) {
return String(text)
.toLowerCase()
.trim()
.replace(/[^\w\s-]/g, "")
.replace(/\s+/g, "-")
.replace(/-+/g, "-");
}
function pageHref(docPath) {
return "#" + normalizeDocPath(docPath).split("/").map(encodeURIComponent).join("/");
}
function sidebarLabel(page) {
return normalizeDocPath(page.path) === "index.md" ? "Overview" : page.title || page.path;
}
// The left docs tree: top-level pages, examples expanded to their recipes, and
// (populated after the doc renders) the active page's own headings.
function renderSidebar(pages, activePath) {
const items = pages
.map((p) => {
const path = normalizeDocPath(p.path);
const active = path === activePath;
const kids = Array.isArray(p.children) ? p.children : [];
let html = `<li><a class="s-page${active ? " active" : ""}"${
active ? ' aria-current="page"' : ""
} href="${pageHref(path)}">${escapeHtml(sidebarLabel(p))}</a>`;
if (kids.length) {
html +=
`<ul class="s-children">` +
kids
.map((c) => {
const cp = normalizeDocPath(c.path);
const ca = cp === activePath;
return `<li><a class="s-child${ca ? " active" : ""}"${
ca ? ' aria-current="page"' : ""
} href="${pageHref(cp)}">${escapeHtml(c.title || cp)}</a>${
ca ? '<ul class="s-toc"></ul>' : ""
}</li>`;
})
.join("") +
`</ul>`;
} else if (active) {
html += `<ul class="s-toc"></ul>`;
}
return html + `</li>`;
})
.join("");
sidebarEl.innerHTML = `<ul class="s-list">${items}</ul>`;
}
// Fill the active page's heading anchors (skipped when a page has <2 headings,
// e.g. the recipe pages, whose place in the tree is enough).
function renderHeadingToc() {
const toc = sidebarEl.querySelector(".s-toc");
if (!toc) return;
const heads = [...contentEl.querySelectorAll("h2, h3")];
if (heads.length < 2) {
toc.remove();
return;
}
toc.innerHTML = heads
.map((h) => {
if (!h.id) h.id = slugify(h.textContent);
const sub = h.tagName === "H3" ? " s-toc-sub" : "";
return `<li><a class="s-toc-link${sub}" href="#" data-target="${h.id}">${escapeHtml(
h.textContent,
)}</a></li>`;
})
.join("");
}
// Heading anchors scroll in-page without touching location.hash (the hash is
// the SPA's doc route, so a real #id anchor would break navigation).
sidebarEl.addEventListener("click", (e) => {
const a = e.target?.closest?.("a[data-target]");
if (!a) return;
e.preventDefault();
const target = document.getElementById(a.getAttribute("data-target"));
if (!target) return;
// A heading can sit inside a closed <details>; scrollIntoView on a hidden
// element is a no-op, so open the ancestors first.
for (let d = target.closest("details"); d; d = d.parentElement?.closest("details")) {
d.open = true;
}
const reduce = matchMedia("(prefers-reduced-motion: reduce)").matches;
target.scrollIntoView({
behavior: reduce ? "auto" : "smooth",
block: "start",
});
});
function titleForPath(pages, path) {
for (const p of pages) {
if (normalizeDocPath(p.path) === path) return p.title || path;
for (const c of p.children || []) {
if (normalizeDocPath(c.path) === path) return c.title || path;
}
}
return path;
}
// Skip link: move focus to the content region without polluting the route hash.
document.querySelector(".skip-link")?.addEventListener("click", (e) => {
e.preventDefault();
contentEl.focus();
});
function installContentLinkHandler() {
contentEl.addEventListener("click", (e) => {
const a = e.target?.closest?.("a");
if (!a) return;
const href = a.getAttribute("href") || "";
if (
href.startsWith("http://") ||
href.startsWith("https://") ||
href.startsWith("mailto:") ||
href.startsWith("#")
) {
return;
}
// Route relative markdown links through the SPA.
if (href.endsWith(".md")) {
e.preventDefault();
setSelectedPath(href);
return;
}
});
}
async function main() {
// SPA fallback: convert pathname to hash route so deep links work
if (location.pathname !== "/" && !location.hash) {
location.replace("#" + docPathFromPathname(location.pathname));
return;
}
if (!globalThis.marked) {
contentEl.innerHTML = `<p class="empty">Markdown renderer failed to load.</p>`;
return;
}
installContentLinkHandler();
let manifest;
try {
manifest = await fetchJson("./manifest.json");
} catch (e) {
contentEl.innerHTML = `<p class="empty">Missing <code>manifest.json</code>. Deploy the site via CI.</p>`;
navEl.innerHTML = "";
console.error(e);
return;
}
const pages = Array.isArray(manifest.pages) ? manifest.pages : [];
const defaultPath = pages[0]?.path ? normalizeDocPath(pages[0].path) : null;
async function render(isNav) {
const activePath = getSelectedPath() || defaultPath;
renderNav(pages, activePath);
renderSidebar(pages, activePath);
if (!activePath) {
contentEl.innerHTML = `<p class="empty">No docs yet.</p>`;
return;
}
try {
const md = await fetchText(`./docs/${activePath}`);
const html = globalThis.marked.parse(md);
contentEl.innerHTML = html;
globalThis.Prism?.highlightAllUnder(contentEl);
applyProfileClientPreference(contentEl);
renderHeadingToc();
window.scrollTo(0, 0);
// On navigation, announce the new page and move focus into it so screen
// reader and keyboard users aren't stranded on stale/orphaned focus.
const liveEl = document.getElementById("a11y-live");
if (liveEl) liveEl.textContent = titleForPath(pages, activePath);
if (isNav) contentEl.focus();
} catch (e) {
contentEl.innerHTML = `<p class="empty">Failed to load <code>${escapeHtml(
activePath,
)}</code>.</p>`;
console.error(e);
}
}
window.addEventListener("hashchange", () => render(true));
// Seed the default route without firing hashchange — the synthetic event
// would run the isNav focus path and yank focus into #content on first load.
if (!getSelectedPath() && defaultPath) {
history.replaceState(null, "", pageHref(defaultPath));
}
await render(false);
}
main();
// atproto profile links honor the "open profiles in" preference (clients.js,
// shared across the zzstoatzz/zat.dev sites via the same localStorage key).
// Authors write plain bsky.app profile URLs in markdown; render tags them
// with data-profile-did so clients.js keeps them fresh on preference change.
function applyProfileClientPreference(root) {
if (!window.LeafletClients) return;
root.querySelectorAll('a[href^="https://bsky.app/profile/"]').forEach((a) => {
const id = a.href.slice("https://bsky.app/profile/".length).replace(/\/+$/, "");
if (!id) return;
a.setAttribute("data-profile-did", id);
a.href = window.LeafletClients.profileUrlFor(id);
});
}
// settings popover: where atproto identities open
(function initClientSettings() {
const btn = document.querySelector(".client-settings-toggle");
if (!btn || !window.LeafletClients) return;
const pop = document.getElementById("client-settings");
function renderOptions() {
const current = window.LeafletClients.getPreferredClient().value;
pop.innerHTML =
'<div class="client-settings-title">open profiles in</div>' +
window.LeafletClients.CLIENTS.map(
(c) =>
`<label class="client-option"><input type="radio" name="profile-client" value="${c.value}"${
c.value === current ? " checked" : ""
}/> ${c.label}</label>`,
).join("");
}
btn.addEventListener("click", (e) => {
e.stopPropagation();
renderOptions();
pop.hidden = !pop.hidden;
});
pop.addEventListener("change", (e) => {
if (e.target.name === "profile-client") window.LeafletClients.setPreferredClient(e.target.value);
});
document.addEventListener("click", (e) => {
if (!pop.hidden && !pop.contains(e.target)) pop.hidden = true;
});
})();