-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
resources-impl.js
1933 lines (1759 loc) · 61.7 KB
/
resources-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 {Deferred} from '../utils/promise';
import {FiniteStateMachine} from '../finite-state-machine';
import {FocusHistory} from '../focus-history';
import {Pass} from '../pass';
import {READY_SCAN_SIGNAL, ResourcesInterface} from './resources-interface';
import {Resource, ResourceState} from './resource';
import {Services} from '../services';
import {TaskQueue} from './task-queue';
import {VisibilityState} from '../visibility-state';
import {dev, devAssert} from '../log';
import {dict} from '../utils/object';
import {expandLayoutRect} from '../layout-rect';
import {getMode} from '../mode';
import {getSourceUrl} from '../url';
import {hasNextNodeInDocumentOrder, isIframed} from '../dom';
import {checkAndFix as ieMediaCheckAndFix} from './ie-media-bug';
import {isBlockedByConsent, reportError} from '../error';
import {isExperimentOn} from '../experiments';
import {listen, loadPromise} from '../event-helper';
import {registerServiceBuilderForDoc} from '../service';
import {remove} from '../utils/array';
import {startupChunk} from '../chunk';
import {throttle} from '../utils/rate-limit';
const TAG_ = 'Resources';
const LAYOUT_TASK_ID_ = 'L';
const LAYOUT_TASK_OFFSET_ = 0;
const PRELOAD_TASK_ID_ = 'P';
const PRELOAD_TASK_OFFSET_ = 2;
const PRIORITY_BASE_ = 10;
const PRIORITY_PENALTY_TIME_ = 1000;
const POST_TASK_PASS_DELAY_ = 1000;
const MUTATE_DEFER_DELAY_ = 500;
const FOCUS_HISTORY_TIMEOUT_ = 1000 * 60; // 1min
const FOUR_FRAME_DELAY_ = 70;
/**
* @implements {ResourcesInterface}
*/
export class ResourcesImpl {
/**
* @param {!./ampdoc-impl.AmpDoc} ampdoc
*/
constructor(ampdoc) {
/** @const {!./ampdoc-impl.AmpDoc} */
this.ampdoc = ampdoc;
/** @const {!Window} */
this.win = ampdoc.win;
/** @const @private {!./viewer-interface.ViewerInterface} */
this.viewer_ = Services.viewerForDoc(ampdoc);
/** @private {boolean} */
this.isRuntimeOn_ = this.viewer_.isRuntimeOn();
/**
* Used primarily for testing to allow build phase to proceed.
* @const @private {boolean}
*/
this.isBuildOn_ = false;
/** @private {number} */
this.resourceIdCounter_ = 0;
/** @private @const {!Array<!Resource>} */
this.resources_ = [];
/** @private {number} */
this.addCount_ = 0;
/** @private {number} */
this.buildAttemptsCount_ = 0;
/** @private {boolean} */
this.visible_ = this.ampdoc.isVisible();
/** @private {number} */
this.prerenderSize_ = this.viewer_.getPrerenderSize();
/** @private {boolean} */
this.documentReady_ = false;
/**
* We want to do some work in the first pass after
* the document is ready.
* @private {boolean}
*/
this.firstPassAfterDocumentReady_ = true;
/**
* Whether AMP has been fully initialized.
* @private {boolean}
*/
this.ampInitialized_ = false;
/**
* We also adjust the timeout penalty shortly after the first pass.
* @private {number}
*/
this.firstVisibleTime_ = -1;
/** @private {boolean} */
this.relayoutAll_ = true;
/**
* @private {number}
*/
this.relayoutTop_ = -1;
/** @private {time} */
this.lastScrollTime_ = 0;
/** @private {number} */
this.lastVelocity_ = 0;
/** @const @private {!Pass} */
this.pass_ = new Pass(this.win, () => this.doPass());
/** @const @private {!Pass} */
this.remeasurePass_ = new Pass(this.win, () => {
// With IntersectionObserver, "remeasuring" hack no longer needed.
devAssert(!this.intersectionObserver_);
this.relayoutAll_ = true;
this.schedulePass();
});
/** @const {!TaskQueue} */
this.exec_ = new TaskQueue();
/** @const {!TaskQueue} */
this.queue_ = new TaskQueue();
/** @const {!function(./task-queue.TaskDef, !Object<string, *>):number} */
this.boundTaskScorer_ = this.calcTaskScore_.bind(this);
/**
* @private {!Array<!./resources-interface.ChangeSizeRequestDef>}
*/
this.requestsChangeSize_ = [];
/** @private {?Array<!Resource>} */
this.pendingBuildResources_ = [];
/** @private {boolean} */
this.isCurrentlyBuildingPendingResources_ = false;
/** @private @const {!./viewport/viewport-interface.ViewportInterface} */
this.viewport_ = Services.viewportForDoc(this.ampdoc);
/** @private @const {!./vsync-impl.Vsync} */
this.vsync_ = Services./*OK*/ vsyncFor(this.win);
/** @private @const {!FocusHistory} */
this.activeHistory_ = new FocusHistory(this.win, FOCUS_HISTORY_TIMEOUT_);
/** @private {boolean} */
this.vsyncScheduled_ = false;
/** @private {number} */
this.contentHeight_ = 0;
/** @private {boolean} */
this.maybeChangeHeight_ = false;
/** @const @private {!Array<function()>} */
this.passCallbacks_ = [];
/** @const @private {!Array<!Element>} */
this.elementsThatScrolled_ = [];
/** @const @private {!Deferred} */
this.firstPassDone_ = new Deferred();
/** @private @const {!FiniteStateMachine<!VisibilityState>} */
this.visibilityStateMachine_ = new FiniteStateMachine(
this.ampdoc.getVisibilityState()
);
/** @private {?IntersectionObserver} */
this.intersectionObserver_ = null;
/**
* True if the callback for intersectionObserver_ has fired at least once.
* @private {boolean}
*/
this.intersectionObserverCallbackFired_ = false;
if (isExperimentOn(this.win, 'intersect-resources')) {
const iframed = isIframed(this.win);
// Classic IntersectionObserver doesn't support viewport tracking and
// rootMargin in x-origin iframes (#25428). As of 1/2020, only Chrome 81+
// supports it via {root: document}, which throws on other browsers.
const root = /** @type {?Element} */ (this.ampdoc.isSingleDoc() && iframed
? /** @type {*} */ (this.win.document)
: null);
try {
this.intersectionObserver_ = new IntersectionObserver(
(e) => this.intersects_(e),
{root, rootMargin: '200% 25%'}
);
// Wait for intersection callback instead of measuring all elements
// during the first pass.
this.relayoutAll_ = false;
} catch (e) {
dev().warn(TAG_, 'Falling back to classic Resources:', e);
}
}
// When user scrolling stops, run pass to check newly in-viewport elements.
// When viewport is resized, we have to re-measure everything.
this.viewport_.onChanged((event) => {
this.lastScrollTime_ = Date.now();
this.lastVelocity_ = event.velocity;
if (event.relayoutAll) {
this.relayoutAll_ = true;
this.maybeChangeHeight_ = true;
}
// With IntersectionObserver, we only need to handle viewport resize.
if (this.relayoutAll_ || !this.intersectionObserver_) {
this.schedulePass();
}
});
this.viewport_.onScroll(() => {
this.lastScrollTime_ = Date.now();
});
// When document becomes visible, e.g. from "prerender" mode, do a
// simple pass.
this.ampdoc.onVisibilityChanged(() => {
if (this.firstVisibleTime_ == -1 && this.ampdoc.isVisible()) {
this.firstVisibleTime_ = Date.now();
}
this.schedulePass();
});
this.viewer_.onRuntimeState((state) => {
dev().fine(TAG_, 'Runtime state:', state);
this.isRuntimeOn_ = state;
this.schedulePass(1);
});
// Schedule initial passes. This must happen in a startup task
// to avoid blocking body visible.
startupChunk(this.ampdoc, () => {
this.setupVisibilityStateMachine_(this.visibilityStateMachine_);
this.schedulePass(0);
});
this.rebuildDomWhenReady_();
if (
!this.intersectionObserver_ &&
isExperimentOn(this.win, 'layoutbox-invalidate-on-scroll')
) {
/** @private @const */
this.throttledScroll_ = throttle(this.win, (e) => this.scrolled_(e), 250);
listen(this.win.document, 'scroll', this.throttledScroll_, {
capture: true,
passive: true,
});
}
}
/** @override */
isIntersectionExperimentOn() {
return !!this.intersectionObserver_;
}
/**
* @param {!Array<!IntersectionObserverEntry>} entries
* @private
*/
intersects_(entries) {
devAssert(this.intersectionObserver_);
// TODO(willchou): Remove assert once #27167 is fixed.
devAssert(this.prerenderSize_ == 1);
if (getMode().localDev) {
const inside = [];
const outside = [];
entries.forEach((e) => {
const r = Resource.forElement(e.target);
(e.isIntersecting ? inside : outside).push({e, id: r.debugid});
});
dev().fine(TAG_, 'intersection', inside, outside);
}
this.intersectionObserverCallbackFired_ = true;
entries.forEach((entry) => {
const {boundingClientRect, target} = entry;
const r = Resource.forElement(target);
// Strangely, JSC is missing x/y from typedefs of boundingClientRect
// despite it being a DOMRectReadOnly (ClientRect) by spec.
r.premeasure(/** @type {!ClientRect} */ (boundingClientRect));
});
this.schedulePass();
}
/** @private */
rebuildDomWhenReady_() {
// Ensure that we attempt to rebuild things when DOM is ready.
this.ampdoc.whenReady().then(() => {
this.documentReady_ = true;
this.buildReadyResources_();
this.pendingBuildResources_ = null;
const input = Services.inputFor(this.win);
input.setupInputModeClasses(this.ampdoc);
// With IntersectionObserver, no need for remeasuring hacks.
if (!this.intersectionObserver_) {
const fixPromise = ieMediaCheckAndFix(this.win);
const remeasure = () => this.remeasurePass_.schedule();
if (fixPromise) {
fixPromise.then(remeasure);
} else {
// No promise means that there's no problem.
remeasure();
}
// Safari 10 and under incorrectly estimates font spacing for
// `@font-face` fonts. This leads to wild measurement errors. The best
// course of action is to remeasure everything on window.onload or font
// timeout (3s), whichever is earlier. This has to be done on the global
// window because this is where the fonts are always added.
// Unfortunately, `document.fonts.ready` cannot be used here due to
// https://bugs.webkit.org/show_bug.cgi?id=174030.
// See https://bugs.webkit.org/show_bug.cgi?id=174031 for more details.
Promise.race([
loadPromise(this.win),
Services.timerFor(this.win).promise(3100),
]).then(remeasure);
// Remeasure the document when all fonts loaded.
if (
this.win.document.fonts &&
this.win.document.fonts.status != 'loaded'
) {
this.win.document.fonts.ready.then(remeasure);
}
}
});
}
/** @override */
get() {
return this.resources_.slice(0);
}
/** @override */
getAmpdoc() {
return this.ampdoc;
}
/** @override */
getResourceForElement(element) {
return Resource.forElement(element);
}
/** @override */
getResourceForElementOptional(element) {
return Resource.forElementOptional(element);
}
/** @override */
getScrollDirection() {
return Math.sign(this.lastVelocity_) || 1;
}
/** @override */
add(element) {
// Ensure the viewport is ready to accept the first element.
this.addCount_++;
if (this.addCount_ == 1) {
this.viewport_.ensureReadyForElements();
}
// First check if the resource is being reparented and if it requires
// reconstruction. Only already built elements are eligible.
let resource = Resource.forElementOptional(element);
if (
resource &&
resource.getState() != ResourceState.NOT_BUILT &&
!element.reconstructWhenReparented()
) {
// With IntersectionObserver, no need to request remeasure
// on reuse since initial intersection callback will trigger soon.
if (!this.intersectionObserver_) {
resource.requestMeasure();
}
dev().fine(TAG_, 'resource reused:', resource.debugid);
} else {
// Create and add a new resource.
resource = new Resource(++this.resourceIdCounter_, element, this);
dev().fine(TAG_, 'resource added:', resource.debugid);
}
this.resources_.push(resource);
if (this.intersectionObserver_) {
// The observer callback will schedule a pass to process this element.
this.intersectionObserver_.observe(element);
} else {
this.remeasurePass_.schedule(1000);
}
}
/**
* Limits the number of elements being build in pre-render phase to
* a finite number. Returns false if the number has been reached.
* @return {boolean}
*/
isUnderBuildQuota_() {
// For pre-render we want to limit the amount of CPU used, so we limit
// the number of elements build. For pre-render to "seem complete"
// we only need to build elements in the first viewport. We can't know
// which are actually in the viewport (because the decision is pre-layout,
// so we use a heuristic instead.
// Most documents have 10 or less AMP tags. By building 20 we should not
// change the behavior for the vast majority of docs, and almost always
// catch everything in the first viewport.
return this.buildAttemptsCount_ < 20 || this.ampdoc.hasBeenVisible();
}
/**
* Builds the element if ready to be built, otherwise adds it to pending
* resources.
* @param {!Resource} resource
* @param {boolean=} checkForDupes
* @param {boolean=} ignoreQuota
* @private
*/
buildOrScheduleBuildForResource_(
resource,
checkForDupes = false,
ignoreQuota = false
) {
const buildingEnabled = this.isRuntimeOn_ || this.isBuildOn_;
// During prerender mode, don't build elements that aren't allowed to be
// prerendered. This avoids wasting our prerender build quota.
// See isUnderBuildQuota_() for more details.
const shouldBuildResource =
this.ampdoc.getVisibilityState() != VisibilityState.PRERENDER ||
resource.prerenderAllowed();
if (buildingEnabled && shouldBuildResource) {
if (this.documentReady_) {
// Build resource immediately, the document has already been parsed.
this.buildResourceUnsafe_(resource, ignoreQuota);
} else if (!resource.isBuilt() && !resource.isBuilding()) {
if (!checkForDupes || !this.pendingBuildResources_.includes(resource)) {
// Otherwise add to pending resources and try to build any ready ones.
this.pendingBuildResources_.push(resource);
this.buildReadyResources_();
}
}
}
}
/**
* Builds resources that are ready to be built.
* @private
*/
buildReadyResources_() {
// Avoid cases where elements add more elements inside of them
// and cause an infinite loop of building - see #3354 for details.
if (this.isCurrentlyBuildingPendingResources_) {
return;
}
try {
this.isCurrentlyBuildingPendingResources_ = true;
this.buildReadyResourcesUnsafe_();
} finally {
this.isCurrentlyBuildingPendingResources_ = false;
}
}
/**
* @private
*/
buildReadyResourcesUnsafe_() {
// This will loop over all current pending resources and those that
// get added by other resources build-cycle, this will make sure all
// elements get a chance to be built.
for (let i = 0; i < this.pendingBuildResources_.length; i++) {
const resource = this.pendingBuildResources_[i];
if (
this.documentReady_ ||
hasNextNodeInDocumentOrder(resource.element, this.ampdoc.getRootNode())
) {
// Remove resource before build to remove it from the pending list
// in either case the build succeed or throws an error.
this.pendingBuildResources_.splice(i--, 1);
this.buildResourceUnsafe_(resource);
}
}
}
/**
* @param {!Resource} resource
* @param {boolean=} ignoreQuota
* @return {?Promise}
* @private
*/
buildResourceUnsafe_(resource, ignoreQuota = false) {
if (
!this.isUnderBuildQuota_() &&
!ignoreQuota &&
// Special case: amp-experiment is allowed to bypass prerender build quota.
!resource.isBuildRenderBlocking()
) {
return null;
}
const promise = resource.build();
if (!promise) {
return null;
}
dev().fine(TAG_, 'build resource:', resource.debugid);
this.buildAttemptsCount_++;
return promise.then(
() => this.schedulePass(),
(error) => {
// Build failed: remove the resource. No other state changes are
// needed.
this.removeResource_(resource);
if (!isBlockedByConsent(error)) {
throw error;
}
}
);
}
/** @override */
remove(element) {
const resource = Resource.forElementOptional(element);
if (!resource) {
return;
}
this.removeResource_(resource);
}
/**
* @param {!Resource} resource
* @private
*/
removeResource_(resource) {
const index = this.resources_.indexOf(resource);
if (index != -1) {
this.resources_.splice(index, 1);
}
if (resource.isBuilt()) {
resource.pauseOnRemove();
}
if (this.intersectionObserver_) {
// TODO(willchou): Fix observe/unobserve churn due to reparenting.
this.intersectionObserver_.unobserve(resource.element);
}
this.cleanupTasks_(resource, /* opt_removePending */ true);
dev().fine(TAG_, 'resource removed:', resource.debugid);
}
/** @override */
upgraded(element) {
const resource = Resource.forElement(element);
// TODO(willchou): Delay this until after 1vp loads. This should improve
// LCP and be safe since we already do something similar in prerender mode.
this.buildOrScheduleBuildForResource_(resource);
dev().fine(TAG_, 'resource upgraded:', resource.debugid);
}
/** @override */
updateLayoutPriority(element, newLayoutPriority) {
const resource = Resource.forElement(element);
resource.updateLayoutPriority(newLayoutPriority);
// Update affected tasks
this.queue_.forEach((task) => {
if (task.resource == resource) {
task.priority = newLayoutPriority;
}
});
this.schedulePass();
}
/** @override */
schedulePass(opt_delay) {
return this.pass_.schedule(opt_delay);
}
/** @override */
updateOrEnqueueMutateTask(resource, newRequest) {
let request = null;
for (let i = 0; i < this.requestsChangeSize_.length; i++) {
if (this.requestsChangeSize_[i].resource == resource) {
request = this.requestsChangeSize_[i];
break;
}
}
if (request) {
request.newHeight = newRequest.newHeight;
request.newWidth = newRequest.newWidth;
request.marginChange = newRequest.marginChange;
request.event = newRequest.event;
request.force = newRequest.force || request.force;
request.callback = newRequest.callback;
} else {
this.requestsChangeSize_.push(newRequest);
}
}
/** @override */
schedulePassVsync() {
if (this.vsyncScheduled_) {
return;
}
this.vsyncScheduled_ = true;
this.vsync_.mutate(() => this.doPass());
}
/** @override */
ampInitComplete() {
this.ampInitialized_ = true;
this.maybeChangeHeight_ = true;
dev().fine(TAG_, 'ampInitComplete');
this.schedulePass();
}
/** @override */
setRelayoutTop(relayoutTop) {
if (this.relayoutTop_ == -1) {
this.relayoutTop_ = relayoutTop;
} else {
this.relayoutTop_ = Math.min(relayoutTop, this.relayoutTop_);
}
}
/** @override */
maybeHeightChanged() {
this.maybeChangeHeight_ = true;
}
/** @override */
onNextPass(callback) {
this.passCallbacks_.push(callback);
}
/**
* Runs a pass immediately.
*
* @visibleForTesting
*/
doPass() {
if (!this.isRuntimeOn_) {
dev().fine(TAG_, 'runtime is off');
return;
}
this.visible_ = this.ampdoc.isVisible();
this.prerenderSize_ = this.viewer_.getPrerenderSize();
const firstPassAfterDocumentReady =
this.documentReady_ && this.firstPassAfterDocumentReady_;
if (firstPassAfterDocumentReady) {
this.firstPassAfterDocumentReady_ = false;
const doc = this.win.document;
const documentInfo = Services.documentInfoForDoc(this.ampdoc);
// TODO(choumx, #26687): Update viewers to read data.viewport instead of
// data.metaTags.viewport from 'documentLoaded' message.
this.viewer_.sendMessage(
'documentLoaded',
dict({
'title': doc.title,
'sourceUrl': getSourceUrl(this.ampdoc.getUrl()),
'serverLayout': doc.documentElement.hasAttribute('i-amphtml-element'),
'linkRels': documentInfo.linkRels,
'metaTags': {'viewport': documentInfo.viewport} /* deprecated */,
'viewport': documentInfo.viewport,
}),
/* cancelUnsent */ true
);
this.contentHeight_ = this.viewport_.getContentHeight();
this.viewer_.sendMessage(
'documentHeight',
dict({'height': this.contentHeight_}),
/* cancelUnsent */ true
);
dev().fine(TAG_, 'document height on load: %s', this.contentHeight_);
}
const viewportSize = this.viewport_.getSize();
dev().fine(
TAG_,
'PASS: visible=',
this.visible_,
', relayoutAll=',
this.relayoutAll_,
', relayoutTop=',
this.relayoutTop_,
', viewportSize=',
viewportSize.width,
viewportSize.height,
', prerenderSize=',
this.prerenderSize_
);
this.pass_.cancel();
this.vsyncScheduled_ = false;
this.visibilityStateMachine_.setState(this.ampdoc.getVisibilityState());
this.signalIfReady_();
if (this.maybeChangeHeight_) {
this.maybeChangeHeight_ = false;
this.vsync_.measure(() => {
const measuredContentHeight = this.viewport_.getContentHeight();
if (measuredContentHeight != this.contentHeight_) {
this.viewer_.sendMessage(
'documentHeight',
dict({'height': measuredContentHeight}),
/* cancelUnsent */ true
);
this.contentHeight_ = measuredContentHeight;
dev().fine(TAG_, 'document height changed: %s', this.contentHeight_);
this.viewport_.contentHeightChanged();
}
});
}
for (let i = 0; i < this.passCallbacks_.length; i++) {
const fn = this.passCallbacks_[i];
fn();
}
this.passCallbacks_.length = 0;
}
/**
* If (1) the document is fully parsed, (2) the AMP runtime (services etc.)
* is initialized, and (3) we did a first pass on element measurements,
* then fire the "ready" signal.
* @private
*/
signalIfReady_() {
if (
this.documentReady_ &&
this.ampInitialized_ &&
// With IntersectionObserver, elements are not measured until the first
// intersection callback.
(!this.intersectionObserver_ ||
this.intersectionObserverCallbackFired_) &&
!this.ampdoc.signals().get(READY_SCAN_SIGNAL)
) {
// This signal mainly signifies that most of elements have been measured
// by now. This is mostly used to avoid measuring too many elements
// individually. May not be called in shadow mode.
this.ampdoc.signals().signal(READY_SCAN_SIGNAL);
dev().fine(TAG_, 'signal: ready-scan');
}
}
/**
* Returns `true` when there's mutate work currently batched.
* @return {boolean}
* @private
*/
hasMutateWork_() {
return this.requestsChangeSize_.length > 0;
}
/**
* Performs pre-discovery mutates.
* @private
*/
mutateWork_() {
// Read all necessary data before mutates.
// The height changing depends largely on the target element's position
// in the active viewport. When not in prerendering, we also consider the
// active viewport the part of the visible viewport below 10% from the top
// and above 25% from the bottom.
// This is basically the portion of the viewport where the reader is most
// likely focused right now. The main goal is to avoid drastic UI changes
// in that part of the content. The elements below the active viewport are
// freely resized. The elements above the viewport are resized and request
// scroll adjustment to avoid active viewport changing without user's
// action. The elements in the active viewport are not resized and instead
// the overflow callbacks are called.
const now = Date.now();
const viewportRect = this.viewport_.getRect();
const topOffset = viewportRect.height / 10;
const bottomOffset = viewportRect.height / 10;
const isScrollingStopped =
(Math.abs(this.lastVelocity_) < 1e-2 &&
now - this.lastScrollTime_ > MUTATE_DEFER_DELAY_) ||
now - this.lastScrollTime_ > MUTATE_DEFER_DELAY_ * 2;
if (this.requestsChangeSize_.length > 0) {
dev().fine(
TAG_,
'change size requests:',
this.requestsChangeSize_.length
);
const requestsChangeSize = this.requestsChangeSize_;
this.requestsChangeSize_ = [];
// Find minimum top position and run all mutates.
let minTop = -1;
const scrollAdjSet = [];
let aboveVpHeightChange = 0;
for (let i = 0; i < requestsChangeSize.length; i++) {
const request = requestsChangeSize[i];
const {
resource,
event,
} = /** @type {!./resources-interface.ChangeSizeRequestDef} */ (request);
const box = resource.getLayoutBox();
let topMarginDiff = 0;
let bottomMarginDiff = 0;
let leftMarginDiff = 0;
let rightMarginDiff = 0;
let {top: topUnchangedBoundary, bottom: bottomDisplacedBoundary} = box;
let newMargins = undefined;
if (request.marginChange) {
newMargins = request.marginChange.newMargins;
const margins = request.marginChange.currentMargins;
if (newMargins.top != undefined) {
topMarginDiff = newMargins.top - margins.top;
}
if (newMargins.bottom != undefined) {
bottomMarginDiff = newMargins.bottom - margins.bottom;
}
if (newMargins.left != undefined) {
leftMarginDiff = newMargins.left - margins.left;
}
if (newMargins.right != undefined) {
rightMarginDiff = newMargins.right - margins.right;
}
if (topMarginDiff) {
topUnchangedBoundary = box.top - margins.top;
}
if (bottomMarginDiff) {
// The lowest boundary of the element that would appear to be
// resized as a result of this size change. If the bottom margin is
// being changed then it is the bottom edge of the margin box,
// otherwise it is the bottom edge of the layout box as set above.
bottomDisplacedBoundary = box.bottom + margins.bottom;
}
}
const heightDiff = request.newHeight - box.height;
const widthDiff = request.newWidth - box.width;
// Check resize rules. It will either resize element immediately, or
// wait until scrolling stops or will call the overflow callback.
let resize = false;
if (
heightDiff == 0 &&
topMarginDiff == 0 &&
bottomMarginDiff == 0 &&
widthDiff == 0 &&
leftMarginDiff == 0 &&
rightMarginDiff == 0
) {
// 1. Nothing to resize.
} else if (request.force || !this.visible_) {
// 2. An immediate execution requested or the document is hidden.
resize = true;
} else if (
this.activeHistory_.hasDescendantsOf(resource.element) ||
(event && event.userActivation && event.userActivation.hasBeenActive)
) {
// 3. Active elements are immediately resized. The assumption is that
// the resize is triggered by the user action or soon after.
resize = true;
} else if (
topUnchangedBoundary >= viewportRect.bottom - bottomOffset ||
(topMarginDiff == 0 &&
box.bottom + Math.min(heightDiff, 0) >=
viewportRect.bottom - bottomOffset)
) {
// 4. Elements under viewport are resized immediately, but only if
// an element's boundary is not changed above the viewport after
// resize.
resize = true;
} else if (
viewportRect.top > 1 &&
bottomDisplacedBoundary <= viewportRect.top + topOffset
) {
// 5. Elements above the viewport can only be resized if we are able
// to compensate the height change by setting scrollTop and only if
// the page has already been scrolled by some amount (1px due to iOS).
// Otherwise the scrolling might move important things like the menu
// bar out of the viewport at initial page load.
if (
heightDiff < 0 &&
viewportRect.top + aboveVpHeightChange < -heightDiff
) {
// Do nothing if height abobe viewport height can't compensate
// height decrease
continue;
}
// Can only resized when scrolling has stopped,
// otherwise defer util next cycle.
if (isScrollingStopped) {
// These requests will be executed in the next animation cycle and
// adjust the scroll position.
aboveVpHeightChange = aboveVpHeightChange + heightDiff;
scrollAdjSet.push(request);
} else {
// Defer till next cycle.
this.requestsChangeSize_.push(request);
}
continue;
} else if (this.elementNearBottom_(resource, box)) {
// 6. Elements close to the bottom of the document (not viewport)
// are resized immediately.
resize = true;
} else if (
heightDiff < 0 ||
topMarginDiff < 0 ||
bottomMarginDiff < 0
) {
// 7. The new height (or one of the margins) is smaller than the
// current one.
} else if (request.newHeight == box.height) {
// 8. Element is in viewport, but this is a width-only expansion.
// Check whether this should be reflow-free, in which case,
// schedule a size change.
this.vsync_.run(
{
measure: (state) => {
state.resize = false;
const parent = resource.element.parentElement;
if (!parent) {
return;
}
// If the element has siblings, it's possible that a width-expansion will
// cause some of them to be pushed down.
const parentWidth =
(parent.getLayoutWidth && parent.getLayoutWidth()) ||
parent./*OK*/ offsetWidth;
let cumulativeWidth = widthDiff;
for (let i = 0; i < parent.childElementCount; i++) {
cumulativeWidth += parent.children[i]./*OK*/ offsetWidth;
if (cumulativeWidth > parentWidth) {
return;
}
}
state.resize = true;
},
mutate: (state) => {
if (state.resize) {
request.resource.changeSize(
request.newHeight,
request.newWidth,
newMargins
);
}
request.resource.overflowCallback(
/* overflown */ !state.resize,
request.newHeight,
request.newWidth,
newMargins
);
},
},
{}
);
} else {
// 9. Element is in viewport don't resize and try overflow callback
// instead.
request.resource.overflowCallback(