@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/src/outline.js ADDED
@@ -0,0 +1,160 @@
1
+ /**
2
+ * CSS outlines in captures. dom-to-svg draws an element's background and
3
+ * border but not its `outline`, which sits outside the box and takes no room
4
+ * in the layout. {@link drawOutlines} adds each one to the drawing as a
5
+ * stroked `<rect>`, and {@link outlineReach} says how far one sticks out, so
6
+ * the capture of a single element can grow to hold it.
7
+ *
8
+ * The geometry ({@link visibleOutline}, {@link outlineRect}) is pure and
9
+ * loads in `node --test`.
10
+ */
11
+ const px = (value) => {
12
+ const number = Number.parseFloat(value);
13
+ return Number.isFinite(number) ? number : 0;
14
+ };
15
+ const clear = (color) => {
16
+ const value = color.trim().toLowerCase();
17
+ if (!value || value === 'transparent')
18
+ return true;
19
+ // Only a fourth value is alpha: `rgb(255, 0, 0)` ends in a 0 that is its blue.
20
+ const alpha = /^rgba?\((?:[^,)]*,){3}\s*([\d.]+)(%?)\s*\)$/.exec(value) ?? /^rgba?\([^)]*\/\s*([\d.]+)(%?)\s*\)$/.exec(value);
21
+ return alpha !== null && Number.parseFloat(alpha[1]) === 0;
22
+ };
23
+ /** The outline a computed style draws, or null when it draws none (no style, `auto`, no width, no colour, hidden). */
24
+ export function visibleOutline(style) {
25
+ const kind = style.outlineStyle.trim().toLowerCase();
26
+ if (!kind || kind === 'none' || kind === 'auto' || kind === 'hidden')
27
+ return null;
28
+ if (style.visibility === 'hidden' || style.visibility === 'collapse')
29
+ return null;
30
+ const width = px(style.outlineWidth);
31
+ if (!(width > 0) || clear(style.outlineColor))
32
+ return null;
33
+ const dash = kind === 'dashed' || kind === 'dotted' ? kind : 'solid';
34
+ return { width, offset: px(style.outlineOffset), color: style.outlineColor, dash };
35
+ }
36
+ /** How far past the border box an outline reaches on each side, px. */
37
+ export const outlineReach = (outline) => (outline ? Math.max(0, outline.width + outline.offset) : 0);
38
+ /** One corner radius length (`12px`, `50%`) taken against a side, at most half of it. */
39
+ function cornerLength(value, side) {
40
+ if (!value)
41
+ return 0;
42
+ const length = value.endsWith('%') ? (px(value) / 100) * side : px(value);
43
+ return Math.min(Math.max(length, 0), side / 2);
44
+ }
45
+ /**
46
+ * The attributes of a `<rect>` that strokes `outline` around `box`: the
47
+ * stroke is centred on the rect's edge, so the rect is the border box grown
48
+ * by the offset and half the width. Its corners follow the box's top left
49
+ * radius, grown as much. Null when the rect would have no area.
50
+ */
51
+ export function outlineRect(box, outline, style) {
52
+ const grow = outline.offset + outline.width / 2;
53
+ const width = box.width + grow * 2;
54
+ const height = box.height + grow * 2;
55
+ if (!(width > 0 && height > 0) || !(box.width > 0 && box.height > 0))
56
+ return null;
57
+ const round = (value) => String(Math.round(value * 100) / 100);
58
+ const attributes = {
59
+ x: round(box.x - grow),
60
+ y: round(box.y - grow),
61
+ width: round(width),
62
+ height: round(height),
63
+ fill: 'none',
64
+ stroke: outline.color,
65
+ 'stroke-width': round(outline.width),
66
+ };
67
+ const [horizontal, vertical = horizontal] = style.borderTopLeftRadius.trim().split(/\s+/);
68
+ const rx = cornerLength(horizontal, box.width);
69
+ const ry = cornerLength(vertical, box.height);
70
+ if (rx > 0 && ry > 0 && rx + grow > 0 && ry + grow > 0) {
71
+ attributes.rx = round(rx + grow);
72
+ attributes.ry = round(ry + grow);
73
+ }
74
+ if (outline.dash === 'dashed')
75
+ attributes['stroke-dasharray'] = `${round(outline.width * 2)} ${round(outline.width)}`;
76
+ if (outline.dash === 'dotted') {
77
+ attributes['stroke-dasharray'] = `0 ${round(outline.width * 2)}`;
78
+ attributes['stroke-linecap'] = 'round';
79
+ }
80
+ const opacity = Number.parseFloat(style.opacity);
81
+ if (Number.isFinite(opacity) && opacity < 1)
82
+ attributes.opacity = String(opacity);
83
+ return attributes;
84
+ }
85
+ /** The outline an element draws (none for a zero-sized one). */
86
+ export function elementOutline(element) {
87
+ const rect = element.getBoundingClientRect();
88
+ if (!(rect.width > 0 && rect.height > 0))
89
+ return null;
90
+ return visibleOutline(element.ownerDocument.defaultView.getComputedStyle(element));
91
+ }
92
+ const LENT_ID = 'oa-capture-outline-';
93
+ const SVG = 'http://www.w3.org/2000/svg';
94
+ /**
95
+ * Finds the elements under `root` (itself included, shapes inside an `<svg>`
96
+ * left out) that draw an outline, and gives each one without an id a
97
+ * temporary one: dom-to-svg names an element's group by its id, which is how
98
+ * the outline finds its place in the drawing. Call `release` when the
99
+ * drawing is made; it takes the lent ids back.
100
+ */
101
+ export function markOutlines(root) {
102
+ const doc = root.ownerDocument;
103
+ const view = doc.defaultView;
104
+ const outlined = [];
105
+ let next = 0;
106
+ for (const element of [root, ...Array.from(root.querySelectorAll('*'))]) {
107
+ if (element.parentElement?.closest('svg'))
108
+ continue;
109
+ const rect = element.getBoundingClientRect();
110
+ if (!(rect.width > 0 && rect.height > 0))
111
+ continue;
112
+ const style = view.getComputedStyle(element);
113
+ const outline = visibleOutline(style);
114
+ if (!outline)
115
+ continue;
116
+ let id = element.id;
117
+ const lent = !id;
118
+ if (lent) {
119
+ do
120
+ id = `${LENT_ID}${next++}`;
121
+ while (doc.getElementById(id));
122
+ element.id = id;
123
+ }
124
+ outlined.push({
125
+ element,
126
+ id,
127
+ lent,
128
+ outline,
129
+ box: { x: rect.x, y: rect.y, width: rect.width, height: rect.height },
130
+ style: { borderTopLeftRadius: style.borderTopLeftRadius, opacity: style.opacity },
131
+ });
132
+ }
133
+ return {
134
+ outlined,
135
+ release: () => {
136
+ for (const mark of outlined)
137
+ if (mark.lent && mark.element.id === mark.id)
138
+ mark.element.removeAttribute('id');
139
+ },
140
+ };
141
+ }
142
+ /** Draws each outline right after its element's group in an SVG drawing made while they were marked. */
143
+ export function drawOutlines(svg, outlined) {
144
+ const groups = new Map();
145
+ for (const group of Array.from(svg.querySelectorAll('[id]')))
146
+ if (!groups.has(group.id))
147
+ groups.set(group.id, group);
148
+ for (const mark of outlined) {
149
+ const group = groups.get(mark.id);
150
+ const attributes = outlineRect(mark.box, mark.outline, mark.style);
151
+ if (!group || !attributes)
152
+ continue;
153
+ const rect = svg.ownerDocument.createElementNS(SVG, 'rect');
154
+ for (const [name, value] of Object.entries(attributes))
155
+ rect.setAttribute(name, value);
156
+ group.after(rect);
157
+ if (mark.lent)
158
+ group.removeAttribute('id');
159
+ }
160
+ }
@@ -0,0 +1,104 @@
1
+ /**
2
+ * A rendered document as pictures: {@link pageImage} draws a document's
3
+ * viewport (an artboard, a page of a long document), and {@link captureHtml}
4
+ * rewrites an element as standalone HTML with its computed styles inlined,
5
+ * which is what the browser is asked to paint through a `<foreignObject>`.
6
+ *
7
+ * The browser paints the computed HTML, which keeps what only it can draw:
8
+ * shadows, filters, blending, masks, `::before`. Where the canvas cannot be
9
+ * read back afterwards, and for a slice of a long page, dom-to-svg rebuilds
10
+ * the page as SVG shapes instead. Every picture carries the web fonts its
11
+ * document uses, inlined (`embeddedFontCss`): a picture is drawn apart from
12
+ * the page and cannot load them itself.
13
+ *
14
+ * Needs a DOM. Shared by the Design editor (artboards) and the Data editor
15
+ * (the dashboard's PDF).
16
+ */
17
+ import { type CaptureLimits } from './capture.js';
18
+ import { type EmbeddedFonts } from './font-embed.js';
19
+ /** How large a capture may be: 12000 px a side, 120 megapixels. */
20
+ export declare const CAPTURE_LIMITS: CaptureLimits;
21
+ /** {@link CAPTURE_LIMITS} with the canvas area this browser is drawing at now (lowered after a canvas it would not make). */
22
+ export declare function captureLimits(): CaptureLimits;
23
+ /** The web fonts a document's pictures carry; none when they cannot be read (the picture is still drawn, in fallback fonts). */
24
+ export declare const documentFonts: (doc: Document, maxBytes?: number) => Promise<EmbeddedFonts>;
25
+ /** Removes what the copy should not carry: scripts, handlers, debug data, external links. */
26
+ export declare function cleanSvg(root: Element): void;
27
+ export interface RasterOptions {
28
+ scale?: number;
29
+ type?: 'image/png' | 'image/jpeg';
30
+ /** Painted under the drawing (JPEG has no transparency). */
31
+ background?: string;
32
+ /** Only rows `[from, to)` (CSS px) keep the drawing; the rest is painted over with `background`. */
33
+ keep?: {
34
+ from: number;
35
+ to: number;
36
+ };
37
+ /**
38
+ * Lets the picture come out smaller than `scale` asks when the browser
39
+ * will not make a canvas that large: it is drawn again on a smaller one,
40
+ * and this is called with the scale it was drawn at.
41
+ */
42
+ onSmaller?: (scale: number) => void;
43
+ }
44
+ /**
45
+ * An SVG drawing as a picture at `scale` (2 by default), within the capture
46
+ * limits. With `onSmaller`, a canvas the browser will not make lowers the
47
+ * area captures use, and the picture is drawn once more under it.
48
+ */
49
+ export declare function rasterize(svg: string, width: number, height: number, options?: RasterOptions): Promise<Blob>;
50
+ /** dom-to-svg cannot paint CSS masks or SVG use shadow trees. */
51
+ export declare function needsBrowserPaint(element: Element): boolean;
52
+ /**
53
+ * Paint the computed HTML, with embedded images and the fonts of `fontCss`, so shadows, masks and ::before survive.
54
+ * `margin` (px) is room left around the element on every side, for what it draws outside its box (an outline).
55
+ */
56
+ export declare function browserDrawing(element: Element, width: number, height: number, top?: number, fontCss?: string, html?: string, margin?: number): Promise<string>;
57
+ /**
58
+ * A frame's page as an image: its viewport (`width` × `height` CSS pixels
59
+ * from the top left) drawn at `scale`, on white.
60
+ *
61
+ * The browser paints it (the page's computed HTML through a
62
+ * `<foreignObject>`), which keeps what only it can draw: shadows, filters,
63
+ * blending, masks. Where the canvas cannot be read back afterwards, and for
64
+ * a `slice` of a long page, dom-to-svg rebuilds the page as SVG shapes
65
+ * instead. Both carry the page's web fonts; call this once they loaded.
66
+ */
67
+ export declare function pageImage(doc: Document, width: number, height: number, options: {
68
+ scale: number;
69
+ type?: 'image/png' | 'image/jpeg';
70
+ /** Top of the captured area, CSS px from the document's top (the frame is never scrolled). */
71
+ top?: number;
72
+ /** Paper under the drawing (default white). */
73
+ background?: string;
74
+ /** Rows of the image that keep the drawing; the rest shows `background` (a PDF page's break margins). */
75
+ keep?: {
76
+ from: number;
77
+ to: number;
78
+ };
79
+ /**
80
+ * One of many images of the same long page (a PDF's paper pages).
81
+ * Browser paint lays the whole page out again for each one, pictures
82
+ * and all, so a slice is rebuilt by dom-to-svg (which only visits what
83
+ * the slice shows) unless the page has something only the browser draws.
84
+ */
85
+ slice?: boolean;
86
+ /** Most web font data to inline, characters of `data:` URL (default 64 MB). */
87
+ fontBytes?: number;
88
+ /** Called with the font families left out: over `fontBytes`, or their files could not be read. */
89
+ onSkippedFonts?: (families: string[]) => void;
90
+ /**
91
+ * Shared by the images of one unchanging document (the pages of a PDF): the document's standalone HTML is made
92
+ * for the first image and kept here for the next ones, instead of reading every computed style again.
93
+ */
94
+ reuse?: {
95
+ html?: string;
96
+ };
97
+ /** Lets the image come out smaller than `scale` where the browser cannot draw it that large (see {@link RasterOptions}). */
98
+ onSmaller?: (scale: number) => void;
99
+ }): Promise<Blob>;
100
+ export type CaptureHtmlMode = 'clipboard' | 'raster' | 'figma';
101
+ /** The element as standalone HTML, images by URL (for a synchronous clipboard write). */
102
+ export declare function standaloneHtml(element: Element): string;
103
+ /** The element as standalone HTML, images inlined as data URLs. */
104
+ export declare function captureHtml(element: Element, mode?: CaptureHtmlMode): Promise<string>;