kepr.js

41.2 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, issue replies and3// attachments, history's scrolling, line-range highlighting, the Atlas panel, picker, filter and4// file viewer, the signed-in 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	// The strip's shift this frame, and the first save at or past an x (x is sorted, see resize).81	const shifted = () => ((offset % strip) + strip) % strip;82	const firstAt = (x) => {83		let [lo, hi] = [0, saves.length];84		while (lo < hi) {85			const mid = (lo + hi) >>> 1;86			if (saves[mid].x <= x) lo = mid + 1;87			else hi = mid;88		}89		return lo;90	};91	const hit = (event) => {92		const box = canvas.getBoundingClientRect();93		const [mx, my] = [event.clientX - box.left, event.clientY - box.top];94		if (Math.abs(my - height / 2) > radius + 7) return null;95		const shift = shifted();96		return (97			saves.find((save) => {98				for (let sx = save.x - shift - strip; sx < width; sx += strip)99					if (sx > 0 && Math.abs(mx - sx) < radius + 7) return true;100				return false;101			}) ?? null102		);103	};104	let [hovered, drag, dragFrom, downX, lastX, velocity, resumeAt, lastFrame] = [105		null,106		null,107		0,108		0,109		0,110		0,111		0,112		0,113	];114	const hover = (save, event) => {115		if (save !== hovered) {116			hovered = save;117			tip.hidden = save === null;118			if (save)119				tip.replaceChildren(120					line("tip-id", save.id),121					line("tip-msg", save.message),122					line("tip-meta", save.meta),123				);124		}125		if (save) {126			const left = event.clientX + 14;127			tip.style.left = `${left + 340 > innerWidth ? Math.max(8, event.clientX - 354) : left}px`;128			tip.style.top = `${event.clientY - 10}px`;129		}130		canvas.style.cursor = save ? "pointer" : drag === null ? "grab" : "grabbing";131	};132	const draw = (time) => {133		const dt = lastFrame ? Math.min((time - lastFrame) / 1000, 0.1) : 0;134		lastFrame = time;135		if (drag === null && hovered === null) {136			if (Math.abs(velocity) > 0.5) {137				offset -= velocity;138				velocity *= 0.92;139			} else if (!reduce.matches && time >= resumeAt) offset += 20 * dt;140		}141		const y = height / 2;142		ctx.clearRect(0, 0, width, height);143		ctx.lineWidth = 1;144		ctx.globalAlpha = 0.7;145		ctx.strokeStyle = css.getPropertyValue("--text-muted");146		ctx.setLineDash([4, 4]);147		ctx.beginPath();148		ctx.moveTo(0, y);149		ctx.lineTo(width, y);150		ctx.stroke();151		ctx.setLineDash([]);152		ctx.font = '10px "Martian Mono", monospace';153		ctx.textAlign = "center";154		const shift = shifted();155		const margin = 10;156		const last = saves[saves.length - 1].x;157		// Saves are sorted by x, so only the copies inside the canvas' windows need visiting: one158		// stripe per k, each holding the copies of a contiguous run of saves.159		for (let k = Math.floor((-shift - width - margin) / strip); ; k++) {160			const base = shift + k * strip;161			if (base - margin > last) break;162			const end = base + width + margin;163			if (end <= 0) continue;164			for (let i = firstAt(base - margin); i < saves.length && saves[i].x < end; i++) {165				const save = saves[i];166				const x = save.x - base;167				ctx.globalAlpha = hovered === null ? save.alpha : hovered === save ? 1 : save.alpha * 0.6;168				ctx.fillStyle = save.fill;169				ctx.beginPath();170				ctx.arc(x, y, radius, 0, Math.PI * 2);171				ctx.fill();172				if (hovered === save) {173					ctx.fillStyle = css.getPropertyValue("--accent");174					ctx.fillText(save.id.slice(0, 6), x, y - radius - 6);175				}176			}177		}178		ctx.globalAlpha = 1;179		if (visible) requestAnimationFrame(draw);180		else drawing = false;181	};182	canvas.addEventListener("pointerdown", (event) => {183		[drag, dragFrom, downX, lastX, velocity] = [184			event.clientX,185			offset,186			event.clientX,187			event.clientX,188			0,189		];190		canvas.setPointerCapture(event.pointerId);191	});192	canvas.addEventListener("pointermove", (event) => {193		if (drag !== null) {194			offset = dragFrom - (event.clientX - drag);195			velocity = velocity * 0.6 + (event.clientX - lastX) * 0.4;196			lastX = event.clientX;197		}198		if (event.pointerType === "mouse") hover(hit(event), event);199	});200	const release = () => {201		drag = null;202		resumeAt = performance.now() + 900;203	};204	canvas.addEventListener("pointerup", (event) => {205		release();206		const save = Math.abs(event.clientX - downX) > 4 ? null : hit(event);207		if (save) location.href = save.href;208	});209	canvas.addEventListener("pointercancel", release);210	canvas.addEventListener("pointerleave", (event) => {211		if (drag === null) hover(null, event);212	});213	addEventListener("resize", resize);214	resize();215	// Off screen, the loop stops; it starts again, without a jump, when the strip scrolls back.216	let [visible, drawing] = [true, false];217	new IntersectionObserver(([entry]) => {218		visible = entry.isIntersecting;219		if (visible && !drawing) {220			drawing = true;221			lastFrame = 0;222			requestAnimationFrame(draw);223		}224	}).observe(canvas);225}226227function line(className, text) {228	const div = document.createElement("div");229	div.className = className;230	div.textContent = text ?? "";231	return div;232}233234function copyButtons(root) {235	for (const button of root.querySelectorAll("button[data-copy]")) {236		const label = button.textContent;237		button.hidden = false;238		button.addEventListener("click", async () => {239			await navigator.clipboard.writeText(button.dataset.copy);240			button.textContent = "copied";241			button.classList.add("copied");242			setTimeout(() => {243				button.textContent = label;244				button.classList.remove("copied");245			}, 1400);246		});247	}248}249250// A Kepr page's <main>, its links made absolute so they point where they did on their own page251// (after any redirect). An error page's <main> comes back too, so a refused form shows why; null if252// nothing came back, and the caller then goes to the page itself.253async function fetchMain(url, init) {254	try {255		const response = await fetch(url, init);256		const page = new DOMParser().parseFromString(await response.text(), "text/html");257		const main = page.querySelector("main");258		for (const link of main?.querySelectorAll("a[href]:not([href^='#'])") ?? []) {259			link.href = new URL(link.getAttribute("href"), response.url || url).href;260		}261		return main;262	} catch {263		return null;264	}265}266267// A click the browser should handle itself: a new tab or window, or a download.268function modified(event) {269	return event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey;270}271272// §21.9's panels omit the root heading; nested pages need their own title and way back.273// The panel's own pages (an issue, the report form) and its forms stay inside it; a link elsewhere,274// or to a file (a download), navigates. The open tab takes the panel back to its first page, and275// closes it from there.276function panels() {277	const host = document.querySelector(".repo-panel");278	if (!host) return;279	let open = null;280	let shown = "";281	const load = async (url, init) => {282		shown = url;283		const main = await fetchMain(url, init);284		if (shown !== url) return;285		if (!main) {286			location.href = url;287			return;288		}289		if (new URL(url).pathname === new URL(open.href).pathname) {290			main.querySelector(".breadcrumb")?.remove();291			main.querySelector(".file-page-title")?.remove();292		}293		host.replaceChildren(...main.childNodes);294		copyButtons(host);295		host.hidden = false;296	};297	const inside = (url) => {298		const base = new URL(open.href).pathname;299		const { pathname } = new URL(url);300		return (pathname === base || pathname.startsWith(`${base}/`)) && !/\.[^/]*$/.test(pathname);301	};302	for (const tab of document.querySelectorAll(".repo-tab[data-panel]")) {303		tab.addEventListener("click", (event) => {304			if (modified(event)) return;305			event.preventDefault();306			if (open === tab && shown !== tab.href) {307				load(tab.href);308				return;309			}310			open?.classList.remove("active");311			if (open === tab) {312				open = null;313				shown = "";314				host.hidden = true;315				return;316			}317			open = tab;318			tab.classList.add("active");319			load(tab.href);320		});321	}322	host.addEventListener("click", (event) => {323		const link = event.target.closest("a[href]");324		if (!link || !open || modified(event) || link.hasAttribute("download")) return;325		if (!inside(link.href)) return;326		event.preventDefault();327		load(link.href);328	});329	host.addEventListener("submit", (event) => {330		const form = event.target;331		if (!open || !inside(form.action)) return;332		event.preventDefault();333		const method = form.method.toUpperCase();334		const data = new FormData(form);335		if (method === "GET") load(`${form.action}?${new URLSearchParams(data)}`);336		else load(form.action, { method, body: data });337	});338}339340// Issue threads (§23): reply and quote fill the composer in place, and quote with text selected in341// a post quotes just that. With nothing selected, quote follows its link, which quotes the post's342// own Markdown. Listening on the document, before the panel's own handler, reaches threads opened343// in a repo's panel too.344function issueReplies() {345	let picked = "";346	// A click collapses the selection, so it is read as the pointer goes down.347	document.addEventListener(348		"pointerdown",349		(event) => {350			const post = event.target.closest?.(".issue-post-actions")?.closest(".issue-post");351			const selection = getSelection();352			picked = post?.contains(selection.anchorNode) ? selection.toString().trim() : "";353		},354		true,355	);356	document.addEventListener(357		"click",358		(event) => {359			const link = event.target.closest(".issue-post-actions a, .issue-composer-to .issues-cancel");360			const form = document.getElementById("reply");361			if (!link || !form || modified(event)) return;362			if (link.dataset.action === "quote" && !picked) return;363			event.preventDefault();364			event.stopPropagation();365			const post = link.closest(".issue-post");366			const to = form.querySelector(".issue-composer-to");367			form.elements.reply_to.value = post?.dataset.entry ?? "";368			to.hidden = !post?.dataset.entry;369			if (post) {370				const name = to.querySelector(".issue-composer-name");371				name.textContent = post.dataset.author;372				name.href = `#${post.id}`;373			}374			const body = form.elements.body;375			if (link.dataset.action === "quote") {376				const quote = `${picked.replace(/^/gm, "> ")}\n\n`;377				body.value = body.value.trim() ? `${body.value.trimEnd()}\n\n${quote}` : quote;378				picked = "";379			}380			body.focus();381			body.scrollIntoView({ block: "center" });382		},383		true,384	);385}386387// Pictures pasted or dropped into an issue's form join its attachments (§23), and each chosen file388// is listed under the field, a picture with its thumbnail, before anything is sent.389function issueAttachments() {390	const fileInput = (target) =>391		target.closest?.("form")?.querySelector("input[type=file][name=files]") ?? null;392	const add = (input, files) => {393		const all = new DataTransfer();394		for (const file of [...input.files, ...files]) all.items.add(file);395		input.files = all.files;396		input.dispatchEvent(new Event("change", { bubbles: true }));397	};398	document.addEventListener("paste", (event) => {399		const input = fileInput(event.target);400		const files = [...(event.clipboardData?.files ?? [])];401		if (!input || files.length === 0) return;402		event.preventDefault();403		add(input, files);404	});405	document.addEventListener("dragover", (event) => {406		if (fileInput(event.target) && event.dataTransfer?.types.includes("Files")) {407			event.preventDefault();408		}409	});410	document.addEventListener("drop", (event) => {411		const input = fileInput(event.target);412		if (!input || !event.dataTransfer?.files.length) return;413		event.preventDefault();414		add(input, event.dataTransfer.files);415	});416	document.addEventListener("change", (event) => {417		const input = event.target;418		const list = input.closest?.("form")?.querySelector(".issue-attached");419		if (input.name !== "files" || !list) return;420		for (const image of list.querySelectorAll("img")) URL.revokeObjectURL(image.src);421		list.replaceChildren(422			...[...input.files].map((file) => {423				const item = element("li", "", file.name);424				if (file.type.startsWith("image/")) {425					const image = element("img", "");426					image.src = URL.createObjectURL(file);427					image.alt = "";428					item.prepend(image);429				}430				return item;431			}),432		);433	});434}435436// History and the Atlas's save picker hold one page of saves; scrolling to the end of either437// brings in the next page's rows. The pager is for pages without JavaScript.438function saveLists() {439	for (const list of document.querySelectorAll(".save-list")) {440		const observer = new IntersectionObserver(441			async ([entry]) => {442				const older = list.querySelector(".pager-older");443				if (!entry?.isIntersecting || !older) return;444				observer.disconnect();445				const main = await fetchMain(older.href);446				const next = main?.querySelector(`.save-list[data-list="${list.dataset.list}"]`);447				if (!next) return;448				next.querySelector(".pager a:not(.pager-older)")?.remove();449				list.querySelector(".pager").replaceWith(...next.childNodes);450				watch();451			},452			{ root: list },453		);454		const watch = () => {455			const older = list.querySelector(".pager-older");456			if (older) observer.observe(older);457		};458		watch();459	}460}461462// `#L42` works through CSS :target alone; a range `#L42-L50` needs marking line by line.463function lineRanges() {464	const code = document.querySelector(".code");465	if (!code) return;466	let anchor = null;467	const mark = () => {468		for (const marked of code.querySelectorAll(".line.hl")) marked.classList.remove("hl");469		const match = /^#L(\d+)(?:-L(\d+))?$/.exec(location.hash);470		if (!match) return;471		const from = Number(match[1]);472		const to = Number(match[2] ?? match[1]);473		anchor = from;474		for (let n = Math.min(from, to); n <= Math.max(from, to); n++) {475			document.getElementById(`L${n}`)?.classList.add("hl");476		}477		document.getElementById(`L${Math.min(from, to)}`)?.scrollIntoView({ block: "center" });478	};479	code.addEventListener("click", (event) => {480		const link = event.target.closest(".ln");481		if (!link || !event.shiftKey || anchor === null) return;482		event.preventDefault();483		const n = Number(link.textContent);484		history.replaceState(null, "", `#L${Math.min(anchor, n)}-L${Math.max(anchor, n)}`);485		mark();486	});487	window.addEventListener("hashchange", mark);488	mark();489}490491// The Atlas (§21.5): each row's detail panel is fetched on hover or select and kept for the page's492// life; the filter narrows by filename; which folders are open is remembered per repo in this browser.493function atlas() {494	const root = document.querySelector(".atlas");495	const filter = document.querySelector(".atlas-filter");496	if (!root || !filter) return;497	const panel = root.querySelector(".atlas-panel");498	const folders = [...root.querySelectorAll(".atlas-folder")];499	const files = [...root.querySelectorAll(".atlas-file")];500	// Its height is the closed tree's, fixed before any folder opens; opening one scrolls within.501	root.style.height = `${root.offsetHeight}px`;502	root.style.overflowY = "hidden";503	const key = `kepr:atlas:${root.dataset.repo}`;504	const privateView = document.body.hasAttribute("data-private-view");505	const opened = new Set(privateView ? [] : remembered(key));506	// `?open=<folder>` from a file page's breadcrumb unfolds that folder, without remembering it.507	const unfold = new URLSearchParams(location.search).get("open");508	const onPath = (path) => unfold !== null && `${unfold}/`.startsWith(`${path}/`);509	for (const folder of folders) {510		folder.open = opened.has(folder.dataset.path) || onPath(folder.dataset.path);511		folder.addEventListener("toggle", () => {512			if (filter.value.trim()) return;513			if (folder.open) opened.add(folder.dataset.path);514			else opened.delete(folder.dataset.path);515			if (!privateView) remember(key, [...opened]);516		});517	}518	const panels = new Map();519	// Each panel is fetched once per row and kept; a hover's fetch is dropped when the pointer leaves520	// the row, so crossing rows asks only for the one the pointer stops on.521	const panelFor = (path, signal) => {522		if (!panels.has(path)) {523			const query = new URLSearchParams({ path });524			if (root.dataset.at) query.set("at", root.dataset.at);525			const text = fetch(`/${root.dataset.repo}/atlas/panel?${query}`, { signal })526				.then((response) => (response.ok ? response.text() : Promise.reject()))527				.catch(() => {528					panels.delete(path);529					return null;530				});531			panels.set(path, text);532		}533		return panels.get(path).then((text) => {534			if (text === null) return null;535			const template = document.createElement("template");536			template.innerHTML = text;537			return template.content;538		});539	};540	let selected = null;541	const select = (row) => {542		if (selected === row) return;543		selected?.classList.remove("selected");544		selected = row;545		row.classList.add("selected");546	};547	const show = async (row, signal) => {548		select(row);549		const content = await panelFor(550			row.dataset.path ?? `${row.parentElement.dataset.path}/`,551			signal,552		);553		if (content && selected === row) panel.replaceChildren(content);554	};555	// A hover waits this long for the pointer to settle before it fetches.556	const HOVER = 100;557	let hovered = null;558	let pending = 0;559	let running = null;560	const cancel = () => {561		clearTimeout(pending);562		pending = 0;563		running?.abort();564		running = null;565	};566	const leave = (row) => {567		if (hovered !== row) return;568		hovered = null;569		cancel();570	};571	for (const row of root.querySelectorAll(".atlas-row")) {572		row.addEventListener("pointerenter", (event) => {573			if (event.pointerType !== "mouse") return;574			cancel();575			hovered = row;576			select(row);577			pending = setTimeout(() => {578				running = new AbortController();579				show(row, running.signal);580			}, HOVER);581		});582		row.addEventListener("pointerleave", () => leave(row));583		row.addEventListener("focus", () => {584			cancel();585			hovered = null;586			show(row);587		});588	}589	// A map link in a panel jumps to its row, opening the folders above it.590	const jump = (path) => {591		const row = path.endsWith("/")592			? folders.find((folder) => `${folder.dataset.path}/` === path)?.firstElementChild593			: files.find((file) => file.dataset.path === path);594		if (!row) return false;595		for (const folder of folders) folder.open ||= path.startsWith(`${folder.dataset.path}/`);596		show(row);597		row.scrollIntoView({ block: "nearest" });598		return true;599	};600	panel.addEventListener("click", (event) => {601		const link = event.target.closest("a.atlas-jump");602		if (link && !modified(event) && jump(link.dataset.path)) event.preventDefault();603	});604	const viewer = fileViewer(root, jump, panelFor);605	for (const file of files) {606		file.addEventListener("click", (event) => {607			if (modified(event)) return;608			event.preventDefault();609			viewer(file);610		});611	}612	const target = folders.find((folder) => folder.dataset.path === unfold)?.firstElementChild;613	if (target) {614		show(target);615		target.scrollIntoView({ block: "center" });616	}617	filter.addEventListener("input", () => {618		const query = filter.value.trim().toLowerCase();619		for (const file of files) file.hidden = query !== "" && !file.dataset.name.includes(query);620		for (const folder of folders) {621			folder.hidden = query !== "" && !folder.querySelector(".atlas-file:not([hidden])");622			folder.open = query !== "" || opened.has(folder.dataset.path);623		}624	});625	// One button opens every folder, or, when they all are, closes them all.626	const fold = document.querySelector(".atlas-fold-btn");627	const label = () => {628		fold.textContent = folders.every((folder) => folder.open) ? "collapse all" : "expand all";629	};630	fold.addEventListener("click", () => {631		const open = !folders.every((folder) => folder.open);632		for (const folder of folders) folder.open = open;633		label();634	});635	for (const folder of folders) folder.addEventListener("toggle", label);636	label();637	fold.hidden = folders.length === 0;638	// The filter waits behind a search button, and folds back into it when left empty.639	const search = document.querySelector(".atlas-search-btn");640	search.addEventListener("click", () => {641		search.hidden = true;642		filter.hidden = false;643		filter.focus();644	});645	filter.addEventListener("blur", () => {646		if (filter.value.trim() !== "") return;647		filter.hidden = true;648		search.hidden = false;649	});650	search.hidden = false;651	panel.hidden = false;652}653654// Kepr 2's Atlas picker: its saves arrive when it first opens, filtered as you type; a click655// outside or Escape closes it.656function atlasPicker() {657	const picker = document.querySelector(".atlas-picker");658	if (!picker) return;659	const filter = picker.querySelector(".atlas-picker-filter");660	const list = picker.querySelector(".atlas-picker-list");661	let rows = [];662	const narrow = () => {663		const query = filter.value.trim().toLowerCase();664		for (const row of rows) {665			row.hidden = query !== "" && !row.textContent.toLowerCase().includes(query);666		}667	};668	filter.addEventListener("input", narrow);669	let loading = null;670	picker.addEventListener("toggle", () => {671		if (!picker.open) return;672		filter.focus();673		if (loading) return;674		loading = fetch(list.dataset.src)675			.then((response) => (response.ok ? response.text() : Promise.reject()))676			.then((text) => {677				const template = document.createElement("template");678				template.innerHTML = text;679				list.replaceChildren(template.content);680				rows = [...list.children];681				narrow();682			})683			.catch(() => {684				loading = null;685			});686	});687	document.addEventListener("click", (event) => {688		if (!picker.contains(event.target)) picker.open = false;689	});690	picker.addEventListener("keydown", (event) => {691		if (event.key === "Escape") picker.open = false;692	});693	filter.hidden = false;694}695696// Files open in a viewer over the page, as in Kepr 2's Atlas: the file page's content with the697// row's detail panel beside it, and controls for text size, wrapping, raw, download and the698// neighbouring files. Escape closes it; the arrow keys step through the files.699function fileViewer(root, jump, panelFor) {700	let [row, size, wrap] = [null, 12, false];701	const overlay = element("div", "fv-overlay");702	overlay.tabIndex = -1;703	overlay.setAttribute("role", "dialog");704	overlay.setAttribute("aria-modal", "true");705	const close = () => {706		overlay.remove();707		row?.focus();708		row = null;709	};710	const step = (by) => {711		const rows = [...root.querySelectorAll(".atlas-file")].filter((file) => !file.hidden);712		const next = rows[rows.indexOf(row) + by];713		if (next) open(next);714	};715	const restyle = () => {716		overlay.style.setProperty("--fv-size", `${size}px`);717		overlay.classList.toggle("fv-wrap", wrap);718	};719	const open = async (file, url = file.href) => {720		row = file;721		const rows = [...root.querySelectorAll(".atlas-file")].filter((each) => !each.hidden);722		const index = rows.indexOf(file);723		const path = file.dataset.path;724		const name = path.split("/").pop();725		const raw = new URL(file.href);726		raw.pathname = raw.pathname.replace(/^(\/[^/]+)\/files\//, "$1/raw/");727		const button = (text, action, className = "fv-ctrl-btn") => {728			const b = element("button", className, text);729			b.type = "button";730			b.addEventListener("click", action);731			return b;732		};733		const link = (text, download) => {734			const a = element("a", "fv-ctrl-btn", text);735			a.href = raw.href;736			if (download) a.download = name;737			return a;738		};739		const source = element("div", "fv-source", "loading…");740		const panel = element("aside", "fv-detail");741		panelFor(path).then((content) => {742			if (row === file) panel.replaceChildren(content);743		});744		const header = element("div", "fv-header");745		const title = element("div", "fv-title");746		title.append(element("span", "fv-name", name), element("span", "fv-path mono", path));747		const controls = element("div", "fv-controls mono");748		controls.append(749			button("A−", () => {750				size = Math.max(9, size - 1);751				restyle();752			}),753			button("A+", () => {754				size = Math.min(20, size + 1);755				restyle();756			}),757			button("⇌ wrap", (event) => {758				wrap = !wrap;759				event.currentTarget.classList.toggle("active", wrap);760				restyle();761			}),762			link("raw", false),763			link("download", true),764		);765		controls.children[2].classList.toggle("active", wrap);766		const nav = element("div", "fv-nav mono");767		const back = button("←", () => step(-1), "fv-ctrl-btn");768		const forward = button("→", () => step(1), "fv-ctrl-btn");769		back.disabled = index <= 0;770		forward.disabled = index >= rows.length - 1;771		nav.append(back, element("span", "fv-pos", `${index + 1}/${rows.length}`), forward);772		header.append(button("×", close, "fv-close"), title, controls, nav);773		const body = element("div", "fv-body");774		body.append(source, panel);775		overlay.replaceChildren(header, body);776		restyle();777		if (!overlay.isConnected) document.body.append(overlay);778		overlay.focus();779		const main = await fetchMain(url);780		if (row !== file) return;781		if (!main) {782			location.href = url;783			return;784		}785		for (const heading of main.querySelectorAll(".breadcrumb, .file-page-title")) heading.remove();786		main.querySelector(".file-meta:not(:last-child)")?.remove();787		source.replaceChildren(...main.childNodes);788	};789	overlay.addEventListener("keydown", (event) => {790		if (event.key === "Escape") close();791		else if (event.key === "ArrowLeft" || event.key === "ArrowRight") {792			event.preventDefault();793			step(event.key === "ArrowLeft" ? -1 : 1);794		}795	});796	// A map link beside the code opens that file here; a folder closes the viewer on its row.797	overlay.addEventListener("click", (event) => {798		const link = event.target.closest(".fv-detail a.atlas-jump");799		if (!link || modified(event)) return;800		const path = link.dataset.path;801		const file = [...root.querySelectorAll(".atlas-file")].find((f) => f.dataset.path === path);802		event.preventDefault();803		if (file) open(file);804		else {805			close();806			jump(path);807		}808	});809	// The Markdown view's rendered/source toggle points at the file page: switch in place.810	overlay.addEventListener("click", (event) => {811		const link = event.target.closest(".fv-source a[href]");812		if (!link || !row || modified(event)) return;813		if (new URL(link.href).pathname !== new URL(row.href).pathname) return;814		event.preventDefault();815		open(row, link.href);816	});817	return open;818}819820// On a phone the nav links fold behind a menu button (2026-10-01). The button only exists with821// JavaScript, so without it the links stay in the bar; the CSS hides them only on `.nav--menu`.822function navMenu() {823	const nav = document.querySelector("body > nav");824	const links = nav?.querySelector(".nav-links");825	if (!links) return;826	links.id = "nav-links";827	const button = element("button", "nav-toggle");828	button.type = "button";829	button.setAttribute("aria-label", "menu");830	button.setAttribute("aria-controls", "nav-links");831	button.setAttribute("aria-expanded", "false");832	button.append(element("span", ""), element("span", ""), element("span", ""));833	const open = () => nav.classList.contains("nav--open");834	const set = (opened) => {835		nav.classList.toggle("nav--open", opened);836		button.setAttribute("aria-expanded", String(opened));837	};838	button.addEventListener("click", () => set(!open()));839	document.addEventListener("click", (event) => {840		if (open() && !nav.contains(event.target)) set(false);841	});842	document.addEventListener("keydown", (event) => {843		if (event.key !== "Escape" || !open()) return;844		set(false);845		button.focus();846	});847	nav.classList.add("nav--menu");848	// Before the links, so tabbing from the open button reaches them next.849	links.before(button);850}851function element(tag, className, text) {852	const node = document.createElement(tag);853	node.className = className;854	if (text !== undefined) node.textContent = text;855	return node;856}857858// Signed in, a repo page's description and details are edited in place: Markdown with a toolbar859// and a preview as the page will show it, pictures and videos picked, dropped or pasted in, and860// the one under the caret sized and placed from a row of controls. The page's HTML is the same861// for everyone; only the cookie signing in sets beside the session brings the controls.862async function repoEditor() {863	const head = document.querySelector(".repo-head");864	if (!head || !/(^|;\s*)kepr_editor=[0-9a-f]{64}/.test(document.cookie)) return;865	const base = `/admin/repos/${location.pathname.split("/")[1]}`;866	const response = await fetch(`${base}/text`).catch(() => null);867	if (!response?.ok) return;868	const texts = await response.json();869	const details = document.querySelector(".repo-details");870	const places = [871		["description", head.querySelector(".repo-desc"), head.querySelector(".repo-desc")],872		["details", details, details.querySelector(".repo-details-body")],873	];874	for (const [field, section, body] of places) {875		section.hidden = false;876		if (field === "description") {877			section.tabIndex = 0;878			section.setAttribute("role", "button");879			section.setAttribute("aria-label", "edit repository description");880			section.classList.add("repo-desc-editable");881			if (!section.textContent.trim()) section.textContent = "add a description";882			const activate = (event) => {883				if (event.target.closest(".editor") || body.querySelector(".editor")) return;884				event.preventDefault();885				editText(base, texts.form, field, body, texts[field]);886			};887			section.addEventListener("click", activate);888			section.addEventListener("keydown", (event) => {889				if (event.target === section && (event.key === "Enter" || event.key === " "))890					activate(event);891			});892			continue;893		}894		const button = element("button", "edit-btn mono", "edit");895		button.type = "button";896		(section.querySelector(".repo-details-head") ?? section).append(button);897		button.addEventListener("click", (event) => {898			event.preventDefault();899			if (!body.querySelector(".editor")) editText(base, texts.form, field, body, texts[field]);900		});901	}902}903904const MEDIA_MARKDOWN = /!\[([^\]]*)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)/g;905const MEDIA_TYPES = "image/png,image/jpeg,image/gif,image/webp,video/mp4,video/webm";906907function editText(base, form, field, body, text) {908	const kept = [...body.childNodes];909	if (field === "description") {910		body.removeAttribute("role");911		body.removeAttribute("tabindex");912		body.removeAttribute("aria-label");913	}914	const input = element("textarea", "editor-input mono");915	input.value = text;916	input.rows = field === "details" ? 16 : 3;917	const preview = element("div", `editor-preview${field === "details" ? " markdown" : ""}`);918	const media = element("div", "editor-media mono");919	const status = element("span", "editor-status");920	const post = (path, fields) => {921		const data = new FormData();922		data.append("form", form);923		for (const [name, value] of Object.entries(fields)) data.append(name, value);924		return fetch(`${base}/${path}`, { method: "POST", body: data });925	};926	let timer = null;927	const changed = () => {928		inspect();929		clearTimeout(timer);930		timer = setTimeout(async () => {931			const answer = await post("preview", { field, value: input.value }).catch(() => null);932			if (!answer?.ok) return;933			// Kepr's own Markdown rendering, raw HTML off: the same markup the page will carry.934			preview.innerHTML = input.value.trim() ? await answer.text() : "";935			preview.dataset.empty = input.value.trim() ? "" : "the README's words show here";936		}, 250);937	};938	const wrap = (before, after = before, fallback = "text") => {939		const [from, to] = [input.selectionStart, input.selectionEnd];940		const chosen = input.value.slice(from, to) || fallback;941		input.setRangeText(before + chosen + after, from, to);942		input.setSelectionRange(from + before.length, from + before.length + chosen.length);943		input.focus();944		changed();945	};946	const prefix = (mark) => {947		const start = input.value.lastIndexOf("\n", input.selectionStart - 1) + 1;948		input.setRangeText(mark, start, start, "end");949		input.focus();950		changed();951	};952	const upload = async (file) => {953		status.textContent = `uploading ${file.name}…`;954		const answer = await post("media", { file }).catch(() => null);955		if (!answer?.ok) {956			status.textContent = answer ? await answer.text() : "upload failed";957			return;958		}959		const { url } = await answer.json();960		const alt = file.name.replace(/\.[^.]+$/, "").replace(/[[\]]/g, "");961		input.setRangeText(962			`\n![${alt}](${url} "width=100 center")\n`,963			input.selectionStart,964			input.selectionEnd,965			"end",966		);967		status.textContent = "";968		input.focus();969		changed();970	};971	const picker = element("input", "");972	picker.type = "file";973	picker.accept = MEDIA_TYPES;974	picker.hidden = true;975	picker.addEventListener("change", () => {976		for (const file of picker.files) upload(file);977		picker.value = "";978	});979	// The picture or video under the caret, with its options, as `![alt](url "options")`.980	const underCaret = () =>981		[...input.value.matchAll(MEDIA_MARKDOWN)].find(982			(m) => input.selectionStart >= m.index && input.selectionStart <= m.index + m[0].length,983		);984	function inspect() {985		const found = field === "details" ? underCaret() : undefined;986		media.hidden = !found;987		if (!found) return;988		const words = (found[3] ?? "").split(/\s+/).filter(Boolean);989		const width = words.find((word) => word.startsWith("width="))?.slice(6) ?? "100";990		const align = words.find((word) => /^(left|center|right)$/.test(word)) ?? "center";991		const loop = words.includes("loop");992		const video = /\.(mp4|webm)$/i.test(found[2]);993		const set = (next) => {994			const options = [`width=${next.width}`, next.align, next.loop && "loop"].filter(Boolean);995			const markdown = `![${found[1]}](${found[2]} "${options.join(" ")}")`;996			const caret = input.selectionStart;997			input.setRangeText(markdown, found.index, found.index + found[0].length);998			input.setSelectionRange(caret, caret);999			changed();1000		};1001		const choice = (label, active, action) => {1002			const b = element("button", `fv-ctrl-btn${active ? " active" : ""}`, label);1003			b.type = "button";1004			b.addEventListener("click", action);1005			return b;1006		};1007		media.replaceChildren(1008			element("span", "editor-label", video ? "video" : "picture"),1009			...["25", "33", "50", "66", "75", "100"].map((w) =>1010				choice(`${w}%`, w === width, () => set({ width: w, align, loop })),1011			),1012			...["left", "center", "right"].map((a) =>1013				choice(a, a === align, () => set({ width, align: a, loop })),1014			),1015			...(video ? [choice("loop like a GIF", loop, () => set({ width, align, loop: !loop }))] : []),1016		);1017	}1018	const save = async (value) => {1019		status.textContent = "saving…";1020		const answer = await post("text", { field, value }).catch(() => null);1021		if (answer?.ok) location.reload();1022		else status.textContent = answer ? await answer.text() : "not saved: offline?";1023	};1024	const cancel = () => {1025		body.replaceChildren(...kept);1026		if (field === "description") {1027			body.tabIndex = 0;1028			body.setAttribute("role", "button");1029			body.setAttribute("aria-label", "edit repository description");1030			body.focus();1031		}1032	};1033	const tool = (label, title, action) => {1034		const b = element("button", "fv-ctrl-btn", label);1035		b.type = "button";1036		b.title = title;1037		b.addEventListener("click", action);1038		return b;1039	};1040	const toolbar = element("div", "editor-toolbar mono");1041	toolbar.append(1042		tool("B", "bold (⌘B)", () => wrap("**")),1043		tool("I", "italic (⌘I)", () => wrap("_")),1044		tool("link", "link (⌘K)", () => wrap("[", "](https://)")),1045		tool("code", "code", () => wrap("`")),1046	);1047	if (field === "details") {1048		toolbar.append(1049			tool("heading", "heading", () => prefix("## ")),1050			tool("list", "list", () => prefix("- ")),1051			tool("quote", "quote", () => prefix("> ")),1052			tool("picture or video", "add a picture, GIF or video (or drop or paste one)", () =>1053				picker.click(),1054			),1055			picker,1056		);1057		input.addEventListener("dragover", (event) => event.preventDefault());1058		input.addEventListener("drop", (event) => {1059			if (event.dataTransfer.files.length === 0) return;1060			event.preventDefault();1061			for (const file of event.dataTransfer.files) upload(file);1062		});1063		input.addEventListener("paste", (event) => {1064			const files = [...event.clipboardData.files];1065			if (files.length === 0) return;1066			event.preventDefault();1067			for (const file of files) upload(file);1068		});1069	}1070	input.addEventListener("input", changed);1071	for (const name of ["click", "keyup"]) input.addEventListener(name, inspect);1072	input.addEventListener("keydown", (event) => {1073		const command = event.metaKey || event.ctrlKey;1074		if (event.key === "Escape") cancel();1075		else if (command && event.key === "Enter") save(input.value);1076		else if (command && event.key === "b") wrap("**");1077		else if (command && event.key === "i") wrap("_");1078		else if (command && event.key === "k") wrap("[", "](https://)");1079		else return;1080		event.preventDefault();1081	});1082	const actions = element("div", "editor-actions mono");1083	actions.append(1084		tool("save", "save (⌘↵)", () => save(input.value)),1085		tool("cancel", "cancel (esc)", cancel),1086		tool("use the README", "clear your words and show the README's again", () => save("")),1087		status,1088	);1089	const panes = element("div", "editor-panes");1090	panes.append(input, preview);1091	const editor = element("div", `editor editor-${field}`);1092	editor.append(toolbar, panes, media, actions);1093	body.replaceChildren(editor);1094	input.focus();1095	changed();1096}10971098// Storage can be missing, refused (private windows, blocked windows) or hold anything; only a1099// list of folder paths is trusted, and otherwise the tree starts closed.1100function remembered(key) {1101	try {1102		const value = JSON.parse(localStorage.getItem(key) ?? "[]");1103		return Array.isArray(value) && value.every((path) => typeof path === "string") ? value : [];1104	} catch {1105		return [];1106	}1107}11081109function remember(key, value) {1110	try {1111		localStorage.setItem(key, JSON.stringify(value));1112	} catch {}1113}11141115function hexStream() {1116	const backdrop = document.querySelector(".hex-backdrop");1117	if (!backdrop) return;1118	let visible = true;1119	const update = () => backdrop.classList.toggle("paused", !visible || document.hidden);1120	new IntersectionObserver(([entry]) => {1121		visible = entry.isIntersecting;1122		update();1123	}).observe(backdrop);1124	document.addEventListener("visibilitychange", update);1125	update();1126}11271128// A CSS duration cannot follow a track's width, so the pace would depend on the messages; set it1129// here so each row slides at its own --speed in px/s, as Kepr 2's canvas did.1130function tickerPace() {1131	for (const track of document.querySelectorAll(".ticker-track")) {1132		const speed = Number(getComputedStyle(track).getPropertyValue("--speed"));1133		if (speed > 0) track.style.animationDuration = `${track.scrollWidth / 2 / speed}s`;1134	}1135}11361137// Widths are only final once Martian Mono has loaded.1138document.fonts.ready.then(tickerPace);1139timeline()1140	.catch((error) => console.error("kepr: the timeline could not load", error))1141	.finally(() => document.documentElement.classList.remove("timeline-pending"));1142copyButtons(document);1143panels();1144issueReplies();1145issueAttachments();1146saveLists();1147atlasPicker();1148repoEditor();1149navMenu();1150lineRanges();1151atlas();1152hexStream();