forked from ampproject/amphtml
/
viewport-impl.js
1753 lines (1540 loc) · 48.9 KB
/
viewport-impl.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 2015 The AMP HTML Authors. 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.
*/
import {Animation} from '../animation';
import {FixedLayer} from './fixed-layer';
import {Observable} from '../observable';
import {checkAndFix as checkAndFixIosScrollfreezeBug,} from
'./ios-scrollfreeze-bug';
import {
getParentWindowFrameElement,
getServiceForDoc,
} from '../service';
import {layoutRectLtwh} from '../layout-rect';
import {dev} from '../log';
import {numeric} from '../transition';
import {onDocumentReady, whenDocumentReady} from '../document-ready';
import {platformFor} from '../platform';
import {px, setStyle, setStyles} from '../style';
import {timerFor} from '../timer';
import {installVsyncService} from './vsync-impl';
import {installViewerServiceForDoc} from './viewer-impl';
import {isExperimentOn} from '../experiments';
import {waitForBody} from '../dom';
import {getMode} from '../mode';
const TAG_ = 'Viewport';
/**
* @typedef {{
* relayoutAll: boolean,
* top: number,
* left: number,
* width: number,
* height: number,
* velocity: number
* }}
*/
export let ViewportChangedEventDef;
/**
* This object represents the viewport. It tracks scroll position, resize
* and other events and notifies interesting parties when viewport has changed
* and how.
* @implements {../service.Disposable}
* @package Visible for type.
*/
export class Viewport {
/**
* @param {!./ampdoc-impl.AmpDoc} ampdoc
* @param {!ViewportBindingDef} binding
* @param {!./viewer-impl.Viewer} viewer
*/
constructor(ampdoc, binding, viewer) {
/** @const {!./ampdoc-impl.AmpDoc} */
this.ampdoc = ampdoc;
/**
* Some viewport operations require the global document.
* @private @const {!Document}
*/
this.globalDoc_ = this.ampdoc.win.document;
/** @const {!ViewportBindingDef} */
this.binding_ = binding;
/** @const {!./viewer-impl.Viewer} */
this.viewer_ = viewer;
/**
* Used to cache the rect of the viewport.
* @private {?../layout-rect.LayoutRectDef}
*/
this.rect_ = null;
/**
* Used to cache the size of the viewport. Also used as last known size,
* so users should call getSize early on to get a value. The timing should
* be chosen to avoid extra style recalcs.
* @private {{width: number, height: number}|null}
*/
this.size_ = null;
/** @private {?number} */
this./*OK*/scrollTop_ = null;
/** @private {?number} */
this.lastMeasureScrollTop_ = null;
/** @private {boolean} */
this.scrollAnimationFrameThrottled_ = false;
/** @private {?number} */
this./*OK*/scrollLeft_ = null;
/** @private {number} */
this.paddingTop_ = viewer.getPaddingTop();
/** @private {number} */
this.lastPaddingTop_ = 0;
/** @private {number} */
this.scrollMeasureTime_ = 0;
/** @private {!./timer-impl.Timer} */
this.timer_ = timerFor(this.ampdoc.win);
/** @private {!./vsync-impl.Vsync} */
this.vsync_ = installVsyncService(this.ampdoc.win);
/** @private {boolean} */
this.scrollTracking_ = false;
/** @private {number} */
this.scrollCount_ = 0;
/** @private @const {!Observable<!ViewportChangedEventDef>} */
this.changeObservable_ = new Observable();
/** @private @const {!Observable} */
this.scrollObservable_ = new Observable();
/** @private {?Element|undefined} */
this.viewportMeta_ = undefined;
/** @private {string|undefined} */
this.originalViewportMetaString_ = undefined;
/** @private @const {!FixedLayer} */
this.fixedLayer_ = new FixedLayer(
this.ampdoc,
this.vsync_,
this.paddingTop_,
this.binding_.requiresFixedLayerTransfer());
this.ampdoc.whenReady().then(() => this.fixedLayer_.setup());
/** @private @const (function()) */
this.boundThrottledScroll_ = this.throttledScroll_.bind(this);
this.viewer_.onViewportEvent(this.updateOnViewportEvent_.bind(this));
this.binding_.updatePaddingTop(this.paddingTop_);
this.binding_.onScroll(this.scroll_.bind(this));
this.binding_.onResize(this.resize_.bind(this));
this.onScroll(this.sendScrollMessage_.bind(this));
/** @private {boolean} */
this.visible_ = false;
this.viewer_.onVisibilityChanged(this.updateVisibility_.bind(this));
this.updateVisibility_();
// TODO(dvoytenko, #4894): Cleanup the experiment by moving this to CSS:
// `html {touch-action: pan-y}` (will require adding `amp-embedded` class).
// The enables passive touch handlers, e.g. for document swipe, since they
// no will longer need to try to cancel vertical scrolls during swipes.
// This is only done in the embedded mode because (a) the document swipe
// is only possible in this case, and (b) we'd like to preserve pinch-zoom.
if (this.ampdoc.isSingleDoc() &&
viewer.isEmbedded() &&
isExperimentOn(this.ampdoc.win, 'pan-y')) {
setStyle(this.globalDoc_.documentElement, 'touch-action', 'pan-y');
}
// TODO(sriramkrish85, #5319): Cleanup the experiment by making the effects
// on CSS permanent and removing the code block below.
if (this.ampdoc.isSingleDoc() &&
isExperimentOn(this.ampdoc.win, 'make-body-block')) {
this.globalDoc_.documentElement.classList.add('-amp-make-body-block');
}
}
/** @override */
dispose() {
this.binding_.disconnect();
}
/**
* Called before a first AMP element is added to resources. Called in the
* mutate context.
*/
ensureReadyForElements() {
this.binding_.ensureReadyForElements();
}
/** @private */
updateVisibility_() {
const visible = this.viewer_.isVisible();
if (visible != this.visible_) {
this.visible_ = visible;
if (visible) {
this.binding_.connect();
} else {
this.binding_.disconnect();
}
}
}
/**
* Returns the top padding mandated by the viewer.
* @return {number}
*/
getPaddingTop() {
return this.paddingTop_;
}
/**
* Returns the viewport's top position in the document. This is essentially
* the scroll position.
* @return {number}
* @deprecated Use {@link getScrollTop}
*/
getTop() {
return this.getScrollTop();
}
/**
* Returns the viewport's vertical scroll position.
* @return {number}
*/
getScrollTop() {
if (this./*OK*/scrollTop_ == null) {
this./*OK*/scrollTop_ = this.binding_.getScrollTop();
}
return this./*OK*/scrollTop_;
}
/**
* Returns the viewport's horizontal scroll position.
* @return {number}
*/
getScrollLeft() {
if (this./*OK*/scrollLeft_ == null) {
this./*OK*/scrollLeft_ = this.binding_.getScrollLeft();
}
return this./*OK*/scrollLeft_;
}
/**
* Sets the desired scroll position on the viewport.
* @param {number} scrollPos
*/
setScrollTop(scrollPos) {
this./*OK*/scrollTop_ = null;
this.binding_.setScrollTop(scrollPos);
}
/**
* Sets the body padding bottom to the specified value.
* @param {number} paddingBottom
*/
updatePaddingBottom(paddingBottom) {
this.ampdoc.whenBodyAvailable().then(body => {
body.style.borderBottom = `${paddingBottom}px solid transparent`;
});
}
/**
* Returns the size of the viewport.
* @return {!{width: number, height: number}}
*/
getSize() {
if (this.size_) {
return this.size_;
}
return this.size_ = this.binding_.getSize();
}
/**
* Returns the height of the viewport.
* @return {number}
*/
getHeight() {
return this.getSize().height;
}
/**
* Returns the width of the viewport.
* @return {number}
*/
getWidth() {
return this.getSize().width;
}
/**
* Returns the scroll width of the content of the document. Note that this
* method is not cached since we there's no indication when it might change.
* @return {number}
*/
getScrollWidth() {
return this.binding_.getScrollWidth();
}
/**
* Returns the scroll height of the content of the document. Note that this
* method is not cached since we there's no indication when it might change.
* @return {number}
*/
getScrollHeight() {
return this.binding_.getScrollHeight();
}
/**
* Returns the rect of the viewport which includes scroll positions and size.
* @return {!../layout-rect.LayoutRectDef}}
*/
getRect() {
if (this.rect_ == null) {
const scrollTop = this.getScrollTop();
const scrollLeft = this.getScrollLeft();
const size = this.getSize();
this.rect_ =
layoutRectLtwh(scrollLeft, scrollTop, size.width, size.height);
}
return this.rect_;
}
/**
* Returns the rect of the element within the document.
* @param {!Element} el
* @return {!../layout-rect.LayoutRectDef}}
*/
getLayoutRect(el) {
const scrollLeft = this.getScrollLeft();
const scrollTop = this.getScrollTop();
// Go up the window hierarchy through friendly iframes.
const frameElement = getParentWindowFrameElement(el, this.ampdoc.win);
if (frameElement) {
const b = this.binding_.getLayoutRect(el, 0, 0);
const c = this.binding_.getLayoutRect(
frameElement, scrollLeft, scrollTop);
return layoutRectLtwh(Math.round(b.left + c.left),
Math.round(b.top + c.top),
Math.round(b.width),
Math.round(b.height));
}
return this.binding_.getLayoutRect(el, scrollLeft, scrollTop);
}
/**
* Whether the element is declared as fixed in any of the user's stylesheets.
* Will include any matches, not necessarily currently fixed elements.
* @param {!Element} element
* @return {boolean}
*/
isDeclaredFixed(element) {
return this.fixedLayer_.isDeclaredFixed(element);
}
/**
* Scrolls element into view much like Element. scrollIntoView does but
* in the AMP/Viewer environment.
* @param {!Element} element
*/
scrollIntoView(element) {
const elementTop = this.binding_.getLayoutRect(element).top;
const newScrollTop = Math.max(0, elementTop - this.paddingTop_);
this.binding_.setScrollTop(newScrollTop);
}
/**
* Scrolls element into view much like Element. scrollIntoView does but
* in the AMP/Viewer environment. Adds animation for the sccrollIntoView
* transition.
*
* @param {!Element} element
* @param {number=} duration
* @param {string=} curve
* @return {!Promise}
*/
animateScrollIntoView(element, duration = 500, curve = 'ease-in') {
const elementTop = this.binding_.getLayoutRect(element).top;
const newScrollTop = Math.max(0, elementTop - this.paddingTop_);
const curScrollTop = this.getScrollTop();
if (newScrollTop == curScrollTop) {
return Promise.resolve();
}
/** @const {!TransitionDef<number>} */
const interpolate = numeric(curScrollTop, newScrollTop);
// TODO(erwinm): the duration should not be a constant and should
// be done in steps for better transition experience when things
// are closer vs farther.
// TODO(dvoytenko, #3742): documentElement will be replaced by ampdoc.
return Animation.animate(this.ampdoc.getRootNode(), pos => {
this.binding_.setScrollTop(interpolate(pos));
}, duration, curve).then();
}
/**
* Registers the handler for ViewportChangedEventDef events.
* @param {!function(!ViewportChangedEventDef)} handler
* @return {!UnlistenDef}
*/
onChanged(handler) {
return this.changeObservable_.add(handler);
}
/**
* Registers the handler for scroll events. These events DO NOT contain
* scrolling offset and it's discouraged to read scrolling offset in the
* event handler. The primary use case for this handler is to inform that
* scrolling might be going on. To get more information {@link onChanged}
* handler should be used.
* @param {!function()} handler
* @return {!UnlistenDef}
*/
onScroll(handler) {
return this.scrollObservable_.add(handler);
}
/**
* Instruct the viewport to enter lightbox mode.
*/
enterLightboxMode() {
this.viewer_.requestFullOverlay();
this.disableTouchZoom();
this.hideFixedLayer();
this.vsync_.mutate(() => this.binding_.updateLightboxMode(true));
}
/**
* Instruct the viewport to enter lightbox mode.
*/
leaveLightboxMode() {
this.viewer_.cancelFullOverlay();
this.showFixedLayer();
this.restoreOriginalTouchZoom();
this.vsync_.mutate(() => this.binding_.updateLightboxMode(false));
}
/**
* Resets touch zoom to initial scale of 1.
*/
resetTouchZoom() {
const windowHeight = this.ampdoc.win./*OK*/innerHeight;
const documentHeight = this.globalDoc_.documentElement./*OK*/clientHeight;
if (windowHeight && documentHeight && windowHeight === documentHeight) {
// This code only works when scrollbar overlay content and take no space,
// which is fine on mobile. For non-mobile devices this code is
// irrelevant.
return;
}
if (this.disableTouchZoom()) {
this.timer_.delay(() => {
this.restoreOriginalTouchZoom();
}, 50);
}
}
/**
* Disables touch zoom on this viewport. Returns `true` if any actual
* changes have been done.
* @return {boolean}
*/
disableTouchZoom() {
const viewportMeta = this.getViewportMeta_();
if (!viewportMeta) {
// This should never happen in a valid AMP document, thus shortcircuit.
return false;
}
// Setting maximum-scale=1 and user-scalable=no zooms page back to normal
// and prohibit further default zooming.
const newValue = updateViewportMetaString(viewportMeta.content, {
'maximum-scale': '1',
'user-scalable': 'no',
});
return this.setViewportMetaString_(newValue);
}
/**
* Restores original touch zoom parameters. Returns `true` if any actual
* changes have been done.
* @return {boolean}
*/
restoreOriginalTouchZoom() {
if (this.originalViewportMetaString_ !== undefined) {
return this.setViewportMetaString_(this.originalViewportMetaString_);
}
return false;
}
/**
* Returns whether the user has scrolled yet.
* @return {boolean}
*/
hasScrolled() {
return this.scrollCount_ > 0;
}
/**
* Hides the fixed layer.
*/
hideFixedLayer() {
this.fixedLayer_.setVisible(false);
}
/**
* Shows the fixed layer.
*/
showFixedLayer() {
this.fixedLayer_.setVisible(true);
}
/**
* Updates the fixed layer.
*/
updateFixedLayer() {
this.fixedLayer_.update();
}
/**
* Adds the element to the fixed layer.
* @param {!Element} element
*/
addToFixedLayer(element) {
this.fixedLayer_.addElement(element);
}
/**
* Removes the element from the fixed layer.
* @param {!Element} element
*/
removeFromFixedLayer(element) {
this.fixedLayer_.removeElement(element);
}
/**
* Updates touch zoom meta data. Returns `true` if any actual
* changes have been done.
* @return {boolean}
*/
setViewportMetaString_(viewportMetaString) {
const viewportMeta = this.getViewportMeta_();
if (viewportMeta && viewportMeta.content != viewportMetaString) {
dev().fine(TAG_, 'changed viewport meta to:', viewportMetaString);
viewportMeta.content = viewportMetaString;
return true;
}
return false;
}
/**
* @return {?Element}
* @private
*/
getViewportMeta_() {
if (this.viewer_.isIframed()) {
// An embedded document does not control its viewport meta tag.
return null;
}
if (this.viewportMeta_ === undefined) {
this.viewportMeta_ = /** @type {?HTMLMetaElement} */ (
this.globalDoc_.querySelector('meta[name=viewport]'));
if (this.viewportMeta_) {
this.originalViewportMetaString_ = this.viewportMeta_.content;
}
}
return this.viewportMeta_;
}
/**
* @param {!JSONType} event
* @private
*/
updateOnViewportEvent_(event) {
const paddingTop = event['paddingTop'];
const duration = event['duration'] || 0;
const curve = event['curve'];
/** @const {boolean} */
const transient = event['transient'];
if (paddingTop != this.paddingTop_) {
this.lastPaddingTop_ = this.paddingTop_;
this.paddingTop_ = paddingTop;
if (this.paddingTop_ < this.lastPaddingTop_) {
this.binding_.hideViewerHeader(transient, this.lastPaddingTop_);
this.animateFixedElements_(duration, curve, transient);
} else {
this.animateFixedElements_(duration, curve, transient).then(() => {
this.binding_.showViewerHeader(transient, this.paddingTop_);
});
}
}
}
/**
* @param {number} duration
* @param {string} curve
* @param {boolean} transient
* @return {!Promise}
* @private
*/
animateFixedElements_(duration, curve, transient) {
this.fixedLayer_.updatePaddingTop(this.paddingTop_, transient);
if (duration <= 0) {
return Promise.resolve();
}
// Add transit effect on position fixed element
const tr = numeric(this.lastPaddingTop_ - this.paddingTop_, 0);
return Animation.animate(this.ampdoc.getRootNode(), time => {
const p = tr(time);
this.fixedLayer_.transformMutate(`translateY(${p}px)`);
}, duration, curve).thenAlways(() => {
this.fixedLayer_.transformMutate(null);
});
}
/**
* @param {boolean} relayoutAll
* @param {number} velocity
* @private
*/
changed_(relayoutAll, velocity) {
const size = this.getSize();
const scrollTop = this.getScrollTop();
const scrollLeft = this.getScrollLeft();
dev().fine(TAG_, 'changed event:',
'relayoutAll=', relayoutAll,
'top=', scrollTop,
'left=', scrollLeft,
'bottom=', (scrollTop + size.height),
'velocity=', velocity);
this.changeObservable_.fire({
relayoutAll,
top: scrollTop,
left: scrollLeft,
width: size.width,
height: size.height,
velocity,
});
}
/** @private */
scroll_() {
this.rect_ = null;
this.scrollCount_++;
this.scrollLeft_ = this.binding_.getScrollLeft();
const newScrollTop = this.binding_.getScrollTop();
if (newScrollTop < 0) {
// iOS and some other browsers use negative values of scrollTop for
// overscroll. Overscroll does not affect the viewport and thus should
// be ignored here.
return;
}
this.scrollTop_ = newScrollTop;
if (!this.scrollTracking_) {
this.scrollTracking_ = true;
const now = Date.now();
// Wait 2 frames and then request an animation frame.
this.timer_.delay(() => {
this.vsync_.measure(() => {
this.throttledScroll_(now, newScrollTop);
});
}, 36);
}
this.scrollObservable_.fire();
}
/**
* This method is called about every 3 frames (assuming 60hz) and it
* is called in a vsync measure task.
* @param {number} referenceTime Time when the scroll measurement, that
* triggered this call made, was made.
* @param {number} referenceTop Scrolltop at that time.
* @private
*/
throttledScroll_(referenceTime, referenceTop) {
this.scrollTop_ = this.binding_.getScrollTop();
/** @const {number} */
const newScrollTop = this.scrollTop_;
const now = Date.now();
let velocity = 0;
if (now != referenceTime) {
velocity = (newScrollTop - referenceTop) /
(now - referenceTime);
}
dev().fine(TAG_, 'scroll: ' +
'scrollTop=' + newScrollTop + '; ' +
'velocity=' + velocity);
if (Math.abs(velocity) < 0.03) {
this.changed_(/* relayoutAll */ false, velocity);
this.scrollTracking_ = false;
} else {
this.timer_.delay(() => this.vsync_.measure(
this.throttledScroll_.bind(this, now, newScrollTop)), 20);
}
}
/**
* Send scroll message via the viewer per animation frame
* @private
*/
sendScrollMessage_() {
if (!this.scrollAnimationFrameThrottled_) {
this.scrollAnimationFrameThrottled_ = true;
this.vsync_.measure(() => {
this.scrollAnimationFrameThrottled_ = false;
this.viewer_.postScroll(this.getScrollTop());
});
}
}
/** @private */
resize_() {
this.rect_ = null;
const oldSize = this.size_;
this.size_ = null; // Need to recalc.
const newSize = this.getSize();
this.fixedLayer_.update().then(() => {
this.changed_(!oldSize || oldSize.width != newSize.width, 0);
});
}
}
/**
* ViewportBindingDef is an interface that defines an underlying technology
* behind the {@link Viewport}.
* @interface
* @visibleForTesting
*/
export class ViewportBindingDef {
/**
* Called before a first AMP element is added to resources. The final
* preparations must be completed here. Called in the mutate context.
*/
ensureReadyForElements() {}
/**
* Add listeners for global resources.
*/
connect() {}
/**
* Remove listeners for global resources.
*/
disconnect() {}
/**
* Whether the binding requires fixed elements to be transfered to a
* independent fixed layer.
* @return {boolean}
*/
requiresFixedLayerTransfer() {}
/**
* Register a callback for scroll events.
* @param {function()} unusedCallback
*/
onScroll(unusedCallback) {}
/**
* Register a callback for resize events.
* @param {function()} unusedCallback
*/
onResize(unusedCallback) {}
/**
* Updates binding with the new padding.
* @param {number} unusedPaddingTop
*/
updatePaddingTop(unusedPaddingTop) {}
/**
* Updates binding with the new padding when hiding viewer header.
* @param {boolean} unusedTransient
* @param {number} unusedLastPaddingTop
*/
hideViewerHeader(unusedTransient, unusedLastPaddingTop) {}
/**
* Updates binding with the new padding when showing viewer header.
* @param {boolean} unusedTransient
* @param {number} unusedPaddingTop
*/
showViewerHeader(unusedTransient, unusedPaddingTop) {}
/**
* Updates the viewport whether it's currently in the lightbox or a normal
* mode.
* @param {boolean} unusedLightboxMode
*/
updateLightboxMode(unusedLightboxMode) {}
/**
* Returns the size of the viewport.
* @return {!{width: number, height: number}}
*/
getSize() {}
/**
* Returns the top scroll position for the viewport.
* @return {number}
*/
getScrollTop() {}
/**
* Sets scroll top position to the specified value or the nearest possible.
* @param {number} unusedScrollTop
*/
setScrollTop(unusedScrollTop) {}
/**
* Returns the left scroll position for the viewport.
* @return {number}
*/
getScrollLeft() {}
/**
* Returns the scroll width of the content of the document.
* @return {number}
*/
getScrollWidth() {}
/**
* Returns the scroll height of the content of the document.
* @return {number}
*/
getScrollHeight() {}
/**
* Returns the rect of the element within the document.
* @param {!Element} unusedEl
* @param {number=} unusedScrollLeft Optional arguments that the caller may
* pass in, if they cached these values and would like to avoid
* remeasure. Requires appropriate updating the values on scroll.
* @param {number=} unusedScrollTop Same comment as above.
* @return {!../layout-rect.LayoutRectDef}
*/
getLayoutRect(unusedEl, unusedScrollLeft, unusedScrollTop) {}
}
/**
* Implementation of ViewportBindingDef based on the native window. It assumes that
* the native window is sized properly and events represent the actual
* scroll/resize events. This mode is applicable to a standalone document
* display or when an iframe has a fixed size.
*
* Visible for testing.
*
* @implements {ViewportBindingDef}
*/
export class ViewportBindingNatural_ {
/**
* @param {!Window} win
*/
constructor(win, viewer) {
/** @const {!Window} */
this.win = win;
/** @const {!../service/platform-impl.Platform} */
this.platform_ = platformFor(win);
/** @private @const {!./viewer-impl.Viewer} */
this.viewer_ = viewer;
/** @private @const {!Observable} */
this.scrollObservable_ = new Observable();
/** @private @const {!Observable} */
this.resizeObservable_ = new Observable();
/** @const {function()} */
this.boundScrollEventListener_ = () => this.scrollObservable_.fire();
/** @const {function()} */
this.boundResizeEventListener_ = () => this.resizeObservable_.fire();
if (this.win.document.defaultView) {
waitForBody(this.win.document, () => {
// Override a user-supplied `body{overflow}` to be always visible. This
// style is set in runtime vs css to avoid conflicts with ios-embedded
// mode and fixed transfer layer.
this.win.document.body.style.overflow = 'visible';
if (this.platform_.isIos() &&
this.viewer_.getParam('webview') === '1') {
setStyles(this.win.document.body, {
overflowX: 'hidden',
overflowY: 'visible',
});
}
// Require `body{position:relative}`.
// TODO(dvoytenko, #5660): cleanup "make-body-relative" experiment by
// merging this style into `amp.css`.
if (isExperimentOn(this.win, 'make-body-relative')) {
setStyles(this.win.document.body, {
display: 'block',
position: 'relative',
overflowX: 'hidden',
overflowY: 'visible',
});
}
});
}
dev().fine(TAG_, 'initialized natural viewport');
}
/** @override */
connect() {
this.win.addEventListener('scroll', this.boundScrollEventListener_);
this.win.addEventListener('resize', this.boundResizeEventListener_);
}
/** @override */
disconnect() {
this.win.removeEventListener('scroll', this.boundScrollEventListener_);
this.win.removeEventListener('resize', this.boundResizeEventListener_);
}
/** @override */
ensureReadyForElements() {
// Nothing.
}
/** @override */
requiresFixedLayerTransfer() {
return false;
}
/** @override */
onScroll(callback) {
this.scrollObservable_.add(callback);
}
/** @override */
onResize(callback) {
this.resizeObservable_.add(callback);
}
/** @override */
updatePaddingTop(paddingTop) {
this.win.document.documentElement.style.paddingTop = px(paddingTop);
}
/** @override */
hideViewerHeader(transient, unusedLastPaddingTop) {
if (!transient) {
this.updatePaddingTop(0);
}
}
/** @override */
showViewerHeader(transient, paddingTop) {
if (!transient) {
this.updatePaddingTop(paddingTop);
}
}
/** @override */
updateLightboxMode(unusedLightboxMode) {
// The layout is always accurate.
}
/** @override */
getSize() {
// Prefer window innerWidth/innerHeight but fall back to
// documentElement clientWidth/clientHeight.
// documentElement./*OK*/clientHeight is buggy on iOS Safari
// and thus cannot be used.
const winWidth = this.win./*OK*/innerWidth;
const winHeight = this.win./*OK*/innerHeight;
if (winWidth && winHeight) {
return {width: winWidth, height: winHeight};
}
const el = this.win.document.documentElement;
return {width: el./*OK*/clientWidth, height: el./*OK*/clientHeight};
}
/** @override */
getScrollTop() {
return this.getScrollingElement_()./*OK*/scrollTop ||
this.win./*OK*/pageYOffset;
}
/** @override */
getScrollLeft() {
return this.getScrollingElement_()./*OK*/scrollLeft ||
this.win./*OK*/pageXOffset;