SPB Git

Repository Public

codeblock.js 3.4 KB 72 lines javascript

1// Code block components: single snippet, and multi-language tabs synced to the site-wide language preference.2import { $, h, LANGS, getLang, setLang, wireTabs, markTabs, copyButton } from "/assets/site/core.js";3import { highlight } from "/assets/site/highlight.js";45let uid = 0;67function pre(code, hl, label) {8  const codeEl = h("code", { html: highlight(code, hl) });9  return h("pre", { tabindex: "0", "aria-label": label }, codeEl);10}1112/** A single code block with a title bar and copy button. */13export function snippet(code, hl = "text", title = "") {14  const text = code.replace(/^\n+|\s+$/g, "");15  return h("div", { class: "code" },16    h("div", { class: "code-head" }, h("span", { class: "code-title" }, title || hl.toUpperCase()), copyButton(() => text)),17    pre(text, hl, title || "Code sample"));18}1920/**21 * Multi-language code block. `variants` = {curl?, python?, typescript?, swift?} (strings).22 * The selected tab follows the persisted site-wide language; a missing language falls back to the first one.23 */24export function codeTabs(variants, { label = "Code sample" } = {}) {25  const id = `code-${++uid}`;26  const langs = LANGS.filter((l) => typeof variants[l.id] === "string");27  const text = Object.fromEntries(langs.map((l) => [l.id, variants[l.id].replace(/^\n+|\s+$/g, "")]));28  let current = null;2930  const tablist = h("div", { class: "code-tabs", role: "tablist", "aria-label": `${label} — language` },31    langs.map((l) => h("button", { type: "button", class: "code-tab", role: "tab", id: `${id}-tab-${l.id}`,32      "aria-controls": `${id}-panel`, "aria-selected": "false", tabindex: "-1", dataset: { value: l.id } }, l.label)),33    h("span", { class: "tab-ink", "aria-hidden": "true" }));34  const panel = h("div", { role: "tabpanel", id: `${id}-panel` });35  const root = h("div", { class: "code", dataset: { codeTabs: "" } },36    h("div", { class: "code-head" }, tablist, copyButton(() => text[current])), panel);3738  function show(langId) {39    const lang = langs.find((l) => l.id === langId) || langs[0];40    if (!lang) return;41    current = lang.id;42    panel.setAttribute("aria-labelledby", `${id}-tab-${lang.id}`);43    panel.replaceChildren(pre(text[lang.id], lang.hl, `${label} (${lang.label})`));44    const tab = markTabs(tablist, lang.id);45    if (tab && tablist.scrollWidth > tablist.clientWidth) {46      tablist.scrollLeft = Math.max(0, tab.offsetLeft - 24);47    }48  }4950  wireTabs(tablist, (value) => setLang(value));51  document.addEventListener("mllm:lang", (e) => { if (root.isConnected) show(e.detail); });52  // The ink indicator needs layout: position once connected and on resize.53  const ro = new ResizeObserver(() => { if (current) markTabs(tablist, current); });54  ro.observe(tablist);55  show(getLang());56  return root;57}5859/** Replaces every <div data-sample="id"> under root using the given sample map. */60export function hydrateSamples(root, samples) {61  for (const el of root.querySelectorAll("[data-sample]")) {62    const s = samples[el.dataset.sample];63    if (!s) { el.textContent = `Missing sample: ${el.dataset.sample}`; continue; }64    el.replaceWith(codeTabs(s, { label: el.dataset.label || "Code sample" }));65  }66  for (const el of root.querySelectorAll("script[type='text/plain'][data-lang], template[data-lang]")) {67    const src = el.tagName === "TEMPLATE" ? el.content.textContent : el.textContent;68    el.replaceWith(snippet(src, el.dataset.lang, el.dataset.title || ""));69  }70}71export { $ };72
Files main
Menu

Theme