-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy pathampdoc-impl.js
1063 lines (938 loc) · 28.1 KB
/
ampdoc-impl.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 {VisibilityState_Enum} from '#core/constants/visibility-state';
import {Observable} from '#core/data-structures/observable';
import {Deferred} from '#core/data-structures/promise';
import {Signals} from '#core/data-structures/signals';
import {isDocumentReady, whenDocumentReady} from '#core/document/ready';
import {
addDocumentVisibilityChangeListener,
getDocumentVisibilityState,
removeDocumentVisibilityChangeListener,
} from '#core/document/visibility';
import {iterateCursor, rootNodeFor, waitForBodyOpenPromise} from '#core/dom';
import {isEnumValue} from '#core/types';
import {map} from '#core/types/object';
import {parseQueryString} from '#core/types/string/url';
import {WindowInterface} from '#core/window/interface';
import {dev, devAssert} from '#utils/log';
import {
disposeServicesForDoc,
getParentWindowFrameElement,
registerServiceBuilder,
} from '../service-helpers';
/** @const {string} */
const AMPDOC_PROP = '__AMPDOC';
/** @const {string} */
const PARAMS_SENTINEL = '__AMP__';
/**
* @typedef {{
* params: (!Object<string, string>|undefined),
* signals: (?Signals|undefined),
* visibilityState: (?VisibilityState_Enum|undefined),
* }}
*/
export let AmpDocOptions;
/**
* Private ampdoc signals.
* @enum {string}
*/
const AmpDocSignals_Enum = {
// A complete preinstalled list of extensions is known.
EXTENSIONS_KNOWN: '-ampdoc-ext-known',
// Signals the document has become visible for the first time.
FIRST_VISIBLE: '-ampdoc-first-visible',
// Signals when the document becomes visible the next time.
NEXT_VISIBLE: '-ampdoc-next-visible',
};
/**
* This service helps locate an ampdoc (`AmpDoc` instance) for any node,
* either in the single-doc or shadow-doc environments.
*
* In the single-doc environment an ampdoc is equivalent to the
* `window.document`. In the shadow-doc mode, any number of AMP documents
* could be hosted in shadow roots in the same global `window.document`.
*
* @package
*/
export class AmpDocService {
/**
* @param {!Window} win
* @param {boolean} isSingleDoc
* @param {!Object<string, string>=} opt_initParams
*/
constructor(win, isSingleDoc, opt_initParams) {
/** @const {!Window} */
this.win = win;
/** @private {?AmpDoc} */
this.singleDoc_ = null;
if (isSingleDoc) {
this.singleDoc_ = new AmpDocSingle(win, {
params: extractSingleDocParams(win, opt_initParams),
});
win.document[AMPDOC_PROP] = this.singleDoc_;
}
}
/**
* Whether the runtime in the single-doc mode. Alternative is the shadow-doc
* mode that supports multiple documents per a single window.
* @return {boolean}
*/
isSingleDoc() {
// TODO(#22733): remove when ampdoc-fie is launched.
return !!this.singleDoc_;
}
/**
* Returns the document in the single-doc mode. In a multi-doc mode, an
* error will be thrown.
* @return {!AmpDoc}
*/
getSingleDoc() {
// TODO(#22733): once docroot migration is done, this should be renamed
// to `getTopDoc()` method.
return devAssert(this.singleDoc_);
}
/**
* If the node is an AMP custom element, retrieves the AmpDoc reference.
* @param {!Node} node
* @return {?AmpDoc} The AmpDoc reference, if one exists.
*/
getCustomElementAmpDocReference_(node) {
// We can only look up the AmpDoc from a custom element if it has been
// attached at some point. If it is not a custom element, one or both of
// these checks should fail.
if (!node.everAttached || typeof node.getAmpDoc !== 'function') {
return null;
}
return node.getAmpDoc();
}
/**
* Returns the instance of the ampdoc (`AmpDoc`) that contains the specified
* node.
*
* @param {!Node} node
* @return {?AmpDoc}
*/
getAmpDocIfAvailable(node) {
let n = node;
while (n) {
// A custom element may already have the reference. If we are looking
// for the closest AmpDoc, the element might have a reference to the
// global AmpDoc, which we do not want. This occurs when using
// <amp-next-page>.
const cachedAmpDoc = this.getCustomElementAmpDocReference_(node);
if (cachedAmpDoc) {
return cachedAmpDoc;
}
// Root note: it's either a document, or a shadow document.
const rootNode = rootNodeFor(n);
if (!rootNode) {
break;
}
const ampdoc = rootNode[AMPDOC_PROP];
if (ampdoc) {
return ampdoc;
}
// Try to iterate to the host of the current root node.
// First try the shadow root's host.
if (rootNode.host) {
n = rootNode.host;
} else {
// Then, traverse the boundary of a friendly iframe.
n = getParentWindowFrameElement(rootNode, this.win);
}
}
return null;
}
/**
* Returns the instance of the ampdoc (`AmpDoc`) that contains the specified
* node. If the runtime is in the single-doc mode, the one global `AmpDoc`
* instance is returned, unless specfically looking for a closer `AmpDoc`.
* Otherwise, this method locates the `AmpDoc` that contains the specified
* node and, if necessary, initializes it.
*
* An Error is thrown in development if no `AmpDoc` is found.
* @param {!Node} node
* @return {!AmpDoc}
*/
getAmpDoc(node) {
const ampdoc = this.getAmpDocIfAvailable(node);
if (!ampdoc) {
throw dev().createError('No ampdoc found for', node);
}
return ampdoc;
}
/**
* Creates and installs the ampdoc for the shadow root.
* @param {string} url
* @param {!ShadowRoot} shadowRoot
* @param {!AmpDocOptions=} opt_options
* @return {!AmpDocShadow}
* @restricted
*/
installShadowDoc(url, shadowRoot, opt_options) {
devAssert(
!shadowRoot[AMPDOC_PROP],
'The shadow root already contains ampdoc'
);
const ampdoc = new AmpDocShadow(this.win, url, shadowRoot, opt_options);
shadowRoot[AMPDOC_PROP] = ampdoc;
return ampdoc;
}
/**
* Creates and installs the ampdoc for the fie root.
* @param {string} url
* @param {!Window} childWin
* @param {!AmpDocOptions=} opt_options
* @return {!AmpDocFie}
* @restricted
*/
installFieDoc(url, childWin, opt_options) {
const doc = childWin.document;
devAssert(!doc[AMPDOC_PROP], 'The fie already contains ampdoc');
const frameElement = devAssert(childWin.frameElement);
const ampdoc = new AmpDocFie(
childWin,
url,
this.getAmpDoc(frameElement),
opt_options
);
doc[AMPDOC_PROP] = ampdoc;
return ampdoc;
}
}
/**
* This class represents a single ampdoc. `AmpDocService` can contain only one
* global ampdoc or multiple, depending on the runtime mode: single-doc or
* shadow-doc.
* @abstract
* @package
*/
export class AmpDoc {
/**
* @param {!Window} win
* @param {?AmpDoc} parent
* @param {!AmpDocOptions=} opt_options
*/
constructor(win, parent, opt_options) {
/** @public @const {!Window} */
this.win = win;
/** @private {!Object<../enums.AMPDOC_SINGLETON_NAME_ENUM, boolean>} */
this.registeredSingleton_ = map();
/** @public @const {?AmpDoc} */
this.parent_ = parent;
/** @private @const */
this.signals_ = (opt_options && opt_options.signals) || new Signals();
/** @private {!Object<string, string>} */
this.params_ = (opt_options && opt_options.params) || map();
/** @protected {?Object<string, string>} */
this.meta_ = null;
/** @private @const {!Object<string, string>} */
this.declaredExtensions_ = {};
const paramsVisibilityState = this.params_['visibilityState'];
devAssert(
!paramsVisibilityState ||
isEnumValue(VisibilityState_Enum, paramsVisibilityState)
);
/** @private {?VisibilityState_Enum} */
this.visibilityStateOverride_ =
(opt_options && opt_options.visibilityState) ||
paramsVisibilityState ||
null;
// Start with `null` to be updated by updateVisibilityState_ in the end
// of the constructor to ensure the correct "update" logic and promise
// resolution.
/** @private {?VisibilityState_Enum} */
this.visibilityState_ = null;
/** @private @const {!Observable<!VisibilityState_Enum>} */
this.visibilityStateHandlers_ = new Observable();
/** @private {?time} */
this.lastVisibleTime_ = null;
/** @private @const {!Array<!UnlistenDef>} */
this.unsubsribes_ = [];
const boundUpdateVisibilityState = this.updateVisibilityState_.bind(this);
if (this.parent_) {
this.unsubsribes_.push(
this.parent_.onVisibilityChanged(boundUpdateVisibilityState)
);
}
addDocumentVisibilityChangeListener(
this.win.document,
boundUpdateVisibilityState
);
this.unsubsribes_.push(() =>
removeDocumentVisibilityChangeListener(
this.win.document,
boundUpdateVisibilityState
)
);
this.updateVisibilityState_();
}
/**
* Dispose the document.
*/
dispose() {
disposeServicesForDoc(this);
this.unsubsribes_.forEach((unsubsribe) => unsubsribe());
}
/**
* Whether the runtime in the single-doc mode. Alternative is the shadow-doc
* mode that supports multiple documents per a single window.
* @return {boolean}
*/
isSingleDoc() {
// TODO(#22733): remove when ampdoc-fie is launched.
return /** @type {?} */ (devAssert(null, 'not implemented'));
}
/**
* @return {?AmpDoc}
*/
getParent() {
return this.parent_;
}
/** @return {!Signals} */
signals() {
return this.signals_;
}
/**
* Returns the value of a ampdoc's startup parameter with the specified
* name or `null` if the parameter wasn't defined at startup time.
* @param {string} name
* @return {?string}
*/
getParam(name) {
const v = this.params_[name];
return v == null ? null : v;
}
/**
* Initializes (if necessary) cached map of an ampdoc's meta name values to
* their associated content values and returns the map.
* @return {!Object<string, string>}
*/
getMeta() {
if (this.meta_) {
return map(this.meta_);
}
this.meta_ = map();
const metaEls = dev()
.assertElement(this.win.document.head)
.querySelectorAll('meta[name]');
iterateCursor(metaEls, (metaEl) => {
const name = metaEl.getAttribute('name');
const content = metaEl.getAttribute('content');
if (!name || content === null) {
return;
}
// Retain only the first meta content value for a given name
if (this.meta_[name] === undefined) {
this.meta_[name] = content;
}
});
return map(this.meta_);
}
/**
* Returns the value of an ampdoc's meta tag content for a given name, or
* `null` if the meta tag does not exist.
* @param {string} name
* @return {?string}
*/
getMetaByName(name) {
if (!name) {
return null;
}
const content = this.getMeta()[name];
return content !== undefined ? content : null;
}
/**
* Stores the value of an ampdoc's meta tag content for a given name. To be
* implemented by subclasses.
* @param {string} unusedName
* @param {string} unusedContent
*
* Avoid using this method in components. It is only meant to be used by the
* runtime for AmpDoc subclasses where <meta> elements do not exist and name/
* content pairs must be stored in this.meta_.
*/
setMetaByName(unusedName, unusedContent) {
devAssert(null, 'not implemented');
}
/**
* Returns whether the specified extension has been declared on this ampdoc.
* @param {string} extensionId
* @param {string=} opt_version
* @return {boolean}
*/
declaresExtension(extensionId, opt_version) {
const declared = this.declaredExtensions_[extensionId];
if (!declared) {
return false;
}
return !opt_version || declared === opt_version;
}
/**
* Adds a declared extension to an ampdoc.
* @param {string} extensionId
* @param {string} version
* @restricted
*/
declareExtension(extensionId, version) {
devAssert(
!this.declaredExtensions_[extensionId] ||
this.declaredExtensions_[extensionId] === version,
'extension already declared %s',
extensionId
);
this.declaredExtensions_[extensionId] = version;
}
/**
* @param {string} extensionId
* @return {?string}
*/
getExtensionVersion(extensionId) {
return this.declaredExtensions_[extensionId] || null;
}
/**
* Signal that the initial document set of extensions is known.
* @restricted
*/
setExtensionsKnown() {
this.signals_.signal(AmpDocSignals_Enum.EXTENSIONS_KNOWN);
}
/**
* Resolved when the initial document set of extension is known.
* @return {!Promise}
*/
whenExtensionsKnown() {
return this.signals_.whenSignal(AmpDocSignals_Enum.EXTENSIONS_KNOWN);
}
/**
* Returns the root node for this ampdoc. It will either be a `Document` for
* the single-doc runtime mode, or a `ShadowRoot` for shadow-doc mode. This
* node can be used, among other things, to add ampdoc-wide event listeners.
*
* @return {!Document|!ShadowRoot}
*/
getRootNode() {
return /** @type {?} */ (devAssert(null, 'not implemented'));
}
/**
* Returns the head node. It's either an element or a shadow root.
* @return {!Element|!ShadowRoot}
* @abstract
*/
getHeadNode() {}
/**
* Returns `true` if the ampdoc's body is available.
*
* @return {boolean}
*/
isBodyAvailable() {
return /** @type {?} */ (devAssert(false, 'not implemented'));
}
/**
* Returns the ampdoc's body. Requires the body to already be available.
*
* See `isBodyAvailable` and `waitForBodyOpen`.
*
* @return {!Element}
*/
getBody() {
return /** @type {?} */ (devAssert(null, 'not implemented'));
}
/**
* Returns a promise that will be resolved when the ampdoc's body is
* available.
* @return {!Promise<!Element>}
*/
waitForBodyOpen() {
return /** @type {?} */ (devAssert(null, 'not implemented'));
}
/**
* Returns `true` if document is ready.
*
* See `whenReady`.
*
* @return {boolean}
*/
isReady() {
return /** @type {?} */ (devAssert(null, 'not implemented'));
}
/**
* Returns a promise that will be resolved when the ampdoc's DOM is fully
* ready.
* @return {!Promise}
*/
whenReady() {
return /** @type {?} */ (devAssert(null, 'not implemented'));
}
/**
* Returns the URL from which the document was loaded.
* @return {string}
*/
getUrl() {
return /** @type {?} */ (devAssert(null, 'not implemented'));
}
/**
* Locates an element with the specified ID within the ampdoc. In the
* shadow-doc mode, when multiple documents could be present, this method
* localizes search only to the DOM subtree specific to this ampdoc.
*
* @param {string} id
* @return {?Element}
*/
getElementById(id) {
return this.getRootNode().getElementById(id);
}
/**
* Whether the node is currently contained in the DOM of the root.
* @param {?Node} node
* @return {boolean}
*/
contains(node) {
return this.getRootNode().contains(node);
}
/**
* @param {!VisibilityState_Enum} visibilityState
* @restricted
*/
overrideVisibilityState(visibilityState) {
if (this.visibilityStateOverride_ != visibilityState) {
this.visibilityStateOverride_ = visibilityState;
this.updateVisibilityState_();
}
}
/** @private */
updateVisibilityState_() {
// Natural visibility state.
const naturalVisibilityState = getDocumentVisibilityState(
this.win.document
);
// Parent visibility: pick the first non-visible state.
let parentVisibilityState = VisibilityState_Enum.VISIBLE;
for (let p = this.parent_; p; p = p.getParent()) {
if (p.getVisibilityState() != VisibilityState_Enum.VISIBLE) {
parentVisibilityState = p.getVisibilityState();
break;
}
}
// Pick the most restricted visibility state.
let visibilityState;
const visibilityStateOverride =
this.visibilityStateOverride_ || VisibilityState_Enum.VISIBLE;
if (
visibilityStateOverride == VisibilityState_Enum.VISIBLE &&
parentVisibilityState == VisibilityState_Enum.VISIBLE &&
naturalVisibilityState == VisibilityState_Enum.VISIBLE
) {
visibilityState = VisibilityState_Enum.VISIBLE;
} else if (
naturalVisibilityState == VisibilityState_Enum.HIDDEN &&
visibilityStateOverride == VisibilityState_Enum.PAUSED
) {
// Hidden document state overrides "paused".
visibilityState = naturalVisibilityState;
} else if (
visibilityStateOverride == VisibilityState_Enum.PAUSED ||
visibilityStateOverride == VisibilityState_Enum.INACTIVE
) {
visibilityState = visibilityStateOverride;
} else if (
parentVisibilityState == VisibilityState_Enum.PAUSED ||
parentVisibilityState == VisibilityState_Enum.INACTIVE
) {
visibilityState = parentVisibilityState;
} else if (
visibilityStateOverride == VisibilityState_Enum.PRERENDER ||
naturalVisibilityState == VisibilityState_Enum.PRERENDER ||
parentVisibilityState == VisibilityState_Enum.PRERENDER
) {
visibilityState = VisibilityState_Enum.PRERENDER;
} else {
visibilityState = VisibilityState_Enum.HIDDEN;
}
if (this.visibilityState_ != visibilityState) {
if (visibilityState == VisibilityState_Enum.VISIBLE) {
const {performance} = this.win;
// We use the initial loading time of the document as the base
// visibleTime. If we are initialized in visible mode, then this is
// accounts for the time that user saw a blank page waiting for JS
// execution.
let visibleTime = Math.floor(
performance.timeOrigin ?? performance.timing.navigationStart
);
if (this.visibilityState_ != null) {
// We're transitioning into visible mode (instead of being
// initialized in it). In this case, we want to adjust the
// visibleTime to the current timestamp, because the user hasn't
// actually been waiting for the page to load. Remember that
// performance.now() is relative to the load time of the document, so
// the current timestamp is actually load+now.
visibleTime += Math.floor(performance.now());
}
this.lastVisibleTime_ = visibleTime;
this.signals_.signal(AmpDocSignals_Enum.FIRST_VISIBLE, visibleTime);
this.signals_.signal(AmpDocSignals_Enum.NEXT_VISIBLE, visibleTime);
} else {
this.signals_.reset(AmpDocSignals_Enum.NEXT_VISIBLE);
}
this.visibilityState_ = visibilityState;
this.visibilityStateHandlers_.fire();
}
}
/**
* Returns a Promise that only ever resolved when the current
* AMP document first becomes visible.
* @return {!Promise}
*/
whenFirstVisible() {
return this.signals_
.whenSignal(AmpDocSignals_Enum.FIRST_VISIBLE)
.then(() => undefined);
}
/**
* Returns a Promise that resolve when current doc becomes visible.
* The promise resolves immediately if doc is already visible.
* @return {!Promise}
*/
whenNextVisible() {
return this.signals_
.whenSignal(AmpDocSignals_Enum.NEXT_VISIBLE)
.then(() => undefined);
}
/**
* Returns the time when the document has become visible for the first time.
* If document has not yet become visible, the returned value is `null`.
* @return {?time}
*/
getFirstVisibleTime() {
return /** @type {?number} */ (
this.signals_.get(AmpDocSignals_Enum.FIRST_VISIBLE)
);
}
/**
* Returns the time when the document has become visible for the last time.
* If document has not yet become visible, the returned value is `null`.
* @return {?time}
*/
getLastVisibleTime() {
return this.lastVisibleTime_;
}
/**
* Returns visibility state configured by the viewer.
* See {@link isVisible}.
* @return {!VisibilityState_Enum}
*/
getVisibilityState() {
return devAssert(this.visibilityState_);
}
/**
* Whether the AMP document currently visible. The reasons why it might not
* be visible include user switching to another tab, browser running the
* document in the prerender mode or viewer running the document in the
* prerender mode.
* @return {boolean}
*/
isVisible() {
return this.visibilityState_ == VisibilityState_Enum.VISIBLE;
}
/**
* Whether the AMP document has been ever visible before. Since the visiblity
* state of a document can be flipped back and forth we sometimes want to know
* if a document has ever been visible.
* @return {boolean}
*/
hasBeenVisible() {
return this.getLastVisibleTime() != null;
}
/**
* Adds a "visibilitychange" event listener for viewer events. The
* callback can check {@link isVisible} and {@link getPrefetchCount}
* methods for more info.
* @param {function(!VisibilityState_Enum)} handler
* @return {!UnlistenDef}
*/
onVisibilityChanged(handler) {
return this.visibilityStateHandlers_.add(handler);
}
/**
* Attempt to register a singleton for each ampdoc.
* Caller need to handle user error when registration returns false.
* @param {!../enums.AMPDOC_SINGLETON_NAME_ENUM} name
* @return {boolean}
*/
registerSingleton(name) {
if (!this.registeredSingleton_[name]) {
this.registeredSingleton_[name] = true;
return true;
}
return false;
}
}
/**
* The version of `AmpDoc` in the single-doc mode that corresponds to the
* global `window.document`.
* @package @visibleForTesting
*/
export class AmpDocSingle extends AmpDoc {
/**
* @param {!Window} win
* @param {!AmpDocOptions=} opt_options
*/
constructor(win, opt_options) {
super(win, /* parent */ null, opt_options);
/** @private @const {!Promise<!Element>} */
this.bodyPromise_ = this.win.document.body
? Promise.resolve(this.win.document.body)
: waitForBodyOpenPromise(this.win.document).then(() => this.getBody());
/** @private @const {!Promise} */
this.readyPromise_ = whenDocumentReady(this.win.document);
}
/** @override */
isSingleDoc() {
return true;
}
/** @override */
getRootNode() {
return this.win.document;
}
/** @override */
getUrl() {
return WindowInterface.getLocation(this.win).href;
}
/** @override */
getHeadNode() {
return dev().assertElement(this.win.document.head);
}
/** @override */
isBodyAvailable() {
return !!this.win.document.body;
}
/** @override */
getBody() {
return dev().assertElement(this.win.document.body, 'body not available');
}
/** @override */
waitForBodyOpen() {
return this.bodyPromise_;
}
/** @override */
isReady() {
return isDocumentReady(this.win.document);
}
/** @override */
whenReady() {
return this.readyPromise_;
}
}
/**
* The version of `AmpDoc` in the shadow-doc mode that is allocated for each
* ampdoc hosted within a shadow root.
* @package @visibleForTesting
*/
export class AmpDocShadow extends AmpDoc {
/**
* @param {!Window} win
* @param {string} url
* @param {!ShadowRoot} shadowRoot
* @param {!AmpDocOptions=} opt_options
*/
constructor(win, url, shadowRoot, opt_options) {
super(win, /* parent */ null, opt_options);
/** @private @const {string} */
this.url_ = url;
/** @private @const {!ShadowRoot} */
this.shadowRoot_ = shadowRoot;
/** @private {?Element} */
this.body_ = null;
const bodyDeferred = new Deferred();
/** @private {!Promise<!Element>} */
this.bodyPromise_ = bodyDeferred.promise;
/** @private {function(!Element)|undefined} */
this.bodyResolver_ = bodyDeferred.resolve;
/** @private {boolean} */
this.ready_ = false;
const readyDeferred = new Deferred();
/** @private {!Promise} */
this.readyPromise_ = readyDeferred.promise;
/** @private {function()|undefined} */
this.readyResolver_ = readyDeferred.resolve;
}
/** @override */
isSingleDoc() {
return false;
}
/** @override */
getRootNode() {
return this.shadowRoot_;
}
/** @override */
getUrl() {
return this.url_;
}
/** @override */
getHeadNode() {
return this.shadowRoot_;
}
/** @override */
isBodyAvailable() {
return !!this.body_;
}
/** @override */
getBody() {
return dev().assertElement(this.body_, 'body not available');
}
/**
* Signals that the shadow doc has a body.
* @param {!Element} body
* @restricted
*/
setBody(body) {
devAssert(!this.body_, 'Duplicate body');
this.body_ = body;
this.bodyResolver_(body);
this.bodyResolver_ = undefined;
}
/** @override */
waitForBodyOpen() {
return this.bodyPromise_;
}
/** @override */
isReady() {
return this.ready_;
}
/**
* Signals that the shadow doc is ready.
* @restricted
*/
setReady() {
devAssert(!this.ready_, 'Duplicate ready state');
this.ready_ = true;
this.readyResolver_();
this.readyResolver_ = undefined;
}
/** @override */
whenReady() {
return this.readyPromise_;
}
/** @override */
getMeta() {
return /** @type {!Object<string,string>} */ (map(this.meta_));
}
/** @override */
setMetaByName(name, content) {
devAssert(name, 'Attempted to store invalid meta name/content pair');
if (!this.meta_) {
this.meta_ = map();
}
this.meta_[name] = content;
}
}
/**
* The version of `AmpDoc` for FIE embeds.
* @package @visibleForTesting
*/
export class AmpDocFie extends AmpDoc {
/**
* @param {!Window} win
* @param {string} url
* @param {!AmpDoc} parent
* @param {!AmpDocOptions=} opt_options
*/
constructor(win, url, parent, opt_options) {
super(win, parent, opt_options);
/** @private @const {string} */
this.url_ = url;
/** @private @const {!Promise<!Element>} */
this.bodyPromise_ = this.win.document.body
? Promise.resolve(this.win.document.body)
: waitForBodyOpenPromise(this.win.document).then(() => this.getBody());
/** @private {boolean} */
this.ready_ = false;
const readyDeferred = new Deferred();
/** @private {!Promise} */
this.readyPromise_ = readyDeferred.promise;
/** @private {function()|undefined} */
this.readyResolver_ = readyDeferred.resolve;
}
/** @override */
isSingleDoc() {
return false;
}
/** @override */
getRootNode() {
return this.win.document;
}
/** @override */
getUrl() {
return this.url_;
}
/** @override */
getHeadNode() {
return dev().assertElement(this.win.document.head);
}
/** @override */
isBodyAvailable() {
return !!this.win.document.body;
}
/** @override */
getBody() {
return dev().assertElement(this.win.document.body, 'body not available');
}
/** @override */
waitForBodyOpen() {