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

Every image on every page declares its size, and one test fails on a page that would shift #13053

Merged opened this

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

Merged

scout/forge:scout/13030-every-image-on-every-page-declares-its-s → main 5 commits fork 3 threads · 3 unresolved

  • Merged. scout/13030-every-image-on-every-page-declares-its-s was merged into main as 3c45d95.

Review

Sign in to review this change.
9 files changed +99 −9
src/web/markdown.ts +5 −2
@@ -105,7 +105,7 @@ function inline(escaped: string, repo?: MarkdownRepo): string {
105105 if (at !== undefined) {
106106 const alt = text.replace(/<\/?(?:code|strong|em)>/g, "");
107107 if (at === "inert" || at.dir || !IMAGE.test(at.path)) return alt;
108 return `<img src="${repo.base}/media/${repo.ref}/${encodePath(at.path)}" alt="${alt}" loading="lazy">`;
108 return `<img src="${repo.base}/media/${repo.ref}/${encodePath(at.path)}" alt="${alt}" class="img-inline" loading="lazy" decoding="async">`;
outdated

Principle 3 / phone: every markdown image, badges included, becomes a full-width 16:9 block. Restrict the box to standalone images; leave inline ones inline.

109109 }
110110 }
111111 // Protocol-relative "//host" escapes to another origin — reject it,
@@ -252,7 +252,10 @@ function renderUncached(source: string, repo?: MarkdownRepo): Html {
252252
253253 const closeParagraph = () => {
254254 if (paragraph.length > 0) {
255 out.push(`<p>${inline(paragraph.join("\n"), repo)}</p>`);
255 // An image alone in its paragraph is a picture and reserves a 16:9 box; one in a line of
256 // text, or inside a link (a badge), stays inline.
257 const made = inline(paragraph.join("\n"), repo);
258 out.push(`<p>${/^[<]img [^>]*>$/.test(made) ? made.replace('class="img-inline"', 'class="img-box"') : made}</p>`);
256259 paragraph = [];
257260 }
258261 };
src/web/pages/looks.ts +3 −1
@@ -290,7 +290,8 @@ export function lookCard(
290290 <a class="look" href="${url}">
291291 <img
292292 src="${url}"
293 ${size === undefined ? html`` : html`width="${size.width}" height="${size.height}"`}
293 ${size === undefined ? html`class="img-box"` : html`width="${size.width}" height="${size.height}"`}
294 decoding="async"
294295 alt="${look.note ?? ""}"
295296 loading="lazy"
296297 />
@@ -364,6 +365,7 @@ export function lookNow(ctx: Ctx, repo: Repo, record: AppRecord): Html {
364365 width="${size.width}"
365366 height="${size.height}"
366367 alt="${repo.name} as it looks now"
368 decoding="async"
367369 />
368370 </a>`;
369371 }
src/web/render/notebook.ts +1 −1
@@ -95,7 +95,7 @@ export function parseNotebook(body: Uint8Array | string): { cells: NbCell[]; tot
9595
9696 function outputHtml(o: NbOutput): Html {
9797 if (o.kind === "image")
98 return html`<img class="nb-img" alt="Notebook output" src="data:${o.mime};base64,${o.data}" />`;
98 return html`<img class="nb-img img-box" decoding="async" alt="Notebook output" src="data:${o.mime};base64,${o.data}" />`;
9999 if (o.kind === "caption") return html`<div class="nb-cap">${o.text}</div>`;
100100 return html`<pre class="${o.kind === "error" ? "nb-out nb-err" : "nb-out"}">${o.text}</pre>`;
101101 }
src/web/render/ora.ts +1 −1
@@ -88,7 +88,7 @@ export function ora(input: RenderInput): Rendered {
8888 const picture =
8989 stack.preview === null
9090 ? `<p class="muted small">No merged preview in this file.</p>`
91 : `<img class="nb-img" src="${stack.preview}" alt="Merged preview of ${escapeHtml(input.path.slice(input.path.lastIndexOf("/") + 1))}"${box}>`;
91 : `<img class="nb-img${w !== null && h !== null ? "" : " img-box"}" decoding="async" src="${stack.preview}" alt="Merged preview of ${escapeHtml(input.path.slice(input.path.lastIndexOf("/") + 1))}"${box}>`;
9292 const more = stack.total > stack.layers.length ? `<p class="muted small">The first ${LAYERS} layers are shown.</p>` : "";
9393 const content = html`${raw(picture)}
9494 <table class="table" data-dense aria-label="Layers, top first">
src/web/studio/tell.ts +1 −1
@@ -596,7 +596,7 @@ async function studioTell(
596596 ${hasPicture(db, repo.id, issue.number)
597597 ? card(
598598 html`<a href="${thread}/picture"
599 ><img src="${thread}/picture" alt="The page the sender was looking at" loading="lazy" class="tell-picture"
599 ><img src="${thread}/picture" alt="The page the sender was looking at" loading="lazy" decoding="async" class="tell-picture img-box"
600600 /></a>`,
601601 {
602602 extra: "mt",
src/web/style/content.ts +3
@@ -478,6 +478,9 @@ form.inline { display: inline; margin-left: auto; }
478478 /* A notebook (render/notebook.ts): cells are rows with space between, never boxes. */
479479 .nb-cell { margin: 0 0 28px; min-width: 0; }
480480 .nb pre { max-width: 100%; overflow-x: auto; margin: 8px 0; }
481 img.img-box, .prose img.img-box, .tell-picture.img-box { display: block; width: 100%; height: auto; aspect-ratio: 16 / 9; object-fit: contain; }

Specificity: img.img-box overrides .imgview-img and .is-actual leaves width:100%, so actual-size zoom is broken for unsized images. Exclude the viewer or reset width there.

482 /* A badge or an image in a line of text: a line of height reserved, the width its own. */
483 .prose img.img-inline { display: inline-block; min-height: 20px; width: auto; vertical-align: middle; }
481484 .nb-img { display: block; max-width: 100%; height: auto; margin: 8px 0; }
482485 .nb-cap { color: var(--muted-fg); font-size: 12.5px; margin-top: 8px; }
483486
test/img-size.test.ts added +82
@@ -0,0 +1,82 @@
1 /** No <img> a page emits moves the page when it arrives: a size, or a box that holds its place. */
2 import { expect, test } from "bun:test";
3 import { Glob } from "bun";
4 import { renderMarkdown } from "../src/web/markdown.ts";
5 import { notebook } from "../src/web/render/notebook.ts";
6 import { image } from "../src/web/render/image.ts";
7
8 /** The `<img>` tags in markup, each as one string. */
9 function tags(markup: string): string[] {
10 return [...markup.matchAll(/<img\s[^>]*>/g)].map((m) => m[0]);
11 }
12
13 /** Tags with no width+height and no reserved box (`img-box`, `img-inline`, the viewer's pane). */
14 export function shifting(markup: string): string[] {
15 return tags(markup).filter(
16 (t) =>
17 !(/\bwidth=/.test(t) && /\bheight=/.test(t)) && !/\b(?:img-box|img-inline|imgview-img)\b/.test(t),
18 );
19 }
20
21 const enc = (s: string): Uint8Array => new TextEncoder().encode(s);
22 const repo = { base: "/o/n", ref: "main", dir: "" };
23
24 test("the detector fails on an image that would shift", () => {
outdated

Box 2 asks to render each layout's page. This greps source text; render real output for the unsized cases instead.

25 expect(shifting(`<img src="/a.png" alt="">`)).toHaveLength(1);
26 expect(shifting(`<img src="/a.png" width="3" height="4" alt="">`)).toHaveLength(0);
27 expect(shifting(`<img class="img-box" src="/a.png" alt="">`)).toHaveLength(0);
28 });
29
30 test("markdown: a picture alone gets a 16:9 box, a badge or inline image stays inline", () => {
31 const alone = String(renderMarkdown("![a](pic.png)", repo));
32 expect(alone).toContain('class="img-box"');
33 const badge = String(renderMarkdown("[![b](b.svg)](x.md) ![c](c.svg) text ![d](d.png)", repo));
34 expect(tags(badge)).toHaveLength(3);
35 expect(badge).not.toContain("img-box");
36 for (const out of [alone, badge]) expect(shifting(out)).toEqual([]);
37 });
38
39 test("a notebook output image, which has no known size, reserves a box", () => {
40 const nb = JSON.stringify({
41 cells: [{ cell_type: "code", source: "x", outputs: [{ output_type: "display_data", data: { "image/png": "iVBORw0KGgo=" } }] }],
42 });
43 const out = String(notebook({ path: "a.ipynb", size: nb.length, body: enc(nb), media: "/m", download: "/d" }).content);
44 expect(tags(out)).toHaveLength(1);
45 expect(shifting(out)).toEqual([]);
46 });
47
48 test("the image viewer on a file whose size cannot be read sits in the pane that holds its place", () => {
49 const out = String(image({ path: "a.png", size: 4, body: enc("nope"), media: "/m", download: "/d" }).content);
50 expect(tags(out)).toHaveLength(1);
51 expect(out).toContain("imgview-pane");
52 expect(shifting(out)).toEqual([]);
53 // Zoom to actual size must not be fought by the box rule.
54 expect(tags(out)[0]).not.toContain("img-box");
55 });
56
57 /** The `<img` tags in a source file, reading past `${...}` holes and `=>` to the tag's own end. */
58 function sourceTags(src: string): string[] {
59 const found: string[] = [];
60 for (const m of src.matchAll(/<img\s/g)) {
61 let depth = 0;
62 let i = (m.index ?? 0) + 4;
63 for (; i < src.length; i++) {
64 const c = src[i];
65 if (c === "$" && src[i + 1] === "{") depth++;
66 else if (c === "}" && depth > 0) depth--;
67 else if (c === ">" && depth === 0 && src[i - 1] !== "=") break;
68 }
69 found.push(src.slice(m.index ?? 0, i + 1));
70 }
71 return found;
72 }
73
74 test("every template's <img> under src/web declares its size or sits in a box", async () => {
75 const bad: string[] = [];
76 for await (const f of new Glob("src/web/**/*.ts").scan(".")) {
77 for (const t of sourceTags(await Bun.file(f).text())) {
78 if (shifting(t).length > 0) bad.push(`${f}: ${t.replace(/\s+/g, " ").slice(0, 100)}`);
79 }
80 }
81 expect(bad).toEqual([]);
82 });
test/markdown-relative.test.ts +2 −2
@@ -9,7 +9,7 @@ const md = (s: string, r = repo): string => String(renderMarkdown(s, r));
99
1010 describe("relative images and links resolve inside the repository", () => {
1111 test("an image renders the file at the same ref", () => {
12 expect(md("![logo](img/a.png)")).toContain('<img src="/ann/app/media/main/docs/img/a.png" alt="logo" loading="lazy">');
12 expect(md("![logo](img/a.png)")).toContain('<img src="/ann/app/media/main/docs/img/a.png" alt="logo" class="img-box" loading="lazy" decoding="async">');
1313 });
1414 test("an image from the root directory and a ../ that stays inside", () => {
1515 expect(md("![x](../pics/b.svg)")).toContain('src="/ann/app/media/main/pics/b.svg"');
@@ -69,7 +69,7 @@ describe("relative images and links resolve inside the repository", () => {
6969
7070 test("an image inside a link is an image inside a link", () => {
7171 const out = md("[![badge](b.svg)](x.md)");
72 expect(out).toContain('<a href="/ann/app/blob/main/docs/x.md" rel="nofollow noopener"><img src="/ann/app/media/main/docs/b.svg" alt="badge" loading="lazy"></a>');
72 expect(out).toContain('<a href="/ann/app/blob/main/docs/x.md" rel="nofollow noopener"><img src="/ann/app/media/main/docs/b.svg" alt="badge" class="img-inline" loading="lazy" decoding="async"></a>');
7373 expect(out).not.toContain("](");
7474 expect(md("[![b](https://ok.test/b.svg)](https://ok.test/)")).not.toContain("](");
7575 });
test/render-notebook.test.ts +1 −1
@@ -37,7 +37,7 @@ describe("notebooks", () => {
3737 expect(out).toContain("<h1");
3838 expect(out).toContain("In [3]:");
3939 expect(out).toContain("a &lt; b");
40 expect(out).toContain(`<img class="nb-img" alt="Notebook output" src="data:image/png;base64,${PNG}"`);
40 expect(out).toContain(`<img class="nb-img img-box" decoding="async" alt="Notebook output" src="data:image/png;base64,${PNG}"`);
4141 expect(out).toContain("&lt;script&gt;alert(1)&lt;/script&gt;");
4242 expect(out).not.toContain("<script");
4343 expect(out).toContain("&lt;b&gt;x&lt;/b&gt;");

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs