@statelyai/flow-dom 3.6.2 → 3.7.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,213 @@
1
+ import type { Rect } from '@statelyai/flow';
2
+ import type { MeasurementObserver } from './index';
3
+
4
+ export type FlowImageExportOptions = {
5
+ format?: 'svg' | 'png' | 'webp';
6
+ region?: 'graph' | 'viewport' | 'selection' | Rect;
7
+ padding?: number;
8
+ scale?: number;
9
+ pixelRatio?: number;
10
+ background?: string;
11
+ styles?: 'computed' | 'none';
12
+ include?: (element: Element) => boolean;
13
+ signal?: { readonly aborted: boolean; addEventListener(type: 'abort', listener: () => void, options?: { once?: boolean }): void };
14
+ };
15
+
16
+ export type FlowImageExportResult = {
17
+ blob: Blob;
18
+ width: number;
19
+ height: number;
20
+ };
21
+
22
+ export type FlowView = {
23
+ exportImage: (options?: FlowImageExportOptions) => Promise<FlowImageExportResult>;
24
+ refreshMeasurements: (targets?: Iterable<string | Element>) => void;
25
+ };
26
+
27
+ export function createFlowView(
28
+ container: HTMLElement,
29
+ options: { measurements?: MeasurementObserver } = {},
30
+ ): FlowView {
31
+ return {
32
+ exportImage: (options) => exportFlowImage(container, options),
33
+ refreshMeasurements: (targets) => options.measurements?.refresh(targets),
34
+ };
35
+ }
36
+
37
+ export async function exportFlowImage(
38
+ container: HTMLElement,
39
+ options: FlowImageExportOptions = {},
40
+ ): Promise<FlowImageExportResult> {
41
+ throwIfAborted(options.signal);
42
+ const win = container.ownerDocument.defaultView;
43
+ if (!win) throw new Error('Flow export requires a window.');
44
+ await nextFrame(win, options.signal);
45
+
46
+ const format = options.format ?? 'svg';
47
+ const padding = Math.max(0, options.padding ?? 0);
48
+ const scale = Math.max(0.01, options.scale ?? 1);
49
+ const pixelRatio = Math.max(0.01, options.pixelRatio ?? win.devicePixelRatio ?? 1);
50
+ const region = resolveRegion(container, options.region ?? 'graph');
51
+ const width = Math.max(1, Math.ceil((region.width + padding * 2) * scale));
52
+ const height = Math.max(1, Math.ceil((region.height + padding * 2) * scale));
53
+ const clone = container.cloneNode(true) as HTMLElement;
54
+ if ((options.styles ?? 'computed') === 'computed') {
55
+ inlineComputedStyles(win, container, clone);
56
+ }
57
+ if (options.include) {
58
+ const originals = [container, ...Array.from(container.querySelectorAll('*'))];
59
+ const clones = [clone, ...Array.from(clone.querySelectorAll('*'))];
60
+ for (let index = originals.length - 1; index >= 0; index--) {
61
+ if (!options.include(originals[index])) clones[index]?.remove();
62
+ }
63
+ }
64
+ const serializer = new win.XMLSerializer();
65
+ const markup = serializer.serializeToString(clone);
66
+ const background = options.background
67
+ ? `<rect width="100%" height="100%" fill="${escapeXml(options.background)}"/>`
68
+ : '';
69
+ const containerRect = container.getBoundingClientRect();
70
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="${region.x - padding} ${region.y - padding} ${region.width + padding * 2} ${region.height + padding * 2}">${background}<foreignObject x="0" y="0" width="${containerRect.width}" height="${containerRect.height}">${markup}</foreignObject></svg>`;
71
+ const svgBlob = new Blob([svg], { type: 'image/svg+xml' });
72
+ if (format === 'svg') return { blob: svgBlob, width, height };
73
+
74
+ throwIfAborted(options.signal);
75
+ const url = await blobDataUrl(win, svgBlob, options.signal);
76
+ const image = await loadImage(win, url, options.signal);
77
+ const canvas = container.ownerDocument.createElement('canvas');
78
+ canvas.width = Math.ceil(width * pixelRatio);
79
+ canvas.height = Math.ceil(height * pixelRatio);
80
+ const context = canvas.getContext('2d');
81
+ if (!context) throw new Error('Canvas 2D context is unavailable.');
82
+ context.scale(pixelRatio, pixelRatio);
83
+ context.drawImage(image, 0, 0, width, height);
84
+ const blob = await canvasBlob(canvas, `image/${format}`, options.signal);
85
+ return { blob, width, height };
86
+ }
87
+
88
+ function inlineComputedStyles(
89
+ win: Window,
90
+ originalRoot: HTMLElement,
91
+ cloneRoot: HTMLElement,
92
+ ): void {
93
+ const originals = [originalRoot, ...Array.from(originalRoot.querySelectorAll('*'))];
94
+ const clones = [cloneRoot, ...Array.from(cloneRoot.querySelectorAll('*'))];
95
+ for (let index = 0; index < originals.length; index++) {
96
+ const clone = clones[index] as (Element & { style?: CSSStyleDeclaration }) | undefined;
97
+ if (!clone?.style) continue;
98
+ const computed = win.getComputedStyle(originals[index]);
99
+ for (let propertyIndex = 0; propertyIndex < computed.length; propertyIndex++) {
100
+ const property = computed.item(propertyIndex);
101
+ clone.style.setProperty(
102
+ property,
103
+ computed.getPropertyValue(property),
104
+ computed.getPropertyPriority(property),
105
+ );
106
+ }
107
+ }
108
+ }
109
+
110
+ function blobDataUrl(
111
+ win: Window,
112
+ blob: Blob,
113
+ signal: FlowImageExportOptions['signal'],
114
+ ): Promise<string> {
115
+ return new Promise((resolve, reject) => {
116
+ const Reader = (win as unknown as { FileReader: typeof FileReader }).FileReader;
117
+ const reader = new Reader();
118
+ reader.onload = () => resolve(String(reader.result));
119
+ reader.onerror = () => reject(reader.error ?? new Error('Unable to encode Flow SVG.'));
120
+ signal?.addEventListener('abort', () => {
121
+ reader.abort();
122
+ reject(abortError());
123
+ }, { once: true });
124
+ reader.readAsDataURL(blob);
125
+ });
126
+ }
127
+
128
+ function resolveRegion(
129
+ container: HTMLElement,
130
+ region: NonNullable<FlowImageExportOptions['region']>,
131
+ ): Rect {
132
+ if (typeof region === 'object') return region;
133
+ const selector = region === 'selection'
134
+ ? '[data-flow-selected="true"], [aria-selected="true"]'
135
+ : region === 'graph'
136
+ ? '[data-entity-id]'
137
+ : null;
138
+ const elements = selector ? Array.from(container.querySelectorAll(selector)) : [container];
139
+ const containerRect = container.getBoundingClientRect();
140
+ if (elements.length === 0) {
141
+ return { x: 0, y: 0, width: containerRect.width, height: containerRect.height };
142
+ }
143
+ const rects = elements.map((element) => element.getBoundingClientRect());
144
+ const left = Math.min(...rects.map((rect) => rect.left));
145
+ const top = Math.min(...rects.map((rect) => rect.top));
146
+ const right = Math.max(...rects.map((rect) => rect.right));
147
+ const bottom = Math.max(...rects.map((rect) => rect.bottom));
148
+ return {
149
+ x: left - containerRect.left,
150
+ y: top - containerRect.top,
151
+ width: right - left,
152
+ height: bottom - top,
153
+ };
154
+ }
155
+
156
+ function nextFrame(
157
+ win: Window,
158
+ signal: FlowImageExportOptions['signal'],
159
+ ): Promise<void> {
160
+ return new Promise((resolve, reject) => {
161
+ const id = win.requestAnimationFrame(() => {
162
+ if (signal?.aborted) reject(abortError());
163
+ else resolve();
164
+ });
165
+ signal?.addEventListener('abort', () => {
166
+ win.cancelAnimationFrame(id);
167
+ reject(abortError());
168
+ }, { once: true });
169
+ });
170
+ }
171
+
172
+ function loadImage(
173
+ win: Window,
174
+ url: string,
175
+ signal: FlowImageExportOptions['signal'],
176
+ ): Promise<HTMLImageElement> {
177
+ return new Promise((resolve, reject) => {
178
+ const ImageCtor = (win as unknown as { Image: new () => HTMLImageElement }).Image;
179
+ const image = new ImageCtor();
180
+ image.onload = () => resolve(image);
181
+ image.onerror = () => reject(new Error('Unable to render Flow SVG.'));
182
+ signal?.addEventListener('abort', () => reject(abortError()), { once: true });
183
+ image.src = url;
184
+ });
185
+ }
186
+
187
+ function canvasBlob(
188
+ canvas: HTMLCanvasElement,
189
+ type: string,
190
+ signal: FlowImageExportOptions['signal'],
191
+ ): Promise<Blob> {
192
+ return new Promise((resolve, reject) => {
193
+ canvas.toBlob((blob) => {
194
+ if (signal?.aborted) reject(abortError());
195
+ else if (blob) resolve(blob);
196
+ else reject(new Error(`Unable to encode ${type}.`));
197
+ }, type);
198
+ });
199
+ }
200
+
201
+ function throwIfAborted(signal: FlowImageExportOptions['signal']): void {
202
+ if (signal?.aborted) throw abortError();
203
+ }
204
+
205
+ function abortError(): Error {
206
+ const error = new Error('The operation was aborted.');
207
+ error.name = 'AbortError';
208
+ return error;
209
+ }
210
+
211
+ function escapeXml(value: string): string {
212
+ return value.replaceAll('&', '&amp;').replaceAll('"', '&quot;').replaceAll('<', '&lt;');
213
+ }