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 `${title}`; }) .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 = `
  • ${escapeHtml(sidebarLabel(p))}`; if (kids.length) { html += ``; } else if (active) { html += ``; } return html + `
  • `; }) .join(""); sidebarEl.innerHTML = ``; } // 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 `
  • ${escapeHtml( h.textContent, )}
  • `; }) .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
    ; 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 = `

    Markdown renderer failed to load.

    `; return; } installContentLinkHandler(); let manifest; try { manifest = await fetchJson("./manifest.json"); } catch (e) { contentEl.innerHTML = `

    Missing manifest.json. Deploy the site via CI.

    `; 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 = `

    No docs yet.

    `; 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 = `

    Failed to load ${escapeHtml( activePath, )}.

    `; 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 = '
    open profiles in
    ' + window.LeafletClients.CLIENTS.map( (c) => ``, ).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; }); })();