@threepenny/md2pdf 2.4.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/lib/fit.js ADDED
@@ -0,0 +1,393 @@
1
+ // Shrinks each displayed formula under `root` that is wider than its column until it fits, on screen and
2
+ // in print. KaTeX draws a displayed formula as one line that never wraps, so a long one runs off the page.
3
+ //
4
+ // Runs in the browser, once the page is rendered and its fonts have loaded. It measures each formula's
5
+ // width in proportion to its font size, which doesn't depend on the column, and sizes it with container
6
+ // query units. So the browser fits it to whatever column it ends up in, including the printed page's,
7
+ // which a script can't measure: when printing starts, the page is still laid out at screen width. A
8
+ // formula that fits keeps its size. Running it again is harmless.
9
+ //
10
+ // Self-contained, so the CLI can put its source in the page. md2pdf.me fits formulas its own way, with
11
+ // the page's width, which its preview knows.
12
+ export function fitFormulas(root = document) {
13
+ for (const formula of root.querySelectorAll('eqn > .katex-display > .katex')) {
14
+ const display = formula.parentElement;
15
+ const section = display.parentElement.parentElement;
16
+ if (!section) continue;
17
+ formula.style.fontSize = '';
18
+ display.style.containerType = '';
19
+ display.style.width = 'max-content';
20
+ // A \tag number sits at the column's edge, outside the formula's own width. The formula is centred,
21
+ // so clearing the number takes its width on both sides.
22
+ const tag = formula.querySelector('.katex-html > .katex-tag');
23
+ const width = formula.getBoundingClientRect().width + 2 * (tag?.getBoundingClientRect().width ?? 0);
24
+ display.style.width = '';
25
+ const size = parseFloat(getComputedStyle(formula).fontSize);
26
+ const parentSize = parseFloat(getComputedStyle(display).fontSize);
27
+ if (!(width > 0 && size > 0 && parentSize > 0)) continue;
28
+ // The container is the formula's own block, whose margins collapse with the text around it as before:
29
+ // a container's children's margins don't. A container sizes without its content, so one in a box that
30
+ // sizes to its content, such as a table cell, would collapse it. Leave such a formula as it was.
31
+ const before = section.getBoundingClientRect().width;
32
+ display.style.containerType = 'inline-size';
33
+ if (section.getBoundingClientRect().width !== before) {
34
+ display.style.containerType = '';
35
+ continue;
36
+ }
37
+ // Only the formula's own text scales, so the space above and below it stays the style's. Glyphs land on
38
+ // rounded positions, so a formula's width doesn't scale exactly with its size: 99% of the column leaves room.
39
+ formula.style.fontSize = `min(${size / parentSize}em, calc(99cqi * ${size / width}))`;
40
+ }
41
+ }
42
+
43
+ // Fits each table under `root` that runs past its box on the printed page, so every column prints. KaTeX's
44
+ // formulas never wrap, and a cell can't be narrower than its longest word, so a table of long words or a
45
+ // long formula can be wider than the page.
46
+ //
47
+ // Runs in the browser after fitFormulas, which resets every displayed formula's size, once the page is
48
+ // rendered and its fonts have loaded. A table's width depends on the column it ends up in, so it lays the
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, 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.
61
+ // A table that fits isn't written to, so it prints as it did. If the printed width can't be read, nothing
62
+ // changes. Running it again is harmless.
63
+ //
64
+ // Self-contained, so the CLI can put its source in the page.
65
+ export function fitTables(root = document) {
66
+ const FIT = 'data-md2pdf-fit';
67
+ // Puts back an element's style attribute as it was. Chrome keeps an empty one after a script has
68
+ // written its style, even through removeAttribute, unless the attribute is set first.
69
+ const restore = (el, style) => {
70
+ el.setAttribute('style', style ?? '');
71
+ if (style === null) el.removeAttribute('style');
72
+ };
73
+ const unset = (el, ...properties) => {
74
+ for (const property of properties) el.style.removeProperty(property);
75
+ restore(el, el.getAttribute('style') || null);
76
+ el.removeAttribute(FIT);
77
+ };
78
+ for (const wbr of root.querySelectorAll(`wbr[${FIT}]`)) {
79
+ const parent = wbr.parentNode;
80
+ wbr.remove();
81
+ parent.normalize();
82
+ }
83
+ for (const el of root.querySelectorAll(`[${FIT}]`)) unset(el, 'overflow-wrap', 'font-size');
84
+ const tables = [...root.querySelectorAll('table')];
85
+ if (!tables.length) return;
86
+
87
+ // The printed page's width and side margins: the last rule without a page selector that sets each.
88
+ const page = {};
89
+ const read = (rules) => {
90
+ for (const rule of rules) {
91
+ if (rule instanceof CSSPageRule) {
92
+ if (rule.selectorText) continue;
93
+ for (const name of ['size', 'margin-left', 'margin-right']) {
94
+ const value = rule.style.getPropertyValue(name);
95
+ if (value) page[name] = value;
96
+ }
97
+ } else if (rule instanceof CSSImportRule) {
98
+ if (!rule.media.length || [...rule.media].some((m) => /\b(all|print)\b/i.test(m) && !/\bnot\b/i.test(m))) {
99
+ try {
100
+ read(rule.styleSheet.cssRules);
101
+ } catch {
102
+ // A stylesheet from another origin can't be read.
103
+ }
104
+ }
105
+ } else if (rule instanceof CSSMediaRule) {
106
+ if ([...rule.media].some((m) => /\b(all|print)\b/i.test(m) && !/\bnot\b/i.test(m))) read(rule.cssRules);
107
+ } else if (rule.cssRules && !(rule instanceof CSSStyleRule)) {
108
+ read(rule.cssRules);
109
+ }
110
+ }
111
+ };
112
+ for (const sheet of document.styleSheets) {
113
+ try {
114
+ read(sheet.cssRules);
115
+ } catch {
116
+ // As above.
117
+ }
118
+ }
119
+ const html = document.documentElement;
120
+ const box = document.createElement('div');
121
+ box.style.cssText = 'position: absolute; visibility: hidden; height: 0; padding: 0; border: 0';
122
+ const probe = box.cloneNode();
123
+ box.append(probe);
124
+ html.append(box);
125
+ const px = (length) => {
126
+ if (!length || /v(w|h|min|max)$/i.test(length)) return NaN;
127
+ probe.style.width = '';
128
+ probe.style.width = length;
129
+ return probe.style.width ? probe.getBoundingClientRect().width : NaN;
130
+ };
131
+ const PAPER = {
132
+ a5: ['148mm', '210mm'], a4: ['210mm', '297mm'], a3: ['297mm', '420mm'], b5: ['176mm', '250mm'],
133
+ b4: ['250mm', '353mm'], 'jis-b5': ['182mm', '257mm'], 'jis-b4': ['257mm', '364mm'],
134
+ letter: ['8.5in', '11in'], legal: ['8.5in', '14in'], ledger: ['11in', '17in'],
135
+ };
136
+ // Chrome prints `auto`, or an orientation alone, on Letter paper.
137
+ const words = (page.size || 'auto').trim().toLowerCase().split(/\s+/);
138
+ const paper = PAPER[words.find((word) => PAPER[word]) ?? 'letter'];
139
+ const width = /^[\d.+]/.test(words[0]) ? px(words[0]) : px(words.includes('landscape') ? paper[1] : paper[0]);
140
+ // A margin in % is a share of the page's width.
141
+ box.style.width = `${width}px`;
142
+ const column = width - px(page['margin-left']) - px(page['margin-right']);
143
+ box.remove();
144
+ if (!(column > 0)) return;
145
+
146
+ const style = html.getAttribute('style');
147
+ html.style.width = `${column}px`;
148
+ try {
149
+ for (const table of tables) fit(table);
150
+ } finally {
151
+ restore(html, style);
152
+ }
153
+
154
+ function fit(table) {
155
+ // How far the table reaches past its box.
156
+ const past = () => {
157
+ const parent = table.parentElement;
158
+ const s = getComputedStyle(parent);
159
+ const edge = parent.getBoundingClientRect().right - parseFloat(s.borderRightWidth) - parseFloat(s.paddingRight);
160
+ let right = table.getBoundingClientRect().right;
161
+ for (const row of table.rows) right = Math.max(right, row.getBoundingClientRect().right);
162
+ return right - edge;
163
+ };
164
+ // A table is fitted when it runs past its box by more than a pixel: less only reaches into the page
165
+ // margin, and the slack keeps a rounding difference from the printed page's width from changing a table
166
+ // that fits. Fitted, it stays inside its box.
167
+ if (!table.parentElement || !(past() > 1)) return;
168
+ const fits = () => past() <= 0;
169
+
170
+ // The table's own cells, by column. A cell that spans columns is broken only with every cell (step 3).
171
+ const columns = [];
172
+ const taken = [];
173
+ [...table.rows].forEach((row, r) => {
174
+ let c = 0;
175
+ for (const cell of row.cells) {
176
+ while (taken[r]?.[c]) c++;
177
+ for (let i = 0; i < (cell.rowSpan || 1); i++) {
178
+ for (let j = 0; j < cell.colSpan; j++) (taken[r + i] ??= [])[c + j] = true;
179
+ }
180
+ if (cell.colSpan === 1) (columns[c] ??= []).push(cell);
181
+ c += cell.colSpan;
182
+ }
183
+ });
184
+ // Each column's width with every cell at its narrowest, as wide as its longest word or formula.
185
+ const narrowest = () => {
186
+ const before = table.getAttribute('style');
187
+ table.style.width = 'min-content';
188
+ const widths = columns.map((cells) => {
189
+ if (!cells?.length) return 0;
190
+ const s = getComputedStyle(cells[0]);
191
+ const edges = ['paddingLeft', 'paddingRight', 'borderLeftWidth', 'borderRightWidth'].reduce((sum, p) => sum + parseFloat(s[p]), 0);
192
+ return cells[0].getBoundingClientRect().width - edges;
193
+ });
194
+ restore(table, before);
195
+ return widths;
196
+ };
197
+ const eight = (cell) => {
198
+ const span = document.createElement('span');
199
+ span.style.cssText = 'position: absolute; visibility: hidden; width: 8ch; padding: 0; border: 0';
200
+ cell.append(span);
201
+ const width = span.getBoundingClientRect().width;
202
+ span.remove();
203
+ return width;
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
+ };
266
+ const mark = (cell) => {
267
+ cell.style.overflowWrap = 'anywhere';
268
+ cell.setAttribute(FIT, '');
269
+ return softenAll([cell], true);
270
+ };
271
+ const long = (widths, c) => columns[c]?.length && widths[c] > eight(columns[c][0]);
272
+ const body = (c) => columns[c].filter((cell) => cell.localName === 'td');
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) => {
278
+ const tried = new Set();
279
+ while (!fits()) {
280
+ const widths = narrowest();
281
+ let best = -1;
282
+ widths.forEach((w, c) => {
283
+ if (!tried.has(c) && long(widths, c) && cellsOf(c).length && (best < 0 || w > widths[best])) best = c;
284
+ });
285
+ if (best < 0) return false;
286
+ tried.add(best);
287
+ const undo = step(cellsOf(best));
288
+ if (undo && narrowest()[best] >= widths[best] - 0.5) undo();
289
+ }
290
+ return true;
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
+ };
336
+
337
+ // Its formulas: displayed ones, and inline ones with a part longer than 8 characters that can't wrap.
338
+ const formulas = [...table.querySelectorAll(':is(td, th) .katex')]
339
+ .filter((formula) => formula.closest('table') === table)
340
+ .filter((formula) => {
341
+ if (formula.parentElement.classList.contains('katex-display')) return true;
342
+ const parts = [...formula.querySelectorAll(':scope > .katex-html > .base')];
343
+ return parts.some((part) => part.getBoundingClientRect().width > eight(formula.closest('td, th')));
344
+ })
345
+ .map((formula) => [formula, parseFloat(getComputedStyle(formula).fontSize) / parseFloat(getComputedStyle(formula.parentElement).fontSize)]);
346
+ const scale = (factor) => {
347
+ for (const [formula, size] of formulas) {
348
+ formula.style.fontSize = `${size * factor}em`;
349
+ formula.setAttribute(FIT, '');
350
+ }
351
+ };
352
+ // The largest size from `small`, at which the table fits, up to `large`. At full size, they're left as
353
+ // they were.
354
+ const largest = (small, large) => {
355
+ scale(large);
356
+ if (fits()) {
357
+ if (large === 1) for (const [formula] of formulas) unset(formula, 'font-size');
358
+ return;
359
+ }
360
+ while (large - small > 0.01) {
361
+ const middle = (small + large) / 2;
362
+ scale(middle);
363
+ if (!fits()) large = middle;
364
+ else small = middle;
365
+ }
366
+ scale(small);
367
+ };
368
+
369
+ const sizeFormulas = () => {
370
+ if (!formulas.length) return;
371
+ if (fits()) return largest(0.5, 1);
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();
392
+ }
393
+ }
package/lib/math.js CHANGED
@@ -1,11 +1,12 @@
1
1
  // TeX math, rendered by KaTeX: $…$ and \(…\) inline, $$…$$, \[…\] and \begin{env}…\end{env} displayed,
2
- // and a number in parentheses after a displayed formula, `$$E = mc^2$$ (1)`. The syntax is that of
2
+ // and a number in parentheses after a displayed formula on its last line, `$$E = mc^2$$ (1)`. The syntax is that of
3
3
  // markdown-it-texmath 1.0.0 with its brackets, dollars and beg_end delimiters and outerSpace, except that
4
- // a $ formula may also start or end beside a line break and can't hold an unescaped $, and that starred
5
- // environments such as align* start a block too. texmath searches for the closing delimiter from every
6
- // opening one, which takes quadratic time on a line of openers, so these rules find closers through
7
- // tables built in one pass over the source. A displayed formula also ends inside the blockquote it starts
8
- // in; texmath's could run on past it, so that each of a run of quotes echoed the rest of the document.
4
+ // a $ formula may also start or end beside a line break, start after ( * or _, or end before ) * _ ? ! or :,
5
+ // and can't hold an unescaped $, and that starred environments such as align* start a block too. texmath
6
+ // searches for the closing delimiter from every opening one, which takes quadratic time on a line of
7
+ // openers, so these rules find closers through tables built in one pass over the source. A displayed
8
+ // formula also ends inside the blockquote it starts in; texmath's could run on past it, so that each of a
9
+ // run of quotes echoed the rest of the document.
9
10
 
10
11
  import { first, nextWhere } from './scan.js';
11
12
 
@@ -56,10 +57,10 @@ const nonSpace = (s, i) => !SPACE.test(s[i]);
56
57
  const bracketNumberStop = (s, i) => ')$\r\n'.includes(s[i]);
57
58
  const dollarNumberStop = (s, i) => s[i] === ')' || SPACE.test(s[i]);
58
59
 
59
- // Whether the $ at `at` opens or closes a formula: whitespace or the paragraph's edge is outside it,
60
- // or after a closing $, punctuation that ends a clause.
61
- const dollarPre = (src, at) => at === 0 || SPACE.test(src[at - 1]);
62
- const dollarPost = (src, at) => at + 1 >= src.length || /[\s.,;]/.test(src[at + 1]);
60
+ // Whether the $ at `at` opens or closes a formula: whitespace or the paragraph's edge is outside it, or
61
+ // emphasis or a parenthesis, or after a closing $, punctuation that ends a clause.
62
+ const dollarPre = (src, at) => at === 0 || /[\s(*_]/.test(src[at - 1]);
63
+ const dollarPost = (src, at) => at + 1 >= src.length || /[\s.,;:?!)*_]/.test(src[at + 1]);
63
64
  // texmath's own test for $$ inside a paragraph, which outerSpace doesn't reach: no backslash or digit
64
65
  // before the opening $$, and no digit after the closing one.
65
66
  const isDigit = (c) => c >= '0' && c <= '9';
@@ -131,10 +132,14 @@ function inline(state, silent) {
131
132
  return true;
132
133
  }
133
134
 
134
- // An equation number after a displayed formula that ends at `from`: whitespace, then (number).
135
+ // An equation number after a displayed formula that ends at `from`: spaces, then (number), on the closing
136
+ // delimiter's own line. texmath's could start on any later line, so it took the (a) that starts the next
137
+ // paragraph.
135
138
  function equationNumber(state, from, stop) {
136
139
  const open = first(state, nonSpace, from);
137
140
  if (open < 0 || state.src[open] !== '(') return null;
141
+ const br = first(state, lineBreak, from);
142
+ if (br >= 0 && br < open) return null;
138
143
  const close = first(state, stop, open + 1);
139
144
  if (close <= open + 1 || state.src[close] !== ')') return null;
140
145
  return { info: state.src.slice(open + 1, close), end: close + 1 };
@@ -0,0 +1,20 @@
1
+ // The @page sizes md2pdf takes, shared by the CLI and buildDocument: auto, a paper name, an orientation or
2
+ // both, or one or two lengths. Chrome prints a size it can't read at Letter without a word. It also reads
3
+ // calc() and newer units, which aren't taken here.
4
+
5
+ export const PAPER = ['a5', 'a4', 'a3', 'b5', 'b4', 'jis-b5', 'jis-b4', 'letter', 'legal', 'ledger'];
6
+ const ORIENTATION = ['portrait', 'landscape'];
7
+ const LENGTH = /^\+?(?:\d+(?:\.\d+)?|\.\d+)(?:e[+-]?\d+)?(?:in|cm|mm|q|pt|pc|px|em|rem|ex|ch|vw|vh|vmin|vmax)$/;
8
+ // buildDocument writes a size that passes straight into its <style> element, so this is checked first, on the
9
+ // string as given: whatever the word rules below come to accept, nothing else can reach the stylesheet. Only
10
+ // CSS's whitespace separates words; to CSS, a no-break space is part of a word.
11
+ const CHARACTERS = /^[A-Za-z0-9.+\- \t\n\r\f]*$/;
12
+
13
+ export function isPageSize(size) {
14
+ if (typeof size !== 'string' || !CHARACTERS.test(size)) return false;
15
+ const words = size.trim().toLowerCase().split(/\s+/);
16
+ if (words.length > 2) return false;
17
+ if (words.every((w) => LENGTH.test(w)) || size.trim().toLowerCase() === 'auto') return true;
18
+ const count = (list) => words.filter((w) => list.includes(w)).length;
19
+ return count(PAPER) <= 1 && count(ORIENTATION) <= 1 && count(PAPER) + count(ORIENTATION) === words.length;
20
+ }
package/lib/render.js CHANGED
@@ -1,5 +1,6 @@
1
1
  // Markdown → HTML rendering shared by the CLI and the md2pdf.me website.
2
2
 
3
+ import { decodeHTML } from 'entities';
3
4
  import MarkdownIt from 'markdown-it';
4
5
  import footnote from 'markdown-it-footnote';
5
6
  import { full as emoji } from 'markdown-it-emoji';
@@ -7,7 +8,9 @@ import callouts from './callouts.js';
7
8
  import footnotes from './footnotes.js';
8
9
  import ids, { ID_PREFIX } from './ids.js';
9
10
  import mathRules from './math.js';
11
+ import { PAPER, isPageSize } from './page-size.js';
10
12
  import taskLists from './tasklists.js';
13
+ import typography from './typography.js';
11
14
  import wikilinks from './wikilinks.js';
12
15
 
13
16
  // YAML front matter: a `---` line at the very start of the document, closed by another `---` line.
@@ -17,6 +20,16 @@ const YAML_KEY = /^[^\s#:-][^:]*:(?:[ \t]|$)/;
17
20
  // Any other line properties can have: a `- item`, an indented continuation or a # comment.
18
21
  const YAML_OTHER = /^(?:-(?:[ \t]|$)|[ \t]+\S|#)/;
19
22
 
23
+ // Windows editors start a file with U+FEFF, which isn't whitespace to markdown-it: left in, the first line
24
+ // is no longer a heading or the start of front matter.
25
+ const withoutByteOrderMark = (s) => (s.charCodeAt(0) === 0xfeff ? s.slice(1) : s);
26
+
27
+ function byteOrderMark(md) {
28
+ md.core.ruler.before('normalize', 'byte_order_mark', (state) => {
29
+ state.src = withoutByteOrderMark(state.src);
30
+ });
31
+ }
32
+
20
33
  // The front matter block at the start of `markdown` and the YAML inside it, or null. A `---…---` block
21
34
  // that isn't YAML properties is Markdown after a divider, as AI answers write it. A # line could be a
22
35
  // comment or a heading, and a - line a list, so the first other line must be a property.
@@ -114,10 +127,12 @@ export function createRenderer({ hljs, math, html = true, idPrefix = '', highlig
114
127
  .use(footnote)
115
128
  .use(footnotes, { idPrefix })
116
129
  .use(taskLists)
130
+ .use(typography)
117
131
  .use(emoji)
118
132
  .use(callouts)
119
133
  .use(wikilinks, { slugify })
120
- .use(frontMatter);
134
+ .use(frontMatter)
135
+ .use(byteOrderMark);
121
136
  if (math) md.use(mathRules, { katex: math.katex, maxHtml: math.maxHtml });
122
137
  return md;
123
138
  }
@@ -133,17 +148,72 @@ function trimSpaceTab(s) {
133
148
  return s.slice(start, end);
134
149
  }
135
150
 
136
- // The document title: the text of the first level-one heading as it renders, else the front matter's
137
- // `title:`, else the fallback.
151
+ // A block scalar's header: > or |, with its chomping and indentation indicators.
152
+ const BLOCK_SCALAR = /^[>|][+-]?\d?[+-]?(?:[ \t]+#[^]*)?$/;
153
+
154
+ // The first `title:` in front matter's YAML that has a value, or ''. A lowercase key only, as YAML's keys
155
+ // are case-sensitive. A `>` or `|` block reads as one line, and a quoted value loses its quotes.
156
+ function yamlTitle(yaml) {
157
+ const lines = yaml.split(/\r?\n/);
158
+ for (let i = 0; i < lines.length; i++) {
159
+ if (!/^title:(?:[ \t]|$)/.test(lines[i])) continue;
160
+ let value = trimSpaceTab(lines[i].slice('title:'.length));
161
+ // [^]* and not .*, here and below: a line can hold a lone \r or a line separator, which . stops at, and
162
+ // the search would then run again from every #.
163
+ const quoted = value.match(/^(["'])(.*?)\1[ \t]*(?:#[^]*)?$/);
164
+ if (BLOCK_SCALAR.test(value)) {
165
+ const text = [];
166
+ for (let j = i + 1; j < lines.length && (/^[ \t]/.test(lines[j]) || !lines[j].trim()); j++) text.push(lines[j].trim());
167
+ value = text.filter(Boolean).join(' ');
168
+ } else if (quoted) {
169
+ value = quoted[2];
170
+ } else {
171
+ // A # after a space starts a comment.
172
+ value = value.startsWith('#') ? '' : value.replace(/[ \t]#[^]*$/, '');
173
+ }
174
+ if (value.trim()) return value.trim();
175
+ }
176
+ return '';
177
+ }
178
+
179
+ // Whether a block token is raw HTML, or holds some, whose text matches `pattern`.
180
+ const rawHtml = (token, pattern = /^/) =>
181
+ token.type === 'html_block'
182
+ ? pattern.test(token.content)
183
+ : token.type === 'inline' && token.children.some((t) => t.type === 'html_inline' && pattern.test(t.content));
184
+
185
+ // The document title: the text of the first level-one heading, Markdown or raw HTML, as headingText finds it
186
+ // in a render with raw HTML on; else the front matter's `title:`, else the fallback.
138
187
  export function titleOf(markdown, fallback) {
139
- titleParser ??= createRenderer({});
188
+ if (!titleParser) {
189
+ // Code renders unhighlighted and callouts without icons, with the same text. Each render call starts
190
+ // the icon cap again, so the pieces below would otherwise draw every icon.
191
+ titleParser = createRenderer({ hljs: { getLanguage: () => undefined } });
192
+ titleParser.renderer.rules.callout_title_open = () => '<p class="markdown-alert-title">';
193
+ }
140
194
  const env = {};
141
195
  const tokens = titleParser.parse(markdown, env);
142
- const at = tokens.findIndex((t) => t.type === 'heading_open' && t.tag === 'h1');
143
- const heading = at < 0 ? '' : headingText(titleParser.renderer.render(tokens.slice(at, at + 3), titleParser.options, env));
144
- const yaml = frontMatterOf(markdown)?.yaml ?? '';
145
- const title = trimSpaceTab(yaml.match(/^title:(.+)$/m)?.[1] ?? '').replace(/^(["'])(.*)\1$/, '$2').trim();
146
- return heading || title || fallback;
196
+ // Before the first h1 or raw HTML, a render has no h1 and leaves no tag open, so it can't change what
197
+ // headingText finds: start there. Render in pieces, each ending at a token that may close an h1. No token
198
+ // that ends a piece looks at the next, and none that starts one looks back, so the pieces' text joins as
199
+ // one render's would. Look for the h1 again only once the HTML has doubled, so a document full of </h1 in
200
+ // comments takes linear time; a longer render finds the same first h1.
201
+ const start = tokens.findIndex((t) => (t.type === 'heading_open' && t.tag === 'h1') || rawHtml(t));
202
+ let heading;
203
+ let html = '';
204
+ let scanned = -1;
205
+ for (let from = start, end = start; start >= 0 && end < tokens.length && heading === undefined; end++) {
206
+ const t = tokens[end];
207
+ const last = end === tokens.length - 1;
208
+ if (!last && !(t.type === 'heading_close' && t.tag === 'h1') && !rawHtml(t, /<\/h1/i)) continue;
209
+ html += titleParser.renderer.render(tokens.slice(from, end + 1), titleParser.options, env);
210
+ from = end + 1;
211
+ if (last || html.length >= 2 * scanned) {
212
+ scanned = html.length;
213
+ heading = firstHeading(html);
214
+ }
215
+ }
216
+ return heading || yamlTitle(frontMatterOf(withoutByteOrderMark(markdown))?.yaml ?? '') || fallback;
147
217
  }
148
218
 
149
219
  // A quoted CSS string, safe inside a <style> element.
@@ -169,19 +239,54 @@ function formulasAsTex(html) {
169
239
  return html;
170
240
  }
171
241
 
172
- const ENTITIES = { lt: '<', gt: '>', quot: '"', amp: '&', '#x27': "'", '#039': "'" };
242
+ // A comment, or a tag whose > may sit in a quoted attribute value; a quote opens a value only after =. Every
243
+ // alternative matches once it starts, so a scan never backs up, and an unclosed comment, tag or quote runs
244
+ // to the end, as in a browser.
245
+ const TAG = /<!--(?:-?>|[\s\S]*?(?:-->|$))|<[a-zA-Z/!?](?:[^>=]|=[\t\n\f\r ]*(?:"[^"]*(?:"|$)|'[^']*(?:'|$))?)*>?/g;
246
+ const H1_OPEN = /^<h1[\t\n\f\r />]/i;
247
+ const H1_CLOSE = /^<\/h1[\t\n\f\r />]/i;
248
+
249
+ // The text of the first <h1> in rendered HTML, as a browser shows it, or undefined if no <h1> is closed. Raw
250
+ // HTML can write the h1 in any case, inside a comment or with entities. A formula in it shows as its TeX.
251
+ function firstHeading(html) {
252
+ let start = -1;
253
+ TAG.lastIndex = 0;
254
+ for (let tag; (tag = TAG.exec(html)); ) {
255
+ if (start < 0) {
256
+ if (H1_OPEN.test(tag[0])) start = TAG.lastIndex;
257
+ } else if (H1_CLOSE.test(tag[0])) {
258
+ return decodeHTML(formulasAsTex(html.slice(start, tag.index)).replace(TAG, '')).trim();
259
+ }
260
+ }
261
+ return undefined;
262
+ }
173
263
 
174
- // The text of the first <h1> in rendered HTML, or '' if there is none. A formula in it shows as its TeX.
264
+ // The text of the first <h1> in rendered HTML, as a browser shows it, or '' if there is none.
175
265
  export function headingText(html) {
176
- const inner = html.match(/<h1[^>]*>([\s\S]*?)<\/h1>/)?.[1] ?? '';
177
- const text = formulasAsTex(inner).replace(/<[^>]*>/g, '');
178
- return text.replace(/&(lt|gt|quot|amp|#x27|#039);/g, (_, e) => ENTITIES[e]).trim();
266
+ return firstHeading(html) ?? '';
267
+ }
268
+
269
+ export { isPageSize };
270
+
271
+ // The value in a pageSize error: quoted and cut short, with < > & and everything outside printable ASCII
272
+ // escaped too, for a host that shows the message as HTML or writes it to a log or a terminal.
273
+ function describe(value) {
274
+ if (value === null) return 'null';
275
+ if (typeof value !== 'string') return `${/^[aeiou]/.test(typeof value) ? 'an' : 'a'} ${typeof value}`;
276
+ const text = JSON.stringify(value.length > 80 ? `${value.slice(0, 80)}…` : value);
277
+ return text.replace(/[^\x20-\x7e…]|[<>&]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`);
179
278
  }
180
279
 
181
280
  // A complete printable HTML document. `css` is the style's on-screen stylesheet followed by its print
182
- // stylesheet.
281
+ // stylesheet, written as given but for a \ before the / of each </style, in any case: the same in CSS, and
282
+ // it can't end the element. `head` and `bodyHtml` are written as given. `pageSize` must pass isPageSize, or this throws.
183
283
  // Styles can show the first heading in a running header with `content: var(--document-title)`.
184
284
  export function buildDocument({ bodyHtml, title, css, pageSize = 'Letter', head = '' }) {
285
+ if (!isPageSize(pageSize)) {
286
+ throw new TypeError(
287
+ `buildDocument: pageSize ${describe(pageSize)} isn't a page size. Use auto, portrait or landscape, a paper name (${PAPER.join(', ')}) alone or with portrait or landscape, or one or two lengths such as "5in 8in"`,
288
+ );
289
+ }
185
290
  return `<!DOCTYPE html>
186
291
  <html lang="en">
187
292
  <head>
@@ -189,7 +294,7 @@ export function buildDocument({ bodyHtml, title, css, pageSize = 'Letter', head
189
294
  <title>${escapeHtml(title)}</title>
190
295
  ${head}
191
296
  <style>
192
- ${css}
297
+ ${String(css).replace(/<\/(style)/gi, '<\\/$1')}
193
298
  @page { size: ${pageSize}; }
194
299
  :root { --document-title: ${cssString(headingText(bodyHtml))}; }
195
300
  </style>