forked from ampproject/amphtml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
amp-story.js
1743 lines (1499 loc) · 48.3 KB
/
amp-story.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 2017 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.
*/
/**
* @fileoverview Embeds a story
*
* Example:
* <code>
* <amp-story standalone>
* [...]
* </amp-story>
* </code>
*/
import './amp-story-cta-layer';
import './amp-story-grid-layer';
import './amp-story-page';
import {
Action,
AmpStoryStoreService,
StateProperty,
} from './amp-story-store-service';
import {ActionTrust} from '../../../src/action-constants';
import {AmpStoryAnalytics} from './analytics';
import {AmpStoryBackground} from './background';
import {AmpStoryConsent} from './amp-story-consent';
import {AmpStoryCtaLayer} from './amp-story-cta-layer';
import {AmpStoryGridLayer} from './amp-story-grid-layer';
import {AmpStoryHint} from './amp-story-hint';
import {AmpStoryPage} from './amp-story-page';
import {AmpStoryRenderService} from './amp-story-render-service';
import {AmpStoryRequestService} from './amp-story-request-service';
import {AmpStoryVariableService} from './variable-service';
import {Bookend} from './amp-story-bookend';
import {CSS} from '../../../build/amp-story-0.1.css';
import {CommonSignals} from '../../../src/common-signals';
import {
DoubletapRecognizer,
SwipeXYRecognizer,
} from '../../../src/gesture-recognizers';
import {EventType, dispatch} from './events';
import {Gestures} from '../../../src/gesture';
import {InfoDialog} from './amp-story-info-dialog';
import {Keys} from '../../../src/utils/key-codes';
import {Layout} from '../../../src/layout';
import {LocalizationService} from '../../../src/service/localization';
import {
LocalizedStringId,
createPseudoLocale,
} from '../../../src/localized-strings';
import {MediaPool, MediaType} from './media-pool';
import {NavigationState} from './navigation-state';
import {ORIGIN_WHITELIST} from './origin-whitelist';
import {PaginationButtons} from './pagination-buttons';
import {Services} from '../../../src/services';
import {ShareMenu} from './amp-story-share-menu';
import {ShareWidget} from './amp-story-share';
import {SystemLayer} from './amp-story-system-layer';
import {TapNavigationDirection} from './page-advancement';
import {UnsupportedBrowserLayer} from './amp-story-unsupported-browser-layer';
import {ViewportWarningLayer} from './amp-story-viewport-warning-layer';
import {
childElement,
childElementByTag,
childElements,
closest,
matches,
removeElement,
scopedQuerySelectorAll,
whenUpgradedToCustomElement,
} from '../../../src/dom';
import {
computedStyle,
resetStyles,
setImportantStyles,
toggle,
} from '../../../src/style';
import {debounce} from '../../../src/utils/rate-limit';
import {dev, devAssert, user} from '../../../src/log';
import {dict} from '../../../src/utils/object';
import {escapeCssSelectorIdent} from '../../../src/css';
import {findIndex} from '../../../src/utils/array';
import {getDetail} from '../../../src/event-helper';
import {getMode} from '../../../src/mode';
import {getSourceOrigin, parseUrlDeprecated} from '../../../src/url';
import {getState} from '../../../src/history';
import {isExperimentOn, toggleExperiment} from '../../../src/experiments';
import {registerServiceBuilder} from '../../../src/service';
import {renderSimpleTemplate} from './simple-template';
import {stringHash32} from '../../../src/string';
import {upgradeBackgroundAudio} from './audio';
import LocalizedStringsDefault from './_locales/default';
import LocalizedStringsEn from './_locales/en';
/** @private @const {string} */
const PRE_ACTIVE_PAGE_ATTRIBUTE_NAME = 'pre-active';
/** @private @const {string} */
const AMP_STORY_STANDALONE_ATTRIBUTE = 'standalone';
/** @private @const {number} */
const DESKTOP_WIDTH_THRESHOLD = 1024;
/** @private @const {number} */
const DESKTOP_HEIGHT_THRESHOLD = 550;
/** @private @const {number} */
const MIN_SWIPE_FOR_HINT_OVERLAY_PX = 50;
/** @private @const {string} */
const ADVANCE_TO_ATTR = 'i-amphtml-advance-to';
/** @private @const {string} */
const RETURN_TO_ATTR = 'i-amphtml-return-to';
/** @private @const {string} */
const AUTO_ADVANCE_TO_ATTR = 'auto-advance-to';
/** @private @const {string} */
const AD_SHOWING_ATTR = 'ad-showing';
/**
* The duration of time (in milliseconds) to wait for a page to be loaded,
* before the story becomes visible.
* @const {number}
*/
const PAGE_LOAD_TIMEOUT_MS = 5000;
/**
* CSS class for an amp-story that indicates the initial load for the story has
* completed.
* @const {string}
*/
const STORY_LOADED_CLASS_NAME = 'i-amphtml-story-loaded';
/** @const {!Object<string, number>} */
const MAX_MEDIA_ELEMENT_COUNTS = {
[MediaType.AUDIO]: 4,
[MediaType.VIDEO]: 8,
};
/** @type {string} */
const TAG = 'amp-story';
/**
* Container for "pill-style" share widget, rendered on desktop.
* @private @const {!./simple-template.ElementDef}
*/
const SHARE_WIDGET_PILL_CONTAINER = {
tag: 'div',
attrs: dict({'class': 'i-amphtml-story-share-pill'}),
children: [
{
tag: 'span',
attrs: dict({'class': 'i-amphtml-story-share-pill-label'}),
localizedStringId:
LocalizedStringId.DEPRECATED_AMP_STORY_SYSTEM_LAYER_SHARE_WIDGET_LABEL,
},
],
};
/**
* Selector for elements that should be hidden when the bookend is open on
* desktop view.
* @private @const {string}
*/
const HIDE_ON_BOOKEND_SELECTOR =
'amp-story-page, .i-amphtml-story-system-layer';
/**
* @implements {./media-pool.MediaPoolRoot}
*/
export class AmpStory extends AMP.BaseElement {
/** @param {!AmpElement} element */
constructor(element) {
super(element);
/** @private @const {!AmpStoryStoreService} */
this.storeService_ = new AmpStoryStoreService(this.win);
registerServiceBuilder(this.win, 'story-store', () => this.storeService_);
/** @private @const {!AmpStoryRequestService} */
this.requestService_ = new AmpStoryRequestService(this.win, this.element);
registerServiceBuilder(
this.win,
'story-request-v01',
() => this.requestService_
);
/** @private {!NavigationState} */
this.navigationState_ = new NavigationState(this.win, () =>
this.hasBookend_()
);
/** @private {!AmpStoryAnalytics} */
this.analytics_ = new AmpStoryAnalytics(this.win, this.element);
/** @const @private {!../../../src/service/vsync-impl.Vsync} */
this.vsync_ = this.getVsync();
/** @private @const {!LocalizationService} */
this.localizationService_ = new LocalizationService(this.win);
this.localizationService_
.registerLocalizedStringBundle('default', LocalizedStringsDefault)
.registerLocalizedStringBundle('en', LocalizedStringsEn);
const enXaPseudoLocaleBundle = createPseudoLocale(
LocalizedStringsEn,
s => `[${s} one two]`
);
this.localizationService_.registerLocalizedStringBundle(
'en-xa',
enXaPseudoLocaleBundle
);
registerServiceBuilder(
this.win,
'localization-v01',
() => this.localizationService_
);
/** @private @const {!Bookend} */
this.bookend_ = new Bookend(this.win, this.element);
/** @private @const {!ShareMenu} Preloads and prerenders the share menu. */
this.shareMenu_ = new ShareMenu(this.win, this.element);
/** @private @const {!SystemLayer} */
this.systemLayer_ = new SystemLayer(this.win);
/** @private @const {!UnsupportedBrowserLayer} */
this.unsupportedBrowserLayer_ = new UnsupportedBrowserLayer(this.win);
/** Instantiates the viewport warning layer. */
new ViewportWarningLayer(this.win, this.element);
/** @private @const {!Array<!./amp-story-page.AmpStoryPage>} */
this.pages_ = [];
/** @private @const {!Array<!./amp-story-page.AmpStoryPage>} */
this.adPages_ = [];
/** @const @private {!AmpStoryVariableService} */
this.variableService_ = new AmpStoryVariableService();
registerServiceBuilder(this.win, 'story-variable', () =>
this.variableService_.get()
);
/** @private {?./amp-story-page.AmpStoryPage} */
this.activePage_ = null;
/** @private @const */
this.desktopMedia_ = this.win.matchMedia(
`(min-width: ${DESKTOP_WIDTH_THRESHOLD}px) and ` +
`(min-height: ${DESKTOP_HEIGHT_THRESHOLD}px)`
);
/** @private @const */
this.canRotateToDesktopMedia_ = this.win.matchMedia(
`(min-width: ${DESKTOP_HEIGHT_THRESHOLD}px) and ` +
`(min-height: ${DESKTOP_WIDTH_THRESHOLD}px)`
);
/** @private {?AmpStoryBackground} */
this.background_ = null;
/** @private {?HTMLMediaElement} */
this.backgroundAudioEl_ = null;
/** @private {?./pagination-buttons.PaginationButtons} */
this.paginationButtons_ = null;
/** @private {?Element} */
this.topBar_ = null;
/** @private {?ShareWidget} */
this.shareWidget_ = null;
/** @private @const {!Array<string>} */
this.originWhitelist_ = ORIGIN_WHITELIST;
/** @private {!AmpStoryHint} */
this.ampStoryHint_ = new AmpStoryHint(this.win, this.element);
/** @private {!MediaPool} */
this.mediaPool_ = MediaPool.for(this);
/** @private @const {!../../../src/service/timer-impl.Timer} */
this.timer_ = Services.timerFor(this.win);
/** @private @const {!../../../src/service/platform-impl.Platform} */
this.platform_ = Services.platformFor(this.win);
}
/** @override */
buildCallback() {
this.assertAmpStoryExperiment_();
if (this.element.hasAttribute(AMP_STORY_STANDALONE_ATTRIBUTE)) {
this.initializeStandaloneStory_();
}
// buildCallback already runs in a mutate context. Calling another
// mutateElement explicitly will force the runtime to remeasure the
// amp-story element, fixing rendering bugs where the story is inactive
// (layoutCallback not called) when accessed from any viewer using
// prerendering, because of a height incorrectly set to 0.
this.mutateElement(() => {});
this.element.querySelector('amp-story-page').setAttribute('active', '');
this.initializeListeners_();
this.initializeListenersForDev_();
if (this.isDesktop_()) {
this.storeService_.dispatch(Action.TOGGLE_DESKTOP, true);
}
this.navigationState_.observe(stateChangeEvent => {
this.variableService_.onNavigationStateChange(stateChangeEvent);
this.analytics_.onNavigationStateChange(stateChangeEvent);
});
}
/** @private */
initializeStandaloneStory_() {
const html = this.win.document.documentElement;
html.classList.add('i-amphtml-story-standalone');
// Lock body to prevent overflow.
this.lockBody_();
// Standalone CSS affects sizing of the entire page.
this.onResize();
}
/**
* Builds the system layer DOM. This is dependent on the pages_ array having
* been initialized, so it cannot happen at build time.
* @private
*/
buildSystemLayer_() {
const pageIds = this.pages_.map(page => page.element.id);
this.element.appendChild(this.systemLayer_.build(pageIds));
this.updateAudioIcon_();
}
/** @private */
initializeListeners_() {
this.element.addEventListener(EventType.NEXT_PAGE, () => {
this.next_();
});
this.element.addEventListener(EventType.PREVIOUS_PAGE, () => {
this.previous_();
});
this.storeService_.subscribe(
StateProperty.MUTED_STATE,
isMuted => {
this.onMutedStateUpdate_(isMuted);
this.variableService_.onMutedStateChange(isMuted);
},
true /** callToInitialize */
);
this.storeService_.subscribe(
StateProperty.MUTED_STATE,
isMuted => {
// We do not want to trigger an analytics event for the initialization of
// the muted state.
this.analytics_.onMutedStateChange(isMuted);
},
false /** callToInitialize */
);
this.storeService_.subscribe(
StateProperty.SUPPORTED_BROWSER_STATE,
isBrowserSupported => {
this.onSupportedBrowserStateUpdate_(isBrowserSupported);
}
);
this.element.addEventListener(EventType.SWITCH_PAGE, e => {
if (this.storeService_.get(StateProperty.BOOKEND_STATE)) {
// Disallow switching pages while the bookend is active.
return;
}
this.switchTo_(getDetail(e)['targetPageId']);
this.ampStoryHint_.hideAllNavigationHint();
});
this.element.addEventListener(EventType.PAGE_PROGRESS, e => {
const detail = getDetail(e);
const pageId = detail['pageId'];
const progress = detail['progress'];
if (pageId !== this.activePage_.element.id) {
// Ignore progress update events from inactive pages.
return;
}
if (!this.activePage_.isAd()) {
this.systemLayer_.updateProgress(pageId, progress);
}
});
this.element.addEventListener(EventType.REPLAY, () => {
this.replay_();
});
this.element.addEventListener(EventType.SHOW_NO_PREVIOUS_PAGE_HELP, () => {
if (this.storeService_.get(StateProperty.CAN_SHOW_PREVIOUS_PAGE_HELP)) {
this.ampStoryHint_.showFirstPageHintOverlay();
}
});
this.element.addEventListener(EventType.TAP_NAVIGATION, e => {
const direction = getDetail(e)['direction'];
this.performTapNavigation_(direction);
});
this.storeService_.subscribe(StateProperty.BOOKEND_STATE, isActive => {
this.onBookendStateUpdate_(isActive);
});
this.storeService_.subscribe(
StateProperty.DESKTOP_STATE,
isDesktop => {
this.onDesktopStateUpdate_(isDesktop);
},
true /** callToInitialize */
);
this.win.document.addEventListener(
'keydown',
e => {
this.onKeyDown_(e);
},
true
);
this.storeService_.subscribe(StateProperty.CURRENT_PAGE_ID, pageId => {
this.onCurrentPageIdUpdate_(pageId);
});
this.getViewport().onResize(debounce(this.win, () => this.onResize(), 300));
this.installGestureRecognizers_();
}
/** @private */
installGestureRecognizers_() {
const {element} = this;
const gestures = Gestures.get(element, /* shouldNotPreventDefault */ true);
// Disables zoom on double-tap.
gestures.onGesture(DoubletapRecognizer, gesture => {
const {event} = gesture;
event.preventDefault();
});
// Shows "tap to navigate" hint when swiping.
gestures.onGesture(SwipeXYRecognizer, gesture => {
const {deltaX, deltaY} = gesture.data;
if (this.storeService_.get(StateProperty.BOOKEND_STATE)) {
return;
}
if (!this.isSwipeLargeEnoughForHint_(deltaX, deltaY)) {
return;
}
if (
!this.storeService_.get(StateProperty.CAN_SHOW_NAVIGATION_OVERLAY_HINT)
) {
return;
}
this.ampStoryHint_.showNavigationOverlay();
});
}
/**
* @param {number} deltaX
* @param {number} deltaY
* @return {boolean}
* @private
*/
isSwipeLargeEnoughForHint_(deltaX, deltaY) {
const sideSwipe = Math.abs(deltaX) >= MIN_SWIPE_FOR_HINT_OVERLAY_PX;
const upSwipe = -1 * deltaY >= MIN_SWIPE_FOR_HINT_OVERLAY_PX;
return sideSwipe || upSwipe;
}
/** @private */
initializeListenersForDev_() {
if (!getMode().development) {
return;
}
this.element.addEventListener(EventType.DEV_LOG_ENTRIES_AVAILABLE, e => {
this.systemLayer_.logAll(/** @type {?} */ (getDetail(e)));
});
}
/** @private */
lockBody_() {
const {document} = this.win;
setImportantStyles(document.documentElement, {
'overflow': 'hidden',
});
setImportantStyles(document.body, {
'overflow': 'hidden',
});
this.getViewport().resetTouchZoom();
this.getViewport().disableTouchZoom();
this.maybeLockScreenOrientation_();
}
/** @private */
maybeLockScreenOrientation_() {
const {screen} = this.win;
if (!screen || !this.canRotateToDesktopMedia_.matches) {
return;
}
const lockOrientation =
screen.lockOrientation ||
screen.mozLockOrientation ||
screen.msLockOrientation ||
(unusedOrientation => {});
try {
lockOrientation('portrait');
} catch (e) {
dev().warn(TAG, 'Failed to lock screen orientation:', e.message);
}
}
/** @private */
buildPaginationButtons_() {
this.paginationButtons_ = PaginationButtons.create(this.win);
this.paginationButtons_.attach(this.element);
this.navigationState_.observe(e =>
this.paginationButtons_.onNavigationStateChange(e)
);
}
/** @visibleForTesting */
buildPaginationButtonsForTesting() {
this.buildPaginationButtons_();
}
/** @private */
buildTopBar_() {
const doc = this.element.ownerDocument;
this.topBar_ = doc.createElement('div');
this.topBar_.classList.add(
'i-amphtml-story-top',
'i-amphtml-story-system-reset'
);
this.topBar_.appendChild(this.buildTopBarShare_());
this.element.insertBefore(this.topBar_, this.element.firstChild);
}
/**
* @return {!Node}
* @private
*/
buildTopBarShare_() {
const container = renderSimpleTemplate(
this.win.document,
SHARE_WIDGET_PILL_CONTAINER
);
this.shareWidget_ = new ShareWidget(this.win);
const shareLabelEl = dev().assertElement(
container.querySelector('.i-amphtml-story-share-pill-label'),
'Expected share pill label to be present.'
);
container.insertBefore(
this.shareWidget_.build(this.getAmpDoc()),
shareLabelEl
);
return container;
}
/** @override */
layoutCallback() {
if (!AmpStory.isBrowserSupported(this.win) && !this.platform_.isBot()) {
this.storeService_.dispatch(Action.TOGGLE_SUPPORTED_BROWSER, false);
return Promise.resolve();
}
const firstPageEl = user().assertElement(
this.element.querySelector('amp-story-page'),
'Story must have at least one page.'
);
const initialPageId = this.getHistoryStatePageId_() || firstPageEl.id;
if (!this.paginationButtons_) {
this.buildPaginationButtons_();
}
const storyLayoutPromise = this.initializePages_()
.then(() => this.buildSystemLayer_())
.then(() => {
this.pages_.forEach(page => {
page.setActive(false);
});
})
.then(() => this.switchTo_(initialPageId))
.then(() => this.preloadPagesByDistance_())
.then(() => {
// Preloads and prerenders the share menu if mobile, where the share
// button is visible.
if (!this.storeService_.get(StateProperty.DESKTOP_STATE)) {
this.shareMenu_.build();
}
const infoDialog = Services.viewerForDoc(this.element).isEmbedded()
? new InfoDialog(this.win, this.element)
: null;
if (infoDialog) {
infoDialog.build();
}
});
// Do not block the layout callback on the completion of these promises, as
// that prevents descendents from being laid out (and therefore loaded).
storyLayoutPromise
.then(() => this.whenPagesLoaded_(PAGE_LOAD_TIMEOUT_MS))
.then(() => this.markStoryAsLoaded_());
this.validateConsent_();
// Story is being prerendered: resolve the layoutCallback when the first
// page is built. Other pages will only build if the document becomes
// visible.
if (!Services.viewerForDoc(this.element).hasBeenVisible()) {
return whenUpgradedToCustomElement(firstPageEl).then(() =>
firstPageEl.whenBuilt()
);
}
return storyLayoutPromise;
}
/**
* @param {number} timeoutMs The maximum amount of time to wait, in
* milliseconds.
* @return {!Promise} A promise that is resolved when the page is loaded or
* the timeout has been exceeded, whichever happens first.
* @private
*/
whenPagesLoaded_(timeoutMs = 0) {
const pagesToWaitFor = this.isDesktop_()
? [this.pages_[0], this.pages_[1]]
: [this.pages_[0]];
const storyLoadPromise = Promise.all(
pagesToWaitFor.filter(page => !!page).map(page => page.whenLoaded())
);
return this.timer_
.timeoutPromise(timeoutMs, storyLoadPromise)
.catch(() => {});
}
/** @private */
markStoryAsLoaded_() {
dispatch(this.element, EventType.STORY_LOADED, true);
this.signals().signal(CommonSignals.INI_LOAD);
this.mutateElement(() => {
this.element.classList.add(STORY_LOADED_CLASS_NAME);
});
}
/**
* Ensures publishers using amp-consent use amp-story-consent.
* @private
*/
validateConsent_() {
const consentEl = this.element.querySelector('amp-consent');
if (!consentEl) {
return;
}
if (!childElementByTag(consentEl, 'amp-story-consent')) {
dev().error(TAG, 'amp-consent must have an amp-story-consent child');
}
const allowedTags = ['SCRIPT', 'AMP-STORY-CONSENT'];
const toRemoveChildren = childElements(
consentEl,
el => allowedTags.indexOf(el.tagName) === -1
);
if (toRemoveChildren.length === 0) {
return;
}
dev().error(TAG, `amp-consent only allows tags: ${allowedTags}`);
toRemoveChildren.forEach(el => consentEl.removeChild(el));
}
/** @override */
isLayoutSupported(layout) {
return layout == Layout.CONTAINER;
}
/** @override */
prerenderAllowed() {
return true;
}
/** @private */
isAmpStoryEnabled_() {
if (
isExperimentOn(this.win, 'amp-story') ||
getMode().test ||
this.win.location.protocol === 'file:'
) {
return true;
}
const origin = getSourceOrigin(this.win.location);
return this.isOriginWhitelisted_(origin);
}
/**
* @param {string} domain The domain part of the origin, to be hashed.
* @return {string} The hashed origin.
* @private
*/
hashOrigin_(domain) {
return stringHash32(domain.toLowerCase());
}
/**
* @param {string} origin The origin to check.
* @return {boolean} Whether the specified origin is whitelisted to use the
* amp-story extension.
* @private
*/
isOriginWhitelisted_(origin) {
const hostName = parseUrlDeprecated(origin).hostname;
const domains = hostName.split('.');
// Check all permutations of the domain to see if any level of the domain is
// whitelisted. Taking the example of the whitelisted domain
// example.co.uk, if the page is served from www.example.co.uk/page.html:
//
// www.example.co.uk => false
// example.co.uk => true
// co.uk => false
// uk => false
//
// This is necessary, since we don't have any guarantees of which level of
// the domain is whitelisted. For many domains (e.g. .com), the second
// level of the domain is likely to be whitelisted, whereas for others
// (e.g. .co.uk) the third level may be whitelisted. Additionally, this
// allows subdomains to be whitelisted individually.
return domains.some((unusedDomain, index) => {
const domain = domains.slice(index, domains.length).join('.');
const domainHash = this.hashOrigin_(domain);
return this.originWhitelist_.includes(domainHash);
});
}
/** @private */
assertAmpStoryExperiment_() {
if (this.isAmpStoryEnabled_()) {
return;
}
const errorIconEl = this.win.document.createElement('div');
errorIconEl.classList.add('i-amphtml-story-experiment-icon');
errorIconEl.classList.add('i-amphtml-story-experiment-icon-error');
const errorMsgEl = this.win.document.createElement('span');
errorMsgEl.textContent = this.localizationService_.getLocalizedString(
LocalizedStringId.AMP_STORY_WARNING_EXPERIMENT_DISABLED_TEXT
);
const experimentsLinkEl = this.win.document.createElement('button');
experimentsLinkEl.textContent = this.localizationService_.getLocalizedString(
LocalizedStringId.DEPRECATED_AMP_STORY_EXPERIMENT_ENABLE_BUTTON_LABEL
);
experimentsLinkEl.addEventListener('click', () => {
toggleExperiment(this.win, 'amp-story', true);
errorIconEl.classList.remove('i-amphtml-story-experiment-icon-error');
errorIconEl.classList.add('i-amphtml-story-experiment-icon-done');
errorMsgEl.textContent = this.localizationService_.getLocalizedString(
LocalizedStringId.DEPRECATED_AMP_STORY_EXPERIMENT_ENABLED_TEXT
);
removeElement(experimentsLinkEl);
});
const errorEl = this.win.document.createElement('div');
errorEl.classList.add('i-amphtml-story-experiment-error');
errorEl.appendChild(errorIconEl);
errorEl.appendChild(errorMsgEl);
errorEl.appendChild(experimentsLinkEl);
this.element.appendChild(errorEl);
user().error(TAG, 'enable amp-story experiment');
}
/** @private */
initializePages_() {
const pageImplPromises = Array.prototype.map.call(
this.element.querySelectorAll('amp-story-page'),
(pageEl, index) => {
return pageEl.getImpl().then(pageImpl => {
this.pages_[index] = pageImpl;
});
}
);
return Promise.all(pageImplPromises);
}
/**
* Advance to the next screen in the story, if there is one.
* @param {boolean=} opt_isAutomaticAdvance Whether this navigation was caused
* by an automatic advancement after a timeout.
* @private
*/
next_(opt_isAutomaticAdvance) {
const activePage = devAssert(
this.activePage_,
'No active page set when navigating to next page.'
);
const lastPage = this.pages_[this.getPageCount() - 1];
if (
activePage.element.hasAttribute(ADVANCE_TO_ATTR) ||
activePage !== lastPage
) {
activePage.next(opt_isAutomaticAdvance);
} else {
this.hasBookend_().then(hasBookend => {
if (hasBookend) {
this.showBookend_();
}
});
}
}
/**
* Go back to the previous screen in the story, if there is one.
* @private
*/
previous_() {
const activePage = devAssert(
this.activePage_,
'No active page set when navigating to next page.'
);
activePage.previous();
}
/**
* @param {!TapNavigationDirection} direction The direction to navigate.
* @private
*/
performTapNavigation_(direction) {
if (this.isDesktop_()) {
this.next_();
return;
}
if (direction === TapNavigationDirection.NEXT) {
this.next_();
} else if (direction === TapNavigationDirection.PREVIOUS) {
this.previous_();
}
}
/**
* Switches to a particular page.
* @param {string} targetPageId
* @return {!Promise}
*/
switchTo_(targetPageId) {
const targetPage = this.getPageById(targetPageId);
const pageIndex = this.getPageIndex(targetPage);
this.storeService_.dispatch(Action.CHANGE_PAGE, {
id: targetPageId,
index: pageIndex,
});
this.updateBackground_(targetPage.element, /* initial */ !this.activePage_);
if (targetPage.isAd()) {
this.vsync_.mutate(() => {
this.element.setAttribute(AD_SHOWING_ATTR, '');
});
} else {
this.vsync_.mutate(() => {
this.element.removeAttribute(AD_SHOWING_ATTR);
});
// TODO(alanorozco): decouple this using NavigationState
this.systemLayer_.setActivePageId(targetPageId);
}
// TODO(alanorozco): check if autoplay
this.navigationState_.updateActivePage(
pageIndex,
this.getPageCount(),
targetPage.element.id
);
const oldPage = this.activePage_;
// TODO(cvializ): Move this to the page class?
const activePriorSibling = targetPage.element.previousElementSibling;
const previousActivePriorSibling = this.element.querySelector(
`[${escapeCssSelectorIdent(PRE_ACTIVE_PAGE_ATTRIBUTE_NAME)}]`
);
this.activePage_ = targetPage;
this.systemLayer_.resetDeveloperLogs();
this.systemLayer_.setDeveloperLogContextString(this.activePage_.element.id);
return targetPage.beforeVisible().then(() => {
this.triggerActiveEventForPage_();
if (oldPage) {
oldPage.setActive(false);
}
targetPage.setActive(true);
if (activePriorSibling && matches(activePriorSibling, 'amp-story-page')) {
activePriorSibling.setAttribute(PRE_ACTIVE_PAGE_ATTRIBUTE_NAME, '');
}
if (previousActivePriorSibling) {
previousActivePriorSibling.removeAttribute(
PRE_ACTIVE_PAGE_ATTRIBUTE_NAME
);
}
// If first navigation.
if (!oldPage) {
this.registerAndPreloadBackgroundAudio_();
}
this.preloadPagesByDistance_();
this.reapplyMuting_();
this.forceRepaintForSafari_();
this.maybePreloadBookend_();
});
}
/** @private */
triggerActiveEventForPage_() {
// TODO(alanorozco): pass event priority once amphtml-story repo is merged
// with upstream.
Services.actionServiceForDoc(this.element).trigger(
this.activePage_.element,
'active',
/* event */ null,
ActionTrust.HIGH
);
}
/**
* For some reason, Safari has an issue where sometimes when pages become
* visible, some descendants are not painted. This is a hack where we detect
* that the browser is Safari and force it to repaint, to avoid this case.
* See newmuis/amphtml-story#106 for details.
* @private
*/
forceRepaintForSafari_() {
if (!this.platform_.isSafari() && !this.platform_.isIos()) {
return;
}
if (this.isDesktop_()) {
// Force repaint is only needed when transitioning from invisible to
// visible