/
resources-impl.js
2347 lines (2143 loc) · 77.5 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 {CommonSignals} from '../common-signals';
import {FiniteStateMachine} from '../finite-state-machine';
import {FocusHistory} from '../focus-history';
import {Pass} from '../pass';
import {Resource, ResourceState} from './resource';
import {Services} from '../services';
import {TaskQueue} from './task-queue';
import {VisibilityState} from '../visibility-state';
import {areMarginsChanged, expandLayoutRect} from '../layout-rect';
import {closest, hasNextNodeInDocumentOrder} from '../dom';
import {computedStyle} from '../style';
import {dev} from '../log';
import {dict, hasOwn} from '../utils/object';
import {filterSplice} from '../utils/array';
import {getSourceUrl} from '../url';
import {checkAndFix as ieMediaCheckAndFix} from './ie-media-bug';
import {isArray} from '../types';
import {isBlockedByConsent, reportError} from '../error';
import {isExperimentOn} from '../experiments';
import {loadPromise} from '../event-helper';
import {registerServiceBuilderForDoc} from '../service';
import {tryResolve} from '../utils/promise';
const TAG_ = 'Resources';
const READY_SCAN_SIGNAL_ = 'ready-scan';
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;
/**
* The internal structure of a ChangeHeightRequest.
* @typedef {{
* newMargins: !../layout-rect.LayoutMarginsChangeDef,
* currentMargins: !../layout-rect.LayoutMarginsDef
* }}
*/
let MarginChangeDef;
/**
* The internal structure of a ChangeHeightRequest.
* @typedef {{
* resource: !Resource,
* newHeight: (number|undefined),
* newWidth: (number|undefined),
* marginChange: (!MarginChangeDef|undefined),
* force: boolean,
* callback: (function(boolean)|undefined)
* }}
*/
let ChangeSizeRequestDef;
export class Resources {
/**
* @param {!./ampdoc-impl.AmpDoc} ampdoc
*/
constructor(ampdoc) {
/** @const {!./ampdoc-impl.AmpDoc} */
this.ampdoc = ampdoc;
/** @const {!Window} */
this.win = ampdoc.win;
/** @const @private {!./viewer-impl.Viewer} */
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 @const {number} */
this.maxDpr_ = this.win.devicePixelRatio || 1;
/** @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.viewer_.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;
/**
* TODO(jridgewell): relayoutTop should be replaced with parent layer
* dirtying.
* @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, () => {
this.relayoutAll_ = true;
this.schedulePass();
});
/** @const {!TaskQueue} */
this.exec_ = new TaskQueue();
/** @const {!TaskQueue} */
this.queue_ = new TaskQueue();
/** @private @const {boolean} */
this.useLayers_ = isExperimentOn(this.win, 'layers');
let boundScorer;
if (this.useLayers_) {
boundScorer = this.calcTaskScoreLayers_.bind(this);
} else {
boundScorer = this.calcTaskScore_.bind(this);
}
/** @const {!function(./task-queue.TaskDef, !Object<string, *>):number} */
this.boundTaskScorer_ = boundScorer;
/**
* @private {!Array<!ChangeSizeRequestDef>}
*/
this.requestsChangeSize_ = [];
/** @private {?Array<!Resource>} */
this.pendingBuildResources_ = [];
/** @private {boolean} */
this.isCurrentlyBuildingPendingResources_ = false;
/** @private @const {!./viewport/viewport-impl.Viewport} */
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;
/** @private @const {!FiniteStateMachine<!VisibilityState>} */
this.visibilityStateMachine_ = new FiniteStateMachine(
this.viewer_.getVisibilityState()
);
this.setupVisibilityStateMachine_(this.visibilityStateMachine_);
// When viewport is resized, we have to re-measure all elements.
this.viewport_.onChanged(event => {
this.lastScrollTime_ = Date.now();
this.lastVelocity_ = event.velocity;
if (event.relayoutAll) {
this.relayoutAll_ = true;
this.maybeChangeHeight_ = true;
}
this.schedulePass();
});
this.viewport_.onScroll(() => {
this.lastScrollTime_ = Date.now();
});
if (this.useLayers_) {
const layers = Services.layersForDoc(this.ampdoc);
/** @private @const {!./layers-impl.LayoutLayers} */
this.layers_ = layers;
layers.onScroll((/* elements */) => {
this.schedulePass();
});
/** @private @const {function((number|undefined), !./layers-impl.LayoutElement, number, !Object<string, *>):number} */
this.boundCalcLayoutScore_ = this.calcLayoutScore_.bind(this);
}
// When document becomes visible, e.g. from "prerender" mode, do a
// simple pass.
this.viewer_.onVisibilityChanged(() => {
if (this.firstVisibleTime_ == -1 && this.viewer_.isVisible()) {
this.firstVisibleTime_ = Date.now();
}
this.schedulePass();
});
this.viewer_.onRuntimeState(state => {
dev().fine(TAG_, 'Runtime state:', state);
this.isRuntimeOn_ = state;
this.schedulePass(1);
});
this.activeHistory_.onFocus(element => {
this.checkPendingChangeSize_(element);
});
this.schedulePass();
this.rebuildDomWhenReady();
}
/** @visibleForTesting */
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 fixPromise = ieMediaCheckAndFix(this.win);
const remeasure = () => this.remeasurePass_.schedule();
if (fixPromise) {
fixPromise.then(remeasure);
} else {
// No promise means that there's no problem.
remeasure();
}
this.monitorInput_();
// 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);
}
});
}
/**
* Returns a list of resources.
* @return {!Array<!Resource>}
* @export
*/
get() {
return this.resources_.slice(0);
}
/**
* Whether the runtime is currently on.
* @return {boolean}
*/
isRuntimeOn() {
return this.isRuntimeOn_;
}
/**
* Signals that the document has been started rendering.
* @restricted
*/
renderStarted() {
this.ampdoc.signals().signal(CommonSignals.RENDER_START);
}
/**
* Returns a subset of resources which are (1) belong to the specified host
* window, and (2) meet the filterFn given.
* @param {!Window} hostWin
* @param {function(!Resource):boolean} filterFn
* @return {!Promise<!Array<!Resource>>}
*/
getMeasuredResources(hostWin, filterFn) {
// First, wait for the `ready-scan` signal. Waiting for each element
// individually is too expensive and `ready-scan` will cover most of
// the initially parsed elements.
// TODO(jridgewell): this path should be switched to use a future
// "layer has been measured" signal.
return this.ampdoc.signals().whenSignal(READY_SCAN_SIGNAL_).then(() => {
// Second, wait for any left-over elements to complete measuring.
const measurePromiseArray = [];
this.resources_.forEach(r => {
if (!r.hasBeenMeasured() && r.hostWin == hostWin && !r.hasOwner()) {
measurePromiseArray.push(this.ensuredMeasured_(r));
}
});
return Promise.all(measurePromiseArray);
}).then(() => this.resources_.filter(r => {
return r.hostWin == hostWin && !r.hasOwner() && r.hasBeenMeasured() &&
filterFn(r);
}));
}
/**
* Returns a subset of resources which are (1) belong to the specified host
* window, and (2) positioned in the specified rect.
* @param {!Window} hostWin
* @param {!../layout-rect.LayoutRectDef} rect
* @param {boolean=} opt_isInPrerender signifies if we are in prerender mode.
* @return {!Promise<!Array<!Resource>>}
*/
getResourcesInRect(hostWin, rect, opt_isInPrerender) {
return this.getMeasuredResources(hostWin, r => {
// TODO(jridgewell): Remove isFixed check here once the position
// is calculted correctly in a separate layer for embeds.
if (!r.isDisplayed() || (!r.overlaps(rect) && !r.isFixed()) ||
(opt_isInPrerender && !r.prerenderAllowed())) {
return false;
}
return true;
});
}
/** @private */
monitorInput_() {
const input = Services.inputFor(this.win);
input.onTouchDetected(detected => {
this.toggleInputClass_('amp-mode-touch', detected);
}, true);
input.onMouseDetected(detected => {
this.toggleInputClass_('amp-mode-mouse', detected);
}, true);
input.onKeyboardStateChanged(active => {
this.toggleInputClass_('amp-mode-keyboard-active', active);
}, true);
}
/**
* @param {string} clazz
* @param {boolean} on
* @private
*/
toggleInputClass_(clazz, on) {
this.ampdoc.whenBodyAvailable().then(body => {
this.vsync_.mutate(() => {
body.classList.toggle(clazz, on);
});
});
}
/**
* Returns the maximum DPR available on this device.
* @return {number}
*/
getMaxDpr() {
return this.maxDpr_;
}
/**
* Returns the most optimal DPR currently recommended.
* @return {number}
*/
getDpr() {
// TODO(dvoytenko): return optimal DPR.
return this.maxDpr_;
}
/**
* Returns the {@link Resource} instance corresponding to the specified AMP
* Element. If no Resource is found, the exception is thrown.
* @param {!AmpElement} element
* @return {!Resource}
*/
getResourceForElement(element) {
return Resource.forElement(element);
}
/**
* Returns the {@link Resource} instance corresponding to the specified AMP
* Element. Returns null if no resource is found.
* @param {!AmpElement} element
* @return {?Resource}
*/
getResourceForElementOptional(element) {
return Resource.forElementOptional(element);
}
/**
* Returns a promise to the layoutBox for the element. If the element is
* resource-backed then makes use of the resource layoutBox, otherwise
* measures the element directly.
* @param {!Element} element
* @return {!Promise<!../layout-rect.LayoutRectDef>}
*/
getElementLayoutBox(element) {
const resource = this.getResourceForElementOptional(element);
if (resource) {
return this.ensuredMeasured_(resource);
}
return this.vsync_.measurePromise(() => {
return this.getViewport().getLayoutRect(element);
});
}
/**
* @param {!Resource} resource
* @return {!Promise<!../layout-rect.LayoutRectDef>}
* @private
*/
ensuredMeasured_(resource) {
if (resource.hasBeenMeasured()) {
return tryResolve(() => resource.getPageLayoutBox());
}
return this.vsync_.measurePromise(() => {
resource.measure();
return resource.getPageLayoutBox();
});
}
/**
* Returns the viewport instance
* @return {!./viewport/viewport-impl.Viewport}
*/
getViewport() {
return this.viewport_;
}
/**
* Returns the direction the user last scrolled.
* - -1 for scrolling up
* - 1 for scrolling down
* - Defaults to 1
* @return {number}
*/
getScrollDirection() {
return Math.sign(this.lastVelocity_) || 1;
}
/**
* Signals that an element has been added to the DOM. Resources manager
* will start tracking it from this point on.
* @param {!AmpElement} element
*/
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()) {
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);
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}
*/
grantBuildPermission() {
// 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.viewer_.hasBeenVisible();
}
/**
* Builds the element if ready to be built, otherwise adds it to pending
* resources.
* @param {!Resource} resource
* @param {boolean=} checkForDupes
* @param {boolean=} scheduleWhenBuilt
* @private
*/
buildOrScheduleBuildForResource_(resource, checkForDupes = false,
scheduleWhenBuilt = true) {
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 grantBuildPermission() for more details.
const shouldBuildResource =
this.viewer_.getVisibilityState() != VisibilityState.PRERENDER
|| resource.prerenderAllowed();
if (buildingEnabled && shouldBuildResource) {
if (this.documentReady_) {
// Build resource immediately, the document has already been parsed.
this.buildResourceUnsafe_(resource, scheduleWhenBuilt);
} 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_(scheduleWhenBuilt);
}
}
}
}
/**
* Builds resources that are ready to be built.
* @param {boolean=} scheduleWhenBuilt
* @private
*/
buildReadyResources_(scheduleWhenBuilt = true) {
// 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_(scheduleWhenBuilt);
} finally {
this.isCurrentlyBuildingPendingResources_ = false;
}
}
/**
* @param {boolean=} scheduleWhenBuilt
* @private
*/
buildReadyResourcesUnsafe_(scheduleWhenBuilt = true) {
// 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, scheduleWhenBuilt);
}
}
}
/**
* @param {!Resource} resource
* @param {boolean} schedulePass
* @return {?Promise}
* @private
*/
buildResourceUnsafe_(resource, schedulePass) {
const promise = resource.build();
if (!promise || !schedulePass) {
return promise;
}
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;
}
});
}
/**
* Signals that an element has been removed to the DOM. Resources manager
* will stop tracking it from this point on.
* @param {!AmpElement} element
*/
remove(element) {
const resource = Resource.forElementOptional(element);
if (!resource) {
return;
}
this.removeResource_(resource);
}
/**
* @param {!Resource} resource
* @param {boolean=} opt_disconnect
* @private
*/
removeResource_(resource, opt_disconnect) {
const index = this.resources_.indexOf(resource);
if (index != -1) {
this.resources_.splice(index, 1);
}
if (resource.isBuilt()) {
resource.pauseOnRemove();
}
if (opt_disconnect) {
resource.disconnect();
}
this.cleanupTasks_(resource, /* opt_removePending */ true);
dev().fine(TAG_, 'element removed:', resource.debugid);
}
/**
* Removes all resources belonging to the specified child window.
* @param {!Window} childWin
*/
removeForChildWindow(childWin) {
const toRemove = this.resources_.filter(r => r.hostWin == childWin);
toRemove.forEach(r => this.removeResource_(r, /* disconnect */ true));
}
/**
* Signals that an element has been upgraded to the DOM. Resources manager
* will perform build and enable layout/viewport signals for this element.
* @param {!AmpElement} element
*/
upgraded(element) {
const resource = Resource.forElement(element);
this.buildOrScheduleBuildForResource_(resource);
dev().fine(TAG_, 'element upgraded:', resource.debugid);
}
/**
* Assigns an owner for the specified element. This means that the resources
* within this element will be managed by the owner and not Resources manager.
* @param {!Element} element
* @param {!AmpElement} owner
* @package
*/
setOwner(element, owner) {
Resource.setOwner(element, owner);
}
/**
* Requires the layout of the specified element or top-level sub-elements
* within.
* @param {!Element} element
* @param {number=} opt_parentPriority
* @return {!Promise}
* @restricted
*/
requireLayout(element, opt_parentPriority) {
const promises = [];
this.discoverResourcesForElement_(element, resource => {
if (resource.getState() == ResourceState.LAYOUT_COMPLETE) {
return;
}
if (resource.getState() != ResourceState.LAYOUT_SCHEDULED) {
promises.push(resource.whenBuilt().then(() => {
resource.measure();
if (!resource.isDisplayed()) {
return;
}
this.scheduleLayoutOrPreload_(
resource,
/* layout */ true,
opt_parentPriority,
/* forceOutsideViewport */ true);
return resource.loadedOnce();
}));
} else if (resource.isDisplayed()) {
promises.push(resource.loadedOnce());
}
});
return Promise.all(promises);
}
/**
* Schedules layout for the specified sub-elements that are children of the
* parent element. The parent element may choose to send this signal either
* because it's an owner (see {@link setOwner}) or because it wants the
* layouts to be done sooner. In either case, both parent's and children's
* priority is observed when scheduling this work.
* @param {!Element} parentElement
* @param {!Element|!Array<!Element>} subElements
*/
scheduleLayout(parentElement, subElements) {
this.scheduleLayoutOrPreloadForSubresources_(
Resource.forElement(parentElement),
/* layout */ true,
elements_(subElements));
}
/**
* Invokes `unload` on the elements' resource which in turn will invoke
* the `documentBecameInactive` callback on the custom element.
* Resources that call `schedulePause` must also call `scheduleResume`.
* @param {!Element} parentElement
* @param {!Element|!Array<!Element>} subElements
*/
schedulePause(parentElement, subElements) {
const parentResource = Resource.forElement(parentElement);
subElements = elements_(subElements);
this.discoverResourcesForArray_(parentResource, subElements, resource => {
resource.pause();
});
}
/**
* Invokes `resume` on the elements' resource which in turn will invoke
* `resumeCallback` only on paused custom elements.
* Resources that call `schedulePause` must also call `scheduleResume`.
* @param {!Element} parentElement
* @param {!Element|!Array<!Element>} subElements
*/
scheduleResume(parentElement, subElements) {
const parentResource = Resource.forElement(parentElement);
subElements = elements_(subElements);
this.discoverResourcesForArray_(parentResource, subElements, resource => {
resource.resume();
});
}
/**
* Schedules unlayout for specified sub-elements that are children of the
* parent element. The parent element can choose to send this signal when
* it want to unload resources for its children.
* @param {!Element} parentElement
* @param {!Element|!Array<!Element>} subElements
*/
scheduleUnlayout(parentElement, subElements) {
const parentResource = Resource.forElement(parentElement);
subElements = elements_(subElements);
this.discoverResourcesForArray_(parentResource, subElements, resource => {
resource.unlayout();
});
}
/**
* Schedules preload for the specified sub-elements that are children of the
* parent element. The parent element may choose to send this signal either
* because it's an owner (see {@link setOwner}) or because it wants the
* preloads to be done sooner. In either case, both parent's and children's
* priority is observed when scheduling this work.
* @param {!Element} parentElement
* @param {!Element|!Array<!Element>} subElements
*/
schedulePreload(parentElement, subElements) {
this.scheduleLayoutOrPreloadForSubresources_(
Resource.forElement(parentElement),
/* layout */ false,
elements_(subElements));
}
/**
* Updates the priority of the resource. If there are tasks currently
* scheduled, their priority is updated as well.
* @param {!Element} element
* @param {number} newLayoutPriority
* @restricted
*/
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();
}
/**
* A parent resource, especially in when it's an owner (see {@link setOwner}),
* may request the Resources manager to update children's inViewport state.
* A child's inViewport state is a logical AND between inLocalViewport
* specified here and parent's own inViewport state.
* @param {!Element} parentElement
* @param {!Element|!Array<!Element>} subElements
* @param {boolean} inLocalViewport
*/
updateInViewport(parentElement, subElements, inLocalViewport) {
this.updateInViewportForSubresources_(
Resource.forElement(parentElement),
elements_(subElements),
inLocalViewport);
}
/**
* Requests the runtime to change the element's size. When the size is
* successfully updated then the opt_callback is called.
* @param {!Element} element
* @param {number|undefined} newHeight
* @param {number|undefined} newWidth
* @param {function()=} opt_callback A callback function.
* @param {!../layout-rect.LayoutMarginsChangeDef=} opt_newMargins
*/
changeSize(element, newHeight, newWidth, opt_callback, opt_newMargins) {
this.scheduleChangeSize_(Resource.forElement(element), newHeight,
newWidth, opt_newMargins, /* force */ true, opt_callback);
}
/**
* Return a promise that requests the runtime to update the size of
* this element to the specified value.
* The runtime will schedule this request and attempt to process it
* as soon as possible. However, unlike in {@link changeSize}, the runtime
* may refuse to make a change in which case it will reject promise, call the
* `overflowCallback` method on the target resource with the height value.
* Overflow callback is expected to provide the reader with the user action
* to update the height manually.
* Note that the runtime does not call the `overflowCallback` method if the
* requested height is 0 or negative.
* If the height is successfully updated then the promise is resolved.
* @param {!Element} element
* @param {number|undefined} newHeight
* @param {number|undefined} newWidth
* @param {!../layout-rect.LayoutMarginsChangeDef=} opt_newMargins
* @return {!Promise}
*/
attemptChangeSize(element, newHeight, newWidth, opt_newMargins) {
return new Promise((resolve, reject) => {
this.scheduleChangeSize_(Resource.forElement(element), newHeight,
newWidth, opt_newMargins, /* force */ false, success => {
if (success) {
resolve();
} else {
reject(new Error('changeSize attempt denied'));
}
});
});
}
/**
* Runs the specified measure, which is called in the "measure" vsync phase.
* This is simply a proxy to the privileged vsync service.
*
* @param {function()} measurer
* @return {!Promise}
*/
measureElement(measurer) {
return this.vsync_.measurePromise(measurer);
}
/**
* Runs the specified mutation on the element and ensures that remeasures and
* layouts performed for the affected elements.
*
* This method should be called whenever a significant mutations are done
* on the DOM that could affect layout of elements inside this subtree or
* its siblings. The top-most affected element should be specified as the
* first argument to this method and all the mutation work should be done
* in the mutator callback which is called in the "mutation" vsync phase.
*
* @param {!Element} element
* @param {function()} mutator
* @return {!Promise}
*/
mutateElement(element, mutator) {
return this.measureMutateElement(element, null, mutator);
}
/**
* Runs the specified mutation on the element and ensures that remeasures and
* layouts performed for the affected elements.
*
* This method should be called whenever a significant mutations are done
* on the DOM that could affect layout of elements inside this subtree or
* its siblings. The top-most affected element should be specified as the
* first argument to this method and all the mutation work should be done
* in the mutator callback which is called in the "mutation" vsync phase.
*
* @param {!Element} element
* @param {?function()} measurer
* @param {function()} mutator
* @return {!Promise}
*/
measureMutateElement(element, measurer, mutator) {
if (this.useLayers_) {
return this.measureMutateElementLayers_(element, measurer, mutator);
} else {
return this.measureMutateElementResources_(element, measurer, mutator);
}
}
/**
* Handles element mutation (and measurement) APIs in the Resources system.
*
* @param {!Element} element
* @param {?function()} measurer
* @param {function()} mutator
* @return {!Promise}
*/
measureMutateElementResources_(element, measurer, mutator) {
const calcRelayoutTop = () => {
const box = this.viewport_.getLayoutRect(element);
if (box.width != 0 && box.height != 0) {
return box.top;
}
return -1;
};
let relayoutTop = -1;
// TODO(jridgewell): support state
return this.vsync_.runPromise({
measure: () => {
if (measurer) {
measurer();
}
relayoutTop = calcRelayoutTop();
},
mutate: () => {
mutator();
if (element.classList.contains('i-amphtml-element')) {
const r = Resource.forElement(element);
r.requestMeasure();
}
const ampElements = element.getElementsByClassName('i-amphtml-element');
for (let i = 0; i < ampElements.length; i++) {
const r = Resource.forElement(ampElements[i]);
r.requestMeasure();
}
if (relayoutTop != -1) {
this.setRelayoutTop_(relayoutTop);
}
this.schedulePass(FOUR_FRAME_DELAY_);
// Need to measure again in case the element has become visible or
// shifted.
this.vsync_.measure(() => {
const updatedRelayoutTop = calcRelayoutTop();
if (updatedRelayoutTop != -1 && updatedRelayoutTop != relayoutTop) {
this.setRelayoutTop_(updatedRelayoutTop);
this.schedulePass(FOUR_FRAME_DELAY_);