-
Notifications
You must be signed in to change notification settings - Fork 85
/
Copy pathbootstrap.js
1327 lines (1149 loc) · 37.2 KB
/
bootstrap.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
/**
* Copyright 2013 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
(function() {
var log_element = document.createElement('pre');
log_element.id = 'debug';
var log_element_parent = setInterval(function() {
if (log_element.parentNode == null && document.body != null) {
document.body.appendChild(log_element);
clearInterval(log_element_parent);
}
}, 100);
function log() {
var output = [];
for (var i = 0; i < arguments.length; i++) {
if (typeof arguments[i] === "function") {
arguments[i] = '' + arguments[i];
}
if (typeof arguments[i] === "string") {
var bits = arguments[i].replace(/\s*$/, '').split('\n');
if (bits.length > 5) {
bits.splice(3, bits.length-5, '...');
}
output.push(bits.join('\n'));
} else if (typeof arguments[i] === "object" && typeof arguments[i].name === "string") {
output.push('"'+arguments[i].name+'"');
} else {
output.push(JSON.stringify(arguments[i], undefined, 2));
}
output.push(' ');
}
log_element.appendChild(document.createTextNode(output.join('') + '\n'));
}
var thisScript = document.querySelector("script[src$='bootstrap.js']");
var coverageMode = Boolean(parent.window.__coverage__) || /coverage/.test(window.location.hash);
// Inherit these properties from the parent test-runner if any.
window.__resources__ = parent.window.__resources__ || {original: {}};
window.__coverage__ = parent.window.__coverage__;
function getSync(src) {
var xhr = new XMLHttpRequest();
xhr.open('GET', src, false);
xhr.send();
if (xhr.responseCode > 400) {
console.error('Error loading ' + src);
return '';
}
return xhr.responseText;
}
function loadScript(src, options) {
// Add changing parameter to prevent script caching.
options = options || {coverage: true};
if (window.__resources__[src]) {
document.write('<script type="text/javascript">eval(window.__resources__["'+src+'"]);</script>');
} else if (coverageMode && options.coverage) {
instrument(src);
loadScript(src);
} else {
if (!inExploreMode()) {
src += '?' + getCacheBuster();
}
document.write('<script type="text/javascript" src="'+ src + '"></script>');
}
}
function loadCSS(src) {
document.write('<link rel="stylesheet" type="text/css" href="' + src + '">');
}
function forEach(array, callback, thisObj) {
for (var i=0; i < array.length; i++) {
if (array.hasOwnProperty(i)) {
callback.call(thisObj, array[i], i, array);
}
}
}
function hasFlag(flag) {
return thisScript && thisScript.getAttribute(flag) !== null;
}
function testType() {
var p = location.pathname;
p = p.replace(/^disabled-/, '');
var match = /(auto|impl|manual|unit)-test[^\\\/]*$/.exec(p);
return match ? match[1]: 'unknown';
}
function inExploreMode() {
return '#explore' == window.location.hash || window.location.hash.length == 0;
}
/**
* Get a value for busting the cache. If we got given a cache buster, pass it
* along, otherwise generate a new one.
*/
var cacheBusterValue = '' + window.Date.now();
function getCacheBuster() {
if (window.location.search.length > 0)
cacheBusterValue = window.location.search.substr(1, window.location.search.length);
return cacheBusterValue;
}
var instrumentationDepsLoaded = false;
/**
* Instrument the source at {@code location} and store it in
* {@code window.__resources__[name]}.
*/
function instrument(src) {
if (__resources__[src]) {
return;
}
if (!instrumentationDepsLoaded) {
instrumentationDepsLoaded = true;
(function() {
eval(getSync('../coverage/esprima/esprima.js'));
eval(getSync('../coverage/escodegen/escodegen.browser.js'));
eval(getSync('../coverage/istanbul/lib/instrumenter.js'));
}).call(window);
}
var js = getSync(src);
window.__resources__.original[src] = js;
var inst = window.__resources__[src] = new Instrumenter().instrumentSync(js, src);
}
var svg_properties = {
cx: 1,
width: 1,
x: 1,
y: 1
};
var is_svg_attrib = function(property, target) {
return target.namespaceURI == 'http://www.w3.org/2000/svg' &&
property in svg_properties;
};
var svg_namespace_uri = 'http://www.w3.org/2000/svg';
window.test_features = (function() {
var style = document.createElement('style');
style.textContent = '' +
'dummyRuleForTesting {' +
'width: calc(0px);' +
'width: -webkit-calc(0px); }';
document.head.appendChild(style);
var transformCandidates = [
'transform',
'webkitTransform',
'msTransform'
];
var transformProperty = transformCandidates.filter(function(property) {
return property in style.sheet.cssRules[0].style;
})[0];
var calcFunction = style.sheet.cssRules[0].style.width.split('(')[0];
document.head.removeChild(style);
return {
transformProperty: transformProperty,
calcFunction: calcFunction
};
})();
/**
* Figure out a useful name for an element.
*
* @param {Element} element Element to get the name for.
*
* @private
*/
function _element_name(element) {
if (element.id) {
return element.tagName.toLowerCase() + '#' + element.id;
} else {
return 'An anonymous ' + element.tagName.toLowerCase();
}
}
/**
* Get the style for a given element.
*
* @param {Array.<Object.<string, string>>|Object.<string, string>} style
* Either;
* * A list of dictionaries, each node returned is checked against the
* associated dictionary, or
* * A single dictionary, each node returned is checked against the
* given dictionary.
* Each dictionary should be of the form {style_name: style_value}.
*
* @private
*/
function _assert_style_get(style, i) {
if (typeof style[i] === 'undefined') {
return style;
} else {
return style[i];
}
}
/**
* Extract all the informative parts of a string. Ignores spacing, punctuation
* and other random extra characters.
*/
function _extract_important(input) {
var re = /([-+]?[0-9]+\.?[0-9]*(?:[eE][-+]?[0-9]+)?)|[A-Za-z%]+/g;
var match;
var result = [];
while (match = re.exec(input)) {
var value = match[0];
if (typeof match[1] != "undefined") {
value = Number(match[1]);
}
result.push(value);
}
return result;
}
window.assert_styles_extract_important = _extract_important;
function AssertionError(message) {
this.message = message;
}
window.assert_styles_assertion_error = AssertionError;
/**
* Asserts that a string is in the array of expected only comparing the
* important parts. Ignores spacing, punctuation and other random extra
* characters.
*/
function _assert_important_in_array(actual, expected, message) {
var actual_array = _extract_important(actual);
var expected_array_array = [];
for (var i = 0; i < expected.length; i++) {
expected_array_array.push(_extract_important(expected[i]));
}
var errors = [];
for (var i = 0; i < expected_array_array.length; i++) {
var expected_array = expected_array_array[i];
var element_errors = [];
if (actual_array.length != expected_array.length) {
element_errors.push('Number of elements don\'t match');
}
for (var j = 0; j < expected_array.length; j++) {
var actual = actual_array[j];
var expected = expected_array[j];
try {
assert_equals(typeof actual, typeof expected);
if (typeof actual === 'number') {
if (Math.abs(actual) < 1e-10) {
actual = 0;
}
actual = '' + actual.toPrecision(4);
}
if (typeof expected === 'number') {
if (Math.abs(expected) < 1e-10) {
expected = 0;
}
expected = '' + expected.toPrecision(4);
}
assert_equals(actual, expected);
} catch (e) {
element_errors.push(
'Element ' + j + ' - ' + e.message);
}
}
if (element_errors.length == 0) {
return;
} else {
errors.push(
' Expectation ' + JSON.stringify(expected_array) + ' did not match\n' +
' ' + element_errors.join('\n '));
}
}
if (expected_array_array.length > 1)
errors.unshift(' ' + expected_array_array.length + ' possible expectations');
errors.unshift(' Actual - ' + JSON.stringify(actual_array));
if (typeof message !== 'undefined') {
errors.unshift(message);
}
throw new AssertionError(errors.join('\n'));
}
window.assert_styles_assert_important_in_array = _assert_important_in_array;
/**
* Optionally sets and then gets a property value from a given element.
*
* @param {String} name The name of the property to get
* @param {Element} element DOM node to get the property from
* @param {Object} value DOM node to get the property from
*
* @private
*/
function _set_get_property(name, element, value) {
var set = typeof value != "undefined";
// ctm is special
if (name == 'ctm') {
if (set) {
var values = _extract_important(value);
var s = "matrix(" + values[0] + "," + values[1] + "," + values[2] + "," + values[3] + "," + values[4] + "," + values[5] + ")";
element.setAttribute("transform", s);
}
var ctm = element.getCTM();
return '{' + ctm.a + ', ' +
ctm.b + ', ' + ctm.c + ', ' + ctm.d + ', ' +
ctm.e + ', ' + ctm.f + '}';
}
if (is_svg_attrib(name, element)) {
if (set) {
element.setAttribute(name, value);
}
return element.attributes[name].value;
} else {
// Map transform to the browser specific value.
if (name == 'transform') {
name = test_features.transformProperty;
}
if (set) {
element.style[name] = "";
element.style[name] = value;
if (element.style[name] == "") {
return undefined;
}
}
return getComputedStyle(element, null).getPropertyValue(name);
}
}
/**
* asserts that actual has the same styles as the dictionary given by
* expected.
*
* @param {Element} object DOM node to check the styles on
* @param {Object.<string, string>} styles Dictionary of {style_name: style_value} to check
* on the object.
* @param {String} description Human readable description of what you are
* trying to check.
*
* @private
*/
function _assert_style_element(object, style, description) {
if (typeof message == 'undefined')
description = '';
// Create an element of the same type as testing so the style can be applied
// from the test. This is so the css property (not the -webkit-does-something
// tag) can be read.
var reference_element = (object.namespaceURI == svg_namespace_uri) ?
document.createElementNS(svg_namespace_uri, object.nodeName) :
document.createElement(object.nodeName);
var computedObjectStyle = getComputedStyle(object, null);
for (var i = 0; i < computedObjectStyle.length; i++) {
var property = computedObjectStyle[i];
reference_element.style.setProperty(property,
computedObjectStyle.getPropertyValue(property));
}
reference_element.style.position = 'absolute';
if (object.parentNode) {
object.parentNode.appendChild(reference_element);
}
try {
// Apply the style
for (var prop_name in style) {
// If the passed in value is an element then grab its current style for
// that property
var prop_values = [];
if (style[prop_name] instanceof HTMLElement ||
style[prop_name] instanceof SVGElement) {
prop_values.push(_set_get_property(prop_name, style[prop_name], undefined));
} else {
if (style[prop_name] instanceof Array) {
prop_values.push.apply(prop_values, style[prop_name]);
} else {
prop_values.push(style[prop_name]);
}
}
// Send all the values via getComputedStyle / SVGElement
var expected_prop_values = [];
var errors = [];
for (var i = 0; i < prop_values.length; i++) {
var reference_prop_value = _set_get_property(prop_name, reference_element, prop_values[i]);
if (typeof reference_prop_value != "undefined" && expected_prop_values.indexOf(reference_prop_value) < 0) {
expected_prop_values.push(reference_prop_value);
} else {
errors.push(' Unable to set value to "' + prop_values[i] + '"\n');
}
}
if (expected_prop_values.length == 0) {
throw new AssertionError(
'Tried to set the reference element\'s "' + prop_name + '"' +
' but all values where invalid:\n' + errors.join('\n'));
}
var actual = _set_get_property(prop_name, object, undefined);
_assert_important_in_array(actual, expected_prop_values, 'Checking '+ prop_name);
}
} finally {
if (reference_element.parentNode) {
reference_element.parentNode.removeChild(reference_element);
}
}
}
/**
* asserts that elements in the list have given styles.
*
* @param {Array.<Element>} objects List of DOM nodes to check the styles on
* @param {Array.<Object.<string, string>>|Object.<string, string>} style
* See _assert_style_get for information.
* @param {String} description Human readable description of what you are
* trying to check.
*
* @private
*/
function _assert_style_element_list(objects, style, description) {
var error = '';
forEach(objects, function(object, i) {
try {
_assert_style_element(
object, _assert_style_get(style, i),
description + ' ' + _element_name(object)
);
} catch (e) {
if (error) {
error += '; ';
}
error += 'Element ' + _element_name(object) + ' at index ' + i + ' failed ' + e.message + '\n';
}
});
if (error) {
throw error;
}
}
/**
* asserts that elements returned from a query selector have a list of styles.
*
* @param {string} qs A query selector to use to get the DOM nodes.
* @param {Array.<Object.<string, string>>|Object.<string, string>} style
* See _assert_style_get for information.
* @param {String} description Human readable description of what you are
* trying to check.
*
* @private
*/
function _assert_style_queryselector(qs, style, description) {
var objects = document.querySelectorAll(qs);
assert_true(objects.length > 0, description +
' is invalid, no elements match query selector: ' + qs);
_assert_style_element_list(objects, style, description);
}
/**
* asserts that elements returned from a query selector have a list of styles.
*
* Assert the element with id #hello is 100px wide;
* assert_styles(document.getElementById('hello'), {'width': '100px'})
* assert_styles('#hello'), {'width': '100px'})
*
* Assert all divs are 100px wide;
* assert_styles(document.getElementsByTagName('div'), {'width': '100px'})
* assert_styles('div', {'width': '100px'})
*
* Assert all objects with class 'red' are 100px wide;
* assert_styles(document.getElementsByClassName('red'), {'width': '100px'})
* assert_styles('.red', {'width': '100px'})
*
* Assert first div is 100px wide, second div is 200px wide;
* assert_styles(document.getElementsByTagName('div'),
* [{'width': '100px'}, {'width': '200px'}])
* assert_styles('div',
* [{'width': '100px'}, {'width': '200px'}])
*
* @param {string|Element|Array.<Element>} objects Either;
* * A query selector to use to get DOM nodes,
* * A DOM node.
* * A list of DOM nodes.
* @param {Array.<Object.<string, string>>|Object.<string, string>} style
* See _assert_style_get for information.
*/
function assert_styles(objects, style, description) {
switch (typeof objects) {
case 'string':
_assert_style_queryselector(objects, style, description);
break;
case 'object':
if (objects instanceof Array || objects instanceof NodeList) {
_assert_style_element_list(objects, style, description);
} else if (objects instanceof Element) {
_assert_style_element(objects, style, description);
} else {
throw new Error('Expected Array, NodeList or Element but got ' + objects);
}
break;
}
}
window.assert_styles = assert_styles;
/**
* Schedule something to be called at a given time.
*
* @constructor
* @param {number} millis Microseconds after start at which the callback should
* be called.
* @param {bool} autostart Auto something...
*/
function TestTimelineGroup(millis) {
this.millis = millis;
/**
* @type {bool}
*/
this.autorun_ = false;
/**
* @type {!Array.<function(): ?Object>}
*/
this.startCallbacks = null;
/**
* Callbacks which are added after the timeline has started. We clear them
* when going backwards.
*
* @type {?Array.<function(): ?Object>}
*/
this.lateCallbacks = null;
/**
* @type {Element}
*/
this.marker = document.createElement('img');
/**
* @type {Element}
*/
this.info = document.createElement('div');
this.setup_();
}
TestTimelineGroup.prototype.setup_ = function() {
this.endTime_ = 0;
this.startCallbacks = new Array();
this.lateCallbacks = null;
this.marker.innerHTML = '';
this.info.innerHTML = '';
};
/**
* Add a new callback to the event group
*
* @param {function(): ?Object} callback Callback given the currentTime of
* callback.
*/
TestTimelineGroup.prototype.add = function(callback) {
if (this.lateCallbacks === null) {
this.startCallbacks.unshift(callback);
} else {
this.lateCallbacks.unshift(callback);
}
// Trim out extra 'function() { ... }'
var callbackString = callback.name;
// FIXME: This should probably unindent too....
this.info.innerHTML += '<div>' + callbackString + '</div>';
};
/**
* Reset this event group to the state before start was called.
*/
TestTimelineGroup.prototype.reset = function() {
this.lateCallbacks = null;
var callbacks = this.startCallbacks.slice(0);
this.setup_();
while (callbacks.length > 0) {
var callback = callbacks.shift();
this.add(callback);
}
};
/**
* Tell the event group that the timeline has started and that any callbacks
* added from now are dynamically generated and hence should be cleared when a
* reset is called.
*/
TestTimelineGroup.prototype.start = function() {
this.lateCallbacks = new Array();
};
/**
* Call all the callbacks in the EventGroup.
*/
TestTimelineGroup.prototype.call = function() {
var callbacks = (this.startCallbacks.slice(0)).concat(this.lateCallbacks);
var statuses = this.info.children;
var overallResult = true;
while (callbacks.length > 0) {
var callback = callbacks.pop();
var status_ = statuses[statuses.length - callbacks.length - 1];
if (typeof callback == 'function') {
log('TestTimelineGroup', 'calling function', callback);
try {
callback();
} catch (e) {
// On IE the only way to get the real stack is to do this
window.onerror(e.message, e.fileName, e.lineNumber, e);
// On other browsers we want to throw the error later
setTimeout(function () { throw e; }, 0);
}
} else {
log('TestTimelineGroup', 'calling test', callback);
var result = callback.step(callback.f);
callback.done();
}
if (result === undefined || result == null) {
overallResult = overallResult && true;
status_.style.color = 'green';
} else {
overallResult = overallResult && false;
status_.style.color = 'red';
status_.innerHTML += '<div>' + result.toString() + '</div>';
}
}
if (overallResult) {
this.marker.src = '../img/success.png';
} else {
this.marker.src = '../img/error.png';
}
}
/**
* Draw the EventGroup's marker at the correct position on the timeline.
*
* FIXME(mithro): This mixes display and control :(
*
* @param {number} endTime The endtime of the timeline in millis. Used to
* display the marker at the right place on the timeline.
*/
TestTimelineGroup.prototype.draw = function(container, endTime) {
this.marker.title = this.millis + 'ms';
this.marker.className = 'marker';
this.marker.src = '../img/unknown.png';
var mleft = 'calc(100% - 10px)';
if (endTime != 0) {
mleft = 'calc(' + (this.millis / endTime) * 100.0 + '%' + ' - 10px)';
}
this.marker.style.left = mleft;
container.appendChild(this.marker);
this.info.className = 'info';
container.appendChild(this.info);
// Display details about the events at this time period when hovering over
// the marker.
this.marker.onmouseover = function() {
this.style.display = 'block';
}.bind(this.info);
this.marker.onmouseout = function() {
this.style.display = 'none';
}.bind(this.info);
var offset = Math.ceil(this.info.offsetWidth / 2);
var ileft = 'calc(100% - ' + offset + 'px)';
if (endTime != 0) {
ileft = 'calc(' + (this.millis / endTime) * 100.0 + '%' + ' - ' + offset +
'px)';
}
this.info.style.left = ileft;
this.info.style.display = 'none';
};
/**
* Moves the testharness_timeline in "real time".
* (IE 1 test second takes 1 real second).
*
* @constructor
*/
function RealtimeRunner(timeline) {
this.timeline = timeline;
// Capture the real requestAnimationFrame so we can run in 'real time' mode
// rather than as fast as possible.
var nativeRequestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame;
this.boundRequestAnimationFrame = function(f) {
nativeRequestAnimationFrame(f.bind(this))
};
this.now = window.Date.now;
this.zeroTime = null; // Time the page loaded
this.pauseStartTime = null; // Time at which we paused raf
this.timeDrift = 0; // Amount we have been stopped for
}
/**
* Callback called from nativeRequestAnimationFrame.
*
* @private
* @param {number} timestamp The current time for the animation frame
* (in millis).
*/
RealtimeRunner.prototype.animationFrame_ = function(timestamp) {
if (this.zeroTime === null) {
this.zeroTime = timestamp;
}
// Are we paused? Stop calling requestAnimationFrame.
if (this.pauseStartTime != null) {
return;
}
var virtualAnimationTime = timestamp - this.zeroTime - this.timeDrift;
var endTime = this.timeline.endTime_;
// If we have no events paste t=0, endTime is going to be zero. Instead
// make the test run for 2 minutes.
if (endTime == 0) {
endTime = 120e3;
}
// Do we still have time to go?
if (virtualAnimationTime < endTime) {
try {
this.timeline.setTime(virtualAnimationTime);
} finally {
this.boundRequestAnimationFrame(this.animationFrame_);
}
} else {
// Have we gone past endTime_? Force the harness to its endTime_.
this.timeline.setTime(endTime);
// Don't continue to raf
}
};
RealtimeRunner.prototype.start = function() {
if (this.pauseStartTime != null) {
this.timeDrift += (this.now() - this.pauseStartTime);
this.pauseStartTime = null;
}
this.boundRequestAnimationFrame(this.animationFrame_);
};
RealtimeRunner.prototype.pause = function() {
if (this.pauseStartTime != null) {
return;
}
this.pauseStartTime = this.now();
};
/**
* Class for storing events that happen during at given times (such as
* animation checks, or setTimeout).
*
* @constructor
*/
function TestTimeline(everyFrame) {
log('TestTimeline', 'constructor', everyFrame);
/**
* Stores the events which are upcoming.
*
* @type Object.<number, TestTimelineGroup>
* @private
*/
this.timeline_ = new Array();
this.everyFrame = everyFrame;
this.frameMillis = 1000.0 / 60; //60fps
this.currentTime_ = -this.frameMillis;
// Schedule an event at t=0, needed temporarily.
this.schedule(function() {}, 0);
this.reset();
this.runner_ = new RealtimeRunner(this);
}
/**
* Create the GUI controller for the timeline.
* @param {Element} body DOM element to add the GUI too, normally the <body>
* element.
*/
TestTimeline.prototype.createGUI = function(body) {
// HTML needed to create the timeline UI
this.div = document.createElement('div');
this.div.id = 'timeline';
this.timelinebar = document.createElement('div');
this.timelinebar.className = 'bar';
this.timelineprogress = document.createElement('div');
this.timelineprogress.className = 'progress';
this.timelinebar.appendChild(this.timelineprogress);
this.div.appendChild(this.timelinebar);
this.next = document.createElement('button');
this.next.innerText = '>';
this.next.id = 'next';
this.next.onclick = this.toNextEvent.bind(this);
this.div.appendChild(this.next);
this.prev = document.createElement('button');
this.prev.innerText = '<';
this.prev.id = 'prev';
this.prev.onclick = this.toPrevEvent.bind(this);
this.div.appendChild(this.prev);
this.control = document.createElement('button');
this.control.innerText = 'Pause';
this.control.id = 'control';
this.control.onclick = function() {
if (this.control.innerText == 'Go!') {
this.runner_.start();
this.control.innerText = 'Pause';
} else {
this.runner_.pause();
this.control.innerText = 'Go!';
}
}.bind(this);
this.div.appendChild(this.control);
body.appendChild(this.div);
}
/**
* Update GUI elements.
*
* @private
*/
TestTimeline.prototype.updateGUI = function () {
// Update the timeline
var width = "100%";
if (this.endTime_ != 0) {
width = (this.currentTime_ / this.endTime_) * 100.0 +'%'
}
this.timelineprogress.style.width = width;
this.timelinebar.title = (this.currentTime_).toFixed(0) + 'ms';
};
/**
* Sort the timeline into run order. Should be called after adding something to
* the timeline.
*
* @private
*/
TestTimeline.prototype.sort_ = function() {
this.timeline_.sort(function(a,b) {
return a.millis - b.millis;
});
};
/**
* Schedule something to be called at a given time.
*
* @param {function(number)} callback Callback to call after the number of millis
* have elapsed.
* @param {number} millis Milliseconds after start at which the callback should
* be called.
*/
TestTimeline.prototype.schedule = function(callback, millis) {
log('TestTimeline', 'schedule', millis, callback);
if (millis < this.currentTime_) {
// Can't schedule something in the past?
return;
}
// See if there is something at that time in the timeline already?
var timeline = this.timeline_.slice(0);
var group = null;
while (timeline.length > 0) {
if (timeline[0].millis == millis) {
group = timeline[0];
break;
} else {
timeline.shift();
}
}
// If not, create a node at that time.
if (group === null) {
group = new TestTimelineGroup(millis);
this.timeline_.unshift(group);
this.sort_();
}
group.add(callback);
var newEndTime = this.timeline_.slice(-1)[0].millis * 1.1;
if (this.endTime_ != newEndTime) {
this.endTime_ = newEndTime;
}
};
/**
* Return the current time in milliseconds.
*/
TestTimeline.prototype.now = function() {
log('TestTimeline', 'now', Math.max(this.currentTime_, 0));
return Math.max(this.currentTime_, 0);
};
/**
* Set the current time to a given value.
*
* @param {number} millis Time in milliseconds to set the current time too.
*/
TestTimeline.prototype.setTime = function(millis) {
log('TestTimeline', 'setTime', millis);
// Time is going backwards, we actually have to reset and go forwards as
// events can cause the creation of more events.
if (this.currentTime_ > millis) {
this.reset();
this.start();
}
var events = this.timeline_.slice(0);
// Already processed events
while (events.length > 0 && events[0].millis <= this.currentTime_) {
events.shift();
}
while (this.currentTime_ < millis) {
var event_ = null;
var moveTo = millis;
if (events.length > 0 && events[0].millis <= millis) {
event_ = events.shift();
moveTo = event_.millis;
}
// Call the callback
if (this.currentTime_ != moveTo) {
log('TestTimeline', 'setting time to', moveTo);
this.currentTime_ = moveTo;
this.animationFrame(this.currentTime_);
}
if (event_) {
event_.call();
}
}
this.updateGUI();