kepr.js

35.8 KB · raw

1// Kepr's browser islands (§18). Every page is complete without this file; it only adds the2// ticker's pace, the drifting timeline, copy buttons, the inline panels, history's scrolling,3// line-range highlighting, the Atlas panel, picker, filter and file viewer, the signed-in4// editor, the phone nav menu, and the profile's visibility pause.56// Kepr 2's save kinds (canvas.js), first match wins: each dot's colour and strength.7const 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];22// Kepr 2's timeline (canvas.js keprThread): the saves on a strip that drifts slowly and loops.23// Hovering pauses it and shows the save, dragging scrubs, a click opens the save. Under reduced24// motion it moves only when dragged, and it draws only while on screen. The saves are fetched25// once the page has drawn; the SVG's plain dots stand in until then.26async function timeline() {27	const svg = document.querySelector("svg.timeline");28	if (!svg) return;29	const response = await fetch(svg.dataset.src);30	if (!response.ok) return;31	const repo = svg.dataset.src.split("/")[1];32	const css = getComputedStyle(document.documentElement);33	const saves = (await response.json())34		.map(({ id, t, message, meta }) => {35			const [, color, alpha] = KINDS.find(([kind]) => kind.test(message)) ?? [36				null,37				"text-secondary",38				0.8,39			];40			const fill = css.getPropertyValue(`--${color}`).trim();41			return { href: `/${repo}/saves/${id}`, id, message, meta, fill, alpha, t };42		})43		.sort((a, b) => a.t - b.t);44	if (saves.length === 0) return;45	const canvas = document.createElement("canvas");46	canvas.className = "timeline-canvas";47	canvas.setAttribute("role", "img");48	canvas.setAttribute("aria-label", svg.getAttribute("aria-label"));49	svg.replaceWith(canvas);50	const ctx = canvas.getContext("2d");51	const tip = document.createElement("div");52	tip.className = "timeline-tip";53	tip.hidden = true;54	document.body.append(tip);55	const reduce = matchMedia("(prefers-reduced-motion: reduce)");56	let [width, height, strip, radius, offset] = [0, 0, 0, 0, 0];57	// Laid out by time, a repo's bursts sat between long empty stretches the drift crawled58	// through. Each dot instead sits after the one before by the gap between them, on a log scale59	// and capped, so a busy day stays tight and a quiet month reads as a pause, not a wait.60	const spacing = (seconds) => radius + 8 + Math.min(96, 12 * Math.log2(1 + seconds / 3600));61	const resize = () => {62		width = canvas.parentElement.getBoundingClientRect().width;63		// Kepr 2's band was tall to hold two lanes; with one line, only room for the dots and label.64		height = 64;65		canvas.width = Math.round(width * devicePixelRatio);66		canvas.height = Math.round(height * devicePixelRatio);67		canvas.style.width = `${width}px`;68		canvas.style.height = `${height}px`;69		ctx.setTransform(devicePixelRatio, 0, 0, devicePixelRatio, 0, 0);70		radius = 5;71		let x = 0;72		saves.forEach((save, i) => {73			if (i > 0) x += spacing(save.t - saves[i - 1].t);74			save.x = x;75		});76		// The seam is one more capped pause, or the rest of the view when the saves are few.77		strip = Math.max(x + spacing(Number.POSITIVE_INFINITY), width);78		offset = x - width * 0.82;79	};80	// Every visible copy of each x on the looping strip.81	const onScreen = (x, margin) => {82		const shift = ((offset % strip) + strip) % strip;83		const copies = [];84		for (let sx = x - shift - strip; sx < width + margin; sx += strip) {85			if (sx > -margin) copies.push(sx);86		}87		return copies;88	};89	const hit = (event) => {90		const box = canvas.getBoundingClientRect();91		const [mx, my] = [event.clientX - box.left, event.clientY - box.top];92		if (Math.abs(my - height / 2) > radius + 7) return null;93		return (94			saves.find((save) => onScreen(save.x, 0).some((x) => Math.abs(mx - x) < radius + 7)) ?? null95		);96	};97	let [hovered, drag, dragFrom, downX, lastX, velocity, resumeAt, lastFrame] = [98		null,99		null,100		0,101		0,102		0,103		0,104		0,105		0,106	];107	const hover = (save, event) => {108		if (save !== hovered) {109			hovered = save;110			tip.hidden = save === null;111			if (save)112				tip.replaceChildren(113					line("tip-id", save.id),114					line("tip-msg", save.message),115					line("tip-meta", save.meta),116				);117		}118		if (save) {119			const left = event.clientX + 14;120			tip.style.left = `${left + 340 > innerWidth ? Math.max(8, event.clientX - 354) : left}px`;121			tip.style.top = `${event.clientY - 10}px`;122		}123		canvas.style.cursor = save ? "pointer" : drag === null ? "grab" : "grabbing";124	};125	const draw = (time) => {126		const dt = lastFrame ? Math.min((time - lastFrame) / 1000, 0.1) : 0;127		lastFrame = time;128		if (drag === null && hovered === null) {129			if (Math.abs(velocity) > 0.5) {130				offset -= velocity;131				velocity *= 0.92;132			} else if (!reduce.matches && time >= resumeAt) offset += 20 * dt;133		}134		const y = height / 2;135		ctx.clearRect(0, 0, width, height);136		ctx.lineWidth = 1;137		ctx.globalAlpha = 0.7;138		ctx.strokeStyle = css.getPropertyValue("--text-muted");139		ctx.setLineDash([4, 4]);140		ctx.beginPath();141		ctx.moveTo(0, y);142		ctx.lineTo(width, y);143		ctx.stroke();144		ctx.setLineDash([]);145		ctx.font = '10px "Martian Mono", monospace';146		ctx.textAlign = "center";147		for (const save of saves) {148			for (const x of onScreen(save.x, 10)) {149				ctx.globalAlpha = hovered === null ? save.alpha : hovered === save ? 1 : save.alpha * 0.6;150				ctx.fillStyle = save.fill;151				ctx.beginPath();152				ctx.arc(x, y, radius, 0, Math.PI * 2);153				ctx.fill();154				if (hovered === save) {155					ctx.fillStyle = css.getPropertyValue("--accent");156					ctx.fillText(save.id.slice(0, 6), x, y - radius - 6);157				}158			}159		}160		ctx.globalAlpha = 1;161		if (visible) requestAnimationFrame(draw);162		else drawing = false;163	};164	canvas.addEventListener("pointerdown", (event) => {165		[drag, dragFrom, downX, lastX, velocity] = [166			event.clientX,167			offset,168			event.clientX,169			event.clientX,170			0,171		];172		canvas.setPointerCapture(event.pointerId);173	});174	canvas.addEventListener("pointermove", (event) => {175		if (drag !== null) {176			offset = dragFrom - (event.clientX - drag);177			velocity = velocity * 0.6 + (event.clientX - lastX) * 0.4;178			lastX = event.clientX;179		}180		if (event.pointerType === "mouse") hover(hit(event), event);181	});182	const release = () => {183		drag = null;184		resumeAt = performance.now() + 900;185	};186	canvas.addEventListener("pointerup", (event) => {187		release();188		const save = Math.abs(event.clientX - downX) > 4 ? null : hit(event);189		if (save) location.href = save.href;190	});191	canvas.addEventListener("pointercancel", release);192	canvas.addEventListener("pointerleave", (event) => {193		if (drag === null) hover(null, event);194	});195	addEventListener("resize", resize);196	resize();197	// Off screen, the loop stops; it starts again, without a jump, when the strip scrolls back.198	let [visible, drawing] = [true, false];199	new IntersectionObserver(([entry]) => {200		visible = entry.isIntersecting;201		if (visible && !drawing) {202			drawing = true;203			lastFrame = 0;204			requestAnimationFrame(draw);205		}206	}).observe(canvas);207}208209function line(className, text) {210	const div = document.createElement("div");211	div.className = className;212	div.textContent = text ?? "";213	return div;214}215216function copyButtons(root) {217	for (const button of root.querySelectorAll("button[data-copy]")) {218		const label = button.textContent;219		button.hidden = false;220		button.addEventListener("click", async () => {221			await navigator.clipboard.writeText(button.dataset.copy);222			button.textContent = "copied";223			button.classList.add("copied");224			setTimeout(() => {225				button.textContent = label;226				button.classList.remove("copied");227			}, 1400);228		});229	}230}231232// A Kepr page's <main>, its links made absolute so they point where they did on their own page233// (after any redirect). An error page's <main> comes back too, so a refused form shows why; null if234// nothing came back, and the caller then goes to the page itself.235async function fetchMain(url, init) {236	try {237		const response = await fetch(url, init);238		const page = new DOMParser().parseFromString(await response.text(), "text/html");239		const main = page.querySelector("main");240		for (const link of main?.querySelectorAll("a[href]:not([href^='#'])") ?? []) {241			link.href = new URL(link.getAttribute("href"), response.url || url).href;242		}243		return main;244	} catch {245		return null;246	}247}248249// A click the browser should handle itself: a new tab or window, or a download.250function modified(event) {251	return event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey;252}253254// §21.9's panels open inline under the tabs, as Kepr 2's did: the panel page without its heading.255// The panel's own pages (an issue, the report form) and its forms stay inside it; a link elsewhere,256// or to a file (a download), navigates. The open tab takes the panel back to its first page, and257// closes it from there.258function panels() {259	const host = document.querySelector(".repo-panel");260	if (!host) return;261	let open = null;262	let shown = "";263	const load = async (url, init) => {264		shown = url;265		const main = await fetchMain(url, init);266		if (shown !== url) return;267		if (!main) {268			location.href = url;269			return;270		}271		main.querySelector(".breadcrumb")?.remove();272		main.querySelector(".file-page-title")?.remove();273		host.replaceChildren(...main.childNodes);274		copyButtons(host);275		host.hidden = false;276	};277	const inside = (url) => {278		const base = new URL(open.href).pathname;279		const { pathname } = new URL(url);280		return (pathname === base || pathname.startsWith(`${base}/`)) && !/\.[^/]*$/.test(pathname);281	};282	for (const tab of document.querySelectorAll(".repo-tab[data-panel]")) {283		tab.addEventListener("click", (event) => {284			if (modified(event)) return;285			event.preventDefault();286			if (open === tab && shown !== tab.href) {287				load(tab.href);288				return;289			}290			open?.classList.remove("active");291			if (open === tab) {292				open = null;293				shown = "";294				host.hidden = true;295				return;296			}297			open = tab;298			tab.classList.add("active");299			load(tab.href);300		});301	}302	host.addEventListener("click", (event) => {303		const link = event.target.closest("a[href]");304		if (!link || !open || modified(event) || link.hasAttribute("download")) return;305		if (!inside(link.href)) return;306		event.preventDefault();307		load(link.href);308	});309	host.addEventListener("submit", (event) => {310		const form = event.target;311		if (!open || !inside(form.action)) return;312		event.preventDefault();313		const method = form.method.toUpperCase();314		const data = new FormData(form);315		if (method === "GET") load(`${form.action}?${new URLSearchParams(data)}`);316		else load(form.action, { method, body: data });317	});318}319320// History and the Atlas's save picker hold one page of saves; scrolling to the end of either321// brings in the next page's rows. The pager is for pages without JavaScript.322function saveLists() {323	for (const list of document.querySelectorAll(".save-list")) {324		const observer = new IntersectionObserver(325			async ([entry]) => {326				const older = list.querySelector(".pager-older");327				if (!entry?.isIntersecting || !older) return;328				observer.disconnect();329				const main = await fetchMain(older.href);330				const next = main?.querySelector(`.save-list[data-list="${list.dataset.list}"]`);331				if (!next) return;332				next.querySelector(".pager a:not(.pager-older)")?.remove();333				list.querySelector(".pager").replaceWith(...next.childNodes);334				watch();335			},336			{ root: list },337		);338		const watch = () => {339			const older = list.querySelector(".pager-older");340			if (older) observer.observe(older);341		};342		watch();343	}344}345346// `#L42` works through CSS :target alone; a range `#L42-L50` needs marking line by line.347function lineRanges() {348	const code = document.querySelector(".code");349	if (!code) return;350	let anchor = null;351	const mark = () => {352		for (const marked of code.querySelectorAll(".line.hl")) marked.classList.remove("hl");353		const match = /^#L(\d+)(?:-L(\d+))?$/.exec(location.hash);354		if (!match) return;355		const from = Number(match[1]);356		const to = Number(match[2] ?? match[1]);357		anchor = from;358		for (let n = Math.min(from, to); n <= Math.max(from, to); n++) {359			document.getElementById(`L${n}`)?.classList.add("hl");360		}361		document.getElementById(`L${Math.min(from, to)}`)?.scrollIntoView({ block: "center" });362	};363	code.addEventListener("click", (event) => {364		const link = event.target.closest(".ln");365		if (!link || !event.shiftKey || anchor === null) return;366		event.preventDefault();367		const n = Number(link.textContent);368		history.replaceState(null, "", `#L${Math.min(anchor, n)}-L${Math.max(anchor, n)}`);369		mark();370	});371	window.addEventListener("hashchange", mark);372	mark();373}374375// The Atlas (§21.5): each row's detail panel is fetched on hover or select and kept for the page's376// life; the filter narrows by filename; which folders are open is remembered per repo in this browser.377function atlas() {378	const root = document.querySelector(".atlas");379	const filter = document.querySelector(".atlas-filter");380	if (!root || !filter) return;381	const panel = root.querySelector(".atlas-panel");382	const folders = [...root.querySelectorAll(".atlas-folder")];383	const files = [...root.querySelectorAll(".atlas-file")];384	// Its height is the closed tree's, fixed before any folder opens; opening one scrolls within.385	root.style.height = `${root.offsetHeight}px`;386	root.style.overflowY = "hidden";387	const key = `kepr:atlas:${root.dataset.repo}`;388	const opened = new Set(remembered(key));389	// `?open=<folder>` from a file page's breadcrumb unfolds that folder, without remembering it.390	const unfold = new URLSearchParams(location.search).get("open");391	const onPath = (path) => unfold !== null && `${unfold}/`.startsWith(`${path}/`);392	for (const folder of folders) {393		folder.open = opened.has(folder.dataset.path) || onPath(folder.dataset.path);394		folder.addEventListener("toggle", () => {395			if (filter.value.trim()) return;396			if (folder.open) opened.add(folder.dataset.path);397			else opened.delete(folder.dataset.path);398			remember(key, [...opened]);399		});400	}401	const panels = new Map();402	const panelFor = (path) => {403		if (!panels.has(path)) {404			const query = new URLSearchParams({ path });405			if (root.dataset.at) query.set("at", root.dataset.at);406			const text = fetch(`/${root.dataset.repo}/atlas/panel?${query}`)407				.then((response) => (response.ok ? response.text() : Promise.reject()))408				.catch(() => {409					panels.delete(path);410					return "";411				});412			panels.set(path, text);413		}414		return panels.get(path).then((text) => {415			const template = document.createElement("template");416			template.innerHTML = text;417			return template.content;418		});419	};420	let selected = null;421	const show = async (row) => {422		selected?.classList.remove("selected");423		selected = row;424		row.classList.add("selected");425		const content = await panelFor(row.dataset.path ?? `${row.parentElement.dataset.path}/`);426		if (selected === row) panel.replaceChildren(content);427	};428	for (const row of root.querySelectorAll(".atlas-row")) {429		row.addEventListener("pointerenter", (event) => {430			if (event.pointerType === "mouse") show(row);431		});432		row.addEventListener("focus", () => show(row));433	}434	// A map link in a panel jumps to its row, opening the folders above it.435	const jump = (path) => {436		const row = path.endsWith("/")437			? folders.find((folder) => `${folder.dataset.path}/` === path)?.firstElementChild438			: files.find((file) => file.dataset.path === path);439		if (!row) return false;440		for (const folder of folders) folder.open ||= path.startsWith(`${folder.dataset.path}/`);441		show(row);442		row.scrollIntoView({ block: "nearest" });443		return true;444	};445	panel.addEventListener("click", (event) => {446		const link = event.target.closest("a.atlas-jump");447		if (link && !modified(event) && jump(link.dataset.path)) event.preventDefault();448	});449	const viewer = fileViewer(root, jump, panelFor);450	for (const file of files) {451		file.addEventListener("click", (event) => {452			if (modified(event)) return;453			event.preventDefault();454			viewer(file);455		});456	}457	const target = folders.find((folder) => folder.dataset.path === unfold)?.firstElementChild;458	if (target) {459		show(target);460		target.scrollIntoView({ block: "center" });461	}462	filter.addEventListener("input", () => {463		const query = filter.value.trim().toLowerCase();464		for (const file of files) file.hidden = query !== "" && !file.dataset.name.includes(query);465		for (const folder of folders) {466			folder.hidden = query !== "" && !folder.querySelector(".atlas-file:not([hidden])");467			folder.open = query !== "" || opened.has(folder.dataset.path);468		}469	});470	// One button opens every folder, or, when they all are, closes them all.471	const fold = document.querySelector(".atlas-fold-btn");472	const label = () => {473		fold.textContent = folders.every((folder) => folder.open) ? "collapse all" : "expand all";474	};475	fold.addEventListener("click", () => {476		const open = !folders.every((folder) => folder.open);477		for (const folder of folders) folder.open = open;478		label();479	});480	for (const folder of folders) folder.addEventListener("toggle", label);481	label();482	fold.hidden = folders.length === 0;483	// The filter waits behind a search button, and folds back into it when left empty.484	const search = document.querySelector(".atlas-search-btn");485	search.addEventListener("click", () => {486		search.hidden = true;487		filter.hidden = false;488		filter.focus();489	});490	filter.addEventListener("blur", () => {491		if (filter.value.trim() !== "") return;492		filter.hidden = true;493		search.hidden = false;494	});495	search.hidden = false;496	panel.hidden = false;497}498499// Kepr 2's Atlas picker: its saves arrive when it first opens, filtered as you type; a click500// outside or Escape closes it.501function atlasPicker() {502	const picker = document.querySelector(".atlas-picker");503	if (!picker) return;504	const filter = picker.querySelector(".atlas-picker-filter");505	const list = picker.querySelector(".atlas-picker-list");506	let rows = [];507	const narrow = () => {508		const query = filter.value.trim().toLowerCase();509		for (const row of rows) {510			row.hidden = query !== "" && !row.textContent.toLowerCase().includes(query);511		}512	};513	filter.addEventListener("input", narrow);514	let loading = null;515	picker.addEventListener("toggle", () => {516		if (!picker.open) return;517		filter.focus();518		if (loading) return;519		loading = fetch(list.dataset.src)520			.then((response) => (response.ok ? response.text() : Promise.reject()))521			.then((text) => {522				const template = document.createElement("template");523				template.innerHTML = text;524				list.replaceChildren(template.content);525				rows = [...list.children];526				narrow();527			})528			.catch(() => {529				loading = null;530			});531	});532	document.addEventListener("click", (event) => {533		if (!picker.contains(event.target)) picker.open = false;534	});535	picker.addEventListener("keydown", (event) => {536		if (event.key === "Escape") picker.open = false;537	});538	filter.hidden = false;539}540541// Files open in a viewer over the page, as in Kepr 2's Atlas: the file page's content with the542// row's detail panel beside it, and controls for text size, wrapping, raw, download and the543// neighbouring files. Escape closes it; the arrow keys step through the files.544function fileViewer(root, jump, panelFor) {545	let [row, size, wrap] = [null, 12, false];546	const overlay = element("div", "fv-overlay");547	overlay.tabIndex = -1;548	overlay.setAttribute("role", "dialog");549	overlay.setAttribute("aria-modal", "true");550	const close = () => {551		overlay.remove();552		row?.focus();553		row = null;554	};555	const step = (by) => {556		const rows = [...root.querySelectorAll(".atlas-file")].filter((file) => !file.hidden);557		const next = rows[rows.indexOf(row) + by];558		if (next) open(next);559	};560	const restyle = () => {561		overlay.style.setProperty("--fv-size", `${size}px`);562		overlay.classList.toggle("fv-wrap", wrap);563	};564	const open = async (file, url = file.href) => {565		row = file;566		const rows = [...root.querySelectorAll(".atlas-file")].filter((each) => !each.hidden);567		const index = rows.indexOf(file);568		const path = file.dataset.path;569		const name = path.split("/").pop();570		const raw = new URL(file.href);571		raw.pathname = raw.pathname.replace(/^(\/[^/]+)\/files\//, "$1/raw/");572		const button = (text, action, className = "fv-ctrl-btn") => {573			const b = element("button", className, text);574			b.type = "button";575			b.addEventListener("click", action);576			return b;577		};578		const link = (text, download) => {579			const a = element("a", "fv-ctrl-btn", text);580			a.href = raw.href;581			if (download) a.download = name;582			return a;583		};584		const source = element("div", "fv-source", "loading…");585		const panel = element("aside", "fv-detail");586		panelFor(path).then((content) => {587			if (row === file) panel.replaceChildren(content);588		});589		const header = element("div", "fv-header");590		const title = element("div", "fv-title");591		title.append(element("span", "fv-name", name), element("span", "fv-path mono", path));592		const controls = element("div", "fv-controls mono");593		controls.append(594			button("A−", () => {595				size = Math.max(9, size - 1);596				restyle();597			}),598			button("A+", () => {599				size = Math.min(20, size + 1);600				restyle();601			}),602			button("⇌ wrap", (event) => {603				wrap = !wrap;604				event.currentTarget.classList.toggle("active", wrap);605				restyle();606			}),607			link("raw", false),608			link("download", true),609		);610		controls.children[2].classList.toggle("active", wrap);611		const nav = element("div", "fv-nav mono");612		const back = button("←", () => step(-1), "fv-ctrl-btn");613		const forward = button("→", () => step(1), "fv-ctrl-btn");614		back.disabled = index <= 0;615		forward.disabled = index >= rows.length - 1;616		nav.append(back, element("span", "fv-pos", `${index + 1}/${rows.length}`), forward);617		header.append(button("×", close, "fv-close"), title, controls, nav);618		const body = element("div", "fv-body");619		body.append(source, panel);620		overlay.replaceChildren(header, body);621		restyle();622		if (!overlay.isConnected) document.body.append(overlay);623		overlay.focus();624		const main = await fetchMain(url);625		if (row !== file) return;626		if (!main) {627			location.href = url;628			return;629		}630		for (const heading of main.querySelectorAll(".breadcrumb, .file-page-title")) heading.remove();631		main.querySelector(".file-meta:not(:last-child)")?.remove();632		source.replaceChildren(...main.childNodes);633	};634	overlay.addEventListener("keydown", (event) => {635		if (event.key === "Escape") close();636		else if (event.key === "ArrowLeft" || event.key === "ArrowRight") {637			event.preventDefault();638			step(event.key === "ArrowLeft" ? -1 : 1);639		}640	});641	// A map link beside the code opens that file here; a folder closes the viewer on its row.642	overlay.addEventListener("click", (event) => {643		const link = event.target.closest(".fv-detail a.atlas-jump");644		if (!link || modified(event)) return;645		const path = link.dataset.path;646		const file = [...root.querySelectorAll(".atlas-file")].find((f) => f.dataset.path === path);647		event.preventDefault();648		if (file) open(file);649		else {650			close();651			jump(path);652		}653	});654	// The Markdown view's rendered/source toggle points at the file page: switch in place.655	overlay.addEventListener("click", (event) => {656		const link = event.target.closest(".fv-source a[href]");657		if (!link || !row || modified(event)) return;658		if (new URL(link.href).pathname !== new URL(row.href).pathname) return;659		event.preventDefault();660		open(row, link.href);661	});662	return open;663}664665// On a phone the nav links fold behind a menu button (2026-10-01). The button only exists with666// JavaScript, so without it the links stay in the bar; the CSS hides them only on `.nav--menu`.667function navMenu() {668	const nav = document.querySelector("body > nav");669	const links = nav?.querySelector(".nav-links");670	if (!links) return;671	links.id = "nav-links";672	const button = element("button", "nav-toggle");673	button.type = "button";674	button.setAttribute("aria-label", "menu");675	button.setAttribute("aria-controls", "nav-links");676	button.setAttribute("aria-expanded", "false");677	button.append(element("span", ""), element("span", ""), element("span", ""));678	const open = () => nav.classList.contains("nav--open");679	const set = (opened) => {680		nav.classList.toggle("nav--open", opened);681		button.setAttribute("aria-expanded", String(opened));682	};683	button.addEventListener("click", () => set(!open()));684	document.addEventListener("click", (event) => {685		if (open() && !nav.contains(event.target)) set(false);686	});687	document.addEventListener("keydown", (event) => {688		if (event.key !== "Escape" || !open()) return;689		set(false);690		button.focus();691	});692	nav.classList.add("nav--menu");693	// Before the links, so tabbing from the open button reaches them next.694	links.before(button);695}696function element(tag, className, text) {697	const node = document.createElement(tag);698	node.className = className;699	if (text !== undefined) node.textContent = text;700	return node;701}702703// Signed in, a repo page's description and details are edited in place: Markdown with a toolbar704// and a preview as the page will show it, pictures and videos picked, dropped or pasted in, and705// the one under the caret sized and placed from a row of controls. The page's HTML is the same706// for everyone; only the cookie signing in sets beside the session brings the controls.707async function repoEditor() {708	const head = document.querySelector(".repo-head");709	if (!head || !/(^|;\s*)kepr_editor=[0-9a-f]{64}/.test(document.cookie)) return;710	const base = `/admin/repos/${location.pathname.split("/")[1]}`;711	const response = await fetch(`${base}/text`).catch(() => null);712	if (!response?.ok) return;713	const texts = await response.json();714	const details = document.querySelector(".repo-details");715	const places = [716		["description", head.querySelector(".repo-desc"), head.querySelector(".repo-desc")],717		["details", details, details.querySelector(".repo-details-body")],718	];719	for (const [field, section, body] of places) {720		section.hidden = false;721		if (field === "description") {722			section.tabIndex = 0;723			section.setAttribute("role", "button");724			section.setAttribute("aria-label", "edit repository description");725			section.classList.add("repo-desc-editable");726			if (!section.textContent.trim()) section.textContent = "add a description";727			const activate = (event) => {728				if (event.target.closest(".editor") || body.querySelector(".editor")) return;729				event.preventDefault();730				editText(base, texts.form, field, body, texts[field]);731			};732			section.addEventListener("click", activate);733			section.addEventListener("keydown", (event) => {734				if (event.target === section && (event.key === "Enter" || event.key === " "))735					activate(event);736			});737			continue;738		}739		const button = element("button", "edit-btn mono", "edit");740		button.type = "button";741		(section.querySelector(".repo-details-head") ?? section).append(button);742		button.addEventListener("click", (event) => {743			event.preventDefault();744			if (!body.querySelector(".editor")) editText(base, texts.form, field, body, texts[field]);745		});746	}747}748749const MEDIA_MARKDOWN = /!\[([^\]]*)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)/g;750const MEDIA_TYPES = "image/png,image/jpeg,image/gif,image/webp,video/mp4,video/webm";751752function editText(base, form, field, body, text) {753	const kept = [...body.childNodes];754	if (field === "description") {755		body.removeAttribute("role");756		body.removeAttribute("tabindex");757		body.removeAttribute("aria-label");758	}759	const input = element("textarea", "editor-input mono");760	input.value = text;761	input.rows = field === "details" ? 16 : 3;762	const preview = element("div", `editor-preview${field === "details" ? " markdown" : ""}`);763	const media = element("div", "editor-media mono");764	const status = element("span", "editor-status");765	const post = (path, fields) => {766		const data = new FormData();767		data.append("form", form);768		for (const [name, value] of Object.entries(fields)) data.append(name, value);769		return fetch(`${base}/${path}`, { method: "POST", body: data });770	};771	let timer = null;772	const changed = () => {773		inspect();774		clearTimeout(timer);775		timer = setTimeout(async () => {776			const answer = await post("preview", { field, value: input.value }).catch(() => null);777			if (!answer?.ok) return;778			// Kepr's own Markdown rendering, raw HTML off: the same markup the page will carry.779			preview.innerHTML = input.value.trim() ? await answer.text() : "";780			preview.dataset.empty = input.value.trim() ? "" : "the README's words show here";781		}, 250);782	};783	const wrap = (before, after = before, fallback = "text") => {784		const [from, to] = [input.selectionStart, input.selectionEnd];785		const chosen = input.value.slice(from, to) || fallback;786		input.setRangeText(before + chosen + after, from, to);787		input.setSelectionRange(from + before.length, from + before.length + chosen.length);788		input.focus();789		changed();790	};791	const prefix = (mark) => {792		const start = input.value.lastIndexOf("\n", input.selectionStart - 1) + 1;793		input.setRangeText(mark, start, start, "end");794		input.focus();795		changed();796	};797	const upload = async (file) => {798		status.textContent = `uploading ${file.name}…`;799		const answer = await post("media", { file }).catch(() => null);800		if (!answer?.ok) {801			status.textContent = answer ? await answer.text() : "upload failed";802			return;803		}804		const { url } = await answer.json();805		const alt = file.name.replace(/\.[^.]+$/, "").replace(/[[\]]/g, "");806		input.setRangeText(807			`\n![${alt}](${url} "width=100 center")\n`,808			input.selectionStart,809			input.selectionEnd,810			"end",811		);812		status.textContent = "";813		input.focus();814		changed();815	};816	const picker = element("input", "");817	picker.type = "file";818	picker.accept = MEDIA_TYPES;819	picker.hidden = true;820	picker.addEventListener("change", () => {821		for (const file of picker.files) upload(file);822		picker.value = "";823	});824	// The picture or video under the caret, with its options, as `![alt](url "options")`.825	const underCaret = () =>826		[...input.value.matchAll(MEDIA_MARKDOWN)].find(827			(m) => input.selectionStart >= m.index && input.selectionStart <= m.index + m[0].length,828		);829	function inspect() {830		const found = field === "details" ? underCaret() : undefined;831		media.hidden = !found;832		if (!found) return;833		const words = (found[3] ?? "").split(/\s+/).filter(Boolean);834		const width = words.find((word) => word.startsWith("width="))?.slice(6) ?? "100";835		const align = words.find((word) => /^(left|center|right)$/.test(word)) ?? "center";836		const loop = words.includes("loop");837		const video = /\.(mp4|webm)$/i.test(found[2]);838		const set = (next) => {839			const options = [`width=${next.width}`, next.align, next.loop && "loop"].filter(Boolean);840			const markdown = `![${found[1]}](${found[2]} "${options.join(" ")}")`;841			const caret = input.selectionStart;842			input.setRangeText(markdown, found.index, found.index + found[0].length);843			input.setSelectionRange(caret, caret);844			changed();845		};846		const choice = (label, active, action) => {847			const b = element("button", `fv-ctrl-btn${active ? " active" : ""}`, label);848			b.type = "button";849			b.addEventListener("click", action);850			return b;851		};852		media.replaceChildren(853			element("span", "editor-label", video ? "video" : "picture"),854			...["25", "33", "50", "66", "75", "100"].map((w) =>855				choice(`${w}%`, w === width, () => set({ width: w, align, loop })),856			),857			...["left", "center", "right"].map((a) =>858				choice(a, a === align, () => set({ width, align: a, loop })),859			),860			...(video ? [choice("loop like a GIF", loop, () => set({ width, align, loop: !loop }))] : []),861		);862	}863	const save = async (value) => {864		status.textContent = "saving…";865		const answer = await post("text", { field, value }).catch(() => null);866		if (answer?.ok) location.reload();867		else status.textContent = answer ? await answer.text() : "not saved: offline?";868	};869	const cancel = () => {870		body.replaceChildren(...kept);871		if (field === "description") {872			body.tabIndex = 0;873			body.setAttribute("role", "button");874			body.setAttribute("aria-label", "edit repository description");875			body.focus();876		}877	};878	const tool = (label, title, action) => {879		const b = element("button", "fv-ctrl-btn", label);880		b.type = "button";881		b.title = title;882		b.addEventListener("click", action);883		return b;884	};885	const toolbar = element("div", "editor-toolbar mono");886	toolbar.append(887		tool("B", "bold (⌘B)", () => wrap("**")),888		tool("I", "italic (⌘I)", () => wrap("_")),889		tool("link", "link (⌘K)", () => wrap("[", "](https://)")),890		tool("code", "code", () => wrap("`")),891	);892	if (field === "details") {893		toolbar.append(894			tool("heading", "heading", () => prefix("## ")),895			tool("list", "list", () => prefix("- ")),896			tool("quote", "quote", () => prefix("> ")),897			tool("picture or video", "add a picture, GIF or video (or drop or paste one)", () =>898				picker.click(),899			),900			picker,901		);902		input.addEventListener("dragover", (event) => event.preventDefault());903		input.addEventListener("drop", (event) => {904			if (event.dataTransfer.files.length === 0) return;905			event.preventDefault();906			for (const file of event.dataTransfer.files) upload(file);907		});908		input.addEventListener("paste", (event) => {909			const files = [...event.clipboardData.files];910			if (files.length === 0) return;911			event.preventDefault();912			for (const file of files) upload(file);913		});914	}915	input.addEventListener("input", changed);916	for (const name of ["click", "keyup"]) input.addEventListener(name, inspect);917	input.addEventListener("keydown", (event) => {918		const command = event.metaKey || event.ctrlKey;919		if (event.key === "Escape") cancel();920		else if (command && event.key === "Enter") save(input.value);921		else if (command && event.key === "b") wrap("**");922		else if (command && event.key === "i") wrap("_");923		else if (command && event.key === "k") wrap("[", "](https://)");924		else return;925		event.preventDefault();926	});927	const actions = element("div", "editor-actions mono");928	actions.append(929		tool("save", "save (⌘↵)", () => save(input.value)),930		tool("cancel", "cancel (esc)", cancel),931		tool("use the README", "clear your words and show the README's again", () => save("")),932		status,933	);934	const panes = element("div", "editor-panes");935	panes.append(input, preview);936	const editor = element("div", `editor editor-${field}`);937	editor.append(toolbar, panes, media, actions);938	body.replaceChildren(editor);939	input.focus();940	changed();941}942943// Storage can be missing, refused (private windows, blocked windows) or hold anything; only a944// list of folder paths is trusted, and otherwise the tree starts closed.945function remembered(key) {946	try {947		const value = JSON.parse(localStorage.getItem(key) ?? "[]");948		return Array.isArray(value) && value.every((path) => typeof path === "string") ? value : [];949	} catch {950		return [];951	}952}953954function remember(key, value) {955	try {956		localStorage.setItem(key, JSON.stringify(value));957	} catch {}958}959960function hexStream() {961	const backdrop = document.querySelector(".hex-backdrop");962	if (!backdrop) return;963	let visible = true;964	const update = () => backdrop.classList.toggle("paused", !visible || document.hidden);965	new IntersectionObserver(([entry]) => {966		visible = entry.isIntersecting;967		update();968	}).observe(backdrop);969	document.addEventListener("visibilitychange", update);970	update();971}972973// A CSS duration cannot follow a track's width, so the pace would depend on the messages; set it974// here so each row slides at its own --speed in px/s, as Kepr 2's canvas did.975function tickerPace() {976	for (const track of document.querySelectorAll(".ticker-track")) {977		const speed = Number(getComputedStyle(track).getPropertyValue("--speed"));978		if (speed > 0) track.style.animationDuration = `${track.scrollWidth / 2 / speed}s`;979	}980}981982// Widths are only final once Martian Mono has loaded.983document.fonts.ready.then(tickerPace);984timeline()985	.catch((error) => console.error("kepr: the timeline could not load", error))986	.finally(() => document.documentElement.classList.remove("timeline-pending"));987copyButtons(document);988panels();989saveLists();990atlasPicker();991repoEditor();992navMenu();993lineRanges();994atlas();995hexStream();