Skip to content
Navigation Menu
{{ message }}
forked from ampproject/amphtml
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcustom-element.js
More file actions
1278 lines (1165 loc) · 39 KB
/
Copy pathcustom-element.js
File metadata and controls
1278 lines (1165 loc) · 39 KB
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 {Layout, getLayoutClass, getLengthNumeral, getLengthUnits,
isInternalElement, isLayoutSizeDefined, isLoadingAllowed,
parseLayout, parseLength, getNaturalDimensions,
hasNaturalDimensions} from './layout';
import {ElementStub, stubbedElements} from './element-stub';
import {createLoaderElement} from '../src/loader';
import {dev, rethrowAsync, user} from './log';
import {getIntersectionChangeEntry} from '../src/intersection-observer';
import {parseSizeList} from './size-list';
import {reportError} from './error';
import {resourcesFor} from './resources';
import {timer} from './timer';
import {vsyncFor} from './vsync';
import {getServicePromise, getServicePromiseOrNull} from './service';
import * as dom from './dom';
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;
/**
* Map from element name to implementation class.
* @const {Object}
*/
const knownElements = {};
/**
* Whether this platform supports template tags.
* @const {boolean}
*/
const TEMPLATE_TAG_SUPPORTED = 'content' in window.document.createElement(
'template'
);
/**
* Registers an element. Upgrades it if has previously been stubbed.
* @param {!Window} win
* @param {string}
* @param {function(!Function)} toClass
*/
export function upgradeOrRegisterElement(win, name, toClass) {
if (!knownElements[name]) {
registerElement(win, name, toClass);
return;
}
user.assert(knownElements[name] == ElementStub,
'%s is already registered. The script tag for ' +
'%s is likely included twice in the page.', name, name);
for (let i = 0; i < stubbedElements.length; i++) {
const stub = stubbedElements[i];
// There are 3 possible states here:
// 1. We never made the stub because the extended impl. loaded first.
// In that case the element won't be in the array.
// 2. We made a stub but the browser didn't attach it yet. In
// that case we don't need to upgrade but simply switch to the new
// implementation.
// 3. A stub was attached. We upgrade which means we replay the
// implementation.
const element = stub.element;
if (element.tagName.toLowerCase() == name) {
try {
element.upgrade(toClass);
} catch (e) {
reportError(e, this);
}
}
}
}
/**
* Stub extended elements missing an implementation.
* @param {!Window} win
*/
export function stubElements(win) {
if (!win.ampExtendedElements) {
win.ampExtendedElements = {};
}
const list = win.document.querySelectorAll('[custom-element]');
for (let i = 0; i < list.length; i++) {
const name = list[i].getAttribute('custom-element');
win.ampExtendedElements[name] = true;
if (knownElements[name]) {
continue;
}
registerElement(win, name, ElementStub);
}
// Repeat stubbing when HEAD is complete.
if (!win.document.body) {
dom.waitForBody(win.document, () => stubElements(win));
}
}
/**
* Applies layout to the element. Visible for testing only.
* @param {!AmpElement} element
*/
export function applyLayout_(element) {
const layoutAttr = element.getAttribute('layout');
const widthAttr = element.getAttribute('width');
const heightAttr = element.getAttribute('height');
const sizesAttr = element.getAttribute('sizes');
const heightsAttr = element.getAttribute('heights');
// Input layout attributes.
const inputLayout = layoutAttr ? parseLayout(layoutAttr) : null;
user.assert(inputLayout !== undefined, 'Unknown layout: %s', layoutAttr);
const inputWidth = (widthAttr && widthAttr != 'auto') ?
parseLength(widthAttr) : widthAttr;
user.assert(inputWidth !== undefined, 'Invalid width value: %s', widthAttr);
const inputHeight = heightAttr ? parseLength(heightAttr) : null;
user.assert(inputHeight !== undefined, 'Invalid height value: %s',
heightAttr);
// Effective layout attributes. These are effectively constants.
let width;
let height;
let layout;
// Calculate effective width and height.
if ((!inputLayout || inputLayout == Layout.FIXED ||
inputLayout == Layout.FIXED_HEIGHT) &&
(!inputWidth || !inputHeight) && hasNaturalDimensions(element.tagName)) {
// Default width and height: handle elements that do not specify a
// width/height and are defined to have natural browser dimensions.
const dimensions = getNaturalDimensions(element);
width = (inputWidth || inputLayout == Layout.FIXED_HEIGHT) ? inputWidth :
dimensions.width;
height = inputHeight || dimensions.height;
} else {
width = inputWidth;
height = inputHeight;
}
// Calculate effective layout.
if (inputLayout) {
layout = inputLayout;
} else if (!width && !height) {
layout = Layout.CONTAINER;
} else if (height && (!width || width == 'auto')) {
layout = Layout.FIXED_HEIGHT;
} else if (height && width && (sizesAttr || heightsAttr)) {
layout = Layout.RESPONSIVE;
} else {
layout = Layout.FIXED;
}
// Verify layout attributes.
if (layout == Layout.FIXED || layout == Layout.FIXED_HEIGHT ||
layout == Layout.RESPONSIVE) {
user.assert(height, 'Expected height to be available: %s', heightAttr);
}
if (layout == Layout.FIXED_HEIGHT) {
user.assert(!width || width == 'auto',
'Expected width to be either absent or equal "auto" ' +
'for fixed-height layout: %s', widthAttr);
}
if (layout == Layout.FIXED || layout == Layout.RESPONSIVE) {
user.assert(width && width != 'auto',
'Expected width to be available and not equal to "auto": %s',
widthAttr);
}
if (layout == Layout.RESPONSIVE) {
user.assert(getLengthUnits(width) == getLengthUnits(height),
'Length units should be the same for width and height: %s, %s',
widthAttr, heightAttr);
} else {
user.assert(heightsAttr === null,
'Unexpected "heights" attribute for none-responsive layout');
}
// Apply UI.
element.classList.add(getLayoutClass(layout));
if (isLayoutSizeDefined(layout)) {
element.classList.add('-amp-layout-size-defined');
}
if (layout == Layout.NODISPLAY) {
element.style.display = 'none';
} else if (layout == Layout.FIXED) {
element.style.width = width;
element.style.height = height;
} else if (layout == Layout.FIXED_HEIGHT) {
element.style.height = height;
} else if (layout == Layout.RESPONSIVE) {
const sizer = element.ownerDocument.createElement('i-amp-sizer');
sizer.style.display = 'block';
sizer.style.paddingTop =
((getLengthNumeral(height) / getLengthNumeral(width)) * 100) + '%';
element.insertBefore(sizer, element.firstChild);
element.sizerElement_ = sizer;
} else if (layout == Layout.FILL) {
// Do nothing.
} else if (layout == Layout.CONTAINER) {
// Do nothing. Elements themselves will check whether the supplied
// layout value is acceptable. In particular container is only OK
// sometimes.
}
return layout;
}
/**
* Returns "true" for internal AMP nodes or for placeholder elements.
* @param {!Node} node
* @return {boolean}
*/
function isInternalOrServiceNode(node) {
if (isInternalElement(node)) {
return true;
}
if (node.tagName && (node.hasAttribute('placeholder') ||
node.hasAttribute('fallback') ||
node.hasAttribute('overflow'))) {
return true;
}
return false;
}
/**
* The interface that is implemented by all custom elements in the AMP
* namespace.
* @interface
*/
class AmpElement {
// TODO(dvoytenko): Add all exposed methods.
}
/**
* Creates a new custom element class prototype.
*
* Visible for testing only.
*
* @param {!Window} win The window in which to register the elements.
* @param {string} name Name of the custom element
* @param {function(new:BaseElement, !Element)} implementationClass
* @return {!AmpElement.prototype}
*/
export function createAmpElementProto(win, name, implementationClass) {
/**
* @lends {AmpElement.prototype}
*/
const ElementProto = win.Object.create(win.HTMLElement.prototype);
/**
* Called when elements is created. Sets instance vars since there is no
* constructor.
* @final
*/
ElementProto.createdCallback = function() {
this.classList.add('-amp-element');
// Flag "notbuilt" is removed by Resource manager when the resource is
// considered to be built. See "setBuilt" method.
/** @private {boolean} */
this.built_ = false;
this.classList.add('-amp-notbuilt');
this.classList.add('amp-notbuilt');
this.readyState = 'loading';
this.everAttached = false;
/** @private @const {!Resources} */
this.resources_ = resourcesFor(win);
/** @private {!Layout} */
this.layout_ = Layout.NODISPLAY;
/** @private {number} */
this.layoutWidth_ = -1;
/** @private {number} */
this.layoutCount_ = 0;
/** @private {boolean} */
this.isInViewport_ = false;
/** @private {string|null|undefined} */
this.mediaQuery_ = undefined;
/** @private {!SizeList|null|undefined} */
this.sizeList_ = undefined;
/** @private {!SizeList|null|undefined} */
this.heightsList_ = undefined;
/**
* This element can be assigned by the {@link applyLayout_} to a child
* element that will be used to size this element.
* @private {?Element}
*/
this.sizerElement_ = null;
/** @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;
/** @private {!BaseElement} */
this.implementation_ = new implementationClass(this);
this.implementation_.createdCallback();
/**
* Action queue is initially created and kept around until the element
* is ready to send actions directly to the implementation.
* @private {?Array<!ActionInvocation>}
*/
this.actionQueue_ = [];
/**
* Whether the element is in the template.
* @private {boolean|undefined}
*/
this.isInTemplate_ = undefined;
};
/** @private */
ElementProto.assertNotTemplate_ = function() {
dev.assert(!this.isInTemplate_, 'Must never be called in template');
};
/**
* Whether the element has been upgraded yet.
* @return {boolean}
* @final
*/
ElementProto.isUpgraded = function() {
return !(this.implementation_ instanceof ElementStub);
};
/**
* 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:BaseElement, !Element)} newImplClass
* @final @package
*/
ElementProto.upgrade = function(newImplClass) {
if (this.isInTemplate_) {
return;
}
this.implementation_ = new newImplClass(this);
this.classList.remove('amp-unresolved');
this.classList.remove('-amp-unresolved');
this.implementation_.createdCallback();
if (this.layout_ != Layout.NODISPLAY &&
!this.implementation_.isLayoutSupported(this.layout_)) {
throw new Error('Layout not supported: ' + this.layout_);
}
this.implementation_.layout_ = this.layout_;
this.implementation_.layoutWidth_ = this.layoutWidth_;
if (this.everAttached) {
this.implementation_.firstAttachedCallback();
this.dispatchCustomEvent('amp:attached');
}
this.resources_.upgraded(this);
};
/**
* Whether the element has been built. A built element had its
* {@link buildCallback} method successfully invoked.
* @return {boolean}
* @final
*/
ElementProto.isBuilt = function() {
return this.built_;
};
/**
* Requests or requires the element to be built. The build is done by
* invoking {@link BaseElement.buildCallback} method.
*
* If the "force" argument is "false", the element will first check if
* implementation is ready to build by calling
* {@link BaseElement.isReadyToBuild} method. If this method returns "true"
* the build proceeds, otherwise no build is done.
*
* If the "force" argument is "true", the element performs build regardless
* of what {@link BaseElement.isReadyToBuild} would return.
*
* Returned value indicates whether or not build has been performed.
*
* This method can only be called on a upgraded element.
*
* @param {boolean} force Whether or not force the build.
* @return {boolean}
* @final
*/
ElementProto.build = function(force) {
this.assertNotTemplate_();
if (this.isBuilt()) {
return true;
}
dev.assert(this.isUpgraded(), 'Cannot build unupgraded element');
if (!force && !this.implementation_.isReadyToBuild()) {
return false;
}
try {
this.implementation_.buildCallback();
this.preconnect(/* onLayout */ false);
this.built_ = true;
this.classList.remove('-amp-notbuilt');
this.classList.remove('amp-notbuilt');
} catch (e) {
reportError(e, this);
throw e;
}
if (this.built_ && this.isInViewport_) {
this.updateInViewport_(true);
}
if (this.actionQueue_) {
if (this.actionQueue_.length > 0) {
// Only schedule when the queue is not empty, which should be
// the case 99% of the time.
timer.delay(this.dequeueActions_.bind(this), 1);
} else {
this.actionQueue_ = null;
}
}
return true;
};
/**
* Called to instruct the element to preconnect to hosts it uses during
* layout.
* @param {boolean} onLayout Whether this was called after a layout.
*/
ElementProto.preconnect = function(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
timer.delay(() => {
this.implementation_.preconnectCallback(onLayout);
}, 1);
}
};
/**
* @return {!Vsync}
* @private
*/
ElementProto.getVsync_ = function() {
return vsyncFor(this.ownerDocument.defaultView);
};
/**
* Updates the layout box of the element.
* See {@link BaseElement.getLayoutWidth} for details.
* @param {!LayoutRect} layoutBox
*/
ElementProto.updateLayoutBox = function(layoutBox) {
this.layoutWidth_ = layoutBox.width;
if (this.isUpgraded()) {
this.implementation_.layoutWidth_ = this.layoutWidth_;
}
// TODO(malteubl): Forward for stubbed elements.
this.implementation_.onLayoutMeasure();
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.getVsync_().mutate(() => {
this.prepareLoading_();
});
}
}
};
/**
* If the element has a media attribute, evaluates the value as a media
* query and based on the result adds or removes the class
* `-amp-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
*/
ElementProto.applySizesAndMediaQuery = function() {
this.assertNotTemplate_();
// Media query.
if (this.mediaQuery_ === undefined) {
this.mediaQuery_ = this.getAttribute('media') || null;
}
if (this.mediaQuery_) {
this.classList.toggle('-amp-hidden-by-media-query',
!this.ownerDocument.defaultView.matchMedia(this.mediaQuery_).matches);
}
// Sizes.
if (this.sizeList_ === undefined) {
const sizesAttr = this.getAttribute('sizes');
this.sizeList_ = sizesAttr ? parseSizeList(sizesAttr) : null;
}
if (this.sizeList_) {
this.style.width = this.sizeList_.select(this.ownerDocument.defaultView);
}
// Heights.
if (this.heightsList_ === undefined) {
const heightsAttr = this.getAttribute('heights');
this.heightsList_ = heightsAttr ?
parseSizeList(heightsAttr, /* allowPercent */ true) : null;
}
if (this.heightsList_ && this.layout_ ===
Layout.RESPONSIVE && this.sizerElement_) {
this.sizerElement_.style.paddingTop = this.heightsList_.select(
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
* @final
* @package
*/
ElementProto./*OK*/changeSize = function(newHeight, newWidth) {
if (this.sizerElement_) {
// From the moment height is changed the element becomes fully
// responsible for managing its height. Aspect ratio is no longer
// preserved.
this.sizerElement_.style.paddingTop = '0';
}
if (newHeight !== undefined) {
this.style.height = newHeight + 'px';
}
if (newWidth !== undefined) {
this.style.width = newWidth + 'px';
}
};
/**
* Called when the element is first attached to the DOM. Calls
* {@link firstAttachedCallback} if this is the first attachment.
* @final
*/
ElementProto.attachedCallback = function() {
if (!TEMPLATE_TAG_SUPPORTED) {
this.isInTemplate_ = !!dom.closestByTag(this, 'template');
}
if (this.isInTemplate_) {
return;
}
if (!this.everAttached) {
this.everAttached = true;
try {
this.firstAttachedCallback_();
} catch (e) {
reportError(e, this);
}
}
this.resources_.add(this);
};
/**
* Called when the element is detached from the DOM.
* @final
*/
ElementProto.detachedCallback = function() {
if (this.isInTemplate_) {
return;
}
this.resources_.remove(this);
};
/**
* Called when the element is attached to the DOM for the first time.
* @private @final
*/
ElementProto.firstAttachedCallback_ = function() {
if (!this.isUpgraded()) {
this.classList.add('amp-unresolved');
this.classList.add('-amp-unresolved');
}
try {
this.layout_ = applyLayout_(this);
if (this.layout_ != Layout.NODISPLAY &&
!this.implementation_.isLayoutSupported(this.layout_)) {
throw new Error('Layout not supported for: ' + this.layout_);
}
this.implementation_.layout_ = this.layout_;
this.implementation_.firstAttachedCallback();
} catch (e) {
reportError(e, this);
throw e;
}
if (!this.isUpgraded()) {
// amp:attached is dispatched from the ElementStub class when it replayed
// the firstAttachedCallback call.
this.dispatchCustomEvent('amp:stubbed');
} else {
this.dispatchCustomEvent('amp:attached');
}
};
/**
* @param {string} name
* @param {!Object=} opt_data Event data.
* @final
*/
ElementProto.dispatchCustomEvent = function(name, opt_data) {
const data = opt_data || {};
// Constructors of events need to come from the correct window. Sigh.
const win = this.ownerDocument.defaultView;
const event = win.document.createEvent('Event');
event.data = data;
event.initEvent(name, true, true);
this.dispatchEvent(event);
};
/**
* Whether the element can pre-render.
* @return {boolean}
* @final
*/
ElementProto.prerenderAllowed = function() {
return this.implementation_.prerenderAllowed();
};
/**
* Whether the element should ever render when it is not in viewport.
* @return {boolean}
* @final
*/
ElementProto.renderOutsideViewport = function() {
return this.implementation_.renderOutsideViewport();
};
/**
* @return {!LayoutRect}
* @final
*/
ElementProto.getLayoutBox = function() {
return this.resources_.getResourceForElement(this).getLayoutBox();
};
/**
* Returns a change entry for that should be compatible with
* IntersectionObserverEntry.
* @return {!IntersectionObserverEntry} A change entry.
* @final
*/
ElementProto.getIntersectionChangeEntry = function() {
const box = this.implementation_.getIntersectionElementLayoutBox();
const rootBounds = this.implementation_.getViewport().getRect();
return getIntersectionChangeEntry(
timer.now(),
rootBounds,
box);
};
/**
* The runtime calls this method to determine if {@link layoutCallback}
* should be called again when layout changes.
* @return {boolean}
* @package @final
*/
ElementProto.isRelayoutNeeded = function() {
return this.implementation_.isRelayoutNeeded();
};
/**
* Instructs the element to layout its content and load its resources if
* necessary by calling the {@link BaseElement.layoutCallback} method that
* should be implemented by BaseElement subclasses. Must return a promise
* that will yield when the layout and associated loadings are complete.
*
* This method is always called for the first layout, but for subsequent
* layouts the runtime consults {@link isRelayoutNeeded} method.
*
* Can only be called on a upgraded and built element.
*
* @return {!Promise}
* @package @final
*/
ElementProto.layoutCallback = function() {
this.assertNotTemplate_();
dev.assert(this.isUpgraded() && this.isBuilt(),
'Must be upgraded and built to receive viewport events');
this.dispatchCustomEvent('amp:load:start');
const promise = this.implementation_.layoutCallback();
this.preconnect(/* onLayout */ true);
this.classList.add('-amp-layout');
return promise.then(() => {
this.readyState = 'complete';
this.layoutCount_++;
this.toggleLoading_(false, /* cleanup */ true);
if (this.layoutCount_ == 1) {
this.implementation_.firstLayoutCompleted();
}
}, reason => {
this.toggleLoading_(false, /* cleanup */ true);
throw reason;
});
};
/**
* Instructs the resource that it entered or exited the visible viewport.
*
* Can only be called on a upgraded and built element.
*
* @param {boolean} inViewport Whether the element has entered or exited
* the visible viewport.
* @final @package
*/
ElementProto.viewportCallback = function(inViewport) {
this.assertNotTemplate_();
this.isInViewport_ = inViewport;
if (this.layoutCount_ == 0) {
if (!inViewport) {
this.toggleLoading_(false);
} else {
// Set a minimum delay in case the element loads very fast or if it
// leaves the viewport.
timer.delay(() => {
if (this.layoutCount_ == 0 && this.isInViewport_) {
this.toggleLoading_(true);
}
}, 100);
}
}
if (this.isUpgraded() && this.isBuilt()) {
this.updateInViewport_(inViewport);
}
};
/**
* @param {boolean} inViewport
* @private
*/
ElementProto.updateInViewport_ = function(inViewport) {
this.implementation_.inViewport_ = inViewport;
this.implementation_.viewportCallback(inViewport);
};
/**
* Requests the resource to stop its activity when the document goes into
* inactive state. The scope is up to the actual component. Among other
* things the active playback of video or audio content must be stopped.
*
* @package @final
*/
ElementProto.pauseCallback = function() {
this.assertNotTemplate_();
if (!this.isBuilt() || !this.isUpgraded()) {
return;
}
this.implementation_.pauseCallback();
};
/**
* Requests the resource to resume its activity when the document returns from
* an inactive state. The scope is up to the actual component. Among other
* things the active playback of video or audio content may be resumed.
*
* @package @final
*/
ElementProto.resumeCallback = function() {
this.assertNotTemplate_();
if (!this.isBuilt() || !this.isUpgraded()) {
return;
}
this.implementation_.resumeCallback();
};
/**
* Requests the element to unload any expensive resources when the element
* goes into non-visible state. The scope is up to the actual component.
*
* Calling this method on unbuilt ot unupgraded element has no effect.
*
* @return {boolean}
* @package @final
*/
ElementProto.unlayoutCallback = function() {
this.assertNotTemplate_();
if (!this.isBuilt() || !this.isUpgraded()) {
return false;
}
return this.implementation_.unlayoutCallback();
};
/**
* Whether to call {@link unlayoutCallback} when pausing the element.
* Certain elements cannot properly pause (like amp-iframes with unknown
* video content), and so we must unlayout to stop playback.
*
* @return {boolean}
* @package @final
*/
ElementProto.unlayoutOnPause = function() {
return this.implementation_.unlayoutOnPause();
};
/**
* Enqueues the action with the element. If element has been upgraded and
* built, the action is dispatched to the implementation right away.
* Otherwise the invocation is enqueued until the implementation is ready
* to receive actions.
* @param {!ActionInvocation} invocation
* @final
*/
ElementProto.enqueAction = function(invocation) {
this.assertNotTemplate_();
if (!this.isBuilt()) {
dev.assert(this.actionQueue_).push(invocation);
} else {
this.executionAction_(invocation, false);
}
};
/**
* Dequeues events from the queue and dispatches them to the implementation
* with "deferred" flag.
* @private
*/
ElementProto.dequeueActions_ = function() {
if (!this.actionQueue_) {
return;
}
const actionQueue = dev.assert(this.actionQueue_);
this.actionQueue_ = null;
// TODO(dvoytenko, #1260): dedupe actions.
actionQueue.forEach(invocation => {
this.executionAction_(invocation, true);
});
};
/**
* Executes the action immediately. All errors are consumed and reported.
* @param {!ActionInvocation} invocation
* @param {boolean} deferred
* @final
* @private
*/
ElementProto.executionAction_ = function(invocation, deferred) {
try {
this.implementation_.executeAction(invocation, deferred);
} catch (e) {
rethrowAsync('Action execution failed:', e,
invocation.target.tagName, invocation.method);
}
};
/**
* Returns the original nodes of the custom element without any service nodes
* that could have been added for markup. These nodes can include Text,
* Comment and other child nodes.
* @return {!Array<!Node>}
* @package @final
*/
ElementProto.getRealChildNodes = function() {
const nodes = [];
for (let n = this.firstChild; n; n = n.nextSibling) {
if (!isInternalOrServiceNode(n)) {
nodes.push(n);
}
}
return nodes;
};
/**
* Returns the original children of the custom element without any service
* nodes that could have been added for markup.
* @return {!Array<!Element>}
* @package @final
*/
ElementProto.getRealChildren = function() {
const elements = [];
for (let i = 0; i < this.children.length; i++) {
const child = this.children[i];
if (!isInternalOrServiceNode(child)) {
elements.push(child);
}
}
return elements;
};
/**
* Returns an optional placeholder element for this custom element.
* @return {?Element}
* @package @final
*/
ElementProto.getPlaceholder = function() {
return dom.childElementByAttr(this, 'placeholder');
};
/**
* Hides or shows the placeholder, if available.
* @param {boolean} state
* @package @final
*/
ElementProto.togglePlaceholder = function(state) {
this.assertNotTemplate_();
const placeholder = this.getPlaceholder();
if (placeholder) {
placeholder.classList.toggle('amp-hidden', !state);
}
};
/**
* Returns an optional fallback element for this custom element.
* @return {?Element}
* @package @final
*/
ElementProto.getFallback = function() {
return dom.childElementByAttr(this, 'fallback');
};
/**
* Hides or shows the fallback, if available. This function must only
* be called inside a mutate context.
* @param {boolean} state
* @package @final
*/
ElementProto.toggleFallback = function(state) {
this.assertNotTemplate_();
// This implementation is notably less efficient then placeholder toggling.
// The reasons for this are: (a) "not supported" is the state of the whole
// element, (b) some realyout is expected and (c) fallback condition would
// be rare.
this.classList.toggle('amp-notsupported', state);
if (state == true) {
const fallbackElement = this.getFallback();
if (fallbackElement) {
this.resources_.scheduleLayout(this, fallbackElement);
}
}
};
/**
* Whether the loading can be shown for this element.
You can’t perform that action at this time.
