repo.ts

8.5 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, atlasPickerRows, 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	// The Atlas picker's rows, fetched by kepr.js when it first opens (§21.5).65	app.get("/:repo/atlas/saves", (c) => {66		const repo = openPublicRepo(ctx, c.req.param("repo"));67		const at = c.req.query("at");68		const save = repo && at !== undefined ? saveByPrefix(repo.mirror, at) : null;69		if (!repo || (at !== undefined && !save)) return notFound(c, ctx);70		cacheFor(c, false);71		const rows = atlasPickerRows(repo.settings.name, timeline(repo.mirror), save?.id ?? null);72		return c.html(rows.map(String).join(""));73	});74	// One Atlas row's detail panel, fetched by kepr.js on hover or select (§21.5).75	app.get("/:repo/atlas/panel", (c) => {76		const repo = openPublicRepo(ctx, c.req.param("repo"));77		const at = c.req.query("at");78		const path = c.req.query("path") ?? "";79		const save = repo && (at === undefined ? null : saveByPrefix(repo.mirror, at));80		const saveId = save?.id ?? (repo && headId(repo.mirror));81		const panel =82			repo &&83			saveId &&84			(at === undefined || save) &&85			isSafePath(path.replace(/\/$/, "")) &&86			atlasPanel(repo, saveId, save?.id ?? null, path);87		if (!panel) return notFound(c, ctx);88		cacheFor(c, save !== null && save !== undefined);89		return c.html(String(panel));90	});91}9293/**94 * The repo's description, as markup and as plain text: the operator's own, or else the README's95 * first paragraph (§21.4).96 */97export function repoIntro(repo: PublicRepo): { html: Html; text: string } | null {98	const { name, description } = repo.settings;99	if (description)100		return renderParagraph(description, { repo: name, dir: "", at: null, own: true });101	const readme = readmeAtHead(repo.mirror);102	const paragraph = readme === null ? null : describeFile("README.md", readme);103	return paragraph === null ? null : renderParagraph(paragraph, { repo: name, dir: "", at: null });104}105106/** The details section: the operator's own Markdown, or else the rendered README. */107export function repoDetails(repo: PublicRepo): Html | null {108	const { name, details } = repo.settings;109	if (details) return renderMarkdown(details, { repo: name, dir: "", at: null, own: true });110	const readme = readmeAtHead(repo.mirror);111	return readme === null ? null : renderMarkdown(readme, { repo: name, dir: "", at: null });112}113114export function readmeAtHead(mirror: PublicRepo["mirror"]): string | null {115	const head = headId(mirror);116	const path =117		head && filesAt(mirror, head).find((f) => f.path.toLowerCase() === "readme.md")?.path;118	const file = head && path ? fileAt(mirror, head, path) : null;119	const bytes = file && objectBytes(mirror, file.hash);120	return bytes ? new TextDecoder().decode(bytes) : null;121}122123function header(ctx: PageContext, repo: PublicRepo, intro: Html | null): Html {124	const { name, homepage, languages } = repo.settings;125	const steal = `koh steal ${ctx.domain}/${name}`;126	const stats = repoStats(repo.mirror);127	const handle = setting(ctx.kepr, "handle");128	// §21.4: the version is the newest release; with none, the header shows no version.129	const newest = visibleReleases(ctx.kepr, repo.mirror, name)[0];130	const meta = [131		newest && `v${newest.version}`,132		plural(stats.saves, "save"),133		stats.lines > 0 && plural(stats.lines, "line"),134		stats.updated !== null && `updated ${relativeTime(stats.updated)}`,135	].filter(Boolean);136	return html`<header class="repo-head">137<h1 class="repo-name">${name}</h1>138${handle && html`<p class="repo-contributor mono"><a href="/@${handle}">@${handle}</a></p>`}139${html`<div class="repo-desc"${!intro && " hidden"}><p>${intro}</p></div>`}140${141	HTTP_URL.test(homepage) &&142	html`<p class="repo-homepage"><a href="${homepage}">${homepage}</a></p>`143}144${145	(languages.length > 0 || stats.language) &&146	html`<div class="lang-badges">${(languages.length > 0 ? languages : [stats.language]).map(147		(language) => html`<span class="lang-badge">${language}</span>`,148	)}</div>`149}150<p class="repo-meta">${meta.join(" · ")}</p>151<div class="repo-tabbar">152<nav class="repo-tabs" aria-label="Repository panels">${PANELS.map(153		([label, path]) =>154			html`<a class="repo-tab" href="/${name}/${path}" data-panel="${path}">${label}</a>`,155	)}</nav>156<div class="install-lines">157<button type="button" class="repo-steal-btn" data-copy="${steal}">${steal}</button>158</div>159</div>160<div class="repo-panel" hidden></div>161</header>`;162}163164function sections(repo: PublicRepo, requestedPage: number, at: string | null): Html {165	const name = repo.settings.name;166	const saves = timeline(repo.mirror);167	// Past the last page, even at an unbindable number like Infinity, is page 1.168	const pageNumber = (requestedPage - 1) * PAGE_SIZE < saves.length ? requestedPage : 1;169	const rows = history(repo.mirror, PAGE_SIZE, (pageNumber - 1) * PAGE_SIZE);170	const pages: Pages = {171		at,172		newer: pageNumber > 1 ? pageNumber - 1 : null,173		older: pageNumber * PAGE_SIZE < saves.length ? pageNumber + 1 : null,174	};175	const atlas = atlasSection(repo, at ?? (headId(repo.mirror) as string), at);176	return html`<section class="repo-section">177<details class="repo-section-toggle" open>178<summary class="section-head"><span class="section-label">timeline</span></summary>179${timelineSvg(name, saves)}180</details>181</section>182${atlas}183<section class="repo-section" id="history">184<details class="repo-section-toggle" open>185<summary class="section-head"><span class="section-label">history</span></summary>186${saveList(name, rows, pages)}187</details>188</section>`;189}190191type Pages = { at: string | null; newer: number | null; older: number | null };192193/**194 * One page of saves in a box that scrolls four rows at a time, as Kepr 2's; kepr.js fetches the195 * older pages into it as it scrolls, and without JavaScript the pager links page the whole view.196 */197function saveList(repo: string, rows: Save[], pages: Pages): Html {198	const pageHref = (n: number) => {199		const query = new URLSearchParams(pages.at ? { at: pages.at } : {});200		query.set("page", String(n));201		return `?${query}#history`;202	};203	return html`<div class="save-list" data-list="history">204${rows.map(205	(save) =>206		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>`,207)}208${209	(pages.newer || pages.older) &&210	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>`211}212</div>`;213}214215// Empty and hidden when there is nothing to show, so a signed-in editor still has a place to write.216function details(body: Html | null): Html {217	return html`<section class="repo-details"${!body && " hidden"}>218<details class="repo-details-toggle" open>219<summary class="repo-details-head">details</summary>220<div class="repo-details-body markdown">${body}</div>221</details>222</section>`;223}