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 22 saves: Save[];23};2425type AtlasFolder = {26 name: string;27 path: string;28 folders: AtlasFolder[];29 files: AtlasFile[];30 31 saves: Save[];32};3334type View = { repo: string; at: string | null };3536type Facts = { lines: number | null; description: string | null };373839404142const 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}57585960616263export 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="/${92 view.repo93 }/saves/${at}">${at}</a> · <a href="/${view.repo}#atlas">back to HEAD</a>`94 : "HEAD";95 return html`<section class="repo-section" id="atlas">96<details class="repo-section-toggle" open>97<summary class="section-head"><span class="section-label">atlas</span><span class="section-count">${plural(98 entries.length,99 "file",100 )}</span></summary>101<p class="atlas-where mono">${where}</p>102<input class="atlas-filter mono" type="search" placeholder="filter by filename" aria-label="Filter files by name" hidden>103<div class="atlas" data-repo="${view.repo}">104<div class="atlas-tree">${children(root, view)}</div>105<aside class="atlas-panel" hidden><p class="atlas-hint mono">hover or select a row for details</p></aside>106</div>107</details>108</section>`;109}110111function children(folder: AtlasFolder, view: View): Html[] {112 const byName = (a: { name: string }, b: { name: string }) =>113 a.name.toLowerCase().localeCompare(b.name.toLowerCase()) || a.name.localeCompare(b.name);114 return [115 ...folder.folders.sort(byName).map((child) => folderRow(child, view)),116 ...folder.files.sort(byName).map((file) => fileRow(file, view)),117 ];118}119120function fileRow(file: AtlasFile, view: View): Html {121 const { description } = file;122 const base = markdownBase(view, file.path);123 const href = `/${view.repo}/files/${pathUrl(file.path)}${view.at ? `?at=${view.at}` : ""}`;124 return html`<a class="atlas-row atlas-file" href="${125 href126 }" data-name="${file.name.toLowerCase()}">${row(file.name, description, base, file.size, file.saves)}</a>127<template>${panel(128 file.name,129 file.path,130 [131 ["size", formatSize(file.size)],132 ["lines", file.lines === null ? "binary" : file.lines.toLocaleString("en-US")],133 ...saveFacts(file.saves, view),134 ],135 description,136 base,137 )}${recent(file.saves, view)}</template>`;138}139140function folderRow(folder: AtlasFolder, view: View): Html {141 const description = describeFolder(folder.files);142 const base = markdownBase(view, `${folder.path}/`);143 const files = allFiles(folder);144 const size = files.reduce((sum, f) => sum + f.size, 0);145 const lines = files.reduce((sum, f) => sum + (f.lines ?? 0), 0);146 return html`<details class="atlas-folder" data-path="${folder.path}">147<summary class="atlas-row">${row(148 `${folder.name}/`,149 description,150 base,151 size,152 folder.saves,153 )}</summary>154<template>${panel(155 `${folder.name}/`,156 folder.path,157 [158 ["size", formatSize(size)],159 ["lines", lines.toLocaleString("en-US")],160 ["files", files.length.toLocaleString("en-US")],161 ...saveFacts(folder.saves, view),162 ],163 description,164 base,165 )}${recent(folder.saves, view)}</template>166<div class="atlas-children">${children(folder, view)}</div>167</details>`;168}169170function row(171 name: string,172 description: string | null,173 base: MarkdownBase,174 size: number,175 saves: Save[],176): Html {177 const last = saves[saves.length - 1];178 const meta = [formatSize(size), last && relativeTime(last.created_at)]179 .filter(Boolean)180 .join(" · ");181 return html`<span class="atlas-name">${name}</span>${html`<span class="atlas-desc">${182 description && renderLine(firstSentence(description), base)183 }</span>`}${html`<span class="atlas-meta mono">${meta}</span>`}`;184}185186function panel(187 name: string,188 path: string,189 facts: [string, Html | string][],190 description: string | null,191 base: MarkdownBase,192): Html {193 return html`<h3 class="atlas-info-name">${name}</h3>194<p class="atlas-info-path mono">${path}</p>195<dl class="atlas-facts mono">${facts.map(196 ([term, value]) => html`<dt>${term}</dt><dd>${value}</dd>`,197 )}</dl>198${199 description &&200 html`<div class="markdown atlas-info-desc">${renderMarkdown(description, base)}</div>`201}`;202}203204function saveFacts(saves: Save[], view: View): [string, Html | string][] {205 const [first, last] = [saves[0], saves[saves.length - 1]];206 if (!first || !last) return [];207 return [208 ["first save", saveLink(first, view)],209 ["last save", saveLink(last, view)],210 ["saves", saves.length.toLocaleString("en-US")],211 ];212}213214function saveLink(save: Save, view: View): Html {215 return html`<a href="/${216 view.repo217 }/saves/${save.id}">${save.id}</a> ${formatDate(save.created_at)}`;218}219220function recent(saves: Save[], view: View): Html | null {221 if (saves.length === 0) return null;222 return html`<ul class="atlas-recent">${saves223 .slice(-5)224 .reverse()225 .map(226 (save) =>227 html`<li><a class="mono" href="/${228 view.repo229 }/saves/${save.id}">${save.id}</a> <span>${save.message.split("\n")[0]}</span> <span class="atlas-when mono">${relativeTime(save.created_at)}</span></li>`,230 )}</ul>`;231}232233234function folderTouches(touches: Touches): Map<string, Save[]> {235 const ids = new Map<string, Set<string>>();236 for (const [path, saves] of touches.byPath) {237 const parts = path.split("/");238 for (let depth = 1; depth < parts.length; depth++) {239 const folder = parts.slice(0, depth).join("/");240 const set = ids.get(folder) ?? new Set<string>();241 for (const save of saves) set.add(save.id);242 ids.set(folder, set);243 }244 }245 return new Map(246 [...ids].map(([folder, set]) => [folder, touches.line.filter((save) => set.has(save.id))]),247 );248}249250function allFiles(folder: AtlasFolder): AtlasFile[] {251 return [...folder.files, ...folder.folders.flatMap(allFiles)];252}253254255function markdownBase(view: View, path: string): MarkdownBase {256 return { repo: view.repo, dir: path.split("/").slice(0, -1).join("/"), at: view.at };257}258259function countLines(text: string): number {260 if (text === "") return 0;261 let count = 0;262 for (let i = text.indexOf("\n"); i >= 0; i = text.indexOf("\n", i + 1)) count++;263 return text.endsWith("\n") ? count : count + 1;264}