~ knotless Search/
↑↓ move↵ open⇧↵ all results

zat.dev/zat

atproto utils for zig · mirror of https://tangled.org/zat.dev/zat

0
0
343 lines · 10.9 KB Raw History
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("<", "&lt;")
    .replaceAll(">", "&gt;")
    .replaceAll('"', "&quot;")
    .replaceAll("'", "&#039;");
}

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;
  });
})();