forked from tsayen/dom-to-image
-
Notifications
You must be signed in to change notification settings - Fork 111
/
Copy pathdom-to-image-more.js
1399 lines (1219 loc) · 50.5 KB
/
dom-to-image-more.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function (global) {
'use strict';
const util = newUtil();
const inliner = newInliner();
const fontFaces = newFontFaces();
const images = newImages();
// Default impl options
const defaultOptions = {
// Default is to copy default styles of elements
copyDefaultStyles: true,
// Default is to fail on error, no placeholder
imagePlaceholder: undefined,
// Default cache bust is false, it will use the cache
cacheBust: false,
// Use (existing) authentication credentials for external URIs (CORS requests)
useCredentials: false,
// Default resolve timeout
httpTimeout: 30000,
// Style computation cache tag rules (options are strict, relaxed)
styleCaching: 'strict',
};
const domtoimage = {
toSvg: toSvg,
toPng: toPng,
toJpeg: toJpeg,
toBlob: toBlob,
toPixelData: toPixelData,
toCanvas: toCanvas,
impl: {
fontFaces: fontFaces,
images: images,
util: util,
inliner: inliner,
urlCache: [],
options: {},
},
};
if (typeof exports === 'object' && typeof module === 'object') {
module.exports = domtoimage; // eslint-disable-line no-undef
} else {
global.domtoimage = domtoimage;
}
// support node and browsers
const ELEMENT_NODE =
(typeof Node !== 'undefined' ? Node.ELEMENT_NODE : undefined) || 1;
const getComputedStyle =
(typeof global !== 'undefined' ? global.getComputedStyle : undefined) ||
(typeof window !== 'undefined' ? window.getComputedStyle : undefined) ||
globalThis.getComputedStyle;
const atob =
(typeof global !== 'undefined' ? global.atob : undefined) ||
(typeof window !== 'undefined' ? window.atob : undefined) ||
globalThis.atob;
/**
* @param {Node} node - The DOM Node object to render
* @param {Object} options - Rendering options
* @param {Function} options.filter - Should return true if passed node should be included in the output
* (excluding node means excluding it's children as well). Not called on the root node.
* @param {Function} options.onclone - Callback function which is called when the Document has been cloned for
* rendering, can be used to modify the contents that will be rendered without affecting the original
* source document.
* @param {String} options.bgcolor - color for the background, any valid CSS color value.
* @param {Number} options.width - width to be applied to node before rendering.
* @param {Number} options.height - height to be applied to node before rendering.
* @param {Object} options.style - an object whose properties to be copied to node's style before rendering.
* @param {Number} options.quality - a Number between 0 and 1 indicating image quality (applicable to JPEG only),
defaults to 1.0.
* @param {Number} options.scale - a Number multiplier to scale up the canvas before rendering to reduce fuzzy images, defaults to 1.0.
* @param {String} options.imagePlaceholder - dataURL to use as a placeholder for failed images, default behaviour is to fail fast on images we can't fetch
* @param {Boolean} options.cacheBust - set to true to cache bust by appending the time to the request url
* @param {String} options.styleCaching - set to 'strict', 'relaxed' to select style caching rules
* @param {Boolean} options.copyDefaultStyles - set to false to disable use of default styles of elements
* @return {Promise} - A promise that is fulfilled with a SVG image data URL
* */
function toSvg(node, options) {
const ownerWindow = domtoimage.impl.util.getWindow(node);
options = options || {};
copyOptions(options);
let restorations = [];
return Promise.resolve(node)
.then(ensureElement)
.then(function (clonee) {
return cloneNode(clonee, options, null, ownerWindow);
})
.then(embedFonts)
.then(inlineImages)
.then(applyOptions)
.then(makeSvgDataUri)
.then(restoreWrappers)
.then(clearCache);
function ensureElement(node) {
if (node.nodeType === ELEMENT_NODE) return node;
const originalChild = node;
const originalParent = node.parentNode;
const wrappingSpan = document.createElement('span');
originalParent.replaceChild(wrappingSpan, originalChild);
wrappingSpan.append(node);
restorations.push({
parent: originalParent,
child: originalChild,
wrapper: wrappingSpan,
});
return wrappingSpan;
}
function restoreWrappers(result) {
// put the original children back where the wrappers were inserted
while (restorations.length > 0) {
const restoration = restorations.pop();
restoration.parent.replaceChild(restoration.child, restoration.wrapper);
}
return result;
}
function clearCache(result) {
domtoimage.impl.urlCache = [];
removeSandbox();
return result;
}
function applyOptions(clone) {
if (options.bgcolor) {
clone.style.backgroundColor = options.bgcolor;
}
if (options.width) {
clone.style.width = `${options.width}px`;
}
if (options.height) {
clone.style.height = `${options.height}px`;
}
if (options.style) {
Object.keys(options.style).forEach(function (property) {
clone.style[property] = options.style[property];
});
}
let onCloneResult = null;
if (typeof options.onclone === 'function') {
onCloneResult = options.onclone(clone);
}
return Promise.resolve(onCloneResult).then(function () {
return clone;
});
}
function makeSvgDataUri(node) {
let width = options.width || util.width(node);
let height = options.height || util.height(node);
return Promise.resolve(node)
.then(function (svg) {
svg.setAttribute('xmlns', 'http://www.w3.org/1999/xhtml');
return new XMLSerializer().serializeToString(svg);
})
.then(util.escapeXhtml)
.then(function (xhtml) {
const foreignObjectSizing =
(util.isDimensionMissing(width)
? ' width="100%"'
: ` width="${width}"`) +
(util.isDimensionMissing(height)
? ' height="100%"'
: ` height="${height}"`);
const svgSizing =
(util.isDimensionMissing(width) ? '' : ` width="${width}"`) +
(util.isDimensionMissing(height) ? '' : ` height="${height}"`);
return `<svg xmlns="http://www.w3.org/2000/svg"${svgSizing}><foreignObject${foreignObjectSizing}>${xhtml}</foreignObject></svg>`;
})
.then(function (svg) {
return `data:image/svg+xml;charset=utf-8,${svg}`;
});
}
}
/**
* @param {Node} node - The DOM Node object to render
* @param {Object} options - Rendering options, @see {@link toSvg}
* @return {Promise} - A promise that is fulfilled with a Uint8Array containing RGBA pixel data.
* */
function toPixelData(node, options) {
return draw(node, options).then(function (canvas) {
return canvas
.getContext('2d')
.getImageData(0, 0, util.width(node), util.height(node)).data;
});
}
/**
* @param {Node} node - The DOM Node object to render
* @param {Object} options - Rendering options, @see {@link toSvg}
* @return {Promise} - A promise that is fulfilled with a PNG image data URL
* */
function toPng(node, options) {
return draw(node, options).then(function (canvas) {
return canvas.toDataURL();
});
}
/**
* @param {Node} node - The DOM Node object to render
* @param {Object} options - Rendering options, @see {@link toSvg}
* @return {Promise} - A promise that is fulfilled with a JPEG image data URL
* */
function toJpeg(node, options) {
return draw(node, options).then(function (canvas) {
return canvas.toDataURL(
'image/jpeg',
(options ? options.quality : undefined) || 1.0
);
});
}
/**
* @param {Node} node - The DOM Node object to render
* @param {Object} options - Rendering options, @see {@link toSvg}
* @return {Promise} - A promise that is fulfilled with a PNG image blob
* */
function toBlob(node, options) {
return draw(node, options).then(util.canvasToBlob);
}
/**
* @param {Node} node - The DOM Node object to render
* @param {Object} options - Rendering options, @see {@link toSvg}
* @return {Promise} - A promise that is fulfilled with a canvas object
* */
function toCanvas(node, options) {
return draw(node, options);
}
function copyOptions(options) {
// Copy options to impl options for use in impl
if (typeof options.copyDefaultStyles === 'undefined') {
domtoimage.impl.options.copyDefaultStyles = defaultOptions.copyDefaultStyles;
} else {
domtoimage.impl.options.copyDefaultStyles = options.copyDefaultStyles;
}
if (typeof options.imagePlaceholder === 'undefined') {
domtoimage.impl.options.imagePlaceholder = defaultOptions.imagePlaceholder;
} else {
domtoimage.impl.options.imagePlaceholder = options.imagePlaceholder;
}
if (typeof options.cacheBust === 'undefined') {
domtoimage.impl.options.cacheBust = defaultOptions.cacheBust;
} else {
domtoimage.impl.options.cacheBust = options.cacheBust;
}
if (typeof options.useCredentials === 'undefined') {
domtoimage.impl.options.useCredentials = defaultOptions.useCredentials;
} else {
domtoimage.impl.options.useCredentials = options.useCredentials;
}
if (typeof options.httpTimeout === 'undefined') {
domtoimage.impl.options.httpTimeout = defaultOptions.httpTimeout;
} else {
domtoimage.impl.options.httpTimeout = options.httpTimeout;
}
if (typeof options.styleCaching === 'undefined') {
domtoimage.impl.options.styleCaching = defaultOptions.styleCaching;
} else {
domtoimage.impl.options.styleCaching = options.styleCaching;
}
}
function draw(domNode, options) {
options = options || {};
return toSvg(domNode, options)
.then(util.makeImage)
.then(function (image) {
const scale = typeof options.scale !== 'number' ? 1 : options.scale;
const canvas = newCanvas(domNode, scale);
const ctx = canvas.getContext('2d');
ctx.msImageSmoothingEnabled = false;
ctx.imageSmoothingEnabled = false;
if (image) {
ctx.scale(scale, scale);
ctx.drawImage(image, 0, 0);
}
return canvas;
});
function newCanvas(node, scale) {
let width = options.width || util.width(node);
let height = options.height || util.height(node);
// per https://www.w3.org/TR/CSS2/visudet.html#inline-replaced-width the default width should be 300px if height
// not set, otherwise should be 2:1 aspect ratio for whatever height is specified
if (util.isDimensionMissing(width)) {
width = util.isDimensionMissing(height) ? 300 : height * 2.0;
}
if (util.isDimensionMissing(height)) {
height = width / 2.0;
}
const canvas = document.createElement('canvas');
canvas.width = width * scale;
canvas.height = height * scale;
if (options.bgcolor) {
const ctx = canvas.getContext('2d');
ctx.fillStyle = options.bgcolor;
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
return canvas;
}
}
let sandbox = null;
function cloneNode(node, options, parentComputedStyles, ownerWindow) {
const filter = options.filter;
if (
node === sandbox ||
util.isHTMLScriptElement(node) ||
util.isHTMLStyleElement(node) ||
util.isHTMLLinkElement(node) ||
(parentComputedStyles !== null && filter && !filter(node))
) {
return Promise.resolve();
}
return Promise.resolve(node)
.then(makeNodeCopy)
.then(function (clone) {
return cloneChildren(clone, getParentOfChildren(node));
})
.then(function (clone) {
return processClone(clone, node);
});
function makeNodeCopy(original) {
if (util.isHTMLCanvasElement(original)) {
return util.makeImage(original.toDataURL());
}
return original.cloneNode(false);
}
function getParentOfChildren(original) {
if (util.isElementHostForOpenShadowRoot(original)) {
return original.shadowRoot; // jump "down" to #shadow-root
}
return original;
}
function cloneChildren(clone, original) {
const originalChildren = getRenderedChildren(original);
let done = Promise.resolve();
if (originalChildren.length !== 0) {
const originalComputedStyles = getComputedStyle(
getRenderedParent(original)
);
util.asArray(originalChildren).forEach(function (originalChild) {
done = done.then(function () {
return cloneNode(
originalChild,
options,
originalComputedStyles,
ownerWindow
).then(function (clonedChild) {
if (clonedChild) {
clone.appendChild(clonedChild);
}
});
});
});
}
return done.then(function () {
return clone;
});
function getRenderedParent(original) {
if (util.isShadowRoot(original)) {
return original.host; // jump up from #shadow-root to its parent <element>
}
return original;
}
function getRenderedChildren(original) {
if (util.isShadowSlotElement(original)) {
return original.assignedNodes(); // shadow DOM <slot> has "assigned nodes" as rendered children
}
return original.childNodes;
}
}
function processClone(clone, original) {
if (!util.isElement(clone) || util.isShadowSlotElement(original)) {
return Promise.resolve(clone);
}
return Promise.resolve()
.then(cloneStyle)
.then(clonePseudoElements)
.then(copyUserInput)
.then(fixSvg)
.then(function () {
return clone;
});
function cloneStyle() {
copyStyle(original, clone);
function copyFont(source, target) {
target.font = source.font;
target.fontFamily = source.fontFamily;
target.fontFeatureSettings = source.fontFeatureSettings;
target.fontKerning = source.fontKerning;
target.fontSize = source.fontSize;
target.fontStretch = source.fontStretch;
target.fontStyle = source.fontStyle;
target.fontVariant = source.fontVariant;
target.fontVariantCaps = source.fontVariantCaps;
target.fontVariantEastAsian = source.fontVariantEastAsian;
target.fontVariantLigatures = source.fontVariantLigatures;
target.fontVariantNumeric = source.fontVariantNumeric;
target.fontVariationSettings = source.fontVariationSettings;
target.fontWeight = source.fontWeight;
}
function copyStyle(sourceElement, targetElement) {
const sourceComputedStyles = getComputedStyle(sourceElement);
if (sourceComputedStyles.cssText) {
targetElement.style.cssText = sourceComputedStyles.cssText;
copyFont(sourceComputedStyles, targetElement.style); // here we re-assign the font props.
} else {
copyUserComputedStyleFast(
options,
sourceElement,
sourceComputedStyles,
parentComputedStyles,
targetElement
);
// Remove positioning of initial element, which stops them from being captured correctly
if (parentComputedStyles === null) {
[
'inset-block',
'inset-block-start',
'inset-block-end',
].forEach((prop) => targetElement.style.removeProperty(prop));
['left', 'right', 'top', 'bottom'].forEach((prop) => {
if (targetElement.style.getPropertyValue(prop)) {
targetElement.style.setProperty(prop, '0px');
}
});
}
}
}
}
function clonePseudoElements() {
const cloneClassName = util.uid();
[':before', ':after'].forEach(function (element) {
clonePseudoElement(element);
});
function clonePseudoElement(element) {
const style = getComputedStyle(original, element);
const content = style.getPropertyValue('content');
if (content === '' || content === 'none') {
return;
}
const currentClass = clone.getAttribute('class') || '';
clone.setAttribute('class', `${currentClass} ${cloneClassName}`);
const styleElement = document.createElement('style');
styleElement.appendChild(formatPseudoElementStyle());
clone.appendChild(styleElement);
function formatPseudoElementStyle() {
const selector = `.${cloneClassName}:${element}`;
const cssText = style.cssText
? formatCssText()
: formatCssProperties();
return document.createTextNode(`${selector}{${cssText}}`);
function formatCssText() {
return `${style.cssText} content: ${content};`;
}
function formatCssProperties() {
const styleText = util
.asArray(style)
.map(formatProperty)
.join('; ');
return `${styleText};`;
function formatProperty(name) {
const propertyValue = style.getPropertyValue(name);
const propertyPriority = style.getPropertyPriority(name)
? ' !important'
: '';
return `${name}: ${propertyValue}${propertyPriority}`;
}
}
}
}
}
function copyUserInput() {
if (util.isHTMLTextAreaElement(original)) {
clone.innerHTML = original.value;
}
if (util.isHTMLInputElement(original)) {
clone.setAttribute('value', original.value);
}
}
function fixSvg() {
if (util.isSVGElement(clone)) {
clone.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
if (util.isSVGRectElement(clone)) {
['width', 'height'].forEach(function (attribute) {
const value = clone.getAttribute(attribute);
if (value) {
clone.style.setProperty(attribute, value);
}
});
}
}
}
}
}
function embedFonts(node) {
return fontFaces.resolveAll().then(function (cssText) {
if (cssText !== '') {
const styleNode = document.createElement('style');
node.appendChild(styleNode);
styleNode.appendChild(document.createTextNode(cssText));
}
return node;
});
}
function inlineImages(node) {
return images.inlineAll(node).then(function () {
return node;
});
}
function newUtil() {
let uid_index = 0;
return {
escape: escapeRegEx,
isDataUrl: isDataUrl,
canvasToBlob: canvasToBlob,
resolveUrl: resolveUrl,
getAndEncode: getAndEncode,
uid: uid,
delay: delay,
asArray: asArray,
escapeXhtml: escapeXhtml,
makeImage: makeImage,
width: width,
height: height,
getWindow: getWindow,
isElement: isElement,
isElementHostForOpenShadowRoot: isElementHostForOpenShadowRoot,
isShadowRoot: isShadowRoot,
isInShadowRoot: isInShadowRoot,
isHTMLElement: isHTMLElement,
isHTMLCanvasElement: isHTMLCanvasElement,
isHTMLInputElement: isHTMLInputElement,
isHTMLImageElement: isHTMLImageElement,
isHTMLLinkElement: isHTMLLinkElement,
isHTMLScriptElement: isHTMLScriptElement,
isHTMLStyleElement: isHTMLStyleElement,
isHTMLTextAreaElement: isHTMLTextAreaElement,
isShadowSlotElement: isShadowSlotElement,
isSVGElement: isSVGElement,
isSVGRectElement: isSVGRectElement,
isDimensionMissing: isDimensionMissing,
};
function getWindow(node) {
const ownerDocument = node ? node.ownerDocument : undefined;
return (
(ownerDocument ? ownerDocument.defaultView : undefined) ||
global ||
window
);
}
function isElementHostForOpenShadowRoot(value) {
return isElement(value) && value.shadowRoot !== null;
}
function isShadowRoot(value) {
return value instanceof getWindow(value).ShadowRoot;
}
function isInShadowRoot(value) {
return (
value !== null &&
Object.prototype.hasOwnProperty.call(value, 'getRootNode') &&
isShadowRoot(value.getRootNode())
);
}
function isElement(value) {
return value instanceof getWindow(value).Element;
}
function isHTMLCanvasElement(value) {
return value instanceof getWindow(value).HTMLCanvasElement;
}
function isHTMLElement(value) {
return value instanceof getWindow(value).HTMLElement;
}
function isHTMLImageElement(value) {
return value instanceof getWindow(value).HTMLImageElement;
}
function isHTMLInputElement(value) {
return value instanceof getWindow(value).HTMLInputElement;
}
function isHTMLLinkElement(value) {
return value instanceof getWindow(value).HTMLLinkElement;
}
function isHTMLScriptElement(value) {
return value instanceof getWindow(value).HTMLScriptElement;
}
function isHTMLStyleElement(value) {
return value instanceof getWindow(value).HTMLStyleElement;
}
function isHTMLTextAreaElement(value) {
return value instanceof getWindow(value).HTMLTextAreaElement;
}
function isShadowSlotElement(value) {
return (
isInShadowRoot(value) && value instanceof getWindow(value).HTMLSlotElement
);
}
function isSVGElement(value) {
return value instanceof getWindow(value).SVGElement;
}
function isSVGRectElement(value) {
return value instanceof getWindow(value).SVGRectElement;
}
function isDataUrl(url) {
return url.search(/^(data:)/) !== -1;
}
function isDimensionMissing(value) {
return isNaN(value) || value <= 0;
}
function asBlob(canvas) {
return new Promise(function (resolve) {
const binaryString = atob(canvas.toDataURL().split(',')[1]);
const length = binaryString.length;
const binaryArray = new Uint8Array(length);
for (let i = 0; i < length; i++) {
binaryArray[i] = binaryString.charCodeAt(i);
}
resolve(
new Blob([binaryArray], {
type: 'image/png',
})
);
});
}
function canvasToBlob(canvas) {
if (canvas.toBlob) {
return new Promise(function (resolve) {
canvas.toBlob(resolve);
});
}
return asBlob(canvas);
}
function resolveUrl(url, baseUrl) {
const doc = document.implementation.createHTMLDocument();
const base = doc.createElement('base');
doc.head.appendChild(base);
const a = doc.createElement('a');
doc.body.appendChild(a);
base.href = baseUrl;
a.href = url;
return a.href;
}
function uid() {
return `u${fourRandomChars()}${uid_index++}`;
function fourRandomChars() {
/* see https://stackoverflow.com/a/6248722/2519373 */
return `0000${((Math.random() * Math.pow(36, 4)) << 0).toString(
36
)}`.slice(-4);
}
}
function makeImage(uri) {
if (uri === 'data:,') {
return Promise.resolve();
}
return new Promise(function (resolve, reject) {
const image = new Image();
if (domtoimage.impl.options.useCredentials) {
image.crossOrigin = 'use-credentials';
}
image.onload = function () {
if (window && window.requestAnimationFrame) {
// In order to work around a Firefox bug (webcompat/web-bugs#119834) we
// need to wait one extra frame before it's safe to read the image data.
window.requestAnimationFrame(function () {
resolve(image);
});
} else {
// If we don't have a window or requestAnimationFrame function proceed immediately.
resolve(image);
}
};
image.onerror = reject;
image.src = uri;
});
}
function getAndEncode(url) {
let cacheEntry = domtoimage.impl.urlCache.find(function (el) {
return el.url === url;
});
if (!cacheEntry) {
cacheEntry = {
url: url,
promise: null,
};
domtoimage.impl.urlCache.push(cacheEntry);
}
if (cacheEntry.promise === null) {
if (domtoimage.impl.options.cacheBust) {
// Cache bypass so we dont have CORS issues with cached images
// Source: https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Bypassing_the_cache
url += (/\?/.test(url) ? '&' : '?') + new Date().getTime();
}
cacheEntry.promise = new Promise(function (resolve) {
const httpTimeout = domtoimage.impl.options.httpTimeout;
const request = new XMLHttpRequest();
request.onreadystatechange = done;
request.ontimeout = timeout;
request.responseType = 'blob';
request.timeout = httpTimeout;
if (domtoimage.impl.options.useCredentials) {
request.withCredentials = true;
}
request.open('GET', url, true);
request.send();
let placeholder;
if (domtoimage.impl.options.imagePlaceholder) {
const split = domtoimage.impl.options.imagePlaceholder.split(/,/);
if (split && split[1]) {
placeholder = split[1];
}
}
function done() {
if (request.readyState !== 4) {
return;
}
if (request.status !== 200) {
if (placeholder) {
resolve(placeholder);
} else {
fail(
`cannot fetch resource: ${url}, status: ${request.status}`
);
}
return;
}
const encoder = new FileReader();
encoder.onloadend = function () {
resolve(encoder.result);
};
encoder.readAsDataURL(request.response);
}
function timeout() {
if (placeholder) {
resolve(placeholder);
} else {
fail(
`timeout of ${httpTimeout}ms occured while fetching resource: ${url}`
);
}
}
function fail(message) {
console.error(message);
resolve('');
}
});
}
return cacheEntry.promise;
}
function escapeRegEx(string) {
return string.replace(/([.*+?^${}()|[]\/\\])/g, '\\$1');
}
function delay(ms) {
return function (arg) {
return new Promise(function (resolve) {
setTimeout(function () {
resolve(arg);
}, ms);
});
};
}
function asArray(arrayLike) {
const array = [];
const length = arrayLike.length;
for (let i = 0; i < length; i++) {
array.push(arrayLike[i]);
}
return array;
}
function escapeXhtml(string) {
return string.replace(/%/g, '%25').replace(/#/g, '%23').replace(/\n/g, '%0A');
}
function width(node) {
const width = px(node, 'width');
if (!isNaN(width)) return width;
const leftBorder = px(node, 'border-left-width');
const rightBorder = px(node, 'border-right-width');
return node.scrollWidth + leftBorder + rightBorder;
}
function height(node) {
const height = px(node, 'height');
if (!isNaN(height)) return height;
const topBorder = px(node, 'border-top-width');
const bottomBorder = px(node, 'border-bottom-width');
return node.scrollHeight + topBorder + bottomBorder;
}
function px(node, styleProperty) {
if (node.nodeType === ELEMENT_NODE) {
let value = getComputedStyle(node).getPropertyValue(styleProperty);
if (value.slice(-2) === 'px') {
value = value.slice(0, -2);
return parseFloat(value);
}
}
return NaN;
}
}
function newInliner() {
const URL_REGEX = /url\(['"]?([^'"]+?)['"]?\)/g;
return {
inlineAll: inlineAll,
shouldProcess: shouldProcess,
impl: {
readUrls: readUrls,
inline: inline,
},
};
function shouldProcess(string) {
return string.search(URL_REGEX) !== -1;
}
function readUrls(string) {
const result = [];
let match;
while ((match = URL_REGEX.exec(string)) !== null) {
result.push(match[1]);
}
return result.filter(function (url) {
return !util.isDataUrl(url);
});
}
function inline(string, url, baseUrl, get) {
return Promise.resolve(url)
.then(function (urlValue) {
return baseUrl ? util.resolveUrl(urlValue, baseUrl) : urlValue;
})
.then(get || util.getAndEncode)
.then(function (dataUrl) {
return string.replace(urlAsRegex(url), `$1${dataUrl}$3`);
});
function urlAsRegex(urlValue) {
return new RegExp(
`(url\\(['"]?)(${util.escape(urlValue)})(['"]?\\))`,
'g'
);
}
}
function inlineAll(string, baseUrl, get) {
if (nothingToInline()) {
return Promise.resolve(string);
}
return Promise.resolve(string)
.then(readUrls)
.then(function (urls) {
let done = Promise.resolve(string);
urls.forEach(function (url) {
done = done.then(function (prefix) {
return inline(prefix, url, baseUrl, get);
});
});
return done;
});
function nothingToInline() {
return !shouldProcess(string);
}
}
}
function newFontFaces() {
return {
resolveAll: resolveAll,
impl: {
readAll: readAll,
},
};
function resolveAll() {
return readAll()
.then(function (webFonts) {
return Promise.all(
webFonts.map(function (webFont) {
return webFont.resolve();
})
);
})
.then(function (cssStrings) {
return cssStrings.join('\n');
});
}
function readAll() {
return Promise.resolve(util.asArray(document.styleSheets))
.then(getCssRules)