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 panelFile,8 panelFolder,9 type Save,10 type Touches,11 tarballGeneration,12} from "../mirror/queries.ts";13import { type Html, html } from "./html.ts";14import {15 formatDate,16 formatSize,17 type PublicRepo,18 pathUrl,19 plural,20 relativeTime,21} from "./layout.ts";22import { type MarkdownBase, renderLine, renderMarkdown } from "./markdown.ts";2324type AtlasFile = {25 name: string;26 path: string;27 size: number;28 lines: number | null;29 description: string | null;30 outline: Outline | null;31 32 saves: Save[];33};3435type AtlasFolder = {36 name: string;37 path: string;38 folders: AtlasFolder[];39 files: AtlasFile[];40 41 saves: Save[];42};434445type Links = { imports: Map<string, string[]>; usedBy: Map<string, string[]> };464748type Linked = { path: string; outline: Outline | null };4950type View = { repo: string; at: string | null; links: Links };515253const LISTED = 12;545556type AtlasModel = { root: AtlasFolder; links: Links; count: number };5758596061const linkCache = new Map<string, Links>();6263function linksFor(repo: PublicRepo, saveId: string, read: () => Linked[]): Links {64 const key = `${repo.settings.name}\n${saveId}\n${tarballGeneration(repo.mirror)}`;65 const found = linkCache.get(key);66 if (found) return found;67 const links = linksOf(read());68 if (linkCache.size > 3) linkCache.clear();69 linkCache.set(key, links);70 return links;71}7273function buildAtlasModel(repo: PublicRepo, saveId: string): AtlasModel {74 const touches = fileTouches(repo.mirror, saveId);75 const foldersTouches = folderTouches(touches);76 const root: AtlasFolder = { name: "", path: "", folders: [], files: [], saves: [] };77 78 const entries = filesWithFacts(repo.mirror, saveId).filter(79 (entry) => entry.path !== ".kohignore",80 );81 for (const entry of entries) {82 const parts = entry.path.split("/");83 let folder = root;84 for (const name of parts.slice(0, -1)) {85 let child = folder.folders.find((f) => f.name === name);86 if (!child) {87 const path = folder.path ? `${folder.path}/${name}` : name;88 child = { name, path, folders: [], files: [], saves: foldersTouches.get(path) ?? [] };89 folder.folders.push(child);90 }91 folder = child;92 }93 folder.files.push({94 name: parts[parts.length - 1] as string,95 path: entry.path,96 size: entry.size,97 lines: entry.lines,98 description: entry.description,99 outline: entry.outline,100 saves: touches.byPath.get(entry.path) ?? [],101 });102 }103 return { root, links: linksFor(repo, saveId, () => entries), count: entries.length };104}105106107108109110111112export function atlasSection(repo: PublicRepo, saveId: string, at: string | null): Html {113 114 const model = repo.mirror.transaction(() => buildAtlasModel(repo, saveId))();115 const view = { repo: repo.settings.name, at, links: model.links };116 return html`<section class="repo-section" id="atlas">117<details class="repo-section-toggle" open>118<summary class="section-head"><span class="section-label">atlas</span><span class="section-count">${plural(119 model.count,120 "file",121 )}</span></summary>122<div class="atlas-bar">123${picker(view)}124${at && html`<a class="atlas-head-link mono" href="/${view.repo}#atlas">back to HEAD</a>`}125<button type="button" class="atlas-fold-btn mono" hidden>expand all</button>126<button type="button" class="atlas-search-btn mono" hidden>search</button>127<input class="atlas-filter mono" type="search" placeholder="filter by filename" aria-label="Filter files by name" hidden>128</div>129<div class="atlas" data-repo="${view.repo}"${at && html` data-at="${at}"`}>130<div class="atlas-tree">${children(model.root, view)}</div>131<aside class="atlas-panel" hidden><p class="atlas-hint mono">hover or select a row for details</p></aside>132</div>133</details>134</section>`;135}136137138function pathTouches(db: Database, saveId: string, path: string, under: boolean): Save[] {139 const scope = under ? "path >= ? AND path < ?" : "path = ?";140 const params = under ? [saveId, `${path}/`, `${path}0`] : [saveId, path];141 return db142 .query<Save, string[]>(143 `SELECT id, COALESCE(parent, '') AS parent, message, created_at, machine,144 COALESCE(agent, '') AS agent, COALESCE(session, '') AS session,145 is_checkpoint = 1 AS is_checkpoint146 FROM saves147 WHERE is_checkpoint = 0148 AND rowid IN (149 SELECT n FROM touches150 WHERE n <= (SELECT rowid FROM saves WHERE id = ?) AND ${scope}151 )152 ORDER BY rowid`,153 )154 .all(...params)155 .map((row) => ({ ...row, is_checkpoint: Boolean(row.is_checkpoint) }));156}157158159export function atlasPanel(160 repo: PublicRepo,161 saveId: string,162 at: string | null,163 path: string,164): Html | null {165 const folder = path.endsWith("/");166 const dir = folder ? path.slice(0, -1) : path;167 return repo.mirror.transaction((): Html | null => {168 const rows = folder ? panelFolder(repo.mirror, saveId, dir) : [];169 const row = folder ? null : panelFile(repo.mirror, saveId, dir);170 if (folder ? rows.length === 0 : row === null) return null;171 const view = {172 repo: repo.settings.name,173 at,174 links: linksFor(repo, saveId, () =>175 filesWithFacts(repo.mirror, saveId).filter((entry) => entry.path !== ".kohignore"),176 ),177 };178 if (rows.length > 0) {179 const files = rows.map(180 (entry): AtlasFile => ({181 name: entry.path.split("/").pop() as string,182 path: entry.path,183 size: entry.size,184 lines: entry.lines,185 description: entry.description,186 outline: null,187 saves: [],188 }),189 );190 return folderPanel(191 {192 name: dir.split("/").pop() as string,193 path: dir,194 folders: [],195 files: files.filter((file) => !file.path.slice(dir.length + 1).includes("/")),196 saves: pathTouches(repo.mirror, saveId, dir, true),197 },198 files,199 view,200 );201 }202 if (row === null) return null;203 return filePanel(204 {205 name: dir.split("/").pop() as string,206 path: dir,207 size: row.size,208 lines: row.lines,209 description: row.description,210 outline: row.outline === null ? null : (JSON.parse(row.outline) as Outline),211 saves: pathTouches(repo.mirror, saveId, dir, false),212 },213 view,214 );215 })();216}217218219220function picker(view: View): Html {221 const query = view.at ? `?at=${view.at}` : "";222 return html`<details class="atlas-picker">223<summary class="atlas-ref-tab mono" title="explore through time">${view.at ?? "HEAD"}</summary>224<div class="atlas-picker-popover">225<input class="atlas-picker-filter mono" type="search" placeholder="search" aria-label="Search saves" hidden>226<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>227</div>228</details>`;229}230231232export function atlasPickerRows(repo: string, saves: Save[], at: string | null): Html[] {233 return saves.toReversed().map((save) => {234 const message = save.message.split("\n")[0] as string;235 return html`<a class="atlas-picker-row${save.id === at ? " active" : ""}" href="/${236 repo237 }?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>`;238 });239}240241function children(folder: AtlasFolder, view: View): Html[] {242 const byName = (a: { name: string }, b: { name: string }) =>243 a.name.toLowerCase().localeCompare(b.name.toLowerCase()) || a.name.localeCompare(b.name);244 return [245 ...folder.folders.sort(byName).map((child) => folderRow(child, view)),246 ...folder.files.sort(byName).map((file) => fileRow(file, view)),247 ];248}249250function fileRow(file: AtlasFile, view: View): Html {251 const href = `/${view.repo}/files/${pathUrl(file.path)}${view.at ? `?at=${view.at}` : ""}`;252 return html`<a class="atlas-row atlas-file" href="${253 href254 }" data-name="${file.name.toLowerCase()}" data-path="${file.path}">${row(file.name, file.description, markdownBase(view, file.path), file.size, file.saves)}</a>`;255}256257function filePanel(file: AtlasFile, view: View): Html {258 return panel(259 file.name,260 file.path,261 [262 ["size", formatSize(file.size)],263 ["lines", file.lines === null ? "binary" : file.lines.toLocaleString("en-US")],264 ...saveFacts(file.saves, view),265 ],266 file.description,267 markdownBase(view, file.path),268 fileMap(file, view),269 );270}271272273274function fileMap(file: AtlasFile, view: View): [string, Html[]][] {275 const users = view.links.usedBy.get(file.path) ?? [];276 return [277 ["exports", listed((file.outline?.exports ?? []).map((name) => html`${name}`))],278 ["imports", targets(view.links.imports.get(file.path) ?? [], view)],279 [280 "used by",281 targets(282 users.filter((path) => !isTestPath(path)),283 view,284 ),285 ],286 ["tested by", targets(users.filter(isTestPath), view)],287 ];288}289290function targets(paths: string[], view: View): Html[] {291 return listed(paths.toSorted().map((path) => targetLink(path, view)));292}293294295function targetLink(target: string, view: View): Html {296 const folder = target.endsWith("/");297 const path = folder ? target.slice(0, -1) : target;298 const query = new URLSearchParams(view.at ? { at: view.at } : {});299 if (folder) query.set("open", path);300 const href = folder301 ? `/${view.repo}?${query}#atlas`302 : `/${view.repo}/files/${pathUrl(path)}${view.at ? `?${query}` : ""}`;303 const name = `${path.split("/").pop()}${folder ? "/" : ""}`;304 return html`<a class="atlas-jump" href="${href}" data-path="${target}" title="${path}">${name}</a>`;305}306307function listed(items: Html[]): Html[] {308 const more = items.length - LISTED;309 return more > 0 ? [...items.slice(0, LISTED), html`+${more} more`] : items;310}311312function linksOf(files: Linked[]): Links {313 const index = repoIndex(files.map((file) => file.path));314 const imports = new Map<string, string[]>();315 const usedBy = new Map<string, string[]>();316 for (const file of files) {317 const found = resolveImports(file.path, file.outline?.imports ?? [], index);318 imports.set(file.path, found);319 for (const target of found) usedBy.set(target, [...(usedBy.get(target) ?? []), file.path]);320 }321 return { imports, usedBy };322}323324function folderRow(folder: AtlasFolder, view: View): Html {325 const files = allFiles(folder);326 const size = files.reduce((sum, f) => sum + f.size, 0);327 return html`<details class="atlas-folder" data-path="${folder.path}">328<summary class="atlas-row">${row(329 `${folder.name}/`,330 describeFolder(folder.files),331 markdownBase(view, `${folder.path}/`),332 size,333 folder.saves,334 )}</summary>335<div class="atlas-children">${children(folder, view)}</div>336</details>`;337}338339function folderPanel(folder: AtlasFolder, files: AtlasFile[], view: View): Html {340 const size = files.reduce((sum, f) => sum + f.size, 0);341 const lines = files.reduce((sum, f) => sum + (f.lines ?? 0), 0);342 return panel(343 `${folder.name}/`,344 folder.path,345 [346 ["size", formatSize(size)],347 ["lines", lines.toLocaleString("en-US")],348 ["files", files.length.toLocaleString("en-US")],349 ...saveFacts(folder.saves, view),350 ],351 describeFolder(folder.files),352 markdownBase(view, `${folder.path}/`),353 [["used by", targets(folderUsers(folder, files, view), view)]],354 );355}356357function row(358 name: string,359 description: string | null,360 base: MarkdownBase,361 size: number,362 saves: Save[],363): Html {364 const last = saves[saves.length - 1];365 const meta = [formatSize(size), last && relativeTime(last.created_at)]366 .filter(Boolean)367 .join(" · ");368 return html`<span class="atlas-name">${name}</span>${html`<span class="atlas-desc">${369 description && renderLine(firstSentence(description), base)370 }</span>`}${html`<span class="atlas-meta mono">${meta}</span>`}`;371}372373374function folderUsers(folder: AtlasFolder, files: AtlasFile[], view: View): string[] {375 const inside = (path: string) => path.startsWith(`${folder.path}/`);376 const users = new Set(view.links.usedBy.get(`${folder.path}/`) ?? []);377 for (const file of files) {378 for (const user of view.links.usedBy.get(file.path) ?? []) if (!inside(user)) users.add(user);379 }380 return [...users];381}382383function panel(384 name: string,385 path: string,386 facts: [string, Html | string][],387 description: string | null,388 base: MarkdownBase,389 map: [string, Html[]][],390): Html {391 const shown = map.filter(([, items]) => items.length > 0);392 return html`<h3 class="atlas-info-name">${name}</h3>393<p class="atlas-info-path mono">${path}</p>394<dl class="atlas-facts mono">${facts.map(395 ([term, value]) => html`<dt>${term}</dt><dd>${value}</dd>`,396 )}</dl>397${398 description &&399 html`<div class="markdown atlas-info-desc">${renderMarkdown(description, base)}</div>`400}401${402 shown.length > 0 &&403 html`<dl class="atlas-facts atlas-map mono">${shown.map(404 ([term, items]) =>405 html`<dt>${term}</dt><dd>${items.map((item, i) => html`${i > 0 && " · "}${item}`)}</dd>`,406 )}</dl>`407}`;408}409410function saveFacts(saves: Save[], view: View): [string, Html | string][] {411 const [first, last] = [saves[0], saves[saves.length - 1]];412 if (!first || !last) return [];413 return [414 ["first save", saveLink(first, view)],415 ["last save", saveLink(last, view)],416 ["saves", saves.length.toLocaleString("en-US")],417 ];418}419420function saveLink(save: Save, view: View): Html {421 return html`<a href="/${422 view.repo423 }/saves/${save.id}">${save.id}</a> ${formatDate(save.created_at)}`;424}425426427function folderTouches(touches: Touches): Map<string, Save[]> {428 const order = new Map(touches.line.map((save, i) => [save, i]));429 const saves = new Map<string, Set<Save>>();430 for (const [path, touched] of touches.byPath) {431 const parts = path.split("/");432 for (let depth = 1; depth < parts.length; depth++) {433 const folder = parts.slice(0, depth).join("/");434 const set = saves.get(folder) ?? new Set<Save>();435 for (const save of touched) set.add(save);436 saves.set(folder, set);437 }438 }439 const byLine = (a: Save, b: Save) => (order.get(a) ?? 0) - (order.get(b) ?? 0);440 return new Map([...saves].map(([folder, set]) => [folder, [...set].sort(byLine)]));441}442443function allFiles(folder: AtlasFolder): AtlasFile[] {444 return [...folder.files, ...folder.folders.flatMap(allFiles)];445}446447448function markdownBase(view: View, path: string): MarkdownBase {449 return { repo: view.repo, dir: path.split("/").slice(0, -1).join("/"), at: view.at };450}