-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy pathcustom-element.js
2201 lines (2005 loc) · 64.5 KB
/
custom-element.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 * as dom from './core/dom';
import * as query from './core/dom/query';
import {AmpEvents} from './core/constants/amp-events';
import {CommonSignals} from './core/constants/common-signals';
import {ElementStub} from './element-stub';
import {Layout, LayoutPriority, isLoadingAllowed} from './core/dom/layout';
import {MediaQueryProps} from './core/dom/media-query-props';
import {ReadyState} from './core/constants/ready-state';
import {ResourceState} from './service/resource';
import {Services} from './service';
import {Signals} from './core/data-structures/signals';
import {
UPGRADE_TO_CUSTOMELEMENT_PROMISE,
UPGRADE_TO_CUSTOMELEMENT_RESOLVER,
} from './amp-element-helpers';
import {applyStaticLayout} from './static-layout';
import {
blockedByConsentError,
cancellation,
isBlockedByConsent,
isCancellation,
reportError,
} from './error-reporting';
import {dev, devAssert, user, userAssert} from './log';
import {getIntersectionChangeEntry} from './utils/intersection-observer-3p-host';
import {getMode} from './mode';
import {getSchedulerForDoc} from './service/scheduler';
import {isExperimentOn} from './experiments';
import {rethrowAsync} from './core/error';
import {setStyle} from './core/dom/style';
import {shouldBlockOnConsentByMeta} from './consent';
import {startupChunk} from './chunk';
import {toWin} from './core/window';
import {tryResolve} from './core/data-structures/promise';
const TAG = 'CustomElement';
/**
* @enum {number}
*/
const UpgradeState = {
NOT_UPGRADED: 1,
UPGRADED: 2,
UPGRADE_FAILED: 3,
UPGRADE_IN_PROGRESS: 4,
};
const NO_BUBBLES = {bubbles: false};
const RETURN_TRUE = () => true;
/**
* Caches whether the template tag is supported to avoid memory allocations.
* @type {boolean|undefined}
*/
let templateTagSupported;
/** @type {!Array} */
export const stubbedElements = [];
/**
* Whether this platform supports template tags.
* @return {boolean}
*/
function isTemplateTagSupported() {
if (templateTagSupported === undefined) {
const template = self.document.createElement('template');
templateTagSupported = 'content' in template;
}
return templateTagSupported;
}
/**
* Creates a named custom element class.
*
* @param {!Window} win The window in which to register the custom element.
* @param {function(!./service/ampdoc-impl.AmpDoc, !AmpElement, ?(typeof BaseElement))} elementConnectedCallback
* @return {typeof AmpElement} The custom element class.
*/
export function createCustomElementClass(win, elementConnectedCallback) {
const BaseCustomElement = /** @type {typeof HTMLElement} */ (
createBaseCustomElementClass(win, elementConnectedCallback)
);
// It's necessary to create a subclass, because the same "base" class cannot
// be registered to multiple custom elements.
class CustomAmpElement extends BaseCustomElement {
/**
* adoptedCallback is only called when using a Native implementation of Custom Elements V1.
* Our polyfill does not call this method.
*/
adoptedCallback() {
// Work around an issue with Firefox changing the prototype of our
// already constructed element to the new document's HTMLElement.
if (Object.getPrototypeOf(this) !== customAmpElementProto) {
Object.setPrototypeOf(this, customAmpElementProto);
}
}
}
const customAmpElementProto = CustomAmpElement.prototype;
return /** @type {typeof AmpElement} */ (CustomAmpElement);
}
/**
* Creates a base custom element class.
*
* @param {!Window} win The window in which to register the custom element.
* @param {function(!./service/ampdoc-impl.AmpDoc, !AmpElement, ?(typeof BaseElement))} elementConnectedCallback
* @return {typeof HTMLElement}
*/
function createBaseCustomElementClass(win, elementConnectedCallback) {
if (win.__AMP_BASE_CE_CLASS) {
return win.__AMP_BASE_CE_CLASS;
}
const htmlElement = /** @type {typeof HTMLElement} */ (win.HTMLElement);
/**
* @abstract @extends {HTMLElement}
*/
class BaseCustomElement extends htmlElement {
/** */
constructor() {
super();
this.createdCallback();
}
/**
* Called when elements is created. Sets instance vars since there is no
* constructor.
* @final
*/
createdCallback() {
// Flag "notbuilt" is removed by Resource manager when the resource is
// considered to be built. See "setBuilt" method.
/** @private {boolean} */
this.built_ = false;
/**
* Several APIs require the element to be connected to the DOM tree, but
* the CustomElement lifecycle APIs are async. This lead to subtle bugs
* that require state tracking. See #12849, https://crbug.com/821195, and
* https://bugs.webkit.org/show_bug.cgi?id=180940.
* @private {boolean}
*/
this.isConnected_ = false;
/** @private {?Promise} */
this.buildingPromise_ = null;
/**
* Indicates that the `mountCallback()` has been called and it hasn't
* been reversed with an `unmountCallback()` call.
* @private {boolean}
*/
this.mounted_ = false;
/** @private {?Promise} */
this.mountPromise_ = null;
/** @private {?AbortController} */
this.mountAbortController_ = null;
/** @private {!ReadyState} */
this.readyState_ = ReadyState.UPGRADING;
/** @type {boolean} */
this.everAttached = false;
/**
* Ampdoc can only be looked up when an element is attached.
* @private {?./service/ampdoc-impl.AmpDoc}
*/
this.ampdoc_ = null;
/**
* Resources can only be looked up when an element is attached.
* @private {?./service/resources-interface.ResourcesInterface}
*/
this.resources_ = null;
/** @private {!Layout} */
this.layout_ = Layout.NODISPLAY;
/** @private {number} */
this.layoutCount_ = 0;
/** @private {boolean} */
this.isFirstLayoutCompleted_ = false;
/** @public {boolean} */
this.warnOnMissingOverflow = true;
/**
* This element can be assigned by the {@link applyStaticLayout} to a
* child element that will be used to size this element.
* @package {?Element|undefined}
*/
this.sizerElement = undefined;
/** @private {?Element|undefined} */
this.overflowElement_ = undefined;
/**
* The time at which this element was scheduled for layout relative to
* the epoch. This value will be set to 0 until the this element has been
* scheduled.
* Note that this value may change over time if the element is enqueued,
* then dequeued and re-enqueued by the scheduler.
* @type {number|undefined}
*/
this.layoutScheduleTime = undefined;
// Closure compiler appears to mark HTMLElement as @struct which
// disables bracket access. Force this with a type coercion.
const nonStructThis = /** @type {!Object} */ (this);
// `opt_implementationClass` is only used for tests.
/** @type {?(typeof ../base-element.BaseElement)} */
let Ctor =
win.__AMP_EXTENDED_ELEMENTS &&
win.__AMP_EXTENDED_ELEMENTS[this.localName];
if (getMode().test && nonStructThis['implementationClassForTesting']) {
Ctor = nonStructThis['implementationClassForTesting'];
}
/** @private {?(typeof ../base-element.BaseElement)} */
this.implClass_ = Ctor === ElementStub ? null : Ctor || null;
if (!this.implClass_) {
stubbedElements.push(this);
}
/** @private {?./base-element.BaseElement} */
this.impl_ = null;
/**
* An element always starts in a unupgraded state until it's added to DOM
* for the first time in which case it can be upgraded immediately or wait
* for script download or `upgradeCallback`.
* @private {!UpgradeState}
*/
this.upgradeState_ = UpgradeState.NOT_UPGRADED;
/**
* Time delay imposed by baseElement upgradeCallback. If no
* upgradeCallback specified or not yet executed, delay is 0.
* @private {number}
*/
this.upgradeDelayMs_ = 0;
/**
* Action queue is initially created and kept around until the element
* is ready to send actions directly to the implementation.
* - undefined initially
* - array if used
* - null after unspun
* @private {?Array<!./service/action-impl.ActionInvocation>|undefined}
*/
this.actionQueue_ = undefined;
/**
* Whether the element is in the template.
* @private {boolean|undefined}
*/
this.isInTemplate_ = undefined;
/** @private @const */
this.signals_ = new Signals();
if (this.implClass_) {
this.signals_.signal(CommonSignals.READY_TO_UPGRADE);
}
const perf = Services.performanceForOrNull(win);
/** @private {boolean} */
this.perfOn_ = perf && perf.isPerformanceTrackingOn();
/** @private {?MediaQueryProps} */
this.mediaQueryProps_ = null;
if (nonStructThis[UPGRADE_TO_CUSTOMELEMENT_RESOLVER]) {
nonStructThis[UPGRADE_TO_CUSTOMELEMENT_RESOLVER](nonStructThis);
delete nonStructThis[UPGRADE_TO_CUSTOMELEMENT_RESOLVER];
delete nonStructThis[UPGRADE_TO_CUSTOMELEMENT_PROMISE];
}
}
/** @return {!ReadyState} */
get readyState() {
return this.readyState_;
}
/** @return {!Signals} */
signals() {
return this.signals_;
}
/**
* Returns the associated ampdoc. Only available after attachment. It throws
* exception before the element is attached.
* @return {!./service/ampdoc-impl.AmpDoc}
* @final
* @package
*/
getAmpDoc() {
devAssert(this.ampdoc_, 'no ampdoc yet, since element is not attached');
return /** @type {!./service/ampdoc-impl.AmpDoc} */ (this.ampdoc_);
}
/**
* Returns Resources manager. Only available after attachment. It throws
* exception before the element is attached.
* @return {!./service/resources-interface.ResourcesInterface}
* @final
* @package
*/
getResources() {
devAssert(
this.resources_,
'no resources yet, since element is not attached'
);
return /** @type {!./service/resources-interface.ResourcesInterface} */ (
this.resources_
);
}
/**
* Whether the element has been upgraded yet. Always returns false when
* the element has not yet been added to DOM. After the element has been
* added to DOM, the value depends on the `BaseElement` implementation and
* its `upgradeElement` callback.
* @return {boolean}
* @final
*/
isUpgraded() {
return this.upgradeState_ == UpgradeState.UPGRADED;
}
/** @return {!Promise} */
whenUpgraded() {
return this.signals_.whenSignal(CommonSignals.UPGRADED);
}
/**
* Upgrades the element to the provided new implementation. If element
* has already been attached, it's layout validation and attachment flows
* are repeated for the new implementation.
* @param {typeof ./base-element.BaseElement} newImplClass
* @final @package
*/
upgrade(newImplClass) {
if (this.isInTemplate_) {
return;
}
if (this.upgradeState_ != UpgradeState.NOT_UPGRADED) {
// Already upgraded or in progress or failed.
return;
}
this.implClass_ = newImplClass;
this.signals_.signal(CommonSignals.READY_TO_UPGRADE);
if (this.everAttached) {
// Usually, we do an implementation upgrade when the element is
// attached to the DOM. But, if it hadn't yet upgraded from
// ElementStub, we couldn't. Now that it's upgraded from a stub, go
// ahead and do the full upgrade.
this.upgradeOrSchedule_();
}
}
/**
* Time delay imposed by baseElement upgradeCallback. If no
* upgradeCallback specified or not yet executed, delay is 0.
* @return {number}
*/
getUpgradeDelayMs() {
return this.upgradeDelayMs_;
}
/**
* Completes the upgrade of the element with the provided implementation.
* @param {!./base-element.BaseElement} newImpl
* @param {number} upgradeStartTime
* @final @private
*/
completeUpgrade_(newImpl, upgradeStartTime) {
this.impl_ = newImpl;
this.upgradeDelayMs_ = win.Date.now() - upgradeStartTime;
this.upgradeState_ = UpgradeState.UPGRADED;
this.setReadyStateInternal(ReadyState.BUILDING);
this.classList.remove('amp-unresolved');
this.classList.remove('i-amphtml-unresolved');
this.assertLayout_();
this.dispatchCustomEventForTesting(AmpEvents.ATTACHED);
if (!this.R1()) {
this.getResources().upgraded(this);
}
this.signals_.signal(CommonSignals.UPGRADED);
}
/** @private */
assertLayout_() {
if (
this.layout_ != Layout.NODISPLAY &&
this.impl_ &&
!this.impl_.isLayoutSupported(this.layout_)
) {
userAssert(
this.getAttribute('layout'),
'The element did not specify a layout attribute. ' +
'Check https://amp.dev/documentation/guides-and-tutorials/' +
'develop/style_and_layout/control_layout and the respective ' +
'element documentation for details.'
);
userAssert(false, `Layout not supported: ${this.layout_}`);
}
}
/**
* Get the priority to build the element.
* @return {number}
*/
getBuildPriority() {
return this.implClass_
? this.implClass_.getBuildPriority(this)
: LayoutPriority.BACKGROUND;
}
/**
* Get the priority to load the element.
* @return {number}
* TODO(#31915): remove once R1 migration is complete.
*/
getLayoutPriority() {
return this.impl_
? this.impl_.getLayoutPriority()
: LayoutPriority.BACKGROUND;
}
/**
* Get the default action alias.
* @return {?string}
*/
getDefaultActionAlias() {
devAssert(
this.isUpgraded(),
'Cannot get default action alias of unupgraded element'
);
return this.impl_.getDefaultActionAlias();
}
/** @return {boolean} */
isBuilding() {
return !!this.buildingPromise_;
}
/**
* Whether the element has been built. A built element had its
* {@link buildCallback} method successfully invoked.
* @return {boolean}
* @final
*/
isBuilt() {
return this.built_;
}
/**
* Returns the promise that's resolved when the element has been built. If
* the build fails, the resulting promise is rejected.
* @return {!Promise}
*/
whenBuilt() {
return this.signals_.whenSignal(CommonSignals.BUILT);
}
/**
* Requests or requires the element to be built. The build is done by
* invoking {@link BaseElement.buildCallback} method.
*
* Can only be called on a upgraded element. May only be called from
* resource.js to ensure an element and its resource are in sync.
*
* @return {?Promise}
* @final
* @restricted
*/
buildInternal() {
assertNotTemplate(this);
devAssert(this.implClass_, 'Cannot build unupgraded element');
if (this.buildingPromise_) {
return this.buildingPromise_;
}
this.setReadyStateInternal(ReadyState.BUILDING);
// Create the instance.
const implPromise = this.createImpl_();
// Wait for consent.
const consentPromise = implPromise.then(() => {
const policyId = this.getConsentPolicy_();
const isGranularConsentExperimentOn = isExperimentOn(
win,
'amp-consent-granular-consent'
);
const purposeConsents =
isGranularConsentExperimentOn && !policyId
? this.getPurposesConsent_()
: null;
if (!policyId && !(isGranularConsentExperimentOn && purposeConsents)) {
return;
}
// Must have policyId or granularExp w/ purposeConsents
return Services.consentPolicyServiceForDocOrNull(this)
.then((policy) => {
if (!policy) {
return true;
}
return policyId
? policy.whenPolicyUnblock(policyId)
: policy.whenPurposesUnblock(purposeConsents);
})
.then((shouldUnblock) => {
if (!shouldUnblock) {
throw blockedByConsentError();
}
});
});
// Build callback.
const buildPromise = consentPromise.then(() =>
devAssert(this.impl_).buildCallback()
);
// Build the element.
return (this.buildingPromise_ = buildPromise.then(
() => {
this.built_ = true;
this.classList.add('i-amphtml-built');
this.classList.remove('i-amphtml-notbuilt');
this.classList.remove('amp-notbuilt');
this.signals_.signal(CommonSignals.BUILT);
if (this.R1()) {
this.setReadyStateInternal(
this.readyState_ != ReadyState.BUILDING
? this.readyState_
: ReadyState.MOUNTING
);
} else {
this.setReadyStateInternal(ReadyState.LOADING);
this.preconnect(/* onLayout */ false);
}
if (this.isConnected_) {
this.connected_();
}
if (this.actionQueue_) {
// Only schedule when the queue is not empty, which should be
// the case 99% of the time.
Services.timerFor(toWin(this.ownerDocument.defaultView)).delay(
this.dequeueActions_.bind(this),
1
);
}
if (!this.getPlaceholder()) {
const placeholder = this.createPlaceholder();
if (placeholder) {
this.appendChild(placeholder);
}
}
},
(reason) => {
this.signals_.rejectSignal(
CommonSignals.BUILT,
/** @type {!Error} */ (reason)
);
if (this.R1()) {
this.setReadyStateInternal(ReadyState.ERROR, reason);
}
if (!isBlockedByConsent(reason)) {
reportError(reason, this);
}
throw reason;
}
));
}
/**
* @return {!Promise}
*/
build() {
if (this.buildingPromise_) {
return this.buildingPromise_;
}
const readyPromise = this.signals_.whenSignal(
CommonSignals.READY_TO_UPGRADE
);
return readyPromise.then(() => {
if (this.R1()) {
const scheduler = getSchedulerForDoc(this.getAmpDoc());
scheduler.scheduleAsap(this);
}
return this.whenBuilt();
});
}
/**
* Mounts the element by calling the `BaseElement.mountCallback` method.
*
* Can only be called on a upgraded element. May only be called from
* scheduler.js.
*
* @return {!Promise}
* @final
* @restricted
*/
mountInternal() {
if (this.mountPromise_) {
return this.mountPromise_;
}
this.mountAbortController_ =
this.mountAbortController_ || new AbortController();
const {signal} = this.mountAbortController_;
return (this.mountPromise_ = this.buildInternal()
.then(() => {
devAssert(this.R1());
if (signal.aborted) {
// Mounting has been canceled.
return;
}
this.setReadyStateInternal(
this.readyState_ != ReadyState.MOUNTING
? this.readyState_
: this.implClass_.usesLoading(this)
? ReadyState.LOADING
: ReadyState.MOUNTING
);
this.mounted_ = true;
const result = this.impl_.mountCallback(signal);
// The promise supports the V0 format for easy migration. If the
// `mountCallback` returns a promise, the assumption is that the
// element has finished loading when the promise completes.
return result ? result.then(RETURN_TRUE) : false;
})
.then((hasLoaded) => {
this.mountAbortController_ = null;
if (signal.aborted) {
throw cancellation();
}
this.signals_.signal(CommonSignals.MOUNTED);
if (!this.implClass_.usesLoading(this) || hasLoaded) {
this.setReadyStateInternal(ReadyState.COMPLETE);
}
})
.catch((reason) => {
this.mountAbortController_ = null;
if (isCancellation(reason)) {
this.mountPromise_ = null;
} else {
this.signals_.rejectSignal(
CommonSignals.MOUNTED,
/** @type {!Error} */ (reason)
);
this.setReadyStateInternal(ReadyState.ERROR, reason);
}
throw reason;
}));
}
/**
* Requests the element to be mounted as soon as possible.
* @return {!Promise}
* @final
*/
mount() {
if (this.mountPromise_) {
return this.mountPromise_;
}
// Create the abort controller right away to ensure that we the unmount
// will properly cancel this operation.
this.mountAbortController_ =
this.mountAbortController_ || new AbortController();
const {signal} = this.mountAbortController_;
const readyPromise = this.signals_.whenSignal(
CommonSignals.READY_TO_UPGRADE
);
return readyPromise.then(() => {
if (!this.R1()) {
return this.whenBuilt();
}
if (signal.aborted) {
throw cancellation();
}
const scheduler = getSchedulerForDoc(this.getAmpDoc());
scheduler.scheduleAsap(this);
return this.whenMounted();
});
}
/**
* Unmounts the element and makes it ready for the next mounting
* operation.
* @final
*/
unmount() {
// Ensure that the element is paused.
if (this.isConnected_) {
this.pause();
}
// Legacy R0 elements simply unlayout.
if (!this.R1()) {
this.unlayout_();
return;
}
// Cancel the currently mounting operation.
if (this.mountAbortController_) {
this.mountAbortController_.abort();
this.mountAbortController_ = null;
}
// Unschedule a currently pending mount request.
const scheduler = getSchedulerForDoc(this.getAmpDoc());
scheduler.unschedule(this);
// Try to unmount if the element has been built already.
if (this.mounted_) {
this.impl_.unmountCallback();
}
// Complete unmount and reset the state.
this.mounted_ = false;
this.mountPromise_ = null;
this.reset_();
// Prepare for the next mount if the element is connected.
if (this.isConnected_) {
this.upgradeOrSchedule_(/* opt_disablePreload */ true);
}
}
/**
* Returns the promise that's resolved when the element has been mounted. If
* the mount fails, the resulting promise is rejected.
* @return {!Promise}
*/
whenMounted() {
return this.signals_.whenSignal(CommonSignals.MOUNTED);
}
/**
* @return {!Promise}
* @final
*/
whenLoaded() {
return this.signals_.whenSignal(CommonSignals.LOAD_END);
}
/**
* Ensure that the element is eagerly loaded.
*
* @param {number=} opt_parentPriority
* @return {!Promise}
* @final
*/
ensureLoaded(opt_parentPriority) {
return this.mount().then(() => {
if (this.R1()) {
if (this.implClass_.usesLoading(this)) {
this.impl_.ensureLoaded();
}
return this.whenLoaded();
}
// Very ugly! The "built" signal must be resolved from the Resource
// and not the element itself because the Resource has not correctly
// set its state for the downstream to process it correctly.
const resource = this.getResource_();
return resource.whenBuilt().then(() => {
if (resource.getState() == ResourceState.LAYOUT_COMPLETE) {
return;
}
if (
resource.getState() != ResourceState.LAYOUT_SCHEDULED ||
resource.isMeasureRequested()
) {
resource.measure();
}
if (!resource.isDisplayed()) {
return;
}
this.getResources().scheduleLayoutOrPreload(
resource,
/* layout */ true,
opt_parentPriority,
/* forceOutsideViewport */ true
);
return this.whenLoaded();
});
});
}
/**
* See `BaseElement.setAsContainer`.
*
* @param {!Element=} opt_scroller A child of the container that should be
* monitored. Typically a scrollable element.
* @restricted
* @final
*/
setAsContainerInternal(opt_scroller) {
const builder = getSchedulerForDoc(this.getAmpDoc());
builder.setContainer(this, opt_scroller);
}
/**
* See `BaseElement.removeAsContainer`.
* @restricted
* @final
*/
removeAsContainerInternal() {
const builder = getSchedulerForDoc(this.getAmpDoc());
builder.removeContainer(this);
}
/**
* Update the internal ready state.
*
* @param {!ReadyState} state
* @param {*=} opt_failure
* @protected
* @final
*/
setReadyStateInternal(state, opt_failure) {
if (state === this.readyState_) {
return;
}
this.readyState_ = state;
if (!this.R1()) {
return;
}
switch (state) {
case ReadyState.LOADING:
this.signals_.signal(CommonSignals.LOAD_START);
this.signals_.reset(CommonSignals.UNLOAD);
this.signals_.reset(CommonSignals.LOAD_END);
this.classList.add('i-amphtml-layout');
// Potentially start the loading indicator.
this.toggleLoading(true);
this.dispatchCustomEventForTesting(AmpEvents.LOAD_START);
return;
case ReadyState.COMPLETE:
// LOAD_START is set just in case. It won't be overwritten if
// it had been set before.
this.signals_.signal(CommonSignals.LOAD_START);
this.signals_.signal(CommonSignals.LOAD_END);
this.signals_.reset(CommonSignals.UNLOAD);
this.classList.add('i-amphtml-layout');
this.toggleLoading(false);
dom.dispatchCustomEvent(this, 'load', null, NO_BUBBLES);
this.dispatchCustomEventForTesting(AmpEvents.LOAD_END);
return;
case ReadyState.ERROR:
this.signals_.rejectSignal(
CommonSignals.LOAD_END,
/** @type {!Error} */ (opt_failure)
);
this.toggleLoading(false);
dom.dispatchCustomEvent(this, 'error', opt_failure, NO_BUBBLES);
return;
}
}
/**
* Called to instruct the element to preconnect to hosts it uses during
* layout.
* @param {boolean} onLayout Whether this was called after a layout.
* TODO(#31915): remove once R1 migration is complete.
*/
preconnect(onLayout) {
devAssert(this.isUpgraded());
if (onLayout) {
this.impl_.preconnectCallback(onLayout);
} else {
// If we do early preconnects we delay them a bit. This is kind of
// an unfortunate trade off, but it seems faster, because the DOM
// operations themselves are not free and might delay
startupChunk(this.getAmpDoc(), () => {
if (!this.ownerDocument || !this.ownerDocument.defaultView) {
return;
}
this.impl_.preconnectCallback(onLayout);
});
}
}
/**
* See `BaseElement.R1()`.
*
* @return {boolean}
* @final
*/
R1() {
return this.implClass_ ? this.implClass_.R1() : false;
}
/**
* See `BaseElement.deferredMount()`.
*
* @return {boolean}
* @final
*/
deferredMount() {
return this.implClass_ ? this.implClass_.deferredMount(this) : false;
}
/**
* Whether the custom element declares that it has to be fixed.
* @return {boolean}
*/
isAlwaysFixed() {
return this.impl_ ? this.impl_.isAlwaysFixed() : false;
}
/**
* Updates the layout box of the element.
* Should only be called by Resources.
* @param {!./layout-rect.LayoutRectDef} layoutBox
* @param {boolean} sizeChanged
*/
updateLayoutBox(layoutBox, sizeChanged = false) {
if (this.isBuilt()) {
this.onMeasure(sizeChanged);
}
}
/**
* Calls onLayoutMeasure() on the BaseElement implementation.
* Should only be called by Resources.
*/
onMeasure() {
devAssert(this.isBuilt());
try {
this.impl_.onLayoutMeasure();
} catch (e) {
reportError(e, this);
}
}
/**
* @return {?Element}
* @private
*/
getSizer_() {
if (
this.sizerElement === undefined &&
(this.layout_ === Layout.RESPONSIVE ||
this.layout_ === Layout.INTRINSIC)
) {
// Expect sizer to exist, just not yet discovered.
this.sizerElement = this.querySelector('i-amphtml-sizer');
}
return this.sizerElement || null;
}
/**
* @param {Element} sizer
* @private
*/
resetSizer_(sizer) {
if (this.layout_ === Layout.RESPONSIVE) {
setStyle(sizer, 'paddingTop', '0');
return;
}