repo.ts

9.6 KB · raw

1import type { Hono } from "hono";2import { isSafePath } from "../bucket/repo.ts";3import { describeFile } from "../describe/describe.ts";4import { issueCounts } from "../issues/store.ts";5import {6	fileAt,7	filesAt,8	headId,9	history,10	objectBytes,11	repoStats,12	type Save,13	saveByPrefix,14	timeline,15} from "../mirror/queries.ts";16import { mirrorState } from "../mirror/store.ts";17import { visibleReleases } from "../releases/releases.ts";18import { setting } from "../server/db.ts";19import { atlasPanel, atlasPickerRows, atlasSection } from "./atlas.ts";20import { type Html, html } from "./html.ts";21import {22	cacheFor,23	notFound,24	openPublicRepo,25	type PageContext,26	type PublicRepo,27	page,28	plural,29	relativeTime,30} from "./layout.ts";31import { renderMarkdown, renderParagraph } from "./markdown.ts";32import { timelineSaves, timelineSvg } from "./timeline.ts";3334const PAGE_SIZE = 50;35// Each opens inline under the tabs (kepr.js), as Kepr 2's panels did; the page is the fallback.36const PANELS = [37	["issues", "issues"],38	["builds", "releases"],39	["archives", "archives"],40];41const HTTP_URL = /^https?:\/\//i;4243export function registerRepoPage(app: Hono, ctx: PageContext): void {44	app.get("/:repo", (c) => {45		const repo = openPublicRepo(ctx, c.req.param("repo"));46		if (!repo) return notFound(c, ctx);47		// `?at=<id>` shows the Atlas at that save (§21.5); the rest of the page stays at HEAD.48		const at = c.req.query("at");49		const atSave = at === undefined ? null : saveByPrefix(repo.mirror, at);50		if (at !== undefined && !atSave) return notFound(c, ctx);51		const pageNumber = Math.max(1, Number.parseInt(c.req.query("page") ?? "1", 10) || 1);52		const name = repo.settings.name;53		// §21.4: the README, inflated once for both the intro and the details.54		const readme =55			!repo.settings.description || !repo.settings.details ? readmeAtHead(repo.mirror) : null;56		const intro = repoIntro(repo, readme);57		cacheFor(c, false);58		return c.html(59			page(ctx, {60				title: name,61				description: intro?.text ?? "",62				path: `/${name}`,63				body: html`${header(ctx, repo, intro?.html ?? null)}64${headId(repo.mirror) && sections(repo, pageNumber, atSave?.id ?? null)}65${details(repoDetails(repo, readme))}`,66			}),67		);68	});69	// The timeline's saves, fetched by kepr.js once the page has drawn (§21.4).70	app.get("/:repo/timeline", (c) => {71		const repo = openPublicRepo(ctx, c.req.param("repo"));72		if (!repo) return notFound(c, ctx);73		cacheFor(c, false);74		return c.json(timelineSaves(timeline(repo.mirror)));75	});76	// The Atlas picker's rows, fetched by kepr.js when it first opens (§21.5).77	app.get("/:repo/atlas/saves", (c) => {78		const repo = openPublicRepo(ctx, c.req.param("repo"));79		const at = c.req.query("at");80		const save = repo && at !== undefined ? saveByPrefix(repo.mirror, at) : null;81		if (!repo || (at !== undefined && !save)) return notFound(c, ctx);82		cacheFor(c, false);83		const rows = atlasPickerRows(repo.settings.name, timeline(repo.mirror), save?.id ?? null);84		return c.html(rows.map(String).join(""));85	});86	// One Atlas row's detail panel, fetched by kepr.js on hover or select (§21.5).87	app.get("/:repo/atlas/panel", (c) => {88		const repo = openPublicRepo(ctx, c.req.param("repo"));89		const at = c.req.query("at");90		const path = c.req.query("path") ?? "";91		const save = repo && (at === undefined ? null : saveByPrefix(repo.mirror, at));92		const saveId = save?.id ?? (repo && headId(repo.mirror));93		const panel =94			repo &&95			saveId &&96			(at === undefined || save) &&97			isSafePath(path.replace(/\/$/, "")) &&98			atlasPanel(repo, saveId, save?.id ?? null, path);99		if (!panel) return notFound(c, ctx);100		cacheFor(c, save !== null && save !== undefined);101		return c.html(String(panel));102	});103}104105/**106 * The repo's description, as markup and as plain text: the operator's own, or else the README's107 * first paragraph (§21.4).108 */109export function repoIntro(110	repo: PublicRepo,111	readme?: string | null,112): { html: Html; text: string } | null {113	const { name, description } = repo.settings;114	if (description)115		return renderParagraph(description, { repo: name, dir: "", at: null, own: true });116	const text = readme === undefined ? readmeAtHead(repo.mirror) : readme;117	const paragraph = text === null ? null : describeFile("README.md", text);118	return paragraph === null ? null : renderParagraph(paragraph, { repo: name, dir: "", at: null });119}120121/** The details section: the operator's own Markdown, or else the rendered README. */122export function repoDetails(repo: PublicRepo, readme?: string | null): Html | null {123	const { name, details } = repo.settings;124	if (details) return renderMarkdown(details, { repo: name, dir: "", at: null, own: true });125	const text = readme === undefined ? readmeAtHead(repo.mirror) : readme;126	return text === null ? null : renderMarkdown(text, { repo: name, dir: "", at: null });127}128129export function readmeAtHead(mirror: PublicRepo["mirror"]): string | null {130	const head = headId(mirror);131	const path =132		head && filesAt(mirror, head).find((f) => f.path.toLowerCase() === "readme.md")?.path;133	const file = head && path ? fileAt(mirror, head, path) : null;134	const bytes = file && objectBytes(mirror, file.hash);135	return bytes ? new TextDecoder().decode(bytes) : null;136}137138function header(ctx: PageContext, repo: PublicRepo, intro: Html | null): Html {139	const { name, homepage, languages } = repo.settings;140	const steal = `koh steal ${ctx.domain}/${name}`;141	const stats = repoStats(repo.mirror);142	const handle = setting(ctx.kepr, "handle");143	const openIssues = issueCounts(ctx.kepr, name).open;144	// §21.4: the version is the newest release; with none, the version the project declares, by145	// Koh's rule, at its newest save.146	const version =147		visibleReleases(ctx.kepr, repo.mirror, name)[0]?.version ||148		mirrorState(repo.mirror, "declared_version");149	const meta = [150		version && html`<span class="repo-version">v${version}</span>`,151		plural(stats.saves, "save"),152		stats.lines > 0 && plural(stats.lines, "line"),153		stats.updated !== null && `updated ${relativeTime(stats.updated)}`,154	].filter(Boolean);155	return html`<header class="repo-head">156<h1 class="repo-name">${name}</h1>157${handle && html`<p class="repo-contributor mono"><a href="/@${handle}">@${handle}</a></p>`}158${html`<div class="repo-desc"${!intro && " hidden"}><p>${intro}</p></div>`}159${160	HTTP_URL.test(homepage) &&161	html`<p class="repo-homepage"><a href="${homepage}">${homepage}</a></p>`162}163${164	(languages.length > 0 || stats.language) &&165	html`<div class="lang-badges">${(languages.length > 0 ? languages : [stats.language]).map(166		(language) => html`<span class="lang-badge">${language}</span>`,167	)}</div>`168}169<p class="repo-meta">${meta.flatMap((part, i) => (i === 0 ? [part] : [" · ", part]))}</p>170<div class="repo-tabbar">171<nav class="repo-tabs" aria-label="Repository panels">${PANELS.map(172		([label, path]) =>173			html`<a class="repo-tab" href="/${name}/${path}" data-panel="${path}">${label}${174				path === "issues" &&175				openIssues > 0 &&176				html`<span class="repo-issue-count" aria-label="${plural(177					openIssues,178					"open issue",179				)}">${openIssues}</span>`180			}</a>`,181	)}</nav>182<div class="install-lines">183<button type="button" class="repo-steal-btn" data-copy="${steal}">${steal}</button>184</div>185</div>186<div class="repo-panel" hidden></div>187</header>`;188}189190function sections(repo: PublicRepo, requestedPage: number, at: string | null): Html {191	const name = repo.settings.name;192	const saves = timeline(repo.mirror);193	// Past the last page, even at an unbindable number like Infinity, is page 1.194	const pageNumber = (requestedPage - 1) * PAGE_SIZE < saves.length ? requestedPage : 1;195	const rows = history(repo.mirror, PAGE_SIZE, (pageNumber - 1) * PAGE_SIZE);196	const pages: Pages = {197		at,198		newer: pageNumber > 1 ? pageNumber - 1 : null,199		older: pageNumber * PAGE_SIZE < saves.length ? pageNumber + 1 : null,200	};201	const atlas = atlasSection(repo, at ?? (headId(repo.mirror) as string), at);202	return html`<section class="repo-section">203<details class="repo-section-toggle" open>204<summary class="section-head"><span class="section-label">timeline</span></summary>205${timelineSvg(name, saves)}206</details>207</section>208${atlas}209<section class="repo-section" id="history">210<details class="repo-section-toggle" open>211<summary class="section-head"><span class="section-label">history</span></summary>212${saveList(name, rows, pages)}213</details>214</section>`;215}216217type Pages = { at: string | null; newer: number | null; older: number | null };218219/**220 * One page of saves in a box that scrolls four rows at a time, as Kepr 2's; kepr.js fetches the221 * older pages into it as it scrolls, and without JavaScript the pager links page the whole view.222 */223function saveList(repo: string, rows: Save[], pages: Pages): Html {224	const pageHref = (n: number) => {225		const query = new URLSearchParams(pages.at ? { at: pages.at } : {});226		query.set("page", String(n));227		return `?${query}#history`;228	};229	return html`<div class="save-list" data-list="history">230${rows.map(231	(save) =>232		html`<a class="history-row" href="/${repo}/saves/${save.id}"><span class="history-id">${save.id}</span><span class="history-msg">${save.message.split("\n")[0]}</span><span class="history-when">${relativeTime(save.created_at)}</span></a>`,233)}234${235	(pages.newer || pages.older) &&236	html`<p class="pager mono">${pages.newer && html`<a href="${pageHref(pages.newer)}">← newer</a>`}${pages.older && html`<a class="pager-older" href="${pageHref(pages.older)}">older →</a>`}</p>`237}238</div>`;239}240241// Empty and hidden when there is nothing to show, so a signed-in editor still has a place to write.242function details(body: Html | null): Html {243	return html`<section class="repo-details"${!body && " hidden"}>244<details class="repo-details-toggle" open>245<summary class="repo-details-head">details</summary>246<div class="repo-details-body markdown">${body}</div>247</details>248</section>`;249}