@threepenny/md2pdf 2.4.0 → 2.5.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 +13 -9
- package/bin/md2pdf.js +95 -21
- package/lib/css.js +35 -8
- package/lib/fit.js +266 -0
- package/lib/math.js +16 -11
- package/lib/page-size.js +20 -0
- package/lib/render.js +121 -16
- package/lib/typography.js +32 -0
- package/package.json +2 -1
- package/styles/github.css +12 -2
- package/styles/print/academic.css +24 -0
- package/styles/print/classic.css +24 -0
- package/styles/print/cyberpunk.css +24 -0
- package/styles/print/elvish.css +24 -0
- package/styles/print/github.css +20 -0
- package/styles/print/gothic.css +24 -0
- package/styles/print/modern.css +24 -0
- package/styles/print/report.css +24 -0
- package/styles/print/resume.css +24 -0
- package/styles/print/sandwake.css +24 -0
- package/styles/print/worksheet.css +24 -0
package/README.md
CHANGED
|
@@ -6,11 +6,11 @@ Convert Markdown to beautifully styled PDFs. This is the rendering engine and ma
|
|
|
6
6
|
- **On a Mac and comfortable with a terminal?** Install the command-line tool below. It adds a Finder right-click action and a keyboard shortcut.
|
|
7
7
|
- **Building something?** Use the renderer and styles as a dependency, to make PDFs ([Using the renderer](#using-the-renderer)) or to show Markdown in your own pages ([Embedding in a web page](#embedding-in-a-web-page)).
|
|
8
8
|
|
|
9
|
-
Supports GitHub-flavored Markdown: tables, task lists, footnotes, emoji shortcodes, syntax-highlighted code, raw HTML, GitHub alerts and Obsidian callouts (`> [!NOTE]`, `> [!tip] Custom title`), Obsidian wikilinks and embeds (`[[Note|alias]]` prints as plain text, `![[image.png]]` as an image, and an embedded note as a placeholder naming it), YAML front matter (a leading `---` block of `key: value` properties, left out of the PDF; its `title:` names the document when there is no
|
|
9
|
+
Supports GitHub-flavored Markdown: tables, task lists, footnotes, emoji shortcodes, syntax-highlighted code, raw HTML, GitHub alerts and Obsidian callouts (`> [!NOTE]`, `> [!tip] Custom title`), Obsidian wikilinks and embeds (`[[Note|alias]]` prints as plain text, `![[image.png]]` as an image, and an embedded note as a placeholder naming it), YAML front matter (a leading `---` block of `key: value` properties, left out of the PDF; its `title:` names the document when there is no level-one heading, `#` or `<h1>`. A leading `---` block of ordinary Markdown prints as Markdown after a divider), and page breaks (`<div class="page-break"></div>`). Collapsed `<details>` sections print open. Typed `--`, `---`, `...` and `+-` print as –, —, … and ±, and straight quotes as curly ones; `(c)`, `(r)` and `(tm)` print as typed (before 2.5 they became ©, ® and ™, so type the symbol or `©`, `®`, `™` where you want one). Eleven print styles are included: `github`, `classic`, `academic`, `modern`, `report`, `resume`, `worksheet`, `gothic`, `sandwake`, `elvish` and `cyberpunk`.
|
|
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.
|
|
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.
|
|
14
14
|
|
|
15
15
|
## Install
|
|
16
16
|
|
|
@@ -26,7 +26,7 @@ This installs:
|
|
|
26
26
|
- **Convert to PDF** Quick Action — right-click any `.md` file in Finder → **Quick Actions → Convert to PDF**
|
|
27
27
|
- **⌃⌥⌘P** keyboard shortcut — select `.md` files in Finder and press it
|
|
28
28
|
|
|
29
|
-
Re-run `install.sh` if you move this folder, remove the Node version it was installed with, or pull a version that adds a dependency (md2pdf says so when KaTeX, which draws formulas, is missing). `./uninstall.sh` removes all of it.
|
|
29
|
+
Re-run `install.sh` if you move this folder, remove the Node version it was installed with, or pull a version that adds a dependency (md2pdf says so when KaTeX, which draws formulas, is missing). `./uninstall.sh` removes all of it, and your saved default style (below).
|
|
30
30
|
|
|
31
31
|
To use a different shortcut, pass it when installing (`@` ⌘, `~` ⌥, `^` ⌃, `$` ⇧), or set it to empty to skip:
|
|
32
32
|
|
|
@@ -50,6 +50,8 @@ md2pdf notes.md --css my.css # layer extra CSS on top of the style (its url()
|
|
|
50
50
|
md2pdf notes.md --html # also write the intermediate HTML (for tweaking CSS)
|
|
51
51
|
```
|
|
52
52
|
|
|
53
|
+
A `--css` file's `@import`s resolve against it too. The rules they import come before the style, so where they and the style set the same thing equally specifically, the style wins; rules written in the file itself win.
|
|
54
|
+
|
|
53
55
|
From Finder, a single file opens in Preview when done; multiple files show a notification.
|
|
54
56
|
|
|
55
57
|
## Styles
|
|
@@ -75,14 +77,14 @@ Switch the default style — used by the Finder Quick Action, the keyboard short
|
|
|
75
77
|
./set-style.sh classic # make classic the default
|
|
76
78
|
```
|
|
77
79
|
|
|
78
|
-
The choice is saved in `~/.config/md2pdf/config.json`. Use `md2pdf -s <style>` to override it for one conversion.
|
|
80
|
+
The choice is saved in `~/.config/md2pdf/config.json`. Use `md2pdf -s <style>` to override it for one conversion. If you set `XDG_CONFIG_HOME` in your shell, the `md2pdf` command and `set-style.sh` use `$XDG_CONFIG_HOME/md2pdf/config.json` instead, but the Quick Action and the shortcut still read `~/.config`, since Finder doesn't load your shell profile; `MD2PDF_CONFIG` names a config file of your own. `./uninstall.sh` deletes `config.json` from both of those `md2pdf` folders, and nothing else in them, and keeps a file elsewhere that `MD2PDF_CONFIG` names.
|
|
79
81
|
|
|
80
82
|
### Adding a style
|
|
81
83
|
|
|
82
84
|
Styles are registered in the `STYLES` map in `bin/md2pdf.js`; each is a list of CSS files inlined into the page in order. A style has two files:
|
|
83
85
|
|
|
84
86
|
- `styles/<name>.css`, the on-screen look. The content is wrapped in `<article class="markdown-body">`, and every rule must be scoped to it: no `:root`, `html`, `body` or `@page` rules, so the style can be embedded in other pages.
|
|
85
|
-
- `styles/print/<name>.css`, the print-only rules: `@page` margins, running headers and page numbers, `html, body` margins, and `margin-trim: block-end` on `.markdown-body` in Safari, so it doesn't print a blank last page.
|
|
87
|
+
- `styles/print/<name>.css`, the print-only rules: `@page` margins, running headers and page numbers, `html, body` margins, collapsed `<details>` sections printed open, and `margin-trim: block-end` on `.markdown-body` in Safari, so it doesn't print a blank last page.
|
|
86
88
|
|
|
87
89
|
Register it in `STYLES` and add its page margin to `pageMargins` in `lib/styles.js`, and it's available to `-s` and `set-style.sh`. Use `md2pdf --html` to get the intermediate HTML for tweaking in a browser. For one-off tweaks, `--css` is enough.
|
|
88
90
|
|
|
@@ -99,7 +101,7 @@ The CLI resolves a stylesheet's relative `url()`s against the stylesheet, and lo
|
|
|
99
101
|
|
|
100
102
|
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.
|
|
101
103
|
|
|
102
|
-
The text of the document's first
|
|
104
|
+
The text of the document's first level-one heading, written as `#` or as an HTML `<h1>`, read as a browser shows it (empty if there is none, and a formula in it as its TeX, `$e^{i\pi}$`), is available to page margin boxes as `var(--document-title)`, e.g. `@top-left { content: var(--document-title); }`, as the `report` style does.
|
|
103
105
|
|
|
104
106
|
A style declares the [shared variables](#variables) in its first rule, `:where(.markdown-body) { … }`, with a comment saying what each one does there, and uses them for every size, gap, color and font they name. Spacing follows two patterns: `line-height: calc(1 + 0.55 * var(--md2pdf-leading))` and `margin: calc(1.8em * var(--md2pdf-space)) 0 …`. `npm test` checks that each variable is declared and changes the document. Page margins aren't included: they stay in the style's `@page` rule, in `styles/print/<name>.css`.
|
|
105
107
|
|
|
@@ -126,14 +128,16 @@ const html = buildDocument({
|
|
|
126
128
|
});
|
|
127
129
|
```
|
|
128
130
|
|
|
131
|
+
`pageSize` is the page size the CLI's `--page-size` takes, Letter by default: `auto`; `portrait` or `landscape`; a paper name (`a5`, `a4`, `a3`, `b5`, `b4`, `jis-b5`, `jis-b4`, `letter`, `legal`, `ledger`) alone or with `portrait` or `landscape`; or one or two lengths in `in`, `cm`, `mm`, `q`, `pt`, `pc`, `px`, `em`, `rem`, `ex`, `ch`, `vw`, `vh`, `vmin` or `vmax`, such as `5in 8in` (no `calc()` or newer units). Case doesn't matter. Anything else, including a value that isn't a string, throws a `TypeError`, so check a value you didn't choose with `isPageSize(size)` first. `head` (HTML added to the page's `<head>`) and `bodyHtml` are written into the page as given, and so is `css`, except that a `</style` in it can't end the page's `<style>` element. `css` and `head` must come from you, not from a visitor: CSS can still restyle the whole page and load URLs, which can send the page's content to another server. For Markdown you didn't write, render `bodyHtml` with `html: false`, as [below](#embedding-in-a-web-page) describes.
|
|
132
|
+
|
|
129
133
|
A style that [bundles fonts](#adding-a-style) loads them relative to its stylesheet, so a page that inlines the CSS must rewrite those `url()`s, as the CLI does, or let a bundler do it (in Vite, `?inline`, not `?raw`). Before printing, start every font loading and wait: a font used only in a page header may otherwise not be requested until printing starts, and the PDF falls back, as it does in headless Chrome. `await Promise.allSettled([...document.fonts].map((f) => f.load()))`.
|
|
130
134
|
|
|
131
135
|
| Export | What it is |
|
|
132
136
|
| ------ | ---------- |
|
|
133
|
-
| `@threepenny/md2pdf/render` | `createRenderer({ hljs, math?, html?, idPrefix?, highlightBudget? })`, `buildDocument(
|
|
137
|
+
| `@threepenny/md2pdf/render` | `createRenderer({ hljs, math?, html?, idPrefix?, highlightBudget? })`, `buildDocument({ bodyHtml, title, css, pageSize?, head? })`, `isPageSize(size)` (whether `buildDocument` takes `size` as its `pageSize`), `titleOf(markdown, fallback)` (the first level-one heading's text, a `#` heading or a raw-HTML `<h1>`, without Markdown syntax: the h1 `headingText` finds in a render with raw HTML on. Else the front matter's `title:`, else the fallback. The text is decoded, so escape it before writing it into HTML; `buildDocument` escapes its `title`), `escapeHtml(s)`, `cssString(s)`, `headingText(html)` (the text of the first `<h1>` in rendered HTML, as a browser shows it, formulas as their TeX) |
|
|
134
138
|
| `@threepenny/md2pdf/styles` | `pageMargins`: each style's `@page` margin at default spacing, e.g. `pageMargins.classic` is `'1in 1.1in 0.9in'` |
|
|
135
139
|
| `@threepenny/md2pdf/styles/<name>.css` | Each style's on-screen look, scoped to `.markdown-body`. For `github`, load `github-markdown-css/github-markdown-light.css` first |
|
|
136
|
-
| `@threepenny/md2pdf/styles/print/<name>.css` | Each style's print rules: page margins, running headers and page numbers, and, in Safari, no space below the document's last block. Load it after the on-screen file, only in a page that holds nothing but the document |
|
|
140
|
+
| `@threepenny/md2pdf/styles/print/<name>.css` | Each style's print rules: page margins, running headers and page numbers, collapsed `<details>` sections printed open, and, in Safari, no space below the document's last block. Load it after the on-screen file, only in a page that holds nothing but the document. A section without a `<summary>` still shows the browser's closed arrow; to turn the arrow, remove each section's `name` and set `open` on it before printing, as the CLI does |
|
|
137
141
|
|
|
138
142
|
`createRenderer` takes the highlight.js instance to use (so you can pass a smaller bundle such as `highlight.js/lib/common`) and, optionally, `math: { katex }` to render `\( \)`, `\[ \]`, `$` and `$$` formulas with KaTeX; formulas also need KaTeX's stylesheet, `katex/dist/katex.min.css`, which hides the MathML each formula carries for screen readers; without it, that MathML shows beside the formula and can draw far outside it. (Before 2.2 it also took markdown-it-texmath, as `math: { texmath, katex }`; that still works, and texmath is ignored.) A formula over 8,000 characters, one with braces nested over 100 levels deep, or one that defines a macro (`\def`, `\newcommand`), shows as its source in red. So does a formula that would take the HTML of a document's formulas, their MathML included, past 10,000,000 characters, and every formula after it, so that a short document can't make a page hundreds of megabytes; `math: { katex, maxHtml }` changes that budget, and `maxHtml: Infinity` removes it. Sizes such as `\rule` and `\raisebox` are capped at 30em, before a size command such as `\Huge` scales them. Raw HTML in the Markdown is passed through unless you pass `html: false`, which escapes it; page breaks (`<div class="page-break"></div>`) are raw HTML, so they then print as text. `idPrefix` starts the document's ids, as [Embedding in a web page](#embedding-in-a-web-page) describes. `highlightBudget` is how many milliseconds each render may spend highlighting code, after which the rest of the code shows without colour: 100 with `html: false`, unlimited otherwise. Under a budget, a block over 4 KB is highlighted in pieces split at line breaks where it can, so a comment or string that spans a split can be coloured wrongly.
|
|
139
143
|
|
|
@@ -149,7 +153,7 @@ Every style takes the same variables, set on the `.markdown-body` element. A `--
|
|
|
149
153
|
| `--md2pdf-background` | The document's background, white |
|
|
150
154
|
| `--md2pdf-text` | Body text |
|
|
151
155
|
| `--md2pdf-muted` | Secondary text, such as footnotes and captions |
|
|
152
|
-
| `--md2pdf-accent` | The accent color: links, headings, list markers or callouts, depending on the style. `gothic`'s leaf ornaments stay oxblood, `sandwake`'s horizon ornament stays rust, `elvish`'s title, `#`, `##`, `####` and `#####` headings, links, quotes, note callouts, table rules and ornaments keep their own greens and gold, and `cyberpunk`'s `##` and `####` headings, links, nested bullets, list numbers, tick boxes, table headings, the title's frame, most of each rule, the quote label, note callouts and function names in code stay teal |
|
|
156
|
+
| `--md2pdf-accent` | The accent color: links, headings, list markers or callouts, depending on the style, and `github`'s focus rings. `gothic`'s leaf ornaments stay oxblood, `sandwake`'s horizon ornament stays rust, `elvish`'s title, `#`, `##`, `####` and `#####` headings, links, quotes, note callouts, table rules and ornaments keep their own greens and gold, and `cyberpunk`'s `##` and `####` headings, links, nested bullets, list numbers, tick boxes, table headings, the title's frame, most of each rule, the quote label, note callouts and function names in code stay teal |
|
|
153
157
|
| `--md2pdf-rule` | Rules, borders and table lines (every style but `github`) |
|
|
154
158
|
| `--md2pdf-surface` | A tinted background: inline code and code blocks in `classic`, `modern`, `worksheet`, `gothic` and `elvish`, and callouts too in `classic` and `gothic`; inline code, quotes and table headings in `report`; the inside of code blocks, callouts and inline code in `sandwake`, white as designed; the title panel, inline code, code blocks, table headings and shaded table rows in `cyberpunk`. The other styles don't use it |
|
|
155
159
|
| `--md2pdf-font` | The body font |
|
package/bin/md2pdf.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// md2pdf: convert Markdown files to PDF using headless Chrome.
|
|
3
3
|
|
|
4
4
|
import { spawn } from 'node:child_process';
|
|
5
|
-
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
5
|
+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
|
6
6
|
import { homedir, tmpdir } from 'node:os';
|
|
7
7
|
import { basename, dirname, extname, join, resolve } from 'node:path';
|
|
8
8
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
@@ -11,7 +11,9 @@ import { createRequire } from 'node:module';
|
|
|
11
11
|
|
|
12
12
|
import hljs from 'highlight.js';
|
|
13
13
|
import { buildDocument, createRenderer, titleOf } from '../lib/render.js';
|
|
14
|
-
import {
|
|
14
|
+
import { fitFormulas, fitTables } from '../lib/fit.js';
|
|
15
|
+
import { rewriteUrls, splitImports } from '../lib/css.js';
|
|
16
|
+
import { PAPER, isPageSize } from '../lib/page-size.js';
|
|
15
17
|
|
|
16
18
|
const require = createRequire(import.meta.url);
|
|
17
19
|
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
|
@@ -34,6 +36,8 @@ const STYLES = {
|
|
|
34
36
|
cyberpunk: styleFiles('cyberpunk'),
|
|
35
37
|
};
|
|
36
38
|
const FALLBACK_STYLE = 'github';
|
|
39
|
+
// Not STYLES[name], which is truthy for names every object inherits, such as toString.
|
|
40
|
+
const isStyle = (name) => typeof name === 'string' && Object.hasOwn(STYLES, name);
|
|
37
41
|
// A checkout installed before KaTeX was a dependency has none until install.sh runs again; it still converts.
|
|
38
42
|
const katex = await import('katex').then(
|
|
39
43
|
(m) => m.default,
|
|
@@ -75,7 +79,7 @@ Options:
|
|
|
75
79
|
-o, --output <file> Output path (only with a single input file)
|
|
76
80
|
-s, --style <name> Style to use (${Object.keys(STYLES).join(', ')}; default: ${defaultStyle})
|
|
77
81
|
--css <file> Extra CSS file applied after the style
|
|
78
|
-
-p, --page-size <size> Letter, A4, Legal, ... (default: Letter)
|
|
82
|
+
-p, --page-size <size> Letter, A4, Legal, "A4 landscape", "5in 8in", ... (default: Letter)
|
|
79
83
|
--open Open the PDF when done
|
|
80
84
|
--html Also write the intermediate .html (for debugging styles)
|
|
81
85
|
--set-style <name> Make <name> the default style (also used by the Finder Quick Action)
|
|
@@ -89,7 +93,9 @@ Environment:
|
|
|
89
93
|
function readConfig() {
|
|
90
94
|
if (!existsSync(CONFIG_PATH)) return {};
|
|
91
95
|
try {
|
|
92
|
-
|
|
96
|
+
const config = JSON.parse(readFileSync(CONFIG_PATH, 'utf8'));
|
|
97
|
+
if (config === null || typeof config !== 'object' || Array.isArray(config)) throw new Error('not a JSON object');
|
|
98
|
+
return config;
|
|
93
99
|
} catch (err) {
|
|
94
100
|
console.error(`md2pdf: ignoring unreadable config ${CONFIG_PATH}: ${err.message}`);
|
|
95
101
|
return {};
|
|
@@ -113,9 +119,9 @@ function findChrome() {
|
|
|
113
119
|
return found;
|
|
114
120
|
}
|
|
115
121
|
|
|
116
|
-
// A stylesheet's text, with its relative url()s (a style's bundled fonts, say) made absolute:
|
|
117
|
-
// into the page, they would otherwise resolve against the Markdown file's folder. Warns once about
|
|
118
|
-
// file they name that doesn't exist.
|
|
122
|
+
// A stylesheet's text, with its relative url()s and @imports (a style's bundled fonts, say) made absolute:
|
|
123
|
+
// inlined into the page, they would otherwise resolve against the Markdown file's folder. Warns once about
|
|
124
|
+
// each file they name that doesn't exist.
|
|
119
125
|
const warned = new Set();
|
|
120
126
|
function readCss(file) {
|
|
121
127
|
return rewriteUrls(readFileSync(file, 'utf8'), (ref) => {
|
|
@@ -138,7 +144,15 @@ function readCss(file) {
|
|
|
138
144
|
function buildHtml({ markdown, title, baseDir, style, extraCss, pageSize }) {
|
|
139
145
|
const bodyHtml = createRenderer({ hljs, ...(katex && { math: { katex } }) }).render(markdown);
|
|
140
146
|
const math = /<eqn?>/.test(bodyHtml) ? [readCss(MATH_CSS) + EQUATION_NUMBERS] : [];
|
|
141
|
-
|
|
147
|
+
// An @import counts only before every other rule, so the --css file's @imports lead the page's CSS: the
|
|
148
|
+
// style then wins ties with the rules they import, while the file's own rules still follow the style.
|
|
149
|
+
const extra = extraCss ? splitImports(readCss(extraCss)) : null;
|
|
150
|
+
const css = [...(extra ? extra.head : []), ...STYLES[style].map(readCss), ...math, ...(extra ? [extra.rest] : [])].join('\n');
|
|
151
|
+
const loadFonts = `() => document.fonts.forEach((f) => f.load().catch(() => {}))`;
|
|
152
|
+
// Once its fonts have loaded, a displayed formula wider than the column shrinks to fit. It fits whatever
|
|
153
|
+
// column it ends up in, so the printed page needs no second run. Then a table wider than the printed page
|
|
154
|
+
// fits it, measured at that page's width; it goes second, since fitFormulas resets a formula in a cell.
|
|
155
|
+
const fits = [...(/<eqn>/.test(bodyHtml) ? [fitFormulas] : []), ...(/<table[\s>]/i.test(bodyHtml) ? [fitTables] : [])];
|
|
142
156
|
return buildDocument({
|
|
143
157
|
bodyHtml,
|
|
144
158
|
title,
|
|
@@ -146,9 +160,29 @@ function buildHtml({ markdown, title, baseDir, style, extraCss, pageSize }) {
|
|
|
146
160
|
pageSize,
|
|
147
161
|
// <base> makes relative image/link paths resolve against the Markdown file's folder.
|
|
148
162
|
// Chrome loads a font used only in a page header or footer too late for the PDF, so start every
|
|
149
|
-
// declared font loading now; the PDF waits for those loads with the rest of the page.
|
|
163
|
+
// declared font loading now; the PDF waits for those loads with the rest of the page. An imported
|
|
164
|
+
// stylesheet's fonts may not be declared until the page has loaded, so they start then.
|
|
150
165
|
head: `<base href="${pathToFileURL(baseDir + '/').href}">
|
|
151
|
-
<script>document.addEventListener('DOMContentLoaded',
|
|
166
|
+
<script>document.addEventListener('DOMContentLoaded', ${loadFonts});</script>${extra?.head.length ? `
|
|
167
|
+
<script>addEventListener('load', ${loadFonts});</script>` : ''}${
|
|
168
|
+
// The print stylesheet shows a collapsed section's content, but can't reach the closed arrow the
|
|
169
|
+
// browser draws for one without a <summary>. Opening each section turns that arrow too. Opening one
|
|
170
|
+
// section of a named group closes the rest, so each leaves its group first.
|
|
171
|
+
/<details[\s/>]/i.test(bodyHtml)
|
|
172
|
+
? `
|
|
173
|
+
<script>document.addEventListener('DOMContentLoaded', () => {
|
|
174
|
+
for (const section of document.querySelectorAll('details')) {
|
|
175
|
+
section.removeAttribute('name');
|
|
176
|
+
section.open = true;
|
|
177
|
+
}
|
|
178
|
+
});</script>`
|
|
179
|
+
: ''
|
|
180
|
+
}${fits.length
|
|
181
|
+
? `
|
|
182
|
+
<script>${fits.join('\n')}
|
|
183
|
+
addEventListener('load', () => document.fonts.ready.then(() => { ${fits.map((fit) => `${fit.name}();`).join(' ')} }));</script>`
|
|
184
|
+
: ''
|
|
185
|
+
}`,
|
|
152
186
|
});
|
|
153
187
|
}
|
|
154
188
|
|
|
@@ -223,12 +257,34 @@ function runChrome(chrome, htmlPath, pdfPath) {
|
|
|
223
257
|
});
|
|
224
258
|
}
|
|
225
259
|
|
|
226
|
-
|
|
260
|
+
// A file's identity, whatever name reaches it: names can differ by case, a symlink or a hard link.
|
|
261
|
+
const fileId = (stat) => `${stat.dev}:${stat.ino}`;
|
|
262
|
+
|
|
263
|
+
// `written` maps each PDF this run has written, by fileId, to the input it came from;
|
|
264
|
+
// `inputs` maps each of this run's inputs, by fileId, to its name.
|
|
265
|
+
async function convert(input, opts, chrome, written, inputs) {
|
|
227
266
|
const inputPath = resolve(input);
|
|
228
267
|
if (!existsSync(inputPath)) throw new Error(`No such file: ${input}`);
|
|
229
|
-
const
|
|
268
|
+
const source = fileId(statSync(inputPath));
|
|
230
269
|
const stem = basename(inputPath, extname(inputPath));
|
|
231
270
|
const pdfPath = resolve(opts.output ?? join(dirname(inputPath), `${stem}.pdf`));
|
|
271
|
+
const target = statSync(pdfPath, { throwIfNoEntry: false });
|
|
272
|
+
if (target && fileId(target) === source) {
|
|
273
|
+
throw new Error('The PDF would replace the file it is made from; give another path with --output');
|
|
274
|
+
}
|
|
275
|
+
const htmlPath = opts.html && pdfPath.replace(/\.pdf$/i, '') + '.html';
|
|
276
|
+
const htmlTarget = htmlPath && statSync(htmlPath, { throwIfNoEntry: false });
|
|
277
|
+
if (htmlTarget && fileId(htmlTarget) === source) {
|
|
278
|
+
throw new Error('The HTML would replace the file it is made from; give another path with --output');
|
|
279
|
+
}
|
|
280
|
+
if (htmlTarget && inputs.has(fileId(htmlTarget))) {
|
|
281
|
+
throw new Error(`The HTML would replace ${inputs.get(fileId(htmlTarget))}, another input; convert it alone with --output`);
|
|
282
|
+
}
|
|
283
|
+
if (target && written.has(fileId(target))) {
|
|
284
|
+
throw new Error(`${pdfPath} was already written from ${written.get(fileId(target))}; convert it alone with --output`);
|
|
285
|
+
}
|
|
286
|
+
if (!existsSync(dirname(pdfPath))) throw new Error(`No such folder: ${dirname(pdfPath)}`);
|
|
287
|
+
const markdown = readFileSync(inputPath, 'utf8');
|
|
232
288
|
const title = titleOf(markdown, stem);
|
|
233
289
|
|
|
234
290
|
const html = buildHtml({
|
|
@@ -242,13 +298,21 @@ async function convert(input, opts, chrome) {
|
|
|
242
298
|
|
|
243
299
|
const workDir = makeTempDir('md2pdf-');
|
|
244
300
|
try {
|
|
245
|
-
const
|
|
246
|
-
writeFileSync(
|
|
247
|
-
if (
|
|
248
|
-
|
|
301
|
+
const page = join(workDir, `${stem}.html`);
|
|
302
|
+
writeFileSync(page, html);
|
|
303
|
+
if (htmlPath) writeFileSync(htmlPath, html);
|
|
304
|
+
// Chrome prints into the temp folder: printing over a PDF it can't replace, it reports success.
|
|
305
|
+
const printed = join(workDir, 'print.pdf');
|
|
306
|
+
await runChrome(chrome, page, printed);
|
|
307
|
+
try {
|
|
308
|
+
writeFileSync(pdfPath, readFileSync(printed));
|
|
309
|
+
} catch (err) {
|
|
310
|
+
throw new Error(`Could not write ${pdfPath}: ${err.message.split(',')[0]}`);
|
|
311
|
+
}
|
|
249
312
|
} finally {
|
|
250
313
|
removeTempDir(workDir);
|
|
251
314
|
}
|
|
315
|
+
written.set(fileId(statSync(pdfPath)), input);
|
|
252
316
|
return pdfPath;
|
|
253
317
|
}
|
|
254
318
|
|
|
@@ -275,10 +339,10 @@ async function main() {
|
|
|
275
339
|
}
|
|
276
340
|
const { values: opts, positionals: files } = parsed;
|
|
277
341
|
const config = readConfig();
|
|
278
|
-
const defaultStyle =
|
|
342
|
+
const defaultStyle = isStyle(config.style) ? config.style : FALLBACK_STYLE;
|
|
279
343
|
|
|
280
344
|
if (opts['set-style'] !== undefined) {
|
|
281
|
-
if (!
|
|
345
|
+
if (!isStyle(opts['set-style'])) unknownStyle(opts['set-style']);
|
|
282
346
|
writeConfig({ ...config, style: opts['set-style'] });
|
|
283
347
|
console.log(`Default style is now "${opts['set-style']}".`);
|
|
284
348
|
process.exit(0);
|
|
@@ -291,11 +355,15 @@ async function main() {
|
|
|
291
355
|
console.log(usage(defaultStyle));
|
|
292
356
|
process.exit(opts.help ? 0 : 2);
|
|
293
357
|
}
|
|
294
|
-
if (config.style && !
|
|
358
|
+
if (config.style && !isStyle(config.style)) {
|
|
295
359
|
console.error(`md2pdf: config style "${config.style}" no longer exists; using ${FALLBACK_STYLE}`);
|
|
296
360
|
}
|
|
297
361
|
opts.style ??= defaultStyle;
|
|
298
|
-
if (!
|
|
362
|
+
if (!isStyle(opts.style)) unknownStyle(opts.style);
|
|
363
|
+
if (!isPageSize(opts['page-size'])) {
|
|
364
|
+
console.error(`md2pdf: unknown page size "${opts['page-size']}". Use one of ${PAPER.join(', ')}, alone or with "landscape", or a width and height such as "5in 8in"`);
|
|
365
|
+
process.exit(2);
|
|
366
|
+
}
|
|
299
367
|
if (opts.output && files.length > 1) {
|
|
300
368
|
console.error('md2pdf: --output can only be used with a single input file');
|
|
301
369
|
process.exit(2);
|
|
@@ -304,9 +372,15 @@ async function main() {
|
|
|
304
372
|
const chrome = findChrome();
|
|
305
373
|
if (!katex) console.error(`md2pdf: KaTeX isn't installed, so formulas print as their source; run ${join(ROOT, 'install.sh')} again`);
|
|
306
374
|
let failed = 0;
|
|
375
|
+
const written = new Map();
|
|
376
|
+
const inputs = new Map();
|
|
377
|
+
for (const file of files) {
|
|
378
|
+
const stat = statSync(resolve(file), { throwIfNoEntry: false });
|
|
379
|
+
if (stat) inputs.set(fileId(stat), file);
|
|
380
|
+
}
|
|
307
381
|
for (const file of files) {
|
|
308
382
|
try {
|
|
309
|
-
const pdf = await convert(file, opts, chrome);
|
|
383
|
+
const pdf = await convert(file, opts, chrome, written, inputs);
|
|
310
384
|
console.log(pdf);
|
|
311
385
|
if (opts.open) spawn('open', [pdf], { stdio: 'ignore', detached: true }).unref();
|
|
312
386
|
} catch (err) {
|
package/lib/css.js
CHANGED
|
@@ -2,26 +2,53 @@
|
|
|
2
2
|
|
|
3
3
|
import { cssString } from './render.js';
|
|
4
4
|
|
|
5
|
-
// A comment, a string, or a url()
|
|
5
|
+
// A comment, a string, an @import of a string, or a url(); the groups hold the @import's double- or
|
|
6
|
+
// single-quoted reference, then the url()'s double-quoted, single-quoted or bare one.
|
|
6
7
|
const STRING = (q) => `${q}(?:\\\\[^]|[^${q}\\\\\\n])*${q}`;
|
|
7
8
|
const TOKENS = new RegExp(
|
|
8
|
-
String.raw`\/\*[^]
|
|
9
|
+
String.raw`\/\*[^]*?\*\/|@import\s*(?:"((?:\\[^]|[^"\\\n])*)"|'((?:\\[^]|[^'\\\n])*)')|${STRING('"')}|${STRING("'")}|url\(\s*(?:"((?:\\[^]|[^"\\\n])*)"|'((?:\\[^]|[^'\\\n])*)'|([^)\s'"\\]*))\s*\)`,
|
|
9
10
|
'gi',
|
|
10
11
|
);
|
|
11
12
|
|
|
12
|
-
// Replaces each relative url() in a stylesheet with url(<resolve(ref)>)
|
|
13
|
-
// and references that are absolute, root-relative,
|
|
13
|
+
// Replaces each relative url() and @import "…" in a stylesheet with url(<resolve(ref)>) or
|
|
14
|
+
// @import "<resolve(ref)>", leaving comments, strings, and references that are absolute, root-relative,
|
|
15
|
+
// fragments or contain CSS escapes as they are.
|
|
14
16
|
export function rewriteUrls(css, resolve) {
|
|
15
|
-
return css.replace(TOKENS, (whole, dq, sq, bare) => {
|
|
16
|
-
const ref = dq ?? sq ?? bare;
|
|
17
|
+
return css.replace(TOKENS, (whole, idq, isq, dq, sq, bare) => {
|
|
18
|
+
const ref = idq ?? isq ?? dq ?? sq ?? bare;
|
|
17
19
|
if (!ref || ref.includes('\\') || /^(?:[a-z][a-z\d+.-]*:|\/|#)/i.test(ref)) return whole;
|
|
18
|
-
return `url(${cssString(resolve(ref))})`;
|
|
20
|
+
return (idq ?? isq) !== undefined ? `@import ${cssString(resolve(ref))}` : `url(${cssString(resolve(ref))})`;
|
|
19
21
|
});
|
|
20
22
|
}
|
|
21
23
|
|
|
22
|
-
// The relative references a stylesheet's url()s make, as rewriteUrls sees them.
|
|
24
|
+
// The relative references a stylesheet's url()s and @imports make, as rewriteUrls sees them.
|
|
23
25
|
export function relativeUrls(css) {
|
|
24
26
|
const refs = [];
|
|
25
27
|
rewriteUrls(css, (ref) => (refs.push(ref), ref));
|
|
26
28
|
return refs;
|
|
27
29
|
}
|
|
30
|
+
|
|
31
|
+
// What may open a stylesheet: white space, a comment, or an @charset, @layer or @import statement.
|
|
32
|
+
// Each character of a statement can match only one way, and a comment ends at its first */, so a long
|
|
33
|
+
// statement that never ends can't make the match backtrack; an unclosed comment ends the opening.
|
|
34
|
+
const COMMENT = String.raw`\/\*[^*]*\*+(?:[^/*][^*]*\*+)*\/`;
|
|
35
|
+
const QUOTED = `${STRING('"')}|${STRING("'")}`;
|
|
36
|
+
const group = (inner) => String.raw`\((?:${COMMENT}|${QUOTED}|${inner}|\/(?!\*)|[^()"'/])*\)`;
|
|
37
|
+
const PRELUDE = String.raw`\s+|${COMMENT}|@(charset|layer|import)(?![\w-])(?:${COMMENT}|${QUOTED}|${group(group(group('(?!)')))}|\/(?!\*)|[^;{}()"'/])*(?:;|$)`;
|
|
38
|
+
|
|
39
|
+
// A stylesheet's leading @import rules, which count only before every other rule, with the @layer
|
|
40
|
+
// statements among them so its layers keep their order; and the rest of its text. A stylesheet with no
|
|
41
|
+
// @import comes back whole.
|
|
42
|
+
export function splitImports(css) {
|
|
43
|
+
const prelude = new RegExp(PRELUDE, 'iy');
|
|
44
|
+
const head = [];
|
|
45
|
+
let rest = '';
|
|
46
|
+
let end = 0;
|
|
47
|
+
for (let m; (m = prelude.exec(css)); end = prelude.lastIndex) {
|
|
48
|
+
// One at the very end may have no semicolon; moved ahead of other rules, it needs one.
|
|
49
|
+
if (/^(?:import|layer)$/i.test(m[1] ?? '')) head.push(m[0].endsWith(';') ? m[0] : `${m[0]};`);
|
|
50
|
+
else rest += m[0];
|
|
51
|
+
}
|
|
52
|
+
if (!head.some((rule) => /^@import/i.test(rule))) return { head: [], rest: css };
|
|
53
|
+
return { head, rest: rest + css.slice(end) };
|
|
54
|
+
}
|
package/lib/fit.js
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
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:
|
|
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.
|
|
57
|
+
// A table that fits isn't written to, so it prints as it did. If the printed width can't be read, nothing
|
|
58
|
+
// changes. Running it again is harmless.
|
|
59
|
+
//
|
|
60
|
+
// Self-contained, so the CLI can put its source in the page.
|
|
61
|
+
export function fitTables(root = document) {
|
|
62
|
+
const FIT = 'data-md2pdf-fit';
|
|
63
|
+
// Puts back an element's style attribute as it was. Chrome keeps an empty one after a script has
|
|
64
|
+
// written its style, even through removeAttribute, unless the attribute is set first.
|
|
65
|
+
const restore = (el, style) => {
|
|
66
|
+
el.setAttribute('style', style ?? '');
|
|
67
|
+
if (style === null) el.removeAttribute('style');
|
|
68
|
+
};
|
|
69
|
+
const unset = (el, ...properties) => {
|
|
70
|
+
for (const property of properties) el.style.removeProperty(property);
|
|
71
|
+
restore(el, el.getAttribute('style') || null);
|
|
72
|
+
el.removeAttribute(FIT);
|
|
73
|
+
};
|
|
74
|
+
for (const el of root.querySelectorAll(`[${FIT}]`)) unset(el, 'overflow-wrap', 'font-size');
|
|
75
|
+
const tables = [...root.querySelectorAll('table')];
|
|
76
|
+
if (!tables.length) return;
|
|
77
|
+
|
|
78
|
+
// The printed page's width and side margins: the last rule without a page selector that sets each.
|
|
79
|
+
const page = {};
|
|
80
|
+
const read = (rules) => {
|
|
81
|
+
for (const rule of rules) {
|
|
82
|
+
if (rule instanceof CSSPageRule) {
|
|
83
|
+
if (rule.selectorText) continue;
|
|
84
|
+
for (const name of ['size', 'margin-left', 'margin-right']) {
|
|
85
|
+
const value = rule.style.getPropertyValue(name);
|
|
86
|
+
if (value) page[name] = value;
|
|
87
|
+
}
|
|
88
|
+
} else if (rule instanceof CSSImportRule) {
|
|
89
|
+
if (!rule.media.length || [...rule.media].some((m) => /\b(all|print)\b/i.test(m) && !/\bnot\b/i.test(m))) {
|
|
90
|
+
try {
|
|
91
|
+
read(rule.styleSheet.cssRules);
|
|
92
|
+
} catch {
|
|
93
|
+
// A stylesheet from another origin can't be read.
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
} else if (rule instanceof CSSMediaRule) {
|
|
97
|
+
if ([...rule.media].some((m) => /\b(all|print)\b/i.test(m) && !/\bnot\b/i.test(m))) read(rule.cssRules);
|
|
98
|
+
} else if (rule.cssRules && !(rule instanceof CSSStyleRule)) {
|
|
99
|
+
read(rule.cssRules);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
for (const sheet of document.styleSheets) {
|
|
104
|
+
try {
|
|
105
|
+
read(sheet.cssRules);
|
|
106
|
+
} catch {
|
|
107
|
+
// As above.
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
const html = document.documentElement;
|
|
111
|
+
const box = document.createElement('div');
|
|
112
|
+
box.style.cssText = 'position: absolute; visibility: hidden; height: 0; padding: 0; border: 0';
|
|
113
|
+
const probe = box.cloneNode();
|
|
114
|
+
box.append(probe);
|
|
115
|
+
html.append(box);
|
|
116
|
+
const px = (length) => {
|
|
117
|
+
if (!length || /v(w|h|min|max)$/i.test(length)) return NaN;
|
|
118
|
+
probe.style.width = '';
|
|
119
|
+
probe.style.width = length;
|
|
120
|
+
return probe.style.width ? probe.getBoundingClientRect().width : NaN;
|
|
121
|
+
};
|
|
122
|
+
const PAPER = {
|
|
123
|
+
a5: ['148mm', '210mm'], a4: ['210mm', '297mm'], a3: ['297mm', '420mm'], b5: ['176mm', '250mm'],
|
|
124
|
+
b4: ['250mm', '353mm'], 'jis-b5': ['182mm', '257mm'], 'jis-b4': ['257mm', '364mm'],
|
|
125
|
+
letter: ['8.5in', '11in'], legal: ['8.5in', '14in'], ledger: ['11in', '17in'],
|
|
126
|
+
};
|
|
127
|
+
// Chrome prints `auto`, or an orientation alone, on Letter paper.
|
|
128
|
+
const words = (page.size || 'auto').trim().toLowerCase().split(/\s+/);
|
|
129
|
+
const paper = PAPER[words.find((word) => PAPER[word]) ?? 'letter'];
|
|
130
|
+
const width = /^[\d.+]/.test(words[0]) ? px(words[0]) : px(words.includes('landscape') ? paper[1] : paper[0]);
|
|
131
|
+
// A margin in % is a share of the page's width.
|
|
132
|
+
box.style.width = `${width}px`;
|
|
133
|
+
const column = width - px(page['margin-left']) - px(page['margin-right']);
|
|
134
|
+
box.remove();
|
|
135
|
+
if (!(column > 0)) return;
|
|
136
|
+
|
|
137
|
+
const style = html.getAttribute('style');
|
|
138
|
+
html.style.width = `${column}px`;
|
|
139
|
+
try {
|
|
140
|
+
for (const table of tables) fit(table);
|
|
141
|
+
} finally {
|
|
142
|
+
restore(html, style);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function fit(table) {
|
|
146
|
+
// How far the table reaches past its box.
|
|
147
|
+
const past = () => {
|
|
148
|
+
const parent = table.parentElement;
|
|
149
|
+
const s = getComputedStyle(parent);
|
|
150
|
+
const edge = parent.getBoundingClientRect().right - parseFloat(s.borderRightWidth) - parseFloat(s.paddingRight);
|
|
151
|
+
let right = table.getBoundingClientRect().right;
|
|
152
|
+
for (const row of table.rows) right = Math.max(right, row.getBoundingClientRect().right);
|
|
153
|
+
return right - edge;
|
|
154
|
+
};
|
|
155
|
+
// A table is fitted when it runs past its box by more than a pixel: less only reaches into the page
|
|
156
|
+
// margin, and the slack keeps a rounding difference from the printed page's width from changing a table
|
|
157
|
+
// that fits. Fitted, it stays inside its box.
|
|
158
|
+
if (!table.parentElement || !(past() > 1)) return;
|
|
159
|
+
const fits = () => past() <= 0;
|
|
160
|
+
|
|
161
|
+
// The table's own cells, by column. A cell that spans columns is broken only with every cell (step 2).
|
|
162
|
+
const columns = [];
|
|
163
|
+
const taken = [];
|
|
164
|
+
[...table.rows].forEach((row, r) => {
|
|
165
|
+
let c = 0;
|
|
166
|
+
for (const cell of row.cells) {
|
|
167
|
+
while (taken[r]?.[c]) c++;
|
|
168
|
+
for (let i = 0; i < (cell.rowSpan || 1); i++) {
|
|
169
|
+
for (let j = 0; j < cell.colSpan; j++) (taken[r + i] ??= [])[c + j] = true;
|
|
170
|
+
}
|
|
171
|
+
if (cell.colSpan === 1) (columns[c] ??= []).push(cell);
|
|
172
|
+
c += cell.colSpan;
|
|
173
|
+
}
|
|
174
|
+
});
|
|
175
|
+
// Each column's width with every cell at its narrowest, as wide as its longest word or formula.
|
|
176
|
+
const narrowest = () => {
|
|
177
|
+
const before = table.getAttribute('style');
|
|
178
|
+
table.style.width = 'min-content';
|
|
179
|
+
const widths = columns.map((cells) => {
|
|
180
|
+
if (!cells?.length) return 0;
|
|
181
|
+
const s = getComputedStyle(cells[0]);
|
|
182
|
+
const edges = ['paddingLeft', 'paddingRight', 'borderLeftWidth', 'borderRightWidth'].reduce((sum, p) => sum + parseFloat(s[p]), 0);
|
|
183
|
+
return cells[0].getBoundingClientRect().width - edges;
|
|
184
|
+
});
|
|
185
|
+
restore(table, before);
|
|
186
|
+
return widths;
|
|
187
|
+
};
|
|
188
|
+
const eight = (cell) => {
|
|
189
|
+
const span = document.createElement('span');
|
|
190
|
+
span.style.cssText = 'position: absolute; visibility: hidden; width: 8ch; padding: 0; border: 0';
|
|
191
|
+
cell.append(span);
|
|
192
|
+
const width = span.getBoundingClientRect().width;
|
|
193
|
+
span.remove();
|
|
194
|
+
return width;
|
|
195
|
+
};
|
|
196
|
+
const mark = (cell) => {
|
|
197
|
+
cell.style.overflowWrap = 'anywhere';
|
|
198
|
+
cell.setAttribute(FIT, '');
|
|
199
|
+
};
|
|
200
|
+
const long = (widths, c) => columns[c]?.length && widths[c] > eight(columns[c][0]);
|
|
201
|
+
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 = () => {
|
|
204
|
+
const tried = new Set();
|
|
205
|
+
while (!fits()) {
|
|
206
|
+
const widths = narrowest();
|
|
207
|
+
let best = -1;
|
|
208
|
+
widths.forEach((w, c) => {
|
|
209
|
+
if (!tried.has(c) && long(widths, c) && body(c).length && (best < 0 || w > widths[best])) best = c;
|
|
210
|
+
});
|
|
211
|
+
if (best < 0) return false;
|
|
212
|
+
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');
|
|
215
|
+
}
|
|
216
|
+
return true;
|
|
217
|
+
};
|
|
218
|
+
|
|
219
|
+
// Its formulas: displayed ones, and inline ones with a part longer than 8 characters that can't wrap.
|
|
220
|
+
const formulas = [...table.querySelectorAll(':is(td, th) .katex')]
|
|
221
|
+
.filter((formula) => formula.closest('table') === table)
|
|
222
|
+
.filter((formula) => {
|
|
223
|
+
if (formula.parentElement.classList.contains('katex-display')) return true;
|
|
224
|
+
const parts = [...formula.querySelectorAll(':scope > .katex-html > .base')];
|
|
225
|
+
return parts.some((part) => part.getBoundingClientRect().width > eight(formula.closest('td, th')));
|
|
226
|
+
})
|
|
227
|
+
.map((formula) => [formula, parseFloat(getComputedStyle(formula).fontSize) / parseFloat(getComputedStyle(formula.parentElement).fontSize)]);
|
|
228
|
+
const scale = (factor) => {
|
|
229
|
+
for (const [formula, size] of formulas) {
|
|
230
|
+
formula.style.fontSize = `${size * factor}em`;
|
|
231
|
+
formula.setAttribute(FIT, '');
|
|
232
|
+
}
|
|
233
|
+
};
|
|
234
|
+
// The largest size from `small`, at which the table fits, up to `large`. At full size, they're left as
|
|
235
|
+
// they were.
|
|
236
|
+
const largest = (small, large) => {
|
|
237
|
+
scale(large);
|
|
238
|
+
if (fits()) {
|
|
239
|
+
if (large === 1) for (const [formula] of formulas) unset(formula, 'font-size');
|
|
240
|
+
return;
|
|
241
|
+
}
|
|
242
|
+
while (large - small > 0.01) {
|
|
243
|
+
const middle = (small + large) / 2;
|
|
244
|
+
scale(middle);
|
|
245
|
+
if (!fits()) large = middle;
|
|
246
|
+
else small = middle;
|
|
247
|
+
}
|
|
248
|
+
scale(small);
|
|
249
|
+
};
|
|
250
|
+
|
|
251
|
+
if (formulas.length) {
|
|
252
|
+
scale(0.5);
|
|
253
|
+
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);
|
|
265
|
+
}
|
|
266
|
+
}
|