@openartifactsai/export-kit 0.0.0-stage → 0.23.0-rc.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/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +5 -2
- package/package.json +36 -4
- package/src/canvas-area.d.ts +29 -0
- package/src/canvas-area.js +37 -0
- package/src/capture-safe.d.ts +32 -0
- package/src/capture-safe.js +190 -0
- package/src/capture.d.ts +120 -0
- package/src/capture.js +301 -0
- package/src/content-bottom.d.ts +50 -0
- package/src/content-bottom.js +131 -0
- package/src/document-measure.d.ts +36 -0
- package/src/document-measure.js +240 -0
- package/src/font-embed.d.ts +71 -0
- package/src/font-embed.js +366 -0
- package/src/font-subset.d.ts +65 -0
- package/src/font-subset.js +627 -0
- package/src/fonts.d.ts +57 -0
- package/src/fonts.js +156 -0
- package/src/index.d.ts +40 -0
- package/src/index.js +40 -0
- package/src/measure.d.ts +53 -0
- package/src/measure.js +116 -0
- package/src/outline.d.ts +73 -0
- package/src/outline.js +160 -0
- package/src/page-image.d.ts +104 -0
- package/src/page-image.js +507 -0
- package/src/pagination.d.ts +79 -0
- package/src/pagination.js +193 -0
- package/src/pdf-text.d.ts +31 -0
- package/src/pdf-text.js +45 -0
- package/src/pictures.d.ts +45 -0
- package/src/pictures.js +125 -0
- package/src/text-layer.d.ts +55 -0
- package/src/text-layer.js +48 -0
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Measuring a rendered document for a PDF: the words drawn (for the
|
|
3
|
+
* invisible, selectable text layer), the web links, the spans a page cut
|
|
4
|
+
* must not fall inside, the blocks kept with their neighbours, and the
|
|
5
|
+
* places a page is told to break. The pure parts live in text-layer.ts
|
|
6
|
+
* (line grouping), pdf-text.ts and pagination.ts.
|
|
7
|
+
*
|
|
8
|
+
* Every measure is in document px: the measured frame is never scrolled, so
|
|
9
|
+
* client rects are document coordinates.
|
|
10
|
+
*/
|
|
11
|
+
import { isDrawn, measureLinks, measureWords } from "./measure.js";
|
|
12
|
+
import { MAX_UNSPLIT_PICTURE } from "./pagination.js";
|
|
13
|
+
const styleOf = (element) => element.ownerDocument.defaultView.getComputedStyle(element);
|
|
14
|
+
/** Is this element (and every ancestor) drawn? */
|
|
15
|
+
const drawn = (element, cache) => isDrawn(element, null, cache);
|
|
16
|
+
/** The words drawn in the document, in reading (document) order. */
|
|
17
|
+
export function documentWords(doc) {
|
|
18
|
+
return measureWords(doc.body ?? doc.documentElement, {
|
|
19
|
+
origin: 'client',
|
|
20
|
+
drawnWithin: null,
|
|
21
|
+
skip: /^(script|style|template|noscript|textarea|title)$/i,
|
|
22
|
+
brokenWord: 'extent',
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
/** The clickable boxes of web links that are drawn. */
|
|
26
|
+
export function documentLinks(doc) {
|
|
27
|
+
return measureLinks(doc.documentElement, { origin: 'client', drawnWithin: null, drawnOnly: true });
|
|
28
|
+
}
|
|
29
|
+
/** The paper colour: the body's background, else the root's, else white. */
|
|
30
|
+
export function documentBackground(doc) {
|
|
31
|
+
for (const element of [doc.body, doc.documentElement]) {
|
|
32
|
+
if (!element)
|
|
33
|
+
continue;
|
|
34
|
+
const color = styleOf(element).backgroundColor;
|
|
35
|
+
if (color && color !== 'transparent' && !/^rgba\(.*,\s*0\)$/.test(color))
|
|
36
|
+
return color;
|
|
37
|
+
}
|
|
38
|
+
return '#ffffff';
|
|
39
|
+
}
|
|
40
|
+
const PICTURES = 'img, svg, video, canvas, picture, iframe, object, embed';
|
|
41
|
+
/**
|
|
42
|
+
* Spans a page cut must not fall inside: each drawn text line, and each
|
|
43
|
+
* picture up to {@link MAX_UNSPLIT_PICTURE} px tall (taller ones are cut
|
|
44
|
+
* where the page ends).
|
|
45
|
+
*/
|
|
46
|
+
export function documentBands(doc) {
|
|
47
|
+
const root = doc.body ?? doc.documentElement;
|
|
48
|
+
const bands = [];
|
|
49
|
+
const shown = new Map();
|
|
50
|
+
const range = doc.createRange();
|
|
51
|
+
const walker = doc.createTreeWalker(root, NodeFilter.SHOW_TEXT);
|
|
52
|
+
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
|
|
53
|
+
if (!node.nodeValue?.trim())
|
|
54
|
+
continue;
|
|
55
|
+
const parent = node.parentElement;
|
|
56
|
+
if (!parent || /^(script|style|template|noscript|title)$/i.test(parent.localName) || !drawn(parent, shown))
|
|
57
|
+
continue;
|
|
58
|
+
range.selectNodeContents(node);
|
|
59
|
+
for (const rect of range.getClientRects())
|
|
60
|
+
if (rect.height > 0 && rect.width > 0)
|
|
61
|
+
bands.push([rect.top, rect.bottom]);
|
|
62
|
+
}
|
|
63
|
+
for (const picture of root.querySelectorAll(PICTURES)) {
|
|
64
|
+
// An svg inside another picture is part of it.
|
|
65
|
+
if (picture.parentElement?.closest('svg, picture'))
|
|
66
|
+
continue;
|
|
67
|
+
if (!drawn(picture, shown))
|
|
68
|
+
continue;
|
|
69
|
+
const rect = picture.getBoundingClientRect();
|
|
70
|
+
if (rect.height > 0 && rect.height <= MAX_UNSPLIT_PICTURE)
|
|
71
|
+
bands.push([rect.top, rect.bottom]);
|
|
72
|
+
}
|
|
73
|
+
return bands;
|
|
74
|
+
}
|
|
75
|
+
/** Boxes the page draws around things: a border above and below, a shadow, or a fill of its own. */
|
|
76
|
+
function boxed(style) {
|
|
77
|
+
if (style.boxShadow !== '' && style.boxShadow !== 'none')
|
|
78
|
+
return true;
|
|
79
|
+
const side = (name) => style[`border${name}Style`] !== 'none' && parseFloat(style[`border${name}Width`]) > 0;
|
|
80
|
+
if (side('Top') && side('Bottom'))
|
|
81
|
+
return true;
|
|
82
|
+
const fill = style.backgroundColor;
|
|
83
|
+
return fill !== '' && fill !== 'transparent' && !/^rgba\(.*,\s*0\)$/.test(fill);
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Boxes a page cut should not fall inside, as a printer keeps them: what the page asks to keep whole
|
|
87
|
+
* (`break-inside: avoid`), and the boxes it draws (a card: bordered, shadowed or filled) up to `maxBoxHeight` px
|
|
88
|
+
* tall. A taller card is cut between its lines like the rest of the page.
|
|
89
|
+
*/
|
|
90
|
+
export function documentBoxes(doc, maxBoxHeight) {
|
|
91
|
+
const root = doc.body ?? doc.documentElement;
|
|
92
|
+
const shown = new Map();
|
|
93
|
+
const boxes = [];
|
|
94
|
+
for (const element of root.querySelectorAll('*')) {
|
|
95
|
+
if (element.namespaceURI !== 'http://www.w3.org/1999/xhtml')
|
|
96
|
+
continue;
|
|
97
|
+
const style = styleOf(element);
|
|
98
|
+
if (style.display === 'none' || style.display === 'contents' || style.display === 'inline')
|
|
99
|
+
continue;
|
|
100
|
+
const asked = style.breakInside === 'avoid' || style.breakInside === 'avoid-page' || style.getPropertyValue('page-break-inside') === 'avoid';
|
|
101
|
+
if (!asked && !boxed(style))
|
|
102
|
+
continue;
|
|
103
|
+
const rect = element.getBoundingClientRect();
|
|
104
|
+
if (!(rect.height >= 8 && rect.width >= 8) || (!asked && rect.height > maxBoxHeight))
|
|
105
|
+
continue;
|
|
106
|
+
if (!drawn(element, shown))
|
|
107
|
+
continue;
|
|
108
|
+
boxes.push([rect.top, rect.bottom]);
|
|
109
|
+
}
|
|
110
|
+
return boxes;
|
|
111
|
+
}
|
|
112
|
+
/** Headings, captions and header rows, with the run each is kept with (see pagination.ts). */
|
|
113
|
+
export function documentKeepBlocks(doc) {
|
|
114
|
+
const root = doc.body ?? doc.documentElement;
|
|
115
|
+
const range = doc.createRange();
|
|
116
|
+
const blocks = [];
|
|
117
|
+
const inFlow = (element) => {
|
|
118
|
+
const style = styleOf(element);
|
|
119
|
+
return style.display !== 'none' && style.position !== 'absolute' && style.position !== 'fixed';
|
|
120
|
+
};
|
|
121
|
+
const measure = (element) => {
|
|
122
|
+
if (!inFlow(element))
|
|
123
|
+
return null;
|
|
124
|
+
const visible = typeof element.checkVisibility !== 'function' || element.checkVisibility({ visibilityProperty: true, opacityProperty: true });
|
|
125
|
+
if (!visible)
|
|
126
|
+
return null;
|
|
127
|
+
const rect = element.getBoundingClientRect();
|
|
128
|
+
return rect.height >= 8 && rect.width >= 8 ? rect : null;
|
|
129
|
+
};
|
|
130
|
+
const previousMeasured = (element) => {
|
|
131
|
+
for (let sibling = element.previousElementSibling; sibling; sibling = sibling.previousElementSibling) {
|
|
132
|
+
const rect = measure(sibling);
|
|
133
|
+
if (rect)
|
|
134
|
+
return { element: sibling, rect };
|
|
135
|
+
}
|
|
136
|
+
return null;
|
|
137
|
+
};
|
|
138
|
+
const ancestorsInFlow = (element) => {
|
|
139
|
+
for (let parent = element.parentElement; parent && parent !== root; parent = parent.parentElement)
|
|
140
|
+
if (!inFlow(parent))
|
|
141
|
+
return false;
|
|
142
|
+
return true;
|
|
143
|
+
};
|
|
144
|
+
for (const element of root.querySelectorAll('h1,h2,h3,h4,h5,h6,hgroup,[role=heading],caption,thead,tr:first-child,figcaption')) {
|
|
145
|
+
const tag = element.localName;
|
|
146
|
+
if (tag === 'tr') {
|
|
147
|
+
// Only a header row (all th) that is the table's first row and not in a thead/tfoot.
|
|
148
|
+
const table = element.closest('table');
|
|
149
|
+
const section = element.parentElement?.localName ?? '';
|
|
150
|
+
if (!table || table.querySelector('tr') !== element || section === 'thead' || section === 'tfoot' || !element.querySelector('th') || element.querySelector('td'))
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
const rect = measure(element);
|
|
154
|
+
if (!rect || !ancestorsInFlow(element))
|
|
155
|
+
continue;
|
|
156
|
+
const style = styleOf(element);
|
|
157
|
+
let next = false;
|
|
158
|
+
let prev = false;
|
|
159
|
+
let fromTop = rect.top;
|
|
160
|
+
if (tag === 'caption' && style.captionSide === 'bottom') {
|
|
161
|
+
prev = true;
|
|
162
|
+
const rows = element.parentElement?.localName === 'table' ? element.parentElement.rows : null;
|
|
163
|
+
for (let i = rows ? rows.length - 1 : -1; i >= 0; i--) {
|
|
164
|
+
const row = rows[i].getBoundingClientRect();
|
|
165
|
+
if (row.height > 0) {
|
|
166
|
+
fromTop = row.top;
|
|
167
|
+
break;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
else if (tag === 'figcaption' && previousMeasured(element)) {
|
|
172
|
+
prev = true;
|
|
173
|
+
fromTop = previousMeasured(element).rect.top;
|
|
174
|
+
}
|
|
175
|
+
else
|
|
176
|
+
next = true;
|
|
177
|
+
const pullsLeadIn = next && tag !== 'caption' && tag !== 'thead' && tag !== 'tr' && tag !== 'figcaption';
|
|
178
|
+
range.selectNodeContents(element);
|
|
179
|
+
const content = range.getBoundingClientRect();
|
|
180
|
+
const inset = (parseFloat(style.paddingBottom) || 0) + (parseFloat(style.borderBottomWidth) || 0);
|
|
181
|
+
const top = rect.top;
|
|
182
|
+
const bottom = content.height > 0 ? Math.max(Math.min(rect.bottom, content.bottom + inset), Math.min(top + 1, rect.bottom)) : rect.bottom;
|
|
183
|
+
if (!(bottom > top))
|
|
184
|
+
continue;
|
|
185
|
+
if (pullsLeadIn) {
|
|
186
|
+
const leadInGap = 2 * (parseFloat(style.fontSize) || 0) || 48;
|
|
187
|
+
let anchor = element;
|
|
188
|
+
let anchorTop = rect.top;
|
|
189
|
+
let pulled = 0;
|
|
190
|
+
for (let level = 0; level < 3; level++) {
|
|
191
|
+
for (let sibling = previousMeasured(anchor); sibling && pulled < 2; sibling = previousMeasured(anchor)) {
|
|
192
|
+
const gap = anchorTop - sibling.rect.bottom;
|
|
193
|
+
if (gap < -0.5 || gap > leadInGap || sibling.rect.height > 48 || !(sibling.rect.left < rect.right && sibling.rect.right > rect.left))
|
|
194
|
+
break;
|
|
195
|
+
const before = previousMeasured(sibling.element);
|
|
196
|
+
if (before && !(sibling.rect.top - before.rect.bottom > gap))
|
|
197
|
+
break;
|
|
198
|
+
anchor = sibling.element;
|
|
199
|
+
anchorTop = sibling.rect.top;
|
|
200
|
+
fromTop = Math.min(fromTop, sibling.rect.top);
|
|
201
|
+
pulled += 1;
|
|
202
|
+
}
|
|
203
|
+
const parent = anchor.parentElement;
|
|
204
|
+
if (!parent || parent === root || previousMeasured(anchor))
|
|
205
|
+
break;
|
|
206
|
+
const parentRect = measure(parent);
|
|
207
|
+
if (!parentRect || anchorTop - parentRect.top > 48 || parentRect.top > anchorTop + 0.5)
|
|
208
|
+
break;
|
|
209
|
+
anchor = parent;
|
|
210
|
+
anchorTop = parentRect.top;
|
|
211
|
+
fromTop = Math.min(fromTop, parentRect.top);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
blocks.push({ top, bottom, from: Math.min(fromTop, top), next, prev });
|
|
215
|
+
}
|
|
216
|
+
return blocks;
|
|
217
|
+
}
|
|
218
|
+
/** The full height of the document's content. */
|
|
219
|
+
export function documentHeight(doc) {
|
|
220
|
+
return Math.ceil(Math.max(doc.documentElement.scrollHeight, doc.body?.scrollHeight ?? 0));
|
|
221
|
+
}
|
|
222
|
+
/** `break-before` values that start a new page (the legacy `page-break-before: always` computes to `page`). */
|
|
223
|
+
const PAGE_BREAKS = new Set(['page', 'always', 'left', 'right', 'recto', 'verso']);
|
|
224
|
+
/** Tops of the drawn elements that ask for a new page before them (`break-before: page`), in document px. */
|
|
225
|
+
export function documentPageBreaks(doc) {
|
|
226
|
+
const root = doc.body ?? doc.documentElement;
|
|
227
|
+
const shown = new Map();
|
|
228
|
+
const tops = [];
|
|
229
|
+
for (const element of root.querySelectorAll('*')) {
|
|
230
|
+
const style = styleOf(element);
|
|
231
|
+
if (!PAGE_BREAKS.has(style.breakBefore) && style.getPropertyValue('page-break-before') !== 'always')
|
|
232
|
+
continue;
|
|
233
|
+
if (!drawn(element, shown))
|
|
234
|
+
continue;
|
|
235
|
+
const rect = element.getBoundingClientRect();
|
|
236
|
+
if (rect.height > 0 || rect.width > 0)
|
|
237
|
+
tops.push(rect.top);
|
|
238
|
+
}
|
|
239
|
+
return tops;
|
|
240
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The web fonts of a rendered document, as `@font-face` rules that carry
|
|
3
|
+
* their font files in `data:` URLs.
|
|
4
|
+
*
|
|
5
|
+
* A picture drawn from serialized markup (an SVG loaded as an image) is cut
|
|
6
|
+
* off from the page it came from: it shares none of the page's loaded fonts
|
|
7
|
+
* and may not request any. Text in a web font is drawn in a fallback font
|
|
8
|
+
* instead, and where each line was placed by its measured position, the
|
|
9
|
+
* fallback's different metrics also move it. {@link embeddedFontCss} gives
|
|
10
|
+
* such a drawing the faces the document really uses:
|
|
11
|
+
*
|
|
12
|
+
* - every `@font-face` rule of the document's stylesheets is read: inline
|
|
13
|
+
* `<style>`s, linked and imported sheets, rules inside `@media` or
|
|
14
|
+
* `@layer`. A sheet from another origin (Google Fonts through a plain
|
|
15
|
+
* `<link>`) hides its rules from script, so its text is fetched instead;
|
|
16
|
+
* - of those, only the faces the browser loaded for this document are kept
|
|
17
|
+
* (it loads a face when some text needs it), so a family split into a
|
|
18
|
+
* hundred `unicode-range` files costs the few that are in use;
|
|
19
|
+
* - each kept face's first loadable source is fetched and inlined.
|
|
20
|
+
*
|
|
21
|
+
* The browser parses an inlined font again for every picture, about 30 ms of
|
|
22
|
+
* main thread a megabyte, and a CJK font runs to tens of megabytes. So a
|
|
23
|
+
* TrueType file is inlined as a subset where it can be (font-subset.ts): the
|
|
24
|
+
* outlines of the ideographs and Hangul syllables the document cannot draw
|
|
25
|
+
* are dropped, everything else is kept as it is. The code points it may draw
|
|
26
|
+
* are read from its text, attribute values, form field values, open shadow
|
|
27
|
+
* roots and stylesheet text (generated content), plus the ideographs list
|
|
28
|
+
* counters make, each also in the forms the shaper normalizes it to (NFC:
|
|
29
|
+
* conjoining jamo become syllables, compatibility ideographs unified ones),
|
|
30
|
+
* since those are the glyphs it looks up. Left whole: CFF (OpenType-CFF) fonts, variable fonts with
|
|
31
|
+
* `gvar`, WOFF and WOFF2 files, TrueType collections, AAT (`morx`) fonts,
|
|
32
|
+
* and fonts with too few ideographs to be worth it.
|
|
33
|
+
*
|
|
34
|
+
* Font files stay cached between captures (the same fonts are drawn again
|
|
35
|
+
* for every artboard and every page), within {@link FONT_CACHE_BYTES}, and
|
|
36
|
+
* so do the `data:` URLs made from them, within {@link INLINED_CACHE_BYTES}.
|
|
37
|
+
*
|
|
38
|
+
* Needs a DOM.
|
|
39
|
+
*/
|
|
40
|
+
/** What {@link embeddedFontCss} made. */
|
|
41
|
+
export interface EmbeddedFonts {
|
|
42
|
+
/** Self-contained `@font-face` rules. */
|
|
43
|
+
css: string;
|
|
44
|
+
/** Families (as written) with a face left out: over the budget, or its file could not be read. */
|
|
45
|
+
skipped: string[];
|
|
46
|
+
}
|
|
47
|
+
/** Options of {@link embeddedFontCss}. */
|
|
48
|
+
export interface EmbedFontsOptions {
|
|
49
|
+
/** Most font data to inline, characters of `data:` URL (default: no limit). Faces that do not fit are left out. */
|
|
50
|
+
maxBytes?: number;
|
|
51
|
+
/** Inline TrueType fonts as subsets holding only the ideographs and Hangul the document uses (default true). */
|
|
52
|
+
subset?: boolean;
|
|
53
|
+
}
|
|
54
|
+
/** What has been inlined since the page loaded: for tests and debugging. */
|
|
55
|
+
export interface FontEmbedStats {
|
|
56
|
+
/** Fonts inlined as subsets. */
|
|
57
|
+
subsets: number;
|
|
58
|
+
/** Their size, characters of `data:` URL. */
|
|
59
|
+
subsetBytes: number;
|
|
60
|
+
/** Size of the font files inlined whole, characters of `data:` URL (sources already inline not counted). */
|
|
61
|
+
wholeBytes: number;
|
|
62
|
+
}
|
|
63
|
+
/** Fonts inlined as subsets and whole since the page loaded. */
|
|
64
|
+
export declare function fontEmbedStats(): FontEmbedStats;
|
|
65
|
+
/**
|
|
66
|
+
* `@font-face` rules for the web fonts the document draws its text with,
|
|
67
|
+
* their files inlined as `data:` URLs: what a picture of the document needs
|
|
68
|
+
* to show the same fonts. Call it once the document's fonts have loaded
|
|
69
|
+
* (`document.fonts.ready`); a face still loading is not in use yet.
|
|
70
|
+
*/
|
|
71
|
+
export declare function embeddedFontCss(doc: Document, options?: EmbedFontsOptions): Promise<EmbeddedFonts>;
|
|
@@ -0,0 +1,366 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The web fonts of a rendered document, as `@font-face` rules that carry
|
|
3
|
+
* their font files in `data:` URLs.
|
|
4
|
+
*
|
|
5
|
+
* A picture drawn from serialized markup (an SVG loaded as an image) is cut
|
|
6
|
+
* off from the page it came from: it shares none of the page's loaded fonts
|
|
7
|
+
* and may not request any. Text in a web font is drawn in a fallback font
|
|
8
|
+
* instead, and where each line was placed by its measured position, the
|
|
9
|
+
* fallback's different metrics also move it. {@link embeddedFontCss} gives
|
|
10
|
+
* such a drawing the faces the document really uses:
|
|
11
|
+
*
|
|
12
|
+
* - every `@font-face` rule of the document's stylesheets is read: inline
|
|
13
|
+
* `<style>`s, linked and imported sheets, rules inside `@media` or
|
|
14
|
+
* `@layer`. A sheet from another origin (Google Fonts through a plain
|
|
15
|
+
* `<link>`) hides its rules from script, so its text is fetched instead;
|
|
16
|
+
* - of those, only the faces the browser loaded for this document are kept
|
|
17
|
+
* (it loads a face when some text needs it), so a family split into a
|
|
18
|
+
* hundred `unicode-range` files costs the few that are in use;
|
|
19
|
+
* - each kept face's first loadable source is fetched and inlined.
|
|
20
|
+
*
|
|
21
|
+
* The browser parses an inlined font again for every picture, about 30 ms of
|
|
22
|
+
* main thread a megabyte, and a CJK font runs to tens of megabytes. So a
|
|
23
|
+
* TrueType file is inlined as a subset where it can be (font-subset.ts): the
|
|
24
|
+
* outlines of the ideographs and Hangul syllables the document cannot draw
|
|
25
|
+
* are dropped, everything else is kept as it is. The code points it may draw
|
|
26
|
+
* are read from its text, attribute values, form field values, open shadow
|
|
27
|
+
* roots and stylesheet text (generated content), plus the ideographs list
|
|
28
|
+
* counters make, each also in the forms the shaper normalizes it to (NFC:
|
|
29
|
+
* conjoining jamo become syllables, compatibility ideographs unified ones),
|
|
30
|
+
* since those are the glyphs it looks up. Left whole: CFF (OpenType-CFF) fonts, variable fonts with
|
|
31
|
+
* `gvar`, WOFF and WOFF2 files, TrueType collections, AAT (`morx`) fonts,
|
|
32
|
+
* and fonts with too few ideographs to be worth it.
|
|
33
|
+
*
|
|
34
|
+
* Font files stay cached between captures (the same fonts are drawn again
|
|
35
|
+
* for every artboard and every page), within {@link FONT_CACHE_BYTES}, and
|
|
36
|
+
* so do the `data:` URLs made from them, within {@link INLINED_CACHE_BYTES}.
|
|
37
|
+
*
|
|
38
|
+
* Needs a DOM.
|
|
39
|
+
*/
|
|
40
|
+
import { blockUnicodeRange, faceKey, familyName, fontFaceBlocks, fontFaceDescriptors, fontSources, parseUnicodeRange, rangeCovers } from "./fonts.js";
|
|
41
|
+
import { addBulkCodePoints, COUNTER_IDEOGRAPHS, subsetFont } from "./font-subset.js";
|
|
42
|
+
import { blobToDataUrl } from "./pictures.js";
|
|
43
|
+
/** How long a stylesheet or a font file may take, ms. */
|
|
44
|
+
const FETCH_TIMEOUT = 15_000;
|
|
45
|
+
/** Font files kept between captures, bytes. */
|
|
46
|
+
const FONT_CACHE_BYTES = 64 * 1024 * 1024;
|
|
47
|
+
/** Inlined fonts (subsets, and files inlined whole) kept between captures, characters of `data:` URL. */
|
|
48
|
+
const INLINED_CACHE_BYTES = 32 * 1024 * 1024;
|
|
49
|
+
/** Formats no current browser loads from a `data:` URL. */
|
|
50
|
+
const DEAD_FORMATS = /embedded-opentype|svg/;
|
|
51
|
+
const stats = { subsets: 0, subsetBytes: 0, wholeBytes: 0 };
|
|
52
|
+
/** Fonts inlined as subsets and whole since the page loaded. */
|
|
53
|
+
export function fontEmbedStats() {
|
|
54
|
+
return { ...stats };
|
|
55
|
+
}
|
|
56
|
+
async function fetched(url) {
|
|
57
|
+
try {
|
|
58
|
+
const response = await fetch(url, { signal: AbortSignal.timeout(FETCH_TIMEOUT) });
|
|
59
|
+
return response.ok ? response : null;
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
/** Text of stylesheets whose rules script may not read, by address. */
|
|
66
|
+
const sheetTexts = new Map();
|
|
67
|
+
function sheetText(url) {
|
|
68
|
+
let text = sheetTexts.get(url);
|
|
69
|
+
if (!text) {
|
|
70
|
+
text = fetched(url).then((response) => response?.text() ?? null, () => null);
|
|
71
|
+
sheetTexts.set(url, text);
|
|
72
|
+
// A sheet that could not be read is asked for again next time.
|
|
73
|
+
void text.then((value) => value === null && sheetTexts.delete(url));
|
|
74
|
+
}
|
|
75
|
+
return text;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Values made on demand and kept, least recently used first, within a size.
|
|
79
|
+
* A request still in flight is shared; a null result (a failure) is not kept.
|
|
80
|
+
*/
|
|
81
|
+
class Lru {
|
|
82
|
+
entries = new Map();
|
|
83
|
+
bytes = 0;
|
|
84
|
+
limit;
|
|
85
|
+
sizeOf;
|
|
86
|
+
constructor(limit, sizeOf) {
|
|
87
|
+
this.limit = limit;
|
|
88
|
+
this.sizeOf = sizeOf;
|
|
89
|
+
}
|
|
90
|
+
get(key, make) {
|
|
91
|
+
const hit = this.entries.get(key);
|
|
92
|
+
if (hit) {
|
|
93
|
+
this.entries.delete(key);
|
|
94
|
+
this.entries.set(key, hit);
|
|
95
|
+
return hit.value;
|
|
96
|
+
}
|
|
97
|
+
const entry = { value: make().catch(() => null), size: 0 };
|
|
98
|
+
this.entries.set(key, entry);
|
|
99
|
+
void entry.value.then((value) => {
|
|
100
|
+
if (this.entries.get(key) !== entry)
|
|
101
|
+
return;
|
|
102
|
+
if (value === null) {
|
|
103
|
+
this.entries.delete(key);
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
entry.size = this.sizeOf(value);
|
|
107
|
+
this.bytes += entry.size;
|
|
108
|
+
for (const [old, other] of this.entries) {
|
|
109
|
+
if (this.bytes <= this.limit)
|
|
110
|
+
break;
|
|
111
|
+
if (other === entry || !other.size)
|
|
112
|
+
continue;
|
|
113
|
+
this.entries.delete(old);
|
|
114
|
+
this.bytes -= other.size;
|
|
115
|
+
}
|
|
116
|
+
});
|
|
117
|
+
return entry.value;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
/** Font files by address. */
|
|
121
|
+
const fontFiles = new Lru(FONT_CACHE_BYTES, (file) => file.bytes.byteLength);
|
|
122
|
+
function fontFile(url) {
|
|
123
|
+
return fontFiles.get(url, async () => {
|
|
124
|
+
const response = await fetched(url);
|
|
125
|
+
if (!response)
|
|
126
|
+
return null;
|
|
127
|
+
const blob = await response.blob();
|
|
128
|
+
return { bytes: new Uint8Array(await blob.arrayBuffer()), type: blob.type };
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
/** Inlined fonts as `data:` URLs: by address for a whole file, by address and code points for a subset. */
|
|
132
|
+
const inlinedFonts = new Lru(INLINED_CACHE_BYTES, (data) => data.length);
|
|
133
|
+
/** A font file as a `data:` URL: a subset when `used` is given and the font allows one, else the whole file. */
|
|
134
|
+
async function inlinedFont(address, used) {
|
|
135
|
+
const file = await fontFile(address);
|
|
136
|
+
if (!file)
|
|
137
|
+
return null;
|
|
138
|
+
if (used) {
|
|
139
|
+
const data = await inlinedFonts.get(`${address}\n${used.key}`, async () => {
|
|
140
|
+
const smaller = subsetFont(file.bytes, used.points);
|
|
141
|
+
return smaller ? blobToDataUrl(new Blob([smaller], { type: 'font/ttf' })) : null;
|
|
142
|
+
});
|
|
143
|
+
if (data)
|
|
144
|
+
return { data, subset: true };
|
|
145
|
+
}
|
|
146
|
+
const data = await inlinedFonts.get(address, () => blobToDataUrl(new Blob([file.bytes], { type: file.type })));
|
|
147
|
+
return data ? { data, subset: false } : null;
|
|
148
|
+
}
|
|
149
|
+
/** Adds the bulk code points of a document's (or a shadow root's) text, attribute values and form field values. */
|
|
150
|
+
function addDocumentBulk(root, into) {
|
|
151
|
+
addBulkCodePoints(('documentElement' in root ? root.documentElement?.textContent : root.textContent) ?? '', into);
|
|
152
|
+
for (const element of Array.from(root.querySelectorAll('*'))) {
|
|
153
|
+
for (const attribute of Array.from(element.attributes))
|
|
154
|
+
addBulkCodePoints(attribute.value, into);
|
|
155
|
+
// Told apart by tag, not `instanceof`: the element may belong to another frame's realm.
|
|
156
|
+
if (element.localName === 'input' || element.localName === 'textarea')
|
|
157
|
+
addBulkCodePoints(element.value ?? '', into);
|
|
158
|
+
if (element.shadowRoot)
|
|
159
|
+
addDocumentBulk(element.shadowRoot, into);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
/** Every `@font-face` rule of the document, in stylesheet order. Adds the bulk code points of every rule's text to `used`. */
|
|
163
|
+
async function documentFaces(doc, used) {
|
|
164
|
+
const found = [];
|
|
165
|
+
const seen = new Set();
|
|
166
|
+
const unreadable = (href) => {
|
|
167
|
+
found.push(sheetText(href).then((text) => {
|
|
168
|
+
if (!text)
|
|
169
|
+
return [];
|
|
170
|
+
addBulkCodePoints(text, used);
|
|
171
|
+
return fontFaceBlocks(text).map((css) => ({ css, base: href }));
|
|
172
|
+
}));
|
|
173
|
+
};
|
|
174
|
+
const sheet = (styles, base) => {
|
|
175
|
+
if (seen.has(styles))
|
|
176
|
+
return;
|
|
177
|
+
seen.add(styles);
|
|
178
|
+
const own = styles.href ?? base;
|
|
179
|
+
let rules;
|
|
180
|
+
try {
|
|
181
|
+
rules = styles.cssRules;
|
|
182
|
+
}
|
|
183
|
+
catch {
|
|
184
|
+
// Another origin's sheet, loaded without CORS.
|
|
185
|
+
if (styles.href)
|
|
186
|
+
unreadable(styles.href);
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
walk(rules, own);
|
|
190
|
+
};
|
|
191
|
+
const walk = (rules, base) => {
|
|
192
|
+
// Rules belong to the frame's realm: told apart by what they hold, not by `instanceof`.
|
|
193
|
+
for (const rule of Array.from(rules)) {
|
|
194
|
+
const text = rule.cssText;
|
|
195
|
+
if (/^@font-face\b/i.test(text))
|
|
196
|
+
found.push({ css: text, base });
|
|
197
|
+
else if ('styleSheet' in rule && 'href' in rule) {
|
|
198
|
+
const imported = rule.styleSheet;
|
|
199
|
+
if (imported)
|
|
200
|
+
sheet(imported, base);
|
|
201
|
+
}
|
|
202
|
+
else if ('cssRules' in rule)
|
|
203
|
+
walk(rule.cssRules, base);
|
|
204
|
+
// Generated content (`content: "…"`, `quotes`, counter `symbols`) draws text no element holds.
|
|
205
|
+
else
|
|
206
|
+
addBulkCodePoints(text, used);
|
|
207
|
+
}
|
|
208
|
+
};
|
|
209
|
+
for (const styles of [...Array.from(doc.styleSheets), ...(doc.adoptedStyleSheets ?? [])])
|
|
210
|
+
sheet(styles, doc.baseURI);
|
|
211
|
+
return (await Promise.all(found)).flat();
|
|
212
|
+
}
|
|
213
|
+
/** The faces the browser loaded for the document, as {@link faceKey}s by family; null when it does not say. */
|
|
214
|
+
function loadedFaces(doc) {
|
|
215
|
+
const fonts = doc.fonts;
|
|
216
|
+
if (!fonts || typeof fonts.forEach !== 'function')
|
|
217
|
+
return null;
|
|
218
|
+
const loaded = new Map();
|
|
219
|
+
fonts.forEach((face) => {
|
|
220
|
+
if (face.status !== 'loaded')
|
|
221
|
+
return;
|
|
222
|
+
const family = familyName(face.family);
|
|
223
|
+
let keys = loaded.get(family);
|
|
224
|
+
if (!keys)
|
|
225
|
+
loaded.set(family, (keys = new Set()));
|
|
226
|
+
keys.add(faceKey({ family: face.family, weight: face.weight, style: face.style, unicodeRange: face.unicodeRange }));
|
|
227
|
+
});
|
|
228
|
+
return loaded;
|
|
229
|
+
}
|
|
230
|
+
/** The faces the document draws text with. */
|
|
231
|
+
async function usedFaces(doc, used) {
|
|
232
|
+
const faces = await documentFaces(doc, used);
|
|
233
|
+
if (!faces.length)
|
|
234
|
+
return faces;
|
|
235
|
+
const loaded = loadedFaces(doc);
|
|
236
|
+
let points;
|
|
237
|
+
/** By `unicode-range` alone: when the browser's own account cannot be matched to the rules. */
|
|
238
|
+
const coversText = (css) => {
|
|
239
|
+
points ??= new Set(Array.from(doc.documentElement.textContent ?? '', (char) => char.codePointAt(0)));
|
|
240
|
+
return rangeCovers(parseUnicodeRange(blockUnicodeRange(css)), points);
|
|
241
|
+
};
|
|
242
|
+
if (!loaded)
|
|
243
|
+
return faces.filter((face) => coversText(face.css));
|
|
244
|
+
const read = faces.map((face) => {
|
|
245
|
+
const descriptors = fontFaceDescriptors(face.css);
|
|
246
|
+
const family = familyName(descriptors.get('font-family'));
|
|
247
|
+
const key = faceKey({ family, weight: descriptors.get('font-weight'), style: descriptors.get('font-style'), unicodeRange: descriptors.get('unicode-range') });
|
|
248
|
+
return { face, family, key, exact: Boolean(loaded.get(family)?.has(key)) };
|
|
249
|
+
});
|
|
250
|
+
// A loaded face no rule accounts for (traits spelled in a way the keys do not level): its family goes by range.
|
|
251
|
+
const ruleKeys = new Set(read.map((item) => item.key));
|
|
252
|
+
const loose = new Set();
|
|
253
|
+
for (const [family, keys] of loaded)
|
|
254
|
+
for (const key of keys)
|
|
255
|
+
if (!ruleKeys.has(key))
|
|
256
|
+
loose.add(family);
|
|
257
|
+
return read.filter((item) => item.exact || (loose.has(item.family) && coversText(item.face.css))).map((item) => item.face);
|
|
258
|
+
}
|
|
259
|
+
/** The face with its first loadable source inlined; null when none could be read, `'large'` when it does not fit. */
|
|
260
|
+
async function embeddedFace(face, budget, used) {
|
|
261
|
+
const descriptors = fontFaceDescriptors(face.css);
|
|
262
|
+
const sources = [];
|
|
263
|
+
let inlined = false;
|
|
264
|
+
for (const source of fontSources(descriptors.get('src') ?? '')) {
|
|
265
|
+
if (!source.url) {
|
|
266
|
+
// `local(…)` works inside a picture as it does on the page.
|
|
267
|
+
sources.push(source.text);
|
|
268
|
+
continue;
|
|
269
|
+
}
|
|
270
|
+
if (inlined || (source.format && DEAD_FORMATS.test(source.format)))
|
|
271
|
+
continue;
|
|
272
|
+
let data;
|
|
273
|
+
let subset = null;
|
|
274
|
+
if (source.url.url.startsWith('data:'))
|
|
275
|
+
data = source.url.url;
|
|
276
|
+
else {
|
|
277
|
+
let address;
|
|
278
|
+
try {
|
|
279
|
+
address = new URL(source.url.url, face.base).href;
|
|
280
|
+
}
|
|
281
|
+
catch {
|
|
282
|
+
continue;
|
|
283
|
+
}
|
|
284
|
+
const font = await inlinedFont(address, used);
|
|
285
|
+
data = font?.data ?? null;
|
|
286
|
+
subset = font?.subset ?? null;
|
|
287
|
+
}
|
|
288
|
+
if (!data)
|
|
289
|
+
continue;
|
|
290
|
+
if (data.length > budget.left)
|
|
291
|
+
return 'large';
|
|
292
|
+
budget.left -= data.length;
|
|
293
|
+
if (subset) {
|
|
294
|
+
stats.subsets++;
|
|
295
|
+
stats.subsetBytes += data.length;
|
|
296
|
+
}
|
|
297
|
+
else if (subset === false)
|
|
298
|
+
stats.wholeBytes += data.length;
|
|
299
|
+
sources.push(source.text.replace(source.url.match, () => `url("${data}")`));
|
|
300
|
+
inlined = true;
|
|
301
|
+
}
|
|
302
|
+
if (!inlined)
|
|
303
|
+
return null;
|
|
304
|
+
descriptors.set('src', sources.join(', '));
|
|
305
|
+
return `@font-face{${Array.from(descriptors, ([name, value]) => `${name}:${value}`).join(';')}}`;
|
|
306
|
+
}
|
|
307
|
+
async function embed(faces, maxBytes, used) {
|
|
308
|
+
// Start every download at once; the pass below takes them in order, so the budget goes to the first rules.
|
|
309
|
+
for (const face of faces) {
|
|
310
|
+
const first = fontSources(fontFaceDescriptors(face.css).get('src') ?? '').find((source) => source.url && !(source.format && DEAD_FORMATS.test(source.format)));
|
|
311
|
+
if (!first?.url || first.url.url.startsWith('data:'))
|
|
312
|
+
continue;
|
|
313
|
+
try {
|
|
314
|
+
void fontFile(new URL(first.url.url, face.base).href);
|
|
315
|
+
}
|
|
316
|
+
catch {
|
|
317
|
+
// An address that does not parse is passed over again below.
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
const budget = { left: maxBytes };
|
|
321
|
+
const rules = [];
|
|
322
|
+
const skipped = new Set();
|
|
323
|
+
let unread = false;
|
|
324
|
+
for (const face of faces) {
|
|
325
|
+
const rule = await embeddedFace(face, budget, used);
|
|
326
|
+
if (rule === null || rule === 'large') {
|
|
327
|
+
skipped.add((fontFaceDescriptors(face.css).get('font-family') ?? '').replace(/^(['"])(.*)\1$/, '$2'));
|
|
328
|
+
unread ||= rule === null;
|
|
329
|
+
}
|
|
330
|
+
else
|
|
331
|
+
rules.push(rule);
|
|
332
|
+
}
|
|
333
|
+
return { css: rules.join('\n'), skipped: [...skipped].filter(Boolean), unread };
|
|
334
|
+
}
|
|
335
|
+
/** The last result per document, and what it was made from. */
|
|
336
|
+
const made = new WeakMap();
|
|
337
|
+
/**
|
|
338
|
+
* `@font-face` rules for the web fonts the document draws its text with,
|
|
339
|
+
* their files inlined as `data:` URLs: what a picture of the document needs
|
|
340
|
+
* to show the same fonts. Call it once the document's fonts have loaded
|
|
341
|
+
* (`document.fonts.ready`); a face still loading is not in use yet.
|
|
342
|
+
*/
|
|
343
|
+
export async function embeddedFontCss(doc, options = {}) {
|
|
344
|
+
const maxBytes = options.maxBytes ?? Infinity;
|
|
345
|
+
const points = new Set();
|
|
346
|
+
const faces = await usedFaces(doc, points);
|
|
347
|
+
if (!faces.length)
|
|
348
|
+
return { css: '', skipped: [] };
|
|
349
|
+
let used = null;
|
|
350
|
+
if (options.subset ?? true) {
|
|
351
|
+
addBulkCodePoints(COUNTER_IDEOGRAPHS, points);
|
|
352
|
+
addDocumentBulk(doc, points);
|
|
353
|
+
used = { points, key: Array.from(points, (point) => String.fromCodePoint(point)).sort().join('') };
|
|
354
|
+
}
|
|
355
|
+
// A subset holds the characters of the text it was made for: an edit makes another.
|
|
356
|
+
const from = `${maxBytes}\n${used ? used.key : '*'}\n${faces.map((face) => `${face.base}\n${face.css}`).join('\n')}`;
|
|
357
|
+
const last = made.get(doc);
|
|
358
|
+
if (last?.from === from)
|
|
359
|
+
return last.fonts;
|
|
360
|
+
const work = embed(faces, maxBytes, used);
|
|
361
|
+
const fonts = work.then(({ css, skipped }) => ({ css, skipped }));
|
|
362
|
+
made.set(doc, { from, fonts });
|
|
363
|
+
// A font that could not be read may be there next time.
|
|
364
|
+
void work.then((result) => result.unread && made.get(doc)?.fonts === fonts && made.delete(doc));
|
|
365
|
+
return fonts;
|
|
366
|
+
}
|