kepr.js

22.3 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, and the profile's4// glow.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.25function timeline() {26	const svg = document.querySelector("svg.timeline");27	if (!svg) return;28	const css = getComputedStyle(document.documentElement);29	const saves = [...svg.querySelectorAll(".dot")]30		.map((dot) => {31			const [id, message, meta] = (dot.querySelector("title")?.textContent ?? "").split("\n");32			const [, color, alpha] = KINDS.find(([kind]) => kind.test(message)) ?? [33				null,34				"text-secondary",35				0.8,36			];37			const fill = css.getPropertyValue(`--${color}`).trim();38			return { href: dot.getAttribute("href"), id, message, meta, fill, alpha, t: +dot.dataset.t };39		})40		.sort((a, b) => a.t - b.t);41	if (saves.length === 0) return;42	const canvas = document.createElement("canvas");43	canvas.className = "timeline-canvas";44	canvas.setAttribute("role", "img");45	canvas.setAttribute("aria-label", svg.getAttribute("aria-label"));46	svg.replaceWith(canvas);47	const ctx = canvas.getContext("2d");48	const tip = document.createElement("div");49	tip.className = "timeline-tip";50	tip.hidden = true;51	document.body.append(tip);52	const reduce = matchMedia("(prefers-reduced-motion: reduce)");53	let [width, height, strip, radius, offset] = [0, 0, 0, 0, 0];54	// Laid out by time, a repo's bursts sat between long empty stretches the drift crawled55	// through. Each dot instead sits after the one before by the gap between them, on a log scale56	// and capped, so a busy day stays tight and a quiet month reads as a pause, not a wait.57	const spacing = (seconds) => radius + 8 + Math.min(96, 12 * Math.log2(1 + seconds / 3600));58	const resize = () => {59		width = canvas.parentElement.getBoundingClientRect().width;60		// Kepr 2's band was tall to hold two lanes; with one line, only room for the dots and label.61		height = 64;62		canvas.width = Math.round(width * devicePixelRatio);63		canvas.height = Math.round(height * devicePixelRatio);64		canvas.style.width = `${width}px`;65		canvas.style.height = `${height}px`;66		ctx.setTransform(devicePixelRatio, 0, 0, devicePixelRatio, 0, 0);67		radius = 4;68		let x = 0;69		saves.forEach((save, i) => {70			if (i > 0) x += spacing(save.t - saves[i - 1].t);71			save.x = x;72		});73		// The seam is one more capped pause, or the rest of the view when the saves are few.74		strip = Math.max(x + spacing(Number.POSITIVE_INFINITY), width);75		offset = x - width * 0.82;76	};77	// Every visible copy of each x on the looping strip.78	const onScreen = (x, margin) => {79		const shift = ((offset % strip) + strip) % strip;80		const copies = [];81		for (let sx = x - shift - strip; sx < width + margin; sx += strip) {82			if (sx > -margin) copies.push(sx);83		}84		return copies;85	};86	const hit = (event) => {87		const box = canvas.getBoundingClientRect();88		const [mx, my] = [event.clientX - box.left, event.clientY - box.top];89		if (Math.abs(my - height / 2) > radius + 7) return null;90		return (91			saves.find((save) => onScreen(save.x, 0).some((x) => Math.abs(mx - x) < radius + 7)) ?? null92		);93	};94	let [hovered, drag, dragFrom, downX, lastX, velocity, resumeAt, lastFrame] = [95		null,96		null,97		0,98		0,99		0,100		0,101		0,102		0,103	];104	const hover = (save, event) => {105		if (save !== hovered) {106			hovered = save;107			tip.hidden = save === null;108			if (save)109				tip.replaceChildren(110					line("tip-id", save.id),111					line("tip-msg", save.message),112					line("tip-meta", save.meta),113				);114		}115		if (save) {116			const left = event.clientX + 14;117			tip.style.left = `${left + 340 > innerWidth ? Math.max(8, event.clientX - 354) : left}px`;118			tip.style.top = `${event.clientY - 10}px`;119		}120		canvas.style.cursor = save ? "pointer" : drag === null ? "grab" : "grabbing";121	};122	const draw = (time) => {123		const dt = lastFrame ? Math.min((time - lastFrame) / 1000, 0.1) : 0;124		lastFrame = time;125		if (drag === null && hovered === null) {126			if (Math.abs(velocity) > 0.5) {127				offset -= velocity;128				velocity *= 0.92;129			} else if (!reduce.matches && time >= resumeAt) offset += 20 * dt;130		}131		const y = height / 2;132		ctx.clearRect(0, 0, width, height);133		ctx.lineWidth = 1;134		ctx.globalAlpha = 0.7;135		ctx.strokeStyle = css.getPropertyValue("--text-muted");136		ctx.setLineDash([4, 4]);137		ctx.beginPath();138		ctx.moveTo(0, y);139		ctx.lineTo(width, y);140		ctx.stroke();141		ctx.setLineDash([]);142		ctx.font = '10px "Martian Mono", monospace';143		ctx.textAlign = "center";144		for (const save of saves) {145			for (const x of onScreen(save.x, 10)) {146				ctx.globalAlpha = hovered === null ? save.alpha : hovered === save ? 1 : save.alpha * 0.6;147				ctx.fillStyle = save.fill;148				ctx.beginPath();149				ctx.arc(x, y, radius, 0, Math.PI * 2);150				ctx.fill();151				if (hovered === save) {152					ctx.fillStyle = css.getPropertyValue("--accent");153					ctx.fillText(save.id.slice(0, 6), x, y - radius - 6);154				}155			}156		}157		ctx.globalAlpha = 1;158		requestAnimationFrame(draw);159	};160	canvas.addEventListener("pointerdown", (event) => {161		[drag, dragFrom, downX, lastX, velocity] = [162			event.clientX,163			offset,164			event.clientX,165			event.clientX,166			0,167		];168		canvas.setPointerCapture(event.pointerId);169	});170	canvas.addEventListener("pointermove", (event) => {171		if (drag !== null) {172			offset = dragFrom - (event.clientX - drag);173			velocity = velocity * 0.6 + (event.clientX - lastX) * 0.4;174			lastX = event.clientX;175		}176		if (event.pointerType === "mouse") hover(hit(event), event);177	});178	const release = () => {179		drag = null;180		resumeAt = performance.now() + 900;181	};182	canvas.addEventListener("pointerup", (event) => {183		release();184		const save = Math.abs(event.clientX - downX) > 4 ? null : hit(event);185		if (save) location.href = save.href;186	});187	canvas.addEventListener("pointercancel", release);188	canvas.addEventListener("pointerleave", (event) => {189		if (drag === null) hover(null, event);190	});191	addEventListener("resize", resize);192	resize();193	requestAnimationFrame(draw);194}195196function line(className, text) {197	const div = document.createElement("div");198	div.className = className;199	div.textContent = text ?? "";200	return div;201}202203function copyButtons(root) {204	for (const button of root.querySelectorAll("button[data-copy]")) {205		const label = button.textContent;206		button.hidden = false;207		button.addEventListener("click", async () => {208			await navigator.clipboard.writeText(button.dataset.copy);209			button.textContent = "copied";210			button.classList.add("copied");211			setTimeout(() => {212				button.textContent = label;213				button.classList.remove("copied");214			}, 1400);215		});216	}217}218219// A Kepr page's <main>, its links made absolute so they point where they did on their own page220// (after any redirect). An error page's <main> comes back too, so a refused form shows why; null if221// nothing came back, and the caller then goes to the page itself.222async function fetchMain(url, init) {223	try {224		const response = await fetch(url, init);225		const page = new DOMParser().parseFromString(await response.text(), "text/html");226		const main = page.querySelector("main");227		for (const link of main?.querySelectorAll("a[href]:not([href^='#'])") ?? []) {228			link.href = new URL(link.getAttribute("href"), response.url || url).href;229		}230		return main;231	} catch {232		return null;233	}234}235236// A click the browser should handle itself: a new tab or window, or a download.237function modified(event) {238	return event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey;239}240241// §21.9's panels open inline under the tabs, as Kepr 2's did: the panel page without its heading.242// The panel's own pages (an issue, the report form) and its forms stay inside it; a link elsewhere,243// or to a file (a download), navigates. The open tab takes the panel back to its first page, and244// closes it from there.245function panels() {246	const host = document.querySelector(".repo-panel");247	if (!host) return;248	let open = null;249	let shown = "";250	const load = async (url, init) => {251		shown = url;252		const main = await fetchMain(url, init);253		if (shown !== url) return;254		if (!main) {255			location.href = url;256			return;257		}258		main.querySelector(".breadcrumb")?.remove();259		main.querySelector(".file-page-title")?.remove();260		host.replaceChildren(...main.childNodes);261		copyButtons(host);262		host.hidden = false;263	};264	const inside = (url) => {265		const base = new URL(open.href).pathname;266		const { pathname } = new URL(url);267		return (pathname === base || pathname.startsWith(`${base}/`)) && !/\.[^/]*$/.test(pathname);268	};269	for (const tab of document.querySelectorAll(".repo-tab[data-panel]")) {270		tab.addEventListener("click", (event) => {271			if (modified(event)) return;272			event.preventDefault();273			if (open === tab && shown !== tab.href) {274				load(tab.href);275				return;276			}277			open?.classList.remove("active");278			if (open === tab) {279				open = null;280				shown = "";281				host.hidden = true;282				return;283			}284			open = tab;285			tab.classList.add("active");286			load(tab.href);287		});288	}289	host.addEventListener("click", (event) => {290		const link = event.target.closest("a[href]");291		if (!link || !open || modified(event) || link.hasAttribute("download")) return;292		if (!inside(link.href)) return;293		event.preventDefault();294		load(link.href);295	});296	host.addEventListener("submit", (event) => {297		const form = event.target;298		if (!open || !inside(form.action)) return;299		event.preventDefault();300		const method = form.method.toUpperCase();301		const data = new FormData(form);302		if (method === "GET") load(`${form.action}?${new URLSearchParams(data)}`);303		else load(form.action, { method, body: data });304	});305}306307// History and the Atlas's save picker hold one page of saves; scrolling to the end of either308// brings in the next page's rows. The pager is for pages without JavaScript.309function saveLists() {310	for (const list of document.querySelectorAll(".save-list")) {311		const observer = new IntersectionObserver(312			async ([entry]) => {313				const older = list.querySelector(".pager-older");314				if (!entry?.isIntersecting || !older) return;315				observer.disconnect();316				const main = await fetchMain(older.href);317				const next = main?.querySelector(`.save-list[data-list="${list.dataset.list}"]`);318				if (!next) return;319				next.querySelector(".pager a:not(.pager-older)")?.remove();320				list.querySelector(".pager").replaceWith(...next.childNodes);321				watch();322			},323			{ root: list },324		);325		const watch = () => {326			const older = list.querySelector(".pager-older");327			if (older) observer.observe(older);328		};329		watch();330	}331}332333// `#L42` works through CSS :target alone; a range `#L42-L50` needs marking line by line.334function lineRanges() {335	const code = document.querySelector(".code");336	if (!code) return;337	let anchor = null;338	const mark = () => {339		for (const marked of code.querySelectorAll(".line.hl")) marked.classList.remove("hl");340		const match = /^#L(\d+)(?:-L(\d+))?$/.exec(location.hash);341		if (!match) return;342		const from = Number(match[1]);343		const to = Number(match[2] ?? match[1]);344		anchor = from;345		for (let n = Math.min(from, to); n <= Math.max(from, to); n++) {346			document.getElementById(`L${n}`)?.classList.add("hl");347		}348		document.getElementById(`L${Math.min(from, to)}`)?.scrollIntoView({ block: "center" });349	};350	code.addEventListener("click", (event) => {351		const link = event.target.closest(".ln");352		if (!link || !event.shiftKey || anchor === null) return;353		event.preventDefault();354		const n = Number(link.textContent);355		history.replaceState(null, "", `#L${Math.min(anchor, n)}-L${Math.max(anchor, n)}`);356		mark();357	});358	window.addEventListener("hashchange", mark);359	mark();360}361362// The Atlas (§21.5): each row's detail panel waits in the <template> after it; the filter narrows363// by filename; which folders are open is remembered per repo in this browser.364function atlas() {365	const root = document.querySelector(".atlas");366	const filter = document.querySelector(".atlas-filter");367	if (!root || !filter) return;368	const panel = root.querySelector(".atlas-panel");369	const folders = [...root.querySelectorAll(".atlas-folder")];370	const files = [...root.querySelectorAll(".atlas-file")];371	// Its height is the closed tree's, fixed before any folder opens; opening one scrolls within.372	root.style.height = `${root.offsetHeight}px`;373	root.style.overflowY = "hidden";374	const key = `kepr:atlas:${root.dataset.repo}`;375	const opened = new Set(remembered(key));376	// `?open=<folder>` from a file page's breadcrumb unfolds that folder, without remembering it.377	const unfold = new URLSearchParams(location.search).get("open");378	const onPath = (path) => unfold !== null && `${unfold}/`.startsWith(`${path}/`);379	for (const folder of folders) {380		folder.open = opened.has(folder.dataset.path) || onPath(folder.dataset.path);381		folder.addEventListener("toggle", () => {382			if (filter.value.trim()) return;383			if (folder.open) opened.add(folder.dataset.path);384			else opened.delete(folder.dataset.path);385			remember(key, [...opened]);386		});387	}388	let selected = null;389	const show = (row) => {390		selected?.classList.remove("selected");391		selected = row;392		row.classList.add("selected");393		panel.replaceChildren(row.nextElementSibling.content.cloneNode(true));394	};395	for (const row of root.querySelectorAll(".atlas-row")) {396		row.addEventListener("pointerenter", (event) => {397			if (event.pointerType === "mouse") show(row);398		});399		row.addEventListener("focus", () => show(row));400	}401	const viewer = fileViewer(root);402	for (const file of files) {403		file.addEventListener("click", (event) => {404			if (modified(event)) return;405			event.preventDefault();406			viewer(file);407		});408	}409	const target = folders.find((folder) => folder.dataset.path === unfold)?.firstElementChild;410	if (target) {411		show(target);412		target.scrollIntoView({ block: "center" });413	}414	filter.addEventListener("input", () => {415		const query = filter.value.trim().toLowerCase();416		for (const file of files) file.hidden = query !== "" && !file.dataset.name.includes(query);417		for (const folder of folders) {418			folder.hidden = query !== "" && !folder.querySelector(".atlas-file:not([hidden])");419			folder.open = query !== "" || opened.has(folder.dataset.path);420		}421	});422	// The filter waits behind a search button, and folds back into it when left empty.423	const search = document.querySelector(".atlas-search-btn");424	search.addEventListener("click", () => {425		search.hidden = true;426		filter.hidden = false;427		filter.focus();428	});429	filter.addEventListener("blur", () => {430		if (filter.value.trim() !== "") return;431		filter.hidden = true;432		search.hidden = false;433	});434	search.hidden = false;435	panel.hidden = false;436}437438// Kepr 2's Atlas picker: saves filtered as you type; a click outside or Escape closes it.439function atlasPicker() {440	const picker = document.querySelector(".atlas-picker");441	if (!picker) return;442	const filter = picker.querySelector(".atlas-picker-filter");443	const rows = [...picker.querySelectorAll(".atlas-picker-row")];444	filter.addEventListener("input", () => {445		const query = filter.value.trim().toLowerCase();446		for (const row of rows) row.hidden = query !== "" && !row.dataset.q.includes(query);447	});448	picker.addEventListener("toggle", () => {449		if (picker.open) filter.focus();450	});451	document.addEventListener("click", (event) => {452		if (!picker.contains(event.target)) picker.open = false;453	});454	picker.addEventListener("keydown", (event) => {455		if (event.key === "Escape") picker.open = false;456	});457	filter.hidden = false;458}459460// Files open in a viewer over the page, as in Kepr 2's Atlas: the file page's content with the461// row's detail panel beside it, and controls for text size, wrapping, raw, download and the462// neighbouring files. Escape closes it; the arrow keys step through the files.463function fileViewer(root) {464	let [row, size, wrap] = [null, 12, false];465	const overlay = element("div", "fv-overlay");466	overlay.tabIndex = -1;467	overlay.setAttribute("role", "dialog");468	overlay.setAttribute("aria-modal", "true");469	const close = () => {470		overlay.remove();471		row?.focus();472		row = null;473	};474	const step = (by) => {475		const rows = [...root.querySelectorAll(".atlas-file")].filter((file) => !file.hidden);476		const next = rows[rows.indexOf(row) + by];477		if (next) open(next);478	};479	const restyle = () => {480		overlay.style.setProperty("--fv-size", `${size}px`);481		overlay.classList.toggle("fv-wrap", wrap);482	};483	const open = async (file, url = file.href) => {484		row = file;485		const rows = [...root.querySelectorAll(".atlas-file")].filter((each) => !each.hidden);486		const index = rows.indexOf(file);487		const detail = file.nextElementSibling.content.cloneNode(true);488		const name = detail.querySelector(".atlas-info-name").textContent;489		const path = detail.querySelector(".atlas-info-path").textContent;490		const raw = new URL(file.href);491		raw.pathname = raw.pathname.replace(/^(\/[^/]+)\/files\//, "$1/raw/");492		const button = (text, action, className = "fv-ctrl-btn") => {493			const b = element("button", className, text);494			b.type = "button";495			b.addEventListener("click", action);496			return b;497		};498		const link = (text, download) => {499			const a = element("a", "fv-ctrl-btn", text);500			a.href = raw.href;501			if (download) a.download = name;502			return a;503		};504		const source = element("div", "fv-source", "loading…");505		const panel = element("aside", "fv-detail");506		panel.append(detail);507		const header = element("div", "fv-header");508		const title = element("div", "fv-title");509		title.append(element("span", "fv-name", name), element("span", "fv-path mono", path));510		const controls = element("div", "fv-controls mono");511		controls.append(512			button("A−", () => {513				size = Math.max(9, size - 1);514				restyle();515			}),516			button("A+", () => {517				size = Math.min(20, size + 1);518				restyle();519			}),520			button("⇌ wrap", (event) => {521				wrap = !wrap;522				event.currentTarget.classList.toggle("active", wrap);523				restyle();524			}),525			link("raw", false),526			link("download", true),527		);528		controls.children[2].classList.toggle("active", wrap);529		const nav = element("div", "fv-nav mono");530		const back = button("←", () => step(-1), "fv-ctrl-btn");531		const forward = button("→", () => step(1), "fv-ctrl-btn");532		back.disabled = index <= 0;533		forward.disabled = index >= rows.length - 1;534		nav.append(back, element("span", "fv-pos", `${index + 1}/${rows.length}`), forward);535		header.append(button("×", close, "fv-close"), title, controls, nav);536		const body = element("div", "fv-body");537		body.append(source, panel);538		overlay.replaceChildren(header, body);539		restyle();540		if (!overlay.isConnected) document.body.append(overlay);541		overlay.focus();542		const main = await fetchMain(url);543		if (row !== file) return;544		if (!main) {545			location.href = url;546			return;547		}548		for (const heading of main.querySelectorAll(".breadcrumb, .file-page-title")) heading.remove();549		main.querySelector(".file-meta:not(:last-child)")?.remove();550		source.replaceChildren(...main.childNodes);551	};552	overlay.addEventListener("keydown", (event) => {553		if (event.key === "Escape") close();554		else if (event.key === "ArrowLeft" || event.key === "ArrowRight") {555			event.preventDefault();556			step(event.key === "ArrowLeft" ? -1 : 1);557		}558	});559	// The Markdown view's rendered/source toggle points at the file page: switch in place.560	overlay.addEventListener("click", (event) => {561		const link = event.target.closest(".fv-source a[href]");562		if (!link || !row || modified(event)) return;563		if (new URL(link.href).pathname !== new URL(row.href).pathname) return;564		event.preventDefault();565		open(row, link.href);566	});567	return open;568}569570function element(tag, className, text) {571	const node = document.createElement(tag);572	node.className = className;573	if (text !== undefined) node.textContent = text;574	return node;575}576577// Storage can be missing, refused (private windows, blocked windows) or hold anything; only a578// list of folder paths is trusted, and otherwise the tree starts closed.579function remembered(key) {580	try {581		const value = JSON.parse(localStorage.getItem(key) ?? "[]");582		return Array.isArray(value) && value.every((path) => typeof path === "string") ? value : [];583	} catch {584		return [];585	}586}587588function remember(key, value) {589	try {590		localStorage.setItem(key, JSON.stringify(value));591	} catch {}592}593594// The profile's hex backdrop already breathes in CSS; this lights a few columns at a time, as595// Kepr 2's canvas did. Nothing moves under reduced motion, including when it is switched on later.596function hexGlow() {597	const columns = document.querySelectorAll(".hex-col");598	if (columns.length === 0) return;599	const reduce = matchMedia("(prefers-reduced-motion: reduce)");600	let timer = null;601	const update = () => {602		clearInterval(timer);603		for (const column of columns) column.classList.remove("glow");604		if (reduce.matches) return;605		timer = setInterval(() => {606			const column = columns[Math.floor(Math.random() * columns.length)];607			if (document.querySelectorAll(".hex-col.glow").length >= 3) return;608			column.classList.add("glow");609			setTimeout(() => column.classList.remove("glow"), 3200);610		}, 1500);611	};612	reduce.addEventListener("change", update);613	update();614}615616// A CSS duration cannot follow a track's width, so the pace would depend on the messages; set it617// here so each row slides at its own --speed in px/s, as Kepr 2's canvas did.618function tickerPace() {619	for (const track of document.querySelectorAll(".ticker-track")) {620		const speed = Number(getComputedStyle(track).getPropertyValue("--speed"));621		if (speed > 0) track.style.animationDuration = `${track.scrollWidth / 2 / speed}s`;622	}623}624625// Widths are only final once Martian Mono has loaded.626document.fonts.ready.then(tickerPace);627timeline();628copyButtons(document);629panels();630saveLists();631atlasPicker();632lineRanges();633atlas();634hexGlow();