forked from facebook/yoga
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLayout-test-utils.js
607 lines (544 loc) · 17.6 KB
/
Layout-test-utils.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
/**
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
/* globals document, computeLayout, navigator */
var layoutTestUtils = (function() {
//
// Sets the test cases precision, by default set to 1.0, aka pixel precision
// (assuming the browser does pixel snapping - and that we're ok with being
// 'only' pixel perfect).
//
// Set it to '10' for .1 precision, etc... in theory the browser is doing
// 'pixel' snapping so 1.0 should do, the code is left for clarity...
//
// Set it to undefined to disable and use full precision.
//
var testMeasurePrecision = 1.0;
if (typeof jasmine !== 'undefined') {
jasmine.matchersUtil.buildFailureMessage = function() {
var args = Array.prototype.slice.call(arguments, 0);
var matcherName = args[0];
var isNot = args[1];
var actual = args[2];
var expected = args.slice(3);
var englishyPredicate = matcherName.replace(/[A-Z]/g, function(s) { return ' ' + s.toLowerCase(); });
var pp = function(node) {
return jasmine.pp(node)
.replace(/([\{\[]) /g, '$1')
.replace(/ ([\}\]:])/g, '$1');
};
var message = 'Expected ' +
pp(actual) +
(isNot ? ' not ' : ' ') +
'\n' +
englishyPredicate;
if (expected.length > 0) {
for (var i = 0; i < expected.length; i++) {
if (i > 0) {
message += ',';
}
message += ' ' + pp(expected[i]);
}
}
return message + '.';
};
}
var _cachedIframe;
function renderIframe() {
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
return iframe;
}
function getIframe(iframe) {
if (_cachedIframe) {
return _cachedIframe;
}
var doc = iframe.contentDocument;
if (doc.readyState === 'complete') {
var style = document.createElement('style');
style.textContent = (function() {/*
body, div {
box-sizing: border-box;
border: 0 solid black;
position: relative;
display: flex;
display: -webkit-flex;
flex-direction: column;
-webkit-flex-direction: column;
align-items: stretch;
-webkit-align-items: stretch;
justify-content: flex-start;
-webkit-justify-content: flex-start;
flex-shrink: 0;
-webkit-flex-shrink: 0;
margin: 0;
padding: 0;
min-width: 0;
}
hack to ignore three hundred px width of the body {}
body > div {
align-self: flex-start;
}
*/} + '').slice(15, -4);
doc.head.appendChild(style);
_cachedIframe = iframe;
return iframe;
} else {
setTimeout(getIframe.bind(null, iframe), 0);
}
}
if (typeof window !== 'undefined') {
var iframe = renderIframe();
getIframe(iframe);
}
if (typeof computeLayout === 'object') {
var fillNodes = computeLayout.fillNodes;
var realComputeLayout = computeLayout.computeLayout;
var canUseCachedMeasurement = computeLayout.canUseCachedMeasurement;
}
function extractNodes(node) {
var keysToCopy = [
'width',
'height',
'left',
'top'
];
var layout = {};
keysToCopy.forEach(function(key) {
layout[key] = node.layout[key];
});
if (node.children && node.children.length > 0) {
layout.children = node.children.map(extractNodes);
} else {
delete node.children;
}
delete node.layout;
return layout;
}
function roundLayout(layout) {
// Chrome rounds all the numbers with a precision of 1/64
// Reproduce the same behavior
function round(number) {
var floored = Math.floor(number);
var decimal = number - floored;
if (decimal === 0) {
return number;
}
var minDifference = Infinity;
var minDecimal = Infinity;
for (var i = 1; i < 64; ++i) {
var roundedDecimal = i / 64;
var difference = Math.abs(roundedDecimal - decimal);
if (difference < minDifference) {
minDifference = difference;
minDecimal = roundedDecimal;
}
}
return floored + minDecimal;
}
function rec(layout) {
layout.top = round(layout.top);
layout.left = round(layout.left);
layout.width = round(layout.width);
layout.height = round(layout.height);
if (layout.children) {
for (var i = 0; i < layout.children.length; ++i) {
rec(layout.children[i]);
}
}
}
rec(layout);
return layout;
}
function capitalizeFirst(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
function computeCSSLayout(rootNode) {
fillNodes(rootNode);
realComputeLayout(rootNode);
return roundLayout(extractNodes(rootNode));
}
function computeDOMLayout(node) {
var body = getIframe().contentDocument.body;
function setStyle(div, name, value) {
div.style['-webkit-' + name] = value;
div.style['webkit' + capitalizeFirst(name)] = value;
div.style[name] = value;
}
function transfer(div, node, name, ext) {
if (name in node.style) {
var value = node.style[name] + (ext || '');
setStyle(div, name, value);
}
}
function transferSpacing(div, node, type, suffix) {
transfer(div, node, type + suffix, 'px');
transfer(div, node, type + 'Left' + suffix, 'px');
transfer(div, node, type + 'Top' + suffix, 'px');
transfer(div, node, type + 'Bottom' + suffix, 'px');
transfer(div, node, type + 'Right' + suffix, 'px');
transfer(div, node, type + 'Start' + suffix, 'px');
transfer(div, node, type + 'End' + suffix, 'px');
}
function transferFlex(div, node) {
if ('flex' in node.style) {
var flex = node.style.flex;
var resolvedFlex = (
flex < 0 ? '0 1 auto' :
flex > 0 ? (flex + ' 0 0') :
'0 0 auto'
);
setStyle(div, 'flex', resolvedFlex);
}
}
function renderNode(parent, node) {
var div = document.createElement('div');
transfer(div, node, 'width', 'px');
transfer(div, node, 'height', 'px');
transfer(div, node, 'minWidth', 'px');
transfer(div, node, 'minHeight', 'px');
transfer(div, node, 'maxWidth', 'px');
transfer(div, node, 'maxHeight', 'px');
transfer(div, node, 'top', 'px');
transfer(div, node, 'left', 'px');
transfer(div, node, 'right', 'px');
transfer(div, node, 'bottom', 'px');
transferSpacing(div, node, 'margin', '');
transferSpacing(div, node, 'padding', '');
transferSpacing(div, node, 'border', 'Width');
transfer(div, node, 'flexDirection');
transfer(div, node, 'direction');
transferFlex(div, node);
transfer(div, node, 'flexWrap');
transfer(div, node, 'justifyContent');
transfer(div, node, 'alignSelf');
transfer(div, node, 'alignItems');
transfer(div, node, 'alignContent');
transfer(div, node, 'position');
transfer(div, node, 'overflow');
parent.appendChild(div);
(node.children || []).forEach(function(child) {
renderNode(div, child);
});
if (node.style.measure) {
div.innerText = node.style.measure.toString();
}
return div;
}
var div = renderNode(body, node);
function buildLayout(absoluteRect, div) {
var rect = div.getBoundingClientRect();
var result = {
width: rect.width,
height: rect.height,
top: rect.top - absoluteRect.top,
left: rect.left - absoluteRect.left
};
var children = [];
for (var child = div.firstChild; child; child = child.nextSibling) {
if (child.nodeType !== 3 /* textNode */) {
children.push(buildLayout(rect, child));
}
}
if (children.length) {
result.children = children;
}
return result;
}
var layout = buildLayout({left: 0, top: 0}, div);
body.removeChild(div);
return layout;
}
function inplaceRoundNumbersInObject(obj) {
if (!testMeasurePrecision) {
// undefined/0, disables rounding
return;
}
for (var key in obj) {
if (!obj.hasOwnProperty(key)) {
continue;
}
var val = obj[key];
if (typeof val === 'number') {
obj[key] = Math.floor((val * testMeasurePrecision) + 0.5) / testMeasurePrecision;
} else if (typeof val === 'object') {
inplaceRoundNumbersInObject(val);
}
}
}
function nameLayout(name, layout) {
var namedLayout = {name: name};
for (var key in layout) {
namedLayout[key] = layout[key];
}
return namedLayout;
}
function testFillNodes(node, filledNode) {
expect(fillNodes(node)).toEqual(filledNode);
}
function testExtractNodes(node, extractedNode) {
expect(extractNodes(node)).toEqual(extractedNode);
}
function testCanUseCachedMeasurement(canReuse, spec, cacheEntry) {
var availableWidth = spec.availableWidth;
var availableHeight = spec.availableHeight;
var widthMeasureMode = spec.widthMeasureMode;
var heightMeasureMode = spec.heightMeasureMode;
expect(
canUseCachedMeasurement(
availableWidth, availableHeight,
0, 0,
widthMeasureMode, heightMeasureMode,
cacheEntry
)
).toEqual(canReuse);
}
function testNamedLayout(name, layoutA, layoutB) {
expect(nameLayout(name, layoutA))
.toEqual(nameLayout(name, layoutB));
}
function isEqual(a, b) {
// computeCSSLayout and computeDOMLayout output a tree with same ordered elements
return JSON.stringify(a) === JSON.stringify(b);
}
function reduceTest(node) {
function isWorking() {
return isEqual(
computeDOMLayout(node),
computeCSSLayout(node)
);
}
if (isWorking()) {
return node;
}
var isModified = true;
function rec(node) {
var key;
var value;
// Style
for (key in node.style) {
value = node.style[key];
delete node.style[key];
if (isWorking()) {
node.style[key] = value;
} else {
isModified = true;
}
}
// Round values
for (key in node.style) {
value = node.style[key];
if (value > 100) {
node.style[key] = Math.round(value / 100) * 100;
} else if (value > 10) {
node.style[key] = Math.round(value / 10) * 10;
} else if (value > 1) {
node.style[key] = 5;
}
if (node.style[key] !== value) {
if (isWorking()) {
node.style[key] = value;
} else {
isModified = true;
}
}
}
// Children
for (var i = 0; node.children && i < node.children.length; ++i) {
value = node.children[i];
node.children.splice(i, 1);
if (isWorking()) {
if (!node.children) {
node.children = [];
}
node.children.splice(i, 0, value);
rec(node.children[i]);
} else {
i--;
isModified = true;
}
}
}
while (isModified) {
isModified = false;
rec(node);
}
return node;
}
var iframeText;
function measureTextSizes(text, width) {
iframeText = iframeText || document.createElement('iframe');
document.body.appendChild(iframeText);
var body = iframeText.contentDocument.body;
if (width === undefined || isNaN(width)) {
width = Infinity;
}
var div = document.createElement('div');
div.style.width = (width === Infinity ? 10000000 : width) + 'px';
div.style.display = 'flex';
div.style.flexDirection = 'column';
div.style.alignItems = 'flex-start';
div.style.alignContent = 'flex-start';
var span = document.createElement('span');
span.style.display = 'flex';
span.style.flexDirection = 'column';
span.style.alignItems = 'flex-start';
span.style.alignContent = 'flex-start';
span.innerText = text;
div.appendChild(span);
body.appendChild(div);
var rect = span.getBoundingClientRect();
body.removeChild(div);
return {
width: rect.width,
height: rect.height
};
}
var texts = {
small: 'small',
big: 'loooooooooong with space'
};
var preDefinedTextSizes = {
smallWidth: 34.671875,
smallHeight: 18,
bigWidth: 172.421875,
bigHeight: 36,
bigMinWidth: 100.4375
};
// Note(prenaux): Clearly not what I would like, but it seems to be the only
// way :( My guess is that since the font on Windows is
// different than on OSX it has a different size.
if (typeof navigator !== 'undefined' && navigator.userAgent.indexOf('Windows NT') > -1) {
preDefinedTextSizes.bigHeight = 36;
}
var textSizes;
if (typeof require === 'function') {
textSizes = preDefinedTextSizes;
} else {
textSizes = {
smallWidth: measureTextSizes(texts.small, 0).width,
smallHeight: measureTextSizes(texts.small, 0).height,
bigWidth: measureTextSizes(texts.big).width,
bigHeight: measureTextSizes(texts.big, 0).height,
bigMinWidth: measureTextSizes(texts.big, 0).width
};
}
// round the text sizes so that we dont have to update it for every browser
// update, assumes we're ok with pixel precision
inplaceRoundNumbersInObject(preDefinedTextSizes);
inplaceRoundNumbersInObject(textSizes);
return {
texts: texts,
textSizes: textSizes,
preDefinedTextSizes: preDefinedTextSizes,
testLayout: function(node, expectedLayout) {
var layout = computeCSSLayout(node);
var domLayout = computeDOMLayout(node);
inplaceRoundNumbersInObject(layout);
inplaceRoundNumbersInObject(domLayout);
inplaceRoundNumbersInObject(expectedLayout);
testNamedLayout('expected-dom', expectedLayout, domLayout);
testNamedLayout('layout-dom', layout, domLayout);
},
testLayoutAgainstDomOnly: function(node) {
var layout = computeCSSLayout(node);
var domLayout = computeDOMLayout(node);
inplaceRoundNumbersInObject(layout);
inplaceRoundNumbersInObject(domLayout);
testNamedLayout('layout-dom', layout, domLayout);
},
testLayoutAgainstExpectedOnly: function(node, expectedLayout) {
var layout = computeCSSLayout(node);
inplaceRoundNumbersInObject(layout);
inplaceRoundNumbersInObject(expectedLayout);
testNamedLayout('expected-dom', expectedLayout, layout);
},
testFillNodes: testFillNodes,
testExtractNodes: testExtractNodes,
testCanUseCachedMeasurement: testCanUseCachedMeasurement,
testRandomLayout: function(node) {
var layout = computeCSSLayout(node);
var domLayout = computeDOMLayout(node);
inplaceRoundNumbersInObject(layout);
inplaceRoundNumbersInObject(domLayout);
expect({node: node, layout: layout})
.toEqual({node: node, layout: domLayout});
},
testsFinished: function() {
console.log('tests finished!');
},
computeLayout: computeCSSLayout,
computeDOMLayout: computeDOMLayout,
reduceTest: reduceTest,
text: function(text) {
var fn = function(width, widthMode, height, heightMode) {
if (widthMode === 'undefined') {
width = Infinity;
}
// Constants for testing purposes between C/JS and other platforms
// Comment this block of code if you want to use the browser to
// generate proper sizes
if (text === texts.small) {
return {
width: Math.min(textSizes.smallWidth, width),
height: textSizes.smallWidth > width ? textSizes.bigHeight : textSizes.smallHeight
};
}
if (text === texts.big) {
return {
width: Math.min(textSizes.bigWidth, width),
height: textSizes.bigWidth > width ? textSizes.bigHeight : textSizes.smallHeight
};
}
};
// Name of the function is used in DOM tests as a text in the measured node
// and as a way to tell different measure functions apart in transpiled tests
fn.toString = function() { return text; };
return fn;
},
measureWithRatio2: function() {
var fn = function(width, widthMode, height, heightMode) {
if (widthMode === 'exactly') {
height = width * 2;
} else if (heightMode === 'exactly') {
width = height * 2;
} else if (widthMode === 'at-most') {
height = width * 2;
} else if (heightMode === 'at-most') {
width = height * 2;
} else {
// This should be Infinity, but it would be pain to transpile,
// so let's just go with big numbers.
height = 99999;
width = 99999;
}
return {width: width, height: height};
};
// This is necessary for transpiled tests, see previous comment
fn.toString = function() { return 'measureWithRatio2'; };
return fn;
},
measureWithMatchParent: function() {
var fn = function(width, widthMode, height, heightMode) {
if (widthMode === 'undefined') {
width = 99999;
}
if (heightMode === 'undefined') {
height = 99999;
}
return {width: width, height: height};
};
// This is necessary for transpiled tests, see previous comment
fn.toString = function() { return 'measureWithMatchParent'; };
return fn;
}
};
})();
if (typeof module !== 'undefined') {
module.exports = layoutTestUtils;
}