layout.ts

5.0 KB · raw

1import type { Database } from "bun:sqlite";2import type { Context } from "hono";3import { openMirror } from "../mirror/store.ts";4import { publicRepo, type RepoSettings, setting } from "../server/db.ts";5import { type Html, html } from "./html.ts";67export type PageContext = { domain: string; kepr: Database; mirrorDir: string };89export type PublicRepo = { settings: RepoSettings; mirror: Database };1011// Static files are cached for an hour; the release in their URLs makes a new one load at once.12const { version } = (await Bun.file(`${import.meta.dir}/../../package.json`).json()) as {13	version: string;14};1516const HEAD_CACHE = "public, max-age=60";17// Content at a save never changes, but strip can remove it, so it is long-lived rather than18// immutable, and `private`, so no shared cache keeps it after the repo turns private (§20).19const SAVE_CACHE = "private, max-age=31536000";20const FONTS =21	"https://fonts.bunny.net/css?family=bellota:700|comfortaa:700|martian-mono:400|quicksand:400,600|sacramento:400&display=swap";2223/**24 * The gate of §20: a private repo and an unknown one both come back null, and so both 404 alike.25 */26export function openPublicRepo(27	ctx: Pick<PageContext, "kepr" | "mirrorDir">,28	name: string,29): PublicRepo | null {30	const settings = publicRepo(ctx.kepr, name);31	return settings ? { settings, mirror: openMirror(ctx.mirrorDir, name) } : null;32}3334export function cacheFor(c: Context, atSave: boolean): void {35	c.header("Cache-Control", atSave ? SAVE_CACHE : HEAD_CACHE);36}3738export function notFound(c: Context, ctx: PageContext): Response {39	c.header("Cache-Control", "no-store");40	const body = html`<h1 class="file-page-title">Not found</h1>41		<p class="muted">Nothing lives at this address.</p>`;42	return c.html(page(ctx, { title: "Not found", description: "", path: c.req.path, body }), 404);43}4445type PageOptions = { title: string; description: string; path: string; body: Html };4647export function page(ctx: PageContext, options: PageOptions): string {48	const site = setting(ctx.kepr, "site_name") ?? "kepr";49	const branding = setting(ctx.kepr, "branding");50	// The front page is the site itself, so its title is the bare site name.51	const title = options.title ? `${options.title} — ${site}` : site;52	const url = `https://${ctx.domain}${options.path}`;53	return html`<!doctype html>54<html lang="en">55<head>56<meta charset="utf-8">57<meta name="viewport" content="width=device-width, initial-scale=1">58<title>${title}</title>59<meta name="description" content="${options.description}">60<meta property="og:site_name" content="${site}">61<meta property="og:type" content="website">62<meta property="og:url" content="${url}">63<meta property="og:title" content="${title}">64<meta property="og:description" content="${options.description}">65<meta name="twitter:card" content="summary">66<meta name="twitter:title" content="${title}">67<meta name="twitter:description" content="${options.description}">68<meta name="theme-color" content="#090706">69<link rel="canonical" href="${url}">70<link rel="icon" href="/favicon.svg" type="image/svg+xml">71<link rel="preconnect" href="https://fonts.bunny.net">72<link rel="stylesheet" href="${FONTS}">73<link rel="stylesheet" href="/static/css/kepr.css?v=${version}">74<script src="/static/js/kepr.js?v=${version}" defer></script>75</head>76<body>77<nav>78<a class="wordmark" href="/" aria-label="${79		site80	}"><svg viewBox="0 0 32 32" class="wordmark-icon" aria-hidden="true"><g class="tri-outer"><polygon points="16,3 27,23 5,23"/></g><g class="tri-inner"><polygon points="16,10 22,21 10,21"/></g></svg></a>81${branding && html`<span class="wordmark-by">${branding}</span>`}82<span class="nav-links"><a href="/browse">browse</a><a href="/docs">docs</a>${!setting(ctx.kepr, "support_off") && html`<a href="/support">support</a>`}<a href="/sign-in?next=${encodeURIComponent(options.path).replaceAll("%2F", "/")}">log in</a></span>83</nav>84<main>85${options.body}86</main>87<footer><div class="credit">${site}</div></footer>88</body>89</html>`.value;90}9192const UNITS: [number, string][] = [93	[365 * 86400, "year"],94	[30 * 86400, "month"],95	[7 * 86400, "week"],96	[86400, "day"],97	[3600, "hour"],98	[60, "minute"],99];100101export function relativeTime(unixSeconds: number, now = Date.now() / 1000): string {102	const elapsed = now - unixSeconds;103	for (const [seconds, unit] of UNITS) {104		const n = Math.floor(elapsed / seconds);105		if (n >= 1) return `${n} ${unit}${n === 1 ? "" : "s"} ago`;106	}107	return "just now";108}109110export function formatDate(unixSeconds: number): string {111	return new Date(unixSeconds * 1000).toISOString().slice(0, 16).replace("T", " ");112}113114export function plural(n: number, noun: string): string {115	return `${n.toLocaleString("en-US")} ${noun}${n === 1 ? "" : "s"}`;116}117118export function formatSize(bytes: number): string {119	if (bytes < 1024) return `${bytes} B`;120	if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;121	return `${(bytes / 1024 / 1024).toFixed(1)} MB`;122}123124/** Percent-encodes each segment of a repo path for use in a URL. */125export function pathUrl(path: string): string {126	return path.split("/").map(encodeURIComponent).join("/");127}