-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
viewport-impl.js
1238 lines (1106 loc) · 32.5 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 {Observable} from '../../core/data-structures/observable';
import {Services} from '../../services';
import {ViewportBindingDef} from './viewport-binding-def';
import {ViewportBindingIosEmbedWrapper_} from './viewport-binding-ios-embed-wrapper';
import {ViewportBindingNatural_} from './viewport-binding-natural';
import {ViewportInterface} from './viewport-interface';
import {VisibilityState} from '../../core/constants/visibility-state';
import {clamp} from '../../core/math';
import {closestAncestorElementBySelector} from '../../core/dom/query';
import {computedStyle, setStyle} from '../../style';
import {dev, devAssert} from '../../log';
import {dict} from '../../core/types/object';
import {getFriendlyIframeEmbedOptional} from '../../iframe-helper';
import {getMode} from '../../mode';
import {
getParentWindowFrameElement,
registerServiceBuilderForDoc,
} from '../../service';
import {getVerticalScrollbarWidth, isIframed} from '../../dom';
import {isExperimentOn} from '../../experiments';
import {
layoutRectFromDomRect,
layoutRectLtwh,
moveLayoutRect,
} from '../../core/math/layout-rect';
import {numeric} from '../../transition';
import {tryResolve} from '../../core/data-structures/promise';
const TAG_ = 'Viewport';
const SCROLL_POS_TO_BLOCK = {
'top': 'start',
'center': 'center',
'bottom': 'end',
};
const SMOOTH_SCROLL_DELAY_ = 300;
/**
* This object represents the viewport. It tracks scroll position, resize
* and other events and notifies interesting parties when viewport has changed
* and how.
*
* @implements {ViewportInterface}
*/
export class ViewportImpl {
/**
* @param {!../ampdoc-impl.AmpDoc} ampdoc
* @param {!ViewportBindingDef} binding
* @param {!../viewer-interface.ViewerInterface} viewer
*/
constructor(ampdoc, binding, viewer) {
const {win} = ampdoc;
/** @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-interface.ViewerInterface} */
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 {boolean} */
this.scrollAnimationFrameThrottled_ = false;
/** @private {?number} */
this./*OK*/ scrollLeft_ = null;
/** @private {number} */
this.paddingTop_ = Number(viewer.getParam('paddingTop') || 0);
/** @private {number} */
this.lastPaddingTop_ = 0;
/** @private {!../timer-impl.Timer} */
this.timer_ = Services.timerFor(win);
/** @private {!../vsync-impl.Vsync} */
this.vsync_ = Services.vsyncFor(win);
/** @private {boolean} */
this.scrollTracking_ = false;
/** @private {Element} */
this.scrollingElement_ = null;
/** @private {number} */
this.scrollCount_ = 0;
/** @private @const {!Observable<!./viewport-interface.ViewportChangedEventDef>} */
this.changeObservable_ = new Observable();
/** @private @const {!Observable} */
this.scrollObservable_ = new Observable();
/** @private @const {!Observable<!./viewport-interface.ViewportResizedEventDef>} */
this.resizeObservable_ = new Observable();
/** @private {?HTMLMetaElement|undefined} */
this.viewportMeta_ = undefined;
/** @private {string|undefined} */
this.originalViewportMetaString_ = undefined;
/** @private {?../fixed-layer.FixedLayer} */
this.fixedLayer_ = null;
this.viewer_.onMessage('viewport', this.updateOnViewportEvent_.bind(this));
this.viewer_.onMessage('scroll', this.viewerSetScrollTop_.bind(this));
this.viewer_.onMessage(
'disableScroll',
this.disableScrollEventHandler_.bind(this)
);
if (this.viewer_.isEmbedded()) {
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.ampdoc.onVisibilityChanged(this.updateVisibility_.bind(this));
this.updateVisibility_();
// Top-level mode classes.
const globalDocElement = this.globalDoc_.documentElement;
if (ampdoc.isSingleDoc()) {
globalDocElement.classList.add('i-amphtml-singledoc');
}
if (viewer.isEmbedded()) {
globalDocElement.classList.add('i-amphtml-embedded');
} else {
globalDocElement.classList.add('i-amphtml-standalone');
}
if (isIframed(win)) {
globalDocElement.classList.add('i-amphtml-iframed');
}
if (viewer.getParam('webview') === '1') {
globalDocElement.classList.add('i-amphtml-webview');
}
// To avoid browser restore scroll position when traverse history
if (isIframed(win) && 'scrollRestoration' in win.history) {
win.history.scrollRestoration = 'manual';
}
// Override global scrollTo if requested.
if (this.binding_.overrideGlobalScrollTo()) {
try {
Object.defineProperty(win, 'scrollTo', {
value: (x, y) => this.setScrollTop(y),
});
['pageYOffset', 'scrollY'].forEach((prop) => {
Object.defineProperty(win, prop, {
get: () => this.getScrollTop(),
});
});
} catch (e) {
// Ignore errors.
}
}
// BF-cache navigation sometimes breaks clicks in an iframe on iOS. See
// https://github.com/ampproject/amphtml/issues/30838 for more details.
// The solution is to make a "fake" scrolling API call.
const isIframedIos = Services.platformFor(win).isIos() && isIframed(win);
// We dont want to scroll if we're in a shadow doc, so check that we're
// in a single doc. Fix for
// https://github.com/ampproject/amphtml/issues/32165.
if (isIframedIos && this.ampdoc.isSingleDoc()) {
this.ampdoc.whenReady().then(() => {
win./*OK*/ scrollTo(-0.1, 0);
});
}
}
/** @override */
dispose() {
this.binding_.disconnect();
}
/** @override */
ensureReadyForElements() {
this.binding_.ensureReadyForElements();
}
/** @private */
updateVisibility_() {
const visible = this.ampdoc.isVisible();
if (visible != this.visible_) {
this.visible_ = visible;
if (visible) {
this.binding_.connect();
if (this.size_) {
// If the size has already been intialized, check it again in case
// the size has changed between `disconnect` and `connect`.
this.resize_();
}
if (this.scrollTop_) {
// Remeasure scrollTop when resource becomes visible to fix #11983
this./*OK*/ scrollTop_ = null;
this.getScrollTop();
}
} else {
this.binding_.disconnect();
}
}
}
/** @override */
getPaddingTop() {
return this.paddingTop_;
}
/** @override */
getScrollTop() {
if (this./*OK*/ scrollTop_ == null) {
this./*OK*/ scrollTop_ = this.binding_.getScrollTop();
}
return this./*OK*/ scrollTop_;
}
/** @override */
getScrollLeft() {
if (this./*OK*/ scrollLeft_ == null) {
this./*OK*/ scrollLeft_ = this.binding_.getScrollLeft();
}
return this./*OK*/ scrollLeft_;
}
/** @override */
setScrollTop(scrollPos) {
this./*OK*/ scrollTop_ = null;
this.binding_.setScrollTop(scrollPos);
}
/** @override */
updatePaddingBottom(paddingBottom) {
this.ampdoc.waitForBodyOpen().then((body) => {
setStyle(body, 'borderBottom', `${paddingBottom}px solid transparent`);
});
}
/** @override */
getSize() {
if (this.size_) {
return this.size_;
}
this.size_ = this.binding_.getSize();
if (this.size_.width == 0 || this.size_.height == 0) {
// Only report when the visibility is "visible" or "prerender".
const visibilityState = this.ampdoc.getVisibilityState();
if (
visibilityState == VisibilityState.PRERENDER ||
visibilityState == VisibilityState.VISIBLE
) {
if (Math.random() < 0.01) {
dev().error(TAG_, 'viewport has zero dimensions');
}
}
}
return this.size_;
}
/** @override */
getHeight() {
return this.getSize().height;
}
/** @override */
getWidth() {
return this.getSize().width;
}
/** @override */
getScrollWidth() {
return this.binding_.getScrollWidth();
}
/** @override */
getScrollHeight() {
return this.binding_.getScrollHeight();
}
/** @override */
getContentHeight() {
return this.binding_.getContentHeight();
}
/** @override */
contentHeightChanged() {
this.binding_.contentHeightChanged();
}
/** @override */
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_;
}
/** @override */
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);
}
/** @override */
getClientRectAsync(el) {
const local = this.vsync_.measurePromise(() => {
return el./*OK*/ getBoundingClientRect();
});
let root = this.binding_.getRootClientRectAsync();
const frameElement = getParentWindowFrameElement(el, this.ampdoc.win);
if (frameElement) {
root = this.vsync_.measurePromise(() => {
return frameElement./*OK*/ getBoundingClientRect();
});
}
return Promise.all([local, root]).then((values) => {
const l = values[0];
const r = values[1];
if (!r) {
return layoutRectFromDomRect(l);
}
return moveLayoutRect(l, r.left, r.top);
});
}
/** @override */
supportsPositionFixed() {
return this.binding_.supportsPositionFixed();
}
/** @override */
isDeclaredFixed(element) {
if (!this.fixedLayer_) {
return false;
}
return this.fixedLayer_.isDeclaredFixed(element);
}
/** @override */
scrollIntoView(element) {
if (IS_SXG) {
element./* OK */ scrollIntoView();
return Promise.resolve();
} else {
return this.getScrollingContainerFor_(element).then((parent) =>
this.scrollIntoViewInternal_(element, parent)
);
}
}
/**
* @param {!Element} element
* @param {!Element} parent
*/
scrollIntoViewInternal_(element, parent) {
const elementTop = this.binding_.getLayoutRect(element).top;
const newScrollTopPromise = tryResolve(() =>
Math.max(0, elementTop - this.paddingTop_)
);
newScrollTopPromise.then((newScrollTop) =>
this.setElementScrollTop_(parent, newScrollTop)
);
}
/** @override */
animateScrollIntoView(element, pos = 'top', opt_duration, opt_curve) {
if (IS_SXG) {
return new Promise((resolve, opt_) => {
element./* OK */ scrollIntoView({
block: SCROLL_POS_TO_BLOCK[pos],
behavior: 'smooth',
});
setTimeout(resolve, SMOOTH_SCROLL_DELAY_);
});
} else {
devAssert(
!opt_curve || opt_duration !== undefined,
"Curve without duration doesn't make sense."
);
return this.getScrollingContainerFor_(element).then((parent) =>
this.animateScrollWithinParent(
element,
parent,
dev().assertString(pos),
opt_duration,
opt_curve
)
);
}
}
/** @override */
animateScrollWithinParent(element, parent, pos, opt_duration, opt_curve) {
devAssert(
!opt_curve || opt_duration !== undefined,
"Curve without duration doesn't make sense."
);
const elementRect = this.binding_.getLayoutRect(element);
const {height: parentHeight} = this.isScrollingElement_(parent)
? this.getSize()
: this.getLayoutRect(parent);
let offset;
switch (pos) {
case 'bottom':
offset = -parentHeight + elementRect.height;
break;
case 'center':
offset = -parentHeight / 2 + elementRect.height / 2;
break;
default:
offset = 0;
break;
}
return this.getElementScrollTop_(parent).then((curScrollTop) => {
const calculatedScrollTop = elementRect.top - this.paddingTop_ + offset;
const newScrollTop = Math.max(0, calculatedScrollTop);
if (newScrollTop == curScrollTop) {
return;
}
return this.interpolateScrollIntoView_(
parent,
curScrollTop,
newScrollTop,
opt_duration,
opt_curve
);
});
}
/**
* @param {!Element} parent
* @param {number} curScrollTop
* @param {number} newScrollTop
* @param {number=} opt_duration
* @param {string=} curve
* @private
*/
interpolateScrollIntoView_(
parent,
curScrollTop,
newScrollTop,
opt_duration,
curve = 'ease-in'
) {
const duration =
opt_duration !== undefined
? dev().assertNumber(opt_duration)
: getDefaultScrollAnimationDuration(curScrollTop, newScrollTop);
/** @const {!TransitionDef<number>} */
const interpolate = numeric(curScrollTop, newScrollTop);
return Animation.animate(
parent,
(position) => {
this.setElementScrollTop_(parent, interpolate(position));
},
duration,
curve
).thenAlways(() => {
this.setElementScrollTop_(parent, newScrollTop);
});
}
/**
* @param {!Element} element
* @return {!Promise<!Element>}
*/
getScrollingContainerFor_(element) {
return this.vsync_.measurePromise(
() =>
closestAncestorElementBySelector(element, '.i-amphtml-scrollable') ||
this.binding_.getScrollingElement()
);
}
/**
* @param {!Element} element
* @param {number} scrollTop
*/
setElementScrollTop_(element, scrollTop) {
if (this.isScrollingElement_(element)) {
this.binding_.setScrollTop(scrollTop);
return;
}
this.vsync_.mutate(() => {
element./*OK*/ scrollTop = scrollTop;
});
}
/**
* @param {!Element} element
* @return {!Promise<number>}
*/
getElementScrollTop_(element) {
if (this.isScrollingElement_(element)) {
return tryResolve(() => this.getScrollTop());
}
return this.vsync_.measurePromise(() => element./*OK*/ scrollTop);
}
/**
* @param {!Element} element
* @return {boolean}
*/
isScrollingElement_(element) {
return element == this.binding_.getScrollingElement();
}
/** @override */
getScrollingElement() {
if (this.scrollingElement_) {
return this.scrollingElement_;
}
return (this.scrollingElement_ = this.binding_.getScrollingElement());
}
/** @override */
onChanged(handler) {
return this.changeObservable_.add(handler);
}
/** @override */
onScroll(handler) {
return this.scrollObservable_.add(handler);
}
/** @override */
onResize(handler) {
return this.resizeObservable_.add(handler);
}
/** @override */
enterLightboxMode(opt_requestingElement, opt_onComplete) {
this.viewer_.sendMessage(
'requestFullOverlay',
dict(),
/* cancelUnsent */ true
);
this.enterOverlayMode();
if (this.fixedLayer_) {
this.fixedLayer_.enterLightbox(opt_requestingElement, opt_onComplete);
}
if (opt_requestingElement) {
this.maybeEnterFieLightboxMode(
dev().assertElement(opt_requestingElement)
);
}
return this.binding_.updateLightboxMode(true);
}
/** @override */
leaveLightboxMode(opt_requestingElement) {
this.viewer_.sendMessage(
'cancelFullOverlay',
dict(),
/* cancelUnsent */ true
);
if (this.fixedLayer_) {
this.fixedLayer_.leaveLightbox();
}
this.leaveOverlayMode();
if (opt_requestingElement) {
this.maybeLeaveFieLightboxMode(
dev().assertElement(opt_requestingElement)
);
}
return this.binding_.updateLightboxMode(false);
}
/**
* @return {boolean}
* @visibleForTesting
*/
isLightboxExperimentOn() {
return isExperimentOn(this.ampdoc.win, 'amp-lightbox-a4a-proto');
}
/**
* Enters frame lightbox mode if under a Friendly Iframe Embed.
* @param {!Element} requestingElement
* @visibleForTesting
*/
maybeEnterFieLightboxMode(requestingElement) {
const fieOptional = this.getFriendlyIframeEmbed_(requestingElement);
if (fieOptional) {
devAssert(
this.isLightboxExperimentOn(),
'Lightbox mode for A4A is only available when ' +
"'amp-lightbox-a4a-proto' experiment is on"
);
fieOptional.enterFullOverlayMode();
}
}
/**
* Leaves frame lightbox mode if under a Friendly Iframe Embed.
* @param {!Element} requestingElement
* @visibleForTesting
*/
maybeLeaveFieLightboxMode(requestingElement) {
const fieOptional = this.getFriendlyIframeEmbed_(requestingElement);
if (fieOptional) {
devAssert(fieOptional).leaveFullOverlayMode();
}
}
/**
* Get FriendlyIframeEmbed if available.
* @param {!Element} element Element supposedly inside the FIE.
* @return {?../../friendly-iframe-embed.FriendlyIframeEmbed}
* @private
*/
getFriendlyIframeEmbed_(element) {
const iframeOptional = getParentWindowFrameElement(
element,
this.ampdoc.win
);
return (
iframeOptional &&
getFriendlyIframeEmbedOptional(
/** @type {!HTMLIFrameElement} */
(dev().assertElement(iframeOptional))
)
);
}
/** @override */
enterOverlayMode() {
this.disableTouchZoom();
this.disableScroll();
}
/** @override */
leaveOverlayMode() {
this.resetScroll();
this.restoreOriginalTouchZoom();
}
/** @override */
disableScroll() {
const {win} = this.ampdoc;
const {documentElement} = win.document;
let requestedMarginRight;
// Calculate the scrollbar width so we can set it as a right margin. This
// is so that we do not cause content to shift when we disable scroll on
// platforms that have a width-taking scrollbar.
this.vsync_.measure(() => {
const existingMargin = computedStyle(win, documentElement).marginRight;
const scrollbarWidth = getVerticalScrollbarWidth(this.ampdoc.win);
requestedMarginRight = parseInt(existingMargin, 10) + scrollbarWidth;
});
this.vsync_.mutate(() => {
setStyle(documentElement, 'margin-right', requestedMarginRight, 'px');
this.binding_.disableScroll();
});
}
/** @override */
resetScroll() {
const {win} = this.ampdoc;
const {documentElement} = win.document;
this.vsync_.mutate(() => {
setStyle(documentElement, 'margin-right', '');
this.binding_.resetScroll();
});
}
/** @override */
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);
}
}
/** @override */
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);
}
/** @override */
restoreOriginalTouchZoom() {
if (this.originalViewportMetaString_ !== undefined) {
return this.setViewportMetaString_(this.originalViewportMetaString_);
}
return false;
}
/** @override */
updateFixedLayer() {
if (!this.fixedLayer_) {
return Promise.resolve();
}
return this.fixedLayer_.update();
}
/** @override */
addToFixedLayer(element, opt_forceTransfer) {
if (!this.fixedLayer_) {
return Promise.resolve();
}
return this.fixedLayer_.addElement(element, opt_forceTransfer);
}
/** @override */
removeFromFixedLayer(element) {
if (!this.fixedLayer_) {
return;
}
this.fixedLayer_.removeElement(element);
}
/** @override */
createFixedLayer(constructor) {
this.fixedLayer_ = new constructor(
this.ampdoc,
this.vsync_,
this.binding_.getBorderTop(),
this.paddingTop_,
this.binding_.requiresFixedLayerTransfer()
);
this.ampdoc.whenReady().then(() => this.fixedLayer_.setup());
}
/**
* Updates touch zoom meta data. Returns `true` if any actual
* changes have been done.
* @param {string} viewportMetaString
* @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 {?HTMLMetaElement}
* @private
*/
getViewportMeta_() {
if (isIframed(this.ampdoc.win)) {
// 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 {!JsonObject} data
* @private
*/
viewerSetScrollTop_(data) {
const targetScrollTop = data['scrollTop'];
this.setScrollTop(targetScrollTop);
}
/**
* @param {!JsonObject} data
* @private
*/
updateOnViewportEvent_(data) {
const paddingTop = data['paddingTop'];
const duration = data['duration'] || 0;
const curve = data['curve'];
/** @const {boolean} */
const transient = data['transient'];
if (paddingTop == undefined || paddingTop == this.paddingTop_) {
return;
}
this.lastPaddingTop_ = this.paddingTop_;
this.paddingTop_ = paddingTop;
if (this.fixedLayer_) {
const animPromise = this.fixedLayer_.animateFixedElements(
this.paddingTop_,
this.lastPaddingTop_,
duration,
curve,
transient
);
if (paddingTop < this.lastPaddingTop_) {
this.binding_.hideViewerHeader(transient, this.lastPaddingTop_);
} else {
animPromise.then(() => {
this.binding_.showViewerHeader(transient, paddingTop);
});
}
}
}
/**
* @param {!JsonObject} data
* @private
*/
disableScrollEventHandler_(data) {
if (!!data) {
this.disableScroll();
} else {
this.resetScroll();
}
}
/**
* @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
*/