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

One design language: every page, card and word at the home page's standard #9463

Parked opened this in answer to
Closed without merging

torque/forge:torque/9433-one-design-language-every-page-card-and → main 3 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
21 files changed +302 −43
docs/DESIGN.md +22
@@ -7,6 +7,28 @@ has a name for, that is the bug.
77
88 Read this once. It is short on purpose.
99
10 ## The design language
11
12 Every page speaks like the home page (`src/web/studio/home.ts`). Words follow
13 `docs/WRITING.md`; the message is "Software for what you're building. Yours to keep."
14
15 1. **One confident sentence per page.** The title says what the page is for. Nothing above it says it again.
16 2. **The real product is the visual.** Show the actual feed, app or run, not a picture of one.
17 3. **One background, one text color, at most one accent.** Status is a word, not a color wash.
18 4. **Rows over boxes.** A list is rows with space between. A card needs a reason; a card inside a card has none.
19 5. **Few borders.** A hairline separates sections; it does not wrap every item.
20 6. **Generous rhythm.** Space does the grouping that rules and labels did.
21 7. **Plain words.** A grandma, a gamer, a developer and an artist each get it. No jargon where a common word works, no "Status: Open", no label that repeats its value.
22 8. **A share card is the page's first line.** The same type and restraint: title, a few muted lines, one stat. No kind label, no edge strip, nothing cut mid-sentence.
23 9. **Every page is a link and a document.** Title, description, canonical URL, `og:` tags and image.
24
25 Worked examples: the home page (`src/web/studio/home.ts`: one sentence, the feed
26 as the visual, rows) and Security settings (`src/web/pages/security.ts`: one
27 sentence of what is protected, then one row per control).
28
29 Enforced: `bun scripts/design-lint.ts` (colors, sizes, classes, quiet-page rules), `test/og-restraint.test.ts`
30 (cards), `test/og-tags.test.ts` (page heads). The rest is review.
31
1032 Each section is its own file under `docs/design/sections/`, so a change to one
1133 never conflicts with a change to another. This page is the spine: it orders
1234 them, and the design check (`bun scripts/design-lint.ts`) reads them in this
src/core/reserved.ts +1
@@ -97,6 +97,7 @@ export const SYSTEM_NAMES: readonly string[] = [
9797 "resilience",
9898 "origins",
9999 "robots.txt",
100 "humans.txt",
100101 "favicon.ico",
101102 "apple-touch-icon.png",
102103 "apple-touch-icon-precomposed.png",
src/crew/brief.ts +2 −2
@@ -174,7 +174,7 @@ export function systemPrompt(input: BriefInput): string {
174174 "- Keep state under `FORGE_APP_DATA`. Never write elsewhere at runtime.",
175175 "- The app's terminal (`tty` in forge.json) is reached with the exact command in `FORGE_APP_SSH` (for example `ssh -p 2222 notes@localhost`: the app is the login name, the forge is the host). When a page or the terminal tells people how to connect, print that variable verbatim and never invent a form like `[email protected]`; when it is unset, say the terminal is off.",
176176 "- Run the tests (`bun test`, or whatever `forge.json` names) before you push: the deploy runs them, and a failing test fails the preview. When a test fails, fix the code; change the test only when the test was wrong, and say which in the pull.",
177 "- Touching src/web/: run `bun scripts/design-lint.ts` before you push; it names the file:line and what to use instead. A new component class is named in your own docs/design/areas/<area>.md, never in docs/DESIGN.md, which every pull would otherwise edit.",
177 "- Touching src/web/: follow the design language that opens docs/DESIGN.md, run `bun scripts/design-lint.ts` before you push; it names the file:line and what to use instead. A new component class goes in your own docs/design/areas/<area>.md, never docs/DESIGN.md.",
178178 "- The bar is the forge's own: small modules named for one concept, every input validated at the boundary and every output escaped, the security floor in " +
179179 (isForge(repo) ? "`src/http/respond.ts` (`securityFloor`)" : "`src/server.ts`") +
180180 " kept on every response, no dependency without a reason in the pull, and a page that answers in milliseconds. `AGENTS.md` in the repository says how this app is shaped; keep its shape.",
@@ -472,7 +472,7 @@ function taskBody(input: TaskInput): string {
472472 "- Clean: small modules named after one concept, no dead code, no commented-out code, no TODOs left as work, no new dependency without a reason in the pull.",
473473 ...(input.design === true
474474 ? [
475 "- The design system: this change touches src/web/, so you read it as the design team. Read docs/DESIGN.md first, then hold the change to it strictly — tokens and the named components rather than hand-rolled markup, one accent per page, anything that navigates an <a> and anything that mutates a <button> in a post form, everything working with JavaScript off. A page that departs from docs/DESIGN.md is a change request, whatever else it does well.",
475 "- The design system: this change touches src/web/, so you read it as the design team. Read docs/DESIGN.md first, then hold the change to its design language (one confident sentence, rows over boxes, few borders, one accent, plain words) and to the rest strictly — tokens and the named components rather than hand-rolled markup, one accent per page, anything that navigates an <a> and anything that mutates a <button> in a post form, everything working with JavaScript off. A page that departs from docs/DESIGN.md is a change request, whatever else it does well.",
476476 ]
477477 : []),
478478 "- True to the direction: it does what the issue asked and nothing the direction did not, and the preview shows it working.",
src/http/server.ts +2
@@ -157,6 +157,7 @@ import {
157157 iconPng,
158158 appleTouchIcon,
159159 favicon,
160 humansTxt,
160161 llmsTxt,
161162 releasesJson,
162163 robotsTxt,
@@ -683,6 +684,7 @@ export function buildRouter(): Router<Handler> {
683684 router.add("GET", "/agents", agentsPage);
684685 router.add("GET", "/.well-known/change-password", changePassword);
685686 router.add("GET", "/robots.txt", robotsTxt);
687 router.add("GET", "/humans.txt", humansTxt);
686688 // The conventional path an agent guesses, answered as /api/v1/openapi.json is.
687689 router.add(
688690 "GET",
src/web/describe.ts +29 −2
@@ -69,7 +69,32 @@ export function ownerLine(o: {
6969 return `${o.org ? "Organization" : "User"} @${o.name} · ${n} public ${noun}.`;
7070 }
7171
72 /** An app: its own description, and whether it is up, in `envPhrase`'s word. */
72 /**
73 * Words that say nothing to a reader: a placeholder someone typed once, or
74 * a bare label. A description that is only these gets the plain fallback.
75 */
76 const EMPTY_WORDS =
77 /^(?:wip|todo|tbd|test|testing|tmp|temp|untitled|n\/a|none|description|my (?:app|repo|project)|new (?:app|repo|project))\W*$/i;
78
79 /** True when `text` is empty, a placeholder, or too short to tell anyone anything. */
80 export function isEmptyDescription(text: string): boolean {
81 const t = firstLine(text);
82 return t.length < 8 || EMPTY_WORDS.test(t);
83 }
84
85 /**
86 * What a repository or app says about itself, or a plain sentence when its
87 * description is empty or a placeholder. `kind` is "repository" or "app".
88 */
89 export function plainDescription(text: string, name: string, kind: "repository" | "app"): string {
90 if (!isEmptyDescription(text)) return firstLine(text);
91 return `${name}, ${kind === "app" ? "an app" : "a repository"} on forge.`;
92 }
93
94 /**
95 * An app: its own description, in plain words. A running app says nothing
96 * more; any other state is named after it. Never ends in " · live."
97 */
7398 export function appLine(o: {
7499 private: boolean;
75100 name: string;
@@ -77,5 +102,7 @@ export function appLine(o: {
77102 state: string;
78103 }): string {
79104 if (o.private) return PRIVATE_LINE;
80 return `${firstLine(o.description) || o.name} · ${o.state}.`;
105 const base = plainDescription(o.description, o.name, "app").replace(/[.!?\s]+$/, "");
106 const state = o.state.trim().toLowerCase();
107 return state === "live" || state === "up" || state === "" ? `${base}.` : `${base}. Status: ${state}.`;
81108 }
src/web/layout.ts +11
@@ -61,6 +61,7 @@ import { noRoom } from "../spawn/door.ts";
6161 import { quotaFull } from "../spawn/quota.ts";
6262 import { icon, inlineIcons, pointAtSprite, themeGlyph } from "./icons.ts";
6363 import { btn, copyField, hintAttr, kbd, menu, type MenuItem } from "./ui.ts";
64 import { jsonLd, siteData } from "./structured.ts";
6465 import { SITE_LINE } from "./site_line.ts";
6566
6667 /** One row of the command palette: title, href, category. */
@@ -104,6 +105,8 @@ export interface PageOptions {
104105 * signed-out unfurler; absent, the forge's own card (`/og/site.png`) stands in.
105106 */
106107 ogImage?: string | undefined;
108 /** schema.org data for this page (JSON-LD); the home page gets the site's own. */
109 structured?: Record<string, unknown> | undefined;
107110 /** This page's feed, advertised in the head so a reader can find it. */
108111 feed?: { href: string; title: string };
109112 /** This page's JSON twin, advertised in the head for agents. */
@@ -769,6 +772,14 @@ export function page(options: PageOptions, status = 200): Response {
769772 <meta property="og:image:width" content="1200" />
770773 <meta property="og:image:height" content="630" />
771774 <meta name="twitter:card" content="summary_large_image" />
775 ${(() => {
776 const data =
777 options.structured ??
778 (status === 200 && ctx.url.pathname === "/" ? siteData(ctx.url.origin) : undefined);
779 return data === undefined
780 ? null
781 : raw(`<script type="application/ld+json">${jsonLd(data)}</script>`);
782 })()}
772783 <link rel="manifest" href="/manifest.webmanifest" />
773784 <link
774785 rel="search"
src/web/og/card.ts +13 −27
@@ -72,17 +72,8 @@ const TITLE_LINES = 2;
7272 /** Widest average glyph advance, in em, for the bold sans: wider than the regular face. */
7373 const EM_BOLD = 0.68;
7474 const EM_MONO = 0.62;
75
76 const KIND_COLOR: Record<CardKind, string> = {
77 repo: T.accent,
78 issue: T.success,
79 pull: T.merged,
80 run: T.primary,
81 app: T.attn,
82 map: T.accent,
83 audit: T.success,
84 page: T.primary,
85 };
75 /** Average glyph advance, in em, for the regular sans (the same bound `fit` uses). */
76 const EM_REG = 0.6;
8677
8778 /** Break a title into at most `n` lines of `max` chars; the last is clamped. */
8879 function wrap(text: string, size: number, n: number, em: number, width = INNER): string[] {
@@ -174,7 +165,7 @@ function drawImages(images: unknown): string {
174165
175166 export function renderCard(input: CardInput): string {
176167 const kind: CardKind = CARD_KINDS.includes(input?.kind) ? input.kind : "page";
177 const color = KIND_COLOR[kind];
168 void kind;
178169 const out: string[] = [];
179170
180171 out.push(
@@ -185,17 +176,6 @@ export function renderCard(input: CardInput): string {
185176 text(PAD + 60, PAD + 26, 30, T.fg, "forge", ` font-weight="700"`),
186177 );
187178
188 // A card about one thing is marked with its kind: a strip down the left
189 // edge and a badge in the header. The forge's own card is plain, as the
190 // home page is.
191 const plain = kind === "page";
192 if (!plain) {
193 out.push(
194 `<rect x="0" y="0" width="12" height="${CARD_HEIGHT}" fill="${color}"/>`,
195 text(CARD_WIDTH - PAD, PAD + 24, 24, color, kind.toUpperCase(), ` font-weight="700" text-anchor="end" letter-spacing="2"`),
196 );
197 }
198
199179 const figure = drawFigure(input?.figure) || drawImages(input?.images);
200180 const column = figure ? COLUMN : INNER;
201181 if (figure) out.push(figure);
@@ -204,7 +184,7 @@ export function renderCard(input: CardInput): string {
204184 const tsize = figure ? 56 : 64;
205185 const title = wrap(input?.title ?? "", tsize, TITLE_LINES, EM_BOLD, column);
206186 const tagline = clean(input?.tagline);
207 const tight = plain ? ` letter-spacing="-1.5"` : "";
187 const tight = ` letter-spacing="-1.5"`;
208188 let y = tagline ? 230 : 270;
209189 for (const row of title) {
210190 out.push(text(PAD, y, tsize, T.fg, row, ` font-weight="700"${tight}`));
@@ -222,9 +202,15 @@ export function renderCard(input: CardInput): string {
222202 .slice(0, MAX_LINES);
223203 const lsize = figure ? 26 : 30;
224204 y = Math.max(y + 10, 360);
205 // A line that does not fit wraps on word boundaries, never cut mid-word.
206 let rows = MAX_LINES;
225207 for (const l of lines) {
226 out.push(text(PAD, y, lsize, T["muted-fg"], fit(l, lsize, column)));
227 y += lsize + 14;
208 if (rows <= 0) break;
209 for (const row of wrap(l, lsize, rows, EM_REG, column)) {
210 out.push(text(PAD, y, lsize, T["muted-fg"], row));
211 y += lsize + 14;
212 rows--;
213 }
228214 }
229215
230216 // Footer rule and stat.
@@ -234,7 +220,7 @@ export function renderCard(input: CardInput): string {
234220 const stat = clean(input?.stat);
235221 if (stat) {
236222 out.push(
237 text(PAD, CARD_HEIGHT - 52, 32, plain ? T["muted-fg"] : color, fit(stat, 32, INNER, EM_MONO), ` font-family="${MONO}" font-weight="600"`),
223 text(PAD, CARD_HEIGHT - 52, 32, T["muted-fg"], fit(stat, 32, INNER, EM_MONO), ` font-family="${MONO}" font-weight="600"`),
238224 );
239225 }
240226 out.push(`</svg>`);
src/web/pages/repo.ts +19 −2
@@ -72,6 +72,8 @@ import { countLines, highlightPrefix } from "../code.ts";
7272 import { latestWave } from "../../story/waves.ts";
7373 import { notePhase, takeSessionTime, timePhase, timePhaseAsync } from "../../core/route_timing.ts";
7474 import { liveClientJs, liveMount } from "../live.ts";
75 import { plainDescription } from "../describe.ts";
76 import { softwareData } from "../structured.ts";
7577 import { appStrip } from "./apps.ts";
7678 import { studioApp } from "../studio/app.ts";
7779 import { getAppByRepo } from "../../core/apps.ts";
@@ -136,6 +138,19 @@ const forksFor = (ctx: Ctx, repo: Repo): Repo[] =>
136138 * GET /:owner/:name/forks — every fork of this repository the viewer may
137139 * see, newest first. The count on the repository page is the way in.
138140 */
141 /** The repository as software for a search engine; nothing for one that is not public. */
142 function repoData(ctx: Ctx, repo: Repo): Record<string, unknown> | undefined {
143 if (repo.visibility !== "public") return undefined;
144 return softwareData({
145 origin: ctx.url.origin,
146 path: ctx.url.pathname,
147 name: repo.name,
148 description: plainDescription(repo.description, repo.name, "repository"),
149 owner: repo.ownerName,
150 kind: "repository",
151 });
152 }
153
139154 export async function forksPage(ctx: Ctx): Promise<Response> {
140155 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
141156 let t = performance.now();
@@ -1330,7 +1345,8 @@ async function codeHome(ctx: Ctx, repo: Repo): Promise<Response> {
13301345 const emptyResponse = page({
13311346 ctx,
13321347 title: repo.name,
1333 description: repo.description,
1348 description: plainDescription(repo.description, repo.name, "repository"),
1349 structured: repoData(ctx, repo),
13341350 ogImage: `/og/repo/${repo.ownerName}~${repo.name}.png`,
13351351 feed: {
13361352 href: `${repoBase(repo)}/activity.atom`,
@@ -1404,7 +1420,8 @@ async function codeHome(ctx: Ctx, repo: Repo): Promise<Response> {
14041420 const response = page({
14051421 ctx,
14061422 title: repo.name,
1407 description: repo.description,
1423 description: plainDescription(repo.description, repo.name, "repository"),
1424 structured: repoData(ctx, repo),
14081425 ogImage: `/og/repo/${repo.ownerName}~${repo.name}.png`,
14091426 feed: {
14101427 href: `${repoBase(repo)}/activity.atom`,
src/web/standards.ts +15
@@ -8,6 +8,7 @@
88 * only fields we keep true)
99 * /.well-known/change-password where a password manager sends someone
1010 * /robots.txt what a crawler may index, and the sitemap
11 * /humans.txt who runs it and what it is made with
1112 * /sitemap.xml every public repository
1213 * /releases.json the releases this forge has shipped, newest
1314 * first, for a child forge to read
@@ -180,6 +181,20 @@ export function robotsTxt(ctx: Ctx): Response {
180181 );
181182 }
182183
184 /** GET /humans.txt — who runs this forge and what it is made with (humanstxt.org). */
185 export function humansTxt(ctx: Ctx): Response {
186 return text(
187 [
188 "/* SITE */",
189 `Site: ${ctx.url.origin}/`,
190 `About: ${SITE_LINE}`,
191 "Software: forge, one Bun process and one SQLite file",
192 `Security: ${ctx.url.origin}/.well-known/security.txt`,
193 "",
194 ].join("\n"),
195 );
196 }
197
183198 function xml(s: string): string {
184199 return s.replace(/[<>&'"]/g, (c) =>
185200 c === "<"
src/web/structured.ts added +55
@@ -0,0 +1,55 @@
1 /**
2 * Structured data (schema.org, as JSON-LD) for the pages that are a thing
3 * search engines and agents can name: the site itself, and an app or a
4 * repository as software. Plain data in, a string out. Only what an
5 * anonymous reader may already see goes in: callers pass nothing for a
6 * private repository.
7 */
8
9 import { SITE_LINE } from "./site_line.ts";
10
11 /** The site: a WebSite that can be searched, published by the forge as an Organization. */
12 export function siteData(origin: string): Record<string, unknown> {
13 return {
14 "@context": "https://schema.org",
15 "@graph": [
16 {
17 "@type": "WebSite",
18 name: "forge",
19 url: `${origin}/`,
20 description: SITE_LINE,
21 potentialAction: {
22 "@type": "SearchAction",
23 target: `${origin}/search?q={search_term_string}`,
24 "query-input": "required name=search_term_string",
25 },
26 },
27 { "@type": "Organization", name: "forge", url: `${origin}/`, logo: `${origin}/icons/forge-180.png` },
28 ],
29 };
30 }
31
32 /** A public app or repository as software. */
33 export function softwareData(o: {
34 origin: string;
35 path: string;
36 name: string;
37 description: string;
38 owner: string;
39 kind: "app" | "repository";
40 }): Record<string, unknown> {
41 return {
42 "@context": "https://schema.org",
43 "@type": o.kind === "app" ? "SoftwareApplication" : "SoftwareSourceCode",
44 name: o.name,
45 description: o.description,
46 url: `${o.origin}${o.path}`,
47 author: { "@type": "Person", name: o.owner, url: `${o.origin}/${o.owner}` },
48 ...(o.kind === "app" ? { applicationCategory: "WebApplication", operatingSystem: "Any" } : {}),
49 };
50 }
51
52 /** The `<script type="application/ld+json">` body: `<` is escaped so no value can close the tag. */
53 export function jsonLd(data: Record<string, unknown>): string {
54 return JSON.stringify(data).replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
55 }
src/web/studio/app.ts +13 −1
@@ -34,7 +34,8 @@ import type { Ctx } from "../../http/context.ts";
3434 import { crumbsFor, repoBase, repoHeader, repoPalette } from "../chrome.ts";
3535 import { appTailJs, liveRegionsJs } from "../client.ts";
3636 import { html, when, type Html } from "../html.ts";
37 import { appLine } from "../describe.ts";
37 import { appLine, plainDescription } from "../describe.ts";
38 import { softwareData } from "../structured.ts";
3839 import { page } from "../layout.ts";
3940 import { liveClientJs, liveMount } from "../live.ts";
4041 import {
@@ -540,6 +541,17 @@ export async function studioApp(
540541 const response = page({
541542 ctx,
542543 title: `${repo.name}`,
544 structured:
545 repo.visibility === "public"
546 ? softwareData({
547 origin: ctx.url.origin,
548 path: ctx.url.pathname,
549 name: repo.name,
550 description: plainDescription(repo.description, repo.name, "app"),
551 owner: repo.ownerName,
552 kind: "app",
553 })
554 : undefined,
543555 description: appLine({
544556 private: repo.visibility === "private",
545557 name: repo.name,
test/design-audit.test.ts +1 −1
@@ -15,7 +15,7 @@ const doc = readFileSync("docs/design/audit.md", "utf8");
1515
1616 /** Routes that answer a file, a fragment, a redirect hop or a callback. */
1717 const NOT_PAGES =
18 /^\/(assets\/|\.well-known\/|icons\/|og\/|live\/|__forge\/|go\/|new\/issue$|events$|system\/stream$|talk\/stream$|settings\/teams\/stream$|sw\.js$|robots\.txt$|favicon\.ico$|apple-touch-icon(-precomposed)?\.png$|sitemap\.xml$|manifest\.webmanifest$|opensearch\.xml$|llms\.txt$|openapi\.json$|releases\.json$|changelog\.atom$|audit\.csv$|fleet\/graph\/live$|fleet\/graph\.csv$|settings\/origins\/callback$|home\/archived\/|settings\/backups\/live$|api\/v1\/)/;
18 /^\/(assets\/|\.well-known\/|icons\/|og\/|live\/|__forge\/|go\/|new\/issue$|events$|system\/stream$|talk\/stream$|settings\/teams\/stream$|sw\.js$|robots\.txt$|humans\.txt$|favicon\.ico$|apple-touch-icon(-precomposed)?\.png$|sitemap\.xml$|manifest\.webmanifest$|opensearch\.xml$|llms\.txt$|openapi\.json$|releases\.json$|changelog\.atom$|audit\.csv$|fleet\/graph\/live$|fleet\/graph\.csv$|settings\/origins\/callback$|home\/archived\/|settings\/backups\/live$|api\/v1\/)/;
1919
2020 const getRoutes = [
2121 ...server.matchAll(/router\.add\(\s*"GET",\s*"([^"]+)"/g),
test/design-language.test.ts added +22
@@ -0,0 +1,22 @@
1 import { describe, expect, test } from "bun:test";
2 import { readFileSync } from "node:fs";
3
4 const design = readFileSync("docs/DESIGN.md", "utf8");
5
6 describe("the design language", () => {
7 test("docs/DESIGN.md opens with the principles in under 30 lines, with both worked examples", () => {
8 const start = design.indexOf("## The design language");
9 expect(start).toBeGreaterThan(0);
10 const end = design.indexOf("\n---\n", start);
11 const lines = design.slice(start, end).trimEnd().split("\n");
12 expect(lines.length).toBeLessThan(30);
13 expect(lines.filter((l) => /^\d+\. /.test(l))).toHaveLength(9);
14 expect(design).toContain("src/web/studio/home.ts");
15 expect(design).toContain("src/web/pages/security.ts");
16 });
17
18 test("the crew's brief and the design review point at it", () => {
19 const brief = readFileSync("src/crew/brief.ts", "utf8");
20 expect(brief.match(/design language/g)?.length).toBeGreaterThanOrEqual(2);
21 });
22 });
test/forge-looks.test.ts +1
@@ -27,6 +27,7 @@ const NOT_A_PAGE: Record<string, string> = {
2727 "/llms.txt": "plain markdown for machines, not a page to picture",
2828 "/agents": "/llms.txt drawn as a page for an assistant; no picture: the cap of 24 looks is spent, and test/agents-page.test.ts covers it",
2929 "/robots.txt": "plain text for crawlers",
30 "/humans.txt": "plain text credits, for people who read it",
3031 "/openapi.json": "a redirect to the contract document",
3132 "/favicon.ico": "the tab icon, an image",
3233 "/releases.json": "JSON feed of /releases",
test/og-designs.test.ts +2 −2
@@ -106,7 +106,7 @@ describe("the map's thumbnail", () => {
106106 const figure = svg.slice(svg.indexOf("<g>"), svg.indexOf("</g>"));
107107 expect(figure.match(/<rect /g)?.length).toBe(4);
108108 expect(figure.match(new RegExp(`<path [^>]*stroke="${T.accent}"`, "g"))?.length).toBe(2);
109 expect(svg).toContain(">MAP<");
109 expect(svg).not.toContain(">MAP<");
110110 });
111111
112112 test("with nothing linked, the loose issues are drawn, four rows at most", () => {
@@ -237,7 +237,7 @@ describe("the audit's findings", () => {
237237 const svg = renderCard(card);
238238 wellFormed(svg);
239239 expect(svg).toContain(">50%<");
240 expect(svg).toContain(">AUDIT<");
240 expect(svg).not.toContain(">AUDIT<");
241241 });
242242
243243 test("every app holding says so; no apps draws no ring", () => {
test/og-restraint.test.ts added +41
@@ -0,0 +1,41 @@
1 import { describe, expect, test } from "bun:test";
2 import { decodePng } from "../src/design/image/png.ts";
3 import { CARD_KINDS, renderCard, type CardInput } from "../src/web/og/card.ts";
4 import { rasterizer } from "../src/web/og/raster.ts";
5
6 /** The home page's restraint: one background, the same type on every card. */
7 const LONG =
8 "A very long description of what this thing does for the people who use it every single day without fail";
9
10 function input(kind: (typeof CARD_KINDS)[number]): CardInput {
11 return { kind, title: `A ${kind} titled for the test`, lines: [LONG, "alice/shown", "ready"], stat: "#1 · open" };
12 }
13
14 describe("every card is as plain as the home page", () => {
15 for (const kind of CARD_KINDS) {
16 test(`${kind}: no kind label, no edge strip, and its lines are whole`, () => {
17 const svg = renderCard(input(kind));
18 expect(svg).not.toContain(`>${kind.toUpperCase()}<`);
19 // The strip was a rect at x=0 the height of the card.
20 expect(svg).not.toMatch(/<rect x="0" y="0" width="\d+" height="630"/);
21 // A long line wraps on a word boundary: no row ends in a cut word.
22 const rows = [...svg.matchAll(/font-size="30" fill="#a1a1aa">([^<]*)</g)].map((m) => m[1]!);
23 expect(rows.length).toBeGreaterThan(1);
24 for (const row of rows) expect(LONG.includes(row.replace(/…$/, "")) || !row.endsWith("…")).toBe(true);
25 expect(rows.join(" ")).toContain("A very long description");
26 });
27
28 test(`${kind}: as an image its left edge is the background`, async () => {
29 const raster = await rasterizer();
30 const img = decodePng(raster(renderCard(input(kind))));
31 if (!img.ok) throw new Error(img.error);
32 const { width, height, rgba } = img.value;
33 const first = [rgba[0], rgba[1], rgba[2]];
34 for (let y = 0; y < height; y += 10)
35 for (let x = 0; x < 40; x += 4) {
36 const i = (y * width + x) * 4;
37 expect([rgba[i], rgba[i + 1], rgba[i + 2]]).toEqual(first);
38 }
39 });
40 }
41 });
test/og-route.test.ts +2 −2
@@ -197,8 +197,8 @@ describe("og cards", () => {
197197 });
198198
199199 test("the card says what the thing is", async () => {
200 expect(await (await get("/og/issue/alice~shown~1.svg")).text()).toContain("ISSUE");
201 expect(await (await get("/og/pull/alice~shown~2.svg")).text()).toContain("PULL");
200 expect(await (await get("/og/issue/alice~shown~1.svg")).text()).not.toContain(">ISSUE<");
201 expect(await (await get("/og/pull/alice~shown~2.svg")).text()).not.toContain(">PULL<");
202202 expect(await (await get(`/og/run/alice~shown~${runId}.svg`)).text()).toContain("did a thing");
203203 });
204204
test/og-tags.test.ts +10 −2
@@ -131,9 +131,16 @@ describe("every kind of page unfurls", () => {
131131 test(`${path} carries og and twitter tags with a card that answers`, async () => {
132132 const res = await fetch(base + path, { redirect: "manual" });
133133 expect(res.status).toBe(200);
134 const t = tags(await res.text());
134 const doc = await res.text();
135 // Every public page: a title, a description and the one address it has.
136 expect(doc).toMatch(/<title>[^<]+<\/title>/);
137 expect(doc).toMatch(/<meta name="description" content="[^"]+"/);
138 const canonical = doc.match(/<link\s+rel="canonical"\s+href="([^"]+)"/)?.[1];
139 expect(canonical).toBe(new URL(path, base).href);
140 const t = tags(doc);
135141 expect(t.get("og:title")).toBeTruthy();
136142 expect(t.get("og:description")).toBeTruthy();
143 expect(t.get("og:description")).not.toMatch(/ · live\.?$/);
137144 expect(t.get("twitter:card")).toBe("summary_large_image");
138145 const image = t.get("og:image")!;
139146 expect(image).toBeTruthy();
@@ -165,7 +172,8 @@ describe("every kind of page unfurls", () => {
165172 expect(res.status).toBe(200);
166173 const t = tags(await res.text());
167174 expect(t.get("og:title")).toBeTruthy();
168 expect(t.get("og:description")).toMatch(/·.*\.$/);
175 expect(t.get("og:description")).toMatch(/\.$/);
176 expect(t.get("og:description")).not.toMatch(/ · live\.$/);
169177 expect(t.get("twitter:card")).toBe("summary_large_image");
170178 const image = new URL(t.get("og:image")!).pathname;
171179 expect(image).toBe("/og/app/widget.png");
test/standards.test.ts +24
@@ -494,6 +494,30 @@ describe("what the open web expects", () => {
494494 expect(html).toContain("viewport-fit=cover");
495495 });
496496
497 test("the home page and a public repository carry structured data, escaped", async () => {
498 const ld = (h: string) =>
499 [...h.matchAll(/<script type="application\/ld\+json">([^<]*)<\/script>/g)].map((m) => JSON.parse(m[1]!));
500 const home = ld(await fetch(`${base}/`).then((r) => r.text()));
501 expect(home).toHaveLength(1);
502 expect(home[0]["@graph"].map((n: { "@type": string }) => n["@type"])).toEqual(["WebSite", "Organization"]);
503 const repo = ld(await fetch(`${base}/alice/open`).then((r) => r.text()));
504 expect(repo[0]["@type"]).toBe("SoftwareSourceCode");
505 expect(repo[0].url).toBe(`${base}/alice/open`);
506 expect(repo[0].description).toMatch(/\.$/);
507 // A private repository is not described to anyone who is not signed in.
508 const closed = await fetch(`${base}/alice/closed`, { redirect: "manual" });
509 expect(await closed.text()).not.toContain("application/ld+json");
510 });
511
512 test("humans.txt says who runs the forge and where to report a problem", async () => {
513 const res = await fetch(`${base}/humans.txt`);
514 expect(res.status).toBe(200);
515 expect(res.headers.get("content-type")).toContain("text/plain");
516 const body = await res.text();
517 expect(body).toContain(`Site: ${base}/`);
518 expect(body).toContain(`${base}/.well-known/security.txt`);
519 });
520
497521 test("the page's own policy lets a browser read what it links", async () => {
498522 // default-src 'none' refuses a manifest like everything else; a link the
499523 // policy blocks is a link that does nothing. Same for the icons.
test/unfurl.test.ts +16 −1
@@ -20,6 +20,7 @@ import {
2020 appLine,
2121 firstLine,
2222 ownerLine,
23 plainDescription,
2324 PRIVATE_LINE,
2425 runLine,
2526 threadLine,
@@ -39,6 +40,20 @@ describe("the sentences", () => {
3940 ).toBe(PRIVATE_LINE);
4041 });
4142
43 test("an empty or placeholder description gets a plain sentence", () => {
44 expect(plainDescription("", "widget", "app")).toBe("widget, an app on forge.");
45 expect(plainDescription("wip", "widget", "repository")).toBe("widget, a repository on forge.");
46 expect(plainDescription("\n Tracks the tide.", "widget", "app")).toBe("Tracks the tide.");
47 });
48
49 test("an app line never ends in ' · live.'", () => {
50 const line = appLine({ private: false, name: "n", description: "Tracks the tide.", state: "live" });
51 expect(line).toBe("Tracks the tide.");
52 expect(appLine({ private: false, name: "n", description: "", state: "not running" })).toBe(
53 "n, an app on forge. Status: not running.",
54 );
55 });
56
4257 test("the first non-empty line, and nothing past it", () => {
4358 expect(firstLine("\n\n Hello \nmore")).toBe("Hello");
4459 expect(firstLine("")).toBe("");
@@ -187,7 +202,7 @@ describe("the pages", () => {
187202
188203 test("an app opens on its description and whether it is up", async () => {
189204 const line = unfurl(await get("/alice/open/app"));
190 expect(line).toMatch(/^open app for the unfurl test · [a-z ·]+\.$/);
205 expect(line).toMatch(/^open app for the unfurl test\.( Status: [a-z ·]+\.)?$/);
191206 });
192207
193208 test("no sentence uses dev's vocabulary", async () => {
test/web-budget.test.ts +1 −1
@@ -54,7 +54,7 @@ describe("web budgets (docs/web.md)", () => {
5454 const res = await fetch(base + path);
5555 const text = await res.text();
5656 expect(new TextEncoder().encode(text).length).toBeLessThan(BUDGET.html);
57 expect(/<script(?![^>]*\s(src=|type="application\/json"))/.test(text)).toBe(BUDGET.inlineScripts > 0);
57 expect(/<script(?![^>]*\s(src=|type="application\/(ld\+)?json"))/.test(text)).toBe(BUDGET.inlineScripts > 0);
5858 expect(text.includes("<symbol")).toBe(BUDGET.inlineSvg > 0);
5959 expect(text).toContain("/assets/i-");
6060 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs