SPB Git

Repository Public

core.js 10.5 KB 252 lines javascript

1/**2 * =============================================================================3 * SP BOUCHER | SOURCE FILE4 * =============================================================================5 * Project      : MacLustr LLM API6 * File         : web/assets/site/core.js7 * Author       : Simon-Pierre Boucher | https://spboucher.ai8 * Contact      : admin@spboucher.ai9 * Copyright    : (c) 2026 Simon-Pierre Boucher10 * License      : None specified (no license file in this repository)11 * =============================================================================12 * END OF SP BOUCHER SOURCE HEADER13 * =============================================================================14 */1516// Shared helpers for the public portal: DOM, storage, theme toggle, mobile nav, clipboard, status fetch.1718export const $ = (sel, root = document) => root.querySelector(sel);19export const $$ = (sel, root = document) => Array.from(root.querySelectorAll(sel));2021export function esc(value) {22  return String(value).replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);23}2425/** h("div", {class: "x", onclick: fn}, child, "text") — children are appended as nodes or text (never parsed as HTML). */26export function h(tag, attrs, ...children) {27  const el = document.createElement(tag);28  if (attrs) {29    for (const [k, v] of Object.entries(attrs)) {30      if (v === null || v === undefined || v === false) continue;31      if (k.startsWith("on") && typeof v === "function") el.addEventListener(k.slice(2), v);32      else if (k === "html") el.innerHTML = v; // trusted, authored markup only33      else if (k === "text") el.textContent = v;34      else if (k === "dataset") Object.assign(el.dataset, v);35      else el.setAttribute(k, v === true ? "" : v);36    }37  }38  for (const c of children.flat(Infinity)) {39    if (c === null || c === undefined || c === false) continue;40    el.append(c instanceof Node ? c : document.createTextNode(String(c)));41  }42  return el;43}4445function storage(kind) {46  return {47    get(key, fallback = null) {48      try { const v = window[kind].getItem(key); return v === null ? fallback : v; } catch { return fallback; }49    },50    set(key, value) { try { window[kind].setItem(key, value); } catch { /* unavailable (private mode) */ } },51    remove(key) { try { window[kind].removeItem(key); } catch { /* ignore */ } },52  };53}54export const local = storage("localStorage");55export const session = storage("sessionStorage");5657export const ICONS = {58  copy: '<svg class="i-copy" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="9" y="9" width="11" height="11" rx="2.5"/><path d="M5 15V6.5A2.5 2.5 0 0 1 7.500 4H15"/></svg>',59  check: '<svg class="i-check" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m5 12.5 4.500 4.500L19 7.500"/></svg>',60  alert: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 8v5"/><circle cx="12" cy="16.500" r=".6" fill="currentColor"/><path d="M10.300 3.900 2.600 17.400A2 2 0 0 0 4.300 20.400h15.400a2 2 0 0 0 1.700-3L13.700 3.900a2 2 0 0 0-3.400 0Z"/></svg>',61  info: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="9"/><path d="M12 11v5"/><circle cx="12" cy="7.800" r=".6" fill="currentColor"/></svg>',62};6364export async function copyText(text, button) {65  let ok = false;66  try {67    await navigator.clipboard.writeText(text);68    ok = true;69  } catch {70    const ta = h("textarea", { class: "sr-only", "aria-hidden": "true", tabindex: "-1" });71    ta.value = text;72    document.body.append(ta);73    ta.select();74    try { ok = document.execCommand("copy"); } catch { ok = false; }75    ta.remove();76  }77  if (button) {78    const label = button.querySelector("[data-label]");79    const original = label ? label.dataset.label : null;80    button.classList.toggle("copied", ok);81    if (label) label.textContent = ok ? "Copied" : "Copy failed";82    announce(ok ? "Copied to clipboard" : "Copy failed");83    clearTimeout(button._t);84    button._t = setTimeout(() => {85      button.classList.remove("copied");86      if (label) label.textContent = original;87    }, 1600);88  }89  return ok;90}9192export function copyButton(getText, label = "Copy") {93  const btn = h("button", { type: "button", class: "code-copy", "aria-label": "Copy to clipboard",94    html: `${ICONS.copy}${ICONS.check}<span data-label="${esc(label)}">${esc(label)}</span>` });95  btn.addEventListener("click", () => copyText(getText(), btn));96  return btn;97}9899let liveRegion;100export function announce(message) {101  if (!liveRegion) {102    liveRegion = h("div", { class: "sr-only", role: "status", "aria-live": "polite" });103    document.body.append(liveRegion);104  }105  liveRegion.textContent = "";106  setTimeout(() => { liveRegion.textContent = message; }, 30);107}108109export async function fetchJSON(url, { timeout = 8000, ...init } = {}) {110  const ctrl = new AbortController();111  const timer = setTimeout(() => ctrl.abort(), timeout);112  try {113    const res = await fetch(url, { ...init, signal: ctrl.signal, headers: { Accept: "application/json", ...(init.headers || {}) } });114    let body = null;115    try { body = await res.json(); } catch { body = null; }116    return { ok: res.ok, status: res.status, body, headers: res.headers };117  } finally {118    clearTimeout(timer);119  }120}121122/** Public status. Never throws: {state: "operational"|"unavailable"|"unreachable", data|null}. */123export async function getStatus() {124  try {125    const r = await fetchJSON("/api/status", { cache: "no-store" });126    if (!r.ok || !r.body || typeof r.body.status !== "string") return { state: "unreachable", data: null };127    return { state: r.body.status === "operational" ? "operational" : "unavailable", data: r.body };128  } catch {129    return { state: "unreachable", data: null };130  }131}132133export const STATUS_LABEL = {134  loading: "Checking status…",135  operational: "All systems operational",136  unavailable: "Inference unavailable",137  unreachable: "Status unreachable",138};139140export function fmtInt(n) {141  return typeof n === "number" && Number.isFinite(n) ? n.toLocaleString("en-US") : "—";142}143export function fmtNum(n, digits = 1) {144  return typeof n === "number" && Number.isFinite(n)145    ? n.toLocaleString("en-US", { minimumFractionDigits: digits, maximumFractionDigits: digits }) : "—";146}147export function fmtDate(iso) {148  if (typeof iso !== "string" || !/^\d{4}-\d{2}-\d{2}/.test(iso)) return "—";149  const [y, m, d] = iso.slice(0, 10).split("-").map(Number);150  return new Date(Date.UTC(y, m - 1, d)).toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric", timeZone: "UTC" });151}152153// ---- Preferred code language (persists across the site) ----154export const LANGS = [155  { id: "curl", label: "cURL", hl: "bash" },156  { id: "python", label: "Python", hl: "python" },157  { id: "typescript", label: "TypeScript", hl: "typescript" },158  { id: "swift", label: "Swift", hl: "swift" },159];160export function getLang() {161  const v = local.get("mllm-lang");162  return LANGS.some((l) => l.id === v) ? v : "curl";163}164export function setLang(id) {165  if (!LANGS.some((l) => l.id === id)) return;166  local.set("mllm-lang", id);167  document.dispatchEvent(new CustomEvent("mllm:lang", { detail: id }));168}169170// ---- Roving-tabindex tablist (ARIA tabs pattern, automatic activation) ----171export function wireTabs(tablist, onSelect) {172  const tabs = () => $$('[role="tab"]', tablist);173  tablist.addEventListener("click", (e) => {174    const tab = e.target.closest('[role="tab"]');175    if (tab && tablist.contains(tab)) onSelect(tab.dataset.value, tab);176  });177  tablist.addEventListener("keydown", (e) => {178    const list = tabs();179    const i = list.indexOf(document.activeElement);180    if (i < 0) return;181    let j = null;182    if (e.key === "ArrowRight" || e.key === "ArrowDown") j = (i + 1) % list.length;183    else if (e.key === "ArrowLeft" || e.key === "ArrowUp") j = (i - 1 + list.length) % list.length;184    else if (e.key === "Home") j = 0;185    else if (e.key === "End") j = list.length - 1;186    if (j === null) return;187    e.preventDefault();188    list[j].focus();189    onSelect(list[j].dataset.value, list[j]);190  });191}192export function markTabs(tablist, value) {193  let active = null;194  for (const tab of $$('[role="tab"]', tablist)) {195    const on = tab.dataset.value === value;196    tab.setAttribute("aria-selected", on ? "true" : "false");197    tab.tabIndex = on ? 0 : -1;198    if (on) active = tab;199  }200  const ink = $(".tab-ink", tablist);201  if (ink && active) {202    ink.style.transform = `translateX(${active.offsetLeft + 12}px) scaleX(${Math.max(1, active.offsetWidth - 24)})`;203  }204  return active;205}206207// ---- Page chrome: theme toggle, mobile nav ----208function initTheme() {209  const btn = $("[data-theme-toggle]");210  if (!btn) return;211  const sync = () => {212    const light = document.documentElement.getAttribute("data-theme") === "light";213    btn.setAttribute("aria-label", light ? "Switch to dark theme" : "Switch to light theme");214    btn.setAttribute("aria-pressed", light ? "true" : "false");215  };216  btn.addEventListener("click", () => {217    const next = document.documentElement.getAttribute("data-theme") === "light" ? "dark" : "light";218    document.documentElement.setAttribute("data-theme", next);219    local.set("mllm-theme", next);220    sync();221    document.dispatchEvent(new CustomEvent("mllm:theme", { detail: next }));222  });223  new MutationObserver(sync).observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme"] });224  sync();225}226227function initNav() {228  const btn = $("[data-menu-btn]");229  const nav = $("#site-nav");230  if (!btn || !nav) return;231  const set = (open) => {232    nav.classList.toggle("open", open);233    btn.setAttribute("aria-expanded", open ? "true" : "false");234    btn.setAttribute("aria-label", open ? "Close menu" : "Open menu");235  };236  btn.addEventListener("click", () => set(!nav.classList.contains("open")));237  document.addEventListener("keydown", (e) => {238    if (e.key === "Escape" && nav.classList.contains("open")) { set(false); btn.focus(); }239  });240  document.addEventListener("click", (e) => {241    if (nav.classList.contains("open") && !nav.contains(e.target) && !btn.contains(e.target)) set(false);242  });243  nav.addEventListener("click", (e) => { if (e.target.closest("a")) set(false); });244}245246export function initChrome() {247  initTheme();248  initNav();249  const year = $("[data-year]");250  if (year) year.textContent = String(new Date().getFullYear());251}252
Files main
Menu

Theme