Public: anyone can read this; the crew can change it.
A PDF's page count, title and author show above the viewer #14090
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/14063-a-pdf-s-page-count-title-and-author-show → main 6 commits fork 3 threads · 3 unresolved
7 files
changed +268
−0
docs/design/areas/render.md +2
| @@ -80,3 +80,5 @@ A .zip, .tar or .tar.gz is drawn by `src/web/render/archive-view.ts` as the exis | ||
| 80 | 80 | ## Diagrams (.drawio, .excalidraw, .mmd) |
| 81 | 81 | |
| 82 | 82 | `src/web/render/diagram.ts` draws a draw.io or Excalidraw file as one inline SVG in `.diagram-view` (same rules as `.dxf-view`: `currentColor`, no accent), inside `.diagram-scroll`, a frame that never lets the SVG exceed it (no fixed width, so no rule fixes a width over 390 px). A Mermaid file shows its diagram type and its source in a native `<details>` (`.diagram-source`, its summary a 44px tap target), folded, whose `pre` scrolls sideways inside its own box. |
| 83 | ||
| 84 | - `.pdf-facts`: the page count, title and author above a PDF's viewer, one line of label and value pairs. |
docs/features/README.md +1
| @@ -286,6 +286,7 @@ Read with the guide page [Your apps](../guide-your-apps.md). | ||
| 286 | 286 | ### Files in the browser |
| 287 | 287 | |
| 288 | 288 | - [](file-kinds.md) |
| 289 | - [](pdf-facts.md) | |
| 289 | 290 | - [](mesh-files.md) |
| 290 | 291 | - [](file-stl.md) |
| 291 | 292 | - [](file-dxf.md) |
docs/features/pdf-facts.md added +23
| @@ -0,0 +1,23 @@ | ||
| 1 | # A PDF's facts above the viewer | |
| 2 | ||
| 3 | Open a `.pdf` on a repository's blob page: above the browser's own viewer a | |
| 4 | strip says how many pages it has and, when the file's info dictionary names | |
| 5 | them, its title and author. A file with neither shows only the page count. | |
| 6 | ||
| 7 | - **Where it is read:** `src/web/render/pdf-meta.ts`. The page count is the | |
| 8 | `/Count` of the catalog's page-tree root; when the tree sits in compressed | |
| 9 | object streams the page objects that can be seen are counted. Title and | |
| 10 | Author come from the info dictionary the last trailer points at (an | |
| 11 | appended update wins). Literal and hex strings are read, UTF-16 included; | |
| 12 | each is cut at 300 characters and control characters become spaces. At most | |
| 13 | the first 8 MiB of the file is scanned. | |
| 14 | - **Escaping:** the strings are drawn through the `html` template, so a | |
| 15 | hostile title shows as text. | |
| 16 | - **Left out:** compressed object streams and XMP metadata are not read, and a | |
| 17 | PDF over the page's read ceiling (empty body) shows no strip. | |
| 18 | - **Terminal:** there is no door. The terminal has no blob or file view and | |
| 19 | draws no PDFs (it lists no file contents at all), so there is nothing for | |
| 20 | these facts to annotate; they would belong on a terminal blob view if one is | |
| 21 | ever built. | |
| 22 | - **Try it:** open `/<owner>/<repo>/blob/<ref>/<file>.pdf`. | |
| 23 | Tests: `test/render-pdf-meta.test.ts`. |
src/web/render/pdf-meta.ts added +130
| @@ -0,0 +1,130 @@ | ||
| 1 | /** | |
| 2 | * What a PDF says about itself, read from its own bytes: the page count, and | |
| 3 | * the Title and Author of the info dictionary the trailer points at. Only | |
| 4 | * what sits in plain text is read (a file whose objects are packed into | |
| 5 | * compressed streams yields what it can, or nothing); each fact is optional. | |
| 6 | * The strings are plain data: the caller escapes them. | |
| 7 | */ | |
| 8 | ||
| 9 | export interface PdfFacts { | |
| 10 | readonly pages?: number; | |
| 11 | readonly title?: string; | |
| 12 | readonly author?: string; | |
| 13 | } | |
| 14 | ||
| 15 | const MAX_FIELD = 300; | |
| 16 | const DICT = 8192; | |
| 17 | const MAX_SCAN = 8 * 1024 * 1024; | |
| 18 | ||
| 19 | const latin1 = (b: Uint8Array): string => new TextDecoder("latin1").decode(b); | |
| 20 | ||
| 21 | /** | |
| 22 | * A literal `( … )` string starting at `s[i]`, with escapes and nested parentheses resolved to | |
| 23 | * bytes. | |
| 24 | */ | |
| 25 | function literal(s: string, i: number): Uint8Array | undefined { | |
| 26 | const out: number[] = []; | |
| 27 | const push = (b: number) => void (out.length < MAX_FIELD * 2 && out.push(b)); | |
| 28 | let depth = 0; | |
| 29 | for (let k = i; k < s.length; k++) { | |
| 30 | const c = s[k]!; | |
| 31 | if (c === "\\") { | |
| 32 | const n = s[++k] ?? ""; | |
| 33 | const oct = /^[0-7]{1,3}/.exec(s.slice(k, k + 3)); | |
| 34 | if (oct) { | |
| 35 | push(parseInt(oct[0], 8) & 255); | |
| 36 | k += oct[0].length - 1; | |
| 37 | } else if (n === "n") push(10); | |
| 38 | else if (n === "r") push(13); | |
| 39 | else if (n === "t") push(9); | |
| 40 | else if (n === "b") push(8); | |
| 41 | else if (n === "f") push(12); | |
| 42 | else if (n !== "\n" && n !== "\r") push(n.charCodeAt(0) & 255); | |
| 43 | } else if (c === "(") { | |
| 44 | if (depth++ > 0) push(40); | |
| 45 | } else if (c === ")") { | |
| 46 | if (--depth === 0) return Uint8Array.from(out); | |
| 47 | push(41); | |
| 48 | } else push(c.charCodeAt(0) & 255); | |
| 49 | } | |
| 50 | return undefined; | |
| 51 | } | |
| 52 | ||
| 53 | function hex(s: string, i: number): Uint8Array | undefined { | |
| 54 | const end = s.indexOf(">", i); | |
| 55 | if (end < 0 || end - i > MAX_FIELD * 4) return undefined; | |
| 56 | let h = s.slice(i + 1, end).replace(/\s+/g, ""); | |
| 57 | if (!/^[0-9a-fA-F]*$/.test(h)) return undefined; | |
| 58 | if (h.length % 2) h += "0"; | |
| 59 | return Uint8Array.from(h.match(/../g) ?? [], (x) => parseInt(x, 16)); | |
| 60 | } | |
| 61 | ||
| 62 | /** | |
| 63 | * A text string: UTF-16BE behind a byte-order mark, else Latin-1 (close enough to PDFDocEncoding). | |
| 64 | */ | |
| 65 | function text(bytes: Uint8Array): string { | |
| 66 | const s = | |
| 67 | bytes[0] === 0xfe && bytes[1] === 0xff | |
| 68 | ? new TextDecoder("utf-16be").decode(bytes.subarray(2)) | |
| 69 | : latin1(bytes); | |
| 70 | // Control characters out; a title is one line. | |
| 71 | return s.replace(/[\u0000-\u001f\u007f-\u009f]+/g, " ").trim().slice(0, MAX_FIELD); | |
| 72 | } | |
| 73 | ||
| 74 | /** The value of `/Key` inside a dictionary body, when it is a string. */ | |
| 75 | function field(dict: string, key: string): string | undefined { | |
| 76 | const m = new RegExp(`/${key}\\s*([(<])`).exec(dict); | |
| 77 | if (!m) return undefined; | |
| 78 | const at = m.index + m[0].length - 1; | |
| 79 | const raw = m[1] === "(" ? literal(dict, at) : hex(dict, at); | |
| 80 | const t = raw && text(raw); | |
| 81 | return t || undefined; | |
| 82 | } | |
| 83 | ||
| 84 | /** The dictionary text of object `n g`, the last one when an update appended another. */ | |
| 85 | function object(s: string, n: string, g: string): string | undefined { | |
| 86 | let at = -1; | |
| 87 | const re = new RegExp(`(?:^|\\s)${n}\\s+${g}\\s+obj\\b`, "g"); | |
| 88 | for (const m of s.matchAll(re)) at = m.index + m[0].length; | |
| 89 | if (at < 0) return undefined; | |
| 90 | const end = s.indexOf("endobj", at); | |
| 91 | return s.slice(at, end < 0 ? at + DICT : Math.min(end, at + DICT)); | |
| 92 | } | |
| 93 | ||
| 94 | /** The last `/Key n g R` reference in the file (an appended update comes last). */ | |
| 95 | function lastRef(s: string, key: string): [string, string] | undefined { | |
| 96 | let ref: [string, string] | undefined; | |
| 97 | for (const m of s.matchAll(new RegExp(`/${key}\\s+(\\d{1,9})\\s+(\\d{1,5})\\s+R`, "g"))) ref = [m[1]!, m[2]!]; | |
| 98 | return ref; | |
| 99 | } | |
| 100 | ||
| 101 | function pageCount(s: string): number | undefined { | |
| 102 | // The catalog's page-tree root says how many; a hostile or embedded object elsewhere does not | |
| 103 | // count. | |
| 104 | const root = lastRef(s, "Root"); | |
| 105 | const catalog = root && object(s, root[0], root[1]); | |
| 106 | const tree = catalog && /\/Pages\s+(\d{1,9})\s+(\d{1,5})\s+R/.exec(catalog); | |
| 107 | const dict = tree && object(s, tree[1]!, tree[2]!); | |
| 108 | const n = dict && /\/Count\s+(\d{1,7})\b/.exec(dict); | |
| 109 | if (n) return Number(n[1]); | |
| 110 | // Objects packed into compressed streams: count the page objects that can be seen. | |
| 111 | let pages = 0; | |
| 112 | for (const _ of s.matchAll(/\/Type\s*\/Page\b(?!s)/g)) pages++; | |
| 113 | return pages > 0 ? pages : undefined; | |
| 114 | } | |
| 115 | ||
| 116 | export function pdfFacts(body: Uint8Array): PdfFacts { | |
| 117 | if (body.length < 8 || latin1(body.subarray(0, 5)) !== "%PDF-") return {}; | |
| 118 | // One decode, bounded: nothing past MAX_SCAN is read. | |
| 119 | const s = latin1(body.subarray(0, MAX_SCAN)); | |
| 120 | const pages = pageCount(s); | |
| 121 | const ref = lastRef(s, "Info"); | |
| 122 | const dict = ref && object(s, ref[0], ref[1]); | |
| 123 | const title = dict ? field(dict, "Title") : undefined; | |
| 124 | const author = dict ? field(dict, "Author") : undefined; | |
| 125 | return { | |
| 126 | ...(pages === undefined ? {} : { pages }), | |
| 127 | ...(title ? { title } : {}), | |
| 128 | ...(author ? { author } : {}), | |
| 129 | }; | |
| 130 | } |
src/web/render/pdf.ts +11
| @@ -9,13 +9,24 @@ | ||
| 9 | 9 | |
| 10 | 10 | import { html } from "../html.ts"; |
| 11 | 11 | import { fileSize } from "../ui.ts"; |
Both doors: no docs/features/ how-to and no terminal path or stated reason. |
||
| 12 | import { pdfFacts, type PdfFacts } from "./pdf-meta.ts"; | |
| 12 | 13 | import type { Rendered, RenderInput } from "./renderers.ts"; |
| 13 | 14 | |
| 15 | const facts = (f: PdfFacts) => | |
| 16 | f.pages === undefined && !f.title && !f.author | |
| 17 | ? "" | |
| 18 | : html`<dl class="pdf-facts"> | |
| 19 | ${f.pages === undefined ? "" : html`<div><dt>Pages</dt><dd>${String(f.pages)}</dd></div>`} | |
| 20 | ${f.title ? html`<div><dt>Title</dt><dd>${f.title}</dd></div>` : ""} | |
| 21 | ${f.author ? html`<div><dt>Author</dt><dd>${f.author}</dd></div>` : ""} | |
| 22 | </dl>`; | |
| 23 | ||
| 14 | 24 | export function pdf(input: RenderInput): Rendered { |
| 15 | 25 | return { |
| 16 | 26 | lines: 0, |
| 17 | 27 | summary: `${fileSize(input.size)} · PDF`, |
| 18 | 28 | content: html`<div class="card pdf-view"> |
| 29 | ${facts(pdfFacts(input.body))} | |
| 19 | 30 | <object class="pdf-frame" data="${input.media}" type="application/pdf"> |
| 20 | 31 | <p class="pdf-fallback"> |
| 21 | 32 | This browser cannot show the PDF here. |
src/web/style/content.ts +3
| @@ -564,6 +564,9 @@ img.img-box, .prose img.img-box, .tell-picture.img-box { display: block; width: | ||
| 564 | 564 | /* A PDF in the browser's own viewer: a fixed frame, so nothing shifts. */ |
| 565 | 565 | .pdf-view { overflow: hidden; } |
| 566 | 566 | .pdf-frame { display: block; width: 100%; height: 80vh; min-height: 480px; border: 0; } |
| 567 | .pdf-facts { padding: 12px 24px 4px; display: flex; flex-wrap: wrap; gap: 4px 24px; } | |
outdated
Principles 4 and 6: bare tokens, no literal fallbacks (#8884), and the border-bottom adds a box edge inside a card; use spacing. |
||
| 568 | .pdf-facts dt { display: inline; color: var(--muted-fg); } | |
| 569 | .pdf-facts dd { display: inline; margin: 0 0 0 4px; overflow-wrap: anywhere; } | |
| 567 | 570 | .pdf-fallback { padding: 16px 20px; display: flex; flex-wrap: wrap; gap: 12px; align-items: center; } |
| 568 | 571 | /* A phone: a shorter frame, so a thumb can scroll the page past it. */ |
| 569 | 572 | @media (max-width: 600px) { .pdf-frame { height: 60vh; min-height: 360px; } } |
test/render-pdf-meta.test.ts added +98
| @@ -0,0 +1,98 @@ | ||
| 1 | /** A PDF's page count, title and author, read from its own bytes and escaped. */ | |
| 2 | ||
| 3 | import { describe, expect, test } from "bun:test"; | |
| 4 | import { pdfFacts } from "../src/web/render/pdf-meta.ts"; | |
| 5 | import { pdf } from "../src/web/render/pdf.ts"; | |
| 6 | ||
| 7 | const enc = (s: string) => new TextEncoder().encode(s); | |
| 8 | ||
| 9 | const sample = (info: string) => | |
| 10 | enc( | |
| 11 | `%PDF-1.4\n1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj\n2 0 obj<</Type/Pages/Kids[3 0 R 4 0 R]/Count 2>>endobj\n` + | |
| 12 | `3 0 obj<</Type/Page/Parent 2 0 R>>endobj\n4 0 obj<</Type/Page/Parent 2 0 R>>endobj\n` + | |
| 13 | (info ? `5 0 obj<<${info}>>endobj\n` : "") + | |
| 14 | `trailer<</Root 1 0 R${info ? " /Info 5 0 R" : ""}>>\n%%EOF\n`, | |
| 15 | ); | |
| 16 | ||
| 17 | const render = (body: Uint8Array) => | |
| 18 | String(pdf({ path: "a.pdf", size: body.length, body, media: "/m", download: "/d" }).content); | |
| 19 | ||
| 20 | describe("PDF facts", () => { | |
| 21 | test("reads pages, title and author", () => { | |
| 22 | expect(pdfFacts(sample("/Title(Q3 \\(draft\\) plan)/Author(Ada)"))).toEqual({ | |
| 23 | pages: 2, | |
| 24 | title: "Q3 (draft) plan", | |
| 25 | author: "Ada", | |
| 26 | }); | |
| 27 | }); | |
| 28 | ||
| 29 | test("a hex UTF-16 title is decoded", () => { | |
| 30 | expect(pdfFacts(sample("/Title<FEFF00480069>")).title).toBe("Hi"); | |
| 31 | }); | |
| 32 | ||
| 33 | test("a PDF with no info shows only the page count", () => { | |
| 34 | expect(pdfFacts(sample(""))).toEqual({ pages: 2 }); | |
| 35 | const html = render(sample("")); | |
| 36 | expect(html).toContain("Pages"); | |
| 37 | expect(html).not.toContain("Title"); | |
| 38 | expect(html).not.toContain("Author"); | |
| 39 | }); | |
| 40 | ||
| 41 | test("each fact is optional", () => { | |
| 42 | expect(pdfFacts(sample("/Author(Bo)"))).toEqual({ pages: 2, author: "Bo" }); | |
| 43 | }); | |
| 44 | ||
| 45 | test("a hostile title is escaped", () => { | |
| 46 | const html = render(sample("/Title(<script>alert(1)</script><img src=x onerror=y>)/Author(\"><b>)")); | |
| 47 | expect(html).not.toContain("<script>"); | |
| 48 | expect(html).not.toContain("<img"); | |
| 49 | expect(html).not.toContain("<b>"); | |
| 50 | expect(html).toContain("<script>"); | |
| 51 | }); | |
| 52 | ||
| 53 | test("not a PDF, or an empty body, shows no facts", () => { | |
| 54 | expect(pdfFacts(enc("hello world, not a pdf"))).toEqual({}); | |
| 55 | expect(render(new Uint8Array(0))).not.toContain("pdf-facts"); | |
| 56 | }); | |
| 57 | ||
| 58 | test("the page count is the catalog's page-tree root, not the largest /Count anywhere", () => { | |
| 59 | const body = enc( | |
| 60 | "%PDF-1.4\n1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj\n2 0 obj<</Type/Pages/Count 3>>endobj\n" + | |
| 61 | "9 0 obj<</Type/Pages/Count 999999>>endobj\ntrailer<</Root 1 0 R>>\n", | |
| 62 | ); | |
| 63 | expect(pdfFacts(body).pages).toBe(3); | |
| 64 | }); | |
| 65 | ||
| 66 | test("without a readable page tree, the page objects are counted", () => { | |
| 67 | const body = enc("%PDF-1.5\n3 0 obj<</Type/Page>>endobj\n4 0 obj<</Type /Page>>endobj\n5 0 obj<</Type/Pages>>endobj\n"); | |
| 68 | expect(pdfFacts(body)).toEqual({ pages: 2 }); | |
| 69 | }); | |
| 70 | ||
| 71 | test("an appended update's /Info wins over the first", () => { | |
| 72 | const body = enc( | |
| 73 | "%PDF-1.4\n5 0 obj<</Title(Old)>>endobj\ntrailer<</Info 5 0 R>>\n" + | |
| 74 | "6 0 obj<</Title(New)>>endobj\ntrailer<</Info 6 0 R>>\n%%EOF\n", | |
| 75 | ); | |
| 76 | expect(pdfFacts(body).title).toBe("New"); | |
| 77 | }); | |
| 78 | ||
| 79 | test("a long title is cut at 300 characters", () => { | |
| 80 | expect(pdfFacts(sample(`/Title(${"a".repeat(1000)})`)).title).toBe("a".repeat(300)); | |
| 81 | }); | |
| 82 | ||
| 83 | test("control characters in a title become spaces", () => { | |
| 84 | expect(pdfFacts(sample("/Title(a\\000b\\nc\x01d)")).title).toBe("a b c d"); | |
| 85 | }); | |
| 86 | ||
| 87 | test("an unterminated string gives no title, and the rest still reads", () => { | |
| 88 | expect(pdfFacts(sample("/Title(never closed /Author(Ada)"))).toEqual({ pages: 2, author: "Ada" }); | |
| 89 | }); | |
| 90 | ||
| 91 | test("a large adversarial body is read in well under a second", () => { | |
| 92 | const junk = "/Type/Pages /Count ".repeat(200_000) + "/Title(".repeat(100_000) + "5 0 obj ".repeat(100_000); | |
| 93 | const body = enc("%PDF-1.4\n" + junk); | |
| 94 | const t = performance.now(); | |
| 95 | pdfFacts(body); | |
| 96 | expect(performance.now() - t).toBeLessThan(1000); | |
| 97 | }); | |
| 98 | }); |
new above
offline
Whole-body latin1 decode plus
tail + sdoubles the copy; the tail is redundant. Bound the work and test an adversarial large body.