repo.ts

8.0 KB · raw

1import type { Hono } from "hono";2import { isSafePath } from "../bucket/repo.ts";3import { describeFile } from "../describe/describe.ts";4import {5	fileAt,6	filesAt,7	headId,8	history,9	objectBytes,10	repoStats,11	type Save,12	saveByPrefix,13	timeline,14} from "../mirror/queries.ts";15import { visibleReleases } from "../releases/releases.ts";16import { setting } from "../server/db.ts";17import { atlasPanel, atlasSection } from "./atlas.ts";18import { type Html, html } from "./html.ts";19import {20	cacheFor,21	notFound,22	openPublicRepo,23	type PageContext,24	type PublicRepo,25	page,26	plural,27	relativeTime,28} from "./layout.ts";29import { renderMarkdown, renderParagraph } from "./markdown.ts";30import { timelineSvg } from "./timeline.ts";3132const PAGE_SIZE = 50;33// Each opens inline under the tabs (kepr.js), as Kepr 2's panels did; the page is the fallback.34const PANELS = [35	["issues", "issues"],36	["builds", "releases"],37	["archives", "archives"],38];39const HTTP_URL = /^https?:\/\//i;4041export function registerRepoPage(app: Hono, ctx: PageContext): void {42	app.get("/:repo", (c) => {43		const repo = openPublicRepo(ctx, c.req.param("repo"));44		if (!repo) return notFound(c, ctx);45		// `?at=<id>` shows the Atlas at that save (§21.5); the rest of the page stays at HEAD.46		const at = c.req.query("at");47		const atSave = at === undefined ? null : saveByPrefix(repo.mirror, at);48		if (at !== undefined && !atSave) return notFound(c, ctx);49		const pageNumber = Math.max(1, Number.parseInt(c.req.query("page") ?? "1", 10) || 1);50		const name = repo.settings.name;51		const intro = repoIntro(repo);52		cacheFor(c, false);53		return c.html(54			page(ctx, {55				title: name,56				description: intro?.text ?? "",57				path: `/${name}`,58				body: html`${header(ctx, repo, intro?.html ?? null)}59${headId(repo.mirror) && sections(repo, pageNumber, atSave?.id ?? null)}60${details(repoDetails(repo))}`,61			}),62		);63	});64	// One Atlas row's detail panel, fetched by kepr.js on hover or select (§21.5).65	app.get("/:repo/atlas/panel", (c) => {66		const repo = openPublicRepo(ctx, c.req.param("repo"));67		const at = c.req.query("at");68		const path = c.req.query("path") ?? "";69		const save = repo && (at === undefined ? null : saveByPrefix(repo.mirror, at));70		const saveId = save?.id ?? (repo && headId(repo.mirror));71		const panel =72			repo &&73			saveId &&74			(at === undefined || save) &&75			isSafePath(path.replace(/\/$/, "")) &&76			atlasPanel(repo, saveId, save?.id ?? null, path);77		if (!panel) return notFound(c, ctx);78		cacheFor(c, save !== null && save !== undefined);79		return c.html(String(panel));80	});81}8283/**84 * The repo's description, as markup and as plain text: the operator's own, or else the README's85 * first paragraph (§21.4).86 */87export function repoIntro(repo: PublicRepo): { html: Html; text: string } | null {88	const { name, description } = repo.settings;89	if (description)90		return renderParagraph(description, { repo: name, dir: "", at: null, own: true });91	const readme = readmeAtHead(repo.mirror);92	const paragraph = readme === null ? null : describeFile("README.md", readme);93	return paragraph === null ? null : renderParagraph(paragraph, { repo: name, dir: "", at: null });94}9596/** The details section: the operator's own Markdown, or else the rendered README. */97export function repoDetails(repo: PublicRepo): Html | null {98	const { name, details } = repo.settings;99	if (details) return renderMarkdown(details, { repo: name, dir: "", at: null, own: true });100	const readme = readmeAtHead(repo.mirror);101	return readme === null ? null : renderMarkdown(readme, { repo: name, dir: "", at: null });102}103104export function readmeAtHead(mirror: PublicRepo["mirror"]): string | null {105	const head = headId(mirror);106	const path =107		head && filesAt(mirror, head).find((f) => f.path.toLowerCase() === "readme.md")?.path;108	const file = head && path ? fileAt(mirror, head, path) : null;109	const bytes = file && objectBytes(mirror, file.hash);110	return bytes ? new TextDecoder().decode(bytes) : null;111}112113function header(ctx: PageContext, repo: PublicRepo, intro: Html | null): Html {114	const { name, homepage, languages } = repo.settings;115	const steal = `koh steal ${ctx.domain}/${name}`;116	const stats = repoStats(repo.mirror);117	const handle = setting(ctx.kepr, "handle");118	// §21.4: the version is the newest release; with none, the header shows no version.119	const newest = visibleReleases(ctx.kepr, repo.mirror, name)[0];120	const meta = [121		newest && `v${newest.version}`,122		plural(stats.saves, "save"),123		stats.lines > 0 && plural(stats.lines, "line"),124		stats.updated !== null && `updated ${relativeTime(stats.updated)}`,125	].filter(Boolean);126	return html`<header class="repo-head">127<h1 class="repo-name">${name}</h1>128${handle && html`<p class="repo-contributor mono"><a href="/@${handle}">@${handle}</a></p>`}129${html`<div class="repo-desc"${!intro && " hidden"}><p>${intro}</p></div>`}130${131	HTTP_URL.test(homepage) &&132	html`<p class="repo-homepage"><a href="${homepage}">${homepage}</a></p>`133}134${135	(languages.length > 0 || stats.language) &&136	html`<div class="lang-badges">${(languages.length > 0 ? languages : [stats.language]).map(137		(language) => html`<span class="lang-badge">${language}</span>`,138	)}</div>`139}140<p class="repo-meta">${meta.join(" · ")}</p>141<div class="repo-tabbar">142<nav class="repo-tabs" aria-label="Repository panels">${PANELS.map(143		([label, path]) =>144			html`<a class="repo-tab" href="/${name}/${path}" data-panel="${path}">${label}</a>`,145	)}</nav>146<div class="install-lines">147<button type="button" class="repo-steal-btn" data-copy="${steal}">${steal}</button>148</div>149</div>150<div class="repo-panel" hidden></div>151</header>`;152}153154function sections(repo: PublicRepo, requestedPage: number, at: string | null): Html {155	const name = repo.settings.name;156	const saves = timeline(repo.mirror);157	// Past the last page, even at an unbindable number like Infinity, is page 1.158	const pageNumber = (requestedPage - 1) * PAGE_SIZE < saves.length ? requestedPage : 1;159	const rows = history(repo.mirror, PAGE_SIZE, (pageNumber - 1) * PAGE_SIZE);160	const pages: Pages = {161		at,162		newer: pageNumber > 1 ? pageNumber - 1 : null,163		older: pageNumber * PAGE_SIZE < saves.length ? pageNumber + 1 : null,164	};165	const atlas = atlasSection(repo, at ?? (headId(repo.mirror) as string), at, saves);166	return html`<section class="repo-section">167<details class="repo-section-toggle" open>168<summary class="section-head"><span class="section-label">timeline</span></summary>169${timelineSvg(name, saves)}170</details>171</section>172${atlas}173<section class="repo-section" id="history">174<details class="repo-section-toggle" open>175<summary class="section-head"><span class="section-label">history</span></summary>176${saveList(name, rows, pages)}177</details>178</section>`;179}180181type Pages = { at: string | null; newer: number | null; older: number | null };182183/**184 * One page of saves in a box that scrolls four rows at a time, as Kepr 2's; kepr.js fetches the185 * older pages into it as it scrolls, and without JavaScript the pager links page the whole view.186 */187function saveList(repo: string, rows: Save[], pages: Pages): Html {188	const pageHref = (n: number) => {189		const query = new URLSearchParams(pages.at ? { at: pages.at } : {});190		query.set("page", String(n));191		return `?${query}#history`;192	};193	return html`<div class="save-list" data-list="history">194${rows.map(195	(save) =>196		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>`,197)}198${199	(pages.newer || pages.older) &&200	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>`201}202</div>`;203}204205// Empty and hidden when there is nothing to show, so a signed-in editor still has a place to write.206function details(body: Html | null): Html {207	return html`<section class="repo-details"${!body && " hidden"}>208<details class="repo-details-toggle" open>209<summary class="repo-details-head">details</summary>210<div class="repo-details-body markdown">${body}</div>211</details>212</section>`;213}