-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathScreenCapture.js
More file actions
1354 lines (1215 loc) · 48.7 KB
/
Copy pathScreenCapture.js
File metadata and controls
1354 lines (1215 loc) · 48.7 KB
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
import { isMobile, resizeImage } from './GleapHelper';
import { getFieldValueMask, getTextMask, isBlockedElement, isMaskMarker } from './GleapInputMasking';
import { isBlacklisted } from './ResourceExclusionList';
/**
* Captures the page as HTML for the screenshot renderer.
* @param {boolean} isLiveSite
* @param {object} privacyOptions The replay options (Gleap.setReplayOptions), so form fields are
* masked by the same rule as in replays.
*/
export const startScreenCapture = (isLiveSite, privacyOptions) => {
return prepareScreenshotData(isLiveSite, privacyOptions || {});
};
const documentToHTML = (clone) => {
var html = '';
var node = window.document.doctype;
if (node) {
html =
'<!DOCTYPE ' +
node.name +
(node.publicId ? ' PUBLIC "' + node.publicId + '"' : '') +
(!node.publicId && node.systemId ? ' SYSTEM' : '') +
(node.systemId ? ' "' + node.systemId + '"' : '') +
'>';
}
if (clone && clone.childNodes && clone.childNodes.length > 0) {
for (var i = 0; i < clone.childNodes.length; i++) {
if (clone.childNodes[i]) {
html += clone.childNodes[i].outerHTML;
}
}
}
return html;
};
const replaceAsync = (str, regex, asyncFn) => {
return new Promise((resolve, reject) => {
const promises = [];
str.replace(regex, (match, ...args) => {
const promise = asyncFn(match, ...args);
promises.push(promise);
});
Promise.all(promises)
.then((data) => {
resolve(str.replace(regex, () => data.shift()));
})
.catch(() => {
reject();
});
});
};
const loadCSSUrlResources = (data, basePath, remote) => {
return replaceAsync(
data,
/url\((.*?)\)/g,
(matchedData) =>
new Promise((resolve, reject) => {
if (!matchedData) {
return resolve(matchedData);
}
var matchedUrl = matchedData
.substr(4, matchedData.length - 5)
.replaceAll("'", '')
.replaceAll('"', '');
// Remote file or data
if (matchedUrl.indexOf('http') === 0 || matchedUrl.indexOf('//') === 0 || matchedUrl.indexOf('data') === 0) {
return resolve(matchedData);
}
try {
var resourcePath = matchedUrl;
if (basePath) {
resourcePath = new URL(matchedUrl, basePath + '/').href;
}
// Try to fetch external resource.
if (!remote) {
return fetchCSSResource(resourcePath).then((resourceData) => {
return resolve('url(' + resourceData + ')');
});
} else {
return resolve('url(' + resourcePath + ')');
}
} catch (exp) {
return resolve(matchedData);
}
})
);
};
const fetchCSSResource = (url) => {
return new Promise((resolve, reject) => {
if (url) {
var xhr = new XMLHttpRequest();
xhr.onload = function () {
var reader = new FileReader();
reader.onloadend = function () {
resolve(reader.result);
};
reader.onerror = function () {
reject();
};
reader.readAsDataURL(xhr.response);
};
xhr.onerror = function (err) {
resolve();
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
} else {
resolve();
}
});
};
const progressResource = (data, elem, resolve, reject) => {
resizeImage(data, 500, 500)
.then((data) => {
elem.src = data;
resolve();
})
.catch(() => {
console.warn('BB: Image resize failed.');
resolve();
});
};
const fetchItemResource = (elem) => {
return new Promise((resolve, reject) => {
if (elem && elem.src) {
if (isBlacklisted(elem.src)) {
return resolve();
}
var xhr = new XMLHttpRequest();
xhr.onload = function () {
var reader = new FileReader();
reader.onloadend = function () {
progressResource(reader.result, elem, resolve, reject);
};
reader.onerror = function () {
resolve();
};
reader.readAsDataURL(xhr.response);
};
xhr.onerror = function (err) {
resolve();
};
var url = elem.src;
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
} else {
resolve();
}
});
};
const downloadAllImages = (dom) => {
const imgItems = dom.querySelectorAll('img');
const imgItemsPromises = [];
for (var i = 0; i < imgItems.length; i++) {
const item = imgItems[i];
imgItemsPromises.push(fetchItemResource(item));
}
return Promise.all(imgItemsPromises);
};
const replaceStyleNodes = (clone, styleSheet, cssTextContent, styleId) => {
{
var cloneTargetNode = null;
if (styleSheet.ownerNode) {
cloneTargetNode = clone.querySelector('[bb-styleid="' + styleId + '"]');
}
try {
if (cloneTargetNode) {
var replacementNode = null;
if (cssTextContent != '') {
// Create node.
const head = clone.querySelector('head');
var styleNode = window.document.createElement('style');
head.appendChild(styleNode);
styleNode.type = 'text/css';
if (styleNode.styleSheet) {
styleNode.styleSheet.cssText = cssTextContent;
} else {
styleNode.appendChild(window.document.createTextNode(cssTextContent));
}
replacementNode = styleNode;
} else {
var linkNode = window.document.createElement('link');
linkNode.rel = 'stylesheet';
linkNode.type = styleSheet.type;
linkNode.href = styleSheet.href;
linkNode.media = styleSheet.media;
replacementNode = linkNode;
}
if (replacementNode) {
cloneTargetNode.parentNode.insertBefore(replacementNode, cloneTargetNode);
cloneTargetNode.remove();
}
}
} catch (exp) {}
}
};
const sanitizeCSSBraces = (css) => {
var result = '';
var depth = 0;
for (var i = 0; i < css.length; i++) {
if (css[i] === '{') {
depth++;
result += css[i];
} else if (css[i] === '}') {
if (depth > 0) {
depth--;
result += css[i];
}
// Skip stray closing braces at depth 0
} else {
result += css[i];
}
}
return result;
};
const getTextContentFromStyleSheet = (styleSheet) => {
var cssRules = null;
try {
if (styleSheet.cssRules) {
cssRules = styleSheet.cssRules;
} else if (styleSheet.rules) {
cssRules = styleSheet.rules;
}
} catch (exp) {}
var cssTextContent = '';
if (cssRules) {
for (var cssRuleItem in cssRules) {
if (cssRules[cssRuleItem].cssText) {
cssTextContent += cssRules[cssRuleItem].cssText + '\n';
}
}
}
return sanitizeCSSBraces(cssTextContent);
};
const downloadAllCSSUrlResources = (clone, remote) => {
var promises = [];
for (var i = 0; i < document.styleSheets.length; i++) {
const styleSheet = document.styleSheets[i];
// Skip if the stylesheet is meant for print
if (styleSheet.media && styleSheet.media.mediaText === 'print') {
continue;
}
const cssTextContent = getTextContentFromStyleSheet(styleSheet);
if (styleSheet && styleSheet.ownerNode) {
if (cssTextContent != '') {
// Resolve resources.
const baseTags = document.getElementsByTagName('base');
var basePathURL = baseTags.length
? baseTags[0].href.substr(location.origin.length, 999)
: window.location.href.split(/[?#]/)[0];
if (styleSheet.href) {
basePathURL = styleSheet.href;
}
const basePath = basePathURL.substring(0, basePathURL.lastIndexOf('/'));
promises.push(
loadCSSUrlResources(cssTextContent, basePath, remote).then((replacedStyle) => {
return {
styletext: replacedStyle,
stylesheet: styleSheet,
styleId: styleSheet.ownerNode.getAttribute('bb-styleid'),
};
})
);
} else {
promises.push(
Promise.resolve({
styletext: cssTextContent,
stylesheet: styleSheet,
styleId: styleSheet.ownerNode.getAttribute('bb-styleid'),
})
);
}
}
}
return Promise.all(promises).then((results) => {
if (results) {
for (var i = 0; i < results.length; i++) {
replaceStyleNodes(clone, results[i].stylesheet, results[i].styletext, results[i].styleId);
}
}
return true;
});
};
const prepareRemoteData = (clone, remote) => {
return new Promise((resolve, reject) => {
if (remote) {
// Always download CSS.
return downloadAllCSSUrlResources(clone, remote)
.then(() => {
resolve();
})
.catch(() => {
resolve();
});
} else {
return downloadAllImages(clone)
.then(() => {
return downloadAllCSSUrlResources(clone, remote).then(() => {
resolve();
});
})
.catch(() => {
console.warn('Gleap: Failed with resolving local resources. Please contact the Gleap support team.');
resolve();
});
}
});
};
const handleAdoptedStyleSheets = (doc, clone, shadowNodeId) => {
if (typeof doc.adoptedStyleSheets !== 'undefined') {
for (let i = 0; i < doc.adoptedStyleSheets.length; i++) {
const styleSheet = doc.adoptedStyleSheets[i];
const cssTextContent = getTextContentFromStyleSheet(styleSheet);
var shadowStyleNode = window.document.createElement('style');
shadowStyleNode.type = 'text/css';
if (shadowStyleNode.styleSheet) {
shadowStyleNode.styleSheet.cssText = cssTextContent;
} else {
shadowStyleNode.appendChild(window.document.createTextNode(cssTextContent));
}
if (shadowNodeId) {
shadowStyleNode.setAttribute('bb-shadow-child', shadowNodeId);
}
clone.insertBefore(shadowStyleNode, clone.firstElementChild);
}
}
};
// Element.getAnimations() has to flush pending style before it can answer, and a page with a
// running animation (a spinner, a pulsing dot) re-dirties style the moment it does — so asking
// per node made the clone walk force one full style recalc per element. That is quadratic in DOM
// size: ~2.8s at 6k elements, ~17.6s at 12k, minutes on a dashboard-sized page, all of it while
// the user waits for their report to send. Asking the ROOT instead answers the same question for
// every element under it in a single flush, so we resolve it once and index the result by target.
//
// One root is not enough: document.getAnimations() stops at shadow boundaries, so a web
// component's animations would silently drop out of the capture. Shadow roots expose the same
// call, and deepClone already discovers each one as it walks — so we index them as we go, which
// costs one flush per shadow ROOT rather than one per element.
const collectAnimationsInto = (animationsByTarget, root) => {
try {
if (!root || typeof root.getAnimations !== 'function') {
return animationsByTarget;
}
const animations = root.getAnimations();
for (var i = 0; i < animations.length; i++) {
const target = animations[i].effect && animations[i].effect.target;
if (!target) {
continue;
}
const existing = animationsByTarget.get(target);
if (existing) {
existing.push(animations[i]);
} else {
animationsByTarget.set(target, [animations[i]]);
}
}
} catch (exp) {}
return animationsByTarget;
};
const extractFinalCSSState = (element, animationsByTarget) => {
const animations = animationsByTarget.get(element);
if (!animations) {
return null;
}
const finalCSSState = {};
// One live computed-style object per element rather than one lookup per animated property.
const computedStyle = getComputedStyle(element);
animations.forEach((animation) => {
const keyframes = animation.effect?.getKeyframes() || [];
const finalKeyframe = keyframes[keyframes.length - 1] || {};
// Extract only the keys (CSS properties) from the final keyframe
Object.keys(finalKeyframe).forEach((property) => {
if (property !== 'offset') {
// Store the computed style for each animated property
finalCSSState[property] = computedStyle[property];
}
});
});
if (Object.keys(finalCSSState).length === 0) {
return null;
}
return JSON.stringify(finalCSSState);
};
// Computed values that decide where a box sits among its siblings, and how tall the line an inline
// box sits on is (overflow: whether its margins and floats stay inside it). A blocked element's
// placeholder copies them, because the inline styles, attributes and id selectors that may have set
// them do not reach the snapshot.
const PLACEHOLDER_LAYOUT_PROPERTIES = [
'position',
'top',
'right',
'bottom',
'left',
'float',
'clear',
'margin-top',
'margin-right',
'margin-bottom',
'margin-left',
'overflow-x',
'overflow-y',
'order',
'align-self',
'justify-self',
'grid-row-start',
'grid-row-end',
'grid-column-start',
'grid-column-end',
'vertical-align',
'font-family',
'font-size',
'line-height',
];
// Table parts made of the rows and cells of the table's grid, which size the cells around them.
const TABLE_PART_DISPLAY = /^table-(row-group|header-group|footer-group|row|column-group)$/;
// A table cell's box. With collapsed borders, a cell's box takes half of each border it shares, the
// widest of those on either side, so its size depends on its neighbours; its width and height,
// padding and borders make the same box again.
const CELL_BOX_PROPERTIES = [
'box-sizing',
'width',
'height',
'padding-top',
'padding-right',
'padding-bottom',
'padding-left',
'border-top-width',
'border-right-width',
'border-bottom-width',
'border-left-width',
'border-top-style',
'border-right-style',
'border-bottom-style',
'border-left-style',
];
const REPLACED_TAGS = /^(img|video|audio|canvas|iframe|embed|object|svg)$/;
const FORM_FIELD_TAGS = /^(input|select|textarea)$/;
const setImportant = (style, property, value) => style.setProperty(property, value, 'important');
const px = (style, property) => parseFloat(style.getPropertyValue(property)) || 0;
// A fixed border-box size, whatever the page's CSS says about min / max sizes or flex and grid
// sizing.
const pinSize = (style, width, height) => {
setImportant(style, 'box-sizing', 'border-box');
['width', 'min-width', 'max-width'].forEach((property) => setImportant(style, property, width + 'px'));
['height', 'min-height', 'max-height'].forEach((property) => setImportant(style, property, height + 'px'));
};
// Width is 'auto' where it does not apply: an inline box of text, not an image, a media element or a
// form field.
const isTextInline = (style) => style.display === 'inline' && style.width === 'auto';
const isOutOfFlow = (style) => style.position === 'absolute' || style.position === 'fixed' || style.float !== 'none';
const isScrollContainer = (style) => !/^(visible|clip)$/.test(style.overflowX) || !/^(visible|clip)$/.test(style.overflowY);
// The nodes an element's box is made of: a shadow host's shadow tree, the nodes assigned to a slot.
const flatChildNodes = (element) => {
if (element.shadowRoot) {
return Array.from(element.shadowRoot.childNodes);
}
const assigned = typeof element.assignedNodes === 'function' ? element.assignedNodes() : [];
return Array.from(assigned.length ? assigned : element.childNodes);
};
const flatParent = (node) => node.assignedSlot || node.parentElement || (node.parentNode && node.parentNode.host) || null;
// The box a node is laid out in: its parent's, or, past display: contents elements, an ancestor's.
const boxParent = (node) => {
let parent = flatParent(node);
while (parent && window.getComputedStyle(parent).display === 'contents') {
parent = flatParent(parent);
}
return parent;
};
const textRects = (text) => {
const range = document.createRange();
range.selectNodeContents(text);
return typeof range.getClientRects === 'function' ? Array.from(range.getClientRects()) : [];
};
// An element's border-box size in its own CSS pixels, from its used width and height.
// getBoundingClientRect() measures it on screen, where a transform or zoom on the element or an
// ancestor scales it, and the placeholder, rendered in the same place, would be scaled a second time.
// offsetWidth and offsetHeight are rounded to whole pixels, which can wrap a row of floats.
const layoutSize = (element, style) => {
let width = parseFloat(style.width);
let height = parseFloat(style.height);
if (isNaN(width) || isNaN(height)) {
const rect = element.getBoundingClientRect();
return { width: rect.width, height: rect.height };
}
if (style.boxSizing !== 'border-box') {
width +=
px(style, 'padding-left') +
px(style, 'padding-right') +
px(style, 'border-left-width') +
px(style, 'border-right-width');
height +=
px(style, 'padding-top') +
px(style, 'padding-bottom') +
px(style, 'border-top-width') +
px(style, 'border-bottom-width');
}
return { width, height };
};
// How much transforms and zoom scale a box on screen. Up to a pixel off is rounding.
const screenScale = (rect, size) => {
const ratio = (onScreen, layout) =>
onScreen > 0 && layout > 0 && Math.abs(onScreen - layout) > 1 ? onScreen / layout : 1;
return { x: ratio(rect.width, size.width), y: ratio(rect.height, size.height) };
};
// Line fragments, which only getClientRects() measures, are scaled on screen as much as the content of
// the nearest box around them.
const contentScale = (node) => {
for (let element = flatParent(node); element; element = flatParent(element)) {
const style = window.getComputedStyle(element);
if (parseFloat(style.width) > 0 && parseFloat(style.height) > 0) {
return screenScale(element.getBoundingClientRect(), layoutSize(element, style));
}
}
return { x: 1, y: 1 };
};
const inLayoutPixels = (rect, scale) => ({
left: rect.left / scale.x,
right: rect.right / scale.x,
top: rect.top / scale.y,
bottom: rect.bottom / scale.y,
width: rect.width / scale.x,
height: rect.height / scale.y,
});
const createSpacer = (ownerDocument) => {
const spacer = ownerDocument.createElement('span');
setImportant(spacer.style, 'display', 'inline-block');
['margin', 'padding', 'border-width'].forEach((property) => setImportant(spacer.style, property, '0'));
return spacer;
};
// The boxes inside an inline element that its line fragments do not cover: block boxes (a <div> in
// an <a>, or in the shadow tree of a web component), which sit between the fragments, and images,
// inline-blocks and form fields, which can make a line taller. Margin boxes, with vertical-align.
const collectInlineContent = (element, scale, content) => {
flatChildNodes(element).forEach((child) => {
if (child.nodeType !== Node.ELEMENT_NODE) {
return;
}
const style = window.getComputedStyle(child);
if (style.display === 'none' || isOutOfFlow(style)) {
return;
}
if (style.display === 'contents' || isTextInline(style)) {
collectInlineContent(child, scale, content);
return;
}
const rect = inLayoutPixels(child.getBoundingClientRect(), scale);
const box = {
left: rect.left - px(style, 'margin-left'),
right: rect.right + px(style, 'margin-right'),
top: rect.top - px(style, 'margin-top'),
bottom: rect.bottom + px(style, 'margin-bottom'),
verticalAlign: style.verticalAlign,
};
if (style.display.indexOf('inline') !== 0) {
content.blocks.push(box);
return;
}
// Its spacer is empty, so it sits on its bottom edge like an image. A box with text in it, a
// badge or a form field, sits on its text's baseline instead, which middle comes closest to.
if (box.verticalAlign === 'baseline' && !REPLACED_TAGS.test(child.localName)) {
box.verticalAlign = 'middle';
}
content.atomicInlines.push(box);
});
return content;
};
// An inline box of text wraps into one fragment per line. The placeholder gets an empty inline-block
// per fragment, as wide as the fragment, and a line break between fragments on different lines, so
// the text around it stays in place. A spacer has no height, which leaves the line as tall as the
// element's font makes it, unless an image, inline-block or form field made that line taller: then
// it takes the tallest one's height and vertical-align.
const appendLineSpacers = (placeholder, fragments, atomicInlines) => {
const middle = (box) => (box.top + box.bottom) / 2;
const tallestOnLine = [];
atomicInlines.forEach((box) => {
let line = 0;
for (let i = 1; i < fragments.length; i++) {
if (Math.abs(middle(fragments[i]) - middle(box)) < Math.abs(middle(fragments[line]) - middle(box))) {
line = i;
}
}
const tallest = tallestOnLine[line];
if (!tallest || box.bottom - box.top > tallest.bottom - tallest.top) {
tallestOnLine[line] = box;
}
});
for (let i = 0; i < fragments.length; i++) {
const previous = fragments[i - 1];
if (previous && fragments[i].top >= previous.top + previous.height / 2) {
placeholder.appendChild(placeholder.ownerDocument.createElement('br'));
}
const tallest = tallestOnLine[i];
const spacer = createSpacer(placeholder.ownerDocument);
setImportant(spacer.style, 'vertical-align', tallest ? tallest.verticalAlign : 'baseline');
pinSize(spacer.style, fragments[i].width, tallest ? tallest.bottom - tallest.top : 0);
placeholder.appendChild(spacer);
}
};
// Text in a display: contents element is laid out in its parent's lines, like an inline element of
// text.
const appendTextPlaceholder = (placeholder, text) => {
const rects = textRects(text);
if (!rects.length) {
return;
}
const scale = contentScale(text);
const box = placeholder.ownerDocument.createElement('span');
setImportant(box.style, 'display', 'inline');
['margin', 'padding', 'border-width'].forEach((property) => setImportant(box.style, property, '0'));
appendLineSpacers(
box,
rects.map((rect) => inLayoutPixels(rect, scale)),
[]
);
placeholder.appendChild(box);
};
// A display: contents element has no box: its children's boxes are laid out by its parent. The rows
// and cells of a table part make up the table's grid. Each of these boxes gets an inner placeholder of
// its own.
const appendInnerPlaceholders = (placeholder, node, isTableGrid) => {
flatChildNodes(node).forEach((child) => {
if (child.nodeType === Node.TEXT_NODE) {
appendTextPlaceholder(placeholder, child);
return;
}
if (child.nodeType !== Node.ELEMENT_NODE) {
return;
}
const display = window.getComputedStyle(child).display;
if (display === 'contents') {
appendInnerPlaceholders(placeholder, child, isTableGrid);
} else if (display !== 'none') {
placeholder.appendChild(createBlockedPlaceholder(child, placeholder.ownerDocument, true, isTableGrid));
}
});
};
// A block container whose first and last children's margins can collapse with its own: one that
// starts no formatting context of its own, as floats, absolutely positioned boxes, scroll containers
// and flow-roots do. Flex and grid items pass for one here; touchesEdge() tells them apart.
const collapsesWithChildren = (style) =>
(style.display === 'block' || style.display === 'list-item') &&
!isOutOfFlow(style) &&
!isScrollContainer(style) &&
!/layout|paint|strict|content/.test(style.contain);
// Whether a child's top (or bottom) border edge is where its parent's is, as it is when the child's
// margin collapses through the parent's edge. Compared in layout offsets, which transforms (a
// scroll-reveal animation, say) do not move; they are whole pixels, hence the tolerance.
const touchesEdge = (parent, child, childStyle, side) => {
if (!(child instanceof HTMLElement)) {
return false;
}
let parentTop = parent.offsetTop;
let parentBottom = parent.offsetTop + parent.offsetHeight;
if (child.offsetParent === parent) {
// Offsets from the parent's padding edge, which is its border edge on this side.
parentTop = 0;
parentBottom = parent.clientHeight;
} else if (child.offsetParent !== parent.offsetParent) {
return false;
}
// offsetTop includes a relatively positioned box's offset.
const top = child.offsetTop - (childStyle.position === 'relative' ? px(childStyle, 'top') : 0);
const distance = side === 'top' ? top - parentTop : top + child.offsetHeight - parentBottom;
return Math.abs(distance) <= 1;
};
// Text puts a line box between margins, unless it is white space that collapses away.
const rendersText = (text) => /[^\t\n\f\r ]/.test(text.data) || textRects(text).length > 0;
// The margins that collapse with an element's own top (or bottom) margin (CSS 2.1, 8.3.1): those of
// its first (or last) in-flow child, when no padding, border, line box or clearance separates them,
// and on through that child's children, and past empty children, whose own margins collapse too. They
// sit outside the element's box, where its placeholder, which has no children, has to carry them.
const addAdjoiningMargins = (element, style, side, margins) => {
margins.push(px(style, 'margin-' + side));
if (collapsesWithChildren(style) && !px(style, 'padding-' + side) && !px(style, 'border-' + side + '-width')) {
addEdgeChildMargins(element, flatChildNodes(element), side, margins);
}
return margins;
};
// Returns whether the margins continue past all of the children.
const addEdgeChildMargins = (parent, children, side, margins) => {
if (side === 'bottom') {
children.reverse();
}
for (let i = 0; i < children.length; i++) {
const child = children[i];
if (child.nodeType === Node.TEXT_NODE && rendersText(child)) {
return false;
}
if (child.nodeType !== Node.ELEMENT_NODE) {
continue;
}
const style = window.getComputedStyle(child);
if (style.display === 'none' || isOutOfFlow(style)) {
continue;
}
if (style.display === 'contents') {
if (!addEdgeChildMargins(parent, flatChildNodes(child), side, margins)) {
return false;
}
continue;
}
// Inline content makes a line box; clearance, or a formatting context of the parent's own, moves
// the child off the edge.
if (/^(inline|ruby)/.test(style.display) || !touchesEdge(parent, child, style, side)) {
return false;
}
addAdjoiningMargins(child, style, side, margins);
if (child.getBoundingClientRect().height !== 0 || !collapsesWithChildren(style)) {
return false;
}
addAdjoiningMargins(child, style, side === 'top' ? 'bottom' : 'top', margins);
}
return true;
};
// Adjoining margins collapse into the largest positive one plus the most negative one. The
// placeholder carries that sum, which collapses with a neighbour's margin as the margins did, unless
// they were of both signs.
const collapse = (margins) => Math.max(0, Math.max.apply(null, margins)) + Math.min(0, Math.min.apply(null, margins));
let fontMetricsContext = null;
const fontAscents = new Map();
// How far a font's line of text reaches above its baseline.
const fontAscent = (element) => {
const style = window.getComputedStyle(element);
const font = [style.fontStyle, style.fontWeight, style.fontSize, style.fontFamily].join(' ');
if (!fontAscents.has(font)) {
fontMetricsContext = fontMetricsContext || document.createElement('canvas').getContext('2d');
fontMetricsContext.font = font;
fontAscents.set(font, fontMetricsContext.measureText('').fontBoundingBoxAscent);
}
return fontAscents.get(font);
};
// The baseline of the first (or last) line of text in an element, or of an image on that line, on
// screen.
const edgeBaseline = (element, last, scale) => {
const children = flatChildNodes(element);
if (last) {
children.reverse();
}
for (let i = 0; i < children.length; i++) {
const child = children[i];
if (child.nodeType === Node.TEXT_NODE && /[^\t\n\f\r ]/.test(child.data)) {
const rects = textRects(child);
if (rects.length) {
const rect = rects[last ? rects.length - 1 : 0];
return rect.top + fontAscent(flatParent(child)) * scale.y;
}
} else if (child.nodeType === Node.ELEMENT_NODE) {
const style = window.getComputedStyle(child);
if (style.display === 'none' || isOutOfFlow(style)) {
continue;
}
if (REPLACED_TAGS.test(child.localName)) {
if (style.verticalAlign === 'baseline') {
return child.getBoundingClientRect().bottom + px(style, 'margin-bottom') * scale.y;
}
continue;
}
const baseline = edgeBaseline(child, last, scale);
if (baseline !== null) {
return baseline;
}
}
}
return null;
};
// Which line of text in it a box is aligned on, if on any: on a line of text (an inline-level box on
// the baseline, or a length or a subscript away from it), in a table row, or in a flex or grid line.
// It aligns its first line, an inline-block its last.
const baselineLine = (node, style) => {
if (style.display === 'table-cell') {
return style.verticalAlign === 'baseline' ? 'first' : null;
}
const parent = boxParent(node);
const parentStyle = parent && window.getComputedStyle(parent);
if (parentStyle && /flex|grid/.test(parentStyle.display) && !isOutOfFlow(style)) {
const align = /^(auto|normal)$/.test(style.alignSelf) ? parentStyle.alignItems : style.alignSelf;
return /baseline/.test(align) ? (/last/.test(align) ? 'last' : 'first') : null;
}
// The placeholder of an image or a form field, of the same tag, has its baseline where the element
// has: on its bottom edge, or on its own line of text.
if (
style.display.indexOf('inline-') !== 0 ||
/^(top|bottom|middle|text-top|text-bottom)$/.test(style.verticalAlign) ||
REPLACED_TAGS.test(node.localName) ||
FORM_FIELD_TAGS.test(node.localName)
) {
return null;
}
if (style.display === 'inline-block' && node.localName !== 'button') {
// A scroll container sits on its bottom edge, as the empty placeholder does.
return isScrollContainer(style) ? null : 'last';
}
return 'first';
};
// An empty box has no baseline and sits on its bottom edge. A spacer lowered so that the line it makes
// has its baseline where the element's is puts it back.
const appendBaselineSpacer = (placeholder, baseline, height) => {
setImportant(placeholder.style, 'font-size', '0');
setImportant(placeholder.style, 'line-height', '0');
const spacer = createSpacer(placeholder.ownerDocument);
setImportant(spacer.style, 'vertical-align', baseline - height + 'px');
pinSize(spacer.style, 0, height);
placeholder.appendChild(spacer);
};
// How many columns and rows a cell or column spans, and a list item's number, decide where the cells
// and items after it go. Taken from the element's properties, which are numbers whatever the
// attributes say.
const copyGridAttributes = (node, placeholder) => {
if (node instanceof HTMLTableCellElement) {
[
['colspan', 'colSpan'],
['rowspan', 'rowSpan'],
].forEach(([attribute, property]) => {
if (node.hasAttribute(attribute)) {
placeholder.setAttribute(attribute, node[property]);
}
});
} else if (node instanceof HTMLTableColElement && node.hasAttribute('span')) {
placeholder.setAttribute('span', node.span);
} else if (node instanceof HTMLLIElement && node.hasAttribute('value')) {
placeholder.setAttribute('value', node.value);
}
};
// A row or a cell inside a blocked table part is placed by the table's grid, styled by the page's CSS
// for its tag as the original was, and hidden with the part. A cell keeps its size, which sizes its
// column and row. The cells around it are placeholders too, with no text to align on: aligned on its
// baseline, an empty cell would sit on its bottom edge and could stretch the row. Plain declarations
// keep the placeholder of a long table short.
const placeGridPart = (placeholder, node, computedStyle) => {
if (computedStyle.display === 'table-cell') {
const style = placeholder.style;
style.setProperty('vertical-align', 'top');
CELL_BOX_PROPERTIES.forEach((property) => style.setProperty(property, computedStyle.getPropertyValue(property)));
} else if (TABLE_PART_DISPLAY.test(computedStyle.display)) {
appendInnerPlaceholders(placeholder, node, true);
}
};
// A box keeps its size, without its padding and border, which draw nothing, and with the margins of
// its children that collapse through its edges, and the baseline of its text.
const placeBox = (placeholder, node, computedStyle) => {
const style = placeholder.style;
const display = computedStyle.display;
const isCell = display === 'table-cell';
const size = layoutSize(node, computedStyle);
// An inline image or media element without a source is an empty inline box, which width and height
// do not apply to.
setImportant(style, 'display', display === 'inline' ? 'inline-block' : display);
if (isCell) {
CELL_BOX_PROPERTIES.forEach((property) => setImportant(style, property, computedStyle.getPropertyValue(property)));
} else {
pinSize(style, size.width, size.height);
setImportant(style, 'padding', '0');
setImportant(style, 'border-width', '0');
setImportant(style, 'margin-top', collapse(addAdjoiningMargins(node, computedStyle, 'top', [])) + 'px');
setImportant(style, 'margin-bottom', collapse(addAdjoiningMargins(node, computedStyle, 'bottom', [])) + 'px');
}
const line = baselineLine(node, computedStyle);
if (!line) {
return;
}
const rect = node.getBoundingClientRect();
// offsetHeight has a cell's share of collapsed borders.
const scale = screenScale(rect, { width: node.offsetWidth, height: node.offsetHeight });
const baseline = edgeBaseline(node, line === 'last', scale);
if (baseline === null || isNaN(baseline)) {
return;
}
const offset = (baseline - rect.top) / scale.y;
if (isCell) {
// The line starts at the top of its content box (clientTop is the border the cell has), and the
// row aligns it on its baseline.
const contentOffset = offset - node.clientTop - px(computedStyle, 'padding-top');
appendBaselineSpacer(placeholder, contentOffset, contentOffset);
} else {
// An inline-block's line is its baseline, whatever layout the element had. The spacer fills it,
// so a button, which centres its content, leaves the line where it is.
setImportant(style, 'display', 'inline-block');
appendBaselineSpacer(placeholder, offset, size.height);
}
};
// An inline element of text keeps its line fragments, as line spacers, unless it holds block boxes.
const placeInline = (placeholder, node) => {
const style = placeholder.style;
const scale = contentScale(node);
const content = collectInlineContent(node, scale, { blocks: [], atomicInlines: [] });
if (content.blocks.length) {
// Block boxes inside an inline element break its line, as a block placeholder does, and make up
// its height.
const area = content.blocks.reduce((union, box) => ({
left: Math.min(union.left, box.left),
right: Math.max(union.right, box.right),
top: Math.min(union.top, box.top),
bottom: Math.max(union.bottom, box.bottom),
}));
setImportant(style, 'display', 'block');
setImportant(style, 'margin-top', '0');
setImportant(style, 'margin-bottom', '0');
pinSize(style, area.right - area.left, area.bottom - area.top);
return;
}
setImportant(style, 'display', 'inline');
// The line fragments include the element's padding and border, and the ::before and ::after content
// in its lines, which its class would add to the placeholder a second time.
setImportant(style, 'padding', '0');
setImportant(style, 'border-width', '0');
const pseudoElements = ['before', 'after'].filter((pseudo) => {