@taskon/widget-react 0.0.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.
Files changed (37) hide show
  1. package/README.md +1064 -0
  2. package/dist/CommunityTaskList.css +5010 -0
  3. package/dist/EligibilityInfo.css +1966 -0
  4. package/dist/LeaderboardWidget.css +815 -0
  5. package/dist/Quest.css +4584 -0
  6. package/dist/Table.css +389 -0
  7. package/dist/TaskOnProvider.css +163 -0
  8. package/dist/WidgetShell.css +182 -0
  9. package/dist/chunks/CommunityTaskList-CrH6r4Av.js +6886 -0
  10. package/dist/chunks/EligibilityInfo-DesW9-k9.js +24900 -0
  11. package/dist/chunks/LeaderboardWidget-BSGpHKTk.js +1156 -0
  12. package/dist/chunks/Quest-uSIVq78I.js +8581 -0
  13. package/dist/chunks/Table-CWGf2FKV.js +449 -0
  14. package/dist/chunks/TaskOnProvider-QMwxGL44.js +1435 -0
  15. package/dist/chunks/ThemeProvider-Cs8IUVQj.js +1118 -0
  16. package/dist/chunks/WidgetShell-NlOgn1x5.js +1517 -0
  17. package/dist/chunks/common-ja-DWhTaFHb.js +23 -0
  18. package/dist/chunks/common-ko-80ezXsMG.js +23 -0
  19. package/dist/chunks/index-CwMvO_wZ.js +777 -0
  20. package/dist/chunks/leaderboardwidget-ja-Bj6gz6y1.js +119 -0
  21. package/dist/chunks/leaderboardwidget-ko-f1cLO9ic.js +119 -0
  22. package/dist/chunks/useToast-BGJhd3BX.js +93 -0
  23. package/dist/chunks/useWidgetLocale-BVcopbZS.js +74 -0
  24. package/dist/chunks/usercenter-ja-DBj_dtuz.js +329 -0
  25. package/dist/chunks/usercenter-ko-DYTkHAld.js +329 -0
  26. package/dist/community-task.d.ts +451 -0
  27. package/dist/community-task.js +9 -0
  28. package/dist/core.d.ts +803 -0
  29. package/dist/core.js +22 -0
  30. package/dist/index.css +3662 -0
  31. package/dist/index.d.ts +1627 -0
  32. package/dist/index.js +7372 -0
  33. package/dist/leaderboard.d.ts +547 -0
  34. package/dist/leaderboard.js +17 -0
  35. package/dist/quest.d.ts +389 -0
  36. package/dist/quest.js +8 -0
  37. package/package.json +97 -0
@@ -0,0 +1,777 @@
1
+ function resolveUrl(url, baseUrl) {
2
+ if (url.match(/^[a-z]+:\/\//i)) {
3
+ return url;
4
+ }
5
+ if (url.match(/^\/\//)) {
6
+ return window.location.protocol + url;
7
+ }
8
+ if (url.match(/^[a-z]+:/i)) {
9
+ return url;
10
+ }
11
+ const doc = document.implementation.createHTMLDocument();
12
+ const base = doc.createElement("base");
13
+ const a = doc.createElement("a");
14
+ doc.head.appendChild(base);
15
+ doc.body.appendChild(a);
16
+ if (baseUrl) {
17
+ base.href = baseUrl;
18
+ }
19
+ a.href = url;
20
+ return a.href;
21
+ }
22
+ const uuid = /* @__PURE__ */ (() => {
23
+ let counter = 0;
24
+ const random = () => (
25
+ // eslint-disable-next-line no-bitwise
26
+ `0000${(Math.random() * 36 ** 4 << 0).toString(36)}`.slice(-4)
27
+ );
28
+ return () => {
29
+ counter += 1;
30
+ return `u${random()}${counter}`;
31
+ };
32
+ })();
33
+ function toArray(arrayLike) {
34
+ const arr = [];
35
+ for (let i = 0, l = arrayLike.length; i < l; i++) {
36
+ arr.push(arrayLike[i]);
37
+ }
38
+ return arr;
39
+ }
40
+ let styleProps = null;
41
+ function getStyleProperties(options = {}) {
42
+ if (styleProps) {
43
+ return styleProps;
44
+ }
45
+ if (options.includeStyleProperties) {
46
+ styleProps = options.includeStyleProperties;
47
+ return styleProps;
48
+ }
49
+ styleProps = toArray(window.getComputedStyle(document.documentElement));
50
+ return styleProps;
51
+ }
52
+ function px(node, styleProperty) {
53
+ const win = node.ownerDocument.defaultView || window;
54
+ const val = win.getComputedStyle(node).getPropertyValue(styleProperty);
55
+ return val ? parseFloat(val.replace("px", "")) : 0;
56
+ }
57
+ function getNodeWidth(node) {
58
+ const leftBorder = px(node, "border-left-width");
59
+ const rightBorder = px(node, "border-right-width");
60
+ return node.clientWidth + leftBorder + rightBorder;
61
+ }
62
+ function getNodeHeight(node) {
63
+ const topBorder = px(node, "border-top-width");
64
+ const bottomBorder = px(node, "border-bottom-width");
65
+ return node.clientHeight + topBorder + bottomBorder;
66
+ }
67
+ function getImageSize(targetNode, options = {}) {
68
+ const width = options.width || getNodeWidth(targetNode);
69
+ const height = options.height || getNodeHeight(targetNode);
70
+ return { width, height };
71
+ }
72
+ function getPixelRatio() {
73
+ let ratio;
74
+ let FINAL_PROCESS;
75
+ try {
76
+ FINAL_PROCESS = process;
77
+ } catch (e) {
78
+ }
79
+ const val = FINAL_PROCESS && FINAL_PROCESS.env ? FINAL_PROCESS.env.devicePixelRatio : null;
80
+ if (val) {
81
+ ratio = parseInt(val, 10);
82
+ if (Number.isNaN(ratio)) {
83
+ ratio = 1;
84
+ }
85
+ }
86
+ return ratio || window.devicePixelRatio || 1;
87
+ }
88
+ const canvasDimensionLimit = 16384;
89
+ function checkCanvasDimensions(canvas) {
90
+ if (canvas.width > canvasDimensionLimit || canvas.height > canvasDimensionLimit) {
91
+ if (canvas.width > canvasDimensionLimit && canvas.height > canvasDimensionLimit) {
92
+ if (canvas.width > canvas.height) {
93
+ canvas.height *= canvasDimensionLimit / canvas.width;
94
+ canvas.width = canvasDimensionLimit;
95
+ } else {
96
+ canvas.width *= canvasDimensionLimit / canvas.height;
97
+ canvas.height = canvasDimensionLimit;
98
+ }
99
+ } else if (canvas.width > canvasDimensionLimit) {
100
+ canvas.height *= canvasDimensionLimit / canvas.width;
101
+ canvas.width = canvasDimensionLimit;
102
+ } else {
103
+ canvas.width *= canvasDimensionLimit / canvas.height;
104
+ canvas.height = canvasDimensionLimit;
105
+ }
106
+ }
107
+ }
108
+ function createImage(url) {
109
+ return new Promise((resolve, reject) => {
110
+ const img = new Image();
111
+ img.onload = () => {
112
+ img.decode().then(() => {
113
+ requestAnimationFrame(() => resolve(img));
114
+ });
115
+ };
116
+ img.onerror = reject;
117
+ img.crossOrigin = "anonymous";
118
+ img.decoding = "async";
119
+ img.src = url;
120
+ });
121
+ }
122
+ async function svgToDataURL(svg) {
123
+ return Promise.resolve().then(() => new XMLSerializer().serializeToString(svg)).then(encodeURIComponent).then((html) => `data:image/svg+xml;charset=utf-8,${html}`);
124
+ }
125
+ async function nodeToDataURL(node, width, height) {
126
+ const xmlns = "http://www.w3.org/2000/svg";
127
+ const svg = document.createElementNS(xmlns, "svg");
128
+ const foreignObject = document.createElementNS(xmlns, "foreignObject");
129
+ svg.setAttribute("width", `${width}`);
130
+ svg.setAttribute("height", `${height}`);
131
+ svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
132
+ foreignObject.setAttribute("width", "100%");
133
+ foreignObject.setAttribute("height", "100%");
134
+ foreignObject.setAttribute("x", "0");
135
+ foreignObject.setAttribute("y", "0");
136
+ foreignObject.setAttribute("externalResourcesRequired", "true");
137
+ svg.appendChild(foreignObject);
138
+ foreignObject.appendChild(node);
139
+ return svgToDataURL(svg);
140
+ }
141
+ const isInstanceOfElement = (node, instance) => {
142
+ if (node instanceof instance)
143
+ return true;
144
+ const nodePrototype = Object.getPrototypeOf(node);
145
+ if (nodePrototype === null)
146
+ return false;
147
+ return nodePrototype.constructor.name === instance.name || isInstanceOfElement(nodePrototype, instance);
148
+ };
149
+ function formatCSSText(style) {
150
+ const content = style.getPropertyValue("content");
151
+ return `${style.cssText} content: '${content.replace(/'|"/g, "")}';`;
152
+ }
153
+ function formatCSSProperties(style, options) {
154
+ return getStyleProperties(options).map((name) => {
155
+ const value = style.getPropertyValue(name);
156
+ const priority = style.getPropertyPriority(name);
157
+ return `${name}: ${value}${priority ? " !important" : ""};`;
158
+ }).join(" ");
159
+ }
160
+ function getPseudoElementStyle(className, pseudo, style, options) {
161
+ const selector = `.${className}:${pseudo}`;
162
+ const cssText = style.cssText ? formatCSSText(style) : formatCSSProperties(style, options);
163
+ return document.createTextNode(`${selector}{${cssText}}`);
164
+ }
165
+ function clonePseudoElement(nativeNode, clonedNode, pseudo, options) {
166
+ const style = window.getComputedStyle(nativeNode, pseudo);
167
+ const content = style.getPropertyValue("content");
168
+ if (content === "" || content === "none") {
169
+ return;
170
+ }
171
+ const className = uuid();
172
+ try {
173
+ clonedNode.className = `${clonedNode.className} ${className}`;
174
+ } catch (err) {
175
+ return;
176
+ }
177
+ const styleElement = document.createElement("style");
178
+ styleElement.appendChild(getPseudoElementStyle(className, pseudo, style, options));
179
+ clonedNode.appendChild(styleElement);
180
+ }
181
+ function clonePseudoElements(nativeNode, clonedNode, options) {
182
+ clonePseudoElement(nativeNode, clonedNode, ":before", options);
183
+ clonePseudoElement(nativeNode, clonedNode, ":after", options);
184
+ }
185
+ const WOFF = "application/font-woff";
186
+ const JPEG = "image/jpeg";
187
+ const mimes = {
188
+ woff: WOFF,
189
+ woff2: WOFF,
190
+ ttf: "application/font-truetype",
191
+ eot: "application/vnd.ms-fontobject",
192
+ png: "image/png",
193
+ jpg: JPEG,
194
+ jpeg: JPEG,
195
+ gif: "image/gif",
196
+ tiff: "image/tiff",
197
+ svg: "image/svg+xml",
198
+ webp: "image/webp"
199
+ };
200
+ function getExtension(url) {
201
+ const match = /\.([^./]*?)$/g.exec(url);
202
+ return match ? match[1] : "";
203
+ }
204
+ function getMimeType(url) {
205
+ const extension = getExtension(url).toLowerCase();
206
+ return mimes[extension] || "";
207
+ }
208
+ function getContentFromDataUrl(dataURL) {
209
+ return dataURL.split(/,/)[1];
210
+ }
211
+ function isDataUrl(url) {
212
+ return url.search(/^(data:)/) !== -1;
213
+ }
214
+ function makeDataUrl(content, mimeType) {
215
+ return `data:${mimeType};base64,${content}`;
216
+ }
217
+ async function fetchAsDataURL(url, init, process2) {
218
+ const res = await fetch(url, init);
219
+ if (res.status === 404) {
220
+ throw new Error(`Resource "${res.url}" not found`);
221
+ }
222
+ const blob = await res.blob();
223
+ return new Promise((resolve, reject) => {
224
+ const reader = new FileReader();
225
+ reader.onerror = reject;
226
+ reader.onloadend = () => {
227
+ try {
228
+ resolve(process2({ res, result: reader.result }));
229
+ } catch (error) {
230
+ reject(error);
231
+ }
232
+ };
233
+ reader.readAsDataURL(blob);
234
+ });
235
+ }
236
+ const cache = {};
237
+ function getCacheKey(url, contentType, includeQueryParams) {
238
+ let key = url.replace(/\?.*/, "");
239
+ if (includeQueryParams) {
240
+ key = url;
241
+ }
242
+ if (/ttf|otf|eot|woff2?/i.test(key)) {
243
+ key = key.replace(/.*\//, "");
244
+ }
245
+ return contentType ? `[${contentType}]${key}` : key;
246
+ }
247
+ async function resourceToDataURL(resourceUrl, contentType, options) {
248
+ const cacheKey = getCacheKey(resourceUrl, contentType, options.includeQueryParams);
249
+ if (cache[cacheKey] != null) {
250
+ return cache[cacheKey];
251
+ }
252
+ if (options.cacheBust) {
253
+ resourceUrl += (/\?/.test(resourceUrl) ? "&" : "?") + (/* @__PURE__ */ new Date()).getTime();
254
+ }
255
+ let dataURL;
256
+ try {
257
+ const content = await fetchAsDataURL(resourceUrl, options.fetchRequestInit, ({ res, result }) => {
258
+ if (!contentType) {
259
+ contentType = res.headers.get("Content-Type") || "";
260
+ }
261
+ return getContentFromDataUrl(result);
262
+ });
263
+ dataURL = makeDataUrl(content, contentType);
264
+ } catch (error) {
265
+ dataURL = options.imagePlaceholder || "";
266
+ let msg = `Failed to fetch resource: ${resourceUrl}`;
267
+ if (error) {
268
+ msg = typeof error === "string" ? error : error.message;
269
+ }
270
+ if (msg) {
271
+ console.warn(msg);
272
+ }
273
+ }
274
+ cache[cacheKey] = dataURL;
275
+ return dataURL;
276
+ }
277
+ async function cloneCanvasElement(canvas) {
278
+ const dataURL = canvas.toDataURL();
279
+ if (dataURL === "data:,") {
280
+ return canvas.cloneNode(false);
281
+ }
282
+ return createImage(dataURL);
283
+ }
284
+ async function cloneVideoElement(video, options) {
285
+ if (video.currentSrc) {
286
+ const canvas = document.createElement("canvas");
287
+ const ctx = canvas.getContext("2d");
288
+ canvas.width = video.clientWidth;
289
+ canvas.height = video.clientHeight;
290
+ ctx === null || ctx === void 0 ? void 0 : ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
291
+ const dataURL2 = canvas.toDataURL();
292
+ return createImage(dataURL2);
293
+ }
294
+ const poster = video.poster;
295
+ const contentType = getMimeType(poster);
296
+ const dataURL = await resourceToDataURL(poster, contentType, options);
297
+ return createImage(dataURL);
298
+ }
299
+ async function cloneIFrameElement(iframe, options) {
300
+ var _a;
301
+ try {
302
+ if ((_a = iframe === null || iframe === void 0 ? void 0 : iframe.contentDocument) === null || _a === void 0 ? void 0 : _a.body) {
303
+ return await cloneNode(iframe.contentDocument.body, options, true);
304
+ }
305
+ } catch (_b) {
306
+ }
307
+ return iframe.cloneNode(false);
308
+ }
309
+ async function cloneSingleNode(node, options) {
310
+ if (isInstanceOfElement(node, HTMLCanvasElement)) {
311
+ return cloneCanvasElement(node);
312
+ }
313
+ if (isInstanceOfElement(node, HTMLVideoElement)) {
314
+ return cloneVideoElement(node, options);
315
+ }
316
+ if (isInstanceOfElement(node, HTMLIFrameElement)) {
317
+ return cloneIFrameElement(node, options);
318
+ }
319
+ return node.cloneNode(isSVGElement(node));
320
+ }
321
+ const isSlotElement = (node) => node.tagName != null && node.tagName.toUpperCase() === "SLOT";
322
+ const isSVGElement = (node) => node.tagName != null && node.tagName.toUpperCase() === "SVG";
323
+ async function cloneChildren(nativeNode, clonedNode, options) {
324
+ var _a, _b;
325
+ if (isSVGElement(clonedNode)) {
326
+ return clonedNode;
327
+ }
328
+ let children = [];
329
+ if (isSlotElement(nativeNode) && nativeNode.assignedNodes) {
330
+ children = toArray(nativeNode.assignedNodes());
331
+ } else if (isInstanceOfElement(nativeNode, HTMLIFrameElement) && ((_a = nativeNode.contentDocument) === null || _a === void 0 ? void 0 : _a.body)) {
332
+ children = toArray(nativeNode.contentDocument.body.childNodes);
333
+ } else {
334
+ children = toArray(((_b = nativeNode.shadowRoot) !== null && _b !== void 0 ? _b : nativeNode).childNodes);
335
+ }
336
+ if (children.length === 0 || isInstanceOfElement(nativeNode, HTMLVideoElement)) {
337
+ return clonedNode;
338
+ }
339
+ await children.reduce((deferred, child) => deferred.then(() => cloneNode(child, options)).then((clonedChild) => {
340
+ if (clonedChild) {
341
+ clonedNode.appendChild(clonedChild);
342
+ }
343
+ }), Promise.resolve());
344
+ return clonedNode;
345
+ }
346
+ function cloneCSSStyle(nativeNode, clonedNode, options) {
347
+ const targetStyle = clonedNode.style;
348
+ if (!targetStyle) {
349
+ return;
350
+ }
351
+ const sourceStyle = window.getComputedStyle(nativeNode);
352
+ if (sourceStyle.cssText) {
353
+ targetStyle.cssText = sourceStyle.cssText;
354
+ targetStyle.transformOrigin = sourceStyle.transformOrigin;
355
+ } else {
356
+ getStyleProperties(options).forEach((name) => {
357
+ let value = sourceStyle.getPropertyValue(name);
358
+ if (name === "font-size" && value.endsWith("px")) {
359
+ const reducedFont = Math.floor(parseFloat(value.substring(0, value.length - 2))) - 0.1;
360
+ value = `${reducedFont}px`;
361
+ }
362
+ if (isInstanceOfElement(nativeNode, HTMLIFrameElement) && name === "display" && value === "inline") {
363
+ value = "block";
364
+ }
365
+ if (name === "d" && clonedNode.getAttribute("d")) {
366
+ value = `path(${clonedNode.getAttribute("d")})`;
367
+ }
368
+ targetStyle.setProperty(name, value, sourceStyle.getPropertyPriority(name));
369
+ });
370
+ }
371
+ }
372
+ function cloneInputValue(nativeNode, clonedNode) {
373
+ if (isInstanceOfElement(nativeNode, HTMLTextAreaElement)) {
374
+ clonedNode.innerHTML = nativeNode.value;
375
+ }
376
+ if (isInstanceOfElement(nativeNode, HTMLInputElement)) {
377
+ clonedNode.setAttribute("value", nativeNode.value);
378
+ }
379
+ }
380
+ function cloneSelectValue(nativeNode, clonedNode) {
381
+ if (isInstanceOfElement(nativeNode, HTMLSelectElement)) {
382
+ const clonedSelect = clonedNode;
383
+ const selectedOption = Array.from(clonedSelect.children).find((child) => nativeNode.value === child.getAttribute("value"));
384
+ if (selectedOption) {
385
+ selectedOption.setAttribute("selected", "");
386
+ }
387
+ }
388
+ }
389
+ function decorate(nativeNode, clonedNode, options) {
390
+ if (isInstanceOfElement(clonedNode, Element)) {
391
+ cloneCSSStyle(nativeNode, clonedNode, options);
392
+ clonePseudoElements(nativeNode, clonedNode, options);
393
+ cloneInputValue(nativeNode, clonedNode);
394
+ cloneSelectValue(nativeNode, clonedNode);
395
+ }
396
+ return clonedNode;
397
+ }
398
+ async function ensureSVGSymbols(clone, options) {
399
+ const uses = clone.querySelectorAll ? clone.querySelectorAll("use") : [];
400
+ if (uses.length === 0) {
401
+ return clone;
402
+ }
403
+ const processedDefs = {};
404
+ for (let i = 0; i < uses.length; i++) {
405
+ const use = uses[i];
406
+ const id = use.getAttribute("xlink:href");
407
+ if (id) {
408
+ const exist = clone.querySelector(id);
409
+ const definition = document.querySelector(id);
410
+ if (!exist && definition && !processedDefs[id]) {
411
+ processedDefs[id] = await cloneNode(definition, options, true);
412
+ }
413
+ }
414
+ }
415
+ const nodes = Object.values(processedDefs);
416
+ if (nodes.length) {
417
+ const ns = "http://www.w3.org/1999/xhtml";
418
+ const svg = document.createElementNS(ns, "svg");
419
+ svg.setAttribute("xmlns", ns);
420
+ svg.style.position = "absolute";
421
+ svg.style.width = "0";
422
+ svg.style.height = "0";
423
+ svg.style.overflow = "hidden";
424
+ svg.style.display = "none";
425
+ const defs = document.createElementNS(ns, "defs");
426
+ svg.appendChild(defs);
427
+ for (let i = 0; i < nodes.length; i++) {
428
+ defs.appendChild(nodes[i]);
429
+ }
430
+ clone.appendChild(svg);
431
+ }
432
+ return clone;
433
+ }
434
+ async function cloneNode(node, options, isRoot) {
435
+ if (!isRoot && options.filter && !options.filter(node)) {
436
+ return null;
437
+ }
438
+ return Promise.resolve(node).then((clonedNode) => cloneSingleNode(clonedNode, options)).then((clonedNode) => cloneChildren(node, clonedNode, options)).then((clonedNode) => decorate(node, clonedNode, options)).then((clonedNode) => ensureSVGSymbols(clonedNode, options));
439
+ }
440
+ const URL_REGEX = /url\((['"]?)([^'"]+?)\1\)/g;
441
+ const URL_WITH_FORMAT_REGEX = /url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g;
442
+ const FONT_SRC_REGEX = /src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;
443
+ function toRegex(url) {
444
+ const escaped = url.replace(/([.*+?^${}()|\[\]\/\\])/g, "\\$1");
445
+ return new RegExp(`(url\\(['"]?)(${escaped})(['"]?\\))`, "g");
446
+ }
447
+ function parseURLs(cssText) {
448
+ const urls = [];
449
+ cssText.replace(URL_REGEX, (raw, quotation, url) => {
450
+ urls.push(url);
451
+ return raw;
452
+ });
453
+ return urls.filter((url) => !isDataUrl(url));
454
+ }
455
+ async function embed(cssText, resourceURL, baseURL, options, getContentFromUrl) {
456
+ try {
457
+ const resolvedURL = baseURL ? resolveUrl(resourceURL, baseURL) : resourceURL;
458
+ const contentType = getMimeType(resourceURL);
459
+ let dataURL;
460
+ if (getContentFromUrl) ;
461
+ else {
462
+ dataURL = await resourceToDataURL(resolvedURL, contentType, options);
463
+ }
464
+ return cssText.replace(toRegex(resourceURL), `$1${dataURL}$3`);
465
+ } catch (error) {
466
+ }
467
+ return cssText;
468
+ }
469
+ function filterPreferredFontFormat(str, { preferredFontFormat }) {
470
+ return !preferredFontFormat ? str : str.replace(FONT_SRC_REGEX, (match) => {
471
+ while (true) {
472
+ const [src, , format] = URL_WITH_FORMAT_REGEX.exec(match) || [];
473
+ if (!format) {
474
+ return "";
475
+ }
476
+ if (format === preferredFontFormat) {
477
+ return `src: ${src};`;
478
+ }
479
+ }
480
+ });
481
+ }
482
+ function shouldEmbed(url) {
483
+ return url.search(URL_REGEX) !== -1;
484
+ }
485
+ async function embedResources(cssText, baseUrl, options) {
486
+ if (!shouldEmbed(cssText)) {
487
+ return cssText;
488
+ }
489
+ const filteredCSSText = filterPreferredFontFormat(cssText, options);
490
+ const urls = parseURLs(filteredCSSText);
491
+ return urls.reduce((deferred, url) => deferred.then((css) => embed(css, url, baseUrl, options)), Promise.resolve(filteredCSSText));
492
+ }
493
+ async function embedProp(propName, node, options) {
494
+ var _a;
495
+ const propValue = (_a = node.style) === null || _a === void 0 ? void 0 : _a.getPropertyValue(propName);
496
+ if (propValue) {
497
+ const cssString = await embedResources(propValue, null, options);
498
+ node.style.setProperty(propName, cssString, node.style.getPropertyPriority(propName));
499
+ return true;
500
+ }
501
+ return false;
502
+ }
503
+ async function embedBackground(clonedNode, options) {
504
+ await embedProp("background", clonedNode, options) || await embedProp("background-image", clonedNode, options);
505
+ await embedProp("mask", clonedNode, options) || await embedProp("-webkit-mask", clonedNode, options) || await embedProp("mask-image", clonedNode, options) || await embedProp("-webkit-mask-image", clonedNode, options);
506
+ }
507
+ async function embedImageNode(clonedNode, options) {
508
+ const isImageElement = isInstanceOfElement(clonedNode, HTMLImageElement);
509
+ if (!(isImageElement && !isDataUrl(clonedNode.src)) && !(isInstanceOfElement(clonedNode, SVGImageElement) && !isDataUrl(clonedNode.href.baseVal))) {
510
+ return;
511
+ }
512
+ const url = isImageElement ? clonedNode.src : clonedNode.href.baseVal;
513
+ const dataURL = await resourceToDataURL(url, getMimeType(url), options);
514
+ await new Promise((resolve, reject) => {
515
+ clonedNode.onload = resolve;
516
+ clonedNode.onerror = options.onImageErrorHandler ? (...attributes) => {
517
+ try {
518
+ resolve(options.onImageErrorHandler(...attributes));
519
+ } catch (error) {
520
+ reject(error);
521
+ }
522
+ } : reject;
523
+ const image = clonedNode;
524
+ if (image.decode) {
525
+ image.decode = resolve;
526
+ }
527
+ if (image.loading === "lazy") {
528
+ image.loading = "eager";
529
+ }
530
+ if (isImageElement) {
531
+ clonedNode.srcset = "";
532
+ clonedNode.src = dataURL;
533
+ } else {
534
+ clonedNode.href.baseVal = dataURL;
535
+ }
536
+ });
537
+ }
538
+ async function embedChildren(clonedNode, options) {
539
+ const children = toArray(clonedNode.childNodes);
540
+ const deferreds = children.map((child) => embedImages(child, options));
541
+ await Promise.all(deferreds).then(() => clonedNode);
542
+ }
543
+ async function embedImages(clonedNode, options) {
544
+ if (isInstanceOfElement(clonedNode, Element)) {
545
+ await embedBackground(clonedNode, options);
546
+ await embedImageNode(clonedNode, options);
547
+ await embedChildren(clonedNode, options);
548
+ }
549
+ }
550
+ function applyStyle(node, options) {
551
+ const { style } = node;
552
+ if (options.backgroundColor) {
553
+ style.backgroundColor = options.backgroundColor;
554
+ }
555
+ if (options.width) {
556
+ style.width = `${options.width}px`;
557
+ }
558
+ if (options.height) {
559
+ style.height = `${options.height}px`;
560
+ }
561
+ const manual = options.style;
562
+ if (manual != null) {
563
+ Object.keys(manual).forEach((key) => {
564
+ style[key] = manual[key];
565
+ });
566
+ }
567
+ return node;
568
+ }
569
+ const cssFetchCache = {};
570
+ async function fetchCSS(url) {
571
+ let cache2 = cssFetchCache[url];
572
+ if (cache2 != null) {
573
+ return cache2;
574
+ }
575
+ const res = await fetch(url);
576
+ const cssText = await res.text();
577
+ cache2 = { url, cssText };
578
+ cssFetchCache[url] = cache2;
579
+ return cache2;
580
+ }
581
+ async function embedFonts(data, options) {
582
+ let cssText = data.cssText;
583
+ const regexUrl = /url\(["']?([^"')]+)["']?\)/g;
584
+ const fontLocs = cssText.match(/url\([^)]+\)/g) || [];
585
+ const loadFonts = fontLocs.map(async (loc) => {
586
+ let url = loc.replace(regexUrl, "$1");
587
+ if (!url.startsWith("https://")) {
588
+ url = new URL(url, data.url).href;
589
+ }
590
+ return fetchAsDataURL(url, options.fetchRequestInit, ({ result }) => {
591
+ cssText = cssText.replace(loc, `url(${result})`);
592
+ return [loc, result];
593
+ });
594
+ });
595
+ return Promise.all(loadFonts).then(() => cssText);
596
+ }
597
+ function parseCSS(source) {
598
+ if (source == null) {
599
+ return [];
600
+ }
601
+ const result = [];
602
+ const commentsRegex = /(\/\*[\s\S]*?\*\/)/gi;
603
+ let cssText = source.replace(commentsRegex, "");
604
+ const keyframesRegex = new RegExp("((@.*?keyframes [\\s\\S]*?){([\\s\\S]*?}\\s*?)})", "gi");
605
+ while (true) {
606
+ const matches = keyframesRegex.exec(cssText);
607
+ if (matches === null) {
608
+ break;
609
+ }
610
+ result.push(matches[0]);
611
+ }
612
+ cssText = cssText.replace(keyframesRegex, "");
613
+ const importRegex = /@import[\s\S]*?url\([^)]*\)[\s\S]*?;/gi;
614
+ const combinedCSSRegex = "((\\s*?(?:\\/\\*[\\s\\S]*?\\*\\/)?\\s*?@media[\\s\\S]*?){([\\s\\S]*?)}\\s*?})|(([\\s\\S]*?){([\\s\\S]*?)})";
615
+ const unifiedRegex = new RegExp(combinedCSSRegex, "gi");
616
+ while (true) {
617
+ let matches = importRegex.exec(cssText);
618
+ if (matches === null) {
619
+ matches = unifiedRegex.exec(cssText);
620
+ if (matches === null) {
621
+ break;
622
+ } else {
623
+ importRegex.lastIndex = unifiedRegex.lastIndex;
624
+ }
625
+ } else {
626
+ unifiedRegex.lastIndex = importRegex.lastIndex;
627
+ }
628
+ result.push(matches[0]);
629
+ }
630
+ return result;
631
+ }
632
+ async function getCSSRules(styleSheets, options) {
633
+ const ret = [];
634
+ const deferreds = [];
635
+ styleSheets.forEach((sheet) => {
636
+ if ("cssRules" in sheet) {
637
+ try {
638
+ toArray(sheet.cssRules || []).forEach((item, index) => {
639
+ if (item.type === CSSRule.IMPORT_RULE) {
640
+ let importIndex = index + 1;
641
+ const url = item.href;
642
+ const deferred = fetchCSS(url).then((metadata) => embedFonts(metadata, options)).then((cssText) => parseCSS(cssText).forEach((rule) => {
643
+ try {
644
+ sheet.insertRule(rule, rule.startsWith("@import") ? importIndex += 1 : sheet.cssRules.length);
645
+ } catch (error) {
646
+ console.error("Error inserting rule from remote css", {
647
+ rule,
648
+ error
649
+ });
650
+ }
651
+ })).catch((e) => {
652
+ console.error("Error loading remote css", e.toString());
653
+ });
654
+ deferreds.push(deferred);
655
+ }
656
+ });
657
+ } catch (e) {
658
+ const inline = styleSheets.find((a) => a.href == null) || document.styleSheets[0];
659
+ if (sheet.href != null) {
660
+ deferreds.push(fetchCSS(sheet.href).then((metadata) => embedFonts(metadata, options)).then((cssText) => parseCSS(cssText).forEach((rule) => {
661
+ inline.insertRule(rule, inline.cssRules.length);
662
+ })).catch((err) => {
663
+ console.error("Error loading remote stylesheet", err);
664
+ }));
665
+ }
666
+ console.error("Error inlining remote css file", e);
667
+ }
668
+ }
669
+ });
670
+ return Promise.all(deferreds).then(() => {
671
+ styleSheets.forEach((sheet) => {
672
+ if ("cssRules" in sheet) {
673
+ try {
674
+ toArray(sheet.cssRules || []).forEach((item) => {
675
+ ret.push(item);
676
+ });
677
+ } catch (e) {
678
+ console.error(`Error while reading CSS rules from ${sheet.href}`, e);
679
+ }
680
+ }
681
+ });
682
+ return ret;
683
+ });
684
+ }
685
+ function getWebFontRules(cssRules) {
686
+ return cssRules.filter((rule) => rule.type === CSSRule.FONT_FACE_RULE).filter((rule) => shouldEmbed(rule.style.getPropertyValue("src")));
687
+ }
688
+ async function parseWebFontRules(node, options) {
689
+ if (node.ownerDocument == null) {
690
+ throw new Error("Provided element is not within a Document");
691
+ }
692
+ const styleSheets = toArray(node.ownerDocument.styleSheets);
693
+ const cssRules = await getCSSRules(styleSheets, options);
694
+ return getWebFontRules(cssRules);
695
+ }
696
+ function normalizeFontFamily(font) {
697
+ return font.trim().replace(/["']/g, "");
698
+ }
699
+ function getUsedFonts(node) {
700
+ const fonts = /* @__PURE__ */ new Set();
701
+ function traverse(node2) {
702
+ const fontFamily = node2.style.fontFamily || getComputedStyle(node2).fontFamily;
703
+ fontFamily.split(",").forEach((font) => {
704
+ fonts.add(normalizeFontFamily(font));
705
+ });
706
+ Array.from(node2.children).forEach((child) => {
707
+ if (child instanceof HTMLElement) {
708
+ traverse(child);
709
+ }
710
+ });
711
+ }
712
+ traverse(node);
713
+ return fonts;
714
+ }
715
+ async function getWebFontCSS(node, options) {
716
+ const rules = await parseWebFontRules(node, options);
717
+ const usedFonts = getUsedFonts(node);
718
+ const cssTexts = await Promise.all(rules.filter((rule) => usedFonts.has(normalizeFontFamily(rule.style.fontFamily))).map((rule) => {
719
+ const baseUrl = rule.parentStyleSheet ? rule.parentStyleSheet.href : null;
720
+ return embedResources(rule.cssText, baseUrl, options);
721
+ }));
722
+ return cssTexts.join("\n");
723
+ }
724
+ async function embedWebFonts(clonedNode, options) {
725
+ const cssText = options.fontEmbedCSS != null ? options.fontEmbedCSS : options.skipFonts ? null : await getWebFontCSS(clonedNode, options);
726
+ if (cssText) {
727
+ const styleNode = document.createElement("style");
728
+ const sytleContent = document.createTextNode(cssText);
729
+ styleNode.appendChild(sytleContent);
730
+ if (clonedNode.firstChild) {
731
+ clonedNode.insertBefore(styleNode, clonedNode.firstChild);
732
+ } else {
733
+ clonedNode.appendChild(styleNode);
734
+ }
735
+ }
736
+ }
737
+ async function toSvg(node, options = {}) {
738
+ const { width, height } = getImageSize(node, options);
739
+ const clonedNode = await cloneNode(node, options, true);
740
+ await embedWebFonts(clonedNode, options);
741
+ await embedImages(clonedNode, options);
742
+ applyStyle(clonedNode, options);
743
+ const datauri = await nodeToDataURL(clonedNode, width, height);
744
+ return datauri;
745
+ }
746
+ async function toCanvas(node, options = {}) {
747
+ const { width, height } = getImageSize(node, options);
748
+ const svg = await toSvg(node, options);
749
+ const img = await createImage(svg);
750
+ const canvas = document.createElement("canvas");
751
+ const context = canvas.getContext("2d");
752
+ const ratio = options.pixelRatio || getPixelRatio();
753
+ const canvasWidth = options.canvasWidth || width;
754
+ const canvasHeight = options.canvasHeight || height;
755
+ canvas.width = canvasWidth * ratio;
756
+ canvas.height = canvasHeight * ratio;
757
+ if (!options.skipAutoScale) {
758
+ checkCanvasDimensions(canvas);
759
+ }
760
+ canvas.style.width = `${canvasWidth}`;
761
+ canvas.style.height = `${canvasHeight}`;
762
+ if (options.backgroundColor) {
763
+ context.fillStyle = options.backgroundColor;
764
+ context.fillRect(0, 0, canvas.width, canvas.height);
765
+ }
766
+ context.drawImage(img, 0, 0, canvas.width, canvas.height);
767
+ return canvas;
768
+ }
769
+ async function toPng(node, options = {}) {
770
+ const canvas = await toCanvas(node, options);
771
+ return canvas.toDataURL();
772
+ }
773
+ export {
774
+ toCanvas,
775
+ toPng,
776
+ toSvg
777
+ };