@threepenny/md2pdf 2.5.0 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,7 +10,7 @@ Supports GitHub-flavored Markdown: tables, task lists, footnotes, emoji shortcod
10
10
 
11
11
  # Command-line tool (macOS)
12
12
 
13
- Markdown is rendered to HTML with [markdown-it](https://github.com/markdown-it/markdown-it) and printed to PDF by headless Chrome. Formulas (`$…$`, `$$…$$`, `\(…\)`, `\[…\]`, and environments such as `\begin{aligned}…\end{aligned}` or `\begin{align*}…\end{align*}` that start a block) are drawn with [KaTeX](https://katex.org), as on md2pdf.me; the HTML that `--html` writes also carries MathML for screen readers, which the PDF doesn't. Prices such as $5 and $10 stay text, even beside a formula. A displayed formula wider than the page shrinks until it fits, so a very long one prints small; split it over lines with `aligned` to keep it full size. A table wider than the page fits by breaking the long words in its widest columns, mid-word and without a hyphen, then its headers if that isn't enough, and every cell as a last resort. A formula in one of its cells first shrinks to as little as half size, before any word breaks, and smaller only if the table still doesn't fit. A table that fits prints as written.
13
+ Markdown is rendered to HTML with [markdown-it](https://github.com/markdown-it/markdown-it) and printed to PDF by headless Chrome. Formulas (`$…$`, `$$…$$`, `\(…\)`, `\[…\]`, and environments such as `\begin{aligned}…\end{aligned}` or `\begin{align*}…\end{align*}` that start a block) are drawn with [KaTeX](https://katex.org), as on md2pdf.me; the HTML that `--html` writes also carries MathML for screen readers, which the PDF doesn't. Prices such as $5 and $10 stay text, even beside a formula. A displayed formula wider than the page shrinks until it fits, so a very long one prints small; split it over lines with `aligned` to keep it full size. A table wider than the page fits by letting the inline code and links in its widest columns break after a slash, then before a dot or an underscore too, so `@threepenny/md2pdf/render` can break after `@threepenny/`. If that isn't enough, a formula in one of its cells shrinks, to as little as half size. If it still doesn't fit, the long words in those columns break mid-word, without a hyphen, then their headers, then every cell as a last resort; a formula shrinks further only if the table still doesn't fit. A table that fits prints as written.
14
14
 
15
15
  ## Install
16
16
 
@@ -93,11 +93,12 @@ Register it in `STYLES` and add its page margin to `pageMargins` in `lib/styles.
93
93
  A style can bundle fonts, so it looks the same on every computer:
94
94
 
95
95
  - Put each family in `styles/fonts/<family>/`: its `.woff2` files (the smallest format, and every current browser reads it) and its `OFL.txt`, and nothing else. Only fonts under the SIL Open Font License, which allows bundling. Fonts are the only files a style bundles.
96
+ - Check whether the font reserves its name, in the copyright lines at the top of upstream's `OFL.txt` or in the font's own copyright notice; a Fontsource or Google Fonts copy of `OFL.txt` can leave the name out. A modified font can't use a reserved name, and subsetting counts as modifying, so subset files like Fontsource's can't be bundled under it. Bundle upstream's own `.woff2` files, unchanged, and add the family's folder name to `RESERVED_NAME_FONTS` in `test/run.js` with the reason; or pick another font. IM Fell English is listed there for another reason: its files reserve the name, but Google Fonts' licence for them doesn't, and John decided that's the one that counts (#37).
96
97
  - Declare them in the on-screen file with `@font-face`, relative to it: `src: url("fonts/<family>/<file>.woff2") format("woff2")`, with a `font-weight` and `font-style` for each face. The print file can use them without declaring them again.
97
98
  - Name each family `md2pdf <Name>`, so it can't collide with a font on a page that embeds the style. Don't use `local()`, which would bring back the differences between computers, or `font-display: optional`, which lets the browser skip the font.
98
99
  - Set the bundled family through the font variables, e.g. `--md2pdf-font: "md2pdf Andika", sans-serif`, so they can still be overridden.
99
100
 
100
- The CLI resolves a stylesheet's relative `url()`s against the stylesheet, and loads every declared font before printing, including one used only in a page header. `npm test` checks the file layout, the licence, the family names, `local()` and `font-display`.
101
+ The CLI resolves a stylesheet's relative `url()`s against the stylesheet, and loads every declared font before printing, including one used only in a page header. `npm test` checks the file layout, the licence and any reserved font name, the family names, `local()` and `font-display`.
101
102
 
102
103
  End the on-screen file with the rule the other styles end with, which turns off ligatures when Safari prints: Safari's PDFs copy a ligature as the wrong characters ("The" pastes as "!e"), while Chrome's, the CLI's and on-screen text are unaffected. It belongs in the on-screen file, not the print file, because a page that embeds a style prints without the print file. On a Mac with `swiftc`, `npm test` prints every style through WebKit and checks the copied text.
103
104
 
package/bin/md2pdf.js CHANGED
@@ -223,6 +223,45 @@ for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) {
223
223
  });
224
224
  }
225
225
 
226
+ // What went wrong and what to do on the first line, the only one the Quick Action's notification shows,
227
+ // so it never suggests setting CHROME_PATH, which a Quick Action can't see. The Chrome that ran and its
228
+ // own output go below.
229
+ function chromeFailed(chrome, first, { output = '', suggestChromePath = true } = {}) {
230
+ const lines = [first];
231
+ if (suggestChromePath) lines.push(' If it keeps failing, set CHROME_PATH to a different Chrome-based browser.');
232
+ lines.push(` Chrome: ${chrome}`);
233
+ if (output.trim()) lines.push(" Chrome's output:", ...output.trim().split('\n').map((l) => ` ${l}`));
234
+ return new Error(lines.join('\n'));
235
+ }
236
+
237
+ const TRY_AGAIN = 'It may be updating; try again in a moment.';
238
+
239
+ function cantStart(chrome, err) {
240
+ if (!process.env.CHROME_PATH) return chromeFailed(chrome, `Chrome couldn't start (${err.code ?? err.message}). ${TRY_AGAIN}`);
241
+ let folder = false;
242
+ try {
243
+ folder = statSync(chrome).isDirectory();
244
+ } catch {
245
+ // Missing, or in a folder md2pdf can't read: not a folder it can name.
246
+ }
247
+ if (folder) {
248
+ return chromeFailed(
249
+ chrome,
250
+ `Chrome couldn't start: CHROME_PATH names a folder (${err.code ?? err.message}). ` +
251
+ 'For an app, give the program inside it, such as /Applications/Google Chrome.app/Contents/MacOS/Google Chrome.',
252
+ { suggestChromePath: false },
253
+ );
254
+ }
255
+ const why = {
256
+ ENOENT: "there's no file at CHROME_PATH",
257
+ ENOTDIR: "there's no file at CHROME_PATH",
258
+ EACCES: "the file at CHROME_PATH can't be run",
259
+ }[err.code] ?? "the file at CHROME_PATH didn't run";
260
+ return chromeFailed(chrome, `Chrome couldn't start: ${why} (${err.code ?? err.message}). Check that it names a Chrome-based browser.`, {
261
+ suggestChromePath: false,
262
+ });
263
+ }
264
+
226
265
  function runChrome(chrome, htmlPath, pdfPath) {
227
266
  // A throwaway profile keeps headless Chrome separate from any Chrome you have open.
228
267
  const profile = makeTempDir('md2pdf-chrome-');
@@ -239,20 +278,32 @@ function runChrome(chrome, htmlPath, pdfPath) {
239
278
  pathToFileURL(htmlPath).href,
240
279
  ];
241
280
  return new Promise((resolvePromise, reject) => {
242
- const proc = (chromeProc = spawn(chrome, args, { stdio: ['ignore', 'ignore', 'pipe'] }));
281
+ let proc;
282
+ try {
283
+ proc = chromeProc = spawn(chrome, args, { stdio: ['ignore', 'ignore', 'pipe'] });
284
+ } catch (err) {
285
+ // Most failures to start arrive as 'error' below; some (ENOTDIR, say) are thrown here.
286
+ removeTempDir(profile);
287
+ reject(cantStart(chrome, err));
288
+ return;
289
+ }
243
290
  let stderr = '';
244
291
  proc.stderr.on('data', (d) => (stderr += d));
245
292
  // A Chrome that fails to start emits 'error' first, and main() may exit before its 'close' arrives.
246
293
  proc.on('error', (err) => {
247
294
  if (chromeProc === proc) chromeProc = null;
248
295
  removeTempDir(profile);
249
- reject(err);
296
+ reject(cantStart(chrome, err));
250
297
  });
251
- proc.on('close', (code) => {
298
+ proc.on('close', (code, signal) => {
252
299
  if (chromeProc === proc) chromeProc = null;
253
300
  removeTempDir(profile);
254
301
  if (code === 0 && existsSync(pdfPath)) resolvePromise();
255
- else reject(new Error(`Chrome failed (exit ${code}):\n${stderr.trim()}`));
302
+ else if (code === 0) reject(chromeFailed(chrome, `Chrome quit without printing. ${TRY_AGAIN}`, { output: stderr }));
303
+ else {
304
+ const how = signal ? `stopped by ${signal}` : `exit ${code}`;
305
+ reject(chromeFailed(chrome, `Chrome quit before printing (${how}). ${TRY_AGAIN}`, { output: stderr }));
306
+ }
256
307
  });
257
308
  });
258
309
  }
@@ -369,7 +420,13 @@ async function main() {
369
420
  process.exit(2);
370
421
  }
371
422
 
372
- const chrome = findChrome();
423
+ let chrome;
424
+ try {
425
+ chrome = findChrome();
426
+ } catch (err) {
427
+ console.error(`md2pdf: ${err.message}`);
428
+ process.exit(1);
429
+ }
373
430
  if (!katex) console.error(`md2pdf: KaTeX isn't installed, so formulas print as their source; run ${join(ROOT, 'install.sh')} again`);
374
431
  let failed = 0;
375
432
  const written = new Map();
package/lib/fit.js CHANGED
@@ -47,13 +47,17 @@ export function fitFormulas(root = document) {
47
47
  // Runs in the browser after fitFormulas, which resets every displayed formula's size, once the page is
48
48
  // rendered and its fonts have loaded. A table's width depends on the column it ends up in, so it lays the
49
49
  // page out at the printed column's width, read from the page's @page rules, while it measures. Then, for a
50
- // table that runs past its box:
51
- // 1. A formula in one of its cells shrinks, down to half size, keeping every word whole.
52
- // 2. If that isn't enough, the body cells of its columns whose longest word is longer than 8 characters
53
- // break their words, widest column first, measuring after each, until it fits. A break that doesn't
54
- // narrow its column is taken back. If the table still doesn't fit, those columns' headers break too,
55
- // all at once, so the broken columns share the width; then every cell.
56
- // 3. Its formulas then grow back as large as fits, or shrink further if they must.
50
+ // table that runs past its box, working on the columns whose longest word is longer than 8 characters,
51
+ // widest column first, measuring after each, until it fits:
52
+ // 1. The code and links in their body cells, then in their headers, may break after a slash; if that
53
+ // isn't enough, before a dot or an underscore too. A break that doesn't narrow its column is taken back.
54
+ // 2. If that isn't enough, a formula in one of its cells shrinks, down to half size.
55
+ // 3. If that isn't enough, those columns' body cells break their words anywhere, still at a slash, a dot
56
+ // or an underscore where they can. A break that doesn't narrow its column is taken back. If the table
57
+ // still doesn't fit, those columns' headers break too, all at once, so the broken columns share the
58
+ // width; then every cell.
59
+ // 4. Its formulas then grow back as large as fits, or shrink further if they must. Code or a link no
60
+ // wider than its column's longest unbroken piece is kept whole, unless its cell breaks anywhere.
57
61
  // A table that fits isn't written to, so it prints as it did. If the printed width can't be read, nothing
58
62
  // changes. Running it again is harmless.
59
63
  //
@@ -71,6 +75,11 @@ export function fitTables(root = document) {
71
75
  restore(el, el.getAttribute('style') || null);
72
76
  el.removeAttribute(FIT);
73
77
  };
78
+ for (const wbr of root.querySelectorAll(`wbr[${FIT}]`)) {
79
+ const parent = wbr.parentNode;
80
+ wbr.remove();
81
+ parent.normalize();
82
+ }
74
83
  for (const el of root.querySelectorAll(`[${FIT}]`)) unset(el, 'overflow-wrap', 'font-size');
75
84
  const tables = [...root.querySelectorAll('table')];
76
85
  if (!tables.length) return;
@@ -158,7 +167,7 @@ export function fitTables(root = document) {
158
167
  if (!table.parentElement || !(past() > 1)) return;
159
168
  const fits = () => past() <= 0;
160
169
 
161
- // The table's own cells, by column. A cell that spans columns is broken only with every cell (step 2).
170
+ // The table's own cells, by column. A cell that spans columns is broken only with every cell (step 3).
162
171
  const columns = [];
163
172
  const taken = [];
164
173
  [...table.rows].forEach((row, r) => {
@@ -193,28 +202,137 @@ export function fitTables(root = document) {
193
202
  span.remove();
194
203
  return width;
195
204
  };
205
+ // The code and links in a cell, each with its text: the outermost of each, and none in a formula or in
206
+ // a table inside the cell.
207
+ const spans = (cell) =>
208
+ [...cell.querySelectorAll('code, a')].filter(
209
+ (el) => el.closest('td, th') === cell && !el.parentElement.closest('code, a, .katex') && !el.closest('.katex'),
210
+ );
211
+ // Lets `el`'s text break after a slash, and with `dots`, before a dot or an underscore, with a <wbr>,
212
+ // which prints nothing. Never inside the characters its text starts or ends with (`@scope`, `.hidden`,
213
+ // `~/`, `../`, `__init__`, `etc.`), within a run (`//`, `...`), or at a dot between digits (`2.5.0`).
214
+ // Returns the <wbr>s it adds.
215
+ const LEAD = /^[@.~/_]*/;
216
+ const soften = (el, dots) => {
217
+ const texts = [];
218
+ const have = new Set();
219
+ let text = '';
220
+ const walk = (node) => {
221
+ for (const child of node.childNodes) {
222
+ if (child.nodeType === Node.TEXT_NODE) {
223
+ texts.push([child, text.length]);
224
+ text += child.data;
225
+ } else if (child.localName === 'wbr') {
226
+ have.add(text.length);
227
+ } else if (child.nodeType === Node.ELEMENT_NODE && !child.classList.contains('katex')) {
228
+ walk(child);
229
+ }
230
+ }
231
+ };
232
+ walk(el);
233
+ const start = LEAD.exec(text)[0].length;
234
+ const end = text.search(/[._]*$/);
235
+ const at = [];
236
+ for (let i = start + 1; i < end; i++) {
237
+ const [before, here] = [text[i - 1], text[i]];
238
+ if (before === '/' && here !== '/' && !/\s/.test(here)) at.push(i);
239
+ else if (dots && /[._]/.test(here) && !/[._/\s]/.test(before)) {
240
+ const next = text.slice(i).match(/^[._]+(.)/)?.[1];
241
+ if (next && !/\s/.test(next) && !(here === '.' && /\d/.test(before) && /\d/.test(next))) at.push(i);
242
+ }
243
+ }
244
+ const added = [];
245
+ for (const i of at.reverse()) {
246
+ if (have.has(i)) continue;
247
+ const [node, offset] = texts.findLast(([, offset]) => offset < i) ?? [];
248
+ if (!node || i > offset + node.data.length) continue;
249
+ const wbr = document.createElement('wbr');
250
+ wbr.setAttribute(FIT, '');
251
+ if (i < offset + node.data.length) node.splitText(i - offset);
252
+ node.after(wbr);
253
+ added.push(wbr);
254
+ }
255
+ return added;
256
+ };
257
+ const softenAll = (cells, dots) => cells.flatMap((cell) => spans(cell).flatMap((el) => soften(el, dots)));
258
+ // Takes back <wbr>s, keeping where each went, so they can be put back.
259
+ const removed = [];
260
+ const takeBack = (wbrs) => {
261
+ for (const wbr of wbrs) {
262
+ removed.push(wbr.parentNode);
263
+ wbr.remove();
264
+ }
265
+ };
196
266
  const mark = (cell) => {
197
267
  cell.style.overflowWrap = 'anywhere';
198
268
  cell.setAttribute(FIT, '');
269
+ return softenAll([cell], true);
199
270
  };
200
271
  const long = (widths, c) => columns[c]?.length && widths[c] > eight(columns[c][0]);
201
272
  const body = (c) => columns[c].filter((cell) => cell.localName === 'td');
202
- // Breaks the body cells of the long columns, widest first, until the table fits. Returns whether it does.
203
- const breakBodies = () => {
273
+ const head = (c) => columns[c].filter((cell) => cell.localName === 'th');
274
+ // Applies `step` to some of the cells of the long columns, widest first, until the table fits. `step`
275
+ // returns a function that takes it back, which runs if it doesn't narrow its column. Returns whether
276
+ // the table fits.
277
+ const widestFirst = (cellsOf, step) => {
204
278
  const tried = new Set();
205
279
  while (!fits()) {
206
280
  const widths = narrowest();
207
281
  let best = -1;
208
282
  widths.forEach((w, c) => {
209
- if (!tried.has(c) && long(widths, c) && body(c).length && (best < 0 || w > widths[best])) best = c;
283
+ if (!tried.has(c) && long(widths, c) && cellsOf(c).length && (best < 0 || w > widths[best])) best = c;
210
284
  });
211
285
  if (best < 0) return false;
212
286
  tried.add(best);
213
- body(best).forEach(mark);
214
- if (narrowest()[best] >= widths[best] - 0.5) for (const cell of body(best)) unset(cell, 'overflow-wrap');
287
+ const undo = step(cellsOf(best));
288
+ if (undo && narrowest()[best] >= widths[best] - 0.5) undo();
215
289
  }
216
290
  return true;
217
291
  };
292
+ // Breaks the code and links of the long columns at slashes, then at dots and underscores too: body
293
+ // cells, then headers. Returns whether the table fits.
294
+ const breakNaturally = () =>
295
+ columns.some((cells) => cells?.some((cell) => spans(cell).length)) &&
296
+ [false, true].some((dots) =>
297
+ [body, head].some((cellsOf) =>
298
+ widestFirst(cellsOf, (cells) => {
299
+ const wbrs = softenAll(cells, dots);
300
+ return wbrs.length && (() => takeBack(wbrs));
301
+ }),
302
+ ),
303
+ );
304
+ // Breaks the body cells of the long columns anywhere. Returns whether the table fits.
305
+ const breakBodies = () =>
306
+ widestFirst(body, (cells) => {
307
+ const wbrs = cells.flatMap(mark);
308
+ return () => {
309
+ takeBack(wbrs);
310
+ for (const cell of cells) unset(cell, 'overflow-wrap');
311
+ };
312
+ });
313
+ // Keeps whole, one at a time, the code and links whose break points don't narrow their column at its
314
+ // narrowest: those no wider than its longest unbroken piece. A <wbr> doesn't change a column's widest
315
+ // either, so no column's width changes. A cell that breaks anywhere keeps its break points, which it
316
+ // breaks at first.
317
+ const keepWhole = () => {
318
+ const widths = narrowest();
319
+ const softened = new Map();
320
+ for (const wbr of table.querySelectorAll(`wbr[${FIT}]`)) {
321
+ const cell = wbr.closest('td, th');
322
+ if (cell.closest('table') !== table || cell.hasAttribute(FIT)) continue;
323
+ const c = columns.findIndex((cells) => cells?.includes(cell));
324
+ if (c >= 0) softened.set(spans(cell).find((el) => el.contains(wbr)), c);
325
+ }
326
+ for (const [el, c] of softened) {
327
+ const wbrs = [...el.querySelectorAll(`wbr[${FIT}]`)];
328
+ const places = wbrs.map((wbr) => wbr.previousSibling);
329
+ takeBack(wbrs);
330
+ if (narrowest()[c] > widths[c] + 0.5) {
331
+ wbrs.forEach((wbr, i) => places[i].after(wbr));
332
+ removed.splice(removed.length - wbrs.length);
333
+ }
334
+ }
335
+ };
218
336
 
219
337
  // Its formulas: displayed ones, and inline ones with a part longer than 8 characters that can't wrap.
220
338
  const formulas = [...table.querySelectorAll(':is(td, th) .katex')]
@@ -248,19 +366,28 @@ export function fitTables(root = document) {
248
366
  scale(small);
249
367
  };
250
368
 
251
- if (formulas.length) {
252
- scale(0.5);
369
+ const sizeFormulas = () => {
370
+ if (!formulas.length) return;
253
371
  if (fits()) return largest(0.5, 1);
254
- }
255
- if (!breakBodies()) {
256
- const widths = narrowest();
257
- columns.forEach((cells, c) => long(widths, c) && cells.forEach(mark));
258
- if (!fits()) for (const row of table.rows) for (const cell of row.cells) mark(cell);
259
- }
260
- if (!formulas.length) return;
261
- if (fits()) return largest(0.5, 1);
262
- scale(0.05);
263
- if (!fits()) scale(0.5);
264
- else largest(0.05, 0.5);
372
+ scale(0.05);
373
+ if (!fits()) scale(0.5);
374
+ else largest(0.05, 0.5);
375
+ };
376
+ const place = () => {
377
+ if (breakNaturally()) return;
378
+ if (formulas.length) {
379
+ scale(0.5);
380
+ if (fits()) return largest(0.5, 1);
381
+ }
382
+ if (!breakBodies()) {
383
+ const widths = narrowest();
384
+ columns.forEach((cells, c) => long(widths, c) && cells.forEach(mark));
385
+ if (!fits()) for (const row of table.rows) for (const cell of row.cells) mark(cell);
386
+ }
387
+ sizeFormulas();
388
+ };
389
+ place();
390
+ keepWhole();
391
+ for (const parent of new Set(removed)) parent.normalize();
265
392
  }
266
393
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@threepenny/md2pdf",
3
- "version": "2.5.0",
3
+ "version": "2.6.0",
4
4
  "description": "Markdown to beautifully styled PDF: the renderer and macOS CLI behind md2pdf.me",
5
5
  "type": "module",
6
6
  "license": "MIT",