atlas.ts

8.6 KB · raw

1import { describeFile, describeFolder, firstSentence } from "../describe/describe.ts";2import { filesAt, fileTouches, objectBytes, type Save, type Touches } from "../mirror/queries.ts";3import { isText } from "./files.ts";4import { type Html, html } from "./html.ts";5import {6	formatDate,7	formatSize,8	type PublicRepo,9	pathUrl,10	plural,11	relativeTime,12} from "./layout.ts";13import { type MarkdownBase, renderLine, renderMarkdown } from "./markdown.ts";1415type AtlasFile = {16	name: string;17	path: string;18	size: number;19	lines: number | null;20	description: string | null;21	/** The saves that touched it, oldest first. */22	saves: Save[];23};2425type AtlasFolder = {26	name: string;27	path: string;28	folders: AtlasFolder[];29	files: AtlasFile[];30	/** The saves that touched anything under it, removed files included, oldest first. */31	saves: Save[];32};3334type View = { repo: string; at: string | null };3536type Facts = { lines: number | null; description: string | null };3738// Measured: Koh 3's vendored 9 MB sqlite3.c cost every Atlas view ~25 ms to inflate and scan. An39// object never changes, so what it says about itself is kept for the life of the process, keyed by40// hash and file name (the name picks the comment syntax).41// ponytail: unbounded, one small entry per object viewed; an LRU if a bucket reaches millions.42const known = new Map<string, Facts>();4344function factsOf(db: PublicRepo["mirror"], hash: string, name: string): Facts {45	const key = `${hash} ${name}`;46	const cached = known.get(key);47	if (cached) return cached;48	const bytes = objectBytes(db, hash);49	const text = bytes && isText(bytes) ? new TextDecoder().decode(bytes) : null;50	const facts =51		text === null52			? { lines: null, description: null }53			: { lines: countLines(text), description: describeFile(name, text) };54	known.set(key, facts);55	return facts;56}5758/**59 * §21.5's Atlas at one save: the folder tree as `<details>`, so it opens and links without60 * JavaScript. Each row is followed by a `<template>` holding its detail panel, which the browser61 * island shows on hover or select.62 */63export function atlasSection(repo: PublicRepo, saveId: string, at: string | null): Html {64	const touches = fileTouches(repo.mirror, saveId);65	const foldersTouches = folderTouches(touches);66	const root: AtlasFolder = { name: "", path: "", folders: [], files: [], saves: [] };67	const entries = filesAt(repo.mirror, saveId);68	for (const entry of entries) {69		const parts = entry.path.split("/");70		let folder = root;71		for (const name of parts.slice(0, -1)) {72			let child = folder.folders.find((f) => f.name === name);73			if (!child) {74				const path = folder.path ? `${folder.path}/${name}` : name;75				child = { name, path, folders: [], files: [], saves: foldersTouches.get(path) ?? [] };76				folder.folders.push(child);77			}78			folder = child;79		}80		const name = parts[parts.length - 1] as string;81		folder.files.push({82			name,83			path: entry.path,84			size: entry.size,85			...factsOf(repo.mirror, entry.hash, name),86			saves: touches.byPath.get(entry.path) ?? [],87		});88	}89	const view = { repo: repo.settings.name, at };90	const where = at91		? html`at <a href="/${view.repo}/saves/${at}">${at}</a> · <a href="/${view.repo}#atlas">back to HEAD</a>`92		: "HEAD";93	return html`<section class="repo-section" id="atlas">94<details class="repo-section-toggle" open>95<summary class="section-head"><span class="section-label">atlas</span><span class="section-count">${plural(entries.length, "file")}</span></summary>96<p class="atlas-where mono">${where}</p>97<input class="atlas-filter mono" type="search" placeholder="filter by filename" aria-label="Filter files by name" hidden>98<div class="atlas" data-repo="${view.repo}">99<div class="atlas-tree">${children(root, view)}</div>100<aside class="atlas-panel" hidden><p class="atlas-hint mono">hover or select a row for details</p></aside>101</div>102</details>103</section>`;104}105106function children(folder: AtlasFolder, view: View): Html[] {107	const byName = (a: { name: string }, b: { name: string }) =>108		a.name.toLowerCase().localeCompare(b.name.toLowerCase()) || a.name.localeCompare(b.name);109	return [110		...folder.folders.sort(byName).map((child) => folderRow(child, view)),111		...folder.files.sort(byName).map((file) => fileRow(file, view)),112	];113}114115function fileRow(file: AtlasFile, view: View): Html {116	const { description } = file;117	const base = markdownBase(view, file.path);118	const href = `/${view.repo}/files/${pathUrl(file.path)}${view.at ? `?at=${view.at}` : ""}`;119	return html`<a class="atlas-row atlas-file" href="${href}" data-name="${file.name.toLowerCase()}">${row(file.name, description, base, file.size, file.saves)}</a>120<template>${panel(121		file.name,122		file.path,123		[124			["size", formatSize(file.size)],125			["lines", file.lines === null ? "binary" : file.lines.toLocaleString("en-US")],126			...saveFacts(file.saves, view),127		],128		description,129		base,130	)}${recent(file.saves, view)}</template>`;131}132133function folderRow(folder: AtlasFolder, view: View): Html {134	const description = describeFolder(folder.files);135	const base = markdownBase(view, `${folder.path}/`);136	const files = allFiles(folder);137	const size = files.reduce((sum, f) => sum + f.size, 0);138	const lines = files.reduce((sum, f) => sum + (f.lines ?? 0), 0);139	return html`<details class="atlas-folder" data-path="${folder.path}">140<summary class="atlas-row">${row(`${folder.name}/`, description, base, size, folder.saves)}</summary>141<template>${panel(142		`${folder.name}/`,143		folder.path,144		[145			["size", formatSize(size)],146			["lines", lines.toLocaleString("en-US")],147			["files", files.length.toLocaleString("en-US")],148			...saveFacts(folder.saves, view),149		],150		description,151		base,152	)}${recent(folder.saves, view)}</template>153<div class="atlas-children">${children(folder, view)}</div>154</details>`;155}156157function row(158	name: string,159	description: string | null,160	base: MarkdownBase,161	size: number,162	saves: Save[],163): Html {164	const last = saves[saves.length - 1];165	const meta = [formatSize(size), last && relativeTime(last.created_at)]166		.filter(Boolean)167		.join(" · ");168	return html`<span class="atlas-name">${name}</span><span class="atlas-desc">${description && renderLine(firstSentence(description), base)}</span><span class="atlas-meta mono">${meta}</span>`;169}170171function panel(172	name: string,173	path: string,174	facts: [string, Html | string][],175	description: string | null,176	base: MarkdownBase,177): Html {178	return html`<h3 class="atlas-info-name">${name}</h3>179<p class="atlas-info-path mono">${path}</p>180<dl class="atlas-facts mono">${facts.map(([term, value]) => html`<dt>${term}</dt><dd>${value}</dd>`)}</dl>181${description && html`<div class="markdown atlas-info-desc">${renderMarkdown(description, base)}</div>`}`;182}183184function saveFacts(saves: Save[], view: View): [string, Html | string][] {185	const [first, last] = [saves[0], saves[saves.length - 1]];186	if (!first || !last) return [];187	return [188		["first save", saveLink(first, view)],189		["last save", saveLink(last, view)],190		["saves", saves.length.toLocaleString("en-US")],191	];192}193194function saveLink(save: Save, view: View): Html {195	return html`<a href="/${view.repo}/saves/${save.id}">${save.id}</a> ${formatDate(save.created_at)}`;196}197198function recent(saves: Save[], view: View): Html | null {199	if (saves.length === 0) return null;200	return html`<ul class="atlas-recent">${saves201		.slice(-5)202		.reverse()203		.map(204			(save) =>205				html`<li><a class="mono" href="/${view.repo}/saves/${save.id}">${save.id}</a> <span>${save.message.split("\n")[0]}</span> <span class="atlas-when mono">${relativeTime(save.created_at)}</span></li>`,206		)}</ul>`;207}208209// Each folder's saves are the line's saves that touched any path under it, in line order.210function folderTouches(touches: Touches): Map<string, Save[]> {211	const ids = new Map<string, Set<string>>();212	for (const [path, saves] of touches.byPath) {213		const parts = path.split("/");214		for (let depth = 1; depth < parts.length; depth++) {215			const folder = parts.slice(0, depth).join("/");216			const set = ids.get(folder) ?? new Set<string>();217			for (const save of saves) set.add(save.id);218			ids.set(folder, set);219		}220	}221	return new Map(222		[...ids].map(([folder, set]) => [folder, touches.line.filter((save) => set.has(save.id))]),223	);224}225226function allFiles(folder: AtlasFolder): AtlasFile[] {227	return [...folder.files, ...folder.folders.flatMap(allFiles)];228}229230// Relative links in a description resolve from the file's own folder, as in a README.231function markdownBase(view: View, path: string): MarkdownBase {232	return { repo: view.repo, dir: path.split("/").slice(0, -1).join("/"), at: view.at };233}234235function countLines(text: string): number {236	if (text === "") return 0;237	let count = 0;238	for (let i = text.indexOf("\n"); i >= 0; i = text.indexOf("\n", i + 1)) count++;239	return text.endsWith("\n") ? count : count + 1;240}