@youasked/react 0.0.0-stage → 0.4.1

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,1578 @@
1
+ "use client";
2
+
3
+ // ../../node_modules/modern-screenshot/dist/index.mjs
4
+ var _P = "p".charCodeAt(0);
5
+ var _H = "H".charCodeAt(0);
6
+ var _Y = "Y".charCodeAt(0);
7
+ var _S = "s".charCodeAt(0);
8
+ var PREFIX = "[modern-screenshot]";
9
+ var IN_BROWSER = typeof window !== "undefined";
10
+ var SUPPORT_WEB_WORKER = IN_BROWSER && "Worker" in window;
11
+ var SUPPORT_ATOB = IN_BROWSER && "atob" in window;
12
+ var SUPPORT_BTOA = IN_BROWSER && "btoa" in window;
13
+ var USER_AGENT = IN_BROWSER ? window.navigator?.userAgent : "";
14
+ var IN_CHROME = USER_AGENT.includes("Chrome");
15
+ var IN_SAFARI = USER_AGENT.includes("AppleWebKit") && !IN_CHROME;
16
+ var IN_FIREFOX = USER_AGENT.includes("Firefox");
17
+ var isContext = (value) => value && "__CONTEXT__" in value;
18
+ var isCssFontFaceRule = (rule) => rule.constructor.name === "CSSFontFaceRule";
19
+ var isCSSImportRule = (rule) => rule.constructor.name === "CSSImportRule";
20
+ var isLayerBlockRule = (rule) => rule.constructor.name === "CSSLayerBlockRule";
21
+ var isElementNode = (node) => node.nodeType === 1;
22
+ var isSVGElementNode = (node) => typeof node.className === "object";
23
+ var isSVGImageElementNode = (node) => node.tagName === "image";
24
+ var isSVGUseElementNode = (node) => node.tagName === "use";
25
+ var isHTMLElementNode = (node) => isElementNode(node) && typeof node.style !== "undefined" && !isSVGElementNode(node);
26
+ var isCommentNode = (node) => node.nodeType === 8;
27
+ var isTextNode = (node) => node.nodeType === 3;
28
+ var isImageElement = (node) => node.tagName === "IMG";
29
+ var isVideoElement = (node) => node.tagName === "VIDEO";
30
+ var isCanvasElement = (node) => node.tagName === "CANVAS";
31
+ var isTextareaElement = (node) => node.tagName === "TEXTAREA";
32
+ var isInputElement = (node) => node.tagName === "INPUT";
33
+ var isStyleElement = (node) => node.tagName === "STYLE";
34
+ var isScriptElement = (node) => node.tagName === "SCRIPT";
35
+ var isSelectElement = (node) => node.tagName === "SELECT";
36
+ var isSlotElement = (node) => node.tagName === "SLOT";
37
+ var isIFrameElement = (node) => node.tagName === "IFRAME";
38
+ var consoleWarn = (...args) => console.warn(PREFIX, ...args);
39
+ function supportWebp(ownerDocument) {
40
+ const canvas = ownerDocument?.createElement?.("canvas");
41
+ if (canvas) {
42
+ canvas.height = canvas.width = 1;
43
+ }
44
+ return Boolean(canvas) && "toDataURL" in canvas && Boolean(canvas.toDataURL("image/webp").includes("image/webp"));
45
+ }
46
+ var isDataUrl = (url) => url.startsWith("data:");
47
+ function resolveUrl(url, baseUrl) {
48
+ if (url.match(/^[a-z]+:\/\//i))
49
+ return url;
50
+ if (IN_BROWSER && url.match(/^\/\//))
51
+ return window.location.protocol + url;
52
+ if (url.match(/^[a-z]+:/i))
53
+ return url;
54
+ if (!IN_BROWSER)
55
+ return url;
56
+ const doc = getDocument().implementation.createHTMLDocument();
57
+ const base = doc.createElement("base");
58
+ const a = doc.createElement("a");
59
+ doc.head.appendChild(base);
60
+ doc.body.appendChild(a);
61
+ if (baseUrl)
62
+ base.href = baseUrl;
63
+ a.href = url;
64
+ return a.href;
65
+ }
66
+ function getDocument(target) {
67
+ return (target && isElementNode(target) ? target?.ownerDocument : target) ?? window.document;
68
+ }
69
+ var XMLNS = "http://www.w3.org/2000/svg";
70
+ function createSvg(width, height, ownerDocument) {
71
+ const svg = getDocument(ownerDocument).createElementNS(XMLNS, "svg");
72
+ svg.setAttributeNS(null, "width", width.toString());
73
+ svg.setAttributeNS(null, "height", height.toString());
74
+ svg.setAttributeNS(null, "viewBox", `0 0 ${width} ${height}`);
75
+ return svg;
76
+ }
77
+ function svgToDataUrl(svg, removeControlCharacter) {
78
+ let xhtml = new XMLSerializer().serializeToString(svg);
79
+ if (removeControlCharacter) {
80
+ xhtml = xhtml.replace(/[\u0000-\u0008\v\f\u000E-\u001F\uD800-\uDFFF\uFFFE\uFFFF]/gu, "");
81
+ }
82
+ return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(xhtml)}`;
83
+ }
84
+ function readBlob(blob, type) {
85
+ return new Promise((resolve, reject) => {
86
+ const reader = new FileReader();
87
+ reader.onload = () => resolve(reader.result);
88
+ reader.onerror = () => reject(reader.error);
89
+ reader.onabort = () => reject(new Error(`Failed read blob to ${type}`));
90
+ if (type === "dataUrl") {
91
+ reader.readAsDataURL(blob);
92
+ } else if (type === "arrayBuffer") {
93
+ reader.readAsArrayBuffer(blob);
94
+ }
95
+ });
96
+ }
97
+ var blobToDataUrl = (blob) => readBlob(blob, "dataUrl");
98
+ function createImage(url, ownerDocument) {
99
+ const img = getDocument(ownerDocument).createElement("img");
100
+ img.decoding = "sync";
101
+ img.loading = "eager";
102
+ img.src = url;
103
+ return img;
104
+ }
105
+ function loadMedia(media, options) {
106
+ return new Promise((resolve) => {
107
+ const { timeout, ownerDocument, onError: userOnError, onWarn } = options ?? {};
108
+ const node = typeof media === "string" ? createImage(media, getDocument(ownerDocument)) : media;
109
+ let timer = null;
110
+ let removeEventListeners = null;
111
+ function onResolve() {
112
+ resolve(node);
113
+ timer && clearTimeout(timer);
114
+ removeEventListeners?.();
115
+ }
116
+ if (timeout) {
117
+ timer = setTimeout(onResolve, timeout);
118
+ }
119
+ if (isVideoElement(node)) {
120
+ const currentSrc = node.currentSrc || node.src;
121
+ if (!currentSrc) {
122
+ if (node.poster) {
123
+ return loadMedia(node.poster, options).then(resolve);
124
+ }
125
+ return onResolve();
126
+ }
127
+ if (node.readyState >= 2) {
128
+ return onResolve();
129
+ }
130
+ const onLoadeddata = onResolve;
131
+ const onError = (error) => {
132
+ onWarn?.(
133
+ "Failed video load",
134
+ currentSrc,
135
+ error
136
+ );
137
+ userOnError?.(error);
138
+ onResolve();
139
+ };
140
+ removeEventListeners = () => {
141
+ node.removeEventListener("loadeddata", onLoadeddata);
142
+ node.removeEventListener("error", onError);
143
+ };
144
+ node.addEventListener("loadeddata", onLoadeddata, { once: true });
145
+ node.addEventListener("error", onError, { once: true });
146
+ } else {
147
+ const currentSrc = isSVGImageElementNode(node) ? node.href.baseVal : node.currentSrc || node.src;
148
+ if (!currentSrc) {
149
+ return onResolve();
150
+ }
151
+ const onLoad = async () => {
152
+ if (isImageElement(node) && "decode" in node) {
153
+ try {
154
+ await node.decode();
155
+ } catch (error) {
156
+ onWarn?.(
157
+ "Failed to decode image, trying to render anyway",
158
+ node.dataset.originalSrc || currentSrc,
159
+ error
160
+ );
161
+ }
162
+ }
163
+ onResolve();
164
+ };
165
+ const onError = (error) => {
166
+ onWarn?.(
167
+ "Failed image load",
168
+ node.dataset.originalSrc || currentSrc,
169
+ error
170
+ );
171
+ onResolve();
172
+ };
173
+ if (isImageElement(node) && node.complete) {
174
+ return onLoad();
175
+ }
176
+ removeEventListeners = () => {
177
+ node.removeEventListener("load", onLoad);
178
+ node.removeEventListener("error", onError);
179
+ };
180
+ node.addEventListener("load", onLoad, { once: true });
181
+ node.addEventListener("error", onError, { once: true });
182
+ }
183
+ });
184
+ }
185
+ async function waitUntilLoad(node, options) {
186
+ if (isHTMLElementNode(node)) {
187
+ if (isImageElement(node) || isVideoElement(node)) {
188
+ await loadMedia(node, options);
189
+ } else {
190
+ await Promise.all(
191
+ ["img", "video"].flatMap((selectors) => {
192
+ return Array.from(node.querySelectorAll(selectors)).map((el) => loadMedia(el, options));
193
+ })
194
+ );
195
+ }
196
+ }
197
+ }
198
+ var uuid = /* @__PURE__ */ (function uuid2() {
199
+ let counter = 0;
200
+ const random = () => `0000${(Math.random() * 36 ** 4 << 0).toString(36)}`.slice(-4);
201
+ return () => {
202
+ counter += 1;
203
+ return `u${random()}${counter}`;
204
+ };
205
+ })();
206
+ function splitFontFamily(fontFamily) {
207
+ return fontFamily?.split(",").map((val) => val.trim().replace(/"|'/g, "").toLowerCase()).filter(Boolean);
208
+ }
209
+ var uid = 0;
210
+ function createLogger(debug) {
211
+ const prefix = `${PREFIX}[#${uid}]`;
212
+ uid++;
213
+ return {
214
+ // eslint-disable-next-line no-console
215
+ time: (label) => debug && console.time(`${prefix} ${label}`),
216
+ // eslint-disable-next-line no-console
217
+ timeEnd: (label) => debug && console.timeEnd(`${prefix} ${label}`),
218
+ warn: (...args) => debug && consoleWarn(...args)
219
+ };
220
+ }
221
+ function getDefaultRequestInit(bypassingCache) {
222
+ return {
223
+ cache: bypassingCache ? "no-cache" : "force-cache"
224
+ };
225
+ }
226
+ async function orCreateContext(node, options) {
227
+ return isContext(node) ? node : createContext(node, { ...options, autoDestruct: true });
228
+ }
229
+ async function createContext(node, options) {
230
+ const { scale = 1, workerUrl, workerNumber = 1 } = options || {};
231
+ const debug = Boolean(options?.debug);
232
+ const features = options?.features ?? true;
233
+ const ownerDocument = node.ownerDocument ?? (IN_BROWSER ? window.document : void 0);
234
+ const ownerWindow = node.ownerDocument?.defaultView ?? (IN_BROWSER ? window : void 0);
235
+ const requests = /* @__PURE__ */ new Map();
236
+ const context = {
237
+ // Options
238
+ width: 0,
239
+ height: 0,
240
+ quality: 1,
241
+ type: "image/png",
242
+ scale,
243
+ backgroundColor: null,
244
+ style: null,
245
+ filter: null,
246
+ maximumCanvasSize: 0,
247
+ timeout: 3e4,
248
+ progress: null,
249
+ debug,
250
+ fetch: {
251
+ requestInit: getDefaultRequestInit(options?.fetch?.bypassingCache),
252
+ placeholderImage: "data:image/png;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",
253
+ bypassingCache: false,
254
+ ...options?.fetch
255
+ },
256
+ fetchFn: null,
257
+ font: {},
258
+ drawImageInterval: 100,
259
+ workerUrl: null,
260
+ workerNumber,
261
+ onCloneEachNode: null,
262
+ onCloneNode: null,
263
+ onEmbedNode: null,
264
+ onCreateForeignObjectSvg: null,
265
+ includeStyleProperties: null,
266
+ autoDestruct: false,
267
+ ...options,
268
+ // InternalContext
269
+ __CONTEXT__: true,
270
+ log: createLogger(debug),
271
+ node,
272
+ ownerDocument,
273
+ ownerWindow,
274
+ dpi: scale === 1 ? null : 96 * scale,
275
+ svgStyleElement: createStyleElement(ownerDocument),
276
+ svgDefsElement: ownerDocument?.createElementNS(XMLNS, "defs"),
277
+ svgStyles: /* @__PURE__ */ new Map(),
278
+ defaultComputedStyles: /* @__PURE__ */ new Map(),
279
+ workers: [
280
+ ...Array.from({
281
+ length: SUPPORT_WEB_WORKER && workerUrl && workerNumber ? workerNumber : 0
282
+ })
283
+ ].map(() => {
284
+ try {
285
+ const worker = new Worker(workerUrl);
286
+ worker.onmessage = async (event) => {
287
+ const { url, result } = event.data;
288
+ if (result) {
289
+ requests.get(url)?.resolve?.(result);
290
+ } else {
291
+ requests.get(url)?.reject?.(new Error(`Error receiving message from worker: ${url}`));
292
+ }
293
+ };
294
+ worker.onmessageerror = (event) => {
295
+ const { url } = event.data;
296
+ requests.get(url)?.reject?.(new Error(`Error receiving message from worker: ${url}`));
297
+ };
298
+ return worker;
299
+ } catch (error) {
300
+ context.log.warn("Failed to new Worker", error);
301
+ return null;
302
+ }
303
+ }).filter(Boolean),
304
+ fontFamilies: /* @__PURE__ */ new Map(),
305
+ fontCssTexts: /* @__PURE__ */ new Map(),
306
+ acceptOfImage: `${[
307
+ supportWebp(ownerDocument) && "image/webp",
308
+ "image/svg+xml",
309
+ "image/*",
310
+ "*/*"
311
+ ].filter(Boolean).join(",")};q=0.8`,
312
+ requests,
313
+ drawImageCount: 0,
314
+ tasks: [],
315
+ features,
316
+ isEnable: (key) => {
317
+ if (key === "restoreScrollPosition") {
318
+ return typeof features === "boolean" ? false : features[key] ?? false;
319
+ }
320
+ if (typeof features === "boolean") {
321
+ return features;
322
+ }
323
+ return features[key] ?? true;
324
+ },
325
+ shadowRoots: []
326
+ };
327
+ context.log.time("wait until load");
328
+ await waitUntilLoad(node, { timeout: context.timeout, onWarn: context.log.warn });
329
+ context.log.timeEnd("wait until load");
330
+ const { width, height } = resolveBoundingBox(node, context);
331
+ context.width = width;
332
+ context.height = height;
333
+ return context;
334
+ }
335
+ function createStyleElement(ownerDocument) {
336
+ if (!ownerDocument)
337
+ return void 0;
338
+ const style = ownerDocument.createElement("style");
339
+ const cssText = style.ownerDocument.createTextNode(`
340
+ .______background-clip--text {
341
+ background-clip: text;
342
+ -webkit-background-clip: text;
343
+ }
344
+ `);
345
+ style.appendChild(cssText);
346
+ return style;
347
+ }
348
+ function resolveBoundingBox(node, context) {
349
+ let { width, height } = context;
350
+ if (isElementNode(node) && (!width || !height)) {
351
+ const box = node.getBoundingClientRect();
352
+ width = width || box.width || Number(node.getAttribute("width")) || 0;
353
+ height = height || box.height || Number(node.getAttribute("height")) || 0;
354
+ }
355
+ return { width, height };
356
+ }
357
+ async function imageToCanvas(image, context) {
358
+ const {
359
+ log,
360
+ timeout,
361
+ drawImageCount,
362
+ drawImageInterval
363
+ } = context;
364
+ log.time("image to canvas");
365
+ const loaded = await loadMedia(image, { timeout, onWarn: context.log.warn });
366
+ const { canvas, context2d } = createCanvas(image.ownerDocument, context);
367
+ const drawImage = () => {
368
+ try {
369
+ context2d?.drawImage(loaded, 0, 0, canvas.width, canvas.height);
370
+ } catch (error) {
371
+ context.log.warn("Failed to drawImage", error);
372
+ }
373
+ };
374
+ drawImage();
375
+ if (context.isEnable("fixSvgXmlDecode")) {
376
+ for (let i = 0; i < drawImageCount; i++) {
377
+ await new Promise((resolve) => {
378
+ setTimeout(() => {
379
+ context2d?.clearRect(0, 0, canvas.width, canvas.height);
380
+ drawImage();
381
+ resolve();
382
+ }, i + drawImageInterval);
383
+ });
384
+ }
385
+ }
386
+ context.drawImageCount = 0;
387
+ log.timeEnd("image to canvas");
388
+ return canvas;
389
+ }
390
+ function createCanvas(ownerDocument, context) {
391
+ const { width, height, scale, backgroundColor, maximumCanvasSize: max } = context;
392
+ const canvas = ownerDocument.createElement("canvas");
393
+ canvas.width = Math.floor(width * scale);
394
+ canvas.height = Math.floor(height * scale);
395
+ canvas.style.width = `${width}px`;
396
+ canvas.style.height = `${height}px`;
397
+ if (max) {
398
+ if (canvas.width > max || canvas.height > max) {
399
+ if (canvas.width > max && canvas.height > max) {
400
+ if (canvas.width > canvas.height) {
401
+ canvas.height *= max / canvas.width;
402
+ canvas.width = max;
403
+ } else {
404
+ canvas.width *= max / canvas.height;
405
+ canvas.height = max;
406
+ }
407
+ } else if (canvas.width > max) {
408
+ canvas.height *= max / canvas.width;
409
+ canvas.width = max;
410
+ } else {
411
+ canvas.width *= max / canvas.height;
412
+ canvas.height = max;
413
+ }
414
+ }
415
+ }
416
+ const context2d = canvas.getContext("2d");
417
+ if (context2d && backgroundColor) {
418
+ context2d.fillStyle = backgroundColor;
419
+ context2d.fillRect(0, 0, canvas.width, canvas.height);
420
+ }
421
+ return { canvas, context2d };
422
+ }
423
+ function cloneCanvas(canvas, context) {
424
+ if (canvas.ownerDocument) {
425
+ try {
426
+ const dataURL = canvas.toDataURL();
427
+ if (dataURL !== "data:,") {
428
+ return createImage(dataURL, canvas.ownerDocument);
429
+ }
430
+ } catch (error) {
431
+ context.log.warn("Failed to clone canvas", error);
432
+ }
433
+ }
434
+ const cloned = canvas.cloneNode(false);
435
+ const ctx = canvas.getContext("2d");
436
+ const clonedCtx = cloned.getContext("2d");
437
+ try {
438
+ if (ctx && clonedCtx) {
439
+ clonedCtx.putImageData(
440
+ ctx.getImageData(0, 0, canvas.width, canvas.height),
441
+ 0,
442
+ 0
443
+ );
444
+ }
445
+ return cloned;
446
+ } catch (error) {
447
+ context.log.warn("Failed to clone canvas", error);
448
+ }
449
+ return cloned;
450
+ }
451
+ function cloneIframe(iframe, context) {
452
+ try {
453
+ if (iframe?.contentDocument?.documentElement) {
454
+ return cloneNode(iframe.contentDocument.documentElement, context);
455
+ }
456
+ } catch (error) {
457
+ context.log.warn("Failed to clone iframe", error);
458
+ }
459
+ return iframe.cloneNode(false);
460
+ }
461
+ function cloneImage(image) {
462
+ const cloned = image.cloneNode(false);
463
+ if (image.currentSrc && image.currentSrc !== image.src) {
464
+ cloned.src = image.currentSrc;
465
+ cloned.srcset = "";
466
+ }
467
+ if (cloned.loading === "lazy") {
468
+ cloned.loading = "eager";
469
+ }
470
+ return cloned;
471
+ }
472
+ async function cloneVideo(video, context) {
473
+ if (video.ownerDocument && !video.currentSrc && video.poster) {
474
+ return createImage(video.poster, video.ownerDocument);
475
+ }
476
+ const cloned = video.cloneNode(false);
477
+ cloned.crossOrigin = "anonymous";
478
+ if (video.currentSrc && video.currentSrc !== video.src) {
479
+ cloned.src = video.currentSrc;
480
+ }
481
+ const ownerDocument = cloned.ownerDocument;
482
+ if (ownerDocument) {
483
+ let canPlay = true;
484
+ await loadMedia(cloned, { onError: () => canPlay = false, onWarn: context.log.warn });
485
+ if (!canPlay) {
486
+ if (video.poster) {
487
+ return createImage(video.poster, video.ownerDocument);
488
+ }
489
+ return cloned;
490
+ }
491
+ cloned.currentTime = video.currentTime;
492
+ await new Promise((resolve) => {
493
+ cloned.addEventListener("seeked", resolve, { once: true });
494
+ });
495
+ const canvas = ownerDocument.createElement("canvas");
496
+ canvas.width = video.offsetWidth;
497
+ canvas.height = video.offsetHeight;
498
+ try {
499
+ const ctx = canvas.getContext("2d");
500
+ if (ctx)
501
+ ctx.drawImage(cloned, 0, 0, canvas.width, canvas.height);
502
+ } catch (error) {
503
+ context.log.warn("Failed to clone video", error);
504
+ if (video.poster) {
505
+ return createImage(video.poster, video.ownerDocument);
506
+ }
507
+ return cloned;
508
+ }
509
+ return cloneCanvas(canvas, context);
510
+ }
511
+ return cloned;
512
+ }
513
+ function cloneElement(node, context) {
514
+ if (isCanvasElement(node)) {
515
+ return cloneCanvas(node, context);
516
+ }
517
+ if (isIFrameElement(node)) {
518
+ return cloneIframe(node, context);
519
+ }
520
+ if (isImageElement(node)) {
521
+ return cloneImage(node);
522
+ }
523
+ if (isVideoElement(node)) {
524
+ return cloneVideo(node, context);
525
+ }
526
+ return node.cloneNode(false);
527
+ }
528
+ function getSandBox(context) {
529
+ let sandbox = context.sandbox;
530
+ if (!sandbox) {
531
+ const { ownerDocument } = context;
532
+ try {
533
+ if (ownerDocument) {
534
+ sandbox = ownerDocument.createElement("iframe");
535
+ sandbox.id = `__SANDBOX__${uuid()}`;
536
+ sandbox.width = "0";
537
+ sandbox.height = "0";
538
+ sandbox.style.visibility = "hidden";
539
+ sandbox.style.position = "fixed";
540
+ ownerDocument.body.appendChild(sandbox);
541
+ sandbox.srcdoc = '<!DOCTYPE html><meta charset="UTF-8"><title></title><body>';
542
+ context.sandbox = sandbox;
543
+ }
544
+ } catch (error) {
545
+ context.log.warn("Failed to getSandBox", error);
546
+ }
547
+ }
548
+ return sandbox;
549
+ }
550
+ var ignoredStyles = [
551
+ "width",
552
+ "height",
553
+ "-webkit-text-fill-color"
554
+ ];
555
+ var includedAttributes = [
556
+ "stroke",
557
+ "fill"
558
+ ];
559
+ function getDefaultStyle(node, pseudoElement, context) {
560
+ const { defaultComputedStyles } = context;
561
+ const nodeName = node.nodeName.toLowerCase();
562
+ const isSvgNode = isSVGElementNode(node) && nodeName !== "svg";
563
+ const attributes = isSvgNode ? includedAttributes.map((name) => [name, node.getAttribute(name)]).filter(([, value]) => value !== null) : [];
564
+ const key = [
565
+ isSvgNode && "svg",
566
+ nodeName,
567
+ attributes.map((name, value) => `${name}=${value}`).join(","),
568
+ pseudoElement
569
+ ].filter(Boolean).join(":");
570
+ if (defaultComputedStyles.has(key))
571
+ return defaultComputedStyles.get(key);
572
+ const sandbox = getSandBox(context);
573
+ const sandboxWindow = sandbox?.contentWindow;
574
+ if (!sandboxWindow)
575
+ return /* @__PURE__ */ new Map();
576
+ const sandboxDocument = sandboxWindow?.document;
577
+ let root;
578
+ let el;
579
+ if (isSvgNode) {
580
+ root = sandboxDocument.createElementNS(XMLNS, "svg");
581
+ el = root.ownerDocument.createElementNS(root.namespaceURI, nodeName);
582
+ attributes.forEach(([name, value]) => {
583
+ el.setAttributeNS(null, name, value);
584
+ });
585
+ root.appendChild(el);
586
+ } else {
587
+ root = el = sandboxDocument.createElement(nodeName);
588
+ }
589
+ el.textContent = " ";
590
+ sandboxDocument.body.appendChild(root);
591
+ const computedStyle = sandboxWindow.getComputedStyle(el, pseudoElement);
592
+ const styles = /* @__PURE__ */ new Map();
593
+ for (let len = computedStyle.length, i = 0; i < len; i++) {
594
+ const name = computedStyle.item(i);
595
+ if (ignoredStyles.includes(name))
596
+ continue;
597
+ styles.set(name, computedStyle.getPropertyValue(name));
598
+ }
599
+ sandboxDocument.body.removeChild(root);
600
+ defaultComputedStyles.set(key, styles);
601
+ return styles;
602
+ }
603
+ function getDiffStyle(style, defaultStyle, includeStyleProperties) {
604
+ const diffStyle = /* @__PURE__ */ new Map();
605
+ const prefixs = [];
606
+ const prefixTree = /* @__PURE__ */ new Map();
607
+ if (includeStyleProperties) {
608
+ for (const name of includeStyleProperties) {
609
+ applyTo(name);
610
+ }
611
+ } else {
612
+ for (let len = style.length, i = 0; i < len; i++) {
613
+ const name = style.item(i);
614
+ applyTo(name);
615
+ }
616
+ }
617
+ for (let len = prefixs.length, i = 0; i < len; i++) {
618
+ prefixTree.get(prefixs[i])?.forEach((value, name) => diffStyle.set(name, value));
619
+ }
620
+ function applyTo(name) {
621
+ const value = style.getPropertyValue(name);
622
+ const priority = style.getPropertyPriority(name);
623
+ const subIndex = name.lastIndexOf("-");
624
+ const prefix = subIndex > -1 ? name.substring(0, subIndex) : void 0;
625
+ if (prefix) {
626
+ let map = prefixTree.get(prefix);
627
+ if (!map) {
628
+ map = /* @__PURE__ */ new Map();
629
+ prefixTree.set(prefix, map);
630
+ }
631
+ map.set(name, [value, priority]);
632
+ }
633
+ if (defaultStyle.get(name) === value && !priority)
634
+ return;
635
+ if (prefix) {
636
+ prefixs.push(prefix);
637
+ } else {
638
+ diffStyle.set(name, [value, priority]);
639
+ }
640
+ }
641
+ return diffStyle;
642
+ }
643
+ function copyCssStyles(node, cloned, isRoot, context) {
644
+ const { ownerWindow, includeStyleProperties, currentParentNodeStyle } = context;
645
+ const clonedStyle = cloned.style;
646
+ const computedStyle = ownerWindow.getComputedStyle(node);
647
+ const defaultStyle = getDefaultStyle(node, null, context);
648
+ currentParentNodeStyle?.forEach((_, key) => {
649
+ defaultStyle.delete(key);
650
+ });
651
+ const style = getDiffStyle(computedStyle, defaultStyle, includeStyleProperties);
652
+ style.delete("transition-property");
653
+ style.delete("all");
654
+ style.delete("d");
655
+ style.delete("content");
656
+ if (isRoot) {
657
+ style.delete("position");
658
+ style.delete("margin-top");
659
+ style.delete("margin-right");
660
+ style.delete("margin-bottom");
661
+ style.delete("margin-left");
662
+ style.delete("margin-block-start");
663
+ style.delete("margin-block-end");
664
+ style.delete("margin-inline-start");
665
+ style.delete("margin-inline-end");
666
+ style.set("box-sizing", ["border-box", ""]);
667
+ }
668
+ if (style.get("background-clip")?.[0] === "text") {
669
+ cloned.classList.add("______background-clip--text");
670
+ }
671
+ if (IN_CHROME) {
672
+ if (!style.has("font-kerning"))
673
+ style.set("font-kerning", ["normal", ""]);
674
+ if ((style.get("overflow-x")?.[0] === "hidden" || style.get("overflow-y")?.[0] === "hidden") && style.get("text-overflow")?.[0] === "ellipsis" && node.scrollWidth === node.clientWidth) {
675
+ style.set("text-overflow", ["clip", ""]);
676
+ }
677
+ }
678
+ for (let len = clonedStyle.length, i = 0; i < len; i++) {
679
+ clonedStyle.removeProperty(clonedStyle.item(i));
680
+ }
681
+ style.forEach(([value, priority], name) => {
682
+ clonedStyle.setProperty(name, value, priority);
683
+ });
684
+ return style;
685
+ }
686
+ function copyInputValue(node, cloned) {
687
+ if (isTextareaElement(node) || isInputElement(node) || isSelectElement(node)) {
688
+ cloned.setAttribute("value", node.value);
689
+ }
690
+ }
691
+ var pseudoClasses = [
692
+ "::before",
693
+ "::after"
694
+ // '::placeholder', TODO
695
+ ];
696
+ var scrollbarPseudoClasses = [
697
+ "::-webkit-scrollbar",
698
+ "::-webkit-scrollbar-button",
699
+ // '::-webkit-scrollbar:horizontal', TODO
700
+ "::-webkit-scrollbar-thumb",
701
+ "::-webkit-scrollbar-track",
702
+ "::-webkit-scrollbar-track-piece",
703
+ // '::-webkit-scrollbar:vertical', TODO
704
+ "::-webkit-scrollbar-corner",
705
+ "::-webkit-resizer"
706
+ ];
707
+ function copyPseudoClass(node, cloned, copyScrollbar, context, addWordToFontFamilies) {
708
+ const { ownerWindow, svgStyleElement, svgStyles, currentNodeStyle } = context;
709
+ if (!svgStyleElement || !ownerWindow)
710
+ return;
711
+ function copyBy(pseudoClass) {
712
+ const computedStyle = ownerWindow.getComputedStyle(node, pseudoClass);
713
+ let content = computedStyle.getPropertyValue("content");
714
+ if (!content || content === "none")
715
+ return;
716
+ addWordToFontFamilies?.(content);
717
+ content = content.replace(/(')|(")|(counter\(.+\))/g, "");
718
+ const klasses = [uuid()];
719
+ const defaultStyle = getDefaultStyle(node, pseudoClass, context);
720
+ currentNodeStyle?.forEach((_, key) => {
721
+ defaultStyle.delete(key);
722
+ });
723
+ const style = getDiffStyle(computedStyle, defaultStyle, context.includeStyleProperties);
724
+ style.delete("content");
725
+ style.delete("-webkit-locale");
726
+ if (style.get("background-clip")?.[0] === "text") {
727
+ cloned.classList.add("______background-clip--text");
728
+ }
729
+ const cloneStyle = [
730
+ `content: '${content}';`
731
+ ];
732
+ style.forEach(([value, priority], name) => {
733
+ cloneStyle.push(`${name}: ${value}${priority ? " !important" : ""};`);
734
+ });
735
+ if (cloneStyle.length === 1)
736
+ return;
737
+ try {
738
+ cloned.className = [cloned.className, ...klasses].join(" ");
739
+ } catch (err) {
740
+ context.log.warn("Failed to copyPseudoClass", err);
741
+ return;
742
+ }
743
+ const cssText = cloneStyle.join("\n ");
744
+ let allClasses = svgStyles.get(cssText);
745
+ if (!allClasses) {
746
+ allClasses = [];
747
+ svgStyles.set(cssText, allClasses);
748
+ }
749
+ allClasses.push(`.${klasses[0]}${pseudoClass}`);
750
+ }
751
+ pseudoClasses.forEach(copyBy);
752
+ if (copyScrollbar)
753
+ scrollbarPseudoClasses.forEach(copyBy);
754
+ }
755
+ var excludeParentNodes = /* @__PURE__ */ new Set([
756
+ "symbol"
757
+ // test/fixtures/svg.symbol.html
758
+ ]);
759
+ async function appendChildNode(node, cloned, child, context, addWordToFontFamilies) {
760
+ if (isElementNode(child) && (isStyleElement(child) || isScriptElement(child)))
761
+ return;
762
+ if (context.filter && !context.filter(child))
763
+ return;
764
+ if (excludeParentNodes.has(cloned.nodeName) || excludeParentNodes.has(child.nodeName)) {
765
+ context.currentParentNodeStyle = void 0;
766
+ } else {
767
+ context.currentParentNodeStyle = context.currentNodeStyle;
768
+ }
769
+ const childCloned = await cloneNode(child, context, false, addWordToFontFamilies);
770
+ if (context.isEnable("restoreScrollPosition")) {
771
+ restoreScrollPosition(node, childCloned);
772
+ }
773
+ cloned.appendChild(childCloned);
774
+ }
775
+ async function cloneChildNodes(node, cloned, context, addWordToFontFamilies) {
776
+ let firstChild = node.firstChild;
777
+ if (isElementNode(node)) {
778
+ if (node.shadowRoot) {
779
+ firstChild = node.shadowRoot?.firstChild;
780
+ context.shadowRoots.push(node.shadowRoot);
781
+ }
782
+ }
783
+ for (let child = firstChild; child; child = child.nextSibling) {
784
+ if (isCommentNode(child))
785
+ continue;
786
+ if (isElementNode(child) && isSlotElement(child) && typeof child.assignedNodes === "function") {
787
+ const nodes = child.assignedNodes();
788
+ for (let i = 0; i < nodes.length; i++) {
789
+ await appendChildNode(node, cloned, nodes[i], context, addWordToFontFamilies);
790
+ }
791
+ } else {
792
+ await appendChildNode(node, cloned, child, context, addWordToFontFamilies);
793
+ }
794
+ }
795
+ }
796
+ function restoreScrollPosition(node, chlidCloned) {
797
+ if (!isHTMLElementNode(node) || !isHTMLElementNode(chlidCloned))
798
+ return;
799
+ const { scrollTop, scrollLeft } = node;
800
+ if (!scrollTop && !scrollLeft) {
801
+ return;
802
+ }
803
+ const { transform } = chlidCloned.style;
804
+ const matrix = new DOMMatrix(transform);
805
+ const { a, b, c, d } = matrix;
806
+ matrix.a = 1;
807
+ matrix.b = 0;
808
+ matrix.c = 0;
809
+ matrix.d = 1;
810
+ matrix.translateSelf(-scrollLeft, -scrollTop);
811
+ matrix.a = a;
812
+ matrix.b = b;
813
+ matrix.c = c;
814
+ matrix.d = d;
815
+ chlidCloned.style.transform = matrix.toString();
816
+ }
817
+ function applyCssStyleWithOptions(cloned, context) {
818
+ const { backgroundColor, width, height, style: styles } = context;
819
+ const clonedStyle = cloned.style;
820
+ if (backgroundColor)
821
+ clonedStyle.setProperty("background-color", backgroundColor, "important");
822
+ if (width)
823
+ clonedStyle.setProperty("width", `${width}px`, "important");
824
+ if (height)
825
+ clonedStyle.setProperty("height", `${height}px`, "important");
826
+ if (styles) {
827
+ for (const name in styles) clonedStyle[name] = styles[name];
828
+ }
829
+ }
830
+ var NORMAL_ATTRIBUTE_RE = /^[\w-:]+$/;
831
+ async function cloneNode(node, context, isRoot = false, addWordToFontFamilies) {
832
+ const { ownerDocument, ownerWindow, fontFamilies, onCloneEachNode } = context;
833
+ if (ownerDocument && isTextNode(node)) {
834
+ if (addWordToFontFamilies && /\S/.test(node.data)) {
835
+ addWordToFontFamilies(node.data);
836
+ }
837
+ return ownerDocument.createTextNode(node.data);
838
+ }
839
+ if (ownerDocument && ownerWindow && isElementNode(node) && (isHTMLElementNode(node) || isSVGElementNode(node))) {
840
+ const cloned2 = await cloneElement(node, context);
841
+ if (context.isEnable("removeAbnormalAttributes")) {
842
+ const names = cloned2.getAttributeNames();
843
+ for (let len = names.length, i = 0; i < len; i++) {
844
+ const name = names[i];
845
+ if (!NORMAL_ATTRIBUTE_RE.test(name)) {
846
+ cloned2.removeAttribute(name);
847
+ }
848
+ }
849
+ }
850
+ const style = context.currentNodeStyle = copyCssStyles(node, cloned2, isRoot, context);
851
+ if (isRoot)
852
+ applyCssStyleWithOptions(cloned2, context);
853
+ let copyScrollbar = false;
854
+ if (context.isEnable("copyScrollbar")) {
855
+ const overflow = [
856
+ style.get("overflow-x")?.[0],
857
+ style.get("overflow-y")?.[0]
858
+ ];
859
+ copyScrollbar = overflow.includes("scroll") || (overflow.includes("auto") || overflow.includes("overlay")) && (node.scrollHeight > node.clientHeight || node.scrollWidth > node.clientWidth);
860
+ }
861
+ const textTransform = style.get("text-transform")?.[0];
862
+ const families = splitFontFamily(style.get("font-family")?.[0]);
863
+ const addWordToFontFamilies2 = families ? (word) => {
864
+ if (textTransform === "uppercase") {
865
+ word = word.toUpperCase();
866
+ } else if (textTransform === "lowercase") {
867
+ word = word.toLowerCase();
868
+ } else if (textTransform === "capitalize") {
869
+ word = word[0].toUpperCase() + word.substring(1);
870
+ }
871
+ families.forEach((family) => {
872
+ let fontFamily = fontFamilies.get(family);
873
+ if (!fontFamily) {
874
+ fontFamilies.set(family, fontFamily = /* @__PURE__ */ new Set());
875
+ }
876
+ word.split("").forEach((text) => fontFamily.add(text));
877
+ });
878
+ } : void 0;
879
+ copyPseudoClass(
880
+ node,
881
+ cloned2,
882
+ copyScrollbar,
883
+ context,
884
+ addWordToFontFamilies2
885
+ );
886
+ copyInputValue(node, cloned2);
887
+ if (!isVideoElement(node)) {
888
+ await cloneChildNodes(
889
+ node,
890
+ cloned2,
891
+ context,
892
+ addWordToFontFamilies2
893
+ );
894
+ }
895
+ await onCloneEachNode?.(cloned2);
896
+ return cloned2;
897
+ }
898
+ const cloned = node.cloneNode(false);
899
+ await cloneChildNodes(node, cloned, context);
900
+ await onCloneEachNode?.(cloned);
901
+ return cloned;
902
+ }
903
+ function destroyContext(context) {
904
+ context.ownerDocument = void 0;
905
+ context.ownerWindow = void 0;
906
+ context.svgStyleElement = void 0;
907
+ context.svgDefsElement = void 0;
908
+ context.svgStyles.clear();
909
+ context.defaultComputedStyles.clear();
910
+ if (context.sandbox) {
911
+ try {
912
+ context.sandbox.remove();
913
+ } catch (err) {
914
+ context.log.warn("Failed to destroyContext", err);
915
+ }
916
+ context.sandbox = void 0;
917
+ }
918
+ context.workers = [];
919
+ context.fontFamilies.clear();
920
+ context.fontCssTexts.clear();
921
+ context.requests.clear();
922
+ context.tasks = [];
923
+ context.shadowRoots = [];
924
+ }
925
+ function baseFetch(options) {
926
+ const { url, timeout, responseType, ...requestInit } = options;
927
+ const controller = new AbortController();
928
+ const timer = timeout ? setTimeout(() => controller.abort(), timeout) : void 0;
929
+ return fetch(url, { signal: controller.signal, ...requestInit }).then((response) => {
930
+ if (!response.ok) {
931
+ throw new Error("Failed fetch, not 2xx response", { cause: response });
932
+ }
933
+ switch (responseType) {
934
+ case "arrayBuffer":
935
+ return response.arrayBuffer();
936
+ case "dataUrl":
937
+ return response.blob().then(blobToDataUrl);
938
+ case "text":
939
+ default:
940
+ return response.text();
941
+ }
942
+ }).finally(() => clearTimeout(timer));
943
+ }
944
+ function contextFetch(context, options) {
945
+ const { url: rawUrl, requestType = "text", responseType = "text", imageDom } = options;
946
+ let url = rawUrl;
947
+ const {
948
+ timeout,
949
+ acceptOfImage,
950
+ requests,
951
+ fetchFn,
952
+ fetch: {
953
+ requestInit,
954
+ bypassingCache,
955
+ placeholderImage
956
+ },
957
+ font,
958
+ workers,
959
+ fontFamilies
960
+ } = context;
961
+ if (requestType === "image" && (IN_SAFARI || IN_FIREFOX)) {
962
+ context.drawImageCount++;
963
+ }
964
+ let request = requests.get(rawUrl);
965
+ if (!request) {
966
+ if (bypassingCache) {
967
+ if (bypassingCache instanceof RegExp && bypassingCache.test(url)) {
968
+ url += (/\?/.test(url) ? "&" : "?") + (/* @__PURE__ */ new Date()).getTime();
969
+ }
970
+ }
971
+ const canFontMinify = requestType.startsWith("font") && font && font.minify;
972
+ const fontTexts = /* @__PURE__ */ new Set();
973
+ if (canFontMinify) {
974
+ const families = requestType.split(";")[1].split(",");
975
+ families.forEach((family) => {
976
+ if (!fontFamilies.has(family))
977
+ return;
978
+ fontFamilies.get(family).forEach((text) => fontTexts.add(text));
979
+ });
980
+ }
981
+ const needFontMinify = canFontMinify && fontTexts.size;
982
+ const baseFetchOptions = {
983
+ url,
984
+ timeout,
985
+ responseType: needFontMinify ? "arrayBuffer" : responseType,
986
+ headers: requestType === "image" ? { accept: acceptOfImage } : void 0,
987
+ ...requestInit
988
+ };
989
+ request = {
990
+ type: requestType,
991
+ resolve: void 0,
992
+ reject: void 0,
993
+ response: null
994
+ };
995
+ request.response = (async () => {
996
+ if (fetchFn && requestType === "image") {
997
+ const result = await fetchFn(rawUrl);
998
+ if (result)
999
+ return result;
1000
+ }
1001
+ if (!IN_SAFARI && rawUrl.startsWith("http") && workers.length) {
1002
+ return new Promise((resolve, reject) => {
1003
+ const worker = workers[requests.size & workers.length - 1];
1004
+ worker.postMessage({ rawUrl, ...baseFetchOptions });
1005
+ request.resolve = resolve;
1006
+ request.reject = reject;
1007
+ });
1008
+ }
1009
+ return baseFetch(baseFetchOptions);
1010
+ })().catch((error) => {
1011
+ requests.delete(rawUrl);
1012
+ if (requestType === "image" && placeholderImage) {
1013
+ context.log.warn("Failed to fetch image base64, trying to use placeholder image", url);
1014
+ return typeof placeholderImage === "string" ? placeholderImage : placeholderImage(imageDom);
1015
+ }
1016
+ throw error;
1017
+ });
1018
+ requests.set(rawUrl, request);
1019
+ }
1020
+ return request.response;
1021
+ }
1022
+ async function replaceCssUrlToDataUrl(cssText, baseUrl, context, isImage) {
1023
+ if (!hasCssUrl(cssText))
1024
+ return cssText;
1025
+ for (const [rawUrl, url] of parseCssUrls(cssText, baseUrl)) {
1026
+ try {
1027
+ const dataUrl = await contextFetch(
1028
+ context,
1029
+ {
1030
+ url,
1031
+ requestType: isImage ? "image" : "text",
1032
+ responseType: "dataUrl"
1033
+ }
1034
+ );
1035
+ cssText = cssText.replace(toRE(rawUrl), `$1${dataUrl}$3`);
1036
+ } catch (error) {
1037
+ context.log.warn("Failed to fetch css data url", rawUrl, error);
1038
+ }
1039
+ }
1040
+ return cssText;
1041
+ }
1042
+ function hasCssUrl(cssText) {
1043
+ return /url\((['"]?)([^'"]+?)\1\)/.test(cssText);
1044
+ }
1045
+ var URL_RE = /url\((['"]?)([^'"]+?)\1\)/g;
1046
+ function parseCssUrls(cssText, baseUrl) {
1047
+ const result = [];
1048
+ cssText.replace(URL_RE, (raw, quotation, url) => {
1049
+ result.push([url, resolveUrl(url, baseUrl)]);
1050
+ return raw;
1051
+ });
1052
+ return result.filter(([url]) => !isDataUrl(url));
1053
+ }
1054
+ function toRE(url) {
1055
+ const escaped = url.replace(/([.*+?^${}()|\[\]\/\\])/g, "\\$1");
1056
+ return new RegExp(`(url\\(['"]?)(${escaped})(['"]?\\))`, "g");
1057
+ }
1058
+ var properties = [
1059
+ "background-image",
1060
+ "border-image-source",
1061
+ "-webkit-border-image",
1062
+ "-webkit-mask-image",
1063
+ "list-style-image"
1064
+ ];
1065
+ function embedCssStyleImage(style, context) {
1066
+ return properties.map((property) => {
1067
+ const value = style.getPropertyValue(property);
1068
+ if (!value || value === "none") {
1069
+ return null;
1070
+ }
1071
+ if (IN_SAFARI || IN_FIREFOX) {
1072
+ context.drawImageCount++;
1073
+ }
1074
+ return replaceCssUrlToDataUrl(value, null, context, true).then((newValue) => {
1075
+ if (!newValue || value === newValue)
1076
+ return;
1077
+ style.setProperty(
1078
+ property,
1079
+ newValue,
1080
+ style.getPropertyPriority(property)
1081
+ );
1082
+ });
1083
+ }).filter(Boolean);
1084
+ }
1085
+ function embedImageElement(cloned, context) {
1086
+ if (isImageElement(cloned)) {
1087
+ const originalSrc = cloned.currentSrc || cloned.src;
1088
+ if (!isDataUrl(originalSrc)) {
1089
+ return [
1090
+ contextFetch(context, {
1091
+ url: originalSrc,
1092
+ imageDom: cloned,
1093
+ requestType: "image",
1094
+ responseType: "dataUrl"
1095
+ }).then((url) => {
1096
+ if (!url)
1097
+ return;
1098
+ cloned.srcset = "";
1099
+ cloned.dataset.originalSrc = originalSrc;
1100
+ cloned.src = url || "";
1101
+ })
1102
+ ];
1103
+ }
1104
+ if (IN_SAFARI || IN_FIREFOX) {
1105
+ context.drawImageCount++;
1106
+ }
1107
+ } else if (isSVGElementNode(cloned) && !isDataUrl(cloned.href.baseVal)) {
1108
+ const originalSrc = cloned.href.baseVal;
1109
+ return [
1110
+ contextFetch(context, {
1111
+ url: originalSrc,
1112
+ imageDom: cloned,
1113
+ requestType: "image",
1114
+ responseType: "dataUrl"
1115
+ }).then((url) => {
1116
+ if (!url)
1117
+ return;
1118
+ cloned.dataset.originalSrc = originalSrc;
1119
+ cloned.href.baseVal = url || "";
1120
+ })
1121
+ ];
1122
+ }
1123
+ return [];
1124
+ }
1125
+ function embedSvgUse(cloned, context) {
1126
+ const { ownerDocument, svgDefsElement } = context;
1127
+ const href = cloned.getAttribute("href") ?? cloned.getAttribute("xlink:href");
1128
+ if (!href)
1129
+ return [];
1130
+ const [svgUrl, id] = href.split("#");
1131
+ if (id) {
1132
+ const query = `#${id}`;
1133
+ const definition = context.shadowRoots.reduce(
1134
+ (res, root) => {
1135
+ return res ?? root.querySelector(`svg ${query}`);
1136
+ },
1137
+ ownerDocument?.querySelector(`svg ${query}`)
1138
+ );
1139
+ if (svgUrl) {
1140
+ cloned.setAttribute("href", query);
1141
+ }
1142
+ if (svgDefsElement?.querySelector(query))
1143
+ return [];
1144
+ if (definition) {
1145
+ svgDefsElement?.appendChild(definition.cloneNode(true));
1146
+ return [];
1147
+ } else if (svgUrl) {
1148
+ return [
1149
+ contextFetch(context, {
1150
+ url: svgUrl,
1151
+ responseType: "text"
1152
+ }).then((svgData) => {
1153
+ svgDefsElement?.insertAdjacentHTML("beforeend", svgData);
1154
+ })
1155
+ ];
1156
+ }
1157
+ }
1158
+ return [];
1159
+ }
1160
+ function embedNode(cloned, context) {
1161
+ const { tasks } = context;
1162
+ if (isElementNode(cloned)) {
1163
+ if (isImageElement(cloned) || isSVGImageElementNode(cloned)) {
1164
+ tasks.push(...embedImageElement(cloned, context));
1165
+ }
1166
+ if (isSVGUseElementNode(cloned)) {
1167
+ tasks.push(...embedSvgUse(cloned, context));
1168
+ }
1169
+ }
1170
+ if (isHTMLElementNode(cloned)) {
1171
+ tasks.push(...embedCssStyleImage(cloned.style, context));
1172
+ }
1173
+ cloned.childNodes.forEach((child) => {
1174
+ embedNode(child, context);
1175
+ });
1176
+ }
1177
+ async function embedWebFont(clone, context) {
1178
+ const {
1179
+ ownerDocument,
1180
+ svgStyleElement,
1181
+ fontFamilies,
1182
+ fontCssTexts,
1183
+ tasks,
1184
+ font
1185
+ } = context;
1186
+ if (!ownerDocument || !svgStyleElement || !fontFamilies.size) {
1187
+ return;
1188
+ }
1189
+ if (font && font.cssText) {
1190
+ const cssText = filterPreferredFormat(font.cssText, context);
1191
+ svgStyleElement.appendChild(ownerDocument.createTextNode(`${cssText}
1192
+ `));
1193
+ } else {
1194
+ const styleSheets = Array.from(ownerDocument.styleSheets).filter((styleSheet) => {
1195
+ try {
1196
+ return "cssRules" in styleSheet && Boolean(styleSheet.cssRules.length);
1197
+ } catch (error) {
1198
+ context.log.warn(`Error while reading CSS rules from ${styleSheet.href}`, error);
1199
+ return false;
1200
+ }
1201
+ });
1202
+ const tempDoc = ownerDocument.implementation.createHTMLDocument("");
1203
+ const tempStyleEl = tempDoc.createElement("style");
1204
+ tempDoc.head.appendChild(tempStyleEl);
1205
+ const tempStyleSheet = tempStyleEl.sheet;
1206
+ await Promise.all(
1207
+ styleSheets.flatMap((styleSheet) => {
1208
+ return Array.from(styleSheet.cssRules).map(async (cssRule) => {
1209
+ if (isCSSImportRule(cssRule)) {
1210
+ const baseUrl = cssRule.href;
1211
+ let cssText = "";
1212
+ try {
1213
+ cssText = await contextFetch(context, {
1214
+ url: baseUrl,
1215
+ requestType: "text",
1216
+ responseType: "text"
1217
+ });
1218
+ } catch (error) {
1219
+ context.log.warn(`Error fetch remote css import from ${baseUrl}`, error);
1220
+ }
1221
+ const replacedCssText = cssText.replace(
1222
+ URL_RE,
1223
+ (raw, quotation, url) => raw.replace(url, resolveUrl(url, baseUrl))
1224
+ );
1225
+ for (const rule of parseCss(replacedCssText)) {
1226
+ try {
1227
+ tempStyleSheet.insertRule(rule, tempStyleSheet.cssRules.length);
1228
+ } catch (error) {
1229
+ context.log.warn("Error inserting rule from remote css import", { rule, error });
1230
+ }
1231
+ }
1232
+ }
1233
+ });
1234
+ })
1235
+ );
1236
+ if (tempStyleSheet.cssRules.length)
1237
+ styleSheets.push(tempStyleSheet);
1238
+ const cssRules = [];
1239
+ styleSheets.forEach((sheet) => {
1240
+ unwrapCssLayers(sheet.cssRules, cssRules);
1241
+ });
1242
+ cssRules.filter((cssRule) => isCssFontFaceRule(cssRule) && hasCssUrl(cssRule.style.getPropertyValue("src")) && splitFontFamily(cssRule.style.getPropertyValue("font-family"))?.some((val) => fontFamilies.has(val))).forEach((value) => {
1243
+ const rule = value;
1244
+ const cssText = fontCssTexts.get(rule.cssText);
1245
+ if (cssText) {
1246
+ svgStyleElement.appendChild(ownerDocument.createTextNode(`${cssText}
1247
+ `));
1248
+ } else {
1249
+ tasks.push(
1250
+ replaceCssUrlToDataUrl(
1251
+ rule.cssText,
1252
+ rule.parentStyleSheet ? rule.parentStyleSheet.href : null,
1253
+ context
1254
+ ).then((cssText2) => {
1255
+ cssText2 = filterPreferredFormat(cssText2, context);
1256
+ fontCssTexts.set(rule.cssText, cssText2);
1257
+ svgStyleElement.appendChild(ownerDocument.createTextNode(`${cssText2}
1258
+ `));
1259
+ })
1260
+ );
1261
+ }
1262
+ });
1263
+ }
1264
+ }
1265
+ var COMMENTS_RE = /(\/\*[\s\S]*?\*\/)/g;
1266
+ var KEYFRAMES_RE = /((@.*?keyframes [\s\S]*?){([\s\S]*?}\s*?)})/gi;
1267
+ function parseCss(source) {
1268
+ if (source == null)
1269
+ return [];
1270
+ const result = [];
1271
+ let cssText = source.replace(COMMENTS_RE, "");
1272
+ while (true) {
1273
+ const matches = KEYFRAMES_RE.exec(cssText);
1274
+ if (!matches)
1275
+ break;
1276
+ result.push(matches[0]);
1277
+ }
1278
+ cssText = cssText.replace(KEYFRAMES_RE, "");
1279
+ const IMPORT_RE = /@import[\s\S]*?url\([^)]*\)[\s\S]*?;/gi;
1280
+ const UNIFIED_RE = new RegExp(
1281
+ // eslint-disable-next-line
1282
+ "((\\s*?(?:\\/\\*[\\s\\S]*?\\*\\/)?\\s*?@media[\\s\\S]*?){([\\s\\S]*?)}\\s*?})|(([\\s\\S]*?){([\\s\\S]*?)})",
1283
+ "gi"
1284
+ );
1285
+ while (true) {
1286
+ let matches = IMPORT_RE.exec(cssText);
1287
+ if (!matches) {
1288
+ matches = UNIFIED_RE.exec(cssText);
1289
+ if (!matches) {
1290
+ break;
1291
+ } else {
1292
+ IMPORT_RE.lastIndex = UNIFIED_RE.lastIndex;
1293
+ }
1294
+ } else {
1295
+ UNIFIED_RE.lastIndex = IMPORT_RE.lastIndex;
1296
+ }
1297
+ result.push(matches[0]);
1298
+ }
1299
+ return result;
1300
+ }
1301
+ var URL_WITH_FORMAT_RE = /url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g;
1302
+ var FONT_SRC_RE = /src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;
1303
+ function filterPreferredFormat(str, context) {
1304
+ const { font } = context;
1305
+ const preferredFormat = font ? font?.preferredFormat : void 0;
1306
+ return preferredFormat ? str.replace(FONT_SRC_RE, (match) => {
1307
+ while (true) {
1308
+ const [src, , format] = URL_WITH_FORMAT_RE.exec(match) || [];
1309
+ if (!format)
1310
+ return "";
1311
+ if (format === preferredFormat)
1312
+ return `src: ${src};`;
1313
+ }
1314
+ }) : str;
1315
+ }
1316
+ function unwrapCssLayers(rules, out = []) {
1317
+ for (const rule of Array.from(rules)) {
1318
+ if (isLayerBlockRule(rule)) {
1319
+ out.push(...unwrapCssLayers(rule.cssRules));
1320
+ } else if ("cssRules" in rule) {
1321
+ unwrapCssLayers(rule.cssRules, out);
1322
+ } else {
1323
+ out.push(rule);
1324
+ }
1325
+ }
1326
+ return out;
1327
+ }
1328
+ var SVG_EXTERNAL_RESOURCE_REGEX = /\bx?link:?href\s*=\s*["'](?!data:)[^"']+["']/i;
1329
+ function svgHasExternalResources(svg) {
1330
+ return SVG_EXTERNAL_RESOURCE_REGEX.test(svg.innerHTML);
1331
+ }
1332
+ async function domToForeignObjectSvg(node, options) {
1333
+ const context = await orCreateContext(node, options);
1334
+ if (isElementNode(context.node) && isSVGElementNode(context.node) && !svgHasExternalResources(context.node))
1335
+ return context.node;
1336
+ const {
1337
+ ownerDocument,
1338
+ log,
1339
+ tasks,
1340
+ svgStyleElement,
1341
+ svgDefsElement,
1342
+ svgStyles,
1343
+ font,
1344
+ progress,
1345
+ autoDestruct,
1346
+ onCloneNode,
1347
+ onEmbedNode,
1348
+ onCreateForeignObjectSvg
1349
+ } = context;
1350
+ log.time("clone node");
1351
+ const clone = await cloneNode(context.node, context, true);
1352
+ if (svgStyleElement && ownerDocument) {
1353
+ let allCssText = "";
1354
+ svgStyles.forEach((klasses, cssText) => {
1355
+ allCssText += `${klasses.join(",\n")} {
1356
+ ${cssText}
1357
+ }
1358
+ `;
1359
+ });
1360
+ svgStyleElement.appendChild(ownerDocument.createTextNode(allCssText));
1361
+ }
1362
+ log.timeEnd("clone node");
1363
+ await onCloneNode?.(clone);
1364
+ if (font !== false && isElementNode(clone)) {
1365
+ log.time("embed web font");
1366
+ await embedWebFont(clone, context);
1367
+ log.timeEnd("embed web font");
1368
+ }
1369
+ log.time("embed node");
1370
+ embedNode(clone, context);
1371
+ const count = tasks.length;
1372
+ let current = 0;
1373
+ const runTask = async () => {
1374
+ while (true) {
1375
+ const task = tasks.pop();
1376
+ if (!task)
1377
+ break;
1378
+ try {
1379
+ await task;
1380
+ } catch (error) {
1381
+ context.log.warn("Failed to run task", error);
1382
+ }
1383
+ progress?.(++current, count);
1384
+ }
1385
+ };
1386
+ progress?.(current, count);
1387
+ await Promise.all([...Array.from({ length: 4 })].map(runTask));
1388
+ log.timeEnd("embed node");
1389
+ await onEmbedNode?.(clone);
1390
+ const svg = createForeignObjectSvg(clone, context);
1391
+ svgDefsElement && svg.insertBefore(svgDefsElement, svg.children[0]);
1392
+ svgStyleElement && svg.insertBefore(svgStyleElement, svg.children[0]);
1393
+ autoDestruct && destroyContext(context);
1394
+ await onCreateForeignObjectSvg?.(svg);
1395
+ return svg;
1396
+ }
1397
+ function createForeignObjectSvg(clone, context) {
1398
+ const { width, height } = context;
1399
+ const svg = createSvg(width, height, clone.ownerDocument);
1400
+ const foreignObject = svg.ownerDocument.createElementNS(svg.namespaceURI, "foreignObject");
1401
+ foreignObject.setAttributeNS(null, "x", "0%");
1402
+ foreignObject.setAttributeNS(null, "y", "0%");
1403
+ foreignObject.setAttributeNS(null, "width", "100%");
1404
+ foreignObject.setAttributeNS(null, "height", "100%");
1405
+ foreignObject.append(clone);
1406
+ svg.appendChild(foreignObject);
1407
+ return svg;
1408
+ }
1409
+ async function domToCanvas(node, options) {
1410
+ const context = await orCreateContext(node, options);
1411
+ const svg = await domToForeignObjectSvg(context);
1412
+ const dataUrl = svgToDataUrl(svg, context.isEnable("removeControlCharacter"));
1413
+ if (!context.autoDestruct) {
1414
+ context.svgStyleElement = createStyleElement(context.ownerDocument);
1415
+ context.svgDefsElement = context.ownerDocument?.createElementNS(XMLNS, "defs");
1416
+ context.svgStyles.clear();
1417
+ }
1418
+ const image = createImage(dataUrl, svg.ownerDocument);
1419
+ return await imageToCanvas(image, context);
1420
+ }
1421
+
1422
+ // src/capture.tsx
1423
+ import { useEffect, useRef, useState } from "react";
1424
+ import { jsx, jsxs } from "react/jsx-runtime";
1425
+ var MAX_BOXES = 6;
1426
+ var MAX_WIDTH = 1600;
1427
+ var MIN_SIDE = 14;
1428
+ function Capture({ onDone, onCancel }) {
1429
+ const [boxes, setBoxes] = useState([]);
1430
+ const [drawing, setDrawing] = useState(null);
1431
+ const [busy, setBusy] = useState(false);
1432
+ const [failed, setFailed] = useState(false);
1433
+ const start = useRef(null);
1434
+ const sampleRef = useRef(null);
1435
+ const doneRef = useRef(null);
1436
+ useEffect(() => {
1437
+ doneRef.current?.focus({ preventScroll: true });
1438
+ const stop = (e) => e.preventDefault();
1439
+ window.addEventListener("wheel", stop, { passive: false });
1440
+ return () => window.removeEventListener("wheel", stop);
1441
+ }, []);
1442
+ const finish = async () => {
1443
+ if (busy) return;
1444
+ setBusy(true);
1445
+ setFailed(false);
1446
+ try {
1447
+ await new Promise((r) => requestAnimationFrame(() => setTimeout(r, 30)));
1448
+ onDone(await capturePage(boxes, sampleRef.current ? getComputedStyle(sampleRef.current).color : "#2b4bee"));
1449
+ } catch (err) {
1450
+ console.error("youasked: couldn't capture the page", err);
1451
+ setBusy(false);
1452
+ setFailed(true);
1453
+ }
1454
+ };
1455
+ useEffect(() => {
1456
+ const onKey = (e) => {
1457
+ if (e.key === "Escape") {
1458
+ e.stopPropagation();
1459
+ onCancel();
1460
+ } else if (e.key === "Enter" && !e.target.closest?.("button")) {
1461
+ e.preventDefault();
1462
+ void finish();
1463
+ }
1464
+ };
1465
+ document.addEventListener("keydown", onKey, true);
1466
+ return () => document.removeEventListener("keydown", onKey, true);
1467
+ });
1468
+ const rect = (a, e) => ({
1469
+ x: Math.min(a.x, e.clientX),
1470
+ y: Math.min(a.y, e.clientY),
1471
+ w: Math.abs(e.clientX - a.x),
1472
+ h: Math.abs(e.clientY - a.y)
1473
+ });
1474
+ return /* @__PURE__ */ jsxs("div", { className: "ya-capture", role: "dialog", "aria-label": "Show us what you mean", "data-busy": busy || void 0, children: [
1475
+ /* @__PURE__ */ jsx("span", { className: "ya-capture-sample", ref: sampleRef, "aria-hidden": "true" }),
1476
+ /* @__PURE__ */ jsx(
1477
+ "div",
1478
+ {
1479
+ className: "ya-capture-surface",
1480
+ onPointerDown: (e) => {
1481
+ if (busy || e.button !== 0 || boxes.length >= MAX_BOXES) return;
1482
+ e.currentTarget.setPointerCapture(e.pointerId);
1483
+ start.current = { x: e.clientX, y: e.clientY };
1484
+ setDrawing({ x: e.clientX, y: e.clientY, w: 0, h: 0 });
1485
+ },
1486
+ onPointerMove: (e) => start.current && setDrawing(rect(start.current, e)),
1487
+ onPointerUp: (e) => {
1488
+ if (!start.current) return;
1489
+ const box = rect(start.current, e);
1490
+ start.current = null;
1491
+ setDrawing(null);
1492
+ if (box.w >= MIN_SIDE && box.h >= MIN_SIDE) setBoxes((b) => [...b, box]);
1493
+ },
1494
+ onPointerCancel: () => {
1495
+ start.current = null;
1496
+ setDrawing(null);
1497
+ },
1498
+ children: [...boxes, ...drawing ? [drawing] : []].map((b, i) => /* @__PURE__ */ jsx("div", { className: "ya-capture-box", style: { left: b.x, top: b.y, width: b.w, height: b.h } }, i))
1499
+ }
1500
+ ),
1501
+ /* @__PURE__ */ jsx("p", { className: "ya-capture-hint", role: "status", children: failed ? "Couldn't capture this page. Try again, or cancel." : boxes.length === 0 ? "Drag to circle what you mean" : boxes.length >= MAX_BOXES ? "That's enough boxes. Press Done." : "Add another, or press Done" }),
1502
+ /* @__PURE__ */ jsxs("div", { className: "ya-capture-bar", children: [
1503
+ /* @__PURE__ */ jsx("button", { type: "button", className: "ya-btn ya-btn-sm ya-btn-ghost", onClick: onCancel, disabled: busy, children: "Cancel" }),
1504
+ boxes.length > 0 && !busy && /* @__PURE__ */ jsx("button", { type: "button", className: "ya-btn ya-btn-sm ya-btn-ghost", onClick: () => setBoxes((b) => b.slice(0, -1)), children: "Undo" }),
1505
+ /* @__PURE__ */ jsx("button", { type: "button", className: "ya-btn ya-btn-sm", onClick: finish, disabled: busy, ref: doneRef, children: busy ? "Capturing\u2026" : "Done" })
1506
+ ] })
1507
+ ] });
1508
+ }
1509
+ function pageBackground() {
1510
+ for (const el of [document.body, document.documentElement]) {
1511
+ const c = getComputedStyle(el).backgroundColor;
1512
+ if (c && c !== "transparent" && !/rgba\(.*,\s*0\)$/.test(c)) return c;
1513
+ }
1514
+ return "#ffffff";
1515
+ }
1516
+ async function capturePage(boxes, accent) {
1517
+ const w = window.innerWidth;
1518
+ const h = window.innerHeight;
1519
+ const scale = Math.min(window.devicePixelRatio || 1, MAX_WIDTH / w);
1520
+ const page = await domToCanvas(document.documentElement, {
1521
+ width: w,
1522
+ height: h,
1523
+ scale,
1524
+ backgroundColor: pageBackground(),
1525
+ // Shift the page up and left by how far it's scrolled, on a root tall enough to still reach the bottom of the screen.
1526
+ onCloneNode: (clone) => {
1527
+ const style = clone.style;
1528
+ style.width = `${w + window.scrollX}px`;
1529
+ style.height = `${h + window.scrollY}px`;
1530
+ style.transformOrigin = "0 0";
1531
+ style.transform = `translate(${-window.scrollX}px, ${-window.scrollY}px)`;
1532
+ },
1533
+ // The widget's own layers (marked data-ya-skip) are never part of the picture.
1534
+ filter: (node) => !(node instanceof Element && node.hasAttribute("data-ya-skip"))
1535
+ });
1536
+ const k = Math.min(1, MAX_WIDTH / page.width);
1537
+ const canvas = document.createElement("canvas");
1538
+ canvas.width = Math.round(page.width * k);
1539
+ canvas.height = Math.round(page.height * k);
1540
+ const ctx = canvas.getContext("2d");
1541
+ ctx.drawImage(page, 0, 0, canvas.width, canvas.height);
1542
+ if (boxes.length) {
1543
+ const f = canvas.width / w;
1544
+ const rects = boxes.map((b) => [b.x * f, b.y * f, b.w * f, b.h * f]);
1545
+ ctx.save();
1546
+ ctx.fillStyle = "rgba(8, 10, 20, 0.4)";
1547
+ ctx.beginPath();
1548
+ ctx.rect(0, 0, canvas.width, canvas.height);
1549
+ for (const [x, y, bw, bh] of rects) ctx.roundRect(x, y, bw, bh, 8 * f);
1550
+ ctx.fill("evenodd");
1551
+ ctx.restore();
1552
+ for (const [x, y, bw, bh] of rects) {
1553
+ ctx.beginPath();
1554
+ ctx.roundRect(x, y, bw, bh, 8 * f);
1555
+ ctx.lineJoin = "round";
1556
+ ctx.strokeStyle = "rgba(255,255,255,.95)";
1557
+ ctx.lineWidth = 6.5 * f;
1558
+ ctx.stroke();
1559
+ ctx.strokeStyle = accent;
1560
+ ctx.lineWidth = 3.5 * f;
1561
+ ctx.stroke();
1562
+ }
1563
+ }
1564
+ return encode(canvas);
1565
+ }
1566
+ function toBlob(canvas, type, quality) {
1567
+ return new Promise((resolve) => canvas.toBlob(resolve, type, quality));
1568
+ }
1569
+ async function encode(canvas) {
1570
+ let blob = await toBlob(canvas, "image/webp", 0.8);
1571
+ if (!blob || blob.type !== "image/webp") blob = await toBlob(canvas, "image/jpeg", 0.8);
1572
+ if (blob && blob.size > 18e5) blob = await toBlob(canvas, "image/jpeg", 0.6) ?? blob;
1573
+ if (!blob) throw new Error("encode_failed");
1574
+ return blob;
1575
+ }
1576
+ export {
1577
+ Capture as default
1578
+ };