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

/templates filters by name with a ?q= kept in the URL, and says so when nothing matches #13547

Merged opened this

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

Merged

scout/forge:scout/13531-templates-filters-by-name-with-a-q-kept → main 6 commits fork 2 threads · 2 unresolved

  • Merged. scout/13531-templates-filters-by-name-with-a-q-kept was merged into main as 64fd138.

Review

Sign in to review this change.
6 files changed +109 −6
docs/features/new-forge-template.md +4
@@ -11,3 +11,7 @@ Code: `src/spawn/templates.ts` (ids and words), `src/spawn/forge_code.ts` (the f
1111 `/templates` lists what a new forge can start from: the built-in templates, then the template repositories you can read. Each row has one sentence and one secondary button, "Start a forge from <name>", which opens `/forges/new?template=<id>` with that template chosen. Signed out works too: a stranger lands on the same form with the template kept. `?template=` is accepted only when spawn accepts it (`parseTemplate`); anything else leaves Blank chosen, and it is never echoed. The plan (`do=plan`) shows "It starts from the <b>…</b> template".
1212
1313 The terminal has the same list: the "Templates" command (`src/tui/screens/templates.ts`) shows the same rows; Enter on a row opens New forge with that template chosen, for people signed in, and a guest is told to sign in. Both read `templateList` (`src/spawn/template_list.ts`), so a private template repository is listed only to people who can read it, on the page and in the terminal alike.
14
15 ### Filtering the list
16
17 `/templates?q=star` keeps the rows whose title or id contains the word, case-insensitively; the field keeps its value, `q` is trimmed and capped at 80 characters, and a word that matches nothing says "No template matches that name." with a link to `/templates` that clears it. In the terminal, `/` on the Templates screen types the same filter (Enter or Esc stops typing). Both use `filterTemplates` in `src/spawn/template_list.ts`.
src/spawn/template_list.ts +8
@@ -23,3 +23,11 @@ export function templateList(db: Database, viewer: User | undefined): TemplateRo
2323 return { id, title: t.title, says: t.says };
2424 });
2525 }
26
27 export const TEMPLATES_QUERY_MAX = 80;
28
29 /** Rows whose title or id contains the query, case-insensitively; an empty query keeps all. */
30 export function filterTemplates<T extends { id: string; title: string }>(rows: readonly T[], q: string): T[] {
31 const needle = q.toLowerCase();
32 return needle === "" ? [...rows] : rows.filter((r) => r.title.toLowerCase().includes(needle) || r.id.toLowerCase().includes(needle));
33 }
src/tui/screens/templates.ts +21 −3
@@ -4,7 +4,7 @@
44 * the list and is told the form is for people signed in.
55 */
66
7 import { templateList } from "../../spawn/template_list.ts";
7 import { filterTemplates, TEMPLATES_QUERY_MAX, templateList } from "../../spawn/template_list.ts";
88 import type { Ctx, Screen } from "../app/app.ts";
99 import { binding } from "../app/keys.ts";
1010 import { style } from "../term/style.ts";
@@ -14,15 +14,19 @@ import { newForgeScreen } from "./newforge.ts";
1414
1515 export function templatesScreen(session: Session, ctx: Ctx): Screen {
1616 let at = 0;
17 const rows = () => templateList(session.app.db, session.user);
17 let q = "";
18 let typing = false;
19 const rows = () => filterTemplates(templateList(session.app.db, session.user), q);
1820 return {
1921 title: "Templates",
20 keys: [binding(["j", "k"], "move"), ...(session.user === undefined ? [] : [binding(["enter"], "start a forge from it")]), binding(["esc"], "back")],
22 keys: [binding(["j", "k"], "move"), ...(session.user === undefined ? [] : [binding(["enter"], "start a forge from it")]), binding(["/"], "filter by name"), binding(["esc"], "back")],
2123 render(area, s) {
2224 const c = ctx.theme.c;
2325 const list = rows();
2426 at = Math.min(at, Math.max(0, list.length - 1));
2527 let y = area.y;
28 if (typing || q !== "") s.text(area.x + 1, y++, truncate(`Filter: ${q}${typing ? "_" : ""}`, area.w - 2), style(c.mutedFg, c.bg), area.x + area.w);
29 if (list.length === 0 && y < area.y + area.h) s.text(area.x + 1, y++, truncate("No template matches that name. Press / and clear it to show all.", area.w - 2), style(c.mutedFg, c.bg), area.x + area.w);
2630 list.forEach((r, i) => {
2731 const on = i === at;
2832 if (y < area.y + area.h) s.text(area.x + 1, y, truncate(`${on ? "> " : " "}${r.title} (${r.id})`, area.w - 2), style(on ? c.accent : c.fg, c.bg), area.x + area.w);
@@ -34,6 +38,20 @@ export function templatesScreen(session: Session, ctx: Ctx): Screen {
3438 },
3539 key(e) {
3640 if (e.ctrl || e.alt) return false;
41 if (typing) {
42 if (e.key === "enter" || e.key === "esc") typing = false;
43 else if (e.key === "backspace") q = q.slice(0, -1);
44 else if (e.key.length === 1 && q.length < TEMPLATES_QUERY_MAX) q += e.key;
45 else return false;
46 at = 0;
47 ctx.invalidate();
48 return true;
49 }
50 if (e.key === "/") {
51 typing = true;
52 ctx.invalidate();
53 return true;
54 }
3755 if (e.key === "esc" || e.key === "q") ctx.pop();
3856 else if (e.key === "j" || e.key === "down") at = Math.min(Math.max(0, rows().length - 1), at + 1);
3957 else if (e.key === "k" || e.key === "up") at = Math.max(0, at - 1);
src/web/pages/templates.ts +13 −3
@@ -7,7 +7,7 @@
77
88 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
99 import type { Ctx } from "../../http/context.ts";
10 import { templateList, type TemplateRow } from "../../spawn/template_list.ts";
10 import { filterTemplates, TEMPLATES_QUERY_MAX, templateList, type TemplateRow } from "../../spawn/template_list.ts";
1111 import { pageHead } from "../chrome.ts";
1212 import { html, type Html } from "../html.ts";
1313 import { page } from "../layout.ts";
@@ -15,6 +15,8 @@ import { btn } from "../ui.ts";
1515
1616 export const TEMPLATES_WORDS = "Pick where your forge starts. You can change everything after.";
1717
18 export const TEMPLATES_NONE = "No template matches that name.";
19
1820 /** The rows: one sentence and one button each. The unknown-template 404 shows the same list. */
1921 export function templateRows(rows: readonly TemplateRow[]): Html {
2022 return html`<ul class="plain" id="templates">
@@ -33,7 +35,9 @@ export function templateRows(rows: readonly TemplateRow[]): Html {
3335 export function templatesPage(ctx: Ctx): Response {
3436 const user = ctx.auth.user;
3537 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
36 const rows = timePhase(ctx.request, "reads", () => templateList(ctx.app.db, user?.kind === "user" ? user : undefined));
38 const q = (ctx.url.searchParams.get("q") ?? "").trim().slice(0, TEMPLATES_QUERY_MAX);
39 const all = timePhase(ctx.request, "reads", () => templateList(ctx.app.db, user?.kind === "user" ? user : undefined));
40 const rows = filterTemplates(all, q);
3741 return timePhase(ctx.request, "render", () =>
3842 page({
3943 ctx,
@@ -41,7 +45,13 @@ export function templatesPage(ctx: Ctx): Response {
4145 description: TEMPLATES_WORDS,
4246 body: html`<div class="narrow-wide">
4347 ${pageHead("Templates", { sub: TEMPLATES_WORDS })}
44 ${templateRows(rows)}
48 <form method="get" action="/templates" class="bar" role="search" aria-label="Templates">
outdated

Principle 7 (rows over boxes) / the named components: .row is the list-row component (padding 8px 14px, min-height 40, hover rules), not a form layout. Use class="bar" as src/web/pages/browse.ts does for its search form. Also the topbar already has an unlabeled role="search", so this makes two landmarks of the same name: add aria-label="Templates" to the form so a screen-reader user can tell them apart.

49 <input class="input" type="search" name="q" value="${q}" maxlength="${TEMPLATES_QUERY_MAX}" placeholder="Filter by name" aria-label="Filter templates by name">
50 ${btn("Filter", { variant: "secondary" })}
51 </form>
52 ${rows.length === 0
outdated

Principle 1 (nothing explains itself twice): when nothing matches the page renders the sentence and then an empty <ul id="templates">. Render the empty list only when rows exist so the page has one thing to say. Also add role="status" to this paragraph so the no-match result is announced after a keyboard-submitted filter.

53 ? html`<p class="muted" id="templates-none" role="status">${TEMPLATES_NONE} <a href="/templates">Show all templates</a></p>`
54 : templateRows(rows)}
4555 </div>`,
4656 }),
4757 );
test/templates-filter.test.ts added +47
@@ -0,0 +1,47 @@
1 /** /templates?q= narrows by name, keeps the query, says so when nothing matches (#13531). */
2 import { afterAll, beforeAll, expect, test } from "bun:test";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createApp, type App } from "../src/app.ts";
7 import { serve, type Servers } from "../src/http/server.ts";
8
9 let dir: string;
10 let app: App;
11 let servers: Servers;
12
13 beforeAll(async () => {
14 dir = await mkdtemp(join(tmpdir(), "forge-templates-filter-"));
15 app = createApp({ dataDir: dir, url: "https://forge.test", port: 0, forgeRepo: "alice/forge-code" });
16 servers = await serve(app);
17 }, 30_000);
18
19 afterAll(async () => {
20 servers.stop();
21 app.close();
22 await rm(dir, { recursive: true, force: true });
23 });
24
25 const get = async (q: string) => (await fetch(`${servers.url}/templates${q}`)).text();
26
27 test("q narrows case-insensitively and the field keeps its value", async () => {
28 const text = await get("?q=STARTER");
29 expect(text).toContain('data-template="starter"');
30 expect(text).not.toContain('data-template="blank"');
31 expect(text).toContain('value="STARTER"');
32 });
33
34 test("no match says one sentence and links to the cleared list", async () => {
35 const text = await get("?q=zzzz");
36 expect(text).toContain("No template matches that name.");
37 expect(text).toContain('<a href="/templates">Show all templates</a>');
38 expect(text).not.toContain("data-template=");
39 });
40
41 test("the query is escaped and capped at 80", async () => {
42 const text = await get("?q=%22%3E%3Cscript%3Ealert(1)%3C/script%3E");
43 expect(text).not.toContain("<script>alert(1)");
44 const long = await get(`?q=${"a".repeat(200)}`);
45 expect(long).toContain(`value="${"a".repeat(80)}"`);
46 expect(long).not.toContain(`value="${"a".repeat(81)}`);
47 });
test/templates-tui.test.ts +16
@@ -85,3 +85,19 @@ test("a guest reads the public rows only and is told to sign in", async () => {
8585 expect(g.tui.screen.toText()).toContain("Sign in to start a forge");
8686 g.tui.stop?.();
8787 });
88
89 test("/ filters by name in the terminal, as ?q= does on the page", async () => {
90 const t = open(otto);
91 await settleApp(t.tui);
92 for (const k of ["/", "S", "T", "A", "R", "enter"]) t.screen.key(key(k));
93 await settleApp(t.tui);
94 let text = t.tui.screen.toText();
95 expect(text).toContain("Starter app");
96 expect(text).not.toContain("Blank");
97 expect(text).toContain("Filter: STAR");
98 for (const k of ["/", "z", "enter"]) t.screen.key(key(k));
99 await settleApp(t.tui);
100 text = t.tui.screen.toText();
101 expect(text).toContain("No template matches that name.");
102 t.tui.stop?.();
103 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs