forked from ampproject/amphtml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resources.js
1495 lines (1327 loc) · 41.1 KB
/
resources.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 {Pass} from './pass';
import {assert} from './asserts';
import {expandLayoutRect, layoutRectLtwh, layoutRectsOverlap} from
'./layout-rect';
import {inputFor} from './input';
import {log} from './log';
import {documentStateFor} from './document-state';
import {reportError} from './error';
import {timer} from './timer';
import {viewerFor} from './viewer';
import {viewportFor} from './viewport';
import {vsync} from './vsync';
let TAG_ = 'Resources';
let RESOURCE_PROP_ = '__AMP__RESOURCE';
let OWNER_PROP_ = '__AMP__OWNER';
let LAYOUT_TASK_ID_ = 'L';
let LAYOUT_TASK_OFFSET_ = 0;
let PRELOAD_TASK_ID_ = 'P';
let PRELOAD_TASK_OFFSET_ = 2;
let PRIORITY_BASE_ = 10;
let PRIORITY_PENALTY_TIME_ = 1000;
let POST_TASK_PASS_DELAY_ = 1000;
/**
* Returns the element-based priority. A value from 0 to 10.
* @param {string} tagName
* @return {number}
*/
export function getElementPriority(tagName) {
tagName = tagName.toLowerCase();
if (tagName == 'amp-ad') {
return 2;
}
if (tagName == 'amp-pixel') {
return 1;
}
return 0;
}
export class Resources {
constructor(window) {
/** @const {!Window} */
this.win = window;
/** @const {!Viewer} */
this.viewer_ = viewerFor(window);
/** @private {boolean} */
this.isRuntimeOn_ = this.viewer_.isRuntimeOn();
/** @private @const {number} */
this.maxDpr_ = this.win.devicePixelRatio || 1;
/** @private {number} */
this.resourceIdCounter_ = 0;
/** @private @const {!Array<!Resource>} */
this.resources_ = [];
/** @private {boolean} */
this.visible_ = this.viewer_.isVisible();
/** @private {number} */
this.prerenderSize_ = this.viewer_.getPrerenderSize();
/** @private {boolean} */
this.documentReady_ = false;
/** @private {boolean} */
this.relayoutAll_ = false;
/** @private {number} */
this.relayoutTop_ = -1;
/** @private {boolean} */
this.forceBuild_ = false;
/** @private {number} */
this.lastVelocity_ = 0;
/** @const {!Pass} */
this.pass_ = new Pass(() => this.doPass_());
/** @const {!TaskQueue_} */
this.exec_ = new TaskQueue_();
/** @const {!TaskQueue_} */
this.queue_ = new TaskQueue_();
/** @private {!Array<{resource: !Resource, newHeight: number}>} */
this.changeHeightRequests_ = [];
/** @private {!Array<!Function>} */
this.deferredMutates_ = [];
/** @private {number} */
this.scrollHeight_ = 0;
/** @private {!Viewport} */
this.viewport_ = viewportFor(this.win);
/** @private {!DocumentState} */
this.docState_ = documentStateFor(this.win);
/** @private {boolean} */
this.vsyncScheduled_ = false;
// When viewport is resized, we have to re-measure all elements.
this.viewport_.onChanged((event) => {
this.lastVelocity_ = event.velocity;
this.relayoutAll_ = this.relayoutAll_ || event.relayoutAll;
this.schedulePass();
});
// Ensure that we attempt to rebuild things when DOM is ready.
this.docState_.onReady(() => {
this.setDocumentReady_();
this.forceBuild_ = true;
this.relayoutAll_ = true;
this.schedulePass();
this.monitorInput_();
});
// When document becomes visible, e.g. from "prerender" mode, do a
// simple pass.
this.viewer_.onVisibilityChanged(() => {
this.schedulePass();
});
this.viewer_.onRuntimeState((state) => {
log.fine(TAG_, 'Runtime state:', state);
this.isRuntimeOn_ = state;
this.schedulePass(1);
});
this.relayoutAll_ = true;
this.schedulePass();
}
/** @private */
monitorInput_() {
let input = 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) {
vsync.mutate(() => {
this.win.document.body.classList.toggle(clazz, on);
});
}
/** @private */
setDocumentReady_() {
this.documentReady_ = true;
this.viewer_.postDocumentReady(this.viewport_.getSize().width,
this.win.document.body./*OK*/scrollHeight);
this.updateScrollHeight_();
}
/** @private */
updateScrollHeight_() {
if (!this.win.document.body) {
return;
}
let scrollHeight = this.win.document.body./*OK*/scrollHeight;
if (scrollHeight != this./*OK*/scrollHeight_) {
this./*OK*/scrollHeight_ = scrollHeight;
this.viewer_.postDocumentResized(this.viewport_.getSize().width,
scrollHeight);
}
}
/**
* 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}
* @package
*/
getResourceForElement(element) {
return assert(/** @type {!Resource} */ (element[RESOURCE_PROP_]),
'Missing resource prop on %s', element);
}
/**
* Signals that an element has been added to the DOM. Resources manager
* will start tracking it from this point on.
* @param {!AmpElement} element
* @package
*/
add(element) {
let resource = new Resource((++this.resourceIdCounter_), element, this);
if (!element.id) {
element.id = 'AMP_' + resource.getId();
}
element[RESOURCE_PROP_] = resource;
this.resources_.push(resource);
// Try to immediately build element, it may already be ready.
resource.build(this.forceBuild_);
this.schedulePass();
log.fine(TAG_, 'element added:', resource.debugid);
}
/**
* Signals that an element has been removed to the DOM. Resources manager
* will stop tracking it from this point on.
* @param {!AmpElement} element
* @package
*/
remove(element) {
let resource = this.getResourceForElement(element);
let index = resource ? this.resources_.indexOf(resource) : -1;
if (index != -1) {
this.resources_.splice(index, 1);
}
log.fine(TAG_, 'element removed:', resource.debugid);
}
/**
* 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
* @package
*/
upgraded(element) {
let resource = this.getResourceForElement(element);
resource.build(this.forceBuild_);
this.schedulePass();
log.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) {
assert(owner.contains(element), 'Owner must contain the element');
element[OWNER_PROP_] = owner;
}
/**
* 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_(
this.getResourceForElement(parentElement),
/* layout */ true,
elements_(subElements));
}
/**
* 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_(
this.getResourceForElement(parentElement),
/* layout */ false,
elements_(subElements));
}
/**
* 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_(
this.getResourceForElement(parentElement),
elements_(subElements),
inLocalViewport);
}
/**
* Requests the runtime to change the element's height.
* @param {!Element} element
* @param {number} newHeight
*/
changeHeight(element, newHeight) {
this.scheduleChangeHeight_(this.getResourceForElement(element), newHeight);
}
/**
* Requests mutate callback to executed at the earliest possibility.
* @param {!Element} element
* @param {!Function} callback
*/
deferMutate(element, callback) {
this.scheduleDeferredMutate_(this.getResourceForElement(element), callback);
this.schedulePassVsync();
}
/**
* Schedules the work pass at the latest with the specified delay.
* @param {number=} opt_delay
*/
schedulePass(opt_delay) {
this.pass_.schedule(opt_delay);
}
/**
* Schedules the work pass at the latest with the specified delay.
*/
schedulePassVsync() {
if (this.vsyncScheduled_) {
return;
}
this.vsyncScheduled_ = true;
if (!this.docState_.isHidden()) {
vsync.mutate(() => this.doPass_());
} else {
this.schedulePass(16);
}
}
/**
* @private
*/
doPass_() {
if (!this.isRuntimeOn_) {
log.fine(TAG_, 'runtime is off');
return;
}
let prevVisible = this.visible_;
this.visible_ = this.viewer_.isVisible();
this.prerenderSize_ = this.viewer_.getPrerenderSize();
let viewportSize = this.viewport_.getSize();
log.fine(TAG_, 'PASS: at ' + timer.now() +
', visible=', this.visible_,
', forceBuild=', this.forceBuild_,
', relayoutAll=', this.relayoutAll_,
', relayoutTop=', this.relayoutTop_,
', viewportSize=', viewportSize.width, viewportSize.height,
', prerenderSize=', this.prerenderSize_);
this.pass_.cancel();
this.vsyncScheduled_ = false;
// If document becomes invisible, bring everything into inactive state.
if (prevVisible && !this.visible_) {
log.fine(TAG_, 'document become inactive');
this.documentBecameInactive_();
return;
}
// If viewport size is 0, the manager will wait for the resize event.
if (viewportSize.height > 0 && viewportSize.width > 0) {
this.mutateWork_();
this.discoverWork_();
let delay = this.work_();
if (this.visible_) {
log.fine(TAG_, 'next pass:', delay);
this.schedulePass(delay);
this.updateScrollHeight_();
} else {
log.fine(TAG_, 'document is not visible: no scheduling');
}
}
}
/**
* Performs pre-discovery mutates.
* @private
*/
mutateWork_() {
if (this.deferredMutates_.length > 0) {
log.fine(TAG_, 'deferred mutates:', this.deferredMutates_.length);
let deferredMutates = this.deferredMutates_;
this.deferredMutates_ = [];
for (let i = 0; i < deferredMutates.length; i++) {
deferredMutates[i]();
}
}
if (this.changeHeightRequests_.length > 0) {
log.fine(TAG_, 'change height requests:',
this.changeHeightRequests_.length);
let changeHeightRequests = this.changeHeightRequests_;
this.changeHeightRequests_ = [];
// Find minimum top position and run all mutates.
let minTop = -1;
for (let i = 0; i < changeHeightRequests.length; i++) {
let request = changeHeightRequests[i];
let box = request.resource.getLayoutBox();
if (box.height == request.newHeight) {
// Nothing to do.
continue;
}
if (box.top >= 0) {
minTop = minTop == -1 ? box.top : Math.min(minTop, box.top);
}
request.resource.changeHeight(request.newHeight);
}
if (minTop != -1) {
this.relayoutTop_ = minTop;
}
// TODO(dvoytenko, #367): Explore updating scroll position.
}
}
/**
* Discovers work that needs to be done since the last pass. If viewport
* has changed, it will try to build new elements, measure changed elements,
* and schedule layouts and preloads within a resonable distance of the
* current viewport. Finally, this process also updates inViewport state
* of changed elements.
*
* Layouts and preloads are not executed immediately, but instead scheduled
* in the queue with different priorities.
*
* @private
*/
discoverWork_() {
// TODO(dvoytenko): vsync separation may be needed for different phases
let now = timer.now();
// Ensure all resources layout phase complete; when relayoutAll is requested
// force re-layout.
let relayoutAll = this.relayoutAll_;
this.relayoutAll_ = false;
let relayoutTop = this.relayoutTop_;
this.relayoutTop_ = -1;
// Phase 1: Build and relayout as needed. All mutations happen here.
let relayoutCount = 0;
for (let i = 0; i < this.resources_.length; i++) {
let r = this.resources_[i];
if (r.getState() == ResourceState_.NOT_BUILT) {
r.build(this.forceBuild_);
}
if (r.getState() == ResourceState_.NOT_LAID_OUT || relayoutAll) {
r.applyMediaQuery();
relayoutCount++;
}
}
// Phase 2: Remeasure if there were any relayouts. Unfortunately, currently
// there's no way to optimize this. All reads happen here.
if (relayoutCount > 0 || relayoutAll || relayoutTop != -1) {
for (let i = 0; i < this.resources_.length; i++) {
let r = this.resources_[i];
if (r.getState() == ResourceState_.NOT_BUILT || r.hasOwner()) {
continue;
}
if (relayoutAll ||
r.getState() == ResourceState_.NOT_LAID_OUT ||
relayoutTop != -1 && r.getLayoutBox().bottom >= relayoutTop) {
r.measure();
}
}
}
let viewportRect = this.viewport_.getRect();
// Load viewport = viewport + 3x up/down when document is visible or
// depending on prerenderSize in pre-render mode.
let loadRect;
if (this.visible_) {
loadRect = expandLayoutRect(viewportRect, 0.25, 2);
} else if (this.prerenderSize_ > 0) {
loadRect = expandLayoutRect(viewportRect, 0.25,
this.prerenderSize_ - 1 + 0.25);
} else {
loadRect = null;
}
// Visible viewport = viewport + 25% up/down.
let visibleRect = expandLayoutRect(viewportRect, 0.25, 0.25);
// Phase 3: Schedule elements for layout within a reasonable distance from
// current viewport.
if (loadRect) {
for (let i = 0; i < this.resources_.length; i++) {
let r = this.resources_[i];
if (r.getState() != ResourceState_.READY_FOR_LAYOUT || r.hasOwner()) {
continue;
}
if (r.isDisplayed() && r.overlaps(loadRect)) {
this.scheduleLayoutOrPreload_(r, /* layout */ true);
}
}
}
// Phase 4: Trigger "viewport enter/exit" events.
for (let i = 0; i < this.resources_.length; i++) {
let r = this.resources_[i];
if (r.hasOwner()) {
continue;
}
// Note that when the document is not visible, neither are any of its
// elements to reduce CPU cycles.
var shouldBeInViewport = (this.visible_ && r.isDisplayed() &&
r.overlaps(visibleRect));
if (r.isInViewport() != shouldBeInViewport) {
r.setInViewport(shouldBeInViewport);
}
}
// Phase 5: Idle layout: layout more if we are otherwise not doing much.
// TODO(dvoytenko): document/estimate IDLE timeouts and other constants
if (this.visible_ &&
this.exec_.getSize() == 0 &&
this.queue_.getSize() == 0 &&
now > this.exec_.getLastDequeueTime() + 5000) {
let idleScheduledCount = 0;
for (let i = 0; i < this.resources_.length; i++) {
let r = this.resources_[i];
if (r.getState() == ResourceState_.READY_FOR_LAYOUT &&
!r.hasOwner() && r.isDisplayed()) {
log.fine(TAG_, 'idle layout:', r.debugid);
this.scheduleLayoutOrPreload_(r, /* layout */ false);
idleScheduledCount++;
if (idleScheduledCount >= 4) {
break;
}
}
}
}
}
/**
* Brings all resources into inactive state. First it sets "in viewport"
* state to false and then it calls documentInactive callback.
* @private
*/
documentBecameInactive_() {
for (let i = 0; i < this.resources_.length; i++) {
let r = this.resources_[i];
r.documentBecameInactive();
}
}
/**
* Dequeues layout and preload tasks from the queue and initiates their
* execution.
*
* There are two main drivers to dequeueing: a task's score and timeout. The
* score is built based on the resource's priority and viewport location
* (see {@link calcTaskScore_}). Timeout depends on the priority and age
* of tasks currently in the execution pool (see {@link calcTaskTimeout_}).
*
* @return {!time}
* @private
*/
work_() {
let now = timer.now();
let scorer = this.calcTaskScore_.bind(this, this.viewport_.getRect(),
Math.sign(this.lastVelocity_));
let timeout = -1;
let task = this.queue_.peek(scorer);
if (task) {
do {
timeout = this.calcTaskTimeout_(task);
log.fine(TAG_, 'peek from queue:', task.id,
'sched at', task.scheduleTime,
'score', scorer(task),
'timeout', timeout);
if (timeout > 16) {
break;
}
this.queue_.dequeue(task);
// Do not override a task in execution. This task will have to wait
// until the current one finished the execution.
let executing = this.exec_.getTaskById(task.id);
if (!executing) {
// Ensure that task can prerender
task.promise = task.callback(this.visible_);
task.startTime = now;
log.fine(TAG_, 'exec:', task.id, 'at', task.startTime);
this.exec_.enqueue(task);
task.promise.then(this.taskComplete_.bind(this, task, true),
this.taskComplete_.bind(this, task, false))
.catch(reportError);
} else {
// Reschedule post execution.
executing.promise.then(this.reschedule_.bind(this, task),
this.reschedule_.bind(this, task));
}
task = this.queue_.peek(scorer);
timeout = -1;
} while (task);
}
log.fine(TAG_, 'queue size:', this.queue_.getSize());
log.fine(TAG_, 'exec size:', this.exec_.getSize());
if (timeout >= 0) {
// Work pass.
return timeout;
}
// Idle pass.
var nextPassDelay = (now - this.exec_.getLastDequeueTime()) * 2;
nextPassDelay = Math.max(Math.min(30000, nextPassDelay), 5000);
return nextPassDelay;
}
/**
* Calculates the task's score. A task with the lowest score will be dequeued
* from the queue the first.
*
* There are three components of the score: element's priority, operation or
* offset priority and viewport priority.
*
* Element's priority is constant of the element's name. E.g. amp-img has a
* priority of 0, while amp-ad has a priority of 2.
*
* The operation (offset) priority is the priority of the task. A layout is
* a high-priority task while preload is a lower-priority task.
*
* Viewport priority is a function of the distance of the element from the
* currently visible viewports. The elements in the visible viewport get
* higher priority and further away from the viewport get lower priority.
* This priority also depends on whether or not the user is scrolling towards
* this element or away from it.
*
* @param {!LayoutRect} viewportRect
* @param {number} dir
* @param {!Task_} task
* @private
*/
calcTaskScore_(viewportRect, dir, task) {
let box = task.resource.getLayoutBox();
let posPriority = Math.floor((box.top - viewportRect.top) /
viewportRect.height);
if (posPriority != 0 && Math.sign(posPriority) != (dir || 1)) {
posPriority *= 2;
}
posPriority = Math.abs(posPriority);
return task.priority * PRIORITY_BASE_ + posPriority;
}
/**
* Calculates the timeout of a task. The timeout depends on two main factors:
* the priorities of the tasks currently in the execution pool and their age.
* The timeout is calculated against each task in the execution pool and the
* maximum value is returned.
*
* A task is penalized with higher timeout values when it's lower in priority
* than the task in the execution pool. However, this penalty is judged
* against the age of the executing task. If it has been in executing for
* some time, the penalty is reduced.
*
* @param {!Task_} task
* @private
*/
calcTaskTimeout_(task) {
if (this.exec_.getSize() == 0) {
return 0;
}
let now = timer.now();
let timeout = 0;
this.exec_.forEach((other) => {
// Higher priority tasks get the head start. Currently 500ms per a drop
// in priority (note that priority is 10-based).
let penalty = Math.max((task.priority - other.priority) *
PRIORITY_PENALTY_TIME_, 0);
// TODO(dvoytenko): Consider running total and not maximum.
timeout = Math.max(timeout, penalty - (now - other.startTime));
});
return timeout;
}
/**
* @param {!Task_} task
* @private
*/
reschedule_(task) {
if (!this.queue_.getTaskById(task.id)) {
this.queue_.enqueue(task);
}
}
/**
* @param {!Task_} task
* @param {boolean} success
* @param {*=} opt_reason
* @return {!Promise|undefined}
* @private
*/
taskComplete_(task, success, opt_reason) {
this.exec_.dequeue(task);
this.schedulePass(POST_TASK_PASS_DELAY_);
if (!success) {
log.error(TAG_, 'task failed:',
task.id, task.resource.debugid, opt_reason);
return Promise.reject(opt_reason);
}
}
/**
* Schedules change of the element's height.
* @param {!Resource} resource
* @param {number} newHeight
* @private
*/
scheduleChangeHeight_(resource, newHeight) {
if (resource.getLayoutBox().height == newHeight) {
// Nothing to do.
return;
}
let request = null;
for (let i = 0; i < this.changeHeightRequests_.length; i++) {
if (this.changeHeightRequests_[i].resource == resource) {
request = this.changeHeightRequests_[i];
break;
}
}
if (request) {
request.newHeight = newHeight;
} else {
this.changeHeightRequests_.push(
{resource: resource, newHeight: newHeight});
}
this.schedulePassVsync();
}
/**
* Schedules deferred mutate.
* @param {!Resource} resource
* @param {!Function} callback
* @private
*/
scheduleDeferredMutate_(resource, callback) {
this.deferredMutates_.push(callback);
}
/**
* Schedules layout or preload for the specified resource.
* @param {!Resource} resource
* @param {boolean} layout
* @param {number=} opt_parentPriority
* @private
*/
scheduleLayoutOrPreload_(resource, layout, opt_parentPriority) {
assert(resource.getState() != ResourceState_.NOT_BUILT &&
resource.isDisplayed(),
'Not ready for layout: %s (%s)',
resource.debugid, resource.getState());
// Don't schedule elements that can't prerender, they won't be allowed
// to execute anyway.
if (!this.visible_ && !resource.prerenderAllowed()) {
return;
}
if (!resource.isInViewport() && !resource.renderOutsideViewport()) {
return;
}
if (layout) {
this.schedule_(resource,
LAYOUT_TASK_ID_, LAYOUT_TASK_OFFSET_,
opt_parentPriority || 0,
resource.startLayout.bind(resource));
} else {
this.schedule_(resource,
PRELOAD_TASK_ID_, PRELOAD_TASK_OFFSET_,
opt_parentPriority || 0,
resource.startLayout.bind(resource));
}
}
/**
* Schedules layout or preload for the sub-resources of the specified
* resource.
* @param {!Resource} parentResource
* @param {boolean} layout
* @param {!Array<!Element>} subElements
* @private
*/
scheduleLayoutOrPreloadForSubresources_(parentResource, layout, subElements) {
let resources = [];
this.discoverResourcesForArray_(parentResource, subElements, (resource) => {
if (resource.getState() != ResourceState_.NOT_BUILT) {
resources.push(resource);
}
});
if (resources.length > 0) {
resources.forEach((resource) => {
resource.measure();
if (resource.getState() == ResourceState_.READY_FOR_LAYOUT &&
resource.isDisplayed()) {
this.scheduleLayoutOrPreload_(resource, layout,
parentResource.getPriority());
}
});
}
}
/**
* Schedules a task.
* @param {!Resource} resource
* @param {string} localId
* @param {number} priorityOffset
* @param {number} parentPriority
* @param {function():!Promise} callback
* @private
*/
schedule_(resource, localId, priorityOffset, parentPriority, callback) {
let taskId = resource.debugid + '#' + localId;
let task = {
id: taskId,
resource: resource,
priority: Math.max(resource.getPriority(), parentPriority) +
priorityOffset,
callback: callback,
scheduleTime: timer.now()
};
log.fine(TAG_, 'schedule:', task.id, 'at', task.scheduleTime);
// Only schedule a new task if there's no one enqueued yet or if this task
// has a higher priority.
let queued = this.queue_.getTaskById(taskId);
if (!queued || task.priority < queued.priority) {
if (queued) {
this.queue_.dequeue(queued);
}
this.queue_.enqueue(task);
this.schedulePass(this.calcTaskTimeout_(task));
}
task.resource.layoutScheduled();
}
/**
* Updates inViewport state for the specified sub-resources of a resource.
* @param {!Resource} parentResource
* @param {!Array<!Element>} subElements
* @param {boolean} inLocalViewport
* @private
*/
updateInViewportForSubresources_(parentResource, subElements,
inLocalViewport) {
let inViewport = parentResource.isInViewport() && inLocalViewport;
this.discoverResourcesForArray_(parentResource, subElements, (resource) => {
resource.setInViewport(inViewport);
});
}
/**
* Finds resources within the parent resource's shallow subtree.
* @param {!Resource} parentResource
* @param {!Array<!Element>} elements
* @param {function(!Resource)} callback
*/
discoverResourcesForArray_(parentResource, elements, callback) {
elements.forEach((element) => {
assert(parentResource.element.contains(element));
this.discoverResourcesForElement_(element, callback);
});
}
/**
* @param {!Element} element
* @param {function(!Resource)} callback
*/
discoverResourcesForElement_(element, callback) {
// Breadth-first search.
if (element.classList.contains('-amp-element')) {
callback(this.getResourceForElement(element));
} else {
let ampElements = element.getElementsByClassName('-amp-element');
let seen = [];
for (let i = 0; i < ampElements.length; i++) {
let ampElement = ampElements[i];
let covered = false;
for (let j = 0; j < seen.length; j++) {
if (seen[j].contains(ampElement)) {
covered = true;
break;
}
}
if (!covered) {
seen.push(ampElement);
callback(this.getResourceForElement(ampElement));
}
}
}
}
}
/**
* A Resource binding for an AmpElement.
*
* Visible for testing only!
*/
export class Resource {
/**
* @param {number} id
* @param {!AmpElement} element
* @param {!Resources} resources
*/
constructor(id, element, resources) {
/** @private {number} */
this.id_ = id;
/* @const {!AmpElement} */
this.element = element;
/* @const {string} */
this.debugid = element.tagName.toLowerCase() + '#' + id;
/** @private {!Resources} */
this.resources_ = resources;
/* @private {boolean} */
this.blacklisted_ = false;
/* @const {!AmpElement|undefined|null} */
this.owner_ = undefined;
/** @const {number} */
this.priority_ = getElementPriority(element.tagName);
/* @private {!ResourceState_} */
this.state_ = element.isBuilt() ? ResourceState_.NOT_LAID_OUT :
ResourceState_.NOT_BUILT;