@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.
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Capturing rendered DOM as pictures, two ways:
3
+ *
4
+ * - through an SVG `<foreignObject>`: a copy of the markup with every
5
+ * picture inlined as a `data:` URL ({@link inlinedCopy}) is wrapped in an
6
+ * SVG document ({@link foreignObjectSvg}), loaded as an image
7
+ * ({@link loadSvgImage}) and drawn onto a canvas. It keeps everything the
8
+ * browser can draw, but some browsers refuse to read the canvas back;
9
+ * - with dom-to-svg ({@link elementSvg}), which rebuilds the element as
10
+ * plain SVG shapes: a vector drawing that pastes into design tools, and
11
+ * the fallback when the first way fails.
12
+ *
13
+ * What is captured (a slide, an artboard's element) and how the result is
14
+ * drawn stays with each editor.
15
+ */
16
+ /** A transparent 1×1 GIF: stands in for pictures a capture leaves out. */
17
+ export declare const BLANK_GIF = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
18
+ export declare const SVG_NS = "http://www.w3.org/2000/svg";
19
+ export declare const XHTML_NS = "http://www.w3.org/1999/xhtml";
20
+ /** How large a capture may be. */
21
+ export interface CaptureLimits {
22
+ /** Largest side, px. */
23
+ maxSide: number;
24
+ /** Most pixels in one capture. */
25
+ maxPixels: number;
26
+ }
27
+ /** The largest scale an area of `width` × `height` can be drawn at within `limits`. */
28
+ export declare function maxCaptureScale(width: number, height: number, limits: CaptureLimits): number;
29
+ /** Resolves once every picture in the element loaded (or failed, or took longer than `timeout` ms) and decoded. */
30
+ export declare function picturesReady(root: ParentNode, timeout: number): Promise<void>;
31
+ /**
32
+ * Hides everything under `root` but `target` (live elements or a copy), so a
33
+ * capture draws only the target where it sits. `bare` also hides what the
34
+ * target holds (its background and border only). Returns an undo.
35
+ */
36
+ export declare function hideOutside(root: HTMLElement, target: Element | undefined, bare: boolean): () => void;
37
+ /** How {@link inlinedCopy} reads and replaces pictures. */
38
+ export interface InlineOptions {
39
+ /** A picture's address as a `data:` URL, or null when it cannot be read. */
40
+ dataUrl: (src: string) => Promise<string | null>;
41
+ /**
42
+ * What becomes of a picture that cannot be read. `leave`: an `<img>`
43
+ * loses its `src`; an SVG `<image>` and a style's `url(…)` keep their
44
+ * address. `blank`: each becomes {@link BLANK_GIF}.
45
+ */
46
+ unreadable: 'leave' | 'blank';
47
+ /** Called with each `<img>` source and style `url(…)` that could not be read. */
48
+ onMissing?: (src: string) => void;
49
+ /** Inlines only pictures in this element; `<img>`s outside it are blanked (their size kept) so the copy stays small, and it alone is shown. */
50
+ only?: Element;
51
+ /** With `only`: hides what the element holds (see {@link hideOutside}). */
52
+ bare?: boolean;
53
+ }
54
+ /** Replaces `url(…)` references in an element's inline style with `data:` URLs. */
55
+ export declare function inlineStyleUrls(el: Element, options: Pick<InlineOptions, 'dataUrl' | 'unreadable' | 'onMissing'>): Promise<void>;
56
+ /** A copy of the element's markup with every picture inlined, ready to be drawn in isolation. */
57
+ export declare function inlinedCopy(root: HTMLElement, options: InlineOptions): Promise<HTMLElement>;
58
+ /** Escapes text (such as CSS) for an XML text node. */
59
+ export declare function xmlText(text: string): string;
60
+ /** The size of a {@link foreignObjectSvg} drawing. */
61
+ export interface ForeignObjectSize {
62
+ /** The markup's layout size, CSS px (also the view box). */
63
+ width: number;
64
+ height: number;
65
+ /** The SVG's own size (default: the layout size). */
66
+ outerWidth?: number;
67
+ outerHeight?: number;
68
+ /**
69
+ * The device pixels per CSS px the markup was laid out at (its window's `devicePixelRatio`). An SVG image is laid
70
+ * out at 1, and some text is as wide as its size in device pixels says (the system font's Han glyphs on macOS), so
71
+ * lines measured on a 2× screen would wrap elsewhere in the drawing. With it, the drawing lays out zoomed by as
72
+ * much and is scaled back, and its text is as wide as it was measured.
73
+ */
74
+ zoom?: number;
75
+ }
76
+ /** An SVG document drawing serialized XHTML `markup`, styled by `css`, through a `<foreignObject>`. */
77
+ export declare function foreignObjectSvg(markup: string, css: string, size: ForeignObjectSize): string;
78
+ /** Loads an SVG document as an image (from a `data:` URL), decoded; rejects with `error` when it will not load. */
79
+ export declare function loadSvgImage(svg: string, options: {
80
+ error: string;
81
+ decoding?: HTMLImageElement['decoding'];
82
+ }): Promise<HTMLImageElement>;
83
+ /** An area to capture, CSS px in the element's window. */
84
+ export interface CaptureArea {
85
+ x: number;
86
+ y: number;
87
+ width: number;
88
+ height: number;
89
+ }
90
+ export declare const XLINK_NS = "http://www.w3.org/1999/xlink";
91
+ /**
92
+ * Puts every `<image>` link under `root` in the XLink namespace.
93
+ *
94
+ * dom-to-svg writes an image's address with `setAttribute('xlink:href', …)`,
95
+ * which in its XML document makes an attribute in no namespace. Its
96
+ * `inlineResources` reads `href.baseVal`, which only sees a namespaced
97
+ * `xlink:href` (or a plain `href`), so every picture failed with "No URL
98
+ * passed", kept its web address, and came out blank once the address was
99
+ * dropped. Once namespaced, inlining's own `setAttribute('xlink:href', data)`
100
+ * updates that same attribute.
101
+ */
102
+ export declare function linkImages(root: Element): void;
103
+ /** `object-position` as an SVG alignment (`xMidYMid`); positions other than 0%, 50% and 100% are taken as the middle. */
104
+ export declare function objectAlign(position: string): string;
105
+ /** `object-fit` (and `object-position`) as an SVG `preserveAspectRatio`; null where SVG has no match (`none`). */
106
+ export declare function objectFitAspect(fit: string, position: string): string | null;
107
+ /**
108
+ * The element rebuilt as plain SVG by dom-to-svg (links dropped), its
109
+ * resources inlined, and the CSS outlines dom-to-svg leaves out drawn as
110
+ * rects. `area` defaults to the element's own box.
111
+ *
112
+ * `fontCss` replaces the `@font-face` rules dom-to-svg copies itself. It
113
+ * only copies those of linked stylesheets it may read (none from an inline
114
+ * `<style>`, none from another origin), and without its font a text is
115
+ * drawn in a fallback at the place measured for the real one. Pass the
116
+ * document's {@link embeddedFontCss} for a drawing that is rasterized.
117
+ */
118
+ export declare function elementSvg(element: Element, area?: CaptureArea, options?: {
119
+ fontCss?: string;
120
+ }): Promise<XMLDocument>;
package/src/capture.js ADDED
@@ -0,0 +1,301 @@
1
+ /**
2
+ * Capturing rendered DOM as pictures, two ways:
3
+ *
4
+ * - through an SVG `<foreignObject>`: a copy of the markup with every
5
+ * picture inlined as a `data:` URL ({@link inlinedCopy}) is wrapped in an
6
+ * SVG document ({@link foreignObjectSvg}), loaded as an image
7
+ * ({@link loadSvgImage}) and drawn onto a canvas. It keeps everything the
8
+ * browser can draw, but some browsers refuse to read the canvas back;
9
+ * - with dom-to-svg ({@link elementSvg}), which rebuilds the element as
10
+ * plain SVG shapes: a vector drawing that pastes into design tools, and
11
+ * the fallback when the first way fails.
12
+ *
13
+ * What is captured (a slide, an artboard's element) and how the result is
14
+ * drawn stays with each editor.
15
+ */
16
+ import { elementToSVG, inlineResources } from 'dom-to-svg';
17
+ import { withCaptureSafeDom } from "./capture-safe.js";
18
+ import { cssUrls } from "./fonts.js";
19
+ import { drawOutlines, markOutlines } from "./outline.js";
20
+ /** A transparent 1×1 GIF: stands in for pictures a capture leaves out. */
21
+ export const BLANK_GIF = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
22
+ export const SVG_NS = 'http://www.w3.org/2000/svg';
23
+ export const XHTML_NS = 'http://www.w3.org/1999/xhtml';
24
+ /** The largest scale an area of `width` × `height` can be drawn at within `limits`. */
25
+ export function maxCaptureScale(width, height, limits) {
26
+ return Math.min(limits.maxSide / Math.max(width, height, 1), Math.sqrt(limits.maxPixels / Math.max(width * height, 1)));
27
+ }
28
+ /** Resolves once every picture in the element loaded (or failed, or took longer than `timeout` ms) and decoded. */
29
+ export async function picturesReady(root, timeout) {
30
+ await Promise.all(Array.from(root.querySelectorAll('img')).map(async (image) => {
31
+ if (!image.complete) {
32
+ await new Promise((resolve) => {
33
+ const done = () => resolve();
34
+ image.addEventListener('load', done, { once: true });
35
+ image.addEventListener('error', done, { once: true });
36
+ setTimeout(done, timeout);
37
+ });
38
+ }
39
+ await image.decode().catch(() => undefined);
40
+ }));
41
+ }
42
+ /**
43
+ * Hides everything under `root` but `target` (live elements or a copy), so a
44
+ * capture draws only the target where it sits. `bare` also hides what the
45
+ * target holds (its background and border only). Returns an undo.
46
+ */
47
+ export function hideOutside(root, target, bare) {
48
+ const touched = [];
49
+ const set = (el, property, value) => {
50
+ const styled = el;
51
+ if (!styled.style)
52
+ return;
53
+ touched.push([styled, property, styled.style.getPropertyValue(property), styled.style.getPropertyPriority(property)]);
54
+ styled.style.setProperty(property, value, 'important');
55
+ };
56
+ if (target) {
57
+ if (target !== root) {
58
+ set(root, 'visibility', 'hidden');
59
+ set(target, 'visibility', 'visible');
60
+ }
61
+ if (bare) {
62
+ for (const child of Array.from(target.children))
63
+ set(child, 'visibility', 'hidden');
64
+ set(target, '-webkit-text-fill-color', 'transparent');
65
+ set(target, 'text-shadow', 'none');
66
+ }
67
+ }
68
+ return () => {
69
+ for (const [el, property, value, priority] of touched.reverse()) {
70
+ if (value)
71
+ el.style.setProperty(property, value, priority);
72
+ else
73
+ el.style.removeProperty(property);
74
+ }
75
+ };
76
+ }
77
+ /** Replaces `url(…)` references in an element's inline style with `data:` URLs. */
78
+ export async function inlineStyleUrls(el, options) {
79
+ const style = el.getAttribute('style');
80
+ if (!style || !style.includes('url('))
81
+ return;
82
+ let next = style;
83
+ for (const { match, url: raw } of cssUrls(style)) {
84
+ const url = raw.replace(/&quot;/g, '');
85
+ if (url.startsWith('data:'))
86
+ continue;
87
+ const data = await options.dataUrl(url);
88
+ if (data)
89
+ next = next.replace(match, `url("${data}")`);
90
+ else if (options.unreadable === 'blank')
91
+ next = next.replace(match, `url("${BLANK_GIF}")`);
92
+ else
93
+ options.onMissing?.(url);
94
+ }
95
+ el.setAttribute('style', next);
96
+ }
97
+ /** A copy of the element's markup with every picture inlined, ready to be drawn in isolation. */
98
+ export async function inlinedCopy(root, options) {
99
+ const copy = root.cloneNode(true);
100
+ const live = [root, ...Array.from(root.querySelectorAll('*'))];
101
+ const copies = [copy, ...Array.from(copy.querySelectorAll('*'))];
102
+ const target = options.only;
103
+ const inside = (el) => !target || target === el || target.contains(el);
104
+ await Promise.all(live.map(async (el, i) => {
105
+ const twin = copies[i];
106
+ if (el instanceof HTMLImageElement) {
107
+ twin.removeAttribute('srcset');
108
+ twin.removeAttribute('loading');
109
+ const src = el.currentSrc || el.src;
110
+ if (inside(el)) {
111
+ const data = src ? await options.dataUrl(src) : null;
112
+ if (data)
113
+ twin.setAttribute('src', data);
114
+ else if (options.unreadable === 'blank')
115
+ twin.setAttribute('src', BLANK_GIF);
116
+ else {
117
+ twin.removeAttribute('src');
118
+ if (src)
119
+ options.onMissing?.(src);
120
+ }
121
+ }
122
+ else {
123
+ twin.setAttribute('src', BLANK_GIF);
124
+ twin.style.width = `${el.offsetWidth}px`;
125
+ twin.style.height = `${el.offsetHeight}px`;
126
+ }
127
+ }
128
+ else if (el instanceof SVGImageElement) {
129
+ const href = el.getAttribute('href') ?? el.getAttribute('xlink:href');
130
+ if (href && !href.startsWith('data:')) {
131
+ const data = await options.dataUrl(href);
132
+ if (data)
133
+ twin.setAttribute('href', data);
134
+ else if (options.unreadable === 'blank')
135
+ twin.setAttribute('href', BLANK_GIF);
136
+ twin.removeAttribute('xlink:href');
137
+ }
138
+ }
139
+ if (inside(el))
140
+ await inlineStyleUrls(twin, options);
141
+ }));
142
+ if (target) {
143
+ const index = live.indexOf(target);
144
+ if (index >= 0)
145
+ hideOutside(copy, copies[index], Boolean(options.bare));
146
+ }
147
+ return copy;
148
+ }
149
+ /** Escapes text (such as CSS) for an XML text node. */
150
+ export function xmlText(text) {
151
+ return text.replace(/&/g, '&amp;').replace(/</g, '&lt;');
152
+ }
153
+ /** An SVG document drawing serialized XHTML `markup`, styled by `css`, through a `<foreignObject>`. */
154
+ export function foreignObjectSvg(markup, css, size) {
155
+ const { width, height } = size;
156
+ const zoom = size.zoom !== undefined && Number.isFinite(size.zoom) && size.zoom > 0 && size.zoom !== 1 ? size.zoom : 1;
157
+ return (`<svg xmlns="${SVG_NS}" width="${size.outerWidth ?? width}" height="${size.outerHeight ?? height}" viewBox="0 0 ${width * zoom} ${height * zoom}">` +
158
+ `<foreignObject x="0" y="0" width="${width * zoom}" height="${height * zoom}">` +
159
+ `<div xmlns="${XHTML_NS}" style="width:${width}px;height:${height}px;margin:0;overflow:hidden${zoom === 1 ? '' : `;zoom:${zoom}`}"><style>${xmlText(css)}</style>${markup}</div>` +
160
+ '</foreignObject></svg>');
161
+ }
162
+ /** Loads an SVG document as an image (from a `data:` URL), decoded; rejects with `error` when it will not load. */
163
+ export async function loadSvgImage(svg, options) {
164
+ const image = new Image();
165
+ if (options.decoding)
166
+ image.decoding = options.decoding;
167
+ await new Promise((resolve, reject) => {
168
+ image.onload = () => resolve();
169
+ image.onerror = () => reject(new Error(options.error));
170
+ image.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
171
+ });
172
+ await image.decode().catch(() => undefined);
173
+ return image;
174
+ }
175
+ export const XLINK_NS = 'http://www.w3.org/1999/xlink';
176
+ /**
177
+ * Puts every `<image>` link under `root` in the XLink namespace.
178
+ *
179
+ * dom-to-svg writes an image's address with `setAttribute('xlink:href', …)`,
180
+ * which in its XML document makes an attribute in no namespace. Its
181
+ * `inlineResources` reads `href.baseVal`, which only sees a namespaced
182
+ * `xlink:href` (or a plain `href`), so every picture failed with "No URL
183
+ * passed", kept its web address, and came out blank once the address was
184
+ * dropped. Once namespaced, inlining's own `setAttribute('xlink:href', data)`
185
+ * updates that same attribute.
186
+ */
187
+ export function linkImages(root) {
188
+ for (const image of Array.from(root.getElementsByTagNameNS(SVG_NS, 'image'))) {
189
+ const plain = image.getAttributeNodeNS(null, 'xlink:href');
190
+ if (!plain)
191
+ continue;
192
+ image.removeAttributeNode(plain);
193
+ image.setAttributeNS(XLINK_NS, 'xlink:href', plain.value);
194
+ }
195
+ }
196
+ /** `object-position` as an SVG alignment (`xMidYMid`); positions other than 0%, 50% and 100% are taken as the middle. */
197
+ export function objectAlign(position) {
198
+ const [x = '50%', y = '50%'] = position.trim().split(/\s+/);
199
+ const KEYWORDS = { left: 0, top: 0, center: 50, right: 100, bottom: 100 };
200
+ const axis = (value) => {
201
+ const at = KEYWORDS[value] ?? (value.endsWith('%') || Number.parseFloat(value) === 0 ? Number.parseFloat(value) : Number.NaN);
202
+ return at === 0 ? 'Min' : at === 100 ? 'Max' : 'Mid';
203
+ };
204
+ return `x${axis(x)}Y${axis(y)}`;
205
+ }
206
+ /** `object-fit` (and `object-position`) as an SVG `preserveAspectRatio`; null where SVG has no match (`none`). */
207
+ export function objectFitAspect(fit, position) {
208
+ switch (fit) {
209
+ case 'fill':
210
+ return 'none';
211
+ case 'cover':
212
+ return `${objectAlign(position)} slice`;
213
+ case 'contain':
214
+ case 'scale-down':
215
+ return `${objectAlign(position)} meet`;
216
+ default:
217
+ return null;
218
+ }
219
+ }
220
+ /** How each `<img>` under `element` fills its box, measured where dom-to-svg measures it. */
221
+ function imageFits(element) {
222
+ const view = element.ownerDocument.defaultView;
223
+ const fits = [];
224
+ const images = element.localName === 'img' ? [element] : Array.from(element.querySelectorAll('img'));
225
+ for (const image of images) {
226
+ const style = view.getComputedStyle(image);
227
+ const preserveAspectRatio = objectFitAspect(style.objectFit, style.objectPosition);
228
+ if (!preserveAspectRatio)
229
+ continue;
230
+ const rect = image.getBoundingClientRect();
231
+ const left = Number.parseFloat(style.paddingLeft) || 0;
232
+ const top = Number.parseFloat(style.paddingTop) || 0;
233
+ fits.push({
234
+ x: rect.x + left,
235
+ y: rect.y + top,
236
+ width: rect.width - left - (Number.parseFloat(style.paddingRight) || 0),
237
+ height: rect.height - top - (Number.parseFloat(style.paddingBottom) || 0),
238
+ preserveAspectRatio,
239
+ });
240
+ }
241
+ return fits;
242
+ }
243
+ /**
244
+ * Gives each `<image>` dom-to-svg made for an `<img>` the picture's
245
+ * `object-fit`: it leaves SVG's default (`xMidYMid meet`), which letterboxes
246
+ * a cropped (`cover`) or stretched (`fill`, HTML's default) picture. Images
247
+ * are matched by position and size; background images already carry their
248
+ * own `preserveAspectRatio` and are left alone.
249
+ */
250
+ function fitImages(root, fits) {
251
+ if (!fits.length)
252
+ return;
253
+ const near = (a, b) => a !== null && Math.abs(Number(a) - b) < 0.5;
254
+ for (const image of Array.from(root.getElementsByTagNameNS(SVG_NS, 'image'))) {
255
+ if (image.hasAttribute('preserveAspectRatio'))
256
+ continue;
257
+ const fit = fits.find((f) => near(image.getAttribute('x'), f.x) && near(image.getAttribute('y'), f.y) && near(image.getAttribute('width'), f.width) && near(image.getAttribute('height'), f.height));
258
+ if (fit)
259
+ image.setAttribute('preserveAspectRatio', fit.preserveAspectRatio);
260
+ }
261
+ }
262
+ /**
263
+ * The element rebuilt as plain SVG by dom-to-svg (links dropped), its
264
+ * resources inlined, and the CSS outlines dom-to-svg leaves out drawn as
265
+ * rects. `area` defaults to the element's own box.
266
+ *
267
+ * `fontCss` replaces the `@font-face` rules dom-to-svg copies itself. It
268
+ * only copies those of linked stylesheets it may read (none from an inline
269
+ * `<style>`, none from another origin), and without its font a text is
270
+ * drawn in a fallback at the place measured for the real one. Pass the
271
+ * document's {@link embeddedFontCss} for a drawing that is rasterized.
272
+ */
273
+ export async function elementSvg(element, area, options = {}) {
274
+ const box = area ?? element.getBoundingClientRect();
275
+ const view = element.ownerDocument.defaultView;
276
+ const fits = imageFits(element);
277
+ const outlines = markOutlines(element);
278
+ let doc;
279
+ try {
280
+ doc = withCaptureSafeDom(element, () => elementToSVG(element, { captureArea: new view.DOMRect(box.x, box.y, box.width, box.height), keepLinks: false }));
281
+ }
282
+ finally {
283
+ outlines.release();
284
+ }
285
+ drawOutlines(doc.documentElement, outlines.outlined);
286
+ linkImages(doc.documentElement);
287
+ fitImages(doc.documentElement, fits);
288
+ // dom-to-svg's own rules sit in the first <style>; emptied, there is nothing for it to download a second time.
289
+ const fontStyle = options.fontCss === undefined ? null : Array.from(doc.documentElement.children).find((child) => child.localName === 'style');
290
+ if (fontStyle)
291
+ fontStyle.textContent = '';
292
+ await inlineResources(doc.documentElement);
293
+ if (fontStyle)
294
+ fontStyle.textContent = options.fontCss;
295
+ else if (options.fontCss) {
296
+ const style = doc.createElementNS(SVG_NS, 'style');
297
+ style.textContent = options.fontCss;
298
+ doc.documentElement.prepend(style);
299
+ }
300
+ return doc;
301
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Where a rendered page's content ends: the lowest thing a reader would see
3
+ * (text, a picture, a control, a rule, an outline, a filled box that stands
4
+ * out from what is behind it). Below it the page is blank, however tall its
5
+ * frame or its `min-height: 100vh` wrappers are.
6
+ *
7
+ * The test of one element ({@link countsAsContent}) is pure and loads in
8
+ * `node --test`; {@link contentBottom} walks a rendered document with it.
9
+ */
10
+ /** Past this many elements the walk gives up and takes the document's height. */
11
+ export declare const MAX_MEASURED_ELEMENTS = 20000;
12
+ /** Least height of a filled box that counts by its fill alone. */
13
+ export declare const MIN_FILLED_HEIGHT = 40;
14
+ /** Least difference from what is behind (red + green + blue, 0–765) for a fill to count. */
15
+ export declare const MIN_FILL_CONTRAST = 24;
16
+ /** An RGB colour, 0–255 each, with its alpha 0–1. */
17
+ export type Rgba = readonly [number, number, number, number];
18
+ /** A CSS colour as the browser computes it (`rgb(…)`, `rgba(…)`, `transparent`); `null` when it can't be read. */
19
+ export declare function parseColor(value: string): Rgba | null;
20
+ /** `fill` painted over the opaque colour `behind`. */
21
+ export declare function paintOver(fill: Rgba, behind: Rgba): Rgba;
22
+ /** How far apart two opaque colours are: the sum of their red, green and blue differences. */
23
+ export declare const colorDistance: (a: Rgba, b: Rgba) => number;
24
+ /** What decides whether an element is content, read from its computed style. */
25
+ export interface ElementLook {
26
+ /** Lower-case tag name. */
27
+ tag: string;
28
+ backgroundImage: string;
29
+ borderBottomStyle: string;
30
+ borderBottomWidth: number;
31
+ /** Whether it draws an outline (outline.ts's `visibleOutline`). */
32
+ outline: boolean;
33
+ /** Whether it holds text of its own that isn't only white space. */
34
+ ownText: boolean;
35
+ height: number;
36
+ /** Its background colour. */
37
+ fill: Rgba | null;
38
+ /** The opaque colour behind it. */
39
+ behind: Rgba;
40
+ }
41
+ /** Whether a reader would see this element itself (not its children). */
42
+ export declare function countsAsContent(look: ElementLook): boolean;
43
+ /**
44
+ * How far down the rendered document's content reaches, in document px (the
45
+ * frame is never scrolled, so client rects are document coordinates). A page
46
+ * that clips its own overflow (`overflow: hidden` or `clip` on the root or
47
+ * body) is as tall as its viewport; a very large one is as tall as its
48
+ * document.
49
+ */
50
+ export declare function contentBottom(doc: Document): number;
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Where a rendered page's content ends: the lowest thing a reader would see
3
+ * (text, a picture, a control, a rule, an outline, a filled box that stands
4
+ * out from what is behind it). Below it the page is blank, however tall its
5
+ * frame or its `min-height: 100vh` wrappers are.
6
+ *
7
+ * The test of one element ({@link countsAsContent}) is pure and loads in
8
+ * `node --test`; {@link contentBottom} walks a rendered document with it.
9
+ */
10
+ import { documentHeight } from "./document-measure.js";
11
+ import { outlineReach, visibleOutline } from "./outline.js";
12
+ /** Elements that are content by themselves, empty or not. */
13
+ const CONTENT_TAGS = new Set(['img', 'svg', 'canvas', 'video', 'picture', 'input', 'button', 'textarea', 'select', 'iframe', 'hr', 'object', 'embed']);
14
+ /** Past this many elements the walk gives up and takes the document's height. */
15
+ export const MAX_MEASURED_ELEMENTS = 20000;
16
+ /** Least height of a filled box that counts by its fill alone. */
17
+ export const MIN_FILLED_HEIGHT = 40;
18
+ /** Least difference from what is behind (red + green + blue, 0–765) for a fill to count. */
19
+ export const MIN_FILL_CONTRAST = 24;
20
+ /** A CSS colour as the browser computes it (`rgb(…)`, `rgba(…)`, `transparent`); `null` when it can't be read. */
21
+ export function parseColor(value) {
22
+ const text = value.trim().toLowerCase();
23
+ if (text === 'transparent')
24
+ return [0, 0, 0, 0];
25
+ const match = /^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)(?:\s*[,/]\s*([\d.]+%?))?\s*\)$/.exec(text);
26
+ if (!match)
27
+ return null;
28
+ const alphaText = match[4];
29
+ const alpha = alphaText === undefined ? 1 : alphaText.endsWith('%') ? parseFloat(alphaText) / 100 : parseFloat(alphaText);
30
+ return [Number(match[1]), Number(match[2]), Number(match[3]), Math.max(0, Math.min(1, alpha))];
31
+ }
32
+ /** `fill` painted over the opaque colour `behind`. */
33
+ export function paintOver(fill, behind) {
34
+ const a = fill[3];
35
+ return [fill[0] * a + behind[0] * (1 - a), fill[1] * a + behind[1] * (1 - a), fill[2] * a + behind[2] * (1 - a), 1];
36
+ }
37
+ /** How far apart two opaque colours are: the sum of their red, green and blue differences. */
38
+ export const colorDistance = (a, b) => [0, 1, 2].reduce((sum, channel) => sum + Math.abs(a[channel] - b[channel]), 0);
39
+ /** Whether a reader would see this element itself (not its children). */
40
+ export function countsAsContent(look) {
41
+ if (CONTENT_TAGS.has(look.tag))
42
+ return true;
43
+ if (look.ownText)
44
+ return true;
45
+ if (look.backgroundImage !== '' && look.backgroundImage !== 'none')
46
+ return true;
47
+ if (look.borderBottomStyle !== 'none' && look.borderBottomStyle !== 'hidden' && look.borderBottomWidth > 0)
48
+ return true;
49
+ if (look.outline)
50
+ return true;
51
+ if (look.height >= MIN_FILLED_HEIGHT && look.fill && look.fill[3] > 0)
52
+ return colorDistance(paintOver(look.fill, look.behind), look.behind) > MIN_FILL_CONTRAST;
53
+ return false;
54
+ }
55
+ const WHITE = [255, 255, 255, 1];
56
+ /**
57
+ * How far down the rendered document's content reaches, in document px (the
58
+ * frame is never scrolled, so client rects are document coordinates). A page
59
+ * that clips its own overflow (`overflow: hidden` or `clip` on the root or
60
+ * body) is as tall as its viewport; a very large one is as tall as its
61
+ * document.
62
+ */
63
+ export function contentBottom(doc) {
64
+ const view = doc.defaultView;
65
+ const root = doc.documentElement;
66
+ const body = doc.body;
67
+ const style = (element) => view.getComputedStyle(element);
68
+ const clips = (element) => element !== null && /^(hidden|clip)$/.test(style(element).overflowY);
69
+ if (clips(root) || clips(body))
70
+ return root.clientHeight || view.innerHeight;
71
+ if (root.getElementsByTagName('*').length > MAX_MEASURED_ELEMENTS)
72
+ return documentHeight(doc);
73
+ const height = documentHeight(doc);
74
+ const page = [body, root].map((element) => (element ? parseColor(style(element).backgroundColor) : null)).find((color) => color && color[3] > 0);
75
+ const range = doc.createRange();
76
+ let bottom = 0;
77
+ const textBottom = (element) => {
78
+ let lowest = 0;
79
+ for (const node of element.childNodes) {
80
+ if (node.nodeType !== 3 || !node.nodeValue?.trim())
81
+ continue;
82
+ range.selectNodeContents(node);
83
+ const rect = range.getBoundingClientRect();
84
+ if (rect.height > 0)
85
+ lowest = Math.max(lowest, rect.bottom);
86
+ }
87
+ return lowest;
88
+ };
89
+ const visit = (element, behind) => {
90
+ const css = style(element);
91
+ if (css.display === 'none' || css.position === 'fixed' || parseFloat(css.opacity) === 0)
92
+ return;
93
+ const rect = element.getBoundingClientRect();
94
+ const fill = parseColor(css.backgroundColor);
95
+ const tag = element.localName.toLowerCase();
96
+ // A wrapper as tall as the whole document (`min-height: 100vh`) is the page, not content on it.
97
+ const wrapper = rect.top <= 1 && rect.bottom >= height - 1;
98
+ if (css.visibility !== 'hidden') {
99
+ const outline = visibleOutline(css);
100
+ // Text counts by the lines it draws, wherever it sits.
101
+ bottom = Math.max(bottom, textBottom(element));
102
+ const look = {
103
+ tag,
104
+ backgroundImage: css.backgroundImage,
105
+ borderBottomStyle: css.borderBottomStyle,
106
+ borderBottomWidth: parseFloat(css.borderBottomWidth) || 0,
107
+ outline: outline !== null,
108
+ ownText: false,
109
+ height: rect.height,
110
+ fill,
111
+ behind,
112
+ };
113
+ // A wrapper's fill, border and outline frame the page; a picture it shows is still content.
114
+ if (rect.width > 0 && rect.height > 0 && countsAsContent(wrapper ? { ...look, fill: null, borderBottomWidth: 0, outline: false } : look)) {
115
+ bottom = Math.max(bottom, rect.bottom + (wrapper ? 0 : outlineReach(outline)));
116
+ }
117
+ }
118
+ // What is inside a picture or a control is part of it.
119
+ if (CONTENT_TAGS.has(tag))
120
+ return;
121
+ const next = fill && fill[3] > 0 ? paintOver(fill, behind) : behind;
122
+ for (const child of element.children)
123
+ visit(child, next);
124
+ };
125
+ const start = body ?? root;
126
+ const base = page ? paintOver(page, WHITE) : WHITE;
127
+ bottom = textBottom(start);
128
+ for (const child of start.children)
129
+ visit(child, base);
130
+ return Math.ceil(bottom);
131
+ }
@@ -0,0 +1,36 @@
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 { type Interval, type KeepBlock } from './pagination.js';
12
+ import type { LinkArea, Word } from './text-layer.js';
13
+ /** The words drawn in the document, in reading (document) order. */
14
+ export declare function documentWords(doc: Document): Word[];
15
+ /** The clickable boxes of web links that are drawn. */
16
+ export declare function documentLinks(doc: Document): LinkArea[];
17
+ /** The paper colour: the body's background, else the root's, else white. */
18
+ export declare function documentBackground(doc: Document): string;
19
+ /**
20
+ * Spans a page cut must not fall inside: each drawn text line, and each
21
+ * picture up to {@link MAX_UNSPLIT_PICTURE} px tall (taller ones are cut
22
+ * where the page ends).
23
+ */
24
+ export declare function documentBands(doc: Document): Interval[];
25
+ /**
26
+ * Boxes a page cut should not fall inside, as a printer keeps them: what the page asks to keep whole
27
+ * (`break-inside: avoid`), and the boxes it draws (a card: bordered, shadowed or filled) up to `maxBoxHeight` px
28
+ * tall. A taller card is cut between its lines like the rest of the page.
29
+ */
30
+ export declare function documentBoxes(doc: Document, maxBoxHeight: number): Interval[];
31
+ /** Headings, captions and header rows, with the run each is kept with (see pagination.ts). */
32
+ export declare function documentKeepBlocks(doc: Document): KeepBlock[];
33
+ /** The full height of the document's content. */
34
+ export declare function documentHeight(doc: Document): number;
35
+ /** Tops of the drawn elements that ask for a new page before them (`break-before: page`), in document px. */
36
+ export declare function documentPageBreaks(doc: Document): number[];