atlas.ts

16.9 KB · raw

1import type { Database } from "bun:sqlite";2import { describeFolder, firstSentence } from "../describe/describe.ts";3import { isTestPath, type Outline, repoIndex, resolveImports } from "../describe/links.ts";4import {5	filesWithFacts,6	fileTouches,7	type Save,8	type Touches,9	tarballGeneration,10} from "../mirror/queries.ts";11import { type Html, html } from "./html.ts";12import {13	formatDate,14	formatSize,15	type PublicRepo,16	pathUrl,17	plural,18	relativeTime,19} from "./layout.ts";20import { type MarkdownBase, renderLine, renderMarkdown } from "./markdown.ts";2122type AtlasFile = {23	name: string;24	path: string;25	size: number;26	lines: number | null;27	description: string | null;28	outline: Outline | null;29	/** The saves that touched it, oldest first. */30	saves: Save[];31};3233type AtlasFolder = {34	name: string;35	path: string;36	folders: AtlasFolder[];37	files: AtlasFile[];38	/** The saves that touched anything under it, removed files included, oldest first. */39	saves: Save[];40};4142/** Each file's resolved imports, and who imports each file or `folder/`. */43type Links = { imports: Map<string, string[]>; usedBy: Map<string, string[]> };4445/** The fields resolving imports reads, from the tree or straight from the mirror's facts. */46type Linked = { path: string; outline: Outline | null };4748type View = { repo: string; at: string | null; links: Links };4950// A panel lists this many names or links, then says how many more.51const LISTED = 12;5253/** The tree at one save with each file's facts and the links between files. */54type AtlasModel = { root: AtlasFolder; links: Links; count: number };5556// Linking needs every file's outline, so a save's links are worked out once and kept for its57// panels: a hover then reads its own row alone. `tarballGeneration` names what a landed sync can58// change behind a save (strips, hidden paths, a cleared mirror).59const linkCache = new Map<string, Links>();6061function linksFor(repo: PublicRepo, saveId: string, read: () => Linked[]): Links {62	const key = `${repo.settings.name}\n${saveId}\n${tarballGeneration(repo.mirror)}`;63	const found = linkCache.get(key);64	if (found) return found;65	const links = linksOf(read());66	if (linkCache.size > 3) linkCache.clear();67	linkCache.set(key, links);68	return links;69}7071function buildAtlasModel(repo: PublicRepo, saveId: string): AtlasModel {72	const touches = fileTouches(repo.mirror, saveId);73	const foldersTouches = folderTouches(touches);74	const root: AtlasFolder = { name: "", path: "", folders: [], files: [], saves: [] };75	// Koh's own rules file is bookkeeping, not part of the project; Koh never saves what it names.76	const entries = filesWithFacts(repo.mirror, saveId).filter(77		(entry) => entry.path !== ".kohignore",78	);79	for (const entry of entries) {80		const parts = entry.path.split("/");81		let folder = root;82		for (const name of parts.slice(0, -1)) {83			let child = folder.folders.find((f) => f.name === name);84			if (!child) {85				const path = folder.path ? `${folder.path}/${name}` : name;86				child = { name, path, folders: [], files: [], saves: foldersTouches.get(path) ?? [] };87				folder.folders.push(child);88			}89			folder = child;90		}91		folder.files.push({92			name: parts[parts.length - 1] as string,93			path: entry.path,94			size: entry.size,95			lines: entry.lines,96			description: entry.description,97			outline: entry.outline,98			saves: touches.byPath.get(entry.path) ?? [],99		});100	}101	return { root, links: linksFor(repo, saveId, () => entries), count: entries.length };102}103104/**105 * §21.5's Atlas at one save: the folder tree as `<details>`, so it opens and links without106 * JavaScript. A row's detail panel is fetched from `atlasPanel` on hover or select (kepr.js), so107 * a big repo's page carries rows only. `HEAD` (or the save shown) opens Kepr 2's picker of saves108 * to view it at instead, its rows fetched from `atlasPickerRows` when first opened.109 */110export function atlasSection(repo: PublicRepo, saveId: string, at: string | null): Html {111	// In one read snapshot: the sync's thread can change the mirror between any two statements.112	const model = repo.mirror.transaction(() => buildAtlasModel(repo, saveId))();113	const view = { repo: repo.settings.name, at, links: model.links };114	return html`<section class="repo-section" id="atlas">115<details class="repo-section-toggle" open>116<summary class="section-head"><span class="section-label">atlas</span><span class="section-count">${plural(117		model.count,118		"file",119	)}</span></summary>120<div class="atlas-bar">121${picker(view)}122${at && html`<a class="atlas-head-link mono" href="/${view.repo}#atlas">back to HEAD</a>`}123<button type="button" class="atlas-fold-btn mono" hidden>expand all</button>124<button type="button" class="atlas-search-btn mono" hidden>search</button>125<input class="atlas-filter mono" type="search" placeholder="filter by filename" aria-label="Filter files by name" hidden>126</div>127<div class="atlas" data-repo="${view.repo}"${at && html` data-at="${at}"`}>128<div class="atlas-tree">${children(model.root, view)}</div>129<aside class="atlas-panel" hidden><p class="atlas-hint mono">hover or select a row for details</p></aside>130</div>131</details>132</section>`;133}134135type PanelRow = { path: string; size: number; lines: number | null; description: string | null };136137// A panel's own reads: one row's facts, and the saves that touched it or (for a folder) anything138// under it. Everything else the panel needs comes from the links, which are kept (linksFor).139const FILE_SQL = `SELECT f.path, o.size, x.lines, x.description, x.outline140	FROM save_files f141	JOIN objects o ON o.hash = f.hash142	LEFT JOIN facts x ON x.hash = f.hash AND x.path = f.path143	WHERE f.save_id = ? AND f.path = ? AND f.path != '.kohignore'`;144const FOLDER_SQL = `SELECT f.path, o.size, x.lines, x.description145	FROM save_files f146	JOIN objects o ON o.hash = f.hash147	LEFT JOIN facts x ON x.hash = f.hash AND x.path = f.path148	WHERE f.save_id = ? AND f.path >= ? AND f.path < ? AND f.path != '.kohignore'149	ORDER BY f.path`;150151// The saves that touched a path, or (with `under`) anything under a folder, oldest first.152function pathTouches(db: Database, saveId: string, path: string, under: boolean): Save[] {153	const scope = under ? "path >= ? AND path < ?" : "path = ?";154	const params = under ? [saveId, `${path}/`, `${path}0`] : [saveId, path];155	return db156		.query<Save, string[]>(157			`SELECT id, COALESCE(parent, '') AS parent, message, created_at, machine,158			COALESCE(agent, '') AS agent, COALESCE(session, '') AS session,159			is_checkpoint = 1 AS is_checkpoint160			FROM saves161			WHERE is_checkpoint = 0162			AND rowid IN (163				SELECT n FROM touches164				WHERE n <= (SELECT rowid FROM saves WHERE id = ?) AND ${scope}165			)166			ORDER BY rowid`,167		)168		.all(...params)169		.map((row) => ({ ...row, is_checkpoint: Boolean(row.is_checkpoint) }));170}171172/** One row's detail panel: a file's, or a folder's when `path` ends in a slash; null if absent. */173export function atlasPanel(174	repo: PublicRepo,175	saveId: string,176	at: string | null,177	path: string,178): Html | null {179	const folder = path.endsWith("/");180	const dir = folder ? path.slice(0, -1) : path;181	return repo.mirror.transaction((): Html | null => {182		const rows = folder183			? repo.mirror184					.query<PanelRow, [string, string, string]>(FOLDER_SQL)185					.all(saveId, `${dir}/`, `${dir}0`)186			: [];187		const row = folder188			? null189			: (repo.mirror190					.query<PanelRow & { outline: string | null }, [string, string]>(FILE_SQL)191					.get(saveId, dir) ?? null);192		if (folder ? rows.length === 0 : row === null) return null;193		const view = {194			repo: repo.settings.name,195			at,196			links: linksFor(repo, saveId, () =>197				filesWithFacts(repo.mirror, saveId).filter((entry) => entry.path !== ".kohignore"),198			),199		};200		if (rows.length > 0) {201			const files = rows.map(202				(entry): AtlasFile => ({203					name: entry.path.split("/").pop() as string,204					path: entry.path,205					size: entry.size,206					lines: entry.lines,207					description: entry.description,208					outline: null,209					saves: [],210				}),211			);212			return folderPanel(213				{214					name: dir.split("/").pop() as string,215					path: dir,216					folders: [],217					files: files.filter((file) => !file.path.slice(dir.length + 1).includes("/")),218					saves: pathTouches(repo.mirror, saveId, dir, true),219				},220				files,221				view,222			);223		}224		if (row === null) return null;225		return filePanel(226			{227				name: dir.split("/").pop() as string,228				path: dir,229				size: row.size,230				lines: row.lines,231				description: row.description,232				outline: row.outline === null ? null : (JSON.parse(row.outline) as Outline),233				saves: pathTouches(repo.mirror, saveId, dir, false),234			},235			view,236		);237	})();238}239240// Kepr 2's "explore through time". Its rows arrive when first opened (kepr.js): a big repo's241// every save was most of its page. Without JavaScript, History's save pages link to the Atlas.242function picker(view: View): Html {243	const query = view.at ? `?at=${view.at}` : "";244	return html`<details class="atlas-picker">245<summary class="atlas-ref-tab mono" title="explore through time">${view.at ?? "HEAD"}</summary>246<div class="atlas-picker-popover">247<input class="atlas-picker-filter mono" type="search" placeholder="search" aria-label="Search saves" hidden>248<div class="atlas-picker-list" data-src="/${view.repo}/atlas/saves${query}"><a class="atlas-picker-row" href="#history">pick a save from the history</a></div>249</div>250</details>`;251}252253/** The picker's rows: every save, newest first, `at` marked. kepr.js filters on their text. */254export function atlasPickerRows(repo: string, saves: Save[], at: string | null): Html[] {255	return saves.toReversed().map((save) => {256		const message = save.message.split("\n")[0] as string;257		return html`<a class="atlas-picker-row${save.id === at ? " active" : ""}" href="/${258			repo259		}?at=${save.id}#atlas"><span class="atlas-picker-id">${save.id}</span><span class="atlas-picker-msg">${message}</span><span class="atlas-picker-age">· ${relativeTime(save.created_at)}</span></a>`;260	});261}262263function children(folder: AtlasFolder, view: View): Html[] {264	const byName = (a: { name: string }, b: { name: string }) =>265		a.name.toLowerCase().localeCompare(b.name.toLowerCase()) || a.name.localeCompare(b.name);266	return [267		...folder.folders.sort(byName).map((child) => folderRow(child, view)),268		...folder.files.sort(byName).map((file) => fileRow(file, view)),269	];270}271272function fileRow(file: AtlasFile, view: View): Html {273	const href = `/${view.repo}/files/${pathUrl(file.path)}${view.at ? `?at=${view.at}` : ""}`;274	return html`<a class="atlas-row atlas-file" href="${275		href276	}" data-name="${file.name.toLowerCase()}" data-path="${file.path}">${row(file.name, file.description, markdownBase(view, file.path), file.size, file.saves)}</a>`;277}278279function filePanel(file: AtlasFile, view: View): Html {280	return panel(281		file.name,282		file.path,283		[284			["size", formatSize(file.size)],285			["lines", file.lines === null ? "binary" : file.lines.toLocaleString("en-US")],286			...saveFacts(file.saves, view),287		],288		file.description,289		markdownBase(view, file.path),290		fileMap(file, view),291	);292}293294// Kepr 2's map of the repo, only where a file has something to say: what it offers, what it295// leans on, and what leans on it, tests apart.296function fileMap(file: AtlasFile, view: View): [string, Html[]][] {297	const users = view.links.usedBy.get(file.path) ?? [];298	return [299		["exports", listed((file.outline?.exports ?? []).map((name) => html`${name}`))],300		["imports", targets(view.links.imports.get(file.path) ?? [], view)],301		[302			"used by",303			targets(304				users.filter((path) => !isTestPath(path)),305				view,306			),307		],308		["tested by", targets(users.filter(isTestPath), view)],309	];310}311312function targets(paths: string[], view: View): Html[] {313	return listed(paths.toSorted().map((path) => targetLink(path, view)));314}315316// A file links to its page and a folder to the Atlas with it open; kepr.js jumps to the row.317function targetLink(target: string, view: View): Html {318	const folder = target.endsWith("/");319	const path = folder ? target.slice(0, -1) : target;320	const query = new URLSearchParams(view.at ? { at: view.at } : {});321	if (folder) query.set("open", path);322	const href = folder323		? `/${view.repo}?${query}#atlas`324		: `/${view.repo}/files/${pathUrl(path)}${view.at ? `?${query}` : ""}`;325	const name = `${path.split("/").pop()}${folder ? "/" : ""}`;326	return html`<a class="atlas-jump" href="${href}" data-path="${target}" title="${path}">${name}</a>`;327}328329function listed(items: Html[]): Html[] {330	const more = items.length - LISTED;331	return more > 0 ? [...items.slice(0, LISTED), html`+${more} more`] : items;332}333334function linksOf(files: Linked[]): Links {335	const index = repoIndex(files.map((file) => file.path));336	const imports = new Map<string, string[]>();337	const usedBy = new Map<string, string[]>();338	for (const file of files) {339		const found = resolveImports(file.path, file.outline?.imports ?? [], index);340		imports.set(file.path, found);341		for (const target of found) usedBy.set(target, [...(usedBy.get(target) ?? []), file.path]);342	}343	return { imports, usedBy };344}345346function folderRow(folder: AtlasFolder, view: View): Html {347	const files = allFiles(folder);348	const size = files.reduce((sum, f) => sum + f.size, 0);349	return html`<details class="atlas-folder" data-path="${folder.path}">350<summary class="atlas-row">${row(351		`${folder.name}/`,352		describeFolder(folder.files),353		markdownBase(view, `${folder.path}/`),354		size,355		folder.saves,356	)}</summary>357<div class="atlas-children">${children(folder, view)}</div>358</details>`;359}360361function folderPanel(folder: AtlasFolder, files: AtlasFile[], view: View): Html {362	const size = files.reduce((sum, f) => sum + f.size, 0);363	const lines = files.reduce((sum, f) => sum + (f.lines ?? 0), 0);364	return panel(365		`${folder.name}/`,366		folder.path,367		[368			["size", formatSize(size)],369			["lines", lines.toLocaleString("en-US")],370			["files", files.length.toLocaleString("en-US")],371			...saveFacts(folder.saves, view),372		],373		describeFolder(folder.files),374		markdownBase(view, `${folder.path}/`),375		[["used by", targets(folderUsers(folder, files, view), view)]],376	);377}378379function row(380	name: string,381	description: string | null,382	base: MarkdownBase,383	size: number,384	saves: Save[],385): Html {386	const last = saves[saves.length - 1];387	const meta = [formatSize(size), last && relativeTime(last.created_at)]388		.filter(Boolean)389		.join(" · ");390	return html`<span class="atlas-name">${name}</span>${html`<span class="atlas-desc">${391		description && renderLine(firstSentence(description), base)392	}</span>`}${html`<span class="atlas-meta mono">${meta}</span>`}`;393}394395// Files outside a folder that import it as a module, or anything inside it.396function folderUsers(folder: AtlasFolder, files: AtlasFile[], view: View): string[] {397	const inside = (path: string) => path.startsWith(`${folder.path}/`);398	const users = new Set(view.links.usedBy.get(`${folder.path}/`) ?? []);399	for (const file of files) {400		for (const user of view.links.usedBy.get(file.path) ?? []) if (!inside(user)) users.add(user);401	}402	return [...users];403}404405function panel(406	name: string,407	path: string,408	facts: [string, Html | string][],409	description: string | null,410	base: MarkdownBase,411	map: [string, Html[]][],412): Html {413	const shown = map.filter(([, items]) => items.length > 0);414	return html`<h3 class="atlas-info-name">${name}</h3>415<p class="atlas-info-path mono">${path}</p>416<dl class="atlas-facts mono">${facts.map(417		([term, value]) => html`<dt>${term}</dt><dd>${value}</dd>`,418	)}</dl>419${420	description &&421	html`<div class="markdown atlas-info-desc">${renderMarkdown(description, base)}</div>`422}423${424	shown.length > 0 &&425	html`<dl class="atlas-facts atlas-map mono">${shown.map(426		([term, items]) =>427			html`<dt>${term}</dt><dd>${items.map((item, i) => html`${i > 0 && " · "}${item}`)}</dd>`,428	)}</dl>`429}`;430}431432function saveFacts(saves: Save[], view: View): [string, Html | string][] {433	const [first, last] = [saves[0], saves[saves.length - 1]];434	if (!first || !last) return [];435	return [436		["first save", saveLink(first, view)],437		["last save", saveLink(last, view)],438		["saves", saves.length.toLocaleString("en-US")],439	];440}441442function saveLink(save: Save, view: View): Html {443	return html`<a href="/${444		view.repo445	}/saves/${save.id}">${save.id}</a> ${formatDate(save.created_at)}`;446}447448// Each folder's saves are the line's saves that touched any path under it, in line order.449function folderTouches(touches: Touches): Map<string, Save[]> {450	const order = new Map(touches.line.map((save, i) => [save, i]));451	const saves = new Map<string, Set<Save>>();452	for (const [path, touched] of touches.byPath) {453		const parts = path.split("/");454		for (let depth = 1; depth < parts.length; depth++) {455			const folder = parts.slice(0, depth).join("/");456			const set = saves.get(folder) ?? new Set<Save>();457			for (const save of touched) set.add(save);458			saves.set(folder, set);459		}460	}461	const byLine = (a: Save, b: Save) => (order.get(a) ?? 0) - (order.get(b) ?? 0);462	return new Map([...saves].map(([folder, set]) => [folder, [...set].sort(byLine)]));463}464465function allFiles(folder: AtlasFolder): AtlasFile[] {466	return [...folder.files, ...folder.folders.flatMap(allFiles)];467}468469// Relative links in a description resolve from the file's own folder, as in a README.470function markdownBase(view: View, path: string): MarkdownBase {471	return { repo: view.repo, dir: path.split("/").slice(0, -1).join("/"), at: view.at };472}