@nuniapp/widget 0.1.3 → 0.1.4
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 +6 -5
- package/dist/index.d.ts +39 -3
- package/dist/index.js +643 -104
- package/dist/mark-BeysEAHp.js +66 -0
- package/dist/nuni-screenshot.global.js +14 -0
- package/dist/nuni.global.js +29 -3
- package/dist/screenshot-B2x2-nI_.js +1288 -0
- package/package.json +2 -1
|
@@ -0,0 +1,1288 @@
|
|
|
1
|
+
import { i as LIMITS, n as MASK_ATTRIBUTE, t as CAPTURE_MARK } from "./mark-BeysEAHp.js";
|
|
2
|
+
"p".charCodeAt(0);
|
|
3
|
+
"H".charCodeAt(0);
|
|
4
|
+
"Y".charCodeAt(0);
|
|
5
|
+
"s".charCodeAt(0);
|
|
6
|
+
const PREFIX = "[modern-screenshot]";
|
|
7
|
+
const IN_BROWSER = typeof window !== "undefined";
|
|
8
|
+
const SUPPORT_WEB_WORKER = IN_BROWSER && "Worker" in window;
|
|
9
|
+
IN_BROWSER && "atob" in window;
|
|
10
|
+
IN_BROWSER && "btoa" in window;
|
|
11
|
+
const USER_AGENT = IN_BROWSER ? window.navigator?.userAgent : "";
|
|
12
|
+
const IN_CHROME = USER_AGENT.includes("Chrome");
|
|
13
|
+
const IN_SAFARI = USER_AGENT.includes("AppleWebKit") && !IN_CHROME;
|
|
14
|
+
const IN_FIREFOX = USER_AGENT.includes("Firefox");
|
|
15
|
+
const isContext = (value) => value && "__CONTEXT__" in value;
|
|
16
|
+
const isCssFontFaceRule = (rule) => rule.constructor.name === "CSSFontFaceRule";
|
|
17
|
+
const isCSSImportRule = (rule) => rule.constructor.name === "CSSImportRule";
|
|
18
|
+
const isLayerBlockRule = (rule) => rule.constructor.name === "CSSLayerBlockRule";
|
|
19
|
+
const isElementNode = (node) => node.nodeType === 1;
|
|
20
|
+
const isSVGElementNode = (node) => typeof node.className === "object";
|
|
21
|
+
const isSVGImageElementNode = (node) => node.tagName === "image";
|
|
22
|
+
const isSVGUseElementNode = (node) => node.tagName === "use";
|
|
23
|
+
const isHTMLElementNode = (node) => isElementNode(node) && typeof node.style !== "undefined" && !isSVGElementNode(node);
|
|
24
|
+
const isCommentNode = (node) => node.nodeType === 8;
|
|
25
|
+
const isTextNode = (node) => node.nodeType === 3;
|
|
26
|
+
const isImageElement = (node) => node.tagName === "IMG";
|
|
27
|
+
const isVideoElement = (node) => node.tagName === "VIDEO";
|
|
28
|
+
const isCanvasElement = (node) => node.tagName === "CANVAS";
|
|
29
|
+
const isTextareaElement = (node) => node.tagName === "TEXTAREA";
|
|
30
|
+
const isInputElement = (node) => node.tagName === "INPUT";
|
|
31
|
+
const isStyleElement = (node) => node.tagName === "STYLE";
|
|
32
|
+
const isScriptElement = (node) => node.tagName === "SCRIPT";
|
|
33
|
+
const isSelectElement = (node) => node.tagName === "SELECT";
|
|
34
|
+
const isSlotElement = (node) => node.tagName === "SLOT";
|
|
35
|
+
const isIFrameElement = (node) => node.tagName === "IFRAME";
|
|
36
|
+
const consoleWarn = (...args) => console.warn(PREFIX, ...args);
|
|
37
|
+
function supportWebp(ownerDocument) {
|
|
38
|
+
const canvas = ownerDocument?.createElement?.("canvas");
|
|
39
|
+
if (canvas) canvas.height = canvas.width = 1;
|
|
40
|
+
return Boolean(canvas) && "toDataURL" in canvas && Boolean(canvas.toDataURL("image/webp").includes("image/webp"));
|
|
41
|
+
}
|
|
42
|
+
const isDataUrl = (url) => url.startsWith("data:");
|
|
43
|
+
function resolveUrl(url, baseUrl) {
|
|
44
|
+
if (url.match(/^[a-z]+:\/\//i)) return url;
|
|
45
|
+
if (IN_BROWSER && url.match(/^\/\//)) return window.location.protocol + url;
|
|
46
|
+
if (url.match(/^[a-z]+:/i)) return url;
|
|
47
|
+
if (!IN_BROWSER) return url;
|
|
48
|
+
const doc = getDocument().implementation.createHTMLDocument();
|
|
49
|
+
const base = doc.createElement("base");
|
|
50
|
+
const a = doc.createElement("a");
|
|
51
|
+
doc.head.appendChild(base);
|
|
52
|
+
doc.body.appendChild(a);
|
|
53
|
+
if (baseUrl) base.href = baseUrl;
|
|
54
|
+
a.href = url;
|
|
55
|
+
return a.href;
|
|
56
|
+
}
|
|
57
|
+
function getDocument(target) {
|
|
58
|
+
return (target && isElementNode(target) ? target?.ownerDocument : target) ?? window.document;
|
|
59
|
+
}
|
|
60
|
+
const XMLNS = "http://www.w3.org/2000/svg";
|
|
61
|
+
function createSvg(width, height, ownerDocument) {
|
|
62
|
+
const svg = getDocument(ownerDocument).createElementNS(XMLNS, "svg");
|
|
63
|
+
svg.setAttributeNS(null, "width", width.toString());
|
|
64
|
+
svg.setAttributeNS(null, "height", height.toString());
|
|
65
|
+
svg.setAttributeNS(null, "viewBox", `0 0 ${width} ${height}`);
|
|
66
|
+
return svg;
|
|
67
|
+
}
|
|
68
|
+
function svgToDataUrl(svg, removeControlCharacter) {
|
|
69
|
+
let xhtml = new XMLSerializer().serializeToString(svg);
|
|
70
|
+
if (removeControlCharacter) xhtml = xhtml.replace(/[\u0000-\u0008\v\f\u000E-\u001F\uD800-\uDFFF\uFFFE\uFFFF]/gu, "");
|
|
71
|
+
return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(xhtml)}`;
|
|
72
|
+
}
|
|
73
|
+
function readBlob(blob, type) {
|
|
74
|
+
return new Promise((resolve, reject) => {
|
|
75
|
+
const reader = new FileReader();
|
|
76
|
+
reader.onload = () => resolve(reader.result);
|
|
77
|
+
reader.onerror = () => reject(reader.error);
|
|
78
|
+
reader.onabort = () => reject(/* @__PURE__ */ new Error(`Failed read blob to ${type}`));
|
|
79
|
+
if (type === "dataUrl") reader.readAsDataURL(blob);
|
|
80
|
+
else if (type === "arrayBuffer") reader.readAsArrayBuffer(blob);
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
const blobToDataUrl = (blob) => readBlob(blob, "dataUrl");
|
|
84
|
+
function createImage(url, ownerDocument) {
|
|
85
|
+
const img = getDocument(ownerDocument).createElement("img");
|
|
86
|
+
img.decoding = "sync";
|
|
87
|
+
img.loading = "eager";
|
|
88
|
+
img.src = url;
|
|
89
|
+
return img;
|
|
90
|
+
}
|
|
91
|
+
function loadMedia(media, options) {
|
|
92
|
+
return new Promise((resolve) => {
|
|
93
|
+
const { timeout, ownerDocument, onError: userOnError, onWarn } = options ?? {};
|
|
94
|
+
const node = typeof media === "string" ? createImage(media, getDocument(ownerDocument)) : media;
|
|
95
|
+
let timer = null;
|
|
96
|
+
let removeEventListeners = null;
|
|
97
|
+
function onResolve() {
|
|
98
|
+
resolve(node);
|
|
99
|
+
timer && clearTimeout(timer);
|
|
100
|
+
removeEventListeners?.();
|
|
101
|
+
}
|
|
102
|
+
if (timeout) timer = setTimeout(onResolve, timeout);
|
|
103
|
+
if (isVideoElement(node)) {
|
|
104
|
+
const currentSrc = node.currentSrc || node.src;
|
|
105
|
+
if (!currentSrc) {
|
|
106
|
+
if (node.poster) return loadMedia(node.poster, options).then(resolve);
|
|
107
|
+
return onResolve();
|
|
108
|
+
}
|
|
109
|
+
if (node.readyState >= 2) return onResolve();
|
|
110
|
+
const onLoadeddata = onResolve;
|
|
111
|
+
const onError = (error) => {
|
|
112
|
+
onWarn?.("Failed video load", currentSrc, error);
|
|
113
|
+
userOnError?.(error);
|
|
114
|
+
onResolve();
|
|
115
|
+
};
|
|
116
|
+
removeEventListeners = () => {
|
|
117
|
+
node.removeEventListener("loadeddata", onLoadeddata);
|
|
118
|
+
node.removeEventListener("error", onError);
|
|
119
|
+
};
|
|
120
|
+
node.addEventListener("loadeddata", onLoadeddata, { once: true });
|
|
121
|
+
node.addEventListener("error", onError, { once: true });
|
|
122
|
+
} else {
|
|
123
|
+
const currentSrc = isSVGImageElementNode(node) ? node.href.baseVal : node.currentSrc || node.src;
|
|
124
|
+
if (!currentSrc) return onResolve();
|
|
125
|
+
const onLoad = async () => {
|
|
126
|
+
if (isImageElement(node) && "decode" in node) try {
|
|
127
|
+
await node.decode();
|
|
128
|
+
} catch (error) {
|
|
129
|
+
onWarn?.("Failed to decode image, trying to render anyway", node.dataset.originalSrc || currentSrc, error);
|
|
130
|
+
}
|
|
131
|
+
onResolve();
|
|
132
|
+
};
|
|
133
|
+
const onError = (error) => {
|
|
134
|
+
onWarn?.("Failed image load", node.dataset.originalSrc || currentSrc, error);
|
|
135
|
+
onResolve();
|
|
136
|
+
};
|
|
137
|
+
if (isImageElement(node) && node.complete) return onLoad();
|
|
138
|
+
removeEventListeners = () => {
|
|
139
|
+
node.removeEventListener("load", onLoad);
|
|
140
|
+
node.removeEventListener("error", onError);
|
|
141
|
+
};
|
|
142
|
+
node.addEventListener("load", onLoad, { once: true });
|
|
143
|
+
node.addEventListener("error", onError, { once: true });
|
|
144
|
+
}
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
async function waitUntilLoad(node, options) {
|
|
148
|
+
if (isHTMLElementNode(node)) {
|
|
149
|
+
if (isImageElement(node) || isVideoElement(node)) await loadMedia(node, options);
|
|
150
|
+
else await Promise.all(["img", "video"].flatMap((selectors) => {
|
|
151
|
+
return Array.from(node.querySelectorAll(selectors)).map((el) => loadMedia(el, options));
|
|
152
|
+
}));
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
const uuid = /* @__PURE__ */ function uuid2() {
|
|
156
|
+
let counter = 0;
|
|
157
|
+
const random = () => `0000${(Math.random() * 36 ** 4 << 0).toString(36)}`.slice(-4);
|
|
158
|
+
return () => {
|
|
159
|
+
counter += 1;
|
|
160
|
+
return `u${random()}${counter}`;
|
|
161
|
+
};
|
|
162
|
+
}();
|
|
163
|
+
function splitFontFamily(fontFamily) {
|
|
164
|
+
return fontFamily?.split(",").map((val) => val.trim().replace(/"|'/g, "").toLowerCase()).filter(Boolean);
|
|
165
|
+
}
|
|
166
|
+
let uid = 0;
|
|
167
|
+
function createLogger(debug) {
|
|
168
|
+
const prefix = `${PREFIX}[#${uid}]`;
|
|
169
|
+
uid++;
|
|
170
|
+
return {
|
|
171
|
+
time: (label) => debug && console.time(`${prefix} ${label}`),
|
|
172
|
+
timeEnd: (label) => debug && console.timeEnd(`${prefix} ${label}`),
|
|
173
|
+
warn: (...args) => debug && consoleWarn(...args)
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
function getDefaultRequestInit(bypassingCache) {
|
|
177
|
+
return { cache: bypassingCache ? "no-cache" : "force-cache" };
|
|
178
|
+
}
|
|
179
|
+
async function orCreateContext(node, options) {
|
|
180
|
+
return isContext(node) ? node : createContext(node, {
|
|
181
|
+
...options,
|
|
182
|
+
autoDestruct: true
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
async function createContext(node, options) {
|
|
186
|
+
const { scale = 1, workerUrl, workerNumber = 1 } = options || {};
|
|
187
|
+
const debug = Boolean(options?.debug);
|
|
188
|
+
const features = options?.features ?? true;
|
|
189
|
+
const ownerDocument = node.ownerDocument ?? (IN_BROWSER ? window.document : void 0);
|
|
190
|
+
const ownerWindow = node.ownerDocument?.defaultView ?? (IN_BROWSER ? window : void 0);
|
|
191
|
+
const requests = /* @__PURE__ */ new Map();
|
|
192
|
+
const context = {
|
|
193
|
+
width: 0,
|
|
194
|
+
height: 0,
|
|
195
|
+
quality: 1,
|
|
196
|
+
type: "image/png",
|
|
197
|
+
scale,
|
|
198
|
+
backgroundColor: null,
|
|
199
|
+
style: null,
|
|
200
|
+
filter: null,
|
|
201
|
+
maximumCanvasSize: 0,
|
|
202
|
+
timeout: 3e4,
|
|
203
|
+
progress: null,
|
|
204
|
+
debug,
|
|
205
|
+
fetch: {
|
|
206
|
+
requestInit: getDefaultRequestInit(options?.fetch?.bypassingCache),
|
|
207
|
+
placeholderImage: "data:image/png;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",
|
|
208
|
+
bypassingCache: false,
|
|
209
|
+
...options?.fetch
|
|
210
|
+
},
|
|
211
|
+
fetchFn: null,
|
|
212
|
+
font: {},
|
|
213
|
+
drawImageInterval: 100,
|
|
214
|
+
workerUrl: null,
|
|
215
|
+
workerNumber,
|
|
216
|
+
onCloneEachNode: null,
|
|
217
|
+
onCloneNode: null,
|
|
218
|
+
onEmbedNode: null,
|
|
219
|
+
onCreateForeignObjectSvg: null,
|
|
220
|
+
includeStyleProperties: null,
|
|
221
|
+
autoDestruct: false,
|
|
222
|
+
...options,
|
|
223
|
+
__CONTEXT__: true,
|
|
224
|
+
log: createLogger(debug),
|
|
225
|
+
node,
|
|
226
|
+
ownerDocument,
|
|
227
|
+
ownerWindow,
|
|
228
|
+
dpi: scale === 1 ? null : 96 * scale,
|
|
229
|
+
svgStyleElement: createStyleElement(ownerDocument),
|
|
230
|
+
svgDefsElement: ownerDocument?.createElementNS(XMLNS, "defs"),
|
|
231
|
+
svgStyles: /* @__PURE__ */ new Map(),
|
|
232
|
+
defaultComputedStyles: /* @__PURE__ */ new Map(),
|
|
233
|
+
workers: [...Array.from({ length: SUPPORT_WEB_WORKER && workerUrl && workerNumber ? workerNumber : 0 })].map(() => {
|
|
234
|
+
try {
|
|
235
|
+
const worker = new Worker(workerUrl);
|
|
236
|
+
worker.onmessage = async (event) => {
|
|
237
|
+
const { url, result } = event.data;
|
|
238
|
+
if (result) requests.get(url)?.resolve?.(result);
|
|
239
|
+
else requests.get(url)?.reject?.(/* @__PURE__ */ new Error(`Error receiving message from worker: ${url}`));
|
|
240
|
+
};
|
|
241
|
+
worker.onmessageerror = (event) => {
|
|
242
|
+
const { url } = event.data;
|
|
243
|
+
requests.get(url)?.reject?.(/* @__PURE__ */ new Error(`Error receiving message from worker: ${url}`));
|
|
244
|
+
};
|
|
245
|
+
return worker;
|
|
246
|
+
} catch (error) {
|
|
247
|
+
context.log.warn("Failed to new Worker", error);
|
|
248
|
+
return null;
|
|
249
|
+
}
|
|
250
|
+
}).filter(Boolean),
|
|
251
|
+
fontFamilies: /* @__PURE__ */ new Map(),
|
|
252
|
+
fontCssTexts: /* @__PURE__ */ new Map(),
|
|
253
|
+
acceptOfImage: `${[
|
|
254
|
+
supportWebp(ownerDocument) && "image/webp",
|
|
255
|
+
"image/svg+xml",
|
|
256
|
+
"image/*",
|
|
257
|
+
"*/*"
|
|
258
|
+
].filter(Boolean).join(",")};q=0.8`,
|
|
259
|
+
requests,
|
|
260
|
+
drawImageCount: 0,
|
|
261
|
+
tasks: [],
|
|
262
|
+
features,
|
|
263
|
+
isEnable: (key) => {
|
|
264
|
+
if (key === "restoreScrollPosition") return typeof features === "boolean" ? false : features[key] ?? false;
|
|
265
|
+
if (typeof features === "boolean") return features;
|
|
266
|
+
return features[key] ?? true;
|
|
267
|
+
},
|
|
268
|
+
shadowRoots: []
|
|
269
|
+
};
|
|
270
|
+
context.log.time("wait until load");
|
|
271
|
+
await waitUntilLoad(node, {
|
|
272
|
+
timeout: context.timeout,
|
|
273
|
+
onWarn: context.log.warn
|
|
274
|
+
});
|
|
275
|
+
context.log.timeEnd("wait until load");
|
|
276
|
+
const { width, height } = resolveBoundingBox(node, context);
|
|
277
|
+
context.width = width;
|
|
278
|
+
context.height = height;
|
|
279
|
+
return context;
|
|
280
|
+
}
|
|
281
|
+
function createStyleElement(ownerDocument) {
|
|
282
|
+
if (!ownerDocument) return void 0;
|
|
283
|
+
const style = ownerDocument.createElement("style");
|
|
284
|
+
const cssText = style.ownerDocument.createTextNode(`
|
|
285
|
+
.______background-clip--text {
|
|
286
|
+
background-clip: text;
|
|
287
|
+
-webkit-background-clip: text;
|
|
288
|
+
}
|
|
289
|
+
`);
|
|
290
|
+
style.appendChild(cssText);
|
|
291
|
+
return style;
|
|
292
|
+
}
|
|
293
|
+
function resolveBoundingBox(node, context) {
|
|
294
|
+
let { width, height } = context;
|
|
295
|
+
if (isElementNode(node) && (!width || !height)) {
|
|
296
|
+
const box = node.getBoundingClientRect();
|
|
297
|
+
width = width || box.width || Number(node.getAttribute("width")) || 0;
|
|
298
|
+
height = height || box.height || Number(node.getAttribute("height")) || 0;
|
|
299
|
+
}
|
|
300
|
+
return {
|
|
301
|
+
width,
|
|
302
|
+
height
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
async function imageToCanvas(image, context) {
|
|
306
|
+
const { log, timeout, drawImageCount, drawImageInterval } = context;
|
|
307
|
+
log.time("image to canvas");
|
|
308
|
+
const loaded = await loadMedia(image, {
|
|
309
|
+
timeout,
|
|
310
|
+
onWarn: context.log.warn
|
|
311
|
+
});
|
|
312
|
+
const { canvas, context2d } = createCanvas(image.ownerDocument, context);
|
|
313
|
+
const drawImage = () => {
|
|
314
|
+
try {
|
|
315
|
+
context2d?.drawImage(loaded, 0, 0, canvas.width, canvas.height);
|
|
316
|
+
} catch (error) {
|
|
317
|
+
context.log.warn("Failed to drawImage", error);
|
|
318
|
+
}
|
|
319
|
+
};
|
|
320
|
+
drawImage();
|
|
321
|
+
if (context.isEnable("fixSvgXmlDecode")) for (let i = 0; i < drawImageCount; i++) await new Promise((resolve) => {
|
|
322
|
+
setTimeout(() => {
|
|
323
|
+
context2d?.clearRect(0, 0, canvas.width, canvas.height);
|
|
324
|
+
drawImage();
|
|
325
|
+
resolve();
|
|
326
|
+
}, i + drawImageInterval);
|
|
327
|
+
});
|
|
328
|
+
context.drawImageCount = 0;
|
|
329
|
+
log.timeEnd("image to canvas");
|
|
330
|
+
return canvas;
|
|
331
|
+
}
|
|
332
|
+
function createCanvas(ownerDocument, context) {
|
|
333
|
+
const { width, height, scale, backgroundColor, maximumCanvasSize: max } = context;
|
|
334
|
+
const canvas = ownerDocument.createElement("canvas");
|
|
335
|
+
canvas.width = Math.floor(width * scale);
|
|
336
|
+
canvas.height = Math.floor(height * scale);
|
|
337
|
+
canvas.style.width = `${width}px`;
|
|
338
|
+
canvas.style.height = `${height}px`;
|
|
339
|
+
if (max) {
|
|
340
|
+
if (canvas.width > max || canvas.height > max) {
|
|
341
|
+
if (canvas.width > max && canvas.height > max) {
|
|
342
|
+
if (canvas.width > canvas.height) {
|
|
343
|
+
canvas.height *= max / canvas.width;
|
|
344
|
+
canvas.width = max;
|
|
345
|
+
} else {
|
|
346
|
+
canvas.width *= max / canvas.height;
|
|
347
|
+
canvas.height = max;
|
|
348
|
+
}
|
|
349
|
+
} else if (canvas.width > max) {
|
|
350
|
+
canvas.height *= max / canvas.width;
|
|
351
|
+
canvas.width = max;
|
|
352
|
+
} else {
|
|
353
|
+
canvas.width *= max / canvas.height;
|
|
354
|
+
canvas.height = max;
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
const context2d = canvas.getContext("2d");
|
|
359
|
+
if (context2d && backgroundColor) {
|
|
360
|
+
context2d.fillStyle = backgroundColor;
|
|
361
|
+
context2d.fillRect(0, 0, canvas.width, canvas.height);
|
|
362
|
+
}
|
|
363
|
+
return {
|
|
364
|
+
canvas,
|
|
365
|
+
context2d
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
function cloneCanvas(canvas, context) {
|
|
369
|
+
if (canvas.ownerDocument) try {
|
|
370
|
+
const dataURL = canvas.toDataURL();
|
|
371
|
+
if (dataURL !== "data:,") return createImage(dataURL, canvas.ownerDocument);
|
|
372
|
+
} catch (error) {
|
|
373
|
+
context.log.warn("Failed to clone canvas", error);
|
|
374
|
+
}
|
|
375
|
+
const cloned = canvas.cloneNode(false);
|
|
376
|
+
const ctx = canvas.getContext("2d");
|
|
377
|
+
const clonedCtx = cloned.getContext("2d");
|
|
378
|
+
try {
|
|
379
|
+
if (ctx && clonedCtx) clonedCtx.putImageData(ctx.getImageData(0, 0, canvas.width, canvas.height), 0, 0);
|
|
380
|
+
return cloned;
|
|
381
|
+
} catch (error) {
|
|
382
|
+
context.log.warn("Failed to clone canvas", error);
|
|
383
|
+
}
|
|
384
|
+
return cloned;
|
|
385
|
+
}
|
|
386
|
+
function cloneIframe(iframe, context) {
|
|
387
|
+
try {
|
|
388
|
+
if (iframe?.contentDocument?.documentElement) return cloneNode(iframe.contentDocument.documentElement, context);
|
|
389
|
+
} catch (error) {
|
|
390
|
+
context.log.warn("Failed to clone iframe", error);
|
|
391
|
+
}
|
|
392
|
+
return iframe.cloneNode(false);
|
|
393
|
+
}
|
|
394
|
+
function cloneImage(image) {
|
|
395
|
+
const cloned = image.cloneNode(false);
|
|
396
|
+
if (image.currentSrc && image.currentSrc !== image.src) {
|
|
397
|
+
cloned.src = image.currentSrc;
|
|
398
|
+
cloned.srcset = "";
|
|
399
|
+
}
|
|
400
|
+
if (cloned.loading === "lazy") cloned.loading = "eager";
|
|
401
|
+
return cloned;
|
|
402
|
+
}
|
|
403
|
+
async function cloneVideo(video, context) {
|
|
404
|
+
if (video.ownerDocument && !video.currentSrc && video.poster) return createImage(video.poster, video.ownerDocument);
|
|
405
|
+
const cloned = video.cloneNode(false);
|
|
406
|
+
cloned.crossOrigin = "anonymous";
|
|
407
|
+
if (video.currentSrc && video.currentSrc !== video.src) cloned.src = video.currentSrc;
|
|
408
|
+
const ownerDocument = cloned.ownerDocument;
|
|
409
|
+
if (ownerDocument) {
|
|
410
|
+
let canPlay = true;
|
|
411
|
+
await loadMedia(cloned, {
|
|
412
|
+
onError: () => canPlay = false,
|
|
413
|
+
onWarn: context.log.warn
|
|
414
|
+
});
|
|
415
|
+
if (!canPlay) {
|
|
416
|
+
if (video.poster) return createImage(video.poster, video.ownerDocument);
|
|
417
|
+
return cloned;
|
|
418
|
+
}
|
|
419
|
+
cloned.currentTime = video.currentTime;
|
|
420
|
+
await new Promise((resolve) => {
|
|
421
|
+
cloned.addEventListener("seeked", resolve, { once: true });
|
|
422
|
+
});
|
|
423
|
+
const canvas = ownerDocument.createElement("canvas");
|
|
424
|
+
canvas.width = video.offsetWidth;
|
|
425
|
+
canvas.height = video.offsetHeight;
|
|
426
|
+
try {
|
|
427
|
+
const ctx = canvas.getContext("2d");
|
|
428
|
+
if (ctx) ctx.drawImage(cloned, 0, 0, canvas.width, canvas.height);
|
|
429
|
+
} catch (error) {
|
|
430
|
+
context.log.warn("Failed to clone video", error);
|
|
431
|
+
if (video.poster) return createImage(video.poster, video.ownerDocument);
|
|
432
|
+
return cloned;
|
|
433
|
+
}
|
|
434
|
+
return cloneCanvas(canvas, context);
|
|
435
|
+
}
|
|
436
|
+
return cloned;
|
|
437
|
+
}
|
|
438
|
+
function cloneElement(node, context) {
|
|
439
|
+
if (isCanvasElement(node)) return cloneCanvas(node, context);
|
|
440
|
+
if (isIFrameElement(node)) return cloneIframe(node, context);
|
|
441
|
+
if (isImageElement(node)) return cloneImage(node);
|
|
442
|
+
if (isVideoElement(node)) return cloneVideo(node, context);
|
|
443
|
+
return node.cloneNode(false);
|
|
444
|
+
}
|
|
445
|
+
function getSandBox(context) {
|
|
446
|
+
let sandbox = context.sandbox;
|
|
447
|
+
if (!sandbox) {
|
|
448
|
+
const { ownerDocument } = context;
|
|
449
|
+
try {
|
|
450
|
+
if (ownerDocument) {
|
|
451
|
+
sandbox = ownerDocument.createElement("iframe");
|
|
452
|
+
sandbox.id = `__SANDBOX__${uuid()}`;
|
|
453
|
+
sandbox.width = "0";
|
|
454
|
+
sandbox.height = "0";
|
|
455
|
+
sandbox.style.visibility = "hidden";
|
|
456
|
+
sandbox.style.position = "fixed";
|
|
457
|
+
ownerDocument.body.appendChild(sandbox);
|
|
458
|
+
sandbox.srcdoc = "<!DOCTYPE html><meta charset=\"UTF-8\"><title></title><body>";
|
|
459
|
+
context.sandbox = sandbox;
|
|
460
|
+
}
|
|
461
|
+
} catch (error) {
|
|
462
|
+
context.log.warn("Failed to getSandBox", error);
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
return sandbox;
|
|
466
|
+
}
|
|
467
|
+
const ignoredStyles = [
|
|
468
|
+
"width",
|
|
469
|
+
"height",
|
|
470
|
+
"-webkit-text-fill-color"
|
|
471
|
+
];
|
|
472
|
+
const includedAttributes = ["stroke", "fill"];
|
|
473
|
+
function getDefaultStyle(node, pseudoElement, context) {
|
|
474
|
+
const { defaultComputedStyles } = context;
|
|
475
|
+
const nodeName = node.nodeName.toLowerCase();
|
|
476
|
+
const isSvgNode = isSVGElementNode(node) && nodeName !== "svg";
|
|
477
|
+
const attributes = isSvgNode ? includedAttributes.map((name) => [name, node.getAttribute(name)]).filter(([, value]) => value !== null) : [];
|
|
478
|
+
const key = [
|
|
479
|
+
isSvgNode && "svg",
|
|
480
|
+
nodeName,
|
|
481
|
+
attributes.map((name, value) => `${name}=${value}`).join(","),
|
|
482
|
+
pseudoElement
|
|
483
|
+
].filter(Boolean).join(":");
|
|
484
|
+
if (defaultComputedStyles.has(key)) return defaultComputedStyles.get(key);
|
|
485
|
+
const sandboxWindow = getSandBox(context)?.contentWindow;
|
|
486
|
+
if (!sandboxWindow) return /* @__PURE__ */ new Map();
|
|
487
|
+
const sandboxDocument = sandboxWindow?.document;
|
|
488
|
+
let root;
|
|
489
|
+
let el;
|
|
490
|
+
if (isSvgNode) {
|
|
491
|
+
root = sandboxDocument.createElementNS(XMLNS, "svg");
|
|
492
|
+
el = root.ownerDocument.createElementNS(root.namespaceURI, nodeName);
|
|
493
|
+
attributes.forEach(([name, value]) => {
|
|
494
|
+
el.setAttributeNS(null, name, value);
|
|
495
|
+
});
|
|
496
|
+
root.appendChild(el);
|
|
497
|
+
} else root = el = sandboxDocument.createElement(nodeName);
|
|
498
|
+
el.textContent = " ";
|
|
499
|
+
sandboxDocument.body.appendChild(root);
|
|
500
|
+
const computedStyle = sandboxWindow.getComputedStyle(el, pseudoElement);
|
|
501
|
+
const styles = /* @__PURE__ */ new Map();
|
|
502
|
+
for (let len = computedStyle.length, i = 0; i < len; i++) {
|
|
503
|
+
const name = computedStyle.item(i);
|
|
504
|
+
if (ignoredStyles.includes(name)) continue;
|
|
505
|
+
styles.set(name, computedStyle.getPropertyValue(name));
|
|
506
|
+
}
|
|
507
|
+
sandboxDocument.body.removeChild(root);
|
|
508
|
+
defaultComputedStyles.set(key, styles);
|
|
509
|
+
return styles;
|
|
510
|
+
}
|
|
511
|
+
function getDiffStyle(style, defaultStyle, includeStyleProperties) {
|
|
512
|
+
const diffStyle = /* @__PURE__ */ new Map();
|
|
513
|
+
const prefixs = [];
|
|
514
|
+
const prefixTree = /* @__PURE__ */ new Map();
|
|
515
|
+
if (includeStyleProperties) for (const name of includeStyleProperties) applyTo(name);
|
|
516
|
+
else for (let len = style.length, i = 0; i < len; i++) applyTo(style.item(i));
|
|
517
|
+
for (let len = prefixs.length, i = 0; i < len; i++) prefixTree.get(prefixs[i])?.forEach((value, name) => diffStyle.set(name, value));
|
|
518
|
+
function applyTo(name) {
|
|
519
|
+
const value = style.getPropertyValue(name);
|
|
520
|
+
const priority = style.getPropertyPriority(name);
|
|
521
|
+
const subIndex = name.lastIndexOf("-");
|
|
522
|
+
const prefix = subIndex > -1 ? name.substring(0, subIndex) : void 0;
|
|
523
|
+
if (prefix) {
|
|
524
|
+
let map = prefixTree.get(prefix);
|
|
525
|
+
if (!map) {
|
|
526
|
+
map = /* @__PURE__ */ new Map();
|
|
527
|
+
prefixTree.set(prefix, map);
|
|
528
|
+
}
|
|
529
|
+
map.set(name, [value, priority]);
|
|
530
|
+
}
|
|
531
|
+
if (defaultStyle.get(name) === value && !priority) return;
|
|
532
|
+
if (prefix) prefixs.push(prefix);
|
|
533
|
+
else diffStyle.set(name, [value, priority]);
|
|
534
|
+
}
|
|
535
|
+
return diffStyle;
|
|
536
|
+
}
|
|
537
|
+
function copyCssStyles(node, cloned, isRoot, context) {
|
|
538
|
+
const { ownerWindow, includeStyleProperties, currentParentNodeStyle } = context;
|
|
539
|
+
const clonedStyle = cloned.style;
|
|
540
|
+
const computedStyle = ownerWindow.getComputedStyle(node);
|
|
541
|
+
const defaultStyle = getDefaultStyle(node, null, context);
|
|
542
|
+
currentParentNodeStyle?.forEach((_, key) => {
|
|
543
|
+
defaultStyle.delete(key);
|
|
544
|
+
});
|
|
545
|
+
const style = getDiffStyle(computedStyle, defaultStyle, includeStyleProperties);
|
|
546
|
+
style.delete("transition-property");
|
|
547
|
+
style.delete("all");
|
|
548
|
+
style.delete("d");
|
|
549
|
+
style.delete("content");
|
|
550
|
+
if (isRoot) {
|
|
551
|
+
style.delete("position");
|
|
552
|
+
style.delete("margin-top");
|
|
553
|
+
style.delete("margin-right");
|
|
554
|
+
style.delete("margin-bottom");
|
|
555
|
+
style.delete("margin-left");
|
|
556
|
+
style.delete("margin-block-start");
|
|
557
|
+
style.delete("margin-block-end");
|
|
558
|
+
style.delete("margin-inline-start");
|
|
559
|
+
style.delete("margin-inline-end");
|
|
560
|
+
style.set("box-sizing", ["border-box", ""]);
|
|
561
|
+
}
|
|
562
|
+
if (style.get("background-clip")?.[0] === "text") cloned.classList.add("______background-clip--text");
|
|
563
|
+
if (IN_CHROME) {
|
|
564
|
+
if (!style.has("font-kerning")) style.set("font-kerning", ["normal", ""]);
|
|
565
|
+
if ((style.get("overflow-x")?.[0] === "hidden" || style.get("overflow-y")?.[0] === "hidden") && style.get("text-overflow")?.[0] === "ellipsis" && node.scrollWidth === node.clientWidth) style.set("text-overflow", ["clip", ""]);
|
|
566
|
+
}
|
|
567
|
+
for (let len = clonedStyle.length, i = 0; i < len; i++) clonedStyle.removeProperty(clonedStyle.item(i));
|
|
568
|
+
style.forEach(([value, priority], name) => {
|
|
569
|
+
clonedStyle.setProperty(name, value, priority);
|
|
570
|
+
});
|
|
571
|
+
return style;
|
|
572
|
+
}
|
|
573
|
+
function copyInputValue(node, cloned) {
|
|
574
|
+
if (isTextareaElement(node) || isInputElement(node) || isSelectElement(node)) cloned.setAttribute("value", node.value);
|
|
575
|
+
}
|
|
576
|
+
const pseudoClasses = ["::before", "::after"];
|
|
577
|
+
const scrollbarPseudoClasses = [
|
|
578
|
+
"::-webkit-scrollbar",
|
|
579
|
+
"::-webkit-scrollbar-button",
|
|
580
|
+
"::-webkit-scrollbar-thumb",
|
|
581
|
+
"::-webkit-scrollbar-track",
|
|
582
|
+
"::-webkit-scrollbar-track-piece",
|
|
583
|
+
"::-webkit-scrollbar-corner",
|
|
584
|
+
"::-webkit-resizer"
|
|
585
|
+
];
|
|
586
|
+
function copyPseudoClass(node, cloned, copyScrollbar, context, addWordToFontFamilies) {
|
|
587
|
+
const { ownerWindow, svgStyleElement, svgStyles, currentNodeStyle } = context;
|
|
588
|
+
if (!svgStyleElement || !ownerWindow) return;
|
|
589
|
+
function copyBy(pseudoClass) {
|
|
590
|
+
const computedStyle = ownerWindow.getComputedStyle(node, pseudoClass);
|
|
591
|
+
let content = computedStyle.getPropertyValue("content");
|
|
592
|
+
if (!content || content === "none") return;
|
|
593
|
+
addWordToFontFamilies?.(content);
|
|
594
|
+
content = content.replace(/(')|(")|(counter\(.+\))/g, "");
|
|
595
|
+
const klasses = [uuid()];
|
|
596
|
+
const defaultStyle = getDefaultStyle(node, pseudoClass, context);
|
|
597
|
+
currentNodeStyle?.forEach((_, key) => {
|
|
598
|
+
defaultStyle.delete(key);
|
|
599
|
+
});
|
|
600
|
+
const style = getDiffStyle(computedStyle, defaultStyle, context.includeStyleProperties);
|
|
601
|
+
style.delete("content");
|
|
602
|
+
style.delete("-webkit-locale");
|
|
603
|
+
if (style.get("background-clip")?.[0] === "text") cloned.classList.add("______background-clip--text");
|
|
604
|
+
const cloneStyle = [`content: '${content}';`];
|
|
605
|
+
style.forEach(([value, priority], name) => {
|
|
606
|
+
cloneStyle.push(`${name}: ${value}${priority ? " !important" : ""};`);
|
|
607
|
+
});
|
|
608
|
+
if (cloneStyle.length === 1) return;
|
|
609
|
+
try {
|
|
610
|
+
cloned.className = [cloned.className, ...klasses].join(" ");
|
|
611
|
+
} catch (err) {
|
|
612
|
+
context.log.warn("Failed to copyPseudoClass", err);
|
|
613
|
+
return;
|
|
614
|
+
}
|
|
615
|
+
const cssText = cloneStyle.join("\n ");
|
|
616
|
+
let allClasses = svgStyles.get(cssText);
|
|
617
|
+
if (!allClasses) {
|
|
618
|
+
allClasses = [];
|
|
619
|
+
svgStyles.set(cssText, allClasses);
|
|
620
|
+
}
|
|
621
|
+
allClasses.push(`.${klasses[0]}${pseudoClass}`);
|
|
622
|
+
}
|
|
623
|
+
pseudoClasses.forEach(copyBy);
|
|
624
|
+
if (copyScrollbar) scrollbarPseudoClasses.forEach(copyBy);
|
|
625
|
+
}
|
|
626
|
+
const excludeParentNodes = /* @__PURE__ */ new Set(["symbol"]);
|
|
627
|
+
async function appendChildNode(node, cloned, child, context, addWordToFontFamilies) {
|
|
628
|
+
if (isElementNode(child) && (isStyleElement(child) || isScriptElement(child))) return;
|
|
629
|
+
if (context.filter && !context.filter(child)) return;
|
|
630
|
+
if (excludeParentNodes.has(cloned.nodeName) || excludeParentNodes.has(child.nodeName)) context.currentParentNodeStyle = void 0;
|
|
631
|
+
else context.currentParentNodeStyle = context.currentNodeStyle;
|
|
632
|
+
const childCloned = await cloneNode(child, context, false, addWordToFontFamilies);
|
|
633
|
+
if (context.isEnable("restoreScrollPosition")) restoreScrollPosition(node, childCloned);
|
|
634
|
+
cloned.appendChild(childCloned);
|
|
635
|
+
}
|
|
636
|
+
async function cloneChildNodes(node, cloned, context, addWordToFontFamilies) {
|
|
637
|
+
let firstChild = node.firstChild;
|
|
638
|
+
if (isElementNode(node)) {
|
|
639
|
+
if (node.shadowRoot) {
|
|
640
|
+
firstChild = node.shadowRoot?.firstChild;
|
|
641
|
+
context.shadowRoots.push(node.shadowRoot);
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
for (let child = firstChild; child; child = child.nextSibling) {
|
|
645
|
+
if (isCommentNode(child)) continue;
|
|
646
|
+
if (isElementNode(child) && isSlotElement(child) && typeof child.assignedNodes === "function") {
|
|
647
|
+
const nodes = child.assignedNodes();
|
|
648
|
+
for (let i = 0; i < nodes.length; i++) await appendChildNode(node, cloned, nodes[i], context, addWordToFontFamilies);
|
|
649
|
+
} else await appendChildNode(node, cloned, child, context, addWordToFontFamilies);
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
function restoreScrollPosition(node, chlidCloned) {
|
|
653
|
+
if (!isHTMLElementNode(node) || !isHTMLElementNode(chlidCloned)) return;
|
|
654
|
+
const { scrollTop, scrollLeft } = node;
|
|
655
|
+
if (!scrollTop && !scrollLeft) return;
|
|
656
|
+
const { transform } = chlidCloned.style;
|
|
657
|
+
const matrix = new DOMMatrix(transform);
|
|
658
|
+
const { a, b, c, d } = matrix;
|
|
659
|
+
matrix.a = 1;
|
|
660
|
+
matrix.b = 0;
|
|
661
|
+
matrix.c = 0;
|
|
662
|
+
matrix.d = 1;
|
|
663
|
+
matrix.translateSelf(-scrollLeft, -scrollTop);
|
|
664
|
+
matrix.a = a;
|
|
665
|
+
matrix.b = b;
|
|
666
|
+
matrix.c = c;
|
|
667
|
+
matrix.d = d;
|
|
668
|
+
chlidCloned.style.transform = matrix.toString();
|
|
669
|
+
}
|
|
670
|
+
function applyCssStyleWithOptions(cloned, context) {
|
|
671
|
+
const { backgroundColor, width, height, style: styles } = context;
|
|
672
|
+
const clonedStyle = cloned.style;
|
|
673
|
+
if (backgroundColor) clonedStyle.setProperty("background-color", backgroundColor, "important");
|
|
674
|
+
if (width) clonedStyle.setProperty("width", `${width}px`, "important");
|
|
675
|
+
if (height) clonedStyle.setProperty("height", `${height}px`, "important");
|
|
676
|
+
if (styles) for (const name in styles) clonedStyle[name] = styles[name];
|
|
677
|
+
}
|
|
678
|
+
const NORMAL_ATTRIBUTE_RE = /^[\w-:]+$/;
|
|
679
|
+
async function cloneNode(node, context, isRoot = false, addWordToFontFamilies) {
|
|
680
|
+
const { ownerDocument, ownerWindow, fontFamilies, onCloneEachNode } = context;
|
|
681
|
+
if (ownerDocument && isTextNode(node)) {
|
|
682
|
+
if (addWordToFontFamilies && /\S/.test(node.data)) addWordToFontFamilies(node.data);
|
|
683
|
+
return ownerDocument.createTextNode(node.data);
|
|
684
|
+
}
|
|
685
|
+
if (ownerDocument && ownerWindow && isElementNode(node) && (isHTMLElementNode(node) || isSVGElementNode(node))) {
|
|
686
|
+
const cloned2 = await cloneElement(node, context);
|
|
687
|
+
if (context.isEnable("removeAbnormalAttributes")) {
|
|
688
|
+
const names = cloned2.getAttributeNames();
|
|
689
|
+
for (let len = names.length, i = 0; i < len; i++) {
|
|
690
|
+
const name = names[i];
|
|
691
|
+
if (!NORMAL_ATTRIBUTE_RE.test(name)) cloned2.removeAttribute(name);
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
const style = context.currentNodeStyle = copyCssStyles(node, cloned2, isRoot, context);
|
|
695
|
+
if (isRoot) applyCssStyleWithOptions(cloned2, context);
|
|
696
|
+
let copyScrollbar = false;
|
|
697
|
+
if (context.isEnable("copyScrollbar")) {
|
|
698
|
+
const overflow = [style.get("overflow-x")?.[0], style.get("overflow-y")?.[0]];
|
|
699
|
+
copyScrollbar = overflow.includes("scroll") || (overflow.includes("auto") || overflow.includes("overlay")) && (node.scrollHeight > node.clientHeight || node.scrollWidth > node.clientWidth);
|
|
700
|
+
}
|
|
701
|
+
const textTransform = style.get("text-transform")?.[0];
|
|
702
|
+
const families = splitFontFamily(style.get("font-family")?.[0]);
|
|
703
|
+
const addWordToFontFamilies2 = families ? (word) => {
|
|
704
|
+
if (textTransform === "uppercase") word = word.toUpperCase();
|
|
705
|
+
else if (textTransform === "lowercase") word = word.toLowerCase();
|
|
706
|
+
else if (textTransform === "capitalize") word = word[0].toUpperCase() + word.substring(1);
|
|
707
|
+
families.forEach((family) => {
|
|
708
|
+
let fontFamily = fontFamilies.get(family);
|
|
709
|
+
if (!fontFamily) fontFamilies.set(family, fontFamily = /* @__PURE__ */ new Set());
|
|
710
|
+
word.split("").forEach((text) => fontFamily.add(text));
|
|
711
|
+
});
|
|
712
|
+
} : void 0;
|
|
713
|
+
copyPseudoClass(node, cloned2, copyScrollbar, context, addWordToFontFamilies2);
|
|
714
|
+
copyInputValue(node, cloned2);
|
|
715
|
+
if (!isVideoElement(node)) await cloneChildNodes(node, cloned2, context, addWordToFontFamilies2);
|
|
716
|
+
await onCloneEachNode?.(cloned2);
|
|
717
|
+
return cloned2;
|
|
718
|
+
}
|
|
719
|
+
const cloned = node.cloneNode(false);
|
|
720
|
+
await cloneChildNodes(node, cloned, context);
|
|
721
|
+
await onCloneEachNode?.(cloned);
|
|
722
|
+
return cloned;
|
|
723
|
+
}
|
|
724
|
+
function destroyContext(context) {
|
|
725
|
+
context.ownerDocument = void 0;
|
|
726
|
+
context.ownerWindow = void 0;
|
|
727
|
+
context.svgStyleElement = void 0;
|
|
728
|
+
context.svgDefsElement = void 0;
|
|
729
|
+
context.svgStyles.clear();
|
|
730
|
+
context.defaultComputedStyles.clear();
|
|
731
|
+
if (context.sandbox) {
|
|
732
|
+
try {
|
|
733
|
+
context.sandbox.remove();
|
|
734
|
+
} catch (err) {
|
|
735
|
+
context.log.warn("Failed to destroyContext", err);
|
|
736
|
+
}
|
|
737
|
+
context.sandbox = void 0;
|
|
738
|
+
}
|
|
739
|
+
context.workers = [];
|
|
740
|
+
context.fontFamilies.clear();
|
|
741
|
+
context.fontCssTexts.clear();
|
|
742
|
+
context.requests.clear();
|
|
743
|
+
context.tasks = [];
|
|
744
|
+
context.shadowRoots = [];
|
|
745
|
+
}
|
|
746
|
+
function baseFetch(options) {
|
|
747
|
+
const { url, timeout, responseType, ...requestInit } = options;
|
|
748
|
+
const controller = new AbortController();
|
|
749
|
+
const timer = timeout ? setTimeout(() => controller.abort(), timeout) : void 0;
|
|
750
|
+
return fetch(url, {
|
|
751
|
+
signal: controller.signal,
|
|
752
|
+
...requestInit
|
|
753
|
+
}).then((response) => {
|
|
754
|
+
if (!response.ok) throw new Error("Failed fetch, not 2xx response", { cause: response });
|
|
755
|
+
switch (responseType) {
|
|
756
|
+
case "arrayBuffer": return response.arrayBuffer();
|
|
757
|
+
case "dataUrl": return response.blob().then(blobToDataUrl);
|
|
758
|
+
default: return response.text();
|
|
759
|
+
}
|
|
760
|
+
}).finally(() => clearTimeout(timer));
|
|
761
|
+
}
|
|
762
|
+
function contextFetch(context, options) {
|
|
763
|
+
const { url: rawUrl, requestType = "text", responseType = "text", imageDom } = options;
|
|
764
|
+
let url = rawUrl;
|
|
765
|
+
const { timeout, acceptOfImage, requests, fetchFn, fetch: { requestInit, bypassingCache, placeholderImage }, font, workers, fontFamilies } = context;
|
|
766
|
+
if (requestType === "image" && (IN_SAFARI || IN_FIREFOX)) context.drawImageCount++;
|
|
767
|
+
let request = requests.get(rawUrl);
|
|
768
|
+
if (!request) {
|
|
769
|
+
if (bypassingCache) {
|
|
770
|
+
if (bypassingCache instanceof RegExp && bypassingCache.test(url)) url += (/\?/.test(url) ? "&" : "?") + (/* @__PURE__ */ new Date()).getTime();
|
|
771
|
+
}
|
|
772
|
+
const canFontMinify = requestType.startsWith("font") && font && font.minify;
|
|
773
|
+
const fontTexts = /* @__PURE__ */ new Set();
|
|
774
|
+
if (canFontMinify) requestType.split(";")[1].split(",").forEach((family) => {
|
|
775
|
+
if (!fontFamilies.has(family)) return;
|
|
776
|
+
fontFamilies.get(family).forEach((text) => fontTexts.add(text));
|
|
777
|
+
});
|
|
778
|
+
const needFontMinify = canFontMinify && fontTexts.size;
|
|
779
|
+
const baseFetchOptions = {
|
|
780
|
+
url,
|
|
781
|
+
timeout,
|
|
782
|
+
responseType: needFontMinify ? "arrayBuffer" : responseType,
|
|
783
|
+
headers: requestType === "image" ? { accept: acceptOfImage } : void 0,
|
|
784
|
+
...requestInit
|
|
785
|
+
};
|
|
786
|
+
request = {
|
|
787
|
+
type: requestType,
|
|
788
|
+
resolve: void 0,
|
|
789
|
+
reject: void 0,
|
|
790
|
+
response: null
|
|
791
|
+
};
|
|
792
|
+
request.response = (async () => {
|
|
793
|
+
if (fetchFn && requestType === "image") {
|
|
794
|
+
const result = await fetchFn(rawUrl);
|
|
795
|
+
if (result) return result;
|
|
796
|
+
}
|
|
797
|
+
if (!IN_SAFARI && rawUrl.startsWith("http") && workers.length) return new Promise((resolve, reject) => {
|
|
798
|
+
workers[requests.size & workers.length - 1].postMessage({
|
|
799
|
+
rawUrl,
|
|
800
|
+
...baseFetchOptions
|
|
801
|
+
});
|
|
802
|
+
request.resolve = resolve;
|
|
803
|
+
request.reject = reject;
|
|
804
|
+
});
|
|
805
|
+
return baseFetch(baseFetchOptions);
|
|
806
|
+
})().catch((error) => {
|
|
807
|
+
requests.delete(rawUrl);
|
|
808
|
+
if (requestType === "image" && placeholderImage) {
|
|
809
|
+
context.log.warn("Failed to fetch image base64, trying to use placeholder image", url);
|
|
810
|
+
return typeof placeholderImage === "string" ? placeholderImage : placeholderImage(imageDom);
|
|
811
|
+
}
|
|
812
|
+
throw error;
|
|
813
|
+
});
|
|
814
|
+
requests.set(rawUrl, request);
|
|
815
|
+
}
|
|
816
|
+
return request.response;
|
|
817
|
+
}
|
|
818
|
+
async function replaceCssUrlToDataUrl(cssText, baseUrl, context, isImage) {
|
|
819
|
+
if (!hasCssUrl(cssText)) return cssText;
|
|
820
|
+
for (const [rawUrl, url] of parseCssUrls(cssText, baseUrl)) try {
|
|
821
|
+
const dataUrl = await contextFetch(context, {
|
|
822
|
+
url,
|
|
823
|
+
requestType: isImage ? "image" : "text",
|
|
824
|
+
responseType: "dataUrl"
|
|
825
|
+
});
|
|
826
|
+
cssText = cssText.replace(toRE(rawUrl), `$1${dataUrl}$3`);
|
|
827
|
+
} catch (error) {
|
|
828
|
+
context.log.warn("Failed to fetch css data url", rawUrl, error);
|
|
829
|
+
}
|
|
830
|
+
return cssText;
|
|
831
|
+
}
|
|
832
|
+
function hasCssUrl(cssText) {
|
|
833
|
+
return /url\((['"]?)([^'"]+?)\1\)/.test(cssText);
|
|
834
|
+
}
|
|
835
|
+
const URL_RE = /url\((['"]?)([^'"]+?)\1\)/g;
|
|
836
|
+
function parseCssUrls(cssText, baseUrl) {
|
|
837
|
+
const result = [];
|
|
838
|
+
cssText.replace(URL_RE, (raw, quotation, url) => {
|
|
839
|
+
result.push([url, resolveUrl(url, baseUrl)]);
|
|
840
|
+
return raw;
|
|
841
|
+
});
|
|
842
|
+
return result.filter(([url]) => !isDataUrl(url));
|
|
843
|
+
}
|
|
844
|
+
function toRE(url) {
|
|
845
|
+
const escaped = url.replace(/([.*+?^${}()|\[\]\/\\])/g, "\\$1");
|
|
846
|
+
return new RegExp(`(url\\(['"]?)(${escaped})(['"]?\\))`, "g");
|
|
847
|
+
}
|
|
848
|
+
const properties = [
|
|
849
|
+
"background-image",
|
|
850
|
+
"border-image-source",
|
|
851
|
+
"-webkit-border-image",
|
|
852
|
+
"-webkit-mask-image",
|
|
853
|
+
"list-style-image"
|
|
854
|
+
];
|
|
855
|
+
function embedCssStyleImage(style, context) {
|
|
856
|
+
return properties.map((property) => {
|
|
857
|
+
const value = style.getPropertyValue(property);
|
|
858
|
+
if (!value || value === "none") return null;
|
|
859
|
+
if (IN_SAFARI || IN_FIREFOX) context.drawImageCount++;
|
|
860
|
+
return replaceCssUrlToDataUrl(value, null, context, true).then((newValue) => {
|
|
861
|
+
if (!newValue || value === newValue) return;
|
|
862
|
+
style.setProperty(property, newValue, style.getPropertyPriority(property));
|
|
863
|
+
});
|
|
864
|
+
}).filter(Boolean);
|
|
865
|
+
}
|
|
866
|
+
function embedImageElement(cloned, context) {
|
|
867
|
+
if (isImageElement(cloned)) {
|
|
868
|
+
const originalSrc = cloned.currentSrc || cloned.src;
|
|
869
|
+
if (!isDataUrl(originalSrc)) return [contextFetch(context, {
|
|
870
|
+
url: originalSrc,
|
|
871
|
+
imageDom: cloned,
|
|
872
|
+
requestType: "image",
|
|
873
|
+
responseType: "dataUrl"
|
|
874
|
+
}).then((url) => {
|
|
875
|
+
if (!url) return;
|
|
876
|
+
cloned.srcset = "";
|
|
877
|
+
cloned.dataset.originalSrc = originalSrc;
|
|
878
|
+
cloned.src = url || "";
|
|
879
|
+
})];
|
|
880
|
+
if (IN_SAFARI || IN_FIREFOX) context.drawImageCount++;
|
|
881
|
+
} else if (isSVGElementNode(cloned) && !isDataUrl(cloned.href.baseVal)) {
|
|
882
|
+
const originalSrc = cloned.href.baseVal;
|
|
883
|
+
return [contextFetch(context, {
|
|
884
|
+
url: originalSrc,
|
|
885
|
+
imageDom: cloned,
|
|
886
|
+
requestType: "image",
|
|
887
|
+
responseType: "dataUrl"
|
|
888
|
+
}).then((url) => {
|
|
889
|
+
if (!url) return;
|
|
890
|
+
cloned.dataset.originalSrc = originalSrc;
|
|
891
|
+
cloned.href.baseVal = url || "";
|
|
892
|
+
})];
|
|
893
|
+
}
|
|
894
|
+
return [];
|
|
895
|
+
}
|
|
896
|
+
function embedSvgUse(cloned, context) {
|
|
897
|
+
const { ownerDocument, svgDefsElement } = context;
|
|
898
|
+
const href = cloned.getAttribute("href") ?? cloned.getAttribute("xlink:href");
|
|
899
|
+
if (!href) return [];
|
|
900
|
+
const [svgUrl, id] = href.split("#");
|
|
901
|
+
if (id) {
|
|
902
|
+
const query = `#${id}`;
|
|
903
|
+
const definition = context.shadowRoots.reduce((res, root) => {
|
|
904
|
+
return res ?? root.querySelector(`svg ${query}`);
|
|
905
|
+
}, ownerDocument?.querySelector(`svg ${query}`));
|
|
906
|
+
if (svgUrl) cloned.setAttribute("href", query);
|
|
907
|
+
if (svgDefsElement?.querySelector(query)) return [];
|
|
908
|
+
if (definition) {
|
|
909
|
+
svgDefsElement?.appendChild(definition.cloneNode(true));
|
|
910
|
+
return [];
|
|
911
|
+
} else if (svgUrl) return [contextFetch(context, {
|
|
912
|
+
url: svgUrl,
|
|
913
|
+
responseType: "text"
|
|
914
|
+
}).then((svgData) => {
|
|
915
|
+
svgDefsElement?.insertAdjacentHTML("beforeend", svgData);
|
|
916
|
+
})];
|
|
917
|
+
}
|
|
918
|
+
return [];
|
|
919
|
+
}
|
|
920
|
+
function embedNode(cloned, context) {
|
|
921
|
+
const { tasks } = context;
|
|
922
|
+
if (isElementNode(cloned)) {
|
|
923
|
+
if (isImageElement(cloned) || isSVGImageElementNode(cloned)) tasks.push(...embedImageElement(cloned, context));
|
|
924
|
+
if (isSVGUseElementNode(cloned)) tasks.push(...embedSvgUse(cloned, context));
|
|
925
|
+
}
|
|
926
|
+
if (isHTMLElementNode(cloned)) tasks.push(...embedCssStyleImage(cloned.style, context));
|
|
927
|
+
cloned.childNodes.forEach((child) => {
|
|
928
|
+
embedNode(child, context);
|
|
929
|
+
});
|
|
930
|
+
}
|
|
931
|
+
async function embedWebFont(clone, context) {
|
|
932
|
+
const { ownerDocument, svgStyleElement, fontFamilies, fontCssTexts, tasks, font } = context;
|
|
933
|
+
if (!ownerDocument || !svgStyleElement || !fontFamilies.size) return;
|
|
934
|
+
if (font && font.cssText) {
|
|
935
|
+
const cssText = filterPreferredFormat(font.cssText, context);
|
|
936
|
+
svgStyleElement.appendChild(ownerDocument.createTextNode(`${cssText}
|
|
937
|
+
`));
|
|
938
|
+
} else {
|
|
939
|
+
const styleSheets = Array.from(ownerDocument.styleSheets).filter((styleSheet) => {
|
|
940
|
+
try {
|
|
941
|
+
return "cssRules" in styleSheet && Boolean(styleSheet.cssRules.length);
|
|
942
|
+
} catch (error) {
|
|
943
|
+
context.log.warn(`Error while reading CSS rules from ${styleSheet.href}`, error);
|
|
944
|
+
return false;
|
|
945
|
+
}
|
|
946
|
+
});
|
|
947
|
+
const tempDoc = ownerDocument.implementation.createHTMLDocument("");
|
|
948
|
+
const tempStyleEl = tempDoc.createElement("style");
|
|
949
|
+
tempDoc.head.appendChild(tempStyleEl);
|
|
950
|
+
const tempStyleSheet = tempStyleEl.sheet;
|
|
951
|
+
await Promise.all(styleSheets.flatMap((styleSheet) => {
|
|
952
|
+
return Array.from(styleSheet.cssRules).map(async (cssRule) => {
|
|
953
|
+
if (isCSSImportRule(cssRule)) {
|
|
954
|
+
const baseUrl = cssRule.href;
|
|
955
|
+
let cssText = "";
|
|
956
|
+
try {
|
|
957
|
+
cssText = await contextFetch(context, {
|
|
958
|
+
url: baseUrl,
|
|
959
|
+
requestType: "text",
|
|
960
|
+
responseType: "text"
|
|
961
|
+
});
|
|
962
|
+
} catch (error) {
|
|
963
|
+
context.log.warn(`Error fetch remote css import from ${baseUrl}`, error);
|
|
964
|
+
}
|
|
965
|
+
const replacedCssText = cssText.replace(URL_RE, (raw, quotation, url) => raw.replace(url, resolveUrl(url, baseUrl)));
|
|
966
|
+
for (const rule of parseCss(replacedCssText)) try {
|
|
967
|
+
tempStyleSheet.insertRule(rule, tempStyleSheet.cssRules.length);
|
|
968
|
+
} catch (error) {
|
|
969
|
+
context.log.warn("Error inserting rule from remote css import", {
|
|
970
|
+
rule,
|
|
971
|
+
error
|
|
972
|
+
});
|
|
973
|
+
}
|
|
974
|
+
}
|
|
975
|
+
});
|
|
976
|
+
}));
|
|
977
|
+
if (tempStyleSheet.cssRules.length) styleSheets.push(tempStyleSheet);
|
|
978
|
+
const cssRules = [];
|
|
979
|
+
styleSheets.forEach((sheet) => {
|
|
980
|
+
unwrapCssLayers(sheet.cssRules, cssRules);
|
|
981
|
+
});
|
|
982
|
+
cssRules.filter((cssRule) => isCssFontFaceRule(cssRule) && hasCssUrl(cssRule.style.getPropertyValue("src")) && splitFontFamily(cssRule.style.getPropertyValue("font-family"))?.some((val) => fontFamilies.has(val))).forEach((value) => {
|
|
983
|
+
const rule = value;
|
|
984
|
+
const cssText = fontCssTexts.get(rule.cssText);
|
|
985
|
+
if (cssText) svgStyleElement.appendChild(ownerDocument.createTextNode(`${cssText}
|
|
986
|
+
`));
|
|
987
|
+
else tasks.push(replaceCssUrlToDataUrl(rule.cssText, rule.parentStyleSheet ? rule.parentStyleSheet.href : null, context).then((cssText2) => {
|
|
988
|
+
cssText2 = filterPreferredFormat(cssText2, context);
|
|
989
|
+
fontCssTexts.set(rule.cssText, cssText2);
|
|
990
|
+
svgStyleElement.appendChild(ownerDocument.createTextNode(`${cssText2}
|
|
991
|
+
`));
|
|
992
|
+
}));
|
|
993
|
+
});
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
const COMMENTS_RE = /(\/\*[\s\S]*?\*\/)/g;
|
|
997
|
+
const KEYFRAMES_RE = /((@.*?keyframes [\s\S]*?){([\s\S]*?}\s*?)})/gi;
|
|
998
|
+
function parseCss(source) {
|
|
999
|
+
if (source == null) return [];
|
|
1000
|
+
const result = [];
|
|
1001
|
+
let cssText = source.replace(COMMENTS_RE, "");
|
|
1002
|
+
while (true) {
|
|
1003
|
+
const matches = KEYFRAMES_RE.exec(cssText);
|
|
1004
|
+
if (!matches) break;
|
|
1005
|
+
result.push(matches[0]);
|
|
1006
|
+
}
|
|
1007
|
+
cssText = cssText.replace(KEYFRAMES_RE, "");
|
|
1008
|
+
const IMPORT_RE = /@import[\s\S]*?url\([^)]*\)[\s\S]*?;/gi;
|
|
1009
|
+
const UNIFIED_RE = /* @__PURE__ */ new RegExp("((\\s*?(?:\\/\\*[\\s\\S]*?\\*\\/)?\\s*?@media[\\s\\S]*?){([\\s\\S]*?)}\\s*?})|(([\\s\\S]*?){([\\s\\S]*?)})", "gi");
|
|
1010
|
+
while (true) {
|
|
1011
|
+
let matches = IMPORT_RE.exec(cssText);
|
|
1012
|
+
if (!matches) {
|
|
1013
|
+
matches = UNIFIED_RE.exec(cssText);
|
|
1014
|
+
if (!matches) break;
|
|
1015
|
+
else IMPORT_RE.lastIndex = UNIFIED_RE.lastIndex;
|
|
1016
|
+
} else UNIFIED_RE.lastIndex = IMPORT_RE.lastIndex;
|
|
1017
|
+
result.push(matches[0]);
|
|
1018
|
+
}
|
|
1019
|
+
return result;
|
|
1020
|
+
}
|
|
1021
|
+
const URL_WITH_FORMAT_RE = /url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g;
|
|
1022
|
+
const FONT_SRC_RE = /src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;
|
|
1023
|
+
function filterPreferredFormat(str, context) {
|
|
1024
|
+
const { font } = context;
|
|
1025
|
+
const preferredFormat = font ? font?.preferredFormat : void 0;
|
|
1026
|
+
return preferredFormat ? str.replace(FONT_SRC_RE, (match) => {
|
|
1027
|
+
while (true) {
|
|
1028
|
+
const [src, , format] = URL_WITH_FORMAT_RE.exec(match) || [];
|
|
1029
|
+
if (!format) return "";
|
|
1030
|
+
if (format === preferredFormat) return `src: ${src};`;
|
|
1031
|
+
}
|
|
1032
|
+
}) : str;
|
|
1033
|
+
}
|
|
1034
|
+
function unwrapCssLayers(rules, out = []) {
|
|
1035
|
+
for (const rule of Array.from(rules)) if (isLayerBlockRule(rule)) out.push(...unwrapCssLayers(rule.cssRules));
|
|
1036
|
+
else if ("cssRules" in rule) unwrapCssLayers(rule.cssRules, out);
|
|
1037
|
+
else out.push(rule);
|
|
1038
|
+
return out;
|
|
1039
|
+
}
|
|
1040
|
+
const SVG_EXTERNAL_RESOURCE_REGEX = /\bx?link:?href\s*=\s*["'](?!data:)[^"']+["']/i;
|
|
1041
|
+
function svgHasExternalResources(svg) {
|
|
1042
|
+
return SVG_EXTERNAL_RESOURCE_REGEX.test(svg.innerHTML);
|
|
1043
|
+
}
|
|
1044
|
+
async function domToForeignObjectSvg(node, options) {
|
|
1045
|
+
const context = await orCreateContext(node, options);
|
|
1046
|
+
if (isElementNode(context.node) && isSVGElementNode(context.node) && !svgHasExternalResources(context.node)) return context.node;
|
|
1047
|
+
const { ownerDocument, log, tasks, svgStyleElement, svgDefsElement, svgStyles, font, progress, autoDestruct, onCloneNode, onEmbedNode, onCreateForeignObjectSvg } = context;
|
|
1048
|
+
log.time("clone node");
|
|
1049
|
+
const clone = await cloneNode(context.node, context, true);
|
|
1050
|
+
if (svgStyleElement && ownerDocument) {
|
|
1051
|
+
let allCssText = "";
|
|
1052
|
+
svgStyles.forEach((klasses, cssText) => {
|
|
1053
|
+
allCssText += `${klasses.join(",\n")} {
|
|
1054
|
+
${cssText}
|
|
1055
|
+
}
|
|
1056
|
+
`;
|
|
1057
|
+
});
|
|
1058
|
+
svgStyleElement.appendChild(ownerDocument.createTextNode(allCssText));
|
|
1059
|
+
}
|
|
1060
|
+
log.timeEnd("clone node");
|
|
1061
|
+
await onCloneNode?.(clone);
|
|
1062
|
+
if (font !== false && isElementNode(clone)) {
|
|
1063
|
+
log.time("embed web font");
|
|
1064
|
+
await embedWebFont(clone, context);
|
|
1065
|
+
log.timeEnd("embed web font");
|
|
1066
|
+
}
|
|
1067
|
+
log.time("embed node");
|
|
1068
|
+
embedNode(clone, context);
|
|
1069
|
+
const count = tasks.length;
|
|
1070
|
+
let current = 0;
|
|
1071
|
+
const runTask = async () => {
|
|
1072
|
+
while (true) {
|
|
1073
|
+
const task = tasks.pop();
|
|
1074
|
+
if (!task) break;
|
|
1075
|
+
try {
|
|
1076
|
+
await task;
|
|
1077
|
+
} catch (error) {
|
|
1078
|
+
context.log.warn("Failed to run task", error);
|
|
1079
|
+
}
|
|
1080
|
+
progress?.(++current, count);
|
|
1081
|
+
}
|
|
1082
|
+
};
|
|
1083
|
+
progress?.(current, count);
|
|
1084
|
+
await Promise.all([...Array.from({ length: 4 })].map(runTask));
|
|
1085
|
+
log.timeEnd("embed node");
|
|
1086
|
+
await onEmbedNode?.(clone);
|
|
1087
|
+
const svg = createForeignObjectSvg(clone, context);
|
|
1088
|
+
svgDefsElement && svg.insertBefore(svgDefsElement, svg.children[0]);
|
|
1089
|
+
svgStyleElement && svg.insertBefore(svgStyleElement, svg.children[0]);
|
|
1090
|
+
autoDestruct && destroyContext(context);
|
|
1091
|
+
await onCreateForeignObjectSvg?.(svg);
|
|
1092
|
+
return svg;
|
|
1093
|
+
}
|
|
1094
|
+
function createForeignObjectSvg(clone, context) {
|
|
1095
|
+
const { width, height } = context;
|
|
1096
|
+
const svg = createSvg(width, height, clone.ownerDocument);
|
|
1097
|
+
const foreignObject = svg.ownerDocument.createElementNS(svg.namespaceURI, "foreignObject");
|
|
1098
|
+
foreignObject.setAttributeNS(null, "x", "0%");
|
|
1099
|
+
foreignObject.setAttributeNS(null, "y", "0%");
|
|
1100
|
+
foreignObject.setAttributeNS(null, "width", "100%");
|
|
1101
|
+
foreignObject.setAttributeNS(null, "height", "100%");
|
|
1102
|
+
foreignObject.append(clone);
|
|
1103
|
+
svg.appendChild(foreignObject);
|
|
1104
|
+
return svg;
|
|
1105
|
+
}
|
|
1106
|
+
async function domToCanvas(node, options) {
|
|
1107
|
+
const context = await orCreateContext(node, options);
|
|
1108
|
+
const svg = await domToForeignObjectSvg(context);
|
|
1109
|
+
const dataUrl = svgToDataUrl(svg, context.isEnable("removeControlCharacter"));
|
|
1110
|
+
if (!context.autoDestruct) {
|
|
1111
|
+
context.svgStyleElement = createStyleElement(context.ownerDocument);
|
|
1112
|
+
context.svgDefsElement = context.ownerDocument?.createElementNS(XMLNS, "defs");
|
|
1113
|
+
context.svgStyles.clear();
|
|
1114
|
+
}
|
|
1115
|
+
return await imageToCanvas(createImage(dataUrl, svg.ownerDocument), context);
|
|
1116
|
+
}
|
|
1117
|
+
//#endregion
|
|
1118
|
+
//#region src/screenshot.ts
|
|
1119
|
+
const MAX_WIDTH = 1280;
|
|
1120
|
+
const MAX_HEIGHT = 1600;
|
|
1121
|
+
/** Largest canvas side rendered before cropping. */
|
|
1122
|
+
const MAX_RENDER = 4096;
|
|
1123
|
+
/** How much of the surroundings is kept around the element, in CSS px. */
|
|
1124
|
+
const MARGIN = 48;
|
|
1125
|
+
const MASK_COLOR = "#a1a1aa";
|
|
1126
|
+
const MASKED_INPUT_TYPES = /* @__PURE__ */ new Set([
|
|
1127
|
+
"text",
|
|
1128
|
+
"file",
|
|
1129
|
+
"email",
|
|
1130
|
+
"tel",
|
|
1131
|
+
"url",
|
|
1132
|
+
"search",
|
|
1133
|
+
"password",
|
|
1134
|
+
"number",
|
|
1135
|
+
"date",
|
|
1136
|
+
"datetime-local",
|
|
1137
|
+
"month",
|
|
1138
|
+
"week",
|
|
1139
|
+
"time"
|
|
1140
|
+
]);
|
|
1141
|
+
const around = (b) => ({
|
|
1142
|
+
left: b.left - MARGIN,
|
|
1143
|
+
top: b.top - MARGIN,
|
|
1144
|
+
right: b.right + MARGIN,
|
|
1145
|
+
bottom: b.bottom + MARGIN
|
|
1146
|
+
});
|
|
1147
|
+
/**
|
|
1148
|
+
* The closest ancestor that contains the element plus a small margin: the
|
|
1149
|
+
* node to render from. Only that margin ends up in the image, never the rest
|
|
1150
|
+
* of the page (it may hold the visitor's own data).
|
|
1151
|
+
*/
|
|
1152
|
+
function frameFor(el) {
|
|
1153
|
+
const doc = el.ownerDocument;
|
|
1154
|
+
const want = around(el.getBoundingClientRect());
|
|
1155
|
+
let frame = el;
|
|
1156
|
+
while (frame.parentElement && frame.parentElement !== doc.body) {
|
|
1157
|
+
const r = frame.getBoundingClientRect();
|
|
1158
|
+
if (r.left <= want.left && r.top <= want.top && r.right >= want.right && r.bottom >= want.bottom) break;
|
|
1159
|
+
frame = frame.parentElement;
|
|
1160
|
+
}
|
|
1161
|
+
return frame;
|
|
1162
|
+
}
|
|
1163
|
+
/**
|
|
1164
|
+
* Measure the frame the way the renderer lays it out. The clone is rendered
|
|
1165
|
+
* on its own, so a child margin that collapses through the frame on the page
|
|
1166
|
+
* stays inside it there; `display: flow-root` gives that same layout. The
|
|
1167
|
+
* frame's style attribute is restored exactly afterwards.
|
|
1168
|
+
*/
|
|
1169
|
+
function isolatedLayout(frame, el) {
|
|
1170
|
+
const { display } = getComputedStyle(frame);
|
|
1171
|
+
const isolate = display === "block" || display === "list-item";
|
|
1172
|
+
const before = frame.getAttribute("style");
|
|
1173
|
+
if (isolate) frame.setAttribute("style", `${before ? `${before};` : ""}display: flow-root !important`);
|
|
1174
|
+
try {
|
|
1175
|
+
const box = frame.getBoundingClientRect();
|
|
1176
|
+
const target = el.getBoundingClientRect();
|
|
1177
|
+
const want = around(target);
|
|
1178
|
+
return {
|
|
1179
|
+
box,
|
|
1180
|
+
target,
|
|
1181
|
+
masks: maskedBoxes(frame),
|
|
1182
|
+
crop: {
|
|
1183
|
+
left: Math.max(box.left, want.left),
|
|
1184
|
+
top: Math.max(box.top, want.top),
|
|
1185
|
+
right: Math.min(box.right, want.right),
|
|
1186
|
+
bottom: Math.min(box.bottom, want.bottom)
|
|
1187
|
+
}
|
|
1188
|
+
};
|
|
1189
|
+
} finally {
|
|
1190
|
+
if (isolate) {
|
|
1191
|
+
if (before === null) frame.removeAttribute("style");
|
|
1192
|
+
else frame.setAttribute("style", before);
|
|
1193
|
+
}
|
|
1194
|
+
}
|
|
1195
|
+
}
|
|
1196
|
+
function contentBox(el) {
|
|
1197
|
+
const r = el.getBoundingClientRect();
|
|
1198
|
+
const s = getComputedStyle(el);
|
|
1199
|
+
const px = (value) => parseFloat(value) || 0;
|
|
1200
|
+
return {
|
|
1201
|
+
left: r.left + px(s.borderLeftWidth) + px(s.paddingLeft),
|
|
1202
|
+
top: r.top + px(s.borderTopWidth) + px(s.paddingTop),
|
|
1203
|
+
right: r.right - px(s.borderRightWidth) - px(s.paddingRight),
|
|
1204
|
+
bottom: r.bottom - px(s.borderBottomWidth) - px(s.paddingBottom)
|
|
1205
|
+
};
|
|
1206
|
+
}
|
|
1207
|
+
/**
|
|
1208
|
+
* Areas painted over: what people typed into form fields (the field's
|
|
1209
|
+
* border stays visible) and anything marked with data-nuni-mask.
|
|
1210
|
+
*/
|
|
1211
|
+
function maskedBoxes(frame) {
|
|
1212
|
+
const out = [];
|
|
1213
|
+
const fields = frame.querySelectorAll(`input, textarea, select, [${MASK_ATTRIBUTE}]`);
|
|
1214
|
+
const masked = frame.closest(`[${MASK_ATTRIBUTE}]`);
|
|
1215
|
+
if (masked) return [masked.getBoundingClientRect()];
|
|
1216
|
+
for (const el of [frame, ...Array.from(fields)]) {
|
|
1217
|
+
if (el.hasAttribute("data-nuni-mask")) {
|
|
1218
|
+
out.push(el.getBoundingClientRect());
|
|
1219
|
+
continue;
|
|
1220
|
+
}
|
|
1221
|
+
const tag = el.tagName;
|
|
1222
|
+
if (el instanceof HTMLInputElement && MASKED_INPUT_TYPES.has(el.type) || tag === "TEXTAREA" || tag === "SELECT") out.push(contentBox(el));
|
|
1223
|
+
}
|
|
1224
|
+
return out;
|
|
1225
|
+
}
|
|
1226
|
+
function toBlob(canvas, type, quality) {
|
|
1227
|
+
return new Promise((resolve) => canvas.toBlob(resolve, type, quality));
|
|
1228
|
+
}
|
|
1229
|
+
const captureScreenshot = async (el, options) => {
|
|
1230
|
+
const frame = frameFor(el);
|
|
1231
|
+
const { box, target, masks, crop } = isolatedLayout(frame, el);
|
|
1232
|
+
const cropW = crop.right - crop.left;
|
|
1233
|
+
const cropH = crop.bottom - crop.top;
|
|
1234
|
+
if (cropW < 1 || cropH < 1) return null;
|
|
1235
|
+
const scale = Math.min(window.devicePixelRatio || 1, MAX_WIDTH / cropW, MAX_HEIGHT / cropH, MAX_RENDER / box.width, MAX_RENDER / box.height);
|
|
1236
|
+
const background = getComputedStyle(el.ownerDocument.body).backgroundColor || "rgb(255, 255, 255)";
|
|
1237
|
+
const rendered = await domToCanvas(frame, {
|
|
1238
|
+
width: box.width,
|
|
1239
|
+
height: box.height,
|
|
1240
|
+
scale,
|
|
1241
|
+
backgroundColor: background === "rgba(0, 0, 0, 0)" ? "rgb(255, 255, 255)" : background,
|
|
1242
|
+
filter: (node) => node !== options.exclude,
|
|
1243
|
+
timeout: 8e3,
|
|
1244
|
+
fetch: { requestInit: {
|
|
1245
|
+
cache: "force-cache",
|
|
1246
|
+
[CAPTURE_MARK]: true
|
|
1247
|
+
} }
|
|
1248
|
+
});
|
|
1249
|
+
const canvas = el.ownerDocument.createElement("canvas");
|
|
1250
|
+
canvas.width = Math.max(1, Math.round(cropW * scale));
|
|
1251
|
+
canvas.height = Math.max(1, Math.round(cropH * scale));
|
|
1252
|
+
const ctx = canvas.getContext("2d");
|
|
1253
|
+
if (!ctx) return null;
|
|
1254
|
+
ctx.drawImage(rendered, (crop.left - box.left) * scale, (crop.top - box.top) * scale, canvas.width, canvas.height, 0, 0, canvas.width, canvas.height);
|
|
1255
|
+
const toCanvas = (b) => ({
|
|
1256
|
+
x: (b.left - crop.left) * scale,
|
|
1257
|
+
y: (b.top - crop.top) * scale,
|
|
1258
|
+
w: (b.right - b.left) * scale,
|
|
1259
|
+
h: (b.bottom - b.top) * scale
|
|
1260
|
+
});
|
|
1261
|
+
ctx.fillStyle = MASK_COLOR;
|
|
1262
|
+
for (const mask of masks) {
|
|
1263
|
+
const { x, y, w, h } = toCanvas(mask);
|
|
1264
|
+
if (w > 0 && h > 0) ctx.fillRect(x, y, w, h);
|
|
1265
|
+
}
|
|
1266
|
+
const line = Math.max(2, 3 * scale);
|
|
1267
|
+
const half = line / 2;
|
|
1268
|
+
const pad = 4 * scale;
|
|
1269
|
+
const t = toCanvas(target);
|
|
1270
|
+
const x0 = Math.max(half, t.x - pad);
|
|
1271
|
+
const y0 = Math.max(half, t.y - pad);
|
|
1272
|
+
const x1 = Math.min(canvas.width - half, t.x + t.w + pad);
|
|
1273
|
+
const y1 = Math.min(canvas.height - half, t.y + t.h + pad);
|
|
1274
|
+
ctx.strokeStyle = options.accent;
|
|
1275
|
+
ctx.lineWidth = line;
|
|
1276
|
+
if (x1 > x0 && y1 > y0) ctx.strokeRect(x0, y0, x1 - x0, y1 - y0);
|
|
1277
|
+
for (const [type, quality] of [
|
|
1278
|
+
["image/webp", .82],
|
|
1279
|
+
["image/jpeg", .8],
|
|
1280
|
+
["image/jpeg", .55]
|
|
1281
|
+
]) {
|
|
1282
|
+
const blob = await toBlob(canvas, type, quality);
|
|
1283
|
+
if (blob && blob.type === type && blob.size <= LIMITS.screenshotMaxBytes) return blob;
|
|
1284
|
+
}
|
|
1285
|
+
return null;
|
|
1286
|
+
};
|
|
1287
|
+
//#endregion
|
|
1288
|
+
export { captureScreenshot };
|