Public: anyone can read this; the crew can change it.

/templates shows each template's latest picture beside its name, with a plain placeholder when it has none #14584

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

mason/forge:mason/14558-templates-shows-each-template-s-latest-p → main 13 commits fork 4 threads · 4 unresolved

  • Merged. mason/14558-templates-shows-each-template-s-latest-p was merged into main as 6d42919.

Review

Sign in to review this change.
9 files changed +177 −16
docs/design/areas/templates.md added +3
@@ -0,0 +1,3 @@
1 # Templates
2
3 - `.template-thumb` — a template's picture on /templates: its newest look in a fixed 64×40 box (lazy, alt naming the template), or the same box holding the template's initial when it has no look, so a row never shifts and never shows a broken image.
docs/design/size-budget.json +15 −11
@@ -1,31 +1,31 @@
11 {
22 "/": {
33 "js": 22016,
4 "css": 47104
4 "css": 47616
55 },
66 "/explore": {
77 "js": 21760,
8 "css": 47104
8 "css": 47616
99 },
1010 "/map": {
1111 "js": 28672,
12 "css": 48640
12 "css": 49152
1313 },
1414 "/:owner/:name": {
1515 "js": 38400,
16 "css": 47104
16 "css": 47616
1717 },
1818 "/changelog": {
1919 "js": 26880,
20 "css": 47104
20 "css": 47616
2121 },
2222 "/:owner/:name/next": {
2323 "js": 23296,
24 "css": 47360
24 "css": 47872
2525 },
2626 "/:owner/:name/space": {
2727 "js": 29696,
28 "css": 48128
28 "css": 48640
2929 },
3030 "/:owner/:name/space.json": {
3131 "js": 0,
@@ -33,18 +33,22 @@
3333 },
3434 "/maintenance": {
3535 "js": 21760,
36 "css": 47104
36 "css": 47616
3737 },
3838 "/pricing": {
3939 "js": 21760,
40 "css": 47104
40 "css": 47616
4141 },
4242 "/forges/new": {
4343 "js": 21760,
44 "css": 47104
44 "css": 47616
4545 },
4646 "/claim": {
4747 "js": 24320,
48 "css": 47104
48 "css": 47616
49 },
50 "/templates": {
51 "js": 21760,
52 "css": 47616
4953 }
5054 }
src/perf/page_budget.ts +2
@@ -23,6 +23,7 @@ import { budget as maintenance } from "./page_budgets/maintenance.ts";
2323 import { budget as pricing } from "./page_budgets/pricing.ts";
2424 import { budget as newForge } from "./page_budgets/new_forge.ts";
2525 import { budget as claim } from "./page_budgets/claim.ts";
26 import { budget as templates } from "./page_budgets/templates.ts";
2627
2728 export interface PageBudget {
2829 /** What the page is, in words, for the failure line. */
@@ -56,6 +57,7 @@ export const PAGE_BUDGETS: readonly PageBudget[] = [
5657 pricing,
5758 newForge,
5859 claim,
60 templates,
5961 ];
6062
6163 /**
src/perf/page_budgets/templates.ts added +4
@@ -0,0 +1,4 @@
1 import type { PageBudget } from "../page_budget.ts";
2
3 // The templates list with each row's picture (#14558): walked signed out.
4 export const budget: PageBudget = { page: "templates", pattern: "/templates", medianMs: 50, statements: 12, signedOut: true };
src/web/pages/templates.ts +16 −2
@@ -20,6 +20,7 @@ import { html, type Html } from "../html.ts";
2020 import { page } from "../layout.ts";
2121 import { previewLink } from "../template_card.ts";
2222 import { btn } from "../ui.ts";
23 import { templatePictures } from "../template_picture.ts";
2324
2425 export const TEMPLATES_WORDS = "Pick where your forge starts. You can change everything after.";
2526
@@ -35,13 +36,25 @@ function holdsView(id: string, holds: TemplateHolds | undefined, known: boolean)
3536 </dl>`;
3637 }
3738
outdated

alt duplicates the adjacent <b>title</b>; word it as 'Latest look of …'. Move the initial logic into a named helper.

39 /** The letter a template's placeholder box shows: the first of its name, without the owner. */
40 export function templateInitial(title: string): string {
41 return [...(title.split("/").pop() ?? "")][0]?.toUpperCase() ?? "?";
42 }
43
44 /** A template's picture at a fixed size, or a neutral box with its initial when it has none. */
45 function thumb(r: TemplateRow, src: string | undefined): Html {
46 if (src === undefined) return html`<span class="template-thumb" aria-hidden="true">${templateInitial(r.title)}</span>`;
47 return html`<img class="template-thumb" src="${src}" width="64" height="40" alt="Latest look of ${r.title}" loading="lazy" decoding="async">`;
48 }
49
3850 /** The rows: one sentence and one button each. The unknown-template 404 shows the same list. */
39 export function templateRows(rows: readonly TemplateRow[], held?: ReadonlyMap<string, TemplateHolds | undefined>, used?: ReadonlyMap<string, TemplateUse>): Html {
51 export function templateRows(rows: readonly TemplateRow[], held?: ReadonlyMap<string, TemplateHolds | undefined>, used?: ReadonlyMap<string, TemplateUse>, pictures?: ReadonlyMap<string, string>): Html {
4052 return html`<ul class="plain" id="templates">
4153 ${rows.map(
4254 (r) => html`<li data-template="${r.id}">
4355 <form method="get" action="/forges/new" class="row">
4456 <input type="hidden" name="template" value="${r.id}">
57 ${pictures === undefined ? null : thumb(r, pictures.get(r.id))}
4558 <span><b>${r.title}</b> ${r.says}${held === undefined ? null : html` ${previewLink(r.id, r.title, held.get(r.id))}`}</span>
4659 ${btn(`Start a forge from ${r.title}`, { variant: "secondary" })}
4760 </form>
@@ -62,6 +75,7 @@ export async function templatesPage(ctx: Ctx): Promise<Response> {
6275 const held = new Map<string, TemplateHolds | undefined>();
6376 await Promise.all(rows.map(async (r) => held.set(r.id, await templateHolds(ctx.app, r.id))));
6477 const used = templateUse(await listChildren(ctx.app));
78 const pictures = timePhase(ctx.request, "pictures", () => templatePictures(ctx, rows.map((r) => r.id)));
6579 return timePhase(ctx.request, "render", () =>
6680 page({
6781 ctx,
@@ -75,7 +89,7 @@ export async function templatesPage(ctx: Ctx): Promise<Response> {
7589 </form>
7690 ${rows.length === 0
7791 ? html`<p class="muted" id="templates-none" role="status">${TEMPLATES_NONE} <a href="/templates">Show all templates</a></p>`
78 : templateRows(rows, held, used)}
92 : templateRows(rows, held, used, pictures)}
7993 ${q === "" && noRepoTemplates(listed)
8094 ? user?.isAdmin === true
8195 ? html`<p class="muted" id="templates-empty" role="status"><a href="/repos">${TEMPLATES_EMPTY_ADMIN}</a>: repository settings, App card.</p>`
src/web/style/components.ts +4
@@ -468,6 +468,10 @@ a.sha:hover { color: var(--accent); }
468468 .look img { display: block; width: 100%; height: auto; }
469469 .look[data-slot="thumb"] { flex: none; width: 30px; height: 40px; border-radius: 4px; }
470470 .look[data-slot="thumb"] img { height: 100%; object-fit: cover; object-position: top; }
471 /* A template's picture on /templates: one fixed box, so the row never shifts; the placeholder is the same box with an initial. */
472 .template-thumb { flex: none; display: inline-flex; align-items: center; justify-content: center; width: 64px; height: 40px; border-radius: var(--radius-sm); background: var(--muted); object-fit: cover; object-position: top; font-weight: 600; }
outdated

Principle 6: drop border: 1px solid var(--border); the muted fill already marks the box.

473 /* The sentence takes the room the picture and button leave and wraps inside it, so a 360px phone never squeezes it to nothing. */
474 #templates form.row > span:not(.template-thumb) { flex: 1 1 0; min-width: 0; overflow-wrap: anywhere; }
471475 .permalink, [data-filter-app] { display: inline-block; padding: 12px 6px; margin: -12px -6px; }
472476 /* The depth link under a post: a touch-sized hit area, the line itself no taller. */
473477 [data-depth] { display: inline-flex; align-items: center; min-height: 44px; padding: 0 6px; margin: -12px -6px; }
src/web/template_picture.ts added +30
@@ -0,0 +1,30 @@
1 /**
2 * The picture beside a template on /templates: its repository's newest production look, the one
3 * the repository page uses, as a URL; none for a built-in or a repository with no look the viewer
4 * may fetch. One read of every look for all the rows.
5 */
6
7 import { getAppByRepo } from "../core/apps.ts";
8 import { looksForApps, lookUrl } from "../core/looks.ts";
9 import { getRepo } from "../core/repos.ts";
10 import { repoBase } from "./chrome.ts";
11 import { thumbLook, type Reader } from "./pages/looks.ts";
12
13 /** Template id to picture URL, for the ids that have one. */
14 export function templatePictures(ctx: Reader, ids: readonly string[]): Map<string, string> {
15 const db = ctx.app.db;
16 const found = ids.flatMap((id) => {
17 const [owner, name, ...rest] = id.split("/");
18 if (owner === undefined || name === undefined || rest.length > 0) return [];
19 const repo = getRepo(db, owner, name);
20 const record = repo && getAppByRepo(db, repo.id);
21 return repo && record ? [{ id, repo, record }] : [];
22 });
23 const looks = looksForApps(db, found.map((f) => f.record.id));
24 const out = new Map<string, string>();
25 for (const f of found) {
26 const look = thumbLook(ctx, f.repo, f.record, looks.filter((l) => l.appId === f.record.id && l.env === "production"));
27 if (look) out.set(f.id, lookUrl(repoBase(f.repo), look));
28 }
29 return out;
30 }
test/page-budget.test.ts +3 −3
@@ -161,10 +161,10 @@ async function time(
161161 return { samples, walls, phases: parsePhases(header) };
162162 }
163163
164 test("the budget table names twelve pages, each once, with a median and a statement limit", () => {
164 test("the budget table names thirteen pages, each once, with a median and a statement limit", () => {
165165 expect(PAGE_BUDGETS.map((b) => b.pattern)).toEqual([
166166 "/", "/explore", "/map", "/:owner/:name", "/changelog", "/:owner/:name/next",
167 "/:owner/:name/space", "/:owner/:name/space.json", "/maintenance", "/pricing", "/forges/new", "/claim",
167 "/:owner/:name/space", "/:owner/:name/space.json", "/maintenance", "/pricing", "/forges/new", "/claim", "/templates",
168168 ]);
169169 for (const b of PAGE_BUDGETS) {
170170 expect(b.medianMs).toBeLessThanOrEqual(50);
@@ -174,7 +174,7 @@ test("the budget table names twelve pages, each once, with a median and a statem
174174
175175 test("a stranger's way to a forge is on the list, walked signed out", () => {
176176 const strangers = PAGE_BUDGETS.filter((b) => b.signedOut).map((b) => b.pattern);
177 expect(strangers).toEqual(["/pricing", "/forges/new", "/claim"]);
177 expect(strangers).toEqual(["/pricing", "/forges/new", "/claim", "/templates"]);
178178 });
179179
180180 test("each first page runs no more SQL statements warm than its budget", async () => {
test/templates-picture.test.ts added +100
@@ -0,0 +1,100 @@
1 /**
2 * /templates shows each template's newest look at a fixed size, or a plain box with its initial
3 * (#14558).
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { encodePng } from "../src/design/image/png.ts";
10 import { createApp, type App } from "../src/app.ts";
11 import { commitToBranch, createRepo, updateRepoSettings } from "../src/actions/repos.ts";
12 import { createApp as insertApp } from "../src/core/apps.ts";
13 import { recordLook } from "../src/core/looks.ts";
14 import { getRepo } from "../src/core/repos.ts";
15 import { createUser } from "../src/core/users.ts";
16 import { serve, type Servers } from "../src/http/server.ts";
17 import { templateInitial, templateRows } from "../src/web/pages/templates.ts";
18 import { quietLogs } from "./helpers/globals.ts";
19
20 quietLogs();
21
22 let dir: string;
23 let app: App;
24 let servers: Servers;
25 const OID = "a".repeat(40);
26
27 beforeAll(async () => {
28 dir = await mkdtemp(join(tmpdir(), "forge-templates-picture-"));
29 app = createApp({ dataDir: dir, port: 0 });
30 servers = await serve(app);
31 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
32 if (!made.ok) throw new Error("user");
33 for (const name of ["seen", "unseen", "private"]) {
34 const repo = await createRepo(app, made.value, { name, visibility: "public", description: "" });
35 if (!repo.ok) throw new Error("repo");
36 await commitToBranch(app, made.value, repo.value, { message: "seed", files: [{ path: "forge.json", content: '{"app":{"run":"bun main.ts"}}' }] });
37 const marked = await updateRepoSettings(app, made.value, getRepo(app.db, "alice", name) ?? repo.value, { template: true });
38 if (!marked.ok) throw new Error("mark");
39 const rec = insertApp(app.db, { repoId: repo.value.id, slug: name, access: "public" });
40 if (!rec.ok) throw new Error(rec.error);
41 if (name === "seen") {
42 await mkdir(join(dir, "looks"), { recursive: true });
43 await writeFile(join(dir, "looks/x.png"), encodePng(640, 400, new Uint8Array(640 * 400 * 4)));
44 }
45 if (name === "private") {
46 // A phone shot is the owner's view: a stranger may not fetch it, so the row shows the box.
47 await mkdir(join(dir, "looks"), { recursive: true });
48 await writeFile(join(dir, "looks/p.png"), encodePng(390, 844, new Uint8Array(390 * 844 * 4)));
49 recordLook(app.db, { appId: rec.value.id, env: "production", commitOid: OID, kind: "phone", path: "looks/p.png", takenAs: "owner" });
50 }
51 if (name === "seen") recordLook(app.db, { appId: rec.value.id, env: "production", commitOid: OID, kind: "thumb", path: "looks/x.png", takenAs: "nobody" });
52 }
53 }, 30_000);
54
55 afterAll(async () => {
56 servers.stop();
57 app.close();
58 await rm(dir, { recursive: true, force: true });
59 });
60
61 const rowOf = (body: string, id: string): string => body.split("<li ").find((s) => s.includes(`data-template="${id}"`)) ?? "";
62
63 test("a template with a look shows it, fixed size, lazy, alt naming it", async () => {
64 const body = await (await fetch(`${servers.url}/templates`)).text();
65 const row = rowOf(body, "alice/seen");
66 expect(row).toContain('src="/alice/seen/looks/production/' + OID + '/thumb.png');
67 expect(row).toContain('width="64" height="40"');
68 expect(row).toContain('loading="lazy"');
69 expect(row).toContain('alt="Latest look of alice/seen"');
70 });
71
72 test("a template with no look, and a built-in, show a box with the initial and no image", async () => {
73 const body = await (await fetch(`${servers.url}/templates`)).text();
74 for (const id of ["alice/unseen", "starter"]) {
75 const row = rowOf(body, id);
76 expect(row).not.toContain("<img");
77 expect(row).toContain('class="template-thumb"');
outdated

Assert the escaped form (&lt;script&gt; inside alt="...") and that no raw <script> appears; toContain("alt=") passes for almost any output.

78 }
79 expect(rowOf(body, "alice/unseen")).toContain(">U</span>");
80 });
81
82 test("the alt text is escaped", () => {
83 const rows = [{ id: "x/y", title: '"><script>alert(1)</script>', says: "s" }];
84 const out = String(templateRows(rows, undefined, undefined, new Map([["x/y", "/p.png"]])));
outdated

A 500 ms bound proves nothing about the page budget; use the repo's existing page-budget helper/threshold, and add a case where the look is private to the viewer and the placeholder shows.

85 expect(out).not.toContain("<script>");
86 expect(out).toContain('alt="Latest look of &quot;&gt;&lt;script&gt;alert(1)&lt;/script&gt;"');
87 });
88
89 test("a look the viewer may not fetch gives the placeholder, not a broken image", async () => {
90 const body = await (await fetch(`${servers.url}/templates`)).text();
91 const row = rowOf(body, "alice/private");
92 expect(row).not.toContain("<img");
93 expect(row).toContain(">P</span>");
94 });
95
96 test("the initial is the first letter of the name without its owner", () => {
97 expect(templateInitial("alice/notes")).toBe("N");
98 expect(templateInitial("starter")).toBe("S");
99 expect(templateInitial("")).toBe("?");
100 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs