forked from ampproject/amphtml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcustom-element.js
1950 lines (1791 loc) · 58.1 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 './dom';
import {AmpEvents} from './amp-events';
import {CommonSignals} from './common-signals';
import {ElementStub} from './element-stub';
import {
Layout,
applyStaticLayout,
isInternalElement,
isLayoutSizeDefined,
isLoadingAllowed,
} from './layout';
import {LayoutDelayMeter} from './layout-delay-meter';
import {ResourceState} from './service/resource';
import {Services} from './services';
import {Signals} from './utils/signals';
import {blockedByConsentError, isBlockedByConsent, reportError} from './error';
import {
createLegacyLoaderElement,
createNewLoaderElement,
isNewLoaderExperimentEnabled,
} from '../src/loader.js';
import {dev, devAssert, rethrowAsync, user, userAssert} from './log';
import {getIntersectionChangeEntry} from '../src/intersection-observer-polyfill';
import {getMode} from './mode';
import {htmlFor} from './static-template';
import {parseSizeList} from './size-list';
import {setStyle} from './style';
import {shouldBlockOnConsentByMeta} from '../src/consent';
import {startupChunk} from './chunk';
import {toWin} from './types';
import {tryResolve} from '../src/utils/promise';
const TAG = 'CustomElement';
/**
* This is the minimum width of the element needed to trigger `loading`
* animation. This value is justified as about 1/3 of a smallish mobile
* device viewport. Trying to put a loading indicator into a small element
* is meaningless.
* @private @const {number}
*/
const MIN_WIDTH_FOR_LOADING = 100;
/**
* The elements positioned ahead of this threshold may have their loading
* indicator initialized faster. This is benefitial to avoid relayout during
* render phase or scrolling.
* @private @const {number}
*/
const PREPARE_LOADING_THRESHOLD = 1000;
/**
* @enum {number}
*/
const UpgradeState = {
NOT_UPGRADED: 1,
UPGRADED: 2,
UPGRADE_FAILED: 3,
UPGRADE_IN_PROGRESS: 4,
};
/**
* Caches whether the template tag is supported to avoid memory allocations.
* @type {boolean|undefined}
*/
let templateTagSupported;
/**
* 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 {string} name The name of the custom element.
* @return {function(new:AmpElement)} The custom element class.
*/
export function createCustomElementClass(win, name) {
const baseCustomElement = /** @type {function(new:HTMLElement)} */ (createBaseCustomElementClass(
win
));
class CustomAmpElement extends baseCustomElement {
/**
* @see https://github.com/WebReflection/document-register-element#v1-caveat
* @suppress {checkTypes}
* @param {HTMLElement} self
*/
constructor(self) {
return super(self);
}
/**
* The name of the custom element.
* @return {string}
*/
elementName() {
return name;
}
}
return /** @type {function(new:AmpElement)} */ (CustomAmpElement);
}
/**
* Creates a base custom element class.
*
* @param {!Window} win The window in which to register the custom element.
* @return {function(new:HTMLElement)}
*/
function createBaseCustomElementClass(win) {
if (win.__AMP_BASE_CE_CLASS) {
return win.__AMP_BASE_CE_CLASS;
}
const htmlElement =
/** @type {function(new:HTMLElement)} */ (win.HTMLElement);
/**
* @abstract @extends {HTMLElement}
*/
class BaseCustomElement extends htmlElement {
/**
* @see https://github.com/WebReflection/document-register-element#v1-caveat
* @suppress {checkTypes}
* @param {HTMLElement} self
*/
constructor(self) {
self = super(self);
self.createdCallback();
return self;
}
/**
* 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;
/** @type {string} */
this.readyState = 'loading';
/** @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.layoutWidth_ = -1;
/** @private {number} */
this.layoutHeight_ = -1;
/** @private {number} */
this.layoutCount_ = 0;
/** @private {boolean} */
this.isFirstLayoutCompleted_ = false;
/** @private {boolean} */
this.isInViewport_ = false;
/** @private {boolean} */
this.paused_ = false;
/** @private {string|null|undefined} */
this.mediaQuery_ = undefined;
/** @private {!./size-list.SizeList|null|undefined} */
this.sizeList_ = undefined;
/** @private {!./size-list.SizeList|null|undefined} */
this.heightsList_ = undefined;
/** @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 {boolean|undefined} */
this.loadingDisabled_ = undefined;
/** @private {boolean|undefined} */
this.loadingState_ = undefined;
/** @private {?Element} */
this.loadingContainer_ = null;
/** @private {?Element} */
this.loadingElement_ = null;
/** @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.
let Ctor =
win.__AMP_EXTENDED_ELEMENTS &&
win.__AMP_EXTENDED_ELEMENTS[this.elementName()];
if (getMode().test && nonStructThis['implementationClassForTesting']) {
Ctor = nonStructThis['implementationClassForTesting'];
}
devAssert(Ctor);
/** @private {!./base-element.BaseElement} */
this.implementation_ = new Ctor(this);
/**
* 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();
const perf = Services.performanceForOrNull(win);
/** @private {boolean} */
this.perfOn_ = perf && perf.isPerformanceTrackingOn();
/** @private {?./layout-delay-meter.LayoutDelayMeter} */
this.layoutDelayMeter_ = null;
if (nonStructThis[dom.UPGRADE_TO_CUSTOMELEMENT_RESOLVER]) {
nonStructThis[dom.UPGRADE_TO_CUSTOMELEMENT_RESOLVER](nonStructThis);
delete nonStructThis[dom.UPGRADE_TO_CUSTOMELEMENT_RESOLVER];
delete nonStructThis[dom.UPGRADE_TO_CUSTOMELEMENT_PROMISE];
}
}
/**
* The name of the custom element.
* @abstract
* @return {string}
*/
elementName() {}
/** @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 /** @typedef {!./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 /** @typedef {!./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 {function(new:./base-element.BaseElement, !Element)} newImplClass
* @final @package
*/
upgrade(newImplClass) {
if (this.isInTemplate_) {
return;
}
if (this.upgradeState_ != UpgradeState.NOT_UPGRADED) {
// Already upgraded or in progress or failed.
return;
}
this.implementation_ = new newImplClass(this);
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.tryUpgrade_();
}
}
/**
* 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.upgradeDelayMs_ = win.Date.now() - upgradeStartTime;
this.upgradeState_ = UpgradeState.UPGRADED;
this.implementation_ = newImpl;
this.classList.remove('amp-unresolved');
this.classList.remove('i-amphtml-unresolved');
this.implementation_.createdCallback();
this.assertLayout_();
this.implementation_.layout_ = this.layout_;
this.implementation_.layoutWidth_ = this.layoutWidth_;
this.implementation_.firstAttachedCallback();
this.dispatchCustomEventForTesting(AmpEvents.ATTACHED);
this.getResources().upgraded(this);
this.signals_.signal(CommonSignals.UPGRADED);
}
/** @private */
assertLayout_() {
if (
this.layout_ != Layout.NODISPLAY &&
!this.implementation_.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_}`);
}
}
/**
* 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);
}
/**
* Get the priority to load the element.
* @return {number}
*/
getLayoutPriority() {
devAssert(this.isUpgraded(), 'Cannot get priority of unupgraded element');
return this.implementation_.getLayoutPriority();
}
/**
* Get the default action alias.
* @return {?string}
*/
getDefaultActionAlias() {
devAssert(
this.isUpgraded(),
'Cannot get default action alias of unupgraded element'
);
return this.implementation_.getDefaultActionAlias();
}
/**
* 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
*/
build() {
assertNotTemplate(this);
devAssert(this.isUpgraded(), 'Cannot build unupgraded element');
if (this.buildingPromise_) {
return this.buildingPromise_;
}
return (this.buildingPromise_ = new Promise((resolve, reject) => {
const policyId = this.getConsentPolicy_();
if (!policyId) {
resolve(this.implementation_.buildCallback());
} else {
Services.consentPolicyServiceForDocOrNull(this)
.then(policy => {
if (!policy) {
return true;
}
return policy.whenPolicyUnblock(/** @type {string} */ (policyId));
})
.then(shouldUnblock => {
if (shouldUnblock) {
resolve(this.implementation_.buildCallback());
} else {
reject(blockedByConsentError());
}
});
}
}).then(
() => {
this.preconnect(/* onLayout */ false);
this.built_ = true;
this.classList.remove('i-amphtml-notbuilt');
this.classList.remove('amp-notbuilt');
this.signals_.signal(CommonSignals.BUILT);
if (this.isInViewport_) {
this.updateInViewport_(true);
}
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 (!isBlockedByConsent(reason)) {
reportError(reason, this);
}
throw reason;
}
));
}
/**
* Called to instruct the element to preconnect to hosts it uses during
* layout.
* @param {boolean} onLayout Whether this was called after a layout.
*/
preconnect(onLayout) {
if (onLayout) {
this.implementation_.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(self.document, () => {
const TAG = this.tagName;
if (!this.ownerDocument) {
dev().error(TAG, 'preconnect without ownerDocument');
return;
} else if (!this.ownerDocument.defaultView) {
dev().error(TAG, 'preconnect without defaultView');
return;
}
this.implementation_.preconnectCallback(onLayout);
});
}
}
/**
* Whether the custom element declares that it has to be fixed.
* @return {boolean}
*/
isAlwaysFixed() {
return this.implementation_.isAlwaysFixed();
}
/**
* Updates the layout box of the element.
* See {@link BaseElement.getLayoutWidth} for details.
* @param {!./layout-rect.LayoutRectDef} layoutBox
* @param {boolean=} opt_measurementsChanged
*/
updateLayoutBox(layoutBox, opt_measurementsChanged) {
this.layoutWidth_ = layoutBox.width;
this.layoutHeight_ = layoutBox.height;
if (this.isUpgraded()) {
this.implementation_.layoutWidth_ = this.layoutWidth_;
}
if (this.isBuilt()) {
try {
this.implementation_.onLayoutMeasure();
if (opt_measurementsChanged) {
this.implementation_.onMeasureChanged();
}
} catch (e) {
reportError(e, this);
}
}
if (this.isLoadingEnabled_()) {
if (this.isInViewport_) {
// Already in viewport - start showing loading.
this.toggleLoading(true);
} else if (
layoutBox.top < PREPARE_LOADING_THRESHOLD &&
layoutBox.top >= 0
) {
// Few top elements will also be pre-initialized with a loading
// element.
this.mutateOrInvoke_(() => this.prepareLoading_());
}
}
}
/**
* @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;
}
if (this.layout_ === Layout.INTRINSIC) {
const intrinsicSizerImg = sizer.querySelector(
'.i-amphtml-intrinsic-sizer'
);
if (!intrinsicSizerImg) {
return;
}
intrinsicSizerImg.setAttribute('src', '');
return;
}
}
/**
* If the element has a media attribute, evaluates the value as a media
* query and based on the result adds or removes the class
* `i-amphtml-hidden-by-media-query`. The class adds display:none to the
* element which in turn prevents any of the resource loading to happen for
* the element.
*
* This method is called by Resources and shouldn't be called by anyone
* else.
*
* @final
* @package
*/
applySizesAndMediaQuery() {
assertNotTemplate(this);
// Media query.
if (this.mediaQuery_ === undefined) {
this.mediaQuery_ = this.getAttribute('media') || null;
}
if (this.mediaQuery_) {
const {defaultView} = this.ownerDocument;
this.classList.toggle(
'i-amphtml-hidden-by-media-query',
!defaultView.matchMedia(this.mediaQuery_).matches
);
}
// Sizes.
if (this.sizeList_ === undefined) {
const sizesAttr = this.getAttribute('sizes');
this.sizeList_ = sizesAttr ? parseSizeList(sizesAttr) : null;
}
if (this.sizeList_) {
setStyle(
this,
'width',
this.sizeList_.select(toWin(this.ownerDocument.defaultView))
);
}
// Heights.
if (
this.heightsList_ === undefined &&
this.layout_ === Layout.RESPONSIVE
) {
const heightsAttr = this.getAttribute('heights');
this.heightsList_ = heightsAttr
? parseSizeList(heightsAttr, /* allowPercent */ true)
: null;
}
if (this.heightsList_) {
const sizer = this.getSizer_();
if (sizer) {
setStyle(
sizer,
'paddingTop',
this.heightsList_.select(toWin(this.ownerDocument.defaultView))
);
}
}
}
/**
* Changes the size of the element.
*
* This method is called by Resources and shouldn't be called by anyone
* else. This method must always be called in the mutation context.
*
* @param {number|undefined} newHeight
* @param {number|undefined} newWidth
* @param {!./layout-rect.LayoutMarginsDef=} opt_newMargins
* @final
* @package
*/
changeSize(newHeight, newWidth, opt_newMargins) {
const sizer = this.getSizer_();
if (sizer) {
// From the moment height is changed the element becomes fully
// responsible for managing its height. Aspect ratio is no longer
// preserved.
this.sizerElement = null;
this.resetSizer_(sizer);
this.mutateOrInvoke_(() => {
if (sizer) {
dom.removeElement(sizer);
}
});
}
if (newHeight !== undefined) {
setStyle(this, 'height', newHeight, 'px');
}
if (newWidth !== undefined) {
setStyle(this, 'width', newWidth, 'px');
}
if (opt_newMargins) {
if (opt_newMargins.top != null) {
setStyle(this, 'marginTop', opt_newMargins.top, 'px');
}
if (opt_newMargins.right != null) {
setStyle(this, 'marginRight', opt_newMargins.right, 'px');
}
if (opt_newMargins.bottom != null) {
setStyle(this, 'marginBottom', opt_newMargins.bottom, 'px');
}
if (opt_newMargins.left != null) {
setStyle(this, 'marginLeft', opt_newMargins.left, 'px');
}
}
if (this.isAwaitingSize_()) {
this.sizeProvided_();
}
this.dispatchCustomEvent(AmpEvents.SIZE_CHANGED);
}
/**
* Called when the element is first connected to the DOM. Calls
* {@link firstAttachedCallback} if this is the first attachment.
*
* This callback is guarded by checks to see if the element is still
* connected. Chrome and Safari can trigger connectedCallback even when
* the node is disconnected. See #12849, https://crbug.com/821195, and
* https://bugs.webkit.org/show_bug.cgi?id=180940. Thankfully,
* connectedCallback will later be called when the disconnected root is
* connected to the document tree.
*
* @final
*/
connectedCallback() {
if (!isTemplateTagSupported() && this.isInTemplate_ === undefined) {
this.isInTemplate_ = !!dom.closestAncestorElementBySelector(
this,
'template'
);
}
if (this.isInTemplate_) {
return;
}
if (this.isConnected_ || !dom.isConnectedNode(this)) {
return;
}
this.isConnected_ = true;
if (!this.everAttached) {
this.classList.add('i-amphtml-element');
this.classList.add('i-amphtml-notbuilt');
this.classList.add('amp-notbuilt');
}
if (!this.ampdoc_) {
// Ampdoc can now be initialized.
const win = toWin(this.ownerDocument.defaultView);
const ampdocService = Services.ampdocServiceFor(win);
const ampdoc = ampdocService.getAmpDoc(this);
this.ampdoc_ = ampdoc;
// Load the pre-stubbed extension if needed.
const extensionId = this.tagName.toLowerCase();
if (
isStub(this.implementation_) &&
!ampdoc.declaresExtension(extensionId)
) {
Services.extensionsFor(win).installExtensionForDoc(
ampdoc,
extensionId
);
}
}
if (!this.resources_) {
// Resources can now be initialized since the ampdoc is now available.
this.resources_ = Services.resourcesForDoc(this.ampdoc_);
}
this.getResources().add(this);
if (this.everAttached) {
const reconstruct = this.reconstructWhenReparented();
if (reconstruct) {
this.reset_();
}
if (this.isUpgraded()) {
if (reconstruct) {
this.getResources().upgraded(this);
}
this.dispatchCustomEventForTesting(AmpEvents.ATTACHED);
}
} else {
this.everAttached = true;
try {
this.layout_ = applyStaticLayout(this);
} catch (e) {
reportError(e, this);
}
if (!isStub(this.implementation_)) {
this.tryUpgrade_();
}
if (!this.isUpgraded()) {
this.classList.add('amp-unresolved');
this.classList.add('i-amphtml-unresolved');
// amp:attached is dispatched from the ElementStub class when it
// replayed the firstAttachedCallback call.
this.dispatchCustomEventForTesting(AmpEvents.STUBBED);
}
}
}
/**
* @return {boolean}
* @private
*/
isAwaitingSize_() {
return this.classList.contains('i-amphtml-layout-awaiting-size');
}
/**
* @private
*/
sizeProvided_() {
this.classList.remove('i-amphtml-layout-awaiting-size');
}
/** The Custom Elements V0 sibling to `connectedCallback`. */
attachedCallback() {
this.connectedCallback();
}
/**
* Try to upgrade the element with the provided implementation.
* @private @final
*/
tryUpgrade_() {
const impl = this.implementation_;
devAssert(!isStub(impl), 'Implementation must not be a stub');
if (this.upgradeState_ != UpgradeState.NOT_UPGRADED) {
// Already upgraded or in progress or failed.
return;
}
// The `upgradeCallback` only allows redirect once for the top-level
// non-stub class. We may allow nested upgrades later, but they will
// certainly be bad for performance.
this.upgradeState_ = UpgradeState.UPGRADE_IN_PROGRESS;
const startTime = win.Date.now();
const res = impl.upgradeCallback();
if (!res) {
// Nothing returned: the current object is the upgraded version.
this.completeUpgrade_(impl, startTime);
} else if (typeof res.then == 'function') {
// It's a promise: wait until it's done.
res
.then(upgrade => {
this.completeUpgrade_(upgrade || impl, startTime);
})
.catch(reason => {
this.upgradeState_ = UpgradeState.UPGRADE_FAILED;
rethrowAsync(reason);
});
} else {
// It's an actual instance: upgrade immediately.
this.completeUpgrade_(
/** @type {!./base-element.BaseElement} */ (res),
startTime
);
}
}
/**
* Called when the element is disconnected from the DOM.
*
* @final
*/
disconnectedCallback() {
this.disconnect(/* pretendDisconnected */ false);
}
/** The Custom Elements V0 sibling to `disconnectedCallback`. */
detachedCallback() {
this.disconnectedCallback();
}
/**
* Called when an element is disconnected from DOM, or when an ampDoc is
* being disconnected (the element itself may still be connected to ampDoc).
*
* This callback is guarded by checks to see if the element is still
* connected. See #12849, https://crbug.com/821195, and
* https://bugs.webkit.org/show_bug.cgi?id=180940.
* If the element is still connected to the document, you'll need to pass
* opt_pretendDisconnected.
*
* @param {boolean} pretendDisconnected Forces disconnection regardless
* of DOM isConnected.
*/
disconnect(pretendDisconnected) {
if (this.isInTemplate_ || !this.isConnected_) {
return;
}
if (!pretendDisconnected && dom.isConnectedNode(this)) {
return;
}
// This path only comes from Resource#disconnect, which deletes the
// Resource instance tied to this element. Therefore, it is no longer
// an AMP Element. But, DOM queries for i-amphtml-element assume that
// the element is tied to a Resource.
if (pretendDisconnected) {
this.classList.remove('i-amphtml-element');
}
this.isConnected_ = false;
this.getResources().remove(this);
this.implementation_.detachedCallback();
}
/**
* Dispatches a custom event.
*
* @param {string} name
* @param {!Object=} opt_data Event data.
* @final
*/
dispatchCustomEvent(name, opt_data) {
const data = opt_data || {};
// Constructors of events need to come from the correct window. Sigh.
const event = this.ownerDocument.createEvent('Event');