-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy pathbase-element.js
1000 lines (888 loc) · 27.1 KB
/
base-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
import {devAssert} from '#core/assert';
import {AmpEvents_Enum} from '#core/constants/amp-events';
import {Loading_Enum} from '#core/constants/loading-instructions';
import {ReadyState_Enum} from '#core/constants/ready-state';
import {
addGroup,
discover,
setGroupProp,
setParent,
subscribe,
} from '#core/context';
import {Deferred} from '#core/data-structures/promise';
import {createElementWithAttributes, dispatchCustomEvent} from '#core/dom';
import {
Layout_Enum,
applyFillContent,
isLayoutSizeDefined,
} from '#core/dom/layout';
import {MediaQueryProps} from '#core/dom/media-query-props';
import {childElementByAttr, childElementByTag} from '#core/dom/query';
import {installShadowStyle} from '#core/dom/shadow-embed';
import {PauseHelper} from '#core/dom/video/pause-helper';
import * as mode from '#core/mode';
import {isElement} from '#core/types';
import {hasOwn, map} from '#core/types/object';
import * as Preact from '#preact';
import {hydrate, render} from '#preact';
import {BaseElement} from '#preact/bento-ce';
import {WithAmpContext} from './context';
import {CanPlay, CanRender, LoadingProp} from './contextprops';
import {HAS_SELECTOR, checkPropsFor, collectProps} from './parse-props';
/** @typedef {import('./parse-props').AmpElementProp} AmpElementProp */
/** @const {MutationObserverInit} */
const CHILDREN_MUTATION_INIT = {
childList: true,
};
/** @const {MutationObserverInit} */
const PASSTHROUGH_MUTATION_INIT = {
childList: true,
characterData: true,
};
/** @const {MutationObserverInit} */
const TEMPLATES_MUTATION_INIT = {
childList: true,
};
/** @const {JsonObject<string, string>} */
const SHADOW_CONTAINER_ATTRS = {
'style': 'display: contents; background: inherit;',
'part': 'c',
};
/** @const {string} */
const SERVICE_SLOT_NAME = 'i-amphtml-svc';
/** @const {JsonObject<string, string>} */
const SERVICE_SLOT_ATTRS = {'name': SERVICE_SLOT_NAME};
/** @const {string} */
const RENDERED_ATTR = 'i-amphtml-rendered';
/** @const {JsonObject<string, string>} */
const RENDERED_ATTRS = {'i-amphtml-rendered': ''};
/**
* This is an internal property that marks light DOM nodes that were rendered
* by AMP/Preact bridge and thus must be ignored by the mutation observer to
* avoid mutate->rerender->mutate loops.
*/
const RENDERED_PROP = '__AMP_RENDERED';
const UNSLOTTED_GROUP = 'unslotted';
/** @return {boolean} */
const MATCH_ANY = () => true;
/**
* @param {AmpElementProp} def
* @return {boolean}
*/
const HAS_MEDIA = (def) => !!def.media;
/**
* @param {AmpElementProp} def
* @return {boolean}
*/
const HAS_PASSTHROUGH = (def) => !!(def.passthrough || def.passthroughNonEmpty);
/**
* Wraps a Preact Component in a BaseElement class.
*
* Most functionality should be done in Preact. We don't expose the BaseElement
* subclass on purpose, you're not meant to do work in the subclass! There will
* be very few exceptions, which is why we allow options to configure the
* class.
*
* @template {{
* readyState?: ReadyState_Enum,
* pause?: function():void
* }} API_TYPE
*/
export class PreactBaseElement extends BaseElement {
/** @override */
static R1() {
return true;
}
/** @override */
static requiresShadowDom() {
return this['usesShadowDom'];
}
/** @override */
static usesLoading() {
return this['loadable'];
}
/** @override */
static prerenderAllowed() {
return !this.usesLoading();
}
/** @override */
static previewAllowed() {
return false;
}
/**
* Override to provide the Component definition.
*
* @type {import('preact').FunctionComponent}
* @return {ReturnType<import('preact').FunctionComponent>}
*/
static Component() {
devAssert(false, 'Must provide Component');
}
/**
* If default props are static, this can be used instead of init().
* @type {JsonObject|undefined}
*/
static staticProps = undefined;
/**
* @type {import('#core/context').IContextProp<*,*>[]}
*/
static useContexts = mode.isLocalDev()
? Object.freeze([])
: /** @type {?} */ ([]);
/**
* Whether the component implements a loading protocol.
*
* @type {boolean}
*/
static loadable = false;
/**
* Whether a component should be unloaded for `pauseCallback`.
*
* @type {boolean}
*/
static unloadOnPause = false;
/**
* An override to specify that the component requires `layoutSizeDefined`.
* This typically means that the element's `isLayoutSupported()` is
* implemented via `isLayoutSizeDefined()`, and this is how the default
* `isLayoutSupported()` is implemented when this flag is set.
*
* @type {boolean}
*/
static layoutSizeDefined = false;
/**
* The tag name, e.g. "div", "span", time" that should be used as a replacement
* node for Preact rendering. This is the node that Preact will diff with
* with specified, instead of rendering a new node. Only applicable to light-DOM
* mapping styles.
*
* @type {string}
*/
static lightDomTag = '';
/**
* Whether this element uses "templates" system.
*
* @type {boolean}
*/
static usesTemplate = false;
/**
* The CSS for shadow stylesheets.
*
* @type {?string}
*/
static shadowCss = null;
/**
* Whether this element uses Shadow DOM.
*
* @type {boolean}
*/
static usesShadowDom = false;
/**
* Enabling detached mode alters the children to be rendered in an
* unappended container. By default the children will be attached to the DOM.
*
* @type {boolean}
*/
static detached = false;
/**
* This enables the 'delegatesFocus' option when creating the shadow DOM for
* this component. A key feature of 'delegatesFocus' set to true is that
* when elements within the shadow DOM gain focus, the focus is also applied
* to the host element.
*/
static delegatesFocus = false;
/**
* Provides a mapping of Preact prop to AmpElement DOM attributes.
*
* @type {{[key: string]: AmpElementProp}}
*/
static props = {};
/**
* Returns default props
* @return {JsonObject}
*/
getDefaultProps() {
return {
'loading': Loading_Enum.AUTO,
/**
* @param {import('#core/constants/ready-state').ReadyState_Enum} state
* @param {Error=} opt_failure
*/
'onReadyState': (state, opt_failure) => {
this.onReadyState_(state, opt_failure);
},
/**
* @param {boolean} isPlaying
*/
'onPlayingState': (isPlaying) => {
this.updateIsPlaying_(isPlaying);
},
};
}
/** @param {AmpElement} element */
constructor(element) {
super(element);
/** @protected {JsonObject} */
this.defaultProps_ = this.getDefaultProps();
/**
* @type {import('./context').AmpContext}
* @private
*/
this.context_ = {
renderable: false,
playable: true,
loading: Loading_Enum.AUTO,
notify: () => this.mutateElement(() => {}),
};
/** @private {boolean} */
this.resetLoading_ = false;
/** @private {API_TYPE|null} */
this.apiWrapper_ = null;
/**
* @type {API_TYPE|null}
* @private
*/
this.currentRef_ = null;
/** @type {function(API_TYPE):void} current */
this.refSetter_ = (current) => {
// The API shape **must** be consistent.
if (current !== null) {
if (this.apiWrapper_) {
this.checkApiWrapper_(current);
} else {
this.initApiWrapper_(current);
}
}
this.currentRef_ = current;
this.maybeUpdateReadyState_();
};
/** @type {?Deferred<API_TYPE>} */
this.deferredApi_ = null;
/** @private {?Array} */
this.contextValues_ = null;
/** @protected {Element | null} */
this.container_ = null;
/** @private {boolean} */
this.scheduledRender_ = false;
/** @private {?Deferred} */
this.renderDeferred_ = null;
/** @private @const {function()} */
this.boundRerender_ = () => {
this.scheduledRender_ = false;
this.rerender_();
};
/** @private {boolean} */
this.hydrationPending_ = false;
/** @private {boolean} */
this.mounted_ = false;
/** @protected {?MutationObserver} */
this.observer = null;
/** @private {PauseHelper} */
this.pauseHelper_ = new PauseHelper(element);
/** @protected {?MediaQueryProps} */
this.mediaQueryProps_ = null;
}
/**
* A chance to initialize default Preact props for the element.
*
* @return {JsonObject|void}
*/
init() {}
/**
* @override
* @param {import('#core/dom/layout').Layout_Enum} layout
*/
isLayoutSupported(layout) {
const Ctor = /** @type {typeof PreactBaseElement} */ (
/** @type {?} */ (this.constructor)
);
if (Ctor.layoutSizeDefined) {
return (
isLayoutSizeDefined(layout) ||
// This allows a developer to specify the component's size using the
// user stylesheet without the help of AMP's static layout rules.
// Bento components use `ContainWrapper` with `contain:strict`, thus
// if a user stylesheet doesn't provide for the appropriate size, the
// element's size will be 0. The user stylesheet CSS can use
// fixed `width`/`height`, `aspect-ratio`, `flex`, `grid`, or any
// other CSS layouts coupled with `@media` queries and other CSS tools.
// Besides normal benefits of using plain CSS, an important feature of
// using this layout is that AMP does not add "sizer" elements thus
// keeping the user DOM clean.
layout == Layout_Enum.CONTAINER
);
}
return super.isLayoutSupported(layout);
}
/** @override */
buildCallback() {
const Ctor = /** @type {typeof PreactBaseElement} */ (
/** @type {?} */ (this.constructor)
);
this.observer = new MutationObserver((rs) => this.checkMutations_(rs));
const {props} = Ctor;
const childrenInit = checkPropsFor(props, HAS_SELECTOR)
? CHILDREN_MUTATION_INIT
: null;
const passthroughInit = checkPropsFor(props, HAS_PASSTHROUGH)
? PASSTHROUGH_MUTATION_INIT
: null;
const templatesInit = Ctor.usesTemplate ? TEMPLATES_MUTATION_INIT : null;
this.observer.observe(this.element, {
attributes: true,
...childrenInit,
...passthroughInit,
...templatesInit,
});
this.mediaQueryProps_ = checkPropsFor(props, HAS_MEDIA)
? new MediaQueryProps(this.win, () => this.scheduleRender_())
: null;
const {staticProps} = Ctor;
const initProps = this.init();
Object.assign(this.defaultProps_, staticProps, initProps);
this.checkPropsPostMutations();
// Unmount callback.
subscribe(this.element, [], () => {
return () => {
this.mounted_ = false;
if (this.container_) {
// We have to unmount the component to run all cleanup functions and
// release handlers. The only way to unmount right now is by
// unrendering the DOM. If the new `unmount` API becomes available, this
// code can be changed to `unmount` and the follow up render would
// have to execute the fast `hydrate` API.
render(null, this.container_);
}
};
});
// Unblock rendering on first `CanRender` response. And keep the context
// in-sync.
subscribe(
this.element,
/** @type {import('#core/context').IContextProp<*, boolean>[]} */ ([
CanRender,
CanPlay,
LoadingProp,
]),
(canRender, canPlay, loading) => {
this.context_.renderable = canRender;
this.context_.playable = canPlay;
this.context_.loading = loading;
this.mounted_ = true;
this.scheduleRender_();
}
);
const {useContexts} = Ctor;
if (useContexts.length != 0) {
subscribe(this.element, useContexts, (...contexts) => {
this.contextValues_ = contexts;
this.scheduleRender_();
});
}
this.renderDeferred_ = new Deferred();
this.scheduleRender_();
if (Ctor.loadable) {
this.setReadyState?.(ReadyState_Enum.LOADING);
}
this.maybeUpdateReadyState_();
return this.renderDeferred_.promise;
}
/** @override */
ensureLoaded() {
const Ctor = /** @type {typeof PreactBaseElement} */ (
/** @type {?} */ (this.constructor)
);
if (!Ctor.loadable) {
return;
}
this.mutateProps({'loading': Loading_Enum.EAGER});
this.resetLoading_ = true;
}
/** @override */
mountCallback() {
discover(this.element);
const Ctor = /** @type {typeof PreactBaseElement} */ (
/** @type {?} */ (this.constructor)
);
if (Ctor.loadable && this.getProp('loading') != Loading_Enum.AUTO) {
this.mutateProps({'loading': Loading_Enum.AUTO});
this.resetLoading_ = false;
}
}
/** @override */
unmountCallback() {
discover(this.element);
const Ctor = /** @type {typeof PreactBaseElement} */ (
/** @type {?} */ (this.constructor)
);
if (Ctor.loadable) {
this.mutateProps({'loading': Loading_Enum.UNLOAD});
}
this.updateIsPlaying_(false);
this.mediaQueryProps_?.dispose();
}
/**
* @protected
* @param {JsonObject} props
*/
mutateProps(props) {
Object.assign(/** @type {object} */ (this.defaultProps_), props);
this.scheduleRender_();
}
/**
* @return {API_TYPE}
* @protected
*/
api() {
const ref = this.currentRef_;
devAssert(ref);
return ref;
}
/**
* A callback called immediately after mutations have been observed on a
* component. This differs from `checkPropsPostMutations` in that it is
* called in all cases of mutation.
* @param {Array<MutationRecord>} unusedRecords
* @protected
*/
mutationObserverCallback(unusedRecords) {}
/**
* A callback called immediately after mutations have been observed on a
* component's defined props. The implementation can verify if any
* additional properties need to be mutated via `mutateProps()` API.
* @protected
*/
checkPropsPostMutations() {}
/**
* A callback called to compute props before rendering is run. The properties
* computed here and ephemeral and thus should not be persisted via a
* `mutateProps()` method.
* @param {JsonObject} unusedProps
* @protected
*/
updatePropsForRendering(unusedProps) {}
/**
* A callback called to check whether the element is ready for rendering.
* @param {JsonObject} unusedProps
* @return {boolean}
* @protected
*/
isReady(unusedProps) {
return true;
}
/**
* @param {Array<MutationRecord>} records
* @private
*/
checkMutations_(records) {
const Ctor = /** @type {typeof PreactBaseElement} */ (
/** @type {?} */ (this.constructor)
);
this.mutationObserverCallback(records);
const rerender = records.some((m) => shouldMutationBeRerendered(Ctor, m));
if (rerender) {
this.checkPropsPostMutations();
this.scheduleRender_();
}
}
/** @protected */
scheduleRender_() {
if (!this.scheduledRender_) {
this.scheduledRender_ = true;
this.mutateElement(this.boundRerender_);
}
}
/** @private */
maybeUpdateReadyState_() {
const {currentRef_: api} = this;
const apiReadyState = api?.['readyState'];
if (apiReadyState && apiReadyState !== this.element.readyState) {
this.onReadyState_(apiReadyState);
}
}
/**
* @param {ReadyState_Enum} state
* @param {*=} opt_failure
* @private
*/
onReadyState_(state, opt_failure) {
this.setReadyState?.(state, opt_failure);
const Ctor = /** @type {typeof PreactBaseElement} */ (
/** @type {?} */ (this.constructor)
);
if (Ctor.unloadOnPause) {
// These are typically iframe-based elements where we don't know
// whether a media is currently playing. So we have to assume that
// it is whenever the element is loaded.
this.updateIsPlaying_(state == ReadyState_Enum.COMPLETE);
}
// Reset "loading" property back to "auto".
if (this.resetLoading_) {
this.resetLoading_ = false;
this.mutateProps({'loading': Loading_Enum.AUTO});
}
}
/** @private */
rerender_() {
// If the component unmounted before the scheduled render runs, exit
// early.
if (!this.mounted_) {
return;
}
const Ctor = /** @type {typeof PreactBaseElement} */ (
/** @type {?} */ (this.constructor)
);
const {detached: isDetached, usesShadowDom: isShadow} = Ctor;
const lightDomTag = isShadow ? null : Ctor.lightDomTag;
if (!this.container_) {
const doc = this.win.document;
if (isShadow) {
devAssert(
!isDetached,
'The AMP element cannot be rendered in detached mode ' +
'when "props" are configured with "children" property.'
);
// Check if there's a pre-constructed shadow DOM.
let {shadowRoot} = this.element;
let container = shadowRoot && childElementByTag(shadowRoot, 'c');
if (container) {
this.hydrationPending_ = true;
} else {
// Create new shadow root.
shadowRoot = this.element.attachShadow({
mode: 'open',
delegatesFocus: Ctor.delegatesFocus,
});
// The pre-constructed shadow root is required to have the stylesheet
// inline. Thus, only the new shadow roots share the stylesheets.
const {shadowCss} = Ctor;
if (shadowCss) {
installShadowStyle(shadowRoot, this.element.tagName, shadowCss);
}
// Create container.
// The pre-constructed shadow root is required to have this container.
container = createElementWithAttributes(
doc,
'c',
SHADOW_CONTAINER_ATTRS
);
shadowRoot.appendChild(container);
// Create a slot for internal service elements i.e. "i-amphtml-sizer".
// The pre-constructed shadow root is required to have this slot.
const serviceSlot = createElementWithAttributes(
doc,
'slot',
SERVICE_SLOT_ATTRS
);
shadowRoot.appendChild(serviceSlot);
this.getPlaceholder?.()?.setAttribute('slot', SERVICE_SLOT_NAME);
this.getFallback?.()?.setAttribute('slot', SERVICE_SLOT_NAME);
this.getOverflowElement?.()?.setAttribute('slot', SERVICE_SLOT_NAME);
}
this.container_ = container;
// Connect shadow root to the element's context.
devAssert(shadowRoot);
setParent(shadowRoot, this.element);
// In Shadow DOM, only the children distributed in
// slots are displayed. All other children are undisplayed. We need
// to create a simple mechanism that would automatically compute
// `CanRender = false` on undistributed children.
addGroup(this.element, UNSLOTTED_GROUP, MATCH_ANY, /* weight */ -1);
setGroupProp(
this.element,
UNSLOTTED_GROUP,
CanRender,
// TODO: is `this` correct as the setter arg for setGroupProp
// eslint-disable-next-line local/restrict-this-access
/** @type {*} */ (this),
false
);
} else if (lightDomTag) {
const container = this.element;
this.container_ = container;
const replacement =
childElementByAttr(container, RENDERED_ATTR) ||
createElementWithAttributes(doc, lightDomTag, RENDERED_ATTRS);
replacement[RENDERED_PROP] = true;
if (Ctor.layoutSizeDefined) {
replacement.classList.add('i-amphtml-fill-content');
}
this.container_.appendChild(replacement);
} else {
const container = doc.createElement('i-amphtml-c');
this.container_ = container;
applyFillContent(container);
if (!isDetached) {
this.element.appendChild(container);
}
}
}
const container = this.container_;
devAssert(container);
// Exit early if contexts are not ready. Optional contexts will yield
// right away, even when `null`. The required contexts will block the
// `contextValues` until available.
const {useContexts} = Ctor;
const contextValues = this.contextValues_;
const isContextReady = useContexts.length == 0 || contextValues != null;
if (!isContextReady) {
return;
}
// Process attributes and children.
const props = collectProps(
Ctor,
this.element,
this.refSetter_,
this.defaultProps_,
this.mediaQueryProps_
);
this.updatePropsForRendering(props);
if (!this.isReady(props)) {
return;
}
// While this "creates" a new element, diffing will not create a second
// instance of Component. Instead, the existing one already rendered into
// this element will be reused.
let comp = Preact.createElement(Ctor.Component, props);
// Add contexts.
for (let i = 0; i < useContexts.length; i++) {
devAssert(contextValues);
const Context = useContexts[i].type;
const value = contextValues[i];
if (value) {
comp = <Context.Provider value={value}>{comp}</Context.Provider>;
}
}
// Add AmpContext with renderable/playable proeprties.
const v = <WithAmpContext {...this.context_}>{comp}</WithAmpContext>;
try {
if (this.hydrationPending_) {
this.hydrationPending_ = false;
hydrate(v, container);
} else {
const replacement = lightDomTag
? childElementByAttr(container, RENDERED_ATTR)
: null;
if (replacement) {
replacement[RENDERED_PROP] = true;
}
render(v, container, replacement ?? undefined);
}
} catch (err) {
this.renderDeferred_?.reject(err);
throw err;
}
// Dispatch the DOM_UPDATE event when rendered in the light DOM.
if (!isShadow && !isDetached) {
this.mutateElement(() =>
dispatchCustomEvent(this.element, AmpEvents_Enum.DOM_UPDATE, undefined)
);
}
if (this.renderDeferred_) {
this.renderDeferred_.resolve(undefined);
this.renderDeferred_ = null;
}
}
/**
* @protected
* @param {string} prop
* @param {*=} opt_fallback
* @return {*}
*/
getProp(prop, opt_fallback) {
if (!hasOwn(this.defaultProps_, prop)) {
return opt_fallback;
}
return this.defaultProps_[prop];
}
/**
* Returns reference to upgraded imperative API object, as in React's
* useImperativeHandle.
*
* @return {Promise<API_TYPE>}
* @override
*/
getApi() {
const api = this.apiWrapper_;
if (api) {
return Promise.resolve(api);
}
if (!this.deferredApi_) {
this.deferredApi_ = new Deferred();
}
return this.deferredApi_.promise;
}
/**
* Creates a wrapper around a Preact ref. The API surface exposed by this ref
* **must** be consistent accross all rerenders.
*
* This wrapper is necessary because every time React rerenders, it creates
* (depending on deps checking) a new imperative handle and sets that to
* `ref.current`. So if we ever returned `ref.current` directly, it could go
* stale by the time its actually used.
*
* @param {API_TYPE} current
* @private
*/
initApiWrapper_(current) {
const api = map();
const keys = /** @type Array<keyof API_TYPE> */ (Object.keys(current));
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
this.wrapRefProperty_(api, key);
}
this.apiWrapper_ = api;
if (this.deferredApi_) {
this.deferredApi_.resolve(api);
this.deferredApi_ = null;
}
}
/**
* Verifies that every Preact render exposes the same API surface as the previous render.
* If it does not, the API wrapper is syncrhonized.
*
* @param {API_TYPE} current
* @private
*/
checkApiWrapper_(current) {
if (!mode.isLocalDev()) {
return;
}
// Hack around https://github.com/preactjs/preact/issues/3084
if (current.constructor && current.constructor.name !== 'Object') {
return;
}
const api = this.apiWrapper_;
const newKeys = Object.keys(current);
for (let i = 0; i < newKeys.length; i++) {
const key = newKeys[i];
devAssert(
hasOwn(api, key),
'Inconsistent Bento API shape: imperative API gained a "%s" key for %s',
key,
this.element
);
}
const oldKeys = Object.keys(api);
for (let i = 0; i < oldKeys.length; i++) {
const key = oldKeys[i];
devAssert(
hasOwn(current, key),
'Inconsistent Bento API shape: imperative API lost a "%s" key for %s',
key,
this.element
);
}
}
/**
* Dispatches an error event. Provided as a method so Preact components can
* call into it, while AMP components can override to trigger action services.
* @param {Element} element
* @param {string} eventName
* @param {JsonObject} detail
*/
triggerEvent(element, eventName, detail) {
dispatchCustomEvent(element, eventName, detail);
}
/** @override */
pauseCallback() {
const Ctor = /** @type {typeof PreactBaseElement} */ (
/** @type {?} */ (this.constructor)
);
if (Ctor.unloadOnPause) {
this.mutateProps({'loading': Loading_Enum.UNLOAD});
this.resetLoading_ = true;
} else {
const {currentRef_: api} = this;
api?.['pause']?.();
}
}
/**
* @param {boolean} isPlaying
* @private
*/
updateIsPlaying_(isPlaying) {
this.pauseHelper_.updatePlaying(isPlaying);
}
/**
* @param {object} api
* @param {keyof API_TYPE} key
* @private
*/
wrapRefProperty_(api, key) {
Object.defineProperty(api, key, {
configurable: true,
get: () => {
const ref = this.currentRef_;
devAssert(ref);
return ref[key];
},
set: (v) => {
const ref = this.currentRef_;
devAssert(ref);
ref[key] = v;
},
});
}
}
/**
* @param {NodeList} nodeList
* @return {boolean}
*/
function shouldMutationForNodeListBeRerendered(nodeList) {
for (let i = 0; i < nodeList.length; i++) {
const node = nodeList[i];
if (isElement(node)) {
// Ignore service elements, e.g. `<i-amphtml-svc>` or
// `<x slot="i-amphtml-svc">`.
if (
node[RENDERED_PROP] ||
node.tagName.startsWith('I-') ||
node.getAttribute('slot') == 'i-amphtml-svc'
) {
continue;
}
return true;
}
if (node.nodeType == /* TEXT */ 3) {
return true;
}
}
return false;
}
/**
* @param {typeof PreactBaseElement} Ctor
* @param {MutationRecord} m
* @return {boolean}
*/
function shouldMutationBeRerendered(Ctor, m) {
const {type} = m;
if (type == 'attributes') {
// Check whether this is a templates attribute.
if (Ctor.usesTemplate && m.attributeName == 'template') {
return true;
}
// Check if the attribute is mapped to one of the properties.
const {props} = Ctor;
for (const name in props) {
const def = /** @type {AmpElementProp} */ (props[name]);
const attrName = m.attributeName;
devAssert(attrName);
if (
attrName == def.attr ||
def.attrs?.includes(attrName) ||
def.attrMatches?.(attrName)
) {
return true;
}
}
return false;
}
if (type == 'childList') {
return (
shouldMutationForNodeListBeRerendered(m.addedNodes) ||
shouldMutationForNodeListBeRerendered(m.removedNodes)
);
}
return false;
}