diff --git a/changelog.d/make-pdf-swiss-followups.md b/changelog.d/make-pdf-swiss-followups.md new file mode 100644 index 000000000..fee1fa67c --- /dev/null +++ b/changelog.d/make-pdf-swiss-followups.md @@ -0,0 +1,4 @@ +--- +bump: patch +--- +**make-pdf's new layout handles three more cases.** A mermaid or excalidraw diagram right after a `###` sub-heading now spans the full width instead of being squeezed into the text column, and a wide one that gets its own sideways page takes its sub-heading along. A sub-heading with `
` line breaks now reserves room for every line, so it no longer prints over the next heading. `--to html` output now declares a phone-width viewport, so it switches to one column on phones. diff --git a/make-pdf/src/diagram-prepass.ts b/make-pdf/src/diagram-prepass.ts index 3f5d2f9aa..83d76d253 100644 --- a/make-pdf/src/diagram-prepass.ts +++ b/make-pdf/src/diagram-prepass.ts @@ -96,6 +96,9 @@ export class StrictModeError extends Error { const DIAGRAM_LANGS = new Set(["mermaid", "excalidraw"]); +/** Start of every diagram placeholder token (render.ts tells a diagram slot from a paragraph by it). */ +export const DIAGRAM_SLOT_PREFIX = "gstack-diagram-slot-"; + /** * Extract column-0 ```mermaid / ```excalidraw fences, replacing each with a * unique placeholder token paragraph. Backtick and tilde fences, any length @@ -131,7 +134,7 @@ export function extractDiagramFences(markdown: string): FenceExtraction { const info = parseInfoString(openFence.info); if (DIAGRAM_LANGS.has(info.lang) && info.render && openFence.indent === 0) { ordinal++; - const token = `gstack-diagram-slot-${runId}-${ordinal}`; + const token = `${DIAGRAM_SLOT_PREFIX}${runId}-${ordinal}`; fences.push({ lang: info.lang, source: openFence.body.join("\n"), diff --git a/make-pdf/src/orchestrator.ts b/make-pdf/src/orchestrator.ts index 474659548..1e5985276 100644 --- a/make-pdf/src/orchestrator.ts +++ b/make-pdf/src/orchestrator.ts @@ -183,10 +183,9 @@ export async function generate(requested: GenerateOptions): Promise { // ─── --to html: write the self-contained document, no print round-trip ── if (to === "html") { - const withScreenLayer = finalHtml.replace( - "", - `\n`, - ); + const withScreenLayer = finalHtml + .replace(``, `\n`) + .replace("", `\n`); fs.writeFileSync(outputPath, withScreenLayer, "utf8"); const kb = Math.round(fs.statSync(outputPath).size / 1024); progress.done(`${rendered.meta.wordCount} words · ${kb}KB · ${outputPath}`); diff --git a/make-pdf/src/render.ts b/make-pdf/src/render.ts index 023401145..5564d8e3f 100644 --- a/make-pdf/src/render.ts +++ b/make-pdf/src/render.ts @@ -16,7 +16,7 @@ import { smartypants } from "./smartypants"; import { DEFAULT_STYLE, printCss, resolveMargins, type PrintCssOptions, type Style } from "./print-css"; import { swissCoverTitle, swissFieldHeadingLines } from "./style-swiss"; import { applyImageDirectives } from "./image-policy"; -import { contentHeightInches, contentWidthInches } from "./diagram-prepass"; +import { contentHeightInches, contentWidthInches, DIAGRAM_SLOT_PREFIX } from "./diagram-prepass"; export interface RenderOptions { markdown: string; @@ -420,8 +420,10 @@ function sanitizePass(html: string): string { * paragraph, list or quote right after it go in
, * where the CSS pins the h3 to the wrapper's top and the wrapper starts where * the text does. min-height keeps a sub-heading longer than its text clear of - * the next block. (Code, tables, figures and image-only paragraphs need no - * wrapper: the CSS keeps the h3 in normal flow above them.) Only top-level + * the next block. (Code, tables, figures, image-only paragraphs and diagrams, + * which are still placeholder paragraphs here, need no wrapper: the CSS keeps + * the h3 in normal flow above them.) Each
in the heading starts a new + * line of that estimate. Only top-level * blocks are paired: an h3 inside raw HTML, a quote or a list item is not in * the field, and the CSS that positions the wrapper applies only at the top. */ @@ -435,8 +437,10 @@ export function keepFieldHeadingsWithText(html: string): string { if (html.slice(h3.end, next.start).trim() !== "") continue; const text = html.slice(next.start, next.end); if (next.tag === "p" && /^]*>[^<]*]*>[^<]*<\/p>$/i.test(text)) continue; + if (next.tag === "p" && new RegExp(`^

\\s*${DIAGRAM_SLOT_PREFIX}[0-9a-f]+-\\d+\\s*

$`).test(text)) continue; const heading = html.slice(h3.start, h3.end); - const minPt = swissFieldHeadingLines(stripTags(heading)) * 13 + 2; + const lines = heading.split(/]*>/i).reduce((n, line) => n + swissFieldHeadingLines(stripTags(line)), 0); + const minPt = lines * 13 + 2; out.push(html.slice(last, h3.start), `
${html.slice(h3.start, next.end)}
`); last = next.end; i++; diff --git a/make-pdf/src/style-swiss.ts b/make-pdf/src/style-swiss.ts index 6b5e536eb..2de6d1b8f 100644 --- a/make-pdf/src/style-swiss.ts +++ b/make-pdf/src/style-swiss.ts @@ -60,6 +60,9 @@ export function swissRules(opts: { cover?: boolean; toc?: boolean } = {}): strin // sub-heading stays in normal flow, so break-after: avoid still keeps it // with that block instead of stranding it at a page foot. `.chapter > h3:has(+ pre), .chapter > h3:has(+ table), .chapter > h3:has(+ figure), .chapter > h3:has(+ p > img:only-child) { float: none; margin: 6pt 0 4pt 0; }`, + // Above a block promoted to a landscape page, the sub-heading takes the same + // named page, so it prints on that page instead of alone before it. + `.chapter > h3:has(+ .page-wide) { float: none; margin: 6pt 0 4pt 0; page: wide; }`, `.chapter > .swiss-keep > h3 { float: none; }`, `p { margin: 0 0 7.5pt; }`, `ul, ol { padding-left: 14pt; margin: 0 0 7.5pt; }`, diff --git a/make-pdf/test/e2e/swiss-gate.test.ts b/make-pdf/test/e2e/swiss-gate.test.ts index 978a9f478..15944a26e 100644 --- a/make-pdf/test/e2e/swiss-gate.test.ts +++ b/make-pdf/test/e2e/swiss-gate.test.ts @@ -24,6 +24,8 @@ import { SWISS_FIELD_IN, SWISS_MARGINS } from "../../src/style-swiss"; import { browserAvailable, NO_BROWSER_REASON } from "../../../test/helpers/browser-available"; const FIXTURE = path.resolve(__dirname, "../fixtures/swiss-gate.md"); +const AFTER_H3_FIXTURE = path.resolve(__dirname, "../fixtures/swiss-after-h3.md"); +const BUNDLE = path.resolve(__dirname, "../../../lib/diagram-render/dist/diagram-render.html"); const ROOT = path.resolve(__dirname, "../../.."); const PDF_BIN = path.join(ROOT, "make-pdf/dist/pdf"); const CHILD_TIMEOUT_MS = 60_000; @@ -63,9 +65,9 @@ function lines(pdf: string): Line[] { /** Body lines: inside the page's type area (no running header or footer). */ const body = (ls: Line[]) => ls.filter((l) => l.y0 > 0.7 * 72 - 1 && l.y1 < l.pageH - 0.85 * 72 + 1); -function render(dir: string, name: string, args: string[]): string { +function render(dir: string, name: string, args: string[], fixture = FIXTURE): string { const out = path.join(dir, `${name}.pdf`); - execFileSync(PDF_BIN, ["generate", FIXTURE, out, "--quiet", ...args], { encoding: "utf8", timeout: CHILD_TIMEOUT_MS, stdio: ["ignore", "pipe", "pipe"] }); + execFileSync(PDF_BIN, ["generate", fixture, out, "--quiet", ...args], { encoding: "utf8", timeout: CHILD_TIMEOUT_MS, stdio: ["ignore", "pipe", "pipe"] }); return out; } @@ -186,6 +188,52 @@ describe("swiss layout gate", () => { } }, 120000); + test.skipIf(!avail.ok || !fs.existsSync(BUNDLE))("every block after a sub-heading: diagrams span the full width and no sub-heading overprints", () => { + if (!avail.ok) return; + const d = fs.mkdtempSync(path.join(os.tmpdir(), "make-pdf-swiss-gate-")); + try { + const all = body(lines(render(d, "after-h3", [], AFTER_H3_FIXTURE))); + const find = (t: string) => { + const l = all.find((x) => x.text === t); + expect({ t, found: !!l }).toEqual({ t, found: true }); + return l!; + }; + + for (const labels of [["afterh3alpha", "afterh3beta", "afterh3gamma", "afterh3delta"], ["excalialphanode", "excalibetanode"]]) { + const ls = all.filter((l) => labels.some((w) => l.text.includes(w))); + expect({ labels, found: ls.length >= labels.length }).toEqual({ labels, found: true }); + expect({ labels, leftmost: Math.min(...ls.map((l) => l.x0)) < COLUMN_PT - 20 }).toEqual({ labels, leftmost: true }); + } + for (const h of ["Mermaid follows", "Excalidraw follows"]) { + const l = find(h); + const next = all.filter((x) => x.page === l.page && x.y0 > l.y1 - 1 && x !== l); + expect({ h, labelsBelow: next.some((x) => /afterh3alpha|excalialphanode/.test(x.text)) }).toEqual({ h, labelsBelow: true }); + } + + const landscape = find("Landscape next"); + const landLabels = all.filter((l) => /landalpha|landbeta|landgamma/.test(l.text)); + expect(landLabels.length).toBeGreaterThanOrEqual(3); + expect({ landscapeHeadingPage: landscape.page }).toEqual({ landscapeHeadingPage: Math.min(...landLabels.map((l) => l.page)) }); + expect(Math.min(...landLabels.map((l) => l.x0))).toBeLessThan(COLUMN_PT - 20); + + const days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"].map(find); + for (const day of days) expect({ day: day.text, inField: day.x0 < LEFT_PT + 3 && day.x1 < COLUMN_PT }).toEqual({ day: day.text, inField: true }); + const closing = find("Closing bar heading"); + const saturday = days[days.length - 1]; + expect(saturday.page < closing.page || saturday.y1 < closing.y0).toBe(true); + + const headings = ["Paragraph follows", "List follows", "Ordered list follows", "Quote follows", "Code follows", "Table follows", + "Image follows", "Text and image follow", "Mermaid follows", "Excalidraw follows", "Landscape next", "Rule follows", "Raw HTML follows", + "Heading follows", "Second heading"].map(find); + for (const h of [...headings, ...days]) { + const hits = all.filter((x) => x !== h && x.page === h.page && x.x0 < h.x1 - 1 && x.x1 > h.x0 + 1 && x.y0 < h.y1 - 1 && x.y1 > h.y0 + 1); + expect({ h: h.text, overprints: hits.map((x) => x.text) }).toEqual({ h: h.text, overprints: [] }); + } + } finally { + fs.rmSync(d, { recursive: true, force: true }); + } + }, 120000); + test("cleanup", () => { if (dir) fs.rmSync(dir, { recursive: true, force: true }); }); diff --git a/make-pdf/test/fixtures/swiss-after-h3.md b/make-pdf/test/fixtures/swiss-after-h3.md new file mode 100644 index 000000000..92ead0d4e --- /dev/null +++ b/make-pdf/test/fixtures/swiss-after-h3.md @@ -0,0 +1,85 @@ +# Blocks after a sub-heading + +Sentence 1 of this paragraph keeps the line long enough to wrap across the text column several times, which is what a reading measure needs. Sentence 2 of this paragraph keeps the line long enough to wrap across the text column several times, which is what a reading measure needs. + +## Every block after a sub-heading + +### Paragraph follows + +Sentence 1 of this paragraph keeps the line long enough to wrap across the text column several times, which is what a reading measure needs. Sentence 2 of this paragraph keeps the line long enough to wrap across the text column several times, which is what a reading measure needs. + +### List follows + +- afterh3 list item one +- afterh3 list item two + +### Ordered list follows + +1. afterh3 ordered item one +2. afterh3 ordered item two + +### Quote follows + +> afterh3 quoted text. + +### Code follows + +``` +afterh3codeline = 1 +``` + +### Table follows + +| Column one | Column two | +|---|---| +| afterh3tablecell | b | + +### Image follows + +![a red box](./diagram-assets/red-box.png) + +### Text and image follow + +See the box ![a red box](./diagram-assets/red-box.png) inline. + +### Mermaid follows + +```mermaid +graph LR + AFTERONE[afterh3alpha] --> AFTERTWO[afterh3beta] --> AFTERTHREE[afterh3gamma] --> AFTERFOUR[afterh3delta] +``` + +### Excalidraw follows + +```excalidraw +{"type":"excalidraw","version":2,"source":"gstack-diagram-render","elements":[{"id":"VL7JRGkMTpqCVBye2mq3X","type":"rectangle","x":0,"y":0,"width":197.046875,"height":44,"angle":0,"strokeColor":"#1e1e1e","backgroundColor":"transparent","fillStyle":"solid","strokeWidth":2,"strokeStyle":"solid","roughness":1,"opacity":100,"groupIds":[],"frameId":null,"index":"a0","roundness":null,"seed":172328728,"version":3,"versionNonce":1118377320,"isDeleted":false,"boundElements":[{"type":"text","id":"mQsqVweT6BUmQpwbW6sOU"},{"id":"aVaLIsulCLlHiV1XqWi1-","type":"arrow"}],"updated":1781273248718,"link":null,"locked":false},{"id":"YX9Ff_UgFhhRa7lGo6xS9","type":"rectangle","x":247.046875,"y":0,"width":186.4375,"height":44,"angle":0,"strokeColor":"#1e1e1e","backgroundColor":"transparent","fillStyle":"solid","strokeWidth":2,"strokeStyle":"solid","roughness":1,"opacity":100,"groupIds":[],"frameId":null,"index":"a1","roundness":null,"seed":1275860584,"version":3,"versionNonce":45230184,"isDeleted":false,"boundElements":[{"type":"text","id":"9oes2DZoL-mRrT3RGakLq"},{"id":"aVaLIsulCLlHiV1XqWi1-","type":"arrow"}],"updated":1781273248718,"link":null,"locked":false},{"id":"aVaLIsulCLlHiV1XqWi1-","type":"arrow","x":197.047,"y":22,"width":44.70000000000002,"height":0,"angle":0,"strokeColor":"#1e1e1e","backgroundColor":"transparent","fillStyle":"solid","strokeWidth":2,"strokeStyle":"solid","roughness":1,"opacity":100,"groupIds":[],"frameId":null,"index":"a2","roundness":{"type":2},"seed":1530192920,"version":4,"versionNonce":1747670296,"isDeleted":false,"boundElements":null,"updated":1781273248718,"link":null,"locked":false,"points":[[0.5,0],[44.20000000000002,0]],"lastCommittedPoint":null,"startBinding":{"elementId":"VL7JRGkMTpqCVBye2mq3X","focus":0,"gap":1},"endBinding":{"elementId":"YX9Ff_UgFhhRa7lGo6xS9","focus":0,"gap":5.299874999999986},"startArrowhead":null,"endArrowhead":"arrow","elbowed":false},{"id":"mQsqVweT6BUmQpwbW6sOU","type":"text","x":33.5576171875,"y":9.5,"width":129.931640625,"height":25,"angle":0,"strokeColor":"#1e1e1e","backgroundColor":"transparent","fillStyle":"solid","strokeWidth":2,"strokeStyle":"solid","roughness":1,"opacity":100,"groupIds":[],"frameId":null,"index":"a3","roundness":null,"seed":1219280408,"version":3,"versionNonce":1462825496,"isDeleted":false,"boundElements":null,"updated":1781273248718,"link":null,"locked":false,"text":"excalialphanode","fontSize":20,"fontFamily":5,"textAlign":"center","verticalAlign":"middle","containerId":"VL7JRGkMTpqCVBye2mq3X","originalText":"excalialphanode","autoResize":true,"lineHeight":1.25},{"id":"9oes2DZoL-mRrT3RGakLq","type":"text","x":280.2998046875,"y":9.5,"width":119.931640625,"height":25,"angle":0,"strokeColor":"#1e1e1e","backgroundColor":"transparent","fillStyle":"solid","strokeWidth":2,"strokeStyle":"solid","roughness":1,"opacity":100,"groupIds":[],"frameId":null,"index":"a4","roundness":null,"seed":1436367640,"version":3,"versionNonce":639687528,"isDeleted":false,"boundElements":null,"updated":1781273248718,"link":null,"locked":false,"text":"excalibetanode","fontSize":20,"fontFamily":5,"textAlign":"center","verticalAlign":"middle","containerId":"YX9Ff_UgFhhRa7lGo6xS9","originalText":"excalibetanode","autoResize":true,"lineHeight":1.25}],"appState":{"viewBackgroundColor":"#ffffff"},"files":{}} +``` + +### Landscape next + +```mermaid page=landscape +graph LR + LANDONE[landalpha] --> LANDTWO[landbeta] --> LANDTHREE[landgamma] +``` + +### Rule follows + +--- + +### Raw HTML follows + +
afterh3 raw html block
+ +### Heading follows + +### Second heading + +Sentence 1 of this paragraph keeps the line long enough to wrap across the text column several times, which is what a reading measure needs. Sentence 2 of this paragraph keeps the line long enough to wrap across the text column several times, which is what a reading measure needs. + +### Monday
Tuesday
Wednesday
Thursday
Friday
Saturday + +Short. + +## Closing bar heading + +Sentence 1 of this paragraph keeps the line long enough to wrap across the text column several times, which is what a reading measure needs. Sentence 2 of this paragraph keeps the line long enough to wrap across the text column several times, which is what a reading measure needs. diff --git a/make-pdf/test/style-swiss.test.ts b/make-pdf/test/style-swiss.test.ts index 93168c122..d666ad45e 100644 --- a/make-pdf/test/style-swiss.test.ts +++ b/make-pdf/test/style-swiss.test.ts @@ -15,7 +15,8 @@ import * as path from "node:path"; import { printCss, resolveMargins, screenCss } from "../src/print-css"; import { keepFieldHeadingsWithText, render } from "../src/render"; -import { contentWidthInches, landscapeContentBox } from "../src/diagram-prepass"; +import { buildDiagramFigure, contentWidthInches, extractDiagramFences, landscapeContentBox, substituteSlots } from "../src/diagram-prepass"; +import { applyImagePolicy } from "../src/image-policy"; import { generate } from "../src/orchestrator"; import { DEFAULT_STYLE, SWISS_FIELD_IN, SWISS_MARGIN_SHORTHAND, swissCoverTitle, swissFieldHeadingLines } from "../src/style-swiss"; @@ -162,6 +163,85 @@ describe("swiss field headings stay with their text", () => { }); }); +describe("blocks after a swiss sub-heading", () => { + const FIXTURE = path.join(import.meta.dir, "fixtures", "swiss-after-h3.md"); + const rendered = () => { + const extraction = extractDiagramFences(fs.readFileSync(FIXTURE, "utf8")); + return { extraction, html: render({ markdown: extraction.markdown }).html }; + }; + const wrapped = (html: string) => [...html.matchAll(/
]*>

([\s\S]*?)<\/h3>/g)].map((m) => m[1]); + + test("only paragraphs, lists and quotes pair with the sub-heading before them", () => { + const { extraction, html } = rendered(); + expect(extraction.fences.map((f) => f.lang)).toEqual(["mermaid", "excalidraw", "mermaid"]); + expect(wrapped(html)).toEqual([ + "Paragraph follows", + "List follows", + "Ordered list follows", + "Quote follows", + "Second heading", + "Monday
Tuesday
Wednesday
Thursday
Friday
Saturday", + ]); + }); + + test("a diagram after a sub-heading stays a top-level block, so it keeps the full width", () => { + const { extraction, html } = rendered(); + const slots = new Map(extraction.fences.map((f) => [f.token, buildDiagramFigure(f, `${f.lang}`)])); + const out = substituteSlots(html, slots); + expect(out).not.toMatch(/
]*>

(Mermaid|Excalidraw) follows/); + expect(out).toMatch(/

Mermaid follows<\/h3>\s*
Excalidraw follows<\/h3>\s*
h3:has(+ figure)"); + }); + + test("a landscape-promoted diagram after a sub-heading lands outside the field wrapper", () => { + const { extraction, html } = rendered(); + const mermaid = extraction.fences[0]; + const figure = buildDiagramFigure({ ...mermaid, page: "landscape" }, ''); + const out = applyImagePolicy(substituteSlots(html, new Map([[mermaid.token, figure]])), { + contentWidthIn: 7, landscape: { contentWIn: 9.5, contentHIn: 7 }, warn: () => {}, + }); + expect(out.hasLandscape).toBe(true); + expect(out.html).toMatch(/

Mermaid follows<\/h3>\s*
]*>\s*
/g) ?? []) expect(keep).not.toContain("page-wide"); + expect(printCss()).toMatch(/\.chapter > h3:has\(\+ \.page-wide\) \{[^}]*page: wide;/); + }); + + test("explicit
line breaks in a sub-heading count toward its height", () => { + expect(render({ markdown: "### Monday
Tuesday
Wednesday\n\nShort." }).html).toContain('
'); + expect(render({ markdown: "### Monday
Tuesday
Wednesday\n\nShort." }).html).toContain('
'); + const unbroken = swissFieldHeadingLines("Monday Tuesday Wednesday") * 13 + 2; + expect(unbroken).toBeLessThan(41); + expect(render({ markdown: "### Monday Tuesday Wednesday\n\nShort." }).html).toContain(`
`); + }); +}); + +describe("--to html fits phone screens", () => { + const VIEWPORT = ''; + for (const style of ["swiss", "plain"] as const) { + test(`${style} HTML export declares one device-width viewport in its head`, async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "make-pdf-viewport-")); + try { + const input = path.join(dir, "doc.md"); + const output = path.join(dir, "doc.html"); + fs.writeFileSync(input, '# Doc\n\n\n\n### Sub\n\nBody text.\n'); + await generate({ input, output, to: "html", quiet: true, style }); + const html = fs.readFileSync(output, "utf8"); + expect(html.split(VIEWPORT).length - 1).toBe(1); + expect(html).not.toContain("width=10"); + expect(html.indexOf(VIEWPORT)).toBeLessThan(html.indexOf("")); + expect(html).toContain(screenCss(style)); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } + }, 60_000); + } + test("the HTML staged for printing carries no viewport", () => { + expect(render({ markdown: "# Doc" }).html).not.toContain('name="viewport"'); + expect(render({ markdown: "# Doc", style: "plain" }).html).not.toContain('name="viewport"'); + }); +}); + describe("swiss cover title sizing", () => { test("short titles get the full 96pt poster size and the deep top pad", () => { expect(swissCoverTitle("gstack ethos")).toEqual({ fontPt: 96, padTopIn: 3.2 });