kepr.js

37.6 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, history's3// scrolling, 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 omit the root heading; nested pages need their own title and way back.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		if (new URL(url).pathname === new URL(open.href).pathname) {272			main.querySelector(".breadcrumb")?.remove();273			main.querySelector(".file-page-title")?.remove();274		}275		host.replaceChildren(...main.childNodes);276		copyButtons(host);277		host.hidden = false;278	};279	const inside = (url) => {280		const base = new URL(open.href).pathname;281		const { pathname } = new URL(url);282		return (pathname === base || pathname.startsWith(`${base}/`)) && !/\.[^/]*$/.test(pathname);283	};284	for (const tab of document.querySelectorAll(".repo-tab[data-panel]")) {285		tab.addEventListener("click", (event) => {286			if (modified(event)) return;287			event.preventDefault();288			if (open === tab && shown !== tab.href) {289				load(tab.href);290				return;291			}292			open?.classList.remove("active");293			if (open === tab) {294				open = null;295				shown = "";296				host.hidden = true;297				return;298			}299			open = tab;300			tab.classList.add("active");301			load(tab.href);302		});303	}304	host.addEventListener("click", (event) => {305		const link = event.target.closest("a[href]");306		if (!link || !open || modified(event) || link.hasAttribute("download")) return;307		if (!inside(link.href)) return;308		event.preventDefault();309		load(link.href);310	});311	host.addEventListener("submit", (event) => {312		const form = event.target;313		if (!open || !inside(form.action)) return;314		event.preventDefault();315		const method = form.method.toUpperCase();316		const data = new FormData(form);317		if (method === "GET") load(`${form.action}?${new URLSearchParams(data)}`);318		else load(form.action, { method, body: data });319	});320}321322// Issue threads (§23): reply and quote fill the composer in place, and quote with text selected in323// a post quotes just that. With nothing selected, quote follows its link, which quotes the post's324// own Markdown. Listening on the document, before the panel's own handler, reaches threads opened325// in a repo's panel too.326function issueReplies() {327	let picked = "";328	// A click collapses the selection, so it is read as the pointer goes down.329	document.addEventListener(330		"pointerdown",331		(event) => {332			const post = event.target.closest?.(".issue-post-actions")?.closest(".issue-post");333			const selection = getSelection();334			picked = post?.contains(selection.anchorNode) ? selection.toString().trim() : "";335		},336		true,337	);338	document.addEventListener(339		"click",340		(event) => {341			const link = event.target.closest(".issue-post-actions a, .issue-composer-to .issues-cancel");342			const form = document.getElementById("reply");343			if (!link || !form || modified(event)) return;344			if (link.dataset.action === "quote" && !picked) return;345			event.preventDefault();346			event.stopPropagation();347			const post = link.closest(".issue-post");348			const to = form.querySelector(".issue-composer-to");349			form.elements.reply_to.value = post?.dataset.entry ?? "";350			to.hidden = !post?.dataset.entry;351			if (post) {352				const name = to.querySelector(".issue-composer-name");353				name.textContent = post.dataset.author;354				name.href = `#${post.id}`;355			}356			const body = form.elements.body;357			if (link.dataset.action === "quote") {358				const quote = `${picked.replace(/^/gm, "> ")}\n\n`;359				body.value = body.value.trim() ? `${body.value.trimEnd()}\n\n${quote}` : quote;360				picked = "";361			}362			body.focus();363			body.scrollIntoView({ block: "center" });364		},365		true,366	);367}368369// History and the Atlas's save picker hold one page of saves; scrolling to the end of either370// brings in the next page's rows. The pager is for pages without JavaScript.371function saveLists() {372	for (const list of document.querySelectorAll(".save-list")) {373		const observer = new IntersectionObserver(374			async ([entry]) => {375				const older = list.querySelector(".pager-older");376				if (!entry?.isIntersecting || !older) return;377				observer.disconnect();378				const main = await fetchMain(older.href);379				const next = main?.querySelector(`.save-list[data-list="${list.dataset.list}"]`);380				if (!next) return;381				next.querySelector(".pager a:not(.pager-older)")?.remove();382				list.querySelector(".pager").replaceWith(...next.childNodes);383				watch();384			},385			{ root: list },386		);387		const watch = () => {388			const older = list.querySelector(".pager-older");389			if (older) observer.observe(older);390		};391		watch();392	}393}394395// `#L42` works through CSS :target alone; a range `#L42-L50` needs marking line by line.396function lineRanges() {397	const code = document.querySelector(".code");398	if (!code) return;399	let anchor = null;400	const mark = () => {401		for (const marked of code.querySelectorAll(".line.hl")) marked.classList.remove("hl");402		const match = /^#L(\d+)(?:-L(\d+))?$/.exec(location.hash);403		if (!match) return;404		const from = Number(match[1]);405		const to = Number(match[2] ?? match[1]);406		anchor = from;407		for (let n = Math.min(from, to); n <= Math.max(from, to); n++) {408			document.getElementById(`L${n}`)?.classList.add("hl");409		}410		document.getElementById(`L${Math.min(from, to)}`)?.scrollIntoView({ block: "center" });411	};412	code.addEventListener("click", (event) => {413		const link = event.target.closest(".ln");414		if (!link || !event.shiftKey || anchor === null) return;415		event.preventDefault();416		const n = Number(link.textContent);417		history.replaceState(null, "", `#L${Math.min(anchor, n)}-L${Math.max(anchor, n)}`);418		mark();419	});420	window.addEventListener("hashchange", mark);421	mark();422}423424// The Atlas (§21.5): each row's detail panel is fetched on hover or select and kept for the page's425// life; the filter narrows by filename; which folders are open is remembered per repo in this browser.426function atlas() {427	const root = document.querySelector(".atlas");428	const filter = document.querySelector(".atlas-filter");429	if (!root || !filter) return;430	const panel = root.querySelector(".atlas-panel");431	const folders = [...root.querySelectorAll(".atlas-folder")];432	const files = [...root.querySelectorAll(".atlas-file")];433	// Its height is the closed tree's, fixed before any folder opens; opening one scrolls within.434	root.style.height = `${root.offsetHeight}px`;435	root.style.overflowY = "hidden";436	const key = `kepr:atlas:${root.dataset.repo}`;437	const opened = new Set(remembered(key));438	// `?open=<folder>` from a file page's breadcrumb unfolds that folder, without remembering it.439	const unfold = new URLSearchParams(location.search).get("open");440	const onPath = (path) => unfold !== null && `${unfold}/`.startsWith(`${path}/`);441	for (const folder of folders) {442		folder.open = opened.has(folder.dataset.path) || onPath(folder.dataset.path);443		folder.addEventListener("toggle", () => {444			if (filter.value.trim()) return;445			if (folder.open) opened.add(folder.dataset.path);446			else opened.delete(folder.dataset.path);447			remember(key, [...opened]);448		});449	}450	const panels = new Map();451	const panelFor = (path) => {452		if (!panels.has(path)) {453			const query = new URLSearchParams({ path });454			if (root.dataset.at) query.set("at", root.dataset.at);455			const text = fetch(`/${root.dataset.repo}/atlas/panel?${query}`)456				.then((response) => (response.ok ? response.text() : Promise.reject()))457				.catch(() => {458					panels.delete(path);459					return "";460				});461			panels.set(path, text);462		}463		return panels.get(path).then((text) => {464			const template = document.createElement("template");465			template.innerHTML = text;466			return template.content;467		});468	};469	let selected = null;470	const show = async (row) => {471		selected?.classList.remove("selected");472		selected = row;473		row.classList.add("selected");474		const content = await panelFor(row.dataset.path ?? `${row.parentElement.dataset.path}/`);475		if (selected === row) panel.replaceChildren(content);476	};477	for (const row of root.querySelectorAll(".atlas-row")) {478		row.addEventListener("pointerenter", (event) => {479			if (event.pointerType === "mouse") show(row);480		});481		row.addEventListener("focus", () => show(row));482	}483	// A map link in a panel jumps to its row, opening the folders above it.484	const jump = (path) => {485		const row = path.endsWith("/")486			? folders.find((folder) => `${folder.dataset.path}/` === path)?.firstElementChild487			: files.find((file) => file.dataset.path === path);488		if (!row) return false;489		for (const folder of folders) folder.open ||= path.startsWith(`${folder.dataset.path}/`);490		show(row);491		row.scrollIntoView({ block: "nearest" });492		return true;493	};494	panel.addEventListener("click", (event) => {495		const link = event.target.closest("a.atlas-jump");496		if (link && !modified(event) && jump(link.dataset.path)) event.preventDefault();497	});498	const viewer = fileViewer(root, jump, panelFor);499	for (const file of files) {500		file.addEventListener("click", (event) => {501			if (modified(event)) return;502			event.preventDefault();503			viewer(file);504		});505	}506	const target = folders.find((folder) => folder.dataset.path === unfold)?.firstElementChild;507	if (target) {508		show(target);509		target.scrollIntoView({ block: "center" });510	}511	filter.addEventListener("input", () => {512		const query = filter.value.trim().toLowerCase();513		for (const file of files) file.hidden = query !== "" && !file.dataset.name.includes(query);514		for (const folder of folders) {515			folder.hidden = query !== "" && !folder.querySelector(".atlas-file:not([hidden])");516			folder.open = query !== "" || opened.has(folder.dataset.path);517		}518	});519	// One button opens every folder, or, when they all are, closes them all.520	const fold = document.querySelector(".atlas-fold-btn");521	const label = () => {522		fold.textContent = folders.every((folder) => folder.open) ? "collapse all" : "expand all";523	};524	fold.addEventListener("click", () => {525		const open = !folders.every((folder) => folder.open);526		for (const folder of folders) folder.open = open;527		label();528	});529	for (const folder of folders) folder.addEventListener("toggle", label);530	label();531	fold.hidden = folders.length === 0;532	// The filter waits behind a search button, and folds back into it when left empty.533	const search = document.querySelector(".atlas-search-btn");534	search.addEventListener("click", () => {535		search.hidden = true;536		filter.hidden = false;537		filter.focus();538	});539	filter.addEventListener("blur", () => {540		if (filter.value.trim() !== "") return;541		filter.hidden = true;542		search.hidden = false;543	});544	search.hidden = false;545	panel.hidden = false;546}547548// Kepr 2's Atlas picker: its saves arrive when it first opens, filtered as you type; a click549// outside or Escape closes it.550function atlasPicker() {551	const picker = document.querySelector(".atlas-picker");552	if (!picker) return;553	const filter = picker.querySelector(".atlas-picker-filter");554	const list = picker.querySelector(".atlas-picker-list");555	let rows = [];556	const narrow = () => {557		const query = filter.value.trim().toLowerCase();558		for (const row of rows) {559			row.hidden = query !== "" && !row.textContent.toLowerCase().includes(query);560		}561	};562	filter.addEventListener("input", narrow);563	let loading = null;564	picker.addEventListener("toggle", () => {565		if (!picker.open) return;566		filter.focus();567		if (loading) return;568		loading = fetch(list.dataset.src)569			.then((response) => (response.ok ? response.text() : Promise.reject()))570			.then((text) => {571				const template = document.createElement("template");572				template.innerHTML = text;573				list.replaceChildren(template.content);574				rows = [...list.children];575				narrow();576			})577			.catch(() => {578				loading = null;579			});580	});581	document.addEventListener("click", (event) => {582		if (!picker.contains(event.target)) picker.open = false;583	});584	picker.addEventListener("keydown", (event) => {585		if (event.key === "Escape") picker.open = false;586	});587	filter.hidden = false;588}589590// Files open in a viewer over the page, as in Kepr 2's Atlas: the file page's content with the591// row's detail panel beside it, and controls for text size, wrapping, raw, download and the592// neighbouring files. Escape closes it; the arrow keys step through the files.593function fileViewer(root, jump, panelFor) {594	let [row, size, wrap] = [null, 12, false];595	const overlay = element("div", "fv-overlay");596	overlay.tabIndex = -1;597	overlay.setAttribute("role", "dialog");598	overlay.setAttribute("aria-modal", "true");599	const close = () => {600		overlay.remove();601		row?.focus();602		row = null;603	};604	const step = (by) => {605		const rows = [...root.querySelectorAll(".atlas-file")].filter((file) => !file.hidden);606		const next = rows[rows.indexOf(row) + by];607		if (next) open(next);608	};609	const restyle = () => {610		overlay.style.setProperty("--fv-size", `${size}px`);611		overlay.classList.toggle("fv-wrap", wrap);612	};613	const open = async (file, url = file.href) => {614		row = file;615		const rows = [...root.querySelectorAll(".atlas-file")].filter((each) => !each.hidden);616		const index = rows.indexOf(file);617		const path = file.dataset.path;618		const name = path.split("/").pop();619		const raw = new URL(file.href);620		raw.pathname = raw.pathname.replace(/^(\/[^/]+)\/files\//, "$1/raw/");621		const button = (text, action, className = "fv-ctrl-btn") => {622			const b = element("button", className, text);623			b.type = "button";624			b.addEventListener("click", action);625			return b;626		};627		const link = (text, download) => {628			const a = element("a", "fv-ctrl-btn", text);629			a.href = raw.href;630			if (download) a.download = name;631			return a;632		};633		const source = element("div", "fv-source", "loading…");634		const panel = element("aside", "fv-detail");635		panelFor(path).then((content) => {636			if (row === file) panel.replaceChildren(content);637		});638		const header = element("div", "fv-header");639		const title = element("div", "fv-title");640		title.append(element("span", "fv-name", name), element("span", "fv-path mono", path));641		const controls = element("div", "fv-controls mono");642		controls.append(643			button("A−", () => {644				size = Math.max(9, size - 1);645				restyle();646			}),647			button("A+", () => {648				size = Math.min(20, size + 1);649				restyle();650			}),651			button("⇌ wrap", (event) => {652				wrap = !wrap;653				event.currentTarget.classList.toggle("active", wrap);654				restyle();655			}),656			link("raw", false),657			link("download", true),658		);659		controls.children[2].classList.toggle("active", wrap);660		const nav = element("div", "fv-nav mono");661		const back = button("←", () => step(-1), "fv-ctrl-btn");662		const forward = button("→", () => step(1), "fv-ctrl-btn");663		back.disabled = index <= 0;664		forward.disabled = index >= rows.length - 1;665		nav.append(back, element("span", "fv-pos", `${index + 1}/${rows.length}`), forward);666		header.append(button("×", close, "fv-close"), title, controls, nav);667		const body = element("div", "fv-body");668		body.append(source, panel);669		overlay.replaceChildren(header, body);670		restyle();671		if (!overlay.isConnected) document.body.append(overlay);672		overlay.focus();673		const main = await fetchMain(url);674		if (row !== file) return;675		if (!main) {676			location.href = url;677			return;678		}679		for (const heading of main.querySelectorAll(".breadcrumb, .file-page-title")) heading.remove();680		main.querySelector(".file-meta:not(:last-child)")?.remove();681		source.replaceChildren(...main.childNodes);682	};683	overlay.addEventListener("keydown", (event) => {684		if (event.key === "Escape") close();685		else if (event.key === "ArrowLeft" || event.key === "ArrowRight") {686			event.preventDefault();687			step(event.key === "ArrowLeft" ? -1 : 1);688		}689	});690	// A map link beside the code opens that file here; a folder closes the viewer on its row.691	overlay.addEventListener("click", (event) => {692		const link = event.target.closest(".fv-detail a.atlas-jump");693		if (!link || modified(event)) return;694		const path = link.dataset.path;695		const file = [...root.querySelectorAll(".atlas-file")].find((f) => f.dataset.path === path);696		event.preventDefault();697		if (file) open(file);698		else {699			close();700			jump(path);701		}702	});703	// The Markdown view's rendered/source toggle points at the file page: switch in place.704	overlay.addEventListener("click", (event) => {705		const link = event.target.closest(".fv-source a[href]");706		if (!link || !row || modified(event)) return;707		if (new URL(link.href).pathname !== new URL(row.href).pathname) return;708		event.preventDefault();709		open(row, link.href);710	});711	return open;712}713714// On a phone the nav links fold behind a menu button (2026-10-01). The button only exists with715// JavaScript, so without it the links stay in the bar; the CSS hides them only on `.nav--menu`.716function navMenu() {717	const nav = document.querySelector("body > nav");718	const links = nav?.querySelector(".nav-links");719	if (!links) return;720	links.id = "nav-links";721	const button = element("button", "nav-toggle");722	button.type = "button";723	button.setAttribute("aria-label", "menu");724	button.setAttribute("aria-controls", "nav-links");725	button.setAttribute("aria-expanded", "false");726	button.append(element("span", ""), element("span", ""), element("span", ""));727	const open = () => nav.classList.contains("nav--open");728	const set = (opened) => {729		nav.classList.toggle("nav--open", opened);730		button.setAttribute("aria-expanded", String(opened));731	};732	button.addEventListener("click", () => set(!open()));733	document.addEventListener("click", (event) => {734		if (open() && !nav.contains(event.target)) set(false);735	});736	document.addEventListener("keydown", (event) => {737		if (event.key !== "Escape" || !open()) return;738		set(false);739		button.focus();740	});741	nav.classList.add("nav--menu");742	// Before the links, so tabbing from the open button reaches them next.743	links.before(button);744}745function element(tag, className, text) {746	const node = document.createElement(tag);747	node.className = className;748	if (text !== undefined) node.textContent = text;749	return node;750}751752// Signed in, a repo page's description and details are edited in place: Markdown with a toolbar753// and a preview as the page will show it, pictures and videos picked, dropped or pasted in, and754// the one under the caret sized and placed from a row of controls. The page's HTML is the same755// for everyone; only the cookie signing in sets beside the session brings the controls.756async function repoEditor() {757	const head = document.querySelector(".repo-head");758	if (!head || !/(^|;\s*)kepr_editor=[0-9a-f]{64}/.test(document.cookie)) return;759	const base = `/admin/repos/${location.pathname.split("/")[1]}`;760	const response = await fetch(`${base}/text`).catch(() => null);761	if (!response?.ok) return;762	const texts = await response.json();763	const details = document.querySelector(".repo-details");764	const places = [765		["description", head.querySelector(".repo-desc"), head.querySelector(".repo-desc")],766		["details", details, details.querySelector(".repo-details-body")],767	];768	for (const [field, section, body] of places) {769		section.hidden = false;770		if (field === "description") {771			section.tabIndex = 0;772			section.setAttribute("role", "button");773			section.setAttribute("aria-label", "edit repository description");774			section.classList.add("repo-desc-editable");775			if (!section.textContent.trim()) section.textContent = "add a description";776			const activate = (event) => {777				if (event.target.closest(".editor") || body.querySelector(".editor")) return;778				event.preventDefault();779				editText(base, texts.form, field, body, texts[field]);780			};781			section.addEventListener("click", activate);782			section.addEventListener("keydown", (event) => {783				if (event.target === section && (event.key === "Enter" || event.key === " "))784					activate(event);785			});786			continue;787		}788		const button = element("button", "edit-btn mono", "edit");789		button.type = "button";790		(section.querySelector(".repo-details-head") ?? section).append(button);791		button.addEventListener("click", (event) => {792			event.preventDefault();793			if (!body.querySelector(".editor")) editText(base, texts.form, field, body, texts[field]);794		});795	}796}797798const MEDIA_MARKDOWN = /!\[([^\]]*)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)/g;799const MEDIA_TYPES = "image/png,image/jpeg,image/gif,image/webp,video/mp4,video/webm";800801function editText(base, form, field, body, text) {802	const kept = [...body.childNodes];803	if (field === "description") {804		body.removeAttribute("role");805		body.removeAttribute("tabindex");806		body.removeAttribute("aria-label");807	}808	const input = element("textarea", "editor-input mono");809	input.value = text;810	input.rows = field === "details" ? 16 : 3;811	const preview = element("div", `editor-preview${field === "details" ? " markdown" : ""}`);812	const media = element("div", "editor-media mono");813	const status = element("span", "editor-status");814	const post = (path, fields) => {815		const data = new FormData();816		data.append("form", form);817		for (const [name, value] of Object.entries(fields)) data.append(name, value);818		return fetch(`${base}/${path}`, { method: "POST", body: data });819	};820	let timer = null;821	const changed = () => {822		inspect();823		clearTimeout(timer);824		timer = setTimeout(async () => {825			const answer = await post("preview", { field, value: input.value }).catch(() => null);826			if (!answer?.ok) return;827			// Kepr's own Markdown rendering, raw HTML off: the same markup the page will carry.828			preview.innerHTML = input.value.trim() ? await answer.text() : "";829			preview.dataset.empty = input.value.trim() ? "" : "the README's words show here";830		}, 250);831	};832	const wrap = (before, after = before, fallback = "text") => {833		const [from, to] = [input.selectionStart, input.selectionEnd];834		const chosen = input.value.slice(from, to) || fallback;835		input.setRangeText(before + chosen + after, from, to);836		input.setSelectionRange(from + before.length, from + before.length + chosen.length);837		input.focus();838		changed();839	};840	const prefix = (mark) => {841		const start = input.value.lastIndexOf("\n", input.selectionStart - 1) + 1;842		input.setRangeText(mark, start, start, "end");843		input.focus();844		changed();845	};846	const upload = async (file) => {847		status.textContent = `uploading ${file.name}…`;848		const answer = await post("media", { file }).catch(() => null);849		if (!answer?.ok) {850			status.textContent = answer ? await answer.text() : "upload failed";851			return;852		}853		const { url } = await answer.json();854		const alt = file.name.replace(/\.[^.]+$/, "").replace(/[[\]]/g, "");855		input.setRangeText(856			`\n![${alt}](${url} "width=100 center")\n`,857			input.selectionStart,858			input.selectionEnd,859			"end",860		);861		status.textContent = "";862		input.focus();863		changed();864	};865	const picker = element("input", "");866	picker.type = "file";867	picker.accept = MEDIA_TYPES;868	picker.hidden = true;869	picker.addEventListener("change", () => {870		for (const file of picker.files) upload(file);871		picker.value = "";872	});873	// The picture or video under the caret, with its options, as `![alt](url "options")`.874	const underCaret = () =>875		[...input.value.matchAll(MEDIA_MARKDOWN)].find(876			(m) => input.selectionStart >= m.index && input.selectionStart <= m.index + m[0].length,877		);878	function inspect() {879		const found = field === "details" ? underCaret() : undefined;880		media.hidden = !found;881		if (!found) return;882		const words = (found[3] ?? "").split(/\s+/).filter(Boolean);883		const width = words.find((word) => word.startsWith("width="))?.slice(6) ?? "100";884		const align = words.find((word) => /^(left|center|right)$/.test(word)) ?? "center";885		const loop = words.includes("loop");886		const video = /\.(mp4|webm)$/i.test(found[2]);887		const set = (next) => {888			const options = [`width=${next.width}`, next.align, next.loop && "loop"].filter(Boolean);889			const markdown = `![${found[1]}](${found[2]} "${options.join(" ")}")`;890			const caret = input.selectionStart;891			input.setRangeText(markdown, found.index, found.index + found[0].length);892			input.setSelectionRange(caret, caret);893			changed();894		};895		const choice = (label, active, action) => {896			const b = element("button", `fv-ctrl-btn${active ? " active" : ""}`, label);897			b.type = "button";898			b.addEventListener("click", action);899			return b;900		};901		media.replaceChildren(902			element("span", "editor-label", video ? "video" : "picture"),903			...["25", "33", "50", "66", "75", "100"].map((w) =>904				choice(`${w}%`, w === width, () => set({ width: w, align, loop })),905			),906			...["left", "center", "right"].map((a) =>907				choice(a, a === align, () => set({ width, align: a, loop })),908			),909			...(video ? [choice("loop like a GIF", loop, () => set({ width, align, loop: !loop }))] : []),910		);911	}912	const save = async (value) => {913		status.textContent = "saving…";914		const answer = await post("text", { field, value }).catch(() => null);915		if (answer?.ok) location.reload();916		else status.textContent = answer ? await answer.text() : "not saved: offline?";917	};918	const cancel = () => {919		body.replaceChildren(...kept);920		if (field === "description") {921			body.tabIndex = 0;922			body.setAttribute("role", "button");923			body.setAttribute("aria-label", "edit repository description");924			body.focus();925		}926	};927	const tool = (label, title, action) => {928		const b = element("button", "fv-ctrl-btn", label);929		b.type = "button";930		b.title = title;931		b.addEventListener("click", action);932		return b;933	};934	const toolbar = element("div", "editor-toolbar mono");935	toolbar.append(936		tool("B", "bold (⌘B)", () => wrap("**")),937		tool("I", "italic (⌘I)", () => wrap("_")),938		tool("link", "link (⌘K)", () => wrap("[", "](https://)")),939		tool("code", "code", () => wrap("`")),940	);941	if (field === "details") {942		toolbar.append(943			tool("heading", "heading", () => prefix("## ")),944			tool("list", "list", () => prefix("- ")),945			tool("quote", "quote", () => prefix("> ")),946			tool("picture or video", "add a picture, GIF or video (or drop or paste one)", () =>947				picker.click(),948			),949			picker,950		);951		input.addEventListener("dragover", (event) => event.preventDefault());952		input.addEventListener("drop", (event) => {953			if (event.dataTransfer.files.length === 0) return;954			event.preventDefault();955			for (const file of event.dataTransfer.files) upload(file);956		});957		input.addEventListener("paste", (event) => {958			const files = [...event.clipboardData.files];959			if (files.length === 0) return;960			event.preventDefault();961			for (const file of files) upload(file);962		});963	}964	input.addEventListener("input", changed);965	for (const name of ["click", "keyup"]) input.addEventListener(name, inspect);966	input.addEventListener("keydown", (event) => {967		const command = event.metaKey || event.ctrlKey;968		if (event.key === "Escape") cancel();969		else if (command && event.key === "Enter") save(input.value);970		else if (command && event.key === "b") wrap("**");971		else if (command && event.key === "i") wrap("_");972		else if (command && event.key === "k") wrap("[", "](https://)");973		else return;974		event.preventDefault();975	});976	const actions = element("div", "editor-actions mono");977	actions.append(978		tool("save", "save (⌘↵)", () => save(input.value)),979		tool("cancel", "cancel (esc)", cancel),980		tool("use the README", "clear your words and show the README's again", () => save("")),981		status,982	);983	const panes = element("div", "editor-panes");984	panes.append(input, preview);985	const editor = element("div", `editor editor-${field}`);986	editor.append(toolbar, panes, media, actions);987	body.replaceChildren(editor);988	input.focus();989	changed();990}991992// Storage can be missing, refused (private windows, blocked windows) or hold anything; only a993// list of folder paths is trusted, and otherwise the tree starts closed.994function remembered(key) {995	try {996		const value = JSON.parse(localStorage.getItem(key) ?? "[]");997		return Array.isArray(value) && value.every((path) => typeof path === "string") ? value : [];998	} catch {999		return [];1000	}1001}10021003function remember(key, value) {1004	try {1005		localStorage.setItem(key, JSON.stringify(value));1006	} catch {}1007}10081009function hexStream() {1010	const backdrop = document.querySelector(".hex-backdrop");1011	if (!backdrop) return;1012	let visible = true;1013	const update = () => backdrop.classList.toggle("paused", !visible || document.hidden);1014	new IntersectionObserver(([entry]) => {1015		visible = entry.isIntersecting;1016		update();1017	}).observe(backdrop);1018	document.addEventListener("visibilitychange", update);1019	update();1020}10211022// A CSS duration cannot follow a track's width, so the pace would depend on the messages; set it1023// here so each row slides at its own --speed in px/s, as Kepr 2's canvas did.1024function tickerPace() {1025	for (const track of document.querySelectorAll(".ticker-track")) {1026		const speed = Number(getComputedStyle(track).getPropertyValue("--speed"));1027		if (speed > 0) track.style.animationDuration = `${track.scrollWidth / 2 / speed}s`;1028	}1029}10301031// Widths are only final once Martian Mono has loaded.1032document.fonts.ready.then(tickerPace);1033timeline()1034	.catch((error) => console.error("kepr: the timeline could not load", error))1035	.finally(() => document.documentElement.classList.remove("timeline-pending"));1036copyButtons(document);1037panels();1038issueReplies();1039saveLists();1040atlasPicker();1041repoEditor();1042navMenu();1043lineRanges();1044atlas();1045hexStream();