summaryrefslogtreecommitdiff
path: root/dom/base/test/test_intersectionobservers.html
blob: e7875e3af0710a2cdbf5953f4c81c40dfc2ac43f (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
<!DOCTYPE HTML>
<html>
<!--
https://bugzilla.mozilla.org/show_bug.cgi?id=1243846

Some tests ported from IntersectionObserver/polyfill/intersection-observer-test.html

Original license header:

Copyright 2016 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.
-->
<head>
  <meta charset="utf-8">
  <title>Test for Bug 1243846</title>
  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
</head>
<body onload="next()">
<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=1243846">Mozilla Bug 1243846</a>
<p id="display"></p>
<pre id="test">
<script type="application/javascript">

  SpecialPowers.setIntPref("layout.visibility.min-notify-intersection-observers-interval-ms", 0);

  var tests = [];
  var curDescribeMsg = '';
  var curItMsg = '';

  function beforeEach_fn() { };
  function afterEach_fn() { };

  function before(fn) {
    fn();
  }

  function beforeEach(fn) {
    beforeEach_fn = fn;
  }

  function afterEach(fn) {
    afterEach_fn = fn;
  }

  function it(msg, fn) {
    tests.push({
      msg: `${msg} [${curDescribeMsg}]`,
      fn: fn
    });
  }

  var callbacks = [];
  function callDelayed(fn, delay) {
    callbacks.push({
      fn: fn,
      time: +new Date() + delay
    });
  }

  requestAnimationFrame(function tick() {
    var i = callbacks.length;
    while (i--) {
      var cb = callbacks[i];
      if (+new Date() >= cb.time) {
        SimpleTest.executeSoon(cb.fn);
        callbacks.splice(i, 1);
      }
    }
    requestAnimationFrame(tick);
  });

  function expect(val) {
    return {
      to: {
        throwException: function (regexp) {
          try {
            val();
            ok(false, `${curItMsg} - an exception should have beeen thrown`);
          } catch (e) {
            ok(regexp.test(e), `${curItMsg} - supplied regexp should match thrown exception`);
          }
        },
        get be() {
          var fn = function (expected) {
            is(val, expected, curItMsg);
          };
          fn.ok = function () {
            ok(val, curItMsg);
          };
          fn.greaterThan = function (other) {
            ok(val > other, `${curItMsg} - ${val} should be greater than ${other}`);
          };
          fn.lessThan = function (other) {
            ok(val < other, `${curItMsg} - ${val} should be less than ${other}`);
          };
          return fn;
        },
        eql: function (expected) {
          if (Array.isArray(expected)) {
            if (!Array.isArray(val)) {
              ok(false, curItMsg, `${curItMsg} - should be an array,`);
              return;
            }
            is(val.length, expected.length, curItMsg, `${curItMsg} - arrays should be the same length`);
            if (expected.length != val.length) {
              return;
            }
            for (var i = 0; i < expected.length; i++) {
              is(val[i], expected[i], `${curItMsg} - array elements at position ${i} should be equal`);
              if (expected[i] != val[i]) {
                return;
              }
            }
            ok(true);
          }
        },
      }
    }
  }

  function describe(msg, fn) {
    curDescribeMsg = msg;
    fn();
    curDescribeMsg = '';
  }

  function next() {
    var test = tests.shift();
    if (test) {
      console.log(test.msg);
      curItMsg = test.msg;
      var fn = test.fn;
      beforeEach_fn();
      if (fn.length) {
        fn(function () {
          afterEach_fn();
          next();
        });
      } else {
        fn();
        afterEach_fn();
        next();
      }
    } else {
      SimpleTest.finish();
    }
  }

  var sinon = {
    spy: function () {
      var callbacks = [];
      var fn = function () {
        fn.callCount++;
        fn.lastCall = { args: arguments };
        if (callbacks.length) {
          callbacks.shift()();
        }
      };
      fn.callCount = 0;
      fn.lastCall = { args: [] };
      fn.waitForNotification = (fn) => {
        callbacks.push(fn);
      };
      return fn;
    }
  };

  var ASYNC_TIMEOUT = 300;


  var io;
  var noop = function() {};


  // References to DOM elements, which are accessible to any test
  // and reset prior to each test so state isn't shared.
  var rootEl;
  var grandParentEl;
  var parentEl;
  var targetEl1;
  var targetEl2;
  var targetEl3;
  var targetEl4;
  var targetEl5;


  describe('IntersectionObserver', function() {

    before(function() {

    });


    beforeEach(function() {
      addStyles();
      addFixtures();
    });


    afterEach(function() {
      if (io && 'disconnect' in io) io.disconnect();
      io = null;

      window.onmessage = null;

      removeStyles();
      removeFixtures();
    });


    describe('constructor', function() {

      it('throws when callback is not a function', function() {
        expect(function() {
          io = new IntersectionObserver(null);
        }).to.throwException(/.*/i);
      });


      it('instantiates root correctly', function() {
        io = new IntersectionObserver(noop);
        expect(io.root).to.be(null);

        io = new IntersectionObserver(noop, {root: rootEl});
        expect(io.root).to.be(rootEl);
      });


      it('throws when root is not an Element', function() {
        expect(function() {
          io = new IntersectionObserver(noop, {root: 'foo'});
        }).to.throwException(/.*/i);
      });


      it('instantiates rootMargin correctly', function() {
        io = new IntersectionObserver(noop, {rootMargin: '10px'});
        expect(io.rootMargin).to.be('10px 10px 10px 10px');

        io = new IntersectionObserver(noop, {rootMargin: '10px -5%'});
        expect(io.rootMargin).to.be('10px -5% 10px -5%');

        io = new IntersectionObserver(noop, {rootMargin: '10px 20% 0px'});
        expect(io.rootMargin).to.be('10px 20% 0px 20%');

        io = new IntersectionObserver(noop, {rootMargin: '0px 0px -5% 5px'});
        expect(io.rootMargin).to.be('0px 0px -5% 5px');
      });


      it('throws when rootMargin is not in pixels or percent', function() {
        expect(function() {
          io = new IntersectionObserver(noop, {rootMargin: 'auto'});
        }).to.throwException(/pixels.*percent/i);
      });


      it('instantiates thresholds correctly', function() {
        io = new IntersectionObserver(noop);
        expect(io.thresholds).to.eql([0]);

        io = new IntersectionObserver(noop, {threshold: 0.5});
        expect(io.thresholds).to.eql([0.5]);

        io = new IntersectionObserver(noop, {threshold: [0.25, 0.5, 0.75]});
        expect(io.thresholds).to.eql([0.25, 0.5, 0.75]);

        io = new IntersectionObserver(noop, {threshold: [1, .5, 0]});
        expect(io.thresholds).to.eql([0, .5, 1]);
      });

      it('throws when a threshold value is not between 0 and 1', function() {
        expect(function() {
          io = new IntersectionObserver(noop, {threshold: [0, -1]});
        }).to.throwException(/threshold/i);
      });

      it('throws when a threshold value is not a number', function() {
        expect(function() {
          io = new IntersectionObserver(noop, {threshold: "foo"});
        }).to.throwException(/.*/i);
      });

    });


    describe('observe', function() {

      it('throws when target is not an Element', function() {
        expect(function() {
          io = new IntersectionObserver(noop);
          io.observe(null);
        }).to.throwException(/.*/i);
      });


      it('triggers if target intersects when observing begins', function(done) {
        io = new IntersectionObserver(function(records) {
          expect(records.length).to.be(1);
          expect(records[0].intersectionRatio).to.be(1);
          done();
        }, {root: rootEl});
        io.observe(targetEl1);
      });


      it('triggers with the correct arguments', function(done) {
        io = new IntersectionObserver(function(records, observer) {
          expect(records.length).to.be(1);
          expect(records[0] instanceof IntersectionObserverEntry).to.be.ok();
          expect(observer).to.be(io);
          expect(this).to.be(io);
          done();
        }, {root: rootEl});
        io.observe(targetEl1);
      });


      it('does not trigger if target does not intersect when observing begins',
          function(done) {

        var spy = sinon.spy();
        io = new IntersectionObserver(spy, {root: rootEl});

        targetEl2.style.top = '-40px';
        io.observe(targetEl2);
        callDelayed(function() {
          expect(spy.callCount).to.be(0);
          done();
        }, ASYNC_TIMEOUT);
      });


      it('does not trigger if target is not a descendant of the intersection root in the containing block chain',
          function(done) {

        var spy = sinon.spy();
        io = new IntersectionObserver(spy, {root: parentEl});

        parentEl.style.position = 'static';
        io.observe(targetEl2);
        callDelayed(function() {
          expect(spy.callCount).to.be(0);
          done();
        }, ASYNC_TIMEOUT);
      });

      it('triggers if target or root becomes invisible',
          function(done) {

        var spy = sinon.spy();
        io = new IntersectionObserver(spy, {root: rootEl});

        runSequence([
          function(done) {
            io.observe(targetEl1);
            spy.waitForNotification(function() {
              expect(spy.callCount).to.be(1);
              var records = sortRecords(spy.lastCall.args[0]);
              expect(records.length).to.be(1);
              expect(records[0].intersectionRatio).to.be(1);
              done();
            }, ASYNC_TIMEOUT);
          },
          function(done) {
            targetEl1.style.display = 'none';
            spy.waitForNotification(function() {
              expect(spy.callCount).to.be(2);
              var records = sortRecords(spy.lastCall.args[0]);
              expect(records.length).to.be(1);
              expect(records[0].intersectionRatio).to.be(0);
              done();
            }, ASYNC_TIMEOUT);
          },
          function(done) {
            targetEl1.style.display = 'block';
            spy.waitForNotification(function() {
              expect(spy.callCount).to.be(3);
              var records = sortRecords(spy.lastCall.args[0]);
              expect(records.length).to.be(1);
              expect(records[0].intersectionRatio).to.be(1);
              done();
            }, ASYNC_TIMEOUT);
          },
          function(done) {
            rootEl.style.display = 'none';
            spy.waitForNotification(function() {
              expect(spy.callCount).to.be(4);
              var records = sortRecords(spy.lastCall.args[0]);
              expect(records.length).to.be(1);
              expect(records[0].intersectionRatio).to.be(0);
              done();
            }, ASYNC_TIMEOUT);
          },
          function(done) {
            rootEl.style.display = 'block';
            spy.waitForNotification(function() {
              expect(spy.callCount).to.be(5);
              var records = sortRecords(spy.lastCall.args[0]);
              expect(records.length).to.be(1);
              expect(records[0].intersectionRatio).to.be(1);
              done();
            }, ASYNC_TIMEOUT);
          },
        ], done);
      });


      it('handles container elements with non-visible overflow',
          function(done) {

        var spy = sinon.spy();
        io = new IntersectionObserver(spy, {root: rootEl});

        runSequence([
          function(done) {
            io.observe(targetEl1);
            spy.waitForNotification(function() {
              expect(spy.callCount).to.be(1);
              var records = sortRecords(spy.lastCall.args[0]);
              expect(records.length).to.be(1);
              expect(records[0].intersectionRatio).to.be(1);
              done();
            }, ASYNC_TIMEOUT);
          },
          function(done) {
            targetEl1.style.left = '-40px';
            spy.waitForNotification(function() {
              expect(spy.callCount).to.be(2);
              var records = sortRecords(spy.lastCall.args[0]);
              expect(records.length).to.be(1);
              expect(records[0].intersectionRatio).to.be(0);
              done();
            }, ASYNC_TIMEOUT);
          },
          function(done) {
            parentEl.style.overflow = 'visible';
            spy.waitForNotification(function() {
              expect(spy.callCount).to.be(3);
              var records = sortRecords(spy.lastCall.args[0]);
              expect(records.length).to.be(1);
              expect(records[0].intersectionRatio).to.be(1);
              done();
            }, ASYNC_TIMEOUT);
          }
        ], done);
      });


      it('observes one target at a single threshold correctly', function(done) {

        var spy = sinon.spy();
        io = new IntersectionObserver(spy, {root: rootEl, threshold: 0.5});

        runSequence([
          function(done) {
            targetEl1.style.left = '-5px';
            io.observe(targetEl1);
            spy.waitForNotification(function() {
              expect(spy.callCount).to.be(1);
              var records = sortRecords(spy.lastCall.args[0]);
              expect(records.length).to.be(1);
              expect(records[0].intersectionRatio).to.be.greaterThan(0.5);
              done();
            }, ASYNC_TIMEOUT);
          },
          function(done) {
            targetEl1.style.left = '-15px';
            spy.waitForNotification(function() {
              expect(spy.callCount).to.be(2);
              var records = sortRecords(spy.lastCall.args[0]);
              expect(records.length).to.be(1);
              expect(records[0].intersectionRatio).to.be.lessThan(0.5);
              done();
            }, ASYNC_TIMEOUT);
          },
          function(done) {
            targetEl1.style.left = '-25px';
            callDelayed(function() {
              expect(spy.callCount).to.be(2);
              done();
            }, ASYNC_TIMEOUT);
          },
          function(done) {
            targetEl1.style.left = '-10px';
            spy.waitForNotification(function() {
              expect(spy.callCount).to.be(3);
              var records = sortRecords(spy.lastCall.args[0]);
              expect(records.length).to.be(1);
              expect(records[0].intersectionRatio).to.be(0.5);
              done();
            }, ASYNC_TIMEOUT);
          }
        ], done);

      });


      it('observes multiple targets at multiple thresholds correctly',
          function(done) {

        var spy = sinon.spy();
        io = new IntersectionObserver(spy, {
          root: rootEl,
          threshold: [1, 0.5, 0]
        });

        runSequence([
          function(done) {
            targetEl1.style.top = '0px';
            targetEl1.style.left = '-15px';
            targetEl2.style.top = '-5px';
            targetEl2.style.left = '0px';
            targetEl3.style.top = '0px';
            targetEl3.style.left = '205px';
            io.observe(targetEl1);
            io.observe(targetEl2);
            io.observe(targetEl3);
            spy.waitForNotification(function() {
              expect(spy.callCount).to.be(1);
              var records = sortRecords(spy.lastCall.args[0]);
              expect(records.length).to.be(2);
              expect(records[0].target).to.be(targetEl1);
              expect(records[0].intersectionRatio).to.be(0.25);
              expect(records[1].target).to.be(targetEl2);
              expect(records[1].intersectionRatio).to.be(0.75);
              done();
            }, ASYNC_TIMEOUT);
          },
          function(done) {
            targetEl1.style.top = '0px';
            targetEl1.style.left = '-5px';
            targetEl2.style.top = '-15px';
            targetEl2.style.left = '0px';
            targetEl3.style.top = '0px';
            targetEl3.style.left = '195px';
            spy.waitForNotification(function() {
              expect(spy.callCount).to.be(2);
              var records = sortRecords(spy.lastCall.args[0]);
              expect(records.length).to.be(3);
              expect(records[0].target).to.be(targetEl1);
              expect(records[0].intersectionRatio).to.be(0.75);
              expect(records[1].target).to.be(targetEl2);
              expect(records[1].intersectionRatio).to.be(0.25);
              expect(records[2].target).to.be(targetEl3);
              expect(records[2].intersectionRatio).to.be(0.25);
              done();
            }, ASYNC_TIMEOUT);
          },
          function(done) {
            targetEl1.style.top = '0px';
            targetEl1.style.left = '5px';
            targetEl2.style.top = '-25px';
            targetEl2.style.left = '0px';
            targetEl3.style.top = '0px';
            targetEl3.style.left = '185px';
            spy.waitForNotification(function() {
              expect(spy.callCount).to.be(3);
              var records = sortRecords(spy.lastCall.args[0]);
              expect(records.length).to.be(3);
              expect(records[0].target).to.be(targetEl1);
              expect(records[0].intersectionRatio).to.be(1);
              expect(records[1].target).to.be(targetEl2);
              expect(records[1].intersectionRatio).to.be(0);
              expect(records[2].target).to.be(targetEl3);
              expect(records[2].intersectionRatio).to.be(0.75);
              done();
            }, ASYNC_TIMEOUT);
          },
          function(done) {
            targetEl1.style.top = '0px';
            targetEl1.style.left = '15px';
            targetEl2.style.top = '-35px';
            targetEl2.style.left = '0px';
            targetEl3.style.top = '0px';
            targetEl3.style.left = '175px';
            spy.waitForNotification(function() {
              expect(spy.callCount).to.be(4);
              var records = sortRecords(spy.lastCall.args[0]);
              expect(records.length).to.be(1);
              expect(records[0].target).to.be(targetEl3);
              expect(records[0].intersectionRatio).to.be(1);
              done();
            }, ASYNC_TIMEOUT);
          }
        ], done);
      });


      it('handles rootMargin properly', function(done) {

        parentEl.style.overflow = 'visible';
        targetEl1.style.top = '0px';
        targetEl1.style.left = '-20px';
        targetEl2.style.top = '-20px';
        targetEl2.style.left = '0px';
        targetEl3.style.top = '0px';
        targetEl3.style.left = '200px';
        targetEl4.style.top = '180px';
        targetEl4.style.left = '180px';

        runSequence([
          function(done) {
            io = new IntersectionObserver(function(records) {
              records = sortRecords(records);
              expect(records.length).to.be(4);
              expect(records[0].target).to.be(targetEl1);
              expect(records[0].intersectionRatio).to.be(1);
              expect(records[1].target).to.be(targetEl2);
              expect(records[1].intersectionRatio).to.be(.5);
              expect(records[2].target).to.be(targetEl3);
              expect(records[2].intersectionRatio).to.be(.5);
              expect(records[3].target).to.be(targetEl4);
              expect(records[3].intersectionRatio).to.be(1);
              io.disconnect();
              done();
            }, {root: rootEl, rootMargin: '10px'});

            io.observe(targetEl1);
            io.observe(targetEl2);
            io.observe(targetEl3);
            io.observe(targetEl4);
          },
          function(done) {
            io = new IntersectionObserver(function(records) {
              records = sortRecords(records);
              expect(records.length).to.be(3);
              expect(records[0].target).to.be(targetEl1);
              expect(records[0].intersectionRatio).to.be(0.5);
              expect(records[1].target).to.be(targetEl3);
              expect(records[1].intersectionRatio).to.be(0.5);
              expect(records[2].target).to.be(targetEl4);
              expect(records[2].intersectionRatio).to.be(0.5);
              io.disconnect();
              done();
            }, {root: rootEl, rootMargin: '-10px 10%'});

            io.observe(targetEl1);
            io.observe(targetEl2);
            io.observe(targetEl3);
            io.observe(targetEl4);
          },
          function(done) {
            io = new IntersectionObserver(function(records) {
              records = sortRecords(records);
              expect(records.length).to.be(2);
              expect(records[0].target).to.be(targetEl1);
              expect(records[0].intersectionRatio).to.be(0.5);
              expect(records[1].target).to.be(targetEl4);
              expect(records[1].intersectionRatio).to.be(0.5);
              io.disconnect();
              done();
            }, {root: rootEl, rootMargin: '-5% -2.5% 0px'});

            io.observe(targetEl1);
            io.observe(targetEl2);
            io.observe(targetEl3);
            io.observe(targetEl4);
          },
          function(done) {
            io = new IntersectionObserver(function(records) {
              records = sortRecords(records);
              expect(records.length).to.be(3);
              expect(records[0].target).to.be(targetEl1);
              expect(records[0].intersectionRatio).to.be(0.5);
              expect(records[1].target).to.be(targetEl2);
              expect(records[1].intersectionRatio).to.be(0.5);
              expect(records[2].target).to.be(targetEl4);
              expect(records[2].intersectionRatio).to.be(0.25);
              io.disconnect();
              done();
            }, {root: rootEl, rootMargin: '5% -2.5% -10px -190px'});

            io.observe(targetEl1);
            io.observe(targetEl2);
            io.observe(targetEl3);
            io.observe(targetEl4);
          }
        ], done);
      });


      it('handles targets on the boundary of root', function(done) {

        var spy = sinon.spy();
        io = new IntersectionObserver(spy, {root: rootEl});

        runSequence([
          function(done) {
            targetEl1.style.top = '0px';
            targetEl1.style.left = '-21px';
            targetEl2.style.top = '-20px';
            targetEl2.style.left = '0px';
            io.observe(targetEl1);
            io.observe(targetEl2);
            spy.waitForNotification(function() {
              expect(spy.callCount).to.be(1);
              var records = sortRecords(spy.lastCall.args[0]);
              expect(records.length).to.be(1);
              expect(records[0].intersectionRatio).to.be(0);
              expect(records[0].target).to.be(targetEl2);
              done();
            }, ASYNC_TIMEOUT);
          },
          function(done) {
            targetEl1.style.top = '0px';
            targetEl1.style.left = '-20px';
            targetEl2.style.top = '-21px';
            targetEl2.style.left = '0px';
            spy.waitForNotification(function() {
              expect(spy.callCount).to.be(2);
              var records = sortRecords(spy.lastCall.args[0]);
              expect(records.length).to.be(2);
              expect(records[0].intersectionRatio).to.be(0);
              expect(records[0].target).to.be(targetEl1);
              expect(records[1].intersectionRatio).to.be(0);
              expect(records[1].target).to.be(targetEl2);
              done();
            }, ASYNC_TIMEOUT);
          },
          function(done) {
            targetEl1.style.top = '-20px';
            targetEl1.style.left = '200px';
            targetEl2.style.top = '200px';
            targetEl2.style.left = '200px';
            spy.waitForNotification(function() {
              expect(spy.callCount).to.be(3);
              var records = sortRecords(spy.lastCall.args[0]);
              expect(records.length).to.be(1);
              expect(records[0].intersectionRatio).to.be(0);
              expect(records[0].target).to.be(targetEl2);
              done();
            }, ASYNC_TIMEOUT);
          },
          function(done) {
            targetEl3.style.top = '20px';
            targetEl3.style.left = '-20px';
            targetEl4.style.top = '-20px';
            targetEl4.style.left = '20px';
            io.observe(targetEl3);
            io.observe(targetEl4);
            spy.waitForNotification(function() {
              expect(spy.callCount).to.be(4);
              var records = sortRecords(spy.lastCall.args[0]);
              expect(records.length).to.be(2);
              expect(records[0].intersectionRatio).to.be(0);
              expect(records[0].target).to.be(targetEl3);
              expect(records[1].intersectionRatio).to.be(0);
              expect(records[1].target).to.be(targetEl4);
              done();
            }, ASYNC_TIMEOUT);
          }
        ], done);

      });


      it('handles zero-size targets within the root coordinate space',
          function(done) {

        io = new IntersectionObserver(function(records) {
          expect(records.length).to.be(1);
          expect(records[0].intersectionRatio).to.be(0);
          done();
        }, {root: rootEl});

        targetEl1.style.top = '0px';
        targetEl1.style.left = '0px';
        targetEl1.style.width = '0px';
        targetEl1.style.height = '0px';
        io.observe(targetEl1);
      });


      it('handles root/target elements not yet in the DOM', function(done) {

        rootEl.parentNode.removeChild(rootEl);
        targetEl1.parentNode.removeChild(targetEl1);

        var spy = sinon.spy();
        io = new IntersectionObserver(spy, {root: rootEl});

        runSequence([
          function(done) {
            io.observe(targetEl1);
            callDelayed(done, 0);
          },
          function(done) {
            document.getElementById('fixtures').appendChild(rootEl);
            callDelayed(function() {
              expect(spy.callCount).to.be(0);
              done();
            }, ASYNC_TIMEOUT);
          },
          function(done) {
            parentEl.insertBefore(targetEl1, targetEl2);
            spy.waitForNotification(function() {
              expect(spy.callCount).to.be(1);
              var records = sortRecords(spy.lastCall.args[0]);
              expect(records.length).to.be(1);
              expect(records[0].intersectionRatio).to.be(1);
              expect(records[0].target).to.be(targetEl1);
              done();
            }, ASYNC_TIMEOUT);
          },
          function(done) {
            grandParentEl.parentNode.removeChild(grandParentEl);
            spy.waitForNotification(function() {
              expect(spy.callCount).to.be(2);
              var records = sortRecords(spy.lastCall.args[0]);
              expect(records.length).to.be(1);
              expect(records[0].intersectionRatio).to.be(0);
              expect(records[0].target).to.be(targetEl1);
              done();
            }, ASYNC_TIMEOUT);
          },
          function(done) {
            rootEl.appendChild(targetEl1);
            spy.waitForNotification(function() {
              expect(spy.callCount).to.be(3);
              var records = sortRecords(spy.lastCall.args[0]);
              expect(records.length).to.be(1);
              expect(records[0].intersectionRatio).to.be(1);
              expect(records[0].target).to.be(targetEl1);
              done();
            }, ASYNC_TIMEOUT);
          },
          function(done) {
            rootEl.parentNode.removeChild(rootEl);
            spy.waitForNotification(function() {
              expect(spy.callCount).to.be(4);
              var records = sortRecords(spy.lastCall.args[0]);
              expect(records.length).to.be(1);
              expect(records[0].intersectionRatio).to.be(0);
              expect(records[0].target).to.be(targetEl1);
              done();
            }, ASYNC_TIMEOUT);
          }
        ], done);
      });


      it('handles sub-root element scrolling', function(done) {
        io = new IntersectionObserver(function(records) {
          expect(records.length).to.be(1);
          expect(records[0].intersectionRatio).to.be(1);
          done();
        }, {root: rootEl});

        io.observe(targetEl3);
        callDelayed(function() {
          parentEl.scrollLeft = 40;
        }, 0);
      });


      it('supports CSS transitions and transforms', function(done) {

        targetEl1.style.top = '220px';
        targetEl1.style.left = '220px';

        io = new IntersectionObserver(function(records) {
          expect(records.length).to.be(1);
          expect(records[0].intersectionRatio).to.be(1);
          done();
        }, {root: rootEl, threshold: [1]});

        io.observe(targetEl1);
        callDelayed(function() {
          targetEl1.style.transform = 'translateX(-40px) translateY(-40px)';
        }, 0);
      });


      it('uses the viewport when no root is specified', function(done) {
        window.onmessage = function (e) {
          expect(e.data).to.be.ok();
          win.close();
          done();
        };

        var win = window.open("intersectionobserver_window.html");
      });

    });

    describe('observe subframe', function () {
      
      it('should not trigger if target and root are not in the same document',
          function(done) {

        var spy = sinon.spy();
        io = new IntersectionObserver(spy, {root: rootEl});

        targetEl4.onload = function () {
          targetEl5 = targetEl4.contentDocument.getElementById('target5');
          io.observe(targetEl5);
          callDelayed(function() {
            expect(spy.callCount).to.be(0);
            done();
          }, ASYNC_TIMEOUT);
        }

        targetEl4.src = "intersectionobserver_iframe.html";
      
      });

      it('boundingClientRect matches target.getBoundingClientRect() for an element inside an iframe',
          function(done) {

        io = new IntersectionObserver(function(records) {
          expect(records.length).to.be(1);
          expect(records[0].boundingClientRect.top, targetEl5.getBoundingClientRect().top);
          expect(records[0].boundingClientRect.left, targetEl5.getBoundingClientRect().left);
          expect(records[0].boundingClientRect.width, targetEl5.getBoundingClientRect().width);
          expect(records[0].boundingClientRect.height, targetEl5.getBoundingClientRect().height);
          done();
        }, {threshold: [1]});

        targetEl4.onload = function () {
          targetEl5 = targetEl4.contentDocument.getElementById('target5');
          io.observe(targetEl5);
        }

        targetEl4.src = "intersectionobserver_iframe.html";
      });

      it('rootBounds should is set to null for cross-origin observations', function(done) {

        window.onmessage = function (e) {
          expect(e.data).to.be.ok();
          done();
        };

        targetEl4.src = "http://example.org/tests/dom/base/test/intersectionobserver_iframe.html";

      });
    
    });

    describe('takeRecords', function() {

      it('supports getting records before the callback is invoked',
          function(done) {

        var lastestRecords = [];
        io = new IntersectionObserver(function(records) {
          lastestRecords = lastestRecords.concat(records);
        }, {root: rootEl});
        io.observe(targetEl1);

        window.requestAnimationFrame && requestAnimationFrame(function() {
          lastestRecords = lastestRecords.concat(io.takeRecords());
        });

        callDelayed(function() {
          expect(lastestRecords.length).to.be(1);
          expect(lastestRecords[0].intersectionRatio).to.be(1);
          done();
        }, ASYNC_TIMEOUT);
      });

    });


    describe('unobserve', function() {

      it('removes targets from the internal store', function(done) {

        var spy = sinon.spy();
        io = new IntersectionObserver(spy, {root: rootEl});

        runSequence([
          function(done) {
            targetEl1.style.top = targetEl2.style.top = '0px';
            targetEl1.style.left = targetEl2.style.left = '0px';
            io.observe(targetEl1);
            io.observe(targetEl2);
            spy.waitForNotification(function() {
              expect(spy.callCount).to.be(1);
              var records = sortRecords(spy.lastCall.args[0]);
              expect(records.length).to.be(2);
              expect(records[0].target).to.be(targetEl1);
              expect(records[0].intersectionRatio).to.be(1);
              expect(records[1].target).to.be(targetEl2);
              expect(records[1].intersectionRatio).to.be(1);
              done();
            }, ASYNC_TIMEOUT);
          },
          function(done) {
            io.unobserve(targetEl1);
            targetEl1.style.top = targetEl2.style.top = '0px';
            targetEl1.style.left = targetEl2.style.left = '-40px';
            spy.waitForNotification(function() {
              expect(spy.callCount).to.be(2);
              var records = sortRecords(spy.lastCall.args[0]);
              expect(records.length).to.be(1);
              expect(records[0].target).to.be(targetEl2);
              expect(records[0].intersectionRatio).to.be(0);
              done();
            }, ASYNC_TIMEOUT);
          },
          function(done) {
            io.unobserve(targetEl2);
            targetEl1.style.top = targetEl2.style.top = '0px';
            targetEl1.style.left = targetEl2.style.left = '0px';
            callDelayed(function() {
              expect(spy.callCount).to.be(2);
              done();
            }, ASYNC_TIMEOUT);
          }
        ], done);

      });

    });

    describe('disconnect', function() {

      it('removes all targets and stops listening for changes', function(done) {

        var spy = sinon.spy();
        io = new IntersectionObserver(spy, {root: rootEl});

        runSequence([
          function(done) {
            targetEl1.style.top = targetEl2.style.top = '0px';
            targetEl1.style.left = targetEl2.style.left = '0px';
            io.observe(targetEl1);
            io.observe(targetEl2);
            spy.waitForNotification(function() {
              expect(spy.callCount).to.be(1);
              var records = sortRecords(spy.lastCall.args[0]);
              expect(records.length).to.be(2);
              expect(records[0].target).to.be(targetEl1);
              expect(records[0].intersectionRatio).to.be(1);
              expect(records[1].target).to.be(targetEl2);
              expect(records[1].intersectionRatio).to.be(1);
              done();
            }, ASYNC_TIMEOUT);
          },
          function(done) {
            io.disconnect();
            targetEl1.style.top = targetEl2.style.top = '0px';
            targetEl1.style.left = targetEl2.style.left = '-40px';
            callDelayed(function() {
              expect(spy.callCount).to.be(1);
              done();
            }, ASYNC_TIMEOUT);
          }
        ], done);

      });

    });

  });


  /**
   * Runs a sequence of function and when finished invokes the done callback.
   * Each function in the sequence is invoked with its own done function and
   * it should call that function once it's complete.
   * @param {Array<Function>} functions An array of async functions.
   * @param {Function} done A final callback to be invoked once all function
   *     have run.
   */
  function runSequence(functions, done) {
    var next = functions.shift();
    if (next) {
      next(function() {
        runSequence(functions, done);
      });
    } else {
      done && done();
    }
  }


  /**
   * Sorts an array of records alphebetically by ascending ID. Since the current
   * native implementation doesn't sort change entries by `observe` order, we do
   * that ourselves for the non-polyfill case. Since all tests call observe
   * on targets in sequential order, this should always match.
   * https://crbug.com/613679
   * @param {Array<IntersectionObserverEntry>} entries The entries to sort.
   * @return {Array<IntersectionObserverEntry>} The sorted array.
   */
  function sortRecords(entries) {
    entries = entries.sort(function(a, b) {
      return a.target.id < b.target.id ? -1 : 1;
    });
    return entries;
  }


  /**
   * Adds the common styles used by all tests to the page.
   */
  function addStyles() {
    var styles = document.createElement('style');
    styles.id = 'styles';
    document.documentElement.appendChild(styles);

    var cssText =
        '#root {' +
        '  position: relative;' +
        '  width: 400px;' +
        '  height: 200px;' +
        '  background: #eee' +
        '}' +
        '#grand-parent {' +
        '  position: relative;' +
        '  width: 200px;' +
        '  height: 200px;' +
        '}' +
        '#parent {' +
        '  position: absolute;' +
        '  top: 0px;' +
        '  left: 200px;' +
        '  overflow: hidden;' +
        '  width: 200px;' +
        '  height: 200px;' +
        '  background: #ddd;' +
        '}' +
        '#target1, #target2, #target3, #target4 {' +
        '  position: absolute;' +
        '  top: 0px;' +
        '  left: 0px;' +
        '  width: 20px;' +
        '  height: 20px;' +
        '  transform: translateX(0px) translateY(0px);' +
        '  transition: transform .5s;' +
        '  background: #f00;' +
        '  border: none;' +
        '}';

    styles.innerHTML = cssText;
  }


  /**
   * Adds the DOM fixtures used by all tests to the page and assigns them to
   * global variables so they can be referenced within the tests.
   */
  function addFixtures() {
    var fixtures = document.createElement('div');
    fixtures.id = 'fixtures';

    fixtures.innerHTML =
        '<div id="root">' +
        '  <div id="grand-parent">' +
        '    <div id="parent">' +
        '      <div id="target1"></div>' +
        '      <div id="target2"></div>' +
        '      <div id="target3"></div>' +
        '      <iframe id="target4"></iframe>' +
        '    </div>' +
        '  </div>' +
        '</div>';

    document.body.appendChild(fixtures);

    rootEl = document.getElementById('root');
    grandParentEl = document.getElementById('grand-parent');
    parentEl = document.getElementById('parent');
    targetEl1 = document.getElementById('target1');
    targetEl2 = document.getElementById('target2');
    targetEl3 = document.getElementById('target3');
    targetEl4 = document.getElementById('target4');
  }


  /**
   * Removes the common styles from the page.
   */
  function removeStyles() {
    var styles = document.getElementById('styles');
    styles.parentNode.removeChild(styles);
  }


  /**
   * Removes the DOM fixtures from the page and resets the global references.
   */
  function removeFixtures() {
    var fixtures = document.getElementById('fixtures');
    fixtures.parentNode.removeChild(fixtures);

    rootEl = null;
    grandParentEl = null;
    parentEl = null;
    targetEl1 = null;
    targetEl2 = null;
    targetEl3 = null;
    targetEl4 = null;
  }

  SimpleTest.waitForExplicitFinish();
</script>
</pre>
<div id="log">
</div>
</body>
</html>