make-pdf: bold Swiss-style layout by default, --style plain keeps the old look (GST-3770) (#4820)

make-pdf now prints in a bold Swiss-style layout by default: black bars
for section headings, small red sub-headings in a left column beside the
text, a large cover title, and a shorter, easier line.

Generated documents should look designed, not default; Garry picked this
look over today's in two rounds of blind comparisons.

Nothing to do: pass `--style plain` to get exactly the PDF you got
before. Word output always uses the plain look.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
Review-Finding: p1/specialist-batched#1 reader=red-team
Review-Finding: p1/specialist-batched#2 reader=design-checklist
Review-Finding: p2/red-team#1 reader=red-team
Review-Finding: p2/outside-voice#1 reader=outside-voice
Review-Finding: p2/outside-voice#2 reader=outside-voice
Review-Finding: p2/outside-voice#3 reader=outside-voice
Review-Finding: p2/outside-voice#4 reader=outside-voice
Review-Finding: p2/adversarial-native#3 reader=adversarial-native
Review-Finding: p2/specialist-batched#1 reader=specialist-batched
This commit is contained in:
Garry Tanandcapy-ai[bot] authored and GitHub committed 2026-11-25 13:31:02 +00:00
1 parent 64fe9e5231
commit 80fd754fd1
26 files changed
+1279 -38

No files matched your search

+20 -2
View File
@@ -13,7 +13,8 @@
import { COMMANDS } from "./commands";
import { ExitCode, BrowserUnavailableError } from "./types";
import type { GenerateOptions, PreviewOptions } from "./types";
import type { GenerateOptions, PreviewOptions, Style } from "./types";
import { STYLES } from "./style-swiss";
interface ParsedArgs {
command: string;
@@ -85,8 +86,14 @@ function printUsage(): void {
lines.push(" html = single self-contained file, no network refs.");
lines.push(" docx = content fidelity, diagrams as PNG.");
lines.push("");
lines.push("Look:");
lines.push(" --style swiss|plain swiss (default): bold Swiss layout, black heading bars,");
lines.push(" red accents, a left field for sub-headings.");
lines.push(" plain: the look before swiss, unchanged.");
lines.push("");
lines.push("Page layout:");
lines.push(" --margins <dim> All four margins (default: 1in). in, pt, cm, mm.");
lines.push(" --margins <dim> All four margins (default: 0.7in 0.75in 0.85in 0.75in");
lines.push(" under swiss, 1in under plain). in, pt, cm, mm.");
lines.push(" --page-size letter|a4|legal (aliases: --format — page SIZE, not output format)");
lines.push("");
lines.push("Document structure:");
@@ -126,6 +133,15 @@ function printUsage(): void {
console.error(lines.join("\n"));
}
function styleFromFlags(f: Record<string, string | boolean>, command: string): Style | undefined {
if (f.style === undefined) return undefined;
const value = typeof f.style === "string" ? f.style.toLowerCase() : "";
if ((STYLES as readonly string[]).includes(value)) return value as Style;
const got = typeof f.style === "string" ? `'${f.style}'` : "no value";
console.error(`$P ${command}: invalid --style (got ${got}). Expected ${STYLES.join(" or ")}, for example --style plain.`);
process.exit(ExitCode.BadArgs);
}
function generateOptionsFromFlags(parsed: ParsedArgs): GenerateOptions {
const p = parsed.positional;
if (p.length === 0) {
@@ -149,6 +165,7 @@ function generateOptionsFromFlags(parsed: ParsedArgs): GenerateOptions {
input: p[0],
output: p[1],
to: to as GenerateOptions["to"],
style: styleFromFlags(f, "generate"),
margins: f.margins as string | undefined,
marginTop: f["margin-top"] as string | undefined,
marginRight: f["margin-right"] as string | undefined,
@@ -192,6 +209,7 @@ function previewOptionsFromFlags(parsed: ParsedArgs): PreviewOptions {
};
return {
input: p[0],
style: styleFromFlags(f, "preview"),
cover: f.cover === true,
toc: f.toc === true,
watermark: typeof f.watermark === "string" ? f.watermark : undefined,
+3
View File
@@ -20,6 +20,8 @@ export const COMMANDS = new Map<string, {
usage: "generate <input.md> [output.pdf] [options]",
category: "Primary",
flags: [
// Look
"--style",
// Page layout
"--margins", "--margin-top", "--margin-right", "--margin-bottom", "--margin-left",
"--page-size", "--format",
@@ -41,6 +43,7 @@ export const COMMANDS = new Map<string, {
usage: "preview <input.md> [options]",
category: "Primary",
flags: [
"--style",
"--cover", "--toc", "--no-chapter-breaks", "--watermark",
"--no-confidential", "--allow-network",
"--title", "--author", "--date",
+12
View File
@@ -833,6 +833,18 @@ const PAGE_HEIGHTS_IN: Record<string, number> = {
tabloid: 17,
};
export function contentHeightInches(opts: {
pageSize?: string;
margins?: string;
marginTop?: string;
marginBottom?: string;
}): number {
const pageH = PAGE_HEIGHTS_IN[opts.pageSize ?? "letter"] ?? 11;
const top = dimToInches(opts.marginTop ?? opts.margins, 1);
const bottom = dimToInches(opts.marginBottom ?? opts.margins, 1);
return Math.max(1, pageH - top - bottom);
}
/**
* Content box of the rotated (landscape) named page: portrait page HEIGHT
* becomes the landscape width; portrait WIDTH becomes the landscape height.
+11 -5
View File
@@ -23,7 +23,7 @@ import * as path from "node:path";
import { spawn } from "node:child_process";
import { render } from "./render";
import { screenCss } from "./print-css";
import { DEFAULT_STYLE, resolveMargins, screenCss } from "./print-css";
import type { GenerateOptions, PreviewOptions } from "./types";
import { ExitCode } from "./types";
import { pickEngine } from "../../lib/aside-render";
@@ -84,7 +84,9 @@ class ProgressReporter {
/**
* generate — full pipeline. Returns the output PDF path on success.
*/
export async function generate(opts: GenerateOptions): Promise<string> {
export async function generate(requested: GenerateOptions): Promise<string> {
const style = requested.to === "docx" ? "plain" : requested.style ?? DEFAULT_STYLE;
const opts = resolveMargins(requested, style);
const progress = new ProgressReporter(opts);
const input = path.resolve(opts.input);
@@ -118,6 +120,7 @@ export async function generate(opts: GenerateOptions): Promise<string> {
watermark: opts.watermark,
noChapterBreaks: opts.noChapterBreaks,
confidential: opts.confidential,
style,
pageSize: opts.pageSize,
margins: opts.margins,
marginTop: opts.marginTop,
@@ -182,7 +185,7 @@ export async function generate(opts: GenerateOptions): Promise<string> {
if (to === "html") {
const withScreenLayer = finalHtml.replace(
"</style>",
`</style>\n<style>\n${screenCss()}\n</style>`,
`</style>\n<style>\n${screenCss(style)}\n</style>`,
);
fs.writeFileSync(outputPath, withScreenLayer, "utf8");
const kb = Math.round(fs.statSync(outputPath).size / 1024);
@@ -201,7 +204,8 @@ export async function generate(opts: GenerateOptions): Promise<string> {
if (opts.headerTemplate) printOnly.push("--header-template");
if (opts.footerTemplate) printOnly.push("--footer-template");
if (opts.pageSize) printOnly.push("--page-size");
if (opts.margins || opts.marginTop || opts.marginRight || opts.marginBottom || opts.marginLeft) printOnly.push("--margins");
if (requested.margins || requested.marginTop || requested.marginRight || requested.marginBottom || requested.marginLeft) printOnly.push("--margins");
if (requested.style) printOnly.push("--style");
if (printOnly.length > 0) {
warn(`docx is content-fidelity: ${printOnly.join(", ")} do not apply to Word output`);
}
@@ -240,7 +244,8 @@ export async function generate(opts: GenerateOptions): Promise<string> {
pageNumbers: false,
tagged: opts.tagged !== false,
outline: opts.outline !== false,
printBackground: !!opts.watermark,
// swiss paints black heading bars and a black cover block: backgrounds must print.
printBackground: !!opts.watermark || style === "swiss",
// Named landscape pages only take effect when Chromium honors CSS page
// sizes. Flip it ONLY when a promotion exists — minimal behavior change
// for every other document.
@@ -301,6 +306,7 @@ export async function preview(opts: PreviewOptions): Promise<string> {
noChapterBreaks: opts.noChapterBreaks,
confidential: opts.confidential,
pageNumbers: opts.pageNumbers,
style: opts.style,
});
progress.end("Rendering HTML", `${rendered.meta.wordCount} words`);
+43 -4
View File
@@ -34,6 +34,15 @@
* single source of truth (DRY) and every stack stays in sync.
*/
import {
DEFAULT_STYLE,
SWISS_MARGIN_SHORTHAND,
SWISS_MARGINS,
swissRules,
swissScreenCss,
type Style,
} from "./style-swiss";
// Metric-compatible sans stack: Helvetica (macOS), Liberation Sans (Linux,
// ships via fonts-liberation), Arial (Windows). Shared by every text surface.
const SANS_STACK = `Helvetica, "Liberation Sans", Arial`;
@@ -42,7 +51,12 @@ const CJK_STACK = `"PingFang SC", "Heiti SC", "Noto Sans CJK SC", "Source Han Sa
// Color-emoji families: Apple (macOS), Segoe (Windows), Noto (Linux).
const EMOJI_FAMILIES = `"Apple Color Emoji", "Segoe UI Emoji", "Noto Color Emoji"`;
export { DEFAULT_STYLE, STYLES, type Style } from "./style-swiss";
export interface PrintCssOptions {
// Look: "swiss" (default) or "plain" (the look before GSTA-849, byte for byte).
style?: Style;
// Document structure
cover?: boolean;
toc?: boolean;
@@ -58,7 +72,7 @@ export interface PrintCssOptions {
// Page size (in CSS `@page size:` terms)
pageSize?: "letter" | "a4" | "legal" | "tabloid";
// Margins (default 1in)
// Margins (default: 1in plain, 0.7in 0.75in 0.85in 0.75in swiss)
margins?: string;
// Whether to render "N of M" page numbers in the @page @bottom-center rule.
@@ -71,8 +85,9 @@ export interface PrintCssOptions {
* Produce a CSS block (no <style> wrapper) for inline injection.
*/
export function printCss(opts: PrintCssOptions = {}): string {
const style = opts.style ?? DEFAULT_STYLE;
const size = opts.pageSize ?? "letter";
const margin = opts.margins ?? "1in";
const margin = opts.margins ?? (style === "swiss" ? SWISS_MARGIN_SHORTHAND : "1in");
const hasWatermark = typeof opts.watermark === "string" && opts.watermark.length > 0;
return [
@@ -91,9 +106,32 @@ export function printCss(opts: PrintCssOptions = {}): string {
footnoteRules(),
hasWatermark ? watermarkRules() : "",
breakAvoidRules(),
style === "swiss" ? swissRules({ cover: opts.cover, toc: opts.toc }) : "",
].filter(Boolean).join("\n\n");
}
type MarginOptions = {
margins?: string; marginTop?: string; marginRight?: string;
marginBottom?: string; marginLeft?: string;
};
/**
* Fill in the style's default margins. Explicit --margins sets all four
* sides and --margin-<side> overrides one, under either style. plain returns
* the options untouched, so every plain code path still sees exactly what
* the user passed (and falls back to 1in where it always did).
*/
export function resolveMargins<T extends MarginOptions>(opts: T, style: Style): T {
if (style !== "swiss") return opts;
return {
...opts,
marginTop: opts.marginTop ?? opts.margins ?? SWISS_MARGINS.top,
marginRight: opts.marginRight ?? opts.margins ?? SWISS_MARGINS.right,
marginBottom: opts.marginBottom ?? opts.margins ?? SWISS_MARGINS.bottom,
marginLeft: opts.marginLeft ?? opts.margins ?? SWISS_MARGINS.left,
};
}
function pageRules(size: string, margin: string, opts: PrintCssOptions): string {
const runningHeader = escapeCssString(opts.runningHeader ?? "");
const showConfidential = opts.confidential !== false;
@@ -156,8 +194,8 @@ function pageRules(size: string, margin: string, opts: PrintCssOptions): string
* (centered measure, padding, no print-only chapter breaks forcing scroll
* gaps). Print output is unaffected — media-scoped.
*/
export function screenCss(): string {
return [
export function screenCss(style: Style = DEFAULT_STYLE): string {
const plain = [
`@media screen {`,
// ~42em at 12pt ≈ 70-75 characters per line — the readable ceiling.
` body { max-width: 42em; margin: 0 auto; padding: 2.5em 1.5em; }`,
@@ -168,6 +206,7 @@ export function screenCss(): string {
` .toc li .toc-page, .toc li .toc-dots { display: none; }`,
`}`,
].join("\n");
return style === "swiss" ? `${plain}\n${swissScreenCss()}` : plain;
}
function rootTypography(): string {
+85 -5
View File
@@ -13,8 +13,10 @@
import { marked } from "marked";
import { smartypants } from "./smartypants";
import { printCss, type PrintCssOptions } from "./print-css";
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";
export interface RenderOptions {
markdown: string;
@@ -32,6 +34,9 @@ export interface RenderOptions {
noChapterBreaks?: boolean;
confidential?: boolean; // default: true
// Look: "swiss" (default) or "plain".
style?: Style;
// Page layout
pageSize?: "letter" | "a4" | "legal" | "tabloid";
margins?: string;
@@ -95,7 +100,10 @@ export function render(opts: RenderOptions): RenderResult {
// numbering is always off in orchestrator). If the caller supplied a custom
// footerTemplate, suppress CSS page numbers too so their footer wins.
const showPageNumbers = opts.pageNumbers !== false && !opts.footerTemplate;
const style = opts.style ?? DEFAULT_STYLE;
const pageBox = resolveMargins(opts, style);
const cssOptions: PrintCssOptions = {
style,
cover: opts.cover,
toc: opts.toc,
noChapterBreaks: opts.noChapterBreaks,
@@ -105,7 +113,7 @@ export function render(opts: RenderOptions): RenderResult {
pageSize: opts.pageSize,
// Compose per-side margins into the CSS shorthand so @page stays the
// single source of truth even under preferCSSPageSize.
margins: composeMargins(opts),
margins: composeMargins(pageBox),
pageNumbers: showPageNumbers,
};
const css = printCss(cssOptions);
@@ -117,6 +125,8 @@ export function render(opts: RenderOptions): RenderResult {
subtitle: opts.subtitle,
author: derivedAuthor,
date: derivedDate,
style,
box: { contentWIn: contentWidthInches(pageBox), contentHIn: contentHeightInches(pageBox) },
})
: "";
@@ -128,10 +138,12 @@ export function render(opts: RenderOptions): RenderResult {
const tocBlock = opts.toc ? buildTocBlock(anchored.entries) : "";
const laidOutHtml = style === "swiss" ? keepFieldHeadingsWithText(anchoredHtml) : anchoredHtml;
// Wrap body in .chapter sections at H1 boundaries if chapter breaks are on.
const chapterHtml = opts.noChapterBreaks
? `<section class="chapter">${anchoredHtml}</section>`
: wrapChaptersByH1(anchoredHtml);
? `<section class="chapter">${laidOutHtml}</section>`
: wrapChaptersByH1(laidOutHtml);
const watermarkBlock = opts.watermark
? `<div class="watermark">${escapeHtml(opts.watermark)}</div>`
@@ -401,19 +413,87 @@ function sanitizePass(html: string): string {
// ─── Cover / TOC / Chapter helpers ────────────────────────────────────
/**
* swiss sets an h3 in the left field beside the text that follows it. A float
* does not move with that text: when orphans push a paragraph to the next
* page, a floated sub-heading stays behind at the page foot. So the h3 and the
* paragraph, list or quote right after it go in <div class="swiss-keep">,
* 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
* 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.
*/
export function keepFieldHeadingsWithText(html: string): string {
const blocks = topLevelBlocks(html);
const out: string[] = [];
let last = 0;
for (let i = 0; i + 1 < blocks.length; i++) {
const [h3, next] = [blocks[i], blocks[i + 1]];
if (h3.tag !== "h3" || !/^(p|ul|ol|blockquote)$/.test(next.tag)) continue;
if (html.slice(h3.end, next.start).trim() !== "") continue;
const text = html.slice(next.start, next.end);
if (next.tag === "p" && /^<p\b[^>]*>[^<]*<img\b[^>]*>[^<]*<\/p>$/i.test(text)) continue;
const heading = html.slice(h3.start, h3.end);
const minPt = swissFieldHeadingLines(stripTags(heading)) * 13 + 2;
out.push(html.slice(last, h3.start), `<div class="swiss-keep" style="min-height: ${minPt}pt;">${html.slice(h3.start, next.end)}</div>`);
last = next.end;
i++;
}
out.push(html.slice(last));
return out.join("");
}
const VOID_TAGS = new Set(["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track", "wbr"]);
/**
* Spans of the top-level elements in a fragment. Comments are skipped, void
* tags open nothing, a close tag with no matching open tag is ignored, and a
* close tag closes whatever it left open, so unbalanced raw HTML cannot leave
* the rest of the document nested.
*/
function topLevelBlocks(html: string): Array<{ tag: string; start: number; end: number }> {
const blocks: Array<{ tag: string; start: number; end: number }> = [];
const stack: string[] = [];
let start = 0;
const token = /<!--[\s\S]*?(?:-->|$)|<(\/?)([a-zA-Z][\w-]*)\b[^>]*>/g;
let m: RegExpExecArray | null;
while ((m = token.exec(html)) !== null) {
if (!m[2]) continue;
const tag = m[2].toLowerCase();
if (m[1]) {
const at = stack.lastIndexOf(tag);
if (at < 0) continue;
stack.length = at;
if (at === 0) blocks.push({ tag, start, end: token.lastIndex });
continue;
}
if (VOID_TAGS.has(tag) || m[0].endsWith("/>")) continue;
if ((tag === "li" || tag === "p") && stack[stack.length - 1] === tag) stack.pop();
if (stack.length === 0) start = m.index;
stack.push(tag);
}
return blocks;
}
function buildCoverBlock(opts: {
title: string;
subtitle?: string;
author?: string;
date: string;
style: Style;
box: { contentWIn: number; contentHIn: number };
}): string {
const title = escapeHtml(opts.title);
const size = opts.style === "swiss" ? swissCoverTitle(opts.title, opts.box) : undefined;
const titleStyle = size ? ` style="font-size: ${size.fontPt}pt; padding-top: ${size.padTopIn}in;"` : "";
const subtitle = opts.subtitle ? escapeHtml(opts.subtitle) : "";
const author = opts.author ? escapeHtml(opts.author) : "";
const date = escapeHtml(opts.date);
return [
`<section class="cover">`,
` <h1 class="cover-title">${title}</h1>`,
` <h1 class="cover-title"${titleStyle}>${title}</h1>`,
subtitle ? ` <p class="cover-subtitle">${subtitle}</p>` : ``,
` <hr class="rule">`,
` <div class="cover-meta">`,
+187
View File
@@ -0,0 +1,187 @@
/**
* The "swiss" print style: make-pdf's default look since GSTA-849.
*
* A Swiss-poster layout in the Müller-Brockmann tradition, picked by the
* owner in blind A/B pairs over today's plain look ("plain" lives in
* print-css.ts and is untouched by this file). The page is split into two
* fields: a narrow left field that holds small red sub-headings, and a text
* column to its right. Section headings run the full width as white type on a
* black bar whose text starts at the column edge, so every heading, paragraph
* and list shares one left edge. Tables, code, figures and images use the full
* width. Readable line length comes from the field, never from wide margins.
*
* These rules are appended after the plain rules, so every structural rule
* (page boxes, chapter breaks, TOC leaders, footnotes, watermark, break-avoid)
* keeps a single source in print-css.ts.
*/
export type Style = "swiss" | "plain";
export const DEFAULT_STYLE: Style = "swiss";
export const STYLES: readonly Style[] = ["swiss", "plain"];
/** Width of the left field. The text column starts this far into the type area. */
export const SWISS_FIELD_IN = 1.9;
/** Widest text column, so long lines stay readable on legal and tabloid paper. */
const SWISS_COLUMN_MAX_IN = 5.1;
export const SWISS_MARGINS = { top: "0.7in", right: "0.75in", bottom: "0.85in", left: "0.75in" } as const;
export const SWISS_MARGIN_SHORTHAND = `${SWISS_MARGINS.top} ${SWISS_MARGINS.right} ${SWISS_MARGINS.bottom} ${SWISS_MARGINS.left}`;
const RED = "#e30613";
const INK = "#111";
const EXACT = "-webkit-print-color-adjust: exact; print-color-adjust: exact;";
export function swissRules(opts: { cover?: boolean; toc?: boolean } = {}): string {
return [
`:root { --swiss-field: ${SWISS_FIELD_IN}in; }`,
`body { font-size: 11pt; line-height: 15pt; }`,
`.chapter { display: flow-root; }`,
`.chapter > * { margin-left: var(--swiss-field); max-width: ${SWISS_COLUMN_MAX_IN}in; }`,
`.chapter > h1, .chapter > h2, .chapter > table, .chapter > pre, .chapter > figure, .chapter > .page-wide, .chapter > p:has(> img:only-child) { margin-left: 0; max-width: none; clear: left; }`,
// An h3 with text after it sits absolutely at the top of a wrapper that holds
// that text, so it always starts on the page where the text starts; the
// wrapper's min-height (set by render.ts from the heading's length) keeps a
// long sub-heading clear of the next block.
`.chapter > .swiss-keep { position: relative; clear: left; margin-left: 0; max-width: none; }`,
`.chapter > .swiss-keep > h3 { position: absolute; top: 0; left: 0; }`,
`.chapter > .swiss-keep > :not(h3) { margin-left: var(--swiss-field); max-width: ${SWISS_COLUMN_MAX_IN}in; }`,
`.chapter > hr { clear: left; height: 0; border: 0; border-top: 0.5pt solid ${INK}; margin: 12pt 0 12pt var(--swiss-field); }`,
`.chapter > h1 { font-size: 46pt; line-height: 46pt; letter-spacing: -0.035em; font-weight: 700; margin: 0 0 20pt; color: ${RED}; overflow-wrap: anywhere; }`,
`.chapter > h1 + p { font-size: 15pt; line-height: 20pt; margin-bottom: 18pt; }`,
`.chapter > h2 { ${EXACT} background: ${INK}; color: #fff; font-size: 17pt; line-height: 20pt; font-weight: 700; letter-spacing: -0.01em; margin: 24pt 0 12pt; padding: 7pt 10pt 8pt var(--swiss-field); overflow-wrap: anywhere; }`,
// A bar never ends a page: the block after it brings at least three of its lines along.
`.chapter > h2 + p, .chapter > h2 + blockquote, .chapter > h2 + ul > li:first-child, .chapter > h2 + ol > li:first-child { orphans: 3; }`,
`.chapter > h3, .chapter > .swiss-keep > h3 { float: left; clear: left; width: calc(var(--swiss-field) - 0.2in); margin: 1pt 0 0 0; break-inside: avoid; font-size: 10pt; line-height: 13pt; font-weight: 700; color: ${RED}; text-transform: none; letter-spacing: 0; overflow-wrap: anywhere; }`,
// Above a block that cannot split (code, a table, a figure, an image) the
// 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; }`,
`.chapter > .swiss-keep > h3 { float: none; }`,
`p { margin: 0 0 7.5pt; }`,
`ul, ol { padding-left: 14pt; margin: 0 0 7.5pt; }`,
`li { margin: 0; line-height: 15pt; }`,
`table { font-size: 9.5pt; line-height: 13pt; border-top: 2pt solid ${INK}; border-bottom: 2pt solid ${INK}; margin: 6pt 0 15pt; }`,
`th, td { padding: 4pt 10pt 4pt 0; border-bottom: 0.5pt solid #bbb; }`,
`th { color: ${RED}; border-bottom: 1pt solid ${INK}; }`,
`pre { background: none; border: 0; border-left: 3pt solid ${RED}; border-radius: 0; padding: 2pt 0 2pt 10pt; font-size: 9pt; line-height: 12pt; }`,
`blockquote { border-left: 3pt solid ${RED}; }`,
`figure.diagram, figure.diagram .diagram-caption { text-align: left; }`,
`figcaption, .diagram-caption { font-style: normal; font-weight: 700; color: ${RED}; font-size: 9pt; }`,
opts.cover ? coverRules() : "",
opts.toc ? `.toc h2 { ${EXACT} background: ${INK}; color: #fff; font-size: 17pt; line-height: 20pt; letter-spacing: -0.01em; text-transform: none; margin: 0 0 18pt; padding: 7pt 10pt 8pt var(--swiss-field); }` : "",
].filter(Boolean).join("\n");
}
function coverRules(): string {
return [
`.cover { ${EXACT} padding-top: 0; }`,
`.cover h1.cover-title { ${EXACT} background: ${INK}; color: #fff; font-size: 96pt; line-height: 0.92; letter-spacing: -0.045em; max-width: none; margin: 0 0 18pt; padding: 3.2in 18pt 22pt 18pt; overflow-wrap: anywhere; }`,
`.cover .cover-subtitle, .cover .cover-meta { margin-left: var(--swiss-field); }`,
`.cover hr.rule { ${EXACT} width: calc(var(--swiss-field) - 0.2in); border-top: 10pt solid ${RED}; margin: 0 0 14pt var(--swiss-field); }`,
`.cover .cover-meta { font-size: 13pt; line-height: 18pt; color: ${INK}; }`,
].join("\n");
}
/** Screen layer for `--to html`: room for the field on wide screens, one column on phones. */
export function swissScreenCss(): string {
return [
`@media screen {`,
` body { max-width: 7.5in; }`,
`}`,
`@media screen and (max-width: 48em) {`,
` .chapter > *, .chapter > hr, .cover .cover-subtitle, .cover .cover-meta, .cover hr.rule { margin-left: 0; max-width: none; }`,
` .chapter > h3, .chapter > .swiss-keep > h3 { float: none; position: static; width: auto; margin: 14pt 0 4pt; }`,
` .chapter > .swiss-keep { min-height: 0 !important; }`,
` .chapter > .swiss-keep > :not(h3) { margin-left: 0; max-width: none; }`,
` .chapter > h2, .toc h2 { padding-left: 10pt; }`,
` .cover h1.cover-title { font-size: 44pt !important; padding-top: 1in !important; }`,
`}`,
].join("\n");
}
/** Estimated lines an h3 takes in the left field (10pt bold, field width less 0.2in). */
export function swissFieldHeadingLines(text: string): number {
const widthPt = (SWISS_FIELD_IN - 0.2) * 72;
let lines = 1;
let x = 0;
for (const word of text.trim().split(/\s+/)) {
const w = Array.from(word).reduce((s, g) => s + glyphEm(g) * 1.06, 0) * 10;
const space = glyphEm(" ") * 10;
if (x > 0 && x + w > widthPt) { lines++; x = 0; }
if (w > widthPt) {
lines += Math.ceil(w / widthPt) - 1;
x = w % widthPt;
} else {
x += w;
}
x += space;
}
return lines;
}
const WIDE_CHAR = /[\u1100-\u115F\u2E80-\uA4CF\uAC00-\uD7A3\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFF60\uFFE0-\uFFE6]|[\u{1F000}-\u{1FAFF}]/u;
const COVER_SIZES_PT = [96, 84, 72, 60, 48];
const COVER_BLOCK_IN = 5.97;
const COVER_BELOW_BLOCK_IN = 3.48;
const COVER_BLOCK_MIN_IN = 1.5;
const SWISS_LETTER_BOX = { contentWIn: 7, contentHIn: 9.45 };
/** Estimated width of one glyph in ems of bold Helvetica with the cover's tight tracking. */
function glyphEm(ch: string): number {
if (WIDE_CHAR.test(ch)) return 1;
if (ch === " ") return 0.28;
if (/[A-Z0-9]/.test(ch)) return 0.66;
if (/[iljtf.,:;'!|]/.test(ch)) return 0.3;
if (/[mwMW]/.test(ch)) return 0.85;
return 0.55;
}
/** Lines a title takes at a size, or Infinity when one unbreakable word is wider than the block. */
function coverLines(title: string, sizePt: number, widthPt: number): number {
let lines = 1;
let x = 0;
for (const word of title.trim().split(/\s+/)) {
const glyphs = Array.from(word);
const wide = glyphs.some((g) => WIDE_CHAR.test(g));
if (wide) {
for (const g of glyphs) {
const w = glyphEm(g) * sizePt;
if (x + w > widthPt) { lines++; x = 0; }
x += w;
}
x += glyphEm(" ") * sizePt;
continue;
}
const w = glyphs.reduce((s, g) => s + glyphEm(g), 0) * sizePt;
if (w > widthPt) return Infinity;
if (x > 0 && x + w > widthPt) { lines++; x = 0; }
x += w + glyphEm(" ") * sizePt;
}
return lines;
}
/**
* Size the swiss cover title so the black block, the red bar and the meta
* always fit on page 1 of the actual page box (paper size less margins): the
* largest size whose estimated lines fit the block, and a top padding that
* shrinks as the title grows. The 48pt floor still wraps anything longer
* (overflow-wrap: anywhere), it never clips. The default box is swiss Letter.
*/
export function swissCoverTitle(
title: string,
box: { contentWIn: number; contentHIn: number } = SWISS_LETTER_BOX,
): { fontPt: number; padTopIn: number } {
const widthPt = box.contentWIn * 72 - 58;
const blockIn = Math.max(COVER_BLOCK_MIN_IN, Math.min(COVER_BLOCK_IN, box.contentHIn - COVER_BELOW_BLOCK_IN));
const maxTextPt = blockIn * 72 - 56;
const fontPt = COVER_SIZES_PT.find((s) => coverLines(title, s, widthPt) * s * 0.92 <= maxTextPt)
?? COVER_SIZES_PT[COVER_SIZES_PT.length - 1];
const lines = Math.min(coverLines(title, fontPt, widthPt), Math.max(1, Math.floor(maxTextPt / (fontPt * 0.92))));
const textIn = (lines * fontPt * 0.92) / 72;
const padTopIn = Math.round(Math.min(3.2, Math.max(0.4, blockIn - textIn - 0.31)) * 100) / 100;
return { fontPt, padTopIn };
}
+6
View File
@@ -5,6 +5,8 @@
*/
export type PageSize = "letter" | "a4" | "legal" | "tabloid";
export type { Style } from "./style-swiss";
import type { Style } from "./style-swiss";
export type FontMode = "sans"; // v1: Helvetica only. Future: "serif" | "custom".
/**
@@ -23,6 +25,9 @@ export interface GenerateOptions {
// docx — content-fidelity Word document (diagrams embedded as PNG)
to?: OutputFormat;
// Look: "swiss" (default, bold Swiss-poster layout) | "plain" (the look before it)
style?: Style;
// Page layout
margins?: string; // "1in" | "72pt" | "25mm" | "2.54cm"
marginTop?: string;
@@ -70,6 +75,7 @@ export interface PreviewOptions {
quiet?: boolean;
verbose?: boolean;
// Same render flags as generate so preview matches output
style?: Style;
cover?: boolean;
toc?: boolean;
watermark?: string;