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

/explore's first view is ranked rows with one filter line, under 10 KB #13026

Merged opened this

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

Merged

torque/forge:torque/12999-explore-s-first-view-is-ranked-rows-with → main 5 commits fork 3 threads · 3 unresolved

  • Merged. torque/12999-explore-s-first-view-is-ranked-rows-with was merged into main as 383295e.

Review

Sign in to review this change.
8 files changed +197 −77
docs/design/areas/explore.md +3
@@ -5,3 +5,6 @@
55 The count line above the list (`[data-hits]`, a muted span at the end of the sort bar) is server-rendered with a 24px line height, so the list never moves; "Clear filters" appears in it only while a filter (not the sort) is active.
66
77 The how-to is in docs/features/explore.md.
8
9 ## First view
10 A row is its name, what it does, and one signal (the phrase `whyOf` gives), with "Make it yours" as its one tap. The filter line (`[data-filter-line]`) is the search box and the kind tabs; sort, time and archived sit in one `<details data-more-filters>`, closed on the bare view and open when any of them is set. The explore part of the page is compacted by `web/compact.ts` (indentation between and inside tags only; text and attribute values are untouched) and is under 10 KB raw; "Sort and time" (`.sort-toggle`) is a 44px target (`test/explore-first-view.test.ts`).
docs/features/explore.md +5
@@ -75,3 +75,8 @@ The terminal's palette has `Explore feed`, which opens or shows the feed's addre
7575 Under the filters, `/explore` says how much a filter leaves: `66 results`, `2 apps`, `1 app`, `No apps match`, in the words of `exploreCount` in `src/actions/explore.ts` (the count is the whole filtered list, not the page). While a filter narrows the list (kind, words, archived, updated or owner; the sort only orders) the line ends with `Clear filters`, a link to bare `/explore`. When nothing matches it also offers `Drop <term>` for each filter, one tap to remove just that one. With no filter and nothing public the line is silent; the empty state speaks.
7676
7777 In the terminal the same sentence sits in the `Read as:` line under the search box (`Read as: kind:app · 2 apps · Esc clears`); Esc clears the line.
78
79 ## What a row shows
80 A row shows the app's name, what it does in plain words, and the one signal that explains its place (the other numbers are left off the page; the API and the MCP still carry them all). The filter line is the search box and the kind tabs; "Sort and time" opens the sorts, the time windows and "Show archived", and stays open while one of them is set. The ranking order is unchanged.
81
82 The terminal's explore screen deliberately keeps the stacked numbers (forks, ships, likes, use) that the page leaves off: a terminal row has the width for them and no second tap to reach them. The ranking is the same on both.
src/web/compact.ts added +28
@@ -0,0 +1,28 @@
1 /**
2 * Markup without its indentation. Templates (and the shared `btn`, `seg`,
3 * `row`) are written for reading; this takes the whitespace that cannot be
4 * seen out of what is sent. Only the spaces between and inside tags and at the
5 * edges of text go: runs inside text and quoted attribute values (a search
6 * value `a b`) are left as they are, and a page with `<pre>`, `<textarea>`,
7 * `<script>` or `<style>` is returned untouched. Escaped output has no bare
8 * `<`, `>` or `"` in a value, so a tag is found by shape, not by guessing.
9 */
10 import { raw, type Html } from "./html.ts";
11
12 const TAG = /<(?:"[^"]*"|'[^']*'|[^<>"'])*>/g;
13 const IN_TAG = /("[^"]*"|'[^']*')|\s+/g;
14
15 export function compactText(markup: string): string {
16 if (/<(?:pre|textarea|script|style)[\s>]/i.test(markup)) return markup;
17 let out = "";
18 let last = 0;
19 const text = (t: string): string => t.replace(/^\s+|\s+$/g, (m) => (m === t ? (t === "" ? "" : " ") : " "));
20 for (const m of markup.matchAll(TAG)) {
21 out += text(markup.slice(last, m.index));
22 out += m[0].replace(IN_TAG, (_all, quoted: string | undefined) => quoted ?? " ").replace(/ (\/?>)$/, "$1");
23 last = m.index + m[0].length;
24 }
25 return out + text(markup.slice(last));
26 }
27
28 export const compact = (markup: Html): Html => raw(compactText(markup.toString()));
src/web/studio/explore.ts +53 −76
@@ -20,7 +20,6 @@ import {
2020 readExploreLine,
2121 type ExploreQuery,
2222 type ExploreRow,
23 type WhySignal,
2423 } from "../../actions/explore.ts";
2524 import { frontWeights, type FrontWeights } from "../../core/front.ts";
2625 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
@@ -28,6 +27,7 @@ import type { Ctx } from "../../http/context.ts";
2827 import { activeEdgeToken, edgeLoginUrl } from "../../http/edge.ts";
2928 import { offersSignup, pageHead } from "../chrome.ts";
3029 import { html, type Html } from "../html.ts";
30 import { compact } from "../compact.ts";
3131 import { page } from "../layout.ts";
3232 import { btn, card, empty, nameMark, row as rowOf, seg, tabs, time } from "../ui.ts";
3333
@@ -36,41 +36,15 @@ const href = (query: ExploreQuery): string => {
3636 return params === "" ? "/explore" : `/explore?${params}`;
3737 };
3838
39 /**
40 * A row's numbers as a person reads them; nothing that is zero. Hours awake
41 * are not among them: summed over every copy of an app, previews too, they
42 * read as a figure ("3085.9 h") that says nothing to a visitor. They still
43 * weigh in the ranking (`core/front.ts`).
44 */
45 function numbers(row: ExploreRow, said: WhySignal | undefined): { apps: string; rest: Html } {
46 const n = row.numbers;
47 // What the row's reason already says is not said again beside it.
48 const rest = [
49 n.forks > 0 && said !== "forks" ? `${n.forks} fork${n.forks === 1 ? "" : "s"}` : "",
50 n.likes > 0 && said !== "likes" ? `${n.likes} like${n.likes === 1 ? "" : "s"}` : "",
51 n.ships > 0 && said !== "ships" ? `${n.ships} shipped this month` : "",
52 ];
53 const shipped = row.shippedAt === null || said === "fresh" ? null : html`shipped ${time(row.shippedAt)}`;
54 const restText = rest.filter((p) => p !== "").map((p) => html`${p}`);
55 if (shipped !== null) restText.push(shipped);
56 return {
57 apps: row.kind === "person" ? `${n.apps} app${n.apps === 1 ? "" : "s"}` : "",
58 rest: restText.reduce((all, p, i) => (i === 0 ? p : html`${all} · ${p}`), html``),
59 };
60 }
61
6239 function rowHtml(row: ExploreRow, signedIn: boolean, query: ExploreQuery, now: number, weights: FrontWeights): Html {
6340 const why = whyOf(row, query.sort, now, weights);
64 const { apps, rest } = numbers(row, why?.signal);
41 // One row: what it does in plain words, then the one signal that explains its place.
42 const signal = why === undefined ? "" : why.signal === "fresh" && row.shippedAt !== null ? html`shipped ${time(row.shippedAt)}` : html`${why.text}`;
6543 // One tap from a person to their apps; with none, the count is plain text.
6644 const theirs = href({ kind: "app", sort: "score", text: "", archived: false, updated: "all", owner: row.name });
45 const apps = row.kind === "person" ? `${row.numbers.apps} app${row.numbers.apps === 1 ? "" : "s"}` : "";
6746 const count = apps === "" ? html`` : row.numbers.apps > 0 ? html`<a href="${theirs}">${apps}</a>` : html`${apps}`;
68 const parts = [
69 why === undefined ? html`` : why.signal === "fresh" && row.shippedAt !== null ? html`shipped ${time(row.shippedAt)}` : html`${why.text}`,
70 row.description === "" ? html`` : html`${row.description}`,
71 count,
72 rest,
73 ].filter((p) => p.toString() !== "");
47 const parts = [row.description === "" ? html`` : html`${row.description}`, signal === "" ? html`` : html`${signal}`, count].filter((p) => p.toString() !== "");
7448 const metaHtml = parts.reduce((all, p, i) => (i === 0 ? p : html`${all} · ${p}`), html``);
7549 return rowOf({
7650 title: html`<a href="${row.url}">${row.name}</a>${nameMark(row.mark)}`,
@@ -238,27 +212,20 @@ export async function explorePage(ctx: Ctx): Promise<Response> {
238212 const body = html`<div data-explore>${pageHead("Explore", {
239213 sub: "Apps and their makers, ranked by forks, ships, use and recency.",
240214 })}
241 <form method="get" action="/explore" class="bar mb">
242 <input
243 type="search"
244 class="input mono"
245 name="q"
246 value="${exploreLine(query)}"
247 placeholder="kind:app sort:forks garden"
248 aria-label="Narrow the list"
249 autocomplete="off"
250 spellcheck="false"
251 />
252 ${btn("Go", { size: "sm" })}
253 </form>
254 ${chipRow(query)}
255 ${returned ? html`<p class="muted mb" role="status">That page link is not one for this list, so this is the first page.</p>` : html``}
256 ${note === "" ? html`` : html`<p class="muted mb" role="status">${note}${
257 suggestion === undefined
258 ? html``
259 : html` Did you mean <a href="${href(readExploreLine(suggestion.line).query)}">${suggestion.fix}</a>?`
260 }</p>`}
261 <div class="mb">
215 <div class="bar mb" data-filter-line>
216 <form method="get" action="/explore" class="bar">
217 <input
218 type="search"
219 class="input mono"
220 name="q"
221 value="${exploreLine(query)}"
222 placeholder="kind:app sort:forks garden"
223 aria-label="Narrow the list"
224 autocomplete="off"
225 spellcheck="false"
226 />
227 ${btn("Go", { size: "sm" })}
228 </form>
262229 ${tabs(
263230 kinds.map((k) => ({
264231 label: k.label,
@@ -268,29 +235,39 @@ export async function explorePage(ctx: Ctx): Promise<Response> {
268235 "Kind",
269236 )}
270237 </div>
271 <div class="bar mb small">
272 ${seg(
273 sorts.map((s) => ({
274 label: s.label,
275 href: href({ ...query, sort: s.sort }),
276 current: query.sort === s.sort,
277 })),
278 )}
279 ${seg(
280 windows.map((w) => ({
281 label: w.label,
282 href: href({ ...query, updated: w.updated }),
283 current: query.updated === w.updated,
284 })),
285 )}
286 <a
287 class="muted home-doors"
288 href="${href({ ...query, archived: !query.archived })}"
289 aria-pressed="${query.archived ? "true" : "false"}"
290 >Show archived</a
291 >
292 ${countLine(query, page0?.total ?? 0, ctx.auth.user?.isAdmin === true)}
293 </div>
238 ${chipRow(query)}
239 ${returned ? html`<p class="muted mb" role="status">That page link is not one for this list, so this is the first page.</p>` : html``}
240 ${note === "" ? html`` : html`<p class="muted mb" role="status">${note}${
241 suggestion === undefined
242 ? html``
243 : html` Did you mean <a href="${href(readExploreLine(suggestion.line).query)}">${suggestion.fix}</a>?`
244 }</p>`}
outdated

Principle 3/phone: summary needs a thumb-sized target (change 4).

245 <details class="mb small" data-more-filters${query.sort !== "score" || query.updated !== "all" || query.archived ? " open" : ""}>
246 <summary class="muted sort-toggle">Sort and time</summary>
247 <div class="bar">
248 ${seg(
249 sorts.map((s) => ({
250 label: s.label,
251 href: href({ ...query, sort: s.sort }),
252 current: query.sort === s.sort,
253 })),
254 )}
255 ${seg(
256 windows.map((w) => ({
257 label: w.label,
258 href: href({ ...query, updated: w.updated }),
259 current: query.updated === w.updated,
260 })),
261 )}
262 <a
263 class="muted home-doors"
264 href="${href({ ...query, archived: !query.archived })}"
265 aria-pressed="${query.archived ? "true" : "false"}"
266 >Show archived</a
267 >
268 </div>
269 </details>
270 <p class="mb small">${countLine(query, page0?.total ?? 0, ctx.auth.user?.isAdmin === true)}</p>
294271 ${rows.length === 0
295272 ? emptyState(ctx, query)
296273 : card(html`<ul class="list">${rows.map((r) => rowHtml(r, ctx.auth.user !== undefined, query, now, weights))}</ul>`, {
@@ -299,7 +276,7 @@ export async function explorePage(ctx: Ctx): Promise<Response> {
299276 })}${more === null
300277 ? html``
301278 : html`<div class="explore-more">${btn("More results", { href: `${here}${here.includes("?") ? "&" : "?"}cursor=${encodeURIComponent(more)}`, variant: "outline", extra: "explore-more-link" })}</div>`}</div>`;
302 const drawn = page({ ctx, title: "Explore", body, feed: { href: "/explore.atom", title: "Explore" } });
279 const drawn = page({ ctx, title: "Explore", body: compact(body), feed: { href: "/explore.atom", title: "Explore" } });
303280 // An unknown filter is ignored with a plain note on the page (200); the API and the MCP stay strict.
304281 notePhase(ctx.request, "render", performance.now() - rendering);
305282 return drawn;
src/web/style/content.ts +4
@@ -296,6 +296,10 @@ form.inline { display: inline; margin-left: auto; }
296296 .door-start { width: 100%; max-width: 28rem; }
297297 .door-start .btn { width: 100%; }
298298 [data-hits] { line-height: 24px; }
299 /* "Sort and time": a thumb-sized target; the line height is fixed so opening it moves only
300 what is below. */
301 .sort-toggle { display: flex; align-items: center; min-height: 44px; padding: 0 4px; cursor: pointer; }
302 .sort-toggle:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; border-radius: var(--radius-sm); }
299303 .explore-more { margin-top: 12px; }
300304 .explore-more .btn { width: 100%; min-height: 44px; }
301305 .door-says { min-height: 1lh; margin: 6px 0 0; }
test/compact.test.ts added +13
@@ -0,0 +1,13 @@
1 import { expect, test } from "bun:test";
2 import { compactText } from "../src/web/compact.ts";
3
4 test("indentation between and inside tags goes; quoted values and text runs stay", () => {
5 const out = compactText('<div>\n <input\n value="a b"\n />\n <p>x y</p>\n</div>');
6 expect(out).toBe('<div> <input value="a b"/> <p>x y</p> </div>');
7 });
8
9 test("a page with preformatted text is left as it is", () => {
10 const src = "<div>\n <pre>a\n b</pre>\n</div>";
11 expect(compactText(src)).toBe(src);
12 expect(compactText("<textarea>\n x</textarea>")).toBe("<textarea>\n x</textarea>");
13 });
test/explore-first-view.test.ts added +90
@@ -0,0 +1,90 @@
1 /**
2 * /explore's first view: ranked rows — name, what it does, one
3 * signal — under one filter line, in under 10 KB; ranking order unchanged.
4 */
5 import { afterAll, beforeAll, describe, 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 { createRepo, forkRepo } from "../src/actions/repos.ts";
11 import { explorePage } from "../src/actions/explore.ts";
12 import { createApp as insertApp } from "../src/core/apps.ts";
13 import { createUser } from "../src/core/users.ts";
14 import { serve, type Servers } from "../src/http/server.ts";
15 import { proveAll } from "./helpers/verified.ts";
16 import { quietLogs } from "./helpers/globals.ts";
17
18 quietLogs();
19
20 let dir: string;
21 let app: App;
22 let servers: Servers;
23 let html: string;
24 let ranked: string[];
25
26 beforeAll(async () => {
27 dir = await mkdtemp(join(tmpdir(), "forge-explore-first-"));
28 app = createApp({ dataDir: dir, port: 0 });
29 servers = await serve(app);
30 const made = await createUser(app.db, { origin: "seed", username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
31 if (!made.ok) throw new Error(made.error);
32 proveAll(app);
33 for (let n = 0; n < 12; n++) {
34 const r = await createRepo(app, made.value, { name: `app-${n}`, visibility: "public", description: `Does thing number ${n} in plain words` });
35 if (!r.ok) throw new Error(String(r.error));
36 const rec = insertApp(app.db, { repoId: r.value.id, slug: `alice-${n}`, access: "public" });
37 if (!rec.ok) throw new Error(rec.error);
38 }
39 const parent = (await import("../src/core/repos.ts")).getRepo(app.db, "alice", "app-0");
40 if (parent === undefined) throw new Error("no app-0");
41 const forked = await forkRepo(app, made.value, parent, "app-0-copy");
42 if (!forked.ok) throw new Error(String(forked.error));
43 html = await (await fetch(`${servers.url}/explore?kind=app`)).text();
44 const page = await explorePage(app, undefined, { kind: "app", sort: "score", text: "", archived: false, updated: "all" }, null);
45 ranked = (page?.items ?? []).map((r) => r.name);
46 }, 30_000);
47 afterAll(async () => {
48 servers.stop();
49 app.close();
50 await rm(dir, { recursive: true, force: true });
51 });
outdated

Gzip-only size check does not meet 'under 10 KB' of raw page (change 1); per-row slice can pass vacuously (change 5).

52
53 describe("/explore first view", () => {
54 test("the explore part of the page is under 10 KB raw, and a row costs under 500 bytes of markup", () => {
55 const start = html.indexOf("<div data-explore>");
56 const part = html.slice(start, html.indexOf("</main>", start));
57 expect(start).toBeGreaterThan(0);
58 // Page-specific bytes, uncompressed: the shell around them is shared.
59 expect(new TextEncoder().encode(part).length).toBeLessThan(10_000);
60 // The whole page too goes over the wire in under 10 KB when compressed (http/compress.ts).
61 expect(Bun.gzipSync(new TextEncoder().encode(html)).length).toBeLessThan(10_000);
62 const from = html.indexOf('class="list"');
63 const list = html.slice(from, html.indexOf("</ul>", from));
64 expect((list.match(/class="row"/g) ?? []).length).toBe(12);
65 expect(list.length / 12).toBeLessThan(500);
66 });
67
68 test("the rows come in the ranking's order", () => {
69 expect(ranked.length).toBe(12);
70 const shown = [...html.matchAll(/class="row-title"[^>]*>\s*<a href="[^"]*">([^<]+)<\/a>/g)].map((m) => m[1]);
71 expect(shown).toEqual(ranked);
72 });
73
74 test("a row is its name, what it does, and one signal; the filters are one line", () => {
75 expect(html).toContain("Does thing number 0 in plain words");
76 // A row's meta is `description · signal`, one signal and no more.
77 const meta = [...html.matchAll(/class="row-meta">([^<]*)</g)].map((m) => m[1]);
78 expect(meta).toContain("Does thing number 0 in plain words · 1 fork");
79 expect(meta).toContain("Does thing number 1 in plain words");
80 for (const m of meta) expect(m!.split(" · ").length).toBeLessThanOrEqual(2);
81 // Sort, time and archived sit behind one disclosure, closed on the bare view.
82 expect(html).toMatch(/<details class="mb small" data-more-filters>/);
83 expect(html.match(/data-filter-line/g)!.length).toBe(1);
84 });
85
86 test("a chosen sort opens the disclosure", async () => {
87 const sorted = await (await fetch(`${servers.url}/explore?sort=forks`)).text();
88 expect(sorted).toMatch(/data-more-filters open>/);
89 });
90 });
test/explore.test.ts +1 −1
@@ -286,7 +286,7 @@ describe("explore", () => {
286286 expect(page).toContain('class="row"');
287287 expect(page).toContain('class="row-title"');
288288 expect(page).toContain(`<nav class="tabs" aria-label="Kind">`);
289 expect(page).toContain(`<div class="bar mb small">`);
289 expect(page).toContain("data-filter-line");
290290 expect(page).not.toMatch(/class="[^"]*\bfilters\b/);
291291 expect(page).not.toContain("explore-");
292292 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs