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

/templates filters by a ?q= word with a plain GET form #13989

Merged opened this

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

Merged

scout/forge:scout/13973-templates-filters-by-a-q-word-with-a-pla → main 6 commits fork

  • Merged. scout/13973-templates-filters-by-a-q-word-with-a-pla was merged into main as e5c35ac.

Review

Sign in to review this change.
6 files changed +74 −5
docs/features/README.md +1
@@ -250,6 +250,7 @@ Read with the guide page [Your apps](../guide-your-apps.md).
250250 - [An app's own domain: cut-over and the way back](app-own-domain.md)
251251 - [App templates](app-templates.md)
252252 - [Template page](template-page.md)
253 - [Find a template by a word in its name or description](templates-search.md)
253254 - [Archive listing](archive-listing.md)
254255 - [A binary file shows its size and type](binary-file.md)
255256 - [An OPML or RSS/Atom file opens as its entries](feed-xml.md)
docs/features/templates-search.md added +8
@@ -0,0 +1,8 @@
1 # Find a template
2
3 `/templates?q=word` narrows the list to templates whose name, id or description contains the word, case-insensitively.
4
5 - **Page:** a plain GET form (`role="search"`), server-rendered, no script. The box keeps what was typed, escaped, capped at 80 characters.
6 - **No match:** one sentence, "No template matches that name.", and a link to the full list.
7 - **Terminal:** `/templates` in the terminal filters with `/` and reads the same function (`filterTemplates`, `src/spawn/template_list.ts`), so both doors match the same rows.
8 - Code: `src/web/pages/templates.ts`, `src/tui/screens/templates.ts`. Tests: `test/templates-search.test.ts`, `test/templates-filter.test.ts`, `test/templates-tui.test.ts`.
src/spawn/template_list.ts +7 −3
@@ -48,8 +48,12 @@ export function templateRow(db: Database, viewer: User | undefined, id: string):
4848
4949 export const TEMPLATES_QUERY_MAX = 80;
5050
51 /** Rows whose title or id contains the query, case-insensitively; an empty query keeps all. */
52 export function filterTemplates<T extends { id: string; title: string }>(rows: readonly T[], q: string): T[] {
51 /**
52 * Rows whose title, id or description contains the query, case-insensitively; an empty query keeps
53 * all.
54 */
55 export function filterTemplates<T extends { id: string; title: string; says?: string }>(rows: readonly T[], q: string): T[] {
5356 const needle = q.toLowerCase();
54 return needle === "" ? [...rows] : rows.filter((r) => r.title.toLowerCase().includes(needle) || r.id.toLowerCase().includes(needle));
57 if (needle === "") return [...rows];
58 return rows.filter((r) => [r.title, r.id, r.says ?? ""].some((f) => f.toLowerCase().includes(needle)));
5559 }
src/tui/screens/templates.ts +1 −1
@@ -20,7 +20,7 @@ export function templatesScreen(session: Session, ctx: Ctx): Screen {
2020 const rows = () => filterTemplates(templateList(session.app.db, session.user), q);
2121 return {
2222 title: "Templates",
23 keys: [binding(["j", "k"], "move"), ...(session.user === undefined ? [] : [binding(["enter"], "start a forge from it")]), binding(["/"], "filter by name"), binding(["esc"], "back")],
23 keys: [binding(["j", "k"], "move"), ...(session.user === undefined ? [] : [binding(["enter"], "start a forge from it")]), binding(["/"], "filter by name or description"), binding(["esc"], "back")],
2424 render(area, s) {
2525 const c = ctx.theme.c;
2626 const list = rows();
src/web/pages/templates.ts +1 −1
@@ -46,7 +46,7 @@ export function templatesPage(ctx: Ctx): Response {
4646 body: html`<div class="narrow-wide">
4747 ${pageHead("Templates", { sub: TEMPLATES_WORDS })}
4848 <form method="get" action="/templates" class="bar" role="search" aria-label="Templates">
49 <input class="input" type="search" name="q" value="${q}" maxlength="${TEMPLATES_QUERY_MAX}" placeholder="Filter by name" aria-label="Filter templates by name">
49 <input class="input" type="search" name="q" value="${q}" maxlength="${TEMPLATES_QUERY_MAX}" placeholder="Filter by name or description" aria-label="Filter templates by name or description">
5050 ${btn("Filter", { variant: "secondary" })}
5151 </form>
5252 ${rows.length === 0
test/templates-search.test.ts added +56
@@ -0,0 +1,56 @@
1 /**
2 * /templates?q= matches name and description, no match offers the full list, a hostile q is escaped
3 * (#13973).
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { serve, type Servers } from "../src/http/server.ts";
11 import { filterTemplates } from "../src/spawn/template_list.ts";
12 import { TEMPLATES } from "../src/spawn/templates.ts";
13
14 let dir: string;
15 let app: App;
16 let servers: Servers;
17
18 beforeAll(async () => {
19 dir = await mkdtemp(join(tmpdir(), "forge-templates-search-"));
20 app = createApp({ dataDir: dir, url: "https://forge.test", port: 0, forgeRepo: "alice/forge-code" });
21 servers = await serve(app);
22 }, 30_000);
23
24 afterAll(async () => {
25 servers.stop();
26 app.close();
27 await rm(dir, { recursive: true, force: true });
28 });
29
30 const get = async (q: string) => (await fetch(`${servers.url}/templates${q}`)).text();
31
32 test("a word from a description matches, whatever its case", () => {
33 const t = TEMPLATES.find((x) => x.says.split(" ").some((w) => w.length > 4))!;
34 const word = t.says.split(" ").find((w) => /^[a-z]{5,}$/i.test(w))!;
35 const rows = TEMPLATES.map((x) => ({ id: x.id, title: x.title, says: x.says }));
36 const hit = filterTemplates(rows, word.toUpperCase());
37 expect(hit.map((r) => r.id)).toContain(t.id);
38 });
39
40 test("the page matches a name and echoes it", async () => {
41 const text = await get("?q=STARTER");
42 expect(text).toContain('data-template="starter"');
43 expect(text).toContain('value="STARTER"');
44 });
45
46 test("no match says so and offers the full list", async () => {
47 const text = await get("?q=zzzz");
48 expect(text).toContain("No template matches that name.");
49 expect(text).toContain('<a href="/templates">Show all templates</a>');
50 });
51
52 test("a hostile q is escaped in the echoed box", async () => {
53 const text = await get("?q=%22%3E%3Cscript%3Ealert(1)%3C/script%3E");
54 expect(text).not.toContain("<script>alert(1)");
55 expect(text).toContain("&lt;script&gt;");
56 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs