kepr.js

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