1234567const KINDS = [8 [/\b(release|version|bump|tag)\b/i, "accent", 1],9 [/\b(fix|bug|patch|issue|crash|error|regress|revert)\b/i, "accent-dim", 0.8],10 [/\b(add|new|implement|feat|introduce|wire|support)\b/i, "accent", 1],11 [12 /\b(refactor|restructure|reorganize|extract|move|rename|split|cleanup|clean up)\b/i,13 "text",14 0.85,15 ],16 [/\b(perf|optim|speed|fast|slow|cache|memory|alloc)\b/i, "accent", 0.9],17 [/\b(test|spec|coverage|assert)\b/i, "text-secondary", 0.74],18 [/\b(doc|readme|comment|example|guide)\b/i, "text-secondary", 0.7],19 [/\b(polish|style|format|lint|whitespace|typo|wording|copy)\b/i, "text-secondary", 0.66],20 [/\b(chore|deps|update|upgrade|build|ci|config)\b/i, "text-secondary", 0.62],21];22232425function timeline() {26 const svg = document.querySelector("svg.timeline");27 if (!svg) return;28 const css = getComputedStyle(document.documentElement);29 const saves = [...svg.querySelectorAll(".dot")]30 .map((dot) => {31 const [id, message, meta] = (dot.querySelector("title")?.textContent ?? "").split("\n");32 const [, color, alpha] = KINDS.find(([kind]) => kind.test(message)) ?? [33 null,34 "text-secondary",35 0.8,36 ];37 const fill = css.getPropertyValue(`--${color}`).trim();38 return { href: dot.getAttribute("href"), id, message, meta, fill, alpha, t: +dot.dataset.t };39 })40 .sort((a, b) => a.t - b.t);41 if (saves.length === 0) return;42 const canvas = document.createElement("canvas");43 canvas.className = "timeline-canvas";44 canvas.setAttribute("role", "img");45 canvas.setAttribute("aria-label", svg.getAttribute("aria-label"));46 svg.replaceWith(canvas);47 const ctx = canvas.getContext("2d");48 const tip = document.createElement("div");49 tip.className = "timeline-tip";50 tip.hidden = true;51 document.body.append(tip);52 const reduce = matchMedia("(prefers-reduced-motion: reduce)");53 let [width, height, strip, radius, offset] = [0, 0, 0, 0, 0];54 55 56 57 const spacing = (seconds) => radius + 8 + Math.min(96, 12 * Math.log2(1 + seconds / 3600));58 const resize = () => {59 width = canvas.parentElement.getBoundingClientRect().width;60 61 height = 64;62 canvas.width = Math.round(width * devicePixelRatio);63 canvas.height = Math.round(height * devicePixelRatio);64 canvas.style.width = `${width}px`;65 canvas.style.height = `${height}px`;66 ctx.setTransform(devicePixelRatio, 0, 0, devicePixelRatio, 0, 0);67 radius = 5;68 let x = 0;69 saves.forEach((save, i) => {70 if (i > 0) x += spacing(save.t - saves[i - 1].t);71 save.x = x;72 });73 74 strip = Math.max(x + spacing(Number.POSITIVE_INFINITY), width);75 offset = x - width * 0.82;76 };77 78 const onScreen = (x, margin) => {79 const shift = ((offset % strip) + strip) % strip;80 const copies = [];81 for (let sx = x - shift - strip; sx < width + margin; sx += strip) {82 if (sx > -margin) copies.push(sx);83 }84 return copies;85 };86 const hit = (event) => {87 const box = canvas.getBoundingClientRect();88 const [mx, my] = [event.clientX - box.left, event.clientY - box.top];89 if (Math.abs(my - height / 2) > radius + 7) return null;90 return (91 saves.find((save) => onScreen(save.x, 0).some((x) => Math.abs(mx - x) < radius + 7)) ?? null92 );93 };94 let [hovered, drag, dragFrom, downX, lastX, velocity, resumeAt, lastFrame] = [95 null,96 null,97 0,98 0,99 0,100 0,101 0,102 0,103 ];104 const hover = (save, event) => {105 if (save !== hovered) {106 hovered = save;107 tip.hidden = save === null;108 if (save)109 tip.replaceChildren(110 line("tip-id", save.id),111 line("tip-msg", save.message),112 line("tip-meta", save.meta),113 );114 }115 if (save) {116 const left = event.clientX + 14;117 tip.style.left = `${left + 340 > innerWidth ? Math.max(8, event.clientX - 354) : left}px`;118 tip.style.top = `${event.clientY - 10}px`;119 }120 canvas.style.cursor = save ? "pointer" : drag === null ? "grab" : "grabbing";121 };122 const draw = (time) => {123 const dt = lastFrame ? Math.min((time - lastFrame) / 1000, 0.1) : 0;124 lastFrame = time;125 if (drag === null && hovered === null) {126 if (Math.abs(velocity) > 0.5) {127 offset -= velocity;128 velocity *= 0.92;129 } else if (!reduce.matches && time >= resumeAt) offset += 20 * dt;130 }131 const y = height / 2;132 ctx.clearRect(0, 0, width, height);133 ctx.lineWidth = 1;134 ctx.globalAlpha = 0.7;135 ctx.strokeStyle = css.getPropertyValue("--text-muted");136 ctx.setLineDash([4, 4]);137 ctx.beginPath();138 ctx.moveTo(0, y);139 ctx.lineTo(width, y);140 ctx.stroke();141 ctx.setLineDash([]);142 ctx.font = '10px "Martian Mono", monospace';143 ctx.textAlign = "center";144 for (const save of saves) {145 for (const x of onScreen(save.x, 10)) {146 ctx.globalAlpha = hovered === null ? save.alpha : hovered === save ? 1 : save.alpha * 0.6;147 ctx.fillStyle = save.fill;148 ctx.beginPath();149 ctx.arc(x, y, radius, 0, Math.PI * 2);150 ctx.fill();151 if (hovered === save) {152 ctx.fillStyle = css.getPropertyValue("--accent");153 ctx.fillText(save.id.slice(0, 6), x, y - radius - 6);154 }155 }156 }157 ctx.globalAlpha = 1;158 requestAnimationFrame(draw);159 };160 canvas.addEventListener("pointerdown", (event) => {161 [drag, dragFrom, downX, lastX, velocity] = [162 event.clientX,163 offset,164 event.clientX,165 event.clientX,166 0,167 ];168 canvas.setPointerCapture(event.pointerId);169 });170 canvas.addEventListener("pointermove", (event) => {171 if (drag !== null) {172 offset = dragFrom - (event.clientX - drag);173 velocity = velocity * 0.6 + (event.clientX - lastX) * 0.4;174 lastX = event.clientX;175 }176 if (event.pointerType === "mouse") hover(hit(event), event);177 });178 const release = () => {179 drag = null;180 resumeAt = performance.now() + 900;181 };182 canvas.addEventListener("pointerup", (event) => {183 release();184 const save = Math.abs(event.clientX - downX) > 4 ? null : hit(event);185 if (save) location.href = save.href;186 });187 canvas.addEventListener("pointercancel", release);188 canvas.addEventListener("pointerleave", (event) => {189 if (drag === null) hover(null, event);190 });191 addEventListener("resize", resize);192 resize();193 requestAnimationFrame(draw);194}195196function line(className, text) {197 const div = document.createElement("div");198 div.className = className;199 div.textContent = text ?? "";200 return div;201}202203function copyButtons(root) {204 for (const button of root.querySelectorAll("button[data-copy]")) {205 const label = button.textContent;206 button.hidden = false;207 button.addEventListener("click", async () => {208 await navigator.clipboard.writeText(button.dataset.copy);209 button.textContent = "copied";210 button.classList.add("copied");211 setTimeout(() => {212 button.textContent = label;213 button.classList.remove("copied");214 }, 1400);215 });216 }217}218219220221222async function fetchMain(url, init) {223 try {224 const response = await fetch(url, init);225 const page = new DOMParser().parseFromString(await response.text(), "text/html");226 const main = page.querySelector("main");227 for (const link of main?.querySelectorAll("a[href]:not([href^='#'])") ?? []) {228 link.href = new URL(link.getAttribute("href"), response.url || url).href;229 }230 return main;231 } catch {232 return null;233 }234}235236237function modified(event) {238 return event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey;239}240241242243244245function panels() {246 const host = document.querySelector(".repo-panel");247 if (!host) return;248 let open = null;249 let shown = "";250 const load = async (url, init) => {251 shown = url;252 const main = await fetchMain(url, init);253 if (shown !== url) return;254 if (!main) {255 location.href = url;256 return;257 }258 main.querySelector(".breadcrumb")?.remove();259 main.querySelector(".file-page-title")?.remove();260 host.replaceChildren(...main.childNodes);261 copyButtons(host);262 host.hidden = false;263 };264 const inside = (url) => {265 const base = new URL(open.href).pathname;266 const { pathname } = new URL(url);267 return (pathname === base || pathname.startsWith(`${base}/`)) && !/\.[^/]*$/.test(pathname);268 };269 for (const tab of document.querySelectorAll(".repo-tab[data-panel]")) {270 tab.addEventListener("click", (event) => {271 if (modified(event)) return;272 event.preventDefault();273 if (open === tab && shown !== tab.href) {274 load(tab.href);275 return;276 }277 open?.classList.remove("active");278 if (open === tab) {279 open = null;280 shown = "";281 host.hidden = true;282 return;283 }284 open = tab;285 tab.classList.add("active");286 load(tab.href);287 });288 }289 host.addEventListener("click", (event) => {290 const link = event.target.closest("a[href]");291 if (!link || !open || modified(event) || link.hasAttribute("download")) return;292 if (!inside(link.href)) return;293 event.preventDefault();294 load(link.href);295 });296 host.addEventListener("submit", (event) => {297 const form = event.target;298 if (!open || !inside(form.action)) return;299 event.preventDefault();300 const method = form.method.toUpperCase();301 const data = new FormData(form);302 if (method === "GET") load(`${form.action}?${new URLSearchParams(data)}`);303 else load(form.action, { method, body: data });304 });305}306307308309function saveLists() {310 for (const list of document.querySelectorAll(".save-list")) {311 const observer = new IntersectionObserver(312 async ([entry]) => {313 const older = list.querySelector(".pager-older");314 if (!entry?.isIntersecting || !older) return;315 observer.disconnect();316 const main = await fetchMain(older.href);317 const next = main?.querySelector(`.save-list[data-list="${list.dataset.list}"]`);318 if (!next) return;319 next.querySelector(".pager a:not(.pager-older)")?.remove();320 list.querySelector(".pager").replaceWith(...next.childNodes);321 watch();322 },323 { root: list },324 );325 const watch = () => {326 const older = list.querySelector(".pager-older");327 if (older) observer.observe(older);328 };329 watch();330 }331}332333334function lineRanges() {335 const code = document.querySelector(".code");336 if (!code) return;337 let anchor = null;338 const mark = () => {339 for (const marked of code.querySelectorAll(".line.hl")) marked.classList.remove("hl");340 const match = /^#L(\d+)(?:-L(\d+))?$/.exec(location.hash);341 if (!match) return;342 const from = Number(match[1]);343 const to = Number(match[2] ?? match[1]);344 anchor = from;345 for (let n = Math.min(from, to); n <= Math.max(from, to); n++) {346 document.getElementById(`L${n}`)?.classList.add("hl");347 }348 document.getElementById(`L${Math.min(from, to)}`)?.scrollIntoView({ block: "center" });349 };350 code.addEventListener("click", (event) => {351 const link = event.target.closest(".ln");352 if (!link || !event.shiftKey || anchor === null) return;353 event.preventDefault();354 const n = Number(link.textContent);355 history.replaceState(null, "", `#L${Math.min(anchor, n)}-L${Math.max(anchor, n)}`);356 mark();357 });358 window.addEventListener("hashchange", mark);359 mark();360}361362363364function atlas() {365 const root = document.querySelector(".atlas");366 const filter = document.querySelector(".atlas-filter");367 if (!root || !filter) return;368 const panel = root.querySelector(".atlas-panel");369 const folders = [...root.querySelectorAll(".atlas-folder")];370 const files = [...root.querySelectorAll(".atlas-file")];371 372 root.style.height = `${root.offsetHeight}px`;373 root.style.overflowY = "hidden";374 const key = `kepr:atlas:${root.dataset.repo}`;375 const opened = new Set(remembered(key));376 377 const unfold = new URLSearchParams(location.search).get("open");378 const onPath = (path) => unfold !== null && `${unfold}/`.startsWith(`${path}/`);379 for (const folder of folders) {380 folder.open = opened.has(folder.dataset.path) || onPath(folder.dataset.path);381 folder.addEventListener("toggle", () => {382 if (filter.value.trim()) return;383 if (folder.open) opened.add(folder.dataset.path);384 else opened.delete(folder.dataset.path);385 remember(key, [...opened]);386 });387 }388 let selected = null;389 const show = (row) => {390 selected?.classList.remove("selected");391 selected = row;392 row.classList.add("selected");393 panel.replaceChildren(row.nextElementSibling.content.cloneNode(true));394 };395 for (const row of root.querySelectorAll(".atlas-row")) {396 row.addEventListener("pointerenter", (event) => {397 if (event.pointerType === "mouse") show(row);398 });399 row.addEventListener("focus", () => show(row));400 }401 402 const jump = (path) => {403 const row = path.endsWith("/")404 ? folders.find((folder) => `${folder.dataset.path}/` === path)?.firstElementChild405 : files.find((file) => file.dataset.path === path);406 if (!row) return false;407 for (const folder of folders) folder.open ||= path.startsWith(`${folder.dataset.path}/`);408 show(row);409 row.scrollIntoView({ block: "nearest" });410 return true;411 };412 panel.addEventListener("click", (event) => {413 const link = event.target.closest("a.atlas-jump");414 if (link && !modified(event) && jump(link.dataset.path)) event.preventDefault();415 });416 const viewer = fileViewer(root, jump);417 for (const file of files) {418 file.addEventListener("click", (event) => {419 if (modified(event)) return;420 event.preventDefault();421 viewer(file);422 });423 }424 const target = folders.find((folder) => folder.dataset.path === unfold)?.firstElementChild;425 if (target) {426 show(target);427 target.scrollIntoView({ block: "center" });428 }429 filter.addEventListener("input", () => {430 const query = filter.value.trim().toLowerCase();431 for (const file of files) file.hidden = query !== "" && !file.dataset.name.includes(query);432 for (const folder of folders) {433 folder.hidden = query !== "" && !folder.querySelector(".atlas-file:not([hidden])");434 folder.open = query !== "" || opened.has(folder.dataset.path);435 }436 });437 438 const fold = document.querySelector(".atlas-fold-btn");439 const label = () => {440 fold.textContent = folders.every((folder) => folder.open) ? "collapse all" : "expand all";441 };442 fold.addEventListener("click", () => {443 const open = !folders.every((folder) => folder.open);444 for (const folder of folders) folder.open = open;445 label();446 });447 for (const folder of folders) folder.addEventListener("toggle", label);448 label();449 fold.hidden = folders.length === 0;450 451 const search = document.querySelector(".atlas-search-btn");452 search.addEventListener("click", () => {453 search.hidden = true;454 filter.hidden = false;455 filter.focus();456 });457 filter.addEventListener("blur", () => {458 if (filter.value.trim() !== "") return;459 filter.hidden = true;460 search.hidden = false;461 });462 search.hidden = false;463 panel.hidden = false;464}465466467function atlasPicker() {468 const picker = document.querySelector(".atlas-picker");469 if (!picker) return;470 const filter = picker.querySelector(".atlas-picker-filter");471 const rows = [...picker.querySelectorAll(".atlas-picker-row")];472 filter.addEventListener("input", () => {473 const query = filter.value.trim().toLowerCase();474 for (const row of rows) row.hidden = query !== "" && !row.dataset.q.includes(query);475 });476 picker.addEventListener("toggle", () => {477 if (picker.open) filter.focus();478 });479 document.addEventListener("click", (event) => {480 if (!picker.contains(event.target)) picker.open = false;481 });482 picker.addEventListener("keydown", (event) => {483 if (event.key === "Escape") picker.open = false;484 });485 filter.hidden = false;486}487488489490491function fileViewer(root, jump) {492 let [row, size, wrap] = [null, 12, false];493 const overlay = element("div", "fv-overlay");494 overlay.tabIndex = -1;495 overlay.setAttribute("role", "dialog");496 overlay.setAttribute("aria-modal", "true");497 const close = () => {498 overlay.remove();499 row?.focus();500 row = null;501 };502 const step = (by) => {503 const rows = [...root.querySelectorAll(".atlas-file")].filter((file) => !file.hidden);504 const next = rows[rows.indexOf(row) + by];505 if (next) open(next);506 };507 const restyle = () => {508 overlay.style.setProperty("--fv-size", `${size}px`);509 overlay.classList.toggle("fv-wrap", wrap);510 };511 const open = async (file, url = file.href) => {512 row = file;513 const rows = [...root.querySelectorAll(".atlas-file")].filter((each) => !each.hidden);514 const index = rows.indexOf(file);515 const detail = file.nextElementSibling.content.cloneNode(true);516 const name = detail.querySelector(".atlas-info-name").textContent;517 const path = detail.querySelector(".atlas-info-path").textContent;518 const raw = new URL(file.href);519 raw.pathname = raw.pathname.replace(/^(\/[^/]+)\/files\//, "$1/raw/");520 const button = (text, action, className = "fv-ctrl-btn") => {521 const b = element("button", className, text);522 b.type = "button";523 b.addEventListener("click", action);524 return b;525 };526 const link = (text, download) => {527 const a = element("a", "fv-ctrl-btn", text);528 a.href = raw.href;529 if (download) a.download = name;530 return a;531 };532 const source = element("div", "fv-source", "loading…");533 const panel = element("aside", "fv-detail");534 panel.append(detail);535 const header = element("div", "fv-header");536 const title = element("div", "fv-title");537 title.append(element("span", "fv-name", name), element("span", "fv-path mono", path));538 const controls = element("div", "fv-controls mono");539 controls.append(540 button("A−", () => {541 size = Math.max(9, size - 1);542 restyle();543 }),544 button("A+", () => {545 size = Math.min(20, size + 1);546 restyle();547 }),548 button("⇌ wrap", (event) => {549 wrap = !wrap;550 event.currentTarget.classList.toggle("active", wrap);551 restyle();552 }),553 link("raw", false),554 link("download", true),555 );556 controls.children[2].classList.toggle("active", wrap);557 const nav = element("div", "fv-nav mono");558 const back = button("←", () => step(-1), "fv-ctrl-btn");559 const forward = button("→", () => step(1), "fv-ctrl-btn");560 back.disabled = index <= 0;561 forward.disabled = index >= rows.length - 1;562 nav.append(back, element("span", "fv-pos", `${index + 1}/${rows.length}`), forward);563 header.append(button("×", close, "fv-close"), title, controls, nav);564 const body = element("div", "fv-body");565 body.append(source, panel);566 overlay.replaceChildren(header, body);567 restyle();568 if (!overlay.isConnected) document.body.append(overlay);569 overlay.focus();570 const main = await fetchMain(url);571 if (row !== file) return;572 if (!main) {573 location.href = url;574 return;575 }576 for (const heading of main.querySelectorAll(".breadcrumb, .file-page-title")) heading.remove();577 main.querySelector(".file-meta:not(:last-child)")?.remove();578 source.replaceChildren(...main.childNodes);579 };580 overlay.addEventListener("keydown", (event) => {581 if (event.key === "Escape") close();582 else if (event.key === "ArrowLeft" || event.key === "ArrowRight") {583 event.preventDefault();584 step(event.key === "ArrowLeft" ? -1 : 1);585 }586 });587 588 overlay.addEventListener("click", (event) => {589 const link = event.target.closest(".fv-detail a.atlas-jump");590 if (!link || modified(event)) return;591 const path = link.dataset.path;592 const file = [...root.querySelectorAll(".atlas-file")].find((f) => f.dataset.path === path);593 event.preventDefault();594 if (file) open(file);595 else {596 close();597 jump(path);598 }599 });600 601 overlay.addEventListener("click", (event) => {602 const link = event.target.closest(".fv-source a[href]");603 if (!link || !row || modified(event)) return;604 if (new URL(link.href).pathname !== new URL(row.href).pathname) return;605 event.preventDefault();606 open(row, link.href);607 });608 return open;609}610611async function navbarLogin() {612 const link = document.querySelector('.nav-links a[href^="/sign-in"]');613 if (!link || !/(^|;\s*)kepr_editor=1(?:;|$)/.test(document.cookie)) return;614 try {615 const response = await fetch("/admin", { cache: "no-store" });616 if (!response.ok) return;617 const doc = new DOMParser().parseFromString(await response.text(), "text/html");618 const token = doc.querySelector('form[action="/admin/sign-out"] input[name="form"]');619 if (!token) return;620 const form = element("form", "nav-logout");621 form.method = "post";622 form.action = "/admin/sign-out";623 const button = element("button", "", "log out");624 button.type = "submit";625 form.append(token, button);626 form.addEventListener("submit", async (event) => {627 event.preventDefault();628 button.disabled = true;629 try {630 const result = await fetch(form.action, { method: "POST", body: new FormData(form) });631 if (!result.ok) throw new Error("Log out failed. Reload and try again.");632 location.href = "/";633 } catch (error) {634 button.disabled = false;635 button.textContent = "try log out again";636 console.error(error);637 }638 });639 const admin = element("a", "", "admin");640 admin.href = "/admin";641 link.replaceWith(admin, form);642 } catch (error) {643 console.error("Could not check navbar sign-in state", error);644 }645}646647function element(tag, className, text) {648 const node = document.createElement(tag);649 node.className = className;650 if (text !== undefined) node.textContent = text;651 return node;652}653654655656657658async function repoEditor() {659 const head = document.querySelector(".repo-head");660 if (!head || !/(^|;\s*)kepr_editor=1/.test(document.cookie)) return;661 const base = `/admin/repos/${location.pathname.split("/")[1]}`;662 const response = await fetch(`${base}/text`).catch(() => null);663 if (!response?.ok) return;664 const texts = await response.json();665 const details = document.querySelector(".repo-details");666 const places = [667 ["description", head.querySelector(".repo-desc"), head.querySelector(".repo-desc")],668 ["details", details, details.querySelector(".repo-details-body")],669 ];670 for (const [field, section, body] of places) {671 section.hidden = false;672 if (field === "description") {673 section.tabIndex = 0;674 section.setAttribute("role", "button");675 section.setAttribute("aria-label", "edit repository description");676 section.classList.add("repo-desc-editable");677 if (!section.textContent.trim()) section.textContent = "add a description";678 const activate = (event) => {679 if (event.target.closest(".editor") || body.querySelector(".editor")) return;680 event.preventDefault();681 editText(base, texts.form, field, body, texts[field]);682 };683 section.addEventListener("click", activate);684 section.addEventListener("keydown", (event) => {685 if (event.target === section && (event.key === "Enter" || event.key === " "))686 activate(event);687 });688 continue;689 }690 const button = element("button", "edit-btn mono", "edit");691 button.type = "button";692 (section.querySelector(".repo-details-head") ?? section).append(button);693 button.addEventListener("click", (event) => {694 event.preventDefault();695 if (!body.querySelector(".editor")) editText(base, texts.form, field, body, texts[field]);696 });697 }698}699700const MEDIA_MARKDOWN = /!\[([^\]]*)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)/g;701const MEDIA_TYPES = "image/png,image/jpeg,image/gif,image/webp,video/mp4,video/webm";702703function editText(base, form, field, body, text) {704 const kept = [...body.childNodes];705 if (field === "description") {706 body.removeAttribute("role");707 body.removeAttribute("tabindex");708 body.removeAttribute("aria-label");709 }710 const input = element("textarea", "editor-input mono");711 input.value = text;712 input.rows = field === "details" ? 16 : 3;713 const preview = element("div", `editor-preview${field === "details" ? " markdown" : ""}`);714 const media = element("div", "editor-media mono");715 const status = element("span", "editor-status");716 const post = (path, fields) => {717 const data = new FormData();718 data.append("form", form);719 for (const [name, value] of Object.entries(fields)) data.append(name, value);720 return fetch(`${base}/${path}`, { method: "POST", body: data });721 };722 let timer = null;723 const changed = () => {724 inspect();725 clearTimeout(timer);726 timer = setTimeout(async () => {727 const answer = await post("preview", { field, value: input.value }).catch(() => null);728 if (!answer?.ok) return;729 730 preview.innerHTML = input.value.trim() ? await answer.text() : "";731 preview.dataset.empty = input.value.trim() ? "" : "the README's words show here";732 }, 250);733 };734 const wrap = (before, after = before, fallback = "text") => {735 const [from, to] = [input.selectionStart, input.selectionEnd];736 const chosen = input.value.slice(from, to) || fallback;737 input.setRangeText(before + chosen + after, from, to);738 input.setSelectionRange(from + before.length, from + before.length + chosen.length);739 input.focus();740 changed();741 };742 const prefix = (mark) => {743 const start = input.value.lastIndexOf("\n", input.selectionStart - 1) + 1;744 input.setRangeText(mark, start, start, "end");745 input.focus();746 changed();747 };748 const upload = async (file) => {749 status.textContent = `uploading ${file.name}…`;750 const answer = await post("media", { file }).catch(() => null);751 if (!answer?.ok) {752 status.textContent = answer ? await answer.text() : "upload failed";753 return;754 }755 const { url } = await answer.json();756 const alt = file.name.replace(/\.[^.]+$/, "").replace(/[[\]]/g, "");757 input.setRangeText(758 `\n\n`,759 input.selectionStart,760 input.selectionEnd,761 "end",762 );763 status.textContent = "";764 input.focus();765 changed();766 };767 const picker = element("input", "");768 picker.type = "file";769 picker.accept = MEDIA_TYPES;770 picker.hidden = true;771 picker.addEventListener("change", () => {772 for (const file of picker.files) upload(file);773 picker.value = "";774 });775 776 const underCaret = () =>777 [...input.value.matchAll(MEDIA_MARKDOWN)].find(778 (m) => input.selectionStart >= m.index && input.selectionStart <= m.index + m[0].length,779 );780 function inspect() {781 const found = field === "details" ? underCaret() : undefined;782 media.hidden = !found;783 if (!found) return;784 const words = (found[3] ?? "").split(/\s+/).filter(Boolean);785 const width = words.find((word) => word.startsWith("width="))?.slice(6) ?? "100";786 const align = words.find((word) => /^(left|center|right)$/.test(word)) ?? "center";787 const loop = words.includes("loop");788 const video = /\.(mp4|webm)$/i.test(found[2]);789 const set = (next) => {790 const options = [`width=${next.width}`, next.align, next.loop && "loop"].filter(Boolean);791 const markdown = `![${found[1]}](${found[2]} "${options.join(" ")}")`;792 const caret = input.selectionStart;793 input.setRangeText(markdown, found.index, found.index + found[0].length);794 input.setSelectionRange(caret, caret);795 changed();796 };797 const choice = (label, active, action) => {798 const b = element("button", `fv-ctrl-btn${active ? " active" : ""}`, label);799 b.type = "button";800 b.addEventListener("click", action);801 return b;802 };803 media.replaceChildren(804 element("span", "editor-label", video ? "video" : "picture"),805 ...["25", "33", "50", "66", "75", "100"].map((w) =>806 choice(`${w}%`, w === width, () => set({ width: w, align, loop })),807 ),808 ...["left", "center", "right"].map((a) =>809 choice(a, a === align, () => set({ width, align: a, loop })),810 ),811 ...(video ? [choice("loop like a GIF", loop, () => set({ width, align, loop: !loop }))] : []),812 );813 }814 const save = async (value) => {815 status.textContent = "saving…";816 const answer = await post("text", { field, value }).catch(() => null);817 if (answer?.ok) location.reload();818 else status.textContent = answer ? await answer.text() : "not saved: offline?";819 };820 const cancel = () => {821 body.replaceChildren(...kept);822 if (field === "description") {823 body.tabIndex = 0;824 body.setAttribute("role", "button");825 body.setAttribute("aria-label", "edit repository description");826 body.focus();827 }828 };829 const tool = (label, title, action) => {830 const b = element("button", "fv-ctrl-btn", label);831 b.type = "button";832 b.title = title;833 b.addEventListener("click", action);834 return b;835 };836 const toolbar = element("div", "editor-toolbar mono");837 toolbar.append(838 tool("B", "bold (⌘B)", () => wrap("**")),839 tool("I", "italic (⌘I)", () => wrap("_")),840 tool("link", "link (⌘K)", () => wrap("[", "](https://)")),841 tool("code", "code", () => wrap("`")),842 );843 if (field === "details") {844 toolbar.append(845 tool("heading", "heading", () => prefix("## ")),846 tool("list", "list", () => prefix("- ")),847 tool("quote", "quote", () => prefix("> ")),848 tool("picture or video", "add a picture, GIF or video (or drop or paste one)", () =>849 picker.click(),850 ),851 picker,852 );853 input.addEventListener("dragover", (event) => event.preventDefault());854 input.addEventListener("drop", (event) => {855 if (event.dataTransfer.files.length === 0) return;856 event.preventDefault();857 for (const file of event.dataTransfer.files) upload(file);858 });859 input.addEventListener("paste", (event) => {860 const files = [...event.clipboardData.files];861 if (files.length === 0) return;862 event.preventDefault();863 for (const file of files) upload(file);864 });865 }866 input.addEventListener("input", changed);867 for (const name of ["click", "keyup"]) input.addEventListener(name, inspect);868 input.addEventListener("keydown", (event) => {869 const command = event.metaKey || event.ctrlKey;870 if (event.key === "Escape") cancel();871 else if (command && event.key === "Enter") save(input.value);872 else if (command && event.key === "b") wrap("**");873 else if (command && event.key === "i") wrap("_");874 else if (command && event.key === "k") wrap("[", "](https://)");875 else return;876 event.preventDefault();877 });878 const actions = element("div", "editor-actions mono");879 actions.append(880 tool("save", "save (⌘↵)", () => save(input.value)),881 tool("cancel", "cancel (esc)", cancel),882 tool("use the README", "clear your words and show the README's again", () => save("")),883 status,884 );885 const panes = element("div", "editor-panes");886 panes.append(input, preview);887 const editor = element("div", `editor editor-${field}`);888 editor.append(toolbar, panes, media, actions);889 body.replaceChildren(editor);890 input.focus();891 changed();892}893894895896function remembered(key) {897 try {898 const value = JSON.parse(localStorage.getItem(key) ?? "[]");899 return Array.isArray(value) && value.every((path) => typeof path === "string") ? value : [];900 } catch {901 return [];902 }903}904905function remember(key, value) {906 try {907 localStorage.setItem(key, JSON.stringify(value));908 } catch {}909}910911912913function hexGlow() {914 const columns = document.querySelectorAll(".hex-col");915 if (columns.length === 0) return;916 const reduce = matchMedia("(prefers-reduced-motion: reduce)");917 let timer = null;918 const update = () => {919 clearInterval(timer);920 for (const column of columns) column.classList.remove("glow");921 if (reduce.matches) return;922 timer = setInterval(() => {923 const column = columns[Math.floor(Math.random() * columns.length)];924 if (document.querySelectorAll(".hex-col.glow").length >= 3) return;925 column.classList.add("glow");926 setTimeout(() => column.classList.remove("glow"), 3200);927 }, 1500);928 };929 reduce.addEventListener("change", update);930 update();931}932933934935function tickerPace() {936 for (const track of document.querySelectorAll(".ticker-track")) {937 const speed = Number(getComputedStyle(track).getPropertyValue("--speed"));938 if (speed > 0) track.style.animationDuration = `${track.scrollWidth / 2 / speed}s`;939 }940}941942943document.fonts.ready.then(tickerPace);944timeline();945copyButtons(document);946panels();947saveLists();948atlasPicker();949repoEditor();950navbarLogin();951lineRanges();952atlas();953hexGlow();