summaryrefslogtreecommitdiffstats
path: root/browser/components/newtab
diff options
context:
space:
mode:
Diffstat (limited to 'browser/components/newtab')
-rw-r--r--browser/components/newtab/.eslintrc.js226
-rw-r--r--browser/components/newtab/.nvmrc1
-rw-r--r--browser/components/newtab/.sass-lint.yml27
-rw-r--r--browser/components/newtab/AboutNewTabService.jsm512
-rw-r--r--browser/components/newtab/aboutwelcome/AboutWelcomeChild.jsm386
-rw-r--r--browser/components/newtab/aboutwelcome/AboutWelcomeParent.jsm310
-rw-r--r--browser/components/newtab/aboutwelcome/content/aboutwelcome.bundle.js1501
-rw-r--r--browser/components/newtab/aboutwelcome/content/aboutwelcome.css538
-rw-r--r--browser/components/newtab/aboutwelcome/content/aboutwelcome.html26
-rw-r--r--browser/components/newtab/aboutwelcome/lib/AboutWelcomeTelemetry.jsm115
-rw-r--r--browser/components/newtab/actors/ASRouterChild.jsm109
-rw-r--r--browser/components/newtab/actors/ASRouterParent.jsm115
-rw-r--r--browser/components/newtab/bin/render-activity-stream-html.js130
-rw-r--r--browser/components/newtab/bin/try-runner.js179
-rw-r--r--browser/components/newtab/bin/vendor.js38
-rw-r--r--browser/components/newtab/common/Actions.jsm451
-rw-r--r--browser/components/newtab/common/ActorConstants.jsm45
-rw-r--r--browser/components/newtab/common/Dedupe.jsm38
-rw-r--r--browser/components/newtab/common/Reducers.jsm834
-rw-r--r--browser/components/newtab/components.conf14
-rw-r--r--browser/components/newtab/components/CustomElements/paragraph.js72
-rw-r--r--browser/components/newtab/content-src/.eslintrc.js12
-rw-r--r--browser/components/newtab/content-src/aboutwelcome/aboutwelcome.jsx188
-rw-r--r--browser/components/newtab/content-src/aboutwelcome/aboutwelcome.scss673
-rw-r--r--browser/components/newtab/content-src/aboutwelcome/components/FxCards.jsx83
-rw-r--r--browser/components/newtab/content-src/aboutwelcome/components/HeroText.jsx19
-rw-r--r--browser/components/newtab/content-src/aboutwelcome/components/MSLocalized.jsx50
-rw-r--r--browser/components/newtab/content-src/aboutwelcome/components/MultiStageAboutWelcome.jsx445
-rw-r--r--browser/components/newtab/content-src/aboutwelcome/components/ReturnToAMO.jsx100
-rw-r--r--browser/components/newtab/content-src/aboutwelcome/components/SimpleAboutWelcome.jsx35
-rw-r--r--browser/components/newtab/content-src/aboutwelcome/components/Zap.jsx60
-rw-r--r--browser/components/newtab/content-src/activity-stream.jsx54
-rw-r--r--browser/components/newtab/content-src/asrouter/README.md34
-rw-r--r--browser/components/newtab/content-src/asrouter/asrouter-content.jsx326
-rw-r--r--browser/components/newtab/content-src/asrouter/asrouter-utils.js108
-rw-r--r--browser/components/newtab/content-src/asrouter/components/Button/Button.jsx32
-rw-r--r--browser/components/newtab/content-src/asrouter/components/Button/_Button.scss94
-rw-r--r--browser/components/newtab/content-src/asrouter/components/ConditionalWrapper/ConditionalWrapper.jsx9
-rw-r--r--browser/components/newtab/content-src/asrouter/components/ImpressionsWrapper/ImpressionsWrapper.jsx76
-rw-r--r--browser/components/newtab/content-src/asrouter/components/ModalOverlay/ModalOverlay.jsx56
-rw-r--r--browser/components/newtab/content-src/asrouter/components/ModalOverlay/_ModalOverlay.scss104
-rw-r--r--browser/components/newtab/content-src/asrouter/components/RichText/RichText.jsx83
-rw-r--r--browser/components/newtab/content-src/asrouter/components/SnippetBase/SnippetBase.jsx121
-rw-r--r--browser/components/newtab/content-src/asrouter/components/SnippetBase/_SnippetBase.scss117
-rw-r--r--browser/components/newtab/content-src/asrouter/docs/cfr_doorhanger_screenshot.pngbin0 -> 257709 bytes
-rw-r--r--browser/components/newtab/content-src/asrouter/docs/debugging-docs.md62
-rw-r--r--browser/components/newtab/content-src/asrouter/docs/debugging-guide.pngbin0 -> 247644 bytes
-rw-r--r--browser/components/newtab/content-src/asrouter/docs/experiment-guide.md52
-rw-r--r--browser/components/newtab/content-src/asrouter/docs/first-run.md9
-rw-r--r--browser/components/newtab/content-src/asrouter/docs/index.rst104
-rw-r--r--browser/components/newtab/content-src/asrouter/docs/message-routing-overview.pngbin0 -> 50250 bytes
-rw-r--r--browser/components/newtab/content-src/asrouter/docs/simple-cfr-template.rst37
-rw-r--r--browser/components/newtab/content-src/asrouter/docs/targeting-attributes.md828
-rw-r--r--browser/components/newtab/content-src/asrouter/docs/targeting-guide.md37
-rw-r--r--browser/components/newtab/content-src/asrouter/docs/telemetry-screenshot.pngbin0 -> 104954 bytes
-rw-r--r--browser/components/newtab/content-src/asrouter/rich-text-strings.js44
-rw-r--r--browser/components/newtab/content-src/asrouter/schemas/message-format.md101
-rw-r--r--browser/components/newtab/content-src/asrouter/schemas/message-group.schema.json63
-rw-r--r--browser/components/newtab/content-src/asrouter/schemas/panel/cfr-fxa-bookmark.schema.json163
-rw-r--r--browser/components/newtab/content-src/asrouter/schemas/provider-response.schema.json75
-rw-r--r--browser/components/newtab/content-src/asrouter/template-utils.js21
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/CFR/templates/CFRUrlbarChiclet.schema.json75
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/CFR/templates/ExtensionDoorhanger.schema.json365
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/CFR/templates/InfoBar.schema.json96
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/EOYSnippet/EOYSnippet.jsx153
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/EOYSnippet/EOYSnippet.schema.json159
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/EOYSnippet/_EOYSnippet.scss54
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/FXASignupSnippet/FXASignupSnippet.jsx38
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/FXASignupSnippet/FXASignupSnippet.schema.json187
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/FirstRun/addUtmParams.js30
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/NewsletterSnippet/NewsletterSnippet.jsx34
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/NewsletterSnippet/NewsletterSnippet.schema.json177
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/OnboardingMessage/OnboardingMessage.jsx52
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/OnboardingMessage/OnboardingMessage.schema.json142
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/OnboardingMessage/ToolbarBadgeMessage.schema.json39
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/OnboardingMessage/UpdateAction.schema.json36
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/OnboardingMessage/WhatsNewMessage.schema.json97
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/OnboardingMessage/_OnboardingMessage.scss131
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/SendToDeviceSnippet/SendToDeviceSnippet.jsx76
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/SendToDeviceSnippet/SendToDeviceSnippet.schema.json234
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/SendToDeviceSnippet/isEmailOrPhoneNumber.js38
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/SimpleBelowSearchSnippet/SimpleBelowSearchSnippet.jsx133
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/SimpleBelowSearchSnippet/SimpleBelowSearchSnippet.schema.json110
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/SimpleBelowSearchSnippet/_SimpleBelowSearchSnippet.scss198
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/SimpleSnippet/SimpleSnippet.jsx225
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/SimpleSnippet/SimpleSnippet.schema.json155
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/SimpleSnippet/_SimpleSnippet.scss135
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/SubmitFormSnippet/SubmitFormScene2Snippet.schema.json163
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/SubmitFormSnippet/SubmitFormSnippet.jsx409
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/SubmitFormSnippet/SubmitFormSnippet.schema.json225
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/SubmitFormSnippet/_SubmitFormSnippet.scss176
-rw-r--r--browser/components/newtab/content-src/asrouter/templates/template-manifest.jsx24
-rw-r--r--browser/components/newtab/content-src/components/A11yLinkButton/A11yLinkButton.jsx18
-rw-r--r--browser/components/newtab/content-src/components/A11yLinkButton/_A11yLinkButton.scss13
-rw-r--r--browser/components/newtab/content-src/components/ASRouterAdmin/ASRouterAdmin.jsx1936
-rw-r--r--browser/components/newtab/content-src/components/ASRouterAdmin/ASRouterAdmin.scss273
-rw-r--r--browser/components/newtab/content-src/components/ASRouterAdmin/SimpleHashRouter.jsx35
-rw-r--r--browser/components/newtab/content-src/components/Base/Base.jsx294
-rw-r--r--browser/components/newtab/content-src/components/Base/_Base.scss179
-rw-r--r--browser/components/newtab/content-src/components/Card/Card.jsx354
-rw-r--r--browser/components/newtab/content-src/components/Card/_Card.scss369
-rw-r--r--browser/components/newtab/content-src/components/Card/types.js30
-rw-r--r--browser/components/newtab/content-src/components/CollapsibleSection/CollapsibleSection.jsx342
-rw-r--r--browser/components/newtab/content-src/components/CollapsibleSection/_CollapsibleSection.scss188
-rw-r--r--browser/components/newtab/content-src/components/ComponentPerfTimer/ComponentPerfTimer.jsx174
-rw-r--r--browser/components/newtab/content-src/components/ConfirmDialog/ConfirmDialog.jsx103
-rw-r--r--browser/components/newtab/content-src/components/ConfirmDialog/_ConfirmDialog.scss68
-rw-r--r--browser/components/newtab/content-src/components/ContextMenu/ContextMenu.jsx179
-rw-r--r--browser/components/newtab/content-src/components/ContextMenu/ContextMenuButton.jsx72
-rw-r--r--browser/components/newtab/content-src/components/ContextMenu/_ContextMenu.scss55
-rw-r--r--browser/components/newtab/content-src/components/CustomizeMenu/BackgroundsSection/BackgroundsSection.jsx11
-rw-r--r--browser/components/newtab/content-src/components/CustomizeMenu/ContentSection/ContentSection.jsx277
-rw-r--r--browser/components/newtab/content-src/components/CustomizeMenu/CustomizeMenu.jsx38
-rw-r--r--browser/components/newtab/content-src/components/CustomizeMenu/ThemesSection/ThemesSection.jsx11
-rw-r--r--browser/components/newtab/content-src/components/CustomizeMenu/_CustomizeMenu.scss297
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamBase/DiscoveryStreamBase.jsx393
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamBase/_DiscoveryStreamBase.scss70
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/CardGrid/CardGrid.jsx109
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/CardGrid/_CardGrid.scss164
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/CollectionCardGrid/CollectionCardGrid.jsx139
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/CollectionCardGrid/_CollectionCardGrid.scss46
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSCard/DSCard.jsx323
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSCard/_DSCard.scss313
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSContextFooter/DSContextFooter.jsx85
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSContextFooter/_DSContextFooter.scss109
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSDismiss/DSDismiss.jsx57
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSDismiss/_DSDismiss.scss68
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSEmptyState/DSEmptyState.jsx97
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSEmptyState/_DSEmptyState.scss87
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSImage/DSImage.jsx157
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSImage/_DSImage.scss23
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSLinkMenu/DSLinkMenu.jsx90
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSLinkMenu/_DSLinkMenu.scss33
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSMessage/DSMessage.jsx34
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSMessage/_DSMessage.scss45
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSPrivacyModal/DSPrivacyModal.jsx69
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSPrivacyModal/_DSPrivacyModal.scss48
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSSignup/DSSignup.jsx167
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSSignup/DSSignup.scss52
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSTextPromo/DSTextPromo.jsx143
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSTextPromo/_DSTextPromo.scss119
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/Hero/Hero.jsx207
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/Hero/_Hero.scss282
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/Highlights/Highlights.jsx26
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/Highlights/_Highlights.scss40
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/HorizontalRule/HorizontalRule.jsx11
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/HorizontalRule/_HorizontalRule.scss7
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/List/List.jsx221
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/List/_List.scss269
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/Navigation/Navigation.jsx73
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/Navigation/_Navigation.scss64
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/SafeAnchor/SafeAnchor.jsx62
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/SectionTitle/SectionTitle.jsx19
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/SectionTitle/_SectionTitle.scss26
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/TopSites/TopSites.jsx157
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamComponents/TopSites/_TopSites.scss119
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamImpressionStats/ImpressionStats.jsx223
-rw-r--r--browser/components/newtab/content-src/components/DiscoveryStreamImpressionStats/_ImpressionStats.scss7
-rw-r--r--browser/components/newtab/content-src/components/ErrorBoundary/ErrorBoundary.jsx68
-rw-r--r--browser/components/newtab/content-src/components/ErrorBoundary/_ErrorBoundary.scss21
-rw-r--r--browser/components/newtab/content-src/components/FluentOrText/FluentOrText.jsx36
-rw-r--r--browser/components/newtab/content-src/components/LinkMenu/LinkMenu.jsx108
-rw-r--r--browser/components/newtab/content-src/components/MoreRecommendations/MoreRecommendations.jsx21
-rw-r--r--browser/components/newtab/content-src/components/MoreRecommendations/_MoreRecommendations.scss22
-rw-r--r--browser/components/newtab/content-src/components/PocketLoggedInCta/PocketLoggedInCta.jsx42
-rw-r--r--browser/components/newtab/content-src/components/PocketLoggedInCta/_PocketLoggedInCta.scss39
-rw-r--r--browser/components/newtab/content-src/components/Search/Search.jsx208
-rw-r--r--browser/components/newtab/content-src/components/Search/_Search.scss516
-rw-r--r--browser/components/newtab/content-src/components/SectionMenu/SectionMenu.jsx122
-rw-r--r--browser/components/newtab/content-src/components/Sections/Sections.jsx390
-rw-r--r--browser/components/newtab/content-src/components/Sections/_Sections.scss135
-rw-r--r--browser/components/newtab/content-src/components/TopSites/SearchShortcutsForm.jsx189
-rw-r--r--browser/components/newtab/content-src/components/TopSites/TopSite.jsx823
-rw-r--r--browser/components/newtab/content-src/components/TopSites/TopSiteForm.jsx330
-rw-r--r--browser/components/newtab/content-src/components/TopSites/TopSiteFormInput.jsx111
-rw-r--r--browser/components/newtab/content-src/components/TopSites/TopSites.jsx241
-rw-r--r--browser/components/newtab/content-src/components/TopSites/TopSitesConstants.js43
-rw-r--r--browser/components/newtab/content-src/components/TopSites/_TopSites.scss803
-rw-r--r--browser/components/newtab/content-src/components/Topics/Topics.jsx33
-rw-r--r--browser/components/newtab/content-src/components/Topics/_Topics.scss23
-rw-r--r--browser/components/newtab/content-src/lib/aboutwelcome-utils.js235
-rw-r--r--browser/components/newtab/content-src/lib/constants.js32
-rw-r--r--browser/components/newtab/content-src/lib/detect-user-session-start.js78
-rw-r--r--browser/components/newtab/content-src/lib/init-store.js175
-rw-r--r--browser/components/newtab/content-src/lib/link-menu-options.js276
-rw-r--r--browser/components/newtab/content-src/lib/perf-service.js104
-rw-r--r--browser/components/newtab/content-src/lib/screenshot-utils.js61
-rw-r--r--browser/components/newtab/content-src/lib/section-menu-options.js93
-rw-r--r--browser/components/newtab/content-src/lib/selectLayoutRender.js260
-rw-r--r--browser/components/newtab/content-src/styles/_OnboardingImages.scss71
-rw-r--r--browser/components/newtab/content-src/styles/_activity-stream.scss179
-rw-r--r--browser/components/newtab/content-src/styles/_icons.scss208
-rw-r--r--browser/components/newtab/content-src/styles/_mixins.scss50
-rw-r--r--browser/components/newtab/content-src/styles/_normalize.scss29
-rw-r--r--browser/components/newtab/content-src/styles/_theme.scss231
-rw-r--r--browser/components/newtab/content-src/styles/_variables.scss323
-rw-r--r--browser/components/newtab/content-src/styles/activity-stream-linux.scss13
-rw-r--r--browser/components/newtab/content-src/styles/activity-stream-mac.scss17
-rw-r--r--browser/components/newtab/content-src/styles/activity-stream-windows.scss13
-rw-r--r--browser/components/newtab/contributing.md154
-rw-r--r--browser/components/newtab/css/activity-stream-linux.css4545
-rw-r--r--browser/components/newtab/css/activity-stream-mac.css4548
-rw-r--r--browser/components/newtab/css/activity-stream-windows.css4545
-rw-r--r--browser/components/newtab/data/content/abouthomecache/page.html.template43
-rw-r--r--browser/components/newtab/data/content/abouthomecache/script.js.template19
-rw-r--r--browser/components/newtab/data/content/activity-stream.bundle.js15952
-rw-r--r--browser/components/newtab/data/content/assets/cfr_enhancer_youtube.pngbin0 -> 1387 bytes
-rw-r--r--browser/components/newtab/data/content/assets/cfr_fb_container.pngbin0 -> 3345 bytes
-rw-r--r--browser/components/newtab/data/content/assets/cfr_google_translate.pngbin0 -> 1722 bytes
-rw-r--r--browser/components/newtab/data/content/assets/cfr_pinnedtab_animated.pngbin0 -> 95908 bytes
-rw-r--r--browser/components/newtab/data/content/assets/cfr_pinnedtab_animated@2x.pngbin0 -> 191893 bytes
-rw-r--r--browser/components/newtab/data/content/assets/cfr_pinnedtab_animated_darktheme.pngbin0 -> 99064 bytes
-rw-r--r--browser/components/newtab/data/content/assets/cfr_pinnedtab_animated_darktheme@2x.pngbin0 -> 198663 bytes
-rw-r--r--browser/components/newtab/data/content/assets/cfr_pinnedtab_static.pngbin0 -> 1936 bytes
-rw-r--r--browser/components/newtab/data/content/assets/cfr_pinnedtab_static@2x.pngbin0 -> 3799 bytes
-rw-r--r--browser/components/newtab/data/content/assets/cfr_reddit_enhancement.pngbin0 -> 6508 bytes
-rw-r--r--browser/components/newtab/data/content/assets/cfr_wiki_search.pngbin0 -> 1258 bytes
-rw-r--r--browser/components/newtab/data/content/assets/firefox-protections.svg4
-rw-r--r--browser/components/newtab/data/content/assets/glyph-add-16.svg4
-rw-r--r--browser/components/newtab/data/content/assets/glyph-arrow.svg4
-rw-r--r--browser/components/newtab/data/content/assets/glyph-arrowhead-down-12.svg4
-rw-r--r--browser/components/newtab/data/content/assets/glyph-arrowhead-down-16.svg4
-rw-r--r--browser/components/newtab/data/content/assets/glyph-cancel-16.svg4
-rw-r--r--browser/components/newtab/data/content/assets/glyph-caret-right.svg4
-rw-r--r--browser/components/newtab/data/content/assets/glyph-cfr-feature-16.svg4
-rw-r--r--browser/components/newtab/data/content/assets/glyph-delete-16.svg4
-rw-r--r--browser/components/newtab/data/content/assets/glyph-dismiss-16.svg4
-rw-r--r--browser/components/newtab/data/content/assets/glyph-edit-16.svg4
-rw-r--r--browser/components/newtab/data/content/assets/glyph-help-24.svg4
-rw-r--r--browser/components/newtab/data/content/assets/glyph-highlights-16.svg4
-rw-r--r--browser/components/newtab/data/content/assets/glyph-info-16.svg4
-rw-r--r--browser/components/newtab/data/content/assets/glyph-mail-16.svg4
-rw-r--r--browser/components/newtab/data/content/assets/glyph-maximize-16.svg4
-rw-r--r--browser/components/newtab/data/content/assets/glyph-minimize-16.svg4
-rw-r--r--browser/components/newtab/data/content/assets/glyph-modal-delete-32.svg4
-rw-r--r--browser/components/newtab/data/content/assets/glyph-newWindow-16.svg4
-rw-r--r--browser/components/newtab/data/content/assets/glyph-open-file-16.svg4
-rw-r--r--browser/components/newtab/data/content/assets/glyph-pause-12.svg4
-rw-r--r--browser/components/newtab/data/content/assets/glyph-pin-12.svg4
-rw-r--r--browser/components/newtab/data/content/assets/glyph-pin-16.svg4
-rw-r--r--browser/components/newtab/data/content/assets/glyph-play-12.svg4
-rw-r--r--browser/components/newtab/data/content/assets/glyph-playhead.svg6
-rw-r--r--browser/components/newtab/data/content/assets/glyph-pocket-16.svg4
-rw-r--r--browser/components/newtab/data/content/assets/glyph-pocket-archive-16.svg4
-rw-r--r--browser/components/newtab/data/content/assets/glyph-pocket-delete-16.svg4
-rw-r--r--browser/components/newtab/data/content/assets/glyph-pocket-save-16.svg4
-rw-r--r--browser/components/newtab/data/content/assets/glyph-search-16.svg4
-rw-r--r--browser/components/newtab/data/content/assets/glyph-star-17.svg4
-rw-r--r--browser/components/newtab/data/content/assets/glyph-topsites-16.svg4
-rw-r--r--browser/components/newtab/data/content/assets/glyph-trending-16.svg4
-rw-r--r--browser/components/newtab/data/content/assets/glyph-unpin-16.svg4
-rw-r--r--browser/components/newtab/data/content/assets/glyph-webextension-16.svg4
-rw-r--r--browser/components/newtab/data/content/assets/icon-removed-bookmark.svg4
-rw-r--r--browser/components/newtab/data/content/assets/illustration-addons@2x.pngbin0 -> 20104 bytes
-rw-r--r--browser/components/newtab/data/content/assets/illustration-gift@2x.pngbin0 -> 14115 bytes
-rw-r--r--browser/components/newtab/data/content/assets/illustration-privatebrowsing@2x.pngbin0 -> 16627 bytes
-rw-r--r--browser/components/newtab/data/content/assets/illustration-screenshots@2x.pngbin0 -> 10990 bytes
-rw-r--r--browser/components/newtab/data/content/assets/illustration-sync@2x.pngbin0 -> 12047 bytes
-rw-r--r--browser/components/newtab/data/content/assets/long-zap.svg4
-rw-r--r--browser/components/newtab/data/content/assets/protection-report-icon.pngbin0 -> 4309 bytes
-rw-r--r--browser/components/newtab/data/content/assets/remote/pin-to-taskbar-v1.svg4
-rw-r--r--browser/components/newtab/data/content/assets/remote/pin-to-taskbar-v2.svg116
-rw-r--r--browser/components/newtab/data/content/assets/remote/pip-message-icon.svg4
-rw-r--r--browser/components/newtab/data/content/assets/short-zap.svg4
-rw-r--r--browser/components/newtab/data/content/assets/spinner.svg4
-rw-r--r--browser/components/newtab/data/content/assets/topic-show-more-12.svg4
-rw-r--r--browser/components/newtab/data/content/assets/trailhead/card-illo-devices.svg5
-rw-r--r--browser/components/newtab/data/content/assets/trailhead/card-illo-fbcont.svg5
-rw-r--r--browser/components/newtab/data/content/assets/trailhead/card-illo-ffmonitor.svg5
-rw-r--r--browser/components/newtab/data/content/assets/trailhead/card-illo-ffsend.svg5
-rw-r--r--browser/components/newtab/data/content/assets/trailhead/card-illo-import.svg4
-rw-r--r--browser/components/newtab/data/content/assets/trailhead/card-illo-lockwise.svg5
-rw-r--r--browser/components/newtab/data/content/assets/trailhead/card-illo-mobile.svg5
-rw-r--r--browser/components/newtab/data/content/assets/trailhead/card-illo-pledge.svg5
-rw-r--r--browser/components/newtab/data/content/assets/trailhead/card-illo-pocket.svg5
-rw-r--r--browser/components/newtab/data/content/assets/trailhead/card-illo-private.svg5
-rw-r--r--browser/components/newtab/data/content/assets/trailhead/card-illo-sendtab.svg5
-rw-r--r--browser/components/newtab/data/content/assets/trailhead/card-illo-tracking.svg5
-rw-r--r--browser/components/newtab/data/content/assets/whatsnew-send-icon.pngbin0 -> 2038 bytes
-rw-r--r--browser/components/newtab/data/content/newtab-render.js11
-rw-r--r--browser/components/newtab/data/content/tippytop/favicons/adidas.pngbin0 -> 3226 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/favicons/aliexpress-com.icobin0 -> 4286 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/favicons/allegro-pl.icobin0 -> 1150 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/favicons/amazon.icobin0 -> 1407 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/favicons/avito-ru.icobin0 -> 5430 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/favicons/baidu-com.pngbin0 -> 1983 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/favicons/bbc-uk.icobin0 -> 958 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/favicons/bing-com.icobin0 -> 3638 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/favicons/ctrip-com.icobin0 -> 1150 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/favicons/duckduckgo-com.icobin0 -> 5430 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/favicons/ebay.icobin0 -> 1455 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/favicons/etsy.icobin0 -> 4286 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/favicons/facebook-com.icobin0 -> 5430 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/favicons/geico.pngbin0 -> 1472 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/favicons/google-com.icobin0 -> 5430 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/favicons/hrblock.icobin0 -> 3950 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/favicons/ifeng-com.icobin0 -> 4038 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/favicons/iqiyi-com.icobin0 -> 5430 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/favicons/leboncoin-fr.pngbin0 -> 454 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/favicons/nike.icobin0 -> 1150 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/favicons/ok-ru.icobin0 -> 5430 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/favicons/olx-pl.icobin0 -> 5430 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/favicons/reddit-com.pngbin0 -> 2094 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/favicons/samsung.icobin0 -> 4286 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/favicons/turbotax.pngbin0 -> 3744 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/favicons/twitter-com.icobin0 -> 1650 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/favicons/vk-com.icobin0 -> 302 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/favicons/vodafone.pngbin0 -> 1757 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/favicons/weibo-com.icobin0 -> 10134 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/favicons/wikipedia-org.icobin0 -> 2734 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/favicons/wix.icobin0 -> 1061 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/favicons/wykop-pl.pngbin0 -> 1705 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/favicons/yandex-com.pngbin0 -> 826 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/favicons/yandex-ru.pngbin0 -> 850 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/favicons/youtube-com.pngbin0 -> 348 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/favicons/zhihu-com.icobin0 -> 6518 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/images/adidas@2x.pngbin0 -> 5448 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/images/aliexpress-com@2x.pngbin0 -> 12459 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/images/allegro-pl@2x.pngbin0 -> 5041 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/images/amazon@2x.pngbin0 -> 6061 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/images/avito-ru@2x.pngbin0 -> 1568 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/images/baidu-com@2x.pngbin0 -> 8198 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/images/bbc-uk@2x.pngbin0 -> 18207 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/images/bing-com@2x.pngbin0 -> 2875 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/images/ctrip-com@2x.pngbin0 -> 15862 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/images/duckduckgo-com@2x.pngbin0 -> 4391 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/images/ebay@2x.pngbin0 -> 4665 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/images/etsy@2x.jpgbin0 -> 4094 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/images/facebook-com@2x.pngbin0 -> 10780 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/images/geico@2x.jpgbin0 -> 11834 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/images/google-com@2x.pngbin0 -> 3035 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/images/hrblock@2x.pngbin0 -> 4642 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/images/ifeng-com@2x.pngbin0 -> 22282 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/images/iqiyi-com@2x.pngbin0 -> 14340 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/images/leboncoin-fr@2x.pngbin0 -> 7146 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/images/nike@2x.jpgbin0 -> 5163 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/images/ok-ru@2x.pngbin0 -> 2526 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/images/olx-pl@2x.pngbin0 -> 5287 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/images/reddit-com@2x.pngbin0 -> 5180 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/images/samsung@2x.jpgbin0 -> 3347 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/images/turbotax@2x.jpgbin0 -> 11930 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/images/twitter-com@2x.pngbin0 -> 1260 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/images/vk-com@2x.pngbin0 -> 9897 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/images/vodafone@2x.jpgbin0 -> 7050 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/images/weibo-com@2x.pngbin0 -> 15507 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/images/wikipedia-org@2x.pngbin0 -> 19001 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/images/wix@2x.jpgbin0 -> 8714 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/images/wykop-pl@2x.pngbin0 -> 4415 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/images/yandex-com@2x.pngbin0 -> 1708 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/images/yandex-ru@2x.pngbin0 -> 1647 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/images/youtube-com@2x.pngbin0 -> 2924 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/images/zhihu-com@2x.pngbin0 -> 10225 bytes
-rw-r--r--browser/components/newtab/data/content/tippytop/top_sites.json182
-rw-r--r--browser/components/newtab/docs/index.rst99
-rw-r--r--browser/components/newtab/docs/v2-system-addon/about_home_startup_cache.md86
-rw-r--r--browser/components/newtab/docs/v2-system-addon/data_dictionary.md341
-rw-r--r--browser/components/newtab/docs/v2-system-addon/data_events.md1144
-rw-r--r--browser/components/newtab/docs/v2-system-addon/geo_locale.md23
-rw-r--r--browser/components/newtab/docs/v2-system-addon/mochitests.md28
-rw-r--r--browser/components/newtab/docs/v2-system-addon/preferences.md282
-rw-r--r--browser/components/newtab/docs/v2-system-addon/remote_cfr.md63
-rw-r--r--browser/components/newtab/docs/v2-system-addon/sections.md82
-rw-r--r--browser/components/newtab/docs/v2-system-addon/telemetry.md13
-rw-r--r--browser/components/newtab/docs/v2-system-addon/tippytop.md40
-rw-r--r--browser/components/newtab/docs/v2-system-addon/unit_testing_guide.md149
-rw-r--r--browser/components/newtab/jar.mn44
-rw-r--r--browser/components/newtab/karma.mc.config.js299
-rw-r--r--browser/components/newtab/lib/ASRouter.jsm1753
-rw-r--r--browser/components/newtab/lib/ASRouterDefaultConfig.jsm65
-rw-r--r--browser/components/newtab/lib/ASRouterNewTabHook.jsm122
-rw-r--r--browser/components/newtab/lib/ASRouterParentProcessMessageHandler.jsm161
-rw-r--r--browser/components/newtab/lib/ASRouterPreferences.jsm228
-rw-r--r--browser/components/newtab/lib/ASRouterTargeting.jsm837
-rw-r--r--browser/components/newtab/lib/ASRouterTriggerListeners.jsm594
-rw-r--r--browser/components/newtab/lib/AboutPreferences.jsm334
-rw-r--r--browser/components/newtab/lib/ActivityStream.jsm842
-rw-r--r--browser/components/newtab/lib/ActivityStreamMessageChannel.jsm344
-rw-r--r--browser/components/newtab/lib/ActivityStreamPrefs.jsm95
-rw-r--r--browser/components/newtab/lib/ActivityStreamStorage.jsm121
-rw-r--r--browser/components/newtab/lib/BookmarkPanelHub.jsm332
-rw-r--r--browser/components/newtab/lib/CFRMessageProvider.jsm1076
-rw-r--r--browser/components/newtab/lib/CFRPageActions.jsm1194
-rw-r--r--browser/components/newtab/lib/DefaultSites.jsm50
-rw-r--r--browser/components/newtab/lib/DiscoveryStreamFeed.jsm1945
-rw-r--r--browser/components/newtab/lib/DownloadsManager.jsm194
-rw-r--r--browser/components/newtab/lib/FaviconFeed.jsm213
-rw-r--r--browser/components/newtab/lib/FilterAdult.jsm2980
-rw-r--r--browser/components/newtab/lib/HighlightsFeed.jsm361
-rw-r--r--browser/components/newtab/lib/InfoBar.jsm158
-rw-r--r--browser/components/newtab/lib/LinksCache.jsm136
-rw-r--r--browser/components/newtab/lib/MomentsPageHub.jsm179
-rw-r--r--browser/components/newtab/lib/NewTabInit.jsm57
-rw-r--r--browser/components/newtab/lib/OnboardingMessageProvider.jsm92
-rw-r--r--browser/components/newtab/lib/PanelTestProvider.jsm355
-rw-r--r--browser/components/newtab/lib/PersistentCache.jsm108
-rw-r--r--browser/components/newtab/lib/PersonalityProvider/NaiveBayesTextTagger.jsm67
-rw-r--r--browser/components/newtab/lib/PersonalityProvider/NmfTextTagger.jsm65
-rw-r--r--browser/components/newtab/lib/PersonalityProvider/PersonalityProvider.jsm315
-rw-r--r--browser/components/newtab/lib/PersonalityProvider/PersonalityProviderWorker.js37
-rw-r--r--browser/components/newtab/lib/PersonalityProvider/PersonalityProviderWorkerClass.jsm279
-rw-r--r--browser/components/newtab/lib/PersonalityProvider/RecipeExecutor.jsm1126
-rw-r--r--browser/components/newtab/lib/PersonalityProvider/Tokenize.jsm89
-rw-r--r--browser/components/newtab/lib/PlacesFeed.jsm568
-rw-r--r--browser/components/newtab/lib/PrefsFeed.jsm291
-rw-r--r--browser/components/newtab/lib/RecommendationProviderSwitcher.jsm195
-rw-r--r--browser/components/newtab/lib/RemoteL10n.jsm248
-rw-r--r--browser/components/newtab/lib/Screenshots.jsm151
-rw-r--r--browser/components/newtab/lib/SearchShortcuts.jsm82
-rw-r--r--browser/components/newtab/lib/SectionsManager.jsm727
-rw-r--r--browser/components/newtab/lib/ShortURL.jsm84
-rw-r--r--browser/components/newtab/lib/SiteClassifier.jsm99
-rw-r--r--browser/components/newtab/lib/SnippetsTestMessageProvider.jsm721
-rw-r--r--browser/components/newtab/lib/Store.jsm190
-rw-r--r--browser/components/newtab/lib/SystemTickFeed.jsm45
-rw-r--r--browser/components/newtab/lib/TelemetryFeed.jsm1112
-rw-r--r--browser/components/newtab/lib/TippyTopProvider.jsm72
-rw-r--r--browser/components/newtab/lib/ToolbarBadgeHub.jsm316
-rw-r--r--browser/components/newtab/lib/ToolbarPanelHub.jsm631
-rw-r--r--browser/components/newtab/lib/TopSitesFeed.jsm1174
-rw-r--r--browser/components/newtab/lib/TopStoriesFeed.jsm929
-rw-r--r--browser/components/newtab/lib/UTEventReporting.jsm68
-rw-r--r--browser/components/newtab/lib/UserDomainAffinityProvider.jsm390
-rw-r--r--browser/components/newtab/lib/cache-worker.js193
-rw-r--r--browser/components/newtab/loaders/inject-loader.js57
-rw-r--r--browser/components/newtab/moz.build43
-rw-r--r--browser/components/newtab/nsIAboutNewTabService.idl39
-rw-r--r--browser/components/newtab/package-lock.json11820
-rw-r--r--browser/components/newtab/package.json126
-rw-r--r--browser/components/newtab/prerendered/activity-stream-debug.html33
-rw-r--r--browser/components/newtab/prerendered/activity-stream-noscripts.html22
-rw-r--r--browser/components/newtab/prerendered/activity-stream.html33
-rw-r--r--browser/components/newtab/test/.eslintrc.js19
-rw-r--r--browser/components/newtab/test/browser/abouthomecache/browser.ini35
-rw-r--r--browser/components/newtab/test/browser/abouthomecache/browser_basic_endtoend.js22
-rw-r--r--browser/components/newtab/test/browser/abouthomecache/browser_bump_version.js29
-rw-r--r--browser/components/newtab/test/browser/abouthomecache/browser_disabled.js97
-rw-r--r--browser/components/newtab/test/browser/abouthomecache/browser_locale_change.js23
-rw-r--r--browser/components/newtab/test/browser/abouthomecache/browser_no_cache.js21
-rw-r--r--browser/components/newtab/test/browser/abouthomecache/browser_no_startup_actions.js79
-rw-r--r--browser/components/newtab/test/browser/abouthomecache/browser_overwrite_cache.js38
-rw-r--r--browser/components/newtab/test/browser/abouthomecache/browser_process_crash.js81
-rw-r--r--browser/components/newtab/test/browser/abouthomecache/browser_same_consumer.js52
-rw-r--r--browser/components/newtab/test/browser/abouthomecache/browser_sanitize.js47
-rw-r--r--browser/components/newtab/test/browser/abouthomecache/browser_shutdown_timeout.js45
-rw-r--r--browser/components/newtab/test/browser/abouthomecache/head.js325
-rw-r--r--browser/components/newtab/test/browser/blue_page.html6
-rw-r--r--browser/components/newtab/test/browser/browser.ini58
-rw-r--r--browser/components/newtab/test/browser/browser_aboutwelcome_actors.js237
-rw-r--r--browser/components/newtab/test/browser/browser_aboutwelcome_attribution.js113
-rw-r--r--browser/components/newtab/test/browser/browser_aboutwelcome_multistage.js779
-rw-r--r--browser/components/newtab/test/browser/browser_aboutwelcome_observer.js76
-rw-r--r--browser/components/newtab/test/browser/browser_aboutwelcome_rtamo.js193
-rw-r--r--browser/components/newtab/test/browser/browser_aboutwelcome_simplified.js77
-rw-r--r--browser/components/newtab/test/browser/browser_as_load_location.js44
-rw-r--r--browser/components/newtab/test/browser/browser_as_render.js83
-rw-r--r--browser/components/newtab/test/browser/browser_asrouter_bookmarkpanel.js94
-rw-r--r--browser/components/newtab/test/browser/browser_asrouter_cfr.js1134
-rw-r--r--browser/components/newtab/test/browser/browser_asrouter_experimentsAPILoader.js268
-rw-r--r--browser/components/newtab/test/browser/browser_asrouter_group_frequency.js188
-rw-r--r--browser/components/newtab/test/browser/browser_asrouter_group_userprefs.js156
-rw-r--r--browser/components/newtab/test/browser/browser_asrouter_infobar.js85
-rw-r--r--browser/components/newtab/test/browser/browser_asrouter_momentspagehub.js113
-rw-r--r--browser/components/newtab/test/browser/browser_asrouter_snippets.js193
-rw-r--r--browser/components/newtab/test/browser/browser_asrouter_targeting.js1137
-rw-r--r--browser/components/newtab/test/browser/browser_asrouter_toolbarbadge.js143
-rw-r--r--browser/components/newtab/test/browser/browser_asrouter_whatsnewpanel.js99
-rw-r--r--browser/components/newtab/test/browser/browser_context_menu_item.js29
-rw-r--r--browser/components/newtab/test/browser/browser_customize_menu_content.js243
-rw-r--r--browser/components/newtab/test/browser/browser_customize_menu_render.js183
-rw-r--r--browser/components/newtab/test/browser/browser_discovery_card.js44
-rw-r--r--browser/components/newtab/test/browser/browser_discovery_render.js32
-rw-r--r--browser/components/newtab/test/browser/browser_discovery_styles.js171
-rw-r--r--browser/components/newtab/test/browser/browser_enabled_newtabpage.js25
-rw-r--r--browser/components/newtab/test/browser/browser_getScreenshots.js90
-rw-r--r--browser/components/newtab/test/browser/browser_highlights_section.js101
-rw-r--r--browser/components/newtab/test/browser/browser_newtab_experiment_api.js90
-rw-r--r--browser/components/newtab/test/browser/browser_newtab_header.js296
-rw-r--r--browser/components/newtab/test/browser/browser_newtab_overrides.js138
-rw-r--r--browser/components/newtab/test/browser/browser_open_tab_focus.js37
-rw-r--r--browser/components/newtab/test/browser/browser_topsites_contextMenu_options.js129
-rw-r--r--browser/components/newtab/test/browser/browser_topsites_section.js213
-rw-r--r--browser/components/newtab/test/browser/browser_trigger_listeners.js65
-rw-r--r--browser/components/newtab/test/browser/ds_layout.json89
-rw-r--r--browser/components/newtab/test/browser/head.js256
-rw-r--r--browser/components/newtab/test/browser/red_page.html6
-rw-r--r--browser/components/newtab/test/browser/snippet.json25
-rw-r--r--browser/components/newtab/test/browser/snippet_below_search_test.json20
-rw-r--r--browser/components/newtab/test/browser/snippet_simple_test.json24
-rw-r--r--browser/components/newtab/test/browser/topstories.json1
-rw-r--r--browser/components/newtab/test/schemas/pings.js317
-rw-r--r--browser/components/newtab/test/unit/aboutwelcome/MultiStageAboutWelcome.test.jsx186
-rw-r--r--browser/components/newtab/test/unit/asrouter/ASRouter.test.js2898
-rw-r--r--browser/components/newtab/test/unit/asrouter/ASRouterChild.test.js74
-rw-r--r--browser/components/newtab/test/unit/asrouter/ASRouterNewTabHook.test.js151
-rw-r--r--browser/components/newtab/test/unit/asrouter/ASRouterParent.test.js103
-rw-r--r--browser/components/newtab/test/unit/asrouter/ASRouterParentProcessMessageHandler.test.js418
-rw-r--r--browser/components/newtab/test/unit/asrouter/ASRouterPreferences.test.js377
-rw-r--r--browser/components/newtab/test/unit/asrouter/ASRouterTargeting.test.js546
-rw-r--r--browser/components/newtab/test/unit/asrouter/ASRouterTriggerListeners.test.js506
-rw-r--r--browser/components/newtab/test/unit/asrouter/CFRMessageProvider.test.js46
-rw-r--r--browser/components/newtab/test/unit/asrouter/CFRPageActions.test.js1241
-rw-r--r--browser/components/newtab/test/unit/asrouter/MessageLoaderUtils.test.js459
-rw-r--r--browser/components/newtab/test/unit/asrouter/ModalOverlay.test.jsx69
-rw-r--r--browser/components/newtab/test/unit/asrouter/PanelTestProvider.test.js42
-rw-r--r--browser/components/newtab/test/unit/asrouter/RemoteL10n.test.js165
-rw-r--r--browser/components/newtab/test/unit/asrouter/RichText.test.jsx81
-rw-r--r--browser/components/newtab/test/unit/asrouter/SnippetsTestMessageProvider.test.js43
-rw-r--r--browser/components/newtab/test/unit/asrouter/TargetingDocs.test.js92
-rw-r--r--browser/components/newtab/test/unit/asrouter/asrouter-content.test.jsx516
-rw-r--r--browser/components/newtab/test/unit/asrouter/asrouter-utils.test.js100
-rw-r--r--browser/components/newtab/test/unit/asrouter/compatibility-reference/fx57-compat.test.js26
-rw-r--r--browser/components/newtab/test/unit/asrouter/compatibility-reference/snippets-fx57.js126
-rw-r--r--browser/components/newtab/test/unit/asrouter/constants.js166
-rw-r--r--browser/components/newtab/test/unit/asrouter/schemas/panel/cfr-fxa-bookmark.schema.test.js28
-rw-r--r--browser/components/newtab/test/unit/asrouter/template-utils.test.js31
-rw-r--r--browser/components/newtab/test/unit/asrouter/templates/EOYSnippet.test.jsx194
-rw-r--r--browser/components/newtab/test/unit/asrouter/templates/ExtensionDoorhanger.test.jsx98
-rw-r--r--browser/components/newtab/test/unit/asrouter/templates/FXASignupSnippet.test.jsx84
-rw-r--r--browser/components/newtab/test/unit/asrouter/templates/NewsletterSnippet.test.jsx86
-rw-r--r--browser/components/newtab/test/unit/asrouter/templates/OnboardingMessage.test.jsx80
-rw-r--r--browser/components/newtab/test/unit/asrouter/templates/SendToDeviceSnippet.test.jsx252
-rw-r--r--browser/components/newtab/test/unit/asrouter/templates/SimpleBelowSearchSnippet.test.jsx62
-rw-r--r--browser/components/newtab/test/unit/asrouter/templates/SimpleSnippet.test.jsx255
-rw-r--r--browser/components/newtab/test/unit/asrouter/templates/SubmitFormSnippet.test.jsx341
-rw-r--r--browser/components/newtab/test/unit/asrouter/templates/isEmailOrPhoneNumber.test.js56
-rw-r--r--browser/components/newtab/test/unit/common/Actions.test.js241
-rw-r--r--browser/components/newtab/test/unit/common/Dedupe.test.js38
-rw-r--r--browser/components/newtab/test/unit/common/Reducers.test.js1560
-rw-r--r--browser/components/newtab/test/unit/content-src/components/ASRouterAdmin.test.jsx610
-rw-r--r--browser/components/newtab/test/unit/content-src/components/Base.test.jsx147
-rw-r--r--browser/components/newtab/test/unit/content-src/components/Card.test.jsx507
-rw-r--r--browser/components/newtab/test/unit/content-src/components/CollapsibleSection.test.jsx224
-rw-r--r--browser/components/newtab/test/unit/content-src/components/ComponentPerfTimer.test.jsx444
-rw-r--r--browser/components/newtab/test/unit/content-src/components/ConfirmDialog.test.jsx179
-rw-r--r--browser/components/newtab/test/unit/content-src/components/ContextMenu.test.jsx230
-rw-r--r--browser/components/newtab/test/unit/content-src/components/CustomiseMenu.test.jsx76
-rw-r--r--browser/components/newtab/test/unit/content-src/components/DiscoveryStreamBase.test.jsx377
-rw-r--r--browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/CardGrid.test.jsx40
-rw-r--r--browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/CollectionCardGrid.test.jsx149
-rw-r--r--browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSCard.test.jsx373
-rw-r--r--browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSContextFooter.test.jsx145
-rw-r--r--browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSDismiss.test.jsx51
-rw-r--r--browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSEmptyState.test.jsx73
-rw-r--r--browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSImage.test.jsx127
-rw-r--r--browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSLinkMenu.test.jsx171
-rw-r--r--browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSMessage.test.jsx75
-rw-r--r--browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSPrivacyModal.test.jsx50
-rw-r--r--browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSSignup.test.jsx92
-rw-r--r--browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSTextPromo.test.jsx93
-rw-r--r--browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/Hero.test.jsx179
-rw-r--r--browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/Highlights.test.jsx41
-rw-r--r--browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/HorizontalRule.test.jsx16
-rw-r--r--browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/ImpressionStats.test.jsx252
-rw-r--r--browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/List.test.jsx278
-rw-r--r--browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/Navigation.test.jsx119
-rw-r--r--browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/SafeAnchor.test.jsx56
-rw-r--r--browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/SectionTitle.test.jsx22
-rw-r--r--browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/TopSites.test.jsx247
-rw-r--r--browser/components/newtab/test/unit/content-src/components/ErrorBoundary.test.jsx110
-rw-r--r--browser/components/newtab/test/unit/content-src/components/FluentOrText.test.jsx66
-rw-r--r--browser/components/newtab/test/unit/content-src/components/LinkMenu.test.jsx523
-rw-r--r--browser/components/newtab/test/unit/content-src/components/MSLocalized.test.jsx46
-rw-r--r--browser/components/newtab/test/unit/content-src/components/MoreRecommendations.test.jsx24
-rw-r--r--browser/components/newtab/test/unit/content-src/components/PocketLoggedInCta.test.jsx46
-rw-r--r--browser/components/newtab/test/unit/content-src/components/Search.test.jsx176
-rw-r--r--browser/components/newtab/test/unit/content-src/components/SectionMenu.test.jsx273
-rw-r--r--browser/components/newtab/test/unit/content-src/components/Sections.test.jsx633
-rw-r--r--browser/components/newtab/test/unit/content-src/components/TopSites.test.jsx1833
-rw-r--r--browser/components/newtab/test/unit/content-src/components/TopSites/SearchShortcutsForm.test.jsx60
-rw-r--r--browser/components/newtab/test/unit/content-src/components/Topics.test.jsx22
-rw-r--r--browser/components/newtab/test/unit/content-src/components/addUtmParams.test.js28
-rw-r--r--browser/components/newtab/test/unit/content-src/lib/detect-user-session-start.test.js117
-rw-r--r--browser/components/newtab/test/unit/content-src/lib/init-store.test.js204
-rw-r--r--browser/components/newtab/test/unit/content-src/lib/perf-service.test.js89
-rw-r--r--browser/components/newtab/test/unit/content-src/lib/screenshot-utils.test.js147
-rw-r--r--browser/components/newtab/test/unit/content-src/lib/selectLayoutRender.test.js605
-rw-r--r--browser/components/newtab/test/unit/lib/AboutPreferences.test.js423
-rw-r--r--browser/components/newtab/test/unit/lib/ActivityStream.test.js531
-rw-r--r--browser/components/newtab/test/unit/lib/ActivityStreamMessageChannel.test.js508
-rw-r--r--browser/components/newtab/test/unit/lib/ActivityStreamPrefs.test.js113
-rw-r--r--browser/components/newtab/test/unit/lib/ActivityStreamStorage.test.js161
-rw-r--r--browser/components/newtab/test/unit/lib/BookmarkPanelHub.test.js514
-rw-r--r--browser/components/newtab/test/unit/lib/DiscoveryStreamFeed.test.js2915
-rw-r--r--browser/components/newtab/test/unit/lib/DownloadsManager.test.js373
-rw-r--r--browser/components/newtab/test/unit/lib/FaviconFeed.test.js233
-rw-r--r--browser/components/newtab/test/unit/lib/FilterAdult.test.js54
-rw-r--r--browser/components/newtab/test/unit/lib/HighlightsFeed.test.js819
-rw-r--r--browser/components/newtab/test/unit/lib/LinksCache.test.js16
-rw-r--r--browser/components/newtab/test/unit/lib/MomentsPageHub.test.js336
-rw-r--r--browser/components/newtab/test/unit/lib/NewTabInit.test.js78
-rw-r--r--browser/components/newtab/test/unit/lib/PersistentCache.test.js131
-rw-r--r--browser/components/newtab/test/unit/lib/PersonalityProvider/NaiveBayesTextTagger.test.js109
-rw-r--r--browser/components/newtab/test/unit/lib/PersonalityProvider/NmfTextTagger.test.js1083
-rw-r--r--browser/components/newtab/test/unit/lib/PersonalityProvider/PersonalityProvider.test.js389
-rw-r--r--browser/components/newtab/test/unit/lib/PersonalityProvider/PersonalityProviderWorkerClass.test.js450
-rw-r--r--browser/components/newtab/test/unit/lib/PersonalityProvider/RecipeExecutor.test.js1547
-rw-r--r--browser/components/newtab/test/unit/lib/PersonalityProvider/Tokenize.test.js134
-rw-r--r--browser/components/newtab/test/unit/lib/PlacesFeed.test.js1139
-rw-r--r--browser/components/newtab/test/unit/lib/PrefsFeed.test.js248
-rw-r--r--browser/components/newtab/test/unit/lib/RecommendationProviderSwitcher.test.js243
-rw-r--r--browser/components/newtab/test/unit/lib/Screenshots.test.js209
-rw-r--r--browser/components/newtab/test/unit/lib/SectionsManager.test.js884
-rw-r--r--browser/components/newtab/test/unit/lib/ShortUrl.test.js104
-rw-r--r--browser/components/newtab/test/unit/lib/SiteClassifier.test.js252
-rw-r--r--browser/components/newtab/test/unit/lib/Store.test.js307
-rw-r--r--browser/components/newtab/test/unit/lib/SystemTickFeed.test.js46
-rw-r--r--browser/components/newtab/test/unit/lib/TelemetryFeed.test.js1816
-rw-r--r--browser/components/newtab/test/unit/lib/TippyTopProvider.test.js121
-rw-r--r--browser/components/newtab/test/unit/lib/ToolbarBadgeHub.test.js651
-rw-r--r--browser/components/newtab/test/unit/lib/ToolbarPanelHub.test.js927
-rw-r--r--browser/components/newtab/test/unit/lib/TopSitesFeed.test.js2015
-rw-r--r--browser/components/newtab/test/unit/lib/TopStoriesFeed.test.js2252
-rw-r--r--browser/components/newtab/test/unit/lib/UTEventReporting.test.js115
-rw-r--r--browser/components/newtab/test/unit/lib/UserDomainAffinityProvider.test.js256
-rw-r--r--browser/components/newtab/test/unit/unit-entry.js482
-rw-r--r--browser/components/newtab/test/unit/utils.js263
-rw-r--r--browser/components/newtab/test/xpcshell/ds_layout.json89
-rw-r--r--browser/components/newtab/test/xpcshell/head.js11
-rw-r--r--browser/components/newtab/test/xpcshell/test_ASRouterTargeting_attribution.js64
-rw-r--r--browser/components/newtab/test/xpcshell/test_AboutHomeStartupCacheChild.js33
-rw-r--r--browser/components/newtab/test/xpcshell/test_AboutHomeStartupCacheWorker.js239
-rw-r--r--browser/components/newtab/test/xpcshell/test_AboutNewTab.js359
-rw-r--r--browser/components/newtab/test/xpcshell/test_AboutWelcomeAttribution.js38
-rw-r--r--browser/components/newtab/test/xpcshell/test_AboutWelcomeTelemetry.js87
-rw-r--r--browser/components/newtab/test/xpcshell/topstories.json1
-rw-r--r--browser/components/newtab/test/xpcshell/xpcshell.ini19
-rw-r--r--browser/components/newtab/vendor/PROP_TYPES_LICENSE21
-rw-r--r--browser/components/newtab/vendor/REACT_AND_REACT_DOM_LICENSE21
-rw-r--r--browser/components/newtab/vendor/REACT_REDUX_LICENSE21
-rw-r--r--browser/components/newtab/vendor/REACT_TRANSITION_GROUP_LICENSE30
-rw-r--r--browser/components/newtab/vendor/REDUX_LICENSE21
-rw-r--r--browser/components/newtab/vendor/Redux.jsm690
-rw-r--r--browser/components/newtab/vendor/prop-types.js1
-rw-r--r--browser/components/newtab/vendor/react-dev.js3318
-rw-r--r--browser/components/newtab/vendor/react-dom-dev.js25147
-rw-r--r--browser/components/newtab/vendor/react-dom-server.js45
-rw-r--r--browser/components/newtab/vendor/react-dom.js239
-rw-r--r--browser/components/newtab/vendor/react-redux.js1
-rw-r--r--browser/components/newtab/vendor/react-transition-group.js1
-rw-r--r--browser/components/newtab/vendor/react.js32
-rw-r--r--browser/components/newtab/vendor/redux.js948
-rw-r--r--browser/components/newtab/webpack.aboutwelcome.config.js24
-rw-r--r--browser/components/newtab/webpack.system-addon.config.js72
-rw-r--r--browser/components/newtab/yamscripts.yml63
644 files changed, 187626 insertions, 0 deletions
diff --git a/browser/components/newtab/.eslintrc.js b/browser/components/newtab/.eslintrc.js
new file mode 100644
index 0000000000..fa180392c0
--- /dev/null
+++ b/browser/components/newtab/.eslintrc.js
@@ -0,0 +1,226 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+module.exports = {
+ // When adding items to this file please check for effects on sub-directories.
+ parserOptions: {
+ ecmaVersion: 2018,
+ ecmaFeatures: {
+ jsx: true,
+ },
+ sourceType: "module",
+ },
+ env: {
+ node: true,
+ },
+ plugins: [
+ "import", // require("eslint-plugin-import")
+ "react", // require("eslint-plugin-react")
+ "jsx-a11y", // require("eslint-plugin-jsx-a11y")
+ ],
+ settings: {
+ react: {
+ version: "16.2.0",
+ },
+ },
+ extends: [
+ "eslint:recommended",
+ "plugin:jsx-a11y/recommended", // require("eslint-plugin-jsx-a11y")
+ "plugin:mozilla/recommended", // require("eslint-plugin-mozilla") require("eslint-plugin-fetch-options") require("eslint-plugin-html") require("eslint-plugin-no-unsanitized")
+ "plugin:mozilla/browser-test",
+ "plugin:mozilla/mochitest-test",
+ "plugin:mozilla/xpcshell-test",
+ "plugin:prettier/recommended", // require("eslint-plugin-prettier")
+ "prettier/react", // require("eslint-config-prettier")
+ ],
+ overrides: [
+ {
+ // These files use fluent-dom to insert content
+ files: [
+ "content-src/aboutwelcome/components/HeroText.jsx",
+ "content-src/aboutwelcome/components/Zap.jsx",
+ "content-src/aboutwelcome/components/MultiStageAboutWelcome.jsx",
+ "content-src/aboutwelcome/components/ReturnToAMO.jsx",
+ "content-src/asrouter/templates/OnboardingMessage/**",
+ "content-src/asrouter/templates/FirstRun/**",
+ "content-src/components/TopSites/**",
+ "content-src/components/MoreRecommendations/MoreRecommendations.jsx",
+ "content-src/components/CollapsibleSection/CollapsibleSection.jsx",
+ "content-src/components/DiscoveryStreamComponents/DSEmptyState/DSEmptyState.jsx",
+ "content-src/components/DiscoveryStreamComponents/DSPrivacyModal/DSPrivacyModal.jsx",
+ "content-src/components/CustomizeMenu/**",
+ ],
+ rules: {
+ "jsx-a11y/anchor-has-content": 0,
+ "jsx-a11y/heading-has-content": 0,
+ "jsx-a11y/label-has-associated-control": 0,
+ "jsx-a11y/no-onchange": 0,
+ },
+ },
+ {
+ // Use a configuration that's more appropriate for JSMs
+ files: "**/*.jsm",
+ parserOptions: {
+ sourceType: "script",
+ },
+ env: {
+ node: false,
+ },
+ rules: {
+ "no-implicit-globals": 0,
+ },
+ },
+ ],
+ rules: {
+ "fetch-options/no-fetch-credentials": 2,
+
+ "react/jsx-boolean-value": [2, "always"],
+ "react/jsx-key": 2,
+ "react/jsx-no-bind": 2,
+ "react/jsx-no-comment-textnodes": 2,
+ "react/jsx-no-duplicate-props": 2,
+ "react/jsx-no-target-blank": 2,
+ "react/jsx-no-undef": 2,
+ "react/jsx-pascal-case": 2,
+ "react/jsx-uses-react": 2,
+ "react/jsx-uses-vars": 2,
+ "react/no-access-state-in-setstate": 2,
+ "react/no-danger": 2,
+ "react/no-deprecated": 2,
+ "react/no-did-mount-set-state": 2,
+ "react/no-did-update-set-state": 2,
+ "react/no-direct-mutation-state": 2,
+ "react/no-is-mounted": 2,
+ "react/no-unknown-property": 2,
+ "react/require-render-return": 2,
+
+ "accessor-pairs": [2, { setWithoutGet: true, getWithoutSet: false }],
+ "array-callback-return": 2,
+ "block-scoped-var": 2,
+ "callback-return": 0,
+ camelcase: 0,
+ "capitalized-comments": 0,
+ "class-methods-use-this": 0,
+ "consistent-this": [2, "use-bind"],
+ "default-case": 0,
+ eqeqeq: 2,
+ "for-direction": 2,
+ "func-name-matching": 2,
+ "func-names": 0,
+ "func-style": 0,
+ "getter-return": 2,
+ "global-require": 0,
+ "guard-for-in": 2,
+ "handle-callback-err": 2,
+ "id-blacklist": 0,
+ "id-length": 0,
+ "id-match": 0,
+ "init-declarations": 0,
+ "line-comment-position": 0,
+ "lines-between-class-members": 2,
+ "max-depth": [2, 4],
+ "max-lines": 0,
+ "max-nested-callbacks": [2, 4],
+ "max-params": [2, 6],
+ "max-statements": [2, 50],
+ "max-statements-per-line": [2, { max: 2 }],
+ "multiline-comment-style": 0,
+ "new-cap": [2, { newIsCap: true, capIsNew: false }],
+ "newline-after-var": 0,
+ "newline-before-return": 0,
+ "no-alert": 2,
+ "no-await-in-loop": 0,
+ "no-bitwise": 0,
+ "no-buffer-constructor": 2,
+ "no-catch-shadow": 2,
+ "no-console": 1,
+ "no-continue": 0,
+ "no-div-regex": 2,
+ "no-duplicate-imports": 2,
+ "no-empty-function": 0,
+ "no-eq-null": 2,
+ "no-extend-native": 2,
+ "no-extra-label": 2,
+ "no-implicit-coercion": [2, { allow: ["!!"] }],
+ "no-implicit-globals": 2,
+ "no-inline-comments": 0,
+ "no-invalid-this": 0,
+ "no-label-var": 2,
+ "no-loop-func": 2,
+ "no-magic-numbers": 0,
+ "no-mixed-requires": 2,
+ "no-multi-assign": 2,
+ "no-multi-str": 2,
+ "no-negated-condition": 0,
+ "no-negated-in-lhs": 2,
+ "no-new": 2,
+ "no-new-func": 2,
+ "no-new-require": 2,
+ "no-octal-escape": 2,
+ "no-param-reassign": 2,
+ "no-path-concat": 2,
+ "no-plusplus": 0,
+ "no-process-env": 0,
+ "no-process-exit": 2,
+ "no-proto": 2,
+ "no-prototype-builtins": 2,
+ "no-restricted-globals": 0,
+ "no-restricted-imports": 0,
+ "no-restricted-modules": 0,
+ "no-restricted-properties": 0,
+ "no-restricted-syntax": 0,
+ "no-return-assign": [2, "except-parens"],
+ "no-script-url": 2,
+ "no-shadow": 2,
+ "no-sync": 0,
+ "no-template-curly-in-string": 2,
+ "no-ternary": 0,
+ "no-undef-init": 2,
+ "no-undefined": 0,
+ "no-underscore-dangle": 0,
+ "no-unmodified-loop-condition": 2,
+ "no-unused-expressions": 2,
+ "no-use-before-define": 2,
+ "no-useless-computed-key": 2,
+ "no-useless-constructor": 2,
+ "no-useless-rename": 2,
+ "no-var": 2,
+ "no-void": 2,
+ "no-warning-comments": 0, // TODO: Change to `1`?
+ "one-var": [2, "never"],
+ "operator-assignment": [2, "always"],
+ "padding-line-between-statements": 0,
+ "prefer-const": 0, // TODO: Change to `1`?
+ "prefer-destructuring": [
+ 2,
+ {
+ AssignmentExpression: { array: true },
+ VariableDeclarator: { array: true, object: true },
+ },
+ ],
+ "prefer-numeric-literals": 2,
+ "prefer-promise-reject-errors": 2,
+ "prefer-reflect": 0,
+ "prefer-rest-params": 2,
+ "prefer-spread": 2,
+ "prefer-template": 2,
+ radix: [2, "always"],
+ "require-await": 2,
+ "require-jsdoc": 0,
+ "sort-keys": 0,
+ "sort-vars": 2,
+ strict: 0,
+ "symbol-description": 2,
+ "valid-jsdoc": [
+ 0,
+ {
+ requireReturn: false,
+ requireParamDescription: false,
+ requireReturnDescription: false,
+ },
+ ],
+ "vars-on-top": 2,
+ yoda: [2, "never"],
+ },
+};
diff --git a/browser/components/newtab/.nvmrc b/browser/components/newtab/.nvmrc
new file mode 100644
index 0000000000..2baa2d433a
--- /dev/null
+++ b/browser/components/newtab/.nvmrc
@@ -0,0 +1 @@
+10.23.1
diff --git a/browser/components/newtab/.sass-lint.yml b/browser/components/newtab/.sass-lint.yml
new file mode 100644
index 0000000000..bb7a68d3eb
--- /dev/null
+++ b/browser/components/newtab/.sass-lint.yml
@@ -0,0 +1,27 @@
+options:
+ merge-default-rules: true
+ max-warnings: 0
+
+files:
+ include: 'content-src/**/*.scss'
+
+rules:
+ class-name-format: 0
+ extends-before-declarations: 2
+ extends-before-mixins: 2
+ force-element-nesting: 0
+ force-pseudo-nesting: 0
+ hex-notation: [2, {style: uppercase}]
+ indentation: [2, {size: 2}]
+ leading-zero: [2, {include: true}]
+ mixins-before-declarations: [2, {exclude: [breakpoint, mq]}]
+ nesting-depth: [2, {max-depth: 4}]
+ no-debug: 1
+ no-disallowed-properties: [1, {properties: [margin-left, margin-right, text-transform]}]
+ no-duplicate-properties: 2
+ no-misspelled-properties: [2, {extra-properties: [-moz-context-properties]}]
+ no-url-domains: 0
+ no-vendor-prefixes: 0
+ no-warn: 1
+ placeholder-in-extend: 2
+ property-sort-order: 0
diff --git a/browser/components/newtab/AboutNewTabService.jsm b/browser/components/newtab/AboutNewTabService.jsm
new file mode 100644
index 0000000000..65e4d38b8d
--- /dev/null
+++ b/browser/components/newtab/AboutNewTabService.jsm
@@ -0,0 +1,512 @@
+/**
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
+ */
+
+"use strict";
+
+const EXPORTED_SYMBOLS = [
+ "AboutNewTabStubService",
+ "AboutHomeStartupCacheChild",
+];
+
+/**
+ * The nsIAboutNewTabService is accessed by the AboutRedirector anytime
+ * about:home, about:newtab or about:welcome are requested. The primary
+ * job of an nsIAboutNewTabService is to tell the AboutRedirector what
+ * resources to actually load for those requests.
+ *
+ * The nsIAboutNewTabService is not involved when the user has overridden
+ * the default about:home or about:newtab pages.
+ *
+ * There are two implementations of this service - one for the parent
+ * process, and one for content processes. Each one has some secondary
+ * responsibilties that are process-specific.
+ *
+ * The need for two implementations is an unfortunate consequence of how
+ * document loading and process redirection for about: pages currently
+ * works in Gecko. The commonalities between the two implementations has
+ * been put into an abstract base class.
+ */
+
+const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
+const { XPCOMUtils } = ChromeUtils.import(
+ "resource://gre/modules/XPCOMUtils.jsm"
+);
+const { AppConstants } = ChromeUtils.import(
+ "resource://gre/modules/AppConstants.jsm"
+);
+const { E10SUtils } = ChromeUtils.import(
+ "resource://gre/modules/E10SUtils.jsm"
+);
+
+const { ExperimentAPI } = ChromeUtils.import(
+ "resource://messaging-system/experiments/ExperimentAPI.jsm"
+);
+
+/**
+ * BEWARE: Do not add variables for holding state in the global scope.
+ * Any state variables should be properties of the appropriate class
+ * below. This is to avoid confusion where the state is set in one process,
+ * but not in another.
+ *
+ * Constants are fine in the global scope.
+ */
+
+const PREF_ABOUT_HOME_CACHE_ENABLED =
+ "browser.startup.homepage.abouthome_cache.enabled";
+const PREF_ABOUT_HOME_CACHE_TESTING =
+ "browser.startup.homepage.abouthome_cache.testing";
+const PREF_ABOUT_WELCOME_ENABLED = "browser.aboutwelcome.enabled";
+const ABOUT_WELCOME_URL =
+ "resource://activity-stream/aboutwelcome/aboutwelcome.html";
+
+ChromeUtils.defineModuleGetter(
+ this,
+ "BasePromiseWorker",
+ "resource://gre/modules/PromiseWorker.jsm"
+);
+
+const CACHE_WORKER_URL = "resource://activity-stream/lib/cache-worker.js";
+
+const IS_PRIVILEGED_PROCESS =
+ Services.appinfo.remoteType === E10SUtils.PRIVILEGEDABOUT_REMOTE_TYPE;
+
+const PREF_SEPARATE_PRIVILEGEDABOUT_CONTENT_PROCESS =
+ "browser.tabs.remote.separatePrivilegedContentProcess";
+const PREF_ACTIVITY_STREAM_DEBUG = "browser.newtabpage.activity-stream.debug";
+
+/**
+ * The AboutHomeStartupCacheChild is responsible for connecting the
+ * nsIAboutNewTabService with a cached document and script for about:home
+ * if one happens to exist. The AboutHomeStartupCacheChild is only ever
+ * handed the streams for those caches when the "privileged about content
+ * process" first launches, so subsequent loads of about:home do not read
+ * from this cache.
+ *
+ * See https://firefox-source-docs.mozilla.org/browser/components/newtab/docs/v2-system-addon/about_home_startup_cache.html
+ * for further details.
+ */
+const AboutHomeStartupCacheChild = {
+ _initted: false,
+ CACHE_REQUEST_MESSAGE: "AboutHomeStartupCache:CacheRequest",
+ CACHE_RESPONSE_MESSAGE: "AboutHomeStartupCache:CacheResponse",
+ CACHE_USAGE_RESULT_MESSAGE: "AboutHomeStartupCache:UsageResult",
+ STATES: {
+ UNAVAILABLE: 0,
+ UNCONSUMED: 1,
+ PAGE_CONSUMED: 2,
+ PAGE_AND_SCRIPT_CONSUMED: 3,
+ FAILED: 4,
+ },
+ REQUEST_TYPE: {
+ PAGE: 0,
+ SCRIPT: 1,
+ },
+ _state: 0,
+ _consumerBCID: null,
+
+ /**
+ * Called via a process script very early on in the process lifetime. This
+ * prepares the AboutHomeStartupCacheChild to pass an nsIChannel back to
+ * the nsIAboutNewTabService when the initial about:home document is
+ * eventually requested.
+ *
+ * @param pageInputStream (nsIInputStream)
+ * The stream for the cached page markup.
+ * @param scriptInputStream (nsIInputStream)
+ * The stream for the cached script to run on the page.
+ */
+ init(pageInputStream, scriptInputStream) {
+ if (
+ !IS_PRIVILEGED_PROCESS &&
+ !Services.prefs.getBoolPref(PREF_ABOUT_HOME_CACHE_TESTING, false)
+ ) {
+ throw new Error(
+ "Can only instantiate in the privileged about content processes."
+ );
+ }
+
+ if (!Services.prefs.getBoolPref(PREF_ABOUT_HOME_CACHE_ENABLED, false)) {
+ return;
+ }
+
+ if (this._initted) {
+ throw new Error("AboutHomeStartupCacheChild already initted.");
+ }
+
+ Services.obs.addObserver(this, "memory-pressure");
+ Services.cpmm.addMessageListener(this.CACHE_REQUEST_MESSAGE, this);
+
+ this._pageInputStream = pageInputStream;
+ this._scriptInputStream = scriptInputStream;
+ this._initted = true;
+ this.setState(this.STATES.UNCONSUMED);
+ },
+
+ /**
+ * A function that lets us put the AboutHomeStartupCacheChild back into
+ * its initial state. This is used by tests to let us simulate the startup
+ * behaviour of the module without having to manually launch a new privileged
+ * about content process every time.
+ */
+ uninit() {
+ if (!Services.prefs.getBoolPref(PREF_ABOUT_HOME_CACHE_TESTING, false)) {
+ throw new Error(
+ "Cannot uninit AboutHomeStartupCacheChild unless testing."
+ );
+ }
+
+ if (!this._initted) {
+ return;
+ }
+
+ Services.obs.removeObserver(this, "memory-pressure");
+ Services.cpmm.removeMessageListener(this.CACHE_REQUEST_MESSAGE, this);
+
+ if (this._cacheWorker) {
+ this._cacheWorker.terminate();
+ this._cacheWorker = null;
+ }
+
+ this._pageInputStream = null;
+ this._scriptInputStream = null;
+ this._initted = false;
+ this._state = this.STATES.UNAVAILABLE;
+ this._consumerBCID = null;
+ },
+
+ /**
+ * A public method called from nsIAboutNewTabService that attempts
+ * return an nsIChannel for a cached about:home document that we
+ * were initialized with. If we failed to be initted with the
+ * cache, or the input streams that we were sent have no data
+ * yet available, this function returns null. The caller should
+ * fall back to generating the page dynamically.
+ *
+ * This function will be called when loading about:home, or
+ * about:home?jscache - the latter returns the cached script.
+ *
+ * It is expected that the same BrowsingContext that loads the cached
+ * page will also load the cached script.
+ *
+ * @param uri (nsIURI)
+ * The URI for the requested page, as passed by nsIAboutNewTabService.
+ * @param loadInfo (nsILoadInfo)
+ * The nsILoadInfo for the requested load, as passed by
+ * nsIAboutNewWTabService.
+ * @return nsIChannel or null.
+ */
+ maybeGetCachedPageChannel(uri, loadInfo) {
+ if (!this._initted) {
+ return null;
+ }
+
+ if (this._state >= this.STATES.PAGE_AND_SCRIPT_CONSUMED) {
+ return null;
+ }
+
+ let requestType =
+ uri.query === "jscache"
+ ? this.REQUEST_TYPE.SCRIPT
+ : this.REQUEST_TYPE.PAGE;
+
+ // If this is a page request, then we need to be in the UNCONSUMED state,
+ // since we expect the page request to come first. If this is a script
+ // request, we expect to be in PAGE_CONSUMED state, since the page cache
+ // stream should he been consumed already.
+ if (
+ (requestType === this.REQUEST_TYPE.PAGE &&
+ this._state !== this.STATES.UNCONSUMED) ||
+ (requestType === this.REQUEST_TYPE_SCRIPT &&
+ this._state !== this.STATES.PAGE_CONSUMED)
+ ) {
+ return null;
+ }
+
+ // If by this point, we don't have anything in the streams,
+ // then either the cache was too slow to give us data, or the cache
+ // doesn't exist. The caller should fall back to generating the
+ // page dynamically.
+ //
+ // We only do this on the page request, because by the time
+ // we get to the script request, we should have already drained
+ // the page input stream.
+ if (requestType === this.REQUEST_TYPE.PAGE) {
+ try {
+ if (
+ !this._scriptInputStream.available() ||
+ !this._pageInputStream.available()
+ ) {
+ this.setState(this.STATES.FAILED);
+ this.reportUsageResult(false /* success */);
+ return null;
+ }
+ } catch (e) {
+ this.setState(this.STATES.FAILED);
+ if (e.result === Cr.NS_BASE_STREAM_CLOSED) {
+ this.reportUsageResult(false /* success */);
+ return null;
+ }
+ throw e;
+ }
+ }
+
+ if (
+ requestType === this.REQUEST_TYPE.SCRIPT &&
+ this._consumerBCID !== loadInfo.browsingContextID
+ ) {
+ // Some other document is somehow requesting the script - one
+ // that didn't originally request the page. This is not allowed.
+ this.setState(this.STATES.FAILED);
+ return null;
+ }
+
+ let channel = Cc[
+ "@mozilla.org/network/input-stream-channel;1"
+ ].createInstance(Ci.nsIInputStreamChannel);
+ channel.QueryInterface(Ci.nsIChannel);
+ channel.setURI(uri);
+ channel.loadInfo = loadInfo;
+ channel.contentStream =
+ requestType === this.REQUEST_TYPE.PAGE
+ ? this._pageInputStream
+ : this._scriptInputStream;
+
+ if (requestType === this.REQUEST_TYPE.SCRIPT) {
+ this.setState(this.STATES.PAGE_AND_SCRIPT_CONSUMED);
+ this.reportUsageResult(true /* success */);
+ } else {
+ this.setState(this.STATES.PAGE_CONSUMED);
+ // Stash the BrowsingContext ID so that when the script stream
+ // attempts to be consumed, we ensure that it's from the same
+ // BrowsingContext that loaded the page.
+ this._consumerBCID = loadInfo.browsingContextID;
+ }
+
+ return channel;
+ },
+
+ /**
+ * This function takes the state information required to generate
+ * the about:home cache markup and script, and then generates that
+ * markup in script asynchronously. Once that's done, a message
+ * is sent to the parent process with the nsIInputStream's for the
+ * markup and script contents.
+ *
+ * @param state (Object)
+ * The Redux state of the about:home document to render.
+ * @return Promise
+ * @resolves undefined
+ * After the message with the nsIInputStream's have been sent to
+ * the parent.
+ */
+ async constructAndSendCache(state) {
+ if (!IS_PRIVILEGED_PROCESS) {
+ throw new Error("Wrong process type.");
+ }
+
+ let worker = this.getOrCreateWorker();
+
+ TelemetryStopwatch.start("FX_ABOUTHOME_CACHE_CONSTRUCTION");
+
+ let { page, script } = await worker
+ .post("construct", [state])
+ .finally(() => {
+ TelemetryStopwatch.finish("FX_ABOUTHOME_CACHE_CONSTRUCTION");
+ });
+
+ let pageInputStream = Cc[
+ "@mozilla.org/io/string-input-stream;1"
+ ].createInstance(Ci.nsIStringInputStream);
+
+ pageInputStream.setUTF8Data(page);
+
+ let scriptInputStream = Cc[
+ "@mozilla.org/io/string-input-stream;1"
+ ].createInstance(Ci.nsIStringInputStream);
+
+ scriptInputStream.setUTF8Data(script);
+
+ Services.cpmm.sendAsyncMessage(this.CACHE_RESPONSE_MESSAGE, {
+ pageInputStream,
+ scriptInputStream,
+ });
+ },
+
+ _cacheWorker: null,
+ getOrCreateWorker() {
+ if (this._cacheWorker) {
+ return this._cacheWorker;
+ }
+
+ this._cacheWorker = new BasePromiseWorker(CACHE_WORKER_URL);
+ return this._cacheWorker;
+ },
+
+ receiveMessage(message) {
+ if (message.name === this.CACHE_REQUEST_MESSAGE) {
+ let { state } = message.data;
+ this.constructAndSendCache(state);
+ }
+ },
+
+ reportUsageResult(success) {
+ Services.cpmm.sendAsyncMessage(this.CACHE_USAGE_RESULT_MESSAGE, {
+ success,
+ });
+ },
+
+ observe(subject, topic, data) {
+ if (topic === "memory-pressure" && this._cacheWorker) {
+ this._cacheWorker.terminate();
+ this._cacheWorker = null;
+ }
+ },
+
+ /**
+ * Transitions the AboutHomeStartupCacheChild from one state
+ * to the next, where each state is defined in this.STATES.
+ *
+ * States can only be transitioned in increasing order, otherwise
+ * an error is logged.
+ */
+ setState(state) {
+ if (state > this._state) {
+ this._state = state;
+ } else {
+ console.error(
+ "AboutHomeStartupCacheChild could not transition from state " +
+ `${this._state} to ${state}`,
+ new Error().stack
+ );
+ }
+ },
+};
+
+/**
+ * This is an abstract base class for the nsIAboutNewTabService
+ * implementations that has some common methods and properties.
+ */
+class BaseAboutNewTabService {
+ constructor() {
+ if (!AppConstants.RELEASE_OR_BETA) {
+ XPCOMUtils.defineLazyPreferenceGetter(
+ this,
+ "activityStreamDebug",
+ PREF_ACTIVITY_STREAM_DEBUG,
+ false
+ );
+ } else {
+ this.activityStreamDebug = false;
+ }
+
+ XPCOMUtils.defineLazyPreferenceGetter(
+ this,
+ "isAboutWelcomePrefEnabled",
+ PREF_ABOUT_WELCOME_ENABLED,
+ false
+ );
+
+ XPCOMUtils.defineLazyPreferenceGetter(
+ this,
+ "privilegedAboutProcessEnabled",
+ PREF_SEPARATE_PRIVILEGEDABOUT_CONTENT_PROCESS,
+ false
+ );
+
+ this.classID = Components.ID("{cb36c925-3adc-49b3-b720-a5cc49d8a40e}");
+ this.QueryInterface = ChromeUtils.generateQI([
+ "nsIAboutNewTabService",
+ "nsIObserver",
+ ]);
+ }
+
+ /**
+ * Returns the default URL.
+ *
+ * This URL depends on various activity stream prefs. Overriding
+ * the newtab page has no effect on the result of this function.
+ */
+ get defaultURL() {
+ // Generate the desired activity stream resource depending on state, e.g.,
+ // "resource://activity-stream/prerendered/activity-stream.html"
+ // "resource://activity-stream/prerendered/activity-stream-debug.html"
+ // "resource://activity-stream/prerendered/activity-stream-noscripts.html"
+ return [
+ "resource://activity-stream/prerendered/",
+ "activity-stream",
+ // Debug version loads dev scripts but noscripts separately loads scripts
+ this.activityStreamDebug && !this.privilegedAboutProcessEnabled
+ ? "-debug"
+ : "",
+ this.privilegedAboutProcessEnabled ? "-noscripts" : "",
+ ".html",
+ ].join("");
+ }
+
+ get welcomeURL() {
+ /*
+ * Returns the about:welcome URL
+ *
+ * This is calculated in the same way the default URL is.
+ */
+
+ if (
+ this.isAboutWelcomePrefEnabled &&
+ // about:welcome should be enabled by default if no experiment exists.
+ ExperimentAPI.isFeatureEnabled("aboutwelcome", true)
+ ) {
+ return ABOUT_WELCOME_URL;
+ }
+ return this.defaultURL;
+ }
+
+ aboutHomeChannel(uri, loadInfo) {
+ throw Components.Exception(
+ "AboutHomeChannel not implemented for this process.",
+ Cr.NS_ERROR_NOT_IMPLEMENTED
+ );
+ }
+}
+
+/**
+ * The child-process implementation of nsIAboutNewTabService,
+ * which also does the work of redirecting about:home loads to
+ * the about:home startup cache if its available.
+ */
+class AboutNewTabChildService extends BaseAboutNewTabService {
+ aboutHomeChannel(uri, loadInfo) {
+ if (IS_PRIVILEGED_PROCESS) {
+ let cacheChannel = AboutHomeStartupCacheChild.maybeGetCachedPageChannel(
+ uri,
+ loadInfo
+ );
+ if (cacheChannel) {
+ return cacheChannel;
+ }
+ }
+
+ let pageURI = Services.io.newURI(this.defaultURL);
+ let fileChannel = Services.io.newChannelFromURIWithLoadInfo(
+ pageURI,
+ loadInfo
+ );
+ fileChannel.originalURI = uri;
+ return fileChannel;
+ }
+}
+
+/**
+ * The AboutNewTabStubService is a function called in both the main and
+ * content processes when trying to get at the nsIAboutNewTabService. This
+ * function does the job of choosing the appropriate implementation of
+ * nsIAboutNewTabService for the process type.
+ */
+function AboutNewTabStubService() {
+ if (Services.appinfo.processType === Services.appinfo.PROCESS_TYPE_DEFAULT) {
+ return new BaseAboutNewTabService();
+ }
+ return new AboutNewTabChildService();
+}
diff --git a/browser/components/newtab/aboutwelcome/AboutWelcomeChild.jsm b/browser/components/newtab/aboutwelcome/AboutWelcomeChild.jsm
new file mode 100644
index 0000000000..459603c379
--- /dev/null
+++ b/browser/components/newtab/aboutwelcome/AboutWelcomeChild.jsm
@@ -0,0 +1,386 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+const EXPORTED_SYMBOLS = ["AboutWelcomeChild"];
+
+const { XPCOMUtils } = ChromeUtils.import(
+ "resource://gre/modules/XPCOMUtils.jsm"
+);
+
+XPCOMUtils.defineLazyModuleGetters(this, {
+ DEFAULT_SITES: "resource://activity-stream/lib/DefaultSites.jsm",
+ ExperimentAPI: "resource://messaging-system/experiments/ExperimentAPI.jsm",
+ shortURL: "resource://activity-stream/lib/ShortURL.jsm",
+ TippyTopProvider: "resource://activity-stream/lib/TippyTopProvider.jsm",
+});
+
+XPCOMUtils.defineLazyGetter(this, "log", () => {
+ const { Logger } = ChromeUtils.import(
+ "resource://messaging-system/lib/Logger.jsm"
+ );
+ return new Logger("AboutWelcomeChild");
+});
+
+XPCOMUtils.defineLazyGetter(this, "tippyTopProvider", () =>
+ (async () => {
+ const provider = new TippyTopProvider();
+ await provider.init();
+ return provider;
+ })()
+);
+
+function _parseOverrideContent(value) {
+ let result = {};
+ try {
+ result = value ? JSON.parse(value) : {};
+ } catch (e) {
+ Cu.reportError(e);
+ }
+ return result;
+}
+
+XPCOMUtils.defineLazyPreferenceGetter(
+ this,
+ "multiStageAboutWelcomeContent",
+ "browser.aboutwelcome.overrideContent",
+ "",
+ null,
+ _parseOverrideContent
+);
+
+const SEARCH_REGION_PREF = "browser.search.region";
+
+XPCOMUtils.defineLazyPreferenceGetter(
+ this,
+ "searchRegion",
+ SEARCH_REGION_PREF,
+ ""
+);
+
+/**
+ * Lazily get importable sites from parent or reuse cached ones.
+ */
+function getImportableSites(child) {
+ return (
+ getImportableSites.cache ??
+ (getImportableSites.cache = (async () => {
+ // Use tippy top to get packaged rich icons
+ const tippyTop = await tippyTopProvider;
+ // Remove duplicate entries if they would appear the same
+ return `[${[
+ ...new Set(
+ (await child.sendQuery("AWPage:IMPORTABLE_SITES")).map(url => {
+ // Get both rich icon and short name and save for deduping
+ const site = { url };
+ tippyTop.processSite(site, "*");
+ return JSON.stringify({
+ icon: site.tippyTopIcon,
+ label: shortURL(site),
+ });
+ })
+ ),
+ ]}]`;
+ })())
+ );
+}
+
+async function getDefaultSites(child) {
+ // Get default TopSites by region
+ let sites = DEFAULT_SITES.get(
+ DEFAULT_SITES.has(searchRegion) ? searchRegion : ""
+ );
+
+ // Use tippy top to get packaged rich icons
+ const tippyTop = await tippyTopProvider;
+ let defaultSites = sites.split(",").map(link => {
+ let site = { url: link };
+ tippyTop.processSite(site);
+ return {
+ icon: site.tippyTopIcon,
+ title: shortURL(site),
+ };
+ });
+ return Cu.cloneInto(defaultSites, child.contentWindow);
+}
+
+async function getSelectedTheme(child) {
+ let activeThemeId = await child.sendQuery("AWPage:GET_SELECTED_THEME");
+ return activeThemeId;
+}
+
+class AboutWelcomeChild extends JSWindowActorChild {
+ actorCreated() {
+ this.exportFunctions();
+ this.initWebProgressListener();
+ }
+
+ initWebProgressListener() {
+ const webProgress = this.manager.browsingContext.top.docShell
+ .QueryInterface(Ci.nsIInterfaceRequestor)
+ .getInterface(Ci.nsIWebProgress);
+
+ const listener = {
+ QueryInterface: ChromeUtils.generateQI([
+ "nsIWebProgressListener",
+ "nsISupportsWeakReference",
+ ]),
+ };
+
+ listener.onLocationChange = (aWebProgress, aRequest, aLocation, aFlags) => {
+ // Exit if actor 'AboutWelcome' has already been destroyed or
+ // content window doesn't exist
+ if (!this.manager || !this.contentWindow) {
+ return;
+ }
+ log.debug(`onLocationChange handled: ${aWebProgress.DOMWindow}`);
+ this.AWSendToParent("LOCATION_CHANGED");
+ };
+
+ webProgress.addProgressListener(
+ listener,
+ Ci.nsIWebProgress.NOTIFY_LOCATION
+ );
+ }
+
+ /**
+ * Send event that can be handled by the page
+ * @param {{type: string, data?: any}} action
+ */
+ sendToPage(action) {
+ log.debug(`Sending to page: ${action.type}`);
+ const win = this.document.defaultView;
+ const event = new win.CustomEvent("AboutWelcomeChromeToContent", {
+ detail: Cu.cloneInto(action, win),
+ });
+ win.dispatchEvent(event);
+ }
+
+ /**
+ * Export functions that can be called by page js
+ */
+ exportFunctions() {
+ let window = this.contentWindow;
+
+ Cu.exportFunction(this.AWGetExperimentData.bind(this), window, {
+ defineAs: "AWGetExperimentData",
+ });
+
+ Cu.exportFunction(this.AWGetAttributionData.bind(this), window, {
+ defineAs: "AWGetAttributionData",
+ });
+
+ // For local dev, checks for JSON content inside pref browser.aboutwelcome.overrideContent
+ // that is used to override default welcome UI
+ Cu.exportFunction(this.AWGetWelcomeOverrideContent.bind(this), window, {
+ defineAs: "AWGetWelcomeOverrideContent",
+ });
+
+ Cu.exportFunction(this.AWGetFxAMetricsFlowURI.bind(this), window, {
+ defineAs: "AWGetFxAMetricsFlowURI",
+ });
+
+ Cu.exportFunction(this.AWGetImportableSites.bind(this), window, {
+ defineAs: "AWGetImportableSites",
+ });
+
+ Cu.exportFunction(this.AWGetDefaultSites.bind(this), window, {
+ defineAs: "AWGetDefaultSites",
+ });
+
+ Cu.exportFunction(this.AWGetSelectedTheme.bind(this), window, {
+ defineAs: "AWGetSelectedTheme",
+ });
+
+ Cu.exportFunction(this.AWGetRegion.bind(this), window, {
+ defineAs: "AWGetRegion",
+ });
+
+ Cu.exportFunction(this.AWSelectTheme.bind(this), window, {
+ defineAs: "AWSelectTheme",
+ });
+
+ Cu.exportFunction(this.AWSendEventTelemetry.bind(this), window, {
+ defineAs: "AWSendEventTelemetry",
+ });
+
+ Cu.exportFunction(this.AWSendToParent.bind(this), window, {
+ defineAs: "AWSendToParent",
+ });
+
+ Cu.exportFunction(this.AWWaitForMigrationClose.bind(this), window, {
+ defineAs: "AWWaitForMigrationClose",
+ });
+ }
+
+ /**
+ * Wrap a promise so content can use Promise methods.
+ */
+ wrapPromise(promise) {
+ return new this.contentWindow.Promise((resolve, reject) =>
+ promise.then(resolve, reject)
+ );
+ }
+
+ /**
+ * Send multistage welcome JSON data read from aboutwelcome.overrideConetent pref to page
+ */
+ AWGetWelcomeOverrideContent() {
+ return Cu.cloneInto(
+ multiStageAboutWelcomeContent || {},
+ this.contentWindow
+ );
+ }
+
+ AWSelectTheme(data) {
+ return this.wrapPromise(
+ this.sendQuery("AWPage:SELECT_THEME", data.toUpperCase())
+ );
+ }
+
+ async getAddonInfo(attrbObj) {
+ let { content, source } = attrbObj;
+ try {
+ if (!content || source !== "addons.mozilla.org") {
+ return null;
+ }
+ // Attribution data can be double encoded
+ while (content.includes("%")) {
+ try {
+ const result = decodeURIComponent(content);
+ if (result === content) {
+ break;
+ }
+ content = result;
+ } catch (e) {
+ break;
+ }
+ }
+ return await this.sendQuery("AWPage:GET_ADDON_FROM_REPOSITORY", content);
+ } catch (e) {
+ Cu.reportError(
+ "Failed to get the latest add-on version for Return to AMO"
+ );
+ return null;
+ }
+ }
+
+ hasAMOAttribution(attributionData) {
+ return (
+ attributionData &&
+ attributionData.campaign === "non-fx-button" &&
+ attributionData.source === "addons.mozilla.org"
+ );
+ }
+
+ async formatAttributionData(attribution) {
+ let result = {};
+ if (this.hasAMOAttribution(attribution)) {
+ let extraProps = await this.getAddonInfo(attribution);
+ if (extraProps) {
+ result = {
+ template: "return_to_amo",
+ extraProps,
+ };
+ }
+ }
+ return result;
+ }
+
+ async getAttributionData() {
+ return Cu.cloneInto(
+ await this.formatAttributionData(
+ await this.sendQuery("AWPage:GET_ATTRIBUTION_DATA")
+ ),
+ this.contentWindow
+ );
+ }
+
+ AWGetAttributionData() {
+ return this.wrapPromise(this.getAttributionData());
+ }
+
+ /**
+ * Send initial data to page including experiment information
+ */
+ AWGetExperimentData() {
+ let experimentData;
+ try {
+ // Note that we specifically don't wait for experiments to be loaded from disk so if
+ // about:welcome loads outside of the "FirstStartup" scenario this will likely not be ready
+ experimentData = ExperimentAPI.getExperiment({
+ featureId: "aboutwelcome",
+ // Telemetry handled in AboutNewTabService.jsm
+ sendExposurePing: false,
+ });
+ } catch (e) {
+ Cu.reportError(e);
+ }
+
+ if (experimentData?.slug) {
+ log.debug(
+ `Loading about:welcome with experiment: ${experimentData.slug}`
+ );
+ } else {
+ log.debug("Loading about:welcome without experiment");
+ }
+ return Cu.cloneInto(experimentData || {}, this.contentWindow);
+ }
+
+ AWGetFxAMetricsFlowURI() {
+ return this.wrapPromise(this.sendQuery("AWPage:FXA_METRICS_FLOW_URI"));
+ }
+
+ AWGetImportableSites() {
+ return this.wrapPromise(getImportableSites(this));
+ }
+
+ AWGetDefaultSites() {
+ return this.wrapPromise(getDefaultSites(this));
+ }
+
+ AWGetSelectedTheme() {
+ return this.wrapPromise(getSelectedTheme(this));
+ }
+
+ /**
+ * Send Event Telemetry
+ * @param {object} eventData
+ */
+ AWSendEventTelemetry(eventData) {
+ this.AWSendToParent("TELEMETRY_EVENT", {
+ ...eventData,
+ event_context: {
+ ...eventData.event_context,
+ page: "about:welcome",
+ },
+ });
+ }
+
+ /**
+ * Send message that can be handled by AboutWelcomeParent.jsm
+ * @param {string} type
+ * @param {any=} data
+ */
+ AWSendToParent(type, data) {
+ this.sendAsyncMessage(`AWPage:${type}`, data);
+ }
+
+ AWWaitForMigrationClose() {
+ return this.wrapPromise(this.sendQuery("AWPage:WAIT_FOR_MIGRATION_CLOSE"));
+ }
+
+ AWGetRegion() {
+ return this.wrapPromise(this.sendQuery("AWPage:GET_REGION"));
+ }
+
+ /**
+ * @param {{type: string, detail?: any}} event
+ * @override
+ */
+ handleEvent(event) {
+ log.debug(`Received page event ${event.type}`);
+ }
+}
diff --git a/browser/components/newtab/aboutwelcome/AboutWelcomeParent.jsm b/browser/components/newtab/aboutwelcome/AboutWelcomeParent.jsm
new file mode 100644
index 0000000000..37e32ac1d7
--- /dev/null
+++ b/browser/components/newtab/aboutwelcome/AboutWelcomeParent.jsm
@@ -0,0 +1,310 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+const EXPORTED_SYMBOLS = ["AboutWelcomeParent"];
+const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
+
+const { XPCOMUtils } = ChromeUtils.import(
+ "resource://gre/modules/XPCOMUtils.jsm"
+);
+
+XPCOMUtils.defineLazyModuleGetters(this, {
+ AddonManager: "resource://gre/modules/AddonManager.jsm",
+ AddonRepository: "resource://gre/modules/addons/AddonRepository.jsm",
+ FxAccounts: "resource://gre/modules/FxAccounts.jsm",
+ MigrationUtils: "resource:///modules/MigrationUtils.jsm",
+ OS: "resource://gre/modules/osfile.jsm",
+ SpecialMessageActions:
+ "resource://messaging-system/lib/SpecialMessageActions.jsm",
+ AboutWelcomeTelemetry:
+ "resource://activity-stream/aboutwelcome/lib/AboutWelcomeTelemetry.jsm",
+ AttributionCode: "resource:///modules/AttributionCode.jsm",
+ PromiseUtils: "resource://gre/modules/PromiseUtils.jsm",
+ Region: "resource://gre/modules/Region.jsm",
+});
+
+XPCOMUtils.defineLazyGetter(this, "log", () => {
+ const { Logger } = ChromeUtils.import(
+ "resource://messaging-system/lib/Logger.jsm"
+ );
+ return new Logger("AboutWelcomeParent");
+});
+
+XPCOMUtils.defineLazyGetter(
+ this,
+ "Telemetry",
+ () => new AboutWelcomeTelemetry()
+);
+
+const DID_SEE_ABOUT_WELCOME_PREF = "trailhead.firstrun.didSeeAboutWelcome";
+const AWTerminate = {
+ UNKNOWN: "unknown",
+ WINDOW_CLOSED: "welcome-window-closed",
+ TAB_CLOSED: "welcome-tab-closed",
+ APP_SHUT_DOWN: "app-shut-down",
+ ADDRESS_BAR_NAVIGATED: "address-bar-navigated",
+};
+const LIGHT_WEIGHT_THEMES = {
+ DARK: "firefox-compact-dark@mozilla.org",
+ LIGHT: "firefox-compact-light@mozilla.org",
+ AUTOMATIC: "default-theme@mozilla.org",
+ ALPENGLOW: "firefox-alpenglow@mozilla.org",
+};
+
+async function getImportableSites() {
+ const sites = [];
+
+ // Just handle these chromium-based browsers for now
+ for (const browserId of ["chrome", "chromium-edge", "chromium"]) {
+ // Skip if there's no profile data.
+ const migrator = await MigrationUtils.getMigrator(browserId);
+ if (!migrator) {
+ continue;
+ }
+
+ // Check each profile for top sites
+ const dataPath = await migrator.wrappedJSObject._getChromeUserDataPathIfExists();
+ for (const profile of await migrator.getSourceProfiles()) {
+ let path = OS.Path.join(dataPath, profile.id, "Top Sites");
+ // Skip if top sites data is missing
+ if (!(await OS.File.exists(path))) {
+ Cu.reportError(`Missing file at ${path}`);
+ continue;
+ }
+
+ try {
+ for (const row of await MigrationUtils.getRowsFromDBWithoutLocks(
+ path,
+ `Importable ${browserId} top sites`,
+ `SELECT url
+ FROM top_sites
+ ORDER BY url_rank`
+ )) {
+ sites.push(row.getString(0));
+ }
+ } catch (ex) {
+ Cu.reportError(
+ `Failed to get importable top sites from ${browserId} ${ex}`
+ );
+ }
+ }
+ }
+ return sites;
+}
+
+class AboutWelcomeObserver {
+ constructor() {
+ Services.obs.addObserver(this, "quit-application");
+
+ this.win = Services.focus.activeWindow;
+ if (!this.win) {
+ return;
+ }
+
+ this.terminateReason = AWTerminate.UNKNOWN;
+
+ this.onWindowClose = () => {
+ this.terminateReason = AWTerminate.WINDOW_CLOSED;
+ };
+
+ this.onTabClose = () => {
+ this.terminateReason = AWTerminate.TAB_CLOSED;
+ };
+
+ this.win.addEventListener("TabClose", this.onTabClose, { once: true });
+ this.win.addEventListener("unload", this.onWindowClose, { once: true });
+ }
+
+ observe(aSubject, aTopic, aData) {
+ switch (aTopic) {
+ case "quit-application":
+ this.terminateReason = AWTerminate.APP_SHUT_DOWN;
+ break;
+ }
+ }
+
+ // Added for testing
+ get AWTerminate() {
+ return AWTerminate;
+ }
+
+ stop() {
+ log.debug(`Terminate reason is ${this.terminateReason}`);
+ Services.obs.removeObserver(this, "quit-application");
+ if (!this.win) {
+ return;
+ }
+ this.win.removeEventListener("TabClose", this.onTabClose);
+ this.win.removeEventListener("unload", this.onWindowClose);
+ this.win = null;
+ }
+}
+
+class RegionHomeObserver {
+ observe(aSubject, aTopic, aData) {
+ switch (aTopic) {
+ case Region.REGION_TOPIC:
+ if (aData === Region.REGION_UPDATED) {
+ Services.obs.removeObserver(this, Region.REGION_TOPIC);
+ this.regionHomeDeferred.resolve(Region.home);
+ this.regionHomeDeferred = null;
+ }
+ break;
+ }
+ }
+
+ promiseRegionHome() {
+ // Add observer and create promise that should be resolved
+ // with region or rejected inside didDestroy if user exits
+ // before region is available
+ if (!this.regionHomeDeferred) {
+ Services.obs.addObserver(this, Region.REGION_TOPIC);
+ this.regionHomeDeferred = PromiseUtils.defer();
+ }
+ return this.regionHomeDeferred.promise;
+ }
+
+ stop() {
+ if (this.regionHomeDeferred) {
+ Services.obs.removeObserver(this, Region.REGION_TOPIC);
+ // Reject unresolved deferred promise on exit
+ this.regionHomeDeferred.reject(
+ new Error("Unresolved region home promise")
+ );
+ this.regionHomeDeferred = null;
+ }
+ }
+}
+
+class AboutWelcomeParent extends JSWindowActorParent {
+ constructor() {
+ super();
+ this.AboutWelcomeObserver = new AboutWelcomeObserver(this);
+ }
+
+ didDestroy() {
+ if (this.AboutWelcomeObserver) {
+ this.AboutWelcomeObserver.stop();
+ }
+ this.RegionHomeObserver?.stop();
+
+ Telemetry.sendTelemetry({
+ event: "SESSION_END",
+ event_context: {
+ reason: this.AboutWelcomeObserver.terminateReason,
+ page: "about:welcome",
+ },
+ message_id: this.AWMessageId,
+ id: "ABOUT_WELCOME",
+ });
+ }
+
+ /**
+ * Handle messages from AboutWelcomeChild.jsm
+ *
+ * @param {string} type
+ * @param {any=} data
+ * @param {Browser} browser
+ * @param {Window} window
+ */
+ async onContentMessage(type, data, browser, window) {
+ log.debug(`Received content event: ${type}`);
+ switch (type) {
+ case "AWPage:SET_WELCOME_MESSAGE_SEEN":
+ this.AWMessageId = data;
+ try {
+ Services.prefs.setBoolPref(DID_SEE_ABOUT_WELCOME_PREF, true);
+ } catch (e) {
+ log.debug(`Fails to set ${DID_SEE_ABOUT_WELCOME_PREF}.`);
+ }
+ break;
+ case "AWPage:SPECIAL_ACTION":
+ SpecialMessageActions.handleAction(data, browser);
+ break;
+ case "AWPage:FXA_METRICS_FLOW_URI":
+ return FxAccounts.config.promiseMetricsFlowURI("aboutwelcome");
+ case "AWPage:GET_ATTRIBUTION_DATA":
+ return AttributionCode.getAttrDataAsync();
+ case "AWPage:IMPORTABLE_SITES":
+ return getImportableSites();
+ case "AWPage:TELEMETRY_EVENT":
+ Telemetry.sendTelemetry(data);
+ break;
+ case "AWPage:LOCATION_CHANGED":
+ this.AboutWelcomeObserver.terminateReason =
+ AWTerminate.ADDRESS_BAR_NAVIGATED;
+ break;
+ case "AWPage:GET_ADDON_FROM_REPOSITORY":
+ const [addonInfo] = await AddonRepository.getAddonsByIDs([data]);
+ if (addonInfo.sourceURI.scheme !== "https") {
+ return null;
+ }
+ return {
+ name: addonInfo.name,
+ url: addonInfo.sourceURI.spec,
+ iconURL: addonInfo.icons["64"] || addonInfo.icons["32"],
+ };
+ case "AWPage:SELECT_THEME":
+ return AddonManager.getAddonByID(
+ LIGHT_WEIGHT_THEMES[data]
+ ).then(addon => addon.enable());
+ case "AWPage:GET_SELECTED_THEME":
+ let themes = await AddonManager.getAddonsByTypes(["theme"]);
+ let activeTheme = themes.find(addon => addon.isActive);
+
+ // convert this to the short form name that the front end code
+ // expects
+ let themeShortName = Object.keys(LIGHT_WEIGHT_THEMES).find(
+ key => LIGHT_WEIGHT_THEMES[key] === activeTheme?.id
+ );
+ return themeShortName?.toLowerCase();
+ case "AWPage:GET_REGION":
+ if (Region.home !== null) {
+ return Region.home;
+ }
+ if (!this.RegionHomeObserver) {
+ this.RegionHomeObserver = new RegionHomeObserver(this);
+ }
+ return this.RegionHomeObserver.promiseRegionHome();
+ case "AWPage:WAIT_FOR_MIGRATION_CLOSE":
+ return new Promise(resolve =>
+ Services.ww.registerNotification(function observer(subject, topic) {
+ if (
+ topic === "domwindowclosed" &&
+ subject.document.documentURI ===
+ "chrome://browser/content/migration/migration.xhtml"
+ ) {
+ Services.ww.unregisterNotification(observer);
+ resolve();
+ }
+ })
+ );
+ default:
+ log.debug(`Unexpected event ${type} was not handled.`);
+ }
+
+ return undefined;
+ }
+
+ /**
+ * @param {{name: string, data?: any}} message
+ * @override
+ */
+ receiveMessage(message) {
+ const { name, data } = message;
+ let browser;
+ let window;
+
+ if (this.manager.rootFrameLoader) {
+ browser = this.manager.rootFrameLoader.ownerElement;
+ window = browser.ownerGlobal;
+ return this.onContentMessage(name, data, browser, window);
+ }
+
+ log.warn(`Not handling ${name} because the browser doesn't exist.`);
+ return null;
+ }
+}
diff --git a/browser/components/newtab/aboutwelcome/content/aboutwelcome.bundle.js b/browser/components/newtab/aboutwelcome/content/aboutwelcome.bundle.js
new file mode 100644
index 0000000000..deed7d749f
--- /dev/null
+++ b/browser/components/newtab/aboutwelcome/content/aboutwelcome.bundle.js
@@ -0,0 +1,1501 @@
+/*!
+ *
+ * NOTE: This file is generated by webpack from aboutwelcome.jsx
+ * using the npm bundle task.
+ *
+ */
+/******/ (function(modules) { // webpackBootstrap
+/******/ // The module cache
+/******/ var installedModules = {};
+/******/
+/******/ // The require function
+/******/ function __webpack_require__(moduleId) {
+/******/
+/******/ // Check if module is in cache
+/******/ if(installedModules[moduleId]) {
+/******/ return installedModules[moduleId].exports;
+/******/ }
+/******/ // Create a new module (and put it into the cache)
+/******/ var module = installedModules[moduleId] = {
+/******/ i: moduleId,
+/******/ l: false,
+/******/ exports: {}
+/******/ };
+/******/
+/******/ // Execute the module function
+/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
+/******/
+/******/ // Flag the module as loaded
+/******/ module.l = true;
+/******/
+/******/ // Return the exports of the module
+/******/ return module.exports;
+/******/ }
+/******/
+/******/
+/******/ // expose the modules object (__webpack_modules__)
+/******/ __webpack_require__.m = modules;
+/******/
+/******/ // expose the module cache
+/******/ __webpack_require__.c = installedModules;
+/******/
+/******/ // define getter function for harmony exports
+/******/ __webpack_require__.d = function(exports, name, getter) {
+/******/ if(!__webpack_require__.o(exports, name)) {
+/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
+/******/ }
+/******/ };
+/******/
+/******/ // define __esModule on exports
+/******/ __webpack_require__.r = function(exports) {
+/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
+/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
+/******/ }
+/******/ Object.defineProperty(exports, '__esModule', { value: true });
+/******/ };
+/******/
+/******/ // create a fake namespace object
+/******/ // mode & 1: value is a module id, require it
+/******/ // mode & 2: merge all properties of value into the ns
+/******/ // mode & 4: return value when already ns object
+/******/ // mode & 8|1: behave like require
+/******/ __webpack_require__.t = function(value, mode) {
+/******/ if(mode & 1) value = __webpack_require__(value);
+/******/ if(mode & 8) return value;
+/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
+/******/ var ns = Object.create(null);
+/******/ __webpack_require__.r(ns);
+/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
+/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
+/******/ return ns;
+/******/ };
+/******/
+/******/ // getDefaultExport function for compatibility with non-harmony modules
+/******/ __webpack_require__.n = function(module) {
+/******/ var getter = module && module.__esModule ?
+/******/ function getDefault() { return module['default']; } :
+/******/ function getModuleExports() { return module; };
+/******/ __webpack_require__.d(getter, 'a', getter);
+/******/ return getter;
+/******/ };
+/******/
+/******/ // Object.prototype.hasOwnProperty.call
+/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
+/******/
+/******/ // __webpack_public_path__
+/******/ __webpack_require__.p = "";
+/******/
+/******/
+/******/ // Load entry module and return exports
+/******/ return __webpack_require__(__webpack_require__.s = 0);
+/******/ })
+/************************************************************************/
+/******/ ([
+/* 0 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
+/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2);
+/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react_dom__WEBPACK_IMPORTED_MODULE_1__);
+/* harmony import */ var _components_MultiStageAboutWelcome__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(3);
+/* harmony import */ var _components_SimpleAboutWelcome__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8);
+/* harmony import */ var _components_ReturnToAMO__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(12);
+/* harmony import */ var _lib_aboutwelcome_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(6);
+function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
+
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+
+
+
+
+
+class AboutWelcome extends react__WEBPACK_IMPORTED_MODULE_0___default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.state = {
+ metricsFlowUri: null
+ };
+ this.fetchFxAFlowUri = this.fetchFxAFlowUri.bind(this);
+ this.handleStartBtnClick = this.handleStartBtnClick.bind(this);
+ }
+
+ async fetchFxAFlowUri() {
+ this.setState({
+ metricsFlowUri: await window.AWGetFxAMetricsFlowURI()
+ });
+ }
+
+ componentDidMount() {
+ this.fetchFxAFlowUri(); // Record impression with performance data after allowing the page to load
+
+ const recordImpression = domState => {
+ const {
+ domComplete,
+ domInteractive
+ } = performance.getEntriesByType("navigation").pop();
+ window.AWSendEventTelemetry({
+ event: "IMPRESSION",
+ event_context: {
+ domComplete,
+ domInteractive,
+ mountStart: performance.getEntriesByName("mount").pop().startTime,
+ domState,
+ source: this.props.UTMTerm,
+ page: "about:welcome"
+ },
+ message_id: this.props.messageId
+ });
+ };
+
+ if (document.readyState === "complete") {
+ // Page might have already triggered a load event because it waited for async data,
+ // e.g., attribution, so the dom load timing could be of a empty content
+ // with domState in telemetry captured as 'complete'
+ recordImpression(document.readyState);
+ } else {
+ window.addEventListener("load", () => recordImpression("load"), {
+ once: true
+ });
+ } // Captures user has seen about:welcome by setting
+ // firstrun.didSeeAboutWelcome pref to true and capturing welcome UI unique messageId
+
+
+ window.AWSendToParent("SET_WELCOME_MESSAGE_SEEN", this.props.messageId);
+ }
+
+ handleStartBtnClick() {
+ _lib_aboutwelcome_utils__WEBPACK_IMPORTED_MODULE_5__["AboutWelcomeUtils"].handleUserAction(this.props.startButton.action);
+ const ping = {
+ event: "CLICK_BUTTON",
+ event_context: {
+ source: this.props.startButton.message_id,
+ page: "about:welcome"
+ },
+ message_id: this.props.messageId,
+ id: "ABOUT_WELCOME"
+ };
+ window.AWSendEventTelemetry(ping);
+ }
+
+ render() {
+ const {
+ props
+ } = this;
+
+ if (props.template === "simplified") {
+ return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_components_SimpleAboutWelcome__WEBPACK_IMPORTED_MODULE_3__["SimpleAboutWelcome"], {
+ metricsFlowUri: this.state.metricsFlowUri,
+ message_id: props.messageId,
+ utm_term: props.UTMTerm,
+ title: props.title,
+ subtitle: props.subtitle,
+ cards: props.cards,
+ startButton: props.startButton,
+ handleStartBtnClick: this.handleStartBtnClick
+ });
+ } else if (props.template === "return_to_amo") {
+ return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_components_ReturnToAMO__WEBPACK_IMPORTED_MODULE_4__["ReturnToAMO"], {
+ message_id: props.messageId,
+ name: props.name,
+ url: props.url,
+ iconURL: props.iconURL
+ });
+ }
+
+ return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_components_MultiStageAboutWelcome__WEBPACK_IMPORTED_MODULE_2__["MultiStageAboutWelcome"], {
+ screens: props.screens,
+ metricsFlowUri: this.state.metricsFlowUri,
+ message_id: props.messageId,
+ utm_term: props.UTMTerm
+ });
+ }
+
+}
+
+AboutWelcome.defaultProps = _lib_aboutwelcome_utils__WEBPACK_IMPORTED_MODULE_5__["DEFAULT_WELCOME_CONTENT"]; // Computes messageId and UTMTerm info used in telemetry
+
+function ComputeTelemetryInfo(welcomeContent, experimentId, branchId) {
+ let messageId = welcomeContent.template === "return_to_amo" ? "RTAMO_DEFAULT_WELCOME" : "DEFAULT_ABOUTWELCOME";
+ let UTMTerm = "default";
+
+ if (welcomeContent.id) {
+ messageId = welcomeContent.id.toUpperCase();
+ }
+
+ if (experimentId && branchId) {
+ UTMTerm = `${experimentId}-${branchId}`.toLowerCase();
+ }
+
+ return {
+ messageId,
+ UTMTerm
+ };
+}
+
+async function retrieveRenderContent() {
+ var _aboutWelcomeProps;
+
+ // Check for override content in pref browser.aboutwelcome.overrideContent
+ let aboutWelcomeProps = await window.AWGetWelcomeOverrideContent();
+
+ if ((_aboutWelcomeProps = aboutWelcomeProps) === null || _aboutWelcomeProps === void 0 ? void 0 : _aboutWelcomeProps.template) {
+ let {
+ messageId,
+ UTMTerm
+ } = ComputeTelemetryInfo(aboutWelcomeProps);
+ return {
+ aboutWelcomeProps,
+ messageId,
+ UTMTerm
+ };
+ } // Check for experiment and retrieve content
+
+
+ const {
+ slug,
+ branch
+ } = await window.AWGetExperimentData();
+ aboutWelcomeProps = (branch === null || branch === void 0 ? void 0 : branch.feature) ? branch.feature.value : {}; // Check if there is any attribution data, this could take a while to await in series
+ // especially when there is an add-on that requires remote lookup
+ // Moving RTAMO as part of another screen of multistage is one option to fix the delay
+ // as it will allow the initial page to be fast while we fetch attribution data in parallel for a later screen.
+
+ const attribution = await window.AWGetAttributionData();
+
+ if (attribution === null || attribution === void 0 ? void 0 : attribution.template) {
+ var _aboutWelcomeProps2;
+
+ aboutWelcomeProps = { ...aboutWelcomeProps,
+ // If part of an experiment, render experiment template
+ template: ((_aboutWelcomeProps2 = aboutWelcomeProps) === null || _aboutWelcomeProps2 === void 0 ? void 0 : _aboutWelcomeProps2.template) ? aboutWelcomeProps.template : attribution.template,
+ ...attribution.extraProps
+ };
+ }
+
+ let {
+ messageId,
+ UTMTerm
+ } = ComputeTelemetryInfo(aboutWelcomeProps, slug, branch && branch.slug);
+ return {
+ aboutWelcomeProps,
+ messageId,
+ UTMTerm
+ };
+}
+
+async function mount() {
+ let {
+ aboutWelcomeProps,
+ messageId,
+ UTMTerm
+ } = await retrieveRenderContent();
+ react_dom__WEBPACK_IMPORTED_MODULE_1___default.a.render(react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(AboutWelcome, _extends({
+ messageId: messageId,
+ UTMTerm: UTMTerm
+ }, aboutWelcomeProps)), document.getElementById("root"));
+}
+
+performance.mark("mount");
+mount();
+
+/***/ }),
+/* 1 */
+/***/ (function(module, exports) {
+
+module.exports = React;
+
+/***/ }),
+/* 2 */
+/***/ (function(module, exports) {
+
+module.exports = ReactDOM;
+
+/***/ }),
+/* 3 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MultiStageAboutWelcome", function() { return MultiStageAboutWelcome; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WelcomeScreen", function() { return WelcomeScreen; });
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
+/* harmony import */ var _MSLocalized__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4);
+/* harmony import */ var _Zap__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(5);
+/* harmony import */ var _lib_aboutwelcome_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(6);
+/* harmony import */ var _asrouter_templates_FirstRun_addUtmParams__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(7);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+
+
+
+const MultiStageAboutWelcome = props => {
+ const [index, setScreenIndex] = Object(react__WEBPACK_IMPORTED_MODULE_0__["useState"])(0);
+ Object(react__WEBPACK_IMPORTED_MODULE_0__["useEffect"])(() => {
+ // Send impression ping when respective screen first renders
+ props.screens.forEach(screen => {
+ if (index === screen.order) {
+ _lib_aboutwelcome_utils__WEBPACK_IMPORTED_MODULE_3__["AboutWelcomeUtils"].sendImpressionTelemetry(`${props.message_id}_${screen.id}`);
+ }
+ }); // Remember that a new screen has loaded for browser navigation
+
+ if (index > window.history.state) {
+ window.history.pushState(index, "");
+ }
+ }, [index]);
+ Object(react__WEBPACK_IMPORTED_MODULE_0__["useEffect"])(() => {
+ // Switch to the screen tracked in state (null for initial state)
+ const handler = ({
+ state
+ }) => setScreenIndex(Number(state)); // Handle page load, e.g., going back to about:welcome from about:home
+
+
+ handler(window.history); // Watch for browser back/forward button navigation events
+
+ window.addEventListener("popstate", handler);
+ return () => window.removeEventListener("popstate", handler);
+ }, []);
+ const [flowParams, setFlowParams] = Object(react__WEBPACK_IMPORTED_MODULE_0__["useState"])(null);
+ const {
+ metricsFlowUri
+ } = props;
+ Object(react__WEBPACK_IMPORTED_MODULE_0__["useEffect"])(() => {
+ (async () => {
+ if (metricsFlowUri) {
+ setFlowParams((await _lib_aboutwelcome_utils__WEBPACK_IMPORTED_MODULE_3__["AboutWelcomeUtils"].fetchFlowParams(metricsFlowUri)));
+ }
+ })();
+ }, [metricsFlowUri]); // Transition to next screen, opening about:home on last screen button CTA
+
+ const handleTransition = index < props.screens.length - 1 ? () => setScreenIndex(prevState => prevState + 1) : () => _lib_aboutwelcome_utils__WEBPACK_IMPORTED_MODULE_3__["AboutWelcomeUtils"].handleUserAction({
+ type: "OPEN_ABOUT_PAGE",
+ data: {
+ args: "home",
+ where: "current"
+ }
+ }); // Update top sites with default sites by region when region is available
+
+ const [region, setRegion] = Object(react__WEBPACK_IMPORTED_MODULE_0__["useState"])(null);
+ Object(react__WEBPACK_IMPORTED_MODULE_0__["useEffect"])(() => {
+ (async () => {
+ setRegion((await window.AWGetRegion()));
+ })();
+ }, []); // Get the active theme so the rendering code can make it selected
+ // by default.
+
+ const [activeTheme, setActiveTheme] = Object(react__WEBPACK_IMPORTED_MODULE_0__["useState"])(null);
+ const [initialTheme, setInitialTheme] = Object(react__WEBPACK_IMPORTED_MODULE_0__["useState"])(null);
+ Object(react__WEBPACK_IMPORTED_MODULE_0__["useEffect"])(() => {
+ (async () => {
+ let theme = await window.AWGetSelectedTheme();
+ setInitialTheme(theme);
+ setActiveTheme(theme);
+ })();
+ }, []);
+ const useImportable = props.message_id.includes("IMPORTABLE"); // Track whether we have already sent the importable sites impression telemetry
+
+ const importTelemetrySent = Object(react__WEBPACK_IMPORTED_MODULE_0__["useRef"])(false);
+ const [topSites, setTopSites] = Object(react__WEBPACK_IMPORTED_MODULE_0__["useState"])([]);
+ Object(react__WEBPACK_IMPORTED_MODULE_0__["useEffect"])(() => {
+ (async () => {
+ let DEFAULT_SITES = await window.AWGetDefaultSites();
+ const importable = JSON.parse((await window.AWGetImportableSites()));
+ const showImportable = useImportable && importable.length >= 5;
+
+ if (!importTelemetrySent.current) {
+ _lib_aboutwelcome_utils__WEBPACK_IMPORTED_MODULE_3__["AboutWelcomeUtils"].sendImpressionTelemetry(`${props.message_id}_SITES`, {
+ display: showImportable ? "importable" : "static",
+ importable: importable.length
+ });
+ importTelemetrySent.current = true;
+ }
+
+ setTopSites(showImportable ? {
+ data: importable,
+ showImportable
+ } : {
+ data: DEFAULT_SITES,
+ showImportable
+ });
+ })();
+ }, [useImportable, region]);
+ return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_0___default.a.Fragment, null, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
+ className: `outer-wrapper onboardingContainer`
+ }, props.screens.map(screen => {
+ return index === screen.order ? react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(WelcomeScreen, {
+ key: screen.id,
+ id: screen.id,
+ totalNumberOfScreens: props.screens.length,
+ order: screen.order,
+ content: screen.content,
+ navigate: handleTransition,
+ topSites: topSites,
+ messageId: `${props.message_id}_${screen.id}`,
+ UTMTerm: props.utm_term,
+ flowParams: flowParams,
+ activeTheme: activeTheme,
+ initialTheme: initialTheme,
+ setActiveTheme: setActiveTheme
+ }) : null;
+ })));
+};
+class WelcomeScreen extends react__WEBPACK_IMPORTED_MODULE_0___default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.handleAction = this.handleAction.bind(this);
+ }
+
+ handleOpenURL(action, flowParams, UTMTerm) {
+ let {
+ type,
+ data
+ } = action;
+
+ if (type === "SHOW_FIREFOX_ACCOUNTS") {
+ let params = { ..._asrouter_templates_FirstRun_addUtmParams__WEBPACK_IMPORTED_MODULE_4__["BASE_PARAMS"],
+ utm_term: `aboutwelcome-${UTMTerm}-screen`
+ };
+
+ if (action.addFlowParams && flowParams) {
+ params = { ...params,
+ ...flowParams
+ };
+ }
+
+ data = { ...data,
+ extraParams: params
+ };
+ } else if (type === "OPEN_URL") {
+ let url = new URL(data.args);
+ Object(_asrouter_templates_FirstRun_addUtmParams__WEBPACK_IMPORTED_MODULE_4__["addUtmParams"])(url, `aboutwelcome-${UTMTerm}-screen`);
+
+ if (action.addFlowParams && flowParams) {
+ url.searchParams.append("device_id", flowParams.deviceId);
+ url.searchParams.append("flow_id", flowParams.flowId);
+ url.searchParams.append("flow_begin_time", flowParams.flowBeginTime);
+ }
+
+ data = { ...data,
+ args: url.toString()
+ };
+ }
+
+ _lib_aboutwelcome_utils__WEBPACK_IMPORTED_MODULE_3__["AboutWelcomeUtils"].handleUserAction({
+ type,
+ data
+ });
+ }
+
+ async handleAction(event) {
+ let {
+ props
+ } = this;
+ let targetContent = props.content[event.currentTarget.value] || props.content.tiles;
+
+ if (!(targetContent && targetContent.action)) {
+ return;
+ } // Send telemetry before waiting on actions
+
+
+ _lib_aboutwelcome_utils__WEBPACK_IMPORTED_MODULE_3__["AboutWelcomeUtils"].sendActionTelemetry(props.messageId, event.currentTarget.value);
+ let {
+ action
+ } = targetContent;
+
+ if (["OPEN_URL", "SHOW_FIREFOX_ACCOUNTS"].includes(action.type)) {
+ this.handleOpenURL(action, props.flowParams, props.UTMTerm);
+ } else if (action.type) {
+ _lib_aboutwelcome_utils__WEBPACK_IMPORTED_MODULE_3__["AboutWelcomeUtils"].handleUserAction(action); // Wait until migration closes to complete the action
+
+ if (action.type === "SHOW_MIGRATION_WIZARD") {
+ await window.AWWaitForMigrationClose();
+ _lib_aboutwelcome_utils__WEBPACK_IMPORTED_MODULE_3__["AboutWelcomeUtils"].sendActionTelemetry(props.messageId, "migrate_close");
+ }
+ } // A special tiles.action.theme value indicates we should use the event's value vs provided value.
+
+
+ if (action.theme) {
+ let themeToUse = action.theme === "<event>" ? event.currentTarget.value : this.props.initialTheme || action.theme;
+ this.props.setActiveTheme(themeToUse);
+ window.AWSelectTheme(themeToUse);
+ }
+
+ if (action.navigate) {
+ props.navigate();
+ }
+ }
+
+ renderSecondaryCTA(className) {
+ return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
+ className: className ? `secondary-cta ${className}` : `secondary-cta`
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_1__["Localized"], {
+ text: this.props.content.secondary_button.text
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", null)), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_1__["Localized"], {
+ text: this.props.content.secondary_button.label
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("button", {
+ className: "secondary",
+ value: "secondary_button",
+ onClick: this.handleAction
+ })));
+ }
+
+ renderTiles() {
+ switch (this.props.content.tiles.type) {
+ case "topsites":
+ return this.props.topSites && this.props.topSites.data ? react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
+ className: `tiles-container ${this.props.content.tiles.info ? "info" : ""}`
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
+ className: "tiles-topsites-section",
+ name: "topsites-section",
+ id: "topsites-section",
+ "aria-labelledby": "helptext",
+ role: "region"
+ }, this.props.topSites.data.slice(0, 5).map(({
+ icon,
+ label,
+ title
+ }) => react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
+ className: "site",
+ key: icon + label,
+ "aria-label": title ? title : label,
+ role: "img"
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
+ className: "icon",
+ style: icon ? {
+ backgroundColor: "transparent",
+ backgroundImage: `url(${icon})`
+ } : {}
+ }, icon ? "" : label && label[0].toUpperCase()), this.props.content.tiles.showTitles && react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
+ className: "host"
+ }, title || label))))) : null;
+
+ case "theme":
+ return this.props.content.tiles.data ? react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
+ className: "tiles-theme-container"
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", null, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("fieldset", {
+ className: "tiles-theme-section"
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_1__["Localized"], {
+ text: this.props.content.subtitle
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("legend", {
+ className: "sr-only"
+ })), this.props.content.tiles.data.map(({
+ theme,
+ label,
+ tooltip,
+ description
+ }) => react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_1__["Localized"], {
+ key: theme + label,
+ text: typeof tooltip === "object" ? tooltip : {}
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("label", {
+ className: `theme${theme === this.props.activeTheme ? " selected" : ""}`,
+ title: theme + label
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_1__["Localized"], {
+ text: typeof description === "object" ? description : {}
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("input", {
+ type: "radio",
+ value: theme,
+ name: "theme",
+ checked: theme === this.props.activeTheme,
+ className: "sr-only input",
+ onClick: this.handleAction,
+ "data-l10n-attrs": "aria-description"
+ })), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
+ className: `icon ${theme}`
+ }), label && react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_1__["Localized"], {
+ text: label
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
+ className: "text"
+ })))))))) : null;
+
+ case "video":
+ return this.props.content.tiles.source ? react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
+ className: `tiles-media-section ${this.props.content.tiles.media_type}`
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
+ className: "fade"
+ }), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("video", {
+ className: "media",
+ autoPlay: "true",
+ loop: "true",
+ muted: "true",
+ src: _lib_aboutwelcome_utils__WEBPACK_IMPORTED_MODULE_3__["AboutWelcomeUtils"].hasDarkMode() ? this.props.content.tiles.source.dark : this.props.content.tiles.source.default
+ })) : null;
+
+ case "image":
+ return this.props.content.tiles.source ? react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
+ className: `${this.props.content.tiles.media_type}`
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("img", {
+ src: _lib_aboutwelcome_utils__WEBPACK_IMPORTED_MODULE_3__["AboutWelcomeUtils"].hasDarkMode() && this.props.content.tiles.source.dark ? this.props.content.tiles.source.dark : this.props.content.tiles.source.default,
+ role: "presentation",
+ alt: ""
+ })) : null;
+ }
+
+ return null;
+ }
+
+ renderStepsIndicator() {
+ let steps = [];
+
+ for (let i = 0; i < this.props.totalNumberOfScreens; i++) {
+ let className = i === this.props.order ? "current" : "";
+ steps.push(react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
+ key: i,
+ className: `indicator ${className}`
+ }));
+ }
+
+ return steps;
+ }
+
+ renderHelpText() {
+ return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_1__["Localized"], {
+ text: this.props.content.help_text.text
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("p", {
+ id: "helptext",
+ className: `helptext ${this.props.content.help_text.position}`
+ }));
+ }
+
+ render() {
+ const {
+ content,
+ topSites
+ } = this.props;
+ const hasSecondaryTopCTA = content.secondary_button && content.secondary_button.position === "top";
+ const showImportableSitesDisclaimer = content.tiles && content.tiles.type === "topsites" && topSites && topSites.showImportable;
+ return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("main", {
+ className: `screen ${this.props.id}`
+ }, hasSecondaryTopCTA ? this.renderSecondaryCTA("top") : null, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
+ className: `brand-logo ${hasSecondaryTopCTA ? "cta-top" : ""}`
+ }), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
+ className: "welcome-text"
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_Zap__WEBPACK_IMPORTED_MODULE_2__["Zap"], {
+ hasZap: content.zap,
+ text: content.title
+ }), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_1__["Localized"], {
+ text: content.subtitle
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("h2", null))), content.tiles ? this.renderTiles() : null, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", null, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_1__["Localized"], {
+ text: content.primary_button ? content.primary_button.label : null
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("button", {
+ className: "primary",
+ value: "primary_button",
+ onClick: this.handleAction
+ }))), content.secondary_button && content.secondary_button.position !== "top" ? this.renderSecondaryCTA() : null, content.help_text && content.help_text.position === "default" ? this.renderHelpText() : null, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("nav", {
+ className: content.help_text && content.help_text.position === "footer" || showImportableSitesDisclaimer ? "steps has-helptext" : "steps",
+ "data-l10n-id": "onboarding-welcome-steps-indicator",
+ "data-l10n-args": `{"current": ${parseInt(this.props.order, 10) + 1}, "total": ${this.props.totalNumberOfScreens}}`
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("br", null), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("p", null), this.renderStepsIndicator()), content.help_text && content.help_text.position === "footer" || showImportableSitesDisclaimer ? this.renderHelpText() : null);
+ }
+
+}
+
+/***/ }),
+/* 4 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Localized", function() { return Localized; });
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+const MS_STRING_PROP = "string_id";
+/**
+ * Based on the .text prop, localizes an inner element if a string_id
+ * is provided, OR renders plain text, OR hides it if nothing is provided.
+ *
+ * Examples:
+ *
+ * Localized text
+ * ftl:
+ * title = Welcome
+ * jsx:
+ * <Localized text={{string_id: "title"}}><h1 /></Localized>
+ * output:
+ * <h1 data-l10n-id="title">Welcome</h1>
+ *
+ * Unlocalized text
+ * jsx:
+ * <Localized text="Welcome"><h1 /></Localized>
+ * output:
+ * <h1>Welcome</h1>
+ */
+
+const Localized = ({
+ text,
+ children
+}) => {
+ if (!text) {
+ return null;
+ }
+
+ let props = children ? children.props : {};
+ let textNode;
+
+ if (typeof text === "object" && text[MS_STRING_PROP]) {
+ props = { ...props
+ };
+ props["data-l10n-id"] = text[MS_STRING_PROP];
+ } else if (typeof text === "string") {
+ textNode = text;
+ }
+
+ if (!children) {
+ return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", props, textNode);
+ } else if (textNode) {
+ return react__WEBPACK_IMPORTED_MODULE_0___default.a.cloneElement(children, props, textNode);
+ }
+
+ return react__WEBPACK_IMPORTED_MODULE_0___default.a.cloneElement(children, props);
+};
+
+/***/ }),
+/* 5 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Zap", function() { return Zap; });
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
+/* harmony import */ var _MSLocalized__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+const MS_STRING_PROP = "string_id";
+const ZAP_SIZE_THRESHOLD = 160;
+
+function calculateZapLength() {
+ let span = document.querySelector(".zap");
+
+ if (!span) {
+ return;
+ }
+
+ let rect = span.getBoundingClientRect();
+
+ if (rect && rect.width > ZAP_SIZE_THRESHOLD) {
+ span.classList.add("long");
+ } else {
+ span.classList.add("short");
+ }
+}
+
+const Zap = props => {
+ Object(react__WEBPACK_IMPORTED_MODULE_0__["useEffect"])(() => {
+ requestAnimationFrame(() => calculateZapLength());
+ });
+
+ if (!props.text) {
+ return null;
+ }
+
+ if (props.hasZap) {
+ if (typeof props.text === "object" && props.text[MS_STRING_PROP]) {
+ return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_1__["Localized"], {
+ text: props.text
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("h1", {
+ className: "welcomeZap"
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", {
+ "data-l10n-name": "zap",
+ className: "zap"
+ })));
+ } else if (typeof props.text === "string") {
+ // Parse string to zap style last word of the props.text
+ let titleArray = props.text.split(" ");
+ let lastWord = `${titleArray.pop()}`;
+ return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("h1", {
+ className: "welcomeZap"
+ }, titleArray.join(" ").concat(" "), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", {
+ className: "zap"
+ }, lastWord));
+ }
+ } else {
+ return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_1__["Localized"], {
+ text: props.text
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("h1", null));
+ }
+
+ return null;
+};
+
+/***/ }),
+/* 6 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AboutWelcomeUtils", function() { return AboutWelcomeUtils; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DEFAULT_RTAMO_CONTENT", function() { return DEFAULT_RTAMO_CONTENT; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DEFAULT_WELCOME_CONTENT", function() { return DEFAULT_WELCOME_CONTENT; });
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+const AboutWelcomeUtils = {
+ handleUserAction(action) {
+ window.AWSendToParent("SPECIAL_ACTION", action);
+ },
+
+ sendImpressionTelemetry(messageId, context) {
+ window.AWSendEventTelemetry({
+ event: "IMPRESSION",
+ event_context: context,
+ message_id: messageId
+ });
+ },
+
+ sendActionTelemetry(messageId, elementId) {
+ const ping = {
+ event: "CLICK_BUTTON",
+ event_context: {
+ source: elementId,
+ page: "about:welcome"
+ },
+ message_id: messageId
+ };
+ window.AWSendEventTelemetry(ping);
+ },
+
+ async fetchFlowParams(metricsFlowUri) {
+ let flowParams;
+
+ try {
+ const response = await fetch(metricsFlowUri, {
+ credentials: "omit"
+ });
+
+ if (response.status === 200) {
+ const {
+ deviceId,
+ flowId,
+ flowBeginTime
+ } = await response.json();
+ flowParams = {
+ deviceId,
+ flowId,
+ flowBeginTime
+ };
+ } else {
+ console.error("Non-200 response", response); // eslint-disable-line no-console
+ }
+ } catch (e) {
+ flowParams = null;
+ }
+
+ return flowParams;
+ },
+
+ sendEvent(type, detail) {
+ document.dispatchEvent(new CustomEvent(`AWPage:${type}`, {
+ bubbles: true,
+ detail
+ }));
+ },
+
+ hasDarkMode() {
+ return document.body.hasAttribute("lwt-newtab-brighttext");
+ }
+
+};
+const DEFAULT_RTAMO_CONTENT = {
+ template: "return_to_amo",
+ content: {
+ header: {
+ string_id: "onboarding-welcome-header"
+ },
+ subtitle: {
+ string_id: "return-to-amo-subtitle"
+ },
+ text: {
+ string_id: "return-to-amo-addon-title"
+ },
+ primary_button: {
+ label: {
+ string_id: "return-to-amo-add-extension-label"
+ },
+ action: {
+ type: "INSTALL_ADDON_FROM_URL",
+ data: {
+ url: null,
+ telemetrySource: "rtamo"
+ }
+ }
+ },
+ startButton: {
+ label: {
+ string_id: "onboarding-not-now-button-label"
+ },
+ message_id: "RTAMO_START_BROWSING_BUTTON",
+ action: {
+ type: "OPEN_AWESOME_BAR"
+ }
+ }
+ }
+};
+const DEFAULT_WELCOME_CONTENT = {
+ template: "multistage",
+ screens: [{
+ id: "AW_GET_STARTED",
+ order: 0,
+ content: {
+ zap: true,
+ title: {
+ string_id: "onboarding-multistage-welcome-header"
+ },
+ subtitle: {
+ string_id: "onboarding-multistage-welcome-subtitle"
+ },
+ primary_button: {
+ label: {
+ string_id: "onboarding-multistage-welcome-primary-button-label"
+ },
+ action: {
+ navigate: true
+ }
+ },
+ secondary_button: {
+ text: {
+ string_id: "onboarding-multistage-welcome-secondary-button-text"
+ },
+ label: {
+ string_id: "onboarding-multistage-welcome-secondary-button-label"
+ },
+ position: "top",
+ action: {
+ type: "SHOW_FIREFOX_ACCOUNTS",
+ addFlowParams: true,
+ data: {
+ entrypoint: "activity-stream-firstrun"
+ }
+ }
+ }
+ }
+ }, {
+ id: "AW_IMPORT_SETTINGS",
+ order: 1,
+ content: {
+ zap: true,
+ help_text: {
+ text: {
+ string_id: "onboarding-import-sites-disclaimer"
+ }
+ },
+ title: {
+ string_id: "onboarding-multistage-import-header"
+ },
+ subtitle: {
+ string_id: "onboarding-multistage-import-subtitle"
+ },
+ tiles: {
+ type: "topsites",
+ showTitles: true
+ },
+ primary_button: {
+ label: {
+ string_id: "onboarding-multistage-import-primary-button-label"
+ },
+ action: {
+ type: "SHOW_MIGRATION_WIZARD",
+ navigate: true
+ }
+ },
+ secondary_button: {
+ label: {
+ string_id: "onboarding-multistage-import-secondary-button-label"
+ },
+ action: {
+ navigate: true
+ }
+ }
+ }
+ }, {
+ id: "AW_CHOOSE_THEME",
+ order: 2,
+ content: {
+ zap: true,
+ title: {
+ string_id: "onboarding-multistage-theme-header"
+ },
+ subtitle: {
+ string_id: "onboarding-multistage-theme-subtitle"
+ },
+ tiles: {
+ type: "theme",
+ action: {
+ theme: "<event>"
+ },
+ data: [{
+ theme: "automatic",
+ label: {
+ string_id: "onboarding-multistage-theme-label-automatic"
+ },
+ tooltip: {
+ string_id: "onboarding-multistage-theme-tooltip-automatic-2"
+ },
+ description: {
+ string_id: "onboarding-multistage-theme-description-automatic-2"
+ }
+ }, {
+ theme: "light",
+ label: {
+ string_id: "onboarding-multistage-theme-label-light"
+ },
+ tooltip: {
+ string_id: "onboarding-multistage-theme-tooltip-light-2"
+ },
+ description: {
+ string_id: "onboarding-multistage-theme-description-light"
+ }
+ }, {
+ theme: "dark",
+ label: {
+ string_id: "onboarding-multistage-theme-label-dark"
+ },
+ tooltip: {
+ string_id: "onboarding-multistage-theme-tooltip-dark-2"
+ },
+ description: {
+ string_id: "onboarding-multistage-theme-description-dark"
+ }
+ }, {
+ theme: "alpenglow",
+ label: {
+ string_id: "onboarding-multistage-theme-label-alpenglow"
+ },
+ tooltip: {
+ string_id: "onboarding-multistage-theme-tooltip-alpenglow-2"
+ },
+ description: {
+ string_id: "onboarding-multistage-theme-description-alpenglow"
+ }
+ }]
+ },
+ primary_button: {
+ label: {
+ string_id: "onboarding-multistage-theme-primary-button-label"
+ },
+ action: {
+ navigate: true
+ }
+ },
+ secondary_button: {
+ label: {
+ string_id: "onboarding-multistage-theme-secondary-button-label"
+ },
+ action: {
+ theme: "automatic",
+ navigate: true
+ }
+ }
+ }
+ }]
+};
+
+/***/ }),
+/* 7 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BASE_PARAMS", function() { return BASE_PARAMS; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addUtmParams", function() { return addUtmParams; });
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/**
+ * BASE_PARAMS keys/values can be modified from outside this file
+ */
+const BASE_PARAMS = {
+ utm_source: "activity-stream",
+ utm_campaign: "firstrun",
+ utm_medium: "referral"
+};
+/**
+ * Takes in a url as a string or URL object and returns a URL object with the
+ * utm_* parameters added to it. If a URL object is passed in, the paraemeters
+ * are added to it (the return value can be ignored in that case as it's the
+ * same object).
+ */
+
+function addUtmParams(url, utmTerm) {
+ let returnUrl = url;
+
+ if (typeof returnUrl === "string") {
+ returnUrl = new URL(url);
+ }
+
+ Object.keys(BASE_PARAMS).forEach(key => {
+ returnUrl.searchParams.append(key, BASE_PARAMS[key]);
+ });
+ returnUrl.searchParams.append("utm_term", utmTerm);
+ return returnUrl;
+}
+
+/***/ }),
+/* 8 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SimpleAboutWelcome", function() { return SimpleAboutWelcome; });
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
+/* harmony import */ var _HeroText__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(9);
+/* harmony import */ var _FxCards__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(10);
+/* harmony import */ var _MSLocalized__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+
+
+class SimpleAboutWelcome extends react__WEBPACK_IMPORTED_MODULE_0___default.a.PureComponent {
+ render() {
+ const {
+ props
+ } = this;
+ return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
+ className: "outer-wrapper welcomeContainer"
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
+ className: "welcomeContainerInner"
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("main", null, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_HeroText__WEBPACK_IMPORTED_MODULE_1__["HeroText"], {
+ title: props.title,
+ subtitle: props.subtitle
+ }), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_FxCards__WEBPACK_IMPORTED_MODULE_2__["FxCards"], {
+ cards: props.cards,
+ metricsFlowUri: this.props.metricsFlowUri,
+ sendTelemetry: window.AWSendEventTelemetry,
+ utm_term: this.props.UTMTerm
+ }), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_3__["Localized"], {
+ text: props.startButton.label
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("button", {
+ className: "start-button",
+ onClick: this.props.handleStartBtnClick
+ })))));
+ }
+
+}
+
+/***/ }),
+/* 9 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HeroText", function() { return HeroText; });
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
+/* harmony import */ var _MSLocalized__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+const HeroText = props => {
+ return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_0___default.a.Fragment, null, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_1__["Localized"], {
+ text: props.title
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("h1", {
+ className: "welcome-title"
+ })), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_1__["Localized"], {
+ text: props.subtitle
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("h2", {
+ className: "welcome-subtitle"
+ })));
+};
+
+/***/ }),
+/* 10 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FxCards", function() { return FxCards; });
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
+/* harmony import */ var _asrouter_templates_FirstRun_addUtmParams__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(7);
+/* harmony import */ var _asrouter_templates_OnboardingMessage_OnboardingMessage__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(11);
+/* harmony import */ var _lib_aboutwelcome_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(6);
+function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
+
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+
+
+class FxCards extends react__WEBPACK_IMPORTED_MODULE_0___default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.state = {
+ flowParams: null
+ };
+ this.fetchFxAFlowParams = this.fetchFxAFlowParams.bind(this);
+ this.onCardAction = this.onCardAction.bind(this);
+ }
+
+ componentDidUpdate() {
+ this.fetchFxAFlowParams();
+ }
+
+ componentDidMount() {
+ this.fetchFxAFlowParams();
+ }
+
+ async fetchFxAFlowParams() {
+ if (this.state.flowParams || !this.props.metricsFlowUri) {
+ return;
+ }
+
+ const flowParams = await _lib_aboutwelcome_utils__WEBPACK_IMPORTED_MODULE_3__["AboutWelcomeUtils"].fetchFlowParams(this.props.metricsFlowUri);
+ this.setState({
+ flowParams
+ });
+ }
+
+ onCardAction(action) {
+ let {
+ type,
+ data
+ } = action;
+ let UTMTerm = `aboutwelcome-${this.props.utm_term}-card`;
+
+ if (action.type === "OPEN_URL") {
+ let url = new URL(action.data.args);
+ Object(_asrouter_templates_FirstRun_addUtmParams__WEBPACK_IMPORTED_MODULE_1__["addUtmParams"])(url, UTMTerm);
+
+ if (action.addFlowParams && this.state.flowParams) {
+ url.searchParams.append("device_id", this.state.flowParams.deviceId);
+ url.searchParams.append("flow_id", this.state.flowParams.flowId);
+ url.searchParams.append("flow_begin_time", this.state.flowParams.flowBeginTime);
+ }
+
+ data = { ...data,
+ args: url.toString()
+ };
+ }
+
+ _lib_aboutwelcome_utils__WEBPACK_IMPORTED_MODULE_3__["AboutWelcomeUtils"].handleUserAction({
+ type,
+ data
+ });
+ }
+
+ render() {
+ const {
+ props
+ } = this;
+ return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_0___default.a.Fragment, null, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
+ className: `welcomeCardGrid show`
+ }, props.cards.map(card => react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_asrouter_templates_OnboardingMessage_OnboardingMessage__WEBPACK_IMPORTED_MODULE_2__["OnboardingCard"], _extends({
+ key: card.id,
+ message: card,
+ className: "welcomeCard",
+ sendUserActionTelemetry: props.sendTelemetry,
+ onAction: this.onCardAction,
+ UISurface: "ABOUT_WELCOME"
+ }, card)))));
+ }
+
+}
+
+/***/ }),
+/* 11 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OnboardingCard", function() { return OnboardingCard; });
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
+/* harmony import */ var _aboutwelcome_components_MSLocalized__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+class OnboardingCard extends react__WEBPACK_IMPORTED_MODULE_0___default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onClick = this.onClick.bind(this);
+ }
+
+ onClick() {
+ const {
+ props
+ } = this;
+ const ping = {
+ event: "CLICK_BUTTON",
+ message_id: props.id,
+ id: props.UISurface
+ };
+ props.sendUserActionTelemetry(ping);
+ props.onAction(props.content.primary_button.action, props.message);
+ }
+
+ render() {
+ const {
+ content
+ } = this.props;
+ const className = this.props.className || "onboardingMessage";
+ return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
+ className: className
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
+ className: `onboardingMessageImage ${content.icon}`
+ }), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
+ className: "onboardingContent"
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", null, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_aboutwelcome_components_MSLocalized__WEBPACK_IMPORTED_MODULE_1__["Localized"], {
+ text: content.title
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("h2", {
+ className: "onboardingTitle"
+ })), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_aboutwelcome_components_MSLocalized__WEBPACK_IMPORTED_MODULE_1__["Localized"], {
+ text: content.text
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("p", {
+ className: "onboardingText"
+ }))), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", {
+ className: "onboardingButtonContainer"
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_aboutwelcome_components_MSLocalized__WEBPACK_IMPORTED_MODULE_1__["Localized"], {
+ text: content.primary_button.label
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("button", {
+ className: "button onboardingButton",
+ onClick: this.onClick
+ })))));
+ }
+
+}
+
+/***/ }),
+/* 12 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReturnToAMO", function() { return ReturnToAMO; });
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
+/* harmony import */ var _lib_aboutwelcome_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6);
+/* harmony import */ var _MSLocalized__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(4);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+
+class ReturnToAMO extends react__WEBPACK_IMPORTED_MODULE_0___default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onClickAddExtension = this.onClickAddExtension.bind(this);
+ this.handleStartBtnClick = this.handleStartBtnClick.bind(this);
+ }
+
+ onClickAddExtension() {
+ var _content$primary_butt, _content$primary_butt2;
+
+ const {
+ content,
+ message_id,
+ url
+ } = this.props;
+
+ if (!(content === null || content === void 0 ? void 0 : (_content$primary_butt = content.primary_button) === null || _content$primary_butt === void 0 ? void 0 : (_content$primary_butt2 = _content$primary_butt.action) === null || _content$primary_butt2 === void 0 ? void 0 : _content$primary_butt2.data)) {
+ return;
+ } // Set add-on url in action.data.url property from JSON
+
+
+ content.primary_button.action.data.url = url;
+ _lib_aboutwelcome_utils__WEBPACK_IMPORTED_MODULE_1__["AboutWelcomeUtils"].handleUserAction(content.primary_button.action);
+ const ping = {
+ event: "INSTALL",
+ event_context: {
+ source: "ADD_EXTENSION_BUTTON",
+ page: "about:welcome"
+ },
+ message_id
+ };
+ window.AWSendEventTelemetry(ping);
+ }
+
+ handleStartBtnClick() {
+ const {
+ content,
+ message_id
+ } = this.props;
+ _lib_aboutwelcome_utils__WEBPACK_IMPORTED_MODULE_1__["AboutWelcomeUtils"].handleUserAction(content.startButton.action);
+ const ping = {
+ event: "CLICK_BUTTON",
+ event_context: {
+ source: content.startButton.message_id,
+ page: "about:welcome"
+ },
+ message_id
+ };
+ window.AWSendEventTelemetry(ping);
+ }
+
+ render() {
+ const {
+ content
+ } = this.props;
+
+ if (!content) {
+ return null;
+ } // For experiments, when needed below rendered UI allows settings hard coded strings
+ // directly inside JSON except for ReturnToAMOText which picks add-on name and icon from fluent string
+
+
+ return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
+ className: "outer-wrapper onboardingContainer"
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("main", {
+ className: "screen"
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
+ className: "brand-logo"
+ }), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
+ className: "welcome-text"
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_2__["Localized"], {
+ text: content.subtitle
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("h1", null)), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_2__["Localized"], {
+ text: content.text
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("h2", {
+ "data-l10n-args": this.props.name ? JSON.stringify({
+ "addon-name": this.props.name
+ }) : null
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("img", {
+ "data-l10n-name": "icon",
+ src: this.props.iconURL,
+ role: "presentation",
+ alt: ""
+ }))), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_2__["Localized"], {
+ text: content.primary_button.label
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("button", {
+ onClick: this.onClickAddExtension,
+ className: "primary"
+ })), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_MSLocalized__WEBPACK_IMPORTED_MODULE_2__["Localized"], {
+ text: content.startButton.label
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("button", {
+ onClick: this.handleStartBtnClick,
+ className: "secondary"
+ })))));
+ }
+
+}
+ReturnToAMO.defaultProps = _lib_aboutwelcome_utils__WEBPACK_IMPORTED_MODULE_1__["DEFAULT_RTAMO_CONTENT"];
+
+/***/ })
+/******/ ]); \ No newline at end of file
diff --git a/browser/components/newtab/aboutwelcome/content/aboutwelcome.css b/browser/components/newtab/aboutwelcome/content/aboutwelcome.css
new file mode 100644
index 0000000000..5cb0e4a79f
--- /dev/null
+++ b/browser/components/newtab/aboutwelcome/content/aboutwelcome.css
@@ -0,0 +1,538 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+html {
+ box-sizing: border-box; }
+
+*,
+*::before,
+*::after {
+ box-sizing: inherit; }
+
+*::-moz-focus-inner {
+ border: 0; }
+
+body {
+ margin: 0; }
+
+button,
+input {
+ background-color: inherit;
+ color: inherit;
+ font-family: inherit;
+ font-size: inherit; }
+
+[hidden] {
+ display: none !important; }
+
+.onboardingMessageImage.addons {
+ background-image: url("chrome://activity-stream/content/data/content/assets/illustration-addons@2x.png"); }
+
+.onboardingMessageImage.privatebrowsing {
+ background-image: url("chrome://activity-stream/content/data/content/assets/illustration-privatebrowsing@2x.png"); }
+
+.onboardingMessageImage.screenshots {
+ background-image: url("chrome://activity-stream/content/data/content/assets/illustration-screenshots@2x.png"); }
+
+.onboardingMessageImage.gift {
+ background-image: url("chrome://activity-stream/content/data/content/assets/illustration-gift@2x.png"); }
+
+.onboardingMessageImage.sync {
+ background-image: url("chrome://activity-stream/content/data/content/assets/illustration-sync@2x.png"); }
+
+.onboardingMessageImage.devices {
+ background-image: url("chrome://activity-stream/content/data/content/assets/trailhead/card-illo-devices.svg"); }
+
+.onboardingMessageImage.fbcont {
+ background-image: url("chrome://activity-stream/content/data/content/assets/trailhead/card-illo-fbcont.svg"); }
+
+.onboardingMessageImage.import {
+ background-image: url("chrome://activity-stream/content/data/content/assets/trailhead/card-illo-import.svg"); }
+
+.onboardingMessageImage.ffmonitor {
+ background-image: url("chrome://activity-stream/content/data/content/assets/trailhead/card-illo-ffmonitor.svg"); }
+
+.onboardingMessageImage.ffsend {
+ background-image: url("chrome://activity-stream/content/data/content/assets/trailhead/card-illo-ffsend.svg"); }
+
+.onboardingMessageImage.lockwise {
+ background-image: url("chrome://activity-stream/content/data/content/assets/trailhead/card-illo-lockwise.svg"); }
+
+.onboardingMessageImage.mobile {
+ background-image: url("chrome://activity-stream/content/data/content/assets/trailhead/card-illo-mobile.svg"); }
+
+.onboardingMessageImage.pledge {
+ background-image: url("chrome://activity-stream/content/data/content/assets/trailhead/card-illo-pledge.svg"); }
+
+.onboardingMessageImage.pocket {
+ background-image: url("chrome://activity-stream/content/data/content/assets/trailhead/card-illo-pocket.svg"); }
+
+.onboardingMessageImage.private {
+ background-image: url("chrome://activity-stream/content/data/content/assets/trailhead/card-illo-private.svg"); }
+
+.onboardingMessageImage.sendtab {
+ background-image: url("chrome://activity-stream/content/data/content/assets/trailhead/card-illo-sendtab.svg"); }
+
+.onboardingMessageImage.tracking {
+ background-image: url("chrome://activity-stream/content/data/content/assets/trailhead/card-illo-tracking.svg"); }
+
+html {
+ height: 100%; }
+
+body {
+ --grey-subtitle: #4A4A4F;
+ --grey-subtitle-1: #696977;
+ --newtab-background-color: #EDEDF0;
+ --newtab-background-color-1: #F9F9FA;
+ --newtab-text-primary-color: #0C0C0D;
+ --newtab-text-conditional-color: #4A4A4F;
+ --newtab-button-primary-color: #0060DF;
+ --newtab-button-secondary-color: #0060DF;
+ --newtab-card-background-color: #FFF;
+ --newtab-card-shadow: 0 1px 4px 0 rgba(12, 12, 13, 0.4);
+ --tiles-theme-section-border-width: 1px;
+ --welcome-header-text-color: #2B2156;
+ --welcome-header-text-color-1: #20133A;
+ --welcome-card-button-background-color: rgba(12, 12, 13, 0.1);
+ --welcome-card-button-background-hover-color: rgba(12, 12, 13, 0.2);
+ --welcome-card-button-background-active-color: rgba(12, 12, 13, 0.3);
+ --welcome-button-box-shadow-color: #0A84FF;
+ --welcome-button-box-shadow-inset-color: rgba(10, 132, 255, 0.3);
+ --welcome-button-text-color: #FFF;
+ --welcome-button-background-hover-color: #003EAA;
+ --welcome-button-background-active-color: #002275;
+ --about-welcome-media-fade: linear-gradient(transparent, transparent 35%, #F9F9FA, #F9F9FA);
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Ubuntu', 'Helvetica Neue', sans-serif;
+ font-size: 16px;
+ position: relative;
+ /* these two rules fix test failures in
+ "browser_ext_themes_ntp_colors" & "browser_ext_themes_ntp_colors_perwindow".*/
+ color: var(--newtab-text-primary-color);
+ background-color: var(--newtab-background-color); }
+ body[lwt-newtab-brighttext] {
+ --newtab-background-color: #2A2A2E;
+ --newtab-background-color-1: #1D1133;
+ --newtab-text-primary-color: #F9F9FA;
+ --newtab-text-conditional-color: #F9F9FA;
+ --grey-subtitle-1: #FFF;
+ --newtab-button-primary-color: #0060DF;
+ --newtab-button-secondary-color: #FFF;
+ --newtab-card-background-color: #38383D;
+ --newtab-card-shadow: 0 1px 8px 0 rgba(12, 12, 13, 0.4);
+ --welcome-header-text-color: rgba(255, 255, 255, 0.6);
+ --welcome-header-text-color-1: #7542E5;
+ --welcome-card-button-background-color: rgba(12, 12, 13, 0.3);
+ --welcome-card-button-background-hover-color: rgba(12, 12, 13, 0.5);
+ --welcome-card-button-background-active-color: rgba(12, 12, 13, 0.7);
+ --welcome-button-box-shadow-color: #0A84FF;
+ --about-welcome-media-fade: linear-gradient(transparent, transparent 35%, #1D1133, #1D1133); }
+
+.welcomeCardGrid {
+ margin: 0;
+ margin-top: 32px;
+ display: grid;
+ grid-gap: 32px;
+ transition: opacity 0.4s;
+ transition-delay: 0.1s;
+ grid-auto-rows: 1fr; }
+ @media (min-width: 610px) {
+ .welcomeCardGrid {
+ grid-template-columns: repeat(auto-fit, 224px); } }
+ @media (min-width: 1122px) {
+ .welcomeCardGrid {
+ grid-template-columns: repeat(auto-fit, 309px); } }
+
+.welcomeContainer {
+ text-align: center; }
+ @media (min-width: 610px) {
+ .welcomeContainer {
+ max-height: 1000px; } }
+ .welcomeContainer h1 {
+ font-size: 36px;
+ font-weight: 200;
+ margin: 0 0 40px;
+ color: var(--welcome-header-text-color); }
+ .welcomeContainer .welcome-title {
+ margin-bottom: 5px;
+ line-height: 52px; }
+ .welcomeContainer .welcome-subtitle {
+ font-size: 28px;
+ font-weight: 200;
+ margin: 6px 0 0;
+ color: var(--grey-subtitle);
+ line-height: 42px; }
+
+.welcomeContainerInner {
+ margin: auto;
+ padding: 40px 25px; }
+ @media (min-width: 610px) {
+ .welcomeContainerInner {
+ width: 530px; } }
+ @media (min-width: 866px) {
+ .welcomeContainerInner {
+ width: 786px; } }
+ @media (min-width: 1122px) {
+ .welcomeContainerInner {
+ width: 1042px; } }
+
+.welcomeCard {
+ position: relative;
+ background: var(--newtab-card-background-color);
+ border-radius: 4px;
+ box-shadow: var(--newtab-card-shadow);
+ font-size: 13px;
+ padding: 20px 20px 60px; }
+ @media (max-width: 866px) {
+ .welcomeCard {
+ padding: 20px; } }
+ @media (min-width: 1122px) {
+ .welcomeCard {
+ font-size: 15px; } }
+
+.welcomeCard .onboardingTitle {
+ font-weight: normal;
+ color: var(--newtab-text-primary-color);
+ margin: 10px 0 4px;
+ font-size: 15px; }
+ @media (min-width: 1122px) {
+ .welcomeCard .onboardingTitle {
+ font-size: 18px; } }
+
+.welcomeCard .onboardingText {
+ margin: 0 0 60px;
+ color: var(--newtab-text-conditional-color);
+ line-height: 1.5;
+ font-weight: 200; }
+
+.welcomeCard .onboardingButton {
+ color: var(--newtab-text-conditional-color);
+ background: var(--welcome-card-button-background-color);
+ border: 0;
+ border-radius: 4px;
+ margin: 14px;
+ min-width: 70%;
+ padding: 6px 14px;
+ white-space: pre-wrap;
+ cursor: pointer; }
+ .welcomeCard .onboardingButton:focus, .welcomeCard .onboardingButton:hover {
+ box-shadow: none;
+ background: var(--welcome-card-button-background-hover-color); }
+ .welcomeCard .onboardingButton:focus {
+ outline: dotted 1px; }
+ .welcomeCard .onboardingButton:active {
+ background: var(--welcome-card-button-background-active-color); }
+
+.welcomeCard .onboardingButtonContainer {
+ position: absolute;
+ bottom: 16px;
+ left: 0;
+ width: 100%;
+ text-align: center; }
+
+.onboardingMessageImage {
+ height: 112px;
+ width: 180px;
+ background-size: auto 140px;
+ background-position: center center;
+ background-repeat: no-repeat;
+ display: inline-block; }
+ @media (max-width: 866px) {
+ .onboardingMessageImage {
+ height: 75px;
+ min-width: 80px;
+ background-size: 140px; } }
+
+.start-button {
+ border: 0;
+ font-size: 15px;
+ font-family: inherit;
+ font-weight: 200;
+ margin-inline-start: 12px;
+ margin: 30px 0 25px;
+ padding: 8px 16px;
+ white-space: nowrap;
+ background-color: var(--newtab-button-primary-color);
+ color: var(--welcome-button-text-color);
+ cursor: pointer;
+ border-radius: 2px; }
+ .start-button:focus {
+ background: var(--welcome-button-background-hover-color);
+ box-shadow: 0 0 0 1px var(--welcome-button-box-shadow-inset-color) inset, 0 0 0 1px var(--welcome-button-box-shadow-inset-color), 0 0 0 4px var(--welcome-button-box-shadow-color); }
+ .start-button:hover {
+ background: var(--welcome-button-background-hover-color); }
+ .start-button:active {
+ background: var(--welcome-button-background-active-color); }
+
+.onboardingContainer {
+ text-align: center;
+ overflow-x: auto;
+ height: 100vh;
+ background-color: var(--newtab-background-color-1); }
+ .onboardingContainer .screen {
+ display: flex;
+ flex-flow: column nowrap;
+ height: 100%; }
+ .onboardingContainer .brand-logo {
+ background: url("chrome://branding/content/about-logo.svg") top center/112px no-repeat;
+ padding: 112px 0 20px;
+ margin-top: 60px; }
+ .onboardingContainer .brand-logo.cta-top {
+ margin-top: 25px; }
+ .onboardingContainer .welcomeZap span {
+ position: relative;
+ z-index: 1;
+ white-space: nowrap; }
+ .onboardingContainer .welcomeZap .zap::after {
+ display: block;
+ background-repeat: no-repeat;
+ background-size: 100% 100%;
+ content: '';
+ position: absolute;
+ top: calc(100% - 0.15em);
+ width: 100%;
+ height: 0.3em;
+ left: 0;
+ z-index: -1; }
+ .onboardingContainer .welcomeZap .zap.short::after {
+ background-image: url("chrome://activity-stream/content/data/content/assets/short-zap.svg"); }
+ .onboardingContainer .welcomeZap .zap.long::after {
+ background-image: url("chrome://activity-stream/content/data/content/assets/long-zap.svg"); }
+ .onboardingContainer .welcome-text {
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ align-items: center;
+ margin-bottom: 20px; }
+ .onboardingContainer .welcome-text h1,
+ .onboardingContainer .welcome-text h2 {
+ width: 860px; }
+ @media (max-width: 866px) {
+ .onboardingContainer .welcome-text h1,
+ .onboardingContainer .welcome-text h2 {
+ width: 530px; } }
+ @media (max-width: 610px) {
+ .onboardingContainer .welcome-text h1,
+ .onboardingContainer .welcome-text h2 {
+ width: 430px; } }
+ .onboardingContainer .welcome-text h1 {
+ font-size: 48px;
+ line-height: 56px;
+ font-weight: bold;
+ margin: 0 6px;
+ color: var(--welcome-header-text-color-1); }
+ .onboardingContainer .welcome-text h2 {
+ font-size: 18px;
+ font-weight: normal;
+ margin: 10px 6px 0;
+ color: var(--grey-subtitle-1);
+ line-height: 28px;
+ max-width: 750px;
+ letter-spacing: -0.01em; }
+ .onboardingContainer .welcome-text img {
+ margin-inline: 2px;
+ width: 20px;
+ height: 20px; }
+ .onboardingContainer .tiles-theme-container {
+ margin: 10px auto;
+ border: 0; }
+ .onboardingContainer .sr-only {
+ opacity: 0;
+ overflow: hidden;
+ position: absolute; }
+ .onboardingContainer .sr-only.input {
+ height: 1px;
+ width: 1px; }
+ .onboardingContainer .tiles-theme-section {
+ display: grid;
+ grid-gap: 21px;
+ grid-template-columns: repeat(4, auto);
+ /* --newtab-background-color-1 will be invisible, but it's necessary to
+ * keep the content from jumping around when it gets focus-within and
+ * does sprout a dotted border. This way it keeps a 1 pixel wide border
+ * either way so things don't change position.
+ */
+ border: var(--tiles-theme-section-border-width) solid var(--newtab-background-color-1); }
+ @media (max-width: 610px) {
+ .onboardingContainer .tiles-theme-section {
+ grid-template-columns: repeat(2, auto); } }
+ .onboardingContainer .tiles-theme-section:focus-within {
+ border: var(--tiles-theme-section-border-width) dotted; }
+ .onboardingContainer .tiles-theme-section .theme {
+ display: flex;
+ flex-direction: column;
+ padding: 0;
+ width: 180px;
+ height: 145px;
+ color: #000;
+ background-color: #FFF;
+ box-shadow: 0 1px 4px 0 rgba(12, 12, 13, 0.4);
+ border-radius: 4px;
+ cursor: pointer; }
+ .onboardingContainer .tiles-theme-section .theme .icon {
+ background-size: cover;
+ border-top-left-radius: 4px;
+ border-top-right-radius: 4px;
+ height: 91px; }
+ .onboardingContainer .tiles-theme-section .theme .icon:dir(rtl) {
+ transform: scaleX(-1); }
+ .onboardingContainer .tiles-theme-section .theme .icon.light {
+ background-image: url("chrome://mozapps/content/extensions/firefox-compact-light.svg"); }
+ .onboardingContainer .tiles-theme-section .theme .icon.dark {
+ background-image: url("chrome://mozapps/content/extensions/firefox-compact-dark.svg"); }
+ .onboardingContainer .tiles-theme-section .theme .icon.automatic {
+ background-image: url("chrome://mozapps/content/extensions/default-theme.svg"); }
+ .onboardingContainer .tiles-theme-section .theme .icon.alpenglow {
+ background-image: url("chrome://mozapps/content/extensions/firefox-alpenglow.svg"); }
+ .onboardingContainer .tiles-theme-section .theme .text {
+ display: flex;
+ font-size: 14px;
+ font-weight: bold;
+ line-height: 22px;
+ margin-inline-start: 12px;
+ margin-top: 9px; }
+ .onboardingContainer .tiles-theme-section .theme.selected {
+ outline: 4px solid #0090ED;
+ outline-offset: -4px; }
+ .onboardingContainer .tiles-theme-section .theme:focus, .onboardingContainer .tiles-theme-section .theme:active {
+ outline: 4px solid #0090ED;
+ outline-offset: -4px; }
+ .onboardingContainer .tiles-container {
+ margin: 10px auto; }
+ .onboardingContainer .tiles-container.info {
+ padding: 6px 12px 12px; }
+ .onboardingContainer .tiles-container.info:hover, .onboardingContainer .tiles-container.info:focus {
+ background-color: rgba(217, 217, 227, 0.3);
+ border-radius: 4px; }
+ .onboardingContainer .tiles-topsites-section {
+ display: grid;
+ grid-gap: 24px;
+ grid-template-columns: repeat(5, auto); }
+ @media (max-width: 610px) {
+ .onboardingContainer .tiles-topsites-section {
+ grid-template-columns: repeat(3, auto); } }
+ .onboardingContainer .tiles-topsites-section .site {
+ width: 96px; }
+ .onboardingContainer .tiles-topsites-section .icon {
+ background-size: cover;
+ border-radius: 4px;
+ box-shadow: var(--newtab-card-shadow);
+ color: rgba(255, 255, 255, 0.5);
+ font-size: 24px;
+ font-weight: bold;
+ height: 96px;
+ line-height: 96px; }
+ .onboardingContainer .tiles-topsites-section .host {
+ font-size: 12px;
+ line-height: 36px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap; }
+ .onboardingContainer .tiles-topsites-section .site:nth-child(1) .icon {
+ background-color: #7542E5; }
+ .onboardingContainer .tiles-topsites-section .site:nth-child(2) .icon {
+ background-color: #952BB9; }
+ .onboardingContainer .tiles-topsites-section .site:nth-child(3) .icon {
+ background-color: #E31587; }
+ .onboardingContainer .tiles-topsites-section .site:nth-child(4) .icon {
+ background-color: #E25920; }
+ .onboardingContainer .tiles-topsites-section .site:nth-child(5) .icon {
+ background-color: #0250BB; }
+ .onboardingContainer .tiles-media-section {
+ align-self: center;
+ position: relative;
+ margin-top: -12px;
+ margin-bottom: -155px; }
+ .onboardingContainer .tiles-media-section .fade {
+ height: 390px;
+ width: 800px;
+ position: absolute;
+ background-image: var(--about-welcome-media-fade); }
+ .onboardingContainer .tiles-media-section .media {
+ height: 390px;
+ width: 800px; }
+ .onboardingContainer .tiles-media-section.privacy {
+ background: top no-repeat url("chrome://activity-stream/content/data/content/assets/firefox-protections.svg");
+ height: 200px;
+ width: 800px;
+ margin: 0; }
+ .onboardingContainer .tiles-media-section.privacy.media {
+ opacity: 0; }
+ .onboardingContainer button {
+ font-family: inherit;
+ cursor: pointer;
+ border: 0;
+ border-radius: 4px; }
+ .onboardingContainer button.primary {
+ font-size: 16px;
+ margin-inline-start: 12px;
+ margin: 20px 0 0;
+ padding: 12px 20px;
+ white-space: nowrap;
+ background-color: var(--newtab-button-primary-color);
+ color: var(--welcome-button-text-color);
+ fill: currentColor;
+ position: relative;
+ z-index: 1;
+ border: 1px solid transparent; }
+ .onboardingContainer button.primary:focus {
+ background: var(--welcome-button-background-hover-color);
+ box-shadow: 0 0 0 4px var(--welcome-button-box-shadow-color); }
+ .onboardingContainer button.primary:hover {
+ background: var(--welcome-button-background-hover-color); }
+ .onboardingContainer button.primary:active {
+ background: var(--welcome-button-background-active-color); }
+ .onboardingContainer button.secondary {
+ background-color: initial;
+ text-decoration: underline;
+ display: block;
+ padding: 0;
+ width: auto;
+ color: var(--newtab-button-secondary-color);
+ margin-top: 14px; }
+ .onboardingContainer button.secondary:hover, .onboardingContainer button.secondary:active {
+ background-color: initial; }
+ .onboardingContainer .secondary-cta {
+ display: flex;
+ flex-direction: row;
+ justify-content: center;
+ font-size: 14px; }
+ .onboardingContainer .secondary-cta.top {
+ justify-content: end;
+ align-items: end;
+ padding-inline-end: 30px;
+ padding-top: 4px; }
+ @media (max-width: 610px) {
+ .onboardingContainer .secondary-cta.top {
+ justify-content: center; } }
+ .onboardingContainer .secondary-cta span {
+ color: var(--grey-subtitle-1);
+ margin: 0 4px; }
+ .onboardingContainer .helptext {
+ padding: 1em;
+ text-align: center;
+ color: var(--grey-subtitle-1);
+ font-size: 12px;
+ line-height: 18px; }
+ .onboardingContainer .helptext.default {
+ align-self: center;
+ max-width: 40%; }
+ .onboardingContainer .steps {
+ display: flex;
+ flex-direction: row;
+ justify-content: center;
+ margin-top: auto;
+ padding: 32px 0 66px;
+ z-index: 1; }
+ .onboardingContainer .steps.has-helptext {
+ padding-bottom: 0; }
+ .onboardingContainer .steps .indicator {
+ width: 60px;
+ height: 4px;
+ margin-inline-end: 4px;
+ margin-inline-start: 4px;
+ background: var(--grey-subtitle-1);
+ border-radius: 5px;
+ border: 1px solid transparent;
+ opacity: 0.25; }
+ .onboardingContainer .steps .indicator.current {
+ opacity: 1; }
diff --git a/browser/components/newtab/aboutwelcome/content/aboutwelcome.html b/browser/components/newtab/aboutwelcome/content/aboutwelcome.html
new file mode 100644
index 0000000000..39d2b88f97
--- /dev/null
+++ b/browser/components/newtab/aboutwelcome/content/aboutwelcome.html
@@ -0,0 +1,26 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ - You can obtain one at http://mozilla.org/MPL/2.0/. -->
+
+<!doctype html>
+<html>
+ <head>
+ <meta charset="utf-8">
+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; object-src 'none'; script-src resource: chrome:; media-src resource: chrome:; connect-src https:; img-src https: data: blob:; style-src resource: chrome:;">
+ <title data-l10n-id="onboarding-welcome-header"></title>
+ <link rel="icon" type="image/png" href="chrome://branding/content/icon32.png">
+ <link rel="stylesheet" href="chrome://activity-stream/content/aboutwelcome/aboutwelcome.css">
+ <link rel="localization" href="branding/brand.ftl"/>
+ <link rel="localization" href="browser/branding/sync-brand.ftl"/>
+ <link rel="localization" href="browser/branding/brandings.ftl"/>
+ <link rel="localization" href="browser/newtab/onboarding.ftl"/>
+ </head>
+ <body>
+ <div id="root" class="welcome-container" role="presentation">
+ </div>
+ <script src="resource://activity-stream/vendor/react.js"></script>
+ <script src="resource://activity-stream/vendor/react-dom.js"></script>
+ <script src="chrome://browser/content/contentTheme.js"></script>
+ <script src="resource://activity-stream/aboutwelcome/aboutwelcome.bundle.js"></script>
+ </body>
+</html>
diff --git a/browser/components/newtab/aboutwelcome/lib/AboutWelcomeTelemetry.jsm b/browser/components/newtab/aboutwelcome/lib/AboutWelcomeTelemetry.jsm
new file mode 100644
index 0000000000..8c103dd280
--- /dev/null
+++ b/browser/components/newtab/aboutwelcome/lib/AboutWelcomeTelemetry.jsm
@@ -0,0 +1,115 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
+const EXPORTED_SYMBOLS = ["AboutWelcomeTelemetry"];
+const { XPCOMUtils } = ChromeUtils.import(
+ "resource://gre/modules/XPCOMUtils.jsm"
+);
+
+XPCOMUtils.defineLazyModuleGetters(this, {
+ PingCentre: "resource:///modules/PingCentre.jsm",
+ ClientID: "resource://gre/modules/ClientID.jsm",
+ Services: "resource://gre/modules/Services.jsm",
+ TelemetrySession: "resource://gre/modules/TelemetrySession.jsm",
+ AttributionCode: "resource:///modules/AttributionCode.jsm",
+});
+XPCOMUtils.defineLazyServiceGetters(this, {
+ gUUIDGenerator: ["@mozilla.org/uuid-generator;1", "nsIUUIDGenerator"],
+});
+XPCOMUtils.defineLazyPreferenceGetter(
+ this,
+ "structuredIngestionEndpointBase",
+ "browser.newtabpage.activity-stream.telemetry.structuredIngestion.endpoint",
+ ""
+);
+XPCOMUtils.defineLazyGetter(this, "telemetryClientId", () =>
+ ClientID.getClientID()
+);
+XPCOMUtils.defineLazyGetter(
+ this,
+ "browserSessionId",
+ () => TelemetrySession.getMetadata("").sessionId
+);
+const TELEMETRY_TOPIC = "about:welcome";
+const PING_TYPE = "onboarding";
+const PING_VERSION = "1";
+const STRUCTURED_INGESTION_NAMESPACE_MS = "messaging-system";
+
+class AboutWelcomeTelemetry {
+ constructor() {
+ XPCOMUtils.defineLazyPreferenceGetter(
+ this,
+ "telemetryEnabled",
+ "browser.newtabpage.activity-stream.telemetry",
+ false
+ );
+ }
+
+ /**
+ * Lazily initialize PingCentre for Activity Stream to send pings
+ */
+ get pingCentre() {
+ Object.defineProperty(this, "pingCentre", {
+ value: new PingCentre({ topic: TELEMETRY_TOPIC }),
+ });
+ return this.pingCentre;
+ }
+
+ _generateStructuredIngestionEndpoint() {
+ const uuid = gUUIDGenerator.generateUUID().toString();
+ // Structured Ingestion does not support the UUID generated by gUUIDGenerator,
+ // because it contains leading and trailing braces. Need to trim them first.
+ const docID = uuid.slice(1, -1);
+ const extension = `${STRUCTURED_INGESTION_NAMESPACE_MS}/${PING_TYPE}/${PING_VERSION}/${docID}`;
+ return `${structuredIngestionEndpointBase}/${extension}`;
+ }
+
+ /**
+ * Attach browser attribution data to a ping payload.
+ *
+ * It intentionally queries the *cached* attribution data other than calling
+ * `getAttrDataAsync()` in order to minimize the overhead here.
+ * For the same reason, we are not querying the attribution data from
+ * `TelemetryEnvironment.currentEnvironment.settings`.
+ *
+ * In practice, it's very likely that the attribution data is already read
+ * and cached at some point by `AboutWelcomeParent`, so it should be able to
+ * read the cached results for the most if not all of the pings.
+ */
+ _maybeAttachAttribution(ping) {
+ const attribution = AttributionCode.getCachedAttributionData();
+ if (attribution && Object.keys(attribution).length) {
+ ping.attribution = attribution;
+ }
+ return ping;
+ }
+
+ async _createPing(event) {
+ if (event.event_context && typeof event.event_context === "object") {
+ event.event_context = JSON.stringify(event.event_context);
+ }
+ let ping = {
+ ...event,
+ addon_version: Services.appinfo.appBuildID,
+ locale: Services.locale.appLocaleAsBCP47,
+ client_id: await telemetryClientId,
+ browser_session_id: browserSessionId,
+ };
+
+ return this._maybeAttachAttribution(ping);
+ }
+
+ async sendTelemetry(event) {
+ if (!this.telemetryEnabled) {
+ return;
+ }
+
+ const ping = await this._createPing(event);
+ this.pingCentre.sendStructuredIngestionPing(
+ ping,
+ this._generateStructuredIngestionEndpoint()
+ );
+ }
+}
diff --git a/browser/components/newtab/actors/ASRouterChild.jsm b/browser/components/newtab/actors/ASRouterChild.jsm
new file mode 100644
index 0000000000..62b3a756d3
--- /dev/null
+++ b/browser/components/newtab/actors/ASRouterChild.jsm
@@ -0,0 +1,109 @@
+/* vim: set ts=2 sw=2 sts=2 et tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
+const EXPORTED_SYMBOLS = ["ASRouterChild"];
+
+const { MESSAGE_TYPE_LIST, MESSAGE_TYPE_HASH: msg } = ChromeUtils.import(
+ "resource://activity-stream/common/ActorConstants.jsm"
+);
+const VALID_TYPES = new Set(MESSAGE_TYPE_LIST);
+
+class ASRouterChild extends JSWindowActorChild {
+ constructor() {
+ super();
+ this.observers = new Set();
+ }
+
+ didDestroy() {
+ this.observers.clear();
+ }
+
+ handleEvent(event) {
+ switch (event.type) {
+ case "DOMWindowCreated": {
+ const window = this.contentWindow;
+ Cu.exportFunction(this.asRouterMessage.bind(this), window, {
+ defineAs: "ASRouterMessage",
+ });
+ Cu.exportFunction(this.addParentListener.bind(this), window, {
+ defineAs: "ASRouterAddParentListener",
+ });
+ Cu.exportFunction(this.removeParentListener.bind(this), window, {
+ defineAs: "ASRouterRemoveParentListener",
+ });
+ break;
+ }
+ }
+ }
+
+ addParentListener(listener) {
+ this.observers.add(listener);
+ }
+
+ removeParentListener(listener) {
+ this.observers.delete(listener);
+ }
+
+ receiveMessage({ name, data }) {
+ switch (name) {
+ case "EnterSnippetsPreviewMode":
+ case "UpdateAdminState":
+ case "ClearProviders":
+ case "ClearMessages": {
+ this.observers.forEach(listener => {
+ let result = Cu.cloneInto(
+ {
+ type: name,
+ data,
+ },
+ this.contentWindow
+ );
+ listener(result);
+ });
+ break;
+ }
+ }
+ }
+
+ wrapPromise(promise) {
+ return new this.contentWindow.Promise((resolve, reject) =>
+ promise.then(resolve, reject)
+ );
+ }
+
+ sendQuery(aName, aData = null) {
+ return this.wrapPromise(
+ new Promise(resolve => {
+ super.sendQuery(aName, aData).then(result => {
+ resolve(Cu.cloneInto(result, this.contentWindow));
+ });
+ })
+ );
+ }
+
+ asRouterMessage({ type, data }) {
+ if (VALID_TYPES.has(type)) {
+ switch (type) {
+ case msg.DISABLE_PROVIDER:
+ case msg.ENABLE_PROVIDER:
+ case msg.EXPIRE_QUERY_CACHE:
+ case msg.FORCE_WHATSNEW_PANEL:
+ case msg.CLOSE_WHATSNEW_PANEL:
+ case msg.IMPRESSION:
+ case msg.RESET_PROVIDER_PREF:
+ case msg.SET_PROVIDER_USER_PREF:
+ case msg.USER_ACTION: {
+ return this.sendAsyncMessage(type, data);
+ }
+ default: {
+ // these messages need a response
+ return this.sendQuery(type, data);
+ }
+ }
+ }
+ throw new Error(`Unexpected type "${type}"`);
+ }
+}
diff --git a/browser/components/newtab/actors/ASRouterParent.jsm b/browser/components/newtab/actors/ASRouterParent.jsm
new file mode 100644
index 0000000000..358c532b23
--- /dev/null
+++ b/browser/components/newtab/actors/ASRouterParent.jsm
@@ -0,0 +1,115 @@
+/* vim: set ts=2 sw=2 sts=2 et tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+const EXPORTED_SYMBOLS = ["ASRouterParent", "ASRouterTabs"];
+
+const {
+ MESSAGE_TYPE_HASH: { BLOCK_MESSAGE_BY_ID },
+} = ChromeUtils.import("resource://activity-stream/common/ActorConstants.jsm");
+const { ASRouterNewTabHook } = ChromeUtils.import(
+ "resource://activity-stream/lib/ASRouterNewTabHook.jsm"
+);
+const { ASRouterDefaultConfig } = ChromeUtils.import(
+ "resource://activity-stream/lib/ASRouterDefaultConfig.jsm"
+);
+
+class ASRouterTabs {
+ constructor({ asRouterNewTabHook }) {
+ this.actors = new Set();
+ this.destroy = () => {};
+ asRouterNewTabHook.createInstance(ASRouterDefaultConfig());
+ this.loadingMessageHandler = asRouterNewTabHook
+ .getInstance()
+ .then(initializer => {
+ const parentProcessMessageHandler = initializer.connect({
+ clearChildMessages: ids => this.messageAll("ClearMessages", ids),
+ clearChildProviders: ids => this.messageAll("ClearProviders", ids),
+ updateAdminState: state => this.messageAll("UpdateAdminState", state),
+ });
+ this.destroy = () => {
+ initializer.disconnect();
+ };
+ return parentProcessMessageHandler;
+ });
+ }
+
+ get size() {
+ return this.actors.size;
+ }
+
+ messageAll(message, data) {
+ return Promise.all(
+ [...this.actors].map(a => a.sendAsyncMessage(message, data))
+ );
+ }
+
+ messagePreloaded(message, data) {
+ return Promise.all(
+ [...this.actors]
+ .filter(a =>
+ a.browsingContext.embedderElement.getAttribute("preloaded")
+ )
+ .map(a => a.sendAsyncMessage(message, data))
+ );
+ }
+
+ registerActor(actor) {
+ this.actors.add(actor);
+ }
+
+ unregisterActor(actor) {
+ this.actors.delete(actor);
+ }
+}
+
+const defaultTabsFactory = () =>
+ new ASRouterTabs({ asRouterNewTabHook: ASRouterNewTabHook });
+
+class ASRouterParent extends JSWindowActorParent {
+ static tabs = null;
+
+ static nextTabId = 0;
+
+ constructor({ tabsFactory } = { tabsFactory: defaultTabsFactory }) {
+ super();
+ this.tabsFactory = tabsFactory;
+ }
+
+ actorCreated() {
+ ASRouterParent.tabs = ASRouterParent.tabs || this.tabsFactory();
+ this.tabsFactory = null;
+ this.tabId = ++ASRouterParent.nextTabId;
+ ASRouterParent.tabs.registerActor(this);
+ }
+
+ didDestroy() {
+ ASRouterParent.tabs.unregisterActor(this);
+ if (ASRouterParent.tabs.size < 1) {
+ ASRouterParent.tabs.destroy();
+ ASRouterParent.tabs = null;
+ }
+ }
+
+ getTab() {
+ return {
+ id: this.tabId,
+ browser: this.browsingContext.embedderElement,
+ };
+ }
+
+ receiveMessage({ name, data }) {
+ return ASRouterParent.tabs.loadingMessageHandler.then(handler => {
+ if (name === BLOCK_MESSAGE_BY_ID && data.preloadedOnly) {
+ return Promise.all([
+ handler.handleMessage(name, data, this.getTab()),
+ ASRouterParent.tabs.messagePreloaded("ClearMessages", [data.id]),
+ ]).then(() => false);
+ }
+ return handler.handleMessage(name, data, this.getTab());
+ });
+ }
+}
diff --git a/browser/components/newtab/bin/render-activity-stream-html.js b/browser/components/newtab/bin/render-activity-stream-html.js
new file mode 100644
index 0000000000..3c31255b7d
--- /dev/null
+++ b/browser/components/newtab/bin/render-activity-stream-html.js
@@ -0,0 +1,130 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* eslint-disable no-console */
+const fs = require("fs");
+const { mkdir } = require("shelljs");
+const path = require("path");
+
+// Note: DEFAULT_OPTIONS.baseUrl should match BASE_URL in aboutNewTabService.js
+// in mozilla-central.
+const DEFAULT_OPTIONS = {
+ addonPath: "..",
+ baseUrl: "resource://activity-stream/",
+};
+
+/**
+ * templateHTML - Generates HTML for activity stream, given some options and
+ * prerendered HTML if necessary.
+ *
+ * @param {obj} options
+ * {str} options.baseUrl The base URL for all local assets
+ * {bool} options.debug Should we use dev versions of JS libraries?
+ * {bool} options.noscripts Should we include scripts in the prerendered files?
+ * @return {str} An HTML document as a string
+ */
+function templateHTML(options) {
+ const debugString = options.debug ? "-dev" : "";
+ // This list must match any similar ones in AboutNewTabService.jsm.
+ const scripts = [
+ "chrome://browser/content/contentSearchUI.js",
+ "chrome://browser/content/contentSearchHandoffUI.js",
+ "chrome://browser/content/contentTheme.js",
+ `${options.baseUrl}vendor/react${debugString}.js`,
+ `${options.baseUrl}vendor/react-dom${debugString}.js`,
+ `${options.baseUrl}vendor/prop-types.js`,
+ `${options.baseUrl}vendor/redux.js`,
+ `${options.baseUrl}vendor/react-redux.js`,
+ `${options.baseUrl}vendor/react-transition-group.js`,
+ `${options.baseUrl}data/content/activity-stream.bundle.js`,
+ `${options.baseUrl}data/content/newtab-render.js`,
+ ];
+
+ // Add spacing and script tags
+ const scriptRender = `\n${scripts
+ .map(script => ` <script src="${script}"></script>`)
+ .join("\n")}`;
+
+ return `
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ - You can obtain one at http://mozilla.org/MPL/2.0/. -->
+
+<!doctype html>
+<html>
+ <head>
+ <meta charset="utf-8">
+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; object-src 'none'; script-src resource: chrome:; connect-src https:; img-src https: data: blob:; style-src 'unsafe-inline';">
+ <title data-l10n-id="newtab-page-title"></title>
+ <link rel="icon" type="image/png" href="chrome://branding/content/icon32.png"/>
+ <link rel="localization" href="branding/brand.ftl" />
+ <link rel="localization" href="browser/branding/brandings.ftl" />
+ <link rel="localization" href="browser/newtab/newtab.ftl" />
+ <link rel="stylesheet" href="chrome://browser/content/contentSearchUI.css" />
+ <link rel="stylesheet" href="chrome://activity-stream/content/css/activity-stream.css" />
+ </head>
+ <body class="activity-stream">
+ <div id="root"></div>
+ <div id="footer-asrouter-container" role="presentation"></div>${
+ options.noscripts ? "" : scriptRender
+ }
+ </body>
+</html>
+`.trimLeft();
+}
+
+/**
+ * writeFiles - Writes to the desired files the result of a template given
+ * various prerendered data and options.
+ *
+ * @param {string} destPath Path to write the files to
+ * @param {Map} filesMap Mapping of a string file name to templater
+ * @param {Object} options Various options for the templater
+ */
+function writeFiles(destPath, filesMap, options) {
+ for (const [file, templater] of filesMap) {
+ console.log("\x1b[32m", `✓ ${file}`, "\x1b[0m");
+ fs.writeFileSync(path.join(destPath, file), templater({ options }));
+ }
+}
+
+const STATIC_FILES = new Map([
+ ["activity-stream.html", ({ options }) => templateHTML(options)],
+ [
+ "activity-stream-debug.html",
+ ({ options }) => templateHTML(Object.assign({}, options, { debug: true })),
+ ],
+ [
+ "activity-stream-noscripts.html",
+ ({ options }) =>
+ templateHTML(Object.assign({}, options, { noscripts: true })),
+ ],
+]);
+
+/**
+ * main - Parses command line arguments, generates html and js with templates,
+ * and writes files to their specified locations.
+ */
+function main() {
+ // eslint-disable-line max-statements
+ // This code parses command line arguments passed to this script.
+ // Note: process.argv.slice(2) is necessary because the first two items in
+ // process.argv are paths
+ const args = require("minimist")(process.argv.slice(2), {
+ alias: {
+ addonPath: "a",
+ baseUrl: "b",
+ },
+ });
+
+ const options = Object.assign({ debug: false }, DEFAULT_OPTIONS, args || {});
+ const addonPath = path.resolve(__dirname, options.addonPath);
+ const prerenderedPath = path.join(addonPath, "prerendered");
+ console.log(`Writing prerendered files to ${prerenderedPath}:`);
+
+ mkdir("-p", prerenderedPath);
+ writeFiles(prerenderedPath, STATIC_FILES, options);
+}
+
+main();
diff --git a/browser/components/newtab/bin/try-runner.js b/browser/components/newtab/bin/try-runner.js
new file mode 100644
index 0000000000..d2e9404db6
--- /dev/null
+++ b/browser/components/newtab/bin/try-runner.js
@@ -0,0 +1,179 @@
+/* eslint-disable no-console */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at <http://mozilla.org/MPL/2.0/>. */
+
+/*
+ * A small test runner/reporter for node-based tests,
+ * which are run via taskcluster node(debugger).
+ *
+ * Forked from
+ * https://searchfox.org/mozilla-central/source/devtools/client/debugger/bin/try-runner.js
+ */
+
+const { execFileSync } = require("child_process");
+const { readFileSync } = require("fs");
+const path = require("path");
+
+function logErrors(tool, errors) {
+ for (const error of errors) {
+ console.log(`TEST-UNEXPECTED-FAIL ${tool} | ${error}`);
+ }
+ return errors;
+}
+
+function execOut(...args) {
+ let exitCode = 0;
+ let out;
+ let err;
+
+ try {
+ out = execFileSync(...args, {
+ silent: false,
+ });
+ } catch (e) {
+ // For debugging on (eg) try server...
+ //
+ // if (e) {
+ // logErrors("execOut", ["execFileSync returned exception: ", e]);
+ // }
+
+ out = e && e.stdout;
+ err = e && e.stderr;
+ exitCode = e && e.status;
+ }
+ return { exitCode, out: out && out.toString(), err: err && err.toString() };
+}
+
+function logStart(name) {
+ console.log(`TEST START | ${name}`);
+}
+
+function checkBundles() {
+ logStart("checkBundles");
+
+ const ASbundle = path.join("data", "content", "activity-stream.bundle.js");
+ const AWbundle = path.join(
+ "aboutwelcome",
+ "content",
+ "aboutwelcome.bundle.js"
+ );
+ let errors = [];
+
+ let ASbefore = readFileSync(ASbundle, "utf8");
+ let AWbefore = readFileSync(AWbundle, "utf8");
+
+ execOut("npm", ["run", "bundle"]);
+
+ let ASafter = readFileSync(ASbundle, "utf8");
+ let AWafter = readFileSync(AWbundle, "utf8");
+
+ if (ASbefore !== ASafter) {
+ errors.push("Activity Stream bundle out of date");
+ }
+
+ if (AWbefore !== AWafter) {
+ errors.push("About:welcome bundle out of date");
+ }
+
+ logErrors("checkBundles", errors);
+ return errors.length === 0;
+}
+
+function karma() {
+ logStart("karma");
+
+ const errors = [];
+ const { exitCode, out } = execOut("npm", [
+ "run",
+ "testmc:unit",
+ // , "--", "--log-level", "--verbose",
+ // to debug the karma integration, uncomment the above line
+ ]);
+
+ // karma spits everything to stdout, not stderr, so if nothing came back on
+ // stdout, give up now.
+ if (!out) {
+ return false;
+ }
+
+ // Detect mocha failures
+ let jsonContent;
+ try {
+ // Note that this will be overwritten at each run, but that shouldn't
+ // matter.
+ jsonContent = readFileSync(path.join("logs", "karma-run-results.json"));
+ } catch (ex) {
+ console.error("exception reading karma-run-results.json: ", ex);
+ return false;
+ }
+ const results = JSON.parse(jsonContent);
+ // eslint-disable-next-line guard-for-in
+ for (let testArray in results.result) {
+ let failedTests = Array.from(results.result[testArray]).filter(
+ test => !test.success && !test.skipped
+ );
+
+ errors.push(
+ ...failedTests.map(
+ test => `${test.suite.join(":")} ${test.description}: ${test.log[0]}`
+ )
+ );
+ }
+
+ // Detect istanbul failures (coverage thresholds set in karma config)
+ const coverage = out.match(/ERROR.+coverage-istanbul.+/g);
+ if (coverage) {
+ errors.push(...coverage.map(line => line.match(/Coverage.+/)[0]));
+ }
+
+ logErrors("karma", errors);
+
+ // Pass if there's no detected errors and nothing unexpected.
+ return errors.length === 0 && !exitCode;
+}
+
+function sasslint() {
+ logStart("sasslint");
+ const { exitCode, out } = execOut("npm", [
+ "run",
+ "--silent",
+ "lint:sasslint",
+ "--",
+ "--format",
+ "json",
+ ]);
+
+ // Successful exit and no output means sasslint passed.
+ if (!exitCode && !out.length) {
+ return true;
+ }
+
+ let fileObjects = JSON.parse(out);
+ let filesWithIssues = fileObjects.filter(
+ file => file.warningCount || file.errorCount
+ );
+
+ let errs = [];
+ let errorString;
+ filesWithIssues.forEach(file => {
+ file.messages.forEach(messageObj => {
+ errorString = `${file.filePath}(${messageObj.line}, ${messageObj.column}): ${messageObj.message} (${messageObj.ruleId})`;
+ errs.push(errorString);
+ });
+ });
+
+ const errors = logErrors("sasslint", errs);
+
+ // Pass if there's no detected errors and nothing unexpected.
+ return errors.length === 0 && !exitCode;
+}
+
+const tests = {};
+const success = [checkBundles, karma, sasslint].every(
+ t => (tests[t.name] = t())
+);
+console.log(tests);
+
+process.exitCode = success ? 0 : 1;
+console.log("CODE", process.exitCode);
diff --git a/browser/components/newtab/bin/vendor.js b/browser/components/newtab/bin/vendor.js
new file mode 100644
index 0000000000..3d929dcf4b
--- /dev/null
+++ b/browser/components/newtab/bin/vendor.js
@@ -0,0 +1,38 @@
+#!/usr/bin/env node
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* eslint-disable no-console */
+
+const { cp, set } = require("shelljs");
+const path = require("path");
+
+const filesToVendor = {
+ // XXX currently these two licenses are identical. Perhaps we should check
+ // in case that changes at some point in the future.
+ "react/LICENSE": "REACT_AND_REACT_DOM_LICENSE",
+ "react/umd/react.production.min.js": "react.js",
+ "react/umd/react.development.js": "react-dev.js",
+ "react-dom/umd/react-dom.production.min.js": "react-dom.js",
+ "react-dom/umd/react-dom.development.js": "react-dom-dev.js",
+ "react-dom/umd/react-dom-server.browser.production.min.js":
+ "react-dom-server.js",
+ "react-redux/LICENSE.md": "REACT_REDUX_LICENSE",
+ "react-redux/dist/react-redux.min.js": "react-redux.js",
+ "react-transition-group/dist/react-transition-group.min.js":
+ "react-transition-group.js",
+ "react-transition-group/LICENSE": "REACT_TRANSITION_GROUP_LICENSE",
+};
+
+set("-v"); // Echo all the copy commands so the user can see what's going on
+for (let srcPath of Object.keys(filesToVendor)) {
+ cp(
+ path.join("node_modules", srcPath),
+ path.join("vendor", filesToVendor[srcPath])
+ );
+}
+
+console.log(`
+Check to see if any license files have changed, and, if so, be sure to update
+https://searchfox.org/mozilla-central/source/toolkit/content/license.html`);
diff --git a/browser/components/newtab/common/Actions.jsm b/browser/components/newtab/common/Actions.jsm
new file mode 100644
index 0000000000..ce108b415e
--- /dev/null
+++ b/browser/components/newtab/common/Actions.jsm
@@ -0,0 +1,451 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
+this.MAIN_MESSAGE_TYPE = "ActivityStream:Main";
+this.CONTENT_MESSAGE_TYPE = "ActivityStream:Content";
+this.PRELOAD_MESSAGE_TYPE = "ActivityStream:PreloadedBrowser";
+this.UI_CODE = 1;
+this.BACKGROUND_PROCESS = 2;
+
+/**
+ * globalImportContext - Are we in UI code (i.e. react, a dom) or some kind of background process?
+ * Use this in action creators if you need different logic
+ * for ui/background processes.
+ */
+const globalImportContext =
+ typeof Window === "undefined" ? BACKGROUND_PROCESS : UI_CODE;
+// Export for tests
+this.globalImportContext = globalImportContext;
+
+// Create an object that avoids accidental differing key/value pairs:
+// {
+// INIT: "INIT",
+// UNINIT: "UNINIT"
+// }
+const actionTypes = {};
+for (const type of [
+ "ABOUT_SPONSORED_TOP_SITES",
+ "ADDONS_INFO_REQUEST",
+ "ADDONS_INFO_RESPONSE",
+ "ARCHIVE_FROM_POCKET",
+ "AS_ROUTER_INITIALIZED",
+ "AS_ROUTER_PREF_CHANGED",
+ "AS_ROUTER_TARGETING_UPDATE",
+ "AS_ROUTER_TELEMETRY_USER_EVENT",
+ "BLOCK_URL",
+ "BOOKMARK_URL",
+ "CLEAR_PREF",
+ "COPY_DOWNLOAD_LINK",
+ "DELETE_BOOKMARK_BY_ID",
+ "DELETE_FROM_POCKET",
+ "DELETE_HISTORY_URL",
+ "DIALOG_CANCEL",
+ "DIALOG_OPEN",
+ "DISCOVERY_STREAM_COLLECTION_DISMISSIBLE_TOGGLE",
+ "DISCOVERY_STREAM_CONFIG_CHANGE",
+ "DISCOVERY_STREAM_CONFIG_RESET",
+ "DISCOVERY_STREAM_CONFIG_RESET_DEFAULTS",
+ "DISCOVERY_STREAM_CONFIG_SETUP",
+ "DISCOVERY_STREAM_CONFIG_SET_VALUE",
+ "DISCOVERY_STREAM_DEV_EXPIRE_CACHE",
+ "DISCOVERY_STREAM_DEV_IDLE_DAILY",
+ "DISCOVERY_STREAM_DEV_SYNC_RS",
+ "DISCOVERY_STREAM_DEV_SYSTEM_TICK",
+ "DISCOVERY_STREAM_FEEDS_UPDATE",
+ "DISCOVERY_STREAM_FEED_UPDATE",
+ "DISCOVERY_STREAM_IMPRESSION_STATS",
+ "DISCOVERY_STREAM_LAYOUT_RESET",
+ "DISCOVERY_STREAM_LAYOUT_UPDATE",
+ "DISCOVERY_STREAM_LINK_BLOCKED",
+ "DISCOVERY_STREAM_LOADED_CONTENT",
+ "DISCOVERY_STREAM_PERSONALIZATION_INIT",
+ "DISCOVERY_STREAM_PERSONALIZATION_LAST_UPDATED",
+ "DISCOVERY_STREAM_PERSONALIZATION_VERSION",
+ "DISCOVERY_STREAM_PERSONALIZATION_VERSION_TOGGLE",
+ "DISCOVERY_STREAM_RETRY_FEED",
+ "DISCOVERY_STREAM_SPOCS_CAPS",
+ "DISCOVERY_STREAM_SPOCS_ENDPOINT",
+ "DISCOVERY_STREAM_SPOCS_PLACEMENTS",
+ "DISCOVERY_STREAM_SPOCS_UPDATE",
+ "DISCOVERY_STREAM_SPOC_BLOCKED",
+ "DISCOVERY_STREAM_SPOC_IMPRESSION",
+ "DOWNLOAD_CHANGED",
+ "FAKE_FOCUS_SEARCH",
+ "FILL_SEARCH_TERM",
+ "HANDOFF_SEARCH_TO_AWESOMEBAR",
+ "HIDE_PRIVACY_INFO",
+ "HIDE_SEARCH",
+ "INIT",
+ "NEW_TAB_INIT",
+ "NEW_TAB_INITIAL_STATE",
+ "NEW_TAB_LOAD",
+ "NEW_TAB_REHYDRATED",
+ "NEW_TAB_STATE_REQUEST",
+ "NEW_TAB_UNLOAD",
+ "OPEN_DOWNLOAD_FILE",
+ "OPEN_LINK",
+ "OPEN_NEW_WINDOW",
+ "OPEN_PRIVATE_WINDOW",
+ "OPEN_WEBEXT_SETTINGS",
+ "PARTNER_LINK_ATTRIBUTION",
+ "PLACES_BOOKMARK_ADDED",
+ "PLACES_BOOKMARK_REMOVED",
+ "PLACES_HISTORY_CLEARED",
+ "PLACES_LINKS_CHANGED",
+ "PLACES_LINK_BLOCKED",
+ "PLACES_LINK_DELETED",
+ "PLACES_SAVED_TO_POCKET",
+ "POCKET_CTA",
+ "POCKET_LINK_DELETED_OR_ARCHIVED",
+ "POCKET_LOGGED_IN",
+ "POCKET_WAITING_FOR_SPOC",
+ "PREFS_INITIAL_VALUES",
+ "PREF_CHANGED",
+ "PREVIEW_REQUEST",
+ "PREVIEW_REQUEST_CANCEL",
+ "PREVIEW_RESPONSE",
+ "REMOVE_DOWNLOAD_FILE",
+ "RICH_ICON_MISSING",
+ "SAVE_SESSION_PERF_DATA",
+ "SAVE_TO_POCKET",
+ "SCREENSHOT_UPDATED",
+ "SECTION_DEREGISTER",
+ "SECTION_DISABLE",
+ "SECTION_ENABLE",
+ "SECTION_MOVE",
+ "SECTION_OPTIONS_CHANGED",
+ "SECTION_REGISTER",
+ "SECTION_UPDATE",
+ "SECTION_UPDATE_CARD",
+ "SETTINGS_CLOSE",
+ "SETTINGS_OPEN",
+ "SET_PREF",
+ "SHOW_DOWNLOAD_FILE",
+ "SHOW_FIREFOX_ACCOUNTS",
+ "SHOW_PRIVACY_INFO",
+ "SHOW_SEARCH",
+ "SKIPPED_SIGNIN",
+ "SNIPPETS_BLOCKLIST_CLEARED",
+ "SNIPPETS_BLOCKLIST_UPDATED",
+ "SNIPPETS_DATA",
+ "SNIPPETS_PREVIEW_MODE",
+ "SNIPPETS_RESET",
+ "SNIPPET_BLOCKED",
+ "SUBMIT_EMAIL",
+ "SUBMIT_SIGNIN",
+ "SYSTEM_TICK",
+ "TELEMETRY_IMPRESSION_STATS",
+ "TELEMETRY_USER_EVENT",
+ "TOP_SITES_CANCEL_EDIT",
+ "TOP_SITES_CLOSE_SEARCH_SHORTCUTS_MODAL",
+ "TOP_SITES_EDIT",
+ "TOP_SITES_INSERT",
+ "TOP_SITES_OPEN_SEARCH_SHORTCUTS_MODAL",
+ "TOP_SITES_PIN",
+ "TOP_SITES_PREFS_UPDATED",
+ "TOP_SITES_UNPIN",
+ "TOP_SITES_UPDATED",
+ "TOTAL_BOOKMARKS_REQUEST",
+ "TOTAL_BOOKMARKS_RESPONSE",
+ "UNINIT",
+ "UPDATE_PINNED_SEARCH_SHORTCUTS",
+ "UPDATE_SEARCH_SHORTCUTS",
+ "UPDATE_SECTION_PREFS",
+ "WEBEXT_CLICK",
+ "WEBEXT_DISMISS",
+]) {
+ actionTypes[type] = type;
+}
+
+// Helper function for creating routed actions between content and main
+// Not intended to be used by consumers
+function _RouteMessage(action, options) {
+ const meta = action.meta ? { ...action.meta } : {};
+ if (!options || !options.from || !options.to) {
+ throw new Error(
+ "Routed Messages must have options as the second parameter, and must at least include a .from and .to property."
+ );
+ }
+ // For each of these fields, if they are passed as an option,
+ // add them to the action. If they are not defined, remove them.
+ ["from", "to", "toTarget", "fromTarget", "skipMain", "skipLocal"].forEach(
+ o => {
+ if (typeof options[o] !== "undefined") {
+ meta[o] = options[o];
+ } else if (meta[o]) {
+ delete meta[o];
+ }
+ }
+ );
+ return { ...action, meta };
+}
+
+/**
+ * AlsoToMain - Creates a message that will be dispatched locally and also sent to the Main process.
+ *
+ * @param {object} action Any redux action (required)
+ * @param {object} options
+ * @param {bool} skipLocal Used by OnlyToMain to skip the main reducer
+ * @param {string} fromTarget The id of the content port from which the action originated. (optional)
+ * @return {object} An action with added .meta properties
+ */
+function AlsoToMain(action, fromTarget, skipLocal) {
+ return _RouteMessage(action, {
+ from: CONTENT_MESSAGE_TYPE,
+ to: MAIN_MESSAGE_TYPE,
+ fromTarget,
+ skipLocal,
+ });
+}
+
+/**
+ * OnlyToMain - Creates a message that will be sent to the Main process and skip the local reducer.
+ *
+ * @param {object} action Any redux action (required)
+ * @param {object} options
+ * @param {string} fromTarget The id of the content port from which the action originated. (optional)
+ * @return {object} An action with added .meta properties
+ */
+function OnlyToMain(action, fromTarget) {
+ return AlsoToMain(action, fromTarget, true);
+}
+
+/**
+ * BroadcastToContent - Creates a message that will be dispatched to main and sent to ALL content processes.
+ *
+ * @param {object} action Any redux action (required)
+ * @return {object} An action with added .meta properties
+ */
+function BroadcastToContent(action) {
+ return _RouteMessage(action, {
+ from: MAIN_MESSAGE_TYPE,
+ to: CONTENT_MESSAGE_TYPE,
+ });
+}
+
+/**
+ * AlsoToOneContent - Creates a message that will be will be dispatched to the main store
+ * and also sent to a particular Content process.
+ *
+ * @param {object} action Any redux action (required)
+ * @param {string} target The id of a content port
+ * @param {bool} skipMain Used by OnlyToOneContent to skip the main process
+ * @return {object} An action with added .meta properties
+ */
+function AlsoToOneContent(action, target, skipMain) {
+ if (!target) {
+ throw new Error(
+ "You must provide a target ID as the second parameter of AlsoToOneContent. If you want to send to all content processes, use BroadcastToContent"
+ );
+ }
+ return _RouteMessage(action, {
+ from: MAIN_MESSAGE_TYPE,
+ to: CONTENT_MESSAGE_TYPE,
+ toTarget: target,
+ skipMain,
+ });
+}
+
+/**
+ * OnlyToOneContent - Creates a message that will be sent to a particular Content process
+ * and skip the main reducer.
+ *
+ * @param {object} action Any redux action (required)
+ * @param {string} target The id of a content port
+ * @return {object} An action with added .meta properties
+ */
+function OnlyToOneContent(action, target) {
+ return AlsoToOneContent(action, target, true);
+}
+
+/**
+ * AlsoToPreloaded - Creates a message that dispatched to the main reducer and also sent to the preloaded tab.
+ *
+ * @param {object} action Any redux action (required)
+ * @return {object} An action with added .meta properties
+ */
+function AlsoToPreloaded(action) {
+ return _RouteMessage(action, {
+ from: MAIN_MESSAGE_TYPE,
+ to: PRELOAD_MESSAGE_TYPE,
+ });
+}
+
+/**
+ * UserEvent - A telemetry ping indicating a user action. This should only
+ * be sent from the UI during a user session.
+ *
+ * @param {object} data Fields to include in the ping (source, etc.)
+ * @return {object} An AlsoToMain action
+ */
+function UserEvent(data) {
+ return AlsoToMain({
+ type: actionTypes.TELEMETRY_USER_EVENT,
+ data,
+ });
+}
+
+/**
+ * ASRouterUserEvent - A telemetry ping indicating a user action from AS router. This should only
+ * be sent from the UI during a user session.
+ *
+ * @param {object} data Fields to include in the ping (source, etc.)
+ * @return {object} An AlsoToMain action
+ */
+function ASRouterUserEvent(data) {
+ return AlsoToMain({
+ type: actionTypes.AS_ROUTER_TELEMETRY_USER_EVENT,
+ data,
+ });
+}
+
+/**
+ * ImpressionStats - A telemetry ping indicating an impression stats.
+ *
+ * @param {object} data Fields to include in the ping
+ * @param {int} importContext (For testing) Override the import context for testing.
+ * #return {object} An action. For UI code, a AlsoToMain action.
+ */
+function ImpressionStats(data, importContext = globalImportContext) {
+ const action = {
+ type: actionTypes.TELEMETRY_IMPRESSION_STATS,
+ data,
+ };
+ return importContext === UI_CODE ? AlsoToMain(action) : action;
+}
+
+/**
+ * DiscoveryStreamImpressionStats - A telemetry ping indicating an impression stats in Discovery Stream.
+ *
+ * @param {object} data Fields to include in the ping
+ * @param {int} importContext (For testing) Override the import context for testing.
+ * #return {object} An action. For UI code, a AlsoToMain action.
+ */
+function DiscoveryStreamImpressionStats(
+ data,
+ importContext = globalImportContext
+) {
+ const action = {
+ type: actionTypes.DISCOVERY_STREAM_IMPRESSION_STATS,
+ data,
+ };
+ return importContext === UI_CODE ? AlsoToMain(action) : action;
+}
+
+/**
+ * DiscoveryStreamLoadedContent - A telemetry ping indicating a content gets loaded in Discovery Stream.
+ *
+ * @param {object} data Fields to include in the ping
+ * @param {int} importContext (For testing) Override the import context for testing.
+ * #return {object} An action. For UI code, a AlsoToMain action.
+ */
+function DiscoveryStreamLoadedContent(
+ data,
+ importContext = globalImportContext
+) {
+ const action = {
+ type: actionTypes.DISCOVERY_STREAM_LOADED_CONTENT,
+ data,
+ };
+ return importContext === UI_CODE ? AlsoToMain(action) : action;
+}
+
+function SetPref(name, value, importContext = globalImportContext) {
+ const action = { type: actionTypes.SET_PREF, data: { name, value } };
+ return importContext === UI_CODE ? AlsoToMain(action) : action;
+}
+
+function WebExtEvent(type, data, importContext = globalImportContext) {
+ if (!data || !data.source) {
+ throw new Error(
+ 'WebExtEvent actions should include a property "source", the id of the webextension that should receive the event.'
+ );
+ }
+ const action = { type, data };
+ return importContext === UI_CODE ? AlsoToMain(action) : action;
+}
+
+this.actionTypes = actionTypes;
+
+this.actionCreators = {
+ BroadcastToContent,
+ UserEvent,
+ ASRouterUserEvent,
+ ImpressionStats,
+ AlsoToOneContent,
+ OnlyToOneContent,
+ AlsoToMain,
+ OnlyToMain,
+ AlsoToPreloaded,
+ SetPref,
+ WebExtEvent,
+ DiscoveryStreamImpressionStats,
+ DiscoveryStreamLoadedContent,
+};
+
+// These are helpers to test for certain kinds of actions
+this.actionUtils = {
+ isSendToMain(action) {
+ if (!action.meta) {
+ return false;
+ }
+ return (
+ action.meta.to === MAIN_MESSAGE_TYPE &&
+ action.meta.from === CONTENT_MESSAGE_TYPE
+ );
+ },
+ isBroadcastToContent(action) {
+ if (!action.meta) {
+ return false;
+ }
+ if (action.meta.to === CONTENT_MESSAGE_TYPE && !action.meta.toTarget) {
+ return true;
+ }
+ return false;
+ },
+ isSendToOneContent(action) {
+ if (!action.meta) {
+ return false;
+ }
+ if (action.meta.to === CONTENT_MESSAGE_TYPE && action.meta.toTarget) {
+ return true;
+ }
+ return false;
+ },
+ isSendToPreloaded(action) {
+ if (!action.meta) {
+ return false;
+ }
+ return (
+ action.meta.to === PRELOAD_MESSAGE_TYPE &&
+ action.meta.from === MAIN_MESSAGE_TYPE
+ );
+ },
+ isFromMain(action) {
+ if (!action.meta) {
+ return false;
+ }
+ return (
+ action.meta.from === MAIN_MESSAGE_TYPE &&
+ action.meta.to === CONTENT_MESSAGE_TYPE
+ );
+ },
+ getPortIdOfSender(action) {
+ return (action.meta && action.meta.fromTarget) || null;
+ },
+ _RouteMessage,
+};
+
+const EXPORTED_SYMBOLS = [
+ "actionTypes",
+ "actionCreators",
+ "actionUtils",
+ "globalImportContext",
+ "UI_CODE",
+ "BACKGROUND_PROCESS",
+ "MAIN_MESSAGE_TYPE",
+ "CONTENT_MESSAGE_TYPE",
+ "PRELOAD_MESSAGE_TYPE",
+];
diff --git a/browser/components/newtab/common/ActorConstants.jsm b/browser/components/newtab/common/ActorConstants.jsm
new file mode 100644
index 0000000000..edeb19bd3e
--- /dev/null
+++ b/browser/components/newtab/common/ActorConstants.jsm
@@ -0,0 +1,45 @@
+/* vim: set ts=2 sw=2 sts=2 et tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
+const MESSAGE_TYPE_LIST = [
+ "BLOCK_MESSAGE_BY_ID",
+ "USER_ACTION",
+ "IMPRESSION",
+ "TRIGGER",
+ "NEWTAB_MESSAGE_REQUEST",
+ "DOORHANGER_TELEMETRY",
+ "TOOLBAR_BADGE_TELEMETRY",
+ "TOOLBAR_PANEL_TELEMETRY",
+ "MOMENTS_PAGE_TELEMETRY",
+ "INFOBAR_TELEMETRY",
+ "AS_ROUTER_TELEMETRY_USER_EVENT",
+
+ // Admin types
+ "ADMIN_CONNECT_STATE",
+ "UNBLOCK_MESSAGE_BY_ID",
+ "UNBLOCK_ALL",
+ "BLOCK_BUNDLE",
+ "UNBLOCK_BUNDLE",
+ "DISABLE_PROVIDER",
+ "ENABLE_PROVIDER",
+ "EVALUATE_JEXL_EXPRESSION",
+ "EXPIRE_QUERY_CACHE",
+ "FORCE_ATTRIBUTION",
+ "FORCE_WHATSNEW_PANEL",
+ "CLOSE_WHATSNEW_PANEL",
+ "OVERRIDE_MESSAGE",
+ "MODIFY_MESSAGE_JSON",
+ "RESET_PROVIDER_PREF",
+ "SET_PROVIDER_USER_PREF",
+ "RESET_GROUPS_STATE",
+];
+
+const MESSAGE_TYPE_HASH = MESSAGE_TYPE_LIST.reduce((hash, value) => {
+ hash[value] = value;
+ return hash;
+}, {});
+
+const EXPORTED_SYMBOLS = ["MESSAGE_TYPE_LIST", "MESSAGE_TYPE_HASH"];
diff --git a/browser/components/newtab/common/Dedupe.jsm b/browser/components/newtab/common/Dedupe.jsm
new file mode 100644
index 0000000000..280615ba6a
--- /dev/null
+++ b/browser/components/newtab/common/Dedupe.jsm
@@ -0,0 +1,38 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+this.Dedupe = class Dedupe {
+ constructor(createKey) {
+ this.createKey = createKey || this.defaultCreateKey;
+ }
+
+ defaultCreateKey(item) {
+ return item;
+ }
+
+ /**
+ * Dedupe any number of grouped elements favoring those from earlier groups.
+ *
+ * @param {Array} groups Contains an arbitrary number of arrays of elements.
+ * @returns {Array} A matching array of each provided group deduped.
+ */
+ group(...groups) {
+ const globalKeys = new Set();
+ const result = [];
+ for (const values of groups) {
+ const valueMap = new Map();
+ for (const value of values) {
+ const key = this.createKey(value);
+ if (!globalKeys.has(key) && !valueMap.has(key)) {
+ valueMap.set(key, value);
+ }
+ }
+ result.push(valueMap);
+ valueMap.forEach((value, key) => globalKeys.add(key));
+ }
+ return result.map(m => Array.from(m.values()));
+ }
+};
+
+const EXPORTED_SYMBOLS = ["Dedupe"];
diff --git a/browser/components/newtab/common/Reducers.jsm b/browser/components/newtab/common/Reducers.jsm
new file mode 100644
index 0000000000..b1cf3db2c5
--- /dev/null
+++ b/browser/components/newtab/common/Reducers.jsm
@@ -0,0 +1,834 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
+const { actionTypes: at } = ChromeUtils.import(
+ "resource://activity-stream/common/Actions.jsm"
+);
+const { Dedupe } = ChromeUtils.import(
+ "resource://activity-stream/common/Dedupe.jsm"
+);
+
+const TOP_SITES_DEFAULT_ROWS = 1;
+const TOP_SITES_MAX_SITES_PER_ROW = 8;
+const PREF_PERSONALIZATION_VERSION = "discoverystream.personalization.version";
+const PREF_COLLECTION_DISMISSIBLE = "discoverystream.isCollectionDismissible";
+
+const dedupe = new Dedupe(site => site && site.url);
+
+const INITIAL_STATE = {
+ App: {
+ // Have we received real data from the app yet?
+ initialized: false,
+ locale: "",
+ },
+ ASRouter: { initialized: false },
+ Snippets: { initialized: false },
+ TopSites: {
+ // Have we received real data from history yet?
+ initialized: false,
+ // The history (and possibly default) links
+ rows: [],
+ // Used in content only to dispatch action to TopSiteForm.
+ editForm: null,
+ // Used in content only to open the SearchShortcutsForm modal.
+ showSearchShortcutsForm: false,
+ // The list of available search shortcuts.
+ searchShortcuts: [],
+ },
+ Prefs: {
+ initialized: false,
+ values: {},
+ },
+ Dialog: {
+ visible: false,
+ data: {},
+ },
+ Sections: [],
+ Pocket: {
+ isUserLoggedIn: null,
+ pocketCta: {},
+ waitingForSpoc: true,
+ },
+ // This is the new pocket configurable layout state.
+ DiscoveryStream: {
+ // This is a JSON-parsed copy of the discoverystream.config pref value.
+ config: { enabled: false, layout_endpoint: "" },
+ layout: [],
+ lastUpdated: null,
+ isPrivacyInfoModalVisible: false,
+ isCollectionDismissible: false,
+ feeds: {
+ data: {
+ // "https://foo.com/feed1": {lastUpdated: 123, data: []}
+ },
+ loaded: false,
+ },
+ spocs: {
+ spocs_endpoint: "",
+ lastUpdated: null,
+ data: {
+ // "spocs": {title: "", context: "", items: []},
+ // "placement1": {title: "", context: "", items: []},
+ },
+ loaded: false,
+ frequency_caps: [],
+ blocked: [],
+ placements: [],
+ },
+ },
+ Personalization: {
+ version: 1,
+ lastUpdated: null,
+ initialized: false,
+ },
+ Search: {
+ // When search hand-off is enabled, we render a big button that is styled to
+ // look like a search textbox. If the button is clicked, we style
+ // the button as if it was a focused search box and show a fake cursor but
+ // really focus the awesomebar without the focus styles ("hidden focus").
+ fakeFocus: false,
+ // Hide the search box after handing off to AwesomeBar and user starts typing.
+ hide: false,
+ },
+};
+
+function App(prevState = INITIAL_STATE.App, action) {
+ switch (action.type) {
+ case at.INIT:
+ return Object.assign({}, prevState, action.data || {}, {
+ initialized: true,
+ });
+ default:
+ return prevState;
+ }
+}
+
+function ASRouter(prevState = INITIAL_STATE.ASRouter, action) {
+ switch (action.type) {
+ case at.AS_ROUTER_INITIALIZED:
+ return { ...action.data, initialized: true };
+ default:
+ return prevState;
+ }
+}
+
+/**
+ * insertPinned - Inserts pinned links in their specified slots
+ *
+ * @param {array} a list of links
+ * @param {array} a list of pinned links
+ * @return {array} resulting list of links with pinned links inserted
+ */
+function insertPinned(links, pinned) {
+ // Remove any pinned links
+ const pinnedUrls = pinned.map(link => link && link.url);
+ let newLinks = links.filter(link =>
+ link ? !pinnedUrls.includes(link.url) : false
+ );
+ newLinks = newLinks.map(link => {
+ if (link && link.isPinned) {
+ delete link.isPinned;
+ delete link.pinIndex;
+ }
+ return link;
+ });
+
+ // Then insert them in their specified location
+ pinned.forEach((val, index) => {
+ if (!val) {
+ return;
+ }
+ let link = Object.assign({}, val, { isPinned: true, pinIndex: index });
+ if (index > newLinks.length) {
+ newLinks[index] = link;
+ } else {
+ newLinks.splice(index, 0, link);
+ }
+ });
+
+ return newLinks;
+}
+
+function TopSites(prevState = INITIAL_STATE.TopSites, action) {
+ let hasMatch;
+ let newRows;
+ switch (action.type) {
+ case at.TOP_SITES_UPDATED:
+ if (!action.data || !action.data.links) {
+ return prevState;
+ }
+ return Object.assign(
+ {},
+ prevState,
+ { initialized: true, rows: action.data.links },
+ action.data.pref ? { pref: action.data.pref } : {}
+ );
+ case at.TOP_SITES_PREFS_UPDATED:
+ return Object.assign({}, prevState, { pref: action.data.pref });
+ case at.TOP_SITES_EDIT:
+ return Object.assign({}, prevState, {
+ editForm: {
+ index: action.data.index,
+ previewResponse: null,
+ },
+ });
+ case at.TOP_SITES_CANCEL_EDIT:
+ return Object.assign({}, prevState, { editForm: null });
+ case at.TOP_SITES_OPEN_SEARCH_SHORTCUTS_MODAL:
+ return Object.assign({}, prevState, { showSearchShortcutsForm: true });
+ case at.TOP_SITES_CLOSE_SEARCH_SHORTCUTS_MODAL:
+ return Object.assign({}, prevState, { showSearchShortcutsForm: false });
+ case at.PREVIEW_RESPONSE:
+ if (
+ !prevState.editForm ||
+ action.data.url !== prevState.editForm.previewUrl
+ ) {
+ return prevState;
+ }
+ return Object.assign({}, prevState, {
+ editForm: {
+ index: prevState.editForm.index,
+ previewResponse: action.data.preview,
+ previewUrl: action.data.url,
+ },
+ });
+ case at.PREVIEW_REQUEST:
+ if (!prevState.editForm) {
+ return prevState;
+ }
+ return Object.assign({}, prevState, {
+ editForm: {
+ index: prevState.editForm.index,
+ previewResponse: null,
+ previewUrl: action.data.url,
+ },
+ });
+ case at.PREVIEW_REQUEST_CANCEL:
+ if (!prevState.editForm) {
+ return prevState;
+ }
+ return Object.assign({}, prevState, {
+ editForm: {
+ index: prevState.editForm.index,
+ previewResponse: null,
+ },
+ });
+ case at.SCREENSHOT_UPDATED:
+ newRows = prevState.rows.map(row => {
+ if (row && row.url === action.data.url) {
+ hasMatch = true;
+ return Object.assign({}, row, { screenshot: action.data.screenshot });
+ }
+ return row;
+ });
+ return hasMatch
+ ? Object.assign({}, prevState, { rows: newRows })
+ : prevState;
+ case at.PLACES_BOOKMARK_ADDED:
+ if (!action.data) {
+ return prevState;
+ }
+ newRows = prevState.rows.map(site => {
+ if (site && site.url === action.data.url) {
+ const { bookmarkGuid, bookmarkTitle, dateAdded } = action.data;
+ return Object.assign({}, site, {
+ bookmarkGuid,
+ bookmarkTitle,
+ bookmarkDateCreated: dateAdded,
+ });
+ }
+ return site;
+ });
+ return Object.assign({}, prevState, { rows: newRows });
+ case at.PLACES_BOOKMARK_REMOVED:
+ if (!action.data) {
+ return prevState;
+ }
+ newRows = prevState.rows.map(site => {
+ if (site && site.url === action.data.url) {
+ const newSite = Object.assign({}, site);
+ delete newSite.bookmarkGuid;
+ delete newSite.bookmarkTitle;
+ delete newSite.bookmarkDateCreated;
+ return newSite;
+ }
+ return site;
+ });
+ return Object.assign({}, prevState, { rows: newRows });
+ case at.PLACES_LINK_DELETED:
+ if (!action.data) {
+ return prevState;
+ }
+ newRows = prevState.rows.filter(site => action.data.url !== site.url);
+ return Object.assign({}, prevState, { rows: newRows });
+ case at.UPDATE_SEARCH_SHORTCUTS:
+ return { ...prevState, searchShortcuts: action.data.searchShortcuts };
+ case at.SNIPPETS_PREVIEW_MODE:
+ return { ...prevState, rows: [] };
+ default:
+ return prevState;
+ }
+}
+
+function Dialog(prevState = INITIAL_STATE.Dialog, action) {
+ switch (action.type) {
+ case at.DIALOG_OPEN:
+ return Object.assign({}, prevState, { visible: true, data: action.data });
+ case at.DIALOG_CANCEL:
+ return Object.assign({}, prevState, { visible: false });
+ case at.DELETE_HISTORY_URL:
+ return Object.assign({}, INITIAL_STATE.Dialog);
+ default:
+ return prevState;
+ }
+}
+
+function Prefs(prevState = INITIAL_STATE.Prefs, action) {
+ let newValues;
+ switch (action.type) {
+ case at.PREFS_INITIAL_VALUES:
+ return Object.assign({}, prevState, {
+ initialized: true,
+ values: action.data,
+ });
+ case at.PREF_CHANGED:
+ newValues = Object.assign({}, prevState.values);
+ newValues[action.data.name] = action.data.value;
+ return Object.assign({}, prevState, { values: newValues });
+ default:
+ return prevState;
+ }
+}
+
+function Sections(prevState = INITIAL_STATE.Sections, action) {
+ let hasMatch;
+ let newState;
+ switch (action.type) {
+ case at.SECTION_DEREGISTER:
+ return prevState.filter(section => section.id !== action.data);
+ case at.SECTION_REGISTER:
+ // If section exists in prevState, update it
+ newState = prevState.map(section => {
+ if (section && section.id === action.data.id) {
+ hasMatch = true;
+ return Object.assign({}, section, action.data);
+ }
+ return section;
+ });
+ // Otherwise, append it
+ if (!hasMatch) {
+ const initialized = !!(action.data.rows && !!action.data.rows.length);
+ const section = Object.assign(
+ { title: "", rows: [], enabled: false },
+ action.data,
+ { initialized }
+ );
+ newState.push(section);
+ }
+ return newState;
+ case at.SECTION_UPDATE:
+ newState = prevState.map(section => {
+ if (section && section.id === action.data.id) {
+ // If the action is updating rows, we should consider initialized to be true.
+ // This can be overridden if initialized is defined in the action.data
+ const initialized = action.data.rows ? { initialized: true } : {};
+
+ // Make sure pinned cards stay at their current position when rows are updated.
+ // Disabling a section (SECTION_UPDATE with empty rows) does not retain pinned cards.
+ if (
+ action.data.rows &&
+ !!action.data.rows.length &&
+ section.rows.find(card => card.pinned)
+ ) {
+ const rows = Array.from(action.data.rows);
+ section.rows.forEach((card, index) => {
+ if (card.pinned) {
+ // Only add it if it's not already there.
+ if (rows[index].guid !== card.guid) {
+ rows.splice(index, 0, card);
+ }
+ }
+ });
+ return Object.assign(
+ {},
+ section,
+ initialized,
+ Object.assign({}, action.data, { rows })
+ );
+ }
+
+ return Object.assign({}, section, initialized, action.data);
+ }
+ return section;
+ });
+
+ if (!action.data.dedupeConfigurations) {
+ return newState;
+ }
+
+ action.data.dedupeConfigurations.forEach(dedupeConf => {
+ newState = newState.map(section => {
+ if (section.id === dedupeConf.id) {
+ const dedupedRows = dedupeConf.dedupeFrom.reduce(
+ (rows, dedupeSectionId) => {
+ const dedupeSection = newState.find(
+ s => s.id === dedupeSectionId
+ );
+ const [, newRows] = dedupe.group(dedupeSection.rows, rows);
+ return newRows;
+ },
+ section.rows
+ );
+
+ return Object.assign({}, section, { rows: dedupedRows });
+ }
+
+ return section;
+ });
+ });
+
+ return newState;
+ case at.SECTION_UPDATE_CARD:
+ return prevState.map(section => {
+ if (section && section.id === action.data.id && section.rows) {
+ const newRows = section.rows.map(card => {
+ if (card.url === action.data.url) {
+ return Object.assign({}, card, action.data.options);
+ }
+ return card;
+ });
+ return Object.assign({}, section, { rows: newRows });
+ }
+ return section;
+ });
+ case at.PLACES_BOOKMARK_ADDED:
+ if (!action.data) {
+ return prevState;
+ }
+ return prevState.map(section =>
+ Object.assign({}, section, {
+ rows: section.rows.map(item => {
+ // find the item within the rows that is attempted to be bookmarked
+ if (item.url === action.data.url) {
+ const { bookmarkGuid, bookmarkTitle, dateAdded } = action.data;
+ return Object.assign({}, item, {
+ bookmarkGuid,
+ bookmarkTitle,
+ bookmarkDateCreated: dateAdded,
+ type: "bookmark",
+ });
+ }
+ return item;
+ }),
+ })
+ );
+ case at.PLACES_SAVED_TO_POCKET:
+ if (!action.data) {
+ return prevState;
+ }
+ return prevState.map(section =>
+ Object.assign({}, section, {
+ rows: section.rows.map(item => {
+ if (item.url === action.data.url) {
+ return Object.assign({}, item, {
+ open_url: action.data.open_url,
+ pocket_id: action.data.pocket_id,
+ title: action.data.title,
+ type: "pocket",
+ });
+ }
+ return item;
+ }),
+ })
+ );
+ case at.PLACES_BOOKMARK_REMOVED:
+ if (!action.data) {
+ return prevState;
+ }
+ return prevState.map(section =>
+ Object.assign({}, section, {
+ rows: section.rows.map(item => {
+ // find the bookmark within the rows that is attempted to be removed
+ if (item.url === action.data.url) {
+ const newSite = Object.assign({}, item);
+ delete newSite.bookmarkGuid;
+ delete newSite.bookmarkTitle;
+ delete newSite.bookmarkDateCreated;
+ if (!newSite.type || newSite.type === "bookmark") {
+ newSite.type = "history";
+ }
+ return newSite;
+ }
+ return item;
+ }),
+ })
+ );
+ case at.PLACES_LINK_DELETED:
+ case at.PLACES_LINK_BLOCKED:
+ if (!action.data) {
+ return prevState;
+ }
+ return prevState.map(section =>
+ Object.assign({}, section, {
+ rows: section.rows.filter(site => site.url !== action.data.url),
+ })
+ );
+ case at.DELETE_FROM_POCKET:
+ case at.ARCHIVE_FROM_POCKET:
+ return prevState.map(section =>
+ Object.assign({}, section, {
+ rows: section.rows.filter(
+ site => site.pocket_id !== action.data.pocket_id
+ ),
+ })
+ );
+ case at.SNIPPETS_PREVIEW_MODE:
+ return prevState.map(section => ({ ...section, rows: [] }));
+ default:
+ return prevState;
+ }
+}
+
+function Snippets(prevState = INITIAL_STATE.Snippets, action) {
+ switch (action.type) {
+ case at.SNIPPETS_DATA:
+ return Object.assign({}, prevState, { initialized: true }, action.data);
+ case at.SNIPPET_BLOCKED:
+ return Object.assign({}, prevState, {
+ blockList: prevState.blockList.concat(action.data),
+ });
+ case at.SNIPPETS_BLOCKLIST_CLEARED:
+ return Object.assign({}, prevState, { blockList: [] });
+ case at.SNIPPETS_RESET:
+ return INITIAL_STATE.Snippets;
+ default:
+ return prevState;
+ }
+}
+
+function Pocket(prevState = INITIAL_STATE.Pocket, action) {
+ switch (action.type) {
+ case at.POCKET_WAITING_FOR_SPOC:
+ return { ...prevState, waitingForSpoc: action.data };
+ case at.POCKET_LOGGED_IN:
+ return { ...prevState, isUserLoggedIn: !!action.data };
+ case at.POCKET_CTA:
+ return {
+ ...prevState,
+ pocketCta: {
+ ctaButton: action.data.cta_button,
+ ctaText: action.data.cta_text,
+ ctaUrl: action.data.cta_url,
+ useCta: action.data.use_cta,
+ },
+ };
+ default:
+ return prevState;
+ }
+}
+
+function Personalization(prevState = INITIAL_STATE.Personalization, action) {
+ switch (action.type) {
+ case at.DISCOVERY_STREAM_PERSONALIZATION_VERSION:
+ return {
+ ...prevState,
+ version: action.data.version,
+ };
+ case at.DISCOVERY_STREAM_PERSONALIZATION_LAST_UPDATED:
+ return {
+ ...prevState,
+ lastUpdated: action.data.lastUpdated,
+ };
+ case at.DISCOVERY_STREAM_PERSONALIZATION_INIT:
+ return {
+ ...prevState,
+ initialized: true,
+ };
+ case at.PREF_CHANGED:
+ if (action.data.name === PREF_PERSONALIZATION_VERSION) {
+ return {
+ ...prevState,
+ version: action.data.value,
+ };
+ }
+ return prevState;
+ default:
+ return prevState;
+ }
+}
+
+// eslint-disable-next-line complexity
+function DiscoveryStream(prevState = INITIAL_STATE.DiscoveryStream, action) {
+ // Return if action data is empty, or spocs or feeds data is not loaded
+ const isNotReady = () =>
+ !action.data || !prevState.spocs.loaded || !prevState.feeds.loaded;
+
+ const handlePlacements = handleSites => {
+ const { data, placements } = prevState.spocs;
+ const result = {};
+
+ const forPlacement = placement => {
+ const placementSpocs = data[placement.name];
+
+ if (
+ !placementSpocs ||
+ !placementSpocs.items ||
+ !placementSpocs.items.length
+ ) {
+ return;
+ }
+
+ result[placement.name] = {
+ ...placementSpocs,
+ items: handleSites(placementSpocs.items),
+ };
+ };
+
+ if (!placements || !placements.length) {
+ [{ name: "spocs" }].forEach(forPlacement);
+ } else {
+ placements.forEach(forPlacement);
+ }
+ return result;
+ };
+
+ const nextState = handleSites => ({
+ ...prevState,
+ spocs: {
+ ...prevState.spocs,
+ data: handlePlacements(handleSites),
+ },
+ feeds: {
+ ...prevState.feeds,
+ data: Object.keys(prevState.feeds.data).reduce(
+ (accumulator, feed_url) => {
+ accumulator[feed_url] = {
+ data: {
+ ...prevState.feeds.data[feed_url].data,
+ recommendations: handleSites(
+ prevState.feeds.data[feed_url].data.recommendations
+ ),
+ },
+ };
+ return accumulator;
+ },
+ {}
+ ),
+ },
+ });
+
+ switch (action.type) {
+ case at.DISCOVERY_STREAM_CONFIG_CHANGE:
+ // Fall through to a separate action is so it doesn't trigger a listener update on init
+ case at.DISCOVERY_STREAM_CONFIG_SETUP:
+ return { ...prevState, config: action.data || {} };
+ case at.DISCOVERY_STREAM_LAYOUT_UPDATE:
+ return {
+ ...prevState,
+ lastUpdated: action.data.lastUpdated || null,
+ layout: action.data.layout || [],
+ };
+ case at.DISCOVERY_STREAM_COLLECTION_DISMISSIBLE_TOGGLE:
+ return {
+ ...prevState,
+ isCollectionDismissible: action.data.value,
+ };
+ case at.HIDE_PRIVACY_INFO:
+ return {
+ ...prevState,
+ isPrivacyInfoModalVisible: false,
+ };
+ case at.SHOW_PRIVACY_INFO:
+ return {
+ ...prevState,
+ isPrivacyInfoModalVisible: true,
+ };
+ case at.DISCOVERY_STREAM_LAYOUT_RESET:
+ return { ...INITIAL_STATE.DiscoveryStream, config: prevState.config };
+ case at.DISCOVERY_STREAM_FEEDS_UPDATE:
+ return {
+ ...prevState,
+ feeds: {
+ ...prevState.feeds,
+ loaded: true,
+ },
+ };
+ case at.DISCOVERY_STREAM_FEED_UPDATE:
+ const newData = {};
+ newData[action.data.url] = action.data.feed;
+ return {
+ ...prevState,
+ feeds: {
+ ...prevState.feeds,
+ data: {
+ ...prevState.feeds.data,
+ ...newData,
+ },
+ },
+ };
+ case at.DISCOVERY_STREAM_SPOCS_CAPS:
+ return {
+ ...prevState,
+ spocs: {
+ ...prevState.spocs,
+ frequency_caps: [...prevState.spocs.frequency_caps, ...action.data],
+ },
+ };
+ case at.DISCOVERY_STREAM_SPOCS_ENDPOINT:
+ return {
+ ...prevState,
+ spocs: {
+ ...INITIAL_STATE.DiscoveryStream.spocs,
+ spocs_endpoint:
+ action.data.url ||
+ INITIAL_STATE.DiscoveryStream.spocs.spocs_endpoint,
+ },
+ };
+ case at.DISCOVERY_STREAM_SPOCS_PLACEMENTS:
+ return {
+ ...prevState,
+ spocs: {
+ ...prevState.spocs,
+ placements:
+ action.data.placements ||
+ INITIAL_STATE.DiscoveryStream.spocs.placements,
+ },
+ };
+ case at.DISCOVERY_STREAM_SPOCS_UPDATE:
+ if (action.data) {
+ return {
+ ...prevState,
+ spocs: {
+ ...prevState.spocs,
+ lastUpdated: action.data.lastUpdated,
+ data: action.data.spocs,
+ loaded: true,
+ },
+ };
+ }
+ return prevState;
+ case at.DISCOVERY_STREAM_SPOC_BLOCKED:
+ return {
+ ...prevState,
+ spocs: {
+ ...prevState.spocs,
+ blocked: [...prevState.spocs.blocked, action.data.url],
+ },
+ };
+ case at.DISCOVERY_STREAM_LINK_BLOCKED:
+ return isNotReady()
+ ? prevState
+ : nextState(items =>
+ items.filter(item => item.url !== action.data.url)
+ );
+
+ case at.PLACES_SAVED_TO_POCKET:
+ const addPocketInfo = item => {
+ if (item.url === action.data.url) {
+ return Object.assign({}, item, {
+ open_url: action.data.open_url,
+ pocket_id: action.data.pocket_id,
+ context_type: "pocket",
+ });
+ }
+ return item;
+ };
+ return isNotReady()
+ ? prevState
+ : nextState(items => items.map(addPocketInfo));
+
+ case at.DELETE_FROM_POCKET:
+ case at.ARCHIVE_FROM_POCKET:
+ return isNotReady()
+ ? prevState
+ : nextState(items =>
+ items.filter(item => item.pocket_id !== action.data.pocket_id)
+ );
+
+ case at.PLACES_BOOKMARK_ADDED:
+ const updateBookmarkInfo = item => {
+ if (item.url === action.data.url) {
+ const { bookmarkGuid, bookmarkTitle, dateAdded } = action.data;
+ return Object.assign({}, item, {
+ bookmarkGuid,
+ bookmarkTitle,
+ bookmarkDateCreated: dateAdded,
+ context_type: "bookmark",
+ });
+ }
+ return item;
+ };
+ return isNotReady()
+ ? prevState
+ : nextState(items => items.map(updateBookmarkInfo));
+
+ case at.PLACES_BOOKMARK_REMOVED:
+ const removeBookmarkInfo = item => {
+ if (item.url === action.data.url) {
+ const newSite = Object.assign({}, item);
+ delete newSite.bookmarkGuid;
+ delete newSite.bookmarkTitle;
+ delete newSite.bookmarkDateCreated;
+ if (!newSite.context_type || newSite.context_type === "bookmark") {
+ newSite.context_type = "removedBookmark";
+ }
+ return newSite;
+ }
+ return item;
+ };
+ return isNotReady()
+ ? prevState
+ : nextState(items => items.map(removeBookmarkInfo));
+ case at.PREF_CHANGED:
+ if (action.data.name === PREF_COLLECTION_DISMISSIBLE) {
+ return {
+ ...prevState,
+ isCollectionDismissible: action.data.value,
+ };
+ }
+ return prevState;
+ default:
+ return prevState;
+ }
+}
+
+function Search(prevState = INITIAL_STATE.Search, action) {
+ switch (action.type) {
+ case at.HIDE_SEARCH:
+ return Object.assign({ ...prevState, hide: true });
+ case at.FAKE_FOCUS_SEARCH:
+ return Object.assign({ ...prevState, fakeFocus: true });
+ case at.SHOW_SEARCH:
+ return Object.assign({ ...prevState, hide: false, fakeFocus: false });
+ default:
+ return prevState;
+ }
+}
+
+this.INITIAL_STATE = INITIAL_STATE;
+this.TOP_SITES_DEFAULT_ROWS = TOP_SITES_DEFAULT_ROWS;
+this.TOP_SITES_MAX_SITES_PER_ROW = TOP_SITES_MAX_SITES_PER_ROW;
+
+this.reducers = {
+ TopSites,
+ App,
+ ASRouter,
+ Snippets,
+ Prefs,
+ Dialog,
+ Sections,
+ Pocket,
+ Personalization,
+ DiscoveryStream,
+ Search,
+};
+
+const EXPORTED_SYMBOLS = [
+ "reducers",
+ "INITIAL_STATE",
+ "insertPinned",
+ "TOP_SITES_DEFAULT_ROWS",
+ "TOP_SITES_MAX_SITES_PER_ROW",
+];
diff --git a/browser/components/newtab/components.conf b/browser/components/newtab/components.conf
new file mode 100644
index 0000000000..25466d28e3
--- /dev/null
+++ b/browser/components/newtab/components.conf
@@ -0,0 +1,14 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+Classes = [
+ {
+ 'cid': '{dfcd2adc-7867-4d3a-ba70-17501f208142}',
+ 'contract_ids': ['@mozilla.org/browser/aboutnewtab-service;1'],
+ 'jsm': 'resource:///modules/AboutNewTabService.jsm',
+ 'constructor': 'AboutNewTabStubService',
+ },
+]
diff --git a/browser/components/newtab/components/CustomElements/paragraph.js b/browser/components/newtab/components/CustomElements/paragraph.js
new file mode 100644
index 0000000000..a8e3329801
--- /dev/null
+++ b/browser/components/newtab/components/CustomElements/paragraph.js
@@ -0,0 +1,72 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+// This is loaded into all XUL windows. Wrap in a block to prevent
+// leaking to window scope.
+{
+ const { RemoteL10n } = ChromeUtils.import(
+ "resource://activity-stream/lib/RemoteL10n.jsm"
+ );
+ class MozTextParagraph extends HTMLElement {
+ constructor() {
+ super();
+
+ this._content = null;
+ }
+
+ get fluentAttributeValues() {
+ const attributes = {};
+ for (let name of this.getAttributeNames()) {
+ if (name.startsWith("fluent-variable-")) {
+ let value = this.getAttribute(name);
+ // Attribute value is a string, in some cases that is not useful
+ // for example instantiating a Date object will fail. We try to
+ // convert all possible integers back.
+ if (value.match(/^\d+/)) {
+ value = parseInt(value, 10);
+ }
+ attributes[name.replace(/^fluent-variable-/, "")] = value;
+ }
+ }
+
+ return attributes;
+ }
+
+ render() {
+ if (this.getAttribute("fluent-remote-id") && this._content) {
+ RemoteL10n.l10n.setAttributes(
+ this._content,
+ this.getAttribute("fluent-remote-id"),
+ this.fluentAttributeValues
+ );
+ }
+ }
+
+ static get observedAttributes() {
+ return ["fluent-remote-id"];
+ }
+
+ attributeChangedCallback(name, oldValue, newValue) {
+ this.render();
+ }
+
+ connectedCallback() {
+ if (this.shadowRoot) {
+ this.render();
+ return;
+ }
+
+ const shadowRoot = this.attachShadow({ mode: "open" });
+ this._content = document.createElement("span");
+ shadowRoot.appendChild(this._content);
+
+ this.render();
+ RemoteL10n.l10n.translateFragment(this._content);
+ }
+ }
+
+ customElements.define("remote-text", MozTextParagraph);
+}
diff --git a/browser/components/newtab/content-src/.eslintrc.js b/browser/components/newtab/content-src/.eslintrc.js
new file mode 100644
index 0000000000..bf7904cc43
--- /dev/null
+++ b/browser/components/newtab/content-src/.eslintrc.js
@@ -0,0 +1,12 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* eslint-disable import/no-commonjs */
+
+module.exports = {
+ rules: {
+ "import/no-commonjs": 2,
+ "react/jsx-no-bind": 0,
+ },
+};
diff --git a/browser/components/newtab/content-src/aboutwelcome/aboutwelcome.jsx b/browser/components/newtab/content-src/aboutwelcome/aboutwelcome.jsx
new file mode 100644
index 0000000000..d9503584b9
--- /dev/null
+++ b/browser/components/newtab/content-src/aboutwelcome/aboutwelcome.jsx
@@ -0,0 +1,188 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import React from "react";
+import ReactDOM from "react-dom";
+import { MultiStageAboutWelcome } from "./components/MultiStageAboutWelcome";
+import { SimpleAboutWelcome } from "./components/SimpleAboutWelcome";
+import { ReturnToAMO } from "./components/ReturnToAMO";
+
+import {
+ AboutWelcomeUtils,
+ DEFAULT_WELCOME_CONTENT,
+} from "../lib/aboutwelcome-utils";
+
+class AboutWelcome extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.state = { metricsFlowUri: null };
+ this.fetchFxAFlowUri = this.fetchFxAFlowUri.bind(this);
+ this.handleStartBtnClick = this.handleStartBtnClick.bind(this);
+ }
+
+ async fetchFxAFlowUri() {
+ this.setState({ metricsFlowUri: await window.AWGetFxAMetricsFlowURI() });
+ }
+
+ componentDidMount() {
+ this.fetchFxAFlowUri();
+
+ // Record impression with performance data after allowing the page to load
+ const recordImpression = domState => {
+ const { domComplete, domInteractive } = performance
+ .getEntriesByType("navigation")
+ .pop();
+ window.AWSendEventTelemetry({
+ event: "IMPRESSION",
+ event_context: {
+ domComplete,
+ domInteractive,
+ mountStart: performance.getEntriesByName("mount").pop().startTime,
+ domState,
+ source: this.props.UTMTerm,
+ page: "about:welcome",
+ },
+ message_id: this.props.messageId,
+ });
+ };
+ if (document.readyState === "complete") {
+ // Page might have already triggered a load event because it waited for async data,
+ // e.g., attribution, so the dom load timing could be of a empty content
+ // with domState in telemetry captured as 'complete'
+ recordImpression(document.readyState);
+ } else {
+ window.addEventListener("load", () => recordImpression("load"), {
+ once: true,
+ });
+ }
+
+ // Captures user has seen about:welcome by setting
+ // firstrun.didSeeAboutWelcome pref to true and capturing welcome UI unique messageId
+ window.AWSendToParent("SET_WELCOME_MESSAGE_SEEN", this.props.messageId);
+ }
+
+ handleStartBtnClick() {
+ AboutWelcomeUtils.handleUserAction(this.props.startButton.action);
+ const ping = {
+ event: "CLICK_BUTTON",
+ event_context: {
+ source: this.props.startButton.message_id,
+ page: "about:welcome",
+ },
+ message_id: this.props.messageId,
+ id: "ABOUT_WELCOME",
+ };
+ window.AWSendEventTelemetry(ping);
+ }
+
+ render() {
+ const { props } = this;
+ if (props.template === "simplified") {
+ return (
+ <SimpleAboutWelcome
+ metricsFlowUri={this.state.metricsFlowUri}
+ message_id={props.messageId}
+ utm_term={props.UTMTerm}
+ title={props.title}
+ subtitle={props.subtitle}
+ cards={props.cards}
+ startButton={props.startButton}
+ handleStartBtnClick={this.handleStartBtnClick}
+ />
+ );
+ } else if (props.template === "return_to_amo") {
+ return (
+ <ReturnToAMO
+ message_id={props.messageId}
+ name={props.name}
+ url={props.url}
+ iconURL={props.iconURL}
+ />
+ );
+ }
+
+ return (
+ <MultiStageAboutWelcome
+ screens={props.screens}
+ metricsFlowUri={this.state.metricsFlowUri}
+ message_id={props.messageId}
+ utm_term={props.UTMTerm}
+ />
+ );
+ }
+}
+
+AboutWelcome.defaultProps = DEFAULT_WELCOME_CONTENT;
+
+// Computes messageId and UTMTerm info used in telemetry
+function ComputeTelemetryInfo(welcomeContent, experimentId, branchId) {
+ let messageId =
+ welcomeContent.template === "return_to_amo"
+ ? "RTAMO_DEFAULT_WELCOME"
+ : "DEFAULT_ABOUTWELCOME";
+ let UTMTerm = "default";
+
+ if (welcomeContent.id) {
+ messageId = welcomeContent.id.toUpperCase();
+ }
+
+ if (experimentId && branchId) {
+ UTMTerm = `${experimentId}-${branchId}`.toLowerCase();
+ }
+ return {
+ messageId,
+ UTMTerm,
+ };
+}
+
+async function retrieveRenderContent() {
+ // Check for override content in pref browser.aboutwelcome.overrideContent
+ let aboutWelcomeProps = await window.AWGetWelcomeOverrideContent();
+ if (aboutWelcomeProps?.template) {
+ let { messageId, UTMTerm } = ComputeTelemetryInfo(aboutWelcomeProps);
+ return { aboutWelcomeProps, messageId, UTMTerm };
+ }
+
+ // Check for experiment and retrieve content
+ const { slug, branch } = await window.AWGetExperimentData();
+ aboutWelcomeProps = branch?.feature ? branch.feature.value : {};
+
+ // Check if there is any attribution data, this could take a while to await in series
+ // especially when there is an add-on that requires remote lookup
+ // Moving RTAMO as part of another screen of multistage is one option to fix the delay
+ // as it will allow the initial page to be fast while we fetch attribution data in parallel for a later screen.
+ const attribution = await window.AWGetAttributionData();
+ if (attribution?.template) {
+ aboutWelcomeProps = {
+ ...aboutWelcomeProps,
+ // If part of an experiment, render experiment template
+ template: aboutWelcomeProps?.template
+ ? aboutWelcomeProps.template
+ : attribution.template,
+ ...attribution.extraProps,
+ };
+ }
+
+ let { messageId, UTMTerm } = ComputeTelemetryInfo(
+ aboutWelcomeProps,
+ slug,
+ branch && branch.slug
+ );
+ return { aboutWelcomeProps, messageId, UTMTerm };
+}
+
+async function mount() {
+ let { aboutWelcomeProps, messageId, UTMTerm } = await retrieveRenderContent();
+ ReactDOM.render(
+ <AboutWelcome
+ messageId={messageId}
+ UTMTerm={UTMTerm}
+ {...aboutWelcomeProps}
+ />,
+ document.getElementById("root")
+ );
+}
+
+performance.mark("mount");
+mount();
diff --git a/browser/components/newtab/content-src/aboutwelcome/aboutwelcome.scss b/browser/components/newtab/content-src/aboutwelcome/aboutwelcome.scss
new file mode 100644
index 0000000000..501b57952f
--- /dev/null
+++ b/browser/components/newtab/content-src/aboutwelcome/aboutwelcome.scss
@@ -0,0 +1,673 @@
+// sass-lint:disable no-css-comments
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+@import '../styles/normalize';
+@import '../styles/OnboardingImages';
+
+$break-point-medium: 610px;
+$break-point-large: 866px;
+$break-point-widest: 1122px;
+$logo-size: 112px;
+
+html {
+ height: 100%;
+}
+
+body {
+ // sass-lint:disable no-color-literals
+ --grey-subtitle: #4A4A4F;
+ --grey-subtitle-1: #696977;
+ --newtab-background-color: #EDEDF0;
+ --newtab-background-color-1: #F9F9FA;
+ --newtab-text-primary-color: #0C0C0D;
+ --newtab-text-conditional-color: #4A4A4F;
+ --newtab-button-primary-color: #0060DF;
+ --newtab-button-secondary-color: #0060DF;
+ --newtab-card-background-color: #FFF;
+ --newtab-card-shadow: 0 1px 4px 0 rgba(12, 12, 13, 0.4);
+ --tiles-theme-section-border-width: 1px;
+ --welcome-header-text-color: #2B2156;
+ --welcome-header-text-color-1: #20133A;
+ --welcome-card-button-background-color: rgba(12, 12, 13, 0.1);
+ --welcome-card-button-background-hover-color: rgba(12, 12, 13, 0.2);
+ --welcome-card-button-background-active-color: rgba(12, 12, 13, 0.3);
+ --welcome-button-box-shadow-color: #0A84FF;
+ --welcome-button-box-shadow-inset-color: rgba(10, 132, 255, 0.3);
+ --welcome-button-text-color: #FFF;
+ --welcome-button-background-hover-color: #003EAA;
+ --welcome-button-background-active-color: #002275;
+ --about-welcome-media-fade: linear-gradient(transparent, transparent 35%, #F9F9FA, #F9F9FA);
+
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Ubuntu',
+ 'Helvetica Neue', sans-serif;
+ font-size: 16px;
+ position: relative;
+ /* these two rules fix test failures in
+ "browser_ext_themes_ntp_colors" & "browser_ext_themes_ntp_colors_perwindow".*/
+ color: var(--newtab-text-primary-color);
+ background-color: var(--newtab-background-color);
+
+ &[lwt-newtab-brighttext] {
+ --newtab-background-color: #2A2A2E;
+ --newtab-background-color-1: #1D1133;
+ --newtab-text-primary-color: #F9F9FA;
+ --newtab-text-conditional-color: #F9F9FA;
+ --grey-subtitle-1: #FFF;
+ --newtab-button-primary-color: #0060DF;
+ --newtab-button-secondary-color: #FFF;
+ --newtab-card-background-color: #38383D;
+ --newtab-card-shadow: 0 1px 8px 0 rgba(12, 12, 13, 0.4);
+ --welcome-header-text-color: rgba(255, 255, 255, 0.6);
+ --welcome-header-text-color-1: #7542E5;
+ --welcome-card-button-background-color: rgba(12, 12, 13, 0.3);
+ --welcome-card-button-background-hover-color: rgba(12, 12, 13, 0.5);
+ --welcome-card-button-background-active-color: rgba(12, 12, 13, 0.7);
+ --welcome-button-box-shadow-color: #0A84FF;
+ --about-welcome-media-fade: linear-gradient(transparent, transparent 35%, #1D1133, #1D1133);
+ }
+}
+
+.welcomeCardGrid {
+ margin: 0;
+ margin-top: 32px;
+ display: grid;
+ grid-gap: 32px;
+ transition: opacity 0.4s;
+ transition-delay: 0.1s;
+ grid-auto-rows: 1fr;
+
+ @media (min-width: $break-point-medium) {
+ grid-template-columns: repeat(auto-fit, 224px);
+ }
+
+ @media (min-width: $break-point-widest) {
+ grid-template-columns: repeat(auto-fit, 309px);
+ }
+}
+
+.welcomeContainer {
+ text-align: center;
+
+ @media (min-width: $break-point-medium) {
+ max-height: 1000px;
+ }
+
+ h1 {
+ font-size: 36px;
+ font-weight: 200;
+ margin: 0 0 40px;
+ color: var(--welcome-header-text-color);
+ }
+
+ .welcome-title {
+ margin-bottom: 5px;
+ line-height: 52px;
+ }
+
+ .welcome-subtitle {
+ font-size: 28px;
+ font-weight: 200;
+ margin: 6px 0 0;
+ color: var(--grey-subtitle);
+ line-height: 42px;
+ }
+}
+
+.welcomeContainerInner {
+ margin: auto;
+ padding: 40px 25px;
+
+ @media (min-width: $break-point-medium) {
+ width: 530px;
+ }
+
+ @media (min-width: $break-point-large) {
+ width: 786px;
+ }
+
+ @media (min-width: $break-point-widest) {
+ width: 1042px;
+ }
+}
+
+.welcomeCard {
+ position: relative;
+ background: var(--newtab-card-background-color);
+ border-radius: 4px;
+ box-shadow: var(--newtab-card-shadow);
+ font-size: 13px;
+ padding: 20px 20px 60px;
+
+ @media (max-width: $break-point-large) {
+ padding: 20px;
+ }
+
+ @media (min-width: $break-point-widest) {
+ font-size: 15px;
+ }
+}
+
+.welcomeCard .onboardingTitle {
+ font-weight: normal;
+ color: var(--newtab-text-primary-color);
+ margin: 10px 0 4px;
+ font-size: 15px;
+
+ @media (min-width: $break-point-widest) {
+ font-size: 18px;
+ }
+}
+
+.welcomeCard .onboardingText {
+ margin: 0 0 60px;
+ color: var(--newtab-text-conditional-color);
+ line-height: 1.5;
+ font-weight: 200;
+}
+
+.welcomeCard .onboardingButton {
+ color: var(--newtab-text-conditional-color);
+ background: var(--welcome-card-button-background-color);
+ border: 0;
+ border-radius: 4px;
+ margin: 14px;
+ min-width: 70%;
+ padding: 6px 14px;
+ white-space: pre-wrap;
+ cursor: pointer;
+
+ &:focus,
+ &:hover {
+ box-shadow: none;
+ background: var(--welcome-card-button-background-hover-color);
+ }
+
+ &:focus {
+ outline: dotted 1px;
+ }
+
+ &:active {
+ background: var(--welcome-card-button-background-active-color);
+ }
+}
+
+.welcomeCard .onboardingButtonContainer {
+ position: absolute;
+ bottom: 16px;
+ left: 0;
+ width: 100%;
+ text-align: center;
+}
+
+.onboardingMessageImage {
+ height: 112px;
+ width: 180px;
+ background-size: auto 140px;
+ background-position: center center;
+ background-repeat: no-repeat;
+ display: inline-block;
+
+ @media (max-width: $break-point-large) {
+ height: 75px;
+ min-width: 80px;
+ background-size: 140px;
+ }
+}
+
+.start-button {
+ border: 0;
+ font-size: 15px;
+ font-family: inherit;
+ font-weight: 200;
+ margin-inline-start: 12px;
+ margin: 30px 0 25px;
+ padding: 8px 16px;
+ white-space: nowrap;
+ background-color: var(--newtab-button-primary-color);
+ color: var(--welcome-button-text-color);
+ cursor: pointer;
+ border-radius: 2px;
+
+ &:focus {
+ background: var(--welcome-button-background-hover-color);
+ box-shadow: 0 0 0 1px var(--welcome-button-box-shadow-inset-color) inset,
+ 0 0 0 1px var(--welcome-button-box-shadow-inset-color),
+ 0 0 0 4px var(--welcome-button-box-shadow-color);
+ }
+
+ &:hover {
+ background: var(--welcome-button-background-hover-color);
+ }
+
+ &:active {
+ background: var(--welcome-button-background-active-color);
+ }
+}
+
+
+.onboardingContainer {
+ text-align: center;
+ overflow-x: auto;
+ height: 100vh;
+ background-color: var(--newtab-background-color-1);
+
+ .screen {
+ display: flex;
+ flex-flow: column nowrap;
+ height: 100%;
+ }
+
+ .brand-logo {
+ background: url('chrome://branding/content/about-logo.svg') top
+ center / $logo-size no-repeat;
+ padding: $logo-size 0 20px;
+ margin-top: 60px;
+
+ &.cta-top {
+ margin-top: 25px;
+ }
+ }
+
+ .welcomeZap {
+ span {
+ position: relative;
+ z-index: 1;
+ white-space: nowrap;
+ }
+
+ .zap {
+ &::after {
+ display: block;
+ background-repeat: no-repeat;
+ background-size: 100% 100%;
+ content: '';
+ position: absolute;
+ top: calc(100% - 0.15em);
+ width: 100%;
+ height: 0.3em;
+ left: 0;
+ z-index: -1;
+ }
+
+ &.short::after {
+ background-image: url('chrome://activity-stream/content/data/content/assets/short-zap.svg');
+ }
+
+ &.long::after {
+ background-image: url('chrome://activity-stream/content/data/content/assets/long-zap.svg');
+ }
+ }
+
+
+ }
+
+ .welcome-text {
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ align-items: center;
+ margin-bottom: 20px;
+
+ h1,
+ h2 {
+ width: 860px;
+ @media (max-width: $break-point-large) {
+ width: 530px;
+ }
+
+ @media (max-width: $break-point-medium) {
+ width: 430px;
+ }
+ }
+
+ h1 {
+ font-size: 48px;
+ line-height: 56px;
+ font-weight: bold;
+ margin: 0 6px;
+ color: var(--welcome-header-text-color-1);
+ }
+
+ h2 {
+ font-size: 18px;
+ font-weight: normal;
+ margin: 10px 6px 0;
+ color: var(--grey-subtitle-1);
+ line-height: 28px;
+ max-width: 750px;
+ letter-spacing: -0.01em;
+ }
+
+ img {
+ margin-inline: 2px;
+ width: 20px;
+ height: 20px;
+ }
+ }
+
+ .tiles-theme-container {
+ margin: 10px auto;
+ border: 0;
+ }
+
+ .sr-only {
+ opacity: 0;
+ overflow: hidden;
+ position: absolute;
+
+ &.input {
+ height: 1px;
+ width: 1px;
+ }
+ }
+
+ .tiles-theme-section {
+ display: grid;
+ grid-gap: 21px;
+ grid-template-columns: repeat(4, auto);
+
+ /* --newtab-background-color-1 will be invisible, but it's necessary to
+ * keep the content from jumping around when it gets focus-within and
+ * does sprout a dotted border. This way it keeps a 1 pixel wide border
+ * either way so things don't change position.
+ */
+ border: var(--tiles-theme-section-border-width)
+ solid
+ var(--newtab-background-color-1);
+
+ @media (max-width: $break-point-medium) {
+ grid-template-columns: repeat(2, auto);
+ }
+
+ &:focus-within {
+ border: var(--tiles-theme-section-border-width) dotted;
+ }
+
+ .theme {
+ display: flex;
+ flex-direction: column;
+ padding: 0;
+ width: 180px;
+ height: 145px;
+ color: #000;
+ background-color: #FFF;
+ box-shadow: 0 1px 4px 0 rgba(12, 12, 13, 0.4);
+ border-radius: 4px;
+ cursor: pointer;
+
+ .icon {
+ background-size: cover;
+ border-top-left-radius: 4px;
+ border-top-right-radius: 4px;
+ height: 91px;
+
+ &:dir(rtl) {
+ transform: scaleX(-1);
+ }
+
+ &.light {
+ background-image: url('chrome://mozapps/content/extensions/firefox-compact-light.svg');
+ }
+
+ &.dark {
+ background-image: url('chrome://mozapps/content/extensions/firefox-compact-dark.svg');
+ }
+
+ &.automatic {
+ background-image: url('chrome://mozapps/content/extensions/default-theme.svg');
+ }
+
+ &.alpenglow {
+ background-image: url('chrome://mozapps/content/extensions/firefox-alpenglow.svg');
+ }
+ }
+
+ .text {
+ display: flex;
+ font-size: 14px;
+ font-weight: bold;
+ line-height: 22px;
+ margin-inline-start: 12px;
+ margin-top: 9px;
+ }
+
+ &.selected {
+ outline: 4px solid #0090ED;
+ outline-offset: -4px;
+ }
+
+ &:focus,
+ &:active {
+ outline: 4px solid #0090ED;
+ outline-offset: -4px;
+ }
+ }
+ }
+
+ .tiles-container {
+ margin: 10px auto;
+
+ &.info {
+ padding: 6px 12px 12px;
+
+ &:hover,
+ &:focus {
+ background-color: rgba(217, 217, 227, 0.3);
+ border-radius: 4px;
+ }
+ }
+ }
+
+ .tiles-topsites-section {
+ $host-size: 12px;
+ $tile-size: 96px;
+
+ display: grid;
+ grid-gap: $tile-size / 4;
+ grid-template-columns: repeat(5, auto);
+
+ @media (max-width: $break-point-medium) {
+ grid-template-columns: repeat(3, auto);
+ }
+
+ .site {
+ width: $tile-size;
+ }
+
+ .icon {
+ background-size: cover;
+ border-radius: 4px;
+ box-shadow: var(--newtab-card-shadow);
+ color: rgba(255, 255, 255, 0.5);
+ font-size: $host-size * 2;
+ font-weight: bold;
+ height: $tile-size;
+ line-height: $tile-size;
+ }
+
+ .host {
+ font-size: $host-size;
+ line-height: $host-size * 3;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+
+ .site:nth-child(1) .icon {
+ background-color: #7542E5;
+ }
+
+ .site:nth-child(2) .icon {
+ background-color: #952BB9;
+ }
+
+ .site:nth-child(3) .icon {
+ background-color: #E31587;
+ }
+
+ .site:nth-child(4) .icon {
+ background-color: #E25920;
+ }
+
+ .site:nth-child(5) .icon {
+ background-color: #0250BB;
+ }
+ }
+
+ // "tiles-media-section" styles here will support tiles of type
+ // "video" when the screen JSON it set in the below format:
+
+ // "tiles": {
+ // "type": "video",
+ // "source": {
+ // "default" : "<media-file-uri>",
+ // "dark" : "<media-file-dark-mode-uri>"
+ // }
+ // }
+
+ .tiles-media-section {
+ align-self: center;
+ position: relative;
+ margin-top: -12px;
+ margin-bottom: -155px;
+
+ .fade {
+ height: 390px;
+ width: 800px;
+ position: absolute;
+ background-image: var(--about-welcome-media-fade);
+ }
+
+ .media {
+ height: 390px;
+ width: 800px;
+ }
+
+ &.privacy {
+ background: top no-repeat url('chrome://activity-stream/content/data/content/assets/firefox-protections.svg');
+ height: 200px;
+ width: 800px;
+ margin: 0;
+
+ &.media {
+ opacity: 0;
+ }
+ }
+ }
+
+ button {
+ font-family: inherit;
+ cursor: pointer;
+ border: 0;
+ border-radius: 4px;
+
+ &.primary {
+ font-size: 16px;
+ margin-inline-start: 12px;
+ margin: 20px 0 0;
+ padding: 12px 20px;
+ white-space: nowrap;
+ background-color: var(--newtab-button-primary-color);
+ color: var(--welcome-button-text-color);
+ fill: currentColor;
+ position: relative;
+ z-index: 1;
+ // This transparent border will show up in Windows High Contrast Mode to improve accessibility.
+ border: 1px solid transparent;
+
+ &:focus {
+ background: var(--welcome-button-background-hover-color);
+ box-shadow: 0 0 0 4px var(--welcome-button-box-shadow-color);
+ }
+
+ &:hover {
+ background: var(--welcome-button-background-hover-color);
+ }
+
+ &:active {
+ background: var(--welcome-button-background-active-color);
+ }
+ }
+
+ &.secondary {
+ background-color: initial;
+ text-decoration: underline;
+ display: block;
+ padding: 0;
+ width: auto;
+ color: var(--newtab-button-secondary-color);
+ margin-top: 14px;
+
+ &:hover,
+ &:active {
+ background-color: initial;
+ }
+ }
+ }
+
+ .secondary-cta {
+ display: flex;
+ flex-direction: row;
+ justify-content: center;
+ font-size: 14px;
+
+ &.top {
+ justify-content: end;
+ align-items: end;
+ padding-inline-end: 30px;
+ padding-top: 4px;
+
+ @media (max-width: $break-point-medium) {
+ justify-content: center;
+ }
+ }
+
+ span {
+ color: var(--grey-subtitle-1);
+ margin: 0 4px;
+ }
+ }
+
+ .helptext {
+ padding: 1em;
+ text-align: center;
+ color: var(--grey-subtitle-1);
+ font-size: 12px;
+ line-height: 18px;
+
+ &.default {
+ align-self: center;
+ max-width: 40%;
+ }
+ }
+
+ .steps {
+ display: flex;
+ flex-direction: row;
+ justify-content: center;
+ margin-top: auto;
+ padding: 32px 0 66px;
+ z-index: 1;
+
+ &.has-helptext {
+ padding-bottom: 0;
+ }
+
+ .indicator {
+ width: 60px;
+ height: 4px;
+ margin-inline-end: 4px;
+ margin-inline-start: 4px;
+ background: var(--grey-subtitle-1);
+ border-radius: 5px;
+ // This transparent border will show up in Windows High Contrast Mode to improve accessibility.
+ border: 1px solid transparent;
+ opacity: 0.25;
+
+ &.current {
+ opacity: 1;
+ }
+ }
+ }
+}
diff --git a/browser/components/newtab/content-src/aboutwelcome/components/FxCards.jsx b/browser/components/newtab/content-src/aboutwelcome/components/FxCards.jsx
new file mode 100644
index 0000000000..4275c59c8f
--- /dev/null
+++ b/browser/components/newtab/content-src/aboutwelcome/components/FxCards.jsx
@@ -0,0 +1,83 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import React from "react";
+import { addUtmParams } from "../../asrouter/templates/FirstRun/addUtmParams";
+import { OnboardingCard } from "../../asrouter/templates/OnboardingMessage/OnboardingMessage";
+import { AboutWelcomeUtils } from "../../lib/aboutwelcome-utils";
+
+export class FxCards extends React.PureComponent {
+ constructor(props) {
+ super(props);
+
+ this.state = { flowParams: null };
+
+ this.fetchFxAFlowParams = this.fetchFxAFlowParams.bind(this);
+ this.onCardAction = this.onCardAction.bind(this);
+ }
+
+ componentDidUpdate() {
+ this.fetchFxAFlowParams();
+ }
+
+ componentDidMount() {
+ this.fetchFxAFlowParams();
+ }
+
+ async fetchFxAFlowParams() {
+ if (this.state.flowParams || !this.props.metricsFlowUri) {
+ return;
+ }
+
+ const flowParams = await AboutWelcomeUtils.fetchFlowParams(
+ this.props.metricsFlowUri
+ );
+
+ this.setState({ flowParams });
+ }
+
+ onCardAction(action) {
+ let { type, data } = action;
+ let UTMTerm = `aboutwelcome-${this.props.utm_term}-card`;
+
+ if (action.type === "OPEN_URL") {
+ let url = new URL(action.data.args);
+ addUtmParams(url, UTMTerm);
+
+ if (action.addFlowParams && this.state.flowParams) {
+ url.searchParams.append("device_id", this.state.flowParams.deviceId);
+ url.searchParams.append("flow_id", this.state.flowParams.flowId);
+ url.searchParams.append(
+ "flow_begin_time",
+ this.state.flowParams.flowBeginTime
+ );
+ }
+
+ data = { ...data, args: url.toString() };
+ }
+
+ AboutWelcomeUtils.handleUserAction({ type, data });
+ }
+
+ render() {
+ const { props } = this;
+ return (
+ <React.Fragment>
+ <div className={`welcomeCardGrid show`}>
+ {props.cards.map(card => (
+ <OnboardingCard
+ key={card.id}
+ message={card}
+ className="welcomeCard"
+ sendUserActionTelemetry={props.sendTelemetry}
+ onAction={this.onCardAction}
+ UISurface="ABOUT_WELCOME"
+ {...card}
+ />
+ ))}
+ </div>
+ </React.Fragment>
+ );
+ }
+}
diff --git a/browser/components/newtab/content-src/aboutwelcome/components/HeroText.jsx b/browser/components/newtab/content-src/aboutwelcome/components/HeroText.jsx
new file mode 100644
index 0000000000..bb3a296d54
--- /dev/null
+++ b/browser/components/newtab/content-src/aboutwelcome/components/HeroText.jsx
@@ -0,0 +1,19 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import React from "react";
+import { Localized } from "./MSLocalized";
+
+export const HeroText = props => {
+ return (
+ <React.Fragment>
+ <Localized text={props.title}>
+ <h1 className="welcome-title" />
+ </Localized>
+ <Localized text={props.subtitle}>
+ <h2 className="welcome-subtitle" />
+ </Localized>
+ </React.Fragment>
+ );
+};
diff --git a/browser/components/newtab/content-src/aboutwelcome/components/MSLocalized.jsx b/browser/components/newtab/content-src/aboutwelcome/components/MSLocalized.jsx
new file mode 100644
index 0000000000..694a294028
--- /dev/null
+++ b/browser/components/newtab/content-src/aboutwelcome/components/MSLocalized.jsx
@@ -0,0 +1,50 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import React from "react";
+const MS_STRING_PROP = "string_id";
+
+/**
+ * Based on the .text prop, localizes an inner element if a string_id
+ * is provided, OR renders plain text, OR hides it if nothing is provided.
+ *
+ * Examples:
+ *
+ * Localized text
+ * ftl:
+ * title = Welcome
+ * jsx:
+ * <Localized text={{string_id: "title"}}><h1 /></Localized>
+ * output:
+ * <h1 data-l10n-id="title">Welcome</h1>
+ *
+ * Unlocalized text
+ * jsx:
+ * <Localized text="Welcome"><h1 /></Localized>
+ * output:
+ * <h1>Welcome</h1>
+ */
+
+export const Localized = ({ text, children }) => {
+ if (!text) {
+ return null;
+ }
+
+ let props = children ? children.props : {};
+ let textNode;
+
+ if (typeof text === "object" && text[MS_STRING_PROP]) {
+ props = { ...props };
+ props["data-l10n-id"] = text[MS_STRING_PROP];
+ } else if (typeof text === "string") {
+ textNode = text;
+ }
+
+ if (!children) {
+ return React.createElement("span", props, textNode);
+ } else if (textNode) {
+ return React.cloneElement(children, props, textNode);
+ }
+ return React.cloneElement(children, props);
+};
diff --git a/browser/components/newtab/content-src/aboutwelcome/components/MultiStageAboutWelcome.jsx b/browser/components/newtab/content-src/aboutwelcome/components/MultiStageAboutWelcome.jsx
new file mode 100644
index 0000000000..fde65d3673
--- /dev/null
+++ b/browser/components/newtab/content-src/aboutwelcome/components/MultiStageAboutWelcome.jsx
@@ -0,0 +1,445 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import React, { useState, useEffect, useRef } from "react";
+import { Localized } from "./MSLocalized";
+import { Zap } from "./Zap";
+import { AboutWelcomeUtils } from "../../lib/aboutwelcome-utils";
+import {
+ BASE_PARAMS,
+ addUtmParams,
+} from "../../asrouter/templates/FirstRun/addUtmParams";
+
+export const MultiStageAboutWelcome = props => {
+ const [index, setScreenIndex] = useState(0);
+ useEffect(() => {
+ // Send impression ping when respective screen first renders
+ props.screens.forEach(screen => {
+ if (index === screen.order) {
+ AboutWelcomeUtils.sendImpressionTelemetry(
+ `${props.message_id}_${screen.id}`
+ );
+ }
+ });
+
+ // Remember that a new screen has loaded for browser navigation
+ if (index > window.history.state) {
+ window.history.pushState(index, "");
+ }
+ }, [index]);
+
+ useEffect(() => {
+ // Switch to the screen tracked in state (null for initial state)
+ const handler = ({ state }) => setScreenIndex(Number(state));
+
+ // Handle page load, e.g., going back to about:welcome from about:home
+ handler(window.history);
+
+ // Watch for browser back/forward button navigation events
+ window.addEventListener("popstate", handler);
+ return () => window.removeEventListener("popstate", handler);
+ }, []);
+
+ const [flowParams, setFlowParams] = useState(null);
+ const { metricsFlowUri } = props;
+ useEffect(() => {
+ (async () => {
+ if (metricsFlowUri) {
+ setFlowParams(await AboutWelcomeUtils.fetchFlowParams(metricsFlowUri));
+ }
+ })();
+ }, [metricsFlowUri]);
+
+ // Transition to next screen, opening about:home on last screen button CTA
+ const handleTransition =
+ index < props.screens.length - 1
+ ? () => setScreenIndex(prevState => prevState + 1)
+ : () =>
+ AboutWelcomeUtils.handleUserAction({
+ type: "OPEN_ABOUT_PAGE",
+ data: { args: "home", where: "current" },
+ });
+
+ // Update top sites with default sites by region when region is available
+ const [region, setRegion] = useState(null);
+ useEffect(() => {
+ (async () => {
+ setRegion(await window.AWGetRegion());
+ })();
+ }, []);
+
+ // Get the active theme so the rendering code can make it selected
+ // by default.
+ const [activeTheme, setActiveTheme] = useState(null);
+ const [initialTheme, setInitialTheme] = useState(null);
+ useEffect(() => {
+ (async () => {
+ let theme = await window.AWGetSelectedTheme();
+ setInitialTheme(theme);
+ setActiveTheme(theme);
+ })();
+ }, []);
+
+ const useImportable = props.message_id.includes("IMPORTABLE");
+ // Track whether we have already sent the importable sites impression telemetry
+ const importTelemetrySent = useRef(false);
+ const [topSites, setTopSites] = useState([]);
+ useEffect(() => {
+ (async () => {
+ let DEFAULT_SITES = await window.AWGetDefaultSites();
+ const importable = JSON.parse(await window.AWGetImportableSites());
+ const showImportable = useImportable && importable.length >= 5;
+ if (!importTelemetrySent.current) {
+ AboutWelcomeUtils.sendImpressionTelemetry(`${props.message_id}_SITES`, {
+ display: showImportable ? "importable" : "static",
+ importable: importable.length,
+ });
+ importTelemetrySent.current = true;
+ }
+ setTopSites(
+ showImportable
+ ? { data: importable, showImportable }
+ : { data: DEFAULT_SITES, showImportable }
+ );
+ })();
+ }, [useImportable, region]);
+
+ return (
+ <React.Fragment>
+ <div className={`outer-wrapper onboardingContainer`}>
+ {props.screens.map(screen => {
+ return index === screen.order ? (
+ <WelcomeScreen
+ key={screen.id}
+ id={screen.id}
+ totalNumberOfScreens={props.screens.length}
+ order={screen.order}
+ content={screen.content}
+ navigate={handleTransition}
+ topSites={topSites}
+ messageId={`${props.message_id}_${screen.id}`}
+ UTMTerm={props.utm_term}
+ flowParams={flowParams}
+ activeTheme={activeTheme}
+ initialTheme={initialTheme}
+ setActiveTheme={setActiveTheme}
+ />
+ ) : null;
+ })}
+ </div>
+ </React.Fragment>
+ );
+};
+
+export class WelcomeScreen extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.handleAction = this.handleAction.bind(this);
+ }
+
+ handleOpenURL(action, flowParams, UTMTerm) {
+ let { type, data } = action;
+ if (type === "SHOW_FIREFOX_ACCOUNTS") {
+ let params = {
+ ...BASE_PARAMS,
+ utm_term: `aboutwelcome-${UTMTerm}-screen`,
+ };
+ if (action.addFlowParams && flowParams) {
+ params = {
+ ...params,
+ ...flowParams,
+ };
+ }
+ data = { ...data, extraParams: params };
+ } else if (type === "OPEN_URL") {
+ let url = new URL(data.args);
+ addUtmParams(url, `aboutwelcome-${UTMTerm}-screen`);
+ if (action.addFlowParams && flowParams) {
+ url.searchParams.append("device_id", flowParams.deviceId);
+ url.searchParams.append("flow_id", flowParams.flowId);
+ url.searchParams.append("flow_begin_time", flowParams.flowBeginTime);
+ }
+ data = { ...data, args: url.toString() };
+ }
+ AboutWelcomeUtils.handleUserAction({ type, data });
+ }
+
+ async handleAction(event) {
+ let { props } = this;
+
+ let targetContent =
+ props.content[event.currentTarget.value] || props.content.tiles;
+ if (!(targetContent && targetContent.action)) {
+ return;
+ }
+
+ // Send telemetry before waiting on actions
+ AboutWelcomeUtils.sendActionTelemetry(
+ props.messageId,
+ event.currentTarget.value
+ );
+
+ let { action } = targetContent;
+
+ if (["OPEN_URL", "SHOW_FIREFOX_ACCOUNTS"].includes(action.type)) {
+ this.handleOpenURL(action, props.flowParams, props.UTMTerm);
+ } else if (action.type) {
+ AboutWelcomeUtils.handleUserAction(action);
+ // Wait until migration closes to complete the action
+ if (action.type === "SHOW_MIGRATION_WIZARD") {
+ await window.AWWaitForMigrationClose();
+ AboutWelcomeUtils.sendActionTelemetry(props.messageId, "migrate_close");
+ }
+ }
+
+ // A special tiles.action.theme value indicates we should use the event's value vs provided value.
+ if (action.theme) {
+ let themeToUse =
+ action.theme === "<event>"
+ ? event.currentTarget.value
+ : this.props.initialTheme || action.theme;
+
+ this.props.setActiveTheme(themeToUse);
+ window.AWSelectTheme(themeToUse);
+ }
+
+ if (action.navigate) {
+ props.navigate();
+ }
+ }
+
+ renderSecondaryCTA(className) {
+ return (
+ <div
+ className={className ? `secondary-cta ${className}` : `secondary-cta`}
+ >
+ <Localized text={this.props.content.secondary_button.text}>
+ <span />
+ </Localized>
+ <Localized text={this.props.content.secondary_button.label}>
+ <button
+ className="secondary"
+ value="secondary_button"
+ onClick={this.handleAction}
+ />
+ </Localized>
+ </div>
+ );
+ }
+
+ renderTiles() {
+ switch (this.props.content.tiles.type) {
+ case "topsites":
+ return this.props.topSites && this.props.topSites.data ? (
+ <div
+ className={`tiles-container ${
+ this.props.content.tiles.info ? "info" : ""
+ }`}
+ >
+ <div
+ className="tiles-topsites-section"
+ name="topsites-section"
+ id="topsites-section"
+ aria-labelledby="helptext"
+ role="region"
+ >
+ {this.props.topSites.data
+ .slice(0, 5)
+ .map(({ icon, label, title }) => (
+ <div
+ className="site"
+ key={icon + label}
+ aria-label={title ? title : label}
+ role="img"
+ >
+ <div
+ className="icon"
+ style={
+ icon
+ ? {
+ backgroundColor: "transparent",
+ backgroundImage: `url(${icon})`,
+ }
+ : {}
+ }
+ >
+ {icon ? "" : label && label[0].toUpperCase()}
+ </div>
+ {this.props.content.tiles.showTitles && (
+ <div className="host">{title || label}</div>
+ )}
+ </div>
+ ))}
+ </div>
+ </div>
+ ) : null;
+ case "theme":
+ return this.props.content.tiles.data ? (
+ <div className="tiles-theme-container">
+ <div>
+ <fieldset className="tiles-theme-section">
+ <Localized text={this.props.content.subtitle}>
+ <legend className="sr-only" />
+ </Localized>
+ {this.props.content.tiles.data.map(
+ ({ theme, label, tooltip, description }) => (
+ <Localized
+ key={theme + label}
+ text={typeof tooltip === "object" ? tooltip : {}}
+ >
+ <label
+ className={`theme${
+ theme === this.props.activeTheme ? " selected" : ""
+ }`}
+ title={theme + label}
+ >
+ <Localized
+ text={
+ typeof description === "object" ? description : {}
+ }
+ >
+ <input
+ type="radio"
+ value={theme}
+ name="theme"
+ checked={theme === this.props.activeTheme}
+ className="sr-only input"
+ onClick={this.handleAction}
+ data-l10n-attrs="aria-description"
+ />
+ </Localized>
+ <div className={`icon ${theme}`} />
+ {label && (
+ <Localized text={label}>
+ <div className="text" />
+ </Localized>
+ )}
+ </label>
+ </Localized>
+ )
+ )}
+ </fieldset>
+ </div>
+ </div>
+ ) : null;
+ case "video":
+ return this.props.content.tiles.source ? (
+ <div
+ className={`tiles-media-section ${this.props.content.tiles.media_type}`}
+ >
+ <div className="fade" />
+ <video
+ className="media"
+ autoPlay="true"
+ loop="true"
+ muted="true"
+ src={
+ AboutWelcomeUtils.hasDarkMode()
+ ? this.props.content.tiles.source.dark
+ : this.props.content.tiles.source.default
+ }
+ />
+ </div>
+ ) : null;
+ case "image":
+ return this.props.content.tiles.source ? (
+ <div className={`${this.props.content.tiles.media_type}`}>
+ <img
+ src={
+ AboutWelcomeUtils.hasDarkMode() &&
+ this.props.content.tiles.source.dark
+ ? this.props.content.tiles.source.dark
+ : this.props.content.tiles.source.default
+ }
+ role="presentation"
+ alt=""
+ />
+ </div>
+ ) : null;
+ }
+ return null;
+ }
+
+ renderStepsIndicator() {
+ let steps = [];
+ for (let i = 0; i < this.props.totalNumberOfScreens; i++) {
+ let className = i === this.props.order ? "current" : "";
+ steps.push(<div key={i} className={`indicator ${className}`} />);
+ }
+ return steps;
+ }
+
+ renderHelpText() {
+ return (
+ <Localized text={this.props.content.help_text.text}>
+ <p
+ id="helptext"
+ className={`helptext ${this.props.content.help_text.position}`}
+ />
+ </Localized>
+ );
+ }
+
+ render() {
+ const { content, topSites } = this.props;
+ const hasSecondaryTopCTA =
+ content.secondary_button && content.secondary_button.position === "top";
+ const showImportableSitesDisclaimer =
+ content.tiles &&
+ content.tiles.type === "topsites" &&
+ topSites &&
+ topSites.showImportable;
+
+ return (
+ <main className={`screen ${this.props.id}`}>
+ {hasSecondaryTopCTA ? this.renderSecondaryCTA("top") : null}
+ <div className={`brand-logo ${hasSecondaryTopCTA ? "cta-top" : ""}`} />
+ <div className="welcome-text">
+ <Zap hasZap={content.zap} text={content.title} />
+ <Localized text={content.subtitle}>
+ <h2 />
+ </Localized>
+ </div>
+ {content.tiles ? this.renderTiles() : null}
+ <div>
+ <Localized
+ text={content.primary_button ? content.primary_button.label : null}
+ >
+ <button
+ className="primary"
+ value="primary_button"
+ onClick={this.handleAction}
+ />
+ </Localized>
+ </div>
+ {content.secondary_button && content.secondary_button.position !== "top"
+ ? this.renderSecondaryCTA()
+ : null}
+ {content.help_text && content.help_text.position === "default"
+ ? this.renderHelpText()
+ : null}
+ <nav
+ className={
+ (content.help_text && content.help_text.position === "footer") ||
+ showImportableSitesDisclaimer
+ ? "steps has-helptext"
+ : "steps"
+ }
+ data-l10n-id={"onboarding-welcome-steps-indicator"}
+ data-l10n-args={`{"current": ${parseInt(this.props.order, 10) +
+ 1}, "total": ${this.props.totalNumberOfScreens}}`}
+ >
+ {/* These empty elements are here to help trigger the nav for screen readers. */}
+ <br />
+ <p />
+ {this.renderStepsIndicator()}
+ </nav>
+ {(content.help_text && content.help_text.position === "footer") ||
+ showImportableSitesDisclaimer
+ ? this.renderHelpText()
+ : null}
+ </main>
+ );
+ }
+}
diff --git a/browser/components/newtab/content-src/aboutwelcome/components/ReturnToAMO.jsx b/browser/components/newtab/content-src/aboutwelcome/components/ReturnToAMO.jsx
new file mode 100644
index 0000000000..2d5501dc46
--- /dev/null
+++ b/browser/components/newtab/content-src/aboutwelcome/components/ReturnToAMO.jsx
@@ -0,0 +1,100 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import React from "react";
+import {
+ AboutWelcomeUtils,
+ DEFAULT_RTAMO_CONTENT,
+} from "../../lib/aboutwelcome-utils";
+import { Localized } from "./MSLocalized";
+
+export class ReturnToAMO extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onClickAddExtension = this.onClickAddExtension.bind(this);
+ this.handleStartBtnClick = this.handleStartBtnClick.bind(this);
+ }
+
+ onClickAddExtension() {
+ const { content, message_id, url } = this.props;
+ if (!content?.primary_button?.action?.data) {
+ return;
+ }
+
+ // Set add-on url in action.data.url property from JSON
+ content.primary_button.action.data.url = url;
+ AboutWelcomeUtils.handleUserAction(content.primary_button.action);
+ const ping = {
+ event: "INSTALL",
+ event_context: {
+ source: "ADD_EXTENSION_BUTTON",
+ page: "about:welcome",
+ },
+ message_id,
+ };
+ window.AWSendEventTelemetry(ping);
+ }
+
+ handleStartBtnClick() {
+ const { content, message_id } = this.props;
+ AboutWelcomeUtils.handleUserAction(content.startButton.action);
+ const ping = {
+ event: "CLICK_BUTTON",
+ event_context: {
+ source: content.startButton.message_id,
+ page: "about:welcome",
+ },
+ message_id,
+ };
+ window.AWSendEventTelemetry(ping);
+ }
+
+ render() {
+ const { content } = this.props;
+ if (!content) {
+ return null;
+ }
+ // For experiments, when needed below rendered UI allows settings hard coded strings
+ // directly inside JSON except for ReturnToAMOText which picks add-on name and icon from fluent string
+ return (
+ <div className="outer-wrapper onboardingContainer">
+ <main className="screen">
+ <div className="brand-logo" />
+ <div className="welcome-text">
+ <Localized text={content.subtitle}>
+ <h1 />
+ </Localized>
+ <Localized text={content.text}>
+ <h2
+ data-l10n-args={
+ this.props.name
+ ? JSON.stringify({ "addon-name": this.props.name })
+ : null
+ }
+ >
+ <img
+ data-l10n-name="icon"
+ src={this.props.iconURL}
+ role="presentation"
+ alt=""
+ />
+ </h2>
+ </Localized>
+ <Localized text={content.primary_button.label}>
+ <button onClick={this.onClickAddExtension} className="primary" />
+ </Localized>
+ <Localized text={content.startButton.label}>
+ <button
+ onClick={this.handleStartBtnClick}
+ className="secondary"
+ />
+ </Localized>
+ </div>
+ </main>
+ </div>
+ );
+ }
+}
+
+ReturnToAMO.defaultProps = DEFAULT_RTAMO_CONTENT;
diff --git a/browser/components/newtab/content-src/aboutwelcome/components/SimpleAboutWelcome.jsx b/browser/components/newtab/content-src/aboutwelcome/components/SimpleAboutWelcome.jsx
new file mode 100644
index 0000000000..4186cb2d69
--- /dev/null
+++ b/browser/components/newtab/content-src/aboutwelcome/components/SimpleAboutWelcome.jsx
@@ -0,0 +1,35 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import React from "react";
+import { HeroText } from "./HeroText";
+import { FxCards } from "./FxCards";
+import { Localized } from "./MSLocalized";
+
+export class SimpleAboutWelcome extends React.PureComponent {
+ render() {
+ const { props } = this;
+ return (
+ <div className="outer-wrapper welcomeContainer">
+ <div className="welcomeContainerInner">
+ <main>
+ <HeroText title={props.title} subtitle={props.subtitle} />
+ <FxCards
+ cards={props.cards}
+ metricsFlowUri={this.props.metricsFlowUri}
+ sendTelemetry={window.AWSendEventTelemetry}
+ utm_term={this.props.UTMTerm}
+ />
+ <Localized text={props.startButton.label}>
+ <button
+ className="start-button"
+ onClick={this.props.handleStartBtnClick}
+ />
+ </Localized>
+ </main>
+ </div>
+ </div>
+ );
+ }
+}
diff --git a/browser/components/newtab/content-src/aboutwelcome/components/Zap.jsx b/browser/components/newtab/content-src/aboutwelcome/components/Zap.jsx
new file mode 100644
index 0000000000..a067c4d7fe
--- /dev/null
+++ b/browser/components/newtab/content-src/aboutwelcome/components/Zap.jsx
@@ -0,0 +1,60 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import React, { useEffect } from "react";
+import { Localized } from "./MSLocalized";
+const MS_STRING_PROP = "string_id";
+const ZAP_SIZE_THRESHOLD = 160;
+
+function calculateZapLength() {
+ let span = document.querySelector(".zap");
+ if (!span) {
+ return;
+ }
+ let rect = span.getBoundingClientRect();
+ if (rect && rect.width > ZAP_SIZE_THRESHOLD) {
+ span.classList.add("long");
+ } else {
+ span.classList.add("short");
+ }
+}
+
+export const Zap = props => {
+ useEffect(() => {
+ requestAnimationFrame(() => calculateZapLength());
+ });
+
+ if (!props.text) {
+ return null;
+ }
+
+ if (props.hasZap) {
+ if (typeof props.text === "object" && props.text[MS_STRING_PROP]) {
+ return (
+ <Localized text={props.text}>
+ <h1 className="welcomeZap">
+ <span data-l10n-name="zap" className="zap" />
+ </h1>
+ </Localized>
+ );
+ } else if (typeof props.text === "string") {
+ // Parse string to zap style last word of the props.text
+ let titleArray = props.text.split(" ");
+ let lastWord = `${titleArray.pop()}`;
+ return (
+ <h1 className="welcomeZap">
+ {titleArray.join(" ").concat(" ")}
+ <span className="zap">{lastWord}</span>
+ </h1>
+ );
+ }
+ } else {
+ return (
+ <Localized text={props.text}>
+ <h1 />
+ </Localized>
+ );
+ }
+ return null;
+};
diff --git a/browser/components/newtab/content-src/activity-stream.jsx b/browser/components/newtab/content-src/activity-stream.jsx
new file mode 100644
index 0000000000..a49bfa7dce
--- /dev/null
+++ b/browser/components/newtab/content-src/activity-stream.jsx
@@ -0,0 +1,54 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { actionCreators as ac, actionTypes as at } from "common/Actions.jsm";
+import { Base } from "content-src/components/Base/Base";
+import { DetectUserSessionStart } from "content-src/lib/detect-user-session-start";
+import { initStore } from "content-src/lib/init-store";
+import { Provider } from "react-redux";
+import React from "react";
+import ReactDOM from "react-dom";
+import { reducers } from "common/Reducers.jsm";
+
+export const NewTab = ({ store }) => (
+ <Provider store={store}>
+ <Base />
+ </Provider>
+);
+
+export function renderWithoutState() {
+ const store = initStore(reducers);
+ new DetectUserSessionStart(store).sendEventOrAddListener();
+
+ // If this document has already gone into the background by the time we've reached
+ // here, we can deprioritize requesting the initial state until the event loop
+ // frees up. If, however, the visibility changes, we then send the request.
+ let didRequest = false;
+ let requestIdleCallbackId = 0;
+ function doRequest() {
+ if (!didRequest) {
+ if (requestIdleCallbackId) {
+ cancelIdleCallback(requestIdleCallbackId);
+ }
+ didRequest = true;
+ store.dispatch(ac.AlsoToMain({ type: at.NEW_TAB_STATE_REQUEST }));
+ }
+ }
+
+ if (document.hidden) {
+ requestIdleCallbackId = requestIdleCallback(doRequest);
+ addEventListener("visibilitychange", doRequest, { once: true });
+ } else {
+ doRequest();
+ }
+
+ ReactDOM.hydrate(<NewTab store={store} />, document.getElementById("root"));
+}
+
+export function renderCache(initialState) {
+ const store = initStore(reducers, initialState);
+ new DetectUserSessionStart(store).sendEventOrAddListener();
+
+ ReactDOM.hydrate(<NewTab store={store} />, document.getElementById("root"));
+}
diff --git a/browser/components/newtab/content-src/asrouter/README.md b/browser/components/newtab/content-src/asrouter/README.md
new file mode 100644
index 0000000000..0ee3345630
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/README.md
@@ -0,0 +1,34 @@
+# Activity Stream Router
+
+## Preferences `browser.newtab.activity-stream.asrouter.*`
+
+Name | Used for | Type | Example value
+--- | --- | --- | ---
+`allowHosts` | Allow a host in order to fetch messages from its endpoint | `[String]` | `["gist.github.com", "gist.githubusercontent.com", "localhost:8000"]`
+`providers.snippets` | Message provider options for snippets | `Object` | [see below](#message-providers)
+`providers.cfr` | Message provider options for cfr | `Object` | [see below](#message-providers)
+`providers.onboarding` | Message provider options for onboarding | `Object` | [see below](#message-providers)
+`useRemoteL10n` | Controls whether to use the remote Fluent files for l10n, default as `true` | `Boolean` | `[true|false]`
+
+### Message providers examples
+
+```json
+{
+ "id" : "snippets",
+ "type" : "remote",
+ "enabled": true,
+ "url" : "https://snippets.cdn.mozilla.net/us-west/bundles/bundle_d6d90fb9098ce8b45e60acf601bcb91b68322309.json",
+ "updateCycleInMs" : 14400000
+}
+```
+
+```json
+{
+ "id" : "onboarding",
+ "enabled": true,
+ "type" : "local",
+ "localProvider" : "OnboardingMessageProvider"
+}
+```
+
+### [Snippet message format documentation](https://github.com/mozilla/activity-stream/blob/master/content-src/asrouter/schemas/message-format.md)
diff --git a/browser/components/newtab/content-src/asrouter/asrouter-content.jsx b/browser/components/newtab/content-src/asrouter/asrouter-content.jsx
new file mode 100644
index 0000000000..0ad8999ebc
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/asrouter-content.jsx
@@ -0,0 +1,326 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { MESSAGE_TYPE_HASH as msg } from "common/ActorConstants.jsm";
+import { actionTypes as at } from "common/Actions.jsm";
+import { ASRouterUtils } from "./asrouter-utils";
+import { generateBundles } from "./rich-text-strings";
+import { ImpressionsWrapper } from "./components/ImpressionsWrapper/ImpressionsWrapper";
+import { LocalizationProvider } from "fluent-react";
+import { NEWTAB_DARK_THEME } from "content-src/lib/constants";
+import React from "react";
+import ReactDOM from "react-dom";
+import { SnippetsTemplates } from "./templates/template-manifest";
+
+const TEMPLATES_BELOW_SEARCH = ["simple_below_search_snippet"];
+
+// Note: nextProps/prevProps refer to props passed to <ImpressionsWrapper />, not <ASRouterUISurface />
+function shouldSendImpressionOnUpdate(nextProps, prevProps) {
+ return (
+ nextProps.message.id &&
+ (!prevProps.message || prevProps.message.id !== nextProps.message.id)
+ );
+}
+
+export class ASRouterUISurface extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.sendClick = this.sendClick.bind(this);
+ this.sendImpression = this.sendImpression.bind(this);
+ this.sendUserActionTelemetry = this.sendUserActionTelemetry.bind(this);
+ this.onUserAction = this.onUserAction.bind(this);
+ this.fetchFlowParams = this.fetchFlowParams.bind(this);
+ this.onBlockSelected = this.onBlockSelected.bind(this);
+ this.onBlockById = this.onBlockById.bind(this);
+ this.onDismiss = this.onDismiss.bind(this);
+ this.onMessageFromParent = this.onMessageFromParent.bind(this);
+
+ this.state = { message: {} };
+ if (props.document) {
+ this.footerPortal = props.document.getElementById(
+ "footer-asrouter-container"
+ );
+ }
+ }
+
+ async fetchFlowParams(params = {}) {
+ let result = {};
+ const { fxaEndpoint } = this.props;
+ if (!fxaEndpoint) {
+ const err =
+ "Tried to fetch flow params before fxaEndpoint pref was ready";
+ console.error(err); // eslint-disable-line no-console
+ }
+
+ try {
+ const urlObj = new URL(fxaEndpoint);
+ urlObj.pathname = "metrics-flow";
+ Object.keys(params).forEach(key => {
+ urlObj.searchParams.append(key, params[key]);
+ });
+ const response = await fetch(urlObj.toString(), { credentials: "omit" });
+ if (response.status === 200) {
+ const { deviceId, flowId, flowBeginTime } = await response.json();
+ result = { deviceId, flowId, flowBeginTime };
+ } else {
+ console.error("Non-200 response", response); // eslint-disable-line no-console
+ }
+ } catch (error) {
+ console.error(error); // eslint-disable-line no-console
+ }
+ return result;
+ }
+
+ sendUserActionTelemetry(extraProps = {}) {
+ const { message } = this.state;
+ const eventType = `${message.provider}_user_event`;
+ const source = extraProps.id;
+ delete extraProps.id;
+ ASRouterUtils.sendTelemetry({
+ source,
+ message_id: message.id,
+ action: eventType,
+ ...extraProps,
+ });
+ }
+
+ sendImpression(extraProps) {
+ if (this.state.message.provider === "preview") {
+ return Promise.resolve();
+ }
+
+ this.sendUserActionTelemetry({ event: "IMPRESSION", ...extraProps });
+ return ASRouterUtils.sendMessage({
+ type: msg.IMPRESSION,
+ data: this.state.message,
+ });
+ }
+
+ // If link has a `metric` data attribute send it as part of the `event_context`
+ // telemetry field which can have arbitrary values.
+ // Used for router messages with links as part of the content.
+ sendClick(event) {
+ const { dataset } = event.target;
+ const metric = {
+ event_context: dataset.metric,
+ // Used for the `source` of the event. Needed to differentiate
+ // from other snippet or onboarding events that may occur.
+ id: "NEWTAB_FOOTER_BAR_CONTENT",
+ };
+ const { entrypoint_name, entrypoint_value } = dataset;
+ // Assign the snippet referral for the action
+ const entrypoint = entrypoint_name
+ ? new URLSearchParams([[entrypoint_name, entrypoint_value]]).toString()
+ : entrypoint_value;
+ const action = {
+ type: dataset.action,
+ data: {
+ args: dataset.args,
+ ...(entrypoint && { entrypoint }),
+ },
+ };
+ if (action.type) {
+ ASRouterUtils.executeAction(action);
+ }
+ if (
+ !this.state.message.content.do_not_autoblock &&
+ !dataset.do_not_autoblock
+ ) {
+ this.onBlockById(this.state.message.id);
+ }
+ if (this.state.message.provider !== "preview") {
+ this.sendUserActionTelemetry({ event: "CLICK_BUTTON", ...metric });
+ }
+ }
+
+ onBlockSelected(options) {
+ return this.onBlockById(this.state.message.id, options);
+ }
+
+ onBlockById(id, options) {
+ return ASRouterUtils.blockById(id, options).then(clearAll => {
+ if (clearAll) {
+ this.setState({ message: {} });
+ }
+ });
+ }
+
+ onDismiss() {
+ this.clearMessage(this.state.message.id);
+ }
+
+ clearMessage(id) {
+ if (id === this.state.message.id) {
+ this.setState({ message: {} });
+ }
+ }
+
+ clearProvider(id) {
+ if (this.state.message.provider === id) {
+ this.setState({ message: {} });
+ }
+ }
+
+ onMessageFromParent({ type, data }) {
+ // These only exists due to onPrefChange events in ASRouter
+ switch (type) {
+ case "ClearMessages": {
+ data.forEach(id => this.clearMessage(id));
+ break;
+ }
+ case "ClearProviders": {
+ data.forEach(id => this.clearProvider(id));
+ break;
+ }
+ case "EnterSnippetsPreviewMode": {
+ this.props.dispatch({ type: at.SNIPPETS_PREVIEW_MODE });
+ break;
+ }
+ }
+ }
+
+ requestMessage(endpoint) {
+ ASRouterUtils.sendMessage({
+ type: "NEWTAB_MESSAGE_REQUEST",
+ data: { endpoint },
+ }).then(state => this.setState(state));
+ }
+
+ componentWillMount() {
+ const endpoint = ASRouterUtils.getPreviewEndpoint();
+ if (endpoint && endpoint.theme === "dark") {
+ global.window.dispatchEvent(
+ new CustomEvent("LightweightTheme:Set", {
+ detail: { data: NEWTAB_DARK_THEME },
+ })
+ );
+ }
+ if (endpoint && endpoint.dir === "rtl") {
+ //Set `dir = rtl` on the HTML
+ this.props.document.dir = "rtl";
+ }
+ ASRouterUtils.addListener(this.onMessageFromParent);
+ this.requestMessage(endpoint);
+ }
+
+ componentWillUnmount() {
+ ASRouterUtils.removeListener(this.onMessageFromParent);
+ }
+
+ componentDidUpdate(prevProps) {
+ if (
+ prevProps.adminContent &&
+ JSON.stringify(prevProps.adminContent) !==
+ JSON.stringify(this.props.adminContent)
+ ) {
+ this.updateContent();
+ }
+ }
+
+ updateContent() {
+ this.setState({
+ ...this.props.adminContent,
+ });
+ }
+
+ async getMonitorUrl({ url, flowRequestParams = {} }) {
+ const flowValues = await this.fetchFlowParams(flowRequestParams);
+
+ // Note that flowParams are actually added dynamically on the page
+ const urlObj = new URL(url);
+ ["deviceId", "flowId", "flowBeginTime"].forEach(key => {
+ if (key in flowValues) {
+ urlObj.searchParams.append(key, flowValues[key]);
+ }
+ });
+
+ return urlObj.toString();
+ }
+
+ async onUserAction(action) {
+ switch (action.type) {
+ // This needs to be handled locally because its
+ case "ENABLE_FIREFOX_MONITOR":
+ const url = await this.getMonitorUrl(action.data.args);
+ ASRouterUtils.executeAction({ type: "OPEN_URL", data: { args: url } });
+ break;
+ default:
+ ASRouterUtils.executeAction(action);
+ }
+ }
+
+ renderSnippets() {
+ const { message } = this.state;
+ if (!SnippetsTemplates[message.template]) {
+ return null;
+ }
+ const SnippetComponent = SnippetsTemplates[message.template];
+ const { content } = this.state.message;
+
+ return (
+ <ImpressionsWrapper
+ id="NEWTAB_FOOTER_BAR"
+ message={this.state.message}
+ sendImpression={this.sendImpression}
+ shouldSendImpressionOnUpdate={shouldSendImpressionOnUpdate}
+ // This helps with testing
+ document={this.props.document}
+ >
+ <LocalizationProvider bundles={generateBundles(content)}>
+ <SnippetComponent
+ {...this.state.message}
+ UISurface="NEWTAB_FOOTER_BAR"
+ onBlock={this.onBlockSelected}
+ onDismiss={this.onDismiss}
+ onAction={this.onUserAction}
+ sendClick={this.sendClick}
+ sendUserActionTelemetry={this.sendUserActionTelemetry}
+ />
+ </LocalizationProvider>
+ </ImpressionsWrapper>
+ );
+ }
+
+ renderPreviewBanner() {
+ if (this.state.message.provider !== "preview") {
+ return null;
+ }
+
+ return (
+ <div className="snippets-preview-banner">
+ <span className="icon icon-small-spacer icon-info" />
+ <span>Preview Purposes Only</span>
+ </div>
+ );
+ }
+
+ render() {
+ const { message } = this.state;
+ if (!message.id) {
+ return null;
+ }
+ const shouldRenderBelowSearch = TEMPLATES_BELOW_SEARCH.includes(
+ message.template
+ );
+
+ return shouldRenderBelowSearch ? (
+ // Render special below search snippets in place;
+ <div className="below-search-snippet-wrapper">
+ {this.renderSnippets()}
+ </div>
+ ) : (
+ // For regular snippets etc. we should render everything in our footer
+ // container.
+ ReactDOM.createPortal(
+ <>
+ {this.renderPreviewBanner()}
+ {this.renderSnippets()}
+ </>,
+ this.footerPortal
+ )
+ );
+ }
+}
+
+ASRouterUISurface.defaultProps = { document: global.document };
diff --git a/browser/components/newtab/content-src/asrouter/asrouter-utils.js b/browser/components/newtab/content-src/asrouter/asrouter-utils.js
new file mode 100644
index 0000000000..fe7f0110f2
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/asrouter-utils.js
@@ -0,0 +1,108 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { MESSAGE_TYPE_HASH as msg } from "common/ActorConstants.jsm";
+import { actionCreators as ac } from "common/Actions.jsm";
+
+export const ASRouterUtils = {
+ addListener(listener) {
+ if (global.ASRouterAddParentListener) {
+ global.ASRouterAddParentListener(listener);
+ }
+ },
+ removeListener(listener) {
+ if (global.ASRouterRemoveParentListener) {
+ global.ASRouterRemoveParentListener(listener);
+ }
+ },
+ sendMessage(action) {
+ if (global.ASRouterMessage) {
+ return global.ASRouterMessage(action);
+ }
+ throw new Error(`Unexpected call:\n${JSON.stringify(action, null, 3)}`);
+ },
+ blockById(id, options) {
+ return ASRouterUtils.sendMessage({
+ type: msg.BLOCK_MESSAGE_BY_ID,
+ data: { id, ...options },
+ });
+ },
+ modifyMessageJson(content) {
+ return ASRouterUtils.sendMessage({
+ type: msg.MODIFY_MESSAGE_JSON,
+ data: { content },
+ });
+ },
+ executeAction(button_action) {
+ return ASRouterUtils.sendMessage({
+ type: msg.USER_ACTION,
+ data: button_action,
+ });
+ },
+ unblockById(id) {
+ return ASRouterUtils.sendMessage({
+ type: msg.UNBLOCK_MESSAGE_BY_ID,
+ data: { id },
+ });
+ },
+ blockBundle(bundle) {
+ return ASRouterUtils.sendMessage({
+ type: msg.BLOCK_BUNDLE,
+ data: { bundle },
+ });
+ },
+ unblockBundle(bundle) {
+ return ASRouterUtils.sendMessage({
+ type: msg.UNBLOCK_BUNDLE,
+ data: { bundle },
+ });
+ },
+ overrideMessage(id) {
+ return ASRouterUtils.sendMessage({
+ type: msg.OVERRIDE_MESSAGE,
+ data: { id },
+ });
+ },
+ sendTelemetry(ping) {
+ return ASRouterUtils.sendMessage(ac.ASRouterUserEvent(ping));
+ },
+ getPreviewEndpoint() {
+ if (
+ global.document &&
+ global.document.location &&
+ global.document.location.href.includes("endpoint")
+ ) {
+ const params = new URLSearchParams(
+ global.document.location.href.slice(
+ global.document.location.href.indexOf("endpoint")
+ )
+ );
+ try {
+ const endpoint = new URL(params.get("endpoint"));
+ return {
+ url: endpoint.href,
+ snippetId: params.get("snippetId"),
+ theme: this.getPreviewTheme(),
+ dir: this.getPreviewDir(),
+ };
+ } catch (e) {}
+ }
+
+ return null;
+ },
+ getPreviewTheme() {
+ return new URLSearchParams(
+ global.document.location.href.slice(
+ global.document.location.href.indexOf("theme")
+ )
+ ).get("theme");
+ },
+ getPreviewDir() {
+ return new URLSearchParams(
+ global.document.location.href.slice(
+ global.document.location.href.indexOf("dir")
+ )
+ ).get("dir");
+ },
+};
diff --git a/browser/components/newtab/content-src/asrouter/components/Button/Button.jsx b/browser/components/newtab/content-src/asrouter/components/Button/Button.jsx
new file mode 100644
index 0000000000..b3ece86f16
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/components/Button/Button.jsx
@@ -0,0 +1,32 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import React from "react";
+
+const ALLOWED_STYLE_TAGS = ["color", "backgroundColor"];
+
+export const Button = props => {
+ const style = {};
+
+ // Add allowed style tags from props, e.g. props.color becomes style={color: props.color}
+ for (const tag of ALLOWED_STYLE_TAGS) {
+ if (typeof props[tag] !== "undefined") {
+ style[tag] = props[tag];
+ }
+ }
+ // remove border if bg is set to something custom
+ if (style.backgroundColor) {
+ style.border = "0";
+ }
+
+ return (
+ <button
+ onClick={props.onClick}
+ className={props.className || "ASRouterButton secondary"}
+ style={style}
+ >
+ {props.children}
+ </button>
+ );
+};
diff --git a/browser/components/newtab/content-src/asrouter/components/Button/_Button.scss b/browser/components/newtab/content-src/asrouter/components/Button/_Button.scss
new file mode 100644
index 0000000000..330bfbb4fb
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/components/Button/_Button.scss
@@ -0,0 +1,94 @@
+.ASRouterButton {
+ font-weight: 600;
+ font-size: 14px;
+ white-space: nowrap;
+ border-radius: 2px;
+ border: 0;
+ font-family: inherit;
+ padding: 8px 15px;
+ margin-inline-start: 12px;
+ color: inherit;
+ cursor: pointer;
+
+ .tall & {
+ margin-inline-start: 20px;
+ }
+
+ &.test-only {
+ width: 0;
+ height: 0;
+ overflow: hidden;
+ display: block;
+ visibility: hidden;
+ }
+
+ &.primary {
+ border: 1px solid var(--newtab-button-primary-color);
+ background-color: var(--newtab-button-primary-color);
+ color: $grey-10;
+
+ &:hover {
+ background-color: $blue-70;
+ }
+
+ &:active {
+ background-color: $blue-80;
+ }
+ }
+
+ &.secondary {
+ background-color: $grey-90-10;
+
+ &:hover {
+ background-color: $grey-90-20;
+ }
+
+ &:active {
+ background-color: $grey-90-30;
+ }
+
+ &:focus {
+ box-shadow: 0 0 0 1px $blue-50 inset, 0 0 0 1px $blue-50, 0 0 0 4px $blue-50-30;
+ }
+ }
+
+ &.slim {
+ background-color: $grey-90-10;
+ margin-inline-start: 0;
+ font-size: 12px;
+ padding: 6px 12px;
+
+ &:hover {
+ background-color: $grey-90-20;
+ }
+ }
+}
+
+[lwt-newtab-brighttext] {
+ .secondary {
+ background-color: $grey-10-10;
+
+ &:hover {
+ background-color: $grey-10-20;
+ }
+
+ &:active {
+ background-color: $grey-10-30;
+ }
+ }
+
+ // Snippets scene 2 footer
+ .footer {
+ .secondary {
+ background-color: $grey-10-30;
+
+ &:hover {
+ background-color: $grey-10-40;
+ }
+
+ &:active {
+ background-color: $grey-10-50;
+ }
+ }
+ }
+}
diff --git a/browser/components/newtab/content-src/asrouter/components/ConditionalWrapper/ConditionalWrapper.jsx b/browser/components/newtab/content-src/asrouter/components/ConditionalWrapper/ConditionalWrapper.jsx
new file mode 100644
index 0000000000..e4b0812f26
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/components/ConditionalWrapper/ConditionalWrapper.jsx
@@ -0,0 +1,9 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+// lifted from https://gist.github.com/kitze/23d82bb9eb0baabfd03a6a720b1d637f
+const ConditionalWrapper = ({ condition, wrap, children }) =>
+ condition && wrap ? wrap(children) : children;
+
+export default ConditionalWrapper;
diff --git a/browser/components/newtab/content-src/asrouter/components/ImpressionsWrapper/ImpressionsWrapper.jsx b/browser/components/newtab/content-src/asrouter/components/ImpressionsWrapper/ImpressionsWrapper.jsx
new file mode 100644
index 0000000000..8498bde03b
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/components/ImpressionsWrapper/ImpressionsWrapper.jsx
@@ -0,0 +1,76 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import React from "react";
+
+export const VISIBLE = "visible";
+export const VISIBILITY_CHANGE_EVENT = "visibilitychange";
+
+/**
+ * Component wrapper used to send telemetry pings on every impression.
+ */
+export class ImpressionsWrapper extends React.PureComponent {
+ // This sends an event when a user sees a set of new content. If content
+ // changes while the page is hidden (i.e. preloaded or on a hidden tab),
+ // only send the event if the page becomes visible again.
+ sendImpressionOrAddListener() {
+ if (this.props.document.visibilityState === VISIBLE) {
+ this.props.sendImpression({ id: this.props.id });
+ } else {
+ // We should only ever send the latest impression stats ping, so remove any
+ // older listeners.
+ if (this._onVisibilityChange) {
+ this.props.document.removeEventListener(
+ VISIBILITY_CHANGE_EVENT,
+ this._onVisibilityChange
+ );
+ }
+
+ // When the page becomes visible, send the impression stats ping if the section isn't collapsed.
+ this._onVisibilityChange = () => {
+ if (this.props.document.visibilityState === VISIBLE) {
+ this.props.sendImpression({ id: this.props.id });
+ this.props.document.removeEventListener(
+ VISIBILITY_CHANGE_EVENT,
+ this._onVisibilityChange
+ );
+ }
+ };
+ this.props.document.addEventListener(
+ VISIBILITY_CHANGE_EVENT,
+ this._onVisibilityChange
+ );
+ }
+ }
+
+ componentWillUnmount() {
+ if (this._onVisibilityChange) {
+ this.props.document.removeEventListener(
+ VISIBILITY_CHANGE_EVENT,
+ this._onVisibilityChange
+ );
+ }
+ }
+
+ componentDidMount() {
+ if (this.props.sendOnMount) {
+ this.sendImpressionOrAddListener();
+ }
+ }
+
+ componentDidUpdate(prevProps) {
+ if (this.props.shouldSendImpressionOnUpdate(this.props, prevProps)) {
+ this.sendImpressionOrAddListener();
+ }
+ }
+
+ render() {
+ return this.props.children;
+ }
+}
+
+ImpressionsWrapper.defaultProps = {
+ document: global.document,
+ sendOnMount: true,
+};
diff --git a/browser/components/newtab/content-src/asrouter/components/ModalOverlay/ModalOverlay.jsx b/browser/components/newtab/content-src/asrouter/components/ModalOverlay/ModalOverlay.jsx
new file mode 100644
index 0000000000..fdfdf22db2
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/components/ModalOverlay/ModalOverlay.jsx
@@ -0,0 +1,56 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import React from "react";
+
+export class ModalOverlayWrapper extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onKeyDown = this.onKeyDown.bind(this);
+ }
+
+ // The intended behaviour is to listen for an escape key
+ // but not for a click; see Bug 1582242
+ onKeyDown(event) {
+ if (event.key === "Escape") {
+ this.props.onClose(event);
+ }
+ }
+
+ componentWillMount() {
+ this.props.document.addEventListener("keydown", this.onKeyDown);
+ this.props.document.body.classList.add("modal-open");
+ }
+
+ componentWillUnmount() {
+ this.props.document.removeEventListener("keydown", this.onKeyDown);
+ this.props.document.body.classList.remove("modal-open");
+ }
+
+ render() {
+ const { props } = this;
+ let className = props.unstyled ? "" : "modalOverlayInner active";
+ if (props.innerClassName) {
+ className += ` ${props.innerClassName}`;
+ }
+ return (
+ <div
+ className="modalOverlayOuter active"
+ onKeyDown={this.onKeyDown}
+ role="presentation"
+ >
+ <div
+ className={className}
+ aria-labelledby={props.headerId}
+ id={props.id}
+ role="dialog"
+ >
+ {props.children}
+ </div>
+ </div>
+ );
+ }
+}
+
+ModalOverlayWrapper.defaultProps = { document: global.document };
diff --git a/browser/components/newtab/content-src/asrouter/components/ModalOverlay/_ModalOverlay.scss b/browser/components/newtab/content-src/asrouter/components/ModalOverlay/_ModalOverlay.scss
new file mode 100644
index 0000000000..2cdbfcb1db
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/components/ModalOverlay/_ModalOverlay.scss
@@ -0,0 +1,104 @@
+// Variable for the about:welcome modal scrollbars
+$modal-scrollbar-z-index: 1100;
+
+.activity-stream {
+ &.modal-open {
+ overflow: hidden;
+ }
+}
+
+.modalOverlayOuter {
+ background: var(--newtab-overlay-color);
+ height: 100%;
+ position: fixed;
+ top: 0;
+ left: 0;
+ width: 100%;
+ display: none;
+ z-index: $modal-scrollbar-z-index;
+ overflow: auto;
+
+ &.active {
+ display: flex;
+ }
+}
+
+.modalOverlayInner {
+ min-width: min-content;
+ width: 100%;
+ max-width: 960px;
+ position: relative;
+ margin: auto;
+ background: var(--newtab-modal-color);
+ box-shadow: 0 1px 15px 0 $black-30;
+ border-radius: 4px;
+ display: none;
+ z-index: $modal-scrollbar-z-index;
+
+ // modal takes over entire screen
+ @media(max-width: 960px) {
+ height: 100%;
+ top: 0;
+ left: 0;
+ box-shadow: none;
+ border-radius: 0;
+ }
+
+ &.active {
+ display: block;
+ }
+
+ h2 {
+ color: $grey-60;
+ text-align: center;
+ font-weight: 200;
+ margin-top: 30px;
+ font-size: 28px;
+ line-height: 37px;
+ letter-spacing: -0.13px;
+
+ @media(max-width: 960px) {
+ margin-top: 100px;
+ }
+
+ @media(max-width: 850px) {
+ margin-top: 30px;
+ }
+ }
+
+ .footer {
+ border-top: 1px solid $grey-30;
+ border-radius: 4px;
+ height: 70px;
+ width: 100%;
+ position: absolute;
+ bottom: 0;
+ text-align: center;
+ background-color: $white;
+
+ // if modal is short enough, footer becomes sticky
+ @media(max-width: 850px) and (max-height: 730px) {
+ position: sticky;
+ }
+
+ // if modal is narrow enough, footer becomes sticky
+ @media(max-width: 650px) and (max-height: 600px) {
+ position: sticky;
+ }
+
+ .modalButton {
+ margin-top: 20px;
+ min-width: 150px;
+ height: 30px;
+ padding: 4px 30px 6px;
+ font-size: 15px;
+
+ &:focus,
+ &.active,
+ &:hover {
+ box-shadow: 0 0 0 5px $grey-30;
+ transition: box-shadow 150ms;
+ }
+ }
+ }
+}
diff --git a/browser/components/newtab/content-src/asrouter/components/RichText/RichText.jsx b/browser/components/newtab/content-src/asrouter/components/RichText/RichText.jsx
new file mode 100644
index 0000000000..45e35b83cc
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/components/RichText/RichText.jsx
@@ -0,0 +1,83 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { Localized } from "fluent-react";
+import React from "react";
+import { RICH_TEXT_KEYS } from "../../rich-text-strings";
+import { safeURI } from "../../template-utils";
+
+// Elements allowed in snippet content
+const ALLOWED_TAGS = {
+ b: <b />,
+ i: <i />,
+ u: <u />,
+ strong: <strong />,
+ em: <em />,
+ br: <br />,
+};
+
+/**
+ * Transform an object (tag name: {url}) into (tag name: anchor) where the url
+ * is used as href, in order to render links inside a Fluent.Localized component.
+ */
+export function convertLinks(
+ links,
+ sendClick,
+ doNotAutoBlock,
+ openNewWindow = false
+) {
+ if (links) {
+ return Object.keys(links).reduce((acc, linkTag) => {
+ const { action } = links[linkTag];
+ // Setting the value to false will not include the attribute in the anchor
+ const url = action ? false : safeURI(links[linkTag].url);
+
+ acc[linkTag] = (
+ // eslint was getting a false positive caused by the dynamic injection
+ // of content.
+ // eslint-disable-next-line jsx-a11y/anchor-has-content
+ <a
+ href={url}
+ target={openNewWindow ? "_blank" : ""}
+ data-metric={links[linkTag].metric}
+ data-action={action}
+ data-args={links[linkTag].args}
+ data-do_not_autoblock={doNotAutoBlock}
+ data-entrypoint_name={links[linkTag].entrypoint_name}
+ data-entrypoint_value={links[linkTag].entrypoint_value}
+ onClick={sendClick}
+ />
+ );
+ return acc;
+ }, {});
+ }
+
+ return null;
+}
+
+/**
+ * Message wrapper used to sanitize markup and render HTML.
+ */
+export function RichText(props) {
+ if (!RICH_TEXT_KEYS.includes(props.localization_id)) {
+ throw new Error(
+ `ASRouter: ${props.localization_id} is not a valid rich text property. If you want it to be processed, you need to add it to asrouter/rich-text-strings.js`
+ );
+ }
+ return (
+ <Localized
+ id={props.localization_id}
+ {...ALLOWED_TAGS}
+ {...props.customElements}
+ {...convertLinks(
+ props.links,
+ props.sendClick,
+ props.doNotAutoBlock,
+ props.openNewWindow
+ )}
+ >
+ <span>{props.text}</span>
+ </Localized>
+ );
+}
diff --git a/browser/components/newtab/content-src/asrouter/components/SnippetBase/SnippetBase.jsx b/browser/components/newtab/content-src/asrouter/components/SnippetBase/SnippetBase.jsx
new file mode 100644
index 0000000000..fd25337fbf
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/components/SnippetBase/SnippetBase.jsx
@@ -0,0 +1,121 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import React from "react";
+
+export class SnippetBase extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onBlockClicked = this.onBlockClicked.bind(this);
+ this.onDismissClicked = this.onDismissClicked.bind(this);
+ this.setBlockButtonRef = this.setBlockButtonRef.bind(this);
+ this.onBlockButtonMouseEnter = this.onBlockButtonMouseEnter.bind(this);
+ this.onBlockButtonMouseLeave = this.onBlockButtonMouseLeave.bind(this);
+ this.state = { blockButtonHover: false };
+ }
+
+ componentDidMount() {
+ if (this.blockButtonRef) {
+ this.blockButtonRef.addEventListener(
+ "mouseenter",
+ this.onBlockButtonMouseEnter
+ );
+ this.blockButtonRef.addEventListener(
+ "mouseleave",
+ this.onBlockButtonMouseLeave
+ );
+ }
+ }
+
+ componentWillUnmount() {
+ if (this.blockButtonRef) {
+ this.blockButtonRef.removeEventListener(
+ "mouseenter",
+ this.onBlockButtonMouseEnter
+ );
+ this.blockButtonRef.removeEventListener(
+ "mouseleave",
+ this.onBlockButtonMouseLeave
+ );
+ }
+ }
+
+ setBlockButtonRef(element) {
+ this.blockButtonRef = element;
+ }
+
+ onBlockButtonMouseEnter() {
+ this.setState({ blockButtonHover: true });
+ }
+
+ onBlockButtonMouseLeave() {
+ this.setState({ blockButtonHover: false });
+ }
+
+ onBlockClicked() {
+ if (this.props.provider !== "preview") {
+ this.props.sendUserActionTelemetry({
+ event: "BLOCK",
+ id: this.props.UISurface,
+ });
+ }
+
+ this.props.onBlock();
+ }
+
+ onDismissClicked() {
+ if (this.props.provider !== "preview") {
+ this.props.sendUserActionTelemetry({
+ event: "DISMISS",
+ id: this.props.UISurface,
+ });
+ }
+
+ this.props.onDismiss();
+ }
+
+ renderDismissButton() {
+ if (this.props.footerDismiss) {
+ return (
+ <div className="footer">
+ <div className="footer-content">
+ <button
+ className="ASRouterButton secondary"
+ onClick={this.onDismissClicked}
+ >
+ {this.props.content.scene2_dismiss_button_text}
+ </button>
+ </div>
+ </div>
+ );
+ }
+
+ const label = this.props.content.block_button_text || "Remove this";
+ return (
+ <button
+ className="blockButton"
+ title={label}
+ aria-label={label}
+ onClick={this.onBlockClicked}
+ ref={this.setBlockButtonRef}
+ />
+ );
+ }
+
+ render() {
+ const { props } = this;
+ const { blockButtonHover } = this.state;
+
+ const containerClassName = `SnippetBaseContainer${
+ props.className ? ` ${props.className}` : ""
+ }${blockButtonHover ? " active" : ""}`;
+
+ return (
+ <div className={containerClassName} style={this.props.textStyle}>
+ <div className="innerWrapper">{props.children}</div>
+ {this.renderDismissButton()}
+ </div>
+ );
+ }
+}
diff --git a/browser/components/newtab/content-src/asrouter/components/SnippetBase/_SnippetBase.scss b/browser/components/newtab/content-src/asrouter/components/SnippetBase/_SnippetBase.scss
new file mode 100644
index 0000000000..cfa090f89b
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/components/SnippetBase/_SnippetBase.scss
@@ -0,0 +1,117 @@
+.SnippetBaseContainer {
+ position: fixed;
+ z-index: 2;
+ bottom: 0;
+ left: 0;
+ right: 0;
+ background-color: var(--newtab-snippets-background-color);
+ color: var(--newtab-text-primary-color);
+ font-size: 14px;
+ line-height: 20px;
+ border-top: 1px solid var(--newtab-snippets-hairline-color);
+ box-shadow: $shadow-secondary;
+ display: flex;
+ align-items: center;
+
+ a {
+ cursor: pointer;
+ color: var(--newtab-link-primary-color);
+
+ &:hover {
+ text-decoration: underline;
+ }
+
+ [lwt-newtab-brighttext] & {
+ font-weight: bold;
+ }
+ }
+
+ input {
+ &[type='checkbox'] {
+ margin-inline-start: 0;
+ }
+ }
+
+ .innerWrapper {
+ margin: 0 auto;
+ display: flex;
+ align-items: center;
+ padding: 12px $section-horizontal-padding;
+
+ // This is to account for the block button on smaller screens
+ padding-inline-end: 36px;
+ @media (min-width: $break-point-large) {
+ padding-inline-end: $section-horizontal-padding;
+ }
+
+ max-width: $wrapper-max-width-large + ($section-horizontal-padding * 2);
+ @media (min-width: $break-point-widest) {
+ max-width: $wrapper-max-width-widest + ($section-horizontal-padding * 2);
+ }
+ }
+
+ .blockButton {
+ display: none;
+ background: none;
+ border: 0;
+ position: absolute;
+ top: 50%;
+ inset-inline-end: 12px;
+ height: 16px;
+ width: 16px;
+ background-image: url('chrome://activity-stream/content/data/content/assets/glyph-dismiss-16.svg');
+ -moz-context-properties: fill;
+ color: inherit;
+ fill: currentColor;
+ opacity: 0.5;
+ margin-top: -8px;
+ padding: 0;
+ cursor: pointer;
+ }
+
+ &:hover .blockButton {
+ display: block;
+ }
+
+ .icon {
+ height: 42px;
+ width: 42px;
+ margin-inline-end: 12px;
+ flex-shrink: 0;
+ }
+}
+
+.snippets-preview-banner {
+ font-size: 15px;
+ line-height: 42px;
+ color: $grey-60-70;
+ background: $grey-30-60;
+ text-align: center;
+ position: absolute;
+ top: 0;
+ width: 100%;
+
+ span {
+ vertical-align: middle;
+ }
+}
+
+// We show snippet icons for both themes and conditionally hide
+// based on which theme is currently active
+body {
+ &:not([lwt-newtab-brighttext]) {
+ .icon-dark-theme,
+ .icon.icon-dark-theme,
+ .scene2Icon .icon-dark-theme {
+ display: none;
+ }
+ }
+
+ &[lwt-newtab-brighttext] {
+ .icon-light-theme,
+ .icon.icon-light-theme,
+ .scene2Icon .icon-light-theme {
+ display: none;
+ }
+ }
+}
diff --git a/browser/components/newtab/content-src/asrouter/docs/cfr_doorhanger_screenshot.png b/browser/components/newtab/content-src/asrouter/docs/cfr_doorhanger_screenshot.png
new file mode 100644
index 0000000000..aee3bcf3bd
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/docs/cfr_doorhanger_screenshot.png
Binary files differ
diff --git a/browser/components/newtab/content-src/asrouter/docs/debugging-docs.md b/browser/components/newtab/content-src/asrouter/docs/debugging-docs.md
new file mode 100644
index 0000000000..035118b987
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/docs/debugging-docs.md
@@ -0,0 +1,62 @@
+# Using ASRouter Devtools
+
+## How to enable ASRouter devtools
+- In `about:config`, set `browser.newtabpage.activity-stream.asrouter.devtoolsEnabled` to `true`
+- Visit `about:newtab#asrouter` to see the devtools.
+
+## Overview of ASRouter devtools
+
+![Devtools image](./debugging-guide.png)
+
+## How to enable/disable a provider
+
+To enable a provider such as `snippets`, Look at the list of "Message Providers" at the top of the page. Make sure the checkbox is checked next to the provider you want to enable.
+
+To disable it, uncheck the checkbox. You should see a red label indicating the provider is now disabled.
+
+## How to see all messages from a provider
+
+(Only available in Firefox 65+)
+
+In order to see all active messages for a current provider such as `snippets`, use the drop down selector under the "Messages" section. Select the name of the provider you are interested in.
+
+The messages on the page should now be filtered to include only the provider you selected.
+
+## How to test telemetry pings
+
+To test telemetry pings, complete the the following steps:
+
+- In about:config, set:
+ - `browser.newtabpage.activity-stream.telemetry` to `true`
+ - `browser.ping-centre.log` to `true`
+- Open the Browser Toolbox devtools (Tools > Web Developer > Browser Toolbox) and switch to the console tab. Add a filter for for `activity-stream` to only display relevant pings:
+
+![Devtools telemetry ping](./telemetry-screenshot.png)
+
+You should now see pings show up as you view/interact with ASR messages/templates.
+
+## Snippets debugging
+
+### How to view preview URLs
+
+Follow these steps to view preview URLs (e.g. `about:newtab?endpoint=https://gist.githubusercontent.com/piatra/d193ca7e0f513cc19fc6a1d396c214f7/raw/8bcaf9548212e4c613577e839198cc14e7317630/newsletter_snippet.json&theme=dark`)
+
+You can preview in the two different themes (light and dark) by adding `&theme=dark` or `&theme=light` at the end of the url.
+
+#### IMPORTANT NOTES
+- Links to URLs starting with `about:newtab` cannot be clicked on directly. They must be copy and pasted into the address bar.
+- Previews should only be tested in `Firefox 64` and later.
+- The endpoint must be HTTPS, the host must be allowed (see testing instructions below)
+- Errors are surfaced in the `Console` tab of the `Browser Toolbox`
+
+#### Testing instructions
+- If your endpoint URL has a host name of `snippets-admin.mozilla.org`, you can paste the URL into the address bar view it without any further steps.
+- If your endpoint URL starts with some other host name, it must be **allowed**. Open the Browser Toolbox devtools (Tools > Developer > Browser Toolbox) and paste the following code (where `gist.githubusercontent.com` is the hostname of your endpoint URL):
+```js
+Services.prefs.setStringPref(
+ "browser.newtab.activity-stream.asrouter.allowHosts",
+ "[\"gist.githubusercontent.com\"]"
+);
+```
+- Restart the browser
+- You should now be able to paste the URL into the address bar and view it.
diff --git a/browser/components/newtab/content-src/asrouter/docs/debugging-guide.png b/browser/components/newtab/content-src/asrouter/docs/debugging-guide.png
new file mode 100644
index 0000000000..8616a29ab3
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/docs/debugging-guide.png
Binary files differ
diff --git a/browser/components/newtab/content-src/asrouter/docs/experiment-guide.md b/browser/components/newtab/content-src/asrouter/docs/experiment-guide.md
new file mode 100644
index 0000000000..ac2784bb1f
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/docs/experiment-guide.md
@@ -0,0 +1,52 @@
+# How to run experiments with ASRouter
+
+This guide will tell you how to run an experiment with ASRouter messages.
+Note that the actual experiment process and infrastructure is handled by
+the experiments team (#ask-experimenter).
+
+## Why run an experiment
+
+* To measure the effect of a message on a Firefox metric (e.g. retention)
+* To test a potentially risky message on a smaller group of users
+* To compare the performance of multiple variants of messages in a controlled way
+
+## Choose cohort IDs and request an experiment
+
+First you should decide on a cohort ID (this can be any arbitrary unique string) for each
+individual group you need to segment for your experiment.
+
+For example, if I want to test two variants of an FXA Snippet, I might have two cohort IDs,
+`FXA_SNIPPET_V1` and `FXA_SNIPPET_V2`.
+
+You will then [request](https://experimenter.services.mozilla.com/) a new "pref-flip" study with the Firefox Experiments team.
+The preferences you will submit will be based on the cohort IDs you chose.
+
+For the FXA Snippet example, your preference name would be `browser.newtabpage.activity-stream.asrouter.providers.snippets` and values would be:
+
+Control (default value)
+```json
+{"id":"snippets","enabled":true,"type":"remote","url":"https://snippets.cdn.mozilla.net/%STARTPAGE_VERSION%/%NAME%/%VERSION%/%APPBUILDID%/%BUILD_TARGET%/%LOCALE%/release/%OS_VERSION%/%DISTRIBUTION%/%DISTRIBUTION_VERSION%/","updateCycleInMs":14400000}
+```
+
+Variant 1:
+```json
+{"id":"snippets", "cohort": "FXA_SNIPPET_V1", "enabled":true,"type":"remote","url":"https://snippets.cdn.mozilla.net/%STARTPAGE_VERSION%/%NAME%/%VERSION%/%APPBUILDID%/%BUILD_TARGET%/%LOCALE%/release/%OS_VERSION%/%DISTRIBUTION%/%DISTRIBUTION_VERSION%/","updateCycleInMs":14400000}
+```
+
+Variant 2:
+```json
+{"id":"snippets", "cohort": "FXA_SNIPPET_V1", "enabled":true,"type":"remote","url":"https://snippets.cdn.mozilla.net/%STARTPAGE_VERSION%/%NAME%/%VERSION%/%APPBUILDID%/%BUILD_TARGET%/%LOCALE%/release/%OS_VERSION%/%DISTRIBUTION%/%DISTRIBUTION_VERSION%/","updateCycleInMs":14400000}
+```
+
+## Add targeting to your messages
+
+You must now check for the cohort ID in the `targeting` expression of the messages you want to include in your experiments.
+
+For the previous example, you wold include the following to target the first cohort:
+
+```json
+{
+ "targeting": "providerCohorts.snippets == \"FXA_SNIPPET_V1\""
+}
+
+```
diff --git a/browser/components/newtab/content-src/asrouter/docs/first-run.md b/browser/components/newtab/content-src/asrouter/docs/first-run.md
new file mode 100644
index 0000000000..82ccde3e39
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/docs/first-run.md
@@ -0,0 +1,9 @@
+# First run on-boarding flow
+
+First Run flow describes the entire experience users have after Firefox has successfully been installed up until the first instance of new tab is shown.
+First run help onboard new users by showing relevant messaging on about:welcome and about:newtab using triplets.
+
+### First Run Multistage
+A full-page multistep experience that shows up on first run since Fx80 with browser.aboutwelcome.enabled pref as true.
+
+Setting browser.aboutwelcome.enabled to false make first run looks like about:newtab and hides about:welcome
diff --git a/browser/components/newtab/content-src/asrouter/docs/index.rst b/browser/components/newtab/content-src/asrouter/docs/index.rst
new file mode 100644
index 0000000000..87476d32ac
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/docs/index.rst
@@ -0,0 +1,104 @@
+================
+Messaging System
+================
+
+Vision
+------
+Firefox must be an opinionated user agent that keeps folks safe, informed and
+effective while browsing the Web. In order to have an opinion, Firefox must
+have a voice.
+
+That voice will **respect the user’s attention** while surfacing contextually
+relevant and timely information tailored to their individual needs and choices.
+
+What does Messaging System support?
+-----------------------------------
+There are several key windows of opportunity, such as the first-run activation
+phase or coordinated feature releases, where Firefox engages with users.
+
+The Firefox Messaging System supports this engagement by targeting messages
+exactly to the users who need to see them and enables the development of new
+user messages that can be easily tested and deployed. It offers standard
+mechanisms to measure user engagement and to perform user messaging experiments
+with reduced effort across engineering teams and a faster delivery cycle from
+ideation to analysis of results.
+
+This translates to **users seeing fewer and more relevant in-product
+messages**, while supporting fast delivery, experimentation, and protection of
+our users time and attention.
+
+Messaging System Overview
+-------------------------
+At the core of the Firefox Messaging System is the Messaging System Router
+(called ASRouter for historical reasons). The router is a generalized Firefox
+component and set of conventions that provides:
+
+* Flexible and configurable routing of local or remote Messages to UI
+ Templates. This allows new message campaigns to be started and controlled
+ on or off-trains
+* Traffic Cop message sequencing and intermediation to prevent multiple
+ messages being concurrently shown
+* Programmable message targeting language to show the right message to the
+ right user at the right time
+* A template library of reusable Message and Notification UIs
+* Full compatibility with Normandy pref-flip experiments
+* Generalized and privacy conscious event telemetry
+* Flexible Frequency Capping to mitigate user message fatigue
+* Localized off train Messages
+* Powerful development/debugging/QA tools on about:newtab#devtools
+
+Message Routing
+---------------
+.. image:: ./message-routing-overview.png
+ :align: center
+ :alt: Message Routing Overview
+
+The Firefox Messaging System implements a separation-of-concerns pattern for
+Messages, UI Templates, and Timing/Targeting mechanisms. This allows us to
+maintain a high standard of security and quality while still allowing for
+maximum flexibility around content creation.
+
+UI Templates
+------------
+We have built a library of reusable Notification and Message interfaces which
+land in the Firefox codebase and ride the trains. These templates have a
+defined schema according to the available design components (e.g. titles, text,
+icons) and access to a set of enhanced user actions such as triggering URLs,
+launching menus, or installing addons, which can be attached to interactive
+elements (such as buttons).
+
+Current templates include\:
+
+* What's New Panel - an icon in the toolbar and menu item that appears if a
+ message is available in the panel, usually after major Firefox releases
+* Moments Page - appears on start-up as a full content page
+* Contextual Feature Recommendation - highlighted word in the Location Bar
+ that, if clicked, drops down a panel with information about a feature
+ relevant to that user at that time
+* First Run - shown on startup in a content page as a set of onboarding cards
+ with calls to action that persist for several days
+* Snippets - short messages that appear on New Tab Page to highlight products,
+ features and initiatives
+* Badging - A colorful dot to highlight icons in the toolbar or menu items in
+ order to draw attention with minimal interruption
+
+Detailed Docs
+-------------
+
+* Read more about `trigger listeners and user action schemas`__.
+
+.. __: /toolkit/components/messaging-system/docs
+
+.. In theory, we ought to be able to use the :glob: directive here to
+.. automatically generate the list below. For unknown reasons, however,
+.. `mach doc` _sometimes_ gets confused and refuses to find patterns like
+.. `*.md`.
+.. toctree::
+ :maxdepth: 2
+
+ simple-cfr-template
+ debugging-docs
+ experiment-guide
+ first-run
+ targeting-attributes
+ targeting-guide
diff --git a/browser/components/newtab/content-src/asrouter/docs/message-routing-overview.png b/browser/components/newtab/content-src/asrouter/docs/message-routing-overview.png
new file mode 100644
index 0000000000..0ec2ec3c14
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/docs/message-routing-overview.png
Binary files differ
diff --git a/browser/components/newtab/content-src/asrouter/docs/simple-cfr-template.rst b/browser/components/newtab/content-src/asrouter/docs/simple-cfr-template.rst
new file mode 100644
index 0000000000..d553547420
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/docs/simple-cfr-template.rst
@@ -0,0 +1,37 @@
+Simple CFR Template
+--------------------
+
+The “Simple CFR Template” is a two-stage UI (a chiclet notification and a door-hanger)
+that shows up on a configurable `trigger condition`__, such as when the user visits a
+particular web page.
+
+.. __: /toolkit/components/messaging-system/docs/TriggerActionSchemas
+
+Warning! Before reading, you should consider whether a `Messaging Experiment is relevant for your needs`__.
+
+.. __: https://docs.google.com/document/d/1S45a_nFn8QRM8gvsxCM6HHROrIQlQQl6fUlJ2j63PGI/edit
+
+.. image:: ./cfr_doorhanger_screenshot.png
+ :align: center
+ :alt: Simple CFR Template 2 stage
+
+Doorhanger Configuration
+=========================
+
+Stage 1 – Chiclet
+++++++++++++++++++
+
+* **chiclet_label**: The text that shows up in the chiclet. 20 characters max.
+* **chiclet_color**: The background color of the chiclet as a HEX code.
+
+
+Stage 2 – Door-hanger
+++++++++++++++++++++++
+
+* **title**: Title text at the top of the door hanger.
+* **body**: A longer paragraph of text.
+* **icon**: An image (please provide a URL or the image file up to 96x96px).
+* **primary_button_label**: The label of the button.
+* **primary_button_action**: The special action triggered by clicking on the button. Choose any of the available `button actions`__. Common examples include opening a section of about:preferences, or opening a URL.
+
+.. __: /toolkit/components/messaging-system/docs/SpecialMessageActionSchemas
diff --git a/browser/components/newtab/content-src/asrouter/docs/targeting-attributes.md b/browser/components/newtab/content-src/asrouter/docs/targeting-attributes.md
new file mode 100644
index 0000000000..128ea2a0b3
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/docs/targeting-attributes.md
@@ -0,0 +1,828 @@
+# Targeting attributes
+
+When you create ASRouter messages such as snippets, contextual feature recommendations, or onboarding cards, you may choose to include **targeting information** with those messages.
+
+Targeting information must be captured in [an expression](./targeting-guide.md) that has access to the following attributes. You may combine and compare any of these attributes as needed.
+
+Please note that some targeting attributes require stricter controls on the telemetry than can be colleted, so when in doubt, ask for review.
+
+## Available attributes
+
+* [addonsInfo](#addonsinfo)
+* [attributionData](#attributiondata)
+* [browserSettings](#browsersettings)
+* [currentDate](#currentdate)
+* [devToolsOpenedCount](#devtoolsopenedcount)
+* [isDefaultBrowser](#isdefaultbrowser)
+* [firefoxVersion](#firefoxversion)
+* [locale](#locale)
+* [localeLanguageCode](#localelanguagecode)
+* [needsUpdate](#needsupdate)
+* [pinnedSites](#pinnedsites)
+* [previousSessionEnd](#previoussessionend)
+* [profileAgeCreated](#profileagecreated)
+* [profileAgeReset](#profileagereset)
+* [providerCohorts](#providercohorts)
+* [region](#region)
+* [searchEngines](#searchengines)
+* [sync](#sync)
+* [topFrecentSites](#topfrecentsites)
+* [totalBookmarksCount](#totalbookmarkscount)
+* [usesFirefoxSync](#usesfirefoxsync)
+* [isFxAEnabled](#isFxAEnabled)
+* [xpinstallEnabled](#xpinstallEnabled)
+* [hasPinnedTabs](#haspinnedtabs)
+* [hasAccessedFxAPanel](#hasaccessedfxapanel)
+* [isWhatsNewPanelEnabled](#iswhatsnewpanelenabled)
+* [totalBlockedCount](#totalblockedcount)
+* [recentBookmarks](#recentbookmarks)
+* [userPrefs](#userprefs)
+* [attachedFxAOAuthClients](#attachedfxaoauthclients)
+* [platformName](#platformname)
+* [scores](#scores)
+* [scoreThreshold](#scorethreshold)
+* [messageImpressions](#messageimpressions)
+* [blockedCountByType](#blockedcountbytype)
+* [isChinaRepack](#ischinarepack)
+* [userId](#userid)
+* [profileRestartCount](#profilerestartcount)
+* [homePageSettings](#homepagesettings)
+* [newtabSettings](#newtabsettings)
+* [isFissionExperimentEnabled](#isfissionexperimentenabled)
+* [activeNotifications](#activenotifications)
+
+## Detailed usage
+
+### `addonsInfo`
+Provides information about the add-ons the user has installed.
+
+Note that the `name`, `userDisabled`, and `installDate` is only available if `isFullData` is `true` (this is usually not the case right at start-up).
+
+**Due to an existing bug, `userDisabled` is not currently available**
+
+#### Examples
+* Has the user installed the unicorn addon?
+```java
+addonsInfo.addons["unicornaddon@mozilla.org"]
+```
+
+* Has the user installed and disabled the unicorn addon?
+```java
+addonsInfo.isFullData && addonsInfo.addons["unicornaddon@mozilla.org"].userDisabled
+```
+
+#### Definition
+```ts
+declare const addonsInfo: Promise<AddonsInfoResponse>;
+interface AddonsInfoResponse {
+ // Does this include extra information requiring I/O?
+ isFullData: boolean;
+ // addonId should be something like activity-stream@mozilla.org
+ [addonId: string]: {
+ // Version of the add-on
+ version: string;
+ // (string) e.g. "extension"
+ type: AddonType;
+ // Version of the add-on
+ isSystem: boolean;
+ // Is the add-on a webextension?
+ isWebExtension: boolean;
+ // The name of the add-on
+ name: string;
+ // Is the add-on disabled?
+ // CURRENTLY UNAVAILABLE due to an outstanding bug
+ userDisabled: boolean;
+ // When was it installed? e.g. "2018-03-10T03:41:06.000Z"
+ installDate: string;
+ };
+}
+```
+### `attributionData`
+
+An object containing information on exactly how Firefox was downloaded
+
+#### Examples
+* Was the browser installed via the `"back_to_school"` campaign?
+```java
+attributionData && attributionData.campaign == "back_to_school"
+```
+
+#### Definition
+```ts
+declare const attributionData: AttributionCode;
+interface AttributionCode {
+ // Descriptor for where the download started from
+ campaign: string,
+ // A source, like addons.mozilla.org, or google.com
+ source: string,
+ // The medium for the download, like if this was referral
+ medium: string,
+ // Additional content, like an addonID for instance
+ content: string
+}
+```
+
+### `browserSettings`
+
+Includes two properties:
+* `attribution`, which indicates how Firefox was downloaded - DEPRECATED - please use [attributionData](#attributiondata)
+* `update`, which has information about how Firefox updates
+
+Note that attribution can be `undefined`, so you should check that it exists first.
+
+#### Examples
+* Is updating enabled?
+```java
+browserSettings.update.enabled
+```
+
+#### Definition
+
+```ts
+declare const browserSettings: {
+ attribution: undefined | {
+ // Referring partner domain, when install happens via a known partner
+ // e.g. google.com
+ source: string;
+ // category of the source, such as "organic" for a search engine
+ // e.g. organic
+ medium: string;
+ // identifier of the particular campaign that led to the download of the product
+ // e.g. back_to_school
+ campaign: string;
+ // identifier to indicate the particular link within a campaign
+ // e.g. https://mozilla.org/some-page
+ content: string;
+ },
+ update: {
+ // Is auto-downloading enabled?
+ autoDownload: boolean;
+ // What release channel, e.g. "nightly"
+ channel: string;
+ // Is updating enabled?
+ enabled: boolean;
+ }
+}
+```
+
+### `currentDate`
+
+The current date at the moment message targeting is checked.
+
+#### Examples
+* Is the current date after Oct 3, 2018?
+```java
+currentDate > "Wed Oct 03 2018 00:00:00"|date
+```
+
+#### Definition
+
+```ts
+declare const currentDate; ECMA262DateString;
+// ECMA262DateString = Date.toString()
+type ECMA262DateString = string;
+```
+
+### `devToolsOpenedCount`
+Number of usages of the web console.
+
+#### Examples
+* Has the user opened the web console more than 10 times?
+```java
+devToolsOpenedCount > 10
+```
+
+#### Definition
+```ts
+declare const devToolsOpenedCount: number;
+```
+
+### `isDefaultBrowser`
+
+Is Firefox the user's default browser?
+
+#### Definition
+
+```ts
+declare const isDefaultBrowser: boolean;
+```
+
+### `firefoxVersion`
+
+The major Firefox version of the browser
+
+#### Examples
+* Is the version of the browser greater than 63?
+```java
+firefoxVersion > 63
+```
+
+#### Definition
+
+```ts
+declare const firefoxVersion: number;
+```
+
+### `locale`
+The current locale of the browser including country code, e.g. `en-US`.
+
+#### Examples
+* Is the locale of the browser either English (US) or German (Germany)?
+```java
+locale in ["en-US", "de-DE"]
+```
+
+#### Definition
+```ts
+declare const locale: string;
+```
+
+### `localeLanguageCode`
+The current locale of the browser NOT including country code, e.g. `en`.
+This is useful for matching all countries of a particular language.
+
+#### Examples
+* Is the locale of the browser any English locale?
+```java
+localeLanguageCode == "en"
+```
+
+#### Definition
+```ts
+declare const localeLanguageCode: string;
+```
+
+### `needsUpdate`
+
+Does the client have the latest available version installed
+
+```ts
+declare const needsUpdate: boolean;
+```
+
+### `pinnedSites`
+The sites (including search shortcuts) that are pinned on a user's new tab page.
+
+#### Examples
+* Has the user pinned any site on `foo.com`?
+```java
+"foo.com" in pinnedSites|mapToProperty("host")
+```
+
+* Does the user have a pinned `duckduckgo.com` search shortcut?
+```java
+"duckduckgo.com" in pinnedSites[.searchTopSite == true]|mapToProperty("host")
+```
+
+#### Definition
+```ts
+interface PinnedSite {
+ // e.g. https://foo.mozilla.com/foo/bar
+ url: string;
+ // e.g. foo.mozilla.com
+ host: string;
+ // is the pin a search shortcut?
+ searchTopSite: boolean;
+}
+declare const pinnedSites: Array<PinnedSite>
+```
+
+### `previousSessionEnd`
+
+Timestamp of the previously closed session.
+
+#### Definition
+```ts
+declare const previousSessionEnd: UnixEpochNumber;
+// UnixEpochNumber is UNIX Epoch timestamp, e.g. 1522843725924
+type UnixEpochNumber = number;
+```
+
+### `profileAgeCreated`
+
+The date the profile was created as a UNIX Epoch timestamp.
+
+#### Definition
+
+```ts
+declare const profileAgeCreated: UnixEpochNumber;
+// UnixEpochNumber is UNIX Epoch timestamp, e.g. 1522843725924
+type UnixEpochNumber = number;
+```
+
+### `profileAgeReset`
+
+The date the profile was reset as a UNIX Epoch timestamp (if it was reset).
+
+#### Examples
+* Was the profile never reset?
+```java
+!profileAgeReset
+```
+
+#### Definition
+```ts
+// profileAgeReset can be undefined if the profile was never reset
+// UnixEpochNumber is number, e.g. 1522843725924
+declare const profileAgeReset: undefined | UnixEpochNumber;
+// UnixEpochNumber is UNIX Epoch timestamp, e.g. 1522843725924
+type UnixEpochNumber = number;
+```
+
+### `providerCohorts`
+
+Information about cohort settings (from prefs, including shield studies) for each provider.
+
+#### Examples
+* Is the user in the "foo_test" cohort for snippets?
+```java
+providerCohorts.snippets == "foo_test"
+```
+
+#### Definition
+
+```ts
+declare const providerCohorts: {
+ [providerId: string]: string;
+}
+```
+
+### `region`
+
+Country code retrieved from `location.services.mozilla.com`. Can be `""` if request did not finish or encountered an error.
+
+#### Examples
+* Is the user in Canada?
+```java
+region == "CA"
+```
+
+#### Definition
+
+```ts
+declare const region: string;
+```
+
+### `searchEngines`
+
+Information about the current and available search engines.
+
+#### Examples
+* Is the current default search engine set to google?
+```java
+searchEngines.current == "google"
+```
+
+#### Definition
+
+```ts
+declare const searchEngines: Promise<SearchEnginesResponse>;
+interface SearchEnginesResponse: {
+ current: SearchEngineId;
+ installed: Array<SearchEngineId>;
+}
+// This is an identifier for a search engine such as "google" or "amazondotcom"
+type SearchEngineId = string;
+```
+
+### `sync`
+
+Information about synced devices.
+
+#### Examples
+* Is at least 1 mobile device synced to this profile?
+```java
+sync.mobileDevices > 0
+```
+
+#### Definition
+
+```ts
+declare const sync: {
+ desktopDevices: number;
+ mobileDevices: number;
+ totalDevices: number;
+}
+```
+
+### `topFrecentSites`
+
+Information about the browser's top 25 frecent sites.
+
+**Please note this is a restricted targeting property that influences what telemetry is allowed to be collected may not be used without review**
+
+
+#### Examples
+* Is mozilla.com in the user's top frecent sites with a frececy greater than 400?
+```java
+"mozilla.com" in topFrecentSites[.frecency >= 400]|mapToProperty("host")
+```
+
+#### Definition
+```ts
+declare const topFrecentSites: Promise<Array<TopSite>>
+interface TopSite {
+ // e.g. https://foo.mozilla.com/foo/bar
+ url: string;
+ // e.g. foo.mozilla.com
+ host: string;
+ frecency: number;
+ lastVisitDate: UnixEpochNumber;
+}
+// UnixEpochNumber is UNIX Epoch timestamp, e.g. 1522843725924
+type UnixEpochNumber = number;
+```
+
+### `totalBookmarksCount`
+
+Total number of bookmarks.
+
+#### Definition
+
+```ts
+declare const totalBookmarksCount: number;
+```
+
+### `usesFirefoxSync`
+
+Does the user use Firefox sync?
+
+#### Definition
+
+```ts
+declare const usesFirefoxSync: boolean;
+```
+
+### `isFxAEnabled`
+
+Does the user have Firefox sync enabled? The service could potentially be turned off [for enterprise builds](https://searchfox.org/mozilla-central/rev/b59a99943de4dd314bae4e44ab43ce7687ccbbec/browser/components/enterprisepolicies/Policies.jsm#327).
+
+#### Definition
+
+```ts
+declare const isFxAEnabled: boolean;
+```
+
+### `xpinstallEnabled`
+
+Pref used by system administrators to disallow add-ons from installed altogether.
+
+#### Definition
+
+```ts
+declare const xpinstallEnabled: boolean;
+```
+
+### `hasPinnedTabs`
+
+Does the user have any pinned tabs in any windows.
+
+#### Definition
+
+```ts
+declare const hasPinnedTabs: boolean;
+```
+
+### `hasAccessedFxAPanel`
+
+Boolean pref that gets set the first time the user opens the FxA toolbar panel
+
+#### Definition
+
+```ts
+declare const hasAccessedFxAPanel: boolean;
+```
+
+### `isWhatsNewPanelEnabled`
+
+Boolean pref that controls if the What's New panel feature is enabled
+
+#### Definition
+
+```ts
+declare const isWhatsNewPanelEnabled: boolean;
+```
+
+### `totalBlockedCount`
+
+Total number of events from the content blocking database
+
+#### Definition
+
+```ts
+declare const totalBlockedCount: number;
+```
+
+### `recentBookmarks`
+
+An array of GUIDs of recent bookmarks as provided by [`NewTabUtils.getRecentBookmarks`](https://searchfox.org/mozilla-central/rev/e0b0c38ee83f99d3cf868bad525ace4a395039f1/toolkit/modules/NewTabUtils.jsm#1087)
+
+#### Definition
+
+```ts
+interface Bookmark {
+ bookmarkGuid: string;
+ url: string;
+ title: string;
+ ...
+}
+declare const recentBookmarks: Array<Bookmark>
+```
+
+### `userPrefs`
+
+Information about user facing prefs configurable from `about:preferences`.
+
+#### Examples
+```java
+userPrefs.cfrFeatures == false
+```
+
+#### Definition
+
+```ts
+declare const userPrefs: {
+ cfrFeatures: boolean;
+ cfrAddons: boolean;
+ snippets: boolean;
+}
+```
+
+### `attachedFxAOAuthClients`
+
+Information about connected services associated with the FxA Account.
+Return an empty array if no account is found or an error occurs.
+
+#### Definition
+
+```
+interface OAuthClient {
+ // OAuth client_id of the service
+ // https://docs.telemetry.mozilla.org/datasets/fxa_metrics/attribution.html#service-attribution
+ id: string;
+ lastAccessedDaysAgo: number;
+}
+
+declare const attachedFxAOAuthClients: Promise<OAuthClient[]>
+```
+
+#### Examples
+```javascript
+{
+ id: "7377719276ad44ee",
+ name: "Pocket",
+ lastAccessTime: 1513599164000
+}
+```
+
+### `platformName`
+
+[Platform information](https://searchfox.org/mozilla-central/rev/05a22d864814cb1e4352faa4004e1f975c7d2eb9/toolkit/modules/AppConstants.jsm#156).
+
+#### Definition
+
+```
+declare const platformName = "linux" | "win" | "macosx" | "android" | "other";
+```
+
+### `scores`
+
+#### Definition
+
+See more in [CFR Machine Learning Experiment](https://bugzilla.mozilla.org/show_bug.cgi?id=1594422).
+
+```
+declare const scores = { [cfrId: string]: number (integer); }
+```
+
+### `scoreThreshold`
+
+#### Definition
+
+See more in [CFR Machine Learning Experiment](https://bugzilla.mozilla.org/show_bug.cgi?id=1594422).
+
+```
+declare const scoreThreshold = integer;
+```
+
+### `messageImpressions`
+
+Dictionary that maps message ids to impression timestamps. Timestamps are stored in
+consecutive order. Can be used to detect first impression of a message, number of
+impressions. Can be used in targeting to show a message if another message has been
+seen.
+Impressions are used for frequency capping so we only store them if the message has
+`frequency` configured.
+Impressions for badges might not work as expected: we add a badge for every opened
+window so the number of impressions stored might be higher than expected. Additionally
+not all badges have `frequency` cap so `messageImpressions` might not be defined.
+Badge impressions should not be used for targeting.
+
+#### Definition
+
+```
+declare const messageImpressions: { [key: string]: Array<UnixEpochNumber> };
+```
+
+### `blockedCountByType`
+
+Returns a breakdown by category of all blocked resources in the past 42 days.
+
+#### Definition
+
+```
+declare const messageImpressions: { [key: string]: number };
+```
+
+#### Examples
+
+```javascript
+Object {
+ trackerCount: 0,
+ cookieCount: 34,
+ cryptominerCount: 0,
+ fingerprinterCount: 3,
+ socialCount: 2
+}
+```
+
+### `isChinaRepack`
+
+Does the user use [the partner repack distributed by Mozilla Online](https://github.com/mozilla-partners/mozillaonline),
+a wholly owned subsidiary of the Mozilla Corporation that operates in China.
+
+#### Definition
+
+```ts
+declare const isChinaRepack: boolean;
+```
+
+### `userId`
+
+A unique user id generated by Normandy (note that this is not clientId).
+
+#### Definition
+
+```ts
+declare const userId: string;
+```
+
+### `profileRestartCount`
+
+A session counter that shows how many times the browser was started.
+More info about the details in [the telemetry docs](https://firefox-source-docs.mozilla.org/toolkit/components/telemetry/concepts/sessions.html).
+
+#### Definition
+
+```ts
+declare const profileRestartCount: number;
+```
+
+### `homePageSettings`
+
+An object reflecting the current settings of the browser home page (about:home)
+
+#### Definition
+
+```ts
+declare const homePageSettings: {
+ isDefault: boolean;
+ isLocked: boolean;
+ isWebExt: boolean;
+ isCustomUrl: boolean;
+ urls: Array<URL>;
+}
+
+interface URL {
+ url: string;
+ host: string;
+}
+```
+
+#### Examples
+
+* Default about:home
+```javascript
+Object {
+ isDefault: true,
+ isLocked: false,
+ isCustomUrl: false,
+ isWebExt: false,
+ urls: [
+ { url: "about:home", host: "" }
+ ],
+}
+```
+
+* Default about:home with locked preference
+```javascript
+Object {
+ isDefault: true,
+ isLocked: true,
+ isCustomUrl: false,
+ isWebExt: false,
+ urls: [
+ { url: "about:home", host: "" }
+ ],
+}
+```
+
+* Custom URL
+```javascript
+Object {
+ isDefault: false,
+ isLocked: false,
+ isCustomUrl: true,
+ isWebExt: false,
+ urls: [
+ { url: "https://www.google.com", host: "google.com" }
+ ],
+}
+```
+
+* Custom URLs
+```javascript
+Object {
+ isDefault: false,
+ isLocked: false,
+ isCustomUrl: true,
+ isWebExt: false,
+ urls: [
+ { url: "https://www.google.com", host: "google.com" },
+ { url: "https://www.youtube.com", host: "youtube.com" }
+ ],
+}
+```
+
+* Web extension
+```javascript
+Object {
+ isDefault: false,
+ isLocked: false,
+ isCustomUrl: false,
+ isWebExt: true,
+ urls: [
+ { url: "moz-extension://123dsa43213acklncd/home.html", host: "" }
+ ],
+}
+```
+
+### `newtabSettings`
+
+An object reflecting the current settings of the browser newtab page (about:newtab)
+
+#### Definition
+
+```ts
+declare const newtabSettings: {
+ isDefault: boolean;
+ isWebExt: boolean;
+ isCustomUrl: boolean;
+ url: string;
+ host: string;
+}
+```
+
+#### Examples
+
+* Default about:newtab
+```javascript
+Object {
+ isDefault: true,
+ isCustomUrl: false,
+ isWebExt: false,
+ url: "about:newtab",
+ host: "",
+}
+```
+
+* Custom URL
+```javascript
+Object {
+ isDefault: false,
+ isCustomUrl: true,
+ isWebExt: false,
+ url: "https://www.google.com",
+ host: "google.com",
+}
+```
+
+* Web extension
+```javascript
+Object {
+ isDefault: false,
+ isCustomUrl: false,
+ isWebExt: true,
+ url: "moz-extension://123dsa43213acklncd/home.html",
+ host: "",
+}
+```
+
+### `isFissionExperimentEnabled`
+
+A boolean. `true` if we're running Fission experiment, `false` otherwise.
+
+### `activeNotifications`
+
+True when an infobar style message is displayed or when the awesomebar is
+expanded to show a message (for example onboarding tips).
diff --git a/browser/components/newtab/content-src/asrouter/docs/targeting-guide.md b/browser/components/newtab/content-src/asrouter/docs/targeting-guide.md
new file mode 100644
index 0000000000..901756bca5
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/docs/targeting-guide.md
@@ -0,0 +1,37 @@
+# Guide to targeting with JEXL
+
+For a more in-depth explanation of JEXL syntax you can read the [Normady project docs](https://mozilla.github.io/normandy/user/filters.html?highlight=jexl).
+
+### How to write JEXL targeting expressions
+A message needs to contain the `targeting` property (JEXL string) which is evaluated against the provided attributes.
+Examples:
+
+```javascript
+{
+ "id": "7864",
+ "content": {...},
+ // simple equality check
+ "targeting": "usesFirefoxSync == true"
+}
+
+{
+ "id": "7865",
+ "content": {...},
+ // using JEXL transforms and combining two attributes
+ "targeting": "usesFirefoxSync == true && profileAgeCreated > '2018-01-07'|date"
+}
+
+{
+ "id": "7866",
+ "content": {...},
+ // targeting addon information
+ "targeting": "addonsInfo.addons['activity-stream@mozilla.org'].name == 'Activity Stream'"
+}
+
+{
+ "id": "7866",
+ "content": {...},
+ // targeting based on time
+ "targeting": "currentDate > '2018-08-08'|date"
+}
+```
diff --git a/browser/components/newtab/content-src/asrouter/docs/telemetry-screenshot.png b/browser/components/newtab/content-src/asrouter/docs/telemetry-screenshot.png
new file mode 100644
index 0000000000..b27b4ab958
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/docs/telemetry-screenshot.png
Binary files differ
diff --git a/browser/components/newtab/content-src/asrouter/rich-text-strings.js b/browser/components/newtab/content-src/asrouter/rich-text-strings.js
new file mode 100644
index 0000000000..6a52732ad1
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/rich-text-strings.js
@@ -0,0 +1,44 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { FluentBundle } from "fluent";
+
+/**
+ * Properties that allow rich text MUST be added to this list.
+ * key: the localization_id that should be used
+ * value: a property or array of properties on the message.content object
+ */
+const RICH_TEXT_CONFIG = {
+ text: ["text", "scene1_text"],
+ success_text: "success_text",
+ error_text: "error_text",
+ scene2_text: "scene2_text",
+ amo_html: "amo_html",
+ privacy_html: "scene2_privacy_html",
+ disclaimer_html: "scene2_disclaimer_html",
+};
+
+export const RICH_TEXT_KEYS = Object.keys(RICH_TEXT_CONFIG);
+
+/**
+ * Generates an array of messages suitable for fluent's localization provider
+ * including all needed strings for rich text.
+ * @param {object} content A .content object from an ASR message (i.e. message.content)
+ * @returns {FluentBundle[]} A array containing the fluent message context
+ */
+export function generateBundles(content) {
+ const bundle = new FluentBundle("en-US");
+
+ RICH_TEXT_KEYS.forEach(key => {
+ const attrs = RICH_TEXT_CONFIG[key];
+ const attrsToTry = Array.isArray(attrs) ? [...attrs] : [attrs];
+ let string = "";
+ while (!string && attrsToTry.length) {
+ const attr = attrsToTry.pop();
+ string = content[attr];
+ }
+ bundle.addMessages(`${key} = ${string}`);
+ });
+ return [bundle];
+}
diff --git a/browser/components/newtab/content-src/asrouter/schemas/message-format.md b/browser/components/newtab/content-src/asrouter/schemas/message-format.md
new file mode 100644
index 0000000000..debcce0572
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/schemas/message-format.md
@@ -0,0 +1,101 @@
+## Activity Stream Router message format
+
+Field name | Type | Required | Description | Example / Note
+--- | --- | --- | --- | ---
+`id` | `string` | Yes | A unique identifier for the message that should not conflict with any other previous message | `ONBOARDING_1`
+`template` | `string` | Yes | An id matching an existing Activity Stream Router template | [See example](https://github.com/mozilla/activity-stream/blob/33669c67c2269078a6d3d6d324fb48175d98f634/system-addon/content-src/message-center/templates/SimpleSnippet.jsx)
+`content` | `object` | Yes | An object containing all variables/props to be rendered in the template. Subset of allowed tags detailed below. | [See example below](#html-subset)
+`bundled` | `integer` | No | The number of messages of the same template this one should be shown with | [See example below](#a-bundled-message-example)
+`order` | `integer` | No | If bundled with other messages of the same template, which order should this one be placed in? Defaults to 0 if no order is desired | [See example below](#a-bundled-message-example)
+`campaign` | `string` | No | Campaign id that the message belongs to | `RustWebAssembly`
+`targeting` | `string` `JEXL` | No | A [JEXL expression](http://normandy.readthedocs.io/en/latest/user/filter_expressions.html#jexl-basics) with all targeting information needed in order to decide if the message is shown | Not yet implemented, [Examples](#targeting-attributes)
+`trigger` | `string` | No | An event or condition upon which the message will be immediately shown. This can be combined with `targeting`. Messages that define a trigger will not be shown during non-trigger-based passive message rotation.
+`trigger.params` | `[string]` | No | A set of hostnames passed down as parameters to the trigger condition. Used to restrict the number of domains where the trigger/message is valid. | [See example below](#trigger-params)
+`trigger.patterns` | `[string]` | No | A set of patterns that match multiple hostnames passed down as parameters to the trigger condition. Used to restrict the number of domains where the trigger/message is valid. | [See example below](#trigger-patterns)
+`frequency` | `object` | No | A definition for frequency cap information for the message
+`frequency.lifetime` | `integer` | No | The maximum number of lifetime impressions for the message.
+`frequency.custom` | `array` | No | An array of frequency cap definition objects including `period`, a time period in milliseconds, and `cap`, a max number of impressions for that period.
+
+### Message example
+```javascript
+{
+ id: "ONBOARDING_1",
+ template: "simple_snippet",
+ content: {
+ title: "Find it faster",
+ body: "Access all of your favorite search engines with a click. Search the whole Web or just one website from the search box."
+ },
+ targeting: "usesFirefoxSync && !addonsInfo.addons['activity-stream@mozilla.org']",
+ frequency: {
+ lifetime: 20,
+ custom: [{period: 86400000, cap: 5}, {period: 3600000, cap: 1}]
+ }
+}
+```
+
+### A Bundled Message example
+The following 2 messages have a `bundled` property, indicating that they should be shown together, since they have the same template. The number `2` indicates that this message should be shown in a bundle of 2 messages of the same template. The order property defines that ONBOARDING_2 should be shown after ONBOARDING_3 in the bundle.
+```javascript
+{
+ id: "ONBOARDING_2",
+ template: "onboarding",
+ bundled: 2,
+ order: 2,
+ content: {
+ title: "Private Browsing",
+ body: "Browse by yourself. Private Browsing with Tracking Protection blocks online trackers that follow you around the web."
+ },
+ targeting: "",
+ trigger: "firstRun"
+}
+{
+ id: "ONBOARDING_3",
+ template: "onboarding",
+ bundled: 2,
+ order: 1,
+ content: {
+ title: "Find it faster",
+ body: "Access all of your favorite search engines with a click. Search the whole Web or just one website from the search box."
+ },
+ targeting: "",
+ trigger: "firstRun"
+}
+```
+
+### HTML subset
+The following tags are allowed in the content of the snippet: `i, b, u, strong, em, br`.
+
+Links cannot be rendered using regular anchor tags because [Fluent does not allow for href attributes](https://github.com/projectfluent/fluent.js/blob/a03d3aa833660f8c620738b26c80e46b1a4edb05/fluent-dom/src/overlay.js#L13). They will be wrapped in custom tags, for example `<cta>link</cta>` and the url will be provided as part of the payload:
+```
+{
+ "id": "7899",
+ "content": {
+ "text": "Use the CMD (CTRL) + T keyboard shortcut to <cta>open a new tab quickly!</cta>",
+ "links": {
+ "cta": {
+ "url": "https://support.mozilla.org/en-US/kb/keyboard-shortcuts-perform-firefox-tasks-quickly"
+ }
+ }
+ }
+}
+```
+If a tag that is not on the allowed is used, the text content will be extracted and displayed.
+
+Grouping multiple allowed elements is not possible, only the first level will be used: `<u><b>text</b></u>` will be interpreted as `<u>text</u>`.
+
+### Trigger params
+A set of hostnames that need to exactly match the location of the selected tab in order for the trigger to execute.
+```
+["github.com", "wwww.github.com"]
+```
+More examples in the [CFRMessageProvider](https://github.com/mozilla/activity-stream/blob/e76ce12fbaaac1182aa492b84fc038f78c3acc33/lib/CFRMessageProvider.jsm#L40-L47).
+
+### Trigger patterns
+A set of patterns that can match multiple hostnames. When the location of the selected tab matches one of the patterns it can execute a trigger.
+```
+["*://*.github.com"] // can match `github.com` but also match `https://gist.github.com/`
+```
+More [MatchPattern examples](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Match_patterns#Examples).
+
+### Targeting attributes
+(This section has moved to [targeting-attributes.md](../docs/targeting-attributes.md)).
diff --git a/browser/components/newtab/content-src/asrouter/schemas/message-group.schema.json b/browser/components/newtab/content-src/asrouter/schemas/message-group.schema.json
new file mode 100644
index 0000000000..64f30e7c49
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/schemas/message-group.schema.json
@@ -0,0 +1,63 @@
+{
+ "title": "MessageGroup",
+ "description": "Configuration object for groups of Messaging System messages",
+ "type": "object",
+ "version": "1.0.0",
+ "properties": {
+ "id": {
+ "type": "string",
+ "description": "A unique identifier for the message that should not conflict with any other previous message."
+ },
+ "enabled": {
+ "type": "boolean",
+ "description": "Enables or disables all messages associated with this group."
+ },
+ "userPreferences": {
+ "type": "array",
+ "description": "Collection of preferences that control if the group is enabled.",
+ "items": {
+ "type": "string",
+ "description": "Preference name"
+ }
+ },
+ "frequency": {
+ "type": "object",
+ "description": "An object containing frequency cap information for a message.",
+ "properties": {
+ "lifetime": {
+ "type": "integer",
+ "description": "The maximum lifetime impressions for a message.",
+ "minimum": 1,
+ "maximum": 100
+ },
+ "custom": {
+ "type": "array",
+ "description": "An array of custom frequency cap definitions.",
+ "items": {
+ "description": "A frequency cap definition containing time and max impression information",
+ "type": "object",
+ "properties": {
+ "period": {
+ "oneOf": [
+ {
+ "type": "integer",
+ "description": "Period of time in milliseconds (e.g. 86400000 for one day)"
+ }
+ ]
+ },
+ "cap": {
+ "type": "integer",
+ "description": "The maximum impressions for the message within the defined period.",
+ "minimum": 1,
+ "maximum": 100
+ }
+ },
+ "required": ["period", "cap"]
+ }
+ }
+ }
+ }
+ },
+ "required": ["id", "enabled"],
+ "additionalProperties": false
+}
diff --git a/browser/components/newtab/content-src/asrouter/schemas/panel/cfr-fxa-bookmark.schema.json b/browser/components/newtab/content-src/asrouter/schemas/panel/cfr-fxa-bookmark.schema.json
new file mode 100644
index 0000000000..2ea50d482d
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/schemas/panel/cfr-fxa-bookmark.schema.json
@@ -0,0 +1,163 @@
+{
+ "title": "CFRFxABookmark",
+ "description": "A message shown in the bookmark panel when user adds or edits a bookmark",
+ "version": "1.0.0",
+ "type": "object",
+ "definitions": {
+ "plainText": {
+ "description": "Plain text (no HTML allowed)",
+ "type": "string"
+ },
+ "richText": {
+ "description": "Text with HTML subset allowed: i, b, u, strong, em, br",
+ "type": "string"
+ },
+ "link_url": {
+ "description": "Target for links or buttons",
+ "type": "string",
+ "format": "uri"
+ }
+ },
+ "properties": {
+ "title": {
+ "description": "Shown at the top of the message in the largest font size.",
+ "oneOf": [
+ {
+ "allOf": [
+ {"$ref": "#/definitions/richText"},
+ {"description": "Message to be shown"}
+ ]
+ },
+ {
+ "type": "object",
+ "properties": {
+ "string_id": {
+ "type": "string",
+ "description": "Fluent id of localized string"
+ }
+ },
+ "required": ["string_id"]
+ }
+ ]
+ },
+ "text": {
+ "description": "Longest part of the message, below the title, provides explanation.",
+ "oneOf": [
+ {
+ "allOf": [
+ {"$ref": "#/definitions/richText"},
+ {"description": "Message to be shown"}
+ ]
+ },
+ {
+ "type": "object",
+ "properties": {
+ "string_id": {
+ "type": "string",
+ "description": "Fluent id of localized string"
+ }
+ },
+ "required": ["string_id"]
+ }
+ ]
+ },
+ "cta": {
+ "description": "Link shown at the bottom of the message, call to action",
+ "oneOf": [
+ {
+ "allOf": [
+ {"$ref": "#/definitions/richText"},
+ {"description": "Message to be shown"}
+ ]
+ },
+ {
+ "type": "object",
+ "properties": {
+ "string_id": {
+ "type": "string",
+ "description": "Fluent id of localized string"
+ }
+ },
+ "required": ["string_id"]
+ }
+ ]
+ },
+ "info_icon": {
+ "type": "object",
+ "description": "The small icon displayed in the top right corner of the panel. Not configurable, only the tooltip text." ,
+ "properties": {
+ "tooltiptext": {
+ "oneOf": [
+ {
+ "allOf": [
+ {"$ref": "#/definitions/plainText"},
+ {"description": "Message to be shown"}
+ ]
+ },
+ {
+ "type": "object",
+ "properties": {
+ "string_id": {
+ "type": "string",
+ "description": "Fluent id of localized string"
+ }
+ },
+ "required": ["string_id"]
+ }
+ ]
+ }
+ },
+ "required": ["tooltiptext"]
+ },
+ "close_button": {
+ "type": "object",
+ "description": "The small dissmiss icon displayed in the top right corner of the message. Not configurable, only the tooltip text." ,
+ "properties": {
+ "tooltiptext": {
+ "oneOf": [
+ {
+ "allOf": [
+ {"$ref": "#/definitions/plainText"},
+ {"description": "Message to be shown"}
+ ]
+ },
+ {
+ "type": "object",
+ "properties": {
+ "string_id": {
+ "type": "string",
+ "description": "Fluent id of localized string"
+ }
+ },
+ "required": ["string_id"]
+ }
+ ]
+ }
+ },
+ "required": ["tooltiptext"]
+ },
+ "color": {
+ "description": "Message text color",
+ "allOf": [
+ {"$ref": "#/definitions/plainText"},
+ {"description": "Valid CSS color"}
+ ]
+ },
+ "background_color_1": {
+ "description": "Configurable background color through CSS gradient",
+ "allOf": [
+ {"$ref": "#/definitions/plainText"},
+ {"description": "Valid CSS color"}
+ ]
+ },
+ "background_color_2": {
+ "description": "Configurable background color through CSS gradient",
+ "allOf": [
+ {"$ref": "#/definitions/plainText"},
+ {"description": "Valid CSS color"}
+ ]
+ }
+ },
+ "additionalProperties": false,
+ "required": ["title", "text", "cta", "info_icon"]
+}
diff --git a/browser/components/newtab/content-src/asrouter/schemas/provider-response.schema.json b/browser/components/newtab/content-src/asrouter/schemas/provider-response.schema.json
new file mode 100644
index 0000000000..76e2249d31
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/schemas/provider-response.schema.json
@@ -0,0 +1,75 @@
+{
+ "title": "ProviderResponse",
+ "description": "A response object for remote providers of AS Router",
+ "type": "object",
+ "version": "6.1.0",
+ "properties": {
+ "messages": {
+ "type": "array",
+ "description": "An array of router messages",
+ "items": {
+ "title": "RouterMessage",
+ "description": "A definition of an individual message",
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string",
+ "description": "A unique identifier for the message that should not conflict with any other previous message"
+ },
+ "template": {
+ "type": "string",
+ "description": "An id matching an existing Activity Stream Router template",
+ "enum": ["simple_snippet"]
+ },
+ "bundled": {
+ "type": "integer",
+ "description": "The number of messages of the same template this one should be shown with (optional)"
+ },
+ "order": {
+ "type": "integer",
+ "minimum": 0,
+ "description": "If bundled with other messages of the same template, which order should this one be placed in? (optional - defaults to 0)"
+ },
+ "content": {
+ "type": "object",
+ "description": "An object containing all variables/props to be rendered in the template. See individual template schemas for details."
+ },
+ "targeting": {
+ "type": "string",
+ "description": "A JEXL expression representing targeting information"
+ },
+ "personalized": {
+ "type": "boolean",
+ "description": "Is a personalized score applied to the provider's messages?"
+ },
+ "personalizedModelVersion": {
+ "type": "string",
+ "description": "The version of the model use for personalization"
+ },
+ "trigger": {
+ "type": "object",
+ "description": "An action to trigger potentially showing the message",
+ "properties": {
+ "id": {
+ "type": "string",
+ "description": "A string identifying the trigger action",
+ "enum": ["firstRun", "openURL"]
+ },
+ "params": {
+ "type": "array",
+ "description": "An optional array of string parameters for the trigger action",
+ "items": {
+ "type": "string",
+ "description": "A parameter for the trigger action"
+ }
+ }
+ },
+ "required": ["id"]
+ }
+ },
+ "required": ["id", "template", "content"]
+ }
+ }
+ },
+ "required": ["messages"]
+}
diff --git a/browser/components/newtab/content-src/asrouter/template-utils.js b/browser/components/newtab/content-src/asrouter/template-utils.js
new file mode 100644
index 0000000000..8d6109a968
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/template-utils.js
@@ -0,0 +1,21 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+export function safeURI(url) {
+ if (!url) {
+ return "";
+ }
+ const { protocol } = new URL(url);
+ const isAllowed = [
+ "http:",
+ "https:",
+ "data:",
+ "resource:",
+ "chrome:",
+ ].includes(protocol);
+ if (!isAllowed) {
+ console.warn(`The protocol ${protocol} is not allowed for template URLs.`); // eslint-disable-line no-console
+ }
+ return isAllowed ? url : "";
+}
diff --git a/browser/components/newtab/content-src/asrouter/templates/CFR/templates/CFRUrlbarChiclet.schema.json b/browser/components/newtab/content-src/asrouter/templates/CFR/templates/CFRUrlbarChiclet.schema.json
new file mode 100644
index 0000000000..5758efd686
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/CFR/templates/CFRUrlbarChiclet.schema.json
@@ -0,0 +1,75 @@
+{
+ "title": "CFRUrlbarChiclet",
+ "description": "A template with a chiclet button with text.",
+ "version": "1.0.0",
+ "type": "object",
+ "definitions": {
+ "plainText": {
+ "description": "Plain text (no HTML allowed)",
+ "type": "string"
+ },
+ "linkUrl": {
+ "description": "Target for links or buttons",
+ "type": "string",
+ "format": "uri"
+ }
+ },
+ "properties": {
+ "category": {
+ "type": "string",
+ "description": "Attribute used for different groups of messages from the same provider"
+ },
+ "layout": {
+ "type": "string",
+ "description": "Describes how content should be displayed.",
+ "enum": ["chiclet_open_url"]
+ },
+ "bucket_id": {
+ "type": "string",
+ "description": "A bucket identifier for the addon. This is used in order to anonymize telemetry for history-sensitive targeting."
+ },
+ "notification_text": {
+ "description": "The text in the small blue chicklet that appears in the URL bar. This can be a reference to a localized string in Firefox or just a plain string.",
+ "oneOf": [
+ {
+ "type": "string",
+ "description": "Message shown in the location bar notification."
+ },
+ {
+ "type": "object",
+ "properties": {
+ "string_id": {
+ "type": "string",
+ "description": "Id of localized string for the location bar notification."
+ }
+ },
+ "required": ["string_id"]
+ }
+ ]
+ },
+ "active_color": {
+ "type": "string",
+ "description": "Background color of the button"
+ },
+ "action": {
+ "type": "object",
+ "properties": {
+ "url": {
+ "description": "The page to open when the button is clicked.",
+ "allOf": [
+ {"$ref": "#/definitions/linkUrl"},
+ {"description": "Icon associated with the message"}
+ ]
+ },
+ "where": {
+ "description": "Should it open in a new tab or the current tab",
+ "enum": ["current", "tabshifted"]
+ }
+ },
+ "additionalProperties": "false",
+ "required": ["url", "where"]
+ }
+ },
+ "additionalProperties": false,
+ "required": ["layout", "category", "bucket_id", "notification_text", "action"]
+}
diff --git a/browser/components/newtab/content-src/asrouter/templates/CFR/templates/ExtensionDoorhanger.schema.json b/browser/components/newtab/content-src/asrouter/templates/CFR/templates/ExtensionDoorhanger.schema.json
new file mode 100644
index 0000000000..fd9e3acc0e
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/CFR/templates/ExtensionDoorhanger.schema.json
@@ -0,0 +1,365 @@
+{
+ "title": "ExtensionDoorhanger",
+ "description": "A template with a heading, addon icon, title and description. No markup allowed.",
+ "version": "1.0.0",
+ "type": "object",
+ "definitions": {
+ "plainText": {
+ "description": "Plain text (no HTML allowed)",
+ "type": "string"
+ },
+ "linkUrl": {
+ "description": "Target for links or buttons",
+ "type": "string",
+ "format": "uri"
+ }
+ },
+ "properties": {
+ "category": {
+ "type": "string",
+ "description": "Attribute used for different groups of messages from the same provider"
+ },
+ "layout": {
+ "type": "string",
+ "description": "Attribute used for different groups of messages from the same provider",
+ "enum": ["short_message", "message_and_animation", "icon_and_message", "addon_recommendation"]
+ },
+ "anchor_id": {
+ "type": "string",
+ "description": "A DOM element ID that the pop-over will be anchored."
+ },
+ "bucket_id": {
+ "type": "string",
+ "description": "A bucket identifier for the addon. This is used in order to anonymize telemetry for history-sensitive targeting."
+ },
+ "skip_address_bar_notifier": {
+ "type": "boolean",
+ "description": "Skip the 'Recommend' notifier and show directly."
+ },
+ "persistent_doorhanger": {
+ "type": "boolean",
+ "description": "Prevent the doorhanger from being dismissed if user interacts with the page or switches between applications."
+ },
+ "notification_text": {
+ "description": "The text in the small blue chicklet that appears in the URL bar. This can be a reference to a localized string in Firefox or just a plain string.",
+ "oneOf": [
+ {
+ "type": "string",
+ "description": "Message shown in the location bar notification."
+ },
+ {
+ "type": "object",
+ "properties": {
+ "string_id": {
+ "type": "string",
+ "description": "Id of localized string for the location bar notification."
+ }
+ },
+ "required": ["string_id"]
+ }
+ ]
+ },
+ "info_icon": {
+ "type": "object",
+ "description": "The small icon displayed in the top right corner of the pop-over. Should be 19x19px, svg or png. Defaults to a small question mark." ,
+ "properties": {
+ "label": {
+ "oneOf": [
+ {
+ "type": "object",
+ "properties": {
+ "attributes": {
+ "type": "object",
+ "properties": {
+ "tooltiptext": {
+ "type": "string",
+ "description": "Text for button tooltip used to provide information about the doorhanger."
+ }
+ },
+ "required": ["tooltiptext"]
+ }
+ },
+ "required": ["attributes"]
+ },
+ {
+ "type": "object",
+ "properties": {
+ "string_id": {
+ "type": "string",
+ "description": "Id of localized string used to provide information about the doorhanger."
+ }
+ },
+ "required": ["string_id"]
+ }
+ ]
+ },
+ "sumo_path": {
+ "type": "string",
+ "description": "Last part of the path in the URL to the support page with the information about the doorhanger.",
+ "examples": ["extensionpromotions", "extensionrecommendations"]
+ }
+ }
+ },
+ "learn_more": {
+ "type": "string",
+ "description": "Last part of the path in the SUMO URL to the support page with the information about the doorhanger.",
+ "examples": ["extensionpromotions", "extensionrecommendations"]
+ },
+ "heading_text": {
+ "description": "The larger heading text displayed in the pop-over. This can be a reference to a localized string in Firefox or just a plain string.",
+ "oneOf": [
+ {
+ "type": "string",
+ "description": "The message displayed in the title of the extension doorhanger"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "string_id": {
+ "type": "string"
+ }
+ },
+ "required": ["string_id"],
+ "description": "Id of localized string for extension doorhanger title"
+ }
+ ]
+ },
+ "icon": {
+ "description": "The icon displayed in the pop-over. Should be 32x32px or 64x64px and png/svg.",
+ "allOf": [
+ {"$ref": "#/definitions/linkUrl"},
+ {"description": "Icon associated with the message"}
+ ]
+ },
+ "icon_dark_theme": {
+ "type": "string",
+ "description": "Pop-over icon, dark theme variant. Should be 32x32px or 64x64px and png/svg."
+ },
+ "icon_class": {
+ "type": "string",
+ "description": "CSS class of the pop-over icon."
+ },
+ "addon": {
+ "description": "Addon information including AMO URL.",
+ "type": "object",
+ "properties": {
+ "id": {
+ "allOf": [
+ {"$ref": "#/definitions/plainText"},
+ {"description": "Unique addon ID"}
+ ]
+ },
+ "title": {
+ "allOf": [
+ {"$ref": "#/definitions/plainText"},
+ {"description": "Addon name"}
+ ]
+ },
+ "author": {
+ "allOf": [
+ {"$ref": "#/definitions/plainText"},
+ {"description": "Addon author"}
+ ]
+ },
+ "icon": {
+ "description": "The icon displayed in the pop-over. Should be 64x64px and png/svg.",
+ "allOf": [
+ {"$ref": "#/definitions/linkUrl"},
+ {"description": "Addon icon"}
+ ]
+ },
+ "rating": {
+ "type": "number",
+ "minimum": 0,
+ "maximum": 5,
+ "description": "Star rating"
+ },
+ "users": {
+ "type": "integer",
+ "minimum": 0,
+ "description": "Installed users"
+ },
+ "amo_url": {
+ "allOf": [
+ {"$ref": "#/definitions/linkUrl"},
+ {"description": "Link that offers more information related to the addon."}
+ ]
+ }
+ },
+ "required": ["title", "author", "icon", "amo_url"]
+ },
+ "text": {
+ "description": "The body text displayed in the pop-over. This can be a reference to a localized string in Firefox or just a plain string.",
+ "oneOf": [
+ {
+ "type": "string",
+ "description": "Description message of the addon."
+ },
+ {
+ "type": "object",
+ "properties": {
+ "string_id": {
+ "type": "string",
+ "description": "Id of string to localized addon description"
+ }
+ },
+ "required": ["string_id"]
+ }
+ ]
+ },
+ "descriptionDetails": {
+ "description": "Additional information and steps on how to use",
+ "type": "object",
+ "properties": {
+ "steps": {
+ "description": "Array of messages or string_ids",
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "string_id": {
+ "type": "string",
+ "description": "Id of string to localized addon description"
+ }
+ },
+ "required": ["string_id"]
+ }
+ }
+ },
+ "required": ["steps"]
+ },
+ "buttons": {
+ "description": "The label and functionality for the buttons in the pop-over.",
+ "type": "object",
+ "properties": {
+ "primary": {
+ "type": "object",
+ "properties": {
+ "label": {
+ "type": "object",
+ "oneOf": [
+ {
+ "properties": {
+ "value": {
+ "allOf": [
+ {"$ref": "#/definitions/plainText"},
+ {"description": "Button label override used when a localized version is not available."}
+ ]
+ },
+ "attributes": {
+ "type": "object",
+ "properties": {
+ "accesskey": {
+ "type": "string",
+ "description": "A single character to be used as a shortcut key for the secondary button. This should be one of the characters that appears in the button label."
+ }
+ },
+ "required": ["accesskey"],
+ "description": "Button attributes."
+ }
+ },
+ "required": ["value", "attributes"]
+ },
+ {
+ "properties": {
+ "string_id": {
+ "allOf": [
+ {"$ref": "#/definitions/plainText"},
+ {"description": "Id of localized string for button"}
+ ]
+ }
+ },
+ "required": ["string_id"]
+ }
+ ],
+ "description": "Id of localized string or message override."
+ },
+ "action": {
+ "type": "object",
+ "properties": {
+ "type": {
+ "type": "string",
+ "description": "Action dispatched by the button."
+ },
+ "data": {
+ "properties": {
+ "url": {
+ "type": "string",
+ "$comment": "This is dynamically generated from the addon.id. See CFRPageActions.jsm",
+ "description": "URL used in combination with the primary action dispatched."
+ }
+ }
+ }
+ }
+ }
+ },
+ "secondary": {
+ "type": "object",
+ "properties": {
+ "label": {
+ "type": "object",
+ "oneOf": [
+ {
+ "properties": {
+ "value": {
+ "allOf": [
+ {"$ref": "#/definitions/plainText"},
+ {"description": "Button label override used when a localized version is not available."}
+ ]
+ },
+ "attributes": {
+ "type": "object",
+ "properties": {
+ "accesskey": {
+ "type": "string",
+ "description": "A single character to be used as a shortcut key for the secondary button. This should be one of the characters that appears in the button label."
+ }
+ },
+ "required": ["accesskey"],
+ "description": "Button attributes."
+ }
+ },
+ "required": ["value", "attributes"]
+ },
+ {
+ "properties": {
+ "string_id": {
+ "allOf": [
+ {"$ref": "#/definitions/plainText"},
+ {"description": "Id of localized string for button"}
+ ]
+ }
+ },
+ "required": ["string_id"]
+ }
+ ],
+ "description": "Id of localized string or message override."
+ },
+ "action": {
+ "type": "object",
+ "properties": {
+ "type": {
+ "type": "string",
+ "description": "Action dispatched by the button."
+ },
+ "data": {
+ "properties": {
+ "url": {
+ "allOf": [
+ {"$ref": "#/definitions/linkUrl"},
+ {"description": "URL used in combination with the primary action dispatched."}
+ ]
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "additionalProperties": false,
+ "required": ["layout", "category", "bucket_id", "notification_text", "heading_text", "text", "buttons"]
+}
diff --git a/browser/components/newtab/content-src/asrouter/templates/CFR/templates/InfoBar.schema.json b/browser/components/newtab/content-src/asrouter/templates/CFR/templates/InfoBar.schema.json
new file mode 100644
index 0000000000..3bbaa1ca4f
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/CFR/templates/InfoBar.schema.json
@@ -0,0 +1,96 @@
+{
+ "title": "InfoBar",
+ "description": "A template with an image, test and buttons.",
+ "version": "1.0.0",
+ "type": "object",
+ "definitions": {
+ "plainText": {
+ "description": "Plain text (no HTML allowed)",
+ "type": "string"
+ },
+ "linkUrl": {
+ "description": "Target for links or buttons",
+ "type": "string",
+ "format": "uri"
+ }
+ },
+ "properties": {
+ "type": {
+ "type": "string",
+ "description": "Should the message be global (persisted across tabs) or local (disappear when switching to a different tab).",
+ "enum": ["global", "tab"]
+ },
+ "text": {
+ "description": "The text show in the notification box.",
+ "oneOf": [
+ {
+ "type": "string",
+ "description": "Message shown in the location bar notification."
+ },
+ {
+ "type": "object",
+ "properties": {
+ "string_id": {
+ "type": "string",
+ "description": "Id of localized string for the location bar notification."
+ }
+ },
+ "required": ["string_id"]
+ }
+ ]
+ },
+ "buttons": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "label": {
+ "description": "The text label of the button.",
+ "oneOf": [
+ {
+ "type": "string",
+ "description": "Message content for the button."
+ },
+ {
+ "type": "object",
+ "properties": {
+ "string_id": {
+ "type": "string",
+ "description": "Id of localized string for the button."
+ }
+ },
+ "required": ["string_id"]
+ }
+ ]
+ },
+ "primary": {
+ "type": "boolean",
+ "description": "Is this the primary button?"
+ },
+ "accessKey": {
+ "type": "string",
+ "description": "Keyboard shortcut letter."
+ },
+ "action": {
+ "type": "object",
+ "properties": {
+ "type": {
+ "type": "string",
+ "description": "Action dispatched by the button."
+ },
+ "data": {
+ "type": "object"
+ }
+ },
+ "required": ["type"],
+ "additionalProperties": false
+ }
+ },
+ "required": ["label", "action", "accessKey"],
+ "additionalProperties": false
+ }
+ }
+ },
+ "additionalProperties": false,
+ "required": ["text", "buttons"]
+}
diff --git a/browser/components/newtab/content-src/asrouter/templates/EOYSnippet/EOYSnippet.jsx b/browser/components/newtab/content-src/asrouter/templates/EOYSnippet/EOYSnippet.jsx
new file mode 100644
index 0000000000..f324a69853
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/EOYSnippet/EOYSnippet.jsx
@@ -0,0 +1,153 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import React from "react";
+import { SimpleSnippet } from "../SimpleSnippet/SimpleSnippet";
+
+class EOYSnippetBase extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.handleSubmit = this.handleSubmit.bind(this);
+ }
+
+ /**
+ * setFrequencyValue - `frequency` form parameter value should be `monthly`
+ * if `monthly-checkbox` is selected or `single` otherwise
+ */
+ setFrequencyValue() {
+ const frequencyCheckbox = this.refs.form.querySelector("#monthly-checkbox");
+ if (frequencyCheckbox.checked) {
+ this.refs.form.querySelector("[name='frequency']").value = "monthly";
+ }
+ }
+
+ handleSubmit(event) {
+ event.preventDefault();
+ this.props.sendClick(event);
+ this.setFrequencyValue();
+ if (!this.props.content.do_not_autoblock) {
+ this.props.onBlock();
+ }
+ this.refs.form.submit();
+ }
+
+ renderDonations() {
+ const fieldNames = ["first", "second", "third", "fourth"];
+ const numberFormat = new Intl.NumberFormat(
+ this.props.content.locale || navigator.language,
+ {
+ style: "currency",
+ currency: this.props.content.currency_code,
+ minimumFractionDigits: 0,
+ }
+ );
+ // Default to `second` button
+ const { selected_button } = this.props.content;
+ const btnStyle = {
+ color: this.props.content.button_color,
+ backgroundColor: this.props.content.button_background_color,
+ };
+ const donationURLParams = [];
+ const paramsStartIndex = this.props.content.donation_form_url.indexOf("?");
+ for (const entry of new URLSearchParams(
+ this.props.content.donation_form_url.slice(paramsStartIndex)
+ ).entries()) {
+ donationURLParams.push(entry);
+ }
+
+ return (
+ <form
+ className="EOYSnippetForm"
+ action={this.props.content.donation_form_url}
+ method={this.props.form_method}
+ onSubmit={this.handleSubmit}
+ data-metric="EOYSnippetForm"
+ ref="form"
+ >
+ {donationURLParams.map(([key, value], idx) => (
+ <input type="hidden" name={key} value={value} key={idx} />
+ ))}
+ {fieldNames.map((field, idx) => {
+ const button_name = `donation_amount_${field}`;
+ const amount = this.props.content[button_name];
+ return (
+ <React.Fragment key={idx}>
+ <input
+ type="radio"
+ name="amount"
+ value={amount}
+ id={field}
+ defaultChecked={button_name === selected_button}
+ />
+ <label htmlFor={field} className="donation-amount">
+ {numberFormat.format(amount)}
+ </label>
+ </React.Fragment>
+ );
+ })}
+
+ <div className="monthly-checkbox-container">
+ <input id="monthly-checkbox" type="checkbox" />
+ <label htmlFor="monthly-checkbox">
+ {this.props.content.monthly_checkbox_label_text}
+ </label>
+ </div>
+
+ <input type="hidden" name="frequency" value="single" />
+ <input
+ type="hidden"
+ name="currency"
+ value={this.props.content.currency_code}
+ />
+ <input
+ type="hidden"
+ name="presets"
+ value={fieldNames.map(
+ field => this.props.content[`donation_amount_${field}`]
+ )}
+ />
+ <button
+ style={btnStyle}
+ type="submit"
+ className="ASRouterButton primary donation-form-url"
+ >
+ {this.props.content.button_label}
+ </button>
+ </form>
+ );
+ }
+
+ render() {
+ const textStyle = {
+ color: this.props.content.text_color,
+ backgroundColor: this.props.content.background_color,
+ };
+ const customElement = (
+ <em style={{ backgroundColor: this.props.content.highlight_color }} />
+ );
+ return (
+ <SimpleSnippet
+ {...this.props}
+ className={this.props.content.test}
+ customElements={{ em: customElement }}
+ textStyle={textStyle}
+ extraContent={this.renderDonations()}
+ />
+ );
+ }
+}
+
+export const EOYSnippet = props => {
+ const extendedContent = {
+ monthly_checkbox_label_text: "Make my donation monthly",
+ locale: "en-US",
+ currency_code: "usd",
+ selected_button: "donation_amount_second",
+ ...props.content,
+ };
+
+ return (
+ <EOYSnippetBase {...props} content={extendedContent} form_method="GET" />
+ );
+};
diff --git a/browser/components/newtab/content-src/asrouter/templates/EOYSnippet/EOYSnippet.schema.json b/browser/components/newtab/content-src/asrouter/templates/EOYSnippet/EOYSnippet.schema.json
new file mode 100644
index 0000000000..a82de98e09
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/EOYSnippet/EOYSnippet.schema.json
@@ -0,0 +1,159 @@
+{
+ "title": "EOYSnippet",
+ "description": "Fundraising Snippet",
+ "version": "1.1.0",
+ "type": "object",
+ "definitions": {
+ "plainText": {
+ "description": "Plain text (no HTML allowed)",
+ "type": "string"
+ },
+ "richText": {
+ "description": "Text with HTML subset allowed: i, b, u, strong, em, br",
+ "type": "string"
+ },
+ "link_url": {
+ "description": "Target for links or buttons",
+ "type": "string",
+ "format": "uri"
+ }
+ },
+ "properties": {
+ "donation_form_url": {
+ "type": "string",
+ "description": "Url to the donation form."
+ },
+ "currency_code": {
+ "type": "string",
+ "description": "The code for the currency. Examle gbp, cad, usd.",
+ "default": "usd"
+ },
+ "locale": {
+ "type": "string",
+ "description": "String for the locale code.",
+ "default": "en-US"
+ },
+ "text": {
+ "allOf": [
+ {"$ref": "#/definitions/richText"},
+ {"description": "Main body text of snippet. HTML subset allowed: i, b, u, strong, em, br"}
+ ]
+ },
+ "text_color": {
+ "type": "string",
+ "description": "Modify the text message color"
+ },
+ "background_color": {
+ "type": "string",
+ "description": "Snippet background color."
+ },
+ "highlight_color": {
+ "type": "string",
+ "description": "Paragraph em highlight color."
+ },
+ "donation_amount_first": {
+ "type": "number",
+ "description": "First button amount."
+ },
+ "donation_amount_second": {
+ "type": "number",
+ "description": "Second button amount."
+ },
+ "donation_amount_third": {
+ "type": "number",
+ "description": "Third button amount."
+ },
+ "donation_amount_fourth": {
+ "type": "number",
+ "description": "Fourth button amount."
+ },
+ "selected_button": {
+ "type": "string",
+ "description": "Default donation_amount_second. Donation amount button that's selected by default.",
+ "default": "donation_amount_second"
+ },
+ "icon": {
+ "type": "string",
+ "description": "Snippet icon. 64x64px. SVG or PNG preferred."
+ },
+ "icon_dark_theme": {
+ "type": "string",
+ "description": "Snippet icon. Dark theme variant. 64x64px. SVG or PNG preferred."
+ },
+ "icon_alt_text": {
+ "type": "string",
+ "description": "Alt text for accessibility",
+ "default": ""
+ },
+ "title": {
+ "allOf": [
+ {"$ref": "#/definitions/plainText"},
+ {"description": "Snippet title displayed before snippet text"}
+ ]
+ },
+ "title_icon": {
+ "type": "string",
+ "description": "Small icon that shows up before the title / text. 16x16px. SVG or PNG preferred. Grayscale."
+ },
+ "title_icon_dark_theme": {
+ "type": "string",
+ "description": "Small icon that shows up before the title / text. Dark theme variant. 16x16px. SVG or PNG preferred. Grayscale."
+ },
+ "button_label": {
+ "allOf": [
+ {"$ref": "#/definitions/plainText"},
+ {"description": "Text for a button next to main snippet text that links to button_url. Requires button_url."}
+ ]
+ },
+ "button_color": {
+ "type": "string",
+ "description": "The text color of the button. Valid CSS color."
+ },
+ "button_background_color": {
+ "type": "string",
+ "description": "The background color of the button. Valid CSS color."
+ },
+ "block_button_text": {
+ "type": "string",
+ "description": "Tooltip text used for dismiss button."
+ },
+ "monthly_checkbox_label_text": {
+ "type": "string",
+ "description": "Label text for monthly checkbox.",
+ "default": "Make my donation monthly"
+ },
+ "test": {
+ "type": "string",
+ "description": "Different styles for the snippet. Options are bold and takeover."
+ },
+ "do_not_autoblock": {
+ "type": "boolean",
+ "description": "Used to prevent blocking the snippet after the CTA (link or button) has been clicked"
+ },
+ "links": {
+ "additionalProperties": {
+ "url": {
+ "allOf": [
+ {"$ref": "#/definitions/link_url"},
+ {"description": "The url where the link points to."}
+ ]
+ },
+ "metric": {
+ "type": "string",
+ "description": "Custom event name sent with telemetry event."
+ },
+ "args": {
+ "type": "string",
+ "description": "Additional parameters for link action, example which specific menu the button should open"
+ }
+ }
+ }
+ },
+ "additionalProperties": false,
+ "required": ["text", "donation_form_url", "donation_amount_first", "donation_amount_second", "donation_amount_third", "donation_amount_fourth", "button_label", "currency_code"],
+ "dependencies": {
+ "button_color": ["button_label"],
+ "button_background_color": ["button_label"]
+ }
+}
+
diff --git a/browser/components/newtab/content-src/asrouter/templates/EOYSnippet/_EOYSnippet.scss b/browser/components/newtab/content-src/asrouter/templates/EOYSnippet/_EOYSnippet.scss
new file mode 100644
index 0000000000..ef17606e80
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/EOYSnippet/_EOYSnippet.scss
@@ -0,0 +1,54 @@
+.EOYSnippetForm {
+ margin: 10px 0 8px;
+ align-self: start;
+ font-size: 14px;
+ display: flex;
+ align-items: center;
+
+ .donation-amount,
+ .donation-form-url {
+ white-space: nowrap;
+ font-size: 14px;
+ padding: 8px 20px;
+ border-radius: 2px;
+ }
+
+ .donation-amount {
+ color: $grey-90;
+ margin-inline-end: 18px;
+ border: 1px solid $grey-40;
+ padding: 5px 14px;
+ background: $grey-10;
+ cursor: pointer;
+ }
+
+ input {
+ &[type='radio'] {
+ opacity: 0;
+ margin-inline-end: -18px;
+
+ &:checked + .donation-amount {
+ background: $grey-50;
+ color: $white;
+ border: 1px solid $grey-60;
+ }
+
+ // accessibility
+ &:checked:focus + .donation-amount,
+ &:not(:checked):focus + .donation-amount {
+ border: 1px dotted var(--newtab-link-primary-color);
+ }
+ }
+ }
+
+ .monthly-checkbox-container {
+ display: flex;
+ width: 100%;
+ }
+
+ .donation-form-url {
+ margin-inline-start: 18px;
+ align-self: flex-end;
+ display: flex;
+ }
+}
diff --git a/browser/components/newtab/content-src/asrouter/templates/FXASignupSnippet/FXASignupSnippet.jsx b/browser/components/newtab/content-src/asrouter/templates/FXASignupSnippet/FXASignupSnippet.jsx
new file mode 100644
index 0000000000..1d8197d675
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/FXASignupSnippet/FXASignupSnippet.jsx
@@ -0,0 +1,38 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import React from "react";
+import { SubmitFormSnippet } from "../SubmitFormSnippet/SubmitFormSnippet.jsx";
+
+export const FXASignupSnippet = props => {
+ const userAgent = window.navigator.userAgent.match(/Firefox\/([0-9]+)\./);
+ const firefox_version = userAgent ? parseInt(userAgent[1], 10) : 0;
+ const extendedContent = {
+ scene1_button_label: "Learn more",
+ retry_button_label: "Try again",
+ scene2_email_placeholder_text: "Your email here",
+ scene2_button_label: "Sign me up",
+ scene2_dismiss_button_text: "Dismiss",
+ ...props.content,
+ hidden_inputs: {
+ action: "email",
+ context: "fx_desktop_v3",
+ entrypoint: "snippets",
+ utm_source: "snippet",
+ utm_content: firefox_version,
+ utm_campaign: props.content.utm_campaign,
+ utm_term: props.content.utm_term,
+ ...props.content.hidden_inputs,
+ },
+ };
+
+ return (
+ <SubmitFormSnippet
+ {...props}
+ content={extendedContent}
+ form_action={"https://accounts.firefox.com/"}
+ form_method="GET"
+ />
+ );
+};
diff --git a/browser/components/newtab/content-src/asrouter/templates/FXASignupSnippet/FXASignupSnippet.schema.json b/browser/components/newtab/content-src/asrouter/templates/FXASignupSnippet/FXASignupSnippet.schema.json
new file mode 100644
index 0000000000..d7d3e37bbc
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/FXASignupSnippet/FXASignupSnippet.schema.json
@@ -0,0 +1,187 @@
+{
+ "title": "FXASignupSnippet",
+ "description": "A snippet template for FxA sign up/sign in",
+ "version": "1.2.0",
+ "type": "object",
+ "definitions": {
+ "plainText": {
+ "description": "Plain text (no HTML allowed)",
+ "type": "string"
+ },
+ "richText": {
+ "description": "Text with HTML subset allowed: i, b, u, strong, em, br",
+ "type": "string"
+ },
+ "link_url": {
+ "description": "Target for links or buttons",
+ "type": "string",
+ "format": "uri"
+ }
+ },
+ "properties": {
+ "scene1_title": {
+ "allof": [
+ {"$ref": "#/definitions/plainText"},
+ {"description": "snippet title displayed before snippet text"}
+ ]
+ },
+ "scene1_text": {
+ "allOf": [
+ {"$ref": "#/definitions/richText"},
+ {"description": "Main body text of snippet. HTML subset allowed: i, b, u, strong, em, br"}
+ ]
+ },
+ "scene1_section_title_icon": {
+ "type": "string",
+ "description": "Section title icon for scene 1. 16x16px. SVG or PNG preferred. scene1_section_title_text must also be specified to display."
+ },
+ "scene1_section_title_icon_dark_theme": {
+ "type": "string",
+ "description": "Section title icon for scene 1, dark theme variant. 16x16px. SVG or PNG preferred. scene1_section_title_text must also be specified to display."
+ },
+ "scene1_section_title_text": {
+ "type": "string",
+ "description": "Section title text for scene 1. scene1_section_title_icon must also be specified to display."
+ },
+ "scene1_section_title_url": {
+ "allOf": [
+ {"$ref": "#/definitions/link_url"},
+ {"description": "A url, scene1_section_title_text links to this"}
+ ]
+ },
+ "scene2_title": {
+ "allOf": [
+ {"$ref": "#/definitions/plainText"},
+ {"description": "Title displayed before text in scene 2. Should be plain text."}
+ ]
+ },
+ "scene2_text": {
+ "allOf": [
+ {"$ref": "#/definitions/richText"},
+ {"description": "Main body text of snippet. HTML subset allowed: i, b, u, strong, em, br"}
+ ]
+ },
+ "scene1_icon": {
+ "type": "string",
+ "description": "Snippet icon. 64x64px. SVG or PNG preferred."
+ },
+ "scene1_icon_dark_theme": {
+ "type": "string",
+ "description": "Snippet icon. Dark theme variant. 64x64px. SVG or PNG preferred."
+ },
+ "scene1_title_icon": {
+ "type": "string",
+ "description": "Small icon that shows up before the title / text. 16x16px. SVG or PNG preferred. Grayscale."
+ },
+ "scene1_title_icon_dark_theme": {
+ "type": "string",
+ "description": "Small icon that shows up before the title / text. Dark theme variant. 16x16px. SVG or PNG preferred. Grayscale."
+ },
+ "scene2_email_placeholder_text": {
+ "type": "string",
+ "description": "Value to show while input is empty.",
+ "default": "Your email here"
+ },
+ "scene2_button_label": {
+ "type": "string",
+ "description": "Label for form submit button",
+ "default": "Sign me up"
+ },
+ "scene2_dismiss_button_text": {
+ "type": "string",
+ "description": "Label for the dismiss button when the sign-up form is expanded.",
+ "default": "Dismiss"
+ },
+ "hidden_inputs": {
+ "type": "object",
+ "description": "Each entry represents a hidden input, key is used as value for the name property.",
+ "properties": {
+ "action": {
+ "type": "string",
+ "enum": ["email"]
+ },
+ "context": {
+ "type": "string",
+ "enum": ["fx_desktop_v3"]
+ },
+ "entrypoint": {
+ "type": "string",
+ "enum": ["snippets"]
+ },
+ "utm_content": {
+ "type": "number",
+ "description": "Firefox version number"
+ },
+ "utm_source": {
+ "type": "string",
+ "enum": ["snippet"]
+ },
+ "utm_campaign": {
+ "type": "string",
+ "description": "(fxa) Value to pass through to GA as utm_campaign."
+ },
+ "utm_term": {
+ "type": "string",
+ "description": "(fxa) Value to pass through to GA as utm_term."
+ },
+ "additionalProperties": false
+ }
+ },
+ "scene1_button_label": {
+ "allOf": [
+ {"$ref": "#/definitions/plainText"},
+ {"description": "Text for a button next to main snippet text that links to button_url. Requires button_url."}
+ ],
+ "default": "Learn more"
+ },
+ "scene1_button_color": {
+ "type": "string",
+ "description": "The text color of the button. Valid CSS color."
+ },
+ "scene1_button_background_color": {
+ "type": "string",
+ "description": "The background color of the button. Valid CSS color."
+ },
+ "retry_button_label": {
+ "allOf": [
+ {"$ref": "#/definitions/plainText"},
+ {"description": "Text for the button in the event of a submission error/failure."}
+ ],
+ "default": "Try again"
+ },
+ "do_not_autoblock": {
+ "type": "boolean",
+ "description": "Used to prevent blocking the snippet after the CTA (link or button) has been clicked",
+ "default": false
+ },
+ "utm_campaign": {
+ "type": "string",
+ "description": "(fxa) Value to pass through to GA as utm_campaign."
+ },
+ "utm_term": {
+ "type": "string",
+ "description": "(fxa) Value to pass through to GA as utm_term."
+ },
+ "links": {
+ "additionalProperties": {
+ "url": {
+ "allOf": [
+ {"$ref": "#/definitions/link_url"},
+ {"description": "The url where the link points to."}
+ ]
+ },
+ "metric": {
+ "type": "string",
+ "description": "Custom event name sent with telemetry event."
+ }
+ }
+ }
+ },
+ "additionalProperties": false,
+ "required": ["scene1_text", "scene2_text", "scene1_button_label"],
+ "dependencies": {
+ "scene1_button_color": ["scene1_button_label"],
+ "scene1_button_background_color": ["scene1_button_label"]
+ }
+}
+
diff --git a/browser/components/newtab/content-src/asrouter/templates/FirstRun/addUtmParams.js b/browser/components/newtab/content-src/asrouter/templates/FirstRun/addUtmParams.js
new file mode 100644
index 0000000000..cb29f66d6e
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/FirstRun/addUtmParams.js
@@ -0,0 +1,30 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/**
+ * BASE_PARAMS keys/values can be modified from outside this file
+ */
+export const BASE_PARAMS = {
+ utm_source: "activity-stream",
+ utm_campaign: "firstrun",
+ utm_medium: "referral",
+};
+
+/**
+ * Takes in a url as a string or URL object and returns a URL object with the
+ * utm_* parameters added to it. If a URL object is passed in, the paraemeters
+ * are added to it (the return value can be ignored in that case as it's the
+ * same object).
+ */
+export function addUtmParams(url, utmTerm) {
+ let returnUrl = url;
+ if (typeof returnUrl === "string") {
+ returnUrl = new URL(url);
+ }
+ Object.keys(BASE_PARAMS).forEach(key => {
+ returnUrl.searchParams.append(key, BASE_PARAMS[key]);
+ });
+ returnUrl.searchParams.append("utm_term", utmTerm);
+ return returnUrl;
+}
diff --git a/browser/components/newtab/content-src/asrouter/templates/NewsletterSnippet/NewsletterSnippet.jsx b/browser/components/newtab/content-src/asrouter/templates/NewsletterSnippet/NewsletterSnippet.jsx
new file mode 100644
index 0000000000..27c1684762
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/NewsletterSnippet/NewsletterSnippet.jsx
@@ -0,0 +1,34 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import React from "react";
+import { SubmitFormSnippet } from "../SubmitFormSnippet/SubmitFormSnippet.jsx";
+
+export const NewsletterSnippet = props => {
+ const extendedContent = {
+ scene1_button_label: "Learn more",
+ retry_button_label: "Try again",
+ scene2_email_placeholder_text: "Your email here",
+ scene2_button_label: "Sign me up",
+ scene2_dismiss_button_text: "Dismiss",
+ scene2_newsletter: "mozilla-foundation",
+ ...props.content,
+ hidden_inputs: {
+ newsletters: props.content.scene2_newsletter || "mozilla-foundation",
+ fmt: "H",
+ lang: props.content.locale || "en-US",
+ source_url: `https://snippets.mozilla.com/show/${props.id}`,
+ ...props.content.hidden_inputs,
+ },
+ };
+
+ return (
+ <SubmitFormSnippet
+ {...props}
+ content={extendedContent}
+ form_action={"https://basket.mozilla.org/subscribe.json"}
+ form_method="POST"
+ />
+ );
+};
diff --git a/browser/components/newtab/content-src/asrouter/templates/NewsletterSnippet/NewsletterSnippet.schema.json b/browser/components/newtab/content-src/asrouter/templates/NewsletterSnippet/NewsletterSnippet.schema.json
new file mode 100644
index 0000000000..eeb63554ed
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/NewsletterSnippet/NewsletterSnippet.schema.json
@@ -0,0 +1,177 @@
+{
+ "title": "NewsletterSnippet",
+ "description": "A snippet template for send to device mobile download",
+ "version": "1.2.0",
+ "type": "object",
+ "definitions": {
+ "plainText": {
+ "description": "Plain text (no HTML allowed)",
+ "type": "string"
+ },
+ "richText": {
+ "description": "Text with HTML subset allowed: i, b, u, strong, em, br",
+ "type": "string"
+ },
+ "link_url": {
+ "description": "Target for links or buttons",
+ "type": "string",
+ "format": "uri"
+ }
+ },
+ "properties": {
+ "locale": {
+ "type": "string",
+ "description": "Two to five character string for the locale code",
+ "default": "en-US"
+ },
+ "scene1_title": {
+ "allof": [
+ {"$ref": "#/definitions/plainText"},
+ {"description": "snippet title displayed before snippet text"}
+ ]
+ },
+ "scene1_text": {
+ "allOf": [
+ {"$ref": "#/definitions/richText"},
+ {"description": "Main body text of snippet. HTML subset allowed: i, b, u, strong, em, br"}
+ ]
+ },
+ "scene1_section_title_icon": {
+ "type": "string",
+ "description": "Section title icon for scene 1. 16x16px. SVG or PNG preferred. scene1_section_title_text must also be specified to display."
+ },
+ "scene1_section_title_icon_dark_theme": {
+ "type": "string",
+ "description": "Section title icon for scene 1, dark theme variant. 16x16px. SVG or PNG preferred. scene1_section_title_text must also be specified to display."
+ },
+ "scene1_section_title_text": {
+ "type": "string",
+ "description": "Section title text for scene 1. scene1_section_title_icon must also be specified to display."
+ },
+ "scene1_section_title_url": {
+ "allOf": [
+ {"$ref": "#/definitions/link_url"},
+ {"description": "A url, scene1_section_title_text links to this"}
+ ]
+ },
+ "scene2_title": {
+ "allOf": [
+ {"$ref": "#/definitions/plainText"},
+ {"description": "Title displayed before text in scene 2. Should be plain text."}
+ ]
+ },
+ "scene2_text": {
+ "allOf": [
+ {"$ref": "#/definitions/richText"},
+ {"description": "Main body text of snippet. HTML subset allowed: i, b, u, strong, em, br"}
+ ]
+ },
+ "scene1_icon": {
+ "type": "string",
+ "description": "Snippet icon. 64x64px. SVG or PNG preferred."
+ },
+ "scene1_icon_dark_theme": {
+ "type": "string",
+ "description": "Snippet icon. Dark theme variant. 64x64px. SVG or PNG preferred."
+ },
+ "scene1_title_icon": {
+ "type": "string",
+ "description": "Small icon that shows up before the title / text. 16x16px. SVG or PNG preferred. Grayscale."
+ },
+ "scene1_title_icon_dark_theme": {
+ "type": "string",
+ "description": "Small icon that shows up before the title / text. Dark theme variant. 16x16px. SVG or PNG preferred. Grayscale."
+ },
+ "scene2_email_placeholder_text": {
+ "type": "string",
+ "description": "Value to show while input is empty.",
+ "default": "Your email here"
+ },
+ "scene2_button_label": {
+ "type": "string",
+ "description": "Label for form submit button",
+ "default": "Sign me up"
+ },
+ "scene2_privacy_html": {
+ "type": "string",
+ "description": "(send to device) Html for disclaimer and link underneath input box."
+ },
+ "scene2_dismiss_button_text": {
+ "type": "string",
+ "description": "Label for the dismiss button when the sign-up form is expanded.",
+ "default": "Dismiss"
+ },
+ "hidden_inputs": {
+ "type": "object",
+ "description": "Each entry represents a hidden input, key is used as value for the name property.",
+ "properties": {
+ "fmt": {
+ "type": "string",
+ "description": "",
+ "default": "H"
+ }
+ }
+ },
+ "scene1_button_label": {
+ "allOf": [
+ {"$ref": "#/definitions/plainText"},
+ {"description": "Text for a button next to main snippet text that links to button_url. Requires button_url."}
+ ],
+ "default": "Learn more"
+ },
+ "scene1_button_color": {
+ "type": "string",
+ "description": "The text color of the button. Valid CSS color."
+ },
+ "scene1_button_background_color": {
+ "type": "string",
+ "description": "The background color of the button. Valid CSS color."
+ },
+ "retry_button_label": {
+ "allOf": [
+ {"$ref": "#/definitions/plainText"},
+ {"description": "Text for the button in the event of a submission error/failure."}
+ ],
+ "default": "Try again"
+ },
+ "do_not_autoblock": {
+ "type": "boolean",
+ "description": "Used to prevent blocking the snippet after the CTA (link or button) has been clicked",
+ "default": false
+ },
+ "success_text": {
+ "type": "string",
+ "description": "Message shown on successful registration."
+ },
+ "error_text": {
+ "type": "string",
+ "description": "Message shown if registration failed."
+ },
+ "scene2_newsletter": {
+ "type": "string",
+ "description": "Newsletter/basket id user is subscribing to.",
+ "default": "mozilla-foundation"
+ },
+ "links": {
+ "additionalProperties": {
+ "url": {
+ "allOf": [
+ {"$ref": "#/definitions/link_url"},
+ {"description": "The url where the link points to."}
+ ]
+ },
+ "metric": {
+ "type": "string",
+ "description": "Custom event name sent with telemetry event."
+ }
+ }
+ }
+ },
+ "additionalProperties": false,
+ "required": ["scene1_text", "scene2_text", "scene1_button_label"],
+ "dependencies": {
+ "scene1_button_color": ["scene1_button_label"],
+ "scene1_button_background_color": ["scene1_button_label"]
+ }
+}
+
diff --git a/browser/components/newtab/content-src/asrouter/templates/OnboardingMessage/OnboardingMessage.jsx b/browser/components/newtab/content-src/asrouter/templates/OnboardingMessage/OnboardingMessage.jsx
new file mode 100644
index 0000000000..ce1a840247
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/OnboardingMessage/OnboardingMessage.jsx
@@ -0,0 +1,52 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import React from "react";
+import { Localized } from "../../../aboutwelcome/components/MSLocalized";
+
+export class OnboardingCard extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onClick = this.onClick.bind(this);
+ }
+
+ onClick() {
+ const { props } = this;
+ const ping = {
+ event: "CLICK_BUTTON",
+ message_id: props.id,
+ id: props.UISurface,
+ };
+ props.sendUserActionTelemetry(ping);
+ props.onAction(props.content.primary_button.action, props.message);
+ }
+
+ render() {
+ const { content } = this.props;
+ const className = this.props.className || "onboardingMessage";
+ return (
+ <div className={className}>
+ <div className={`onboardingMessageImage ${content.icon}`} />
+ <div className="onboardingContent">
+ <span>
+ <Localized text={content.title}>
+ <h2 className="onboardingTitle" />
+ </Localized>
+ <Localized text={content.text}>
+ <p className="onboardingText" />
+ </Localized>
+ </span>
+ <span className="onboardingButtonContainer">
+ <Localized text={content.primary_button.label}>
+ <button
+ className="button onboardingButton"
+ onClick={this.onClick}
+ />
+ </Localized>
+ </span>
+ </div>
+ </div>
+ );
+ }
+}
diff --git a/browser/components/newtab/content-src/asrouter/templates/OnboardingMessage/OnboardingMessage.schema.json b/browser/components/newtab/content-src/asrouter/templates/OnboardingMessage/OnboardingMessage.schema.json
new file mode 100644
index 0000000000..f355d89da7
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/OnboardingMessage/OnboardingMessage.schema.json
@@ -0,0 +1,142 @@
+{
+ "title": "OnboardingMessage",
+ "description": "A template with a title, icon, button and description. No markup allowed.",
+ "version": "1.0.0",
+ "type": "object",
+ "properties": {
+ "title": {
+ "oneOf": [
+ {
+ "type": "string",
+ "description": "The message displayed in the title of the onboarding card"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "string_id": {
+ "type": "string"
+ }
+ },
+ "required": ["string_id"],
+ "description": "Id of localized string for onboarding card title"
+ }
+ ],
+ "description": "Id of localized string or message override."
+ },
+ "text": {
+ "oneOf": [
+ {
+ "type": "string",
+ "description": "The message displayed in the description of the onboarding card"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "string_id": {
+ "type": "string"
+ },
+ "args": {
+ "type": "object",
+ "description": "An optional argument to pass to the localization module"
+ }
+ },
+ "required": ["string_id"],
+ "description": "Id of localized string for onboarding card description"
+ }
+ ],
+ "description": "Id of localized string or message override."
+ },
+ "icon": {
+ "allOf": [
+ {
+ "type": "string",
+ "description": "Image associated with the onboarding card"
+ }
+ ]
+ },
+ "primary_button": {
+ "type": "object",
+ "properties": {
+ "label": {
+ "oneOf": [
+ {
+ "type": "string",
+ "description": "The label of the onboarding messages' action button"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "string_id": {
+ "type": "string"
+ }
+ },
+ "required": ["string_id"],
+ "description": "Id of localized string for onboarding messages' button"
+ }
+ ],
+ "description": "Id of localized string or message override."
+ },
+ "action": {
+ "type": "object",
+ "properties": {
+ "type": {
+ "type": "string",
+ "description": "Action dispatched by the button."
+ },
+ "data": {
+ "properties": {
+ "args": {
+ "type": "string",
+ "description": "Additional parameters for button action, for example which link the button should open."
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "secondary_buttons": {
+ "type": "object",
+ "properties": {
+ "label": {
+ "oneOf": [
+ {
+ "type": "string",
+ "description": "The label of the onboarding messages' (optional) secondary action button"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "string_id": {
+ "type": "string"
+ }
+ },
+ "required": ["string_id"],
+ "description": "Id of localized string for onboarding messages' button"
+ }
+ ],
+ "description": "Id of localized string or message override."
+ },
+ "action": {
+ "type": "object",
+ "properties": {
+ "type": {
+ "type": "string",
+ "description": "Action dispatched by the button."
+ },
+ "data": {
+ "properties": {
+ "args": {
+ "type": "string",
+ "description": "Additional parameters for button action, for example which link the button should open."
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "additionalProperties": true,
+ "required": ["title", "text", "icon", "primary_button"]
+}
diff --git a/browser/components/newtab/content-src/asrouter/templates/OnboardingMessage/ToolbarBadgeMessage.schema.json b/browser/components/newtab/content-src/asrouter/templates/OnboardingMessage/ToolbarBadgeMessage.schema.json
new file mode 100644
index 0000000000..b873e62b83
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/OnboardingMessage/ToolbarBadgeMessage.schema.json
@@ -0,0 +1,39 @@
+{
+ "title": "ToolbarBadgeMessage",
+ "description": "A template that specifies to which element in the browser toolbar to add a notification.",
+ "version": "1.1.0",
+ "type": "object",
+ "properties": {
+ "target": {
+ "type": "string"
+ },
+ "action": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ }
+ },
+ "additionalProperties": false,
+ "required": ["id"],
+ "description": "Optional action to take in addition to showing the notification"
+ },
+ "delay": {
+ "type": "number",
+ "description": "Optional delay in ms after which to show the notification"
+ },
+ "badgeDescription": {
+ "type": "object",
+ "description": "This is used in combination with the badged button to offer a text based alternative to the visual badging. Example 'New Feature: What's New'",
+ "properties": {
+ "string_id": {
+ "type": "string",
+ "description": "Fluent string id"
+ }
+ },
+ "required": ["string_id"]
+ }
+ },
+ "additionalProperties": false,
+ "required": ["target"]
+}
diff --git a/browser/components/newtab/content-src/asrouter/templates/OnboardingMessage/UpdateAction.schema.json b/browser/components/newtab/content-src/asrouter/templates/OnboardingMessage/UpdateAction.schema.json
new file mode 100644
index 0000000000..7624c67d4c
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/OnboardingMessage/UpdateAction.schema.json
@@ -0,0 +1,36 @@
+{
+ "title": "UpdateActionMessage",
+ "description": "A template for messages that execute predetermined actions.",
+ "version": "1.0.0",
+ "type": "object",
+ "properties": {
+ "action": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "data": {
+ "type": "object",
+ "properties": {
+ "url": {
+ "type": "string",
+ "description": "URL data to be used as argument to the action"
+ },
+ "expireDelta": {
+ "type": "number",
+ "description": "Expiration timestamp to be used as argument to the action"
+ }
+ }
+ },
+ "description": "Additional data provided as argument when executing the action"
+ },
+ "additionalProperties": false,
+ "description": "Optional action to take in addition to showing the notification"
+ },
+ "additionalProperties": false,
+ "required": ["id", "action"]
+ },
+ "additionalProperties": false,
+ "required": ["action"]
+}
diff --git a/browser/components/newtab/content-src/asrouter/templates/OnboardingMessage/WhatsNewMessage.schema.json b/browser/components/newtab/content-src/asrouter/templates/OnboardingMessage/WhatsNewMessage.schema.json
new file mode 100644
index 0000000000..998f2cfc8d
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/OnboardingMessage/WhatsNewMessage.schema.json
@@ -0,0 +1,97 @@
+{
+ "title": "WhatsNewMessage",
+ "description": "A template for the messages that appear in the What's New panel.",
+ "version": "1.2.0",
+ "type": "object",
+ "definitions": {
+ "localizableText": {
+ "oneOf": [
+ {
+ "type": "string",
+ "description": "The string to be rendered."
+ },
+ {
+ "type": "object",
+ "properties": {
+ "string_id": {
+ "type": "string"
+ }
+ },
+ "required": ["string_id"],
+ "description": "Id of localized string to be rendered."
+ }
+ ]
+ }
+ },
+ "properties": {
+ "layout": {
+ "description": "Different message layouts",
+ "enum": ["tracking-protections"]
+ },
+ "layout_title_content_variable": {
+ "description": "Select what profile specific value to show for the current layout.",
+ "type": "string"
+ },
+ "bucket_id": {
+ "type": "string",
+ "description": "A bucket identifier for the addon. This is used in order to anonymize telemetry for history-sensitive targeting."
+ },
+ "published_date": {
+ "type": "integer",
+ "description": "The date/time (number of milliseconds elapsed since January 1, 1970 00:00:00 UTC) the message was published."
+ },
+ "title": {
+ "allOf": [
+ {"$ref": "#/definitions/localizableText"},
+ {"description": "Id of localized string or message override of What's New message title"}
+ ]
+ },
+ "subtitle": {
+ "allOf": [
+ {"$ref": "#/definitions/localizableText"},
+ {"description": "Id of localized string or message override of What's New message subtitle"}
+ ]
+ },
+ "body": {
+ "allOf": [
+ {"$ref": "#/definitions/localizableText"},
+ {"description": "Id of localized string or message override of What's New message body"}
+ ]
+ },
+ "link_text": {
+ "allOf": [
+ {"$ref": "#/definitions/localizableText"},
+ {"description": "(optional) Id of localized string or message override of What's New message link text"}
+ ]
+ },
+ "cta_url": {
+ "description": "Target URL for the What's New message.",
+ "type": "string",
+ "format": "uri"
+ },
+ "cta_type": {
+ "description": "Type of url open action",
+ "enum": ["OPEN_URL", "OPEN_ABOUT_PAGE", "OPEN_PROTECTION_REPORT"]
+ },
+ "cta_where": {
+ "description": "How to open the cta: new window, tab, focused, unfocused.",
+ "enum": ["current", "tabshifted", "tab", "save", "window"]
+ },
+ "icon_url": {
+ "description": "(optional) URL for the What's New message icon.",
+ "type": "string",
+ "format": "uri"
+ },
+ "icon_alt": {
+ "allOf": [
+ {"$ref": "#/definitions/localizableText"},
+ {"description": "Alt text for image."}
+ ]
+ }
+ },
+ "additionalProperties": false,
+ "required": ["published_date", "title", "body", "cta_url", "bucket_id"],
+ "dependencies": {
+ "layout": ["layout_title_content_variable"]
+ }
+}
diff --git a/browser/components/newtab/content-src/asrouter/templates/OnboardingMessage/_OnboardingMessage.scss b/browser/components/newtab/content-src/asrouter/templates/OnboardingMessage/_OnboardingMessage.scss
new file mode 100644
index 0000000000..d4109317a1
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/OnboardingMessage/_OnboardingMessage.scss
@@ -0,0 +1,131 @@
+@import '../../../styles/OnboardingImages';
+
+.onboardingMessage {
+ height: 340px;
+ text-align: center;
+ padding: 13px;
+ font-weight: 200;
+
+ // at 850px, img floats left, content floats right next to it
+ @media(max-width: 850px) {
+ height: 170px;
+ text-align: left;
+ padding: 10px;
+ border-bottom: 1px solid $grey-30;
+ display: flex;
+ margin-bottom: 11px;
+
+ &:last-child {
+ border: 0;
+ }
+
+ .onboardingContent {
+ padding-left: 10px;
+ height: 100%;
+
+ > span > h3 {
+ margin-top: 0;
+ margin-bottom: 4px;
+ font-weight: 400;
+ }
+
+ > span > p {
+ margin-top: 0;
+ line-height: 22px;
+ font-size: 15px;
+ }
+ }
+ }
+
+ @media(max-width: 650px) {
+ height: 250px;
+ }
+
+ .onboardingContent {
+ height: 175px;
+
+ > span > h3 {
+ color: $grey-90;
+ margin-bottom: 8px;
+ font-weight: 400;
+ }
+
+ > span > p {
+ color: $grey-60;
+ margin-top: 0;
+ height: 180px;
+ margin-bottom: 12px;
+ font-size: 15px;
+ line-height: 22px;
+
+ @media(max-width: 650px) {
+ margin-bottom: 0;
+ height: 160px;
+ }
+ }
+ }
+
+ .onboardingButton {
+ background-color: $grey-90-10;
+ border: 0;
+ width: 150px;
+ height: 30px;
+ margin-bottom: 23px;
+ padding: 4px 0 6px;
+ font-size: 15px;
+
+ // at 850px, the button shimmies down and to the right
+ @media(max-width: 850px) {
+ float: right;
+ margin-top: -105px;
+ margin-inline-end: -10px;
+ }
+
+ @media(max-width: 650px) {
+ float: none;
+ }
+
+ &:focus,
+ &.active,
+ &:hover {
+ box-shadow: 0 0 0 5px $grey-30;
+ transition: box-shadow 150ms;
+ }
+ }
+
+
+ &::before {
+ content: '';
+ height: 230px;
+ width: 1px;
+ position: absolute;
+ background-color: $grey-30;
+ margin-top: 40px;
+ margin-inline-start: 215px;
+
+ // at 850px, the line goes from vertical to horizontal
+ @media(max-width: 850px) {
+ content: none;
+ }
+ }
+
+ &:last-child::before {
+ content: none;
+ }
+}
+
+.onboardingMessageImage {
+ height: 112px;
+ width: 180px;
+ background-size: auto 140px;
+ background-position: center center;
+ background-repeat: no-repeat;
+ display: inline-block;
+
+ // Cards will wrap into the next line after this breakpoint
+ @media(max-width: 865px) {
+ height: 75px;
+ min-width: 80px;
+ background-size: 140px;
+ }
+}
diff --git a/browser/components/newtab/content-src/asrouter/templates/SendToDeviceSnippet/SendToDeviceSnippet.jsx b/browser/components/newtab/content-src/asrouter/templates/SendToDeviceSnippet/SendToDeviceSnippet.jsx
new file mode 100644
index 0000000000..0929b8f711
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/SendToDeviceSnippet/SendToDeviceSnippet.jsx
@@ -0,0 +1,76 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { isEmailOrPhoneNumber } from "./isEmailOrPhoneNumber";
+import React from "react";
+import { SubmitFormSnippet } from "../SubmitFormSnippet/SubmitFormSnippet.jsx";
+
+function validateInput(value, content) {
+ const type = isEmailOrPhoneNumber(value, content);
+ return type ? "" : "Must be an email or a phone number.";
+}
+
+function processFormData(input, message) {
+ const { content } = message;
+ const type = content.include_sms
+ ? isEmailOrPhoneNumber(input.value, content)
+ : "email";
+ const formData = new FormData();
+ let url;
+ if (type === "phone") {
+ url = "https://basket.mozilla.org/news/subscribe_sms/";
+ formData.append("mobile_number", input.value);
+ formData.append("msg_name", content.message_id_sms);
+ formData.append("country", content.country);
+ } else if (type === "email") {
+ url = "https://basket.mozilla.org/news/subscribe/";
+ formData.append("email", input.value);
+ formData.append("newsletters", content.message_id_email);
+ formData.append(
+ "source_url",
+ encodeURIComponent(`https://snippets.mozilla.com/show/${message.id}`)
+ );
+ }
+ formData.append("lang", content.locale);
+ return { formData, url };
+}
+
+function addDefaultValues(props) {
+ return {
+ ...props,
+ content: {
+ scene1_button_label: "Learn more",
+ retry_button_label: "Try again",
+ scene2_dismiss_button_text: "Dismiss",
+ scene2_button_label: "Send",
+ scene2_input_placeholder: "Your email here",
+ locale: "en-US",
+ country: "us",
+ message_id_email: "",
+ include_sms: false,
+ ...props.content,
+ },
+ };
+}
+
+export const SendToDeviceSnippet = props => {
+ const propsWithDefaults = addDefaultValues(props);
+
+ return (
+ <SubmitFormSnippet
+ {...propsWithDefaults}
+ form_method="POST"
+ className="send_to_device_snippet"
+ inputType={propsWithDefaults.content.include_sms ? "text" : "email"}
+ validateInput={
+ propsWithDefaults.content.include_sms ? validateInput : null
+ }
+ processFormData={processFormData}
+ />
+ );
+};
+
+export const SendToDeviceScene2Snippet = props => {
+ return <SendToDeviceSnippet expandedAlt={true} {...props} />;
+};
diff --git a/browser/components/newtab/content-src/asrouter/templates/SendToDeviceSnippet/SendToDeviceSnippet.schema.json b/browser/components/newtab/content-src/asrouter/templates/SendToDeviceSnippet/SendToDeviceSnippet.schema.json
new file mode 100644
index 0000000000..238840234a
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/SendToDeviceSnippet/SendToDeviceSnippet.schema.json
@@ -0,0 +1,234 @@
+{
+ "title": "SendToDeviceSnippet",
+ "description": "A snippet template for send to device mobile download",
+ "version": "1.2.0",
+ "type": "object",
+ "definitions": {
+ "plainText": {
+ "description": "Plain text (no HTML allowed)",
+ "type": "string"
+ },
+ "richText": {
+ "description": "Text with HTML subset allowed: i, b, u, strong, em, br",
+ "type": "string"
+ },
+ "link_url": {
+ "description": "Target for links or buttons",
+ "type": "string",
+ "format": "uri"
+ }
+ },
+ "properties": {
+ "locale": {
+ "type": "string",
+ "description": "Two to five character string for the locale code",
+ "default": "en-US"
+ },
+ "country": {
+ "type": "string",
+ "description": "Two character string for the country code (used for SMS)",
+ "default": "us"
+ },
+ "scene1_title": {
+ "allof": [
+ {"$ref": "#/definitions/plainText"},
+ {"description": "snippet title displayed before snippet text"}
+ ]
+ },
+ "scene1_text": {
+ "allOf": [
+ {"$ref": "#/definitions/richText"},
+ {"description": "Main body text of snippet. HTML subset allowed: i, b, u, strong, em, br"}
+ ]
+ },
+ "scene1_section_title_icon": {
+ "type": "string",
+ "description": "Section title icon for scene 1. 16x16px. SVG or PNG preferred. scene1_section_title_text must also be specified to display."
+ },
+ "scene1_section_title_icon_dark_theme": {
+ "type": "string",
+ "description": "Section title icon for scene 1, dark theme variant. 16x16px. SVG or PNG preferred. scene1_section_title_text must also be specified to display."
+ },
+ "scene1_section_title_text": {
+ "type": "string",
+ "description": "Section title text for scene 1. scene1_section_title_icon must also be specified to display."
+ },
+ "scene1_section_title_url": {
+ "allOf": [
+ {"$ref": "#/definitions/link_url"},
+ {"description": "A url, scene1_section_title_text links to this"}
+ ]
+ },
+ "scene2_title": {
+ "allOf": [
+ {"$ref": "#/definitions/plainText"},
+ {"description": "Title displayed before text in scene 2. Should be plain text."}
+ ]
+ },
+ "scene2_text": {
+ "allOf": [
+ {"$ref": "#/definitions/richText"},
+ {"description": "Main body text of snippet. HTML subset allowed: i, b, u, strong, em, br"}
+ ]
+ },
+ "scene1_icon": {
+ "type": "string",
+ "description": "Snippet icon. 64x64px. SVG or PNG preferred."
+ },
+ "scene1_icon_dark_theme": {
+ "type": "string",
+ "description": "Snippet icon. Dark theme variant. 64x64px. SVG or PNG preferred."
+ },
+ "scene2_icon": {
+ "type": "string",
+ "description": "(send to device) Image to display above the form. Dark theme variant. 98x98px. SVG or PNG preferred."
+ },
+ "scene2_icon_dark_theme": {
+ "type": "string",
+ "description": "(send to device) Image to display above the form. 98x98px. SVG or PNG preferred."
+ },
+ "scene1_title_icon": {
+ "type": "string",
+ "description": "Small icon that shows up before the title / text. 16x16px. SVG or PNG preferred. Grayscale."
+ },
+ "scene1_title_icon_dark_theme": {
+ "type": "string",
+ "description": "Small icon that shows up before the title / text. Dark theme variant. 16x16px. SVG or PNG preferred. Grayscale."
+ },
+ "scene2_button_label": {
+ "type": "string",
+ "description": "Label for form submit button",
+ "default": "Send"
+ },
+ "scene2_input_placeholder": {
+ "type": "string",
+ "description": "(send to device) Value to show while input is empty.",
+ "default": "Your email here"
+ },
+ "scene2_disclaimer_html": {
+ "type": "string",
+ "description": "(send to device) Html for disclaimer and link underneath input box."
+ },
+ "scene2_dismiss_button_text": {
+ "type": "string",
+ "description": "Label for the dismiss button when the sign-up form is expanded.",
+ "default": "Dismiss"
+ },
+ "hidden_inputs": {
+ "type": "object",
+ "description": "Each entry represents a hidden input, key is used as value for the name property.",
+ "properties": {
+ "action": {
+ "type": "string",
+ "enum": ["email"]
+ },
+ "context": {
+ "type": "string",
+ "enum": ["fx_desktop_v3"]
+ },
+ "entrypoint": {
+ "type": "string",
+ "enum": ["snippets"]
+ },
+ "utm_content": {
+ "type": "string",
+ "description": "Firefox version number"
+ },
+ "utm_source": {
+ "type": "string",
+ "enum": ["snippet"]
+ },
+ "utm_campaign": {
+ "type": "string",
+ "description": "(fxa) Value to pass through to GA as utm_campaign."
+ },
+ "utm_term": {
+ "type": "string",
+ "description": "(fxa) Value to pass through to GA as utm_term."
+ },
+ "additionalProperties": false
+ }
+ },
+ "scene1_button_label": {
+ "allOf": [
+ {"$ref": "#/definitions/plainText"},
+ {"description": "Text for a button next to main snippet text that links to button_url. Requires button_url."}
+ ],
+ "default": "Learn more"
+ },
+ "scene1_button_color": {
+ "type": "string",
+ "description": "The text color of the button. Valid CSS color."
+ },
+ "scene1_button_background_color": {
+ "type": "string",
+ "description": "The background color of the button. Valid CSS color."
+ },
+ "retry_button_label": {
+ "allOf": [
+ {"$ref": "#/definitions/plainText"},
+ {"description": "Text for the button in the event of a submission error/failure."}
+ ],
+ "default": "Try again"
+ },
+ "do_not_autoblock": {
+ "type": "boolean",
+ "description": "Used to prevent blocking the snippet after the CTA (link or button) has been clicked",
+ "default": false
+ },
+ "success_title": {
+ "type": "string",
+ "description": "(send to device) Title shown before text on successful registration."
+ },
+ "success_text": {
+ "type": "string",
+ "description": "Message shown on successful registration."
+ },
+ "error_text": {
+ "type": "string",
+ "description": "Message shown if registration failed."
+ },
+ "include_sms": {
+ "type": "boolean",
+ "description": "(send to device) Allow users to send an SMS message with the form?",
+ "default": false
+ },
+ "message_id_sms": {
+ "type": "string",
+ "description": "(send to device) Newsletter/basket id representing the SMS message to be sent."
+ },
+ "message_id_email": {
+ "type": "string",
+ "description": "(send to device) Newsletter/basket id representing the email message to be sent. Must be a value from the 'Slug' column here: https://basket.mozilla.org/news/."
+ },
+ "utm_campaign": {
+ "type": "string",
+ "description": "(fxa) Value to pass through to GA as utm_campaign."
+ },
+ "utm_term": {
+ "type": "string",
+ "description": "(fxa) Value to pass through to GA as utm_term."
+ },
+ "links": {
+ "additionalProperties": {
+ "url": {
+ "allOf": [
+ {"$ref": "#/definitions/link_url"},
+ {"description": "The url where the link points to."}
+ ]
+ },
+ "metric": {
+ "type": "string",
+ "description": "Custom event name sent with telemetry event."
+ }
+ }
+ }
+ },
+ "additionalProperties": false,
+ "required": ["scene1_text", "scene2_text", "scene1_button_label"],
+ "dependencies": {
+ "scene1_button_color": ["scene1_button_label"],
+ "scene1_button_background_color": ["scene1_button_label"]
+ }
+}
+
diff --git a/browser/components/newtab/content-src/asrouter/templates/SendToDeviceSnippet/isEmailOrPhoneNumber.js b/browser/components/newtab/content-src/asrouter/templates/SendToDeviceSnippet/isEmailOrPhoneNumber.js
new file mode 100644
index 0000000000..29addb688d
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/SendToDeviceSnippet/isEmailOrPhoneNumber.js
@@ -0,0 +1,38 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/**
+ * Checks if a given string is an email or phone number or neither
+ * @param {string} val The user input
+ * @param {ASRMessageContent} content .content property on ASR message
+ * @returns {"email"|"phone"|""} The type of the input
+ */
+export function isEmailOrPhoneNumber(val, content) {
+ const { locale } = content;
+ // http://emailregex.com/
+ const email_re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
+ const check_email = email_re.test(val);
+ let check_phone; // depends on locale
+ switch (locale) {
+ case "en-US":
+ case "en-CA":
+ // allow 10-11 digits in case user wants to enter country code
+ check_phone = val.length >= 10 && val.length <= 11 && !isNaN(val);
+ break;
+ case "de":
+ // allow between 2 and 12 digits for german phone numbers
+ check_phone = val.length >= 2 && val.length <= 12 && !isNaN(val);
+ break;
+ // this case should never be hit, but good to have a fallback just in case
+ default:
+ check_phone = !isNaN(val);
+ break;
+ }
+ if (check_email) {
+ return "email";
+ } else if (check_phone) {
+ return "phone";
+ }
+ return "";
+}
diff --git a/browser/components/newtab/content-src/asrouter/templates/SimpleBelowSearchSnippet/SimpleBelowSearchSnippet.jsx b/browser/components/newtab/content-src/asrouter/templates/SimpleBelowSearchSnippet/SimpleBelowSearchSnippet.jsx
new file mode 100644
index 0000000000..2641d51e86
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/SimpleBelowSearchSnippet/SimpleBelowSearchSnippet.jsx
@@ -0,0 +1,133 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import React from "react";
+import { Button } from "../../components/Button/Button";
+import { RichText } from "../../components/RichText/RichText";
+import { safeURI } from "../../template-utils";
+import { SnippetBase } from "../../components/SnippetBase/SnippetBase";
+
+const DEFAULT_ICON_PATH = "chrome://branding/content/icon64.png";
+// Alt text placeholder in case the prop from the server isn't available
+const ICON_ALT_TEXT = "";
+
+export class SimpleBelowSearchSnippet extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onButtonClick = this.onButtonClick.bind(this);
+ }
+
+ renderText() {
+ const { props } = this;
+ return props.content.text ? (
+ <RichText
+ text={props.content.text}
+ customElements={this.props.customElements}
+ localization_id="text"
+ links={props.content.links}
+ sendClick={props.sendClick}
+ />
+ ) : null;
+ }
+
+ renderTitle() {
+ const { title } = this.props.content;
+ return title ? (
+ <h3 className={"title title-inline"}>
+ {title}
+ <br />
+ </h3>
+ ) : null;
+ }
+
+ async onButtonClick() {
+ if (this.props.provider !== "preview") {
+ this.props.sendUserActionTelemetry({
+ event: "CLICK_BUTTON",
+ id: this.props.UISurface,
+ });
+ }
+ const { button_url } = this.props.content;
+ // If button_url is defined handle it as OPEN_URL action
+ const type = this.props.content.button_action || (button_url && "OPEN_URL");
+ await this.props.onAction({
+ type,
+ data: { args: this.props.content.button_action_args || button_url },
+ });
+ if (!this.props.content.do_not_autoblock) {
+ this.props.onBlock();
+ }
+ }
+
+ _shouldRenderButton() {
+ return (
+ this.props.content.button_action ||
+ this.props.onButtonClick ||
+ this.props.content.button_url
+ );
+ }
+
+ renderButton() {
+ const { props } = this;
+ if (!this._shouldRenderButton()) {
+ return null;
+ }
+
+ return (
+ <Button
+ onClick={props.onButtonClick || this.onButtonClick}
+ color={props.content.button_color}
+ backgroundColor={props.content.button_background_color}
+ >
+ {props.content.button_label}
+ </Button>
+ );
+ }
+
+ render() {
+ const { props } = this;
+ let className = "SimpleBelowSearchSnippet";
+ let containerName = "below-search-snippet";
+
+ if (props.className) {
+ className += ` ${props.className}`;
+ }
+ if (this._shouldRenderButton()) {
+ className += " withButton";
+ containerName += " withButton";
+ }
+
+ return (
+ <div className={containerName}>
+ <div className="snippet-hover-wrapper">
+ <SnippetBase
+ {...props}
+ className={className}
+ textStyle={this.props.textStyle}
+ >
+ <img
+ src={safeURI(props.content.icon) || DEFAULT_ICON_PATH}
+ className="icon icon-light-theme"
+ alt={props.content.icon_alt_text || ICON_ALT_TEXT}
+ />
+ <img
+ src={
+ safeURI(props.content.icon_dark_theme || props.content.icon) ||
+ DEFAULT_ICON_PATH
+ }
+ className="icon icon-dark-theme"
+ alt={props.content.icon_alt_text || ICON_ALT_TEXT}
+ />
+ <div className="textContainer">
+ {this.renderTitle()}
+ <p className="body">{this.renderText()}</p>
+ {this.props.extraContent}
+ </div>
+ {<div className="buttonContainer">{this.renderButton()}</div>}
+ </SnippetBase>
+ </div>
+ </div>
+ );
+ }
+}
diff --git a/browser/components/newtab/content-src/asrouter/templates/SimpleBelowSearchSnippet/SimpleBelowSearchSnippet.schema.json b/browser/components/newtab/content-src/asrouter/templates/SimpleBelowSearchSnippet/SimpleBelowSearchSnippet.schema.json
new file mode 100644
index 0000000000..049f66ef6b
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/SimpleBelowSearchSnippet/SimpleBelowSearchSnippet.schema.json
@@ -0,0 +1,110 @@
+{
+ "title": "SimpleBelowSearchSnippet",
+ "description": "A simple template with an icon, rich text and an optional button. It gets inserted below the Activity Stream search box.",
+ "version": "1.2.0",
+ "type": "object",
+ "definitions": {
+ "plainText": {
+ "description": "Plain text (no HTML allowed)",
+ "type": "string"
+ },
+ "richText": {
+ "description": "Text with HTML subset allowed: i, b, u, strong, em, br",
+ "type": "string"
+ },
+ "link_url": {
+ "description": "Target for links or buttons",
+ "type": "string",
+ "format": "uri"
+ }
+ },
+ "properties": {
+ "title": {
+ "allOf": [
+ {"$ref": "#/definitions/plainText"},
+ {"description": "Snippet title displayed before snippet text"}
+ ]
+ },
+ "text": {
+ "allOf": [
+ {"$ref": "#/definitions/richText"},
+ {"description": "Main body text of snippet. HTML subset allowed: i, b, u, strong, em, br"}
+ ]
+ },
+ "icon": {
+ "type": "string",
+ "description": "Snippet icon. 64x64px. SVG or PNG preferred."
+ },
+ "icon_dark_theme": {
+ "type": "string",
+ "description": "Snippet icon. Dark theme variant. 64x64px. SVG or PNG preferred."
+ },
+ "icon_alt_text": {
+ "type": "string",
+ "description": "Alt text describing icon for screen readers",
+ "default": ""
+ },
+ "block_button_text": {
+ "type": "string",
+ "description": "Tooltip text used for dismiss button.",
+ "default": "Remove this"
+ },
+ "button_action": {
+ "type": "string",
+ "description": "The type of action the button should trigger."
+ },
+ "button_url": {
+ "allOf": [
+ {"$ref": "#/definitions/link_url"},
+ {"description": "A url, button_label links to this"}
+ ]
+ },
+ "button_action_args": {
+ "description": "Additional parameters for button action, example which specific menu the button should open"
+ },
+ "button_label": {
+ "allOf": [
+ {"$ref": "#/definitions/plainText"},
+ {"description": "Text for a button next to main snippet text that links to button_url. Requires button_url."}
+ ]
+ },
+ "button_color": {
+ "type": "string",
+ "description": "The text color of the button. Valid CSS color."
+ },
+ "button_background_color": {
+ "type": "string",
+ "description": "The background color of the button. Valid CSS color."
+ },
+ "do_not_autoblock": {
+ "type": "boolean",
+ "description": "Used to prevent blocking the snippet after the CTA link has been clicked"
+ },
+ "links": {
+ "additionalProperties": {
+ "url": {
+ "allOf": [
+ {"$ref": "#/definitions/link_url"},
+ {"description": "The url where the link points to."}
+ ]
+ },
+ "metric": {
+ "type": "string",
+ "description": "Custom event name sent with telemetry event."
+ },
+ "args": {
+ "type": "string",
+ "description": "Additional parameters for link action, example which specific menu the button should open"
+ }
+ }
+ }
+ },
+ "additionalProperties": false,
+ "required": ["text"],
+ "dependencies": {
+ "button_action": ["button_label"],
+ "button_url": ["button_label"],
+ "button_color": ["button_label"],
+ "button_background_color": ["button_label"]
+ }
+}
diff --git a/browser/components/newtab/content-src/asrouter/templates/SimpleBelowSearchSnippet/_SimpleBelowSearchSnippet.scss b/browser/components/newtab/content-src/asrouter/templates/SimpleBelowSearchSnippet/_SimpleBelowSearchSnippet.scss
new file mode 100644
index 0000000000..dd9e637529
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/SimpleBelowSearchSnippet/_SimpleBelowSearchSnippet.scss
@@ -0,0 +1,198 @@
+
+.below-search-snippet {
+ margin: 0 auto 16px;
+
+ &.withButton {
+ margin: auto;
+ min-height: 60px;
+ background-color: transparent;
+
+ .snippet-hover-wrapper {
+ min-height: 60px;
+ border-radius: 4px;
+
+ &:hover {
+ background-color: var(--newtab-element-hover-color);
+
+ .blockButton {
+ display: block;
+ opacity: 1;
+ }
+ }
+ }
+ }
+}
+
+.SimpleBelowSearchSnippet {
+ background-color: transparent;
+ border: 0;
+ box-shadow: none;
+ position: relative;
+ margin: auto;
+ z-index: auto;
+
+ @media (min-width: $break-point-large) {
+ width: 736px;
+ }
+
+ &.active {
+ background-color: var(--newtab-element-hover-color);
+ border-radius: 4px;
+ }
+
+ .innerWrapper {
+ align-items: center;
+ background-color: transparent;
+ border-radius: 4px;
+ box-shadow: var(--newtab-card-shadow);
+ flex-direction: column;
+ padding: 16px;
+ text-align: center;
+ width: 100%;
+
+ @mixin full-width-styles {
+ align-items: flex-start;
+ background-color: transparent;
+ border-radius: 4px;
+ box-shadow: none;
+ flex-direction: row;
+ padding: 0;
+ text-align: inherit;
+ width: 696px;
+ }
+
+ @media (min-width: $break-point-medium) {
+ @include full-width-styles;
+ }
+
+ @media (max-width: 865px) {
+ margin-inline-start: 0;
+ }
+
+ // There is an off-by-one gap between breakpoints; this is to prevent weirdness at exactly 610px.
+ @media (max-width: $break-point-medium - 1px) {
+ margin: auto;
+ }
+ }
+
+ .blockButton {
+ display: block;
+ inset-inline-end: 10px;
+ opacity: 1;
+ top: 50%;
+
+ &:focus {
+ box-shadow: 0 0 0 1px $blue-50 inset, 0 0 0 1px $blue-50, 0 0 0 4px $blue-50-30;
+ border-radius: 2px;
+ }
+ }
+
+ .title {
+ font-size: inherit;
+ margin: 0;
+ }
+
+ .title-inline {
+ display: inline;
+ }
+
+ .textContainer {
+ margin: 10px;
+ margin-inline-start: 0;
+ padding-inline-end: 20px;
+ }
+
+ .icon {
+ margin-top: 8px;
+ margin-inline-start: 12px;
+ height: 32px;
+ width: 32px;
+
+ @mixin full-width-styles {
+ height: 24px;
+ width: 24px;
+ }
+
+ @media (min-width: $break-point-medium) {
+ @include full-width-styles;
+ }
+
+ @media (max-width: $break-point-medium) {
+ margin: auto;
+ }
+ }
+
+ &.withButton {
+ line-height: 20px;
+ margin-bottom: 10px;
+ min-height: 60px;
+ background-color: transparent;
+
+ .innerWrapper {
+ // There is an off-by-one gap between breakpoints; this is to prevent weirdness at exactly 1121px.
+ @media (max-width: $break-point-widest + 1px) {
+ margin: 0 40px;
+ }
+ }
+
+ .blockButton {
+ display: block;
+ inset-inline-end: -10%;
+ opacity: 0;
+ margin: auto;
+ top: unset;
+
+ &:focus {
+ opacity: 1;
+ box-shadow: none;
+ }
+
+ // There is an off-by-one gap between breakpoints; this is to prevent weirdness at exactly 1121px.
+ @media (max-width: $break-point-widest + 1px) {
+ inset-inline-end: 2%;
+ }
+ }
+
+ .icon {
+ width: 42px;
+ height: 42px;
+ flex-shrink: 0;
+ margin: auto 0;
+ margin-inline-end: 10px;
+
+ @media (max-width: $break-point-medium) {
+ margin: auto;
+ }
+ }
+
+ .buttonContainer {
+ margin: auto;
+ margin-inline-end: 0;
+
+ @media (max-width: $break-point-medium) {
+ margin: auto;
+ }
+ }
+ }
+
+ button {
+ @media (max-width: $break-point-medium) {
+ margin: auto;
+ }
+ }
+
+ .body {
+ display: inline;
+ position: sticky;
+ transform: translateY(-50%);
+ margin: 8px 0 0;
+
+ @media (min-width: $break-point-medium) {
+ margin: 12px 0;
+ }
+
+ a {
+ font-weight: 600;
+ }
+ }
+}
diff --git a/browser/components/newtab/content-src/asrouter/templates/SimpleSnippet/SimpleSnippet.jsx b/browser/components/newtab/content-src/asrouter/templates/SimpleSnippet/SimpleSnippet.jsx
new file mode 100644
index 0000000000..8d7b8c1f7b
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/SimpleSnippet/SimpleSnippet.jsx
@@ -0,0 +1,225 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { Button } from "../../components/Button/Button";
+import ConditionalWrapper from "../../components/ConditionalWrapper/ConditionalWrapper";
+import React from "react";
+import { RichText } from "../../components/RichText/RichText";
+import { safeURI } from "../../template-utils";
+import { SnippetBase } from "../../components/SnippetBase/SnippetBase";
+
+const DEFAULT_ICON_PATH = "chrome://branding/content/icon64.png";
+// Alt text placeholder in case the prop from the server isn't available
+const ICON_ALT_TEXT = "";
+
+export class SimpleSnippet extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onButtonClick = this.onButtonClick.bind(this);
+ }
+
+ onButtonClick() {
+ if (this.props.provider !== "preview") {
+ this.props.sendUserActionTelemetry({
+ event: "CLICK_BUTTON",
+ id: this.props.UISurface,
+ });
+ }
+ const {
+ button_url,
+ button_entrypoint_value,
+ button_entrypoint_name,
+ } = this.props.content;
+ // If button_url is defined handle it as OPEN_URL action
+ const type = this.props.content.button_action || (button_url && "OPEN_URL");
+ // Assign the snippet referral for the action
+ const entrypoint = button_entrypoint_name
+ ? new URLSearchParams([
+ [button_entrypoint_name, button_entrypoint_value],
+ ]).toString()
+ : button_entrypoint_value;
+ this.props.onAction({
+ type,
+ data: {
+ args: this.props.content.button_action_args || button_url,
+ ...(entrypoint && { entrypoint }),
+ },
+ });
+ if (!this.props.content.do_not_autoblock) {
+ this.props.onBlock();
+ }
+ }
+
+ _shouldRenderButton() {
+ return (
+ this.props.content.button_action ||
+ this.props.onButtonClick ||
+ this.props.content.button_url
+ );
+ }
+
+ renderTitle() {
+ const { title } = this.props.content;
+ return title ? (
+ <h3
+ className={`title ${this._shouldRenderButton() ? "title-inline" : ""}`}
+ >
+ {this.renderTitleIcon()} {title}
+ </h3>
+ ) : null;
+ }
+
+ renderTitleIcon() {
+ const titleIconLight = safeURI(this.props.content.title_icon);
+ const titleIconDark = safeURI(
+ this.props.content.title_icon_dark_theme || this.props.content.title_icon
+ );
+ if (!titleIconLight) {
+ return null;
+ }
+
+ return (
+ <React.Fragment>
+ <span
+ className="titleIcon icon-light-theme"
+ style={{ backgroundImage: `url("${titleIconLight}")` }}
+ />
+ <span
+ className="titleIcon icon-dark-theme"
+ style={{ backgroundImage: `url("${titleIconDark}")` }}
+ />
+ </React.Fragment>
+ );
+ }
+
+ renderButton() {
+ const { props } = this;
+ if (!this._shouldRenderButton()) {
+ return null;
+ }
+
+ return (
+ <Button
+ onClick={props.onButtonClick || this.onButtonClick}
+ color={props.content.button_color}
+ backgroundColor={props.content.button_background_color}
+ >
+ {props.content.button_label}
+ </Button>
+ );
+ }
+
+ renderText() {
+ const { props } = this;
+ return (
+ <RichText
+ text={props.content.text}
+ customElements={this.props.customElements}
+ localization_id="text"
+ links={props.content.links}
+ sendClick={props.sendClick}
+ />
+ );
+ }
+
+ wrapSectionHeader(url) {
+ return function(children) {
+ return <a href={url}>{children}</a>;
+ };
+ }
+
+ wrapSnippetContent(children) {
+ return <div className="innerContentWrapper">{children}</div>;
+ }
+
+ renderSectionHeader() {
+ const { props } = this;
+
+ // an icon and text must be specified to render the section header
+ if (props.content.section_title_icon && props.content.section_title_text) {
+ const sectionTitleIconLight = safeURI(props.content.section_title_icon);
+ const sectionTitleIconDark = safeURI(
+ props.content.section_title_icon_dark_theme ||
+ props.content.section_title_icon
+ );
+ const sectionTitleURL = props.content.section_title_url;
+
+ return (
+ <div className="section-header">
+ <h3 className="section-title">
+ <ConditionalWrapper
+ condition={sectionTitleURL}
+ wrap={this.wrapSectionHeader(sectionTitleURL)}
+ >
+ <span
+ className="icon icon-small-spacer icon-light-theme"
+ style={{ backgroundImage: `url("${sectionTitleIconLight}")` }}
+ />
+ <span
+ className="icon icon-small-spacer icon-dark-theme"
+ style={{ backgroundImage: `url("${sectionTitleIconDark}")` }}
+ />
+ <span className="section-title-text">
+ {props.content.section_title_text}
+ </span>
+ </ConditionalWrapper>
+ </h3>
+ </div>
+ );
+ }
+
+ return null;
+ }
+
+ render() {
+ const { props } = this;
+ const sectionHeader = this.renderSectionHeader();
+ let className = "SimpleSnippet";
+
+ if (props.className) {
+ className += ` ${props.className}`;
+ }
+ if (props.content.tall) {
+ className += " tall";
+ }
+ if (sectionHeader) {
+ className += " has-section-header";
+ }
+
+ return (
+ <div className="snippet-hover-wrapper">
+ <SnippetBase
+ {...props}
+ className={className}
+ textStyle={this.props.textStyle}
+ >
+ {sectionHeader}
+ <ConditionalWrapper
+ condition={sectionHeader}
+ wrap={this.wrapSnippetContent}
+ >
+ <img
+ src={safeURI(props.content.icon) || DEFAULT_ICON_PATH}
+ className="icon icon-light-theme"
+ alt={props.content.icon_alt_text || ICON_ALT_TEXT}
+ />
+ <img
+ src={
+ safeURI(props.content.icon_dark_theme || props.content.icon) ||
+ DEFAULT_ICON_PATH
+ }
+ className="icon icon-dark-theme"
+ alt={props.content.icon_alt_text || ICON_ALT_TEXT}
+ />
+ <div>
+ {this.renderTitle()} <p className="body">{this.renderText()}</p>
+ {this.props.extraContent}
+ </div>
+ {<div>{this.renderButton()}</div>}
+ </ConditionalWrapper>
+ </SnippetBase>
+ </div>
+ );
+ }
+}
diff --git a/browser/components/newtab/content-src/asrouter/templates/SimpleSnippet/SimpleSnippet.schema.json b/browser/components/newtab/content-src/asrouter/templates/SimpleSnippet/SimpleSnippet.schema.json
new file mode 100644
index 0000000000..1229700d67
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/SimpleSnippet/SimpleSnippet.schema.json
@@ -0,0 +1,155 @@
+{
+ "title": "SimpleSnippet",
+ "description": "A simple template with an icon, text, and optional button.",
+ "version": "1.1.2",
+ "type": "object",
+ "definitions": {
+ "plainText": {
+ "description": "Plain text (no HTML allowed)",
+ "type": "string"
+ },
+ "richText": {
+ "description": "Text with HTML subset allowed: i, b, u, strong, em, br",
+ "type": "string"
+ },
+ "link_url": {
+ "description": "Target for links or buttons",
+ "type": "string",
+ "format": "uri"
+ }
+ },
+ "properties": {
+ "title": {
+ "allOf": [
+ {"$ref": "#/definitions/plainText"},
+ {"description": "Snippet title displayed before snippet text"}
+ ]
+ },
+ "text": {
+ "allOf": [
+ {"$ref": "#/definitions/richText"},
+ {"description": "Main body text of snippet. HTML subset allowed: i, b, u, strong, em, br"}
+ ]
+ },
+ "icon": {
+ "type": "string",
+ "description": "Snippet icon. 64x64px. SVG or PNG preferred."
+ },
+ "icon_dark_theme": {
+ "type": "string",
+ "description": "Snippet icon, dark theme variant. 64x64px. SVG or PNG preferred."
+ },
+ "icon_alt_text": {
+ "type": "string",
+ "description": "Alt text describing icon for screen readers",
+ "default": ""
+ },
+ "title_icon": {
+ "type": "string",
+ "description": "Small icon that shows up before the title / text. 16x16px. SVG or PNG preferred. Grayscale."
+ },
+ "title_icon_dark_theme": {
+ "type": "string",
+ "description": "Small icon that shows up before the title / text. Dark theme variant. 16x16px. SVG or PNG preferred. Grayscale."
+ },
+ "title_icon_alt_text": {
+ "type": "string",
+ "description": "Alt text describing title icon for screen readers",
+ "default": ""
+ },
+ "button_action": {
+ "type": "string",
+ "description": "The type of action the button should trigger."
+ },
+ "button_url": {
+ "allOf": [
+ {"$ref": "#/definitions/link_url"},
+ {"description": "A url, button_label links to this"}
+ ]
+ },
+ "button_action_args": {
+ "description": "Additional parameters for button action, example which specific menu the button should open"
+ },
+ "button_entrypoint_value": {
+ "description": "String used for telemetry attribution of clicks",
+ "type": "string"
+ },
+ "button_entrypoint_name": {
+ "description": "String used for telemetry attribution of clicks",
+ "type": "string"
+ },
+ "button_label": {
+ "allOf": [
+ {"$ref": "#/definitions/plainText"},
+ {"description": "Text for a button next to main snippet text that links to button_url. Requires button_url."}
+ ]
+ },
+ "button_color": {
+ "type": "string",
+ "description": "The text color of the button. Valid CSS color."
+ },
+ "button_background_color": {
+ "type": "string",
+ "description": "The background color of the button. Valid CSS color."
+ },
+ "block_button_text": {
+ "type": "string",
+ "description": "Tooltip text used for dismiss button.",
+ "default": "Remove this"
+ },
+ "tall": {
+ "type": "boolean",
+ "description": "To be used by fundraising only, increases height to roughly 120px. Defaults to false."
+ },
+ "do_not_autoblock": {
+ "type": "boolean",
+ "description": "Used to prevent blocking the snippet after the CTA (link or button) has been clicked"
+ },
+ "links": {
+ "additionalProperties": {
+ "url": {
+ "allOf": [
+ {"$ref": "#/definitions/link_url"},
+ {"description": "The url where the link points to."}
+ ]
+ },
+ "metric": {
+ "type": "string",
+ "description": "Custom event name sent with telemetry event."
+ },
+ "args": {
+ "type": "string",
+ "description": "Additional parameters for link action, example which specific menu the button should open"
+ }
+ }
+ },
+ "section_title_icon": {
+ "type": "string",
+ "description": "Section title icon. 16x16px. SVG or PNG preferred. section_title_text must also be specified to display."
+ },
+ "section_title_icon_dark_theme": {
+ "type": "string",
+ "description": "Section title icon, dark theme variant. 16x16px. SVG or PNG preferred. section_title_text must also be specified to display."
+ },
+ "section_title_text": {
+ "type": "string",
+ "description": "Section title text. section_title_icon must also be specified to display."
+ },
+ "section_title_url": {
+ "allOf": [
+ {"$ref": "#/definitions/link_url"},
+ {"description": "A url, section_title_text links to this"}
+ ]
+ }
+ },
+ "additionalProperties": false,
+ "required": ["text"],
+ "dependencies": {
+ "button_action": ["button_label"],
+ "button_url": ["button_label"],
+ "button_color": ["button_label"],
+ "button_background_color": ["button_label"],
+ "section_title_url": ["section_title_text"],
+ "button_entrypoint_name": ["button_entrypoint_value"]
+ }
+}
diff --git a/browser/components/newtab/content-src/asrouter/templates/SimpleSnippet/_SimpleSnippet.scss b/browser/components/newtab/content-src/asrouter/templates/SimpleSnippet/_SimpleSnippet.scss
new file mode 100644
index 0000000000..b16f78dc93
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/SimpleSnippet/_SimpleSnippet.scss
@@ -0,0 +1,135 @@
+$section-header-height: 30px;
+$icon-width: 54px; // width of primary icon + margin
+
+.SimpleSnippet {
+ &.tall {
+ padding: 27px 0;
+ }
+
+ p em {
+ color: $grey-90;
+ font-style: normal;
+ background: $yellow-50;
+ }
+
+ &.bold,
+ &.takeover {
+ .donation-form-url,
+ .donation-amount {
+ padding-top: 8px;
+ padding-bottom: 8px;
+ }
+ }
+
+ &.bold {
+ height: 176px;
+
+ .body {
+ font-size: 14px;
+ line-height: 20px;
+ margin-bottom: 20px;
+ }
+
+ .icon {
+ width: 71px;
+ height: 71px;
+ }
+ }
+
+ &.takeover {
+ height: 344px;
+
+ .body {
+ font-size: 16px;
+ line-height: 24px;
+ margin-bottom: 35px;
+ }
+
+ .icon {
+ width: 79px;
+ height: 79px;
+ }
+ }
+
+ .title {
+ font-size: inherit;
+ margin: 0;
+ }
+
+ .title-inline {
+ display: inline;
+ }
+
+ .titleIcon {
+ background-repeat: no-repeat;
+ background-size: 14px;
+ background-position: center;
+ height: 16px;
+ width: 16px;
+ margin-top: 2px;
+ margin-inline-end: 2px;
+ display: inline-block;
+ vertical-align: top;
+ }
+
+ .body {
+ display: inline;
+ margin: 0;
+ }
+
+ &.tall .icon {
+ margin-inline-end: 20px;
+ }
+
+ &.takeover,
+ &.bold {
+ .icon {
+ margin-inline-end: 20px;
+ }
+ }
+
+ .icon {
+ align-self: flex-start;
+ }
+
+ &.has-section-header .innerWrapper {
+ // account for section header being 100% width
+ flex-wrap: wrap;
+ padding-top: 7px;
+ }
+
+ // wrapper div added if section-header is displayed that allows icon/text/button
+ // to squish instead of wrapping. this is effectively replicating layout behavior
+ // when section-header is *not* present.
+ .innerContentWrapper {
+ align-items: center;
+ display: flex;
+ }
+
+ .section-header {
+ flex: 0 0 100%;
+ margin-bottom: 10px;
+ }
+
+ .section-title {
+ // color should match that of 'Recommended by Pocket' and 'Highlights' in newtab page
+ color: var(--newtab-section-header-text-color);
+ display: inline-block;
+ font-size: 13px;
+ font-weight: bold;
+ margin: 0;
+
+ a {
+ color: var(--newtab-section-header-text-color);
+ font-weight: inherit;
+ text-decoration: none;
+ }
+
+ .icon {
+ height: 16px;
+ margin-inline-end: 6px;
+ margin-top: -2px;
+ width: 16px;
+ }
+ }
+}
diff --git a/browser/components/newtab/content-src/asrouter/templates/SubmitFormSnippet/SubmitFormScene2Snippet.schema.json b/browser/components/newtab/content-src/asrouter/templates/SubmitFormSnippet/SubmitFormScene2Snippet.schema.json
new file mode 100644
index 0000000000..f3dcde11af
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/SubmitFormSnippet/SubmitFormScene2Snippet.schema.json
@@ -0,0 +1,163 @@
+{
+ "title": "SubmitFormSnippet",
+ "description": "A template with two states: a SimpleSnippet and another that contains a form",
+ "version": "1.2.0",
+ "type": "object",
+ "definitions": {
+ "plainText": {
+ "description": "Plain text (no HTML allowed)",
+ "type": "string"
+ },
+ "richText": {
+ "description": "Text with HTML subset allowed: i, b, u, strong, em, br",
+ "type": "string"
+ },
+ "link_url": {
+ "description": "Target for links or buttons",
+ "type": "string",
+ "format": "uri"
+ }
+ },
+ "properties": {
+ "locale": {
+ "type": "string",
+ "description": "Two to five character string for the locale code"
+ },
+ "country": {
+ "type": "string",
+ "description": "Two character string for the country code (used for SMS)"
+ },
+ "section_title_icon": {
+ "type": "string",
+ "description": "Section title icon. 16x16px. SVG or PNG preferred. section_title_text must also be specified to display."
+ },
+ "section_title_icon_dark_theme": {
+ "type": "string",
+ "description": "Section title icon, dark theme variant. 16x16px. SVG or PNG preferred. section_title_text must also be specified to display."
+ },
+ "section_title_text": {
+ "type": "string",
+ "description": "Section title text. section_title_icon must also be specified to display."
+ },
+ "section_title_url": {
+ "allOf": [
+ {"$ref": "#/definitions/link_url"},
+ {"description": "A url, section_title_text links to this"}
+ ]
+ },
+ "scene2_text": {
+ "allOf": [
+ {"$ref": "#/definitions/richText"},
+ {"description": "Main body text of snippet. HTML subset allowed: i, b, u, strong, em, br"}
+ ]
+ },
+ "form_action": {
+ "type": "string",
+ "description": "Endpoint to submit form data."
+ },
+ "success_title": {
+ "type": "string",
+ "description": "(send to device) Title shown before text on successful registration."
+ },
+ "success_text": {
+ "type": "string",
+ "description": "Message shown on successful registration."
+ },
+ "error_text": {
+ "type": "string",
+ "description": "Message shown if registration failed."
+ },
+ "scene2_email_placeholder_text": {
+ "type": "string",
+ "description": "Value to show while input is empty."
+ },
+ "scene2_input_placeholder": {
+ "type": "string",
+ "description": "(send to device) Value to show while input is empty."
+ },
+ "scene2_button_label": {
+ "type": "string",
+ "description": "Label for form submit button"
+ },
+ "scene2_privacy_html": {
+ "type": "string",
+ "description": "Information about how the form data is used."
+ },
+ "scene2_disclaimer_html": {
+ "type": "string",
+ "description": "(send to device) Html for disclaimer and link underneath input box."
+ },
+ "scene2_icon": {
+ "type": "string",
+ "description": "(send to device) Image to display above the form. 98x98px. SVG or PNG preferred."
+ },
+ "scene2_icon_dark_theme": {
+ "type": "string",
+ "description": "(send to device) Image to display above the form. Dark theme variant. 98x98px. SVG or PNG preferred."
+ },
+ "scene2_icon_alt_text": {
+ "type": "string",
+ "description": "Alt text describing scene2 icon for screen readers",
+ "default": ""
+ },
+ "scene2_newsletter": {
+ "type": "string",
+ "description": "Newsletter/basket id user is subscribing to. Must be a value from the 'Slug' column here: https://basket.mozilla.org/news/. Default 'mozilla-foundation'."
+ },
+ "hidden_inputs": {
+ "type": "object",
+ "description": "Each entry represents a hidden input, key is used as value for the name property."
+ },
+ "retry_button_label": {
+ "allOf": [
+ {"$ref": "#/definitions/plainText"},
+ {"description": "Text for the button in the event of a submission error/failure."}
+ ],
+ "default": "Try again"
+ },
+ "do_not_autoblock": {
+ "type": "boolean",
+ "description": "Used to prevent blocking the snippet after the CTA (link or button) has been clicked"
+ },
+ "include_sms": {
+ "type": "boolean",
+ "description": "(send to device) Allow users to send an SMS message with the form?"
+ },
+ "message_id_sms": {
+ "type": "string",
+ "description": "(send to device) Newsletter/basket id representing the SMS message to be sent."
+ },
+ "message_id_email": {
+ "type": "string",
+ "description": "(send to device) Newsletter/basket id representing the email message to be sent. Must be a value from the 'Slug' column here: https://basket.mozilla.org/news/."
+ },
+ "utm_campaign": {
+ "type": "string",
+ "description": "(fxa) Value to pass through to GA as utm_campaign."
+ },
+ "utm_term": {
+ "type": "string",
+ "description": "(fxa) Value to pass through to GA as utm_term."
+ },
+ "links": {
+ "additionalProperties": {
+ "url": {
+ "allOf": [
+ {"$ref": "#/definitions/link_url"},
+ {"description": "The url where the link points to."}
+ ]
+ },
+ "metric": {
+ "type": "string",
+ "description": "Custom event name sent with telemetry event."
+ }
+ }
+ }
+ },
+ "additionalProperties": false,
+ "required": ["scene2_text"],
+ "dependencies": {
+ "section_title_icon": ["section_title_text"],
+ "section_title_icon_dark_theme": ["section_title_text"]
+ }
+}
diff --git a/browser/components/newtab/content-src/asrouter/templates/SubmitFormSnippet/SubmitFormSnippet.jsx b/browser/components/newtab/content-src/asrouter/templates/SubmitFormSnippet/SubmitFormSnippet.jsx
new file mode 100644
index 0000000000..d1f267f2fa
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/SubmitFormSnippet/SubmitFormSnippet.jsx
@@ -0,0 +1,409 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { Button } from "../../components/Button/Button";
+import React from "react";
+import { RichText } from "../../components/RichText/RichText";
+import { safeURI } from "../../template-utils";
+import { SimpleSnippet } from "../SimpleSnippet/SimpleSnippet";
+import { SnippetBase } from "../../components/SnippetBase/SnippetBase";
+import ConditionalWrapper from "../../components/ConditionalWrapper/ConditionalWrapper";
+
+// Alt text placeholder in case the prop from the server isn't available
+const ICON_ALT_TEXT = "";
+
+export class SubmitFormSnippet extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.expandSnippet = this.expandSnippet.bind(this);
+ this.handleSubmit = this.handleSubmit.bind(this);
+ this.handleSubmitAttempt = this.handleSubmitAttempt.bind(this);
+ this.onInputChange = this.onInputChange.bind(this);
+ this.state = {
+ expanded: false,
+ submitAttempted: false,
+ signupSubmitted: false,
+ signupSuccess: false,
+ disableForm: false,
+ };
+ }
+
+ handleSubmitAttempt() {
+ if (!this.state.submitAttempted) {
+ this.setState({ submitAttempted: true });
+ }
+ }
+
+ async handleSubmit(event) {
+ let json;
+
+ if (this.state.disableForm) {
+ return;
+ }
+
+ event.preventDefault();
+ this.setState({ disableForm: true });
+ this.props.sendUserActionTelemetry({
+ event: "CLICK_BUTTON",
+ event_context: "conversion-subscribe-activation",
+ id: "NEWTAB_FOOTER_BAR_CONTENT",
+ });
+
+ if (this.props.form_method.toUpperCase() === "GET") {
+ this.props.onBlock({ preventDismiss: true });
+ this.refs.form.submit();
+ return;
+ }
+
+ const { url, formData } = this.props.processFormData
+ ? this.props.processFormData(this.refs.mainInput, this.props)
+ : { url: this.refs.form.action, formData: new FormData(this.refs.form) };
+
+ try {
+ const fetchRequest = new Request(url, {
+ body: formData,
+ method: "POST",
+ credentials: "omit",
+ });
+ const response = await fetch(fetchRequest); // eslint-disable-line fetch-options/no-fetch-credentials
+ json = await response.json();
+ } catch (err) {
+ console.log(err); // eslint-disable-line no-console
+ }
+
+ if (json && json.status === "ok") {
+ this.setState({ signupSuccess: true, signupSubmitted: true });
+ if (!this.props.content.do_not_autoblock) {
+ this.props.onBlock({ preventDismiss: true });
+ }
+ this.props.sendUserActionTelemetry({
+ event: "CLICK_BUTTON",
+ event_context: "subscribe-success",
+ id: "NEWTAB_FOOTER_BAR_CONTENT",
+ });
+ } else {
+ // eslint-disable-next-line no-console
+ console.error(
+ "There was a problem submitting the form",
+ json || "[No JSON response]"
+ );
+ this.setState({ signupSuccess: false, signupSubmitted: true });
+ this.props.sendUserActionTelemetry({
+ event: "CLICK_BUTTON",
+ event_context: "subscribe-error",
+ id: "NEWTAB_FOOTER_BAR_CONTENT",
+ });
+ }
+
+ this.setState({ disableForm: false });
+ }
+
+ expandSnippet() {
+ this.props.sendUserActionTelemetry({
+ event: "CLICK_BUTTON",
+ event_context: "scene1-button-learn-more",
+ id: this.props.UISurface,
+ });
+
+ this.setState({
+ expanded: true,
+ signupSuccess: false,
+ signupSubmitted: false,
+ });
+ }
+
+ renderHiddenFormInputs() {
+ const { hidden_inputs } = this.props.content;
+
+ if (!hidden_inputs) {
+ return null;
+ }
+
+ return Object.keys(hidden_inputs).map((key, idx) => (
+ <input key={idx} type="hidden" name={key} value={hidden_inputs[key]} />
+ ));
+ }
+
+ renderDisclaimer() {
+ const { content } = this.props;
+ if (!content.scene2_disclaimer_html) {
+ return null;
+ }
+ return (
+ <p className="disclaimerText">
+ <RichText
+ text={content.scene2_disclaimer_html}
+ localization_id="disclaimer_html"
+ links={content.links}
+ doNotAutoBlock={true}
+ openNewWindow={true}
+ sendClick={this.props.sendClick}
+ />
+ </p>
+ );
+ }
+
+ renderFormPrivacyNotice() {
+ const { content } = this.props;
+ if (!content.scene2_privacy_html) {
+ return null;
+ }
+ return (
+ <p className="privacyNotice">
+ <input
+ type="checkbox"
+ id="id_privacy"
+ name="privacy"
+ required="required"
+ />
+ <label htmlFor="id_privacy">
+ <RichText
+ text={content.scene2_privacy_html}
+ localization_id="privacy_html"
+ links={content.links}
+ doNotAutoBlock={true}
+ openNewWindow={true}
+ sendClick={this.props.sendClick}
+ />
+ </label>
+ </p>
+ );
+ }
+
+ renderSignupSubmitted() {
+ const { content } = this.props;
+ const isSuccess = this.state.signupSuccess;
+ const successTitle = isSuccess && content.success_title;
+ const bodyText = isSuccess
+ ? { success_text: content.success_text }
+ : { error_text: content.error_text };
+ const retryButtonText = content.retry_button_label;
+ return (
+ <SnippetBase {...this.props}>
+ <div className="submissionStatus">
+ {successTitle ? (
+ <h2 className="submitStatusTitle">{successTitle}</h2>
+ ) : null}
+ <p>
+ <RichText
+ {...bodyText}
+ localization_id={isSuccess ? "success_text" : "error_text"}
+ />
+ {isSuccess ? null : (
+ <Button onClick={this.expandSnippet}>{retryButtonText}</Button>
+ )}
+ </p>
+ </div>
+ </SnippetBase>
+ );
+ }
+
+ onInputChange(event) {
+ if (!this.props.validateInput) {
+ return;
+ }
+ const hasError = this.props.validateInput(
+ event.target.value,
+ this.props.content
+ );
+ event.target.setCustomValidity(hasError);
+ }
+
+ wrapSectionHeader(url) {
+ return function(children) {
+ return <a href={url}>{children}</a>;
+ };
+ }
+
+ renderInput() {
+ const placholder =
+ this.props.content.scene2_email_placeholder_text ||
+ this.props.content.scene2_input_placeholder;
+ return (
+ <input
+ ref="mainInput"
+ type={this.props.inputType || "email"}
+ className={`mainInput${this.state.submitAttempted ? "" : " clean"}`}
+ name="email"
+ required={true}
+ placeholder={placholder}
+ onChange={this.props.validateInput ? this.onInputChange : null}
+ />
+ );
+ }
+
+ renderForm() {
+ return (
+ <form
+ action={this.props.form_action}
+ method={this.props.form_method}
+ onSubmit={this.handleSubmit}
+ ref="form"
+ >
+ {this.renderHiddenFormInputs()}
+ <div>
+ {this.renderInput()}
+ <button
+ type="submit"
+ className="ASRouterButton primary"
+ onClick={this.handleSubmitAttempt}
+ ref="formSubmitBtn"
+ >
+ {this.props.content.scene2_button_label}
+ </button>
+ </div>
+ {this.renderFormPrivacyNotice() || this.renderDisclaimer()}
+ </form>
+ );
+ }
+
+ renderScene2Icon() {
+ const { content } = this.props;
+ if (!content.scene2_icon) {
+ return null;
+ }
+
+ return (
+ <div className="scene2Icon">
+ <img
+ src={safeURI(content.scene2_icon)}
+ className="icon-light-theme"
+ alt={content.scene2_icon_alt_text || ICON_ALT_TEXT}
+ />
+ <img
+ src={safeURI(content.scene2_icon_dark_theme || content.scene2_icon)}
+ className="icon-dark-theme"
+ alt={content.scene2_icon_alt_text || ICON_ALT_TEXT}
+ />
+ </div>
+ );
+ }
+
+ renderSignupView() {
+ const { content } = this.props;
+ const containerClass = `SubmitFormSnippet ${this.props.className}`;
+ return (
+ <SnippetBase
+ {...this.props}
+ className={containerClass}
+ footerDismiss={true}
+ >
+ {this.renderScene2Icon()}
+ <div className="message">
+ <p>
+ {content.scene2_title && (
+ <h3 className="scene2Title">{content.scene2_title}</h3>
+ )}{" "}
+ {content.scene2_text && (
+ <RichText
+ scene2_text={content.scene2_text}
+ localization_id="scene2_text"
+ />
+ )}
+ </p>
+ </div>
+ {this.renderForm()}
+ </SnippetBase>
+ );
+ }
+
+ renderSectionHeader() {
+ const { props } = this;
+
+ // an icon and text must be specified to render the section header
+ if (props.content.section_title_icon && props.content.section_title_text) {
+ const sectionTitleIconLight = safeURI(props.content.section_title_icon);
+ const sectionTitleIconDark = safeURI(
+ props.content.section_title_icon_dark_theme ||
+ props.content.section_title_icon
+ );
+ const sectionTitleURL = props.content.section_title_url;
+
+ return (
+ <div className="section-header">
+ <h3 className="section-title">
+ <ConditionalWrapper
+ wrap={this.wrapSectionHeader(sectionTitleURL)}
+ condition={sectionTitleURL}
+ >
+ <span
+ className="icon icon-small-spacer icon-light-theme"
+ style={{ backgroundImage: `url("${sectionTitleIconLight}")` }}
+ />
+ <span
+ className="icon icon-small-spacer icon-dark-theme"
+ style={{ backgroundImage: `url("${sectionTitleIconDark}")` }}
+ />
+ <span className="section-title-text">
+ {props.content.section_title_text}
+ </span>
+ </ConditionalWrapper>
+ </h3>
+ </div>
+ );
+ }
+
+ return null;
+ }
+
+ renderSignupViewAlt() {
+ const { content } = this.props;
+ const containerClass = `SubmitFormSnippet ${this.props.className} scene2Alt`;
+ return (
+ <SnippetBase
+ {...this.props}
+ className={containerClass}
+ // Don't show bottom dismiss button
+ footerDismiss={false}
+ >
+ {this.renderSectionHeader()}
+ {this.renderScene2Icon()}
+ <div className="message">
+ <p>
+ {content.scene2_text && (
+ <RichText
+ scene2_text={content.scene2_text}
+ localization_id="scene2_text"
+ />
+ )}
+ </p>
+ {this.renderForm()}
+ </div>
+ </SnippetBase>
+ );
+ }
+
+ getFirstSceneContent() {
+ return Object.keys(this.props.content)
+ .filter(key => key.includes("scene1"))
+ .reduce((acc, key) => {
+ acc[key.substr(7)] = this.props.content[key];
+ return acc;
+ }, {});
+ }
+
+ render() {
+ const content = { ...this.props.content, ...this.getFirstSceneContent() };
+
+ if (this.state.signupSubmitted) {
+ return this.renderSignupSubmitted();
+ }
+ // Render only scene 2 (signup view). Must check before `renderSignupView`
+ // to catch the Failure/Try again scenario where we want to return and render
+ // the scene again.
+ if (this.props.expandedAlt) {
+ return this.renderSignupViewAlt();
+ }
+ if (this.state.expanded) {
+ return this.renderSignupView();
+ }
+ return (
+ <SimpleSnippet
+ {...this.props}
+ content={content}
+ onButtonClick={this.expandSnippet}
+ />
+ );
+ }
+}
diff --git a/browser/components/newtab/content-src/asrouter/templates/SubmitFormSnippet/SubmitFormSnippet.schema.json b/browser/components/newtab/content-src/asrouter/templates/SubmitFormSnippet/SubmitFormSnippet.schema.json
new file mode 100644
index 0000000000..0fc3128d1c
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/SubmitFormSnippet/SubmitFormSnippet.schema.json
@@ -0,0 +1,225 @@
+{
+ "title": "SubmitFormSnippet",
+ "description": "A template with two states: a SimpleSnippet and another that contains a form",
+ "version": "1.2.0",
+ "type": "object",
+ "definitions": {
+ "plainText": {
+ "description": "Plain text (no HTML allowed)",
+ "type": "string"
+ },
+ "richText": {
+ "description": "Text with HTML subset allowed: i, b, u, strong, em, br",
+ "type": "string"
+ },
+ "link_url": {
+ "description": "Target for links or buttons",
+ "type": "string",
+ "format": "uri"
+ }
+ },
+ "properties": {
+ "locale": {
+ "type": "string",
+ "description": "Two to five character string for the locale code"
+ },
+ "country": {
+ "type": "string",
+ "description": "Two character string for the country code (used for SMS)"
+ },
+ "scene1_title": {
+ "allof": [
+ {"$ref": "#/definitions/plainText"},
+ {"description": "snippet title displayed before snippet text"}
+ ]
+ },
+ "scene1_text": {
+ "allOf": [
+ {"$ref": "#/definitions/richText"},
+ {"description": "Main body text of snippet. HTML subset allowed: i, b, u, strong, em, br"}
+ ]
+ },
+ "scene1_section_title_icon": {
+ "type": "string",
+ "description": "Section title icon for scene 1. 16x16px. SVG or PNG preferred. scene1_section_title_text must also be specified to display."
+ },
+ "scene1_section_title_icon_dark_theme": {
+ "type": "string",
+ "description": "Section title icon for scene 1, dark theme variant. 16x16px. SVG or PNG preferred. scene1_section_title_text must also be specified to display."
+ },
+ "scene1_section_title_text": {
+ "type": "string",
+ "description": "Section title text for scene 1. scene1_section_title_icon must also be specified to display."
+ },
+ "scene1_section_title_url": {
+ "allOf": [
+ {"$ref": "#/definitions/link_url"},
+ {"description": "A url, scene1_section_title_text links to this"}
+ ]
+ },
+ "scene2_title": {
+ "allOf": [
+ {"$ref": "#/definitions/plainText"},
+ {"description": "Title displayed before text in scene 2. Should be plain text."}
+ ]
+ },
+ "scene2_text": {
+ "allOf": [
+ {"$ref": "#/definitions/richText"},
+ {"description": "Main body text of snippet. HTML subset allowed: i, b, u, strong, em, br"}
+ ]
+ },
+ "scene1_icon": {
+ "type": "string",
+ "description": "Snippet icon. 64x64px. SVG or PNG preferred."
+ },
+ "scene1_icon_dark_theme": {
+ "type": "string",
+ "description": "Snippet icon. Dark theme variant. 64x64px. SVG or PNG preferred."
+ },
+ "scene1_icon_alt_text": {
+ "type": "string",
+ "description": "Alt text describing scene1 icon for screen readers",
+ "default": ""
+ },
+ "scene1_title_icon": {
+ "type": "string",
+ "description": "Small icon that shows up before the title / text. 16x16px. SVG or PNG preferred. Grayscale."
+ },
+ "scene1_title_icon_dark_theme": {
+ "type": "string",
+ "description": "Small icon that shows up before the title / text. Dark theme variant. 16x16px. SVG or PNG preferred. Grayscale."
+ },
+ "scene1_title_icon_alt_text": {
+ "type": "string",
+ "description": "Alt text describing scene1 title icon for screen readers",
+ "default": ""
+ },
+ "form_action": {
+ "type": "string",
+ "description": "Endpoint to submit form data."
+ },
+ "success_title": {
+ "type": "string",
+ "description": "(send to device) Title shown before text on successful registration."
+ },
+ "success_text": {
+ "type": "string",
+ "description": "Message shown on successful registration."
+ },
+ "error_text": {
+ "type": "string",
+ "description": "Message shown if registration failed."
+ },
+ "scene2_email_placeholder_text": {
+ "type": "string",
+ "description": "Value to show while input is empty."
+ },
+ "scene2_input_placeholder": {
+ "type": "string",
+ "description": "(send to device) Value to show while input is empty."
+ },
+ "scene2_button_label": {
+ "type": "string",
+ "description": "Label for form submit button"
+ },
+ "scene2_privacy_html": {
+ "type": "string",
+ "description": "Information about how the form data is used."
+ },
+ "scene2_disclaimer_html": {
+ "type": "string",
+ "description": "(send to device) Html for disclaimer and link underneath input box."
+ },
+ "scene2_dismiss_button_text": {
+ "type": "string",
+ "description": "Label for the dismiss button when the sign-up form is expanded."
+ },
+ "scene2_icon": {
+ "type": "string",
+ "description": "(send to device) Image to display above the form. 98x98px. SVG or PNG preferred."
+ },
+ "scene2_icon_dark_theme": {
+ "type": "string",
+ "description": "(send to device) Image to display above the form. Dark theme variant. 98x98px. SVG or PNG preferred."
+ },
+ "scene2_icon_alt_text": {
+ "type": "string",
+ "description": "Alt text describing scene2 icon for screen readers",
+ "default": ""
+ },
+ "scene2_newsletter": {
+ "type": "string",
+ "description": "Newsletter/basket id user is subscribing to. Must be a value from the 'Slug' column here: https://basket.mozilla.org/news/. Default 'mozilla-foundation'."
+ },
+ "hidden_inputs": {
+ "type": "object",
+ "description": "Each entry represents a hidden input, key is used as value for the name property."
+ },
+ "scene1_button_label": {
+ "allOf": [
+ {"$ref": "#/definitions/plainText"},
+ {"description": "Text for a button next to main snippet text that links to button_url. Requires button_url."}
+ ]
+ },
+ "scene1_button_color": {
+ "type": "string",
+ "description": "The text color of the button. Valid CSS color."
+ },
+ "scene1_button_background_color": {
+ "type": "string",
+ "description": "The background color of the button. Valid CSS color."
+ },
+ "retry_button_label": {
+ "allOf": [
+ {"$ref": "#/definitions/plainText"},
+ {"description": "Text for the button in the event of a submission error/failure."}
+ ],
+ "default": "Try again"
+ },
+ "do_not_autoblock": {
+ "type": "boolean",
+ "description": "Used to prevent blocking the snippet after the CTA (link or button) has been clicked"
+ },
+ "include_sms": {
+ "type": "boolean",
+ "description": "(send to device) Allow users to send an SMS message with the form?"
+ },
+ "message_id_sms": {
+ "type": "string",
+ "description": "(send to device) Newsletter/basket id representing the SMS message to be sent."
+ },
+ "message_id_email": {
+ "type": "string",
+ "description": "(send to device) Newsletter/basket id representing the email message to be sent. Must be a value from the 'Slug' column here: https://basket.mozilla.org/news/."
+ },
+ "utm_campaign": {
+ "type": "string",
+ "description": "(fxa) Value to pass through to GA as utm_campaign."
+ },
+ "utm_term": {
+ "type": "string",
+ "description": "(fxa) Value to pass through to GA as utm_term."
+ },
+ "links": {
+ "additionalProperties": {
+ "url": {
+ "allOf": [
+ {"$ref": "#/definitions/link_url"},
+ {"description": "The url where the link points to."}
+ ]
+ },
+ "metric": {
+ "type": "string",
+ "description": "Custom event name sent with telemetry event."
+ }
+ }
+ }
+ },
+ "additionalProperties": false,
+ "required": ["scene1_text", "scene2_text", "scene1_button_label"],
+ "dependencies": {
+ "scene1_button_color": ["scene1_button_label"],
+ "scene1_button_background_color": ["scene1_button_label"]
+ }
+}
diff --git a/browser/components/newtab/content-src/asrouter/templates/SubmitFormSnippet/_SubmitFormSnippet.scss b/browser/components/newtab/content-src/asrouter/templates/SubmitFormSnippet/_SubmitFormSnippet.scss
new file mode 100644
index 0000000000..286366c12b
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/SubmitFormSnippet/_SubmitFormSnippet.scss
@@ -0,0 +1,176 @@
+.SubmitFormSnippet {
+ flex-direction: column;
+ flex: 1 1 100%;
+ width: 100%;
+
+ .disclaimerText {
+ margin: 5px 0 0;
+ font-size: 12px;
+ color: var(--newtab-text-secondary-color);
+ }
+
+ p {
+ margin: 0;
+ }
+
+ &.send_to_device_snippet {
+ text-align: center;
+
+ .message {
+ font-size: 16px;
+ margin-bottom: 20px;
+ }
+
+ .scene2Title {
+ font-size: 24px;
+ display: block;
+ }
+ }
+
+ .ASRouterButton {
+ &.primary {
+ flex: 1 1 0;
+ }
+ }
+
+ .scene2Icon {
+ width: 100%;
+ margin-bottom: 20px;
+
+ img {
+ width: 98px;
+ display: inline-block;
+ }
+ }
+
+ .scene2Title {
+ font-size: inherit;
+ margin: 0 0 10px;
+ font-weight: bold;
+ display: inline;
+ }
+
+ form {
+ display: flex;
+ flex-direction: column;
+ width: 100%;
+ }
+
+ .message {
+ font-size: 14px;
+ align-self: stretch;
+ flex: 0 0 100%;
+ margin-bottom: 10px;
+ }
+
+ .privacyNotice {
+ font-size: 12px;
+ color: var(--newtab-text-secondary-color);
+ margin-top: 10px;
+ display: flex;
+ flex: 0 0 100%;
+ }
+
+ .innerWrapper {
+ // https://github.com/mozmeao/snippets/blob/2054899350590adcb3c0b0a341c782b0e2f81d0b/activity-stream/newsletter-subscribe.html#L46
+ max-width: 736px;
+ flex-wrap: wrap;
+ justify-items: center;
+ padding-top: 40px;
+ padding-bottom: 40px;
+ }
+
+ .footer {
+ width: 100%;
+ margin: 0 auto;
+ text-align: right;
+ background-color: var(--newtab-background-color);
+ padding: 10px 0;
+
+ .footer-content {
+ margin: 0 auto;
+ max-width: 768px;
+ width: 100%;
+ text-align: right;
+
+ [dir='rtl'] & {
+ text-align: left;
+ }
+ }
+ }
+
+ input {
+ &.mainInput {
+ border-radius: 2px;
+ background-color: var(--newtab-textbox-background-color);
+ border: $input-border;
+ padding: 0 8px;
+ height: 100%;
+ font-size: 14px;
+ width: 50%;
+
+ &.clean {
+ &:invalid,
+ &:required {
+ box-shadow: none;
+ }
+ }
+
+ &:focus {
+ border: $input-border-active;
+ box-shadow: var(--newtab-textbox-focus-boxshadow);
+ }
+ }
+ }
+
+ &.scene2Alt {
+ text-align: start;
+
+ .scene2Icon {
+ flex: 1;
+ margin-bottom: 0;
+ }
+
+ .message {
+ flex: 5;
+ margin-bottom: 0;
+
+ p {
+ margin-bottom: 10px;
+ }
+ }
+
+ .section-header {
+ width: 100%;
+
+ .icon {
+ width: 16px;
+ height: 16px;
+ }
+ }
+
+ .section-title {
+ font-size: 13px;
+ }
+
+ .section-title a {
+ color: var(--newtab-section-header-text-color);
+ font-weight: inherit;
+ text-decoration: none;
+ }
+
+ .innerWrapper {
+ padding: 0 0 16px;
+ }
+ }
+}
+
+.submissionStatus {
+ text-align: center;
+ font-size: 14px;
+ padding: 20px 0;
+
+ .submitStatusTitle {
+ font-size: 20px;
+ }
+}
diff --git a/browser/components/newtab/content-src/asrouter/templates/template-manifest.jsx b/browser/components/newtab/content-src/asrouter/templates/template-manifest.jsx
new file mode 100644
index 0000000000..57f8afa6f5
--- /dev/null
+++ b/browser/components/newtab/content-src/asrouter/templates/template-manifest.jsx
@@ -0,0 +1,24 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { EOYSnippet } from "./EOYSnippet/EOYSnippet";
+import { FXASignupSnippet } from "./FXASignupSnippet/FXASignupSnippet";
+import { NewsletterSnippet } from "./NewsletterSnippet/NewsletterSnippet";
+import {
+ SendToDeviceSnippet,
+ SendToDeviceScene2Snippet,
+} from "./SendToDeviceSnippet/SendToDeviceSnippet";
+import { SimpleBelowSearchSnippet } from "./SimpleBelowSearchSnippet/SimpleBelowSearchSnippet";
+import { SimpleSnippet } from "./SimpleSnippet/SimpleSnippet";
+
+// Key names matching schema name of templates
+export const SnippetsTemplates = {
+ simple_snippet: SimpleSnippet,
+ newsletter_snippet: NewsletterSnippet,
+ fxa_signup_snippet: FXASignupSnippet,
+ send_to_device_snippet: SendToDeviceSnippet,
+ send_to_device_scene2_snippet: SendToDeviceScene2Snippet,
+ eoy_snippet: EOYSnippet,
+ simple_below_search_snippet: SimpleBelowSearchSnippet,
+};
diff --git a/browser/components/newtab/content-src/components/A11yLinkButton/A11yLinkButton.jsx b/browser/components/newtab/content-src/components/A11yLinkButton/A11yLinkButton.jsx
new file mode 100644
index 0000000000..3aab52cdff
--- /dev/null
+++ b/browser/components/newtab/content-src/components/A11yLinkButton/A11yLinkButton.jsx
@@ -0,0 +1,18 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import React from "react";
+
+export function A11yLinkButton(props) {
+ // function for merging classes, if necessary
+ let className = "a11y-link-button";
+ if (props.className) {
+ className += ` ${props.className}`;
+ }
+ return (
+ <button type="button" {...props} className={className}>
+ {props.children}
+ </button>
+ );
+}
diff --git a/browser/components/newtab/content-src/components/A11yLinkButton/_A11yLinkButton.scss b/browser/components/newtab/content-src/components/A11yLinkButton/_A11yLinkButton.scss
new file mode 100644
index 0000000000..622e5a2b7b
--- /dev/null
+++ b/browser/components/newtab/content-src/components/A11yLinkButton/_A11yLinkButton.scss
@@ -0,0 +1,13 @@
+
+.a11y-link-button {
+ border: 0;
+ padding: 0;
+ cursor: pointer;
+ text-align: unset;
+ color: var(--newtab-link-primary-color);
+
+ &:hover,
+ &:focus {
+ text-decoration: underline;
+ }
+}
diff --git a/browser/components/newtab/content-src/components/ASRouterAdmin/ASRouterAdmin.jsx b/browser/components/newtab/content-src/components/ASRouterAdmin/ASRouterAdmin.jsx
new file mode 100644
index 0000000000..e0d8e45cc0
--- /dev/null
+++ b/browser/components/newtab/content-src/components/ASRouterAdmin/ASRouterAdmin.jsx
@@ -0,0 +1,1936 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { actionCreators as ac, actionTypes as at } from "common/Actions.jsm";
+import { ASRouterUtils } from "../../asrouter/asrouter-utils";
+import { connect } from "react-redux";
+import React from "react";
+import { SimpleHashRouter } from "./SimpleHashRouter";
+
+const Row = props => (
+ <tr className="message-item" {...props}>
+ {props.children}
+ </tr>
+);
+
+function relativeTime(timestamp) {
+ if (!timestamp) {
+ return "";
+ }
+ const seconds = Math.floor((Date.now() - timestamp) / 1000);
+ const minutes = Math.floor((Date.now() - timestamp) / 60000);
+ if (seconds < 2) {
+ return "just now";
+ } else if (seconds < 60) {
+ return `${seconds} seconds ago`;
+ } else if (minutes === 1) {
+ return "1 minute ago";
+ } else if (minutes < 600) {
+ return `${minutes} minutes ago`;
+ }
+ return new Date(timestamp).toLocaleString();
+}
+
+const LAYOUT_VARIANTS = {
+ basic: "Basic default layout (on by default in nightly)",
+ staging_spocs: "A layout with all spocs shown",
+ "dev-test-all":
+ "A little bit of everything. Good layout for testing all components",
+ "dev-test-feeds": "Stress testing for slow feeds",
+};
+
+export class ToggleStoryButton extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.handleClick = this.handleClick.bind(this);
+ }
+
+ handleClick() {
+ this.props.onClick(this.props.story);
+ }
+
+ render() {
+ return <button onClick={this.handleClick}>collapse/open</button>;
+ }
+}
+
+export class ToggleMessageJSON extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.handleClick = this.handleClick.bind(this);
+ }
+
+ handleClick() {
+ this.props.toggleJSON(this.props.msgId);
+ }
+
+ render() {
+ let iconName = this.props.isCollapsed
+ ? "icon icon-arrowhead-forward-small"
+ : "icon icon-arrowhead-down-small";
+ return (
+ <button className="clearButton" onClick={this.handleClick}>
+ <span className={iconName} />
+ </button>
+ );
+ }
+}
+
+export class TogglePrefCheckbox extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onChange = this.onChange.bind(this);
+ }
+
+ onChange(event) {
+ this.props.onChange(this.props.pref, event.target.checked);
+ }
+
+ render() {
+ return (
+ <>
+ <input
+ type="checkbox"
+ checked={this.props.checked}
+ onChange={this.onChange}
+ disabled={this.props.disabled}
+ />{" "}
+ {this.props.pref}{" "}
+ </>
+ );
+ }
+}
+
+export class Personalization extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.togglePersonalizationVersion = this.togglePersonalizationVersion.bind(
+ this
+ );
+ }
+
+ togglePersonalizationVersion() {
+ this.props.dispatch(
+ ac.OnlyToMain({
+ type: at.DISCOVERY_STREAM_PERSONALIZATION_VERSION_TOGGLE,
+ })
+ );
+ }
+
+ render() {
+ const {
+ lastUpdated,
+ version,
+ initialized,
+ } = this.props.state.Personalization;
+ return (
+ <React.Fragment>
+ <button className="button" onClick={this.togglePersonalizationVersion}>
+ {version === 1
+ ? "Enable V2 Personalization"
+ : "Enable V1 Personalization"}
+ </button>
+ <table>
+ <tbody>
+ <Row>
+ <td className="min">Personalization version</td>
+ <td>{version}</td>
+ </Row>
+ <Row>
+ <td className="min">Personalization Last Updated</td>
+ <td>{relativeTime(lastUpdated) || "(no data)"}</td>
+ </Row>
+ {version === 2 ? (
+ <Row>
+ <td className="min">Personalization V2 Initialized</td>
+ <td>{initialized ? "true" : "false"}</td>
+ </Row>
+ ) : null}
+ </tbody>
+ </table>
+ </React.Fragment>
+ );
+ }
+}
+
+export class DiscoveryStreamAdmin extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.restorePrefDefaults = this.restorePrefDefaults.bind(this);
+ this.setConfigValue = this.setConfigValue.bind(this);
+ this.expireCache = this.expireCache.bind(this);
+ this.refreshCache = this.refreshCache.bind(this);
+ this.idleDaily = this.idleDaily.bind(this);
+ this.systemTick = this.systemTick.bind(this);
+ this.syncRemoteSettings = this.syncRemoteSettings.bind(this);
+ this.changeEndpointVariant = this.changeEndpointVariant.bind(this);
+ this.onStoryToggle = this.onStoryToggle.bind(this);
+ this.state = {
+ toggledStories: {},
+ };
+ }
+
+ setConfigValue(name, value) {
+ this.props.dispatch(
+ ac.OnlyToMain({
+ type: at.DISCOVERY_STREAM_CONFIG_SET_VALUE,
+ data: { name, value },
+ })
+ );
+ }
+
+ restorePrefDefaults(event) {
+ this.props.dispatch(
+ ac.OnlyToMain({
+ type: at.DISCOVERY_STREAM_CONFIG_RESET_DEFAULTS,
+ })
+ );
+ }
+
+ refreshCache() {
+ const { config } = this.props.state.DiscoveryStream;
+ this.props.dispatch(
+ ac.OnlyToMain({
+ type: at.DISCOVERY_STREAM_CONFIG_CHANGE,
+ data: config,
+ })
+ );
+ }
+
+ dispatchSimpleAction(type) {
+ this.props.dispatch(
+ ac.OnlyToMain({
+ type,
+ })
+ );
+ }
+
+ systemTick() {
+ this.dispatchSimpleAction(at.DISCOVERY_STREAM_DEV_SYSTEM_TICK);
+ }
+
+ expireCache() {
+ this.dispatchSimpleAction(at.DISCOVERY_STREAM_DEV_EXPIRE_CACHE);
+ }
+
+ idleDaily() {
+ this.dispatchSimpleAction(at.DISCOVERY_STREAM_DEV_IDLE_DAILY);
+ }
+
+ syncRemoteSettings() {
+ this.dispatchSimpleAction(at.DISCOVERY_STREAM_DEV_SYNC_RS);
+ }
+
+ changeEndpointVariant(event) {
+ const endpoint = this.props.state.DiscoveryStream.config.layout_endpoint;
+ if (endpoint) {
+ this.setConfigValue(
+ "layout_endpoint",
+ endpoint.replace(
+ /layout_variant=.+/,
+ `layout_variant=${event.target.value}`
+ )
+ );
+ }
+ }
+
+ renderComponent(width, component) {
+ return (
+ <table>
+ <tbody>
+ <Row>
+ <td className="min">Type</td>
+ <td>{component.type}</td>
+ </Row>
+ <Row>
+ <td className="min">Width</td>
+ <td>{width}</td>
+ </Row>
+ {component.feed && this.renderFeed(component.feed)}
+ </tbody>
+ </table>
+ );
+ }
+
+ isCurrentVariant(id) {
+ const endpoint = this.props.state.DiscoveryStream.config.layout_endpoint;
+ const isMatch = endpoint && !!endpoint.match(`layout_variant=${id}`);
+ return isMatch;
+ }
+
+ renderFeedData(url) {
+ const { feeds } = this.props.state.DiscoveryStream;
+ const feed = feeds.data[url].data;
+ return (
+ <React.Fragment>
+ <h4>Feed url: {url}</h4>
+ <table>
+ <tbody>
+ {feed.recommendations.map(story => this.renderStoryData(story))}
+ </tbody>
+ </table>
+ </React.Fragment>
+ );
+ }
+
+ renderFeedsData() {
+ const { feeds } = this.props.state.DiscoveryStream;
+ return (
+ <React.Fragment>
+ {Object.keys(feeds.data).map(url => this.renderFeedData(url))}
+ </React.Fragment>
+ );
+ }
+
+ renderSpocs() {
+ const { spocs } = this.props.state.DiscoveryStream;
+ let spocsData = [];
+ if (spocs.data && spocs.data.spocs && spocs.data.spocs.items) {
+ spocsData = spocs.data.spocs.items || [];
+ }
+
+ return (
+ <React.Fragment>
+ <table>
+ <tbody>
+ <Row>
+ <td className="min">spocs_endpoint</td>
+ <td>{spocs.spocs_endpoint}</td>
+ </Row>
+ <Row>
+ <td className="min">Data last fetched</td>
+ <td>{relativeTime(spocs.lastUpdated)}</td>
+ </Row>
+ </tbody>
+ </table>
+ <h4>Spoc data</h4>
+ <table>
+ <tbody>{spocsData.map(spoc => this.renderStoryData(spoc))}</tbody>
+ </table>
+ <h4>Spoc frequency caps</h4>
+ <table>
+ <tbody>
+ {spocs.frequency_caps.map(spoc => this.renderStoryData(spoc))}
+ </tbody>
+ </table>
+ </React.Fragment>
+ );
+ }
+
+ onStoryToggle(story) {
+ const { toggledStories } = this.state;
+ this.setState({
+ toggledStories: {
+ ...toggledStories,
+ [story.id]: !toggledStories[story.id],
+ },
+ });
+ }
+
+ renderStoryData(story) {
+ let storyData = "";
+ if (this.state.toggledStories[story.id]) {
+ storyData = JSON.stringify(story, null, 2);
+ }
+ return (
+ <tr className="message-item" key={story.id}>
+ <td className="message-id">
+ <span>
+ {story.id} <br />
+ </span>
+ <ToggleStoryButton story={story} onClick={this.onStoryToggle} />
+ </td>
+ <td className="message-summary">
+ <pre>{storyData}</pre>
+ </td>
+ </tr>
+ );
+ }
+
+ renderFeed(feed) {
+ const { feeds } = this.props.state.DiscoveryStream;
+ if (!feed.url) {
+ return null;
+ }
+ return (
+ <React.Fragment>
+ <Row>
+ <td className="min">Feed url</td>
+ <td>{feed.url}</td>
+ </Row>
+ <Row>
+ <td className="min">Data last fetched</td>
+ <td>
+ {relativeTime(
+ feeds.data[feed.url] ? feeds.data[feed.url].lastUpdated : null
+ ) || "(no data)"}
+ </td>
+ </Row>
+ </React.Fragment>
+ );
+ }
+
+ render() {
+ const prefToggles = "enabled hardcoded_layout show_spocs personalized collapsible".split(
+ " "
+ );
+ const { config, lastUpdated, layout } = this.props.state.DiscoveryStream;
+ return (
+ <div>
+ <button className="button" onClick={this.restorePrefDefaults}>
+ Restore Pref Defaults
+ </button>{" "}
+ <button className="button" onClick={this.refreshCache}>
+ Refresh Cache
+ </button>
+ <br />
+ <button className="button" onClick={this.expireCache}>
+ Expire Cache
+ </button>{" "}
+ <button className="button" onClick={this.systemTick}>
+ Trigger System Tick
+ </button>{" "}
+ <button className="button" onClick={this.idleDaily}>
+ Trigger Idle Daily
+ </button>
+ <br />
+ <button className="button" onClick={this.syncRemoteSettings}>
+ Sync Remote Settings
+ </button>
+ <table>
+ <tbody>
+ {prefToggles.map(pref => (
+ <Row key={pref}>
+ <td>
+ <TogglePrefCheckbox
+ checked={config[pref]}
+ pref={pref}
+ onChange={this.setConfigValue}
+ />
+ </td>
+ </Row>
+ ))}
+ </tbody>
+ </table>
+ <h3>Endpoint variant</h3>
+ <p>
+ You can also change this manually by changing this pref:{" "}
+ <code>browser.newtabpage.activity-stream.discoverystream.config</code>
+ </p>
+ <table
+ style={
+ config.enabled && !config.hardcoded_layout ? null : { opacity: 0.5 }
+ }
+ >
+ <tbody>
+ {Object.keys(LAYOUT_VARIANTS).map(id => (
+ <Row key={id}>
+ <td className="min">
+ <input
+ type="radio"
+ value={id}
+ checked={this.isCurrentVariant(id)}
+ onChange={this.changeEndpointVariant}
+ />
+ </td>
+ <td className="min">{id}</td>
+ <td>{LAYOUT_VARIANTS[id]}</td>
+ </Row>
+ ))}
+ </tbody>
+ </table>
+ <h3>Caching info</h3>
+ <table style={config.enabled ? null : { opacity: 0.5 }}>
+ <tbody>
+ <Row>
+ <td className="min">Data last fetched</td>
+ <td>{relativeTime(lastUpdated) || "(no data)"}</td>
+ </Row>
+ </tbody>
+ </table>
+ <h3>Layout</h3>
+ {layout.map((row, rowIndex) => (
+ <div key={`row-${rowIndex}`}>
+ {row.components.map((component, componentIndex) => (
+ <div key={`component-${componentIndex}`} className="ds-component">
+ {this.renderComponent(row.width, component)}
+ </div>
+ ))}
+ </div>
+ ))}
+ <h3>Personalization</h3>
+ <Personalization
+ dispatch={this.props.dispatch}
+ state={{
+ Personalization: this.props.state.Personalization,
+ }}
+ />
+ <h3>Spocs</h3>
+ {this.renderSpocs()}
+ <h3>Feeds Data</h3>
+ {this.renderFeedsData()}
+ </div>
+ );
+ }
+}
+
+export class ASRouterAdminInner extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.handleEnabledToggle = this.handleEnabledToggle.bind(this);
+ this.handleUserPrefToggle = this.handleUserPrefToggle.bind(this);
+ this.onChangeMessageFilter = this.onChangeMessageFilter.bind(this);
+ this.onChangeMessageGroupsFilter = this.onChangeMessageGroupsFilter.bind(
+ this
+ );
+ this.unblockAll = this.unblockAll.bind(this);
+ this.handleClearAllImpressionsByProvider = this.handleClearAllImpressionsByProvider.bind(
+ this
+ );
+ this.handleExpressionEval = this.handleExpressionEval.bind(this);
+ this.onChangeTargetingParameters = this.onChangeTargetingParameters.bind(
+ this
+ );
+ this.onChangeAttributionParameters = this.onChangeAttributionParameters.bind(
+ this
+ );
+ this.setAttribution = this.setAttribution.bind(this);
+ this.onCopyTargetingParams = this.onCopyTargetingParams.bind(this);
+ this.onNewTargetingParams = this.onNewTargetingParams.bind(this);
+ this.handleUpdateWNMessages = this.handleUpdateWNMessages.bind(this);
+ this.handleForceWNP = this.handleForceWNP.bind(this);
+ this.handleCloseWNP = this.handleCloseWNP.bind(this);
+ this.resetPanel = this.resetPanel.bind(this);
+ this.restoreWNMessageState = this.restoreWNMessageState.bind(this);
+ this.toggleJSON = this.toggleJSON.bind(this);
+ this.toggleAllMessages = this.toggleAllMessages.bind(this);
+ this.resetGroups = this.resetGroups.bind(this);
+ this.onMessageFromParent = this.onMessageFromParent.bind(this);
+ this.setStateFromParent = this.setStateFromParent.bind(this);
+ this.setState = this.setState.bind(this);
+ this.state = {
+ messageFilter: "all",
+ messageGroupsFilter: "all",
+ WNMessages: [],
+ collapsedMessages: [],
+ modifiedMessages: [],
+ evaluationStatus: {},
+ stringTargetingParameters: null,
+ newStringTargetingParameters: null,
+ copiedToClipboard: false,
+ attributionParameters: {
+ source: "addons.mozilla.org",
+ medium: "referral",
+ campaign: "non-fx-button",
+ content: "iridium@particlecore.github.io",
+ experiment: "ua-onboarding",
+ variation: "chrome",
+ ua: "Google Chrome 123",
+ dltoken: "00000000-0000-0000-0000-000000000000",
+ },
+ };
+ }
+
+ onMessageFromParent({ type, data }) {
+ // These only exists due to onPrefChange events in ASRouter
+ switch (type) {
+ case "UpdateAdminState": {
+ this.setStateFromParent(data);
+ break;
+ }
+ }
+ }
+
+ setStateFromParent(data) {
+ this.setState(data);
+ if (!this.state.stringTargetingParameters) {
+ const stringTargetingParameters = {};
+ for (const param of Object.keys(data.targetingParameters)) {
+ stringTargetingParameters[param] = JSON.stringify(
+ data.targetingParameters[param],
+ null,
+ 2
+ );
+ }
+ this.setState({ stringTargetingParameters });
+ }
+ }
+
+ componentWillMount() {
+ ASRouterUtils.addListener(this.onMessageFromParent);
+ const endpoint = ASRouterUtils.getPreviewEndpoint();
+ ASRouterUtils.sendMessage({
+ type: "ADMIN_CONNECT_STATE",
+ data: { endpoint },
+ }).then(this.setStateFromParent);
+ }
+
+ handleBlock(msg) {
+ return () => ASRouterUtils.blockById(msg.id);
+ }
+
+ handleUnblock(msg) {
+ return () => ASRouterUtils.unblockById(msg.id);
+ }
+
+ resetJSON(msg) {
+ // reset the displayed JSON for the given message
+ document.getElementById(`${msg.id}-textarea`).value = JSON.stringify(
+ msg,
+ null,
+ 2
+ );
+ // remove the message from the list of modified IDs
+ let index = this.state.modifiedMessages.indexOf(msg.id);
+ this.setState(prevState => ({
+ modifiedMessages: [
+ ...prevState.modifiedMessages.slice(0, index),
+ ...prevState.modifiedMessages.slice(index + 1),
+ ],
+ }));
+ }
+
+ resetAllJSON() {
+ let messageCheckboxes = document.querySelectorAll('input[type="checkbox"]');
+
+ for (const checkbox of messageCheckboxes) {
+ let trimmedId = checkbox.id.replace(" checkbox", "");
+
+ let message = this.state.messages.filter(msg => msg.id === trimmedId);
+ let msgId = message[0].id;
+
+ document.getElementById(`${msgId}-textarea`).value = JSON.stringify(
+ message[0],
+ null,
+ 2
+ );
+ }
+ this.setState({
+ WNMessages: [],
+ });
+ }
+
+ resetPanel() {
+ this.resetAllJSON();
+ this.handleCloseWNP();
+ }
+
+ handleOverride(id) {
+ return () =>
+ ASRouterUtils.overrideMessage(id).then(state => {
+ this.setStateFromParent(state);
+ this.props.notifyContent({
+ message: state.message,
+ });
+ });
+ }
+
+ async handleUpdateWNMessages() {
+ await this.restoreWNMessageState();
+ let messages = this.state.WNMessages;
+
+ for (const msg of messages) {
+ ASRouterUtils.modifyMessageJson(JSON.parse(msg));
+ }
+ }
+
+ handleForceWNP() {
+ ASRouterUtils.sendMessage({ type: "FORCE_WHATSNEW_PANEL" });
+ }
+
+ handleCloseWNP() {
+ ASRouterUtils.sendMessage({ type: "CLOSE_WHATSNEW_PANEL" });
+ }
+
+ expireCache() {
+ ASRouterUtils.sendMessage({ type: "EXPIRE_QUERY_CACHE" });
+ }
+
+ resetPref() {
+ ASRouterUtils.sendMessage({ type: "RESET_PROVIDER_PREF" });
+ }
+
+ resetGroups(id, value) {
+ ASRouterUtils.sendMessage({
+ type: "RESET_GROUPS_STATE",
+ }).then(this.setStateFromParent);
+ }
+
+ handleExpressionEval() {
+ const context = {};
+ for (const param of Object.keys(this.state.stringTargetingParameters)) {
+ const value = this.state.stringTargetingParameters[param];
+ context[param] = value ? JSON.parse(value) : null;
+ }
+ ASRouterUtils.sendMessage({
+ type: "EVALUATE_JEXL_EXPRESSION",
+ data: {
+ expression: this.refs.expressionInput.value,
+ context,
+ },
+ }).then(this.setStateFromParent);
+ }
+
+ onChangeTargetingParameters(event) {
+ const { name } = event.target;
+ const { value } = event.target;
+
+ this.setState(({ stringTargetingParameters }) => {
+ let targetingParametersError = null;
+ const updatedParameters = { ...stringTargetingParameters };
+ updatedParameters[name] = value;
+ try {
+ JSON.parse(value);
+ } catch (e) {
+ console.log(`Error parsing value of parameter ${name}`); // eslint-disable-line no-console
+ targetingParametersError = { id: name };
+ }
+
+ return {
+ copiedToClipboard: false,
+ evaluationStatus: {},
+ stringTargetingParameters: updatedParameters,
+ targetingParametersError,
+ };
+ });
+ }
+
+ unblockAll() {
+ return ASRouterUtils.sendMessage({
+ type: "UNBLOCK_ALL",
+ }).then(this.setStateFromParent);
+ }
+
+ handleClearAllImpressionsByProvider() {
+ const providerId = this.state.messageFilter;
+ if (!providerId) {
+ return;
+ }
+ const userPrefInfo = this.state.userPrefs;
+
+ const isUserEnabled =
+ providerId in userPrefInfo ? userPrefInfo[providerId] : true;
+
+ ASRouterUtils.sendMessage({
+ type: "DISABLE_PROVIDER",
+ data: providerId,
+ });
+ if (!isUserEnabled) {
+ ASRouterUtils.sendMessage({
+ type: "SET_PROVIDER_USER_PREF",
+ data: { id: providerId, value: true },
+ });
+ }
+ ASRouterUtils.sendMessage({
+ type: "ENABLE_PROVIDER",
+ data: providerId,
+ });
+ }
+
+ handleEnabledToggle(event) {
+ const provider = this.state.providerPrefs.find(
+ p => p.id === event.target.dataset.provider
+ );
+ const userPrefInfo = this.state.userPrefs;
+
+ const isUserEnabled =
+ provider.id in userPrefInfo ? userPrefInfo[provider.id] : true;
+ const isSystemEnabled = provider.enabled;
+ const isEnabling = event.target.checked;
+
+ if (isEnabling) {
+ if (!isUserEnabled) {
+ ASRouterUtils.sendMessage({
+ type: "SET_PROVIDER_USER_PREF",
+ data: { id: provider.id, value: true },
+ });
+ }
+ if (!isSystemEnabled) {
+ ASRouterUtils.sendMessage({
+ type: "ENABLE_PROVIDER",
+ data: provider.id,
+ });
+ }
+ } else {
+ ASRouterUtils.sendMessage({
+ type: "DISABLE_PROVIDER",
+ data: provider.id,
+ });
+ }
+
+ this.setState({ messageFilter: "all" });
+ }
+
+ handleUserPrefToggle(event) {
+ const action = {
+ type: "SET_PROVIDER_USER_PREF",
+ data: { id: event.target.dataset.provider, value: event.target.checked },
+ };
+ ASRouterUtils.sendMessage(action);
+ this.setState({ messageFilter: "all" });
+ }
+
+ onChangeMessageFilter(event) {
+ this.setState({ messageFilter: event.target.value });
+ }
+
+ onChangeMessageGroupsFilter(event) {
+ this.setState({ messageGroupsFilter: event.target.value });
+ }
+
+ // Simulate a copy event that sets to clipboard all targeting paramters and values
+ onCopyTargetingParams(event) {
+ const stringTargetingParameters = {
+ ...this.state.stringTargetingParameters,
+ };
+ for (const key of Object.keys(stringTargetingParameters)) {
+ // If the value is not set the parameter will be lost when we stringify
+ if (stringTargetingParameters[key] === undefined) {
+ stringTargetingParameters[key] = null;
+ }
+ }
+ const setClipboardData = e => {
+ e.preventDefault();
+ e.clipboardData.setData(
+ "text",
+ JSON.stringify(stringTargetingParameters, null, 2)
+ );
+ document.removeEventListener("copy", setClipboardData);
+ this.setState({ copiedToClipboard: true });
+ };
+
+ document.addEventListener("copy", setClipboardData);
+
+ document.execCommand("copy");
+ }
+
+ onNewTargetingParams(event) {
+ this.setState({ newStringTargetingParameters: event.target.value });
+ event.target.classList.remove("errorState");
+ this.refs.targetingParamsEval.innerText = "";
+
+ try {
+ const stringTargetingParameters = JSON.parse(event.target.value);
+ this.setState({ stringTargetingParameters });
+ } catch (e) {
+ event.target.classList.add("errorState");
+ this.refs.targetingParamsEval.innerText = e.message;
+ }
+ }
+
+ toggleJSON(msgId) {
+ if (this.state.collapsedMessages.includes(msgId)) {
+ let index = this.state.collapsedMessages.indexOf(msgId);
+ this.setState(prevState => ({
+ collapsedMessages: [
+ ...prevState.collapsedMessages.slice(0, index),
+ ...prevState.collapsedMessages.slice(index + 1),
+ ],
+ }));
+ } else {
+ this.setState(prevState => ({
+ collapsedMessages: prevState.collapsedMessages.concat(msgId),
+ }));
+ }
+ }
+
+ handleChange(msgId) {
+ if (!this.state.modifiedMessages.includes(msgId)) {
+ this.setState(prevState => ({
+ modifiedMessages: prevState.modifiedMessages.concat(msgId),
+ }));
+ }
+ }
+
+ renderMessageItem(msg) {
+ const isBlockedByGroup = this.state.groups
+ .filter(group => msg.groups.includes(group.id))
+ .some(group => !group.enabled);
+ const msgProvider =
+ this.state.providers.find(provider => provider.id === msg.provider) || {};
+ const isProviderExcluded =
+ msgProvider.exclude && msgProvider.exclude.includes(msg.id);
+ const isMessageBlocked =
+ this.state.messageBlockList.includes(msg.id) ||
+ this.state.messageBlockList.includes(msg.campaign);
+ const isBlocked =
+ isMessageBlocked || isBlockedByGroup || isProviderExcluded;
+ const impressions = this.state.messageImpressions[msg.id]
+ ? this.state.messageImpressions[msg.id].length
+ : 0;
+ const isCollapsed = this.state.collapsedMessages.includes(msg.id);
+ const isModified = this.state.modifiedMessages.includes(msg.id);
+
+ let itemClassName = "message-item";
+ if (isBlocked) {
+ itemClassName += " blocked";
+ }
+
+ return (
+ <tr className={itemClassName} key={`${msg.id}-${msg.provider}`}>
+ <td className="message-id">
+ <span>
+ {msg.id} <br />
+ </span>
+ </td>
+ <td>
+ <ToggleMessageJSON
+ msgId={`${msg.id}`}
+ toggleJSON={this.toggleJSON}
+ isCollapsed={isCollapsed}
+ />
+ </td>
+ <td className="button-column">
+ <button
+ className={`button ${isBlocked ? "" : " primary"}`}
+ onClick={
+ isBlocked ? this.handleUnblock(msg) : this.handleBlock(msg)
+ }
+ >
+ {isBlocked ? "Unblock" : "Block"}
+ </button>
+ {// eslint-disable-next-line no-nested-ternary
+ isBlocked ? null : isModified ? (
+ <button
+ className="button restore"
+ // eslint-disable-next-line react/jsx-no-bind
+ onClick={e => this.resetJSON(msg)}
+ >
+ Reset
+ </button>
+ ) : (
+ <button
+ className="button show"
+ onClick={this.handleOverride(msg.id)}
+ >
+ Show
+ </button>
+ )}
+ {isBlocked ? null : (
+ <button
+ className="button modify"
+ // eslint-disable-next-line react/jsx-no-bind
+ onClick={e => this.modifyJson(msg)}
+ >
+ Modify
+ </button>
+ )}
+ <br />({impressions} impressions)
+ </td>
+ <td className="message-summary">
+ {isBlocked && (
+ <tr>
+ Block reason:
+ {isBlockedByGroup && " Blocked by group"}
+ {isProviderExcluded && " Excluded by provider"}
+ {isMessageBlocked && " Message blocked"}
+ </tr>
+ )}
+ <tr>
+ <pre className={isCollapsed ? "collapsed" : "expanded"}>
+ <textarea
+ id={`${msg.id}-textarea`}
+ name={msg.id}
+ className="general-textarea"
+ disabled={isBlocked}
+ // eslint-disable-next-line react/jsx-no-bind
+ onChange={e => this.handleChange(msg.id)}
+ >
+ {JSON.stringify(msg, null, 2)}
+ </textarea>
+ </pre>
+ </tr>
+ </td>
+ </tr>
+ );
+ }
+
+ restoreWNMessageState() {
+ // check the page for checked boxes, and reset the state of WNMessages based on that.
+ let tempState = [];
+ let messageCheckboxes = document.querySelectorAll('input[type="checkbox"]');
+ // put the JSON of all the checked checkboxes in the array
+ for (const checkbox of messageCheckboxes) {
+ let trimmedId = checkbox.id.replace(" checkbox", "");
+ let msg = document.getElementById(`${trimmedId}-textarea`).value;
+
+ if (checkbox.checked) {
+ tempState.push(msg);
+ }
+ }
+
+ this.setState({
+ WNMessages: tempState,
+ });
+ }
+
+ modifyJson(content) {
+ const message = JSON.parse(
+ document.getElementById(`${content.id}-textarea`).value
+ );
+ return ASRouterUtils.modifyMessageJson(message).then(state => {
+ this.setStateFromParent(state);
+ this.props.notifyContent({
+ message: state.message,
+ });
+ });
+ }
+
+ renderWNMessageItem(msg) {
+ const isBlocked =
+ this.state.messageBlockList.includes(msg.id) ||
+ this.state.messageBlockList.includes(msg.campaign);
+ const impressions = this.state.messageImpressions[msg.id]
+ ? this.state.messageImpressions[msg.id].length
+ : 0;
+
+ const isCollapsed = this.state.collapsedMessages.includes(msg.id);
+
+ let itemClassName = "message-item";
+ if (isBlocked) {
+ itemClassName += " blocked";
+ }
+
+ return (
+ <tr className={itemClassName} key={`${msg.id}-${msg.provider}`}>
+ <td className="message-id">
+ <span>
+ {msg.id} <br />
+ <br />({impressions} impressions)
+ </span>
+ </td>
+ <td>
+ <ToggleMessageJSON
+ msgId={`${msg.id}`}
+ toggleJSON={this.toggleJSON}
+ isCollapsed={isCollapsed}
+ />
+ </td>
+ <td>
+ <input
+ type="checkbox"
+ id={`${msg.id} checkbox`}
+ name={`${msg.id} checkbox`}
+ />
+ </td>
+ <td className={`message-summary`}>
+ <pre className={isCollapsed ? "collapsed" : "expanded"}>
+ <textarea
+ id={`${msg.id}-textarea`}
+ className="wnp-textarea"
+ name={msg.id}
+ >
+ {JSON.stringify(msg, null, 2)}
+ </textarea>
+ </pre>
+ </td>
+ </tr>
+ );
+ }
+
+ toggleAllMessages(messagesToShow) {
+ if (this.state.collapsedMessages.length) {
+ this.setState({
+ collapsedMessages: [],
+ });
+ } else {
+ Array.prototype.forEach.call(messagesToShow, msg => {
+ this.setState(prevState => ({
+ collapsedMessages: prevState.collapsedMessages.concat(msg.id),
+ }));
+ });
+ }
+ }
+
+ renderMessages() {
+ if (!this.state.messages) {
+ return null;
+ }
+ const messagesToShow =
+ this.state.messageFilter === "all"
+ ? this.state.messages
+ : this.state.messages.filter(
+ message => message.provider === this.state.messageFilter
+ );
+
+ return (
+ <div>
+ <button
+ className="ASRouterButton slim"
+ // eslint-disable-next-line react/jsx-no-bind
+ onClick={e => this.toggleAllMessages(messagesToShow)}
+ >
+ Collapse/Expand All
+ </button>
+ <p className="helpLink">
+ <span className="icon icon-small-spacer icon-info" />{" "}
+ <span>
+ To modify a message, change the JSON and click 'Modify' to see your
+ changes. Click 'Reset' to restore the JSON to the original.
+ </span>
+ </p>
+ <table>
+ <tbody>
+ {messagesToShow.map(msg => this.renderMessageItem(msg))}
+ </tbody>
+ </table>
+ </div>
+ );
+ }
+
+ renderMessagesByGroup() {
+ if (!this.state.messages) {
+ return null;
+ }
+ const messagesToShow =
+ this.state.messageGroupsFilter === "all"
+ ? this.state.messages.filter(m => m.groups.length)
+ : this.state.messages.filter(message =>
+ message.groups.includes(this.state.messageGroupsFilter)
+ );
+
+ return (
+ <table>
+ <tbody>{messagesToShow.map(msg => this.renderMessageItem(msg))}</tbody>
+ </table>
+ );
+ }
+
+ renderWNMessages() {
+ if (!this.state.messages) {
+ return null;
+ }
+ const messagesToShow = this.state.messages.filter(
+ message => message.provider === "whats-new-panel" && message.content.body
+ );
+ return (
+ <table>
+ <tbody>
+ {messagesToShow.map(msg => this.renderWNMessageItem(msg))}
+ </tbody>
+ </table>
+ );
+ }
+
+ renderMessageFilter() {
+ if (!this.state.providers) {
+ return null;
+ }
+
+ return (
+ <p>
+ <button
+ className="unblock-all ASRouterButton test-only"
+ onClick={this.unblockAll}
+ >
+ Unblock All Snippets
+ </button>
+ {/* eslint-disable-next-line prettier/prettier */}
+ Show messages from {/* eslint-disable-next-line jsx-a11y/no-onchange */}
+ <select
+ value={this.state.messageFilter}
+ onChange={this.onChangeMessageFilter}
+ >
+ <option value="all">all providers</option>
+ {this.state.providers.map(provider => (
+ <option key={provider.id} value={provider.id}>
+ {provider.id}
+ </option>
+ ))}
+ </select>
+ {this.state.messageFilter !== "all" &&
+ !this.state.messageFilter.includes("_local_testing") ? (
+ <button
+ className="button messages-reset"
+ onClick={this.handleClearAllImpressionsByProvider}
+ >
+ Reset All
+ </button>
+ ) : null}
+ </p>
+ );
+ }
+
+ renderMessageGroupsFilter() {
+ if (!this.state.groups) {
+ return null;
+ }
+
+ return (
+ <p>
+ Show messages from {/* eslint-disable-next-line jsx-a11y/no-onchange */}
+ <select
+ value={this.state.messageGroupsFilter}
+ onChange={this.onChangeMessageGroupsFilter}
+ >
+ <option value="all">all groups</option>
+ {this.state.groups.map(group => (
+ <option key={group.id} value={group.id}>
+ {group.id}
+ </option>
+ ))}
+ </select>
+ </p>
+ );
+ }
+
+ renderTableHead() {
+ return (
+ <thead>
+ <tr className="message-item">
+ <td className="min" />
+ <td className="min">Provider ID</td>
+ <td>Source</td>
+ <td className="min">Cohort</td>
+ <td className="min">Last Updated</td>
+ </tr>
+ </thead>
+ );
+ }
+
+ renderProviders() {
+ const providersConfig = this.state.providerPrefs;
+ const providerInfo = this.state.providers;
+ const userPrefInfo = this.state.userPrefs;
+
+ return (
+ <table>
+ {this.renderTableHead()}
+ <tbody>
+ {providersConfig.map((provider, i) => {
+ const isTestProvider = provider.id.includes("_local_testing");
+ const info = providerInfo.find(p => p.id === provider.id) || {};
+ const isUserEnabled =
+ provider.id in userPrefInfo ? userPrefInfo[provider.id] : true;
+ const isSystemEnabled = isTestProvider || provider.enabled;
+
+ let label = "local";
+ if (provider.type === "remote") {
+ label = (
+ <span>
+ endpoint (
+ <a
+ className="providerUrl"
+ target="_blank"
+ href={info.url}
+ rel="noopener noreferrer"
+ >
+ {info.url}
+ </a>
+ )
+ </span>
+ );
+ } else if (provider.type === "remote-settings") {
+ label = `remote settings (${provider.bucket})`;
+ } else if (provider.type === "remote-experiments") {
+ label = (
+ <span>
+ remote settings (
+ <a
+ className="providerUrl"
+ target="_blank"
+ href="https://firefox.settings.services.mozilla.com/v1/buckets/main/collections/nimbus-desktop-experiments/records"
+ rel="noopener noreferrer"
+ >
+ nimbus-desktop-experiments
+ </a>
+ )
+ </span>
+ );
+ }
+
+ let reasonsDisabled = [];
+ if (!isSystemEnabled) {
+ reasonsDisabled.push("system pref");
+ }
+ if (!isUserEnabled) {
+ reasonsDisabled.push("user pref");
+ }
+ if (reasonsDisabled.length) {
+ label = `disabled via ${reasonsDisabled.join(", ")}`;
+ }
+
+ return (
+ <tr className="message-item" key={i}>
+ <td>
+ {isTestProvider ? (
+ <input
+ type="checkbox"
+ disabled={true}
+ readOnly={true}
+ checked={true}
+ />
+ ) : (
+ <input
+ type="checkbox"
+ data-provider={provider.id}
+ checked={isUserEnabled && isSystemEnabled}
+ onChange={this.handleEnabledToggle}
+ />
+ )}
+ </td>
+ <td>{provider.id}</td>
+ <td>
+ <span
+ className={`sourceLabel${
+ isUserEnabled && isSystemEnabled ? "" : " isDisabled"
+ }`}
+ >
+ {label}
+ </span>
+ </td>
+ <td>{provider.cohort}</td>
+ <td style={{ whiteSpace: "nowrap" }}>
+ {info.lastUpdated
+ ? new Date(info.lastUpdated).toLocaleString()
+ : ""}
+ </td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ );
+ }
+
+ renderTargetingParameters() {
+ // There was no error and the result is truthy
+ const success =
+ this.state.evaluationStatus.success &&
+ !!this.state.evaluationStatus.result;
+ const result =
+ JSON.stringify(this.state.evaluationStatus.result, null, 2) ||
+ "(Empty result)";
+
+ return (
+ <table>
+ <tbody>
+ <tr>
+ <td>
+ <h2>Evaluate JEXL expression</h2>
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <p>
+ <textarea
+ ref="expressionInput"
+ rows="10"
+ cols="60"
+ placeholder="Evaluate JEXL expressions and mock parameters by changing their values below"
+ />
+ </p>
+ <p>
+ Status:{" "}
+ <span ref="evaluationStatus">
+ {success ? "✅" : "❌"}, Result: {result}
+ </span>
+ </p>
+ </td>
+ <td>
+ <button
+ className="ASRouterButton secondary"
+ onClick={this.handleExpressionEval}
+ >
+ Evaluate
+ </button>
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <h2>Modify targeting parameters</h2>
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <button
+ className="ASRouterButton secondary"
+ onClick={this.onCopyTargetingParams}
+ disabled={this.state.copiedToClipboard}
+ >
+ {this.state.copiedToClipboard
+ ? "Parameters copied!"
+ : "Copy parameters"}
+ </button>
+ </td>
+ </tr>
+ {this.state.stringTargetingParameters &&
+ Object.keys(this.state.stringTargetingParameters).map(
+ (param, i) => {
+ const value = this.state.stringTargetingParameters[param];
+ const errorState =
+ this.state.targetingParametersError &&
+ this.state.targetingParametersError.id === param;
+ const className = errorState ? "errorState" : "";
+ const inputComp =
+ (value && value.length) > 30 ? (
+ <textarea
+ name={param}
+ className={className}
+ value={value}
+ rows="10"
+ cols="60"
+ onChange={this.onChangeTargetingParameters}
+ />
+ ) : (
+ <input
+ name={param}
+ className={className}
+ value={value}
+ onChange={this.onChangeTargetingParameters}
+ />
+ );
+
+ return (
+ <tr key={i}>
+ <td>{param}</td>
+ <td>{inputComp}</td>
+ </tr>
+ );
+ }
+ )}
+ </tbody>
+ </table>
+ );
+ }
+
+ onChangeAttributionParameters(event) {
+ const { name, value } = event.target;
+
+ this.setState(({ attributionParameters }) => {
+ const updatedParameters = { ...attributionParameters };
+ updatedParameters[name] = value;
+
+ return { attributionParameters: updatedParameters };
+ });
+ }
+
+ setAttribution(e) {
+ ASRouterUtils.sendMessage({
+ type: "FORCE_ATTRIBUTION",
+ data: this.state.attributionParameters,
+ }).then(this.setStateFromParent);
+ }
+
+ _getGroupImpressionsCount(id, frequency) {
+ if (frequency) {
+ return this.state.groupImpressions[id]
+ ? this.state.groupImpressions[id].length
+ : 0;
+ }
+
+ return "n/a";
+ }
+
+ renderDiscoveryStream() {
+ const { config } = this.props.DiscoveryStream;
+
+ return (
+ <div>
+ <table>
+ <tbody>
+ <tr className="message-item">
+ <td className="min">Enabled</td>
+ <td>{config.enabled ? "yes" : "no"}</td>
+ </tr>
+ <tr className="message-item">
+ <td className="min">Endpoint</td>
+ <td>{config.endpoint || "(empty)"}</td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ );
+ }
+
+ renderAttributionParamers() {
+ return (
+ <div>
+ <h2> Attribution Parameters </h2>
+ <p>
+ {" "}
+ This forces the browser to set some attribution parameters, useful for
+ testing the Return To AMO feature. Clicking on 'Force Attribution',
+ with the default values in each field, will demo the Return To AMO
+ flow with the addon called 'Iridium for Youtube'. If you wish to try
+ different attribution parameters, enter them in the text boxes. If you
+ wish to try a different addon with the Return To AMO flow, make sure
+ the 'content' text box has the addon GUID, then click 'Force
+ Attribution'. Clicking on 'Force Attribution' with blank text boxes
+ reset attribution data.
+ </p>
+ <table>
+ <tr>
+ <td>
+ <b> Source </b>
+ </td>
+ <td>
+ {" "}
+ <input
+ type="text"
+ name="source"
+ placeholder="addons.mozilla.org"
+ value={this.state.attributionParameters.source}
+ onChange={this.onChangeAttributionParameters}
+ />{" "}
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <b> Medium </b>
+ </td>
+ <td>
+ {" "}
+ <input
+ type="text"
+ name="medium"
+ placeholder="referral"
+ value={this.state.attributionParameters.medium}
+ onChange={this.onChangeAttributionParameters}
+ />{" "}
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <b> Campaign </b>
+ </td>
+ <td>
+ {" "}
+ <input
+ type="text"
+ name="campaign"
+ placeholder="non-fx-button"
+ value={this.state.attributionParameters.campaign}
+ onChange={this.onChangeAttributionParameters}
+ />{" "}
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <b> Content </b>
+ </td>
+ <td>
+ {" "}
+ <input
+ type="text"
+ name="content"
+ placeholder="iridium@particlecore.github.io"
+ value={this.state.attributionParameters.content}
+ onChange={this.onChangeAttributionParameters}
+ />{" "}
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <b> Experiment </b>
+ </td>
+ <td>
+ {" "}
+ <input
+ type="text"
+ name="experiment"
+ placeholder="ua-onboarding"
+ value={this.state.attributionParameters.experiment}
+ onChange={this.onChangeAttributionParameters}
+ />{" "}
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <b> Variation </b>
+ </td>
+ <td>
+ {" "}
+ <input
+ type="text"
+ name="variation"
+ placeholder="chrome"
+ value={this.state.attributionParameters.variation}
+ onChange={this.onChangeAttributionParameters}
+ />{" "}
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <b> User Agent </b>
+ </td>
+ <td>
+ {" "}
+ <input
+ type="text"
+ name="ua"
+ placeholder="Google Chrome 123"
+ value={this.state.attributionParameters.ua}
+ onChange={this.onChangeAttributionParameters}
+ />{" "}
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <b> Download Token </b>
+ </td>
+ <td>
+ {" "}
+ <input
+ type="text"
+ name="dltoken"
+ placeholder="00000000-0000-0000-0000-000000000000"
+ value={this.state.attributionParameters.dltoken}
+ onChange={this.onChangeAttributionParameters}
+ />{" "}
+ </td>
+ </tr>
+ <tr>
+ <td>
+ {" "}
+ <button
+ className="ASRouterButton primary button"
+ onClick={this.setAttribution}
+ >
+ {" "}
+ Force Attribution{" "}
+ </button>{" "}
+ </td>
+ </tr>
+ </table>
+ </div>
+ );
+ }
+
+ renderErrorMessage({ id, errors }) {
+ const providerId = <td rowSpan={errors.length}>{id}</td>;
+ // .reverse() so that the last error (most recent) is first
+ return errors
+ .map(({ error, timestamp }, cellKey) => (
+ <tr key={cellKey}>
+ {cellKey === errors.length - 1 ? providerId : null}
+ <td>{error.message}</td>
+ <td>{relativeTime(timestamp)}</td>
+ </tr>
+ ))
+ .reverse();
+ }
+
+ renderErrors() {
+ const providersWithErrors =
+ this.state.providers &&
+ this.state.providers.filter(p => p.errors && p.errors.length);
+
+ if (providersWithErrors && providersWithErrors.length) {
+ return (
+ <table className="errorReporting">
+ <thead>
+ <tr>
+ <th>Provider ID</th>
+ <th>Message</th>
+ <th>Timestamp</th>
+ </tr>
+ </thead>
+ <tbody>{providersWithErrors.map(this.renderErrorMessage)}</tbody>
+ </table>
+ );
+ }
+
+ return <p>No errors</p>;
+ }
+
+ renderWNPTests() {
+ if (!this.state.messages) {
+ return null;
+ }
+ let messagesToShow = this.state.messages.filter(
+ message => message.provider === "whats-new-panel"
+ );
+
+ return (
+ <div>
+ <p className="helpLink">
+ <span className="icon icon-small-spacer icon-info" />{" "}
+ <span>
+ To correctly render selected messages, click 'Open What's New
+ Panel', select the messages you want to see, and click 'Render
+ Selected Messages'.
+ <br />
+ <br />
+ To modify a message, select it, modify the JSON and click 'Render
+ Selected Messages' again to see your changes.
+ <br />
+ Click 'Reset Panel' to close the panel and reset all JSON to its
+ original state.
+ </span>
+ </p>
+ <div>
+ <button
+ className="ASRouterButton primary button"
+ onClick={this.handleForceWNP}
+ >
+ Open What's New Panel
+ </button>
+ <button
+ className="ASRouterButton secondary button"
+ onClick={this.handleUpdateWNMessages}
+ >
+ Render Selected Messages
+ </button>
+ <button
+ className="ASRouterButton secondary button"
+ onClick={this.resetPanel}
+ >
+ Reset Panel
+ </button>
+ <h2>Messages</h2>
+ <button
+ className="ASRouterButton slim button"
+ // eslint-disable-next-line react/jsx-no-bind
+ onClick={e => this.toggleAllMessages(messagesToShow)}
+ >
+ Collapse/Expand All
+ </button>
+ {this.renderWNMessages()}
+ </div>
+ </div>
+ );
+ }
+
+ getSection() {
+ const [section] = this.props.location.routes;
+ switch (section) {
+ case "wnpanel":
+ return (
+ <React.Fragment>
+ <h2>What's New Panel</h2>
+ {this.renderWNPTests()}
+ </React.Fragment>
+ );
+ case "targeting":
+ return (
+ <React.Fragment>
+ <h2>Targeting Utilities</h2>
+ <button className="button" onClick={this.expireCache}>
+ Expire Cache
+ </button>{" "}
+ (This expires the cache in ASR Targeting for bookmarks and top
+ sites)
+ {this.renderTargetingParameters()}
+ {this.renderAttributionParamers()}
+ </React.Fragment>
+ );
+ case "groups":
+ return (
+ <React.Fragment>
+ <h2>Message Groups</h2>
+ <button className="button" onClick={this.resetGroups}>
+ Reset group impressions
+ </button>
+ <table>
+ <thead>
+ <tr className="message-item">
+ <td>Enabled</td>
+ <td>Impressions count</td>
+ <td>Custom frequency</td>
+ <td>User preferences</td>
+ </tr>
+ </thead>
+ <tbody>
+ {this.state.groups &&
+ this.state.groups.map(
+ (
+ { id, enabled, frequency, userPreferences = [] },
+ index
+ ) => (
+ <Row key={id}>
+ <td>
+ <TogglePrefCheckbox
+ checked={enabled}
+ pref={id}
+ disabled={true}
+ />
+ </td>
+ <td>{this._getGroupImpressionsCount(id, frequency)}</td>
+ <td>{JSON.stringify(frequency, null, 2)}</td>
+ <td>{userPreferences.join(", ")}</td>
+ </Row>
+ )
+ )}
+ </tbody>
+ </table>
+ {this.renderMessageGroupsFilter()}
+ {this.renderMessagesByGroup()}
+ </React.Fragment>
+ );
+ case "ds":
+ return (
+ <React.Fragment>
+ <h2>Discovery Stream</h2>
+ <DiscoveryStreamAdmin
+ state={{
+ DiscoveryStream: this.props.DiscoveryStream,
+ Personalization: this.props.Personalization,
+ }}
+ otherPrefs={this.props.Prefs.values}
+ dispatch={this.props.dispatch}
+ />
+ </React.Fragment>
+ );
+ case "errors":
+ return (
+ <React.Fragment>
+ <h2>ASRouter Errors</h2>
+ {this.renderErrors()}
+ </React.Fragment>
+ );
+ default:
+ return (
+ <React.Fragment>
+ <h2>
+ Message Providers{" "}
+ <button
+ title="Restore all provider settings that ship with Firefox"
+ className="button"
+ onClick={this.resetPref}
+ >
+ Restore default prefs
+ </button>
+ </h2>
+ {this.state.providers ? this.renderProviders() : null}
+ <h2>Messages</h2>
+ {this.renderMessageFilter()}
+ {this.renderMessages()}
+ </React.Fragment>
+ );
+ }
+ }
+
+ render() {
+ return (
+ <div
+ className={`asrouter-admin ${
+ this.props.collapsed ? "collapsed" : "expanded"
+ }`}
+ >
+ <aside className="sidebar">
+ <ul>
+ <li>
+ <a href="#devtools">General</a>
+ </li>
+ <li>
+ <a href="#devtools-wnpanel">What's New Panel</a>
+ </li>
+ <li>
+ <a href="#devtools-targeting">Targeting</a>
+ </li>
+ <li>
+ <a href="#devtools-groups">Message Groups</a>
+ </li>
+ <li>
+ <a href="#devtools-ds">Discovery Stream</a>
+ </li>
+ <li>
+ <a href="#devtools-errors">Errors</a>
+ </li>
+ </ul>
+ </aside>
+ <main className="main-panel">
+ <h1>AS Router Admin</h1>
+
+ <p className="helpLink">
+ <span className="icon icon-small-spacer icon-info" />{" "}
+ <span>
+ Need help using these tools? Check out our{" "}
+ <a
+ target="blank"
+ href="https://github.com/mozilla/activity-stream/blob/master/content-src/asrouter/docs/debugging-docs.md"
+ >
+ documentation
+ </a>
+ </span>
+ </p>
+
+ {this.getSection()}
+ </main>
+ </div>
+ );
+ }
+}
+
+export class CollapseToggle extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onCollapseToggle = this.onCollapseToggle.bind(this);
+ this.state = { collapsed: false };
+ }
+
+ get renderAdmin() {
+ const { props } = this;
+ return (
+ props.location.hash &&
+ (props.location.hash.startsWith("#asrouter") ||
+ props.location.hash.startsWith("#devtools"))
+ );
+ }
+
+ onCollapseToggle(e) {
+ e.preventDefault();
+ this.setState(state => ({ collapsed: !state.collapsed }));
+ }
+
+ setBodyClass() {
+ if (this.renderAdmin && !this.state.collapsed) {
+ global.document.body.classList.add("no-scroll");
+ } else {
+ global.document.body.classList.remove("no-scroll");
+ }
+ }
+
+ componentDidMount() {
+ this.setBodyClass();
+ }
+
+ componentDidUpdate() {
+ this.setBodyClass();
+ }
+
+ componentWillUnmount() {
+ global.document.body.classList.remove("no-scroll");
+ ASRouterUtils.removeListener(this.onMessageFromParent);
+ }
+
+ render() {
+ const { props } = this;
+ const { renderAdmin } = this;
+ const isCollapsed = this.state.collapsed || !renderAdmin;
+ const label = `${isCollapsed ? "Expand" : "Collapse"} devtools`;
+ return (
+ <React.Fragment>
+ <a
+ href="#devtools"
+ title={label}
+ aria-label={label}
+ className={`asrouter-toggle ${
+ isCollapsed ? "collapsed" : "expanded"
+ }`}
+ onClick={this.renderAdmin ? this.onCollapseToggle : null}
+ >
+ <span className="icon icon-devtools" />
+ </a>
+ {renderAdmin ? (
+ <ASRouterAdminInner {...props} collapsed={this.state.collapsed} />
+ ) : null}
+ </React.Fragment>
+ );
+ }
+}
+
+const _ASRouterAdmin = props => (
+ <SimpleHashRouter>
+ <CollapseToggle {...props} />
+ </SimpleHashRouter>
+);
+
+export const ASRouterAdmin = connect(state => ({
+ Sections: state.Sections,
+ DiscoveryStream: state.DiscoveryStream,
+ Personalization: state.Personalization,
+ Prefs: state.Prefs,
+}))(_ASRouterAdmin);
diff --git a/browser/components/newtab/content-src/components/ASRouterAdmin/ASRouterAdmin.scss b/browser/components/newtab/content-src/components/ASRouterAdmin/ASRouterAdmin.scss
new file mode 100644
index 0000000000..0e12ec97e7
--- /dev/null
+++ b/browser/components/newtab/content-src/components/ASRouterAdmin/ASRouterAdmin.scss
@@ -0,0 +1,273 @@
+.asrouter-toggle {
+ position: fixed;
+ top: 50px;
+ inset-inline-end: 15px;
+ border: 0;
+ background: none;
+ z-index: 1;
+ border-radius: 2px;
+
+ .icon-devtools {
+ background-image: url('chrome://browser/skin/developer.svg');
+ padding: 15px;
+ }
+
+ &:dir(rtl) {
+ transform: scaleX(-1);
+ }
+
+ &:hover {
+ background: var(--newtab-element-hover-color);
+ }
+
+ &.expanded {
+ background: $black-20;
+ }
+}
+
+.asrouter-admin {
+ position: fixed;
+ top: 0;
+ inset-inline-start: 0;
+ width: 100%;
+ background: var(--newtab-background-color);
+ height: 100%;
+ overflow-y: scroll;
+ $border-color: var(--newtab-border-secondary-color);
+ $monospace: 'SF Mono', 'Monaco', 'Inconsolata', 'Fira Mono', 'Droid Sans Mono',
+ 'Source Code Pro', monospace;
+ $sidebar-width: 240px;
+ margin: 0 auto;
+ font-size: 14px;
+ padding-inline-start: $sidebar-width;
+ color: var(--newtab-text-primary-color);
+
+ &.collapsed {
+ display: none;
+ }
+
+ .sidebar {
+ inset-inline-start: 0;
+ position: fixed;
+ width: $sidebar-width;
+ padding: 30px 20px;
+
+ ul {
+ margin: 0;
+ padding: 0;
+ list-style: none;
+ }
+
+ li a {
+ padding: 10px 34px;
+ display: block;
+ color: var(--lwt-sidebar-text-color);
+
+ &:hover {
+ background: var(--newtab-textbox-background-color);
+ }
+ }
+ }
+
+ h1 {
+ font-weight: 200;
+ font-size: 32px;
+ }
+
+ h2 .button,
+ p .button {
+ font-size: 14px;
+ padding: 6px 12px;
+ margin-inline-start: 5px;
+ margin-bottom: 0;
+ }
+
+ .general-textarea {
+ direction: ltr;
+ width: 740px;
+ height: 500px;
+ overflow: auto;
+ resize: none;
+ border-radius: 4px;
+ display: flex;
+ }
+
+ .wnp-textarea {
+ direction: ltr;
+ width: 740px;
+ height: 500px;
+ overflow: auto;
+ resize: none;
+ border-radius: 4px;
+ display: flex;
+ }
+
+ .json-button {
+ display: inline-flex;
+ font-size: 10px;
+ padding: 4px 10px;
+ margin-bottom: 6px;
+ margin-inline-end: 4px;
+
+ &:hover {
+ background-color: $grey-20-60;
+ box-shadow: none;
+ }
+ }
+
+ table {
+ border-collapse: collapse;
+ width: 100%;
+
+ &.minimal-table {
+ border-collapse: collapse;
+ border: 1px solid $border-color;
+
+ td {
+ padding: 8px;
+ }
+
+ td:first-child {
+ width: 1%;
+ white-space: nowrap;
+ }
+
+ td:not(:first-child) {
+ font-family: $monospace;
+ }
+ }
+
+ &.errorReporting {
+ tr {
+ border: 1px solid var(--newtab-textbox-background-color);
+ }
+
+ td {
+ padding: 4px;
+
+ &[rowspan] {
+ border: 1px solid var(--newtab-textbox-background-color);
+ }
+ }
+ }
+ }
+
+ .sourceLabel {
+ background: var(--newtab-textbox-background-color);
+ padding: 2px 5px;
+ border-radius: 3px;
+
+ &.isDisabled {
+ background: $email-input-invalid;
+ color: $red-60;
+ }
+ }
+
+ .message-item {
+ &:first-child td {
+ border-top: 1px solid $border-color;
+ }
+
+ td {
+ vertical-align: top;
+ padding: 8px;
+ border-bottom: 1px solid $border-color;
+
+ &.min {
+ width: 1%;
+ white-space: nowrap;
+ }
+
+ &.message-summary {
+ width: 60%;
+ }
+
+ &.button-column {
+ width: 15%;
+ }
+
+ &:first-child {
+ border-inline-start: 1px solid $border-color;
+ }
+
+ &:last-child {
+ border-inline-end: 1px solid $border-color;
+ }
+ }
+
+ &.blocked {
+ .message-id,
+ .message-summary {
+ opacity: 0.5;
+ }
+
+ .message-id {
+ opacity: 0.5;
+ }
+ }
+
+ .message-id {
+ font-family: $monospace;
+ font-size: 12px;
+ }
+ }
+
+ .providerUrl {
+ font-size: 12px;
+ }
+
+ pre {
+ background: var(--newtab-textbox-background-color);
+ margin: 0;
+ padding: 8px;
+ font-size: 12px;
+ max-width: 750px;
+ overflow: auto;
+ font-family: $monospace;
+ }
+
+ .errorState {
+ border: 1px solid $red-60;
+ }
+
+ .helpLink {
+ padding: 10px;
+ display: flex;
+ background: $black-10;
+ border-radius: 3px;
+
+ a {
+ text-decoration: underline;
+ }
+ }
+
+ .ds-component {
+ margin-bottom: 20px;
+ }
+
+ .modalOverlayInner {
+ height: 80%;
+ }
+
+ .clearButton {
+ border: 0;
+ padding: 4px;
+ border-radius: 4px;
+ display: flex;
+
+ &:hover {
+ background: var(--newtab-element-hover-color);
+ }
+ }
+
+ .collapsed {
+ display: none;
+ }
+
+ .icon {
+ display: inline-table;
+ cursor: pointer;
+ width: 18px;
+ height: 18px;
+ }
+}
diff --git a/browser/components/newtab/content-src/components/ASRouterAdmin/SimpleHashRouter.jsx b/browser/components/newtab/content-src/components/ASRouterAdmin/SimpleHashRouter.jsx
new file mode 100644
index 0000000000..9c3fd8579c
--- /dev/null
+++ b/browser/components/newtab/content-src/components/ASRouterAdmin/SimpleHashRouter.jsx
@@ -0,0 +1,35 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import React from "react";
+
+export class SimpleHashRouter extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onHashChange = this.onHashChange.bind(this);
+ this.state = { hash: global.location.hash };
+ }
+
+ onHashChange() {
+ this.setState({ hash: global.location.hash });
+ }
+
+ componentWillMount() {
+ global.addEventListener("hashchange", this.onHashChange);
+ }
+
+ componentWillUnmount() {
+ global.removeEventListener("hashchange", this.onHashChange);
+ }
+
+ render() {
+ const [, ...routes] = this.state.hash.split("-");
+ return React.cloneElement(this.props.children, {
+ location: {
+ hash: this.state.hash,
+ routes,
+ },
+ });
+ }
+}
diff --git a/browser/components/newtab/content-src/components/Base/Base.jsx b/browser/components/newtab/content-src/components/Base/Base.jsx
new file mode 100644
index 0000000000..9bb1193159
--- /dev/null
+++ b/browser/components/newtab/content-src/components/Base/Base.jsx
@@ -0,0 +1,294 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { actionCreators as ac, actionTypes as at } from "common/Actions.jsm";
+import { ASRouterAdmin } from "content-src/components/ASRouterAdmin/ASRouterAdmin";
+import { ASRouterUISurface } from "../../asrouter/asrouter-content";
+import { ConfirmDialog } from "content-src/components/ConfirmDialog/ConfirmDialog";
+import { connect } from "react-redux";
+import { DiscoveryStreamBase } from "content-src/components/DiscoveryStreamBase/DiscoveryStreamBase";
+import { ErrorBoundary } from "content-src/components/ErrorBoundary/ErrorBoundary";
+import { CustomizeMenu } from "content-src/components/CustomizeMenu/CustomizeMenu";
+import React from "react";
+import { Search } from "content-src/components/Search/Search";
+import { Sections } from "content-src/components/Sections/Sections";
+import { CSSTransition } from "react-transition-group";
+
+export const PrefsButton = ({ onClick, icon }) => (
+ <div className="prefs-button">
+ <button
+ className={`icon ${icon || "icon-settings"}`}
+ onClick={onClick}
+ data-l10n-id="newtab-settings-button"
+ />
+ </div>
+);
+
+export const PersonalizeButton = ({ onClick }) => (
+ <button
+ className="personalize-button"
+ onClick={onClick}
+ data-l10n-id="newtab-personalize-button-label"
+ />
+);
+
+// Returns a function will not be continuously triggered when called. The
+// function will be triggered if called again after `wait` milliseconds.
+function debounce(func, wait) {
+ let timer;
+ return (...args) => {
+ if (timer) {
+ return;
+ }
+
+ let wakeUp = () => {
+ timer = null;
+ };
+
+ timer = setTimeout(wakeUp, wait);
+ func.apply(this, args);
+ };
+}
+
+export class _Base extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.state = {
+ message: {},
+ };
+ this.notifyContent = this.notifyContent.bind(this);
+ }
+
+ notifyContent(state) {
+ this.setState(state);
+ }
+
+ componentWillUnmount() {
+ this.updateTheme();
+ }
+
+ componentWillUpdate() {
+ this.updateTheme();
+ }
+
+ updateTheme() {
+ const bodyClassName = [
+ "activity-stream",
+ // If we skipped the about:welcome overlay and removed the CSS classes
+ // we don't want to add them back to the Activity Stream view
+ document.body.classList.contains("inline-onboarding")
+ ? "inline-onboarding"
+ : "",
+ ]
+ .filter(v => v)
+ .join(" ");
+ global.document.body.className = bodyClassName;
+ }
+
+ render() {
+ const { props } = this;
+ const { App } = props;
+ const isDevtoolsEnabled = props.Prefs.values["asrouter.devtoolsEnabled"];
+
+ if (!App.initialized) {
+ return null;
+ }
+
+ return (
+ <ErrorBoundary className="base-content-fallback">
+ <React.Fragment>
+ <BaseContent {...this.props} adminContent={this.state} />
+ {isDevtoolsEnabled ? (
+ <ASRouterAdmin notifyContent={this.notifyContent} />
+ ) : null}
+ </React.Fragment>
+ </ErrorBoundary>
+ );
+ }
+}
+
+export class BaseContent extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.openPreferences = this.openPreferences.bind(this);
+ this.openCustomizationMenu = this.openCustomizationMenu.bind(this);
+ this.closeCustomizationMenu = this.closeCustomizationMenu.bind(this);
+ this.handleOnKeyDown = this.handleOnKeyDown.bind(this);
+ this.onWindowScroll = debounce(this.onWindowScroll.bind(this), 5);
+ this.setPref = this.setPref.bind(this);
+ this.state = { fixedSearch: false, customizeMenuVisible: false };
+ }
+
+ componentDidMount() {
+ global.addEventListener("scroll", this.onWindowScroll);
+ global.addEventListener("keydown", this.handleOnKeyDown);
+ }
+
+ componentWillUnmount() {
+ global.removeEventListener("scroll", this.onWindowScroll);
+ global.removeEventListener("keydown", this.handleOnKeyDown);
+ }
+
+ onWindowScroll() {
+ const prefs = this.props.Prefs.values;
+ const SCROLL_THRESHOLD = prefs["logowordmark.alwaysVisible"] ? 179 : 34;
+ if (global.scrollY > SCROLL_THRESHOLD && !this.state.fixedSearch) {
+ this.setState({ fixedSearch: true });
+ } else if (global.scrollY <= SCROLL_THRESHOLD && this.state.fixedSearch) {
+ this.setState({ fixedSearch: false });
+ }
+ }
+
+ openPreferences() {
+ this.props.dispatch(ac.OnlyToMain({ type: at.SETTINGS_OPEN }));
+ this.props.dispatch(ac.UserEvent({ event: "OPEN_NEWTAB_PREFS" }));
+ }
+
+ openCustomizationMenu() {
+ this.setState({ customizeMenuVisible: true });
+ this.props.dispatch(ac.UserEvent({ event: "SHOW_PERSONALIZE" }));
+ }
+
+ closeCustomizationMenu() {
+ if (this.state.customizeMenuVisible) {
+ this.setState({ customizeMenuVisible: false });
+ this.props.dispatch(ac.UserEvent({ event: "HIDE_PERSONALIZE" }));
+ }
+ }
+
+ handleOnKeyDown(e) {
+ if (e.key === "Escape") {
+ this.closeCustomizationMenu();
+ }
+ }
+
+ setPref(pref, value) {
+ this.props.dispatch(ac.SetPref(pref, value));
+ }
+
+ render() {
+ const { props } = this;
+ const { App } = props;
+ const { initialized } = App;
+ const prefs = props.Prefs.values;
+
+ // Values from experiment data
+ const { prefsButtonIcon } = prefs.featureConfig || {};
+
+ const isDiscoveryStream =
+ props.DiscoveryStream.config && props.DiscoveryStream.config.enabled;
+ let filteredSections = props.Sections.filter(
+ section => section.id !== "topstories"
+ );
+
+ const pocketEnabled =
+ prefs["feeds.section.topstories"] && prefs["feeds.system.topstories"];
+ const noSectionsEnabled =
+ !prefs["feeds.topsites"] &&
+ !pocketEnabled &&
+ filteredSections.filter(section => section.enabled).length === 0;
+ const searchHandoffEnabled = prefs["improvesearch.handoffToAwesomebar"];
+ const customizationMenuEnabled = prefs["customizationMenu.enabled"];
+ const newNewtabExperienceEnabled = prefs["newNewtabExperience.enabled"];
+ const canShowCustomizationMenu =
+ customizationMenuEnabled || newNewtabExperienceEnabled;
+ const showCustomizationMenu =
+ canShowCustomizationMenu && this.state.customizeMenuVisible;
+ const enabledSections = {
+ topSitesEnabled: prefs["feeds.topsites"],
+ pocketEnabled: prefs["feeds.section.topstories"],
+ snippetsEnabled: prefs["feeds.snippets"],
+ highlightsEnabled: prefs["feeds.section.highlights"],
+ showSponsoredTopSitesEnabled: prefs.showSponsoredTopSites,
+ showSponsoredPocketEnabled: prefs.showSponsored,
+ topSitesRowsCount: prefs.topSitesRows,
+ };
+ const pocketRegion = prefs["feeds.system.topstories"];
+ const { mayHaveSponsoredTopSites } = prefs;
+
+ const outerClassName = [
+ "outer-wrapper",
+ isDiscoveryStream && pocketEnabled && "ds-outer-wrapper-search-alignment",
+ isDiscoveryStream && "ds-outer-wrapper-breakpoint-override",
+ prefs.showSearch &&
+ this.state.fixedSearch &&
+ !noSectionsEnabled &&
+ "fixed-search",
+ prefs.showSearch && noSectionsEnabled && "only-search",
+ prefs["logowordmark.alwaysVisible"] && "visible-logo",
+ newNewtabExperienceEnabled && "newtab-experience",
+ ]
+ .filter(v => v)
+ .join(" ");
+
+ return (
+ <div>
+ {canShowCustomizationMenu ? (
+ <span>
+ <PersonalizeButton onClick={this.openCustomizationMenu} />
+ <CSSTransition
+ timeout={0}
+ classNames="customize-animate"
+ in={showCustomizationMenu}
+ appear={true}
+ >
+ <CustomizeMenu
+ onClose={this.closeCustomizationMenu}
+ openPreferences={this.openPreferences}
+ setPref={this.setPref}
+ enabledSections={enabledSections}
+ pocketRegion={pocketRegion}
+ mayHaveSponsoredTopSites={mayHaveSponsoredTopSites}
+ />
+ </CSSTransition>
+ </span>
+ ) : (
+ <PrefsButton onClick={this.openPreferences} icon={prefsButtonIcon} />
+ )}
+ {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions*/}
+ <div className={outerClassName} onClick={this.closeCustomizationMenu}>
+ <main>
+ {prefs.showSearch && (
+ <div className="non-collapsible-section">
+ <ErrorBoundary>
+ <Search
+ showLogo={
+ noSectionsEnabled || prefs["logowordmark.alwaysVisible"]
+ }
+ handoffEnabled={searchHandoffEnabled}
+ {...props.Search}
+ />
+ </ErrorBoundary>
+ </div>
+ )}
+ <ASRouterUISurface
+ adminContent={this.props.adminContent}
+ appUpdateChannel={this.props.Prefs.values.appUpdateChannel}
+ fxaEndpoint={this.props.Prefs.values.fxa_endpoint}
+ dispatch={this.props.dispatch}
+ />
+ <div className={`body-wrapper${initialized ? " on" : ""}`}>
+ {isDiscoveryStream ? (
+ <ErrorBoundary className="borderless-error">
+ <DiscoveryStreamBase locale={props.App.locale} />
+ </ErrorBoundary>
+ ) : (
+ <Sections />
+ )}
+ </div>
+ <ConfirmDialog />
+ </main>
+ </div>
+ </div>
+ );
+ }
+}
+
+export const Base = connect(state => ({
+ App: state.App,
+ Prefs: state.Prefs,
+ Sections: state.Sections,
+ DiscoveryStream: state.DiscoveryStream,
+ Search: state.Search,
+}))(_Base);
diff --git a/browser/components/newtab/content-src/components/Base/_Base.scss b/browser/components/newtab/content-src/components/Base/_Base.scss
new file mode 100644
index 0000000000..a12e14cb95
--- /dev/null
+++ b/browser/components/newtab/content-src/components/Base/_Base.scss
@@ -0,0 +1,179 @@
+.outer-wrapper {
+ color: var(--newtab-text-primary-color);
+ display: flex;
+ flex-grow: 1;
+ min-height: 100vh;
+ padding: ($section-spacing + $section-vertical-padding) $base-gutter $base-gutter;
+
+ &.ds-outer-wrapper-breakpoint-override {
+ padding: 30px 0 32px;
+
+ @media(min-width: $break-point-medium) {
+ padding: 30px 32px 32px;
+ }
+ }
+
+ &.only-search {
+ display: block;
+ padding-top: 134px;
+ }
+
+ a {
+ color: var(--newtab-link-primary-color);
+ }
+}
+
+main {
+ margin: auto;
+ width: $wrapper-default-width;
+ // Offset the snippets container so things at the bottom of the page are still
+ // visible when snippets are visible. Adjust for other spacing.
+ padding-bottom: $snippets-container-height - $section-spacing - $base-gutter;
+
+ section {
+ margin-bottom: $section-spacing;
+ position: relative;
+ }
+
+ .hide-main & {
+ visibility: hidden;
+ }
+
+ @media (min-width: $break-point-medium) {
+ width: $wrapper-max-width-medium;
+ }
+
+ @media (min-width: $break-point-large) {
+ width: $wrapper-max-width-large;
+ }
+
+ @media (min-width: $break-point-widest) {
+ width: $wrapper-max-width-widest;
+ }
+
+}
+
+.below-search-snippet.withButton {
+ margin: auto;
+ width: 100%;
+}
+
+.ds-outer-wrapper-search-alignment {
+ main {
+ // This override is to ensure while Discovery Stream loads,
+ // the search bar does not jump around. (it sticks to the top)
+ margin: 0 auto;
+ }
+}
+
+.ds-outer-wrapper-breakpoint-override {
+ main {
+ width: 266px;
+ padding-bottom: 68px;
+
+ @media (min-width: $break-point-medium) {
+ width: 510px;
+ }
+
+ @media (min-width: $break-point-large) {
+ width: 746px;
+ }
+
+ @media (min-width: $break-point-widest) {
+ width: 986px;
+ }
+ }
+}
+
+.base-content-fallback {
+ // Make the error message be centered against the viewport
+ height: 100vh;
+}
+
+.body-wrapper {
+ // Hide certain elements so the page structure is fixed, e.g., placeholders,
+ // while avoiding flashes of changing content, e.g., icons and text
+ $selectors-to-hide: '
+ .section-title,
+ .sections-list .section:last-of-type,
+ .topics
+ ';
+
+ #{$selectors-to-hide} {
+ opacity: 0;
+ }
+
+ &.on {
+ #{$selectors-to-hide} {
+ opacity: 1;
+ }
+ }
+}
+
+.non-collapsible-section {
+ padding: 0 $section-horizontal-padding;
+}
+
+.prefs-button {
+ button {
+ background-color: transparent;
+ border: 0;
+ border-radius: 2px;
+ cursor: pointer;
+ inset-inline-end: 15px;
+ padding: 15px;
+ position: fixed;
+ top: 15px;
+ z-index: 1000;
+
+ &:hover,
+ &:focus {
+ background-color: var(--newtab-element-hover-color);
+ }
+
+ &:active {
+ background-color: var(--newtab-element-active-color);
+ }
+ }
+}
+
+@media (max-height: 701px) {
+ .personalize-button {
+ position: absolute;
+ top: 16px;
+ inset-inline-end: 16px;
+ }
+}
+
+@media (min-height: 700px) {
+ .personalize-button {
+ position: fixed;
+ top: 16px;
+ inset-inline-end: 16px;
+ z-index: 1000;
+ }
+}
+
+.personalize-button {
+ font-size: 12px;
+ font-weight: 600;
+ border: 0;
+ border-radius: 4px;
+ background-color: var(--newtab-background-button-color);
+ color: var(--newtab-background-button-text-color);
+ padding: 3px 10px;
+ min-height: 32px;
+ max-width: 117px;
+
+ &:hover {
+ background-color: var(--newtab-background-button-hover-color);
+ }
+
+ &:active {
+ background-color: var(--newtab-background-button-active-color);
+ }
+
+ &:focus-visible {
+ @include ds-focus-nte;
+ }
+}
diff --git a/browser/components/newtab/content-src/components/Card/Card.jsx b/browser/components/newtab/content-src/components/Card/Card.jsx
new file mode 100644
index 0000000000..3e2c5ace83
--- /dev/null
+++ b/browser/components/newtab/content-src/components/Card/Card.jsx
@@ -0,0 +1,354 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { actionCreators as ac, actionTypes as at } from "common/Actions.jsm";
+import { cardContextTypes } from "./types";
+import { connect } from "react-redux";
+import { ContextMenuButton } from "content-src/components/ContextMenu/ContextMenuButton";
+import { LinkMenu } from "content-src/components/LinkMenu/LinkMenu";
+import React from "react";
+import { ScreenshotUtils } from "content-src/lib/screenshot-utils";
+
+// Keep track of pending image loads to only request once
+const gImageLoading = new Map();
+
+/**
+ * Card component.
+ * Cards are found within a Section component and contain information about a link such
+ * as preview image, page title, page description, and some context about if the page
+ * was visited, bookmarked, trending etc...
+ * Each Section can make an unordered list of Cards which will create one instane of
+ * this class. Each card will then get a context menu which reflects the actions that
+ * can be done on this Card.
+ */
+export class _Card extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.state = {
+ activeCard: null,
+ imageLoaded: false,
+ cardImage: null,
+ };
+ this.onMenuButtonUpdate = this.onMenuButtonUpdate.bind(this);
+ this.onLinkClick = this.onLinkClick.bind(this);
+ }
+
+ /**
+ * Helper to conditionally load an image and update state when it loads.
+ */
+ async maybeLoadImage() {
+ // No need to load if it's already loaded or no image
+ const { cardImage } = this.state;
+ if (!cardImage) {
+ return;
+ }
+
+ const imageUrl = cardImage.url;
+ if (!this.state.imageLoaded) {
+ // Initialize a promise to share a load across multiple card updates
+ if (!gImageLoading.has(imageUrl)) {
+ const loaderPromise = new Promise((resolve, reject) => {
+ const loader = new Image();
+ loader.addEventListener("load", resolve);
+ loader.addEventListener("error", reject);
+ loader.src = imageUrl;
+ });
+
+ // Save and remove the promise only while it's pending
+ gImageLoading.set(imageUrl, loaderPromise);
+ loaderPromise
+ .catch(ex => ex)
+ .then(() => gImageLoading.delete(imageUrl))
+ .catch();
+ }
+
+ // Wait for the image whether just started loading or reused promise
+ await gImageLoading.get(imageUrl);
+
+ // Only update state if we're still waiting to load the original image
+ if (
+ ScreenshotUtils.isRemoteImageLocal(
+ this.state.cardImage,
+ this.props.link.image
+ ) &&
+ !this.state.imageLoaded
+ ) {
+ this.setState({ imageLoaded: true });
+ }
+ }
+ }
+
+ /**
+ * Helper to obtain the next state based on nextProps and prevState.
+ *
+ * NOTE: Rename this method to getDerivedStateFromProps when we update React
+ * to >= 16.3. We will need to update tests as well. We cannot rename this
+ * method to getDerivedStateFromProps now because there is a mismatch in
+ * the React version that we are using for both testing and production.
+ * (i.e. react-test-render => "16.3.2", react => "16.2.0").
+ *
+ * See https://github.com/airbnb/enzyme/blob/master/packages/enzyme-adapter-react-16/package.json#L43.
+ */
+ static getNextStateFromProps(nextProps, prevState) {
+ const { image } = nextProps.link;
+ const imageInState = ScreenshotUtils.isRemoteImageLocal(
+ prevState.cardImage,
+ image
+ );
+ let nextState = null;
+
+ // Image is updating.
+ if (!imageInState && nextProps.link) {
+ nextState = { imageLoaded: false };
+ }
+
+ if (imageInState) {
+ return nextState;
+ }
+
+ // Since image was updated, attempt to revoke old image blob URL, if it exists.
+ ScreenshotUtils.maybeRevokeBlobObjectURL(prevState.cardImage);
+
+ nextState = nextState || {};
+ nextState.cardImage = ScreenshotUtils.createLocalImageObject(image);
+
+ return nextState;
+ }
+
+ onMenuButtonUpdate(isOpen) {
+ if (isOpen) {
+ this.setState({ activeCard: this.props.index });
+ } else {
+ this.setState({ activeCard: null });
+ }
+ }
+
+ /**
+ * Report to telemetry additional information about the item.
+ */
+ _getTelemetryInfo() {
+ // Filter out "history" type for being the default
+ if (this.props.link.type !== "history") {
+ return { value: { card_type: this.props.link.type } };
+ }
+
+ return null;
+ }
+
+ onLinkClick(event) {
+ event.preventDefault();
+ const { altKey, button, ctrlKey, metaKey, shiftKey } = event;
+ if (this.props.link.type === "download") {
+ this.props.dispatch(
+ ac.OnlyToMain({
+ type: at.OPEN_DOWNLOAD_FILE,
+ data: Object.assign(this.props.link, {
+ event: { button, ctrlKey, metaKey, shiftKey },
+ }),
+ })
+ );
+ } else {
+ this.props.dispatch(
+ ac.OnlyToMain({
+ type: at.OPEN_LINK,
+ data: Object.assign(this.props.link, {
+ event: { altKey, button, ctrlKey, metaKey, shiftKey },
+ }),
+ })
+ );
+ }
+ if (this.props.isWebExtension) {
+ this.props.dispatch(
+ ac.WebExtEvent(at.WEBEXT_CLICK, {
+ source: this.props.eventSource,
+ url: this.props.link.url,
+ action_position: this.props.index,
+ })
+ );
+ } else {
+ this.props.dispatch(
+ ac.UserEvent(
+ Object.assign(
+ {
+ event: "CLICK",
+ source: this.props.eventSource,
+ action_position: this.props.index,
+ },
+ this._getTelemetryInfo()
+ )
+ )
+ );
+
+ if (this.props.shouldSendImpressionStats) {
+ this.props.dispatch(
+ ac.ImpressionStats({
+ source: this.props.eventSource,
+ click: 0,
+ tiles: [{ id: this.props.link.guid, pos: this.props.index }],
+ })
+ );
+ }
+ }
+ }
+
+ componentDidMount() {
+ this.maybeLoadImage();
+ }
+
+ componentDidUpdate() {
+ this.maybeLoadImage();
+ }
+
+ // NOTE: Remove this function when we update React to >= 16.3 since React will
+ // call getDerivedStateFromProps automatically. We will also need to
+ // rename getNextStateFromProps to getDerivedStateFromProps.
+ componentWillMount() {
+ const nextState = _Card.getNextStateFromProps(this.props, this.state);
+ if (nextState) {
+ this.setState(nextState);
+ }
+ }
+
+ // NOTE: Remove this function when we update React to >= 16.3 since React will
+ // call getDerivedStateFromProps automatically. We will also need to
+ // rename getNextStateFromProps to getDerivedStateFromProps.
+ componentWillReceiveProps(nextProps) {
+ const nextState = _Card.getNextStateFromProps(nextProps, this.state);
+ if (nextState) {
+ this.setState(nextState);
+ }
+ }
+
+ componentWillUnmount() {
+ ScreenshotUtils.maybeRevokeBlobObjectURL(this.state.cardImage);
+ }
+
+ render() {
+ const {
+ index,
+ className,
+ link,
+ dispatch,
+ contextMenuOptions,
+ eventSource,
+ shouldSendImpressionStats,
+ } = this.props;
+ const { props } = this;
+ const title = link.title || link.hostname;
+ const isContextMenuOpen = this.state.activeCard === index;
+ // Display "now" as "trending" until we have new strings #3402
+ const { icon, fluentID } =
+ cardContextTypes[link.type === "now" ? "trending" : link.type] || {};
+ const hasImage = this.state.cardImage || link.hasImage;
+ const imageStyle = {
+ backgroundImage: this.state.cardImage
+ ? `url(${this.state.cardImage.url})`
+ : "none",
+ };
+ const outerClassName = [
+ "card-outer",
+ className,
+ isContextMenuOpen && "active",
+ props.placeholder && "placeholder",
+ ]
+ .filter(v => v)
+ .join(" ");
+
+ return (
+ <li className={outerClassName}>
+ <a
+ href={link.type === "pocket" ? link.open_url : link.url}
+ onClick={!props.placeholder ? this.onLinkClick : undefined}
+ >
+ <div className="card">
+ <div className="card-preview-image-outer">
+ {hasImage && (
+ <div
+ className={`card-preview-image${
+ this.state.imageLoaded ? " loaded" : ""
+ }`}
+ style={imageStyle}
+ />
+ )}
+ </div>
+ <div className="card-details">
+ {link.type === "download" && (
+ <div
+ className="card-host-name alternate"
+ data-l10n-id="newtab-menu-open-file"
+ />
+ )}
+ {link.hostname && (
+ <div className="card-host-name">
+ {link.hostname.slice(0, 100)}
+ {link.type === "download" && ` \u2014 ${link.description}`}
+ </div>
+ )}
+ <div
+ className={[
+ "card-text",
+ icon ? "" : "no-context",
+ link.description ? "" : "no-description",
+ link.hostname ? "" : "no-host-name",
+ ].join(" ")}
+ >
+ <h4 className="card-title" dir="auto">
+ {link.title}
+ </h4>
+ <p className="card-description" dir="auto">
+ {link.description}
+ </p>
+ </div>
+ <div className="card-context">
+ {icon && !link.context && (
+ <span
+ aria-haspopup="true"
+ className={`card-context-icon icon icon-${icon}`}
+ />
+ )}
+ {link.icon && link.context && (
+ <span
+ aria-haspopup="true"
+ className="card-context-icon icon"
+ style={{ backgroundImage: `url('${link.icon}')` }}
+ />
+ )}
+ {fluentID && !link.context && (
+ <div className="card-context-label" data-l10n-id={fluentID} />
+ )}
+ {link.context && (
+ <div className="card-context-label">{link.context}</div>
+ )}
+ </div>
+ </div>
+ </div>
+ </a>
+ {!props.placeholder && (
+ <ContextMenuButton
+ tooltip="newtab-menu-content-tooltip"
+ tooltipArgs={{ title }}
+ onUpdate={this.onMenuButtonUpdate}
+ >
+ <LinkMenu
+ dispatch={dispatch}
+ index={index}
+ source={eventSource}
+ options={link.contextMenuOptions || contextMenuOptions}
+ site={link}
+ siteInfo={this._getTelemetryInfo()}
+ shouldSendImpressionStats={shouldSendImpressionStats}
+ />
+ </ContextMenuButton>
+ )}
+ </li>
+ );
+ }
+}
+_Card.defaultProps = { link: {} };
+export const Card = connect(state => ({
+ platform: state.Prefs.values.platform,
+}))(_Card);
+export const PlaceholderCard = props => (
+ <Card placeholder={true} className={props.className} />
+);
diff --git a/browser/components/newtab/content-src/components/Card/_Card.scss b/browser/components/newtab/content-src/components/Card/_Card.scss
new file mode 100644
index 0000000000..64dd5c0cf6
--- /dev/null
+++ b/browser/components/newtab/content-src/components/Card/_Card.scss
@@ -0,0 +1,369 @@
+// Special styling for the New Tab Experience styles,
+// This is to be incorporated once the styles are made permanent
+.outer-wrapper.newtab-experience {
+ .card-outer {
+ border-radius: $border-radius-new;
+
+ &:is(:focus):not(.placeholder) {
+ @include ds-focus-nte;
+
+ transition: none;
+ }
+
+ &:hover {
+ box-shadow: none;
+ transition: none;
+ }
+
+ .card {
+ box-shadow: 0 3px 8px var(--newtab-card-first-shadow), 0 0 2px var(--newtab-card-second-shadow);
+ border-radius: $border-radius-new;
+ }
+
+ .card-preview-image-outer {
+ border-radius: $border-radius-new $border-radius-new 0 0;
+ }
+
+ // Temporary fix to have the context button focus blend in with other New Tab Experience context menu focus
+ .context-menu-button {
+ &:is(:active, :focus) {
+ outline: 0;
+ fill: var(--newtab-primary-action-background);
+ border: 1px solid var(--newtab-primary-action-background);
+ }
+ }
+
+ > a {
+ &:is(:focus) {
+ .card {
+ @include ds-focus-nte;
+ }
+ }
+ }
+ }
+}
+
+.outer-wrapper:not(.newtab-experience) {
+ .card-outer {
+ &:is(:hover, :focus, .active):not(.placeholder) {
+ @include fade-in-card;
+ }
+ }
+}
+
+.card-outer {
+ @include context-menu-button;
+ background: var(--newtab-card-background-color);
+ border-radius: $border-radius;
+ display: inline-block;
+ height: $card-height;
+ margin-inline-end: $base-gutter;
+ position: relative;
+ width: 100%;
+
+ &.placeholder {
+ background: transparent;
+
+ .card {
+ box-shadow: inset $inner-box-shadow;
+ }
+
+ .card-preview-image-outer,
+ .card-context {
+ display: none;
+ }
+ }
+
+ .card {
+ border-radius: $border-radius;
+ box-shadow: var(--newtab-card-shadow);
+ height: 100%;
+ }
+
+ > a {
+ color: inherit;
+ display: block;
+ height: 100%;
+ outline: none;
+ position: absolute;
+ width: 100%;
+
+ &:is(.active, :focus) {
+ .card {
+ @include fade-in-card;
+ }
+
+ .card-title {
+ color: var(--newtab-link-primary-color);
+ }
+ }
+ }
+
+ &:is(:hover, :focus, .active):not(.placeholder) {
+ @include context-menu-button-hover;
+ outline: none;
+
+ .card-title {
+ color: var(--newtab-link-primary-color);
+ }
+
+ .alternate ~ .card-host-name {
+ display: none;
+ }
+
+ .card-host-name.alternate {
+ display: block;
+ }
+ }
+
+ .card-preview-image-outer {
+ background-color: $grey-30;
+ border-radius: $border-radius $border-radius 0 0;
+ height: $card-preview-image-height;
+ overflow: hidden;
+ position: relative;
+
+ [lwt-newtab-brighttext] & {
+ background-color: $grey-60;
+ }
+
+ &::after {
+ border-bottom: 1px solid var(--newtab-card-hairline-color);
+ bottom: 0;
+ content: '';
+ position: absolute;
+ width: 100%;
+ }
+
+ .card-preview-image {
+ background-position: center;
+ background-repeat: no-repeat;
+ background-size: cover;
+ height: 100%;
+ opacity: 0;
+ transition: opacity 1s $photon-easing;
+ width: 100%;
+
+ &.loaded {
+ opacity: 1;
+ }
+ }
+ }
+
+ .card-details {
+ padding: 15px 16px 12px;
+ }
+
+ .card-text {
+ max-height: 4 * $card-text-line-height + $card-title-margin;
+ overflow: hidden;
+
+ &.no-host-name,
+ &.no-context {
+ max-height: 5 * $card-text-line-height + $card-title-margin;
+ }
+
+ &.no-host-name.no-context {
+ max-height: 6 * $card-text-line-height + $card-title-margin;
+ }
+
+ &:not(.no-description) .card-title {
+ max-height: 3 * $card-text-line-height;
+ overflow: hidden;
+ }
+ }
+
+ .card-host-name {
+ color: var(--newtab-text-secondary-color);
+ font-size: 10px;
+ overflow: hidden;
+ padding-bottom: 4px;
+ text-overflow: ellipsis;
+ text-transform: uppercase; // sass-lint:disable-line no-disallowed-properties
+ white-space: nowrap;
+ }
+
+ .card-host-name.alternate { display: none; }
+
+ .card-title {
+ font-size: 14px;
+ font-weight: 600;
+ line-height: $card-text-line-height;
+ margin: 0 0 $card-title-margin;
+ word-wrap: break-word;
+ }
+
+ .card-description {
+ font-size: 12px;
+ line-height: $card-text-line-height;
+ margin: 0;
+ overflow: hidden;
+ word-wrap: break-word;
+ }
+
+ .card-context {
+ bottom: 0;
+ color: var(--newtab-text-secondary-color);
+ display: flex;
+ font-size: 11px;
+ inset-inline-start: 0;
+ padding: 9px 16px 9px 14px;
+ position: absolute;
+ }
+
+ .card-context-icon {
+ fill: var(--newtab-text-secondary-color);
+ height: 22px;
+ margin-inline-end: 6px;
+ }
+
+ .card-context-label {
+ flex-grow: 1;
+ line-height: 22px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+}
+
+.normal-cards {
+ .card-outer {
+ // Wide layout styles
+ @media (min-width: $break-point-widest) {
+ $line-height: 23px;
+ height: $card-height-large;
+
+ .card-preview-image-outer {
+ height: $card-preview-image-height-large;
+ }
+
+ .card-details {
+ padding: 13px 16px 12px;
+ }
+
+ .card-text {
+ max-height: 6 * $line-height + $card-title-margin;
+ }
+
+ .card-host-name {
+ font-size: 12px;
+ padding-bottom: 5px;
+ }
+
+ .card-title {
+ font-size: 17px;
+ line-height: $line-height;
+ margin-bottom: 0;
+ }
+
+ .card-text:not(.no-description) {
+ .card-title {
+ max-height: 3 * $line-height;
+ }
+ }
+
+ .card-description {
+ font-size: 15px;
+ line-height: $line-height;
+ }
+
+ .card-context {
+ bottom: 4px;
+ font-size: 14px;
+ }
+ }
+ }
+}
+
+.compact-cards {
+ $card-detail-vertical-spacing: 12px;
+ $card-title-font-size: 12px;
+
+ .card-outer {
+ height: $card-height-compact;
+
+ .card-preview-image-outer {
+ height: $card-preview-image-height-compact;
+ }
+
+ .card-details {
+ padding: $card-detail-vertical-spacing 16px;
+ }
+
+ .card-host-name {
+ line-height: 10px;
+ }
+
+ .card-text {
+ .card-title,
+ &:not(.no-description) .card-title {
+ font-size: $card-title-font-size;
+ line-height: $card-title-font-size + 1;
+ max-height: $card-title-font-size + 5;
+ overflow: hidden;
+ padding: 0 0 4px;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ }
+
+ .card-description {
+ display: none;
+ }
+
+ .card-context {
+ $icon-size: 16px;
+ $container-size: 32px;
+ background-color: var(--newtab-card-background-color);
+ border-radius: $container-size / 2;
+ clip-path: inset(-1px -1px $container-size - ($card-height-compact - $card-preview-image-height-compact - 2 * $card-detail-vertical-spacing));
+ height: $container-size;
+ width: $container-size;
+ padding: ($container-size - $icon-size) / 2;
+ // The -1 at the end is so both opacity borders don't overlap, which causes bug 1629483
+ top: $card-preview-image-height-compact - $container-size / 2 - 1;
+ inset-inline-end: 12px;
+ inset-inline-start: auto;
+
+ &::after {
+ border: 1px solid var(--newtab-card-hairline-color);
+ border-bottom: 0;
+ border-radius: ($container-size / 2) + 1 ($container-size / 2) + 1 0 0;
+ content: '';
+ position: absolute;
+ height: ($container-size + 2) / 2;
+ width: $container-size + 2;
+ top: -1px;
+ left: -1px;
+ }
+
+ .card-context-icon {
+ margin-inline-end: 0;
+ height: $icon-size;
+ width: $icon-size;
+
+ &.icon-bookmark-added {
+ fill: $bookmark-icon-fill;
+ }
+
+ &.icon-download {
+ fill: $download-icon-fill;
+ }
+
+ &.icon-pocket {
+ fill: $pocket-icon-fill;
+ }
+ }
+
+ .card-context-label {
+ display: none;
+ }
+ }
+ }
+
+ @media not all and (min-width: $break-point-widest) {
+ .hide-for-narrow {
+ display: none;
+ }
+ }
+}
diff --git a/browser/components/newtab/content-src/components/Card/types.js b/browser/components/newtab/content-src/components/Card/types.js
new file mode 100644
index 0000000000..0b17eea408
--- /dev/null
+++ b/browser/components/newtab/content-src/components/Card/types.js
@@ -0,0 +1,30 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+export const cardContextTypes = {
+ history: {
+ fluentID: "newtab-label-visited",
+ icon: "history-item",
+ },
+ removedBookmark: {
+ fluentID: "newtab-label-removed-bookmark",
+ icon: "bookmark-removed",
+ },
+ bookmark: {
+ fluentID: "newtab-label-bookmarked",
+ icon: "bookmark-added",
+ },
+ trending: {
+ fluentID: "newtab-label-recommended",
+ icon: "trending",
+ },
+ pocket: {
+ fluentID: "newtab-label-saved",
+ icon: "pocket",
+ },
+ download: {
+ fluentID: "newtab-label-download",
+ icon: "download",
+ },
+};
diff --git a/browser/components/newtab/content-src/components/CollapsibleSection/CollapsibleSection.jsx b/browser/components/newtab/content-src/components/CollapsibleSection/CollapsibleSection.jsx
new file mode 100644
index 0000000000..e52c2a8da9
--- /dev/null
+++ b/browser/components/newtab/content-src/components/CollapsibleSection/CollapsibleSection.jsx
@@ -0,0 +1,342 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { actionCreators as ac } from "common/Actions.jsm";
+import { ErrorBoundary } from "content-src/components/ErrorBoundary/ErrorBoundary";
+import { FluentOrText } from "content-src/components/FluentOrText/FluentOrText";
+import React from "react";
+import { connect } from "react-redux";
+import { SectionMenu } from "content-src/components/SectionMenu/SectionMenu";
+import { SectionMenuOptions } from "content-src/lib/section-menu-options";
+import { ContextMenuButton } from "content-src/components/ContextMenu/ContextMenuButton";
+
+const VISIBLE = "visible";
+const VISIBILITY_CHANGE_EVENT = "visibilitychange";
+
+export class _CollapsibleSection extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onBodyMount = this.onBodyMount.bind(this);
+ this.collapseOrExpandSection = this.collapseOrExpandSection.bind(this);
+ this.onHeaderClick = this.onHeaderClick.bind(this);
+ this.onKeyPress = this.onKeyPress.bind(this);
+ this.onTransitionEnd = this.onTransitionEnd.bind(this);
+ this.enableOrDisableAnimation = this.enableOrDisableAnimation.bind(this);
+ this.onMenuButtonMouseEnter = this.onMenuButtonMouseEnter.bind(this);
+ this.onMenuButtonMouseLeave = this.onMenuButtonMouseLeave.bind(this);
+ this.onMenuUpdate = this.onMenuUpdate.bind(this);
+ this.state = {
+ enableAnimation: true,
+ isAnimating: false,
+ menuButtonHover: false,
+ showContextMenu: false,
+ };
+ this.setContextMenuButtonRef = this.setContextMenuButtonRef.bind(this);
+ }
+
+ componentWillMount() {
+ this.props.document.addEventListener(
+ VISIBILITY_CHANGE_EVENT,
+ this.enableOrDisableAnimation
+ );
+ }
+
+ componentWillUpdate(nextProps) {
+ // Check if we're about to go from expanded to collapsed
+ if (!this.props.collapsed && nextProps.collapsed) {
+ // This next line forces a layout flush of the section body, which has a
+ // max-height style set, so that the upcoming collapse animation can
+ // animate from that height to the collapsed height. Without this, the
+ // update is coalesced and there's no animation from no-max-height to 0.
+ this.sectionBody.scrollHeight; // eslint-disable-line no-unused-expressions
+ }
+ }
+
+ setContextMenuButtonRef(element) {
+ this.contextMenuButtonRef = element;
+ }
+
+ componentDidMount() {
+ if (!this.props.Prefs.values["newNewtabExperience.enabled"]) {
+ this.contextMenuButtonRef.addEventListener(
+ "mouseenter",
+ this.onMenuButtonMouseEnter
+ );
+ this.contextMenuButtonRef.addEventListener(
+ "mouseleave",
+ this.onMenuButtonMouseLeave
+ );
+ }
+ }
+
+ componentWillUnmount() {
+ this.props.document.removeEventListener(
+ VISIBILITY_CHANGE_EVENT,
+ this.enableOrDisableAnimation
+ );
+
+ if (!this.props.Prefs.values["newNewtabExperience.enabled"]) {
+ this.contextMenuButtonRef.removeEventListener(
+ "mouseenter",
+ this.onMenuButtonMouseEnter
+ );
+ this.contextMenuButtonRef.removeEventListener(
+ "mouseleave",
+ this.onMenuButtonMouseLeave
+ );
+ }
+ }
+
+ enableOrDisableAnimation() {
+ // Only animate the collapse/expand for visible tabs.
+ const visible = this.props.document.visibilityState === VISIBLE;
+ if (this.state.enableAnimation !== visible) {
+ this.setState({ enableAnimation: visible });
+ }
+ }
+
+ onBodyMount(node) {
+ this.sectionBody = node;
+ }
+
+ collapseOrExpandSection() {
+ // If this.sectionBody is unset, it means that we're in some sort of error
+ // state, probably displaying the error fallback, so we won't be able to
+ // compute the height, and we don't want to persist the preference.
+ if (!this.sectionBody) {
+ return;
+ }
+
+ // Get the current height of the body so max-height transitions can work
+ this.setState({
+ isAnimating: true,
+ maxHeight: `${this._getSectionBodyHeight()}px`,
+ });
+ const { action } = SectionMenuOptions.CheckCollapsed(this.props);
+ this.props.dispatch(action);
+ }
+
+ onHeaderClick() {
+ // If the new new tab experience pref is turned on,
+ // sections should not be collapsible.
+ // If this.sectionBody is unset, it means that we're in some sort of error
+ // state, probably displaying the error fallback, so we won't be able to
+ // compute the height, and we don't want to persist the preference.
+ // If props.collapsed is undefined handler shouldn't do anything.
+ if (
+ this.props.Prefs.values["newNewtabExperience.enabled"] ||
+ !this.sectionBody ||
+ this.props.collapsed === undefined
+ ) {
+ return;
+ }
+
+ this.collapseOrExpandSection();
+ const { userEvent } = SectionMenuOptions.CheckCollapsed(this.props);
+ this.props.dispatch(
+ ac.UserEvent({
+ event: userEvent,
+ source: this.props.eventSource,
+ })
+ );
+ }
+
+ onKeyPress(event) {
+ if (event.key === "Enter" || event.key === " ") {
+ event.preventDefault();
+ this.onHeaderClick();
+ }
+ }
+
+ _getSectionBodyHeight() {
+ const div = this.sectionBody;
+ if (div.style.display === "none") {
+ // If the div isn't displayed, we can't get it's height. So we display it
+ // to get the height (it doesn't show up because max-height is set to 0px
+ // in CSS). We don't undo this because we are about to expand the section.
+ div.style.display = "block";
+ }
+ return div.scrollHeight;
+ }
+
+ onTransitionEnd(event) {
+ // Only update the animating state for our own transition (not a child's)
+ if (event.target === event.currentTarget) {
+ this.setState({ isAnimating: false });
+ }
+ }
+
+ renderIcon() {
+ const { icon } = this.props;
+ if (icon && icon.startsWith("moz-extension://")) {
+ return (
+ <span
+ className="icon icon-small-spacer"
+ style={{ backgroundImage: `url('${icon}')` }}
+ />
+ );
+ }
+ return (
+ <span
+ className={`icon icon-small-spacer icon-${icon || "webextension"}`}
+ />
+ );
+ }
+
+ onMenuButtonMouseEnter() {
+ this.setState({ menuButtonHover: true });
+ }
+
+ onMenuButtonMouseLeave() {
+ this.setState({ menuButtonHover: false });
+ }
+
+ onMenuUpdate(showContextMenu) {
+ this.setState({ showContextMenu });
+ }
+
+ render() {
+ const isCollapsible = this.props.collapsed !== undefined;
+ const isNewNewtabExperienceEnabled = this.props.Prefs.values[
+ "newNewtabExperience.enabled"
+ ];
+
+ // If new new tab prefs are set to true, sections should not be
+ // collapsible. Expand and make the section visible, if it has been
+ // previously collapsed.
+ if (isNewNewtabExperienceEnabled && this.props.collapsed) {
+ this.collapseOrExpandSection();
+ }
+
+ const {
+ enableAnimation,
+ isAnimating,
+ maxHeight,
+ menuButtonHover,
+ showContextMenu,
+ } = this.state;
+ const {
+ id,
+ eventSource,
+ collapsed,
+ learnMore,
+ title,
+ extraMenuOptions,
+ showPrefName,
+ privacyNoticeURL,
+ dispatch,
+ isFixed,
+ isFirst,
+ isLast,
+ isWebExtension,
+ } = this.props;
+ const active = menuButtonHover || showContextMenu;
+ let bodyStyle;
+ if (isAnimating && !collapsed) {
+ bodyStyle = { maxHeight };
+ } else if (!isAnimating && collapsed) {
+ bodyStyle = { display: "none" };
+ }
+ let titleStyle;
+ if (this.props.hideTitle) {
+ titleStyle = { visibility: "hidden" };
+ }
+ return (
+ <section
+ className={`collapsible-section ${this.props.className}${
+ enableAnimation ? " animation-enabled" : ""
+ }${collapsed ? " collapsed" : ""}${active ? " active" : ""}`}
+ aria-expanded={!collapsed}
+ // Note: data-section-id is used for web extension api tests in mozilla central
+ data-section-id={id}
+ >
+ <div className="section-top-bar">
+ <h3 className="section-title" style={titleStyle}>
+ <span className="click-target-container">
+ {/* Click-targets that toggle a collapsible section should have an aria-expanded attribute; see bug 1553234 */}
+ <span
+ className="click-target"
+ role="button"
+ tabIndex="0"
+ onKeyPress={this.onKeyPress}
+ onClick={this.onHeaderClick}
+ >
+ {!isNewNewtabExperienceEnabled && this.renderIcon()}
+ <FluentOrText message={title} />
+ {!isNewNewtabExperienceEnabled && isCollapsible && (
+ <span
+ data-l10n-id={
+ collapsed
+ ? "newtab-section-expand-section-label"
+ : "newtab-section-collapse-section-label"
+ }
+ className={`collapsible-arrow icon ${
+ collapsed
+ ? "icon-arrowhead-forward-small"
+ : "icon-arrowhead-down-small"
+ }`}
+ />
+ )}
+ </span>
+ <span className="learn-more-link-wrapper">
+ {learnMore && (
+ <span className="learn-more-link">
+ <FluentOrText message={learnMore.link.message}>
+ <a href={learnMore.link.href} />
+ </FluentOrText>
+ </span>
+ )}
+ </span>
+ </span>
+ </h3>
+ {!isNewNewtabExperienceEnabled && (
+ <div>
+ <ContextMenuButton
+ tooltip="newtab-menu-section-tooltip"
+ onUpdate={this.onMenuUpdate}
+ refFunction={this.setContextMenuButtonRef}
+ >
+ <SectionMenu
+ id={id}
+ extraOptions={extraMenuOptions}
+ source={eventSource}
+ showPrefName={showPrefName}
+ privacyNoticeURL={privacyNoticeURL}
+ collapsed={collapsed}
+ isFixed={isFixed}
+ isFirst={isFirst}
+ isLast={isLast}
+ dispatch={dispatch}
+ isWebExtension={isWebExtension}
+ />
+ </ContextMenuButton>
+ </div>
+ )}
+ </div>
+ <ErrorBoundary className="section-body-fallback">
+ <div
+ className={`section-body${isAnimating ? " animating" : ""}`}
+ onTransitionEnd={this.onTransitionEnd}
+ ref={this.onBodyMount}
+ style={bodyStyle}
+ >
+ {this.props.children}
+ </div>
+ </ErrorBoundary>
+ </section>
+ );
+ }
+}
+
+_CollapsibleSection.defaultProps = {
+ document: global.document || {
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ visibilityState: "hidden",
+ },
+};
+
+export const CollapsibleSection = connect(state => ({
+ Prefs: state.Prefs,
+}))(_CollapsibleSection);
diff --git a/browser/components/newtab/content-src/components/CollapsibleSection/_CollapsibleSection.scss b/browser/components/newtab/content-src/components/CollapsibleSection/_CollapsibleSection.scss
new file mode 100644
index 0000000000..89aacaccfb
--- /dev/null
+++ b/browser/components/newtab/content-src/components/CollapsibleSection/_CollapsibleSection.scss
@@ -0,0 +1,188 @@
+.outer-wrapper.newtab-experience {
+ .collapsible-section {
+ &[data-section-id='topsites'] {
+ .section-top-bar {
+ display: none;
+ }
+ }
+
+ .click-target-container {
+ .click-target {
+ span {
+ cursor: default;
+ font-weight: 600;
+ font-size: 17px;
+ color: var(--newtab-background-primary-text-color);
+ }
+ }
+ }
+ }
+}
+
+.outer-wrapper:not(.newtab-experience) {
+ .collapsible-section {
+ .section-title {
+ span {
+ vertical-align: middle;
+ }
+ }
+ }
+}
+
+.collapsible-section {
+ padding: $section-vertical-padding $section-horizontal-padding;
+ transition-delay: 100ms;
+ transition-duration: 100ms;
+ transition-property: background-color;
+
+ .section-title {
+ font-size: $section-title-font-size;
+ font-weight: bold;
+ margin: 0;
+
+ &.grey-title,
+ span {
+ color: var(--newtab-section-header-text-color);
+ display: inline-block;
+ fill: var(--newtab-section-header-text-color);
+ }
+
+ &.grey-title {
+ vertical-align: middle;
+ }
+
+ .click-target-container {
+ // Center "What's Pocket?" for "mobile" viewport
+ @media (max-width: $break-point-medium - 1) {
+ display: block;
+
+ .learn-more-link-wrapper {
+ display: block;
+ text-align: center;
+
+ .learn-more-link {
+ margin-inline-start: 0;
+ }
+ }
+ }
+
+ vertical-align: top;
+
+ .click-target {
+ white-space: nowrap;
+ cursor: pointer;
+ }
+ }
+
+ .collapsible-arrow {
+ margin-inline-start: 8px;
+ margin-top: -1px;
+ }
+ }
+
+ .section-top-bar {
+ min-height: 19px;
+ margin-bottom: 13px;
+ position: relative;
+
+ .context-menu-button {
+ background: url('chrome://global/skin/icons/more.svg') no-repeat right center;
+ border: 0;
+ cursor: pointer;
+ fill: var(--newtab-section-header-text-color);
+ height: 100%;
+ inset-inline-end: 0;
+ opacity: 0;
+ position: absolute;
+ top: 0;
+ transition-duration: 200ms;
+ transition-property: opacity;
+ width: $context-menu-button-size;
+
+ &:is(:active, :focus, :hover) {
+ fill: var(--newtab-section-header-text-color);
+ opacity: 1;
+ }
+ }
+
+ .context-menu {
+ top: 16px;
+ }
+
+ @media (max-width: $break-point-widest + $card-width * 1.5) {
+ @include context-menu-open-left;
+ }
+ }
+
+ &:hover,
+ &.active {
+ .section-top-bar {
+ .context-menu-button {
+ opacity: 1;
+ }
+ }
+ }
+
+ &.active {
+ background: var(--newtab-element-hover-color);
+ border-radius: 4px;
+
+ .section-top-bar {
+ .context-menu-button {
+ fill: var(--newtab-section-active-contextmenu-color);
+ }
+ }
+ }
+
+ .learn-more-link {
+ font-size: 11px;
+ margin-inline-start: 12px;
+
+ a {
+ color: var(--newtab-link-secondary-color);
+ }
+ }
+
+ .section-body-fallback {
+ height: $card-height;
+ }
+
+ .section-body {
+ // This is so the top sites favicon and card dropshadows don't get clipped during animation:
+ $horizontal-padding: 7px;
+ margin: 0 (-$horizontal-padding);
+ padding: 0 $horizontal-padding;
+
+ &.animating {
+ overflow: hidden;
+ pointer-events: none;
+ }
+ }
+
+ &.animation-enabled {
+ .section-title {
+ .collapsible-arrow {
+ transition: transform 0.5s $photon-easing;
+ }
+ }
+
+ .section-body {
+ transition: max-height 0.5s $photon-easing;
+ }
+ }
+
+ &.collapsed {
+ .section-body {
+ max-height: 0;
+ overflow: hidden;
+ }
+ }
+
+ // Hide first story card for the medium breakpoint to prevent orphaned third story
+ &[data-section-id='topstories'] .card-outer:first-child {
+ @media (min-width: $break-point-medium) and (max-width: $break-point-large - 1) {
+ display: none;
+ }
+ }
+}
+
diff --git a/browser/components/newtab/content-src/components/ComponentPerfTimer/ComponentPerfTimer.jsx b/browser/components/newtab/content-src/components/ComponentPerfTimer/ComponentPerfTimer.jsx
new file mode 100644
index 0000000000..169632c2c5
--- /dev/null
+++ b/browser/components/newtab/content-src/components/ComponentPerfTimer/ComponentPerfTimer.jsx
@@ -0,0 +1,174 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { actionCreators as ac, actionTypes as at } from "common/Actions.jsm";
+import { perfService as perfSvc } from "content-src/lib/perf-service";
+import React from "react";
+
+// Currently record only a fixed set of sections. This will prevent data
+// from custom sections from showing up or from topstories.
+const RECORDED_SECTIONS = ["highlights", "topsites"];
+
+export class ComponentPerfTimer extends React.Component {
+ constructor(props) {
+ super(props);
+ // Just for test dependency injection:
+ this.perfSvc = this.props.perfSvc || perfSvc;
+
+ this._sendBadStateEvent = this._sendBadStateEvent.bind(this);
+ this._sendPaintedEvent = this._sendPaintedEvent.bind(this);
+ this._reportMissingData = false;
+ this._timestampHandled = false;
+ this._recordedFirstRender = false;
+ }
+
+ componentDidMount() {
+ if (!RECORDED_SECTIONS.includes(this.props.id)) {
+ return;
+ }
+
+ this._maybeSendPaintedEvent();
+ }
+
+ componentDidUpdate() {
+ if (!RECORDED_SECTIONS.includes(this.props.id)) {
+ return;
+ }
+
+ this._maybeSendPaintedEvent();
+ }
+
+ /**
+ * Call the given callback after the upcoming frame paints.
+ *
+ * @note Both setTimeout and requestAnimationFrame are throttled when the page
+ * is hidden, so this callback may get called up to a second or so after the
+ * requestAnimationFrame "paint" for hidden tabs.
+ *
+ * Newtabs hidden while loading will presumably be fairly rare (other than
+ * preloaded tabs, which we will be filtering out on the server side), so such
+ * cases should get lost in the noise.
+ *
+ * If we decide that it's important to find out when something that's hidden
+ * has "painted", however, another option is to post a message to this window.
+ * That should happen even faster than setTimeout, and, at least as of this
+ * writing, it's not throttled in hidden windows in Firefox.
+ *
+ * @param {Function} callback
+ *
+ * @returns void
+ */
+ _afterFramePaint(callback) {
+ requestAnimationFrame(() => setTimeout(callback, 0));
+ }
+
+ _maybeSendBadStateEvent() {
+ // Follow up bugs:
+ // https://github.com/mozilla/activity-stream/issues/3691
+ if (!this.props.initialized) {
+ // Remember to report back when data is available.
+ this._reportMissingData = true;
+ } else if (this._reportMissingData) {
+ this._reportMissingData = false;
+ // Report how long it took for component to become initialized.
+ this._sendBadStateEvent();
+ }
+ }
+
+ _maybeSendPaintedEvent() {
+ // If we've already handled a timestamp, don't do it again.
+ if (this._timestampHandled || !this.props.initialized) {
+ return;
+ }
+
+ // And if we haven't, we're doing so now, so remember that. Even if
+ // something goes wrong in the callback, we can't try again, as we'd be
+ // sending back the wrong data, and we have to do it here, so that other
+ // calls to this method while waiting for the next frame won't also try to
+ // handle it.
+ this._timestampHandled = true;
+ this._afterFramePaint(this._sendPaintedEvent);
+ }
+
+ /**
+ * Triggered by call to render. Only first call goes through due to
+ * `_recordedFirstRender`.
+ */
+ _ensureFirstRenderTsRecorded() {
+ // Used as t0 for recording how long component took to initialize.
+ if (!this._recordedFirstRender) {
+ this._recordedFirstRender = true;
+ // topsites_first_render_ts, highlights_first_render_ts.
+ const key = `${this.props.id}_first_render_ts`;
+ this.perfSvc.mark(key);
+ }
+ }
+
+ /**
+ * Creates `SAVE_SESSION_PERF_DATA` with timestamp in ms
+ * of how much longer the data took to be ready for display than it would
+ * have been the ideal case.
+ * https://github.com/mozilla/ping-centre/issues/98
+ */
+ _sendBadStateEvent() {
+ // highlights_data_ready_ts, topsites_data_ready_ts.
+ const dataReadyKey = `${this.props.id}_data_ready_ts`;
+ this.perfSvc.mark(dataReadyKey);
+
+ try {
+ const firstRenderKey = `${this.props.id}_first_render_ts`;
+ // value has to be Int32.
+ const value = parseInt(
+ this.perfSvc.getMostRecentAbsMarkStartByName(dataReadyKey) -
+ this.perfSvc.getMostRecentAbsMarkStartByName(firstRenderKey),
+ 10
+ );
+ this.props.dispatch(
+ ac.OnlyToMain({
+ type: at.SAVE_SESSION_PERF_DATA,
+ // highlights_data_late_by_ms, topsites_data_late_by_ms.
+ data: { [`${this.props.id}_data_late_by_ms`]: value },
+ })
+ );
+ } catch (ex) {
+ // If this failed, it's likely because the `privacy.resistFingerprinting`
+ // pref is true.
+ }
+ }
+
+ _sendPaintedEvent() {
+ // Record first_painted event but only send if topsites.
+ if (this.props.id !== "topsites") {
+ return;
+ }
+
+ // topsites_first_painted_ts.
+ const key = `${this.props.id}_first_painted_ts`;
+ this.perfSvc.mark(key);
+
+ try {
+ const data = {};
+ data[key] = this.perfSvc.getMostRecentAbsMarkStartByName(key);
+
+ this.props.dispatch(
+ ac.OnlyToMain({
+ type: at.SAVE_SESSION_PERF_DATA,
+ data,
+ })
+ );
+ } catch (ex) {
+ // If this failed, it's likely because the `privacy.resistFingerprinting`
+ // pref is true. We should at least not blow up, and should continue
+ // to set this._timestampHandled to avoid going through this again.
+ }
+ }
+
+ render() {
+ if (RECORDED_SECTIONS.includes(this.props.id)) {
+ this._ensureFirstRenderTsRecorded();
+ this._maybeSendBadStateEvent();
+ }
+ return this.props.children;
+ }
+}
diff --git a/browser/components/newtab/content-src/components/ConfirmDialog/ConfirmDialog.jsx b/browser/components/newtab/content-src/components/ConfirmDialog/ConfirmDialog.jsx
new file mode 100644
index 0000000000..b2e80b8645
--- /dev/null
+++ b/browser/components/newtab/content-src/components/ConfirmDialog/ConfirmDialog.jsx
@@ -0,0 +1,103 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { actionCreators as ac, actionTypes } from "common/Actions.jsm";
+import { connect } from "react-redux";
+import React from "react";
+
+/**
+ * ConfirmDialog component.
+ * One primary action button, one cancel button.
+ *
+ * Content displayed is controlled by `data` prop the component receives.
+ * Example:
+ * data: {
+ * // Any sort of data needed to be passed around by actions.
+ * payload: site.url,
+ * // Primary button AlsoToMain action.
+ * action: "DELETE_HISTORY_URL",
+ * // Primary button USerEvent action.
+ * userEvent: "DELETE",
+ * // Array of locale ids to display.
+ * message_body: ["confirm_history_delete_p1", "confirm_history_delete_notice_p2"],
+ * // Text for primary button.
+ * confirm_button_string_id: "menu_action_delete"
+ * },
+ */
+export class _ConfirmDialog extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this._handleCancelBtn = this._handleCancelBtn.bind(this);
+ this._handleConfirmBtn = this._handleConfirmBtn.bind(this);
+ }
+
+ _handleCancelBtn() {
+ this.props.dispatch({ type: actionTypes.DIALOG_CANCEL });
+ this.props.dispatch(
+ ac.UserEvent({
+ event: actionTypes.DIALOG_CANCEL,
+ source: this.props.data.eventSource,
+ })
+ );
+ }
+
+ _handleConfirmBtn() {
+ this.props.data.onConfirm.forEach(this.props.dispatch);
+ }
+
+ _renderModalMessage() {
+ const message_body = this.props.data.body_string_id;
+
+ if (!message_body) {
+ return null;
+ }
+
+ return (
+ <span>
+ {message_body.map(msg => (
+ <p key={msg} data-l10n-id={msg} />
+ ))}
+ </span>
+ );
+ }
+
+ render() {
+ if (!this.props.visible) {
+ return null;
+ }
+
+ return (
+ <div className="confirmation-dialog">
+ <div
+ className="modal-overlay"
+ onClick={this._handleCancelBtn}
+ role="presentation"
+ />
+ <div className="modal">
+ <section className="modal-message">
+ {this.props.data.icon && (
+ <span
+ className={`icon icon-spacer icon-${this.props.data.icon}`}
+ />
+ )}
+ {this._renderModalMessage()}
+ </section>
+ <section className="actions">
+ <button
+ onClick={this._handleCancelBtn}
+ data-l10n-id={this.props.data.cancel_button_string_id}
+ />
+ <button
+ className="done"
+ onClick={this._handleConfirmBtn}
+ data-l10n-id={this.props.data.confirm_button_string_id}
+ />
+ </section>
+ </div>
+ </div>
+ );
+ }
+}
+
+export const ConfirmDialog = connect(state => state.Dialog)(_ConfirmDialog);
diff --git a/browser/components/newtab/content-src/components/ConfirmDialog/_ConfirmDialog.scss b/browser/components/newtab/content-src/components/ConfirmDialog/_ConfirmDialog.scss
new file mode 100644
index 0000000000..1bdb41dbb7
--- /dev/null
+++ b/browser/components/newtab/content-src/components/ConfirmDialog/_ConfirmDialog.scss
@@ -0,0 +1,68 @@
+.confirmation-dialog {
+ .modal {
+ box-shadow: 0 2px 2px 0 $black-10;
+ left: 0;
+ margin: auto;
+ position: fixed;
+ right: 0;
+ top: 20%;
+ width: 400px;
+ }
+
+ section {
+ margin: 0;
+ }
+
+ .modal-message {
+ display: flex;
+ padding: 16px;
+ padding-bottom: 0;
+
+ p {
+ margin: 0;
+ margin-bottom: 16px;
+ }
+ }
+
+ .actions {
+ border: 0;
+ display: flex;
+ flex-wrap: nowrap;
+ padding: 0 16px;
+
+ button {
+ margin-inline-end: 16px;
+ padding-inline-end: 18px;
+ padding-inline-start: 18px;
+ white-space: normal;
+ width: 50%;
+
+ &.done {
+ margin-inline-end: 0;
+ margin-inline-start: 0;
+ }
+ }
+ }
+
+ .icon {
+ margin-inline-end: 16px;
+ }
+}
+
+.modal-overlay {
+ background: var(--newtab-overlay-color);
+ height: 100%;
+ left: 0;
+ position: fixed;
+ top: 0;
+ width: 100%;
+ z-index: 11001;
+}
+
+.modal {
+ background: var(--newtab-modal-color);
+ border: $border-secondary;
+ border-radius: 5px;
+ font-size: 15px;
+ z-index: 11002;
+}
diff --git a/browser/components/newtab/content-src/components/ContextMenu/ContextMenu.jsx b/browser/components/newtab/content-src/components/ContextMenu/ContextMenu.jsx
new file mode 100644
index 0000000000..f2f3fde03f
--- /dev/null
+++ b/browser/components/newtab/content-src/components/ContextMenu/ContextMenu.jsx
@@ -0,0 +1,179 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import React from "react";
+import { connect } from "react-redux";
+
+export class ContextMenu extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.hideContext = this.hideContext.bind(this);
+ this.onShow = this.onShow.bind(this);
+ this.onClick = this.onClick.bind(this);
+ }
+
+ hideContext() {
+ this.props.onUpdate(false);
+ }
+
+ onShow() {
+ if (this.props.onShow) {
+ this.props.onShow();
+ }
+ }
+
+ componentDidMount() {
+ this.onShow();
+ setTimeout(() => {
+ global.addEventListener("click", this.hideContext);
+ }, 0);
+ }
+
+ componentWillUnmount() {
+ global.removeEventListener("click", this.hideContext);
+ }
+
+ onClick(event) {
+ // Eat all clicks on the context menu so they don't bubble up to window.
+ // This prevents the context menu from closing when clicking disabled items
+ // or the separators.
+ event.stopPropagation();
+ }
+
+ render() {
+ // Disabling focus on the menu span allows the first tab to focus on the first menu item instead of the wrapper.
+ return (
+ // eslint-disable-next-line jsx-a11y/interactive-supports-focus
+ <span className="context-menu">
+ <ul
+ role="menu"
+ onClick={this.onClick}
+ onKeyDown={this.onClick}
+ className="context-menu-list"
+ >
+ {this.props.options.map((option, i) =>
+ option.type === "separator" ? (
+ <li key={i} className="separator" role="separator" />
+ ) : (
+ option.type !== "empty" && (
+ <ContextMenuItem
+ key={i}
+ option={option}
+ hideContext={this.hideContext}
+ keyboardAccess={this.props.keyboardAccess}
+ />
+ )
+ )
+ )}
+ </ul>
+ </span>
+ );
+ }
+}
+
+export class _ContextMenuItem extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onClick = this.onClick.bind(this);
+ this.onKeyDown = this.onKeyDown.bind(this);
+ this.onKeyUp = this.onKeyUp.bind(this);
+ this.focusFirst = this.focusFirst.bind(this);
+ }
+
+ onClick(event) {
+ this.props.hideContext();
+ this.props.option.onClick(event);
+ }
+
+ // Focus the first menu item if the menu was accessed via the keyboard.
+ focusFirst(button) {
+ if (this.props.keyboardAccess && button) {
+ button.focus();
+ }
+ }
+
+ // This selects the correct node based on the key pressed
+ focusSibling(target, key) {
+ const parent = target.parentNode;
+ const closestSiblingSelector =
+ key === "ArrowUp" ? "previousSibling" : "nextSibling";
+ if (!parent[closestSiblingSelector]) {
+ return;
+ }
+ if (parent[closestSiblingSelector].firstElementChild) {
+ parent[closestSiblingSelector].firstElementChild.focus();
+ } else {
+ parent[closestSiblingSelector][
+ closestSiblingSelector
+ ].firstElementChild.focus();
+ }
+ }
+
+ onKeyDown(event) {
+ const { option } = this.props;
+ switch (event.key) {
+ case "Tab":
+ // tab goes down in context menu, shift + tab goes up in context menu
+ // if we're on the last item, one more tab will close the context menu
+ // similarly, if we're on the first item, one more shift + tab will close it
+ if (
+ (event.shiftKey && option.first) ||
+ (!event.shiftKey && option.last)
+ ) {
+ this.props.hideContext();
+ }
+ break;
+ case "ArrowUp":
+ case "ArrowDown":
+ event.preventDefault();
+ this.focusSibling(event.target, event.key);
+ break;
+ case "Enter":
+ case " ":
+ event.preventDefault();
+ this.props.hideContext();
+ option.onClick();
+ break;
+ case "Escape":
+ this.props.hideContext();
+ break;
+ }
+ }
+
+ // Prevents the default behavior of spacebar
+ // scrolling the page & auto-triggering buttons.
+ onKeyUp(event) {
+ if (event.key === " ") {
+ event.preventDefault();
+ }
+ }
+
+ render() {
+ const { option } = this.props;
+ const isNewNewtabExperienceEnabled = this.props.Prefs.values[
+ "newNewtabExperience.enabled"
+ ];
+ return (
+ <li role="presentation" className="context-menu-item">
+ <button
+ className={option.disabled ? "disabled" : ""}
+ role="menuitem"
+ onClick={this.onClick}
+ onKeyDown={this.onKeyDown}
+ onKeyUp={this.onKeyUp}
+ ref={option.first ? this.focusFirst : null}
+ >
+ {!isNewNewtabExperienceEnabled && option.icon && (
+ <span className={`icon icon-spacer icon-${option.icon}`} />
+ )}
+ <span data-l10n-id={option.string_id || option.id} />
+ </button>
+ </li>
+ );
+ }
+}
+
+export const ContextMenuItem = connect(state => ({
+ Prefs: state.Prefs,
+}))(_ContextMenuItem);
diff --git a/browser/components/newtab/content-src/components/ContextMenu/ContextMenuButton.jsx b/browser/components/newtab/content-src/components/ContextMenu/ContextMenuButton.jsx
new file mode 100644
index 0000000000..0364f5386a
--- /dev/null
+++ b/browser/components/newtab/content-src/components/ContextMenu/ContextMenuButton.jsx
@@ -0,0 +1,72 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import React from "react";
+
+export class ContextMenuButton extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.state = {
+ showContextMenu: false,
+ contextMenuKeyboard: false,
+ };
+ this.onClick = this.onClick.bind(this);
+ this.onKeyDown = this.onKeyDown.bind(this);
+ this.onUpdate = this.onUpdate.bind(this);
+ }
+
+ openContextMenu(isKeyBoard, event) {
+ if (this.props.onUpdate) {
+ this.props.onUpdate(true);
+ }
+ this.setState({
+ showContextMenu: true,
+ contextMenuKeyboard: isKeyBoard,
+ });
+ }
+
+ onClick(event) {
+ event.preventDefault();
+ this.openContextMenu(false, event);
+ }
+
+ onKeyDown(event) {
+ if (event.key === "Enter" || event.key === " ") {
+ event.preventDefault();
+ this.openContextMenu(true, event);
+ }
+ }
+
+ onUpdate(showContextMenu) {
+ if (this.props.onUpdate) {
+ this.props.onUpdate(showContextMenu);
+ }
+ this.setState({ showContextMenu });
+ }
+
+ render() {
+ const { tooltipArgs, tooltip, children, refFunction } = this.props;
+ const { showContextMenu, contextMenuKeyboard } = this.state;
+
+ return (
+ <React.Fragment>
+ <button
+ aria-haspopup="true"
+ data-l10n-id={tooltip}
+ data-l10n-args={tooltipArgs ? JSON.stringify(tooltipArgs) : null}
+ className="context-menu-button icon"
+ onKeyDown={this.onKeyDown}
+ onClick={this.onClick}
+ ref={refFunction}
+ />
+ {showContextMenu
+ ? React.cloneElement(children, {
+ keyboardAccess: contextMenuKeyboard,
+ onUpdate: this.onUpdate,
+ })
+ : null}
+ </React.Fragment>
+ );
+ }
+}
diff --git a/browser/components/newtab/content-src/components/ContextMenu/_ContextMenu.scss b/browser/components/newtab/content-src/components/ContextMenu/_ContextMenu.scss
new file mode 100644
index 0000000000..bf6e602de7
--- /dev/null
+++ b/browser/components/newtab/content-src/components/ContextMenu/_ContextMenu.scss
@@ -0,0 +1,55 @@
+.context-menu {
+ background: var(--newtab-contextmenu-background-color);
+ border-radius: $context-menu-border-radius;
+ box-shadow: $context-menu-shadow;
+ display: block;
+ font-size: $context-menu-font-size;
+ margin-inline-start: 5px;
+ inset-inline-start: 100%;
+ position: absolute;
+ top: ($context-menu-button-size / 4);
+ z-index: 8;
+
+ > ul {
+ list-style: none;
+ margin: 0;
+ padding: $context-menu-outer-padding 0;
+
+ > li {
+ margin: 0;
+ width: 100%;
+
+ &.separator {
+ border-bottom: $border-secondary;
+ margin: $context-menu-outer-padding 0;
+ }
+
+ > a,
+ > button {
+ align-items: center;
+ color: inherit;
+ cursor: pointer;
+ display: flex;
+ width: 100%;
+ line-height: 16px;
+ outline: none;
+ border: 0;
+ padding: $context-menu-item-padding;
+ white-space: nowrap;
+
+ &:is(:focus, :hover) {
+ background: var(--newtab-element-hover-color);
+ }
+
+ &:active {
+ background: var(--newtab-element-active-color);
+ }
+
+ &.disabled {
+ opacity: 0.4;
+ pointer-events: none;
+ }
+ }
+ }
+ }
+}
diff --git a/browser/components/newtab/content-src/components/CustomizeMenu/BackgroundsSection/BackgroundsSection.jsx b/browser/components/newtab/content-src/components/CustomizeMenu/BackgroundsSection/BackgroundsSection.jsx
new file mode 100644
index 0000000000..522ea6841f
--- /dev/null
+++ b/browser/components/newtab/content-src/components/CustomizeMenu/BackgroundsSection/BackgroundsSection.jsx
@@ -0,0 +1,11 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import React from "react";
+
+export class BackgroundsSection extends React.PureComponent {
+ render() {
+ return <div />;
+ }
+}
diff --git a/browser/components/newtab/content-src/components/CustomizeMenu/ContentSection/ContentSection.jsx b/browser/components/newtab/content-src/components/CustomizeMenu/ContentSection/ContentSection.jsx
new file mode 100644
index 0000000000..b6c8b43f51
--- /dev/null
+++ b/browser/components/newtab/content-src/components/CustomizeMenu/ContentSection/ContentSection.jsx
@@ -0,0 +1,277 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import React from "react";
+import { actionCreators as ac } from "common/Actions.jsm";
+
+export class ContentSection extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onPreferenceSelect = this.onPreferenceSelect.bind(this);
+ }
+
+ inputUserEvent(eventSource, status) {
+ this.props.dispatch(
+ ac.UserEvent({
+ event: "PREF_CHANGED",
+ source: eventSource,
+ value: { status, menu_source: "CUSTOMIZE_MENU" },
+ })
+ );
+ }
+
+ onPreferenceSelect(e) {
+ let prefName = e.target.getAttribute("preference");
+ const eventSource = e.target.getAttribute("eventSource");
+ let value;
+ if (e.target.nodeName === "SELECT") {
+ value = parseInt(e.target.value, 10);
+ } else if (e.target.nodeName === "INPUT") {
+ value = e.target.checked;
+ if (eventSource) {
+ this.inputUserEvent(eventSource, value);
+ }
+ }
+ this.props.setPref(prefName, value);
+ }
+
+ render() {
+ const {
+ topSitesEnabled,
+ pocketEnabled,
+ highlightsEnabled,
+ snippetsEnabled,
+ showSponsoredTopSitesEnabled,
+ showSponsoredPocketEnabled,
+ topSitesRowsCount,
+ } = this.props.enabledSections;
+
+ return (
+ <div className="home-section">
+ <div id="shortcuts-section" className="section">
+ <label className="switch">
+ <input
+ id="shortcuts-toggle"
+ checked={topSitesEnabled}
+ type="checkbox"
+ onChange={this.onPreferenceSelect}
+ preference="feeds.topsites"
+ aria-labelledby="custom-shortcuts-title"
+ aria-describedby="custom-shortcuts-subtitle"
+ eventSource="TOP_SITES"
+ />
+ <span className="slider" role="presentation"></span>
+ </label>
+ <div>
+ <h2 id="custom-shortcuts-title" className="title">
+ <label
+ htmlFor="shortcuts-toggle"
+ data-l10n-id="newtab-custom-shortcuts-title"
+ ></label>
+ </h2>
+ <p
+ id="custom-shortcuts-subtitle"
+ className="subtitle"
+ data-l10n-id="newtab-custom-shortcuts-subtitle"
+ ></p>
+ <div
+ className={`more-info-top-wrapper ${
+ topSitesEnabled ? "" : "shrink"
+ }`}
+ >
+ <div
+ className={`more-information ${
+ topSitesEnabled ? "expand" : "shrink"
+ }`}
+ >
+ <select
+ id="row-selector"
+ className="selector"
+ name="row-count"
+ preference="topSitesRows"
+ value={topSitesRowsCount}
+ onChange={this.onPreferenceSelect}
+ disabled={!topSitesEnabled}
+ aria-labelledby="custom-shortcuts-title"
+ >
+ <option
+ value="1"
+ data-l10n-id="newtab-custom-row-selector"
+ data-l10n-args='{"num": 1}'
+ />
+ <option
+ value="2"
+ data-l10n-id="newtab-custom-row-selector"
+ data-l10n-args='{"num": 2}'
+ />
+ <option
+ value="3"
+ data-l10n-id="newtab-custom-row-selector"
+ data-l10n-args='{"num": 3}'
+ />
+ <option
+ value="4"
+ data-l10n-id="newtab-custom-row-selector"
+ data-l10n-args='{"num": 4}'
+ />
+ </select>
+ {this.props.mayHaveSponsoredTopSites && (
+ <div className="check-wrapper" role="presentation">
+ <input
+ id="sponsored-shortcuts"
+ className="sponsored-checkbox"
+ disabled={!topSitesEnabled}
+ checked={showSponsoredTopSitesEnabled}
+ type="checkbox"
+ onChange={this.onPreferenceSelect}
+ preference="showSponsoredTopSites"
+ eventSource="SPONSORED_TOP_SITES"
+ />
+ <label
+ className="sponsored"
+ htmlFor="sponsored-shortcuts"
+ data-l10n-id="newtab-custom-sponsored-sites"
+ />
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ </div>
+
+ {this.props.pocketRegion && (
+ <div id="pocket-section" className="section">
+ <label className="switch">
+ <input
+ id="pocket-toggle"
+ checked={pocketEnabled}
+ type="checkbox"
+ onChange={this.onPreferenceSelect}
+ preference="feeds.section.topstories"
+ aria-labelledby="custom-pocket-title"
+ aria-describedby="custom-pocket-subtitle"
+ eventSource="TOP_STORIES"
+ />
+ <span className="slider" role="presentation"></span>
+ </label>
+ <div>
+ <h2 id="custom-pocket-title" className="title">
+ <label
+ htmlFor="pocket-toggle"
+ data-l10n-id="newtab-custom-pocket-title"
+ ></label>
+ </h2>
+ <p
+ id="custom-pocket-subtitle"
+ className="subtitle"
+ data-l10n-id="newtab-custom-pocket-subtitle"
+ />
+ {this.props.mayHaveSponsoredStories && (
+ <div
+ className={`more-info-pocket-wrapper ${
+ pocketEnabled ? "" : "shrink"
+ }`}
+ >
+ <div
+ className={`more-information ${
+ pocketEnabled ? "expand" : "shrink"
+ }`}
+ >
+ <div className="check-wrapper" role="presentation">
+ <input
+ id="sponsored-pocket"
+ className="sponsored-checkbox"
+ disabled={!pocketEnabled}
+ checked={showSponsoredPocketEnabled}
+ type="checkbox"
+ onChange={this.onPreferenceSelect}
+ preference="showSponsored"
+ eventSource="POCKET_SPOCS"
+ />
+ <label
+ className="sponsored"
+ htmlFor="sponsored-pocket"
+ data-l10n-id="newtab-custom-pocket-sponsored"
+ />
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ )}
+
+ <div id="recent-section" className="section">
+ <label className="switch">
+ <input
+ id="highlights-toggle"
+ checked={highlightsEnabled}
+ type="checkbox"
+ onChange={this.onPreferenceSelect}
+ preference="feeds.section.highlights"
+ eventSource="HIGHLIGHTS"
+ aria-labelledby="custom-recent-title"
+ aria-describedby="custom-recent-subtitle"
+ />
+ <span className="slider" role="presentation"></span>
+ </label>
+ <div>
+ <h2 id="custom-recent-title" className="title">
+ <label
+ htmlFor="highlights-toggle"
+ data-l10n-id="newtab-custom-recent-title"
+ ></label>
+ </h2>
+
+ <p
+ id="custom-recent-subtitle"
+ className="subtitle"
+ data-l10n-id="newtab-custom-recent-subtitle"
+ />
+ </div>
+ </div>
+
+ <div id="snippets-section" className="section">
+ <label className="switch">
+ <input
+ id="snippets-toggle"
+ checked={snippetsEnabled}
+ type="checkbox"
+ onChange={this.onPreferenceSelect}
+ preference="feeds.snippets"
+ aria-labelledby="custom-snippets-title"
+ aria-describedby="custom-snippets-subtitle"
+ eventSource="SNIPPETS"
+ />
+ <span className="slider" role="presentation"></span>
+ </label>
+ <div>
+ <h2 id="custom-snippets-title" className="title">
+ <label
+ htmlFor="snippets-toggle"
+ data-l10n-id="newtab-custom-snippets-title"
+ ></label>
+ </h2>
+ <p
+ id="custom-snippets-subtitle"
+ className="subtitle"
+ data-l10n-id="newtab-custom-snippets-subtitle"
+ />
+ </div>
+ </div>
+
+ <span className="divider" role="separator"></span>
+
+ <div>
+ <button
+ id="settings-link"
+ className="external-link"
+ onClick={this.props.openPreferences}
+ data-l10n-id="newtab-custom-settings"
+ />
+ </div>
+ </div>
+ );
+ }
+}
diff --git a/browser/components/newtab/content-src/components/CustomizeMenu/CustomizeMenu.jsx b/browser/components/newtab/content-src/components/CustomizeMenu/CustomizeMenu.jsx
new file mode 100644
index 0000000000..8e08efef2b
--- /dev/null
+++ b/browser/components/newtab/content-src/components/CustomizeMenu/CustomizeMenu.jsx
@@ -0,0 +1,38 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { ThemesSection } from "content-src/components/CustomizeMenu/ThemesSection/ThemesSection";
+import { BackgroundsSection } from "content-src/components/CustomizeMenu/BackgroundsSection/BackgroundsSection";
+import { ContentSection } from "content-src/components/CustomizeMenu/ContentSection/ContentSection";
+import { connect } from "react-redux";
+import React from "react";
+
+export class _CustomizeMenu extends React.PureComponent {
+ render() {
+ return (
+ <div className="customize-menu">
+ <button
+ onClick={this.props.onClose}
+ className="close-button"
+ data-l10n-id="newtab-custom-close-button"
+ />
+ <ThemesSection />
+ <BackgroundsSection />
+ <ContentSection
+ openPreferences={this.props.openPreferences}
+ setPref={this.props.setPref}
+ enabledSections={this.props.enabledSections}
+ pocketRegion={this.props.pocketRegion}
+ mayHaveSponsoredTopSites={this.props.mayHaveSponsoredTopSites}
+ mayHaveSponsoredStories={this.props.DiscoveryStream.config.show_spocs}
+ dispatch={this.props.dispatch}
+ />
+ </div>
+ );
+ }
+}
+
+export const CustomizeMenu = connect(state => ({
+ DiscoveryStream: state.DiscoveryStream,
+}))(_CustomizeMenu);
diff --git a/browser/components/newtab/content-src/components/CustomizeMenu/ThemesSection/ThemesSection.jsx b/browser/components/newtab/content-src/components/CustomizeMenu/ThemesSection/ThemesSection.jsx
new file mode 100644
index 0000000000..e220b93b00
--- /dev/null
+++ b/browser/components/newtab/content-src/components/CustomizeMenu/ThemesSection/ThemesSection.jsx
@@ -0,0 +1,11 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import React from "react";
+
+export class ThemesSection extends React.PureComponent {
+ render() {
+ return <div />;
+ }
+}
diff --git a/browser/components/newtab/content-src/components/CustomizeMenu/_CustomizeMenu.scss b/browser/components/newtab/content-src/components/CustomizeMenu/_CustomizeMenu.scss
new file mode 100644
index 0000000000..d4dfd37a9c
--- /dev/null
+++ b/browser/components/newtab/content-src/components/CustomizeMenu/_CustomizeMenu.scss
@@ -0,0 +1,297 @@
+
+.customize-menu {
+ color: var(--customize-menu-primary-text-color);
+ background-color: var(--customize-menu-background);
+ width: 432px;
+ height: 100%;
+ position: fixed;
+ inset-block: 0;
+ inset-inline-end: 0;
+ z-index: 1001;
+ padding: 16px;
+ transition: transform 250ms $customize-menu-slide-bezier;
+ overflow: auto;
+ transform: translateX(435px);
+ visibility: hidden;
+ cursor: default;
+
+ &:dir(rtl) {
+ transform: translateX(-435px);
+ }
+
+ &.customize-animate-enter-done {
+ transform: translateX(0);
+ }
+
+ &.customize-animate-enter-done,
+ &.customize-animate-enter-active,
+ &.customize-animate-enter {
+ box-shadow: 0 0 64px var(--customize-menu-first-shadow), 0 0 24px var(--customize-menu-second-shadow);
+ transition: transform 250ms $customize-menu-slide-bezier, visibility 1ms;
+ visibility: visible;
+ }
+
+ &.customize-animate-exit-active,
+ &.customize-animate-exit {
+ box-shadow: 0 0 64px var(--customize-menu-first-shadow), 0 0 24px var(--customize-menu-second-shadow);
+ transition: transform 250ms $customize-menu-slide-bezier, visibility 1ms 250ms;
+ visibility: visible;
+ }
+
+ &.customize-animate-exit-done {
+ transform: translateX(435px);
+ transition: transform 250ms $customize-menu-slide-bezier, visibility 1ms 250ms;
+
+ &:dir(rtl) {
+ transform: translateX(-435px);
+ }
+ }
+
+ .close-button {
+ margin-inline-start: auto;
+ margin-bottom: 28px;
+ white-space: nowrap;
+ display: block;
+ background-color: var(--customize-menu-secondary-action-background);
+ padding: 8px 10px;
+ border: $customize-menu-border-tint;
+ border-radius: 4px;
+ color: var(--customize-menu-primary-text-color);
+ font-size: 13px;
+ font-weight: 600;
+ }
+
+ .close-button:hover {
+ background-color: var(--customize-menu-secondary-action-background-hover);
+ }
+
+ .close-button:hover:active {
+ background-color: var(--customize-menu-secondary-action-background-active);
+ }
+}
+
+.grid-skip {
+ display: contents;
+}
+
+.home-section {
+ display: grid;
+ grid-template-columns: 1fr;
+ grid-template-rows: repeat(4, auto);
+ grid-row-gap: 32px;
+ padding: 0 16px;
+
+ .section {
+ display: grid;
+ grid-template-rows: auto;
+ grid-template-columns: auto 26px;
+
+ & > div {
+ grid-area: 1;
+ }
+
+ .title {
+ grid-column: 1 / -1;
+ margin: 0;
+ font-weight: 600;
+ font-size: 16px;
+ margin-bottom: 10px;
+ }
+
+ .subtitle {
+ margin: 0;
+ font-size: 14px;
+ }
+
+ .sponsored {
+ font-size: 14px;
+ margin-inline-start: 5px;
+ }
+
+ .check-wrapper {
+ position: relative;
+ }
+
+ .sponsored-checkbox {
+ margin-inline-start: 2px;
+ width: 16px;
+ height: 16px;
+ vertical-align: middle;
+ border: $customize-menu-border-tint;
+ box-sizing: border-box;
+ border-radius: 4px;
+ appearance: none;
+ background-color: var(--newtab-primary-action-background-off);
+ }
+
+ .sponsored-checkbox:checked {
+ -moz-context-properties: fill;
+ fill: var(--customize-menu-check-fill);
+ background: url('chrome://global/skin/icons/check.svg') center no-repeat;
+ background-color: var(--newtab-primary-action-background);
+ background-size: 10px;
+ }
+
+ .sponsored-checkbox:active + .checkmark {
+ fill: $newtab-card-tint;
+ }
+
+ .selector {
+ color: var(--customize-menu-primary-text-color);
+ width: 118px;
+ display: block;
+ border: 1px solid var(--customize-menu-line-color);
+ border-radius: 4px;
+ appearance: none;
+ padding-block: 7px;
+ padding-inline: 10px 13px;
+ margin-inline-start: 2px;
+ -moz-context-properties: fill;
+ fill: var(--customize-menu-primary-text-color);
+ background: url('#{$image-path}glyph-arrowhead-down-12.svg') right no-repeat;
+ background-size: 8px;
+ background-origin: content-box;
+ background-color: var(--customize-menu-background);
+
+ &:dir(rtl) {
+ background-position-x: left;
+ }
+ }
+
+ .switch {
+ position: relative;
+ display: inline-block;
+ width: 26px;
+ height: 16px;
+ grid-column: 2;
+ margin-top: 2px;
+ }
+
+ .switch input {
+ opacity: 0;
+ width: 0;
+ height: 0;
+ }
+
+ .slider {
+ position: absolute;
+ inset: 0;
+ transition: transform 250ms;
+ border-radius: 13px;
+ border: $customize-menu-border-tint;
+ background-color: var(--newtab-primary-action-background-off);
+
+ &::before {
+ position: absolute;
+ content: '';
+ height: 8px;
+ width: 8px;
+ inset-inline-start: 3px;
+ bottom: 3px;
+ background-color: var(--customize-menu-primary-action-text);
+ transition: transform 250ms;
+ border-radius: 50%;
+ outline: $customize-menu-border-tint;
+ -moz-outline-radius: 11px;
+ }
+ }
+
+ .switch input:focus-visible + .slider {
+ border: 1px solid var(--newtab-focus-border-selected);
+ outline: 0;
+ box-shadow: 0 0 0 2px var(--newtab-focus-outline);
+ }
+
+ .switch input:not(:checked):focus-visible + .slider {
+ border: 1px solid var(--newtab-focus-border);
+ }
+
+ input:checked + .slider {
+ background-color: var(--newtab-primary-action-background);
+ }
+
+ input:checked + .slider::before {
+ transform: translateX(10px);
+ }
+
+ input:checked + .slider:dir(rtl)::before {
+ transform: translateX(-10px);
+ }
+
+ .more-info-top-wrapper,
+ .more-info-pocket-wrapper {
+ margin-inline-start: -2px;
+ overflow: hidden;
+ transition: max-height 250ms $customize-menu-expand-bezier;
+
+ &.shrink {
+ max-height: 0;
+ }
+
+ .more-information {
+ padding-top: 12px;
+ position: relative;
+ transition: top 250ms $customize-menu-expand-bezier;
+ }
+
+ .more-information.expand {
+ top: 0;
+ }
+ }
+
+ .more-info-top-wrapper {
+ max-height: 78px;
+
+ .more-information {
+ top: -77px;
+ }
+
+ .check-wrapper {
+ margin-top: 10px;
+ }
+ }
+
+ .more-info-pocket-wrapper {
+ max-height: 35px;
+
+ .more-information {
+ top: -35px;
+ }
+ }
+ }
+
+ .divider {
+ border-top: 1px var(--customize-menu-seperator-line-color) solid;
+ margin: 0 -16px;
+ }
+
+ .external-link {
+ font-size: 14px;
+ cursor: pointer;
+ border: 1px solid transparent;
+ border-radius: 4px;
+ -moz-context-properties: fill;
+ fill: var(--customize-menu-primary-text-color);
+ background: url('chrome://global/skin/icons/settings.svg') left no-repeat;
+ background-size: 16px;
+ padding-inline-start: 21px;
+ margin-bottom: 20px;
+
+ &:dir(rtl) {
+ background-position-x: right;
+ }
+ }
+
+ .external-link:hover {
+ text-decoration: underline;
+ }
+}
+
+.home-section .section .sponsored-checkbox:focus-visible,
+.selector:focus-visible,
+.external-link:focus-visible,
+.close-button:focus-visible {
+ border: 1px solid var(--newtab-focus-border);
+ outline: 0;
+ box-shadow: 0 0 0 2px var(--newtab-focus-outline);
+}
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamBase/DiscoveryStreamBase.jsx b/browser/components/newtab/content-src/components/DiscoveryStreamBase/DiscoveryStreamBase.jsx
new file mode 100644
index 0000000000..590223a981
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamBase/DiscoveryStreamBase.jsx
@@ -0,0 +1,393 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { CardGrid } from "content-src/components/DiscoveryStreamComponents/CardGrid/CardGrid";
+import { CollectionCardGrid } from "content-src/components/DiscoveryStreamComponents/CollectionCardGrid/CollectionCardGrid";
+import { CollapsibleSection } from "content-src/components/CollapsibleSection/CollapsibleSection";
+import { connect } from "react-redux";
+import { DSMessage } from "content-src/components/DiscoveryStreamComponents/DSMessage/DSMessage";
+import { DSPrivacyModal } from "content-src/components/DiscoveryStreamComponents/DSPrivacyModal/DSPrivacyModal";
+import { DSSignup } from "content-src/components/DiscoveryStreamComponents/DSSignup/DSSignup";
+import { DSTextPromo } from "content-src/components/DiscoveryStreamComponents/DSTextPromo/DSTextPromo";
+import { Hero } from "content-src/components/DiscoveryStreamComponents/Hero/Hero";
+import { Highlights } from "content-src/components/DiscoveryStreamComponents/Highlights/Highlights";
+import { HorizontalRule } from "content-src/components/DiscoveryStreamComponents/HorizontalRule/HorizontalRule";
+import { List } from "content-src/components/DiscoveryStreamComponents/List/List";
+import { Navigation } from "content-src/components/DiscoveryStreamComponents/Navigation/Navigation";
+import React from "react";
+import { SectionTitle } from "content-src/components/DiscoveryStreamComponents/SectionTitle/SectionTitle";
+import { selectLayoutRender } from "content-src/lib/selectLayoutRender";
+import { TopSites } from "content-src/components/DiscoveryStreamComponents/TopSites/TopSites";
+
+const ALLOWED_CSS_URL_PREFIXES = [
+ "chrome://",
+ "resource://",
+ "https://img-getpocket.cdn.mozilla.net/",
+];
+const DUMMY_CSS_SELECTOR = "DUMMY#CSS.SELECTOR";
+
+/**
+ * Validate a CSS declaration. The values are assumed to be normalized by CSSOM.
+ */
+export function isAllowedCSS(property, value) {
+ // Bug 1454823: INTERNAL properties, e.g., -moz-context-properties, are
+ // exposed but their values aren't resulting in getting nothing. Fortunately,
+ // we don't care about validating the values of the current set of properties.
+ if (value === undefined) {
+ return true;
+ }
+
+ // Make sure all urls are of the allowed protocols/prefixes
+ const urls = value.match(/url\("[^"]+"\)/g);
+ return (
+ !urls ||
+ urls.every(url =>
+ ALLOWED_CSS_URL_PREFIXES.some(prefix => url.slice(5).startsWith(prefix))
+ )
+ );
+}
+
+export class _DiscoveryStreamBase extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onStyleMount = this.onStyleMount.bind(this);
+ }
+
+ onStyleMount(style) {
+ // Unmounting style gets rid of old styles, so nothing else to do
+ if (!style) {
+ return;
+ }
+
+ const { sheet } = style;
+ const styles = JSON.parse(style.dataset.styles);
+ styles.forEach((row, rowIndex) => {
+ row.forEach((component, componentIndex) => {
+ // Nothing to do without optional styles overrides
+ if (!component) {
+ return;
+ }
+
+ Object.entries(component).forEach(([selectors, declarations]) => {
+ // Start with a dummy rule to validate declarations and selectors
+ sheet.insertRule(`${DUMMY_CSS_SELECTOR} {}`);
+ const [rule] = sheet.cssRules;
+
+ // Validate declarations and remove any offenders. CSSOM silently
+ // discards invalid entries, so here we apply extra restrictions.
+ rule.style = declarations;
+ [...rule.style].forEach(property => {
+ const value = rule.style[property];
+ if (!isAllowedCSS(property, value)) {
+ console.error(`Bad CSS declaration ${property}: ${value}`); // eslint-disable-line no-console
+ rule.style.removeProperty(property);
+ }
+ });
+
+ // Set the actual desired selectors scoped to the component
+ const prefix = `.ds-layout > .ds-column:nth-child(${rowIndex +
+ 1}) .ds-column-grid > :nth-child(${componentIndex + 1})`;
+ // NB: Splitting on "," doesn't work with strings with commas, but
+ // we're okay with not supporting those selectors
+ rule.selectorText = selectors
+ .split(",")
+ .map(
+ selector =>
+ prefix +
+ // Assume :pseudo-classes are for component instead of descendant
+ (selector[0] === ":" ? "" : " ") +
+ selector
+ )
+ .join(",");
+
+ // CSSOM silently ignores bad selectors, so we'll be noisy instead
+ if (rule.selectorText === DUMMY_CSS_SELECTOR) {
+ console.error(`Bad CSS selector ${selectors}`); // eslint-disable-line no-console
+ }
+ });
+ });
+ });
+ }
+
+ renderComponent(component, embedWidth) {
+ const ENGAGEMENT_LABEL_ENABLED = this.props.Prefs.values[
+ `discoverystream.engagementLabelEnabled`
+ ];
+
+ switch (component.type) {
+ case "Highlights":
+ return <Highlights />;
+ case "TopSites":
+ let promoAlignment;
+ if (
+ component.spocs &&
+ component.spocs.positions &&
+ component.spocs.positions.length
+ ) {
+ promoAlignment =
+ component.spocs.positions[0].index === 0 ? "left" : "right";
+ }
+ return (
+ <TopSites
+ header={component.header}
+ data={component.data}
+ promoAlignment={promoAlignment}
+ />
+ );
+ case "TextPromo":
+ return (
+ <DSTextPromo
+ dispatch={this.props.dispatch}
+ type={component.type}
+ data={component.data}
+ />
+ );
+ case "Signup":
+ return (
+ <DSSignup
+ dispatch={this.props.dispatch}
+ type={component.type}
+ data={component.data}
+ />
+ );
+ case "Message":
+ return (
+ <DSMessage
+ title={component.header && component.header.title}
+ subtitle={component.header && component.header.subtitle}
+ link_text={component.header && component.header.link_text}
+ link_url={component.header && component.header.link_url}
+ icon={component.header && component.header.icon}
+ />
+ );
+ case "SectionTitle":
+ return <SectionTitle header={component.header} />;
+ case "Navigation":
+ return (
+ <Navigation
+ dispatch={this.props.dispatch}
+ links={component.properties.links}
+ alignment={component.properties.alignment}
+ display_variant={component.properties.display_variant}
+ explore_topics={component.properties.explore_topics}
+ header={component.header}
+ />
+ );
+ case "CollectionCardGrid":
+ const { DiscoveryStream } = this.props;
+ return (
+ <CollectionCardGrid
+ data={component.data}
+ feed={component.feed}
+ spocs={DiscoveryStream.spocs}
+ placement={component.placement}
+ border={component.properties.border}
+ type={component.type}
+ items={component.properties.items}
+ cta_variant={component.cta_variant}
+ display_engagement_labels={ENGAGEMENT_LABEL_ENABLED}
+ dismissible={this.props.DiscoveryStream.isCollectionDismissible}
+ dispatch={this.props.dispatch}
+ />
+ );
+ case "CardGrid":
+ return (
+ <CardGrid
+ enable_video_playheads={
+ !!component.properties.enable_video_playheads
+ }
+ title={component.header && component.header.title}
+ display_variant={component.properties.display_variant}
+ data={component.data}
+ feed={component.feed}
+ border={component.properties.border}
+ type={component.type}
+ dispatch={this.props.dispatch}
+ items={component.properties.items}
+ cta_variant={component.cta_variant}
+ display_engagement_labels={ENGAGEMENT_LABEL_ENABLED}
+ />
+ );
+ case "Hero":
+ return (
+ <Hero
+ subComponentType={embedWidth >= 9 ? `cards` : `list`}
+ feed={component.feed}
+ title={component.header && component.header.title}
+ data={component.data}
+ border={component.properties.border}
+ type={component.type}
+ dispatch={this.props.dispatch}
+ items={component.properties.items}
+ />
+ );
+ case "HorizontalRule":
+ return <HorizontalRule />;
+ case "List":
+ return (
+ <List
+ data={component.data}
+ feed={component.feed}
+ fullWidth={component.properties.full_width}
+ hasBorders={component.properties.border === "border"}
+ hasImages={component.properties.has_images}
+ hasNumbers={component.properties.has_numbers}
+ items={component.properties.items}
+ type={component.type}
+ header={component.header}
+ />
+ );
+ default:
+ return <div>{component.type}</div>;
+ }
+ }
+
+ renderStyles(styles) {
+ // Use json string as both the key and styles to render so React knows when
+ // to unmount and mount a new instance for new styles.
+ const json = JSON.stringify(styles);
+ return <style key={json} data-styles={json} ref={this.onStyleMount} />;
+ }
+
+ render() {
+ // Select layout render data by adding spocs and position to recommendations
+ const { layoutRender } = selectLayoutRender({
+ state: this.props.DiscoveryStream,
+ prefs: this.props.Prefs.values,
+ locale: this.props.locale,
+ });
+ const { config } = this.props.DiscoveryStream;
+
+ // Allow rendering without extracting special components
+ if (!config.collapsible) {
+ return this.renderLayout(layoutRender);
+ }
+
+ // Find the first component of a type and remove it from layout
+ const extractComponent = type => {
+ for (const [rowIndex, row] of Object.entries(layoutRender)) {
+ for (const [index, component] of Object.entries(row.components)) {
+ if (component.type === type) {
+ // Remove the row if it was the only component or the single item
+ if (row.components.length === 1) {
+ layoutRender.splice(rowIndex, 1);
+ } else {
+ row.components.splice(index, 1);
+ }
+ return component;
+ }
+ }
+ }
+ return null;
+ };
+
+ // Get "topstories" Section state for default values
+ const topStories = this.props.Sections.find(s => s.id === "topstories");
+
+ if (!topStories) {
+ return null;
+ }
+
+ // Extract TopSites to render before the rest and Message to use for header
+ const topSites = extractComponent("TopSites");
+ const sponsoredCollection = extractComponent("CollectionCardGrid");
+ const message = extractComponent("Message") || {
+ header: {
+ link_text: topStories.learnMore.link.message,
+ link_url: topStories.learnMore.link.href,
+ title: topStories.title,
+ },
+ };
+
+ // Render a DS-style TopSites then the rest if any in a collapsible section
+ return (
+ <React.Fragment>
+ {this.props.DiscoveryStream.isPrivacyInfoModalVisible && (
+ <DSPrivacyModal dispatch={this.props.dispatch} />
+ )}
+ {topSites &&
+ this.renderLayout([
+ {
+ width: 12,
+ components: [topSites],
+ },
+ ])}
+ {sponsoredCollection &&
+ this.renderLayout([
+ {
+ width: 12,
+ components: [sponsoredCollection],
+ },
+ ])}
+ {!!layoutRender.length && (
+ <CollapsibleSection
+ className="ds-layout"
+ collapsed={topStories.pref.collapsed}
+ dispatch={this.props.dispatch}
+ icon={topStories.icon}
+ id={topStories.id}
+ isFixed={true}
+ learnMore={{
+ link: {
+ href: message.header.link_url,
+ message: message.header.link_text,
+ },
+ }}
+ privacyNoticeURL={topStories.privacyNoticeURL}
+ showPrefName={topStories.pref.feed}
+ title={message.header.title}
+ eventSource="CARDGRID"
+ >
+ {this.renderLayout(layoutRender)}
+ </CollapsibleSection>
+ )}
+ {this.renderLayout([
+ {
+ width: 12,
+ components: [{ type: "Highlights" }],
+ },
+ ])}
+ </React.Fragment>
+ );
+ }
+
+ renderLayout(layoutRender) {
+ const styles = [];
+ return (
+ <div className="discovery-stream ds-layout">
+ {layoutRender.map((row, rowIndex) => (
+ <div
+ key={`row-${rowIndex}`}
+ className={`ds-column ds-column-${row.width}`}
+ >
+ <div className="ds-column-grid">
+ {row.components.map((component, componentIndex) => {
+ if (!component) {
+ return null;
+ }
+ styles[rowIndex] = [
+ ...(styles[rowIndex] || []),
+ component.styles,
+ ];
+ return (
+ <div key={`component-${componentIndex}`}>
+ {this.renderComponent(component, row.width)}
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ ))}
+ {this.renderStyles(styles)}
+ </div>
+ );
+ }
+}
+
+export const DiscoveryStreamBase = connect(state => ({
+ DiscoveryStream: state.DiscoveryStream,
+ Prefs: state.Prefs,
+ Sections: state.Sections,
+ document: global.document,
+}))(_DiscoveryStreamBase);
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamBase/_DiscoveryStreamBase.scss b/browser/components/newtab/content-src/components/DiscoveryStreamBase/_DiscoveryStreamBase.scss
new file mode 100644
index 0000000000..7626ebbd45
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamBase/_DiscoveryStreamBase.scss
@@ -0,0 +1,70 @@
+$ds-width: 936px;
+
+.discovery-stream.ds-layout {
+ $columns: 12;
+ --gridColumnGap: 48px;
+ --gridRowGap: 24px;
+ grid-template-columns: repeat($columns, 1fr);
+ grid-column-gap: var(--gridColumnGap);
+ grid-row-gap: var(--gridRowGap);
+ margin: 0 auto;
+
+ @while $columns > 0 {
+ .ds-column-#{$columns} {
+ grid-column-start: auto;
+ grid-column-end: span $columns;
+ }
+
+ $columns: $columns - 1;
+ }
+
+ .ds-column-grid {
+ display: grid;
+ grid-row-gap: var(--gridRowGap);
+
+ // We want to completely hide components with no content,
+ // otherwise, it creates grid-row-gap gaps around nothing.
+ > div:empty {
+ display: none;
+ }
+ }
+}
+
+.ds-header {
+ margin: 8px 0;
+
+ .ds-context {
+ font-weight: 400;
+ }
+}
+
+.ds-header,
+.ds-layout .section-title span {
+ @include dark-theme-only {
+ color: $grey-30;
+ }
+
+ color: $grey-50;
+ font-size: 13px;
+ font-weight: 600;
+ line-height: 20px;
+
+ .icon {
+ fill: var(--newtab-text-secondary-color);
+ }
+}
+
+.collapsible-section.ds-layout {
+ margin: auto;
+
+ .section-top-bar {
+ .learn-more-link a {
+ color: var(--newtab-link-primary-color);
+ font-weight: normal;
+
+ &:is(:focus, :hover) {
+ text-decoration: underline;
+ }
+ }
+ }
+}
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamComponents/CardGrid/CardGrid.jsx b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/CardGrid/CardGrid.jsx
new file mode 100644
index 0000000000..6734d8d00c
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/CardGrid/CardGrid.jsx
@@ -0,0 +1,109 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { DSCard, PlaceholderDSCard } from "../DSCard/DSCard.jsx";
+import { DSEmptyState } from "../DSEmptyState/DSEmptyState.jsx";
+import { FluentOrText } from "../../FluentOrText/FluentOrText.jsx";
+import React from "react";
+
+export class CardGrid extends React.PureComponent {
+ renderCards() {
+ const recs = this.props.data.recommendations.slice(0, this.props.items);
+ const cards = [];
+
+ for (let index = 0; index < this.props.items; index++) {
+ const rec = recs[index];
+ cards.push(
+ !rec || rec.placeholder ? (
+ <PlaceholderDSCard key={`dscard-${index}`} />
+ ) : (
+ <DSCard
+ key={`dscard-${rec.id}`}
+ pos={rec.pos}
+ flightId={rec.flight_id}
+ image_src={rec.image_src}
+ raw_image_src={rec.raw_image_src}
+ title={rec.title}
+ excerpt={rec.excerpt}
+ url={rec.url}
+ id={rec.id}
+ shim={rec.shim}
+ type={this.props.type}
+ context={rec.context}
+ sponsor={rec.sponsor}
+ sponsored_by_override={rec.sponsored_by_override}
+ dispatch={this.props.dispatch}
+ source={rec.domain}
+ pocket_id={rec.pocket_id}
+ context_type={rec.context_type}
+ bookmarkGuid={rec.bookmarkGuid}
+ engagement={rec.engagement}
+ display_engagement_labels={this.props.display_engagement_labels}
+ cta={rec.cta}
+ cta_variant={this.props.cta_variant}
+ is_video={this.props.enable_video_playheads && rec.is_video}
+ is_collection={this.props.is_collection}
+ />
+ )
+ );
+ }
+
+ // Used for CSS overrides to default styling (eg: "hero")
+ const variantClass = this.props.display_variant
+ ? `ds-card-grid-${this.props.display_variant}`
+ : ``;
+
+ return (
+ <div
+ className={`ds-card-grid ds-card-grid-${this.props.border} ${variantClass}`}
+ >
+ {cards}
+ </div>
+ );
+ }
+
+ render() {
+ const { data } = this.props;
+
+ // Handle a render before feed has been fetched by displaying nothing
+ if (!data) {
+ return null;
+ }
+
+ // Handle the case where a user has dismissed all recommendations
+ const isEmpty = data.recommendations.length === 0;
+
+ return (
+ <div>
+ {this.props.title && (
+ <div className="ds-header">
+ <div className="title">{this.props.title}</div>
+ {this.props.context && (
+ <FluentOrText message={this.props.context}>
+ <div className="ds-context" />
+ </FluentOrText>
+ )}
+ </div>
+ )}
+ {isEmpty ? (
+ <div className="ds-card-grid empty">
+ <DSEmptyState
+ status={data.status}
+ dispatch={this.props.dispatch}
+ feed={this.props.feed}
+ />
+ </div>
+ ) : (
+ this.renderCards()
+ )}
+ </div>
+ );
+ }
+}
+
+CardGrid.defaultProps = {
+ border: `border`,
+ items: 4, // Number of stories to display
+ enable_video_playheads: false,
+};
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamComponents/CardGrid/_CardGrid.scss b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/CardGrid/_CardGrid.scss
new file mode 100644
index 0000000000..3eed3a70b5
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/CardGrid/_CardGrid.scss
@@ -0,0 +1,164 @@
+$col4-header-line-height: 20;
+$col4-header-font-size: 14;
+
+// Special styling for the New Tab Experience styles,
+// This is to be incorporated once the styles are made permanent
+.outer-wrapper.newtab-experience {
+ .ds-card-grid {
+ &.ds-card-grid-border {
+ .ds-card:not(.placeholder) {
+ border-radius: $border-radius-new;
+ box-shadow: 0 3px 8px var(--newtab-card-first-shadow), 0 0 2px var(--newtab-card-second-shadow);
+
+ .img-wrapper .img img {
+ border-radius: $border-radius-new $border-radius-new 0 0;
+ }
+ }
+ }
+
+ .ds-card-link:focus {
+ @include ds-focus-nte;
+ transition: none;
+ border-radius: $border-radius-new;
+ }
+ }
+}
+
+.ds-card-grid {
+ display: grid;
+ grid-gap: 24px;
+
+ .ds-card {
+ @include dark-theme-only {
+ background: none;
+ }
+
+ background: $white;
+ border-radius: 4px;
+ }
+
+ .ds-column-12 &.ds-card-grid-hero {
+ @media (min-width: $break-point-large) {
+ grid-template-columns: repeat(12, 1fr);
+
+ // "hero"
+ .ds-card:nth-child(1) {
+ grid-column-start: 1;
+ grid-column-end: span 6;
+ grid-row-start: 1;
+ grid-row-end: span 2;
+
+ .excerpt {
+ -webkit-line-clamp: 4;
+ }
+ }
+
+ .ds-card:nth-child(2),
+ .ds-card:nth-child(4) {
+ grid-column-start: 7;
+ grid-column-end: span 3;
+ }
+
+ .ds-card:nth-child(3),
+ .ds-card:nth-child(5) {
+ grid-column-start: 10;
+ grid-column-end: span 3;
+ }
+
+ // "small" cards
+ .ds-card:nth-child(n+2):nth-child(-n+5) {
+ .excerpt {
+ display: none;
+ }
+
+ .meta {
+ padding: 8px;
+
+ .title {
+ font-size: 13px;
+ line-height: 19px;
+ }
+
+ .story-sponsored-label {
+ -webkit-line-clamp: none;
+ line-height: 19px;
+ }
+ }
+ }
+
+ .ds-card:nth-child(n+6) {
+ grid-column-start: auto;
+ grid-column-end: span 4;
+ }
+ }
+
+ @media (min-width: $break-point-widest) {
+ // "small" cards
+ .ds-card:nth-child(n+2):nth-child(-n+5) {
+ min-height: 222px;
+ }
+ }
+ }
+
+ &.ds-card-grid-border {
+ .ds-card:not(.placeholder) {
+ @include dark-theme-only {
+ box-shadow: 0 1px 4px $shadow-10;
+ background: $grey-70;
+ }
+
+ box-shadow: 0 1px 4px 0 $grey-90-10;
+
+ .img-wrapper .img img {
+ border-radius: 4px 4px 0 0;
+ }
+ }
+ }
+
+ &.ds-card-grid-no-border {
+ .ds-card {
+ background: none;
+
+ .meta {
+ padding: 12px 0;
+ }
+ }
+ }
+
+ // "2/3 width layout"
+ .ds-column-5 &,
+ .ds-column-6 &,
+ .ds-column-7 &,
+ .ds-column-8 & {
+ grid-template-columns: repeat(2, 1fr);
+ }
+
+ // "Full width layout"
+ .ds-column-9 &,
+ .ds-column-10 &,
+ .ds-column-11 &,
+ .ds-column-12 & {
+ grid-template-columns: repeat(1, 1fr);
+
+ @media (min-width: $break-point-medium) {
+ grid-template-columns: repeat(2, 1fr);
+ }
+
+ @media (min-width: $break-point-large) {
+ grid-template-columns: repeat(3, 1fr);
+ }
+
+ .title {
+ font-size: 17px;
+ line-height: 24px;
+ }
+
+ .excerpt {
+ @include limit-visible-lines(3, 24, 15);
+ }
+ }
+
+ &.empty {
+ grid-template-columns: auto;
+ }
+}
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamComponents/CollectionCardGrid/CollectionCardGrid.jsx b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/CollectionCardGrid/CollectionCardGrid.jsx
new file mode 100644
index 0000000000..fa7b2b7b4f
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/CollectionCardGrid/CollectionCardGrid.jsx
@@ -0,0 +1,139 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { actionCreators as ac } from "common/Actions.jsm";
+import { CardGrid } from "content-src/components/DiscoveryStreamComponents/CardGrid/CardGrid";
+import { DSDismiss } from "content-src/components/DiscoveryStreamComponents/DSDismiss/DSDismiss";
+import { LinkMenuOptions } from "content-src/lib/link-menu-options";
+import React from "react";
+
+export class CollectionCardGrid extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onDismissClick = this.onDismissClick.bind(this);
+ this.state = {
+ dismissed: false,
+ };
+ }
+
+ onDismissClick() {
+ const { data } = this.props;
+ if (this.props.dispatch && data && data.spocs && data.spocs.length) {
+ this.setState({
+ dismissed: true,
+ });
+ const pos = 0;
+ const source = this.props.type.toUpperCase();
+ // Grab the available items in the array to dismiss.
+ // This fires a ping for all items available, even if below the fold.
+ const spocsData = data.spocs.map(item => ({
+ url: item.url,
+ guid: item.id,
+ shim: item.shim,
+ flight_id: item.flightId,
+ }));
+
+ const blockUrlOption = LinkMenuOptions.BlockUrls(spocsData, pos, source);
+ const { action, impression, userEvent } = blockUrlOption;
+ this.props.dispatch(action);
+
+ this.props.dispatch(
+ ac.UserEvent({
+ event: userEvent,
+ source,
+ action_position: pos,
+ })
+ );
+ if (impression) {
+ this.props.dispatch(impression);
+ }
+ }
+ }
+
+ render() {
+ const { data, dismissible } = this.props;
+ if (
+ this.state.dismissed ||
+ !data ||
+ !data.spocs ||
+ !data.spocs[0] ||
+ // We only display complete collections.
+ data.spocs.length < 3
+ ) {
+ return null;
+ }
+ const { spocs, placement, feed } = this.props;
+ // spocs.data is spocs state data, and not an array of spocs.
+ const { title, context, sponsored_by_override, sponsor } =
+ spocs.data[placement.name] || {};
+ // Just in case of bad data, don't display a broken collection.
+ if (!title) {
+ return null;
+ }
+
+ let sponsoredByMessage = "";
+
+ // If override is not false or an empty string.
+ if (sponsored_by_override || sponsored_by_override === "") {
+ // We specifically want to display nothing if the server returns an empty string.
+ // So the server can turn off the label.
+ // This is to support the use cases where the sponsored context is displayed elsewhere.
+ sponsoredByMessage = sponsored_by_override;
+ } else if (sponsor) {
+ sponsoredByMessage = {
+ id: `newtab-label-sponsored-by`,
+ values: { sponsor },
+ };
+ } else if (context) {
+ sponsoredByMessage = context;
+ }
+
+ // Generally a card grid displays recs with spocs already injected.
+ // Normally it doesn't care which rec is a spoc and which isn't,
+ // it just displays content in a grid.
+ // For collections, we're only displaying a list of spocs.
+ // We don't need to tell the card grid that our list of cards are spocs,
+ // it shouldn't need to care. So we just pass our spocs along as recs.
+ // Think of it as injecting all rec positions with spocs.
+ // Consider maybe making recommendations in CardGrid use a more generic name.
+ const recsData = {
+ recommendations: data.spocs,
+ };
+
+ // All cards inside of a collection card grid have a slightly different type.
+ // For the case of interactions to the card grid, we use the type "COLLECTIONCARDGRID".
+ // Example, you dismiss the whole collection, we use the type "COLLECTIONCARDGRID".
+ // For interactions inside the card grid, example, you dismiss a single card in the collection,
+ // we use the type "COLLECTIONCARDGRID_CARD".
+ const type = `${this.props.type}_card`;
+
+ const collectionGrid = (
+ <div className="ds-collection-card-grid">
+ <CardGrid
+ title={title}
+ context={sponsoredByMessage}
+ data={recsData}
+ feed={feed}
+ border={this.props.border}
+ type={type}
+ is_collection={true}
+ dispatch={this.props.dispatch}
+ items={this.props.items}
+ />
+ </div>
+ );
+
+ if (dismissible) {
+ return (
+ <DSDismiss
+ onDismissClick={this.onDismissClick}
+ extraClasses={`ds-dismiss-ds-collection`}
+ >
+ {collectionGrid}
+ </DSDismiss>
+ );
+ }
+ return collectionGrid;
+ }
+}
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamComponents/CollectionCardGrid/_CollectionCardGrid.scss b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/CollectionCardGrid/_CollectionCardGrid.scss
new file mode 100644
index 0000000000..14667be1bd
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/CollectionCardGrid/_CollectionCardGrid.scss
@@ -0,0 +1,46 @@
+.ds-dismiss.ds-dismiss-ds-collection {
+ .ds-dismiss-button {
+ margin: 15px 0 0;
+ inset-inline-end: 25px;
+ }
+
+ &.hovering {
+ background: var(--newtab-element-hover-color);
+ }
+}
+
+.ds-collection-card-grid {
+ padding: 10px 25px 25px;
+ margin: 0 0 20px;
+
+ .story-footer {
+ display: none;
+ }
+
+ .ds-header {
+ padding: 0 40px 0 0;
+ margin-bottom: 12px;
+
+ .title {
+ @include dark-theme-only {
+ color: $grey-30;
+ }
+
+ color: $grey-90;
+ font-weight: 600;
+ font-size: 17px;
+ line-height: 24px;
+ }
+
+ .ds-context {
+ @include dark-theme-only {
+ color: $grey-40;
+ }
+
+ color: $grey-50;
+ font-weight: normal;
+ font-size: 13px;
+ line-height: 24px;
+ }
+ }
+}
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSCard/DSCard.jsx b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSCard/DSCard.jsx
new file mode 100644
index 0000000000..b94d29bb6d
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSCard/DSCard.jsx
@@ -0,0 +1,323 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { actionCreators as ac } from "common/Actions.jsm";
+import { DSImage } from "../DSImage/DSImage.jsx";
+import { DSLinkMenu } from "../DSLinkMenu/DSLinkMenu";
+import { ImpressionStats } from "../../DiscoveryStreamImpressionStats/ImpressionStats";
+import React from "react";
+import { SafeAnchor } from "../SafeAnchor/SafeAnchor";
+import { DSContextFooter } from "../DSContextFooter/DSContextFooter.jsx";
+import { FluentOrText } from "../../FluentOrText/FluentOrText.jsx";
+import { connect } from "react-redux";
+
+// Default Meta that displays CTA as link if cta_variant in layout is set as "link"
+export const DefaultMeta = ({
+ display_engagement_labels,
+ source,
+ title,
+ excerpt,
+ context,
+ context_type,
+ cta,
+ engagement,
+ cta_variant,
+ sponsor,
+ sponsored_by_override,
+}) => (
+ <div className="meta">
+ <div className="info-wrap">
+ <p className="source clamp">{source}</p>
+ <header className="title clamp">{title}</header>
+ {excerpt && <p className="excerpt clamp">{excerpt}</p>}
+ {cta_variant === "link" && cta && (
+ <div role="link" className="cta-link icon icon-arrow" tabIndex="0">
+ {cta}
+ </div>
+ )}
+ </div>
+ <DSContextFooter
+ context_type={context_type}
+ context={context}
+ sponsor={sponsor}
+ sponsored_by_override={sponsored_by_override}
+ display_engagement_labels={display_engagement_labels}
+ engagement={engagement}
+ />
+ </div>
+);
+
+export const CTAButtonMeta = ({
+ display_engagement_labels,
+ source,
+ title,
+ excerpt,
+ context,
+ context_type,
+ cta,
+ engagement,
+ sponsor,
+ sponsored_by_override,
+}) => (
+ <div className="meta">
+ <div className="info-wrap">
+ <p className="source clamp">
+ {context && (
+ <FluentOrText
+ message={{
+ id: `newtab-label-sponsored`,
+ values: { sponsorOrSource: sponsor ? sponsor : source },
+ }}
+ />
+ )}
+
+ {!context && (sponsor ? sponsor : source)}
+ </p>
+ <header className="title clamp">{title}</header>
+ {excerpt && <p className="excerpt clamp">{excerpt}</p>}
+ </div>
+ {context && cta && <button className="button cta-button">{cta}</button>}
+ {!context && (
+ <DSContextFooter
+ context_type={context_type}
+ context={context}
+ sponsor={sponsor}
+ sponsored_by_override={sponsored_by_override}
+ display_engagement_labels={display_engagement_labels}
+ engagement={engagement}
+ />
+ )}
+ </div>
+);
+
+export class _DSCard extends React.PureComponent {
+ constructor(props) {
+ super(props);
+
+ this.onLinkClick = this.onLinkClick.bind(this);
+ this.setPlaceholderRef = element => {
+ this.placeholderElement = element;
+ };
+
+ this.state = {
+ isSeen: false,
+ };
+
+ // If this is for the about:home startup cache, then we always want
+ // to render the DSCard, regardless of whether or not its been seen.
+ if (props.App.isForStartupCache) {
+ this.state.isSeen = true;
+ }
+
+ // We want to choose the optimal thumbnail for the underlying DSImage, but
+ // want to do it in a performant way. The breakpoints used in the
+ // CSS of the page are, unfortuntely, not easy to retrieve without
+ // causing a style flush. To avoid that, we hardcode them here.
+ //
+ // The values chosen here were the dimensions of the card thumbnails as
+ // computed by getBoundingClientRect() for each type of viewport width
+ // across both high-density and normal-density displays.
+ this.dsImageSizes = [
+ {
+ mediaMatcher: "(min-width: 1122px)",
+ width: 296,
+ height: 148,
+ },
+
+ {
+ mediaMatcher: "(min-width: 866px)",
+ width: 218,
+ height: 109,
+ },
+
+ {
+ mediaMatcher: "(max-width: 610px)",
+ width: 202,
+ height: 101,
+ },
+ ];
+ }
+
+ onLinkClick(event) {
+ if (this.props.dispatch) {
+ this.props.dispatch(
+ ac.UserEvent({
+ event: "CLICK",
+ source: this.props.is_video
+ ? "CARDGRID_VIDEO"
+ : this.props.type.toUpperCase(),
+ action_position: this.props.pos,
+ value: { card_type: this.props.flightId ? "spoc" : "organic" },
+ })
+ );
+
+ this.props.dispatch(
+ ac.ImpressionStats({
+ source: this.props.is_video
+ ? "CARDGRID_VIDEO"
+ : this.props.type.toUpperCase(),
+ click: 0,
+ tiles: [
+ {
+ id: this.props.id,
+ pos: this.props.pos,
+ ...(this.props.shim && this.props.shim.click
+ ? { shim: this.props.shim.click }
+ : {}),
+ },
+ ],
+ })
+ );
+ }
+ }
+
+ onSeen(entries) {
+ if (this.state) {
+ const entry = entries.find(e => e.isIntersecting);
+
+ if (entry) {
+ if (this.placeholderElement) {
+ this.observer.unobserve(this.placeholderElement);
+ }
+
+ // Stop observing since element has been seen
+ this.setState({
+ isSeen: true,
+ });
+ }
+ }
+ }
+
+ onIdleCallback() {
+ if (!this.state.isSeen) {
+ if (this.observer && this.placeholderElement) {
+ this.observer.unobserve(this.placeholderElement);
+ }
+ this.setState({
+ isSeen: true,
+ });
+ }
+ }
+
+ componentDidMount() {
+ this.idleCallbackId = this.props.windowObj.requestIdleCallback(
+ this.onIdleCallback.bind(this)
+ );
+ if (this.placeholderElement) {
+ this.observer = new IntersectionObserver(this.onSeen.bind(this));
+ this.observer.observe(this.placeholderElement);
+ }
+ }
+
+ componentWillUnmount() {
+ // Remove observer on unmount
+ if (this.observer && this.placeholderElement) {
+ this.observer.unobserve(this.placeholderElement);
+ }
+ if (this.idleCallbackId) {
+ this.props.windowObj.cancelIdleCallback(this.idleCallbackId);
+ }
+ }
+
+ render() {
+ if (this.props.placeholder || !this.state.isSeen) {
+ return (
+ <div className="ds-card placeholder" ref={this.setPlaceholderRef} />
+ );
+ }
+ const isButtonCTA = this.props.cta_variant === "button";
+ const baseClass = `ds-card ${this.props.is_video ? `video-card` : ``}`;
+
+ return (
+ <div className={baseClass}>
+ <SafeAnchor
+ className="ds-card-link"
+ dispatch={this.props.dispatch}
+ onLinkClick={!this.props.placeholder ? this.onLinkClick : undefined}
+ url={this.props.url}
+ >
+ <div className="img-wrapper">
+ <DSImage
+ extraClassNames="img"
+ source={this.props.image_src}
+ rawSource={this.props.raw_image_src}
+ sizes={this.dsImageSizes}
+ />
+ {this.props.is_video && (
+ <div className="playhead">
+ <span>Video Content</span>
+ </div>
+ )}
+ </div>
+ {isButtonCTA ? (
+ <CTAButtonMeta
+ display_engagement_labels={this.props.display_engagement_labels}
+ source={this.props.source}
+ title={this.props.title}
+ excerpt={this.props.excerpt}
+ context={this.props.context}
+ context_type={this.props.context_type}
+ engagement={this.props.engagement}
+ cta={this.props.cta}
+ sponsor={this.props.sponsor}
+ sponsored_by_override={this.props.sponsored_by_override}
+ />
+ ) : (
+ <DefaultMeta
+ display_engagement_labels={this.props.display_engagement_labels}
+ source={this.props.source}
+ title={this.props.title}
+ excerpt={this.props.excerpt}
+ context={this.props.context}
+ engagement={this.props.engagement}
+ context_type={this.props.context_type}
+ cta={this.props.cta}
+ cta_variant={this.props.cta_variant}
+ sponsor={this.props.sponsor}
+ sponsored_by_override={this.props.sponsored_by_override}
+ />
+ )}
+ <ImpressionStats
+ flightId={this.props.flightId}
+ rows={[
+ {
+ id: this.props.id,
+ pos: this.props.pos,
+ ...(this.props.shim && this.props.shim.impression
+ ? { shim: this.props.shim.impression }
+ : {}),
+ },
+ ]}
+ dispatch={this.props.dispatch}
+ source={this.props.is_video ? "CARDGRID_VIDEO" : this.props.type}
+ />
+ </SafeAnchor>
+ <DSLinkMenu
+ id={this.props.id}
+ index={this.props.pos}
+ dispatch={this.props.dispatch}
+ url={this.props.url}
+ title={this.props.title}
+ source={this.props.source}
+ type={this.props.type}
+ pocket_id={this.props.pocket_id}
+ shim={this.props.shim}
+ bookmarkGuid={this.props.bookmarkGuid}
+ flightId={!this.props.is_collection ? this.props.flightId : undefined}
+ showPrivacyInfo={!!this.props.flightId}
+ />
+ </div>
+ );
+ }
+}
+
+_DSCard.defaultProps = {
+ windowObj: window, // Added to support unit tests
+};
+
+export const DSCard = connect(state => ({
+ App: state.App,
+}))(_DSCard);
+
+export const PlaceholderDSCard = props => <DSCard placeholder={true} />;
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSCard/_DSCard.scss b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSCard/_DSCard.scss
new file mode 100644
index 0000000000..8564fa4f67
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSCard/_DSCard.scss
@@ -0,0 +1,313 @@
+// Type sizes
+$header-font-size: 17;
+$header-line-height: 24;
+$excerpt-font-size: 14;
+$excerpt-line-height: 20;
+
+.outer-wrapper:not(.newtab-experience) {
+ .ds-card {
+ .ds-card-link {
+ &:hover {
+ @include ds-fade-in($grey-30);
+
+ @include dark-theme-only {
+ @include ds-fade-in($grey-60);
+ }
+ }
+
+ &:focus {
+ @include ds-fade-in;
+
+ @include dark-theme-only {
+ @include ds-fade-in($blue-40-40);
+ }
+ }
+
+ &:active {
+ @include ds-fade-in($grey-30);
+
+ @include dark-theme-only {
+ @include ds-fade-in($grey-60);
+ }
+ }
+ }
+ }
+}
+
+.ds-card {
+ display: flex;
+ flex-direction: column;
+ position: relative;
+
+ .playhead {
+ background: $blue-60 url('chrome://activity-stream/content/data/content/assets/glyph-playhead.svg') no-repeat 12px center;
+ border-radius: 20px;
+ bottom: -16px;
+ color: $white-0;
+ display: flex;
+ flex-direction: column;
+ height: 40px;
+ justify-content: center;
+ left: 16px;
+ min-width: 40px;
+ padding: 0 0 0 40px;
+ position: absolute;
+ transition: padding 100ms ease-in-out 0ms, color 100ms linear 100ms;
+
+ &:hover {
+ color: $white-100;
+ padding: 0 20px 0 40px;
+ }
+
+ span {
+ display: none;
+ }
+
+ &:hover span {
+ display: inline;
+ font-style: normal;
+ font-weight: 600;
+ font-size: 13px;
+ }
+ }
+
+ &.placeholder {
+ background: transparent;
+ box-shadow: inset $inner-box-shadow;
+ border-radius: 4px;
+ min-height: 300px;
+ }
+
+ .img-wrapper {
+ width: 100%;
+ position: relative;
+ }
+
+ .img {
+ height: 0;
+ padding-top: 50%; // 2:1 aspect ratio
+
+ img {
+ border-radius: 4px;
+ box-shadow: inset 0 0 0 0.5px $black-15;
+ }
+ }
+
+ .ds-card-link {
+ height: 100%;
+ display: flex;
+ flex-direction: column;
+
+ &:hover {
+ header {
+ @include dark-theme-only {
+ color: $blue-40;
+ }
+
+ color: $blue-60;
+ }
+ }
+
+ &:focus {
+ header {
+ @include dark-theme-only {
+ color: $blue-40;
+ }
+
+ color: $blue-60;
+ }
+ }
+
+ &:active {
+ header {
+ @include dark-theme-only {
+ color: $blue-50;
+ }
+
+ color: $blue-70;
+ }
+ }
+ }
+
+ &.video-card .meta {
+ margin-top: 4px;
+ }
+
+ .meta {
+ display: flex;
+ flex-direction: column;
+ padding: 12px 16px;
+ flex-grow: 1;
+
+ .info-wrap {
+ flex-grow: 1;
+ }
+
+ .title {
+ // show only 3 lines of copy
+ @include limit-visible-lines(3, $header-line-height, $header-font-size);
+ font-weight: 600;
+ }
+
+ .excerpt {
+ // show only 3 lines of copy
+ @include limit-visible-lines(
+ 3,
+ $excerpt-line-height,
+ $excerpt-font-size
+ );
+ }
+
+ .source {
+ @include dark-theme-only {
+ color: $grey-40;
+ }
+
+ -webkit-line-clamp: 1;
+ margin-bottom: 2px;
+ font-size: 13px;
+ color: $grey-50;
+ }
+
+ .cta-button {
+ @include dark-theme-only {
+ color: $grey-10;
+ background: $grey-90-70;
+ }
+
+ width: 100%;
+ margin: 12px 0 4px;
+ box-shadow: none;
+ border-radius: 4px;
+ height: 32px;
+ font-size: 14px;
+ font-weight: 600;
+ padding: 5px 8px 7px;
+ border: 0;
+ color: $grey-90;
+ background: $grey-90-10;
+
+ &:focus {
+ @include dark-theme-only {
+ background: $grey-90-70;
+ box-shadow: 0 0 0 2px $grey-80, 0 0 0 5px $blue-50-50;
+ }
+
+ background: $grey-90-10;
+ box-shadow: 0 0 0 2px $white, 0 0 0 5px $blue-50-50;
+ }
+
+ &:hover {
+ @include dark-theme-only {
+ background: $grey-90-50;
+ }
+
+ background: $grey-90-20;
+ }
+
+ &:active {
+ @include dark-theme-only {
+ background: $grey-90-70;
+ }
+
+ background: $grey-90-30;
+ }
+ }
+
+ .cta-link {
+ @include dark-theme-only {
+ color: $blue-40;
+ fill: $blue-40;
+ }
+
+ font-size: 15px;
+ font-weight: 600;
+ line-height: 24px;
+ height: 24px;
+ width: auto;
+ background-size: auto;
+ background-position: right 1.5px;
+ padding-right: 9px;
+ color: $blue-60;
+ fill: $blue-60;
+
+ &:focus {
+ @include dark-theme-only {
+ box-shadow: 0 0 0 1px $grey-80, 0 0 0 4px $blue-50-50;
+ }
+
+ box-shadow: 0 0 0 1px $white, 0 0 0 4px $blue-50-50;
+ border-radius: 4px;
+ outline: 0;
+ }
+
+ &:active {
+ @include dark-theme-only {
+ color: $blue-50;
+ fill: $blue-50;
+ box-shadow: none;
+ }
+
+ color: $blue-70;
+ fill: $blue-70;
+ box-shadow: none;
+ }
+
+ &:hover {
+ text-decoration: underline;
+ }
+ }
+ }
+
+ header {
+ @include dark-theme-only {
+ color: $grey-10;
+ }
+
+ line-height: $header-line-height * 1px;
+ font-size: $header-font-size * 1px;
+ color: $grey-90;
+ }
+
+ p {
+ @include dark-theme-only {
+ color: $grey-10;
+ }
+
+ font-size: $excerpt-font-size * 1px;
+ line-height: $excerpt-line-height * 1px;
+ color: $grey-90;
+ margin: 0;
+ }
+}
+
+// Special styling for the New Tab Experience styles,
+// This is to be incorporated once the styles are made permanent
+.outer-wrapper.newtab-experience {
+ .ds-card {
+ // Temporary fix to have the context button focus blend in with other New Tab Experience context menu focus
+ .context-menu-button {
+ &:is(:active, :focus) {
+ outline: 0;
+ fill: var(--newtab-primary-action-background);
+ border: 1px solid var(--newtab-primary-action-background);
+ }
+ }
+
+ .ds-card-link {
+ &:focus {
+ @include ds-focus-nte;
+
+ transition: none;
+
+ header {
+ @include dark-theme-only {
+ color: $blue-40;
+ }
+
+ color: $blue-60;
+ }
+ }
+ }
+ }
+}
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSContextFooter/DSContextFooter.jsx b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSContextFooter/DSContextFooter.jsx
new file mode 100644
index 0000000000..0da08d3664
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSContextFooter/DSContextFooter.jsx
@@ -0,0 +1,85 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { cardContextTypes } from "../../Card/types.js";
+import { CSSTransition, TransitionGroup } from "react-transition-group";
+import { FluentOrText } from "../../FluentOrText/FluentOrText.jsx";
+import React from "react";
+
+// Animation time is mirrored in DSContextFooter.scss
+const ANIMATION_DURATION = 3000;
+
+export const StatusMessage = ({ icon, fluentID }) => (
+ <div className="status-message">
+ <span
+ aria-haspopup="true"
+ className={`story-badge-icon icon icon-${icon}`}
+ />
+ <div className="story-context-label" data-l10n-id={fluentID} />
+ </div>
+);
+
+export const SponsorLabel = ({ sponsored_by_override, sponsor, context }) => {
+ const classList = "story-sponsored-label clamp";
+ // If override is not false or an empty string.
+ if (sponsored_by_override) {
+ return <p className={classList}>{sponsored_by_override}</p>;
+ } else if (sponsored_by_override === "") {
+ // We specifically want to display nothing if the server returns an empty string.
+ // So the server can turn off the label.
+ // This is to support the use cases where the sponsored context is displayed elsewhere.
+ return null;
+ } else if (sponsor) {
+ return (
+ <p className={classList}>
+ <FluentOrText
+ message={{
+ id: `newtab-label-sponsored-by`,
+ values: { sponsor },
+ }}
+ />
+ </p>
+ );
+ } else if (context) {
+ return <p className={classList}>{context}</p>;
+ }
+ return null;
+};
+
+export class DSContextFooter extends React.PureComponent {
+ render() {
+ // display_engagement_labels is based on pref `browser.newtabpage.activity-stream.discoverystream.engagementLabelEnabled`
+ const {
+ context,
+ context_type,
+ engagement,
+ display_engagement_labels,
+ sponsor,
+ sponsored_by_override,
+ } = this.props;
+ const { icon, fluentID } = cardContextTypes[context_type] || {};
+
+ return (
+ <div className="story-footer">
+ {SponsorLabel({ sponsored_by_override, sponsor, context })}
+ <TransitionGroup component={null}>
+ {!context &&
+ (context_type || (display_engagement_labels && engagement)) && (
+ <CSSTransition
+ key={fluentID}
+ timeout={ANIMATION_DURATION}
+ classNames="story-animate"
+ >
+ {engagement && !context_type ? (
+ <div className="story-view-count">{engagement}</div>
+ ) : (
+ <StatusMessage icon={icon} fluentID={fluentID} />
+ )}
+ </CSSTransition>
+ )}
+ </TransitionGroup>
+ </div>
+ );
+ }
+}
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSContextFooter/_DSContextFooter.scss b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSContextFooter/_DSContextFooter.scss
new file mode 100644
index 0000000000..4c4aa7b93e
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSContextFooter/_DSContextFooter.scss
@@ -0,0 +1,109 @@
+$status-green: #058B00;
+$status-dark-green: #7C6;
+
+.story-footer {
+ color: var(--newtab-text-secondary-color);
+ inset-inline-start: 0;
+ margin-top: 12px;
+ position: relative;
+
+ .story-sponsored-label,
+ .story-view-count,
+ .status-message {
+ @include dark-theme-only {
+ color: $grey-40;
+ }
+
+ -webkit-line-clamp: 1;
+ font-size: 13px;
+ line-height: 24px;
+ color: $grey-50;
+ }
+
+ .status-message {
+ display: flex;
+ align-items: center;
+ height: 24px;
+
+ .story-badge-icon {
+ @include dark-theme-only {
+ fill: $grey-40;
+ }
+
+ fill: $grey-50;
+ height: 16px;
+ margin-inline-end: 6px;
+
+ &.icon-bookmark-removed {
+ background-image: url('#{$image-path}icon-removed-bookmark.svg');
+ }
+ }
+
+ .story-context-label {
+ @include dark-theme-only {
+ color: $grey-40;
+ }
+
+ color: $grey-50;
+ flex-grow: 1;
+ font-size: 13px;
+ line-height: 24px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ }
+}
+
+.story-animate-enter {
+ opacity: 0;
+}
+
+.story-animate-enter-active {
+ opacity: 1;
+ transition: opacity 150ms ease-in 300ms;
+
+ .story-badge-icon,
+ .story-context-label {
+ @include dark-theme-only {
+ animation: dark-color 3s ease-out 0.3s;
+ }
+
+ animation: color 3s ease-out 0.3s;
+
+ @keyframes color {
+ 0% {
+ color: $status-green;
+ fill: $status-green;
+ }
+
+ 100% {
+ color: $grey-50;
+ fill: $grey-50;
+ }
+ }
+
+ @keyframes dark-color {
+ 0% {
+ color: $status-dark-green;
+ fill: $status-dark-green;
+ }
+
+ 100% {
+ color: $grey-40;
+ fill: $grey-40;
+ }
+ }
+ }
+}
+
+.story-animate-exit {
+ position: absolute;
+ top: 0;
+ opacity: 1;
+}
+
+.story-animate-exit-active {
+ opacity: 0;
+ transition: opacity 250ms ease-in;
+}
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSDismiss/DSDismiss.jsx b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSDismiss/DSDismiss.jsx
new file mode 100644
index 0000000000..9090ebe582
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSDismiss/DSDismiss.jsx
@@ -0,0 +1,57 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import React from "react";
+
+export class DSDismiss extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onDismissClick = this.onDismissClick.bind(this);
+ this.onHover = this.onHover.bind(this);
+ this.offHover = this.offHover.bind(this);
+ this.state = {
+ hovering: false,
+ };
+ }
+
+ onDismissClick() {
+ if (this.props.onDismissClick) {
+ this.props.onDismissClick();
+ }
+ }
+
+ onHover() {
+ this.setState({
+ hovering: true,
+ });
+ }
+
+ offHover() {
+ this.setState({
+ hovering: false,
+ });
+ }
+
+ render() {
+ let className = `ds-dismiss
+ ${this.state.hovering ? ` hovering` : ``}
+ ${this.props.extraClasses ? ` ${this.props.extraClasses}` : ``}`;
+
+ return (
+ <div className={className}>
+ {this.props.children}
+ <button
+ className="ds-dismiss-button"
+ data-l10n-id="newtab-dismiss-button-tooltip"
+ onHover={this.onHover}
+ onClick={this.onDismissClick}
+ onMouseEnter={this.onHover}
+ onMouseLeave={this.offHover}
+ >
+ <span className="icon icon-dismiss" />
+ </button>
+ </div>
+ );
+ }
+}
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSDismiss/_DSDismiss.scss b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSDismiss/_DSDismiss.scss
new file mode 100644
index 0000000000..1d28be53a9
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSDismiss/_DSDismiss.scss
@@ -0,0 +1,68 @@
+.ds-dismiss {
+ position: relative;
+ border-radius: 8px;
+ transition-duration: 250ms;
+ transition-property: background;
+
+ &:hover {
+ .ds-dismiss-button {
+ opacity: 1;
+ }
+ }
+
+ .ds-dismiss-button {
+ border: 0;
+ cursor: pointer;
+ height: 32px;
+ width: 32px;
+ padding: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ position: absolute;
+ inset-inline-end: 0;
+ top: 0;
+ border-radius: 50%;
+ background-color: transparent;
+
+ .icon {
+ @include dark-theme-only {
+ fill: $grey-20;
+ }
+
+ fill: $grey-50;
+ }
+
+ &:hover {
+ @include dark-theme-only {
+ background: $grey-90-50;
+
+ .icon {
+ fill: $grey-10;
+ }
+ }
+
+ background: $grey-90-20;
+
+ .icon {
+ fill: $grey-80;
+ }
+ }
+
+ &:active {
+ @include dark-theme-only {
+ background: $grey-90-70;
+ }
+
+ background: $grey-90-30;
+ }
+
+ &:focus {
+ @include dark-theme-only {
+ box-shadow: 0 0 0 2px $grey-80, 0 0 0 5px $blue-50-50;
+ }
+
+ box-shadow: 0 0 0 2px $white, 0 0 0 5px $blue-50-50;
+ }
+ }
+}
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSEmptyState/DSEmptyState.jsx b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSEmptyState/DSEmptyState.jsx
new file mode 100644
index 0000000000..2f3822b825
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSEmptyState/DSEmptyState.jsx
@@ -0,0 +1,97 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { actionCreators as ac, actionTypes as at } from "common/Actions.jsm";
+import React from "react";
+
+export class DSEmptyState extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onReset = this.onReset.bind(this);
+ this.state = {};
+ }
+
+ componentWillUnmount() {
+ if (this.timeout) {
+ clearTimeout(this.timeout);
+ }
+ }
+
+ onReset() {
+ if (this.props.dispatch && this.props.feed) {
+ const { feed } = this.props;
+ const { url } = feed;
+ this.props.dispatch({
+ type: at.DISCOVERY_STREAM_FEED_UPDATE,
+ data: {
+ feed: {
+ ...feed,
+ data: {
+ ...feed.data,
+ status: "waiting",
+ },
+ },
+ url,
+ },
+ });
+
+ this.setState({ waiting: true });
+ this.timeout = setTimeout(() => {
+ this.timeout = null;
+ this.setState({
+ waiting: false,
+ });
+ }, 300);
+
+ this.props.dispatch(
+ ac.OnlyToMain({ type: at.DISCOVERY_STREAM_RETRY_FEED, data: { feed } })
+ );
+ }
+ }
+
+ renderButton() {
+ if (this.props.status === "waiting" || this.state.waiting) {
+ return (
+ <button
+ className="try-again-button waiting"
+ data-l10n-id="newtab-discovery-empty-section-topstories-loading"
+ />
+ );
+ }
+
+ return (
+ <button
+ className="try-again-button"
+ onClick={this.onReset}
+ data-l10n-id="newtab-discovery-empty-section-topstories-try-again-button"
+ />
+ );
+ }
+
+ renderState() {
+ if (this.props.status === "waiting" || this.props.status === "failed") {
+ return (
+ <React.Fragment>
+ <h2 data-l10n-id="newtab-discovery-empty-section-topstories-timed-out" />
+ {this.renderButton()}
+ </React.Fragment>
+ );
+ }
+
+ return (
+ <React.Fragment>
+ <h2 data-l10n-id="newtab-discovery-empty-section-topstories-header" />
+ <p data-l10n-id="newtab-discovery-empty-section-topstories-content" />
+ </React.Fragment>
+ );
+ }
+
+ render() {
+ return (
+ <div className="section-empty-state">
+ <div className="empty-state-message">{this.renderState()}</div>
+ </div>
+ );
+ }
+}
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSEmptyState/_DSEmptyState.scss b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSEmptyState/_DSEmptyState.scss
new file mode 100644
index 0000000000..bc66424a5a
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSEmptyState/_DSEmptyState.scss
@@ -0,0 +1,87 @@
+.section-empty-state {
+ border: $border-secondary;
+ border-radius: 4px;
+ display: flex;
+ height: $card-height-compact;
+ width: 100%;
+
+ .empty-state-message {
+ color: var(--newtab-text-secondary-color);
+ font-size: 14px;
+ line-height: 20px;
+ text-align: center;
+ margin: auto;
+ max-width: 936px;
+ }
+
+ .try-again-button {
+ margin-top: 12px;
+ padding: 6px 32px;
+ border-radius: 2px;
+ border: 0;
+ background: var(--newtab-feed-button-background);
+ color: var(--newtab-feed-button-text);
+ cursor: pointer;
+ position: relative;
+ transition: background 0.2s ease, color 0.2s ease;
+
+ &:not(.waiting) {
+ &:focus {
+ @include ds-fade-in;
+
+ @include dark-theme-only {
+ @include ds-fade-in($blue-40-40);
+ }
+ }
+
+ &:hover {
+ @include ds-fade-in($grey-30);
+
+ @include dark-theme-only {
+ @include ds-fade-in($grey-60);
+ }
+ }
+ }
+
+ &::after {
+ content: '';
+ height: 20px;
+ width: 20px;
+ animation: spinner 1s linear infinite;
+ opacity: 0;
+ position: absolute;
+ top: 50%;
+ left: 50%;
+ margin: -10px 0 0 -10px;
+ mask-image: url('chrome://activity-stream/content/data/content/assets/spinner.svg');
+ mask-size: 20px;
+ background: var(--newtab-feed-button-spinner);
+ }
+
+ &.waiting {
+ cursor: initial;
+ background: var(--newtab-feed-button-background-faded);
+ color: var(--newtab-feed-button-text-faded);
+ transition: background 0.2s ease;
+
+ &::after {
+ transition: opacity 0.2s ease;
+ opacity: 1;
+ }
+ }
+ }
+
+ h2 {
+ font-size: 15px;
+ font-weight: 600;
+ margin: 0;
+ }
+
+ p {
+ margin: 0;
+ }
+}
+
+@keyframes spinner {
+ to { transform: rotate(360deg); }
+}
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSImage/DSImage.jsx b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSImage/DSImage.jsx
new file mode 100644
index 0000000000..919a110fbc
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSImage/DSImage.jsx
@@ -0,0 +1,157 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import React from "react";
+
+export class DSImage extends React.PureComponent {
+ constructor(props) {
+ super(props);
+
+ this.onOptimizedImageError = this.onOptimizedImageError.bind(this);
+ this.onNonOptimizedImageError = this.onNonOptimizedImageError.bind(this);
+ this.onLoad = this.onLoad.bind(this);
+
+ this.state = {
+ isLoaded: false,
+ optimizedImageFailed: false,
+ useTransition: false,
+ };
+ }
+
+ onIdleCallback() {
+ if (!this.state.isLoaded) {
+ this.setState({
+ useTransition: true,
+ });
+ }
+ }
+
+ reformatImageURL(url, width, height) {
+ // Change the image URL to request a size tailored for the parent container width
+ // Also: force JPEG, quality 60, no upscaling, no EXIF data
+ // Uses Thumbor: https://thumbor.readthedocs.io/en/latest/usage.html
+ return `https://img-getpocket.cdn.mozilla.net/${width}x${height}/filters:format(jpeg):quality(60):no_upscale():strip_exif()/${encodeURIComponent(
+ url
+ )}`;
+ }
+
+ componentDidMount() {
+ this.idleCallbackId = this.props.windowObj.requestIdleCallback(
+ this.onIdleCallback.bind(this)
+ );
+ }
+
+ componentWillUnmount() {
+ if (this.idleCallbackId) {
+ this.props.windowObj.cancelIdleCallback(this.idleCallbackId);
+ }
+ }
+
+ render() {
+ let classNames = `ds-image
+ ${this.props.extraClassNames ? ` ${this.props.extraClassNames}` : ``}
+ ${this.state && this.state.useTransition ? ` use-transition` : ``}
+ ${this.state && this.state.isLoaded ? ` loaded` : ``}
+ `;
+
+ let img;
+
+ if (this.state) {
+ if (
+ this.props.optimize &&
+ this.props.rawSource &&
+ !this.state.optimizedImageFailed
+ ) {
+ let baseSource = this.props.rawSource;
+
+ let sizeRules = [];
+ let srcSetRules = [];
+
+ for (let rule of this.props.sizes) {
+ let { mediaMatcher, width, height } = rule;
+ let sizeRule = `${mediaMatcher} ${width}px`;
+ sizeRules.push(sizeRule);
+ let srcSetRule = `${this.reformatImageURL(
+ baseSource,
+ width,
+ height
+ )} ${width}w`;
+ let srcSetRule2x = `${this.reformatImageURL(
+ baseSource,
+ width * 2,
+ height * 2
+ )} ${width * 2}w`;
+ srcSetRules.push(srcSetRule);
+ srcSetRules.push(srcSetRule2x);
+ }
+
+ if (this.props.sizes.length) {
+ // We have to supply a fallback in the very unlikely event that none of
+ // the media queries match. The smallest dimension was chosen arbitrarily.
+ sizeRules.push(
+ `${this.props.sizes[this.props.sizes.length - 1].width}px`
+ );
+ }
+
+ img = (
+ <img
+ loading="lazy"
+ alt={this.props.alt_text}
+ crossOrigin="anonymous"
+ onLoad={this.onLoad}
+ onError={this.onOptimizedImageError}
+ sizes={sizeRules.join(",")}
+ src={baseSource}
+ srcSet={srcSetRules.join(",")}
+ />
+ );
+ } else if (!this.state.nonOptimizedImageFailed) {
+ img = (
+ <img
+ loading="lazy"
+ alt={this.props.alt_text}
+ crossOrigin="anonymous"
+ onLoad={this.onLoad}
+ onError={this.onNonOptimizedImageError}
+ src={this.props.source}
+ />
+ );
+ } else {
+ // Remove the img element if both sources fail. Render a placeholder instead.
+ img = <div className="broken-image" />;
+ }
+ }
+
+ return <picture className={classNames}>{img}</picture>;
+ }
+
+ onOptimizedImageError() {
+ // This will trigger a re-render and the unoptimized 450px image will be used as a fallback
+ this.setState({
+ optimizedImageFailed: true,
+ });
+ }
+
+ onNonOptimizedImageError() {
+ this.setState({
+ nonOptimizedImageFailed: true,
+ });
+ }
+
+ onLoad() {
+ this.setState({
+ isLoaded: true,
+ });
+ }
+}
+
+DSImage.defaultProps = {
+ source: null, // The current source style from Pocket API (always 450px)
+ rawSource: null, // Unadulterated image URL to filter through Thumbor
+ extraClassNames: null, // Additional classnames to append to component
+ optimize: true, // Measure parent container to request exact sizes
+ alt_text: null,
+ windowObj: window, // Added to support unit tests
+ sizes: [],
+};
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSImage/_DSImage.scss b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSImage/_DSImage.scss
new file mode 100644
index 0000000000..03063c0cf8
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSImage/_DSImage.scss
@@ -0,0 +1,23 @@
+.ds-image {
+ display: block;
+ position: relative;
+ opacity: 0;
+
+ &.use-transition {
+ transition: opacity 0.8s;
+ }
+
+ &.loaded {
+ opacity: 1;
+ }
+
+ img,
+ .broken-image {
+ background-color: var(--newtab-card-placeholder-color);
+ position: absolute;
+ top: 0;
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ }
+}
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSLinkMenu/DSLinkMenu.jsx b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSLinkMenu/DSLinkMenu.jsx
new file mode 100644
index 0000000000..469857f6e3
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSLinkMenu/DSLinkMenu.jsx
@@ -0,0 +1,90 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { LinkMenu } from "content-src/components/LinkMenu/LinkMenu";
+import { ContextMenuButton } from "content-src/components/ContextMenu/ContextMenuButton";
+import React from "react";
+
+export class DSLinkMenu extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onMenuUpdate = this.onMenuUpdate.bind(this);
+ this.onMenuShow = this.onMenuShow.bind(this);
+ this.contextMenuButtonRef = React.createRef();
+ }
+
+ onMenuUpdate(showContextMenu) {
+ if (!showContextMenu) {
+ const dsLinkMenuHostDiv = this.contextMenuButtonRef.current.parentElement;
+ dsLinkMenuHostDiv.parentElement.classList.remove("active", "last-item");
+ }
+ }
+
+ nextAnimationFrame() {
+ return new Promise(resolve =>
+ this.props.windowObj.requestAnimationFrame(resolve)
+ );
+ }
+
+ async onMenuShow() {
+ const dsLinkMenuHostDiv = this.contextMenuButtonRef.current.parentElement;
+ // Wait for next frame before computing scrollMaxX to allow fluent menu strings to be visible
+ await this.nextAnimationFrame();
+ if (this.props.windowObj.scrollMaxX > 0) {
+ dsLinkMenuHostDiv.parentElement.classList.add("last-item");
+ }
+ dsLinkMenuHostDiv.parentElement.classList.add("active");
+ }
+
+ render() {
+ const { index, dispatch } = this.props;
+ const TOP_STORIES_CONTEXT_MENU_OPTIONS = [
+ "CheckBookmarkOrArchive",
+ "CheckSavedToPocket",
+ "Separator",
+ "OpenInNewWindow",
+ "OpenInPrivateWindow",
+ "Separator",
+ "BlockUrl",
+ ...(this.props.showPrivacyInfo ? ["ShowPrivacyInfo"] : []),
+ ];
+ const type = this.props.type || "DISCOVERY_STREAM";
+ const title = this.props.title || this.props.source;
+
+ return (
+ <div>
+ <ContextMenuButton
+ refFunction={this.contextMenuButtonRef}
+ tooltip={"newtab-menu-content-tooltip"}
+ tooltipArgs={{ title }}
+ onUpdate={this.onMenuUpdate}
+ >
+ <LinkMenu
+ dispatch={dispatch}
+ index={index}
+ source={type.toUpperCase()}
+ onShow={this.onMenuShow}
+ options={TOP_STORIES_CONTEXT_MENU_OPTIONS}
+ shouldSendImpressionStats={true}
+ site={{
+ referrer: "https://getpocket.com/recommendations",
+ title: this.props.title,
+ type: this.props.type,
+ url: this.props.url,
+ guid: this.props.id,
+ pocket_id: this.props.pocket_id,
+ shim: this.props.shim,
+ bookmarkGuid: this.props.bookmarkGuid,
+ flight_id: this.props.flightId,
+ }}
+ />
+ </ContextMenuButton>
+ </div>
+ );
+ }
+}
+
+DSLinkMenu.defaultProps = {
+ windowObj: window, // Added to support unit tests
+};
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSLinkMenu/_DSLinkMenu.scss b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSLinkMenu/_DSLinkMenu.scss
new file mode 100644
index 0000000000..6e05e4ef9f
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSLinkMenu/_DSLinkMenu.scss
@@ -0,0 +1,33 @@
+.ds-hero-item,
+.ds-list-item,
+.ds-card,
+.ds-signup {
+ @include context-menu-button;
+
+ .context-menu {
+ opacity: 0;
+ }
+
+ &.active {
+ .context-menu {
+ opacity: 1;
+ }
+ }
+
+ &.last-item {
+ @include context-menu-open-left;
+
+ .context-menu {
+ opacity: 1;
+ }
+ }
+
+ &:is(:hover, :focus, .active) {
+ @include context-menu-button-hover;
+ outline: none;
+
+ &.ds-card-grid-border {
+ @include fade-in-card;
+ }
+ }
+}
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSMessage/DSMessage.jsx b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSMessage/DSMessage.jsx
new file mode 100644
index 0000000000..df9ad4f641
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSMessage/DSMessage.jsx
@@ -0,0 +1,34 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import React from "react";
+import { SafeAnchor } from "../SafeAnchor/SafeAnchor";
+import { FluentOrText } from "content-src/components/FluentOrText/FluentOrText";
+
+export class DSMessage extends React.PureComponent {
+ render() {
+ return (
+ <div className="ds-message">
+ <header className="title">
+ {this.props.icon && (
+ <div
+ className="glyph"
+ style={{ backgroundImage: `url(${this.props.icon})` }}
+ />
+ )}
+ {this.props.title && (
+ <span className="title-text">
+ <FluentOrText message={this.props.title} />
+ </span>
+ )}
+ {this.props.link_text && this.props.link_url && (
+ <SafeAnchor className="link" url={this.props.link_url}>
+ <FluentOrText message={this.props.link_text} />
+ </SafeAnchor>
+ )}
+ </header>
+ </div>
+ );
+ }
+}
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSMessage/_DSMessage.scss b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSMessage/_DSMessage.scss
new file mode 100644
index 0000000000..41b4c3863b
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSMessage/_DSMessage.scss
@@ -0,0 +1,45 @@
+.ds-message {
+ margin: 8px 0 0;
+
+ .title {
+ display: flex;
+ align-items: center;
+
+ .glyph {
+ @include dark-theme-only {
+ fill: $grey-30;
+ }
+
+ width: 16px;
+ height: 16px;
+ margin: 0 6px 0 0;
+ -moz-context-properties: fill;
+ fill: $grey-50;
+ background-position: center center;
+ background-size: 16px;
+ background-repeat: no-repeat;
+ }
+
+ .title-text {
+ @include dark-theme-only {
+ color: $grey-30;
+ }
+
+ line-height: 20px;
+ font-size: 13px;
+ color: $grey-50;
+ font-weight: 600;
+ padding-right: 12px;
+ }
+
+ .link {
+ line-height: 20px;
+ font-size: 13px;
+
+ &:hover,
+ &:focus {
+ text-decoration: underline;
+ }
+ }
+ }
+}
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSPrivacyModal/DSPrivacyModal.jsx b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSPrivacyModal/DSPrivacyModal.jsx
new file mode 100644
index 0000000000..56bb4cc580
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSPrivacyModal/DSPrivacyModal.jsx
@@ -0,0 +1,69 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import React from "react";
+import { actionCreators as ac, actionTypes as at } from "common/Actions.jsm";
+import { ModalOverlayWrapper } from "content-src/asrouter/components/ModalOverlay/ModalOverlay";
+
+export class DSPrivacyModal extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.closeModal = this.closeModal.bind(this);
+ this.onLearnLinkClick = this.onLearnLinkClick.bind(this);
+ this.onManageLinkClick = this.onManageLinkClick.bind(this);
+ }
+
+ onLearnLinkClick(event) {
+ this.props.dispatch(
+ ac.UserEvent({
+ event: "CLICK_PRIVACY_INFO",
+ source: "DS_PRIVACY_MODAL",
+ })
+ );
+ }
+
+ onManageLinkClick(event) {
+ this.props.dispatch(ac.OnlyToMain({ type: at.SETTINGS_OPEN }));
+ }
+
+ closeModal() {
+ this.props.dispatch({
+ type: `HIDE_PRIVACY_INFO`,
+ data: {},
+ });
+ }
+
+ render() {
+ return (
+ <ModalOverlayWrapper
+ onClose={this.closeModal}
+ innerClassName="ds-privacy-modal"
+ >
+ <div className="privacy-notice">
+ <h3 data-l10n-id="newtab-privacy-modal-header" />
+ <p data-l10n-id="newtab-privacy-modal-paragraph-2" />
+ <a
+ className="modal-link modal-link-privacy"
+ data-l10n-id="newtab-privacy-modal-link"
+ onClick={this.onLearnLinkClick}
+ href="https://help.getpocket.com/article/1142-firefox-new-tab-recommendations-faq"
+ />
+ <button
+ className="modal-link modal-link-manage"
+ data-l10n-id="newtab-privacy-modal-button-manage"
+ onClick={this.onManageLinkClick}
+ />
+ </div>
+ <section className="actions">
+ <button
+ className="done"
+ type="submit"
+ onClick={this.closeModal}
+ data-l10n-id="newtab-privacy-modal-button-done"
+ />
+ </section>
+ </ModalOverlayWrapper>
+ );
+ }
+}
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSPrivacyModal/_DSPrivacyModal.scss b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSPrivacyModal/_DSPrivacyModal.scss
new file mode 100644
index 0000000000..d7dceac6e5
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSPrivacyModal/_DSPrivacyModal.scss
@@ -0,0 +1,48 @@
+.ds-privacy-modal {
+ .modal-link {
+ display: flex;
+ align-items: center;
+ margin: 0 0 8px;
+ border: 0;
+ padding: 0;
+ color: $blue-60;
+ width: max-content;
+
+ &:hover {
+ text-decoration: underline;
+ cursor: pointer;
+ }
+
+ &::before {
+ -moz-context-properties: fill;
+ fill: $blue-60;
+ content: '';
+ display: inline-block;
+ width: 16px;
+ height: 16px;
+ margin: 0;
+ margin-inline-end: 8px;
+ background-position: center center;
+ background-repeat: no-repeat;
+ background-size: 16px;
+ }
+
+ &.modal-link-privacy::before {
+ background-image: url('chrome://activity-stream/content/data/content/assets/glyph-info-16.svg');
+ }
+
+ &.modal-link-manage::before {
+ background-image: url('chrome://global/skin/icons/settings.svg');
+ }
+ }
+
+ p {
+ line-height: 24px;
+ }
+
+ .privacy-notice {
+ max-width: 572px;
+ padding: 40px;
+ margin: auto;
+ }
+}
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSSignup/DSSignup.jsx b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSSignup/DSSignup.jsx
new file mode 100644
index 0000000000..5ae2df57c2
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSSignup/DSSignup.jsx
@@ -0,0 +1,167 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { actionCreators as ac } from "common/Actions.jsm";
+import { LinkMenu } from "content-src/components/LinkMenu/LinkMenu";
+import { ContextMenuButton } from "content-src/components/ContextMenu/ContextMenuButton";
+import { ImpressionStats } from "../../DiscoveryStreamImpressionStats/ImpressionStats";
+import React from "react";
+import { SafeAnchor } from "../SafeAnchor/SafeAnchor";
+
+export class DSSignup extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.state = {
+ active: false,
+ lastItem: false,
+ };
+ this.onMenuButtonUpdate = this.onMenuButtonUpdate.bind(this);
+ this.onLinkClick = this.onLinkClick.bind(this);
+ this.onMenuShow = this.onMenuShow.bind(this);
+ }
+
+ onMenuButtonUpdate(showContextMenu) {
+ if (!showContextMenu) {
+ this.setState({
+ active: false,
+ lastItem: false,
+ });
+ }
+ }
+
+ nextAnimationFrame() {
+ return new Promise(resolve =>
+ this.props.windowObj.requestAnimationFrame(resolve)
+ );
+ }
+
+ async onMenuShow() {
+ let { lastItem } = this.state;
+ // Wait for next frame before computing scrollMaxX to allow fluent menu strings to be visible
+ await this.nextAnimationFrame();
+ if (this.props.windowObj.scrollMaxX > 0) {
+ lastItem = true;
+ }
+ this.setState({
+ active: true,
+ lastItem,
+ });
+ }
+
+ onLinkClick() {
+ const { data } = this.props;
+ if (this.props.dispatch && data && data.spocs && data.spocs.length) {
+ const source = this.props.type.toUpperCase();
+ // Grab the first item in the array as we only have 1 spoc position.
+ const [spoc] = data.spocs;
+ this.props.dispatch(
+ ac.UserEvent({
+ event: "CLICK",
+ source,
+ action_position: 0,
+ })
+ );
+
+ this.props.dispatch(
+ ac.ImpressionStats({
+ source,
+ click: 0,
+ tiles: [
+ {
+ id: spoc.id,
+ pos: 0,
+ ...(spoc.shim && spoc.shim.click
+ ? { shim: spoc.shim.click }
+ : {}),
+ },
+ ],
+ })
+ );
+ }
+ }
+
+ render() {
+ const { data, dispatch, type } = this.props;
+ if (!data || !data.spocs || !data.spocs[0]) {
+ return null;
+ }
+ // Grab the first item in the array as we only have 1 spoc position.
+ const [spoc] = data.spocs;
+ const { title, url, excerpt, flight_id, id, shim } = spoc;
+
+ const SIGNUP_CONTEXT_MENU_OPTIONS = [
+ "OpenInNewWindow",
+ "OpenInPrivateWindow",
+ "Separator",
+ "BlockUrl",
+ ...(flight_id ? ["ShowPrivacyInfo"] : []),
+ ];
+
+ const outerClassName = [
+ "ds-signup",
+ this.state.active && "active",
+ this.state.lastItem && "last-item",
+ ]
+ .filter(v => v)
+ .join(" ");
+
+ return (
+ <div className={outerClassName}>
+ <div className="ds-signup-content">
+ <span className="icon icon-small-spacer icon-mail"></span>
+ <span>
+ {title}{" "}
+ <SafeAnchor
+ className="ds-chevron-link"
+ dispatch={dispatch}
+ onLinkClick={this.onLinkClick}
+ url={url}
+ >
+ {excerpt}
+ </SafeAnchor>
+ </span>
+ <ImpressionStats
+ flightId={flight_id}
+ rows={[
+ {
+ id,
+ pos: 0,
+ shim: shim && shim.impression,
+ },
+ ]}
+ dispatch={dispatch}
+ source={type}
+ />
+ </div>
+ <ContextMenuButton
+ tooltip={"newtab-menu-content-tooltip"}
+ tooltipArgs={{ title }}
+ onUpdate={this.onMenuButtonUpdate}
+ >
+ <LinkMenu
+ dispatch={dispatch}
+ index={0}
+ source={type.toUpperCase()}
+ onShow={this.onMenuShow}
+ options={SIGNUP_CONTEXT_MENU_OPTIONS}
+ shouldSendImpressionStats={true}
+ site={{
+ referrer: "https://getpocket.com/recommendations",
+ title,
+ type,
+ url,
+ guid: id,
+ shim,
+ flight_id,
+ }}
+ />
+ </ContextMenuButton>
+ </div>
+ );
+ }
+}
+
+DSSignup.defaultProps = {
+ windowObj: window, // Added to support unit tests
+};
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSSignup/DSSignup.scss b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSSignup/DSSignup.scss
new file mode 100644
index 0000000000..758076f168
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSSignup/DSSignup.scss
@@ -0,0 +1,52 @@
+.ds-signup {
+ max-width: 300px;
+ margin: 0 auto;
+ padding: 8px;
+ position: relative;
+ text-align: center;
+ font-size: 17px;
+ font-weight: 600;
+
+ &:hover {
+ background: var(--newtab-element-hover-color);
+ border-radius: 4px;
+ }
+
+ .icon-mail {
+ height: 40px;
+ width: 40px;
+ margin-inline-end: 8px;
+ fill: #{$grey-40};
+ background-size: 30px;
+ flex-shrink: 0;
+ }
+
+ .ds-signup-content {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ flex-direction: column;
+
+ .ds-chevron-link {
+ margin-top: 4px;
+ box-shadow: none;
+ display: block;
+ white-space: nowrap;
+ }
+ }
+
+ @media (min-width: $break-point-large) {
+ min-width: 756px;
+ width: max-content;
+ text-align: start;
+
+ .ds-signup-content {
+ flex-direction: row;
+
+ .ds-chevron-link {
+ margin-top: 0;
+ display: inline;
+ }
+ }
+ }
+}
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSTextPromo/DSTextPromo.jsx b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSTextPromo/DSTextPromo.jsx
new file mode 100644
index 0000000000..a0040ac650
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSTextPromo/DSTextPromo.jsx
@@ -0,0 +1,143 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { actionCreators as ac } from "common/Actions.jsm";
+import { DSDismiss } from "content-src/components/DiscoveryStreamComponents/DSDismiss/DSDismiss";
+import { DSImage } from "../DSImage/DSImage.jsx";
+import { ImpressionStats } from "../../DiscoveryStreamImpressionStats/ImpressionStats";
+import { LinkMenuOptions } from "content-src/lib/link-menu-options";
+import React from "react";
+import { SafeAnchor } from "../SafeAnchor/SafeAnchor";
+
+export class DSTextPromo extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onLinkClick = this.onLinkClick.bind(this);
+ this.onDismissClick = this.onDismissClick.bind(this);
+ }
+
+ onLinkClick() {
+ const { data } = this.props;
+ if (this.props.dispatch && data && data.spocs && data.spocs.length) {
+ const source = this.props.type.toUpperCase();
+ // Grab the first item in the array as we only have 1 spoc position.
+ const [spoc] = data.spocs;
+ this.props.dispatch(
+ ac.UserEvent({
+ event: "CLICK",
+ source,
+ action_position: 0,
+ })
+ );
+
+ this.props.dispatch(
+ ac.ImpressionStats({
+ source,
+ click: 0,
+ tiles: [
+ {
+ id: spoc.id,
+ pos: 0,
+ ...(spoc.shim && spoc.shim.click
+ ? { shim: spoc.shim.click }
+ : {}),
+ },
+ ],
+ })
+ );
+ }
+ }
+
+ onDismissClick() {
+ const { data } = this.props;
+ if (this.props.dispatch && data && data.spocs && data.spocs.length) {
+ const index = 0;
+ const source = this.props.type.toUpperCase();
+ // Grab the first item in the array as we only have 1 spoc position.
+ const [spoc] = data.spocs;
+ const spocData = {
+ url: spoc.url,
+ guid: spoc.id,
+ shim: spoc.shim,
+ };
+ const blockUrlOption = LinkMenuOptions.BlockUrl(spocData, index, source);
+
+ const { action, impression, userEvent } = blockUrlOption;
+
+ this.props.dispatch(action);
+ this.props.dispatch(
+ ac.UserEvent({
+ event: userEvent,
+ source,
+ action_position: index,
+ })
+ );
+ if (impression) {
+ this.props.dispatch(impression);
+ }
+ }
+ }
+
+ render() {
+ const { data } = this.props;
+ if (!data || !data.spocs || !data.spocs[0]) {
+ return null;
+ }
+ // Grab the first item in the array as we only have 1 spoc position.
+ const [spoc] = data.spocs;
+ const {
+ image_src,
+ raw_image_src,
+ alt_text,
+ title,
+ url,
+ context,
+ cta,
+ flight_id,
+ id,
+ shim,
+ } = spoc;
+
+ return (
+ <DSDismiss
+ onDismissClick={this.onDismissClick}
+ extraClasses={`ds-dismiss-ds-text-promo`}
+ >
+ <div className="ds-text-promo">
+ <DSImage
+ alt_text={alt_text}
+ source={image_src}
+ rawSource={raw_image_src}
+ />
+ <div className="text">
+ <h3>
+ {`${title}\u2003`}
+ <SafeAnchor
+ className="ds-chevron-link"
+ dispatch={this.props.dispatch}
+ onLinkClick={this.onLinkClick}
+ url={url}
+ >
+ {cta}
+ </SafeAnchor>
+ </h3>
+ <p className="subtitle">{context}</p>
+ </div>
+ <ImpressionStats
+ flightId={flight_id}
+ rows={[
+ {
+ id,
+ pos: 0,
+ shim: shim && shim.impression,
+ },
+ ]}
+ dispatch={this.props.dispatch}
+ source={this.props.type}
+ />
+ </div>
+ </DSDismiss>
+ );
+ }
+}
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSTextPromo/_DSTextPromo.scss b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSTextPromo/_DSTextPromo.scss
new file mode 100644
index 0000000000..6dea98d802
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/DSTextPromo/_DSTextPromo.scss
@@ -0,0 +1,119 @@
+.ds-dismiss-ds-text-promo {
+ max-width: 744px;
+ margin: auto;
+ overflow: hidden;
+
+ &.hovering {
+ @include dark-theme-only {
+ background: $grey-90-30;
+ }
+
+ background: $grey-90-10;
+ }
+
+ .ds-dismiss-button {
+ margin-inline: 0 18px;
+ margin-block: 18px 0;
+ }
+}
+
+.ds-text-promo {
+ max-width: 640px;
+ margin: 0;
+ padding: 18px;
+
+ @media(min-width: $break-point-medium) {
+ display: flex;
+ margin: 18px 24px;
+ padding: 0 32px 0 0;
+ }
+
+ .ds-image {
+ width: 40px;
+ height: 40px;
+ flex-shrink: 0;
+ margin: 0 0 18px;
+
+ @media(min-width: $break-point-medium) {
+ margin: 4px 12px 0 0;
+ }
+
+ img {
+ border-radius: 4px;
+ }
+ }
+
+ .text {
+ line-height: 24px;
+ }
+
+ h3 {
+ @include dark-theme-only {
+ color: $grey-10;
+ }
+
+ margin: 0;
+ font-weight: 600;
+ font-size: 15px;
+ }
+
+ .subtitle {
+ @include dark-theme-only {
+ color: $grey-40;
+ }
+
+ font-size: 13px;
+ margin: 0;
+ color: $grey-50;
+ }
+}
+
+.ds-chevron-link {
+ color: $blue-60;
+ display: inline-block;
+ outline: 0;
+
+ &:hover {
+ text-decoration: underline;
+ }
+
+ &:active {
+ @include dark-theme-only {
+ color: $blue-50;
+ }
+
+ color: $blue-70;
+
+ &::after {
+ @include dark-theme-only {
+ background-color: $blue-50;
+ }
+
+ background-color: $blue-70;
+ }
+ }
+
+ &:focus {
+ @include dark-theme-only {
+ box-shadow: 0 0 0 2px $grey-80, 0 0 0 5px $blue-50-50;
+ }
+
+ box-shadow: 0 0 0 2px $white, 0 0 0 5px $blue-50-50;
+ border-radius: 2px;
+ }
+
+ &::after {
+ @include dark-theme-only {
+ background-color: $blue-40;
+ }
+
+ content: ' ';
+ mask: url('chrome://activity-stream/content/data/content/assets/glyph-caret-right.svg') 0 -8px no-repeat;
+ background-color: $blue-60;
+ margin: 0 0 0 4px;
+ width: 5px;
+ height: 8px;
+ text-decoration: none;
+ display: inline-block;
+ }
+}
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamComponents/Hero/Hero.jsx b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/Hero/Hero.jsx
new file mode 100644
index 0000000000..eaa9ed20c5
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/Hero/Hero.jsx
@@ -0,0 +1,207 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { DSCard, PlaceholderDSCard } from "../DSCard/DSCard.jsx";
+import { actionCreators as ac } from "common/Actions.jsm";
+import { DSEmptyState } from "../DSEmptyState/DSEmptyState.jsx";
+import { DSImage } from "../DSImage/DSImage.jsx";
+import { DSLinkMenu } from "../DSLinkMenu/DSLinkMenu";
+import { ImpressionStats } from "../../DiscoveryStreamImpressionStats/ImpressionStats";
+import { List } from "../List/List.jsx";
+import React from "react";
+import { SafeAnchor } from "../SafeAnchor/SafeAnchor";
+import { DSContextFooter } from "../DSContextFooter/DSContextFooter.jsx";
+
+export class Hero extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onLinkClick = this.onLinkClick.bind(this);
+ }
+
+ onLinkClick(event) {
+ if (this.props.dispatch) {
+ this.props.dispatch(
+ ac.UserEvent({
+ event: "CLICK",
+ source: this.props.type.toUpperCase(),
+ action_position: this.heroRec.pos,
+ })
+ );
+
+ this.props.dispatch(
+ ac.ImpressionStats({
+ source: this.props.type.toUpperCase(),
+ click: 0,
+ tiles: [
+ {
+ id: this.heroRec.id,
+ pos: this.heroRec.pos,
+ ...(this.heroRec.shim && this.heroRec.shim.click
+ ? { shim: this.heroRec.shim.click }
+ : {}),
+ },
+ ],
+ })
+ );
+ }
+ }
+
+ renderHero() {
+ let [heroRec, ...otherRecs] = this.props.data.recommendations.slice(
+ 0,
+ this.props.items
+ );
+ this.heroRec = heroRec;
+
+ const cards = [];
+ for (let index = 0; index < this.props.items - 1; index++) {
+ const rec = otherRecs[index];
+ cards.push(
+ !rec || rec.placeholder ? (
+ <PlaceholderDSCard key={`dscard-${index}`} />
+ ) : (
+ <DSCard
+ flightId={rec.flight_id}
+ key={`dscard-${rec.id}`}
+ image_src={rec.image_src}
+ raw_image_src={rec.raw_image_src}
+ title={rec.title}
+ url={rec.url}
+ id={rec.id}
+ shim={rec.shim}
+ pos={rec.pos}
+ type={this.props.type}
+ dispatch={this.props.dispatch}
+ context={rec.context}
+ context_type={rec.context_type}
+ source={rec.domain}
+ pocket_id={rec.pocket_id}
+ bookmarkGuid={rec.bookmarkGuid}
+ engagement={rec.engagement}
+ />
+ )
+ );
+ }
+
+ let heroCard = null;
+
+ if (!heroRec || heroRec.placeholder) {
+ heroCard = <PlaceholderDSCard />;
+ } else {
+ heroCard = (
+ <div className="ds-hero-item" key={`dscard-${heroRec.id}`}>
+ <SafeAnchor
+ className="wrapper"
+ dispatch={this.props.dispatch}
+ onLinkClick={this.onLinkClick}
+ url={heroRec.url}
+ >
+ <div className="img-wrapper">
+ <DSImage
+ extraClassNames="img"
+ source={heroRec.image_src}
+ rawSource={heroRec.raw_image_src}
+ />
+ </div>
+ <div className="meta">
+ <div className="header-and-excerpt">
+ <p className="source clamp">{heroRec.domain}</p>
+ <header className="clamp">{heroRec.title}</header>
+ <p className="excerpt clamp">{heroRec.excerpt}</p>
+ </div>
+ <DSContextFooter
+ context={heroRec.context}
+ context_type={heroRec.context_type}
+ engagement={heroRec.engagement}
+ />
+ </div>
+ <ImpressionStats
+ flightId={heroRec.flight_id}
+ rows={[
+ {
+ id: heroRec.id,
+ pos: heroRec.pos,
+ ...(heroRec.shim && heroRec.shim.impression
+ ? { shim: heroRec.shim.impression }
+ : {}),
+ },
+ ]}
+ dispatch={this.props.dispatch}
+ source={this.props.type}
+ />
+ </SafeAnchor>
+ <DSLinkMenu
+ id={heroRec.id}
+ index={heroRec.pos}
+ dispatch={this.props.dispatch}
+ url={heroRec.url}
+ title={heroRec.title}
+ source={heroRec.domain}
+ type={this.props.type}
+ pocket_id={heroRec.pocket_id}
+ shim={heroRec.shim}
+ bookmarkGuid={heroRec.bookmarkGuid}
+ flightId={heroRec.flight_id}
+ />
+ </div>
+ );
+ }
+
+ let list = (
+ <List
+ recStartingPoint={1}
+ data={this.props.data}
+ feed={this.props.feed}
+ hasImages={true}
+ hasBorders={this.props.border === `border`}
+ items={this.props.items - 1}
+ type={`Hero`}
+ />
+ );
+
+ return (
+ <div className={`ds-hero ds-hero-${this.props.border}`}>
+ {heroCard}
+ <div className={`${this.props.subComponentType}`}>
+ {this.props.subComponentType === `cards` ? cards : list}
+ </div>
+ </div>
+ );
+ }
+
+ render() {
+ const { data } = this.props;
+
+ // Handle a render before feed has been fetched by displaying nothing
+ if (!data || !data.recommendations) {
+ return <div />;
+ }
+
+ // Handle the case where a user has dismissed all recommendations
+ const isEmpty = data.recommendations.length === 0;
+
+ return (
+ <div>
+ <div className="ds-header">{this.props.title}</div>
+ {isEmpty ? (
+ <div className="ds-hero empty">
+ <DSEmptyState
+ status={data.status}
+ dispatch={this.props.dispatch}
+ feed={this.props.feed}
+ />
+ </div>
+ ) : (
+ this.renderHero()
+ )}
+ </div>
+ );
+ }
+}
+
+Hero.defaultProps = {
+ data: {},
+ border: `border`,
+ items: 1, // Number of stories to display
+};
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamComponents/Hero/_Hero.scss b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/Hero/_Hero.scss
new file mode 100644
index 0000000000..ed81e42946
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/Hero/_Hero.scss
@@ -0,0 +1,282 @@
+$card-header-in-hero-font-size: 14;
+$card-header-in-hero-line-height: 20;
+
+.ds-hero {
+ position: relative;
+
+ header {
+ font-weight: 600;
+ }
+
+ p {
+ line-height: 1.538;
+ margin: 8px 0;
+ }
+
+ .excerpt {
+ @include limit-visible-lines(3, 24, 15);
+ @include dark-theme-only {
+ color: $grey-10;
+ }
+
+ color: $grey-90;
+ margin: 0 0 10px;
+ }
+
+ .ds-card:not(.placeholder) {
+ border: 0;
+ padding-bottom: 20px;
+
+ &:hover {
+ border: 0;
+ box-shadow: none;
+ border-radius: 0;
+ }
+
+ .meta {
+ padding: 0;
+ }
+
+ .img-wrapper {
+ margin: 0 0 12px;
+ }
+ }
+
+ .ds-card.placeholder {
+ margin-bottom: 20px;
+ padding-bottom: 20px;
+ min-height: 180px;
+ }
+
+ .img-wrapper {
+ margin: 0 0 12px;
+ }
+
+ .ds-hero-item {
+ position: relative;
+ }
+
+ // "1/3 width layout" (aka "Mobile First")
+ .wrapper {
+ @include ds-border-top;
+ @include dark-theme-only {
+ color: $grey-30;
+ }
+
+ color: $grey-50;
+ display: block;
+ margin: 12px 0 16px;
+ padding-top: 16px;
+ height: 100%;
+
+ &:focus {
+ @include ds-fade-in;
+ }
+
+ @at-root .ds-hero-no-border .ds-hero-item .wrapper {
+ border-top: 0;
+ border-bottom: 0;
+ padding: 0 0 8px;
+ }
+
+ &:hover .meta header {
+ @include dark-theme-only {
+ color: $blue-40;
+ }
+
+ color: $blue-60;
+ }
+
+ &:active .meta header {
+ @include dark-theme-only {
+ color: $blue-40;
+ }
+
+ color: $blue-70;
+ }
+
+ .img-wrapper {
+ width: 100%;
+ }
+
+ .img {
+ height: 0;
+ padding-top: 50%; // 2:1 aspect ratio
+
+ img {
+ border-radius: 4px;
+ box-shadow: inset 0 0 0 0.5px $black-15;
+ }
+ }
+
+ .meta {
+ display: block;
+ flex-direction: column;
+ justify-content: space-between;
+
+ .header-and-excerpt {
+ flex: 1;
+ }
+
+ header {
+ @include dark-theme-only {
+ color: $white;
+ }
+
+ @include limit-visible-lines(4, 28, 22);
+ color: $grey-90;
+ margin-bottom: 0;
+ }
+
+ .context,
+ .source {
+ margin: 0 0 4px;
+ }
+
+ .context {
+ @include dark-theme-only {
+ color: $teal-10;
+ }
+
+ color: $teal-70;
+ }
+
+ .source {
+ @include dark-theme-only {
+ color: $grey-40;
+ }
+
+ font-size: 13px;
+ color: $grey-50;
+ -webkit-line-clamp: 1;
+ margin-bottom: 0;
+ }
+ }
+ }
+
+ // "2/3 width layout"
+ .ds-column-5 &,
+ .ds-column-6 &,
+ .ds-column-7 &,
+ .ds-column-8 & {
+ .wrapper {
+ display: grid;
+ grid-template-columns: repeat(2, 1fr);
+ grid-column-gap: 24px;
+
+ .img-wrapper {
+ margin: 0;
+ grid-column: 2;
+ grid-row: 1;
+ }
+
+ .meta {
+ grid-column: 1;
+ grid-row: 1;
+ display: flex;
+ }
+
+ .img {
+ height: 0;
+ padding-top: 100%; // 1:1 aspect ratio
+ }
+ }
+
+ .cards {
+ display: grid;
+ grid-template-columns: repeat(2, 1fr);
+ grid-column-gap: 24px;
+ grid-auto-rows: min-content;
+ }
+ }
+
+ // "Full width layout"
+ .ds-column-9 &,
+ .ds-column-10 &,
+ .ds-column-11 &,
+ .ds-column-12 & {
+ display: grid;
+ grid-template-columns: repeat(2, 1fr);
+ grid-column-gap: 24px;
+
+ &.ds-hero-border {
+ @include ds-border-top;
+ padding: 20px 0;
+
+ .ds-card:not(.placeholder):nth-child(-n+2) {
+ @include ds-border-bottom;
+ margin-bottom: 20px;
+ }
+ }
+
+ .wrapper {
+ border-top: 0;
+ border-bottom: 0;
+ margin: 0;
+ padding: 0 0 20px;
+ display: flex;
+ flex-direction: column;
+
+ .img-wrapper {
+ margin: 0;
+ }
+
+ .img {
+ margin-bottom: 12px;
+ height: 0;
+ padding-top: 50%; // 2:1 aspect ratio
+ }
+
+ .meta {
+ flex-grow: 1;
+ display: flex;
+ padding: 0 24px 0 0;
+
+ header {
+ @include limit-visible-lines(3, 28, 22);
+ }
+
+ .source {
+ margin-bottom: 0;
+ }
+ }
+ }
+
+ .cards {
+ display: grid;
+ grid-template-columns: repeat(2, 1fr);
+ grid-column-gap: 24px;
+ grid-auto-rows: min-content;
+
+ .ds-card {
+ &:hover {
+ @include dark-theme-only {
+ background: none;
+
+ .title {
+ color: $blue-40;
+ }
+ }
+ }
+
+ &:active .title {
+ @include dark-theme-only {
+ color: $blue-50;
+ }
+ }
+
+ .title {
+ @include dark-theme-only {
+ color: $white;
+ }
+
+ @include limit-visible-lines(3, 20, 14);
+ }
+ }
+ }
+ }
+
+ &.empty {
+ grid-template-columns: auto;
+ }
+}
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamComponents/Highlights/Highlights.jsx b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/Highlights/Highlights.jsx
new file mode 100644
index 0000000000..d0cc87cce3
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/Highlights/Highlights.jsx
@@ -0,0 +1,26 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { connect } from "react-redux";
+import React from "react";
+import { SectionIntl } from "content-src/components/Sections/Sections";
+
+export class _Highlights extends React.PureComponent {
+ render() {
+ const section = this.props.Sections.find(s => s.id === "highlights");
+ if (!section || !section.enabled) {
+ return null;
+ }
+
+ return (
+ <div className="ds-highlights sections-list">
+ <SectionIntl {...section} isFixed={true} />
+ </div>
+ );
+ }
+}
+
+export const Highlights = connect(state => ({ Sections: state.Sections }))(
+ _Highlights
+);
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamComponents/Highlights/_Highlights.scss b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/Highlights/_Highlights.scss
new file mode 100644
index 0000000000..bf0a0557da
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/Highlights/_Highlights.scss
@@ -0,0 +1,40 @@
+.ds-highlights {
+ .section {
+ .section-list {
+ grid-gap: var(--gridRowGap);
+ grid-template-columns: repeat(1, 1fr);
+
+ @media (min-width: $break-point-medium) {
+ grid-template-columns: repeat(2, 1fr);
+ }
+
+ @media (min-width: $break-point-large) {
+ grid-template-columns: repeat(4, 1fr);
+ }
+
+ .card-outer {
+ $line-height: 20px;
+ height: 175px;
+
+ .card-host-name {
+ font-size: 13px;
+ line-height: $line-height;
+ margin-bottom: 2px;
+ padding-bottom: 0;
+ text-transform: unset; // sass-lint:disable-line no-disallowed-properties
+ }
+
+ .card-title {
+ font-size: 14px;
+ font-weight: 600;
+ line-height: $line-height;
+ max-height: $line-height;
+ }
+ }
+ }
+ }
+
+ .hide-for-narrow {
+ display: block;
+ }
+}
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamComponents/HorizontalRule/HorizontalRule.jsx b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/HorizontalRule/HorizontalRule.jsx
new file mode 100644
index 0000000000..4cdfc7594f
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/HorizontalRule/HorizontalRule.jsx
@@ -0,0 +1,11 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import React from "react";
+
+export class HorizontalRule extends React.PureComponent {
+ render() {
+ return <hr className="ds-hr" />;
+ }
+}
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamComponents/HorizontalRule/_HorizontalRule.scss b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/HorizontalRule/_HorizontalRule.scss
new file mode 100644
index 0000000000..aa5d6ff9f3
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/HorizontalRule/_HorizontalRule.scss
@@ -0,0 +1,7 @@
+.ds-hr {
+ @include ds-border-top {
+ border: 0;
+ };
+
+ height: 0;
+}
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamComponents/List/List.jsx b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/List/List.jsx
new file mode 100644
index 0000000000..057d507099
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/List/List.jsx
@@ -0,0 +1,221 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { actionCreators as ac } from "common/Actions.jsm";
+import { connect } from "react-redux";
+import { DSEmptyState } from "../DSEmptyState/DSEmptyState.jsx";
+import { DSImage } from "../DSImage/DSImage.jsx";
+import { DSLinkMenu } from "../DSLinkMenu/DSLinkMenu";
+import { ImpressionStats } from "../../DiscoveryStreamImpressionStats/ImpressionStats";
+import React from "react";
+import { SafeAnchor } from "../SafeAnchor/SafeAnchor";
+import { DSContextFooter } from "../DSContextFooter/DSContextFooter.jsx";
+
+/**
+ * @note exported for testing only
+ */
+export class ListItem extends React.PureComponent {
+ // TODO performance: get feeds to send appropriately sized images rather
+ // than waiting longer and scaling down on client?
+ constructor(props) {
+ super(props);
+ this.onLinkClick = this.onLinkClick.bind(this);
+ }
+
+ onLinkClick(event) {
+ if (this.props.dispatch) {
+ this.props.dispatch(
+ ac.UserEvent({
+ event: "CLICK",
+ source: this.props.type.toUpperCase(),
+ action_position: this.props.pos,
+ value: { card_type: this.props.flightId ? "spoc" : "organic" },
+ })
+ );
+
+ this.props.dispatch(
+ ac.ImpressionStats({
+ source: this.props.type.toUpperCase(),
+ click: 0,
+ tiles: [
+ {
+ id: this.props.id,
+ pos: this.props.pos,
+ ...(this.props.shim && this.props.shim.click
+ ? { shim: this.props.shim.click }
+ : {}),
+ },
+ ],
+ })
+ );
+ }
+ }
+
+ render() {
+ return (
+ <li
+ className={`ds-list-item${
+ this.props.placeholder ? " placeholder" : ""
+ }`}
+ >
+ <SafeAnchor
+ className="ds-list-item-link"
+ dispatch={this.props.dispatch}
+ onLinkClick={!this.props.placeholder ? this.onLinkClick : undefined}
+ url={this.props.url}
+ >
+ <div className="ds-list-item-text">
+ <p>
+ <span className="ds-list-item-info clamp">
+ {this.props.domain}
+ </span>
+ </p>
+ <div className="ds-list-item-body">
+ <div className="ds-list-item-title clamp">{this.props.title}</div>
+ {this.props.excerpt && (
+ <div className="ds-list-item-excerpt clamp">
+ {this.props.excerpt}
+ </div>
+ )}
+ </div>
+ <DSContextFooter
+ context={this.props.context}
+ context_type={this.props.context_type}
+ engagement={this.props.engagement}
+ />
+ </div>
+ <DSImage
+ extraClassNames="ds-list-image"
+ source={this.props.image_src}
+ rawSource={this.props.raw_image_src}
+ />
+ <ImpressionStats
+ flightId={this.props.flightId}
+ rows={[
+ {
+ id: this.props.id,
+ pos: this.props.pos,
+ ...(this.props.shim && this.props.shim.impression
+ ? { shim: this.props.shim.impression }
+ : {}),
+ },
+ ]}
+ dispatch={this.props.dispatch}
+ source={this.props.type}
+ />
+ </SafeAnchor>
+ {!this.props.placeholder && (
+ <DSLinkMenu
+ id={this.props.id}
+ index={this.props.pos}
+ dispatch={this.props.dispatch}
+ url={this.props.url}
+ title={this.props.title}
+ source={this.props.source}
+ type={this.props.type}
+ pocket_id={this.props.pocket_id}
+ shim={this.props.shim}
+ bookmarkGuid={this.props.bookmarkGuid}
+ flightId={this.props.flightId}
+ />
+ )}
+ </li>
+ );
+ }
+}
+
+export const PlaceholderListItem = props => <ListItem placeholder={true} />;
+
+/**
+ * @note exported for testing only
+ */
+export function _List(props) {
+ const renderList = () => {
+ const recs = props.data.recommendations.slice(
+ props.recStartingPoint,
+ props.recStartingPoint + props.items
+ );
+ const recMarkup = [];
+
+ for (let index = 0; index < props.items; index++) {
+ const rec = recs[index];
+ recMarkup.push(
+ !rec || rec.placeholder ? (
+ <PlaceholderListItem key={`ds-list-item-${index}`} />
+ ) : (
+ <ListItem
+ key={`ds-list-item-${rec.id}`}
+ dispatch={props.dispatch}
+ flightId={rec.flight_id}
+ domain={rec.domain}
+ excerpt={rec.excerpt}
+ id={rec.id}
+ shim={rec.shim}
+ image_src={rec.image_src}
+ raw_image_src={rec.raw_image_src}
+ pos={rec.pos}
+ title={rec.title}
+ context={rec.context}
+ context_type={rec.context_type}
+ type={props.type}
+ url={rec.url}
+ pocket_id={rec.pocket_id}
+ bookmarkGuid={rec.bookmarkGuid}
+ engagement={rec.engagement}
+ />
+ )
+ );
+ }
+
+ const listStyles = [
+ "ds-list",
+ props.fullWidth ? "ds-list-full-width" : "",
+ props.hasBorders ? "ds-list-borders" : "",
+ props.hasImages ? "ds-list-images" : "",
+ props.hasNumbers ? "ds-list-numbers" : "",
+ ];
+
+ return <ul className={listStyles.join(" ")}>{recMarkup}</ul>;
+ };
+
+ const { data } = props;
+ if (!data || !data.recommendations) {
+ return null;
+ }
+
+ // Handle the case where a user has dismissed all recommendations
+ const isEmpty = data.recommendations.length === 0;
+
+ return (
+ <div>
+ {props.header && props.header.title ? (
+ <div className="ds-header">{props.header.title}</div>
+ ) : null}
+ {isEmpty ? (
+ <div className="ds-list empty">
+ <DSEmptyState
+ status={data.status}
+ dispatch={props.dispatch}
+ feed={props.feed}
+ />
+ </div>
+ ) : (
+ renderList()
+ )}
+ </div>
+ );
+}
+
+_List.defaultProps = {
+ recStartingPoint: 0, // Index of recommendations to start displaying from
+ fullWidth: false, // Display items taking up the whole column
+ hasBorders: false, // Display lines separating each item
+ hasImages: false, // Display images for each item
+ hasNumbers: false, // Display numbers for each item
+ items: 6, // Number of stories to display. TODO: get from endpoint
+};
+
+export const List = connect(state => ({
+ DiscoveryStream: state.DiscoveryStream,
+}))(_List);
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamComponents/List/_List.scss b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/List/_List.scss
new file mode 100644
index 0000000000..6841ed4a46
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/List/_List.scss
@@ -0,0 +1,269 @@
+// Type sizes
+$bordered-spacing: 16px;
+$item-font-size: 14;
+$item-image-size: 80px;
+$item-line-height: 20;
+
+// XXX this is gross, and attaches the bottom-border to the item above.
+// Ideally, we'd attach the top-border to the item that needs it.
+// Unfortunately the border needs to go _above_ the row gap as currently
+// set up, which means that some refactoring will be required to do this.
+@mixin bottom-border-except-last-grid-row($columns) {
+ .ds-list-item:not(.placeholder):not(:nth-last-child(-n+#{$columns})) {
+ @include ds-border-bottom;
+ margin-bottom: -1px; // cancel out the pixel we used for the border
+ padding-bottom: $bordered-spacing;
+ }
+}
+
+@mixin set-item-sizes($font-size, $line-height, $image-size) {
+ .ds-list-item {
+ // XXX see if we really want absolute units, maybe hoist somewhere central?
+ font-size: $font-size * 1px;
+ line-height: $line-height * 1px;
+ position: relative;
+ }
+
+ .ds-list-item-title {
+ @include limit-visible-lines(3, $line-height, $font-size);
+ }
+
+ .ds-list-image {
+ min-width: $image-size;
+ width: $image-size;
+ }
+}
+
+.ds-list {
+ display: grid;
+ grid-row-gap: 24px;
+ grid-column-gap: 24px;
+
+ // reset some stuff from <ul>. Should maybe be hoisted when we have better
+ // regression detection?
+ padding-inline-start: 0;
+
+ &:not(.ds-list-full-width) {
+ @include set-item-sizes($item-font-size, $item-line-height, $item-image-size);
+
+ // "2/3 width layout"
+ .ds-column-5 &,
+ .ds-column-6 &,
+ .ds-column-7 &,
+ .ds-column-8 & {
+ grid-template-columns: repeat(2, 1fr);
+ }
+
+ // "Full width layout"
+ .ds-column-9 &,
+ .ds-column-10 &,
+ .ds-column-11 &,
+ .ds-column-12 & {
+ grid-template-columns: repeat(3, 1fr);
+ }
+
+ &.empty {
+ grid-template-columns: auto;
+ }
+
+ .ds-list-item-excerpt {
+ display: none;
+ }
+ }
+
+ &:not(.ds-list-images) {
+ .ds-list-image {
+ display: none;
+ }
+ }
+
+ a {
+ @include dark-theme-only {
+ color: $grey-10;
+ }
+
+ color: $grey-90;
+ }
+}
+
+.ds-list-item-link:focus {
+ @include ds-fade-in;
+}
+
+.ds-list-numbers {
+ $counter-whitespace: ($item-line-height - $item-font-size) * 1px;
+ $counter-size: 32px;
+ $counter-padded-size: $counter-size + $counter-whitespace * 1.5;
+
+ .ds-list-item {
+ counter-increment: list;
+ }
+
+ .ds-list-item:not(.placeholder) > .ds-list-item-link {
+ padding-inline-start: $counter-padded-size;
+
+ &::before {
+ @include dark-theme-only {
+ background-color: $teal-70;
+ }
+
+ background-color: $pocket-teal;
+ border-radius: $counter-size;
+ color: $white;
+ content: counter(list);
+ font-size: 17px;
+ height: $counter-size;
+ line-height: $counter-size;
+ margin-inline-start: -$counter-padded-size;
+ margin-top: $counter-whitespace / 2;
+ position: absolute;
+ text-align: center;
+ width: $counter-size;
+ }
+
+ &:hover::before {
+ @include dark-theme-only {
+ background-color: $blue-40;
+ }
+
+ background-color: $blue-40;
+ }
+
+ &:active::before {
+ @include dark-theme-only {
+ background-color: $blue-60;
+ }
+
+ background-color: $blue-70;
+ }
+ }
+}
+
+.ds-list-borders {
+ @include ds-border-top;
+ grid-row-gap: $bordered-spacing;
+ padding-top: $bordered-spacing;
+
+ &.ds-list-full-width,
+ .ds-column-1 &,
+ .ds-column-2 &,
+ .ds-column-3 &,
+ .ds-column-4 & {
+ @include bottom-border-except-last-grid-row(1);
+ }
+
+ &:not(.ds-list-full-width) {
+ // "2/3 width layout"
+ .ds-column-5 &,
+ .ds-column-6 &,
+ .ds-column-7 &,
+ .ds-column-8 & {
+ @include bottom-border-except-last-grid-row(2);
+ }
+
+ // "Full width layout"
+ .ds-column-9 &,
+ .ds-column-10 &,
+ .ds-column-11 &,
+ .ds-column-12 & {
+ @include bottom-border-except-last-grid-row(3);
+ }
+ }
+}
+
+.ds-list-full-width {
+ @include set-item-sizes(17, 24, $item-image-size * 2);
+}
+
+.ds-list-item {
+ // reset some stuff from <li>. Should maybe be hoisted when we have better
+ // regression detection?
+ display: block;
+ text-align: start;
+
+ &.placeholder {
+ background: transparent;
+ min-height: $item-image-size;
+ box-shadow: inset $inner-box-shadow;
+ border-radius: 4px;
+
+ .ds-list-item-link {
+ cursor: default;
+ }
+
+ .ds-list-image {
+ opacity: 0;
+ }
+ }
+
+ .ds-list-item-link {
+ mix-blend-mode: normal;
+
+ display: flex;
+ justify-content: space-between;
+ height: 100%;
+ }
+
+ .ds-list-item-excerpt {
+ @include limit-visible-lines(2, $item-line-height, $item-font-size);
+ @include dark-theme-only {
+ color: $grey-10-80;
+ }
+ color: $grey-50;
+ margin: 4px 0 8px;
+ }
+
+ p {
+ font-size: $item-font-size * 1px;
+ line-height: $item-line-height * 1px;
+ margin: 0;
+ }
+
+ .ds-list-item-info {
+ @include limit-visible-lines(1, $item-line-height, $item-font-size);
+ @include dark-theme-only {
+ color: $grey-40;
+ }
+
+ color: $grey-50;
+ font-size: 13px;
+ }
+
+ .ds-list-item-title {
+ font-weight: 600;
+ margin-bottom: 4px;
+ }
+
+ .ds-list-item-body {
+ flex: 1;
+ }
+
+ .ds-list-item-text {
+ display: flex;
+ flex-direction: column;
+ justify-content: space-between;
+ }
+
+ .ds-list-image {
+ height: $item-image-size;
+ margin-inline-start: $item-font-size * 1px;
+ min-height: $item-image-size;
+
+ img {
+ border-radius: 4px;
+ box-shadow: inset 0 0 0 0.5px $black-15;
+ }
+ }
+
+ &:hover {
+ .ds-list-item-title {
+ color: $blue-40;
+ }
+ }
+
+ &:active {
+ .ds-list-item-title {
+ color: $blue-70;
+ }
+ }
+}
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamComponents/Navigation/Navigation.jsx b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/Navigation/Navigation.jsx
new file mode 100644
index 0000000000..45445bf889
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/Navigation/Navigation.jsx
@@ -0,0 +1,73 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { actionCreators as ac } from "common/Actions.jsm";
+import React from "react";
+import { SafeAnchor } from "../SafeAnchor/SafeAnchor";
+import { FluentOrText } from "content-src/components/FluentOrText/FluentOrText";
+
+export class Topic extends React.PureComponent {
+ constructor(props) {
+ super(props);
+
+ this.onLinkClick = this.onLinkClick.bind(this);
+ }
+
+ onLinkClick(event) {
+ if (this.props.dispatch) {
+ this.props.dispatch(
+ ac.UserEvent({
+ event: "CLICK",
+ source: "POPULAR_TOPICS",
+ action_position: 0,
+ value: {
+ topic: event.target.text.toLowerCase().replace(` `, `-`),
+ },
+ })
+ );
+ }
+ }
+
+ render() {
+ const { url, name } = this.props;
+ return (
+ <SafeAnchor
+ onLinkClick={this.onLinkClick}
+ className={this.props.className}
+ url={url}
+ >
+ {name}
+ </SafeAnchor>
+ );
+ }
+}
+
+export class Navigation extends React.PureComponent {
+ render() {
+ const links = this.props.links || [];
+ const alignment = this.props.alignment || "centered";
+ const header = this.props.header || {};
+ return (
+ <div className={`ds-navigation ds-navigation-${alignment}`}>
+ {header.title ? (
+ <FluentOrText message={header.title}>
+ <span className="ds-navigation-header" />
+ </FluentOrText>
+ ) : null}
+ <ul>
+ {links &&
+ links.map(t => (
+ <li key={t.name}>
+ <Topic
+ url={t.url}
+ name={t.name}
+ dispatch={this.props.dispatch}
+ />
+ </li>
+ ))}
+ </ul>
+ </div>
+ );
+ }
+}
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamComponents/Navigation/_Navigation.scss b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/Navigation/_Navigation.scss
new file mode 100644
index 0000000000..c48b36281b
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/Navigation/_Navigation.scss
@@ -0,0 +1,64 @@
+.outer-wrapper.newtab-experience {
+ .ds-navigation {
+ color: var(--newtab-background-primary-text-color);
+ }
+}
+
+.ds-navigation {
+ @include dark-theme-only {
+ color: $grey-30;
+ }
+
+ color: $grey-50;
+ padding: 4px 0;
+ font-weight: 600;
+ line-height: 22px;
+ font-size: 11.5px;
+
+ @media (min-width: $break-point-widest) {
+ line-height: 32px;
+ font-size: 14px;
+ }
+
+ &.ds-navigation-centered {
+ text-align: center;
+ }
+
+ &.ds-navigation-right-aligned {
+ text-align: end;
+ }
+
+ ul {
+ display: inline;
+ margin: 0;
+ padding: 0;
+ }
+
+ ul li {
+ display: inline-block;
+
+ &::after {
+ content: '·';
+ padding: 6px;
+ }
+
+ &:last-child::after {
+ content: none;
+ }
+
+ a {
+ &:hover,
+ &:active {
+ text-decoration: underline;
+ }
+
+ &:active {
+ color: $blue-70;
+ }
+ }
+ }
+
+ .ds-navigation-header {
+ padding-inline-end: 6px;
+ }
+}
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamComponents/SafeAnchor/SafeAnchor.jsx b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/SafeAnchor/SafeAnchor.jsx
new file mode 100644
index 0000000000..5a65a50bb8
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/SafeAnchor/SafeAnchor.jsx
@@ -0,0 +1,62 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { actionCreators as ac, actionTypes as at } from "common/Actions.jsm";
+import React from "react";
+
+export class SafeAnchor extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onClick = this.onClick.bind(this);
+ }
+
+ onClick(event) {
+ // Use dispatch instead of normal link click behavior to include referrer
+ if (this.props.dispatch) {
+ event.preventDefault();
+ const { altKey, button, ctrlKey, metaKey, shiftKey } = event;
+ this.props.dispatch(
+ ac.OnlyToMain({
+ type: at.OPEN_LINK,
+ data: {
+ event: { altKey, button, ctrlKey, metaKey, shiftKey },
+ referrer: "https://getpocket.com/recommendations",
+ // Use the anchor's url, which could have been cleaned up
+ url: event.currentTarget.href,
+ },
+ })
+ );
+ }
+
+ // Propagate event if there's a handler
+ if (this.props.onLinkClick) {
+ this.props.onLinkClick(event);
+ }
+ }
+
+ safeURI(url) {
+ let protocol = null;
+ try {
+ protocol = new URL(url).protocol;
+ } catch (e) {
+ return "";
+ }
+
+ const isAllowed = ["http:", "https:"].includes(protocol);
+ if (!isAllowed) {
+ console.warn(`${url} is not allowed for anchor targets.`); // eslint-disable-line no-console
+ return "";
+ }
+ return url;
+ }
+
+ render() {
+ const { url, className } = this.props;
+ return (
+ <a href={this.safeURI(url)} className={className} onClick={this.onClick}>
+ {this.props.children}
+ </a>
+ );
+ }
+}
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamComponents/SectionTitle/SectionTitle.jsx b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/SectionTitle/SectionTitle.jsx
new file mode 100644
index 0000000000..646dc2263e
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/SectionTitle/SectionTitle.jsx
@@ -0,0 +1,19 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import React from "react";
+
+export class SectionTitle extends React.PureComponent {
+ render() {
+ const {
+ header: { title, subtitle },
+ } = this.props;
+ return (
+ <div className="ds-section-title">
+ <div className="title">{title}</div>
+ {subtitle ? <div className="subtitle">{subtitle}</div> : null}
+ </div>
+ );
+ }
+}
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamComponents/SectionTitle/_SectionTitle.scss b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/SectionTitle/_SectionTitle.scss
new file mode 100644
index 0000000000..317bb29466
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/SectionTitle/_SectionTitle.scss
@@ -0,0 +1,26 @@
+.ds-section-title {
+ text-align: center;
+ margin-top: 24px;
+
+ .title {
+ @include dark-theme-only {
+ color: $white;
+ }
+
+ line-height: 48px;
+ font-size: 36px;
+ font-weight: 300;
+ color: $grey-90;
+ }
+
+ .subtitle {
+ @include dark-theme-only {
+ color: $grey-30;
+ }
+
+ line-height: 24px;
+ font-size: 14px;
+ color: $grey-50;
+ margin-top: 4px;
+ }
+}
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamComponents/TopSites/TopSites.jsx b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/TopSites/TopSites.jsx
new file mode 100644
index 0000000000..bcc388698f
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/TopSites/TopSites.jsx
@@ -0,0 +1,157 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { connect } from "react-redux";
+import { TopSites as OldTopSites } from "content-src/components/TopSites/TopSites";
+import { TOP_SITES_MAX_SITES_PER_ROW } from "common/Reducers.jsm";
+import React from "react";
+
+export class _TopSites extends React.PureComponent {
+ // Find a SPOC that doesn't already exist in User's TopSites
+ getFirstAvailableSpoc(topSites, data) {
+ const { spocs } = data;
+ if (!spocs || spocs.length === 0) {
+ return null;
+ }
+
+ const userTopSites = new Set(
+ topSites.map(topSite => topSite && topSite.url)
+ );
+
+ // We "clean urls" with http in TopSiteForm.jsx
+ // Spoc domains are in the format 'sponsorname.com'
+ return spocs.find(
+ spoc =>
+ !userTopSites.has(spoc.url) &&
+ !userTopSites.has(`http://${spoc.domain}`) &&
+ !userTopSites.has(`https://${spoc.domain}`) &&
+ !userTopSites.has(`http://www.${spoc.domain}`) &&
+ !userTopSites.has(`https://www.${spoc.domain}`)
+ );
+ }
+
+ // Find the first empty or unpinned index we can place the SPOC in.
+ // Return -1 if no available index and we should push it at the end.
+ getFirstAvailableIndex(topSites, promoAlignment) {
+ if (promoAlignment === "left") {
+ return topSites.findIndex(topSite => !topSite || !topSite.isPinned);
+ }
+
+ // The row isn't full so we can push it to the end of the row.
+ if (topSites.length < TOP_SITES_MAX_SITES_PER_ROW) {
+ return -1;
+ }
+
+ // If the row is full, we can check the row first for unpinned topsites to replace.
+ // Else we can check after the row. This behavior is how unpinned topsites move while drag and drop.
+ let endOfRow = TOP_SITES_MAX_SITES_PER_ROW - 1;
+ for (let i = endOfRow; i >= 0; i--) {
+ if (!topSites[i] || !topSites[i].isPinned) {
+ return i;
+ }
+ }
+
+ for (let i = endOfRow + 1; i < topSites.length; i++) {
+ if (!topSites[i] || !topSites[i].isPinned) {
+ return i;
+ }
+ }
+
+ return -1;
+ }
+
+ insertSpocContent(TopSites, data, promoAlignment) {
+ if (
+ !TopSites.rows ||
+ TopSites.rows.length === 0 ||
+ !data.spocs ||
+ data.spocs.length === 0
+ ) {
+ return null;
+ }
+
+ let topSites = [...TopSites.rows];
+ const topSiteSpoc = this.getFirstAvailableSpoc(topSites, data);
+
+ if (!topSiteSpoc) {
+ return null;
+ }
+
+ const link = {
+ customScreenshotURL: topSiteSpoc.image_src,
+ type: "SPOC",
+ label: topSiteSpoc.sponsor,
+ title: topSiteSpoc.sponsor,
+ url: topSiteSpoc.url,
+ flightId: topSiteSpoc.flight_id,
+ id: topSiteSpoc.id,
+ guid: topSiteSpoc.id,
+ shim: topSiteSpoc.shim,
+ // For now we are assuming position based on intended position.
+ // Actual position can shift based on other content.
+ // We also hard code left and right to be 0 and 7.
+ // We send the intended postion in the ping.
+ pos: promoAlignment === "left" ? 0 : 7,
+ };
+
+ const firstAvailableIndex = this.getFirstAvailableIndex(
+ topSites,
+ promoAlignment
+ );
+
+ if (firstAvailableIndex === -1) {
+ topSites.push(link);
+ } else {
+ // Normal insertion will not work since pinned topsites are in their correct index already
+ // Similar logic is done to handle drag and drop with pinned topsites in TopSite.jsx
+
+ let shiftedTopSite = topSites[firstAvailableIndex];
+ let index = firstAvailableIndex + 1;
+
+ // Shift unpinned topsites to the right by finding the next unpinned topsite to replace
+ while (shiftedTopSite) {
+ if (index === topSites.length) {
+ topSites.push(shiftedTopSite);
+ shiftedTopSite = null;
+ } else if (topSites[index] && topSites[index].isPinned) {
+ index += 1;
+ } else {
+ const nextTopSite = topSites[index];
+ topSites[index] = shiftedTopSite;
+ shiftedTopSite = nextTopSite;
+ index += 1;
+ }
+ }
+
+ topSites[firstAvailableIndex] = link;
+ }
+
+ return { ...TopSites, rows: topSites };
+ }
+
+ render() {
+ const { header = {}, data, promoAlignment, TopSites } = this.props;
+
+ const TopSitesWithSpoc =
+ TopSites && data && promoAlignment
+ ? this.insertSpocContent(TopSites, data, promoAlignment)
+ : null;
+
+ return (
+ <div
+ className={`ds-top-sites ${TopSitesWithSpoc ? "top-sites-spoc" : ""}`}
+ >
+ <OldTopSites
+ isFixed={true}
+ title={header.title}
+ TopSitesWithSpoc={TopSitesWithSpoc}
+ />
+ </div>
+ );
+ }
+}
+
+export const TopSites = connect(state => ({ TopSites: state.TopSites }))(
+ _TopSites
+);
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamComponents/TopSites/_TopSites.scss b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/TopSites/_TopSites.scss
new file mode 100644
index 0000000000..b40ce5bb7b
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamComponents/TopSites/_TopSites.scss
@@ -0,0 +1,119 @@
+// ds topsites wraps the original topsites, with a few css changes.
+.outer-wrapper:not(.newtab-experience) {
+ .ds-top-sites {
+ // This is the override layer.
+ .top-sites {
+ .top-site-outer {
+ padding: 0 12px;
+
+ .top-site-inner > a:is(.active, :focus) .tile {
+ @include ds-fade-in;
+
+ @include dark-theme-only {
+ @include ds-fade-in($blue-40-40);
+ }
+ }
+
+ .top-site-inner > a:is(:hover) .tile {
+
+ @include ds-fade-in($grey-30);
+
+ @include dark-theme-only {
+ @include ds-fade-in($grey-60);
+ }
+ }
+ }
+
+ .top-sites-list {
+ margin: 0 -12px;
+ }
+ }
+ }
+}
+
+.outer-wrapper.newtab-experience {
+ .ds-top-sites {
+ // This is the override layer.
+ .top-sites {
+ .top-site-outer {
+ .top-site-inner > a:is(.active, :focus) .tile {
+ @include ds-focus-nte;
+ }
+
+ .top-site-inner > a:is(:hover) .top-site-inner {
+
+ @include ds-fade-in($grey-30);
+
+ @include dark-theme-only {
+ @include ds-fade-in($grey-60);
+ }
+ }
+ }
+
+ .top-sites-list {
+ margin: 0 -12px;
+ }
+ }
+ }
+}
+
+// Size overrides for topsites in the 2/3 view.
+.ds-column-5,
+.ds-column-6,
+.ds-column-7,
+.ds-column-8 {
+ .ds-top-sites {
+
+ .top-site-outer {
+ padding: 0 10px;
+ }
+
+ .top-sites-list {
+ margin: 0 -10px;
+ }
+
+ .top-site-inner {
+ --leftPanelIconWidth: 84.67px;
+
+ .tile {
+ width: var(--leftPanelIconWidth);
+ height: var(--leftPanelIconWidth);
+ }
+
+ .title {
+ width: var(--leftPanelIconWidth);
+ }
+ }
+ }
+}
+
+// Size overrides for topsites in the 1/3 view.
+.ds-column-1,
+.ds-column-2,
+.ds-column-3,
+.ds-column-4 {
+ .ds-top-sites {
+
+ .top-site-outer {
+ padding: 0 8px;
+ }
+
+ .top-sites-list {
+ margin: 0 -8px;
+ }
+
+ .top-site-inner {
+ --rightPanelIconWidth: 82.67px;
+
+ .tile {
+ width: var(--rightPanelIconWidth);
+ height: var(--rightPanelIconWidth);
+ }
+
+ .title {
+ width: var(--rightPanelIconWidth);
+ }
+ }
+ }
+}
+
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamImpressionStats/ImpressionStats.jsx b/browser/components/newtab/content-src/components/DiscoveryStreamImpressionStats/ImpressionStats.jsx
new file mode 100644
index 0000000000..cc0082bdfe
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamImpressionStats/ImpressionStats.jsx
@@ -0,0 +1,223 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { actionCreators as ac, actionTypes as at } from "common/Actions.jsm";
+import React from "react";
+
+const VISIBLE = "visible";
+const VISIBILITY_CHANGE_EVENT = "visibilitychange";
+
+// Per analytical requirement, we set the minimal intersection ratio to
+// 0.5, and an impression is identified when the wrapped item has at least
+// 50% visibility.
+//
+// This constant is exported for unit test
+export const INTERSECTION_RATIO = 0.5;
+
+/**
+ * Impression wrapper for Discovery Stream related React components.
+ *
+ * It makses use of the Intersection Observer API to detect the visibility,
+ * and relies on page visibility to ensure the impression is reported
+ * only when the component is visible on the page.
+ *
+ * Note:
+ * * This wrapper used to be used either at the individual card level,
+ * or by the card container components.
+ * It is now only used for individual card level.
+ * * Each impression will be sent only once as soon as the desired
+ * visibility is detected
+ * * Batching is not yet implemented, hence it might send multiple
+ * impression pings separately
+ */
+export class ImpressionStats extends React.PureComponent {
+ // This checks if the given cards are the same as those in the last impression ping.
+ // If so, it should not send the same impression ping again.
+ _needsImpressionStats(cards) {
+ if (
+ !this.impressionCardGuids ||
+ this.impressionCardGuids.length !== cards.length
+ ) {
+ return true;
+ }
+
+ for (let i = 0; i < cards.length; i++) {
+ if (cards[i].id !== this.impressionCardGuids[i]) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ _dispatchImpressionStats() {
+ const { props } = this;
+ const cards = props.rows;
+
+ if (this.props.flightId) {
+ this.props.dispatch(
+ ac.OnlyToMain({
+ type: at.DISCOVERY_STREAM_SPOC_IMPRESSION,
+ data: { flightId: this.props.flightId },
+ })
+ );
+ }
+
+ if (this._needsImpressionStats(cards)) {
+ props.dispatch(
+ ac.DiscoveryStreamImpressionStats({
+ source: props.source.toUpperCase(),
+ tiles: cards.map(link => ({
+ id: link.id,
+ pos: link.pos,
+ ...(link.shim ? { shim: link.shim } : {}),
+ })),
+ })
+ );
+ this.impressionCardGuids = cards.map(link => link.id);
+ }
+ }
+
+ // This checks if the given cards are the same as those in the last loaded content ping.
+ // If so, it should not send the same loaded content ping again.
+ _needsLoadedContent(cards) {
+ if (
+ !this.loadedContentGuids ||
+ this.loadedContentGuids.length !== cards.length
+ ) {
+ return true;
+ }
+
+ for (let i = 0; i < cards.length; i++) {
+ if (cards[i].id !== this.loadedContentGuids[i]) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ _dispatchLoadedContent() {
+ const { props } = this;
+ const cards = props.rows;
+
+ if (this._needsLoadedContent(cards)) {
+ props.dispatch(
+ ac.DiscoveryStreamLoadedContent({
+ source: props.source.toUpperCase(),
+ tiles: cards.map(link => ({ id: link.id, pos: link.pos })),
+ })
+ );
+ this.loadedContentGuids = cards.map(link => link.id);
+ }
+ }
+
+ setImpressionObserverOrAddListener() {
+ const { props } = this;
+
+ if (!props.dispatch) {
+ return;
+ }
+
+ if (props.document.visibilityState === VISIBLE) {
+ // Send the loaded content ping once the page is visible.
+ this._dispatchLoadedContent();
+ this.setImpressionObserver();
+ } else {
+ // We should only ever send the latest impression stats ping, so remove any
+ // older listeners.
+ if (this._onVisibilityChange) {
+ props.document.removeEventListener(
+ VISIBILITY_CHANGE_EVENT,
+ this._onVisibilityChange
+ );
+ }
+
+ this._onVisibilityChange = () => {
+ if (props.document.visibilityState === VISIBLE) {
+ // Send the loaded content ping once the page is visible.
+ this._dispatchLoadedContent();
+ this.setImpressionObserver();
+ props.document.removeEventListener(
+ VISIBILITY_CHANGE_EVENT,
+ this._onVisibilityChange
+ );
+ }
+ };
+ props.document.addEventListener(
+ VISIBILITY_CHANGE_EVENT,
+ this._onVisibilityChange
+ );
+ }
+ }
+
+ /**
+ * Set an impression observer for the wrapped component. It makes use of
+ * the Intersection Observer API to detect if the wrapped component is
+ * visible with a desired ratio, and only sends impression if that's the case.
+ *
+ * See more details about Intersection Observer API at:
+ * https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
+ */
+ setImpressionObserver() {
+ const { props } = this;
+
+ if (!props.rows.length) {
+ return;
+ }
+
+ this._handleIntersect = entries => {
+ if (
+ entries.some(
+ entry =>
+ entry.isIntersecting &&
+ entry.intersectionRatio >= INTERSECTION_RATIO
+ )
+ ) {
+ this._dispatchImpressionStats();
+ this.impressionObserver.unobserve(this.refs.impression);
+ }
+ };
+
+ const options = { threshold: INTERSECTION_RATIO };
+ this.impressionObserver = new props.IntersectionObserver(
+ this._handleIntersect,
+ options
+ );
+ this.impressionObserver.observe(this.refs.impression);
+ }
+
+ componentDidMount() {
+ if (this.props.rows.length) {
+ this.setImpressionObserverOrAddListener();
+ }
+ }
+
+ componentWillUnmount() {
+ if (this._handleIntersect && this.impressionObserver) {
+ this.impressionObserver.unobserve(this.refs.impression);
+ }
+ if (this._onVisibilityChange) {
+ this.props.document.removeEventListener(
+ VISIBILITY_CHANGE_EVENT,
+ this._onVisibilityChange
+ );
+ }
+ }
+
+ render() {
+ return (
+ <div ref={"impression"} className="impression-observer">
+ {this.props.children}
+ </div>
+ );
+ }
+}
+
+ImpressionStats.defaultProps = {
+ IntersectionObserver: global.IntersectionObserver,
+ document: global.document,
+ rows: [],
+ source: "",
+};
diff --git a/browser/components/newtab/content-src/components/DiscoveryStreamImpressionStats/_ImpressionStats.scss b/browser/components/newtab/content-src/components/DiscoveryStreamImpressionStats/_ImpressionStats.scss
new file mode 100644
index 0000000000..943e4e34a9
--- /dev/null
+++ b/browser/components/newtab/content-src/components/DiscoveryStreamImpressionStats/_ImpressionStats.scss
@@ -0,0 +1,7 @@
+.impression-observer {
+ position: absolute;
+ top: 0;
+ width: 100%;
+ height: 100%;
+ pointer-events: none;
+}
diff --git a/browser/components/newtab/content-src/components/ErrorBoundary/ErrorBoundary.jsx b/browser/components/newtab/content-src/components/ErrorBoundary/ErrorBoundary.jsx
new file mode 100644
index 0000000000..1834a0a521
--- /dev/null
+++ b/browser/components/newtab/content-src/components/ErrorBoundary/ErrorBoundary.jsx
@@ -0,0 +1,68 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { A11yLinkButton } from "content-src/components/A11yLinkButton/A11yLinkButton";
+import React from "react";
+
+export class ErrorBoundaryFallback extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.windowObj = this.props.windowObj || window;
+ this.onClick = this.onClick.bind(this);
+ }
+
+ /**
+ * Since we only get here if part of the page has crashed, do a
+ * forced reload to give us the best chance at recovering.
+ */
+ onClick() {
+ this.windowObj.location.reload(true);
+ }
+
+ render() {
+ const defaultClass = "as-error-fallback";
+ let className;
+ if ("className" in this.props) {
+ className = `${this.props.className} ${defaultClass}`;
+ } else {
+ className = defaultClass;
+ }
+
+ // "A11yLinkButton" to force normal link styling stuff (eg cursor on hover)
+ return (
+ <div className={className}>
+ <div data-l10n-id="newtab-error-fallback-info" />
+ <span>
+ <A11yLinkButton
+ className="reload-button"
+ onClick={this.onClick}
+ data-l10n-id="newtab-error-fallback-refresh-link"
+ />
+ </span>
+ </div>
+ );
+ }
+}
+ErrorBoundaryFallback.defaultProps = { className: "as-error-fallback" };
+
+export class ErrorBoundary extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.state = { hasError: false };
+ }
+
+ componentDidCatch(error, info) {
+ this.setState({ hasError: true });
+ }
+
+ render() {
+ if (!this.state.hasError) {
+ return this.props.children;
+ }
+
+ return <this.props.FallbackComponent className={this.props.className} />;
+ }
+}
+
+ErrorBoundary.defaultProps = { FallbackComponent: ErrorBoundaryFallback };
diff --git a/browser/components/newtab/content-src/components/ErrorBoundary/_ErrorBoundary.scss b/browser/components/newtab/content-src/components/ErrorBoundary/_ErrorBoundary.scss
new file mode 100644
index 0000000000..8607be7de4
--- /dev/null
+++ b/browser/components/newtab/content-src/components/ErrorBoundary/_ErrorBoundary.scss
@@ -0,0 +1,21 @@
+.as-error-fallback {
+ align-items: center;
+ border-radius: $border-radius;
+ box-shadow: inset $inner-box-shadow;
+ color: var(--newtab-text-conditional-color);
+ display: flex;
+ flex-direction: column;
+ font-size: $error-fallback-font-size;
+ justify-content: center;
+ justify-items: center;
+ line-height: $error-fallback-line-height;
+
+ &.borderless-error {
+ box-shadow: none;
+ }
+
+ a {
+ color: var(--newtab-text-conditional-color);
+ text-decoration: underline;
+ }
+}
diff --git a/browser/components/newtab/content-src/components/FluentOrText/FluentOrText.jsx b/browser/components/newtab/content-src/components/FluentOrText/FluentOrText.jsx
new file mode 100644
index 0000000000..583a5e4a01
--- /dev/null
+++ b/browser/components/newtab/content-src/components/FluentOrText/FluentOrText.jsx
@@ -0,0 +1,36 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import React from "react";
+
+/**
+ * Set text on a child element/component depending on if the message is already
+ * translated plain text or a fluent id with optional args.
+ */
+export class FluentOrText extends React.PureComponent {
+ render() {
+ // Ensure we have a single child to attach attributes
+ const { children, message } = this.props;
+ const child = children ? React.Children.only(children) : <span />;
+
+ // For a string message, just use it as the child's text
+ let grandChildren = message;
+ let extraProps;
+
+ // Convert a message object to set desired fluent-dom attributes
+ if (typeof message === "object") {
+ const args = message.args || message.values;
+ extraProps = {
+ "data-l10n-args": args && JSON.stringify(args),
+ "data-l10n-id": message.id || message.string_id,
+ };
+
+ // Use original children potentially with data-l10n-name attributes
+ grandChildren = child.props.children;
+ }
+
+ // Add the message to the child via fluent attributes or text node
+ return React.cloneElement(child, extraProps, grandChildren);
+ }
+}
diff --git a/browser/components/newtab/content-src/components/LinkMenu/LinkMenu.jsx b/browser/components/newtab/content-src/components/LinkMenu/LinkMenu.jsx
new file mode 100644
index 0000000000..f8ba0786e9
--- /dev/null
+++ b/browser/components/newtab/content-src/components/LinkMenu/LinkMenu.jsx
@@ -0,0 +1,108 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { actionCreators as ac } from "common/Actions.jsm";
+import { connect } from "react-redux";
+import { ContextMenu } from "content-src/components/ContextMenu/ContextMenu";
+import { LinkMenuOptions } from "content-src/lib/link-menu-options";
+import React from "react";
+
+const DEFAULT_SITE_MENU_OPTIONS = [
+ "CheckPinTopSite",
+ "EditTopSite",
+ "Separator",
+ "OpenInNewWindow",
+ "OpenInPrivateWindow",
+ "Separator",
+ "BlockUrl",
+];
+
+export class _LinkMenu extends React.PureComponent {
+ getOptions() {
+ const { props } = this;
+ const {
+ site,
+ index,
+ source,
+ isPrivateBrowsingEnabled,
+ siteInfo,
+ platform,
+ } = props;
+
+ // Handle special case of default site
+ const propOptions =
+ site.isDefault && !site.searchTopSite && !site.sponsored_position
+ ? DEFAULT_SITE_MENU_OPTIONS
+ : props.options;
+
+ const options = propOptions
+ .map(o =>
+ LinkMenuOptions[o](
+ site,
+ index,
+ source,
+ isPrivateBrowsingEnabled,
+ siteInfo,
+ platform
+ )
+ )
+ .map(option => {
+ const { action, impression, id, type, userEvent } = option;
+ if (!type && id) {
+ option.onClick = (event = {}) => {
+ const { ctrlKey, metaKey, shiftKey, button } = event;
+ // Only send along event info if there's something non-default to send
+ if (ctrlKey || metaKey || shiftKey || button === 1) {
+ action.data = Object.assign(
+ {
+ event: { ctrlKey, metaKey, shiftKey, button },
+ },
+ action.data
+ );
+ }
+ props.dispatch(action);
+ if (userEvent) {
+ const userEventData = Object.assign(
+ {
+ event: userEvent,
+ source,
+ action_position: index,
+ },
+ siteInfo
+ );
+ props.dispatch(ac.UserEvent(userEventData));
+ }
+ if (impression && props.shouldSendImpressionStats) {
+ props.dispatch(impression);
+ }
+ };
+ }
+ return option;
+ });
+
+ // This is for accessibility to support making each item tabbable.
+ // We want to know which item is the first and which item
+ // is the last, so we can close the context menu accordingly.
+ options[0].first = true;
+ options[options.length - 1].last = true;
+ return options;
+ }
+
+ render() {
+ return (
+ <ContextMenu
+ onUpdate={this.props.onUpdate}
+ onShow={this.props.onShow}
+ options={this.getOptions()}
+ keyboardAccess={this.props.keyboardAccess}
+ />
+ );
+ }
+}
+
+const getState = state => ({
+ isPrivateBrowsingEnabled: state.Prefs.values.isPrivateBrowsingEnabled,
+ platform: state.Prefs.values.platform,
+});
+export const LinkMenu = connect(getState)(_LinkMenu);
diff --git a/browser/components/newtab/content-src/components/MoreRecommendations/MoreRecommendations.jsx b/browser/components/newtab/content-src/components/MoreRecommendations/MoreRecommendations.jsx
new file mode 100644
index 0000000000..f2c332e5bd
--- /dev/null
+++ b/browser/components/newtab/content-src/components/MoreRecommendations/MoreRecommendations.jsx
@@ -0,0 +1,21 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import React from "react";
+
+export class MoreRecommendations extends React.PureComponent {
+ render() {
+ const { read_more_endpoint } = this.props;
+ if (read_more_endpoint) {
+ return (
+ <a
+ className="more-recommendations"
+ href={read_more_endpoint}
+ data-l10n-id="newtab-pocket-more-recommendations"
+ />
+ );
+ }
+ return null;
+ }
+}
diff --git a/browser/components/newtab/content-src/components/MoreRecommendations/_MoreRecommendations.scss b/browser/components/newtab/content-src/components/MoreRecommendations/_MoreRecommendations.scss
new file mode 100644
index 0000000000..bfc441afee
--- /dev/null
+++ b/browser/components/newtab/content-src/components/MoreRecommendations/_MoreRecommendations.scss
@@ -0,0 +1,22 @@
+.more-recommendations {
+ display: flex;
+ align-items: center;
+ white-space: nowrap;
+ line-height: 1.230769231; // (16 / 13) -> 16px computed
+
+ &::after {
+ background: url('#{$image-path}topic-show-more-12.svg') no-repeat center center;
+ content: '';
+ -moz-context-properties: fill;
+ display: inline-block;
+ fill: var(--newtab-link-secondary-color);
+ height: 16px;
+ margin-inline-start: 5px;
+ vertical-align: top;
+ width: 12px;
+ }
+
+ &:dir(rtl)::after {
+ transform: scaleX(-1);
+ }
+}
diff --git a/browser/components/newtab/content-src/components/PocketLoggedInCta/PocketLoggedInCta.jsx b/browser/components/newtab/content-src/components/PocketLoggedInCta/PocketLoggedInCta.jsx
new file mode 100644
index 0000000000..53c22f319c
--- /dev/null
+++ b/browser/components/newtab/content-src/components/PocketLoggedInCta/PocketLoggedInCta.jsx
@@ -0,0 +1,42 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { connect } from "react-redux";
+import React from "react";
+
+export class _PocketLoggedInCta extends React.PureComponent {
+ render() {
+ const { pocketCta } = this.props.Pocket;
+ return (
+ <span className="pocket-logged-in-cta">
+ <a
+ className="pocket-cta-button"
+ href={pocketCta.ctaUrl ? pocketCta.ctaUrl : "https://getpocket.com/"}
+ >
+ {pocketCta.ctaButton ? (
+ pocketCta.ctaButton
+ ) : (
+ <span data-l10n-id="newtab-pocket-cta-button" />
+ )}
+ </a>
+
+ <a
+ href={pocketCta.ctaUrl ? pocketCta.ctaUrl : "https://getpocket.com/"}
+ >
+ <span className="cta-text">
+ {pocketCta.ctaText ? (
+ pocketCta.ctaText
+ ) : (
+ <span data-l10n-id="newtab-pocket-cta-text" />
+ )}
+ </span>
+ </a>
+ </span>
+ );
+ }
+}
+
+export const PocketLoggedInCta = connect(state => ({ Pocket: state.Pocket }))(
+ _PocketLoggedInCta
+);
diff --git a/browser/components/newtab/content-src/components/PocketLoggedInCta/_PocketLoggedInCta.scss b/browser/components/newtab/content-src/components/PocketLoggedInCta/_PocketLoggedInCta.scss
new file mode 100644
index 0000000000..3a55da9112
--- /dev/null
+++ b/browser/components/newtab/content-src/components/PocketLoggedInCta/_PocketLoggedInCta.scss
@@ -0,0 +1,39 @@
+.pocket-logged-in-cta {
+ $max-button-width: 130px;
+ $min-button-height: 18px;
+ font-size: 13px;
+ margin-inline-end: 20px;
+ display: flex;
+ align-items: flex-start;
+
+ .pocket-cta-button {
+ white-space: nowrap;
+ background: $blue-60;
+ letter-spacing: -0.34px;
+ color: $white;
+ border-radius: 4px;
+ cursor: pointer;
+ max-width: $max-button-width;
+ // The button height is 2px taller than the rest of the cta text.
+ // So I move it up by 1px to align with the rest of the cta text.
+ margin-top: -1px;
+ min-height: $min-button-height;
+ padding: 0 8px;
+ display: inline-flex;
+ justify-content: center;
+ align-items: center;
+ font-size: 11px;
+ margin-inline-end: 10px;
+ }
+
+ .cta-text {
+ font-weight: normal;
+ font-size: 13px;
+ line-height: 1.230769231; // (16 / 13) –> 16px computed
+ }
+
+ .pocket-cta-button,
+ .cta-text {
+ vertical-align: top;
+ }
+}
diff --git a/browser/components/newtab/content-src/components/Search/Search.jsx b/browser/components/newtab/content-src/components/Search/Search.jsx
new file mode 100644
index 0000000000..62a0dcb787
--- /dev/null
+++ b/browser/components/newtab/content-src/components/Search/Search.jsx
@@ -0,0 +1,208 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* globals ContentSearchUIController, ContentSearchHandoffUIController */
+"use strict";
+
+import { actionCreators as ac, actionTypes as at } from "common/Actions.jsm";
+import { connect } from "react-redux";
+import { IS_NEWTAB } from "content-src/lib/constants";
+import React from "react";
+
+export class _Search extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onSearchClick = this.onSearchClick.bind(this);
+ this.onSearchHandoffClick = this.onSearchHandoffClick.bind(this);
+ this.onSearchHandoffPaste = this.onSearchHandoffPaste.bind(this);
+ this.onSearchHandoffDrop = this.onSearchHandoffDrop.bind(this);
+ this.onInputMount = this.onInputMount.bind(this);
+ this.onInputMountHandoff = this.onInputMountHandoff.bind(this);
+ this.onSearchHandoffButtonMount = this.onSearchHandoffButtonMount.bind(
+ this
+ );
+ }
+
+ handleEvent(event) {
+ // Also track search events with our own telemetry
+ if (event.detail.type === "Search") {
+ this.props.dispatch(ac.UserEvent({ event: "SEARCH" }));
+ }
+ }
+
+ onSearchClick(event) {
+ window.gContentSearchController.search(event);
+ }
+
+ doSearchHandoff(text) {
+ this.props.dispatch(
+ ac.OnlyToMain({ type: at.HANDOFF_SEARCH_TO_AWESOMEBAR, data: { text } })
+ );
+ this.props.dispatch({ type: at.FAKE_FOCUS_SEARCH });
+ this.props.dispatch(ac.UserEvent({ event: "SEARCH_HANDOFF" }));
+ if (text) {
+ this.props.dispatch({ type: at.HIDE_SEARCH });
+ }
+ }
+
+ onSearchHandoffClick(event) {
+ // When search hand-off is enabled, we render a big button that is styled to
+ // look like a search textbox. If the button is clicked, we style
+ // the button as if it was a focused search box and show a fake cursor but
+ // really focus the awesomebar without the focus styles ("hidden focus").
+ event.preventDefault();
+ this.doSearchHandoff();
+ }
+
+ onSearchHandoffPaste(event) {
+ event.preventDefault();
+ this.doSearchHandoff(event.clipboardData.getData("Text"));
+ }
+
+ onSearchHandoffDrop(event) {
+ event.preventDefault();
+ let text = event.dataTransfer.getData("text");
+ if (text) {
+ this.doSearchHandoff(text);
+ }
+ }
+
+ componentWillUnmount() {
+ delete window.gContentSearchController;
+ }
+
+ onInputMount(input) {
+ if (input) {
+ // The "healthReportKey" and needs to be "newtab" or "abouthome" so that
+ // BrowserUsageTelemetry.jsm knows to handle events with this name, and
+ // can add the appropriate telemetry probes for search. Without the correct
+ // name, certain tests like browser_UsageTelemetry_content.js will fail
+ // (See github ticket #2348 for more details)
+ const healthReportKey = IS_NEWTAB ? "newtab" : "abouthome";
+
+ // The "searchSource" needs to be "newtab" or "homepage" and is sent with
+ // the search data and acts as context for the search request (See
+ // nsISearchEngine.getSubmission). It is necessary so that search engine
+ // plugins can correctly atribute referrals. (See github ticket #3321 for
+ // more details)
+ const searchSource = IS_NEWTAB ? "newtab" : "homepage";
+
+ // gContentSearchController needs to exist as a global so that tests for
+ // the existing about:home can find it; and so it allows these tests to pass.
+ // In the future, when activity stream is default about:home, this can be renamed
+ window.gContentSearchController = new ContentSearchUIController(
+ input,
+ input.parentNode,
+ healthReportKey,
+ searchSource
+ );
+ addEventListener("ContentSearchClient", this);
+ } else {
+ window.gContentSearchController = null;
+ removeEventListener("ContentSearchClient", this);
+ }
+ }
+
+ onInputMountHandoff(input) {
+ if (input) {
+ // The handoff UI controller helps usset the search icon and reacts to
+ // changes to default engine to keep everything in sync.
+ this._handoffSearchController = new ContentSearchHandoffUIController();
+ }
+ }
+
+ onSearchHandoffButtonMount(button) {
+ // Keep a reference to the button for use during "paste" event handling.
+ this._searchHandoffButton = button;
+ }
+
+ /*
+ * Do not change the ID on the input field, as legacy newtab code
+ * specifically looks for the id 'newtab-search-text' on input fields
+ * in order to execute searches in various tests
+ */
+ render() {
+ const wrapperClassName = [
+ "search-wrapper",
+ this.props.hide && "search-hidden",
+ this.props.fakeFocus && "fake-focus",
+ ]
+ .filter(v => v)
+ .join(" ");
+
+ const isNewNewtabExperienceEnabled = this.props.Prefs.values[
+ "newNewtabExperience.enabled"
+ ];
+
+ return (
+ <div className={wrapperClassName}>
+ {this.props.showLogo && (
+ <div className="logo-and-wordmark">
+ <div className="logo" />
+ <div className="wordmark" />
+ </div>
+ )}
+ {!this.props.handoffEnabled && (
+ <div className="search-inner-wrapper">
+ <input
+ id="newtab-search-text"
+ data-l10n-id={
+ isNewNewtabExperienceEnabled
+ ? "newtab-search-box-input"
+ : "newtab-search-box-search-the-web-input"
+ }
+ maxLength="256"
+ ref={this.onInputMount}
+ type="search"
+ />
+ <button
+ id="searchSubmit"
+ className="search-button"
+ data-l10n-id="newtab-search-box-search-button"
+ onClick={this.onSearchClick}
+ />
+ </div>
+ )}
+ {this.props.handoffEnabled && (
+ <div className="search-inner-wrapper">
+ <button
+ className="search-handoff-button"
+ data-l10n-id={
+ isNewNewtabExperienceEnabled
+ ? "newtab-search-box-input"
+ : "newtab-search-box-search-the-web-input"
+ }
+ ref={this.onSearchHandoffButtonMount}
+ onClick={this.onSearchHandoffClick}
+ tabIndex="-1"
+ >
+ <div
+ className="fake-textbox"
+ data-l10n-id={
+ isNewNewtabExperienceEnabled
+ ? "newtab-search-box-text"
+ : "newtab-search-box-search-the-web-text"
+ }
+ />
+ <input
+ type="search"
+ className="fake-editable"
+ tabIndex="-1"
+ aria-hidden="true"
+ onDrop={this.onSearchHandoffDrop}
+ onPaste={this.onSearchHandoffPaste}
+ ref={this.onInputMountHandoff}
+ />
+ <div className="fake-caret" />
+ </button>
+ </div>
+ )}
+ </div>
+ );
+ }
+}
+
+export const Search = connect(state => ({
+ Prefs: state.Prefs,
+}))(_Search);
diff --git a/browser/components/newtab/content-src/components/Search/_Search.scss b/browser/components/newtab/content-src/components/Search/_Search.scss
new file mode 100644
index 0000000000..87bfdb0427
--- /dev/null
+++ b/browser/components/newtab/content-src/components/Search/_Search.scss
@@ -0,0 +1,516 @@
+$search-height: 48px;
+$search-height-new: 52px;
+$search-icon-size: 24px;
+$search-icon-padding: 12px;
+$search-icon-width: 2 * $search-icon-padding + $search-icon-size -2;
+$search-button-width: 48px;
+$glyph-forward: url('chrome://browser/skin/forward.svg');
+
+.outer-wrapper.newtab-experience {
+ $search-icon-padding: 16px;
+ $search-icon-width: 2 * $search-icon-padding + $search-icon-size -4;
+
+ &.visible-logo {
+ .logo-and-wordmark {
+ .wordmark {
+ fill: var(--newtab-wordmark-color);
+ }
+ }
+ }
+
+ .search-wrapper {
+ padding-bottom: 38px;
+
+ .search-inner-wrapper {
+ min-height: $search-height-new;
+ width: $searchbar-width-small-new;
+
+ @media (min-width: $break-point-medium) {
+ width: $searchbar-width-medium-new;
+ }
+
+ @media (min-width: $break-point-large) {
+ width: $searchbar-width-large-new;
+ }
+
+ @media (min-width: $break-point-widest) {
+ width: $searchbar-width-largest-new;
+ }
+ }
+
+ .search-button {
+ &:focus {
+ outline: 0;
+ box-shadow: 0 0 0 2px var(--newtab-focus-outline);
+ border: 1px solid var(--newtab-focus-border);
+ border-radius: 0 $border-radius-new $border-radius-new 0;
+ }
+ }
+
+ input:focus {
+ outline: 0;
+ border: 1px solid var(--newtab-focus-border);
+ box-shadow: 0 0 0 2px var(--newtab-focus-outline);
+ }
+
+ &.fake-focus {
+ .search-handoff-button {
+ border: 1px solid var(--newtab-focus-border);
+ box-shadow: 0 0 0 2px var(--newtab-focus-outline);
+ }
+ }
+
+ .search-handoff-button,
+ input {
+ background: var(--newtab-textbox-background-color) var(--newtab-search-icon) $search-icon-padding center no-repeat;
+ background-size: $search-icon-size;
+ padding-inline-start: $search-icon-width;
+ padding-inline-end: 10px;
+ box-shadow: 0 3px 8px var(--newtab-search-first-shadow), 0 0 2px var(--newtab-search-second-shadow);
+ border: 1px solid transparent;
+ border-radius: 8px;
+ color: var(--newtab-search-text-color);
+ font-weight: 500;
+ font-size: 15px;
+ }
+
+ .search-handoff-button {
+ padding-inline-end: 15px;
+
+ .fake-caret {
+ top: 18px;
+ inset-inline-start: $search-icon-width;
+
+ &:dir(rtl) {
+ background-position-x: right $search-icon-padding;
+ }
+ }
+ }
+ }
+}
+
+.search-wrapper {
+ padding: 34px 0 64px;
+
+ .only-search & {
+ padding: 0 0 64px;
+ }
+
+ .logo-and-wordmark {
+ $logo-size: 82px;
+ $wordmark-size: 134px;
+
+ align-items: center;
+ display: flex;
+ justify-content: center;
+ margin-bottom: 48px;
+
+ .logo {
+ background: url('chrome://branding/content/about-logo.png') no-repeat center;
+ background-size: $logo-size;
+ @media (min-resolution: 2x) {
+ background-image: url('chrome://branding/content/about-logo@2x.png');
+ }
+ display: inline-block;
+ height: $logo-size;
+ width: $logo-size;
+ }
+
+ .wordmark {
+ background: url('chrome://branding/content/firefox-wordmark.svg') no-repeat center center;
+ background-size: $wordmark-size;
+ -moz-context-properties: fill;
+ display: inline-block;
+ fill: var(--newtab-search-wordmark-color);
+ height: $logo-size;
+ margin-inline-start: 16px;
+ width: $wordmark-size;
+ }
+
+ @media (max-width: $break-point-medium - 1) {
+ $logo-size-small: 64px;
+ $wordmark-small-size: 100px;
+
+ .logo {
+ background-size: $logo-size-small;
+ height: $logo-size-small;
+ width: $logo-size-small;
+ }
+
+ .wordmark {
+ background-size: $wordmark-small-size;
+ height: $logo-size-small;
+ width: $wordmark-small-size;
+ margin-inline-start: 12px;
+ }
+ }
+ }
+
+ .search-inner-wrapper {
+ cursor: default;
+ display: flex;
+ min-height: $search-height;
+ margin: 0 auto;
+ position: relative;
+ width: $searchbar-width-small;
+
+ .ds-outer-wrapper-breakpoint-override & {
+ width: 216px;
+ }
+
+ @media (min-width: $break-point-medium) {
+ width: $searchbar-width-medium;
+
+ .ds-outer-wrapper-breakpoint-override & {
+ width: 460px;
+ }
+ }
+
+ @media (min-width: $break-point-large) {
+ width: $searchbar-width-large;
+
+ .ds-outer-wrapper-breakpoint-override & {
+ width: 696px;
+ }
+ }
+ }
+
+ input {
+ background: var(--newtab-textbox-background-color) var(--newtab-search-icon) $search-icon-padding center no-repeat;
+ background-size: $search-icon-size;
+ border: solid 1px var(--newtab-search-border-color);
+ box-shadow: $shadow-secondary, 0 0 0 1px $black-15;
+ font-size: 15px;
+ -moz-context-properties: fill;
+ fill: var(--newtab-search-icon-color);
+ padding: 0;
+ padding-inline-end: $search-button-width;
+ padding-inline-start: $search-icon-width;
+ width: 100%;
+
+ &:dir(rtl) {
+ background-position-x: right $search-icon-padding;
+ }
+ }
+
+ &:hover input {
+ box-shadow: $shadow-secondary, 0 0 0 1px $black-25;
+ }
+
+ .search-inner-wrapper:active input,
+ input:focus {
+ border: $input-border-active;
+ box-shadow: var(--newtab-textbox-focus-boxshadow);
+ }
+
+ .search-button {
+ background: $glyph-forward no-repeat center center;
+ background-size: 16px 16px;
+ border: 0;
+ border-radius: 0 $border-radius $border-radius 0;
+ -moz-context-properties: fill;
+ fill: var(--newtab-search-icon-color);
+ height: 100%;
+ inset-inline-end: 0;
+ position: absolute;
+ width: $search-button-width;
+
+ &:focus,
+ &:hover {
+ background-color: $grey-90-10;
+ cursor: pointer;
+ }
+
+ &:active {
+ background-color: $grey-90-20;
+ }
+
+ &:dir(rtl) {
+ transform: scaleX(-1);
+ }
+ }
+}
+
+.non-collapsible-section + .below-search-snippet-wrapper {
+ // If search is enabled, we need to invade its large bottom padding.
+ margin-top: -48px;
+}
+
+@media (max-height: 700px) {
+ .search-wrapper {
+ padding: 0 0 30px;
+ }
+
+ .non-collapsible-section + .below-search-snippet-wrapper {
+ // In shorter windows, search doesn't have such a large padding.
+ margin-top: -14px;
+ }
+
+ .below-search-snippet-wrapper {
+ min-height: 0;
+ }
+}
+
+.search-handoff-button {
+ background: var(--newtab-textbox-background-color) var(--newtab-search-icon) $search-icon-padding center no-repeat;
+ background-size: $search-icon-size;
+ border: solid 1px var(--newtab-search-border-color);
+ border-radius: 3px;
+ box-shadow: $shadow-secondary, 0 0 0 1px $black-15;
+ cursor: text;
+ font-size: 15px;
+ padding: 0;
+ padding-inline-end: 48px;
+ padding-inline-start: 46px;
+ opacity: 1;
+ transition: opacity 500ms;
+ width: 100%;
+
+ &:dir(rtl) {
+ background-position-x: right $search-icon-padding;
+ }
+
+ &:hover {
+ box-shadow: $shadow-secondary, 0 0 0 1px $black-25;
+ }
+
+ .fake-focus & {
+ border: $input-border-active;
+ box-shadow: var(--newtab-textbox-focus-boxshadow);
+
+ .fake-caret {
+ display: block;
+ }
+ }
+
+ .search-hidden & {
+ opacity: 0;
+ visibility: hidden;
+ }
+
+ .fake-editable:focus {
+ outline: none;
+ caret-color: transparent;
+ }
+
+ .fake-editable {
+ color: transparent;
+ height: 100%;
+ opacity: 0;
+ position: absolute;
+ top: 0;
+ left: 0;
+ right: 0;
+ bottom: 0;
+ }
+
+ .fake-textbox {
+ opacity: 0.54;
+ text-align: start;
+ }
+
+ .fake-caret {
+ animation: caret-animation 1.3s steps(5, start) infinite;
+ background: var(--newtab-text-primary-color);
+ display: none;
+ inset-inline-start: 47px;
+ height: 17px;
+ position: absolute;
+ top: 16px;
+ width: 1px;
+
+ @keyframes caret-animation {
+ to {
+ visibility: hidden;
+ }
+ }
+ }
+}
+
+@media (min-height: 701px) {
+ body:not(.inline-onboarding) .fixed-search {
+ main {
+ padding-top: 146px;
+ }
+
+ &.visible-logo {
+ main {
+ padding-top: 276px;
+ }
+ }
+
+ .search-wrapper {
+ $search-height: 35px;
+ $search-icon-size: 16px;
+ $search-icon-padding: 16px;
+
+ border-bottom: solid 1px var(--newtab-border-secondary-color);
+ padding: 30px 0;
+ $search-header-bar-height: 95px;
+ background-color: var(--newtab-search-header-background-color);
+ min-height: $search-header-bar-height;
+ left: 0;
+ position: fixed;
+ top: 0;
+ width: 100%;
+ z-index: 9;
+
+ .search-inner-wrapper {
+ min-height: $search-height;
+ }
+
+ input {
+ background-position-x: $search-icon-padding;
+ background-size: $search-icon-size;
+
+ &:dir(rtl) {
+ background-position-x: right $search-icon-padding;
+ }
+ }
+
+ .search-handoff-button .fake-caret {
+ top: 14px;
+ }
+
+ .logo-and-wordmark {
+ display: none;
+ }
+ }
+
+ &.newtab-experience {
+ main {
+ padding-top: 124px;
+ }
+
+ &.visible-logo {
+ main {
+ padding-top: 254px;
+ }
+ }
+
+ .search-wrapper {
+ $search-height: 45px;
+ $search-icon-size: 24px;
+ $search-icon-padding: 16px;
+
+ border-bottom: solid 1px var(--newtab-seperator-line-color);
+ padding: 27px 0;
+
+ .search-inner-wrapper {
+ min-height: $search-height;
+ }
+
+ input {
+ background-position-x: $search-icon-padding;
+ background-size: $search-icon-size;
+
+ &:dir(rtl) {
+ background-position-x: right $search-icon-padding;
+ }
+ }
+ }
+ }
+
+ .search-handoff-button {
+ background-position-x: $search-icon-padding;
+ background-size: $search-icon-size;
+
+ &:dir(rtl) {
+ background-position-x: right $search-icon-padding;
+ }
+
+ .fake-caret {
+ top: 10px;
+ }
+ }
+ }
+}
+
+@at-root {
+ // Adjust the style of the contentSearchUI-generated table
+ .contentSearchSuggestionTable {
+ background-color: var(--newtab-search-dropdown-color);
+ border: 0;
+ box-shadow: $context-menu-shadow;
+ transform: translateY($textbox-shadow-size);
+
+ .contentSearchHeader {
+ background-color: var(--newtab-search-dropdown-header-color);
+ color: var(--newtab-text-secondary-color);
+ }
+
+ .contentSearchHeader,
+ .contentSearchSettingsButton {
+ border-color: var(--newtab-border-secondary-color);
+ }
+
+ .contentSearchSuggestionsList {
+ border: 0;
+ }
+
+ .contentSearchOneOffsTable {
+ background-color: var(--newtab-search-dropdown-header-color);
+ border-top: solid 1px var(--newtab-border-secondary-color);
+ }
+
+ .contentSearchSearchWithHeaderSearchText {
+ color: var(--newtab-text-primary-color);
+ }
+
+ .contentSearchSuggestionsContainer {
+ background-color: var(--newtab-search-dropdown-color);
+ }
+
+ .contentSearchSuggestionRow {
+ &.selected {
+ background: var(--newtab-element-hover-color);
+ color: var(--newtab-text-primary-color);
+
+ &:active {
+ background: var(--newtab-element-active-color);
+ }
+
+ .historyIcon {
+ fill: var(--newtab-icon-secondary-color);
+ }
+ }
+ }
+
+ .contentSearchOneOffsTable {
+ .contentSearchSuggestionsContainer {
+ background-color: var(--newtab-search-dropdown-header-color);
+ }
+ }
+
+ .contentSearchOneOffItem {
+ // Make the border slightly shorter by offsetting from the top and bottom
+ $border-offset: 18%;
+
+ background-image: none;
+ border-image: linear-gradient(transparent $border-offset, var(--newtab-border-secondary-color) $border-offset, var(--newtab-border-secondary-color) 100% - $border-offset, transparent 100% - $border-offset) 1;
+ border-inline-end: 1px solid;
+ position: relative;
+
+ &.selected {
+ background: var(--newtab-element-hover-color);
+ }
+
+ &:active {
+ background: var(--newtab-element-active-color);
+ }
+ }
+
+ .contentSearchSettingsButton {
+ &:hover {
+ background: var(--newtab-element-hover-color);
+ color: var(--newtab-text-primary-color);
+ }
+ }
+ }
+
+ .contentSearchHeaderRow > td > img,
+ .contentSearchSuggestionRow > td > .historyIcon {
+ margin-inline-start: 7px;
+ margin-inline-end: 15px;
+ }
+}
diff --git a/browser/components/newtab/content-src/components/SectionMenu/SectionMenu.jsx b/browser/components/newtab/content-src/components/SectionMenu/SectionMenu.jsx
new file mode 100644
index 0000000000..25e44ad060
--- /dev/null
+++ b/browser/components/newtab/content-src/components/SectionMenu/SectionMenu.jsx
@@ -0,0 +1,122 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { actionCreators as ac } from "common/Actions.jsm";
+import { ContextMenu } from "content-src/components/ContextMenu/ContextMenu";
+import React from "react";
+import { connect } from "react-redux";
+import { SectionMenuOptions } from "content-src/lib/section-menu-options";
+
+const DEFAULT_SECTION_MENU_OPTIONS = [
+ "MoveUp",
+ "MoveDown",
+ "Separator",
+ "RemoveSection",
+ "CheckCollapsed",
+ "Separator",
+ "ManageSection",
+];
+const WEBEXT_SECTION_MENU_OPTIONS = [
+ "MoveUp",
+ "MoveDown",
+ "Separator",
+ "CheckCollapsed",
+ "Separator",
+ "ManageWebExtension",
+];
+
+export class _SectionMenu extends React.PureComponent {
+ handleAddWhileCollapsed() {
+ const { action, userEvent } = SectionMenuOptions.ExpandSection(this.props);
+ this.props.dispatch(action);
+ if (userEvent) {
+ this.props.dispatch(
+ ac.UserEvent({
+ event: userEvent,
+ source: this.props.source,
+ })
+ );
+ }
+ }
+
+ getOptions() {
+ const { props } = this;
+
+ const propOptions = props.isWebExtension
+ ? [...WEBEXT_SECTION_MENU_OPTIONS]
+ : [...DEFAULT_SECTION_MENU_OPTIONS];
+
+ // Remove Collapse/Expand related option if the `newNewtabExperience.enabled`
+ // pref is set to true.
+ if (props.Prefs.values["newNewtabExperience.enabled"]) {
+ if (props.isWebExtension) {
+ propOptions.splice(2, 2);
+ } else {
+ propOptions.splice(4, 1);
+ }
+ }
+
+ // Remove the move related options if the section is fixed
+ if (props.isFixed) {
+ propOptions.splice(propOptions.indexOf("MoveUp"), 3);
+ }
+ // Prepend custom options and a separator
+ if (props.extraOptions) {
+ propOptions.splice(0, 0, ...props.extraOptions, "Separator");
+ }
+ // Insert privacy notice before the last option ("ManageSection")
+ if (props.privacyNoticeURL) {
+ propOptions.splice(-1, 0, "PrivacyNotice");
+ }
+
+ const options = propOptions
+ .map(o => SectionMenuOptions[o](props))
+ .map(option => {
+ const { action, id, type, userEvent } = option;
+ if (!type && id) {
+ option.onClick = () => {
+ const hasAddEvent =
+ userEvent === "MENU_ADD_TOPSITE" ||
+ userEvent === "MENU_ADD_SEARCH";
+
+ if (props.collapsed && hasAddEvent) {
+ this.handleAddWhileCollapsed();
+ }
+
+ props.dispatch(action);
+ if (userEvent) {
+ props.dispatch(
+ ac.UserEvent({
+ event: userEvent,
+ source: props.source,
+ })
+ );
+ }
+ };
+ }
+ return option;
+ });
+
+ // This is for accessibility to support making each item tabbable.
+ // We want to know which item is the first and which item
+ // is the last, so we can close the context menu accordingly.
+ options[0].first = true;
+ options[options.length - 1].last = true;
+ return options;
+ }
+
+ render() {
+ return (
+ <ContextMenu
+ onUpdate={this.props.onUpdate}
+ options={this.getOptions()}
+ keyboardAccess={this.props.keyboardAccess}
+ />
+ );
+ }
+}
+
+export const SectionMenu = connect(state => ({
+ Prefs: state.Prefs,
+}))(_SectionMenu);
diff --git a/browser/components/newtab/content-src/components/Sections/Sections.jsx b/browser/components/newtab/content-src/components/Sections/Sections.jsx
new file mode 100644
index 0000000000..cc00e93b94
--- /dev/null
+++ b/browser/components/newtab/content-src/components/Sections/Sections.jsx
@@ -0,0 +1,390 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { actionCreators as ac, actionTypes as at } from "common/Actions.jsm";
+import { Card, PlaceholderCard } from "content-src/components/Card/Card";
+import { CollapsibleSection } from "content-src/components/CollapsibleSection/CollapsibleSection";
+import { ComponentPerfTimer } from "content-src/components/ComponentPerfTimer/ComponentPerfTimer";
+import { FluentOrText } from "content-src/components/FluentOrText/FluentOrText";
+import { connect } from "react-redux";
+import { MoreRecommendations } from "content-src/components/MoreRecommendations/MoreRecommendations";
+import { PocketLoggedInCta } from "content-src/components/PocketLoggedInCta/PocketLoggedInCta";
+import React from "react";
+import { Topics } from "content-src/components/Topics/Topics";
+import { TopSites } from "content-src/components/TopSites/TopSites";
+
+const VISIBLE = "visible";
+const VISIBILITY_CHANGE_EVENT = "visibilitychange";
+const CARDS_PER_ROW_DEFAULT = 3;
+const CARDS_PER_ROW_COMPACT_WIDE = 4;
+
+export class Section extends React.PureComponent {
+ get numRows() {
+ const { rowsPref, maxRows, Prefs } = this.props;
+ return rowsPref ? Prefs.values[rowsPref] : maxRows;
+ }
+
+ _dispatchImpressionStats() {
+ const { props } = this;
+ let cardsPerRow = CARDS_PER_ROW_DEFAULT;
+ if (
+ props.compactCards &&
+ global.matchMedia(`(min-width: 1072px)`).matches
+ ) {
+ // If the section has compact cards and the viewport is wide enough, we show
+ // 4 columns instead of 3.
+ // $break-point-widest = 1072px (from _variables.scss)
+ cardsPerRow = CARDS_PER_ROW_COMPACT_WIDE;
+ }
+ const maxCards = cardsPerRow * this.numRows;
+ const cards = props.rows.slice(0, maxCards);
+
+ if (this.needsImpressionStats(cards)) {
+ props.dispatch(
+ ac.ImpressionStats({
+ source: props.eventSource,
+ tiles: cards.map(link => ({ id: link.guid })),
+ })
+ );
+ this.impressionCardGuids = cards.map(link => link.guid);
+ }
+ }
+
+ // This sends an event when a user sees a set of new content. If content
+ // changes while the page is hidden (i.e. preloaded or on a hidden tab),
+ // only send the event if the page becomes visible again.
+ sendImpressionStatsOrAddListener() {
+ const { props } = this;
+
+ if (!props.shouldSendImpressionStats || !props.dispatch) {
+ return;
+ }
+
+ if (props.document.visibilityState === VISIBLE) {
+ this._dispatchImpressionStats();
+ } else {
+ // We should only ever send the latest impression stats ping, so remove any
+ // older listeners.
+ if (this._onVisibilityChange) {
+ props.document.removeEventListener(
+ VISIBILITY_CHANGE_EVENT,
+ this._onVisibilityChange
+ );
+ }
+
+ // When the page becomes visible, send the impression stats ping if the section isn't collapsed.
+ this._onVisibilityChange = () => {
+ if (props.document.visibilityState === VISIBLE) {
+ if (!this.props.pref.collapsed) {
+ this._dispatchImpressionStats();
+ }
+ props.document.removeEventListener(
+ VISIBILITY_CHANGE_EVENT,
+ this._onVisibilityChange
+ );
+ }
+ };
+ props.document.addEventListener(
+ VISIBILITY_CHANGE_EVENT,
+ this._onVisibilityChange
+ );
+ }
+ }
+
+ componentWillMount() {
+ this.sendNewTabRehydrated(this.props.initialized);
+ }
+
+ componentDidMount() {
+ if (this.props.rows.length && !this.props.pref.collapsed) {
+ this.sendImpressionStatsOrAddListener();
+ }
+ }
+
+ componentDidUpdate(prevProps) {
+ const { props } = this;
+ const isCollapsed = props.pref.collapsed;
+ const wasCollapsed = prevProps.pref.collapsed;
+ if (
+ // Don't send impression stats for the empty state
+ props.rows.length &&
+ // We only want to send impression stats if the content of the cards has changed
+ // and the section is not collapsed...
+ ((props.rows !== prevProps.rows && !isCollapsed) ||
+ // or if we are expanding a section that was collapsed.
+ (wasCollapsed && !isCollapsed))
+ ) {
+ this.sendImpressionStatsOrAddListener();
+ }
+ }
+
+ componentWillUpdate(nextProps) {
+ this.sendNewTabRehydrated(nextProps.initialized);
+ }
+
+ componentWillUnmount() {
+ if (this._onVisibilityChange) {
+ this.props.document.removeEventListener(
+ VISIBILITY_CHANGE_EVENT,
+ this._onVisibilityChange
+ );
+ }
+ }
+
+ needsImpressionStats(cards) {
+ if (
+ !this.impressionCardGuids ||
+ this.impressionCardGuids.length !== cards.length
+ ) {
+ return true;
+ }
+
+ for (let i = 0; i < cards.length; i++) {
+ if (cards[i].guid !== this.impressionCardGuids[i]) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ // The NEW_TAB_REHYDRATED event is used to inform feeds that their
+ // data has been consumed e.g. for counting the number of tabs that
+ // have rendered that data.
+ sendNewTabRehydrated(initialized) {
+ if (initialized && !this.renderNotified) {
+ this.props.dispatch(
+ ac.AlsoToMain({ type: at.NEW_TAB_REHYDRATED, data: {} })
+ );
+ this.renderNotified = true;
+ }
+ }
+
+ render() {
+ const {
+ id,
+ eventSource,
+ title,
+ icon,
+ rows,
+ Pocket,
+ topics,
+ emptyState,
+ dispatch,
+ compactCards,
+ read_more_endpoint,
+ contextMenuOptions,
+ initialized,
+ learnMore,
+ pref,
+ privacyNoticeURL,
+ isFirst,
+ isLast,
+ } = this.props;
+
+ const waitingForSpoc =
+ id === "topstories" && this.props.Pocket.waitingForSpoc;
+ const maxCardsPerRow = compactCards
+ ? CARDS_PER_ROW_COMPACT_WIDE
+ : CARDS_PER_ROW_DEFAULT;
+ const { numRows } = this;
+ const maxCards = maxCardsPerRow * numRows;
+ const maxCardsOnNarrow = CARDS_PER_ROW_DEFAULT * numRows;
+
+ const { pocketCta, isUserLoggedIn } = Pocket || {};
+ const { useCta } = pocketCta || {};
+
+ // Don't display anything until we have a definitve result from Pocket,
+ // to avoid a flash of logged out state while we render.
+ const isPocketLoggedInDefined =
+ isUserLoggedIn === true || isUserLoggedIn === false;
+
+ const hasTopics = topics && !!topics.length;
+
+ const shouldShowPocketCta =
+ id === "topstories" && useCta && isUserLoggedIn === false;
+
+ // Show topics only for top stories and if it has loaded with topics.
+ // The classs .top-stories-bottom-container ensures content doesn't shift as things load.
+ const shouldShowTopics =
+ id === "topstories" &&
+ hasTopics &&
+ ((useCta && isUserLoggedIn === true) ||
+ (!useCta && isPocketLoggedInDefined));
+
+ // We use topics to determine language support for read more.
+ const shouldShowReadMore = read_more_endpoint && hasTopics;
+
+ const realRows = rows.slice(0, maxCards);
+
+ // The empty state should only be shown after we have initialized and there is no content.
+ // Otherwise, we should show placeholders.
+ const shouldShowEmptyState = initialized && !rows.length;
+
+ const cards = [];
+ if (!shouldShowEmptyState) {
+ for (let i = 0; i < maxCards; i++) {
+ const link = realRows[i];
+ // On narrow viewports, we only show 3 cards per row. We'll mark the rest as
+ // .hide-for-narrow to hide in CSS via @media query.
+ const className = i >= maxCardsOnNarrow ? "hide-for-narrow" : "";
+ let usePlaceholder = !link;
+ // If we are in the third card and waiting for spoc,
+ // use the placeholder.
+ if (!usePlaceholder && i === 2 && waitingForSpoc) {
+ usePlaceholder = true;
+ }
+ cards.push(
+ !usePlaceholder ? (
+ <Card
+ key={i}
+ index={i}
+ className={className}
+ dispatch={dispatch}
+ link={link}
+ contextMenuOptions={contextMenuOptions}
+ eventSource={eventSource}
+ shouldSendImpressionStats={this.props.shouldSendImpressionStats}
+ isWebExtension={this.props.isWebExtension}
+ />
+ ) : (
+ <PlaceholderCard key={i} className={className} />
+ )
+ );
+ }
+ }
+
+ const sectionClassName = [
+ "section",
+ compactCards ? "compact-cards" : "normal-cards",
+ ].join(" ");
+
+ // <Section> <-- React component
+ // <section> <-- HTML5 element
+ return (
+ <ComponentPerfTimer {...this.props}>
+ <CollapsibleSection
+ className={sectionClassName}
+ icon={icon}
+ title={title}
+ id={id}
+ eventSource={eventSource}
+ collapsed={this.props.pref.collapsed}
+ showPrefName={(pref && pref.feed) || id}
+ privacyNoticeURL={privacyNoticeURL}
+ Prefs={this.props.Prefs}
+ isFixed={this.props.isFixed}
+ isFirst={isFirst}
+ isLast={isLast}
+ learnMore={learnMore}
+ dispatch={this.props.dispatch}
+ isWebExtension={this.props.isWebExtension}
+ >
+ {!shouldShowEmptyState && (
+ <ul className="section-list" style={{ padding: 0 }}>
+ {cards}
+ </ul>
+ )}
+ {shouldShowEmptyState && (
+ <div className="section-empty-state">
+ <div className="empty-state">
+ {emptyState.icon &&
+ emptyState.icon.startsWith("moz-extension://") ? (
+ <span
+ className="empty-state-icon icon"
+ style={{ "background-image": `url('${emptyState.icon}')` }}
+ />
+ ) : (
+ <span
+ className={`empty-state-icon icon icon-${emptyState.icon}`}
+ />
+ )}
+ <FluentOrText message={emptyState.message}>
+ <p className="empty-state-message" />
+ </FluentOrText>
+ </div>
+ </div>
+ )}
+ {id === "topstories" && (
+ <div className="top-stories-bottom-container">
+ {shouldShowTopics && (
+ <div className="wrapper-topics">
+ <Topics topics={this.props.topics} />
+ </div>
+ )}
+
+ {shouldShowPocketCta && (
+ <div className="wrapper-cta">
+ <PocketLoggedInCta />
+ </div>
+ )}
+
+ <div className="wrapper-more-recommendations">
+ {shouldShowReadMore && (
+ <MoreRecommendations
+ read_more_endpoint={read_more_endpoint}
+ />
+ )}
+ </div>
+ </div>
+ )}
+ </CollapsibleSection>
+ </ComponentPerfTimer>
+ );
+ }
+}
+
+Section.defaultProps = {
+ document: global.document,
+ rows: [],
+ emptyState: {},
+ pref: {},
+ title: "",
+};
+
+export const SectionIntl = connect(state => ({
+ Prefs: state.Prefs,
+ Pocket: state.Pocket,
+}))(Section);
+
+export class _Sections extends React.PureComponent {
+ renderSections() {
+ const sections = [];
+ const enabledSections = this.props.Sections.filter(
+ section => section.enabled
+ );
+ const {
+ sectionOrder,
+ "feeds.topsites": showTopSites,
+ } = this.props.Prefs.values;
+ // Enabled sections doesn't include Top Sites, so we add it if enabled.
+ const expectedCount = enabledSections.length + ~~showTopSites;
+
+ for (const sectionId of sectionOrder.split(",")) {
+ const commonProps = {
+ key: sectionId,
+ isFirst: sections.length === 0,
+ isLast: sections.length === expectedCount - 1,
+ };
+ if (sectionId === "topsites" && showTopSites) {
+ sections.push(<TopSites {...commonProps} />);
+ } else {
+ const section = enabledSections.find(s => s.id === sectionId);
+ if (section) {
+ sections.push(<SectionIntl {...section} {...commonProps} />);
+ }
+ }
+ }
+ return sections;
+ }
+
+ render() {
+ return <div className="sections-list">{this.renderSections()}</div>;
+ }
+}
+
+export const Sections = connect(state => ({
+ Sections: state.Sections,
+ Prefs: state.Prefs,
+}))(_Sections);
diff --git a/browser/components/newtab/content-src/components/Sections/_Sections.scss b/browser/components/newtab/content-src/components/Sections/_Sections.scss
new file mode 100644
index 0000000000..ba6e2681e0
--- /dev/null
+++ b/browser/components/newtab/content-src/components/Sections/_Sections.scss
@@ -0,0 +1,135 @@
+.sections-list {
+ .section-list {
+ display: grid;
+ grid-gap: $base-gutter;
+ grid-template-columns: repeat(auto-fit, $card-width);
+ margin: 0;
+
+ @media (max-width: $break-point-medium) {
+ @include context-menu-open-left;
+ }
+
+ @media (min-width: $break-point-medium) and (max-width: $break-point-large) {
+ :nth-child(2n) {
+ @include context-menu-open-left;
+ }
+ }
+
+ @media (min-width: $break-point-large) and (max-width: $break-point-large + 2 * $card-width) {
+ :nth-child(3n) {
+ @include context-menu-open-left;
+ }
+ }
+
+ @media (min-width: $break-point-widest) and (max-width: $break-point-widest + 2 * $card-width) {
+ // 3n for normal cards, 4n for compact cards
+ :nth-child(3n),
+ :nth-child(4n) {
+ @include context-menu-open-left;
+ }
+ }
+ }
+
+ .section-empty-state {
+ border: $border-secondary;
+ border-radius: $border-radius;
+ display: flex;
+ height: $card-height;
+ width: 100%;
+
+ .empty-state {
+ margin: auto;
+ max-width: 350px;
+
+ .empty-state-icon {
+ background-position: center;
+ background-repeat: no-repeat;
+ background-size: 50px 50px;
+ -moz-context-properties: fill;
+ display: block;
+ fill: var(--newtab-icon-secondary-color);
+ height: 50px;
+ margin: 0 auto;
+ width: 50px;
+ }
+
+ .empty-state-message {
+ color: var(--newtab-text-primary-color);
+ font-size: 13px;
+ margin-bottom: 0;
+ text-align: center;
+ }
+ }
+
+ @media (min-width: $break-point-widest) {
+ height: $card-height-large;
+ }
+ }
+}
+
+.top-stories-bottom-container {
+ color: var(--newtab-section-navigation-text-color);
+ font-size: 12px;
+ line-height: 1.6;
+ margin-top: $topic-margin-top;
+ display: flex;
+ justify-content: space-between;
+
+ a {
+ color: var(--newtab-link-secondary-color);
+ font-weight: bold;
+
+ &.more-recommendations {
+ font-weight: normal;
+ font-size: 13px;
+ }
+ }
+
+ .wrapper-topics,
+ .wrapper-cta + .wrapper-more-recommendations {
+ @media (max-width: $break-point-large - 1) {
+ display: none;
+ }
+ }
+
+ @media (max-width: $break-point-medium - 1) {
+ .wrapper-cta {
+ text-align: center;
+
+ .pocket-logged-in-cta {
+ display: block;
+ margin-inline-end: 0;
+
+ .pocket-cta-button {
+ max-width: none;
+ display: block;
+ margin-inline-end: 0;
+ margin: 5px 0 10px;
+ }
+ }
+ }
+
+ .wrapper-more-recommendations {
+ width: 100%;
+
+ .more-recommendations {
+ justify-content: center;
+
+ &::after {
+ display: none;
+ }
+ }
+ }
+ }
+}
+
+@media (min-width: $break-point-widest) {
+ .sections-list {
+ // Compact cards stay the same size but normal cards get bigger.
+ .normal-cards {
+ .section-list {
+ grid-template-columns: repeat(auto-fit, $card-width-large);
+ }
+ }
+ }
+}
diff --git a/browser/components/newtab/content-src/components/TopSites/SearchShortcutsForm.jsx b/browser/components/newtab/content-src/components/TopSites/SearchShortcutsForm.jsx
new file mode 100644
index 0000000000..540660d254
--- /dev/null
+++ b/browser/components/newtab/content-src/components/TopSites/SearchShortcutsForm.jsx
@@ -0,0 +1,189 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { actionCreators as ac, actionTypes as at } from "common/Actions.jsm";
+import React from "react";
+import { TOP_SITES_SOURCE } from "./TopSitesConstants";
+
+export class SelectableSearchShortcut extends React.PureComponent {
+ render() {
+ const { shortcut, selected } = this.props;
+ const imageStyle = { backgroundImage: `url("${shortcut.tippyTopIcon}")` };
+ return (
+ <div className="top-site-outer search-shortcut">
+ <input
+ type="checkbox"
+ id={shortcut.keyword}
+ name={shortcut.keyword}
+ checked={selected}
+ onChange={this.props.onChange}
+ />
+ <label htmlFor={shortcut.keyword}>
+ <div className="top-site-inner">
+ <span>
+ <div className="tile">
+ <div
+ className="top-site-icon rich-icon"
+ style={imageStyle}
+ data-fallback="@"
+ />
+ <div className="top-site-icon search-topsite" />
+ </div>
+ <div className="title">
+ <span dir="auto">{shortcut.keyword}</span>
+ </div>
+ </span>
+ </div>
+ </label>
+ </div>
+ );
+ }
+}
+
+export class SearchShortcutsForm extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.handleChange = this.handleChange.bind(this);
+ this.onCancelButtonClick = this.onCancelButtonClick.bind(this);
+ this.onSaveButtonClick = this.onSaveButtonClick.bind(this);
+
+ // clone the shortcuts and add them to the state so we can add isSelected property
+ const shortcuts = [];
+ const { rows, searchShortcuts } = props.TopSites;
+ searchShortcuts.forEach(shortcut => {
+ shortcuts.push({
+ ...shortcut,
+ isSelected: !!rows.find(
+ row =>
+ row &&
+ row.isPinned &&
+ row.searchTopSite &&
+ row.label === shortcut.keyword
+ ),
+ });
+ });
+ this.state = { shortcuts };
+ }
+
+ handleChange(event) {
+ const { target } = event;
+ const { name, checked } = target;
+ this.setState(prevState => {
+ const shortcuts = prevState.shortcuts.slice();
+ let shortcut = shortcuts.find(({ keyword }) => keyword === name);
+ shortcut.isSelected = checked;
+ return { shortcuts };
+ });
+ }
+
+ onCancelButtonClick(ev) {
+ ev.preventDefault();
+ this.props.onClose();
+ }
+
+ onSaveButtonClick(ev) {
+ ev.preventDefault();
+
+ // Check if there were any changes and act accordingly
+ const { rows } = this.props.TopSites;
+ const pinQueue = [];
+ const unpinQueue = [];
+ this.state.shortcuts.forEach(shortcut => {
+ const alreadyPinned = rows.find(
+ row =>
+ row &&
+ row.isPinned &&
+ row.searchTopSite &&
+ row.label === shortcut.keyword
+ );
+ if (shortcut.isSelected && !alreadyPinned) {
+ pinQueue.push(this._searchTopSite(shortcut));
+ } else if (!shortcut.isSelected && alreadyPinned) {
+ unpinQueue.push({
+ url: alreadyPinned.url,
+ searchVendor: shortcut.shortURL,
+ });
+ }
+ });
+
+ // Tell the feed to do the work.
+ this.props.dispatch(
+ ac.OnlyToMain({
+ type: at.UPDATE_PINNED_SEARCH_SHORTCUTS,
+ data: {
+ addedShortcuts: pinQueue,
+ deletedShortcuts: unpinQueue,
+ },
+ })
+ );
+
+ // Send the Telemetry pings.
+ pinQueue.forEach(shortcut => {
+ this.props.dispatch(
+ ac.UserEvent({
+ source: TOP_SITES_SOURCE,
+ event: "SEARCH_EDIT_ADD",
+ value: { search_vendor: shortcut.searchVendor },
+ })
+ );
+ });
+ unpinQueue.forEach(shortcut => {
+ this.props.dispatch(
+ ac.UserEvent({
+ source: TOP_SITES_SOURCE,
+ event: "SEARCH_EDIT_DELETE",
+ value: { search_vendor: shortcut.searchVendor },
+ })
+ );
+ });
+
+ this.props.onClose();
+ }
+
+ _searchTopSite(shortcut) {
+ return {
+ url: shortcut.url,
+ searchTopSite: true,
+ label: shortcut.keyword,
+ searchVendor: shortcut.shortURL,
+ };
+ }
+
+ render() {
+ return (
+ <form className="topsite-form">
+ <div className="search-shortcuts-container">
+ <h3
+ className="section-title grey-title"
+ data-l10n-id="newtab-topsites-add-search-engine-header"
+ />
+ <div>
+ {this.state.shortcuts.map(shortcut => (
+ <SelectableSearchShortcut
+ key={shortcut.keyword}
+ shortcut={shortcut}
+ selected={shortcut.isSelected}
+ onChange={this.handleChange}
+ />
+ ))}
+ </div>
+ </div>
+ <section className="actions">
+ <button
+ className="cancel"
+ type="button"
+ onClick={this.onCancelButtonClick}
+ data-l10n-id="newtab-topsites-cancel-button"
+ />
+ <button
+ className="done"
+ type="submit"
+ onClick={this.onSaveButtonClick}
+ data-l10n-id="newtab-topsites-save-button"
+ />
+ </section>
+ </form>
+ );
+ }
+}
diff --git a/browser/components/newtab/content-src/components/TopSites/TopSite.jsx b/browser/components/newtab/content-src/components/TopSites/TopSite.jsx
new file mode 100644
index 0000000000..cb57f11f4a
--- /dev/null
+++ b/browser/components/newtab/content-src/components/TopSites/TopSite.jsx
@@ -0,0 +1,823 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { actionCreators as ac, actionTypes as at } from "common/Actions.jsm";
+import {
+ MIN_CORNER_FAVICON_SIZE,
+ MIN_RICH_FAVICON_SIZE,
+ TOP_SITES_CONTEXT_MENU_OPTIONS,
+ TOP_SITES_SPOC_CONTEXT_MENU_OPTIONS,
+ TOP_SITES_SPONSORED_POSITION_CONTEXT_MENU_OPTIONS,
+ TOP_SITES_SEARCH_SHORTCUTS_CONTEXT_MENU_OPTIONS,
+ TOP_SITES_SOURCE,
+} from "./TopSitesConstants";
+import { LinkMenu } from "content-src/components/LinkMenu/LinkMenu";
+import { ImpressionStats } from "../DiscoveryStreamImpressionStats/ImpressionStats";
+import React from "react";
+import { ScreenshotUtils } from "content-src/lib/screenshot-utils";
+import { TOP_SITES_MAX_SITES_PER_ROW } from "common/Reducers.jsm";
+import { ContextMenuButton } from "content-src/components/ContextMenu/ContextMenuButton";
+const SPOC_TYPE = "SPOC";
+
+export class TopSiteLink extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.state = { screenshotImage: null };
+ this.onDragEvent = this.onDragEvent.bind(this);
+ this.onKeyPress = this.onKeyPress.bind(this);
+ }
+
+ /*
+ * Helper to determine whether the drop zone should allow a drop. We only allow
+ * dropping top sites for now. We don't allow dropping on sponsored top sites
+ * as their position is fixed.
+ */
+ _allowDrop(e) {
+ return (
+ (this.dragged || !this.props.link.sponsored_position) &&
+ e.dataTransfer.types.includes("text/topsite-index")
+ );
+ }
+
+ onDragEvent(event) {
+ switch (event.type) {
+ case "click":
+ // Stop any link clicks if we started any dragging
+ if (this.dragged) {
+ event.preventDefault();
+ }
+ break;
+ case "dragstart":
+ this.dragged = true;
+ event.dataTransfer.effectAllowed = "move";
+ event.dataTransfer.setData("text/topsite-index", this.props.index);
+ event.target.blur();
+ this.props.onDragEvent(
+ event,
+ this.props.index,
+ this.props.link,
+ this.props.title
+ );
+ break;
+ case "dragend":
+ this.props.onDragEvent(event);
+ break;
+ case "dragenter":
+ case "dragover":
+ case "drop":
+ if (this._allowDrop(event)) {
+ event.preventDefault();
+ this.props.onDragEvent(event, this.props.index);
+ }
+ break;
+ case "mousedown":
+ // Block the scroll wheel from appearing for middle clicks on search top sites
+ if (event.button === 1 && this.props.link.searchTopSite) {
+ event.preventDefault();
+ }
+ // Reset at the first mouse event of a potential drag
+ this.dragged = false;
+ break;
+ }
+ }
+
+ /**
+ * Helper to obtain the next state based on nextProps and prevState.
+ *
+ * NOTE: Rename this method to getDerivedStateFromProps when we update React
+ * to >= 16.3. We will need to update tests as well. We cannot rename this
+ * method to getDerivedStateFromProps now because there is a mismatch in
+ * the React version that we are using for both testing and production.
+ * (i.e. react-test-render => "16.3.2", react => "16.2.0").
+ *
+ * See https://github.com/airbnb/enzyme/blob/master/packages/enzyme-adapter-react-16/package.json#L43.
+ */
+ static getNextStateFromProps(nextProps, prevState) {
+ const { screenshot } = nextProps.link;
+ const imageInState = ScreenshotUtils.isRemoteImageLocal(
+ prevState.screenshotImage,
+ screenshot
+ );
+ if (imageInState) {
+ return null;
+ }
+
+ // Since image was updated, attempt to revoke old image blob URL, if it exists.
+ ScreenshotUtils.maybeRevokeBlobObjectURL(prevState.screenshotImage);
+
+ return {
+ screenshotImage: ScreenshotUtils.createLocalImageObject(screenshot),
+ };
+ }
+
+ // NOTE: Remove this function when we update React to >= 16.3 since React will
+ // call getDerivedStateFromProps automatically. We will also need to
+ // rename getNextStateFromProps to getDerivedStateFromProps.
+ componentWillMount() {
+ const nextState = TopSiteLink.getNextStateFromProps(this.props, this.state);
+ if (nextState) {
+ this.setState(nextState);
+ }
+ }
+
+ // NOTE: Remove this function when we update React to >= 16.3 since React will
+ // call getDerivedStateFromProps automatically. We will also need to
+ // rename getNextStateFromProps to getDerivedStateFromProps.
+ componentWillReceiveProps(nextProps) {
+ const nextState = TopSiteLink.getNextStateFromProps(nextProps, this.state);
+ if (nextState) {
+ this.setState(nextState);
+ }
+ }
+
+ componentWillUnmount() {
+ ScreenshotUtils.maybeRevokeBlobObjectURL(this.state.screenshotImage);
+ }
+
+ onKeyPress(event) {
+ // If we have tabbed to a search shortcut top site, and we click 'enter',
+ // we should execute the onClick function. This needs to be added because
+ // search top sites are anchor tags without an href. See bug 1483135
+ if (this.props.link.searchTopSite && event.key === "Enter") {
+ this.props.onClick(event);
+ }
+ }
+
+ /*
+ * Takes the url as a string, runs it through a simple (non-secure) hash turning it into a random number
+ * Apply that random number to the color array. The same url will always generate the same color.
+ */
+ generateColor() {
+ let { title, colors } = this.props;
+ if (!colors) {
+ return "";
+ }
+
+ let colorArray = colors.split(",");
+
+ const hashStr = str => {
+ let hash = 0;
+ for (let i = 0; i < str.length; i++) {
+ let charCode = str.charCodeAt(i);
+ hash += charCode;
+ }
+ return hash;
+ };
+
+ let hash = hashStr(title);
+ let index = hash % colorArray.length;
+ return colorArray[index];
+ }
+
+ calculateStyle() {
+ const { defaultStyle, link, newNewtabExperienceEnabled } = this.props;
+
+ const { tippyTopIcon, faviconSize } = link;
+ let imageClassName;
+ let imageStyle;
+ let showSmallFavicon = false;
+ let smallFaviconStyle;
+ let smallFaviconFallback;
+ let hasScreenshotImage =
+ this.state.screenshotImage && this.state.screenshotImage.url;
+ let selectedColor;
+
+ if (defaultStyle) {
+ // force no styles (letter fallback) even if the link has imagery
+ smallFaviconFallback = false;
+ if (newNewtabExperienceEnabled) {
+ selectedColor = this.generateColor();
+ }
+ } else if (link.searchTopSite) {
+ imageClassName = "top-site-icon rich-icon";
+ imageStyle = {
+ backgroundColor: link.backgroundColor,
+ backgroundImage: `url(${tippyTopIcon})`,
+ };
+ smallFaviconStyle = { backgroundImage: `url(${tippyTopIcon})` };
+ } else if (link.customScreenshotURL) {
+ // assume high quality custom screenshot and use rich icon styles and class names
+
+ // TopSite spoc experiment only
+ const spocImgURL =
+ link.type === SPOC_TYPE ? link.customScreenshotURL : "";
+
+ imageClassName = "top-site-icon rich-icon";
+ imageStyle = {
+ backgroundColor: link.backgroundColor,
+ backgroundImage: hasScreenshotImage
+ ? `url(${this.state.screenshotImage.url})`
+ : `url(${spocImgURL})`,
+ };
+ } else if (tippyTopIcon || faviconSize >= MIN_RICH_FAVICON_SIZE) {
+ // styles and class names for top sites with rich icons
+ imageClassName = "top-site-icon rich-icon";
+ imageStyle = {
+ backgroundColor: link.backgroundColor,
+ backgroundImage: `url(${tippyTopIcon || link.favicon})`,
+ };
+ } else {
+ // styles and class names for top sites with screenshot + small icon in top left corner
+ imageClassName = `screenshot${hasScreenshotImage ? " active" : ""}`;
+ imageStyle = {
+ backgroundImage: hasScreenshotImage
+ ? `url(${this.state.screenshotImage.url})`
+ : "none",
+ };
+ // only show a favicon in top left if it's greater than 16x16
+ if (faviconSize >= MIN_CORNER_FAVICON_SIZE) {
+ showSmallFavicon = true;
+ smallFaviconStyle = { backgroundImage: `url(${link.favicon})` };
+ } else if (newNewtabExperienceEnabled) {
+ selectedColor = this.generateColor();
+ imageClassName = "";
+ } else if (hasScreenshotImage) {
+ // Don't show a small favicon if there is no screenshot, because that
+ // would result in two fallback icons
+ showSmallFavicon = true;
+ smallFaviconFallback = true;
+ }
+ }
+
+ return {
+ showSmallFavicon,
+ smallFaviconFallback,
+ smallFaviconStyle,
+ imageStyle,
+ imageClassName,
+ selectedColor,
+ };
+ }
+
+ render() {
+ const {
+ children,
+ className,
+ isDraggable,
+ link,
+ onClick,
+ title,
+ newNewtabExperienceEnabled,
+ } = this.props;
+ const topSiteOuterClassName = `top-site-outer${
+ className ? ` ${className}` : ""
+ }${link.isDragged ? " dragged" : ""}${
+ link.searchTopSite ? " search-shortcut" : ""
+ }`;
+ const [letterFallback] = title;
+ const {
+ showSmallFavicon,
+ smallFaviconFallback,
+ smallFaviconStyle,
+ imageStyle,
+ imageClassName,
+ selectedColor,
+ } = this.calculateStyle();
+
+ let draggableProps = {};
+ if (isDraggable) {
+ draggableProps = {
+ onClick: this.onDragEvent,
+ onDragEnd: this.onDragEvent,
+ onDragStart: this.onDragEvent,
+ onMouseDown: this.onDragEvent,
+ };
+ }
+
+ return (
+ <li
+ className={topSiteOuterClassName}
+ onDrop={this.onDragEvent}
+ onDragOver={this.onDragEvent}
+ onDragEnter={this.onDragEvent}
+ onDragLeave={this.onDragEvent}
+ {...draggableProps}
+ >
+ <div className="top-site-inner">
+ {/* We don't yet support an accessible drag-and-drop implementation, see Bug 1552005 */}
+ {/* eslint-disable-next-line jsx-a11y/anchor-is-valid */}
+ <a
+ className="top-site-button"
+ href={link.searchTopSite ? undefined : link.url}
+ tabIndex="0"
+ onKeyPress={this.onKeyPress}
+ onClick={onClick}
+ draggable={true}
+ >
+ {(newNewtabExperienceEnabled && (
+ <div className="tile" aria-hidden={true}>
+ <div
+ className={
+ selectedColor
+ ? "icon-wrapper letter-fallback"
+ : "icon-wrapper"
+ }
+ data-fallback={letterFallback}
+ style={
+ selectedColor ? { backgroundColor: selectedColor } : {}
+ }
+ >
+ <div className={imageClassName} style={imageStyle} />
+ {showSmallFavicon && (
+ <div
+ className="top-site-icon default-icon"
+ data-fallback={smallFaviconFallback && letterFallback}
+ style={smallFaviconStyle}
+ />
+ )}
+ </div>
+ {link.searchTopSite && (
+ <div className="top-site-icon search-topsite" />
+ )}
+ </div>
+ )) || (
+ <div
+ className="tile"
+ aria-hidden={true}
+ data-fallback={letterFallback}
+ >
+ <div className={imageClassName} style={imageStyle} />
+ {link.searchTopSite && (
+ <div className="top-site-icon search-topsite" />
+ )}
+ {showSmallFavicon && (
+ <div
+ className="top-site-icon default-icon"
+ data-fallback={smallFaviconFallback && letterFallback}
+ style={smallFaviconStyle}
+ />
+ )}
+ </div>
+ )}
+ <div
+ className={`title${link.isPinned ? " has-icon pinned" : ""}${
+ link.type === SPOC_TYPE || link.sponsored_position
+ ? " sponsored"
+ : ""
+ }`}
+ >
+ {(newNewtabExperienceEnabled && (
+ <span dir="auto">
+ {link.isPinned && <div className="icon icon-pin-small" />}
+ {title || <br />}
+ <span
+ className="sponsored-label"
+ data-l10n-id="newtab-topsite-sponsored"
+ />
+ </span>
+ )) || (
+ <div>
+ {link.isPinned && <div className="icon icon-pin-small" />}
+ <span dir="auto">{title || <br />}</span>
+ <span
+ className="sponsored-label"
+ data-l10n-id="newtab-topsite-sponsored"
+ />
+ </div>
+ )}
+ </div>
+ </a>
+ {children}
+ {link.type === SPOC_TYPE ? (
+ <ImpressionStats
+ flightId={link.flightId}
+ rows={[
+ {
+ id: link.id,
+ pos: link.pos,
+ shim: link.shim && link.shim.impression,
+ },
+ ]}
+ dispatch={this.props.dispatch}
+ source={TOP_SITES_SOURCE}
+ />
+ ) : null}
+ </div>
+ </li>
+ );
+ }
+}
+TopSiteLink.defaultProps = {
+ title: "",
+ link: {},
+ isDraggable: true,
+};
+
+export class TopSite extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.state = { showContextMenu: false };
+ this.onLinkClick = this.onLinkClick.bind(this);
+ this.onMenuUpdate = this.onMenuUpdate.bind(this);
+ }
+
+ /**
+ * Report to telemetry additional information about the item.
+ */
+ _getTelemetryInfo() {
+ const value = { icon_type: this.props.link.iconType };
+ // Filter out "not_pinned" type for being the default
+ if (this.props.link.isPinned) {
+ value.card_type = "pinned";
+ }
+ if (this.props.link.searchTopSite) {
+ // Set the card_type as "search" regardless of its pinning status
+ value.card_type = "search";
+ value.search_vendor = this.props.link.hostname;
+ }
+ if (
+ this.props.link.type === SPOC_TYPE ||
+ this.props.link.sponsored_position
+ ) {
+ value.card_type = "spoc";
+ }
+ return { value };
+ }
+
+ userEvent(event) {
+ this.props.dispatch(
+ ac.UserEvent(
+ Object.assign(
+ {
+ event,
+ source: TOP_SITES_SOURCE,
+ action_position: this.props.index,
+ },
+ this._getTelemetryInfo()
+ )
+ )
+ );
+ }
+
+ onLinkClick(event) {
+ this.userEvent("CLICK");
+
+ // Specially handle a top site link click for "typed" frecency bonus as
+ // specified as a property on the link.
+ event.preventDefault();
+ const { altKey, button, ctrlKey, metaKey, shiftKey } = event;
+ if (!this.props.link.searchTopSite) {
+ this.props.dispatch(
+ ac.OnlyToMain({
+ type: at.OPEN_LINK,
+ data: Object.assign(this.props.link, {
+ event: { altKey, button, ctrlKey, metaKey, shiftKey },
+ }),
+ })
+ );
+
+ // Fire off a spoc specific impression.
+ if (this.props.link.type === SPOC_TYPE) {
+ this.props.dispatch(
+ ac.ImpressionStats({
+ source: TOP_SITES_SOURCE,
+ click: 0,
+ tiles: [
+ {
+ id: this.props.link.id,
+ pos: this.props.link.pos,
+ shim: this.props.link.shim && this.props.link.shim.click,
+ },
+ ],
+ })
+ );
+ }
+ if (this.props.link.sendAttributionRequest) {
+ this.props.dispatch(
+ ac.OnlyToMain({
+ type: at.PARTNER_LINK_ATTRIBUTION,
+ data: {
+ targetURL: this.props.link.url,
+ source: "newtab",
+ },
+ })
+ );
+ }
+ } else {
+ this.props.dispatch(
+ ac.OnlyToMain({
+ type: at.FILL_SEARCH_TERM,
+ data: { label: this.props.link.label },
+ })
+ );
+ }
+ }
+
+ onMenuUpdate(isOpen) {
+ if (isOpen) {
+ this.props.onActivate(this.props.index);
+ } else {
+ this.props.onActivate();
+ }
+ }
+
+ render() {
+ const { props } = this;
+ const { link } = props;
+ const isContextMenuOpen = props.activeIndex === props.index;
+ const title = link.label || link.hostname;
+ let menuOptions;
+ if (link.sponsored_position) {
+ menuOptions = TOP_SITES_SPONSORED_POSITION_CONTEXT_MENU_OPTIONS;
+ } else if (link.searchTopSite) {
+ menuOptions = TOP_SITES_SEARCH_SHORTCUTS_CONTEXT_MENU_OPTIONS;
+ } else if (link.type === SPOC_TYPE) {
+ menuOptions = TOP_SITES_SPOC_CONTEXT_MENU_OPTIONS;
+ } else {
+ menuOptions = TOP_SITES_CONTEXT_MENU_OPTIONS;
+ }
+
+ return (
+ <TopSiteLink
+ {...props}
+ onClick={this.onLinkClick}
+ onDragEvent={this.props.onDragEvent}
+ className={`${props.className || ""}${
+ isContextMenuOpen ? " active" : ""
+ }`}
+ title={title}
+ >
+ <div>
+ <ContextMenuButton
+ tooltip="newtab-menu-content-tooltip"
+ tooltipArgs={{ title }}
+ onUpdate={this.onMenuUpdate}
+ >
+ <LinkMenu
+ dispatch={props.dispatch}
+ index={props.index}
+ onUpdate={this.onMenuUpdate}
+ options={menuOptions}
+ site={link}
+ shouldSendImpressionStats={link.type === SPOC_TYPE}
+ siteInfo={this._getTelemetryInfo()}
+ source={TOP_SITES_SOURCE}
+ />
+ </ContextMenuButton>
+ </div>
+ </TopSiteLink>
+ );
+ }
+}
+TopSite.defaultProps = {
+ link: {},
+ onActivate() {},
+};
+
+export class TopSitePlaceholder extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onEditButtonClick = this.onEditButtonClick.bind(this);
+ }
+
+ onEditButtonClick() {
+ this.props.dispatch({
+ type: at.TOP_SITES_EDIT,
+ data: { index: this.props.index },
+ });
+ }
+
+ render() {
+ return (
+ <TopSiteLink
+ {...this.props}
+ className={`placeholder ${this.props.className || ""}`}
+ isDraggable={false}
+ >
+ <button
+ aria-haspopup="true"
+ className="context-menu-button edit-button icon"
+ data-l10n-id="newtab-menu-topsites-placeholder-tooltip"
+ onClick={this.onEditButtonClick}
+ />
+ </TopSiteLink>
+ );
+ }
+}
+
+export class TopSiteList extends React.PureComponent {
+ static get DEFAULT_STATE() {
+ return {
+ activeIndex: null,
+ draggedIndex: null,
+ draggedSite: null,
+ draggedTitle: null,
+ topSitesPreview: null,
+ };
+ }
+
+ constructor(props) {
+ super(props);
+ this.state = TopSiteList.DEFAULT_STATE;
+ this.onDragEvent = this.onDragEvent.bind(this);
+ this.onActivate = this.onActivate.bind(this);
+ }
+
+ componentWillReceiveProps(nextProps) {
+ if (this.state.draggedSite) {
+ const prevTopSites = this.props.TopSites && this.props.TopSites.rows;
+ const newTopSites = nextProps.TopSites && nextProps.TopSites.rows;
+ if (
+ prevTopSites &&
+ prevTopSites[this.state.draggedIndex] &&
+ prevTopSites[this.state.draggedIndex].url ===
+ this.state.draggedSite.url &&
+ (!newTopSites[this.state.draggedIndex] ||
+ newTopSites[this.state.draggedIndex].url !==
+ this.state.draggedSite.url)
+ ) {
+ // We got the new order from the redux store via props. We can clear state now.
+ this.setState(TopSiteList.DEFAULT_STATE);
+ }
+ }
+ }
+
+ userEvent(event, index) {
+ this.props.dispatch(
+ ac.UserEvent({
+ event,
+ source: TOP_SITES_SOURCE,
+ action_position: index,
+ })
+ );
+ }
+
+ onDragEvent(event, index, link, title) {
+ switch (event.type) {
+ case "dragstart":
+ this.dropped = false;
+ this.setState({
+ draggedIndex: index,
+ draggedSite: link,
+ draggedTitle: title,
+ activeIndex: null,
+ });
+ this.userEvent("DRAG", index);
+ break;
+ case "dragend":
+ if (!this.dropped) {
+ // If there was no drop event, reset the state to the default.
+ this.setState(TopSiteList.DEFAULT_STATE);
+ }
+ break;
+ case "dragenter":
+ if (index === this.state.draggedIndex) {
+ this.setState({ topSitesPreview: null });
+ } else {
+ this.setState({
+ topSitesPreview: this._makeTopSitesPreview(index),
+ });
+ }
+ break;
+ case "drop":
+ if (index !== this.state.draggedIndex) {
+ this.dropped = true;
+ this.props.dispatch(
+ ac.AlsoToMain({
+ type: at.TOP_SITES_INSERT,
+ data: {
+ site: {
+ url: this.state.draggedSite.url,
+ label: this.state.draggedTitle,
+ customScreenshotURL: this.state.draggedSite
+ .customScreenshotURL,
+ // Only if the search topsites experiment is enabled
+ ...(this.state.draggedSite.searchTopSite && {
+ searchTopSite: true,
+ }),
+ },
+ index,
+ draggedFromIndex: this.state.draggedIndex,
+ },
+ })
+ );
+ this.userEvent("DROP", index);
+ }
+ break;
+ }
+ }
+
+ _getTopSites() {
+ // Make a copy of the sites to truncate or extend to desired length
+ let topSites = this.props.TopSites.rows.slice();
+ topSites.length = this.props.TopSitesRows * TOP_SITES_MAX_SITES_PER_ROW;
+ return topSites;
+ }
+
+ /**
+ * Make a preview of the topsites that will be the result of dropping the currently
+ * dragged site at the specified index.
+ */
+ _makeTopSitesPreview(index) {
+ const topSites = this._getTopSites();
+ topSites[this.state.draggedIndex] = null;
+ const preview = topSites.map(site =>
+ site && (site.isPinned || site.sponsored_position) ? site : null
+ );
+ const unpinned = topSites.filter(
+ site => site && !site.isPinned && !site.sponsored_position
+ );
+ const siteToInsert = Object.assign({}, this.state.draggedSite, {
+ isPinned: true,
+ isDragged: true,
+ });
+
+ if (!preview[index]) {
+ preview[index] = siteToInsert;
+ } else {
+ // Find the hole to shift the pinned site(s) towards. We shift towards the
+ // hole left by the site being dragged.
+ let holeIndex = index;
+ const indexStep = index > this.state.draggedIndex ? -1 : 1;
+ while (preview[holeIndex]) {
+ holeIndex += indexStep;
+ }
+
+ // Shift towards the hole.
+ const shiftingStep = index > this.state.draggedIndex ? 1 : -1;
+ while (
+ index > this.state.draggedIndex ? holeIndex < index : holeIndex > index
+ ) {
+ let nextIndex = holeIndex + shiftingStep;
+ while (preview[nextIndex] && preview[nextIndex].sponsored_position) {
+ nextIndex += shiftingStep;
+ }
+ preview[holeIndex] = preview[nextIndex];
+ holeIndex = nextIndex;
+ }
+ preview[index] = siteToInsert;
+ }
+
+ // Fill in the remaining holes with unpinned sites.
+ for (let i = 0; i < preview.length; i++) {
+ if (!preview[i]) {
+ preview[i] = unpinned.shift() || null;
+ }
+ }
+
+ return preview;
+ }
+
+ onActivate(index) {
+ this.setState({ activeIndex: index });
+ }
+
+ render() {
+ const { props } = this;
+ const topSites = this.state.topSitesPreview || this._getTopSites();
+ const topSitesUI = [];
+ const commonProps = {
+ onDragEvent: this.onDragEvent,
+ dispatch: props.dispatch,
+ newNewtabExperienceEnabled: props.newNewtabExperienceEnabled,
+ };
+ // We assign a key to each placeholder slot. We need it to be independent
+ // of the slot index (i below) so that the keys used stay the same during
+ // drag and drop reordering and the underlying DOM nodes are reused.
+ // This mostly (only?) affects linux so be sure to test on linux before changing.
+ let holeIndex = 0;
+
+ // On narrow viewports, we only show 6 sites per row. We'll mark the rest as
+ // .hide-for-narrow to hide in CSS via @media query.
+ const maxNarrowVisibleIndex = props.TopSitesRows * 6;
+
+ for (let i = 0, l = topSites.length; i < l; i++) {
+ const link =
+ topSites[i] &&
+ Object.assign({}, topSites[i], {
+ iconType: this.props.topSiteIconType(topSites[i]),
+ });
+ const slotProps = {
+ key: link ? link.url : holeIndex++,
+ index: i,
+ };
+ if (i >= maxNarrowVisibleIndex) {
+ slotProps.className = "hide-for-narrow";
+ }
+ topSitesUI.push(
+ !link ? (
+ <TopSitePlaceholder {...slotProps} {...commonProps} />
+ ) : (
+ <TopSite
+ link={link}
+ activeIndex={this.state.activeIndex}
+ onActivate={this.onActivate}
+ {...slotProps}
+ {...commonProps}
+ colors={props.colors}
+ />
+ )
+ );
+ }
+ return (
+ <ul
+ className={`top-sites-list${
+ this.state.draggedSite ? " dnd-active" : ""
+ }`}
+ >
+ {topSitesUI}
+ </ul>
+ );
+ }
+}
diff --git a/browser/components/newtab/content-src/components/TopSites/TopSiteForm.jsx b/browser/components/newtab/content-src/components/TopSites/TopSiteForm.jsx
new file mode 100644
index 0000000000..258f749486
--- /dev/null
+++ b/browser/components/newtab/content-src/components/TopSites/TopSiteForm.jsx
@@ -0,0 +1,330 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { actionCreators as ac, actionTypes as at } from "common/Actions.jsm";
+import { A11yLinkButton } from "content-src/components/A11yLinkButton/A11yLinkButton";
+import React from "react";
+import { TOP_SITES_SOURCE } from "./TopSitesConstants";
+import { TopSiteFormInput } from "./TopSiteFormInput";
+import { TopSiteLink } from "./TopSite";
+
+export class TopSiteForm extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ const { site } = props;
+ this.state = {
+ label: site ? site.label || site.hostname : "",
+ url: site ? site.url : "",
+ validationError: false,
+ customScreenshotUrl: site ? site.customScreenshotURL : "",
+ showCustomScreenshotForm: site ? site.customScreenshotURL : false,
+ };
+ this.onClearScreenshotInput = this.onClearScreenshotInput.bind(this);
+ this.onLabelChange = this.onLabelChange.bind(this);
+ this.onUrlChange = this.onUrlChange.bind(this);
+ this.onCancelButtonClick = this.onCancelButtonClick.bind(this);
+ this.onClearUrlClick = this.onClearUrlClick.bind(this);
+ this.onDoneButtonClick = this.onDoneButtonClick.bind(this);
+ this.onCustomScreenshotUrlChange = this.onCustomScreenshotUrlChange.bind(
+ this
+ );
+ this.onPreviewButtonClick = this.onPreviewButtonClick.bind(this);
+ this.onEnableScreenshotUrlForm = this.onEnableScreenshotUrlForm.bind(this);
+ this.validateUrl = this.validateUrl.bind(this);
+ }
+
+ onLabelChange(event) {
+ this.setState({ label: event.target.value });
+ }
+
+ onUrlChange(event) {
+ this.setState({
+ url: event.target.value,
+ validationError: false,
+ });
+ }
+
+ onClearUrlClick() {
+ this.setState({
+ url: "",
+ validationError: false,
+ });
+ }
+
+ onEnableScreenshotUrlForm() {
+ this.setState({ showCustomScreenshotForm: true });
+ }
+
+ _updateCustomScreenshotInput(customScreenshotUrl) {
+ this.setState({
+ customScreenshotUrl,
+ validationError: false,
+ });
+ this.props.dispatch({ type: at.PREVIEW_REQUEST_CANCEL });
+ }
+
+ onCustomScreenshotUrlChange(event) {
+ this._updateCustomScreenshotInput(event.target.value);
+ }
+
+ onClearScreenshotInput() {
+ this._updateCustomScreenshotInput("");
+ }
+
+ onCancelButtonClick(ev) {
+ ev.preventDefault();
+ this.props.onClose();
+ }
+
+ onDoneButtonClick(ev) {
+ ev.preventDefault();
+
+ if (this.validateForm()) {
+ const site = { url: this.cleanUrl(this.state.url) };
+ const { index } = this.props;
+ if (this.state.label !== "") {
+ site.label = this.state.label;
+ }
+
+ if (this.state.customScreenshotUrl) {
+ site.customScreenshotURL = this.cleanUrl(
+ this.state.customScreenshotUrl
+ );
+ } else if (this.props.site && this.props.site.customScreenshotURL) {
+ // Used to flag that previously cached screenshot should be removed
+ site.customScreenshotURL = null;
+ }
+ this.props.dispatch(
+ ac.AlsoToMain({
+ type: at.TOP_SITES_PIN,
+ data: { site, index },
+ })
+ );
+ this.props.dispatch(
+ ac.UserEvent({
+ source: TOP_SITES_SOURCE,
+ event: "TOP_SITES_EDIT",
+ action_position: index,
+ })
+ );
+
+ this.props.onClose();
+ }
+ }
+
+ onPreviewButtonClick(event) {
+ event.preventDefault();
+ if (this.validateForm()) {
+ this.props.dispatch(
+ ac.AlsoToMain({
+ type: at.PREVIEW_REQUEST,
+ data: { url: this.cleanUrl(this.state.customScreenshotUrl) },
+ })
+ );
+ this.props.dispatch(
+ ac.UserEvent({
+ source: TOP_SITES_SOURCE,
+ event: "PREVIEW_REQUEST",
+ })
+ );
+ }
+ }
+
+ cleanUrl(url) {
+ // If we are missing a protocol, prepend http://
+ if (!url.startsWith("http:") && !url.startsWith("https:")) {
+ return `http://${url}`;
+ }
+ return url;
+ }
+
+ _tryParseUrl(url) {
+ try {
+ return new URL(url);
+ } catch (e) {
+ return null;
+ }
+ }
+
+ validateUrl(url) {
+ const validProtocols = ["http:", "https:"];
+ const urlObj =
+ this._tryParseUrl(url) || this._tryParseUrl(this.cleanUrl(url));
+
+ return urlObj && validProtocols.includes(urlObj.protocol);
+ }
+
+ validateCustomScreenshotUrl() {
+ const { customScreenshotUrl } = this.state;
+ return !customScreenshotUrl || this.validateUrl(customScreenshotUrl);
+ }
+
+ validateForm() {
+ const validate =
+ this.validateUrl(this.state.url) && this.validateCustomScreenshotUrl();
+
+ if (!validate) {
+ this.setState({ validationError: true });
+ }
+
+ return validate;
+ }
+
+ _renderCustomScreenshotInput() {
+ const { customScreenshotUrl } = this.state;
+ const requestFailed = this.props.previewResponse === "";
+ const validationError =
+ (this.state.validationError && !this.validateCustomScreenshotUrl()) ||
+ requestFailed;
+ // Set focus on error if the url field is valid or when the input is first rendered and is empty
+ const shouldFocus =
+ (validationError && this.validateUrl(this.state.url)) ||
+ !customScreenshotUrl;
+ const isLoading =
+ this.props.previewResponse === null &&
+ customScreenshotUrl &&
+ this.props.previewUrl === this.cleanUrl(customScreenshotUrl);
+
+ if (!this.state.showCustomScreenshotForm) {
+ return (
+ <A11yLinkButton
+ onClick={this.onEnableScreenshotUrlForm}
+ className="enable-custom-image-input"
+ data-l10n-id="newtab-topsites-use-image-link"
+ />
+ );
+ }
+ return (
+ <div className="custom-image-input-container">
+ <TopSiteFormInput
+ errorMessageId={
+ requestFailed
+ ? "newtab-topsites-image-validation"
+ : "newtab-topsites-url-validation"
+ }
+ loading={isLoading}
+ onChange={this.onCustomScreenshotUrlChange}
+ onClear={this.onClearScreenshotInput}
+ shouldFocus={shouldFocus}
+ typeUrl={true}
+ value={customScreenshotUrl}
+ validationError={validationError}
+ titleId="newtab-topsites-image-url-label"
+ placeholderId="newtab-topsites-url-input"
+ />
+ </div>
+ );
+ }
+
+ render() {
+ const { customScreenshotUrl } = this.state;
+ const requestFailed = this.props.previewResponse === "";
+ // For UI purposes, editing without an existing link is "add"
+ const showAsAdd = !this.props.site;
+ const previous =
+ (this.props.site && this.props.site.customScreenshotURL) || "";
+ const changed =
+ customScreenshotUrl && this.cleanUrl(customScreenshotUrl) !== previous;
+ // Preview mode if changes were made to the custom screenshot URL and no preview was received yet
+ // or the request failed
+ const previewMode = changed && !this.props.previewResponse;
+ const previewLink = Object.assign({}, this.props.site);
+ if (this.props.previewResponse) {
+ previewLink.screenshot = this.props.previewResponse;
+ previewLink.customScreenshotURL = this.props.previewUrl;
+ }
+ // Handles the form submit so an enter press performs the correct action
+ const onSubmit = previewMode
+ ? this.onPreviewButtonClick
+ : this.onDoneButtonClick;
+
+ // When the newNewtabExperience is enabled by default, use only shortcut ids.
+ const addTopsitesHeaderL10nId =
+ this.props.newNewtabExperienceEnabled ||
+ this.props.customizationMenuEnabled
+ ? "newtab-topsites-add-shortcut-header"
+ : "newtab-topsites-add-topsites-header";
+ const editTopsitesHeaderL10nId =
+ this.props.newNewtabExperienceEnabled ||
+ this.props.customizationMenuEnabled
+ ? "newtab-topsites-edit-shortcut-header"
+ : "newtab-topsites-edit-topsites-header";
+ return (
+ <form className="topsite-form" onSubmit={onSubmit}>
+ <div className="form-input-container">
+ <h3
+ className="section-title grey-title"
+ data-l10n-id={
+ showAsAdd ? addTopsitesHeaderL10nId : editTopsitesHeaderL10nId
+ }
+ />
+ <div className="fields-and-preview">
+ <div className="form-wrapper">
+ <TopSiteFormInput
+ onChange={this.onLabelChange}
+ value={this.state.label}
+ titleId="newtab-topsites-title-label"
+ placeholderId="newtab-topsites-title-input"
+ />
+ <TopSiteFormInput
+ onChange={this.onUrlChange}
+ shouldFocus={
+ this.state.validationError &&
+ !this.validateUrl(this.state.url)
+ }
+ value={this.state.url}
+ onClear={this.onClearUrlClick}
+ validationError={
+ this.state.validationError &&
+ !this.validateUrl(this.state.url)
+ }
+ titleId="newtab-topsites-url-label"
+ typeUrl={true}
+ placeholderId="newtab-topsites-url-input"
+ errorMessageId="newtab-topsites-url-validation"
+ />
+ {this._renderCustomScreenshotInput()}
+ </div>
+ <TopSiteLink
+ link={previewLink}
+ defaultStyle={requestFailed}
+ title={this.state.label}
+ newNewtabExperienceEnabled={this.props.newNewtabExperienceEnabled}
+ />
+ </div>
+ </div>
+ <section className="actions">
+ <button
+ className="cancel"
+ type="button"
+ onClick={this.onCancelButtonClick}
+ data-l10n-id="newtab-topsites-cancel-button"
+ />
+ {previewMode ? (
+ <button
+ className="done preview"
+ type="submit"
+ data-l10n-id="newtab-topsites-preview-button"
+ />
+ ) : (
+ <button
+ className="done"
+ type="submit"
+ data-l10n-id={
+ showAsAdd
+ ? "newtab-topsites-add-button"
+ : "newtab-topsites-save-button"
+ }
+ />
+ )}
+ </section>
+ </form>
+ );
+ }
+}
+
+TopSiteForm.defaultProps = {
+ site: null,
+ index: -1,
+};
diff --git a/browser/components/newtab/content-src/components/TopSites/TopSiteFormInput.jsx b/browser/components/newtab/content-src/components/TopSites/TopSiteFormInput.jsx
new file mode 100644
index 0000000000..6ec0271122
--- /dev/null
+++ b/browser/components/newtab/content-src/components/TopSites/TopSiteFormInput.jsx
@@ -0,0 +1,111 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import React from "react";
+
+export class TopSiteFormInput extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.state = { validationError: this.props.validationError };
+ this.onChange = this.onChange.bind(this);
+ this.onMount = this.onMount.bind(this);
+ this.onClearIconPress = this.onClearIconPress.bind(this);
+ }
+
+ componentWillReceiveProps(nextProps) {
+ if (nextProps.shouldFocus && !this.props.shouldFocus) {
+ this.input.focus();
+ }
+ if (nextProps.validationError && !this.props.validationError) {
+ this.setState({ validationError: true });
+ }
+ // If the component is in an error state but the value was cleared by the parent
+ if (this.state.validationError && !nextProps.value) {
+ this.setState({ validationError: false });
+ }
+ }
+
+ onClearIconPress(event) {
+ // If there is input in the URL or custom image URL fields,
+ // and we hit 'enter' while tabbed over the clear icon,
+ // we should execute the function to clear the field.
+ if (event.key === "Enter") {
+ this.props.onClear();
+ }
+ }
+
+ onChange(ev) {
+ if (this.state.validationError) {
+ this.setState({ validationError: false });
+ }
+ this.props.onChange(ev);
+ }
+
+ onMount(input) {
+ this.input = input;
+ }
+
+ renderLoadingOrCloseButton() {
+ const showClearButton = this.props.value && this.props.onClear;
+
+ if (this.props.loading) {
+ return (
+ <div className="loading-container">
+ <div className="loading-animation" />
+ </div>
+ );
+ } else if (showClearButton) {
+ return (
+ <button
+ type="button"
+ className="icon icon-clear-input icon-button-style"
+ onClick={this.props.onClear}
+ onKeyPress={this.onClearIconPress}
+ />
+ );
+ }
+ return null;
+ }
+
+ render() {
+ const { typeUrl } = this.props;
+ const { validationError } = this.state;
+
+ return (
+ <label>
+ <span data-l10n-id={this.props.titleId} />
+ <div
+ className={`field ${typeUrl ? "url" : ""}${
+ validationError ? " invalid" : ""
+ }`}
+ >
+ <input
+ type="text"
+ value={this.props.value}
+ ref={this.onMount}
+ onChange={this.onChange}
+ data-l10n-id={this.props.placeholderId}
+ // Set focus on error if the url field is valid or when the input is first rendered and is empty
+ // eslint-disable-next-line jsx-a11y/no-autofocus
+ autoFocus={this.props.shouldFocus}
+ disabled={this.props.loading}
+ />
+ {this.renderLoadingOrCloseButton()}
+ {validationError && (
+ <aside
+ className="error-tooltip"
+ data-l10n-id={this.props.errorMessageId}
+ />
+ )}
+ </div>
+ </label>
+ );
+ }
+}
+
+TopSiteFormInput.defaultProps = {
+ showClearButton: false,
+ value: "",
+ validationError: false,
+};
diff --git a/browser/components/newtab/content-src/components/TopSites/TopSites.jsx b/browser/components/newtab/content-src/components/TopSites/TopSites.jsx
new file mode 100644
index 0000000000..2c9419cb42
--- /dev/null
+++ b/browser/components/newtab/content-src/components/TopSites/TopSites.jsx
@@ -0,0 +1,241 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { actionCreators as ac, actionTypes as at } from "common/Actions.jsm";
+import {
+ MIN_CORNER_FAVICON_SIZE,
+ MIN_RICH_FAVICON_SIZE,
+ TOP_SITES_SOURCE,
+} from "./TopSitesConstants";
+import { CollapsibleSection } from "content-src/components/CollapsibleSection/CollapsibleSection";
+import { ComponentPerfTimer } from "content-src/components/ComponentPerfTimer/ComponentPerfTimer";
+import { connect } from "react-redux";
+import { ModalOverlayWrapper } from "../../asrouter/components/ModalOverlay/ModalOverlay";
+import React from "react";
+import { SearchShortcutsForm } from "./SearchShortcutsForm";
+import { TOP_SITES_MAX_SITES_PER_ROW } from "common/Reducers.jsm";
+import { TopSiteForm } from "./TopSiteForm";
+import { TopSiteList } from "./TopSite";
+
+function topSiteIconType(link) {
+ if (link.customScreenshotURL) {
+ return "custom_screenshot";
+ }
+ if (link.tippyTopIcon || link.faviconRef === "tippytop") {
+ return "tippytop";
+ }
+ if (link.faviconSize >= MIN_RICH_FAVICON_SIZE) {
+ return "rich_icon";
+ }
+ if (link.screenshot && link.faviconSize >= MIN_CORNER_FAVICON_SIZE) {
+ return "screenshot_with_icon";
+ }
+ if (link.screenshot) {
+ return "screenshot";
+ }
+ return "no_image";
+}
+
+/**
+ * Iterates through TopSites and counts types of images.
+ * @param acc Accumulator for reducer.
+ * @param topsite Entry in TopSites.
+ */
+function countTopSitesIconsTypes(topSites) {
+ const countTopSitesTypes = (acc, link) => {
+ acc[topSiteIconType(link)]++;
+ return acc;
+ };
+
+ return topSites.reduce(countTopSitesTypes, {
+ custom_screenshot: 0,
+ screenshot_with_icon: 0,
+ screenshot: 0,
+ tippytop: 0,
+ rich_icon: 0,
+ no_image: 0,
+ });
+}
+
+export class _TopSites extends React.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onEditFormClose = this.onEditFormClose.bind(this);
+ this.onSearchShortcutsFormClose = this.onSearchShortcutsFormClose.bind(
+ this
+ );
+ }
+
+ /**
+ * Dispatch session statistics about the quality of TopSites icons and pinned count.
+ */
+ _dispatchTopSitesStats() {
+ const topSites = this._getVisibleTopSites().filter(
+ topSite => topSite !== null && topSite !== undefined
+ );
+ const topSitesIconsStats = countTopSitesIconsTypes(topSites);
+ const topSitesPinned = topSites.filter(site => !!site.isPinned).length;
+ const searchShortcuts = topSites.filter(site => !!site.searchTopSite)
+ .length;
+ // Dispatch telemetry event with the count of TopSites images types.
+ this.props.dispatch(
+ ac.AlsoToMain({
+ type: at.SAVE_SESSION_PERF_DATA,
+ data: {
+ topsites_icon_stats: topSitesIconsStats,
+ topsites_pinned: topSitesPinned,
+ topsites_search_shortcuts: searchShortcuts,
+ },
+ })
+ );
+ }
+
+ /**
+ * Return the TopSites that are visible based on prefs and window width.
+ */
+ _getVisibleTopSites() {
+ // We hide 2 sites per row when not in the wide layout.
+ let sitesPerRow = TOP_SITES_MAX_SITES_PER_ROW;
+ // $break-point-widest = 1072px (from _variables.scss)
+ if (!global.matchMedia(`(min-width: 1072px)`).matches) {
+ sitesPerRow -= 2;
+ }
+ return this.props.TopSites.rows.slice(
+ 0,
+ this.props.TopSitesRows * sitesPerRow
+ );
+ }
+
+ componentDidUpdate() {
+ this._dispatchTopSitesStats();
+ }
+
+ componentDidMount() {
+ this._dispatchTopSitesStats();
+ }
+
+ onEditFormClose() {
+ this.props.dispatch(
+ ac.UserEvent({
+ source: TOP_SITES_SOURCE,
+ event: "TOP_SITES_EDIT_CLOSE",
+ })
+ );
+ this.props.dispatch({ type: at.TOP_SITES_CANCEL_EDIT });
+ }
+
+ onSearchShortcutsFormClose() {
+ this.props.dispatch(
+ ac.UserEvent({
+ source: TOP_SITES_SOURCE,
+ event: "SEARCH_EDIT_CLOSE",
+ })
+ );
+ this.props.dispatch({ type: at.TOP_SITES_CLOSE_SEARCH_SHORTCUTS_MODAL });
+ }
+
+ render() {
+ const { props } = this;
+ const { editForm, showSearchShortcutsForm } = props.TopSites;
+ const extraMenuOptions = ["AddTopSite"];
+ const newNewtabExperienceEnabled =
+ props.Prefs.values["newNewtabExperience.enabled"];
+ const customizationMenuEnabled =
+ props.Prefs.values["customizationMenu.enabled"];
+ const colors = props.Prefs.values["newNewtabExperience.colors"];
+
+ if (props.Prefs.values["improvesearch.topSiteSearchShortcuts"]) {
+ extraMenuOptions.push("AddSearchShortcut");
+ }
+
+ const canShowCustomizationMenu =
+ newNewtabExperienceEnabled || customizationMenuEnabled;
+ const hideTitle =
+ props.Prefs.values.hideTopSitesTitle || canShowCustomizationMenu;
+
+ // `collapsed` should be sent to CollapsibleSection as undefined if
+ // `props.TopSites.pref` is not set to true.
+ let collapsed;
+ if (props.TopSites.pref) {
+ collapsed = canShowCustomizationMenu
+ ? false
+ : props.TopSites.pref.collapsed;
+ }
+
+ return (
+ <ComponentPerfTimer
+ id="topsites"
+ initialized={props.TopSites.initialized}
+ dispatch={props.dispatch}
+ >
+ <CollapsibleSection
+ className="top-sites"
+ icon="topsites"
+ id="topsites"
+ title={props.title || { id: "newtab-section-header-topsites" }}
+ hideTitle={hideTitle}
+ extraMenuOptions={extraMenuOptions}
+ showPrefName="feeds.topsites"
+ eventSource={TOP_SITES_SOURCE}
+ collapsed={collapsed}
+ isFixed={props.isFixed}
+ isFirst={props.isFirst}
+ isLast={props.isLast}
+ dispatch={props.dispatch}
+ >
+ <TopSiteList
+ TopSites={props.TopSites}
+ TopSitesRows={props.TopSitesRows}
+ dispatch={props.dispatch}
+ topSiteIconType={topSiteIconType}
+ newNewtabExperienceEnabled={newNewtabExperienceEnabled}
+ colors={colors}
+ />
+ <div className="edit-topsites-wrapper">
+ {editForm && (
+ <div className="edit-topsites">
+ <ModalOverlayWrapper
+ unstyled={true}
+ onClose={this.onEditFormClose}
+ innerClassName="modal"
+ >
+ <TopSiteForm
+ site={props.TopSites.rows[editForm.index]}
+ onClose={this.onEditFormClose}
+ dispatch={this.props.dispatch}
+ {...editForm}
+ newNewtabExperienceEnabled={newNewtabExperienceEnabled}
+ customizationMenuEnabled={customizationMenuEnabled}
+ />
+ </ModalOverlayWrapper>
+ </div>
+ )}
+ {showSearchShortcutsForm && (
+ <div className="edit-search-shortcuts">
+ <ModalOverlayWrapper
+ unstyled={true}
+ onClose={this.onSearchShortcutsFormClose}
+ innerClassName="modal"
+ >
+ <SearchShortcutsForm
+ TopSites={props.TopSites}
+ onClose={this.onSearchShortcutsFormClose}
+ dispatch={this.props.dispatch}
+ />
+ </ModalOverlayWrapper>
+ </div>
+ )}
+ </div>
+ </CollapsibleSection>
+ </ComponentPerfTimer>
+ );
+ }
+}
+
+export const TopSites = connect((state, props) => ({
+ // For SPOC Experiment only, take TopSites from DiscoveryStream TopSites that takes in SPOC Data
+ TopSites: props.TopSitesWithSpoc || state.TopSites,
+ Prefs: state.Prefs,
+ TopSitesRows: state.Prefs.values.topSitesRows,
+}))(_TopSites);
diff --git a/browser/components/newtab/content-src/components/TopSites/TopSitesConstants.js b/browser/components/newtab/content-src/components/TopSites/TopSitesConstants.js
new file mode 100644
index 0000000000..7058557d88
--- /dev/null
+++ b/browser/components/newtab/content-src/components/TopSites/TopSitesConstants.js
@@ -0,0 +1,43 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+export const TOP_SITES_SOURCE = "TOP_SITES";
+export const TOP_SITES_CONTEXT_MENU_OPTIONS = [
+ "CheckPinTopSite",
+ "EditTopSite",
+ "Separator",
+ "OpenInNewWindow",
+ "OpenInPrivateWindow",
+ "Separator",
+ "BlockUrl",
+ "DeleteUrl",
+];
+export const TOP_SITES_SPOC_CONTEXT_MENU_OPTIONS = [
+ "PinTopSite",
+ "Separator",
+ "OpenInNewWindow",
+ "OpenInPrivateWindow",
+ "Separator",
+ "BlockUrl",
+ "ShowPrivacyInfo",
+];
+export const TOP_SITES_SPONSORED_POSITION_CONTEXT_MENU_OPTIONS = [
+ "PinTopSite",
+ "Separator",
+ "OpenInNewWindow",
+ "OpenInPrivateWindow",
+ "Separator",
+ "BlockUrl",
+ "AboutSponsored",
+];
+// the special top site for search shortcut experiment can only have the option to unpin (which removes) the topsite
+export const TOP_SITES_SEARCH_SHORTCUTS_CONTEXT_MENU_OPTIONS = [
+ "CheckPinTopSite",
+ "Separator",
+ "BlockUrl",
+];
+// minimum size necessary to show a rich icon instead of a screenshot
+export const MIN_RICH_FAVICON_SIZE = 96;
+// minimum size necessary to show any icon in the top left corner with a screenshot
+export const MIN_CORNER_FAVICON_SIZE = 16;
diff --git a/browser/components/newtab/content-src/components/TopSites/_TopSites.scss b/browser/components/newtab/content-src/components/TopSites/_TopSites.scss
new file mode 100644
index 0000000000..b4b2615613
--- /dev/null
+++ b/browser/components/newtab/content-src/components/TopSites/_TopSites.scss
@@ -0,0 +1,803 @@
+$top-sites-size: $grid-unit;
+$top-sites-size-nte: $grid-unit-small;
+$top-sites-border-radius: 4px;
+$nt-experience-top-sites-border-radius: 8px;
+$top-sites-vertical-space: 8px;
+$screenshot-size: cover;
+$rich-icon-size: 96px;
+$default-icon-wrapper-size: 42px;
+$nt-experience-default-icon-wrapper-size: 32px;
+$search-icon-wrapper-size: 42px;
+$default-icon-size: 32px;
+$default-icon-offset: 6px;
+$half-base-gutter: $base-gutter / 2;
+$hover-transition-duration: 150ms;
+$letter-fallback-color: $white;
+
+.top-sites-list {
+ list-style: none;
+ margin: 0 (-$half-base-gutter);
+ padding: 0;
+
+ // Two columns
+ @media (max-width: $break-point-medium) {
+ > :nth-child(2n+1) {
+ @include context-menu-open-middle;
+ }
+
+ > :nth-child(2n) {
+ @include context-menu-open-left;
+ }
+ }
+
+ // Four columns
+ @media (min-width: $break-point-medium) and (max-width: $break-point-large) {
+ :nth-child(4n) {
+ @include context-menu-open-left;
+ }
+ }
+ @media (min-width: $break-point-medium) and (max-width: $break-point-medium + $card-width) {
+ :nth-child(4n+3) {
+ @include context-menu-open-left;
+ }
+ }
+
+ // Six columns
+ @media (min-width: $break-point-large) and (max-width: $break-point-large + 2 * $card-width) {
+ :nth-child(6n) {
+ @include context-menu-open-left;
+ }
+ }
+ @media (min-width: $break-point-large) and (max-width: $break-point-large + $card-width) {
+ :nth-child(6n+5) {
+ @include context-menu-open-left;
+ }
+ }
+
+ // Eight columns
+ @media (min-width: $break-point-widest) and (max-width: $break-point-widest + 2 * $card-width) {
+ :nth-child(8n) {
+ @include context-menu-open-left;
+ }
+ }
+ @media (min-width: $break-point-widest) and (max-width: $break-point-widest + $card-width) {
+ :nth-child(8n+7) {
+ @include context-menu-open-left;
+ }
+ }
+
+ .hide-for-narrow {
+ display: none;
+ }
+
+ @media (min-width: $break-point-medium) {
+ .hide-for-narrow {
+ display: inline-block;
+ }
+ }
+
+ @media (min-width: $break-point-large) {
+ .hide-for-narrow {
+ display: none;
+ }
+ }
+
+ @media (min-width: $break-point-widest) {
+ .hide-for-narrow {
+ display: inline-block;
+ }
+ }
+}
+
+// container for drop zone
+.top-site-outer {
+ padding: 0 $half-base-gutter;
+ display: inline-block;
+
+ // container for context menu
+ .top-site-inner {
+ position: relative;
+
+ > a {
+ color: inherit;
+ display: block;
+ outline: none;
+ }
+ }
+
+ .tile { // sass-lint:disable-block property-sort-order
+ border-radius: $top-sites-border-radius;
+ box-shadow: inset $inner-box-shadow, var(--newtab-card-shadow);
+ cursor: pointer;
+ position: relative;
+
+ // For letter fallback
+ align-items: center;
+ color: var(--newtab-text-secondary-color);
+ display: flex;
+ font-size: 32px;
+ font-weight: 200;
+ justify-content: center;
+ text-transform: uppercase; // sass-lint:disable-line no-disallowed-properties
+
+ .icon-wrapper {
+ border-radius: 4px;
+ width: 48px;
+ height: 48px;
+ overflow: hidden;
+ position: relative;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+
+ &.letter-fallback::before {
+ content: attr(data-fallback);
+ text-transform: uppercase; // sass-lint:disable-line no-disallowed-properties
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ font-size: 64px;
+ font-weight: 800;
+ transform: rotate(-10deg);
+ top: 6px;
+ position: relative;
+ color: $letter-fallback-color;
+ }
+ }
+ }
+
+ // Some common styles for all icons (rich and default) in top sites
+ .top-site-icon {
+ background-color: var(--newtab-topsites-background-color);
+ background-position: center center;
+ background-repeat: no-repeat;
+ border-radius: $top-sites-border-radius;
+ position: absolute;
+ }
+
+ .rich-icon {
+ background-size: cover;
+ height: 100%;
+ inset-inline-start: 0;
+ top: 0;
+ width: 100%;
+ }
+
+ .default-icon,
+ .search-topsite {
+ background-size: $default-icon-size;
+ height: $default-icon-wrapper-size;
+ width: $default-icon-wrapper-size;
+
+ // for corner letter fallback
+ align-items: center;
+ display: flex;
+ font-size: 20px;
+ justify-content: center;
+
+ &[data-fallback]::before {
+ content: attr(data-fallback);
+ }
+ }
+
+ .search-topsite {
+ background-image: url('#{$image-path}glyph-search-16.svg');
+ background-size: 26px;
+ background-color: $blue-60;
+ border-radius: $default-icon-wrapper-size;
+ -moz-context-properties: fill;
+ fill: $white;
+ box-shadow: var(--newtab-card-shadow);
+ transition-duration: $hover-transition-duration;
+ transition-property: background-size, bottom, inset-inline-end, height, width;
+ height: $search-icon-wrapper-size;
+ width: $search-icon-wrapper-size;
+ bottom: -$default-icon-offset;
+ inset-inline-end: -$default-icon-offset;
+ }
+
+ .title {
+ color: var(--newtab-topsites-label-color);
+ font: message-box;
+ padding-top: 4px;
+ text-align: center;
+ position: relative;
+
+ .icon {
+ fill: var(--newtab-icon-tertiary-color);
+ }
+
+ span {
+ display: block;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+
+ .sponsored-label {
+ color: $grey-50;
+ font-size: 0.9em;
+ }
+
+ &:not(.sponsored) .sponsored-label {
+ visibility: hidden;
+ }
+ }
+
+ // We want all search shortcuts to have a white background in case they have transparency.
+ &.search-shortcut {
+ .rich-icon {
+ background-color: $white;
+ }
+ }
+
+ .edit-button {
+ background-image: url('#{$image-path}glyph-edit-16.svg');
+ }
+
+ &.placeholder {
+ .screenshot {
+ display: none;
+ }
+ }
+
+ &.dragged {
+ .tile {
+ background: $grey-20;
+ box-shadow: none;
+
+ *,
+ &::before {
+ display: none;
+ }
+ }
+
+ .title {
+ visibility: hidden;
+ }
+ }
+}
+
+.edit-topsites-wrapper {
+ .modal {
+ box-shadow: $shadow-secondary;
+ left: 0;
+ margin: 0 auto;
+ max-height: calc(100% - 40px);
+ position: fixed;
+ right: 0;
+ top: 40px;
+ width: $wrapper-default-width;
+
+ @media (min-width: $break-point-medium) {
+ width: $wrapper-max-width-medium;
+ }
+
+ @media (min-width: $break-point-large) {
+ width: $wrapper-max-width-large;
+ }
+ }
+}
+
+.topsite-form {
+ $form-width: 300px;
+ $form-spacing: 32px;
+
+ .section-title {
+ font-size: 16px;
+ margin: 0 0 16px;
+ }
+
+ .form-input-container {
+ max-width: $form-width + 3 * $form-spacing + $rich-icon-size;
+ margin: 0 auto;
+ padding: $form-spacing;
+
+ .top-site-outer {
+ pointer-events: none;
+ }
+ }
+
+ .search-shortcuts-container {
+ max-width: 700px;
+ margin: 0 auto;
+ padding: $form-spacing;
+
+ > div {
+ margin-inline-end: -39px;
+ }
+
+ .top-site-outer {
+ margin-inline-start: 0;
+ margin-inline-end: 39px;
+ }
+ }
+
+ .top-site-outer {
+ padding: 0;
+ margin: 24px 0 0;
+ margin-inline-start: $form-spacing;
+ }
+
+ .fields-and-preview {
+ display: flex;
+ }
+
+ label {
+ font-size: $section-title-font-size;
+ }
+
+ .form-wrapper {
+ width: 100%;
+
+ .field {
+ position: relative;
+
+ .icon-clear-input {
+ position: absolute;
+ transform: translateY(-50%);
+ top: 50%;
+ inset-inline-end: 8px;
+ }
+ }
+
+ .url {
+ input:dir(ltr) {
+ padding-right: 32px;
+ }
+
+ input:dir(rtl) {
+ padding-left: 32px;
+
+ &:not(:placeholder-shown) {
+ direction: ltr;
+ text-align: right;
+ }
+ }
+ }
+
+ .enable-custom-image-input {
+ display: inline-block;
+ font-size: 13px;
+ margin-top: 4px;
+ cursor: pointer;
+ }
+
+ .custom-image-input-container {
+ margin-top: 4px;
+
+ .loading-container {
+ width: 16px;
+ height: 16px;
+ overflow: hidden;
+ position: absolute;
+ transform: translateY(-50%);
+ top: 50%;
+ inset-inline-end: 8px;
+ }
+
+ // This animation is derived from Firefox's tab loading animation
+ // See https://searchfox.org/mozilla-central/rev/b29daa46443b30612415c35be0a3c9c13b9dc5f6/browser/themes/shared/tabs.inc.css#208-216
+ .loading-animation {
+ @keyframes tab-throbber-animation {
+ 100% { transform: translateX(-960px); }
+ }
+
+ @keyframes tab-throbber-animation-rtl {
+ 100% { transform: translateX(960px); }
+ }
+
+ width: 960px;
+ height: 16px;
+ -moz-context-properties: fill;
+ fill: $blue-50;
+ background-image: url('chrome://browser/skin/tabbrowser/loading.svg');
+ animation: tab-throbber-animation 1.05s steps(60) infinite;
+
+ &:dir(rtl) {
+ animation-name: tab-throbber-animation-rtl;
+ }
+ }
+ }
+
+ input {
+ &[type='text'] {
+ background-color: var(--newtab-textbox-background-color);
+ border: $input-border;
+ margin: 8px 0;
+ padding: 0 8px;
+ height: 32px;
+ width: 100%;
+ font-size: 15px;
+
+ &[disabled] {
+ border: $input-border;
+ box-shadow: none;
+ opacity: 0.4;
+ }
+ }
+ }
+
+ .invalid {
+ input {
+ &[type='text'] {
+ border: $input-error-border;
+ box-shadow: $input-error-boxshadow;
+ }
+ }
+ }
+
+ .error-tooltip {
+ animation: fade-up-tt 450ms;
+ background: $red-60;
+ border-radius: 2px;
+ color: $white;
+ inset-inline-start: 3px;
+ padding: 5px 12px;
+ position: absolute;
+ top: 44px;
+ z-index: 1;
+
+ // tooltip caret
+ &::before {
+ background: $red-60;
+ bottom: -8px;
+ content: '.';
+ height: 16px;
+ inset-inline-start: 12px;
+ position: absolute;
+ text-indent: -999px;
+ top: -7px;
+ transform: rotate(45deg);
+ white-space: nowrap;
+ width: 16px;
+ z-index: -1;
+ }
+ }
+ }
+
+ .actions {
+ justify-content: flex-end;
+
+ button {
+ margin-inline-start: 10px;
+ margin-inline-end: 0;
+ }
+ }
+
+ @media (max-width: $break-point-medium) {
+ .fields-and-preview {
+ flex-direction: column;
+
+ .top-site-outer {
+ margin-inline-start: 0;
+ }
+ }
+ }
+
+ // prevent text selection of keyword label when clicking to select
+ .title {
+ user-select: none;
+ }
+
+ // CSS styled checkbox
+ [type='checkbox']:not(:checked),
+ [type='checkbox']:checked {
+ inset-inline-start: -9999px;
+ position: absolute;
+ }
+
+ [type='checkbox']:not(:checked) + label,
+ [type='checkbox']:checked + label {
+ cursor: pointer;
+ display: block;
+ position: relative;
+ }
+
+ $checkbox-offset: -8px;
+
+ [type='checkbox']:not(:checked) + label::before,
+ [type='checkbox']:checked + label::before {
+ background: var(--newtab-background-color);
+ border: $input-border;
+ border-radius: $border-radius;
+ content: '';
+ height: 21px;
+ left: $checkbox-offset;
+ position: absolute;
+ top: $checkbox-offset;
+ width: 21px;
+ z-index: 1;
+
+ [dir='rtl'] & {
+ left: auto;
+ right: $checkbox-offset;
+ }
+ }
+
+ // checkmark
+ [type='checkbox']:not(:checked) + label::after,
+ [type='checkbox']:checked + label::after {
+ background: url('chrome://global/skin/icons/check.svg') no-repeat center center; // sass-lint:disable-line no-url-domains
+ content: '';
+ height: 21px;
+ left: $checkbox-offset;
+ position: absolute;
+ top: $checkbox-offset;
+ width: 21px;
+ -moz-context-properties: fill;
+ fill: var(--newtab-link-primary-color);
+ z-index: 2;
+
+ [dir='rtl'] & {
+ left: auto;
+ right: $checkbox-offset;
+ }
+ }
+
+ // when selected, highlight the tile
+ [type='checkbox']:checked + label {
+ .tile {
+ box-shadow: 0 0 0 2px var(--newtab-link-primary-color);
+ }
+ }
+
+ // checkmark changes
+ [type='checkbox']:not(:checked) + label::after {
+ opacity: 0;
+ }
+
+ [type='checkbox']:checked + label::after {
+ opacity: 1;
+ }
+
+ // accessibility
+ [type='checkbox']:checked:focus + label::before,
+ [type='checkbox']:not(:checked):focus + label::before {
+ border: 1px dotted var(--newtab-link-primary-color);
+ }
+}
+
+.outer-wrapper {
+ // Special styling for when we are using the old new tab styling,
+ // this is to be removed once the changes are made permanent
+ &:not(.newtab-experience) {
+ .top-site-outer {
+ @include context-menu-button;
+
+ .tile {
+ height: $top-sites-size;
+ width: $top-sites-size;
+ transition: box-shadow $hover-transition-duration;
+ }
+
+ .top-site-icon {
+ box-shadow: var(--newtab-topsites-icon-shadow);
+ }
+
+ .title {
+ width: $top-sites-size;
+
+ &.has-icon {
+ span {
+ padding: 0 13px;
+ }
+ }
+
+ .icon {
+ inset-inline-start: 0;
+ position: absolute;
+ top: 0.5em;
+ }
+ }
+
+ // container for context menu
+ .top-site-inner {
+ position: relative;
+
+ > a {
+ color: inherit;
+ display: block;
+ outline: none;
+
+ &:is(.active, :focus) {
+ .tile {
+ @include fade-in;
+ }
+ }
+ }
+ }
+
+ .screenshot {
+ background-color: $white;
+ background-position: top left;
+ background-size: $screenshot-size;
+ border-radius: $top-sites-border-radius;
+ box-shadow: inset $inner-box-shadow;
+ height: 100%;
+ opacity: 0;
+ position: absolute;
+ top: 0;
+ left: 0;
+ transition: opacity 1s;
+ width: 100%;
+
+ &.active {
+ opacity: 1;
+ }
+ }
+
+ .default-icon,
+ .search-topsite {
+ bottom: -$default-icon-offset;
+ inset-inline-end: -$default-icon-offset;
+ }
+
+ &:hover .search-topsite {
+ $hover-icon-wrapper-size: $default-icon-wrapper-size + 4;
+ $hover-icon-offset: -$default-icon-offset - 3;
+
+ background-size: 28px;
+ border-radius: $hover-icon-wrapper-size;
+ bottom: $hover-icon-offset;
+ height: $hover-icon-wrapper-size;
+ inset-inline-end: $hover-icon-offset;
+ width: $hover-icon-wrapper-size;
+ }
+
+ &.placeholder {
+ .tile {
+ box-shadow: inset $inner-box-shadow;
+ }
+ }
+ }
+
+ .top-sites-list {
+ &:not(.dnd-active) {
+ .top-site-outer:is(.active, :focus, :hover) {
+ .tile {
+ @include fade-in;
+ }
+
+ @include context-menu-button-hover;
+ }
+ }
+
+ li {
+ margin: 0 0 $top-sites-vertical-space;
+ }
+ }
+ }
+
+ // Special styling for the New Tab Experience styles,
+ // This is to be incorporated once the styles are made permanent
+ &.newtab-experience {
+ .top-site-outer {
+ @include context-menu-button-newtab-experience;
+ width: 120px;
+ padding-block: 20px 4px;
+ border-radius: 8px;
+
+ .edit-button {
+ background-image: url('#{$image-path}glyph-edit-16.svg');
+ }
+
+ .tile {
+ border-radius: $nt-experience-top-sites-border-radius;
+ box-shadow: $inner-box-shadow-nte, $tile-shadow-second;
+ background-color: var(--newtab-topsites-background-color);
+ justify-content: center;
+ margin: 0 auto;
+ height: $top-sites-size-nte;
+ width: $top-sites-size-nte;
+ }
+
+ .title {
+ color: var(--newtab-background-primary-text-color);
+ padding-top: 8px;
+ font-size: 12px;
+
+ .icon {
+ margin-inline-end: 2px;
+ fill: var(--newtab-background-primary-text-color);
+ }
+
+ .sponsored-label {
+ font-size: 12px;
+ }
+ }
+
+ .default-icon,
+ .search-topsite {
+ height: $nt-experience-default-icon-wrapper-size;
+ width: $nt-experience-default-icon-wrapper-size;
+ }
+
+ .search-topsite {
+ background-size: 16px;
+ height: 32px;
+ width: 32px;
+ }
+
+ &:hover .search-topsite {
+ $hover-icon-wrapper-size: $search-icon-wrapper-size + 4;
+ }
+
+ &.placeholder {
+ .tile {
+ box-shadow: $inner-box-shadow;
+ }
+ }
+ }
+
+ .top-sites-list {
+ // Two columns
+ @media (max-width: $break-point-medium) {
+ > :nth-child(2n+1) {
+ @include context-menu-open-middle;
+ }
+
+ > :nth-child(2n) {
+ @include context-menu-open-left;
+ }
+ }
+
+ // Four columns
+ @media (min-width: $break-point-medium) and (max-width: $break-point-large) {
+ :nth-child(4n) {
+ @include context-menu-open-left;
+ }
+ }
+ @media (min-width: $break-point-medium) and (max-width: $break-point-medium + $card-width-nte) {
+ :nth-child(4n+3) {
+ @include context-menu-open-left;
+ }
+ }
+
+ // Six columns
+ @media (min-width: $break-point-large) and (max-width: $break-point-large + 2 * $card-width-nte) {
+ :nth-child(6n) {
+ @include context-menu-open-left;
+ }
+ }
+ @media (min-width: $break-point-large) and (max-width: $break-point-large + $card-width-nte) {
+ :nth-child(6n+5) {
+ @include context-menu-open-left;
+ }
+ }
+
+ // Eight columns
+ @media (min-width: $break-point-widest) and (max-width: $break-point-widest + 2 * $card-width-nte) {
+ :nth-child(8n) {
+ @include context-menu-open-left;
+ }
+ }
+ @media (min-width: $break-point-widest) and (max-width: $break-point-widest + $card-width-nte) {
+ :nth-child(8n+7) {
+ @include context-menu-open-left;
+ }
+ }
+ }
+
+ &:not(.dnd-active) {
+ .top-site-outer:is(.active, :focus, :hover) {
+ @include nt-experience-context-menu-button-hover;
+ background: var(--newtab-topsites-outer-card-hover);
+ }
+ }
+ }
+
+}
+
+//used for tooltips below form element
+@keyframes fade-up-tt {
+ 0% {
+ opacity: 0;
+ transform: translateY(15px);
+ }
+
+ 100% {
+ opacity: 1;
+ transform: translateY(0);
+ }
+}
diff --git a/browser/components/newtab/content-src/components/Topics/Topics.jsx b/browser/components/newtab/content-src/components/Topics/Topics.jsx
new file mode 100644
index 0000000000..ef59094c65
--- /dev/null
+++ b/browser/components/newtab/content-src/components/Topics/Topics.jsx
@@ -0,0 +1,33 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import React from "react";
+
+export class Topic extends React.PureComponent {
+ render() {
+ const { url, name } = this.props;
+ return (
+ <li>
+ <a key={name} href={url}>
+ {name}
+ </a>
+ </li>
+ );
+ }
+}
+
+export class Topics extends React.PureComponent {
+ render() {
+ const { topics } = this.props;
+ return (
+ <span className="topics">
+ <span data-l10n-id="newtab-pocket-read-more" />
+ <ul>
+ {topics &&
+ topics.map(t => <Topic key={t.name} url={t.url} name={t.name} />)}
+ </ul>
+ </span>
+ );
+ }
+}
diff --git a/browser/components/newtab/content-src/components/Topics/_Topics.scss b/browser/components/newtab/content-src/components/Topics/_Topics.scss
new file mode 100644
index 0000000000..0a2159beee
--- /dev/null
+++ b/browser/components/newtab/content-src/components/Topics/_Topics.scss
@@ -0,0 +1,23 @@
+.topics {
+ ul {
+ margin: 0;
+ padding: 0;
+ @media (min-width: $break-point-large) {
+ display: inline;
+ padding-inline-start: 12px;
+ }
+ }
+
+ ul li {
+ display: inline-block;
+
+ &::after {
+ content: '•';
+ padding: 8px;
+ }
+
+ &:last-child::after {
+ content: none;
+ }
+ }
+}
diff --git a/browser/components/newtab/content-src/lib/aboutwelcome-utils.js b/browser/components/newtab/content-src/lib/aboutwelcome-utils.js
new file mode 100644
index 0000000000..54efde5e52
--- /dev/null
+++ b/browser/components/newtab/content-src/lib/aboutwelcome-utils.js
@@ -0,0 +1,235 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+export const AboutWelcomeUtils = {
+ handleUserAction(action) {
+ window.AWSendToParent("SPECIAL_ACTION", action);
+ },
+ sendImpressionTelemetry(messageId, context) {
+ window.AWSendEventTelemetry({
+ event: "IMPRESSION",
+ event_context: context,
+ message_id: messageId,
+ });
+ },
+ sendActionTelemetry(messageId, elementId) {
+ const ping = {
+ event: "CLICK_BUTTON",
+ event_context: {
+ source: elementId,
+ page: "about:welcome",
+ },
+ message_id: messageId,
+ };
+ window.AWSendEventTelemetry(ping);
+ },
+ async fetchFlowParams(metricsFlowUri) {
+ let flowParams;
+ try {
+ const response = await fetch(metricsFlowUri, {
+ credentials: "omit",
+ });
+ if (response.status === 200) {
+ const { deviceId, flowId, flowBeginTime } = await response.json();
+ flowParams = { deviceId, flowId, flowBeginTime };
+ } else {
+ console.error("Non-200 response", response); // eslint-disable-line no-console
+ }
+ } catch (e) {
+ flowParams = null;
+ }
+ return flowParams;
+ },
+ sendEvent(type, detail) {
+ document.dispatchEvent(
+ new CustomEvent(`AWPage:${type}`, {
+ bubbles: true,
+ detail,
+ })
+ );
+ },
+ hasDarkMode() {
+ return document.body.hasAttribute("lwt-newtab-brighttext");
+ },
+};
+
+export const DEFAULT_RTAMO_CONTENT = {
+ template: "return_to_amo",
+ content: {
+ header: { string_id: "onboarding-welcome-header" },
+ subtitle: { string_id: "return-to-amo-subtitle" },
+ text: {
+ string_id: "return-to-amo-addon-title",
+ },
+ primary_button: {
+ label: { string_id: "return-to-amo-add-extension-label" },
+ action: {
+ type: "INSTALL_ADDON_FROM_URL",
+ data: { url: null, telemetrySource: "rtamo" },
+ },
+ },
+ startButton: {
+ label: {
+ string_id: "onboarding-not-now-button-label",
+ },
+ message_id: "RTAMO_START_BROWSING_BUTTON",
+ action: {
+ type: "OPEN_AWESOME_BAR",
+ },
+ },
+ },
+};
+
+export const DEFAULT_WELCOME_CONTENT = {
+ template: "multistage",
+ screens: [
+ {
+ id: "AW_GET_STARTED",
+ order: 0,
+ content: {
+ zap: true,
+ title: {
+ string_id: "onboarding-multistage-welcome-header",
+ },
+ subtitle: { string_id: "onboarding-multistage-welcome-subtitle" },
+ primary_button: {
+ label: {
+ string_id: "onboarding-multistage-welcome-primary-button-label",
+ },
+ action: {
+ navigate: true,
+ },
+ },
+ secondary_button: {
+ text: {
+ string_id: "onboarding-multistage-welcome-secondary-button-text",
+ },
+ label: {
+ string_id: "onboarding-multistage-welcome-secondary-button-label",
+ },
+ position: "top",
+ action: {
+ type: "SHOW_FIREFOX_ACCOUNTS",
+ addFlowParams: true,
+ data: {
+ entrypoint: "activity-stream-firstrun",
+ },
+ },
+ },
+ },
+ },
+ {
+ id: "AW_IMPORT_SETTINGS",
+ order: 1,
+ content: {
+ zap: true,
+ help_text: {
+ text: { string_id: "onboarding-import-sites-disclaimer" },
+ },
+ title: { string_id: "onboarding-multistage-import-header" },
+ subtitle: { string_id: "onboarding-multistage-import-subtitle" },
+ tiles: {
+ type: "topsites",
+ showTitles: true,
+ },
+ primary_button: {
+ label: {
+ string_id: "onboarding-multistage-import-primary-button-label",
+ },
+ action: {
+ type: "SHOW_MIGRATION_WIZARD",
+ navigate: true,
+ },
+ },
+ secondary_button: {
+ label: {
+ string_id: "onboarding-multistage-import-secondary-button-label",
+ },
+ action: {
+ navigate: true,
+ },
+ },
+ },
+ },
+ {
+ id: "AW_CHOOSE_THEME",
+ order: 2,
+ content: {
+ zap: true,
+ title: { string_id: "onboarding-multistage-theme-header" },
+ subtitle: { string_id: "onboarding-multistage-theme-subtitle" },
+ tiles: {
+ type: "theme",
+ action: {
+ theme: "<event>",
+ },
+ data: [
+ {
+ theme: "automatic",
+ label: {
+ string_id: "onboarding-multistage-theme-label-automatic",
+ },
+ tooltip: {
+ string_id: "onboarding-multistage-theme-tooltip-automatic-2",
+ },
+ description: {
+ string_id:
+ "onboarding-multistage-theme-description-automatic-2",
+ },
+ },
+ {
+ theme: "light",
+ label: { string_id: "onboarding-multistage-theme-label-light" },
+ tooltip: {
+ string_id: "onboarding-multistage-theme-tooltip-light-2",
+ },
+ description: {
+ string_id: "onboarding-multistage-theme-description-light",
+ },
+ },
+ {
+ theme: "dark",
+ label: { string_id: "onboarding-multistage-theme-label-dark" },
+ tooltip: {
+ string_id: "onboarding-multistage-theme-tooltip-dark-2",
+ },
+ description: {
+ string_id: "onboarding-multistage-theme-description-dark",
+ },
+ },
+ {
+ theme: "alpenglow",
+ label: {
+ string_id: "onboarding-multistage-theme-label-alpenglow",
+ },
+ tooltip: {
+ string_id: "onboarding-multistage-theme-tooltip-alpenglow-2",
+ },
+ description: {
+ string_id: "onboarding-multistage-theme-description-alpenglow",
+ },
+ },
+ ],
+ },
+ primary_button: {
+ label: {
+ string_id: "onboarding-multistage-theme-primary-button-label",
+ },
+ action: {
+ navigate: true,
+ },
+ },
+ secondary_button: {
+ label: {
+ string_id: "onboarding-multistage-theme-secondary-button-label",
+ },
+ action: {
+ theme: "automatic",
+ navigate: true,
+ },
+ },
+ },
+ },
+ ],
+};
diff --git a/browser/components/newtab/content-src/lib/constants.js b/browser/components/newtab/content-src/lib/constants.js
new file mode 100644
index 0000000000..bd3da63682
--- /dev/null
+++ b/browser/components/newtab/content-src/lib/constants.js
@@ -0,0 +1,32 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+export const IS_NEWTAB =
+ global.document && global.document.documentURI === "about:newtab";
+export const NEWTAB_DARK_THEME = {
+ ntp_background: {
+ r: 42,
+ g: 42,
+ b: 46,
+ a: 1,
+ },
+ ntp_text: {
+ r: 249,
+ g: 249,
+ b: 250,
+ a: 1,
+ },
+ sidebar: {
+ r: 56,
+ g: 56,
+ b: 61,
+ a: 1,
+ },
+ sidebar_text: {
+ r: 249,
+ g: 249,
+ b: 250,
+ a: 1,
+ },
+};
diff --git a/browser/components/newtab/content-src/lib/detect-user-session-start.js b/browser/components/newtab/content-src/lib/detect-user-session-start.js
new file mode 100644
index 0000000000..ecc57dba72
--- /dev/null
+++ b/browser/components/newtab/content-src/lib/detect-user-session-start.js
@@ -0,0 +1,78 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { actionCreators as ac, actionTypes as at } from "common/Actions.jsm";
+import { perfService as perfSvc } from "content-src/lib/perf-service";
+
+const VISIBLE = "visible";
+const VISIBILITY_CHANGE_EVENT = "visibilitychange";
+
+export class DetectUserSessionStart {
+ constructor(store, options = {}) {
+ this._store = store;
+ // Overrides for testing
+ this.document = options.document || global.document;
+ this._perfService = options.perfService || perfSvc;
+ this._onVisibilityChange = this._onVisibilityChange.bind(this);
+ }
+
+ /**
+ * sendEventOrAddListener - Notify immediately if the page is already visible,
+ * or else set up a listener for when visibility changes.
+ * This is needed for accurate session tracking for telemetry,
+ * because tabs are pre-loaded.
+ */
+ sendEventOrAddListener() {
+ if (this.document.visibilityState === VISIBLE) {
+ // If the document is already visible, to the user, send a notification
+ // immediately that a session has started.
+ this._sendEvent();
+ } else {
+ // If the document is not visible, listen for when it does become visible.
+ this.document.addEventListener(
+ VISIBILITY_CHANGE_EVENT,
+ this._onVisibilityChange
+ );
+ }
+ }
+
+ /**
+ * _sendEvent - Sends a message to the main process to indicate the current
+ * tab is now visible to the user, includes the
+ * visibility_event_rcvd_ts time in ms from the UNIX epoch.
+ */
+ _sendEvent() {
+ this._perfService.mark("visibility_event_rcvd_ts");
+
+ try {
+ let visibility_event_rcvd_ts = this._perfService.getMostRecentAbsMarkStartByName(
+ "visibility_event_rcvd_ts"
+ );
+
+ this._store.dispatch(
+ ac.AlsoToMain({
+ type: at.SAVE_SESSION_PERF_DATA,
+ data: { visibility_event_rcvd_ts },
+ })
+ );
+ } catch (ex) {
+ // If this failed, it's likely because the `privacy.resistFingerprinting`
+ // pref is true. We should at least not blow up.
+ }
+ }
+
+ /**
+ * _onVisibilityChange - If the visibility has changed to visible, sends a notification
+ * and removes the event listener. This should only be called once per tab.
+ */
+ _onVisibilityChange() {
+ if (this.document.visibilityState === VISIBLE) {
+ this._sendEvent();
+ this.document.removeEventListener(
+ VISIBILITY_CHANGE_EVENT,
+ this._onVisibilityChange
+ );
+ }
+ }
+}
diff --git a/browser/components/newtab/content-src/lib/init-store.js b/browser/components/newtab/content-src/lib/init-store.js
new file mode 100644
index 0000000000..c0931ab5d8
--- /dev/null
+++ b/browser/components/newtab/content-src/lib/init-store.js
@@ -0,0 +1,175 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* eslint-env mozilla/frame-script */
+
+import {
+ actionCreators as ac,
+ actionTypes as at,
+ actionUtils as au,
+} from "common/Actions.jsm";
+import { applyMiddleware, combineReducers, createStore } from "redux";
+
+export const MERGE_STORE_ACTION = "NEW_TAB_INITIAL_STATE";
+export const OUTGOING_MESSAGE_NAME = "ActivityStream:ContentToMain";
+export const INCOMING_MESSAGE_NAME = "ActivityStream:MainToContent";
+export const EARLY_QUEUED_ACTIONS = [at.SAVE_SESSION_PERF_DATA];
+
+/**
+ * A higher-order function which returns a reducer that, on MERGE_STORE action,
+ * will return the action.data object merged into the previous state.
+ *
+ * For all other actions, it merely calls mainReducer.
+ *
+ * Because we want this to merge the entire state object, it's written as a
+ * higher order function which takes the main reducer (itself often a call to
+ * combineReducers) as a parameter.
+ *
+ * @param {function} mainReducer reducer to call if action != MERGE_STORE_ACTION
+ * @return {function} a reducer that, on MERGE_STORE_ACTION action,
+ * will return the action.data object merged
+ * into the previous state, and the result
+ * of calling mainReducer otherwise.
+ */
+function mergeStateReducer(mainReducer) {
+ return (prevState, action) => {
+ if (action.type === MERGE_STORE_ACTION) {
+ return { ...prevState, ...action.data };
+ }
+
+ return mainReducer(prevState, action);
+ };
+}
+
+/**
+ * messageMiddleware - Middleware that looks for SentToMain type actions, and sends them if necessary
+ */
+const messageMiddleware = store => next => action => {
+ const skipLocal = action.meta && action.meta.skipLocal;
+ if (au.isSendToMain(action)) {
+ RPMSendAsyncMessage(OUTGOING_MESSAGE_NAME, action);
+ }
+ if (!skipLocal) {
+ next(action);
+ }
+};
+
+export const rehydrationMiddleware = ({ getState }) => {
+ // NB: The parameter here is MiddlewareAPI which looks like a Store and shares
+ // the same getState, so attached properties are accessible from the store.
+ getState.didRehydrate = false;
+ getState.didRequestInitialState = false;
+ return next => action => {
+ if (getState.didRehydrate || window.__FROM_STARTUP_CACHE__) {
+ // Startup messages can be safely ignored by the about:home document
+ // stored in the startup cache.
+ if (
+ window.__FROM_STARTUP_CACHE__ &&
+ action.meta &&
+ action.meta.isStartup
+ ) {
+ return null;
+ }
+ return next(action);
+ }
+
+ const isMergeStoreAction = action.type === MERGE_STORE_ACTION;
+ const isRehydrationRequest = action.type === at.NEW_TAB_STATE_REQUEST;
+
+ if (isRehydrationRequest) {
+ getState.didRequestInitialState = true;
+ return next(action);
+ }
+
+ if (isMergeStoreAction) {
+ getState.didRehydrate = true;
+ return next(action);
+ }
+
+ // If init happened after our request was made, we need to re-request
+ if (getState.didRequestInitialState && action.type === at.INIT) {
+ return next(ac.AlsoToMain({ type: at.NEW_TAB_STATE_REQUEST }));
+ }
+
+ if (
+ au.isBroadcastToContent(action) ||
+ au.isSendToOneContent(action) ||
+ au.isSendToPreloaded(action)
+ ) {
+ // Note that actions received before didRehydrate will not be dispatched
+ // because this could negatively affect preloading and the the state
+ // will be replaced by rehydration anyway.
+ return null;
+ }
+
+ return next(action);
+ };
+};
+
+/**
+ * This middleware queues up all the EARLY_QUEUED_ACTIONS until it receives
+ * the first action from main. This is useful for those actions for main which
+ * require higher reliability, i.e. the action will not be lost in the case
+ * that it gets sent before the main is ready to receive it. Conversely, any
+ * actions allowed early are accepted to be ignorable or re-sendable.
+ */
+export const queueEarlyMessageMiddleware = ({ getState }) => {
+ // NB: The parameter here is MiddlewareAPI which looks like a Store and shares
+ // the same getState, so attached properties are accessible from the store.
+ getState.earlyActionQueue = [];
+ getState.receivedFromMain = false;
+ return next => action => {
+ if (getState.receivedFromMain) {
+ next(action);
+ } else if (au.isFromMain(action)) {
+ next(action);
+ getState.receivedFromMain = true;
+ // Sending out all the early actions as main is ready now
+ getState.earlyActionQueue.forEach(next);
+ getState.earlyActionQueue.length = 0;
+ } else if (EARLY_QUEUED_ACTIONS.includes(action.type)) {
+ getState.earlyActionQueue.push(action);
+ } else {
+ // Let any other type of action go through
+ next(action);
+ }
+ };
+};
+
+/**
+ * initStore - Create a store and listen for incoming actions
+ *
+ * @param {object} reducers An object containing Redux reducers
+ * @param {object} intialState (optional) The initial state of the store, if desired
+ * @return {object} A redux store
+ */
+export function initStore(reducers, initialState) {
+ const store = createStore(
+ mergeStateReducer(combineReducers(reducers)),
+ initialState,
+ global.RPMAddMessageListener &&
+ applyMiddleware(
+ queueEarlyMessageMiddleware,
+ rehydrationMiddleware,
+ messageMiddleware
+ )
+ );
+
+ if (global.RPMAddMessageListener) {
+ global.RPMAddMessageListener(INCOMING_MESSAGE_NAME, msg => {
+ try {
+ store.dispatch(msg.data);
+ } catch (ex) {
+ console.error("Content msg:", msg, "Dispatch error: ", ex); // eslint-disable-line no-console
+ dump(
+ `Content msg: ${JSON.stringify(msg)}\nDispatch error: ${ex}\n${
+ ex.stack
+ }`
+ );
+ }
+ });
+ }
+
+ return store;
+}
diff --git a/browser/components/newtab/content-src/lib/link-menu-options.js b/browser/components/newtab/content-src/lib/link-menu-options.js
new file mode 100644
index 0000000000..cb45c0df2d
--- /dev/null
+++ b/browser/components/newtab/content-src/lib/link-menu-options.js
@@ -0,0 +1,276 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { actionCreators as ac, actionTypes as at } from "common/Actions.jsm";
+
+const _OpenInPrivateWindow = site => ({
+ id: "newtab-menu-open-new-private-window",
+ icon: "new-window-private",
+ action: ac.OnlyToMain({
+ type: at.OPEN_PRIVATE_WINDOW,
+ data: { url: site.url, referrer: site.referrer },
+ }),
+ userEvent: "OPEN_PRIVATE_WINDOW",
+});
+
+/**
+ * List of functions that return items that can be included as menu options in a
+ * LinkMenu. All functions take the site as the first parameter, and optionally
+ * the index of the site.
+ */
+export const LinkMenuOptions = {
+ Separator: () => ({ type: "separator" }),
+ EmptyItem: () => ({ type: "empty" }),
+ ShowPrivacyInfo: site => ({
+ id: "newtab-menu-show-privacy-info",
+ icon: "info",
+ action: {
+ type: at.SHOW_PRIVACY_INFO,
+ },
+ userEvent: "SHOW_PRIVACY_INFO",
+ }),
+ AboutSponsored: site => ({
+ id: "newtab-menu-show-privacy-info",
+ icon: "info",
+ action: ac.AlsoToMain({
+ type: at.ABOUT_SPONSORED_TOP_SITES,
+ }),
+ userEvent: "TOPSITE_SPONSOR_INFO",
+ }),
+ RemoveBookmark: site => ({
+ id: "newtab-menu-remove-bookmark",
+ icon: "bookmark-added",
+ action: ac.AlsoToMain({
+ type: at.DELETE_BOOKMARK_BY_ID,
+ data: site.bookmarkGuid,
+ }),
+ userEvent: "BOOKMARK_DELETE",
+ }),
+ AddBookmark: site => ({
+ id: "newtab-menu-bookmark",
+ icon: "bookmark-hollow",
+ action: ac.AlsoToMain({
+ type: at.BOOKMARK_URL,
+ data: { url: site.url, title: site.title, type: site.type },
+ }),
+ userEvent: "BOOKMARK_ADD",
+ }),
+ OpenInNewWindow: site => ({
+ id: "newtab-menu-open-new-window",
+ icon: "new-window",
+ action: ac.AlsoToMain({
+ type: at.OPEN_NEW_WINDOW,
+ data: {
+ referrer: site.referrer,
+ typedBonus: site.typedBonus,
+ url: site.url,
+ },
+ }),
+ userEvent: "OPEN_NEW_WINDOW",
+ }),
+ // This blocks the url for regular stories,
+ // but also sends a message to DiscoveryStream with flight_id.
+ // If DiscoveryStream sees this message for a flight_id
+ // it also blocks it on the flight_id.
+ BlockUrl: (site, index, eventSource) => {
+ return LinkMenuOptions.BlockUrls([site], index, eventSource);
+ },
+ // Same as BlockUrl, cept can work on an array of sites.
+ BlockUrls: (tiles, pos, eventSource) => ({
+ id: "newtab-menu-dismiss",
+ icon: "dismiss",
+ action: ac.AlsoToMain({
+ type: at.BLOCK_URL,
+ data: tiles.map(site => ({
+ url: site.original_url || site.open_url || site.url,
+ // pocket_id is only for pocket stories being in highlights, and then dismissed.
+ pocket_id: site.pocket_id,
+ ...(site.flight_id ? { flight_id: site.flight_id } : {}),
+ })),
+ }),
+ impression: ac.ImpressionStats({
+ source: eventSource,
+ block: 0,
+ tiles: tiles.map((site, index) => ({
+ id: site.guid,
+ pos: pos + index,
+ ...(site.shim && site.shim.delete ? { shim: site.shim.delete } : {}),
+ })),
+ }),
+ userEvent: "BLOCK",
+ }),
+
+ // This is an option for web extentions which will result in remove items from
+ // memory and notify the web extenion, rather than using the built-in block list.
+ WebExtDismiss: (site, index, eventSource) => ({
+ id: "menu_action_webext_dismiss",
+ string_id: "newtab-menu-dismiss",
+ icon: "dismiss",
+ action: ac.WebExtEvent(at.WEBEXT_DISMISS, {
+ source: eventSource,
+ url: site.url,
+ action_position: index,
+ }),
+ }),
+ DeleteUrl: (site, index, eventSource, isEnabled, siteInfo) => ({
+ id: "newtab-menu-delete-history",
+ icon: "delete",
+ action: {
+ type: at.DIALOG_OPEN,
+ data: {
+ onConfirm: [
+ ac.AlsoToMain({
+ type: at.DELETE_HISTORY_URL,
+ data: {
+ url: site.url,
+ pocket_id: site.pocket_id,
+ forceBlock: site.bookmarkGuid,
+ },
+ }),
+ ac.UserEvent(
+ Object.assign(
+ { event: "DELETE", source: eventSource, action_position: index },
+ siteInfo
+ )
+ ),
+ ],
+ eventSource,
+ body_string_id: [
+ "newtab-confirm-delete-history-p1",
+ "newtab-confirm-delete-history-p2",
+ ],
+ confirm_button_string_id: "newtab-topsites-delete-history-button",
+ cancel_button_string_id: "newtab-topsites-cancel-button",
+ icon: "modal-delete",
+ },
+ },
+ userEvent: "DIALOG_OPEN",
+ }),
+ ShowFile: site => ({
+ id: "newtab-menu-show-file",
+ icon: "search",
+ action: ac.OnlyToMain({
+ type: at.SHOW_DOWNLOAD_FILE,
+ data: { url: site.url },
+ }),
+ }),
+ OpenFile: site => ({
+ id: "newtab-menu-open-file",
+ icon: "open-file",
+ action: ac.OnlyToMain({
+ type: at.OPEN_DOWNLOAD_FILE,
+ data: { url: site.url },
+ }),
+ }),
+ CopyDownloadLink: site => ({
+ id: "newtab-menu-copy-download-link",
+ icon: "copy",
+ action: ac.OnlyToMain({
+ type: at.COPY_DOWNLOAD_LINK,
+ data: { url: site.url },
+ }),
+ }),
+ GoToDownloadPage: site => ({
+ id: "newtab-menu-go-to-download-page",
+ icon: "download",
+ action: ac.OnlyToMain({
+ type: at.OPEN_LINK,
+ data: { url: site.referrer },
+ }),
+ disabled: !site.referrer,
+ }),
+ RemoveDownload: site => ({
+ id: "newtab-menu-remove-download",
+ icon: "delete",
+ action: ac.OnlyToMain({
+ type: at.REMOVE_DOWNLOAD_FILE,
+ data: { url: site.url },
+ }),
+ }),
+ PinTopSite: (site, index) => ({
+ id: "newtab-menu-pin",
+ icon: "pin",
+ action: ac.AlsoToMain({
+ type: at.TOP_SITES_PIN,
+ data: {
+ site,
+ index,
+ },
+ }),
+ userEvent: "PIN",
+ }),
+ UnpinTopSite: site => ({
+ id: "newtab-menu-unpin",
+ icon: "unpin",
+ action: ac.AlsoToMain({
+ type: at.TOP_SITES_UNPIN,
+ data: { site: { url: site.url } },
+ }),
+ userEvent: "UNPIN",
+ }),
+ SaveToPocket: (site, index, eventSource) => ({
+ id: "newtab-menu-save-to-pocket",
+ icon: "pocket-save",
+ action: ac.AlsoToMain({
+ type: at.SAVE_TO_POCKET,
+ data: { site: { url: site.url, title: site.title } },
+ }),
+ impression: ac.ImpressionStats({
+ source: eventSource,
+ pocket: 0,
+ tiles: [
+ {
+ id: site.guid,
+ pos: index,
+ ...(site.shim && site.shim.save ? { shim: site.shim.save } : {}),
+ },
+ ],
+ }),
+ userEvent: "SAVE_TO_POCKET",
+ }),
+ DeleteFromPocket: site => ({
+ id: "newtab-menu-delete-pocket",
+ icon: "pocket-delete",
+ action: ac.AlsoToMain({
+ type: at.DELETE_FROM_POCKET,
+ data: { pocket_id: site.pocket_id },
+ }),
+ userEvent: "DELETE_FROM_POCKET",
+ }),
+ ArchiveFromPocket: site => ({
+ id: "newtab-menu-archive-pocket",
+ icon: "pocket-archive",
+ action: ac.AlsoToMain({
+ type: at.ARCHIVE_FROM_POCKET,
+ data: { pocket_id: site.pocket_id },
+ }),
+ userEvent: "ARCHIVE_FROM_POCKET",
+ }),
+ EditTopSite: (site, index) => ({
+ id: "newtab-menu-edit-topsites",
+ icon: "edit",
+ action: {
+ type: at.TOP_SITES_EDIT,
+ data: { index },
+ },
+ }),
+ CheckBookmark: site =>
+ site.bookmarkGuid
+ ? LinkMenuOptions.RemoveBookmark(site)
+ : LinkMenuOptions.AddBookmark(site),
+ CheckPinTopSite: (site, index) =>
+ site.isPinned
+ ? LinkMenuOptions.UnpinTopSite(site)
+ : LinkMenuOptions.PinTopSite(site, index),
+ CheckSavedToPocket: (site, index) =>
+ site.pocket_id
+ ? LinkMenuOptions.DeleteFromPocket(site)
+ : LinkMenuOptions.SaveToPocket(site, index),
+ CheckBookmarkOrArchive: site =>
+ site.pocket_id
+ ? LinkMenuOptions.ArchiveFromPocket(site)
+ : LinkMenuOptions.CheckBookmark(site),
+ OpenInPrivateWindow: (site, index, eventSource, isEnabled) =>
+ isEnabled ? _OpenInPrivateWindow(site) : LinkMenuOptions.EmptyItem(),
+};
diff --git a/browser/components/newtab/content-src/lib/perf-service.js b/browser/components/newtab/content-src/lib/perf-service.js
new file mode 100644
index 0000000000..6ea99ce877
--- /dev/null
+++ b/browser/components/newtab/content-src/lib/perf-service.js
@@ -0,0 +1,104 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+let usablePerfObj = window.performance;
+
+export function _PerfService(options) {
+ // For testing, so that we can use a fake Window.performance object with
+ // known state.
+ if (options && options.performanceObj) {
+ this._perf = options.performanceObj;
+ } else {
+ this._perf = usablePerfObj;
+ }
+}
+
+_PerfService.prototype = {
+ /**
+ * Calls the underlying mark() method on the appropriate Window.performance
+ * object to add a mark with the given name to the appropriate performance
+ * timeline.
+ *
+ * @param {String} name the name to give the current mark
+ * @return {void}
+ */
+ mark: function mark(str) {
+ this._perf.mark(str);
+ },
+
+ /**
+ * Calls the underlying getEntriesByName on the appropriate Window.performance
+ * object.
+ *
+ * @param {String} name
+ * @param {String} type eg "mark"
+ * @return {Array} Performance* objects
+ */
+ getEntriesByName: function getEntriesByName(name, type) {
+ return this._perf.getEntriesByName(name, type);
+ },
+
+ /**
+ * The timeOrigin property from the appropriate performance object.
+ * Used to ensure that timestamps from the add-on code and the content code
+ * are comparable.
+ *
+ * @note If this is called from a context without a window
+ * (eg a JSM in chrome), it will return the timeOrigin of the XUL hidden
+ * window, which appears to be the first created window (and thus
+ * timeOrigin) in the browser. Note also, however, there is also a private
+ * hidden window, presumably for private browsing, which appears to be
+ * created dynamically later. Exactly how/when that shows up needs to be
+ * investigated.
+ *
+ * @return {Number} A double of milliseconds with a precision of 0.5us.
+ */
+ get timeOrigin() {
+ return this._perf.timeOrigin;
+ },
+
+ /**
+ * Returns the "absolute" version of performance.now(), i.e. one that
+ * should ([bug 1401406](https://bugzilla.mozilla.org/show_bug.cgi?id=1401406)
+ * be comparable across both chrome and content.
+ *
+ * @return {Number}
+ */
+ absNow: function absNow() {
+ return this.timeOrigin + this._perf.now();
+ },
+
+ /**
+ * This returns the absolute startTime from the most recent performance.mark()
+ * with the given name.
+ *
+ * @param {String} name the name to lookup the start time for
+ *
+ * @return {Number} the returned start time, as a DOMHighResTimeStamp
+ *
+ * @throws {Error} "No Marks with the name ..." if none are available
+ *
+ * @note Always surround calls to this by try/catch. Otherwise your code
+ * may fail when the `privacy.resistFingerprinting` pref is true. When
+ * this pref is set, all attempts to get marks will likely fail, which will
+ * cause this method to throw.
+ *
+ * See [bug 1369303](https://bugzilla.mozilla.org/show_bug.cgi?id=1369303)
+ * for more info.
+ */
+ getMostRecentAbsMarkStartByName(name) {
+ let entries = this.getEntriesByName(name, "mark");
+
+ if (!entries.length) {
+ throw new Error(`No marks with the name ${name}`);
+ }
+
+ let mostRecentEntry = entries[entries.length - 1];
+ return this._perf.timeOrigin + mostRecentEntry.startTime;
+ },
+};
+
+export const perfService = new _PerfService();
diff --git a/browser/components/newtab/content-src/lib/screenshot-utils.js b/browser/components/newtab/content-src/lib/screenshot-utils.js
new file mode 100644
index 0000000000..7ea93f12ae
--- /dev/null
+++ b/browser/components/newtab/content-src/lib/screenshot-utils.js
@@ -0,0 +1,61 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/**
+ * List of helper functions for screenshot-based images.
+ *
+ * There are two kinds of images:
+ * 1. Remote Image: This is the image from the main process and it refers to
+ * the image in the React props. This can either be an object with the `data`
+ * and `path` properties, if it is a blob, or a string, if it is a normal image.
+ * 2. Local Image: This is the image object in the content process and it refers
+ * to the image *object* in the React component's state. All local image
+ * objects have the `url` property, and an additional property `path`, if they
+ * are blobs.
+ */
+export const ScreenshotUtils = {
+ isBlob(isLocal, image) {
+ return !!(
+ image &&
+ image.path &&
+ ((!isLocal && image.data) || (isLocal && image.url))
+ );
+ },
+
+ // This should always be called with a remote image and not a local image.
+ createLocalImageObject(remoteImage) {
+ if (!remoteImage) {
+ return null;
+ }
+ if (this.isBlob(false, remoteImage)) {
+ return {
+ url: global.URL.createObjectURL(remoteImage.data),
+ path: remoteImage.path,
+ };
+ }
+ return { url: remoteImage };
+ },
+
+ // Revokes the object URL of the image if the local image is a blob.
+ // This should always be called with a local image and not a remote image.
+ maybeRevokeBlobObjectURL(localImage) {
+ if (this.isBlob(true, localImage)) {
+ global.URL.revokeObjectURL(localImage.url);
+ }
+ },
+
+ // Checks if remoteImage and localImage are the same.
+ isRemoteImageLocal(localImage, remoteImage) {
+ // Both remoteImage and localImage are present.
+ if (remoteImage && localImage) {
+ return this.isBlob(false, remoteImage)
+ ? localImage.path === remoteImage.path
+ : localImage.url === remoteImage;
+ }
+
+ // This will only handle the remaining three possible outcomes.
+ // (i.e. everything except when both image and localImage are present)
+ return !remoteImage && !localImage;
+ },
+};
diff --git a/browser/components/newtab/content-src/lib/section-menu-options.js b/browser/components/newtab/content-src/lib/section-menu-options.js
new file mode 100644
index 0000000000..9a3070a9f4
--- /dev/null
+++ b/browser/components/newtab/content-src/lib/section-menu-options.js
@@ -0,0 +1,93 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import { actionCreators as ac, actionTypes as at } from "common/Actions.jsm";
+
+/**
+ * List of functions that return items that can be included as menu options in a
+ * SectionMenu. All functions take the section as the only parameter.
+ */
+export const SectionMenuOptions = {
+ Separator: () => ({ type: "separator" }),
+ MoveUp: section => ({
+ id: "newtab-section-menu-move-up",
+ icon: "arrowhead-up",
+ action: ac.OnlyToMain({
+ type: at.SECTION_MOVE,
+ data: { id: section.id, direction: -1 },
+ }),
+ userEvent: "MENU_MOVE_UP",
+ disabled: !!section.isFirst,
+ }),
+ MoveDown: section => ({
+ id: "newtab-section-menu-move-down",
+ icon: "arrowhead-down",
+ action: ac.OnlyToMain({
+ type: at.SECTION_MOVE,
+ data: { id: section.id, direction: +1 },
+ }),
+ userEvent: "MENU_MOVE_DOWN",
+ disabled: !!section.isLast,
+ }),
+ RemoveSection: section => ({
+ id: "newtab-section-menu-remove-section",
+ icon: "dismiss",
+ action: ac.SetPref(section.showPrefName, false),
+ userEvent: "MENU_REMOVE",
+ }),
+ CollapseSection: section => ({
+ id: "newtab-section-menu-collapse-section",
+ icon: "minimize",
+ action: ac.OnlyToMain({
+ type: at.UPDATE_SECTION_PREFS,
+ data: { id: section.id, value: { collapsed: true } },
+ }),
+ userEvent: "MENU_COLLAPSE",
+ }),
+ ExpandSection: section => ({
+ id: "newtab-section-menu-expand-section",
+ icon: "maximize",
+ action: ac.OnlyToMain({
+ type: at.UPDATE_SECTION_PREFS,
+ data: { id: section.id, value: { collapsed: false } },
+ }),
+ userEvent: "MENU_EXPAND",
+ }),
+ ManageSection: section => ({
+ id: "newtab-section-menu-manage-section",
+ icon: "settings",
+ action: ac.OnlyToMain({ type: at.SETTINGS_OPEN }),
+ userEvent: "MENU_MANAGE",
+ }),
+ ManageWebExtension: section => ({
+ id: "newtab-section-menu-manage-webext",
+ icon: "settings",
+ action: ac.OnlyToMain({ type: at.OPEN_WEBEXT_SETTINGS, data: section.id }),
+ }),
+ AddTopSite: section => ({
+ id: "newtab-section-menu-add-topsite",
+ icon: "add",
+ action: { type: at.TOP_SITES_EDIT, data: { index: -1 } },
+ userEvent: "MENU_ADD_TOPSITE",
+ }),
+ AddSearchShortcut: section => ({
+ id: "newtab-section-menu-add-search-engine",
+ icon: "search",
+ action: { type: at.TOP_SITES_OPEN_SEARCH_SHORTCUTS_MODAL },
+ userEvent: "MENU_ADD_SEARCH",
+ }),
+ PrivacyNotice: section => ({
+ id: "newtab-section-menu-privacy-notice",
+ icon: "info",
+ action: ac.OnlyToMain({
+ type: at.OPEN_LINK,
+ data: { url: section.privacyNoticeURL },
+ }),
+ userEvent: "MENU_PRIVACY_NOTICE",
+ }),
+ CheckCollapsed: section =>
+ section.collapsed
+ ? SectionMenuOptions.ExpandSection(section)
+ : SectionMenuOptions.CollapseSection(section),
+};
diff --git a/browser/components/newtab/content-src/lib/selectLayoutRender.js b/browser/components/newtab/content-src/lib/selectLayoutRender.js
new file mode 100644
index 0000000000..f15fb777a5
--- /dev/null
+++ b/browser/components/newtab/content-src/lib/selectLayoutRender.js
@@ -0,0 +1,260 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+export const selectLayoutRender = ({ state = {}, prefs = {}, locale = "" }) => {
+ const { layout, feeds, spocs } = state;
+ let spocIndexPlacementMap = {};
+
+ /* This function fills spoc positions on a per placement basis with available spocs.
+ * It does this by looping through each position for a placement and replacing a rec with a spoc.
+ * If it runs out of spocs or positions, it stops.
+ * If it sees the same placement again, it remembers the previous spoc index, and continues.
+ * If it sees a blocked spoc, it skips that position leaving in a regular story.
+ */
+ function fillSpocPositionsForPlacement(
+ data,
+ spocsConfig,
+ spocsData,
+ placementName
+ ) {
+ if (
+ !spocIndexPlacementMap[placementName] &&
+ spocIndexPlacementMap[placementName] !== 0
+ ) {
+ spocIndexPlacementMap[placementName] = 0;
+ }
+ const results = [...data];
+ for (let position of spocsConfig.positions) {
+ const spoc = spocsData[spocIndexPlacementMap[placementName]];
+ // If there are no spocs left, we can stop filling positions.
+ if (!spoc) {
+ break;
+ }
+
+ // A placement could be used in two sections.
+ // In these cases, we want to maintain the index of the previous section.
+ // If we didn't do this, it might duplicate spocs.
+ spocIndexPlacementMap[placementName]++;
+
+ // A spoc that's blocked is removed from the source for subsequent newtab loads.
+ // If we have a spoc in the source that's blocked, it means it was *just* blocked,
+ // and in this case, we skip this position, and show a regular spoc instead.
+ if (!spocs.blocked.includes(spoc.url)) {
+ results.splice(position.index, 0, spoc);
+ }
+ }
+
+ return results;
+ }
+
+ const positions = {};
+ const DS_COMPONENTS = [
+ "Message",
+ "TextPromo",
+ "SectionTitle",
+ "Signup",
+ "Navigation",
+ "CardGrid",
+ "CollectionCardGrid",
+ "Hero",
+ "HorizontalRule",
+ "List",
+ ];
+
+ const filterArray = [];
+
+ if (!prefs["feeds.topsites"]) {
+ filterArray.push("TopSites");
+ }
+
+ if (!locale.startsWith("en-")) {
+ filterArray.push("Navigation");
+ }
+
+ const pocketEnabled =
+ prefs["feeds.section.topstories"] && prefs["feeds.system.topstories"];
+ if (!pocketEnabled) {
+ filterArray.push(...DS_COMPONENTS);
+ }
+
+ const placeholderComponent = component => {
+ if (!component.feed) {
+ // TODO we now need a placeholder for topsites and textPromo.
+ return {
+ ...component,
+ data: {
+ spocs: [],
+ },
+ };
+ }
+ const data = {
+ recommendations: [],
+ };
+
+ let items = 0;
+ if (component.properties && component.properties.items) {
+ items = component.properties.items;
+ }
+ for (let i = 0; i < items; i++) {
+ data.recommendations.push({ placeholder: true });
+ }
+
+ return { ...component, data };
+ };
+
+ // TODO update devtools to show placements
+ const handleSpocs = (data, component) => {
+ let result = [...data];
+ // Do we ever expect to possibly have a spoc.
+ if (
+ component.spocs &&
+ component.spocs.positions &&
+ component.spocs.positions.length
+ ) {
+ const placement = component.placement || {};
+ const placementName = placement.name || "spocs";
+ const spocsData = spocs.data[placementName];
+ // We expect a spoc, spocs are loaded, and the server returned spocs.
+ if (
+ spocs.loaded &&
+ spocsData &&
+ spocsData.items &&
+ spocsData.items.length
+ ) {
+ result = fillSpocPositionsForPlacement(
+ result,
+ component.spocs,
+ spocsData.items,
+ placementName
+ );
+ }
+ }
+ return result;
+ };
+
+ const handleComponent = component => {
+ if (
+ component.spocs &&
+ component.spocs.positions &&
+ component.spocs.positions.length
+ ) {
+ const placement = component.placement || {};
+ const placementName = placement.name || "spocs";
+ const spocsData = spocs.data[placementName];
+ if (
+ spocs.loaded &&
+ spocsData &&
+ spocsData.items &&
+ spocsData.items.length
+ ) {
+ return {
+ ...component,
+ data: {
+ spocs: spocsData.items
+ .filter(spoc => spoc && !spocs.blocked.includes(spoc.url))
+ .map((spoc, index) => ({
+ ...spoc,
+ pos: index,
+ })),
+ },
+ };
+ }
+ }
+ return {
+ ...component,
+ data: {
+ spocs: [],
+ },
+ };
+ };
+
+ const handleComponentWithFeed = component => {
+ positions[component.type] = positions[component.type] || 0;
+ let data = {
+ recommendations: [],
+ };
+
+ const feed = feeds.data[component.feed.url];
+ if (feed && feed.data) {
+ data = {
+ ...feed.data,
+ recommendations: [...(feed.data.recommendations || [])],
+ };
+ }
+
+ if (component && component.properties && component.properties.offset) {
+ data = {
+ ...data,
+ recommendations: data.recommendations.slice(
+ component.properties.offset
+ ),
+ };
+ }
+
+ data = {
+ ...data,
+ recommendations: handleSpocs(data.recommendations, component),
+ };
+
+ let items = 0;
+ if (component.properties && component.properties.items) {
+ items = Math.min(component.properties.items, data.recommendations.length);
+ }
+
+ // loop through a component items
+ // Store the items position sequentially for multiple components of the same type.
+ // Example: A second card grid starts pos offset from the last card grid.
+ for (let i = 0; i < items; i++) {
+ data.recommendations[i] = {
+ ...data.recommendations[i],
+ pos: positions[component.type]++,
+ };
+ }
+
+ return { ...component, data };
+ };
+
+ const renderLayout = () => {
+ const renderedLayoutArray = [];
+ for (const row of layout.filter(
+ r => r.components.filter(c => !filterArray.includes(c.type)).length
+ )) {
+ let components = [];
+ renderedLayoutArray.push({
+ ...row,
+ components,
+ });
+ for (const component of row.components.filter(
+ c => !filterArray.includes(c.type)
+ )) {
+ const spocsConfig = component.spocs;
+ if (spocsConfig || component.feed) {
+ // TODO make sure this still works for different loading cases.
+ if (
+ (component.feed && !feeds.data[component.feed.url]) ||
+ (spocsConfig &&
+ spocsConfig.positions &&
+ spocsConfig.positions.length &&
+ !spocs.loaded)
+ ) {
+ components.push(placeholderComponent(component));
+ return renderedLayoutArray;
+ }
+ if (component.feed) {
+ components.push(handleComponentWithFeed(component));
+ } else {
+ components.push(handleComponent(component));
+ }
+ } else {
+ components.push(component);
+ }
+ }
+ }
+ return renderedLayoutArray;
+ };
+
+ const layoutRender = renderLayout();
+
+ return { layoutRender };
+};
diff --git a/browser/components/newtab/content-src/styles/_OnboardingImages.scss b/browser/components/newtab/content-src/styles/_OnboardingImages.scss
new file mode 100644
index 0000000000..cd7fa48ad2
--- /dev/null
+++ b/browser/components/newtab/content-src/styles/_OnboardingImages.scss
@@ -0,0 +1,71 @@
+// Used for Trailhead and about:welcome
+
+.onboardingMessageImage {
+ &.addons {
+ background-image: url('chrome://activity-stream/content/data/content/assets/illustration-addons@2x.png');
+ }
+
+ &.privatebrowsing {
+ background-image: url('chrome://activity-stream/content/data/content/assets/illustration-privatebrowsing@2x.png');
+ }
+
+ &.screenshots {
+ background-image: url('chrome://activity-stream/content/data/content/assets/illustration-screenshots@2x.png');
+ }
+
+ &.gift {
+ background-image: url('chrome://activity-stream/content/data/content/assets/illustration-gift@2x.png');
+ }
+
+ &.sync {
+ background-image: url('chrome://activity-stream/content/data/content/assets/illustration-sync@2x.png');
+ }
+
+ &.devices {
+ background-image: url('chrome://activity-stream/content/data/content/assets/trailhead/card-illo-devices.svg');
+ }
+
+ &.fbcont {
+ background-image: url('chrome://activity-stream/content/data/content/assets/trailhead/card-illo-fbcont.svg');
+ }
+
+ &.import {
+ background-image: url('chrome://activity-stream/content/data/content/assets/trailhead/card-illo-import.svg');
+ }
+
+ &.ffmonitor {
+ background-image: url('chrome://activity-stream/content/data/content/assets/trailhead/card-illo-ffmonitor.svg');
+ }
+
+ &.ffsend {
+ background-image: url('chrome://activity-stream/content/data/content/assets/trailhead/card-illo-ffsend.svg');
+ }
+
+ &.lockwise {
+ background-image: url('chrome://activity-stream/content/data/content/assets/trailhead/card-illo-lockwise.svg');
+ }
+
+ &.mobile {
+ background-image: url('chrome://activity-stream/content/data/content/assets/trailhead/card-illo-mobile.svg');
+ }
+
+ &.pledge {
+ background-image: url('chrome://activity-stream/content/data/content/assets/trailhead/card-illo-pledge.svg');
+ }
+
+ &.pocket {
+ background-image: url('chrome://activity-stream/content/data/content/assets/trailhead/card-illo-pocket.svg');
+ }
+
+ &.private {
+ background-image: url('chrome://activity-stream/content/data/content/assets/trailhead/card-illo-private.svg');
+ }
+
+ &.sendtab {
+ background-image: url('chrome://activity-stream/content/data/content/assets/trailhead/card-illo-sendtab.svg');
+ }
+
+ &.tracking {
+ background-image: url('chrome://activity-stream/content/data/content/assets/trailhead/card-illo-tracking.svg');
+ }
+}
diff --git a/browser/components/newtab/content-src/styles/_activity-stream.scss b/browser/components/newtab/content-src/styles/_activity-stream.scss
new file mode 100644
index 0000000000..702ef9bdd1
--- /dev/null
+++ b/browser/components/newtab/content-src/styles/_activity-stream.scss
@@ -0,0 +1,179 @@
+@import './normalize';
+@import './variables';
+@import './theme';
+@import './icons';
+@import './mixins';
+
+html {
+ height: 100%;
+}
+
+body,
+#root { // sass-lint:disable-line no-ids
+ min-height: 100vh;
+}
+
+#root { // sass-lint:disable-line no-ids
+ position: relative;
+}
+
+body {
+ background-color: var(--newtab-background-color);
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Ubuntu', 'Helvetica Neue', sans-serif;
+ font-size: 16px;
+}
+
+.no-scroll {
+ overflow: hidden;
+}
+
+h1,
+h2 {
+ font-weight: normal;
+}
+
+a {
+ text-decoration: none;
+}
+
+.inner-border {
+ border: $border-secondary;
+ border-radius: $border-radius;
+ height: 100%;
+ left: 0;
+ pointer-events: none;
+ position: absolute;
+ top: 0;
+ width: 100%;
+ z-index: 100;
+}
+
+@keyframes fadeIn {
+ from {
+ opacity: 0;
+ }
+
+ to {
+ opacity: 1;
+ }
+}
+
+.show-on-init {
+ opacity: 0;
+ transition: opacity 0.2s ease-in;
+
+ &.on {
+ animation: fadeIn 0.2s;
+ opacity: 1;
+ }
+}
+
+.actions {
+ border-top: $border-secondary;
+ display: flex;
+ flex-direction: row;
+ flex-wrap: wrap;
+ justify-content: flex-start;
+ margin: 0;
+ padding: 15px 25px 0;
+}
+
+// Default button (grey)
+.button,
+.actions button {
+ background-color: var(--newtab-button-secondary-color);
+ border: $border-primary;
+ border-radius: 4px;
+ color: inherit;
+ cursor: pointer;
+ margin-bottom: 15px;
+ padding: 10px 30px;
+ white-space: nowrap;
+
+ &:hover:not(.dismiss),
+ &:focus:not(.dismiss) {
+ box-shadow: $shadow-primary;
+ transition: box-shadow 150ms;
+ }
+
+ &.dismiss {
+ background-color: transparent;
+ border: 0;
+ padding: 0;
+ text-decoration: underline;
+ }
+
+ // Blue button
+ &.primary,
+ &.done {
+ background-color: var(--newtab-button-primary-color);
+ border: solid 1px var(--newtab-button-primary-color);
+ color: $white;
+ margin-inline-start: auto;
+ }
+}
+
+input {
+ &[type='text'],
+ &[type='search'] {
+ border-radius: $border-radius;
+ }
+}
+
+// These styles are needed for -webkit-line-clamp to work correctly, so reuse
+// this class name while separately setting a clamp value via CSS or JS.
+.clamp {
+ -webkit-box-orient: vertical;
+ display: -webkit-box;
+ overflow: hidden;
+ word-break: break-word;
+}
+
+// Components
+@import '../components/A11yLinkButton/A11yLinkButton';
+@import '../components/Base/Base';
+@import '../components/ErrorBoundary/ErrorBoundary';
+@import '../components/TopSites/TopSites';
+@import '../components/Sections/Sections';
+@import '../components/Topics/Topics';
+@import '../components/Search/Search';
+@import '../components/ContextMenu/ContextMenu';
+@import '../components/ConfirmDialog/ConfirmDialog';
+@import '../components/CustomizeMenu/CustomizeMenu';
+@import '../components/Card/Card';
+@import '../components/CollapsibleSection/CollapsibleSection';
+@import '../components/ASRouterAdmin/ASRouterAdmin';
+@import '../components/PocketLoggedInCta/PocketLoggedInCta';
+@import '../components/MoreRecommendations/MoreRecommendations';
+@import '../components/DiscoveryStreamBase/DiscoveryStreamBase';
+
+// Discovery Stream Components
+@import '../components/DiscoveryStreamComponents/CardGrid/CardGrid';
+@import '../components/DiscoveryStreamComponents/CollectionCardGrid/CollectionCardGrid';
+@import '../components/DiscoveryStreamComponents/Hero/Hero';
+@import '../components/DiscoveryStreamComponents/Highlights/Highlights';
+@import '../components/DiscoveryStreamComponents/HorizontalRule/HorizontalRule';
+@import '../components/DiscoveryStreamComponents/List/List';
+@import '../components/DiscoveryStreamComponents/Navigation/Navigation';
+@import '../components/DiscoveryStreamComponents/SectionTitle/SectionTitle';
+@import '../components/DiscoveryStreamComponents/TopSites/TopSites';
+@import '../components/DiscoveryStreamComponents/DSLinkMenu/DSLinkMenu';
+@import '../components/DiscoveryStreamComponents/DSCard/DSCard';
+@import '../components/DiscoveryStreamComponents/DSContextFooter/DSContextFooter';
+@import '../components/DiscoveryStreamComponents/DSImage/DSImage';
+@import '../components/DiscoveryStreamComponents/DSDismiss/DSDismiss';
+@import '../components/DiscoveryStreamComponents/DSMessage/DSMessage';
+@import '../components/DiscoveryStreamImpressionStats/ImpressionStats';
+@import '../components/DiscoveryStreamComponents/DSEmptyState/DSEmptyState';
+@import '../components/DiscoveryStreamComponents/DSTextPromo/DSTextPromo';
+@import '../components/DiscoveryStreamComponents/DSSignup/DSSignup';
+@import '../components/DiscoveryStreamComponents/DSPrivacyModal/DSPrivacyModal';
+
+// AS Router
+@import '../asrouter/components/Button/Button';
+@import '../asrouter/components/SnippetBase/SnippetBase';
+@import '../asrouter/components/ModalOverlay/ModalOverlay';
+@import '../asrouter/templates/SimpleBelowSearchSnippet/SimpleBelowSearchSnippet';
+@import '../asrouter/templates/SimpleSnippet/SimpleSnippet';
+@import '../asrouter/templates/SubmitFormSnippet/SubmitFormSnippet';
+@import '../asrouter/templates/EOYSnippet/EOYSnippet';
diff --git a/browser/components/newtab/content-src/styles/_icons.scss b/browser/components/newtab/content-src/styles/_icons.scss
new file mode 100644
index 0000000000..f665dc5fb3
--- /dev/null
+++ b/browser/components/newtab/content-src/styles/_icons.scss
@@ -0,0 +1,208 @@
+.icon {
+ background-position: center center;
+ background-repeat: no-repeat;
+ background-size: $icon-size;
+ -moz-context-properties: fill;
+ display: inline-block;
+ color: var(--newtab-icon-primary-color);
+ fill: currentColor;
+ height: $icon-size;
+ vertical-align: middle;
+ width: $icon-size;
+
+ // helper classes
+ &.icon-spacer {
+ margin-inline-end: 8px;
+ }
+
+ &.icon-small-spacer {
+ margin-inline-end: 6px;
+ }
+
+ &.icon-button-style {
+ fill: var(--newtab-icon-secondary-color);
+ border: 0;
+
+ &:focus,
+ &:hover {
+ fill: var(--newtab-text-primary-color);
+ }
+ }
+
+ // icon images
+ &.icon-bookmark-added {
+ background-image: url('chrome://browser/skin/bookmark.svg');
+ }
+
+ &.icon-bookmark-hollow {
+ background-image: url('chrome://browser/skin/bookmark-hollow.svg');
+ }
+
+ &.icon-clear-input {
+ background-image: url('chrome://activity-stream/content/data/content/assets/glyph-cancel-16.svg');
+ }
+
+ &.icon-delete {
+ background-image: url('chrome://activity-stream/content/data/content/assets/glyph-delete-16.svg');
+ }
+
+ &.icon-search {
+ background-image: url('chrome://browser/skin/search-glass.svg');
+ }
+
+ &.icon-modal-delete {
+ flex-shrink: 0;
+ background-image: url('chrome://activity-stream/content/data/content/assets/glyph-modal-delete-32.svg');
+ background-size: $larger-icon-size;
+ height: $larger-icon-size;
+ width: $larger-icon-size;
+ }
+
+ &.icon-mail {
+ background-image: url('chrome://activity-stream/content/data/content/assets/glyph-mail-16.svg');
+ }
+
+ &.icon-dismiss {
+ background-image: url('chrome://activity-stream/content/data/content/assets/glyph-dismiss-16.svg');
+ }
+
+ &.icon-info {
+ background-image: url('chrome://activity-stream/content/data/content/assets/glyph-info-16.svg');
+ }
+
+ &.icon-new-window {
+ @include flip-icon;
+ background-image: url('chrome://activity-stream/content/data/content/assets/glyph-newWindow-16.svg');
+ }
+
+ &.icon-new-window-private {
+ background-image: url('chrome://browser/skin/privateBrowsing.svg');
+ }
+
+ &.icon-settings {
+ background-image: url('chrome://global/skin/icons/settings.svg');
+ }
+
+ &.icon-pin {
+ @include flip-icon;
+ background-image: url('chrome://activity-stream/content/data/content/assets/glyph-pin-16.svg');
+ }
+
+ &.icon-unpin {
+ @include flip-icon;
+ background-image: url('chrome://activity-stream/content/data/content/assets/glyph-unpin-16.svg');
+ }
+
+ &.icon-edit {
+ background-image: url('chrome://activity-stream/content/data/content/assets/glyph-edit-16.svg');
+ }
+
+ &.icon-pocket {
+ background-image: url('chrome://activity-stream/content/data/content/assets/glyph-pocket-16.svg');
+ }
+
+ &.icon-pocket-save {
+ background-image: url('chrome://activity-stream/content/data/content/assets/glyph-pocket-save-16.svg');
+ }
+
+ &.icon-pocket-delete {
+ background-image: url('chrome://activity-stream/content/data/content/assets/glyph-pocket-delete-16.svg');
+ }
+
+ &.icon-pocket-archive {
+ background-image: url('chrome://activity-stream/content/data/content/assets/glyph-pocket-archive-16.svg');
+ }
+
+ &.icon-history-item {
+ background-image: url('chrome://browser/skin/history.svg');
+ }
+
+ &.icon-trending {
+ background-image: url('chrome://activity-stream/content/data/content/assets/glyph-trending-16.svg');
+ transform: translateY(2px); // trending bolt is visually top heavy
+ }
+
+ &.icon-now {
+ background-image: url('chrome://browser/skin/history.svg');
+ }
+
+ &.icon-topsites {
+ background-image: url('chrome://activity-stream/content/data/content/assets/glyph-topsites-16.svg');
+ }
+
+ &.icon-pin-small {
+ @include flip-icon;
+ background-image: url('chrome://activity-stream/content/data/content/assets/glyph-pin-12.svg');
+ background-size: $smaller-icon-size;
+ height: $smaller-icon-size;
+ width: $smaller-icon-size;
+ }
+
+ &.icon-check {
+ background-image: url('chrome://global/skin/icons/check.svg');
+ }
+
+ &.icon-download {
+ background-image: url('chrome://browser/skin/downloads/download-icons.svg#arrow-with-bar');
+ }
+
+ &.icon-copy {
+ background-image: url('chrome://browser/skin/edit-copy.svg');
+ }
+
+ &.icon-open-file {
+ background-image: url('chrome://activity-stream/content/data/content/assets/glyph-open-file-16.svg');
+ }
+
+ &.icon-webextension {
+ background-image: url('chrome://activity-stream/content/data/content/assets/glyph-webextension-16.svg');
+ }
+
+ &.icon-highlights {
+ background-image: url('chrome://activity-stream/content/data/content/assets/glyph-highlights-16.svg');
+ }
+
+ &.icon-arrowhead-down {
+ background-image: url('chrome://activity-stream/content/data/content/assets/glyph-arrowhead-down-16.svg');
+ }
+
+ &.icon-arrowhead-down-small {
+ background-image: url('chrome://activity-stream/content/data/content/assets/glyph-arrowhead-down-12.svg');
+ background-size: $smaller-icon-size;
+ height: $smaller-icon-size;
+ width: $smaller-icon-size;
+ }
+
+ &.icon-arrowhead-forward-small {
+ background-image: url('chrome://activity-stream/content/data/content/assets/glyph-arrowhead-down-12.svg');
+ background-size: $smaller-icon-size;
+ height: $smaller-icon-size;
+ transform: rotate(-90deg);
+ width: $smaller-icon-size;
+
+ &:dir(rtl) {
+ transform: rotate(90deg);
+ }
+ }
+
+ &.icon-arrowhead-up {
+ background-image: url('chrome://activity-stream/content/data/content/assets/glyph-arrowhead-down-16.svg');
+ transform: rotate(180deg);
+ }
+
+ &.icon-add {
+ background-image: url('chrome://activity-stream/content/data/content/assets/glyph-add-16.svg');
+ }
+
+ &.icon-minimize {
+ background-image: url('chrome://activity-stream/content/data/content/assets/glyph-minimize-16.svg');
+ }
+
+ &.icon-maximize {
+ background-image: url('chrome://activity-stream/content/data/content/assets/glyph-maximize-16.svg');
+ }
+
+ &.icon-arrow {
+ background-image: url('chrome://activity-stream/content/data/content/assets/glyph-arrow.svg');
+ }
+}
diff --git a/browser/components/newtab/content-src/styles/_mixins.scss b/browser/components/newtab/content-src/styles/_mixins.scss
new file mode 100644
index 0000000000..0189408b06
--- /dev/null
+++ b/browser/components/newtab/content-src/styles/_mixins.scss
@@ -0,0 +1,50 @@
+// Shared styling of article images shown as background
+@mixin image-as-background {
+ background-color: var(--newtab-card-placeholder-color);
+ background-position: center;
+ background-repeat: no-repeat;
+ background-size: cover;
+ border-radius: 4px;
+ box-shadow: inset 0 0 0 0.5px $black-15;
+}
+
+// Note: lineHeight and fontSize should be unitless but can be derived from pixel values
+// Bug 1550624 to clean up / remove this mixin to avoid duplicate styles
+@mixin limit-visible-lines($line-count, $line-height, $font-size) {
+ font-size: $font-size * 1px;
+ -webkit-line-clamp: $line-count;
+ line-height: $line-height * 1px;
+}
+
+@mixin dark-theme-only {
+ [lwt-newtab-brighttext] & {
+ @content;
+ }
+}
+
+@mixin ds-border-top {
+ @content;
+
+ @include dark-theme-only {
+ border-top: 1px solid $grey-60;
+ }
+
+ border-top: 1px solid $grey-30;
+}
+
+@mixin ds-border-bottom {
+ @content;
+
+ @include dark-theme-only {
+ border-bottom: 1px solid $grey-60;
+ }
+
+ border-bottom: 1px solid $grey-30;
+}
+
+@mixin ds-fade-in($halo-color: $blue-50-30) {
+ box-shadow: 0 0 0 5px $halo-color;
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none;
+}
diff --git a/browser/components/newtab/content-src/styles/_normalize.scss b/browser/components/newtab/content-src/styles/_normalize.scss
new file mode 100644
index 0000000000..32f5ef3677
--- /dev/null
+++ b/browser/components/newtab/content-src/styles/_normalize.scss
@@ -0,0 +1,29 @@
+html {
+ box-sizing: border-box;
+}
+
+*,
+*::before,
+*::after {
+ box-sizing: inherit;
+}
+
+*::-moz-focus-inner {
+ border: 0;
+}
+
+body {
+ margin: 0;
+}
+
+button,
+input {
+ background-color: inherit;
+ color: inherit;
+ font-family: inherit;
+ font-size: inherit;
+}
+
+[hidden] {
+ display: none !important; // sass-lint:disable-line no-important
+}
diff --git a/browser/components/newtab/content-src/styles/_theme.scss b/browser/components/newtab/content-src/styles/_theme.scss
new file mode 100644
index 0000000000..29e313873e
--- /dev/null
+++ b/browser/components/newtab/content-src/styles/_theme.scss
@@ -0,0 +1,231 @@
+@function textbox-shadow($color) {
+ @return 0 0 0 1px $color, 0 0 0 $textbox-shadow-size rgba($color, 0.3);
+}
+
+@mixin textbox-focus($color) {
+ --newtab-textbox-focus-color: #{$color};
+ --newtab-textbox-focus-boxshadow: #{textbox-shadow($color)};
+}
+
+// scss variables related to the theme.
+$border-primary: 1px solid var(--newtab-border-primary-color);
+$border-secondary: 1px solid var(--newtab-border-secondary-color);
+$inner-box-shadow: 0 0 0 1px var(--newtab-inner-box-shadow-color);
+$inner-box-shadow-nte: 0 3px 8px var(--newtab-inner-box-shadow-color-nte);
+$tile-shadow-second: 0 0 2px var(--newtab-tile-shadow-secondary);
+$input-border: 1px solid var(--newtab-textbox-border);
+$input-border-active: 1px solid var(--newtab-textbox-focus-color);
+$input-error-border: 1px solid $red-60;
+$input-error-boxshadow: textbox-shadow($red-60);
+$shadow-primary: 0 0 0 5px var(--newtab-card-active-outline-color);
+$shadow-secondary: 0 1px 4px 0 $grey-90-20;
+
+// Default theme
+body {
+ // General styles
+ --newtab-background-color: #{$grey-10};
+ --newtab-border-primary-color: #{$grey-40};
+ --newtab-border-secondary-color: #{$grey-30};
+ --newtab-element-active-color: #{$grey-30-60};
+ --newtab-element-hover-color: #{$grey-20};
+ --newtab-icon-primary-color: #{$grey-90-80};
+ --newtab-icon-secondary-color: #{$grey-90-60};
+ --newtab-icon-tertiary-color: #{$grey-30};
+ --newtab-inner-box-shadow-color: #{$black-10};
+ --newtab-inner-box-shadow-color-nte: #{$newtab-card-firstshadow};
+ --newtab-tile-shadow-secondary: #{$newtab-tile-shadow-secondary};
+
+ --newtab-link-primary-color: #{$blue-60};
+ --newtab-link-secondary-color: #{$teal-70};
+ --newtab-text-conditional-color: #{$grey-60};
+ --newtab-text-primary-color: #{$grey-90};
+ --newtab-text-secondary-color: #{$grey-50};
+ --newtab-textbox-background-color: #{$white};
+ --newtab-textbox-border: #{$grey-90-20};
+ @include textbox-focus($blue-60); // sass-lint:disable-line mixins-before-declarations
+
+ // Background buttons
+ --newtab-background-button-color: #{$newtab-background-button-default-color};
+ --newtab-background-button-text-color: #{$newtab-background-button-default-text-color};
+ --newtab-background-button-hover-color: #{$newtab-background-button-default-hover-color};
+ --newtab-background-button-active-color: #{$newtab-background-button-default-active-color};
+
+ // Buttons
+ --newtab-button-primary-color: #{$blue-60};
+ --newtab-button-secondary-color: inherit;
+ // Feed buttons
+ --newtab-feed-button-background: #{$grey-20};
+ --newtab-feed-button-text: #{$grey-90};
+ --newtab-feed-button-background-faded: #{$grey-20-60};
+ --newtab-feed-button-text-faded: #{$grey-90-00};
+ --newtab-feed-button-spinner: #{$grey-50};
+
+
+ // Context menu
+ --newtab-contextmenu-background-color: #{$grey-10};
+ --newtab-contextmenu-button-color: #{$white};
+
+ // Modal + overlay
+ --newtab-modal-color: #{$white};
+ --newtab-overlay-color: #{$grey-20-80};
+
+ // Sections
+ --newtab-section-header-text-color: #{$grey-50};
+ --newtab-section-navigation-text-color: #{$grey-50};
+ --newtab-section-active-contextmenu-color: #{$grey-90};
+
+ // Search
+ --newtab-search-border-color: transparent;
+ --newtab-search-dropdown-color: #{$white};
+ --newtab-search-dropdown-header-color: #{$grey-10};
+ --newtab-search-header-background-color: #{$grey-10-95};
+ --newtab-search-icon-color: #{$grey-90-40};
+ --newtab-search-wordmark-color: #{$firefox-wordmark-default-color};
+
+ // Top Sites
+ --newtab-topsites-background-color: #{$white};
+ --newtab-topsites-icon-shadow: inset #{$inner-box-shadow};
+ --newtab-topsites-label-color: inherit;
+ --newtab-topsites-outer-card-hover: #{$newtab-card-hover-color};
+ --newtab-topsites-context-menu-hover: #{$newtab-card-hover-color};
+
+ // Cards
+ --newtab-card-active-outline-color: #{$grey-30};
+ --newtab-card-background-color: #{$white};
+ --newtab-card-hairline-color: #{$black-10};
+ --newtab-card-placeholder-color: #{$grey-30};
+ --newtab-card-shadow: 0 1px 4px 0 #{$grey-90-10};
+
+ // Snippets
+ --newtab-snippets-background-color: #{$white};
+ --newtab-snippets-hairline-color: transparent;
+
+ // New New Tab
+ --newtab-background-primary-text-color: #{$newtab-background-primary-text-color};
+ --newtab-focus-outline: #{$newtab-focus-outline-color};
+ --newtab-focus-border: #{$blue-60};
+ --newtab-focus-border-selected: #{$newtab-card-tint};
+ --newtab-seperator-line-color: #{$newtab-card-separator-line-color};
+ --newtab-primary-action-background: #{$blue-60};
+ --newtab-primary-action-background-off: #{$newtab-primary-action-background-off};
+ --customize-menu-primary-text-color: #{$newtab-card-primary-text-color};
+ --customize-menu-check-fill: #{$white};
+ --customize-menu-background: #{$white};
+ --customize-menu-secondary-action-background: #{$grey-10};
+ --customize-menu-secondary-action-background-hover: #{$grey-20};
+ --customize-menu-secondary-action-background-active: #{$newtab-card-secondary-action-background-active};
+ --customize-menu-seperator-line-color: #{$newtab-card-separator-line-color};
+ --customize-menu-first-shadow: #{$newtab-card-firstshadow};
+ --customize-menu-second-shadow: #{$newtab-card-secondshadow};
+ --customize-menu-primary-action-text: #{$white};
+ --customize-menu-line-color: #{$newtab-card-line-color};
+ --newtab-search-first-shadow: #{$newtab-card-firstshadow};
+ --newtab-search-second-shadow: #{$newtab-card-secondshadow};
+ --newtab-search-text-color: #{$newtab-card-secondary-text-color};
+ --newtab-card-first-shadow: #{$newtab-card-firstshadow};
+ --newtab-card-second-shadow: #{$newtab-card-secondshadow};
+ --newtab-wordmark-color: #{$newtab-wordmark-default-color};
+
+ &[lwt-newtab-brighttext] {
+ // General styles
+ --newtab-background-color: #{$grey-80};
+ --newtab-border-primary-color: #{$grey-10-80};
+ --newtab-border-secondary-color: #{$grey-10-10};
+ --newtab-button-primary-color: #{$blue-60};
+ --newtab-button-secondary-color: #{$grey-70};
+ --newtab-element-active-color: #{$grey-10-20};
+ --newtab-element-hover-color: #{$grey-10-10};
+ --newtab-icon-primary-color: #{$grey-10-80};
+ --newtab-icon-secondary-color: #{$grey-10-40};
+ --newtab-icon-tertiary-color: #{$grey-10-40};
+ --newtab-inner-box-shadow-color: #{$grey-10-20};
+ --newtab-inner-box-shadow-color-nte: #{$newtab-card-darktheme-firstshadow};
+ --newtab-tile-shadow-secondary: #{$newtab-tile-darktheme-shadow-secondary};
+ --newtab-link-primary-color: #{$blue-40};
+ --newtab-link-secondary-color: #{$pocket-teal};
+ --newtab-text-conditional-color: #{$grey-10};
+ --newtab-text-primary-color: #{$grey-10};
+ --newtab-text-secondary-color: #{$grey-10-80};
+ --newtab-textbox-background-color: #{$grey-70};
+ --newtab-textbox-border: #{$grey-10-20};
+ @include textbox-focus($blue-40); // sass-lint:disable-line mixins-before-declarations
+
+ // Background buttons.
+ --newtab-background-button-color: #{$newtab-background-button-darktheme-color};
+ --newtab-background-button-text-color: #{$newtab-background-button-darktheme-text-color};
+ --newtab-background-button-hover-color: #{$newtab-background-button-darktheme-hover-color};
+ --newtab-background-button-active-color: #{$newtab-background-button-darktheme-active-color};
+
+ // Feed buttons
+ --newtab-feed-button-background: #{$grey-70};
+ --newtab-feed-button-text: #{$grey-10};
+ --newtab-feed-button-background-faded: #{$grey-70-60};
+ --newtab-feed-button-text-faded: #{$grey-10-00};
+ --newtab-feed-button-spinner: #{$grey-30};
+
+ // Context menu
+ --newtab-contextmenu-background-color: #{$grey-60};
+ --newtab-contextmenu-button-color: #{$grey-80};
+
+ // Modal + overlay
+ --newtab-modal-color: #{$grey-80};
+ --newtab-overlay-color: #{$grey-90-80};
+
+ // Sections
+ --newtab-section-header-text-color: #{$grey-10-80};
+ --newtab-section-navigation-text-color: #{$grey-10-80};
+ --newtab-section-active-contextmenu-color: #{$white};
+
+ // Search
+ --newtab-search-border-color: #{$grey-10-20};
+ --newtab-search-dropdown-color: #{$grey-70};
+ --newtab-search-dropdown-header-color: #{$grey-60};
+ --newtab-search-header-background-color: #{$grey-80-95};
+ --newtab-search-icon-color: #{$grey-10-60};
+ --newtab-search-wordmark-color: #{$firefox-wordmark-darktheme-color};
+
+ // Top Sites
+ --newtab-topsites-background-color: #{$grey-70};
+ --newtab-topsites-icon-shadow: none;
+ --newtab-topsites-label-color: #{$grey-10-80};
+ --newtab-topsites-outer-card-hover: #{$newtab-card-darktheme-hover-color};
+ --newtab-topsites-context-menu-hover: #{$newtab-card-darktheme-hover-color};
+
+ // Cards
+ --newtab-card-active-outline-color: #{$grey-60};
+ --newtab-card-background-color: #{$grey-70};
+ --newtab-card-hairline-color: #{$grey-10-10};
+ --newtab-card-placeholder-color: #{$grey-60};
+ --newtab-card-shadow: 0 1px 8px 0 #{$grey-90-20};
+
+ // Snippets
+ --newtab-snippets-background-color: #{$grey-70};
+ --newtab-snippets-hairline-color: #{$white-10};
+
+ // New New Tab
+ --newtab-background-primary-text-color: #{$newtab-background-darktheme-primary-text-color};
+ --newtab-focus-outline: #{$newtab-darktheme-focus-outline-color};
+ --newtab-focus-border: #{$newtab-darktheme-focus-border};
+ --newtab-focus-border-selected: #{$newtab-darktheme-focus-border-selected};
+ --newtab-primary-action-background: #{$newtab-darktheme-primary-action-background};
+ --newtab-primary-action-background-off: #{$newtab-darktheme-primary-action-background-off};
+ --newtab-seperator-line-color: #{$newtab-card-darktheme-separator-line-color};
+ --customize-menu-primary-text-color: #{$newtab-card-darktheme-primary-text-color};
+ --customize-menu-check-fill: #{$newtab-card-darktheme-primary-text-color};
+ --customize-menu-background: #{$grey-70};
+ --customize-menu-secondary-action-background: #{$newtab-card-darktheme-secondary-action-background};
+ --customize-menu-secondary-action-background-hover: #{$newtab-card-darktheme-secondary-action-background-hover};
+ --customize-menu-secondary-action-background-active: #{$newtab-card-darktheme-secondary-action-background-active};
+ --customize-menu-seperator-line-color: #{$newtab-card-darktheme-separator-line-color};
+ --customize-menu-first-shadow: #{$newtab-card-darktheme-firstshadow};
+ --customize-menu-second-shadow: #{$newtab-darktheme-card-secondshadow};
+ --customize-menu-primary-action-text: #{$newtab-card-darktheme-primary-text-color};
+ --customize-menu-line-color: #{$newtab-card-darktheme-line-color};
+ --newtab-search-first-shadow: #{$newtab-card-darktheme-firstshadow};
+ --newtab-search-second-shadow: #{$newtab-darktheme-card-secondshadow};
+ --newtab-search-text-color: #{$newtab-card-darktheme-secondary-text-color};
+ --newtab-card-first-shadow: #{$newtab-card-darktheme-firstshadow};
+ --newtab-card-second-shadow: #{$newtab-darktheme-card-secondshadow};
+ --newtab-wordmark-color: #{$firefox-wordmark-darktheme-color};
+ }
+}
diff --git a/browser/components/newtab/content-src/styles/_variables.scss b/browser/components/newtab/content-src/styles/_variables.scss
new file mode 100644
index 0000000000..b43b9fe924
--- /dev/null
+++ b/browser/components/newtab/content-src/styles/_variables.scss
@@ -0,0 +1,323 @@
+// Photon colors from http://design.firefox.com/photon/visuals/color.html
+$blue-40: #45A1FF;
+$blue-50: #0A84FF;
+$blue-60: #0060DF;
+$blue-70: #003EAA;
+$blue-80: #002275;
+$grey-10: #F9F9FA;
+$grey-20: #EDEDF0;
+$grey-30: #D7D7DB;
+$grey-40: #B1B1B3;
+$grey-50: #737373;
+$grey-60: #4A4A4F;
+$grey-70: #38383D;
+$grey-80: #2A2A2E;
+$grey-90: #0C0C0D;
+$teal-10: #A7FFFE;
+$teal-60: #00C8D7;
+$teal-70: #008EA4;
+$teal-80: #005A71;
+$red-60: #D70022;
+$yellow-50: #FFE900;
+$violet-20: #CB9EFF;
+
+// Photon opacity from http://design.firefox.com/photon/visuals/color.html#opacity
+$grey-10-00: rgba($grey-10, 0);
+$grey-10-10: rgba($grey-10, 0.1);
+$grey-10-20: rgba($grey-10, 0.2);
+$grey-10-30: rgba($grey-10, 0.3);
+$grey-10-40: rgba($grey-10, 0.4);
+$grey-10-50: rgba($grey-10, 0.5);
+$grey-10-60: rgba($grey-10, 0.6);
+$grey-10-80: rgba($grey-10, 0.8);
+$grey-10-95: rgba($grey-10, 0.95);
+$grey-20-60: rgba($grey-20, 0.6);
+$grey-20-80: rgba($grey-20, 0.8);
+$grey-30-60: rgba($grey-30, 0.6);
+$grey-60-60: rgba($grey-60, 0.6);
+$grey-60-70: rgba($grey-60, 0.7);
+$grey-70-40: rgba($grey-70, 0.4);
+$grey-70-60: rgba($grey-70, 0.6);
+$grey-80-95: rgba($grey-80, 0.95);
+$grey-90-00: rgba($grey-90, 0);
+$grey-90-10: rgba($grey-90, 0.1);
+$grey-90-20: rgba($grey-90, 0.2);
+$grey-90-30: rgba($grey-90, 0.3);
+$grey-90-40: rgba($grey-90, 0.4);
+$grey-90-50: rgba($grey-90, 0.5);
+$grey-90-60: rgba($grey-90, 0.6);
+$grey-90-70: rgba($grey-90, 0.7);
+$grey-90-80: rgba($grey-90, 0.8);
+$grey-90-90: rgba($grey-90, 0.9);
+
+$blue-40-40: rgba($blue-40, 0.4);
+$blue-50-50: rgba($blue-50, 0.5);
+$blue-50-30: rgba($blue-50, 0.3);
+$blue-50-50: rgba($blue-50, 0.5);
+
+$black: #000;
+$black-5: rgba($black, 0.05);
+$black-10: rgba($black, 0.1);
+$black-12: rgba($black, 0.12);
+$black-15: rgba($black, 0.15);
+$black-20: rgba($black, 0.2);
+$black-25: rgba($black, 0.25);
+$black-30: rgba($black, 0.3);
+
+// Other colors
+$white: #FFF;
+$white-0: rgba($white, 0);
+$white-10: rgba($white, 0.1);
+$white-50: rgba($white, 0.5);
+$white-60: rgba($white, 0.6);
+$white-70: rgba($white, 0.7);
+$white-100: rgba($white, 1);
+$ghost-white: #FAFAFC;
+$pocket-teal: #50BCB6;
+$pocket-red: #EF4056;
+$shadow-10: rgba(12, 12, 13, 0.1);
+$bookmark-icon-fill: #0A84FF;
+$download-icon-fill: #12BC00;
+$pocket-icon-fill: #D70022;
+$email-input-focus: rgba($blue-50, 0.3);
+$email-input-invalid: rgba($red-60, 0.3);
+$aw-extra-blue-1: #004EC2;
+$aw-extra-blue-2: #0080FF;
+$aw-extra-blue-3: #00C7FF;
+$about-welcome-gradient: linear-gradient(to bottom, $blue-70 40%, $aw-extra-blue-1 60%, $blue-60 80%, $aw-extra-blue-2 90%, $aw-extra-blue-3 100%);
+$about-welcome-extra-links: #676F7E;
+$firefox-wordmark-default-color: #363959;
+$firefox-wordmark-darktheme-color: $white;
+
+// New New Tab Experience colors.
+$newtab-background-button-default-color: rgba(223, 223, 223, 0.5);
+$newtab-background-button-darktheme-color: rgba(80, 80, 80, 0.5);
+$newtab-background-button-default-text-color: #484848;
+$newtab-background-button-darktheme-text-color: #CDCDD4;
+$newtab-background-button-default-hover-color: rgba(196, 196, 196, 0.5);
+$newtab-background-button-darktheme-hover-color: rgba(114, 114, 114, 0.5);
+$newtab-background-button-default-active-color: rgba(151, 151, 151, 0.5);
+$newtab-background-button-darktheme-active-color: rgba(173, 173, 173, 0.5);
+$newtab-background-primary-text-color: #151515;
+$newtab-background-darktheme-primary-text-color: #CDCDD4;
+$newtab-wordmark-default-color: #20123A;
+
+$newtab-card-primary-text-color: #20123A;
+$newtab-card-darktheme-primary-text-color: #E0E0E6;
+$newtab-card-line-color: #716F87;
+$newtab-card-darktheme-line-color: #B9B7CC;
+$newtab-card-separator-line-color: #E1E0E6;
+$newtab-card-darktheme-separator-line-color: #53515F;
+$newtab-card-tint: rgba(0, 0, 0, 0.15);
+$newtab-card-firstshadow: rgba(9, 32, 77, 0.12);
+$newtab-card-darktheme-firstshadow: rgba(21, 20, 26, 0.5);
+$newtab-card-secondshadow: rgba(29, 17, 51, 0.12);
+$newtab-darktheme-card-secondshadow: rgba(21, 20, 26, 0.75);
+$newtab-focus-outline-color: rgba(0, 96, 223, 0.25);
+$newtab-darktheme-focus-outline-color: rgba(80, 145, 241, 0.5);
+$newtab-darktheme-focus-border: #B5D3FF;
+$newtab-darktheme-focus-border-selected: #B5D3FF;
+$newtab-darktheme-primary-action-background: #4484E2;
+$newtab-primary-action-background-off: #E9E9E9;
+$newtab-darktheme-primary-action-background-off: #6A6A6F;
+$newtab-card-darktheme-secondary-action-background: #515156;
+$newtab-card-darktheme-secondary-action-background-hover: #606065;
+$newtab-card-secondary-action-background-active: #E2E2E6;
+$newtab-card-darktheme-secondary-action-background-active: #6F6F74;
+$newtab-card-darktheme-hover-color: rgba(180, 180, 180, 0.1);
+$newtab-card-hover-color: rgba(0, 0, 0, 0.05);
+$newtab-tile-shadow-secondary: rgba(29, 17, 51, 0.2);
+$newtab-tile-darktheme-shadow-secondary: rgba(21, 20, 26, 0.75);
+$newtab-card-secondary-text-color: #585165;
+$newtab-card-darktheme-secondary-text-color: #B1B1BD;
+
+// Photon transitions from http://design.firefox.com/photon/motion/duration-and-easing.html
+$photon-easing: cubic-bezier(0.07, 0.95, 0, 1);
+
+$border-radius: 3px;
+$border-radius-new: 8px;
+
+// Grid related styles
+$base-gutter: 32px;
+$section-horizontal-padding: 25px;
+$section-vertical-padding: 10px;
+$section-spacing: 40px - $section-vertical-padding * 2;
+$grid-unit: 96px; // 1 top site
+// New Tab Experience grid unit needs to be smaller, but for now we are changing this UI with a pref, so requires duplication.
+$grid-unit-small: 80px; // 1 top site
+
+$icon-size: 16px;
+$smaller-icon-size: 12px;
+$larger-icon-size: 32px;
+
+$searchbar-width-small: $grid-unit * 2 + $base-gutter * 1;
+$searchbar-width-medium: $grid-unit * 4 + $base-gutter * 3;
+$searchbar-width-large: $grid-unit * 6 + $base-gutter * 5;
+
+$searchbar-width-small-new: ($grid-unit * 2 + $base-gutter * 1) - 24px;
+$searchbar-width-medium-new: ($grid-unit * 4 + $base-gutter * 3) - 120px;
+$searchbar-width-large-new: ($grid-unit * 6 + $base-gutter * 5) - 136px;
+$searchbar-width-largest-new: ($grid-unit * 6 + $base-gutter * 5) - 16px;
+
+$wrapper-default-width: $grid-unit * 2 + $base-gutter * 1 + $section-horizontal-padding * 2; // 2 top sites
+$wrapper-max-width-medium: $grid-unit * 4 + $base-gutter * 3 + $section-horizontal-padding * 2; // 4 top sites
+$wrapper-max-width-large: $grid-unit * 6 + $base-gutter * 5 + $section-horizontal-padding * 2; // 6 top sites
+$wrapper-max-width-widest: $grid-unit * 8 + $base-gutter * 7 + $section-horizontal-padding * 2; // 8 top sites
+// For the breakpoints, we need to add space for the scrollbar to avoid weird
+// layout issues when the scrollbar is visible. 16px is wide enough to cover all
+// OSes and keeps it simpler than a per-OS value.
+$scrollbar-width: 16px;
+
+// Breakpoints
+// If updating these breakpoints, don't forget to update uses of DSImage, which
+// might choose the right image src to use depending on the viewport size.
+$break-point-medium: $wrapper-max-width-medium + $base-gutter * 2 + $scrollbar-width; // 610px
+$break-point-large: $wrapper-max-width-large + $base-gutter * 2 + $scrollbar-width; // 866px
+$break-point-widest: $wrapper-max-width-widest + $base-gutter * 2 + $scrollbar-width; // 1122px
+
+$section-title-font-size: 13px;
+
+$card-width: $grid-unit * 2 + $base-gutter;
+$card-width-nte: $grid-unit-small * 2 + $base-gutter;
+
+$card-height: 266px;
+$card-preview-image-height: 122px;
+$card-title-margin: 2px;
+$card-text-line-height: 19px;
+// Larger cards for wider screens:
+$card-width-large: 309px;
+$card-height-large: 370px;
+$card-preview-image-height-large: 155px;
+// Compact cards for Highlights
+$card-height-compact: 160px;
+$card-preview-image-height-compact: 108px;
+
+$topic-margin-top: 12px;
+
+$context-menu-button-size: 27px;
+$context-menu-button-boxshadow: 0 2px $grey-90-10;
+$context-menu-shadow: 0 5px 10px $black-30, 0 0 0 1px $black-20;
+$context-menu-font-size: 14px;
+$context-menu-border-radius: 5px;
+$context-menu-outer-padding: 5px;
+$context-menu-item-padding: 3px 12px;
+
+$error-fallback-font-size: 12px;
+$error-fallback-line-height: 1.5;
+
+$image-path: 'chrome://activity-stream/content/data/content/assets/';
+
+$snippets-container-height: 120px;
+
+$textbox-shadow-size: 4px;
+
+$customize-menu-slide-bezier: cubic-bezier(0.46, 0.03, 0.52, 0.96);
+$customize-menu-expand-bezier: cubic-bezier(0.82, 0.085, 0.395, 0.895);
+$customize-menu-border-tint: 1px solid $newtab-card-tint;
+
+@mixin fade-in {
+ box-shadow: inset $inner-box-shadow, $shadow-primary;
+ transition: box-shadow 150ms;
+}
+
+@mixin fade-in-card {
+ box-shadow: $shadow-primary;
+ transition: box-shadow 150ms;
+}
+
+@mixin ds-focus-nte {
+ border: 0;
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-focus-outline), 0 0 0 1px var(--newtab-focus-border);
+}
+
+@mixin context-menu-button-newtab-experience {
+ .context-menu-button {
+ background-image: url('chrome://global/skin/icons/more.svg');
+ border: 0;
+ border-radius: 4px;
+ cursor: pointer;
+ fill: var(--newtab-icon-primary-color);
+ -moz-context-properties: fill;
+ height: 20px;
+ width: 20px;
+ inset-inline-end: -9px;
+ opacity: 0;
+ position: absolute;
+ top: -20px;
+ transition: opacity 200ms;
+
+ &:is(:active, :focus) {
+ outline: 0;
+ opacity: 1;
+ background-color: var(--newtab-topsites-context-menu-hover);
+ fill: var(--newtab-primary-action-background);
+ }
+ }
+}
+
+@mixin context-menu-button {
+ .context-menu-button {
+ background-clip: padding-box;
+ background-color: var(--newtab-contextmenu-button-color);
+ background-image: url('chrome://global/skin/icons/more.svg');
+ background-position: 55%;
+ border: $border-primary;
+ border-radius: 100%;
+ box-shadow: $context-menu-button-boxshadow;
+ cursor: pointer;
+ fill: var(--newtab-icon-primary-color);
+ height: $context-menu-button-size;
+ inset-inline-end: -($context-menu-button-size / 2);
+ opacity: 0;
+ position: absolute;
+ top: -($context-menu-button-size / 2);
+ transform: scale(0.25);
+ transition-duration: 150ms;
+ transition-property: transform, opacity;
+ width: $context-menu-button-size;
+
+ &:is(:active, :focus) {
+ opacity: 1;
+ transform: scale(1);
+ }
+ }
+}
+
+@mixin context-menu-button-hover {
+ .context-menu-button {
+ opacity: 1;
+ transform: scale(1);
+ transition-delay: 333ms;
+ }
+}
+
+@mixin nt-experience-context-menu-button-hover {
+ .context-menu-button {
+ opacity: 1;
+ }
+}
+
+@mixin context-menu-open-middle {
+ .context-menu {
+ margin-inline-end: auto;
+ margin-inline-start: auto;
+ inset-inline-end: auto;
+ inset-inline-start: -$base-gutter;
+ }
+}
+
+@mixin context-menu-open-left {
+ .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto;
+ }
+}
+
+@mixin flip-icon {
+ &:dir(rtl) {
+ transform: scaleX(-1);
+ }
+}
diff --git a/browser/components/newtab/content-src/styles/activity-stream-linux.scss b/browser/components/newtab/content-src/styles/activity-stream-linux.scss
new file mode 100644
index 0000000000..aaff2d2efe
--- /dev/null
+++ b/browser/components/newtab/content-src/styles/activity-stream-linux.scss
@@ -0,0 +1,13 @@
+// sass-lint:disable no-css-comments
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* This is the linux variant */
+// sass-lint:enable no-css-comments
+
+$os-infopanel-arrow-height: 10px;
+$os-infopanel-arrow-offset-end: 6px;
+$os-infopanel-arrow-width: 20px;
+
+@import './activity-stream';
diff --git a/browser/components/newtab/content-src/styles/activity-stream-mac.scss b/browser/components/newtab/content-src/styles/activity-stream-mac.scss
new file mode 100644
index 0000000000..1c19e514fb
--- /dev/null
+++ b/browser/components/newtab/content-src/styles/activity-stream-mac.scss
@@ -0,0 +1,17 @@
+// sass-lint:disable no-css-comments
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* This is the mac variant */
+// sass-lint:enable no-css-comments
+
+$os-infopanel-arrow-height: 10px;
+$os-infopanel-arrow-offset-end: 7px;
+$os-infopanel-arrow-width: 18px;
+
+[lwt-newtab-brighttext] {
+ -moz-osx-font-smoothing: grayscale;
+}
+
+@import './activity-stream';
diff --git a/browser/components/newtab/content-src/styles/activity-stream-windows.scss b/browser/components/newtab/content-src/styles/activity-stream-windows.scss
new file mode 100644
index 0000000000..10b8f61ef4
--- /dev/null
+++ b/browser/components/newtab/content-src/styles/activity-stream-windows.scss
@@ -0,0 +1,13 @@
+// sass-lint:disable no-css-comments
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* This is the windows variant */
+// sass-lint:enable no-css-comments
+
+$os-infopanel-arrow-height: 10px;
+$os-infopanel-arrow-offset-end: 6px;
+$os-infopanel-arrow-width: 20px;
+
+@import './activity-stream';
diff --git a/browser/components/newtab/contributing.md b/browser/components/newtab/contributing.md
new file mode 100644
index 0000000000..60ef4754ee
--- /dev/null
+++ b/browser/components/newtab/contributing.md
@@ -0,0 +1,154 @@
+# Contributing to Activity Stream
+
+Activity Stream is an enhancement to the functionality of Firefox's about:newtab page. We welcome new 'streamers' to contribute to the project!
+
+## Where to ask questions
+
+- Most of the core dev team can be found on the `#activity-stream` channel on `irc.mozilla.org`.
+ You can also direct message the core team (`dmose`, `emtwo`, `jkerim`, `k88hudson`, `Mardak`, `nanj`, `r1cky`, `ursula`, `andreio`)
+ or our manager (`tspurway`)
+- Slack channel (staff only): #activitystream
+- Mailing List: [activity-stream-dev](https://groups.google.com/a/mozilla.com/d/forum/activity-stream-dev)
+- File issues/questions on Github: https://github.com/mozilla/activity-stream/issues. We typically triage new issues every Monday.
+
+## Architecture ##
+
+Activity Stream is a Firefox system add-on. One of the cool things about Activity Stream is that the
+[content side of the add-on](https://developer.mozilla.org/en-US/Add-ons/SDK/Guides/Content_Scripts)
+is written using [ReactJS](https://facebook.github.io/react/). This makes it an awesome project for React hackers to contribute to!
+
+## Finding Bugs, Filing Tickets, Earning Karma ##
+
+Activity Stream lives on [GitHub](https://github.com/mozilla/activity-stream), but you already knew that! If you've found
+a bug, or have a feature idea that you you'd like to see in Activity Stream, follow these simple guidelines:
+- Pick a thoughtful and terse title for the issue (ie. *not* Thing Doesn't Work!)
+- Make sure to mention your Firefox version, OS and basic system parameters (eg. Firefox 49.0, Windows XP, 512KB RAM)
+- If you can reproduce the bug, give a step-by-step recipe
+- Include [stack traces from the console(s)](https://developer.mozilla.org/en-US/docs/Mozilla/Debugging/Debugging_JavaScript) where appropriate
+- Screenshots welcome!
+- When in doubt, take a look at some [existing issues](https://github.com/mozilla/activity-stream/issues) and emulate
+
+## Take a Ticket, Hack some Code ##
+
+If you are new to the repo, you might want to pay close attention to [`Good first bug`](https://github.com/mozilla/activity-stream/issues?q=is%3Aopen+is%3Aissue+label%3A%22Good+first+bug%22),
+ [`Bug`](https://github.com/mozilla/activity-stream/issues?q=is%3Aopen%20is%3Aissue%20label%3ABug%20),
+ [`Chore`](https://github.com/mozilla/activity-stream/issues?q=is%3Aopen+is%3Aissue+label%3AChore) and
+ [`Polish`](https://github.com/mozilla/activity-stream/issues?q=is%3Aopen+is%3Aissue+label%3APolish) tags, as these are
+typically a great way to get started. You might see a bug that is not yet assigned to anyone, or start a conversation with
+an engineer in the ticket itself, expressing your interest in taking the bug. If you take the bug, someone will set
+the ticket to [`Assigned to Contributor`](https://github.com/mozilla/activity-stream/issues?utf8=%E2%9C%93&q=is%3Aopen%20is%3Aissue%20label%3A%22Assigned%20to%20contributor%22%20), which is a way we can be pro-active about helping you succeed in fixing the bug.
+
+When you have some code written, you can open up a [Pull Request](#pull-requests), get your code [reviewed](#code-reviews), and see your code merged into the Activity Stream codebase.
+
+If you are thinking about contributing on a longer-term basis, check out the section on [milestones](#milestones) and [priorities](#priorities)
+to get a sense of how we plan and prioritize work.
+
+## Setting up your development environment
+
+Check out [this guide](docs/v2-system-addon/1.GETTING_STARTED.md) on how to install dependencies, get set up, and run tests.
+
+## Pull Requests ##
+
+You have identified the bug, written code and now want to get it into the main repo using a [Pull Request](https://help.github.com/articles/about-pull-requests/).
+
+All code is added using a pull request against the `master` branch of our repo. Before submitting a PR, please go through this checklist:
+- all [unit tests](docs/v2-system-addon/unit_testing_guide.md) must pass
+- if you haven't written unit tests for your patch, eyebrows will be curmudgeonly furrowed (write unit tests!)
+- if your pull request fixes a particular ticket (it does, right?), please use the `fixes #nnn` github annotation to indicate this
+- please add a `PR / Needs review` tag to your PR (if you have permission). This starts the code review process. If you cannot add a tag, don't worry, we will add it during triage.
+- if you can pick a module owner to be your reviewer by including `r? @username` in the comment (if not, don't worry, we will assign a reviewer)
+- make sure your PR will merge gracefully with `master` at the time you create the PR, and that your commit history is 'clean'
+
+### Setting up pre-push hooks
+
+If you contribute often and would like to set up a pre-push hook to always run `npm lint` before you push to Github,
+you can run the following from the root of the activity-stream directory:
+
+```
+cp hooks/pre-push .git/hooks/pre-push && chmod +x .git/hooks/pre-push
+```
+
+Your hook should now run whenever you run `git push`. To skip it, use the `--no-verify` option:
+
+```
+git push --no-verify
+```
+
+
+## Code Reviews ##
+
+You have created a PR and submitted it to the repo, and now are waiting patiently for you code review feedback. One of the projects
+module owners will be along and will either:
+- make suggestions for some improvements
+- give you an `R+` in the comments section, indicating the review is done and the code can be merged
+
+Typically, you will iterate on the PR, making changes and pushing your changes to new commits on the PR. When the reviewer is
+ satisfied that your code is good-to-go, you will get the coveted `R+` comment, and your code can be merged. If you have
+ commit permission, you can go ahead and merge the code to `master`, otherwise, it will be done for you.
+
+Our project prides itself on it's respectful, patient and positive attitude when it comes to reviewing contributor's code, and as such,
+we expect contributors to be respectful, patient and positive in their communications as well. Let's be friends and learn
+from each other for a free and awesome web!
+
+[Mozilla Committing Rules and Responsibilities](https://developer.mozilla.org/en-US/docs/Mozilla/Developer_guide/Committing_Rules_and_Responsibilities)
+
+## Git Commit Guidelines ##
+
+We loosely follow the [Angular commit guidelines](https://github.com/angular/angular.js/blob/master/CONTRIBUTING.md#type) of `<type>(<scope>): <subject>` where `type` must be one of:
+
+* **feat**: A new feature
+* **fix**: A bug fix
+* **docs**: Documentation only changes
+* **style**: Changes that do not affect the meaning of the code (white-space, formatting, missing
+ semi-colons, etc)
+* **refactor**: A code change that neither fixes a bug or adds a feature
+* **perf**: A code change that improves performance
+* **test**: Adding missing tests
+* **chore**: Changes to the build process or auxiliary tools and libraries such as documentation
+ generation
+
+### Scope
+The scope could be anything specifying place of the commit change. For example `timeline`,
+`metadata`, `reporting`, `experiments` etc...
+
+### Subject
+The subject contains succinct description of the change:
+
+* use the imperative, present tense: "change" not "changed" nor "changes"
+* don't capitalize first letter
+* no dot (.) at the end
+
+### Body
+In order to maintain a reference to the context of the commit, add
+`fixes #<issue_number>` if it closes a related issue or `issue #<issue_number>`
+if it's a partial fix.
+
+You can also write a detailed description of the commit:
+Just as in the **subject**, use the imperative, present tense: "change" not "changed" nor "changes"
+It should include the motivation for the change and contrast this with previous behavior.
+
+### Footer
+The footer should contain any information about **Breaking Changes** and is also the place to
+reference GitHub issues that this commit **Closes**.
+
+## Milestones ##
+
+All work on Activity Stream is broken into two week iterations, which we map into a GitHub [Milestone](https://github.com/mozilla/activity-stream/milestones). At the beginning of the iteration, we prioritize and estimate tickets
+into the milestone, attempting to figure out how much progress we can make during the iteration.
+
+## Priorities ##
+
+All tickets that have been [triaged](#triage) will have a priority tag of either `P1`, `P2`, `P3`, or `P4` which are highest to lowest
+priorities of tickets in Activity Stream. We love ticket tags and you might also see `Blocked`, `Critical` or `Chemspill` tags, which
+indicate our level of anxiety about that particular ticket.
+
+## Triage ##
+
+The project team meets weekly (in a closed meeting, for the time being), to discuss project priorities, to triage new tickets, and to
+redistribute the work amongst team members. Any contributors tickets or PRs are carefully considered, prioritized, and if needed,
+assigned a reviewer. The project's GitHub [Milestone page](https://github.com/mozilla/activity-stream/milestones) is the best
+place to look for up-to-date information on project priorities and current workload.
+
+## License
+
+MPL 2.0
diff --git a/browser/components/newtab/css/activity-stream-linux.css b/browser/components/newtab/css/activity-stream-linux.css
new file mode 100644
index 0000000000..86edcbd62d
--- /dev/null
+++ b/browser/components/newtab/css/activity-stream-linux.css
@@ -0,0 +1,4545 @@
+@charset "UTF-8";
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+/* This is the linux variant */
+html {
+ box-sizing: border-box; }
+
+*,
+*::before,
+*::after {
+ box-sizing: inherit; }
+
+*::-moz-focus-inner {
+ border: 0; }
+
+body {
+ margin: 0; }
+
+button,
+input {
+ background-color: inherit;
+ color: inherit;
+ font-family: inherit;
+ font-size: inherit; }
+
+[hidden] {
+ display: none !important; }
+
+body {
+ --newtab-background-color: #F9F9FA;
+ --newtab-border-primary-color: #B1B1B3;
+ --newtab-border-secondary-color: #D7D7DB;
+ --newtab-element-active-color: rgba(215, 215, 219, 0.6);
+ --newtab-element-hover-color: #EDEDF0;
+ --newtab-icon-primary-color: rgba(12, 12, 13, 0.8);
+ --newtab-icon-secondary-color: rgba(12, 12, 13, 0.6);
+ --newtab-icon-tertiary-color: #D7D7DB;
+ --newtab-inner-box-shadow-color: rgba(0, 0, 0, 0.1);
+ --newtab-inner-box-shadow-color-nte: rgba(9, 32, 77, 0.12);
+ --newtab-tile-shadow-secondary: rgba(29, 17, 51, 0.2);
+ --newtab-link-primary-color: #0060DF;
+ --newtab-link-secondary-color: #008EA4;
+ --newtab-text-conditional-color: #4A4A4F;
+ --newtab-text-primary-color: #0C0C0D;
+ --newtab-text-secondary-color: #737373;
+ --newtab-textbox-background-color: #FFF;
+ --newtab-textbox-border: rgba(12, 12, 13, 0.2);
+ --newtab-textbox-focus-color: #0060DF;
+ --newtab-textbox-focus-boxshadow: 0 0 0 1px #0060DF, 0 0 0 4px rgba(0, 96, 223, 0.3);
+ --newtab-background-button-color: rgba(223, 223, 223, 0.5);
+ --newtab-background-button-text-color: #484848;
+ --newtab-background-button-hover-color: rgba(196, 196, 196, 0.5);
+ --newtab-background-button-active-color: rgba(151, 151, 151, 0.5);
+ --newtab-button-primary-color: #0060DF;
+ --newtab-button-secondary-color: inherit;
+ --newtab-feed-button-background: #EDEDF0;
+ --newtab-feed-button-text: #0C0C0D;
+ --newtab-feed-button-background-faded: rgba(237, 237, 240, 0.6);
+ --newtab-feed-button-text-faded: rgba(12, 12, 13, 0);
+ --newtab-feed-button-spinner: #737373;
+ --newtab-contextmenu-background-color: #F9F9FA;
+ --newtab-contextmenu-button-color: #FFF;
+ --newtab-modal-color: #FFF;
+ --newtab-overlay-color: rgba(237, 237, 240, 0.8);
+ --newtab-section-header-text-color: #737373;
+ --newtab-section-navigation-text-color: #737373;
+ --newtab-section-active-contextmenu-color: #0C0C0D;
+ --newtab-search-border-color: transparent;
+ --newtab-search-dropdown-color: #FFF;
+ --newtab-search-dropdown-header-color: #F9F9FA;
+ --newtab-search-header-background-color: rgba(249, 249, 250, 0.95);
+ --newtab-search-icon-color: rgba(12, 12, 13, 0.4);
+ --newtab-search-wordmark-color: #363959;
+ --newtab-topsites-background-color: #FFF;
+ --newtab-topsites-icon-shadow: inset 0 0 0 1px var(--newtab-inner-box-shadow-color);
+ --newtab-topsites-label-color: inherit;
+ --newtab-topsites-outer-card-hover: rgba(0, 0, 0, 0.05);
+ --newtab-topsites-context-menu-hover: rgba(0, 0, 0, 0.05);
+ --newtab-card-active-outline-color: #D7D7DB;
+ --newtab-card-background-color: #FFF;
+ --newtab-card-hairline-color: rgba(0, 0, 0, 0.1);
+ --newtab-card-placeholder-color: #D7D7DB;
+ --newtab-card-shadow: 0 1px 4px 0 rgba(12, 12, 13, 0.1);
+ --newtab-snippets-background-color: #FFF;
+ --newtab-snippets-hairline-color: transparent;
+ --newtab-background-primary-text-color: #151515;
+ --newtab-focus-outline: rgba(0, 96, 223, 0.25);
+ --newtab-focus-border: #0060DF;
+ --newtab-focus-border-selected: rgba(0, 0, 0, 0.15);
+ --newtab-seperator-line-color: #E1E0E6;
+ --newtab-primary-action-background: #0060DF;
+ --newtab-primary-action-background-off: #E9E9E9;
+ --customize-menu-primary-text-color: #20123A;
+ --customize-menu-check-fill: #FFF;
+ --customize-menu-background: #FFF;
+ --customize-menu-secondary-action-background: #F9F9FA;
+ --customize-menu-secondary-action-background-hover: #EDEDF0;
+ --customize-menu-secondary-action-background-active: #E2E2E6;
+ --customize-menu-seperator-line-color: #E1E0E6;
+ --customize-menu-first-shadow: rgba(9, 32, 77, 0.12);
+ --customize-menu-second-shadow: rgba(29, 17, 51, 0.12);
+ --customize-menu-primary-action-text: #FFF;
+ --customize-menu-line-color: #716F87;
+ --newtab-search-first-shadow: rgba(9, 32, 77, 0.12);
+ --newtab-search-second-shadow: rgba(29, 17, 51, 0.12);
+ --newtab-search-text-color: #585165;
+ --newtab-card-first-shadow: rgba(9, 32, 77, 0.12);
+ --newtab-card-second-shadow: rgba(29, 17, 51, 0.12);
+ --newtab-wordmark-color: #20123A; }
+ body[lwt-newtab-brighttext] {
+ --newtab-background-color: #2A2A2E;
+ --newtab-border-primary-color: rgba(249, 249, 250, 0.8);
+ --newtab-border-secondary-color: rgba(249, 249, 250, 0.1);
+ --newtab-button-primary-color: #0060DF;
+ --newtab-button-secondary-color: #38383D;
+ --newtab-element-active-color: rgba(249, 249, 250, 0.2);
+ --newtab-element-hover-color: rgba(249, 249, 250, 0.1);
+ --newtab-icon-primary-color: rgba(249, 249, 250, 0.8);
+ --newtab-icon-secondary-color: rgba(249, 249, 250, 0.4);
+ --newtab-icon-tertiary-color: rgba(249, 249, 250, 0.4);
+ --newtab-inner-box-shadow-color: rgba(249, 249, 250, 0.2);
+ --newtab-inner-box-shadow-color-nte: rgba(21, 20, 26, 0.5);
+ --newtab-tile-shadow-secondary: rgba(21, 20, 26, 0.75);
+ --newtab-link-primary-color: #45A1FF;
+ --newtab-link-secondary-color: #50BCB6;
+ --newtab-text-conditional-color: #F9F9FA;
+ --newtab-text-primary-color: #F9F9FA;
+ --newtab-text-secondary-color: rgba(249, 249, 250, 0.8);
+ --newtab-textbox-background-color: #38383D;
+ --newtab-textbox-border: rgba(249, 249, 250, 0.2);
+ --newtab-textbox-focus-color: #45A1FF;
+ --newtab-textbox-focus-boxshadow: 0 0 0 1px #45A1FF, 0 0 0 4px rgba(69, 161, 255, 0.3);
+ --newtab-background-button-color: rgba(80, 80, 80, 0.5);
+ --newtab-background-button-text-color: #CDCDD4;
+ --newtab-background-button-hover-color: rgba(114, 114, 114, 0.5);
+ --newtab-background-button-active-color: rgba(173, 173, 173, 0.5);
+ --newtab-feed-button-background: #38383D;
+ --newtab-feed-button-text: #F9F9FA;
+ --newtab-feed-button-background-faded: rgba(56, 56, 61, 0.6);
+ --newtab-feed-button-text-faded: rgba(249, 249, 250, 0);
+ --newtab-feed-button-spinner: #D7D7DB;
+ --newtab-contextmenu-background-color: #4A4A4F;
+ --newtab-contextmenu-button-color: #2A2A2E;
+ --newtab-modal-color: #2A2A2E;
+ --newtab-overlay-color: rgba(12, 12, 13, 0.8);
+ --newtab-section-header-text-color: rgba(249, 249, 250, 0.8);
+ --newtab-section-navigation-text-color: rgba(249, 249, 250, 0.8);
+ --newtab-section-active-contextmenu-color: #FFF;
+ --newtab-search-border-color: rgba(249, 249, 250, 0.2);
+ --newtab-search-dropdown-color: #38383D;
+ --newtab-search-dropdown-header-color: #4A4A4F;
+ --newtab-search-header-background-color: rgba(42, 42, 46, 0.95);
+ --newtab-search-icon-color: rgba(249, 249, 250, 0.6);
+ --newtab-search-wordmark-color: #FFF;
+ --newtab-topsites-background-color: #38383D;
+ --newtab-topsites-icon-shadow: none;
+ --newtab-topsites-label-color: rgba(249, 249, 250, 0.8);
+ --newtab-topsites-outer-card-hover: rgba(180, 180, 180, 0.1);
+ --newtab-topsites-context-menu-hover: rgba(180, 180, 180, 0.1);
+ --newtab-card-active-outline-color: #4A4A4F;
+ --newtab-card-background-color: #38383D;
+ --newtab-card-hairline-color: rgba(249, 249, 250, 0.1);
+ --newtab-card-placeholder-color: #4A4A4F;
+ --newtab-card-shadow: 0 1px 8px 0 rgba(12, 12, 13, 0.2);
+ --newtab-snippets-background-color: #38383D;
+ --newtab-snippets-hairline-color: rgba(255, 255, 255, 0.1);
+ --newtab-background-primary-text-color: #CDCDD4;
+ --newtab-focus-outline: rgba(80, 145, 241, 0.5);
+ --newtab-focus-border: #B5D3FF;
+ --newtab-focus-border-selected: #B5D3FF;
+ --newtab-primary-action-background: #4484E2;
+ --newtab-primary-action-background-off: #6A6A6F;
+ --newtab-seperator-line-color: #53515F;
+ --customize-menu-primary-text-color: #E0E0E6;
+ --customize-menu-check-fill: #E0E0E6;
+ --customize-menu-background: #38383D;
+ --customize-menu-secondary-action-background: #515156;
+ --customize-menu-secondary-action-background-hover: #606065;
+ --customize-menu-secondary-action-background-active: #6F6F74;
+ --customize-menu-seperator-line-color: #53515F;
+ --customize-menu-first-shadow: rgba(21, 20, 26, 0.5);
+ --customize-menu-second-shadow: rgba(21, 20, 26, 0.75);
+ --customize-menu-primary-action-text: #E0E0E6;
+ --customize-menu-line-color: #B9B7CC;
+ --newtab-search-first-shadow: rgba(21, 20, 26, 0.5);
+ --newtab-search-second-shadow: rgba(21, 20, 26, 0.75);
+ --newtab-search-text-color: #B1B1BD;
+ --newtab-card-first-shadow: rgba(21, 20, 26, 0.5);
+ --newtab-card-second-shadow: rgba(21, 20, 26, 0.75);
+ --newtab-wordmark-color: #FFF; }
+
+.icon {
+ background-position: center center;
+ background-repeat: no-repeat;
+ background-size: 16px;
+ -moz-context-properties: fill;
+ display: inline-block;
+ color: var(--newtab-icon-primary-color);
+ fill: currentColor;
+ height: 16px;
+ vertical-align: middle;
+ width: 16px; }
+ .icon.icon-spacer {
+ margin-inline-end: 8px; }
+ .icon.icon-small-spacer {
+ margin-inline-end: 6px; }
+ .icon.icon-button-style {
+ fill: var(--newtab-icon-secondary-color);
+ border: 0; }
+ .icon.icon-button-style:focus, .icon.icon-button-style:hover {
+ fill: var(--newtab-text-primary-color); }
+ .icon.icon-bookmark-added {
+ background-image: url("chrome://browser/skin/bookmark.svg"); }
+ .icon.icon-bookmark-hollow {
+ background-image: url("chrome://browser/skin/bookmark-hollow.svg"); }
+ .icon.icon-clear-input {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-cancel-16.svg"); }
+ .icon.icon-delete {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-delete-16.svg"); }
+ .icon.icon-search {
+ background-image: url("chrome://browser/skin/search-glass.svg"); }
+ .icon.icon-modal-delete {
+ flex-shrink: 0;
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-modal-delete-32.svg");
+ background-size: 32px;
+ height: 32px;
+ width: 32px; }
+ .icon.icon-mail {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-mail-16.svg"); }
+ .icon.icon-dismiss {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-dismiss-16.svg"); }
+ .icon.icon-info {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-info-16.svg"); }
+ .icon.icon-new-window {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-newWindow-16.svg"); }
+ .icon.icon-new-window:dir(rtl) {
+ transform: scaleX(-1); }
+ .icon.icon-new-window-private {
+ background-image: url("chrome://browser/skin/privateBrowsing.svg"); }
+ .icon.icon-settings {
+ background-image: url("chrome://global/skin/icons/settings.svg"); }
+ .icon.icon-pin {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-pin-16.svg"); }
+ .icon.icon-pin:dir(rtl) {
+ transform: scaleX(-1); }
+ .icon.icon-unpin {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-unpin-16.svg"); }
+ .icon.icon-unpin:dir(rtl) {
+ transform: scaleX(-1); }
+ .icon.icon-edit {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-edit-16.svg"); }
+ .icon.icon-pocket {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-pocket-16.svg"); }
+ .icon.icon-pocket-save {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-pocket-save-16.svg"); }
+ .icon.icon-pocket-delete {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-pocket-delete-16.svg"); }
+ .icon.icon-pocket-archive {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-pocket-archive-16.svg"); }
+ .icon.icon-history-item {
+ background-image: url("chrome://browser/skin/history.svg"); }
+ .icon.icon-trending {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-trending-16.svg");
+ transform: translateY(2px); }
+ .icon.icon-now {
+ background-image: url("chrome://browser/skin/history.svg"); }
+ .icon.icon-topsites {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-topsites-16.svg"); }
+ .icon.icon-pin-small {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-pin-12.svg");
+ background-size: 12px;
+ height: 12px;
+ width: 12px; }
+ .icon.icon-pin-small:dir(rtl) {
+ transform: scaleX(-1); }
+ .icon.icon-check {
+ background-image: url("chrome://global/skin/icons/check.svg"); }
+ .icon.icon-download {
+ background-image: url("chrome://browser/skin/downloads/download-icons.svg#arrow-with-bar"); }
+ .icon.icon-copy {
+ background-image: url("chrome://browser/skin/edit-copy.svg"); }
+ .icon.icon-open-file {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-open-file-16.svg"); }
+ .icon.icon-webextension {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-webextension-16.svg"); }
+ .icon.icon-highlights {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-highlights-16.svg"); }
+ .icon.icon-arrowhead-down {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-arrowhead-down-16.svg"); }
+ .icon.icon-arrowhead-down-small {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-arrowhead-down-12.svg");
+ background-size: 12px;
+ height: 12px;
+ width: 12px; }
+ .icon.icon-arrowhead-forward-small {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-arrowhead-down-12.svg");
+ background-size: 12px;
+ height: 12px;
+ transform: rotate(-90deg);
+ width: 12px; }
+ .icon.icon-arrowhead-forward-small:dir(rtl) {
+ transform: rotate(90deg); }
+ .icon.icon-arrowhead-up {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-arrowhead-down-16.svg");
+ transform: rotate(180deg); }
+ .icon.icon-add {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-add-16.svg"); }
+ .icon.icon-minimize {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-minimize-16.svg"); }
+ .icon.icon-maximize {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-maximize-16.svg"); }
+ .icon.icon-arrow {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-arrow.svg"); }
+
+html {
+ height: 100%; }
+
+body,
+#root {
+ min-height: 100vh; }
+
+#root {
+ position: relative; }
+
+body {
+ background-color: var(--newtab-background-color);
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Ubuntu', 'Helvetica Neue', sans-serif;
+ font-size: 16px; }
+
+.no-scroll {
+ overflow: hidden; }
+
+h1,
+h2 {
+ font-weight: normal; }
+
+a {
+ text-decoration: none; }
+
+.inner-border {
+ border: 1px solid var(--newtab-border-secondary-color);
+ border-radius: 3px;
+ height: 100%;
+ left: 0;
+ pointer-events: none;
+ position: absolute;
+ top: 0;
+ width: 100%;
+ z-index: 100; }
+
+@keyframes fadeIn {
+ from {
+ opacity: 0; }
+ to {
+ opacity: 1; } }
+
+.show-on-init {
+ opacity: 0;
+ transition: opacity 0.2s ease-in; }
+ .show-on-init.on {
+ animation: fadeIn 0.2s;
+ opacity: 1; }
+
+.actions {
+ border-top: 1px solid var(--newtab-border-secondary-color);
+ display: flex;
+ flex-direction: row;
+ flex-wrap: wrap;
+ justify-content: flex-start;
+ margin: 0;
+ padding: 15px 25px 0; }
+
+.button,
+.actions button {
+ background-color: var(--newtab-button-secondary-color);
+ border: 1px solid var(--newtab-border-primary-color);
+ border-radius: 4px;
+ color: inherit;
+ cursor: pointer;
+ margin-bottom: 15px;
+ padding: 10px 30px;
+ white-space: nowrap; }
+ .button:hover:not(.dismiss), .button:focus:not(.dismiss),
+ .actions button:hover:not(.dismiss),
+ .actions button:focus:not(.dismiss) {
+ box-shadow: 0 0 0 5px var(--newtab-card-active-outline-color);
+ transition: box-shadow 150ms; }
+ .button.dismiss,
+ .actions button.dismiss {
+ background-color: transparent;
+ border: 0;
+ padding: 0;
+ text-decoration: underline; }
+ .button.primary, .button.done,
+ .actions button.primary,
+ .actions button.done {
+ background-color: var(--newtab-button-primary-color);
+ border: solid 1px var(--newtab-button-primary-color);
+ color: #FFF;
+ margin-inline-start: auto; }
+
+input[type='text'], input[type='search'] {
+ border-radius: 3px; }
+
+.clamp {
+ -webkit-box-orient: vertical;
+ display: -webkit-box;
+ overflow: hidden;
+ word-break: break-word; }
+
+.a11y-link-button {
+ border: 0;
+ padding: 0;
+ cursor: pointer;
+ text-align: unset;
+ color: var(--newtab-link-primary-color); }
+ .a11y-link-button:hover, .a11y-link-button:focus {
+ text-decoration: underline; }
+
+.outer-wrapper {
+ color: var(--newtab-text-primary-color);
+ display: flex;
+ flex-grow: 1;
+ min-height: 100vh;
+ padding: 30px 32px 32px; }
+ .outer-wrapper.ds-outer-wrapper-breakpoint-override {
+ padding: 30px 0 32px; }
+ @media (min-width: 610px) {
+ .outer-wrapper.ds-outer-wrapper-breakpoint-override {
+ padding: 30px 32px 32px; } }
+ .outer-wrapper.only-search {
+ display: block;
+ padding-top: 134px; }
+ .outer-wrapper a {
+ color: var(--newtab-link-primary-color); }
+
+main {
+ margin: auto;
+ width: 274px;
+ padding-bottom: 68px; }
+ main section {
+ margin-bottom: 20px;
+ position: relative; }
+ .hide-main main {
+ visibility: hidden; }
+ @media (min-width: 610px) {
+ main {
+ width: 530px; } }
+ @media (min-width: 866px) {
+ main {
+ width: 786px; } }
+ @media (min-width: 1122px) {
+ main {
+ width: 1042px; } }
+
+.below-search-snippet.withButton {
+ margin: auto;
+ width: 100%; }
+
+.ds-outer-wrapper-search-alignment main {
+ margin: 0 auto; }
+
+.ds-outer-wrapper-breakpoint-override main {
+ width: 266px;
+ padding-bottom: 68px; }
+ @media (min-width: 610px) {
+ .ds-outer-wrapper-breakpoint-override main {
+ width: 510px; } }
+ @media (min-width: 866px) {
+ .ds-outer-wrapper-breakpoint-override main {
+ width: 746px; } }
+ @media (min-width: 1122px) {
+ .ds-outer-wrapper-breakpoint-override main {
+ width: 986px; } }
+
+.base-content-fallback {
+ height: 100vh; }
+
+
+.body-wrapper .section-title,
+.body-wrapper .sections-list .section:last-of-type,
+.body-wrapper .topics {
+ opacity: 0; }
+
+
+.body-wrapper.on .section-title,
+.body-wrapper.on .sections-list .section:last-of-type,
+.body-wrapper.on .topics {
+ opacity: 1; }
+
+.non-collapsible-section {
+ padding: 0 25px; }
+
+.prefs-button button {
+ background-color: transparent;
+ border: 0;
+ border-radius: 2px;
+ cursor: pointer;
+ inset-inline-end: 15px;
+ padding: 15px;
+ position: fixed;
+ top: 15px;
+ z-index: 1000; }
+ .prefs-button button:hover, .prefs-button button:focus {
+ background-color: var(--newtab-element-hover-color); }
+ .prefs-button button:active {
+ background-color: var(--newtab-element-active-color); }
+
+@media (max-height: 701px) {
+ .personalize-button {
+ position: absolute;
+ top: 16px;
+ inset-inline-end: 16px; } }
+
+@media (min-height: 700px) {
+ .personalize-button {
+ position: fixed;
+ top: 16px;
+ inset-inline-end: 16px;
+ z-index: 1000; } }
+
+.personalize-button {
+ font-size: 12px;
+ font-weight: 600;
+ border: 0;
+ border-radius: 4px;
+ background-color: var(--newtab-background-button-color);
+ color: var(--newtab-background-button-text-color);
+ padding: 3px 10px;
+ min-height: 32px;
+ max-width: 117px; }
+ .personalize-button:hover {
+ background-color: var(--newtab-background-button-hover-color); }
+ .personalize-button:active {
+ background-color: var(--newtab-background-button-active-color); }
+ .personalize-button:focus-visible {
+ border: 0;
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-focus-outline), 0 0 0 1px var(--newtab-focus-border); }
+
+.as-error-fallback {
+ align-items: center;
+ border-radius: 3px;
+ box-shadow: inset 0 0 0 1px var(--newtab-inner-box-shadow-color);
+ color: var(--newtab-text-conditional-color);
+ display: flex;
+ flex-direction: column;
+ font-size: 12px;
+ justify-content: center;
+ justify-items: center;
+ line-height: 1.5; }
+ .as-error-fallback.borderless-error {
+ box-shadow: none; }
+ .as-error-fallback a {
+ color: var(--newtab-text-conditional-color);
+ text-decoration: underline; }
+
+.top-sites-list {
+ list-style: none;
+ margin: 0 -16px;
+ padding: 0; }
+ @media (max-width: 610px) {
+ .top-sites-list > :nth-child(2n+1) .context-menu {
+ margin-inline-end: auto;
+ margin-inline-start: auto;
+ inset-inline-end: auto;
+ inset-inline-start: -32px; }
+ .top-sites-list > :nth-child(2n) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+ @media (min-width: 610px) and (max-width: 866px) {
+ .top-sites-list :nth-child(4n) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+ @media (min-width: 610px) and (max-width: 834px) {
+ .top-sites-list :nth-child(4n+3) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+ @media (min-width: 866px) and (max-width: 1314px) {
+ .top-sites-list :nth-child(6n) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+ @media (min-width: 866px) and (max-width: 1090px) {
+ .top-sites-list :nth-child(6n+5) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+ @media (min-width: 1122px) and (max-width: 1570px) {
+ .top-sites-list :nth-child(8n) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+ @media (min-width: 1122px) and (max-width: 1346px) {
+ .top-sites-list :nth-child(8n+7) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+ .top-sites-list .hide-for-narrow {
+ display: none; }
+ @media (min-width: 610px) {
+ .top-sites-list .hide-for-narrow {
+ display: inline-block; } }
+ @media (min-width: 866px) {
+ .top-sites-list .hide-for-narrow {
+ display: none; } }
+ @media (min-width: 1122px) {
+ .top-sites-list .hide-for-narrow {
+ display: inline-block; } }
+
+.top-site-outer {
+ padding: 0 16px;
+ display: inline-block; }
+ .top-site-outer .top-site-inner {
+ position: relative; }
+ .top-site-outer .top-site-inner > a {
+ color: inherit;
+ display: block;
+ outline: none; }
+ .top-site-outer .tile {
+ border-radius: 4px;
+ box-shadow: inset 0 0 0 1px var(--newtab-inner-box-shadow-color), var(--newtab-card-shadow);
+ cursor: pointer;
+ position: relative;
+ align-items: center;
+ color: var(--newtab-text-secondary-color);
+ display: flex;
+ font-size: 32px;
+ font-weight: 200;
+ justify-content: center;
+ text-transform: uppercase; }
+ .top-site-outer .tile .icon-wrapper {
+ border-radius: 4px;
+ width: 48px;
+ height: 48px;
+ overflow: hidden;
+ position: relative;
+ display: flex;
+ align-items: center;
+ justify-content: center; }
+ .top-site-outer .tile .icon-wrapper.letter-fallback::before {
+ content: attr(data-fallback);
+ text-transform: uppercase;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ font-size: 64px;
+ font-weight: 800;
+ transform: rotate(-10deg);
+ top: 6px;
+ position: relative;
+ color: #FFF; }
+ .top-site-outer .top-site-icon {
+ background-color: var(--newtab-topsites-background-color);
+ background-position: center center;
+ background-repeat: no-repeat;
+ border-radius: 4px;
+ position: absolute; }
+ .top-site-outer .rich-icon {
+ background-size: cover;
+ height: 100%;
+ inset-inline-start: 0;
+ top: 0;
+ width: 100%; }
+ .top-site-outer .default-icon,
+ .top-site-outer .search-topsite {
+ background-size: 32px;
+ height: 42px;
+ width: 42px;
+ align-items: center;
+ display: flex;
+ font-size: 20px;
+ justify-content: center; }
+ .top-site-outer .default-icon[data-fallback]::before,
+ .top-site-outer .search-topsite[data-fallback]::before {
+ content: attr(data-fallback); }
+ .top-site-outer .search-topsite {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-search-16.svg");
+ background-size: 26px;
+ background-color: #0060DF;
+ border-radius: 42px;
+ -moz-context-properties: fill;
+ fill: #FFF;
+ box-shadow: var(--newtab-card-shadow);
+ transition-duration: 150ms;
+ transition-property: background-size, bottom, inset-inline-end, height, width;
+ height: 42px;
+ width: 42px;
+ bottom: -6px;
+ inset-inline-end: -6px; }
+ .top-site-outer .title {
+ color: var(--newtab-topsites-label-color);
+ font: message-box;
+ padding-top: 4px;
+ text-align: center;
+ position: relative; }
+ .top-site-outer .title .icon {
+ fill: var(--newtab-icon-tertiary-color); }
+ .top-site-outer .title span {
+ display: block;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap; }
+ .top-site-outer .title .sponsored-label {
+ color: #737373;
+ font-size: 0.9em; }
+ .top-site-outer .title:not(.sponsored) .sponsored-label {
+ visibility: hidden; }
+ .top-site-outer.search-shortcut .rich-icon {
+ background-color: #FFF; }
+ .top-site-outer .edit-button {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-edit-16.svg"); }
+ .top-site-outer.placeholder .screenshot {
+ display: none; }
+ .top-site-outer.dragged .tile {
+ background: #EDEDF0;
+ box-shadow: none; }
+ .top-site-outer.dragged .tile *, .top-site-outer.dragged .tile::before {
+ display: none; }
+ .top-site-outer.dragged .title {
+ visibility: hidden; }
+
+.edit-topsites-wrapper .modal {
+ box-shadow: 0 1px 4px 0 rgba(12, 12, 13, 0.2);
+ left: 0;
+ margin: 0 auto;
+ max-height: calc(100% - 40px);
+ position: fixed;
+ right: 0;
+ top: 40px;
+ width: 274px; }
+ @media (min-width: 610px) {
+ .edit-topsites-wrapper .modal {
+ width: 530px; } }
+ @media (min-width: 866px) {
+ .edit-topsites-wrapper .modal {
+ width: 786px; } }
+
+.topsite-form .section-title {
+ font-size: 16px;
+ margin: 0 0 16px; }
+
+.topsite-form .form-input-container {
+ max-width: 492px;
+ margin: 0 auto;
+ padding: 32px; }
+ .topsite-form .form-input-container .top-site-outer {
+ pointer-events: none; }
+
+.topsite-form .search-shortcuts-container {
+ max-width: 700px;
+ margin: 0 auto;
+ padding: 32px; }
+ .topsite-form .search-shortcuts-container > div {
+ margin-inline-end: -39px; }
+ .topsite-form .search-shortcuts-container .top-site-outer {
+ margin-inline-start: 0;
+ margin-inline-end: 39px; }
+
+.topsite-form .top-site-outer {
+ padding: 0;
+ margin: 24px 0 0;
+ margin-inline-start: 32px; }
+
+.topsite-form .fields-and-preview {
+ display: flex; }
+
+.topsite-form label {
+ font-size: 13px; }
+
+.topsite-form .form-wrapper {
+ width: 100%; }
+ .topsite-form .form-wrapper .field {
+ position: relative; }
+ .topsite-form .form-wrapper .field .icon-clear-input {
+ position: absolute;
+ transform: translateY(-50%);
+ top: 50%;
+ inset-inline-end: 8px; }
+ .topsite-form .form-wrapper .url input:dir(ltr) {
+ padding-right: 32px; }
+ .topsite-form .form-wrapper .url input:dir(rtl) {
+ padding-left: 32px; }
+ .topsite-form .form-wrapper .url input:dir(rtl):not(:placeholder-shown) {
+ direction: ltr;
+ text-align: right; }
+ .topsite-form .form-wrapper .enable-custom-image-input {
+ display: inline-block;
+ font-size: 13px;
+ margin-top: 4px;
+ cursor: pointer; }
+ .topsite-form .form-wrapper .custom-image-input-container {
+ margin-top: 4px; }
+ .topsite-form .form-wrapper .custom-image-input-container .loading-container {
+ width: 16px;
+ height: 16px;
+ overflow: hidden;
+ position: absolute;
+ transform: translateY(-50%);
+ top: 50%;
+ inset-inline-end: 8px; }
+ .topsite-form .form-wrapper .custom-image-input-container .loading-animation {
+ width: 960px;
+ height: 16px;
+ -moz-context-properties: fill;
+ fill: #0A84FF;
+ background-image: url("chrome://browser/skin/tabbrowser/loading.svg");
+ animation: tab-throbber-animation 1.05s steps(60) infinite; }
+
+@keyframes tab-throbber-animation {
+ 100% {
+ transform: translateX(-960px); } }
+
+@keyframes tab-throbber-animation-rtl {
+ 100% {
+ transform: translateX(960px); } }
+ .topsite-form .form-wrapper .custom-image-input-container .loading-animation:dir(rtl) {
+ animation-name: tab-throbber-animation-rtl; }
+ .topsite-form .form-wrapper input[type='text'] {
+ background-color: var(--newtab-textbox-background-color);
+ border: 1px solid var(--newtab-textbox-border);
+ margin: 8px 0;
+ padding: 0 8px;
+ height: 32px;
+ width: 100%;
+ font-size: 15px; }
+ .topsite-form .form-wrapper input[type='text'][disabled] {
+ border: 1px solid var(--newtab-textbox-border);
+ box-shadow: none;
+ opacity: 0.4; }
+ .topsite-form .form-wrapper .invalid input[type='text'] {
+ border: 1px solid #D70022;
+ box-shadow: 0 0 0 1px #D70022, 0 0 0 4px rgba(215, 0, 34, 0.3); }
+ .topsite-form .form-wrapper .error-tooltip {
+ animation: fade-up-tt 450ms;
+ background: #D70022;
+ border-radius: 2px;
+ color: #FFF;
+ inset-inline-start: 3px;
+ padding: 5px 12px;
+ position: absolute;
+ top: 44px;
+ z-index: 1; }
+ .topsite-form .form-wrapper .error-tooltip::before {
+ background: #D70022;
+ bottom: -8px;
+ content: '.';
+ height: 16px;
+ inset-inline-start: 12px;
+ position: absolute;
+ text-indent: -999px;
+ top: -7px;
+ transform: rotate(45deg);
+ white-space: nowrap;
+ width: 16px;
+ z-index: -1; }
+
+.topsite-form .actions {
+ justify-content: flex-end; }
+ .topsite-form .actions button {
+ margin-inline-start: 10px;
+ margin-inline-end: 0; }
+
+@media (max-width: 610px) {
+ .topsite-form .fields-and-preview {
+ flex-direction: column; }
+ .topsite-form .fields-and-preview .top-site-outer {
+ margin-inline-start: 0; } }
+
+.topsite-form .title {
+ user-select: none; }
+
+.topsite-form [type='checkbox']:not(:checked),
+.topsite-form [type='checkbox']:checked {
+ inset-inline-start: -9999px;
+ position: absolute; }
+
+.topsite-form [type='checkbox']:not(:checked) + label,
+.topsite-form [type='checkbox']:checked + label {
+ cursor: pointer;
+ display: block;
+ position: relative; }
+
+.topsite-form [type='checkbox']:not(:checked) + label::before,
+.topsite-form [type='checkbox']:checked + label::before {
+ background: var(--newtab-background-color);
+ border: 1px solid var(--newtab-textbox-border);
+ border-radius: 3px;
+ content: '';
+ height: 21px;
+ left: -8px;
+ position: absolute;
+ top: -8px;
+ width: 21px;
+ z-index: 1; }
+ [dir='rtl'] .topsite-form [type='checkbox']:not(:checked) + label::before, [dir='rtl']
+ .topsite-form [type='checkbox']:checked + label::before {
+ left: auto;
+ right: -8px; }
+
+.topsite-form [type='checkbox']:not(:checked) + label::after,
+.topsite-form [type='checkbox']:checked + label::after {
+ background: url("chrome://global/skin/icons/check.svg") no-repeat center center;
+ content: '';
+ height: 21px;
+ left: -8px;
+ position: absolute;
+ top: -8px;
+ width: 21px;
+ -moz-context-properties: fill;
+ fill: var(--newtab-link-primary-color);
+ z-index: 2; }
+ [dir='rtl'] .topsite-form [type='checkbox']:not(:checked) + label::after, [dir='rtl']
+ .topsite-form [type='checkbox']:checked + label::after {
+ left: auto;
+ right: -8px; }
+
+.topsite-form [type='checkbox']:checked + label .tile {
+ box-shadow: 0 0 0 2px var(--newtab-link-primary-color); }
+
+.topsite-form [type='checkbox']:not(:checked) + label::after {
+ opacity: 0; }
+
+.topsite-form [type='checkbox']:checked + label::after {
+ opacity: 1; }
+
+.topsite-form [type='checkbox']:checked:focus + label::before,
+.topsite-form [type='checkbox']:not(:checked):focus + label::before {
+ border: 1px dotted var(--newtab-link-primary-color); }
+
+.outer-wrapper:not(.newtab-experience) .top-site-outer .context-menu-button {
+ background-clip: padding-box;
+ background-color: var(--newtab-contextmenu-button-color);
+ background-image: url("chrome://global/skin/icons/more.svg");
+ background-position: 55%;
+ border: 1px solid var(--newtab-border-primary-color);
+ border-radius: 100%;
+ box-shadow: 0 2px rgba(12, 12, 13, 0.1);
+ cursor: pointer;
+ fill: var(--newtab-icon-primary-color);
+ height: 27px;
+ inset-inline-end: -13.5px;
+ opacity: 0;
+ position: absolute;
+ top: -13.5px;
+ transform: scale(0.25);
+ transition-duration: 150ms;
+ transition-property: transform, opacity;
+ width: 27px; }
+ .outer-wrapper:not(.newtab-experience) .top-site-outer .context-menu-button:is(:active, :focus) {
+ opacity: 1;
+ transform: scale(1); }
+
+.outer-wrapper:not(.newtab-experience) .top-site-outer .tile {
+ height: 96px;
+ width: 96px;
+ transition: box-shadow 150ms; }
+
+.outer-wrapper:not(.newtab-experience) .top-site-outer .top-site-icon {
+ box-shadow: var(--newtab-topsites-icon-shadow); }
+
+.outer-wrapper:not(.newtab-experience) .top-site-outer .title {
+ width: 96px; }
+ .outer-wrapper:not(.newtab-experience) .top-site-outer .title.has-icon span {
+ padding: 0 13px; }
+ .outer-wrapper:not(.newtab-experience) .top-site-outer .title .icon {
+ inset-inline-start: 0;
+ position: absolute;
+ top: 0.5em; }
+
+.outer-wrapper:not(.newtab-experience) .top-site-outer .top-site-inner {
+ position: relative; }
+ .outer-wrapper:not(.newtab-experience) .top-site-outer .top-site-inner > a {
+ color: inherit;
+ display: block;
+ outline: none; }
+ .outer-wrapper:not(.newtab-experience) .top-site-outer .top-site-inner > a:is(.active, :focus) .tile {
+ box-shadow: inset 0 0 0 1px var(--newtab-inner-box-shadow-color), 0 0 0 5px var(--newtab-card-active-outline-color);
+ transition: box-shadow 150ms; }
+
+.outer-wrapper:not(.newtab-experience) .top-site-outer .screenshot {
+ background-color: #FFF;
+ background-position: top left;
+ background-size: cover;
+ border-radius: 4px;
+ box-shadow: inset 0 0 0 1px var(--newtab-inner-box-shadow-color);
+ height: 100%;
+ opacity: 0;
+ position: absolute;
+ top: 0;
+ left: 0;
+ transition: opacity 1s;
+ width: 100%; }
+ .outer-wrapper:not(.newtab-experience) .top-site-outer .screenshot.active {
+ opacity: 1; }
+
+.outer-wrapper:not(.newtab-experience) .top-site-outer .default-icon,
+.outer-wrapper:not(.newtab-experience) .top-site-outer .search-topsite {
+ bottom: -6px;
+ inset-inline-end: -6px; }
+
+.outer-wrapper:not(.newtab-experience) .top-site-outer:hover .search-topsite {
+ background-size: 28px;
+ border-radius: 46px;
+ bottom: -9px;
+ height: 46px;
+ inset-inline-end: -9px;
+ width: 46px; }
+
+.outer-wrapper:not(.newtab-experience) .top-site-outer.placeholder .tile {
+ box-shadow: inset 0 0 0 1px var(--newtab-inner-box-shadow-color); }
+
+.outer-wrapper:not(.newtab-experience) .top-sites-list:not(.dnd-active) .top-site-outer:is(.active, :focus, :hover) .tile {
+ box-shadow: inset 0 0 0 1px var(--newtab-inner-box-shadow-color), 0 0 0 5px var(--newtab-card-active-outline-color);
+ transition: box-shadow 150ms; }
+
+.outer-wrapper:not(.newtab-experience) .top-sites-list:not(.dnd-active) .top-site-outer:is(.active, :focus, :hover) .context-menu-button {
+ opacity: 1;
+ transform: scale(1);
+ transition-delay: 333ms; }
+
+.outer-wrapper:not(.newtab-experience) .top-sites-list li {
+ margin: 0 0 8px; }
+
+.outer-wrapper.newtab-experience .top-site-outer {
+ width: 120px;
+ padding-block: 20px 4px;
+ border-radius: 8px; }
+ .outer-wrapper.newtab-experience .top-site-outer .context-menu-button {
+ background-image: url("chrome://global/skin/icons/more.svg");
+ border: 0;
+ border-radius: 4px;
+ cursor: pointer;
+ fill: var(--newtab-icon-primary-color);
+ -moz-context-properties: fill;
+ height: 20px;
+ width: 20px;
+ inset-inline-end: -9px;
+ opacity: 0;
+ position: absolute;
+ top: -20px;
+ transition: opacity 200ms; }
+ .outer-wrapper.newtab-experience .top-site-outer .context-menu-button:is(:active, :focus) {
+ outline: 0;
+ opacity: 1;
+ background-color: var(--newtab-topsites-context-menu-hover);
+ fill: var(--newtab-primary-action-background); }
+ .outer-wrapper.newtab-experience .top-site-outer .edit-button {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-edit-16.svg"); }
+ .outer-wrapper.newtab-experience .top-site-outer .tile {
+ border-radius: 8px;
+ box-shadow: 0 3px 8px var(--newtab-inner-box-shadow-color-nte), 0 0 2px var(--newtab-tile-shadow-secondary);
+ background-color: var(--newtab-topsites-background-color);
+ justify-content: center;
+ margin: 0 auto;
+ height: 80px;
+ width: 80px; }
+ .outer-wrapper.newtab-experience .top-site-outer .title {
+ color: var(--newtab-background-primary-text-color);
+ padding-top: 8px;
+ font-size: 12px; }
+ .outer-wrapper.newtab-experience .top-site-outer .title .icon {
+ margin-inline-end: 2px;
+ fill: var(--newtab-background-primary-text-color); }
+ .outer-wrapper.newtab-experience .top-site-outer .title .sponsored-label {
+ font-size: 12px; }
+ .outer-wrapper.newtab-experience .top-site-outer .default-icon,
+ .outer-wrapper.newtab-experience .top-site-outer .search-topsite {
+ height: 32px;
+ width: 32px; }
+ .outer-wrapper.newtab-experience .top-site-outer .search-topsite {
+ background-size: 16px;
+ height: 32px;
+ width: 32px; }
+ .outer-wrapper.newtab-experience .top-site-outer.placeholder .tile {
+ box-shadow: 0 0 0 1px var(--newtab-inner-box-shadow-color); }
+
+@media (max-width: 610px) {
+ .outer-wrapper.newtab-experience .top-sites-list > :nth-child(2n+1) .context-menu {
+ margin-inline-end: auto;
+ margin-inline-start: auto;
+ inset-inline-end: auto;
+ inset-inline-start: -32px; }
+ .outer-wrapper.newtab-experience .top-sites-list > :nth-child(2n) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+
+@media (min-width: 610px) and (max-width: 866px) {
+ .outer-wrapper.newtab-experience .top-sites-list :nth-child(4n) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+
+@media (min-width: 610px) and (max-width: 802px) {
+ .outer-wrapper.newtab-experience .top-sites-list :nth-child(4n+3) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+
+@media (min-width: 866px) and (max-width: 1250px) {
+ .outer-wrapper.newtab-experience .top-sites-list :nth-child(6n) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+
+@media (min-width: 866px) and (max-width: 1058px) {
+ .outer-wrapper.newtab-experience .top-sites-list :nth-child(6n+5) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+
+@media (min-width: 1122px) and (max-width: 1506px) {
+ .outer-wrapper.newtab-experience .top-sites-list :nth-child(8n) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+
+@media (min-width: 1122px) and (max-width: 1314px) {
+ .outer-wrapper.newtab-experience .top-sites-list :nth-child(8n+7) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+
+.outer-wrapper.newtab-experience:not(.dnd-active) .top-site-outer:is(.active, :focus, :hover) {
+ background: var(--newtab-topsites-outer-card-hover); }
+ .outer-wrapper.newtab-experience:not(.dnd-active) .top-site-outer:is(.active, :focus, :hover) .context-menu-button {
+ opacity: 1; }
+
+@keyframes fade-up-tt {
+ 0% {
+ opacity: 0;
+ transform: translateY(15px); }
+ 100% {
+ opacity: 1;
+ transform: translateY(0); } }
+
+.sections-list .section-list {
+ display: grid;
+ grid-gap: 32px;
+ grid-template-columns: repeat(auto-fit, 224px);
+ margin: 0; }
+ @media (max-width: 610px) {
+ .sections-list .section-list .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+ @media (min-width: 610px) and (max-width: 866px) {
+ .sections-list .section-list :nth-child(2n) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+ @media (min-width: 866px) and (max-width: 1314px) {
+ .sections-list .section-list :nth-child(3n) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+ @media (min-width: 1122px) and (max-width: 1570px) {
+ .sections-list .section-list :nth-child(3n) .context-menu,
+ .sections-list .section-list :nth-child(4n) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+
+.sections-list .section-empty-state {
+ border: 1px solid var(--newtab-border-secondary-color);
+ border-radius: 3px;
+ display: flex;
+ height: 266px;
+ width: 100%; }
+ .sections-list .section-empty-state .empty-state {
+ margin: auto;
+ max-width: 350px; }
+ .sections-list .section-empty-state .empty-state .empty-state-icon {
+ background-position: center;
+ background-repeat: no-repeat;
+ background-size: 50px 50px;
+ -moz-context-properties: fill;
+ display: block;
+ fill: var(--newtab-icon-secondary-color);
+ height: 50px;
+ margin: 0 auto;
+ width: 50px; }
+ .sections-list .section-empty-state .empty-state .empty-state-message {
+ color: var(--newtab-text-primary-color);
+ font-size: 13px;
+ margin-bottom: 0;
+ text-align: center; }
+ @media (min-width: 1122px) {
+ .sections-list .section-empty-state {
+ height: 370px; } }
+
+.top-stories-bottom-container {
+ color: var(--newtab-section-navigation-text-color);
+ font-size: 12px;
+ line-height: 1.6;
+ margin-top: 12px;
+ display: flex;
+ justify-content: space-between; }
+ .top-stories-bottom-container a {
+ color: var(--newtab-link-secondary-color);
+ font-weight: bold; }
+ .top-stories-bottom-container a.more-recommendations {
+ font-weight: normal;
+ font-size: 13px; }
+ @media (max-width: 865px) {
+ .top-stories-bottom-container .wrapper-topics,
+ .top-stories-bottom-container .wrapper-cta + .wrapper-more-recommendations {
+ display: none; } }
+ @media (max-width: 609px) {
+ .top-stories-bottom-container .wrapper-cta {
+ text-align: center; }
+ .top-stories-bottom-container .wrapper-cta .pocket-logged-in-cta {
+ display: block;
+ margin-inline-end: 0; }
+ .top-stories-bottom-container .wrapper-cta .pocket-logged-in-cta .pocket-cta-button {
+ max-width: none;
+ display: block;
+ margin-inline-end: 0;
+ margin: 5px 0 10px; }
+ .top-stories-bottom-container .wrapper-more-recommendations {
+ width: 100%; }
+ .top-stories-bottom-container .wrapper-more-recommendations .more-recommendations {
+ justify-content: center; }
+ .top-stories-bottom-container .wrapper-more-recommendations .more-recommendations::after {
+ display: none; } }
+
+@media (min-width: 1122px) {
+ .sections-list .normal-cards .section-list {
+ grid-template-columns: repeat(auto-fit, 309px); } }
+
+.topics ul {
+ margin: 0;
+ padding: 0; }
+ @media (min-width: 866px) {
+ .topics ul {
+ display: inline;
+ padding-inline-start: 12px; } }
+
+.topics ul li {
+ display: inline-block; }
+ .topics ul li::after {
+ content: '•';
+ padding: 8px; }
+ .topics ul li:last-child::after {
+ content: none; }
+
+.outer-wrapper.newtab-experience.visible-logo .logo-and-wordmark .wordmark {
+ fill: var(--newtab-wordmark-color); }
+
+.outer-wrapper.newtab-experience .search-wrapper {
+ padding-bottom: 38px; }
+ .outer-wrapper.newtab-experience .search-wrapper .search-inner-wrapper {
+ min-height: 52px;
+ width: 200px; }
+ @media (min-width: 610px) {
+ .outer-wrapper.newtab-experience .search-wrapper .search-inner-wrapper {
+ width: 360px; } }
+ @media (min-width: 866px) {
+ .outer-wrapper.newtab-experience .search-wrapper .search-inner-wrapper {
+ width: 600px; } }
+ @media (min-width: 1122px) {
+ .outer-wrapper.newtab-experience .search-wrapper .search-inner-wrapper {
+ width: 720px; } }
+ .outer-wrapper.newtab-experience .search-wrapper .search-button:focus {
+ outline: 0;
+ box-shadow: 0 0 0 2px var(--newtab-focus-outline);
+ border: 1px solid var(--newtab-focus-border);
+ border-radius: 0 8px 8px 0; }
+ .outer-wrapper.newtab-experience .search-wrapper input:focus {
+ outline: 0;
+ border: 1px solid var(--newtab-focus-border);
+ box-shadow: 0 0 0 2px var(--newtab-focus-outline); }
+ .outer-wrapper.newtab-experience .search-wrapper.fake-focus .search-handoff-button {
+ border: 1px solid var(--newtab-focus-border);
+ box-shadow: 0 0 0 2px var(--newtab-focus-outline); }
+ .outer-wrapper.newtab-experience .search-wrapper .search-handoff-button,
+ .outer-wrapper.newtab-experience .search-wrapper input {
+ background: var(--newtab-textbox-background-color) var(--newtab-search-icon) 16px center no-repeat;
+ background-size: 24px;
+ padding-inline-start: 52px;
+ padding-inline-end: 10px;
+ box-shadow: 0 3px 8px var(--newtab-search-first-shadow), 0 0 2px var(--newtab-search-second-shadow);
+ border: 1px solid transparent;
+ border-radius: 8px;
+ color: var(--newtab-search-text-color);
+ font-weight: 500;
+ font-size: 15px; }
+ .outer-wrapper.newtab-experience .search-wrapper .search-handoff-button {
+ padding-inline-end: 15px; }
+ .outer-wrapper.newtab-experience .search-wrapper .search-handoff-button .fake-caret {
+ top: 18px;
+ inset-inline-start: 52px; }
+ .outer-wrapper.newtab-experience .search-wrapper .search-handoff-button .fake-caret:dir(rtl) {
+ background-position-x: right 16px; }
+
+.search-wrapper {
+ padding: 34px 0 64px; }
+ .only-search .search-wrapper {
+ padding: 0 0 64px; }
+ .search-wrapper .logo-and-wordmark {
+ align-items: center;
+ display: flex;
+ justify-content: center;
+ margin-bottom: 48px; }
+ .search-wrapper .logo-and-wordmark .logo {
+ background: url("chrome://branding/content/about-logo.png") no-repeat center;
+ background-size: 82px;
+ display: inline-block;
+ height: 82px;
+ width: 82px; }
+ @media (min-resolution: 2x) {
+ .search-wrapper .logo-and-wordmark .logo {
+ background-image: url("chrome://branding/content/about-logo@2x.png"); } }
+ .search-wrapper .logo-and-wordmark .wordmark {
+ background: url("chrome://branding/content/firefox-wordmark.svg") no-repeat center center;
+ background-size: 134px;
+ -moz-context-properties: fill;
+ display: inline-block;
+ fill: var(--newtab-search-wordmark-color);
+ height: 82px;
+ margin-inline-start: 16px;
+ width: 134px; }
+ @media (max-width: 609px) {
+ .search-wrapper .logo-and-wordmark .logo {
+ background-size: 64px;
+ height: 64px;
+ width: 64px; }
+ .search-wrapper .logo-and-wordmark .wordmark {
+ background-size: 100px;
+ height: 64px;
+ width: 100px;
+ margin-inline-start: 12px; } }
+ .search-wrapper .search-inner-wrapper {
+ cursor: default;
+ display: flex;
+ min-height: 48px;
+ margin: 0 auto;
+ position: relative;
+ width: 224px; }
+ .ds-outer-wrapper-breakpoint-override .search-wrapper .search-inner-wrapper {
+ width: 216px; }
+ @media (min-width: 610px) {
+ .search-wrapper .search-inner-wrapper {
+ width: 480px; }
+ .ds-outer-wrapper-breakpoint-override .search-wrapper .search-inner-wrapper {
+ width: 460px; } }
+ @media (min-width: 866px) {
+ .search-wrapper .search-inner-wrapper {
+ width: 736px; }
+ .ds-outer-wrapper-breakpoint-override .search-wrapper .search-inner-wrapper {
+ width: 696px; } }
+ .search-wrapper input {
+ background: var(--newtab-textbox-background-color) var(--newtab-search-icon) 12px center no-repeat;
+ background-size: 24px;
+ border: solid 1px var(--newtab-search-border-color);
+ box-shadow: 0 1px 4px 0 rgba(12, 12, 13, 0.2), 0 0 0 1px rgba(0, 0, 0, 0.15);
+ font-size: 15px;
+ -moz-context-properties: fill;
+ fill: var(--newtab-search-icon-color);
+ padding: 0;
+ padding-inline-end: 48px;
+ padding-inline-start: 46px;
+ width: 100%; }
+ .search-wrapper input:dir(rtl) {
+ background-position-x: right 12px; }
+ .search-wrapper:hover input {
+ box-shadow: 0 1px 4px 0 rgba(12, 12, 13, 0.2), 0 0 0 1px rgba(0, 0, 0, 0.25); }
+ .search-wrapper .search-inner-wrapper:active input,
+ .search-wrapper input:focus {
+ border: 1px solid var(--newtab-textbox-focus-color);
+ box-shadow: var(--newtab-textbox-focus-boxshadow); }
+ .search-wrapper .search-button {
+ background: url("chrome://browser/skin/forward.svg") no-repeat center center;
+ background-size: 16px 16px;
+ border: 0;
+ border-radius: 0 3px 3px 0;
+ -moz-context-properties: fill;
+ fill: var(--newtab-search-icon-color);
+ height: 100%;
+ inset-inline-end: 0;
+ position: absolute;
+ width: 48px; }
+ .search-wrapper .search-button:focus, .search-wrapper .search-button:hover {
+ background-color: rgba(12, 12, 13, 0.1);
+ cursor: pointer; }
+ .search-wrapper .search-button:active {
+ background-color: rgba(12, 12, 13, 0.2); }
+ .search-wrapper .search-button:dir(rtl) {
+ transform: scaleX(-1); }
+
+.non-collapsible-section + .below-search-snippet-wrapper {
+ margin-top: -48px; }
+
+@media (max-height: 700px) {
+ .search-wrapper {
+ padding: 0 0 30px; }
+ .non-collapsible-section + .below-search-snippet-wrapper {
+ margin-top: -14px; }
+ .below-search-snippet-wrapper {
+ min-height: 0; } }
+
+.search-handoff-button {
+ background: var(--newtab-textbox-background-color) var(--newtab-search-icon) 12px center no-repeat;
+ background-size: 24px;
+ border: solid 1px var(--newtab-search-border-color);
+ border-radius: 3px;
+ box-shadow: 0 1px 4px 0 rgba(12, 12, 13, 0.2), 0 0 0 1px rgba(0, 0, 0, 0.15);
+ cursor: text;
+ font-size: 15px;
+ padding: 0;
+ padding-inline-end: 48px;
+ padding-inline-start: 46px;
+ opacity: 1;
+ transition: opacity 500ms;
+ width: 100%; }
+ .search-handoff-button:dir(rtl) {
+ background-position-x: right 12px; }
+ .search-handoff-button:hover {
+ box-shadow: 0 1px 4px 0 rgba(12, 12, 13, 0.2), 0 0 0 1px rgba(0, 0, 0, 0.25); }
+ .fake-focus .search-handoff-button {
+ border: 1px solid var(--newtab-textbox-focus-color);
+ box-shadow: var(--newtab-textbox-focus-boxshadow); }
+ .fake-focus .search-handoff-button .fake-caret {
+ display: block; }
+ .search-hidden .search-handoff-button {
+ opacity: 0;
+ visibility: hidden; }
+ .search-handoff-button .fake-editable:focus {
+ outline: none;
+ caret-color: transparent; }
+ .search-handoff-button .fake-editable {
+ color: transparent;
+ height: 100%;
+ opacity: 0;
+ position: absolute;
+ top: 0;
+ left: 0;
+ right: 0;
+ bottom: 0; }
+ .search-handoff-button .fake-textbox {
+ opacity: 0.54;
+ text-align: start; }
+ .search-handoff-button .fake-caret {
+ animation: caret-animation 1.3s steps(5, start) infinite;
+ background: var(--newtab-text-primary-color);
+ display: none;
+ inset-inline-start: 47px;
+ height: 17px;
+ position: absolute;
+ top: 16px;
+ width: 1px; }
+
+@keyframes caret-animation {
+ to {
+ visibility: hidden; } }
+
+@media (min-height: 701px) {
+ body:not(.inline-onboarding) .fixed-search main {
+ padding-top: 146px; }
+ body:not(.inline-onboarding) .fixed-search.visible-logo main {
+ padding-top: 276px; }
+ body:not(.inline-onboarding) .fixed-search .search-wrapper {
+ border-bottom: solid 1px var(--newtab-border-secondary-color);
+ padding: 30px 0;
+ background-color: var(--newtab-search-header-background-color);
+ min-height: 95px;
+ left: 0;
+ position: fixed;
+ top: 0;
+ width: 100%;
+ z-index: 9; }
+ body:not(.inline-onboarding) .fixed-search .search-wrapper .search-inner-wrapper {
+ min-height: 35px; }
+ body:not(.inline-onboarding) .fixed-search .search-wrapper input {
+ background-position-x: 16px;
+ background-size: 16px; }
+ body:not(.inline-onboarding) .fixed-search .search-wrapper input:dir(rtl) {
+ background-position-x: right 16px; }
+ body:not(.inline-onboarding) .fixed-search .search-wrapper .search-handoff-button .fake-caret {
+ top: 14px; }
+ body:not(.inline-onboarding) .fixed-search .search-wrapper .logo-and-wordmark {
+ display: none; }
+ body:not(.inline-onboarding) .fixed-search.newtab-experience main {
+ padding-top: 124px; }
+ body:not(.inline-onboarding) .fixed-search.newtab-experience.visible-logo main {
+ padding-top: 254px; }
+ body:not(.inline-onboarding) .fixed-search.newtab-experience .search-wrapper {
+ border-bottom: solid 1px var(--newtab-seperator-line-color);
+ padding: 27px 0; }
+ body:not(.inline-onboarding) .fixed-search.newtab-experience .search-wrapper .search-inner-wrapper {
+ min-height: 45px; }
+ body:not(.inline-onboarding) .fixed-search.newtab-experience .search-wrapper input {
+ background-position-x: 16px;
+ background-size: 24px; }
+ body:not(.inline-onboarding) .fixed-search.newtab-experience .search-wrapper input:dir(rtl) {
+ background-position-x: right 16px; }
+ body:not(.inline-onboarding) .fixed-search .search-handoff-button {
+ background-position-x: 12px;
+ background-size: 24px; }
+ body:not(.inline-onboarding) .fixed-search .search-handoff-button:dir(rtl) {
+ background-position-x: right 12px; }
+ body:not(.inline-onboarding) .fixed-search .search-handoff-button .fake-caret {
+ top: 10px; } }
+
+.contentSearchSuggestionTable {
+ background-color: var(--newtab-search-dropdown-color);
+ border: 0;
+ box-shadow: 0 5px 10px rgba(0, 0, 0, 0.3), 0 0 0 1px rgba(0, 0, 0, 0.2);
+ transform: translateY(4px); }
+ .contentSearchSuggestionTable .contentSearchHeader {
+ background-color: var(--newtab-search-dropdown-header-color);
+ color: var(--newtab-text-secondary-color); }
+ .contentSearchSuggestionTable .contentSearchHeader,
+ .contentSearchSuggestionTable .contentSearchSettingsButton {
+ border-color: var(--newtab-border-secondary-color); }
+ .contentSearchSuggestionTable .contentSearchSuggestionsList {
+ border: 0; }
+ .contentSearchSuggestionTable .contentSearchOneOffsTable {
+ background-color: var(--newtab-search-dropdown-header-color);
+ border-top: solid 1px var(--newtab-border-secondary-color); }
+ .contentSearchSuggestionTable .contentSearchSearchWithHeaderSearchText {
+ color: var(--newtab-text-primary-color); }
+ .contentSearchSuggestionTable .contentSearchSuggestionsContainer {
+ background-color: var(--newtab-search-dropdown-color); }
+ .contentSearchSuggestionTable .contentSearchSuggestionRow.selected {
+ background: var(--newtab-element-hover-color);
+ color: var(--newtab-text-primary-color); }
+ .contentSearchSuggestionTable .contentSearchSuggestionRow.selected:active {
+ background: var(--newtab-element-active-color); }
+ .contentSearchSuggestionTable .contentSearchSuggestionRow.selected .historyIcon {
+ fill: var(--newtab-icon-secondary-color); }
+ .contentSearchSuggestionTable .contentSearchOneOffsTable .contentSearchSuggestionsContainer {
+ background-color: var(--newtab-search-dropdown-header-color); }
+ .contentSearchSuggestionTable .contentSearchOneOffItem {
+ background-image: none;
+ border-image: linear-gradient(transparent 18%, var(--newtab-border-secondary-color) 18%, var(--newtab-border-secondary-color) 82%, transparent 82%) 1;
+ border-inline-end: 1px solid;
+ position: relative; }
+ .contentSearchSuggestionTable .contentSearchOneOffItem.selected {
+ background: var(--newtab-element-hover-color); }
+ .contentSearchSuggestionTable .contentSearchOneOffItem:active {
+ background: var(--newtab-element-active-color); }
+ .contentSearchSuggestionTable .contentSearchSettingsButton:hover {
+ background: var(--newtab-element-hover-color);
+ color: var(--newtab-text-primary-color); }
+
+.contentSearchHeaderRow > td > img,
+.contentSearchSuggestionRow > td > .historyIcon {
+ margin-inline-start: 7px;
+ margin-inline-end: 15px; }
+
+.context-menu {
+ background: var(--newtab-contextmenu-background-color);
+ border-radius: 5px;
+ box-shadow: 0 5px 10px rgba(0, 0, 0, 0.3), 0 0 0 1px rgba(0, 0, 0, 0.2);
+ display: block;
+ font-size: 14px;
+ margin-inline-start: 5px;
+ inset-inline-start: 100%;
+ position: absolute;
+ top: 6.75px;
+ z-index: 8; }
+ .context-menu > ul {
+ list-style: none;
+ margin: 0;
+ padding: 5px 0; }
+ .context-menu > ul > li {
+ margin: 0;
+ width: 100%; }
+ .context-menu > ul > li.separator {
+ border-bottom: 1px solid var(--newtab-border-secondary-color);
+ margin: 5px 0; }
+ .context-menu > ul > li > a,
+ .context-menu > ul > li > button {
+ align-items: center;
+ color: inherit;
+ cursor: pointer;
+ display: flex;
+ width: 100%;
+ line-height: 16px;
+ outline: none;
+ border: 0;
+ padding: 3px 12px;
+ white-space: nowrap; }
+ .context-menu > ul > li > a:is(:focus, :hover),
+ .context-menu > ul > li > button:is(:focus, :hover) {
+ background: var(--newtab-element-hover-color); }
+ .context-menu > ul > li > a:active,
+ .context-menu > ul > li > button:active {
+ background: var(--newtab-element-active-color); }
+ .context-menu > ul > li > a.disabled,
+ .context-menu > ul > li > button.disabled {
+ opacity: 0.4;
+ pointer-events: none; }
+
+.confirmation-dialog .modal {
+ box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.1);
+ left: 0;
+ margin: auto;
+ position: fixed;
+ right: 0;
+ top: 20%;
+ width: 400px; }
+
+.confirmation-dialog section {
+ margin: 0; }
+
+.confirmation-dialog .modal-message {
+ display: flex;
+ padding: 16px;
+ padding-bottom: 0; }
+ .confirmation-dialog .modal-message p {
+ margin: 0;
+ margin-bottom: 16px; }
+
+.confirmation-dialog .actions {
+ border: 0;
+ display: flex;
+ flex-wrap: nowrap;
+ padding: 0 16px; }
+ .confirmation-dialog .actions button {
+ margin-inline-end: 16px;
+ padding-inline-end: 18px;
+ padding-inline-start: 18px;
+ white-space: normal;
+ width: 50%; }
+ .confirmation-dialog .actions button.done {
+ margin-inline-end: 0;
+ margin-inline-start: 0; }
+
+.confirmation-dialog .icon {
+ margin-inline-end: 16px; }
+
+.modal-overlay {
+ background: var(--newtab-overlay-color);
+ height: 100%;
+ left: 0;
+ position: fixed;
+ top: 0;
+ width: 100%;
+ z-index: 11001; }
+
+.modal {
+ background: var(--newtab-modal-color);
+ border: 1px solid var(--newtab-border-secondary-color);
+ border-radius: 5px;
+ font-size: 15px;
+ z-index: 11002; }
+
+.customize-menu {
+ color: var(--customize-menu-primary-text-color);
+ background-color: var(--customize-menu-background);
+ width: 432px;
+ height: 100%;
+ position: fixed;
+ inset-block: 0;
+ inset-inline-end: 0;
+ z-index: 1001;
+ padding: 16px;
+ transition: transform 250ms cubic-bezier(0.46, 0.03, 0.52, 0.96);
+ overflow: auto;
+ transform: translateX(435px);
+ visibility: hidden;
+ cursor: default; }
+ .customize-menu:dir(rtl) {
+ transform: translateX(-435px); }
+ .customize-menu.customize-animate-enter-done {
+ transform: translateX(0); }
+ .customize-menu.customize-animate-enter-done, .customize-menu.customize-animate-enter-active, .customize-menu.customize-animate-enter {
+ box-shadow: 0 0 64px var(--customize-menu-first-shadow), 0 0 24px var(--customize-menu-second-shadow);
+ transition: transform 250ms cubic-bezier(0.46, 0.03, 0.52, 0.96), visibility 1ms;
+ visibility: visible; }
+ .customize-menu.customize-animate-exit-active, .customize-menu.customize-animate-exit {
+ box-shadow: 0 0 64px var(--customize-menu-first-shadow), 0 0 24px var(--customize-menu-second-shadow);
+ transition: transform 250ms cubic-bezier(0.46, 0.03, 0.52, 0.96), visibility 1ms 250ms;
+ visibility: visible; }
+ .customize-menu.customize-animate-exit-done {
+ transform: translateX(435px);
+ transition: transform 250ms cubic-bezier(0.46, 0.03, 0.52, 0.96), visibility 1ms 250ms; }
+ .customize-menu.customize-animate-exit-done:dir(rtl) {
+ transform: translateX(-435px); }
+ .customize-menu .close-button {
+ margin-inline-start: auto;
+ margin-bottom: 28px;
+ white-space: nowrap;
+ display: block;
+ background-color: var(--customize-menu-secondary-action-background);
+ padding: 8px 10px;
+ border: 1px solid rgba(0, 0, 0, 0.15);
+ border-radius: 4px;
+ color: var(--customize-menu-primary-text-color);
+ font-size: 13px;
+ font-weight: 600; }
+ .customize-menu .close-button:hover {
+ background-color: var(--customize-menu-secondary-action-background-hover); }
+ .customize-menu .close-button:hover:active {
+ background-color: var(--customize-menu-secondary-action-background-active); }
+
+.grid-skip {
+ display: contents; }
+
+.home-section {
+ display: grid;
+ grid-template-columns: 1fr;
+ grid-template-rows: repeat(4, auto);
+ grid-row-gap: 32px;
+ padding: 0 16px; }
+ .home-section .section {
+ display: grid;
+ grid-template-rows: auto;
+ grid-template-columns: auto 26px; }
+ .home-section .section > div {
+ grid-area: 1; }
+ .home-section .section .title {
+ grid-column: 1 / -1;
+ margin: 0;
+ font-weight: 600;
+ font-size: 16px;
+ margin-bottom: 10px; }
+ .home-section .section .subtitle {
+ margin: 0;
+ font-size: 14px; }
+ .home-section .section .sponsored {
+ font-size: 14px;
+ margin-inline-start: 5px; }
+ .home-section .section .check-wrapper {
+ position: relative; }
+ .home-section .section .sponsored-checkbox {
+ margin-inline-start: 2px;
+ width: 16px;
+ height: 16px;
+ vertical-align: middle;
+ border: 1px solid rgba(0, 0, 0, 0.15);
+ box-sizing: border-box;
+ border-radius: 4px;
+ appearance: none;
+ background-color: var(--newtab-primary-action-background-off); }
+ .home-section .section .sponsored-checkbox:checked {
+ -moz-context-properties: fill;
+ fill: var(--customize-menu-check-fill);
+ background: url("chrome://global/skin/icons/check.svg") center no-repeat;
+ background-color: var(--newtab-primary-action-background);
+ background-size: 10px; }
+ .home-section .section .sponsored-checkbox:active + .checkmark {
+ fill: rgba(0, 0, 0, 0.15); }
+ .home-section .section .selector {
+ color: var(--customize-menu-primary-text-color);
+ width: 118px;
+ display: block;
+ border: 1px solid var(--customize-menu-line-color);
+ border-radius: 4px;
+ appearance: none;
+ padding-block: 7px;
+ padding-inline: 10px 13px;
+ margin-inline-start: 2px;
+ -moz-context-properties: fill;
+ fill: var(--customize-menu-primary-text-color);
+ background: url("chrome://activity-stream/content/data/content/assets/glyph-arrowhead-down-12.svg") right no-repeat;
+ background-size: 8px;
+ background-origin: content-box;
+ background-color: var(--customize-menu-background); }
+ .home-section .section .selector:dir(rtl) {
+ background-position-x: left; }
+ .home-section .section .switch {
+ position: relative;
+ display: inline-block;
+ width: 26px;
+ height: 16px;
+ grid-column: 2;
+ margin-top: 2px; }
+ .home-section .section .switch input {
+ opacity: 0;
+ width: 0;
+ height: 0; }
+ .home-section .section .slider {
+ position: absolute;
+ inset: 0;
+ transition: transform 250ms;
+ border-radius: 13px;
+ border: 1px solid rgba(0, 0, 0, 0.15);
+ background-color: var(--newtab-primary-action-background-off); }
+ .home-section .section .slider::before {
+ position: absolute;
+ content: '';
+ height: 8px;
+ width: 8px;
+ inset-inline-start: 3px;
+ bottom: 3px;
+ background-color: var(--customize-menu-primary-action-text);
+ transition: transform 250ms;
+ border-radius: 50%;
+ outline: 1px solid rgba(0, 0, 0, 0.15);
+ -moz-outline-radius: 11px; }
+ .home-section .section .switch input:focus-visible + .slider {
+ border: 1px solid var(--newtab-focus-border-selected);
+ outline: 0;
+ box-shadow: 0 0 0 2px var(--newtab-focus-outline); }
+ .home-section .section .switch input:not(:checked):focus-visible + .slider {
+ border: 1px solid var(--newtab-focus-border); }
+ .home-section .section input:checked + .slider {
+ background-color: var(--newtab-primary-action-background); }
+ .home-section .section input:checked + .slider::before {
+ transform: translateX(10px); }
+ .home-section .section input:checked + .slider:dir(rtl)::before {
+ transform: translateX(-10px); }
+ .home-section .section .more-info-top-wrapper,
+ .home-section .section .more-info-pocket-wrapper {
+ margin-inline-start: -2px;
+ overflow: hidden;
+ transition: max-height 250ms cubic-bezier(0.82, 0.085, 0.395, 0.895); }
+ .home-section .section .more-info-top-wrapper.shrink,
+ .home-section .section .more-info-pocket-wrapper.shrink {
+ max-height: 0; }
+ .home-section .section .more-info-top-wrapper .more-information,
+ .home-section .section .more-info-pocket-wrapper .more-information {
+ padding-top: 12px;
+ position: relative;
+ transition: top 250ms cubic-bezier(0.82, 0.085, 0.395, 0.895); }
+ .home-section .section .more-info-top-wrapper .more-information.expand,
+ .home-section .section .more-info-pocket-wrapper .more-information.expand {
+ top: 0; }
+ .home-section .section .more-info-top-wrapper {
+ max-height: 78px; }
+ .home-section .section .more-info-top-wrapper .more-information {
+ top: -77px; }
+ .home-section .section .more-info-top-wrapper .check-wrapper {
+ margin-top: 10px; }
+ .home-section .section .more-info-pocket-wrapper {
+ max-height: 35px; }
+ .home-section .section .more-info-pocket-wrapper .more-information {
+ top: -35px; }
+ .home-section .divider {
+ border-top: 1px var(--customize-menu-seperator-line-color) solid;
+ margin: 0 -16px; }
+ .home-section .external-link {
+ font-size: 14px;
+ cursor: pointer;
+ border: 1px solid transparent;
+ border-radius: 4px;
+ -moz-context-properties: fill;
+ fill: var(--customize-menu-primary-text-color);
+ background: url("chrome://global/skin/icons/settings.svg") left no-repeat;
+ background-size: 16px;
+ padding-inline-start: 21px;
+ margin-bottom: 20px; }
+ .home-section .external-link:dir(rtl) {
+ background-position-x: right; }
+ .home-section .external-link:hover {
+ text-decoration: underline; }
+
+.home-section .section .sponsored-checkbox:focus-visible,
+.selector:focus-visible,
+.external-link:focus-visible,
+.close-button:focus-visible {
+ border: 1px solid var(--newtab-focus-border);
+ outline: 0;
+ box-shadow: 0 0 0 2px var(--newtab-focus-outline); }
+
+.outer-wrapper.newtab-experience .card-outer {
+ border-radius: 8px; }
+ .outer-wrapper.newtab-experience .card-outer:is(:focus):not(.placeholder) {
+ border: 0;
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-focus-outline), 0 0 0 1px var(--newtab-focus-border);
+ transition: none; }
+ .outer-wrapper.newtab-experience .card-outer:hover {
+ box-shadow: none;
+ transition: none; }
+ .outer-wrapper.newtab-experience .card-outer .card {
+ box-shadow: 0 3px 8px var(--newtab-card-first-shadow), 0 0 2px var(--newtab-card-second-shadow);
+ border-radius: 8px; }
+ .outer-wrapper.newtab-experience .card-outer .card-preview-image-outer {
+ border-radius: 8px 8px 0 0; }
+ .outer-wrapper.newtab-experience .card-outer .context-menu-button:is(:active, :focus) {
+ outline: 0;
+ fill: var(--newtab-primary-action-background);
+ border: 1px solid var(--newtab-primary-action-background); }
+ .outer-wrapper.newtab-experience .card-outer > a:is(:focus) .card {
+ border: 0;
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-focus-outline), 0 0 0 1px var(--newtab-focus-border); }
+
+.outer-wrapper:not(.newtab-experience) .card-outer:is(:hover, :focus, .active):not(.placeholder) {
+ box-shadow: 0 0 0 5px var(--newtab-card-active-outline-color);
+ transition: box-shadow 150ms; }
+
+.card-outer {
+ background: var(--newtab-card-background-color);
+ border-radius: 3px;
+ display: inline-block;
+ height: 266px;
+ margin-inline-end: 32px;
+ position: relative;
+ width: 100%; }
+ .card-outer .context-menu-button {
+ background-clip: padding-box;
+ background-color: var(--newtab-contextmenu-button-color);
+ background-image: url("chrome://global/skin/icons/more.svg");
+ background-position: 55%;
+ border: 1px solid var(--newtab-border-primary-color);
+ border-radius: 100%;
+ box-shadow: 0 2px rgba(12, 12, 13, 0.1);
+ cursor: pointer;
+ fill: var(--newtab-icon-primary-color);
+ height: 27px;
+ inset-inline-end: -13.5px;
+ opacity: 0;
+ position: absolute;
+ top: -13.5px;
+ transform: scale(0.25);
+ transition-duration: 150ms;
+ transition-property: transform, opacity;
+ width: 27px; }
+ .card-outer .context-menu-button:is(:active, :focus) {
+ opacity: 1;
+ transform: scale(1); }
+ .card-outer.placeholder {
+ background: transparent; }
+ .card-outer.placeholder .card {
+ box-shadow: inset 0 0 0 1px var(--newtab-inner-box-shadow-color); }
+ .card-outer.placeholder .card-preview-image-outer,
+ .card-outer.placeholder .card-context {
+ display: none; }
+ .card-outer .card {
+ border-radius: 3px;
+ box-shadow: var(--newtab-card-shadow);
+ height: 100%; }
+ .card-outer > a {
+ color: inherit;
+ display: block;
+ height: 100%;
+ outline: none;
+ position: absolute;
+ width: 100%; }
+ .card-outer > a:is(.active, :focus) .card {
+ box-shadow: 0 0 0 5px var(--newtab-card-active-outline-color);
+ transition: box-shadow 150ms; }
+ .card-outer > a:is(.active, :focus) .card-title {
+ color: var(--newtab-link-primary-color); }
+ .card-outer:is(:hover, :focus, .active):not(.placeholder) {
+ outline: none; }
+ .card-outer:is(:hover, :focus, .active):not(.placeholder) .context-menu-button {
+ opacity: 1;
+ transform: scale(1);
+ transition-delay: 333ms; }
+ .card-outer:is(:hover, :focus, .active):not(.placeholder) .card-title {
+ color: var(--newtab-link-primary-color); }
+ .card-outer:is(:hover, :focus, .active):not(.placeholder) .alternate ~ .card-host-name {
+ display: none; }
+ .card-outer:is(:hover, :focus, .active):not(.placeholder) .card-host-name.alternate {
+ display: block; }
+ .card-outer .card-preview-image-outer {
+ background-color: #D7D7DB;
+ border-radius: 3px 3px 0 0;
+ height: 122px;
+ overflow: hidden;
+ position: relative; }
+ [lwt-newtab-brighttext] .card-outer .card-preview-image-outer {
+ background-color: #4A4A4F; }
+ .card-outer .card-preview-image-outer::after {
+ border-bottom: 1px solid var(--newtab-card-hairline-color);
+ bottom: 0;
+ content: '';
+ position: absolute;
+ width: 100%; }
+ .card-outer .card-preview-image-outer .card-preview-image {
+ background-position: center;
+ background-repeat: no-repeat;
+ background-size: cover;
+ height: 100%;
+ opacity: 0;
+ transition: opacity 1s cubic-bezier(0.07, 0.95, 0, 1);
+ width: 100%; }
+ .card-outer .card-preview-image-outer .card-preview-image.loaded {
+ opacity: 1; }
+ .card-outer .card-details {
+ padding: 15px 16px 12px; }
+ .card-outer .card-text {
+ max-height: 78px;
+ overflow: hidden; }
+ .card-outer .card-text.no-host-name, .card-outer .card-text.no-context {
+ max-height: 97px; }
+ .card-outer .card-text.no-host-name.no-context {
+ max-height: 116px; }
+ .card-outer .card-text:not(.no-description) .card-title {
+ max-height: 57px;
+ overflow: hidden; }
+ .card-outer .card-host-name {
+ color: var(--newtab-text-secondary-color);
+ font-size: 10px;
+ overflow: hidden;
+ padding-bottom: 4px;
+ text-overflow: ellipsis;
+ text-transform: uppercase;
+ white-space: nowrap; }
+ .card-outer .card-host-name.alternate {
+ display: none; }
+ .card-outer .card-title {
+ font-size: 14px;
+ font-weight: 600;
+ line-height: 19px;
+ margin: 0 0 2px;
+ word-wrap: break-word; }
+ .card-outer .card-description {
+ font-size: 12px;
+ line-height: 19px;
+ margin: 0;
+ overflow: hidden;
+ word-wrap: break-word; }
+ .card-outer .card-context {
+ bottom: 0;
+ color: var(--newtab-text-secondary-color);
+ display: flex;
+ font-size: 11px;
+ inset-inline-start: 0;
+ padding: 9px 16px 9px 14px;
+ position: absolute; }
+ .card-outer .card-context-icon {
+ fill: var(--newtab-text-secondary-color);
+ height: 22px;
+ margin-inline-end: 6px; }
+ .card-outer .card-context-label {
+ flex-grow: 1;
+ line-height: 22px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap; }
+
+@media (min-width: 1122px) {
+ .normal-cards .card-outer {
+ height: 370px; }
+ .normal-cards .card-outer .card-preview-image-outer {
+ height: 155px; }
+ .normal-cards .card-outer .card-details {
+ padding: 13px 16px 12px; }
+ .normal-cards .card-outer .card-text {
+ max-height: 140px; }
+ .normal-cards .card-outer .card-host-name {
+ font-size: 12px;
+ padding-bottom: 5px; }
+ .normal-cards .card-outer .card-title {
+ font-size: 17px;
+ line-height: 23px;
+ margin-bottom: 0; }
+ .normal-cards .card-outer .card-text:not(.no-description) .card-title {
+ max-height: 69px; }
+ .normal-cards .card-outer .card-description {
+ font-size: 15px;
+ line-height: 23px; }
+ .normal-cards .card-outer .card-context {
+ bottom: 4px;
+ font-size: 14px; } }
+
+.compact-cards .card-outer {
+ height: 160px; }
+ .compact-cards .card-outer .card-preview-image-outer {
+ height: 108px; }
+ .compact-cards .card-outer .card-details {
+ padding: 12px 16px; }
+ .compact-cards .card-outer .card-host-name {
+ line-height: 10px; }
+ .compact-cards .card-outer .card-text .card-title,
+ .compact-cards .card-outer .card-text:not(.no-description) .card-title {
+ font-size: 12px;
+ line-height: 13px;
+ max-height: 17px;
+ overflow: hidden;
+ padding: 0 0 4px;
+ text-overflow: ellipsis;
+ white-space: nowrap; }
+ .compact-cards .card-outer .card-description {
+ display: none; }
+ .compact-cards .card-outer .card-context {
+ background-color: var(--newtab-card-background-color);
+ border-radius: 16px;
+ clip-path: inset(-1px -1px 4px);
+ height: 32px;
+ width: 32px;
+ padding: 8px;
+ top: 91px;
+ inset-inline-end: 12px;
+ inset-inline-start: auto; }
+ .compact-cards .card-outer .card-context::after {
+ border: 1px solid var(--newtab-card-hairline-color);
+ border-bottom: 0;
+ border-radius: 17px 17px 0 0;
+ content: '';
+ position: absolute;
+ height: 17px;
+ width: 34px;
+ top: -1px;
+ left: -1px; }
+ .compact-cards .card-outer .card-context .card-context-icon {
+ margin-inline-end: 0;
+ height: 16px;
+ width: 16px; }
+ .compact-cards .card-outer .card-context .card-context-icon.icon-bookmark-added {
+ fill: #0A84FF; }
+ .compact-cards .card-outer .card-context .card-context-icon.icon-download {
+ fill: #12BC00; }
+ .compact-cards .card-outer .card-context .card-context-icon.icon-pocket {
+ fill: #D70022; }
+ .compact-cards .card-outer .card-context .card-context-label {
+ display: none; }
+
+@media not all and (min-width: 1122px) {
+ .compact-cards .hide-for-narrow {
+ display: none; } }
+
+.outer-wrapper.newtab-experience .collapsible-section[data-section-id='topsites'] .section-top-bar {
+ display: none; }
+
+.outer-wrapper.newtab-experience .collapsible-section .click-target-container .click-target span {
+ cursor: default;
+ font-weight: 600;
+ font-size: 17px;
+ color: var(--newtab-background-primary-text-color); }
+
+.outer-wrapper:not(.newtab-experience) .collapsible-section .section-title span {
+ vertical-align: middle; }
+
+.collapsible-section {
+ padding: 10px 25px;
+ transition-delay: 100ms;
+ transition-duration: 100ms;
+ transition-property: background-color; }
+ .collapsible-section .section-title {
+ font-size: 13px;
+ font-weight: bold;
+ margin: 0; }
+ .collapsible-section .section-title.grey-title,
+ .collapsible-section .section-title span {
+ color: var(--newtab-section-header-text-color);
+ display: inline-block;
+ fill: var(--newtab-section-header-text-color); }
+ .collapsible-section .section-title.grey-title {
+ vertical-align: middle; }
+ .collapsible-section .section-title .click-target-container {
+ vertical-align: top; }
+ @media (max-width: 609px) {
+ .collapsible-section .section-title .click-target-container {
+ display: block; }
+ .collapsible-section .section-title .click-target-container .learn-more-link-wrapper {
+ display: block;
+ text-align: center; }
+ .collapsible-section .section-title .click-target-container .learn-more-link-wrapper .learn-more-link {
+ margin-inline-start: 0; } }
+ .collapsible-section .section-title .click-target-container .click-target {
+ white-space: nowrap;
+ cursor: pointer; }
+ .collapsible-section .section-title .collapsible-arrow {
+ margin-inline-start: 8px;
+ margin-top: -1px; }
+ .collapsible-section .section-top-bar {
+ min-height: 19px;
+ margin-bottom: 13px;
+ position: relative; }
+ .collapsible-section .section-top-bar .context-menu-button {
+ background: url("chrome://global/skin/icons/more.svg") no-repeat right center;
+ border: 0;
+ cursor: pointer;
+ fill: var(--newtab-section-header-text-color);
+ height: 100%;
+ inset-inline-end: 0;
+ opacity: 0;
+ position: absolute;
+ top: 0;
+ transition-duration: 200ms;
+ transition-property: opacity;
+ width: 27px; }
+ .collapsible-section .section-top-bar .context-menu-button:is(:active, :focus, :hover) {
+ fill: var(--newtab-section-header-text-color);
+ opacity: 1; }
+ .collapsible-section .section-top-bar .context-menu {
+ top: 16px; }
+ @media (max-width: 1458px) {
+ .collapsible-section .section-top-bar .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+ .collapsible-section:hover .section-top-bar .context-menu-button, .collapsible-section.active .section-top-bar .context-menu-button {
+ opacity: 1; }
+ .collapsible-section.active {
+ background: var(--newtab-element-hover-color);
+ border-radius: 4px; }
+ .collapsible-section.active .section-top-bar .context-menu-button {
+ fill: var(--newtab-section-active-contextmenu-color); }
+ .collapsible-section .learn-more-link {
+ font-size: 11px;
+ margin-inline-start: 12px; }
+ .collapsible-section .learn-more-link a {
+ color: var(--newtab-link-secondary-color); }
+ .collapsible-section .section-body-fallback {
+ height: 266px; }
+ .collapsible-section .section-body {
+ margin: 0 -7px;
+ padding: 0 7px; }
+ .collapsible-section .section-body.animating {
+ overflow: hidden;
+ pointer-events: none; }
+ .collapsible-section.animation-enabled .section-title .collapsible-arrow {
+ transition: transform 0.5s cubic-bezier(0.07, 0.95, 0, 1); }
+ .collapsible-section.animation-enabled .section-body {
+ transition: max-height 0.5s cubic-bezier(0.07, 0.95, 0, 1); }
+ .collapsible-section.collapsed .section-body {
+ max-height: 0;
+ overflow: hidden; }
+ @media (min-width: 610px) and (max-width: 865px) {
+ .collapsible-section[data-section-id='topstories'] .card-outer:first-child {
+ display: none; } }
+
+.asrouter-toggle {
+ position: fixed;
+ top: 50px;
+ inset-inline-end: 15px;
+ border: 0;
+ background: none;
+ z-index: 1;
+ border-radius: 2px; }
+ .asrouter-toggle .icon-devtools {
+ background-image: url("chrome://browser/skin/developer.svg");
+ padding: 15px; }
+ .asrouter-toggle:dir(rtl) {
+ transform: scaleX(-1); }
+ .asrouter-toggle:hover {
+ background: var(--newtab-element-hover-color); }
+ .asrouter-toggle.expanded {
+ background: rgba(0, 0, 0, 0.2); }
+
+.asrouter-admin {
+ position: fixed;
+ top: 0;
+ inset-inline-start: 0;
+ width: 100%;
+ background: var(--newtab-background-color);
+ height: 100%;
+ overflow-y: scroll;
+ margin: 0 auto;
+ font-size: 14px;
+ padding-inline-start: 240px;
+ color: var(--newtab-text-primary-color); }
+ .asrouter-admin.collapsed {
+ display: none; }
+ .asrouter-admin .sidebar {
+ inset-inline-start: 0;
+ position: fixed;
+ width: 240px;
+ padding: 30px 20px; }
+ .asrouter-admin .sidebar ul {
+ margin: 0;
+ padding: 0;
+ list-style: none; }
+ .asrouter-admin .sidebar li a {
+ padding: 10px 34px;
+ display: block;
+ color: var(--lwt-sidebar-text-color); }
+ .asrouter-admin .sidebar li a:hover {
+ background: var(--newtab-textbox-background-color); }
+ .asrouter-admin h1 {
+ font-weight: 200;
+ font-size: 32px; }
+ .asrouter-admin h2 .button,
+ .asrouter-admin p .button {
+ font-size: 14px;
+ padding: 6px 12px;
+ margin-inline-start: 5px;
+ margin-bottom: 0; }
+ .asrouter-admin .general-textarea {
+ direction: ltr;
+ width: 740px;
+ height: 500px;
+ overflow: auto;
+ resize: none;
+ border-radius: 4px;
+ display: flex; }
+ .asrouter-admin .wnp-textarea {
+ direction: ltr;
+ width: 740px;
+ height: 500px;
+ overflow: auto;
+ resize: none;
+ border-radius: 4px;
+ display: flex; }
+ .asrouter-admin .json-button {
+ display: inline-flex;
+ font-size: 10px;
+ padding: 4px 10px;
+ margin-bottom: 6px;
+ margin-inline-end: 4px; }
+ .asrouter-admin .json-button:hover {
+ background-color: rgba(237, 237, 240, 0.6);
+ box-shadow: none; }
+ .asrouter-admin table {
+ border-collapse: collapse;
+ width: 100%; }
+ .asrouter-admin table.minimal-table {
+ border-collapse: collapse;
+ border: 1px solid var(--newtab-border-secondary-color); }
+ .asrouter-admin table.minimal-table td {
+ padding: 8px; }
+ .asrouter-admin table.minimal-table td:first-child {
+ width: 1%;
+ white-space: nowrap; }
+ .asrouter-admin table.minimal-table td:not(:first-child) {
+ font-family: "SF Mono", "Monaco", "Inconsolata", "Fira Mono", "Droid Sans Mono", "Source Code Pro", monospace; }
+ .asrouter-admin table.errorReporting tr {
+ border: 1px solid var(--newtab-textbox-background-color); }
+ .asrouter-admin table.errorReporting td {
+ padding: 4px; }
+ .asrouter-admin table.errorReporting td[rowspan] {
+ border: 1px solid var(--newtab-textbox-background-color); }
+ .asrouter-admin .sourceLabel {
+ background: var(--newtab-textbox-background-color);
+ padding: 2px 5px;
+ border-radius: 3px; }
+ .asrouter-admin .sourceLabel.isDisabled {
+ background: rgba(215, 0, 34, 0.3);
+ color: #D70022; }
+ .asrouter-admin .message-item:first-child td {
+ border-top: 1px solid var(--newtab-border-secondary-color); }
+ .asrouter-admin .message-item td {
+ vertical-align: top;
+ padding: 8px;
+ border-bottom: 1px solid var(--newtab-border-secondary-color); }
+ .asrouter-admin .message-item td.min {
+ width: 1%;
+ white-space: nowrap; }
+ .asrouter-admin .message-item td.message-summary {
+ width: 60%; }
+ .asrouter-admin .message-item td.button-column {
+ width: 15%; }
+ .asrouter-admin .message-item td:first-child {
+ border-inline-start: 1px solid var(--newtab-border-secondary-color); }
+ .asrouter-admin .message-item td:last-child {
+ border-inline-end: 1px solid var(--newtab-border-secondary-color); }
+ .asrouter-admin .message-item.blocked .message-id,
+ .asrouter-admin .message-item.blocked .message-summary {
+ opacity: 0.5; }
+ .asrouter-admin .message-item.blocked .message-id {
+ opacity: 0.5; }
+ .asrouter-admin .message-item .message-id {
+ font-family: "SF Mono", "Monaco", "Inconsolata", "Fira Mono", "Droid Sans Mono", "Source Code Pro", monospace;
+ font-size: 12px; }
+ .asrouter-admin .providerUrl {
+ font-size: 12px; }
+ .asrouter-admin pre {
+ background: var(--newtab-textbox-background-color);
+ margin: 0;
+ padding: 8px;
+ font-size: 12px;
+ max-width: 750px;
+ overflow: auto;
+ font-family: "SF Mono", "Monaco", "Inconsolata", "Fira Mono", "Droid Sans Mono", "Source Code Pro", monospace; }
+ .asrouter-admin .errorState {
+ border: 1px solid #D70022; }
+ .asrouter-admin .helpLink {
+ padding: 10px;
+ display: flex;
+ background: rgba(0, 0, 0, 0.1);
+ border-radius: 3px; }
+ .asrouter-admin .helpLink a {
+ text-decoration: underline; }
+ .asrouter-admin .ds-component {
+ margin-bottom: 20px; }
+ .asrouter-admin .modalOverlayInner {
+ height: 80%; }
+ .asrouter-admin .clearButton {
+ border: 0;
+ padding: 4px;
+ border-radius: 4px;
+ display: flex; }
+ .asrouter-admin .clearButton:hover {
+ background: var(--newtab-element-hover-color); }
+ .asrouter-admin .collapsed {
+ display: none; }
+ .asrouter-admin .icon {
+ display: inline-table;
+ cursor: pointer;
+ width: 18px;
+ height: 18px; }
+
+.pocket-logged-in-cta {
+ font-size: 13px;
+ margin-inline-end: 20px;
+ display: flex;
+ align-items: flex-start; }
+ .pocket-logged-in-cta .pocket-cta-button {
+ white-space: nowrap;
+ background: #0060DF;
+ letter-spacing: -0.34px;
+ color: #FFF;
+ border-radius: 4px;
+ cursor: pointer;
+ max-width: 130px;
+ margin-top: -1px;
+ min-height: 18px;
+ padding: 0 8px;
+ display: inline-flex;
+ justify-content: center;
+ align-items: center;
+ font-size: 11px;
+ margin-inline-end: 10px; }
+ .pocket-logged-in-cta .cta-text {
+ font-weight: normal;
+ font-size: 13px;
+ line-height: 1.230769231; }
+ .pocket-logged-in-cta .pocket-cta-button,
+ .pocket-logged-in-cta .cta-text {
+ vertical-align: top; }
+
+.more-recommendations {
+ display: flex;
+ align-items: center;
+ white-space: nowrap;
+ line-height: 1.230769231; }
+ .more-recommendations::after {
+ background: url("chrome://activity-stream/content/data/content/assets/topic-show-more-12.svg") no-repeat center center;
+ content: '';
+ -moz-context-properties: fill;
+ display: inline-block;
+ fill: var(--newtab-link-secondary-color);
+ height: 16px;
+ margin-inline-start: 5px;
+ vertical-align: top;
+ width: 12px; }
+ .more-recommendations:dir(rtl)::after {
+ transform: scaleX(-1); }
+
+.discovery-stream.ds-layout {
+ --gridColumnGap: 48px;
+ --gridRowGap: 24px;
+ grid-template-columns: repeat(12, 1fr);
+ grid-column-gap: var(--gridColumnGap);
+ grid-row-gap: var(--gridRowGap);
+ margin: 0 auto; }
+ .discovery-stream.ds-layout .ds-column-12 {
+ grid-column-start: auto;
+ grid-column-end: span 12; }
+ .discovery-stream.ds-layout .ds-column-11 {
+ grid-column-start: auto;
+ grid-column-end: span 11; }
+ .discovery-stream.ds-layout .ds-column-10 {
+ grid-column-start: auto;
+ grid-column-end: span 10; }
+ .discovery-stream.ds-layout .ds-column-9 {
+ grid-column-start: auto;
+ grid-column-end: span 9; }
+ .discovery-stream.ds-layout .ds-column-8 {
+ grid-column-start: auto;
+ grid-column-end: span 8; }
+ .discovery-stream.ds-layout .ds-column-7 {
+ grid-column-start: auto;
+ grid-column-end: span 7; }
+ .discovery-stream.ds-layout .ds-column-6 {
+ grid-column-start: auto;
+ grid-column-end: span 6; }
+ .discovery-stream.ds-layout .ds-column-5 {
+ grid-column-start: auto;
+ grid-column-end: span 5; }
+ .discovery-stream.ds-layout .ds-column-4 {
+ grid-column-start: auto;
+ grid-column-end: span 4; }
+ .discovery-stream.ds-layout .ds-column-3 {
+ grid-column-start: auto;
+ grid-column-end: span 3; }
+ .discovery-stream.ds-layout .ds-column-2 {
+ grid-column-start: auto;
+ grid-column-end: span 2; }
+ .discovery-stream.ds-layout .ds-column-1 {
+ grid-column-start: auto;
+ grid-column-end: span 1; }
+ .discovery-stream.ds-layout .ds-column-grid {
+ display: grid;
+ grid-row-gap: var(--gridRowGap); }
+ .discovery-stream.ds-layout .ds-column-grid > div:empty {
+ display: none; }
+
+.ds-header {
+ margin: 8px 0; }
+ .ds-header .ds-context {
+ font-weight: 400; }
+
+.ds-header,
+.ds-layout .section-title span {
+ color: #737373;
+ font-size: 13px;
+ font-weight: 600;
+ line-height: 20px; }
+ [lwt-newtab-brighttext] .ds-header, [lwt-newtab-brighttext]
+ .ds-layout .section-title span {
+ color: #D7D7DB; }
+ .ds-header .icon,
+ .ds-layout .section-title span .icon {
+ fill: var(--newtab-text-secondary-color); }
+
+.collapsible-section.ds-layout {
+ margin: auto; }
+ .collapsible-section.ds-layout .section-top-bar .learn-more-link a {
+ color: var(--newtab-link-primary-color);
+ font-weight: normal; }
+ .collapsible-section.ds-layout .section-top-bar .learn-more-link a:is(:focus, :hover) {
+ text-decoration: underline; }
+
+.outer-wrapper.newtab-experience .ds-card-grid.ds-card-grid-border .ds-card:not(.placeholder) {
+ border-radius: 8px;
+ box-shadow: 0 3px 8px var(--newtab-card-first-shadow), 0 0 2px var(--newtab-card-second-shadow); }
+ .outer-wrapper.newtab-experience .ds-card-grid.ds-card-grid-border .ds-card:not(.placeholder) .img-wrapper .img img {
+ border-radius: 8px 8px 0 0; }
+
+.outer-wrapper.newtab-experience .ds-card-grid .ds-card-link:focus {
+ border: 0;
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-focus-outline), 0 0 0 1px var(--newtab-focus-border);
+ transition: none;
+ border-radius: 8px; }
+
+.ds-card-grid {
+ display: grid;
+ grid-gap: 24px; }
+ .ds-card-grid .ds-card {
+ background: #FFF;
+ border-radius: 4px; }
+ [lwt-newtab-brighttext] .ds-card-grid .ds-card {
+ background: none; }
+ @media (min-width: 866px) {
+ .ds-column-12 .ds-card-grid.ds-card-grid-hero {
+ grid-template-columns: repeat(12, 1fr); }
+ .ds-column-12 .ds-card-grid.ds-card-grid-hero .ds-card:nth-child(1) {
+ grid-column-start: 1;
+ grid-column-end: span 6;
+ grid-row-start: 1;
+ grid-row-end: span 2; }
+ .ds-column-12 .ds-card-grid.ds-card-grid-hero .ds-card:nth-child(1) .excerpt {
+ -webkit-line-clamp: 4; }
+ .ds-column-12 .ds-card-grid.ds-card-grid-hero .ds-card:nth-child(2),
+ .ds-column-12 .ds-card-grid.ds-card-grid-hero .ds-card:nth-child(4) {
+ grid-column-start: 7;
+ grid-column-end: span 3; }
+ .ds-column-12 .ds-card-grid.ds-card-grid-hero .ds-card:nth-child(3),
+ .ds-column-12 .ds-card-grid.ds-card-grid-hero .ds-card:nth-child(5) {
+ grid-column-start: 10;
+ grid-column-end: span 3; }
+ .ds-column-12 .ds-card-grid.ds-card-grid-hero .ds-card:nth-child(n+2):nth-child(-n+5) .excerpt {
+ display: none; }
+ .ds-column-12 .ds-card-grid.ds-card-grid-hero .ds-card:nth-child(n+2):nth-child(-n+5) .meta {
+ padding: 8px; }
+ .ds-column-12 .ds-card-grid.ds-card-grid-hero .ds-card:nth-child(n+2):nth-child(-n+5) .meta .title {
+ font-size: 13px;
+ line-height: 19px; }
+ .ds-column-12 .ds-card-grid.ds-card-grid-hero .ds-card:nth-child(n+2):nth-child(-n+5) .meta .story-sponsored-label {
+ -webkit-line-clamp: none;
+ line-height: 19px; }
+ .ds-column-12 .ds-card-grid.ds-card-grid-hero .ds-card:nth-child(n+6) {
+ grid-column-start: auto;
+ grid-column-end: span 4; } }
+ @media (min-width: 1122px) {
+ .ds-column-12 .ds-card-grid.ds-card-grid-hero .ds-card:nth-child(n+2):nth-child(-n+5) {
+ min-height: 222px; } }
+ .ds-card-grid.ds-card-grid-border .ds-card:not(.placeholder) {
+ box-shadow: 0 1px 4px 0 rgba(12, 12, 13, 0.1); }
+ [lwt-newtab-brighttext] .ds-card-grid.ds-card-grid-border .ds-card:not(.placeholder) {
+ box-shadow: 0 1px 4px rgba(12, 12, 13, 0.1);
+ background: #38383D; }
+ .ds-card-grid.ds-card-grid-border .ds-card:not(.placeholder) .img-wrapper .img img {
+ border-radius: 4px 4px 0 0; }
+ .ds-card-grid.ds-card-grid-no-border .ds-card {
+ background: none; }
+ .ds-card-grid.ds-card-grid-no-border .ds-card .meta {
+ padding: 12px 0; }
+ .ds-column-5 .ds-card-grid,
+ .ds-column-6 .ds-card-grid,
+ .ds-column-7 .ds-card-grid,
+ .ds-column-8 .ds-card-grid {
+ grid-template-columns: repeat(2, 1fr); }
+ .ds-column-9 .ds-card-grid,
+ .ds-column-10 .ds-card-grid,
+ .ds-column-11 .ds-card-grid,
+ .ds-column-12 .ds-card-grid {
+ grid-template-columns: repeat(1, 1fr); }
+ @media (min-width: 610px) {
+ .ds-column-9 .ds-card-grid,
+ .ds-column-10 .ds-card-grid,
+ .ds-column-11 .ds-card-grid,
+ .ds-column-12 .ds-card-grid {
+ grid-template-columns: repeat(2, 1fr); } }
+ @media (min-width: 866px) {
+ .ds-column-9 .ds-card-grid,
+ .ds-column-10 .ds-card-grid,
+ .ds-column-11 .ds-card-grid,
+ .ds-column-12 .ds-card-grid {
+ grid-template-columns: repeat(3, 1fr); } }
+ .ds-column-9 .ds-card-grid .title,
+ .ds-column-10 .ds-card-grid .title,
+ .ds-column-11 .ds-card-grid .title,
+ .ds-column-12 .ds-card-grid .title {
+ font-size: 17px;
+ line-height: 24px; }
+ .ds-column-9 .ds-card-grid .excerpt,
+ .ds-column-10 .ds-card-grid .excerpt,
+ .ds-column-11 .ds-card-grid .excerpt,
+ .ds-column-12 .ds-card-grid .excerpt {
+ font-size: 15px;
+ -webkit-line-clamp: 3;
+ line-height: 24px; }
+ .ds-card-grid.empty {
+ grid-template-columns: auto; }
+
+.ds-dismiss.ds-dismiss-ds-collection .ds-dismiss-button {
+ margin: 15px 0 0;
+ inset-inline-end: 25px; }
+
+.ds-dismiss.ds-dismiss-ds-collection.hovering {
+ background: var(--newtab-element-hover-color); }
+
+.ds-collection-card-grid {
+ padding: 10px 25px 25px;
+ margin: 0 0 20px; }
+ .ds-collection-card-grid .story-footer {
+ display: none; }
+ .ds-collection-card-grid .ds-header {
+ padding: 0 40px 0 0;
+ margin-bottom: 12px; }
+ .ds-collection-card-grid .ds-header .title {
+ color: #0C0C0D;
+ font-weight: 600;
+ font-size: 17px;
+ line-height: 24px; }
+ [lwt-newtab-brighttext] .ds-collection-card-grid .ds-header .title {
+ color: #D7D7DB; }
+ .ds-collection-card-grid .ds-header .ds-context {
+ color: #737373;
+ font-weight: normal;
+ font-size: 13px;
+ line-height: 24px; }
+ [lwt-newtab-brighttext] .ds-collection-card-grid .ds-header .ds-context {
+ color: #B1B1B3; }
+
+.ds-hero {
+ position: relative; }
+ .ds-hero header {
+ font-weight: 600; }
+ .ds-hero p {
+ line-height: 1.538;
+ margin: 8px 0; }
+ .ds-hero .excerpt {
+ font-size: 15px;
+ -webkit-line-clamp: 3;
+ line-height: 24px;
+ color: #0C0C0D;
+ margin: 0 0 10px; }
+ [lwt-newtab-brighttext] .ds-hero .excerpt {
+ color: #F9F9FA; }
+ .ds-hero .ds-card:not(.placeholder) {
+ border: 0;
+ padding-bottom: 20px; }
+ .ds-hero .ds-card:not(.placeholder):hover {
+ border: 0;
+ box-shadow: none;
+ border-radius: 0; }
+ .ds-hero .ds-card:not(.placeholder) .meta {
+ padding: 0; }
+ .ds-hero .ds-card:not(.placeholder) .img-wrapper {
+ margin: 0 0 12px; }
+ .ds-hero .ds-card.placeholder {
+ margin-bottom: 20px;
+ padding-bottom: 20px;
+ min-height: 180px; }
+ .ds-hero .img-wrapper {
+ margin: 0 0 12px; }
+ .ds-hero .ds-hero-item {
+ position: relative; }
+ .ds-hero .wrapper {
+ border-top: 1px solid #D7D7DB;
+ color: #737373;
+ display: block;
+ margin: 12px 0 16px;
+ padding-top: 16px;
+ height: 100%; }
+ [lwt-newtab-brighttext] .ds-hero .wrapper {
+ border-top: 1px solid #4A4A4F; }
+ [lwt-newtab-brighttext] .ds-hero .wrapper {
+ color: #D7D7DB; }
+ .ds-hero .wrapper:focus {
+ box-shadow: 0 0 0 5px rgba(10, 132, 255, 0.3);
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+ .ds-hero-no-border .ds-hero-item .wrapper {
+ border-top: 0;
+ border-bottom: 0;
+ padding: 0 0 8px; }
+ .ds-hero .wrapper:hover .meta header {
+ color: #0060DF; }
+ [lwt-newtab-brighttext] .ds-hero .wrapper:hover .meta header {
+ color: #45A1FF; }
+ .ds-hero .wrapper:active .meta header {
+ color: #003EAA; }
+ [lwt-newtab-brighttext] .ds-hero .wrapper:active .meta header {
+ color: #45A1FF; }
+ .ds-hero .wrapper .img-wrapper {
+ width: 100%; }
+ .ds-hero .wrapper .img {
+ height: 0;
+ padding-top: 50%; }
+ .ds-hero .wrapper .img img {
+ border-radius: 4px;
+ box-shadow: inset 0 0 0 0.5px rgba(0, 0, 0, 0.15); }
+ .ds-hero .wrapper .meta {
+ display: block;
+ flex-direction: column;
+ justify-content: space-between; }
+ .ds-hero .wrapper .meta .header-and-excerpt {
+ flex: 1; }
+ .ds-hero .wrapper .meta header {
+ font-size: 22px;
+ -webkit-line-clamp: 4;
+ line-height: 28px;
+ color: #0C0C0D;
+ margin-bottom: 0; }
+ [lwt-newtab-brighttext] .ds-hero .wrapper .meta header {
+ color: #FFF; }
+ .ds-hero .wrapper .meta .context,
+ .ds-hero .wrapper .meta .source {
+ margin: 0 0 4px; }
+ .ds-hero .wrapper .meta .context {
+ color: #008EA4; }
+ [lwt-newtab-brighttext] .ds-hero .wrapper .meta .context {
+ color: #A7FFFE; }
+ .ds-hero .wrapper .meta .source {
+ font-size: 13px;
+ color: #737373;
+ -webkit-line-clamp: 1;
+ margin-bottom: 0; }
+ [lwt-newtab-brighttext] .ds-hero .wrapper .meta .source {
+ color: #B1B1B3; }
+ .ds-column-5 .ds-hero .wrapper,
+ .ds-column-6 .ds-hero .wrapper,
+ .ds-column-7 .ds-hero .wrapper,
+ .ds-column-8 .ds-hero .wrapper {
+ display: grid;
+ grid-template-columns: repeat(2, 1fr);
+ grid-column-gap: 24px; }
+ .ds-column-5 .ds-hero .wrapper .img-wrapper,
+ .ds-column-6 .ds-hero .wrapper .img-wrapper,
+ .ds-column-7 .ds-hero .wrapper .img-wrapper,
+ .ds-column-8 .ds-hero .wrapper .img-wrapper {
+ margin: 0;
+ grid-column: 2;
+ grid-row: 1; }
+ .ds-column-5 .ds-hero .wrapper .meta,
+ .ds-column-6 .ds-hero .wrapper .meta,
+ .ds-column-7 .ds-hero .wrapper .meta,
+ .ds-column-8 .ds-hero .wrapper .meta {
+ grid-column: 1;
+ grid-row: 1;
+ display: flex; }
+ .ds-column-5 .ds-hero .wrapper .img,
+ .ds-column-6 .ds-hero .wrapper .img,
+ .ds-column-7 .ds-hero .wrapper .img,
+ .ds-column-8 .ds-hero .wrapper .img {
+ height: 0;
+ padding-top: 100%; }
+ .ds-column-5 .ds-hero .cards,
+ .ds-column-6 .ds-hero .cards,
+ .ds-column-7 .ds-hero .cards,
+ .ds-column-8 .ds-hero .cards {
+ display: grid;
+ grid-template-columns: repeat(2, 1fr);
+ grid-column-gap: 24px;
+ grid-auto-rows: min-content; }
+ .ds-column-9 .ds-hero,
+ .ds-column-10 .ds-hero,
+ .ds-column-11 .ds-hero,
+ .ds-column-12 .ds-hero {
+ display: grid;
+ grid-template-columns: repeat(2, 1fr);
+ grid-column-gap: 24px; }
+ .ds-column-9 .ds-hero.ds-hero-border,
+ .ds-column-10 .ds-hero.ds-hero-border,
+ .ds-column-11 .ds-hero.ds-hero-border,
+ .ds-column-12 .ds-hero.ds-hero-border {
+ border-top: 1px solid #D7D7DB;
+ padding: 20px 0; }
+ [lwt-newtab-brighttext] .ds-column-9 .ds-hero.ds-hero-border, [lwt-newtab-brighttext]
+ .ds-column-10 .ds-hero.ds-hero-border, [lwt-newtab-brighttext]
+ .ds-column-11 .ds-hero.ds-hero-border, [lwt-newtab-brighttext]
+ .ds-column-12 .ds-hero.ds-hero-border {
+ border-top: 1px solid #4A4A4F; }
+ .ds-column-9 .ds-hero.ds-hero-border .ds-card:not(.placeholder):nth-child(-n+2),
+ .ds-column-10 .ds-hero.ds-hero-border .ds-card:not(.placeholder):nth-child(-n+2),
+ .ds-column-11 .ds-hero.ds-hero-border .ds-card:not(.placeholder):nth-child(-n+2),
+ .ds-column-12 .ds-hero.ds-hero-border .ds-card:not(.placeholder):nth-child(-n+2) {
+ border-bottom: 1px solid #D7D7DB;
+ margin-bottom: 20px; }
+ [lwt-newtab-brighttext] .ds-column-9 .ds-hero.ds-hero-border .ds-card:not(.placeholder):nth-child(-n+2), [lwt-newtab-brighttext]
+ .ds-column-10 .ds-hero.ds-hero-border .ds-card:not(.placeholder):nth-child(-n+2), [lwt-newtab-brighttext]
+ .ds-column-11 .ds-hero.ds-hero-border .ds-card:not(.placeholder):nth-child(-n+2), [lwt-newtab-brighttext]
+ .ds-column-12 .ds-hero.ds-hero-border .ds-card:not(.placeholder):nth-child(-n+2) {
+ border-bottom: 1px solid #4A4A4F; }
+ .ds-column-9 .ds-hero .wrapper,
+ .ds-column-10 .ds-hero .wrapper,
+ .ds-column-11 .ds-hero .wrapper,
+ .ds-column-12 .ds-hero .wrapper {
+ border-top: 0;
+ border-bottom: 0;
+ margin: 0;
+ padding: 0 0 20px;
+ display: flex;
+ flex-direction: column; }
+ .ds-column-9 .ds-hero .wrapper .img-wrapper,
+ .ds-column-10 .ds-hero .wrapper .img-wrapper,
+ .ds-column-11 .ds-hero .wrapper .img-wrapper,
+ .ds-column-12 .ds-hero .wrapper .img-wrapper {
+ margin: 0; }
+ .ds-column-9 .ds-hero .wrapper .img,
+ .ds-column-10 .ds-hero .wrapper .img,
+ .ds-column-11 .ds-hero .wrapper .img,
+ .ds-column-12 .ds-hero .wrapper .img {
+ margin-bottom: 12px;
+ height: 0;
+ padding-top: 50%; }
+ .ds-column-9 .ds-hero .wrapper .meta,
+ .ds-column-10 .ds-hero .wrapper .meta,
+ .ds-column-11 .ds-hero .wrapper .meta,
+ .ds-column-12 .ds-hero .wrapper .meta {
+ flex-grow: 1;
+ display: flex;
+ padding: 0 24px 0 0; }
+ .ds-column-9 .ds-hero .wrapper .meta header,
+ .ds-column-10 .ds-hero .wrapper .meta header,
+ .ds-column-11 .ds-hero .wrapper .meta header,
+ .ds-column-12 .ds-hero .wrapper .meta header {
+ font-size: 22px;
+ -webkit-line-clamp: 3;
+ line-height: 28px; }
+ .ds-column-9 .ds-hero .wrapper .meta .source,
+ .ds-column-10 .ds-hero .wrapper .meta .source,
+ .ds-column-11 .ds-hero .wrapper .meta .source,
+ .ds-column-12 .ds-hero .wrapper .meta .source {
+ margin-bottom: 0; }
+ .ds-column-9 .ds-hero .cards,
+ .ds-column-10 .ds-hero .cards,
+ .ds-column-11 .ds-hero .cards,
+ .ds-column-12 .ds-hero .cards {
+ display: grid;
+ grid-template-columns: repeat(2, 1fr);
+ grid-column-gap: 24px;
+ grid-auto-rows: min-content; }
+ [lwt-newtab-brighttext] .ds-column-9 .ds-hero .cards .ds-card:hover, [lwt-newtab-brighttext]
+ .ds-column-10 .ds-hero .cards .ds-card:hover, [lwt-newtab-brighttext]
+ .ds-column-11 .ds-hero .cards .ds-card:hover, [lwt-newtab-brighttext]
+ .ds-column-12 .ds-hero .cards .ds-card:hover {
+ background: none; }
+ [lwt-newtab-brighttext] .ds-column-9 .ds-hero .cards .ds-card:hover .title, [lwt-newtab-brighttext]
+ .ds-column-10 .ds-hero .cards .ds-card:hover .title, [lwt-newtab-brighttext]
+ .ds-column-11 .ds-hero .cards .ds-card:hover .title, [lwt-newtab-brighttext]
+ .ds-column-12 .ds-hero .cards .ds-card:hover .title {
+ color: #45A1FF; }
+ [lwt-newtab-brighttext] .ds-column-9 .ds-hero .cards .ds-card:active .title, [lwt-newtab-brighttext]
+ .ds-column-10 .ds-hero .cards .ds-card:active .title, [lwt-newtab-brighttext]
+ .ds-column-11 .ds-hero .cards .ds-card:active .title, [lwt-newtab-brighttext]
+ .ds-column-12 .ds-hero .cards .ds-card:active .title {
+ color: #0A84FF; }
+ .ds-column-9 .ds-hero .cards .ds-card .title,
+ .ds-column-10 .ds-hero .cards .ds-card .title,
+ .ds-column-11 .ds-hero .cards .ds-card .title,
+ .ds-column-12 .ds-hero .cards .ds-card .title {
+ font-size: 14px;
+ -webkit-line-clamp: 3;
+ line-height: 20px; }
+ [lwt-newtab-brighttext] .ds-column-9 .ds-hero .cards .ds-card .title, [lwt-newtab-brighttext]
+ .ds-column-10 .ds-hero .cards .ds-card .title, [lwt-newtab-brighttext]
+ .ds-column-11 .ds-hero .cards .ds-card .title, [lwt-newtab-brighttext]
+ .ds-column-12 .ds-hero .cards .ds-card .title {
+ color: #FFF; }
+ .ds-hero.empty {
+ grid-template-columns: auto; }
+
+.ds-highlights .section .section-list {
+ grid-gap: var(--gridRowGap);
+ grid-template-columns: repeat(1, 1fr); }
+ @media (min-width: 610px) {
+ .ds-highlights .section .section-list {
+ grid-template-columns: repeat(2, 1fr); } }
+ @media (min-width: 866px) {
+ .ds-highlights .section .section-list {
+ grid-template-columns: repeat(4, 1fr); } }
+ .ds-highlights .section .section-list .card-outer {
+ height: 175px; }
+ .ds-highlights .section .section-list .card-outer .card-host-name {
+ font-size: 13px;
+ line-height: 20px;
+ margin-bottom: 2px;
+ padding-bottom: 0;
+ text-transform: unset; }
+ .ds-highlights .section .section-list .card-outer .card-title {
+ font-size: 14px;
+ font-weight: 600;
+ line-height: 20px;
+ max-height: 20px; }
+
+.ds-highlights .hide-for-narrow {
+ display: block; }
+
+.ds-hr {
+ border: 0;
+ border-top: 1px solid #D7D7DB;
+ height: 0; }
+ [lwt-newtab-brighttext] .ds-hr {
+ border-top: 1px solid #4A4A4F; }
+
+.ds-list {
+ display: grid;
+ grid-row-gap: 24px;
+ grid-column-gap: 24px;
+ padding-inline-start: 0; }
+ .ds-list:not(.ds-list-full-width) .ds-list-item {
+ font-size: 14px;
+ line-height: 20px;
+ position: relative; }
+ .ds-list:not(.ds-list-full-width) .ds-list-item-title {
+ font-size: 14px;
+ -webkit-line-clamp: 3;
+ line-height: 20px; }
+ .ds-list:not(.ds-list-full-width) .ds-list-image {
+ min-width: 80px;
+ width: 80px; }
+ .ds-column-5 .ds-list:not(.ds-list-full-width),
+ .ds-column-6 .ds-list:not(.ds-list-full-width),
+ .ds-column-7 .ds-list:not(.ds-list-full-width),
+ .ds-column-8 .ds-list:not(.ds-list-full-width) {
+ grid-template-columns: repeat(2, 1fr); }
+ .ds-column-9 .ds-list:not(.ds-list-full-width),
+ .ds-column-10 .ds-list:not(.ds-list-full-width),
+ .ds-column-11 .ds-list:not(.ds-list-full-width),
+ .ds-column-12 .ds-list:not(.ds-list-full-width) {
+ grid-template-columns: repeat(3, 1fr); }
+ .ds-list:not(.ds-list-full-width).empty {
+ grid-template-columns: auto; }
+ .ds-list:not(.ds-list-full-width) .ds-list-item-excerpt {
+ display: none; }
+ .ds-list:not(.ds-list-images) .ds-list-image {
+ display: none; }
+ .ds-list a {
+ color: #0C0C0D; }
+ [lwt-newtab-brighttext] .ds-list a {
+ color: #F9F9FA; }
+
+.ds-list-item-link:focus {
+ box-shadow: 0 0 0 5px rgba(10, 132, 255, 0.3);
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+
+.ds-list-numbers .ds-list-item {
+ counter-increment: list; }
+
+.ds-list-numbers .ds-list-item:not(.placeholder) > .ds-list-item-link {
+ padding-inline-start: 41px; }
+ .ds-list-numbers .ds-list-item:not(.placeholder) > .ds-list-item-link::before {
+ background-color: #50BCB6;
+ border-radius: 32px;
+ color: #FFF;
+ content: counter(list);
+ font-size: 17px;
+ height: 32px;
+ line-height: 32px;
+ margin-inline-start: -41px;
+ margin-top: 3px;
+ position: absolute;
+ text-align: center;
+ width: 32px; }
+ [lwt-newtab-brighttext] .ds-list-numbers .ds-list-item:not(.placeholder) > .ds-list-item-link::before {
+ background-color: #008EA4; }
+ .ds-list-numbers .ds-list-item:not(.placeholder) > .ds-list-item-link:hover::before {
+ background-color: #45A1FF; }
+ [lwt-newtab-brighttext] .ds-list-numbers .ds-list-item:not(.placeholder) > .ds-list-item-link:hover::before {
+ background-color: #45A1FF; }
+ .ds-list-numbers .ds-list-item:not(.placeholder) > .ds-list-item-link:active::before {
+ background-color: #003EAA; }
+ [lwt-newtab-brighttext] .ds-list-numbers .ds-list-item:not(.placeholder) > .ds-list-item-link:active::before {
+ background-color: #0060DF; }
+
+.ds-list-borders {
+ border-top: 1px solid #D7D7DB;
+ grid-row-gap: 16px;
+ padding-top: 16px; }
+ [lwt-newtab-brighttext] .ds-list-borders {
+ border-top: 1px solid #4A4A4F; }
+ .ds-list-borders.ds-list-full-width .ds-list-item:not(.placeholder):not(:nth-last-child(-n+1)),
+ .ds-column-1 .ds-list-borders .ds-list-item:not(.placeholder):not(:nth-last-child(-n+1)),
+ .ds-column-2 .ds-list-borders .ds-list-item:not(.placeholder):not(:nth-last-child(-n+1)),
+ .ds-column-3 .ds-list-borders .ds-list-item:not(.placeholder):not(:nth-last-child(-n+1)),
+ .ds-column-4 .ds-list-borders .ds-list-item:not(.placeholder):not(:nth-last-child(-n+1)) {
+ border-bottom: 1px solid #D7D7DB;
+ margin-bottom: -1px;
+ padding-bottom: 16px; }
+ [lwt-newtab-brighttext] .ds-list-borders.ds-list-full-width .ds-list-item:not(.placeholder):not(:nth-last-child(-n+1)), [lwt-newtab-brighttext]
+ .ds-column-1 .ds-list-borders .ds-list-item:not(.placeholder):not(:nth-last-child(-n+1)), [lwt-newtab-brighttext]
+ .ds-column-2 .ds-list-borders .ds-list-item:not(.placeholder):not(:nth-last-child(-n+1)), [lwt-newtab-brighttext]
+ .ds-column-3 .ds-list-borders .ds-list-item:not(.placeholder):not(:nth-last-child(-n+1)), [lwt-newtab-brighttext]
+ .ds-column-4 .ds-list-borders .ds-list-item:not(.placeholder):not(:nth-last-child(-n+1)) {
+ border-bottom: 1px solid #4A4A4F; }
+ .ds-column-5 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+2)),
+ .ds-column-6 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+2)),
+ .ds-column-7 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+2)),
+ .ds-column-8 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+2)) {
+ border-bottom: 1px solid #D7D7DB;
+ margin-bottom: -1px;
+ padding-bottom: 16px; }
+ [lwt-newtab-brighttext] .ds-column-5 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+2)), [lwt-newtab-brighttext]
+ .ds-column-6 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+2)), [lwt-newtab-brighttext]
+ .ds-column-7 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+2)), [lwt-newtab-brighttext]
+ .ds-column-8 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+2)) {
+ border-bottom: 1px solid #4A4A4F; }
+ .ds-column-9 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+3)),
+ .ds-column-10 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+3)),
+ .ds-column-11 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+3)),
+ .ds-column-12 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+3)) {
+ border-bottom: 1px solid #D7D7DB;
+ margin-bottom: -1px;
+ padding-bottom: 16px; }
+ [lwt-newtab-brighttext] .ds-column-9 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+3)), [lwt-newtab-brighttext]
+ .ds-column-10 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+3)), [lwt-newtab-brighttext]
+ .ds-column-11 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+3)), [lwt-newtab-brighttext]
+ .ds-column-12 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+3)) {
+ border-bottom: 1px solid #4A4A4F; }
+
+.ds-list-full-width .ds-list-item {
+ font-size: 17px;
+ line-height: 24px;
+ position: relative; }
+
+.ds-list-full-width .ds-list-item-title {
+ font-size: 17px;
+ -webkit-line-clamp: 3;
+ line-height: 24px; }
+
+.ds-list-full-width .ds-list-image {
+ min-width: 160px;
+ width: 160px; }
+
+.ds-list-item {
+ display: block;
+ text-align: start; }
+ .ds-list-item.placeholder {
+ background: transparent;
+ min-height: 80px;
+ box-shadow: inset 0 0 0 1px var(--newtab-inner-box-shadow-color);
+ border-radius: 4px; }
+ .ds-list-item.placeholder .ds-list-item-link {
+ cursor: default; }
+ .ds-list-item.placeholder .ds-list-image {
+ opacity: 0; }
+ .ds-list-item .ds-list-item-link {
+ mix-blend-mode: normal;
+ display: flex;
+ justify-content: space-between;
+ height: 100%; }
+ .ds-list-item .ds-list-item-excerpt {
+ font-size: 14px;
+ -webkit-line-clamp: 2;
+ line-height: 20px;
+ color: #737373;
+ margin: 4px 0 8px; }
+ [lwt-newtab-brighttext] .ds-list-item .ds-list-item-excerpt {
+ color: rgba(249, 249, 250, 0.8); }
+ .ds-list-item p {
+ font-size: 14px;
+ line-height: 20px;
+ margin: 0; }
+ .ds-list-item .ds-list-item-info {
+ font-size: 14px;
+ -webkit-line-clamp: 1;
+ line-height: 20px;
+ color: #737373;
+ font-size: 13px; }
+ [lwt-newtab-brighttext] .ds-list-item .ds-list-item-info {
+ color: #B1B1B3; }
+ .ds-list-item .ds-list-item-title {
+ font-weight: 600;
+ margin-bottom: 4px; }
+ .ds-list-item .ds-list-item-body {
+ flex: 1; }
+ .ds-list-item .ds-list-item-text {
+ display: flex;
+ flex-direction: column;
+ justify-content: space-between; }
+ .ds-list-item .ds-list-image {
+ height: 80px;
+ margin-inline-start: 14px;
+ min-height: 80px; }
+ .ds-list-item .ds-list-image img {
+ border-radius: 4px;
+ box-shadow: inset 0 0 0 0.5px rgba(0, 0, 0, 0.15); }
+ .ds-list-item:hover .ds-list-item-title {
+ color: #45A1FF; }
+ .ds-list-item:active .ds-list-item-title {
+ color: #003EAA; }
+
+.outer-wrapper.newtab-experience .ds-navigation {
+ color: var(--newtab-background-primary-text-color); }
+
+.ds-navigation {
+ color: #737373;
+ padding: 4px 0;
+ font-weight: 600;
+ line-height: 22px;
+ font-size: 11.5px; }
+ [lwt-newtab-brighttext] .ds-navigation {
+ color: #D7D7DB; }
+ @media (min-width: 1122px) {
+ .ds-navigation {
+ line-height: 32px;
+ font-size: 14px; } }
+ .ds-navigation.ds-navigation-centered {
+ text-align: center; }
+ .ds-navigation.ds-navigation-right-aligned {
+ text-align: end; }
+ .ds-navigation ul {
+ display: inline;
+ margin: 0;
+ padding: 0; }
+ .ds-navigation ul li {
+ display: inline-block; }
+ .ds-navigation ul li::after {
+ content: '·';
+ padding: 6px; }
+ .ds-navigation ul li:last-child::after {
+ content: none; }
+ .ds-navigation ul li a:hover, .ds-navigation ul li a:active {
+ text-decoration: underline; }
+ .ds-navigation ul li a:active {
+ color: #003EAA; }
+ .ds-navigation .ds-navigation-header {
+ padding-inline-end: 6px; }
+
+.ds-section-title {
+ text-align: center;
+ margin-top: 24px; }
+ .ds-section-title .title {
+ line-height: 48px;
+ font-size: 36px;
+ font-weight: 300;
+ color: #0C0C0D; }
+ [lwt-newtab-brighttext] .ds-section-title .title {
+ color: #FFF; }
+ .ds-section-title .subtitle {
+ line-height: 24px;
+ font-size: 14px;
+ color: #737373;
+ margin-top: 4px; }
+ [lwt-newtab-brighttext] .ds-section-title .subtitle {
+ color: #D7D7DB; }
+
+.outer-wrapper:not(.newtab-experience) .ds-top-sites .top-sites .top-site-outer {
+ padding: 0 12px; }
+ .outer-wrapper:not(.newtab-experience) .ds-top-sites .top-sites .top-site-outer .top-site-inner > a:is(.active, :focus) .tile {
+ box-shadow: 0 0 0 5px rgba(10, 132, 255, 0.3);
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+ [lwt-newtab-brighttext] .outer-wrapper:not(.newtab-experience) .ds-top-sites .top-sites .top-site-outer .top-site-inner > a:is(.active, :focus) .tile {
+ box-shadow: 0 0 0 5px rgba(69, 161, 255, 0.4);
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+ .outer-wrapper:not(.newtab-experience) .ds-top-sites .top-sites .top-site-outer .top-site-inner > a:is(:hover) .tile {
+ box-shadow: 0 0 0 5px #D7D7DB;
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+ [lwt-newtab-brighttext] .outer-wrapper:not(.newtab-experience) .ds-top-sites .top-sites .top-site-outer .top-site-inner > a:is(:hover) .tile {
+ box-shadow: 0 0 0 5px #4A4A4F;
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+
+.outer-wrapper:not(.newtab-experience) .ds-top-sites .top-sites .top-sites-list {
+ margin: 0 -12px; }
+
+.outer-wrapper.newtab-experience .ds-top-sites .top-sites .top-site-outer .top-site-inner > a:is(.active, :focus) .tile {
+ border: 0;
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-focus-outline), 0 0 0 1px var(--newtab-focus-border); }
+
+.outer-wrapper.newtab-experience .ds-top-sites .top-sites .top-site-outer .top-site-inner > a:is(:hover) .top-site-inner {
+ box-shadow: 0 0 0 5px #D7D7DB;
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+ [lwt-newtab-brighttext] .outer-wrapper.newtab-experience .ds-top-sites .top-sites .top-site-outer .top-site-inner > a:is(:hover) .top-site-inner {
+ box-shadow: 0 0 0 5px #4A4A4F;
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+
+.outer-wrapper.newtab-experience .ds-top-sites .top-sites .top-sites-list {
+ margin: 0 -12px; }
+
+.ds-column-5 .ds-top-sites .top-site-outer,
+.ds-column-6 .ds-top-sites .top-site-outer,
+.ds-column-7 .ds-top-sites .top-site-outer,
+.ds-column-8 .ds-top-sites .top-site-outer {
+ padding: 0 10px; }
+
+.ds-column-5 .ds-top-sites .top-sites-list,
+.ds-column-6 .ds-top-sites .top-sites-list,
+.ds-column-7 .ds-top-sites .top-sites-list,
+.ds-column-8 .ds-top-sites .top-sites-list {
+ margin: 0 -10px; }
+
+.ds-column-5 .ds-top-sites .top-site-inner,
+.ds-column-6 .ds-top-sites .top-site-inner,
+.ds-column-7 .ds-top-sites .top-site-inner,
+.ds-column-8 .ds-top-sites .top-site-inner {
+ --leftPanelIconWidth: 84.67px; }
+ .ds-column-5 .ds-top-sites .top-site-inner .tile,
+ .ds-column-6 .ds-top-sites .top-site-inner .tile,
+ .ds-column-7 .ds-top-sites .top-site-inner .tile,
+ .ds-column-8 .ds-top-sites .top-site-inner .tile {
+ width: var(--leftPanelIconWidth);
+ height: var(--leftPanelIconWidth); }
+ .ds-column-5 .ds-top-sites .top-site-inner .title,
+ .ds-column-6 .ds-top-sites .top-site-inner .title,
+ .ds-column-7 .ds-top-sites .top-site-inner .title,
+ .ds-column-8 .ds-top-sites .top-site-inner .title {
+ width: var(--leftPanelIconWidth); }
+
+.ds-column-1 .ds-top-sites .top-site-outer,
+.ds-column-2 .ds-top-sites .top-site-outer,
+.ds-column-3 .ds-top-sites .top-site-outer,
+.ds-column-4 .ds-top-sites .top-site-outer {
+ padding: 0 8px; }
+
+.ds-column-1 .ds-top-sites .top-sites-list,
+.ds-column-2 .ds-top-sites .top-sites-list,
+.ds-column-3 .ds-top-sites .top-sites-list,
+.ds-column-4 .ds-top-sites .top-sites-list {
+ margin: 0 -8px; }
+
+.ds-column-1 .ds-top-sites .top-site-inner,
+.ds-column-2 .ds-top-sites .top-site-inner,
+.ds-column-3 .ds-top-sites .top-site-inner,
+.ds-column-4 .ds-top-sites .top-site-inner {
+ --rightPanelIconWidth: 82.67px; }
+ .ds-column-1 .ds-top-sites .top-site-inner .tile,
+ .ds-column-2 .ds-top-sites .top-site-inner .tile,
+ .ds-column-3 .ds-top-sites .top-site-inner .tile,
+ .ds-column-4 .ds-top-sites .top-site-inner .tile {
+ width: var(--rightPanelIconWidth);
+ height: var(--rightPanelIconWidth); }
+ .ds-column-1 .ds-top-sites .top-site-inner .title,
+ .ds-column-2 .ds-top-sites .top-site-inner .title,
+ .ds-column-3 .ds-top-sites .top-site-inner .title,
+ .ds-column-4 .ds-top-sites .top-site-inner .title {
+ width: var(--rightPanelIconWidth); }
+
+.ds-hero-item .context-menu-button,
+.ds-list-item .context-menu-button,
+.ds-card .context-menu-button,
+.ds-signup .context-menu-button {
+ background-clip: padding-box;
+ background-color: var(--newtab-contextmenu-button-color);
+ background-image: url("chrome://global/skin/icons/more.svg");
+ background-position: 55%;
+ border: 1px solid var(--newtab-border-primary-color);
+ border-radius: 100%;
+ box-shadow: 0 2px rgba(12, 12, 13, 0.1);
+ cursor: pointer;
+ fill: var(--newtab-icon-primary-color);
+ height: 27px;
+ inset-inline-end: -13.5px;
+ opacity: 0;
+ position: absolute;
+ top: -13.5px;
+ transform: scale(0.25);
+ transition-duration: 150ms;
+ transition-property: transform, opacity;
+ width: 27px; }
+ .ds-hero-item .context-menu-button:is(:active, :focus),
+ .ds-list-item .context-menu-button:is(:active, :focus),
+ .ds-card .context-menu-button:is(:active, :focus),
+ .ds-signup .context-menu-button:is(:active, :focus) {
+ opacity: 1;
+ transform: scale(1); }
+
+.ds-hero-item .context-menu,
+.ds-list-item .context-menu,
+.ds-card .context-menu,
+.ds-signup .context-menu {
+ opacity: 0; }
+
+.ds-hero-item.active .context-menu,
+.ds-list-item.active .context-menu,
+.ds-card.active .context-menu,
+.ds-signup.active .context-menu {
+ opacity: 1; }
+
+.ds-hero-item.last-item .context-menu,
+.ds-list-item.last-item .context-menu,
+.ds-card.last-item .context-menu,
+.ds-signup.last-item .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; }
+
+.ds-hero-item.last-item .context-menu,
+.ds-list-item.last-item .context-menu,
+.ds-card.last-item .context-menu,
+.ds-signup.last-item .context-menu {
+ opacity: 1; }
+
+.ds-hero-item:is(:hover, :focus, .active),
+.ds-list-item:is(:hover, :focus, .active),
+.ds-card:is(:hover, :focus, .active),
+.ds-signup:is(:hover, :focus, .active) {
+ outline: none; }
+ .ds-hero-item:is(:hover, :focus, .active) .context-menu-button,
+ .ds-list-item:is(:hover, :focus, .active) .context-menu-button,
+ .ds-card:is(:hover, :focus, .active) .context-menu-button,
+ .ds-signup:is(:hover, :focus, .active) .context-menu-button {
+ opacity: 1;
+ transform: scale(1);
+ transition-delay: 333ms; }
+ .ds-hero-item:is(:hover, :focus, .active).ds-card-grid-border,
+ .ds-list-item:is(:hover, :focus, .active).ds-card-grid-border,
+ .ds-card:is(:hover, :focus, .active).ds-card-grid-border,
+ .ds-signup:is(:hover, :focus, .active).ds-card-grid-border {
+ box-shadow: 0 0 0 5px var(--newtab-card-active-outline-color);
+ transition: box-shadow 150ms; }
+
+.outer-wrapper:not(.newtab-experience) .ds-card .ds-card-link:hover {
+ box-shadow: 0 0 0 5px #D7D7DB;
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+ [lwt-newtab-brighttext] .outer-wrapper:not(.newtab-experience) .ds-card .ds-card-link:hover {
+ box-shadow: 0 0 0 5px #4A4A4F;
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+
+.outer-wrapper:not(.newtab-experience) .ds-card .ds-card-link:focus {
+ box-shadow: 0 0 0 5px rgba(10, 132, 255, 0.3);
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+ [lwt-newtab-brighttext] .outer-wrapper:not(.newtab-experience) .ds-card .ds-card-link:focus {
+ box-shadow: 0 0 0 5px rgba(69, 161, 255, 0.4);
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+
+.outer-wrapper:not(.newtab-experience) .ds-card .ds-card-link:active {
+ box-shadow: 0 0 0 5px #D7D7DB;
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+ [lwt-newtab-brighttext] .outer-wrapper:not(.newtab-experience) .ds-card .ds-card-link:active {
+ box-shadow: 0 0 0 5px #4A4A4F;
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+
+.ds-card {
+ display: flex;
+ flex-direction: column;
+ position: relative; }
+ .ds-card .playhead {
+ background: #0060DF url("chrome://activity-stream/content/data/content/assets/glyph-playhead.svg") no-repeat 12px center;
+ border-radius: 20px;
+ bottom: -16px;
+ color: rgba(255, 255, 255, 0);
+ display: flex;
+ flex-direction: column;
+ height: 40px;
+ justify-content: center;
+ left: 16px;
+ min-width: 40px;
+ padding: 0 0 0 40px;
+ position: absolute;
+ transition: padding 100ms ease-in-out 0ms, color 100ms linear 100ms; }
+ .ds-card .playhead:hover {
+ color: white;
+ padding: 0 20px 0 40px; }
+ .ds-card .playhead span {
+ display: none; }
+ .ds-card .playhead:hover span {
+ display: inline;
+ font-style: normal;
+ font-weight: 600;
+ font-size: 13px; }
+ .ds-card.placeholder {
+ background: transparent;
+ box-shadow: inset 0 0 0 1px var(--newtab-inner-box-shadow-color);
+ border-radius: 4px;
+ min-height: 300px; }
+ .ds-card .img-wrapper {
+ width: 100%;
+ position: relative; }
+ .ds-card .img {
+ height: 0;
+ padding-top: 50%; }
+ .ds-card .img img {
+ border-radius: 4px;
+ box-shadow: inset 0 0 0 0.5px rgba(0, 0, 0, 0.15); }
+ .ds-card .ds-card-link {
+ height: 100%;
+ display: flex;
+ flex-direction: column; }
+ .ds-card .ds-card-link:hover header {
+ color: #0060DF; }
+ [lwt-newtab-brighttext] .ds-card .ds-card-link:hover header {
+ color: #45A1FF; }
+ .ds-card .ds-card-link:focus header {
+ color: #0060DF; }
+ [lwt-newtab-brighttext] .ds-card .ds-card-link:focus header {
+ color: #45A1FF; }
+ .ds-card .ds-card-link:active header {
+ color: #003EAA; }
+ [lwt-newtab-brighttext] .ds-card .ds-card-link:active header {
+ color: #0A84FF; }
+ .ds-card.video-card .meta {
+ margin-top: 4px; }
+ .ds-card .meta {
+ display: flex;
+ flex-direction: column;
+ padding: 12px 16px;
+ flex-grow: 1; }
+ .ds-card .meta .info-wrap {
+ flex-grow: 1; }
+ .ds-card .meta .title {
+ font-size: 17px;
+ -webkit-line-clamp: 3;
+ line-height: 24px;
+ font-weight: 600; }
+ .ds-card .meta .excerpt {
+ font-size: 14px;
+ -webkit-line-clamp: 3;
+ line-height: 20px; }
+ .ds-card .meta .source {
+ -webkit-line-clamp: 1;
+ margin-bottom: 2px;
+ font-size: 13px;
+ color: #737373; }
+ [lwt-newtab-brighttext] .ds-card .meta .source {
+ color: #B1B1B3; }
+ .ds-card .meta .cta-button {
+ width: 100%;
+ margin: 12px 0 4px;
+ box-shadow: none;
+ border-radius: 4px;
+ height: 32px;
+ font-size: 14px;
+ font-weight: 600;
+ padding: 5px 8px 7px;
+ border: 0;
+ color: #0C0C0D;
+ background: rgba(12, 12, 13, 0.1); }
+ [lwt-newtab-brighttext] .ds-card .meta .cta-button {
+ color: #F9F9FA;
+ background: rgba(12, 12, 13, 0.7); }
+ .ds-card .meta .cta-button:focus {
+ background: rgba(12, 12, 13, 0.1);
+ box-shadow: 0 0 0 2px #FFF, 0 0 0 5px rgba(10, 132, 255, 0.5); }
+ [lwt-newtab-brighttext] .ds-card .meta .cta-button:focus {
+ background: rgba(12, 12, 13, 0.7);
+ box-shadow: 0 0 0 2px #2A2A2E, 0 0 0 5px rgba(10, 132, 255, 0.5); }
+ .ds-card .meta .cta-button:hover {
+ background: rgba(12, 12, 13, 0.2); }
+ [lwt-newtab-brighttext] .ds-card .meta .cta-button:hover {
+ background: rgba(12, 12, 13, 0.5); }
+ .ds-card .meta .cta-button:active {
+ background: rgba(12, 12, 13, 0.3); }
+ [lwt-newtab-brighttext] .ds-card .meta .cta-button:active {
+ background: rgba(12, 12, 13, 0.7); }
+ .ds-card .meta .cta-link {
+ font-size: 15px;
+ font-weight: 600;
+ line-height: 24px;
+ height: 24px;
+ width: auto;
+ background-size: auto;
+ background-position: right 1.5px;
+ padding-right: 9px;
+ color: #0060DF;
+ fill: #0060DF; }
+ [lwt-newtab-brighttext] .ds-card .meta .cta-link {
+ color: #45A1FF;
+ fill: #45A1FF; }
+ .ds-card .meta .cta-link:focus {
+ box-shadow: 0 0 0 1px #FFF, 0 0 0 4px rgba(10, 132, 255, 0.5);
+ border-radius: 4px;
+ outline: 0; }
+ [lwt-newtab-brighttext] .ds-card .meta .cta-link:focus {
+ box-shadow: 0 0 0 1px #2A2A2E, 0 0 0 4px rgba(10, 132, 255, 0.5); }
+ .ds-card .meta .cta-link:active {
+ color: #003EAA;
+ fill: #003EAA;
+ box-shadow: none; }
+ [lwt-newtab-brighttext] .ds-card .meta .cta-link:active {
+ color: #0A84FF;
+ fill: #0A84FF;
+ box-shadow: none; }
+ .ds-card .meta .cta-link:hover {
+ text-decoration: underline; }
+ .ds-card header {
+ line-height: 24px;
+ font-size: 17px;
+ color: #0C0C0D; }
+ [lwt-newtab-brighttext] .ds-card header {
+ color: #F9F9FA; }
+ .ds-card p {
+ font-size: 14px;
+ line-height: 20px;
+ color: #0C0C0D;
+ margin: 0; }
+ [lwt-newtab-brighttext] .ds-card p {
+ color: #F9F9FA; }
+
+.outer-wrapper.newtab-experience .ds-card .context-menu-button:is(:active, :focus) {
+ outline: 0;
+ fill: var(--newtab-primary-action-background);
+ border: 1px solid var(--newtab-primary-action-background); }
+
+.outer-wrapper.newtab-experience .ds-card .ds-card-link:focus {
+ border: 0;
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-focus-outline), 0 0 0 1px var(--newtab-focus-border);
+ transition: none; }
+ .outer-wrapper.newtab-experience .ds-card .ds-card-link:focus header {
+ color: #0060DF; }
+ [lwt-newtab-brighttext] .outer-wrapper.newtab-experience .ds-card .ds-card-link:focus header {
+ color: #45A1FF; }
+
+.story-footer {
+ color: var(--newtab-text-secondary-color);
+ inset-inline-start: 0;
+ margin-top: 12px;
+ position: relative; }
+ .story-footer .story-sponsored-label,
+ .story-footer .story-view-count,
+ .story-footer .status-message {
+ -webkit-line-clamp: 1;
+ font-size: 13px;
+ line-height: 24px;
+ color: #737373; }
+ [lwt-newtab-brighttext] .story-footer .story-sponsored-label, [lwt-newtab-brighttext]
+ .story-footer .story-view-count, [lwt-newtab-brighttext]
+ .story-footer .status-message {
+ color: #B1B1B3; }
+ .story-footer .status-message {
+ display: flex;
+ align-items: center;
+ height: 24px; }
+ .story-footer .status-message .story-badge-icon {
+ fill: #737373;
+ height: 16px;
+ margin-inline-end: 6px; }
+ [lwt-newtab-brighttext] .story-footer .status-message .story-badge-icon {
+ fill: #B1B1B3; }
+ .story-footer .status-message .story-badge-icon.icon-bookmark-removed {
+ background-image: url("chrome://activity-stream/content/data/content/assets/icon-removed-bookmark.svg"); }
+ .story-footer .status-message .story-context-label {
+ color: #737373;
+ flex-grow: 1;
+ font-size: 13px;
+ line-height: 24px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap; }
+ [lwt-newtab-brighttext] .story-footer .status-message .story-context-label {
+ color: #B1B1B3; }
+
+.story-animate-enter {
+ opacity: 0; }
+
+.story-animate-enter-active {
+ opacity: 1;
+ transition: opacity 150ms ease-in 300ms; }
+ .story-animate-enter-active .story-badge-icon,
+ .story-animate-enter-active .story-context-label {
+ animation: color 3s ease-out 0.3s; }
+ [lwt-newtab-brighttext] .story-animate-enter-active .story-badge-icon, [lwt-newtab-brighttext]
+ .story-animate-enter-active .story-context-label {
+ animation: dark-color 3s ease-out 0.3s; }
+
+@keyframes color {
+ 0% {
+ color: #058B00;
+ fill: #058B00; }
+ 100% {
+ color: #737373;
+ fill: #737373; } }
+
+@keyframes dark-color {
+ 0% {
+ color: #7C6;
+ fill: #7C6; }
+ 100% {
+ color: #B1B1B3;
+ fill: #B1B1B3; } }
+
+.story-animate-exit {
+ position: absolute;
+ top: 0;
+ opacity: 1; }
+
+.story-animate-exit-active {
+ opacity: 0;
+ transition: opacity 250ms ease-in; }
+
+.ds-image {
+ display: block;
+ position: relative;
+ opacity: 0; }
+ .ds-image.use-transition {
+ transition: opacity 0.8s; }
+ .ds-image.loaded {
+ opacity: 1; }
+ .ds-image img,
+ .ds-image .broken-image {
+ background-color: var(--newtab-card-placeholder-color);
+ position: absolute;
+ top: 0;
+ width: 100%;
+ height: 100%;
+ object-fit: cover; }
+
+.ds-dismiss {
+ position: relative;
+ border-radius: 8px;
+ transition-duration: 250ms;
+ transition-property: background; }
+ .ds-dismiss:hover .ds-dismiss-button {
+ opacity: 1; }
+ .ds-dismiss .ds-dismiss-button {
+ border: 0;
+ cursor: pointer;
+ height: 32px;
+ width: 32px;
+ padding: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ position: absolute;
+ inset-inline-end: 0;
+ top: 0;
+ border-radius: 50%;
+ background-color: transparent; }
+ .ds-dismiss .ds-dismiss-button .icon {
+ fill: #737373; }
+ [lwt-newtab-brighttext] .ds-dismiss .ds-dismiss-button .icon {
+ fill: #EDEDF0; }
+ .ds-dismiss .ds-dismiss-button:hover {
+ background: rgba(12, 12, 13, 0.2); }
+ [lwt-newtab-brighttext] .ds-dismiss .ds-dismiss-button:hover {
+ background: rgba(12, 12, 13, 0.5); }
+ [lwt-newtab-brighttext] .ds-dismiss .ds-dismiss-button:hover .icon {
+ fill: #F9F9FA; }
+ .ds-dismiss .ds-dismiss-button:hover .icon {
+ fill: #2A2A2E; }
+ .ds-dismiss .ds-dismiss-button:active {
+ background: rgba(12, 12, 13, 0.3); }
+ [lwt-newtab-brighttext] .ds-dismiss .ds-dismiss-button:active {
+ background: rgba(12, 12, 13, 0.7); }
+ .ds-dismiss .ds-dismiss-button:focus {
+ box-shadow: 0 0 0 2px #FFF, 0 0 0 5px rgba(10, 132, 255, 0.5); }
+ [lwt-newtab-brighttext] .ds-dismiss .ds-dismiss-button:focus {
+ box-shadow: 0 0 0 2px #2A2A2E, 0 0 0 5px rgba(10, 132, 255, 0.5); }
+
+.ds-message {
+ margin: 8px 0 0; }
+ .ds-message .title {
+ display: flex;
+ align-items: center; }
+ .ds-message .title .glyph {
+ width: 16px;
+ height: 16px;
+ margin: 0 6px 0 0;
+ -moz-context-properties: fill;
+ fill: #737373;
+ background-position: center center;
+ background-size: 16px;
+ background-repeat: no-repeat; }
+ [lwt-newtab-brighttext] .ds-message .title .glyph {
+ fill: #D7D7DB; }
+ .ds-message .title .title-text {
+ line-height: 20px;
+ font-size: 13px;
+ color: #737373;
+ font-weight: 600;
+ padding-right: 12px; }
+ [lwt-newtab-brighttext] .ds-message .title .title-text {
+ color: #D7D7DB; }
+ .ds-message .title .link {
+ line-height: 20px;
+ font-size: 13px; }
+ .ds-message .title .link:hover, .ds-message .title .link:focus {
+ text-decoration: underline; }
+
+.impression-observer {
+ position: absolute;
+ top: 0;
+ width: 100%;
+ height: 100%;
+ pointer-events: none; }
+
+.section-empty-state {
+ border: 1px solid var(--newtab-border-secondary-color);
+ border-radius: 4px;
+ display: flex;
+ height: 160px;
+ width: 100%; }
+ .section-empty-state .empty-state-message {
+ color: var(--newtab-text-secondary-color);
+ font-size: 14px;
+ line-height: 20px;
+ text-align: center;
+ margin: auto;
+ max-width: 936px; }
+ .section-empty-state .try-again-button {
+ margin-top: 12px;
+ padding: 6px 32px;
+ border-radius: 2px;
+ border: 0;
+ background: var(--newtab-feed-button-background);
+ color: var(--newtab-feed-button-text);
+ cursor: pointer;
+ position: relative;
+ transition: background 0.2s ease, color 0.2s ease; }
+ .section-empty-state .try-again-button:not(.waiting):focus {
+ box-shadow: 0 0 0 5px rgba(10, 132, 255, 0.3);
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+ [lwt-newtab-brighttext] .section-empty-state .try-again-button:not(.waiting):focus {
+ box-shadow: 0 0 0 5px rgba(69, 161, 255, 0.4);
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+ .section-empty-state .try-again-button:not(.waiting):hover {
+ box-shadow: 0 0 0 5px #D7D7DB;
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+ [lwt-newtab-brighttext] .section-empty-state .try-again-button:not(.waiting):hover {
+ box-shadow: 0 0 0 5px #4A4A4F;
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+ .section-empty-state .try-again-button::after {
+ content: '';
+ height: 20px;
+ width: 20px;
+ animation: spinner 1s linear infinite;
+ opacity: 0;
+ position: absolute;
+ top: 50%;
+ left: 50%;
+ margin: -10px 0 0 -10px;
+ mask-image: url("chrome://activity-stream/content/data/content/assets/spinner.svg");
+ mask-size: 20px;
+ background: var(--newtab-feed-button-spinner); }
+ .section-empty-state .try-again-button.waiting {
+ cursor: initial;
+ background: var(--newtab-feed-button-background-faded);
+ color: var(--newtab-feed-button-text-faded);
+ transition: background 0.2s ease; }
+ .section-empty-state .try-again-button.waiting::after {
+ transition: opacity 0.2s ease;
+ opacity: 1; }
+ .section-empty-state h2 {
+ font-size: 15px;
+ font-weight: 600;
+ margin: 0; }
+ .section-empty-state p {
+ margin: 0; }
+
+@keyframes spinner {
+ to {
+ transform: rotate(360deg); } }
+
+.ds-dismiss-ds-text-promo {
+ max-width: 744px;
+ margin: auto;
+ overflow: hidden; }
+ .ds-dismiss-ds-text-promo.hovering {
+ background: rgba(12, 12, 13, 0.1); }
+ [lwt-newtab-brighttext] .ds-dismiss-ds-text-promo.hovering {
+ background: rgba(12, 12, 13, 0.3); }
+ .ds-dismiss-ds-text-promo .ds-dismiss-button {
+ margin-inline: 0 18px;
+ margin-block: 18px 0; }
+
+.ds-text-promo {
+ max-width: 640px;
+ margin: 0;
+ padding: 18px; }
+ @media (min-width: 610px) {
+ .ds-text-promo {
+ display: flex;
+ margin: 18px 24px;
+ padding: 0 32px 0 0; } }
+ .ds-text-promo .ds-image {
+ width: 40px;
+ height: 40px;
+ flex-shrink: 0;
+ margin: 0 0 18px; }
+ @media (min-width: 610px) {
+ .ds-text-promo .ds-image {
+ margin: 4px 12px 0 0; } }
+ .ds-text-promo .ds-image img {
+ border-radius: 4px; }
+ .ds-text-promo .text {
+ line-height: 24px; }
+ .ds-text-promo h3 {
+ margin: 0;
+ font-weight: 600;
+ font-size: 15px; }
+ [lwt-newtab-brighttext] .ds-text-promo h3 {
+ color: #F9F9FA; }
+ .ds-text-promo .subtitle {
+ font-size: 13px;
+ margin: 0;
+ color: #737373; }
+ [lwt-newtab-brighttext] .ds-text-promo .subtitle {
+ color: #B1B1B3; }
+
+.ds-chevron-link {
+ color: #0060DF;
+ display: inline-block;
+ outline: 0; }
+ .ds-chevron-link:hover {
+ text-decoration: underline; }
+ .ds-chevron-link:active {
+ color: #003EAA; }
+ [lwt-newtab-brighttext] .ds-chevron-link:active {
+ color: #0A84FF; }
+ .ds-chevron-link:active::after {
+ background-color: #003EAA; }
+ [lwt-newtab-brighttext] .ds-chevron-link:active::after {
+ background-color: #0A84FF; }
+ .ds-chevron-link:focus {
+ box-shadow: 0 0 0 2px #FFF, 0 0 0 5px rgba(10, 132, 255, 0.5);
+ border-radius: 2px; }
+ [lwt-newtab-brighttext] .ds-chevron-link:focus {
+ box-shadow: 0 0 0 2px #2A2A2E, 0 0 0 5px rgba(10, 132, 255, 0.5); }
+ .ds-chevron-link::after {
+ content: ' ';
+ mask: url("chrome://activity-stream/content/data/content/assets/glyph-caret-right.svg") 0 -8px no-repeat;
+ background-color: #0060DF;
+ margin: 0 0 0 4px;
+ width: 5px;
+ height: 8px;
+ text-decoration: none;
+ display: inline-block; }
+ [lwt-newtab-brighttext] .ds-chevron-link::after {
+ background-color: #45A1FF; }
+
+.ds-signup {
+ max-width: 300px;
+ margin: 0 auto;
+ padding: 8px;
+ position: relative;
+ text-align: center;
+ font-size: 17px;
+ font-weight: 600; }
+ .ds-signup:hover {
+ background: var(--newtab-element-hover-color);
+ border-radius: 4px; }
+ .ds-signup .icon-mail {
+ height: 40px;
+ width: 40px;
+ margin-inline-end: 8px;
+ fill: #B1B1B3;
+ background-size: 30px;
+ flex-shrink: 0; }
+ .ds-signup .ds-signup-content {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ flex-direction: column; }
+ .ds-signup .ds-signup-content .ds-chevron-link {
+ margin-top: 4px;
+ box-shadow: none;
+ display: block;
+ white-space: nowrap; }
+ @media (min-width: 866px) {
+ .ds-signup {
+ min-width: 756px;
+ width: max-content;
+ text-align: start; }
+ .ds-signup .ds-signup-content {
+ flex-direction: row; }
+ .ds-signup .ds-signup-content .ds-chevron-link {
+ margin-top: 0;
+ display: inline; } }
+
+.ds-privacy-modal .modal-link {
+ display: flex;
+ align-items: center;
+ margin: 0 0 8px;
+ border: 0;
+ padding: 0;
+ color: #0060DF;
+ width: max-content; }
+ .ds-privacy-modal .modal-link:hover {
+ text-decoration: underline;
+ cursor: pointer; }
+ .ds-privacy-modal .modal-link::before {
+ -moz-context-properties: fill;
+ fill: #0060DF;
+ content: '';
+ display: inline-block;
+ width: 16px;
+ height: 16px;
+ margin: 0;
+ margin-inline-end: 8px;
+ background-position: center center;
+ background-repeat: no-repeat;
+ background-size: 16px; }
+ .ds-privacy-modal .modal-link.modal-link-privacy::before {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-info-16.svg"); }
+ .ds-privacy-modal .modal-link.modal-link-manage::before {
+ background-image: url("chrome://global/skin/icons/settings.svg"); }
+
+.ds-privacy-modal p {
+ line-height: 24px; }
+
+.ds-privacy-modal .privacy-notice {
+ max-width: 572px;
+ padding: 40px;
+ margin: auto; }
+
+.ASRouterButton {
+ font-weight: 600;
+ font-size: 14px;
+ white-space: nowrap;
+ border-radius: 2px;
+ border: 0;
+ font-family: inherit;
+ padding: 8px 15px;
+ margin-inline-start: 12px;
+ color: inherit;
+ cursor: pointer; }
+ .tall .ASRouterButton {
+ margin-inline-start: 20px; }
+ .ASRouterButton.test-only {
+ width: 0;
+ height: 0;
+ overflow: hidden;
+ display: block;
+ visibility: hidden; }
+ .ASRouterButton.primary {
+ border: 1px solid var(--newtab-button-primary-color);
+ background-color: var(--newtab-button-primary-color);
+ color: #F9F9FA; }
+ .ASRouterButton.primary:hover {
+ background-color: #003EAA; }
+ .ASRouterButton.primary:active {
+ background-color: #002275; }
+ .ASRouterButton.secondary {
+ background-color: rgba(12, 12, 13, 0.1); }
+ .ASRouterButton.secondary:hover {
+ background-color: rgba(12, 12, 13, 0.2); }
+ .ASRouterButton.secondary:active {
+ background-color: rgba(12, 12, 13, 0.3); }
+ .ASRouterButton.secondary:focus {
+ box-shadow: 0 0 0 1px #0A84FF inset, 0 0 0 1px #0A84FF, 0 0 0 4px rgba(10, 132, 255, 0.3); }
+ .ASRouterButton.slim {
+ background-color: rgba(12, 12, 13, 0.1);
+ margin-inline-start: 0;
+ font-size: 12px;
+ padding: 6px 12px; }
+ .ASRouterButton.slim:hover {
+ background-color: rgba(12, 12, 13, 0.2); }
+
+[lwt-newtab-brighttext] .secondary {
+ background-color: rgba(249, 249, 250, 0.1); }
+ [lwt-newtab-brighttext] .secondary:hover {
+ background-color: rgba(249, 249, 250, 0.2); }
+ [lwt-newtab-brighttext] .secondary:active {
+ background-color: rgba(249, 249, 250, 0.3); }
+
+[lwt-newtab-brighttext] .footer .secondary {
+ background-color: rgba(249, 249, 250, 0.3); }
+ [lwt-newtab-brighttext] .footer .secondary:hover {
+ background-color: rgba(249, 249, 250, 0.4); }
+ [lwt-newtab-brighttext] .footer .secondary:active {
+ background-color: rgba(249, 249, 250, 0.5); }
+
+.SnippetBaseContainer {
+ position: fixed;
+ z-index: 2;
+ bottom: 0;
+ left: 0;
+ right: 0;
+ background-color: var(--newtab-snippets-background-color);
+ color: var(--newtab-text-primary-color);
+ font-size: 14px;
+ line-height: 20px;
+ border-top: 1px solid var(--newtab-snippets-hairline-color);
+ box-shadow: 0 1px 4px 0 rgba(12, 12, 13, 0.2);
+ display: flex;
+ align-items: center; }
+ .SnippetBaseContainer a {
+ cursor: pointer;
+ color: var(--newtab-link-primary-color); }
+ .SnippetBaseContainer a:hover {
+ text-decoration: underline; }
+ [lwt-newtab-brighttext] .SnippetBaseContainer a {
+ font-weight: bold; }
+ .SnippetBaseContainer input[type='checkbox'] {
+ margin-inline-start: 0; }
+ .SnippetBaseContainer .innerWrapper {
+ margin: 0 auto;
+ display: flex;
+ align-items: center;
+ padding: 12px 25px;
+ padding-inline-end: 36px;
+ max-width: 836px; }
+ @media (min-width: 866px) {
+ .SnippetBaseContainer .innerWrapper {
+ padding-inline-end: 25px; } }
+ @media (min-width: 1122px) {
+ .SnippetBaseContainer .innerWrapper {
+ max-width: 1092px; } }
+ .SnippetBaseContainer .blockButton {
+ display: none;
+ background: none;
+ border: 0;
+ position: absolute;
+ top: 50%;
+ inset-inline-end: 12px;
+ height: 16px;
+ width: 16px;
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-dismiss-16.svg");
+ -moz-context-properties: fill;
+ color: inherit;
+ fill: currentColor;
+ opacity: 0.5;
+ margin-top: -8px;
+ padding: 0;
+ cursor: pointer; }
+ .SnippetBaseContainer:hover .blockButton {
+ display: block; }
+ .SnippetBaseContainer .icon {
+ height: 42px;
+ width: 42px;
+ margin-inline-end: 12px;
+ flex-shrink: 0; }
+
+.snippets-preview-banner {
+ font-size: 15px;
+ line-height: 42px;
+ color: rgba(74, 74, 79, 0.7);
+ background: rgba(215, 215, 219, 0.6);
+ text-align: center;
+ position: absolute;
+ top: 0;
+ width: 100%; }
+ .snippets-preview-banner span {
+ vertical-align: middle; }
+
+body:not([lwt-newtab-brighttext]) .icon-dark-theme,
+body:not([lwt-newtab-brighttext]) .icon.icon-dark-theme,
+body:not([lwt-newtab-brighttext]) .scene2Icon .icon-dark-theme {
+ display: none; }
+
+body[lwt-newtab-brighttext] .icon-light-theme,
+body[lwt-newtab-brighttext] .icon.icon-light-theme,
+body[lwt-newtab-brighttext] .scene2Icon .icon-light-theme {
+ display: none; }
+
+.activity-stream.modal-open {
+ overflow: hidden; }
+
+.modalOverlayOuter {
+ background: var(--newtab-overlay-color);
+ height: 100%;
+ position: fixed;
+ top: 0;
+ left: 0;
+ width: 100%;
+ display: none;
+ z-index: 1100;
+ overflow: auto; }
+ .modalOverlayOuter.active {
+ display: flex; }
+
+.modalOverlayInner {
+ min-width: min-content;
+ width: 100%;
+ max-width: 960px;
+ position: relative;
+ margin: auto;
+ background: var(--newtab-modal-color);
+ box-shadow: 0 1px 15px 0 rgba(0, 0, 0, 0.3);
+ border-radius: 4px;
+ display: none;
+ z-index: 1100; }
+ @media (max-width: 960px) {
+ .modalOverlayInner {
+ height: 100%;
+ top: 0;
+ left: 0;
+ box-shadow: none;
+ border-radius: 0; } }
+ .modalOverlayInner.active {
+ display: block; }
+ .modalOverlayInner h2 {
+ color: #4A4A4F;
+ text-align: center;
+ font-weight: 200;
+ margin-top: 30px;
+ font-size: 28px;
+ line-height: 37px;
+ letter-spacing: -0.13px; }
+ @media (max-width: 960px) {
+ .modalOverlayInner h2 {
+ margin-top: 100px; } }
+ @media (max-width: 850px) {
+ .modalOverlayInner h2 {
+ margin-top: 30px; } }
+ .modalOverlayInner .footer {
+ border-top: 1px solid #D7D7DB;
+ border-radius: 4px;
+ height: 70px;
+ width: 100%;
+ position: absolute;
+ bottom: 0;
+ text-align: center;
+ background-color: #FFF; }
+ @media (max-width: 850px) and (max-height: 730px) {
+ .modalOverlayInner .footer {
+ position: sticky; } }
+ @media (max-width: 650px) and (max-height: 600px) {
+ .modalOverlayInner .footer {
+ position: sticky; } }
+ .modalOverlayInner .footer .modalButton {
+ margin-top: 20px;
+ min-width: 150px;
+ height: 30px;
+ padding: 4px 30px 6px;
+ font-size: 15px; }
+ .modalOverlayInner .footer .modalButton:focus, .modalOverlayInner .footer .modalButton.active, .modalOverlayInner .footer .modalButton:hover {
+ box-shadow: 0 0 0 5px #D7D7DB;
+ transition: box-shadow 150ms; }
+
+.below-search-snippet {
+ margin: 0 auto 16px; }
+ .below-search-snippet.withButton {
+ margin: auto;
+ min-height: 60px;
+ background-color: transparent; }
+ .below-search-snippet.withButton .snippet-hover-wrapper {
+ min-height: 60px;
+ border-radius: 4px; }
+ .below-search-snippet.withButton .snippet-hover-wrapper:hover {
+ background-color: var(--newtab-element-hover-color); }
+ .below-search-snippet.withButton .snippet-hover-wrapper:hover .blockButton {
+ display: block;
+ opacity: 1; }
+
+.SimpleBelowSearchSnippet {
+ background-color: transparent;
+ border: 0;
+ box-shadow: none;
+ position: relative;
+ margin: auto;
+ z-index: auto; }
+ @media (min-width: 866px) {
+ .SimpleBelowSearchSnippet {
+ width: 736px; } }
+ .SimpleBelowSearchSnippet.active {
+ background-color: var(--newtab-element-hover-color);
+ border-radius: 4px; }
+ .SimpleBelowSearchSnippet .innerWrapper {
+ align-items: center;
+ background-color: transparent;
+ border-radius: 4px;
+ box-shadow: var(--newtab-card-shadow);
+ flex-direction: column;
+ padding: 16px;
+ text-align: center;
+ width: 100%; }
+ @media (min-width: 610px) {
+ .SimpleBelowSearchSnippet .innerWrapper {
+ align-items: flex-start;
+ background-color: transparent;
+ border-radius: 4px;
+ box-shadow: none;
+ flex-direction: row;
+ padding: 0;
+ text-align: inherit;
+ width: 696px; } }
+ @media (max-width: 865px) {
+ .SimpleBelowSearchSnippet .innerWrapper {
+ margin-inline-start: 0; } }
+ @media (max-width: 609px) {
+ .SimpleBelowSearchSnippet .innerWrapper {
+ margin: auto; } }
+ .SimpleBelowSearchSnippet .blockButton {
+ display: block;
+ inset-inline-end: 10px;
+ opacity: 1;
+ top: 50%; }
+ .SimpleBelowSearchSnippet .blockButton:focus {
+ box-shadow: 0 0 0 1px #0A84FF inset, 0 0 0 1px #0A84FF, 0 0 0 4px rgba(10, 132, 255, 0.3);
+ border-radius: 2px; }
+ .SimpleBelowSearchSnippet .title {
+ font-size: inherit;
+ margin: 0; }
+ .SimpleBelowSearchSnippet .title-inline {
+ display: inline; }
+ .SimpleBelowSearchSnippet .textContainer {
+ margin: 10px;
+ margin-inline-start: 0;
+ padding-inline-end: 20px; }
+ .SimpleBelowSearchSnippet .icon {
+ margin-top: 8px;
+ margin-inline-start: 12px;
+ height: 32px;
+ width: 32px; }
+ @media (min-width: 610px) {
+ .SimpleBelowSearchSnippet .icon {
+ height: 24px;
+ width: 24px; } }
+ @media (max-width: 610px) {
+ .SimpleBelowSearchSnippet .icon {
+ margin: auto; } }
+ .SimpleBelowSearchSnippet.withButton {
+ line-height: 20px;
+ margin-bottom: 10px;
+ min-height: 60px;
+ background-color: transparent; }
+ @media (max-width: 1123px) {
+ .SimpleBelowSearchSnippet.withButton .innerWrapper {
+ margin: 0 40px; } }
+ .SimpleBelowSearchSnippet.withButton .blockButton {
+ display: block;
+ inset-inline-end: -10%;
+ opacity: 0;
+ margin: auto;
+ top: unset; }
+ .SimpleBelowSearchSnippet.withButton .blockButton:focus {
+ opacity: 1;
+ box-shadow: none; }
+ @media (max-width: 1123px) {
+ .SimpleBelowSearchSnippet.withButton .blockButton {
+ inset-inline-end: 2%; } }
+ .SimpleBelowSearchSnippet.withButton .icon {
+ width: 42px;
+ height: 42px;
+ flex-shrink: 0;
+ margin: auto 0;
+ margin-inline-end: 10px; }
+ @media (max-width: 610px) {
+ .SimpleBelowSearchSnippet.withButton .icon {
+ margin: auto; } }
+ .SimpleBelowSearchSnippet.withButton .buttonContainer {
+ margin: auto;
+ margin-inline-end: 0; }
+ @media (max-width: 610px) {
+ .SimpleBelowSearchSnippet.withButton .buttonContainer {
+ margin: auto; } }
+ @media (max-width: 610px) {
+ .SimpleBelowSearchSnippet button {
+ margin: auto; } }
+ .SimpleBelowSearchSnippet .body {
+ display: inline;
+ position: sticky;
+ transform: translateY(-50%);
+ margin: 8px 0 0; }
+ @media (min-width: 610px) {
+ .SimpleBelowSearchSnippet .body {
+ margin: 12px 0; } }
+ .SimpleBelowSearchSnippet .body a {
+ font-weight: 600; }
+
+.SimpleSnippet.tall {
+ padding: 27px 0; }
+
+.SimpleSnippet p em {
+ color: #0C0C0D;
+ font-style: normal;
+ background: #FFE900; }
+
+.SimpleSnippet.bold .donation-form-url,
+.SimpleSnippet.bold .donation-amount, .SimpleSnippet.takeover .donation-form-url,
+.SimpleSnippet.takeover .donation-amount {
+ padding-top: 8px;
+ padding-bottom: 8px; }
+
+.SimpleSnippet.bold {
+ height: 176px; }
+ .SimpleSnippet.bold .body {
+ font-size: 14px;
+ line-height: 20px;
+ margin-bottom: 20px; }
+ .SimpleSnippet.bold .icon {
+ width: 71px;
+ height: 71px; }
+
+.SimpleSnippet.takeover {
+ height: 344px; }
+ .SimpleSnippet.takeover .body {
+ font-size: 16px;
+ line-height: 24px;
+ margin-bottom: 35px; }
+ .SimpleSnippet.takeover .icon {
+ width: 79px;
+ height: 79px; }
+
+.SimpleSnippet .title {
+ font-size: inherit;
+ margin: 0; }
+
+.SimpleSnippet .title-inline {
+ display: inline; }
+
+.SimpleSnippet .titleIcon {
+ background-repeat: no-repeat;
+ background-size: 14px;
+ background-position: center;
+ height: 16px;
+ width: 16px;
+ margin-top: 2px;
+ margin-inline-end: 2px;
+ display: inline-block;
+ vertical-align: top; }
+
+.SimpleSnippet .body {
+ display: inline;
+ margin: 0; }
+
+.SimpleSnippet.tall .icon {
+ margin-inline-end: 20px; }
+
+.SimpleSnippet.takeover .icon, .SimpleSnippet.bold .icon {
+ margin-inline-end: 20px; }
+
+.SimpleSnippet .icon {
+ align-self: flex-start; }
+
+.SimpleSnippet.has-section-header .innerWrapper {
+ flex-wrap: wrap;
+ padding-top: 7px; }
+
+.SimpleSnippet .innerContentWrapper {
+ align-items: center;
+ display: flex; }
+
+.SimpleSnippet .section-header {
+ flex: 0 0 100%;
+ margin-bottom: 10px; }
+
+.SimpleSnippet .section-title {
+ color: var(--newtab-section-header-text-color);
+ display: inline-block;
+ font-size: 13px;
+ font-weight: bold;
+ margin: 0; }
+ .SimpleSnippet .section-title a {
+ color: var(--newtab-section-header-text-color);
+ font-weight: inherit;
+ text-decoration: none; }
+ .SimpleSnippet .section-title .icon {
+ height: 16px;
+ margin-inline-end: 6px;
+ margin-top: -2px;
+ width: 16px; }
+
+.SubmitFormSnippet {
+ flex-direction: column;
+ flex: 1 1 100%;
+ width: 100%; }
+ .SubmitFormSnippet .disclaimerText {
+ margin: 5px 0 0;
+ font-size: 12px;
+ color: var(--newtab-text-secondary-color); }
+ .SubmitFormSnippet p {
+ margin: 0; }
+ .SubmitFormSnippet.send_to_device_snippet {
+ text-align: center; }
+ .SubmitFormSnippet.send_to_device_snippet .message {
+ font-size: 16px;
+ margin-bottom: 20px; }
+ .SubmitFormSnippet.send_to_device_snippet .scene2Title {
+ font-size: 24px;
+ display: block; }
+ .SubmitFormSnippet .ASRouterButton.primary {
+ flex: 1 1 0; }
+ .SubmitFormSnippet .scene2Icon {
+ width: 100%;
+ margin-bottom: 20px; }
+ .SubmitFormSnippet .scene2Icon img {
+ width: 98px;
+ display: inline-block; }
+ .SubmitFormSnippet .scene2Title {
+ font-size: inherit;
+ margin: 0 0 10px;
+ font-weight: bold;
+ display: inline; }
+ .SubmitFormSnippet form {
+ display: flex;
+ flex-direction: column;
+ width: 100%; }
+ .SubmitFormSnippet .message {
+ font-size: 14px;
+ align-self: stretch;
+ flex: 0 0 100%;
+ margin-bottom: 10px; }
+ .SubmitFormSnippet .privacyNotice {
+ font-size: 12px;
+ color: var(--newtab-text-secondary-color);
+ margin-top: 10px;
+ display: flex;
+ flex: 0 0 100%; }
+ .SubmitFormSnippet .innerWrapper {
+ max-width: 736px;
+ flex-wrap: wrap;
+ justify-items: center;
+ padding-top: 40px;
+ padding-bottom: 40px; }
+ .SubmitFormSnippet .footer {
+ width: 100%;
+ margin: 0 auto;
+ text-align: right;
+ background-color: var(--newtab-background-color);
+ padding: 10px 0; }
+ .SubmitFormSnippet .footer .footer-content {
+ margin: 0 auto;
+ max-width: 768px;
+ width: 100%;
+ text-align: right; }
+ [dir='rtl'] .SubmitFormSnippet .footer .footer-content {
+ text-align: left; }
+ .SubmitFormSnippet input.mainInput {
+ border-radius: 2px;
+ background-color: var(--newtab-textbox-background-color);
+ border: 1px solid var(--newtab-textbox-border);
+ padding: 0 8px;
+ height: 100%;
+ font-size: 14px;
+ width: 50%; }
+ .SubmitFormSnippet input.mainInput.clean:invalid, .SubmitFormSnippet input.mainInput.clean:required {
+ box-shadow: none; }
+ .SubmitFormSnippet input.mainInput:focus {
+ border: 1px solid var(--newtab-textbox-focus-color);
+ box-shadow: var(--newtab-textbox-focus-boxshadow); }
+ .SubmitFormSnippet.scene2Alt {
+ text-align: start; }
+ .SubmitFormSnippet.scene2Alt .scene2Icon {
+ flex: 1;
+ margin-bottom: 0; }
+ .SubmitFormSnippet.scene2Alt .message {
+ flex: 5;
+ margin-bottom: 0; }
+ .SubmitFormSnippet.scene2Alt .message p {
+ margin-bottom: 10px; }
+ .SubmitFormSnippet.scene2Alt .section-header {
+ width: 100%; }
+ .SubmitFormSnippet.scene2Alt .section-header .icon {
+ width: 16px;
+ height: 16px; }
+ .SubmitFormSnippet.scene2Alt .section-title {
+ font-size: 13px; }
+ .SubmitFormSnippet.scene2Alt .section-title a {
+ color: var(--newtab-section-header-text-color);
+ font-weight: inherit;
+ text-decoration: none; }
+ .SubmitFormSnippet.scene2Alt .innerWrapper {
+ padding: 0 0 16px; }
+
+.submissionStatus {
+ text-align: center;
+ font-size: 14px;
+ padding: 20px 0; }
+ .submissionStatus .submitStatusTitle {
+ font-size: 20px; }
+
+.EOYSnippetForm {
+ margin: 10px 0 8px;
+ align-self: start;
+ font-size: 14px;
+ display: flex;
+ align-items: center; }
+ .EOYSnippetForm .donation-amount,
+ .EOYSnippetForm .donation-form-url {
+ white-space: nowrap;
+ font-size: 14px;
+ padding: 8px 20px;
+ border-radius: 2px; }
+ .EOYSnippetForm .donation-amount {
+ color: #0C0C0D;
+ margin-inline-end: 18px;
+ border: 1px solid #B1B1B3;
+ padding: 5px 14px;
+ background: #F9F9FA;
+ cursor: pointer; }
+ .EOYSnippetForm input[type='radio'] {
+ opacity: 0;
+ margin-inline-end: -18px; }
+ .EOYSnippetForm input[type='radio']:checked + .donation-amount {
+ background: #737373;
+ color: #FFF;
+ border: 1px solid #4A4A4F; }
+ .EOYSnippetForm input[type='radio']:checked:focus + .donation-amount,
+ .EOYSnippetForm input[type='radio']:not(:checked):focus + .donation-amount {
+ border: 1px dotted var(--newtab-link-primary-color); }
+ .EOYSnippetForm .monthly-checkbox-container {
+ display: flex;
+ width: 100%; }
+ .EOYSnippetForm .donation-form-url {
+ margin-inline-start: 18px;
+ align-self: flex-end;
+ display: flex; }
diff --git a/browser/components/newtab/css/activity-stream-mac.css b/browser/components/newtab/css/activity-stream-mac.css
new file mode 100644
index 0000000000..7ed8e04052
--- /dev/null
+++ b/browser/components/newtab/css/activity-stream-mac.css
@@ -0,0 +1,4548 @@
+@charset "UTF-8";
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+/* This is the mac variant */
+[lwt-newtab-brighttext] {
+ -moz-osx-font-smoothing: grayscale; }
+
+html {
+ box-sizing: border-box; }
+
+*,
+*::before,
+*::after {
+ box-sizing: inherit; }
+
+*::-moz-focus-inner {
+ border: 0; }
+
+body {
+ margin: 0; }
+
+button,
+input {
+ background-color: inherit;
+ color: inherit;
+ font-family: inherit;
+ font-size: inherit; }
+
+[hidden] {
+ display: none !important; }
+
+body {
+ --newtab-background-color: #F9F9FA;
+ --newtab-border-primary-color: #B1B1B3;
+ --newtab-border-secondary-color: #D7D7DB;
+ --newtab-element-active-color: rgba(215, 215, 219, 0.6);
+ --newtab-element-hover-color: #EDEDF0;
+ --newtab-icon-primary-color: rgba(12, 12, 13, 0.8);
+ --newtab-icon-secondary-color: rgba(12, 12, 13, 0.6);
+ --newtab-icon-tertiary-color: #D7D7DB;
+ --newtab-inner-box-shadow-color: rgba(0, 0, 0, 0.1);
+ --newtab-inner-box-shadow-color-nte: rgba(9, 32, 77, 0.12);
+ --newtab-tile-shadow-secondary: rgba(29, 17, 51, 0.2);
+ --newtab-link-primary-color: #0060DF;
+ --newtab-link-secondary-color: #008EA4;
+ --newtab-text-conditional-color: #4A4A4F;
+ --newtab-text-primary-color: #0C0C0D;
+ --newtab-text-secondary-color: #737373;
+ --newtab-textbox-background-color: #FFF;
+ --newtab-textbox-border: rgba(12, 12, 13, 0.2);
+ --newtab-textbox-focus-color: #0060DF;
+ --newtab-textbox-focus-boxshadow: 0 0 0 1px #0060DF, 0 0 0 4px rgba(0, 96, 223, 0.3);
+ --newtab-background-button-color: rgba(223, 223, 223, 0.5);
+ --newtab-background-button-text-color: #484848;
+ --newtab-background-button-hover-color: rgba(196, 196, 196, 0.5);
+ --newtab-background-button-active-color: rgba(151, 151, 151, 0.5);
+ --newtab-button-primary-color: #0060DF;
+ --newtab-button-secondary-color: inherit;
+ --newtab-feed-button-background: #EDEDF0;
+ --newtab-feed-button-text: #0C0C0D;
+ --newtab-feed-button-background-faded: rgba(237, 237, 240, 0.6);
+ --newtab-feed-button-text-faded: rgba(12, 12, 13, 0);
+ --newtab-feed-button-spinner: #737373;
+ --newtab-contextmenu-background-color: #F9F9FA;
+ --newtab-contextmenu-button-color: #FFF;
+ --newtab-modal-color: #FFF;
+ --newtab-overlay-color: rgba(237, 237, 240, 0.8);
+ --newtab-section-header-text-color: #737373;
+ --newtab-section-navigation-text-color: #737373;
+ --newtab-section-active-contextmenu-color: #0C0C0D;
+ --newtab-search-border-color: transparent;
+ --newtab-search-dropdown-color: #FFF;
+ --newtab-search-dropdown-header-color: #F9F9FA;
+ --newtab-search-header-background-color: rgba(249, 249, 250, 0.95);
+ --newtab-search-icon-color: rgba(12, 12, 13, 0.4);
+ --newtab-search-wordmark-color: #363959;
+ --newtab-topsites-background-color: #FFF;
+ --newtab-topsites-icon-shadow: inset 0 0 0 1px var(--newtab-inner-box-shadow-color);
+ --newtab-topsites-label-color: inherit;
+ --newtab-topsites-outer-card-hover: rgba(0, 0, 0, 0.05);
+ --newtab-topsites-context-menu-hover: rgba(0, 0, 0, 0.05);
+ --newtab-card-active-outline-color: #D7D7DB;
+ --newtab-card-background-color: #FFF;
+ --newtab-card-hairline-color: rgba(0, 0, 0, 0.1);
+ --newtab-card-placeholder-color: #D7D7DB;
+ --newtab-card-shadow: 0 1px 4px 0 rgba(12, 12, 13, 0.1);
+ --newtab-snippets-background-color: #FFF;
+ --newtab-snippets-hairline-color: transparent;
+ --newtab-background-primary-text-color: #151515;
+ --newtab-focus-outline: rgba(0, 96, 223, 0.25);
+ --newtab-focus-border: #0060DF;
+ --newtab-focus-border-selected: rgba(0, 0, 0, 0.15);
+ --newtab-seperator-line-color: #E1E0E6;
+ --newtab-primary-action-background: #0060DF;
+ --newtab-primary-action-background-off: #E9E9E9;
+ --customize-menu-primary-text-color: #20123A;
+ --customize-menu-check-fill: #FFF;
+ --customize-menu-background: #FFF;
+ --customize-menu-secondary-action-background: #F9F9FA;
+ --customize-menu-secondary-action-background-hover: #EDEDF0;
+ --customize-menu-secondary-action-background-active: #E2E2E6;
+ --customize-menu-seperator-line-color: #E1E0E6;
+ --customize-menu-first-shadow: rgba(9, 32, 77, 0.12);
+ --customize-menu-second-shadow: rgba(29, 17, 51, 0.12);
+ --customize-menu-primary-action-text: #FFF;
+ --customize-menu-line-color: #716F87;
+ --newtab-search-first-shadow: rgba(9, 32, 77, 0.12);
+ --newtab-search-second-shadow: rgba(29, 17, 51, 0.12);
+ --newtab-search-text-color: #585165;
+ --newtab-card-first-shadow: rgba(9, 32, 77, 0.12);
+ --newtab-card-second-shadow: rgba(29, 17, 51, 0.12);
+ --newtab-wordmark-color: #20123A; }
+ body[lwt-newtab-brighttext] {
+ --newtab-background-color: #2A2A2E;
+ --newtab-border-primary-color: rgba(249, 249, 250, 0.8);
+ --newtab-border-secondary-color: rgba(249, 249, 250, 0.1);
+ --newtab-button-primary-color: #0060DF;
+ --newtab-button-secondary-color: #38383D;
+ --newtab-element-active-color: rgba(249, 249, 250, 0.2);
+ --newtab-element-hover-color: rgba(249, 249, 250, 0.1);
+ --newtab-icon-primary-color: rgba(249, 249, 250, 0.8);
+ --newtab-icon-secondary-color: rgba(249, 249, 250, 0.4);
+ --newtab-icon-tertiary-color: rgba(249, 249, 250, 0.4);
+ --newtab-inner-box-shadow-color: rgba(249, 249, 250, 0.2);
+ --newtab-inner-box-shadow-color-nte: rgba(21, 20, 26, 0.5);
+ --newtab-tile-shadow-secondary: rgba(21, 20, 26, 0.75);
+ --newtab-link-primary-color: #45A1FF;
+ --newtab-link-secondary-color: #50BCB6;
+ --newtab-text-conditional-color: #F9F9FA;
+ --newtab-text-primary-color: #F9F9FA;
+ --newtab-text-secondary-color: rgba(249, 249, 250, 0.8);
+ --newtab-textbox-background-color: #38383D;
+ --newtab-textbox-border: rgba(249, 249, 250, 0.2);
+ --newtab-textbox-focus-color: #45A1FF;
+ --newtab-textbox-focus-boxshadow: 0 0 0 1px #45A1FF, 0 0 0 4px rgba(69, 161, 255, 0.3);
+ --newtab-background-button-color: rgba(80, 80, 80, 0.5);
+ --newtab-background-button-text-color: #CDCDD4;
+ --newtab-background-button-hover-color: rgba(114, 114, 114, 0.5);
+ --newtab-background-button-active-color: rgba(173, 173, 173, 0.5);
+ --newtab-feed-button-background: #38383D;
+ --newtab-feed-button-text: #F9F9FA;
+ --newtab-feed-button-background-faded: rgba(56, 56, 61, 0.6);
+ --newtab-feed-button-text-faded: rgba(249, 249, 250, 0);
+ --newtab-feed-button-spinner: #D7D7DB;
+ --newtab-contextmenu-background-color: #4A4A4F;
+ --newtab-contextmenu-button-color: #2A2A2E;
+ --newtab-modal-color: #2A2A2E;
+ --newtab-overlay-color: rgba(12, 12, 13, 0.8);
+ --newtab-section-header-text-color: rgba(249, 249, 250, 0.8);
+ --newtab-section-navigation-text-color: rgba(249, 249, 250, 0.8);
+ --newtab-section-active-contextmenu-color: #FFF;
+ --newtab-search-border-color: rgba(249, 249, 250, 0.2);
+ --newtab-search-dropdown-color: #38383D;
+ --newtab-search-dropdown-header-color: #4A4A4F;
+ --newtab-search-header-background-color: rgba(42, 42, 46, 0.95);
+ --newtab-search-icon-color: rgba(249, 249, 250, 0.6);
+ --newtab-search-wordmark-color: #FFF;
+ --newtab-topsites-background-color: #38383D;
+ --newtab-topsites-icon-shadow: none;
+ --newtab-topsites-label-color: rgba(249, 249, 250, 0.8);
+ --newtab-topsites-outer-card-hover: rgba(180, 180, 180, 0.1);
+ --newtab-topsites-context-menu-hover: rgba(180, 180, 180, 0.1);
+ --newtab-card-active-outline-color: #4A4A4F;
+ --newtab-card-background-color: #38383D;
+ --newtab-card-hairline-color: rgba(249, 249, 250, 0.1);
+ --newtab-card-placeholder-color: #4A4A4F;
+ --newtab-card-shadow: 0 1px 8px 0 rgba(12, 12, 13, 0.2);
+ --newtab-snippets-background-color: #38383D;
+ --newtab-snippets-hairline-color: rgba(255, 255, 255, 0.1);
+ --newtab-background-primary-text-color: #CDCDD4;
+ --newtab-focus-outline: rgba(80, 145, 241, 0.5);
+ --newtab-focus-border: #B5D3FF;
+ --newtab-focus-border-selected: #B5D3FF;
+ --newtab-primary-action-background: #4484E2;
+ --newtab-primary-action-background-off: #6A6A6F;
+ --newtab-seperator-line-color: #53515F;
+ --customize-menu-primary-text-color: #E0E0E6;
+ --customize-menu-check-fill: #E0E0E6;
+ --customize-menu-background: #38383D;
+ --customize-menu-secondary-action-background: #515156;
+ --customize-menu-secondary-action-background-hover: #606065;
+ --customize-menu-secondary-action-background-active: #6F6F74;
+ --customize-menu-seperator-line-color: #53515F;
+ --customize-menu-first-shadow: rgba(21, 20, 26, 0.5);
+ --customize-menu-second-shadow: rgba(21, 20, 26, 0.75);
+ --customize-menu-primary-action-text: #E0E0E6;
+ --customize-menu-line-color: #B9B7CC;
+ --newtab-search-first-shadow: rgba(21, 20, 26, 0.5);
+ --newtab-search-second-shadow: rgba(21, 20, 26, 0.75);
+ --newtab-search-text-color: #B1B1BD;
+ --newtab-card-first-shadow: rgba(21, 20, 26, 0.5);
+ --newtab-card-second-shadow: rgba(21, 20, 26, 0.75);
+ --newtab-wordmark-color: #FFF; }
+
+.icon {
+ background-position: center center;
+ background-repeat: no-repeat;
+ background-size: 16px;
+ -moz-context-properties: fill;
+ display: inline-block;
+ color: var(--newtab-icon-primary-color);
+ fill: currentColor;
+ height: 16px;
+ vertical-align: middle;
+ width: 16px; }
+ .icon.icon-spacer {
+ margin-inline-end: 8px; }
+ .icon.icon-small-spacer {
+ margin-inline-end: 6px; }
+ .icon.icon-button-style {
+ fill: var(--newtab-icon-secondary-color);
+ border: 0; }
+ .icon.icon-button-style:focus, .icon.icon-button-style:hover {
+ fill: var(--newtab-text-primary-color); }
+ .icon.icon-bookmark-added {
+ background-image: url("chrome://browser/skin/bookmark.svg"); }
+ .icon.icon-bookmark-hollow {
+ background-image: url("chrome://browser/skin/bookmark-hollow.svg"); }
+ .icon.icon-clear-input {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-cancel-16.svg"); }
+ .icon.icon-delete {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-delete-16.svg"); }
+ .icon.icon-search {
+ background-image: url("chrome://browser/skin/search-glass.svg"); }
+ .icon.icon-modal-delete {
+ flex-shrink: 0;
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-modal-delete-32.svg");
+ background-size: 32px;
+ height: 32px;
+ width: 32px; }
+ .icon.icon-mail {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-mail-16.svg"); }
+ .icon.icon-dismiss {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-dismiss-16.svg"); }
+ .icon.icon-info {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-info-16.svg"); }
+ .icon.icon-new-window {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-newWindow-16.svg"); }
+ .icon.icon-new-window:dir(rtl) {
+ transform: scaleX(-1); }
+ .icon.icon-new-window-private {
+ background-image: url("chrome://browser/skin/privateBrowsing.svg"); }
+ .icon.icon-settings {
+ background-image: url("chrome://global/skin/icons/settings.svg"); }
+ .icon.icon-pin {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-pin-16.svg"); }
+ .icon.icon-pin:dir(rtl) {
+ transform: scaleX(-1); }
+ .icon.icon-unpin {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-unpin-16.svg"); }
+ .icon.icon-unpin:dir(rtl) {
+ transform: scaleX(-1); }
+ .icon.icon-edit {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-edit-16.svg"); }
+ .icon.icon-pocket {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-pocket-16.svg"); }
+ .icon.icon-pocket-save {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-pocket-save-16.svg"); }
+ .icon.icon-pocket-delete {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-pocket-delete-16.svg"); }
+ .icon.icon-pocket-archive {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-pocket-archive-16.svg"); }
+ .icon.icon-history-item {
+ background-image: url("chrome://browser/skin/history.svg"); }
+ .icon.icon-trending {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-trending-16.svg");
+ transform: translateY(2px); }
+ .icon.icon-now {
+ background-image: url("chrome://browser/skin/history.svg"); }
+ .icon.icon-topsites {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-topsites-16.svg"); }
+ .icon.icon-pin-small {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-pin-12.svg");
+ background-size: 12px;
+ height: 12px;
+ width: 12px; }
+ .icon.icon-pin-small:dir(rtl) {
+ transform: scaleX(-1); }
+ .icon.icon-check {
+ background-image: url("chrome://global/skin/icons/check.svg"); }
+ .icon.icon-download {
+ background-image: url("chrome://browser/skin/downloads/download-icons.svg#arrow-with-bar"); }
+ .icon.icon-copy {
+ background-image: url("chrome://browser/skin/edit-copy.svg"); }
+ .icon.icon-open-file {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-open-file-16.svg"); }
+ .icon.icon-webextension {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-webextension-16.svg"); }
+ .icon.icon-highlights {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-highlights-16.svg"); }
+ .icon.icon-arrowhead-down {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-arrowhead-down-16.svg"); }
+ .icon.icon-arrowhead-down-small {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-arrowhead-down-12.svg");
+ background-size: 12px;
+ height: 12px;
+ width: 12px; }
+ .icon.icon-arrowhead-forward-small {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-arrowhead-down-12.svg");
+ background-size: 12px;
+ height: 12px;
+ transform: rotate(-90deg);
+ width: 12px; }
+ .icon.icon-arrowhead-forward-small:dir(rtl) {
+ transform: rotate(90deg); }
+ .icon.icon-arrowhead-up {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-arrowhead-down-16.svg");
+ transform: rotate(180deg); }
+ .icon.icon-add {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-add-16.svg"); }
+ .icon.icon-minimize {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-minimize-16.svg"); }
+ .icon.icon-maximize {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-maximize-16.svg"); }
+ .icon.icon-arrow {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-arrow.svg"); }
+
+html {
+ height: 100%; }
+
+body,
+#root {
+ min-height: 100vh; }
+
+#root {
+ position: relative; }
+
+body {
+ background-color: var(--newtab-background-color);
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Ubuntu', 'Helvetica Neue', sans-serif;
+ font-size: 16px; }
+
+.no-scroll {
+ overflow: hidden; }
+
+h1,
+h2 {
+ font-weight: normal; }
+
+a {
+ text-decoration: none; }
+
+.inner-border {
+ border: 1px solid var(--newtab-border-secondary-color);
+ border-radius: 3px;
+ height: 100%;
+ left: 0;
+ pointer-events: none;
+ position: absolute;
+ top: 0;
+ width: 100%;
+ z-index: 100; }
+
+@keyframes fadeIn {
+ from {
+ opacity: 0; }
+ to {
+ opacity: 1; } }
+
+.show-on-init {
+ opacity: 0;
+ transition: opacity 0.2s ease-in; }
+ .show-on-init.on {
+ animation: fadeIn 0.2s;
+ opacity: 1; }
+
+.actions {
+ border-top: 1px solid var(--newtab-border-secondary-color);
+ display: flex;
+ flex-direction: row;
+ flex-wrap: wrap;
+ justify-content: flex-start;
+ margin: 0;
+ padding: 15px 25px 0; }
+
+.button,
+.actions button {
+ background-color: var(--newtab-button-secondary-color);
+ border: 1px solid var(--newtab-border-primary-color);
+ border-radius: 4px;
+ color: inherit;
+ cursor: pointer;
+ margin-bottom: 15px;
+ padding: 10px 30px;
+ white-space: nowrap; }
+ .button:hover:not(.dismiss), .button:focus:not(.dismiss),
+ .actions button:hover:not(.dismiss),
+ .actions button:focus:not(.dismiss) {
+ box-shadow: 0 0 0 5px var(--newtab-card-active-outline-color);
+ transition: box-shadow 150ms; }
+ .button.dismiss,
+ .actions button.dismiss {
+ background-color: transparent;
+ border: 0;
+ padding: 0;
+ text-decoration: underline; }
+ .button.primary, .button.done,
+ .actions button.primary,
+ .actions button.done {
+ background-color: var(--newtab-button-primary-color);
+ border: solid 1px var(--newtab-button-primary-color);
+ color: #FFF;
+ margin-inline-start: auto; }
+
+input[type='text'], input[type='search'] {
+ border-radius: 3px; }
+
+.clamp {
+ -webkit-box-orient: vertical;
+ display: -webkit-box;
+ overflow: hidden;
+ word-break: break-word; }
+
+.a11y-link-button {
+ border: 0;
+ padding: 0;
+ cursor: pointer;
+ text-align: unset;
+ color: var(--newtab-link-primary-color); }
+ .a11y-link-button:hover, .a11y-link-button:focus {
+ text-decoration: underline; }
+
+.outer-wrapper {
+ color: var(--newtab-text-primary-color);
+ display: flex;
+ flex-grow: 1;
+ min-height: 100vh;
+ padding: 30px 32px 32px; }
+ .outer-wrapper.ds-outer-wrapper-breakpoint-override {
+ padding: 30px 0 32px; }
+ @media (min-width: 610px) {
+ .outer-wrapper.ds-outer-wrapper-breakpoint-override {
+ padding: 30px 32px 32px; } }
+ .outer-wrapper.only-search {
+ display: block;
+ padding-top: 134px; }
+ .outer-wrapper a {
+ color: var(--newtab-link-primary-color); }
+
+main {
+ margin: auto;
+ width: 274px;
+ padding-bottom: 68px; }
+ main section {
+ margin-bottom: 20px;
+ position: relative; }
+ .hide-main main {
+ visibility: hidden; }
+ @media (min-width: 610px) {
+ main {
+ width: 530px; } }
+ @media (min-width: 866px) {
+ main {
+ width: 786px; } }
+ @media (min-width: 1122px) {
+ main {
+ width: 1042px; } }
+
+.below-search-snippet.withButton {
+ margin: auto;
+ width: 100%; }
+
+.ds-outer-wrapper-search-alignment main {
+ margin: 0 auto; }
+
+.ds-outer-wrapper-breakpoint-override main {
+ width: 266px;
+ padding-bottom: 68px; }
+ @media (min-width: 610px) {
+ .ds-outer-wrapper-breakpoint-override main {
+ width: 510px; } }
+ @media (min-width: 866px) {
+ .ds-outer-wrapper-breakpoint-override main {
+ width: 746px; } }
+ @media (min-width: 1122px) {
+ .ds-outer-wrapper-breakpoint-override main {
+ width: 986px; } }
+
+.base-content-fallback {
+ height: 100vh; }
+
+
+.body-wrapper .section-title,
+.body-wrapper .sections-list .section:last-of-type,
+.body-wrapper .topics {
+ opacity: 0; }
+
+
+.body-wrapper.on .section-title,
+.body-wrapper.on .sections-list .section:last-of-type,
+.body-wrapper.on .topics {
+ opacity: 1; }
+
+.non-collapsible-section {
+ padding: 0 25px; }
+
+.prefs-button button {
+ background-color: transparent;
+ border: 0;
+ border-radius: 2px;
+ cursor: pointer;
+ inset-inline-end: 15px;
+ padding: 15px;
+ position: fixed;
+ top: 15px;
+ z-index: 1000; }
+ .prefs-button button:hover, .prefs-button button:focus {
+ background-color: var(--newtab-element-hover-color); }
+ .prefs-button button:active {
+ background-color: var(--newtab-element-active-color); }
+
+@media (max-height: 701px) {
+ .personalize-button {
+ position: absolute;
+ top: 16px;
+ inset-inline-end: 16px; } }
+
+@media (min-height: 700px) {
+ .personalize-button {
+ position: fixed;
+ top: 16px;
+ inset-inline-end: 16px;
+ z-index: 1000; } }
+
+.personalize-button {
+ font-size: 12px;
+ font-weight: 600;
+ border: 0;
+ border-radius: 4px;
+ background-color: var(--newtab-background-button-color);
+ color: var(--newtab-background-button-text-color);
+ padding: 3px 10px;
+ min-height: 32px;
+ max-width: 117px; }
+ .personalize-button:hover {
+ background-color: var(--newtab-background-button-hover-color); }
+ .personalize-button:active {
+ background-color: var(--newtab-background-button-active-color); }
+ .personalize-button:focus-visible {
+ border: 0;
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-focus-outline), 0 0 0 1px var(--newtab-focus-border); }
+
+.as-error-fallback {
+ align-items: center;
+ border-radius: 3px;
+ box-shadow: inset 0 0 0 1px var(--newtab-inner-box-shadow-color);
+ color: var(--newtab-text-conditional-color);
+ display: flex;
+ flex-direction: column;
+ font-size: 12px;
+ justify-content: center;
+ justify-items: center;
+ line-height: 1.5; }
+ .as-error-fallback.borderless-error {
+ box-shadow: none; }
+ .as-error-fallback a {
+ color: var(--newtab-text-conditional-color);
+ text-decoration: underline; }
+
+.top-sites-list {
+ list-style: none;
+ margin: 0 -16px;
+ padding: 0; }
+ @media (max-width: 610px) {
+ .top-sites-list > :nth-child(2n+1) .context-menu {
+ margin-inline-end: auto;
+ margin-inline-start: auto;
+ inset-inline-end: auto;
+ inset-inline-start: -32px; }
+ .top-sites-list > :nth-child(2n) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+ @media (min-width: 610px) and (max-width: 866px) {
+ .top-sites-list :nth-child(4n) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+ @media (min-width: 610px) and (max-width: 834px) {
+ .top-sites-list :nth-child(4n+3) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+ @media (min-width: 866px) and (max-width: 1314px) {
+ .top-sites-list :nth-child(6n) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+ @media (min-width: 866px) and (max-width: 1090px) {
+ .top-sites-list :nth-child(6n+5) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+ @media (min-width: 1122px) and (max-width: 1570px) {
+ .top-sites-list :nth-child(8n) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+ @media (min-width: 1122px) and (max-width: 1346px) {
+ .top-sites-list :nth-child(8n+7) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+ .top-sites-list .hide-for-narrow {
+ display: none; }
+ @media (min-width: 610px) {
+ .top-sites-list .hide-for-narrow {
+ display: inline-block; } }
+ @media (min-width: 866px) {
+ .top-sites-list .hide-for-narrow {
+ display: none; } }
+ @media (min-width: 1122px) {
+ .top-sites-list .hide-for-narrow {
+ display: inline-block; } }
+
+.top-site-outer {
+ padding: 0 16px;
+ display: inline-block; }
+ .top-site-outer .top-site-inner {
+ position: relative; }
+ .top-site-outer .top-site-inner > a {
+ color: inherit;
+ display: block;
+ outline: none; }
+ .top-site-outer .tile {
+ border-radius: 4px;
+ box-shadow: inset 0 0 0 1px var(--newtab-inner-box-shadow-color), var(--newtab-card-shadow);
+ cursor: pointer;
+ position: relative;
+ align-items: center;
+ color: var(--newtab-text-secondary-color);
+ display: flex;
+ font-size: 32px;
+ font-weight: 200;
+ justify-content: center;
+ text-transform: uppercase; }
+ .top-site-outer .tile .icon-wrapper {
+ border-radius: 4px;
+ width: 48px;
+ height: 48px;
+ overflow: hidden;
+ position: relative;
+ display: flex;
+ align-items: center;
+ justify-content: center; }
+ .top-site-outer .tile .icon-wrapper.letter-fallback::before {
+ content: attr(data-fallback);
+ text-transform: uppercase;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ font-size: 64px;
+ font-weight: 800;
+ transform: rotate(-10deg);
+ top: 6px;
+ position: relative;
+ color: #FFF; }
+ .top-site-outer .top-site-icon {
+ background-color: var(--newtab-topsites-background-color);
+ background-position: center center;
+ background-repeat: no-repeat;
+ border-radius: 4px;
+ position: absolute; }
+ .top-site-outer .rich-icon {
+ background-size: cover;
+ height: 100%;
+ inset-inline-start: 0;
+ top: 0;
+ width: 100%; }
+ .top-site-outer .default-icon,
+ .top-site-outer .search-topsite {
+ background-size: 32px;
+ height: 42px;
+ width: 42px;
+ align-items: center;
+ display: flex;
+ font-size: 20px;
+ justify-content: center; }
+ .top-site-outer .default-icon[data-fallback]::before,
+ .top-site-outer .search-topsite[data-fallback]::before {
+ content: attr(data-fallback); }
+ .top-site-outer .search-topsite {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-search-16.svg");
+ background-size: 26px;
+ background-color: #0060DF;
+ border-radius: 42px;
+ -moz-context-properties: fill;
+ fill: #FFF;
+ box-shadow: var(--newtab-card-shadow);
+ transition-duration: 150ms;
+ transition-property: background-size, bottom, inset-inline-end, height, width;
+ height: 42px;
+ width: 42px;
+ bottom: -6px;
+ inset-inline-end: -6px; }
+ .top-site-outer .title {
+ color: var(--newtab-topsites-label-color);
+ font: message-box;
+ padding-top: 4px;
+ text-align: center;
+ position: relative; }
+ .top-site-outer .title .icon {
+ fill: var(--newtab-icon-tertiary-color); }
+ .top-site-outer .title span {
+ display: block;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap; }
+ .top-site-outer .title .sponsored-label {
+ color: #737373;
+ font-size: 0.9em; }
+ .top-site-outer .title:not(.sponsored) .sponsored-label {
+ visibility: hidden; }
+ .top-site-outer.search-shortcut .rich-icon {
+ background-color: #FFF; }
+ .top-site-outer .edit-button {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-edit-16.svg"); }
+ .top-site-outer.placeholder .screenshot {
+ display: none; }
+ .top-site-outer.dragged .tile {
+ background: #EDEDF0;
+ box-shadow: none; }
+ .top-site-outer.dragged .tile *, .top-site-outer.dragged .tile::before {
+ display: none; }
+ .top-site-outer.dragged .title {
+ visibility: hidden; }
+
+.edit-topsites-wrapper .modal {
+ box-shadow: 0 1px 4px 0 rgba(12, 12, 13, 0.2);
+ left: 0;
+ margin: 0 auto;
+ max-height: calc(100% - 40px);
+ position: fixed;
+ right: 0;
+ top: 40px;
+ width: 274px; }
+ @media (min-width: 610px) {
+ .edit-topsites-wrapper .modal {
+ width: 530px; } }
+ @media (min-width: 866px) {
+ .edit-topsites-wrapper .modal {
+ width: 786px; } }
+
+.topsite-form .section-title {
+ font-size: 16px;
+ margin: 0 0 16px; }
+
+.topsite-form .form-input-container {
+ max-width: 492px;
+ margin: 0 auto;
+ padding: 32px; }
+ .topsite-form .form-input-container .top-site-outer {
+ pointer-events: none; }
+
+.topsite-form .search-shortcuts-container {
+ max-width: 700px;
+ margin: 0 auto;
+ padding: 32px; }
+ .topsite-form .search-shortcuts-container > div {
+ margin-inline-end: -39px; }
+ .topsite-form .search-shortcuts-container .top-site-outer {
+ margin-inline-start: 0;
+ margin-inline-end: 39px; }
+
+.topsite-form .top-site-outer {
+ padding: 0;
+ margin: 24px 0 0;
+ margin-inline-start: 32px; }
+
+.topsite-form .fields-and-preview {
+ display: flex; }
+
+.topsite-form label {
+ font-size: 13px; }
+
+.topsite-form .form-wrapper {
+ width: 100%; }
+ .topsite-form .form-wrapper .field {
+ position: relative; }
+ .topsite-form .form-wrapper .field .icon-clear-input {
+ position: absolute;
+ transform: translateY(-50%);
+ top: 50%;
+ inset-inline-end: 8px; }
+ .topsite-form .form-wrapper .url input:dir(ltr) {
+ padding-right: 32px; }
+ .topsite-form .form-wrapper .url input:dir(rtl) {
+ padding-left: 32px; }
+ .topsite-form .form-wrapper .url input:dir(rtl):not(:placeholder-shown) {
+ direction: ltr;
+ text-align: right; }
+ .topsite-form .form-wrapper .enable-custom-image-input {
+ display: inline-block;
+ font-size: 13px;
+ margin-top: 4px;
+ cursor: pointer; }
+ .topsite-form .form-wrapper .custom-image-input-container {
+ margin-top: 4px; }
+ .topsite-form .form-wrapper .custom-image-input-container .loading-container {
+ width: 16px;
+ height: 16px;
+ overflow: hidden;
+ position: absolute;
+ transform: translateY(-50%);
+ top: 50%;
+ inset-inline-end: 8px; }
+ .topsite-form .form-wrapper .custom-image-input-container .loading-animation {
+ width: 960px;
+ height: 16px;
+ -moz-context-properties: fill;
+ fill: #0A84FF;
+ background-image: url("chrome://browser/skin/tabbrowser/loading.svg");
+ animation: tab-throbber-animation 1.05s steps(60) infinite; }
+
+@keyframes tab-throbber-animation {
+ 100% {
+ transform: translateX(-960px); } }
+
+@keyframes tab-throbber-animation-rtl {
+ 100% {
+ transform: translateX(960px); } }
+ .topsite-form .form-wrapper .custom-image-input-container .loading-animation:dir(rtl) {
+ animation-name: tab-throbber-animation-rtl; }
+ .topsite-form .form-wrapper input[type='text'] {
+ background-color: var(--newtab-textbox-background-color);
+ border: 1px solid var(--newtab-textbox-border);
+ margin: 8px 0;
+ padding: 0 8px;
+ height: 32px;
+ width: 100%;
+ font-size: 15px; }
+ .topsite-form .form-wrapper input[type='text'][disabled] {
+ border: 1px solid var(--newtab-textbox-border);
+ box-shadow: none;
+ opacity: 0.4; }
+ .topsite-form .form-wrapper .invalid input[type='text'] {
+ border: 1px solid #D70022;
+ box-shadow: 0 0 0 1px #D70022, 0 0 0 4px rgba(215, 0, 34, 0.3); }
+ .topsite-form .form-wrapper .error-tooltip {
+ animation: fade-up-tt 450ms;
+ background: #D70022;
+ border-radius: 2px;
+ color: #FFF;
+ inset-inline-start: 3px;
+ padding: 5px 12px;
+ position: absolute;
+ top: 44px;
+ z-index: 1; }
+ .topsite-form .form-wrapper .error-tooltip::before {
+ background: #D70022;
+ bottom: -8px;
+ content: '.';
+ height: 16px;
+ inset-inline-start: 12px;
+ position: absolute;
+ text-indent: -999px;
+ top: -7px;
+ transform: rotate(45deg);
+ white-space: nowrap;
+ width: 16px;
+ z-index: -1; }
+
+.topsite-form .actions {
+ justify-content: flex-end; }
+ .topsite-form .actions button {
+ margin-inline-start: 10px;
+ margin-inline-end: 0; }
+
+@media (max-width: 610px) {
+ .topsite-form .fields-and-preview {
+ flex-direction: column; }
+ .topsite-form .fields-and-preview .top-site-outer {
+ margin-inline-start: 0; } }
+
+.topsite-form .title {
+ user-select: none; }
+
+.topsite-form [type='checkbox']:not(:checked),
+.topsite-form [type='checkbox']:checked {
+ inset-inline-start: -9999px;
+ position: absolute; }
+
+.topsite-form [type='checkbox']:not(:checked) + label,
+.topsite-form [type='checkbox']:checked + label {
+ cursor: pointer;
+ display: block;
+ position: relative; }
+
+.topsite-form [type='checkbox']:not(:checked) + label::before,
+.topsite-form [type='checkbox']:checked + label::before {
+ background: var(--newtab-background-color);
+ border: 1px solid var(--newtab-textbox-border);
+ border-radius: 3px;
+ content: '';
+ height: 21px;
+ left: -8px;
+ position: absolute;
+ top: -8px;
+ width: 21px;
+ z-index: 1; }
+ [dir='rtl'] .topsite-form [type='checkbox']:not(:checked) + label::before, [dir='rtl']
+ .topsite-form [type='checkbox']:checked + label::before {
+ left: auto;
+ right: -8px; }
+
+.topsite-form [type='checkbox']:not(:checked) + label::after,
+.topsite-form [type='checkbox']:checked + label::after {
+ background: url("chrome://global/skin/icons/check.svg") no-repeat center center;
+ content: '';
+ height: 21px;
+ left: -8px;
+ position: absolute;
+ top: -8px;
+ width: 21px;
+ -moz-context-properties: fill;
+ fill: var(--newtab-link-primary-color);
+ z-index: 2; }
+ [dir='rtl'] .topsite-form [type='checkbox']:not(:checked) + label::after, [dir='rtl']
+ .topsite-form [type='checkbox']:checked + label::after {
+ left: auto;
+ right: -8px; }
+
+.topsite-form [type='checkbox']:checked + label .tile {
+ box-shadow: 0 0 0 2px var(--newtab-link-primary-color); }
+
+.topsite-form [type='checkbox']:not(:checked) + label::after {
+ opacity: 0; }
+
+.topsite-form [type='checkbox']:checked + label::after {
+ opacity: 1; }
+
+.topsite-form [type='checkbox']:checked:focus + label::before,
+.topsite-form [type='checkbox']:not(:checked):focus + label::before {
+ border: 1px dotted var(--newtab-link-primary-color); }
+
+.outer-wrapper:not(.newtab-experience) .top-site-outer .context-menu-button {
+ background-clip: padding-box;
+ background-color: var(--newtab-contextmenu-button-color);
+ background-image: url("chrome://global/skin/icons/more.svg");
+ background-position: 55%;
+ border: 1px solid var(--newtab-border-primary-color);
+ border-radius: 100%;
+ box-shadow: 0 2px rgba(12, 12, 13, 0.1);
+ cursor: pointer;
+ fill: var(--newtab-icon-primary-color);
+ height: 27px;
+ inset-inline-end: -13.5px;
+ opacity: 0;
+ position: absolute;
+ top: -13.5px;
+ transform: scale(0.25);
+ transition-duration: 150ms;
+ transition-property: transform, opacity;
+ width: 27px; }
+ .outer-wrapper:not(.newtab-experience) .top-site-outer .context-menu-button:is(:active, :focus) {
+ opacity: 1;
+ transform: scale(1); }
+
+.outer-wrapper:not(.newtab-experience) .top-site-outer .tile {
+ height: 96px;
+ width: 96px;
+ transition: box-shadow 150ms; }
+
+.outer-wrapper:not(.newtab-experience) .top-site-outer .top-site-icon {
+ box-shadow: var(--newtab-topsites-icon-shadow); }
+
+.outer-wrapper:not(.newtab-experience) .top-site-outer .title {
+ width: 96px; }
+ .outer-wrapper:not(.newtab-experience) .top-site-outer .title.has-icon span {
+ padding: 0 13px; }
+ .outer-wrapper:not(.newtab-experience) .top-site-outer .title .icon {
+ inset-inline-start: 0;
+ position: absolute;
+ top: 0.5em; }
+
+.outer-wrapper:not(.newtab-experience) .top-site-outer .top-site-inner {
+ position: relative; }
+ .outer-wrapper:not(.newtab-experience) .top-site-outer .top-site-inner > a {
+ color: inherit;
+ display: block;
+ outline: none; }
+ .outer-wrapper:not(.newtab-experience) .top-site-outer .top-site-inner > a:is(.active, :focus) .tile {
+ box-shadow: inset 0 0 0 1px var(--newtab-inner-box-shadow-color), 0 0 0 5px var(--newtab-card-active-outline-color);
+ transition: box-shadow 150ms; }
+
+.outer-wrapper:not(.newtab-experience) .top-site-outer .screenshot {
+ background-color: #FFF;
+ background-position: top left;
+ background-size: cover;
+ border-radius: 4px;
+ box-shadow: inset 0 0 0 1px var(--newtab-inner-box-shadow-color);
+ height: 100%;
+ opacity: 0;
+ position: absolute;
+ top: 0;
+ left: 0;
+ transition: opacity 1s;
+ width: 100%; }
+ .outer-wrapper:not(.newtab-experience) .top-site-outer .screenshot.active {
+ opacity: 1; }
+
+.outer-wrapper:not(.newtab-experience) .top-site-outer .default-icon,
+.outer-wrapper:not(.newtab-experience) .top-site-outer .search-topsite {
+ bottom: -6px;
+ inset-inline-end: -6px; }
+
+.outer-wrapper:not(.newtab-experience) .top-site-outer:hover .search-topsite {
+ background-size: 28px;
+ border-radius: 46px;
+ bottom: -9px;
+ height: 46px;
+ inset-inline-end: -9px;
+ width: 46px; }
+
+.outer-wrapper:not(.newtab-experience) .top-site-outer.placeholder .tile {
+ box-shadow: inset 0 0 0 1px var(--newtab-inner-box-shadow-color); }
+
+.outer-wrapper:not(.newtab-experience) .top-sites-list:not(.dnd-active) .top-site-outer:is(.active, :focus, :hover) .tile {
+ box-shadow: inset 0 0 0 1px var(--newtab-inner-box-shadow-color), 0 0 0 5px var(--newtab-card-active-outline-color);
+ transition: box-shadow 150ms; }
+
+.outer-wrapper:not(.newtab-experience) .top-sites-list:not(.dnd-active) .top-site-outer:is(.active, :focus, :hover) .context-menu-button {
+ opacity: 1;
+ transform: scale(1);
+ transition-delay: 333ms; }
+
+.outer-wrapper:not(.newtab-experience) .top-sites-list li {
+ margin: 0 0 8px; }
+
+.outer-wrapper.newtab-experience .top-site-outer {
+ width: 120px;
+ padding-block: 20px 4px;
+ border-radius: 8px; }
+ .outer-wrapper.newtab-experience .top-site-outer .context-menu-button {
+ background-image: url("chrome://global/skin/icons/more.svg");
+ border: 0;
+ border-radius: 4px;
+ cursor: pointer;
+ fill: var(--newtab-icon-primary-color);
+ -moz-context-properties: fill;
+ height: 20px;
+ width: 20px;
+ inset-inline-end: -9px;
+ opacity: 0;
+ position: absolute;
+ top: -20px;
+ transition: opacity 200ms; }
+ .outer-wrapper.newtab-experience .top-site-outer .context-menu-button:is(:active, :focus) {
+ outline: 0;
+ opacity: 1;
+ background-color: var(--newtab-topsites-context-menu-hover);
+ fill: var(--newtab-primary-action-background); }
+ .outer-wrapper.newtab-experience .top-site-outer .edit-button {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-edit-16.svg"); }
+ .outer-wrapper.newtab-experience .top-site-outer .tile {
+ border-radius: 8px;
+ box-shadow: 0 3px 8px var(--newtab-inner-box-shadow-color-nte), 0 0 2px var(--newtab-tile-shadow-secondary);
+ background-color: var(--newtab-topsites-background-color);
+ justify-content: center;
+ margin: 0 auto;
+ height: 80px;
+ width: 80px; }
+ .outer-wrapper.newtab-experience .top-site-outer .title {
+ color: var(--newtab-background-primary-text-color);
+ padding-top: 8px;
+ font-size: 12px; }
+ .outer-wrapper.newtab-experience .top-site-outer .title .icon {
+ margin-inline-end: 2px;
+ fill: var(--newtab-background-primary-text-color); }
+ .outer-wrapper.newtab-experience .top-site-outer .title .sponsored-label {
+ font-size: 12px; }
+ .outer-wrapper.newtab-experience .top-site-outer .default-icon,
+ .outer-wrapper.newtab-experience .top-site-outer .search-topsite {
+ height: 32px;
+ width: 32px; }
+ .outer-wrapper.newtab-experience .top-site-outer .search-topsite {
+ background-size: 16px;
+ height: 32px;
+ width: 32px; }
+ .outer-wrapper.newtab-experience .top-site-outer.placeholder .tile {
+ box-shadow: 0 0 0 1px var(--newtab-inner-box-shadow-color); }
+
+@media (max-width: 610px) {
+ .outer-wrapper.newtab-experience .top-sites-list > :nth-child(2n+1) .context-menu {
+ margin-inline-end: auto;
+ margin-inline-start: auto;
+ inset-inline-end: auto;
+ inset-inline-start: -32px; }
+ .outer-wrapper.newtab-experience .top-sites-list > :nth-child(2n) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+
+@media (min-width: 610px) and (max-width: 866px) {
+ .outer-wrapper.newtab-experience .top-sites-list :nth-child(4n) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+
+@media (min-width: 610px) and (max-width: 802px) {
+ .outer-wrapper.newtab-experience .top-sites-list :nth-child(4n+3) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+
+@media (min-width: 866px) and (max-width: 1250px) {
+ .outer-wrapper.newtab-experience .top-sites-list :nth-child(6n) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+
+@media (min-width: 866px) and (max-width: 1058px) {
+ .outer-wrapper.newtab-experience .top-sites-list :nth-child(6n+5) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+
+@media (min-width: 1122px) and (max-width: 1506px) {
+ .outer-wrapper.newtab-experience .top-sites-list :nth-child(8n) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+
+@media (min-width: 1122px) and (max-width: 1314px) {
+ .outer-wrapper.newtab-experience .top-sites-list :nth-child(8n+7) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+
+.outer-wrapper.newtab-experience:not(.dnd-active) .top-site-outer:is(.active, :focus, :hover) {
+ background: var(--newtab-topsites-outer-card-hover); }
+ .outer-wrapper.newtab-experience:not(.dnd-active) .top-site-outer:is(.active, :focus, :hover) .context-menu-button {
+ opacity: 1; }
+
+@keyframes fade-up-tt {
+ 0% {
+ opacity: 0;
+ transform: translateY(15px); }
+ 100% {
+ opacity: 1;
+ transform: translateY(0); } }
+
+.sections-list .section-list {
+ display: grid;
+ grid-gap: 32px;
+ grid-template-columns: repeat(auto-fit, 224px);
+ margin: 0; }
+ @media (max-width: 610px) {
+ .sections-list .section-list .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+ @media (min-width: 610px) and (max-width: 866px) {
+ .sections-list .section-list :nth-child(2n) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+ @media (min-width: 866px) and (max-width: 1314px) {
+ .sections-list .section-list :nth-child(3n) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+ @media (min-width: 1122px) and (max-width: 1570px) {
+ .sections-list .section-list :nth-child(3n) .context-menu,
+ .sections-list .section-list :nth-child(4n) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+
+.sections-list .section-empty-state {
+ border: 1px solid var(--newtab-border-secondary-color);
+ border-radius: 3px;
+ display: flex;
+ height: 266px;
+ width: 100%; }
+ .sections-list .section-empty-state .empty-state {
+ margin: auto;
+ max-width: 350px; }
+ .sections-list .section-empty-state .empty-state .empty-state-icon {
+ background-position: center;
+ background-repeat: no-repeat;
+ background-size: 50px 50px;
+ -moz-context-properties: fill;
+ display: block;
+ fill: var(--newtab-icon-secondary-color);
+ height: 50px;
+ margin: 0 auto;
+ width: 50px; }
+ .sections-list .section-empty-state .empty-state .empty-state-message {
+ color: var(--newtab-text-primary-color);
+ font-size: 13px;
+ margin-bottom: 0;
+ text-align: center; }
+ @media (min-width: 1122px) {
+ .sections-list .section-empty-state {
+ height: 370px; } }
+
+.top-stories-bottom-container {
+ color: var(--newtab-section-navigation-text-color);
+ font-size: 12px;
+ line-height: 1.6;
+ margin-top: 12px;
+ display: flex;
+ justify-content: space-between; }
+ .top-stories-bottom-container a {
+ color: var(--newtab-link-secondary-color);
+ font-weight: bold; }
+ .top-stories-bottom-container a.more-recommendations {
+ font-weight: normal;
+ font-size: 13px; }
+ @media (max-width: 865px) {
+ .top-stories-bottom-container .wrapper-topics,
+ .top-stories-bottom-container .wrapper-cta + .wrapper-more-recommendations {
+ display: none; } }
+ @media (max-width: 609px) {
+ .top-stories-bottom-container .wrapper-cta {
+ text-align: center; }
+ .top-stories-bottom-container .wrapper-cta .pocket-logged-in-cta {
+ display: block;
+ margin-inline-end: 0; }
+ .top-stories-bottom-container .wrapper-cta .pocket-logged-in-cta .pocket-cta-button {
+ max-width: none;
+ display: block;
+ margin-inline-end: 0;
+ margin: 5px 0 10px; }
+ .top-stories-bottom-container .wrapper-more-recommendations {
+ width: 100%; }
+ .top-stories-bottom-container .wrapper-more-recommendations .more-recommendations {
+ justify-content: center; }
+ .top-stories-bottom-container .wrapper-more-recommendations .more-recommendations::after {
+ display: none; } }
+
+@media (min-width: 1122px) {
+ .sections-list .normal-cards .section-list {
+ grid-template-columns: repeat(auto-fit, 309px); } }
+
+.topics ul {
+ margin: 0;
+ padding: 0; }
+ @media (min-width: 866px) {
+ .topics ul {
+ display: inline;
+ padding-inline-start: 12px; } }
+
+.topics ul li {
+ display: inline-block; }
+ .topics ul li::after {
+ content: '•';
+ padding: 8px; }
+ .topics ul li:last-child::after {
+ content: none; }
+
+.outer-wrapper.newtab-experience.visible-logo .logo-and-wordmark .wordmark {
+ fill: var(--newtab-wordmark-color); }
+
+.outer-wrapper.newtab-experience .search-wrapper {
+ padding-bottom: 38px; }
+ .outer-wrapper.newtab-experience .search-wrapper .search-inner-wrapper {
+ min-height: 52px;
+ width: 200px; }
+ @media (min-width: 610px) {
+ .outer-wrapper.newtab-experience .search-wrapper .search-inner-wrapper {
+ width: 360px; } }
+ @media (min-width: 866px) {
+ .outer-wrapper.newtab-experience .search-wrapper .search-inner-wrapper {
+ width: 600px; } }
+ @media (min-width: 1122px) {
+ .outer-wrapper.newtab-experience .search-wrapper .search-inner-wrapper {
+ width: 720px; } }
+ .outer-wrapper.newtab-experience .search-wrapper .search-button:focus {
+ outline: 0;
+ box-shadow: 0 0 0 2px var(--newtab-focus-outline);
+ border: 1px solid var(--newtab-focus-border);
+ border-radius: 0 8px 8px 0; }
+ .outer-wrapper.newtab-experience .search-wrapper input:focus {
+ outline: 0;
+ border: 1px solid var(--newtab-focus-border);
+ box-shadow: 0 0 0 2px var(--newtab-focus-outline); }
+ .outer-wrapper.newtab-experience .search-wrapper.fake-focus .search-handoff-button {
+ border: 1px solid var(--newtab-focus-border);
+ box-shadow: 0 0 0 2px var(--newtab-focus-outline); }
+ .outer-wrapper.newtab-experience .search-wrapper .search-handoff-button,
+ .outer-wrapper.newtab-experience .search-wrapper input {
+ background: var(--newtab-textbox-background-color) var(--newtab-search-icon) 16px center no-repeat;
+ background-size: 24px;
+ padding-inline-start: 52px;
+ padding-inline-end: 10px;
+ box-shadow: 0 3px 8px var(--newtab-search-first-shadow), 0 0 2px var(--newtab-search-second-shadow);
+ border: 1px solid transparent;
+ border-radius: 8px;
+ color: var(--newtab-search-text-color);
+ font-weight: 500;
+ font-size: 15px; }
+ .outer-wrapper.newtab-experience .search-wrapper .search-handoff-button {
+ padding-inline-end: 15px; }
+ .outer-wrapper.newtab-experience .search-wrapper .search-handoff-button .fake-caret {
+ top: 18px;
+ inset-inline-start: 52px; }
+ .outer-wrapper.newtab-experience .search-wrapper .search-handoff-button .fake-caret:dir(rtl) {
+ background-position-x: right 16px; }
+
+.search-wrapper {
+ padding: 34px 0 64px; }
+ .only-search .search-wrapper {
+ padding: 0 0 64px; }
+ .search-wrapper .logo-and-wordmark {
+ align-items: center;
+ display: flex;
+ justify-content: center;
+ margin-bottom: 48px; }
+ .search-wrapper .logo-and-wordmark .logo {
+ background: url("chrome://branding/content/about-logo.png") no-repeat center;
+ background-size: 82px;
+ display: inline-block;
+ height: 82px;
+ width: 82px; }
+ @media (min-resolution: 2x) {
+ .search-wrapper .logo-and-wordmark .logo {
+ background-image: url("chrome://branding/content/about-logo@2x.png"); } }
+ .search-wrapper .logo-and-wordmark .wordmark {
+ background: url("chrome://branding/content/firefox-wordmark.svg") no-repeat center center;
+ background-size: 134px;
+ -moz-context-properties: fill;
+ display: inline-block;
+ fill: var(--newtab-search-wordmark-color);
+ height: 82px;
+ margin-inline-start: 16px;
+ width: 134px; }
+ @media (max-width: 609px) {
+ .search-wrapper .logo-and-wordmark .logo {
+ background-size: 64px;
+ height: 64px;
+ width: 64px; }
+ .search-wrapper .logo-and-wordmark .wordmark {
+ background-size: 100px;
+ height: 64px;
+ width: 100px;
+ margin-inline-start: 12px; } }
+ .search-wrapper .search-inner-wrapper {
+ cursor: default;
+ display: flex;
+ min-height: 48px;
+ margin: 0 auto;
+ position: relative;
+ width: 224px; }
+ .ds-outer-wrapper-breakpoint-override .search-wrapper .search-inner-wrapper {
+ width: 216px; }
+ @media (min-width: 610px) {
+ .search-wrapper .search-inner-wrapper {
+ width: 480px; }
+ .ds-outer-wrapper-breakpoint-override .search-wrapper .search-inner-wrapper {
+ width: 460px; } }
+ @media (min-width: 866px) {
+ .search-wrapper .search-inner-wrapper {
+ width: 736px; }
+ .ds-outer-wrapper-breakpoint-override .search-wrapper .search-inner-wrapper {
+ width: 696px; } }
+ .search-wrapper input {
+ background: var(--newtab-textbox-background-color) var(--newtab-search-icon) 12px center no-repeat;
+ background-size: 24px;
+ border: solid 1px var(--newtab-search-border-color);
+ box-shadow: 0 1px 4px 0 rgba(12, 12, 13, 0.2), 0 0 0 1px rgba(0, 0, 0, 0.15);
+ font-size: 15px;
+ -moz-context-properties: fill;
+ fill: var(--newtab-search-icon-color);
+ padding: 0;
+ padding-inline-end: 48px;
+ padding-inline-start: 46px;
+ width: 100%; }
+ .search-wrapper input:dir(rtl) {
+ background-position-x: right 12px; }
+ .search-wrapper:hover input {
+ box-shadow: 0 1px 4px 0 rgba(12, 12, 13, 0.2), 0 0 0 1px rgba(0, 0, 0, 0.25); }
+ .search-wrapper .search-inner-wrapper:active input,
+ .search-wrapper input:focus {
+ border: 1px solid var(--newtab-textbox-focus-color);
+ box-shadow: var(--newtab-textbox-focus-boxshadow); }
+ .search-wrapper .search-button {
+ background: url("chrome://browser/skin/forward.svg") no-repeat center center;
+ background-size: 16px 16px;
+ border: 0;
+ border-radius: 0 3px 3px 0;
+ -moz-context-properties: fill;
+ fill: var(--newtab-search-icon-color);
+ height: 100%;
+ inset-inline-end: 0;
+ position: absolute;
+ width: 48px; }
+ .search-wrapper .search-button:focus, .search-wrapper .search-button:hover {
+ background-color: rgba(12, 12, 13, 0.1);
+ cursor: pointer; }
+ .search-wrapper .search-button:active {
+ background-color: rgba(12, 12, 13, 0.2); }
+ .search-wrapper .search-button:dir(rtl) {
+ transform: scaleX(-1); }
+
+.non-collapsible-section + .below-search-snippet-wrapper {
+ margin-top: -48px; }
+
+@media (max-height: 700px) {
+ .search-wrapper {
+ padding: 0 0 30px; }
+ .non-collapsible-section + .below-search-snippet-wrapper {
+ margin-top: -14px; }
+ .below-search-snippet-wrapper {
+ min-height: 0; } }
+
+.search-handoff-button {
+ background: var(--newtab-textbox-background-color) var(--newtab-search-icon) 12px center no-repeat;
+ background-size: 24px;
+ border: solid 1px var(--newtab-search-border-color);
+ border-radius: 3px;
+ box-shadow: 0 1px 4px 0 rgba(12, 12, 13, 0.2), 0 0 0 1px rgba(0, 0, 0, 0.15);
+ cursor: text;
+ font-size: 15px;
+ padding: 0;
+ padding-inline-end: 48px;
+ padding-inline-start: 46px;
+ opacity: 1;
+ transition: opacity 500ms;
+ width: 100%; }
+ .search-handoff-button:dir(rtl) {
+ background-position-x: right 12px; }
+ .search-handoff-button:hover {
+ box-shadow: 0 1px 4px 0 rgba(12, 12, 13, 0.2), 0 0 0 1px rgba(0, 0, 0, 0.25); }
+ .fake-focus .search-handoff-button {
+ border: 1px solid var(--newtab-textbox-focus-color);
+ box-shadow: var(--newtab-textbox-focus-boxshadow); }
+ .fake-focus .search-handoff-button .fake-caret {
+ display: block; }
+ .search-hidden .search-handoff-button {
+ opacity: 0;
+ visibility: hidden; }
+ .search-handoff-button .fake-editable:focus {
+ outline: none;
+ caret-color: transparent; }
+ .search-handoff-button .fake-editable {
+ color: transparent;
+ height: 100%;
+ opacity: 0;
+ position: absolute;
+ top: 0;
+ left: 0;
+ right: 0;
+ bottom: 0; }
+ .search-handoff-button .fake-textbox {
+ opacity: 0.54;
+ text-align: start; }
+ .search-handoff-button .fake-caret {
+ animation: caret-animation 1.3s steps(5, start) infinite;
+ background: var(--newtab-text-primary-color);
+ display: none;
+ inset-inline-start: 47px;
+ height: 17px;
+ position: absolute;
+ top: 16px;
+ width: 1px; }
+
+@keyframes caret-animation {
+ to {
+ visibility: hidden; } }
+
+@media (min-height: 701px) {
+ body:not(.inline-onboarding) .fixed-search main {
+ padding-top: 146px; }
+ body:not(.inline-onboarding) .fixed-search.visible-logo main {
+ padding-top: 276px; }
+ body:not(.inline-onboarding) .fixed-search .search-wrapper {
+ border-bottom: solid 1px var(--newtab-border-secondary-color);
+ padding: 30px 0;
+ background-color: var(--newtab-search-header-background-color);
+ min-height: 95px;
+ left: 0;
+ position: fixed;
+ top: 0;
+ width: 100%;
+ z-index: 9; }
+ body:not(.inline-onboarding) .fixed-search .search-wrapper .search-inner-wrapper {
+ min-height: 35px; }
+ body:not(.inline-onboarding) .fixed-search .search-wrapper input {
+ background-position-x: 16px;
+ background-size: 16px; }
+ body:not(.inline-onboarding) .fixed-search .search-wrapper input:dir(rtl) {
+ background-position-x: right 16px; }
+ body:not(.inline-onboarding) .fixed-search .search-wrapper .search-handoff-button .fake-caret {
+ top: 14px; }
+ body:not(.inline-onboarding) .fixed-search .search-wrapper .logo-and-wordmark {
+ display: none; }
+ body:not(.inline-onboarding) .fixed-search.newtab-experience main {
+ padding-top: 124px; }
+ body:not(.inline-onboarding) .fixed-search.newtab-experience.visible-logo main {
+ padding-top: 254px; }
+ body:not(.inline-onboarding) .fixed-search.newtab-experience .search-wrapper {
+ border-bottom: solid 1px var(--newtab-seperator-line-color);
+ padding: 27px 0; }
+ body:not(.inline-onboarding) .fixed-search.newtab-experience .search-wrapper .search-inner-wrapper {
+ min-height: 45px; }
+ body:not(.inline-onboarding) .fixed-search.newtab-experience .search-wrapper input {
+ background-position-x: 16px;
+ background-size: 24px; }
+ body:not(.inline-onboarding) .fixed-search.newtab-experience .search-wrapper input:dir(rtl) {
+ background-position-x: right 16px; }
+ body:not(.inline-onboarding) .fixed-search .search-handoff-button {
+ background-position-x: 12px;
+ background-size: 24px; }
+ body:not(.inline-onboarding) .fixed-search .search-handoff-button:dir(rtl) {
+ background-position-x: right 12px; }
+ body:not(.inline-onboarding) .fixed-search .search-handoff-button .fake-caret {
+ top: 10px; } }
+
+.contentSearchSuggestionTable {
+ background-color: var(--newtab-search-dropdown-color);
+ border: 0;
+ box-shadow: 0 5px 10px rgba(0, 0, 0, 0.3), 0 0 0 1px rgba(0, 0, 0, 0.2);
+ transform: translateY(4px); }
+ .contentSearchSuggestionTable .contentSearchHeader {
+ background-color: var(--newtab-search-dropdown-header-color);
+ color: var(--newtab-text-secondary-color); }
+ .contentSearchSuggestionTable .contentSearchHeader,
+ .contentSearchSuggestionTable .contentSearchSettingsButton {
+ border-color: var(--newtab-border-secondary-color); }
+ .contentSearchSuggestionTable .contentSearchSuggestionsList {
+ border: 0; }
+ .contentSearchSuggestionTable .contentSearchOneOffsTable {
+ background-color: var(--newtab-search-dropdown-header-color);
+ border-top: solid 1px var(--newtab-border-secondary-color); }
+ .contentSearchSuggestionTable .contentSearchSearchWithHeaderSearchText {
+ color: var(--newtab-text-primary-color); }
+ .contentSearchSuggestionTable .contentSearchSuggestionsContainer {
+ background-color: var(--newtab-search-dropdown-color); }
+ .contentSearchSuggestionTable .contentSearchSuggestionRow.selected {
+ background: var(--newtab-element-hover-color);
+ color: var(--newtab-text-primary-color); }
+ .contentSearchSuggestionTable .contentSearchSuggestionRow.selected:active {
+ background: var(--newtab-element-active-color); }
+ .contentSearchSuggestionTable .contentSearchSuggestionRow.selected .historyIcon {
+ fill: var(--newtab-icon-secondary-color); }
+ .contentSearchSuggestionTable .contentSearchOneOffsTable .contentSearchSuggestionsContainer {
+ background-color: var(--newtab-search-dropdown-header-color); }
+ .contentSearchSuggestionTable .contentSearchOneOffItem {
+ background-image: none;
+ border-image: linear-gradient(transparent 18%, var(--newtab-border-secondary-color) 18%, var(--newtab-border-secondary-color) 82%, transparent 82%) 1;
+ border-inline-end: 1px solid;
+ position: relative; }
+ .contentSearchSuggestionTable .contentSearchOneOffItem.selected {
+ background: var(--newtab-element-hover-color); }
+ .contentSearchSuggestionTable .contentSearchOneOffItem:active {
+ background: var(--newtab-element-active-color); }
+ .contentSearchSuggestionTable .contentSearchSettingsButton:hover {
+ background: var(--newtab-element-hover-color);
+ color: var(--newtab-text-primary-color); }
+
+.contentSearchHeaderRow > td > img,
+.contentSearchSuggestionRow > td > .historyIcon {
+ margin-inline-start: 7px;
+ margin-inline-end: 15px; }
+
+.context-menu {
+ background: var(--newtab-contextmenu-background-color);
+ border-radius: 5px;
+ box-shadow: 0 5px 10px rgba(0, 0, 0, 0.3), 0 0 0 1px rgba(0, 0, 0, 0.2);
+ display: block;
+ font-size: 14px;
+ margin-inline-start: 5px;
+ inset-inline-start: 100%;
+ position: absolute;
+ top: 6.75px;
+ z-index: 8; }
+ .context-menu > ul {
+ list-style: none;
+ margin: 0;
+ padding: 5px 0; }
+ .context-menu > ul > li {
+ margin: 0;
+ width: 100%; }
+ .context-menu > ul > li.separator {
+ border-bottom: 1px solid var(--newtab-border-secondary-color);
+ margin: 5px 0; }
+ .context-menu > ul > li > a,
+ .context-menu > ul > li > button {
+ align-items: center;
+ color: inherit;
+ cursor: pointer;
+ display: flex;
+ width: 100%;
+ line-height: 16px;
+ outline: none;
+ border: 0;
+ padding: 3px 12px;
+ white-space: nowrap; }
+ .context-menu > ul > li > a:is(:focus, :hover),
+ .context-menu > ul > li > button:is(:focus, :hover) {
+ background: var(--newtab-element-hover-color); }
+ .context-menu > ul > li > a:active,
+ .context-menu > ul > li > button:active {
+ background: var(--newtab-element-active-color); }
+ .context-menu > ul > li > a.disabled,
+ .context-menu > ul > li > button.disabled {
+ opacity: 0.4;
+ pointer-events: none; }
+
+.confirmation-dialog .modal {
+ box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.1);
+ left: 0;
+ margin: auto;
+ position: fixed;
+ right: 0;
+ top: 20%;
+ width: 400px; }
+
+.confirmation-dialog section {
+ margin: 0; }
+
+.confirmation-dialog .modal-message {
+ display: flex;
+ padding: 16px;
+ padding-bottom: 0; }
+ .confirmation-dialog .modal-message p {
+ margin: 0;
+ margin-bottom: 16px; }
+
+.confirmation-dialog .actions {
+ border: 0;
+ display: flex;
+ flex-wrap: nowrap;
+ padding: 0 16px; }
+ .confirmation-dialog .actions button {
+ margin-inline-end: 16px;
+ padding-inline-end: 18px;
+ padding-inline-start: 18px;
+ white-space: normal;
+ width: 50%; }
+ .confirmation-dialog .actions button.done {
+ margin-inline-end: 0;
+ margin-inline-start: 0; }
+
+.confirmation-dialog .icon {
+ margin-inline-end: 16px; }
+
+.modal-overlay {
+ background: var(--newtab-overlay-color);
+ height: 100%;
+ left: 0;
+ position: fixed;
+ top: 0;
+ width: 100%;
+ z-index: 11001; }
+
+.modal {
+ background: var(--newtab-modal-color);
+ border: 1px solid var(--newtab-border-secondary-color);
+ border-radius: 5px;
+ font-size: 15px;
+ z-index: 11002; }
+
+.customize-menu {
+ color: var(--customize-menu-primary-text-color);
+ background-color: var(--customize-menu-background);
+ width: 432px;
+ height: 100%;
+ position: fixed;
+ inset-block: 0;
+ inset-inline-end: 0;
+ z-index: 1001;
+ padding: 16px;
+ transition: transform 250ms cubic-bezier(0.46, 0.03, 0.52, 0.96);
+ overflow: auto;
+ transform: translateX(435px);
+ visibility: hidden;
+ cursor: default; }
+ .customize-menu:dir(rtl) {
+ transform: translateX(-435px); }
+ .customize-menu.customize-animate-enter-done {
+ transform: translateX(0); }
+ .customize-menu.customize-animate-enter-done, .customize-menu.customize-animate-enter-active, .customize-menu.customize-animate-enter {
+ box-shadow: 0 0 64px var(--customize-menu-first-shadow), 0 0 24px var(--customize-menu-second-shadow);
+ transition: transform 250ms cubic-bezier(0.46, 0.03, 0.52, 0.96), visibility 1ms;
+ visibility: visible; }
+ .customize-menu.customize-animate-exit-active, .customize-menu.customize-animate-exit {
+ box-shadow: 0 0 64px var(--customize-menu-first-shadow), 0 0 24px var(--customize-menu-second-shadow);
+ transition: transform 250ms cubic-bezier(0.46, 0.03, 0.52, 0.96), visibility 1ms 250ms;
+ visibility: visible; }
+ .customize-menu.customize-animate-exit-done {
+ transform: translateX(435px);
+ transition: transform 250ms cubic-bezier(0.46, 0.03, 0.52, 0.96), visibility 1ms 250ms; }
+ .customize-menu.customize-animate-exit-done:dir(rtl) {
+ transform: translateX(-435px); }
+ .customize-menu .close-button {
+ margin-inline-start: auto;
+ margin-bottom: 28px;
+ white-space: nowrap;
+ display: block;
+ background-color: var(--customize-menu-secondary-action-background);
+ padding: 8px 10px;
+ border: 1px solid rgba(0, 0, 0, 0.15);
+ border-radius: 4px;
+ color: var(--customize-menu-primary-text-color);
+ font-size: 13px;
+ font-weight: 600; }
+ .customize-menu .close-button:hover {
+ background-color: var(--customize-menu-secondary-action-background-hover); }
+ .customize-menu .close-button:hover:active {
+ background-color: var(--customize-menu-secondary-action-background-active); }
+
+.grid-skip {
+ display: contents; }
+
+.home-section {
+ display: grid;
+ grid-template-columns: 1fr;
+ grid-template-rows: repeat(4, auto);
+ grid-row-gap: 32px;
+ padding: 0 16px; }
+ .home-section .section {
+ display: grid;
+ grid-template-rows: auto;
+ grid-template-columns: auto 26px; }
+ .home-section .section > div {
+ grid-area: 1; }
+ .home-section .section .title {
+ grid-column: 1 / -1;
+ margin: 0;
+ font-weight: 600;
+ font-size: 16px;
+ margin-bottom: 10px; }
+ .home-section .section .subtitle {
+ margin: 0;
+ font-size: 14px; }
+ .home-section .section .sponsored {
+ font-size: 14px;
+ margin-inline-start: 5px; }
+ .home-section .section .check-wrapper {
+ position: relative; }
+ .home-section .section .sponsored-checkbox {
+ margin-inline-start: 2px;
+ width: 16px;
+ height: 16px;
+ vertical-align: middle;
+ border: 1px solid rgba(0, 0, 0, 0.15);
+ box-sizing: border-box;
+ border-radius: 4px;
+ appearance: none;
+ background-color: var(--newtab-primary-action-background-off); }
+ .home-section .section .sponsored-checkbox:checked {
+ -moz-context-properties: fill;
+ fill: var(--customize-menu-check-fill);
+ background: url("chrome://global/skin/icons/check.svg") center no-repeat;
+ background-color: var(--newtab-primary-action-background);
+ background-size: 10px; }
+ .home-section .section .sponsored-checkbox:active + .checkmark {
+ fill: rgba(0, 0, 0, 0.15); }
+ .home-section .section .selector {
+ color: var(--customize-menu-primary-text-color);
+ width: 118px;
+ display: block;
+ border: 1px solid var(--customize-menu-line-color);
+ border-radius: 4px;
+ appearance: none;
+ padding-block: 7px;
+ padding-inline: 10px 13px;
+ margin-inline-start: 2px;
+ -moz-context-properties: fill;
+ fill: var(--customize-menu-primary-text-color);
+ background: url("chrome://activity-stream/content/data/content/assets/glyph-arrowhead-down-12.svg") right no-repeat;
+ background-size: 8px;
+ background-origin: content-box;
+ background-color: var(--customize-menu-background); }
+ .home-section .section .selector:dir(rtl) {
+ background-position-x: left; }
+ .home-section .section .switch {
+ position: relative;
+ display: inline-block;
+ width: 26px;
+ height: 16px;
+ grid-column: 2;
+ margin-top: 2px; }
+ .home-section .section .switch input {
+ opacity: 0;
+ width: 0;
+ height: 0; }
+ .home-section .section .slider {
+ position: absolute;
+ inset: 0;
+ transition: transform 250ms;
+ border-radius: 13px;
+ border: 1px solid rgba(0, 0, 0, 0.15);
+ background-color: var(--newtab-primary-action-background-off); }
+ .home-section .section .slider::before {
+ position: absolute;
+ content: '';
+ height: 8px;
+ width: 8px;
+ inset-inline-start: 3px;
+ bottom: 3px;
+ background-color: var(--customize-menu-primary-action-text);
+ transition: transform 250ms;
+ border-radius: 50%;
+ outline: 1px solid rgba(0, 0, 0, 0.15);
+ -moz-outline-radius: 11px; }
+ .home-section .section .switch input:focus-visible + .slider {
+ border: 1px solid var(--newtab-focus-border-selected);
+ outline: 0;
+ box-shadow: 0 0 0 2px var(--newtab-focus-outline); }
+ .home-section .section .switch input:not(:checked):focus-visible + .slider {
+ border: 1px solid var(--newtab-focus-border); }
+ .home-section .section input:checked + .slider {
+ background-color: var(--newtab-primary-action-background); }
+ .home-section .section input:checked + .slider::before {
+ transform: translateX(10px); }
+ .home-section .section input:checked + .slider:dir(rtl)::before {
+ transform: translateX(-10px); }
+ .home-section .section .more-info-top-wrapper,
+ .home-section .section .more-info-pocket-wrapper {
+ margin-inline-start: -2px;
+ overflow: hidden;
+ transition: max-height 250ms cubic-bezier(0.82, 0.085, 0.395, 0.895); }
+ .home-section .section .more-info-top-wrapper.shrink,
+ .home-section .section .more-info-pocket-wrapper.shrink {
+ max-height: 0; }
+ .home-section .section .more-info-top-wrapper .more-information,
+ .home-section .section .more-info-pocket-wrapper .more-information {
+ padding-top: 12px;
+ position: relative;
+ transition: top 250ms cubic-bezier(0.82, 0.085, 0.395, 0.895); }
+ .home-section .section .more-info-top-wrapper .more-information.expand,
+ .home-section .section .more-info-pocket-wrapper .more-information.expand {
+ top: 0; }
+ .home-section .section .more-info-top-wrapper {
+ max-height: 78px; }
+ .home-section .section .more-info-top-wrapper .more-information {
+ top: -77px; }
+ .home-section .section .more-info-top-wrapper .check-wrapper {
+ margin-top: 10px; }
+ .home-section .section .more-info-pocket-wrapper {
+ max-height: 35px; }
+ .home-section .section .more-info-pocket-wrapper .more-information {
+ top: -35px; }
+ .home-section .divider {
+ border-top: 1px var(--customize-menu-seperator-line-color) solid;
+ margin: 0 -16px; }
+ .home-section .external-link {
+ font-size: 14px;
+ cursor: pointer;
+ border: 1px solid transparent;
+ border-radius: 4px;
+ -moz-context-properties: fill;
+ fill: var(--customize-menu-primary-text-color);
+ background: url("chrome://global/skin/icons/settings.svg") left no-repeat;
+ background-size: 16px;
+ padding-inline-start: 21px;
+ margin-bottom: 20px; }
+ .home-section .external-link:dir(rtl) {
+ background-position-x: right; }
+ .home-section .external-link:hover {
+ text-decoration: underline; }
+
+.home-section .section .sponsored-checkbox:focus-visible,
+.selector:focus-visible,
+.external-link:focus-visible,
+.close-button:focus-visible {
+ border: 1px solid var(--newtab-focus-border);
+ outline: 0;
+ box-shadow: 0 0 0 2px var(--newtab-focus-outline); }
+
+.outer-wrapper.newtab-experience .card-outer {
+ border-radius: 8px; }
+ .outer-wrapper.newtab-experience .card-outer:is(:focus):not(.placeholder) {
+ border: 0;
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-focus-outline), 0 0 0 1px var(--newtab-focus-border);
+ transition: none; }
+ .outer-wrapper.newtab-experience .card-outer:hover {
+ box-shadow: none;
+ transition: none; }
+ .outer-wrapper.newtab-experience .card-outer .card {
+ box-shadow: 0 3px 8px var(--newtab-card-first-shadow), 0 0 2px var(--newtab-card-second-shadow);
+ border-radius: 8px; }
+ .outer-wrapper.newtab-experience .card-outer .card-preview-image-outer {
+ border-radius: 8px 8px 0 0; }
+ .outer-wrapper.newtab-experience .card-outer .context-menu-button:is(:active, :focus) {
+ outline: 0;
+ fill: var(--newtab-primary-action-background);
+ border: 1px solid var(--newtab-primary-action-background); }
+ .outer-wrapper.newtab-experience .card-outer > a:is(:focus) .card {
+ border: 0;
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-focus-outline), 0 0 0 1px var(--newtab-focus-border); }
+
+.outer-wrapper:not(.newtab-experience) .card-outer:is(:hover, :focus, .active):not(.placeholder) {
+ box-shadow: 0 0 0 5px var(--newtab-card-active-outline-color);
+ transition: box-shadow 150ms; }
+
+.card-outer {
+ background: var(--newtab-card-background-color);
+ border-radius: 3px;
+ display: inline-block;
+ height: 266px;
+ margin-inline-end: 32px;
+ position: relative;
+ width: 100%; }
+ .card-outer .context-menu-button {
+ background-clip: padding-box;
+ background-color: var(--newtab-contextmenu-button-color);
+ background-image: url("chrome://global/skin/icons/more.svg");
+ background-position: 55%;
+ border: 1px solid var(--newtab-border-primary-color);
+ border-radius: 100%;
+ box-shadow: 0 2px rgba(12, 12, 13, 0.1);
+ cursor: pointer;
+ fill: var(--newtab-icon-primary-color);
+ height: 27px;
+ inset-inline-end: -13.5px;
+ opacity: 0;
+ position: absolute;
+ top: -13.5px;
+ transform: scale(0.25);
+ transition-duration: 150ms;
+ transition-property: transform, opacity;
+ width: 27px; }
+ .card-outer .context-menu-button:is(:active, :focus) {
+ opacity: 1;
+ transform: scale(1); }
+ .card-outer.placeholder {
+ background: transparent; }
+ .card-outer.placeholder .card {
+ box-shadow: inset 0 0 0 1px var(--newtab-inner-box-shadow-color); }
+ .card-outer.placeholder .card-preview-image-outer,
+ .card-outer.placeholder .card-context {
+ display: none; }
+ .card-outer .card {
+ border-radius: 3px;
+ box-shadow: var(--newtab-card-shadow);
+ height: 100%; }
+ .card-outer > a {
+ color: inherit;
+ display: block;
+ height: 100%;
+ outline: none;
+ position: absolute;
+ width: 100%; }
+ .card-outer > a:is(.active, :focus) .card {
+ box-shadow: 0 0 0 5px var(--newtab-card-active-outline-color);
+ transition: box-shadow 150ms; }
+ .card-outer > a:is(.active, :focus) .card-title {
+ color: var(--newtab-link-primary-color); }
+ .card-outer:is(:hover, :focus, .active):not(.placeholder) {
+ outline: none; }
+ .card-outer:is(:hover, :focus, .active):not(.placeholder) .context-menu-button {
+ opacity: 1;
+ transform: scale(1);
+ transition-delay: 333ms; }
+ .card-outer:is(:hover, :focus, .active):not(.placeholder) .card-title {
+ color: var(--newtab-link-primary-color); }
+ .card-outer:is(:hover, :focus, .active):not(.placeholder) .alternate ~ .card-host-name {
+ display: none; }
+ .card-outer:is(:hover, :focus, .active):not(.placeholder) .card-host-name.alternate {
+ display: block; }
+ .card-outer .card-preview-image-outer {
+ background-color: #D7D7DB;
+ border-radius: 3px 3px 0 0;
+ height: 122px;
+ overflow: hidden;
+ position: relative; }
+ [lwt-newtab-brighttext] .card-outer .card-preview-image-outer {
+ background-color: #4A4A4F; }
+ .card-outer .card-preview-image-outer::after {
+ border-bottom: 1px solid var(--newtab-card-hairline-color);
+ bottom: 0;
+ content: '';
+ position: absolute;
+ width: 100%; }
+ .card-outer .card-preview-image-outer .card-preview-image {
+ background-position: center;
+ background-repeat: no-repeat;
+ background-size: cover;
+ height: 100%;
+ opacity: 0;
+ transition: opacity 1s cubic-bezier(0.07, 0.95, 0, 1);
+ width: 100%; }
+ .card-outer .card-preview-image-outer .card-preview-image.loaded {
+ opacity: 1; }
+ .card-outer .card-details {
+ padding: 15px 16px 12px; }
+ .card-outer .card-text {
+ max-height: 78px;
+ overflow: hidden; }
+ .card-outer .card-text.no-host-name, .card-outer .card-text.no-context {
+ max-height: 97px; }
+ .card-outer .card-text.no-host-name.no-context {
+ max-height: 116px; }
+ .card-outer .card-text:not(.no-description) .card-title {
+ max-height: 57px;
+ overflow: hidden; }
+ .card-outer .card-host-name {
+ color: var(--newtab-text-secondary-color);
+ font-size: 10px;
+ overflow: hidden;
+ padding-bottom: 4px;
+ text-overflow: ellipsis;
+ text-transform: uppercase;
+ white-space: nowrap; }
+ .card-outer .card-host-name.alternate {
+ display: none; }
+ .card-outer .card-title {
+ font-size: 14px;
+ font-weight: 600;
+ line-height: 19px;
+ margin: 0 0 2px;
+ word-wrap: break-word; }
+ .card-outer .card-description {
+ font-size: 12px;
+ line-height: 19px;
+ margin: 0;
+ overflow: hidden;
+ word-wrap: break-word; }
+ .card-outer .card-context {
+ bottom: 0;
+ color: var(--newtab-text-secondary-color);
+ display: flex;
+ font-size: 11px;
+ inset-inline-start: 0;
+ padding: 9px 16px 9px 14px;
+ position: absolute; }
+ .card-outer .card-context-icon {
+ fill: var(--newtab-text-secondary-color);
+ height: 22px;
+ margin-inline-end: 6px; }
+ .card-outer .card-context-label {
+ flex-grow: 1;
+ line-height: 22px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap; }
+
+@media (min-width: 1122px) {
+ .normal-cards .card-outer {
+ height: 370px; }
+ .normal-cards .card-outer .card-preview-image-outer {
+ height: 155px; }
+ .normal-cards .card-outer .card-details {
+ padding: 13px 16px 12px; }
+ .normal-cards .card-outer .card-text {
+ max-height: 140px; }
+ .normal-cards .card-outer .card-host-name {
+ font-size: 12px;
+ padding-bottom: 5px; }
+ .normal-cards .card-outer .card-title {
+ font-size: 17px;
+ line-height: 23px;
+ margin-bottom: 0; }
+ .normal-cards .card-outer .card-text:not(.no-description) .card-title {
+ max-height: 69px; }
+ .normal-cards .card-outer .card-description {
+ font-size: 15px;
+ line-height: 23px; }
+ .normal-cards .card-outer .card-context {
+ bottom: 4px;
+ font-size: 14px; } }
+
+.compact-cards .card-outer {
+ height: 160px; }
+ .compact-cards .card-outer .card-preview-image-outer {
+ height: 108px; }
+ .compact-cards .card-outer .card-details {
+ padding: 12px 16px; }
+ .compact-cards .card-outer .card-host-name {
+ line-height: 10px; }
+ .compact-cards .card-outer .card-text .card-title,
+ .compact-cards .card-outer .card-text:not(.no-description) .card-title {
+ font-size: 12px;
+ line-height: 13px;
+ max-height: 17px;
+ overflow: hidden;
+ padding: 0 0 4px;
+ text-overflow: ellipsis;
+ white-space: nowrap; }
+ .compact-cards .card-outer .card-description {
+ display: none; }
+ .compact-cards .card-outer .card-context {
+ background-color: var(--newtab-card-background-color);
+ border-radius: 16px;
+ clip-path: inset(-1px -1px 4px);
+ height: 32px;
+ width: 32px;
+ padding: 8px;
+ top: 91px;
+ inset-inline-end: 12px;
+ inset-inline-start: auto; }
+ .compact-cards .card-outer .card-context::after {
+ border: 1px solid var(--newtab-card-hairline-color);
+ border-bottom: 0;
+ border-radius: 17px 17px 0 0;
+ content: '';
+ position: absolute;
+ height: 17px;
+ width: 34px;
+ top: -1px;
+ left: -1px; }
+ .compact-cards .card-outer .card-context .card-context-icon {
+ margin-inline-end: 0;
+ height: 16px;
+ width: 16px; }
+ .compact-cards .card-outer .card-context .card-context-icon.icon-bookmark-added {
+ fill: #0A84FF; }
+ .compact-cards .card-outer .card-context .card-context-icon.icon-download {
+ fill: #12BC00; }
+ .compact-cards .card-outer .card-context .card-context-icon.icon-pocket {
+ fill: #D70022; }
+ .compact-cards .card-outer .card-context .card-context-label {
+ display: none; }
+
+@media not all and (min-width: 1122px) {
+ .compact-cards .hide-for-narrow {
+ display: none; } }
+
+.outer-wrapper.newtab-experience .collapsible-section[data-section-id='topsites'] .section-top-bar {
+ display: none; }
+
+.outer-wrapper.newtab-experience .collapsible-section .click-target-container .click-target span {
+ cursor: default;
+ font-weight: 600;
+ font-size: 17px;
+ color: var(--newtab-background-primary-text-color); }
+
+.outer-wrapper:not(.newtab-experience) .collapsible-section .section-title span {
+ vertical-align: middle; }
+
+.collapsible-section {
+ padding: 10px 25px;
+ transition-delay: 100ms;
+ transition-duration: 100ms;
+ transition-property: background-color; }
+ .collapsible-section .section-title {
+ font-size: 13px;
+ font-weight: bold;
+ margin: 0; }
+ .collapsible-section .section-title.grey-title,
+ .collapsible-section .section-title span {
+ color: var(--newtab-section-header-text-color);
+ display: inline-block;
+ fill: var(--newtab-section-header-text-color); }
+ .collapsible-section .section-title.grey-title {
+ vertical-align: middle; }
+ .collapsible-section .section-title .click-target-container {
+ vertical-align: top; }
+ @media (max-width: 609px) {
+ .collapsible-section .section-title .click-target-container {
+ display: block; }
+ .collapsible-section .section-title .click-target-container .learn-more-link-wrapper {
+ display: block;
+ text-align: center; }
+ .collapsible-section .section-title .click-target-container .learn-more-link-wrapper .learn-more-link {
+ margin-inline-start: 0; } }
+ .collapsible-section .section-title .click-target-container .click-target {
+ white-space: nowrap;
+ cursor: pointer; }
+ .collapsible-section .section-title .collapsible-arrow {
+ margin-inline-start: 8px;
+ margin-top: -1px; }
+ .collapsible-section .section-top-bar {
+ min-height: 19px;
+ margin-bottom: 13px;
+ position: relative; }
+ .collapsible-section .section-top-bar .context-menu-button {
+ background: url("chrome://global/skin/icons/more.svg") no-repeat right center;
+ border: 0;
+ cursor: pointer;
+ fill: var(--newtab-section-header-text-color);
+ height: 100%;
+ inset-inline-end: 0;
+ opacity: 0;
+ position: absolute;
+ top: 0;
+ transition-duration: 200ms;
+ transition-property: opacity;
+ width: 27px; }
+ .collapsible-section .section-top-bar .context-menu-button:is(:active, :focus, :hover) {
+ fill: var(--newtab-section-header-text-color);
+ opacity: 1; }
+ .collapsible-section .section-top-bar .context-menu {
+ top: 16px; }
+ @media (max-width: 1458px) {
+ .collapsible-section .section-top-bar .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+ .collapsible-section:hover .section-top-bar .context-menu-button, .collapsible-section.active .section-top-bar .context-menu-button {
+ opacity: 1; }
+ .collapsible-section.active {
+ background: var(--newtab-element-hover-color);
+ border-radius: 4px; }
+ .collapsible-section.active .section-top-bar .context-menu-button {
+ fill: var(--newtab-section-active-contextmenu-color); }
+ .collapsible-section .learn-more-link {
+ font-size: 11px;
+ margin-inline-start: 12px; }
+ .collapsible-section .learn-more-link a {
+ color: var(--newtab-link-secondary-color); }
+ .collapsible-section .section-body-fallback {
+ height: 266px; }
+ .collapsible-section .section-body {
+ margin: 0 -7px;
+ padding: 0 7px; }
+ .collapsible-section .section-body.animating {
+ overflow: hidden;
+ pointer-events: none; }
+ .collapsible-section.animation-enabled .section-title .collapsible-arrow {
+ transition: transform 0.5s cubic-bezier(0.07, 0.95, 0, 1); }
+ .collapsible-section.animation-enabled .section-body {
+ transition: max-height 0.5s cubic-bezier(0.07, 0.95, 0, 1); }
+ .collapsible-section.collapsed .section-body {
+ max-height: 0;
+ overflow: hidden; }
+ @media (min-width: 610px) and (max-width: 865px) {
+ .collapsible-section[data-section-id='topstories'] .card-outer:first-child {
+ display: none; } }
+
+.asrouter-toggle {
+ position: fixed;
+ top: 50px;
+ inset-inline-end: 15px;
+ border: 0;
+ background: none;
+ z-index: 1;
+ border-radius: 2px; }
+ .asrouter-toggle .icon-devtools {
+ background-image: url("chrome://browser/skin/developer.svg");
+ padding: 15px; }
+ .asrouter-toggle:dir(rtl) {
+ transform: scaleX(-1); }
+ .asrouter-toggle:hover {
+ background: var(--newtab-element-hover-color); }
+ .asrouter-toggle.expanded {
+ background: rgba(0, 0, 0, 0.2); }
+
+.asrouter-admin {
+ position: fixed;
+ top: 0;
+ inset-inline-start: 0;
+ width: 100%;
+ background: var(--newtab-background-color);
+ height: 100%;
+ overflow-y: scroll;
+ margin: 0 auto;
+ font-size: 14px;
+ padding-inline-start: 240px;
+ color: var(--newtab-text-primary-color); }
+ .asrouter-admin.collapsed {
+ display: none; }
+ .asrouter-admin .sidebar {
+ inset-inline-start: 0;
+ position: fixed;
+ width: 240px;
+ padding: 30px 20px; }
+ .asrouter-admin .sidebar ul {
+ margin: 0;
+ padding: 0;
+ list-style: none; }
+ .asrouter-admin .sidebar li a {
+ padding: 10px 34px;
+ display: block;
+ color: var(--lwt-sidebar-text-color); }
+ .asrouter-admin .sidebar li a:hover {
+ background: var(--newtab-textbox-background-color); }
+ .asrouter-admin h1 {
+ font-weight: 200;
+ font-size: 32px; }
+ .asrouter-admin h2 .button,
+ .asrouter-admin p .button {
+ font-size: 14px;
+ padding: 6px 12px;
+ margin-inline-start: 5px;
+ margin-bottom: 0; }
+ .asrouter-admin .general-textarea {
+ direction: ltr;
+ width: 740px;
+ height: 500px;
+ overflow: auto;
+ resize: none;
+ border-radius: 4px;
+ display: flex; }
+ .asrouter-admin .wnp-textarea {
+ direction: ltr;
+ width: 740px;
+ height: 500px;
+ overflow: auto;
+ resize: none;
+ border-radius: 4px;
+ display: flex; }
+ .asrouter-admin .json-button {
+ display: inline-flex;
+ font-size: 10px;
+ padding: 4px 10px;
+ margin-bottom: 6px;
+ margin-inline-end: 4px; }
+ .asrouter-admin .json-button:hover {
+ background-color: rgba(237, 237, 240, 0.6);
+ box-shadow: none; }
+ .asrouter-admin table {
+ border-collapse: collapse;
+ width: 100%; }
+ .asrouter-admin table.minimal-table {
+ border-collapse: collapse;
+ border: 1px solid var(--newtab-border-secondary-color); }
+ .asrouter-admin table.minimal-table td {
+ padding: 8px; }
+ .asrouter-admin table.minimal-table td:first-child {
+ width: 1%;
+ white-space: nowrap; }
+ .asrouter-admin table.minimal-table td:not(:first-child) {
+ font-family: "SF Mono", "Monaco", "Inconsolata", "Fira Mono", "Droid Sans Mono", "Source Code Pro", monospace; }
+ .asrouter-admin table.errorReporting tr {
+ border: 1px solid var(--newtab-textbox-background-color); }
+ .asrouter-admin table.errorReporting td {
+ padding: 4px; }
+ .asrouter-admin table.errorReporting td[rowspan] {
+ border: 1px solid var(--newtab-textbox-background-color); }
+ .asrouter-admin .sourceLabel {
+ background: var(--newtab-textbox-background-color);
+ padding: 2px 5px;
+ border-radius: 3px; }
+ .asrouter-admin .sourceLabel.isDisabled {
+ background: rgba(215, 0, 34, 0.3);
+ color: #D70022; }
+ .asrouter-admin .message-item:first-child td {
+ border-top: 1px solid var(--newtab-border-secondary-color); }
+ .asrouter-admin .message-item td {
+ vertical-align: top;
+ padding: 8px;
+ border-bottom: 1px solid var(--newtab-border-secondary-color); }
+ .asrouter-admin .message-item td.min {
+ width: 1%;
+ white-space: nowrap; }
+ .asrouter-admin .message-item td.message-summary {
+ width: 60%; }
+ .asrouter-admin .message-item td.button-column {
+ width: 15%; }
+ .asrouter-admin .message-item td:first-child {
+ border-inline-start: 1px solid var(--newtab-border-secondary-color); }
+ .asrouter-admin .message-item td:last-child {
+ border-inline-end: 1px solid var(--newtab-border-secondary-color); }
+ .asrouter-admin .message-item.blocked .message-id,
+ .asrouter-admin .message-item.blocked .message-summary {
+ opacity: 0.5; }
+ .asrouter-admin .message-item.blocked .message-id {
+ opacity: 0.5; }
+ .asrouter-admin .message-item .message-id {
+ font-family: "SF Mono", "Monaco", "Inconsolata", "Fira Mono", "Droid Sans Mono", "Source Code Pro", monospace;
+ font-size: 12px; }
+ .asrouter-admin .providerUrl {
+ font-size: 12px; }
+ .asrouter-admin pre {
+ background: var(--newtab-textbox-background-color);
+ margin: 0;
+ padding: 8px;
+ font-size: 12px;
+ max-width: 750px;
+ overflow: auto;
+ font-family: "SF Mono", "Monaco", "Inconsolata", "Fira Mono", "Droid Sans Mono", "Source Code Pro", monospace; }
+ .asrouter-admin .errorState {
+ border: 1px solid #D70022; }
+ .asrouter-admin .helpLink {
+ padding: 10px;
+ display: flex;
+ background: rgba(0, 0, 0, 0.1);
+ border-radius: 3px; }
+ .asrouter-admin .helpLink a {
+ text-decoration: underline; }
+ .asrouter-admin .ds-component {
+ margin-bottom: 20px; }
+ .asrouter-admin .modalOverlayInner {
+ height: 80%; }
+ .asrouter-admin .clearButton {
+ border: 0;
+ padding: 4px;
+ border-radius: 4px;
+ display: flex; }
+ .asrouter-admin .clearButton:hover {
+ background: var(--newtab-element-hover-color); }
+ .asrouter-admin .collapsed {
+ display: none; }
+ .asrouter-admin .icon {
+ display: inline-table;
+ cursor: pointer;
+ width: 18px;
+ height: 18px; }
+
+.pocket-logged-in-cta {
+ font-size: 13px;
+ margin-inline-end: 20px;
+ display: flex;
+ align-items: flex-start; }
+ .pocket-logged-in-cta .pocket-cta-button {
+ white-space: nowrap;
+ background: #0060DF;
+ letter-spacing: -0.34px;
+ color: #FFF;
+ border-radius: 4px;
+ cursor: pointer;
+ max-width: 130px;
+ margin-top: -1px;
+ min-height: 18px;
+ padding: 0 8px;
+ display: inline-flex;
+ justify-content: center;
+ align-items: center;
+ font-size: 11px;
+ margin-inline-end: 10px; }
+ .pocket-logged-in-cta .cta-text {
+ font-weight: normal;
+ font-size: 13px;
+ line-height: 1.230769231; }
+ .pocket-logged-in-cta .pocket-cta-button,
+ .pocket-logged-in-cta .cta-text {
+ vertical-align: top; }
+
+.more-recommendations {
+ display: flex;
+ align-items: center;
+ white-space: nowrap;
+ line-height: 1.230769231; }
+ .more-recommendations::after {
+ background: url("chrome://activity-stream/content/data/content/assets/topic-show-more-12.svg") no-repeat center center;
+ content: '';
+ -moz-context-properties: fill;
+ display: inline-block;
+ fill: var(--newtab-link-secondary-color);
+ height: 16px;
+ margin-inline-start: 5px;
+ vertical-align: top;
+ width: 12px; }
+ .more-recommendations:dir(rtl)::after {
+ transform: scaleX(-1); }
+
+.discovery-stream.ds-layout {
+ --gridColumnGap: 48px;
+ --gridRowGap: 24px;
+ grid-template-columns: repeat(12, 1fr);
+ grid-column-gap: var(--gridColumnGap);
+ grid-row-gap: var(--gridRowGap);
+ margin: 0 auto; }
+ .discovery-stream.ds-layout .ds-column-12 {
+ grid-column-start: auto;
+ grid-column-end: span 12; }
+ .discovery-stream.ds-layout .ds-column-11 {
+ grid-column-start: auto;
+ grid-column-end: span 11; }
+ .discovery-stream.ds-layout .ds-column-10 {
+ grid-column-start: auto;
+ grid-column-end: span 10; }
+ .discovery-stream.ds-layout .ds-column-9 {
+ grid-column-start: auto;
+ grid-column-end: span 9; }
+ .discovery-stream.ds-layout .ds-column-8 {
+ grid-column-start: auto;
+ grid-column-end: span 8; }
+ .discovery-stream.ds-layout .ds-column-7 {
+ grid-column-start: auto;
+ grid-column-end: span 7; }
+ .discovery-stream.ds-layout .ds-column-6 {
+ grid-column-start: auto;
+ grid-column-end: span 6; }
+ .discovery-stream.ds-layout .ds-column-5 {
+ grid-column-start: auto;
+ grid-column-end: span 5; }
+ .discovery-stream.ds-layout .ds-column-4 {
+ grid-column-start: auto;
+ grid-column-end: span 4; }
+ .discovery-stream.ds-layout .ds-column-3 {
+ grid-column-start: auto;
+ grid-column-end: span 3; }
+ .discovery-stream.ds-layout .ds-column-2 {
+ grid-column-start: auto;
+ grid-column-end: span 2; }
+ .discovery-stream.ds-layout .ds-column-1 {
+ grid-column-start: auto;
+ grid-column-end: span 1; }
+ .discovery-stream.ds-layout .ds-column-grid {
+ display: grid;
+ grid-row-gap: var(--gridRowGap); }
+ .discovery-stream.ds-layout .ds-column-grid > div:empty {
+ display: none; }
+
+.ds-header {
+ margin: 8px 0; }
+ .ds-header .ds-context {
+ font-weight: 400; }
+
+.ds-header,
+.ds-layout .section-title span {
+ color: #737373;
+ font-size: 13px;
+ font-weight: 600;
+ line-height: 20px; }
+ [lwt-newtab-brighttext] .ds-header, [lwt-newtab-brighttext]
+ .ds-layout .section-title span {
+ color: #D7D7DB; }
+ .ds-header .icon,
+ .ds-layout .section-title span .icon {
+ fill: var(--newtab-text-secondary-color); }
+
+.collapsible-section.ds-layout {
+ margin: auto; }
+ .collapsible-section.ds-layout .section-top-bar .learn-more-link a {
+ color: var(--newtab-link-primary-color);
+ font-weight: normal; }
+ .collapsible-section.ds-layout .section-top-bar .learn-more-link a:is(:focus, :hover) {
+ text-decoration: underline; }
+
+.outer-wrapper.newtab-experience .ds-card-grid.ds-card-grid-border .ds-card:not(.placeholder) {
+ border-radius: 8px;
+ box-shadow: 0 3px 8px var(--newtab-card-first-shadow), 0 0 2px var(--newtab-card-second-shadow); }
+ .outer-wrapper.newtab-experience .ds-card-grid.ds-card-grid-border .ds-card:not(.placeholder) .img-wrapper .img img {
+ border-radius: 8px 8px 0 0; }
+
+.outer-wrapper.newtab-experience .ds-card-grid .ds-card-link:focus {
+ border: 0;
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-focus-outline), 0 0 0 1px var(--newtab-focus-border);
+ transition: none;
+ border-radius: 8px; }
+
+.ds-card-grid {
+ display: grid;
+ grid-gap: 24px; }
+ .ds-card-grid .ds-card {
+ background: #FFF;
+ border-radius: 4px; }
+ [lwt-newtab-brighttext] .ds-card-grid .ds-card {
+ background: none; }
+ @media (min-width: 866px) {
+ .ds-column-12 .ds-card-grid.ds-card-grid-hero {
+ grid-template-columns: repeat(12, 1fr); }
+ .ds-column-12 .ds-card-grid.ds-card-grid-hero .ds-card:nth-child(1) {
+ grid-column-start: 1;
+ grid-column-end: span 6;
+ grid-row-start: 1;
+ grid-row-end: span 2; }
+ .ds-column-12 .ds-card-grid.ds-card-grid-hero .ds-card:nth-child(1) .excerpt {
+ -webkit-line-clamp: 4; }
+ .ds-column-12 .ds-card-grid.ds-card-grid-hero .ds-card:nth-child(2),
+ .ds-column-12 .ds-card-grid.ds-card-grid-hero .ds-card:nth-child(4) {
+ grid-column-start: 7;
+ grid-column-end: span 3; }
+ .ds-column-12 .ds-card-grid.ds-card-grid-hero .ds-card:nth-child(3),
+ .ds-column-12 .ds-card-grid.ds-card-grid-hero .ds-card:nth-child(5) {
+ grid-column-start: 10;
+ grid-column-end: span 3; }
+ .ds-column-12 .ds-card-grid.ds-card-grid-hero .ds-card:nth-child(n+2):nth-child(-n+5) .excerpt {
+ display: none; }
+ .ds-column-12 .ds-card-grid.ds-card-grid-hero .ds-card:nth-child(n+2):nth-child(-n+5) .meta {
+ padding: 8px; }
+ .ds-column-12 .ds-card-grid.ds-card-grid-hero .ds-card:nth-child(n+2):nth-child(-n+5) .meta .title {
+ font-size: 13px;
+ line-height: 19px; }
+ .ds-column-12 .ds-card-grid.ds-card-grid-hero .ds-card:nth-child(n+2):nth-child(-n+5) .meta .story-sponsored-label {
+ -webkit-line-clamp: none;
+ line-height: 19px; }
+ .ds-column-12 .ds-card-grid.ds-card-grid-hero .ds-card:nth-child(n+6) {
+ grid-column-start: auto;
+ grid-column-end: span 4; } }
+ @media (min-width: 1122px) {
+ .ds-column-12 .ds-card-grid.ds-card-grid-hero .ds-card:nth-child(n+2):nth-child(-n+5) {
+ min-height: 222px; } }
+ .ds-card-grid.ds-card-grid-border .ds-card:not(.placeholder) {
+ box-shadow: 0 1px 4px 0 rgba(12, 12, 13, 0.1); }
+ [lwt-newtab-brighttext] .ds-card-grid.ds-card-grid-border .ds-card:not(.placeholder) {
+ box-shadow: 0 1px 4px rgba(12, 12, 13, 0.1);
+ background: #38383D; }
+ .ds-card-grid.ds-card-grid-border .ds-card:not(.placeholder) .img-wrapper .img img {
+ border-radius: 4px 4px 0 0; }
+ .ds-card-grid.ds-card-grid-no-border .ds-card {
+ background: none; }
+ .ds-card-grid.ds-card-grid-no-border .ds-card .meta {
+ padding: 12px 0; }
+ .ds-column-5 .ds-card-grid,
+ .ds-column-6 .ds-card-grid,
+ .ds-column-7 .ds-card-grid,
+ .ds-column-8 .ds-card-grid {
+ grid-template-columns: repeat(2, 1fr); }
+ .ds-column-9 .ds-card-grid,
+ .ds-column-10 .ds-card-grid,
+ .ds-column-11 .ds-card-grid,
+ .ds-column-12 .ds-card-grid {
+ grid-template-columns: repeat(1, 1fr); }
+ @media (min-width: 610px) {
+ .ds-column-9 .ds-card-grid,
+ .ds-column-10 .ds-card-grid,
+ .ds-column-11 .ds-card-grid,
+ .ds-column-12 .ds-card-grid {
+ grid-template-columns: repeat(2, 1fr); } }
+ @media (min-width: 866px) {
+ .ds-column-9 .ds-card-grid,
+ .ds-column-10 .ds-card-grid,
+ .ds-column-11 .ds-card-grid,
+ .ds-column-12 .ds-card-grid {
+ grid-template-columns: repeat(3, 1fr); } }
+ .ds-column-9 .ds-card-grid .title,
+ .ds-column-10 .ds-card-grid .title,
+ .ds-column-11 .ds-card-grid .title,
+ .ds-column-12 .ds-card-grid .title {
+ font-size: 17px;
+ line-height: 24px; }
+ .ds-column-9 .ds-card-grid .excerpt,
+ .ds-column-10 .ds-card-grid .excerpt,
+ .ds-column-11 .ds-card-grid .excerpt,
+ .ds-column-12 .ds-card-grid .excerpt {
+ font-size: 15px;
+ -webkit-line-clamp: 3;
+ line-height: 24px; }
+ .ds-card-grid.empty {
+ grid-template-columns: auto; }
+
+.ds-dismiss.ds-dismiss-ds-collection .ds-dismiss-button {
+ margin: 15px 0 0;
+ inset-inline-end: 25px; }
+
+.ds-dismiss.ds-dismiss-ds-collection.hovering {
+ background: var(--newtab-element-hover-color); }
+
+.ds-collection-card-grid {
+ padding: 10px 25px 25px;
+ margin: 0 0 20px; }
+ .ds-collection-card-grid .story-footer {
+ display: none; }
+ .ds-collection-card-grid .ds-header {
+ padding: 0 40px 0 0;
+ margin-bottom: 12px; }
+ .ds-collection-card-grid .ds-header .title {
+ color: #0C0C0D;
+ font-weight: 600;
+ font-size: 17px;
+ line-height: 24px; }
+ [lwt-newtab-brighttext] .ds-collection-card-grid .ds-header .title {
+ color: #D7D7DB; }
+ .ds-collection-card-grid .ds-header .ds-context {
+ color: #737373;
+ font-weight: normal;
+ font-size: 13px;
+ line-height: 24px; }
+ [lwt-newtab-brighttext] .ds-collection-card-grid .ds-header .ds-context {
+ color: #B1B1B3; }
+
+.ds-hero {
+ position: relative; }
+ .ds-hero header {
+ font-weight: 600; }
+ .ds-hero p {
+ line-height: 1.538;
+ margin: 8px 0; }
+ .ds-hero .excerpt {
+ font-size: 15px;
+ -webkit-line-clamp: 3;
+ line-height: 24px;
+ color: #0C0C0D;
+ margin: 0 0 10px; }
+ [lwt-newtab-brighttext] .ds-hero .excerpt {
+ color: #F9F9FA; }
+ .ds-hero .ds-card:not(.placeholder) {
+ border: 0;
+ padding-bottom: 20px; }
+ .ds-hero .ds-card:not(.placeholder):hover {
+ border: 0;
+ box-shadow: none;
+ border-radius: 0; }
+ .ds-hero .ds-card:not(.placeholder) .meta {
+ padding: 0; }
+ .ds-hero .ds-card:not(.placeholder) .img-wrapper {
+ margin: 0 0 12px; }
+ .ds-hero .ds-card.placeholder {
+ margin-bottom: 20px;
+ padding-bottom: 20px;
+ min-height: 180px; }
+ .ds-hero .img-wrapper {
+ margin: 0 0 12px; }
+ .ds-hero .ds-hero-item {
+ position: relative; }
+ .ds-hero .wrapper {
+ border-top: 1px solid #D7D7DB;
+ color: #737373;
+ display: block;
+ margin: 12px 0 16px;
+ padding-top: 16px;
+ height: 100%; }
+ [lwt-newtab-brighttext] .ds-hero .wrapper {
+ border-top: 1px solid #4A4A4F; }
+ [lwt-newtab-brighttext] .ds-hero .wrapper {
+ color: #D7D7DB; }
+ .ds-hero .wrapper:focus {
+ box-shadow: 0 0 0 5px rgba(10, 132, 255, 0.3);
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+ .ds-hero-no-border .ds-hero-item .wrapper {
+ border-top: 0;
+ border-bottom: 0;
+ padding: 0 0 8px; }
+ .ds-hero .wrapper:hover .meta header {
+ color: #0060DF; }
+ [lwt-newtab-brighttext] .ds-hero .wrapper:hover .meta header {
+ color: #45A1FF; }
+ .ds-hero .wrapper:active .meta header {
+ color: #003EAA; }
+ [lwt-newtab-brighttext] .ds-hero .wrapper:active .meta header {
+ color: #45A1FF; }
+ .ds-hero .wrapper .img-wrapper {
+ width: 100%; }
+ .ds-hero .wrapper .img {
+ height: 0;
+ padding-top: 50%; }
+ .ds-hero .wrapper .img img {
+ border-radius: 4px;
+ box-shadow: inset 0 0 0 0.5px rgba(0, 0, 0, 0.15); }
+ .ds-hero .wrapper .meta {
+ display: block;
+ flex-direction: column;
+ justify-content: space-between; }
+ .ds-hero .wrapper .meta .header-and-excerpt {
+ flex: 1; }
+ .ds-hero .wrapper .meta header {
+ font-size: 22px;
+ -webkit-line-clamp: 4;
+ line-height: 28px;
+ color: #0C0C0D;
+ margin-bottom: 0; }
+ [lwt-newtab-brighttext] .ds-hero .wrapper .meta header {
+ color: #FFF; }
+ .ds-hero .wrapper .meta .context,
+ .ds-hero .wrapper .meta .source {
+ margin: 0 0 4px; }
+ .ds-hero .wrapper .meta .context {
+ color: #008EA4; }
+ [lwt-newtab-brighttext] .ds-hero .wrapper .meta .context {
+ color: #A7FFFE; }
+ .ds-hero .wrapper .meta .source {
+ font-size: 13px;
+ color: #737373;
+ -webkit-line-clamp: 1;
+ margin-bottom: 0; }
+ [lwt-newtab-brighttext] .ds-hero .wrapper .meta .source {
+ color: #B1B1B3; }
+ .ds-column-5 .ds-hero .wrapper,
+ .ds-column-6 .ds-hero .wrapper,
+ .ds-column-7 .ds-hero .wrapper,
+ .ds-column-8 .ds-hero .wrapper {
+ display: grid;
+ grid-template-columns: repeat(2, 1fr);
+ grid-column-gap: 24px; }
+ .ds-column-5 .ds-hero .wrapper .img-wrapper,
+ .ds-column-6 .ds-hero .wrapper .img-wrapper,
+ .ds-column-7 .ds-hero .wrapper .img-wrapper,
+ .ds-column-8 .ds-hero .wrapper .img-wrapper {
+ margin: 0;
+ grid-column: 2;
+ grid-row: 1; }
+ .ds-column-5 .ds-hero .wrapper .meta,
+ .ds-column-6 .ds-hero .wrapper .meta,
+ .ds-column-7 .ds-hero .wrapper .meta,
+ .ds-column-8 .ds-hero .wrapper .meta {
+ grid-column: 1;
+ grid-row: 1;
+ display: flex; }
+ .ds-column-5 .ds-hero .wrapper .img,
+ .ds-column-6 .ds-hero .wrapper .img,
+ .ds-column-7 .ds-hero .wrapper .img,
+ .ds-column-8 .ds-hero .wrapper .img {
+ height: 0;
+ padding-top: 100%; }
+ .ds-column-5 .ds-hero .cards,
+ .ds-column-6 .ds-hero .cards,
+ .ds-column-7 .ds-hero .cards,
+ .ds-column-8 .ds-hero .cards {
+ display: grid;
+ grid-template-columns: repeat(2, 1fr);
+ grid-column-gap: 24px;
+ grid-auto-rows: min-content; }
+ .ds-column-9 .ds-hero,
+ .ds-column-10 .ds-hero,
+ .ds-column-11 .ds-hero,
+ .ds-column-12 .ds-hero {
+ display: grid;
+ grid-template-columns: repeat(2, 1fr);
+ grid-column-gap: 24px; }
+ .ds-column-9 .ds-hero.ds-hero-border,
+ .ds-column-10 .ds-hero.ds-hero-border,
+ .ds-column-11 .ds-hero.ds-hero-border,
+ .ds-column-12 .ds-hero.ds-hero-border {
+ border-top: 1px solid #D7D7DB;
+ padding: 20px 0; }
+ [lwt-newtab-brighttext] .ds-column-9 .ds-hero.ds-hero-border, [lwt-newtab-brighttext]
+ .ds-column-10 .ds-hero.ds-hero-border, [lwt-newtab-brighttext]
+ .ds-column-11 .ds-hero.ds-hero-border, [lwt-newtab-brighttext]
+ .ds-column-12 .ds-hero.ds-hero-border {
+ border-top: 1px solid #4A4A4F; }
+ .ds-column-9 .ds-hero.ds-hero-border .ds-card:not(.placeholder):nth-child(-n+2),
+ .ds-column-10 .ds-hero.ds-hero-border .ds-card:not(.placeholder):nth-child(-n+2),
+ .ds-column-11 .ds-hero.ds-hero-border .ds-card:not(.placeholder):nth-child(-n+2),
+ .ds-column-12 .ds-hero.ds-hero-border .ds-card:not(.placeholder):nth-child(-n+2) {
+ border-bottom: 1px solid #D7D7DB;
+ margin-bottom: 20px; }
+ [lwt-newtab-brighttext] .ds-column-9 .ds-hero.ds-hero-border .ds-card:not(.placeholder):nth-child(-n+2), [lwt-newtab-brighttext]
+ .ds-column-10 .ds-hero.ds-hero-border .ds-card:not(.placeholder):nth-child(-n+2), [lwt-newtab-brighttext]
+ .ds-column-11 .ds-hero.ds-hero-border .ds-card:not(.placeholder):nth-child(-n+2), [lwt-newtab-brighttext]
+ .ds-column-12 .ds-hero.ds-hero-border .ds-card:not(.placeholder):nth-child(-n+2) {
+ border-bottom: 1px solid #4A4A4F; }
+ .ds-column-9 .ds-hero .wrapper,
+ .ds-column-10 .ds-hero .wrapper,
+ .ds-column-11 .ds-hero .wrapper,
+ .ds-column-12 .ds-hero .wrapper {
+ border-top: 0;
+ border-bottom: 0;
+ margin: 0;
+ padding: 0 0 20px;
+ display: flex;
+ flex-direction: column; }
+ .ds-column-9 .ds-hero .wrapper .img-wrapper,
+ .ds-column-10 .ds-hero .wrapper .img-wrapper,
+ .ds-column-11 .ds-hero .wrapper .img-wrapper,
+ .ds-column-12 .ds-hero .wrapper .img-wrapper {
+ margin: 0; }
+ .ds-column-9 .ds-hero .wrapper .img,
+ .ds-column-10 .ds-hero .wrapper .img,
+ .ds-column-11 .ds-hero .wrapper .img,
+ .ds-column-12 .ds-hero .wrapper .img {
+ margin-bottom: 12px;
+ height: 0;
+ padding-top: 50%; }
+ .ds-column-9 .ds-hero .wrapper .meta,
+ .ds-column-10 .ds-hero .wrapper .meta,
+ .ds-column-11 .ds-hero .wrapper .meta,
+ .ds-column-12 .ds-hero .wrapper .meta {
+ flex-grow: 1;
+ display: flex;
+ padding: 0 24px 0 0; }
+ .ds-column-9 .ds-hero .wrapper .meta header,
+ .ds-column-10 .ds-hero .wrapper .meta header,
+ .ds-column-11 .ds-hero .wrapper .meta header,
+ .ds-column-12 .ds-hero .wrapper .meta header {
+ font-size: 22px;
+ -webkit-line-clamp: 3;
+ line-height: 28px; }
+ .ds-column-9 .ds-hero .wrapper .meta .source,
+ .ds-column-10 .ds-hero .wrapper .meta .source,
+ .ds-column-11 .ds-hero .wrapper .meta .source,
+ .ds-column-12 .ds-hero .wrapper .meta .source {
+ margin-bottom: 0; }
+ .ds-column-9 .ds-hero .cards,
+ .ds-column-10 .ds-hero .cards,
+ .ds-column-11 .ds-hero .cards,
+ .ds-column-12 .ds-hero .cards {
+ display: grid;
+ grid-template-columns: repeat(2, 1fr);
+ grid-column-gap: 24px;
+ grid-auto-rows: min-content; }
+ [lwt-newtab-brighttext] .ds-column-9 .ds-hero .cards .ds-card:hover, [lwt-newtab-brighttext]
+ .ds-column-10 .ds-hero .cards .ds-card:hover, [lwt-newtab-brighttext]
+ .ds-column-11 .ds-hero .cards .ds-card:hover, [lwt-newtab-brighttext]
+ .ds-column-12 .ds-hero .cards .ds-card:hover {
+ background: none; }
+ [lwt-newtab-brighttext] .ds-column-9 .ds-hero .cards .ds-card:hover .title, [lwt-newtab-brighttext]
+ .ds-column-10 .ds-hero .cards .ds-card:hover .title, [lwt-newtab-brighttext]
+ .ds-column-11 .ds-hero .cards .ds-card:hover .title, [lwt-newtab-brighttext]
+ .ds-column-12 .ds-hero .cards .ds-card:hover .title {
+ color: #45A1FF; }
+ [lwt-newtab-brighttext] .ds-column-9 .ds-hero .cards .ds-card:active .title, [lwt-newtab-brighttext]
+ .ds-column-10 .ds-hero .cards .ds-card:active .title, [lwt-newtab-brighttext]
+ .ds-column-11 .ds-hero .cards .ds-card:active .title, [lwt-newtab-brighttext]
+ .ds-column-12 .ds-hero .cards .ds-card:active .title {
+ color: #0A84FF; }
+ .ds-column-9 .ds-hero .cards .ds-card .title,
+ .ds-column-10 .ds-hero .cards .ds-card .title,
+ .ds-column-11 .ds-hero .cards .ds-card .title,
+ .ds-column-12 .ds-hero .cards .ds-card .title {
+ font-size: 14px;
+ -webkit-line-clamp: 3;
+ line-height: 20px; }
+ [lwt-newtab-brighttext] .ds-column-9 .ds-hero .cards .ds-card .title, [lwt-newtab-brighttext]
+ .ds-column-10 .ds-hero .cards .ds-card .title, [lwt-newtab-brighttext]
+ .ds-column-11 .ds-hero .cards .ds-card .title, [lwt-newtab-brighttext]
+ .ds-column-12 .ds-hero .cards .ds-card .title {
+ color: #FFF; }
+ .ds-hero.empty {
+ grid-template-columns: auto; }
+
+.ds-highlights .section .section-list {
+ grid-gap: var(--gridRowGap);
+ grid-template-columns: repeat(1, 1fr); }
+ @media (min-width: 610px) {
+ .ds-highlights .section .section-list {
+ grid-template-columns: repeat(2, 1fr); } }
+ @media (min-width: 866px) {
+ .ds-highlights .section .section-list {
+ grid-template-columns: repeat(4, 1fr); } }
+ .ds-highlights .section .section-list .card-outer {
+ height: 175px; }
+ .ds-highlights .section .section-list .card-outer .card-host-name {
+ font-size: 13px;
+ line-height: 20px;
+ margin-bottom: 2px;
+ padding-bottom: 0;
+ text-transform: unset; }
+ .ds-highlights .section .section-list .card-outer .card-title {
+ font-size: 14px;
+ font-weight: 600;
+ line-height: 20px;
+ max-height: 20px; }
+
+.ds-highlights .hide-for-narrow {
+ display: block; }
+
+.ds-hr {
+ border: 0;
+ border-top: 1px solid #D7D7DB;
+ height: 0; }
+ [lwt-newtab-brighttext] .ds-hr {
+ border-top: 1px solid #4A4A4F; }
+
+.ds-list {
+ display: grid;
+ grid-row-gap: 24px;
+ grid-column-gap: 24px;
+ padding-inline-start: 0; }
+ .ds-list:not(.ds-list-full-width) .ds-list-item {
+ font-size: 14px;
+ line-height: 20px;
+ position: relative; }
+ .ds-list:not(.ds-list-full-width) .ds-list-item-title {
+ font-size: 14px;
+ -webkit-line-clamp: 3;
+ line-height: 20px; }
+ .ds-list:not(.ds-list-full-width) .ds-list-image {
+ min-width: 80px;
+ width: 80px; }
+ .ds-column-5 .ds-list:not(.ds-list-full-width),
+ .ds-column-6 .ds-list:not(.ds-list-full-width),
+ .ds-column-7 .ds-list:not(.ds-list-full-width),
+ .ds-column-8 .ds-list:not(.ds-list-full-width) {
+ grid-template-columns: repeat(2, 1fr); }
+ .ds-column-9 .ds-list:not(.ds-list-full-width),
+ .ds-column-10 .ds-list:not(.ds-list-full-width),
+ .ds-column-11 .ds-list:not(.ds-list-full-width),
+ .ds-column-12 .ds-list:not(.ds-list-full-width) {
+ grid-template-columns: repeat(3, 1fr); }
+ .ds-list:not(.ds-list-full-width).empty {
+ grid-template-columns: auto; }
+ .ds-list:not(.ds-list-full-width) .ds-list-item-excerpt {
+ display: none; }
+ .ds-list:not(.ds-list-images) .ds-list-image {
+ display: none; }
+ .ds-list a {
+ color: #0C0C0D; }
+ [lwt-newtab-brighttext] .ds-list a {
+ color: #F9F9FA; }
+
+.ds-list-item-link:focus {
+ box-shadow: 0 0 0 5px rgba(10, 132, 255, 0.3);
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+
+.ds-list-numbers .ds-list-item {
+ counter-increment: list; }
+
+.ds-list-numbers .ds-list-item:not(.placeholder) > .ds-list-item-link {
+ padding-inline-start: 41px; }
+ .ds-list-numbers .ds-list-item:not(.placeholder) > .ds-list-item-link::before {
+ background-color: #50BCB6;
+ border-radius: 32px;
+ color: #FFF;
+ content: counter(list);
+ font-size: 17px;
+ height: 32px;
+ line-height: 32px;
+ margin-inline-start: -41px;
+ margin-top: 3px;
+ position: absolute;
+ text-align: center;
+ width: 32px; }
+ [lwt-newtab-brighttext] .ds-list-numbers .ds-list-item:not(.placeholder) > .ds-list-item-link::before {
+ background-color: #008EA4; }
+ .ds-list-numbers .ds-list-item:not(.placeholder) > .ds-list-item-link:hover::before {
+ background-color: #45A1FF; }
+ [lwt-newtab-brighttext] .ds-list-numbers .ds-list-item:not(.placeholder) > .ds-list-item-link:hover::before {
+ background-color: #45A1FF; }
+ .ds-list-numbers .ds-list-item:not(.placeholder) > .ds-list-item-link:active::before {
+ background-color: #003EAA; }
+ [lwt-newtab-brighttext] .ds-list-numbers .ds-list-item:not(.placeholder) > .ds-list-item-link:active::before {
+ background-color: #0060DF; }
+
+.ds-list-borders {
+ border-top: 1px solid #D7D7DB;
+ grid-row-gap: 16px;
+ padding-top: 16px; }
+ [lwt-newtab-brighttext] .ds-list-borders {
+ border-top: 1px solid #4A4A4F; }
+ .ds-list-borders.ds-list-full-width .ds-list-item:not(.placeholder):not(:nth-last-child(-n+1)),
+ .ds-column-1 .ds-list-borders .ds-list-item:not(.placeholder):not(:nth-last-child(-n+1)),
+ .ds-column-2 .ds-list-borders .ds-list-item:not(.placeholder):not(:nth-last-child(-n+1)),
+ .ds-column-3 .ds-list-borders .ds-list-item:not(.placeholder):not(:nth-last-child(-n+1)),
+ .ds-column-4 .ds-list-borders .ds-list-item:not(.placeholder):not(:nth-last-child(-n+1)) {
+ border-bottom: 1px solid #D7D7DB;
+ margin-bottom: -1px;
+ padding-bottom: 16px; }
+ [lwt-newtab-brighttext] .ds-list-borders.ds-list-full-width .ds-list-item:not(.placeholder):not(:nth-last-child(-n+1)), [lwt-newtab-brighttext]
+ .ds-column-1 .ds-list-borders .ds-list-item:not(.placeholder):not(:nth-last-child(-n+1)), [lwt-newtab-brighttext]
+ .ds-column-2 .ds-list-borders .ds-list-item:not(.placeholder):not(:nth-last-child(-n+1)), [lwt-newtab-brighttext]
+ .ds-column-3 .ds-list-borders .ds-list-item:not(.placeholder):not(:nth-last-child(-n+1)), [lwt-newtab-brighttext]
+ .ds-column-4 .ds-list-borders .ds-list-item:not(.placeholder):not(:nth-last-child(-n+1)) {
+ border-bottom: 1px solid #4A4A4F; }
+ .ds-column-5 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+2)),
+ .ds-column-6 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+2)),
+ .ds-column-7 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+2)),
+ .ds-column-8 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+2)) {
+ border-bottom: 1px solid #D7D7DB;
+ margin-bottom: -1px;
+ padding-bottom: 16px; }
+ [lwt-newtab-brighttext] .ds-column-5 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+2)), [lwt-newtab-brighttext]
+ .ds-column-6 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+2)), [lwt-newtab-brighttext]
+ .ds-column-7 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+2)), [lwt-newtab-brighttext]
+ .ds-column-8 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+2)) {
+ border-bottom: 1px solid #4A4A4F; }
+ .ds-column-9 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+3)),
+ .ds-column-10 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+3)),
+ .ds-column-11 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+3)),
+ .ds-column-12 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+3)) {
+ border-bottom: 1px solid #D7D7DB;
+ margin-bottom: -1px;
+ padding-bottom: 16px; }
+ [lwt-newtab-brighttext] .ds-column-9 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+3)), [lwt-newtab-brighttext]
+ .ds-column-10 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+3)), [lwt-newtab-brighttext]
+ .ds-column-11 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+3)), [lwt-newtab-brighttext]
+ .ds-column-12 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+3)) {
+ border-bottom: 1px solid #4A4A4F; }
+
+.ds-list-full-width .ds-list-item {
+ font-size: 17px;
+ line-height: 24px;
+ position: relative; }
+
+.ds-list-full-width .ds-list-item-title {
+ font-size: 17px;
+ -webkit-line-clamp: 3;
+ line-height: 24px; }
+
+.ds-list-full-width .ds-list-image {
+ min-width: 160px;
+ width: 160px; }
+
+.ds-list-item {
+ display: block;
+ text-align: start; }
+ .ds-list-item.placeholder {
+ background: transparent;
+ min-height: 80px;
+ box-shadow: inset 0 0 0 1px var(--newtab-inner-box-shadow-color);
+ border-radius: 4px; }
+ .ds-list-item.placeholder .ds-list-item-link {
+ cursor: default; }
+ .ds-list-item.placeholder .ds-list-image {
+ opacity: 0; }
+ .ds-list-item .ds-list-item-link {
+ mix-blend-mode: normal;
+ display: flex;
+ justify-content: space-between;
+ height: 100%; }
+ .ds-list-item .ds-list-item-excerpt {
+ font-size: 14px;
+ -webkit-line-clamp: 2;
+ line-height: 20px;
+ color: #737373;
+ margin: 4px 0 8px; }
+ [lwt-newtab-brighttext] .ds-list-item .ds-list-item-excerpt {
+ color: rgba(249, 249, 250, 0.8); }
+ .ds-list-item p {
+ font-size: 14px;
+ line-height: 20px;
+ margin: 0; }
+ .ds-list-item .ds-list-item-info {
+ font-size: 14px;
+ -webkit-line-clamp: 1;
+ line-height: 20px;
+ color: #737373;
+ font-size: 13px; }
+ [lwt-newtab-brighttext] .ds-list-item .ds-list-item-info {
+ color: #B1B1B3; }
+ .ds-list-item .ds-list-item-title {
+ font-weight: 600;
+ margin-bottom: 4px; }
+ .ds-list-item .ds-list-item-body {
+ flex: 1; }
+ .ds-list-item .ds-list-item-text {
+ display: flex;
+ flex-direction: column;
+ justify-content: space-between; }
+ .ds-list-item .ds-list-image {
+ height: 80px;
+ margin-inline-start: 14px;
+ min-height: 80px; }
+ .ds-list-item .ds-list-image img {
+ border-radius: 4px;
+ box-shadow: inset 0 0 0 0.5px rgba(0, 0, 0, 0.15); }
+ .ds-list-item:hover .ds-list-item-title {
+ color: #45A1FF; }
+ .ds-list-item:active .ds-list-item-title {
+ color: #003EAA; }
+
+.outer-wrapper.newtab-experience .ds-navigation {
+ color: var(--newtab-background-primary-text-color); }
+
+.ds-navigation {
+ color: #737373;
+ padding: 4px 0;
+ font-weight: 600;
+ line-height: 22px;
+ font-size: 11.5px; }
+ [lwt-newtab-brighttext] .ds-navigation {
+ color: #D7D7DB; }
+ @media (min-width: 1122px) {
+ .ds-navigation {
+ line-height: 32px;
+ font-size: 14px; } }
+ .ds-navigation.ds-navigation-centered {
+ text-align: center; }
+ .ds-navigation.ds-navigation-right-aligned {
+ text-align: end; }
+ .ds-navigation ul {
+ display: inline;
+ margin: 0;
+ padding: 0; }
+ .ds-navigation ul li {
+ display: inline-block; }
+ .ds-navigation ul li::after {
+ content: '·';
+ padding: 6px; }
+ .ds-navigation ul li:last-child::after {
+ content: none; }
+ .ds-navigation ul li a:hover, .ds-navigation ul li a:active {
+ text-decoration: underline; }
+ .ds-navigation ul li a:active {
+ color: #003EAA; }
+ .ds-navigation .ds-navigation-header {
+ padding-inline-end: 6px; }
+
+.ds-section-title {
+ text-align: center;
+ margin-top: 24px; }
+ .ds-section-title .title {
+ line-height: 48px;
+ font-size: 36px;
+ font-weight: 300;
+ color: #0C0C0D; }
+ [lwt-newtab-brighttext] .ds-section-title .title {
+ color: #FFF; }
+ .ds-section-title .subtitle {
+ line-height: 24px;
+ font-size: 14px;
+ color: #737373;
+ margin-top: 4px; }
+ [lwt-newtab-brighttext] .ds-section-title .subtitle {
+ color: #D7D7DB; }
+
+.outer-wrapper:not(.newtab-experience) .ds-top-sites .top-sites .top-site-outer {
+ padding: 0 12px; }
+ .outer-wrapper:not(.newtab-experience) .ds-top-sites .top-sites .top-site-outer .top-site-inner > a:is(.active, :focus) .tile {
+ box-shadow: 0 0 0 5px rgba(10, 132, 255, 0.3);
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+ [lwt-newtab-brighttext] .outer-wrapper:not(.newtab-experience) .ds-top-sites .top-sites .top-site-outer .top-site-inner > a:is(.active, :focus) .tile {
+ box-shadow: 0 0 0 5px rgba(69, 161, 255, 0.4);
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+ .outer-wrapper:not(.newtab-experience) .ds-top-sites .top-sites .top-site-outer .top-site-inner > a:is(:hover) .tile {
+ box-shadow: 0 0 0 5px #D7D7DB;
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+ [lwt-newtab-brighttext] .outer-wrapper:not(.newtab-experience) .ds-top-sites .top-sites .top-site-outer .top-site-inner > a:is(:hover) .tile {
+ box-shadow: 0 0 0 5px #4A4A4F;
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+
+.outer-wrapper:not(.newtab-experience) .ds-top-sites .top-sites .top-sites-list {
+ margin: 0 -12px; }
+
+.outer-wrapper.newtab-experience .ds-top-sites .top-sites .top-site-outer .top-site-inner > a:is(.active, :focus) .tile {
+ border: 0;
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-focus-outline), 0 0 0 1px var(--newtab-focus-border); }
+
+.outer-wrapper.newtab-experience .ds-top-sites .top-sites .top-site-outer .top-site-inner > a:is(:hover) .top-site-inner {
+ box-shadow: 0 0 0 5px #D7D7DB;
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+ [lwt-newtab-brighttext] .outer-wrapper.newtab-experience .ds-top-sites .top-sites .top-site-outer .top-site-inner > a:is(:hover) .top-site-inner {
+ box-shadow: 0 0 0 5px #4A4A4F;
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+
+.outer-wrapper.newtab-experience .ds-top-sites .top-sites .top-sites-list {
+ margin: 0 -12px; }
+
+.ds-column-5 .ds-top-sites .top-site-outer,
+.ds-column-6 .ds-top-sites .top-site-outer,
+.ds-column-7 .ds-top-sites .top-site-outer,
+.ds-column-8 .ds-top-sites .top-site-outer {
+ padding: 0 10px; }
+
+.ds-column-5 .ds-top-sites .top-sites-list,
+.ds-column-6 .ds-top-sites .top-sites-list,
+.ds-column-7 .ds-top-sites .top-sites-list,
+.ds-column-8 .ds-top-sites .top-sites-list {
+ margin: 0 -10px; }
+
+.ds-column-5 .ds-top-sites .top-site-inner,
+.ds-column-6 .ds-top-sites .top-site-inner,
+.ds-column-7 .ds-top-sites .top-site-inner,
+.ds-column-8 .ds-top-sites .top-site-inner {
+ --leftPanelIconWidth: 84.67px; }
+ .ds-column-5 .ds-top-sites .top-site-inner .tile,
+ .ds-column-6 .ds-top-sites .top-site-inner .tile,
+ .ds-column-7 .ds-top-sites .top-site-inner .tile,
+ .ds-column-8 .ds-top-sites .top-site-inner .tile {
+ width: var(--leftPanelIconWidth);
+ height: var(--leftPanelIconWidth); }
+ .ds-column-5 .ds-top-sites .top-site-inner .title,
+ .ds-column-6 .ds-top-sites .top-site-inner .title,
+ .ds-column-7 .ds-top-sites .top-site-inner .title,
+ .ds-column-8 .ds-top-sites .top-site-inner .title {
+ width: var(--leftPanelIconWidth); }
+
+.ds-column-1 .ds-top-sites .top-site-outer,
+.ds-column-2 .ds-top-sites .top-site-outer,
+.ds-column-3 .ds-top-sites .top-site-outer,
+.ds-column-4 .ds-top-sites .top-site-outer {
+ padding: 0 8px; }
+
+.ds-column-1 .ds-top-sites .top-sites-list,
+.ds-column-2 .ds-top-sites .top-sites-list,
+.ds-column-3 .ds-top-sites .top-sites-list,
+.ds-column-4 .ds-top-sites .top-sites-list {
+ margin: 0 -8px; }
+
+.ds-column-1 .ds-top-sites .top-site-inner,
+.ds-column-2 .ds-top-sites .top-site-inner,
+.ds-column-3 .ds-top-sites .top-site-inner,
+.ds-column-4 .ds-top-sites .top-site-inner {
+ --rightPanelIconWidth: 82.67px; }
+ .ds-column-1 .ds-top-sites .top-site-inner .tile,
+ .ds-column-2 .ds-top-sites .top-site-inner .tile,
+ .ds-column-3 .ds-top-sites .top-site-inner .tile,
+ .ds-column-4 .ds-top-sites .top-site-inner .tile {
+ width: var(--rightPanelIconWidth);
+ height: var(--rightPanelIconWidth); }
+ .ds-column-1 .ds-top-sites .top-site-inner .title,
+ .ds-column-2 .ds-top-sites .top-site-inner .title,
+ .ds-column-3 .ds-top-sites .top-site-inner .title,
+ .ds-column-4 .ds-top-sites .top-site-inner .title {
+ width: var(--rightPanelIconWidth); }
+
+.ds-hero-item .context-menu-button,
+.ds-list-item .context-menu-button,
+.ds-card .context-menu-button,
+.ds-signup .context-menu-button {
+ background-clip: padding-box;
+ background-color: var(--newtab-contextmenu-button-color);
+ background-image: url("chrome://global/skin/icons/more.svg");
+ background-position: 55%;
+ border: 1px solid var(--newtab-border-primary-color);
+ border-radius: 100%;
+ box-shadow: 0 2px rgba(12, 12, 13, 0.1);
+ cursor: pointer;
+ fill: var(--newtab-icon-primary-color);
+ height: 27px;
+ inset-inline-end: -13.5px;
+ opacity: 0;
+ position: absolute;
+ top: -13.5px;
+ transform: scale(0.25);
+ transition-duration: 150ms;
+ transition-property: transform, opacity;
+ width: 27px; }
+ .ds-hero-item .context-menu-button:is(:active, :focus),
+ .ds-list-item .context-menu-button:is(:active, :focus),
+ .ds-card .context-menu-button:is(:active, :focus),
+ .ds-signup .context-menu-button:is(:active, :focus) {
+ opacity: 1;
+ transform: scale(1); }
+
+.ds-hero-item .context-menu,
+.ds-list-item .context-menu,
+.ds-card .context-menu,
+.ds-signup .context-menu {
+ opacity: 0; }
+
+.ds-hero-item.active .context-menu,
+.ds-list-item.active .context-menu,
+.ds-card.active .context-menu,
+.ds-signup.active .context-menu {
+ opacity: 1; }
+
+.ds-hero-item.last-item .context-menu,
+.ds-list-item.last-item .context-menu,
+.ds-card.last-item .context-menu,
+.ds-signup.last-item .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; }
+
+.ds-hero-item.last-item .context-menu,
+.ds-list-item.last-item .context-menu,
+.ds-card.last-item .context-menu,
+.ds-signup.last-item .context-menu {
+ opacity: 1; }
+
+.ds-hero-item:is(:hover, :focus, .active),
+.ds-list-item:is(:hover, :focus, .active),
+.ds-card:is(:hover, :focus, .active),
+.ds-signup:is(:hover, :focus, .active) {
+ outline: none; }
+ .ds-hero-item:is(:hover, :focus, .active) .context-menu-button,
+ .ds-list-item:is(:hover, :focus, .active) .context-menu-button,
+ .ds-card:is(:hover, :focus, .active) .context-menu-button,
+ .ds-signup:is(:hover, :focus, .active) .context-menu-button {
+ opacity: 1;
+ transform: scale(1);
+ transition-delay: 333ms; }
+ .ds-hero-item:is(:hover, :focus, .active).ds-card-grid-border,
+ .ds-list-item:is(:hover, :focus, .active).ds-card-grid-border,
+ .ds-card:is(:hover, :focus, .active).ds-card-grid-border,
+ .ds-signup:is(:hover, :focus, .active).ds-card-grid-border {
+ box-shadow: 0 0 0 5px var(--newtab-card-active-outline-color);
+ transition: box-shadow 150ms; }
+
+.outer-wrapper:not(.newtab-experience) .ds-card .ds-card-link:hover {
+ box-shadow: 0 0 0 5px #D7D7DB;
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+ [lwt-newtab-brighttext] .outer-wrapper:not(.newtab-experience) .ds-card .ds-card-link:hover {
+ box-shadow: 0 0 0 5px #4A4A4F;
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+
+.outer-wrapper:not(.newtab-experience) .ds-card .ds-card-link:focus {
+ box-shadow: 0 0 0 5px rgba(10, 132, 255, 0.3);
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+ [lwt-newtab-brighttext] .outer-wrapper:not(.newtab-experience) .ds-card .ds-card-link:focus {
+ box-shadow: 0 0 0 5px rgba(69, 161, 255, 0.4);
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+
+.outer-wrapper:not(.newtab-experience) .ds-card .ds-card-link:active {
+ box-shadow: 0 0 0 5px #D7D7DB;
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+ [lwt-newtab-brighttext] .outer-wrapper:not(.newtab-experience) .ds-card .ds-card-link:active {
+ box-shadow: 0 0 0 5px #4A4A4F;
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+
+.ds-card {
+ display: flex;
+ flex-direction: column;
+ position: relative; }
+ .ds-card .playhead {
+ background: #0060DF url("chrome://activity-stream/content/data/content/assets/glyph-playhead.svg") no-repeat 12px center;
+ border-radius: 20px;
+ bottom: -16px;
+ color: rgba(255, 255, 255, 0);
+ display: flex;
+ flex-direction: column;
+ height: 40px;
+ justify-content: center;
+ left: 16px;
+ min-width: 40px;
+ padding: 0 0 0 40px;
+ position: absolute;
+ transition: padding 100ms ease-in-out 0ms, color 100ms linear 100ms; }
+ .ds-card .playhead:hover {
+ color: white;
+ padding: 0 20px 0 40px; }
+ .ds-card .playhead span {
+ display: none; }
+ .ds-card .playhead:hover span {
+ display: inline;
+ font-style: normal;
+ font-weight: 600;
+ font-size: 13px; }
+ .ds-card.placeholder {
+ background: transparent;
+ box-shadow: inset 0 0 0 1px var(--newtab-inner-box-shadow-color);
+ border-radius: 4px;
+ min-height: 300px; }
+ .ds-card .img-wrapper {
+ width: 100%;
+ position: relative; }
+ .ds-card .img {
+ height: 0;
+ padding-top: 50%; }
+ .ds-card .img img {
+ border-radius: 4px;
+ box-shadow: inset 0 0 0 0.5px rgba(0, 0, 0, 0.15); }
+ .ds-card .ds-card-link {
+ height: 100%;
+ display: flex;
+ flex-direction: column; }
+ .ds-card .ds-card-link:hover header {
+ color: #0060DF; }
+ [lwt-newtab-brighttext] .ds-card .ds-card-link:hover header {
+ color: #45A1FF; }
+ .ds-card .ds-card-link:focus header {
+ color: #0060DF; }
+ [lwt-newtab-brighttext] .ds-card .ds-card-link:focus header {
+ color: #45A1FF; }
+ .ds-card .ds-card-link:active header {
+ color: #003EAA; }
+ [lwt-newtab-brighttext] .ds-card .ds-card-link:active header {
+ color: #0A84FF; }
+ .ds-card.video-card .meta {
+ margin-top: 4px; }
+ .ds-card .meta {
+ display: flex;
+ flex-direction: column;
+ padding: 12px 16px;
+ flex-grow: 1; }
+ .ds-card .meta .info-wrap {
+ flex-grow: 1; }
+ .ds-card .meta .title {
+ font-size: 17px;
+ -webkit-line-clamp: 3;
+ line-height: 24px;
+ font-weight: 600; }
+ .ds-card .meta .excerpt {
+ font-size: 14px;
+ -webkit-line-clamp: 3;
+ line-height: 20px; }
+ .ds-card .meta .source {
+ -webkit-line-clamp: 1;
+ margin-bottom: 2px;
+ font-size: 13px;
+ color: #737373; }
+ [lwt-newtab-brighttext] .ds-card .meta .source {
+ color: #B1B1B3; }
+ .ds-card .meta .cta-button {
+ width: 100%;
+ margin: 12px 0 4px;
+ box-shadow: none;
+ border-radius: 4px;
+ height: 32px;
+ font-size: 14px;
+ font-weight: 600;
+ padding: 5px 8px 7px;
+ border: 0;
+ color: #0C0C0D;
+ background: rgba(12, 12, 13, 0.1); }
+ [lwt-newtab-brighttext] .ds-card .meta .cta-button {
+ color: #F9F9FA;
+ background: rgba(12, 12, 13, 0.7); }
+ .ds-card .meta .cta-button:focus {
+ background: rgba(12, 12, 13, 0.1);
+ box-shadow: 0 0 0 2px #FFF, 0 0 0 5px rgba(10, 132, 255, 0.5); }
+ [lwt-newtab-brighttext] .ds-card .meta .cta-button:focus {
+ background: rgba(12, 12, 13, 0.7);
+ box-shadow: 0 0 0 2px #2A2A2E, 0 0 0 5px rgba(10, 132, 255, 0.5); }
+ .ds-card .meta .cta-button:hover {
+ background: rgba(12, 12, 13, 0.2); }
+ [lwt-newtab-brighttext] .ds-card .meta .cta-button:hover {
+ background: rgba(12, 12, 13, 0.5); }
+ .ds-card .meta .cta-button:active {
+ background: rgba(12, 12, 13, 0.3); }
+ [lwt-newtab-brighttext] .ds-card .meta .cta-button:active {
+ background: rgba(12, 12, 13, 0.7); }
+ .ds-card .meta .cta-link {
+ font-size: 15px;
+ font-weight: 600;
+ line-height: 24px;
+ height: 24px;
+ width: auto;
+ background-size: auto;
+ background-position: right 1.5px;
+ padding-right: 9px;
+ color: #0060DF;
+ fill: #0060DF; }
+ [lwt-newtab-brighttext] .ds-card .meta .cta-link {
+ color: #45A1FF;
+ fill: #45A1FF; }
+ .ds-card .meta .cta-link:focus {
+ box-shadow: 0 0 0 1px #FFF, 0 0 0 4px rgba(10, 132, 255, 0.5);
+ border-radius: 4px;
+ outline: 0; }
+ [lwt-newtab-brighttext] .ds-card .meta .cta-link:focus {
+ box-shadow: 0 0 0 1px #2A2A2E, 0 0 0 4px rgba(10, 132, 255, 0.5); }
+ .ds-card .meta .cta-link:active {
+ color: #003EAA;
+ fill: #003EAA;
+ box-shadow: none; }
+ [lwt-newtab-brighttext] .ds-card .meta .cta-link:active {
+ color: #0A84FF;
+ fill: #0A84FF;
+ box-shadow: none; }
+ .ds-card .meta .cta-link:hover {
+ text-decoration: underline; }
+ .ds-card header {
+ line-height: 24px;
+ font-size: 17px;
+ color: #0C0C0D; }
+ [lwt-newtab-brighttext] .ds-card header {
+ color: #F9F9FA; }
+ .ds-card p {
+ font-size: 14px;
+ line-height: 20px;
+ color: #0C0C0D;
+ margin: 0; }
+ [lwt-newtab-brighttext] .ds-card p {
+ color: #F9F9FA; }
+
+.outer-wrapper.newtab-experience .ds-card .context-menu-button:is(:active, :focus) {
+ outline: 0;
+ fill: var(--newtab-primary-action-background);
+ border: 1px solid var(--newtab-primary-action-background); }
+
+.outer-wrapper.newtab-experience .ds-card .ds-card-link:focus {
+ border: 0;
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-focus-outline), 0 0 0 1px var(--newtab-focus-border);
+ transition: none; }
+ .outer-wrapper.newtab-experience .ds-card .ds-card-link:focus header {
+ color: #0060DF; }
+ [lwt-newtab-brighttext] .outer-wrapper.newtab-experience .ds-card .ds-card-link:focus header {
+ color: #45A1FF; }
+
+.story-footer {
+ color: var(--newtab-text-secondary-color);
+ inset-inline-start: 0;
+ margin-top: 12px;
+ position: relative; }
+ .story-footer .story-sponsored-label,
+ .story-footer .story-view-count,
+ .story-footer .status-message {
+ -webkit-line-clamp: 1;
+ font-size: 13px;
+ line-height: 24px;
+ color: #737373; }
+ [lwt-newtab-brighttext] .story-footer .story-sponsored-label, [lwt-newtab-brighttext]
+ .story-footer .story-view-count, [lwt-newtab-brighttext]
+ .story-footer .status-message {
+ color: #B1B1B3; }
+ .story-footer .status-message {
+ display: flex;
+ align-items: center;
+ height: 24px; }
+ .story-footer .status-message .story-badge-icon {
+ fill: #737373;
+ height: 16px;
+ margin-inline-end: 6px; }
+ [lwt-newtab-brighttext] .story-footer .status-message .story-badge-icon {
+ fill: #B1B1B3; }
+ .story-footer .status-message .story-badge-icon.icon-bookmark-removed {
+ background-image: url("chrome://activity-stream/content/data/content/assets/icon-removed-bookmark.svg"); }
+ .story-footer .status-message .story-context-label {
+ color: #737373;
+ flex-grow: 1;
+ font-size: 13px;
+ line-height: 24px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap; }
+ [lwt-newtab-brighttext] .story-footer .status-message .story-context-label {
+ color: #B1B1B3; }
+
+.story-animate-enter {
+ opacity: 0; }
+
+.story-animate-enter-active {
+ opacity: 1;
+ transition: opacity 150ms ease-in 300ms; }
+ .story-animate-enter-active .story-badge-icon,
+ .story-animate-enter-active .story-context-label {
+ animation: color 3s ease-out 0.3s; }
+ [lwt-newtab-brighttext] .story-animate-enter-active .story-badge-icon, [lwt-newtab-brighttext]
+ .story-animate-enter-active .story-context-label {
+ animation: dark-color 3s ease-out 0.3s; }
+
+@keyframes color {
+ 0% {
+ color: #058B00;
+ fill: #058B00; }
+ 100% {
+ color: #737373;
+ fill: #737373; } }
+
+@keyframes dark-color {
+ 0% {
+ color: #7C6;
+ fill: #7C6; }
+ 100% {
+ color: #B1B1B3;
+ fill: #B1B1B3; } }
+
+.story-animate-exit {
+ position: absolute;
+ top: 0;
+ opacity: 1; }
+
+.story-animate-exit-active {
+ opacity: 0;
+ transition: opacity 250ms ease-in; }
+
+.ds-image {
+ display: block;
+ position: relative;
+ opacity: 0; }
+ .ds-image.use-transition {
+ transition: opacity 0.8s; }
+ .ds-image.loaded {
+ opacity: 1; }
+ .ds-image img,
+ .ds-image .broken-image {
+ background-color: var(--newtab-card-placeholder-color);
+ position: absolute;
+ top: 0;
+ width: 100%;
+ height: 100%;
+ object-fit: cover; }
+
+.ds-dismiss {
+ position: relative;
+ border-radius: 8px;
+ transition-duration: 250ms;
+ transition-property: background; }
+ .ds-dismiss:hover .ds-dismiss-button {
+ opacity: 1; }
+ .ds-dismiss .ds-dismiss-button {
+ border: 0;
+ cursor: pointer;
+ height: 32px;
+ width: 32px;
+ padding: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ position: absolute;
+ inset-inline-end: 0;
+ top: 0;
+ border-radius: 50%;
+ background-color: transparent; }
+ .ds-dismiss .ds-dismiss-button .icon {
+ fill: #737373; }
+ [lwt-newtab-brighttext] .ds-dismiss .ds-dismiss-button .icon {
+ fill: #EDEDF0; }
+ .ds-dismiss .ds-dismiss-button:hover {
+ background: rgba(12, 12, 13, 0.2); }
+ [lwt-newtab-brighttext] .ds-dismiss .ds-dismiss-button:hover {
+ background: rgba(12, 12, 13, 0.5); }
+ [lwt-newtab-brighttext] .ds-dismiss .ds-dismiss-button:hover .icon {
+ fill: #F9F9FA; }
+ .ds-dismiss .ds-dismiss-button:hover .icon {
+ fill: #2A2A2E; }
+ .ds-dismiss .ds-dismiss-button:active {
+ background: rgba(12, 12, 13, 0.3); }
+ [lwt-newtab-brighttext] .ds-dismiss .ds-dismiss-button:active {
+ background: rgba(12, 12, 13, 0.7); }
+ .ds-dismiss .ds-dismiss-button:focus {
+ box-shadow: 0 0 0 2px #FFF, 0 0 0 5px rgba(10, 132, 255, 0.5); }
+ [lwt-newtab-brighttext] .ds-dismiss .ds-dismiss-button:focus {
+ box-shadow: 0 0 0 2px #2A2A2E, 0 0 0 5px rgba(10, 132, 255, 0.5); }
+
+.ds-message {
+ margin: 8px 0 0; }
+ .ds-message .title {
+ display: flex;
+ align-items: center; }
+ .ds-message .title .glyph {
+ width: 16px;
+ height: 16px;
+ margin: 0 6px 0 0;
+ -moz-context-properties: fill;
+ fill: #737373;
+ background-position: center center;
+ background-size: 16px;
+ background-repeat: no-repeat; }
+ [lwt-newtab-brighttext] .ds-message .title .glyph {
+ fill: #D7D7DB; }
+ .ds-message .title .title-text {
+ line-height: 20px;
+ font-size: 13px;
+ color: #737373;
+ font-weight: 600;
+ padding-right: 12px; }
+ [lwt-newtab-brighttext] .ds-message .title .title-text {
+ color: #D7D7DB; }
+ .ds-message .title .link {
+ line-height: 20px;
+ font-size: 13px; }
+ .ds-message .title .link:hover, .ds-message .title .link:focus {
+ text-decoration: underline; }
+
+.impression-observer {
+ position: absolute;
+ top: 0;
+ width: 100%;
+ height: 100%;
+ pointer-events: none; }
+
+.section-empty-state {
+ border: 1px solid var(--newtab-border-secondary-color);
+ border-radius: 4px;
+ display: flex;
+ height: 160px;
+ width: 100%; }
+ .section-empty-state .empty-state-message {
+ color: var(--newtab-text-secondary-color);
+ font-size: 14px;
+ line-height: 20px;
+ text-align: center;
+ margin: auto;
+ max-width: 936px; }
+ .section-empty-state .try-again-button {
+ margin-top: 12px;
+ padding: 6px 32px;
+ border-radius: 2px;
+ border: 0;
+ background: var(--newtab-feed-button-background);
+ color: var(--newtab-feed-button-text);
+ cursor: pointer;
+ position: relative;
+ transition: background 0.2s ease, color 0.2s ease; }
+ .section-empty-state .try-again-button:not(.waiting):focus {
+ box-shadow: 0 0 0 5px rgba(10, 132, 255, 0.3);
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+ [lwt-newtab-brighttext] .section-empty-state .try-again-button:not(.waiting):focus {
+ box-shadow: 0 0 0 5px rgba(69, 161, 255, 0.4);
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+ .section-empty-state .try-again-button:not(.waiting):hover {
+ box-shadow: 0 0 0 5px #D7D7DB;
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+ [lwt-newtab-brighttext] .section-empty-state .try-again-button:not(.waiting):hover {
+ box-shadow: 0 0 0 5px #4A4A4F;
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+ .section-empty-state .try-again-button::after {
+ content: '';
+ height: 20px;
+ width: 20px;
+ animation: spinner 1s linear infinite;
+ opacity: 0;
+ position: absolute;
+ top: 50%;
+ left: 50%;
+ margin: -10px 0 0 -10px;
+ mask-image: url("chrome://activity-stream/content/data/content/assets/spinner.svg");
+ mask-size: 20px;
+ background: var(--newtab-feed-button-spinner); }
+ .section-empty-state .try-again-button.waiting {
+ cursor: initial;
+ background: var(--newtab-feed-button-background-faded);
+ color: var(--newtab-feed-button-text-faded);
+ transition: background 0.2s ease; }
+ .section-empty-state .try-again-button.waiting::after {
+ transition: opacity 0.2s ease;
+ opacity: 1; }
+ .section-empty-state h2 {
+ font-size: 15px;
+ font-weight: 600;
+ margin: 0; }
+ .section-empty-state p {
+ margin: 0; }
+
+@keyframes spinner {
+ to {
+ transform: rotate(360deg); } }
+
+.ds-dismiss-ds-text-promo {
+ max-width: 744px;
+ margin: auto;
+ overflow: hidden; }
+ .ds-dismiss-ds-text-promo.hovering {
+ background: rgba(12, 12, 13, 0.1); }
+ [lwt-newtab-brighttext] .ds-dismiss-ds-text-promo.hovering {
+ background: rgba(12, 12, 13, 0.3); }
+ .ds-dismiss-ds-text-promo .ds-dismiss-button {
+ margin-inline: 0 18px;
+ margin-block: 18px 0; }
+
+.ds-text-promo {
+ max-width: 640px;
+ margin: 0;
+ padding: 18px; }
+ @media (min-width: 610px) {
+ .ds-text-promo {
+ display: flex;
+ margin: 18px 24px;
+ padding: 0 32px 0 0; } }
+ .ds-text-promo .ds-image {
+ width: 40px;
+ height: 40px;
+ flex-shrink: 0;
+ margin: 0 0 18px; }
+ @media (min-width: 610px) {
+ .ds-text-promo .ds-image {
+ margin: 4px 12px 0 0; } }
+ .ds-text-promo .ds-image img {
+ border-radius: 4px; }
+ .ds-text-promo .text {
+ line-height: 24px; }
+ .ds-text-promo h3 {
+ margin: 0;
+ font-weight: 600;
+ font-size: 15px; }
+ [lwt-newtab-brighttext] .ds-text-promo h3 {
+ color: #F9F9FA; }
+ .ds-text-promo .subtitle {
+ font-size: 13px;
+ margin: 0;
+ color: #737373; }
+ [lwt-newtab-brighttext] .ds-text-promo .subtitle {
+ color: #B1B1B3; }
+
+.ds-chevron-link {
+ color: #0060DF;
+ display: inline-block;
+ outline: 0; }
+ .ds-chevron-link:hover {
+ text-decoration: underline; }
+ .ds-chevron-link:active {
+ color: #003EAA; }
+ [lwt-newtab-brighttext] .ds-chevron-link:active {
+ color: #0A84FF; }
+ .ds-chevron-link:active::after {
+ background-color: #003EAA; }
+ [lwt-newtab-brighttext] .ds-chevron-link:active::after {
+ background-color: #0A84FF; }
+ .ds-chevron-link:focus {
+ box-shadow: 0 0 0 2px #FFF, 0 0 0 5px rgba(10, 132, 255, 0.5);
+ border-radius: 2px; }
+ [lwt-newtab-brighttext] .ds-chevron-link:focus {
+ box-shadow: 0 0 0 2px #2A2A2E, 0 0 0 5px rgba(10, 132, 255, 0.5); }
+ .ds-chevron-link::after {
+ content: ' ';
+ mask: url("chrome://activity-stream/content/data/content/assets/glyph-caret-right.svg") 0 -8px no-repeat;
+ background-color: #0060DF;
+ margin: 0 0 0 4px;
+ width: 5px;
+ height: 8px;
+ text-decoration: none;
+ display: inline-block; }
+ [lwt-newtab-brighttext] .ds-chevron-link::after {
+ background-color: #45A1FF; }
+
+.ds-signup {
+ max-width: 300px;
+ margin: 0 auto;
+ padding: 8px;
+ position: relative;
+ text-align: center;
+ font-size: 17px;
+ font-weight: 600; }
+ .ds-signup:hover {
+ background: var(--newtab-element-hover-color);
+ border-radius: 4px; }
+ .ds-signup .icon-mail {
+ height: 40px;
+ width: 40px;
+ margin-inline-end: 8px;
+ fill: #B1B1B3;
+ background-size: 30px;
+ flex-shrink: 0; }
+ .ds-signup .ds-signup-content {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ flex-direction: column; }
+ .ds-signup .ds-signup-content .ds-chevron-link {
+ margin-top: 4px;
+ box-shadow: none;
+ display: block;
+ white-space: nowrap; }
+ @media (min-width: 866px) {
+ .ds-signup {
+ min-width: 756px;
+ width: max-content;
+ text-align: start; }
+ .ds-signup .ds-signup-content {
+ flex-direction: row; }
+ .ds-signup .ds-signup-content .ds-chevron-link {
+ margin-top: 0;
+ display: inline; } }
+
+.ds-privacy-modal .modal-link {
+ display: flex;
+ align-items: center;
+ margin: 0 0 8px;
+ border: 0;
+ padding: 0;
+ color: #0060DF;
+ width: max-content; }
+ .ds-privacy-modal .modal-link:hover {
+ text-decoration: underline;
+ cursor: pointer; }
+ .ds-privacy-modal .modal-link::before {
+ -moz-context-properties: fill;
+ fill: #0060DF;
+ content: '';
+ display: inline-block;
+ width: 16px;
+ height: 16px;
+ margin: 0;
+ margin-inline-end: 8px;
+ background-position: center center;
+ background-repeat: no-repeat;
+ background-size: 16px; }
+ .ds-privacy-modal .modal-link.modal-link-privacy::before {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-info-16.svg"); }
+ .ds-privacy-modal .modal-link.modal-link-manage::before {
+ background-image: url("chrome://global/skin/icons/settings.svg"); }
+
+.ds-privacy-modal p {
+ line-height: 24px; }
+
+.ds-privacy-modal .privacy-notice {
+ max-width: 572px;
+ padding: 40px;
+ margin: auto; }
+
+.ASRouterButton {
+ font-weight: 600;
+ font-size: 14px;
+ white-space: nowrap;
+ border-radius: 2px;
+ border: 0;
+ font-family: inherit;
+ padding: 8px 15px;
+ margin-inline-start: 12px;
+ color: inherit;
+ cursor: pointer; }
+ .tall .ASRouterButton {
+ margin-inline-start: 20px; }
+ .ASRouterButton.test-only {
+ width: 0;
+ height: 0;
+ overflow: hidden;
+ display: block;
+ visibility: hidden; }
+ .ASRouterButton.primary {
+ border: 1px solid var(--newtab-button-primary-color);
+ background-color: var(--newtab-button-primary-color);
+ color: #F9F9FA; }
+ .ASRouterButton.primary:hover {
+ background-color: #003EAA; }
+ .ASRouterButton.primary:active {
+ background-color: #002275; }
+ .ASRouterButton.secondary {
+ background-color: rgba(12, 12, 13, 0.1); }
+ .ASRouterButton.secondary:hover {
+ background-color: rgba(12, 12, 13, 0.2); }
+ .ASRouterButton.secondary:active {
+ background-color: rgba(12, 12, 13, 0.3); }
+ .ASRouterButton.secondary:focus {
+ box-shadow: 0 0 0 1px #0A84FF inset, 0 0 0 1px #0A84FF, 0 0 0 4px rgba(10, 132, 255, 0.3); }
+ .ASRouterButton.slim {
+ background-color: rgba(12, 12, 13, 0.1);
+ margin-inline-start: 0;
+ font-size: 12px;
+ padding: 6px 12px; }
+ .ASRouterButton.slim:hover {
+ background-color: rgba(12, 12, 13, 0.2); }
+
+[lwt-newtab-brighttext] .secondary {
+ background-color: rgba(249, 249, 250, 0.1); }
+ [lwt-newtab-brighttext] .secondary:hover {
+ background-color: rgba(249, 249, 250, 0.2); }
+ [lwt-newtab-brighttext] .secondary:active {
+ background-color: rgba(249, 249, 250, 0.3); }
+
+[lwt-newtab-brighttext] .footer .secondary {
+ background-color: rgba(249, 249, 250, 0.3); }
+ [lwt-newtab-brighttext] .footer .secondary:hover {
+ background-color: rgba(249, 249, 250, 0.4); }
+ [lwt-newtab-brighttext] .footer .secondary:active {
+ background-color: rgba(249, 249, 250, 0.5); }
+
+.SnippetBaseContainer {
+ position: fixed;
+ z-index: 2;
+ bottom: 0;
+ left: 0;
+ right: 0;
+ background-color: var(--newtab-snippets-background-color);
+ color: var(--newtab-text-primary-color);
+ font-size: 14px;
+ line-height: 20px;
+ border-top: 1px solid var(--newtab-snippets-hairline-color);
+ box-shadow: 0 1px 4px 0 rgba(12, 12, 13, 0.2);
+ display: flex;
+ align-items: center; }
+ .SnippetBaseContainer a {
+ cursor: pointer;
+ color: var(--newtab-link-primary-color); }
+ .SnippetBaseContainer a:hover {
+ text-decoration: underline; }
+ [lwt-newtab-brighttext] .SnippetBaseContainer a {
+ font-weight: bold; }
+ .SnippetBaseContainer input[type='checkbox'] {
+ margin-inline-start: 0; }
+ .SnippetBaseContainer .innerWrapper {
+ margin: 0 auto;
+ display: flex;
+ align-items: center;
+ padding: 12px 25px;
+ padding-inline-end: 36px;
+ max-width: 836px; }
+ @media (min-width: 866px) {
+ .SnippetBaseContainer .innerWrapper {
+ padding-inline-end: 25px; } }
+ @media (min-width: 1122px) {
+ .SnippetBaseContainer .innerWrapper {
+ max-width: 1092px; } }
+ .SnippetBaseContainer .blockButton {
+ display: none;
+ background: none;
+ border: 0;
+ position: absolute;
+ top: 50%;
+ inset-inline-end: 12px;
+ height: 16px;
+ width: 16px;
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-dismiss-16.svg");
+ -moz-context-properties: fill;
+ color: inherit;
+ fill: currentColor;
+ opacity: 0.5;
+ margin-top: -8px;
+ padding: 0;
+ cursor: pointer; }
+ .SnippetBaseContainer:hover .blockButton {
+ display: block; }
+ .SnippetBaseContainer .icon {
+ height: 42px;
+ width: 42px;
+ margin-inline-end: 12px;
+ flex-shrink: 0; }
+
+.snippets-preview-banner {
+ font-size: 15px;
+ line-height: 42px;
+ color: rgba(74, 74, 79, 0.7);
+ background: rgba(215, 215, 219, 0.6);
+ text-align: center;
+ position: absolute;
+ top: 0;
+ width: 100%; }
+ .snippets-preview-banner span {
+ vertical-align: middle; }
+
+body:not([lwt-newtab-brighttext]) .icon-dark-theme,
+body:not([lwt-newtab-brighttext]) .icon.icon-dark-theme,
+body:not([lwt-newtab-brighttext]) .scene2Icon .icon-dark-theme {
+ display: none; }
+
+body[lwt-newtab-brighttext] .icon-light-theme,
+body[lwt-newtab-brighttext] .icon.icon-light-theme,
+body[lwt-newtab-brighttext] .scene2Icon .icon-light-theme {
+ display: none; }
+
+.activity-stream.modal-open {
+ overflow: hidden; }
+
+.modalOverlayOuter {
+ background: var(--newtab-overlay-color);
+ height: 100%;
+ position: fixed;
+ top: 0;
+ left: 0;
+ width: 100%;
+ display: none;
+ z-index: 1100;
+ overflow: auto; }
+ .modalOverlayOuter.active {
+ display: flex; }
+
+.modalOverlayInner {
+ min-width: min-content;
+ width: 100%;
+ max-width: 960px;
+ position: relative;
+ margin: auto;
+ background: var(--newtab-modal-color);
+ box-shadow: 0 1px 15px 0 rgba(0, 0, 0, 0.3);
+ border-radius: 4px;
+ display: none;
+ z-index: 1100; }
+ @media (max-width: 960px) {
+ .modalOverlayInner {
+ height: 100%;
+ top: 0;
+ left: 0;
+ box-shadow: none;
+ border-radius: 0; } }
+ .modalOverlayInner.active {
+ display: block; }
+ .modalOverlayInner h2 {
+ color: #4A4A4F;
+ text-align: center;
+ font-weight: 200;
+ margin-top: 30px;
+ font-size: 28px;
+ line-height: 37px;
+ letter-spacing: -0.13px; }
+ @media (max-width: 960px) {
+ .modalOverlayInner h2 {
+ margin-top: 100px; } }
+ @media (max-width: 850px) {
+ .modalOverlayInner h2 {
+ margin-top: 30px; } }
+ .modalOverlayInner .footer {
+ border-top: 1px solid #D7D7DB;
+ border-radius: 4px;
+ height: 70px;
+ width: 100%;
+ position: absolute;
+ bottom: 0;
+ text-align: center;
+ background-color: #FFF; }
+ @media (max-width: 850px) and (max-height: 730px) {
+ .modalOverlayInner .footer {
+ position: sticky; } }
+ @media (max-width: 650px) and (max-height: 600px) {
+ .modalOverlayInner .footer {
+ position: sticky; } }
+ .modalOverlayInner .footer .modalButton {
+ margin-top: 20px;
+ min-width: 150px;
+ height: 30px;
+ padding: 4px 30px 6px;
+ font-size: 15px; }
+ .modalOverlayInner .footer .modalButton:focus, .modalOverlayInner .footer .modalButton.active, .modalOverlayInner .footer .modalButton:hover {
+ box-shadow: 0 0 0 5px #D7D7DB;
+ transition: box-shadow 150ms; }
+
+.below-search-snippet {
+ margin: 0 auto 16px; }
+ .below-search-snippet.withButton {
+ margin: auto;
+ min-height: 60px;
+ background-color: transparent; }
+ .below-search-snippet.withButton .snippet-hover-wrapper {
+ min-height: 60px;
+ border-radius: 4px; }
+ .below-search-snippet.withButton .snippet-hover-wrapper:hover {
+ background-color: var(--newtab-element-hover-color); }
+ .below-search-snippet.withButton .snippet-hover-wrapper:hover .blockButton {
+ display: block;
+ opacity: 1; }
+
+.SimpleBelowSearchSnippet {
+ background-color: transparent;
+ border: 0;
+ box-shadow: none;
+ position: relative;
+ margin: auto;
+ z-index: auto; }
+ @media (min-width: 866px) {
+ .SimpleBelowSearchSnippet {
+ width: 736px; } }
+ .SimpleBelowSearchSnippet.active {
+ background-color: var(--newtab-element-hover-color);
+ border-radius: 4px; }
+ .SimpleBelowSearchSnippet .innerWrapper {
+ align-items: center;
+ background-color: transparent;
+ border-radius: 4px;
+ box-shadow: var(--newtab-card-shadow);
+ flex-direction: column;
+ padding: 16px;
+ text-align: center;
+ width: 100%; }
+ @media (min-width: 610px) {
+ .SimpleBelowSearchSnippet .innerWrapper {
+ align-items: flex-start;
+ background-color: transparent;
+ border-radius: 4px;
+ box-shadow: none;
+ flex-direction: row;
+ padding: 0;
+ text-align: inherit;
+ width: 696px; } }
+ @media (max-width: 865px) {
+ .SimpleBelowSearchSnippet .innerWrapper {
+ margin-inline-start: 0; } }
+ @media (max-width: 609px) {
+ .SimpleBelowSearchSnippet .innerWrapper {
+ margin: auto; } }
+ .SimpleBelowSearchSnippet .blockButton {
+ display: block;
+ inset-inline-end: 10px;
+ opacity: 1;
+ top: 50%; }
+ .SimpleBelowSearchSnippet .blockButton:focus {
+ box-shadow: 0 0 0 1px #0A84FF inset, 0 0 0 1px #0A84FF, 0 0 0 4px rgba(10, 132, 255, 0.3);
+ border-radius: 2px; }
+ .SimpleBelowSearchSnippet .title {
+ font-size: inherit;
+ margin: 0; }
+ .SimpleBelowSearchSnippet .title-inline {
+ display: inline; }
+ .SimpleBelowSearchSnippet .textContainer {
+ margin: 10px;
+ margin-inline-start: 0;
+ padding-inline-end: 20px; }
+ .SimpleBelowSearchSnippet .icon {
+ margin-top: 8px;
+ margin-inline-start: 12px;
+ height: 32px;
+ width: 32px; }
+ @media (min-width: 610px) {
+ .SimpleBelowSearchSnippet .icon {
+ height: 24px;
+ width: 24px; } }
+ @media (max-width: 610px) {
+ .SimpleBelowSearchSnippet .icon {
+ margin: auto; } }
+ .SimpleBelowSearchSnippet.withButton {
+ line-height: 20px;
+ margin-bottom: 10px;
+ min-height: 60px;
+ background-color: transparent; }
+ @media (max-width: 1123px) {
+ .SimpleBelowSearchSnippet.withButton .innerWrapper {
+ margin: 0 40px; } }
+ .SimpleBelowSearchSnippet.withButton .blockButton {
+ display: block;
+ inset-inline-end: -10%;
+ opacity: 0;
+ margin: auto;
+ top: unset; }
+ .SimpleBelowSearchSnippet.withButton .blockButton:focus {
+ opacity: 1;
+ box-shadow: none; }
+ @media (max-width: 1123px) {
+ .SimpleBelowSearchSnippet.withButton .blockButton {
+ inset-inline-end: 2%; } }
+ .SimpleBelowSearchSnippet.withButton .icon {
+ width: 42px;
+ height: 42px;
+ flex-shrink: 0;
+ margin: auto 0;
+ margin-inline-end: 10px; }
+ @media (max-width: 610px) {
+ .SimpleBelowSearchSnippet.withButton .icon {
+ margin: auto; } }
+ .SimpleBelowSearchSnippet.withButton .buttonContainer {
+ margin: auto;
+ margin-inline-end: 0; }
+ @media (max-width: 610px) {
+ .SimpleBelowSearchSnippet.withButton .buttonContainer {
+ margin: auto; } }
+ @media (max-width: 610px) {
+ .SimpleBelowSearchSnippet button {
+ margin: auto; } }
+ .SimpleBelowSearchSnippet .body {
+ display: inline;
+ position: sticky;
+ transform: translateY(-50%);
+ margin: 8px 0 0; }
+ @media (min-width: 610px) {
+ .SimpleBelowSearchSnippet .body {
+ margin: 12px 0; } }
+ .SimpleBelowSearchSnippet .body a {
+ font-weight: 600; }
+
+.SimpleSnippet.tall {
+ padding: 27px 0; }
+
+.SimpleSnippet p em {
+ color: #0C0C0D;
+ font-style: normal;
+ background: #FFE900; }
+
+.SimpleSnippet.bold .donation-form-url,
+.SimpleSnippet.bold .donation-amount, .SimpleSnippet.takeover .donation-form-url,
+.SimpleSnippet.takeover .donation-amount {
+ padding-top: 8px;
+ padding-bottom: 8px; }
+
+.SimpleSnippet.bold {
+ height: 176px; }
+ .SimpleSnippet.bold .body {
+ font-size: 14px;
+ line-height: 20px;
+ margin-bottom: 20px; }
+ .SimpleSnippet.bold .icon {
+ width: 71px;
+ height: 71px; }
+
+.SimpleSnippet.takeover {
+ height: 344px; }
+ .SimpleSnippet.takeover .body {
+ font-size: 16px;
+ line-height: 24px;
+ margin-bottom: 35px; }
+ .SimpleSnippet.takeover .icon {
+ width: 79px;
+ height: 79px; }
+
+.SimpleSnippet .title {
+ font-size: inherit;
+ margin: 0; }
+
+.SimpleSnippet .title-inline {
+ display: inline; }
+
+.SimpleSnippet .titleIcon {
+ background-repeat: no-repeat;
+ background-size: 14px;
+ background-position: center;
+ height: 16px;
+ width: 16px;
+ margin-top: 2px;
+ margin-inline-end: 2px;
+ display: inline-block;
+ vertical-align: top; }
+
+.SimpleSnippet .body {
+ display: inline;
+ margin: 0; }
+
+.SimpleSnippet.tall .icon {
+ margin-inline-end: 20px; }
+
+.SimpleSnippet.takeover .icon, .SimpleSnippet.bold .icon {
+ margin-inline-end: 20px; }
+
+.SimpleSnippet .icon {
+ align-self: flex-start; }
+
+.SimpleSnippet.has-section-header .innerWrapper {
+ flex-wrap: wrap;
+ padding-top: 7px; }
+
+.SimpleSnippet .innerContentWrapper {
+ align-items: center;
+ display: flex; }
+
+.SimpleSnippet .section-header {
+ flex: 0 0 100%;
+ margin-bottom: 10px; }
+
+.SimpleSnippet .section-title {
+ color: var(--newtab-section-header-text-color);
+ display: inline-block;
+ font-size: 13px;
+ font-weight: bold;
+ margin: 0; }
+ .SimpleSnippet .section-title a {
+ color: var(--newtab-section-header-text-color);
+ font-weight: inherit;
+ text-decoration: none; }
+ .SimpleSnippet .section-title .icon {
+ height: 16px;
+ margin-inline-end: 6px;
+ margin-top: -2px;
+ width: 16px; }
+
+.SubmitFormSnippet {
+ flex-direction: column;
+ flex: 1 1 100%;
+ width: 100%; }
+ .SubmitFormSnippet .disclaimerText {
+ margin: 5px 0 0;
+ font-size: 12px;
+ color: var(--newtab-text-secondary-color); }
+ .SubmitFormSnippet p {
+ margin: 0; }
+ .SubmitFormSnippet.send_to_device_snippet {
+ text-align: center; }
+ .SubmitFormSnippet.send_to_device_snippet .message {
+ font-size: 16px;
+ margin-bottom: 20px; }
+ .SubmitFormSnippet.send_to_device_snippet .scene2Title {
+ font-size: 24px;
+ display: block; }
+ .SubmitFormSnippet .ASRouterButton.primary {
+ flex: 1 1 0; }
+ .SubmitFormSnippet .scene2Icon {
+ width: 100%;
+ margin-bottom: 20px; }
+ .SubmitFormSnippet .scene2Icon img {
+ width: 98px;
+ display: inline-block; }
+ .SubmitFormSnippet .scene2Title {
+ font-size: inherit;
+ margin: 0 0 10px;
+ font-weight: bold;
+ display: inline; }
+ .SubmitFormSnippet form {
+ display: flex;
+ flex-direction: column;
+ width: 100%; }
+ .SubmitFormSnippet .message {
+ font-size: 14px;
+ align-self: stretch;
+ flex: 0 0 100%;
+ margin-bottom: 10px; }
+ .SubmitFormSnippet .privacyNotice {
+ font-size: 12px;
+ color: var(--newtab-text-secondary-color);
+ margin-top: 10px;
+ display: flex;
+ flex: 0 0 100%; }
+ .SubmitFormSnippet .innerWrapper {
+ max-width: 736px;
+ flex-wrap: wrap;
+ justify-items: center;
+ padding-top: 40px;
+ padding-bottom: 40px; }
+ .SubmitFormSnippet .footer {
+ width: 100%;
+ margin: 0 auto;
+ text-align: right;
+ background-color: var(--newtab-background-color);
+ padding: 10px 0; }
+ .SubmitFormSnippet .footer .footer-content {
+ margin: 0 auto;
+ max-width: 768px;
+ width: 100%;
+ text-align: right; }
+ [dir='rtl'] .SubmitFormSnippet .footer .footer-content {
+ text-align: left; }
+ .SubmitFormSnippet input.mainInput {
+ border-radius: 2px;
+ background-color: var(--newtab-textbox-background-color);
+ border: 1px solid var(--newtab-textbox-border);
+ padding: 0 8px;
+ height: 100%;
+ font-size: 14px;
+ width: 50%; }
+ .SubmitFormSnippet input.mainInput.clean:invalid, .SubmitFormSnippet input.mainInput.clean:required {
+ box-shadow: none; }
+ .SubmitFormSnippet input.mainInput:focus {
+ border: 1px solid var(--newtab-textbox-focus-color);
+ box-shadow: var(--newtab-textbox-focus-boxshadow); }
+ .SubmitFormSnippet.scene2Alt {
+ text-align: start; }
+ .SubmitFormSnippet.scene2Alt .scene2Icon {
+ flex: 1;
+ margin-bottom: 0; }
+ .SubmitFormSnippet.scene2Alt .message {
+ flex: 5;
+ margin-bottom: 0; }
+ .SubmitFormSnippet.scene2Alt .message p {
+ margin-bottom: 10px; }
+ .SubmitFormSnippet.scene2Alt .section-header {
+ width: 100%; }
+ .SubmitFormSnippet.scene2Alt .section-header .icon {
+ width: 16px;
+ height: 16px; }
+ .SubmitFormSnippet.scene2Alt .section-title {
+ font-size: 13px; }
+ .SubmitFormSnippet.scene2Alt .section-title a {
+ color: var(--newtab-section-header-text-color);
+ font-weight: inherit;
+ text-decoration: none; }
+ .SubmitFormSnippet.scene2Alt .innerWrapper {
+ padding: 0 0 16px; }
+
+.submissionStatus {
+ text-align: center;
+ font-size: 14px;
+ padding: 20px 0; }
+ .submissionStatus .submitStatusTitle {
+ font-size: 20px; }
+
+.EOYSnippetForm {
+ margin: 10px 0 8px;
+ align-self: start;
+ font-size: 14px;
+ display: flex;
+ align-items: center; }
+ .EOYSnippetForm .donation-amount,
+ .EOYSnippetForm .donation-form-url {
+ white-space: nowrap;
+ font-size: 14px;
+ padding: 8px 20px;
+ border-radius: 2px; }
+ .EOYSnippetForm .donation-amount {
+ color: #0C0C0D;
+ margin-inline-end: 18px;
+ border: 1px solid #B1B1B3;
+ padding: 5px 14px;
+ background: #F9F9FA;
+ cursor: pointer; }
+ .EOYSnippetForm input[type='radio'] {
+ opacity: 0;
+ margin-inline-end: -18px; }
+ .EOYSnippetForm input[type='radio']:checked + .donation-amount {
+ background: #737373;
+ color: #FFF;
+ border: 1px solid #4A4A4F; }
+ .EOYSnippetForm input[type='radio']:checked:focus + .donation-amount,
+ .EOYSnippetForm input[type='radio']:not(:checked):focus + .donation-amount {
+ border: 1px dotted var(--newtab-link-primary-color); }
+ .EOYSnippetForm .monthly-checkbox-container {
+ display: flex;
+ width: 100%; }
+ .EOYSnippetForm .donation-form-url {
+ margin-inline-start: 18px;
+ align-self: flex-end;
+ display: flex; }
diff --git a/browser/components/newtab/css/activity-stream-windows.css b/browser/components/newtab/css/activity-stream-windows.css
new file mode 100644
index 0000000000..2a84fbbea9
--- /dev/null
+++ b/browser/components/newtab/css/activity-stream-windows.css
@@ -0,0 +1,4545 @@
+@charset "UTF-8";
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+/* This is the windows variant */
+html {
+ box-sizing: border-box; }
+
+*,
+*::before,
+*::after {
+ box-sizing: inherit; }
+
+*::-moz-focus-inner {
+ border: 0; }
+
+body {
+ margin: 0; }
+
+button,
+input {
+ background-color: inherit;
+ color: inherit;
+ font-family: inherit;
+ font-size: inherit; }
+
+[hidden] {
+ display: none !important; }
+
+body {
+ --newtab-background-color: #F9F9FA;
+ --newtab-border-primary-color: #B1B1B3;
+ --newtab-border-secondary-color: #D7D7DB;
+ --newtab-element-active-color: rgba(215, 215, 219, 0.6);
+ --newtab-element-hover-color: #EDEDF0;
+ --newtab-icon-primary-color: rgba(12, 12, 13, 0.8);
+ --newtab-icon-secondary-color: rgba(12, 12, 13, 0.6);
+ --newtab-icon-tertiary-color: #D7D7DB;
+ --newtab-inner-box-shadow-color: rgba(0, 0, 0, 0.1);
+ --newtab-inner-box-shadow-color-nte: rgba(9, 32, 77, 0.12);
+ --newtab-tile-shadow-secondary: rgba(29, 17, 51, 0.2);
+ --newtab-link-primary-color: #0060DF;
+ --newtab-link-secondary-color: #008EA4;
+ --newtab-text-conditional-color: #4A4A4F;
+ --newtab-text-primary-color: #0C0C0D;
+ --newtab-text-secondary-color: #737373;
+ --newtab-textbox-background-color: #FFF;
+ --newtab-textbox-border: rgba(12, 12, 13, 0.2);
+ --newtab-textbox-focus-color: #0060DF;
+ --newtab-textbox-focus-boxshadow: 0 0 0 1px #0060DF, 0 0 0 4px rgba(0, 96, 223, 0.3);
+ --newtab-background-button-color: rgba(223, 223, 223, 0.5);
+ --newtab-background-button-text-color: #484848;
+ --newtab-background-button-hover-color: rgba(196, 196, 196, 0.5);
+ --newtab-background-button-active-color: rgba(151, 151, 151, 0.5);
+ --newtab-button-primary-color: #0060DF;
+ --newtab-button-secondary-color: inherit;
+ --newtab-feed-button-background: #EDEDF0;
+ --newtab-feed-button-text: #0C0C0D;
+ --newtab-feed-button-background-faded: rgba(237, 237, 240, 0.6);
+ --newtab-feed-button-text-faded: rgba(12, 12, 13, 0);
+ --newtab-feed-button-spinner: #737373;
+ --newtab-contextmenu-background-color: #F9F9FA;
+ --newtab-contextmenu-button-color: #FFF;
+ --newtab-modal-color: #FFF;
+ --newtab-overlay-color: rgba(237, 237, 240, 0.8);
+ --newtab-section-header-text-color: #737373;
+ --newtab-section-navigation-text-color: #737373;
+ --newtab-section-active-contextmenu-color: #0C0C0D;
+ --newtab-search-border-color: transparent;
+ --newtab-search-dropdown-color: #FFF;
+ --newtab-search-dropdown-header-color: #F9F9FA;
+ --newtab-search-header-background-color: rgba(249, 249, 250, 0.95);
+ --newtab-search-icon-color: rgba(12, 12, 13, 0.4);
+ --newtab-search-wordmark-color: #363959;
+ --newtab-topsites-background-color: #FFF;
+ --newtab-topsites-icon-shadow: inset 0 0 0 1px var(--newtab-inner-box-shadow-color);
+ --newtab-topsites-label-color: inherit;
+ --newtab-topsites-outer-card-hover: rgba(0, 0, 0, 0.05);
+ --newtab-topsites-context-menu-hover: rgba(0, 0, 0, 0.05);
+ --newtab-card-active-outline-color: #D7D7DB;
+ --newtab-card-background-color: #FFF;
+ --newtab-card-hairline-color: rgba(0, 0, 0, 0.1);
+ --newtab-card-placeholder-color: #D7D7DB;
+ --newtab-card-shadow: 0 1px 4px 0 rgba(12, 12, 13, 0.1);
+ --newtab-snippets-background-color: #FFF;
+ --newtab-snippets-hairline-color: transparent;
+ --newtab-background-primary-text-color: #151515;
+ --newtab-focus-outline: rgba(0, 96, 223, 0.25);
+ --newtab-focus-border: #0060DF;
+ --newtab-focus-border-selected: rgba(0, 0, 0, 0.15);
+ --newtab-seperator-line-color: #E1E0E6;
+ --newtab-primary-action-background: #0060DF;
+ --newtab-primary-action-background-off: #E9E9E9;
+ --customize-menu-primary-text-color: #20123A;
+ --customize-menu-check-fill: #FFF;
+ --customize-menu-background: #FFF;
+ --customize-menu-secondary-action-background: #F9F9FA;
+ --customize-menu-secondary-action-background-hover: #EDEDF0;
+ --customize-menu-secondary-action-background-active: #E2E2E6;
+ --customize-menu-seperator-line-color: #E1E0E6;
+ --customize-menu-first-shadow: rgba(9, 32, 77, 0.12);
+ --customize-menu-second-shadow: rgba(29, 17, 51, 0.12);
+ --customize-menu-primary-action-text: #FFF;
+ --customize-menu-line-color: #716F87;
+ --newtab-search-first-shadow: rgba(9, 32, 77, 0.12);
+ --newtab-search-second-shadow: rgba(29, 17, 51, 0.12);
+ --newtab-search-text-color: #585165;
+ --newtab-card-first-shadow: rgba(9, 32, 77, 0.12);
+ --newtab-card-second-shadow: rgba(29, 17, 51, 0.12);
+ --newtab-wordmark-color: #20123A; }
+ body[lwt-newtab-brighttext] {
+ --newtab-background-color: #2A2A2E;
+ --newtab-border-primary-color: rgba(249, 249, 250, 0.8);
+ --newtab-border-secondary-color: rgba(249, 249, 250, 0.1);
+ --newtab-button-primary-color: #0060DF;
+ --newtab-button-secondary-color: #38383D;
+ --newtab-element-active-color: rgba(249, 249, 250, 0.2);
+ --newtab-element-hover-color: rgba(249, 249, 250, 0.1);
+ --newtab-icon-primary-color: rgba(249, 249, 250, 0.8);
+ --newtab-icon-secondary-color: rgba(249, 249, 250, 0.4);
+ --newtab-icon-tertiary-color: rgba(249, 249, 250, 0.4);
+ --newtab-inner-box-shadow-color: rgba(249, 249, 250, 0.2);
+ --newtab-inner-box-shadow-color-nte: rgba(21, 20, 26, 0.5);
+ --newtab-tile-shadow-secondary: rgba(21, 20, 26, 0.75);
+ --newtab-link-primary-color: #45A1FF;
+ --newtab-link-secondary-color: #50BCB6;
+ --newtab-text-conditional-color: #F9F9FA;
+ --newtab-text-primary-color: #F9F9FA;
+ --newtab-text-secondary-color: rgba(249, 249, 250, 0.8);
+ --newtab-textbox-background-color: #38383D;
+ --newtab-textbox-border: rgba(249, 249, 250, 0.2);
+ --newtab-textbox-focus-color: #45A1FF;
+ --newtab-textbox-focus-boxshadow: 0 0 0 1px #45A1FF, 0 0 0 4px rgba(69, 161, 255, 0.3);
+ --newtab-background-button-color: rgba(80, 80, 80, 0.5);
+ --newtab-background-button-text-color: #CDCDD4;
+ --newtab-background-button-hover-color: rgba(114, 114, 114, 0.5);
+ --newtab-background-button-active-color: rgba(173, 173, 173, 0.5);
+ --newtab-feed-button-background: #38383D;
+ --newtab-feed-button-text: #F9F9FA;
+ --newtab-feed-button-background-faded: rgba(56, 56, 61, 0.6);
+ --newtab-feed-button-text-faded: rgba(249, 249, 250, 0);
+ --newtab-feed-button-spinner: #D7D7DB;
+ --newtab-contextmenu-background-color: #4A4A4F;
+ --newtab-contextmenu-button-color: #2A2A2E;
+ --newtab-modal-color: #2A2A2E;
+ --newtab-overlay-color: rgba(12, 12, 13, 0.8);
+ --newtab-section-header-text-color: rgba(249, 249, 250, 0.8);
+ --newtab-section-navigation-text-color: rgba(249, 249, 250, 0.8);
+ --newtab-section-active-contextmenu-color: #FFF;
+ --newtab-search-border-color: rgba(249, 249, 250, 0.2);
+ --newtab-search-dropdown-color: #38383D;
+ --newtab-search-dropdown-header-color: #4A4A4F;
+ --newtab-search-header-background-color: rgba(42, 42, 46, 0.95);
+ --newtab-search-icon-color: rgba(249, 249, 250, 0.6);
+ --newtab-search-wordmark-color: #FFF;
+ --newtab-topsites-background-color: #38383D;
+ --newtab-topsites-icon-shadow: none;
+ --newtab-topsites-label-color: rgba(249, 249, 250, 0.8);
+ --newtab-topsites-outer-card-hover: rgba(180, 180, 180, 0.1);
+ --newtab-topsites-context-menu-hover: rgba(180, 180, 180, 0.1);
+ --newtab-card-active-outline-color: #4A4A4F;
+ --newtab-card-background-color: #38383D;
+ --newtab-card-hairline-color: rgba(249, 249, 250, 0.1);
+ --newtab-card-placeholder-color: #4A4A4F;
+ --newtab-card-shadow: 0 1px 8px 0 rgba(12, 12, 13, 0.2);
+ --newtab-snippets-background-color: #38383D;
+ --newtab-snippets-hairline-color: rgba(255, 255, 255, 0.1);
+ --newtab-background-primary-text-color: #CDCDD4;
+ --newtab-focus-outline: rgba(80, 145, 241, 0.5);
+ --newtab-focus-border: #B5D3FF;
+ --newtab-focus-border-selected: #B5D3FF;
+ --newtab-primary-action-background: #4484E2;
+ --newtab-primary-action-background-off: #6A6A6F;
+ --newtab-seperator-line-color: #53515F;
+ --customize-menu-primary-text-color: #E0E0E6;
+ --customize-menu-check-fill: #E0E0E6;
+ --customize-menu-background: #38383D;
+ --customize-menu-secondary-action-background: #515156;
+ --customize-menu-secondary-action-background-hover: #606065;
+ --customize-menu-secondary-action-background-active: #6F6F74;
+ --customize-menu-seperator-line-color: #53515F;
+ --customize-menu-first-shadow: rgba(21, 20, 26, 0.5);
+ --customize-menu-second-shadow: rgba(21, 20, 26, 0.75);
+ --customize-menu-primary-action-text: #E0E0E6;
+ --customize-menu-line-color: #B9B7CC;
+ --newtab-search-first-shadow: rgba(21, 20, 26, 0.5);
+ --newtab-search-second-shadow: rgba(21, 20, 26, 0.75);
+ --newtab-search-text-color: #B1B1BD;
+ --newtab-card-first-shadow: rgba(21, 20, 26, 0.5);
+ --newtab-card-second-shadow: rgba(21, 20, 26, 0.75);
+ --newtab-wordmark-color: #FFF; }
+
+.icon {
+ background-position: center center;
+ background-repeat: no-repeat;
+ background-size: 16px;
+ -moz-context-properties: fill;
+ display: inline-block;
+ color: var(--newtab-icon-primary-color);
+ fill: currentColor;
+ height: 16px;
+ vertical-align: middle;
+ width: 16px; }
+ .icon.icon-spacer {
+ margin-inline-end: 8px; }
+ .icon.icon-small-spacer {
+ margin-inline-end: 6px; }
+ .icon.icon-button-style {
+ fill: var(--newtab-icon-secondary-color);
+ border: 0; }
+ .icon.icon-button-style:focus, .icon.icon-button-style:hover {
+ fill: var(--newtab-text-primary-color); }
+ .icon.icon-bookmark-added {
+ background-image: url("chrome://browser/skin/bookmark.svg"); }
+ .icon.icon-bookmark-hollow {
+ background-image: url("chrome://browser/skin/bookmark-hollow.svg"); }
+ .icon.icon-clear-input {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-cancel-16.svg"); }
+ .icon.icon-delete {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-delete-16.svg"); }
+ .icon.icon-search {
+ background-image: url("chrome://browser/skin/search-glass.svg"); }
+ .icon.icon-modal-delete {
+ flex-shrink: 0;
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-modal-delete-32.svg");
+ background-size: 32px;
+ height: 32px;
+ width: 32px; }
+ .icon.icon-mail {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-mail-16.svg"); }
+ .icon.icon-dismiss {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-dismiss-16.svg"); }
+ .icon.icon-info {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-info-16.svg"); }
+ .icon.icon-new-window {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-newWindow-16.svg"); }
+ .icon.icon-new-window:dir(rtl) {
+ transform: scaleX(-1); }
+ .icon.icon-new-window-private {
+ background-image: url("chrome://browser/skin/privateBrowsing.svg"); }
+ .icon.icon-settings {
+ background-image: url("chrome://global/skin/icons/settings.svg"); }
+ .icon.icon-pin {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-pin-16.svg"); }
+ .icon.icon-pin:dir(rtl) {
+ transform: scaleX(-1); }
+ .icon.icon-unpin {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-unpin-16.svg"); }
+ .icon.icon-unpin:dir(rtl) {
+ transform: scaleX(-1); }
+ .icon.icon-edit {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-edit-16.svg"); }
+ .icon.icon-pocket {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-pocket-16.svg"); }
+ .icon.icon-pocket-save {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-pocket-save-16.svg"); }
+ .icon.icon-pocket-delete {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-pocket-delete-16.svg"); }
+ .icon.icon-pocket-archive {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-pocket-archive-16.svg"); }
+ .icon.icon-history-item {
+ background-image: url("chrome://browser/skin/history.svg"); }
+ .icon.icon-trending {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-trending-16.svg");
+ transform: translateY(2px); }
+ .icon.icon-now {
+ background-image: url("chrome://browser/skin/history.svg"); }
+ .icon.icon-topsites {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-topsites-16.svg"); }
+ .icon.icon-pin-small {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-pin-12.svg");
+ background-size: 12px;
+ height: 12px;
+ width: 12px; }
+ .icon.icon-pin-small:dir(rtl) {
+ transform: scaleX(-1); }
+ .icon.icon-check {
+ background-image: url("chrome://global/skin/icons/check.svg"); }
+ .icon.icon-download {
+ background-image: url("chrome://browser/skin/downloads/download-icons.svg#arrow-with-bar"); }
+ .icon.icon-copy {
+ background-image: url("chrome://browser/skin/edit-copy.svg"); }
+ .icon.icon-open-file {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-open-file-16.svg"); }
+ .icon.icon-webextension {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-webextension-16.svg"); }
+ .icon.icon-highlights {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-highlights-16.svg"); }
+ .icon.icon-arrowhead-down {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-arrowhead-down-16.svg"); }
+ .icon.icon-arrowhead-down-small {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-arrowhead-down-12.svg");
+ background-size: 12px;
+ height: 12px;
+ width: 12px; }
+ .icon.icon-arrowhead-forward-small {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-arrowhead-down-12.svg");
+ background-size: 12px;
+ height: 12px;
+ transform: rotate(-90deg);
+ width: 12px; }
+ .icon.icon-arrowhead-forward-small:dir(rtl) {
+ transform: rotate(90deg); }
+ .icon.icon-arrowhead-up {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-arrowhead-down-16.svg");
+ transform: rotate(180deg); }
+ .icon.icon-add {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-add-16.svg"); }
+ .icon.icon-minimize {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-minimize-16.svg"); }
+ .icon.icon-maximize {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-maximize-16.svg"); }
+ .icon.icon-arrow {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-arrow.svg"); }
+
+html {
+ height: 100%; }
+
+body,
+#root {
+ min-height: 100vh; }
+
+#root {
+ position: relative; }
+
+body {
+ background-color: var(--newtab-background-color);
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Ubuntu', 'Helvetica Neue', sans-serif;
+ font-size: 16px; }
+
+.no-scroll {
+ overflow: hidden; }
+
+h1,
+h2 {
+ font-weight: normal; }
+
+a {
+ text-decoration: none; }
+
+.inner-border {
+ border: 1px solid var(--newtab-border-secondary-color);
+ border-radius: 3px;
+ height: 100%;
+ left: 0;
+ pointer-events: none;
+ position: absolute;
+ top: 0;
+ width: 100%;
+ z-index: 100; }
+
+@keyframes fadeIn {
+ from {
+ opacity: 0; }
+ to {
+ opacity: 1; } }
+
+.show-on-init {
+ opacity: 0;
+ transition: opacity 0.2s ease-in; }
+ .show-on-init.on {
+ animation: fadeIn 0.2s;
+ opacity: 1; }
+
+.actions {
+ border-top: 1px solid var(--newtab-border-secondary-color);
+ display: flex;
+ flex-direction: row;
+ flex-wrap: wrap;
+ justify-content: flex-start;
+ margin: 0;
+ padding: 15px 25px 0; }
+
+.button,
+.actions button {
+ background-color: var(--newtab-button-secondary-color);
+ border: 1px solid var(--newtab-border-primary-color);
+ border-radius: 4px;
+ color: inherit;
+ cursor: pointer;
+ margin-bottom: 15px;
+ padding: 10px 30px;
+ white-space: nowrap; }
+ .button:hover:not(.dismiss), .button:focus:not(.dismiss),
+ .actions button:hover:not(.dismiss),
+ .actions button:focus:not(.dismiss) {
+ box-shadow: 0 0 0 5px var(--newtab-card-active-outline-color);
+ transition: box-shadow 150ms; }
+ .button.dismiss,
+ .actions button.dismiss {
+ background-color: transparent;
+ border: 0;
+ padding: 0;
+ text-decoration: underline; }
+ .button.primary, .button.done,
+ .actions button.primary,
+ .actions button.done {
+ background-color: var(--newtab-button-primary-color);
+ border: solid 1px var(--newtab-button-primary-color);
+ color: #FFF;
+ margin-inline-start: auto; }
+
+input[type='text'], input[type='search'] {
+ border-radius: 3px; }
+
+.clamp {
+ -webkit-box-orient: vertical;
+ display: -webkit-box;
+ overflow: hidden;
+ word-break: break-word; }
+
+.a11y-link-button {
+ border: 0;
+ padding: 0;
+ cursor: pointer;
+ text-align: unset;
+ color: var(--newtab-link-primary-color); }
+ .a11y-link-button:hover, .a11y-link-button:focus {
+ text-decoration: underline; }
+
+.outer-wrapper {
+ color: var(--newtab-text-primary-color);
+ display: flex;
+ flex-grow: 1;
+ min-height: 100vh;
+ padding: 30px 32px 32px; }
+ .outer-wrapper.ds-outer-wrapper-breakpoint-override {
+ padding: 30px 0 32px; }
+ @media (min-width: 610px) {
+ .outer-wrapper.ds-outer-wrapper-breakpoint-override {
+ padding: 30px 32px 32px; } }
+ .outer-wrapper.only-search {
+ display: block;
+ padding-top: 134px; }
+ .outer-wrapper a {
+ color: var(--newtab-link-primary-color); }
+
+main {
+ margin: auto;
+ width: 274px;
+ padding-bottom: 68px; }
+ main section {
+ margin-bottom: 20px;
+ position: relative; }
+ .hide-main main {
+ visibility: hidden; }
+ @media (min-width: 610px) {
+ main {
+ width: 530px; } }
+ @media (min-width: 866px) {
+ main {
+ width: 786px; } }
+ @media (min-width: 1122px) {
+ main {
+ width: 1042px; } }
+
+.below-search-snippet.withButton {
+ margin: auto;
+ width: 100%; }
+
+.ds-outer-wrapper-search-alignment main {
+ margin: 0 auto; }
+
+.ds-outer-wrapper-breakpoint-override main {
+ width: 266px;
+ padding-bottom: 68px; }
+ @media (min-width: 610px) {
+ .ds-outer-wrapper-breakpoint-override main {
+ width: 510px; } }
+ @media (min-width: 866px) {
+ .ds-outer-wrapper-breakpoint-override main {
+ width: 746px; } }
+ @media (min-width: 1122px) {
+ .ds-outer-wrapper-breakpoint-override main {
+ width: 986px; } }
+
+.base-content-fallback {
+ height: 100vh; }
+
+
+.body-wrapper .section-title,
+.body-wrapper .sections-list .section:last-of-type,
+.body-wrapper .topics {
+ opacity: 0; }
+
+
+.body-wrapper.on .section-title,
+.body-wrapper.on .sections-list .section:last-of-type,
+.body-wrapper.on .topics {
+ opacity: 1; }
+
+.non-collapsible-section {
+ padding: 0 25px; }
+
+.prefs-button button {
+ background-color: transparent;
+ border: 0;
+ border-radius: 2px;
+ cursor: pointer;
+ inset-inline-end: 15px;
+ padding: 15px;
+ position: fixed;
+ top: 15px;
+ z-index: 1000; }
+ .prefs-button button:hover, .prefs-button button:focus {
+ background-color: var(--newtab-element-hover-color); }
+ .prefs-button button:active {
+ background-color: var(--newtab-element-active-color); }
+
+@media (max-height: 701px) {
+ .personalize-button {
+ position: absolute;
+ top: 16px;
+ inset-inline-end: 16px; } }
+
+@media (min-height: 700px) {
+ .personalize-button {
+ position: fixed;
+ top: 16px;
+ inset-inline-end: 16px;
+ z-index: 1000; } }
+
+.personalize-button {
+ font-size: 12px;
+ font-weight: 600;
+ border: 0;
+ border-radius: 4px;
+ background-color: var(--newtab-background-button-color);
+ color: var(--newtab-background-button-text-color);
+ padding: 3px 10px;
+ min-height: 32px;
+ max-width: 117px; }
+ .personalize-button:hover {
+ background-color: var(--newtab-background-button-hover-color); }
+ .personalize-button:active {
+ background-color: var(--newtab-background-button-active-color); }
+ .personalize-button:focus-visible {
+ border: 0;
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-focus-outline), 0 0 0 1px var(--newtab-focus-border); }
+
+.as-error-fallback {
+ align-items: center;
+ border-radius: 3px;
+ box-shadow: inset 0 0 0 1px var(--newtab-inner-box-shadow-color);
+ color: var(--newtab-text-conditional-color);
+ display: flex;
+ flex-direction: column;
+ font-size: 12px;
+ justify-content: center;
+ justify-items: center;
+ line-height: 1.5; }
+ .as-error-fallback.borderless-error {
+ box-shadow: none; }
+ .as-error-fallback a {
+ color: var(--newtab-text-conditional-color);
+ text-decoration: underline; }
+
+.top-sites-list {
+ list-style: none;
+ margin: 0 -16px;
+ padding: 0; }
+ @media (max-width: 610px) {
+ .top-sites-list > :nth-child(2n+1) .context-menu {
+ margin-inline-end: auto;
+ margin-inline-start: auto;
+ inset-inline-end: auto;
+ inset-inline-start: -32px; }
+ .top-sites-list > :nth-child(2n) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+ @media (min-width: 610px) and (max-width: 866px) {
+ .top-sites-list :nth-child(4n) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+ @media (min-width: 610px) and (max-width: 834px) {
+ .top-sites-list :nth-child(4n+3) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+ @media (min-width: 866px) and (max-width: 1314px) {
+ .top-sites-list :nth-child(6n) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+ @media (min-width: 866px) and (max-width: 1090px) {
+ .top-sites-list :nth-child(6n+5) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+ @media (min-width: 1122px) and (max-width: 1570px) {
+ .top-sites-list :nth-child(8n) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+ @media (min-width: 1122px) and (max-width: 1346px) {
+ .top-sites-list :nth-child(8n+7) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+ .top-sites-list .hide-for-narrow {
+ display: none; }
+ @media (min-width: 610px) {
+ .top-sites-list .hide-for-narrow {
+ display: inline-block; } }
+ @media (min-width: 866px) {
+ .top-sites-list .hide-for-narrow {
+ display: none; } }
+ @media (min-width: 1122px) {
+ .top-sites-list .hide-for-narrow {
+ display: inline-block; } }
+
+.top-site-outer {
+ padding: 0 16px;
+ display: inline-block; }
+ .top-site-outer .top-site-inner {
+ position: relative; }
+ .top-site-outer .top-site-inner > a {
+ color: inherit;
+ display: block;
+ outline: none; }
+ .top-site-outer .tile {
+ border-radius: 4px;
+ box-shadow: inset 0 0 0 1px var(--newtab-inner-box-shadow-color), var(--newtab-card-shadow);
+ cursor: pointer;
+ position: relative;
+ align-items: center;
+ color: var(--newtab-text-secondary-color);
+ display: flex;
+ font-size: 32px;
+ font-weight: 200;
+ justify-content: center;
+ text-transform: uppercase; }
+ .top-site-outer .tile .icon-wrapper {
+ border-radius: 4px;
+ width: 48px;
+ height: 48px;
+ overflow: hidden;
+ position: relative;
+ display: flex;
+ align-items: center;
+ justify-content: center; }
+ .top-site-outer .tile .icon-wrapper.letter-fallback::before {
+ content: attr(data-fallback);
+ text-transform: uppercase;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ font-size: 64px;
+ font-weight: 800;
+ transform: rotate(-10deg);
+ top: 6px;
+ position: relative;
+ color: #FFF; }
+ .top-site-outer .top-site-icon {
+ background-color: var(--newtab-topsites-background-color);
+ background-position: center center;
+ background-repeat: no-repeat;
+ border-radius: 4px;
+ position: absolute; }
+ .top-site-outer .rich-icon {
+ background-size: cover;
+ height: 100%;
+ inset-inline-start: 0;
+ top: 0;
+ width: 100%; }
+ .top-site-outer .default-icon,
+ .top-site-outer .search-topsite {
+ background-size: 32px;
+ height: 42px;
+ width: 42px;
+ align-items: center;
+ display: flex;
+ font-size: 20px;
+ justify-content: center; }
+ .top-site-outer .default-icon[data-fallback]::before,
+ .top-site-outer .search-topsite[data-fallback]::before {
+ content: attr(data-fallback); }
+ .top-site-outer .search-topsite {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-search-16.svg");
+ background-size: 26px;
+ background-color: #0060DF;
+ border-radius: 42px;
+ -moz-context-properties: fill;
+ fill: #FFF;
+ box-shadow: var(--newtab-card-shadow);
+ transition-duration: 150ms;
+ transition-property: background-size, bottom, inset-inline-end, height, width;
+ height: 42px;
+ width: 42px;
+ bottom: -6px;
+ inset-inline-end: -6px; }
+ .top-site-outer .title {
+ color: var(--newtab-topsites-label-color);
+ font: message-box;
+ padding-top: 4px;
+ text-align: center;
+ position: relative; }
+ .top-site-outer .title .icon {
+ fill: var(--newtab-icon-tertiary-color); }
+ .top-site-outer .title span {
+ display: block;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap; }
+ .top-site-outer .title .sponsored-label {
+ color: #737373;
+ font-size: 0.9em; }
+ .top-site-outer .title:not(.sponsored) .sponsored-label {
+ visibility: hidden; }
+ .top-site-outer.search-shortcut .rich-icon {
+ background-color: #FFF; }
+ .top-site-outer .edit-button {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-edit-16.svg"); }
+ .top-site-outer.placeholder .screenshot {
+ display: none; }
+ .top-site-outer.dragged .tile {
+ background: #EDEDF0;
+ box-shadow: none; }
+ .top-site-outer.dragged .tile *, .top-site-outer.dragged .tile::before {
+ display: none; }
+ .top-site-outer.dragged .title {
+ visibility: hidden; }
+
+.edit-topsites-wrapper .modal {
+ box-shadow: 0 1px 4px 0 rgba(12, 12, 13, 0.2);
+ left: 0;
+ margin: 0 auto;
+ max-height: calc(100% - 40px);
+ position: fixed;
+ right: 0;
+ top: 40px;
+ width: 274px; }
+ @media (min-width: 610px) {
+ .edit-topsites-wrapper .modal {
+ width: 530px; } }
+ @media (min-width: 866px) {
+ .edit-topsites-wrapper .modal {
+ width: 786px; } }
+
+.topsite-form .section-title {
+ font-size: 16px;
+ margin: 0 0 16px; }
+
+.topsite-form .form-input-container {
+ max-width: 492px;
+ margin: 0 auto;
+ padding: 32px; }
+ .topsite-form .form-input-container .top-site-outer {
+ pointer-events: none; }
+
+.topsite-form .search-shortcuts-container {
+ max-width: 700px;
+ margin: 0 auto;
+ padding: 32px; }
+ .topsite-form .search-shortcuts-container > div {
+ margin-inline-end: -39px; }
+ .topsite-form .search-shortcuts-container .top-site-outer {
+ margin-inline-start: 0;
+ margin-inline-end: 39px; }
+
+.topsite-form .top-site-outer {
+ padding: 0;
+ margin: 24px 0 0;
+ margin-inline-start: 32px; }
+
+.topsite-form .fields-and-preview {
+ display: flex; }
+
+.topsite-form label {
+ font-size: 13px; }
+
+.topsite-form .form-wrapper {
+ width: 100%; }
+ .topsite-form .form-wrapper .field {
+ position: relative; }
+ .topsite-form .form-wrapper .field .icon-clear-input {
+ position: absolute;
+ transform: translateY(-50%);
+ top: 50%;
+ inset-inline-end: 8px; }
+ .topsite-form .form-wrapper .url input:dir(ltr) {
+ padding-right: 32px; }
+ .topsite-form .form-wrapper .url input:dir(rtl) {
+ padding-left: 32px; }
+ .topsite-form .form-wrapper .url input:dir(rtl):not(:placeholder-shown) {
+ direction: ltr;
+ text-align: right; }
+ .topsite-form .form-wrapper .enable-custom-image-input {
+ display: inline-block;
+ font-size: 13px;
+ margin-top: 4px;
+ cursor: pointer; }
+ .topsite-form .form-wrapper .custom-image-input-container {
+ margin-top: 4px; }
+ .topsite-form .form-wrapper .custom-image-input-container .loading-container {
+ width: 16px;
+ height: 16px;
+ overflow: hidden;
+ position: absolute;
+ transform: translateY(-50%);
+ top: 50%;
+ inset-inline-end: 8px; }
+ .topsite-form .form-wrapper .custom-image-input-container .loading-animation {
+ width: 960px;
+ height: 16px;
+ -moz-context-properties: fill;
+ fill: #0A84FF;
+ background-image: url("chrome://browser/skin/tabbrowser/loading.svg");
+ animation: tab-throbber-animation 1.05s steps(60) infinite; }
+
+@keyframes tab-throbber-animation {
+ 100% {
+ transform: translateX(-960px); } }
+
+@keyframes tab-throbber-animation-rtl {
+ 100% {
+ transform: translateX(960px); } }
+ .topsite-form .form-wrapper .custom-image-input-container .loading-animation:dir(rtl) {
+ animation-name: tab-throbber-animation-rtl; }
+ .topsite-form .form-wrapper input[type='text'] {
+ background-color: var(--newtab-textbox-background-color);
+ border: 1px solid var(--newtab-textbox-border);
+ margin: 8px 0;
+ padding: 0 8px;
+ height: 32px;
+ width: 100%;
+ font-size: 15px; }
+ .topsite-form .form-wrapper input[type='text'][disabled] {
+ border: 1px solid var(--newtab-textbox-border);
+ box-shadow: none;
+ opacity: 0.4; }
+ .topsite-form .form-wrapper .invalid input[type='text'] {
+ border: 1px solid #D70022;
+ box-shadow: 0 0 0 1px #D70022, 0 0 0 4px rgba(215, 0, 34, 0.3); }
+ .topsite-form .form-wrapper .error-tooltip {
+ animation: fade-up-tt 450ms;
+ background: #D70022;
+ border-radius: 2px;
+ color: #FFF;
+ inset-inline-start: 3px;
+ padding: 5px 12px;
+ position: absolute;
+ top: 44px;
+ z-index: 1; }
+ .topsite-form .form-wrapper .error-tooltip::before {
+ background: #D70022;
+ bottom: -8px;
+ content: '.';
+ height: 16px;
+ inset-inline-start: 12px;
+ position: absolute;
+ text-indent: -999px;
+ top: -7px;
+ transform: rotate(45deg);
+ white-space: nowrap;
+ width: 16px;
+ z-index: -1; }
+
+.topsite-form .actions {
+ justify-content: flex-end; }
+ .topsite-form .actions button {
+ margin-inline-start: 10px;
+ margin-inline-end: 0; }
+
+@media (max-width: 610px) {
+ .topsite-form .fields-and-preview {
+ flex-direction: column; }
+ .topsite-form .fields-and-preview .top-site-outer {
+ margin-inline-start: 0; } }
+
+.topsite-form .title {
+ user-select: none; }
+
+.topsite-form [type='checkbox']:not(:checked),
+.topsite-form [type='checkbox']:checked {
+ inset-inline-start: -9999px;
+ position: absolute; }
+
+.topsite-form [type='checkbox']:not(:checked) + label,
+.topsite-form [type='checkbox']:checked + label {
+ cursor: pointer;
+ display: block;
+ position: relative; }
+
+.topsite-form [type='checkbox']:not(:checked) + label::before,
+.topsite-form [type='checkbox']:checked + label::before {
+ background: var(--newtab-background-color);
+ border: 1px solid var(--newtab-textbox-border);
+ border-radius: 3px;
+ content: '';
+ height: 21px;
+ left: -8px;
+ position: absolute;
+ top: -8px;
+ width: 21px;
+ z-index: 1; }
+ [dir='rtl'] .topsite-form [type='checkbox']:not(:checked) + label::before, [dir='rtl']
+ .topsite-form [type='checkbox']:checked + label::before {
+ left: auto;
+ right: -8px; }
+
+.topsite-form [type='checkbox']:not(:checked) + label::after,
+.topsite-form [type='checkbox']:checked + label::after {
+ background: url("chrome://global/skin/icons/check.svg") no-repeat center center;
+ content: '';
+ height: 21px;
+ left: -8px;
+ position: absolute;
+ top: -8px;
+ width: 21px;
+ -moz-context-properties: fill;
+ fill: var(--newtab-link-primary-color);
+ z-index: 2; }
+ [dir='rtl'] .topsite-form [type='checkbox']:not(:checked) + label::after, [dir='rtl']
+ .topsite-form [type='checkbox']:checked + label::after {
+ left: auto;
+ right: -8px; }
+
+.topsite-form [type='checkbox']:checked + label .tile {
+ box-shadow: 0 0 0 2px var(--newtab-link-primary-color); }
+
+.topsite-form [type='checkbox']:not(:checked) + label::after {
+ opacity: 0; }
+
+.topsite-form [type='checkbox']:checked + label::after {
+ opacity: 1; }
+
+.topsite-form [type='checkbox']:checked:focus + label::before,
+.topsite-form [type='checkbox']:not(:checked):focus + label::before {
+ border: 1px dotted var(--newtab-link-primary-color); }
+
+.outer-wrapper:not(.newtab-experience) .top-site-outer .context-menu-button {
+ background-clip: padding-box;
+ background-color: var(--newtab-contextmenu-button-color);
+ background-image: url("chrome://global/skin/icons/more.svg");
+ background-position: 55%;
+ border: 1px solid var(--newtab-border-primary-color);
+ border-radius: 100%;
+ box-shadow: 0 2px rgba(12, 12, 13, 0.1);
+ cursor: pointer;
+ fill: var(--newtab-icon-primary-color);
+ height: 27px;
+ inset-inline-end: -13.5px;
+ opacity: 0;
+ position: absolute;
+ top: -13.5px;
+ transform: scale(0.25);
+ transition-duration: 150ms;
+ transition-property: transform, opacity;
+ width: 27px; }
+ .outer-wrapper:not(.newtab-experience) .top-site-outer .context-menu-button:is(:active, :focus) {
+ opacity: 1;
+ transform: scale(1); }
+
+.outer-wrapper:not(.newtab-experience) .top-site-outer .tile {
+ height: 96px;
+ width: 96px;
+ transition: box-shadow 150ms; }
+
+.outer-wrapper:not(.newtab-experience) .top-site-outer .top-site-icon {
+ box-shadow: var(--newtab-topsites-icon-shadow); }
+
+.outer-wrapper:not(.newtab-experience) .top-site-outer .title {
+ width: 96px; }
+ .outer-wrapper:not(.newtab-experience) .top-site-outer .title.has-icon span {
+ padding: 0 13px; }
+ .outer-wrapper:not(.newtab-experience) .top-site-outer .title .icon {
+ inset-inline-start: 0;
+ position: absolute;
+ top: 0.5em; }
+
+.outer-wrapper:not(.newtab-experience) .top-site-outer .top-site-inner {
+ position: relative; }
+ .outer-wrapper:not(.newtab-experience) .top-site-outer .top-site-inner > a {
+ color: inherit;
+ display: block;
+ outline: none; }
+ .outer-wrapper:not(.newtab-experience) .top-site-outer .top-site-inner > a:is(.active, :focus) .tile {
+ box-shadow: inset 0 0 0 1px var(--newtab-inner-box-shadow-color), 0 0 0 5px var(--newtab-card-active-outline-color);
+ transition: box-shadow 150ms; }
+
+.outer-wrapper:not(.newtab-experience) .top-site-outer .screenshot {
+ background-color: #FFF;
+ background-position: top left;
+ background-size: cover;
+ border-radius: 4px;
+ box-shadow: inset 0 0 0 1px var(--newtab-inner-box-shadow-color);
+ height: 100%;
+ opacity: 0;
+ position: absolute;
+ top: 0;
+ left: 0;
+ transition: opacity 1s;
+ width: 100%; }
+ .outer-wrapper:not(.newtab-experience) .top-site-outer .screenshot.active {
+ opacity: 1; }
+
+.outer-wrapper:not(.newtab-experience) .top-site-outer .default-icon,
+.outer-wrapper:not(.newtab-experience) .top-site-outer .search-topsite {
+ bottom: -6px;
+ inset-inline-end: -6px; }
+
+.outer-wrapper:not(.newtab-experience) .top-site-outer:hover .search-topsite {
+ background-size: 28px;
+ border-radius: 46px;
+ bottom: -9px;
+ height: 46px;
+ inset-inline-end: -9px;
+ width: 46px; }
+
+.outer-wrapper:not(.newtab-experience) .top-site-outer.placeholder .tile {
+ box-shadow: inset 0 0 0 1px var(--newtab-inner-box-shadow-color); }
+
+.outer-wrapper:not(.newtab-experience) .top-sites-list:not(.dnd-active) .top-site-outer:is(.active, :focus, :hover) .tile {
+ box-shadow: inset 0 0 0 1px var(--newtab-inner-box-shadow-color), 0 0 0 5px var(--newtab-card-active-outline-color);
+ transition: box-shadow 150ms; }
+
+.outer-wrapper:not(.newtab-experience) .top-sites-list:not(.dnd-active) .top-site-outer:is(.active, :focus, :hover) .context-menu-button {
+ opacity: 1;
+ transform: scale(1);
+ transition-delay: 333ms; }
+
+.outer-wrapper:not(.newtab-experience) .top-sites-list li {
+ margin: 0 0 8px; }
+
+.outer-wrapper.newtab-experience .top-site-outer {
+ width: 120px;
+ padding-block: 20px 4px;
+ border-radius: 8px; }
+ .outer-wrapper.newtab-experience .top-site-outer .context-menu-button {
+ background-image: url("chrome://global/skin/icons/more.svg");
+ border: 0;
+ border-radius: 4px;
+ cursor: pointer;
+ fill: var(--newtab-icon-primary-color);
+ -moz-context-properties: fill;
+ height: 20px;
+ width: 20px;
+ inset-inline-end: -9px;
+ opacity: 0;
+ position: absolute;
+ top: -20px;
+ transition: opacity 200ms; }
+ .outer-wrapper.newtab-experience .top-site-outer .context-menu-button:is(:active, :focus) {
+ outline: 0;
+ opacity: 1;
+ background-color: var(--newtab-topsites-context-menu-hover);
+ fill: var(--newtab-primary-action-background); }
+ .outer-wrapper.newtab-experience .top-site-outer .edit-button {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-edit-16.svg"); }
+ .outer-wrapper.newtab-experience .top-site-outer .tile {
+ border-radius: 8px;
+ box-shadow: 0 3px 8px var(--newtab-inner-box-shadow-color-nte), 0 0 2px var(--newtab-tile-shadow-secondary);
+ background-color: var(--newtab-topsites-background-color);
+ justify-content: center;
+ margin: 0 auto;
+ height: 80px;
+ width: 80px; }
+ .outer-wrapper.newtab-experience .top-site-outer .title {
+ color: var(--newtab-background-primary-text-color);
+ padding-top: 8px;
+ font-size: 12px; }
+ .outer-wrapper.newtab-experience .top-site-outer .title .icon {
+ margin-inline-end: 2px;
+ fill: var(--newtab-background-primary-text-color); }
+ .outer-wrapper.newtab-experience .top-site-outer .title .sponsored-label {
+ font-size: 12px; }
+ .outer-wrapper.newtab-experience .top-site-outer .default-icon,
+ .outer-wrapper.newtab-experience .top-site-outer .search-topsite {
+ height: 32px;
+ width: 32px; }
+ .outer-wrapper.newtab-experience .top-site-outer .search-topsite {
+ background-size: 16px;
+ height: 32px;
+ width: 32px; }
+ .outer-wrapper.newtab-experience .top-site-outer.placeholder .tile {
+ box-shadow: 0 0 0 1px var(--newtab-inner-box-shadow-color); }
+
+@media (max-width: 610px) {
+ .outer-wrapper.newtab-experience .top-sites-list > :nth-child(2n+1) .context-menu {
+ margin-inline-end: auto;
+ margin-inline-start: auto;
+ inset-inline-end: auto;
+ inset-inline-start: -32px; }
+ .outer-wrapper.newtab-experience .top-sites-list > :nth-child(2n) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+
+@media (min-width: 610px) and (max-width: 866px) {
+ .outer-wrapper.newtab-experience .top-sites-list :nth-child(4n) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+
+@media (min-width: 610px) and (max-width: 802px) {
+ .outer-wrapper.newtab-experience .top-sites-list :nth-child(4n+3) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+
+@media (min-width: 866px) and (max-width: 1250px) {
+ .outer-wrapper.newtab-experience .top-sites-list :nth-child(6n) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+
+@media (min-width: 866px) and (max-width: 1058px) {
+ .outer-wrapper.newtab-experience .top-sites-list :nth-child(6n+5) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+
+@media (min-width: 1122px) and (max-width: 1506px) {
+ .outer-wrapper.newtab-experience .top-sites-list :nth-child(8n) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+
+@media (min-width: 1122px) and (max-width: 1314px) {
+ .outer-wrapper.newtab-experience .top-sites-list :nth-child(8n+7) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+
+.outer-wrapper.newtab-experience:not(.dnd-active) .top-site-outer:is(.active, :focus, :hover) {
+ background: var(--newtab-topsites-outer-card-hover); }
+ .outer-wrapper.newtab-experience:not(.dnd-active) .top-site-outer:is(.active, :focus, :hover) .context-menu-button {
+ opacity: 1; }
+
+@keyframes fade-up-tt {
+ 0% {
+ opacity: 0;
+ transform: translateY(15px); }
+ 100% {
+ opacity: 1;
+ transform: translateY(0); } }
+
+.sections-list .section-list {
+ display: grid;
+ grid-gap: 32px;
+ grid-template-columns: repeat(auto-fit, 224px);
+ margin: 0; }
+ @media (max-width: 610px) {
+ .sections-list .section-list .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+ @media (min-width: 610px) and (max-width: 866px) {
+ .sections-list .section-list :nth-child(2n) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+ @media (min-width: 866px) and (max-width: 1314px) {
+ .sections-list .section-list :nth-child(3n) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+ @media (min-width: 1122px) and (max-width: 1570px) {
+ .sections-list .section-list :nth-child(3n) .context-menu,
+ .sections-list .section-list :nth-child(4n) .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+
+.sections-list .section-empty-state {
+ border: 1px solid var(--newtab-border-secondary-color);
+ border-radius: 3px;
+ display: flex;
+ height: 266px;
+ width: 100%; }
+ .sections-list .section-empty-state .empty-state {
+ margin: auto;
+ max-width: 350px; }
+ .sections-list .section-empty-state .empty-state .empty-state-icon {
+ background-position: center;
+ background-repeat: no-repeat;
+ background-size: 50px 50px;
+ -moz-context-properties: fill;
+ display: block;
+ fill: var(--newtab-icon-secondary-color);
+ height: 50px;
+ margin: 0 auto;
+ width: 50px; }
+ .sections-list .section-empty-state .empty-state .empty-state-message {
+ color: var(--newtab-text-primary-color);
+ font-size: 13px;
+ margin-bottom: 0;
+ text-align: center; }
+ @media (min-width: 1122px) {
+ .sections-list .section-empty-state {
+ height: 370px; } }
+
+.top-stories-bottom-container {
+ color: var(--newtab-section-navigation-text-color);
+ font-size: 12px;
+ line-height: 1.6;
+ margin-top: 12px;
+ display: flex;
+ justify-content: space-between; }
+ .top-stories-bottom-container a {
+ color: var(--newtab-link-secondary-color);
+ font-weight: bold; }
+ .top-stories-bottom-container a.more-recommendations {
+ font-weight: normal;
+ font-size: 13px; }
+ @media (max-width: 865px) {
+ .top-stories-bottom-container .wrapper-topics,
+ .top-stories-bottom-container .wrapper-cta + .wrapper-more-recommendations {
+ display: none; } }
+ @media (max-width: 609px) {
+ .top-stories-bottom-container .wrapper-cta {
+ text-align: center; }
+ .top-stories-bottom-container .wrapper-cta .pocket-logged-in-cta {
+ display: block;
+ margin-inline-end: 0; }
+ .top-stories-bottom-container .wrapper-cta .pocket-logged-in-cta .pocket-cta-button {
+ max-width: none;
+ display: block;
+ margin-inline-end: 0;
+ margin: 5px 0 10px; }
+ .top-stories-bottom-container .wrapper-more-recommendations {
+ width: 100%; }
+ .top-stories-bottom-container .wrapper-more-recommendations .more-recommendations {
+ justify-content: center; }
+ .top-stories-bottom-container .wrapper-more-recommendations .more-recommendations::after {
+ display: none; } }
+
+@media (min-width: 1122px) {
+ .sections-list .normal-cards .section-list {
+ grid-template-columns: repeat(auto-fit, 309px); } }
+
+.topics ul {
+ margin: 0;
+ padding: 0; }
+ @media (min-width: 866px) {
+ .topics ul {
+ display: inline;
+ padding-inline-start: 12px; } }
+
+.topics ul li {
+ display: inline-block; }
+ .topics ul li::after {
+ content: '•';
+ padding: 8px; }
+ .topics ul li:last-child::after {
+ content: none; }
+
+.outer-wrapper.newtab-experience.visible-logo .logo-and-wordmark .wordmark {
+ fill: var(--newtab-wordmark-color); }
+
+.outer-wrapper.newtab-experience .search-wrapper {
+ padding-bottom: 38px; }
+ .outer-wrapper.newtab-experience .search-wrapper .search-inner-wrapper {
+ min-height: 52px;
+ width: 200px; }
+ @media (min-width: 610px) {
+ .outer-wrapper.newtab-experience .search-wrapper .search-inner-wrapper {
+ width: 360px; } }
+ @media (min-width: 866px) {
+ .outer-wrapper.newtab-experience .search-wrapper .search-inner-wrapper {
+ width: 600px; } }
+ @media (min-width: 1122px) {
+ .outer-wrapper.newtab-experience .search-wrapper .search-inner-wrapper {
+ width: 720px; } }
+ .outer-wrapper.newtab-experience .search-wrapper .search-button:focus {
+ outline: 0;
+ box-shadow: 0 0 0 2px var(--newtab-focus-outline);
+ border: 1px solid var(--newtab-focus-border);
+ border-radius: 0 8px 8px 0; }
+ .outer-wrapper.newtab-experience .search-wrapper input:focus {
+ outline: 0;
+ border: 1px solid var(--newtab-focus-border);
+ box-shadow: 0 0 0 2px var(--newtab-focus-outline); }
+ .outer-wrapper.newtab-experience .search-wrapper.fake-focus .search-handoff-button {
+ border: 1px solid var(--newtab-focus-border);
+ box-shadow: 0 0 0 2px var(--newtab-focus-outline); }
+ .outer-wrapper.newtab-experience .search-wrapper .search-handoff-button,
+ .outer-wrapper.newtab-experience .search-wrapper input {
+ background: var(--newtab-textbox-background-color) var(--newtab-search-icon) 16px center no-repeat;
+ background-size: 24px;
+ padding-inline-start: 52px;
+ padding-inline-end: 10px;
+ box-shadow: 0 3px 8px var(--newtab-search-first-shadow), 0 0 2px var(--newtab-search-second-shadow);
+ border: 1px solid transparent;
+ border-radius: 8px;
+ color: var(--newtab-search-text-color);
+ font-weight: 500;
+ font-size: 15px; }
+ .outer-wrapper.newtab-experience .search-wrapper .search-handoff-button {
+ padding-inline-end: 15px; }
+ .outer-wrapper.newtab-experience .search-wrapper .search-handoff-button .fake-caret {
+ top: 18px;
+ inset-inline-start: 52px; }
+ .outer-wrapper.newtab-experience .search-wrapper .search-handoff-button .fake-caret:dir(rtl) {
+ background-position-x: right 16px; }
+
+.search-wrapper {
+ padding: 34px 0 64px; }
+ .only-search .search-wrapper {
+ padding: 0 0 64px; }
+ .search-wrapper .logo-and-wordmark {
+ align-items: center;
+ display: flex;
+ justify-content: center;
+ margin-bottom: 48px; }
+ .search-wrapper .logo-and-wordmark .logo {
+ background: url("chrome://branding/content/about-logo.png") no-repeat center;
+ background-size: 82px;
+ display: inline-block;
+ height: 82px;
+ width: 82px; }
+ @media (min-resolution: 2x) {
+ .search-wrapper .logo-and-wordmark .logo {
+ background-image: url("chrome://branding/content/about-logo@2x.png"); } }
+ .search-wrapper .logo-and-wordmark .wordmark {
+ background: url("chrome://branding/content/firefox-wordmark.svg") no-repeat center center;
+ background-size: 134px;
+ -moz-context-properties: fill;
+ display: inline-block;
+ fill: var(--newtab-search-wordmark-color);
+ height: 82px;
+ margin-inline-start: 16px;
+ width: 134px; }
+ @media (max-width: 609px) {
+ .search-wrapper .logo-and-wordmark .logo {
+ background-size: 64px;
+ height: 64px;
+ width: 64px; }
+ .search-wrapper .logo-and-wordmark .wordmark {
+ background-size: 100px;
+ height: 64px;
+ width: 100px;
+ margin-inline-start: 12px; } }
+ .search-wrapper .search-inner-wrapper {
+ cursor: default;
+ display: flex;
+ min-height: 48px;
+ margin: 0 auto;
+ position: relative;
+ width: 224px; }
+ .ds-outer-wrapper-breakpoint-override .search-wrapper .search-inner-wrapper {
+ width: 216px; }
+ @media (min-width: 610px) {
+ .search-wrapper .search-inner-wrapper {
+ width: 480px; }
+ .ds-outer-wrapper-breakpoint-override .search-wrapper .search-inner-wrapper {
+ width: 460px; } }
+ @media (min-width: 866px) {
+ .search-wrapper .search-inner-wrapper {
+ width: 736px; }
+ .ds-outer-wrapper-breakpoint-override .search-wrapper .search-inner-wrapper {
+ width: 696px; } }
+ .search-wrapper input {
+ background: var(--newtab-textbox-background-color) var(--newtab-search-icon) 12px center no-repeat;
+ background-size: 24px;
+ border: solid 1px var(--newtab-search-border-color);
+ box-shadow: 0 1px 4px 0 rgba(12, 12, 13, 0.2), 0 0 0 1px rgba(0, 0, 0, 0.15);
+ font-size: 15px;
+ -moz-context-properties: fill;
+ fill: var(--newtab-search-icon-color);
+ padding: 0;
+ padding-inline-end: 48px;
+ padding-inline-start: 46px;
+ width: 100%; }
+ .search-wrapper input:dir(rtl) {
+ background-position-x: right 12px; }
+ .search-wrapper:hover input {
+ box-shadow: 0 1px 4px 0 rgba(12, 12, 13, 0.2), 0 0 0 1px rgba(0, 0, 0, 0.25); }
+ .search-wrapper .search-inner-wrapper:active input,
+ .search-wrapper input:focus {
+ border: 1px solid var(--newtab-textbox-focus-color);
+ box-shadow: var(--newtab-textbox-focus-boxshadow); }
+ .search-wrapper .search-button {
+ background: url("chrome://browser/skin/forward.svg") no-repeat center center;
+ background-size: 16px 16px;
+ border: 0;
+ border-radius: 0 3px 3px 0;
+ -moz-context-properties: fill;
+ fill: var(--newtab-search-icon-color);
+ height: 100%;
+ inset-inline-end: 0;
+ position: absolute;
+ width: 48px; }
+ .search-wrapper .search-button:focus, .search-wrapper .search-button:hover {
+ background-color: rgba(12, 12, 13, 0.1);
+ cursor: pointer; }
+ .search-wrapper .search-button:active {
+ background-color: rgba(12, 12, 13, 0.2); }
+ .search-wrapper .search-button:dir(rtl) {
+ transform: scaleX(-1); }
+
+.non-collapsible-section + .below-search-snippet-wrapper {
+ margin-top: -48px; }
+
+@media (max-height: 700px) {
+ .search-wrapper {
+ padding: 0 0 30px; }
+ .non-collapsible-section + .below-search-snippet-wrapper {
+ margin-top: -14px; }
+ .below-search-snippet-wrapper {
+ min-height: 0; } }
+
+.search-handoff-button {
+ background: var(--newtab-textbox-background-color) var(--newtab-search-icon) 12px center no-repeat;
+ background-size: 24px;
+ border: solid 1px var(--newtab-search-border-color);
+ border-radius: 3px;
+ box-shadow: 0 1px 4px 0 rgba(12, 12, 13, 0.2), 0 0 0 1px rgba(0, 0, 0, 0.15);
+ cursor: text;
+ font-size: 15px;
+ padding: 0;
+ padding-inline-end: 48px;
+ padding-inline-start: 46px;
+ opacity: 1;
+ transition: opacity 500ms;
+ width: 100%; }
+ .search-handoff-button:dir(rtl) {
+ background-position-x: right 12px; }
+ .search-handoff-button:hover {
+ box-shadow: 0 1px 4px 0 rgba(12, 12, 13, 0.2), 0 0 0 1px rgba(0, 0, 0, 0.25); }
+ .fake-focus .search-handoff-button {
+ border: 1px solid var(--newtab-textbox-focus-color);
+ box-shadow: var(--newtab-textbox-focus-boxshadow); }
+ .fake-focus .search-handoff-button .fake-caret {
+ display: block; }
+ .search-hidden .search-handoff-button {
+ opacity: 0;
+ visibility: hidden; }
+ .search-handoff-button .fake-editable:focus {
+ outline: none;
+ caret-color: transparent; }
+ .search-handoff-button .fake-editable {
+ color: transparent;
+ height: 100%;
+ opacity: 0;
+ position: absolute;
+ top: 0;
+ left: 0;
+ right: 0;
+ bottom: 0; }
+ .search-handoff-button .fake-textbox {
+ opacity: 0.54;
+ text-align: start; }
+ .search-handoff-button .fake-caret {
+ animation: caret-animation 1.3s steps(5, start) infinite;
+ background: var(--newtab-text-primary-color);
+ display: none;
+ inset-inline-start: 47px;
+ height: 17px;
+ position: absolute;
+ top: 16px;
+ width: 1px; }
+
+@keyframes caret-animation {
+ to {
+ visibility: hidden; } }
+
+@media (min-height: 701px) {
+ body:not(.inline-onboarding) .fixed-search main {
+ padding-top: 146px; }
+ body:not(.inline-onboarding) .fixed-search.visible-logo main {
+ padding-top: 276px; }
+ body:not(.inline-onboarding) .fixed-search .search-wrapper {
+ border-bottom: solid 1px var(--newtab-border-secondary-color);
+ padding: 30px 0;
+ background-color: var(--newtab-search-header-background-color);
+ min-height: 95px;
+ left: 0;
+ position: fixed;
+ top: 0;
+ width: 100%;
+ z-index: 9; }
+ body:not(.inline-onboarding) .fixed-search .search-wrapper .search-inner-wrapper {
+ min-height: 35px; }
+ body:not(.inline-onboarding) .fixed-search .search-wrapper input {
+ background-position-x: 16px;
+ background-size: 16px; }
+ body:not(.inline-onboarding) .fixed-search .search-wrapper input:dir(rtl) {
+ background-position-x: right 16px; }
+ body:not(.inline-onboarding) .fixed-search .search-wrapper .search-handoff-button .fake-caret {
+ top: 14px; }
+ body:not(.inline-onboarding) .fixed-search .search-wrapper .logo-and-wordmark {
+ display: none; }
+ body:not(.inline-onboarding) .fixed-search.newtab-experience main {
+ padding-top: 124px; }
+ body:not(.inline-onboarding) .fixed-search.newtab-experience.visible-logo main {
+ padding-top: 254px; }
+ body:not(.inline-onboarding) .fixed-search.newtab-experience .search-wrapper {
+ border-bottom: solid 1px var(--newtab-seperator-line-color);
+ padding: 27px 0; }
+ body:not(.inline-onboarding) .fixed-search.newtab-experience .search-wrapper .search-inner-wrapper {
+ min-height: 45px; }
+ body:not(.inline-onboarding) .fixed-search.newtab-experience .search-wrapper input {
+ background-position-x: 16px;
+ background-size: 24px; }
+ body:not(.inline-onboarding) .fixed-search.newtab-experience .search-wrapper input:dir(rtl) {
+ background-position-x: right 16px; }
+ body:not(.inline-onboarding) .fixed-search .search-handoff-button {
+ background-position-x: 12px;
+ background-size: 24px; }
+ body:not(.inline-onboarding) .fixed-search .search-handoff-button:dir(rtl) {
+ background-position-x: right 12px; }
+ body:not(.inline-onboarding) .fixed-search .search-handoff-button .fake-caret {
+ top: 10px; } }
+
+.contentSearchSuggestionTable {
+ background-color: var(--newtab-search-dropdown-color);
+ border: 0;
+ box-shadow: 0 5px 10px rgba(0, 0, 0, 0.3), 0 0 0 1px rgba(0, 0, 0, 0.2);
+ transform: translateY(4px); }
+ .contentSearchSuggestionTable .contentSearchHeader {
+ background-color: var(--newtab-search-dropdown-header-color);
+ color: var(--newtab-text-secondary-color); }
+ .contentSearchSuggestionTable .contentSearchHeader,
+ .contentSearchSuggestionTable .contentSearchSettingsButton {
+ border-color: var(--newtab-border-secondary-color); }
+ .contentSearchSuggestionTable .contentSearchSuggestionsList {
+ border: 0; }
+ .contentSearchSuggestionTable .contentSearchOneOffsTable {
+ background-color: var(--newtab-search-dropdown-header-color);
+ border-top: solid 1px var(--newtab-border-secondary-color); }
+ .contentSearchSuggestionTable .contentSearchSearchWithHeaderSearchText {
+ color: var(--newtab-text-primary-color); }
+ .contentSearchSuggestionTable .contentSearchSuggestionsContainer {
+ background-color: var(--newtab-search-dropdown-color); }
+ .contentSearchSuggestionTable .contentSearchSuggestionRow.selected {
+ background: var(--newtab-element-hover-color);
+ color: var(--newtab-text-primary-color); }
+ .contentSearchSuggestionTable .contentSearchSuggestionRow.selected:active {
+ background: var(--newtab-element-active-color); }
+ .contentSearchSuggestionTable .contentSearchSuggestionRow.selected .historyIcon {
+ fill: var(--newtab-icon-secondary-color); }
+ .contentSearchSuggestionTable .contentSearchOneOffsTable .contentSearchSuggestionsContainer {
+ background-color: var(--newtab-search-dropdown-header-color); }
+ .contentSearchSuggestionTable .contentSearchOneOffItem {
+ background-image: none;
+ border-image: linear-gradient(transparent 18%, var(--newtab-border-secondary-color) 18%, var(--newtab-border-secondary-color) 82%, transparent 82%) 1;
+ border-inline-end: 1px solid;
+ position: relative; }
+ .contentSearchSuggestionTable .contentSearchOneOffItem.selected {
+ background: var(--newtab-element-hover-color); }
+ .contentSearchSuggestionTable .contentSearchOneOffItem:active {
+ background: var(--newtab-element-active-color); }
+ .contentSearchSuggestionTable .contentSearchSettingsButton:hover {
+ background: var(--newtab-element-hover-color);
+ color: var(--newtab-text-primary-color); }
+
+.contentSearchHeaderRow > td > img,
+.contentSearchSuggestionRow > td > .historyIcon {
+ margin-inline-start: 7px;
+ margin-inline-end: 15px; }
+
+.context-menu {
+ background: var(--newtab-contextmenu-background-color);
+ border-radius: 5px;
+ box-shadow: 0 5px 10px rgba(0, 0, 0, 0.3), 0 0 0 1px rgba(0, 0, 0, 0.2);
+ display: block;
+ font-size: 14px;
+ margin-inline-start: 5px;
+ inset-inline-start: 100%;
+ position: absolute;
+ top: 6.75px;
+ z-index: 8; }
+ .context-menu > ul {
+ list-style: none;
+ margin: 0;
+ padding: 5px 0; }
+ .context-menu > ul > li {
+ margin: 0;
+ width: 100%; }
+ .context-menu > ul > li.separator {
+ border-bottom: 1px solid var(--newtab-border-secondary-color);
+ margin: 5px 0; }
+ .context-menu > ul > li > a,
+ .context-menu > ul > li > button {
+ align-items: center;
+ color: inherit;
+ cursor: pointer;
+ display: flex;
+ width: 100%;
+ line-height: 16px;
+ outline: none;
+ border: 0;
+ padding: 3px 12px;
+ white-space: nowrap; }
+ .context-menu > ul > li > a:is(:focus, :hover),
+ .context-menu > ul > li > button:is(:focus, :hover) {
+ background: var(--newtab-element-hover-color); }
+ .context-menu > ul > li > a:active,
+ .context-menu > ul > li > button:active {
+ background: var(--newtab-element-active-color); }
+ .context-menu > ul > li > a.disabled,
+ .context-menu > ul > li > button.disabled {
+ opacity: 0.4;
+ pointer-events: none; }
+
+.confirmation-dialog .modal {
+ box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.1);
+ left: 0;
+ margin: auto;
+ position: fixed;
+ right: 0;
+ top: 20%;
+ width: 400px; }
+
+.confirmation-dialog section {
+ margin: 0; }
+
+.confirmation-dialog .modal-message {
+ display: flex;
+ padding: 16px;
+ padding-bottom: 0; }
+ .confirmation-dialog .modal-message p {
+ margin: 0;
+ margin-bottom: 16px; }
+
+.confirmation-dialog .actions {
+ border: 0;
+ display: flex;
+ flex-wrap: nowrap;
+ padding: 0 16px; }
+ .confirmation-dialog .actions button {
+ margin-inline-end: 16px;
+ padding-inline-end: 18px;
+ padding-inline-start: 18px;
+ white-space: normal;
+ width: 50%; }
+ .confirmation-dialog .actions button.done {
+ margin-inline-end: 0;
+ margin-inline-start: 0; }
+
+.confirmation-dialog .icon {
+ margin-inline-end: 16px; }
+
+.modal-overlay {
+ background: var(--newtab-overlay-color);
+ height: 100%;
+ left: 0;
+ position: fixed;
+ top: 0;
+ width: 100%;
+ z-index: 11001; }
+
+.modal {
+ background: var(--newtab-modal-color);
+ border: 1px solid var(--newtab-border-secondary-color);
+ border-radius: 5px;
+ font-size: 15px;
+ z-index: 11002; }
+
+.customize-menu {
+ color: var(--customize-menu-primary-text-color);
+ background-color: var(--customize-menu-background);
+ width: 432px;
+ height: 100%;
+ position: fixed;
+ inset-block: 0;
+ inset-inline-end: 0;
+ z-index: 1001;
+ padding: 16px;
+ transition: transform 250ms cubic-bezier(0.46, 0.03, 0.52, 0.96);
+ overflow: auto;
+ transform: translateX(435px);
+ visibility: hidden;
+ cursor: default; }
+ .customize-menu:dir(rtl) {
+ transform: translateX(-435px); }
+ .customize-menu.customize-animate-enter-done {
+ transform: translateX(0); }
+ .customize-menu.customize-animate-enter-done, .customize-menu.customize-animate-enter-active, .customize-menu.customize-animate-enter {
+ box-shadow: 0 0 64px var(--customize-menu-first-shadow), 0 0 24px var(--customize-menu-second-shadow);
+ transition: transform 250ms cubic-bezier(0.46, 0.03, 0.52, 0.96), visibility 1ms;
+ visibility: visible; }
+ .customize-menu.customize-animate-exit-active, .customize-menu.customize-animate-exit {
+ box-shadow: 0 0 64px var(--customize-menu-first-shadow), 0 0 24px var(--customize-menu-second-shadow);
+ transition: transform 250ms cubic-bezier(0.46, 0.03, 0.52, 0.96), visibility 1ms 250ms;
+ visibility: visible; }
+ .customize-menu.customize-animate-exit-done {
+ transform: translateX(435px);
+ transition: transform 250ms cubic-bezier(0.46, 0.03, 0.52, 0.96), visibility 1ms 250ms; }
+ .customize-menu.customize-animate-exit-done:dir(rtl) {
+ transform: translateX(-435px); }
+ .customize-menu .close-button {
+ margin-inline-start: auto;
+ margin-bottom: 28px;
+ white-space: nowrap;
+ display: block;
+ background-color: var(--customize-menu-secondary-action-background);
+ padding: 8px 10px;
+ border: 1px solid rgba(0, 0, 0, 0.15);
+ border-radius: 4px;
+ color: var(--customize-menu-primary-text-color);
+ font-size: 13px;
+ font-weight: 600; }
+ .customize-menu .close-button:hover {
+ background-color: var(--customize-menu-secondary-action-background-hover); }
+ .customize-menu .close-button:hover:active {
+ background-color: var(--customize-menu-secondary-action-background-active); }
+
+.grid-skip {
+ display: contents; }
+
+.home-section {
+ display: grid;
+ grid-template-columns: 1fr;
+ grid-template-rows: repeat(4, auto);
+ grid-row-gap: 32px;
+ padding: 0 16px; }
+ .home-section .section {
+ display: grid;
+ grid-template-rows: auto;
+ grid-template-columns: auto 26px; }
+ .home-section .section > div {
+ grid-area: 1; }
+ .home-section .section .title {
+ grid-column: 1 / -1;
+ margin: 0;
+ font-weight: 600;
+ font-size: 16px;
+ margin-bottom: 10px; }
+ .home-section .section .subtitle {
+ margin: 0;
+ font-size: 14px; }
+ .home-section .section .sponsored {
+ font-size: 14px;
+ margin-inline-start: 5px; }
+ .home-section .section .check-wrapper {
+ position: relative; }
+ .home-section .section .sponsored-checkbox {
+ margin-inline-start: 2px;
+ width: 16px;
+ height: 16px;
+ vertical-align: middle;
+ border: 1px solid rgba(0, 0, 0, 0.15);
+ box-sizing: border-box;
+ border-radius: 4px;
+ appearance: none;
+ background-color: var(--newtab-primary-action-background-off); }
+ .home-section .section .sponsored-checkbox:checked {
+ -moz-context-properties: fill;
+ fill: var(--customize-menu-check-fill);
+ background: url("chrome://global/skin/icons/check.svg") center no-repeat;
+ background-color: var(--newtab-primary-action-background);
+ background-size: 10px; }
+ .home-section .section .sponsored-checkbox:active + .checkmark {
+ fill: rgba(0, 0, 0, 0.15); }
+ .home-section .section .selector {
+ color: var(--customize-menu-primary-text-color);
+ width: 118px;
+ display: block;
+ border: 1px solid var(--customize-menu-line-color);
+ border-radius: 4px;
+ appearance: none;
+ padding-block: 7px;
+ padding-inline: 10px 13px;
+ margin-inline-start: 2px;
+ -moz-context-properties: fill;
+ fill: var(--customize-menu-primary-text-color);
+ background: url("chrome://activity-stream/content/data/content/assets/glyph-arrowhead-down-12.svg") right no-repeat;
+ background-size: 8px;
+ background-origin: content-box;
+ background-color: var(--customize-menu-background); }
+ .home-section .section .selector:dir(rtl) {
+ background-position-x: left; }
+ .home-section .section .switch {
+ position: relative;
+ display: inline-block;
+ width: 26px;
+ height: 16px;
+ grid-column: 2;
+ margin-top: 2px; }
+ .home-section .section .switch input {
+ opacity: 0;
+ width: 0;
+ height: 0; }
+ .home-section .section .slider {
+ position: absolute;
+ inset: 0;
+ transition: transform 250ms;
+ border-radius: 13px;
+ border: 1px solid rgba(0, 0, 0, 0.15);
+ background-color: var(--newtab-primary-action-background-off); }
+ .home-section .section .slider::before {
+ position: absolute;
+ content: '';
+ height: 8px;
+ width: 8px;
+ inset-inline-start: 3px;
+ bottom: 3px;
+ background-color: var(--customize-menu-primary-action-text);
+ transition: transform 250ms;
+ border-radius: 50%;
+ outline: 1px solid rgba(0, 0, 0, 0.15);
+ -moz-outline-radius: 11px; }
+ .home-section .section .switch input:focus-visible + .slider {
+ border: 1px solid var(--newtab-focus-border-selected);
+ outline: 0;
+ box-shadow: 0 0 0 2px var(--newtab-focus-outline); }
+ .home-section .section .switch input:not(:checked):focus-visible + .slider {
+ border: 1px solid var(--newtab-focus-border); }
+ .home-section .section input:checked + .slider {
+ background-color: var(--newtab-primary-action-background); }
+ .home-section .section input:checked + .slider::before {
+ transform: translateX(10px); }
+ .home-section .section input:checked + .slider:dir(rtl)::before {
+ transform: translateX(-10px); }
+ .home-section .section .more-info-top-wrapper,
+ .home-section .section .more-info-pocket-wrapper {
+ margin-inline-start: -2px;
+ overflow: hidden;
+ transition: max-height 250ms cubic-bezier(0.82, 0.085, 0.395, 0.895); }
+ .home-section .section .more-info-top-wrapper.shrink,
+ .home-section .section .more-info-pocket-wrapper.shrink {
+ max-height: 0; }
+ .home-section .section .more-info-top-wrapper .more-information,
+ .home-section .section .more-info-pocket-wrapper .more-information {
+ padding-top: 12px;
+ position: relative;
+ transition: top 250ms cubic-bezier(0.82, 0.085, 0.395, 0.895); }
+ .home-section .section .more-info-top-wrapper .more-information.expand,
+ .home-section .section .more-info-pocket-wrapper .more-information.expand {
+ top: 0; }
+ .home-section .section .more-info-top-wrapper {
+ max-height: 78px; }
+ .home-section .section .more-info-top-wrapper .more-information {
+ top: -77px; }
+ .home-section .section .more-info-top-wrapper .check-wrapper {
+ margin-top: 10px; }
+ .home-section .section .more-info-pocket-wrapper {
+ max-height: 35px; }
+ .home-section .section .more-info-pocket-wrapper .more-information {
+ top: -35px; }
+ .home-section .divider {
+ border-top: 1px var(--customize-menu-seperator-line-color) solid;
+ margin: 0 -16px; }
+ .home-section .external-link {
+ font-size: 14px;
+ cursor: pointer;
+ border: 1px solid transparent;
+ border-radius: 4px;
+ -moz-context-properties: fill;
+ fill: var(--customize-menu-primary-text-color);
+ background: url("chrome://global/skin/icons/settings.svg") left no-repeat;
+ background-size: 16px;
+ padding-inline-start: 21px;
+ margin-bottom: 20px; }
+ .home-section .external-link:dir(rtl) {
+ background-position-x: right; }
+ .home-section .external-link:hover {
+ text-decoration: underline; }
+
+.home-section .section .sponsored-checkbox:focus-visible,
+.selector:focus-visible,
+.external-link:focus-visible,
+.close-button:focus-visible {
+ border: 1px solid var(--newtab-focus-border);
+ outline: 0;
+ box-shadow: 0 0 0 2px var(--newtab-focus-outline); }
+
+.outer-wrapper.newtab-experience .card-outer {
+ border-radius: 8px; }
+ .outer-wrapper.newtab-experience .card-outer:is(:focus):not(.placeholder) {
+ border: 0;
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-focus-outline), 0 0 0 1px var(--newtab-focus-border);
+ transition: none; }
+ .outer-wrapper.newtab-experience .card-outer:hover {
+ box-shadow: none;
+ transition: none; }
+ .outer-wrapper.newtab-experience .card-outer .card {
+ box-shadow: 0 3px 8px var(--newtab-card-first-shadow), 0 0 2px var(--newtab-card-second-shadow);
+ border-radius: 8px; }
+ .outer-wrapper.newtab-experience .card-outer .card-preview-image-outer {
+ border-radius: 8px 8px 0 0; }
+ .outer-wrapper.newtab-experience .card-outer .context-menu-button:is(:active, :focus) {
+ outline: 0;
+ fill: var(--newtab-primary-action-background);
+ border: 1px solid var(--newtab-primary-action-background); }
+ .outer-wrapper.newtab-experience .card-outer > a:is(:focus) .card {
+ border: 0;
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-focus-outline), 0 0 0 1px var(--newtab-focus-border); }
+
+.outer-wrapper:not(.newtab-experience) .card-outer:is(:hover, :focus, .active):not(.placeholder) {
+ box-shadow: 0 0 0 5px var(--newtab-card-active-outline-color);
+ transition: box-shadow 150ms; }
+
+.card-outer {
+ background: var(--newtab-card-background-color);
+ border-radius: 3px;
+ display: inline-block;
+ height: 266px;
+ margin-inline-end: 32px;
+ position: relative;
+ width: 100%; }
+ .card-outer .context-menu-button {
+ background-clip: padding-box;
+ background-color: var(--newtab-contextmenu-button-color);
+ background-image: url("chrome://global/skin/icons/more.svg");
+ background-position: 55%;
+ border: 1px solid var(--newtab-border-primary-color);
+ border-radius: 100%;
+ box-shadow: 0 2px rgba(12, 12, 13, 0.1);
+ cursor: pointer;
+ fill: var(--newtab-icon-primary-color);
+ height: 27px;
+ inset-inline-end: -13.5px;
+ opacity: 0;
+ position: absolute;
+ top: -13.5px;
+ transform: scale(0.25);
+ transition-duration: 150ms;
+ transition-property: transform, opacity;
+ width: 27px; }
+ .card-outer .context-menu-button:is(:active, :focus) {
+ opacity: 1;
+ transform: scale(1); }
+ .card-outer.placeholder {
+ background: transparent; }
+ .card-outer.placeholder .card {
+ box-shadow: inset 0 0 0 1px var(--newtab-inner-box-shadow-color); }
+ .card-outer.placeholder .card-preview-image-outer,
+ .card-outer.placeholder .card-context {
+ display: none; }
+ .card-outer .card {
+ border-radius: 3px;
+ box-shadow: var(--newtab-card-shadow);
+ height: 100%; }
+ .card-outer > a {
+ color: inherit;
+ display: block;
+ height: 100%;
+ outline: none;
+ position: absolute;
+ width: 100%; }
+ .card-outer > a:is(.active, :focus) .card {
+ box-shadow: 0 0 0 5px var(--newtab-card-active-outline-color);
+ transition: box-shadow 150ms; }
+ .card-outer > a:is(.active, :focus) .card-title {
+ color: var(--newtab-link-primary-color); }
+ .card-outer:is(:hover, :focus, .active):not(.placeholder) {
+ outline: none; }
+ .card-outer:is(:hover, :focus, .active):not(.placeholder) .context-menu-button {
+ opacity: 1;
+ transform: scale(1);
+ transition-delay: 333ms; }
+ .card-outer:is(:hover, :focus, .active):not(.placeholder) .card-title {
+ color: var(--newtab-link-primary-color); }
+ .card-outer:is(:hover, :focus, .active):not(.placeholder) .alternate ~ .card-host-name {
+ display: none; }
+ .card-outer:is(:hover, :focus, .active):not(.placeholder) .card-host-name.alternate {
+ display: block; }
+ .card-outer .card-preview-image-outer {
+ background-color: #D7D7DB;
+ border-radius: 3px 3px 0 0;
+ height: 122px;
+ overflow: hidden;
+ position: relative; }
+ [lwt-newtab-brighttext] .card-outer .card-preview-image-outer {
+ background-color: #4A4A4F; }
+ .card-outer .card-preview-image-outer::after {
+ border-bottom: 1px solid var(--newtab-card-hairline-color);
+ bottom: 0;
+ content: '';
+ position: absolute;
+ width: 100%; }
+ .card-outer .card-preview-image-outer .card-preview-image {
+ background-position: center;
+ background-repeat: no-repeat;
+ background-size: cover;
+ height: 100%;
+ opacity: 0;
+ transition: opacity 1s cubic-bezier(0.07, 0.95, 0, 1);
+ width: 100%; }
+ .card-outer .card-preview-image-outer .card-preview-image.loaded {
+ opacity: 1; }
+ .card-outer .card-details {
+ padding: 15px 16px 12px; }
+ .card-outer .card-text {
+ max-height: 78px;
+ overflow: hidden; }
+ .card-outer .card-text.no-host-name, .card-outer .card-text.no-context {
+ max-height: 97px; }
+ .card-outer .card-text.no-host-name.no-context {
+ max-height: 116px; }
+ .card-outer .card-text:not(.no-description) .card-title {
+ max-height: 57px;
+ overflow: hidden; }
+ .card-outer .card-host-name {
+ color: var(--newtab-text-secondary-color);
+ font-size: 10px;
+ overflow: hidden;
+ padding-bottom: 4px;
+ text-overflow: ellipsis;
+ text-transform: uppercase;
+ white-space: nowrap; }
+ .card-outer .card-host-name.alternate {
+ display: none; }
+ .card-outer .card-title {
+ font-size: 14px;
+ font-weight: 600;
+ line-height: 19px;
+ margin: 0 0 2px;
+ word-wrap: break-word; }
+ .card-outer .card-description {
+ font-size: 12px;
+ line-height: 19px;
+ margin: 0;
+ overflow: hidden;
+ word-wrap: break-word; }
+ .card-outer .card-context {
+ bottom: 0;
+ color: var(--newtab-text-secondary-color);
+ display: flex;
+ font-size: 11px;
+ inset-inline-start: 0;
+ padding: 9px 16px 9px 14px;
+ position: absolute; }
+ .card-outer .card-context-icon {
+ fill: var(--newtab-text-secondary-color);
+ height: 22px;
+ margin-inline-end: 6px; }
+ .card-outer .card-context-label {
+ flex-grow: 1;
+ line-height: 22px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap; }
+
+@media (min-width: 1122px) {
+ .normal-cards .card-outer {
+ height: 370px; }
+ .normal-cards .card-outer .card-preview-image-outer {
+ height: 155px; }
+ .normal-cards .card-outer .card-details {
+ padding: 13px 16px 12px; }
+ .normal-cards .card-outer .card-text {
+ max-height: 140px; }
+ .normal-cards .card-outer .card-host-name {
+ font-size: 12px;
+ padding-bottom: 5px; }
+ .normal-cards .card-outer .card-title {
+ font-size: 17px;
+ line-height: 23px;
+ margin-bottom: 0; }
+ .normal-cards .card-outer .card-text:not(.no-description) .card-title {
+ max-height: 69px; }
+ .normal-cards .card-outer .card-description {
+ font-size: 15px;
+ line-height: 23px; }
+ .normal-cards .card-outer .card-context {
+ bottom: 4px;
+ font-size: 14px; } }
+
+.compact-cards .card-outer {
+ height: 160px; }
+ .compact-cards .card-outer .card-preview-image-outer {
+ height: 108px; }
+ .compact-cards .card-outer .card-details {
+ padding: 12px 16px; }
+ .compact-cards .card-outer .card-host-name {
+ line-height: 10px; }
+ .compact-cards .card-outer .card-text .card-title,
+ .compact-cards .card-outer .card-text:not(.no-description) .card-title {
+ font-size: 12px;
+ line-height: 13px;
+ max-height: 17px;
+ overflow: hidden;
+ padding: 0 0 4px;
+ text-overflow: ellipsis;
+ white-space: nowrap; }
+ .compact-cards .card-outer .card-description {
+ display: none; }
+ .compact-cards .card-outer .card-context {
+ background-color: var(--newtab-card-background-color);
+ border-radius: 16px;
+ clip-path: inset(-1px -1px 4px);
+ height: 32px;
+ width: 32px;
+ padding: 8px;
+ top: 91px;
+ inset-inline-end: 12px;
+ inset-inline-start: auto; }
+ .compact-cards .card-outer .card-context::after {
+ border: 1px solid var(--newtab-card-hairline-color);
+ border-bottom: 0;
+ border-radius: 17px 17px 0 0;
+ content: '';
+ position: absolute;
+ height: 17px;
+ width: 34px;
+ top: -1px;
+ left: -1px; }
+ .compact-cards .card-outer .card-context .card-context-icon {
+ margin-inline-end: 0;
+ height: 16px;
+ width: 16px; }
+ .compact-cards .card-outer .card-context .card-context-icon.icon-bookmark-added {
+ fill: #0A84FF; }
+ .compact-cards .card-outer .card-context .card-context-icon.icon-download {
+ fill: #12BC00; }
+ .compact-cards .card-outer .card-context .card-context-icon.icon-pocket {
+ fill: #D70022; }
+ .compact-cards .card-outer .card-context .card-context-label {
+ display: none; }
+
+@media not all and (min-width: 1122px) {
+ .compact-cards .hide-for-narrow {
+ display: none; } }
+
+.outer-wrapper.newtab-experience .collapsible-section[data-section-id='topsites'] .section-top-bar {
+ display: none; }
+
+.outer-wrapper.newtab-experience .collapsible-section .click-target-container .click-target span {
+ cursor: default;
+ font-weight: 600;
+ font-size: 17px;
+ color: var(--newtab-background-primary-text-color); }
+
+.outer-wrapper:not(.newtab-experience) .collapsible-section .section-title span {
+ vertical-align: middle; }
+
+.collapsible-section {
+ padding: 10px 25px;
+ transition-delay: 100ms;
+ transition-duration: 100ms;
+ transition-property: background-color; }
+ .collapsible-section .section-title {
+ font-size: 13px;
+ font-weight: bold;
+ margin: 0; }
+ .collapsible-section .section-title.grey-title,
+ .collapsible-section .section-title span {
+ color: var(--newtab-section-header-text-color);
+ display: inline-block;
+ fill: var(--newtab-section-header-text-color); }
+ .collapsible-section .section-title.grey-title {
+ vertical-align: middle; }
+ .collapsible-section .section-title .click-target-container {
+ vertical-align: top; }
+ @media (max-width: 609px) {
+ .collapsible-section .section-title .click-target-container {
+ display: block; }
+ .collapsible-section .section-title .click-target-container .learn-more-link-wrapper {
+ display: block;
+ text-align: center; }
+ .collapsible-section .section-title .click-target-container .learn-more-link-wrapper .learn-more-link {
+ margin-inline-start: 0; } }
+ .collapsible-section .section-title .click-target-container .click-target {
+ white-space: nowrap;
+ cursor: pointer; }
+ .collapsible-section .section-title .collapsible-arrow {
+ margin-inline-start: 8px;
+ margin-top: -1px; }
+ .collapsible-section .section-top-bar {
+ min-height: 19px;
+ margin-bottom: 13px;
+ position: relative; }
+ .collapsible-section .section-top-bar .context-menu-button {
+ background: url("chrome://global/skin/icons/more.svg") no-repeat right center;
+ border: 0;
+ cursor: pointer;
+ fill: var(--newtab-section-header-text-color);
+ height: 100%;
+ inset-inline-end: 0;
+ opacity: 0;
+ position: absolute;
+ top: 0;
+ transition-duration: 200ms;
+ transition-property: opacity;
+ width: 27px; }
+ .collapsible-section .section-top-bar .context-menu-button:is(:active, :focus, :hover) {
+ fill: var(--newtab-section-header-text-color);
+ opacity: 1; }
+ .collapsible-section .section-top-bar .context-menu {
+ top: 16px; }
+ @media (max-width: 1458px) {
+ .collapsible-section .section-top-bar .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; } }
+ .collapsible-section:hover .section-top-bar .context-menu-button, .collapsible-section.active .section-top-bar .context-menu-button {
+ opacity: 1; }
+ .collapsible-section.active {
+ background: var(--newtab-element-hover-color);
+ border-radius: 4px; }
+ .collapsible-section.active .section-top-bar .context-menu-button {
+ fill: var(--newtab-section-active-contextmenu-color); }
+ .collapsible-section .learn-more-link {
+ font-size: 11px;
+ margin-inline-start: 12px; }
+ .collapsible-section .learn-more-link a {
+ color: var(--newtab-link-secondary-color); }
+ .collapsible-section .section-body-fallback {
+ height: 266px; }
+ .collapsible-section .section-body {
+ margin: 0 -7px;
+ padding: 0 7px; }
+ .collapsible-section .section-body.animating {
+ overflow: hidden;
+ pointer-events: none; }
+ .collapsible-section.animation-enabled .section-title .collapsible-arrow {
+ transition: transform 0.5s cubic-bezier(0.07, 0.95, 0, 1); }
+ .collapsible-section.animation-enabled .section-body {
+ transition: max-height 0.5s cubic-bezier(0.07, 0.95, 0, 1); }
+ .collapsible-section.collapsed .section-body {
+ max-height: 0;
+ overflow: hidden; }
+ @media (min-width: 610px) and (max-width: 865px) {
+ .collapsible-section[data-section-id='topstories'] .card-outer:first-child {
+ display: none; } }
+
+.asrouter-toggle {
+ position: fixed;
+ top: 50px;
+ inset-inline-end: 15px;
+ border: 0;
+ background: none;
+ z-index: 1;
+ border-radius: 2px; }
+ .asrouter-toggle .icon-devtools {
+ background-image: url("chrome://browser/skin/developer.svg");
+ padding: 15px; }
+ .asrouter-toggle:dir(rtl) {
+ transform: scaleX(-1); }
+ .asrouter-toggle:hover {
+ background: var(--newtab-element-hover-color); }
+ .asrouter-toggle.expanded {
+ background: rgba(0, 0, 0, 0.2); }
+
+.asrouter-admin {
+ position: fixed;
+ top: 0;
+ inset-inline-start: 0;
+ width: 100%;
+ background: var(--newtab-background-color);
+ height: 100%;
+ overflow-y: scroll;
+ margin: 0 auto;
+ font-size: 14px;
+ padding-inline-start: 240px;
+ color: var(--newtab-text-primary-color); }
+ .asrouter-admin.collapsed {
+ display: none; }
+ .asrouter-admin .sidebar {
+ inset-inline-start: 0;
+ position: fixed;
+ width: 240px;
+ padding: 30px 20px; }
+ .asrouter-admin .sidebar ul {
+ margin: 0;
+ padding: 0;
+ list-style: none; }
+ .asrouter-admin .sidebar li a {
+ padding: 10px 34px;
+ display: block;
+ color: var(--lwt-sidebar-text-color); }
+ .asrouter-admin .sidebar li a:hover {
+ background: var(--newtab-textbox-background-color); }
+ .asrouter-admin h1 {
+ font-weight: 200;
+ font-size: 32px; }
+ .asrouter-admin h2 .button,
+ .asrouter-admin p .button {
+ font-size: 14px;
+ padding: 6px 12px;
+ margin-inline-start: 5px;
+ margin-bottom: 0; }
+ .asrouter-admin .general-textarea {
+ direction: ltr;
+ width: 740px;
+ height: 500px;
+ overflow: auto;
+ resize: none;
+ border-radius: 4px;
+ display: flex; }
+ .asrouter-admin .wnp-textarea {
+ direction: ltr;
+ width: 740px;
+ height: 500px;
+ overflow: auto;
+ resize: none;
+ border-radius: 4px;
+ display: flex; }
+ .asrouter-admin .json-button {
+ display: inline-flex;
+ font-size: 10px;
+ padding: 4px 10px;
+ margin-bottom: 6px;
+ margin-inline-end: 4px; }
+ .asrouter-admin .json-button:hover {
+ background-color: rgba(237, 237, 240, 0.6);
+ box-shadow: none; }
+ .asrouter-admin table {
+ border-collapse: collapse;
+ width: 100%; }
+ .asrouter-admin table.minimal-table {
+ border-collapse: collapse;
+ border: 1px solid var(--newtab-border-secondary-color); }
+ .asrouter-admin table.minimal-table td {
+ padding: 8px; }
+ .asrouter-admin table.minimal-table td:first-child {
+ width: 1%;
+ white-space: nowrap; }
+ .asrouter-admin table.minimal-table td:not(:first-child) {
+ font-family: "SF Mono", "Monaco", "Inconsolata", "Fira Mono", "Droid Sans Mono", "Source Code Pro", monospace; }
+ .asrouter-admin table.errorReporting tr {
+ border: 1px solid var(--newtab-textbox-background-color); }
+ .asrouter-admin table.errorReporting td {
+ padding: 4px; }
+ .asrouter-admin table.errorReporting td[rowspan] {
+ border: 1px solid var(--newtab-textbox-background-color); }
+ .asrouter-admin .sourceLabel {
+ background: var(--newtab-textbox-background-color);
+ padding: 2px 5px;
+ border-radius: 3px; }
+ .asrouter-admin .sourceLabel.isDisabled {
+ background: rgba(215, 0, 34, 0.3);
+ color: #D70022; }
+ .asrouter-admin .message-item:first-child td {
+ border-top: 1px solid var(--newtab-border-secondary-color); }
+ .asrouter-admin .message-item td {
+ vertical-align: top;
+ padding: 8px;
+ border-bottom: 1px solid var(--newtab-border-secondary-color); }
+ .asrouter-admin .message-item td.min {
+ width: 1%;
+ white-space: nowrap; }
+ .asrouter-admin .message-item td.message-summary {
+ width: 60%; }
+ .asrouter-admin .message-item td.button-column {
+ width: 15%; }
+ .asrouter-admin .message-item td:first-child {
+ border-inline-start: 1px solid var(--newtab-border-secondary-color); }
+ .asrouter-admin .message-item td:last-child {
+ border-inline-end: 1px solid var(--newtab-border-secondary-color); }
+ .asrouter-admin .message-item.blocked .message-id,
+ .asrouter-admin .message-item.blocked .message-summary {
+ opacity: 0.5; }
+ .asrouter-admin .message-item.blocked .message-id {
+ opacity: 0.5; }
+ .asrouter-admin .message-item .message-id {
+ font-family: "SF Mono", "Monaco", "Inconsolata", "Fira Mono", "Droid Sans Mono", "Source Code Pro", monospace;
+ font-size: 12px; }
+ .asrouter-admin .providerUrl {
+ font-size: 12px; }
+ .asrouter-admin pre {
+ background: var(--newtab-textbox-background-color);
+ margin: 0;
+ padding: 8px;
+ font-size: 12px;
+ max-width: 750px;
+ overflow: auto;
+ font-family: "SF Mono", "Monaco", "Inconsolata", "Fira Mono", "Droid Sans Mono", "Source Code Pro", monospace; }
+ .asrouter-admin .errorState {
+ border: 1px solid #D70022; }
+ .asrouter-admin .helpLink {
+ padding: 10px;
+ display: flex;
+ background: rgba(0, 0, 0, 0.1);
+ border-radius: 3px; }
+ .asrouter-admin .helpLink a {
+ text-decoration: underline; }
+ .asrouter-admin .ds-component {
+ margin-bottom: 20px; }
+ .asrouter-admin .modalOverlayInner {
+ height: 80%; }
+ .asrouter-admin .clearButton {
+ border: 0;
+ padding: 4px;
+ border-radius: 4px;
+ display: flex; }
+ .asrouter-admin .clearButton:hover {
+ background: var(--newtab-element-hover-color); }
+ .asrouter-admin .collapsed {
+ display: none; }
+ .asrouter-admin .icon {
+ display: inline-table;
+ cursor: pointer;
+ width: 18px;
+ height: 18px; }
+
+.pocket-logged-in-cta {
+ font-size: 13px;
+ margin-inline-end: 20px;
+ display: flex;
+ align-items: flex-start; }
+ .pocket-logged-in-cta .pocket-cta-button {
+ white-space: nowrap;
+ background: #0060DF;
+ letter-spacing: -0.34px;
+ color: #FFF;
+ border-radius: 4px;
+ cursor: pointer;
+ max-width: 130px;
+ margin-top: -1px;
+ min-height: 18px;
+ padding: 0 8px;
+ display: inline-flex;
+ justify-content: center;
+ align-items: center;
+ font-size: 11px;
+ margin-inline-end: 10px; }
+ .pocket-logged-in-cta .cta-text {
+ font-weight: normal;
+ font-size: 13px;
+ line-height: 1.230769231; }
+ .pocket-logged-in-cta .pocket-cta-button,
+ .pocket-logged-in-cta .cta-text {
+ vertical-align: top; }
+
+.more-recommendations {
+ display: flex;
+ align-items: center;
+ white-space: nowrap;
+ line-height: 1.230769231; }
+ .more-recommendations::after {
+ background: url("chrome://activity-stream/content/data/content/assets/topic-show-more-12.svg") no-repeat center center;
+ content: '';
+ -moz-context-properties: fill;
+ display: inline-block;
+ fill: var(--newtab-link-secondary-color);
+ height: 16px;
+ margin-inline-start: 5px;
+ vertical-align: top;
+ width: 12px; }
+ .more-recommendations:dir(rtl)::after {
+ transform: scaleX(-1); }
+
+.discovery-stream.ds-layout {
+ --gridColumnGap: 48px;
+ --gridRowGap: 24px;
+ grid-template-columns: repeat(12, 1fr);
+ grid-column-gap: var(--gridColumnGap);
+ grid-row-gap: var(--gridRowGap);
+ margin: 0 auto; }
+ .discovery-stream.ds-layout .ds-column-12 {
+ grid-column-start: auto;
+ grid-column-end: span 12; }
+ .discovery-stream.ds-layout .ds-column-11 {
+ grid-column-start: auto;
+ grid-column-end: span 11; }
+ .discovery-stream.ds-layout .ds-column-10 {
+ grid-column-start: auto;
+ grid-column-end: span 10; }
+ .discovery-stream.ds-layout .ds-column-9 {
+ grid-column-start: auto;
+ grid-column-end: span 9; }
+ .discovery-stream.ds-layout .ds-column-8 {
+ grid-column-start: auto;
+ grid-column-end: span 8; }
+ .discovery-stream.ds-layout .ds-column-7 {
+ grid-column-start: auto;
+ grid-column-end: span 7; }
+ .discovery-stream.ds-layout .ds-column-6 {
+ grid-column-start: auto;
+ grid-column-end: span 6; }
+ .discovery-stream.ds-layout .ds-column-5 {
+ grid-column-start: auto;
+ grid-column-end: span 5; }
+ .discovery-stream.ds-layout .ds-column-4 {
+ grid-column-start: auto;
+ grid-column-end: span 4; }
+ .discovery-stream.ds-layout .ds-column-3 {
+ grid-column-start: auto;
+ grid-column-end: span 3; }
+ .discovery-stream.ds-layout .ds-column-2 {
+ grid-column-start: auto;
+ grid-column-end: span 2; }
+ .discovery-stream.ds-layout .ds-column-1 {
+ grid-column-start: auto;
+ grid-column-end: span 1; }
+ .discovery-stream.ds-layout .ds-column-grid {
+ display: grid;
+ grid-row-gap: var(--gridRowGap); }
+ .discovery-stream.ds-layout .ds-column-grid > div:empty {
+ display: none; }
+
+.ds-header {
+ margin: 8px 0; }
+ .ds-header .ds-context {
+ font-weight: 400; }
+
+.ds-header,
+.ds-layout .section-title span {
+ color: #737373;
+ font-size: 13px;
+ font-weight: 600;
+ line-height: 20px; }
+ [lwt-newtab-brighttext] .ds-header, [lwt-newtab-brighttext]
+ .ds-layout .section-title span {
+ color: #D7D7DB; }
+ .ds-header .icon,
+ .ds-layout .section-title span .icon {
+ fill: var(--newtab-text-secondary-color); }
+
+.collapsible-section.ds-layout {
+ margin: auto; }
+ .collapsible-section.ds-layout .section-top-bar .learn-more-link a {
+ color: var(--newtab-link-primary-color);
+ font-weight: normal; }
+ .collapsible-section.ds-layout .section-top-bar .learn-more-link a:is(:focus, :hover) {
+ text-decoration: underline; }
+
+.outer-wrapper.newtab-experience .ds-card-grid.ds-card-grid-border .ds-card:not(.placeholder) {
+ border-radius: 8px;
+ box-shadow: 0 3px 8px var(--newtab-card-first-shadow), 0 0 2px var(--newtab-card-second-shadow); }
+ .outer-wrapper.newtab-experience .ds-card-grid.ds-card-grid-border .ds-card:not(.placeholder) .img-wrapper .img img {
+ border-radius: 8px 8px 0 0; }
+
+.outer-wrapper.newtab-experience .ds-card-grid .ds-card-link:focus {
+ border: 0;
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-focus-outline), 0 0 0 1px var(--newtab-focus-border);
+ transition: none;
+ border-radius: 8px; }
+
+.ds-card-grid {
+ display: grid;
+ grid-gap: 24px; }
+ .ds-card-grid .ds-card {
+ background: #FFF;
+ border-radius: 4px; }
+ [lwt-newtab-brighttext] .ds-card-grid .ds-card {
+ background: none; }
+ @media (min-width: 866px) {
+ .ds-column-12 .ds-card-grid.ds-card-grid-hero {
+ grid-template-columns: repeat(12, 1fr); }
+ .ds-column-12 .ds-card-grid.ds-card-grid-hero .ds-card:nth-child(1) {
+ grid-column-start: 1;
+ grid-column-end: span 6;
+ grid-row-start: 1;
+ grid-row-end: span 2; }
+ .ds-column-12 .ds-card-grid.ds-card-grid-hero .ds-card:nth-child(1) .excerpt {
+ -webkit-line-clamp: 4; }
+ .ds-column-12 .ds-card-grid.ds-card-grid-hero .ds-card:nth-child(2),
+ .ds-column-12 .ds-card-grid.ds-card-grid-hero .ds-card:nth-child(4) {
+ grid-column-start: 7;
+ grid-column-end: span 3; }
+ .ds-column-12 .ds-card-grid.ds-card-grid-hero .ds-card:nth-child(3),
+ .ds-column-12 .ds-card-grid.ds-card-grid-hero .ds-card:nth-child(5) {
+ grid-column-start: 10;
+ grid-column-end: span 3; }
+ .ds-column-12 .ds-card-grid.ds-card-grid-hero .ds-card:nth-child(n+2):nth-child(-n+5) .excerpt {
+ display: none; }
+ .ds-column-12 .ds-card-grid.ds-card-grid-hero .ds-card:nth-child(n+2):nth-child(-n+5) .meta {
+ padding: 8px; }
+ .ds-column-12 .ds-card-grid.ds-card-grid-hero .ds-card:nth-child(n+2):nth-child(-n+5) .meta .title {
+ font-size: 13px;
+ line-height: 19px; }
+ .ds-column-12 .ds-card-grid.ds-card-grid-hero .ds-card:nth-child(n+2):nth-child(-n+5) .meta .story-sponsored-label {
+ -webkit-line-clamp: none;
+ line-height: 19px; }
+ .ds-column-12 .ds-card-grid.ds-card-grid-hero .ds-card:nth-child(n+6) {
+ grid-column-start: auto;
+ grid-column-end: span 4; } }
+ @media (min-width: 1122px) {
+ .ds-column-12 .ds-card-grid.ds-card-grid-hero .ds-card:nth-child(n+2):nth-child(-n+5) {
+ min-height: 222px; } }
+ .ds-card-grid.ds-card-grid-border .ds-card:not(.placeholder) {
+ box-shadow: 0 1px 4px 0 rgba(12, 12, 13, 0.1); }
+ [lwt-newtab-brighttext] .ds-card-grid.ds-card-grid-border .ds-card:not(.placeholder) {
+ box-shadow: 0 1px 4px rgba(12, 12, 13, 0.1);
+ background: #38383D; }
+ .ds-card-grid.ds-card-grid-border .ds-card:not(.placeholder) .img-wrapper .img img {
+ border-radius: 4px 4px 0 0; }
+ .ds-card-grid.ds-card-grid-no-border .ds-card {
+ background: none; }
+ .ds-card-grid.ds-card-grid-no-border .ds-card .meta {
+ padding: 12px 0; }
+ .ds-column-5 .ds-card-grid,
+ .ds-column-6 .ds-card-grid,
+ .ds-column-7 .ds-card-grid,
+ .ds-column-8 .ds-card-grid {
+ grid-template-columns: repeat(2, 1fr); }
+ .ds-column-9 .ds-card-grid,
+ .ds-column-10 .ds-card-grid,
+ .ds-column-11 .ds-card-grid,
+ .ds-column-12 .ds-card-grid {
+ grid-template-columns: repeat(1, 1fr); }
+ @media (min-width: 610px) {
+ .ds-column-9 .ds-card-grid,
+ .ds-column-10 .ds-card-grid,
+ .ds-column-11 .ds-card-grid,
+ .ds-column-12 .ds-card-grid {
+ grid-template-columns: repeat(2, 1fr); } }
+ @media (min-width: 866px) {
+ .ds-column-9 .ds-card-grid,
+ .ds-column-10 .ds-card-grid,
+ .ds-column-11 .ds-card-grid,
+ .ds-column-12 .ds-card-grid {
+ grid-template-columns: repeat(3, 1fr); } }
+ .ds-column-9 .ds-card-grid .title,
+ .ds-column-10 .ds-card-grid .title,
+ .ds-column-11 .ds-card-grid .title,
+ .ds-column-12 .ds-card-grid .title {
+ font-size: 17px;
+ line-height: 24px; }
+ .ds-column-9 .ds-card-grid .excerpt,
+ .ds-column-10 .ds-card-grid .excerpt,
+ .ds-column-11 .ds-card-grid .excerpt,
+ .ds-column-12 .ds-card-grid .excerpt {
+ font-size: 15px;
+ -webkit-line-clamp: 3;
+ line-height: 24px; }
+ .ds-card-grid.empty {
+ grid-template-columns: auto; }
+
+.ds-dismiss.ds-dismiss-ds-collection .ds-dismiss-button {
+ margin: 15px 0 0;
+ inset-inline-end: 25px; }
+
+.ds-dismiss.ds-dismiss-ds-collection.hovering {
+ background: var(--newtab-element-hover-color); }
+
+.ds-collection-card-grid {
+ padding: 10px 25px 25px;
+ margin: 0 0 20px; }
+ .ds-collection-card-grid .story-footer {
+ display: none; }
+ .ds-collection-card-grid .ds-header {
+ padding: 0 40px 0 0;
+ margin-bottom: 12px; }
+ .ds-collection-card-grid .ds-header .title {
+ color: #0C0C0D;
+ font-weight: 600;
+ font-size: 17px;
+ line-height: 24px; }
+ [lwt-newtab-brighttext] .ds-collection-card-grid .ds-header .title {
+ color: #D7D7DB; }
+ .ds-collection-card-grid .ds-header .ds-context {
+ color: #737373;
+ font-weight: normal;
+ font-size: 13px;
+ line-height: 24px; }
+ [lwt-newtab-brighttext] .ds-collection-card-grid .ds-header .ds-context {
+ color: #B1B1B3; }
+
+.ds-hero {
+ position: relative; }
+ .ds-hero header {
+ font-weight: 600; }
+ .ds-hero p {
+ line-height: 1.538;
+ margin: 8px 0; }
+ .ds-hero .excerpt {
+ font-size: 15px;
+ -webkit-line-clamp: 3;
+ line-height: 24px;
+ color: #0C0C0D;
+ margin: 0 0 10px; }
+ [lwt-newtab-brighttext] .ds-hero .excerpt {
+ color: #F9F9FA; }
+ .ds-hero .ds-card:not(.placeholder) {
+ border: 0;
+ padding-bottom: 20px; }
+ .ds-hero .ds-card:not(.placeholder):hover {
+ border: 0;
+ box-shadow: none;
+ border-radius: 0; }
+ .ds-hero .ds-card:not(.placeholder) .meta {
+ padding: 0; }
+ .ds-hero .ds-card:not(.placeholder) .img-wrapper {
+ margin: 0 0 12px; }
+ .ds-hero .ds-card.placeholder {
+ margin-bottom: 20px;
+ padding-bottom: 20px;
+ min-height: 180px; }
+ .ds-hero .img-wrapper {
+ margin: 0 0 12px; }
+ .ds-hero .ds-hero-item {
+ position: relative; }
+ .ds-hero .wrapper {
+ border-top: 1px solid #D7D7DB;
+ color: #737373;
+ display: block;
+ margin: 12px 0 16px;
+ padding-top: 16px;
+ height: 100%; }
+ [lwt-newtab-brighttext] .ds-hero .wrapper {
+ border-top: 1px solid #4A4A4F; }
+ [lwt-newtab-brighttext] .ds-hero .wrapper {
+ color: #D7D7DB; }
+ .ds-hero .wrapper:focus {
+ box-shadow: 0 0 0 5px rgba(10, 132, 255, 0.3);
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+ .ds-hero-no-border .ds-hero-item .wrapper {
+ border-top: 0;
+ border-bottom: 0;
+ padding: 0 0 8px; }
+ .ds-hero .wrapper:hover .meta header {
+ color: #0060DF; }
+ [lwt-newtab-brighttext] .ds-hero .wrapper:hover .meta header {
+ color: #45A1FF; }
+ .ds-hero .wrapper:active .meta header {
+ color: #003EAA; }
+ [lwt-newtab-brighttext] .ds-hero .wrapper:active .meta header {
+ color: #45A1FF; }
+ .ds-hero .wrapper .img-wrapper {
+ width: 100%; }
+ .ds-hero .wrapper .img {
+ height: 0;
+ padding-top: 50%; }
+ .ds-hero .wrapper .img img {
+ border-radius: 4px;
+ box-shadow: inset 0 0 0 0.5px rgba(0, 0, 0, 0.15); }
+ .ds-hero .wrapper .meta {
+ display: block;
+ flex-direction: column;
+ justify-content: space-between; }
+ .ds-hero .wrapper .meta .header-and-excerpt {
+ flex: 1; }
+ .ds-hero .wrapper .meta header {
+ font-size: 22px;
+ -webkit-line-clamp: 4;
+ line-height: 28px;
+ color: #0C0C0D;
+ margin-bottom: 0; }
+ [lwt-newtab-brighttext] .ds-hero .wrapper .meta header {
+ color: #FFF; }
+ .ds-hero .wrapper .meta .context,
+ .ds-hero .wrapper .meta .source {
+ margin: 0 0 4px; }
+ .ds-hero .wrapper .meta .context {
+ color: #008EA4; }
+ [lwt-newtab-brighttext] .ds-hero .wrapper .meta .context {
+ color: #A7FFFE; }
+ .ds-hero .wrapper .meta .source {
+ font-size: 13px;
+ color: #737373;
+ -webkit-line-clamp: 1;
+ margin-bottom: 0; }
+ [lwt-newtab-brighttext] .ds-hero .wrapper .meta .source {
+ color: #B1B1B3; }
+ .ds-column-5 .ds-hero .wrapper,
+ .ds-column-6 .ds-hero .wrapper,
+ .ds-column-7 .ds-hero .wrapper,
+ .ds-column-8 .ds-hero .wrapper {
+ display: grid;
+ grid-template-columns: repeat(2, 1fr);
+ grid-column-gap: 24px; }
+ .ds-column-5 .ds-hero .wrapper .img-wrapper,
+ .ds-column-6 .ds-hero .wrapper .img-wrapper,
+ .ds-column-7 .ds-hero .wrapper .img-wrapper,
+ .ds-column-8 .ds-hero .wrapper .img-wrapper {
+ margin: 0;
+ grid-column: 2;
+ grid-row: 1; }
+ .ds-column-5 .ds-hero .wrapper .meta,
+ .ds-column-6 .ds-hero .wrapper .meta,
+ .ds-column-7 .ds-hero .wrapper .meta,
+ .ds-column-8 .ds-hero .wrapper .meta {
+ grid-column: 1;
+ grid-row: 1;
+ display: flex; }
+ .ds-column-5 .ds-hero .wrapper .img,
+ .ds-column-6 .ds-hero .wrapper .img,
+ .ds-column-7 .ds-hero .wrapper .img,
+ .ds-column-8 .ds-hero .wrapper .img {
+ height: 0;
+ padding-top: 100%; }
+ .ds-column-5 .ds-hero .cards,
+ .ds-column-6 .ds-hero .cards,
+ .ds-column-7 .ds-hero .cards,
+ .ds-column-8 .ds-hero .cards {
+ display: grid;
+ grid-template-columns: repeat(2, 1fr);
+ grid-column-gap: 24px;
+ grid-auto-rows: min-content; }
+ .ds-column-9 .ds-hero,
+ .ds-column-10 .ds-hero,
+ .ds-column-11 .ds-hero,
+ .ds-column-12 .ds-hero {
+ display: grid;
+ grid-template-columns: repeat(2, 1fr);
+ grid-column-gap: 24px; }
+ .ds-column-9 .ds-hero.ds-hero-border,
+ .ds-column-10 .ds-hero.ds-hero-border,
+ .ds-column-11 .ds-hero.ds-hero-border,
+ .ds-column-12 .ds-hero.ds-hero-border {
+ border-top: 1px solid #D7D7DB;
+ padding: 20px 0; }
+ [lwt-newtab-brighttext] .ds-column-9 .ds-hero.ds-hero-border, [lwt-newtab-brighttext]
+ .ds-column-10 .ds-hero.ds-hero-border, [lwt-newtab-brighttext]
+ .ds-column-11 .ds-hero.ds-hero-border, [lwt-newtab-brighttext]
+ .ds-column-12 .ds-hero.ds-hero-border {
+ border-top: 1px solid #4A4A4F; }
+ .ds-column-9 .ds-hero.ds-hero-border .ds-card:not(.placeholder):nth-child(-n+2),
+ .ds-column-10 .ds-hero.ds-hero-border .ds-card:not(.placeholder):nth-child(-n+2),
+ .ds-column-11 .ds-hero.ds-hero-border .ds-card:not(.placeholder):nth-child(-n+2),
+ .ds-column-12 .ds-hero.ds-hero-border .ds-card:not(.placeholder):nth-child(-n+2) {
+ border-bottom: 1px solid #D7D7DB;
+ margin-bottom: 20px; }
+ [lwt-newtab-brighttext] .ds-column-9 .ds-hero.ds-hero-border .ds-card:not(.placeholder):nth-child(-n+2), [lwt-newtab-brighttext]
+ .ds-column-10 .ds-hero.ds-hero-border .ds-card:not(.placeholder):nth-child(-n+2), [lwt-newtab-brighttext]
+ .ds-column-11 .ds-hero.ds-hero-border .ds-card:not(.placeholder):nth-child(-n+2), [lwt-newtab-brighttext]
+ .ds-column-12 .ds-hero.ds-hero-border .ds-card:not(.placeholder):nth-child(-n+2) {
+ border-bottom: 1px solid #4A4A4F; }
+ .ds-column-9 .ds-hero .wrapper,
+ .ds-column-10 .ds-hero .wrapper,
+ .ds-column-11 .ds-hero .wrapper,
+ .ds-column-12 .ds-hero .wrapper {
+ border-top: 0;
+ border-bottom: 0;
+ margin: 0;
+ padding: 0 0 20px;
+ display: flex;
+ flex-direction: column; }
+ .ds-column-9 .ds-hero .wrapper .img-wrapper,
+ .ds-column-10 .ds-hero .wrapper .img-wrapper,
+ .ds-column-11 .ds-hero .wrapper .img-wrapper,
+ .ds-column-12 .ds-hero .wrapper .img-wrapper {
+ margin: 0; }
+ .ds-column-9 .ds-hero .wrapper .img,
+ .ds-column-10 .ds-hero .wrapper .img,
+ .ds-column-11 .ds-hero .wrapper .img,
+ .ds-column-12 .ds-hero .wrapper .img {
+ margin-bottom: 12px;
+ height: 0;
+ padding-top: 50%; }
+ .ds-column-9 .ds-hero .wrapper .meta,
+ .ds-column-10 .ds-hero .wrapper .meta,
+ .ds-column-11 .ds-hero .wrapper .meta,
+ .ds-column-12 .ds-hero .wrapper .meta {
+ flex-grow: 1;
+ display: flex;
+ padding: 0 24px 0 0; }
+ .ds-column-9 .ds-hero .wrapper .meta header,
+ .ds-column-10 .ds-hero .wrapper .meta header,
+ .ds-column-11 .ds-hero .wrapper .meta header,
+ .ds-column-12 .ds-hero .wrapper .meta header {
+ font-size: 22px;
+ -webkit-line-clamp: 3;
+ line-height: 28px; }
+ .ds-column-9 .ds-hero .wrapper .meta .source,
+ .ds-column-10 .ds-hero .wrapper .meta .source,
+ .ds-column-11 .ds-hero .wrapper .meta .source,
+ .ds-column-12 .ds-hero .wrapper .meta .source {
+ margin-bottom: 0; }
+ .ds-column-9 .ds-hero .cards,
+ .ds-column-10 .ds-hero .cards,
+ .ds-column-11 .ds-hero .cards,
+ .ds-column-12 .ds-hero .cards {
+ display: grid;
+ grid-template-columns: repeat(2, 1fr);
+ grid-column-gap: 24px;
+ grid-auto-rows: min-content; }
+ [lwt-newtab-brighttext] .ds-column-9 .ds-hero .cards .ds-card:hover, [lwt-newtab-brighttext]
+ .ds-column-10 .ds-hero .cards .ds-card:hover, [lwt-newtab-brighttext]
+ .ds-column-11 .ds-hero .cards .ds-card:hover, [lwt-newtab-brighttext]
+ .ds-column-12 .ds-hero .cards .ds-card:hover {
+ background: none; }
+ [lwt-newtab-brighttext] .ds-column-9 .ds-hero .cards .ds-card:hover .title, [lwt-newtab-brighttext]
+ .ds-column-10 .ds-hero .cards .ds-card:hover .title, [lwt-newtab-brighttext]
+ .ds-column-11 .ds-hero .cards .ds-card:hover .title, [lwt-newtab-brighttext]
+ .ds-column-12 .ds-hero .cards .ds-card:hover .title {
+ color: #45A1FF; }
+ [lwt-newtab-brighttext] .ds-column-9 .ds-hero .cards .ds-card:active .title, [lwt-newtab-brighttext]
+ .ds-column-10 .ds-hero .cards .ds-card:active .title, [lwt-newtab-brighttext]
+ .ds-column-11 .ds-hero .cards .ds-card:active .title, [lwt-newtab-brighttext]
+ .ds-column-12 .ds-hero .cards .ds-card:active .title {
+ color: #0A84FF; }
+ .ds-column-9 .ds-hero .cards .ds-card .title,
+ .ds-column-10 .ds-hero .cards .ds-card .title,
+ .ds-column-11 .ds-hero .cards .ds-card .title,
+ .ds-column-12 .ds-hero .cards .ds-card .title {
+ font-size: 14px;
+ -webkit-line-clamp: 3;
+ line-height: 20px; }
+ [lwt-newtab-brighttext] .ds-column-9 .ds-hero .cards .ds-card .title, [lwt-newtab-brighttext]
+ .ds-column-10 .ds-hero .cards .ds-card .title, [lwt-newtab-brighttext]
+ .ds-column-11 .ds-hero .cards .ds-card .title, [lwt-newtab-brighttext]
+ .ds-column-12 .ds-hero .cards .ds-card .title {
+ color: #FFF; }
+ .ds-hero.empty {
+ grid-template-columns: auto; }
+
+.ds-highlights .section .section-list {
+ grid-gap: var(--gridRowGap);
+ grid-template-columns: repeat(1, 1fr); }
+ @media (min-width: 610px) {
+ .ds-highlights .section .section-list {
+ grid-template-columns: repeat(2, 1fr); } }
+ @media (min-width: 866px) {
+ .ds-highlights .section .section-list {
+ grid-template-columns: repeat(4, 1fr); } }
+ .ds-highlights .section .section-list .card-outer {
+ height: 175px; }
+ .ds-highlights .section .section-list .card-outer .card-host-name {
+ font-size: 13px;
+ line-height: 20px;
+ margin-bottom: 2px;
+ padding-bottom: 0;
+ text-transform: unset; }
+ .ds-highlights .section .section-list .card-outer .card-title {
+ font-size: 14px;
+ font-weight: 600;
+ line-height: 20px;
+ max-height: 20px; }
+
+.ds-highlights .hide-for-narrow {
+ display: block; }
+
+.ds-hr {
+ border: 0;
+ border-top: 1px solid #D7D7DB;
+ height: 0; }
+ [lwt-newtab-brighttext] .ds-hr {
+ border-top: 1px solid #4A4A4F; }
+
+.ds-list {
+ display: grid;
+ grid-row-gap: 24px;
+ grid-column-gap: 24px;
+ padding-inline-start: 0; }
+ .ds-list:not(.ds-list-full-width) .ds-list-item {
+ font-size: 14px;
+ line-height: 20px;
+ position: relative; }
+ .ds-list:not(.ds-list-full-width) .ds-list-item-title {
+ font-size: 14px;
+ -webkit-line-clamp: 3;
+ line-height: 20px; }
+ .ds-list:not(.ds-list-full-width) .ds-list-image {
+ min-width: 80px;
+ width: 80px; }
+ .ds-column-5 .ds-list:not(.ds-list-full-width),
+ .ds-column-6 .ds-list:not(.ds-list-full-width),
+ .ds-column-7 .ds-list:not(.ds-list-full-width),
+ .ds-column-8 .ds-list:not(.ds-list-full-width) {
+ grid-template-columns: repeat(2, 1fr); }
+ .ds-column-9 .ds-list:not(.ds-list-full-width),
+ .ds-column-10 .ds-list:not(.ds-list-full-width),
+ .ds-column-11 .ds-list:not(.ds-list-full-width),
+ .ds-column-12 .ds-list:not(.ds-list-full-width) {
+ grid-template-columns: repeat(3, 1fr); }
+ .ds-list:not(.ds-list-full-width).empty {
+ grid-template-columns: auto; }
+ .ds-list:not(.ds-list-full-width) .ds-list-item-excerpt {
+ display: none; }
+ .ds-list:not(.ds-list-images) .ds-list-image {
+ display: none; }
+ .ds-list a {
+ color: #0C0C0D; }
+ [lwt-newtab-brighttext] .ds-list a {
+ color: #F9F9FA; }
+
+.ds-list-item-link:focus {
+ box-shadow: 0 0 0 5px rgba(10, 132, 255, 0.3);
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+
+.ds-list-numbers .ds-list-item {
+ counter-increment: list; }
+
+.ds-list-numbers .ds-list-item:not(.placeholder) > .ds-list-item-link {
+ padding-inline-start: 41px; }
+ .ds-list-numbers .ds-list-item:not(.placeholder) > .ds-list-item-link::before {
+ background-color: #50BCB6;
+ border-radius: 32px;
+ color: #FFF;
+ content: counter(list);
+ font-size: 17px;
+ height: 32px;
+ line-height: 32px;
+ margin-inline-start: -41px;
+ margin-top: 3px;
+ position: absolute;
+ text-align: center;
+ width: 32px; }
+ [lwt-newtab-brighttext] .ds-list-numbers .ds-list-item:not(.placeholder) > .ds-list-item-link::before {
+ background-color: #008EA4; }
+ .ds-list-numbers .ds-list-item:not(.placeholder) > .ds-list-item-link:hover::before {
+ background-color: #45A1FF; }
+ [lwt-newtab-brighttext] .ds-list-numbers .ds-list-item:not(.placeholder) > .ds-list-item-link:hover::before {
+ background-color: #45A1FF; }
+ .ds-list-numbers .ds-list-item:not(.placeholder) > .ds-list-item-link:active::before {
+ background-color: #003EAA; }
+ [lwt-newtab-brighttext] .ds-list-numbers .ds-list-item:not(.placeholder) > .ds-list-item-link:active::before {
+ background-color: #0060DF; }
+
+.ds-list-borders {
+ border-top: 1px solid #D7D7DB;
+ grid-row-gap: 16px;
+ padding-top: 16px; }
+ [lwt-newtab-brighttext] .ds-list-borders {
+ border-top: 1px solid #4A4A4F; }
+ .ds-list-borders.ds-list-full-width .ds-list-item:not(.placeholder):not(:nth-last-child(-n+1)),
+ .ds-column-1 .ds-list-borders .ds-list-item:not(.placeholder):not(:nth-last-child(-n+1)),
+ .ds-column-2 .ds-list-borders .ds-list-item:not(.placeholder):not(:nth-last-child(-n+1)),
+ .ds-column-3 .ds-list-borders .ds-list-item:not(.placeholder):not(:nth-last-child(-n+1)),
+ .ds-column-4 .ds-list-borders .ds-list-item:not(.placeholder):not(:nth-last-child(-n+1)) {
+ border-bottom: 1px solid #D7D7DB;
+ margin-bottom: -1px;
+ padding-bottom: 16px; }
+ [lwt-newtab-brighttext] .ds-list-borders.ds-list-full-width .ds-list-item:not(.placeholder):not(:nth-last-child(-n+1)), [lwt-newtab-brighttext]
+ .ds-column-1 .ds-list-borders .ds-list-item:not(.placeholder):not(:nth-last-child(-n+1)), [lwt-newtab-brighttext]
+ .ds-column-2 .ds-list-borders .ds-list-item:not(.placeholder):not(:nth-last-child(-n+1)), [lwt-newtab-brighttext]
+ .ds-column-3 .ds-list-borders .ds-list-item:not(.placeholder):not(:nth-last-child(-n+1)), [lwt-newtab-brighttext]
+ .ds-column-4 .ds-list-borders .ds-list-item:not(.placeholder):not(:nth-last-child(-n+1)) {
+ border-bottom: 1px solid #4A4A4F; }
+ .ds-column-5 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+2)),
+ .ds-column-6 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+2)),
+ .ds-column-7 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+2)),
+ .ds-column-8 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+2)) {
+ border-bottom: 1px solid #D7D7DB;
+ margin-bottom: -1px;
+ padding-bottom: 16px; }
+ [lwt-newtab-brighttext] .ds-column-5 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+2)), [lwt-newtab-brighttext]
+ .ds-column-6 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+2)), [lwt-newtab-brighttext]
+ .ds-column-7 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+2)), [lwt-newtab-brighttext]
+ .ds-column-8 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+2)) {
+ border-bottom: 1px solid #4A4A4F; }
+ .ds-column-9 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+3)),
+ .ds-column-10 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+3)),
+ .ds-column-11 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+3)),
+ .ds-column-12 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+3)) {
+ border-bottom: 1px solid #D7D7DB;
+ margin-bottom: -1px;
+ padding-bottom: 16px; }
+ [lwt-newtab-brighttext] .ds-column-9 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+3)), [lwt-newtab-brighttext]
+ .ds-column-10 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+3)), [lwt-newtab-brighttext]
+ .ds-column-11 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+3)), [lwt-newtab-brighttext]
+ .ds-column-12 .ds-list-borders:not(.ds-list-full-width) .ds-list-item:not(.placeholder):not(:nth-last-child(-n+3)) {
+ border-bottom: 1px solid #4A4A4F; }
+
+.ds-list-full-width .ds-list-item {
+ font-size: 17px;
+ line-height: 24px;
+ position: relative; }
+
+.ds-list-full-width .ds-list-item-title {
+ font-size: 17px;
+ -webkit-line-clamp: 3;
+ line-height: 24px; }
+
+.ds-list-full-width .ds-list-image {
+ min-width: 160px;
+ width: 160px; }
+
+.ds-list-item {
+ display: block;
+ text-align: start; }
+ .ds-list-item.placeholder {
+ background: transparent;
+ min-height: 80px;
+ box-shadow: inset 0 0 0 1px var(--newtab-inner-box-shadow-color);
+ border-radius: 4px; }
+ .ds-list-item.placeholder .ds-list-item-link {
+ cursor: default; }
+ .ds-list-item.placeholder .ds-list-image {
+ opacity: 0; }
+ .ds-list-item .ds-list-item-link {
+ mix-blend-mode: normal;
+ display: flex;
+ justify-content: space-between;
+ height: 100%; }
+ .ds-list-item .ds-list-item-excerpt {
+ font-size: 14px;
+ -webkit-line-clamp: 2;
+ line-height: 20px;
+ color: #737373;
+ margin: 4px 0 8px; }
+ [lwt-newtab-brighttext] .ds-list-item .ds-list-item-excerpt {
+ color: rgba(249, 249, 250, 0.8); }
+ .ds-list-item p {
+ font-size: 14px;
+ line-height: 20px;
+ margin: 0; }
+ .ds-list-item .ds-list-item-info {
+ font-size: 14px;
+ -webkit-line-clamp: 1;
+ line-height: 20px;
+ color: #737373;
+ font-size: 13px; }
+ [lwt-newtab-brighttext] .ds-list-item .ds-list-item-info {
+ color: #B1B1B3; }
+ .ds-list-item .ds-list-item-title {
+ font-weight: 600;
+ margin-bottom: 4px; }
+ .ds-list-item .ds-list-item-body {
+ flex: 1; }
+ .ds-list-item .ds-list-item-text {
+ display: flex;
+ flex-direction: column;
+ justify-content: space-between; }
+ .ds-list-item .ds-list-image {
+ height: 80px;
+ margin-inline-start: 14px;
+ min-height: 80px; }
+ .ds-list-item .ds-list-image img {
+ border-radius: 4px;
+ box-shadow: inset 0 0 0 0.5px rgba(0, 0, 0, 0.15); }
+ .ds-list-item:hover .ds-list-item-title {
+ color: #45A1FF; }
+ .ds-list-item:active .ds-list-item-title {
+ color: #003EAA; }
+
+.outer-wrapper.newtab-experience .ds-navigation {
+ color: var(--newtab-background-primary-text-color); }
+
+.ds-navigation {
+ color: #737373;
+ padding: 4px 0;
+ font-weight: 600;
+ line-height: 22px;
+ font-size: 11.5px; }
+ [lwt-newtab-brighttext] .ds-navigation {
+ color: #D7D7DB; }
+ @media (min-width: 1122px) {
+ .ds-navigation {
+ line-height: 32px;
+ font-size: 14px; } }
+ .ds-navigation.ds-navigation-centered {
+ text-align: center; }
+ .ds-navigation.ds-navigation-right-aligned {
+ text-align: end; }
+ .ds-navigation ul {
+ display: inline;
+ margin: 0;
+ padding: 0; }
+ .ds-navigation ul li {
+ display: inline-block; }
+ .ds-navigation ul li::after {
+ content: '·';
+ padding: 6px; }
+ .ds-navigation ul li:last-child::after {
+ content: none; }
+ .ds-navigation ul li a:hover, .ds-navigation ul li a:active {
+ text-decoration: underline; }
+ .ds-navigation ul li a:active {
+ color: #003EAA; }
+ .ds-navigation .ds-navigation-header {
+ padding-inline-end: 6px; }
+
+.ds-section-title {
+ text-align: center;
+ margin-top: 24px; }
+ .ds-section-title .title {
+ line-height: 48px;
+ font-size: 36px;
+ font-weight: 300;
+ color: #0C0C0D; }
+ [lwt-newtab-brighttext] .ds-section-title .title {
+ color: #FFF; }
+ .ds-section-title .subtitle {
+ line-height: 24px;
+ font-size: 14px;
+ color: #737373;
+ margin-top: 4px; }
+ [lwt-newtab-brighttext] .ds-section-title .subtitle {
+ color: #D7D7DB; }
+
+.outer-wrapper:not(.newtab-experience) .ds-top-sites .top-sites .top-site-outer {
+ padding: 0 12px; }
+ .outer-wrapper:not(.newtab-experience) .ds-top-sites .top-sites .top-site-outer .top-site-inner > a:is(.active, :focus) .tile {
+ box-shadow: 0 0 0 5px rgba(10, 132, 255, 0.3);
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+ [lwt-newtab-brighttext] .outer-wrapper:not(.newtab-experience) .ds-top-sites .top-sites .top-site-outer .top-site-inner > a:is(.active, :focus) .tile {
+ box-shadow: 0 0 0 5px rgba(69, 161, 255, 0.4);
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+ .outer-wrapper:not(.newtab-experience) .ds-top-sites .top-sites .top-site-outer .top-site-inner > a:is(:hover) .tile {
+ box-shadow: 0 0 0 5px #D7D7DB;
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+ [lwt-newtab-brighttext] .outer-wrapper:not(.newtab-experience) .ds-top-sites .top-sites .top-site-outer .top-site-inner > a:is(:hover) .tile {
+ box-shadow: 0 0 0 5px #4A4A4F;
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+
+.outer-wrapper:not(.newtab-experience) .ds-top-sites .top-sites .top-sites-list {
+ margin: 0 -12px; }
+
+.outer-wrapper.newtab-experience .ds-top-sites .top-sites .top-site-outer .top-site-inner > a:is(.active, :focus) .tile {
+ border: 0;
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-focus-outline), 0 0 0 1px var(--newtab-focus-border); }
+
+.outer-wrapper.newtab-experience .ds-top-sites .top-sites .top-site-outer .top-site-inner > a:is(:hover) .top-site-inner {
+ box-shadow: 0 0 0 5px #D7D7DB;
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+ [lwt-newtab-brighttext] .outer-wrapper.newtab-experience .ds-top-sites .top-sites .top-site-outer .top-site-inner > a:is(:hover) .top-site-inner {
+ box-shadow: 0 0 0 5px #4A4A4F;
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+
+.outer-wrapper.newtab-experience .ds-top-sites .top-sites .top-sites-list {
+ margin: 0 -12px; }
+
+.ds-column-5 .ds-top-sites .top-site-outer,
+.ds-column-6 .ds-top-sites .top-site-outer,
+.ds-column-7 .ds-top-sites .top-site-outer,
+.ds-column-8 .ds-top-sites .top-site-outer {
+ padding: 0 10px; }
+
+.ds-column-5 .ds-top-sites .top-sites-list,
+.ds-column-6 .ds-top-sites .top-sites-list,
+.ds-column-7 .ds-top-sites .top-sites-list,
+.ds-column-8 .ds-top-sites .top-sites-list {
+ margin: 0 -10px; }
+
+.ds-column-5 .ds-top-sites .top-site-inner,
+.ds-column-6 .ds-top-sites .top-site-inner,
+.ds-column-7 .ds-top-sites .top-site-inner,
+.ds-column-8 .ds-top-sites .top-site-inner {
+ --leftPanelIconWidth: 84.67px; }
+ .ds-column-5 .ds-top-sites .top-site-inner .tile,
+ .ds-column-6 .ds-top-sites .top-site-inner .tile,
+ .ds-column-7 .ds-top-sites .top-site-inner .tile,
+ .ds-column-8 .ds-top-sites .top-site-inner .tile {
+ width: var(--leftPanelIconWidth);
+ height: var(--leftPanelIconWidth); }
+ .ds-column-5 .ds-top-sites .top-site-inner .title,
+ .ds-column-6 .ds-top-sites .top-site-inner .title,
+ .ds-column-7 .ds-top-sites .top-site-inner .title,
+ .ds-column-8 .ds-top-sites .top-site-inner .title {
+ width: var(--leftPanelIconWidth); }
+
+.ds-column-1 .ds-top-sites .top-site-outer,
+.ds-column-2 .ds-top-sites .top-site-outer,
+.ds-column-3 .ds-top-sites .top-site-outer,
+.ds-column-4 .ds-top-sites .top-site-outer {
+ padding: 0 8px; }
+
+.ds-column-1 .ds-top-sites .top-sites-list,
+.ds-column-2 .ds-top-sites .top-sites-list,
+.ds-column-3 .ds-top-sites .top-sites-list,
+.ds-column-4 .ds-top-sites .top-sites-list {
+ margin: 0 -8px; }
+
+.ds-column-1 .ds-top-sites .top-site-inner,
+.ds-column-2 .ds-top-sites .top-site-inner,
+.ds-column-3 .ds-top-sites .top-site-inner,
+.ds-column-4 .ds-top-sites .top-site-inner {
+ --rightPanelIconWidth: 82.67px; }
+ .ds-column-1 .ds-top-sites .top-site-inner .tile,
+ .ds-column-2 .ds-top-sites .top-site-inner .tile,
+ .ds-column-3 .ds-top-sites .top-site-inner .tile,
+ .ds-column-4 .ds-top-sites .top-site-inner .tile {
+ width: var(--rightPanelIconWidth);
+ height: var(--rightPanelIconWidth); }
+ .ds-column-1 .ds-top-sites .top-site-inner .title,
+ .ds-column-2 .ds-top-sites .top-site-inner .title,
+ .ds-column-3 .ds-top-sites .top-site-inner .title,
+ .ds-column-4 .ds-top-sites .top-site-inner .title {
+ width: var(--rightPanelIconWidth); }
+
+.ds-hero-item .context-menu-button,
+.ds-list-item .context-menu-button,
+.ds-card .context-menu-button,
+.ds-signup .context-menu-button {
+ background-clip: padding-box;
+ background-color: var(--newtab-contextmenu-button-color);
+ background-image: url("chrome://global/skin/icons/more.svg");
+ background-position: 55%;
+ border: 1px solid var(--newtab-border-primary-color);
+ border-radius: 100%;
+ box-shadow: 0 2px rgba(12, 12, 13, 0.1);
+ cursor: pointer;
+ fill: var(--newtab-icon-primary-color);
+ height: 27px;
+ inset-inline-end: -13.5px;
+ opacity: 0;
+ position: absolute;
+ top: -13.5px;
+ transform: scale(0.25);
+ transition-duration: 150ms;
+ transition-property: transform, opacity;
+ width: 27px; }
+ .ds-hero-item .context-menu-button:is(:active, :focus),
+ .ds-list-item .context-menu-button:is(:active, :focus),
+ .ds-card .context-menu-button:is(:active, :focus),
+ .ds-signup .context-menu-button:is(:active, :focus) {
+ opacity: 1;
+ transform: scale(1); }
+
+.ds-hero-item .context-menu,
+.ds-list-item .context-menu,
+.ds-card .context-menu,
+.ds-signup .context-menu {
+ opacity: 0; }
+
+.ds-hero-item.active .context-menu,
+.ds-list-item.active .context-menu,
+.ds-card.active .context-menu,
+.ds-signup.active .context-menu {
+ opacity: 1; }
+
+.ds-hero-item.last-item .context-menu,
+.ds-list-item.last-item .context-menu,
+.ds-card.last-item .context-menu,
+.ds-signup.last-item .context-menu {
+ margin-inline-end: 5px;
+ margin-inline-start: auto;
+ inset-inline-end: 0;
+ inset-inline-start: auto; }
+
+.ds-hero-item.last-item .context-menu,
+.ds-list-item.last-item .context-menu,
+.ds-card.last-item .context-menu,
+.ds-signup.last-item .context-menu {
+ opacity: 1; }
+
+.ds-hero-item:is(:hover, :focus, .active),
+.ds-list-item:is(:hover, :focus, .active),
+.ds-card:is(:hover, :focus, .active),
+.ds-signup:is(:hover, :focus, .active) {
+ outline: none; }
+ .ds-hero-item:is(:hover, :focus, .active) .context-menu-button,
+ .ds-list-item:is(:hover, :focus, .active) .context-menu-button,
+ .ds-card:is(:hover, :focus, .active) .context-menu-button,
+ .ds-signup:is(:hover, :focus, .active) .context-menu-button {
+ opacity: 1;
+ transform: scale(1);
+ transition-delay: 333ms; }
+ .ds-hero-item:is(:hover, :focus, .active).ds-card-grid-border,
+ .ds-list-item:is(:hover, :focus, .active).ds-card-grid-border,
+ .ds-card:is(:hover, :focus, .active).ds-card-grid-border,
+ .ds-signup:is(:hover, :focus, .active).ds-card-grid-border {
+ box-shadow: 0 0 0 5px var(--newtab-card-active-outline-color);
+ transition: box-shadow 150ms; }
+
+.outer-wrapper:not(.newtab-experience) .ds-card .ds-card-link:hover {
+ box-shadow: 0 0 0 5px #D7D7DB;
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+ [lwt-newtab-brighttext] .outer-wrapper:not(.newtab-experience) .ds-card .ds-card-link:hover {
+ box-shadow: 0 0 0 5px #4A4A4F;
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+
+.outer-wrapper:not(.newtab-experience) .ds-card .ds-card-link:focus {
+ box-shadow: 0 0 0 5px rgba(10, 132, 255, 0.3);
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+ [lwt-newtab-brighttext] .outer-wrapper:not(.newtab-experience) .ds-card .ds-card-link:focus {
+ box-shadow: 0 0 0 5px rgba(69, 161, 255, 0.4);
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+
+.outer-wrapper:not(.newtab-experience) .ds-card .ds-card-link:active {
+ box-shadow: 0 0 0 5px #D7D7DB;
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+ [lwt-newtab-brighttext] .outer-wrapper:not(.newtab-experience) .ds-card .ds-card-link:active {
+ box-shadow: 0 0 0 5px #4A4A4F;
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+
+.ds-card {
+ display: flex;
+ flex-direction: column;
+ position: relative; }
+ .ds-card .playhead {
+ background: #0060DF url("chrome://activity-stream/content/data/content/assets/glyph-playhead.svg") no-repeat 12px center;
+ border-radius: 20px;
+ bottom: -16px;
+ color: rgba(255, 255, 255, 0);
+ display: flex;
+ flex-direction: column;
+ height: 40px;
+ justify-content: center;
+ left: 16px;
+ min-width: 40px;
+ padding: 0 0 0 40px;
+ position: absolute;
+ transition: padding 100ms ease-in-out 0ms, color 100ms linear 100ms; }
+ .ds-card .playhead:hover {
+ color: white;
+ padding: 0 20px 0 40px; }
+ .ds-card .playhead span {
+ display: none; }
+ .ds-card .playhead:hover span {
+ display: inline;
+ font-style: normal;
+ font-weight: 600;
+ font-size: 13px; }
+ .ds-card.placeholder {
+ background: transparent;
+ box-shadow: inset 0 0 0 1px var(--newtab-inner-box-shadow-color);
+ border-radius: 4px;
+ min-height: 300px; }
+ .ds-card .img-wrapper {
+ width: 100%;
+ position: relative; }
+ .ds-card .img {
+ height: 0;
+ padding-top: 50%; }
+ .ds-card .img img {
+ border-radius: 4px;
+ box-shadow: inset 0 0 0 0.5px rgba(0, 0, 0, 0.15); }
+ .ds-card .ds-card-link {
+ height: 100%;
+ display: flex;
+ flex-direction: column; }
+ .ds-card .ds-card-link:hover header {
+ color: #0060DF; }
+ [lwt-newtab-brighttext] .ds-card .ds-card-link:hover header {
+ color: #45A1FF; }
+ .ds-card .ds-card-link:focus header {
+ color: #0060DF; }
+ [lwt-newtab-brighttext] .ds-card .ds-card-link:focus header {
+ color: #45A1FF; }
+ .ds-card .ds-card-link:active header {
+ color: #003EAA; }
+ [lwt-newtab-brighttext] .ds-card .ds-card-link:active header {
+ color: #0A84FF; }
+ .ds-card.video-card .meta {
+ margin-top: 4px; }
+ .ds-card .meta {
+ display: flex;
+ flex-direction: column;
+ padding: 12px 16px;
+ flex-grow: 1; }
+ .ds-card .meta .info-wrap {
+ flex-grow: 1; }
+ .ds-card .meta .title {
+ font-size: 17px;
+ -webkit-line-clamp: 3;
+ line-height: 24px;
+ font-weight: 600; }
+ .ds-card .meta .excerpt {
+ font-size: 14px;
+ -webkit-line-clamp: 3;
+ line-height: 20px; }
+ .ds-card .meta .source {
+ -webkit-line-clamp: 1;
+ margin-bottom: 2px;
+ font-size: 13px;
+ color: #737373; }
+ [lwt-newtab-brighttext] .ds-card .meta .source {
+ color: #B1B1B3; }
+ .ds-card .meta .cta-button {
+ width: 100%;
+ margin: 12px 0 4px;
+ box-shadow: none;
+ border-radius: 4px;
+ height: 32px;
+ font-size: 14px;
+ font-weight: 600;
+ padding: 5px 8px 7px;
+ border: 0;
+ color: #0C0C0D;
+ background: rgba(12, 12, 13, 0.1); }
+ [lwt-newtab-brighttext] .ds-card .meta .cta-button {
+ color: #F9F9FA;
+ background: rgba(12, 12, 13, 0.7); }
+ .ds-card .meta .cta-button:focus {
+ background: rgba(12, 12, 13, 0.1);
+ box-shadow: 0 0 0 2px #FFF, 0 0 0 5px rgba(10, 132, 255, 0.5); }
+ [lwt-newtab-brighttext] .ds-card .meta .cta-button:focus {
+ background: rgba(12, 12, 13, 0.7);
+ box-shadow: 0 0 0 2px #2A2A2E, 0 0 0 5px rgba(10, 132, 255, 0.5); }
+ .ds-card .meta .cta-button:hover {
+ background: rgba(12, 12, 13, 0.2); }
+ [lwt-newtab-brighttext] .ds-card .meta .cta-button:hover {
+ background: rgba(12, 12, 13, 0.5); }
+ .ds-card .meta .cta-button:active {
+ background: rgba(12, 12, 13, 0.3); }
+ [lwt-newtab-brighttext] .ds-card .meta .cta-button:active {
+ background: rgba(12, 12, 13, 0.7); }
+ .ds-card .meta .cta-link {
+ font-size: 15px;
+ font-weight: 600;
+ line-height: 24px;
+ height: 24px;
+ width: auto;
+ background-size: auto;
+ background-position: right 1.5px;
+ padding-right: 9px;
+ color: #0060DF;
+ fill: #0060DF; }
+ [lwt-newtab-brighttext] .ds-card .meta .cta-link {
+ color: #45A1FF;
+ fill: #45A1FF; }
+ .ds-card .meta .cta-link:focus {
+ box-shadow: 0 0 0 1px #FFF, 0 0 0 4px rgba(10, 132, 255, 0.5);
+ border-radius: 4px;
+ outline: 0; }
+ [lwt-newtab-brighttext] .ds-card .meta .cta-link:focus {
+ box-shadow: 0 0 0 1px #2A2A2E, 0 0 0 4px rgba(10, 132, 255, 0.5); }
+ .ds-card .meta .cta-link:active {
+ color: #003EAA;
+ fill: #003EAA;
+ box-shadow: none; }
+ [lwt-newtab-brighttext] .ds-card .meta .cta-link:active {
+ color: #0A84FF;
+ fill: #0A84FF;
+ box-shadow: none; }
+ .ds-card .meta .cta-link:hover {
+ text-decoration: underline; }
+ .ds-card header {
+ line-height: 24px;
+ font-size: 17px;
+ color: #0C0C0D; }
+ [lwt-newtab-brighttext] .ds-card header {
+ color: #F9F9FA; }
+ .ds-card p {
+ font-size: 14px;
+ line-height: 20px;
+ color: #0C0C0D;
+ margin: 0; }
+ [lwt-newtab-brighttext] .ds-card p {
+ color: #F9F9FA; }
+
+.outer-wrapper.newtab-experience .ds-card .context-menu-button:is(:active, :focus) {
+ outline: 0;
+ fill: var(--newtab-primary-action-background);
+ border: 1px solid var(--newtab-primary-action-background); }
+
+.outer-wrapper.newtab-experience .ds-card .ds-card-link:focus {
+ border: 0;
+ outline: 0;
+ box-shadow: 0 0 0 3px var(--newtab-focus-outline), 0 0 0 1px var(--newtab-focus-border);
+ transition: none; }
+ .outer-wrapper.newtab-experience .ds-card .ds-card-link:focus header {
+ color: #0060DF; }
+ [lwt-newtab-brighttext] .outer-wrapper.newtab-experience .ds-card .ds-card-link:focus header {
+ color: #45A1FF; }
+
+.story-footer {
+ color: var(--newtab-text-secondary-color);
+ inset-inline-start: 0;
+ margin-top: 12px;
+ position: relative; }
+ .story-footer .story-sponsored-label,
+ .story-footer .story-view-count,
+ .story-footer .status-message {
+ -webkit-line-clamp: 1;
+ font-size: 13px;
+ line-height: 24px;
+ color: #737373; }
+ [lwt-newtab-brighttext] .story-footer .story-sponsored-label, [lwt-newtab-brighttext]
+ .story-footer .story-view-count, [lwt-newtab-brighttext]
+ .story-footer .status-message {
+ color: #B1B1B3; }
+ .story-footer .status-message {
+ display: flex;
+ align-items: center;
+ height: 24px; }
+ .story-footer .status-message .story-badge-icon {
+ fill: #737373;
+ height: 16px;
+ margin-inline-end: 6px; }
+ [lwt-newtab-brighttext] .story-footer .status-message .story-badge-icon {
+ fill: #B1B1B3; }
+ .story-footer .status-message .story-badge-icon.icon-bookmark-removed {
+ background-image: url("chrome://activity-stream/content/data/content/assets/icon-removed-bookmark.svg"); }
+ .story-footer .status-message .story-context-label {
+ color: #737373;
+ flex-grow: 1;
+ font-size: 13px;
+ line-height: 24px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap; }
+ [lwt-newtab-brighttext] .story-footer .status-message .story-context-label {
+ color: #B1B1B3; }
+
+.story-animate-enter {
+ opacity: 0; }
+
+.story-animate-enter-active {
+ opacity: 1;
+ transition: opacity 150ms ease-in 300ms; }
+ .story-animate-enter-active .story-badge-icon,
+ .story-animate-enter-active .story-context-label {
+ animation: color 3s ease-out 0.3s; }
+ [lwt-newtab-brighttext] .story-animate-enter-active .story-badge-icon, [lwt-newtab-brighttext]
+ .story-animate-enter-active .story-context-label {
+ animation: dark-color 3s ease-out 0.3s; }
+
+@keyframes color {
+ 0% {
+ color: #058B00;
+ fill: #058B00; }
+ 100% {
+ color: #737373;
+ fill: #737373; } }
+
+@keyframes dark-color {
+ 0% {
+ color: #7C6;
+ fill: #7C6; }
+ 100% {
+ color: #B1B1B3;
+ fill: #B1B1B3; } }
+
+.story-animate-exit {
+ position: absolute;
+ top: 0;
+ opacity: 1; }
+
+.story-animate-exit-active {
+ opacity: 0;
+ transition: opacity 250ms ease-in; }
+
+.ds-image {
+ display: block;
+ position: relative;
+ opacity: 0; }
+ .ds-image.use-transition {
+ transition: opacity 0.8s; }
+ .ds-image.loaded {
+ opacity: 1; }
+ .ds-image img,
+ .ds-image .broken-image {
+ background-color: var(--newtab-card-placeholder-color);
+ position: absolute;
+ top: 0;
+ width: 100%;
+ height: 100%;
+ object-fit: cover; }
+
+.ds-dismiss {
+ position: relative;
+ border-radius: 8px;
+ transition-duration: 250ms;
+ transition-property: background; }
+ .ds-dismiss:hover .ds-dismiss-button {
+ opacity: 1; }
+ .ds-dismiss .ds-dismiss-button {
+ border: 0;
+ cursor: pointer;
+ height: 32px;
+ width: 32px;
+ padding: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ position: absolute;
+ inset-inline-end: 0;
+ top: 0;
+ border-radius: 50%;
+ background-color: transparent; }
+ .ds-dismiss .ds-dismiss-button .icon {
+ fill: #737373; }
+ [lwt-newtab-brighttext] .ds-dismiss .ds-dismiss-button .icon {
+ fill: #EDEDF0; }
+ .ds-dismiss .ds-dismiss-button:hover {
+ background: rgba(12, 12, 13, 0.2); }
+ [lwt-newtab-brighttext] .ds-dismiss .ds-dismiss-button:hover {
+ background: rgba(12, 12, 13, 0.5); }
+ [lwt-newtab-brighttext] .ds-dismiss .ds-dismiss-button:hover .icon {
+ fill: #F9F9FA; }
+ .ds-dismiss .ds-dismiss-button:hover .icon {
+ fill: #2A2A2E; }
+ .ds-dismiss .ds-dismiss-button:active {
+ background: rgba(12, 12, 13, 0.3); }
+ [lwt-newtab-brighttext] .ds-dismiss .ds-dismiss-button:active {
+ background: rgba(12, 12, 13, 0.7); }
+ .ds-dismiss .ds-dismiss-button:focus {
+ box-shadow: 0 0 0 2px #FFF, 0 0 0 5px rgba(10, 132, 255, 0.5); }
+ [lwt-newtab-brighttext] .ds-dismiss .ds-dismiss-button:focus {
+ box-shadow: 0 0 0 2px #2A2A2E, 0 0 0 5px rgba(10, 132, 255, 0.5); }
+
+.ds-message {
+ margin: 8px 0 0; }
+ .ds-message .title {
+ display: flex;
+ align-items: center; }
+ .ds-message .title .glyph {
+ width: 16px;
+ height: 16px;
+ margin: 0 6px 0 0;
+ -moz-context-properties: fill;
+ fill: #737373;
+ background-position: center center;
+ background-size: 16px;
+ background-repeat: no-repeat; }
+ [lwt-newtab-brighttext] .ds-message .title .glyph {
+ fill: #D7D7DB; }
+ .ds-message .title .title-text {
+ line-height: 20px;
+ font-size: 13px;
+ color: #737373;
+ font-weight: 600;
+ padding-right: 12px; }
+ [lwt-newtab-brighttext] .ds-message .title .title-text {
+ color: #D7D7DB; }
+ .ds-message .title .link {
+ line-height: 20px;
+ font-size: 13px; }
+ .ds-message .title .link:hover, .ds-message .title .link:focus {
+ text-decoration: underline; }
+
+.impression-observer {
+ position: absolute;
+ top: 0;
+ width: 100%;
+ height: 100%;
+ pointer-events: none; }
+
+.section-empty-state {
+ border: 1px solid var(--newtab-border-secondary-color);
+ border-radius: 4px;
+ display: flex;
+ height: 160px;
+ width: 100%; }
+ .section-empty-state .empty-state-message {
+ color: var(--newtab-text-secondary-color);
+ font-size: 14px;
+ line-height: 20px;
+ text-align: center;
+ margin: auto;
+ max-width: 936px; }
+ .section-empty-state .try-again-button {
+ margin-top: 12px;
+ padding: 6px 32px;
+ border-radius: 2px;
+ border: 0;
+ background: var(--newtab-feed-button-background);
+ color: var(--newtab-feed-button-text);
+ cursor: pointer;
+ position: relative;
+ transition: background 0.2s ease, color 0.2s ease; }
+ .section-empty-state .try-again-button:not(.waiting):focus {
+ box-shadow: 0 0 0 5px rgba(10, 132, 255, 0.3);
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+ [lwt-newtab-brighttext] .section-empty-state .try-again-button:not(.waiting):focus {
+ box-shadow: 0 0 0 5px rgba(69, 161, 255, 0.4);
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+ .section-empty-state .try-again-button:not(.waiting):hover {
+ box-shadow: 0 0 0 5px #D7D7DB;
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+ [lwt-newtab-brighttext] .section-empty-state .try-again-button:not(.waiting):hover {
+ box-shadow: 0 0 0 5px #4A4A4F;
+ transition: box-shadow 150ms;
+ border-radius: 4px;
+ outline: none; }
+ .section-empty-state .try-again-button::after {
+ content: '';
+ height: 20px;
+ width: 20px;
+ animation: spinner 1s linear infinite;
+ opacity: 0;
+ position: absolute;
+ top: 50%;
+ left: 50%;
+ margin: -10px 0 0 -10px;
+ mask-image: url("chrome://activity-stream/content/data/content/assets/spinner.svg");
+ mask-size: 20px;
+ background: var(--newtab-feed-button-spinner); }
+ .section-empty-state .try-again-button.waiting {
+ cursor: initial;
+ background: var(--newtab-feed-button-background-faded);
+ color: var(--newtab-feed-button-text-faded);
+ transition: background 0.2s ease; }
+ .section-empty-state .try-again-button.waiting::after {
+ transition: opacity 0.2s ease;
+ opacity: 1; }
+ .section-empty-state h2 {
+ font-size: 15px;
+ font-weight: 600;
+ margin: 0; }
+ .section-empty-state p {
+ margin: 0; }
+
+@keyframes spinner {
+ to {
+ transform: rotate(360deg); } }
+
+.ds-dismiss-ds-text-promo {
+ max-width: 744px;
+ margin: auto;
+ overflow: hidden; }
+ .ds-dismiss-ds-text-promo.hovering {
+ background: rgba(12, 12, 13, 0.1); }
+ [lwt-newtab-brighttext] .ds-dismiss-ds-text-promo.hovering {
+ background: rgba(12, 12, 13, 0.3); }
+ .ds-dismiss-ds-text-promo .ds-dismiss-button {
+ margin-inline: 0 18px;
+ margin-block: 18px 0; }
+
+.ds-text-promo {
+ max-width: 640px;
+ margin: 0;
+ padding: 18px; }
+ @media (min-width: 610px) {
+ .ds-text-promo {
+ display: flex;
+ margin: 18px 24px;
+ padding: 0 32px 0 0; } }
+ .ds-text-promo .ds-image {
+ width: 40px;
+ height: 40px;
+ flex-shrink: 0;
+ margin: 0 0 18px; }
+ @media (min-width: 610px) {
+ .ds-text-promo .ds-image {
+ margin: 4px 12px 0 0; } }
+ .ds-text-promo .ds-image img {
+ border-radius: 4px; }
+ .ds-text-promo .text {
+ line-height: 24px; }
+ .ds-text-promo h3 {
+ margin: 0;
+ font-weight: 600;
+ font-size: 15px; }
+ [lwt-newtab-brighttext] .ds-text-promo h3 {
+ color: #F9F9FA; }
+ .ds-text-promo .subtitle {
+ font-size: 13px;
+ margin: 0;
+ color: #737373; }
+ [lwt-newtab-brighttext] .ds-text-promo .subtitle {
+ color: #B1B1B3; }
+
+.ds-chevron-link {
+ color: #0060DF;
+ display: inline-block;
+ outline: 0; }
+ .ds-chevron-link:hover {
+ text-decoration: underline; }
+ .ds-chevron-link:active {
+ color: #003EAA; }
+ [lwt-newtab-brighttext] .ds-chevron-link:active {
+ color: #0A84FF; }
+ .ds-chevron-link:active::after {
+ background-color: #003EAA; }
+ [lwt-newtab-brighttext] .ds-chevron-link:active::after {
+ background-color: #0A84FF; }
+ .ds-chevron-link:focus {
+ box-shadow: 0 0 0 2px #FFF, 0 0 0 5px rgba(10, 132, 255, 0.5);
+ border-radius: 2px; }
+ [lwt-newtab-brighttext] .ds-chevron-link:focus {
+ box-shadow: 0 0 0 2px #2A2A2E, 0 0 0 5px rgba(10, 132, 255, 0.5); }
+ .ds-chevron-link::after {
+ content: ' ';
+ mask: url("chrome://activity-stream/content/data/content/assets/glyph-caret-right.svg") 0 -8px no-repeat;
+ background-color: #0060DF;
+ margin: 0 0 0 4px;
+ width: 5px;
+ height: 8px;
+ text-decoration: none;
+ display: inline-block; }
+ [lwt-newtab-brighttext] .ds-chevron-link::after {
+ background-color: #45A1FF; }
+
+.ds-signup {
+ max-width: 300px;
+ margin: 0 auto;
+ padding: 8px;
+ position: relative;
+ text-align: center;
+ font-size: 17px;
+ font-weight: 600; }
+ .ds-signup:hover {
+ background: var(--newtab-element-hover-color);
+ border-radius: 4px; }
+ .ds-signup .icon-mail {
+ height: 40px;
+ width: 40px;
+ margin-inline-end: 8px;
+ fill: #B1B1B3;
+ background-size: 30px;
+ flex-shrink: 0; }
+ .ds-signup .ds-signup-content {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ flex-direction: column; }
+ .ds-signup .ds-signup-content .ds-chevron-link {
+ margin-top: 4px;
+ box-shadow: none;
+ display: block;
+ white-space: nowrap; }
+ @media (min-width: 866px) {
+ .ds-signup {
+ min-width: 756px;
+ width: max-content;
+ text-align: start; }
+ .ds-signup .ds-signup-content {
+ flex-direction: row; }
+ .ds-signup .ds-signup-content .ds-chevron-link {
+ margin-top: 0;
+ display: inline; } }
+
+.ds-privacy-modal .modal-link {
+ display: flex;
+ align-items: center;
+ margin: 0 0 8px;
+ border: 0;
+ padding: 0;
+ color: #0060DF;
+ width: max-content; }
+ .ds-privacy-modal .modal-link:hover {
+ text-decoration: underline;
+ cursor: pointer; }
+ .ds-privacy-modal .modal-link::before {
+ -moz-context-properties: fill;
+ fill: #0060DF;
+ content: '';
+ display: inline-block;
+ width: 16px;
+ height: 16px;
+ margin: 0;
+ margin-inline-end: 8px;
+ background-position: center center;
+ background-repeat: no-repeat;
+ background-size: 16px; }
+ .ds-privacy-modal .modal-link.modal-link-privacy::before {
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-info-16.svg"); }
+ .ds-privacy-modal .modal-link.modal-link-manage::before {
+ background-image: url("chrome://global/skin/icons/settings.svg"); }
+
+.ds-privacy-modal p {
+ line-height: 24px; }
+
+.ds-privacy-modal .privacy-notice {
+ max-width: 572px;
+ padding: 40px;
+ margin: auto; }
+
+.ASRouterButton {
+ font-weight: 600;
+ font-size: 14px;
+ white-space: nowrap;
+ border-radius: 2px;
+ border: 0;
+ font-family: inherit;
+ padding: 8px 15px;
+ margin-inline-start: 12px;
+ color: inherit;
+ cursor: pointer; }
+ .tall .ASRouterButton {
+ margin-inline-start: 20px; }
+ .ASRouterButton.test-only {
+ width: 0;
+ height: 0;
+ overflow: hidden;
+ display: block;
+ visibility: hidden; }
+ .ASRouterButton.primary {
+ border: 1px solid var(--newtab-button-primary-color);
+ background-color: var(--newtab-button-primary-color);
+ color: #F9F9FA; }
+ .ASRouterButton.primary:hover {
+ background-color: #003EAA; }
+ .ASRouterButton.primary:active {
+ background-color: #002275; }
+ .ASRouterButton.secondary {
+ background-color: rgba(12, 12, 13, 0.1); }
+ .ASRouterButton.secondary:hover {
+ background-color: rgba(12, 12, 13, 0.2); }
+ .ASRouterButton.secondary:active {
+ background-color: rgba(12, 12, 13, 0.3); }
+ .ASRouterButton.secondary:focus {
+ box-shadow: 0 0 0 1px #0A84FF inset, 0 0 0 1px #0A84FF, 0 0 0 4px rgba(10, 132, 255, 0.3); }
+ .ASRouterButton.slim {
+ background-color: rgba(12, 12, 13, 0.1);
+ margin-inline-start: 0;
+ font-size: 12px;
+ padding: 6px 12px; }
+ .ASRouterButton.slim:hover {
+ background-color: rgba(12, 12, 13, 0.2); }
+
+[lwt-newtab-brighttext] .secondary {
+ background-color: rgba(249, 249, 250, 0.1); }
+ [lwt-newtab-brighttext] .secondary:hover {
+ background-color: rgba(249, 249, 250, 0.2); }
+ [lwt-newtab-brighttext] .secondary:active {
+ background-color: rgba(249, 249, 250, 0.3); }
+
+[lwt-newtab-brighttext] .footer .secondary {
+ background-color: rgba(249, 249, 250, 0.3); }
+ [lwt-newtab-brighttext] .footer .secondary:hover {
+ background-color: rgba(249, 249, 250, 0.4); }
+ [lwt-newtab-brighttext] .footer .secondary:active {
+ background-color: rgba(249, 249, 250, 0.5); }
+
+.SnippetBaseContainer {
+ position: fixed;
+ z-index: 2;
+ bottom: 0;
+ left: 0;
+ right: 0;
+ background-color: var(--newtab-snippets-background-color);
+ color: var(--newtab-text-primary-color);
+ font-size: 14px;
+ line-height: 20px;
+ border-top: 1px solid var(--newtab-snippets-hairline-color);
+ box-shadow: 0 1px 4px 0 rgba(12, 12, 13, 0.2);
+ display: flex;
+ align-items: center; }
+ .SnippetBaseContainer a {
+ cursor: pointer;
+ color: var(--newtab-link-primary-color); }
+ .SnippetBaseContainer a:hover {
+ text-decoration: underline; }
+ [lwt-newtab-brighttext] .SnippetBaseContainer a {
+ font-weight: bold; }
+ .SnippetBaseContainer input[type='checkbox'] {
+ margin-inline-start: 0; }
+ .SnippetBaseContainer .innerWrapper {
+ margin: 0 auto;
+ display: flex;
+ align-items: center;
+ padding: 12px 25px;
+ padding-inline-end: 36px;
+ max-width: 836px; }
+ @media (min-width: 866px) {
+ .SnippetBaseContainer .innerWrapper {
+ padding-inline-end: 25px; } }
+ @media (min-width: 1122px) {
+ .SnippetBaseContainer .innerWrapper {
+ max-width: 1092px; } }
+ .SnippetBaseContainer .blockButton {
+ display: none;
+ background: none;
+ border: 0;
+ position: absolute;
+ top: 50%;
+ inset-inline-end: 12px;
+ height: 16px;
+ width: 16px;
+ background-image: url("chrome://activity-stream/content/data/content/assets/glyph-dismiss-16.svg");
+ -moz-context-properties: fill;
+ color: inherit;
+ fill: currentColor;
+ opacity: 0.5;
+ margin-top: -8px;
+ padding: 0;
+ cursor: pointer; }
+ .SnippetBaseContainer:hover .blockButton {
+ display: block; }
+ .SnippetBaseContainer .icon {
+ height: 42px;
+ width: 42px;
+ margin-inline-end: 12px;
+ flex-shrink: 0; }
+
+.snippets-preview-banner {
+ font-size: 15px;
+ line-height: 42px;
+ color: rgba(74, 74, 79, 0.7);
+ background: rgba(215, 215, 219, 0.6);
+ text-align: center;
+ position: absolute;
+ top: 0;
+ width: 100%; }
+ .snippets-preview-banner span {
+ vertical-align: middle; }
+
+body:not([lwt-newtab-brighttext]) .icon-dark-theme,
+body:not([lwt-newtab-brighttext]) .icon.icon-dark-theme,
+body:not([lwt-newtab-brighttext]) .scene2Icon .icon-dark-theme {
+ display: none; }
+
+body[lwt-newtab-brighttext] .icon-light-theme,
+body[lwt-newtab-brighttext] .icon.icon-light-theme,
+body[lwt-newtab-brighttext] .scene2Icon .icon-light-theme {
+ display: none; }
+
+.activity-stream.modal-open {
+ overflow: hidden; }
+
+.modalOverlayOuter {
+ background: var(--newtab-overlay-color);
+ height: 100%;
+ position: fixed;
+ top: 0;
+ left: 0;
+ width: 100%;
+ display: none;
+ z-index: 1100;
+ overflow: auto; }
+ .modalOverlayOuter.active {
+ display: flex; }
+
+.modalOverlayInner {
+ min-width: min-content;
+ width: 100%;
+ max-width: 960px;
+ position: relative;
+ margin: auto;
+ background: var(--newtab-modal-color);
+ box-shadow: 0 1px 15px 0 rgba(0, 0, 0, 0.3);
+ border-radius: 4px;
+ display: none;
+ z-index: 1100; }
+ @media (max-width: 960px) {
+ .modalOverlayInner {
+ height: 100%;
+ top: 0;
+ left: 0;
+ box-shadow: none;
+ border-radius: 0; } }
+ .modalOverlayInner.active {
+ display: block; }
+ .modalOverlayInner h2 {
+ color: #4A4A4F;
+ text-align: center;
+ font-weight: 200;
+ margin-top: 30px;
+ font-size: 28px;
+ line-height: 37px;
+ letter-spacing: -0.13px; }
+ @media (max-width: 960px) {
+ .modalOverlayInner h2 {
+ margin-top: 100px; } }
+ @media (max-width: 850px) {
+ .modalOverlayInner h2 {
+ margin-top: 30px; } }
+ .modalOverlayInner .footer {
+ border-top: 1px solid #D7D7DB;
+ border-radius: 4px;
+ height: 70px;
+ width: 100%;
+ position: absolute;
+ bottom: 0;
+ text-align: center;
+ background-color: #FFF; }
+ @media (max-width: 850px) and (max-height: 730px) {
+ .modalOverlayInner .footer {
+ position: sticky; } }
+ @media (max-width: 650px) and (max-height: 600px) {
+ .modalOverlayInner .footer {
+ position: sticky; } }
+ .modalOverlayInner .footer .modalButton {
+ margin-top: 20px;
+ min-width: 150px;
+ height: 30px;
+ padding: 4px 30px 6px;
+ font-size: 15px; }
+ .modalOverlayInner .footer .modalButton:focus, .modalOverlayInner .footer .modalButton.active, .modalOverlayInner .footer .modalButton:hover {
+ box-shadow: 0 0 0 5px #D7D7DB;
+ transition: box-shadow 150ms; }
+
+.below-search-snippet {
+ margin: 0 auto 16px; }
+ .below-search-snippet.withButton {
+ margin: auto;
+ min-height: 60px;
+ background-color: transparent; }
+ .below-search-snippet.withButton .snippet-hover-wrapper {
+ min-height: 60px;
+ border-radius: 4px; }
+ .below-search-snippet.withButton .snippet-hover-wrapper:hover {
+ background-color: var(--newtab-element-hover-color); }
+ .below-search-snippet.withButton .snippet-hover-wrapper:hover .blockButton {
+ display: block;
+ opacity: 1; }
+
+.SimpleBelowSearchSnippet {
+ background-color: transparent;
+ border: 0;
+ box-shadow: none;
+ position: relative;
+ margin: auto;
+ z-index: auto; }
+ @media (min-width: 866px) {
+ .SimpleBelowSearchSnippet {
+ width: 736px; } }
+ .SimpleBelowSearchSnippet.active {
+ background-color: var(--newtab-element-hover-color);
+ border-radius: 4px; }
+ .SimpleBelowSearchSnippet .innerWrapper {
+ align-items: center;
+ background-color: transparent;
+ border-radius: 4px;
+ box-shadow: var(--newtab-card-shadow);
+ flex-direction: column;
+ padding: 16px;
+ text-align: center;
+ width: 100%; }
+ @media (min-width: 610px) {
+ .SimpleBelowSearchSnippet .innerWrapper {
+ align-items: flex-start;
+ background-color: transparent;
+ border-radius: 4px;
+ box-shadow: none;
+ flex-direction: row;
+ padding: 0;
+ text-align: inherit;
+ width: 696px; } }
+ @media (max-width: 865px) {
+ .SimpleBelowSearchSnippet .innerWrapper {
+ margin-inline-start: 0; } }
+ @media (max-width: 609px) {
+ .SimpleBelowSearchSnippet .innerWrapper {
+ margin: auto; } }
+ .SimpleBelowSearchSnippet .blockButton {
+ display: block;
+ inset-inline-end: 10px;
+ opacity: 1;
+ top: 50%; }
+ .SimpleBelowSearchSnippet .blockButton:focus {
+ box-shadow: 0 0 0 1px #0A84FF inset, 0 0 0 1px #0A84FF, 0 0 0 4px rgba(10, 132, 255, 0.3);
+ border-radius: 2px; }
+ .SimpleBelowSearchSnippet .title {
+ font-size: inherit;
+ margin: 0; }
+ .SimpleBelowSearchSnippet .title-inline {
+ display: inline; }
+ .SimpleBelowSearchSnippet .textContainer {
+ margin: 10px;
+ margin-inline-start: 0;
+ padding-inline-end: 20px; }
+ .SimpleBelowSearchSnippet .icon {
+ margin-top: 8px;
+ margin-inline-start: 12px;
+ height: 32px;
+ width: 32px; }
+ @media (min-width: 610px) {
+ .SimpleBelowSearchSnippet .icon {
+ height: 24px;
+ width: 24px; } }
+ @media (max-width: 610px) {
+ .SimpleBelowSearchSnippet .icon {
+ margin: auto; } }
+ .SimpleBelowSearchSnippet.withButton {
+ line-height: 20px;
+ margin-bottom: 10px;
+ min-height: 60px;
+ background-color: transparent; }
+ @media (max-width: 1123px) {
+ .SimpleBelowSearchSnippet.withButton .innerWrapper {
+ margin: 0 40px; } }
+ .SimpleBelowSearchSnippet.withButton .blockButton {
+ display: block;
+ inset-inline-end: -10%;
+ opacity: 0;
+ margin: auto;
+ top: unset; }
+ .SimpleBelowSearchSnippet.withButton .blockButton:focus {
+ opacity: 1;
+ box-shadow: none; }
+ @media (max-width: 1123px) {
+ .SimpleBelowSearchSnippet.withButton .blockButton {
+ inset-inline-end: 2%; } }
+ .SimpleBelowSearchSnippet.withButton .icon {
+ width: 42px;
+ height: 42px;
+ flex-shrink: 0;
+ margin: auto 0;
+ margin-inline-end: 10px; }
+ @media (max-width: 610px) {
+ .SimpleBelowSearchSnippet.withButton .icon {
+ margin: auto; } }
+ .SimpleBelowSearchSnippet.withButton .buttonContainer {
+ margin: auto;
+ margin-inline-end: 0; }
+ @media (max-width: 610px) {
+ .SimpleBelowSearchSnippet.withButton .buttonContainer {
+ margin: auto; } }
+ @media (max-width: 610px) {
+ .SimpleBelowSearchSnippet button {
+ margin: auto; } }
+ .SimpleBelowSearchSnippet .body {
+ display: inline;
+ position: sticky;
+ transform: translateY(-50%);
+ margin: 8px 0 0; }
+ @media (min-width: 610px) {
+ .SimpleBelowSearchSnippet .body {
+ margin: 12px 0; } }
+ .SimpleBelowSearchSnippet .body a {
+ font-weight: 600; }
+
+.SimpleSnippet.tall {
+ padding: 27px 0; }
+
+.SimpleSnippet p em {
+ color: #0C0C0D;
+ font-style: normal;
+ background: #FFE900; }
+
+.SimpleSnippet.bold .donation-form-url,
+.SimpleSnippet.bold .donation-amount, .SimpleSnippet.takeover .donation-form-url,
+.SimpleSnippet.takeover .donation-amount {
+ padding-top: 8px;
+ padding-bottom: 8px; }
+
+.SimpleSnippet.bold {
+ height: 176px; }
+ .SimpleSnippet.bold .body {
+ font-size: 14px;
+ line-height: 20px;
+ margin-bottom: 20px; }
+ .SimpleSnippet.bold .icon {
+ width: 71px;
+ height: 71px; }
+
+.SimpleSnippet.takeover {
+ height: 344px; }
+ .SimpleSnippet.takeover .body {
+ font-size: 16px;
+ line-height: 24px;
+ margin-bottom: 35px; }
+ .SimpleSnippet.takeover .icon {
+ width: 79px;
+ height: 79px; }
+
+.SimpleSnippet .title {
+ font-size: inherit;
+ margin: 0; }
+
+.SimpleSnippet .title-inline {
+ display: inline; }
+
+.SimpleSnippet .titleIcon {
+ background-repeat: no-repeat;
+ background-size: 14px;
+ background-position: center;
+ height: 16px;
+ width: 16px;
+ margin-top: 2px;
+ margin-inline-end: 2px;
+ display: inline-block;
+ vertical-align: top; }
+
+.SimpleSnippet .body {
+ display: inline;
+ margin: 0; }
+
+.SimpleSnippet.tall .icon {
+ margin-inline-end: 20px; }
+
+.SimpleSnippet.takeover .icon, .SimpleSnippet.bold .icon {
+ margin-inline-end: 20px; }
+
+.SimpleSnippet .icon {
+ align-self: flex-start; }
+
+.SimpleSnippet.has-section-header .innerWrapper {
+ flex-wrap: wrap;
+ padding-top: 7px; }
+
+.SimpleSnippet .innerContentWrapper {
+ align-items: center;
+ display: flex; }
+
+.SimpleSnippet .section-header {
+ flex: 0 0 100%;
+ margin-bottom: 10px; }
+
+.SimpleSnippet .section-title {
+ color: var(--newtab-section-header-text-color);
+ display: inline-block;
+ font-size: 13px;
+ font-weight: bold;
+ margin: 0; }
+ .SimpleSnippet .section-title a {
+ color: var(--newtab-section-header-text-color);
+ font-weight: inherit;
+ text-decoration: none; }
+ .SimpleSnippet .section-title .icon {
+ height: 16px;
+ margin-inline-end: 6px;
+ margin-top: -2px;
+ width: 16px; }
+
+.SubmitFormSnippet {
+ flex-direction: column;
+ flex: 1 1 100%;
+ width: 100%; }
+ .SubmitFormSnippet .disclaimerText {
+ margin: 5px 0 0;
+ font-size: 12px;
+ color: var(--newtab-text-secondary-color); }
+ .SubmitFormSnippet p {
+ margin: 0; }
+ .SubmitFormSnippet.send_to_device_snippet {
+ text-align: center; }
+ .SubmitFormSnippet.send_to_device_snippet .message {
+ font-size: 16px;
+ margin-bottom: 20px; }
+ .SubmitFormSnippet.send_to_device_snippet .scene2Title {
+ font-size: 24px;
+ display: block; }
+ .SubmitFormSnippet .ASRouterButton.primary {
+ flex: 1 1 0; }
+ .SubmitFormSnippet .scene2Icon {
+ width: 100%;
+ margin-bottom: 20px; }
+ .SubmitFormSnippet .scene2Icon img {
+ width: 98px;
+ display: inline-block; }
+ .SubmitFormSnippet .scene2Title {
+ font-size: inherit;
+ margin: 0 0 10px;
+ font-weight: bold;
+ display: inline; }
+ .SubmitFormSnippet form {
+ display: flex;
+ flex-direction: column;
+ width: 100%; }
+ .SubmitFormSnippet .message {
+ font-size: 14px;
+ align-self: stretch;
+ flex: 0 0 100%;
+ margin-bottom: 10px; }
+ .SubmitFormSnippet .privacyNotice {
+ font-size: 12px;
+ color: var(--newtab-text-secondary-color);
+ margin-top: 10px;
+ display: flex;
+ flex: 0 0 100%; }
+ .SubmitFormSnippet .innerWrapper {
+ max-width: 736px;
+ flex-wrap: wrap;
+ justify-items: center;
+ padding-top: 40px;
+ padding-bottom: 40px; }
+ .SubmitFormSnippet .footer {
+ width: 100%;
+ margin: 0 auto;
+ text-align: right;
+ background-color: var(--newtab-background-color);
+ padding: 10px 0; }
+ .SubmitFormSnippet .footer .footer-content {
+ margin: 0 auto;
+ max-width: 768px;
+ width: 100%;
+ text-align: right; }
+ [dir='rtl'] .SubmitFormSnippet .footer .footer-content {
+ text-align: left; }
+ .SubmitFormSnippet input.mainInput {
+ border-radius: 2px;
+ background-color: var(--newtab-textbox-background-color);
+ border: 1px solid var(--newtab-textbox-border);
+ padding: 0 8px;
+ height: 100%;
+ font-size: 14px;
+ width: 50%; }
+ .SubmitFormSnippet input.mainInput.clean:invalid, .SubmitFormSnippet input.mainInput.clean:required {
+ box-shadow: none; }
+ .SubmitFormSnippet input.mainInput:focus {
+ border: 1px solid var(--newtab-textbox-focus-color);
+ box-shadow: var(--newtab-textbox-focus-boxshadow); }
+ .SubmitFormSnippet.scene2Alt {
+ text-align: start; }
+ .SubmitFormSnippet.scene2Alt .scene2Icon {
+ flex: 1;
+ margin-bottom: 0; }
+ .SubmitFormSnippet.scene2Alt .message {
+ flex: 5;
+ margin-bottom: 0; }
+ .SubmitFormSnippet.scene2Alt .message p {
+ margin-bottom: 10px; }
+ .SubmitFormSnippet.scene2Alt .section-header {
+ width: 100%; }
+ .SubmitFormSnippet.scene2Alt .section-header .icon {
+ width: 16px;
+ height: 16px; }
+ .SubmitFormSnippet.scene2Alt .section-title {
+ font-size: 13px; }
+ .SubmitFormSnippet.scene2Alt .section-title a {
+ color: var(--newtab-section-header-text-color);
+ font-weight: inherit;
+ text-decoration: none; }
+ .SubmitFormSnippet.scene2Alt .innerWrapper {
+ padding: 0 0 16px; }
+
+.submissionStatus {
+ text-align: center;
+ font-size: 14px;
+ padding: 20px 0; }
+ .submissionStatus .submitStatusTitle {
+ font-size: 20px; }
+
+.EOYSnippetForm {
+ margin: 10px 0 8px;
+ align-self: start;
+ font-size: 14px;
+ display: flex;
+ align-items: center; }
+ .EOYSnippetForm .donation-amount,
+ .EOYSnippetForm .donation-form-url {
+ white-space: nowrap;
+ font-size: 14px;
+ padding: 8px 20px;
+ border-radius: 2px; }
+ .EOYSnippetForm .donation-amount {
+ color: #0C0C0D;
+ margin-inline-end: 18px;
+ border: 1px solid #B1B1B3;
+ padding: 5px 14px;
+ background: #F9F9FA;
+ cursor: pointer; }
+ .EOYSnippetForm input[type='radio'] {
+ opacity: 0;
+ margin-inline-end: -18px; }
+ .EOYSnippetForm input[type='radio']:checked + .donation-amount {
+ background: #737373;
+ color: #FFF;
+ border: 1px solid #4A4A4F; }
+ .EOYSnippetForm input[type='radio']:checked:focus + .donation-amount,
+ .EOYSnippetForm input[type='radio']:not(:checked):focus + .donation-amount {
+ border: 1px dotted var(--newtab-link-primary-color); }
+ .EOYSnippetForm .monthly-checkbox-container {
+ display: flex;
+ width: 100%; }
+ .EOYSnippetForm .donation-form-url {
+ margin-inline-start: 18px;
+ align-self: flex-end;
+ display: flex; }
diff --git a/browser/components/newtab/data/content/abouthomecache/page.html.template b/browser/components/newtab/data/content/abouthomecache/page.html.template
new file mode 100644
index 0000000000..9e70e9e65e
--- /dev/null
+++ b/browser/components/newtab/data/content/abouthomecache/page.html.template
@@ -0,0 +1,43 @@
+#if 0
+#
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+#
+# This template file is used to construct the cached about:home document.
+# The following template strings are used:
+#
+# {{ CACHE_TIME }}:
+# A date string representing when the cache was generated.
+#
+# {{ MARKUP }}:
+# The generated DOM content from ReactDOMServer for the cache.
+#
+# Also note the final script load of about:home?jscache. This loads the cached
+# script, which does the important work of telling React how to connect the
+# cached page state to the pre-existing DOM that's being rendered.
+#
+#endif
+<!doctype html>
+<html>
+ <head>
+ <meta charset="utf-8">
+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; object-src 'none'; script-src resource: chrome:; connect-src https:; img-src https: data: blob:; style-src 'unsafe-inline';">
+ <title data-l10n-id="newtab-page-title"></title>
+ <link rel="icon" type="image/png" href="chrome://branding/content/icon32.png"/>
+ <link rel="localization" href="branding/brand.ftl" />
+ <link rel="localization" href="browser/branding/brandings.ftl" />
+ <link rel="localization" href="browser/newtab/newtab.ftl" />
+ <link rel="stylesheet" href="chrome://browser/content/contentSearchUI.css" />
+ <link rel="stylesheet" href="chrome://activity-stream/content/css/activity-stream.css" />
+ </head>
+ <!-- Cached: {{ CACHE_TIME }} -->
+ <body class="activity-stream">
+ <div id="header-asrouter-container" role="presentation"></div>
+ <div id="root">
+ {{ MARKUP }}
+ </div>
+ <div id="footer-asrouter-container" role="presentation"></div>
+ <script src="about:home?jscache"></script>
+ </body>
+</html>
diff --git a/browser/components/newtab/data/content/abouthomecache/script.js.template b/browser/components/newtab/data/content/abouthomecache/script.js.template
new file mode 100644
index 0000000000..5ba70ea7f5
--- /dev/null
+++ b/browser/components/newtab/data/content/abouthomecache/script.js.template
@@ -0,0 +1,19 @@
+#if 0
+#
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+#
+# This template file is used to construct the script that is loaded by the
+# cached about:home document. It is loaded in the cached about:home document
+# by loading about:home?jscache.
+#
+# The only template string used in this file is {{ STATE }}, which can only
+# be used once. {{ STATE }} will be replaced with the state of about:home
+# at the time that the cache was generated, which is needed by React in order
+# to make the cached document interactive.
+#
+#endif
+window.__FROM_STARTUP_CACHE__ = true;
+window.__STARTUP_STATE__ = {{ STATE }};
+
diff --git a/browser/components/newtab/data/content/activity-stream.bundle.js b/browser/components/newtab/data/content/activity-stream.bundle.js
new file mode 100644
index 0000000000..0c9df8f5a0
--- /dev/null
+++ b/browser/components/newtab/data/content/activity-stream.bundle.js
@@ -0,0 +1,15952 @@
+/*! THIS FILE IS AUTO-GENERATED: webpack.system-addon.config.js */
+var NewtabRenderUtils =
+/******/ (function(modules) { // webpackBootstrap
+/******/ // The module cache
+/******/ var installedModules = {};
+/******/
+/******/ // The require function
+/******/ function __webpack_require__(moduleId) {
+/******/
+/******/ // Check if module is in cache
+/******/ if(installedModules[moduleId]) {
+/******/ return installedModules[moduleId].exports;
+/******/ }
+/******/ // Create a new module (and put it into the cache)
+/******/ var module = installedModules[moduleId] = {
+/******/ i: moduleId,
+/******/ l: false,
+/******/ exports: {}
+/******/ };
+/******/
+/******/ // Execute the module function
+/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
+/******/
+/******/ // Flag the module as loaded
+/******/ module.l = true;
+/******/
+/******/ // Return the exports of the module
+/******/ return module.exports;
+/******/ }
+/******/
+/******/
+/******/ // expose the modules object (__webpack_modules__)
+/******/ __webpack_require__.m = modules;
+/******/
+/******/ // expose the module cache
+/******/ __webpack_require__.c = installedModules;
+/******/
+/******/ // define getter function for harmony exports
+/******/ __webpack_require__.d = function(exports, name, getter) {
+/******/ if(!__webpack_require__.o(exports, name)) {
+/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
+/******/ }
+/******/ };
+/******/
+/******/ // define __esModule on exports
+/******/ __webpack_require__.r = function(exports) {
+/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
+/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
+/******/ }
+/******/ Object.defineProperty(exports, '__esModule', { value: true });
+/******/ };
+/******/
+/******/ // create a fake namespace object
+/******/ // mode & 1: value is a module id, require it
+/******/ // mode & 2: merge all properties of value into the ns
+/******/ // mode & 4: return value when already ns object
+/******/ // mode & 8|1: behave like require
+/******/ __webpack_require__.t = function(value, mode) {
+/******/ if(mode & 1) value = __webpack_require__(value);
+/******/ if(mode & 8) return value;
+/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
+/******/ var ns = Object.create(null);
+/******/ __webpack_require__.r(ns);
+/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
+/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
+/******/ return ns;
+/******/ };
+/******/
+/******/ // getDefaultExport function for compatibility with non-harmony modules
+/******/ __webpack_require__.n = function(module) {
+/******/ var getter = module && module.__esModule ?
+/******/ function getDefault() { return module['default']; } :
+/******/ function getModuleExports() { return module; };
+/******/ __webpack_require__.d(getter, 'a', getter);
+/******/ return getter;
+/******/ };
+/******/
+/******/ // Object.prototype.hasOwnProperty.call
+/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
+/******/
+/******/ // __webpack_public_path__
+/******/ __webpack_require__.p = "";
+/******/
+/******/
+/******/ // Load entry module and return exports
+/******/ return __webpack_require__(__webpack_require__.s = 0);
+/******/ })
+/************************************************************************/
+/******/ ([
+/* 0 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NewTab", function() { return NewTab; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "renderWithoutState", function() { return renderWithoutState; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "renderCache", function() { return renderCache; });
+/* harmony import */ var common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
+/* harmony import */ var content_src_components_Base_Base__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2);
+/* harmony import */ var content_src_lib_detect_user_session_start__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(65);
+/* harmony import */ var content_src_lib_init_store__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(66);
+/* harmony import */ var react_redux__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(7);
+/* harmony import */ var react_redux__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(react_redux__WEBPACK_IMPORTED_MODULE_4__);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_5__);
+/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(14);
+/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(react_dom__WEBPACK_IMPORTED_MODULE_6__);
+/* harmony import */ var common_Reducers_jsm__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(72);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+
+
+
+
+
+
+const NewTab = ({
+ store
+}) => react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement(react_redux__WEBPACK_IMPORTED_MODULE_4__["Provider"], {
+ store: store
+}, react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement(content_src_components_Base_Base__WEBPACK_IMPORTED_MODULE_1__["Base"], null));
+function renderWithoutState() {
+ const store = Object(content_src_lib_init_store__WEBPACK_IMPORTED_MODULE_3__["initStore"])(common_Reducers_jsm__WEBPACK_IMPORTED_MODULE_7__["reducers"]);
+ new content_src_lib_detect_user_session_start__WEBPACK_IMPORTED_MODULE_2__["DetectUserSessionStart"](store).sendEventOrAddListener(); // If this document has already gone into the background by the time we've reached
+ // here, we can deprioritize requesting the initial state until the event loop
+ // frees up. If, however, the visibility changes, we then send the request.
+
+ let didRequest = false;
+ let requestIdleCallbackId = 0;
+
+ function doRequest() {
+ if (!didRequest) {
+ if (requestIdleCallbackId) {
+ cancelIdleCallback(requestIdleCallbackId);
+ }
+
+ didRequest = true;
+ store.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].AlsoToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].NEW_TAB_STATE_REQUEST
+ }));
+ }
+ }
+
+ if (document.hidden) {
+ requestIdleCallbackId = requestIdleCallback(doRequest);
+ addEventListener("visibilitychange", doRequest, {
+ once: true
+ });
+ } else {
+ doRequest();
+ }
+
+ react_dom__WEBPACK_IMPORTED_MODULE_6___default.a.hydrate(react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement(NewTab, {
+ store: store
+ }), document.getElementById("root"));
+}
+function renderCache(initialState) {
+ const store = Object(content_src_lib_init_store__WEBPACK_IMPORTED_MODULE_3__["initStore"])(common_Reducers_jsm__WEBPACK_IMPORTED_MODULE_7__["reducers"], initialState);
+ new content_src_lib_detect_user_session_start__WEBPACK_IMPORTED_MODULE_2__["DetectUserSessionStart"](store).sendEventOrAddListener();
+ react_dom__WEBPACK_IMPORTED_MODULE_6___default.a.hydrate(react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement(NewTab, {
+ store: store
+ }), document.getElementById("root"));
+}
+
+/***/ }),
+/* 1 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MAIN_MESSAGE_TYPE", function() { return MAIN_MESSAGE_TYPE; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CONTENT_MESSAGE_TYPE", function() { return CONTENT_MESSAGE_TYPE; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PRELOAD_MESSAGE_TYPE", function() { return PRELOAD_MESSAGE_TYPE; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UI_CODE", function() { return UI_CODE; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BACKGROUND_PROCESS", function() { return BACKGROUND_PROCESS; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "globalImportContext", function() { return globalImportContext; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "actionTypes", function() { return actionTypes; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "actionCreators", function() { return actionCreators; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "actionUtils", function() { return actionUtils; });
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+var MAIN_MESSAGE_TYPE = "ActivityStream:Main";
+var CONTENT_MESSAGE_TYPE = "ActivityStream:Content";
+var PRELOAD_MESSAGE_TYPE = "ActivityStream:PreloadedBrowser";
+var UI_CODE = 1;
+var BACKGROUND_PROCESS = 2;
+/**
+ * globalImportContext - Are we in UI code (i.e. react, a dom) or some kind of background process?
+ * Use this in action creators if you need different logic
+ * for ui/background processes.
+ */
+
+const globalImportContext = typeof Window === "undefined" ? BACKGROUND_PROCESS : UI_CODE; // Export for tests
+
+// Create an object that avoids accidental differing key/value pairs:
+// {
+// INIT: "INIT",
+// UNINIT: "UNINIT"
+// }
+const actionTypes = {};
+
+for (const type of ["ABOUT_SPONSORED_TOP_SITES", "ADDONS_INFO_REQUEST", "ADDONS_INFO_RESPONSE", "ARCHIVE_FROM_POCKET", "AS_ROUTER_INITIALIZED", "AS_ROUTER_PREF_CHANGED", "AS_ROUTER_TARGETING_UPDATE", "AS_ROUTER_TELEMETRY_USER_EVENT", "BLOCK_URL", "BOOKMARK_URL", "CLEAR_PREF", "COPY_DOWNLOAD_LINK", "DELETE_BOOKMARK_BY_ID", "DELETE_FROM_POCKET", "DELETE_HISTORY_URL", "DIALOG_CANCEL", "DIALOG_OPEN", "DISCOVERY_STREAM_COLLECTION_DISMISSIBLE_TOGGLE", "DISCOVERY_STREAM_CONFIG_CHANGE", "DISCOVERY_STREAM_CONFIG_RESET", "DISCOVERY_STREAM_CONFIG_RESET_DEFAULTS", "DISCOVERY_STREAM_CONFIG_SETUP", "DISCOVERY_STREAM_CONFIG_SET_VALUE", "DISCOVERY_STREAM_DEV_EXPIRE_CACHE", "DISCOVERY_STREAM_DEV_IDLE_DAILY", "DISCOVERY_STREAM_DEV_SYNC_RS", "DISCOVERY_STREAM_DEV_SYSTEM_TICK", "DISCOVERY_STREAM_FEEDS_UPDATE", "DISCOVERY_STREAM_FEED_UPDATE", "DISCOVERY_STREAM_IMPRESSION_STATS", "DISCOVERY_STREAM_LAYOUT_RESET", "DISCOVERY_STREAM_LAYOUT_UPDATE", "DISCOVERY_STREAM_LINK_BLOCKED", "DISCOVERY_STREAM_LOADED_CONTENT", "DISCOVERY_STREAM_PERSONALIZATION_INIT", "DISCOVERY_STREAM_PERSONALIZATION_LAST_UPDATED", "DISCOVERY_STREAM_PERSONALIZATION_VERSION", "DISCOVERY_STREAM_PERSONALIZATION_VERSION_TOGGLE", "DISCOVERY_STREAM_RETRY_FEED", "DISCOVERY_STREAM_SPOCS_CAPS", "DISCOVERY_STREAM_SPOCS_ENDPOINT", "DISCOVERY_STREAM_SPOCS_PLACEMENTS", "DISCOVERY_STREAM_SPOCS_UPDATE", "DISCOVERY_STREAM_SPOC_BLOCKED", "DISCOVERY_STREAM_SPOC_IMPRESSION", "DOWNLOAD_CHANGED", "FAKE_FOCUS_SEARCH", "FILL_SEARCH_TERM", "HANDOFF_SEARCH_TO_AWESOMEBAR", "HIDE_PRIVACY_INFO", "HIDE_SEARCH", "INIT", "NEW_TAB_INIT", "NEW_TAB_INITIAL_STATE", "NEW_TAB_LOAD", "NEW_TAB_REHYDRATED", "NEW_TAB_STATE_REQUEST", "NEW_TAB_UNLOAD", "OPEN_DOWNLOAD_FILE", "OPEN_LINK", "OPEN_NEW_WINDOW", "OPEN_PRIVATE_WINDOW", "OPEN_WEBEXT_SETTINGS", "PARTNER_LINK_ATTRIBUTION", "PLACES_BOOKMARK_ADDED", "PLACES_BOOKMARK_REMOVED", "PLACES_HISTORY_CLEARED", "PLACES_LINKS_CHANGED", "PLACES_LINK_BLOCKED", "PLACES_LINK_DELETED", "PLACES_SAVED_TO_POCKET", "POCKET_CTA", "POCKET_LINK_DELETED_OR_ARCHIVED", "POCKET_LOGGED_IN", "POCKET_WAITING_FOR_SPOC", "PREFS_INITIAL_VALUES", "PREF_CHANGED", "PREVIEW_REQUEST", "PREVIEW_REQUEST_CANCEL", "PREVIEW_RESPONSE", "REMOVE_DOWNLOAD_FILE", "RICH_ICON_MISSING", "SAVE_SESSION_PERF_DATA", "SAVE_TO_POCKET", "SCREENSHOT_UPDATED", "SECTION_DEREGISTER", "SECTION_DISABLE", "SECTION_ENABLE", "SECTION_MOVE", "SECTION_OPTIONS_CHANGED", "SECTION_REGISTER", "SECTION_UPDATE", "SECTION_UPDATE_CARD", "SETTINGS_CLOSE", "SETTINGS_OPEN", "SET_PREF", "SHOW_DOWNLOAD_FILE", "SHOW_FIREFOX_ACCOUNTS", "SHOW_PRIVACY_INFO", "SHOW_SEARCH", "SKIPPED_SIGNIN", "SNIPPETS_BLOCKLIST_CLEARED", "SNIPPETS_BLOCKLIST_UPDATED", "SNIPPETS_DATA", "SNIPPETS_PREVIEW_MODE", "SNIPPETS_RESET", "SNIPPET_BLOCKED", "SUBMIT_EMAIL", "SUBMIT_SIGNIN", "SYSTEM_TICK", "TELEMETRY_IMPRESSION_STATS", "TELEMETRY_USER_EVENT", "TOP_SITES_CANCEL_EDIT", "TOP_SITES_CLOSE_SEARCH_SHORTCUTS_MODAL", "TOP_SITES_EDIT", "TOP_SITES_INSERT", "TOP_SITES_OPEN_SEARCH_SHORTCUTS_MODAL", "TOP_SITES_PIN", "TOP_SITES_PREFS_UPDATED", "TOP_SITES_UNPIN", "TOP_SITES_UPDATED", "TOTAL_BOOKMARKS_REQUEST", "TOTAL_BOOKMARKS_RESPONSE", "UNINIT", "UPDATE_PINNED_SEARCH_SHORTCUTS", "UPDATE_SEARCH_SHORTCUTS", "UPDATE_SECTION_PREFS", "WEBEXT_CLICK", "WEBEXT_DISMISS"]) {
+ actionTypes[type] = type;
+} // Helper function for creating routed actions between content and main
+// Not intended to be used by consumers
+
+
+function _RouteMessage(action, options) {
+ const meta = action.meta ? { ...action.meta
+ } : {};
+
+ if (!options || !options.from || !options.to) {
+ throw new Error("Routed Messages must have options as the second parameter, and must at least include a .from and .to property.");
+ } // For each of these fields, if they are passed as an option,
+ // add them to the action. If they are not defined, remove them.
+
+
+ ["from", "to", "toTarget", "fromTarget", "skipMain", "skipLocal"].forEach(o => {
+ if (typeof options[o] !== "undefined") {
+ meta[o] = options[o];
+ } else if (meta[o]) {
+ delete meta[o];
+ }
+ });
+ return { ...action,
+ meta
+ };
+}
+/**
+ * AlsoToMain - Creates a message that will be dispatched locally and also sent to the Main process.
+ *
+ * @param {object} action Any redux action (required)
+ * @param {object} options
+ * @param {bool} skipLocal Used by OnlyToMain to skip the main reducer
+ * @param {string} fromTarget The id of the content port from which the action originated. (optional)
+ * @return {object} An action with added .meta properties
+ */
+
+
+function AlsoToMain(action, fromTarget, skipLocal) {
+ return _RouteMessage(action, {
+ from: CONTENT_MESSAGE_TYPE,
+ to: MAIN_MESSAGE_TYPE,
+ fromTarget,
+ skipLocal
+ });
+}
+/**
+ * OnlyToMain - Creates a message that will be sent to the Main process and skip the local reducer.
+ *
+ * @param {object} action Any redux action (required)
+ * @param {object} options
+ * @param {string} fromTarget The id of the content port from which the action originated. (optional)
+ * @return {object} An action with added .meta properties
+ */
+
+
+function OnlyToMain(action, fromTarget) {
+ return AlsoToMain(action, fromTarget, true);
+}
+/**
+ * BroadcastToContent - Creates a message that will be dispatched to main and sent to ALL content processes.
+ *
+ * @param {object} action Any redux action (required)
+ * @return {object} An action with added .meta properties
+ */
+
+
+function BroadcastToContent(action) {
+ return _RouteMessage(action, {
+ from: MAIN_MESSAGE_TYPE,
+ to: CONTENT_MESSAGE_TYPE
+ });
+}
+/**
+ * AlsoToOneContent - Creates a message that will be will be dispatched to the main store
+ * and also sent to a particular Content process.
+ *
+ * @param {object} action Any redux action (required)
+ * @param {string} target The id of a content port
+ * @param {bool} skipMain Used by OnlyToOneContent to skip the main process
+ * @return {object} An action with added .meta properties
+ */
+
+
+function AlsoToOneContent(action, target, skipMain) {
+ if (!target) {
+ throw new Error("You must provide a target ID as the second parameter of AlsoToOneContent. If you want to send to all content processes, use BroadcastToContent");
+ }
+
+ return _RouteMessage(action, {
+ from: MAIN_MESSAGE_TYPE,
+ to: CONTENT_MESSAGE_TYPE,
+ toTarget: target,
+ skipMain
+ });
+}
+/**
+ * OnlyToOneContent - Creates a message that will be sent to a particular Content process
+ * and skip the main reducer.
+ *
+ * @param {object} action Any redux action (required)
+ * @param {string} target The id of a content port
+ * @return {object} An action with added .meta properties
+ */
+
+
+function OnlyToOneContent(action, target) {
+ return AlsoToOneContent(action, target, true);
+}
+/**
+ * AlsoToPreloaded - Creates a message that dispatched to the main reducer and also sent to the preloaded tab.
+ *
+ * @param {object} action Any redux action (required)
+ * @return {object} An action with added .meta properties
+ */
+
+
+function AlsoToPreloaded(action) {
+ return _RouteMessage(action, {
+ from: MAIN_MESSAGE_TYPE,
+ to: PRELOAD_MESSAGE_TYPE
+ });
+}
+/**
+ * UserEvent - A telemetry ping indicating a user action. This should only
+ * be sent from the UI during a user session.
+ *
+ * @param {object} data Fields to include in the ping (source, etc.)
+ * @return {object} An AlsoToMain action
+ */
+
+
+function UserEvent(data) {
+ return AlsoToMain({
+ type: actionTypes.TELEMETRY_USER_EVENT,
+ data
+ });
+}
+/**
+ * ASRouterUserEvent - A telemetry ping indicating a user action from AS router. This should only
+ * be sent from the UI during a user session.
+ *
+ * @param {object} data Fields to include in the ping (source, etc.)
+ * @return {object} An AlsoToMain action
+ */
+
+
+function ASRouterUserEvent(data) {
+ return AlsoToMain({
+ type: actionTypes.AS_ROUTER_TELEMETRY_USER_EVENT,
+ data
+ });
+}
+/**
+ * ImpressionStats - A telemetry ping indicating an impression stats.
+ *
+ * @param {object} data Fields to include in the ping
+ * @param {int} importContext (For testing) Override the import context for testing.
+ * #return {object} An action. For UI code, a AlsoToMain action.
+ */
+
+
+function ImpressionStats(data, importContext = globalImportContext) {
+ const action = {
+ type: actionTypes.TELEMETRY_IMPRESSION_STATS,
+ data
+ };
+ return importContext === UI_CODE ? AlsoToMain(action) : action;
+}
+/**
+ * DiscoveryStreamImpressionStats - A telemetry ping indicating an impression stats in Discovery Stream.
+ *
+ * @param {object} data Fields to include in the ping
+ * @param {int} importContext (For testing) Override the import context for testing.
+ * #return {object} An action. For UI code, a AlsoToMain action.
+ */
+
+
+function DiscoveryStreamImpressionStats(data, importContext = globalImportContext) {
+ const action = {
+ type: actionTypes.DISCOVERY_STREAM_IMPRESSION_STATS,
+ data
+ };
+ return importContext === UI_CODE ? AlsoToMain(action) : action;
+}
+/**
+ * DiscoveryStreamLoadedContent - A telemetry ping indicating a content gets loaded in Discovery Stream.
+ *
+ * @param {object} data Fields to include in the ping
+ * @param {int} importContext (For testing) Override the import context for testing.
+ * #return {object} An action. For UI code, a AlsoToMain action.
+ */
+
+
+function DiscoveryStreamLoadedContent(data, importContext = globalImportContext) {
+ const action = {
+ type: actionTypes.DISCOVERY_STREAM_LOADED_CONTENT,
+ data
+ };
+ return importContext === UI_CODE ? AlsoToMain(action) : action;
+}
+
+function SetPref(name, value, importContext = globalImportContext) {
+ const action = {
+ type: actionTypes.SET_PREF,
+ data: {
+ name,
+ value
+ }
+ };
+ return importContext === UI_CODE ? AlsoToMain(action) : action;
+}
+
+function WebExtEvent(type, data, importContext = globalImportContext) {
+ if (!data || !data.source) {
+ throw new Error('WebExtEvent actions should include a property "source", the id of the webextension that should receive the event.');
+ }
+
+ const action = {
+ type,
+ data
+ };
+ return importContext === UI_CODE ? AlsoToMain(action) : action;
+}
+
+var actionCreators = {
+ BroadcastToContent,
+ UserEvent,
+ ASRouterUserEvent,
+ ImpressionStats,
+ AlsoToOneContent,
+ OnlyToOneContent,
+ AlsoToMain,
+ OnlyToMain,
+ AlsoToPreloaded,
+ SetPref,
+ WebExtEvent,
+ DiscoveryStreamImpressionStats,
+ DiscoveryStreamLoadedContent
+}; // These are helpers to test for certain kinds of actions
+
+var actionUtils = {
+ isSendToMain(action) {
+ if (!action.meta) {
+ return false;
+ }
+
+ return action.meta.to === MAIN_MESSAGE_TYPE && action.meta.from === CONTENT_MESSAGE_TYPE;
+ },
+
+ isBroadcastToContent(action) {
+ if (!action.meta) {
+ return false;
+ }
+
+ if (action.meta.to === CONTENT_MESSAGE_TYPE && !action.meta.toTarget) {
+ return true;
+ }
+
+ return false;
+ },
+
+ isSendToOneContent(action) {
+ if (!action.meta) {
+ return false;
+ }
+
+ if (action.meta.to === CONTENT_MESSAGE_TYPE && action.meta.toTarget) {
+ return true;
+ }
+
+ return false;
+ },
+
+ isSendToPreloaded(action) {
+ if (!action.meta) {
+ return false;
+ }
+
+ return action.meta.to === PRELOAD_MESSAGE_TYPE && action.meta.from === MAIN_MESSAGE_TYPE;
+ },
+
+ isFromMain(action) {
+ if (!action.meta) {
+ return false;
+ }
+
+ return action.meta.from === MAIN_MESSAGE_TYPE && action.meta.to === CONTENT_MESSAGE_TYPE;
+ },
+
+ getPortIdOfSender(action) {
+ return action.meta && action.meta.fromTarget || null;
+ },
+
+ _RouteMessage
+};
+
+/***/ }),
+/* 2 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* WEBPACK VAR INJECTION */(function(global) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PrefsButton", function() { return PrefsButton; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PersonalizeButton", function() { return PersonalizeButton; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_Base", function() { return _Base; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BaseContent", function() { return BaseContent; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Base", function() { return Base; });
+/* harmony import */ var common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
+/* harmony import */ var content_src_components_ASRouterAdmin_ASRouterAdmin__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4);
+/* harmony import */ var _asrouter_asrouter_content__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(10);
+/* harmony import */ var content_src_components_ConfirmDialog_ConfirmDialog__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(15);
+/* harmony import */ var react_redux__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(7);
+/* harmony import */ var react_redux__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(react_redux__WEBPACK_IMPORTED_MODULE_4__);
+/* harmony import */ var content_src_components_DiscoveryStreamBase_DiscoveryStreamBase__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(16);
+/* harmony import */ var content_src_components_ErrorBoundary_ErrorBoundary__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(35);
+/* harmony import */ var content_src_components_CustomizeMenu_CustomizeMenu__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(71);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_8__);
+/* harmony import */ var content_src_components_Search_Search__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(64);
+/* harmony import */ var content_src_components_Sections_Sections__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(47);
+/* harmony import */ var react_transition_group__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(29);
+/* harmony import */ var react_transition_group__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(react_transition_group__WEBPACK_IMPORTED_MODULE_11__);
+function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
+
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+
+
+
+
+
+
+
+
+
+
+const PrefsButton = ({
+ onClick,
+ icon
+}) => react__WEBPACK_IMPORTED_MODULE_8___default.a.createElement("div", {
+ className: "prefs-button"
+}, react__WEBPACK_IMPORTED_MODULE_8___default.a.createElement("button", {
+ className: `icon ${icon || "icon-settings"}`,
+ onClick: onClick,
+ "data-l10n-id": "newtab-settings-button"
+}));
+const PersonalizeButton = ({
+ onClick
+}) => react__WEBPACK_IMPORTED_MODULE_8___default.a.createElement("button", {
+ className: "personalize-button",
+ onClick: onClick,
+ "data-l10n-id": "newtab-personalize-button-label"
+}); // Returns a function will not be continuously triggered when called. The
+// function will be triggered if called again after `wait` milliseconds.
+
+function debounce(func, wait) {
+ let timer;
+ return (...args) => {
+ if (timer) {
+ return;
+ }
+
+ let wakeUp = () => {
+ timer = null;
+ };
+
+ timer = setTimeout(wakeUp, wait);
+ func.apply(this, args);
+ };
+}
+
+class _Base extends react__WEBPACK_IMPORTED_MODULE_8___default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.state = {
+ message: {}
+ };
+ this.notifyContent = this.notifyContent.bind(this);
+ }
+
+ notifyContent(state) {
+ this.setState(state);
+ }
+
+ componentWillUnmount() {
+ this.updateTheme();
+ }
+
+ componentWillUpdate() {
+ this.updateTheme();
+ }
+
+ updateTheme() {
+ const bodyClassName = ["activity-stream", // If we skipped the about:welcome overlay and removed the CSS classes
+ // we don't want to add them back to the Activity Stream view
+ document.body.classList.contains("inline-onboarding") ? "inline-onboarding" : ""].filter(v => v).join(" ");
+ global.document.body.className = bodyClassName;
+ }
+
+ render() {
+ const {
+ props
+ } = this;
+ const {
+ App
+ } = props;
+ const isDevtoolsEnabled = props.Prefs.values["asrouter.devtoolsEnabled"];
+
+ if (!App.initialized) {
+ return null;
+ }
+
+ return react__WEBPACK_IMPORTED_MODULE_8___default.a.createElement(content_src_components_ErrorBoundary_ErrorBoundary__WEBPACK_IMPORTED_MODULE_6__["ErrorBoundary"], {
+ className: "base-content-fallback"
+ }, react__WEBPACK_IMPORTED_MODULE_8___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_8___default.a.Fragment, null, react__WEBPACK_IMPORTED_MODULE_8___default.a.createElement(BaseContent, _extends({}, this.props, {
+ adminContent: this.state
+ })), isDevtoolsEnabled ? react__WEBPACK_IMPORTED_MODULE_8___default.a.createElement(content_src_components_ASRouterAdmin_ASRouterAdmin__WEBPACK_IMPORTED_MODULE_1__["ASRouterAdmin"], {
+ notifyContent: this.notifyContent
+ }) : null));
+ }
+
+}
+class BaseContent extends react__WEBPACK_IMPORTED_MODULE_8___default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.openPreferences = this.openPreferences.bind(this);
+ this.openCustomizationMenu = this.openCustomizationMenu.bind(this);
+ this.closeCustomizationMenu = this.closeCustomizationMenu.bind(this);
+ this.handleOnKeyDown = this.handleOnKeyDown.bind(this);
+ this.onWindowScroll = debounce(this.onWindowScroll.bind(this), 5);
+ this.setPref = this.setPref.bind(this);
+ this.state = {
+ fixedSearch: false,
+ customizeMenuVisible: false
+ };
+ }
+
+ componentDidMount() {
+ global.addEventListener("scroll", this.onWindowScroll);
+ global.addEventListener("keydown", this.handleOnKeyDown);
+ }
+
+ componentWillUnmount() {
+ global.removeEventListener("scroll", this.onWindowScroll);
+ global.removeEventListener("keydown", this.handleOnKeyDown);
+ }
+
+ onWindowScroll() {
+ const prefs = this.props.Prefs.values;
+ const SCROLL_THRESHOLD = prefs["logowordmark.alwaysVisible"] ? 179 : 34;
+
+ if (global.scrollY > SCROLL_THRESHOLD && !this.state.fixedSearch) {
+ this.setState({
+ fixedSearch: true
+ });
+ } else if (global.scrollY <= SCROLL_THRESHOLD && this.state.fixedSearch) {
+ this.setState({
+ fixedSearch: false
+ });
+ }
+ }
+
+ openPreferences() {
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].OnlyToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].SETTINGS_OPEN
+ }));
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].UserEvent({
+ event: "OPEN_NEWTAB_PREFS"
+ }));
+ }
+
+ openCustomizationMenu() {
+ this.setState({
+ customizeMenuVisible: true
+ });
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].UserEvent({
+ event: "SHOW_PERSONALIZE"
+ }));
+ }
+
+ closeCustomizationMenu() {
+ if (this.state.customizeMenuVisible) {
+ this.setState({
+ customizeMenuVisible: false
+ });
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].UserEvent({
+ event: "HIDE_PERSONALIZE"
+ }));
+ }
+ }
+
+ handleOnKeyDown(e) {
+ if (e.key === "Escape") {
+ this.closeCustomizationMenu();
+ }
+ }
+
+ setPref(pref, value) {
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].SetPref(pref, value));
+ }
+
+ render() {
+ const {
+ props
+ } = this;
+ const {
+ App
+ } = props;
+ const {
+ initialized
+ } = App;
+ const prefs = props.Prefs.values; // Values from experiment data
+
+ const {
+ prefsButtonIcon
+ } = prefs.featureConfig || {};
+ const isDiscoveryStream = props.DiscoveryStream.config && props.DiscoveryStream.config.enabled;
+ let filteredSections = props.Sections.filter(section => section.id !== "topstories");
+ const pocketEnabled = prefs["feeds.section.topstories"] && prefs["feeds.system.topstories"];
+ const noSectionsEnabled = !prefs["feeds.topsites"] && !pocketEnabled && filteredSections.filter(section => section.enabled).length === 0;
+ const searchHandoffEnabled = prefs["improvesearch.handoffToAwesomebar"];
+ const customizationMenuEnabled = prefs["customizationMenu.enabled"];
+ const newNewtabExperienceEnabled = prefs["newNewtabExperience.enabled"];
+ const canShowCustomizationMenu = customizationMenuEnabled || newNewtabExperienceEnabled;
+ const showCustomizationMenu = canShowCustomizationMenu && this.state.customizeMenuVisible;
+ const enabledSections = {
+ topSitesEnabled: prefs["feeds.topsites"],
+ pocketEnabled: prefs["feeds.section.topstories"],
+ snippetsEnabled: prefs["feeds.snippets"],
+ highlightsEnabled: prefs["feeds.section.highlights"],
+ showSponsoredTopSitesEnabled: prefs.showSponsoredTopSites,
+ showSponsoredPocketEnabled: prefs.showSponsored,
+ topSitesRowsCount: prefs.topSitesRows
+ };
+ const pocketRegion = prefs["feeds.system.topstories"];
+ const {
+ mayHaveSponsoredTopSites
+ } = prefs;
+ const outerClassName = ["outer-wrapper", isDiscoveryStream && pocketEnabled && "ds-outer-wrapper-search-alignment", isDiscoveryStream && "ds-outer-wrapper-breakpoint-override", prefs.showSearch && this.state.fixedSearch && !noSectionsEnabled && "fixed-search", prefs.showSearch && noSectionsEnabled && "only-search", prefs["logowordmark.alwaysVisible"] && "visible-logo", newNewtabExperienceEnabled && "newtab-experience"].filter(v => v).join(" ");
+ return react__WEBPACK_IMPORTED_MODULE_8___default.a.createElement("div", null, canShowCustomizationMenu ? react__WEBPACK_IMPORTED_MODULE_8___default.a.createElement("span", null, react__WEBPACK_IMPORTED_MODULE_8___default.a.createElement(PersonalizeButton, {
+ onClick: this.openCustomizationMenu
+ }), react__WEBPACK_IMPORTED_MODULE_8___default.a.createElement(react_transition_group__WEBPACK_IMPORTED_MODULE_11__["CSSTransition"], {
+ timeout: 0,
+ classNames: "customize-animate",
+ in: showCustomizationMenu,
+ appear: true
+ }, react__WEBPACK_IMPORTED_MODULE_8___default.a.createElement(content_src_components_CustomizeMenu_CustomizeMenu__WEBPACK_IMPORTED_MODULE_7__["CustomizeMenu"], {
+ onClose: this.closeCustomizationMenu,
+ openPreferences: this.openPreferences,
+ setPref: this.setPref,
+ enabledSections: enabledSections,
+ pocketRegion: pocketRegion,
+ mayHaveSponsoredTopSites: mayHaveSponsoredTopSites
+ }))) : react__WEBPACK_IMPORTED_MODULE_8___default.a.createElement(PrefsButton, {
+ onClick: this.openPreferences,
+ icon: prefsButtonIcon
+ }), react__WEBPACK_IMPORTED_MODULE_8___default.a.createElement("div", {
+ className: outerClassName,
+ onClick: this.closeCustomizationMenu
+ }, react__WEBPACK_IMPORTED_MODULE_8___default.a.createElement("main", null, prefs.showSearch && react__WEBPACK_IMPORTED_MODULE_8___default.a.createElement("div", {
+ className: "non-collapsible-section"
+ }, react__WEBPACK_IMPORTED_MODULE_8___default.a.createElement(content_src_components_ErrorBoundary_ErrorBoundary__WEBPACK_IMPORTED_MODULE_6__["ErrorBoundary"], null, react__WEBPACK_IMPORTED_MODULE_8___default.a.createElement(content_src_components_Search_Search__WEBPACK_IMPORTED_MODULE_9__["Search"], _extends({
+ showLogo: noSectionsEnabled || prefs["logowordmark.alwaysVisible"],
+ handoffEnabled: searchHandoffEnabled
+ }, props.Search)))), react__WEBPACK_IMPORTED_MODULE_8___default.a.createElement(_asrouter_asrouter_content__WEBPACK_IMPORTED_MODULE_2__["ASRouterUISurface"], {
+ adminContent: this.props.adminContent,
+ appUpdateChannel: this.props.Prefs.values.appUpdateChannel,
+ fxaEndpoint: this.props.Prefs.values.fxa_endpoint,
+ dispatch: this.props.dispatch
+ }), react__WEBPACK_IMPORTED_MODULE_8___default.a.createElement("div", {
+ className: `body-wrapper${initialized ? " on" : ""}`
+ }, isDiscoveryStream ? react__WEBPACK_IMPORTED_MODULE_8___default.a.createElement(content_src_components_ErrorBoundary_ErrorBoundary__WEBPACK_IMPORTED_MODULE_6__["ErrorBoundary"], {
+ className: "borderless-error"
+ }, react__WEBPACK_IMPORTED_MODULE_8___default.a.createElement(content_src_components_DiscoveryStreamBase_DiscoveryStreamBase__WEBPACK_IMPORTED_MODULE_5__["DiscoveryStreamBase"], {
+ locale: props.App.locale
+ })) : react__WEBPACK_IMPORTED_MODULE_8___default.a.createElement(content_src_components_Sections_Sections__WEBPACK_IMPORTED_MODULE_10__["Sections"], null)), react__WEBPACK_IMPORTED_MODULE_8___default.a.createElement(content_src_components_ConfirmDialog_ConfirmDialog__WEBPACK_IMPORTED_MODULE_3__["ConfirmDialog"], null))));
+ }
+
+}
+const Base = Object(react_redux__WEBPACK_IMPORTED_MODULE_4__["connect"])(state => ({
+ App: state.App,
+ Prefs: state.Prefs,
+ Sections: state.Sections,
+ DiscoveryStream: state.DiscoveryStream,
+ Search: state.Search
+}))(_Base);
+/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(3)))
+
+/***/ }),
+/* 3 */
+/***/ (function(module, exports) {
+
+var g;
+
+// This works in non-strict mode
+g = (function() {
+ return this;
+})();
+
+try {
+ // This works if eval is allowed (see CSP)
+ g = g || new Function("return this")();
+} catch (e) {
+ // This works if the window reference is available
+ if (typeof window === "object") g = window;
+}
+
+// g can still be undefined, but nothing to do about it...
+// We return undefined, instead of nothing here, so it's
+// easier to handle this case. if(!global) { ...}
+
+module.exports = g;
+
+
+/***/ }),
+/* 4 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* WEBPACK VAR INJECTION */(function(global) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ToggleStoryButton", function() { return ToggleStoryButton; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ToggleMessageJSON", function() { return ToggleMessageJSON; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TogglePrefCheckbox", function() { return TogglePrefCheckbox; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Personalization", function() { return Personalization; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiscoveryStreamAdmin", function() { return DiscoveryStreamAdmin; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ASRouterAdminInner", function() { return ASRouterAdminInner; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CollapseToggle", function() { return CollapseToggle; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ASRouterAdmin", function() { return ASRouterAdmin; });
+/* harmony import */ var common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
+/* harmony import */ var _asrouter_asrouter_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(5);
+/* harmony import */ var react_redux__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(7);
+/* harmony import */ var react_redux__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react_redux__WEBPACK_IMPORTED_MODULE_2__);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_3__);
+/* harmony import */ var _SimpleHashRouter__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(9);
+function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
+
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+
+
+
+
+const Row = props => react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("tr", _extends({
+ className: "message-item"
+}, props), props.children);
+
+function relativeTime(timestamp) {
+ if (!timestamp) {
+ return "";
+ }
+
+ const seconds = Math.floor((Date.now() - timestamp) / 1000);
+ const minutes = Math.floor((Date.now() - timestamp) / 60000);
+
+ if (seconds < 2) {
+ return "just now";
+ } else if (seconds < 60) {
+ return `${seconds} seconds ago`;
+ } else if (minutes === 1) {
+ return "1 minute ago";
+ } else if (minutes < 600) {
+ return `${minutes} minutes ago`;
+ }
+
+ return new Date(timestamp).toLocaleString();
+}
+
+const LAYOUT_VARIANTS = {
+ basic: "Basic default layout (on by default in nightly)",
+ staging_spocs: "A layout with all spocs shown",
+ "dev-test-all": "A little bit of everything. Good layout for testing all components",
+ "dev-test-feeds": "Stress testing for slow feeds"
+};
+class ToggleStoryButton extends react__WEBPACK_IMPORTED_MODULE_3___default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.handleClick = this.handleClick.bind(this);
+ }
+
+ handleClick() {
+ this.props.onClick(this.props.story);
+ }
+
+ render() {
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("button", {
+ onClick: this.handleClick
+ }, "collapse/open");
+ }
+
+}
+class ToggleMessageJSON extends react__WEBPACK_IMPORTED_MODULE_3___default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.handleClick = this.handleClick.bind(this);
+ }
+
+ handleClick() {
+ this.props.toggleJSON(this.props.msgId);
+ }
+
+ render() {
+ let iconName = this.props.isCollapsed ? "icon icon-arrowhead-forward-small" : "icon icon-arrowhead-down-small";
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("button", {
+ className: "clearButton",
+ onClick: this.handleClick
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("span", {
+ className: iconName
+ }));
+ }
+
+}
+class TogglePrefCheckbox extends react__WEBPACK_IMPORTED_MODULE_3___default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onChange = this.onChange.bind(this);
+ }
+
+ onChange(event) {
+ this.props.onChange(this.props.pref, event.target.checked);
+ }
+
+ render() {
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_3___default.a.Fragment, null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("input", {
+ type: "checkbox",
+ checked: this.props.checked,
+ onChange: this.onChange,
+ disabled: this.props.disabled
+ }), " ", this.props.pref, " ");
+ }
+
+}
+class Personalization extends react__WEBPACK_IMPORTED_MODULE_3___default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.togglePersonalizationVersion = this.togglePersonalizationVersion.bind(this);
+ }
+
+ togglePersonalizationVersion() {
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].OnlyToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].DISCOVERY_STREAM_PERSONALIZATION_VERSION_TOGGLE
+ }));
+ }
+
+ render() {
+ const {
+ lastUpdated,
+ version,
+ initialized
+ } = this.props.state.Personalization;
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_3___default.a.Fragment, null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("button", {
+ className: "button",
+ onClick: this.togglePersonalizationVersion
+ }, version === 1 ? "Enable V2 Personalization" : "Enable V1 Personalization"), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("table", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("tbody", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(Row, null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", {
+ className: "min"
+ }, "Personalization version"), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, version)), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(Row, null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", {
+ className: "min"
+ }, "Personalization Last Updated"), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, relativeTime(lastUpdated) || "(no data)")), version === 2 ? react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(Row, null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", {
+ className: "min"
+ }, "Personalization V2 Initialized"), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, initialized ? "true" : "false")) : null)));
+ }
+
+}
+class DiscoveryStreamAdmin extends react__WEBPACK_IMPORTED_MODULE_3___default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.restorePrefDefaults = this.restorePrefDefaults.bind(this);
+ this.setConfigValue = this.setConfigValue.bind(this);
+ this.expireCache = this.expireCache.bind(this);
+ this.refreshCache = this.refreshCache.bind(this);
+ this.idleDaily = this.idleDaily.bind(this);
+ this.systemTick = this.systemTick.bind(this);
+ this.syncRemoteSettings = this.syncRemoteSettings.bind(this);
+ this.changeEndpointVariant = this.changeEndpointVariant.bind(this);
+ this.onStoryToggle = this.onStoryToggle.bind(this);
+ this.state = {
+ toggledStories: {}
+ };
+ }
+
+ setConfigValue(name, value) {
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].OnlyToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].DISCOVERY_STREAM_CONFIG_SET_VALUE,
+ data: {
+ name,
+ value
+ }
+ }));
+ }
+
+ restorePrefDefaults(event) {
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].OnlyToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].DISCOVERY_STREAM_CONFIG_RESET_DEFAULTS
+ }));
+ }
+
+ refreshCache() {
+ const {
+ config
+ } = this.props.state.DiscoveryStream;
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].OnlyToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].DISCOVERY_STREAM_CONFIG_CHANGE,
+ data: config
+ }));
+ }
+
+ dispatchSimpleAction(type) {
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].OnlyToMain({
+ type
+ }));
+ }
+
+ systemTick() {
+ this.dispatchSimpleAction(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].DISCOVERY_STREAM_DEV_SYSTEM_TICK);
+ }
+
+ expireCache() {
+ this.dispatchSimpleAction(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].DISCOVERY_STREAM_DEV_EXPIRE_CACHE);
+ }
+
+ idleDaily() {
+ this.dispatchSimpleAction(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].DISCOVERY_STREAM_DEV_IDLE_DAILY);
+ }
+
+ syncRemoteSettings() {
+ this.dispatchSimpleAction(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].DISCOVERY_STREAM_DEV_SYNC_RS);
+ }
+
+ changeEndpointVariant(event) {
+ const endpoint = this.props.state.DiscoveryStream.config.layout_endpoint;
+
+ if (endpoint) {
+ this.setConfigValue("layout_endpoint", endpoint.replace(/layout_variant=.+/, `layout_variant=${event.target.value}`));
+ }
+ }
+
+ renderComponent(width, component) {
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("table", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("tbody", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(Row, null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", {
+ className: "min"
+ }, "Type"), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, component.type)), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(Row, null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", {
+ className: "min"
+ }, "Width"), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, width)), component.feed && this.renderFeed(component.feed)));
+ }
+
+ isCurrentVariant(id) {
+ const endpoint = this.props.state.DiscoveryStream.config.layout_endpoint;
+ const isMatch = endpoint && !!endpoint.match(`layout_variant=${id}`);
+ return isMatch;
+ }
+
+ renderFeedData(url) {
+ const {
+ feeds
+ } = this.props.state.DiscoveryStream;
+ const feed = feeds.data[url].data;
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_3___default.a.Fragment, null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("h4", null, "Feed url: ", url), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("table", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("tbody", null, feed.recommendations.map(story => this.renderStoryData(story)))));
+ }
+
+ renderFeedsData() {
+ const {
+ feeds
+ } = this.props.state.DiscoveryStream;
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_3___default.a.Fragment, null, Object.keys(feeds.data).map(url => this.renderFeedData(url)));
+ }
+
+ renderSpocs() {
+ const {
+ spocs
+ } = this.props.state.DiscoveryStream;
+ let spocsData = [];
+
+ if (spocs.data && spocs.data.spocs && spocs.data.spocs.items) {
+ spocsData = spocs.data.spocs.items || [];
+ }
+
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_3___default.a.Fragment, null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("table", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("tbody", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(Row, null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", {
+ className: "min"
+ }, "spocs_endpoint"), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, spocs.spocs_endpoint)), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(Row, null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", {
+ className: "min"
+ }, "Data last fetched"), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, relativeTime(spocs.lastUpdated))))), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("h4", null, "Spoc data"), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("table", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("tbody", null, spocsData.map(spoc => this.renderStoryData(spoc)))), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("h4", null, "Spoc frequency caps"), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("table", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("tbody", null, spocs.frequency_caps.map(spoc => this.renderStoryData(spoc)))));
+ }
+
+ onStoryToggle(story) {
+ const {
+ toggledStories
+ } = this.state;
+ this.setState({
+ toggledStories: { ...toggledStories,
+ [story.id]: !toggledStories[story.id]
+ }
+ });
+ }
+
+ renderStoryData(story) {
+ let storyData = "";
+
+ if (this.state.toggledStories[story.id]) {
+ storyData = JSON.stringify(story, null, 2);
+ }
+
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("tr", {
+ className: "message-item",
+ key: story.id
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", {
+ className: "message-id"
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("span", null, story.id, " ", react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("br", null)), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(ToggleStoryButton, {
+ story: story,
+ onClick: this.onStoryToggle
+ })), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", {
+ className: "message-summary"
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("pre", null, storyData)));
+ }
+
+ renderFeed(feed) {
+ const {
+ feeds
+ } = this.props.state.DiscoveryStream;
+
+ if (!feed.url) {
+ return null;
+ }
+
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_3___default.a.Fragment, null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(Row, null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", {
+ className: "min"
+ }, "Feed url"), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, feed.url)), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(Row, null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", {
+ className: "min"
+ }, "Data last fetched"), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, relativeTime(feeds.data[feed.url] ? feeds.data[feed.url].lastUpdated : null) || "(no data)")));
+ }
+
+ render() {
+ const prefToggles = "enabled hardcoded_layout show_spocs personalized collapsible".split(" ");
+ const {
+ config,
+ lastUpdated,
+ layout
+ } = this.props.state.DiscoveryStream;
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("div", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("button", {
+ className: "button",
+ onClick: this.restorePrefDefaults
+ }, "Restore Pref Defaults"), " ", react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("button", {
+ className: "button",
+ onClick: this.refreshCache
+ }, "Refresh Cache"), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("br", null), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("button", {
+ className: "button",
+ onClick: this.expireCache
+ }, "Expire Cache"), " ", react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("button", {
+ className: "button",
+ onClick: this.systemTick
+ }, "Trigger System Tick"), " ", react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("button", {
+ className: "button",
+ onClick: this.idleDaily
+ }, "Trigger Idle Daily"), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("br", null), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("button", {
+ className: "button",
+ onClick: this.syncRemoteSettings
+ }, "Sync Remote Settings"), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("table", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("tbody", null, prefToggles.map(pref => react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(Row, {
+ key: pref
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(TogglePrefCheckbox, {
+ checked: config[pref],
+ pref: pref,
+ onChange: this.setConfigValue
+ })))))), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("h3", null, "Endpoint variant"), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("p", null, "You can also change this manually by changing this pref:", " ", react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("code", null, "browser.newtabpage.activity-stream.discoverystream.config")), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("table", {
+ style: config.enabled && !config.hardcoded_layout ? null : {
+ opacity: 0.5
+ }
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("tbody", null, Object.keys(LAYOUT_VARIANTS).map(id => react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(Row, {
+ key: id
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", {
+ className: "min"
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("input", {
+ type: "radio",
+ value: id,
+ checked: this.isCurrentVariant(id),
+ onChange: this.changeEndpointVariant
+ })), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", {
+ className: "min"
+ }, id), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, LAYOUT_VARIANTS[id]))))), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("h3", null, "Caching info"), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("table", {
+ style: config.enabled ? null : {
+ opacity: 0.5
+ }
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("tbody", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(Row, null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", {
+ className: "min"
+ }, "Data last fetched"), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, relativeTime(lastUpdated) || "(no data)")))), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("h3", null, "Layout"), layout.map((row, rowIndex) => react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("div", {
+ key: `row-${rowIndex}`
+ }, row.components.map((component, componentIndex) => react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("div", {
+ key: `component-${componentIndex}`,
+ className: "ds-component"
+ }, this.renderComponent(row.width, component))))), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("h3", null, "Personalization"), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(Personalization, {
+ dispatch: this.props.dispatch,
+ state: {
+ Personalization: this.props.state.Personalization
+ }
+ }), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("h3", null, "Spocs"), this.renderSpocs(), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("h3", null, "Feeds Data"), this.renderFeedsData());
+ }
+
+}
+class ASRouterAdminInner extends react__WEBPACK_IMPORTED_MODULE_3___default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.handleEnabledToggle = this.handleEnabledToggle.bind(this);
+ this.handleUserPrefToggle = this.handleUserPrefToggle.bind(this);
+ this.onChangeMessageFilter = this.onChangeMessageFilter.bind(this);
+ this.onChangeMessageGroupsFilter = this.onChangeMessageGroupsFilter.bind(this);
+ this.unblockAll = this.unblockAll.bind(this);
+ this.handleClearAllImpressionsByProvider = this.handleClearAllImpressionsByProvider.bind(this);
+ this.handleExpressionEval = this.handleExpressionEval.bind(this);
+ this.onChangeTargetingParameters = this.onChangeTargetingParameters.bind(this);
+ this.onChangeAttributionParameters = this.onChangeAttributionParameters.bind(this);
+ this.setAttribution = this.setAttribution.bind(this);
+ this.onCopyTargetingParams = this.onCopyTargetingParams.bind(this);
+ this.onNewTargetingParams = this.onNewTargetingParams.bind(this);
+ this.handleUpdateWNMessages = this.handleUpdateWNMessages.bind(this);
+ this.handleForceWNP = this.handleForceWNP.bind(this);
+ this.handleCloseWNP = this.handleCloseWNP.bind(this);
+ this.resetPanel = this.resetPanel.bind(this);
+ this.restoreWNMessageState = this.restoreWNMessageState.bind(this);
+ this.toggleJSON = this.toggleJSON.bind(this);
+ this.toggleAllMessages = this.toggleAllMessages.bind(this);
+ this.resetGroups = this.resetGroups.bind(this);
+ this.onMessageFromParent = this.onMessageFromParent.bind(this);
+ this.setStateFromParent = this.setStateFromParent.bind(this);
+ this.setState = this.setState.bind(this);
+ this.state = {
+ messageFilter: "all",
+ messageGroupsFilter: "all",
+ WNMessages: [],
+ collapsedMessages: [],
+ modifiedMessages: [],
+ evaluationStatus: {},
+ stringTargetingParameters: null,
+ newStringTargetingParameters: null,
+ copiedToClipboard: false,
+ attributionParameters: {
+ source: "addons.mozilla.org",
+ medium: "referral",
+ campaign: "non-fx-button",
+ content: "iridium@particlecore.github.io",
+ experiment: "ua-onboarding",
+ variation: "chrome",
+ ua: "Google Chrome 123",
+ dltoken: "00000000-0000-0000-0000-000000000000"
+ }
+ };
+ }
+
+ onMessageFromParent({
+ type,
+ data
+ }) {
+ // These only exists due to onPrefChange events in ASRouter
+ switch (type) {
+ case "UpdateAdminState":
+ {
+ this.setStateFromParent(data);
+ break;
+ }
+ }
+ }
+
+ setStateFromParent(data) {
+ this.setState(data);
+
+ if (!this.state.stringTargetingParameters) {
+ const stringTargetingParameters = {};
+
+ for (const param of Object.keys(data.targetingParameters)) {
+ stringTargetingParameters[param] = JSON.stringify(data.targetingParameters[param], null, 2);
+ }
+
+ this.setState({
+ stringTargetingParameters
+ });
+ }
+ }
+
+ componentWillMount() {
+ _asrouter_asrouter_utils__WEBPACK_IMPORTED_MODULE_1__["ASRouterUtils"].addListener(this.onMessageFromParent);
+ const endpoint = _asrouter_asrouter_utils__WEBPACK_IMPORTED_MODULE_1__["ASRouterUtils"].getPreviewEndpoint();
+ _asrouter_asrouter_utils__WEBPACK_IMPORTED_MODULE_1__["ASRouterUtils"].sendMessage({
+ type: "ADMIN_CONNECT_STATE",
+ data: {
+ endpoint
+ }
+ }).then(this.setStateFromParent);
+ }
+
+ handleBlock(msg) {
+ return () => _asrouter_asrouter_utils__WEBPACK_IMPORTED_MODULE_1__["ASRouterUtils"].blockById(msg.id);
+ }
+
+ handleUnblock(msg) {
+ return () => _asrouter_asrouter_utils__WEBPACK_IMPORTED_MODULE_1__["ASRouterUtils"].unblockById(msg.id);
+ }
+
+ resetJSON(msg) {
+ // reset the displayed JSON for the given message
+ document.getElementById(`${msg.id}-textarea`).value = JSON.stringify(msg, null, 2); // remove the message from the list of modified IDs
+
+ let index = this.state.modifiedMessages.indexOf(msg.id);
+ this.setState(prevState => ({
+ modifiedMessages: [...prevState.modifiedMessages.slice(0, index), ...prevState.modifiedMessages.slice(index + 1)]
+ }));
+ }
+
+ resetAllJSON() {
+ let messageCheckboxes = document.querySelectorAll('input[type="checkbox"]');
+
+ for (const checkbox of messageCheckboxes) {
+ let trimmedId = checkbox.id.replace(" checkbox", "");
+ let message = this.state.messages.filter(msg => msg.id === trimmedId);
+ let msgId = message[0].id;
+ document.getElementById(`${msgId}-textarea`).value = JSON.stringify(message[0], null, 2);
+ }
+
+ this.setState({
+ WNMessages: []
+ });
+ }
+
+ resetPanel() {
+ this.resetAllJSON();
+ this.handleCloseWNP();
+ }
+
+ handleOverride(id) {
+ return () => _asrouter_asrouter_utils__WEBPACK_IMPORTED_MODULE_1__["ASRouterUtils"].overrideMessage(id).then(state => {
+ this.setStateFromParent(state);
+ this.props.notifyContent({
+ message: state.message
+ });
+ });
+ }
+
+ async handleUpdateWNMessages() {
+ await this.restoreWNMessageState();
+ let messages = this.state.WNMessages;
+
+ for (const msg of messages) {
+ _asrouter_asrouter_utils__WEBPACK_IMPORTED_MODULE_1__["ASRouterUtils"].modifyMessageJson(JSON.parse(msg));
+ }
+ }
+
+ handleForceWNP() {
+ _asrouter_asrouter_utils__WEBPACK_IMPORTED_MODULE_1__["ASRouterUtils"].sendMessage({
+ type: "FORCE_WHATSNEW_PANEL"
+ });
+ }
+
+ handleCloseWNP() {
+ _asrouter_asrouter_utils__WEBPACK_IMPORTED_MODULE_1__["ASRouterUtils"].sendMessage({
+ type: "CLOSE_WHATSNEW_PANEL"
+ });
+ }
+
+ expireCache() {
+ _asrouter_asrouter_utils__WEBPACK_IMPORTED_MODULE_1__["ASRouterUtils"].sendMessage({
+ type: "EXPIRE_QUERY_CACHE"
+ });
+ }
+
+ resetPref() {
+ _asrouter_asrouter_utils__WEBPACK_IMPORTED_MODULE_1__["ASRouterUtils"].sendMessage({
+ type: "RESET_PROVIDER_PREF"
+ });
+ }
+
+ resetGroups(id, value) {
+ _asrouter_asrouter_utils__WEBPACK_IMPORTED_MODULE_1__["ASRouterUtils"].sendMessage({
+ type: "RESET_GROUPS_STATE"
+ }).then(this.setStateFromParent);
+ }
+
+ handleExpressionEval() {
+ const context = {};
+
+ for (const param of Object.keys(this.state.stringTargetingParameters)) {
+ const value = this.state.stringTargetingParameters[param];
+ context[param] = value ? JSON.parse(value) : null;
+ }
+
+ _asrouter_asrouter_utils__WEBPACK_IMPORTED_MODULE_1__["ASRouterUtils"].sendMessage({
+ type: "EVALUATE_JEXL_EXPRESSION",
+ data: {
+ expression: this.refs.expressionInput.value,
+ context
+ }
+ }).then(this.setStateFromParent);
+ }
+
+ onChangeTargetingParameters(event) {
+ const {
+ name
+ } = event.target;
+ const {
+ value
+ } = event.target;
+ this.setState(({
+ stringTargetingParameters
+ }) => {
+ let targetingParametersError = null;
+ const updatedParameters = { ...stringTargetingParameters
+ };
+ updatedParameters[name] = value;
+
+ try {
+ JSON.parse(value);
+ } catch (e) {
+ console.log(`Error parsing value of parameter ${name}`); // eslint-disable-line no-console
+
+ targetingParametersError = {
+ id: name
+ };
+ }
+
+ return {
+ copiedToClipboard: false,
+ evaluationStatus: {},
+ stringTargetingParameters: updatedParameters,
+ targetingParametersError
+ };
+ });
+ }
+
+ unblockAll() {
+ return _asrouter_asrouter_utils__WEBPACK_IMPORTED_MODULE_1__["ASRouterUtils"].sendMessage({
+ type: "UNBLOCK_ALL"
+ }).then(this.setStateFromParent);
+ }
+
+ handleClearAllImpressionsByProvider() {
+ const providerId = this.state.messageFilter;
+
+ if (!providerId) {
+ return;
+ }
+
+ const userPrefInfo = this.state.userPrefs;
+ const isUserEnabled = providerId in userPrefInfo ? userPrefInfo[providerId] : true;
+ _asrouter_asrouter_utils__WEBPACK_IMPORTED_MODULE_1__["ASRouterUtils"].sendMessage({
+ type: "DISABLE_PROVIDER",
+ data: providerId
+ });
+
+ if (!isUserEnabled) {
+ _asrouter_asrouter_utils__WEBPACK_IMPORTED_MODULE_1__["ASRouterUtils"].sendMessage({
+ type: "SET_PROVIDER_USER_PREF",
+ data: {
+ id: providerId,
+ value: true
+ }
+ });
+ }
+
+ _asrouter_asrouter_utils__WEBPACK_IMPORTED_MODULE_1__["ASRouterUtils"].sendMessage({
+ type: "ENABLE_PROVIDER",
+ data: providerId
+ });
+ }
+
+ handleEnabledToggle(event) {
+ const provider = this.state.providerPrefs.find(p => p.id === event.target.dataset.provider);
+ const userPrefInfo = this.state.userPrefs;
+ const isUserEnabled = provider.id in userPrefInfo ? userPrefInfo[provider.id] : true;
+ const isSystemEnabled = provider.enabled;
+ const isEnabling = event.target.checked;
+
+ if (isEnabling) {
+ if (!isUserEnabled) {
+ _asrouter_asrouter_utils__WEBPACK_IMPORTED_MODULE_1__["ASRouterUtils"].sendMessage({
+ type: "SET_PROVIDER_USER_PREF",
+ data: {
+ id: provider.id,
+ value: true
+ }
+ });
+ }
+
+ if (!isSystemEnabled) {
+ _asrouter_asrouter_utils__WEBPACK_IMPORTED_MODULE_1__["ASRouterUtils"].sendMessage({
+ type: "ENABLE_PROVIDER",
+ data: provider.id
+ });
+ }
+ } else {
+ _asrouter_asrouter_utils__WEBPACK_IMPORTED_MODULE_1__["ASRouterUtils"].sendMessage({
+ type: "DISABLE_PROVIDER",
+ data: provider.id
+ });
+ }
+
+ this.setState({
+ messageFilter: "all"
+ });
+ }
+
+ handleUserPrefToggle(event) {
+ const action = {
+ type: "SET_PROVIDER_USER_PREF",
+ data: {
+ id: event.target.dataset.provider,
+ value: event.target.checked
+ }
+ };
+ _asrouter_asrouter_utils__WEBPACK_IMPORTED_MODULE_1__["ASRouterUtils"].sendMessage(action);
+ this.setState({
+ messageFilter: "all"
+ });
+ }
+
+ onChangeMessageFilter(event) {
+ this.setState({
+ messageFilter: event.target.value
+ });
+ }
+
+ onChangeMessageGroupsFilter(event) {
+ this.setState({
+ messageGroupsFilter: event.target.value
+ });
+ } // Simulate a copy event that sets to clipboard all targeting paramters and values
+
+
+ onCopyTargetingParams(event) {
+ const stringTargetingParameters = { ...this.state.stringTargetingParameters
+ };
+
+ for (const key of Object.keys(stringTargetingParameters)) {
+ // If the value is not set the parameter will be lost when we stringify
+ if (stringTargetingParameters[key] === undefined) {
+ stringTargetingParameters[key] = null;
+ }
+ }
+
+ const setClipboardData = e => {
+ e.preventDefault();
+ e.clipboardData.setData("text", JSON.stringify(stringTargetingParameters, null, 2));
+ document.removeEventListener("copy", setClipboardData);
+ this.setState({
+ copiedToClipboard: true
+ });
+ };
+
+ document.addEventListener("copy", setClipboardData);
+ document.execCommand("copy");
+ }
+
+ onNewTargetingParams(event) {
+ this.setState({
+ newStringTargetingParameters: event.target.value
+ });
+ event.target.classList.remove("errorState");
+ this.refs.targetingParamsEval.innerText = "";
+
+ try {
+ const stringTargetingParameters = JSON.parse(event.target.value);
+ this.setState({
+ stringTargetingParameters
+ });
+ } catch (e) {
+ event.target.classList.add("errorState");
+ this.refs.targetingParamsEval.innerText = e.message;
+ }
+ }
+
+ toggleJSON(msgId) {
+ if (this.state.collapsedMessages.includes(msgId)) {
+ let index = this.state.collapsedMessages.indexOf(msgId);
+ this.setState(prevState => ({
+ collapsedMessages: [...prevState.collapsedMessages.slice(0, index), ...prevState.collapsedMessages.slice(index + 1)]
+ }));
+ } else {
+ this.setState(prevState => ({
+ collapsedMessages: prevState.collapsedMessages.concat(msgId)
+ }));
+ }
+ }
+
+ handleChange(msgId) {
+ if (!this.state.modifiedMessages.includes(msgId)) {
+ this.setState(prevState => ({
+ modifiedMessages: prevState.modifiedMessages.concat(msgId)
+ }));
+ }
+ }
+
+ renderMessageItem(msg) {
+ const isBlockedByGroup = this.state.groups.filter(group => msg.groups.includes(group.id)).some(group => !group.enabled);
+ const msgProvider = this.state.providers.find(provider => provider.id === msg.provider) || {};
+ const isProviderExcluded = msgProvider.exclude && msgProvider.exclude.includes(msg.id);
+ const isMessageBlocked = this.state.messageBlockList.includes(msg.id) || this.state.messageBlockList.includes(msg.campaign);
+ const isBlocked = isMessageBlocked || isBlockedByGroup || isProviderExcluded;
+ const impressions = this.state.messageImpressions[msg.id] ? this.state.messageImpressions[msg.id].length : 0;
+ const isCollapsed = this.state.collapsedMessages.includes(msg.id);
+ const isModified = this.state.modifiedMessages.includes(msg.id);
+ let itemClassName = "message-item";
+
+ if (isBlocked) {
+ itemClassName += " blocked";
+ }
+
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("tr", {
+ className: itemClassName,
+ key: `${msg.id}-${msg.provider}`
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", {
+ className: "message-id"
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("span", null, msg.id, " ", react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("br", null))), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(ToggleMessageJSON, {
+ msgId: `${msg.id}`,
+ toggleJSON: this.toggleJSON,
+ isCollapsed: isCollapsed
+ })), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", {
+ className: "button-column"
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("button", {
+ className: `button ${isBlocked ? "" : " primary"}`,
+ onClick: isBlocked ? this.handleUnblock(msg) : this.handleBlock(msg)
+ }, isBlocked ? "Unblock" : "Block"), // eslint-disable-next-line no-nested-ternary
+ isBlocked ? null : isModified ? react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("button", {
+ className: "button restore" // eslint-disable-next-line react/jsx-no-bind
+ ,
+ onClick: e => this.resetJSON(msg)
+ }, "Reset") : react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("button", {
+ className: "button show",
+ onClick: this.handleOverride(msg.id)
+ }, "Show"), isBlocked ? null : react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("button", {
+ className: "button modify" // eslint-disable-next-line react/jsx-no-bind
+ ,
+ onClick: e => this.modifyJson(msg)
+ }, "Modify"), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("br", null), "(", impressions, " impressions)"), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", {
+ className: "message-summary"
+ }, isBlocked && react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("tr", null, "Block reason:", isBlockedByGroup && " Blocked by group", isProviderExcluded && " Excluded by provider", isMessageBlocked && " Message blocked"), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("pre", {
+ className: isCollapsed ? "collapsed" : "expanded"
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("textarea", {
+ id: `${msg.id}-textarea`,
+ name: msg.id,
+ className: "general-textarea",
+ disabled: isBlocked // eslint-disable-next-line react/jsx-no-bind
+ ,
+ onChange: e => this.handleChange(msg.id)
+ }, JSON.stringify(msg, null, 2))))));
+ }
+
+ restoreWNMessageState() {
+ // check the page for checked boxes, and reset the state of WNMessages based on that.
+ let tempState = [];
+ let messageCheckboxes = document.querySelectorAll('input[type="checkbox"]'); // put the JSON of all the checked checkboxes in the array
+
+ for (const checkbox of messageCheckboxes) {
+ let trimmedId = checkbox.id.replace(" checkbox", "");
+ let msg = document.getElementById(`${trimmedId}-textarea`).value;
+
+ if (checkbox.checked) {
+ tempState.push(msg);
+ }
+ }
+
+ this.setState({
+ WNMessages: tempState
+ });
+ }
+
+ modifyJson(content) {
+ const message = JSON.parse(document.getElementById(`${content.id}-textarea`).value);
+ return _asrouter_asrouter_utils__WEBPACK_IMPORTED_MODULE_1__["ASRouterUtils"].modifyMessageJson(message).then(state => {
+ this.setStateFromParent(state);
+ this.props.notifyContent({
+ message: state.message
+ });
+ });
+ }
+
+ renderWNMessageItem(msg) {
+ const isBlocked = this.state.messageBlockList.includes(msg.id) || this.state.messageBlockList.includes(msg.campaign);
+ const impressions = this.state.messageImpressions[msg.id] ? this.state.messageImpressions[msg.id].length : 0;
+ const isCollapsed = this.state.collapsedMessages.includes(msg.id);
+ let itemClassName = "message-item";
+
+ if (isBlocked) {
+ itemClassName += " blocked";
+ }
+
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("tr", {
+ className: itemClassName,
+ key: `${msg.id}-${msg.provider}`
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", {
+ className: "message-id"
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("span", null, msg.id, " ", react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("br", null), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("br", null), "(", impressions, " impressions)")), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(ToggleMessageJSON, {
+ msgId: `${msg.id}`,
+ toggleJSON: this.toggleJSON,
+ isCollapsed: isCollapsed
+ })), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("input", {
+ type: "checkbox",
+ id: `${msg.id} checkbox`,
+ name: `${msg.id} checkbox`
+ })), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", {
+ className: `message-summary`
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("pre", {
+ className: isCollapsed ? "collapsed" : "expanded"
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("textarea", {
+ id: `${msg.id}-textarea`,
+ className: "wnp-textarea",
+ name: msg.id
+ }, JSON.stringify(msg, null, 2)))));
+ }
+
+ toggleAllMessages(messagesToShow) {
+ if (this.state.collapsedMessages.length) {
+ this.setState({
+ collapsedMessages: []
+ });
+ } else {
+ Array.prototype.forEach.call(messagesToShow, msg => {
+ this.setState(prevState => ({
+ collapsedMessages: prevState.collapsedMessages.concat(msg.id)
+ }));
+ });
+ }
+ }
+
+ renderMessages() {
+ if (!this.state.messages) {
+ return null;
+ }
+
+ const messagesToShow = this.state.messageFilter === "all" ? this.state.messages : this.state.messages.filter(message => message.provider === this.state.messageFilter);
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("div", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("button", {
+ className: "ASRouterButton slim" // eslint-disable-next-line react/jsx-no-bind
+ ,
+ onClick: e => this.toggleAllMessages(messagesToShow)
+ }, "Collapse/Expand All"), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("p", {
+ className: "helpLink"
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("span", {
+ className: "icon icon-small-spacer icon-info"
+ }), " ", react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("span", null, "To modify a message, change the JSON and click 'Modify' to see your changes. Click 'Reset' to restore the JSON to the original.")), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("table", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("tbody", null, messagesToShow.map(msg => this.renderMessageItem(msg)))));
+ }
+
+ renderMessagesByGroup() {
+ if (!this.state.messages) {
+ return null;
+ }
+
+ const messagesToShow = this.state.messageGroupsFilter === "all" ? this.state.messages.filter(m => m.groups.length) : this.state.messages.filter(message => message.groups.includes(this.state.messageGroupsFilter));
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("table", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("tbody", null, messagesToShow.map(msg => this.renderMessageItem(msg))));
+ }
+
+ renderWNMessages() {
+ if (!this.state.messages) {
+ return null;
+ }
+
+ const messagesToShow = this.state.messages.filter(message => message.provider === "whats-new-panel" && message.content.body);
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("table", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("tbody", null, messagesToShow.map(msg => this.renderWNMessageItem(msg))));
+ }
+
+ renderMessageFilter() {
+ if (!this.state.providers) {
+ return null;
+ }
+
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("p", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("button", {
+ className: "unblock-all ASRouterButton test-only",
+ onClick: this.unblockAll
+ }, "Unblock All Snippets"), "Show messages from ", react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("select", {
+ value: this.state.messageFilter,
+ onChange: this.onChangeMessageFilter
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("option", {
+ value: "all"
+ }, "all providers"), this.state.providers.map(provider => react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("option", {
+ key: provider.id,
+ value: provider.id
+ }, provider.id))), this.state.messageFilter !== "all" && !this.state.messageFilter.includes("_local_testing") ? react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("button", {
+ className: "button messages-reset",
+ onClick: this.handleClearAllImpressionsByProvider
+ }, "Reset All") : null);
+ }
+
+ renderMessageGroupsFilter() {
+ if (!this.state.groups) {
+ return null;
+ }
+
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("p", null, "Show messages from ", react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("select", {
+ value: this.state.messageGroupsFilter,
+ onChange: this.onChangeMessageGroupsFilter
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("option", {
+ value: "all"
+ }, "all groups"), this.state.groups.map(group => react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("option", {
+ key: group.id,
+ value: group.id
+ }, group.id))));
+ }
+
+ renderTableHead() {
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("thead", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("tr", {
+ className: "message-item"
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", {
+ className: "min"
+ }), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", {
+ className: "min"
+ }, "Provider ID"), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, "Source"), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", {
+ className: "min"
+ }, "Cohort"), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", {
+ className: "min"
+ }, "Last Updated")));
+ }
+
+ renderProviders() {
+ const providersConfig = this.state.providerPrefs;
+ const providerInfo = this.state.providers;
+ const userPrefInfo = this.state.userPrefs;
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("table", null, this.renderTableHead(), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("tbody", null, providersConfig.map((provider, i) => {
+ const isTestProvider = provider.id.includes("_local_testing");
+ const info = providerInfo.find(p => p.id === provider.id) || {};
+ const isUserEnabled = provider.id in userPrefInfo ? userPrefInfo[provider.id] : true;
+ const isSystemEnabled = isTestProvider || provider.enabled;
+ let label = "local";
+
+ if (provider.type === "remote") {
+ label = react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("span", null, "endpoint (", react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("a", {
+ className: "providerUrl",
+ target: "_blank",
+ href: info.url,
+ rel: "noopener noreferrer"
+ }, info.url), ")");
+ } else if (provider.type === "remote-settings") {
+ label = `remote settings (${provider.bucket})`;
+ } else if (provider.type === "remote-experiments") {
+ label = react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("span", null, "remote settings (", react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("a", {
+ className: "providerUrl",
+ target: "_blank",
+ href: "https://firefox.settings.services.mozilla.com/v1/buckets/main/collections/nimbus-desktop-experiments/records",
+ rel: "noopener noreferrer"
+ }, "nimbus-desktop-experiments"), ")");
+ }
+
+ let reasonsDisabled = [];
+
+ if (!isSystemEnabled) {
+ reasonsDisabled.push("system pref");
+ }
+
+ if (!isUserEnabled) {
+ reasonsDisabled.push("user pref");
+ }
+
+ if (reasonsDisabled.length) {
+ label = `disabled via ${reasonsDisabled.join(", ")}`;
+ }
+
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("tr", {
+ className: "message-item",
+ key: i
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, isTestProvider ? react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("input", {
+ type: "checkbox",
+ disabled: true,
+ readOnly: true,
+ checked: true
+ }) : react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("input", {
+ type: "checkbox",
+ "data-provider": provider.id,
+ checked: isUserEnabled && isSystemEnabled,
+ onChange: this.handleEnabledToggle
+ })), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, provider.id), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("span", {
+ className: `sourceLabel${isUserEnabled && isSystemEnabled ? "" : " isDisabled"}`
+ }, label)), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, provider.cohort), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", {
+ style: {
+ whiteSpace: "nowrap"
+ }
+ }, info.lastUpdated ? new Date(info.lastUpdated).toLocaleString() : ""));
+ })));
+ }
+
+ renderTargetingParameters() {
+ // There was no error and the result is truthy
+ const success = this.state.evaluationStatus.success && !!this.state.evaluationStatus.result;
+ const result = JSON.stringify(this.state.evaluationStatus.result, null, 2) || "(Empty result)";
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("table", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("tbody", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("h2", null, "Evaluate JEXL expression"))), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("p", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("textarea", {
+ ref: "expressionInput",
+ rows: "10",
+ cols: "60",
+ placeholder: "Evaluate JEXL expressions and mock parameters by changing their values below"
+ })), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("p", null, "Status:", " ", react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("span", {
+ ref: "evaluationStatus"
+ }, success ? "✅" : "❌", ", Result: ", result))), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("button", {
+ className: "ASRouterButton secondary",
+ onClick: this.handleExpressionEval
+ }, "Evaluate"))), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("h2", null, "Modify targeting parameters"))), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("button", {
+ className: "ASRouterButton secondary",
+ onClick: this.onCopyTargetingParams,
+ disabled: this.state.copiedToClipboard
+ }, this.state.copiedToClipboard ? "Parameters copied!" : "Copy parameters"))), this.state.stringTargetingParameters && Object.keys(this.state.stringTargetingParameters).map((param, i) => {
+ const value = this.state.stringTargetingParameters[param];
+ const errorState = this.state.targetingParametersError && this.state.targetingParametersError.id === param;
+ const className = errorState ? "errorState" : "";
+ const inputComp = (value && value.length) > 30 ? react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("textarea", {
+ name: param,
+ className: className,
+ value: value,
+ rows: "10",
+ cols: "60",
+ onChange: this.onChangeTargetingParameters
+ }) : react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("input", {
+ name: param,
+ className: className,
+ value: value,
+ onChange: this.onChangeTargetingParameters
+ });
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("tr", {
+ key: i
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, param), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, inputComp));
+ })));
+ }
+
+ onChangeAttributionParameters(event) {
+ const {
+ name,
+ value
+ } = event.target;
+ this.setState(({
+ attributionParameters
+ }) => {
+ const updatedParameters = { ...attributionParameters
+ };
+ updatedParameters[name] = value;
+ return {
+ attributionParameters: updatedParameters
+ };
+ });
+ }
+
+ setAttribution(e) {
+ _asrouter_asrouter_utils__WEBPACK_IMPORTED_MODULE_1__["ASRouterUtils"].sendMessage({
+ type: "FORCE_ATTRIBUTION",
+ data: this.state.attributionParameters
+ }).then(this.setStateFromParent);
+ }
+
+ _getGroupImpressionsCount(id, frequency) {
+ if (frequency) {
+ return this.state.groupImpressions[id] ? this.state.groupImpressions[id].length : 0;
+ }
+
+ return "n/a";
+ }
+
+ renderDiscoveryStream() {
+ const {
+ config
+ } = this.props.DiscoveryStream;
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("div", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("table", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("tbody", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("tr", {
+ className: "message-item"
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", {
+ className: "min"
+ }, "Enabled"), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, config.enabled ? "yes" : "no")), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("tr", {
+ className: "message-item"
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", {
+ className: "min"
+ }, "Endpoint"), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, config.endpoint || "(empty)")))));
+ }
+
+ renderAttributionParamers() {
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("div", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("h2", null, " Attribution Parameters "), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("p", null, " ", "This forces the browser to set some attribution parameters, useful for testing the Return To AMO feature. Clicking on 'Force Attribution', with the default values in each field, will demo the Return To AMO flow with the addon called 'Iridium for Youtube'. If you wish to try different attribution parameters, enter them in the text boxes. If you wish to try a different addon with the Return To AMO flow, make sure the 'content' text box has the addon GUID, then click 'Force Attribution'. Clicking on 'Force Attribution' with blank text boxes reset attribution data."), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("table", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("b", null, " Source ")), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, " ", react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("input", {
+ type: "text",
+ name: "source",
+ placeholder: "addons.mozilla.org",
+ value: this.state.attributionParameters.source,
+ onChange: this.onChangeAttributionParameters
+ }), " ")), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("b", null, " Medium ")), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, " ", react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("input", {
+ type: "text",
+ name: "medium",
+ placeholder: "referral",
+ value: this.state.attributionParameters.medium,
+ onChange: this.onChangeAttributionParameters
+ }), " ")), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("b", null, " Campaign ")), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, " ", react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("input", {
+ type: "text",
+ name: "campaign",
+ placeholder: "non-fx-button",
+ value: this.state.attributionParameters.campaign,
+ onChange: this.onChangeAttributionParameters
+ }), " ")), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("b", null, " Content ")), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, " ", react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("input", {
+ type: "text",
+ name: "content",
+ placeholder: "iridium@particlecore.github.io",
+ value: this.state.attributionParameters.content,
+ onChange: this.onChangeAttributionParameters
+ }), " ")), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("b", null, " Experiment ")), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, " ", react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("input", {
+ type: "text",
+ name: "experiment",
+ placeholder: "ua-onboarding",
+ value: this.state.attributionParameters.experiment,
+ onChange: this.onChangeAttributionParameters
+ }), " ")), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("b", null, " Variation ")), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, " ", react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("input", {
+ type: "text",
+ name: "variation",
+ placeholder: "chrome",
+ value: this.state.attributionParameters.variation,
+ onChange: this.onChangeAttributionParameters
+ }), " ")), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("b", null, " User Agent ")), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, " ", react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("input", {
+ type: "text",
+ name: "ua",
+ placeholder: "Google Chrome 123",
+ value: this.state.attributionParameters.ua,
+ onChange: this.onChangeAttributionParameters
+ }), " ")), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("b", null, " Download Token ")), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, " ", react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("input", {
+ type: "text",
+ name: "dltoken",
+ placeholder: "00000000-0000-0000-0000-000000000000",
+ value: this.state.attributionParameters.dltoken,
+ onChange: this.onChangeAttributionParameters
+ }), " ")), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, " ", react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("button", {
+ className: "ASRouterButton primary button",
+ onClick: this.setAttribution
+ }, " ", "Force Attribution", " "), " "))));
+ }
+
+ renderErrorMessage({
+ id,
+ errors
+ }) {
+ const providerId = react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", {
+ rowSpan: errors.length
+ }, id); // .reverse() so that the last error (most recent) is first
+
+ return errors.map(({
+ error,
+ timestamp
+ }, cellKey) => react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("tr", {
+ key: cellKey
+ }, cellKey === errors.length - 1 ? providerId : null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, error.message), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, relativeTime(timestamp)))).reverse();
+ }
+
+ renderErrors() {
+ const providersWithErrors = this.state.providers && this.state.providers.filter(p => p.errors && p.errors.length);
+
+ if (providersWithErrors && providersWithErrors.length) {
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("table", {
+ className: "errorReporting"
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("thead", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("tr", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("th", null, "Provider ID"), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("th", null, "Message"), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("th", null, "Timestamp"))), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("tbody", null, providersWithErrors.map(this.renderErrorMessage)));
+ }
+
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("p", null, "No errors");
+ }
+
+ renderWNPTests() {
+ if (!this.state.messages) {
+ return null;
+ }
+
+ let messagesToShow = this.state.messages.filter(message => message.provider === "whats-new-panel");
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("div", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("p", {
+ className: "helpLink"
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("span", {
+ className: "icon icon-small-spacer icon-info"
+ }), " ", react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("span", null, "To correctly render selected messages, click 'Open What's New Panel', select the messages you want to see, and click 'Render Selected Messages'.", react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("br", null), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("br", null), "To modify a message, select it, modify the JSON and click 'Render Selected Messages' again to see your changes.", react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("br", null), "Click 'Reset Panel' to close the panel and reset all JSON to its original state.")), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("div", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("button", {
+ className: "ASRouterButton primary button",
+ onClick: this.handleForceWNP
+ }, "Open What's New Panel"), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("button", {
+ className: "ASRouterButton secondary button",
+ onClick: this.handleUpdateWNMessages
+ }, "Render Selected Messages"), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("button", {
+ className: "ASRouterButton secondary button",
+ onClick: this.resetPanel
+ }, "Reset Panel"), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("h2", null, "Messages"), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("button", {
+ className: "ASRouterButton slim button" // eslint-disable-next-line react/jsx-no-bind
+ ,
+ onClick: e => this.toggleAllMessages(messagesToShow)
+ }, "Collapse/Expand All"), this.renderWNMessages()));
+ }
+
+ getSection() {
+ const [section] = this.props.location.routes;
+
+ switch (section) {
+ case "wnpanel":
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_3___default.a.Fragment, null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("h2", null, "What's New Panel"), this.renderWNPTests());
+
+ case "targeting":
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_3___default.a.Fragment, null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("h2", null, "Targeting Utilities"), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("button", {
+ className: "button",
+ onClick: this.expireCache
+ }, "Expire Cache"), " ", "(This expires the cache in ASR Targeting for bookmarks and top sites)", this.renderTargetingParameters(), this.renderAttributionParamers());
+
+ case "groups":
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_3___default.a.Fragment, null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("h2", null, "Message Groups"), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("button", {
+ className: "button",
+ onClick: this.resetGroups
+ }, "Reset group impressions"), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("table", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("thead", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("tr", {
+ className: "message-item"
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, "Enabled"), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, "Impressions count"), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, "Custom frequency"), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, "User preferences"))), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("tbody", null, this.state.groups && this.state.groups.map(({
+ id,
+ enabled,
+ frequency,
+ userPreferences = []
+ }, index) => react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(Row, {
+ key: id
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(TogglePrefCheckbox, {
+ checked: enabled,
+ pref: id,
+ disabled: true
+ })), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, this._getGroupImpressionsCount(id, frequency)), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, JSON.stringify(frequency, null, 2)), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("td", null, userPreferences.join(", ")))))), this.renderMessageGroupsFilter(), this.renderMessagesByGroup());
+
+ case "ds":
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_3___default.a.Fragment, null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("h2", null, "Discovery Stream"), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(DiscoveryStreamAdmin, {
+ state: {
+ DiscoveryStream: this.props.DiscoveryStream,
+ Personalization: this.props.Personalization
+ },
+ otherPrefs: this.props.Prefs.values,
+ dispatch: this.props.dispatch
+ }));
+
+ case "errors":
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_3___default.a.Fragment, null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("h2", null, "ASRouter Errors"), this.renderErrors());
+
+ default:
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_3___default.a.Fragment, null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("h2", null, "Message Providers", " ", react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("button", {
+ title: "Restore all provider settings that ship with Firefox",
+ className: "button",
+ onClick: this.resetPref
+ }, "Restore default prefs")), this.state.providers ? this.renderProviders() : null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("h2", null, "Messages"), this.renderMessageFilter(), this.renderMessages());
+ }
+ }
+
+ render() {
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("div", {
+ className: `asrouter-admin ${this.props.collapsed ? "collapsed" : "expanded"}`
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("aside", {
+ className: "sidebar"
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("ul", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("li", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("a", {
+ href: "#devtools"
+ }, "General")), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("li", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("a", {
+ href: "#devtools-wnpanel"
+ }, "What's New Panel")), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("li", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("a", {
+ href: "#devtools-targeting"
+ }, "Targeting")), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("li", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("a", {
+ href: "#devtools-groups"
+ }, "Message Groups")), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("li", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("a", {
+ href: "#devtools-ds"
+ }, "Discovery Stream")), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("li", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("a", {
+ href: "#devtools-errors"
+ }, "Errors")))), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("main", {
+ className: "main-panel"
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("h1", null, "AS Router Admin"), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("p", {
+ className: "helpLink"
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("span", {
+ className: "icon icon-small-spacer icon-info"
+ }), " ", react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("span", null, "Need help using these tools? Check out our", " ", react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("a", {
+ target: "blank",
+ href: "https://github.com/mozilla/activity-stream/blob/master/content-src/asrouter/docs/debugging-docs.md"
+ }, "documentation"))), this.getSection()));
+ }
+
+}
+class CollapseToggle extends react__WEBPACK_IMPORTED_MODULE_3___default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onCollapseToggle = this.onCollapseToggle.bind(this);
+ this.state = {
+ collapsed: false
+ };
+ }
+
+ get renderAdmin() {
+ const {
+ props
+ } = this;
+ return props.location.hash && (props.location.hash.startsWith("#asrouter") || props.location.hash.startsWith("#devtools"));
+ }
+
+ onCollapseToggle(e) {
+ e.preventDefault();
+ this.setState(state => ({
+ collapsed: !state.collapsed
+ }));
+ }
+
+ setBodyClass() {
+ if (this.renderAdmin && !this.state.collapsed) {
+ global.document.body.classList.add("no-scroll");
+ } else {
+ global.document.body.classList.remove("no-scroll");
+ }
+ }
+
+ componentDidMount() {
+ this.setBodyClass();
+ }
+
+ componentDidUpdate() {
+ this.setBodyClass();
+ }
+
+ componentWillUnmount() {
+ global.document.body.classList.remove("no-scroll");
+ _asrouter_asrouter_utils__WEBPACK_IMPORTED_MODULE_1__["ASRouterUtils"].removeListener(this.onMessageFromParent);
+ }
+
+ render() {
+ const {
+ props
+ } = this;
+ const {
+ renderAdmin
+ } = this;
+ const isCollapsed = this.state.collapsed || !renderAdmin;
+ const label = `${isCollapsed ? "Expand" : "Collapse"} devtools`;
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_3___default.a.Fragment, null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("a", {
+ href: "#devtools",
+ title: label,
+ "aria-label": label,
+ className: `asrouter-toggle ${isCollapsed ? "collapsed" : "expanded"}`,
+ onClick: this.renderAdmin ? this.onCollapseToggle : null
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("span", {
+ className: "icon icon-devtools"
+ })), renderAdmin ? react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(ASRouterAdminInner, _extends({}, props, {
+ collapsed: this.state.collapsed
+ })) : null);
+ }
+
+}
+
+const _ASRouterAdmin = props => react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(_SimpleHashRouter__WEBPACK_IMPORTED_MODULE_4__["SimpleHashRouter"], null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(CollapseToggle, props));
+
+const ASRouterAdmin = Object(react_redux__WEBPACK_IMPORTED_MODULE_2__["connect"])(state => ({
+ Sections: state.Sections,
+ DiscoveryStream: state.DiscoveryStream,
+ Personalization: state.Personalization,
+ Prefs: state.Prefs
+}))(_ASRouterAdmin);
+/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(3)))
+
+/***/ }),
+/* 5 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* WEBPACK VAR INJECTION */(function(global) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ASRouterUtils", function() { return ASRouterUtils; });
+/* harmony import */ var common_ActorConstants_jsm__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6);
+/* harmony import */ var common_Actions_jsm__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+const ASRouterUtils = {
+ addListener(listener) {
+ if (global.ASRouterAddParentListener) {
+ global.ASRouterAddParentListener(listener);
+ }
+ },
+
+ removeListener(listener) {
+ if (global.ASRouterRemoveParentListener) {
+ global.ASRouterRemoveParentListener(listener);
+ }
+ },
+
+ sendMessage(action) {
+ if (global.ASRouterMessage) {
+ return global.ASRouterMessage(action);
+ }
+
+ throw new Error(`Unexpected call:\n${JSON.stringify(action, null, 3)}`);
+ },
+
+ blockById(id, options) {
+ return ASRouterUtils.sendMessage({
+ type: common_ActorConstants_jsm__WEBPACK_IMPORTED_MODULE_0__["MESSAGE_TYPE_HASH"].BLOCK_MESSAGE_BY_ID,
+ data: {
+ id,
+ ...options
+ }
+ });
+ },
+
+ modifyMessageJson(content) {
+ return ASRouterUtils.sendMessage({
+ type: common_ActorConstants_jsm__WEBPACK_IMPORTED_MODULE_0__["MESSAGE_TYPE_HASH"].MODIFY_MESSAGE_JSON,
+ data: {
+ content
+ }
+ });
+ },
+
+ executeAction(button_action) {
+ return ASRouterUtils.sendMessage({
+ type: common_ActorConstants_jsm__WEBPACK_IMPORTED_MODULE_0__["MESSAGE_TYPE_HASH"].USER_ACTION,
+ data: button_action
+ });
+ },
+
+ unblockById(id) {
+ return ASRouterUtils.sendMessage({
+ type: common_ActorConstants_jsm__WEBPACK_IMPORTED_MODULE_0__["MESSAGE_TYPE_HASH"].UNBLOCK_MESSAGE_BY_ID,
+ data: {
+ id
+ }
+ });
+ },
+
+ blockBundle(bundle) {
+ return ASRouterUtils.sendMessage({
+ type: common_ActorConstants_jsm__WEBPACK_IMPORTED_MODULE_0__["MESSAGE_TYPE_HASH"].BLOCK_BUNDLE,
+ data: {
+ bundle
+ }
+ });
+ },
+
+ unblockBundle(bundle) {
+ return ASRouterUtils.sendMessage({
+ type: common_ActorConstants_jsm__WEBPACK_IMPORTED_MODULE_0__["MESSAGE_TYPE_HASH"].UNBLOCK_BUNDLE,
+ data: {
+ bundle
+ }
+ });
+ },
+
+ overrideMessage(id) {
+ return ASRouterUtils.sendMessage({
+ type: common_ActorConstants_jsm__WEBPACK_IMPORTED_MODULE_0__["MESSAGE_TYPE_HASH"].OVERRIDE_MESSAGE,
+ data: {
+ id
+ }
+ });
+ },
+
+ sendTelemetry(ping) {
+ return ASRouterUtils.sendMessage(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_1__["actionCreators"].ASRouterUserEvent(ping));
+ },
+
+ getPreviewEndpoint() {
+ if (global.document && global.document.location && global.document.location.href.includes("endpoint")) {
+ const params = new URLSearchParams(global.document.location.href.slice(global.document.location.href.indexOf("endpoint")));
+
+ try {
+ const endpoint = new URL(params.get("endpoint"));
+ return {
+ url: endpoint.href,
+ snippetId: params.get("snippetId"),
+ theme: this.getPreviewTheme(),
+ dir: this.getPreviewDir()
+ };
+ } catch (e) {}
+ }
+
+ return null;
+ },
+
+ getPreviewTheme() {
+ return new URLSearchParams(global.document.location.href.slice(global.document.location.href.indexOf("theme"))).get("theme");
+ },
+
+ getPreviewDir() {
+ return new URLSearchParams(global.document.location.href.slice(global.document.location.href.indexOf("dir"))).get("dir");
+ }
+
+};
+/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(3)))
+
+/***/ }),
+/* 6 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MESSAGE_TYPE_LIST", function() { return MESSAGE_TYPE_LIST; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MESSAGE_TYPE_HASH", function() { return MESSAGE_TYPE_HASH; });
+/* vim: set ts=2 sw=2 sts=2 et tw=80: */
+
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+const MESSAGE_TYPE_LIST = ["BLOCK_MESSAGE_BY_ID", "USER_ACTION", "IMPRESSION", "TRIGGER", "NEWTAB_MESSAGE_REQUEST", "DOORHANGER_TELEMETRY", "TOOLBAR_BADGE_TELEMETRY", "TOOLBAR_PANEL_TELEMETRY", "MOMENTS_PAGE_TELEMETRY", "INFOBAR_TELEMETRY", "AS_ROUTER_TELEMETRY_USER_EVENT", // Admin types
+"ADMIN_CONNECT_STATE", "UNBLOCK_MESSAGE_BY_ID", "UNBLOCK_ALL", "BLOCK_BUNDLE", "UNBLOCK_BUNDLE", "DISABLE_PROVIDER", "ENABLE_PROVIDER", "EVALUATE_JEXL_EXPRESSION", "EXPIRE_QUERY_CACHE", "FORCE_ATTRIBUTION", "FORCE_WHATSNEW_PANEL", "CLOSE_WHATSNEW_PANEL", "OVERRIDE_MESSAGE", "MODIFY_MESSAGE_JSON", "RESET_PROVIDER_PREF", "SET_PROVIDER_USER_PREF", "RESET_GROUPS_STATE"];
+const MESSAGE_TYPE_HASH = MESSAGE_TYPE_LIST.reduce((hash, value) => {
+ hash[value] = value;
+ return hash;
+}, {});
+
+/***/ }),
+/* 7 */
+/***/ (function(module, exports) {
+
+module.exports = ReactRedux;
+
+/***/ }),
+/* 8 */
+/***/ (function(module, exports) {
+
+module.exports = React;
+
+/***/ }),
+/* 9 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* WEBPACK VAR INJECTION */(function(global) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SimpleHashRouter", function() { return SimpleHashRouter; });
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+class SimpleHashRouter extends react__WEBPACK_IMPORTED_MODULE_0___default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onHashChange = this.onHashChange.bind(this);
+ this.state = {
+ hash: global.location.hash
+ };
+ }
+
+ onHashChange() {
+ this.setState({
+ hash: global.location.hash
+ });
+ }
+
+ componentWillMount() {
+ global.addEventListener("hashchange", this.onHashChange);
+ }
+
+ componentWillUnmount() {
+ global.removeEventListener("hashchange", this.onHashChange);
+ }
+
+ render() {
+ const [, ...routes] = this.state.hash.split("-");
+ return react__WEBPACK_IMPORTED_MODULE_0___default.a.cloneElement(this.props.children, {
+ location: {
+ hash: this.state.hash,
+ routes
+ }
+ });
+ }
+
+}
+/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(3)))
+
+/***/ }),
+/* 10 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* WEBPACK VAR INJECTION */(function(global) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ASRouterUISurface", function() { return ASRouterUISurface; });
+/* harmony import */ var common_ActorConstants_jsm__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6);
+/* harmony import */ var common_Actions_jsm__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1);
+/* harmony import */ var _asrouter_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(5);
+/* harmony import */ var _rich_text_strings__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(70);
+/* harmony import */ var _components_ImpressionsWrapper_ImpressionsWrapper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(11);
+/* harmony import */ var fluent_react__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(68);
+/* harmony import */ var content_src_lib_constants__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(13);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_7__);
+/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(14);
+/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(react_dom__WEBPACK_IMPORTED_MODULE_8__);
+/* harmony import */ var _templates_template_manifest__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(69);
+function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
+
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+
+
+
+
+
+
+
+
+const TEMPLATES_BELOW_SEARCH = ["simple_below_search_snippet"]; // Note: nextProps/prevProps refer to props passed to <ImpressionsWrapper />, not <ASRouterUISurface />
+
+function shouldSendImpressionOnUpdate(nextProps, prevProps) {
+ return nextProps.message.id && (!prevProps.message || prevProps.message.id !== nextProps.message.id);
+}
+
+class ASRouterUISurface extends react__WEBPACK_IMPORTED_MODULE_7___default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.sendClick = this.sendClick.bind(this);
+ this.sendImpression = this.sendImpression.bind(this);
+ this.sendUserActionTelemetry = this.sendUserActionTelemetry.bind(this);
+ this.onUserAction = this.onUserAction.bind(this);
+ this.fetchFlowParams = this.fetchFlowParams.bind(this);
+ this.onBlockSelected = this.onBlockSelected.bind(this);
+ this.onBlockById = this.onBlockById.bind(this);
+ this.onDismiss = this.onDismiss.bind(this);
+ this.onMessageFromParent = this.onMessageFromParent.bind(this);
+ this.state = {
+ message: {}
+ };
+
+ if (props.document) {
+ this.footerPortal = props.document.getElementById("footer-asrouter-container");
+ }
+ }
+
+ async fetchFlowParams(params = {}) {
+ let result = {};
+ const {
+ fxaEndpoint
+ } = this.props;
+
+ if (!fxaEndpoint) {
+ const err = "Tried to fetch flow params before fxaEndpoint pref was ready";
+ console.error(err); // eslint-disable-line no-console
+ }
+
+ try {
+ const urlObj = new URL(fxaEndpoint);
+ urlObj.pathname = "metrics-flow";
+ Object.keys(params).forEach(key => {
+ urlObj.searchParams.append(key, params[key]);
+ });
+ const response = await fetch(urlObj.toString(), {
+ credentials: "omit"
+ });
+
+ if (response.status === 200) {
+ const {
+ deviceId,
+ flowId,
+ flowBeginTime
+ } = await response.json();
+ result = {
+ deviceId,
+ flowId,
+ flowBeginTime
+ };
+ } else {
+ console.error("Non-200 response", response); // eslint-disable-line no-console
+ }
+ } catch (error) {
+ console.error(error); // eslint-disable-line no-console
+ }
+
+ return result;
+ }
+
+ sendUserActionTelemetry(extraProps = {}) {
+ const {
+ message
+ } = this.state;
+ const eventType = `${message.provider}_user_event`;
+ const source = extraProps.id;
+ delete extraProps.id;
+ _asrouter_utils__WEBPACK_IMPORTED_MODULE_2__["ASRouterUtils"].sendTelemetry({
+ source,
+ message_id: message.id,
+ action: eventType,
+ ...extraProps
+ });
+ }
+
+ sendImpression(extraProps) {
+ if (this.state.message.provider === "preview") {
+ return Promise.resolve();
+ }
+
+ this.sendUserActionTelemetry({
+ event: "IMPRESSION",
+ ...extraProps
+ });
+ return _asrouter_utils__WEBPACK_IMPORTED_MODULE_2__["ASRouterUtils"].sendMessage({
+ type: common_ActorConstants_jsm__WEBPACK_IMPORTED_MODULE_0__["MESSAGE_TYPE_HASH"].IMPRESSION,
+ data: this.state.message
+ });
+ } // If link has a `metric` data attribute send it as part of the `event_context`
+ // telemetry field which can have arbitrary values.
+ // Used for router messages with links as part of the content.
+
+
+ sendClick(event) {
+ const {
+ dataset
+ } = event.target;
+ const metric = {
+ event_context: dataset.metric,
+ // Used for the `source` of the event. Needed to differentiate
+ // from other snippet or onboarding events that may occur.
+ id: "NEWTAB_FOOTER_BAR_CONTENT"
+ };
+ const {
+ entrypoint_name,
+ entrypoint_value
+ } = dataset; // Assign the snippet referral for the action
+
+ const entrypoint = entrypoint_name ? new URLSearchParams([[entrypoint_name, entrypoint_value]]).toString() : entrypoint_value;
+ const action = {
+ type: dataset.action,
+ data: {
+ args: dataset.args,
+ ...(entrypoint && {
+ entrypoint
+ })
+ }
+ };
+
+ if (action.type) {
+ _asrouter_utils__WEBPACK_IMPORTED_MODULE_2__["ASRouterUtils"].executeAction(action);
+ }
+
+ if (!this.state.message.content.do_not_autoblock && !dataset.do_not_autoblock) {
+ this.onBlockById(this.state.message.id);
+ }
+
+ if (this.state.message.provider !== "preview") {
+ this.sendUserActionTelemetry({
+ event: "CLICK_BUTTON",
+ ...metric
+ });
+ }
+ }
+
+ onBlockSelected(options) {
+ return this.onBlockById(this.state.message.id, options);
+ }
+
+ onBlockById(id, options) {
+ return _asrouter_utils__WEBPACK_IMPORTED_MODULE_2__["ASRouterUtils"].blockById(id, options).then(clearAll => {
+ if (clearAll) {
+ this.setState({
+ message: {}
+ });
+ }
+ });
+ }
+
+ onDismiss() {
+ this.clearMessage(this.state.message.id);
+ }
+
+ clearMessage(id) {
+ if (id === this.state.message.id) {
+ this.setState({
+ message: {}
+ });
+ }
+ }
+
+ clearProvider(id) {
+ if (this.state.message.provider === id) {
+ this.setState({
+ message: {}
+ });
+ }
+ }
+
+ onMessageFromParent({
+ type,
+ data
+ }) {
+ // These only exists due to onPrefChange events in ASRouter
+ switch (type) {
+ case "ClearMessages":
+ {
+ data.forEach(id => this.clearMessage(id));
+ break;
+ }
+
+ case "ClearProviders":
+ {
+ data.forEach(id => this.clearProvider(id));
+ break;
+ }
+
+ case "EnterSnippetsPreviewMode":
+ {
+ this.props.dispatch({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_1__["actionTypes"].SNIPPETS_PREVIEW_MODE
+ });
+ break;
+ }
+ }
+ }
+
+ requestMessage(endpoint) {
+ _asrouter_utils__WEBPACK_IMPORTED_MODULE_2__["ASRouterUtils"].sendMessage({
+ type: "NEWTAB_MESSAGE_REQUEST",
+ data: {
+ endpoint
+ }
+ }).then(state => this.setState(state));
+ }
+
+ componentWillMount() {
+ const endpoint = _asrouter_utils__WEBPACK_IMPORTED_MODULE_2__["ASRouterUtils"].getPreviewEndpoint();
+
+ if (endpoint && endpoint.theme === "dark") {
+ global.window.dispatchEvent(new CustomEvent("LightweightTheme:Set", {
+ detail: {
+ data: content_src_lib_constants__WEBPACK_IMPORTED_MODULE_6__["NEWTAB_DARK_THEME"]
+ }
+ }));
+ }
+
+ if (endpoint && endpoint.dir === "rtl") {
+ //Set `dir = rtl` on the HTML
+ this.props.document.dir = "rtl";
+ }
+
+ _asrouter_utils__WEBPACK_IMPORTED_MODULE_2__["ASRouterUtils"].addListener(this.onMessageFromParent);
+ this.requestMessage(endpoint);
+ }
+
+ componentWillUnmount() {
+ _asrouter_utils__WEBPACK_IMPORTED_MODULE_2__["ASRouterUtils"].removeListener(this.onMessageFromParent);
+ }
+
+ componentDidUpdate(prevProps) {
+ if (prevProps.adminContent && JSON.stringify(prevProps.adminContent) !== JSON.stringify(this.props.adminContent)) {
+ this.updateContent();
+ }
+ }
+
+ updateContent() {
+ this.setState({ ...this.props.adminContent
+ });
+ }
+
+ async getMonitorUrl({
+ url,
+ flowRequestParams = {}
+ }) {
+ const flowValues = await this.fetchFlowParams(flowRequestParams); // Note that flowParams are actually added dynamically on the page
+
+ const urlObj = new URL(url);
+ ["deviceId", "flowId", "flowBeginTime"].forEach(key => {
+ if (key in flowValues) {
+ urlObj.searchParams.append(key, flowValues[key]);
+ }
+ });
+ return urlObj.toString();
+ }
+
+ async onUserAction(action) {
+ switch (action.type) {
+ // This needs to be handled locally because its
+ case "ENABLE_FIREFOX_MONITOR":
+ const url = await this.getMonitorUrl(action.data.args);
+ _asrouter_utils__WEBPACK_IMPORTED_MODULE_2__["ASRouterUtils"].executeAction({
+ type: "OPEN_URL",
+ data: {
+ args: url
+ }
+ });
+ break;
+
+ default:
+ _asrouter_utils__WEBPACK_IMPORTED_MODULE_2__["ASRouterUtils"].executeAction(action);
+ }
+ }
+
+ renderSnippets() {
+ const {
+ message
+ } = this.state;
+
+ if (!_templates_template_manifest__WEBPACK_IMPORTED_MODULE_9__["SnippetsTemplates"][message.template]) {
+ return null;
+ }
+
+ const SnippetComponent = _templates_template_manifest__WEBPACK_IMPORTED_MODULE_9__["SnippetsTemplates"][message.template];
+ const {
+ content
+ } = this.state.message;
+ return react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement(_components_ImpressionsWrapper_ImpressionsWrapper__WEBPACK_IMPORTED_MODULE_4__["ImpressionsWrapper"], {
+ id: "NEWTAB_FOOTER_BAR",
+ message: this.state.message,
+ sendImpression: this.sendImpression,
+ shouldSendImpressionOnUpdate: shouldSendImpressionOnUpdate // This helps with testing
+ ,
+ document: this.props.document
+ }, react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement(fluent_react__WEBPACK_IMPORTED_MODULE_5__["LocalizationProvider"], {
+ bundles: Object(_rich_text_strings__WEBPACK_IMPORTED_MODULE_3__["generateBundles"])(content)
+ }, react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement(SnippetComponent, _extends({}, this.state.message, {
+ UISurface: "NEWTAB_FOOTER_BAR",
+ onBlock: this.onBlockSelected,
+ onDismiss: this.onDismiss,
+ onAction: this.onUserAction,
+ sendClick: this.sendClick,
+ sendUserActionTelemetry: this.sendUserActionTelemetry
+ }))));
+ }
+
+ renderPreviewBanner() {
+ if (this.state.message.provider !== "preview") {
+ return null;
+ }
+
+ return react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement("div", {
+ className: "snippets-preview-banner"
+ }, react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement("span", {
+ className: "icon icon-small-spacer icon-info"
+ }), react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement("span", null, "Preview Purposes Only"));
+ }
+
+ render() {
+ const {
+ message
+ } = this.state;
+
+ if (!message.id) {
+ return null;
+ }
+
+ const shouldRenderBelowSearch = TEMPLATES_BELOW_SEARCH.includes(message.template);
+ return shouldRenderBelowSearch ? // Render special below search snippets in place;
+ react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement("div", {
+ className: "below-search-snippet-wrapper"
+ }, this.renderSnippets()) : // For regular snippets etc. we should render everything in our footer
+ // container.
+ react_dom__WEBPACK_IMPORTED_MODULE_8___default.a.createPortal(react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_7___default.a.Fragment, null, this.renderPreviewBanner(), this.renderSnippets()), this.footerPortal);
+ }
+
+}
+ASRouterUISurface.defaultProps = {
+ document: global.document
+};
+/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(3)))
+
+/***/ }),
+/* 11 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* WEBPACK VAR INJECTION */(function(global) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VISIBLE", function() { return VISIBLE; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VISIBILITY_CHANGE_EVENT", function() { return VISIBILITY_CHANGE_EVENT; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ImpressionsWrapper", function() { return ImpressionsWrapper; });
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+const VISIBLE = "visible";
+const VISIBILITY_CHANGE_EVENT = "visibilitychange";
+/**
+ * Component wrapper used to send telemetry pings on every impression.
+ */
+
+class ImpressionsWrapper extends react__WEBPACK_IMPORTED_MODULE_0___default.a.PureComponent {
+ // This sends an event when a user sees a set of new content. If content
+ // changes while the page is hidden (i.e. preloaded or on a hidden tab),
+ // only send the event if the page becomes visible again.
+ sendImpressionOrAddListener() {
+ if (this.props.document.visibilityState === VISIBLE) {
+ this.props.sendImpression({
+ id: this.props.id
+ });
+ } else {
+ // We should only ever send the latest impression stats ping, so remove any
+ // older listeners.
+ if (this._onVisibilityChange) {
+ this.props.document.removeEventListener(VISIBILITY_CHANGE_EVENT, this._onVisibilityChange);
+ } // When the page becomes visible, send the impression stats ping if the section isn't collapsed.
+
+
+ this._onVisibilityChange = () => {
+ if (this.props.document.visibilityState === VISIBLE) {
+ this.props.sendImpression({
+ id: this.props.id
+ });
+ this.props.document.removeEventListener(VISIBILITY_CHANGE_EVENT, this._onVisibilityChange);
+ }
+ };
+
+ this.props.document.addEventListener(VISIBILITY_CHANGE_EVENT, this._onVisibilityChange);
+ }
+ }
+
+ componentWillUnmount() {
+ if (this._onVisibilityChange) {
+ this.props.document.removeEventListener(VISIBILITY_CHANGE_EVENT, this._onVisibilityChange);
+ }
+ }
+
+ componentDidMount() {
+ if (this.props.sendOnMount) {
+ this.sendImpressionOrAddListener();
+ }
+ }
+
+ componentDidUpdate(prevProps) {
+ if (this.props.shouldSendImpressionOnUpdate(this.props, prevProps)) {
+ this.sendImpressionOrAddListener();
+ }
+ }
+
+ render() {
+ return this.props.children;
+ }
+
+}
+ImpressionsWrapper.defaultProps = {
+ document: global.document,
+ sendOnMount: true
+};
+/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(3)))
+
+/***/ }),
+/* 12 */
+/***/ (function(module, exports) {
+
+module.exports = PropTypes;
+
+/***/ }),
+/* 13 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* WEBPACK VAR INJECTION */(function(global) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "IS_NEWTAB", function() { return IS_NEWTAB; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NEWTAB_DARK_THEME", function() { return NEWTAB_DARK_THEME; });
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+const IS_NEWTAB = global.document && global.document.documentURI === "about:newtab";
+const NEWTAB_DARK_THEME = {
+ ntp_background: {
+ r: 42,
+ g: 42,
+ b: 46,
+ a: 1
+ },
+ ntp_text: {
+ r: 249,
+ g: 249,
+ b: 250,
+ a: 1
+ },
+ sidebar: {
+ r: 56,
+ g: 56,
+ b: 61,
+ a: 1
+ },
+ sidebar_text: {
+ r: 249,
+ g: 249,
+ b: 250,
+ a: 1
+ }
+};
+/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(3)))
+
+/***/ }),
+/* 14 */
+/***/ (function(module, exports) {
+
+module.exports = ReactDOM;
+
+/***/ }),
+/* 15 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_ConfirmDialog", function() { return _ConfirmDialog; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ConfirmDialog", function() { return ConfirmDialog; });
+/* harmony import */ var common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
+/* harmony import */ var react_redux__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(7);
+/* harmony import */ var react_redux__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react_redux__WEBPACK_IMPORTED_MODULE_1__);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_2__);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+
+/**
+ * ConfirmDialog component.
+ * One primary action button, one cancel button.
+ *
+ * Content displayed is controlled by `data` prop the component receives.
+ * Example:
+ * data: {
+ * // Any sort of data needed to be passed around by actions.
+ * payload: site.url,
+ * // Primary button AlsoToMain action.
+ * action: "DELETE_HISTORY_URL",
+ * // Primary button USerEvent action.
+ * userEvent: "DELETE",
+ * // Array of locale ids to display.
+ * message_body: ["confirm_history_delete_p1", "confirm_history_delete_notice_p2"],
+ * // Text for primary button.
+ * confirm_button_string_id: "menu_action_delete"
+ * },
+ */
+
+class _ConfirmDialog extends react__WEBPACK_IMPORTED_MODULE_2___default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this._handleCancelBtn = this._handleCancelBtn.bind(this);
+ this._handleConfirmBtn = this._handleConfirmBtn.bind(this);
+ }
+
+ _handleCancelBtn() {
+ this.props.dispatch({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].DIALOG_CANCEL
+ });
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].UserEvent({
+ event: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].DIALOG_CANCEL,
+ source: this.props.data.eventSource
+ }));
+ }
+
+ _handleConfirmBtn() {
+ this.props.data.onConfirm.forEach(this.props.dispatch);
+ }
+
+ _renderModalMessage() {
+ const message_body = this.props.data.body_string_id;
+
+ if (!message_body) {
+ return null;
+ }
+
+ return react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("span", null, message_body.map(msg => react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("p", {
+ key: msg,
+ "data-l10n-id": msg
+ })));
+ }
+
+ render() {
+ if (!this.props.visible) {
+ return null;
+ }
+
+ return react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("div", {
+ className: "confirmation-dialog"
+ }, react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("div", {
+ className: "modal-overlay",
+ onClick: this._handleCancelBtn,
+ role: "presentation"
+ }), react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("div", {
+ className: "modal"
+ }, react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("section", {
+ className: "modal-message"
+ }, this.props.data.icon && react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("span", {
+ className: `icon icon-spacer icon-${this.props.data.icon}`
+ }), this._renderModalMessage()), react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("section", {
+ className: "actions"
+ }, react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("button", {
+ onClick: this._handleCancelBtn,
+ "data-l10n-id": this.props.data.cancel_button_string_id
+ }), react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("button", {
+ className: "done",
+ onClick: this._handleConfirmBtn,
+ "data-l10n-id": this.props.data.confirm_button_string_id
+ }))));
+ }
+
+}
+const ConfirmDialog = Object(react_redux__WEBPACK_IMPORTED_MODULE_1__["connect"])(state => state.Dialog)(_ConfirmDialog);
+
+/***/ }),
+/* 16 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* WEBPACK VAR INJECTION */(function(global) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isAllowedCSS", function() { return isAllowedCSS; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_DiscoveryStreamBase", function() { return _DiscoveryStreamBase; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiscoveryStreamBase", function() { return DiscoveryStreamBase; });
+/* harmony import */ var content_src_components_DiscoveryStreamComponents_CardGrid_CardGrid__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(17);
+/* harmony import */ var content_src_components_DiscoveryStreamComponents_CollectionCardGrid_CollectionCardGrid__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(32);
+/* harmony import */ var content_src_components_CollapsibleSection_CollapsibleSection__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(34);
+/* harmony import */ var react_redux__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(7);
+/* harmony import */ var react_redux__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(react_redux__WEBPACK_IMPORTED_MODULE_3__);
+/* harmony import */ var content_src_components_DiscoveryStreamComponents_DSMessage_DSMessage__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(39);
+/* harmony import */ var content_src_components_DiscoveryStreamComponents_DSPrivacyModal_DSPrivacyModal__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(40);
+/* harmony import */ var content_src_components_DiscoveryStreamComponents_DSSignup_DSSignup__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(42);
+/* harmony import */ var content_src_components_DiscoveryStreamComponents_DSTextPromo_DSTextPromo__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(43);
+/* harmony import */ var content_src_components_DiscoveryStreamComponents_Hero_Hero__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(44);
+/* harmony import */ var content_src_components_DiscoveryStreamComponents_Highlights_Highlights__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(46);
+/* harmony import */ var content_src_components_DiscoveryStreamComponents_HorizontalRule_HorizontalRule__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(59);
+/* harmony import */ var content_src_components_DiscoveryStreamComponents_List_List__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(45);
+/* harmony import */ var content_src_components_DiscoveryStreamComponents_Navigation_Navigation__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(60);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_13__);
+/* harmony import */ var content_src_components_DiscoveryStreamComponents_SectionTitle_SectionTitle__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(61);
+/* harmony import */ var content_src_lib_selectLayoutRender__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(62);
+/* harmony import */ var content_src_components_DiscoveryStreamComponents_TopSites_TopSites__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(63);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+const ALLOWED_CSS_URL_PREFIXES = ["chrome://", "resource://", "https://img-getpocket.cdn.mozilla.net/"];
+const DUMMY_CSS_SELECTOR = "DUMMY#CSS.SELECTOR";
+/**
+ * Validate a CSS declaration. The values are assumed to be normalized by CSSOM.
+ */
+
+function isAllowedCSS(property, value) {
+ // Bug 1454823: INTERNAL properties, e.g., -moz-context-properties, are
+ // exposed but their values aren't resulting in getting nothing. Fortunately,
+ // we don't care about validating the values of the current set of properties.
+ if (value === undefined) {
+ return true;
+ } // Make sure all urls are of the allowed protocols/prefixes
+
+
+ const urls = value.match(/url\("[^"]+"\)/g);
+ return !urls || urls.every(url => ALLOWED_CSS_URL_PREFIXES.some(prefix => url.slice(5).startsWith(prefix)));
+}
+class _DiscoveryStreamBase extends react__WEBPACK_IMPORTED_MODULE_13___default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onStyleMount = this.onStyleMount.bind(this);
+ }
+
+ onStyleMount(style) {
+ // Unmounting style gets rid of old styles, so nothing else to do
+ if (!style) {
+ return;
+ }
+
+ const {
+ sheet
+ } = style;
+ const styles = JSON.parse(style.dataset.styles);
+ styles.forEach((row, rowIndex) => {
+ row.forEach((component, componentIndex) => {
+ // Nothing to do without optional styles overrides
+ if (!component) {
+ return;
+ }
+
+ Object.entries(component).forEach(([selectors, declarations]) => {
+ // Start with a dummy rule to validate declarations and selectors
+ sheet.insertRule(`${DUMMY_CSS_SELECTOR} {}`);
+ const [rule] = sheet.cssRules; // Validate declarations and remove any offenders. CSSOM silently
+ // discards invalid entries, so here we apply extra restrictions.
+
+ rule.style = declarations;
+ [...rule.style].forEach(property => {
+ const value = rule.style[property];
+
+ if (!isAllowedCSS(property, value)) {
+ console.error(`Bad CSS declaration ${property}: ${value}`); // eslint-disable-line no-console
+
+ rule.style.removeProperty(property);
+ }
+ }); // Set the actual desired selectors scoped to the component
+
+ const prefix = `.ds-layout > .ds-column:nth-child(${rowIndex + 1}) .ds-column-grid > :nth-child(${componentIndex + 1})`; // NB: Splitting on "," doesn't work with strings with commas, but
+ // we're okay with not supporting those selectors
+
+ rule.selectorText = selectors.split(",").map(selector => prefix + ( // Assume :pseudo-classes are for component instead of descendant
+ selector[0] === ":" ? "" : " ") + selector).join(","); // CSSOM silently ignores bad selectors, so we'll be noisy instead
+
+ if (rule.selectorText === DUMMY_CSS_SELECTOR) {
+ console.error(`Bad CSS selector ${selectors}`); // eslint-disable-line no-console
+ }
+ });
+ });
+ });
+ }
+
+ renderComponent(component, embedWidth) {
+ const ENGAGEMENT_LABEL_ENABLED = this.props.Prefs.values[`discoverystream.engagementLabelEnabled`];
+
+ switch (component.type) {
+ case "Highlights":
+ return react__WEBPACK_IMPORTED_MODULE_13___default.a.createElement(content_src_components_DiscoveryStreamComponents_Highlights_Highlights__WEBPACK_IMPORTED_MODULE_9__["Highlights"], null);
+
+ case "TopSites":
+ let promoAlignment;
+
+ if (component.spocs && component.spocs.positions && component.spocs.positions.length) {
+ promoAlignment = component.spocs.positions[0].index === 0 ? "left" : "right";
+ }
+
+ return react__WEBPACK_IMPORTED_MODULE_13___default.a.createElement(content_src_components_DiscoveryStreamComponents_TopSites_TopSites__WEBPACK_IMPORTED_MODULE_16__["TopSites"], {
+ header: component.header,
+ data: component.data,
+ promoAlignment: promoAlignment
+ });
+
+ case "TextPromo":
+ return react__WEBPACK_IMPORTED_MODULE_13___default.a.createElement(content_src_components_DiscoveryStreamComponents_DSTextPromo_DSTextPromo__WEBPACK_IMPORTED_MODULE_7__["DSTextPromo"], {
+ dispatch: this.props.dispatch,
+ type: component.type,
+ data: component.data
+ });
+
+ case "Signup":
+ return react__WEBPACK_IMPORTED_MODULE_13___default.a.createElement(content_src_components_DiscoveryStreamComponents_DSSignup_DSSignup__WEBPACK_IMPORTED_MODULE_6__["DSSignup"], {
+ dispatch: this.props.dispatch,
+ type: component.type,
+ data: component.data
+ });
+
+ case "Message":
+ return react__WEBPACK_IMPORTED_MODULE_13___default.a.createElement(content_src_components_DiscoveryStreamComponents_DSMessage_DSMessage__WEBPACK_IMPORTED_MODULE_4__["DSMessage"], {
+ title: component.header && component.header.title,
+ subtitle: component.header && component.header.subtitle,
+ link_text: component.header && component.header.link_text,
+ link_url: component.header && component.header.link_url,
+ icon: component.header && component.header.icon
+ });
+
+ case "SectionTitle":
+ return react__WEBPACK_IMPORTED_MODULE_13___default.a.createElement(content_src_components_DiscoveryStreamComponents_SectionTitle_SectionTitle__WEBPACK_IMPORTED_MODULE_14__["SectionTitle"], {
+ header: component.header
+ });
+
+ case "Navigation":
+ return react__WEBPACK_IMPORTED_MODULE_13___default.a.createElement(content_src_components_DiscoveryStreamComponents_Navigation_Navigation__WEBPACK_IMPORTED_MODULE_12__["Navigation"], {
+ dispatch: this.props.dispatch,
+ links: component.properties.links,
+ alignment: component.properties.alignment,
+ display_variant: component.properties.display_variant,
+ explore_topics: component.properties.explore_topics,
+ header: component.header
+ });
+
+ case "CollectionCardGrid":
+ const {
+ DiscoveryStream
+ } = this.props;
+ return react__WEBPACK_IMPORTED_MODULE_13___default.a.createElement(content_src_components_DiscoveryStreamComponents_CollectionCardGrid_CollectionCardGrid__WEBPACK_IMPORTED_MODULE_1__["CollectionCardGrid"], {
+ data: component.data,
+ feed: component.feed,
+ spocs: DiscoveryStream.spocs,
+ placement: component.placement,
+ border: component.properties.border,
+ type: component.type,
+ items: component.properties.items,
+ cta_variant: component.cta_variant,
+ display_engagement_labels: ENGAGEMENT_LABEL_ENABLED,
+ dismissible: this.props.DiscoveryStream.isCollectionDismissible,
+ dispatch: this.props.dispatch
+ });
+
+ case "CardGrid":
+ return react__WEBPACK_IMPORTED_MODULE_13___default.a.createElement(content_src_components_DiscoveryStreamComponents_CardGrid_CardGrid__WEBPACK_IMPORTED_MODULE_0__["CardGrid"], {
+ enable_video_playheads: !!component.properties.enable_video_playheads,
+ title: component.header && component.header.title,
+ display_variant: component.properties.display_variant,
+ data: component.data,
+ feed: component.feed,
+ border: component.properties.border,
+ type: component.type,
+ dispatch: this.props.dispatch,
+ items: component.properties.items,
+ cta_variant: component.cta_variant,
+ display_engagement_labels: ENGAGEMENT_LABEL_ENABLED
+ });
+
+ case "Hero":
+ return react__WEBPACK_IMPORTED_MODULE_13___default.a.createElement(content_src_components_DiscoveryStreamComponents_Hero_Hero__WEBPACK_IMPORTED_MODULE_8__["Hero"], {
+ subComponentType: embedWidth >= 9 ? `cards` : `list`,
+ feed: component.feed,
+ title: component.header && component.header.title,
+ data: component.data,
+ border: component.properties.border,
+ type: component.type,
+ dispatch: this.props.dispatch,
+ items: component.properties.items
+ });
+
+ case "HorizontalRule":
+ return react__WEBPACK_IMPORTED_MODULE_13___default.a.createElement(content_src_components_DiscoveryStreamComponents_HorizontalRule_HorizontalRule__WEBPACK_IMPORTED_MODULE_10__["HorizontalRule"], null);
+
+ case "List":
+ return react__WEBPACK_IMPORTED_MODULE_13___default.a.createElement(content_src_components_DiscoveryStreamComponents_List_List__WEBPACK_IMPORTED_MODULE_11__["List"], {
+ data: component.data,
+ feed: component.feed,
+ fullWidth: component.properties.full_width,
+ hasBorders: component.properties.border === "border",
+ hasImages: component.properties.has_images,
+ hasNumbers: component.properties.has_numbers,
+ items: component.properties.items,
+ type: component.type,
+ header: component.header
+ });
+
+ default:
+ return react__WEBPACK_IMPORTED_MODULE_13___default.a.createElement("div", null, component.type);
+ }
+ }
+
+ renderStyles(styles) {
+ // Use json string as both the key and styles to render so React knows when
+ // to unmount and mount a new instance for new styles.
+ const json = JSON.stringify(styles);
+ return react__WEBPACK_IMPORTED_MODULE_13___default.a.createElement("style", {
+ key: json,
+ "data-styles": json,
+ ref: this.onStyleMount
+ });
+ }
+
+ render() {
+ // Select layout render data by adding spocs and position to recommendations
+ const {
+ layoutRender
+ } = Object(content_src_lib_selectLayoutRender__WEBPACK_IMPORTED_MODULE_15__["selectLayoutRender"])({
+ state: this.props.DiscoveryStream,
+ prefs: this.props.Prefs.values,
+ locale: this.props.locale
+ });
+ const {
+ config
+ } = this.props.DiscoveryStream; // Allow rendering without extracting special components
+
+ if (!config.collapsible) {
+ return this.renderLayout(layoutRender);
+ } // Find the first component of a type and remove it from layout
+
+
+ const extractComponent = type => {
+ for (const [rowIndex, row] of Object.entries(layoutRender)) {
+ for (const [index, component] of Object.entries(row.components)) {
+ if (component.type === type) {
+ // Remove the row if it was the only component or the single item
+ if (row.components.length === 1) {
+ layoutRender.splice(rowIndex, 1);
+ } else {
+ row.components.splice(index, 1);
+ }
+
+ return component;
+ }
+ }
+ }
+
+ return null;
+ }; // Get "topstories" Section state for default values
+
+
+ const topStories = this.props.Sections.find(s => s.id === "topstories");
+
+ if (!topStories) {
+ return null;
+ } // Extract TopSites to render before the rest and Message to use for header
+
+
+ const topSites = extractComponent("TopSites");
+ const sponsoredCollection = extractComponent("CollectionCardGrid");
+ const message = extractComponent("Message") || {
+ header: {
+ link_text: topStories.learnMore.link.message,
+ link_url: topStories.learnMore.link.href,
+ title: topStories.title
+ }
+ }; // Render a DS-style TopSites then the rest if any in a collapsible section
+
+ return react__WEBPACK_IMPORTED_MODULE_13___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_13___default.a.Fragment, null, this.props.DiscoveryStream.isPrivacyInfoModalVisible && react__WEBPACK_IMPORTED_MODULE_13___default.a.createElement(content_src_components_DiscoveryStreamComponents_DSPrivacyModal_DSPrivacyModal__WEBPACK_IMPORTED_MODULE_5__["DSPrivacyModal"], {
+ dispatch: this.props.dispatch
+ }), topSites && this.renderLayout([{
+ width: 12,
+ components: [topSites]
+ }]), sponsoredCollection && this.renderLayout([{
+ width: 12,
+ components: [sponsoredCollection]
+ }]), !!layoutRender.length && react__WEBPACK_IMPORTED_MODULE_13___default.a.createElement(content_src_components_CollapsibleSection_CollapsibleSection__WEBPACK_IMPORTED_MODULE_2__["CollapsibleSection"], {
+ className: "ds-layout",
+ collapsed: topStories.pref.collapsed,
+ dispatch: this.props.dispatch,
+ icon: topStories.icon,
+ id: topStories.id,
+ isFixed: true,
+ learnMore: {
+ link: {
+ href: message.header.link_url,
+ message: message.header.link_text
+ }
+ },
+ privacyNoticeURL: topStories.privacyNoticeURL,
+ showPrefName: topStories.pref.feed,
+ title: message.header.title,
+ eventSource: "CARDGRID"
+ }, this.renderLayout(layoutRender)), this.renderLayout([{
+ width: 12,
+ components: [{
+ type: "Highlights"
+ }]
+ }]));
+ }
+
+ renderLayout(layoutRender) {
+ const styles = [];
+ return react__WEBPACK_IMPORTED_MODULE_13___default.a.createElement("div", {
+ className: "discovery-stream ds-layout"
+ }, layoutRender.map((row, rowIndex) => react__WEBPACK_IMPORTED_MODULE_13___default.a.createElement("div", {
+ key: `row-${rowIndex}`,
+ className: `ds-column ds-column-${row.width}`
+ }, react__WEBPACK_IMPORTED_MODULE_13___default.a.createElement("div", {
+ className: "ds-column-grid"
+ }, row.components.map((component, componentIndex) => {
+ if (!component) {
+ return null;
+ }
+
+ styles[rowIndex] = [...(styles[rowIndex] || []), component.styles];
+ return react__WEBPACK_IMPORTED_MODULE_13___default.a.createElement("div", {
+ key: `component-${componentIndex}`
+ }, this.renderComponent(component, row.width));
+ })))), this.renderStyles(styles));
+ }
+
+}
+const DiscoveryStreamBase = Object(react_redux__WEBPACK_IMPORTED_MODULE_3__["connect"])(state => ({
+ DiscoveryStream: state.DiscoveryStream,
+ Prefs: state.Prefs,
+ Sections: state.Sections,
+ document: global.document
+}))(_DiscoveryStreamBase);
+/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(3)))
+
+/***/ }),
+/* 17 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CardGrid", function() { return CardGrid; });
+/* harmony import */ var _DSCard_DSCard_jsx__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(18);
+/* harmony import */ var _DSEmptyState_DSEmptyState_jsx__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(31);
+/* harmony import */ var _FluentOrText_FluentOrText_jsx__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(30);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_3__);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+
+
+class CardGrid extends react__WEBPACK_IMPORTED_MODULE_3___default.a.PureComponent {
+ renderCards() {
+ const recs = this.props.data.recommendations.slice(0, this.props.items);
+ const cards = [];
+
+ for (let index = 0; index < this.props.items; index++) {
+ const rec = recs[index];
+ cards.push(!rec || rec.placeholder ? react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(_DSCard_DSCard_jsx__WEBPACK_IMPORTED_MODULE_0__["PlaceholderDSCard"], {
+ key: `dscard-${index}`
+ }) : react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(_DSCard_DSCard_jsx__WEBPACK_IMPORTED_MODULE_0__["DSCard"], {
+ key: `dscard-${rec.id}`,
+ pos: rec.pos,
+ flightId: rec.flight_id,
+ image_src: rec.image_src,
+ raw_image_src: rec.raw_image_src,
+ title: rec.title,
+ excerpt: rec.excerpt,
+ url: rec.url,
+ id: rec.id,
+ shim: rec.shim,
+ type: this.props.type,
+ context: rec.context,
+ sponsor: rec.sponsor,
+ sponsored_by_override: rec.sponsored_by_override,
+ dispatch: this.props.dispatch,
+ source: rec.domain,
+ pocket_id: rec.pocket_id,
+ context_type: rec.context_type,
+ bookmarkGuid: rec.bookmarkGuid,
+ engagement: rec.engagement,
+ display_engagement_labels: this.props.display_engagement_labels,
+ cta: rec.cta,
+ cta_variant: this.props.cta_variant,
+ is_video: this.props.enable_video_playheads && rec.is_video,
+ is_collection: this.props.is_collection
+ }));
+ } // Used for CSS overrides to default styling (eg: "hero")
+
+
+ const variantClass = this.props.display_variant ? `ds-card-grid-${this.props.display_variant}` : ``;
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("div", {
+ className: `ds-card-grid ds-card-grid-${this.props.border} ${variantClass}`
+ }, cards);
+ }
+
+ render() {
+ const {
+ data
+ } = this.props; // Handle a render before feed has been fetched by displaying nothing
+
+ if (!data) {
+ return null;
+ } // Handle the case where a user has dismissed all recommendations
+
+
+ const isEmpty = data.recommendations.length === 0;
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("div", null, this.props.title && react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("div", {
+ className: "ds-header"
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("div", {
+ className: "title"
+ }, this.props.title), this.props.context && react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(_FluentOrText_FluentOrText_jsx__WEBPACK_IMPORTED_MODULE_2__["FluentOrText"], {
+ message: this.props.context
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("div", {
+ className: "ds-context"
+ }))), isEmpty ? react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("div", {
+ className: "ds-card-grid empty"
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(_DSEmptyState_DSEmptyState_jsx__WEBPACK_IMPORTED_MODULE_1__["DSEmptyState"], {
+ status: data.status,
+ dispatch: this.props.dispatch,
+ feed: this.props.feed
+ })) : this.renderCards());
+ }
+
+}
+CardGrid.defaultProps = {
+ border: `border`,
+ items: 4,
+ // Number of stories to display
+ enable_video_playheads: false
+};
+
+/***/ }),
+/* 18 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DefaultMeta", function() { return DefaultMeta; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CTAButtonMeta", function() { return CTAButtonMeta; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_DSCard", function() { return _DSCard; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DSCard", function() { return DSCard; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PlaceholderDSCard", function() { return PlaceholderDSCard; });
+/* harmony import */ var common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
+/* harmony import */ var _DSImage_DSImage_jsx__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(19);
+/* harmony import */ var _DSLinkMenu_DSLinkMenu__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(20);
+/* harmony import */ var _DiscoveryStreamImpressionStats_ImpressionStats__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(25);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_4__);
+/* harmony import */ var _SafeAnchor_SafeAnchor__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(26);
+/* harmony import */ var _DSContextFooter_DSContextFooter_jsx__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(27);
+/* harmony import */ var _FluentOrText_FluentOrText_jsx__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(30);
+/* harmony import */ var react_redux__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(7);
+/* harmony import */ var react_redux__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(react_redux__WEBPACK_IMPORTED_MODULE_8__);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+
+
+
+
+
+
+ // Default Meta that displays CTA as link if cta_variant in layout is set as "link"
+
+const DefaultMeta = ({
+ display_engagement_labels,
+ source,
+ title,
+ excerpt,
+ context,
+ context_type,
+ cta,
+ engagement,
+ cta_variant,
+ sponsor,
+ sponsored_by_override
+}) => react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("div", {
+ className: "meta"
+}, react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("div", {
+ className: "info-wrap"
+}, react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("p", {
+ className: "source clamp"
+}, source), react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("header", {
+ className: "title clamp"
+}, title), excerpt && react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("p", {
+ className: "excerpt clamp"
+}, excerpt), cta_variant === "link" && cta && react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("div", {
+ role: "link",
+ className: "cta-link icon icon-arrow",
+ tabIndex: "0"
+}, cta)), react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement(_DSContextFooter_DSContextFooter_jsx__WEBPACK_IMPORTED_MODULE_6__["DSContextFooter"], {
+ context_type: context_type,
+ context: context,
+ sponsor: sponsor,
+ sponsored_by_override: sponsored_by_override,
+ display_engagement_labels: display_engagement_labels,
+ engagement: engagement
+}));
+const CTAButtonMeta = ({
+ display_engagement_labels,
+ source,
+ title,
+ excerpt,
+ context,
+ context_type,
+ cta,
+ engagement,
+ sponsor,
+ sponsored_by_override
+}) => react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("div", {
+ className: "meta"
+}, react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("div", {
+ className: "info-wrap"
+}, react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("p", {
+ className: "source clamp"
+}, context && react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement(_FluentOrText_FluentOrText_jsx__WEBPACK_IMPORTED_MODULE_7__["FluentOrText"], {
+ message: {
+ id: `newtab-label-sponsored`,
+ values: {
+ sponsorOrSource: sponsor ? sponsor : source
+ }
+ }
+}), !context && (sponsor ? sponsor : source)), react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("header", {
+ className: "title clamp"
+}, title), excerpt && react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("p", {
+ className: "excerpt clamp"
+}, excerpt)), context && cta && react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("button", {
+ className: "button cta-button"
+}, cta), !context && react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement(_DSContextFooter_DSContextFooter_jsx__WEBPACK_IMPORTED_MODULE_6__["DSContextFooter"], {
+ context_type: context_type,
+ context: context,
+ sponsor: sponsor,
+ sponsored_by_override: sponsored_by_override,
+ display_engagement_labels: display_engagement_labels,
+ engagement: engagement
+}));
+class _DSCard extends react__WEBPACK_IMPORTED_MODULE_4___default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onLinkClick = this.onLinkClick.bind(this);
+
+ this.setPlaceholderRef = element => {
+ this.placeholderElement = element;
+ };
+
+ this.state = {
+ isSeen: false
+ }; // If this is for the about:home startup cache, then we always want
+ // to render the DSCard, regardless of whether or not its been seen.
+
+ if (props.App.isForStartupCache) {
+ this.state.isSeen = true;
+ } // We want to choose the optimal thumbnail for the underlying DSImage, but
+ // want to do it in a performant way. The breakpoints used in the
+ // CSS of the page are, unfortuntely, not easy to retrieve without
+ // causing a style flush. To avoid that, we hardcode them here.
+ //
+ // The values chosen here were the dimensions of the card thumbnails as
+ // computed by getBoundingClientRect() for each type of viewport width
+ // across both high-density and normal-density displays.
+
+
+ this.dsImageSizes = [{
+ mediaMatcher: "(min-width: 1122px)",
+ width: 296,
+ height: 148
+ }, {
+ mediaMatcher: "(min-width: 866px)",
+ width: 218,
+ height: 109
+ }, {
+ mediaMatcher: "(max-width: 610px)",
+ width: 202,
+ height: 101
+ }];
+ }
+
+ onLinkClick(event) {
+ if (this.props.dispatch) {
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].UserEvent({
+ event: "CLICK",
+ source: this.props.is_video ? "CARDGRID_VIDEO" : this.props.type.toUpperCase(),
+ action_position: this.props.pos,
+ value: {
+ card_type: this.props.flightId ? "spoc" : "organic"
+ }
+ }));
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].ImpressionStats({
+ source: this.props.is_video ? "CARDGRID_VIDEO" : this.props.type.toUpperCase(),
+ click: 0,
+ tiles: [{
+ id: this.props.id,
+ pos: this.props.pos,
+ ...(this.props.shim && this.props.shim.click ? {
+ shim: this.props.shim.click
+ } : {})
+ }]
+ }));
+ }
+ }
+
+ onSeen(entries) {
+ if (this.state) {
+ const entry = entries.find(e => e.isIntersecting);
+
+ if (entry) {
+ if (this.placeholderElement) {
+ this.observer.unobserve(this.placeholderElement);
+ } // Stop observing since element has been seen
+
+
+ this.setState({
+ isSeen: true
+ });
+ }
+ }
+ }
+
+ onIdleCallback() {
+ if (!this.state.isSeen) {
+ if (this.observer && this.placeholderElement) {
+ this.observer.unobserve(this.placeholderElement);
+ }
+
+ this.setState({
+ isSeen: true
+ });
+ }
+ }
+
+ componentDidMount() {
+ this.idleCallbackId = this.props.windowObj.requestIdleCallback(this.onIdleCallback.bind(this));
+
+ if (this.placeholderElement) {
+ this.observer = new IntersectionObserver(this.onSeen.bind(this));
+ this.observer.observe(this.placeholderElement);
+ }
+ }
+
+ componentWillUnmount() {
+ // Remove observer on unmount
+ if (this.observer && this.placeholderElement) {
+ this.observer.unobserve(this.placeholderElement);
+ }
+
+ if (this.idleCallbackId) {
+ this.props.windowObj.cancelIdleCallback(this.idleCallbackId);
+ }
+ }
+
+ render() {
+ if (this.props.placeholder || !this.state.isSeen) {
+ return react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("div", {
+ className: "ds-card placeholder",
+ ref: this.setPlaceholderRef
+ });
+ }
+
+ const isButtonCTA = this.props.cta_variant === "button";
+ const baseClass = `ds-card ${this.props.is_video ? `video-card` : ``}`;
+ return react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("div", {
+ className: baseClass
+ }, react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement(_SafeAnchor_SafeAnchor__WEBPACK_IMPORTED_MODULE_5__["SafeAnchor"], {
+ className: "ds-card-link",
+ dispatch: this.props.dispatch,
+ onLinkClick: !this.props.placeholder ? this.onLinkClick : undefined,
+ url: this.props.url
+ }, react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("div", {
+ className: "img-wrapper"
+ }, react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement(_DSImage_DSImage_jsx__WEBPACK_IMPORTED_MODULE_1__["DSImage"], {
+ extraClassNames: "img",
+ source: this.props.image_src,
+ rawSource: this.props.raw_image_src,
+ sizes: this.dsImageSizes
+ }), this.props.is_video && react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("div", {
+ className: "playhead"
+ }, react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("span", null, "Video Content"))), isButtonCTA ? react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement(CTAButtonMeta, {
+ display_engagement_labels: this.props.display_engagement_labels,
+ source: this.props.source,
+ title: this.props.title,
+ excerpt: this.props.excerpt,
+ context: this.props.context,
+ context_type: this.props.context_type,
+ engagement: this.props.engagement,
+ cta: this.props.cta,
+ sponsor: this.props.sponsor,
+ sponsored_by_override: this.props.sponsored_by_override
+ }) : react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement(DefaultMeta, {
+ display_engagement_labels: this.props.display_engagement_labels,
+ source: this.props.source,
+ title: this.props.title,
+ excerpt: this.props.excerpt,
+ context: this.props.context,
+ engagement: this.props.engagement,
+ context_type: this.props.context_type,
+ cta: this.props.cta,
+ cta_variant: this.props.cta_variant,
+ sponsor: this.props.sponsor,
+ sponsored_by_override: this.props.sponsored_by_override
+ }), react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement(_DiscoveryStreamImpressionStats_ImpressionStats__WEBPACK_IMPORTED_MODULE_3__["ImpressionStats"], {
+ flightId: this.props.flightId,
+ rows: [{
+ id: this.props.id,
+ pos: this.props.pos,
+ ...(this.props.shim && this.props.shim.impression ? {
+ shim: this.props.shim.impression
+ } : {})
+ }],
+ dispatch: this.props.dispatch,
+ source: this.props.is_video ? "CARDGRID_VIDEO" : this.props.type
+ })), react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement(_DSLinkMenu_DSLinkMenu__WEBPACK_IMPORTED_MODULE_2__["DSLinkMenu"], {
+ id: this.props.id,
+ index: this.props.pos,
+ dispatch: this.props.dispatch,
+ url: this.props.url,
+ title: this.props.title,
+ source: this.props.source,
+ type: this.props.type,
+ pocket_id: this.props.pocket_id,
+ shim: this.props.shim,
+ bookmarkGuid: this.props.bookmarkGuid,
+ flightId: !this.props.is_collection ? this.props.flightId : undefined,
+ showPrivacyInfo: !!this.props.flightId
+ }));
+ }
+
+}
+_DSCard.defaultProps = {
+ windowObj: window // Added to support unit tests
+
+};
+const DSCard = Object(react_redux__WEBPACK_IMPORTED_MODULE_8__["connect"])(state => ({
+ App: state.App
+}))(_DSCard);
+const PlaceholderDSCard = props => react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement(DSCard, {
+ placeholder: true
+});
+
+/***/ }),
+/* 19 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DSImage", function() { return DSImage; });
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+class DSImage extends react__WEBPACK_IMPORTED_MODULE_0___default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onOptimizedImageError = this.onOptimizedImageError.bind(this);
+ this.onNonOptimizedImageError = this.onNonOptimizedImageError.bind(this);
+ this.onLoad = this.onLoad.bind(this);
+ this.state = {
+ isLoaded: false,
+ optimizedImageFailed: false,
+ useTransition: false
+ };
+ }
+
+ onIdleCallback() {
+ if (!this.state.isLoaded) {
+ this.setState({
+ useTransition: true
+ });
+ }
+ }
+
+ reformatImageURL(url, width, height) {
+ // Change the image URL to request a size tailored for the parent container width
+ // Also: force JPEG, quality 60, no upscaling, no EXIF data
+ // Uses Thumbor: https://thumbor.readthedocs.io/en/latest/usage.html
+ return `https://img-getpocket.cdn.mozilla.net/${width}x${height}/filters:format(jpeg):quality(60):no_upscale():strip_exif()/${encodeURIComponent(url)}`;
+ }
+
+ componentDidMount() {
+ this.idleCallbackId = this.props.windowObj.requestIdleCallback(this.onIdleCallback.bind(this));
+ }
+
+ componentWillUnmount() {
+ if (this.idleCallbackId) {
+ this.props.windowObj.cancelIdleCallback(this.idleCallbackId);
+ }
+ }
+
+ render() {
+ let classNames = `ds-image
+ ${this.props.extraClassNames ? ` ${this.props.extraClassNames}` : ``}
+ ${this.state && this.state.useTransition ? ` use-transition` : ``}
+ ${this.state && this.state.isLoaded ? ` loaded` : ``}
+ `;
+ let img;
+
+ if (this.state) {
+ if (this.props.optimize && this.props.rawSource && !this.state.optimizedImageFailed) {
+ let baseSource = this.props.rawSource;
+ let sizeRules = [];
+ let srcSetRules = [];
+
+ for (let rule of this.props.sizes) {
+ let {
+ mediaMatcher,
+ width,
+ height
+ } = rule;
+ let sizeRule = `${mediaMatcher} ${width}px`;
+ sizeRules.push(sizeRule);
+ let srcSetRule = `${this.reformatImageURL(baseSource, width, height)} ${width}w`;
+ let srcSetRule2x = `${this.reformatImageURL(baseSource, width * 2, height * 2)} ${width * 2}w`;
+ srcSetRules.push(srcSetRule);
+ srcSetRules.push(srcSetRule2x);
+ }
+
+ if (this.props.sizes.length) {
+ // We have to supply a fallback in the very unlikely event that none of
+ // the media queries match. The smallest dimension was chosen arbitrarily.
+ sizeRules.push(`${this.props.sizes[this.props.sizes.length - 1].width}px`);
+ }
+
+ img = react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("img", {
+ loading: "lazy",
+ alt: this.props.alt_text,
+ crossOrigin: "anonymous",
+ onLoad: this.onLoad,
+ onError: this.onOptimizedImageError,
+ sizes: sizeRules.join(","),
+ src: baseSource,
+ srcSet: srcSetRules.join(",")
+ });
+ } else if (!this.state.nonOptimizedImageFailed) {
+ img = react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("img", {
+ loading: "lazy",
+ alt: this.props.alt_text,
+ crossOrigin: "anonymous",
+ onLoad: this.onLoad,
+ onError: this.onNonOptimizedImageError,
+ src: this.props.source
+ });
+ } else {
+ // Remove the img element if both sources fail. Render a placeholder instead.
+ img = react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
+ className: "broken-image"
+ });
+ }
+ }
+
+ return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("picture", {
+ className: classNames
+ }, img);
+ }
+
+ onOptimizedImageError() {
+ // This will trigger a re-render and the unoptimized 450px image will be used as a fallback
+ this.setState({
+ optimizedImageFailed: true
+ });
+ }
+
+ onNonOptimizedImageError() {
+ this.setState({
+ nonOptimizedImageFailed: true
+ });
+ }
+
+ onLoad() {
+ this.setState({
+ isLoaded: true
+ });
+ }
+
+}
+DSImage.defaultProps = {
+ source: null,
+ // The current source style from Pocket API (always 450px)
+ rawSource: null,
+ // Unadulterated image URL to filter through Thumbor
+ extraClassNames: null,
+ // Additional classnames to append to component
+ optimize: true,
+ // Measure parent container to request exact sizes
+ alt_text: null,
+ windowObj: window,
+ // Added to support unit tests
+ sizes: []
+};
+
+/***/ }),
+/* 20 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DSLinkMenu", function() { return DSLinkMenu; });
+/* harmony import */ var content_src_components_LinkMenu_LinkMenu__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(21);
+/* harmony import */ var content_src_components_ContextMenu_ContextMenuButton__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(24);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_2__);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+
+class DSLinkMenu extends react__WEBPACK_IMPORTED_MODULE_2___default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onMenuUpdate = this.onMenuUpdate.bind(this);
+ this.onMenuShow = this.onMenuShow.bind(this);
+ this.contextMenuButtonRef = react__WEBPACK_IMPORTED_MODULE_2___default.a.createRef();
+ }
+
+ onMenuUpdate(showContextMenu) {
+ if (!showContextMenu) {
+ const dsLinkMenuHostDiv = this.contextMenuButtonRef.current.parentElement;
+ dsLinkMenuHostDiv.parentElement.classList.remove("active", "last-item");
+ }
+ }
+
+ nextAnimationFrame() {
+ return new Promise(resolve => this.props.windowObj.requestAnimationFrame(resolve));
+ }
+
+ async onMenuShow() {
+ const dsLinkMenuHostDiv = this.contextMenuButtonRef.current.parentElement; // Wait for next frame before computing scrollMaxX to allow fluent menu strings to be visible
+
+ await this.nextAnimationFrame();
+
+ if (this.props.windowObj.scrollMaxX > 0) {
+ dsLinkMenuHostDiv.parentElement.classList.add("last-item");
+ }
+
+ dsLinkMenuHostDiv.parentElement.classList.add("active");
+ }
+
+ render() {
+ const {
+ index,
+ dispatch
+ } = this.props;
+ const TOP_STORIES_CONTEXT_MENU_OPTIONS = ["CheckBookmarkOrArchive", "CheckSavedToPocket", "Separator", "OpenInNewWindow", "OpenInPrivateWindow", "Separator", "BlockUrl", ...(this.props.showPrivacyInfo ? ["ShowPrivacyInfo"] : [])];
+ const type = this.props.type || "DISCOVERY_STREAM";
+ const title = this.props.title || this.props.source;
+ return react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("div", null, react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement(content_src_components_ContextMenu_ContextMenuButton__WEBPACK_IMPORTED_MODULE_1__["ContextMenuButton"], {
+ refFunction: this.contextMenuButtonRef,
+ tooltip: "newtab-menu-content-tooltip",
+ tooltipArgs: {
+ title
+ },
+ onUpdate: this.onMenuUpdate
+ }, react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement(content_src_components_LinkMenu_LinkMenu__WEBPACK_IMPORTED_MODULE_0__["LinkMenu"], {
+ dispatch: dispatch,
+ index: index,
+ source: type.toUpperCase(),
+ onShow: this.onMenuShow,
+ options: TOP_STORIES_CONTEXT_MENU_OPTIONS,
+ shouldSendImpressionStats: true,
+ site: {
+ referrer: "https://getpocket.com/recommendations",
+ title: this.props.title,
+ type: this.props.type,
+ url: this.props.url,
+ guid: this.props.id,
+ pocket_id: this.props.pocket_id,
+ shim: this.props.shim,
+ bookmarkGuid: this.props.bookmarkGuid,
+ flight_id: this.props.flightId
+ }
+ })));
+ }
+
+}
+DSLinkMenu.defaultProps = {
+ windowObj: window // Added to support unit tests
+
+};
+
+/***/ }),
+/* 21 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_LinkMenu", function() { return _LinkMenu; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LinkMenu", function() { return LinkMenu; });
+/* harmony import */ var common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
+/* harmony import */ var react_redux__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(7);
+/* harmony import */ var react_redux__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react_redux__WEBPACK_IMPORTED_MODULE_1__);
+/* harmony import */ var content_src_components_ContextMenu_ContextMenu__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(22);
+/* harmony import */ var content_src_lib_link_menu_options__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(23);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_4__);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+
+
+
+const DEFAULT_SITE_MENU_OPTIONS = ["CheckPinTopSite", "EditTopSite", "Separator", "OpenInNewWindow", "OpenInPrivateWindow", "Separator", "BlockUrl"];
+class _LinkMenu extends react__WEBPACK_IMPORTED_MODULE_4___default.a.PureComponent {
+ getOptions() {
+ const {
+ props
+ } = this;
+ const {
+ site,
+ index,
+ source,
+ isPrivateBrowsingEnabled,
+ siteInfo,
+ platform
+ } = props; // Handle special case of default site
+
+ const propOptions = site.isDefault && !site.searchTopSite && !site.sponsored_position ? DEFAULT_SITE_MENU_OPTIONS : props.options;
+ const options = propOptions.map(o => content_src_lib_link_menu_options__WEBPACK_IMPORTED_MODULE_3__["LinkMenuOptions"][o](site, index, source, isPrivateBrowsingEnabled, siteInfo, platform)).map(option => {
+ const {
+ action,
+ impression,
+ id,
+ type,
+ userEvent
+ } = option;
+
+ if (!type && id) {
+ option.onClick = (event = {}) => {
+ const {
+ ctrlKey,
+ metaKey,
+ shiftKey,
+ button
+ } = event; // Only send along event info if there's something non-default to send
+
+ if (ctrlKey || metaKey || shiftKey || button === 1) {
+ action.data = Object.assign({
+ event: {
+ ctrlKey,
+ metaKey,
+ shiftKey,
+ button
+ }
+ }, action.data);
+ }
+
+ props.dispatch(action);
+
+ if (userEvent) {
+ const userEventData = Object.assign({
+ event: userEvent,
+ source,
+ action_position: index
+ }, siteInfo);
+ props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].UserEvent(userEventData));
+ }
+
+ if (impression && props.shouldSendImpressionStats) {
+ props.dispatch(impression);
+ }
+ };
+ }
+
+ return option;
+ }); // This is for accessibility to support making each item tabbable.
+ // We want to know which item is the first and which item
+ // is the last, so we can close the context menu accordingly.
+
+ options[0].first = true;
+ options[options.length - 1].last = true;
+ return options;
+ }
+
+ render() {
+ return react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement(content_src_components_ContextMenu_ContextMenu__WEBPACK_IMPORTED_MODULE_2__["ContextMenu"], {
+ onUpdate: this.props.onUpdate,
+ onShow: this.props.onShow,
+ options: this.getOptions(),
+ keyboardAccess: this.props.keyboardAccess
+ });
+ }
+
+}
+
+const getState = state => ({
+ isPrivateBrowsingEnabled: state.Prefs.values.isPrivateBrowsingEnabled,
+ platform: state.Prefs.values.platform
+});
+
+const LinkMenu = Object(react_redux__WEBPACK_IMPORTED_MODULE_1__["connect"])(getState)(_LinkMenu);
+
+/***/ }),
+/* 22 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* WEBPACK VAR INJECTION */(function(global) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ContextMenu", function() { return ContextMenu; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_ContextMenuItem", function() { return _ContextMenuItem; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ContextMenuItem", function() { return ContextMenuItem; });
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
+/* harmony import */ var react_redux__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(7);
+/* harmony import */ var react_redux__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react_redux__WEBPACK_IMPORTED_MODULE_1__);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+class ContextMenu extends react__WEBPACK_IMPORTED_MODULE_0___default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.hideContext = this.hideContext.bind(this);
+ this.onShow = this.onShow.bind(this);
+ this.onClick = this.onClick.bind(this);
+ }
+
+ hideContext() {
+ this.props.onUpdate(false);
+ }
+
+ onShow() {
+ if (this.props.onShow) {
+ this.props.onShow();
+ }
+ }
+
+ componentDidMount() {
+ this.onShow();
+ setTimeout(() => {
+ global.addEventListener("click", this.hideContext);
+ }, 0);
+ }
+
+ componentWillUnmount() {
+ global.removeEventListener("click", this.hideContext);
+ }
+
+ onClick(event) {
+ // Eat all clicks on the context menu so they don't bubble up to window.
+ // This prevents the context menu from closing when clicking disabled items
+ // or the separators.
+ event.stopPropagation();
+ }
+
+ render() {
+ // Disabling focus on the menu span allows the first tab to focus on the first menu item instead of the wrapper.
+ return (// eslint-disable-next-line jsx-a11y/interactive-supports-focus
+ react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", {
+ className: "context-menu"
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("ul", {
+ role: "menu",
+ onClick: this.onClick,
+ onKeyDown: this.onClick,
+ className: "context-menu-list"
+ }, this.props.options.map((option, i) => option.type === "separator" ? react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("li", {
+ key: i,
+ className: "separator",
+ role: "separator"
+ }) : option.type !== "empty" && react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(ContextMenuItem, {
+ key: i,
+ option: option,
+ hideContext: this.hideContext,
+ keyboardAccess: this.props.keyboardAccess
+ }))))
+ );
+ }
+
+}
+class _ContextMenuItem extends react__WEBPACK_IMPORTED_MODULE_0___default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onClick = this.onClick.bind(this);
+ this.onKeyDown = this.onKeyDown.bind(this);
+ this.onKeyUp = this.onKeyUp.bind(this);
+ this.focusFirst = this.focusFirst.bind(this);
+ }
+
+ onClick(event) {
+ this.props.hideContext();
+ this.props.option.onClick(event);
+ } // Focus the first menu item if the menu was accessed via the keyboard.
+
+
+ focusFirst(button) {
+ if (this.props.keyboardAccess && button) {
+ button.focus();
+ }
+ } // This selects the correct node based on the key pressed
+
+
+ focusSibling(target, key) {
+ const parent = target.parentNode;
+ const closestSiblingSelector = key === "ArrowUp" ? "previousSibling" : "nextSibling";
+
+ if (!parent[closestSiblingSelector]) {
+ return;
+ }
+
+ if (parent[closestSiblingSelector].firstElementChild) {
+ parent[closestSiblingSelector].firstElementChild.focus();
+ } else {
+ parent[closestSiblingSelector][closestSiblingSelector].firstElementChild.focus();
+ }
+ }
+
+ onKeyDown(event) {
+ const {
+ option
+ } = this.props;
+
+ switch (event.key) {
+ case "Tab":
+ // tab goes down in context menu, shift + tab goes up in context menu
+ // if we're on the last item, one more tab will close the context menu
+ // similarly, if we're on the first item, one more shift + tab will close it
+ if (event.shiftKey && option.first || !event.shiftKey && option.last) {
+ this.props.hideContext();
+ }
+
+ break;
+
+ case "ArrowUp":
+ case "ArrowDown":
+ event.preventDefault();
+ this.focusSibling(event.target, event.key);
+ break;
+
+ case "Enter":
+ case " ":
+ event.preventDefault();
+ this.props.hideContext();
+ option.onClick();
+ break;
+
+ case "Escape":
+ this.props.hideContext();
+ break;
+ }
+ } // Prevents the default behavior of spacebar
+ // scrolling the page & auto-triggering buttons.
+
+
+ onKeyUp(event) {
+ if (event.key === " ") {
+ event.preventDefault();
+ }
+ }
+
+ render() {
+ const {
+ option
+ } = this.props;
+ const isNewNewtabExperienceEnabled = this.props.Prefs.values["newNewtabExperience.enabled"];
+ return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("li", {
+ role: "presentation",
+ className: "context-menu-item"
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("button", {
+ className: option.disabled ? "disabled" : "",
+ role: "menuitem",
+ onClick: this.onClick,
+ onKeyDown: this.onKeyDown,
+ onKeyUp: this.onKeyUp,
+ ref: option.first ? this.focusFirst : null
+ }, !isNewNewtabExperienceEnabled && option.icon && react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", {
+ className: `icon icon-spacer icon-${option.icon}`
+ }), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", {
+ "data-l10n-id": option.string_id || option.id
+ })));
+ }
+
+}
+const ContextMenuItem = Object(react_redux__WEBPACK_IMPORTED_MODULE_1__["connect"])(state => ({
+ Prefs: state.Prefs
+}))(_ContextMenuItem);
+/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(3)))
+
+/***/ }),
+/* 23 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LinkMenuOptions", function() { return LinkMenuOptions; });
+/* harmony import */ var common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+const _OpenInPrivateWindow = site => ({
+ id: "newtab-menu-open-new-private-window",
+ icon: "new-window-private",
+ action: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].OnlyToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].OPEN_PRIVATE_WINDOW,
+ data: {
+ url: site.url,
+ referrer: site.referrer
+ }
+ }),
+ userEvent: "OPEN_PRIVATE_WINDOW"
+});
+/**
+ * List of functions that return items that can be included as menu options in a
+ * LinkMenu. All functions take the site as the first parameter, and optionally
+ * the index of the site.
+ */
+
+
+const LinkMenuOptions = {
+ Separator: () => ({
+ type: "separator"
+ }),
+ EmptyItem: () => ({
+ type: "empty"
+ }),
+ ShowPrivacyInfo: site => ({
+ id: "newtab-menu-show-privacy-info",
+ icon: "info",
+ action: {
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].SHOW_PRIVACY_INFO
+ },
+ userEvent: "SHOW_PRIVACY_INFO"
+ }),
+ AboutSponsored: site => ({
+ id: "newtab-menu-show-privacy-info",
+ icon: "info",
+ action: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].AlsoToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].ABOUT_SPONSORED_TOP_SITES
+ }),
+ userEvent: "TOPSITE_SPONSOR_INFO"
+ }),
+ RemoveBookmark: site => ({
+ id: "newtab-menu-remove-bookmark",
+ icon: "bookmark-added",
+ action: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].AlsoToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].DELETE_BOOKMARK_BY_ID,
+ data: site.bookmarkGuid
+ }),
+ userEvent: "BOOKMARK_DELETE"
+ }),
+ AddBookmark: site => ({
+ id: "newtab-menu-bookmark",
+ icon: "bookmark-hollow",
+ action: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].AlsoToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].BOOKMARK_URL,
+ data: {
+ url: site.url,
+ title: site.title,
+ type: site.type
+ }
+ }),
+ userEvent: "BOOKMARK_ADD"
+ }),
+ OpenInNewWindow: site => ({
+ id: "newtab-menu-open-new-window",
+ icon: "new-window",
+ action: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].AlsoToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].OPEN_NEW_WINDOW,
+ data: {
+ referrer: site.referrer,
+ typedBonus: site.typedBonus,
+ url: site.url
+ }
+ }),
+ userEvent: "OPEN_NEW_WINDOW"
+ }),
+ // This blocks the url for regular stories,
+ // but also sends a message to DiscoveryStream with flight_id.
+ // If DiscoveryStream sees this message for a flight_id
+ // it also blocks it on the flight_id.
+ BlockUrl: (site, index, eventSource) => {
+ return LinkMenuOptions.BlockUrls([site], index, eventSource);
+ },
+ // Same as BlockUrl, cept can work on an array of sites.
+ BlockUrls: (tiles, pos, eventSource) => ({
+ id: "newtab-menu-dismiss",
+ icon: "dismiss",
+ action: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].AlsoToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].BLOCK_URL,
+ data: tiles.map(site => ({
+ url: site.original_url || site.open_url || site.url,
+ // pocket_id is only for pocket stories being in highlights, and then dismissed.
+ pocket_id: site.pocket_id,
+ ...(site.flight_id ? {
+ flight_id: site.flight_id
+ } : {})
+ }))
+ }),
+ impression: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].ImpressionStats({
+ source: eventSource,
+ block: 0,
+ tiles: tiles.map((site, index) => ({
+ id: site.guid,
+ pos: pos + index,
+ ...(site.shim && site.shim.delete ? {
+ shim: site.shim.delete
+ } : {})
+ }))
+ }),
+ userEvent: "BLOCK"
+ }),
+ // This is an option for web extentions which will result in remove items from
+ // memory and notify the web extenion, rather than using the built-in block list.
+ WebExtDismiss: (site, index, eventSource) => ({
+ id: "menu_action_webext_dismiss",
+ string_id: "newtab-menu-dismiss",
+ icon: "dismiss",
+ action: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].WebExtEvent(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].WEBEXT_DISMISS, {
+ source: eventSource,
+ url: site.url,
+ action_position: index
+ })
+ }),
+ DeleteUrl: (site, index, eventSource, isEnabled, siteInfo) => ({
+ id: "newtab-menu-delete-history",
+ icon: "delete",
+ action: {
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].DIALOG_OPEN,
+ data: {
+ onConfirm: [common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].AlsoToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].DELETE_HISTORY_URL,
+ data: {
+ url: site.url,
+ pocket_id: site.pocket_id,
+ forceBlock: site.bookmarkGuid
+ }
+ }), common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].UserEvent(Object.assign({
+ event: "DELETE",
+ source: eventSource,
+ action_position: index
+ }, siteInfo))],
+ eventSource,
+ body_string_id: ["newtab-confirm-delete-history-p1", "newtab-confirm-delete-history-p2"],
+ confirm_button_string_id: "newtab-topsites-delete-history-button",
+ cancel_button_string_id: "newtab-topsites-cancel-button",
+ icon: "modal-delete"
+ }
+ },
+ userEvent: "DIALOG_OPEN"
+ }),
+ ShowFile: site => ({
+ id: "newtab-menu-show-file",
+ icon: "search",
+ action: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].OnlyToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].SHOW_DOWNLOAD_FILE,
+ data: {
+ url: site.url
+ }
+ })
+ }),
+ OpenFile: site => ({
+ id: "newtab-menu-open-file",
+ icon: "open-file",
+ action: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].OnlyToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].OPEN_DOWNLOAD_FILE,
+ data: {
+ url: site.url
+ }
+ })
+ }),
+ CopyDownloadLink: site => ({
+ id: "newtab-menu-copy-download-link",
+ icon: "copy",
+ action: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].OnlyToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].COPY_DOWNLOAD_LINK,
+ data: {
+ url: site.url
+ }
+ })
+ }),
+ GoToDownloadPage: site => ({
+ id: "newtab-menu-go-to-download-page",
+ icon: "download",
+ action: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].OnlyToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].OPEN_LINK,
+ data: {
+ url: site.referrer
+ }
+ }),
+ disabled: !site.referrer
+ }),
+ RemoveDownload: site => ({
+ id: "newtab-menu-remove-download",
+ icon: "delete",
+ action: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].OnlyToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].REMOVE_DOWNLOAD_FILE,
+ data: {
+ url: site.url
+ }
+ })
+ }),
+ PinTopSite: (site, index) => ({
+ id: "newtab-menu-pin",
+ icon: "pin",
+ action: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].AlsoToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].TOP_SITES_PIN,
+ data: {
+ site,
+ index
+ }
+ }),
+ userEvent: "PIN"
+ }),
+ UnpinTopSite: site => ({
+ id: "newtab-menu-unpin",
+ icon: "unpin",
+ action: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].AlsoToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].TOP_SITES_UNPIN,
+ data: {
+ site: {
+ url: site.url
+ }
+ }
+ }),
+ userEvent: "UNPIN"
+ }),
+ SaveToPocket: (site, index, eventSource) => ({
+ id: "newtab-menu-save-to-pocket",
+ icon: "pocket-save",
+ action: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].AlsoToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].SAVE_TO_POCKET,
+ data: {
+ site: {
+ url: site.url,
+ title: site.title
+ }
+ }
+ }),
+ impression: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].ImpressionStats({
+ source: eventSource,
+ pocket: 0,
+ tiles: [{
+ id: site.guid,
+ pos: index,
+ ...(site.shim && site.shim.save ? {
+ shim: site.shim.save
+ } : {})
+ }]
+ }),
+ userEvent: "SAVE_TO_POCKET"
+ }),
+ DeleteFromPocket: site => ({
+ id: "newtab-menu-delete-pocket",
+ icon: "pocket-delete",
+ action: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].AlsoToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].DELETE_FROM_POCKET,
+ data: {
+ pocket_id: site.pocket_id
+ }
+ }),
+ userEvent: "DELETE_FROM_POCKET"
+ }),
+ ArchiveFromPocket: site => ({
+ id: "newtab-menu-archive-pocket",
+ icon: "pocket-archive",
+ action: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].AlsoToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].ARCHIVE_FROM_POCKET,
+ data: {
+ pocket_id: site.pocket_id
+ }
+ }),
+ userEvent: "ARCHIVE_FROM_POCKET"
+ }),
+ EditTopSite: (site, index) => ({
+ id: "newtab-menu-edit-topsites",
+ icon: "edit",
+ action: {
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].TOP_SITES_EDIT,
+ data: {
+ index
+ }
+ }
+ }),
+ CheckBookmark: site => site.bookmarkGuid ? LinkMenuOptions.RemoveBookmark(site) : LinkMenuOptions.AddBookmark(site),
+ CheckPinTopSite: (site, index) => site.isPinned ? LinkMenuOptions.UnpinTopSite(site) : LinkMenuOptions.PinTopSite(site, index),
+ CheckSavedToPocket: (site, index) => site.pocket_id ? LinkMenuOptions.DeleteFromPocket(site) : LinkMenuOptions.SaveToPocket(site, index),
+ CheckBookmarkOrArchive: site => site.pocket_id ? LinkMenuOptions.ArchiveFromPocket(site) : LinkMenuOptions.CheckBookmark(site),
+ OpenInPrivateWindow: (site, index, eventSource, isEnabled) => isEnabled ? _OpenInPrivateWindow(site) : LinkMenuOptions.EmptyItem()
+};
+
+/***/ }),
+/* 24 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ContextMenuButton", function() { return ContextMenuButton; });
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+class ContextMenuButton extends react__WEBPACK_IMPORTED_MODULE_0___default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.state = {
+ showContextMenu: false,
+ contextMenuKeyboard: false
+ };
+ this.onClick = this.onClick.bind(this);
+ this.onKeyDown = this.onKeyDown.bind(this);
+ this.onUpdate = this.onUpdate.bind(this);
+ }
+
+ openContextMenu(isKeyBoard, event) {
+ if (this.props.onUpdate) {
+ this.props.onUpdate(true);
+ }
+
+ this.setState({
+ showContextMenu: true,
+ contextMenuKeyboard: isKeyBoard
+ });
+ }
+
+ onClick(event) {
+ event.preventDefault();
+ this.openContextMenu(false, event);
+ }
+
+ onKeyDown(event) {
+ if (event.key === "Enter" || event.key === " ") {
+ event.preventDefault();
+ this.openContextMenu(true, event);
+ }
+ }
+
+ onUpdate(showContextMenu) {
+ if (this.props.onUpdate) {
+ this.props.onUpdate(showContextMenu);
+ }
+
+ this.setState({
+ showContextMenu
+ });
+ }
+
+ render() {
+ const {
+ tooltipArgs,
+ tooltip,
+ children,
+ refFunction
+ } = this.props;
+ const {
+ showContextMenu,
+ contextMenuKeyboard
+ } = this.state;
+ return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_0___default.a.Fragment, null, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("button", {
+ "aria-haspopup": "true",
+ "data-l10n-id": tooltip,
+ "data-l10n-args": tooltipArgs ? JSON.stringify(tooltipArgs) : null,
+ className: "context-menu-button icon",
+ onKeyDown: this.onKeyDown,
+ onClick: this.onClick,
+ ref: refFunction
+ }), showContextMenu ? react__WEBPACK_IMPORTED_MODULE_0___default.a.cloneElement(children, {
+ keyboardAccess: contextMenuKeyboard,
+ onUpdate: this.onUpdate
+ }) : null);
+ }
+
+}
+
+/***/ }),
+/* 25 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* WEBPACK VAR INJECTION */(function(global) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "INTERSECTION_RATIO", function() { return INTERSECTION_RATIO; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ImpressionStats", function() { return ImpressionStats; });
+/* harmony import */ var common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+const VISIBLE = "visible";
+const VISIBILITY_CHANGE_EVENT = "visibilitychange"; // Per analytical requirement, we set the minimal intersection ratio to
+// 0.5, and an impression is identified when the wrapped item has at least
+// 50% visibility.
+//
+// This constant is exported for unit test
+
+const INTERSECTION_RATIO = 0.5;
+/**
+ * Impression wrapper for Discovery Stream related React components.
+ *
+ * It makses use of the Intersection Observer API to detect the visibility,
+ * and relies on page visibility to ensure the impression is reported
+ * only when the component is visible on the page.
+ *
+ * Note:
+ * * This wrapper used to be used either at the individual card level,
+ * or by the card container components.
+ * It is now only used for individual card level.
+ * * Each impression will be sent only once as soon as the desired
+ * visibility is detected
+ * * Batching is not yet implemented, hence it might send multiple
+ * impression pings separately
+ */
+
+class ImpressionStats extends react__WEBPACK_IMPORTED_MODULE_1___default.a.PureComponent {
+ // This checks if the given cards are the same as those in the last impression ping.
+ // If so, it should not send the same impression ping again.
+ _needsImpressionStats(cards) {
+ if (!this.impressionCardGuids || this.impressionCardGuids.length !== cards.length) {
+ return true;
+ }
+
+ for (let i = 0; i < cards.length; i++) {
+ if (cards[i].id !== this.impressionCardGuids[i]) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ _dispatchImpressionStats() {
+ const {
+ props
+ } = this;
+ const cards = props.rows;
+
+ if (this.props.flightId) {
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].OnlyToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].DISCOVERY_STREAM_SPOC_IMPRESSION,
+ data: {
+ flightId: this.props.flightId
+ }
+ }));
+ }
+
+ if (this._needsImpressionStats(cards)) {
+ props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].DiscoveryStreamImpressionStats({
+ source: props.source.toUpperCase(),
+ tiles: cards.map(link => ({
+ id: link.id,
+ pos: link.pos,
+ ...(link.shim ? {
+ shim: link.shim
+ } : {})
+ }))
+ }));
+ this.impressionCardGuids = cards.map(link => link.id);
+ }
+ } // This checks if the given cards are the same as those in the last loaded content ping.
+ // If so, it should not send the same loaded content ping again.
+
+
+ _needsLoadedContent(cards) {
+ if (!this.loadedContentGuids || this.loadedContentGuids.length !== cards.length) {
+ return true;
+ }
+
+ for (let i = 0; i < cards.length; i++) {
+ if (cards[i].id !== this.loadedContentGuids[i]) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ _dispatchLoadedContent() {
+ const {
+ props
+ } = this;
+ const cards = props.rows;
+
+ if (this._needsLoadedContent(cards)) {
+ props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].DiscoveryStreamLoadedContent({
+ source: props.source.toUpperCase(),
+ tiles: cards.map(link => ({
+ id: link.id,
+ pos: link.pos
+ }))
+ }));
+ this.loadedContentGuids = cards.map(link => link.id);
+ }
+ }
+
+ setImpressionObserverOrAddListener() {
+ const {
+ props
+ } = this;
+
+ if (!props.dispatch) {
+ return;
+ }
+
+ if (props.document.visibilityState === VISIBLE) {
+ // Send the loaded content ping once the page is visible.
+ this._dispatchLoadedContent();
+
+ this.setImpressionObserver();
+ } else {
+ // We should only ever send the latest impression stats ping, so remove any
+ // older listeners.
+ if (this._onVisibilityChange) {
+ props.document.removeEventListener(VISIBILITY_CHANGE_EVENT, this._onVisibilityChange);
+ }
+
+ this._onVisibilityChange = () => {
+ if (props.document.visibilityState === VISIBLE) {
+ // Send the loaded content ping once the page is visible.
+ this._dispatchLoadedContent();
+
+ this.setImpressionObserver();
+ props.document.removeEventListener(VISIBILITY_CHANGE_EVENT, this._onVisibilityChange);
+ }
+ };
+
+ props.document.addEventListener(VISIBILITY_CHANGE_EVENT, this._onVisibilityChange);
+ }
+ }
+ /**
+ * Set an impression observer for the wrapped component. It makes use of
+ * the Intersection Observer API to detect if the wrapped component is
+ * visible with a desired ratio, and only sends impression if that's the case.
+ *
+ * See more details about Intersection Observer API at:
+ * https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
+ */
+
+
+ setImpressionObserver() {
+ const {
+ props
+ } = this;
+
+ if (!props.rows.length) {
+ return;
+ }
+
+ this._handleIntersect = entries => {
+ if (entries.some(entry => entry.isIntersecting && entry.intersectionRatio >= INTERSECTION_RATIO)) {
+ this._dispatchImpressionStats();
+
+ this.impressionObserver.unobserve(this.refs.impression);
+ }
+ };
+
+ const options = {
+ threshold: INTERSECTION_RATIO
+ };
+ this.impressionObserver = new props.IntersectionObserver(this._handleIntersect, options);
+ this.impressionObserver.observe(this.refs.impression);
+ }
+
+ componentDidMount() {
+ if (this.props.rows.length) {
+ this.setImpressionObserverOrAddListener();
+ }
+ }
+
+ componentWillUnmount() {
+ if (this._handleIntersect && this.impressionObserver) {
+ this.impressionObserver.unobserve(this.refs.impression);
+ }
+
+ if (this._onVisibilityChange) {
+ this.props.document.removeEventListener(VISIBILITY_CHANGE_EVENT, this._onVisibilityChange);
+ }
+ }
+
+ render() {
+ return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", {
+ ref: "impression",
+ className: "impression-observer"
+ }, this.props.children);
+ }
+
+}
+ImpressionStats.defaultProps = {
+ IntersectionObserver: global.IntersectionObserver,
+ document: global.document,
+ rows: [],
+ source: ""
+};
+/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(3)))
+
+/***/ }),
+/* 26 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SafeAnchor", function() { return SafeAnchor; });
+/* harmony import */ var common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+class SafeAnchor extends react__WEBPACK_IMPORTED_MODULE_1___default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onClick = this.onClick.bind(this);
+ }
+
+ onClick(event) {
+ // Use dispatch instead of normal link click behavior to include referrer
+ if (this.props.dispatch) {
+ event.preventDefault();
+ const {
+ altKey,
+ button,
+ ctrlKey,
+ metaKey,
+ shiftKey
+ } = event;
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].OnlyToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].OPEN_LINK,
+ data: {
+ event: {
+ altKey,
+ button,
+ ctrlKey,
+ metaKey,
+ shiftKey
+ },
+ referrer: "https://getpocket.com/recommendations",
+ // Use the anchor's url, which could have been cleaned up
+ url: event.currentTarget.href
+ }
+ }));
+ } // Propagate event if there's a handler
+
+
+ if (this.props.onLinkClick) {
+ this.props.onLinkClick(event);
+ }
+ }
+
+ safeURI(url) {
+ let protocol = null;
+
+ try {
+ protocol = new URL(url).protocol;
+ } catch (e) {
+ return "";
+ }
+
+ const isAllowed = ["http:", "https:"].includes(protocol);
+
+ if (!isAllowed) {
+ console.warn(`${url} is not allowed for anchor targets.`); // eslint-disable-line no-console
+
+ return "";
+ }
+
+ return url;
+ }
+
+ render() {
+ const {
+ url,
+ className
+ } = this.props;
+ return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("a", {
+ href: this.safeURI(url),
+ className: className,
+ onClick: this.onClick
+ }, this.props.children);
+ }
+
+}
+
+/***/ }),
+/* 27 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StatusMessage", function() { return StatusMessage; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SponsorLabel", function() { return SponsorLabel; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DSContextFooter", function() { return DSContextFooter; });
+/* harmony import */ var _Card_types_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(28);
+/* harmony import */ var react_transition_group__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(29);
+/* harmony import */ var react_transition_group__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react_transition_group__WEBPACK_IMPORTED_MODULE_1__);
+/* harmony import */ var _FluentOrText_FluentOrText_jsx__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(30);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_3__);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+
+ // Animation time is mirrored in DSContextFooter.scss
+
+const ANIMATION_DURATION = 3000;
+const StatusMessage = ({
+ icon,
+ fluentID
+}) => react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("div", {
+ className: "status-message"
+}, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("span", {
+ "aria-haspopup": "true",
+ className: `story-badge-icon icon icon-${icon}`
+}), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("div", {
+ className: "story-context-label",
+ "data-l10n-id": fluentID
+}));
+const SponsorLabel = ({
+ sponsored_by_override,
+ sponsor,
+ context
+}) => {
+ const classList = "story-sponsored-label clamp"; // If override is not false or an empty string.
+
+ if (sponsored_by_override) {
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("p", {
+ className: classList
+ }, sponsored_by_override);
+ } else if (sponsored_by_override === "") {
+ // We specifically want to display nothing if the server returns an empty string.
+ // So the server can turn off the label.
+ // This is to support the use cases where the sponsored context is displayed elsewhere.
+ return null;
+ } else if (sponsor) {
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("p", {
+ className: classList
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(_FluentOrText_FluentOrText_jsx__WEBPACK_IMPORTED_MODULE_2__["FluentOrText"], {
+ message: {
+ id: `newtab-label-sponsored-by`,
+ values: {
+ sponsor
+ }
+ }
+ }));
+ } else if (context) {
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("p", {
+ className: classList
+ }, context);
+ }
+
+ return null;
+};
+class DSContextFooter extends react__WEBPACK_IMPORTED_MODULE_3___default.a.PureComponent {
+ render() {
+ // display_engagement_labels is based on pref `browser.newtabpage.activity-stream.discoverystream.engagementLabelEnabled`
+ const {
+ context,
+ context_type,
+ engagement,
+ display_engagement_labels,
+ sponsor,
+ sponsored_by_override
+ } = this.props;
+ const {
+ icon,
+ fluentID
+ } = _Card_types_js__WEBPACK_IMPORTED_MODULE_0__["cardContextTypes"][context_type] || {};
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("div", {
+ className: "story-footer"
+ }, SponsorLabel({
+ sponsored_by_override,
+ sponsor,
+ context
+ }), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(react_transition_group__WEBPACK_IMPORTED_MODULE_1__["TransitionGroup"], {
+ component: null
+ }, !context && (context_type || display_engagement_labels && engagement) && react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(react_transition_group__WEBPACK_IMPORTED_MODULE_1__["CSSTransition"], {
+ key: fluentID,
+ timeout: ANIMATION_DURATION,
+ classNames: "story-animate"
+ }, engagement && !context_type ? react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("div", {
+ className: "story-view-count"
+ }, engagement) : react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(StatusMessage, {
+ icon: icon,
+ fluentID: fluentID
+ }))));
+ }
+
+}
+
+/***/ }),
+/* 28 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "cardContextTypes", function() { return cardContextTypes; });
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+const cardContextTypes = {
+ history: {
+ fluentID: "newtab-label-visited",
+ icon: "history-item"
+ },
+ removedBookmark: {
+ fluentID: "newtab-label-removed-bookmark",
+ icon: "bookmark-removed"
+ },
+ bookmark: {
+ fluentID: "newtab-label-bookmarked",
+ icon: "bookmark-added"
+ },
+ trending: {
+ fluentID: "newtab-label-recommended",
+ icon: "trending"
+ },
+ pocket: {
+ fluentID: "newtab-label-saved",
+ icon: "pocket"
+ },
+ download: {
+ fluentID: "newtab-label-download",
+ icon: "download"
+ }
+};
+
+/***/ }),
+/* 29 */
+/***/ (function(module, exports) {
+
+module.exports = ReactTransitionGroup;
+
+/***/ }),
+/* 30 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FluentOrText", function() { return FluentOrText; });
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/**
+ * Set text on a child element/component depending on if the message is already
+ * translated plain text or a fluent id with optional args.
+ */
+
+class FluentOrText extends react__WEBPACK_IMPORTED_MODULE_0___default.a.PureComponent {
+ render() {
+ // Ensure we have a single child to attach attributes
+ const {
+ children,
+ message
+ } = this.props;
+ const child = children ? react__WEBPACK_IMPORTED_MODULE_0___default.a.Children.only(children) : react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", null); // For a string message, just use it as the child's text
+
+ let grandChildren = message;
+ let extraProps; // Convert a message object to set desired fluent-dom attributes
+
+ if (typeof message === "object") {
+ const args = message.args || message.values;
+ extraProps = {
+ "data-l10n-args": args && JSON.stringify(args),
+ "data-l10n-id": message.id || message.string_id
+ }; // Use original children potentially with data-l10n-name attributes
+
+ grandChildren = child.props.children;
+ } // Add the message to the child via fluent attributes or text node
+
+
+ return react__WEBPACK_IMPORTED_MODULE_0___default.a.cloneElement(child, extraProps, grandChildren);
+ }
+
+}
+
+/***/ }),
+/* 31 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DSEmptyState", function() { return DSEmptyState; });
+/* harmony import */ var common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+class DSEmptyState extends react__WEBPACK_IMPORTED_MODULE_1___default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onReset = this.onReset.bind(this);
+ this.state = {};
+ }
+
+ componentWillUnmount() {
+ if (this.timeout) {
+ clearTimeout(this.timeout);
+ }
+ }
+
+ onReset() {
+ if (this.props.dispatch && this.props.feed) {
+ const {
+ feed
+ } = this.props;
+ const {
+ url
+ } = feed;
+ this.props.dispatch({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].DISCOVERY_STREAM_FEED_UPDATE,
+ data: {
+ feed: { ...feed,
+ data: { ...feed.data,
+ status: "waiting"
+ }
+ },
+ url
+ }
+ });
+ this.setState({
+ waiting: true
+ });
+ this.timeout = setTimeout(() => {
+ this.timeout = null;
+ this.setState({
+ waiting: false
+ });
+ }, 300);
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].OnlyToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].DISCOVERY_STREAM_RETRY_FEED,
+ data: {
+ feed
+ }
+ }));
+ }
+ }
+
+ renderButton() {
+ if (this.props.status === "waiting" || this.state.waiting) {
+ return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("button", {
+ className: "try-again-button waiting",
+ "data-l10n-id": "newtab-discovery-empty-section-topstories-loading"
+ });
+ }
+
+ return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("button", {
+ className: "try-again-button",
+ onClick: this.onReset,
+ "data-l10n-id": "newtab-discovery-empty-section-topstories-try-again-button"
+ });
+ }
+
+ renderState() {
+ if (this.props.status === "waiting" || this.props.status === "failed") {
+ return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null, react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("h2", {
+ "data-l10n-id": "newtab-discovery-empty-section-topstories-timed-out"
+ }), this.renderButton());
+ }
+
+ return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(react__WEBPACK_IMPORTED_MODULE_1___default.a.Fragment, null, react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("h2", {
+ "data-l10n-id": "newtab-discovery-empty-section-topstories-header"
+ }), react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("p", {
+ "data-l10n-id": "newtab-discovery-empty-section-topstories-content"
+ }));
+ }
+
+ render() {
+ return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", {
+ className: "section-empty-state"
+ }, react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", {
+ className: "empty-state-message"
+ }, this.renderState()));
+ }
+
+}
+
+/***/ }),
+/* 32 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CollectionCardGrid", function() { return CollectionCardGrid; });
+/* harmony import */ var common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
+/* harmony import */ var content_src_components_DiscoveryStreamComponents_CardGrid_CardGrid__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(17);
+/* harmony import */ var content_src_components_DiscoveryStreamComponents_DSDismiss_DSDismiss__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(33);
+/* harmony import */ var content_src_lib_link_menu_options__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(23);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_4__);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+
+
+
+class CollectionCardGrid extends react__WEBPACK_IMPORTED_MODULE_4___default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onDismissClick = this.onDismissClick.bind(this);
+ this.state = {
+ dismissed: false
+ };
+ }
+
+ onDismissClick() {
+ const {
+ data
+ } = this.props;
+
+ if (this.props.dispatch && data && data.spocs && data.spocs.length) {
+ this.setState({
+ dismissed: true
+ });
+ const pos = 0;
+ const source = this.props.type.toUpperCase(); // Grab the available items in the array to dismiss.
+ // This fires a ping for all items available, even if below the fold.
+
+ const spocsData = data.spocs.map(item => ({
+ url: item.url,
+ guid: item.id,
+ shim: item.shim,
+ flight_id: item.flightId
+ }));
+ const blockUrlOption = content_src_lib_link_menu_options__WEBPACK_IMPORTED_MODULE_3__["LinkMenuOptions"].BlockUrls(spocsData, pos, source);
+ const {
+ action,
+ impression,
+ userEvent
+ } = blockUrlOption;
+ this.props.dispatch(action);
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].UserEvent({
+ event: userEvent,
+ source,
+ action_position: pos
+ }));
+
+ if (impression) {
+ this.props.dispatch(impression);
+ }
+ }
+ }
+
+ render() {
+ const {
+ data,
+ dismissible
+ } = this.props;
+
+ if (this.state.dismissed || !data || !data.spocs || !data.spocs[0] || // We only display complete collections.
+ data.spocs.length < 3) {
+ return null;
+ }
+
+ const {
+ spocs,
+ placement,
+ feed
+ } = this.props; // spocs.data is spocs state data, and not an array of spocs.
+
+ const {
+ title,
+ context,
+ sponsored_by_override,
+ sponsor
+ } = spocs.data[placement.name] || {}; // Just in case of bad data, don't display a broken collection.
+
+ if (!title) {
+ return null;
+ }
+
+ let sponsoredByMessage = ""; // If override is not false or an empty string.
+
+ if (sponsored_by_override || sponsored_by_override === "") {
+ // We specifically want to display nothing if the server returns an empty string.
+ // So the server can turn off the label.
+ // This is to support the use cases where the sponsored context is displayed elsewhere.
+ sponsoredByMessage = sponsored_by_override;
+ } else if (sponsor) {
+ sponsoredByMessage = {
+ id: `newtab-label-sponsored-by`,
+ values: {
+ sponsor
+ }
+ };
+ } else if (context) {
+ sponsoredByMessage = context;
+ } // Generally a card grid displays recs with spocs already injected.
+ // Normally it doesn't care which rec is a spoc and which isn't,
+ // it just displays content in a grid.
+ // For collections, we're only displaying a list of spocs.
+ // We don't need to tell the card grid that our list of cards are spocs,
+ // it shouldn't need to care. So we just pass our spocs along as recs.
+ // Think of it as injecting all rec positions with spocs.
+ // Consider maybe making recommendations in CardGrid use a more generic name.
+
+
+ const recsData = {
+ recommendations: data.spocs
+ }; // All cards inside of a collection card grid have a slightly different type.
+ // For the case of interactions to the card grid, we use the type "COLLECTIONCARDGRID".
+ // Example, you dismiss the whole collection, we use the type "COLLECTIONCARDGRID".
+ // For interactions inside the card grid, example, you dismiss a single card in the collection,
+ // we use the type "COLLECTIONCARDGRID_CARD".
+
+ const type = `${this.props.type}_card`;
+ const collectionGrid = react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("div", {
+ className: "ds-collection-card-grid"
+ }, react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement(content_src_components_DiscoveryStreamComponents_CardGrid_CardGrid__WEBPACK_IMPORTED_MODULE_1__["CardGrid"], {
+ title: title,
+ context: sponsoredByMessage,
+ data: recsData,
+ feed: feed,
+ border: this.props.border,
+ type: type,
+ is_collection: true,
+ dispatch: this.props.dispatch,
+ items: this.props.items
+ }));
+
+ if (dismissible) {
+ return react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement(content_src_components_DiscoveryStreamComponents_DSDismiss_DSDismiss__WEBPACK_IMPORTED_MODULE_2__["DSDismiss"], {
+ onDismissClick: this.onDismissClick,
+ extraClasses: `ds-dismiss-ds-collection`
+ }, collectionGrid);
+ }
+
+ return collectionGrid;
+ }
+
+}
+
+/***/ }),
+/* 33 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DSDismiss", function() { return DSDismiss; });
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+class DSDismiss extends react__WEBPACK_IMPORTED_MODULE_0___default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onDismissClick = this.onDismissClick.bind(this);
+ this.onHover = this.onHover.bind(this);
+ this.offHover = this.offHover.bind(this);
+ this.state = {
+ hovering: false
+ };
+ }
+
+ onDismissClick() {
+ if (this.props.onDismissClick) {
+ this.props.onDismissClick();
+ }
+ }
+
+ onHover() {
+ this.setState({
+ hovering: true
+ });
+ }
+
+ offHover() {
+ this.setState({
+ hovering: false
+ });
+ }
+
+ render() {
+ let className = `ds-dismiss
+ ${this.state.hovering ? ` hovering` : ``}
+ ${this.props.extraClasses ? ` ${this.props.extraClasses}` : ``}`;
+ return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
+ className: className
+ }, this.props.children, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("button", {
+ className: "ds-dismiss-button",
+ "data-l10n-id": "newtab-dismiss-button-tooltip",
+ onHover: this.onHover,
+ onClick: this.onDismissClick,
+ onMouseEnter: this.onHover,
+ onMouseLeave: this.offHover
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", {
+ className: "icon icon-dismiss"
+ })));
+ }
+
+}
+
+/***/ }),
+/* 34 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* WEBPACK VAR INJECTION */(function(global) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_CollapsibleSection", function() { return _CollapsibleSection; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CollapsibleSection", function() { return CollapsibleSection; });
+/* harmony import */ var common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
+/* harmony import */ var content_src_components_ErrorBoundary_ErrorBoundary__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(35);
+/* harmony import */ var content_src_components_FluentOrText_FluentOrText__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(30);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_3__);
+/* harmony import */ var react_redux__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(7);
+/* harmony import */ var react_redux__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(react_redux__WEBPACK_IMPORTED_MODULE_4__);
+/* harmony import */ var content_src_components_SectionMenu_SectionMenu__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(37);
+/* harmony import */ var content_src_lib_section_menu_options__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(38);
+/* harmony import */ var content_src_components_ContextMenu_ContextMenuButton__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(24);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+
+
+
+
+
+
+const VISIBLE = "visible";
+const VISIBILITY_CHANGE_EVENT = "visibilitychange";
+class _CollapsibleSection extends react__WEBPACK_IMPORTED_MODULE_3___default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onBodyMount = this.onBodyMount.bind(this);
+ this.collapseOrExpandSection = this.collapseOrExpandSection.bind(this);
+ this.onHeaderClick = this.onHeaderClick.bind(this);
+ this.onKeyPress = this.onKeyPress.bind(this);
+ this.onTransitionEnd = this.onTransitionEnd.bind(this);
+ this.enableOrDisableAnimation = this.enableOrDisableAnimation.bind(this);
+ this.onMenuButtonMouseEnter = this.onMenuButtonMouseEnter.bind(this);
+ this.onMenuButtonMouseLeave = this.onMenuButtonMouseLeave.bind(this);
+ this.onMenuUpdate = this.onMenuUpdate.bind(this);
+ this.state = {
+ enableAnimation: true,
+ isAnimating: false,
+ menuButtonHover: false,
+ showContextMenu: false
+ };
+ this.setContextMenuButtonRef = this.setContextMenuButtonRef.bind(this);
+ }
+
+ componentWillMount() {
+ this.props.document.addEventListener(VISIBILITY_CHANGE_EVENT, this.enableOrDisableAnimation);
+ }
+
+ componentWillUpdate(nextProps) {
+ // Check if we're about to go from expanded to collapsed
+ if (!this.props.collapsed && nextProps.collapsed) {
+ // This next line forces a layout flush of the section body, which has a
+ // max-height style set, so that the upcoming collapse animation can
+ // animate from that height to the collapsed height. Without this, the
+ // update is coalesced and there's no animation from no-max-height to 0.
+ this.sectionBody.scrollHeight; // eslint-disable-line no-unused-expressions
+ }
+ }
+
+ setContextMenuButtonRef(element) {
+ this.contextMenuButtonRef = element;
+ }
+
+ componentDidMount() {
+ if (!this.props.Prefs.values["newNewtabExperience.enabled"]) {
+ this.contextMenuButtonRef.addEventListener("mouseenter", this.onMenuButtonMouseEnter);
+ this.contextMenuButtonRef.addEventListener("mouseleave", this.onMenuButtonMouseLeave);
+ }
+ }
+
+ componentWillUnmount() {
+ this.props.document.removeEventListener(VISIBILITY_CHANGE_EVENT, this.enableOrDisableAnimation);
+
+ if (!this.props.Prefs.values["newNewtabExperience.enabled"]) {
+ this.contextMenuButtonRef.removeEventListener("mouseenter", this.onMenuButtonMouseEnter);
+ this.contextMenuButtonRef.removeEventListener("mouseleave", this.onMenuButtonMouseLeave);
+ }
+ }
+
+ enableOrDisableAnimation() {
+ // Only animate the collapse/expand for visible tabs.
+ const visible = this.props.document.visibilityState === VISIBLE;
+
+ if (this.state.enableAnimation !== visible) {
+ this.setState({
+ enableAnimation: visible
+ });
+ }
+ }
+
+ onBodyMount(node) {
+ this.sectionBody = node;
+ }
+
+ collapseOrExpandSection() {
+ // If this.sectionBody is unset, it means that we're in some sort of error
+ // state, probably displaying the error fallback, so we won't be able to
+ // compute the height, and we don't want to persist the preference.
+ if (!this.sectionBody) {
+ return;
+ } // Get the current height of the body so max-height transitions can work
+
+
+ this.setState({
+ isAnimating: true,
+ maxHeight: `${this._getSectionBodyHeight()}px`
+ });
+ const {
+ action
+ } = content_src_lib_section_menu_options__WEBPACK_IMPORTED_MODULE_6__["SectionMenuOptions"].CheckCollapsed(this.props);
+ this.props.dispatch(action);
+ }
+
+ onHeaderClick() {
+ // If the new new tab experience pref is turned on,
+ // sections should not be collapsible.
+ // If this.sectionBody is unset, it means that we're in some sort of error
+ // state, probably displaying the error fallback, so we won't be able to
+ // compute the height, and we don't want to persist the preference.
+ // If props.collapsed is undefined handler shouldn't do anything.
+ if (this.props.Prefs.values["newNewtabExperience.enabled"] || !this.sectionBody || this.props.collapsed === undefined) {
+ return;
+ }
+
+ this.collapseOrExpandSection();
+ const {
+ userEvent
+ } = content_src_lib_section_menu_options__WEBPACK_IMPORTED_MODULE_6__["SectionMenuOptions"].CheckCollapsed(this.props);
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].UserEvent({
+ event: userEvent,
+ source: this.props.eventSource
+ }));
+ }
+
+ onKeyPress(event) {
+ if (event.key === "Enter" || event.key === " ") {
+ event.preventDefault();
+ this.onHeaderClick();
+ }
+ }
+
+ _getSectionBodyHeight() {
+ const div = this.sectionBody;
+
+ if (div.style.display === "none") {
+ // If the div isn't displayed, we can't get it's height. So we display it
+ // to get the height (it doesn't show up because max-height is set to 0px
+ // in CSS). We don't undo this because we are about to expand the section.
+ div.style.display = "block";
+ }
+
+ return div.scrollHeight;
+ }
+
+ onTransitionEnd(event) {
+ // Only update the animating state for our own transition (not a child's)
+ if (event.target === event.currentTarget) {
+ this.setState({
+ isAnimating: false
+ });
+ }
+ }
+
+ renderIcon() {
+ const {
+ icon
+ } = this.props;
+
+ if (icon && icon.startsWith("moz-extension://")) {
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("span", {
+ className: "icon icon-small-spacer",
+ style: {
+ backgroundImage: `url('${icon}')`
+ }
+ });
+ }
+
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("span", {
+ className: `icon icon-small-spacer icon-${icon || "webextension"}`
+ });
+ }
+
+ onMenuButtonMouseEnter() {
+ this.setState({
+ menuButtonHover: true
+ });
+ }
+
+ onMenuButtonMouseLeave() {
+ this.setState({
+ menuButtonHover: false
+ });
+ }
+
+ onMenuUpdate(showContextMenu) {
+ this.setState({
+ showContextMenu
+ });
+ }
+
+ render() {
+ const isCollapsible = this.props.collapsed !== undefined;
+ const isNewNewtabExperienceEnabled = this.props.Prefs.values["newNewtabExperience.enabled"]; // If new new tab prefs are set to true, sections should not be
+ // collapsible. Expand and make the section visible, if it has been
+ // previously collapsed.
+
+ if (isNewNewtabExperienceEnabled && this.props.collapsed) {
+ this.collapseOrExpandSection();
+ }
+
+ const {
+ enableAnimation,
+ isAnimating,
+ maxHeight,
+ menuButtonHover,
+ showContextMenu
+ } = this.state;
+ const {
+ id,
+ eventSource,
+ collapsed,
+ learnMore,
+ title,
+ extraMenuOptions,
+ showPrefName,
+ privacyNoticeURL,
+ dispatch,
+ isFixed,
+ isFirst,
+ isLast,
+ isWebExtension
+ } = this.props;
+ const active = menuButtonHover || showContextMenu;
+ let bodyStyle;
+
+ if (isAnimating && !collapsed) {
+ bodyStyle = {
+ maxHeight
+ };
+ } else if (!isAnimating && collapsed) {
+ bodyStyle = {
+ display: "none"
+ };
+ }
+
+ let titleStyle;
+
+ if (this.props.hideTitle) {
+ titleStyle = {
+ visibility: "hidden"
+ };
+ }
+
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("section", {
+ className: `collapsible-section ${this.props.className}${enableAnimation ? " animation-enabled" : ""}${collapsed ? " collapsed" : ""}${active ? " active" : ""}`,
+ "aria-expanded": !collapsed // Note: data-section-id is used for web extension api tests in mozilla central
+ ,
+ "data-section-id": id
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("div", {
+ className: "section-top-bar"
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("h3", {
+ className: "section-title",
+ style: titleStyle
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("span", {
+ className: "click-target-container"
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("span", {
+ className: "click-target",
+ role: "button",
+ tabIndex: "0",
+ onKeyPress: this.onKeyPress,
+ onClick: this.onHeaderClick
+ }, !isNewNewtabExperienceEnabled && this.renderIcon(), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(content_src_components_FluentOrText_FluentOrText__WEBPACK_IMPORTED_MODULE_2__["FluentOrText"], {
+ message: title
+ }), !isNewNewtabExperienceEnabled && isCollapsible && react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("span", {
+ "data-l10n-id": collapsed ? "newtab-section-expand-section-label" : "newtab-section-collapse-section-label",
+ className: `collapsible-arrow icon ${collapsed ? "icon-arrowhead-forward-small" : "icon-arrowhead-down-small"}`
+ })), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("span", {
+ className: "learn-more-link-wrapper"
+ }, learnMore && react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("span", {
+ className: "learn-more-link"
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(content_src_components_FluentOrText_FluentOrText__WEBPACK_IMPORTED_MODULE_2__["FluentOrText"], {
+ message: learnMore.link.message
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("a", {
+ href: learnMore.link.href
+ })))))), !isNewNewtabExperienceEnabled && react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("div", null, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(content_src_components_ContextMenu_ContextMenuButton__WEBPACK_IMPORTED_MODULE_7__["ContextMenuButton"], {
+ tooltip: "newtab-menu-section-tooltip",
+ onUpdate: this.onMenuUpdate,
+ refFunction: this.setContextMenuButtonRef
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(content_src_components_SectionMenu_SectionMenu__WEBPACK_IMPORTED_MODULE_5__["SectionMenu"], {
+ id: id,
+ extraOptions: extraMenuOptions,
+ source: eventSource,
+ showPrefName: showPrefName,
+ privacyNoticeURL: privacyNoticeURL,
+ collapsed: collapsed,
+ isFixed: isFixed,
+ isFirst: isFirst,
+ isLast: isLast,
+ dispatch: dispatch,
+ isWebExtension: isWebExtension
+ })))), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(content_src_components_ErrorBoundary_ErrorBoundary__WEBPACK_IMPORTED_MODULE_1__["ErrorBoundary"], {
+ className: "section-body-fallback"
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("div", {
+ className: `section-body${isAnimating ? " animating" : ""}`,
+ onTransitionEnd: this.onTransitionEnd,
+ ref: this.onBodyMount,
+ style: bodyStyle
+ }, this.props.children)));
+ }
+
+}
+_CollapsibleSection.defaultProps = {
+ document: global.document || {
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ visibilityState: "hidden"
+ }
+};
+const CollapsibleSection = Object(react_redux__WEBPACK_IMPORTED_MODULE_4__["connect"])(state => ({
+ Prefs: state.Prefs
+}))(_CollapsibleSection);
+/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(3)))
+
+/***/ }),
+/* 35 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ErrorBoundaryFallback", function() { return ErrorBoundaryFallback; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ErrorBoundary", function() { return ErrorBoundary; });
+/* harmony import */ var content_src_components_A11yLinkButton_A11yLinkButton__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+class ErrorBoundaryFallback extends react__WEBPACK_IMPORTED_MODULE_1___default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.windowObj = this.props.windowObj || window;
+ this.onClick = this.onClick.bind(this);
+ }
+ /**
+ * Since we only get here if part of the page has crashed, do a
+ * forced reload to give us the best chance at recovering.
+ */
+
+
+ onClick() {
+ this.windowObj.location.reload(true);
+ }
+
+ render() {
+ const defaultClass = "as-error-fallback";
+ let className;
+
+ if ("className" in this.props) {
+ className = `${this.props.className} ${defaultClass}`;
+ } else {
+ className = defaultClass;
+ } // "A11yLinkButton" to force normal link styling stuff (eg cursor on hover)
+
+
+ return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", {
+ className: className
+ }, react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", {
+ "data-l10n-id": "newtab-error-fallback-info"
+ }), react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", null, react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(content_src_components_A11yLinkButton_A11yLinkButton__WEBPACK_IMPORTED_MODULE_0__["A11yLinkButton"], {
+ className: "reload-button",
+ onClick: this.onClick,
+ "data-l10n-id": "newtab-error-fallback-refresh-link"
+ })));
+ }
+
+}
+ErrorBoundaryFallback.defaultProps = {
+ className: "as-error-fallback"
+};
+class ErrorBoundary extends react__WEBPACK_IMPORTED_MODULE_1___default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.state = {
+ hasError: false
+ };
+ }
+
+ componentDidCatch(error, info) {
+ this.setState({
+ hasError: true
+ });
+ }
+
+ render() {
+ if (!this.state.hasError) {
+ return this.props.children;
+ }
+
+ return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(this.props.FallbackComponent, {
+ className: this.props.className
+ });
+ }
+
+}
+ErrorBoundary.defaultProps = {
+ FallbackComponent: ErrorBoundaryFallback
+};
+
+/***/ }),
+/* 36 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "A11yLinkButton", function() { return A11yLinkButton; });
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
+function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
+
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+function A11yLinkButton(props) {
+ // function for merging classes, if necessary
+ let className = "a11y-link-button";
+
+ if (props.className) {
+ className += ` ${props.className}`;
+ }
+
+ return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("button", _extends({
+ type: "button"
+ }, props, {
+ className: className
+ }), props.children);
+}
+
+/***/ }),
+/* 37 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_SectionMenu", function() { return _SectionMenu; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SectionMenu", function() { return SectionMenu; });
+/* harmony import */ var common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
+/* harmony import */ var content_src_components_ContextMenu_ContextMenu__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(22);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_2__);
+/* harmony import */ var react_redux__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(7);
+/* harmony import */ var react_redux__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(react_redux__WEBPACK_IMPORTED_MODULE_3__);
+/* harmony import */ var content_src_lib_section_menu_options__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(38);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+
+
+
+const DEFAULT_SECTION_MENU_OPTIONS = ["MoveUp", "MoveDown", "Separator", "RemoveSection", "CheckCollapsed", "Separator", "ManageSection"];
+const WEBEXT_SECTION_MENU_OPTIONS = ["MoveUp", "MoveDown", "Separator", "CheckCollapsed", "Separator", "ManageWebExtension"];
+class _SectionMenu extends react__WEBPACK_IMPORTED_MODULE_2___default.a.PureComponent {
+ handleAddWhileCollapsed() {
+ const {
+ action,
+ userEvent
+ } = content_src_lib_section_menu_options__WEBPACK_IMPORTED_MODULE_4__["SectionMenuOptions"].ExpandSection(this.props);
+ this.props.dispatch(action);
+
+ if (userEvent) {
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].UserEvent({
+ event: userEvent,
+ source: this.props.source
+ }));
+ }
+ }
+
+ getOptions() {
+ const {
+ props
+ } = this;
+ const propOptions = props.isWebExtension ? [...WEBEXT_SECTION_MENU_OPTIONS] : [...DEFAULT_SECTION_MENU_OPTIONS]; // Remove Collapse/Expand related option if the `newNewtabExperience.enabled`
+ // pref is set to true.
+
+ if (props.Prefs.values["newNewtabExperience.enabled"]) {
+ if (props.isWebExtension) {
+ propOptions.splice(2, 2);
+ } else {
+ propOptions.splice(4, 1);
+ }
+ } // Remove the move related options if the section is fixed
+
+
+ if (props.isFixed) {
+ propOptions.splice(propOptions.indexOf("MoveUp"), 3);
+ } // Prepend custom options and a separator
+
+
+ if (props.extraOptions) {
+ propOptions.splice(0, 0, ...props.extraOptions, "Separator");
+ } // Insert privacy notice before the last option ("ManageSection")
+
+
+ if (props.privacyNoticeURL) {
+ propOptions.splice(-1, 0, "PrivacyNotice");
+ }
+
+ const options = propOptions.map(o => content_src_lib_section_menu_options__WEBPACK_IMPORTED_MODULE_4__["SectionMenuOptions"][o](props)).map(option => {
+ const {
+ action,
+ id,
+ type,
+ userEvent
+ } = option;
+
+ if (!type && id) {
+ option.onClick = () => {
+ const hasAddEvent = userEvent === "MENU_ADD_TOPSITE" || userEvent === "MENU_ADD_SEARCH";
+
+ if (props.collapsed && hasAddEvent) {
+ this.handleAddWhileCollapsed();
+ }
+
+ props.dispatch(action);
+
+ if (userEvent) {
+ props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].UserEvent({
+ event: userEvent,
+ source: props.source
+ }));
+ }
+ };
+ }
+
+ return option;
+ }); // This is for accessibility to support making each item tabbable.
+ // We want to know which item is the first and which item
+ // is the last, so we can close the context menu accordingly.
+
+ options[0].first = true;
+ options[options.length - 1].last = true;
+ return options;
+ }
+
+ render() {
+ return react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement(content_src_components_ContextMenu_ContextMenu__WEBPACK_IMPORTED_MODULE_1__["ContextMenu"], {
+ onUpdate: this.props.onUpdate,
+ options: this.getOptions(),
+ keyboardAccess: this.props.keyboardAccess
+ });
+ }
+
+}
+const SectionMenu = Object(react_redux__WEBPACK_IMPORTED_MODULE_3__["connect"])(state => ({
+ Prefs: state.Prefs
+}))(_SectionMenu);
+
+/***/ }),
+/* 38 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SectionMenuOptions", function() { return SectionMenuOptions; });
+/* harmony import */ var common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/**
+ * List of functions that return items that can be included as menu options in a
+ * SectionMenu. All functions take the section as the only parameter.
+ */
+
+const SectionMenuOptions = {
+ Separator: () => ({
+ type: "separator"
+ }),
+ MoveUp: section => ({
+ id: "newtab-section-menu-move-up",
+ icon: "arrowhead-up",
+ action: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].OnlyToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].SECTION_MOVE,
+ data: {
+ id: section.id,
+ direction: -1
+ }
+ }),
+ userEvent: "MENU_MOVE_UP",
+ disabled: !!section.isFirst
+ }),
+ MoveDown: section => ({
+ id: "newtab-section-menu-move-down",
+ icon: "arrowhead-down",
+ action: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].OnlyToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].SECTION_MOVE,
+ data: {
+ id: section.id,
+ direction: +1
+ }
+ }),
+ userEvent: "MENU_MOVE_DOWN",
+ disabled: !!section.isLast
+ }),
+ RemoveSection: section => ({
+ id: "newtab-section-menu-remove-section",
+ icon: "dismiss",
+ action: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].SetPref(section.showPrefName, false),
+ userEvent: "MENU_REMOVE"
+ }),
+ CollapseSection: section => ({
+ id: "newtab-section-menu-collapse-section",
+ icon: "minimize",
+ action: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].OnlyToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].UPDATE_SECTION_PREFS,
+ data: {
+ id: section.id,
+ value: {
+ collapsed: true
+ }
+ }
+ }),
+ userEvent: "MENU_COLLAPSE"
+ }),
+ ExpandSection: section => ({
+ id: "newtab-section-menu-expand-section",
+ icon: "maximize",
+ action: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].OnlyToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].UPDATE_SECTION_PREFS,
+ data: {
+ id: section.id,
+ value: {
+ collapsed: false
+ }
+ }
+ }),
+ userEvent: "MENU_EXPAND"
+ }),
+ ManageSection: section => ({
+ id: "newtab-section-menu-manage-section",
+ icon: "settings",
+ action: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].OnlyToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].SETTINGS_OPEN
+ }),
+ userEvent: "MENU_MANAGE"
+ }),
+ ManageWebExtension: section => ({
+ id: "newtab-section-menu-manage-webext",
+ icon: "settings",
+ action: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].OnlyToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].OPEN_WEBEXT_SETTINGS,
+ data: section.id
+ })
+ }),
+ AddTopSite: section => ({
+ id: "newtab-section-menu-add-topsite",
+ icon: "add",
+ action: {
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].TOP_SITES_EDIT,
+ data: {
+ index: -1
+ }
+ },
+ userEvent: "MENU_ADD_TOPSITE"
+ }),
+ AddSearchShortcut: section => ({
+ id: "newtab-section-menu-add-search-engine",
+ icon: "search",
+ action: {
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].TOP_SITES_OPEN_SEARCH_SHORTCUTS_MODAL
+ },
+ userEvent: "MENU_ADD_SEARCH"
+ }),
+ PrivacyNotice: section => ({
+ id: "newtab-section-menu-privacy-notice",
+ icon: "info",
+ action: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].OnlyToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].OPEN_LINK,
+ data: {
+ url: section.privacyNoticeURL
+ }
+ }),
+ userEvent: "MENU_PRIVACY_NOTICE"
+ }),
+ CheckCollapsed: section => section.collapsed ? SectionMenuOptions.ExpandSection(section) : SectionMenuOptions.CollapseSection(section)
+};
+
+/***/ }),
+/* 39 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DSMessage", function() { return DSMessage; });
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
+/* harmony import */ var _SafeAnchor_SafeAnchor__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(26);
+/* harmony import */ var content_src_components_FluentOrText_FluentOrText__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(30);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+
+class DSMessage extends react__WEBPACK_IMPORTED_MODULE_0___default.a.PureComponent {
+ render() {
+ return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
+ className: "ds-message"
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("header", {
+ className: "title"
+ }, this.props.icon && react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
+ className: "glyph",
+ style: {
+ backgroundImage: `url(${this.props.icon})`
+ }
+ }), this.props.title && react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", {
+ className: "title-text"
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(content_src_components_FluentOrText_FluentOrText__WEBPACK_IMPORTED_MODULE_2__["FluentOrText"], {
+ message: this.props.title
+ })), this.props.link_text && this.props.link_url && react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_SafeAnchor_SafeAnchor__WEBPACK_IMPORTED_MODULE_1__["SafeAnchor"], {
+ className: "link",
+ url: this.props.link_url
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(content_src_components_FluentOrText_FluentOrText__WEBPACK_IMPORTED_MODULE_2__["FluentOrText"], {
+ message: this.props.link_text
+ }))));
+ }
+
+}
+
+/***/ }),
+/* 40 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DSPrivacyModal", function() { return DSPrivacyModal; });
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
+/* harmony import */ var common_Actions_jsm__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1);
+/* harmony import */ var content_src_asrouter_components_ModalOverlay_ModalOverlay__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(41);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+
+class DSPrivacyModal extends react__WEBPACK_IMPORTED_MODULE_0___default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.closeModal = this.closeModal.bind(this);
+ this.onLearnLinkClick = this.onLearnLinkClick.bind(this);
+ this.onManageLinkClick = this.onManageLinkClick.bind(this);
+ }
+
+ onLearnLinkClick(event) {
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_1__["actionCreators"].UserEvent({
+ event: "CLICK_PRIVACY_INFO",
+ source: "DS_PRIVACY_MODAL"
+ }));
+ }
+
+ onManageLinkClick(event) {
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_1__["actionCreators"].OnlyToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_1__["actionTypes"].SETTINGS_OPEN
+ }));
+ }
+
+ closeModal() {
+ this.props.dispatch({
+ type: `HIDE_PRIVACY_INFO`,
+ data: {}
+ });
+ }
+
+ render() {
+ return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(content_src_asrouter_components_ModalOverlay_ModalOverlay__WEBPACK_IMPORTED_MODULE_2__["ModalOverlayWrapper"], {
+ onClose: this.closeModal,
+ innerClassName: "ds-privacy-modal"
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
+ className: "privacy-notice"
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("h3", {
+ "data-l10n-id": "newtab-privacy-modal-header"
+ }), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("p", {
+ "data-l10n-id": "newtab-privacy-modal-paragraph-2"
+ }), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("a", {
+ className: "modal-link modal-link-privacy",
+ "data-l10n-id": "newtab-privacy-modal-link",
+ onClick: this.onLearnLinkClick,
+ href: "https://help.getpocket.com/article/1142-firefox-new-tab-recommendations-faq"
+ }), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("button", {
+ className: "modal-link modal-link-manage",
+ "data-l10n-id": "newtab-privacy-modal-button-manage",
+ onClick: this.onManageLinkClick
+ })), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("section", {
+ className: "actions"
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("button", {
+ className: "done",
+ type: "submit",
+ onClick: this.closeModal,
+ "data-l10n-id": "newtab-privacy-modal-button-done"
+ })));
+ }
+
+}
+
+/***/ }),
+/* 41 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* WEBPACK VAR INJECTION */(function(global) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ModalOverlayWrapper", function() { return ModalOverlayWrapper; });
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+class ModalOverlayWrapper extends react__WEBPACK_IMPORTED_MODULE_0___default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onKeyDown = this.onKeyDown.bind(this);
+ } // The intended behaviour is to listen for an escape key
+ // but not for a click; see Bug 1582242
+
+
+ onKeyDown(event) {
+ if (event.key === "Escape") {
+ this.props.onClose(event);
+ }
+ }
+
+ componentWillMount() {
+ this.props.document.addEventListener("keydown", this.onKeyDown);
+ this.props.document.body.classList.add("modal-open");
+ }
+
+ componentWillUnmount() {
+ this.props.document.removeEventListener("keydown", this.onKeyDown);
+ this.props.document.body.classList.remove("modal-open");
+ }
+
+ render() {
+ const {
+ props
+ } = this;
+ let className = props.unstyled ? "" : "modalOverlayInner active";
+
+ if (props.innerClassName) {
+ className += ` ${props.innerClassName}`;
+ }
+
+ return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
+ className: "modalOverlayOuter active",
+ onKeyDown: this.onKeyDown,
+ role: "presentation"
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
+ className: className,
+ "aria-labelledby": props.headerId,
+ id: props.id,
+ role: "dialog"
+ }, props.children));
+ }
+
+}
+ModalOverlayWrapper.defaultProps = {
+ document: global.document
+};
+/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(3)))
+
+/***/ }),
+/* 42 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DSSignup", function() { return DSSignup; });
+/* harmony import */ var common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
+/* harmony import */ var content_src_components_LinkMenu_LinkMenu__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(21);
+/* harmony import */ var content_src_components_ContextMenu_ContextMenuButton__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(24);
+/* harmony import */ var _DiscoveryStreamImpressionStats_ImpressionStats__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(25);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_4__);
+/* harmony import */ var _SafeAnchor_SafeAnchor__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(26);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+
+
+
+
+class DSSignup extends react__WEBPACK_IMPORTED_MODULE_4___default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.state = {
+ active: false,
+ lastItem: false
+ };
+ this.onMenuButtonUpdate = this.onMenuButtonUpdate.bind(this);
+ this.onLinkClick = this.onLinkClick.bind(this);
+ this.onMenuShow = this.onMenuShow.bind(this);
+ }
+
+ onMenuButtonUpdate(showContextMenu) {
+ if (!showContextMenu) {
+ this.setState({
+ active: false,
+ lastItem: false
+ });
+ }
+ }
+
+ nextAnimationFrame() {
+ return new Promise(resolve => this.props.windowObj.requestAnimationFrame(resolve));
+ }
+
+ async onMenuShow() {
+ let {
+ lastItem
+ } = this.state; // Wait for next frame before computing scrollMaxX to allow fluent menu strings to be visible
+
+ await this.nextAnimationFrame();
+
+ if (this.props.windowObj.scrollMaxX > 0) {
+ lastItem = true;
+ }
+
+ this.setState({
+ active: true,
+ lastItem
+ });
+ }
+
+ onLinkClick() {
+ const {
+ data
+ } = this.props;
+
+ if (this.props.dispatch && data && data.spocs && data.spocs.length) {
+ const source = this.props.type.toUpperCase(); // Grab the first item in the array as we only have 1 spoc position.
+
+ const [spoc] = data.spocs;
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].UserEvent({
+ event: "CLICK",
+ source,
+ action_position: 0
+ }));
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].ImpressionStats({
+ source,
+ click: 0,
+ tiles: [{
+ id: spoc.id,
+ pos: 0,
+ ...(spoc.shim && spoc.shim.click ? {
+ shim: spoc.shim.click
+ } : {})
+ }]
+ }));
+ }
+ }
+
+ render() {
+ const {
+ data,
+ dispatch,
+ type
+ } = this.props;
+
+ if (!data || !data.spocs || !data.spocs[0]) {
+ return null;
+ } // Grab the first item in the array as we only have 1 spoc position.
+
+
+ const [spoc] = data.spocs;
+ const {
+ title,
+ url,
+ excerpt,
+ flight_id,
+ id,
+ shim
+ } = spoc;
+ const SIGNUP_CONTEXT_MENU_OPTIONS = ["OpenInNewWindow", "OpenInPrivateWindow", "Separator", "BlockUrl", ...(flight_id ? ["ShowPrivacyInfo"] : [])];
+ const outerClassName = ["ds-signup", this.state.active && "active", this.state.lastItem && "last-item"].filter(v => v).join(" ");
+ return react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("div", {
+ className: outerClassName
+ }, react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("div", {
+ className: "ds-signup-content"
+ }, react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("span", {
+ className: "icon icon-small-spacer icon-mail"
+ }), react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("span", null, title, " ", react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement(_SafeAnchor_SafeAnchor__WEBPACK_IMPORTED_MODULE_5__["SafeAnchor"], {
+ className: "ds-chevron-link",
+ dispatch: dispatch,
+ onLinkClick: this.onLinkClick,
+ url: url
+ }, excerpt)), react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement(_DiscoveryStreamImpressionStats_ImpressionStats__WEBPACK_IMPORTED_MODULE_3__["ImpressionStats"], {
+ flightId: flight_id,
+ rows: [{
+ id,
+ pos: 0,
+ shim: shim && shim.impression
+ }],
+ dispatch: dispatch,
+ source: type
+ })), react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement(content_src_components_ContextMenu_ContextMenuButton__WEBPACK_IMPORTED_MODULE_2__["ContextMenuButton"], {
+ tooltip: "newtab-menu-content-tooltip",
+ tooltipArgs: {
+ title
+ },
+ onUpdate: this.onMenuButtonUpdate
+ }, react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement(content_src_components_LinkMenu_LinkMenu__WEBPACK_IMPORTED_MODULE_1__["LinkMenu"], {
+ dispatch: dispatch,
+ index: 0,
+ source: type.toUpperCase(),
+ onShow: this.onMenuShow,
+ options: SIGNUP_CONTEXT_MENU_OPTIONS,
+ shouldSendImpressionStats: true,
+ site: {
+ referrer: "https://getpocket.com/recommendations",
+ title,
+ type,
+ url,
+ guid: id,
+ shim,
+ flight_id
+ }
+ })));
+ }
+
+}
+DSSignup.defaultProps = {
+ windowObj: window // Added to support unit tests
+
+};
+
+/***/ }),
+/* 43 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DSTextPromo", function() { return DSTextPromo; });
+/* harmony import */ var common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
+/* harmony import */ var content_src_components_DiscoveryStreamComponents_DSDismiss_DSDismiss__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(33);
+/* harmony import */ var _DSImage_DSImage_jsx__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(19);
+/* harmony import */ var _DiscoveryStreamImpressionStats_ImpressionStats__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(25);
+/* harmony import */ var content_src_lib_link_menu_options__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(23);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_5__);
+/* harmony import */ var _SafeAnchor_SafeAnchor__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(26);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+
+
+
+
+
+class DSTextPromo extends react__WEBPACK_IMPORTED_MODULE_5___default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onLinkClick = this.onLinkClick.bind(this);
+ this.onDismissClick = this.onDismissClick.bind(this);
+ }
+
+ onLinkClick() {
+ const {
+ data
+ } = this.props;
+
+ if (this.props.dispatch && data && data.spocs && data.spocs.length) {
+ const source = this.props.type.toUpperCase(); // Grab the first item in the array as we only have 1 spoc position.
+
+ const [spoc] = data.spocs;
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].UserEvent({
+ event: "CLICK",
+ source,
+ action_position: 0
+ }));
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].ImpressionStats({
+ source,
+ click: 0,
+ tiles: [{
+ id: spoc.id,
+ pos: 0,
+ ...(spoc.shim && spoc.shim.click ? {
+ shim: spoc.shim.click
+ } : {})
+ }]
+ }));
+ }
+ }
+
+ onDismissClick() {
+ const {
+ data
+ } = this.props;
+
+ if (this.props.dispatch && data && data.spocs && data.spocs.length) {
+ const index = 0;
+ const source = this.props.type.toUpperCase(); // Grab the first item in the array as we only have 1 spoc position.
+
+ const [spoc] = data.spocs;
+ const spocData = {
+ url: spoc.url,
+ guid: spoc.id,
+ shim: spoc.shim
+ };
+ const blockUrlOption = content_src_lib_link_menu_options__WEBPACK_IMPORTED_MODULE_4__["LinkMenuOptions"].BlockUrl(spocData, index, source);
+ const {
+ action,
+ impression,
+ userEvent
+ } = blockUrlOption;
+ this.props.dispatch(action);
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].UserEvent({
+ event: userEvent,
+ source,
+ action_position: index
+ }));
+
+ if (impression) {
+ this.props.dispatch(impression);
+ }
+ }
+ }
+
+ render() {
+ const {
+ data
+ } = this.props;
+
+ if (!data || !data.spocs || !data.spocs[0]) {
+ return null;
+ } // Grab the first item in the array as we only have 1 spoc position.
+
+
+ const [spoc] = data.spocs;
+ const {
+ image_src,
+ raw_image_src,
+ alt_text,
+ title,
+ url,
+ context,
+ cta,
+ flight_id,
+ id,
+ shim
+ } = spoc;
+ return react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement(content_src_components_DiscoveryStreamComponents_DSDismiss_DSDismiss__WEBPACK_IMPORTED_MODULE_1__["DSDismiss"], {
+ onDismissClick: this.onDismissClick,
+ extraClasses: `ds-dismiss-ds-text-promo`
+ }, react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("div", {
+ className: "ds-text-promo"
+ }, react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement(_DSImage_DSImage_jsx__WEBPACK_IMPORTED_MODULE_2__["DSImage"], {
+ alt_text: alt_text,
+ source: image_src,
+ rawSource: raw_image_src
+ }), react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("div", {
+ className: "text"
+ }, react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("h3", null, `${title}\u2003`, react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement(_SafeAnchor_SafeAnchor__WEBPACK_IMPORTED_MODULE_6__["SafeAnchor"], {
+ className: "ds-chevron-link",
+ dispatch: this.props.dispatch,
+ onLinkClick: this.onLinkClick,
+ url: url
+ }, cta)), react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("p", {
+ className: "subtitle"
+ }, context)), react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement(_DiscoveryStreamImpressionStats_ImpressionStats__WEBPACK_IMPORTED_MODULE_3__["ImpressionStats"], {
+ flightId: flight_id,
+ rows: [{
+ id,
+ pos: 0,
+ shim: shim && shim.impression
+ }],
+ dispatch: this.props.dispatch,
+ source: this.props.type
+ })));
+ }
+
+}
+
+/***/ }),
+/* 44 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Hero", function() { return Hero; });
+/* harmony import */ var _DSCard_DSCard_jsx__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(18);
+/* harmony import */ var common_Actions_jsm__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1);
+/* harmony import */ var _DSEmptyState_DSEmptyState_jsx__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(31);
+/* harmony import */ var _DSImage_DSImage_jsx__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(19);
+/* harmony import */ var _DSLinkMenu_DSLinkMenu__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(20);
+/* harmony import */ var _DiscoveryStreamImpressionStats_ImpressionStats__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(25);
+/* harmony import */ var _List_List_jsx__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(45);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_7__);
+/* harmony import */ var _SafeAnchor_SafeAnchor__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(26);
+/* harmony import */ var _DSContextFooter_DSContextFooter_jsx__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(27);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+
+
+
+
+
+
+
+
+class Hero extends react__WEBPACK_IMPORTED_MODULE_7___default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onLinkClick = this.onLinkClick.bind(this);
+ }
+
+ onLinkClick(event) {
+ if (this.props.dispatch) {
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_1__["actionCreators"].UserEvent({
+ event: "CLICK",
+ source: this.props.type.toUpperCase(),
+ action_position: this.heroRec.pos
+ }));
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_1__["actionCreators"].ImpressionStats({
+ source: this.props.type.toUpperCase(),
+ click: 0,
+ tiles: [{
+ id: this.heroRec.id,
+ pos: this.heroRec.pos,
+ ...(this.heroRec.shim && this.heroRec.shim.click ? {
+ shim: this.heroRec.shim.click
+ } : {})
+ }]
+ }));
+ }
+ }
+
+ renderHero() {
+ let [heroRec, ...otherRecs] = this.props.data.recommendations.slice(0, this.props.items);
+ this.heroRec = heroRec;
+ const cards = [];
+
+ for (let index = 0; index < this.props.items - 1; index++) {
+ const rec = otherRecs[index];
+ cards.push(!rec || rec.placeholder ? react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement(_DSCard_DSCard_jsx__WEBPACK_IMPORTED_MODULE_0__["PlaceholderDSCard"], {
+ key: `dscard-${index}`
+ }) : react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement(_DSCard_DSCard_jsx__WEBPACK_IMPORTED_MODULE_0__["DSCard"], {
+ flightId: rec.flight_id,
+ key: `dscard-${rec.id}`,
+ image_src: rec.image_src,
+ raw_image_src: rec.raw_image_src,
+ title: rec.title,
+ url: rec.url,
+ id: rec.id,
+ shim: rec.shim,
+ pos: rec.pos,
+ type: this.props.type,
+ dispatch: this.props.dispatch,
+ context: rec.context,
+ context_type: rec.context_type,
+ source: rec.domain,
+ pocket_id: rec.pocket_id,
+ bookmarkGuid: rec.bookmarkGuid,
+ engagement: rec.engagement
+ }));
+ }
+
+ let heroCard = null;
+
+ if (!heroRec || heroRec.placeholder) {
+ heroCard = react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement(_DSCard_DSCard_jsx__WEBPACK_IMPORTED_MODULE_0__["PlaceholderDSCard"], null);
+ } else {
+ heroCard = react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement("div", {
+ className: "ds-hero-item",
+ key: `dscard-${heroRec.id}`
+ }, react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement(_SafeAnchor_SafeAnchor__WEBPACK_IMPORTED_MODULE_8__["SafeAnchor"], {
+ className: "wrapper",
+ dispatch: this.props.dispatch,
+ onLinkClick: this.onLinkClick,
+ url: heroRec.url
+ }, react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement("div", {
+ className: "img-wrapper"
+ }, react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement(_DSImage_DSImage_jsx__WEBPACK_IMPORTED_MODULE_3__["DSImage"], {
+ extraClassNames: "img",
+ source: heroRec.image_src,
+ rawSource: heroRec.raw_image_src
+ })), react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement("div", {
+ className: "meta"
+ }, react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement("div", {
+ className: "header-and-excerpt"
+ }, react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement("p", {
+ className: "source clamp"
+ }, heroRec.domain), react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement("header", {
+ className: "clamp"
+ }, heroRec.title), react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement("p", {
+ className: "excerpt clamp"
+ }, heroRec.excerpt)), react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement(_DSContextFooter_DSContextFooter_jsx__WEBPACK_IMPORTED_MODULE_9__["DSContextFooter"], {
+ context: heroRec.context,
+ context_type: heroRec.context_type,
+ engagement: heroRec.engagement
+ })), react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement(_DiscoveryStreamImpressionStats_ImpressionStats__WEBPACK_IMPORTED_MODULE_5__["ImpressionStats"], {
+ flightId: heroRec.flight_id,
+ rows: [{
+ id: heroRec.id,
+ pos: heroRec.pos,
+ ...(heroRec.shim && heroRec.shim.impression ? {
+ shim: heroRec.shim.impression
+ } : {})
+ }],
+ dispatch: this.props.dispatch,
+ source: this.props.type
+ })), react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement(_DSLinkMenu_DSLinkMenu__WEBPACK_IMPORTED_MODULE_4__["DSLinkMenu"], {
+ id: heroRec.id,
+ index: heroRec.pos,
+ dispatch: this.props.dispatch,
+ url: heroRec.url,
+ title: heroRec.title,
+ source: heroRec.domain,
+ type: this.props.type,
+ pocket_id: heroRec.pocket_id,
+ shim: heroRec.shim,
+ bookmarkGuid: heroRec.bookmarkGuid,
+ flightId: heroRec.flight_id
+ }));
+ }
+
+ let list = react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement(_List_List_jsx__WEBPACK_IMPORTED_MODULE_6__["List"], {
+ recStartingPoint: 1,
+ data: this.props.data,
+ feed: this.props.feed,
+ hasImages: true,
+ hasBorders: this.props.border === `border`,
+ items: this.props.items - 1,
+ type: `Hero`
+ });
+ return react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement("div", {
+ className: `ds-hero ds-hero-${this.props.border}`
+ }, heroCard, react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement("div", {
+ className: `${this.props.subComponentType}`
+ }, this.props.subComponentType === `cards` ? cards : list));
+ }
+
+ render() {
+ const {
+ data
+ } = this.props; // Handle a render before feed has been fetched by displaying nothing
+
+ if (!data || !data.recommendations) {
+ return react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement("div", null);
+ } // Handle the case where a user has dismissed all recommendations
+
+
+ const isEmpty = data.recommendations.length === 0;
+ return react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement("div", null, react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement("div", {
+ className: "ds-header"
+ }, this.props.title), isEmpty ? react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement("div", {
+ className: "ds-hero empty"
+ }, react__WEBPACK_IMPORTED_MODULE_7___default.a.createElement(_DSEmptyState_DSEmptyState_jsx__WEBPACK_IMPORTED_MODULE_2__["DSEmptyState"], {
+ status: data.status,
+ dispatch: this.props.dispatch,
+ feed: this.props.feed
+ })) : this.renderHero());
+ }
+
+}
+Hero.defaultProps = {
+ data: {},
+ border: `border`,
+ items: 1 // Number of stories to display
+
+};
+
+/***/ }),
+/* 45 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ListItem", function() { return ListItem; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PlaceholderListItem", function() { return PlaceholderListItem; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_List", function() { return _List; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "List", function() { return List; });
+/* harmony import */ var common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
+/* harmony import */ var react_redux__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(7);
+/* harmony import */ var react_redux__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react_redux__WEBPACK_IMPORTED_MODULE_1__);
+/* harmony import */ var _DSEmptyState_DSEmptyState_jsx__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(31);
+/* harmony import */ var _DSImage_DSImage_jsx__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(19);
+/* harmony import */ var _DSLinkMenu_DSLinkMenu__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(20);
+/* harmony import */ var _DiscoveryStreamImpressionStats_ImpressionStats__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(25);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_6__);
+/* harmony import */ var _SafeAnchor_SafeAnchor__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(26);
+/* harmony import */ var _DSContextFooter_DSContextFooter_jsx__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(27);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+
+
+
+
+
+
+
+/**
+ * @note exported for testing only
+ */
+
+class ListItem extends react__WEBPACK_IMPORTED_MODULE_6___default.a.PureComponent {
+ // TODO performance: get feeds to send appropriately sized images rather
+ // than waiting longer and scaling down on client?
+ constructor(props) {
+ super(props);
+ this.onLinkClick = this.onLinkClick.bind(this);
+ }
+
+ onLinkClick(event) {
+ if (this.props.dispatch) {
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].UserEvent({
+ event: "CLICK",
+ source: this.props.type.toUpperCase(),
+ action_position: this.props.pos,
+ value: {
+ card_type: this.props.flightId ? "spoc" : "organic"
+ }
+ }));
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].ImpressionStats({
+ source: this.props.type.toUpperCase(),
+ click: 0,
+ tiles: [{
+ id: this.props.id,
+ pos: this.props.pos,
+ ...(this.props.shim && this.props.shim.click ? {
+ shim: this.props.shim.click
+ } : {})
+ }]
+ }));
+ }
+ }
+
+ render() {
+ return react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("li", {
+ className: `ds-list-item${this.props.placeholder ? " placeholder" : ""}`
+ }, react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement(_SafeAnchor_SafeAnchor__WEBPACK_IMPORTED_MODULE_7__["SafeAnchor"], {
+ className: "ds-list-item-link",
+ dispatch: this.props.dispatch,
+ onLinkClick: !this.props.placeholder ? this.onLinkClick : undefined,
+ url: this.props.url
+ }, react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("div", {
+ className: "ds-list-item-text"
+ }, react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("p", null, react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("span", {
+ className: "ds-list-item-info clamp"
+ }, this.props.domain)), react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("div", {
+ className: "ds-list-item-body"
+ }, react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("div", {
+ className: "ds-list-item-title clamp"
+ }, this.props.title), this.props.excerpt && react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("div", {
+ className: "ds-list-item-excerpt clamp"
+ }, this.props.excerpt)), react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement(_DSContextFooter_DSContextFooter_jsx__WEBPACK_IMPORTED_MODULE_8__["DSContextFooter"], {
+ context: this.props.context,
+ context_type: this.props.context_type,
+ engagement: this.props.engagement
+ })), react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement(_DSImage_DSImage_jsx__WEBPACK_IMPORTED_MODULE_3__["DSImage"], {
+ extraClassNames: "ds-list-image",
+ source: this.props.image_src,
+ rawSource: this.props.raw_image_src
+ }), react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement(_DiscoveryStreamImpressionStats_ImpressionStats__WEBPACK_IMPORTED_MODULE_5__["ImpressionStats"], {
+ flightId: this.props.flightId,
+ rows: [{
+ id: this.props.id,
+ pos: this.props.pos,
+ ...(this.props.shim && this.props.shim.impression ? {
+ shim: this.props.shim.impression
+ } : {})
+ }],
+ dispatch: this.props.dispatch,
+ source: this.props.type
+ })), !this.props.placeholder && react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement(_DSLinkMenu_DSLinkMenu__WEBPACK_IMPORTED_MODULE_4__["DSLinkMenu"], {
+ id: this.props.id,
+ index: this.props.pos,
+ dispatch: this.props.dispatch,
+ url: this.props.url,
+ title: this.props.title,
+ source: this.props.source,
+ type: this.props.type,
+ pocket_id: this.props.pocket_id,
+ shim: this.props.shim,
+ bookmarkGuid: this.props.bookmarkGuid,
+ flightId: this.props.flightId
+ }));
+ }
+
+}
+const PlaceholderListItem = props => react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement(ListItem, {
+ placeholder: true
+});
+/**
+ * @note exported for testing only
+ */
+
+function _List(props) {
+ const renderList = () => {
+ const recs = props.data.recommendations.slice(props.recStartingPoint, props.recStartingPoint + props.items);
+ const recMarkup = [];
+
+ for (let index = 0; index < props.items; index++) {
+ const rec = recs[index];
+ recMarkup.push(!rec || rec.placeholder ? react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement(PlaceholderListItem, {
+ key: `ds-list-item-${index}`
+ }) : react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement(ListItem, {
+ key: `ds-list-item-${rec.id}`,
+ dispatch: props.dispatch,
+ flightId: rec.flight_id,
+ domain: rec.domain,
+ excerpt: rec.excerpt,
+ id: rec.id,
+ shim: rec.shim,
+ image_src: rec.image_src,
+ raw_image_src: rec.raw_image_src,
+ pos: rec.pos,
+ title: rec.title,
+ context: rec.context,
+ context_type: rec.context_type,
+ type: props.type,
+ url: rec.url,
+ pocket_id: rec.pocket_id,
+ bookmarkGuid: rec.bookmarkGuid,
+ engagement: rec.engagement
+ }));
+ }
+
+ const listStyles = ["ds-list", props.fullWidth ? "ds-list-full-width" : "", props.hasBorders ? "ds-list-borders" : "", props.hasImages ? "ds-list-images" : "", props.hasNumbers ? "ds-list-numbers" : ""];
+ return react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("ul", {
+ className: listStyles.join(" ")
+ }, recMarkup);
+ };
+
+ const {
+ data
+ } = props;
+
+ if (!data || !data.recommendations) {
+ return null;
+ } // Handle the case where a user has dismissed all recommendations
+
+
+ const isEmpty = data.recommendations.length === 0;
+ return react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("div", null, props.header && props.header.title ? react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("div", {
+ className: "ds-header"
+ }, props.header.title) : null, isEmpty ? react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("div", {
+ className: "ds-list empty"
+ }, react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement(_DSEmptyState_DSEmptyState_jsx__WEBPACK_IMPORTED_MODULE_2__["DSEmptyState"], {
+ status: data.status,
+ dispatch: props.dispatch,
+ feed: props.feed
+ })) : renderList());
+}
+_List.defaultProps = {
+ recStartingPoint: 0,
+ // Index of recommendations to start displaying from
+ fullWidth: false,
+ // Display items taking up the whole column
+ hasBorders: false,
+ // Display lines separating each item
+ hasImages: false,
+ // Display images for each item
+ hasNumbers: false,
+ // Display numbers for each item
+ items: 6 // Number of stories to display. TODO: get from endpoint
+
+};
+const List = Object(react_redux__WEBPACK_IMPORTED_MODULE_1__["connect"])(state => ({
+ DiscoveryStream: state.DiscoveryStream
+}))(_List);
+
+/***/ }),
+/* 46 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_Highlights", function() { return _Highlights; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Highlights", function() { return Highlights; });
+/* harmony import */ var react_redux__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(7);
+/* harmony import */ var react_redux__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react_redux__WEBPACK_IMPORTED_MODULE_0__);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
+/* harmony import */ var content_src_components_Sections_Sections__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(47);
+function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
+
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+
+class _Highlights extends react__WEBPACK_IMPORTED_MODULE_1___default.a.PureComponent {
+ render() {
+ const section = this.props.Sections.find(s => s.id === "highlights");
+
+ if (!section || !section.enabled) {
+ return null;
+ }
+
+ return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", {
+ className: "ds-highlights sections-list"
+ }, react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(content_src_components_Sections_Sections__WEBPACK_IMPORTED_MODULE_2__["SectionIntl"], _extends({}, section, {
+ isFixed: true
+ })));
+ }
+
+}
+const Highlights = Object(react_redux__WEBPACK_IMPORTED_MODULE_0__["connect"])(state => ({
+ Sections: state.Sections
+}))(_Highlights);
+
+/***/ }),
+/* 47 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* WEBPACK VAR INJECTION */(function(global) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Section", function() { return Section; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SectionIntl", function() { return SectionIntl; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_Sections", function() { return _Sections; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Sections", function() { return Sections; });
+/* harmony import */ var common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
+/* harmony import */ var content_src_components_Card_Card__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(48);
+/* harmony import */ var content_src_components_CollapsibleSection_CollapsibleSection__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(34);
+/* harmony import */ var content_src_components_ComponentPerfTimer_ComponentPerfTimer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(50);
+/* harmony import */ var content_src_components_FluentOrText_FluentOrText__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(30);
+/* harmony import */ var react_redux__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(7);
+/* harmony import */ var react_redux__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(react_redux__WEBPACK_IMPORTED_MODULE_5__);
+/* harmony import */ var content_src_components_MoreRecommendations_MoreRecommendations__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(52);
+/* harmony import */ var content_src_components_PocketLoggedInCta_PocketLoggedInCta__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(53);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_8__);
+/* harmony import */ var content_src_components_Topics_Topics__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(54);
+/* harmony import */ var content_src_components_TopSites_TopSites__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(55);
+function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
+
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+
+
+
+
+
+
+
+
+
+const VISIBLE = "visible";
+const VISIBILITY_CHANGE_EVENT = "visibilitychange";
+const CARDS_PER_ROW_DEFAULT = 3;
+const CARDS_PER_ROW_COMPACT_WIDE = 4;
+class Section extends react__WEBPACK_IMPORTED_MODULE_8___default.a.PureComponent {
+ get numRows() {
+ const {
+ rowsPref,
+ maxRows,
+ Prefs
+ } = this.props;
+ return rowsPref ? Prefs.values[rowsPref] : maxRows;
+ }
+
+ _dispatchImpressionStats() {
+ const {
+ props
+ } = this;
+ let cardsPerRow = CARDS_PER_ROW_DEFAULT;
+
+ if (props.compactCards && global.matchMedia(`(min-width: 1072px)`).matches) {
+ // If the section has compact cards and the viewport is wide enough, we show
+ // 4 columns instead of 3.
+ // $break-point-widest = 1072px (from _variables.scss)
+ cardsPerRow = CARDS_PER_ROW_COMPACT_WIDE;
+ }
+
+ const maxCards = cardsPerRow * this.numRows;
+ const cards = props.rows.slice(0, maxCards);
+
+ if (this.needsImpressionStats(cards)) {
+ props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].ImpressionStats({
+ source: props.eventSource,
+ tiles: cards.map(link => ({
+ id: link.guid
+ }))
+ }));
+ this.impressionCardGuids = cards.map(link => link.guid);
+ }
+ } // This sends an event when a user sees a set of new content. If content
+ // changes while the page is hidden (i.e. preloaded or on a hidden tab),
+ // only send the event if the page becomes visible again.
+
+
+ sendImpressionStatsOrAddListener() {
+ const {
+ props
+ } = this;
+
+ if (!props.shouldSendImpressionStats || !props.dispatch) {
+ return;
+ }
+
+ if (props.document.visibilityState === VISIBLE) {
+ this._dispatchImpressionStats();
+ } else {
+ // We should only ever send the latest impression stats ping, so remove any
+ // older listeners.
+ if (this._onVisibilityChange) {
+ props.document.removeEventListener(VISIBILITY_CHANGE_EVENT, this._onVisibilityChange);
+ } // When the page becomes visible, send the impression stats ping if the section isn't collapsed.
+
+
+ this._onVisibilityChange = () => {
+ if (props.document.visibilityState === VISIBLE) {
+ if (!this.props.pref.collapsed) {
+ this._dispatchImpressionStats();
+ }
+
+ props.document.removeEventListener(VISIBILITY_CHANGE_EVENT, this._onVisibilityChange);
+ }
+ };
+
+ props.document.addEventListener(VISIBILITY_CHANGE_EVENT, this._onVisibilityChange);
+ }
+ }
+
+ componentWillMount() {
+ this.sendNewTabRehydrated(this.props.initialized);
+ }
+
+ componentDidMount() {
+ if (this.props.rows.length && !this.props.pref.collapsed) {
+ this.sendImpressionStatsOrAddListener();
+ }
+ }
+
+ componentDidUpdate(prevProps) {
+ const {
+ props
+ } = this;
+ const isCollapsed = props.pref.collapsed;
+ const wasCollapsed = prevProps.pref.collapsed;
+
+ if ( // Don't send impression stats for the empty state
+ props.rows.length && ( // We only want to send impression stats if the content of the cards has changed
+ // and the section is not collapsed...
+ props.rows !== prevProps.rows && !isCollapsed || // or if we are expanding a section that was collapsed.
+ wasCollapsed && !isCollapsed)) {
+ this.sendImpressionStatsOrAddListener();
+ }
+ }
+
+ componentWillUpdate(nextProps) {
+ this.sendNewTabRehydrated(nextProps.initialized);
+ }
+
+ componentWillUnmount() {
+ if (this._onVisibilityChange) {
+ this.props.document.removeEventListener(VISIBILITY_CHANGE_EVENT, this._onVisibilityChange);
+ }
+ }
+
+ needsImpressionStats(cards) {
+ if (!this.impressionCardGuids || this.impressionCardGuids.length !== cards.length) {
+ return true;
+ }
+
+ for (let i = 0; i < cards.length; i++) {
+ if (cards[i].guid !== this.impressionCardGuids[i]) {
+ return true;
+ }
+ }
+
+ return false;
+ } // The NEW_TAB_REHYDRATED event is used to inform feeds that their
+ // data has been consumed e.g. for counting the number of tabs that
+ // have rendered that data.
+
+
+ sendNewTabRehydrated(initialized) {
+ if (initialized && !this.renderNotified) {
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].AlsoToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].NEW_TAB_REHYDRATED,
+ data: {}
+ }));
+ this.renderNotified = true;
+ }
+ }
+
+ render() {
+ const {
+ id,
+ eventSource,
+ title,
+ icon,
+ rows,
+ Pocket,
+ topics,
+ emptyState,
+ dispatch,
+ compactCards,
+ read_more_endpoint,
+ contextMenuOptions,
+ initialized,
+ learnMore,
+ pref,
+ privacyNoticeURL,
+ isFirst,
+ isLast
+ } = this.props;
+ const waitingForSpoc = id === "topstories" && this.props.Pocket.waitingForSpoc;
+ const maxCardsPerRow = compactCards ? CARDS_PER_ROW_COMPACT_WIDE : CARDS_PER_ROW_DEFAULT;
+ const {
+ numRows
+ } = this;
+ const maxCards = maxCardsPerRow * numRows;
+ const maxCardsOnNarrow = CARDS_PER_ROW_DEFAULT * numRows;
+ const {
+ pocketCta,
+ isUserLoggedIn
+ } = Pocket || {};
+ const {
+ useCta
+ } = pocketCta || {}; // Don't display anything until we have a definitve result from Pocket,
+ // to avoid a flash of logged out state while we render.
+
+ const isPocketLoggedInDefined = isUserLoggedIn === true || isUserLoggedIn === false;
+ const hasTopics = topics && !!topics.length;
+ const shouldShowPocketCta = id === "topstories" && useCta && isUserLoggedIn === false; // Show topics only for top stories and if it has loaded with topics.
+ // The classs .top-stories-bottom-container ensures content doesn't shift as things load.
+
+ const shouldShowTopics = id === "topstories" && hasTopics && (useCta && isUserLoggedIn === true || !useCta && isPocketLoggedInDefined); // We use topics to determine language support for read more.
+
+ const shouldShowReadMore = read_more_endpoint && hasTopics;
+ const realRows = rows.slice(0, maxCards); // The empty state should only be shown after we have initialized and there is no content.
+ // Otherwise, we should show placeholders.
+
+ const shouldShowEmptyState = initialized && !rows.length;
+ const cards = [];
+
+ if (!shouldShowEmptyState) {
+ for (let i = 0; i < maxCards; i++) {
+ const link = realRows[i]; // On narrow viewports, we only show 3 cards per row. We'll mark the rest as
+ // .hide-for-narrow to hide in CSS via @media query.
+
+ const className = i >= maxCardsOnNarrow ? "hide-for-narrow" : "";
+ let usePlaceholder = !link; // If we are in the third card and waiting for spoc,
+ // use the placeholder.
+
+ if (!usePlaceholder && i === 2 && waitingForSpoc) {
+ usePlaceholder = true;
+ }
+
+ cards.push(!usePlaceholder ? react__WEBPACK_IMPORTED_MODULE_8___default.a.createElement(content_src_components_Card_Card__WEBPACK_IMPORTED_MODULE_1__["Card"], {
+ key: i,
+ index: i,
+ className: className,
+ dispatch: dispatch,
+ link: link,
+ contextMenuOptions: contextMenuOptions,
+ eventSource: eventSource,
+ shouldSendImpressionStats: this.props.shouldSendImpressionStats,
+ isWebExtension: this.props.isWebExtension
+ }) : react__WEBPACK_IMPORTED_MODULE_8___default.a.createElement(content_src_components_Card_Card__WEBPACK_IMPORTED_MODULE_1__["PlaceholderCard"], {
+ key: i,
+ className: className
+ }));
+ }
+ }
+
+ const sectionClassName = ["section", compactCards ? "compact-cards" : "normal-cards"].join(" "); // <Section> <-- React component
+ // <section> <-- HTML5 element
+
+ return react__WEBPACK_IMPORTED_MODULE_8___default.a.createElement(content_src_components_ComponentPerfTimer_ComponentPerfTimer__WEBPACK_IMPORTED_MODULE_3__["ComponentPerfTimer"], this.props, react__WEBPACK_IMPORTED_MODULE_8___default.a.createElement(content_src_components_CollapsibleSection_CollapsibleSection__WEBPACK_IMPORTED_MODULE_2__["CollapsibleSection"], {
+ className: sectionClassName,
+ icon: icon,
+ title: title,
+ id: id,
+ eventSource: eventSource,
+ collapsed: this.props.pref.collapsed,
+ showPrefName: pref && pref.feed || id,
+ privacyNoticeURL: privacyNoticeURL,
+ Prefs: this.props.Prefs,
+ isFixed: this.props.isFixed,
+ isFirst: isFirst,
+ isLast: isLast,
+ learnMore: learnMore,
+ dispatch: this.props.dispatch,
+ isWebExtension: this.props.isWebExtension
+ }, !shouldShowEmptyState && react__WEBPACK_IMPORTED_MODULE_8___default.a.createElement("ul", {
+ className: "section-list",
+ style: {
+ padding: 0
+ }
+ }, cards), shouldShowEmptyState && react__WEBPACK_IMPORTED_MODULE_8___default.a.createElement("div", {
+ className: "section-empty-state"
+ }, react__WEBPACK_IMPORTED_MODULE_8___default.a.createElement("div", {
+ className: "empty-state"
+ }, emptyState.icon && emptyState.icon.startsWith("moz-extension://") ? react__WEBPACK_IMPORTED_MODULE_8___default.a.createElement("span", {
+ className: "empty-state-icon icon",
+ style: {
+ "background-image": `url('${emptyState.icon}')`
+ }
+ }) : react__WEBPACK_IMPORTED_MODULE_8___default.a.createElement("span", {
+ className: `empty-state-icon icon icon-${emptyState.icon}`
+ }), react__WEBPACK_IMPORTED_MODULE_8___default.a.createElement(content_src_components_FluentOrText_FluentOrText__WEBPACK_IMPORTED_MODULE_4__["FluentOrText"], {
+ message: emptyState.message
+ }, react__WEBPACK_IMPORTED_MODULE_8___default.a.createElement("p", {
+ className: "empty-state-message"
+ })))), id === "topstories" && react__WEBPACK_IMPORTED_MODULE_8___default.a.createElement("div", {
+ className: "top-stories-bottom-container"
+ }, shouldShowTopics && react__WEBPACK_IMPORTED_MODULE_8___default.a.createElement("div", {
+ className: "wrapper-topics"
+ }, react__WEBPACK_IMPORTED_MODULE_8___default.a.createElement(content_src_components_Topics_Topics__WEBPACK_IMPORTED_MODULE_9__["Topics"], {
+ topics: this.props.topics
+ })), shouldShowPocketCta && react__WEBPACK_IMPORTED_MODULE_8___default.a.createElement("div", {
+ className: "wrapper-cta"
+ }, react__WEBPACK_IMPORTED_MODULE_8___default.a.createElement(content_src_components_PocketLoggedInCta_PocketLoggedInCta__WEBPACK_IMPORTED_MODULE_7__["PocketLoggedInCta"], null)), react__WEBPACK_IMPORTED_MODULE_8___default.a.createElement("div", {
+ className: "wrapper-more-recommendations"
+ }, shouldShowReadMore && react__WEBPACK_IMPORTED_MODULE_8___default.a.createElement(content_src_components_MoreRecommendations_MoreRecommendations__WEBPACK_IMPORTED_MODULE_6__["MoreRecommendations"], {
+ read_more_endpoint: read_more_endpoint
+ })))));
+ }
+
+}
+Section.defaultProps = {
+ document: global.document,
+ rows: [],
+ emptyState: {},
+ pref: {},
+ title: ""
+};
+const SectionIntl = Object(react_redux__WEBPACK_IMPORTED_MODULE_5__["connect"])(state => ({
+ Prefs: state.Prefs,
+ Pocket: state.Pocket
+}))(Section);
+class _Sections extends react__WEBPACK_IMPORTED_MODULE_8___default.a.PureComponent {
+ renderSections() {
+ const sections = [];
+ const enabledSections = this.props.Sections.filter(section => section.enabled);
+ const {
+ sectionOrder,
+ "feeds.topsites": showTopSites
+ } = this.props.Prefs.values; // Enabled sections doesn't include Top Sites, so we add it if enabled.
+
+ const expectedCount = enabledSections.length + ~~showTopSites;
+
+ for (const sectionId of sectionOrder.split(",")) {
+ const commonProps = {
+ key: sectionId,
+ isFirst: sections.length === 0,
+ isLast: sections.length === expectedCount - 1
+ };
+
+ if (sectionId === "topsites" && showTopSites) {
+ sections.push(react__WEBPACK_IMPORTED_MODULE_8___default.a.createElement(content_src_components_TopSites_TopSites__WEBPACK_IMPORTED_MODULE_10__["TopSites"], commonProps));
+ } else {
+ const section = enabledSections.find(s => s.id === sectionId);
+
+ if (section) {
+ sections.push(react__WEBPACK_IMPORTED_MODULE_8___default.a.createElement(SectionIntl, _extends({}, section, commonProps)));
+ }
+ }
+ }
+
+ return sections;
+ }
+
+ render() {
+ return react__WEBPACK_IMPORTED_MODULE_8___default.a.createElement("div", {
+ className: "sections-list"
+ }, this.renderSections());
+ }
+
+}
+const Sections = Object(react_redux__WEBPACK_IMPORTED_MODULE_5__["connect"])(state => ({
+ Sections: state.Sections,
+ Prefs: state.Prefs
+}))(_Sections);
+/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(3)))
+
+/***/ }),
+/* 48 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_Card", function() { return _Card; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Card", function() { return Card; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PlaceholderCard", function() { return PlaceholderCard; });
+/* harmony import */ var common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
+/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(28);
+/* harmony import */ var react_redux__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(7);
+/* harmony import */ var react_redux__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react_redux__WEBPACK_IMPORTED_MODULE_2__);
+/* harmony import */ var content_src_components_ContextMenu_ContextMenuButton__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(24);
+/* harmony import */ var content_src_components_LinkMenu_LinkMenu__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(21);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_5__);
+/* harmony import */ var content_src_lib_screenshot_utils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(49);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+
+
+
+
+ // Keep track of pending image loads to only request once
+
+const gImageLoading = new Map();
+/**
+ * Card component.
+ * Cards are found within a Section component and contain information about a link such
+ * as preview image, page title, page description, and some context about if the page
+ * was visited, bookmarked, trending etc...
+ * Each Section can make an unordered list of Cards which will create one instane of
+ * this class. Each card will then get a context menu which reflects the actions that
+ * can be done on this Card.
+ */
+
+class _Card extends react__WEBPACK_IMPORTED_MODULE_5___default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.state = {
+ activeCard: null,
+ imageLoaded: false,
+ cardImage: null
+ };
+ this.onMenuButtonUpdate = this.onMenuButtonUpdate.bind(this);
+ this.onLinkClick = this.onLinkClick.bind(this);
+ }
+ /**
+ * Helper to conditionally load an image and update state when it loads.
+ */
+
+
+ async maybeLoadImage() {
+ // No need to load if it's already loaded or no image
+ const {
+ cardImage
+ } = this.state;
+
+ if (!cardImage) {
+ return;
+ }
+
+ const imageUrl = cardImage.url;
+
+ if (!this.state.imageLoaded) {
+ // Initialize a promise to share a load across multiple card updates
+ if (!gImageLoading.has(imageUrl)) {
+ const loaderPromise = new Promise((resolve, reject) => {
+ const loader = new Image();
+ loader.addEventListener("load", resolve);
+ loader.addEventListener("error", reject);
+ loader.src = imageUrl;
+ }); // Save and remove the promise only while it's pending
+
+ gImageLoading.set(imageUrl, loaderPromise);
+ loaderPromise.catch(ex => ex).then(() => gImageLoading.delete(imageUrl)).catch();
+ } // Wait for the image whether just started loading or reused promise
+
+
+ await gImageLoading.get(imageUrl); // Only update state if we're still waiting to load the original image
+
+ if (content_src_lib_screenshot_utils__WEBPACK_IMPORTED_MODULE_6__["ScreenshotUtils"].isRemoteImageLocal(this.state.cardImage, this.props.link.image) && !this.state.imageLoaded) {
+ this.setState({
+ imageLoaded: true
+ });
+ }
+ }
+ }
+ /**
+ * Helper to obtain the next state based on nextProps and prevState.
+ *
+ * NOTE: Rename this method to getDerivedStateFromProps when we update React
+ * to >= 16.3. We will need to update tests as well. We cannot rename this
+ * method to getDerivedStateFromProps now because there is a mismatch in
+ * the React version that we are using for both testing and production.
+ * (i.e. react-test-render => "16.3.2", react => "16.2.0").
+ *
+ * See https://github.com/airbnb/enzyme/blob/master/packages/enzyme-adapter-react-16/package.json#L43.
+ */
+
+
+ static getNextStateFromProps(nextProps, prevState) {
+ const {
+ image
+ } = nextProps.link;
+ const imageInState = content_src_lib_screenshot_utils__WEBPACK_IMPORTED_MODULE_6__["ScreenshotUtils"].isRemoteImageLocal(prevState.cardImage, image);
+ let nextState = null; // Image is updating.
+
+ if (!imageInState && nextProps.link) {
+ nextState = {
+ imageLoaded: false
+ };
+ }
+
+ if (imageInState) {
+ return nextState;
+ } // Since image was updated, attempt to revoke old image blob URL, if it exists.
+
+
+ content_src_lib_screenshot_utils__WEBPACK_IMPORTED_MODULE_6__["ScreenshotUtils"].maybeRevokeBlobObjectURL(prevState.cardImage);
+ nextState = nextState || {};
+ nextState.cardImage = content_src_lib_screenshot_utils__WEBPACK_IMPORTED_MODULE_6__["ScreenshotUtils"].createLocalImageObject(image);
+ return nextState;
+ }
+
+ onMenuButtonUpdate(isOpen) {
+ if (isOpen) {
+ this.setState({
+ activeCard: this.props.index
+ });
+ } else {
+ this.setState({
+ activeCard: null
+ });
+ }
+ }
+ /**
+ * Report to telemetry additional information about the item.
+ */
+
+
+ _getTelemetryInfo() {
+ // Filter out "history" type for being the default
+ if (this.props.link.type !== "history") {
+ return {
+ value: {
+ card_type: this.props.link.type
+ }
+ };
+ }
+
+ return null;
+ }
+
+ onLinkClick(event) {
+ event.preventDefault();
+ const {
+ altKey,
+ button,
+ ctrlKey,
+ metaKey,
+ shiftKey
+ } = event;
+
+ if (this.props.link.type === "download") {
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].OnlyToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].OPEN_DOWNLOAD_FILE,
+ data: Object.assign(this.props.link, {
+ event: {
+ button,
+ ctrlKey,
+ metaKey,
+ shiftKey
+ }
+ })
+ }));
+ } else {
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].OnlyToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].OPEN_LINK,
+ data: Object.assign(this.props.link, {
+ event: {
+ altKey,
+ button,
+ ctrlKey,
+ metaKey,
+ shiftKey
+ }
+ })
+ }));
+ }
+
+ if (this.props.isWebExtension) {
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].WebExtEvent(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].WEBEXT_CLICK, {
+ source: this.props.eventSource,
+ url: this.props.link.url,
+ action_position: this.props.index
+ }));
+ } else {
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].UserEvent(Object.assign({
+ event: "CLICK",
+ source: this.props.eventSource,
+ action_position: this.props.index
+ }, this._getTelemetryInfo())));
+
+ if (this.props.shouldSendImpressionStats) {
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].ImpressionStats({
+ source: this.props.eventSource,
+ click: 0,
+ tiles: [{
+ id: this.props.link.guid,
+ pos: this.props.index
+ }]
+ }));
+ }
+ }
+ }
+
+ componentDidMount() {
+ this.maybeLoadImage();
+ }
+
+ componentDidUpdate() {
+ this.maybeLoadImage();
+ } // NOTE: Remove this function when we update React to >= 16.3 since React will
+ // call getDerivedStateFromProps automatically. We will also need to
+ // rename getNextStateFromProps to getDerivedStateFromProps.
+
+
+ componentWillMount() {
+ const nextState = _Card.getNextStateFromProps(this.props, this.state);
+
+ if (nextState) {
+ this.setState(nextState);
+ }
+ } // NOTE: Remove this function when we update React to >= 16.3 since React will
+ // call getDerivedStateFromProps automatically. We will also need to
+ // rename getNextStateFromProps to getDerivedStateFromProps.
+
+
+ componentWillReceiveProps(nextProps) {
+ const nextState = _Card.getNextStateFromProps(nextProps, this.state);
+
+ if (nextState) {
+ this.setState(nextState);
+ }
+ }
+
+ componentWillUnmount() {
+ content_src_lib_screenshot_utils__WEBPACK_IMPORTED_MODULE_6__["ScreenshotUtils"].maybeRevokeBlobObjectURL(this.state.cardImage);
+ }
+
+ render() {
+ const {
+ index,
+ className,
+ link,
+ dispatch,
+ contextMenuOptions,
+ eventSource,
+ shouldSendImpressionStats
+ } = this.props;
+ const {
+ props
+ } = this;
+ const title = link.title || link.hostname;
+ const isContextMenuOpen = this.state.activeCard === index; // Display "now" as "trending" until we have new strings #3402
+
+ const {
+ icon,
+ fluentID
+ } = _types__WEBPACK_IMPORTED_MODULE_1__["cardContextTypes"][link.type === "now" ? "trending" : link.type] || {};
+ const hasImage = this.state.cardImage || link.hasImage;
+ const imageStyle = {
+ backgroundImage: this.state.cardImage ? `url(${this.state.cardImage.url})` : "none"
+ };
+ const outerClassName = ["card-outer", className, isContextMenuOpen && "active", props.placeholder && "placeholder"].filter(v => v).join(" ");
+ return react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("li", {
+ className: outerClassName
+ }, react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("a", {
+ href: link.type === "pocket" ? link.open_url : link.url,
+ onClick: !props.placeholder ? this.onLinkClick : undefined
+ }, react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("div", {
+ className: "card"
+ }, react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("div", {
+ className: "card-preview-image-outer"
+ }, hasImage && react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("div", {
+ className: `card-preview-image${this.state.imageLoaded ? " loaded" : ""}`,
+ style: imageStyle
+ })), react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("div", {
+ className: "card-details"
+ }, link.type === "download" && react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("div", {
+ className: "card-host-name alternate",
+ "data-l10n-id": "newtab-menu-open-file"
+ }), link.hostname && react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("div", {
+ className: "card-host-name"
+ }, link.hostname.slice(0, 100), link.type === "download" && ` \u2014 ${link.description}`), react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("div", {
+ className: ["card-text", icon ? "" : "no-context", link.description ? "" : "no-description", link.hostname ? "" : "no-host-name"].join(" ")
+ }, react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("h4", {
+ className: "card-title",
+ dir: "auto"
+ }, link.title), react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("p", {
+ className: "card-description",
+ dir: "auto"
+ }, link.description)), react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("div", {
+ className: "card-context"
+ }, icon && !link.context && react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("span", {
+ "aria-haspopup": "true",
+ className: `card-context-icon icon icon-${icon}`
+ }), link.icon && link.context && react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("span", {
+ "aria-haspopup": "true",
+ className: "card-context-icon icon",
+ style: {
+ backgroundImage: `url('${link.icon}')`
+ }
+ }), fluentID && !link.context && react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("div", {
+ className: "card-context-label",
+ "data-l10n-id": fluentID
+ }), link.context && react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement("div", {
+ className: "card-context-label"
+ }, link.context))))), !props.placeholder && react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement(content_src_components_ContextMenu_ContextMenuButton__WEBPACK_IMPORTED_MODULE_3__["ContextMenuButton"], {
+ tooltip: "newtab-menu-content-tooltip",
+ tooltipArgs: {
+ title
+ },
+ onUpdate: this.onMenuButtonUpdate
+ }, react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement(content_src_components_LinkMenu_LinkMenu__WEBPACK_IMPORTED_MODULE_4__["LinkMenu"], {
+ dispatch: dispatch,
+ index: index,
+ source: eventSource,
+ options: link.contextMenuOptions || contextMenuOptions,
+ site: link,
+ siteInfo: this._getTelemetryInfo(),
+ shouldSendImpressionStats: shouldSendImpressionStats
+ })));
+ }
+
+}
+_Card.defaultProps = {
+ link: {}
+};
+const Card = Object(react_redux__WEBPACK_IMPORTED_MODULE_2__["connect"])(state => ({
+ platform: state.Prefs.values.platform
+}))(_Card);
+const PlaceholderCard = props => react__WEBPACK_IMPORTED_MODULE_5___default.a.createElement(Card, {
+ placeholder: true,
+ className: props.className
+});
+
+/***/ }),
+/* 49 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* WEBPACK VAR INJECTION */(function(global) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ScreenshotUtils", function() { return ScreenshotUtils; });
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/**
+ * List of helper functions for screenshot-based images.
+ *
+ * There are two kinds of images:
+ * 1. Remote Image: This is the image from the main process and it refers to
+ * the image in the React props. This can either be an object with the `data`
+ * and `path` properties, if it is a blob, or a string, if it is a normal image.
+ * 2. Local Image: This is the image object in the content process and it refers
+ * to the image *object* in the React component's state. All local image
+ * objects have the `url` property, and an additional property `path`, if they
+ * are blobs.
+ */
+const ScreenshotUtils = {
+ isBlob(isLocal, image) {
+ return !!(image && image.path && (!isLocal && image.data || isLocal && image.url));
+ },
+
+ // This should always be called with a remote image and not a local image.
+ createLocalImageObject(remoteImage) {
+ if (!remoteImage) {
+ return null;
+ }
+
+ if (this.isBlob(false, remoteImage)) {
+ return {
+ url: global.URL.createObjectURL(remoteImage.data),
+ path: remoteImage.path
+ };
+ }
+
+ return {
+ url: remoteImage
+ };
+ },
+
+ // Revokes the object URL of the image if the local image is a blob.
+ // This should always be called with a local image and not a remote image.
+ maybeRevokeBlobObjectURL(localImage) {
+ if (this.isBlob(true, localImage)) {
+ global.URL.revokeObjectURL(localImage.url);
+ }
+ },
+
+ // Checks if remoteImage and localImage are the same.
+ isRemoteImageLocal(localImage, remoteImage) {
+ // Both remoteImage and localImage are present.
+ if (remoteImage && localImage) {
+ return this.isBlob(false, remoteImage) ? localImage.path === remoteImage.path : localImage.url === remoteImage;
+ } // This will only handle the remaining three possible outcomes.
+ // (i.e. everything except when both image and localImage are present)
+
+
+ return !remoteImage && !localImage;
+ }
+
+};
+/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(3)))
+
+/***/ }),
+/* 50 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ComponentPerfTimer", function() { return ComponentPerfTimer; });
+/* harmony import */ var common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
+/* harmony import */ var content_src_lib_perf_service__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(51);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_2__);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+ // Currently record only a fixed set of sections. This will prevent data
+// from custom sections from showing up or from topstories.
+
+const RECORDED_SECTIONS = ["highlights", "topsites"];
+class ComponentPerfTimer extends react__WEBPACK_IMPORTED_MODULE_2___default.a.Component {
+ constructor(props) {
+ super(props); // Just for test dependency injection:
+
+ this.perfSvc = this.props.perfSvc || content_src_lib_perf_service__WEBPACK_IMPORTED_MODULE_1__["perfService"];
+ this._sendBadStateEvent = this._sendBadStateEvent.bind(this);
+ this._sendPaintedEvent = this._sendPaintedEvent.bind(this);
+ this._reportMissingData = false;
+ this._timestampHandled = false;
+ this._recordedFirstRender = false;
+ }
+
+ componentDidMount() {
+ if (!RECORDED_SECTIONS.includes(this.props.id)) {
+ return;
+ }
+
+ this._maybeSendPaintedEvent();
+ }
+
+ componentDidUpdate() {
+ if (!RECORDED_SECTIONS.includes(this.props.id)) {
+ return;
+ }
+
+ this._maybeSendPaintedEvent();
+ }
+ /**
+ * Call the given callback after the upcoming frame paints.
+ *
+ * @note Both setTimeout and requestAnimationFrame are throttled when the page
+ * is hidden, so this callback may get called up to a second or so after the
+ * requestAnimationFrame "paint" for hidden tabs.
+ *
+ * Newtabs hidden while loading will presumably be fairly rare (other than
+ * preloaded tabs, which we will be filtering out on the server side), so such
+ * cases should get lost in the noise.
+ *
+ * If we decide that it's important to find out when something that's hidden
+ * has "painted", however, another option is to post a message to this window.
+ * That should happen even faster than setTimeout, and, at least as of this
+ * writing, it's not throttled in hidden windows in Firefox.
+ *
+ * @param {Function} callback
+ *
+ * @returns void
+ */
+
+
+ _afterFramePaint(callback) {
+ requestAnimationFrame(() => setTimeout(callback, 0));
+ }
+
+ _maybeSendBadStateEvent() {
+ // Follow up bugs:
+ // https://github.com/mozilla/activity-stream/issues/3691
+ if (!this.props.initialized) {
+ // Remember to report back when data is available.
+ this._reportMissingData = true;
+ } else if (this._reportMissingData) {
+ this._reportMissingData = false; // Report how long it took for component to become initialized.
+
+ this._sendBadStateEvent();
+ }
+ }
+
+ _maybeSendPaintedEvent() {
+ // If we've already handled a timestamp, don't do it again.
+ if (this._timestampHandled || !this.props.initialized) {
+ return;
+ } // And if we haven't, we're doing so now, so remember that. Even if
+ // something goes wrong in the callback, we can't try again, as we'd be
+ // sending back the wrong data, and we have to do it here, so that other
+ // calls to this method while waiting for the next frame won't also try to
+ // handle it.
+
+
+ this._timestampHandled = true;
+
+ this._afterFramePaint(this._sendPaintedEvent);
+ }
+ /**
+ * Triggered by call to render. Only first call goes through due to
+ * `_recordedFirstRender`.
+ */
+
+
+ _ensureFirstRenderTsRecorded() {
+ // Used as t0 for recording how long component took to initialize.
+ if (!this._recordedFirstRender) {
+ this._recordedFirstRender = true; // topsites_first_render_ts, highlights_first_render_ts.
+
+ const key = `${this.props.id}_first_render_ts`;
+ this.perfSvc.mark(key);
+ }
+ }
+ /**
+ * Creates `SAVE_SESSION_PERF_DATA` with timestamp in ms
+ * of how much longer the data took to be ready for display than it would
+ * have been the ideal case.
+ * https://github.com/mozilla/ping-centre/issues/98
+ */
+
+
+ _sendBadStateEvent() {
+ // highlights_data_ready_ts, topsites_data_ready_ts.
+ const dataReadyKey = `${this.props.id}_data_ready_ts`;
+ this.perfSvc.mark(dataReadyKey);
+
+ try {
+ const firstRenderKey = `${this.props.id}_first_render_ts`; // value has to be Int32.
+
+ const value = parseInt(this.perfSvc.getMostRecentAbsMarkStartByName(dataReadyKey) - this.perfSvc.getMostRecentAbsMarkStartByName(firstRenderKey), 10);
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].OnlyToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].SAVE_SESSION_PERF_DATA,
+ // highlights_data_late_by_ms, topsites_data_late_by_ms.
+ data: {
+ [`${this.props.id}_data_late_by_ms`]: value
+ }
+ }));
+ } catch (ex) {// If this failed, it's likely because the `privacy.resistFingerprinting`
+ // pref is true.
+ }
+ }
+
+ _sendPaintedEvent() {
+ // Record first_painted event but only send if topsites.
+ if (this.props.id !== "topsites") {
+ return;
+ } // topsites_first_painted_ts.
+
+
+ const key = `${this.props.id}_first_painted_ts`;
+ this.perfSvc.mark(key);
+
+ try {
+ const data = {};
+ data[key] = this.perfSvc.getMostRecentAbsMarkStartByName(key);
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].OnlyToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].SAVE_SESSION_PERF_DATA,
+ data
+ }));
+ } catch (ex) {// If this failed, it's likely because the `privacy.resistFingerprinting`
+ // pref is true. We should at least not blow up, and should continue
+ // to set this._timestampHandled to avoid going through this again.
+ }
+ }
+
+ render() {
+ if (RECORDED_SECTIONS.includes(this.props.id)) {
+ this._ensureFirstRenderTsRecorded();
+
+ this._maybeSendBadStateEvent();
+ }
+
+ return this.props.children;
+ }
+
+}
+
+/***/ }),
+/* 51 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_PerfService", function() { return _PerfService; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "perfService", function() { return perfService; });
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+let usablePerfObj = window.performance;
+function _PerfService(options) {
+ // For testing, so that we can use a fake Window.performance object with
+ // known state.
+ if (options && options.performanceObj) {
+ this._perf = options.performanceObj;
+ } else {
+ this._perf = usablePerfObj;
+ }
+}
+_PerfService.prototype = {
+ /**
+ * Calls the underlying mark() method on the appropriate Window.performance
+ * object to add a mark with the given name to the appropriate performance
+ * timeline.
+ *
+ * @param {String} name the name to give the current mark
+ * @return {void}
+ */
+ mark: function mark(str) {
+ this._perf.mark(str);
+ },
+
+ /**
+ * Calls the underlying getEntriesByName on the appropriate Window.performance
+ * object.
+ *
+ * @param {String} name
+ * @param {String} type eg "mark"
+ * @return {Array} Performance* objects
+ */
+ getEntriesByName: function getEntriesByName(name, type) {
+ return this._perf.getEntriesByName(name, type);
+ },
+
+ /**
+ * The timeOrigin property from the appropriate performance object.
+ * Used to ensure that timestamps from the add-on code and the content code
+ * are comparable.
+ *
+ * @note If this is called from a context without a window
+ * (eg a JSM in chrome), it will return the timeOrigin of the XUL hidden
+ * window, which appears to be the first created window (and thus
+ * timeOrigin) in the browser. Note also, however, there is also a private
+ * hidden window, presumably for private browsing, which appears to be
+ * created dynamically later. Exactly how/when that shows up needs to be
+ * investigated.
+ *
+ * @return {Number} A double of milliseconds with a precision of 0.5us.
+ */
+ get timeOrigin() {
+ return this._perf.timeOrigin;
+ },
+
+ /**
+ * Returns the "absolute" version of performance.now(), i.e. one that
+ * should ([bug 1401406](https://bugzilla.mozilla.org/show_bug.cgi?id=1401406)
+ * be comparable across both chrome and content.
+ *
+ * @return {Number}
+ */
+ absNow: function absNow() {
+ return this.timeOrigin + this._perf.now();
+ },
+
+ /**
+ * This returns the absolute startTime from the most recent performance.mark()
+ * with the given name.
+ *
+ * @param {String} name the name to lookup the start time for
+ *
+ * @return {Number} the returned start time, as a DOMHighResTimeStamp
+ *
+ * @throws {Error} "No Marks with the name ..." if none are available
+ *
+ * @note Always surround calls to this by try/catch. Otherwise your code
+ * may fail when the `privacy.resistFingerprinting` pref is true. When
+ * this pref is set, all attempts to get marks will likely fail, which will
+ * cause this method to throw.
+ *
+ * See [bug 1369303](https://bugzilla.mozilla.org/show_bug.cgi?id=1369303)
+ * for more info.
+ */
+ getMostRecentAbsMarkStartByName(name) {
+ let entries = this.getEntriesByName(name, "mark");
+
+ if (!entries.length) {
+ throw new Error(`No marks with the name ${name}`);
+ }
+
+ let mostRecentEntry = entries[entries.length - 1];
+ return this._perf.timeOrigin + mostRecentEntry.startTime;
+ }
+
+};
+const perfService = new _PerfService();
+
+/***/ }),
+/* 52 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MoreRecommendations", function() { return MoreRecommendations; });
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+class MoreRecommendations extends react__WEBPACK_IMPORTED_MODULE_0___default.a.PureComponent {
+ render() {
+ const {
+ read_more_endpoint
+ } = this.props;
+
+ if (read_more_endpoint) {
+ return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("a", {
+ className: "more-recommendations",
+ href: read_more_endpoint,
+ "data-l10n-id": "newtab-pocket-more-recommendations"
+ });
+ }
+
+ return null;
+ }
+
+}
+
+/***/ }),
+/* 53 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_PocketLoggedInCta", function() { return _PocketLoggedInCta; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PocketLoggedInCta", function() { return PocketLoggedInCta; });
+/* harmony import */ var react_redux__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(7);
+/* harmony import */ var react_redux__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react_redux__WEBPACK_IMPORTED_MODULE_0__);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+class _PocketLoggedInCta extends react__WEBPACK_IMPORTED_MODULE_1___default.a.PureComponent {
+ render() {
+ const {
+ pocketCta
+ } = this.props.Pocket;
+ return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", {
+ className: "pocket-logged-in-cta"
+ }, react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("a", {
+ className: "pocket-cta-button",
+ href: pocketCta.ctaUrl ? pocketCta.ctaUrl : "https://getpocket.com/"
+ }, pocketCta.ctaButton ? pocketCta.ctaButton : react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", {
+ "data-l10n-id": "newtab-pocket-cta-button"
+ })), react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("a", {
+ href: pocketCta.ctaUrl ? pocketCta.ctaUrl : "https://getpocket.com/"
+ }, react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", {
+ className: "cta-text"
+ }, pocketCta.ctaText ? pocketCta.ctaText : react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", {
+ "data-l10n-id": "newtab-pocket-cta-text"
+ }))));
+ }
+
+}
+const PocketLoggedInCta = Object(react_redux__WEBPACK_IMPORTED_MODULE_0__["connect"])(state => ({
+ Pocket: state.Pocket
+}))(_PocketLoggedInCta);
+
+/***/ }),
+/* 54 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Topic", function() { return Topic; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Topics", function() { return Topics; });
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+class Topic extends react__WEBPACK_IMPORTED_MODULE_0___default.a.PureComponent {
+ render() {
+ const {
+ url,
+ name
+ } = this.props;
+ return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("li", null, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("a", {
+ key: name,
+ href: url
+ }, name));
+ }
+
+}
+class Topics extends react__WEBPACK_IMPORTED_MODULE_0___default.a.PureComponent {
+ render() {
+ const {
+ topics
+ } = this.props;
+ return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", {
+ className: "topics"
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("span", {
+ "data-l10n-id": "newtab-pocket-read-more"
+ }), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("ul", null, topics && topics.map(t => react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(Topic, {
+ key: t.name,
+ url: t.url,
+ name: t.name
+ }))));
+ }
+
+}
+
+/***/ }),
+/* 55 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* WEBPACK VAR INJECTION */(function(global) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_TopSites", function() { return _TopSites; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TopSites", function() { return TopSites; });
+/* harmony import */ var common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
+/* harmony import */ var _TopSitesConstants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(56);
+/* harmony import */ var content_src_components_CollapsibleSection_CollapsibleSection__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(34);
+/* harmony import */ var content_src_components_ComponentPerfTimer_ComponentPerfTimer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(50);
+/* harmony import */ var react_redux__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(7);
+/* harmony import */ var react_redux__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(react_redux__WEBPACK_IMPORTED_MODULE_4__);
+/* harmony import */ var _asrouter_components_ModalOverlay_ModalOverlay__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(41);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_6__);
+/* harmony import */ var _SearchShortcutsForm__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(57);
+/* harmony import */ var common_Reducers_jsm__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(72);
+/* harmony import */ var _TopSiteForm__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(73);
+/* harmony import */ var _TopSite__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(58);
+function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
+
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+
+
+
+
+
+
+
+
+
+
+function topSiteIconType(link) {
+ if (link.customScreenshotURL) {
+ return "custom_screenshot";
+ }
+
+ if (link.tippyTopIcon || link.faviconRef === "tippytop") {
+ return "tippytop";
+ }
+
+ if (link.faviconSize >= _TopSitesConstants__WEBPACK_IMPORTED_MODULE_1__["MIN_RICH_FAVICON_SIZE"]) {
+ return "rich_icon";
+ }
+
+ if (link.screenshot && link.faviconSize >= _TopSitesConstants__WEBPACK_IMPORTED_MODULE_1__["MIN_CORNER_FAVICON_SIZE"]) {
+ return "screenshot_with_icon";
+ }
+
+ if (link.screenshot) {
+ return "screenshot";
+ }
+
+ return "no_image";
+}
+/**
+ * Iterates through TopSites and counts types of images.
+ * @param acc Accumulator for reducer.
+ * @param topsite Entry in TopSites.
+ */
+
+
+function countTopSitesIconsTypes(topSites) {
+ const countTopSitesTypes = (acc, link) => {
+ acc[topSiteIconType(link)]++;
+ return acc;
+ };
+
+ return topSites.reduce(countTopSitesTypes, {
+ custom_screenshot: 0,
+ screenshot_with_icon: 0,
+ screenshot: 0,
+ tippytop: 0,
+ rich_icon: 0,
+ no_image: 0
+ });
+}
+
+class _TopSites extends react__WEBPACK_IMPORTED_MODULE_6___default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onEditFormClose = this.onEditFormClose.bind(this);
+ this.onSearchShortcutsFormClose = this.onSearchShortcutsFormClose.bind(this);
+ }
+ /**
+ * Dispatch session statistics about the quality of TopSites icons and pinned count.
+ */
+
+
+ _dispatchTopSitesStats() {
+ const topSites = this._getVisibleTopSites().filter(topSite => topSite !== null && topSite !== undefined);
+
+ const topSitesIconsStats = countTopSitesIconsTypes(topSites);
+ const topSitesPinned = topSites.filter(site => !!site.isPinned).length;
+ const searchShortcuts = topSites.filter(site => !!site.searchTopSite).length; // Dispatch telemetry event with the count of TopSites images types.
+
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].AlsoToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].SAVE_SESSION_PERF_DATA,
+ data: {
+ topsites_icon_stats: topSitesIconsStats,
+ topsites_pinned: topSitesPinned,
+ topsites_search_shortcuts: searchShortcuts
+ }
+ }));
+ }
+ /**
+ * Return the TopSites that are visible based on prefs and window width.
+ */
+
+
+ _getVisibleTopSites() {
+ // We hide 2 sites per row when not in the wide layout.
+ let sitesPerRow = common_Reducers_jsm__WEBPACK_IMPORTED_MODULE_8__["TOP_SITES_MAX_SITES_PER_ROW"]; // $break-point-widest = 1072px (from _variables.scss)
+
+ if (!global.matchMedia(`(min-width: 1072px)`).matches) {
+ sitesPerRow -= 2;
+ }
+
+ return this.props.TopSites.rows.slice(0, this.props.TopSitesRows * sitesPerRow);
+ }
+
+ componentDidUpdate() {
+ this._dispatchTopSitesStats();
+ }
+
+ componentDidMount() {
+ this._dispatchTopSitesStats();
+ }
+
+ onEditFormClose() {
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].UserEvent({
+ source: _TopSitesConstants__WEBPACK_IMPORTED_MODULE_1__["TOP_SITES_SOURCE"],
+ event: "TOP_SITES_EDIT_CLOSE"
+ }));
+ this.props.dispatch({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].TOP_SITES_CANCEL_EDIT
+ });
+ }
+
+ onSearchShortcutsFormClose() {
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].UserEvent({
+ source: _TopSitesConstants__WEBPACK_IMPORTED_MODULE_1__["TOP_SITES_SOURCE"],
+ event: "SEARCH_EDIT_CLOSE"
+ }));
+ this.props.dispatch({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].TOP_SITES_CLOSE_SEARCH_SHORTCUTS_MODAL
+ });
+ }
+
+ render() {
+ const {
+ props
+ } = this;
+ const {
+ editForm,
+ showSearchShortcutsForm
+ } = props.TopSites;
+ const extraMenuOptions = ["AddTopSite"];
+ const newNewtabExperienceEnabled = props.Prefs.values["newNewtabExperience.enabled"];
+ const customizationMenuEnabled = props.Prefs.values["customizationMenu.enabled"];
+ const colors = props.Prefs.values["newNewtabExperience.colors"];
+
+ if (props.Prefs.values["improvesearch.topSiteSearchShortcuts"]) {
+ extraMenuOptions.push("AddSearchShortcut");
+ }
+
+ const canShowCustomizationMenu = newNewtabExperienceEnabled || customizationMenuEnabled;
+ const hideTitle = props.Prefs.values.hideTopSitesTitle || canShowCustomizationMenu; // `collapsed` should be sent to CollapsibleSection as undefined if
+ // `props.TopSites.pref` is not set to true.
+
+ let collapsed;
+
+ if (props.TopSites.pref) {
+ collapsed = canShowCustomizationMenu ? false : props.TopSites.pref.collapsed;
+ }
+
+ return react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement(content_src_components_ComponentPerfTimer_ComponentPerfTimer__WEBPACK_IMPORTED_MODULE_3__["ComponentPerfTimer"], {
+ id: "topsites",
+ initialized: props.TopSites.initialized,
+ dispatch: props.dispatch
+ }, react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement(content_src_components_CollapsibleSection_CollapsibleSection__WEBPACK_IMPORTED_MODULE_2__["CollapsibleSection"], {
+ className: "top-sites",
+ icon: "topsites",
+ id: "topsites",
+ title: props.title || {
+ id: "newtab-section-header-topsites"
+ },
+ hideTitle: hideTitle,
+ extraMenuOptions: extraMenuOptions,
+ showPrefName: "feeds.topsites",
+ eventSource: _TopSitesConstants__WEBPACK_IMPORTED_MODULE_1__["TOP_SITES_SOURCE"],
+ collapsed: collapsed,
+ isFixed: props.isFixed,
+ isFirst: props.isFirst,
+ isLast: props.isLast,
+ dispatch: props.dispatch
+ }, react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement(_TopSite__WEBPACK_IMPORTED_MODULE_10__["TopSiteList"], {
+ TopSites: props.TopSites,
+ TopSitesRows: props.TopSitesRows,
+ dispatch: props.dispatch,
+ topSiteIconType: topSiteIconType,
+ newNewtabExperienceEnabled: newNewtabExperienceEnabled,
+ colors: colors
+ }), react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("div", {
+ className: "edit-topsites-wrapper"
+ }, editForm && react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("div", {
+ className: "edit-topsites"
+ }, react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement(_asrouter_components_ModalOverlay_ModalOverlay__WEBPACK_IMPORTED_MODULE_5__["ModalOverlayWrapper"], {
+ unstyled: true,
+ onClose: this.onEditFormClose,
+ innerClassName: "modal"
+ }, react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement(_TopSiteForm__WEBPACK_IMPORTED_MODULE_9__["TopSiteForm"], _extends({
+ site: props.TopSites.rows[editForm.index],
+ onClose: this.onEditFormClose,
+ dispatch: this.props.dispatch
+ }, editForm, {
+ newNewtabExperienceEnabled: newNewtabExperienceEnabled,
+ customizationMenuEnabled: customizationMenuEnabled
+ })))), showSearchShortcutsForm && react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement("div", {
+ className: "edit-search-shortcuts"
+ }, react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement(_asrouter_components_ModalOverlay_ModalOverlay__WEBPACK_IMPORTED_MODULE_5__["ModalOverlayWrapper"], {
+ unstyled: true,
+ onClose: this.onSearchShortcutsFormClose,
+ innerClassName: "modal"
+ }, react__WEBPACK_IMPORTED_MODULE_6___default.a.createElement(_SearchShortcutsForm__WEBPACK_IMPORTED_MODULE_7__["SearchShortcutsForm"], {
+ TopSites: props.TopSites,
+ onClose: this.onSearchShortcutsFormClose,
+ dispatch: this.props.dispatch
+ }))))));
+ }
+
+}
+const TopSites = Object(react_redux__WEBPACK_IMPORTED_MODULE_4__["connect"])((state, props) => ({
+ // For SPOC Experiment only, take TopSites from DiscoveryStream TopSites that takes in SPOC Data
+ TopSites: props.TopSitesWithSpoc || state.TopSites,
+ Prefs: state.Prefs,
+ TopSitesRows: state.Prefs.values.topSitesRows
+}))(_TopSites);
+/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(3)))
+
+/***/ }),
+/* 56 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TOP_SITES_SOURCE", function() { return TOP_SITES_SOURCE; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TOP_SITES_CONTEXT_MENU_OPTIONS", function() { return TOP_SITES_CONTEXT_MENU_OPTIONS; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TOP_SITES_SPOC_CONTEXT_MENU_OPTIONS", function() { return TOP_SITES_SPOC_CONTEXT_MENU_OPTIONS; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TOP_SITES_SPONSORED_POSITION_CONTEXT_MENU_OPTIONS", function() { return TOP_SITES_SPONSORED_POSITION_CONTEXT_MENU_OPTIONS; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TOP_SITES_SEARCH_SHORTCUTS_CONTEXT_MENU_OPTIONS", function() { return TOP_SITES_SEARCH_SHORTCUTS_CONTEXT_MENU_OPTIONS; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MIN_RICH_FAVICON_SIZE", function() { return MIN_RICH_FAVICON_SIZE; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MIN_CORNER_FAVICON_SIZE", function() { return MIN_CORNER_FAVICON_SIZE; });
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+const TOP_SITES_SOURCE = "TOP_SITES";
+const TOP_SITES_CONTEXT_MENU_OPTIONS = ["CheckPinTopSite", "EditTopSite", "Separator", "OpenInNewWindow", "OpenInPrivateWindow", "Separator", "BlockUrl", "DeleteUrl"];
+const TOP_SITES_SPOC_CONTEXT_MENU_OPTIONS = ["PinTopSite", "Separator", "OpenInNewWindow", "OpenInPrivateWindow", "Separator", "BlockUrl", "ShowPrivacyInfo"];
+const TOP_SITES_SPONSORED_POSITION_CONTEXT_MENU_OPTIONS = ["PinTopSite", "Separator", "OpenInNewWindow", "OpenInPrivateWindow", "Separator", "BlockUrl", "AboutSponsored"]; // the special top site for search shortcut experiment can only have the option to unpin (which removes) the topsite
+
+const TOP_SITES_SEARCH_SHORTCUTS_CONTEXT_MENU_OPTIONS = ["CheckPinTopSite", "Separator", "BlockUrl"]; // minimum size necessary to show a rich icon instead of a screenshot
+
+const MIN_RICH_FAVICON_SIZE = 96; // minimum size necessary to show any icon in the top left corner with a screenshot
+
+const MIN_CORNER_FAVICON_SIZE = 16;
+
+/***/ }),
+/* 57 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SelectableSearchShortcut", function() { return SelectableSearchShortcut; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SearchShortcutsForm", function() { return SearchShortcutsForm; });
+/* harmony import */ var common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
+/* harmony import */ var _TopSitesConstants__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(56);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+
+class SelectableSearchShortcut extends react__WEBPACK_IMPORTED_MODULE_1___default.a.PureComponent {
+ render() {
+ const {
+ shortcut,
+ selected
+ } = this.props;
+ const imageStyle = {
+ backgroundImage: `url("${shortcut.tippyTopIcon}")`
+ };
+ return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", {
+ className: "top-site-outer search-shortcut"
+ }, react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("input", {
+ type: "checkbox",
+ id: shortcut.keyword,
+ name: shortcut.keyword,
+ checked: selected,
+ onChange: this.props.onChange
+ }), react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("label", {
+ htmlFor: shortcut.keyword
+ }, react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", {
+ className: "top-site-inner"
+ }, react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", null, react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", {
+ className: "tile"
+ }, react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", {
+ className: "top-site-icon rich-icon",
+ style: imageStyle,
+ "data-fallback": "@"
+ }), react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", {
+ className: "top-site-icon search-topsite"
+ })), react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", {
+ className: "title"
+ }, react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", {
+ dir: "auto"
+ }, shortcut.keyword))))));
+ }
+
+}
+class SearchShortcutsForm extends react__WEBPACK_IMPORTED_MODULE_1___default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.handleChange = this.handleChange.bind(this);
+ this.onCancelButtonClick = this.onCancelButtonClick.bind(this);
+ this.onSaveButtonClick = this.onSaveButtonClick.bind(this); // clone the shortcuts and add them to the state so we can add isSelected property
+
+ const shortcuts = [];
+ const {
+ rows,
+ searchShortcuts
+ } = props.TopSites;
+ searchShortcuts.forEach(shortcut => {
+ shortcuts.push({ ...shortcut,
+ isSelected: !!rows.find(row => row && row.isPinned && row.searchTopSite && row.label === shortcut.keyword)
+ });
+ });
+ this.state = {
+ shortcuts
+ };
+ }
+
+ handleChange(event) {
+ const {
+ target
+ } = event;
+ const {
+ name,
+ checked
+ } = target;
+ this.setState(prevState => {
+ const shortcuts = prevState.shortcuts.slice();
+ let shortcut = shortcuts.find(({
+ keyword
+ }) => keyword === name);
+ shortcut.isSelected = checked;
+ return {
+ shortcuts
+ };
+ });
+ }
+
+ onCancelButtonClick(ev) {
+ ev.preventDefault();
+ this.props.onClose();
+ }
+
+ onSaveButtonClick(ev) {
+ ev.preventDefault(); // Check if there were any changes and act accordingly
+
+ const {
+ rows
+ } = this.props.TopSites;
+ const pinQueue = [];
+ const unpinQueue = [];
+ this.state.shortcuts.forEach(shortcut => {
+ const alreadyPinned = rows.find(row => row && row.isPinned && row.searchTopSite && row.label === shortcut.keyword);
+
+ if (shortcut.isSelected && !alreadyPinned) {
+ pinQueue.push(this._searchTopSite(shortcut));
+ } else if (!shortcut.isSelected && alreadyPinned) {
+ unpinQueue.push({
+ url: alreadyPinned.url,
+ searchVendor: shortcut.shortURL
+ });
+ }
+ }); // Tell the feed to do the work.
+
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].OnlyToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].UPDATE_PINNED_SEARCH_SHORTCUTS,
+ data: {
+ addedShortcuts: pinQueue,
+ deletedShortcuts: unpinQueue
+ }
+ })); // Send the Telemetry pings.
+
+ pinQueue.forEach(shortcut => {
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].UserEvent({
+ source: _TopSitesConstants__WEBPACK_IMPORTED_MODULE_2__["TOP_SITES_SOURCE"],
+ event: "SEARCH_EDIT_ADD",
+ value: {
+ search_vendor: shortcut.searchVendor
+ }
+ }));
+ });
+ unpinQueue.forEach(shortcut => {
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].UserEvent({
+ source: _TopSitesConstants__WEBPACK_IMPORTED_MODULE_2__["TOP_SITES_SOURCE"],
+ event: "SEARCH_EDIT_DELETE",
+ value: {
+ search_vendor: shortcut.searchVendor
+ }
+ }));
+ });
+ this.props.onClose();
+ }
+
+ _searchTopSite(shortcut) {
+ return {
+ url: shortcut.url,
+ searchTopSite: true,
+ label: shortcut.keyword,
+ searchVendor: shortcut.shortURL
+ };
+ }
+
+ render() {
+ return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("form", {
+ className: "topsite-form"
+ }, react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", {
+ className: "search-shortcuts-container"
+ }, react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("h3", {
+ className: "section-title grey-title",
+ "data-l10n-id": "newtab-topsites-add-search-engine-header"
+ }), react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", null, this.state.shortcuts.map(shortcut => react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(SelectableSearchShortcut, {
+ key: shortcut.keyword,
+ shortcut: shortcut,
+ selected: shortcut.isSelected,
+ onChange: this.handleChange
+ })))), react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("section", {
+ className: "actions"
+ }, react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("button", {
+ className: "cancel",
+ type: "button",
+ onClick: this.onCancelButtonClick,
+ "data-l10n-id": "newtab-topsites-cancel-button"
+ }), react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("button", {
+ className: "done",
+ type: "submit",
+ onClick: this.onSaveButtonClick,
+ "data-l10n-id": "newtab-topsites-save-button"
+ })));
+ }
+
+}
+
+/***/ }),
+/* 58 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TopSiteLink", function() { return TopSiteLink; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TopSite", function() { return TopSite; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TopSitePlaceholder", function() { return TopSitePlaceholder; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TopSiteList", function() { return TopSiteList; });
+/* harmony import */ var common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
+/* harmony import */ var _TopSitesConstants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(56);
+/* harmony import */ var content_src_components_LinkMenu_LinkMenu__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(21);
+/* harmony import */ var _DiscoveryStreamImpressionStats_ImpressionStats__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(25);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_4__);
+/* harmony import */ var content_src_lib_screenshot_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(49);
+/* harmony import */ var common_Reducers_jsm__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(72);
+/* harmony import */ var content_src_components_ContextMenu_ContextMenuButton__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(24);
+function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
+
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+
+
+
+
+
+
+const SPOC_TYPE = "SPOC";
+class TopSiteLink extends react__WEBPACK_IMPORTED_MODULE_4___default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.state = {
+ screenshotImage: null
+ };
+ this.onDragEvent = this.onDragEvent.bind(this);
+ this.onKeyPress = this.onKeyPress.bind(this);
+ }
+ /*
+ * Helper to determine whether the drop zone should allow a drop. We only allow
+ * dropping top sites for now. We don't allow dropping on sponsored top sites
+ * as their position is fixed.
+ */
+
+
+ _allowDrop(e) {
+ return (this.dragged || !this.props.link.sponsored_position) && e.dataTransfer.types.includes("text/topsite-index");
+ }
+
+ onDragEvent(event) {
+ switch (event.type) {
+ case "click":
+ // Stop any link clicks if we started any dragging
+ if (this.dragged) {
+ event.preventDefault();
+ }
+
+ break;
+
+ case "dragstart":
+ this.dragged = true;
+ event.dataTransfer.effectAllowed = "move";
+ event.dataTransfer.setData("text/topsite-index", this.props.index);
+ event.target.blur();
+ this.props.onDragEvent(event, this.props.index, this.props.link, this.props.title);
+ break;
+
+ case "dragend":
+ this.props.onDragEvent(event);
+ break;
+
+ case "dragenter":
+ case "dragover":
+ case "drop":
+ if (this._allowDrop(event)) {
+ event.preventDefault();
+ this.props.onDragEvent(event, this.props.index);
+ }
+
+ break;
+
+ case "mousedown":
+ // Block the scroll wheel from appearing for middle clicks on search top sites
+ if (event.button === 1 && this.props.link.searchTopSite) {
+ event.preventDefault();
+ } // Reset at the first mouse event of a potential drag
+
+
+ this.dragged = false;
+ break;
+ }
+ }
+ /**
+ * Helper to obtain the next state based on nextProps and prevState.
+ *
+ * NOTE: Rename this method to getDerivedStateFromProps when we update React
+ * to >= 16.3. We will need to update tests as well. We cannot rename this
+ * method to getDerivedStateFromProps now because there is a mismatch in
+ * the React version that we are using for both testing and production.
+ * (i.e. react-test-render => "16.3.2", react => "16.2.0").
+ *
+ * See https://github.com/airbnb/enzyme/blob/master/packages/enzyme-adapter-react-16/package.json#L43.
+ */
+
+
+ static getNextStateFromProps(nextProps, prevState) {
+ const {
+ screenshot
+ } = nextProps.link;
+ const imageInState = content_src_lib_screenshot_utils__WEBPACK_IMPORTED_MODULE_5__["ScreenshotUtils"].isRemoteImageLocal(prevState.screenshotImage, screenshot);
+
+ if (imageInState) {
+ return null;
+ } // Since image was updated, attempt to revoke old image blob URL, if it exists.
+
+
+ content_src_lib_screenshot_utils__WEBPACK_IMPORTED_MODULE_5__["ScreenshotUtils"].maybeRevokeBlobObjectURL(prevState.screenshotImage);
+ return {
+ screenshotImage: content_src_lib_screenshot_utils__WEBPACK_IMPORTED_MODULE_5__["ScreenshotUtils"].createLocalImageObject(screenshot)
+ };
+ } // NOTE: Remove this function when we update React to >= 16.3 since React will
+ // call getDerivedStateFromProps automatically. We will also need to
+ // rename getNextStateFromProps to getDerivedStateFromProps.
+
+
+ componentWillMount() {
+ const nextState = TopSiteLink.getNextStateFromProps(this.props, this.state);
+
+ if (nextState) {
+ this.setState(nextState);
+ }
+ } // NOTE: Remove this function when we update React to >= 16.3 since React will
+ // call getDerivedStateFromProps automatically. We will also need to
+ // rename getNextStateFromProps to getDerivedStateFromProps.
+
+
+ componentWillReceiveProps(nextProps) {
+ const nextState = TopSiteLink.getNextStateFromProps(nextProps, this.state);
+
+ if (nextState) {
+ this.setState(nextState);
+ }
+ }
+
+ componentWillUnmount() {
+ content_src_lib_screenshot_utils__WEBPACK_IMPORTED_MODULE_5__["ScreenshotUtils"].maybeRevokeBlobObjectURL(this.state.screenshotImage);
+ }
+
+ onKeyPress(event) {
+ // If we have tabbed to a search shortcut top site, and we click 'enter',
+ // we should execute the onClick function. This needs to be added because
+ // search top sites are anchor tags without an href. See bug 1483135
+ if (this.props.link.searchTopSite && event.key === "Enter") {
+ this.props.onClick(event);
+ }
+ }
+ /*
+ * Takes the url as a string, runs it through a simple (non-secure) hash turning it into a random number
+ * Apply that random number to the color array. The same url will always generate the same color.
+ */
+
+
+ generateColor() {
+ let {
+ title,
+ colors
+ } = this.props;
+
+ if (!colors) {
+ return "";
+ }
+
+ let colorArray = colors.split(",");
+
+ const hashStr = str => {
+ let hash = 0;
+
+ for (let i = 0; i < str.length; i++) {
+ let charCode = str.charCodeAt(i);
+ hash += charCode;
+ }
+
+ return hash;
+ };
+
+ let hash = hashStr(title);
+ let index = hash % colorArray.length;
+ return colorArray[index];
+ }
+
+ calculateStyle() {
+ const {
+ defaultStyle,
+ link,
+ newNewtabExperienceEnabled
+ } = this.props;
+ const {
+ tippyTopIcon,
+ faviconSize
+ } = link;
+ let imageClassName;
+ let imageStyle;
+ let showSmallFavicon = false;
+ let smallFaviconStyle;
+ let smallFaviconFallback;
+ let hasScreenshotImage = this.state.screenshotImage && this.state.screenshotImage.url;
+ let selectedColor;
+
+ if (defaultStyle) {
+ // force no styles (letter fallback) even if the link has imagery
+ smallFaviconFallback = false;
+
+ if (newNewtabExperienceEnabled) {
+ selectedColor = this.generateColor();
+ }
+ } else if (link.searchTopSite) {
+ imageClassName = "top-site-icon rich-icon";
+ imageStyle = {
+ backgroundColor: link.backgroundColor,
+ backgroundImage: `url(${tippyTopIcon})`
+ };
+ smallFaviconStyle = {
+ backgroundImage: `url(${tippyTopIcon})`
+ };
+ } else if (link.customScreenshotURL) {
+ // assume high quality custom screenshot and use rich icon styles and class names
+ // TopSite spoc experiment only
+ const spocImgURL = link.type === SPOC_TYPE ? link.customScreenshotURL : "";
+ imageClassName = "top-site-icon rich-icon";
+ imageStyle = {
+ backgroundColor: link.backgroundColor,
+ backgroundImage: hasScreenshotImage ? `url(${this.state.screenshotImage.url})` : `url(${spocImgURL})`
+ };
+ } else if (tippyTopIcon || faviconSize >= _TopSitesConstants__WEBPACK_IMPORTED_MODULE_1__["MIN_RICH_FAVICON_SIZE"]) {
+ // styles and class names for top sites with rich icons
+ imageClassName = "top-site-icon rich-icon";
+ imageStyle = {
+ backgroundColor: link.backgroundColor,
+ backgroundImage: `url(${tippyTopIcon || link.favicon})`
+ };
+ } else {
+ // styles and class names for top sites with screenshot + small icon in top left corner
+ imageClassName = `screenshot${hasScreenshotImage ? " active" : ""}`;
+ imageStyle = {
+ backgroundImage: hasScreenshotImage ? `url(${this.state.screenshotImage.url})` : "none"
+ }; // only show a favicon in top left if it's greater than 16x16
+
+ if (faviconSize >= _TopSitesConstants__WEBPACK_IMPORTED_MODULE_1__["MIN_CORNER_FAVICON_SIZE"]) {
+ showSmallFavicon = true;
+ smallFaviconStyle = {
+ backgroundImage: `url(${link.favicon})`
+ };
+ } else if (newNewtabExperienceEnabled) {
+ selectedColor = this.generateColor();
+ imageClassName = "";
+ } else if (hasScreenshotImage) {
+ // Don't show a small favicon if there is no screenshot, because that
+ // would result in two fallback icons
+ showSmallFavicon = true;
+ smallFaviconFallback = true;
+ }
+ }
+
+ return {
+ showSmallFavicon,
+ smallFaviconFallback,
+ smallFaviconStyle,
+ imageStyle,
+ imageClassName,
+ selectedColor
+ };
+ }
+
+ render() {
+ const {
+ children,
+ className,
+ isDraggable,
+ link,
+ onClick,
+ title,
+ newNewtabExperienceEnabled
+ } = this.props;
+ const topSiteOuterClassName = `top-site-outer${className ? ` ${className}` : ""}${link.isDragged ? " dragged" : ""}${link.searchTopSite ? " search-shortcut" : ""}`;
+ const [letterFallback] = title;
+ const {
+ showSmallFavicon,
+ smallFaviconFallback,
+ smallFaviconStyle,
+ imageStyle,
+ imageClassName,
+ selectedColor
+ } = this.calculateStyle();
+ let draggableProps = {};
+
+ if (isDraggable) {
+ draggableProps = {
+ onClick: this.onDragEvent,
+ onDragEnd: this.onDragEvent,
+ onDragStart: this.onDragEvent,
+ onMouseDown: this.onDragEvent
+ };
+ }
+
+ return react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("li", _extends({
+ className: topSiteOuterClassName,
+ onDrop: this.onDragEvent,
+ onDragOver: this.onDragEvent,
+ onDragEnter: this.onDragEvent,
+ onDragLeave: this.onDragEvent
+ }, draggableProps), react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("div", {
+ className: "top-site-inner"
+ }, react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("a", {
+ className: "top-site-button",
+ href: link.searchTopSite ? undefined : link.url,
+ tabIndex: "0",
+ onKeyPress: this.onKeyPress,
+ onClick: onClick,
+ draggable: true
+ }, newNewtabExperienceEnabled && react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("div", {
+ className: "tile",
+ "aria-hidden": true
+ }, react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("div", {
+ className: selectedColor ? "icon-wrapper letter-fallback" : "icon-wrapper",
+ "data-fallback": letterFallback,
+ style: selectedColor ? {
+ backgroundColor: selectedColor
+ } : {}
+ }, react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("div", {
+ className: imageClassName,
+ style: imageStyle
+ }), showSmallFavicon && react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("div", {
+ className: "top-site-icon default-icon",
+ "data-fallback": smallFaviconFallback && letterFallback,
+ style: smallFaviconStyle
+ })), link.searchTopSite && react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("div", {
+ className: "top-site-icon search-topsite"
+ })) || react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("div", {
+ className: "tile",
+ "aria-hidden": true,
+ "data-fallback": letterFallback
+ }, react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("div", {
+ className: imageClassName,
+ style: imageStyle
+ }), link.searchTopSite && react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("div", {
+ className: "top-site-icon search-topsite"
+ }), showSmallFavicon && react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("div", {
+ className: "top-site-icon default-icon",
+ "data-fallback": smallFaviconFallback && letterFallback,
+ style: smallFaviconStyle
+ })), react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("div", {
+ className: `title${link.isPinned ? " has-icon pinned" : ""}${link.type === SPOC_TYPE || link.sponsored_position ? " sponsored" : ""}`
+ }, newNewtabExperienceEnabled && react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("span", {
+ dir: "auto"
+ }, link.isPinned && react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("div", {
+ className: "icon icon-pin-small"
+ }), title || react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("br", null), react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("span", {
+ className: "sponsored-label",
+ "data-l10n-id": "newtab-topsite-sponsored"
+ })) || react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("div", null, link.isPinned && react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("div", {
+ className: "icon icon-pin-small"
+ }), react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("span", {
+ dir: "auto"
+ }, title || react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("br", null)), react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("span", {
+ className: "sponsored-label",
+ "data-l10n-id": "newtab-topsite-sponsored"
+ })))), children, link.type === SPOC_TYPE ? react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement(_DiscoveryStreamImpressionStats_ImpressionStats__WEBPACK_IMPORTED_MODULE_3__["ImpressionStats"], {
+ flightId: link.flightId,
+ rows: [{
+ id: link.id,
+ pos: link.pos,
+ shim: link.shim && link.shim.impression
+ }],
+ dispatch: this.props.dispatch,
+ source: _TopSitesConstants__WEBPACK_IMPORTED_MODULE_1__["TOP_SITES_SOURCE"]
+ }) : null));
+ }
+
+}
+TopSiteLink.defaultProps = {
+ title: "",
+ link: {},
+ isDraggable: true
+};
+class TopSite extends react__WEBPACK_IMPORTED_MODULE_4___default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.state = {
+ showContextMenu: false
+ };
+ this.onLinkClick = this.onLinkClick.bind(this);
+ this.onMenuUpdate = this.onMenuUpdate.bind(this);
+ }
+ /**
+ * Report to telemetry additional information about the item.
+ */
+
+
+ _getTelemetryInfo() {
+ const value = {
+ icon_type: this.props.link.iconType
+ }; // Filter out "not_pinned" type for being the default
+
+ if (this.props.link.isPinned) {
+ value.card_type = "pinned";
+ }
+
+ if (this.props.link.searchTopSite) {
+ // Set the card_type as "search" regardless of its pinning status
+ value.card_type = "search";
+ value.search_vendor = this.props.link.hostname;
+ }
+
+ if (this.props.link.type === SPOC_TYPE || this.props.link.sponsored_position) {
+ value.card_type = "spoc";
+ }
+
+ return {
+ value
+ };
+ }
+
+ userEvent(event) {
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].UserEvent(Object.assign({
+ event,
+ source: _TopSitesConstants__WEBPACK_IMPORTED_MODULE_1__["TOP_SITES_SOURCE"],
+ action_position: this.props.index
+ }, this._getTelemetryInfo())));
+ }
+
+ onLinkClick(event) {
+ this.userEvent("CLICK"); // Specially handle a top site link click for "typed" frecency bonus as
+ // specified as a property on the link.
+
+ event.preventDefault();
+ const {
+ altKey,
+ button,
+ ctrlKey,
+ metaKey,
+ shiftKey
+ } = event;
+
+ if (!this.props.link.searchTopSite) {
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].OnlyToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].OPEN_LINK,
+ data: Object.assign(this.props.link, {
+ event: {
+ altKey,
+ button,
+ ctrlKey,
+ metaKey,
+ shiftKey
+ }
+ })
+ })); // Fire off a spoc specific impression.
+
+ if (this.props.link.type === SPOC_TYPE) {
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].ImpressionStats({
+ source: _TopSitesConstants__WEBPACK_IMPORTED_MODULE_1__["TOP_SITES_SOURCE"],
+ click: 0,
+ tiles: [{
+ id: this.props.link.id,
+ pos: this.props.link.pos,
+ shim: this.props.link.shim && this.props.link.shim.click
+ }]
+ }));
+ }
+
+ if (this.props.link.sendAttributionRequest) {
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].OnlyToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].PARTNER_LINK_ATTRIBUTION,
+ data: {
+ targetURL: this.props.link.url,
+ source: "newtab"
+ }
+ }));
+ }
+ } else {
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].OnlyToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].FILL_SEARCH_TERM,
+ data: {
+ label: this.props.link.label
+ }
+ }));
+ }
+ }
+
+ onMenuUpdate(isOpen) {
+ if (isOpen) {
+ this.props.onActivate(this.props.index);
+ } else {
+ this.props.onActivate();
+ }
+ }
+
+ render() {
+ const {
+ props
+ } = this;
+ const {
+ link
+ } = props;
+ const isContextMenuOpen = props.activeIndex === props.index;
+ const title = link.label || link.hostname;
+ let menuOptions;
+
+ if (link.sponsored_position) {
+ menuOptions = _TopSitesConstants__WEBPACK_IMPORTED_MODULE_1__["TOP_SITES_SPONSORED_POSITION_CONTEXT_MENU_OPTIONS"];
+ } else if (link.searchTopSite) {
+ menuOptions = _TopSitesConstants__WEBPACK_IMPORTED_MODULE_1__["TOP_SITES_SEARCH_SHORTCUTS_CONTEXT_MENU_OPTIONS"];
+ } else if (link.type === SPOC_TYPE) {
+ menuOptions = _TopSitesConstants__WEBPACK_IMPORTED_MODULE_1__["TOP_SITES_SPOC_CONTEXT_MENU_OPTIONS"];
+ } else {
+ menuOptions = _TopSitesConstants__WEBPACK_IMPORTED_MODULE_1__["TOP_SITES_CONTEXT_MENU_OPTIONS"];
+ }
+
+ return react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement(TopSiteLink, _extends({}, props, {
+ onClick: this.onLinkClick,
+ onDragEvent: this.props.onDragEvent,
+ className: `${props.className || ""}${isContextMenuOpen ? " active" : ""}`,
+ title: title
+ }), react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("div", null, react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement(content_src_components_ContextMenu_ContextMenuButton__WEBPACK_IMPORTED_MODULE_7__["ContextMenuButton"], {
+ tooltip: "newtab-menu-content-tooltip",
+ tooltipArgs: {
+ title
+ },
+ onUpdate: this.onMenuUpdate
+ }, react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement(content_src_components_LinkMenu_LinkMenu__WEBPACK_IMPORTED_MODULE_2__["LinkMenu"], {
+ dispatch: props.dispatch,
+ index: props.index,
+ onUpdate: this.onMenuUpdate,
+ options: menuOptions,
+ site: link,
+ shouldSendImpressionStats: link.type === SPOC_TYPE,
+ siteInfo: this._getTelemetryInfo(),
+ source: _TopSitesConstants__WEBPACK_IMPORTED_MODULE_1__["TOP_SITES_SOURCE"]
+ }))));
+ }
+
+}
+TopSite.defaultProps = {
+ link: {},
+
+ onActivate() {}
+
+};
+class TopSitePlaceholder extends react__WEBPACK_IMPORTED_MODULE_4___default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onEditButtonClick = this.onEditButtonClick.bind(this);
+ }
+
+ onEditButtonClick() {
+ this.props.dispatch({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].TOP_SITES_EDIT,
+ data: {
+ index: this.props.index
+ }
+ });
+ }
+
+ render() {
+ return react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement(TopSiteLink, _extends({}, this.props, {
+ className: `placeholder ${this.props.className || ""}`,
+ isDraggable: false
+ }), react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("button", {
+ "aria-haspopup": "true",
+ className: "context-menu-button edit-button icon",
+ "data-l10n-id": "newtab-menu-topsites-placeholder-tooltip",
+ onClick: this.onEditButtonClick
+ }));
+ }
+
+}
+class TopSiteList extends react__WEBPACK_IMPORTED_MODULE_4___default.a.PureComponent {
+ static get DEFAULT_STATE() {
+ return {
+ activeIndex: null,
+ draggedIndex: null,
+ draggedSite: null,
+ draggedTitle: null,
+ topSitesPreview: null
+ };
+ }
+
+ constructor(props) {
+ super(props);
+ this.state = TopSiteList.DEFAULT_STATE;
+ this.onDragEvent = this.onDragEvent.bind(this);
+ this.onActivate = this.onActivate.bind(this);
+ }
+
+ componentWillReceiveProps(nextProps) {
+ if (this.state.draggedSite) {
+ const prevTopSites = this.props.TopSites && this.props.TopSites.rows;
+ const newTopSites = nextProps.TopSites && nextProps.TopSites.rows;
+
+ if (prevTopSites && prevTopSites[this.state.draggedIndex] && prevTopSites[this.state.draggedIndex].url === this.state.draggedSite.url && (!newTopSites[this.state.draggedIndex] || newTopSites[this.state.draggedIndex].url !== this.state.draggedSite.url)) {
+ // We got the new order from the redux store via props. We can clear state now.
+ this.setState(TopSiteList.DEFAULT_STATE);
+ }
+ }
+ }
+
+ userEvent(event, index) {
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].UserEvent({
+ event,
+ source: _TopSitesConstants__WEBPACK_IMPORTED_MODULE_1__["TOP_SITES_SOURCE"],
+ action_position: index
+ }));
+ }
+
+ onDragEvent(event, index, link, title) {
+ switch (event.type) {
+ case "dragstart":
+ this.dropped = false;
+ this.setState({
+ draggedIndex: index,
+ draggedSite: link,
+ draggedTitle: title,
+ activeIndex: null
+ });
+ this.userEvent("DRAG", index);
+ break;
+
+ case "dragend":
+ if (!this.dropped) {
+ // If there was no drop event, reset the state to the default.
+ this.setState(TopSiteList.DEFAULT_STATE);
+ }
+
+ break;
+
+ case "dragenter":
+ if (index === this.state.draggedIndex) {
+ this.setState({
+ topSitesPreview: null
+ });
+ } else {
+ this.setState({
+ topSitesPreview: this._makeTopSitesPreview(index)
+ });
+ }
+
+ break;
+
+ case "drop":
+ if (index !== this.state.draggedIndex) {
+ this.dropped = true;
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].AlsoToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].TOP_SITES_INSERT,
+ data: {
+ site: {
+ url: this.state.draggedSite.url,
+ label: this.state.draggedTitle,
+ customScreenshotURL: this.state.draggedSite.customScreenshotURL,
+ // Only if the search topsites experiment is enabled
+ ...(this.state.draggedSite.searchTopSite && {
+ searchTopSite: true
+ })
+ },
+ index,
+ draggedFromIndex: this.state.draggedIndex
+ }
+ }));
+ this.userEvent("DROP", index);
+ }
+
+ break;
+ }
+ }
+
+ _getTopSites() {
+ // Make a copy of the sites to truncate or extend to desired length
+ let topSites = this.props.TopSites.rows.slice();
+ topSites.length = this.props.TopSitesRows * common_Reducers_jsm__WEBPACK_IMPORTED_MODULE_6__["TOP_SITES_MAX_SITES_PER_ROW"];
+ return topSites;
+ }
+ /**
+ * Make a preview of the topsites that will be the result of dropping the currently
+ * dragged site at the specified index.
+ */
+
+
+ _makeTopSitesPreview(index) {
+ const topSites = this._getTopSites();
+
+ topSites[this.state.draggedIndex] = null;
+ const preview = topSites.map(site => site && (site.isPinned || site.sponsored_position) ? site : null);
+ const unpinned = topSites.filter(site => site && !site.isPinned && !site.sponsored_position);
+ const siteToInsert = Object.assign({}, this.state.draggedSite, {
+ isPinned: true,
+ isDragged: true
+ });
+
+ if (!preview[index]) {
+ preview[index] = siteToInsert;
+ } else {
+ // Find the hole to shift the pinned site(s) towards. We shift towards the
+ // hole left by the site being dragged.
+ let holeIndex = index;
+ const indexStep = index > this.state.draggedIndex ? -1 : 1;
+
+ while (preview[holeIndex]) {
+ holeIndex += indexStep;
+ } // Shift towards the hole.
+
+
+ const shiftingStep = index > this.state.draggedIndex ? 1 : -1;
+
+ while (index > this.state.draggedIndex ? holeIndex < index : holeIndex > index) {
+ let nextIndex = holeIndex + shiftingStep;
+
+ while (preview[nextIndex] && preview[nextIndex].sponsored_position) {
+ nextIndex += shiftingStep;
+ }
+
+ preview[holeIndex] = preview[nextIndex];
+ holeIndex = nextIndex;
+ }
+
+ preview[index] = siteToInsert;
+ } // Fill in the remaining holes with unpinned sites.
+
+
+ for (let i = 0; i < preview.length; i++) {
+ if (!preview[i]) {
+ preview[i] = unpinned.shift() || null;
+ }
+ }
+
+ return preview;
+ }
+
+ onActivate(index) {
+ this.setState({
+ activeIndex: index
+ });
+ }
+
+ render() {
+ const {
+ props
+ } = this;
+
+ const topSites = this.state.topSitesPreview || this._getTopSites();
+
+ const topSitesUI = [];
+ const commonProps = {
+ onDragEvent: this.onDragEvent,
+ dispatch: props.dispatch,
+ newNewtabExperienceEnabled: props.newNewtabExperienceEnabled
+ }; // We assign a key to each placeholder slot. We need it to be independent
+ // of the slot index (i below) so that the keys used stay the same during
+ // drag and drop reordering and the underlying DOM nodes are reused.
+ // This mostly (only?) affects linux so be sure to test on linux before changing.
+
+ let holeIndex = 0; // On narrow viewports, we only show 6 sites per row. We'll mark the rest as
+ // .hide-for-narrow to hide in CSS via @media query.
+
+ const maxNarrowVisibleIndex = props.TopSitesRows * 6;
+
+ for (let i = 0, l = topSites.length; i < l; i++) {
+ const link = topSites[i] && Object.assign({}, topSites[i], {
+ iconType: this.props.topSiteIconType(topSites[i])
+ });
+ const slotProps = {
+ key: link ? link.url : holeIndex++,
+ index: i
+ };
+
+ if (i >= maxNarrowVisibleIndex) {
+ slotProps.className = "hide-for-narrow";
+ }
+
+ topSitesUI.push(!link ? react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement(TopSitePlaceholder, _extends({}, slotProps, commonProps)) : react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement(TopSite, _extends({
+ link: link,
+ activeIndex: this.state.activeIndex,
+ onActivate: this.onActivate
+ }, slotProps, commonProps, {
+ colors: props.colors
+ })));
+ }
+
+ return react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("ul", {
+ className: `top-sites-list${this.state.draggedSite ? " dnd-active" : ""}`
+ }, topSitesUI);
+ }
+
+}
+
+/***/ }),
+/* 59 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HorizontalRule", function() { return HorizontalRule; });
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+class HorizontalRule extends react__WEBPACK_IMPORTED_MODULE_0___default.a.PureComponent {
+ render() {
+ return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("hr", {
+ className: "ds-hr"
+ });
+ }
+
+}
+
+/***/ }),
+/* 60 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Topic", function() { return Topic; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Navigation", function() { return Navigation; });
+/* harmony import */ var common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
+/* harmony import */ var _SafeAnchor_SafeAnchor__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(26);
+/* harmony import */ var content_src_components_FluentOrText_FluentOrText__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(30);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+
+
+class Topic extends react__WEBPACK_IMPORTED_MODULE_1___default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onLinkClick = this.onLinkClick.bind(this);
+ }
+
+ onLinkClick(event) {
+ if (this.props.dispatch) {
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].UserEvent({
+ event: "CLICK",
+ source: "POPULAR_TOPICS",
+ action_position: 0,
+ value: {
+ topic: event.target.text.toLowerCase().replace(` `, `-`)
+ }
+ }));
+ }
+ }
+
+ render() {
+ const {
+ url,
+ name
+ } = this.props;
+ return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(_SafeAnchor_SafeAnchor__WEBPACK_IMPORTED_MODULE_2__["SafeAnchor"], {
+ onLinkClick: this.onLinkClick,
+ className: this.props.className,
+ url: url
+ }, name);
+ }
+
+}
+class Navigation extends react__WEBPACK_IMPORTED_MODULE_1___default.a.PureComponent {
+ render() {
+ const links = this.props.links || [];
+ const alignment = this.props.alignment || "centered";
+ const header = this.props.header || {};
+ return react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("div", {
+ className: `ds-navigation ds-navigation-${alignment}`
+ }, header.title ? react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(content_src_components_FluentOrText_FluentOrText__WEBPACK_IMPORTED_MODULE_3__["FluentOrText"], {
+ message: header.title
+ }, react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("span", {
+ className: "ds-navigation-header"
+ })) : null, react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("ul", null, links && links.map(t => react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement("li", {
+ key: t.name
+ }, react__WEBPACK_IMPORTED_MODULE_1___default.a.createElement(Topic, {
+ url: t.url,
+ name: t.name,
+ dispatch: this.props.dispatch
+ })))));
+ }
+
+}
+
+/***/ }),
+/* 61 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SectionTitle", function() { return SectionTitle; });
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+class SectionTitle extends react__WEBPACK_IMPORTED_MODULE_0___default.a.PureComponent {
+ render() {
+ const {
+ header: {
+ title,
+ subtitle
+ }
+ } = this.props;
+ return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
+ className: "ds-section-title"
+ }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
+ className: "title"
+ }, title), subtitle ? react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
+ className: "subtitle"
+ }, subtitle) : null);
+ }
+
+}
+
+/***/ }),
+/* 62 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "selectLayoutRender", function() { return selectLayoutRender; });
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+const selectLayoutRender = ({
+ state = {},
+ prefs = {},
+ locale = ""
+}) => {
+ const {
+ layout,
+ feeds,
+ spocs
+ } = state;
+ let spocIndexPlacementMap = {};
+ /* This function fills spoc positions on a per placement basis with available spocs.
+ * It does this by looping through each position for a placement and replacing a rec with a spoc.
+ * If it runs out of spocs or positions, it stops.
+ * If it sees the same placement again, it remembers the previous spoc index, and continues.
+ * If it sees a blocked spoc, it skips that position leaving in a regular story.
+ */
+
+ function fillSpocPositionsForPlacement(data, spocsConfig, spocsData, placementName) {
+ if (!spocIndexPlacementMap[placementName] && spocIndexPlacementMap[placementName] !== 0) {
+ spocIndexPlacementMap[placementName] = 0;
+ }
+
+ const results = [...data];
+
+ for (let position of spocsConfig.positions) {
+ const spoc = spocsData[spocIndexPlacementMap[placementName]]; // If there are no spocs left, we can stop filling positions.
+
+ if (!spoc) {
+ break;
+ } // A placement could be used in two sections.
+ // In these cases, we want to maintain the index of the previous section.
+ // If we didn't do this, it might duplicate spocs.
+
+
+ spocIndexPlacementMap[placementName]++; // A spoc that's blocked is removed from the source for subsequent newtab loads.
+ // If we have a spoc in the source that's blocked, it means it was *just* blocked,
+ // and in this case, we skip this position, and show a regular spoc instead.
+
+ if (!spocs.blocked.includes(spoc.url)) {
+ results.splice(position.index, 0, spoc);
+ }
+ }
+
+ return results;
+ }
+
+ const positions = {};
+ const DS_COMPONENTS = ["Message", "TextPromo", "SectionTitle", "Signup", "Navigation", "CardGrid", "CollectionCardGrid", "Hero", "HorizontalRule", "List"];
+ const filterArray = [];
+
+ if (!prefs["feeds.topsites"]) {
+ filterArray.push("TopSites");
+ }
+
+ if (!locale.startsWith("en-")) {
+ filterArray.push("Navigation");
+ }
+
+ const pocketEnabled = prefs["feeds.section.topstories"] && prefs["feeds.system.topstories"];
+
+ if (!pocketEnabled) {
+ filterArray.push(...DS_COMPONENTS);
+ }
+
+ const placeholderComponent = component => {
+ if (!component.feed) {
+ // TODO we now need a placeholder for topsites and textPromo.
+ return { ...component,
+ data: {
+ spocs: []
+ }
+ };
+ }
+
+ const data = {
+ recommendations: []
+ };
+ let items = 0;
+
+ if (component.properties && component.properties.items) {
+ items = component.properties.items;
+ }
+
+ for (let i = 0; i < items; i++) {
+ data.recommendations.push({
+ placeholder: true
+ });
+ }
+
+ return { ...component,
+ data
+ };
+ }; // TODO update devtools to show placements
+
+
+ const handleSpocs = (data, component) => {
+ let result = [...data]; // Do we ever expect to possibly have a spoc.
+
+ if (component.spocs && component.spocs.positions && component.spocs.positions.length) {
+ const placement = component.placement || {};
+ const placementName = placement.name || "spocs";
+ const spocsData = spocs.data[placementName]; // We expect a spoc, spocs are loaded, and the server returned spocs.
+
+ if (spocs.loaded && spocsData && spocsData.items && spocsData.items.length) {
+ result = fillSpocPositionsForPlacement(result, component.spocs, spocsData.items, placementName);
+ }
+ }
+
+ return result;
+ };
+
+ const handleComponent = component => {
+ if (component.spocs && component.spocs.positions && component.spocs.positions.length) {
+ const placement = component.placement || {};
+ const placementName = placement.name || "spocs";
+ const spocsData = spocs.data[placementName];
+
+ if (spocs.loaded && spocsData && spocsData.items && spocsData.items.length) {
+ return { ...component,
+ data: {
+ spocs: spocsData.items.filter(spoc => spoc && !spocs.blocked.includes(spoc.url)).map((spoc, index) => ({ ...spoc,
+ pos: index
+ }))
+ }
+ };
+ }
+ }
+
+ return { ...component,
+ data: {
+ spocs: []
+ }
+ };
+ };
+
+ const handleComponentWithFeed = component => {
+ positions[component.type] = positions[component.type] || 0;
+ let data = {
+ recommendations: []
+ };
+ const feed = feeds.data[component.feed.url];
+
+ if (feed && feed.data) {
+ data = { ...feed.data,
+ recommendations: [...(feed.data.recommendations || [])]
+ };
+ }
+
+ if (component && component.properties && component.properties.offset) {
+ data = { ...data,
+ recommendations: data.recommendations.slice(component.properties.offset)
+ };
+ }
+
+ data = { ...data,
+ recommendations: handleSpocs(data.recommendations, component)
+ };
+ let items = 0;
+
+ if (component.properties && component.properties.items) {
+ items = Math.min(component.properties.items, data.recommendations.length);
+ } // loop through a component items
+ // Store the items position sequentially for multiple components of the same type.
+ // Example: A second card grid starts pos offset from the last card grid.
+
+
+ for (let i = 0; i < items; i++) {
+ data.recommendations[i] = { ...data.recommendations[i],
+ pos: positions[component.type]++
+ };
+ }
+
+ return { ...component,
+ data
+ };
+ };
+
+ const renderLayout = () => {
+ const renderedLayoutArray = [];
+
+ for (const row of layout.filter(r => r.components.filter(c => !filterArray.includes(c.type)).length)) {
+ let components = [];
+ renderedLayoutArray.push({ ...row,
+ components
+ });
+
+ for (const component of row.components.filter(c => !filterArray.includes(c.type))) {
+ const spocsConfig = component.spocs;
+
+ if (spocsConfig || component.feed) {
+ // TODO make sure this still works for different loading cases.
+ if (component.feed && !feeds.data[component.feed.url] || spocsConfig && spocsConfig.positions && spocsConfig.positions.length && !spocs.loaded) {
+ components.push(placeholderComponent(component));
+ return renderedLayoutArray;
+ }
+
+ if (component.feed) {
+ components.push(handleComponentWithFeed(component));
+ } else {
+ components.push(handleComponent(component));
+ }
+ } else {
+ components.push(component);
+ }
+ }
+ }
+
+ return renderedLayoutArray;
+ };
+
+ const layoutRender = renderLayout();
+ return {
+ layoutRender
+ };
+};
+
+/***/ }),
+/* 63 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_TopSites", function() { return _TopSites; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TopSites", function() { return TopSites; });
+/* harmony import */ var react_redux__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(7);
+/* harmony import */ var react_redux__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react_redux__WEBPACK_IMPORTED_MODULE_0__);
+/* harmony import */ var content_src_components_TopSites_TopSites__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(55);
+/* harmony import */ var common_Reducers_jsm__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(72);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_3__);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+
+
+class _TopSites extends react__WEBPACK_IMPORTED_MODULE_3___default.a.PureComponent {
+ // Find a SPOC that doesn't already exist in User's TopSites
+ getFirstAvailableSpoc(topSites, data) {
+ const {
+ spocs
+ } = data;
+
+ if (!spocs || spocs.length === 0) {
+ return null;
+ }
+
+ const userTopSites = new Set(topSites.map(topSite => topSite && topSite.url)); // We "clean urls" with http in TopSiteForm.jsx
+ // Spoc domains are in the format 'sponsorname.com'
+
+ return spocs.find(spoc => !userTopSites.has(spoc.url) && !userTopSites.has(`http://${spoc.domain}`) && !userTopSites.has(`https://${spoc.domain}`) && !userTopSites.has(`http://www.${spoc.domain}`) && !userTopSites.has(`https://www.${spoc.domain}`));
+ } // Find the first empty or unpinned index we can place the SPOC in.
+ // Return -1 if no available index and we should push it at the end.
+
+
+ getFirstAvailableIndex(topSites, promoAlignment) {
+ if (promoAlignment === "left") {
+ return topSites.findIndex(topSite => !topSite || !topSite.isPinned);
+ } // The row isn't full so we can push it to the end of the row.
+
+
+ if (topSites.length < common_Reducers_jsm__WEBPACK_IMPORTED_MODULE_2__["TOP_SITES_MAX_SITES_PER_ROW"]) {
+ return -1;
+ } // If the row is full, we can check the row first for unpinned topsites to replace.
+ // Else we can check after the row. This behavior is how unpinned topsites move while drag and drop.
+
+
+ let endOfRow = common_Reducers_jsm__WEBPACK_IMPORTED_MODULE_2__["TOP_SITES_MAX_SITES_PER_ROW"] - 1;
+
+ for (let i = endOfRow; i >= 0; i--) {
+ if (!topSites[i] || !topSites[i].isPinned) {
+ return i;
+ }
+ }
+
+ for (let i = endOfRow + 1; i < topSites.length; i++) {
+ if (!topSites[i] || !topSites[i].isPinned) {
+ return i;
+ }
+ }
+
+ return -1;
+ }
+
+ insertSpocContent(TopSites, data, promoAlignment) {
+ if (!TopSites.rows || TopSites.rows.length === 0 || !data.spocs || data.spocs.length === 0) {
+ return null;
+ }
+
+ let topSites = [...TopSites.rows];
+ const topSiteSpoc = this.getFirstAvailableSpoc(topSites, data);
+
+ if (!topSiteSpoc) {
+ return null;
+ }
+
+ const link = {
+ customScreenshotURL: topSiteSpoc.image_src,
+ type: "SPOC",
+ label: topSiteSpoc.sponsor,
+ title: topSiteSpoc.sponsor,
+ url: topSiteSpoc.url,
+ flightId: topSiteSpoc.flight_id,
+ id: topSiteSpoc.id,
+ guid: topSiteSpoc.id,
+ shim: topSiteSpoc.shim,
+ // For now we are assuming position based on intended position.
+ // Actual position can shift based on other content.
+ // We also hard code left and right to be 0 and 7.
+ // We send the intended postion in the ping.
+ pos: promoAlignment === "left" ? 0 : 7
+ };
+ const firstAvailableIndex = this.getFirstAvailableIndex(topSites, promoAlignment);
+
+ if (firstAvailableIndex === -1) {
+ topSites.push(link);
+ } else {
+ // Normal insertion will not work since pinned topsites are in their correct index already
+ // Similar logic is done to handle drag and drop with pinned topsites in TopSite.jsx
+ let shiftedTopSite = topSites[firstAvailableIndex];
+ let index = firstAvailableIndex + 1; // Shift unpinned topsites to the right by finding the next unpinned topsite to replace
+
+ while (shiftedTopSite) {
+ if (index === topSites.length) {
+ topSites.push(shiftedTopSite);
+ shiftedTopSite = null;
+ } else if (topSites[index] && topSites[index].isPinned) {
+ index += 1;
+ } else {
+ const nextTopSite = topSites[index];
+ topSites[index] = shiftedTopSite;
+ shiftedTopSite = nextTopSite;
+ index += 1;
+ }
+ }
+
+ topSites[firstAvailableIndex] = link;
+ }
+
+ return { ...TopSites,
+ rows: topSites
+ };
+ }
+
+ render() {
+ const {
+ header = {},
+ data,
+ promoAlignment,
+ TopSites
+ } = this.props;
+ const TopSitesWithSpoc = TopSites && data && promoAlignment ? this.insertSpocContent(TopSites, data, promoAlignment) : null;
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("div", {
+ className: `ds-top-sites ${TopSitesWithSpoc ? "top-sites-spoc" : ""}`
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement(content_src_components_TopSites_TopSites__WEBPACK_IMPORTED_MODULE_1__["TopSites"], {
+ isFixed: true,
+ title: header.title,
+ TopSitesWithSpoc: TopSitesWithSpoc
+ }));
+ }
+
+}
+const TopSites = Object(react_redux__WEBPACK_IMPORTED_MODULE_0__["connect"])(state => ({
+ TopSites: state.TopSites
+}))(_TopSites);
+
+/***/ }),
+/* 64 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_Search", function() { return _Search; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Search", function() { return Search; });
+/* harmony import */ var common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
+/* harmony import */ var react_redux__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(7);
+/* harmony import */ var react_redux__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react_redux__WEBPACK_IMPORTED_MODULE_1__);
+/* harmony import */ var content_src_lib_constants__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(13);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8);
+/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_3__);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* globals ContentSearchUIController, ContentSearchHandoffUIController */
+
+
+
+
+
+
+class _Search extends react__WEBPACK_IMPORTED_MODULE_3___default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onSearchClick = this.onSearchClick.bind(this);
+ this.onSearchHandoffClick = this.onSearchHandoffClick.bind(this);
+ this.onSearchHandoffPaste = this.onSearchHandoffPaste.bind(this);
+ this.onSearchHandoffDrop = this.onSearchHandoffDrop.bind(this);
+ this.onInputMount = this.onInputMount.bind(this);
+ this.onInputMountHandoff = this.onInputMountHandoff.bind(this);
+ this.onSearchHandoffButtonMount = this.onSearchHandoffButtonMount.bind(this);
+ }
+
+ handleEvent(event) {
+ // Also track search events with our own telemetry
+ if (event.detail.type === "Search") {
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].UserEvent({
+ event: "SEARCH"
+ }));
+ }
+ }
+
+ onSearchClick(event) {
+ window.gContentSearchController.search(event);
+ }
+
+ doSearchHandoff(text) {
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].OnlyToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].HANDOFF_SEARCH_TO_AWESOMEBAR,
+ data: {
+ text
+ }
+ }));
+ this.props.dispatch({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].FAKE_FOCUS_SEARCH
+ });
+ this.props.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].UserEvent({
+ event: "SEARCH_HANDOFF"
+ }));
+
+ if (text) {
+ this.props.dispatch({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].HIDE_SEARCH
+ });
+ }
+ }
+
+ onSearchHandoffClick(event) {
+ // When search hand-off is enabled, we render a big button that is styled to
+ // look like a search textbox. If the button is clicked, we style
+ // the button as if it was a focused search box and show a fake cursor but
+ // really focus the awesomebar without the focus styles ("hidden focus").
+ event.preventDefault();
+ this.doSearchHandoff();
+ }
+
+ onSearchHandoffPaste(event) {
+ event.preventDefault();
+ this.doSearchHandoff(event.clipboardData.getData("Text"));
+ }
+
+ onSearchHandoffDrop(event) {
+ event.preventDefault();
+ let text = event.dataTransfer.getData("text");
+
+ if (text) {
+ this.doSearchHandoff(text);
+ }
+ }
+
+ componentWillUnmount() {
+ delete window.gContentSearchController;
+ }
+
+ onInputMount(input) {
+ if (input) {
+ // The "healthReportKey" and needs to be "newtab" or "abouthome" so that
+ // BrowserUsageTelemetry.jsm knows to handle events with this name, and
+ // can add the appropriate telemetry probes for search. Without the correct
+ // name, certain tests like browser_UsageTelemetry_content.js will fail
+ // (See github ticket #2348 for more details)
+ const healthReportKey = content_src_lib_constants__WEBPACK_IMPORTED_MODULE_2__["IS_NEWTAB"] ? "newtab" : "abouthome"; // The "searchSource" needs to be "newtab" or "homepage" and is sent with
+ // the search data and acts as context for the search request (See
+ // nsISearchEngine.getSubmission). It is necessary so that search engine
+ // plugins can correctly atribute referrals. (See github ticket #3321 for
+ // more details)
+
+ const searchSource = content_src_lib_constants__WEBPACK_IMPORTED_MODULE_2__["IS_NEWTAB"] ? "newtab" : "homepage"; // gContentSearchController needs to exist as a global so that tests for
+ // the existing about:home can find it; and so it allows these tests to pass.
+ // In the future, when activity stream is default about:home, this can be renamed
+
+ window.gContentSearchController = new ContentSearchUIController(input, input.parentNode, healthReportKey, searchSource);
+ addEventListener("ContentSearchClient", this);
+ } else {
+ window.gContentSearchController = null;
+ removeEventListener("ContentSearchClient", this);
+ }
+ }
+
+ onInputMountHandoff(input) {
+ if (input) {
+ // The handoff UI controller helps usset the search icon and reacts to
+ // changes to default engine to keep everything in sync.
+ this._handoffSearchController = new ContentSearchHandoffUIController();
+ }
+ }
+
+ onSearchHandoffButtonMount(button) {
+ // Keep a reference to the button for use during "paste" event handling.
+ this._searchHandoffButton = button;
+ }
+ /*
+ * Do not change the ID on the input field, as legacy newtab code
+ * specifically looks for the id 'newtab-search-text' on input fields
+ * in order to execute searches in various tests
+ */
+
+
+ render() {
+ const wrapperClassName = ["search-wrapper", this.props.hide && "search-hidden", this.props.fakeFocus && "fake-focus"].filter(v => v).join(" ");
+ const isNewNewtabExperienceEnabled = this.props.Prefs.values["newNewtabExperience.enabled"];
+ return react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("div", {
+ className: wrapperClassName
+ }, this.props.showLogo && react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("div", {
+ className: "logo-and-wordmark"
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("div", {
+ className: "logo"
+ }), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("div", {
+ className: "wordmark"
+ })), !this.props.handoffEnabled && react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("div", {
+ className: "search-inner-wrapper"
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("input", {
+ id: "newtab-search-text",
+ "data-l10n-id": isNewNewtabExperienceEnabled ? "newtab-search-box-input" : "newtab-search-box-search-the-web-input",
+ maxLength: "256",
+ ref: this.onInputMount,
+ type: "search"
+ }), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("button", {
+ id: "searchSubmit",
+ className: "search-button",
+ "data-l10n-id": "newtab-search-box-search-button",
+ onClick: this.onSearchClick
+ })), this.props.handoffEnabled && react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("div", {
+ className: "search-inner-wrapper"
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("button", {
+ className: "search-handoff-button",
+ "data-l10n-id": isNewNewtabExperienceEnabled ? "newtab-search-box-input" : "newtab-search-box-search-the-web-input",
+ ref: this.onSearchHandoffButtonMount,
+ onClick: this.onSearchHandoffClick,
+ tabIndex: "-1"
+ }, react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("div", {
+ className: "fake-textbox",
+ "data-l10n-id": isNewNewtabExperienceEnabled ? "newtab-search-box-text" : "newtab-search-box-search-the-web-text"
+ }), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("input", {
+ type: "search",
+ className: "fake-editable",
+ tabIndex: "-1",
+ "aria-hidden": "true",
+ onDrop: this.onSearchHandoffDrop,
+ onPaste: this.onSearchHandoffPaste,
+ ref: this.onInputMountHandoff
+ }), react__WEBPACK_IMPORTED_MODULE_3___default.a.createElement("div", {
+ className: "fake-caret"
+ }))));
+ }
+
+}
+const Search = Object(react_redux__WEBPACK_IMPORTED_MODULE_1__["connect"])(state => ({
+ Prefs: state.Prefs
+}))(_Search);
+
+/***/ }),
+/* 65 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* WEBPACK VAR INJECTION */(function(global) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DetectUserSessionStart", function() { return DetectUserSessionStart; });
+/* harmony import */ var common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
+/* harmony import */ var content_src_lib_perf_service__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(51);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+const VISIBLE = "visible";
+const VISIBILITY_CHANGE_EVENT = "visibilitychange";
+class DetectUserSessionStart {
+ constructor(store, options = {}) {
+ this._store = store; // Overrides for testing
+
+ this.document = options.document || global.document;
+ this._perfService = options.perfService || content_src_lib_perf_service__WEBPACK_IMPORTED_MODULE_1__["perfService"];
+ this._onVisibilityChange = this._onVisibilityChange.bind(this);
+ }
+ /**
+ * sendEventOrAddListener - Notify immediately if the page is already visible,
+ * or else set up a listener for when visibility changes.
+ * This is needed for accurate session tracking for telemetry,
+ * because tabs are pre-loaded.
+ */
+
+
+ sendEventOrAddListener() {
+ if (this.document.visibilityState === VISIBLE) {
+ // If the document is already visible, to the user, send a notification
+ // immediately that a session has started.
+ this._sendEvent();
+ } else {
+ // If the document is not visible, listen for when it does become visible.
+ this.document.addEventListener(VISIBILITY_CHANGE_EVENT, this._onVisibilityChange);
+ }
+ }
+ /**
+ * _sendEvent - Sends a message to the main process to indicate the current
+ * tab is now visible to the user, includes the
+ * visibility_event_rcvd_ts time in ms from the UNIX epoch.
+ */
+
+
+ _sendEvent() {
+ this._perfService.mark("visibility_event_rcvd_ts");
+
+ try {
+ let visibility_event_rcvd_ts = this._perfService.getMostRecentAbsMarkStartByName("visibility_event_rcvd_ts");
+
+ this._store.dispatch(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].AlsoToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].SAVE_SESSION_PERF_DATA,
+ data: {
+ visibility_event_rcvd_ts
+ }
+ }));
+ } catch (ex) {// If this failed, it's likely because the `privacy.resistFingerprinting`
+ // pref is true. We should at least not blow up.
+ }
+ }
+ /**
+ * _onVisibilityChange - If the visibility has changed to visible, sends a notification
+ * and removes the event listener. This should only be called once per tab.
+ */
+
+
+ _onVisibilityChange() {
+ if (this.document.visibilityState === VISIBLE) {
+ this._sendEvent();
+
+ this.document.removeEventListener(VISIBILITY_CHANGE_EVENT, this._onVisibilityChange);
+ }
+ }
+
+}
+/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(3)))
+
+/***/ }),
+/* 66 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+/* WEBPACK VAR INJECTION */(function(global) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MERGE_STORE_ACTION", function() { return MERGE_STORE_ACTION; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OUTGOING_MESSAGE_NAME", function() { return OUTGOING_MESSAGE_NAME; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "INCOMING_MESSAGE_NAME", function() { return INCOMING_MESSAGE_NAME; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EARLY_QUEUED_ACTIONS", function() { return EARLY_QUEUED_ACTIONS; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "rehydrationMiddleware", function() { return rehydrationMiddleware; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "queueEarlyMessageMiddleware", function() { return queueEarlyMessageMiddleware; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initStore", function() { return initStore; });
+/* harmony import */ var common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
+/* harmony import */ var redux__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(67);
+/* harmony import */ var redux__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(redux__WEBPACK_IMPORTED_MODULE_1__);
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* eslint-env mozilla/frame-script */
+
+
+const MERGE_STORE_ACTION = "NEW_TAB_INITIAL_STATE";
+const OUTGOING_MESSAGE_NAME = "ActivityStream:ContentToMain";
+const INCOMING_MESSAGE_NAME = "ActivityStream:MainToContent";
+const EARLY_QUEUED_ACTIONS = [common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].SAVE_SESSION_PERF_DATA];
+/**
+ * A higher-order function which returns a reducer that, on MERGE_STORE action,
+ * will return the action.data object merged into the previous state.
+ *
+ * For all other actions, it merely calls mainReducer.
+ *
+ * Because we want this to merge the entire state object, it's written as a
+ * higher order function which takes the main reducer (itself often a call to
+ * combineReducers) as a parameter.
+ *
+ * @param {function} mainReducer reducer to call if action != MERGE_STORE_ACTION
+ * @return {function} a reducer that, on MERGE_STORE_ACTION action,
+ * will return the action.data object merged
+ * into the previous state, and the result
+ * of calling mainReducer otherwise.
+ */
+
+function mergeStateReducer(mainReducer) {
+ return (prevState, action) => {
+ if (action.type === MERGE_STORE_ACTION) {
+ return { ...prevState,
+ ...action.data
+ };
+ }
+
+ return mainReducer(prevState, action);
+ };
+}
+/**
+ * messageMiddleware - Middleware that looks for SentToMain type actions, and sends them if necessary
+ */
+
+
+const messageMiddleware = store => next => action => {
+ const skipLocal = action.meta && action.meta.skipLocal;
+
+ if (common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionUtils"].isSendToMain(action)) {
+ RPMSendAsyncMessage(OUTGOING_MESSAGE_NAME, action);
+ }
+
+ if (!skipLocal) {
+ next(action);
+ }
+};
+
+const rehydrationMiddleware = ({
+ getState
+}) => {
+ // NB: The parameter here is MiddlewareAPI which looks like a Store and shares
+ // the same getState, so attached properties are accessible from the store.
+ getState.didRehydrate = false;
+ getState.didRequestInitialState = false;
+ return next => action => {
+ if (getState.didRehydrate || window.__FROM_STARTUP_CACHE__) {
+ // Startup messages can be safely ignored by the about:home document
+ // stored in the startup cache.
+ if (window.__FROM_STARTUP_CACHE__ && action.meta && action.meta.isStartup) {
+ return null;
+ }
+
+ return next(action);
+ }
+
+ const isMergeStoreAction = action.type === MERGE_STORE_ACTION;
+ const isRehydrationRequest = action.type === common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].NEW_TAB_STATE_REQUEST;
+
+ if (isRehydrationRequest) {
+ getState.didRequestInitialState = true;
+ return next(action);
+ }
+
+ if (isMergeStoreAction) {
+ getState.didRehydrate = true;
+ return next(action);
+ } // If init happened after our request was made, we need to re-request
+
+
+ if (getState.didRequestInitialState && action.type === common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].INIT) {
+ return next(common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionCreators"].AlsoToMain({
+ type: common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionTypes"].NEW_TAB_STATE_REQUEST
+ }));
+ }
+
+ if (common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionUtils"].isBroadcastToContent(action) || common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionUtils"].isSendToOneContent(action) || common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionUtils"].isSendToPreloaded(action)) {
+ // Note that actions received before didRehydrate will not be dispatched
+ // because this could negatively affect preloading and the the state
+ // will be replaced by rehydration anyway.
+ return null;
+ }
+
+ return next(action);
+ };
+};
+/**
+ * This middleware queues up all the EARLY_QUEUED_ACTIONS until it receives
+ * the first action from main. This is useful for those actions for main which
+ * require higher reliability, i.e. the action will not be lost in the case
+ * that it gets sent before the main is ready to receive it. Conversely, any
+ * actions allowed early are accepted to be ignorable or re-sendable.
+ */
+
+const queueEarlyMessageMiddleware = ({
+ getState
+}) => {
+ // NB: The parameter here is MiddlewareAPI which looks like a Store and shares
+ // the same getState, so attached properties are accessible from the store.
+ getState.earlyActionQueue = [];
+ getState.receivedFromMain = false;
+ return next => action => {
+ if (getState.receivedFromMain) {
+ next(action);
+ } else if (common_Actions_jsm__WEBPACK_IMPORTED_MODULE_0__["actionUtils"].isFromMain(action)) {
+ next(action);
+ getState.receivedFromMain = true; // Sending out all the early actions as main is ready now
+
+ getState.earlyActionQueue.forEach(next);
+ getState.earlyActionQueue.length = 0;
+ } else if (EARLY_QUEUED_ACTIONS.includes(action.type)) {
+ getState.earlyActionQueue.push(action);
+ } else {
+ // Let any other type of action go through
+ next(action);
+ }
+ };
+};
+/**
+ * initStore - Create a store and listen for incoming actions
+ *
+ * @param {object} reducers An object containing Redux reducers
+ * @param {object} intialState (optional) The initial state of the store, if desired
+ * @return {object} A redux store
+ */
+
+function initStore(reducers, initialState) {
+ const store = Object(redux__WEBPACK_IMPORTED_MODULE_1__["createStore"])(mergeStateReducer(Object(redux__WEBPACK_IMPORTED_MODULE_1__["combineReducers"])(reducers)), initialState, global.RPMAddMessageListener && Object(redux__WEBPACK_IMPORTED_MODULE_1__["applyMiddleware"])(queueEarlyMessageMiddleware, rehydrationMiddleware, messageMiddleware));
+
+ if (global.RPMAddMessageListener) {
+ global.RPMAddMessageListener(INCOMING_MESSAGE_NAME, msg => {
+ try {
+ store.dispatch(msg.data);
+ } catch (ex) {
+ console.error("Content msg:", msg, "Dispatch error: ", ex); // eslint-disable-line no-console
+
+ dump(`Content msg: ${JSON.stringify(msg)}\nDispatch error: ${ex}\n${ex.stack}`);
+ }
+ });
+ }
+
+ return store;
+}
+/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(3)))
+
+/***/ }),
+/* 67 */
+/***/ (function(module, exports) {
+
+module.exports = Redux;
+
+/***/ }),
+/* 68 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+
+// EXTERNAL MODULE: external "React"
+var external_React_ = __webpack_require__(8);
+
+// EXTERNAL MODULE: external "PropTypes"
+var external_PropTypes_ = __webpack_require__(12);
+var external_PropTypes_default = /*#__PURE__*/__webpack_require__.n(external_PropTypes_);
+
+// CONCATENATED MODULE: ./node_modules/fluent-sequence/src/map_sync.js
+/*
+ * Synchronously map an identifier or an array of identifiers to the best
+ * `FluentBundle` instance(s).
+ *
+ * @param {Iterable} iterable
+ * @param {string|Array<string>} ids
+ * @returns {FluentBundle|Array<FluentBundle>}
+ */
+function mapBundleSync(iterable, ids) {
+ if (!Array.isArray(ids)) {
+ return getBundleForId(iterable, ids);
+ }
+
+ return ids.map(
+ id => getBundleForId(iterable, id)
+ );
+}
+
+/*
+ * Find the best `FluentBundle` with the translation for `id`.
+ */
+function getBundleForId(iterable, id) {
+ for (const bundle of iterable) {
+ if (bundle.hasMessage(id)) {
+ return bundle;
+ }
+ }
+
+ return null;
+}
+
+// CONCATENATED MODULE: ./node_modules/fluent-sequence/src/map_async.js
+/*
+ * Asynchronously map an identifier or an array of identifiers to the best
+ * `FluentBundle` instance(s).
+ *
+ * @param {AsyncIterable} iterable
+ * @param {string|Array<string>} ids
+ * @returns {Promise<FluentBundle|Array<FluentBundle>>}
+ */
+async function mapBundleAsync(iterable, ids) {
+ if (!Array.isArray(ids)) {
+ for await (const bundle of iterable) {
+ if (bundle.hasMessage(ids)) {
+ return bundle;
+ }
+ }
+ }
+
+ let remainingCount = ids.length;
+ const foundBundles = new Array(remainingCount).fill(null);
+
+ for await (const bundle of iterable) {
+ for (const [index, id] of ids.entries()) {
+ if (!foundBundles[index] && bundle.hasMessage(id)) {
+ foundBundles[index] = bundle;
+ remainingCount--;
+ }
+
+ // Return early when all ids have been mapped to contexts.
+ if (remainingCount === 0) {
+ return foundBundles;
+ }
+ }
+ }
+
+ return foundBundles;
+}
+
+// CONCATENATED MODULE: ./node_modules/fluent-sequence/src/index.js
+/*
+ * @module fluent-sequence
+ * @overview Manage ordered sequences of FluentBundles.
+ */
+
+
+
+
+// CONCATENATED MODULE: ./node_modules/cached-iterable/src/cached_iterable.mjs
+/*
+ * Base CachedIterable class.
+ */
+class CachedIterable extends Array {
+ /**
+ * Create a `CachedIterable` instance from an iterable or, if another
+ * instance of `CachedIterable` is passed, return it without any
+ * modifications.
+ *
+ * @param {Iterable} iterable
+ * @returns {CachedIterable}
+ */
+ static from(iterable) {
+ if (iterable instanceof this) {
+ return iterable;
+ }
+
+ return new this(iterable);
+ }
+}
+
+// CONCATENATED MODULE: ./node_modules/cached-iterable/src/cached_sync_iterable.mjs
+
+
+/*
+ * CachedSyncIterable caches the elements yielded by an iterable.
+ *
+ * It can be used to iterate over an iterable many times without depleting the
+ * iterable.
+ */
+class cached_sync_iterable_CachedSyncIterable extends CachedIterable {
+ /**
+ * Create an `CachedSyncIterable` instance.
+ *
+ * @param {Iterable} iterable
+ * @returns {CachedSyncIterable}
+ */
+ constructor(iterable) {
+ super();
+
+ if (Symbol.iterator in Object(iterable)) {
+ this.iterator = iterable[Symbol.iterator]();
+ } else {
+ throw new TypeError("Argument must implement the iteration protocol.");
+ }
+ }
+
+ [Symbol.iterator]() {
+ const cached = this;
+ let cur = 0;
+
+ return {
+ next() {
+ if (cached.length <= cur) {
+ cached.push(cached.iterator.next());
+ }
+ return cached[cur++];
+ }
+ };
+ }
+
+ /**
+ * This method allows user to consume the next element from the iterator
+ * into the cache.
+ *
+ * @param {number} count - number of elements to consume
+ */
+ touchNext(count = 1) {
+ let idx = 0;
+ while (idx++ < count) {
+ const last = this[this.length - 1];
+ if (last && last.done) {
+ break;
+ }
+ this.push(this.iterator.next());
+ }
+ // Return the last cached {value, done} object to allow the calling
+ // code to decide if it needs to call touchNext again.
+ return this[this.length - 1];
+ }
+}
+
+// CONCATENATED MODULE: ./node_modules/cached-iterable/src/cached_async_iterable.mjs
+
+
+/*
+ * CachedAsyncIterable caches the elements yielded by an async iterable.
+ *
+ * It can be used to iterate over an iterable many times without depleting the
+ * iterable.
+ */
+class cached_async_iterable_CachedAsyncIterable extends CachedIterable {
+ /**
+ * Create an `CachedAsyncIterable` instance.
+ *
+ * @param {Iterable} iterable
+ * @returns {CachedAsyncIterable}
+ */
+ constructor(iterable) {
+ super();
+
+ if (Symbol.asyncIterator in Object(iterable)) {
+ this.iterator = iterable[Symbol.asyncIterator]();
+ } else if (Symbol.iterator in Object(iterable)) {
+ this.iterator = iterable[Symbol.iterator]();
+ } else {
+ throw new TypeError("Argument must implement the iteration protocol.");
+ }
+ }
+
+ /**
+ * Synchronous iterator over the cached elements.
+ *
+ * Return a generator object implementing the iterator protocol over the
+ * cached elements of the original (async or sync) iterable.
+ */
+ [Symbol.iterator]() {
+ const cached = this;
+ let cur = 0;
+
+ return {
+ next() {
+ if (cached.length === cur) {
+ return {value: undefined, done: true};
+ }
+ return cached[cur++];
+ }
+ };
+ }
+
+ /**
+ * Asynchronous iterator caching the yielded elements.
+ *
+ * Elements yielded by the original iterable will be cached and available
+ * synchronously. Returns an async generator object implementing the
+ * iterator protocol over the elements of the original (async or sync)
+ * iterable.
+ */
+ [Symbol.asyncIterator]() {
+ const cached = this;
+ let cur = 0;
+
+ return {
+ async next() {
+ if (cached.length <= cur) {
+ cached.push(await cached.iterator.next());
+ }
+ return cached[cur++];
+ }
+ };
+ }
+
+ /**
+ * This method allows user to consume the next element from the iterator
+ * into the cache.
+ *
+ * @param {number} count - number of elements to consume
+ */
+ async touchNext(count = 1) {
+ let idx = 0;
+ while (idx++ < count) {
+ const last = this[this.length - 1];
+ if (last && last.done) {
+ break;
+ }
+ this.push(await this.iterator.next());
+ }
+ // Return the last cached {value, done} object to allow the calling
+ // code to decide if it needs to call touchNext again.
+ return this[this.length - 1];
+ }
+}
+
+// CONCATENATED MODULE: ./node_modules/cached-iterable/src/index.mjs
+
+
+
+// CONCATENATED MODULE: ./node_modules/fluent-react/src/localization.js
+
+
+/*
+ * `ReactLocalization` handles translation formatting and fallback.
+ *
+ * The current negotiated fallback chain of languages is stored in the
+ * `ReactLocalization` instance in form of an iterable of `FluentBundle`
+ * instances. This iterable is used to find the best existing translation for
+ * a given identifier.
+ *
+ * `Localized` components must subscribe to the changes of the
+ * `ReactLocalization`'s fallback chain. When the fallback chain changes (the
+ * `bundles` iterable is set anew), all subscribed compontent must relocalize.
+ *
+ * The `ReactLocalization` class instances are exposed to `Localized` elements
+ * via the `LocalizationProvider` component.
+ */
+
+class localization_ReactLocalization {
+ constructor(bundles) {
+ this.bundles = cached_sync_iterable_CachedSyncIterable.from(bundles);
+ this.subs = new Set();
+ }
+ /*
+ * Subscribe a `Localized` component to changes of `bundles`.
+ */
+
+
+ subscribe(comp) {
+ this.subs.add(comp);
+ }
+ /*
+ * Unsubscribe a `Localized` component from `bundles` changes.
+ */
+
+
+ unsubscribe(comp) {
+ this.subs.delete(comp);
+ }
+ /*
+ * Set a new `bundles` iterable and trigger the retranslation.
+ */
+
+
+ setBundles(bundles) {
+ this.bundles = cached_sync_iterable_CachedSyncIterable.from(bundles); // Update all subscribed Localized components.
+
+ this.subs.forEach(comp => comp.relocalize());
+ }
+
+ getBundle(id) {
+ return mapBundleSync(this.bundles, id);
+ }
+ /*
+ * Find a translation by `id` and format it to a string using `args`.
+ */
+
+
+ getString(id, args, fallback) {
+ const bundle = this.getBundle(id);
+
+ if (bundle === null) {
+ return fallback || id;
+ }
+
+ const msg = bundle.getMessage(id);
+ return bundle.format(msg, args);
+ }
+
+}
+function isReactLocalization(props, propName) {
+ const prop = props[propName];
+
+ if (prop instanceof localization_ReactLocalization) {
+ return null;
+ }
+
+ return new Error(`The ${propName} context field must be an instance of ReactLocalization.`);
+}
+// CONCATENATED MODULE: ./node_modules/fluent-react/src/markup.js
+/* eslint-env browser */
+let cachedParseMarkup; // We use a function creator to make the reference to `document` lazy. At the
+// same time, it's eager enough to throw in <LocalizationProvider> as soon as
+// it's first mounted which reduces the risk of this error making it to the
+// runtime without developers noticing it in development.
+
+function createParseMarkup() {
+ if (typeof document === "undefined") {
+ // We can't use <template> to sanitize translations.
+ throw new Error("`document` is undefined. Without it, translations cannot " + "be safely sanitized. Consult the documentation at " + "https://github.com/projectfluent/fluent.js/wiki/React-Overlays.");
+ }
+
+ if (!cachedParseMarkup) {
+ const template = document.createElement("template");
+
+ cachedParseMarkup = function parseMarkup(str) {
+ template.innerHTML = str;
+ return Array.from(template.content.childNodes);
+ };
+ }
+
+ return cachedParseMarkup;
+}
+// CONCATENATED MODULE: ./node_modules/fluent-react/src/provider.js
+
+
+
+
+/*
+ * The Provider component for the `ReactLocalization` class.
+ *
+ * Exposes a `ReactLocalization` instance to all descendants via React's
+ * context feature. It makes translations available to all localizable
+ * elements in the descendant's render tree without the need to pass them
+ * explicitly.
+ *
+ * <LocalizationProvider bundles={…}>
+ * …
+ * </LocalizationProvider>
+ *
+ * The `LocalizationProvider` component takes one prop: `bundles`. It should
+ * be an iterable of `FluentBundle` instances in order of the user's
+ * preferred languages. The `FluentBundle` instances will be used by
+ * `ReactLocalization` to format translations. If a translation is missing in
+ * one instance, `ReactLocalization` will fall back to the next one.
+ */
+
+class provider_LocalizationProvider extends external_React_["Component"] {
+ constructor(props) {
+ super(props);
+ const {
+ bundles,
+ parseMarkup
+ } = props;
+
+ if (bundles === undefined) {
+ throw new Error("LocalizationProvider must receive the bundles prop.");
+ }
+
+ if (!bundles[Symbol.iterator]) {
+ throw new Error("The bundles prop must be an iterable.");
+ }
+
+ this.l10n = new localization_ReactLocalization(bundles);
+ this.parseMarkup = parseMarkup || createParseMarkup();
+ }
+
+ getChildContext() {
+ return {
+ l10n: this.l10n,
+ parseMarkup: this.parseMarkup
+ };
+ }
+
+ componentWillReceiveProps(next) {
+ const {
+ bundles
+ } = next;
+
+ if (bundles !== this.props.bundles) {
+ this.l10n.setBundles(bundles);
+ }
+ }
+
+ render() {
+ return external_React_["Children"].only(this.props.children);
+ }
+
+}
+provider_LocalizationProvider.childContextTypes = {
+ l10n: isReactLocalization,
+ parseMarkup: external_PropTypes_default.a.func
+};
+provider_LocalizationProvider.propTypes = {
+ children: external_PropTypes_default.a.element.isRequired,
+ bundles: isIterable,
+ parseMarkup: external_PropTypes_default.a.func
+};
+
+function isIterable(props, propName, componentName) {
+ const prop = props[propName];
+
+ if (Symbol.iterator in Object(prop)) {
+ return null;
+ }
+
+ return new Error(`The ${propName} prop supplied to ${componentName} must be an iterable.`);
+}
+// CONCATENATED MODULE: ./node_modules/fluent-react/src/with_localization.js
+
+
+function withLocalization(Inner) {
+ class WithLocalization extends external_React_["Component"] {
+ componentDidMount() {
+ const {
+ l10n
+ } = this.context;
+
+ if (l10n) {
+ l10n.subscribe(this);
+ }
+ }
+
+ componentWillUnmount() {
+ const {
+ l10n
+ } = this.context;
+
+ if (l10n) {
+ l10n.unsubscribe(this);
+ }
+ }
+ /*
+ * Rerender this component in a new language.
+ */
+
+
+ relocalize() {
+ // When the `ReactLocalization`'s fallback chain changes, update the
+ // component.
+ this.forceUpdate();
+ }
+ /*
+ * Find a translation by `id` and format it to a string using `args`.
+ */
+
+
+ getString(id, args, fallback) {
+ const {
+ l10n
+ } = this.context;
+
+ if (!l10n) {
+ return fallback || id;
+ }
+
+ return l10n.getString(id, args, fallback);
+ }
+
+ render() {
+ return Object(external_React_["createElement"])(Inner, Object.assign( // getString needs to be re-bound on updates to trigger a re-render
+ {
+ getString: (...args) => this.getString(...args)
+ }, this.props));
+ }
+
+ }
+
+ WithLocalization.displayName = `WithLocalization(${displayName(Inner)})`;
+ WithLocalization.contextTypes = {
+ l10n: isReactLocalization
+ };
+ return WithLocalization;
+}
+
+function displayName(component) {
+ return component.displayName || component.name || "Component";
+}
+// CONCATENATED MODULE: ./node_modules/fluent-react/vendor/omittedCloseTags.js
+/**
+ * Copyright (c) 2013-present, Facebook, Inc.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in this directory.
+ */
+// For HTML, certain tags should omit their close tag. We keep a whitelist for
+// those special-case tags.
+var omittedCloseTags = {
+ area: true,
+ base: true,
+ br: true,
+ col: true,
+ embed: true,
+ hr: true,
+ img: true,
+ input: true,
+ keygen: true,
+ link: true,
+ meta: true,
+ param: true,
+ source: true,
+ track: true,
+ wbr: true // NOTE: menuitem's close tag should be omitted, but that causes problems.
+
+};
+/* harmony default export */ var vendor_omittedCloseTags = (omittedCloseTags);
+// CONCATENATED MODULE: ./node_modules/fluent-react/vendor/voidElementTags.js
+/**
+ * Copyright (c) 2013-present, Facebook, Inc.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in this directory.
+ */
+ // For HTML, certain tags cannot have children. This has the same purpose as
+// `omittedCloseTags` except that `menuitem` should still have its closing tag.
+
+var voidElementTags = {
+ menuitem: true,
+ ...vendor_omittedCloseTags
+};
+/* harmony default export */ var vendor_voidElementTags = (voidElementTags);
+// CONCATENATED MODULE: ./node_modules/fluent-react/src/localized.js
+
+
+
+ // Match the opening angle bracket (<) in HTML tags, and HTML entities like
+// &amp;, &#0038;, &#x0026;.
+
+const reMarkup = /<|&#?\w+;/;
+/*
+ * Prepare props passed to `Localized` for formatting.
+ */
+
+function toArguments(props) {
+ const args = {};
+ const elems = {};
+
+ for (const [propname, propval] of Object.entries(props)) {
+ if (propname.startsWith("$")) {
+ const name = propname.substr(1);
+ args[name] = propval;
+ } else if (Object(external_React_["isValidElement"])(propval)) {
+ // We'll try to match localNames of elements found in the translation with
+ // names of elements passed as props. localNames are always lowercase.
+ const name = propname.toLowerCase();
+ elems[name] = propval;
+ }
+ }
+
+ return [args, elems];
+}
+/*
+ * The `Localized` class renders its child with translated props and children.
+ *
+ * <Localized id="hello-world">
+ * <p>{'Hello, world!'}</p>
+ * </Localized>
+ *
+ * The `id` prop should be the unique identifier of the translation. Any
+ * attributes found in the translation will be applied to the wrapped element.
+ *
+ * Arguments to the translation can be passed as `$`-prefixed props on
+ * `Localized`.
+ *
+ * <Localized id="hello-world" $username={name}>
+ * <p>{'Hello, { $username }!'}</p>
+ * </Localized>
+ *
+ * It's recommended that the contents of the wrapped component be a string
+ * expression. The string will be used as the ultimate fallback if no
+ * translation is available. It also makes it easy to grep for strings in the
+ * source code.
+ */
+
+
+class localized_Localized extends external_React_["Component"] {
+ componentDidMount() {
+ const {
+ l10n
+ } = this.context;
+
+ if (l10n) {
+ l10n.subscribe(this);
+ }
+ }
+
+ componentWillUnmount() {
+ const {
+ l10n
+ } = this.context;
+
+ if (l10n) {
+ l10n.unsubscribe(this);
+ }
+ }
+ /*
+ * Rerender this component in a new language.
+ */
+
+
+ relocalize() {
+ // When the `ReactLocalization`'s fallback chain changes, update the
+ // component.
+ this.forceUpdate();
+ }
+
+ render() {
+ const {
+ l10n,
+ parseMarkup
+ } = this.context;
+ const {
+ id,
+ attrs,
+ children: elem = null
+ } = this.props; // Validate that the child element isn't an array
+
+ if (Array.isArray(elem)) {
+ throw new Error("<Localized/> expected to receive a single " + "React node child");
+ }
+
+ if (!l10n) {
+ // Use the wrapped component as fallback.
+ return elem;
+ }
+
+ const bundle = l10n.getBundle(id);
+
+ if (bundle === null) {
+ // Use the wrapped component as fallback.
+ return elem;
+ }
+
+ const msg = bundle.getMessage(id);
+ const [args, elems] = toArguments(this.props);
+ const messageValue = bundle.format(msg, args); // Check if the fallback is a valid element -- if not then it's not
+ // markup (e.g. nothing or a fallback string) so just use the
+ // formatted message value
+
+ if (!Object(external_React_["isValidElement"])(elem)) {
+ return messageValue;
+ } // The default is to forbid all message attributes. If the attrs prop exists
+ // on the Localized instance, only set message attributes which have been
+ // explicitly allowed by the developer.
+
+
+ if (attrs && msg.attrs) {
+ var localizedProps = {};
+
+ for (const [name, allowed] of Object.entries(attrs)) {
+ if (allowed && msg.attrs.hasOwnProperty(name)) {
+ localizedProps[name] = bundle.format(msg.attrs[name], args);
+ }
+ }
+ } // If the wrapped component is a known void element, explicitly dismiss the
+ // message value and do not pass it to cloneElement in order to avoid the
+ // "void element tags must neither have `children` nor use
+ // `dangerouslySetInnerHTML`" error.
+
+
+ if (elem.type in vendor_voidElementTags) {
+ return Object(external_React_["cloneElement"])(elem, localizedProps);
+ } // If the message has a null value, we're only interested in its attributes.
+ // Do not pass the null value to cloneElement as it would nuke all children
+ // of the wrapped component.
+
+
+ if (messageValue === null) {
+ return Object(external_React_["cloneElement"])(elem, localizedProps);
+ } // If the message value doesn't contain any markup nor any HTML entities,
+ // insert it as the only child of the wrapped component.
+
+
+ if (!reMarkup.test(messageValue)) {
+ return Object(external_React_["cloneElement"])(elem, localizedProps, messageValue);
+ } // If the message contains markup, parse it and try to match the children
+ // found in the translation with the props passed to this Localized.
+
+
+ const translationNodes = parseMarkup(messageValue);
+ const translatedChildren = translationNodes.map(childNode => {
+ if (childNode.nodeType === childNode.TEXT_NODE) {
+ return childNode.textContent;
+ } // If the child is not expected just take its textContent.
+
+
+ if (!elems.hasOwnProperty(childNode.localName)) {
+ return childNode.textContent;
+ }
+
+ const sourceChild = elems[childNode.localName]; // If the element passed as a prop to <Localized> is a known void element,
+ // explicitly dismiss any textContent which might have accidentally been
+ // defined in the translation to prevent the "void element tags must not
+ // have children" error.
+
+ if (sourceChild.type in vendor_voidElementTags) {
+ return sourceChild;
+ } // TODO Protect contents of elements wrapped in <Localized>
+ // https://github.com/projectfluent/fluent.js/issues/184
+ // TODO Control localizable attributes on elements passed as props
+ // https://github.com/projectfluent/fluent.js/issues/185
+
+
+ return Object(external_React_["cloneElement"])(sourceChild, null, childNode.textContent);
+ });
+ return Object(external_React_["cloneElement"])(elem, localizedProps, ...translatedChildren);
+ }
+
+}
+localized_Localized.contextTypes = {
+ l10n: isReactLocalization,
+ parseMarkup: external_PropTypes_default.a.func
+};
+localized_Localized.propTypes = {
+ children: external_PropTypes_default.a.node
+};
+// CONCATENATED MODULE: ./node_modules/fluent-react/src/index.js
+/* concated harmony reexport LocalizationProvider */__webpack_require__.d(__webpack_exports__, "LocalizationProvider", function() { return provider_LocalizationProvider; });
+/* concated harmony reexport withLocalization */__webpack_require__.d(__webpack_exports__, "withLocalization", function() { return withLocalization; });
+/* concated harmony reexport Localized */__webpack_require__.d(__webpack_exports__, "Localized", function() { return localized_Localized; });
+/* concated harmony reexport ReactLocalization */__webpack_require__.d(__webpack_exports__, "ReactLocalization", function() { return localization_ReactLocalization; });
+/* concated harmony reexport isReactLocalization */__webpack_require__.d(__webpack_exports__, "isReactLocalization", function() { return isReactLocalization; });
+/*
+ * @module fluent-react
+ * @overview
+ *
+
+ * `fluent-react` provides React bindings for Fluent. It takes advantage of
+ * React's Components system and the virtual DOM. Translations are exposed to
+ * components via the provider pattern.
+ *
+ * <LocalizationProvider bundles={…}>
+ * <Localized id="hello-world">
+ * <p>{'Hello, world!'}</p>
+ * </Localized>
+ * </LocalizationProvider>
+ *
+ * Consult the documentation of the `LocalizationProvider` and the `Localized`
+ * components for more information.
+ */
+
+
+
+
+
+/***/ }),
+/* 69 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+
+// EXTERNAL MODULE: external "React"
+var external_React_ = __webpack_require__(8);
+var external_React_default = /*#__PURE__*/__webpack_require__.n(external_React_);
+
+// CONCATENATED MODULE: ./content-src/asrouter/components/Button/Button.jsx
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+const ALLOWED_STYLE_TAGS = ["color", "backgroundColor"];
+const Button = props => {
+ const style = {}; // Add allowed style tags from props, e.g. props.color becomes style={color: props.color}
+
+ for (const tag of ALLOWED_STYLE_TAGS) {
+ if (typeof props[tag] !== "undefined") {
+ style[tag] = props[tag];
+ }
+ } // remove border if bg is set to something custom
+
+
+ if (style.backgroundColor) {
+ style.border = "0";
+ }
+
+ return external_React_default.a.createElement("button", {
+ onClick: props.onClick,
+ className: props.className || "ASRouterButton secondary",
+ style: style
+ }, props.children);
+};
+// CONCATENATED MODULE: ./content-src/asrouter/components/ConditionalWrapper/ConditionalWrapper.jsx
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+// lifted from https://gist.github.com/kitze/23d82bb9eb0baabfd03a6a720b1d637f
+const ConditionalWrapper = ({
+ condition,
+ wrap,
+ children
+}) => condition && wrap ? wrap(children) : children;
+
+/* harmony default export */ var ConditionalWrapper_ConditionalWrapper = (ConditionalWrapper);
+// EXTERNAL MODULE: ./node_modules/fluent-react/src/index.js + 14 modules
+var src = __webpack_require__(68);
+
+// EXTERNAL MODULE: ./content-src/asrouter/rich-text-strings.js + 7 modules
+var rich_text_strings = __webpack_require__(70);
+
+// CONCATENATED MODULE: ./content-src/asrouter/template-utils.js
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+function safeURI(url) {
+ if (!url) {
+ return "";
+ }
+
+ const {
+ protocol
+ } = new URL(url);
+ const isAllowed = ["http:", "https:", "data:", "resource:", "chrome:"].includes(protocol);
+
+ if (!isAllowed) {
+ console.warn(`The protocol ${protocol} is not allowed for template URLs.`); // eslint-disable-line no-console
+ }
+
+ return isAllowed ? url : "";
+}
+// CONCATENATED MODULE: ./content-src/asrouter/components/RichText/RichText.jsx
+function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
+
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+
+ // Elements allowed in snippet content
+
+const ALLOWED_TAGS = {
+ b: external_React_default.a.createElement("b", null),
+ i: external_React_default.a.createElement("i", null),
+ u: external_React_default.a.createElement("u", null),
+ strong: external_React_default.a.createElement("strong", null),
+ em: external_React_default.a.createElement("em", null),
+ br: external_React_default.a.createElement("br", null)
+};
+/**
+ * Transform an object (tag name: {url}) into (tag name: anchor) where the url
+ * is used as href, in order to render links inside a Fluent.Localized component.
+ */
+
+function convertLinks(links, sendClick, doNotAutoBlock, openNewWindow = false) {
+ if (links) {
+ return Object.keys(links).reduce((acc, linkTag) => {
+ const {
+ action
+ } = links[linkTag]; // Setting the value to false will not include the attribute in the anchor
+
+ const url = action ? false : safeURI(links[linkTag].url);
+ acc[linkTag] = // eslint was getting a false positive caused by the dynamic injection
+ // of content.
+ // eslint-disable-next-line jsx-a11y/anchor-has-content
+ external_React_default.a.createElement("a", {
+ href: url,
+ target: openNewWindow ? "_blank" : "",
+ "data-metric": links[linkTag].metric,
+ "data-action": action,
+ "data-args": links[linkTag].args,
+ "data-do_not_autoblock": doNotAutoBlock,
+ "data-entrypoint_name": links[linkTag].entrypoint_name,
+ "data-entrypoint_value": links[linkTag].entrypoint_value,
+ onClick: sendClick
+ });
+ return acc;
+ }, {});
+ }
+
+ return null;
+}
+/**
+ * Message wrapper used to sanitize markup and render HTML.
+ */
+
+function RichText(props) {
+ if (!rich_text_strings["RICH_TEXT_KEYS"].includes(props.localization_id)) {
+ throw new Error(`ASRouter: ${props.localization_id} is not a valid rich text property. If you want it to be processed, you need to add it to asrouter/rich-text-strings.js`);
+ }
+
+ return external_React_default.a.createElement(src["Localized"], _extends({
+ id: props.localization_id
+ }, ALLOWED_TAGS, props.customElements, convertLinks(props.links, props.sendClick, props.doNotAutoBlock, props.openNewWindow)), external_React_default.a.createElement("span", null, props.text));
+}
+// CONCATENATED MODULE: ./content-src/asrouter/components/SnippetBase/SnippetBase.jsx
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+class SnippetBase_SnippetBase extends external_React_default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onBlockClicked = this.onBlockClicked.bind(this);
+ this.onDismissClicked = this.onDismissClicked.bind(this);
+ this.setBlockButtonRef = this.setBlockButtonRef.bind(this);
+ this.onBlockButtonMouseEnter = this.onBlockButtonMouseEnter.bind(this);
+ this.onBlockButtonMouseLeave = this.onBlockButtonMouseLeave.bind(this);
+ this.state = {
+ blockButtonHover: false
+ };
+ }
+
+ componentDidMount() {
+ if (this.blockButtonRef) {
+ this.blockButtonRef.addEventListener("mouseenter", this.onBlockButtonMouseEnter);
+ this.blockButtonRef.addEventListener("mouseleave", this.onBlockButtonMouseLeave);
+ }
+ }
+
+ componentWillUnmount() {
+ if (this.blockButtonRef) {
+ this.blockButtonRef.removeEventListener("mouseenter", this.onBlockButtonMouseEnter);
+ this.blockButtonRef.removeEventListener("mouseleave", this.onBlockButtonMouseLeave);
+ }
+ }
+
+ setBlockButtonRef(element) {
+ this.blockButtonRef = element;
+ }
+
+ onBlockButtonMouseEnter() {
+ this.setState({
+ blockButtonHover: true
+ });
+ }
+
+ onBlockButtonMouseLeave() {
+ this.setState({
+ blockButtonHover: false
+ });
+ }
+
+ onBlockClicked() {
+ if (this.props.provider !== "preview") {
+ this.props.sendUserActionTelemetry({
+ event: "BLOCK",
+ id: this.props.UISurface
+ });
+ }
+
+ this.props.onBlock();
+ }
+
+ onDismissClicked() {
+ if (this.props.provider !== "preview") {
+ this.props.sendUserActionTelemetry({
+ event: "DISMISS",
+ id: this.props.UISurface
+ });
+ }
+
+ this.props.onDismiss();
+ }
+
+ renderDismissButton() {
+ if (this.props.footerDismiss) {
+ return external_React_default.a.createElement("div", {
+ className: "footer"
+ }, external_React_default.a.createElement("div", {
+ className: "footer-content"
+ }, external_React_default.a.createElement("button", {
+ className: "ASRouterButton secondary",
+ onClick: this.onDismissClicked
+ }, this.props.content.scene2_dismiss_button_text)));
+ }
+
+ const label = this.props.content.block_button_text || "Remove this";
+ return external_React_default.a.createElement("button", {
+ className: "blockButton",
+ title: label,
+ "aria-label": label,
+ onClick: this.onBlockClicked,
+ ref: this.setBlockButtonRef
+ });
+ }
+
+ render() {
+ const {
+ props
+ } = this;
+ const {
+ blockButtonHover
+ } = this.state;
+ const containerClassName = `SnippetBaseContainer${props.className ? ` ${props.className}` : ""}${blockButtonHover ? " active" : ""}`;
+ return external_React_default.a.createElement("div", {
+ className: containerClassName,
+ style: this.props.textStyle
+ }, external_React_default.a.createElement("div", {
+ className: "innerWrapper"
+ }, props.children), this.renderDismissButton());
+ }
+
+}
+// CONCATENATED MODULE: ./content-src/asrouter/templates/SimpleSnippet/SimpleSnippet.jsx
+function SimpleSnippet_extends() { SimpleSnippet_extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return SimpleSnippet_extends.apply(this, arguments); }
+
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+
+
+
+
+const DEFAULT_ICON_PATH = "chrome://branding/content/icon64.png"; // Alt text placeholder in case the prop from the server isn't available
+
+const ICON_ALT_TEXT = "";
+class SimpleSnippet_SimpleSnippet extends external_React_default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onButtonClick = this.onButtonClick.bind(this);
+ }
+
+ onButtonClick() {
+ if (this.props.provider !== "preview") {
+ this.props.sendUserActionTelemetry({
+ event: "CLICK_BUTTON",
+ id: this.props.UISurface
+ });
+ }
+
+ const {
+ button_url,
+ button_entrypoint_value,
+ button_entrypoint_name
+ } = this.props.content; // If button_url is defined handle it as OPEN_URL action
+
+ const type = this.props.content.button_action || button_url && "OPEN_URL"; // Assign the snippet referral for the action
+
+ const entrypoint = button_entrypoint_name ? new URLSearchParams([[button_entrypoint_name, button_entrypoint_value]]).toString() : button_entrypoint_value;
+ this.props.onAction({
+ type,
+ data: {
+ args: this.props.content.button_action_args || button_url,
+ ...(entrypoint && {
+ entrypoint
+ })
+ }
+ });
+
+ if (!this.props.content.do_not_autoblock) {
+ this.props.onBlock();
+ }
+ }
+
+ _shouldRenderButton() {
+ return this.props.content.button_action || this.props.onButtonClick || this.props.content.button_url;
+ }
+
+ renderTitle() {
+ const {
+ title
+ } = this.props.content;
+ return title ? external_React_default.a.createElement("h3", {
+ className: `title ${this._shouldRenderButton() ? "title-inline" : ""}`
+ }, this.renderTitleIcon(), " ", title) : null;
+ }
+
+ renderTitleIcon() {
+ const titleIconLight = safeURI(this.props.content.title_icon);
+ const titleIconDark = safeURI(this.props.content.title_icon_dark_theme || this.props.content.title_icon);
+
+ if (!titleIconLight) {
+ return null;
+ }
+
+ return external_React_default.a.createElement(external_React_default.a.Fragment, null, external_React_default.a.createElement("span", {
+ className: "titleIcon icon-light-theme",
+ style: {
+ backgroundImage: `url("${titleIconLight}")`
+ }
+ }), external_React_default.a.createElement("span", {
+ className: "titleIcon icon-dark-theme",
+ style: {
+ backgroundImage: `url("${titleIconDark}")`
+ }
+ }));
+ }
+
+ renderButton() {
+ const {
+ props
+ } = this;
+
+ if (!this._shouldRenderButton()) {
+ return null;
+ }
+
+ return external_React_default.a.createElement(Button, {
+ onClick: props.onButtonClick || this.onButtonClick,
+ color: props.content.button_color,
+ backgroundColor: props.content.button_background_color
+ }, props.content.button_label);
+ }
+
+ renderText() {
+ const {
+ props
+ } = this;
+ return external_React_default.a.createElement(RichText, {
+ text: props.content.text,
+ customElements: this.props.customElements,
+ localization_id: "text",
+ links: props.content.links,
+ sendClick: props.sendClick
+ });
+ }
+
+ wrapSectionHeader(url) {
+ return function (children) {
+ return external_React_default.a.createElement("a", {
+ href: url
+ }, children);
+ };
+ }
+
+ wrapSnippetContent(children) {
+ return external_React_default.a.createElement("div", {
+ className: "innerContentWrapper"
+ }, children);
+ }
+
+ renderSectionHeader() {
+ const {
+ props
+ } = this; // an icon and text must be specified to render the section header
+
+ if (props.content.section_title_icon && props.content.section_title_text) {
+ const sectionTitleIconLight = safeURI(props.content.section_title_icon);
+ const sectionTitleIconDark = safeURI(props.content.section_title_icon_dark_theme || props.content.section_title_icon);
+ const sectionTitleURL = props.content.section_title_url;
+ return external_React_default.a.createElement("div", {
+ className: "section-header"
+ }, external_React_default.a.createElement("h3", {
+ className: "section-title"
+ }, external_React_default.a.createElement(ConditionalWrapper_ConditionalWrapper, {
+ condition: sectionTitleURL,
+ wrap: this.wrapSectionHeader(sectionTitleURL)
+ }, external_React_default.a.createElement("span", {
+ className: "icon icon-small-spacer icon-light-theme",
+ style: {
+ backgroundImage: `url("${sectionTitleIconLight}")`
+ }
+ }), external_React_default.a.createElement("span", {
+ className: "icon icon-small-spacer icon-dark-theme",
+ style: {
+ backgroundImage: `url("${sectionTitleIconDark}")`
+ }
+ }), external_React_default.a.createElement("span", {
+ className: "section-title-text"
+ }, props.content.section_title_text))));
+ }
+
+ return null;
+ }
+
+ render() {
+ const {
+ props
+ } = this;
+ const sectionHeader = this.renderSectionHeader();
+ let className = "SimpleSnippet";
+
+ if (props.className) {
+ className += ` ${props.className}`;
+ }
+
+ if (props.content.tall) {
+ className += " tall";
+ }
+
+ if (sectionHeader) {
+ className += " has-section-header";
+ }
+
+ return external_React_default.a.createElement("div", {
+ className: "snippet-hover-wrapper"
+ }, external_React_default.a.createElement(SnippetBase_SnippetBase, SimpleSnippet_extends({}, props, {
+ className: className,
+ textStyle: this.props.textStyle
+ }), sectionHeader, external_React_default.a.createElement(ConditionalWrapper_ConditionalWrapper, {
+ condition: sectionHeader,
+ wrap: this.wrapSnippetContent
+ }, external_React_default.a.createElement("img", {
+ src: safeURI(props.content.icon) || DEFAULT_ICON_PATH,
+ className: "icon icon-light-theme",
+ alt: props.content.icon_alt_text || ICON_ALT_TEXT
+ }), external_React_default.a.createElement("img", {
+ src: safeURI(props.content.icon_dark_theme || props.content.icon) || DEFAULT_ICON_PATH,
+ className: "icon icon-dark-theme",
+ alt: props.content.icon_alt_text || ICON_ALT_TEXT
+ }), external_React_default.a.createElement("div", null, this.renderTitle(), " ", external_React_default.a.createElement("p", {
+ className: "body"
+ }, this.renderText()), this.props.extraContent), external_React_default.a.createElement("div", null, this.renderButton()))));
+ }
+
+}
+// CONCATENATED MODULE: ./content-src/asrouter/templates/EOYSnippet/EOYSnippet.jsx
+function EOYSnippet_extends() { EOYSnippet_extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return EOYSnippet_extends.apply(this, arguments); }
+
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+
+class EOYSnippet_EOYSnippetBase extends external_React_default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.handleSubmit = this.handleSubmit.bind(this);
+ }
+ /**
+ * setFrequencyValue - `frequency` form parameter value should be `monthly`
+ * if `monthly-checkbox` is selected or `single` otherwise
+ */
+
+
+ setFrequencyValue() {
+ const frequencyCheckbox = this.refs.form.querySelector("#monthly-checkbox");
+
+ if (frequencyCheckbox.checked) {
+ this.refs.form.querySelector("[name='frequency']").value = "monthly";
+ }
+ }
+
+ handleSubmit(event) {
+ event.preventDefault();
+ this.props.sendClick(event);
+ this.setFrequencyValue();
+
+ if (!this.props.content.do_not_autoblock) {
+ this.props.onBlock();
+ }
+
+ this.refs.form.submit();
+ }
+
+ renderDonations() {
+ const fieldNames = ["first", "second", "third", "fourth"];
+ const numberFormat = new Intl.NumberFormat(this.props.content.locale || navigator.language, {
+ style: "currency",
+ currency: this.props.content.currency_code,
+ minimumFractionDigits: 0
+ }); // Default to `second` button
+
+ const {
+ selected_button
+ } = this.props.content;
+ const btnStyle = {
+ color: this.props.content.button_color,
+ backgroundColor: this.props.content.button_background_color
+ };
+ const donationURLParams = [];
+ const paramsStartIndex = this.props.content.donation_form_url.indexOf("?");
+
+ for (const entry of new URLSearchParams(this.props.content.donation_form_url.slice(paramsStartIndex)).entries()) {
+ donationURLParams.push(entry);
+ }
+
+ return external_React_default.a.createElement("form", {
+ className: "EOYSnippetForm",
+ action: this.props.content.donation_form_url,
+ method: this.props.form_method,
+ onSubmit: this.handleSubmit,
+ "data-metric": "EOYSnippetForm",
+ ref: "form"
+ }, donationURLParams.map(([key, value], idx) => external_React_default.a.createElement("input", {
+ type: "hidden",
+ name: key,
+ value: value,
+ key: idx
+ })), fieldNames.map((field, idx) => {
+ const button_name = `donation_amount_${field}`;
+ const amount = this.props.content[button_name];
+ return external_React_default.a.createElement(external_React_default.a.Fragment, {
+ key: idx
+ }, external_React_default.a.createElement("input", {
+ type: "radio",
+ name: "amount",
+ value: amount,
+ id: field,
+ defaultChecked: button_name === selected_button
+ }), external_React_default.a.createElement("label", {
+ htmlFor: field,
+ className: "donation-amount"
+ }, numberFormat.format(amount)));
+ }), external_React_default.a.createElement("div", {
+ className: "monthly-checkbox-container"
+ }, external_React_default.a.createElement("input", {
+ id: "monthly-checkbox",
+ type: "checkbox"
+ }), external_React_default.a.createElement("label", {
+ htmlFor: "monthly-checkbox"
+ }, this.props.content.monthly_checkbox_label_text)), external_React_default.a.createElement("input", {
+ type: "hidden",
+ name: "frequency",
+ value: "single"
+ }), external_React_default.a.createElement("input", {
+ type: "hidden",
+ name: "currency",
+ value: this.props.content.currency_code
+ }), external_React_default.a.createElement("input", {
+ type: "hidden",
+ name: "presets",
+ value: fieldNames.map(field => this.props.content[`donation_amount_${field}`])
+ }), external_React_default.a.createElement("button", {
+ style: btnStyle,
+ type: "submit",
+ className: "ASRouterButton primary donation-form-url"
+ }, this.props.content.button_label));
+ }
+
+ render() {
+ const textStyle = {
+ color: this.props.content.text_color,
+ backgroundColor: this.props.content.background_color
+ };
+ const customElement = external_React_default.a.createElement("em", {
+ style: {
+ backgroundColor: this.props.content.highlight_color
+ }
+ });
+ return external_React_default.a.createElement(SimpleSnippet_SimpleSnippet, EOYSnippet_extends({}, this.props, {
+ className: this.props.content.test,
+ customElements: {
+ em: customElement
+ },
+ textStyle: textStyle,
+ extraContent: this.renderDonations()
+ }));
+ }
+
+}
+
+const EOYSnippet = props => {
+ const extendedContent = {
+ monthly_checkbox_label_text: "Make my donation monthly",
+ locale: "en-US",
+ currency_code: "usd",
+ selected_button: "donation_amount_second",
+ ...props.content
+ };
+ return external_React_default.a.createElement(EOYSnippet_EOYSnippetBase, EOYSnippet_extends({}, props, {
+ content: extendedContent,
+ form_method: "GET"
+ }));
+};
+// CONCATENATED MODULE: ./content-src/asrouter/templates/SubmitFormSnippet/SubmitFormSnippet.jsx
+function SubmitFormSnippet_extends() { SubmitFormSnippet_extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return SubmitFormSnippet_extends.apply(this, arguments); }
+
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+
+
+
+
+ // Alt text placeholder in case the prop from the server isn't available
+
+const SubmitFormSnippet_ICON_ALT_TEXT = "";
+class SubmitFormSnippet_SubmitFormSnippet extends external_React_default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.expandSnippet = this.expandSnippet.bind(this);
+ this.handleSubmit = this.handleSubmit.bind(this);
+ this.handleSubmitAttempt = this.handleSubmitAttempt.bind(this);
+ this.onInputChange = this.onInputChange.bind(this);
+ this.state = {
+ expanded: false,
+ submitAttempted: false,
+ signupSubmitted: false,
+ signupSuccess: false,
+ disableForm: false
+ };
+ }
+
+ handleSubmitAttempt() {
+ if (!this.state.submitAttempted) {
+ this.setState({
+ submitAttempted: true
+ });
+ }
+ }
+
+ async handleSubmit(event) {
+ let json;
+
+ if (this.state.disableForm) {
+ return;
+ }
+
+ event.preventDefault();
+ this.setState({
+ disableForm: true
+ });
+ this.props.sendUserActionTelemetry({
+ event: "CLICK_BUTTON",
+ event_context: "conversion-subscribe-activation",
+ id: "NEWTAB_FOOTER_BAR_CONTENT"
+ });
+
+ if (this.props.form_method.toUpperCase() === "GET") {
+ this.props.onBlock({
+ preventDismiss: true
+ });
+ this.refs.form.submit();
+ return;
+ }
+
+ const {
+ url,
+ formData
+ } = this.props.processFormData ? this.props.processFormData(this.refs.mainInput, this.props) : {
+ url: this.refs.form.action,
+ formData: new FormData(this.refs.form)
+ };
+
+ try {
+ const fetchRequest = new Request(url, {
+ body: formData,
+ method: "POST",
+ credentials: "omit"
+ });
+ const response = await fetch(fetchRequest); // eslint-disable-line fetch-options/no-fetch-credentials
+
+ json = await response.json();
+ } catch (err) {
+ console.log(err); // eslint-disable-line no-console
+ }
+
+ if (json && json.status === "ok") {
+ this.setState({
+ signupSuccess: true,
+ signupSubmitted: true
+ });
+
+ if (!this.props.content.do_not_autoblock) {
+ this.props.onBlock({
+ preventDismiss: true
+ });
+ }
+
+ this.props.sendUserActionTelemetry({
+ event: "CLICK_BUTTON",
+ event_context: "subscribe-success",
+ id: "NEWTAB_FOOTER_BAR_CONTENT"
+ });
+ } else {
+ // eslint-disable-next-line no-console
+ console.error("There was a problem submitting the form", json || "[No JSON response]");
+ this.setState({
+ signupSuccess: false,
+ signupSubmitted: true
+ });
+ this.props.sendUserActionTelemetry({
+ event: "CLICK_BUTTON",
+ event_context: "subscribe-error",
+ id: "NEWTAB_FOOTER_BAR_CONTENT"
+ });
+ }
+
+ this.setState({
+ disableForm: false
+ });
+ }
+
+ expandSnippet() {
+ this.props.sendUserActionTelemetry({
+ event: "CLICK_BUTTON",
+ event_context: "scene1-button-learn-more",
+ id: this.props.UISurface
+ });
+ this.setState({
+ expanded: true,
+ signupSuccess: false,
+ signupSubmitted: false
+ });
+ }
+
+ renderHiddenFormInputs() {
+ const {
+ hidden_inputs
+ } = this.props.content;
+
+ if (!hidden_inputs) {
+ return null;
+ }
+
+ return Object.keys(hidden_inputs).map((key, idx) => external_React_default.a.createElement("input", {
+ key: idx,
+ type: "hidden",
+ name: key,
+ value: hidden_inputs[key]
+ }));
+ }
+
+ renderDisclaimer() {
+ const {
+ content
+ } = this.props;
+
+ if (!content.scene2_disclaimer_html) {
+ return null;
+ }
+
+ return external_React_default.a.createElement("p", {
+ className: "disclaimerText"
+ }, external_React_default.a.createElement(RichText, {
+ text: content.scene2_disclaimer_html,
+ localization_id: "disclaimer_html",
+ links: content.links,
+ doNotAutoBlock: true,
+ openNewWindow: true,
+ sendClick: this.props.sendClick
+ }));
+ }
+
+ renderFormPrivacyNotice() {
+ const {
+ content
+ } = this.props;
+
+ if (!content.scene2_privacy_html) {
+ return null;
+ }
+
+ return external_React_default.a.createElement("p", {
+ className: "privacyNotice"
+ }, external_React_default.a.createElement("input", {
+ type: "checkbox",
+ id: "id_privacy",
+ name: "privacy",
+ required: "required"
+ }), external_React_default.a.createElement("label", {
+ htmlFor: "id_privacy"
+ }, external_React_default.a.createElement(RichText, {
+ text: content.scene2_privacy_html,
+ localization_id: "privacy_html",
+ links: content.links,
+ doNotAutoBlock: true,
+ openNewWindow: true,
+ sendClick: this.props.sendClick
+ })));
+ }
+
+ renderSignupSubmitted() {
+ const {
+ content
+ } = this.props;
+ const isSuccess = this.state.signupSuccess;
+ const successTitle = isSuccess && content.success_title;
+ const bodyText = isSuccess ? {
+ success_text: content.success_text
+ } : {
+ error_text: content.error_text
+ };
+ const retryButtonText = content.retry_button_label;
+ return external_React_default.a.createElement(SnippetBase_SnippetBase, this.props, external_React_default.a.createElement("div", {
+ className: "submissionStatus"
+ }, successTitle ? external_React_default.a.createElement("h2", {
+ className: "submitStatusTitle"
+ }, successTitle) : null, external_React_default.a.createElement("p", null, external_React_default.a.createElement(RichText, SubmitFormSnippet_extends({}, bodyText, {
+ localization_id: isSuccess ? "success_text" : "error_text"
+ })), isSuccess ? null : external_React_default.a.createElement(Button, {
+ onClick: this.expandSnippet
+ }, retryButtonText))));
+ }
+
+ onInputChange(event) {
+ if (!this.props.validateInput) {
+ return;
+ }
+
+ const hasError = this.props.validateInput(event.target.value, this.props.content);
+ event.target.setCustomValidity(hasError);
+ }
+
+ wrapSectionHeader(url) {
+ return function (children) {
+ return external_React_default.a.createElement("a", {
+ href: url
+ }, children);
+ };
+ }
+
+ renderInput() {
+ const placholder = this.props.content.scene2_email_placeholder_text || this.props.content.scene2_input_placeholder;
+ return external_React_default.a.createElement("input", {
+ ref: "mainInput",
+ type: this.props.inputType || "email",
+ className: `mainInput${this.state.submitAttempted ? "" : " clean"}`,
+ name: "email",
+ required: true,
+ placeholder: placholder,
+ onChange: this.props.validateInput ? this.onInputChange : null
+ });
+ }
+
+ renderForm() {
+ return external_React_default.a.createElement("form", {
+ action: this.props.form_action,
+ method: this.props.form_method,
+ onSubmit: this.handleSubmit,
+ ref: "form"
+ }, this.renderHiddenFormInputs(), external_React_default.a.createElement("div", null, this.renderInput(), external_React_default.a.createElement("button", {
+ type: "submit",
+ className: "ASRouterButton primary",
+ onClick: this.handleSubmitAttempt,
+ ref: "formSubmitBtn"
+ }, this.props.content.scene2_button_label)), this.renderFormPrivacyNotice() || this.renderDisclaimer());
+ }
+
+ renderScene2Icon() {
+ const {
+ content
+ } = this.props;
+
+ if (!content.scene2_icon) {
+ return null;
+ }
+
+ return external_React_default.a.createElement("div", {
+ className: "scene2Icon"
+ }, external_React_default.a.createElement("img", {
+ src: safeURI(content.scene2_icon),
+ className: "icon-light-theme",
+ alt: content.scene2_icon_alt_text || SubmitFormSnippet_ICON_ALT_TEXT
+ }), external_React_default.a.createElement("img", {
+ src: safeURI(content.scene2_icon_dark_theme || content.scene2_icon),
+ className: "icon-dark-theme",
+ alt: content.scene2_icon_alt_text || SubmitFormSnippet_ICON_ALT_TEXT
+ }));
+ }
+
+ renderSignupView() {
+ const {
+ content
+ } = this.props;
+ const containerClass = `SubmitFormSnippet ${this.props.className}`;
+ return external_React_default.a.createElement(SnippetBase_SnippetBase, SubmitFormSnippet_extends({}, this.props, {
+ className: containerClass,
+ footerDismiss: true
+ }), this.renderScene2Icon(), external_React_default.a.createElement("div", {
+ className: "message"
+ }, external_React_default.a.createElement("p", null, content.scene2_title && external_React_default.a.createElement("h3", {
+ className: "scene2Title"
+ }, content.scene2_title), " ", content.scene2_text && external_React_default.a.createElement(RichText, {
+ scene2_text: content.scene2_text,
+ localization_id: "scene2_text"
+ }))), this.renderForm());
+ }
+
+ renderSectionHeader() {
+ const {
+ props
+ } = this; // an icon and text must be specified to render the section header
+
+ if (props.content.section_title_icon && props.content.section_title_text) {
+ const sectionTitleIconLight = safeURI(props.content.section_title_icon);
+ const sectionTitleIconDark = safeURI(props.content.section_title_icon_dark_theme || props.content.section_title_icon);
+ const sectionTitleURL = props.content.section_title_url;
+ return external_React_default.a.createElement("div", {
+ className: "section-header"
+ }, external_React_default.a.createElement("h3", {
+ className: "section-title"
+ }, external_React_default.a.createElement(ConditionalWrapper_ConditionalWrapper, {
+ wrap: this.wrapSectionHeader(sectionTitleURL),
+ condition: sectionTitleURL
+ }, external_React_default.a.createElement("span", {
+ className: "icon icon-small-spacer icon-light-theme",
+ style: {
+ backgroundImage: `url("${sectionTitleIconLight}")`
+ }
+ }), external_React_default.a.createElement("span", {
+ className: "icon icon-small-spacer icon-dark-theme",
+ style: {
+ backgroundImage: `url("${sectionTitleIconDark}")`
+ }
+ }), external_React_default.a.createElement("span", {
+ className: "section-title-text"
+ }, props.content.section_title_text))));
+ }
+
+ return null;
+ }
+
+ renderSignupViewAlt() {
+ const {
+ content
+ } = this.props;
+ const containerClass = `SubmitFormSnippet ${this.props.className} scene2Alt`;
+ return external_React_default.a.createElement(SnippetBase_SnippetBase, SubmitFormSnippet_extends({}, this.props, {
+ className: containerClass // Don't show bottom dismiss button
+ ,
+ footerDismiss: false
+ }), this.renderSectionHeader(), this.renderScene2Icon(), external_React_default.a.createElement("div", {
+ className: "message"
+ }, external_React_default.a.createElement("p", null, content.scene2_text && external_React_default.a.createElement(RichText, {
+ scene2_text: content.scene2_text,
+ localization_id: "scene2_text"
+ })), this.renderForm()));
+ }
+
+ getFirstSceneContent() {
+ return Object.keys(this.props.content).filter(key => key.includes("scene1")).reduce((acc, key) => {
+ acc[key.substr(7)] = this.props.content[key];
+ return acc;
+ }, {});
+ }
+
+ render() {
+ const content = { ...this.props.content,
+ ...this.getFirstSceneContent()
+ };
+
+ if (this.state.signupSubmitted) {
+ return this.renderSignupSubmitted();
+ } // Render only scene 2 (signup view). Must check before `renderSignupView`
+ // to catch the Failure/Try again scenario where we want to return and render
+ // the scene again.
+
+
+ if (this.props.expandedAlt) {
+ return this.renderSignupViewAlt();
+ }
+
+ if (this.state.expanded) {
+ return this.renderSignupView();
+ }
+
+ return external_React_default.a.createElement(SimpleSnippet_SimpleSnippet, SubmitFormSnippet_extends({}, this.props, {
+ content: content,
+ onButtonClick: this.expandSnippet
+ }));
+ }
+
+}
+// CONCATENATED MODULE: ./content-src/asrouter/templates/FXASignupSnippet/FXASignupSnippet.jsx
+function FXASignupSnippet_extends() { FXASignupSnippet_extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return FXASignupSnippet_extends.apply(this, arguments); }
+
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+const FXASignupSnippet = props => {
+ const userAgent = window.navigator.userAgent.match(/Firefox\/([0-9]+)\./);
+ const firefox_version = userAgent ? parseInt(userAgent[1], 10) : 0;
+ const extendedContent = {
+ scene1_button_label: "Learn more",
+ retry_button_label: "Try again",
+ scene2_email_placeholder_text: "Your email here",
+ scene2_button_label: "Sign me up",
+ scene2_dismiss_button_text: "Dismiss",
+ ...props.content,
+ hidden_inputs: {
+ action: "email",
+ context: "fx_desktop_v3",
+ entrypoint: "snippets",
+ utm_source: "snippet",
+ utm_content: firefox_version,
+ utm_campaign: props.content.utm_campaign,
+ utm_term: props.content.utm_term,
+ ...props.content.hidden_inputs
+ }
+ };
+ return external_React_default.a.createElement(SubmitFormSnippet_SubmitFormSnippet, FXASignupSnippet_extends({}, props, {
+ content: extendedContent,
+ form_action: "https://accounts.firefox.com/",
+ form_method: "GET"
+ }));
+};
+// CONCATENATED MODULE: ./content-src/asrouter/templates/NewsletterSnippet/NewsletterSnippet.jsx
+function NewsletterSnippet_extends() { NewsletterSnippet_extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return NewsletterSnippet_extends.apply(this, arguments); }
+
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+const NewsletterSnippet = props => {
+ const extendedContent = {
+ scene1_button_label: "Learn more",
+ retry_button_label: "Try again",
+ scene2_email_placeholder_text: "Your email here",
+ scene2_button_label: "Sign me up",
+ scene2_dismiss_button_text: "Dismiss",
+ scene2_newsletter: "mozilla-foundation",
+ ...props.content,
+ hidden_inputs: {
+ newsletters: props.content.scene2_newsletter || "mozilla-foundation",
+ fmt: "H",
+ lang: props.content.locale || "en-US",
+ source_url: `https://snippets.mozilla.com/show/${props.id}`,
+ ...props.content.hidden_inputs
+ }
+ };
+ return external_React_default.a.createElement(SubmitFormSnippet_SubmitFormSnippet, NewsletterSnippet_extends({}, props, {
+ content: extendedContent,
+ form_action: "https://basket.mozilla.org/subscribe.json",
+ form_method: "POST"
+ }));
+};
+// CONCATENATED MODULE: ./content-src/asrouter/templates/SendToDeviceSnippet/isEmailOrPhoneNumber.js
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/**
+ * Checks if a given string is an email or phone number or neither
+ * @param {string} val The user input
+ * @param {ASRMessageContent} content .content property on ASR message
+ * @returns {"email"|"phone"|""} The type of the input
+ */
+function isEmailOrPhoneNumber(val, content) {
+ const {
+ locale
+ } = content; // http://emailregex.com/
+
+ const email_re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
+ const check_email = email_re.test(val);
+ let check_phone; // depends on locale
+
+ switch (locale) {
+ case "en-US":
+ case "en-CA":
+ // allow 10-11 digits in case user wants to enter country code
+ check_phone = val.length >= 10 && val.length <= 11 && !isNaN(val);
+ break;
+
+ case "de":
+ // allow between 2 and 12 digits for german phone numbers
+ check_phone = val.length >= 2 && val.length <= 12 && !isNaN(val);
+ break;
+ // this case should never be hit, but good to have a fallback just in case
+
+ default:
+ check_phone = !isNaN(val);
+ break;
+ }
+
+ if (check_email) {
+ return "email";
+ } else if (check_phone) {
+ return "phone";
+ }
+
+ return "";
+}
+// CONCATENATED MODULE: ./content-src/asrouter/templates/SendToDeviceSnippet/SendToDeviceSnippet.jsx
+function SendToDeviceSnippet_extends() { SendToDeviceSnippet_extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return SendToDeviceSnippet_extends.apply(this, arguments); }
+
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+
+
+function validateInput(value, content) {
+ const type = isEmailOrPhoneNumber(value, content);
+ return type ? "" : "Must be an email or a phone number.";
+}
+
+function processFormData(input, message) {
+ const {
+ content
+ } = message;
+ const type = content.include_sms ? isEmailOrPhoneNumber(input.value, content) : "email";
+ const formData = new FormData();
+ let url;
+
+ if (type === "phone") {
+ url = "https://basket.mozilla.org/news/subscribe_sms/";
+ formData.append("mobile_number", input.value);
+ formData.append("msg_name", content.message_id_sms);
+ formData.append("country", content.country);
+ } else if (type === "email") {
+ url = "https://basket.mozilla.org/news/subscribe/";
+ formData.append("email", input.value);
+ formData.append("newsletters", content.message_id_email);
+ formData.append("source_url", encodeURIComponent(`https://snippets.mozilla.com/show/${message.id}`));
+ }
+
+ formData.append("lang", content.locale);
+ return {
+ formData,
+ url
+ };
+}
+
+function addDefaultValues(props) {
+ return { ...props,
+ content: {
+ scene1_button_label: "Learn more",
+ retry_button_label: "Try again",
+ scene2_dismiss_button_text: "Dismiss",
+ scene2_button_label: "Send",
+ scene2_input_placeholder: "Your email here",
+ locale: "en-US",
+ country: "us",
+ message_id_email: "",
+ include_sms: false,
+ ...props.content
+ }
+ };
+}
+
+const SendToDeviceSnippet = props => {
+ const propsWithDefaults = addDefaultValues(props);
+ return external_React_default.a.createElement(SubmitFormSnippet_SubmitFormSnippet, SendToDeviceSnippet_extends({}, propsWithDefaults, {
+ form_method: "POST",
+ className: "send_to_device_snippet",
+ inputType: propsWithDefaults.content.include_sms ? "text" : "email",
+ validateInput: propsWithDefaults.content.include_sms ? validateInput : null,
+ processFormData: processFormData
+ }));
+};
+const SendToDeviceScene2Snippet = props => {
+ return external_React_default.a.createElement(SendToDeviceSnippet, SendToDeviceSnippet_extends({
+ expandedAlt: true
+ }, props));
+};
+// CONCATENATED MODULE: ./content-src/asrouter/templates/SimpleBelowSearchSnippet/SimpleBelowSearchSnippet.jsx
+function SimpleBelowSearchSnippet_extends() { SimpleBelowSearchSnippet_extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return SimpleBelowSearchSnippet_extends.apply(this, arguments); }
+
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+
+
+
+const SimpleBelowSearchSnippet_DEFAULT_ICON_PATH = "chrome://branding/content/icon64.png"; // Alt text placeholder in case the prop from the server isn't available
+
+const SimpleBelowSearchSnippet_ICON_ALT_TEXT = "";
+class SimpleBelowSearchSnippet_SimpleBelowSearchSnippet extends external_React_default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onButtonClick = this.onButtonClick.bind(this);
+ }
+
+ renderText() {
+ const {
+ props
+ } = this;
+ return props.content.text ? external_React_default.a.createElement(RichText, {
+ text: props.content.text,
+ customElements: this.props.customElements,
+ localization_id: "text",
+ links: props.content.links,
+ sendClick: props.sendClick
+ }) : null;
+ }
+
+ renderTitle() {
+ const {
+ title
+ } = this.props.content;
+ return title ? external_React_default.a.createElement("h3", {
+ className: "title title-inline"
+ }, title, external_React_default.a.createElement("br", null)) : null;
+ }
+
+ async onButtonClick() {
+ if (this.props.provider !== "preview") {
+ this.props.sendUserActionTelemetry({
+ event: "CLICK_BUTTON",
+ id: this.props.UISurface
+ });
+ }
+
+ const {
+ button_url
+ } = this.props.content; // If button_url is defined handle it as OPEN_URL action
+
+ const type = this.props.content.button_action || button_url && "OPEN_URL";
+ await this.props.onAction({
+ type,
+ data: {
+ args: this.props.content.button_action_args || button_url
+ }
+ });
+
+ if (!this.props.content.do_not_autoblock) {
+ this.props.onBlock();
+ }
+ }
+
+ _shouldRenderButton() {
+ return this.props.content.button_action || this.props.onButtonClick || this.props.content.button_url;
+ }
+
+ renderButton() {
+ const {
+ props
+ } = this;
+
+ if (!this._shouldRenderButton()) {
+ return null;
+ }
+
+ return external_React_default.a.createElement(Button, {
+ onClick: props.onButtonClick || this.onButtonClick,
+ color: props.content.button_color,
+ backgroundColor: props.content.button_background_color
+ }, props.content.button_label);
+ }
+
+ render() {
+ const {
+ props
+ } = this;
+ let className = "SimpleBelowSearchSnippet";
+ let containerName = "below-search-snippet";
+
+ if (props.className) {
+ className += ` ${props.className}`;
+ }
+
+ if (this._shouldRenderButton()) {
+ className += " withButton";
+ containerName += " withButton";
+ }
+
+ return external_React_default.a.createElement("div", {
+ className: containerName
+ }, external_React_default.a.createElement("div", {
+ className: "snippet-hover-wrapper"
+ }, external_React_default.a.createElement(SnippetBase_SnippetBase, SimpleBelowSearchSnippet_extends({}, props, {
+ className: className,
+ textStyle: this.props.textStyle
+ }), external_React_default.a.createElement("img", {
+ src: safeURI(props.content.icon) || SimpleBelowSearchSnippet_DEFAULT_ICON_PATH,
+ className: "icon icon-light-theme",
+ alt: props.content.icon_alt_text || SimpleBelowSearchSnippet_ICON_ALT_TEXT
+ }), external_React_default.a.createElement("img", {
+ src: safeURI(props.content.icon_dark_theme || props.content.icon) || SimpleBelowSearchSnippet_DEFAULT_ICON_PATH,
+ className: "icon icon-dark-theme",
+ alt: props.content.icon_alt_text || SimpleBelowSearchSnippet_ICON_ALT_TEXT
+ }), external_React_default.a.createElement("div", {
+ className: "textContainer"
+ }, this.renderTitle(), external_React_default.a.createElement("p", {
+ className: "body"
+ }, this.renderText()), this.props.extraContent), external_React_default.a.createElement("div", {
+ className: "buttonContainer"
+ }, this.renderButton()))));
+ }
+
+}
+// CONCATENATED MODULE: ./content-src/asrouter/templates/template-manifest.jsx
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SnippetsTemplates", function() { return SnippetsTemplates; });
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+
+
+
+ // Key names matching schema name of templates
+
+const SnippetsTemplates = {
+ simple_snippet: SimpleSnippet_SimpleSnippet,
+ newsletter_snippet: NewsletterSnippet,
+ fxa_signup_snippet: FXASignupSnippet,
+ send_to_device_snippet: SendToDeviceSnippet,
+ send_to_device_scene2_snippet: SendToDeviceScene2Snippet,
+ eoy_snippet: EOYSnippet,
+ simple_below_search_snippet: SimpleBelowSearchSnippet_SimpleBelowSearchSnippet
+};
+
+/***/ }),
+/* 70 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+var builtins_namespaceObject = {};
+__webpack_require__.r(builtins_namespaceObject);
+__webpack_require__.d(builtins_namespaceObject, "NUMBER", function() { return NUMBER; });
+__webpack_require__.d(builtins_namespaceObject, "DATETIME", function() { return DATETIME; });
+
+// CONCATENATED MODULE: ./node_modules/fluent/src/types.js
+/* global Intl */
+
+/**
+ * The `FluentType` class is the base of Fluent's type system.
+ *
+ * Fluent types wrap JavaScript values and store additional configuration for
+ * them, which can then be used in the `toString` method together with a proper
+ * `Intl` formatter.
+ */
+class FluentType {
+ /**
+ * Create an `FluentType` instance.
+ *
+ * @param {Any} value - JavaScript value to wrap.
+ * @param {Object} opts - Configuration.
+ * @returns {FluentType}
+ */
+ constructor(value, opts) {
+ this.value = value;
+ this.opts = opts;
+ }
+ /**
+ * Unwrap the raw value stored by this `FluentType`.
+ *
+ * @returns {Any}
+ */
+
+
+ valueOf() {
+ return this.value;
+ }
+ /**
+ * Format this instance of `FluentType` to a string.
+ *
+ * Formatted values are suitable for use outside of the `FluentBundle`.
+ * This method can use `Intl` formatters memoized by the `FluentBundle`
+ * instance passed as an argument.
+ *
+ * @param {FluentBundle} [bundle]
+ * @returns {string}
+ */
+
+
+ toString() {
+ throw new Error("Subclasses of FluentType must implement toString.");
+ }
+
+}
+class FluentNone extends FluentType {
+ valueOf() {
+ return null;
+ }
+
+ toString() {
+ return `{${this.value || "???"}}`;
+ }
+
+}
+class FluentNumber extends FluentType {
+ constructor(value, opts) {
+ super(parseFloat(value), opts);
+ }
+
+ toString(bundle) {
+ try {
+ const nf = bundle._memoizeIntlObject(Intl.NumberFormat, this.opts);
+
+ return nf.format(this.value);
+ } catch (e) {
+ // XXX Report the error.
+ return this.value;
+ }
+ }
+
+}
+class FluentDateTime extends FluentType {
+ constructor(value, opts) {
+ super(new Date(value), opts);
+ }
+
+ toString(bundle) {
+ try {
+ const dtf = bundle._memoizeIntlObject(Intl.DateTimeFormat, this.opts);
+
+ return dtf.format(this.value);
+ } catch (e) {
+ // XXX Report the error.
+ return this.value;
+ }
+ }
+
+}
+// CONCATENATED MODULE: ./node_modules/fluent/src/builtins.js
+/**
+ * @overview
+ *
+ * The FTL resolver ships with a number of functions built-in.
+ *
+ * Each function take two arguments:
+ * - args - an array of positional args
+ * - opts - an object of key-value args
+ *
+ * Arguments to functions are guaranteed to already be instances of
+ * `FluentType`. Functions must return `FluentType` objects as well.
+ */
+
+
+function merge(argopts, opts) {
+ return Object.assign({}, argopts, values(opts));
+}
+
+function values(opts) {
+ const unwrapped = {};
+
+ for (const [name, opt] of Object.entries(opts)) {
+ unwrapped[name] = opt.valueOf();
+ }
+
+ return unwrapped;
+}
+
+function NUMBER([arg], opts) {
+ if (arg instanceof FluentNone) {
+ return arg;
+ }
+
+ if (arg instanceof FluentNumber) {
+ return new FluentNumber(arg.valueOf(), merge(arg.opts, opts));
+ }
+
+ return new FluentNone("NUMBER()");
+}
+function DATETIME([arg], opts) {
+ if (arg instanceof FluentNone) {
+ return arg;
+ }
+
+ if (arg instanceof FluentDateTime) {
+ return new FluentDateTime(arg.valueOf(), merge(arg.opts, opts));
+ }
+
+ return new FluentNone("DATETIME()");
+}
+// CONCATENATED MODULE: ./node_modules/fluent/src/resolver.js
+/* global Intl */
+
+/**
+ * @overview
+ *
+ * The role of the Fluent resolver is to format a translation object to an
+ * instance of `FluentType` or an array of instances.
+ *
+ * Translations can contain references to other messages or variables,
+ * conditional logic in form of select expressions, traits which describe their
+ * grammatical features, and can use Fluent builtins which make use of the
+ * `Intl` formatters to format numbers, dates, lists and more into the
+ * bundle's language. See the documentation of the Fluent syntax for more
+ * information.
+ *
+ * In case of errors the resolver will try to salvage as much of the
+ * translation as possible. In rare situations where the resolver didn't know
+ * how to recover from an error it will return an instance of `FluentNone`.
+ *
+ * All expressions resolve to an instance of `FluentType`. The caller should
+ * use the `toString` method to convert the instance to a native value.
+ *
+ * All functions in this file pass around a special object called `scope`.
+ * This object stores a set of elements used by all resolve functions:
+ *
+ * * {FluentBundle} bundle
+ * bundle for which the given resolution is happening
+ * * {Object} args
+ * list of developer provided arguments that can be used
+ * * {Array} errors
+ * list of errors collected while resolving
+ * * {WeakSet} dirty
+ * Set of patterns already encountered during this resolution.
+ * This is used to prevent cyclic resolutions.
+ */
+
+ // Prevent expansion of too long placeables.
+
+const MAX_PLACEABLE_LENGTH = 2500; // Unicode bidi isolation characters.
+
+const FSI = "\u2068";
+const PDI = "\u2069"; // Helper: match a variant key to the given selector.
+
+function resolver_match(bundle, selector, key) {
+ if (key === selector) {
+ // Both are strings.
+ return true;
+ } // XXX Consider comparing options too, e.g. minimumFractionDigits.
+
+
+ if (key instanceof FluentNumber && selector instanceof FluentNumber && key.value === selector.value) {
+ return true;
+ }
+
+ if (selector instanceof FluentNumber && typeof key === "string") {
+ let category = bundle._memoizeIntlObject(Intl.PluralRules, selector.opts).select(selector.value);
+
+ if (key === category) {
+ return true;
+ }
+ }
+
+ return false;
+} // Helper: resolve the default variant from a list of variants.
+
+
+function getDefault(scope, variants, star) {
+ if (variants[star]) {
+ return Type(scope, variants[star]);
+ }
+
+ scope.errors.push(new RangeError("No default"));
+ return new FluentNone();
+} // Helper: resolve arguments to a call expression.
+
+
+function getArguments(scope, args) {
+ const positional = [];
+ const named = {};
+
+ for (const arg of args) {
+ if (arg.type === "narg") {
+ named[arg.name] = Type(scope, arg.value);
+ } else {
+ positional.push(Type(scope, arg));
+ }
+ }
+
+ return [positional, named];
+} // Resolve an expression to a Fluent type.
+
+
+function Type(scope, expr) {
+ // A fast-path for strings which are the most common case. Since they
+ // natively have the `toString` method they can be used as if they were
+ // a FluentType instance without incurring the cost of creating one.
+ if (typeof expr === "string") {
+ return scope.bundle._transform(expr);
+ } // A fast-path for `FluentNone` which doesn't require any additional logic.
+
+
+ if (expr instanceof FluentNone) {
+ return expr;
+ } // The Runtime AST (Entries) encodes patterns (complex strings with
+ // placeables) as Arrays.
+
+
+ if (Array.isArray(expr)) {
+ return Pattern(scope, expr);
+ }
+
+ switch (expr.type) {
+ case "str":
+ return expr.value;
+
+ case "num":
+ return new FluentNumber(expr.value, {
+ minimumFractionDigits: expr.precision
+ });
+
+ case "var":
+ return VariableReference(scope, expr);
+
+ case "mesg":
+ return MessageReference(scope, expr);
+
+ case "term":
+ return TermReference(scope, expr);
+
+ case "func":
+ return FunctionReference(scope, expr);
+
+ case "select":
+ return SelectExpression(scope, expr);
+
+ case undefined:
+ {
+ // If it's a node with a value, resolve the value.
+ if (expr.value !== null && expr.value !== undefined) {
+ return Type(scope, expr.value);
+ }
+
+ scope.errors.push(new RangeError("No value"));
+ return new FluentNone();
+ }
+
+ default:
+ return new FluentNone();
+ }
+} // Resolve a reference to a variable.
+
+
+function VariableReference(scope, {
+ name
+}) {
+ if (!scope.args || !scope.args.hasOwnProperty(name)) {
+ if (scope.insideTermReference === false) {
+ scope.errors.push(new ReferenceError(`Unknown variable: ${name}`));
+ }
+
+ return new FluentNone(`$${name}`);
+ }
+
+ const arg = scope.args[name]; // Return early if the argument already is an instance of FluentType.
+
+ if (arg instanceof FluentType) {
+ return arg;
+ } // Convert the argument to a Fluent type.
+
+
+ switch (typeof arg) {
+ case "string":
+ return arg;
+
+ case "number":
+ return new FluentNumber(arg);
+
+ case "object":
+ if (arg instanceof Date) {
+ return new FluentDateTime(arg);
+ }
+
+ default:
+ scope.errors.push(new TypeError(`Unsupported variable type: ${name}, ${typeof arg}`));
+ return new FluentNone(`$${name}`);
+ }
+} // Resolve a reference to another message.
+
+
+function MessageReference(scope, {
+ name,
+ attr
+}) {
+ const message = scope.bundle._messages.get(name);
+
+ if (!message) {
+ const err = new ReferenceError(`Unknown message: ${name}`);
+ scope.errors.push(err);
+ return new FluentNone(name);
+ }
+
+ if (attr) {
+ const attribute = message.attrs && message.attrs[attr];
+
+ if (attribute) {
+ return Type(scope, attribute);
+ }
+
+ scope.errors.push(new ReferenceError(`Unknown attribute: ${attr}`));
+ return new FluentNone(`${name}.${attr}`);
+ }
+
+ return Type(scope, message);
+} // Resolve a call to a Term with key-value arguments.
+
+
+function TermReference(scope, {
+ name,
+ attr,
+ args
+}) {
+ const id = `-${name}`;
+
+ const term = scope.bundle._terms.get(id);
+
+ if (!term) {
+ const err = new ReferenceError(`Unknown term: ${id}`);
+ scope.errors.push(err);
+ return new FluentNone(id);
+ } // Every TermReference has its own args.
+
+
+ const [, keyargs] = getArguments(scope, args);
+ const local = { ...scope,
+ args: keyargs,
+ insideTermReference: true
+ };
+
+ if (attr) {
+ const attribute = term.attrs && term.attrs[attr];
+
+ if (attribute) {
+ return Type(local, attribute);
+ }
+
+ scope.errors.push(new ReferenceError(`Unknown attribute: ${attr}`));
+ return new FluentNone(`${id}.${attr}`);
+ }
+
+ return Type(local, term);
+} // Resolve a call to a Function with positional and key-value arguments.
+
+
+function FunctionReference(scope, {
+ name,
+ args
+}) {
+ // Some functions are built-in. Others may be provided by the runtime via
+ // the `FluentBundle` constructor.
+ const func = scope.bundle._functions[name] || builtins_namespaceObject[name];
+
+ if (!func) {
+ scope.errors.push(new ReferenceError(`Unknown function: ${name}()`));
+ return new FluentNone(`${name}()`);
+ }
+
+ if (typeof func !== "function") {
+ scope.errors.push(new TypeError(`Function ${name}() is not callable`));
+ return new FluentNone(`${name}()`);
+ }
+
+ try {
+ return func(...getArguments(scope, args));
+ } catch (e) {
+ // XXX Report errors.
+ return new FluentNone(`${name}()`);
+ }
+} // Resolve a select expression to the member object.
+
+
+function SelectExpression(scope, {
+ selector,
+ variants,
+ star
+}) {
+ let sel = Type(scope, selector);
+
+ if (sel instanceof FluentNone) {
+ const variant = getDefault(scope, variants, star);
+ return Type(scope, variant);
+ } // Match the selector against keys of each variant, in order.
+
+
+ for (const variant of variants) {
+ const key = Type(scope, variant.key);
+
+ if (resolver_match(scope.bundle, sel, key)) {
+ return Type(scope, variant);
+ }
+ }
+
+ const variant = getDefault(scope, variants, star);
+ return Type(scope, variant);
+} // Resolve a pattern (a complex string with placeables).
+
+
+function Pattern(scope, ptn) {
+ if (scope.dirty.has(ptn)) {
+ scope.errors.push(new RangeError("Cyclic reference"));
+ return new FluentNone();
+ } // Tag the pattern as dirty for the purpose of the current resolution.
+
+
+ scope.dirty.add(ptn);
+ const result = []; // Wrap interpolations with Directional Isolate Formatting characters
+ // only when the pattern has more than one element.
+
+ const useIsolating = scope.bundle._useIsolating && ptn.length > 1;
+
+ for (const elem of ptn) {
+ if (typeof elem === "string") {
+ result.push(scope.bundle._transform(elem));
+ continue;
+ }
+
+ const part = Type(scope, elem).toString(scope.bundle);
+
+ if (useIsolating) {
+ result.push(FSI);
+ }
+
+ if (part.length > MAX_PLACEABLE_LENGTH) {
+ scope.errors.push(new RangeError("Too many characters in placeable " + `(${part.length}, max allowed is ${MAX_PLACEABLE_LENGTH})`));
+ result.push(part.slice(MAX_PLACEABLE_LENGTH));
+ } else {
+ result.push(part);
+ }
+
+ if (useIsolating) {
+ result.push(PDI);
+ }
+ }
+
+ scope.dirty.delete(ptn);
+ return result.join("");
+}
+/**
+ * Format a translation into a string.
+ *
+ * @param {FluentBundle} bundle
+ * A FluentBundle instance which will be used to resolve the
+ * contextual information of the message.
+ * @param {Object} args
+ * List of arguments provided by the developer which can be accessed
+ * from the message.
+ * @param {Object} message
+ * An object with the Message to be resolved.
+ * @param {Array} errors
+ * An error array that any encountered errors will be appended to.
+ * @returns {FluentType}
+ */
+
+
+function resolve(bundle, args, message, errors = []) {
+ const scope = {
+ bundle,
+ args,
+ errors,
+ dirty: new WeakSet(),
+ // TermReferences are resolved in a new scope.
+ insideTermReference: false
+ };
+ return Type(scope, message).toString(bundle);
+}
+// CONCATENATED MODULE: ./node_modules/fluent/src/error.js
+class FluentError extends Error {}
+// CONCATENATED MODULE: ./node_modules/fluent/src/resource.js
+ // This regex is used to iterate through the beginnings of messages and terms.
+// With the /m flag, the ^ matches at the beginning of every line.
+
+const RE_MESSAGE_START = /^(-?[a-zA-Z][\w-]*) *= */mg; // Both Attributes and Variants are parsed in while loops. These regexes are
+// used to break out of them.
+
+const RE_ATTRIBUTE_START = /\.([a-zA-Z][\w-]*) *= */y;
+const RE_VARIANT_START = /\*?\[/y;
+const RE_NUMBER_LITERAL = /(-?[0-9]+(?:\.([0-9]+))?)/y;
+const RE_IDENTIFIER = /([a-zA-Z][\w-]*)/y;
+const RE_REFERENCE = /([$-])?([a-zA-Z][\w-]*)(?:\.([a-zA-Z][\w-]*))?/y;
+const RE_FUNCTION_NAME = /^[A-Z][A-Z0-9_-]*$/; // A "run" is a sequence of text or string literal characters which don't
+// require any special handling. For TextElements such special characters are: {
+// (starts a placeable), and line breaks which require additional logic to check
+// if the next line is indented. For StringLiterals they are: \ (starts an
+// escape sequence), " (ends the literal), and line breaks which are not allowed
+// in StringLiterals. Note that string runs may be empty; text runs may not.
+
+const RE_TEXT_RUN = /([^{}\n\r]+)/y;
+const RE_STRING_RUN = /([^\\"\n\r]*)/y; // Escape sequences.
+
+const RE_STRING_ESCAPE = /\\([\\"])/y;
+const RE_UNICODE_ESCAPE = /\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{6})/y; // Used for trimming TextElements and indents.
+
+const RE_LEADING_NEWLINES = /^\n+/;
+const RE_TRAILING_SPACES = / +$/; // Used in makeIndent to strip spaces from blank lines and normalize CRLF to LF.
+
+const RE_BLANK_LINES = / *\r?\n/g; // Used in makeIndent to measure the indentation.
+
+const RE_INDENT = /( *)$/; // Common tokens.
+
+const TOKEN_BRACE_OPEN = /{\s*/y;
+const TOKEN_BRACE_CLOSE = /\s*}/y;
+const TOKEN_BRACKET_OPEN = /\[\s*/y;
+const TOKEN_BRACKET_CLOSE = /\s*] */y;
+const TOKEN_PAREN_OPEN = /\s*\(\s*/y;
+const TOKEN_ARROW = /\s*->\s*/y;
+const TOKEN_COLON = /\s*:\s*/y; // Note the optional comma. As a deviation from the Fluent EBNF, the parser
+// doesn't enforce commas between call arguments.
+
+const TOKEN_COMMA = /\s*,?\s*/y;
+const TOKEN_BLANK = /\s+/y; // Maximum number of placeables in a single Pattern to protect against Quadratic
+// Blowup attacks. See https://msdn.microsoft.com/en-us/magazine/ee335713.aspx.
+
+const MAX_PLACEABLES = 100;
+/**
+ * Fluent Resource is a structure storing a map of parsed localization entries.
+ */
+
+class resource_FluentResource extends Map {
+ /**
+ * Create a new FluentResource from Fluent code.
+ */
+ static fromString(source) {
+ RE_MESSAGE_START.lastIndex = 0;
+ let resource = new this();
+ let cursor = 0; // Iterate over the beginnings of messages and terms to efficiently skip
+ // comments and recover from errors.
+
+ while (true) {
+ let next = RE_MESSAGE_START.exec(source);
+
+ if (next === null) {
+ break;
+ }
+
+ cursor = RE_MESSAGE_START.lastIndex;
+
+ try {
+ resource.set(next[1], parseMessage());
+ } catch (err) {
+ if (err instanceof FluentError) {
+ // Don't report any Fluent syntax errors. Skip directly to the
+ // beginning of the next message or term.
+ continue;
+ }
+
+ throw err;
+ }
+ }
+
+ return resource; // The parser implementation is inlined below for performance reasons.
+ // The parser focuses on minimizing the number of false negatives at the
+ // expense of increasing the risk of false positives. In other words, it
+ // aims at parsing valid Fluent messages with a success rate of 100%, but it
+ // may also parse a few invalid messages which the reference parser would
+ // reject. The parser doesn't perform any validation and may produce entries
+ // which wouldn't make sense in the real world. For best results users are
+ // advised to validate translations with the fluent-syntax parser
+ // pre-runtime.
+ // The parser makes an extensive use of sticky regexes which can be anchored
+ // to any offset of the source string without slicing it. Errors are thrown
+ // to bail out of parsing of ill-formed messages.
+
+ function test(re) {
+ re.lastIndex = cursor;
+ return re.test(source);
+ } // Advance the cursor by the char if it matches. May be used as a predicate
+ // (was the match found?) or, if errorClass is passed, as an assertion.
+
+
+ function consumeChar(char, errorClass) {
+ if (source[cursor] === char) {
+ cursor++;
+ return true;
+ }
+
+ if (errorClass) {
+ throw new errorClass(`Expected ${char}`);
+ }
+
+ return false;
+ } // Advance the cursor by the token if it matches. May be used as a predicate
+ // (was the match found?) or, if errorClass is passed, as an assertion.
+
+
+ function consumeToken(re, errorClass) {
+ if (test(re)) {
+ cursor = re.lastIndex;
+ return true;
+ }
+
+ if (errorClass) {
+ throw new errorClass(`Expected ${re.toString()}`);
+ }
+
+ return false;
+ } // Execute a regex, advance the cursor, and return all capture groups.
+
+
+ function match(re) {
+ re.lastIndex = cursor;
+ let result = re.exec(source);
+
+ if (result === null) {
+ throw new FluentError(`Expected ${re.toString()}`);
+ }
+
+ cursor = re.lastIndex;
+ return result;
+ } // Execute a regex, advance the cursor, and return the capture group.
+
+
+ function match1(re) {
+ return match(re)[1];
+ }
+
+ function parseMessage() {
+ let value = parsePattern();
+ let attrs = parseAttributes();
+
+ if (attrs === null) {
+ if (value === null) {
+ throw new FluentError("Expected message value or attributes");
+ }
+
+ return value;
+ }
+
+ return {
+ value,
+ attrs
+ };
+ }
+
+ function parseAttributes() {
+ let attrs = {};
+
+ while (test(RE_ATTRIBUTE_START)) {
+ let name = match1(RE_ATTRIBUTE_START);
+ let value = parsePattern();
+
+ if (value === null) {
+ throw new FluentError("Expected attribute value");
+ }
+
+ attrs[name] = value;
+ }
+
+ return Object.keys(attrs).length > 0 ? attrs : null;
+ }
+
+ function parsePattern() {
+ // First try to parse any simple text on the same line as the id.
+ if (test(RE_TEXT_RUN)) {
+ var first = match1(RE_TEXT_RUN);
+ } // If there's a placeable on the first line, parse a complex pattern.
+
+
+ if (source[cursor] === "{" || source[cursor] === "}") {
+ // Re-use the text parsed above, if possible.
+ return parsePatternElements(first ? [first] : [], Infinity);
+ } // RE_TEXT_VALUE stops at newlines. Only continue parsing the pattern if
+ // what comes after the newline is indented.
+
+
+ let indent = parseIndent();
+
+ if (indent) {
+ if (first) {
+ // If there's text on the first line, the blank block is part of the
+ // translation content in its entirety.
+ return parsePatternElements([first, indent], indent.length);
+ } // Otherwise, we're dealing with a block pattern, i.e. a pattern which
+ // starts on a new line. Discrad the leading newlines but keep the
+ // inline indent; it will be used by the dedentation logic.
+
+
+ indent.value = trim(indent.value, RE_LEADING_NEWLINES);
+ return parsePatternElements([indent], indent.length);
+ }
+
+ if (first) {
+ // It was just a simple inline text after all.
+ return trim(first, RE_TRAILING_SPACES);
+ }
+
+ return null;
+ } // Parse a complex pattern as an array of elements.
+
+
+ function parsePatternElements(elements = [], commonIndent) {
+ let placeableCount = 0;
+
+ while (true) {
+ if (test(RE_TEXT_RUN)) {
+ elements.push(match1(RE_TEXT_RUN));
+ continue;
+ }
+
+ if (source[cursor] === "{") {
+ if (++placeableCount > MAX_PLACEABLES) {
+ throw new FluentError("Too many placeables");
+ }
+
+ elements.push(parsePlaceable());
+ continue;
+ }
+
+ if (source[cursor] === "}") {
+ throw new FluentError("Unbalanced closing brace");
+ }
+
+ let indent = parseIndent();
+
+ if (indent) {
+ elements.push(indent);
+ commonIndent = Math.min(commonIndent, indent.length);
+ continue;
+ }
+
+ break;
+ }
+
+ let lastIndex = elements.length - 1; // Trim the trailing spaces in the last element if it's a TextElement.
+
+ if (typeof elements[lastIndex] === "string") {
+ elements[lastIndex] = trim(elements[lastIndex], RE_TRAILING_SPACES);
+ }
+
+ let baked = [];
+
+ for (let element of elements) {
+ if (element.type === "indent") {
+ // Dedent indented lines by the maximum common indent.
+ element = element.value.slice(0, element.value.length - commonIndent);
+ } else if (element.type === "str") {
+ // Optimize StringLiterals into their value.
+ element = element.value;
+ }
+
+ if (element) {
+ baked.push(element);
+ }
+ }
+
+ return baked;
+ }
+
+ function parsePlaceable() {
+ consumeToken(TOKEN_BRACE_OPEN, FluentError);
+ let selector = parseInlineExpression();
+
+ if (consumeToken(TOKEN_BRACE_CLOSE)) {
+ return selector;
+ }
+
+ if (consumeToken(TOKEN_ARROW)) {
+ let variants = parseVariants();
+ consumeToken(TOKEN_BRACE_CLOSE, FluentError);
+ return {
+ type: "select",
+ selector,
+ ...variants
+ };
+ }
+
+ throw new FluentError("Unclosed placeable");
+ }
+
+ function parseInlineExpression() {
+ if (source[cursor] === "{") {
+ // It's a nested placeable.
+ return parsePlaceable();
+ }
+
+ if (test(RE_REFERENCE)) {
+ let [, sigil, name, attr = null] = match(RE_REFERENCE);
+
+ if (sigil === "$") {
+ return {
+ type: "var",
+ name
+ };
+ }
+
+ if (consumeToken(TOKEN_PAREN_OPEN)) {
+ let args = parseArguments();
+
+ if (sigil === "-") {
+ // A parameterized term: -term(...).
+ return {
+ type: "term",
+ name,
+ attr,
+ args
+ };
+ }
+
+ if (RE_FUNCTION_NAME.test(name)) {
+ return {
+ type: "func",
+ name,
+ args
+ };
+ }
+
+ throw new FluentError("Function names must be all upper-case");
+ }
+
+ if (sigil === "-") {
+ // A non-parameterized term: -term.
+ return {
+ type: "term",
+ name,
+ attr,
+ args: []
+ };
+ }
+
+ return {
+ type: "mesg",
+ name,
+ attr
+ };
+ }
+
+ return parseLiteral();
+ }
+
+ function parseArguments() {
+ let args = [];
+
+ while (true) {
+ switch (source[cursor]) {
+ case ")":
+ // End of the argument list.
+ cursor++;
+ return args;
+
+ case undefined:
+ // EOF
+ throw new FluentError("Unclosed argument list");
+ }
+
+ args.push(parseArgument()); // Commas between arguments are treated as whitespace.
+
+ consumeToken(TOKEN_COMMA);
+ }
+ }
+
+ function parseArgument() {
+ let expr = parseInlineExpression();
+
+ if (expr.type !== "mesg") {
+ return expr;
+ }
+
+ if (consumeToken(TOKEN_COLON)) {
+ // The reference is the beginning of a named argument.
+ return {
+ type: "narg",
+ name: expr.name,
+ value: parseLiteral()
+ };
+ } // It's a regular message reference.
+
+
+ return expr;
+ }
+
+ function parseVariants() {
+ let variants = [];
+ let count = 0;
+ let star;
+
+ while (test(RE_VARIANT_START)) {
+ if (consumeChar("*")) {
+ star = count;
+ }
+
+ let key = parseVariantKey();
+ let value = parsePattern();
+
+ if (value === null) {
+ throw new FluentError("Expected variant value");
+ }
+
+ variants[count++] = {
+ key,
+ value
+ };
+ }
+
+ if (count === 0) {
+ return null;
+ }
+
+ if (star === undefined) {
+ throw new FluentError("Expected default variant");
+ }
+
+ return {
+ variants,
+ star
+ };
+ }
+
+ function parseVariantKey() {
+ consumeToken(TOKEN_BRACKET_OPEN, FluentError);
+ let key = test(RE_NUMBER_LITERAL) ? parseNumberLiteral() : match1(RE_IDENTIFIER);
+ consumeToken(TOKEN_BRACKET_CLOSE, FluentError);
+ return key;
+ }
+
+ function parseLiteral() {
+ if (test(RE_NUMBER_LITERAL)) {
+ return parseNumberLiteral();
+ }
+
+ if (source[cursor] === "\"") {
+ return parseStringLiteral();
+ }
+
+ throw new FluentError("Invalid expression");
+ }
+
+ function parseNumberLiteral() {
+ let [, value, fraction = ""] = match(RE_NUMBER_LITERAL);
+ let precision = fraction.length;
+ return {
+ type: "num",
+ value: parseFloat(value),
+ precision
+ };
+ }
+
+ function parseStringLiteral() {
+ consumeChar("\"", FluentError);
+ let value = "";
+
+ while (true) {
+ value += match1(RE_STRING_RUN);
+
+ if (source[cursor] === "\\") {
+ value += parseEscapeSequence();
+ continue;
+ }
+
+ if (consumeChar("\"")) {
+ return {
+ type: "str",
+ value
+ };
+ } // We've reached an EOL of EOF.
+
+
+ throw new FluentError("Unclosed string literal");
+ }
+ } // Unescape known escape sequences.
+
+
+ function parseEscapeSequence() {
+ if (test(RE_STRING_ESCAPE)) {
+ return match1(RE_STRING_ESCAPE);
+ }
+
+ if (test(RE_UNICODE_ESCAPE)) {
+ let [, codepoint4, codepoint6] = match(RE_UNICODE_ESCAPE);
+ let codepoint = parseInt(codepoint4 || codepoint6, 16);
+ return codepoint <= 0xD7FF || 0xE000 <= codepoint // It's a Unicode scalar value.
+ ? String.fromCodePoint(codepoint) // Lonely surrogates can cause trouble when the parsing result is
+ // saved using UTF-8. Use U+FFFD REPLACEMENT CHARACTER instead.
+ : "�";
+ }
+
+ throw new FluentError("Unknown escape sequence");
+ } // Parse blank space. Return it if it looks like indent before a pattern
+ // line. Skip it othwerwise.
+
+
+ function parseIndent() {
+ let start = cursor;
+ consumeToken(TOKEN_BLANK); // Check the first non-blank character after the indent.
+
+ switch (source[cursor]) {
+ case ".":
+ case "[":
+ case "*":
+ case "}":
+ case undefined:
+ // EOF
+ // A special character. End the Pattern.
+ return false;
+
+ case "{":
+ // Placeables don't require indentation (in EBNF: block-placeable).
+ // Continue the Pattern.
+ return makeIndent(source.slice(start, cursor));
+ } // If the first character on the line is not one of the special characters
+ // listed above, it's a regular text character. Check if there's at least
+ // one space of indent before it.
+
+
+ if (source[cursor - 1] === " ") {
+ // It's an indented text character (in EBNF: indented-char). Continue
+ // the Pattern.
+ return makeIndent(source.slice(start, cursor));
+ } // A not-indented text character is likely the identifier of the next
+ // message. End the Pattern.
+
+
+ return false;
+ } // Trim blanks in text according to the given regex.
+
+
+ function trim(text, re) {
+ return text.replace(re, "");
+ } // Normalize a blank block and extract the indent details.
+
+
+ function makeIndent(blank) {
+ let value = blank.replace(RE_BLANK_LINES, "\n");
+ let length = RE_INDENT.exec(blank)[1].length;
+ return {
+ type: "indent",
+ value,
+ length
+ };
+ }
+ }
+
+}
+// CONCATENATED MODULE: ./node_modules/fluent/src/bundle.js
+
+
+/**
+ * Message bundles are single-language stores of translations. They are
+ * responsible for parsing translation resources in the Fluent syntax and can
+ * format translation units (entities) to strings.
+ *
+ * Always use `FluentBundle.format` to retrieve translation units from a
+ * bundle. Translations can contain references to other entities or variables,
+ * conditional logic in form of select expressions, traits which describe their
+ * grammatical features, and can use Fluent builtins which make use of the
+ * `Intl` formatters to format numbers, dates, lists and more into the
+ * bundle's language. See the documentation of the Fluent syntax for more
+ * information.
+ */
+
+class bundle_FluentBundle {
+ /**
+ * Create an instance of `FluentBundle`.
+ *
+ * The `locales` argument is used to instantiate `Intl` formatters used by
+ * translations. The `options` object can be used to configure the bundle.
+ *
+ * Examples:
+ *
+ * const bundle = new FluentBundle(locales);
+ *
+ * const bundle = new FluentBundle(locales, { useIsolating: false });
+ *
+ * const bundle = new FluentBundle(locales, {
+ * useIsolating: true,
+ * functions: {
+ * NODE_ENV: () => process.env.NODE_ENV
+ * }
+ * });
+ *
+ * Available options:
+ *
+ * - `functions` - an object of additional functions available to
+ * translations as builtins.
+ *
+ * - `useIsolating` - boolean specifying whether to use Unicode isolation
+ * marks (FSI, PDI) for bidi interpolations.
+ * Default: true
+ *
+ * - `transform` - a function used to transform string parts of patterns.
+ *
+ * @param {string|Array<string>} locales - Locale or locales of the bundle
+ * @param {Object} [options]
+ * @returns {FluentBundle}
+ */
+ constructor(locales, {
+ functions = {},
+ useIsolating = true,
+ transform = v => v
+ } = {}) {
+ this.locales = Array.isArray(locales) ? locales : [locales];
+ this._terms = new Map();
+ this._messages = new Map();
+ this._functions = functions;
+ this._useIsolating = useIsolating;
+ this._transform = transform;
+ this._intls = new WeakMap();
+ }
+ /*
+ * Return an iterator over public `[id, message]` pairs.
+ *
+ * @returns {Iterator}
+ */
+
+
+ get messages() {
+ return this._messages[Symbol.iterator]();
+ }
+ /*
+ * Check if a message is present in the bundle.
+ *
+ * @param {string} id - The identifier of the message to check.
+ * @returns {bool}
+ */
+
+
+ hasMessage(id) {
+ return this._messages.has(id);
+ }
+ /*
+ * Return the internal representation of a message.
+ *
+ * The internal representation should only be used as an argument to
+ * `FluentBundle.format`.
+ *
+ * @param {string} id - The identifier of the message to check.
+ * @returns {Any}
+ */
+
+
+ getMessage(id) {
+ return this._messages.get(id);
+ }
+ /**
+ * Add a translation resource to the bundle.
+ *
+ * The translation resource must use the Fluent syntax. It will be parsed by
+ * the bundle and each translation unit (message) will be available in the
+ * bundle by its identifier.
+ *
+ * bundle.addMessages('foo = Foo');
+ * bundle.getMessage('foo');
+ *
+ * // Returns a raw representation of the 'foo' message.
+ *
+ * bundle.addMessages('bar = Bar');
+ * bundle.addMessages('bar = Newbar', { allowOverrides: true });
+ * bundle.getMessage('bar');
+ *
+ * // Returns a raw representation of the 'bar' message: Newbar.
+ *
+ * Parsed entities should be formatted with the `format` method in case they
+ * contain logic (references, select expressions etc.).
+ *
+ * Available options:
+ *
+ * - `allowOverrides` - boolean specifying whether it's allowed to override
+ * an existing message or term with a new value.
+ * Default: false
+ *
+ * @param {string} source - Text resource with translations.
+ * @param {Object} [options]
+ * @returns {Array<Error>}
+ */
+
+
+ addMessages(source, options) {
+ const res = resource_FluentResource.fromString(source);
+ return this.addResource(res, options);
+ }
+ /**
+ * Add a translation resource to the bundle.
+ *
+ * The translation resource must be an instance of FluentResource,
+ * e.g. parsed by `FluentResource.fromString`.
+ *
+ * let res = FluentResource.fromString("foo = Foo");
+ * bundle.addResource(res);
+ * bundle.getMessage('foo');
+ *
+ * // Returns a raw representation of the 'foo' message.
+ *
+ * let res = FluentResource.fromString("bar = Bar");
+ * bundle.addResource(res);
+ * res = FluentResource.fromString("bar = Newbar");
+ * bundle.addResource(res, { allowOverrides: true });
+ * bundle.getMessage('bar');
+ *
+ * // Returns a raw representation of the 'bar' message: Newbar.
+ *
+ * Parsed entities should be formatted with the `format` method in case they
+ * contain logic (references, select expressions etc.).
+ *
+ * Available options:
+ *
+ * - `allowOverrides` - boolean specifying whether it's allowed to override
+ * an existing message or term with a new value.
+ * Default: false
+ *
+ * @param {FluentResource} res - FluentResource object.
+ * @param {Object} [options]
+ * @returns {Array<Error>}
+ */
+
+
+ addResource(res, {
+ allowOverrides = false
+ } = {}) {
+ const errors = [];
+
+ for (const [id, value] of res) {
+ if (id.startsWith("-")) {
+ // Identifiers starting with a dash (-) define terms. Terms are private
+ // and cannot be retrieved from FluentBundle.
+ if (allowOverrides === false && this._terms.has(id)) {
+ errors.push(`Attempt to override an existing term: "${id}"`);
+ continue;
+ }
+
+ this._terms.set(id, value);
+ } else {
+ if (allowOverrides === false && this._messages.has(id)) {
+ errors.push(`Attempt to override an existing message: "${id}"`);
+ continue;
+ }
+
+ this._messages.set(id, value);
+ }
+ }
+
+ return errors;
+ }
+ /**
+ * Format a message to a string or null.
+ *
+ * Format a raw `message` from the bundle into a string (or a null if it has
+ * a null value). `args` will be used to resolve references to variables
+ * passed as arguments to the translation.
+ *
+ * In case of errors `format` will try to salvage as much of the translation
+ * as possible and will still return a string. For performance reasons, the
+ * encountered errors are not returned but instead are appended to the
+ * `errors` array passed as the third argument.
+ *
+ * const errors = [];
+ * bundle.addMessages('hello = Hello, { $name }!');
+ * const hello = bundle.getMessage('hello');
+ * bundle.format(hello, { name: 'Jane' }, errors);
+ *
+ * // Returns 'Hello, Jane!' and `errors` is empty.
+ *
+ * bundle.format(hello, undefined, errors);
+ *
+ * // Returns 'Hello, name!' and `errors` is now:
+ *
+ * [<ReferenceError: Unknown variable: name>]
+ *
+ * @param {Object | string} message
+ * @param {Object | undefined} args
+ * @param {Array} errors
+ * @returns {?string}
+ */
+
+
+ format(message, args, errors) {
+ // optimize entities which are simple strings with no attributes
+ if (typeof message === "string") {
+ return this._transform(message);
+ } // optimize entities with null values
+
+
+ if (message === null || message.value === null) {
+ return null;
+ } // optimize simple-string entities with attributes
+
+
+ if (typeof message.value === "string") {
+ return this._transform(message.value);
+ }
+
+ return resolve(this, args, message, errors);
+ }
+
+ _memoizeIntlObject(ctor, opts) {
+ const cache = this._intls.get(ctor) || {};
+ const id = JSON.stringify(opts);
+
+ if (!cache[id]) {
+ cache[id] = new ctor(this.locales, opts);
+
+ this._intls.set(ctor, cache);
+ }
+
+ return cache[id];
+ }
+
+}
+// CONCATENATED MODULE: ./node_modules/fluent/src/index.js
+/*
+ * @module fluent
+ * @overview
+ *
+ * `fluent` is a JavaScript implementation of Project Fluent, a localization
+ * framework designed to unleash the expressive power of the natural language.
+ *
+ */
+
+
+
+
+// CONCATENATED MODULE: ./content-src/asrouter/rich-text-strings.js
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RICH_TEXT_KEYS", function() { return RICH_TEXT_KEYS; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "generateBundles", function() { return generateBundles; });
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/**
+ * Properties that allow rich text MUST be added to this list.
+ * key: the localization_id that should be used
+ * value: a property or array of properties on the message.content object
+ */
+
+const RICH_TEXT_CONFIG = {
+ text: ["text", "scene1_text"],
+ success_text: "success_text",
+ error_text: "error_text",
+ scene2_text: "scene2_text",
+ amo_html: "amo_html",
+ privacy_html: "scene2_privacy_html",
+ disclaimer_html: "scene2_disclaimer_html"
+};
+const RICH_TEXT_KEYS = Object.keys(RICH_TEXT_CONFIG);
+/**
+ * Generates an array of messages suitable for fluent's localization provider
+ * including all needed strings for rich text.
+ * @param {object} content A .content object from an ASR message (i.e. message.content)
+ * @returns {FluentBundle[]} A array containing the fluent message context
+ */
+
+function generateBundles(content) {
+ const bundle = new bundle_FluentBundle("en-US");
+ RICH_TEXT_KEYS.forEach(key => {
+ const attrs = RICH_TEXT_CONFIG[key];
+ const attrsToTry = Array.isArray(attrs) ? [...attrs] : [attrs];
+ let string = "";
+
+ while (!string && attrsToTry.length) {
+ const attr = attrsToTry.pop();
+ string = content[attr];
+ }
+
+ bundle.addMessages(`${key} = ${string}`);
+ });
+ return [bundle];
+}
+
+/***/ }),
+/* 71 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+
+// EXTERNAL MODULE: external "React"
+var external_React_ = __webpack_require__(8);
+var external_React_default = /*#__PURE__*/__webpack_require__.n(external_React_);
+
+// CONCATENATED MODULE: ./content-src/components/CustomizeMenu/ThemesSection/ThemesSection.jsx
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+class ThemesSection_ThemesSection extends external_React_default.a.PureComponent {
+ render() {
+ return external_React_default.a.createElement("div", null);
+ }
+
+}
+// CONCATENATED MODULE: ./content-src/components/CustomizeMenu/BackgroundsSection/BackgroundsSection.jsx
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+class BackgroundsSection_BackgroundsSection extends external_React_default.a.PureComponent {
+ render() {
+ return external_React_default.a.createElement("div", null);
+ }
+
+}
+// EXTERNAL MODULE: ./common/Actions.jsm
+var Actions = __webpack_require__(1);
+
+// CONCATENATED MODULE: ./content-src/components/CustomizeMenu/ContentSection/ContentSection.jsx
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+class ContentSection_ContentSection extends external_React_default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.onPreferenceSelect = this.onPreferenceSelect.bind(this);
+ }
+
+ inputUserEvent(eventSource, status) {
+ this.props.dispatch(Actions["actionCreators"].UserEvent({
+ event: "PREF_CHANGED",
+ source: eventSource,
+ value: {
+ status,
+ menu_source: "CUSTOMIZE_MENU"
+ }
+ }));
+ }
+
+ onPreferenceSelect(e) {
+ let prefName = e.target.getAttribute("preference");
+ const eventSource = e.target.getAttribute("eventSource");
+ let value;
+
+ if (e.target.nodeName === "SELECT") {
+ value = parseInt(e.target.value, 10);
+ } else if (e.target.nodeName === "INPUT") {
+ value = e.target.checked;
+
+ if (eventSource) {
+ this.inputUserEvent(eventSource, value);
+ }
+ }
+
+ this.props.setPref(prefName, value);
+ }
+
+ render() {
+ const {
+ topSitesEnabled,
+ pocketEnabled,
+ highlightsEnabled,
+ snippetsEnabled,
+ showSponsoredTopSitesEnabled,
+ showSponsoredPocketEnabled,
+ topSitesRowsCount
+ } = this.props.enabledSections;
+ return external_React_default.a.createElement("div", {
+ className: "home-section"
+ }, external_React_default.a.createElement("div", {
+ id: "shortcuts-section",
+ className: "section"
+ }, external_React_default.a.createElement("label", {
+ className: "switch"
+ }, external_React_default.a.createElement("input", {
+ id: "shortcuts-toggle",
+ checked: topSitesEnabled,
+ type: "checkbox",
+ onChange: this.onPreferenceSelect,
+ preference: "feeds.topsites",
+ "aria-labelledby": "custom-shortcuts-title",
+ "aria-describedby": "custom-shortcuts-subtitle",
+ eventSource: "TOP_SITES"
+ }), external_React_default.a.createElement("span", {
+ className: "slider",
+ role: "presentation"
+ })), external_React_default.a.createElement("div", null, external_React_default.a.createElement("h2", {
+ id: "custom-shortcuts-title",
+ className: "title"
+ }, external_React_default.a.createElement("label", {
+ htmlFor: "shortcuts-toggle",
+ "data-l10n-id": "newtab-custom-shortcuts-title"
+ })), external_React_default.a.createElement("p", {
+ id: "custom-shortcuts-subtitle",
+ className: "subtitle",
+ "data-l10n-id": "newtab-custom-shortcuts-subtitle"
+ }), external_React_default.a.createElement("div", {
+ className: `more-info-top-wrapper ${topSitesEnabled ? "" : "shrink"}`
+ }, external_React_default.a.createElement("div", {
+ className: `more-information ${topSitesEnabled ? "expand" : "shrink"}`
+ }, external_React_default.a.createElement("select", {
+ id: "row-selector",
+ className: "selector",
+ name: "row-count",
+ preference: "topSitesRows",
+ value: topSitesRowsCount,
+ onChange: this.onPreferenceSelect,
+ disabled: !topSitesEnabled,
+ "aria-labelledby": "custom-shortcuts-title"
+ }, external_React_default.a.createElement("option", {
+ value: "1",
+ "data-l10n-id": "newtab-custom-row-selector",
+ "data-l10n-args": "{\"num\": 1}"
+ }), external_React_default.a.createElement("option", {
+ value: "2",
+ "data-l10n-id": "newtab-custom-row-selector",
+ "data-l10n-args": "{\"num\": 2}"
+ }), external_React_default.a.createElement("option", {
+ value: "3",
+ "data-l10n-id": "newtab-custom-row-selector",
+ "data-l10n-args": "{\"num\": 3}"
+ }), external_React_default.a.createElement("option", {
+ value: "4",
+ "data-l10n-id": "newtab-custom-row-selector",
+ "data-l10n-args": "{\"num\": 4}"
+ })), this.props.mayHaveSponsoredTopSites && external_React_default.a.createElement("div", {
+ className: "check-wrapper",
+ role: "presentation"
+ }, external_React_default.a.createElement("input", {
+ id: "sponsored-shortcuts",
+ className: "sponsored-checkbox",
+ disabled: !topSitesEnabled,
+ checked: showSponsoredTopSitesEnabled,
+ type: "checkbox",
+ onChange: this.onPreferenceSelect,
+ preference: "showSponsoredTopSites",
+ eventSource: "SPONSORED_TOP_SITES"
+ }), external_React_default.a.createElement("label", {
+ className: "sponsored",
+ htmlFor: "sponsored-shortcuts",
+ "data-l10n-id": "newtab-custom-sponsored-sites"
+ })))))), this.props.pocketRegion && external_React_default.a.createElement("div", {
+ id: "pocket-section",
+ className: "section"
+ }, external_React_default.a.createElement("label", {
+ className: "switch"
+ }, external_React_default.a.createElement("input", {
+ id: "pocket-toggle",
+ checked: pocketEnabled,
+ type: "checkbox",
+ onChange: this.onPreferenceSelect,
+ preference: "feeds.section.topstories",
+ "aria-labelledby": "custom-pocket-title",
+ "aria-describedby": "custom-pocket-subtitle",
+ eventSource: "TOP_STORIES"
+ }), external_React_default.a.createElement("span", {
+ className: "slider",
+ role: "presentation"
+ })), external_React_default.a.createElement("div", null, external_React_default.a.createElement("h2", {
+ id: "custom-pocket-title",
+ className: "title"
+ }, external_React_default.a.createElement("label", {
+ htmlFor: "pocket-toggle",
+ "data-l10n-id": "newtab-custom-pocket-title"
+ })), external_React_default.a.createElement("p", {
+ id: "custom-pocket-subtitle",
+ className: "subtitle",
+ "data-l10n-id": "newtab-custom-pocket-subtitle"
+ }), this.props.mayHaveSponsoredStories && external_React_default.a.createElement("div", {
+ className: `more-info-pocket-wrapper ${pocketEnabled ? "" : "shrink"}`
+ }, external_React_default.a.createElement("div", {
+ className: `more-information ${pocketEnabled ? "expand" : "shrink"}`
+ }, external_React_default.a.createElement("div", {
+ className: "check-wrapper",
+ role: "presentation"
+ }, external_React_default.a.createElement("input", {
+ id: "sponsored-pocket",
+ className: "sponsored-checkbox",
+ disabled: !pocketEnabled,
+ checked: showSponsoredPocketEnabled,
+ type: "checkbox",
+ onChange: this.onPreferenceSelect,
+ preference: "showSponsored",
+ eventSource: "POCKET_SPOCS"
+ }), external_React_default.a.createElement("label", {
+ className: "sponsored",
+ htmlFor: "sponsored-pocket",
+ "data-l10n-id": "newtab-custom-pocket-sponsored"
+ })))))), external_React_default.a.createElement("div", {
+ id: "recent-section",
+ className: "section"
+ }, external_React_default.a.createElement("label", {
+ className: "switch"
+ }, external_React_default.a.createElement("input", {
+ id: "highlights-toggle",
+ checked: highlightsEnabled,
+ type: "checkbox",
+ onChange: this.onPreferenceSelect,
+ preference: "feeds.section.highlights",
+ eventSource: "HIGHLIGHTS",
+ "aria-labelledby": "custom-recent-title",
+ "aria-describedby": "custom-recent-subtitle"
+ }), external_React_default.a.createElement("span", {
+ className: "slider",
+ role: "presentation"
+ })), external_React_default.a.createElement("div", null, external_React_default.a.createElement("h2", {
+ id: "custom-recent-title",
+ className: "title"
+ }, external_React_default.a.createElement("label", {
+ htmlFor: "highlights-toggle",
+ "data-l10n-id": "newtab-custom-recent-title"
+ })), external_React_default.a.createElement("p", {
+ id: "custom-recent-subtitle",
+ className: "subtitle",
+ "data-l10n-id": "newtab-custom-recent-subtitle"
+ }))), external_React_default.a.createElement("div", {
+ id: "snippets-section",
+ className: "section"
+ }, external_React_default.a.createElement("label", {
+ className: "switch"
+ }, external_React_default.a.createElement("input", {
+ id: "snippets-toggle",
+ checked: snippetsEnabled,
+ type: "checkbox",
+ onChange: this.onPreferenceSelect,
+ preference: "feeds.snippets",
+ "aria-labelledby": "custom-snippets-title",
+ "aria-describedby": "custom-snippets-subtitle",
+ eventSource: "SNIPPETS"
+ }), external_React_default.a.createElement("span", {
+ className: "slider",
+ role: "presentation"
+ })), external_React_default.a.createElement("div", null, external_React_default.a.createElement("h2", {
+ id: "custom-snippets-title",
+ className: "title"
+ }, external_React_default.a.createElement("label", {
+ htmlFor: "snippets-toggle",
+ "data-l10n-id": "newtab-custom-snippets-title"
+ })), external_React_default.a.createElement("p", {
+ id: "custom-snippets-subtitle",
+ className: "subtitle",
+ "data-l10n-id": "newtab-custom-snippets-subtitle"
+ }))), external_React_default.a.createElement("span", {
+ className: "divider",
+ role: "separator"
+ }), external_React_default.a.createElement("div", null, external_React_default.a.createElement("button", {
+ id: "settings-link",
+ className: "external-link",
+ onClick: this.props.openPreferences,
+ "data-l10n-id": "newtab-custom-settings"
+ })));
+ }
+
+}
+// EXTERNAL MODULE: external "ReactRedux"
+var external_ReactRedux_ = __webpack_require__(7);
+
+// CONCATENATED MODULE: ./content-src/components/CustomizeMenu/CustomizeMenu.jsx
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_CustomizeMenu", function() { return CustomizeMenu_CustomizeMenu; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CustomizeMenu", function() { return CustomizeMenu; });
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+
+
+
+class CustomizeMenu_CustomizeMenu extends external_React_default.a.PureComponent {
+ render() {
+ return external_React_default.a.createElement("div", {
+ className: "customize-menu"
+ }, external_React_default.a.createElement("button", {
+ onClick: this.props.onClose,
+ className: "close-button",
+ "data-l10n-id": "newtab-custom-close-button"
+ }), external_React_default.a.createElement(ThemesSection_ThemesSection, null), external_React_default.a.createElement(BackgroundsSection_BackgroundsSection, null), external_React_default.a.createElement(ContentSection_ContentSection, {
+ openPreferences: this.props.openPreferences,
+ setPref: this.props.setPref,
+ enabledSections: this.props.enabledSections,
+ pocketRegion: this.props.pocketRegion,
+ mayHaveSponsoredTopSites: this.props.mayHaveSponsoredTopSites,
+ mayHaveSponsoredStories: this.props.DiscoveryStream.config.show_spocs,
+ dispatch: this.props.dispatch
+ }));
+ }
+
+}
+const CustomizeMenu = Object(external_ReactRedux_["connect"])(state => ({
+ DiscoveryStream: state.DiscoveryStream
+}))(CustomizeMenu_CustomizeMenu);
+
+/***/ }),
+/* 72 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+
+// EXTERNAL MODULE: ./common/Actions.jsm
+var Actions = __webpack_require__(1);
+
+// CONCATENATED MODULE: ./common/Dedupe.jsm
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+class Dedupe {
+ constructor(createKey) {
+ this.createKey = createKey || this.defaultCreateKey;
+ }
+
+ defaultCreateKey(item) {
+ return item;
+ }
+ /**
+ * Dedupe any number of grouped elements favoring those from earlier groups.
+ *
+ * @param {Array} groups Contains an arbitrary number of arrays of elements.
+ * @returns {Array} A matching array of each provided group deduped.
+ */
+
+
+ group(...groups) {
+ const globalKeys = new Set();
+ const result = [];
+
+ for (const values of groups) {
+ const valueMap = new Map();
+
+ for (const value of values) {
+ const key = this.createKey(value);
+
+ if (!globalKeys.has(key) && !valueMap.has(key)) {
+ valueMap.set(key, value);
+ }
+ }
+
+ result.push(valueMap);
+ valueMap.forEach((value, key) => globalKeys.add(key));
+ }
+
+ return result.map(m => Array.from(m.values()));
+ }
+
+}
+// CONCATENATED MODULE: ./common/Reducers.jsm
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TOP_SITES_DEFAULT_ROWS", function() { return TOP_SITES_DEFAULT_ROWS; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TOP_SITES_MAX_SITES_PER_ROW", function() { return TOP_SITES_MAX_SITES_PER_ROW; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "INITIAL_STATE", function() { return INITIAL_STATE; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "insertPinned", function() { return insertPinned; });
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "reducers", function() { return reducers; });
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+
+
+const TOP_SITES_DEFAULT_ROWS = 1;
+const TOP_SITES_MAX_SITES_PER_ROW = 8;
+const PREF_PERSONALIZATION_VERSION = "discoverystream.personalization.version";
+const PREF_COLLECTION_DISMISSIBLE = "discoverystream.isCollectionDismissible";
+const dedupe = new Dedupe(site => site && site.url);
+const INITIAL_STATE = {
+ App: {
+ // Have we received real data from the app yet?
+ initialized: false,
+ locale: ""
+ },
+ ASRouter: {
+ initialized: false
+ },
+ Snippets: {
+ initialized: false
+ },
+ TopSites: {
+ // Have we received real data from history yet?
+ initialized: false,
+ // The history (and possibly default) links
+ rows: [],
+ // Used in content only to dispatch action to TopSiteForm.
+ editForm: null,
+ // Used in content only to open the SearchShortcutsForm modal.
+ showSearchShortcutsForm: false,
+ // The list of available search shortcuts.
+ searchShortcuts: []
+ },
+ Prefs: {
+ initialized: false,
+ values: {}
+ },
+ Dialog: {
+ visible: false,
+ data: {}
+ },
+ Sections: [],
+ Pocket: {
+ isUserLoggedIn: null,
+ pocketCta: {},
+ waitingForSpoc: true
+ },
+ // This is the new pocket configurable layout state.
+ DiscoveryStream: {
+ // This is a JSON-parsed copy of the discoverystream.config pref value.
+ config: {
+ enabled: false,
+ layout_endpoint: ""
+ },
+ layout: [],
+ lastUpdated: null,
+ isPrivacyInfoModalVisible: false,
+ isCollectionDismissible: false,
+ feeds: {
+ data: {// "https://foo.com/feed1": {lastUpdated: 123, data: []}
+ },
+ loaded: false
+ },
+ spocs: {
+ spocs_endpoint: "",
+ lastUpdated: null,
+ data: {// "spocs": {title: "", context: "", items: []},
+ // "placement1": {title: "", context: "", items: []},
+ },
+ loaded: false,
+ frequency_caps: [],
+ blocked: [],
+ placements: []
+ }
+ },
+ Personalization: {
+ version: 1,
+ lastUpdated: null,
+ initialized: false
+ },
+ Search: {
+ // When search hand-off is enabled, we render a big button that is styled to
+ // look like a search textbox. If the button is clicked, we style
+ // the button as if it was a focused search box and show a fake cursor but
+ // really focus the awesomebar without the focus styles ("hidden focus").
+ fakeFocus: false,
+ // Hide the search box after handing off to AwesomeBar and user starts typing.
+ hide: false
+ }
+};
+
+function App(prevState = INITIAL_STATE.App, action) {
+ switch (action.type) {
+ case Actions["actionTypes"].INIT:
+ return Object.assign({}, prevState, action.data || {}, {
+ initialized: true
+ });
+
+ default:
+ return prevState;
+ }
+}
+
+function ASRouter(prevState = INITIAL_STATE.ASRouter, action) {
+ switch (action.type) {
+ case Actions["actionTypes"].AS_ROUTER_INITIALIZED:
+ return { ...action.data,
+ initialized: true
+ };
+
+ default:
+ return prevState;
+ }
+}
+/**
+ * insertPinned - Inserts pinned links in their specified slots
+ *
+ * @param {array} a list of links
+ * @param {array} a list of pinned links
+ * @return {array} resulting list of links with pinned links inserted
+ */
+
+
+function insertPinned(links, pinned) {
+ // Remove any pinned links
+ const pinnedUrls = pinned.map(link => link && link.url);
+ let newLinks = links.filter(link => link ? !pinnedUrls.includes(link.url) : false);
+ newLinks = newLinks.map(link => {
+ if (link && link.isPinned) {
+ delete link.isPinned;
+ delete link.pinIndex;
+ }
+
+ return link;
+ }); // Then insert them in their specified location
+
+ pinned.forEach((val, index) => {
+ if (!val) {
+ return;
+ }
+
+ let link = Object.assign({}, val, {
+ isPinned: true,
+ pinIndex: index
+ });
+
+ if (index > newLinks.length) {
+ newLinks[index] = link;
+ } else {
+ newLinks.splice(index, 0, link);
+ }
+ });
+ return newLinks;
+}
+
+function TopSites(prevState = INITIAL_STATE.TopSites, action) {
+ let hasMatch;
+ let newRows;
+
+ switch (action.type) {
+ case Actions["actionTypes"].TOP_SITES_UPDATED:
+ if (!action.data || !action.data.links) {
+ return prevState;
+ }
+
+ return Object.assign({}, prevState, {
+ initialized: true,
+ rows: action.data.links
+ }, action.data.pref ? {
+ pref: action.data.pref
+ } : {});
+
+ case Actions["actionTypes"].TOP_SITES_PREFS_UPDATED:
+ return Object.assign({}, prevState, {
+ pref: action.data.pref
+ });
+
+ case Actions["actionTypes"].TOP_SITES_EDIT:
+ return Object.assign({}, prevState, {
+ editForm: {
+ index: action.data.index,
+ previewResponse: null
+ }
+ });
+
+ case Actions["actionTypes"].TOP_SITES_CANCEL_EDIT:
+ return Object.assign({}, prevState, {
+ editForm: null
+ });
+
+ case Actions["actionTypes"].TOP_SITES_OPEN_SEARCH_SHORTCUTS_MODAL:
+ return Object.assign({}, prevState, {
+ showSearchShortcutsForm: true
+ });
+
+ case Actions["actionTypes"].TOP_SITES_CLOSE_SEARCH_SHORTCUTS_MODAL:
+ return Object.assign({}, prevState, {
+ showSearchShortcutsForm: false
+ });
+
+ case Actions["actionTypes"].PREVIEW_RESPONSE:
+ if (!prevState.editForm || action.data.url !== prevState.editForm.previewUrl) {
+ return prevState;
+ }
+
+ return Object.assign({}, prevState, {
+ editForm: {
+ index: prevState.editForm.index,
+ previewResponse: action.data.preview,
+ previewUrl: action.data.url
+ }
+ });
+
+ case Actions["actionTypes"].PREVIEW_REQUEST:
+ if (!prevState.editForm) {
+ return prevState;
+ }
+
+ return Object.assign({}, prevState, {
+ editForm: {
+ index: prevState.editForm.index,
+ previewResponse: null,
+ previewUrl: action.data.url
+ }
+ });
+
+ case Actions["actionTypes"].PREVIEW_REQUEST_CANCEL:
+ if (!prevState.editForm) {
+ return prevState;
+ }
+
+ return Object.assign({}, prevState, {
+ editForm: {
+ index: prevState.editForm.index,
+ previewResponse: null
+ }
+ });
+
+ case Actions["actionTypes"].SCREENSHOT_UPDATED:
+ newRows = prevState.rows.map(row => {
+ if (row && row.url === action.data.url) {
+ hasMatch = true;
+ return Object.assign({}, row, {
+ screenshot: action.data.screenshot
+ });
+ }
+
+ return row;
+ });
+ return hasMatch ? Object.assign({}, prevState, {
+ rows: newRows
+ }) : prevState;
+
+ case Actions["actionTypes"].PLACES_BOOKMARK_ADDED:
+ if (!action.data) {
+ return prevState;
+ }
+
+ newRows = prevState.rows.map(site => {
+ if (site && site.url === action.data.url) {
+ const {
+ bookmarkGuid,
+ bookmarkTitle,
+ dateAdded
+ } = action.data;
+ return Object.assign({}, site, {
+ bookmarkGuid,
+ bookmarkTitle,
+ bookmarkDateCreated: dateAdded
+ });
+ }
+
+ return site;
+ });
+ return Object.assign({}, prevState, {
+ rows: newRows
+ });
+
+ case Actions["actionTypes"].PLACES_BOOKMARK_REMOVED:
+ if (!action.data) {
+ return prevState;
+ }
+
+ newRows = prevState.rows.map(site => {
+ if (site && site.url === action.data.url) {
+ const newSite = Object.assign({}, site);
+ delete newSite.bookmarkGuid;
+ delete newSite.bookmarkTitle;
+ delete newSite.bookmarkDateCreated;
+ return newSite;
+ }
+
+ return site;
+ });
+ return Object.assign({}, prevState, {
+ rows: newRows
+ });
+
+ case Actions["actionTypes"].PLACES_LINK_DELETED:
+ if (!action.data) {
+ return prevState;
+ }
+
+ newRows = prevState.rows.filter(site => action.data.url !== site.url);
+ return Object.assign({}, prevState, {
+ rows: newRows
+ });
+
+ case Actions["actionTypes"].UPDATE_SEARCH_SHORTCUTS:
+ return { ...prevState,
+ searchShortcuts: action.data.searchShortcuts
+ };
+
+ case Actions["actionTypes"].SNIPPETS_PREVIEW_MODE:
+ return { ...prevState,
+ rows: []
+ };
+
+ default:
+ return prevState;
+ }
+}
+
+function Dialog(prevState = INITIAL_STATE.Dialog, action) {
+ switch (action.type) {
+ case Actions["actionTypes"].DIALOG_OPEN:
+ return Object.assign({}, prevState, {
+ visible: true,
+ data: action.data
+ });
+
+ case Actions["actionTypes"].DIALOG_CANCEL:
+ return Object.assign({}, prevState, {
+ visible: false
+ });
+
+ case Actions["actionTypes"].DELETE_HISTORY_URL:
+ return Object.assign({}, INITIAL_STATE.Dialog);
+
+ default:
+ return prevState;
+ }
+}
+
+function Prefs(prevState = INITIAL_STATE.Prefs, action) {
+ let newValues;
+
+ switch (action.type) {
+ case Actions["actionTypes"].PREFS_INITIAL_VALUES:
+ return Object.assign({}, prevState, {
+ initialized: true,
+ values: action.data
+ });
+
+ case Actions["actionTypes"].PREF_CHANGED:
+ newValues = Object.assign({}, prevState.values);
+ newValues[action.data.name] = action.data.value;
+ return Object.assign({}, prevState, {
+ values: newValues
+ });
+
+ default:
+ return prevState;
+ }
+}
+
+function Sections(prevState = INITIAL_STATE.Sections, action) {
+ let hasMatch;
+ let newState;
+
+ switch (action.type) {
+ case Actions["actionTypes"].SECTION_DEREGISTER:
+ return prevState.filter(section => section.id !== action.data);
+
+ case Actions["actionTypes"].SECTION_REGISTER:
+ // If section exists in prevState, update it
+ newState = prevState.map(section => {
+ if (section && section.id === action.data.id) {
+ hasMatch = true;
+ return Object.assign({}, section, action.data);
+ }
+
+ return section;
+ }); // Otherwise, append it
+
+ if (!hasMatch) {
+ const initialized = !!(action.data.rows && !!action.data.rows.length);
+ const section = Object.assign({
+ title: "",
+ rows: [],
+ enabled: false
+ }, action.data, {
+ initialized
+ });
+ newState.push(section);
+ }
+
+ return newState;
+
+ case Actions["actionTypes"].SECTION_UPDATE:
+ newState = prevState.map(section => {
+ if (section && section.id === action.data.id) {
+ // If the action is updating rows, we should consider initialized to be true.
+ // This can be overridden if initialized is defined in the action.data
+ const initialized = action.data.rows ? {
+ initialized: true
+ } : {}; // Make sure pinned cards stay at their current position when rows are updated.
+ // Disabling a section (SECTION_UPDATE with empty rows) does not retain pinned cards.
+
+ if (action.data.rows && !!action.data.rows.length && section.rows.find(card => card.pinned)) {
+ const rows = Array.from(action.data.rows);
+ section.rows.forEach((card, index) => {
+ if (card.pinned) {
+ // Only add it if it's not already there.
+ if (rows[index].guid !== card.guid) {
+ rows.splice(index, 0, card);
+ }
+ }
+ });
+ return Object.assign({}, section, initialized, Object.assign({}, action.data, {
+ rows
+ }));
+ }
+
+ return Object.assign({}, section, initialized, action.data);
+ }
+
+ return section;
+ });
+
+ if (!action.data.dedupeConfigurations) {
+ return newState;
+ }
+
+ action.data.dedupeConfigurations.forEach(dedupeConf => {
+ newState = newState.map(section => {
+ if (section.id === dedupeConf.id) {
+ const dedupedRows = dedupeConf.dedupeFrom.reduce((rows, dedupeSectionId) => {
+ const dedupeSection = newState.find(s => s.id === dedupeSectionId);
+ const [, newRows] = dedupe.group(dedupeSection.rows, rows);
+ return newRows;
+ }, section.rows);
+ return Object.assign({}, section, {
+ rows: dedupedRows
+ });
+ }
+
+ return section;
+ });
+ });
+ return newState;
+
+ case Actions["actionTypes"].SECTION_UPDATE_CARD:
+ return prevState.map(section => {
+ if (section && section.id === action.data.id && section.rows) {
+ const newRows = section.rows.map(card => {
+ if (card.url === action.data.url) {
+ return Object.assign({}, card, action.data.options);
+ }
+
+ return card;
+ });
+ return Object.assign({}, section, {
+ rows: newRows
+ });
+ }
+
+ return section;
+ });
+
+ case Actions["actionTypes"].PLACES_BOOKMARK_ADDED:
+ if (!action.data) {
+ return prevState;
+ }
+
+ return prevState.map(section => Object.assign({}, section, {
+ rows: section.rows.map(item => {
+ // find the item within the rows that is attempted to be bookmarked
+ if (item.url === action.data.url) {
+ const {
+ bookmarkGuid,
+ bookmarkTitle,
+ dateAdded
+ } = action.data;
+ return Object.assign({}, item, {
+ bookmarkGuid,
+ bookmarkTitle,
+ bookmarkDateCreated: dateAdded,
+ type: "bookmark"
+ });
+ }
+
+ return item;
+ })
+ }));
+
+ case Actions["actionTypes"].PLACES_SAVED_TO_POCKET:
+ if (!action.data) {
+ return prevState;
+ }
+
+ return prevState.map(section => Object.assign({}, section, {
+ rows: section.rows.map(item => {
+ if (item.url === action.data.url) {
+ return Object.assign({}, item, {
+ open_url: action.data.open_url,
+ pocket_id: action.data.pocket_id,
+ title: action.data.title,
+ type: "pocket"
+ });
+ }
+
+ return item;
+ })
+ }));
+
+ case Actions["actionTypes"].PLACES_BOOKMARK_REMOVED:
+ if (!action.data) {
+ return prevState;
+ }
+
+ return prevState.map(section => Object.assign({}, section, {
+ rows: section.rows.map(item => {
+ // find the bookmark within the rows that is attempted to be removed
+ if (item.url === action.data.url) {
+ const newSite = Object.assign({}, item);
+ delete newSite.bookmarkGuid;
+ delete newSite.bookmarkTitle;
+ delete newSite.bookmarkDateCreated;
+
+ if (!newSite.type || newSite.type === "bookmark") {
+ newSite.type = "history";
+ }
+
+ return newSite;
+ }
+
+ return item;
+ })
+ }));
+
+ case Actions["actionTypes"].PLACES_LINK_DELETED:
+ case Actions["actionTypes"].PLACES_LINK_BLOCKED:
+ if (!action.data) {
+ return prevState;
+ }
+
+ return prevState.map(section => Object.assign({}, section, {
+ rows: section.rows.filter(site => site.url !== action.data.url)
+ }));
+
+ case Actions["actionTypes"].DELETE_FROM_POCKET:
+ case Actions["actionTypes"].ARCHIVE_FROM_POCKET:
+ return prevState.map(section => Object.assign({}, section, {
+ rows: section.rows.filter(site => site.pocket_id !== action.data.pocket_id)
+ }));
+
+ case Actions["actionTypes"].SNIPPETS_PREVIEW_MODE:
+ return prevState.map(section => ({ ...section,
+ rows: []
+ }));
+
+ default:
+ return prevState;
+ }
+}
+
+function Snippets(prevState = INITIAL_STATE.Snippets, action) {
+ switch (action.type) {
+ case Actions["actionTypes"].SNIPPETS_DATA:
+ return Object.assign({}, prevState, {
+ initialized: true
+ }, action.data);
+
+ case Actions["actionTypes"].SNIPPET_BLOCKED:
+ return Object.assign({}, prevState, {
+ blockList: prevState.blockList.concat(action.data)
+ });
+
+ case Actions["actionTypes"].SNIPPETS_BLOCKLIST_CLEARED:
+ return Object.assign({}, prevState, {
+ blockList: []
+ });
+
+ case Actions["actionTypes"].SNIPPETS_RESET:
+ return INITIAL_STATE.Snippets;
+
+ default:
+ return prevState;
+ }
+}
+
+function Pocket(prevState = INITIAL_STATE.Pocket, action) {
+ switch (action.type) {
+ case Actions["actionTypes"].POCKET_WAITING_FOR_SPOC:
+ return { ...prevState,
+ waitingForSpoc: action.data
+ };
+
+ case Actions["actionTypes"].POCKET_LOGGED_IN:
+ return { ...prevState,
+ isUserLoggedIn: !!action.data
+ };
+
+ case Actions["actionTypes"].POCKET_CTA:
+ return { ...prevState,
+ pocketCta: {
+ ctaButton: action.data.cta_button,
+ ctaText: action.data.cta_text,
+ ctaUrl: action.data.cta_url,
+ useCta: action.data.use_cta
+ }
+ };
+
+ default:
+ return prevState;
+ }
+}
+
+function Personalization(prevState = INITIAL_STATE.Personalization, action) {
+ switch (action.type) {
+ case Actions["actionTypes"].DISCOVERY_STREAM_PERSONALIZATION_VERSION:
+ return { ...prevState,
+ version: action.data.version
+ };
+
+ case Actions["actionTypes"].DISCOVERY_STREAM_PERSONALIZATION_LAST_UPDATED:
+ return { ...prevState,
+ lastUpdated: action.data.lastUpdated
+ };
+
+ case Actions["actionTypes"].DISCOVERY_STREAM_PERSONALIZATION_INIT:
+ return { ...prevState,
+ initialized: true
+ };
+
+ case Actions["actionTypes"].PREF_CHANGED:
+ if (action.data.name === PREF_PERSONALIZATION_VERSION) {
+ return { ...prevState,
+ version: action.data.value
+ };
+ }
+
+ return prevState;
+
+ default:
+ return prevState;
+ }
+} // eslint-disable-next-line complexity
+
+
+function DiscoveryStream(prevState = INITIAL_STATE.DiscoveryStream, action) {
+ // Return if action data is empty, or spocs or feeds data is not loaded
+ const isNotReady = () => !action.data || !prevState.spocs.loaded || !prevState.feeds.loaded;
+
+ const handlePlacements = handleSites => {
+ const {
+ data,
+ placements
+ } = prevState.spocs;
+ const result = {};
+
+ const forPlacement = placement => {
+ const placementSpocs = data[placement.name];
+
+ if (!placementSpocs || !placementSpocs.items || !placementSpocs.items.length) {
+ return;
+ }
+
+ result[placement.name] = { ...placementSpocs,
+ items: handleSites(placementSpocs.items)
+ };
+ };
+
+ if (!placements || !placements.length) {
+ [{
+ name: "spocs"
+ }].forEach(forPlacement);
+ } else {
+ placements.forEach(forPlacement);
+ }
+
+ return result;
+ };
+
+ const nextState = handleSites => ({ ...prevState,
+ spocs: { ...prevState.spocs,
+ data: handlePlacements(handleSites)
+ },
+ feeds: { ...prevState.feeds,
+ data: Object.keys(prevState.feeds.data).reduce((accumulator, feed_url) => {
+ accumulator[feed_url] = {
+ data: { ...prevState.feeds.data[feed_url].data,
+ recommendations: handleSites(prevState.feeds.data[feed_url].data.recommendations)
+ }
+ };
+ return accumulator;
+ }, {})
+ }
+ });
+
+ switch (action.type) {
+ case Actions["actionTypes"].DISCOVERY_STREAM_CONFIG_CHANGE: // Fall through to a separate action is so it doesn't trigger a listener update on init
+
+ case Actions["actionTypes"].DISCOVERY_STREAM_CONFIG_SETUP:
+ return { ...prevState,
+ config: action.data || {}
+ };
+
+ case Actions["actionTypes"].DISCOVERY_STREAM_LAYOUT_UPDATE:
+ return { ...prevState,
+ lastUpdated: action.data.lastUpdated || null,
+ layout: action.data.layout || []
+ };
+
+ case Actions["actionTypes"].DISCOVERY_STREAM_COLLECTION_DISMISSIBLE_TOGGLE:
+ return { ...prevState,
+ isCollectionDismissible: action.data.value
+ };
+
+ case Actions["actionTypes"].HIDE_PRIVACY_INFO:
+ return { ...prevState,
+ isPrivacyInfoModalVisible: false
+ };
+
+ case Actions["actionTypes"].SHOW_PRIVACY_INFO:
+ return { ...prevState,
+ isPrivacyInfoModalVisible: true
+ };
+
+ case Actions["actionTypes"].DISCOVERY_STREAM_LAYOUT_RESET:
+ return { ...INITIAL_STATE.DiscoveryStream,
+ config: prevState.config
+ };
+
+ case Actions["actionTypes"].DISCOVERY_STREAM_FEEDS_UPDATE:
+ return { ...prevState,
+ feeds: { ...prevState.feeds,
+ loaded: true
+ }
+ };
+
+ case Actions["actionTypes"].DISCOVERY_STREAM_FEED_UPDATE:
+ const newData = {};
+ newData[action.data.url] = action.data.feed;
+ return { ...prevState,
+ feeds: { ...prevState.feeds,
+ data: { ...prevState.feeds.data,
+ ...newData
+ }
+ }
+ };
+
+ case Actions["actionTypes"].DISCOVERY_STREAM_SPOCS_CAPS:
+ return { ...prevState,
+ spocs: { ...prevState.spocs,
+ frequency_caps: [...prevState.spocs.frequency_caps, ...action.data]
+ }
+ };
+
+ case Actions["actionTypes"].DISCOVERY_STREAM_SPOCS_ENDPOINT:
+ return { ...prevState,
+ spocs: { ...INITIAL_STATE.DiscoveryStream.spocs,
+ spocs_endpoint: action.data.url || INITIAL_STATE.DiscoveryStream.spocs.spocs_endpoint
+ }
+ };
+
+ case Actions["actionTypes"].DISCOVERY_STREAM_SPOCS_PLACEMENTS:
+ return { ...prevState,
+ spocs: { ...prevState.spocs,
+ placements: action.data.placements || INITIAL_STATE.DiscoveryStream.spocs.placements
+ }
+ };
+
+ case Actions["actionTypes"].DISCOVERY_STREAM_SPOCS_UPDATE:
+ if (action.data) {
+ return { ...prevState,
+ spocs: { ...prevState.spocs,
+ lastUpdated: action.data.lastUpdated,
+ data: action.data.spocs,
+ loaded: true
+ }
+ };
+ }
+
+ return prevState;
+
+ case Actions["actionTypes"].DISCOVERY_STREAM_SPOC_BLOCKED:
+ return { ...prevState,
+ spocs: { ...prevState.spocs,
+ blocked: [...prevState.spocs.blocked, action.data.url]
+ }
+ };
+
+ case Actions["actionTypes"].DISCOVERY_STREAM_LINK_BLOCKED:
+ return isNotReady() ? prevState : nextState(items => items.filter(item => item.url !== action.data.url));
+
+ case Actions["actionTypes"].PLACES_SAVED_TO_POCKET:
+ const addPocketInfo = item => {
+ if (item.url === action.data.url) {
+ return Object.assign({}, item, {
+ open_url: action.data.open_url,
+ pocket_id: action.data.pocket_id,
+ context_type: "pocket"
+ });
+ }
+
+ return item;
+ };
+
+ return isNotReady() ? prevState : nextState(items => items.map(addPocketInfo));
+
+ case Actions["actionTypes"].DELETE_FROM_POCKET:
+ case Actions["actionTypes"].ARCHIVE_FROM_POCKET:
+ return isNotReady() ? prevState : nextState(items => items.filter(item => item.pocket_id !== action.data.pocket_id));
+
+ case Actions["actionTypes"].PLACES_BOOKMARK_ADDED:
+ const updateBookmarkInfo = item => {
+ if (item.url === action.data.url) {
+ const {
+ bookmarkGuid,
+ bookmarkTitle,
+ dateAdded
+ } = action.data;
+ return Object.assign({}, item, {
+ bookmarkGuid,
+ bookmarkTitle,
+ bookmarkDateCreated: dateAdded,
+ context_type: "bookmark"
+ });
+ }
+
+ return item;
+ };
+
+ return isNotReady() ? prevState : nextState(items => items.map(updateBookmarkInfo));
+
+ case Actions["actionTypes"].PLACES_BOOKMARK_REMOVED:
+ const removeBookmarkInfo = item => {
+ if (item.url === action.data.url) {
+ const newSite = Object.assign({}, item);
+ delete newSite.bookmarkGuid;
+ delete newSite.bookmarkTitle;
+ delete newSite.bookmarkDateCreated;
+
+ if (!newSite.context_type || newSite.context_type === "bookmark") {
+ newSite.context_type = "removedBookmark";
+ }
+
+ return newSite;
+ }
+
+ return item;
+ };
+
+ return isNotReady() ? prevState : nextState(items => items.map(removeBookmarkInfo));
+
+ case Actions["actionTypes"].PREF_CHANGED:
+ if (action.data.name === PREF_COLLECTION_DISMISSIBLE) {
+ return { ...prevState,
+ isCollectionDismissible: action.data.value
+ };
+ }
+
+ return prevState;
+
+ default:
+ return prevState;
+ }
+}
+
+function Search(prevState = INITIAL_STATE.Search, action) {
+ switch (action.type) {
+ case Actions["actionTypes"].HIDE_SEARCH:
+ return Object.assign({ ...prevState,
+ hide: true
+ });
+
+ case Actions["actionTypes"].FAKE_FOCUS_SEARCH:
+ return Object.assign({ ...prevState,
+ fakeFocus: true
+ });
+
+ case Actions["actionTypes"].SHOW_SEARCH:
+ return Object.assign({ ...prevState,
+ hide: false,
+ fakeFocus: false
+ });
+
+ default:
+ return prevState;
+ }
+}
+
+var reducers = {
+ TopSites,
+ App,
+ ASRouter,
+ Snippets,
+ Prefs,
+ Dialog,
+ Sections,
+ Pocket,
+ Personalization,
+ DiscoveryStream,
+ Search
+};
+
+/***/ }),
+/* 73 */
+/***/ (function(module, __webpack_exports__, __webpack_require__) {
+
+"use strict";
+__webpack_require__.r(__webpack_exports__);
+
+// EXTERNAL MODULE: ./common/Actions.jsm
+var Actions = __webpack_require__(1);
+
+// EXTERNAL MODULE: ./content-src/components/A11yLinkButton/A11yLinkButton.jsx
+var A11yLinkButton = __webpack_require__(36);
+
+// EXTERNAL MODULE: external "React"
+var external_React_ = __webpack_require__(8);
+var external_React_default = /*#__PURE__*/__webpack_require__.n(external_React_);
+
+// EXTERNAL MODULE: ./content-src/components/TopSites/TopSitesConstants.js
+var TopSitesConstants = __webpack_require__(56);
+
+// CONCATENATED MODULE: ./content-src/components/TopSites/TopSiteFormInput.jsx
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+class TopSiteFormInput_TopSiteFormInput extends external_React_default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ this.state = {
+ validationError: this.props.validationError
+ };
+ this.onChange = this.onChange.bind(this);
+ this.onMount = this.onMount.bind(this);
+ this.onClearIconPress = this.onClearIconPress.bind(this);
+ }
+
+ componentWillReceiveProps(nextProps) {
+ if (nextProps.shouldFocus && !this.props.shouldFocus) {
+ this.input.focus();
+ }
+
+ if (nextProps.validationError && !this.props.validationError) {
+ this.setState({
+ validationError: true
+ });
+ } // If the component is in an error state but the value was cleared by the parent
+
+
+ if (this.state.validationError && !nextProps.value) {
+ this.setState({
+ validationError: false
+ });
+ }
+ }
+
+ onClearIconPress(event) {
+ // If there is input in the URL or custom image URL fields,
+ // and we hit 'enter' while tabbed over the clear icon,
+ // we should execute the function to clear the field.
+ if (event.key === "Enter") {
+ this.props.onClear();
+ }
+ }
+
+ onChange(ev) {
+ if (this.state.validationError) {
+ this.setState({
+ validationError: false
+ });
+ }
+
+ this.props.onChange(ev);
+ }
+
+ onMount(input) {
+ this.input = input;
+ }
+
+ renderLoadingOrCloseButton() {
+ const showClearButton = this.props.value && this.props.onClear;
+
+ if (this.props.loading) {
+ return external_React_default.a.createElement("div", {
+ className: "loading-container"
+ }, external_React_default.a.createElement("div", {
+ className: "loading-animation"
+ }));
+ } else if (showClearButton) {
+ return external_React_default.a.createElement("button", {
+ type: "button",
+ className: "icon icon-clear-input icon-button-style",
+ onClick: this.props.onClear,
+ onKeyPress: this.onClearIconPress
+ });
+ }
+
+ return null;
+ }
+
+ render() {
+ const {
+ typeUrl
+ } = this.props;
+ const {
+ validationError
+ } = this.state;
+ return external_React_default.a.createElement("label", null, external_React_default.a.createElement("span", {
+ "data-l10n-id": this.props.titleId
+ }), external_React_default.a.createElement("div", {
+ className: `field ${typeUrl ? "url" : ""}${validationError ? " invalid" : ""}`
+ }, external_React_default.a.createElement("input", {
+ type: "text",
+ value: this.props.value,
+ ref: this.onMount,
+ onChange: this.onChange,
+ "data-l10n-id": this.props.placeholderId // Set focus on error if the url field is valid or when the input is first rendered and is empty
+ // eslint-disable-next-line jsx-a11y/no-autofocus
+ ,
+ autoFocus: this.props.shouldFocus,
+ disabled: this.props.loading
+ }), this.renderLoadingOrCloseButton(), validationError && external_React_default.a.createElement("aside", {
+ className: "error-tooltip",
+ "data-l10n-id": this.props.errorMessageId
+ })));
+ }
+
+}
+TopSiteFormInput_TopSiteFormInput.defaultProps = {
+ showClearButton: false,
+ value: "",
+ validationError: false
+};
+// EXTERNAL MODULE: ./content-src/components/TopSites/TopSite.jsx
+var TopSite = __webpack_require__(58);
+
+// CONCATENATED MODULE: ./content-src/components/TopSites/TopSiteForm.jsx
+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TopSiteForm", function() { return TopSiteForm_TopSiteForm; });
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+
+
+
+
+class TopSiteForm_TopSiteForm extends external_React_default.a.PureComponent {
+ constructor(props) {
+ super(props);
+ const {
+ site
+ } = props;
+ this.state = {
+ label: site ? site.label || site.hostname : "",
+ url: site ? site.url : "",
+ validationError: false,
+ customScreenshotUrl: site ? site.customScreenshotURL : "",
+ showCustomScreenshotForm: site ? site.customScreenshotURL : false
+ };
+ this.onClearScreenshotInput = this.onClearScreenshotInput.bind(this);
+ this.onLabelChange = this.onLabelChange.bind(this);
+ this.onUrlChange = this.onUrlChange.bind(this);
+ this.onCancelButtonClick = this.onCancelButtonClick.bind(this);
+ this.onClearUrlClick = this.onClearUrlClick.bind(this);
+ this.onDoneButtonClick = this.onDoneButtonClick.bind(this);
+ this.onCustomScreenshotUrlChange = this.onCustomScreenshotUrlChange.bind(this);
+ this.onPreviewButtonClick = this.onPreviewButtonClick.bind(this);
+ this.onEnableScreenshotUrlForm = this.onEnableScreenshotUrlForm.bind(this);
+ this.validateUrl = this.validateUrl.bind(this);
+ }
+
+ onLabelChange(event) {
+ this.setState({
+ label: event.target.value
+ });
+ }
+
+ onUrlChange(event) {
+ this.setState({
+ url: event.target.value,
+ validationError: false
+ });
+ }
+
+ onClearUrlClick() {
+ this.setState({
+ url: "",
+ validationError: false
+ });
+ }
+
+ onEnableScreenshotUrlForm() {
+ this.setState({
+ showCustomScreenshotForm: true
+ });
+ }
+
+ _updateCustomScreenshotInput(customScreenshotUrl) {
+ this.setState({
+ customScreenshotUrl,
+ validationError: false
+ });
+ this.props.dispatch({
+ type: Actions["actionTypes"].PREVIEW_REQUEST_CANCEL
+ });
+ }
+
+ onCustomScreenshotUrlChange(event) {
+ this._updateCustomScreenshotInput(event.target.value);
+ }
+
+ onClearScreenshotInput() {
+ this._updateCustomScreenshotInput("");
+ }
+
+ onCancelButtonClick(ev) {
+ ev.preventDefault();
+ this.props.onClose();
+ }
+
+ onDoneButtonClick(ev) {
+ ev.preventDefault();
+
+ if (this.validateForm()) {
+ const site = {
+ url: this.cleanUrl(this.state.url)
+ };
+ const {
+ index
+ } = this.props;
+
+ if (this.state.label !== "") {
+ site.label = this.state.label;
+ }
+
+ if (this.state.customScreenshotUrl) {
+ site.customScreenshotURL = this.cleanUrl(this.state.customScreenshotUrl);
+ } else if (this.props.site && this.props.site.customScreenshotURL) {
+ // Used to flag that previously cached screenshot should be removed
+ site.customScreenshotURL = null;
+ }
+
+ this.props.dispatch(Actions["actionCreators"].AlsoToMain({
+ type: Actions["actionTypes"].TOP_SITES_PIN,
+ data: {
+ site,
+ index
+ }
+ }));
+ this.props.dispatch(Actions["actionCreators"].UserEvent({
+ source: TopSitesConstants["TOP_SITES_SOURCE"],
+ event: "TOP_SITES_EDIT",
+ action_position: index
+ }));
+ this.props.onClose();
+ }
+ }
+
+ onPreviewButtonClick(event) {
+ event.preventDefault();
+
+ if (this.validateForm()) {
+ this.props.dispatch(Actions["actionCreators"].AlsoToMain({
+ type: Actions["actionTypes"].PREVIEW_REQUEST,
+ data: {
+ url: this.cleanUrl(this.state.customScreenshotUrl)
+ }
+ }));
+ this.props.dispatch(Actions["actionCreators"].UserEvent({
+ source: TopSitesConstants["TOP_SITES_SOURCE"],
+ event: "PREVIEW_REQUEST"
+ }));
+ }
+ }
+
+ cleanUrl(url) {
+ // If we are missing a protocol, prepend http://
+ if (!url.startsWith("http:") && !url.startsWith("https:")) {
+ return `http://${url}`;
+ }
+
+ return url;
+ }
+
+ _tryParseUrl(url) {
+ try {
+ return new URL(url);
+ } catch (e) {
+ return null;
+ }
+ }
+
+ validateUrl(url) {
+ const validProtocols = ["http:", "https:"];
+
+ const urlObj = this._tryParseUrl(url) || this._tryParseUrl(this.cleanUrl(url));
+
+ return urlObj && validProtocols.includes(urlObj.protocol);
+ }
+
+ validateCustomScreenshotUrl() {
+ const {
+ customScreenshotUrl
+ } = this.state;
+ return !customScreenshotUrl || this.validateUrl(customScreenshotUrl);
+ }
+
+ validateForm() {
+ const validate = this.validateUrl(this.state.url) && this.validateCustomScreenshotUrl();
+
+ if (!validate) {
+ this.setState({
+ validationError: true
+ });
+ }
+
+ return validate;
+ }
+
+ _renderCustomScreenshotInput() {
+ const {
+ customScreenshotUrl
+ } = this.state;
+ const requestFailed = this.props.previewResponse === "";
+ const validationError = this.state.validationError && !this.validateCustomScreenshotUrl() || requestFailed; // Set focus on error if the url field is valid or when the input is first rendered and is empty
+
+ const shouldFocus = validationError && this.validateUrl(this.state.url) || !customScreenshotUrl;
+ const isLoading = this.props.previewResponse === null && customScreenshotUrl && this.props.previewUrl === this.cleanUrl(customScreenshotUrl);
+
+ if (!this.state.showCustomScreenshotForm) {
+ return external_React_default.a.createElement(A11yLinkButton["A11yLinkButton"], {
+ onClick: this.onEnableScreenshotUrlForm,
+ className: "enable-custom-image-input",
+ "data-l10n-id": "newtab-topsites-use-image-link"
+ });
+ }
+
+ return external_React_default.a.createElement("div", {
+ className: "custom-image-input-container"
+ }, external_React_default.a.createElement(TopSiteFormInput_TopSiteFormInput, {
+ errorMessageId: requestFailed ? "newtab-topsites-image-validation" : "newtab-topsites-url-validation",
+ loading: isLoading,
+ onChange: this.onCustomScreenshotUrlChange,
+ onClear: this.onClearScreenshotInput,
+ shouldFocus: shouldFocus,
+ typeUrl: true,
+ value: customScreenshotUrl,
+ validationError: validationError,
+ titleId: "newtab-topsites-image-url-label",
+ placeholderId: "newtab-topsites-url-input"
+ }));
+ }
+
+ render() {
+ const {
+ customScreenshotUrl
+ } = this.state;
+ const requestFailed = this.props.previewResponse === ""; // For UI purposes, editing without an existing link is "add"
+
+ const showAsAdd = !this.props.site;
+ const previous = this.props.site && this.props.site.customScreenshotURL || "";
+ const changed = customScreenshotUrl && this.cleanUrl(customScreenshotUrl) !== previous; // Preview mode if changes were made to the custom screenshot URL and no preview was received yet
+ // or the request failed
+
+ const previewMode = changed && !this.props.previewResponse;
+ const previewLink = Object.assign({}, this.props.site);
+
+ if (this.props.previewResponse) {
+ previewLink.screenshot = this.props.previewResponse;
+ previewLink.customScreenshotURL = this.props.previewUrl;
+ } // Handles the form submit so an enter press performs the correct action
+
+
+ const onSubmit = previewMode ? this.onPreviewButtonClick : this.onDoneButtonClick; // When the newNewtabExperience is enabled by default, use only shortcut ids.
+
+ const addTopsitesHeaderL10nId = this.props.newNewtabExperienceEnabled || this.props.customizationMenuEnabled ? "newtab-topsites-add-shortcut-header" : "newtab-topsites-add-topsites-header";
+ const editTopsitesHeaderL10nId = this.props.newNewtabExperienceEnabled || this.props.customizationMenuEnabled ? "newtab-topsites-edit-shortcut-header" : "newtab-topsites-edit-topsites-header";
+ return external_React_default.a.createElement("form", {
+ className: "topsite-form",
+ onSubmit: onSubmit
+ }, external_React_default.a.createElement("div", {
+ className: "form-input-container"
+ }, external_React_default.a.createElement("h3", {
+ className: "section-title grey-title",
+ "data-l10n-id": showAsAdd ? addTopsitesHeaderL10nId : editTopsitesHeaderL10nId
+ }), external_React_default.a.createElement("div", {
+ className: "fields-and-preview"
+ }, external_React_default.a.createElement("div", {
+ className: "form-wrapper"
+ }, external_React_default.a.createElement(TopSiteFormInput_TopSiteFormInput, {
+ onChange: this.onLabelChange,
+ value: this.state.label,
+ titleId: "newtab-topsites-title-label",
+ placeholderId: "newtab-topsites-title-input"
+ }), external_React_default.a.createElement(TopSiteFormInput_TopSiteFormInput, {
+ onChange: this.onUrlChange,
+ shouldFocus: this.state.validationError && !this.validateUrl(this.state.url),
+ value: this.state.url,
+ onClear: this.onClearUrlClick,
+ validationError: this.state.validationError && !this.validateUrl(this.state.url),
+ titleId: "newtab-topsites-url-label",
+ typeUrl: true,
+ placeholderId: "newtab-topsites-url-input",
+ errorMessageId: "newtab-topsites-url-validation"
+ }), this._renderCustomScreenshotInput()), external_React_default.a.createElement(TopSite["TopSiteLink"], {
+ link: previewLink,
+ defaultStyle: requestFailed,
+ title: this.state.label,
+ newNewtabExperienceEnabled: this.props.newNewtabExperienceEnabled
+ }))), external_React_default.a.createElement("section", {
+ className: "actions"
+ }, external_React_default.a.createElement("button", {
+ className: "cancel",
+ type: "button",
+ onClick: this.onCancelButtonClick,
+ "data-l10n-id": "newtab-topsites-cancel-button"
+ }), previewMode ? external_React_default.a.createElement("button", {
+ className: "done preview",
+ type: "submit",
+ "data-l10n-id": "newtab-topsites-preview-button"
+ }) : external_React_default.a.createElement("button", {
+ className: "done",
+ type: "submit",
+ "data-l10n-id": showAsAdd ? "newtab-topsites-add-button" : "newtab-topsites-save-button"
+ })));
+ }
+
+}
+TopSiteForm_TopSiteForm.defaultProps = {
+ site: null,
+ index: -1
+};
+
+/***/ })
+/******/ ]); \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/cfr_enhancer_youtube.png b/browser/components/newtab/data/content/assets/cfr_enhancer_youtube.png
new file mode 100644
index 0000000000..bb0f23510c
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/cfr_enhancer_youtube.png
Binary files differ
diff --git a/browser/components/newtab/data/content/assets/cfr_fb_container.png b/browser/components/newtab/data/content/assets/cfr_fb_container.png
new file mode 100644
index 0000000000..c553883537
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/cfr_fb_container.png
Binary files differ
diff --git a/browser/components/newtab/data/content/assets/cfr_google_translate.png b/browser/components/newtab/data/content/assets/cfr_google_translate.png
new file mode 100644
index 0000000000..c00f27fc3f
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/cfr_google_translate.png
Binary files differ
diff --git a/browser/components/newtab/data/content/assets/cfr_pinnedtab_animated.png b/browser/components/newtab/data/content/assets/cfr_pinnedtab_animated.png
new file mode 100644
index 0000000000..3ef7d3c236
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/cfr_pinnedtab_animated.png
Binary files differ
diff --git a/browser/components/newtab/data/content/assets/cfr_pinnedtab_animated@2x.png b/browser/components/newtab/data/content/assets/cfr_pinnedtab_animated@2x.png
new file mode 100644
index 0000000000..905b29e757
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/cfr_pinnedtab_animated@2x.png
Binary files differ
diff --git a/browser/components/newtab/data/content/assets/cfr_pinnedtab_animated_darktheme.png b/browser/components/newtab/data/content/assets/cfr_pinnedtab_animated_darktheme.png
new file mode 100644
index 0000000000..7031762d07
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/cfr_pinnedtab_animated_darktheme.png
Binary files differ
diff --git a/browser/components/newtab/data/content/assets/cfr_pinnedtab_animated_darktheme@2x.png b/browser/components/newtab/data/content/assets/cfr_pinnedtab_animated_darktheme@2x.png
new file mode 100644
index 0000000000..219f5075d0
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/cfr_pinnedtab_animated_darktheme@2x.png
Binary files differ
diff --git a/browser/components/newtab/data/content/assets/cfr_pinnedtab_static.png b/browser/components/newtab/data/content/assets/cfr_pinnedtab_static.png
new file mode 100644
index 0000000000..e4812d8d8d
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/cfr_pinnedtab_static.png
Binary files differ
diff --git a/browser/components/newtab/data/content/assets/cfr_pinnedtab_static@2x.png b/browser/components/newtab/data/content/assets/cfr_pinnedtab_static@2x.png
new file mode 100644
index 0000000000..ac9e2ca845
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/cfr_pinnedtab_static@2x.png
Binary files differ
diff --git a/browser/components/newtab/data/content/assets/cfr_reddit_enhancement.png b/browser/components/newtab/data/content/assets/cfr_reddit_enhancement.png
new file mode 100644
index 0000000000..d96ec82172
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/cfr_reddit_enhancement.png
Binary files differ
diff --git a/browser/components/newtab/data/content/assets/cfr_wiki_search.png b/browser/components/newtab/data/content/assets/cfr_wiki_search.png
new file mode 100644
index 0000000000..74d969aa47
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/cfr_wiki_search.png
Binary files differ
diff --git a/browser/components/newtab/data/content/assets/firefox-protections.svg b/browser/components/newtab/data/content/assets/firefox-protections.svg
new file mode 100644
index 0000000000..e6893a3e4d
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/firefox-protections.svg
@@ -0,0 +1,4 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+<svg height="313" width="699" xmlns="http://www.w3.org/2000/svg"><filter id="e" height="137.5%" width="137.5%" x="-18.8%" y="-15.6%"><feMorphology in="SourceAlpha" operator="dilate" radius="1" result="shadowSpreadOuter1"/><feOffset dy="1" in="shadowSpreadOuter1" result="shadowOffsetOuter1"/><feGaussianBlur in="shadowOffsetOuter1" result="shadowBlurOuter1" stdDeviation="1.5"/><feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"/><feColorMatrix in="shadowBlurOuter1" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.05 0"/></filter><linearGradient id="g" x1="13.265%" x2="86.735%" y1="0%" y2="100%"><stop offset="0" stop-color="#9059ff"/><stop offset="1" stop-color="#0250bb"/></linearGradient><mask id="a" fill="#fff"><path d="M0 0h697v311H0z" fill-rule="evenodd"/></mask><mask id="b" fill="#fff"><path d="M15.7 7.3l-7-7c-.4-.4-1-.4-1.4 0l-7 7c-.4.4-.4 1 0 1.4s1 .4 1.4 0l.3-.3V13c0 1.7 1.3 3 3 3h6c1.7 0 3-1.3 3-3V8.4l.3.3c.2.2.4.3.7.3s.5-.1.7-.3c.4-.4.4-1 0-1.4zM8 11.5c0-.3.2-.5.5-.5s.5.2.5.5-.2.5-.5.5-.5-.2-.5-.5zm4 1.5c0 .6-.4 1-1 1h-1V9c0-.6-.4-1-1-1H7c-.6 0-1 .4-1 1v5H5c-.6 0-1-.4-1-1V6.4l4-4 4 4z" fill-rule="evenodd"/></mask><mask id="c" fill="#fff"><path d="M14.501 1a1 1 0 00-1 1v2.418a6.995 6.995 0 10-6 10.582 6.954 6.954 0 004.95-2.05 1 1 0 00-1.414-1.414A5.019 5.019 0 1112.05 6H9.501a1 1 0 100 2h5a1 1 0 001-1V2a1 1 0 00-1-1z" fill-rule="evenodd"/></mask><mask id="d" fill="#fff"><path d="M15.707 7.293l-6-6a1 1 0 00-1.414 1.414L12.586 7H1a1 1 0 100 2h11.586l-4.293 4.293a1 1 0 101.414 1.414l6-6a1 1 0 000-1.414z" fill-rule="evenodd"/></mask><mask id="f" fill="#fff"><path d="M15 7H3.414l4.293-4.293a1 1 0 00-1.414-1.414l-6 6a1 1 0 000 1.414l6 6a1 1 0 001.414-1.414L3.414 9H15a1 1 0 000-2z" fill-rule="evenodd"/></mask><g fill="none" fill-rule="evenodd"><path d="M698.5.5H.5v312h698z" stroke="#e8e8e8"/><g mask="url(#a)" transform="translate(1 1)"><path d="M697.5-.5H-.5v312h698z" fill="#cdcdcd" stroke="#e8e8e8"/><path d="M21 0h213.842v33H697v41H0V33h21z" fill="#f2f2f2"/><path d="M460 9h16v16h-16z" fill="#f2f2f2"/><path d="M484 14h121v8H484z" fill="#fff" fill-opacity=".4"/><path d="M676 9h16v16h-16z" fill="#f2f2f2"/><path d="M650.061 17l3.47-3.47a.75.75 0 00-1.061-1.06L649 15.939l-3.47-3.469a.75.75 0 10-1.06 1.06l3.469 3.47-3.469 3.47a.75.75 0 101.06 1.06l3.47-3.469 3.47 3.47a.75.75 0 001.06-1.061z" fill="#f9f9fa" fill-opacity=".8" opacity=".6"/><path d="M665 0v33" opacity=".2" stroke="#000" stroke-opacity=".5"/><path d="M245 9h16v16h-16z" fill="#f2f2f2"/><path d="M268 14h121v8H268z" fill="#fff" fill-opacity=".4"/><path d="M434.061 17l3.47-3.47a.75.75 0 00-1.061-1.06L433 15.939l-3.47-3.469a.75.75 0 10-1.06 1.06l3.469 3.47-3.469 3.47a.75.75 0 101.06 1.06l3.47-3.469 3.47 3.47a.75.75 0 001.06-1.061z" fill="#f9f9fa" fill-opacity=".8" opacity=".6"/><path d="M449 0v33" opacity=".2" stroke="#000" stroke-opacity=".5"/><path d="M31 9h16v16H31z" fill="#d8d8d8"/><path d="M54 14h121v8H54z" fill="#a6a6a6" fill-opacity=".4"/><path d="M21 0h214v3H21z" fill="#fff" fill-opacity=".8"/><path d="M220.061 17l3.47-3.47a.75.75 0 00-1.061-1.06L219 15.939l-3.47-3.469a.75.75 0 10-1.06 1.06l3.469 3.47-3.469 3.47a.75.75 0 101.06 1.06l3.47-3.469 3.47 3.47a.75.75 0 001.06-1.061z" fill="#0c0c0d" fill-opacity=".8" opacity=".4"/><g opacity=".908"><path d="M0 74h697v297H0z" fill="#fff"/><path d="M39 102h150v45H39zm173 70h150v105H212zm170 0h150v105H382zm165 0h150v105H547z" fill="#d8d8d8" fill-opacity=".5"/><path d="M212.5 141.5h485" stroke="#d8d8d8" stroke-linecap="square" stroke-opacity=".5" stroke-width="3"/><path d="M39 172h150v10H39zm173-70h80v14h-80zm100 0h80v14h-80zm100 0h80v14h-80zm100 0h80v14h-80zm100 0h80v14h-80zM39 190h150v10H39zm0 103h150v10H39zm0-85h150v10H39zm0 18h150v10H39z" fill="#d8d8d8" fill-opacity=".5"/></g><g opacity=".25"><path d="M110 45h16v16h-16z"/><g fill="#0c0c0d" fill-opacity=".8" mask="url(#b)" transform="translate(110 45)"><path d="M0 0h16v16H0z"/></g><path d="M78 45h16v16H78z"/><g fill="#0c0c0d" fill-opacity=".8" mask="url(#c)" transform="translate(78 45)"><path d="M0 0h16v16H0z"/></g><path d="M46 45h16v16H46z"/><g fill="#0c0c0d" fill-opacity=".8" mask="url(#d)" transform="translate(46 45)"><path d="M0 0h16v16H0z"/></g><g transform="translate(4 37)"><circle cx="16" cy="16" fill="#000" filter="url(#e)" r="16"/><circle cx="16" cy="16" fill="#fff" r="16.5" stroke="#09060d" stroke-opacity=".15"/><path d="M8 8h16v16H8z"/><g fill="#0c0c0d" fill-opacity=".8" mask="url(#f)" transform="translate(8 8)"><path d="M0 0h16v16H0z"/></g></g></g><path d="M932 38.5H175a1.502 1.502 0 00-1.5 1.5v25a1.502 1.502 0 001.5 1.5h757c.414 0 .79-.168 1.06-.44.272-.27.44-.646.44-1.06V40c0-.414-.168-.79-.44-1.06a1.495 1.495 0 00-1.06-.44z" fill="#fff" opacity=".587" stroke="#cdcdcd"/><path d="M231 49h466v8H231z" fill="#a6a6a6" fill-opacity=".2"/><path d="M202.5 44.5v16" opacity=".4" stroke="#979797" stroke-linecap="square"/><path d="M220.5 51.484h-.5V49.5a4 4 0 10-8 0v1.984h-.5a1.5 1.5 0 00-1.5 1.5V58a1.5 1.5 0 001.5 1.5h9A1.5 1.5 0 00222 58v-5.016a1.5 1.5 0 00-1.5-1.5zM214 49.5a2 2 0 114 0v1.984h-4z" fill="#0c0c0d" fill-opacity=".8" opacity=".2"/><path d="M.5 73.5H697" opacity=".247" stroke="#979797" stroke-linecap="square"/></g><path d="M189 46l4.642.78A1.63 1.63 0 01195 48.392c0 1.06 0 2.97-.088 3.838-.227 2.47-.69 3.822-1.83 5.362a6.235 6.235 0 01-4 2.408H189l-.087-.005a6.235 6.235 0 01-4-2.408c-1.14-1.54-1.603-2.892-1.83-5.362-.07-.728-.081-2.207-.083-3.289v-.544a1.63 1.63 0 011.358-1.612zm0 1.5l-.031.004v10.988l.031.008a4.813 4.813 0 002.726-1.612l.156-.196c.978-1.317 1.338-2.392 1.54-4.605.055-.587.078-1.93.078-3.7a.138.138 0 00-.108-.137z" fill="url(#g)"/></g></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/glyph-add-16.svg b/browser/components/newtab/data/content/assets/glyph-add-16.svg
new file mode 100644
index 0000000000..b2e1df50ed
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/glyph-add-16.svg
@@ -0,0 +1,4 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill="context-fill" d="M14 7H9V2a1 1 0 0 0-2 0v5H2a1 1 0 1 0 0 2h5v5a1 1 0 0 0 2 0V9h5a1 1 0 0 0 0-2z"/></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/glyph-arrow.svg b/browser/components/newtab/data/content/assets/glyph-arrow.svg
new file mode 100644
index 0000000000..18ada8d025
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/glyph-arrow.svg
@@ -0,0 +1,4 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+<svg width="5" height="24" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" clip-rule="evenodd" d="M.248 8.204a.77.77 0 0 1 1.088.044L4.8 12l-3.464 3.752a.77.77 0 1 1-1.132-1.045L2.704 12l-2.5-2.707a.77.77 0 0 1 .044-1.089z" fill="context-fill"/></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/glyph-arrowhead-down-12.svg b/browser/components/newtab/data/content/assets/glyph-arrowhead-down-12.svg
new file mode 100644
index 0000000000..0362e0c3c4
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/glyph-arrowhead-down-12.svg
@@ -0,0 +1,4 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 12 12"><path fill="context-fill" d="M6 9a1 1 0 0 1-.707-.293l-3-3a1 1 0 0 1 1.414-1.414L6 6.586l2.293-2.293a1 1 0 0 1 1.414 1.414l-3 3A1 1 0 0 1 6 9z"/></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/glyph-arrowhead-down-16.svg b/browser/components/newtab/data/content/assets/glyph-arrowhead-down-16.svg
new file mode 100644
index 0000000000..56c101a23f
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/glyph-arrowhead-down-16.svg
@@ -0,0 +1,4 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill="context-fill" d="M8 12a1 1 0 0 1-.707-.293l-5-5a1 1 0 0 1 1.414-1.414L8 9.586l4.293-4.293a1 1 0 0 1 1.414 1.414l-5 5A1 1 0 0 1 8 12z"/></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/glyph-cancel-16.svg b/browser/components/newtab/data/content/assets/glyph-cancel-16.svg
new file mode 100644
index 0000000000..a8308d3514
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/glyph-cancel-16.svg
@@ -0,0 +1,4 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill="context-fill" fill-rule="evenodd" d="M6.586 8l-2.293 2.293a1 1 0 0 0 1.414 1.414L8 9.414l2.293 2.293a1 1 0 0 0 1.414-1.414L9.414 8l2.293-2.293a1 1 0 1 0-1.414-1.414L8 6.586 5.707 4.293a1 1 0 0 0-1.414 1.414L6.586 8zM8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0z"/></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/glyph-caret-right.svg b/browser/components/newtab/data/content/assets/glyph-caret-right.svg
new file mode 100644
index 0000000000..1a966815ce
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/glyph-caret-right.svg
@@ -0,0 +1,4 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+<svg width="5" height="24" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" clip-rule="evenodd" d="M.248 8.204a.77.77 0 0 1 1.088.044L4.8 12l-3.464 3.752a.77.77 0 1 1-1.132-1.045L2.704 12l-2.5-2.707a.77.77 0 0 1 .044-1.089z" fill="#0C0C0D"/></svg>
diff --git a/browser/components/newtab/data/content/assets/glyph-cfr-feature-16.svg b/browser/components/newtab/data/content/assets/glyph-cfr-feature-16.svg
new file mode 100644
index 0000000000..871b48ca45
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/glyph-cfr-feature-16.svg
@@ -0,0 +1,4 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill="context-fill" fill-opacity="context-fill-opacity" d="M10 13H6a1 1 0 0 1-1-1 4.552 4.552 0 0 0-1.1-1.87A7.017 7.017 0 0 1 2 6a6 6 0 1 1 12 0 7.017 7.017 0 0 1-1.9 4.13A4.552 4.552 0 0 0 11 12a1 1 0 0 1-1 1zm-3.188-2h2.376a8.489 8.489 0 0 1 1.328-2.093A5.415 5.415 0 0 0 12 6a4.054 4.054 0 0 0-4-4 4.054 4.054 0 0 0-4 4 5.415 5.415 0 0 0 1.484 2.907c.543.629.99 1.334 1.328 2.093zM10 16H6a1 1 0 0 1 0-2h4a1 1 0 0 1 0 2z"/></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/glyph-delete-16.svg b/browser/components/newtab/data/content/assets/glyph-delete-16.svg
new file mode 100644
index 0000000000..93ea650881
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/glyph-delete-16.svg
@@ -0,0 +1,4 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g fill="context-fill"><path d="M6.5 12a.5.5 0 0 0 .5-.5v-6a.5.5 0 0 0-1 0v6a.5.5 0 0 0 .5.5zm2 0a.5.5 0 0 0 .5-.5v-6a.5.5 0 0 0-1 0v6a.5.5 0 0 0 .5.5zm2 0a.5.5 0 0 0 .5-.5v-6a.5.5 0 0 0-1 0v6a.5.5 0 0 0 .5.5z"/><path d="M14 2h-3.05a2.5 2.5 0 0 0-4.9 0H3a1 1 0 0 0 0 2v9a3 3 0 0 0 3 3h5a3 3 0 0 0 3-3V4a1 1 0 0 0 0-2zM8.5 1a1.489 1.489 0 0 1 1.391 1H7.109A1.489 1.489 0 0 1 8.5 1zM12 13a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V4h7z"/></g></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/glyph-dismiss-16.svg b/browser/components/newtab/data/content/assets/glyph-dismiss-16.svg
new file mode 100644
index 0000000000..a0c02ca77e
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/glyph-dismiss-16.svg
@@ -0,0 +1,4 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill="context-fill" d="M9.414 8l3.531-3.531a1 1 0 1 0-1.414-1.414L8 6.586 4.469 3.055a1 1 0 1 0-1.414 1.414L6.586 8l-3.531 3.531a1 1 0 1 0 1.414 1.414L8 9.414l3.531 3.531a1 1 0 1 0 1.414-1.414z"/></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/glyph-edit-16.svg b/browser/components/newtab/data/content/assets/glyph-edit-16.svg
new file mode 100644
index 0000000000..94fb0d5525
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/glyph-edit-16.svg
@@ -0,0 +1,4 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill="context-fill" d="M14.354 2.353l-.708-.707a2.007 2.007 0 0 0-2.828 0l-.379.379a.5.5 0 0 0 0 .707l2.829 2.829a.5.5 0 0 0 .707 0l.379-.379a2.008 2.008 0 0 0 0-2.829zM9.732 3.439a.5.5 0 0 0-.707 0L3.246 9.218a1.986 1.986 0 0 0-.452.712l-1.756 4.39A.5.5 0 0 0 1.5 15a.5.5 0 0 0 .188-.037l4.382-1.752a1.966 1.966 0 0 0 .716-.454l5.779-5.778a.5.5 0 0 0 0-.707zM5.161 12.5l-2.549 1.02a.1.1 0 0 1-.13-.13L3.5 10.831a.1.1 0 0 1 .16-.031l1.54 1.535a.1.1 0 0 1-.039.165z"/></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/glyph-help-24.svg b/browser/components/newtab/data/content/assets/glyph-help-24.svg
new file mode 100644
index 0000000000..88bfec6094
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/glyph-help-24.svg
@@ -0,0 +1,4 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><g fill="context-fill" fill-opacity="context-fill-opacity"><path d="M13.15 17a1.15 1.15 0 1 1-2.3 0 1.15 1.15 0 0 1 2.3 0zM10.5 9.5c0-.764.616-1.5 1.5-1.5s1.5.736 1.5 1.5c0 .311-.144.635-.408.974-.199.254-.386.43-.57.6-.077.072-.153.143-.23.219a1.676 1.676 0 0 1-.048.045c-.13.117-.466.42-.698.757C11.22 12.569 11 13.18 11 14a1 1 0 1 0 2 0c0-.431.106-.645.194-.772.051-.074.114-.144.197-.225.04-.039.08-.075.129-.12l.003-.002.009-.008c.05-.045.114-.104.175-.166l.086-.08a8.13 8.13 0 0 0 .876-.924c.4-.512.831-1.264.831-2.203C15.5 7.764 14.116 6 12 6S8.5 7.764 8.5 9.5a1 1 0 1 0 2 0z"/><path fill-rule="evenodd" d="M12 22c5.523 0 10-4.477 10-10S17.523 2 12 2 2 6.477 2 12s4.477 10 10 10zm0-2a8 8 0 1 0 0-16 8 8 0 0 0 0 16z" clip-rule="evenodd"/></g></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/glyph-highlights-16.svg b/browser/components/newtab/data/content/assets/glyph-highlights-16.svg
new file mode 100644
index 0000000000..4c92bb23b4
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/glyph-highlights-16.svg
@@ -0,0 +1,4 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill="context-fill" fill-opacity="context-fill-opacity" d="M9.5 3s.428 2.43 1.249 3.251S14 7.5 14 7.5s-2.43.394-3.251 1.215S9.5 12 9.5 12s-.394-2.464-1.215-3.285S5 7.5 5 7.5s2.464-.428 3.285-1.249S9.5 3 9.5 3m0-2h-.014a2 2 0 0 0-1.96 1.68 7.536 7.536 0 0 1-.659 2.154 7.9 7.9 0 0 1-2.212.7 2 2 0 0 0 .029 3.945 7.733 7.733 0 0 1 2.183.658 7.74 7.74 0 0 1 .658 2.185A2 2 0 0 0 9.489 14H9.5a2 2 0 0 0 1.971-1.657 7.891 7.891 0 0 1 .7-2.209 7.566 7.566 0 0 1 2.154-.659 2 2 0 0 0 .027-3.944 7.694 7.694 0 0 1-2.181-.7 7.731 7.731 0 0 1-.7-2.181A2 2 0 0 0 9.5 1zM3 15.5a.5.5 0 0 1-.49-.421 3.047 3.047 0 0 0-.4-1.186 3.047 3.047 0 0 0-1.186-.4.5.5 0 0 1-.007-.986 3.147 3.147 0 0 0 1.192-.417 3.051 3.051 0 0 0 .4-1.171A.5.5 0 0 1 3 10.5a.5.5 0 0 1 .492.413 3.094 3.094 0 0 0 .417 1.179 3.142 3.142 0 0 0 1.178.416.5.5 0 0 1-.007.985 3.007 3.007 0 0 0-1.172.4 3.166 3.166 0 0 0-.416 1.192A.5.5 0 0 1 3 15.5zm-.5-11a.5.5 0 0 1-.49-.42 2.344 2.344 0 0 0-.265-.82 2.344 2.344 0 0 0-.82-.265.5.5 0 0 1-.007-.986 2.41 2.41 0 0 0 .827-.277A2.306 2.306 0 0 0 2.007.92.5.5 0 0 1 2.5.5a.5.5 0 0 1 .492.412 2.353 2.353 0 0 0 .278.818 2.372 2.372 0 0 0 .816.276.5.5 0 0 1-.007.985 2.306 2.306 0 0 0-.811.266 2.41 2.41 0 0 0-.277.827.5.5 0 0 1-.491.416z"/></svg>
diff --git a/browser/components/newtab/data/content/assets/glyph-info-16.svg b/browser/components/newtab/data/content/assets/glyph-info-16.svg
new file mode 100644
index 0000000000..7d3101d004
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/glyph-info-16.svg
@@ -0,0 +1,4 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g fill="context-fill"><path d="M8 16a8 8 0 1 1 8-8 8.009 8.009 0 0 1-8 8zM8 2a6 6 0 1 0 6 6 6.006 6.006 0 0 0-6-6z"/><path d="M8 7a1 1 0 0 0-1 1v3a1 1 0 0 0 2 0V8a1 1 0 0 0-1-1z"/><circle cx="8" cy="5" r="1.188"/></g></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/glyph-mail-16.svg b/browser/components/newtab/data/content/assets/glyph-mail-16.svg
new file mode 100644
index 0000000000..8c211c5567
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/glyph-mail-16.svg
@@ -0,0 +1,4 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill="context-fill" d="M13 2H3C1.3 2 0 3.3 0 5v6c0 1.7 1.3 3 3 3h10c1.7 0 3-1.3 3-3V5c0-1.7-1.3-3-3-3zm0 2c.1 0 .2 0 .3.1h-.1L8 7.9 2.8 4.1h-.1c.1-.1.2-.1.3-.1h10zm1 7c0 .6-.4 1-1 1H3c-.6 0-1-.4-1-1V4.8c0 .1.1.1.2.1l5.5 4c.1.1.2.1.3.1.1 0 .2 0 .3-.1l5.5-4c.1 0 .1-.1.1-.2.1.1.1.2.1.3v6z"></path></svg>
diff --git a/browser/components/newtab/data/content/assets/glyph-maximize-16.svg b/browser/components/newtab/data/content/assets/glyph-maximize-16.svg
new file mode 100644
index 0000000000..2f45557cfa
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/glyph-maximize-16.svg
@@ -0,0 +1,4 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill="context-fill" d="M14 1H2a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V2a1 1 0 0 0-1-1zm-1 12H3V3h10z"/><path fill="context-fill" d="M5 9h2v2a1 1 0 0 0 2 0V9h2a1 1 0 0 0 0-2H9V5a1 1 0 0 0-2 0v2H5a1 1 0 0 0 0 2z"/></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/glyph-minimize-16.svg b/browser/components/newtab/data/content/assets/glyph-minimize-16.svg
new file mode 100644
index 0000000000..6bc93fa5e0
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/glyph-minimize-16.svg
@@ -0,0 +1,4 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill="context-fill" d="M14 1H2a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V2a1 1 0 0 0-1-1zm-1 12H3V3h10z"/><path fill="context-fill" d="M5 9h6a1 1 0 0 0 0-2H5a1 1 0 0 0 0 2z"/></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/glyph-modal-delete-32.svg b/browser/components/newtab/data/content/assets/glyph-modal-delete-32.svg
new file mode 100644
index 0000000000..5df073b292
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/glyph-modal-delete-32.svg
@@ -0,0 +1,4 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><g fill="context-fill"><path d="M11.5 11a.5.5 0 0 0-.5.5v12a.5.5 0 0 0 1 0v-12a.5.5 0 0 0-.5-.5zm4 0a.5.5 0 0 0-.5.5v12a.5.5 0 0 0 1 0v-12a.5.5 0 0 0-.5-.5zm4 0a.5.5 0 0 0-.5.5v12a.5.5 0 0 0 1 0v-12a.5.5 0 0 0-.5-.5z"/><path d="M27 5h-6.6a5 5 0 0 0-9.8 0H4a1 1 0 0 0 0 2h1v20a4 4 0 0 0 4 4h13a4 4 0 0 0 4-4V7h1a1 1 0 0 0 0-2zM15.5 2a4 4 0 0 1 3.86 3h-7.72a4 4 0 0 1 3.86-3zM24 27a2 2 0 0 1-2 2H9a2 2 0 0 1-2-2V7h17z"/><path d="M7.04 7h16.92a.04.04 0 0 1 .04.04V28a1 1 0 0 1-1 1H8a1 1 0 0 1-1-1V7.04A.04.04 0 0 1 7.04 7z" opacity=".2"/></g></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/glyph-newWindow-16.svg b/browser/components/newtab/data/content/assets/glyph-newWindow-16.svg
new file mode 100644
index 0000000000..0b09bfde5a
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/glyph-newWindow-16.svg
@@ -0,0 +1,4 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g fill="context-fill"><path d="M14.923 1.618A1 1 0 0 0 14 1H9a1 1 0 0 0 0 2h2.586L8.293 6.293a1 1 0 1 0 1.414 1.414L13 4.414V7a1 1 0 0 0 2 0V2a1 1 0 0 0-.077-.382z"/><path d="M14 10a1 1 0 0 0-1 1v2H3V3h2a1 1 0 0 0 0-2H2a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-3a1 1 0 0 0-1-1z"/></g></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/glyph-open-file-16.svg b/browser/components/newtab/data/content/assets/glyph-open-file-16.svg
new file mode 100644
index 0000000000..a2a23f09eb
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/glyph-open-file-16.svg
@@ -0,0 +1,4 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill="context-fill" d="M14.859 3.2a1.335 1.335 0 0 1-1.217.8H13v1h1v8H2V5h8V4h-.642a1.365 1.365 0 0 1-1.325-1.11L6.584 1.538A2 2 0 0 0 5.219 1H2a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V5a2 2 0 0 0-1.141-1.8zM2 3h3.219l1.072 1H2zm7.854-.146L11 1.707V8.5a.5.5 0 0 0 1 0V1.707l1.146 1.146a.5.5 0 1 0 .707-.707l-2-2a.5.5 0 0 0-.707 0l-2 2a.5.5 0 0 0 .707.707z"/></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/glyph-pause-12.svg b/browser/components/newtab/data/content/assets/glyph-pause-12.svg
new file mode 100644
index 0000000000..a502ac7c0d
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/glyph-pause-12.svg
@@ -0,0 +1,4 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 12"><g fill="none" fill-rule="evenodd" transform="translate(-3 -2)"><path d="M0 0h16v16H0z"/><rect width="3" height="12" x="9.5" y="2" fill="context-fill" rx="1.5"/><rect width="3" height="12" x="3.5" y="2" fill="context-fill" rx="1.5"/></g></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/glyph-pin-12.svg b/browser/components/newtab/data/content/assets/glyph-pin-12.svg
new file mode 100644
index 0000000000..d61e30a2bd
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/glyph-pin-12.svg
@@ -0,0 +1,4 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 12 12"><path fill="context-fill" d="M10.53 9.47L8.25 7.19 9.8 5.643a.694.694 0 0 0 0-.98 3.04 3.04 0 0 0-2.161-.894h-.122A1.673 1.673 0 0 1 5.846 2.1v-.408A.693.693 0 0 0 4.664 1.2L1.2 4.664a.693.693 0 0 0 .49 1.182h.41a1.672 1.672 0 0 1 1.669 1.671v.117a2.8 2.8 0 0 0 .925 2.192.693.693 0 0 0 .949-.026L7.19 8.251l2.28 2.28a.75.75 0 0 0 1.06-1.061z"/></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/glyph-pin-16.svg b/browser/components/newtab/data/content/assets/glyph-pin-16.svg
new file mode 100644
index 0000000000..079fcb9d00
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/glyph-pin-16.svg
@@ -0,0 +1,4 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill="context-fill" d="M14.707 13.293L11.414 10l2.293-2.293a1 1 0 0 0 0-1.414A4.384 4.384 0 0 0 10.586 5h-.172A2.415 2.415 0 0 1 8 2.586V2a1 1 0 0 0-1.707-.707l-5 5A1 1 0 0 0 2 8h.586A2.415 2.415 0 0 1 5 10.414v.169a4.036 4.036 0 0 0 1.337 3.166 1 1 0 0 0 1.37-.042L10 11.414l3.293 3.293a1 1 0 0 0 1.414-1.414zm-7.578-1.837A2.684 2.684 0 0 1 7 10.583v-.169a4.386 4.386 0 0 0-1.292-3.121 4.414 4.414 0 0 0-1.572-1.015l2.143-2.142a4.4 4.4 0 0 0 1.013 1.571A4.384 4.384 0 0 0 10.414 7h.172a2.4 2.4 0 0 1 .848.152z"/></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/glyph-play-12.svg b/browser/components/newtab/data/content/assets/glyph-play-12.svg
new file mode 100644
index 0000000000..9dbfeb48d5
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/glyph-play-12.svg
@@ -0,0 +1,4 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 12 12"><path fill="context-fill" d="M2.128.13A.968.968 0 0 0 .676.964v10.068a.968.968 0 0 0 1.452.838l8.712-5.034a.968.968 0 0 0 0-1.676L2.128.13z"/></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/glyph-playhead.svg b/browser/components/newtab/data/content/assets/glyph-playhead.svg
new file mode 100644
index 0000000000..f1376ca8ca
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/glyph-playhead.svg
@@ -0,0 +1,6 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+<svg width="19" height="22" viewBox="0 0 19 22" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M2.333 1.7651L2.33302 1.76511L17.333 10.4251C17.4343 10.4836 17.5184 10.5678 17.577 10.6691C17.6355 10.7704 17.6663 10.8854 17.6663 11.0024C17.6663 11.1194 17.6355 11.2344 17.577 11.3357L18.443 11.8357L17.577 11.3357C17.5184 11.4371 17.4343 11.5212 17.333 11.5797L17.3327 11.5799L2.33301 20.2464C2.33292 20.2464 2.33282 20.2465 2.33273 20.2465C2.23145 20.305 2.1166 20.3357 1.99968 20.3357C1.88266 20.3357 1.76769 20.3049 1.66635 20.2464C1.565 20.1879 1.48084 20.1037 1.42233 20.0024C1.36382 19.901 1.33301 19.7861 1.33301 19.6691V2.33821C1.33375 2.22195 1.36488 2.1079 1.42332 2.00737C1.48202 1.9064 1.56622 1.82262 1.66749 1.76443C1.76876 1.70623 1.88354 1.67566 2.00034 1.67578C2.11713 1.6759 2.23185 1.7067 2.333 1.7651Z" stroke="white" stroke-width="2"/>
+</svg>
diff --git a/browser/components/newtab/data/content/assets/glyph-pocket-16.svg b/browser/components/newtab/data/content/assets/glyph-pocket-16.svg
new file mode 100644
index 0000000000..c454c68b1e
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/glyph-pocket-16.svg
@@ -0,0 +1,4 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill="context-fill" d="M8 15a8 8 0 0 1-8-8V3a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v4a8 8 0 0 1-8 8zm3.985-10.032a.99.99 0 0 0-.725.319L7.978 8.57 4.755 5.336A.984.984 0 0 0 4 4.968a1 1 0 0 0-.714 1.7l-.016.011 3.293 3.306.707.707a1 1 0 0 0 1.414 0l.707-.707L12.7 6.679a1 1 0 0 0-.715-1.711z"/></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/glyph-pocket-archive-16.svg b/browser/components/newtab/data/content/assets/glyph-pocket-archive-16.svg
new file mode 100644
index 0000000000..10cf13c4d2
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/glyph-pocket-archive-16.svg
@@ -0,0 +1,4 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill="context-fill" fill-opacity="context-fill-opacity" d="M1 14.667V4h14v10.667c0 .736-.597 1.333-1.333 1.333H2.333A1.333 1.333 0 0 1 1 14.667zM1 0h14a1 1 0 0 1 0 2H1a1 1 0 1 1 0-2zm9.341 7.247l-3.295 2.884-.839-.838a1 1 0 1 0-1.414 1.414l1.5 1.5a1 1 0 0 0 1.366.046l4-3.5a1 1 0 0 0-1.318-1.506z"/></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/glyph-pocket-delete-16.svg b/browser/components/newtab/data/content/assets/glyph-pocket-delete-16.svg
new file mode 100644
index 0000000000..95bb4d3edb
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/glyph-pocket-delete-16.svg
@@ -0,0 +1,4 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill="context-fill" fill-opacity="context-fill-opacity" d="M4 2v-.667C4 .597 4.597 0 5.333 0h5.334C11.403 0 12 .597 12 1.333V2h3.02a1 1 0 0 1 0 2H1.003a1 1 0 1 1 0-2H4zM2 14.667V6h12v8.667c0 .736-.597 1.333-1.333 1.333H3.333A1.333 1.333 0 0 1 2 14.667z"/></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/glyph-pocket-save-16.svg b/browser/components/newtab/data/content/assets/glyph-pocket-save-16.svg
new file mode 100644
index 0000000000..7d1e777bde
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/glyph-pocket-save-16.svg
@@ -0,0 +1,4 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill="context-fill" fill-opacity="context-fill-opacity" d="M14.5.932h-13A1.509 1.509 0 0 0 0 2.435v4.5a8 8 0 0 0 16 0v-4.5A1.508 1.508 0 0 0 14.5.932zm-.5 6a6 6 0 0 1-12 0v-4h12zm-6.7 3.477a1 1 0 0 0 1.422 0l3.343-3.39a1 1 0 1 0-1.423-1.406L8.01 8.283 5.38 5.614a1 1 0 0 0-1.425 1.405zm.711.3z"/></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/glyph-search-16.svg b/browser/components/newtab/data/content/assets/glyph-search-16.svg
new file mode 100644
index 0000000000..08e6070e0d
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/glyph-search-16.svg
@@ -0,0 +1,4 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill="context-fill" d="M10 0a5.991 5.991 0 0 0-4.885 9.471L.293 14.293a1 1 0 1 0 1.414 1.414l4.822-4.822A6 6 0 1 0 10 0zm0 10a4 4 0 1 1 4-4 4 4 0 0 1-4 4z"/></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/glyph-star-17.svg b/browser/components/newtab/data/content/assets/glyph-star-17.svg
new file mode 100644
index 0000000000..5c9ac09b42
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/glyph-star-17.svg
@@ -0,0 +1,4 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 17 16"><path fill="context-fill" fill-opacity="context-fill-opacity" d="M16.676 6.013a1.15 1.15 0 0 0-.894-.742l-4.324-.74L9.421.617A1.17 1.17 0 0 0 8.381 0a1.17 1.17 0 0 0-1.042.617L5.301 4.531l-4.315.738a1.15 1.15 0 0 0-.903.743 1.08 1.08 0 0 0 .253 1.114l3.095 3.187-.644 4.415c-.06.414.125.825.482 1.066.356.24.823.27 1.21.076l3.9-1.949 3.903 1.952c.386.194.853.164 1.21-.076.356-.24.542-.652.482-1.066l-.645-4.418 3.094-3.186a1.08 1.08 0 0 0 .253-1.114z"/></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/glyph-topsites-16.svg b/browser/components/newtab/data/content/assets/glyph-topsites-16.svg
new file mode 100644
index 0000000000..9fa6571392
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/glyph-topsites-16.svg
@@ -0,0 +1,4 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g fill="context-fill"><rect width="6" height="6" x="1" y="1" rx="1" ry="1"/><rect width="6" height="6" x="9" y="1" rx="1" ry="1"/><rect width="6" height="6" x="1" y="9" rx="1" ry="1"/><rect width="6" height="6" x="9" y="9" rx="1" ry="1"/></g></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/glyph-trending-16.svg b/browser/components/newtab/data/content/assets/glyph-trending-16.svg
new file mode 100644
index 0000000000..c84c3abf0e
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/glyph-trending-16.svg
@@ -0,0 +1,4 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill="context-fill" fill-rule="evenodd" d="M12.165 5.75a.33.33 0 0 1 .258.535c-1.683 2.087-8.157 9.398-8.264 9.459a385.997 385.997 0 0 0 2.969-6.768h-2.8a.328.328 0 0 1-.305-.45C4.7 6.777 6.862 1.33 7.305.217a.305.305 0 0 1 .29-.2C8.325.013 10.79.003 12.579 0c.266 0 .419.305.264.525L9.172 5.75h2.993z"/></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/glyph-unpin-16.svg b/browser/components/newtab/data/content/assets/glyph-unpin-16.svg
new file mode 100644
index 0000000000..2352839340
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/glyph-unpin-16.svg
@@ -0,0 +1,4 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill="context-fill" d="M11.414 10l2.293-2.293a1 1 0 0 0 0-1.414 4.418 4.418 0 0 0-.8-.622L11.425 7.15h.008l-4.3 4.3v-.017l-1.48 1.476a3.865 3.865 0 0 0 .692.834 1 1 0 0 0 1.37-.042L10 11.414l3.293 3.293a1 1 0 0 0 1.414-1.414zm3.293-8.707a1 1 0 0 0-1.414 0L9.7 4.882A2.382 2.382 0 0 1 8 2.586V2a1 1 0 0 0-1.707-.707l-5 5A1 1 0 0 0 2 8h.586a2.382 2.382 0 0 1 2.3 1.7l-3.593 3.593a1 1 0 1 0 1.414 1.414l12-12a1 1 0 0 0 0-1.414zm-9 6a4.414 4.414 0 0 0-1.571-1.015l2.143-2.142a4.4 4.4 0 0 0 1.013 1.571 4.191 4.191 0 0 0 .9.684l-1.8 1.8a4.2 4.2 0 0 0-.684-.898z"/></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/glyph-webextension-16.svg b/browser/components/newtab/data/content/assets/glyph-webextension-16.svg
new file mode 100644
index 0000000000..b29ea04bf2
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/glyph-webextension-16.svg
@@ -0,0 +1,4 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill="context-fill" fill-opacity="context-fill-opacity" d="M14.5 8c-.971 0-1 1-1.75 1a.765.765 0 0 1-.75-.75V5a1 1 0 0 0-1-1H7.75A.765.765 0 0 1 7 3.25c0-.75 1-.779 1-1.75C8 .635 7.1 0 6 0S4 .635 4 1.5c0 .971 1 1 1 1.75a.765.765 0 0 1-.75.75H1a1 1 0 0 0-1 1v2.25A.765.765 0 0 0 .75 8c.75 0 .779-1 1.75-1C3.365 7 4 7.9 4 9s-.635 2-1.5 2c-.971 0-1-1-1.75-1a.765.765 0 0 0-.75.75V15a1 1 0 0 0 1 1h3.25a.765.765 0 0 0 .75-.75c0-.75-1-.779-1-1.75 0-.865.9-1.5 2-1.5s2 .635 2 1.5c0 .971-1 1-1 1.75a.765.765 0 0 0 .75.75H11a1 1 0 0 0 1-1v-3.25a.765.765 0 0 1 .75-.75c.75 0 .779 1 1.75 1 .865 0 1.5-.9 1.5-2s-.635-2-1.5-2z"/></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/icon-removed-bookmark.svg b/browser/components/newtab/data/content/assets/icon-removed-bookmark.svg
new file mode 100644
index 0000000000..e222da3bfd
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/icon-removed-bookmark.svg
@@ -0,0 +1,4 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><path fill="context-fill" d="M15.845 6.063A1.1 1.1 0 0 0 15 5.331l-1.125-.2-1.729 1.723.872.156-2.45 2.635.5 3.572L8 11.618l-1.291.673-3.468 3.468a1.057 1.057 0 0 0 1.066.038L8 13.874l3.688 1.921a1.1 1.1 0 0 0 1.6-1.126l-.609-4.358 2.926-3.147a1.1 1.1 0 0 0 .24-1.101zm-1.138-4.77a1 1 0 0 0-1.414 0L10.6 3.983 8.984.733A1.093 1.093 0 0 0 8 .124a1.1 1.1 0 0 0-.985.609L5.089 4.6l-4.082.729a1.1 1.1 0 0 0-.614 1.833L3.32 10.31l-.155 1.111-1.872 1.872a1 1 0 1 0 1.414 1.414l12-12a1 1 0 0 0 0-1.414zM2.981 7.01l3.449-.617L8 3.243l1.111 2.232L5.2 9.391z"></path></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/illustration-addons@2x.png b/browser/components/newtab/data/content/assets/illustration-addons@2x.png
new file mode 100644
index 0000000000..67f94d0a1b
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/illustration-addons@2x.png
Binary files differ
diff --git a/browser/components/newtab/data/content/assets/illustration-gift@2x.png b/browser/components/newtab/data/content/assets/illustration-gift@2x.png
new file mode 100644
index 0000000000..665bfc9ee0
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/illustration-gift@2x.png
Binary files differ
diff --git a/browser/components/newtab/data/content/assets/illustration-privatebrowsing@2x.png b/browser/components/newtab/data/content/assets/illustration-privatebrowsing@2x.png
new file mode 100644
index 0000000000..11dd0b895a
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/illustration-privatebrowsing@2x.png
Binary files differ
diff --git a/browser/components/newtab/data/content/assets/illustration-screenshots@2x.png b/browser/components/newtab/data/content/assets/illustration-screenshots@2x.png
new file mode 100644
index 0000000000..046b46c49d
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/illustration-screenshots@2x.png
Binary files differ
diff --git a/browser/components/newtab/data/content/assets/illustration-sync@2x.png b/browser/components/newtab/data/content/assets/illustration-sync@2x.png
new file mode 100644
index 0000000000..90875f2fe1
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/illustration-sync@2x.png
Binary files differ
diff --git a/browser/components/newtab/data/content/assets/long-zap.svg b/browser/components/newtab/data/content/assets/long-zap.svg
new file mode 100644
index 0000000000..e02554d0e1
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/long-zap.svg
@@ -0,0 +1,4 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+<svg data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 16" width="400" height="16"><defs><linearGradient id="a" y1="13.69" x2="435.45" y2="13.69" gradientUnits="userSpaceOnUse" gradientTransform="matrix(.91716 0 0 .7708 .27 .687)"><stop offset="0" stop-color="#616eb3"/><stop offset=".5" stop-color="#ec1067"/><stop offset="1" stop-color="#f6901e"/></linearGradient></defs><path vector-effect="non-scaling-stroke" d="M4.45 2.81c96.1 9.33 158.63 4.37 195.55 2.68 51.53-2.35 183.67-4.32 193.85-1.91 9.32 2.21-81.45-.12-114.57 7.08C258 15.28 315.1 7.17 322.94 14" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="3" stroke="url(#a)"/></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/protection-report-icon.png b/browser/components/newtab/data/content/assets/protection-report-icon.png
new file mode 100644
index 0000000000..05bd7c2376
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/protection-report-icon.png
Binary files differ
diff --git a/browser/components/newtab/data/content/assets/remote/pin-to-taskbar-v1.svg b/browser/components/newtab/data/content/assets/remote/pin-to-taskbar-v1.svg
new file mode 100644
index 0000000000..a1ef351caa
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/remote/pin-to-taskbar-v1.svg
@@ -0,0 +1,4 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+<svg width="516" height="160" fill="none" xmlns="http://www.w3.org/2000/svg"><g clip-path="url(#clip0)"><path fill="#fff" d="M0 0h516v160H0z"/><path fill="#F0F0F4" d="M0 95.853h516.129V160H0z"/><path fill-rule="evenodd" clip-rule="evenodd" d="M385.622 0H146.728v95.853h238.894V0zM297.88 160V95.853h-64.147V160h64.147z" fill="#9F9FAD"/><path d="M281.659 122.372c-.734-1.718-2.222-3.572-3.39-4.158.951 1.812 1.501 3.63 1.711 4.986l.004.027c-1.911-4.63-5.151-6.497-7.797-10.562-.133-.206-.267-.412-.398-.629a5.318 5.318 0 0 1-.186-.34 2.918 2.918 0 0 1-.252-.65.046.046 0 0 0-.011-.029.048.048 0 0 0-.028-.015.055.055 0 0 0-.031 0l-.009.005c-.004.001-.008.004-.012.007l.007-.01c-4.245 2.417-5.685 6.888-5.817 9.125a8.602 8.602 0 0 0-4.651 1.742 5.125 5.125 0 0 0-.438-.321 7.41 7.41 0 0 1-.047-4.015c-1.736.769-3.086 1.983-4.067 3.056h-.008c-.67-.825-.623-3.546-.585-4.114-.008-.035-.499.248-.564.291-.591.41-1.144.87-1.651 1.375a14.448 14.448 0 0 0-1.578 1.84l-.001.002.001-.002a13.682 13.682 0 0 0-2.268 4.977l-.022.108c-.032.145-.147.868-.167 1.026l-.003.035c-.148.748-.24 1.506-.275 2.267l-.001.084c0 9.072 7.566 16.426 16.898 16.426 8.357 0 15.297-5.898 16.656-13.646.028-.211.051-.422.076-.634.336-2.817-.037-5.778-1.096-8.254zm-19.476 12.858c.079.036.153.077.235.112l.011.007a9.319 9.319 0 0 1-.246-.119zm17.802-11.999l-.002-.016.003.018-.001-.002z" fill="url(#paint0_linear)"/><path d="M281.659 122.372c-.734-1.718-2.221-3.572-3.39-4.158.951 1.812 1.501 3.63 1.712 4.986l.002.015.003.018c1.594 4.202.726 8.475-.526 11.086-1.936 4.04-6.624 8.181-13.962 7.979-7.928-.218-14.913-5.937-16.217-13.428-.237-1.181 0-1.781.12-2.74-.146.739-.201.953-.274 2.266l-.002.084c0 9.072 7.566 16.426 16.898 16.426 8.357 0 15.297-5.898 16.656-13.646.028-.211.051-.422.076-.634.336-2.817-.037-5.778-1.096-8.254z" fill="url(#paint1_radial)"/><path d="M281.659 122.372c-.734-1.718-2.221-3.572-3.39-4.158.951 1.812 1.501 3.63 1.712 4.986l.002.015.003.018c1.594 4.202.726 8.475-.526 11.086-1.936 4.04-6.624 8.181-13.962 7.979-7.928-.218-14.913-5.937-16.217-13.428-.237-1.181 0-1.781.12-2.74-.146.739-.201.953-.274 2.266l-.002.084c0 9.072 7.566 16.426 16.898 16.426 8.357 0 15.297-5.898 16.656-13.646.028-.211.051-.422.076-.634.336-2.817-.037-5.778-1.096-8.254z" fill="url(#paint2_radial)"/><path d="M273.448 124.303l.105.075a8.967 8.967 0 0 0-1.569-1.99c-5.253-5.106-1.377-11.072-.724-11.375l.007-.009c-4.245 2.417-5.685 6.888-5.817 9.125.197-.013.393-.029.594-.029a8.572 8.572 0 0 1 7.404 4.203z" fill="url(#paint3_radial)"/><path d="M266.054 125.322c-.027.409-1.512 1.818-2.032 1.818-4.805 0-5.585 2.826-5.585 2.826.213 2.379 1.917 4.339 3.981 5.376.094.047.189.09.284.132.164.07.329.136.497.197a7.686 7.686 0 0 0 2.198.413c8.423.384 10.054-9.789 3.976-12.743 1.557-.263 3.172.345 4.075.961a8.574 8.574 0 0 0-7.404-4.203c-.201 0-.397.017-.594.03a8.591 8.591 0 0 0-4.65 1.742c.257.212.548.495 1.161 1.082 1.146 1.098 4.087 2.236 4.093 2.369z" fill="url(#paint4_radial)"/><path d="M266.054 125.322c-.027.409-1.512 1.818-2.032 1.818-4.805 0-5.585 2.826-5.585 2.826.213 2.379 1.917 4.339 3.981 5.376.094.047.189.09.284.132.164.07.329.136.497.197a7.686 7.686 0 0 0 2.198.413c8.423.384 10.054-9.789 3.976-12.743 1.557-.263 3.172.345 4.075.961a8.574 8.574 0 0 0-7.404-4.203c-.201 0-.397.017-.594.03a8.591 8.591 0 0 0-4.65 1.742c.257.212.548.495 1.161 1.082 1.146 1.098 4.087 2.236 4.093 2.369z" fill="url(#paint5_radial)"/><path d="M260.011 121.325c.118.074.235.149.351.225a7.41 7.41 0 0 1-.048-4.015c-1.736.769-3.086 1.984-4.067 3.056.081-.002 2.532-.045 3.764.734z" fill="url(#paint6_radial)"/><path d="M249.281 128.87c1.304 7.491 8.289 13.21 16.217 13.428 7.338.202 12.026-3.939 13.962-7.979 1.252-2.611 2.12-6.883.526-11.086l-.001-.002-.002-.016-.002-.015.003.027c.599 3.805-1.392 7.491-4.504 9.984l-.009.021c-6.064 4.801-11.867 2.896-13.042 2.117a9.319 9.319 0 0 1-.246-.119c-3.535-1.643-4.996-4.774-4.683-7.46-2.985 0-4.003-2.448-4.003-2.448s2.68-1.858 6.213-.242c3.271 1.497 6.344.242 6.344.242-.006-.133-2.947-1.27-4.094-2.369-.612-.587-.903-.869-1.161-1.082a5.054 5.054 0 0 0-.437-.321 21.016 21.016 0 0 0-.351-.226c-1.232-.778-3.683-.736-3.764-.733h-.008c-.67-.825-.623-3.546-.585-4.115-.008-.035-.499.249-.564.291a12.17 12.17 0 0 0-1.651 1.376 14.38 14.38 0 0 0-1.578 1.84l-.001.002.001-.002a13.663 13.663 0 0 0-2.267 4.977c-.009.035-.609 2.587-.313 3.91z" fill="url(#paint7_radial)"/><path d="M271.984 122.388a8.967 8.967 0 0 1 1.569 1.99c.093.068.18.136.253.202 3.831 3.431 1.824 8.285 1.674 8.631 3.112-2.493 5.103-6.179 4.504-9.984-1.911-4.63-5.151-6.497-7.796-10.562a21.951 21.951 0 0 1-.399-.629 5.318 5.318 0 0 1-.186-.34 2.968 2.968 0 0 1-.252-.65.046.046 0 0 0-.011-.029.048.048 0 0 0-.028-.015.055.055 0 0 0-.031 0l-.009.005a.052.052 0 0 0-.012.007c-.653.302-4.529 6.268.724 11.374z" fill="url(#paint8_radial)"/><path d="M273.806 124.58a3.198 3.198 0 0 0-.253-.202l-.105-.075c-.903-.617-2.518-1.225-4.075-.962 6.078 2.954 4.446 13.127-3.976 12.743a7.713 7.713 0 0 1-2.198-.412 9.696 9.696 0 0 1-.497-.198 6.598 6.598 0 0 1-.284-.132l.011.007c1.175.779 6.978 2.683 13.042-2.117l.009-.021c.15-.346 2.157-5.2-1.674-8.631z" fill="url(#paint9_radial)"/><path d="M258.437 129.966s.78-2.826 5.585-2.826c.52 0 2.005-1.409 2.032-1.818.028-.408-3.072 1.255-6.344-.242-3.533-1.616-6.213.242-6.213.242s1.018 2.448 4.003 2.448c-.313 2.686 1.148 5.818 4.683 7.46.079.037.153.077.234.112-2.063-1.037-3.767-2.997-3.98-5.376z" fill="url(#paint10_radial)"/><path d="M281.659 122.372c-.734-1.718-2.222-3.572-3.39-4.158.951 1.812 1.501 3.63 1.712 4.986l.003.027c-1.911-4.63-5.151-6.497-7.796-10.562a21.951 21.951 0 0 1-.399-.629 5.318 5.318 0 0 1-.186-.34 2.918 2.918 0 0 1-.252-.65.046.046 0 0 0-.011-.029.048.048 0 0 0-.028-.015.055.055 0 0 0-.031 0l-.009.005a.052.052 0 0 0-.012.007l.007-.01c-4.245 2.417-5.685 6.888-5.817 9.125.197-.013.393-.029.593-.029a8.57 8.57 0 0 1 7.404 4.203c-.902-.616-2.518-1.225-4.074-.962 6.078 2.954 4.446 13.127-3.976 12.743a7.726 7.726 0 0 1-2.199-.412 9.662 9.662 0 0 1-.496-.198 6.634 6.634 0 0 1-.285-.132l.012.007a9.319 9.319 0 0 1-.246-.119c.079.036.153.077.234.112-2.064-1.037-3.768-2.997-3.98-5.376 0 0 .78-2.826 5.585-2.826.519 0 2.004-1.409 2.032-1.818-.007-.133-2.948-1.27-4.094-2.369-.613-.587-.904-.869-1.161-1.082a4.919 4.919 0 0 0-.438-.321 7.4 7.4 0 0 1-.047-4.015c-1.736.769-3.086 1.983-4.068 3.056h-.008c-.67-.825-.622-3.546-.584-4.114-.008-.036-.5.248-.564.29-.591.411-1.144.871-1.652 1.376a14.452 14.452 0 0 0-1.577 1.84l-.001.002.001-.002a13.682 13.682 0 0 0-2.268 4.977l-.022.108c-.032.145-.175.879-.195 1.036-.002.012.001-.012 0 0-.13.759-.214 1.524-.249 2.292l-.002.084c0 9.072 7.566 16.426 16.898 16.426 8.357 0 15.297-5.898 16.656-13.646.028-.211.051-.422.076-.634.336-2.817-.037-5.778-1.096-8.254zm-1.676.843l.003.018-.001-.002-.002-.016z" fill="url(#paint11_linear)"/><circle cx="194.654" cy="128.295" r="16.959" fill="#E0E0E6"/><circle cx="123.871" cy="128.295" r="16.959" fill="#E0E0E6"/><circle cx="53.088" cy="128.295" r="16.959" fill="#E0E0E6"/><circle cx="337.696" cy="128.295" r="16.959" fill="#E0E0E6"/><path stroke="#80808F" stroke-width="4" stroke-linecap="round" stroke-linejoin="round" d="M169.864 74.548l12.171-12.172M182.034 74.649l-12.171-12.171"/><path fill="#AFAFBA" d="M196.439 60.461h68.571v16.221h-68.571zM270.909 60.461h49.401v16.221h-49.401z"/><path d="M165.094 31.265h6.118v4.26a1.315 1.315 0 0 0 1.314 1.313 5.763 5.763 0 0 0 4.1-1.698l.159-.16a3.174 3.174 0 0 1 4.485 0l.544.545a1.315 1.315 0 0 0 2.243-.93v-9.288a1.309 1.309 0 0 0-.811-1.214 1.314 1.314 0 0 0-1.432.285l-.544.544a3.172 3.172 0 0 1-4.485 0l-.157-.157a5.298 5.298 0 0 0-4.182-1.699 1.314 1.314 0 0 0-1.234 1.312v4.26h-6.118a1.315 1.315 0 0 0-.914 2.234c.242.246.57.387.914.393zm8.746-5.333c.346.177.661.41.931.691l.157.157a5.766 5.766 0 0 0 4.099 1.699 5.798 5.798 0 0 0 2.403-.517l-.001 3.98a5.779 5.779 0 0 0-2.4-.518 5.76 5.76 0 0 0-4.101 1.699l-.16.16c-.268.27-.583.488-.929.646l.001-7.997z" fill="#fff"/><path fill="#CFCFD8" d="M196.439 22.12h68.571v16.221h-68.571zM269.434 22.12h19.908v16.221h-19.908zM293.766 22.12h44.24v16.221h-44.24z"/></g><defs><linearGradient id="paint0_linear" x1="278.572" y1="116.256" x2="252.177" y2="142.445" gradientUnits="userSpaceOnUse"><stop offset=".05" stop-color="#FFF44F"/><stop offset=".37" stop-color="#FF980E"/><stop offset=".53" stop-color="#FF3647"/><stop offset=".7" stop-color="#E31587"/></linearGradient><radialGradient id="paint1_radial" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(34.5601 0 0 34.166 272.511 114.78)"><stop offset=".13" stop-color="#FFBD4F"/><stop offset=".28" stop-color="#FF980E"/><stop offset=".47" stop-color="#FF3750"/><stop offset=".78" stop-color="#EB0878"/><stop offset=".86" stop-color="#E50080"/></radialGradient><radialGradient id="paint2_radial" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(35.4241 0 0 34.166 262.489 128.891)"><stop offset=".3" stop-color="#960E18"/><stop offset=".35" stop-color="#B11927" stop-opacity=".74"/><stop offset=".43" stop-color="#DB293D" stop-opacity=".34"/><stop offset=".5" stop-color="#F5334B" stop-opacity=".09"/><stop offset=".53" stop-color="#FF3750" stop-opacity="0"/></radialGradient><radialGradient id="paint3_radial" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(11.3435 0 0 18.7236 269.339 109.399)"><stop offset=".13" stop-color="#FFF44F"/><stop offset=".53" stop-color="#FF980E"/></radialGradient><radialGradient id="paint4_radial" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(15.0105 0 0 15.9947 261.854 137.711)"><stop offset=".35" stop-color="#3A8EE6"/><stop offset=".67" stop-color="#9059FF"/><stop offset="1" stop-color="#C139E6"/></radialGradient><radialGradient id="paint5_radial" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(7.97059 0 0 9.43688 264.418 125.378)"><stop offset=".21" stop-color="#9059FF" stop-opacity="0"/><stop offset=".97" stop-color="#6E008B" stop-opacity=".6"/></radialGradient><radialGradient id="paint6_radial" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(11.9334 0 0 11.6432 264.888 113.521)"><stop offset=".1" stop-color="#FFE226"/><stop offset=".79" stop-color="#FF7139"/></radialGradient><radialGradient id="paint7_radial" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(56.9727 0 0 46.497 275.787 105.882)"><stop offset=".11" stop-color="#FFF44F"/><stop offset=".46" stop-color="#FF980E"/><stop offset=".72" stop-color="#FF3647"/><stop offset=".9" stop-color="#E31587"/></radialGradient><radialGradient id="paint8_radial" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="rotate(77.046 51.169 220.542) scale(17.5976 78.0841)"><stop stop-color="#FFF44F"/><stop offset=".3" stop-color="#FF980E"/><stop offset=".57" stop-color="#FF3647"/><stop offset=".74" stop-color="#E31587"/></radialGradient><radialGradient id="paint9_radial" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(32.7107 0 0 31.2434 265.011 117.708)"><stop offset=".14" stop-color="#FFF44F"/><stop offset=".48" stop-color="#FF980E"/><stop offset=".66" stop-color="#FF3647"/><stop offset=".9" stop-color="#E31587"/></radialGradient><radialGradient id="paint10_radial" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(39.3171 0 0 34.1968 273.501 119.536)"><stop offset=".09" stop-color="#FFF44F"/><stop offset=".63" stop-color="#FF980E"/></radialGradient><linearGradient id="paint11_linear" x1="276.125" y1="115.747" x2="255.092" y2="139.385" gradientUnits="userSpaceOnUse"><stop offset=".17" stop-color="#FFF44F" stop-opacity=".8"/><stop offset=".6" stop-color="#FFF44F" stop-opacity="0"/></linearGradient><clipPath id="clip0"><path fill="#fff" d="M0 0h516v160H0z"/></clipPath></defs></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/remote/pin-to-taskbar-v2.svg b/browser/components/newtab/data/content/assets/remote/pin-to-taskbar-v2.svg
new file mode 100644
index 0000000000..17c6f16ff3
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/remote/pin-to-taskbar-v2.svg
@@ -0,0 +1,116 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+<svg width="608" height="197" viewBox="0 0 608 197" fill="none" xmlns="http://www.w3.org/2000/svg">
+<g clip-path="url(#clip0)">
+<rect width="607" height="197" transform="translate(0.5)" fill="#F0F0F4"/>
+<rect x="96.5" y="146" width="511" height="51" fill="#80808F"/>
+<path fill-rule="evenodd" clip-rule="evenodd" d="M503.828 70H314.057V146.143H503.828V70ZM434.128 146.143H383.171V197.1H434.128V146.143Z" fill="#141422"/>
+<path d="M421.179 167.097C420.608 165.723 419.451 164.24 418.543 163.771C419.282 165.221 419.71 166.675 419.874 167.76C419.874 167.762 419.875 167.767 419.876 167.782C418.39 164.078 415.87 162.584 413.812 159.332C413.709 159.167 413.604 159.003 413.503 158.829C413.451 158.74 413.403 158.649 413.358 158.557C413.273 158.392 413.207 158.217 413.162 158.037C413.162 158.028 413.159 158.02 413.154 158.014C413.148 158.007 413.14 158.003 413.132 158.002C413.124 157.999 413.115 157.999 413.107 158.002C413.105 158.002 413.103 158.005 413.101 158.005C413.098 158.006 413.094 158.009 413.091 158.011C413.092 158.009 413.096 158.004 413.096 158.003C409.795 159.937 408.675 163.514 408.572 165.303C407.254 165.394 405.993 165.88 404.955 166.697C404.846 166.605 404.733 166.52 404.614 166.44C404.315 165.392 404.302 164.283 404.578 163.228C403.227 163.843 402.177 164.815 401.414 165.673H401.408C400.887 165.013 400.924 162.836 400.953 162.381C400.947 162.353 400.565 162.58 400.515 162.614C400.055 162.942 399.625 163.311 399.23 163.714C398.781 164.17 398.37 164.662 398.003 165.186C398.003 165.187 398.002 165.188 398.002 165.188C398.002 165.188 398.003 165.187 398.003 165.186C397.158 166.384 396.558 167.737 396.239 169.168C396.233 169.196 396.228 169.226 396.222 169.255C396.197 169.37 396.108 169.949 396.092 170.075C396.091 170.085 396.091 170.094 396.089 170.103C395.974 170.702 395.903 171.308 395.876 171.917C395.876 171.939 395.875 171.961 395.875 171.984C395.875 179.242 401.759 185.125 409.018 185.125C415.518 185.125 420.916 180.406 421.972 174.208C421.994 174.04 422.012 173.87 422.032 173.701C422.293 171.447 422.003 169.078 421.179 167.097ZM406.031 177.384C406.093 177.413 406.151 177.445 406.214 177.473C406.216 177.475 406.22 177.477 406.223 177.479C406.158 177.448 406.095 177.416 406.031 177.384ZM419.877 167.785L419.876 167.772C419.876 167.777 419.877 167.782 419.878 167.786L419.877 167.785Z" fill="url(#paint0_linear)"/>
+<path d="M421.18 167.097C420.608 165.723 419.451 164.24 418.543 163.771C419.282 165.221 419.71 166.675 419.874 167.76C419.874 167.757 419.874 167.763 419.876 167.772C419.876 167.777 419.877 167.782 419.878 167.786C421.118 171.148 420.442 174.567 419.469 176.655C417.963 179.887 414.317 183.2 408.609 183.038C402.443 182.864 397.011 178.288 395.997 172.296C395.812 171.351 395.997 170.871 396.09 170.104C395.976 170.695 395.933 170.866 395.876 171.917C395.876 171.939 395.875 171.962 395.875 171.984C395.875 179.242 401.759 185.125 409.018 185.125C415.518 185.125 420.916 180.406 421.972 174.208C421.995 174.04 422.012 173.87 422.032 173.701C422.293 171.447 422.003 169.078 421.18 167.097Z" fill="url(#paint1_radial)"/>
+<path d="M421.18 167.097C420.608 165.723 419.451 164.24 418.543 163.771C419.282 165.221 419.71 166.675 419.874 167.76C419.874 167.757 419.874 167.763 419.876 167.772C419.876 167.777 419.877 167.782 419.878 167.786C421.118 171.148 420.442 174.567 419.469 176.655C417.963 179.887 414.317 183.2 408.609 183.038C402.443 182.864 397.011 178.288 395.997 172.296C395.812 171.351 395.997 170.871 396.09 170.104C395.976 170.695 395.933 170.866 395.876 171.917C395.876 171.939 395.875 171.962 395.875 171.984C395.875 179.242 401.759 185.125 409.018 185.125C415.518 185.125 420.916 180.406 421.972 174.208C421.995 174.04 422.012 173.87 422.032 173.701C422.293 171.447 422.003 169.078 421.18 167.097Z" fill="url(#paint2_radial)"/>
+<path d="M414.793 168.642C414.821 168.662 414.847 168.682 414.874 168.702C414.544 168.117 414.134 167.581 413.654 167.11C409.569 163.025 412.583 158.253 413.091 158.011C413.093 158.009 413.096 158.004 413.097 158.003C409.795 159.937 408.675 163.514 408.572 165.303C408.725 165.292 408.878 165.28 409.034 165.28C411.498 165.28 413.643 166.634 414.793 168.642Z" fill="url(#paint3_radial)"/>
+<path d="M409.042 169.458C409.021 169.785 407.866 170.912 407.462 170.912C403.725 170.912 403.118 173.173 403.118 173.173C403.283 175.076 404.609 176.644 406.214 177.473C406.287 177.511 406.361 177.545 406.435 177.579C406.562 177.636 406.691 177.688 406.821 177.737C407.372 177.932 407.948 178.043 408.531 178.067C415.082 178.374 416.351 170.236 411.624 167.873C412.834 167.662 414.091 168.149 414.793 168.642C413.644 166.634 411.498 165.28 409.034 165.28C408.878 165.28 408.726 165.292 408.573 165.303C407.254 165.394 405.994 165.879 404.955 166.697C405.156 166.866 405.382 167.093 405.858 167.563C406.75 168.441 409.037 169.351 409.042 169.458Z" fill="url(#paint4_radial)"/>
+<path d="M409.042 169.458C409.021 169.785 407.866 170.912 407.462 170.912C403.725 170.912 403.118 173.173 403.118 173.173C403.283 175.076 404.609 176.644 406.214 177.473C406.287 177.511 406.361 177.545 406.435 177.579C406.562 177.636 406.691 177.688 406.821 177.737C407.372 177.932 407.948 178.043 408.531 178.067C415.082 178.374 416.351 170.236 411.624 167.873C412.834 167.662 414.091 168.149 414.793 168.642C413.644 166.634 411.498 165.28 409.034 165.28C408.878 165.28 408.726 165.292 408.573 165.303C407.254 165.394 405.994 165.879 404.955 166.697C405.156 166.866 405.382 167.093 405.858 167.563C406.75 168.441 409.037 169.351 409.042 169.458Z" fill="url(#paint5_radial)"/>
+<path d="M404.342 166.26C404.434 166.319 404.525 166.379 404.615 166.44C404.315 165.392 404.302 164.283 404.578 163.228C403.228 163.843 402.177 164.815 401.414 165.673C401.477 165.671 403.384 165.637 404.342 166.26Z" fill="url(#paint6_radial)"/>
+<path d="M395.997 172.296C397.011 178.288 402.443 182.864 408.609 183.038C414.317 183.2 417.963 179.887 419.469 176.655C420.442 174.566 421.118 171.148 419.878 167.787L419.878 167.785L419.876 167.772C419.874 167.763 419.874 167.757 419.874 167.76C419.874 167.762 419.875 167.767 419.876 167.782C420.343 170.826 418.794 173.775 416.374 175.769L416.366 175.786C411.65 179.626 407.136 178.103 406.223 177.479C406.158 177.448 406.095 177.417 406.031 177.384C403.281 176.07 402.145 173.565 402.389 171.416C400.067 171.416 399.275 169.458 399.275 169.458C399.275 169.458 401.36 167.972 404.108 169.264C406.652 170.461 409.042 169.458 409.042 169.458C409.037 169.351 406.75 168.441 405.858 167.563C405.382 167.093 405.155 166.867 404.955 166.697C404.846 166.605 404.733 166.519 404.615 166.44C404.524 166.379 404.434 166.319 404.342 166.26C403.384 165.637 401.477 165.671 401.414 165.672H401.408C400.887 165.013 400.924 162.836 400.953 162.381C400.947 162.353 400.565 162.58 400.515 162.614C400.055 162.942 399.625 163.31 399.23 163.714C398.781 164.17 398.37 164.662 398.003 165.186C398.003 165.187 398.003 165.188 398.002 165.188C398.002 165.188 398.003 165.187 398.003 165.186C397.158 166.384 396.558 167.737 396.239 169.168C396.233 169.196 395.766 171.237 395.997 172.296Z" fill="url(#paint7_radial)"/>
+<path d="M413.654 167.11C414.134 167.581 414.544 168.117 414.874 168.702C414.947 168.757 415.014 168.811 415.072 168.864C418.051 171.609 416.49 175.492 416.374 175.769C418.794 173.775 420.342 170.826 419.876 167.782C418.39 164.078 415.87 162.584 413.812 159.332C413.709 159.167 413.604 159.003 413.503 158.829C413.451 158.74 413.403 158.649 413.358 158.557C413.273 158.392 413.207 158.217 413.162 158.037C413.162 158.028 413.159 158.02 413.154 158.014C413.148 158.007 413.14 158.003 413.132 158.002C413.124 157.999 413.115 157.999 413.107 158.002C413.105 158.002 413.103 158.005 413.101 158.005C413.098 158.006 413.094 158.009 413.091 158.011C412.583 158.253 409.569 163.025 413.654 167.11Z" fill="url(#paint8_radial)"/>
+<path d="M415.072 168.864C415.014 168.811 414.947 168.757 414.874 168.702C414.847 168.682 414.821 168.662 414.793 168.642C414.091 168.149 412.834 167.662 411.624 167.873C416.351 170.236 415.082 178.374 408.531 178.067C407.948 178.043 407.371 177.932 406.821 177.737C406.691 177.688 406.562 177.636 406.435 177.579C406.361 177.546 406.287 177.511 406.214 177.474C406.216 177.475 406.22 177.477 406.223 177.479C407.136 178.102 411.65 179.626 416.366 175.786L416.373 175.768C416.49 175.492 418.051 171.609 415.072 168.864Z" fill="url(#paint9_radial)"/>
+<path d="M403.118 173.173C403.118 173.173 403.724 170.912 407.462 170.912C407.866 170.912 409.021 169.785 409.042 169.458C409.063 169.131 406.652 170.461 404.107 169.264C401.36 167.971 399.275 169.458 399.275 169.458C399.275 169.458 400.067 171.416 402.389 171.416C402.145 173.565 403.281 176.07 406.031 177.384C406.093 177.413 406.15 177.445 406.213 177.474C404.609 176.644 403.283 175.076 403.118 173.173Z" fill="url(#paint10_radial)"/>
+<path d="M421.18 167.097C420.608 165.723 419.451 164.24 418.543 163.771C419.282 165.221 419.71 166.675 419.874 167.76C419.874 167.762 419.875 167.767 419.876 167.782C418.39 164.078 415.87 162.584 413.813 159.332C413.709 159.167 413.604 159.003 413.503 158.829C413.451 158.74 413.403 158.649 413.358 158.557C413.273 158.392 413.207 158.217 413.162 158.037C413.162 158.028 413.159 158.02 413.154 158.014C413.148 158.007 413.14 158.003 413.132 158.002C413.124 157.999 413.115 157.999 413.107 158.002C413.105 158.002 413.103 158.005 413.101 158.005C413.098 158.006 413.094 158.009 413.091 158.011C413.092 158.009 413.096 158.004 413.096 158.003C409.795 159.937 408.675 163.514 408.572 165.303C408.725 165.293 408.878 165.28 409.034 165.28C411.498 165.28 413.643 166.634 414.792 168.642C414.091 168.149 412.834 167.662 411.623 167.873C416.351 170.236 415.082 178.374 408.531 178.067C407.948 178.043 407.371 177.932 406.821 177.737C406.691 177.688 406.562 177.636 406.435 177.579C406.361 177.546 406.287 177.512 406.213 177.474C406.216 177.475 406.22 177.477 406.222 177.479C406.158 177.448 406.094 177.416 406.031 177.384C406.092 177.413 406.15 177.445 406.213 177.473C404.608 176.644 403.283 175.076 403.117 173.173C403.117 173.173 403.724 170.912 407.461 170.912C407.865 170.912 409.02 169.785 409.042 169.458C409.037 169.351 406.749 168.441 405.858 167.563C405.381 167.093 405.155 166.867 404.955 166.697C404.846 166.605 404.732 166.519 404.614 166.44C404.315 165.392 404.302 164.283 404.577 163.228C403.227 163.843 402.177 164.815 401.414 165.673H401.408C400.887 165.013 400.923 162.836 400.953 162.381C400.947 162.353 400.564 162.58 400.514 162.614C400.054 162.942 399.625 163.31 399.23 163.714C398.781 164.17 398.37 164.662 398.003 165.186C398.003 165.187 398.003 165.188 398.002 165.188C398.002 165.188 398.003 165.187 398.003 165.186C397.158 166.384 396.558 167.737 396.239 169.168C396.233 169.196 396.228 169.226 396.222 169.255C396.197 169.37 396.086 169.957 396.07 170.083C396.069 170.093 396.071 170.074 396.07 170.083C395.969 170.69 395.904 171.302 395.876 171.917C395.876 171.939 395.875 171.962 395.875 171.984C395.875 179.242 401.759 185.125 409.018 185.125C415.518 185.125 420.916 180.406 421.972 174.208C421.994 174.04 422.012 173.87 422.032 173.701C422.293 171.447 422.003 169.078 421.18 167.097ZM419.876 167.772C419.876 167.777 419.877 167.782 419.878 167.786L419.877 167.785L419.876 167.772Z" fill="url(#paint11_linear)"/>
+<circle cx="352.128" cy="171.914" r="13.4714" fill="#9F9FAD"/>
+<circle cx="295.9" cy="171.914" r="13.4714" fill="#9F9FAD"/>
+<circle cx="239.671" cy="171.914" r="13.4714" fill="#9F9FAD"/>
+<circle cx="465.757" cy="171.914" r="13.4714" fill="#9F9FAD"/>
+<line x1="331.057" y1="128.637" x2="341.067" y2="118.627" stroke="#5B5B66" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
+<line x1="341.066" y1="130.223" x2="331.056" y2="120.213" stroke="#5B5B66" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
+<rect x="350.915" y="118.446" width="57.4179" height="12.5602" fill="#5B5B66"/>
+<rect x="412.705" y="118.029" width="39.2429" height="12.8857" fill="#5B5B66"/>
+<path d="M328.648 94.8357L333.508 94.8357L333.508 98.2196C333.508 98.4963 333.618 98.7617 333.813 98.9573C334.009 99.153 334.274 99.2629 334.551 99.263C335.156 99.2647 335.755 99.1464 336.315 98.9149C336.874 98.6833 337.381 98.3432 337.808 97.9141L337.935 97.7872C338.407 97.315 339.048 97.0498 339.716 97.0498C340.384 97.0498 341.025 97.315 341.497 97.7872L341.93 98.2196C342.076 98.3655 342.262 98.4648 342.464 98.5051C342.666 98.5453 342.876 98.5246 343.067 98.4456C343.257 98.3667 343.42 98.2329 343.535 98.0614C343.65 97.8898 343.711 97.6881 343.711 97.4817L343.711 90.1029C343.711 89.8965 343.65 89.6948 343.535 89.5232C343.42 89.3517 343.257 89.2179 343.067 89.1389C342.876 89.06 342.666 89.0393 342.464 89.0795C342.262 89.1198 342.076 89.2191 341.93 89.365L341.497 89.7974C341.025 90.2695 340.384 90.5348 339.716 90.5348C339.048 90.5348 338.407 90.2695 337.935 89.7974L337.81 89.6727C337.39 89.2171 336.874 88.8598 336.3 88.6266C335.725 88.3933 335.106 88.2896 334.487 88.3231C334.222 88.3393 333.973 88.4561 333.791 88.6497C333.609 88.8434 333.507 89.0992 333.508 89.365L333.508 92.7489L328.648 92.7489C328.374 92.7537 328.113 92.8657 327.922 93.0609C327.73 93.256 327.622 93.5187 327.622 93.7923C327.622 94.0659 327.73 94.3286 327.922 94.5237C328.113 94.7189 328.374 94.8309 328.648 94.8357ZM335.595 90.5995C335.87 90.7404 336.12 90.9259 336.334 91.1485L336.459 91.2732C336.886 91.7022 337.393 92.0423 337.952 92.274C338.511 92.5057 339.11 92.6242 339.715 92.6227C340.374 92.6237 341.025 92.4836 341.624 92.2117L341.624 95.3736C341.025 95.1014 340.375 94.9609 339.717 94.9618C339.112 94.9601 338.512 95.0785 337.953 95.3101C337.393 95.5418 336.886 95.8821 336.459 96.3114L336.332 96.4384C336.119 96.6526 335.869 96.8266 335.594 96.9519L335.595 90.5995Z" fill="white"/>
+<rect x="350.913" y="87.9432" width="57.4179" height="12.5602" fill="#9F9FAD"/>
+<rect x="411.532" y="87.5717" width="15.8143" height="12.8857" fill="#9F9FAD"/>
+<rect x="430.86" y="87.5717" width="35.1429" height="12.8857" fill="#9F9FAD"/>
+<rect x="0.5" width="294" height="197" fill="url(#paint12_linear)"/>
+<path fill-rule="evenodd" clip-rule="evenodd" d="M120.646 11.4611L341.697 70.597C364.899 76.8038 365.608 109.468 342.697 116.675L124.996 185.167L120.646 11.4611ZM336.247 112.401C346.46 112.704 354.985 104.67 355.288 94.4575C355.591 84.2447 347.557 75.7199 337.345 75.4169C327.132 75.1138 318.607 83.1472 318.304 93.36C318.001 103.573 326.034 112.098 336.247 112.401Z" fill="#BFBFC9"/>
+<circle cx="99.5" cy="99" r="90" fill="#15141A"/>
+<mask id="mask0" mask-type="alpha" maskUnits="userSpaceOnUse" x="9" y="9" width="181" height="180">
+<circle cx="99.5" cy="99" r="90" fill="#141422"/>
+</mask>
+<g mask="url(#mask0)">
+<path d="M59.794 101.009L79.6171 101.009L79.6171 114.812C79.6173 115.941 80.0657 117.023 80.8638 117.821C81.662 118.619 82.7444 119.068 83.8731 119.068C86.3414 119.075 88.7866 118.593 91.0671 117.648C93.3477 116.704 95.4181 115.316 97.1587 113.566L97.6764 113.048C99.604 111.122 102.217 110.04 104.942 110.04C107.667 110.04 110.281 111.122 112.208 113.048L113.972 114.812C114.567 115.407 115.326 115.812 116.151 115.977C116.977 116.141 117.833 116.056 118.61 115.734C119.388 115.412 120.053 114.867 120.52 114.167C120.988 113.467 121.238 112.644 121.238 111.802L121.238 81.7034C121.238 80.8617 120.988 80.0389 120.52 79.339C120.053 78.6391 119.388 78.0937 118.61 77.7715C117.833 77.4494 116.977 77.365 116.151 77.5291C115.326 77.6933 114.567 78.0985 113.972 78.6935L112.208 80.4573C110.281 82.3833 107.667 83.4652 104.942 83.4652C102.217 83.4652 99.604 82.3833 97.6764 80.4573L97.1677 79.9487C95.453 78.0901 93.3491 76.633 91.0062 75.6814C88.6634 74.7298 86.1393 74.3071 83.6142 74.4436C82.532 74.5097 81.5158 74.9863 80.773 75.776C80.0302 76.5658 79.6168 77.6093 79.6171 78.6935L79.6171 92.4969L59.794 92.4969C58.6781 92.5163 57.6144 92.9732 56.8321 93.7692C56.0497 94.5653 55.6114 95.6367 55.6114 96.7528C55.6114 97.8689 56.0497 98.9404 56.8321 99.7364C57.6144 100.532 58.6781 100.989 59.794 101.009ZM88.1321 83.7291C89.254 84.304 90.2731 85.0607 91.148 85.9684L91.6566 86.4771C93.3969 88.2271 95.4668 89.6147 97.7467 90.5596C100.027 91.5045 102.471 91.988 104.939 91.9822C107.625 91.9862 110.28 91.4146 112.726 90.3057L112.723 103.203C110.281 102.093 107.628 101.52 104.945 101.523C102.476 101.516 100.03 101.999 97.7492 102.944C95.4682 103.889 93.3973 105.277 91.6566 107.029L91.1389 107.546C90.2702 108.42 89.2505 109.13 88.1291 109.641L88.1321 83.7291Z" fill="white"/>
+<rect x="169.5" y="71.6085" width="221.739" height="52.1739" fill="#9F9FAD"/>
+</g>
+</g>
+<defs>
+<linearGradient id="paint0_linear" x1="418.778" y1="162.204" x2="397.675" y2="182.561" gradientUnits="userSpaceOnUse">
+<stop offset="0.05" stop-color="#FFF44F"/>
+<stop offset="0.37" stop-color="#FF980E"/>
+<stop offset="0.53" stop-color="#FF3647"/>
+<stop offset="0.7" stop-color="#E31587"/>
+</linearGradient>
+<radialGradient id="paint1_radial" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(414.064 161.024) scale(26.8801 27.3328)">
+<stop offset="0.13" stop-color="#FFBD4F"/>
+<stop offset="0.28" stop-color="#FF980E"/>
+<stop offset="0.47" stop-color="#FF3750"/>
+<stop offset="0.78" stop-color="#EB0878"/>
+<stop offset="0.86" stop-color="#E50080"/>
+</radialGradient>
+<radialGradient id="paint2_radial" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(406.27 172.313) scale(27.5521 27.3328)">
+<stop offset="0.3" stop-color="#960E18"/>
+<stop offset="0.35" stop-color="#B11927" stop-opacity="0.74"/>
+<stop offset="0.43" stop-color="#DB293D" stop-opacity="0.34"/>
+<stop offset="0.5" stop-color="#F5334B" stop-opacity="0.09"/>
+<stop offset="0.53" stop-color="#FF3750" stop-opacity="0"/>
+</radialGradient>
+<radialGradient id="paint3_radial" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(411.597 156.719) scale(8.82276 14.9788)">
+<stop offset="0.13" stop-color="#FFF44F"/>
+<stop offset="0.53" stop-color="#FF980E"/>
+</radialGradient>
+<radialGradient id="paint4_radial" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(405.775 179.369) scale(11.6748 12.7958)">
+<stop offset="0.35" stop-color="#3A8EE6"/>
+<stop offset="0.67" stop-color="#9059FF"/>
+<stop offset="1" stop-color="#C139E6"/>
+</radialGradient>
+<radialGradient id="paint5_radial" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(407.77 169.502) scale(6.19934 7.54951)">
+<stop offset="0.21" stop-color="#9059FF" stop-opacity="0"/>
+<stop offset="0.97" stop-color="#6E008B" stop-opacity="0.6"/>
+</radialGradient>
+<radialGradient id="paint6_radial" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(408.135 160.016) scale(9.28154 9.31453)">
+<stop offset="0.1" stop-color="#FFE226"/>
+<stop offset="0.79" stop-color="#FF7139"/>
+</radialGradient>
+<radialGradient id="paint7_radial" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(416.612 153.906) scale(44.3121 37.1976)">
+<stop offset="0.11" stop-color="#FFF44F"/>
+<stop offset="0.46" stop-color="#FF980E"/>
+<stop offset="0.72" stop-color="#FF3647"/>
+<stop offset="0.9" stop-color="#E31587"/>
+</radialGradient>
+<radialGradient id="paint8_radial" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(400.155 166.19) rotate(77.3946) scale(14.0587 60.8158)">
+<stop stop-color="#FFF44F"/>
+<stop offset="0.3" stop-color="#FF980E"/>
+<stop offset="0.57" stop-color="#FF3647"/>
+<stop offset="0.74" stop-color="#E31587"/>
+</radialGradient>
+<radialGradient id="paint9_radial" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(408.231 163.367) scale(25.4416 24.9947)">
+<stop offset="0.14" stop-color="#FFF44F"/>
+<stop offset="0.48" stop-color="#FF980E"/>
+<stop offset="0.66" stop-color="#FF3647"/>
+<stop offset="0.9" stop-color="#E31587"/>
+</radialGradient>
+<radialGradient id="paint10_radial" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(414.834 164.828) scale(30.58 27.3574)">
+<stop offset="0.09" stop-color="#FFF44F"/>
+<stop offset="0.63" stop-color="#FF980E"/>
+</radialGradient>
+<linearGradient id="paint11_linear" x1="416.875" y1="161.798" x2="400" y2="180.236" gradientUnits="userSpaceOnUse">
+<stop offset="0.17" stop-color="#FFF44F" stop-opacity="0.8"/>
+<stop offset="0.6" stop-color="#FFF44F" stop-opacity="0"/>
+</linearGradient>
+<linearGradient id="paint12_linear" x1="168.5" y1="0" x2="294.5" y2="0" gradientUnits="userSpaceOnUse">
+<stop stop-color="#EDEDF0"/>
+<stop offset="1" stop-color="#EDEDF0" stop-opacity="0"/>
+</linearGradient>
+<clipPath id="clip0">
+<rect width="607" height="197" fill="white" transform="translate(0.5)"/>
+</clipPath>
+</defs>
+</svg>
diff --git a/browser/components/newtab/data/content/assets/remote/pip-message-icon.svg b/browser/components/newtab/data/content/assets/remote/pip-message-icon.svg
new file mode 100644
index 0000000000..0c214df71b
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/remote/pip-message-icon.svg
@@ -0,0 +1,4 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+<svg width="64" height="64" xmlns="http://www.w3.org/2000/svg"><rect fill="#0060DF" width="64" height="64" rx="6"/><path d="M46 34a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H34a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2zm-4-16c3.308 0 6 2.692 6 6v4a2 2 0 1 1-4 0v-4c0-1.104-.898-2-2-2H22c-1.102 0-2 .896-2 2v16c0 1.104.898 2 2 2h4a2 2 0 1 1 0 4h-4c-3.308 0-6-2.692-6-6V24c0-3.308 2.692-6 6-6zm-19.708 6.292a1.003 1.003 0 0 1 1.416 0L28 28.586V27a1 1 0 0 1 2 0v4a1.003 1.003 0 0 1-1 1h-4a1 1 0 0 1 0-2h1.586l-4.294-4.292a1.003 1.003 0 0 1 0-1.416z" fill="#F9F9FA"/></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/short-zap.svg b/browser/components/newtab/data/content/assets/short-zap.svg
new file mode 100644
index 0000000000..79d003ae91
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/short-zap.svg
@@ -0,0 +1,4 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+<svg data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 16" width="400" height="16"><defs><linearGradient id="a" y1="13.69" x2="435.45" y2="13.69" gradientUnits="userSpaceOnUse" gradientTransform="matrix(.91716 0 0 .7708 .27 .687)"><stop offset="0" stop-color="#616eb3"/><stop offset=".5" stop-color="#ec1067"/><stop offset="1" stop-color="#f6901e"/></linearGradient></defs><path vector-effect="non-scaling-stroke" d="M3.12 14c161-19.73 207.41 3 223.21-.65 16.76-3.85 20-6.77 31.28-10.29 18.08-5.64-2.49 13.2 8.14 10.71 16.45-3.84 27.73-7.39 39.25-9.4 15-2.6-2 22.49 87.48-2.37" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="3" stroke="url(#a)"/></svg>
diff --git a/browser/components/newtab/data/content/assets/spinner.svg b/browser/components/newtab/data/content/assets/spinner.svg
new file mode 100644
index 0000000000..89567f1b76
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/spinner.svg
@@ -0,0 +1,4 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+<svg width="73" height="73" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><defs><linearGradient x1="93.093%" y1="52.773%" x2="68.513%" y2="119.326%" id="a"><stop stop-color="#FFF" stop-opacity="0" offset="0%"/><stop stop-color="#FFF" offset="69.37%"/><stop stop-color="#FFF" offset="100%"/><stop stop-color="#FFF" stop-opacity=".005" offset="100%"/><stop stop-color="#FFF" stop-opacity="0" offset="100%"/><stop stop-color="#FFF" stop-opacity="0" offset="100%"/></linearGradient><path id="b" d="M0 0h48v60H0z"/></defs><g transform="translate(-5 -1)" fill="none" fill-rule="evenodd"><path d="M41.8 73.8c-19.9 0-36-16.1-36-36 0-19.7 15.8-35.6 35.3-36h.7c2.8.4 5 2.7 5 5.5s-2.2 5.2-5 5.4c-13.8.1-25 11.3-25 25.1s11.2 25 25 25 25-11.2 25-25h11c0 19.9-16.1 36-36 36z" fill="url(#a)"/><mask id="c" fill="#fff"><use xlink:href="#b"/></mask><path d="M41.8 73.8c-19.9 0-36-16.1-36-36 0-19.7 15.8-35.6 35.3-36h.7c2.8.4 5 2.7 5 5.5s-2.2 5.2-5 5.4c-13.8.1-25 11.3-25 25.1s11.2 25 25 25 25-11.2 25-25h11c0 19.9-16.1 36-36 36z" fill="#FFF" mask="url(#c)"/></g></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/topic-show-more-12.svg b/browser/components/newtab/data/content/assets/topic-show-more-12.svg
new file mode 100644
index 0000000000..015bf665da
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/topic-show-more-12.svg
@@ -0,0 +1,4 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 12 12"><path fill="none" stroke="context-fill" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 2l4 4-4 4"/></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/trailhead/card-illo-devices.svg b/browser/components/newtab/data/content/assets/trailhead/card-illo-devices.svg
new file mode 100644
index 0000000000..c7bfae3f0e
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/trailhead/card-illo-devices.svg
@@ -0,0 +1,5 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+
+<svg viewBox="0 0 288 180" xmlns="http://www.w3.org/2000/svg"><circle cx="144" cy="90" fill="#bfbfc9" opacity=".15" r="72"/><path d="m179.18 109.25a5.26 5.26 0 0 0 1.21-3.34v-63.77a5.33 5.33 0 0 0 -5.31-5.31h-90.33a5.33 5.33 0 0 0 -5.32 5.31v63.77a5.26 5.26 0 0 0 1.22 3.34l-11.84 2v5.31h122.19v-5.31z" fill="#9f9fad"/><path d="m139.66 47.46-54.91 54.9a1.78 1.78 0 0 0 1.77 1.78h86.79a1.78 1.78 0 0 0 1.77-1.78v-54.9z" fill="#592acb"/><path d="m84.75 47.46v54.9l54.91-54.9z" fill="#6736d8"/><path d="m173.31 42.14h-86.79a1.78 1.78 0 0 0 -1.77 1.77v3.55h90.33v-3.55a1.78 1.78 0 0 0 -1.77-1.77z" fill="#592acb"/><path d="m173.47 110.54h-86.79a.89.89 0 1 1 0-1.77h86.79a.89.89 0 1 1 0 1.77z" fill="#8f8f9d"/><path d="m123.38 112.85h12.4" fill="none" stroke="#80808e" stroke-linecap="round" stroke-linejoin="round"/><path d="m204.41 68.93h-37.58a5.38 5.38 0 0 0 -5.36 5.37v68a5.38 5.38 0 0 0 5.36 5.37h37.58a5.38 5.38 0 0 0 5.37-5.37v-68a5.38 5.38 0 0 0 -5.37-5.37z" fill="#bfbfc9"/><path d="m166.83 117.25v21.47a1.8 1.8 0 0 0 1.79 1.79h34a1.79 1.79 0 0 0 1.79-1.79v-59z" fill="#f11f89"/><path d="m166.83 79.67v37.58l37.58-37.58z" fill="#ff298a"/><path d="m202.62 74.3h-34a1.79 1.79 0 0 0 -1.79 1.79v3.58h37.58v-3.58a1.79 1.79 0 0 0 -1.79-1.79z" fill="#f11f89"/><circle cx="176.68" cy="132.46" fill="#ffd567" r="2.68"/><circle cx="185.62" cy="132.46" fill="#ff8a50" r="2.68"/><circle cx="194.57" cy="132.46" fill="#7542e5" r="2.68"/><path d="m183.26 144.09h5.05" fill="none" stroke="#9f9fad" stroke-linecap="round" stroke-linejoin="round"/><g fill="#fff"><path d="m141.32 74.4a1.93 1.93 0 0 0 -.83.06 1.81 1.81 0 0 0 -1.64 1.36 9.15 9.15 0 0 1 -8.86 7 11.89 11.89 0 0 1 -1.2-.08 9.06 9.06 0 0 1 -6-3.58h3.61a1.83 1.83 0 0 0 0-3.66h-7.4a1.83 1.83 0 0 0 -1.83 1.83v7.27a1.83 1.83 0 0 0 3.66 0v-1.68a13.44 13.44 0 0 0 7.49 3.38 11.24 11.24 0 0 0 1.65.13c6.35 0 11.73-4.16 12.8-9.89a1.85 1.85 0 0 0 -1.45-2.14z"/><path d="m142.82 62.61a1.84 1.84 0 0 0 -3.67 0v1.68a13.44 13.44 0 0 0 -7.48-3.38 11.66 11.66 0 0 0 -1.68-.13h-.19c-6.26.08-11.55 4.2-12.6 9.87a1.84 1.84 0 0 0 1.46 2.14h.34a2.14 2.14 0 0 0 .35-.06 1.84 1.84 0 0 0 1.78-1.39 9.13 9.13 0 0 1 8.76-6.94h.11a10.19 10.19 0 0 1 1.24.09 9 9 0 0 1 6 3.57h-3.6a1.83 1.83 0 1 0 0 3.66h7.36a1.83 1.83 0 0 0 1.84-1.83v-7.28z"/><path d="m193.26 105.26a1.6 1.6 0 0 0 -1.6.92 5.93 5.93 0 0 1 -5.75 4.51 6.65 6.65 0 0 1 -.78-.06 5.83 5.83 0 0 1 -3.92-2.32h2.34a1.19 1.19 0 0 0 0-2.38h-4.76a1.2 1.2 0 0 0 -1.19 1.19v4.76a1.19 1.19 0 1 0 2.37 0v-1.09a8.78 8.78 0 0 0 4.87 2.2 7.48 7.48 0 0 0 1.07.08 8.24 8.24 0 0 0 8.31-6.42 1.2 1.2 0 0 0 -.96-1.39z"/><path d="m194.24 97.61a1.19 1.19 0 0 0 -2.38 0v1.09a8.79 8.79 0 0 0 -4.86-2.2 7.88 7.88 0 0 0 -1.09-.08h-.12a8.2 8.2 0 0 0 -8.18 6.41 1.18 1.18 0 0 0 .95 1.39h.22a1.7 1.7 0 0 0 .22 0 1.18 1.18 0 0 0 1.15-.9 5.93 5.93 0 0 1 5.69-4.51h.06a7 7 0 0 1 .8.06 5.87 5.87 0 0 1 3.92 2.32h-2.34a1.19 1.19 0 1 0 0 2.38h4.76a1.2 1.2 0 0 0 1.19-1.19v-4.77z"/></g></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/trailhead/card-illo-fbcont.svg b/browser/components/newtab/data/content/assets/trailhead/card-illo-fbcont.svg
new file mode 100644
index 0000000000..03e939f978
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/trailhead/card-illo-fbcont.svg
@@ -0,0 +1,5 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+
+<svg viewBox="0 0 288 180" xmlns="http://www.w3.org/2000/svg"><circle cx="144" cy="90" fill="#bfbfc9" opacity=".15" r="72"/><path d="m68.3 106.33h-.5v14h.5 4 .5v-14h-.5z" fill="none"/><path d="m92.3 106.33h-.5v14h.5 4 .5v-14h-.5z" fill="none"/><path d="m80.3 106.33h-.5v14h.5 4 .5v-14h-.5z" fill="none"/><path d="m92.3 103.33h4v3h-4z" fill="#ffbd4f"/><path d="m68.3 103.33h4v3h-4z" fill="#ffbd4f"/><path d="m80.3 103.33h4v3h-4z" fill="#ffbd4f"/><path d="m92.3 120.33h4v3h-4z" fill="#ffbd4f"/><path d="m80.3 120.33h4v3h-4z" fill="#ffbd4f"/><path d="m68.3 120.33h4v3h-4z" fill="#ffbd4f"/><g fill="#ffa436"><path d="m67.8 103.33h.5v3h-.5z"/><path d="m67.8 120.33h.5v3h-.5z"/><path d="m72.3 103.33h.5v3h-.5z"/><path d="m72.3 120.33h.5v3h-.5z"/><path d="m79.8 103.33h.5v3h-.5z"/><path d="m79.8 120.33h.5v3h-.5z"/><path d="m84.3 103.33h.5v3h-.5z"/><path d="m84.3 120.33h.5v3h-.5z"/><path d="m91.8 103.33h.5v3h-.5z"/><path d="m91.8 120.33h.5v3h-.5z"/><path d="m96.3 103.33h.5v3h-.5z"/><path d="m96.3 120.33h.5v3h-.5z"/></g><path d="m67.8 106.33v-9a.5.5 0 0 0 -.14-.35l-3-3a.5.5 0 0 0 -.66.02l-3 3a.47.47 0 0 0 -.15.35v32a.5.5 0 0 0 .5.5h6a.5.5 0 0 0 .5-.5v-23zm-2.5 15a1 1 0 1 1 -1-1 1 1 0 0 1 1 1zm-1-18a1 1 0 1 1 -1 1 1 1 0 0 1 1-1z" fill="#ffd567"/><path d="m79.8 106.33v-9a.5.5 0 0 0 -.14-.35l-3-3a.5.5 0 0 0 -.66.02l-3 3a.47.47 0 0 0 -.15.35v32a.5.5 0 0 0 .5.5h6a.5.5 0 0 0 .5-.5v-23zm-2.5 15a1 1 0 1 1 -1-1 1 1 0 0 1 1 1zm-1-18a1 1 0 1 1 -1 1 1 1 0 0 1 1-1z" fill="#ffd567"/><path d="m91.8 106.33v-9a.5.5 0 0 0 -.14-.35l-3-3a.5.5 0 0 0 -.66.02l-3 3a.47.47 0 0 0 -.15.35v32a.5.5 0 0 0 .5.5h6a.5.5 0 0 0 .5-.5v-23zm-2.5 15a1 1 0 1 1 -1-1 1 1 0 0 1 1 1zm-1-18a1 1 0 1 1 -1 1 1 1 0 0 1 1-1z" fill="#ffd567"/><path d="m103.66 97-3-3a.5.5 0 0 0 -.71 0l-3 3a.47.47 0 0 0 -.15.35v32a.5.5 0 0 0 .5.5h6a.5.5 0 0 0 .5-.5v-32a.5.5 0 0 0 -.14-.35zm-2.36 7.35a1 1 0 1 1 -1-1 1 1 0 0 1 1 .98zm0 17a1 1 0 1 1 -1-1 1 1 0 0 1 1 .98z" fill="#ffd567"/><circle cx="88.3" cy="104.33" fill="#afafbb" r="1"/><circle cx="100.3" cy="104.33" fill="#afafbb" r="1"/><circle cx="76.3" cy="104.33" fill="#afafbb" r="1"/><circle cx="64.3" cy="104.33" fill="#afafbb" r="1"/><circle cx="88.3" cy="121.33" fill="#afafbb" r="1"/><circle cx="100.3" cy="121.33" fill="#afafbb" r="1"/><circle cx="76.3" cy="121.33" fill="#afafbb" r="1"/><circle cx="64.3" cy="121.33" fill="#afafbb" r="1"/><path d="m191.7 106.33h-.5v14h.5 4 .5v-14h-.5z" fill="none"/><path d="m215.7 106.33h-.5v14h.5 4 .5v-14h-.5z" fill="none"/><path d="m203.7 106.33h-.5v14h.5 4 .5v-14h-.5z" fill="none"/><path d="m215.7 103.33h4v3h-4z" fill="#ffbd4f"/><path d="m191.7 103.33h4v3h-4z" fill="#ffbd4f"/><path d="m203.7 103.33h4v3h-4z" fill="#ffbd4f"/><path d="m215.7 120.33h4v3h-4z" fill="#ffbd4f"/><path d="m203.7 120.33h4v3h-4z" fill="#ffbd4f"/><path d="m191.7 120.33h4v3h-4z" fill="#ffbd4f"/><path d="m191.2 103.33h.5v3h-.5z" fill="#ffa436"/><path d="m191.2 120.33h.5v3h-.5z" fill="#ffa436"/><path d="m195.7 103.33h.5v3h-.5z" fill="#ffa436"/><path d="m195.7 120.33h.5v3h-.5z" fill="#ffa436"/><path d="m203.2 103.33h.5v3h-.5z" fill="#ffa436"/><path d="m203.2 120.33h.5v3h-.5z" fill="#ffa436"/><path d="m207.7 103.33h.5v3h-.5z" fill="#ffa436"/><path d="m207.7 120.33h.5v3h-.5z" fill="#ffa436"/><path d="m215.2 103.33h.5v3h-.5z" fill="#ffa436"/><path d="m215.2 120.33h.5v3h-.5z" fill="#ffa436"/><path d="m219.7 103.33h.5v3h-.5z" fill="#ffa436"/><path d="m219.7 120.33h.5v3h-.5z" fill="#ffa436"/><path d="m191.2 106.33v-9a.47.47 0 0 0 -.15-.35l-3-3a.5.5 0 0 0 -.71 0l-3 3a.5.5 0 0 0 -.14.35v32a.5.5 0 0 0 .5.5h6a.5.5 0 0 0 .5-.5zm-2.5 15a1 1 0 1 1 -1-1 1 1 0 0 1 1 1zm-1-18a1 1 0 1 1 -1 1 1 1 0 0 1 1-1z" fill="#ffd567"/><path d="m203.2 106.33v-9a.47.47 0 0 0 -.15-.35l-3-3a.5.5 0 0 0 -.71 0l-3 3a.5.5 0 0 0 -.14.35v32a.5.5 0 0 0 .5.5h6a.5.5 0 0 0 .5-.5zm-2.5 15a1 1 0 1 1 -1-1 1 1 0 0 1 1 1zm-1-18a1 1 0 1 1 -1 1 1 1 0 0 1 1-1z" fill="#ffd567"/><path d="m215.2 106.33v-9a.47.47 0 0 0 -.15-.35l-3-3a.5.5 0 0 0 -.71 0l-3 3a.5.5 0 0 0 -.14.35v32a.5.5 0 0 0 .5.5h6a.5.5 0 0 0 .5-.5zm-2.5 15a1 1 0 1 1 -1-1 1 1 0 0 1 1 1zm-1-18a1 1 0 1 1 -1 1 1 1 0 0 1 1-1z" fill="#ffd567"/><path d="m227.05 97-3-3a.5.5 0 0 0 -.71 0l-3 3a.5.5 0 0 0 -.14.35v32a.5.5 0 0 0 .5.5h6a.5.5 0 0 0 .5-.5v-32a.47.47 0 0 0 -.15-.35zm-2.35 7.35a1 1 0 1 1 -1-1 1 1 0 0 1 1 .98zm0 17a1 1 0 1 1 -1-1 1 1 0 0 1 1 .98z" fill="#ffd567"/><circle cx="211.7" cy="104.33" fill="#afafbb" r="1"/><circle cx="223.7" cy="104.33" fill="#afafbb" r="1"/><circle cx="199.7" cy="104.33" fill="#afafbb" r="1"/><circle cx="187.7" cy="104.33" fill="#afafbb" r="1"/><circle cx="211.7" cy="121.33" fill="#afafbb" r="1"/><circle cx="223.7" cy="121.33" fill="#afafbb" r="1"/><circle cx="199.7" cy="121.33" fill="#afafbb" r="1"/><circle cx="187.7" cy="121.33" fill="#afafbb" r="1"/><path d="m193.26 122.56a5.24 5.24 0 0 0 1.22-3.33v-63.77a5.33 5.33 0 0 0 -5.31-5.31h-90.34a5.33 5.33 0 0 0 -5.31 5.31v63.77a5.24 5.24 0 0 0 1.22 3.33l-11.85 2v5.31h122.22v-5.31z" fill="#9f9fad"/><path d="m153.74 60.77-54.91 54.91a1.77 1.77 0 0 0 1.77 1.77h86.8a1.77 1.77 0 0 0 1.77-1.77v-54.91z" fill="#0090ed"/><path d="m98.83 60.77v54.91l54.91-54.91z" fill="#00a2f1"/><path d="m187.4 55.46h-86.8a1.78 1.78 0 0 0 -1.77 1.77v3.54h90.34v-3.54a1.78 1.78 0 0 0 -1.77-1.77z" fill="#0090ed"/><path d="m187.56 123.86h-86.79a.89.89 0 1 1 0-1.77h86.79a.89.89 0 0 1 0 1.77z" fill="#8f8f9d"/><path d="m137.47 126.17h12.4" fill="none" stroke="#80808e" stroke-linecap="round" stroke-linejoin="round"/><path d="m156.54 74.46-2.09 2.09v4.18h-4.18v-4.18l-2.09-2.09-2.09 2.09v4.18h-4.18v-4.18l-2.09-2.09-2.09 2.09v4.18h-4.18v-4.18l-2.09-2.09-2.09 2.09v23h4.18v-4.19h4.18v4.18h4.18v-4.18h4.18v4.18h4.18v-4.18h4.18v4.18h4.18v-23zm-18.81 18.81h-4.18v-10.45h4.18zm8.56 0h-3.69v-9.56h3.69zm8.16 0h-4.18v-10.45h4.18z" fill="#fff" fill-rule="evenodd"/></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/trailhead/card-illo-ffmonitor.svg b/browser/components/newtab/data/content/assets/trailhead/card-illo-ffmonitor.svg
new file mode 100644
index 0000000000..4577863c2c
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/trailhead/card-illo-ffmonitor.svg
@@ -0,0 +1,5 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+
+<svg viewBox="0 0 288 180" xmlns="http://www.w3.org/2000/svg"><circle cx="144" cy="90" fill="#bfbfc9" opacity=".15" r="72"/><rect fill="#0df" height="15.49" rx=".5" width="48.16" x="62.2" y="69.68"/><path d="m107.27 66.63h-42.13a7.22 7.22 0 0 0 -7.2 7.2v6.53a7.22 7.22 0 0 0 7.2 7.2h42.13a7.22 7.22 0 0 0 7.2-7.2v-6.53a7.22 7.22 0 0 0 -7.2-7.2zm-29.91 11.37a.39.39 0 0 1 .23.24.4.4 0 0 1 0 .34l-.89 1.51a.4.4 0 0 1 -.28.19.41.41 0 0 1 -.32-.08l-1.91-1.48.3 2.45a.41.41 0 0 1 -.4.46h-1.78a.41.41 0 0 1 -.31-.14.46.46 0 0 1 -.1-.32l.31-2.46-2 1.49a.42.42 0 0 1 -.33.08.45.45 0 0 1 -.27-.2l-.84-1.51a.38.38 0 0 1 0-.33.38.38 0 0 1 .23-.24l2.28-1-2.28-.9a.43.43 0 0 1 -.23-.25.42.42 0 0 1 0-.33l.88-1.52a.4.4 0 0 1 .27-.19.39.39 0 0 1 .33.07l2 1.49-.35-2.37a.46.46 0 0 1 .1-.32.41.41 0 0 1 .31-.14h1.74a.41.41 0 0 1 .4.46l-.3 2.44 2-1.48a.43.43 0 0 1 .33-.07.45.45 0 0 1 .27.2l.85 1.51a.47.47 0 0 1 0 .33.39.39 0 0 1 -.23.24l-2.28.94zm13 0a.39.39 0 0 1 .23.24.44.44 0 0 1 0 .34l-.89 1.51a.4.4 0 0 1 -.28.19.41.41 0 0 1 -.32-.08l-1.91-1.48.3 2.45a.41.41 0 0 1 -.1.32.41.41 0 0 1 -.3.14h-1.75a.41.41 0 0 1 -.3-.14.41.41 0 0 1 -.1-.32l.31-2.46-2 1.49a.42.42 0 0 1 -.33.08.45.45 0 0 1 -.27-.2l-.85-1.51a.47.47 0 0 1 0-.33.39.39 0 0 1 .2-.24l2.27-1-2.27-.9a.43.43 0 0 1 -.23-.25.42.42 0 0 1 0-.33l.92-1.52a.4.4 0 0 1 .27-.19.37.37 0 0 1 .32.07l2 1.49-.34-2.37a.41.41 0 0 1 .1-.32.41.41 0 0 1 .3-.14h1.75a.41.41 0 0 1 .3.14.41.41 0 0 1 .1.32l-.31 2.44 2-1.48a.42.42 0 0 1 .33-.07.45.45 0 0 1 .27.2l.84 1.51a.38.38 0 0 1 0 .33.38.38 0 0 1 -.22.24l-2.28.94zm13 0a.37.37 0 0 1 .23.24.4.4 0 0 1 0 .34l-.9 1.51a.4.4 0 0 1 -.27.19.41.41 0 0 1 -.32-.08l-1.92-1.48.31 2.45a.41.41 0 0 1 -.41.46h-1.7a.41.41 0 0 1 -.3-.14.41.41 0 0 1 -.1-.32l.31-2.46-2 1.49a.44.44 0 0 1 -.33.08.43.43 0 0 1 -.27-.2l-.85-1.51a.38.38 0 0 1 0-.33.39.39 0 0 1 .23-.24l2.27-1-2.34-.9a.42.42 0 0 1 -.19-.58l.92-1.52a.36.36 0 0 1 .27-.19.37.37 0 0 1 .32.07l2 1.49-.32-2.37a.41.41 0 0 1 .1-.32.41.41 0 0 1 .3-.14h1.74a.41.41 0 0 1 .41.46l-.31 2.44 2-1.48a.4.4 0 0 1 .59.13l.85 1.51a.38.38 0 0 1 0 .33.39.39 0 0 1 -.23.24l-2.27.94z" fill="#0090ed"/><path d="m193.26 122.56a5.24 5.24 0 0 0 1.22-3.33v-63.77a5.33 5.33 0 0 0 -5.31-5.31h-90.34a5.33 5.33 0 0 0 -5.31 5.31v63.77a5.24 5.24 0 0 0 1.22 3.33l-11.85 2v5.31h122.22v-5.31z" fill="#9f9fad"/><path d="m153.74 60.77-54.91 54.91a1.77 1.77 0 0 0 1.77 1.77h86.8a1.77 1.77 0 0 0 1.77-1.77v-54.91z" fill="#592acb"/><path d="m98.83 60.77v54.91l54.91-54.91z" fill="#6736d8"/><path d="m187.4 55.46h-86.8a1.78 1.78 0 0 0 -1.77 1.77v3.54h90.34v-3.54a1.78 1.78 0 0 0 -1.77-1.77z" fill="#592acb"/><path d="m187.56 123.86h-86.79a.89.89 0 1 1 0-1.77h86.79a.89.89 0 0 1 0 1.77z" fill="#8f8f9d"/><path d="m137.47 126.17h12.4" fill="none" stroke="#80808e" stroke-linecap="round" stroke-linejoin="round"/><g fill="#fff"><path d="m156.45 76-3.87-2.21-8.83-5.06-.28-.16a4.71 4.71 0 0 0 -4.68 0l-.28.16-12.42 7.11-.28.16a4.66 4.66 0 0 0 -2.34 4v14.84a4.63 4.63 0 0 0 2.34 4l12.7 7.28a2.05 2.05 0 0 0 1 .26 2 2 0 0 0 1.69-1 1.94 1.94 0 0 0 -.72-2.64l-12.48-7.07a1.34 1.34 0 0 1 -.67-1.15v-14.23a1.34 1.34 0 0 1 .67-1.15l2.2-1.26 10.27-5.88a1.34 1.34 0 0 1 1.33 0l12.42 7.11a1.34 1.34 0 0 1 .67 1.15v14.26a1.34 1.34 0 0 1 -.67 1.15l-4.2 2.4-2.12-3.19a10.15 10.15 0 1 0 -6.77 2.57 10.2 10.2 0 0 0 3.42-.59l3.22 4.86a1.2 1.2 0 0 0 .17.21 2.09 2.09 0 0 0 .22.2h.06a1.91 1.91 0 0 0 .27.16h.07l.26.1h.06a1.77 1.77 0 0 0 .32 0h.43a1.94 1.94 0 0 0 .33-.07h.08l.25-.11h.05l6.08-3.48a4.63 4.63 0 0 0 2.34-4v-14.73a4.66 4.66 0 0 0 -2.31-4zm-21.55 11.4a6.24 6.24 0 1 1 6.23 6.19 6.21 6.21 0 0 1 -6.23-6.19z"/><path d="m156.45 76-3.87-2.21-8.83-5.06-.28-.16a4.71 4.71 0 0 0 -4.68 0l-.28.16-12.42 7.11-.28.16a4.66 4.66 0 0 0 -2.34 4v14.84a4.63 4.63 0 0 0 2.34 4l12.7 7.28a2.05 2.05 0 0 0 1 .26 2 2 0 0 0 1.69-1 1.94 1.94 0 0 0 -.72-2.64l-12.48-7.07a1.34 1.34 0 0 1 -.67-1.15v-14.23a1.34 1.34 0 0 1 .67-1.15l2.2-1.26 10.27-5.88a1.34 1.34 0 0 1 1.33 0l12.42 7.11a1.34 1.34 0 0 1 .67 1.15v14.26a1.34 1.34 0 0 1 -.67 1.15l-4.2 2.4-2.12-3.19a10.15 10.15 0 1 0 -6.77 2.57 10.2 10.2 0 0 0 3.42-.59l3.22 4.86a1.2 1.2 0 0 0 .17.21 2.09 2.09 0 0 0 .22.2h.06a1.91 1.91 0 0 0 .27.16h.07l.26.1h.06a1.77 1.77 0 0 0 .32 0h.43a1.94 1.94 0 0 0 .33-.07h.08l.25-.11h.05l6.08-3.48a4.63 4.63 0 0 0 2.34-4v-14.73a4.66 4.66 0 0 0 -2.31-4zm-21.55 11.4a6.24 6.24 0 1 1 6.23 6.19 6.21 6.21 0 0 1 -6.23-6.19z"/><path d="m156.45 76-3.87-2.21-5.4-3.09a4.14 4.14 0 0 0 -4-.06l-2.71 1.36a1.34 1.34 0 0 1 1.33 0l12.42 7.11a1.34 1.34 0 0 1 .67 1.15v14.26a1.32 1.32 0 0 1 -.67 1.15l-4.2 2.4.65 1.05a2.75 2.75 0 0 0 3.7.92l2.08-1.19a4.61 4.61 0 0 0 2.34-4v-14.85a4.63 4.63 0 0 0 -2.34-4z"/><path d="m154.89 80.29v6.9h3.9v-7.19a4.63 4.63 0 0 0 -2.34-4l-3.87-2.21-5.4-3.09a4.14 4.14 0 0 0 -4-.06l-2.71 1.36a1.34 1.34 0 0 1 1.33 0l12.42 7.11a1.34 1.34 0 0 1 .67 1.18z"/><path d="m154.89 88.31v6.21a1.32 1.32 0 0 1 -.67 1.15l-4.2 2.4.65 1.05a2.75 2.75 0 0 0 3.7.92l2.08-1.19a4.61 4.61 0 0 0 2.34-4v-6.54z" opacity=".9"/><path d="m149.72 97.62-1.82-2.74a10.11 10.11 0 0 1 -3.35 2l1.94 2.93c1.09-.72 2.17-1.44 3.23-2.19z" opacity=".9"/></g><rect fill="#ffbdc5" height="13.79" rx="5.4" width="44.43" x="178.92" y="85.86"/><path d="m222.52 81.78h-42.13a7.22 7.22 0 0 0 -7.2 7.2v6.53a7.22 7.22 0 0 0 7.2 7.2h42.13a7.22 7.22 0 0 0 7.2-7.2v-6.51a7.22 7.22 0 0 0 -7.2-7.22zm-29.91 11.41a.39.39 0 0 1 .23.24.44.44 0 0 1 0 .34l-.89 1.51a.4.4 0 0 1 -.28.19.41.41 0 0 1 -.32-.08l-1.91-1.48.3 2.45a.41.41 0 0 1 -.1.32.41.41 0 0 1 -.3.14h-1.75a.41.41 0 0 1 -.3-.14.41.41 0 0 1 -.1-.32l.31-2.46-2 1.49a.42.42 0 0 1 -.33.08.45.45 0 0 1 -.27-.2l-.9-1.51a.47.47 0 0 1 0-.33.39.39 0 0 1 .23-.24l2.27-1-2.27-1a.43.43 0 0 1 -.23-.19.42.42 0 0 1 0-.33l.87-1.48a.4.4 0 0 1 .27-.19.37.37 0 0 1 .32.07l2 1.49-.31-2.43a.41.41 0 0 1 .1-.32.41.41 0 0 1 .3-.14h1.75a.41.41 0 0 1 .3.14.41.41 0 0 1 .1.32l-.31 2.44 2-1.48a.42.42 0 0 1 .33-.07.45.45 0 0 1 .27.2l.84 1.51a.38.38 0 0 1 0 .33.38.38 0 0 1 -.22.24l-2.28.94zm13 0a.37.37 0 0 1 .23.24.4.4 0 0 1 0 .34l-.9 1.51a.4.4 0 0 1 -.27.19.41.41 0 0 1 -.32-.08l-1.92-1.48.31 2.45a.41.41 0 0 1 -.41.46h-1.74a.41.41 0 0 1 -.3-.14.41.41 0 0 1 -.1-.32l.31-2.46-2 1.49a.43.43 0 0 1 -.33.08.43.43 0 0 1 -.27-.2l-.85-1.51a.38.38 0 0 1 0-.33.39.39 0 0 1 .23-.24l2.27-1-2.28-1a.45.45 0 0 1 -.27-.19.42.42 0 0 1 0-.33l.88-1.48a.36.36 0 0 1 .27-.19.37.37 0 0 1 .32.07l2 1.49-.3-2.43a.41.41 0 0 1 .1-.32.41.41 0 0 1 .3-.14h1.74a.41.41 0 0 1 .41.46l-.31 2.44 2-1.48a.4.4 0 0 1 .59.13l.85 1.51a.38.38 0 0 1 0 .33.39.39 0 0 1 -.23.24l-2.27.94zm13 0a.39.39 0 0 1 .23.24.4.4 0 0 1 0 .34l-.9 1.51a.4.4 0 0 1 -.27.19.43.43 0 0 1 -.33-.08l-1.91-1.48.3 2.45a.4.4 0 0 1 -.4.46h-1.74a.41.41 0 0 1 -.4-.46l.3-2.46-2 1.49a.41.41 0 0 1 -.32.08.4.4 0 0 1 -.27-.2l-.85-1.51a.38.38 0 0 1 0-.33.39.39 0 0 1 .23-.24l2.27-1-2.28-1a.39.39 0 0 1 -.22-.25.38.38 0 0 1 0-.33l.87-1.48a.4.4 0 0 1 .27-.19.38.38 0 0 1 .33.07l2 1.49-.3-2.43a.41.41 0 0 1 .4-.46h1.74a.4.4 0 0 1 .4.46l-.3 2.44 2-1.48a.4.4 0 0 1 .59.13l.85 1.51a.38.38 0 0 1 0 .33.39.39 0 0 1 -.23.24l-2.27.94z" fill="#ff298a"/><rect fill="#ff298a" height="16.85" rx="5.4" width="49.79" x="77.09" y="118.86"/><path d="m123.41 117.07h-42.13a7.22 7.22 0 0 0 -7.2 7.2v6.54a7.22 7.22 0 0 0 7.2 7.2h42.13a7.22 7.22 0 0 0 7.2-7.2v-6.54a7.22 7.22 0 0 0 -7.2-7.2zm-29.91 11.42a.39.39 0 0 1 .23.24.45.45 0 0 1 0 .34l-.89 1.5a.45.45 0 0 1 -.28.2.41.41 0 0 1 -.32-.08l-1.91-1.48.3 2.45a.42.42 0 0 1 -.1.32.43.43 0 0 1 -.3.13h-1.78a.44.44 0 0 1 -.31-.13.42.42 0 0 1 -.1-.32l.31-2.47-2 1.5a.38.38 0 0 1 -.33.07.4.4 0 0 1 -.27-.19l-.85-1.51a.47.47 0 0 1 0-.33.39.39 0 0 1 .23-.24l2.28-1-2.28-1a.43.43 0 0 1 -.23-.25.42.42 0 0 1 0-.33l.87-1.48a.4.4 0 0 1 .27-.19.37.37 0 0 1 .32.07l2 1.49-.36-2.37a.4.4 0 0 1 .1-.32.41.41 0 0 1 .31-.14h1.74a.41.41 0 0 1 .4.46l-.31 2.44 2-1.48a.41.41 0 0 1 .6.13l.84 1.5a.4.4 0 0 1 -.19.58l-2.28.94zm13 0a.37.37 0 0 1 .23.24.41.41 0 0 1 0 .34l-.9 1.5a.45.45 0 0 1 -.27.2.41.41 0 0 1 -.32-.08l-1.92-1.48.31 2.45a.42.42 0 0 1 -.1.32.44.44 0 0 1 -.31.13h-1.74a.43.43 0 0 1 -.3-.13.42.42 0 0 1 -.1-.32l.31-2.47-2 1.5a.39.39 0 0 1 -.33.07.38.38 0 0 1 -.27-.19l-.79-1.51a.38.38 0 0 1 0-.33.39.39 0 0 1 .23-.24l2.27-1-2.28-1a.45.45 0 0 1 -.22-.25.39.39 0 0 1 0-.33l.87-1.48a.36.36 0 0 1 .27-.19.37.37 0 0 1 .32.07l2 1.49-.3-2.43a.41.41 0 0 1 .4-.46h1.74a.41.41 0 0 1 .31.14.4.4 0 0 1 .1.32l-.31 2.44 2-1.48a.42.42 0 0 1 .33-.07.38.38 0 0 1 .26.2l.85 1.5a.41.41 0 0 1 0 .34.42.42 0 0 1 -.23.24l-2.27.94zm13 0a.39.39 0 0 1 .23.24.41.41 0 0 1 0 .34l-.9 1.5a.45.45 0 0 1 -.27.2.43.43 0 0 1 -.33-.08l-1.91-1.48.3 2.45a.42.42 0 0 1 -.09.32.44.44 0 0 1 -.31.13h-1.74a.4.4 0 0 1 -.3-.13.39.39 0 0 1 -.1-.32l.3-2.47-2 1.5a.37.37 0 0 1 -.32.07.36.36 0 0 1 -.27-.19l-.85-1.51a.38.38 0 0 1 0-.33.39.39 0 0 1 .23-.24l2.27-1-2.28-1a.39.39 0 0 1 -.22-.25.38.38 0 0 1 0-.33l.87-1.48a.4.4 0 0 1 .27-.19.38.38 0 0 1 .33.07l2 1.49-.3-2.43a.37.37 0 0 1 .1-.32.37.37 0 0 1 .3-.14h1.74a.41.41 0 0 1 .31.14.4.4 0 0 1 .09.32l-.3 2.44 2-1.48a.41.41 0 0 1 .32-.07.37.37 0 0 1 .27.2l.85 1.5a.41.41 0 0 1 0 .34.42.42 0 0 1 -.23.24l-2.27.94z" fill="#ffd567"/></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/trailhead/card-illo-ffsend.svg b/browser/components/newtab/data/content/assets/trailhead/card-illo-ffsend.svg
new file mode 100644
index 0000000000..591d39db33
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/trailhead/card-illo-ffsend.svg
@@ -0,0 +1,5 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+
+<svg viewBox="0 0 288 180" xmlns="http://www.w3.org/2000/svg"><circle cx="144" cy="90" fill="#bfbfc9" opacity=".15" r="72"/><path d="m121.16 76.34-22-8.46a1 1 0 0 0 -1.27.57l-14.09 36.65a1 1 0 0 0 .57 1.27l26.57 10.22a1 1 0 0 0 1.27-.57l12.33-32.02z" fill="#00b3f4"/><path d="m119.4 80.92a1 1 0 0 0 .56 1.27l4.58 1.81-3.38-7.61z" fill="#0090ed"/><path d="m114.9 92.42a2.28 2.28 0 0 0 -1.74.06l-7.16 3.24 5.68-15.07-3.59-3.38-6.35 16.84-3.22-7.11a2.27 2.27 0 0 0 -3-1.13 2.28 2.28 0 0 0 -1.14 3l5.49 12.13a2.28 2.28 0 0 0 3 1.14l12.13-5.52a2.25 2.25 0 0 0 1.19-1.27 2.28 2.28 0 0 0 -1.33-2.93z" fill="#0090ed"/><path d="m116.54 67.77a2.28 2.28 0 1 0 -4.26-1.6l-4.18 11.1 3.59 3.38z" fill="#0060df"/><path d="m140.21 54.66a27.84 27.84 0 0 0 -10.21-11.78 20.44 20.44 0 0 1 5.45 9.63 35.22 35.22 0 0 1 -1.38 20.94 2.07 2.07 0 0 1 -.76 1 1.82 1.82 0 0 1 -.27.15l5.96 2.26a1.68 1.68 0 0 0 1.3 0 1.65 1.65 0 0 0 .88-1 27.83 27.83 0 0 0 -.97-21.2z" fill="#7542e5"/><path d="m95.77 59a35.16 35.16 0 0 1 12.79-16.64 20.2 20.2 0 0 1 10.69-3.64 28 28 0 0 0 -30.53 17.38 1.72 1.72 0 0 0 0 1.3 1.66 1.66 0 0 0 .94.9l6.08 2.29a1.42 1.42 0 0 1 -.1-.29 2.19 2.19 0 0 1 .13-1.3z" fill="#ffd567"/><path d="m134.07 73.45a35.22 35.22 0 0 0 1.38-20.94 20.44 20.44 0 0 0 -5.45-9.63 27.33 27.33 0 0 0 -4.42-2.32c1.38 1.45 2 4.58 1.72 9.06a71.37 71.37 0 0 1 -4.57 19.43 4.26 4.26 0 0 1 -.57 1.09 1.23 1.23 0 0 1 -.28.28l11.12 4.21a1.82 1.82 0 0 0 .27-.15 2.07 2.07 0 0 0 .8-1.03z" fill="#b833e1"/><path d="m106.24 64.14a4.42 4.42 0 0 1 .29-1.2 71.15 71.15 0 0 1 9.39-17.61c2.73-3.51 5.23-5.46 7.22-5.67a27.8 27.8 0 0 0 -3.89-.92 20.2 20.2 0 0 0 -10.69 3.64 35.16 35.16 0 0 0 -12.79 16.62 2.19 2.19 0 0 0 -.1 1.28 1.42 1.42 0 0 0 .1.29l10.49 4a1.61 1.61 0 0 1 -.02-.43z" fill="#ff8a50"/><path d="m123.14 39.66c-2 .21-4.49 2.16-7.22 5.67a71.15 71.15 0 0 0 -9.39 17.61 4.42 4.42 0 0 0 -.29 1.2 1.61 1.61 0 0 0 0 .4l15.62 5.88a1.23 1.23 0 0 0 .28-.28 4.26 4.26 0 0 0 .57-1.09 71.37 71.37 0 0 0 4.57-19.43c.27-4.48-.34-7.61-1.72-9.06l-.93-.38c-.48-.18-.98-.36-1.49-.52z" fill="#ff298a"/><path d="m173.56 92.43-31.2-12a1.4 1.4 0 0 0 -1.8.8l-20 52a1.4 1.4 0 0 0 .8 1.8l37.7 14.51a1.4 1.4 0 0 0 1.8-.8l17.51-45.51z" fill="#00b3f4"/><path d="m171.06 98.93a1.39 1.39 0 0 0 .8 1.8l6.5 2.5-4.8-10.8z" fill="#0090ed"/><path d="m164.68 115.25a3.25 3.25 0 0 0 -2.47.08l-10.15 4.6 8.06-21.39-5.12-4.79-9 23.9-4.59-10.15a3.22 3.22 0 0 0 -4.27-1.61 3.21 3.21 0 0 0 -1.69 1.8 3.16 3.16 0 0 0 .08 2.47l7.8 17.25a3.2 3.2 0 0 0 1.81 1.69 3.25 3.25 0 0 0 2.47-.08l17.24-7.81a3.22 3.22 0 0 0 1.61-4.27 3.21 3.21 0 0 0 -1.78-1.69z" fill="#0090ed"/><path d="m167 80.27a3.23 3.23 0 1 0 -6-2.27l-6 15.75 5.09 4.79z" fill="#0060df"/><path d="m200.58 61.66a39.46 39.46 0 0 0 -14.48-16.66 29 29 0 0 1 7.73 13.67c2.43 9 1.74 19.57-2 29.71a3.1 3.1 0 0 1 -1.09 1.47 2 2 0 0 1 -.38.2l8.41 3.17a2.4 2.4 0 0 0 3.09-1.43 39.52 39.52 0 0 0 -1.28-30.13z" fill="#7542e5"/><path d="m137.54 67.85c3.91-10 10.36-18.44 18.14-23.6a28.66 28.66 0 0 1 15.17-5.17 39.75 39.75 0 0 0 -43.32 24.64 2.39 2.39 0 0 0 1.38 3.11l8.63 3.25a1.34 1.34 0 0 1 -.15-.41 3 3 0 0 1 .15-1.82z" fill="#ffd567"/><path d="m191.88 88.33c3.69-10.14 4.38-20.69 2-29.71a29 29 0 0 0 -7.78-13.62 40.63 40.63 0 0 0 -6.27-3.29c2 2.06 2.82 6.51 2.44 12.85-.48 7.81-2.78 17.6-6.48 27.57a6.38 6.38 0 0 1 -.81 1.55 2 2 0 0 1 -.4.41l15.83 6a2 2 0 0 0 .38-.2 3.1 3.1 0 0 0 1.09-1.56z" fill="#b833e1"/><path d="m152.38 75.12a6.66 6.66 0 0 1 .42-1.7c3.8-9.94 8.53-18.81 13.33-25 3.86-5 7.42-7.75 10.24-8a39.5 39.5 0 0 0 -5.52-1.31 28.66 28.66 0 0 0 -15.17 5.17c-7.78 5.16-14.23 13.55-18.14 23.6a3 3 0 0 0 -.15 1.82 1.34 1.34 0 0 0 .15.41l14.88 5.61a2 2 0 0 1 -.04-.6z" fill="#ff8a50"/><path d="m176.37 40.39c-2.82.29-6.38 3.06-10.24 8-4.8 6.18-9.53 15-13.33 25a6.66 6.66 0 0 0 -.42 1.7 2 2 0 0 0 0 .57l22.2 8.34a2 2 0 0 0 .4-.41 6.38 6.38 0 0 0 .81-1.55c3.7-10 6-19.76 6.48-27.57.38-6.34-.48-10.79-2.44-12.85-.44-.18-.87-.37-1.32-.53-.71-.23-1.42-.47-2.14-.7z" fill="#ff298a"/></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/trailhead/card-illo-import.svg b/browser/components/newtab/data/content/assets/trailhead/card-illo-import.svg
new file mode 100644
index 0000000000..b434343a0b
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/trailhead/card-illo-import.svg
@@ -0,0 +1,4 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+<svg viewBox="0 0 288 180" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><clipPath id="a"><path d="m187.39 55.55h-86.79a1.77 1.77 0 0 0 -1.77 1.77v58.45a1.78 1.78 0 0 0 1.77 1.77h86.79a1.77 1.77 0 0 0 1.77-1.77v-58.45a1.77 1.77 0 0 0 -1.77-1.77z"/></clipPath><circle cx="144" cy="90" fill="#bfbfc9" opacity=".15" r="72"/><path d="m193.26 122.56a5.24 5.24 0 0 0 1.22-3.33v-63.77a5.33 5.33 0 0 0 -5.31-5.31h-90.34a5.33 5.33 0 0 0 -5.31 5.31v63.77a5.24 5.24 0 0 0 1.22 3.33l-11.85 2v5.31h122.22v-5.31z" fill="#9f9fad"/><path d="m153.74 60.77-54.91 54.91a1.77 1.77 0 0 0 1.77 1.77h86.8a1.77 1.77 0 0 0 1.77-1.77v-54.91z" fill="#592acb"/><path d="m98.83 60.77v54.91l54.91-54.91z" fill="#6736d8"/><path d="m187.4 55.46h-86.8a1.78 1.78 0 0 0 -1.77 1.77v3.54h90.34v-3.54a1.78 1.78 0 0 0 -1.77-1.77z" fill="#592acb"/><path d="m187.56 123.86h-86.79a.89.89 0 1 1 0-1.77h86.79a.89.89 0 0 1 0 1.77z" fill="#8f8f9d"/><path d="m137.47 126.17h12.4" fill="none" stroke="#80808e" stroke-linecap="round" stroke-linejoin="round"/><path d="m142.65 49.58a1.48 1.48 0 0 0 -1.16-1l-5.57-1-2.63-5.27a1.5 1.5 0 0 0 -2.69 0l-2.6 5.27-5.57 1a1.5 1.5 0 0 0 -.84 2.5l4 4.3-.84 5.95a1.52 1.52 0 0 0 1.46 1.67 1.57 1.57 0 0 0 .7-.17l5-2.63 5 2.62a1.47 1.47 0 0 0 1.56-.1 1.51 1.51 0 0 0 .63-1.43l-.84-5.95 4-4.3a1.5 1.5 0 0 0 .39-1.46z" fill="#00b3f4"/><path d="m166.76 34.46a1.47 1.47 0 0 0 -1.16-1l-5.57-1-2.63-5.28a1.5 1.5 0 0 0 -2.69 0l-2.63 5.28-5.57 1a1.51 1.51 0 0 0 -.84 2.51l4 4.29-.84 6a1.53 1.53 0 0 0 .63 1.44 1.51 1.51 0 0 0 .86.27 1.38 1.38 0 0 0 .69-.17l5-2.62 5 2.62a1.51 1.51 0 0 0 1.56-.1 1.53 1.53 0 0 0 .63-1.44l-.84-6 4-4.29a1.5 1.5 0 0 0 .4-1.51z" fill="#0090ed"/><path d="m147 15.61a1.48 1.48 0 0 0 -1.16-1l-5.58-1-2.63-5.28a1.5 1.5 0 0 0 -2.68 0l-2.63 5.28-5.57 1a1.48 1.48 0 0 0 -1.17 1 1.53 1.53 0 0 0 .32 1.5l4 4.29-.83 6a1.49 1.49 0 0 0 1.49 1.71 1.44 1.44 0 0 0 .69-.17l5-2.62 5 2.62a1.5 1.5 0 0 0 2.18-1.54l-.83-6 4-4.29a1.51 1.51 0 0 0 .4-1.5z" fill="#0df"/><g clip-path="url(#a)"><path d="m124.24 109.74a1.48 1.48 0 0 0 -1.16-1l-5.57-1-2.63-5.28a1.5 1.5 0 0 0 -2.69 0l-2.63 5.28-5.57 1a1.5 1.5 0 0 0 -.84 2.5l4 4.29-.84 6a1.5 1.5 0 0 0 1.49 1.71 1.38 1.38 0 0 0 .69-.17l5-2.62 5 2.62a1.5 1.5 0 0 0 2.18-1.54l-.83-6 4-4.29a1.5 1.5 0 0 0 .4-1.5z" fill="#00b3f4"/><path d="m148.82 109.39a1.5 1.5 0 0 0 -1.16-1l-5.58-1-2.62-5.28a1.5 1.5 0 0 0 -2.69 0l-2.63 5.28-5.57 1a1.5 1.5 0 0 0 -.84 2.5l4 4.29-.83 6a1.48 1.48 0 0 0 .62 1.43 1.53 1.53 0 0 0 .87.28 1.45 1.45 0 0 0 .69-.18l5-2.62 5 2.62a1.5 1.5 0 0 0 2.18-1.54l-.83-5.95 4-4.29a1.5 1.5 0 0 0 .39-1.54z" fill="#00b3f4"/><path d="m161.75 107.31a1.47 1.47 0 0 0 -1.16-1l-5.57-1-2.63-5.31a1.5 1.5 0 0 0 -2.69 0l-2.63 5.28-5.57 1a1.53 1.53 0 0 0 -1.17 1 1.51 1.51 0 0 0 .33 1.5l4 4.29-.83 6a1.5 1.5 0 0 0 1.49 1.71 1.41 1.41 0 0 0 .69-.17l5-2.62 5 2.62a1.5 1.5 0 0 0 2.18-1.54l-.83-6 4-4.29a1.5 1.5 0 0 0 .39-1.47z" fill="#0df"/><path d="m139.18 105.88a1.53 1.53 0 0 0 -1.16-1l-5.58-1-2.63-5.28a1.5 1.5 0 0 0 -2.69 0l-2.63 5.28-5.57 1a1.5 1.5 0 0 0 -.84 2.5l4 4.3-.83 5.95a1.48 1.48 0 0 0 .62 1.43 1.45 1.45 0 0 0 .86.28 1.57 1.57 0 0 0 .7-.17l5-2.63 5 2.63a1.51 1.51 0 0 0 1.57-.11 1.48 1.48 0 0 0 .62-1.43l-.83-5.95 4-4.3a1.5 1.5 0 0 0 .39-1.5z" fill="#0090ed"/><path d="m154.3 116.29a1.52 1.52 0 0 0 -1.16-1l-5.58-1-2.62-5.29a1.51 1.51 0 0 0 -1.35-.83 1.49 1.49 0 0 0 -1.34.83l-2.63 5.28-5.57 1a1.52 1.52 0 0 0 -1.17 1 1.5 1.5 0 0 0 .33 1.5l4 4.3-.83 5.95a1.49 1.49 0 0 0 1.49 1.71 1.56 1.56 0 0 0 .69-.17l5-2.63 5 2.63a1.5 1.5 0 0 0 2.18-1.54l-.83-5.95 4-4.29a1.52 1.52 0 0 0 .39-1.5z" fill="#00b3f4"/><path d="m173.15 113a1.52 1.52 0 0 0 -1.16-1l-5.58-1-2.63-5.28a1.5 1.5 0 0 0 -2.68 0l-2.63 5.28-5.57 1a1.52 1.52 0 0 0 -1.17 1 1.5 1.5 0 0 0 .33 1.5l4 4.3-.83 6a1.49 1.49 0 0 0 1.49 1.71 1.56 1.56 0 0 0 .69-.17l5-2.63 5 2.63a1.5 1.5 0 0 0 2.18-1.54l-.83-6 4-4.29a1.52 1.52 0 0 0 .39-1.51z" fill="#0090ed"/><path d="m113.09 104.46a1.47 1.47 0 0 0 -1.16-1l-5.57-1-2.63-5.28a1.5 1.5 0 0 0 -2.69 0l-2.63 5.28-5.57 1a1.47 1.47 0 0 0 -1.16 1 1.5 1.5 0 0 0 .32 1.54l4 4.29-.83 6a1.49 1.49 0 0 0 1.48 1.71 1.45 1.45 0 0 0 .7-.17l5-2.62 5 2.62a1.51 1.51 0 0 0 2.19-1.54l-.84-6 4-4.29a1.5 1.5 0 0 0 .39-1.54z" fill="#0df"/><path d="m107 115.2a1.5 1.5 0 0 0 -1.16-1l-5.58-1-2.63-5.28a1.5 1.5 0 0 0 -2.69 0l-2.62 5.28-5.58 1a1.5 1.5 0 0 0 -.84 2.5l4 4.29-.83 6a1.49 1.49 0 0 0 1.49 1.71 1.44 1.44 0 0 0 .69-.17l5-2.62 5 2.62a1.5 1.5 0 0 0 2.18-1.54l-.83-6 4-4.29a1.5 1.5 0 0 0 .4-1.5z" fill="#00b3f4"/><path d="m125.37 115.42a1.48 1.48 0 0 0 -1.16-1l-5.58-1-2.63-5.28a1.5 1.5 0 0 0 -2.68 0l-2.63 5.28-5.57 1a1.5 1.5 0 0 0 -.84 2.51l4 4.29-.83 6a1.49 1.49 0 0 0 1.49 1.71 1.44 1.44 0 0 0 .69-.17l5-2.62 5 2.62a1.5 1.5 0 0 0 2.18-1.54l-.83-6 4-4.29a1.51 1.51 0 0 0 .39-1.51z" fill="#0090ed"/><path d="m138.3 113.33a1.52 1.52 0 0 0 -1.16-1l-5.58-1-2.62-5.28a1.51 1.51 0 0 0 -1.35-.83 1.49 1.49 0 0 0 -1.34.83l-2.63 5.28-5.57 1a1.52 1.52 0 0 0 -1.17 1 1.5 1.5 0 0 0 .33 1.5l4 4.3-.83 6a1.49 1.49 0 0 0 1.49 1.71 1.56 1.56 0 0 0 .69-.17l5-2.63 5 2.63a1.5 1.5 0 0 0 2.18-1.54l-.83-6 4-4.29a1.52 1.52 0 0 0 .39-1.51z" fill="#0df"/><path d="m180.52 110.12a1.51 1.51 0 0 0 -1.17-1l-5.57-1-2.65-5.27a1.49 1.49 0 0 0 -1.34-.83 1.47 1.47 0 0 0 -1.34.84l-2.62 5.28-5.57 1a1.51 1.51 0 0 0 -.83 2.51l4 4.28-.81 6a1.51 1.51 0 0 0 .62 1.44 1.51 1.51 0 0 0 1.56.1l5-2.64 5 2.61a1.51 1.51 0 0 0 2.18-1.55l-.85-5.94 4-4.31a1.5 1.5 0 0 0 .39-1.52z" fill="#00b3f4"/><path d="m205.09 109.71a1.47 1.47 0 0 0 -1.16-1l-5.58-1-2.64-5.27a1.5 1.5 0 0 0 -2.69 0l-2.61 5.29-5.57 1a1.5 1.5 0 0 0 -.84 2.5l4 4.29-.82 6a1.51 1.51 0 0 0 .63 1.43 1.53 1.53 0 0 0 .87.28 1.45 1.45 0 0 0 .69-.18l5-2.64 5.05 2.62a1.51 1.51 0 0 0 2.18-1.55l-.85-5.95 4-4.3a1.48 1.48 0 0 0 .34-1.52z" fill="#00b3f4"/><path d="m218 107.59a1.51 1.51 0 0 0 -1.16-1l-5.58-1-2.64-5.27a1.51 1.51 0 0 0 -1.35-.83 1.48 1.48 0 0 0 -1.34.84l-2.62 5.28-5.57 1a1.51 1.51 0 0 0 -1.16 1 1.48 1.48 0 0 0 .33 1.49l4 4.29-.82 5.95a1.49 1.49 0 0 0 .63 1.44 1.5 1.5 0 0 0 1.55.1l5-2.64 5 2.61a1.51 1.51 0 0 0 2.18-1.55l-.85-5.94 4-4.31a1.5 1.5 0 0 0 .4-1.46z" fill="#0df"/><path d="m195.44 106.22a1.49 1.49 0 0 0 -1.16-1l-5.58-1-2.64-5.22a1.51 1.51 0 0 0 -2.69 0l-2.62 5.29-5.56 1a1.5 1.5 0 0 0 -1.17 1 1.53 1.53 0 0 0 .33 1.5l4 4.28-.82 6a1.51 1.51 0 0 0 .63 1.43 1.51 1.51 0 0 0 1.56.1l5-2.64 5 2.61a1.5 1.5 0 0 0 2.28-1.57l-.84-6 4-4.3a1.52 1.52 0 0 0 .28-1.48z" fill="#0090ed"/><path d="m210.59 116.6a1.48 1.48 0 0 0 -1.16-1l-5.58-1-2.64-5.27a1.5 1.5 0 0 0 -2.69 0l-2.62 5.29-5.56 1a1.5 1.5 0 0 0 -1.17 1 1.52 1.52 0 0 0 .33 1.5l4 4.29-.82 5.95a1.51 1.51 0 0 0 .63 1.43 1.46 1.46 0 0 0 1.56.1l5-2.64 5 2.62a1.51 1.51 0 0 0 2.18-1.55l-.84-5.95 4-4.3a1.5 1.5 0 0 0 .38-1.47z" fill="#00b3f4"/><path d="m229.43 113.26a1.5 1.5 0 0 0 -1.16-1l-5.58-1-2.64-5.26a1.5 1.5 0 0 0 -2.69 0l-2.62 5.29-5.56 1a1.5 1.5 0 0 0 -.84 2.5l4 4.29-.82 6a1.53 1.53 0 0 0 .63 1.44 1.51 1.51 0 0 0 .86.27 1.57 1.57 0 0 0 .7-.17l5-2.64 5 2.61a1.51 1.51 0 0 0 2.29-1.59l-.84-6 4-4.3a1.5 1.5 0 0 0 .27-1.44z" fill="#0090ed"/><path d="m163.24 115.62a1.47 1.47 0 0 0 -1.16-1l-5.58-1-2.64-5.28a1.46 1.46 0 0 0 -1.34-.82 1.5 1.5 0 0 0 -1.35.83l-2.61 5.29-5.57 1a1.5 1.5 0 0 0 -.83 2.5l4 4.28-.81 6a1.49 1.49 0 0 0 1.49 1.7 1.41 1.41 0 0 0 .69-.17l5-2.64 5.05 2.61a1.5 1.5 0 0 0 2.18-1.54l-.85-5.95 4-4.3a1.49 1.49 0 0 0 .33-1.51z" fill="#00b3f4"/><path d="m181.66 115.79a1.5 1.5 0 0 0 -1.17-1l-5.57-1-2.65-5.28a1.49 1.49 0 0 0 -1.34-.83 1.5 1.5 0 0 0 -1.34.84l-2.59 5.32-5.57 1a1.48 1.48 0 0 0 -1.16 1 1.5 1.5 0 0 0 .33 1.5l4 4.28-.81 6a1.48 1.48 0 0 0 .62 1.43 1.54 1.54 0 0 0 .87.27 1.41 1.41 0 0 0 .69-.17l5-2.64 5 2.61a1.5 1.5 0 0 0 2.18-1.54l-.85-6 4-4.3a1.52 1.52 0 0 0 .36-1.49z" fill="#0090ed"/><path d="m194.58 113.68a1.48 1.48 0 0 0 -1.16-1l-5.58-1-2.64-5.27a1.5 1.5 0 0 0 -2.69 0l-2.61 5.29-5.57 1a1.5 1.5 0 0 0 -.84 2.5l4 4.29-.82 6a1.53 1.53 0 0 0 .63 1.44 1.52 1.52 0 0 0 .87.27 1.56 1.56 0 0 0 .69-.17l5-2.64 5 2.61a1.49 1.49 0 0 0 1.56-.11 1.53 1.53 0 0 0 .62-1.44l-.85-5.94 4-4.31a1.48 1.48 0 0 0 .39-1.52z" fill="#0df"/></g><path d="m159.69 81.08a2.18 2.18 0 0 0 -1.7-1.47l-8.17-1.46-3.82-7.73a2.2 2.2 0 0 0 -3.94 0l-3.85 7.73-8.21 1.46a2.21 2.21 0 0 0 -1.23 3.67l5.86 6.29-1.22 8.72a2.2 2.2 0 0 0 2.18 2.51 2.16 2.16 0 0 0 1-.25l7.41-3.85 7.38 3.85a2.22 2.22 0 0 0 2.29-.15 2.18 2.18 0 0 0 .91-2.11l-1.22-8.72 5.86-6.29a2.19 2.19 0 0 0 .47-2.2z" fill="#fff"/></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/trailhead/card-illo-lockwise.svg b/browser/components/newtab/data/content/assets/trailhead/card-illo-lockwise.svg
new file mode 100644
index 0000000000..8ab51d9721
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/trailhead/card-illo-lockwise.svg
@@ -0,0 +1,5 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+
+<svg viewBox="0 0 288 180" xmlns="http://www.w3.org/2000/svg"><circle cx="144" cy="90" fill="#bfbfc9" opacity=".15" r="72"/><rect fill="#0df" height="15.49" rx=".5" width="48.16" x="43.04" y="82.03"/><path d="m88.11 79h-42.11a7.22 7.22 0 0 0 -7.2 7.2v6.53a7.22 7.22 0 0 0 7.2 7.2h42.11a7.22 7.22 0 0 0 7.2-7.2v-6.55a7.22 7.22 0 0 0 -7.2-7.18zm-29.91 11.39a.4.4 0 0 1 .19.58l-.89 1.51a.4.4 0 0 1 -.27.19.42.42 0 0 1 -.33-.08l-1.9-1.47.3 2.44a.41.41 0 0 1 -.4.46h-1.75a.41.41 0 0 1 -.31-.14.46.46 0 0 1 -.1-.32l.31-2.46-2 1.5a.42.42 0 0 1 -.33.07.45.45 0 0 1 -.27-.2l-.83-1.47a.38.38 0 0 1 0-.33.38.38 0 0 1 .22-.24l2.28-1-2.28-1a.39.39 0 0 1 -.23-.24.45.45 0 0 1 0-.34l.87-1.48a.4.4 0 0 1 .27-.19.48.48 0 0 1 .33.07l2 1.49-.31-2.43a.46.46 0 0 1 .1-.32.41.41 0 0 1 .31-.14h1.74a.41.41 0 0 1 .4.46l-.32 2.46 2-1.47a.44.44 0 0 1 .33-.08.45.45 0 0 1 .27.2l.85 1.51a.42.42 0 0 1 0 .33.39.39 0 0 1 -.23.24l-2.28 1zm13 0a.38.38 0 0 1 .23.25.42.42 0 0 1 0 .33l-.89 1.51a.4.4 0 0 1 -.28.19.41.41 0 0 1 -.32-.08l-1.94-1.47.3 2.44a.41.41 0 0 1 -.1.32.41.41 0 0 1 -.3.14h-1.71a.41.41 0 0 1 -.41-.46l.31-2.46-2 1.5a.42.42 0 0 1 -.33.07.45.45 0 0 1 -.27-.2l-.84-1.47a.47.47 0 0 1 0-.33.39.39 0 0 1 .23-.24l2.28-1-2.28-1a.39.39 0 0 1 -.23-.24.45.45 0 0 1 0-.34l.87-1.48a.4.4 0 0 1 .27-.19.45.45 0 0 1 .32.07l2 1.49-.31-2.43a.41.41 0 0 1 .41-.46h1.74a.41.41 0 0 1 .3.14.41.41 0 0 1 .1.32l-.35 2.46 2-1.47a.42.42 0 0 1 .33-.08.45.45 0 0 1 .27.2l.85 1.51a.47.47 0 0 1 0 .33.42.42 0 0 1 -.23.24l-2.28 1zm13 0a.36.36 0 0 1 .23.25.38.38 0 0 1 0 .33l-.9 1.51a.4.4 0 0 1 -.27.19.41.41 0 0 1 -.32-.08l-1.92-1.47.31 2.44a.41.41 0 0 1 -.33.44h-1.78a.41.41 0 0 1 -.3-.14.41.41 0 0 1 -.1-.32l.31-2.46-2 1.5a.41.41 0 0 1 -.6-.13l-.84-1.45a.38.38 0 0 1 0-.33.39.39 0 0 1 .23-.24l2.27-1-2.28-1a.4.4 0 0 1 -.22-.24.41.41 0 0 1 0-.34l.87-1.48a.36.36 0 0 1 .27-.19.45.45 0 0 1 .32.07l2 1.49-.3-2.43a.41.41 0 0 1 .1-.32.41.41 0 0 1 .3-.14h1.75a.41.41 0 0 1 .41.46l-.31 2.44 2-1.47a.42.42 0 0 1 .33-.08.45.45 0 0 1 .27.2l.84 1.51a.38.38 0 0 1 0 .33.39.39 0 0 1 -.23.24l-2.27 1z" fill="#0090ed"/><path d="m161.09 121.72a5.24 5.24 0 0 0 1.22-3.34v-63.76a5.33 5.33 0 0 0 -5.31-5.32h-90.33a5.34 5.34 0 0 0 -5.32 5.32v63.76a5.24 5.24 0 0 0 1.22 3.34l-11.84 2v5.28h122.21v-5.3z" fill="#9f9fad"/><path d="m121.58 59.93-54.91 54.91a1.77 1.77 0 0 0 1.77 1.77h86.79a1.78 1.78 0 0 0 1.77-1.77v-54.91z" fill="#592acb"/><path d="m66.67 59.93v54.91l54.91-54.91z" fill="#6736d8"/><path d="m155.23 54.62h-86.79a1.77 1.77 0 0 0 -1.77 1.77v3.54h90.33v-3.54a1.78 1.78 0 0 0 -1.77-1.77z" fill="#592acb"/><path d="m155.39 123h-86.79a.89.89 0 1 1 0-1.77h86.79a.89.89 0 0 1 0 1.77z" fill="#8f8f9d"/><path d="m105.3 125.33h12.4" fill="none" stroke="#80808e" stroke-linecap="round" stroke-linejoin="round"/><path d="m129.28 81.25a148.43 148.43 0 0 0 -12.79-12.79 7.43 7.43 0 0 0 -9.46 0 148.32 148.32 0 0 0 -12.78 12.8 7.43 7.43 0 0 0 0 9.45 151.34 151.34 0 0 0 12.75 12.79 7.43 7.43 0 0 0 9.47 0c2.35-2.13 4.5-4.18 6.57-6.28a2.15 2.15 0 0 0 -.16-2.94l-6.33-5.92a7.3 7.3 0 0 0 2.45-5.76 7.4 7.4 0 0 0 -6.94-7 7.3 7.3 0 0 0 -5.46 2 7.41 7.41 0 0 0 -2.29 5.34 7.33 7.33 0 0 0 2.44 5.46l-2.3 2.08a1.85 1.85 0 0 0 2.55 2.7l2.54-2.31.07-.06a3.49 3.49 0 0 0 -.24-5.14 3.64 3.64 0 1 1 6-2.93 3.59 3.59 0 0 1 -1.37 2.92 3.54 3.54 0 0 0 -1.26 2.55 3.49 3.49 0 0 0 1 2.6l5.35 5c-1.64 1.62-3.33 3.22-5.15 4.86a3.78 3.78 0 0 1 -4.54 0 146.74 146.74 0 0 1 -12.4-12.41 3.78 3.78 0 0 1 0-4.55 146.74 146.74 0 0 1 12.47-12.47 3.8 3.8 0 0 1 4.54 0 147 147 0 0 1 12.48 12.48 3.78 3.78 0 0 1 0 4.54c-.64.72-1.28 1.42-1.9 2.1a1.85 1.85 0 0 0 2.73 2.51c.63-.69 1.29-1.41 1.95-2.15a7.43 7.43 0 0 0 .01-9.47z" fill="#fff"/><rect fill="#ff298a" height="16.85" rx="5.4" width="49.79" x="147.77" y="72.61"/><path d="m194.09 70.83h-42.09a7.22 7.22 0 0 0 -7.2 7.2v6.53a7.22 7.22 0 0 0 7.2 7.2h42.13a7.22 7.22 0 0 0 7.2-7.2v-6.56a7.22 7.22 0 0 0 -7.24-7.17zm-29.91 11.41a.39.39 0 0 1 .23.24.37.37 0 0 1 0 .34l-.89 1.5a.45.45 0 0 1 -.27.2.43.43 0 0 1 -.33-.08l-1.92-1.44.3 2.45a.42.42 0 0 1 -.09.32.44.44 0 0 1 -.31.13h-1.74a.4.4 0 0 1 -.3-.13.39.39 0 0 1 -.1-.32l.3-2.47-2 1.5a.37.37 0 0 1 -.32.07.36.36 0 0 1 -.27-.19l-.85-1.51a.38.38 0 0 1 0-.33.39.39 0 0 1 .23-.24l2.27-.95-2.28-1a.39.39 0 0 1 -.22-.25.38.38 0 0 1 0-.33l.87-1.48a.4.4 0 0 1 .27-.19.38.38 0 0 1 .33.07l2 1.49-.3-2.43a.37.37 0 0 1 .1-.32.37.37 0 0 1 .3-.14h1.74a.41.41 0 0 1 .31.14.4.4 0 0 1 .09.32l-.3 2.44 2-1.48a.41.41 0 0 1 .32-.07.4.4 0 0 1 .27.2l.85 1.5a.41.41 0 0 1 0 .34.42.42 0 0 1 -.23.24l-2.27.94zm13 0a.39.39 0 0 1 .23.24.41.41 0 0 1 0 .34l-.89 1.5a.45.45 0 0 1 -.27.2.42.42 0 0 1 -.33-.08l-1.92-1.44.3 2.45a.39.39 0 0 1 -.1.32.4.4 0 0 1 -.3.13h-1.74a.44.44 0 0 1 -.31-.13.47.47 0 0 1 -.1-.32l.31-2.47-2 1.5a.38.38 0 0 1 -.33.07.4.4 0 0 1 -.27-.19l-.84-1.51a.38.38 0 0 1 0-.33.38.38 0 0 1 .22-.24l2.28-.95-2.28-1a.43.43 0 0 1 -.23-.25.42.42 0 0 1 0-.33l.87-1.48a.4.4 0 0 1 .27-.19.39.39 0 0 1 .33.07l2 1.49-.31-2.43a.44.44 0 0 1 .1-.32.41.41 0 0 1 .31-.14h1.74a.37.37 0 0 1 .3.14.37.37 0 0 1 .1.32l-.3 2.44 2-1.48a.44.44 0 0 1 .33-.07.42.42 0 0 1 .27.2l.85 1.5a.5.5 0 0 1 0 .34.42.42 0 0 1 -.23.24l-2.28.94zm13 0a.39.39 0 0 1 .23.24.45.45 0 0 1 0 .34l-.89 1.5a.45.45 0 0 1 -.28.2.41.41 0 0 1 -.32-.08l-1.87-1.44.3 2.45a.42.42 0 0 1 -.1.32.43.43 0 0 1 -.3.13h-1.74a.44.44 0 0 1 -.31-.13.42.42 0 0 1 -.1-.32l.31-2.47-2 1.5a.38.38 0 0 1 -.33.07.4.4 0 0 1 -.27-.19l-.85-1.51a.47.47 0 0 1 0-.33.39.39 0 0 1 .23-.24l2.27-.95-2.27-1a.43.43 0 0 1 -.23-.25.42.42 0 0 1 0-.33l.87-1.48a.4.4 0 0 1 .27-.19.37.37 0 0 1 .32.07l2 1.49-.31-2.43a.4.4 0 0 1 .1-.32.41.41 0 0 1 .31-.14h1.78a.41.41 0 0 1 .4.46l-.4 2.41 2-1.48a.41.41 0 0 1 .6.13l.84 1.5a.4.4 0 0 1 -.19.58l-2.28.94z" fill="#ffd567"/><rect fill="#ffbdc5" height="15.78" rx="7.89" width="47.56" x="121.1" y="117.5"/><path d="m166.65 115h-42.13a7.22 7.22 0 0 0 -7.2 7.2v6.53a7.22 7.22 0 0 0 7.2 7.2h42.13a7.22 7.22 0 0 0 7.2-7.2v-6.53a7.22 7.22 0 0 0 -7.2-7.2zm-29.91 11.4a.39.39 0 0 1 .23.24.45.45 0 0 1 0 .34l-.89 1.5a.45.45 0 0 1 -.28.2.41.41 0 0 1 -.32-.08l-1.91-1.48.3 2.45a.42.42 0 0 1 -.1.32.42.42 0 0 1 -.3.13h-1.74a.44.44 0 0 1 -.31-.13.47.47 0 0 1 -.1-.32l.31-2.47-2 1.5a.38.38 0 0 1 -.33.07.4.4 0 0 1 -.27-.19l-.85-1.51a.47.47 0 0 1 0-.33.39.39 0 0 1 .23-.24l2.28-1-2.28-1a.43.43 0 0 1 -.23-.25.42.42 0 0 1 0-.33l.87-1.48a.4.4 0 0 1 .27-.19.37.37 0 0 1 .32.07l2 1.49-.31-2.43a.46.46 0 0 1 .1-.32.41.41 0 0 1 .31-.14h1.74a.39.39 0 0 1 .3.14.37.37 0 0 1 .1.32l-.3 2.44 2-1.48a.43.43 0 0 1 .33-.07.42.42 0 0 1 .27.2l.85 1.51a.47.47 0 0 1 0 .33.42.42 0 0 1 -.23.24l-2.28.94zm13 0a.42.42 0 0 1 .23.24.45.45 0 0 1 0 .34l-.9 1.5a.4.4 0 0 1 -.27.2.41.41 0 0 1 -.32-.08l-1.92-1.48.31 2.45a.42.42 0 0 1 -.1.32.43.43 0 0 1 -.3.13h-1.75a.43.43 0 0 1 -.3-.13.42.42 0 0 1 -.1-.32l.31-2.47-2 1.5a.39.39 0 0 1 -.33.07.4.4 0 0 1 -.27-.19l-.85-1.51a.42.42 0 0 1 0-.33.39.39 0 0 1 .23-.24l2.27-1-2.28-1a.45.45 0 0 1 -.22-.25.39.39 0 0 1 0-.33l.87-1.48a.38.38 0 0 1 .27-.19.37.37 0 0 1 .32.07l2 1.49-.31-2.43a.41.41 0 0 1 .4-.46h1.75a.41.41 0 0 1 .4.46l-.31 2.44 2-1.48a.41.41 0 0 1 .6.13l.84 1.51a.38.38 0 0 1 0 .33.4.4 0 0 1 -.22.24l-2.28.94zm13 0a.37.37 0 0 1 .23.24.41.41 0 0 1 0 .34l-.9 1.5a.45.45 0 0 1 -.27.2.41.41 0 0 1 -.32-.08l-1.92-1.48.31 2.45a.47.47 0 0 1 -.1.32.44.44 0 0 1 -.31.13h-1.74a.42.42 0 0 1 -.3-.13.39.39 0 0 1 -.1-.32l.31-2.47-2 1.5a.4.4 0 0 1 -.33.07.36.36 0 0 1 -.27-.19l-.85-1.51a.38.38 0 0 1 0-.33.39.39 0 0 1 .23-.24l2.27-1-2.28-1a.42.42 0 0 1 -.22-.25.38.38 0 0 1 0-.33l.87-1.48a.4.4 0 0 1 .28-.19.37.37 0 0 1 .32.07l2 1.49-.3-2.43a.38.38 0 0 1 .1-.32.39.39 0 0 1 .3-.14h1.74a.41.41 0 0 1 .31.14.44.44 0 0 1 .1.32l-.31 2.44 2-1.48a.41.41 0 0 1 .32-.07.37.37 0 0 1 .27.2l.85 1.51a.38.38 0 0 1 0 .33.42.42 0 0 1 -.23.24l-2.27.94z" fill="#ff298a"/><path d="m222.84 50.27h-37.58a5.38 5.38 0 0 0 -5.37 5.37v68a5.38 5.38 0 0 0 5.37 5.37h37.58a5.39 5.39 0 0 0 5.37-5.37v-68a5.39 5.39 0 0 0 -5.37-5.37z" fill="#bfbfc9"/><path d="m185.26 98.59v21.47a1.79 1.79 0 0 0 1.79 1.79h34a1.79 1.79 0 0 0 1.79-1.79v-59.06z" fill="#f11f89"/><path d="m185.26 61.01v37.58l37.58-37.58z" fill="#ff298a"/><path d="m221.05 55.64h-34a1.79 1.79 0 0 0 -1.79 1.79v3.57h37.58v-3.57a1.79 1.79 0 0 0 -1.79-1.79z" fill="#f11f89"/><circle cx="195.1" cy="113.8" fill="#ffd567" r="2.68"/><circle cx="204.05" cy="113.8" fill="#ff8a50" r="2.68"/><circle cx="212.99" cy="113.8" fill="#7542e5" r="2.68"/><path d="m201.69 125.43h5.04" fill="none" stroke="#9f9fad" stroke-linecap="round" stroke-linejoin="round"/><path d="m215.38 83.72a96.45 96.45 0 0 0 -8.28-8.27 4.8 4.8 0 0 0 -6.12 0 97.91 97.91 0 0 0 -8.27 8.28 4.82 4.82 0 0 0 0 6.12 99.41 99.41 0 0 0 8.29 8.27 4.8 4.8 0 0 0 6.13 0c1.52-1.37 2.91-2.7 4.25-4.06a1.38 1.38 0 0 0 -.11-1.9l-4.09-3.83a4.7 4.7 0 0 0 1.57-3.72 4.79 4.79 0 0 0 -4.49-4.61 4.76 4.76 0 0 0 -3.44 8.29l-1.49 1.34a1.2 1.2 0 0 0 1.67 1.81l1.59-1.44a2.24 2.24 0 0 0 .66-1.69 2.28 2.28 0 0 0 -.81-1.64 2.35 2.35 0 1 1 3 0 2.25 2.25 0 0 0 -.16 3.33l3.46 3.24c-1.06 1-2.16 2.08-3.33 3.14a2.45 2.45 0 0 1 -2.94 0 94.55 94.55 0 0 1 -8.07-8.07 2.45 2.45 0 0 1 0-2.94 93.12 93.12 0 0 1 8.07-8.07 2.45 2.45 0 0 1 2.94 0 94.67 94.67 0 0 1 8.08 8.07 2.46 2.46 0 0 1 0 2.94l-1.23 1.36a1.19 1.19 0 0 0 .07 1.69 1.2 1.2 0 0 0 1.7-.07c.4-.44.83-.91 1.25-1.39a4.8 4.8 0 0 0 .1-6.18z" fill="#fff"/></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/trailhead/card-illo-mobile.svg b/browser/components/newtab/data/content/assets/trailhead/card-illo-mobile.svg
new file mode 100644
index 0000000000..dcec93678c
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/trailhead/card-illo-mobile.svg
@@ -0,0 +1,5 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+
+<svg viewBox="0 0 288 180" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><radialGradient id="a" cx="134.01" cy="80.95" gradientUnits="userSpaceOnUse" r="46.58"><stop offset=".11" stop-color="#fff44f"/><stop offset=".46" stop-color="#ff980e"/><stop offset=".62" stop-color="#ff5634"/><stop offset=".72" stop-color="#ff3647"/><stop offset=".9" stop-color="#e31587"/></radialGradient><radialGradient id="b" cx="134.01" cy="80.93" r="46.58" xlink:href="#a"/><linearGradient id="c" gradientUnits="userSpaceOnUse" x1="154.94" x2="132.41" y1="77.01" y2="98.75"><stop offset=".05" stop-color="#fff44f"/><stop offset=".11" stop-color="#ffe847"/><stop offset=".22" stop-color="#ffc830"/><stop offset=".37" stop-color="#ff980e"/><stop offset=".4" stop-color="#ff8b16"/><stop offset=".46" stop-color="#ff672a"/><stop offset=".53" stop-color="#ff3647"/><stop offset=".7" stop-color="#e31587"/></linearGradient><radialGradient id="d" cx="153.9" cy="75.78" gradientUnits="userSpaceOnUse" r="28.29"><stop offset=".13" stop-color="#ffbd4f"/><stop offset=".19" stop-color="#ffac31"/><stop offset=".25" stop-color="#ff9d17"/><stop offset=".28" stop-color="#ff980e"/><stop offset=".4" stop-color="#ff563b"/><stop offset=".47" stop-color="#ff3750"/><stop offset=".71" stop-color="#f5156c"/><stop offset=".78" stop-color="#eb0878"/><stop offset=".86" stop-color="#e50080"/></radialGradient><radialGradient id="e" cx="143.56" cy="87.35" gradientUnits="userSpaceOnUse" r="28.29"><stop offset=".3" stop-color="#960e18"/><stop offset=".35" stop-color="#b11927" stop-opacity=".74"/><stop offset=".43" stop-color="#db293d" stop-opacity=".34"/><stop offset=".5" stop-color="#f5334b" stop-opacity=".09"/><stop offset=".53" stop-color="#ff3750" stop-opacity="0"/></radialGradient><radialGradient id="f" cx="146.97" cy="69.36" gradientUnits="userSpaceOnUse" r="20.49"><stop offset=".13" stop-color="#fff44f"/><stop offset=".25" stop-color="#ffdc3e"/><stop offset=".51" stop-color="#ff9d12"/><stop offset=".53" stop-color="#ff980e"/></radialGradient><radialGradient id="g" cx="140.43" cy="94.74" gradientUnits="userSpaceOnUse" r="13.47"><stop offset=".35" stop-color="#3a8ee6"/><stop offset=".47" stop-color="#5c79f0"/><stop offset=".67" stop-color="#9059ff"/><stop offset="1" stop-color="#c139e6"/></radialGradient><radialGradient id="h" cx="143.94" cy="84.04" gradientTransform="matrix(.97 -.24 .28 1.14 -19.11 22.21)" gradientUnits="userSpaceOnUse" r="7.14"><stop offset=".21" stop-color="#9059ff" stop-opacity="0"/><stop offset=".28" stop-color="#8c4ff3" stop-opacity=".06"/><stop offset=".75" stop-color="#7716a8" stop-opacity=".45"/><stop offset=".97" stop-color="#6e008b" stop-opacity=".6"/></radialGradient><radialGradient id="i" cx="141.13" cy="92.8" r=".22" xlink:href="#g"/><radialGradient id="j" cx="141.19" cy="92.72" gradientTransform="matrix(.97 -.24 .28 1.14 -21.58 20.36)" r=".08" xlink:href="#h"/><radialGradient id="k" cx="143.2" cy="74.63" gradientUnits="userSpaceOnUse" r="9.69"><stop offset="0" stop-color="#ffe226"/><stop offset=".12" stop-color="#ffdb27"/><stop offset=".3" stop-color="#ffc82a"/><stop offset=".5" stop-color="#ffa930"/><stop offset=".73" stop-color="#ff7e37"/><stop offset=".79" stop-color="#ff7139"/></radialGradient><radialGradient id="l" cx="150.82" cy="68.48" r="41.34" xlink:href="#a"/><radialGradient id="m" cx="146.9" cy="73.07" gradientTransform="matrix(.1 .99 -.65 .07 179.21 -78.04)" gradientUnits="userSpaceOnUse" r="30.28"><stop offset="0" stop-color="#fff44f"/><stop offset=".06" stop-color="#ffe847"/><stop offset=".17" stop-color="#ffc830"/><stop offset=".3" stop-color="#ff980e"/><stop offset=".36" stop-color="#ff8b16"/><stop offset=".45" stop-color="#ff672a"/><stop offset=".57" stop-color="#ff3647"/><stop offset=".74" stop-color="#e31587"/></radialGradient><radialGradient id="n" cx="142.98" cy="78.21" gradientUnits="userSpaceOnUse" r="25.81"><stop offset=".14" stop-color="#fff44f"/><stop offset=".48" stop-color="#ff980e"/><stop offset=".59" stop-color="#ff5634"/><stop offset=".66" stop-color="#ff3647"/><stop offset=".9" stop-color="#e31587"/></radialGradient><radialGradient id="o" cx="149.79" cy="79.73" gradientUnits="userSpaceOnUse" r="28.25"><stop offset=".09" stop-color="#fff44f"/><stop offset=".23" stop-color="#ffe141"/><stop offset=".51" stop-color="#ffaf1e"/><stop offset=".63" stop-color="#ff980e"/></radialGradient><linearGradient id="p" gradientUnits="userSpaceOnUse" x1="154.67" x2="135.5" y1="76.9" y2="96.06"><stop offset=".17" stop-color="#fff44f" stop-opacity=".8"/><stop offset=".27" stop-color="#fff44f" stop-opacity=".63"/><stop offset=".49" stop-color="#fff44f" stop-opacity=".22"/><stop offset=".6" stop-color="#fff44f" stop-opacity="0"/></linearGradient><circle cx="144" cy="90" fill="#bfbfc9" opacity=".15" r="72"/><path d="m162.79 50.63h-37.58a5.39 5.39 0 0 0 -5.37 5.37v68a5.39 5.39 0 0 0 5.37 5.37h37.58a5.39 5.39 0 0 0 5.37-5.37v-68a5.39 5.39 0 0 0 -5.37-5.37z" fill="#bfbfc9"/><path d="m125.21 99v21.47a1.79 1.79 0 0 0 1.79 1.79h34a1.79 1.79 0 0 0 1.79-1.79v-59z" fill="#592acb"/><path d="m125.21 61.37v37.58l37.58-37.58z" fill="#6736d8"/><path d="m161 56h-34a1.79 1.79 0 0 0 -1.79 1.79v3.58h37.58v-3.58a1.79 1.79 0 0 0 -1.79-1.79z" fill="#592acb"/><circle cx="135.05" cy="114.16" fill="#ffd567" r="2.68"/><circle cx="144" cy="114.16" fill="#ff7139" r="2.68"/><circle cx="152.95" cy="114.16" fill="#ff298a" r="2.68"/><path d="m141.64 125.79h5.04" fill="none" stroke="#9f9fad" stroke-linecap="round" stroke-linejoin="round"/><path d="m138.06 99.33c.01.04.01.02 0 0z" fill="url(#b)"/><path d="m156.73 82.07a7.63 7.63 0 0 0 -2.73-3.44 14 14 0 0 1 1.38 4.12c-1.54-3.82-4.14-5.36-6.26-8.72-.11-.17-.22-.34-.32-.52a2.6 2.6 0 0 1 -.15-.28 2.43 2.43 0 0 1 -.2-.54s0 0 0 0a9.87 9.87 0 0 0 -4.67 7.54 6.77 6.77 0 0 0 -3.78 1.42 3.54 3.54 0 0 0 -.35-.26 6.32 6.32 0 0 1 0-3.32 10.11 10.11 0 0 0 -3.26 2.53c-.54-.68-.5-2.93-.47-3.4a2.25 2.25 0 0 0 -.45.24 9.08 9.08 0 0 0 -1.33 1.14 12 12 0 0 0 -1.26 1.51 11.43 11.43 0 0 0 -1.88 4.12.29.29 0 0 0 0 .09c0 .11-.12.71-.14.84a12.9 12.9 0 0 0 -.22 1.87v.07a13.57 13.57 0 0 0 26.94 2.3c0-.17 0-.35.06-.52a13.94 13.94 0 0 0 -.91-6.79zm-15.63 10.62.18.09z" fill="url(#c)"/><path d="m156.73 82.07a7.63 7.63 0 0 0 -2.73-3.44 14 14 0 0 1 1.38 4.12 12.32 12.32 0 0 1 -.42 9.16 11.69 11.69 0 0 1 -11.21 6.59 13.66 13.66 0 0 1 -13-11.09 6 6 0 0 1 .09-2.27 10 10 0 0 0 -.22 1.87v.07a13.57 13.57 0 0 0 26.94 2.3c0-.17 0-.35.06-.52a13.94 13.94 0 0 0 -.89-6.79z" fill="url(#d)"/><path d="m156.73 82.07a7.63 7.63 0 0 0 -2.73-3.44 14 14 0 0 1 1.38 4.12 12.32 12.32 0 0 1 -.42 9.16 11.69 11.69 0 0 1 -11.21 6.59 13.66 13.66 0 0 1 -13-11.09 6 6 0 0 1 .09-2.27 10 10 0 0 0 -.22 1.87v.07a13.57 13.57 0 0 0 26.94 2.3c0-.17 0-.35.06-.52a13.94 13.94 0 0 0 -.89-6.79z" fill="url(#e)"/><path d="m150.14 83.66a.27.27 0 0 1 .08.07 7.19 7.19 0 0 0 -1.22-1.65 6.85 6.85 0 0 1 -.59-9.39 9.87 9.87 0 0 0 -4.67 7.54 3.75 3.75 0 0 1 .48 0 6.85 6.85 0 0 1 5.92 3.43z" fill="url(#f)"/><path d="m144.2 84.51a3.28 3.28 0 0 1 -1.63 1.5c-3.86 0-4.48 2.33-4.48 2.33a5.73 5.73 0 0 0 3.19 4.44l.23.11.4.16a5.78 5.78 0 0 0 1.77.34 5.61 5.61 0 0 0 3.19-10.52 4.65 4.65 0 0 1 3.27.79 6.85 6.85 0 0 0 -5.94-3.47 3.75 3.75 0 0 0 -.48 0 6.77 6.77 0 0 0 -3.72 1.46c.21.18.44.41.94.9.9.91 3.26 1.84 3.26 1.96z" fill="url(#g)"/><path d="m144.2 84.51a3.28 3.28 0 0 1 -1.63 1.5c-3.86 0-4.48 2.33-4.48 2.33a5.73 5.73 0 0 0 3.19 4.44l.23.11.4.16a5.78 5.78 0 0 0 1.77.34 5.61 5.61 0 0 0 3.19-10.52 4.65 4.65 0 0 1 3.27.79 6.85 6.85 0 0 0 -5.94-3.47 3.75 3.75 0 0 0 -.48 0 6.77 6.77 0 0 0 -3.72 1.46c.21.18.44.41.94.9.9.91 3.26 1.84 3.26 1.96z" fill="url(#h)"/><path d="m141.1 92.69.19.1z" fill="url(#i)"/><path d="m141.1 92.69.19.1z" fill="url(#j)"/><path d="m139.35 81.2.28.19a6.32 6.32 0 0 1 0-3.32 10.11 10.11 0 0 0 -3.26 2.53 6.72 6.72 0 0 1 2.98.6z" fill="url(#k)"/><path d="m130.74 87.44a13.66 13.66 0 0 0 13 11.09 11.69 11.69 0 0 0 11.26-6.59 12.32 12.32 0 0 0 .42-9.16 9.14 9.14 0 0 1 -3.65 8.22c-4.87 4-9.53 2.39-10.48 1.75l-.19-.1a6.15 6.15 0 0 1 -3.76-6.16 3.49 3.49 0 0 1 -3.22-2 5.1 5.1 0 0 1 5-.2 6.78 6.78 0 0 0 5.09.2c0-.12-2.36-1.05-3.28-2-.5-.49-.73-.72-.94-.9a3.54 3.54 0 0 0 -.35-.26l-.28-.19a6.72 6.72 0 0 0 -3-.6c-.54-.68-.5-2.93-.47-3.4a2.25 2.25 0 0 0 -.45.24 9.08 9.08 0 0 0 -1.33 1.14 12 12 0 0 0 -1.26 1.51 11.43 11.43 0 0 0 -1.85 4.18 10 10 0 0 0 -.26 3.23z" fill="url(#l)"/><path d="m149 82.08a7.19 7.19 0 0 1 1.25 1.65 1.92 1.92 0 0 1 .21.16c3.07 2.84 1.46 6.85 1.34 7.13a9.14 9.14 0 0 0 3.62-8.25c-1.54-3.82-4.14-5.36-6.26-8.72-.11-.17-.22-.34-.32-.52a2.6 2.6 0 0 1 -.15-.28 2.43 2.43 0 0 1 -.2-.54s0 0 0 0a6.85 6.85 0 0 0 .51 9.37z" fill="url(#m)"/><path d="m150.43 83.89a1.92 1.92 0 0 0 -.21-.16.27.27 0 0 0 -.08-.07 4.65 4.65 0 0 0 -3.27-.79 5.61 5.61 0 0 1 -3.19 10.52 5.78 5.78 0 0 1 -1.77-.34l-.4-.16-.23-.11c1 .64 5.61 2.21 10.48-1.75.13-.29 1.74-4.3-1.33-7.14z" fill="url(#n)"/><path d="m138.09 88.34s.62-2.33 4.48-2.33a3.28 3.28 0 0 0 1.63-1.5 6.78 6.78 0 0 1 -5.09-.2 5.1 5.1 0 0 0 -5 .2 3.49 3.49 0 0 0 3.22 2 6.15 6.15 0 0 0 3.76 6.16l.18.09a5.73 5.73 0 0 1 -3.18-4.42z" fill="url(#o)"/><path d="m156.73 82.07a7.63 7.63 0 0 0 -2.73-3.44 14 14 0 0 1 1.38 4.12c-1.54-3.82-4.14-5.36-6.26-8.72-.11-.17-.22-.34-.32-.52a2.6 2.6 0 0 1 -.15-.28 2.43 2.43 0 0 1 -.2-.54s0 0 0 0a9.87 9.87 0 0 0 -4.67 7.54 3.75 3.75 0 0 1 .48 0 6.85 6.85 0 0 1 5.94 3.47 4.65 4.65 0 0 0 -3.27-.79 5.61 5.61 0 0 1 -3.19 10.52 5.78 5.78 0 0 1 -1.77-.34l-.4-.16-.23-.11-.19-.1.18.09a5.73 5.73 0 0 1 -3.19-4.44s.62-2.33 4.48-2.33a3.28 3.28 0 0 0 1.63-1.5c0-.12-2.36-1.05-3.28-2-.5-.49-.73-.72-.94-.9a3.54 3.54 0 0 0 -.35-.26 6.32 6.32 0 0 1 0-3.32 10.11 10.11 0 0 0 -3.26 2.53c-.54-.68-.5-2.93-.47-3.4a2.25 2.25 0 0 0 -.45.24 9.08 9.08 0 0 0 -1.33 1.14 12 12 0 0 0 -1.26 1.51 11.43 11.43 0 0 0 -1.91 4.13.29.29 0 0 0 0 .09c0 .11-.14.72-.16.85a16.32 16.32 0 0 0 -.2 1.89v.07a13.57 13.57 0 0 0 26.94 2.3c0-.17 0-.35.06-.52a13.94 13.94 0 0 0 -.91-6.82z" fill="url(#p)"/></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/trailhead/card-illo-pledge.svg b/browser/components/newtab/data/content/assets/trailhead/card-illo-pledge.svg
new file mode 100644
index 0000000000..30d9c02039
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/trailhead/card-illo-pledge.svg
@@ -0,0 +1,5 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+
+<svg viewBox="0 0 288 180" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><linearGradient id="a" gradientTransform="matrix(1 0 0 -1 0 182)" gradientUnits="userSpaceOnUse" x1="161.49" x2="161.49" y1="48.36" y2="138.65"><stop offset="0" stop-color="#3a8ee6"/><stop offset=".24" stop-color="#5c79f0"/><stop offset=".63" stop-color="#9059ff"/><stop offset="1" stop-color="#c139e6"/></linearGradient><linearGradient id="b" gradientTransform="matrix(1 0 0 -1 0 182)" gradientUnits="userSpaceOnUse" x1="192.18" x2="138.57" y1="70.63" y2="70.63"><stop offset=".14" stop-color="#6a2bea" stop-opacity="0"/><stop offset=".34" stop-color="#642de4" stop-opacity=".03"/><stop offset=".55" stop-color="#5131d3" stop-opacity=".12"/><stop offset=".76" stop-color="#3139b7" stop-opacity=".27"/><stop offset=".98" stop-color="#054490" stop-opacity=".48"/><stop offset="1" stop-color="#00458b" stop-opacity=".5"/></linearGradient><linearGradient id="c" gradientTransform="matrix(1 0 0 -1 0 182)" gradientUnits="userSpaceOnUse" x1="146.69" x2="109.67" y1="126.28" y2="62.15"><stop offset="0" stop-color="#ff980e"/><stop offset=".27" stop-color="#ff851b"/><stop offset=".56" stop-color="#ff7f1f"/><stop offset=".77" stop-color="#ff3750"/><stop offset=".9" stop-color="#f92261"/><stop offset="1" stop-color="#f5156c"/></linearGradient><linearGradient id="d" gradientTransform="matrix(1 0 0 -1 0 182)" gradientUnits="userSpaceOnUse" x1="146.69" x2="109.67" y1="126.28" y2="62.15"><stop offset="0" stop-color="#fff261" stop-opacity=".8"/><stop offset=".06" stop-color="#fff261" stop-opacity=".68"/><stop offset=".19" stop-color="#fff261" stop-opacity=".48"/><stop offset=".31" stop-color="#fff261" stop-opacity=".31"/><stop offset=".42" stop-color="#fff261" stop-opacity=".17"/><stop offset=".53" stop-color="#fff261" stop-opacity=".08"/><stop offset=".63" stop-color="#fff261" stop-opacity=".02"/><stop offset=".72" stop-color="#fff261" stop-opacity="0"/></linearGradient><linearGradient id="e" gradientTransform="matrix(1 0 0 -1 11.03 186.57)" gradientUnits="userSpaceOnUse" x1="128.01" x2="128.01" y1="86.9" y2="134.16"><stop offset="0" stop-color="#6e008b" stop-opacity=".5"/><stop offset=".5" stop-color="#c846cb" stop-opacity="0"/></linearGradient><circle cx="144" cy="90" fill="#bfbfc9" opacity=".15" r="72"/><path d="m193.18 52.82a30.66 30.66 0 0 0 -21.93-9.47h-.25a30.62 30.62 0 0 0 -21.8 9l-24.7 24.73a10.53 10.53 0 0 0 0 14.9l4.58 4.57a10.58 10.58 0 0 0 14.93 0l-12.01-11.89 24.67-24.73a20.07 20.07 0 0 1 14.33-5.93h.19a20.07 20.07 0 0 1 14.37 6.19c7.59 7.87 7.2 20.83-.86 28.9l-35.15 35.25a7.75 7.75 0 0 1 -11 0l5.65 5.66.91.92a9.23 9.23 0 0 0 12.31.63l34.7-34.94c12.23-12.13 12.64-31.77 1.06-43.79z" fill="url(#a)"/><path d="m184.66 89.1-35.15 35.25a7.75 7.75 0 0 1 -11 0l5.69 5.65.91.92a9.23 9.23 0 0 0 12.31.63l34.7-34.94z" fill="url(#b)"/><path d="m144.05 96.52h-.05a10.57 10.57 0 0 1 -14.92 0l7.47 7.46a10.55 10.55 0 0 0 14.92 0l12-12a10.58 10.58 0 0 0 0-14.93l-24.63-24.64a30.65 30.65 0 0 0 -21.8-9h-.29a30.68 30.68 0 0 0 -21.93 9.41c-11.58 12-11.13 31.66 1 43.8l34.18 34.15a20 20 0 0 0 27.5.79 9.23 9.23 0 0 1 -12.31-.63l-7.66-7.67-34.18-34.16c-8.07-8.07-8.46-21-.87-28.9a20.05 20.05 0 0 1 14.37-6.2h.15a20.07 20.07 0 0 1 14.31 5.92l24.69 24.57-11.93 12z" fill="url(#c)"/><path d="m144.05 96.52h-.05a10.57 10.57 0 0 1 -14.92 0l7.47 7.46a10.55 10.55 0 0 0 14.92 0l12-12a10.58 10.58 0 0 0 0-14.93l-24.63-24.64a30.65 30.65 0 0 0 -21.8-9h-.29a30.68 30.68 0 0 0 -21.93 9.41c-11.58 12-11.13 31.66 1 43.8l34.18 34.15a20 20 0 0 0 27.5.79 9.23 9.23 0 0 1 -12.31-.63l-7.66-7.67-34.18-34.16c-8.07-8.07-8.46-21-.87-28.9a20.05 20.05 0 0 1 14.37-6.2h.15a20.07 20.07 0 0 1 14.31 5.92l24.69 24.57-11.93 12z" fill="url(#d)"/><path d="m149.16 52.41-24.66 24.67a10.53 10.53 0 0 0 0 14.9l4.58 4.57a10.58 10.58 0 0 0 14.93 0l-12.01-11.89 24.67-24.73z" fill="url(#e)"/></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/trailhead/card-illo-pocket.svg b/browser/components/newtab/data/content/assets/trailhead/card-illo-pocket.svg
new file mode 100644
index 0000000000..124c6c005c
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/trailhead/card-illo-pocket.svg
@@ -0,0 +1,5 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+
+<svg viewBox="0 0 288 180" xmlns="http://www.w3.org/2000/svg"><circle cx="144" cy="90" fill="#bfbfc9" opacity=".15" r="72"/><path d="m165.68 121.55a5.26 5.26 0 0 0 1.22-3.34v-63.77a5.33 5.33 0 0 0 -5.31-5.31h-90.34a5.33 5.33 0 0 0 -5.31 5.31v63.77a5.26 5.26 0 0 0 1.22 3.34l-11.85 2v5.32h122.22v-5.32z" fill="#9f9fad"/><path d="m126.16 59.76-54.91 54.91a1.78 1.78 0 0 0 1.75 1.77h86.79a1.78 1.78 0 0 0 1.77-1.77v-54.91z" fill="#592acb"/><path d="m71.25 59.76v54.91l54.91-54.91z" fill="#6736d8"/><path d="m159.82 54.44h-86.82a1.78 1.78 0 0 0 -1.78 1.77v3.55h90.34v-3.55a1.78 1.78 0 0 0 -1.74-1.77z" fill="#592acb"/><path d="m160 122.84h-86.81a.89.89 0 1 1 0-1.77h86.81a.89.89 0 0 1 0 1.77z" fill="#8f8f9d"/><path d="m109.89 125.15h12.4" fill="none" stroke="#80808e" stroke-linecap="round" stroke-linejoin="round"/><path d="m227.42 50.1h-37.58a5.37 5.37 0 0 0 -5.36 5.36v68a5.38 5.38 0 0 0 5.36 5.37h37.58a5.38 5.38 0 0 0 5.37-5.37v-68a5.38 5.38 0 0 0 -5.37-5.36z" fill="#bfbfc9"/><path d="m189.84 98.41v21.48a1.8 1.8 0 0 0 1.79 1.79h34a1.79 1.79 0 0 0 1.79-1.79v-59.06z" fill="#f11f89"/><path d="m189.84 60.83v37.58l37.58-37.58z" fill="#ff298a"/><path d="m225.63 55.46h-34a1.8 1.8 0 0 0 -1.79 1.79v3.58h37.58v-3.58a1.79 1.79 0 0 0 -1.79-1.79z" fill="#f11f89"/><circle cx="199.69" cy="113.62" fill="#ffd567" r="2.68"/><circle cx="208.63" cy="113.62" fill="#ff8a50" r="2.68"/><circle cx="217.58" cy="113.62" fill="#7542e5" r="2.68"/><path d="m206.27 125.26h5.05" fill="none" stroke="#9f9fad" stroke-linecap="round" stroke-linejoin="round"/><g fill="#fff"><path d="m116.07 99.86a15.1 15.1 0 0 1 -15.07-15.11v-7.56a3.77 3.77 0 0 1 3.78-3.77h22.67a3.77 3.77 0 0 1 3.77 3.77v7.56a15.1 15.1 0 0 1 -15.15 15.11zm7.53-19a1.87 1.87 0 0 0 -1.37.6l-6.23 6.26-6.09-6.11a1.85 1.85 0 0 0 -1.42-.7 1.89 1.89 0 0 0 -1.89 1.89 1.87 1.87 0 0 0 .54 1.32l6.22 6.25 1.33 1.33a1.88 1.88 0 0 0 2.67 0l1.34-1.33 6.3-6.23a1.89 1.89 0 0 0 0-2.67 2 2 0 0 0 -1.4-.56z"/><path d="m208.73 95.37a10.15 10.15 0 0 1 -10.15-10.15v-5.07a2.54 2.54 0 0 1 2.54-2.54h15.22a2.54 2.54 0 0 1 2.53 2.54v5.07a10.15 10.15 0 0 1 -10.14 10.15zm5.05-12.72a1.24 1.24 0 0 0 -.92.4l-4.16 4.16-4.09-4.1a1.22 1.22 0 0 0 -1-.46 1.25 1.25 0 0 0 -1.26 1.26 1.27 1.27 0 0 0 .36.89l4.18 4.2.89.89a1.26 1.26 0 0 0 1.79 0l.9-.89 4.2-4.2a1.26 1.26 0 0 0 -.91-2.16z"/></g></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/trailhead/card-illo-private.svg b/browser/components/newtab/data/content/assets/trailhead/card-illo-private.svg
new file mode 100644
index 0000000000..fb90829d2e
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/trailhead/card-illo-private.svg
@@ -0,0 +1,5 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+
+<svg viewBox="0 0 288 180" xmlns="http://www.w3.org/2000/svg"><circle cx="144" cy="90" fill="#bfbfc9" opacity=".15" r="72"/><path d="m193.26 122.56a5.24 5.24 0 0 0 1.22-3.33v-63.77a5.33 5.33 0 0 0 -5.31-5.31h-90.34a5.33 5.33 0 0 0 -5.31 5.31v63.77a5.24 5.24 0 0 0 1.22 3.33l-11.85 2v5.31h122.22v-5.31z" fill="#9f9fad"/><path d="m153.74 60.77-54.91 54.91a1.77 1.77 0 0 0 1.77 1.77h86.8a1.77 1.77 0 0 0 1.77-1.77v-54.91z" fill="#592acb"/><path d="m98.83 60.77v54.91l54.91-54.91z" fill="#6736d8"/><path d="m187.4 55.46h-86.8a1.78 1.78 0 0 0 -1.77 1.77v3.54h90.34v-3.54a1.78 1.78 0 0 0 -1.77-1.77z" fill="#592acb"/><path d="m187.56 123.86h-86.79a.89.89 0 1 1 0-1.77h86.79a.89.89 0 0 1 0 1.77z" fill="#8f8f9d"/><path d="m137.47 126.17h12.4" fill="none" stroke="#80808e" stroke-linecap="round" stroke-linejoin="round"/><circle cx="144" cy="86.4" fill="#b833e1" r="22.54"/><path d="m153.73 95.48c-3.67 0-6.21-4.41-9.73-4.41s-6.28 4.41-9.73 4.41c-4.53 0-7.87-4.29-7.93-11.64 0-4.56 1.33-6 7.21-6s7.6 2.41 10.45 2.41 4.57-2.41 10.45-2.41 7.24 1.46 7.21 6c-.06 7.35-3.4 11.64-7.93 11.64zm-17.3-12c-3.57.16-5 2.28-5 2.81s2.37 2 4.68 2 5.05-.85 5.05-1.61-1.36-3.39-4.73-3.24zm15.14 0c-3.37-.15-4.69 2.37-4.69 3.21s2.73 1.61 5.05 1.61 4.68-1.49 4.68-2-1.47-2.7-5.04-2.86z" fill="#f9f9fa"/></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/trailhead/card-illo-sendtab.svg b/browser/components/newtab/data/content/assets/trailhead/card-illo-sendtab.svg
new file mode 100644
index 0000000000..318c956686
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/trailhead/card-illo-sendtab.svg
@@ -0,0 +1,5 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+
+<svg viewBox="0 0 288 180" xmlns="http://www.w3.org/2000/svg"><circle cx="144" cy="90" fill="#bfbfc9" opacity=".15" r="72"/><path d="m163.05 84.53h25.83v5.48h-25.83z" fill="#bfbfc9" opacity=".25"/><path d="m165.93 121.47a5.26 5.26 0 0 0 1.22-3.34v-63.77a5.33 5.33 0 0 0 -5.32-5.31h-90.33a5.33 5.33 0 0 0 -5.31 5.31v63.77a5.26 5.26 0 0 0 1.22 3.34l-11.85 2v5.31h122.21v-5.31z" fill="#9f9fad"/><path d="m126.41 59.68-54.91 54.9a1.78 1.78 0 0 0 1.77 1.78h86.79a1.78 1.78 0 0 0 1.77-1.78v-54.9z" fill="#592acb"/><path d="m71.5 59.68v54.9l54.91-54.9z" fill="#6736d8"/><path d="m160.06 54.36h-86.79a1.78 1.78 0 0 0 -1.77 1.77v3.55h90.33v-3.55a1.77 1.77 0 0 0 -1.77-1.77z" fill="#592acb"/><path d="m160.22 122.76h-86.79a.89.89 0 0 1 0-1.77h86.79a.89.89 0 1 1 0 1.77z" fill="#8f8f9d"/><path d="m110.14 125.07h12.39" fill="none" stroke="#80808e" stroke-linecap="round" stroke-linejoin="round"/><path d="m227.67 50h-37.58a5.39 5.39 0 0 0 -5.37 5.37v68a5.38 5.38 0 0 0 5.37 5.36h37.58a5.38 5.38 0 0 0 5.37-5.36v-68a5.39 5.39 0 0 0 -5.37-5.37z" fill="#bfbfc9"/><path d="m190.09 98.33v21.48a1.8 1.8 0 0 0 1.79 1.79h34a1.79 1.79 0 0 0 1.79-1.79v-59.06z" fill="#f11f89"/><path d="m190.09 60.75v37.58l37.58-37.58z" fill="#ff298a"/><path d="m225.88 55.38h-34a1.8 1.8 0 0 0 -1.79 1.79v3.58h37.58v-3.58a1.79 1.79 0 0 0 -1.79-1.79z" fill="#f11f89"/><circle cx="199.93" cy="113.54" fill="#ffd567" r="2.68"/><circle cx="208.88" cy="113.54" fill="#ff8a50" r="2.68"/><circle cx="217.83" cy="113.54" fill="#7542e5" r="2.68"/><path d="m206.52 125.17h5.04" fill="none" stroke="#9f9fad" stroke-linecap="round" stroke-linejoin="round"/><path d="m213.56 85.34-16.45-16.45a2.74 2.74 0 0 0 -3.87 3.88l11.76 11.76h-20.28v5.47h20.28l-11.76 11.76a2.74 2.74 0 0 0 3.81 4l.06-.07 16.45-16.45a2.73 2.73 0 0 0 0-3.9z" fill="#fff"/><path d="m117.57 84.53a2.75 2.75 0 0 0 0 5.49h49.66v-5.49z" fill="#cdcdd4"/></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/trailhead/card-illo-tracking.svg b/browser/components/newtab/data/content/assets/trailhead/card-illo-tracking.svg
new file mode 100644
index 0000000000..cdf43cc23d
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/trailhead/card-illo-tracking.svg
@@ -0,0 +1,5 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
+
+<svg viewBox="0 0 288 180" xmlns="http://www.w3.org/2000/svg"><circle cx="144" cy="90" fill="#bfbfc9" opacity=".15" r="72"/><path d="m187.73 65.17c-.06-4.45-.12-9.5-.14-15.2a4.87 4.87 0 0 0 -4-4.79l-38.73-6.7a5 5 0 0 0 -1.66 0l-38.73 6.7a4.87 4.87 0 0 0 -4 4.79c0 5.7-.08 10.75-.14 15.2-.1 8-.17 13.84.16 17.46 2.09 23.23 7 33.81 15.31 45.21a45.42 45.42 0 0 0 27.31 17.58 5.2 5.2 0 0 0 1 .09 5 5 0 0 0 1-.09 46 46 0 0 0 27.3-17.58c8.31-11.4 13.22-22 15.32-45.21.17-3.63.1-9.43 0-17.46z" fill="#9f9fad"/><path d="m143.18 38.56-38.73 6.7a4.89 4.89 0 0 0 -4 4.79c0 5.7-.07 10.75-.13 15.2-.1 8-.18 13.84.15 17.46 2.1 23.23 7 33.81 15.32 45.21a45.34 45.34 0 0 0 27.31 17.57 4.32 4.32 0 0 0 .95.1v-107.1a4.57 4.57 0 0 0 -.87.07z" fill="#80808e"/><path d="m143.3 45.93-32.48 5.62a4.08 4.08 0 0 0 -3.38 4c0 4.77-.06 9-.11 12.74-.09 6.74-.15 11.61.12 14.64 1.76 19.49 5.88 28.36 12.85 37.92a38 38 0 0 0 22.91 14.74 3.47 3.47 0 0 0 .79.08v-89.8a4.14 4.14 0 0 0 -.7.06z" fill="#592acb"/><path d="m180.67 68.31c0-3.73-.1-8-.11-12.74a4.08 4.08 0 0 0 -3.38-4l-32.48-5.64a4.14 4.14 0 0 0 -.7-.06v89.82a3.62 3.62 0 0 0 .8-.08 38.54 38.54 0 0 0 22.89-14.74c7-9.56 11.09-18.43 12.85-37.92.28-3.03.22-7.9.13-14.64z" fill="#7542e5"/><path d="m156.89 79.5a3.46 3.46 0 0 0 -2.89-3.4l-10-1.65-10 1.65a3.46 3.46 0 0 0 -2.93 3.4c0 2.71 0 6.3.18 8 .48 5.16 1.49 8 4 11.2a13.51 13.51 0 0 0 8.59 5h.17.17a13.51 13.51 0 0 0 8.59-5c2.46-3.22 3.46-6 4-11.2.11-1.8.12-5.78.12-8zm-3.38 7.68c-.44 4.59-1.21 6.82-3.3 9.55a10.39 10.39 0 0 1 -6.21 3.74 10.42 10.42 0 0 1 -6.21-3.74c-2.09-2.74-2.86-5-3.29-9.54-.12-1.22-.17-4-.17-7.68a.26.26 0 0 1 .23-.23l9.44-1.56 9.44 1.56a.25.25 0 0 1 .23.23c0 3.67-.06 6.49-.16 7.67zm-15.95-5.13c0 3.17.1 4.41.14 4.83.41 4.35 1.12 5.89 2.65 7.89a7 7 0 0 0 3.65 2.39v-16.16z" fill="#fff"/></svg> \ No newline at end of file
diff --git a/browser/components/newtab/data/content/assets/whatsnew-send-icon.png b/browser/components/newtab/data/content/assets/whatsnew-send-icon.png
new file mode 100644
index 0000000000..09e371bd81
--- /dev/null
+++ b/browser/components/newtab/data/content/assets/whatsnew-send-icon.png
Binary files differ
diff --git a/browser/components/newtab/data/content/newtab-render.js b/browser/components/newtab/data/content/newtab-render.js
new file mode 100644
index 0000000000..4fd46fad03
--- /dev/null
+++ b/browser/components/newtab/data/content/newtab-render.js
@@ -0,0 +1,11 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
+// exported by activity-stream.bundle.js
+if (window.__FROM_STARTUP_CACHE__) {
+ window.NewtabRenderUtils.renderCache(window.__STARTUP_STATE__);
+} else {
+ window.NewtabRenderUtils.renderWithoutState();
+}
diff --git a/browser/components/newtab/data/content/tippytop/favicons/adidas.png b/browser/components/newtab/data/content/tippytop/favicons/adidas.png
new file mode 100644
index 0000000000..fd7123958c
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/favicons/adidas.png
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/favicons/aliexpress-com.ico b/browser/components/newtab/data/content/tippytop/favicons/aliexpress-com.ico
new file mode 100644
index 0000000000..99b86e13aa
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/favicons/aliexpress-com.ico
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/favicons/allegro-pl.ico b/browser/components/newtab/data/content/tippytop/favicons/allegro-pl.ico
new file mode 100644
index 0000000000..42b4f90149
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/favicons/allegro-pl.ico
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/favicons/amazon.ico b/browser/components/newtab/data/content/tippytop/favicons/amazon.ico
new file mode 100644
index 0000000000..1c39eaf8fe
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/favicons/amazon.ico
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/favicons/avito-ru.ico b/browser/components/newtab/data/content/tippytop/favicons/avito-ru.ico
new file mode 100644
index 0000000000..c41847b27a
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/favicons/avito-ru.ico
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/favicons/baidu-com.png b/browser/components/newtab/data/content/tippytop/favicons/baidu-com.png
new file mode 100644
index 0000000000..e63737eb30
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/favicons/baidu-com.png
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/favicons/bbc-uk.ico b/browser/components/newtab/data/content/tippytop/favicons/bbc-uk.ico
new file mode 100644
index 0000000000..8f62b07af8
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/favicons/bbc-uk.ico
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/favicons/bing-com.ico b/browser/components/newtab/data/content/tippytop/favicons/bing-com.ico
new file mode 100644
index 0000000000..1e90a10d6e
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/favicons/bing-com.ico
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/favicons/ctrip-com.ico b/browser/components/newtab/data/content/tippytop/favicons/ctrip-com.ico
new file mode 100644
index 0000000000..fa44291d84
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/favicons/ctrip-com.ico
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/favicons/duckduckgo-com.ico b/browser/components/newtab/data/content/tippytop/favicons/duckduckgo-com.ico
new file mode 100644
index 0000000000..dda80dfd88
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/favicons/duckduckgo-com.ico
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/favicons/ebay.ico b/browser/components/newtab/data/content/tippytop/favicons/ebay.ico
new file mode 100644
index 0000000000..3af7a36484
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/favicons/ebay.ico
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/favicons/etsy.ico b/browser/components/newtab/data/content/tippytop/favicons/etsy.ico
new file mode 100644
index 0000000000..a94f3efd4f
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/favicons/etsy.ico
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/favicons/facebook-com.ico b/browser/components/newtab/data/content/tippytop/favicons/facebook-com.ico
new file mode 100644
index 0000000000..8ce319b8f7
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/favicons/facebook-com.ico
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/favicons/geico.png b/browser/components/newtab/data/content/tippytop/favicons/geico.png
new file mode 100644
index 0000000000..3f61497dd8
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/favicons/geico.png
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/favicons/google-com.ico b/browser/components/newtab/data/content/tippytop/favicons/google-com.ico
new file mode 100644
index 0000000000..82339b3b1d
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/favicons/google-com.ico
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/favicons/hrblock.ico b/browser/components/newtab/data/content/tippytop/favicons/hrblock.ico
new file mode 100644
index 0000000000..e0d7be35e0
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/favicons/hrblock.ico
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/favicons/ifeng-com.ico b/browser/components/newtab/data/content/tippytop/favicons/ifeng-com.ico
new file mode 100644
index 0000000000..b0003e058f
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/favicons/ifeng-com.ico
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/favicons/iqiyi-com.ico b/browser/components/newtab/data/content/tippytop/favicons/iqiyi-com.ico
new file mode 100644
index 0000000000..4b179bf4d5
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/favicons/iqiyi-com.ico
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/favicons/leboncoin-fr.png b/browser/components/newtab/data/content/tippytop/favicons/leboncoin-fr.png
new file mode 100644
index 0000000000..e23e2a34b0
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/favicons/leboncoin-fr.png
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/favicons/nike.ico b/browser/components/newtab/data/content/tippytop/favicons/nike.ico
new file mode 100644
index 0000000000..7788d580af
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/favicons/nike.ico
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/favicons/ok-ru.ico b/browser/components/newtab/data/content/tippytop/favicons/ok-ru.ico
new file mode 100644
index 0000000000..7db8914287
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/favicons/ok-ru.ico
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/favicons/olx-pl.ico b/browser/components/newtab/data/content/tippytop/favicons/olx-pl.ico
new file mode 100644
index 0000000000..b2a28638f8
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/favicons/olx-pl.ico
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/favicons/reddit-com.png b/browser/components/newtab/data/content/tippytop/favicons/reddit-com.png
new file mode 100644
index 0000000000..3c09931835
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/favicons/reddit-com.png
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/favicons/samsung.ico b/browser/components/newtab/data/content/tippytop/favicons/samsung.ico
new file mode 100644
index 0000000000..eb8c814256
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/favicons/samsung.ico
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/favicons/turbotax.png b/browser/components/newtab/data/content/tippytop/favicons/turbotax.png
new file mode 100644
index 0000000000..c1d52f99fb
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/favicons/turbotax.png
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/favicons/twitter-com.ico b/browser/components/newtab/data/content/tippytop/favicons/twitter-com.ico
new file mode 100644
index 0000000000..e5aaff4379
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/favicons/twitter-com.ico
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/favicons/vk-com.ico b/browser/components/newtab/data/content/tippytop/favicons/vk-com.ico
new file mode 100644
index 0000000000..0066072c39
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/favicons/vk-com.ico
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/favicons/vodafone.png b/browser/components/newtab/data/content/tippytop/favicons/vodafone.png
new file mode 100644
index 0000000000..1a4ba0089e
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/favicons/vodafone.png
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/favicons/weibo-com.ico b/browser/components/newtab/data/content/tippytop/favicons/weibo-com.ico
new file mode 100644
index 0000000000..11a88045ec
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/favicons/weibo-com.ico
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/favicons/wikipedia-org.ico b/browser/components/newtab/data/content/tippytop/favicons/wikipedia-org.ico
new file mode 100644
index 0000000000..e70021849b
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/favicons/wikipedia-org.ico
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/favicons/wix.ico b/browser/components/newtab/data/content/tippytop/favicons/wix.ico
new file mode 100644
index 0000000000..cabcb650a7
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/favicons/wix.ico
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/favicons/wykop-pl.png b/browser/components/newtab/data/content/tippytop/favicons/wykop-pl.png
new file mode 100644
index 0000000000..5aae5b17f2
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/favicons/wykop-pl.png
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/favicons/yandex-com.png b/browser/components/newtab/data/content/tippytop/favicons/yandex-com.png
new file mode 100644
index 0000000000..3414ad4249
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/favicons/yandex-com.png
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/favicons/yandex-ru.png b/browser/components/newtab/data/content/tippytop/favicons/yandex-ru.png
new file mode 100644
index 0000000000..ea5907a775
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/favicons/yandex-ru.png
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/favicons/youtube-com.png b/browser/components/newtab/data/content/tippytop/favicons/youtube-com.png
new file mode 100644
index 0000000000..b0c05d0716
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/favicons/youtube-com.png
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/favicons/zhihu-com.ico b/browser/components/newtab/data/content/tippytop/favicons/zhihu-com.ico
new file mode 100644
index 0000000000..c83d0e6d86
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/favicons/zhihu-com.ico
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/images/adidas@2x.png b/browser/components/newtab/data/content/tippytop/images/adidas@2x.png
new file mode 100644
index 0000000000..f07c17a9a8
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/images/adidas@2x.png
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/images/aliexpress-com@2x.png b/browser/components/newtab/data/content/tippytop/images/aliexpress-com@2x.png
new file mode 100644
index 0000000000..76fac2e935
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/images/aliexpress-com@2x.png
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/images/allegro-pl@2x.png b/browser/components/newtab/data/content/tippytop/images/allegro-pl@2x.png
new file mode 100644
index 0000000000..7aa6ffd4b3
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/images/allegro-pl@2x.png
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/images/amazon@2x.png b/browser/components/newtab/data/content/tippytop/images/amazon@2x.png
new file mode 100644
index 0000000000..fb20eea921
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/images/amazon@2x.png
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/images/avito-ru@2x.png b/browser/components/newtab/data/content/tippytop/images/avito-ru@2x.png
new file mode 100644
index 0000000000..9ba32a8d96
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/images/avito-ru@2x.png
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/images/baidu-com@2x.png b/browser/components/newtab/data/content/tippytop/images/baidu-com@2x.png
new file mode 100644
index 0000000000..b7662dd21f
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/images/baidu-com@2x.png
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/images/bbc-uk@2x.png b/browser/components/newtab/data/content/tippytop/images/bbc-uk@2x.png
new file mode 100644
index 0000000000..e019ac3de6
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/images/bbc-uk@2x.png
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/images/bing-com@2x.png b/browser/components/newtab/data/content/tippytop/images/bing-com@2x.png
new file mode 100644
index 0000000000..6b9c90daf8
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/images/bing-com@2x.png
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/images/ctrip-com@2x.png b/browser/components/newtab/data/content/tippytop/images/ctrip-com@2x.png
new file mode 100644
index 0000000000..76a81da5af
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/images/ctrip-com@2x.png
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/images/duckduckgo-com@2x.png b/browser/components/newtab/data/content/tippytop/images/duckduckgo-com@2x.png
new file mode 100644
index 0000000000..ff6890bae6
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/images/duckduckgo-com@2x.png
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/images/ebay@2x.png b/browser/components/newtab/data/content/tippytop/images/ebay@2x.png
new file mode 100644
index 0000000000..33594e8066
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/images/ebay@2x.png
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/images/etsy@2x.jpg b/browser/components/newtab/data/content/tippytop/images/etsy@2x.jpg
new file mode 100644
index 0000000000..4bd477ca6a
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/images/etsy@2x.jpg
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/images/facebook-com@2x.png b/browser/components/newtab/data/content/tippytop/images/facebook-com@2x.png
new file mode 100644
index 0000000000..8827157878
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/images/facebook-com@2x.png
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/images/geico@2x.jpg b/browser/components/newtab/data/content/tippytop/images/geico@2x.jpg
new file mode 100644
index 0000000000..938b7948e9
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/images/geico@2x.jpg
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/images/google-com@2x.png b/browser/components/newtab/data/content/tippytop/images/google-com@2x.png
new file mode 100644
index 0000000000..263bd973b1
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/images/google-com@2x.png
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/images/hrblock@2x.png b/browser/components/newtab/data/content/tippytop/images/hrblock@2x.png
new file mode 100644
index 0000000000..ba66c46b72
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/images/hrblock@2x.png
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/images/ifeng-com@2x.png b/browser/components/newtab/data/content/tippytop/images/ifeng-com@2x.png
new file mode 100644
index 0000000000..f7099f334e
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/images/ifeng-com@2x.png
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/images/iqiyi-com@2x.png b/browser/components/newtab/data/content/tippytop/images/iqiyi-com@2x.png
new file mode 100644
index 0000000000..901d536ad9
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/images/iqiyi-com@2x.png
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/images/leboncoin-fr@2x.png b/browser/components/newtab/data/content/tippytop/images/leboncoin-fr@2x.png
new file mode 100644
index 0000000000..af293fa8c3
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/images/leboncoin-fr@2x.png
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/images/nike@2x.jpg b/browser/components/newtab/data/content/tippytop/images/nike@2x.jpg
new file mode 100644
index 0000000000..ac5d639d12
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/images/nike@2x.jpg
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/images/ok-ru@2x.png b/browser/components/newtab/data/content/tippytop/images/ok-ru@2x.png
new file mode 100644
index 0000000000..c771bf3ad9
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/images/ok-ru@2x.png
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/images/olx-pl@2x.png b/browser/components/newtab/data/content/tippytop/images/olx-pl@2x.png
new file mode 100644
index 0000000000..964cd2df10
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/images/olx-pl@2x.png
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/images/reddit-com@2x.png b/browser/components/newtab/data/content/tippytop/images/reddit-com@2x.png
new file mode 100644
index 0000000000..3b8833d6c6
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/images/reddit-com@2x.png
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/images/samsung@2x.jpg b/browser/components/newtab/data/content/tippytop/images/samsung@2x.jpg
new file mode 100644
index 0000000000..dec2346e9f
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/images/samsung@2x.jpg
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/images/turbotax@2x.jpg b/browser/components/newtab/data/content/tippytop/images/turbotax@2x.jpg
new file mode 100644
index 0000000000..625703943f
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/images/turbotax@2x.jpg
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/images/twitter-com@2x.png b/browser/components/newtab/data/content/tippytop/images/twitter-com@2x.png
new file mode 100644
index 0000000000..e5835ff98a
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/images/twitter-com@2x.png
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/images/vk-com@2x.png b/browser/components/newtab/data/content/tippytop/images/vk-com@2x.png
new file mode 100644
index 0000000000..b4c14412a4
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/images/vk-com@2x.png
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/images/vodafone@2x.jpg b/browser/components/newtab/data/content/tippytop/images/vodafone@2x.jpg
new file mode 100644
index 0000000000..2597063b47
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/images/vodafone@2x.jpg
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/images/weibo-com@2x.png b/browser/components/newtab/data/content/tippytop/images/weibo-com@2x.png
new file mode 100644
index 0000000000..e047eaac87
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/images/weibo-com@2x.png
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/images/wikipedia-org@2x.png b/browser/components/newtab/data/content/tippytop/images/wikipedia-org@2x.png
new file mode 100644
index 0000000000..53cf1af1c6
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/images/wikipedia-org@2x.png
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/images/wix@2x.jpg b/browser/components/newtab/data/content/tippytop/images/wix@2x.jpg
new file mode 100644
index 0000000000..473caf38a3
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/images/wix@2x.jpg
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/images/wykop-pl@2x.png b/browser/components/newtab/data/content/tippytop/images/wykop-pl@2x.png
new file mode 100644
index 0000000000..fbde175696
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/images/wykop-pl@2x.png
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/images/yandex-com@2x.png b/browser/components/newtab/data/content/tippytop/images/yandex-com@2x.png
new file mode 100644
index 0000000000..872a03138e
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/images/yandex-com@2x.png
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/images/yandex-ru@2x.png b/browser/components/newtab/data/content/tippytop/images/yandex-ru@2x.png
new file mode 100644
index 0000000000..c02451ef4f
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/images/yandex-ru@2x.png
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/images/youtube-com@2x.png b/browser/components/newtab/data/content/tippytop/images/youtube-com@2x.png
new file mode 100644
index 0000000000..6f1d7a1d7b
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/images/youtube-com@2x.png
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/images/zhihu-com@2x.png b/browser/components/newtab/data/content/tippytop/images/zhihu-com@2x.png
new file mode 100644
index 0000000000..a1a9db845e
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/images/zhihu-com@2x.png
Binary files differ
diff --git a/browser/components/newtab/data/content/tippytop/top_sites.json b/browser/components/newtab/data/content/tippytop/top_sites.json
new file mode 100644
index 0000000000..e54d2f8261
--- /dev/null
+++ b/browser/components/newtab/data/content/tippytop/top_sites.json
@@ -0,0 +1,182 @@
+[
+ {
+ "domains": ["adidas.co.uk", "adidas.de", "adidas.fr"],
+ "image_url": "images/adidas@2x.png",
+ "favicon_url": "favicons/adidas.png"
+ },
+ {
+ "domains": ["aliexpress.com"],
+ "image_url": "images/aliexpress-com@2x.png",
+ "favicon_url": "favicons/aliexpress-com.ico"
+ },
+ {
+ "domains": ["allegro.pl"],
+ "image_url": "images/allegro-pl@2x.png",
+ "favicon_url": "favicons/allegro-pl.ico"
+ },
+ {
+ "domains": ["amazon.ae", "amazon.ca", "amazon.co.jp", "amazon.co.uk", "amazon.com", "amazon.com.au", "amazon.com.br", "amazon.com.mx", "amazon.de", "amazon.es", "amazon.fr", "amazon.in", "amazon.it", "amazon.nl", "amazon.sa", "amazon.se", "amazon.sg", "amazon.com.tr"],
+ "image_url": "images/amazon@2x.png",
+ "favicon_url": "favicons/amazon.ico"
+ },
+ {
+ "domains": ["avito.ru"],
+ "image_url": "images/avito-ru@2x.png",
+ "favicon_url": "favicons/avito-ru.ico"
+ },
+ {
+ "domains": ["baidu.com"],
+ "image_url": "images/baidu-com@2x.png",
+ "favicon_url": "favicons/baidu-com.png"
+ },
+ {
+ "domains": ["bbc.co.uk"],
+ "image_url": "images/bbc-uk@2x.png",
+ "favicon_url": "favicons/bbc-uk.ico"
+ },
+ {
+ "domains": ["bing.com"],
+ "image_url": "images/bing-com@2x.png",
+ "favicon_url": "favicons/bing-com.ico"
+ },
+ {
+ "domains": ["ctrip.com"],
+ "image_url": "images/ctrip-com@2x.png",
+ "favicon_url": "favicons/ctrip-com.ico"
+ },
+ {
+ "domains": ["duckduckgo.com"],
+ "image_url": "images/duckduckgo-com@2x.png",
+ "favicon_url": "favicons/duckduckgo-com.ico"
+ },
+ {
+ "domains": ["mx.ebay.com", "benl.ebay.be", "befr.ebay.be", "ebay.ca", "ebay.ch", "ebay.co.jp", "ebay.co.uk", "ebay.com", "ebay.com.au", "ebay.de", "ebay.es", "ebay.fr", "ebay.ie", "ebay.in", "ebay.it", "ebay.nl"],
+ "image_url": "images/ebay@2x.png",
+ "favicon_url": "favicons/ebay.ico"
+ },
+ {
+ "domains": ["etsy.com"],
+ "image_url": "images/etsy@2x.jpg",
+ "favicon_url": "favicons/etsy.ico"
+ },
+ {
+ "domains": ["facebook.com"],
+ "image_url": "images/facebook-com@2x.png",
+ "favicon_url": "favicons/facebook-com.ico"
+ },
+ {
+ "domains": ["geico.com"],
+ "image_url": "images/geico@2x.jpg",
+ "favicon_url": "favicons/geico.png"
+ },
+ {
+ "domains": ["google.com"],
+ "image_url": "images/google-com@2x.png",
+ "favicon_url": "favicons/google-com.ico"
+ },
+ {
+ "domains": ["hrblock.com"],
+ "image_url": "images/hrblock@2x.png",
+ "favicon_url": "favicons/hrblock.ico"
+ },
+ {
+ "domains": ["ifeng.com"],
+ "image_url": "images/ifeng-com@2x.png",
+ "favicon_url": "favicons/ifeng-com.ico"
+ },
+ {
+ "domains": ["iqiyi.com"],
+ "image_url": "images/iqiyi-com@2x.png",
+ "favicon_url": "favicons/iqiyi-com.ico"
+ },
+ {
+ "domains": ["leboncoin.fr"],
+ "image_url": "images/leboncoin-fr@2x.png",
+ "favicon_url": "favicons/leboncoin-fr.png"
+ },
+ {
+ "domains": ["nike.com"],
+ "image_url": "images/nike@2x.jpg",
+ "favicon_url": "favicons/nike.ico"
+ },
+ {
+ "domains": ["ok.ru"],
+ "image_url": "images/ok-ru@2x.png",
+ "favicon_url": "favicons/ok-ru.ico"
+ },
+ {
+ "domains": ["olx.pl"],
+ "image_url": "images/olx-pl@2x.png",
+ "favicon_url": "favicons/olx-pl.ico"
+ },
+ {
+ "domains": ["reddit.com"],
+ "image_url": "images/reddit-com@2x.png",
+ "favicon_url": "favicons/reddit-com.png"
+ },
+ {
+ "domains": ["samsung.com"],
+ "image_url": "images/samsung@2x.jpg",
+ "favicon_url": "favicons/samsung.ico"
+ },
+ {
+ "domains": ["turbotax.intuit.com"],
+ "image_url": "images/turbotax@2x.jpg",
+ "favicon_url": "favicons/turbotax.png"
+ },
+ {
+ "domains": ["twitter.com"],
+ "image_url": "images/twitter-com@2x.png",
+ "favicon_url": "favicons/twitter-com.ico"
+ },
+ {
+ "domains": ["vk.com"],
+ "image_url": "images/vk-com@2x.png",
+ "favicon_url": "favicons/vk-com.ico"
+ },
+ {
+ "domains": ["vodafone.co.uk"],
+ "image_url": "images/vodafone@2x.jpg",
+ "favicon_url": "favicons/vodafone.png"
+ },
+ {
+ "domains": ["weibo.com"],
+ "image_url": "images/weibo-com@2x.png",
+ "favicon_url": "favicons/weibo-com.ico"
+ },
+ {
+ "domains": ["wikipedia.org"],
+ "image_url": "images/wikipedia-org@2x.png",
+ "favicon_url": "favicons/wikipedia-org.ico"
+ },
+ {
+ "domains": ["wix.com"],
+ "image_url": "images/wix@2x.jpg",
+ "favicon_url": "favicons/wix.ico"
+ },
+ {
+ "domains": ["wykop.pl"],
+ "image_url": "images/wykop-pl@2x.png",
+ "favicon_url": "favicons/wykop-pl.png"
+ },
+ {
+ "domains": ["yandex.com", "yandex.com.tr"],
+ "image_url": "images/yandex-com@2x.png",
+ "favicon_url": "favicons/yandex-com.png"
+ },
+ {
+ "domains": ["yandex.by", "yandex.kz", "yandex.ru", "yandex.ua", "yandex.uz"],
+ "image_url": "images/yandex-ru@2x.png",
+ "favicon_url": "favicons/yandex-ru.png"
+ },
+ {
+ "domains": ["youtube.com"],
+ "image_url": "images/youtube-com@2x.png",
+ "favicon_url": "favicons/youtube-com.png"
+ },
+ {
+ "domains": ["zhihu.com"],
+ "image_url": "images/zhihu-com@2x.png",
+ "favicon_url": "favicons/zhihu-com.ico"
+ }
+]
diff --git a/browser/components/newtab/docs/index.rst b/browser/components/newtab/docs/index.rst
new file mode 100644
index 0000000000..06a626307e
--- /dev/null
+++ b/browser/components/newtab/docs/index.rst
@@ -0,0 +1,99 @@
+======================
+Firefox Home (New Tab)
+======================
+
+All files related to Firefox Home, which includes content that appears on `about:home`,
+`about:newtab`, and `about:welcome`, can be found in the `browser/components/newtab` directory.
+Some of these source files (such as `.js`, `.jsx`, and `.sass`) require an additional build step.
+We are working on migrating this to work with `mach`, but in the meantime, please
+follow the following steps if you need to make changes in this directory:
+
+For .jsm files
+---------------
+
+No build step is necessary. Use `mach` and run mochitests according to your regular Firefox workflow.
+
+For .js, .jsx, .sass, or .css files
+-----------------------------------
+
+Prerequisites
+`````````````
+
+You will need the following:
+
+- Node.js 10+ (On Mac, the best way to install Node.js is to use the install link on the `Node.js homepage`_)
+- npm (packaged with Node.js)
+
+To install dependencies, run the following from the root of the mozilla-central repository
+(or cd into browser/components/newtab to omit the `--prefix` in any of these commands):
+
+.. code-block:: shell
+
+ npm install --prefix browser/components/newtab
+
+
+Which files should you edit?
+````````````````````````````
+
+You should not make changes to `.js` or `.css` files in `browser/components/newtab/css` or
+`browser/components/newtab/data` directory. Instead, you should edit the `.jsx`, `.js`, and `.sass` files
+in `browser/components/newtab/content-src` directory.
+
+
+Building assets and running Firefox
+-----------------------------------
+
+To build assets and run Firefox, run the following from the root of the mozilla-central repository:
+
+.. code-block:: shell
+
+ npm run bundle --prefix browser/components/newtab && ./mach build && ./mach run
+
+Continuous development / debugging
+----------------------------------
+Running `npm run watchmc` will start a process that watches files in
+`activity-stream` and rebuilds the bundled files when JS or CSS files change.
+
+**IMPORTANT NOTE**: This task will add inline source maps to help with debugging, which changes the memory footprint.
+Do not use the `watchmc` task for profiling or performance testing!
+
+Running tests
+-------------
+The majority of New Tab / Messaging unit tests are written using
+`mocha <https://mochajs.org>`_, and other errors that may show up there are
+`SCSS <https://sass-lang.com/documentation/syntax>`_ issues flagged by
+`sasslint <https://github.com/sasstools/sass-lint/tree/master>`_. These things
+are all run using `npm test` under the `newtab` slug in Treeherder/Try, so if
+that slug turns red, these tests are what is failing. To execute them, do this:
+
+.. code-block:: shell
+
+ cd browser/components/newtab
+ npm test
+
+These tests are not currently run by `mach test`, but there's a
+`task filed to fix that <https://bugzilla.mozilla.org/show_bug.cgi?id=1581165>`_.
+
+Mochitests and xpcshell tests run normally, using `mach test`.
+
+Code Coverage
+-------------
+Our testing setup will run code coverage tools in addition to just the unit
+tests. It will error out if the code coverage metrics don't meet certain thresholds.
+
+If you see any missing test coverage, you can inspect the coverage report by
+running
+
+.. code-block:: shell
+
+ npm test && npm run debugcoverage
+
+Detailed Docs
+-------------
+.. toctree::
+ :titlesonly:
+ :glob:
+
+ v2-system-addon/*
+
+.. _Node.js homepage: https://nodejs.org/
diff --git a/browser/components/newtab/docs/v2-system-addon/about_home_startup_cache.md b/browser/components/newtab/docs/v2-system-addon/about_home_startup_cache.md
new file mode 100644
index 0000000000..584a683366
--- /dev/null
+++ b/browser/components/newtab/docs/v2-system-addon/about_home_startup_cache.md
@@ -0,0 +1,86 @@
+# The `about:home` startup cache
+
+By default, a user's browser session starts with a single window and a single tab, pointed at about:home. This means that it's important to ensure that `about:home` loads as quickly as possible to provide a fast overall startup experience.
+
+`about:home`, which is functionally identical to `about:newtab`, is generated dynamically by calculating an appropriate state object in the parent process, and passing it down to a content process into the React library in order to render the final interactive page. This is problematic during the startup sequence, as calculating that initial state can be computationally expensive, and requires multiple reads from the disk.
+
+The `about:home` startup cache is an attempt to address this expense. It works by assuming that between browser sessions, `about:home` _usually_ doesn't need to change.
+
+## Components of the `about:home` startup cache mechanism
+
+There are 3 primary components to the cache mechanism:
+
+### The HTTP Cache
+
+The HTTP cache is normally used for caching webpages retrieved over the network, but seemed like the right fit for storage of the `about:home` cache as well.
+
+The HTTP cache is usually queried by the networking stack when browsing the web. The HTTP cache is, however, not typically queried when accessing `chrome://` or `resource://` URLs, so we have to do it ourselves, manually for the `about:home` case. This means giving `about:home` special capabilities for populating and reading from the HTTP cache. In order to avoid potential security issues, this requires that we sequester `about:home` / `about:newtab` in their own special content process. The "privileged about content process" exists for this purpose, and is also used for `about:logins` and `about:certificate`.
+
+The HTTP cache lives in the parent process, and so any read and write operations need to be initiated in the parent process. Thankfully, however, the HTTP cache accepts data using `nsIOutputStream` and serves it using `nsIInputStream`. We can send `nsIInputStream` over the message manager, and convert an `nsIInputStream` into an `nsIOutputStream`, so we have everything we need to efficiently communicate with the "privileged about content process" to save and retrieve page data.
+
+The official documentation for the HTTP cache [can be found here](https://developer.mozilla.org/en-US/docs/Mozilla/HTTP_cache).
+
+### `AboutHomeStartupCache`
+
+This singleton component lives inside of `BrowserGlue` to avoid having to load yet another JSM out of the `omni.ja` file in the parent process during startup.
+
+`AboutHomeStartupCache` is responsible for feeding the "privileged about content process" with the `nsIInputStream`'s that it needs to present the initial `about:home` document. It is also responsible for populating the cache with updated versions of `about:home` that are sent by the "privileged about content process".
+
+Since accessing the HTTP cache is asynchronous, there is an opportunity for a race, where the cache can either be accessed and available before the initial `about:home` is requested, or after. To accommodate for both cases, the `AboutHomeStartupCache` constructs `nsIPipe` instances, which it sends down to the "privileged about content process" as soon as one launches.
+
+If the HTTP cache entry is already available when the process launches, and cached data is available, we connect the cache to the `nsIPipe`'s to stream the data down to the "privileged about content process".
+
+If the HTTP cache is not yet available, we hold references to those `nsIPipe` instances, and wait until the cache entry is available. Only then do we connect the cache entry to the `nsIPipe` instances to send the data down to the "privileged about content process".
+
+### `AboutNewTabService`
+
+The `AboutNewTabService` is used by the `AboutRedirector` in both the parent and content processes to determine how to handle attempts to load `about:home` and `about:newtab`.
+
+There are distinct versions of the `AboutNewTabService` - one for the parent process (`BaseAboutNewTabService`), and one for content processes (`AboutNewTabChildService`, which inherits from `BaseAboutNewTabService`).
+
+The `AboutRedirector`, when running inside of a "privileged about content process" knows to direct attempts to load `about:home` to `AboutNewTabChildService`'s `aboutHomeCacheChannel` method. This method is then responsible for choosing whether or not to return an `nsIChannel` for the cached document, or for the dynamically generated version of `about:home`.
+
+### `AboutHomeStartupCacheChild`
+
+This singleton component lives inside of the "privileged about content process", and is initialized as soon as the message is received from the parent that includes the `nsIInputStream`'s that will be used to potentially load from the cache.
+
+When the `AboutRedirector` in the "privileged about content process" notices that a request has been made to `about:home`, it asks `nsIAboutNewTabService` to return a new `nsIChannel` for that document. The `AboutNewTabChildService` then checks to see if the `AboutHomeStartupCacheChild` can return an `nsIChannel` for any cached content.
+
+If, at this point, nothing has been streamed from the parent, we fall back to loading the dynamic `about:home` document. This might occur if the cache doesn't exist yet, or if we were too slow to pull it off of the disk. Subsequent attempts to load `about:home` will bypass the cache and load the dynamic document instead. This is true even if the privileged about content process crashes and a new one is created.
+
+The `AboutHomeStartupCacheChild` will also be responsible for generating the cache periodically. Periodically, the `AboutNewTabService` will send down the most up-to-date state for `about:home` from the parent process, and then the `AboutHomeStartupCacheChild` will generate document markup using ReactDOMServer within a `ChromeWorker`. After that's generated, the "privileged about content process" will send up `nsIInputStream` instances for both the markup and the script for the initial page state. The `AboutHomeStartupCache` singleton inside of `BrowserGlue` is responsible for receiving those `nsIInputStream`'s and persisting them in the HTTP cache for the next start.
+
+## What is cached?
+
+Two things are cached:
+
+1. The raw HTML mark-up of `about:home`.
+2. A small chunk of JavaScript that "hydrates" the markup through the React libraries, allowing the page to become interactive after painting.
+
+The JavaScript being cached cannot be put directly into the HTML mark-up as inline script due to the CSP of `about:home`, which does not allow inline scripting. Instead, we load a script from `about:home?jscache`. This goes through the same mechanism for retrieving the HTML document from the cache, but instead pulls down the cached script.
+
+If the HTML mark-up is cached, then we presume that the script is also cached. We cannot cache one and not the other. If only one cache exists, or only one has been sent down to the "privileged about content process" by the time the `about:home` document is requested, then we fallback to loading the dynamic `about:home` document.
+
+## Refreshing the cache
+
+The cache is refreshed periodically by having `ActivityStreamMessageChannel` tell `AboutHomeStartupCache` when it has sent any messages down to the preloaded `about:newtab`. In general, such messages are a good hint that something visual has updated for the next `about:newtab`, and that the cache should probably be refreshed.
+
+`AboutHomeStartupCache` debounces notifications about such messages, since they tend to be bursty.
+
+## Invalidating the cache
+
+It's possible that the composition or layout of `about:home` will change over time from release to release. When this occurs, it might be desirable to invalidate any pre-existing cache that might exist for a user, so that they don't see an outdated `about:home` on startup.
+
+To do this, we set a version number on the cache entry, and ensure that the version number is equal to our expectations on startup. If the version number does not match our expectation, then the cache is discarded and the `about:home` document will be rendered dynamically.
+
+The version number is currently set to the application build ID. This means that when the application updates, the cache is invalidated on the first restart after a browser update is applied.
+
+## Handling errors
+
+`about:home` is typically the first thing that the user sees upon starting the browser. It is critically important that it function quickly and correctly. If anything happens to go wrong when retrieving or saving to the cache, we should fall back to generating the document dynamically.
+
+As an example, it's theoretically possible for the browser to crash while in the midst of saving to the cache. In that case, we might have a partial document saved, or a partial script saved - neither of which is acceptable.
+
+Thankfully, the HTTP cache was designed with resilience in mind, so partially written entries are automatically discarded, which allows us to fall back to the dynamic page generation mode.
+
+As additional redundancy to that resilience, we also make sure to create a new nsICacheEntry every time the cache is populated, and write the version metadata as the last step. Since the version metadata is written last, we know that if it's missing when we try to load the cache that the writing of the page and the script did not complete, and that we should fall back to dynamically rendering the page.
diff --git a/browser/components/newtab/docs/v2-system-addon/data_dictionary.md b/browser/components/newtab/docs/v2-system-addon/data_dictionary.md
new file mode 100644
index 0000000000..57bb61e745
--- /dev/null
+++ b/browser/components/newtab/docs/v2-system-addon/data_dictionary.md
@@ -0,0 +1,341 @@
+# Activity Stream Pings
+
+The Activity Stream system add-on sends various types of pings to the backend (HTTPS POST) [Onyx server](https://github.com/mozilla/onyx) :
+- a `health` ping that reports whether or not a user has a custom about:home or about:newtab page
+- a `session` ping that describes the ending of an Activity Stream session (a new tab is closed or refreshed), and
+- an `event` ping that records specific data about individual user interactions while interacting with Activity Stream
+- an `impression_stats` ping that records data about Pocket impressions and user interactions
+
+Schema definitions/validations that can be used for tests can be found in `system-addon/test/schemas/pings.js`.
+
+## Example Activity Stream `health` log
+
+```js
+{
+ "addon_version": "20180710100040",
+ "client_id": "374dc4d8-0cb2-4ac5-a3cf-c5a9bc3c602e",
+ "locale": "en-US",
+ "version": "62.0a1",
+ "release_channel": "nightly",
+ "event": "AS_ENABLED",
+ "value": 10,
+
+ // These fields are generated on the server
+ "date": "2016-03-07",
+ "ip": "10.192.171.13",
+ "ua": "python-requests/2.9.1",
+ "receive_at": 1457396660000
+}
+```
+
+## Example Activity Stream `session` Log
+
+```js
+{
+ // These fields are sent from the client
+ "action": "activity_stream_session",
+ "addon_version": "20180710100040",
+ "client_id": "374dc4d8-0cb2-4ac5-a3cf-c5a9bc3c602e",
+ "locale": "en-US",
+ "page": ["about:newtab" | "about:home" | "about:welcome" | "unknown"],
+ "session_duration": 1635,
+ "session_id": "{12dasd-213asda-213dkakj}",
+ "profile_creation_date": 14786,
+ "user_prefs": 7
+
+ // These fields are generated on the server
+ "date": "2016-03-07",
+ "ip": "10.192.171.13",
+ "ua": "python-requests/2.9.1",
+ "receive_at": 1457396660000
+}
+```
+
+## Example Activity Stream `user_event` Log
+
+```js
+{
+ "action": "activity_stream_user_event",
+ "action_position": "3",
+ "addon_version": "20180710100040",
+ "client_id": "374dc4d8-0cb2-4ac5-a3cf-c5a9bc3c602e",
+ "event": "click or scroll or search or delete",
+ "locale": "en-US",
+ "page": ["about:newtab" | "about:home" | "about:welcome" | "unknown"],
+ "source": "top sites, or bookmarks, or...",
+ "session_id": "{12dasd-213asda-213dkakj}",
+ "recommender_type": "pocket-trending",
+ "metadata_source": "MetadataService or Local or TippyTopProvider",
+ "user_prefs": 7
+
+ // These fields are generated on the server
+ "ip": "10.192.171.13",
+ "ua": "python-requests/2.9.1",
+ "receive_at": 1457396660000,
+ "date": "2016-03-07",
+}
+```
+
+## Example Activity Stream `impression_stats` Logs
+
+```js
+{
+ "impression_id": "{005deed0-e3e4-4c02-a041-17405fd703f6}",
+ "addon_version": "20180710100040",
+ "locale": "en-US",
+ "source": "pocket",
+ "page": ["about:newtab" | "about:home" | "about:welcome" | "unknown"]
+ "tiles": [{"id": 10000}, {"id": 10001}, {"id": 10002}]
+ "user_prefs": 7
+}
+```
+
+```js
+{
+ "impression_id": "{005deed0-e3e4-4c02-a041-17405fd703f6}",
+ "addon_version": "20180710100040",
+ "locale": "en-US",
+ "source": "pocket",
+ "page": "unknown",
+ "user_prefs": 7,
+
+ // "pos" is the 0-based index to record the tile's position in the Pocket section.
+ // "shim" is a base64 encoded shim attached to spocs, unique to the impression from the Ad server.
+ "tiles": [{"id": 10000, "pos": 0, "shim": "enuYa1j73z3RzxgTexHNxYPC/b,9JT6w5KB0CRKYEU+"}],
+
+ // A 0-based index to record which tile in the "tiles" list that the user just interacted with.
+ "click|block|pocket": 0
+}
+```
+
+## Example Activity Stream `Router` Pings
+
+```js
+{
+ "client_id": "n/a",
+ "action": ["snippets_user_event" | "onboarding_user_event"],
+ "impression_id": "{005deed0-e3e4-4c02-a041-17405fd703f6}",
+ "source": "pocket",
+ "addon_version": "20180710100040",
+ "locale": "en-US",
+ "source": "NEWTAB_FOOTER_BAR",
+ "message_id": "some_snippet_id",
+ "event": "IMPRESSION",
+ "event_context": "{\"view\":\"application_menu\"}"
+}
+```
+
+```eval_rst
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| KEY | DESCRIPTION | |
++============================+======================================================================================================================================================+==================+
+| ``action_position`` | [Optional] The index of the element in the ``source`` that was clicked. | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``action`` | [Required] Either ``activity_stream_event`` or ``activity_stream_session``. | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``addon_version`` | [Required] Firefox build ID, i.e. ``Services.appinfo.appBuildID``. | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``client_id`` | [Required] An identifier for this client. | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``card_type`` | [Optional] ("bookmark", "pocket", "trending", "pinned", "search", "spoc", "organic") | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``search_vendor`` | [Optional] the vendor of the search shortcut, one of ("google", "amazon", "wikipedia", "duckduckgo", "bing", etc.). This field only exists when | |
+| | ``card_type = "search"`` | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``date`` | [Auto populated by Onyx] The date in YYYY-MM-DD format. | :three: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``shield_id`` | [Optional] DEPRECATED: use `experiments` instead. The unique identifier for a specific experiment. | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``event`` | [Required] The type of event. Any user defined string ("click", "share", "delete", "more\_items") | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``event_context`` | [Optional] A string to record the context of an AS Router event ping. Compound context values will be stringified by JSON.stringify | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``highlight_type`` | [Optional] Either ["bookmarks", "recommendation", "history"]. | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``impression_id`` | [Optional] The unique impression identifier for a specific client. | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``ip`` | [Auto populated by Onyx] The IP address of the client. | :two: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``locale`` | [Auto populated by Onyx] The browser chrome's language (eg. en-US). | :two: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``load_trigger_ts`` | [Optional][Server Counter][Server Alert for too many omissions] DOMHighResTimeStamp of the action perceived by the user to trigger the load of this | |
+| | page. | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``load_trigger_type`` | [Server Counter][Server Alert for too many omissions] Either ["first\_window\_opened", "menu\_plus\_or\_keyboard", "unexpected"]. | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``metadata_source`` | [Optional] The source of which we computed metadata. Either (``MetadataService`` or ``Local`` or ``TippyTopProvider``). | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``page`` | [Required] One of ["about:newtab", "about:home", "about:welcome", "unknown" (which either means not-applicable or is a bug)]. | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``recommender_type`` | [Optional] The type of recommendation that is being shown, if any. | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``session_duration`` | [Optional][Server Counter][Server Alert for too many omissions] Time in (integer) milliseconds of the difference between the new tab becoming visible| :one: |
+| | and losing focus | |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``session_id`` | [Optional] The unique identifier for a specific session. | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``source`` | [Required] Either ("recent\_links", "recent\_bookmarks", "frecent\_links", "top\_sites", "spotlight", "sidebar") and indicates what ``action``. | :two: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``received_at`` | [Auto populated by Onyx] The time in ms since epoch. | :three: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``total_bookmarks`` | [Optional] The total number of bookmarks in the user's places db. | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``total_history_size`` | [Optional] The number of history items currently in the user's places db. | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``ua`` | [Auto populated by Onyx] The user agent string. | :two: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``unload_reason`` | [Required] The reason the Activity Stream page lost focus. | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``url`` | [Optional] The URL of the recommendation shown in one of the highlights spots, if any. | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``value`` (event) | [Optional] An object with keys "icon\_type" and "card\_type" to record the extra information for event ping | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``ver`` | [Auto populated by Onyx] The version of the Onyx API the ping was sent to. | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``highlights_size`` | [Optional] The size of the Highlights set. | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| highlights_data_late_by_ms | [Optional] Time in ms it took for Highlights to become initialized | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| topsites_data_late_by_ms | [Optional] Time in ms it took for TopSites to become initialized | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| topstories.domain.affinity | [Optional] Time in ms it took for domain affinities to be calculated (topstories.domain.affinity.calculation.ms) | :one: |
+| .calculation.ms | | |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| topsites_first_painted_ts | [Optional][Service Counter][Server Alert for too many omissions] Timestamp of when the Top Sites element finished painting (possibly with only | |
+| | placeholder screenshots) | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``custom_screenshot`` | [Optional] Number of topsites that display a custom screenshot. | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``screenshot_with_icon`` | [Optional] Number of topsites that display a screenshot and a favicon. | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``screenshot`` | [Optional] Number of topsites that display only a screenshot. | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``tippytop`` | [Optional] Number of topsites that display a tippytop icon. | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``rich_icon`` | [Optional] Number of topsites that display a high quality favicon. | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``no_image`` | [Optional] Number of topsites that have no screenshot. | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``topsites_pinned`` | [Optional] Number of topsites that are pinned. | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| topsites_search_shortcuts | [Optional] Number of search shortcut topsites. | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| visibility_event_rcvd_ts | [Optional][Server Counter][Server Alert for too many omissions] DOMHighResTimeStamp of when the page itself receives an event that | |
+| | document.visibilityState == visible. | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``tiles`` | [Required] A list of tile objects for the Pocket articles. Each tile object mush have a ID, optionally a "pos" property to indicate the tile | |
+| | position, and optionally a "shim" property unique to the impression from the Ad server | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``click`` | [Optional] An integer to record the 0-based index when user clicks on a Pocket tile. | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``block`` | [Optional] An integer to record the 0-based index when user blocks a Pocket tile. | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``pocket`` | [Optional] An integer to record the 0-based index when user saves a Pocket tile to Pocket. | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``user_prefs`` | [Required] The encoded integer of user's preferences. | :one: & :four: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``is_preloaded`` | [Required] A boolean to signify whether the page is preloaded or not | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``icon_type`` | [Optional] ("tippytop", "rich\_icon", "screenshot\_with\_icon", "screenshot", "no\_image", "custom\_screenshot") | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``region`` | [Optional] A string maps to pref "browser.search.region", which is essentially the two letter ISO 3166-1 country code populated by the Firefox | |
+| | search service. Note that: 1). it reports "OTHER" for those regions with smaller Firefox user base (less than 10000) so that users cannot be | |
+| | uniquely identified; 2). it reports "UNSET" if this pref is missing; 3). it reports "EMPTY" if the value of this pref is an empty string. | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``profile_creation_date`` | [Optional] An integer to record the age of the Firefox profile as the total number of days since the UNIX epoch. | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``message_id`` | [required] A string identifier of the message in Activity Stream Router. | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``has_flow_params`` | [required] One of [true, false]. A boolean identifier that indicates if Firefox Accounts flow parameters are set or unset. | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``displayed`` | [required] 1: a SPOC is displayed; 0: non-displayed | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``reason`` | [required] The reason if a SPOC is not displayed, "n/a" for the displayed, one of ("frequency\_cap", "blocked\_by\_user", "flight\_duplicate", | |
+| | "probability\_selection", "below\_min\_score", "out\_of\_position", "n/a") | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``full_recalc`` | [required] Is it a full SPOCS recalculation: 0: false; 1: true. Recalculation case: 1). fetch SPOCS from Pocket endpoint. Non-recalculation cases: | |
+| | 1). An impression updates the SPOCS; 2). Any action that triggers the ``selectLayoutRender`` | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``experiments`` | [Optional] An object to record all active experiments (an empty object will be sent if there is no active experiment). The experiments IDs are | :one: |
+| | stored as keys, and the value object stores the branch information. | |
+| | `Example: {"experiment_1": {"branch": "control"}, "experiment_2": {"branch": "treatment"}}`. This deprecates the `shield_id` used in Activity Stream | |
+| | and Messaging System. | |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``browser_session_id`` | [Optional] The unique identifier for a browser session, retrieved from TelemetrySession | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``attribution.source`` | [Optional] Referring partner domain, when install happens via a known partner | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``attribution.medium`` | [Optional] Category of the source, such as 'organic' for a search engine | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``attribution.campaign`` | [Optional] Identifier of the particular campaign that led to the download of the product | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``attribution.content`` | [Optional] Identifier to indicate the particular link within a campaign | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``attribution.experiment`` | [Optional] Funnel experiment identifier, see bug 1567339 | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``attribution.variantion`` | [Optional] Funnel experiment variant identifier, see bug 1567339 | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+| ``attribution.ua`` | [Optional] Derived user agent, see bug 1595063 | :one: |
++----------------------------+------------------------------------------------------------------------------------------------------------------------------------------------------+------------------+
+```
+
+**Where:**
+
+* :one: Firefox data
+* :two: HTTP protocol data
+* :three: server augmented data
+* :four: User preferences encoding table
+
+
+Note: the following session-related fields are not yet implemented in the system-addon,
+but will likely be added in future versions:
+
+```js
+{
+ "total_bookmarks": 19,
+ "total_history_size": 9,
+ "highlights_size": 20
+}
+```
+
+## Encoding and decoding of `user_prefs`
+
+This encoding mapping was defined in `system-addon/lib/TelemetryFeed.jsm`
+
+```eval_rst
++-------------------+------------------------+
+| Preference | Encoded value (binary) |
++===================+========================+
+| `showSearch` | 1 (00000001) |
++-------------------+------------------------+
+| `showTopSites` | 2 (00000010) |
++-------------------+------------------------+
+| `showTopStories` | 4 (00000100) |
++-------------------+------------------------+
+| `showHighlights` | 8 (00001000) |
++-------------------+------------------------+
+| `showSnippets` | 16 (00010000) |
++-------------------+------------------------+
+| `showSponsored` | 32 (00100000) |
++-------------------+------------------------+
+| `showCFRAddons` | 64 (01000000) |
++-------------------+------------------------+
+| `showCFRFeatures` | 128 (10000000) |
++-------------------+------------------------+
+```
+
+Each item above could be combined with other items through bitwise OR (`|`) operation.
+
+Examples:
+
+* Everything is on, `user_prefs = 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128 = 255`
+* Everything is off, `user_prefs = 0`
+* Only show search and Top Stories, `user_prefs = 1 | 4 = 5`
+* Everything except Highlights, `user_prefs = 1 | 2 | 4 | 16 | 32 | 64 | 128 = 247`
+
+Likewise, one can use bitwise AND (`&`) for decoding.
+
+* Check if everything is shown, `user_prefs & (1 | 2 | 4 | 8 | 16 | 32 | 64 | 128)` or `user_prefs == 255`
+* Check if everything is off, `user_prefs == 0`
+* Check if search is shown, `user_prefs & 1`
+* Check if both Top Sites and Top Stories are shown, `(user_prefs & 2) && (user_prefs & 4)`, or `(user_prefs & (2 | 4)) == (2 | 4)`
diff --git a/browser/components/newtab/docs/v2-system-addon/data_events.md b/browser/components/newtab/docs/v2-system-addon/data_events.md
new file mode 100644
index 0000000000..f60301b15b
--- /dev/null
+++ b/browser/components/newtab/docs/v2-system-addon/data_events.md
@@ -0,0 +1,1144 @@
+# Metrics we collect
+
+By default, the about:newtab, about:welcome and about:home pages in Firefox (the pages you see when you open a new tab and when you start the browser), will send data back to Mozilla servers about usage of these pages. The intent is to collect data in order to improve the user's experience while using Activity Stream. Data about your specific browsing behaior or the sites you visit is **never transmitted to any Mozilla server**. At any time, it is easy to **turn off** this data collection by [opting out of Firefox telemetry](https://support.mozilla.org/kb/share-telemetry-data-mozilla-help-improve-firefox).
+
+Data is sent to our servers in the form of discreet HTTPS 'pings' or messages whenever you do some action on the Activity Stream about:home, about:newtab or about:welcome pages. We try to minimize the amount and frequency of pings by batching them together. Pings are sent in [JSON serialized format](http://www.json.org/).
+
+At Mozilla, [we take your privacy very seriously](https://www.mozilla.org/privacy/). The Activity Stream page will never send any data that could personally identify you. We do not transmit what you are browsing, searches you perform or any private settings. Activity Stream does not set or send cookies, and uses [Transport Layer Security](https://en.wikipedia.org/wiki/Transport_Layer_Security) to securely transmit data to Mozilla servers.
+
+Data collected from Activity Stream is retained on Mozilla secured servers for a period of 30 days before being rolled up into an anonymous aggregated format. After this period the raw data is deleted permanently. Mozilla **never shares data with any third party**.
+
+The following is a detailed overview of the different kinds of data we collect in the Activity Stream. See [data_dictionary.md](data_dictionary.md) for more details for each field.
+
+## Page takeover ping
+
+This ping is submitted once upon Activity Stream initialization if either about:home or about:newtab are set to a custom URL. It sends the category of the custom URL. It also includes the web extension id of the extension controlling the home and/or newtab page.
+
+```js
+{
+ "event": "PAGE_TAKEOVER_DATA",
+ "value": {
+ "home_url_category": ["search-engine" | "search-engine-mozilla-tag" | "search-engine-other-tag" | "news-portal" | "ecommerce" | "social-media" | "known-hijacker" | "other"],
+ "home_extension_id": "26288a14-5cc4-d14f-ae0a-bb01ef45be9c",
+ "newtab_url_category": ["search-engine" | "search-engine-mozilla-tag" | "search-engine-other-tag" | "news-portal" | "ecommerce" | "social-media" | "known-hijacker" | "other"],
+ "newtab_extension_id": "26288a14-5cc4-d14f-ae0a-bb01ef45be9c",
+ },
+
+ // Basic metadata
+ "action": "activity_stream_event",
+ "client_id": "26288a14-5cc4-d14f-ae0a-bb01ef45be9c",
+ "session_id": "005deed0-e3e4-4c02-a041-17405fd703f6",
+ "browser_session_id": "e7e52665-7db3-f348-9918-e93160eb2ef3",
+  "addon_version": "20180710100040",
+  "locale": "en-US",
+ "experiments": {
+ "experiment_1": {"branch": "control"},
+ "experiment_2": {"branch": "treatment"}
+ },
+ "user_prefs": 7
+}
+```
+
+## User event pings
+
+These pings are captured when a user **performs some kind of interaction** in the add-on.
+
+### Basic shape
+
+A user event ping includes some basic metadata (tab id, addon version, etc.) as well as variable fields which indicate the location and action of the event.
+
+```js
+{
+ // This indicates the type of interaction
+  "event": ["CLICK", "SEARCH", "BLOCK", "DELETE", "OPEN_NEW_WINDOW", "OPEN_PRIVATE_WINDOW", "BOOKMARK_DELETE", "BOOKMARK_ADD", "OPEN_NEWTAB_PREFS", "CLOSE_NEWTAB_PREFS", "SEARCH_HANDOFF", "SHOW_PERSONALIZE", "HIDE_PERSONALIZE"],
+
+ // Optional field indicating the UI component type
+ "source": "TOP_SITES",
+
+ // Optional field if there is more than one of a component type on a page.
+ // It is zero-indexed.
+ // For example, clicking the second Highlight would result in an action_position of 1
+ "action_position": 1,
+
+ // Basic metadata
+ "page": ["about:newtab" | "about:home" | "about:welcome" | "unknown" ],
+  "client_id": "26288a14-5cc4-d14f-ae0a-bb01ef45be9c",
+ "session_id": "005deed0-e3e4-4c02-a041-17405fd703f6",
+ "browser_session_id": "e7e52665-7db3-f348-9918-e93160eb2ef3",
+  "addon_version": "20180710100040",
+  "locale": "en-US",
+ "action": "activity_stream_event",
+ "experiments": {
+ "experiment_1": {"branch": "control"},
+ "experiment_2": {"branch": "treatment"}
+ },
+ "user_prefs": 7
+}
+```
+
+### Types of user interactions
+
+#### Show/hide Personalization Panel
+
+```js
+{
+ "event": [ "SHOW_PERSONALIZE" | "HIDE_PERSONALIZE" ], // Basic metadata
+ "action": "activity_stream_event",
+ "page": ["about:newtab" | "about:home" | "about:welcome" | "unknown"],
+ "client_id": "26288a14-5cc4-d14f-ae0a-bb01ef45be9c",
+ "session_id": "005deed0-e3e4-4c02-a041-17405fd703f6",
+ "browser_session_id": "e7e52665-7db3-f348-9918-e93160eb2ef3",
+ "addon_version": "20180710100040",
+ "locale": "en-US",
+ "user_prefs": 7
+}
+```
+
+#### Performing a search
+
+```js
+{
+  "event": "SEARCH",
+
+ // Basic metadata
+ "action": "activity_stream_event",
+ "page": ["about:newtab" | "about:home" | "about:welcome" | "unknown"],
+  "client_id": "26288a14-5cc4-d14f-ae0a-bb01ef45be9c",
+ "session_id": "005deed0-e3e4-4c02-a041-17405fd703f6",
+ "browser_session_id": "e7e52665-7db3-f348-9918-e93160eb2ef3",
+  "addon_version": "20180710100040",
+  "locale": "en-US",
+ "user_prefs": 7
+}
+```
+
+#### Performing a search handoff
+
+```js
+{
+  "event": "SEARCH_HANDOFF",
+
+ // Basic metadata
+ "action": "activity_stream_event",
+ "page": ["about:newtab" | "about:home" | "about:welcome" | "unknown"],
+  "client_id": "26288a14-5cc4-d14f-ae0a-bb01ef45be9c",
+ "session_id": "005deed0-e3e4-4c02-a041-17405fd703f6",
+ "browser_session_id": "e7e52665-7db3-f348-9918-e93160eb2ef3",
+  "addon_version": "20180710100040",
+  "locale": "en-US",
+ "user_prefs": 7
+}
+```
+
+#### Clicking a top site item
+
+```js
+{
+  "event": "CLICK",
+ "source": "TOP_SITES",
+  "action_position": 2,
+ "value": {
+ "card_type": ["pinned" | "search" | "spoc"],
+ "icon_type": ["screenshot_with_icon" | "screenshot" | "tippytop" | "rich_icon" | "no_image" | "custom_screenshot"],
+ // only exists if its card_type = "search"
+ "search_vendor": "google"
+ }
+
+ // Basic metadata
+ "action": "activity_stream_event",
+ "page": ["about:newtab" | "about:home" | "about:welcome" | "unknown"],
+ "client_id": "26288a14-5cc4-d14f-ae0a-bb01ef45be9c",
+ "session_id": "005deed0-e3e4-4c02-a041-17405fd703f6",
+ "browser_session_id": "e7e52665-7db3-f348-9918-e93160eb2ef3",
+  "addon_version": "20180710100040",
+  "locale": "en-US",
+ "user_prefs": 7
+}
+```
+
+#### Clicking a top story item
+
+```js
+{
+  "event": "CLICK",
+ "source": "CARDGRID",
+  "action_position": 2,
+ "value": {
+ // "spoc" for sponsored stories, "organic" for regular stories.
+ "card_type": ["organic" | "spoc"],
+ }
+
+ // Basic metadata
+ "action": "activity_stream_event",
+ "page": ["about:newtab" | "about:home" | "about:welcome" | "unknown"],
+ "client_id": "26288a14-5cc4-d14f-ae0a-bb01ef45be9c",
+ "session_id": "005deed0-e3e4-4c02-a041-17405fd703f6",
+ "browser_session_id": "e7e52665-7db3-f348-9918-e93160eb2ef3",
+  "addon_version": "20180710100040",
+  "locale": "en-US",
+ "user_prefs": 7
+}
+```
+
+#### Clicking a popular topic link
+
+```js
+{
+ "event": "CLICK",
+ "source": "POPULAR_TOPICS",
+ "value": {
+ "topic": ["must-reads" | "productivity" | "health" | "finance" | "technology" | "more-recommendations"]
+ }
+ // Basic metadata
+ "action": "activity_stream_event",
+ "page": ["about:newtab" | "about:home" | "about:welcome" | "unknown"],
+ "client_id": "26288a14-5cc4-d14f-ae0a-bb01ef45be9c",
+ "session_id": "005deed0-e3e4-4c02-a041-17405fd703f6",
+ "browser_session_id": "e7e52665-7db3-f348-9918-e93160eb2ef3",
+ "addon_version": "20180710100040",
+ "locale": "en-US",
+ "user_prefs": 7
+}
+```
+
+#### Adding a search shortcut
+```js
+{
+  "event": "SEARCH_EDIT_ADD",
+ "source": "TOP_SITES",
+  "action_position": 2,
+ "value": {
+ "search_vendor": "google"
+ }
+
+ // Basic metadata
+ "action": "activity_stream_event",
+ "page": ["about:newtab" | "about:home" | "about:welcome" | "unknown"],
+ "client_id": "26288a14-5cc4-d14f-ae0a-bb01ef45be9c",
+ "session_id": "005deed0-e3e4-4c02-a041-17405fd703f6",
+ "browser_session_id": "e7e52665-7db3-f348-9918-e93160eb2ef3",
+  "addon_version": "20180710100040",
+  "locale": "en-US",
+ "user_prefs": 7
+}
+```
+
+#### Showing privacy information
+
+```js
+{
+  "event": "SHOW_PRIVACY_INFO",
+ "source": "TOP_SITES",
+  "action_position": 2,
+
+ // Basic metadata
+ "action": "activity_stream_event",
+ "page": ["about:newtab" | "about:home" | "about:welcome" | "unknown"],
+ "client_id": "26288a14-5cc4-d14f-ae0a-bb01ef45be9c",
+ "session_id": "005deed0-e3e4-4c02-a041-17405fd703f6",
+ "browser_session_id": "e7e52665-7db3-f348-9918-e93160eb2ef3",
+  "addon_version": "20180710100040",
+  "locale": "en-US",
+ "user_prefs": 7
+}
+```
+
+#### Clicking on privacy information link
+
+```js
+{
+  "event": "CLICK_PRIVACY_INFO",
+ "source": "DS_PRIVACY_MODAL",
+
+ // Basic metadata
+ "action": "activity_stream_event",
+ "page": ["about:newtab" | "about:home" | "about:welcome" | "unknown"],
+ "client_id": "26288a14-5cc4-d14f-ae0a-bb01ef45be9c",
+ "session_id": "005deed0-e3e4-4c02-a041-17405fd703f6",
+ "browser_session_id": "e7e52665-7db3-f348-9918-e93160eb2ef3",
+  "addon_version": "20180710100040",
+  "locale": "en-US",
+ "user_prefs": 7
+}
+```
+
+#### Deleting a search shortcut
+```js
+{
+  "event": "SEARCH_EDIT_DELETE",
+ "source": "TOP_SITES",
+  "action_position": 2,
+ "value": {
+ "search_vendor": "google"
+ }
+
+ // Basic metadata
+ "action": "activity_stream_event",
+ "page": ["about:newtab" | "about:home" | "about:welcome" | "unknown"],
+ "client_id": "26288a14-5cc4-d14f-ae0a-bb01ef45be9c",
+ "session_id": "005deed0-e3e4-4c02-a041-17405fd703f6",
+ "browser_session_id": "e7e52665-7db3-f348-9918-e93160eb2ef3",
+  "addon_version": "20180710100040",
+  "locale": "en-US",
+ "user_prefs": 7
+}
+```
+
+#### Deleting an item from history
+
+```js
+{
+  "event": "DELETE",
+ "source": "TOP_SITES",
+  "action_position": 2,
+ "value": {
+ "card_type": "pinned",
+ "icon_type": ["screenshot_with_icon" | "screenshot" | "tippytop" | "rich_icon" | "no_image" | "custom_screenshot"]
+ }
+
+ // Basic metadata
+ "action": "activity_stream_event",
+ "page": ["about:newtab" | "about:home" | "about:welcome" | "unknown"],
+ "client_id": "26288a14-5cc4-d14f-ae0a-bb01ef45be9c",
+ "session_id": "005deed0-e3e4-4c02-a041-17405fd703f6",
+ "browser_session_id": "e7e52665-7db3-f348-9918-e93160eb2ef3",
+  "addon_version": "20180710100040",
+  "locale": "en-US",
+ "user_prefs": 7
+}
+```
+
+#### Blocking a site
+
+```js
+{
+  "event": "BLOCK",
+ "source": "TOP_SITES",
+  "action_position": 2,
+ "value": {
+ "card_type": ["pinned" | "search" | "spoc"],
+ "icon_type": ["screenshot_with_icon" | "screenshot" | "tippytop" | "rich_icon" | "no_image" | "custom_screenshot"],
+ // only exists if its card_type = "search"
+ "search_vendor": "google"
+ }
+
+ // Basic metadata
+ "action": "activity_stream_event",
+ "page": ["about:newtab" | "about:home" | "about:welcome" | "unknown"],
+ "client_id": "26288a14-5cc4-d14f-ae0a-bb01ef45be9c",
+ "session_id": "005deed0-e3e4-4c02-a041-17405fd703f6",
+ "browser_session_id": "e7e52665-7db3-f348-9918-e93160eb2ef3",
+  "addon_version": "20180710100040",
+  "locale": "en-US",
+ "user_prefs": 7
+}
+```
+
+#### Bookmarking a link
+
+```js
+{
+  "event": "BOOKMARK_ADD",
+ "source": "HIGHLIGHTS",
+  "action_position": 2,
+ "value": {
+ "card_type": "trending"
+ }
+  
+ // Basic metadata
+ "action": "activity_stream_event",
+ "page": ["about:newtab" | "about:home" | "about:welcome"],
+ "client_id": "26288a14-5cc4-d14f-ae0a-bb01ef45be9c",
+ "session_id": "005deed0-e3e4-4c02-a041-17405fd703f6",
+ "browser_session_id": "e7e52665-7db3-f348-9918-e93160eb2ef3",
+  "addon_version": "20180710100040",
+  "locale": "en-US",
+ "user_prefs": 7
+}
+```
+
+#### Removing a bookmark from a link
+
+```js
+{
+  "event": "BOOKMARK_DELETE",
+ "source": "HIGHLIGHTS",
+  "action_position": 2,
+ "value": {
+ "card_type": "bookmark"
+ }
+
+ // Basic metadata
+ "action": "activity_stream_event",
+ "page": ["about:newtab" | "about:home" | "about:welcome" | "unknown"],
+ "client_id": "26288a14-5cc4-d14f-ae0a-bb01ef45be9c",
+ "session_id": "005deed0-e3e4-4c02-a041-17405fd703f6",
+ "browser_session_id": "e7e52665-7db3-f348-9918-e93160eb2ef3",
+  "addon_version": "20180710100040",
+  "locale": "en-US",
+ "user_prefs": 7
+}
+```
+
+#### Opening a link in a new window
+
+```js
+{
+  "event": "OPEN_NEW_WINDOW",
+ "source": "TOP_SITES",
+  "action_position": 2,
+ "value": {
+ "card_type": "pinned",
+ "icon_type": ["screenshot_with_icon" | "screenshot" | "tippytop" | "rich_icon" | "no_image" | "custom_screenshot"]
+ }
+
+ // Basic metadata
+ "action": "activity_stream_event",
+ "page": ["about:newtab" | "about:home" | "about:welcome" | "unknown"],
+ "client_id": "26288a14-5cc4-d14f-ae0a-bb01ef45be9c",
+ "session_id": "005deed0-e3e4-4c02-a041-17405fd703f6",
+ "browser_session_id": "e7e52665-7db3-f348-9918-e93160eb2ef3",
+  "addon_version": "20180710100040",
+  "locale": "en-US",
+ "user_prefs": 7
+}
+```
+
+#### Opening a link in a new private window
+
+```js
+{
+  "event": "OPEN_PRIVATE_WINDOW",
+ "source": "TOP_SITES",
+  "action_position": 2,
+ "value": {
+ "card_type": "pinned",
+ "icon_type": ["screenshot_with_icon" | "screenshot" | "tippytop" | "rich_icon" | "no_image" | "custom_screenshot"]
+ }
+
+ // Basic metadata
+ "action": "activity_stream_event",
+ "page": ["about:newtab" | "about:home" | "about:welcome" | "unknown"],
+ "client_id": "26288a14-5cc4-d14f-ae0a-bb01ef45be9c",
+ "session_id": "005deed0-e3e4-4c02-a041-17405fd703f6",
+ "browser_session_id": "e7e52665-7db3-f348-9918-e93160eb2ef3",
+  "addon_version": "20180710100040",
+  "locale": "en-US",
+ "user_prefs": 7
+}
+```
+
+#### Opening the new tab preferences pane
+
+```js
+{
+  "event": "OPEN_NEWTAB_PREFS",
+
+ // Basic metadata
+ "action": "activity_stream_event",
+ "page": ["about:newtab" | "about:home" | "about:welcome" | "unknown"],
+ "client_id": "26288a14-5cc4-d14f-ae0a-bb01ef45be9c",
+ "session_id": "005deed0-e3e4-4c02-a041-17405fd703f6",
+ "browser_session_id": "e7e52665-7db3-f348-9918-e93160eb2ef3",
+  "addon_version": "20180710100040",
+  "locale": "en-US",
+ "user_prefs": 7
+}
+```
+
+#### Closing the new tab preferences pane
+
+```js
+{
+  "event": "CLOSE_NEWTAB_PREFS",
+
+ // Basic metadata
+ "action": "activity_stream_event",
+ "page": ["about:newtab" | "about:home" | "about:welcome" | "unknown"],
+ "client_id": "26288a14-5cc4-d14f-ae0a-bb01ef45be9c",
+ "session_id": "005deed0-e3e4-4c02-a041-17405fd703f6",
+ "browser_session_id": "e7e52665-7db3-f348-9918-e93160eb2ef3",
+  "addon_version": "20180710100040",
+  "locale": "en-US",
+ "user_prefs": 7
+}
+```
+
+#### Changing preferences from about:preferences#home or on the customize menu on the newtab page.
+
+```js
+{
+ "event": "PREF_CHANGED",
+ "source": "TOP_STORIES|POCKET_SPOCS|HIGHLIGHTS|SNIPPETS|TOP_SITES|SPONSORED_TOP_SITES",
+ "value": "{\"status\":true|false,\"menu_source\":\"ABOUT_PREFERENCES|CUSTOMIZE_MENU\"}"
+ "release_channel": "default",
+ "experiments": {},
+ "client_id": "26288a14-5cc4-d14f-ae0a-bb01ef45be9c",
+ "browser_session_id": "e7e52665-7db3-f348-9918-e93160eb2ef3",
+ "addon_version": "20180710100040",
+ "locale": "en-US",
+ "user_prefs": 7
+}
+```
+
+#### Pinning a tab
+
+```js
+{
+ "event": "TABPINNED",
+ "source": "TAB_CONTEXT_MENU",
+ "value": "{\"total_pinned_tabs\":2}",
+
+ // Basic metadata
+ "action": "activity_stream_user_event",
+ "client_id": "aabaace5-35f4-7345-a28e-5502147dc93c",
+ "version": "67.0a1",
+ "addon_version": "20190218094427",
+ "locale": "en-US",
+ "user_prefs": 59,
+ "page": "n/a",
+ "session_id": "n/a",
+ "browser_session_id": "e7e52665-7db3-f348-9918-e93160eb2ef3"
+}
+```
+
+#### Adding or editing a new TopSite
+
+```js
+{
+ "event": "TOP_SITES_EDIT",
+ "source": "TOP_SITES_SOURCE",
+ "browser_session_id": "e7e52665-7db3-f348-9918-e93160eb2ef3",
+ // "-1" Is used for prepending a new TopSite at the front of the list, while
+ // any other possible value is used for editing an existing TopSite slot.
+ "action_position": [-1 | "0..TOP_SITES_LENGTH"]
+}
+```
+
+#### Requesting a custom screenshot preview
+
+```js
+{
+ "event": "PREVIEW_REQUEST",
+ "browser_session_id": "e7e52665-7db3-f348-9918-e93160eb2ef3",
+ "source": "TOP_SITES"
+}
+```
+
+## Session end pings
+
+When a session ends, the browser will send a `"activity_stream_session"` ping to our metrics servers. This ping contains the length of the session, a unique reason for why the session ended, and some additional metadata.
+
+### Basic event
+
+All `"activity_stream_session"` pings have the following basic shape. Some fields are variable.
+
+```js
+{
+ "action": "activity_stream_session",
+ "client_id": "26288a14-5cc4-d14f-ae0a-bb01ef45be9c",
+ "session_id": "005deed0-e3e4-4c02-a041-17405fd703f6",
+ "addon_version": "20180710100040",
+ "locale": "en-US",
+ "page": ["about:newtab" | "about:home" | "about:welcome" | "unknown"],
+ "session_duration": 4199,
+ "profile_creation_date": 14786,
+ "experiments": {
+ "experiment_1": {"branch": "control"},
+ "experiment_2": {"branch": "treatment"}
+ },
+ "user_prefs": 7
+}
+```
+
+### What causes a session end?
+
+Here are different scenarios that cause a session end event to be sent:
+
+1. After a search
+2. Clicking on something that causes navigation (top site, highlight, etc.)
+3. Closing the browser
+5. Refreshing
+6. Navigating to a new URL via the url bar or file menu
+
+
+### Session performance data
+
+This data is held in a child object of the `activity_stream_session` event called `perf`. All fields suffixed by `_ts` are type `DOMHighResTimeStamp` (aka a double of milliseconds, with a 5 microsecond precision) with 0 being the [timeOrigin](https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp#The_time_origin) of the browser's hidden chrome window.
+
+An example might look like this:
+
+```javascript
+perf: {
+ // Timestamp of the action perceived by the user to trigger the load
+ // of this page.
+ //
+ // Not required at least for error cases where the
+ // observer event doesn't fire
+ "load_trigger_ts": 1,
+
+ // What was the perceived trigger of the load action:
+ "load_trigger_type": [
+ "first_window_opened" | // home only
+ "menu_plus_or_keyboard" | // newtab only
+ "unexpected" // sessions lacking actual start times
+ ],
+
+ // when the page itself receives an event that document.visibilityStat=visible
+ "visibility_event_rcvd_ts": 2,
+
+ // When did the topsites element finish painting? Note that, at least for
+ // the first tab to be loaded, and maybe some others, this will be before
+ // topsites has yet to receive screenshots updates from the add-on code,
+ // and is therefore just showing placeholder screenshots.
+ "topsites_first_painted_ts": 5,
+
+ // The 6 different types of TopSites icons and how many of each kind did the
+ // user see.
+ "topsites_icon_stats": {
+ "custom_screenshot": 0,
+ "screenshot_with_icon": 2,
+ "screenshot": 1,
+ "tippytop": 2,
+ "rich_icon": 1,
+ "no_image": 0
+ },
+
+ // The number of Top Sites that are pinned.
+ "topsites_pinned": 3,
+
+ // The number of search shortcut Top Sites.
+ "topsites_search_shortcuts": 2,
+
+ // How much longer the data took, in milliseconds, to be ready for display
+ // than it would have been in the ideal case. The user currently sees placeholder
+ // cards instead of real cards for approximately this length of time. This is
+ // sent when the first call of the component's `render()` method happens with
+ // `this.props.initialized` set to `false`, and the value is the amount of
+ // time in ms until `render()` is called with `this.props.initialized` set to `true`.
+ "highlights_data_late_by_ms": 67,
+ "topsites_data_late_by_ms": 35,
+
+ // Whether the page is preloaded or not.
+ "is_preloaded": [true|false],
+}
+```
+
+## Top Story pings
+
+When Top Story (currently powered by Pocket) is enabled in Activity Stream, the browser will send following `activity_stream_impression_stats` to our metrics servers.
+
+### Impression stats
+
+This reports all the Pocket recommended articles (a list of `id`s) when the user opens a newtab.
+
+```js
+{
+ "impression_id": "{005deed0-e3e4-4c02-a041-17405fd703f6}",
+ "addon_version": "20180710100040",
+ "locale": "en-US",
+ "source": "pocket",
+ "page": ["about:newtab" | "about:home" | "about:welcome" | "unknown"],
+ "user_prefs": 7,
+ "experiments": {
+ "experiment_1": {"branch": "control"},
+ "experiment_2": {"branch": "treatment"}
+ },
+ "tiles": [{"id": 10000}, {"id": 10001}, {"id": 10002}]
+}
+```
+
+### Click/block/save_to_pocket ping
+
+This reports the user's interaction with those Pocket tiles.
+
+```js
+{
+ "impression_id": "{005deed0-e3e4-4c02-a041-17405fd703f6}",
+ "addon_version": "20180710100040",
+ "locale": "en-US",
+ "source": "pocket",
+ "page": ["about:newtab" | "about:home" | "about:welcome" | "unknown"],
+ "experiments": {
+ "experiment_1": {"branch": "control"},
+ "experiment_2": {"branch": "treatment"}
+ },
+ "user_prefs": 7,
+
+ // "pos" is the 0-based index to record the tile's position in the Pocket section.
+ // "shim" is a base64 encoded shim attached to spocs, unique to the impression from the Ad server.
+ "tiles": [{"id": 10000, "pos": 0, "shim": "enuYa1j73z3RzxgTexHNxYPC/b,9JT6w5KB0CRKYEU+"}],
+
+ // A 0-based index to record which tile in the "tiles" list that the user just interacted with.
+ "click|block|pocket": 0
+}
+```
+
+## Save to Pocket button pings
+
+Right now the save to Pocket button, while technically outside of newtab, has some similarities with the newtab telemetry.
+
+These pings record user interaction with the save to Pocket button.
+
+### Click/impression ping
+
+```js
+{
+ "locale": "en-US",
+ "version": "83.0a1",
+ "release_channel": "default",
+ "model": "",
+ "events": [{"action":"click|impression|unpin","position":0,"source":"save_button|on_save_recs|learn_more|sign_up_1|sign_up_2|log_in"}],
+ "pocket_logged_in_state": true|false,
+ "impression_id": "{005deed0-e3e4-4c02-a041-17405fd703f6}",
+ "profile_creation_date": 18550
+}
+```
+
+## Activity Stream Router pings
+
+These pings record the impression and user interactions within Activity Stream Router.
+
+### Impression ping
+
+This reports the impression of Activity Stream Router.
+
+#### Snippets impression
+```js
+{
+ "client_id": "26288a14-5cc4-d14f-ae0a-bb01ef45be9c",
+ "action": "snippets_user_event",
+ "impression_id": "n/a",
+ "source": "SNIPPETS",
+ "addon_version": "20180710100040",
+ "locale": "en-US",
+ "experiments": {
+ "experiment_1": {"branch": "control"},
+ "experiment_2": {"branch": "treatment"}
+ },
+ "source": "NEWTAB_FOOTER_BAR",
+ "message_id": "some_snippet_id",
+ "event": "IMPRESSION"
+}
+```
+
+CFR impression ping has two forms, in which the message_id could be of different meanings.
+
+#### CFR impression for all the prerelease channels and shield experiment
+```js
+{
+ "client_id": "26288a14-5cc4-d14f-ae0a-bb01ef45be9c",
+ "action": "cfr_user_event",
+ "impression_id": "n/a",
+ "addon_version": "20180710100040",
+ "locale": "en-US",
+ "experiments": {
+ "experiment_1": {"branch": "control"},
+ "experiment_2": {"branch": "treatment"}
+ },
+ "source": "CFR",
+ // message_id could be the ID of the recommendation, such as "wikipedia_addon"
+ "message_id": "wikipedia_addon",
+ "event": "IMPRESSION"
+}
+```
+
+#### CFR impression for the release channel
+```js
+{
+ "client_id": "n/a",
+ "action": "cfr_user_event",
+ "impression_id": "{005deed0-e3e4-4c02-a041-17405fd703f6}",
+ "addon_version": "20180710100040",
+ "locale": "en-US",
+ "experiments": {
+ "experiment_1": {"branch": "control"},
+ "experiment_2": {"branch": "treatment"}
+ },
+ "source": "CFR",
+ // message_id should be a bucket ID in the release channel, we may not use the
+ // individual ID, such as addon ID, per legal's request
+ "message_id": "bucket_id",
+ "event": "IMPRESSION"
+}
+```
+
+### User interaction pings
+
+This reports the user's interaction with Activity Stream Router.
+
+#### Snippets interaction pings
+```js
+{
+ "client_id": "26288a14-5cc4-d14f-ae0a-bb01ef45be9c",
+ "action": "snippets_user_event",
+ "addon_version": "20180710100040",
+ "impression_id": "n/a",
+ "locale": "en-US",
+ "experiments": {
+ "experiment_1": {"branch": "control"},
+ "experiment_2": {"branch": "treatment"}
+ },
+ "source": "NEWTAB_FOOTER_BAR",
+ "message_id": "some_snippet_id",
+ "event": ["CLICK_BUTTION" | "BLOCK"]
+}
+```
+
+#### CFR interaction pings for all the prerelease channels and shield experiment
+```js
+{
+ "client_id": "26288a14-5cc4-d14f-ae0a-bb01ef45be9c",
+ "action": "cfr_user_event",
+ "addon_version": "20180710100040",
+ "impression_id": "n/a",
+ "locale": "en-US",
+ "experiments": {
+ "experiment_1": {"branch": "control"},
+ "experiment_2": {"branch": "treatment"}
+ },
+ "source": "CFR",
+ // message_id could be the ID of the recommendation, such as "wikipedia_addon"
+ "message_id": "wikipedia_addon",
+ "event": "[IMPRESSION | INSTALL | PIN | BLOCK | DISMISS | RATIONALE | LEARN_MORE | CLICK | CLICK_DOORHANGER | MANAGE]",
+ // "modelVersion" records the model identifier for the CFR machine learning experiment, see more detail in Bug 1594422.
+ // Non-experiment users will not report this field.
+ "event_context": "{ \"modelVersion\": \"some_model_version_id\" }"
+}
+```
+
+#### CFR interaction pings for release channel
+```js
+{
+ "client_id": "n/a",
+ "action": "cfr_user_event",
+ "addon_version": "20180710100040",
+ "impression_id": "{005deed0-e3e4-4c02-a041-17405fd703f6}",
+ "locale": "en-US",
+ "experiments": {
+ "experiment_1": {"branch": "control"},
+ "experiment_2": {"branch": "treatment"}
+ },
+ "source": "CFR",
+ // message_id should be a bucket ID in the release channel, we may not use the
+ // individual ID, such as addon ID, per legal's request
+ "message_id": "bucket_id",
+ "event": "[IMPRESSION | INSTALL | PIN | BLOCK | DISMISS | RATIONALE | LEARN_MORE | CLICK | CLICK_DOORHANGER | MANAGE]"
+}
+```
+
+### Targeting error pings
+
+This reports when an error has occurred when parsing/evaluating a JEXL targeting string in a message.
+
+```js
+{
+ "client_id": "n/a",
+ "action": "asrouter_undesired_event",
+ "addon_version": "20180710100040",
+ "impression_id": "{005deed0-e3e4-4c02-a041-17405fd703f6}",
+ "locale": "en-US",
+ "experiments": {
+ "experiment_1": {"branch": "control"},
+ "experiment_2": {"branch": "treatment"}
+ },
+ "message_id": "some_message_id",
+ "event": "TARGETING_EXPRESSION_ERROR",
+ "event_context": ["MALFORMED_EXPRESSION" | "OTHER_ERROR"]
+}
+```
+
+### Remote Settings error pings
+
+This reports a failure in the Remote Settings loader to load messages for Activity Stream Router.
+
+```js
+{
+ "action": "asrouter_undesired_event",
+ "client_id": "n/a",
+ "addon_version": "20180710100040",
+ "locale": "en-US",
+ "experiments": {
+ "experiment_1": {"branch": "control"},
+ "experiment_2": {"branch": "treatment"}
+ },
+ "user_prefs": 7,
+ "event": ["ASR_RS_NO_MESSAGES" | "ASR_RS_ERROR"],
+ // The value is set to the ID of the message provider. For example: remote-cfr, remote-onboarding, etc.
+ "event_context": "REMOTE_PROVIDER_ID"
+}
+```
+
+## Feature Callouts interaction pings
+
+This reports when a user has seen or clicked a badge/notification in the browser toolbar in a non-PBM window
+
+```
+{
+ "locale": "en-US",
+ "client_id": "9da773d8-4356-f54f-b7cf-6134726bcf3d",
+ "version": "70.0a1",
+ "release_channel": "default",
+ "addon_version": "20190712095934",
+ "action": "cfr_user_event",
+ "experiments": {
+ "experiment_1": {"branch": "control"},
+ "experiment_2": {"branch": "treatment"}
+ },
+ "source": "CFR",
+ "message_id": "FXA_ACCOUNTS_BADGE",
+ "event": ["CLICK" | "IMPRESSION"],
+}
+```
+
+## Panel interaction pings
+
+This reports when a user opens the panel, views messages and clicks on a message.
+For message impressions we concatenate the ids of all messages in the panel.
+
+```
+{
+ "locale": "en-US",
+ "client_id": "9da773d8-4356-f54f-b7cf-6134726bcf3d",
+ "version": "70.0a1",
+ "release_channel": "default",
+ "addon_version": "20190712095934",
+ "action": "cfr_user_event",
+ "experiments": {
+ "experiment_1": {"branch": "control"},
+ "experiment_2": {"branch": "treatment"}
+ },
+ "source": "CFR",
+ "message_id": "WHATS_NEW_70",
+ "event": ["CLICK" | "IMPRESSION"],
+ "value": { "view": ["application_menu" | "toolbar_dropdown"] }
+}
+```
+
+We also report when the panel checkbox (used to allow users to opt out of
+notifications) is checked or unchecked.
+
+```
+{
+ ...
+ "message_id": "n/a",
+ "event": "WNP_PREF_TOGGLE",
+ "value": { "prefValue": true }
+}
+```
+
+## Moments page pings
+
+This reports when a moments page message has set the user preference for
+`browser.startup.homepage_override.once`. It goes through the same policy
+as other CFR messages.
+
+```
+// Release ping
+{
+ "action": "cfr_user_event"
+ "addon_version": "20200225022813"
+ "bucket_id": "WNP_THANK_YOU"
+ "event": "MOMENTS_PAGE_SET"
+ "impression_id": "{d85d2268-b751-9543-b6d7-aad523bf2b26}"
+ "experiments": {
+ "experiment_1": {"branch": "control"},
+ "experiment_2": {"branch": "treatment"}
+ },
+ "locale": "en-US"
+ "message_id": "n/a"
+ "source": "CFR"
+}
+
+// Beta and Nightly channels
+{
+ "source": "CFR",
+ "message_id": "WNP_THANK_YOU",
+ "bucket_id": "WNP_THANK_YOU",
+ "event": "MOMENTS_PAGE_SET",
+ "addon_version": "20200225022813",
+ "experiments": {
+ "experiment_1": {"branch": "control"},
+ "experiment_2": {"branch": "treatment"}
+ },
+ "locale": "en-US",
+ "client_id": "21dc1375-b24e-984b-83e9-c8a9660ae4ff"
+}
+```
+
+## InfoBar pings
+
+This reports when the user interacts with the browser infobar (messaging area
+located at the top of the content area). Similar policy applied as for the
+What's New panel client_id is reported in all the channels.
+
+```
+{
+ "experiments" : {
+ "exp1" : {
+ "branch" : "treatment-a"
+ }
+ },
+ "addon_version" : "20210115035053",
+ "release_channel" : "release",
+ "locale" : "en-US",
+ "event" : ["IMPRESSION", "CLICK_PRIMARY_BUTTON", "CLICK_SECONDARY_BUTTON", "DISMISSED"],
+ "client_id" : "c4beb4bf-4feb-9c4e-9587-9323b28c2e50",
+ "version" : "86",
+ "message_id" : "INFOBAR_ACTION_86",
+ "browser_session_id" : "93714e76-9919-ca49-b697-5e7c09a1394f"
+}
+```
+
+## Messaging-experiments pings
+
+As the new experiment platform, the Messaging experiment manager is now managing & operating all the experiments of Firefox Messaging System, including the first-run experience (about:welcome), CFR, Whats-new-panel, Moments Page, and Snippets.
+
+### Enrollment & Unenrollment pings
+
+Under the hood, the experiment manager makes use of Normandy API for experiment management (enrollment & unenrollment as well as the corresponding telemetry). Therefore, the enrollment & unenrollment pings are collected through the Normandy counterparts. See [`normandy` category](https://searchfox.org/mozilla-central/source/toolkit/components/telemetry/Events.yaml#441) for more details.
+
+### Experiment reach ping
+
+This records whether a branch's targeting is satisfied for Messaging System experiments. All qualified branch ID(s) will be recorded in the `extra_keys` for each active experiment, and the event `value` will be the experiment ID (i.e. slug).
+
+Unlike other Activity Stream pings, this is a Firefox Events telemetry event, and it is sent only for users enrolled in a Messaging System experiment.
+
+```js
+{
+ "category": "messaging_experiments",
+ "method": "reach",
+ // any of ["cfr", "whats_new_panel", "moments_page", "snippets", "cfr_fxa"]
+ "object": "cfr"
+ "value": "experiment_message_id",
+ "extra_keys": {
+ // A semicolon separated string with all the qualified branch IDs
+ "branches": "control;variant_1;variant_2"
+ }
+}
+```
+
+### Experiment attribute errors
+
+This records whether issues were encountered with any of the targeting attributes used in the experiment enrollment or message targeting.
+Two different types of events are sent: `attribute_error` and `attribute_timeout` along with the attribute that caused it.
+
+```js
+[
+ "messaging_experiments",
+ "targeting",
+ "attribute_error", // event
+ "foo" // attribute
+],
+[
+ "messaging_experiments",
+ "targeting",
+ "attribute_timeout", // event
+ "bar" // attribute
+]
+```
+
+## Firefox Onboarding (about:welcome) pings
+
+These record the telemetry metrics during the Firefox onboarding experience.
+
+### Onboarding impressions
+```js
+{
+ "client_id": "26288a14-5cc4-d14f-ae0a-bb01ef45be9c",
+ "version": "76.0a1",
+ "locale": "en-US",
+ "experiments": {},
+ "release_channel": "default",
+ "addon_version": "20200330194034"
+ "message_id": ["DEFAULT_ABOUTWELCOME" | "DEFAULT_ABOUTWELCOME_AW_GET_STARTED" | "DEFAULT_ABOUTWELCOME_SITES" | "DEFAULT_ABOUTWELCOME_AW_IMPORT_SETTINGS" | "DEFAULT_ABOUTWELCOME_AW_CHOOSE_THEME", "RTAMO_DEFAULT_WELCOME"],
+ "event": "IMPRESSION",
+ "browser_session_id": "e7e52665-7db3-f348-9918-e93160eb2ef3",
+ "event_context": { "page": "about:welcome" },
+ "attribution": {
+ "source": "mozilla.org",
+ "medium": "referral",
+ "campaign": "Firefox-Brand-US-Mozilla-Org",
+ "content": "test-addon@github.io",
+ "experiment": "ua-onboarding",
+ "variation": "chrome",
+ "ua": "firefox"
+ }
+}
+```
+
+### Onboarding button clicks
+```js
+{
+ "client_id": "26288a14-5cc4-d14f-ae0a-bb01ef45be9c",
+ "version": "76.0a1",
+ "locale": "en-US",
+ "experiments": {},
+ "release_channel": "default",
+ "addon_version": "20200330194034"
+ "message_id": ["DEFAULT_ABOUTWELCOME_AW_GET_STARTED" | "DEFAULT_ABOUTWELCOME_AW_IMPORT_SETTINGS" | "DEFAULT_ABOUTWELCOME_AW_CHOOSE_THEME" | "RTAMO_DEFAULT_WELCOME"],
+ "event": "CLICK_BUTTION",
+ "browser_session_id": "e7e52665-7db3-f348-9918-e93160eb2ef3",
+ "event_context": { "page": "about:welcome", "source": ["primary_button", "secondary_button"] },
+ "attribution": {
+ "source": "mozilla.org",
+ "medium": "referral",
+ "campaign": "Firefox-Brand-US-Mozilla-Org",
+ "content": "test-addon@github.io",
+ "experiment": "ua-onboarding",
+ "variation": "chrome",
+ "ua": "firefox"
+ }
+}
+```
+
+### Onboarding Return-To-AMO install ping
+```js
+{
+ "client_id": "26288a14-5cc4-d14f-ae0a-bb01ef45be9c",
+ "version": "76.0a1",
+ "locale": "en-US",
+ "experiments": {},
+ "release_channel": "default",
+ "addon_version": "20200330194034"
+ "message_id": "RTAMO_DEFAULT_WELCOME",
+ "event": "INSTALL",
+ "browser_session_id": "e7e52665-7db3-f348-9918-e93160eb2ef3",
+ "event_context": { "page": "about:welcome", "source": "ADD_EXTENSION_BUTTON" },
+ "attribution": {
+ "source": "mozilla.org",
+ "medium": "referral",
+ "campaign": "Firefox-Brand-US-Mozilla-Org",
+ "content": "test-addon@github.io",
+ "experiment": "ua-onboarding",
+ "variation": "chrome",
+ "ua": "firefox"
+ }
+}
+```
+
+### Onboarding session end ping
+```js
+{
+ "client_id": "26288a14-5cc4-d14f-ae0a-bb01ef45be9c",
+ "version": "76.0a1",
+ "locale": "en-US",
+ "experiments": {},
+ "release_channel": "default",
+ "addon_version": "20200330194034"
+ "message_id": "DEFAULT_ABOUTWELCOME",
+ "event": "SESSION_END",
+ "browser_session_id": "e7e52665-7db3-f348-9918-e93160eb2ef3",
+ "event_context": { "page": "about:welcome", "reason":
+ ["welcome-window-closed" | "welcome-tab-closed" | "app-shut-down" | "address-bar-navigated" | "unknown"]},
+ "attribution": {
+ "source": "mozilla.org",
+ "medium": "referral",
+ "campaign": "Firefox-Brand-US-Mozilla-Org",
+ "content": "test-addon@github.io",
+ "experiment": "ua-onboarding",
+ "variation": "chrome",
+ "ua": "firefox"
+ }
+}
+```
diff --git a/browser/components/newtab/docs/v2-system-addon/geo_locale.md b/browser/components/newtab/docs/v2-system-addon/geo_locale.md
new file mode 100644
index 0000000000..a83275489e
--- /dev/null
+++ b/browser/components/newtab/docs/v2-system-addon/geo_locale.md
@@ -0,0 +1,23 @@
+# Custom `geo`, `locale`, and update channels
+
+There are instances where you may need to change your local build's locale, geo, and update channel (such as changes to the visibility of Discovery Stream on a per-geo/locale basis in `ActivityStream.jsm`).
+
+## Changing update channel
+
+- Change `app.update.channel` to desired value (eg: `release`) by editing `LOCAL_BUILD/Contents/Resources/defaults/pref/channel-prefs.js`. (**NOTE:** Changing pref `app.update.channel` from `about:config` seems to have no effect!)
+
+## Changing geo
+
+- Set `browser.search.region` to desired geo (eg `CA`)
+
+## Changing locale
+
+*Note: These prefs are only configurable on a nightly or local build.*
+
+- Toggle `extensions.langpacks.signatures.required` to `false`
+- Toggle `xpinstall.signatures.required` to `false`
+- Toggle `intl.multilingual.downloadEnabled` to `true`
+- Toggle `intl.multilingual.enabled` to `true`
+- For Mac and Linux builds, open the [langpack](https://archive.mozilla.org/pub/firefox/nightly/latest-mozilla-central-l10n/linux-x86_64/xpi/) for target locale in your local build (eg `firefox-70.0a1.en-CA.langpack.xpi` if you want an `en-CA` locale).
+- For Windows, use [https://archive.mozilla.org/pub/firefox/nightly/latest-mozilla-central-l10n/](https://archive.mozilla.org/pub/firefox/nightly/latest-mozilla-central-l10n/)
+- In `about:preferences` click "Set Alternatives" under "Language", move desired locale to the top position, click OK, click "Apply And Restart"
diff --git a/browser/components/newtab/docs/v2-system-addon/mochitests.md b/browser/components/newtab/docs/v2-system-addon/mochitests.md
new file mode 100644
index 0000000000..8ceb0b1ed7
--- /dev/null
+++ b/browser/components/newtab/docs/v2-system-addon/mochitests.md
@@ -0,0 +1,28 @@
+# Mochitests
+
+We use [mochitests](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/Mochitest) to do functional (and possibly integration) testing. Mochitests are part of Firefox and allow us to test activity stream literally as you would use it.
+
+Mochitests live in `test/functional/mochitest`, and as of this writing, they
+ are all the [`browser-chrome`](https://developer.mozilla.org/en-US/docs/Mozilla/Browser_chrome_tests) flavor of mochitests. They currently only run against the bootstrapped version of the add-on in system-addon, not the test pilot version at the top level directory.
+
+## Adding New Tests
+
+If you add new tests, make sure to list them in the `browser.ini` file. You will see the other tests there. Add a new entry with the same format as the others. You can also add new JS or HTML files by listing in under `support-files`. Make sure to start your test name with "browser_", so that the test suite knows the pick it up. E.g: "browser_as_my_new_test.js".
+
+## Writing Tests
+
+Here are a few tips for writing mochitests:
+
+* Only write mochitests for testing the interaction of multiple components on the page and to make sure that the protocol is working.
+* If you need to access the content page, use `ContentTask.spawn`:
+
+```js
+ContentTask.spawn(gBrowser.selectedBrowser, null, function* () {
+ content.wrappedJSObject.foo();
+});
+```
+
+The above calls the function `foo` that exists in the page itself. You can also access the DOM this way: `content.document.querySelector`, if you want to click a button or do other things. You can even you use assertions inside this callback to check DOM state.
+
+* If you run into problems running tests in e10s, refer to the [wiki](https://wiki.mozilla.org/Electrolysis/e10s_test_tips) for tips
+* Nobody likes to see intermittent oranges in their tests, so read the [docs on how to avoid them](https://developer.mozilla.org/en-US/docs/Mozilla/QA/Avoiding_intermittent_oranges)!
diff --git a/browser/components/newtab/docs/v2-system-addon/preferences.md b/browser/components/newtab/docs/v2-system-addon/preferences.md
new file mode 100644
index 0000000000..58b6bae411
--- /dev/null
+++ b/browser/components/newtab/docs/v2-system-addon/preferences.md
@@ -0,0 +1,282 @@
+# Preferences
+
+## Preference branch
+
+The preference branch for activity stream is `browser.newtabpage.activity-stream.`.
+Any preferences defined in the preference configuration will be relative to that
+branch. For example, if a preference is defined with the name `foo`, the full
+preference as it is displayed in `about:config` will be `browser.newtabpage.activity-stream.foo`.
+
+## Defining new preferences
+
+All preferences for Activity Stream should be defined in the `PREFS_CONFIG` Array
+found in `lib/ActivityStream.jsm`.
+The configuration object should have a `name` (the name of the pref), a `title`
+that describes the functionality of the pref, and a `value`, the default value
+of the pref. Optionally a `getValue` function can be provided to dynamically
+generate a default pref value based on args, e.g., geo and locale. For
+developers-specific defaults, an optional `value_local_dev` will be used instead
+of `value`. For example:
+
+```js
+{
+ name: "telemetry.log",
+ title: "Log telemetry events in the console",
+ value: false,
+ value_local_dev: true,
+ getValue: ({geo}) => geo === "CA"
+}
+```
+
+### IMPORTANT: Setting test-specific values for Mozilla Central
+
+If a feed or feature behind a pref makes any network calls or would other be
+disruptive for automated tests and that pref is on by default, make sure you
+disable it for tests in Mozilla Central.
+
+You should create a bug in Bugzilla and a patch that adds lines to turn off your
+pref in the following files:
+- layout/tools/reftest/reftest-preferences.js
+- testing/profiles/prefs_general.js
+- testing/talos/talos/config.py
+
+You can see an example in [this patch](https://github.com/mozilla/activity-stream/pull/2977).
+
+## Reading, setting, and observing preferences from `.jsm`s
+
+To read/set/observe Activity Stream preferences, construct a `Prefs` instance found in `lib/ActivityStreamPrefs.jsm`.
+
+```js
+// Import Prefs
+XPCOMUtils.defineLazyModuleGetter(this, "Prefs",
+ "resource://activity-stream/lib/ActivityStreamPrefs.jsm");
+
+// Create an instance
+const prefs = new Prefs();
+```
+
+The `Prefs` utility will set the Activity Stream branch for you by default, so you
+don't need to worry about prefixing every pref with `browser.newtabpage.activity-stream.`:
+
+```js
+const prefs = new Prefs();
+
+// This will return the value of browser.newtabpage.activity-stream.foo
+prefs.get("foo");
+
+// This will set the value of browser.newtabpage.activity-stream.foo to true
+prefs.set("foo", true)
+
+// This will call aCallback when browser.newtabpage.activity-stream.foo is changed
+prefs.observe("foo", aCallback);
+
+// This will stop listening to browser.newtabpage.activity-stream.foo
+prefs.ignore("foo", aCallback);
+```
+
+See [toolkit/modules/Preferences.jsm](https://searchfox.mozilla.org/mozilla-central/source/toolkit/modules/Preferences.jsm)
+for more information about what methods are available.
+
+## Discovery Stream Preferences
+
+Preferences specific to the Discovery Stream are nested under the sub-branch `browser.newtabpage.activity-stream.discoverystream` (with the exception of `browser.newtabpage.blocked`).
+
+#### `browser.newtabpage.activity-stream.discoverystream.flight.blocks`
+
+- Type: `string (JSON)`
+- Default: `{}`
+- Pref Type: AS
+
+Not intended for user configuration, but is programmatically updated. Used for tracking blocked flight IDs when a user dismisses a SPOC. Keys are flight IDs. Values don't have a specific meaning.
+
+#### `browser.newtabpage.blocked`
+
+- Type: `string (JSON)`
+- Default: `null`
+- Pref Type: AS
+
+Not intended for user configuration, but is programmatically updated. Used for tracking blocked story IDs when a user dismisses one. Keys are story IDs. Values don't have a specific meaning.
+
+#### `browser.newtabpage.activity-stream.discoverystream.config`
+
+- Type `string (JSON)`
+- Default:
+ ```
+ {
+ "api_key_pref": "extensions.pocket.oAuthConsumerKey",
+ "collapsible": true,
+ "enabled": true,
+ "show_spocs": true,
+ "hardcoded_layout": true,
+ "personalized": true,
+ "layout_endpoint": "https://getpocket.cdn.mozilla.net/v3/newtab/layout?version=1&consumer_key=$apiKey&layout_variant=basic"
+ }
+ ```
+ - `api_key_pref` (string): The name of a variable containing the key for the Pocket API.
+ - `collapsible` (boolean): Controls whether the sections in new tab can be collapsed.
+ - `enabled` (boolean): Controls whether DS is turned on and is programmatically set based on a user's locale. DS enablement is a logical `AND` of this and the value of `browser.newtabpage.activity-stream.discoverystream.enabled`.
+ - `show_spocs` (boolean): Show sponsored content in new tab.
+ - `hardcoded_layout` (boolean): When this is true, a hardcoded layout shipped with Firefox will be used instead of a remotely fetched layout definition.
+ - `personalized` (boolean): When this is `true` personalized content based on browsing history will be displayed.
+ - `layout_endpoint` (string): The URL for a remote layout definition that will be used if `hardcoded_layout` is `false`.
+ - `unused_key` (string): This is not set by default and is unused by this codebase. It's a standardized way to differentiate configurations to prevent experiment participants from being unenrolled.
+
+#### `browser.newtabpage.activity-stream.discoverystream.enabled`
+
+- Type: `boolean`
+- Default: `true`
+- Pref Type: Firefox
+
+When this is set to `true` the Discovery Stream experience will show up if `enabled` is also `true` on `browser.newtabpage.activity-stream.discoverystream.config`. Otherwise the old Activity Stream experience will be shown.
+
+#### `browser.newtabpage.activity-stream.discoverystream.endpointSpocsClear`
+
+- Type: `string (URL)`
+- Default: `https://spocs.getpocket.com/user`
+- Pref Type: AS
+
+Endpoint for when a user opts-out of sponsored content to delete the corresponding data from the ad server.
+
+#### `browser.newtabpage.activity-stream.discoverystream.endpoints`
+
+- Type: `string (URLs, CSV)`
+- Default: `https://getpocket.cdn.mozilla.net/,https://spocs.getpocket.com/`
+- Pref Type: AS
+
+A list of endpoints that are allowed to be used by Discovery Stream for remote content (eg: story metadata) and configuration (eg: remote layout definitions for experimentation).
+
+#### `browser.newtabpage.activity-stream.discoverystream.engagementLabelEnabled`
+
+- Type: `boolean`
+- Default: `false`
+- Pref Type: AS
+
+A flag controlling the visibility of engagement labels on cards (eg: "Trending" or "Popular").
+
+#### `browser.newtabpage.activity-stream.discoverystream.hardcoded-basic-layout`
+
+- Type: `boolean`
+- Default: `false`
+- Pref Type: Firefox
+
+If this is `false` the default hardcoded layout is used, and if it's `true` then an alternate hardcoded layout (that currently simulates the older AS experience) is used.
+
+#### `browser.newtabpage.activity-stream.discoverystream.rec.impressions`
+
+- Type: `string (JSON)`
+- Default: `{}`
+- Pref Type: AS
+
+Programmatically generated hash table where the keys are recommendation IDs and the values are timestamps representing the first impression.
+
+#### `browser.newtabpage.activity-stream.discoverystream.spoc.impressions`
+
+- Type: `string (JSON)`
+- Default: `{}`
+- Pref Type: AS
+
+Programmatically generated hash table where the keys are sponsored content IDs and the values are arrays of timestamps for every impression.
+
+#### `browser.newtabpage.activity-stream.discoverystream.locale-list-config`
+
+- Type: `string (CSV, locales)`
+- Default: `null`
+- Pref Type: Firefox
+
+A comma separated list of locales that by default have stories enabled in newtab. It overrides what might be in region-stories-config. So if I set this to "en-US,en-CA,en-GB", all users with a English browser would see newtab stories, even if their region was not in region-stories-config list.
+
+#### `browser.newtabpage.activity-stream.discoverystream.region-stories-config`
+
+- Type: `string (CSV, regions)`
+- Default: `US,DE,CA,GB,IE,CH,AT,BE`
+- Pref Type: Firefox
+
+A comma separated list of geos that by default have stories enabled in newtab. It matches the client's geo with that list, then looks for a matching locale.
+
+#### `browser.newtabpage.activity-stream.discoverystream.region-spocs-config`
+
+- Type: `string (CSV, regions)`
+- Default: `US,CA,DE`
+- Pref Type: Firefox
+
+A comma separated list of geos that by default have spocs enabled in newtab. It matches the client's geo with that list.
+
+#### `browser.newtabpage.activity-stream.discoverystream.region-layout-config`
+
+- Type: `string (CSV, regions)`
+- Default: `US,CA,GB,DE,IE,CH,AT,BE`
+- Pref Type: Firefox
+
+A comma separated list of geos that have 7 rows of stories enabled in newtab. It matches the client's geo with that list.
+
+#### `browser.newtabpage.activity-stream.discoverystream.region-basic-layout`
+
+- Type: `boolean`
+- Default: false
+- Pref Type: AS
+
+If this is `true` newtabs with stories enabled see 1 row. It is set programmatically based on the result from region-layout-config.
+
+#### `browser.newtabpage.activity-stream.discoverystream.spocs-endpoint`
+
+- Type: `string (URL)`
+- Default: `null`
+- Pref Type: Firefox
+
+Override to specify endpoint for SPOCs. Will take precedence over remote and hardcoded layout SPOC endpoints.
+
+#### `browser.newtabpage.activity-stream.discoverystream.personalization.version`
+
+- Type: `integer`
+- Default: `1`
+- Pref Type: Firefox
+
+This controls what version of personalization we should use to score newtab stories.
+
+#### `browser.newtabpage.activity-stream.discoverystream.personalization.modelKeys`
+
+- Type: `string (CSV)`
+- Default: `nb_model_arts_and_entertainment, nb_model_autos_and_vehicles, nb_model_beauty_and_fitness, nb_model_blogging_resources_and_services, nb_model_books_and_literature, nb_model_business_and_industrial, nb_model_computers_and_electronics, nb_model_finance, nb_model_food_and_drink, nb_model_games, nb_model_health, nb_model_hobbies_and_leisure, nb_model_home_and_garden, nb_model_internet_and_telecom, nb_model_jobs_and_education, nb_model_law_and_government, nb_model_online_communities, nb_model_people_and_society, nb_model_pets_and_animals, nb_model_real_estate, nb_model_reference, nb_model_science, nb_model_shopping, nb_model_sports, nb_model_travel`
+- Pref Type: Firefox
+
+This is a configuration for personalization version 2. It is a list of topics the algorithm uses to score stories by.
+
+#### `browser.newtabpage.activity-stream.discoverystream.recs.personalized`
+
+- Type: `boolean`
+- Default: false
+- Pref Type: Firefox
+
+This controls if newtab story personalization includes regular stories or not. See spocs.personalized for sponsored content.
+
+#### `browser.newtabpage.activity-stream.discoverystream.spocs.personalized`
+
+- Type: `boolean`
+- Default: true
+- Pref Type: Firefox
+
+This controls if newtab story personalization includes sponsored content or not. See recs.personalized for regular stories.
+
+#### `browser.newtabpage.activity-stream.discoverystream.isCollectionDismissible`
+
+- Type: `boolean`
+- Default: true
+- Pref Type: Firefox
+
+This controls if newtab story collections are dismissible or not.
+
+#### `browser.newtabpage.activity-stream.feeds.section.topstories`
+
+- Type: `boolean`
+- Default: true
+- Pref Type: Firefox
+
+This controls if the user should see newtab stories or not. It is set by the user via about:preferences#home
+
+#### `browser.newtabpage.activity-stream.feeds.system.topstories`
+
+- Type: `boolean`
+- Default: false
+- Pref Type: AS
+
+Not intended for user configuration, but is programmatically set. It also controls if the user should see newtab stories or not. It is set at run time, and computed based on the locale/region.
diff --git a/browser/components/newtab/docs/v2-system-addon/remote_cfr.md b/browser/components/newtab/docs/v2-system-addon/remote_cfr.md
new file mode 100644
index 0000000000..4c25b06ae3
--- /dev/null
+++ b/browser/components/newtab/docs/v2-system-addon/remote_cfr.md
@@ -0,0 +1,63 @@
+# Remote CFR Messages
+Starting in Firefox 68, CFR messages will be defined using [Remote Settings](https://remote-settings.readthedocs.io/en/latest/index.html). In this document, we'll cover how how to set up a dev environment.
+
+## Using a dev server for Remote CFR
+
+**1. Setup the Remote Settings dev server with the CFR messages.**
+Note that the dev server gets wiped every 24 hours so this will be have to be done once a day. You can check if there currently are any messages [here](https://kinto.dev.mozaws.net/v1//buckets/main/collections/cfr/records).
+
+```bash
+SERVER=https://kinto.dev.mozaws.net/v1
+
+# create user
+curl -X PUT ${SERVER}/accounts/devuser \
+ -d '{"data": {"password": "devpass"}}' \
+ -H 'Content-Type:application/json'
+
+BASIC_AUTH=devuser:devpass
+
+# create collection
+CID=cfr
+curl -X PUT ${SERVER}/buckets/main/collections/${CID} \
+ -H 'Content-Type:application/json' \
+ -u ${BASIC_AUTH}
+
+# post a message
+curl -X POST ${SERVER}/buckets/main/collections/${CID}/records \
+ -d '{"data":{"id":"PIN_TAB","template":"cfr_doorhanger","content":{"category":"cfrFeatures","bucket_id":"CFR_PIN_TAB","notification_text":{"string_id":"cfr-doorhanger-extension-notification"},"heading_text":{"string_id":"cfr-doorhanger-pintab-heading"},"info_icon":{"label":{"string_id":"cfr-doorhanger-extension-sumo-link"},"sumo_path":"extensionrecommendations"},"text":{"string_id":"cfr-doorhanger-pintab-description"},"descriptionDetails":{"steps":[{"string_id":"cfr-doorhanger-pintab-step1"},{"string_id":"cfr-doorhanger-pintab-step2"},{"string_id":"cfr-doorhanger-pintab-step3"}]},"buttons":{"primary":{"label":{"string_id":"cfr-doorhanger-pintab-ok-button"},"action":{"type":"PIN_CURRENT_TAB"}},"secondary":[{"label":{"string_id":"cfr-doorhanger-extension-cancel-button"},"action":{"type":"CANCEL"}},{"label":{"string_id":"cfr-doorhanger-extension-never-show-recommendation"}},{"label":{"string_id":"cfr-doorhanger-extension-manage-settings-button"},"action":{"type":"OPEN_PREFERENCES_PAGE","data":{"category":"general-cfrfeatures"}}}]}},"targeting":"locale == \"en-US\" && !hasPinnedTabs && recentVisits[.timestamp > (currentDate|date - 3600 * 1000 * 1)]|length >= 3","frequency":{"lifetime":3},"trigger":{"id":"frequentVisits","params":["docs.google.com","www.docs.google.com","calendar.google.com","messenger.com","www.messenger.com","web.whatsapp.com","mail.google.com","outlook.live.com","facebook.com","www.facebook.com","twitter.com","www.twitter.com","reddit.com","www.reddit.com","github.com","www.github.com","youtube.com","www.youtube.com","feedly.com","www.feedly.com","drive.google.com","amazon.com","www.amazon.com","messages.android.com"]}}}' \
+ -H 'Content-Type:application/json' \
+ -u ${BASIC_AUTH}
+```
+
+Now there should be a message listed: https://kinto.dev.mozaws.net/v1//buckets/main/collections/cfr/records
+
+NOTE: The collection and messages can also be created manually using the [admin interface](https://kinto.dev.mozaws.net/v1/admin/).
+
+**2. Set Remote Settings prefs to use the dev server.**
+
+```javascript
+Services.prefs.setStringPref("services.settings.server", "https://kinto.dev.mozaws.net/v1");
+
+// Disable signature verification
+const { RemoteSettings } = ChromeUtils.import("resource://services-settings/remote-settings.js", {});
+
+RemoteSettings("cfr").verifySignature = false;
+```
+
+**3. Set ASRouter CFR pref to use Remote Settings provider and enable asrouter devtools.**
+
+```javascript
+Services.prefs.setStringPref("browser.newtabpage.activity-stream.asrouter.providers.cfr", JSON.stringify({"id":"cfr-remote","enabled":true,"type":"remote-settings","bucket":"cfr"}));
+Services.prefs.setBoolPref("browser.newtabpage.activity-stream.asrouter.devtoolsEnabled", true);
+```
+
+**4. Go to `about:newtab#devtools`**
+There should be a "cfr-remote" provider listed.
+
+## Using the staging server for Remote CFR
+
+If your message is published in the staging environment the easiest way to test is using the [Remote Settings Devtools](https://github.com/mozilla/remote-settings-devtools/releases) addon. You can install this by going to `about:debugging` and using the `Load Temporary Addon` feature.
+The devtools allow you to switch your profile between production and staging and takes care of correctly flipping all the required preferences.
+
+## Remote l10n
+By default, all CFR messages are localized with the remote Fluent files hosted in `ms-language-packs` on Remote Settings. For local test and development, you can force ASRouter to use the local Fluent files by flipping the pref `browser.newtabpage.activity-stream.asrouter.useRemoteL10n`.
diff --git a/browser/components/newtab/docs/v2-system-addon/sections.md b/browser/components/newtab/docs/v2-system-addon/sections.md
new file mode 100644
index 0000000000..641b5b4630
--- /dev/null
+++ b/browser/components/newtab/docs/v2-system-addon/sections.md
@@ -0,0 +1,82 @@
+# Sections
+
+Each section in Activity Stream displays data from a corresponding section feed
+in a standardised `Section` UI component. Each section feed is responsible for
+listening to events and updating the section options such as the title, icon,
+and rows (the cards for the section to display).
+
+The `Section` UI component displays the rows provided by the section feed. If no
+rows are available it displays an empty state consisting of an icon and a
+message. Optionally, the section may have a info option menu that is displayed
+when users hover over the info icon.
+
+On load, `SectionsManager` and `SectionsFeed` in `SectionsManager.jsm` add the
+sections configured in the `BUILT_IN_SECTIONS` map to the state. These sections
+are initially disabled, so aren't visible. The section's feed may use the
+methods provided by the `SectionsManager` to enable its section and update its
+properties.
+
+The section configuration in `BUILT_IN_SECTIONS` consists of a generator
+function keyed by the pref name for the section feed. The generator function
+takes an `options` argument as the only parameter, which is passed the object
+stored as serialised JSON in the pref `{feed_pref_name}.options`, or the empty
+object if this doesn't exist. The generator returns a section configuration
+object which may have the following properties:
+
+```eval_rst
++--------------------+---------------------+-------------------------------------------------------------------------------------------------------------------+
+| Property | Type | Description |
++====================+=====================+===================================================================================================================+
+| id | String | Non-optional unique id. |
++--------------------+---------------------+-------------------------------------------------------------------------------------------------------------------+
+| title | Localisation object | Has property `id`, the string localisation id, and optionally a `values` object to fill in placeholders. |
++--------------------+---------------------+-------------------------------------------------------------------------------------------------------------------+
+| icon | String | Icon id. New icons should be added in icons.scss. |
++--------------------+---------------------+-------------------------------------------------------------------------------------------------------------------+
+| maxRows | Integer | Maximum number of rows of cards to display. Should be >= 1. |
++--------------------+---------------------+-------------------------------------------------------------------------------------------------------------------+
+| contextMenuOptions | Array of strings | The menu options to provide in the card context menus. |
++--------------------+---------------------+-------------------------------------------------------------------------------------------------------------------+
+| shouldHidePref | Boolean | If true, will the section preference in the preferences pane will not be shown. |
++--------------------+---------------------+-------------------------------------------------------------------------------------------------------------------+
+| pref | Object | Configures the section preference to show in the preferences pane. Has properties `titleString` and `descString`. |
++--------------------+---------------------+-------------------------------------------------------------------------------------------------------------------+
+| emptyState | Object | Configures the empty state of the section. Has properties `message` and `icon`. |
++--------------------+---------------------+-------------------------------------------------------------------------------------------------------------------+
+```
+
+## Section feeds
+
+Each section feed should be controlled by the pref `feeds.section.{section_id}`.
+
+### Enabling the section
+
+The section feed must listen for the events `INIT` (dispatched when Activity
+Stream is initialised) and `FEED_INIT` (dispatched when a feed is re-enabled
+having been turned off, with the feed id as the `data`). On these events it must
+call `SectionsManager.enableSection(id)`. Care should be taken that this happens
+only once `SectionsManager` has also initialised; the feed can use the method
+`SectionsManager.onceInitialized()`.
+
+### Disabling the section
+
+The section feed must have an `uninit` method. This is called when the section
+feed is disabled by turning the section's pref off. In `uninit` the feed must
+call `SectionsManager.disableSection(id)`. This will remove the section's UI
+component from every existing Activity Stream page.
+
+### Updating the section rows
+
+The section feed can call `SectionsManager.updateSection(id, options)` to update
+section options. The `rows` array property of `options` stores the cards of
+sites to display. Each card object may have the following properties:
+
+```js
+{
+ type, // One of the types in Card/types.js, e.g. "Trending"
+ title, // Title string
+ description, // Description string
+ image, // Image url
+ url // Site url
+}
+```
diff --git a/browser/components/newtab/docs/v2-system-addon/telemetry.md b/browser/components/newtab/docs/v2-system-addon/telemetry.md
new file mode 100644
index 0000000000..4d76d0e615
--- /dev/null
+++ b/browser/components/newtab/docs/v2-system-addon/telemetry.md
@@ -0,0 +1,13 @@
+# Telemetry checklist
+
+Adding telemetry generally involves a few steps:
+
+1. File a "user story" bug about who wants what question answered. This will be used to track the client-side implementation as well as the data review request. If the server side changes are needed, ask Nan (:nanj / @ncloudio) if in doubt, bugs will be filed separately as dependencies.
+1. Implement as usual...
+1. Update `system-addon/test/schemas/pings.js` with a commented JOI schema of your changes, and add tests to system-addon/test/unit/TelemetryFeed.test.js to exercise the ping creation.
+1. Update [data_events.md](data_events.md) with an example of the data in question.
+1. Update any fields that you've added, deleted, or changed in [data_dictionary.md](data_dictionary.md).
+1. Get review from Nan on the data schema and the documentation changes.
+1. Request `data-review` of your documentation changes from a [data steward](https://wiki.mozilla.org/Firefox/Data_Collection) to ensure suitability for collection controlled by the opt-out `datareporting.healthreport.uploadEnabled` pref. Download and fill out the [data review request form](https://github.com/mozilla/data-review/blob/master/request.md) and then attach it as a text file on Bugzilla so you can r? a data steward. We've been working with Chris H-C (:chutten) for the Firefox specific telemetry, and Kenny Long (kenny@getpocket.com) for the Pocket specific telemetry, they are the best candidates for the review work as they know well about the context.
+1. After landing the implementation, check with Nan to make sure the pings are making it to the database.
+1. Once data flows in, you can build dashboard for the new telemetry on [Redash](https://sql.telemetry.mozilla.org/dashboards). If you're looking for some help about Redash or dashboard building, Nan is the guy for that.
diff --git a/browser/components/newtab/docs/v2-system-addon/tippytop.md b/browser/components/newtab/docs/v2-system-addon/tippytop.md
new file mode 100644
index 0000000000..d89e107c57
--- /dev/null
+++ b/browser/components/newtab/docs/v2-system-addon/tippytop.md
@@ -0,0 +1,40 @@
+# TippyTop in Activity Stream
+TippyTop, a collection of icons from the Alexa top sites, provides high quality images for the Top Sites in Activity Stream. The TippyTop manifest is hosted on S3, and then moved to [Remote Settings](https://remote-settings.readthedocs.io/en/latest/index.html) since Firefox 63. In this document, we'll cover how we produce and manage TippyTop manifest for Activity Stream.
+
+## TippyTop manifest production
+TippyTop manifest is produced by [tippy-top-sites](https://github.com/mozilla/tippy-top-sites).
+
+```sh
+# set up the environment, only needed for the first time
+$ pip install -r requirements.txt
+$ python make_manifest.py --count 2000 > icons.json # Alexa top 2000 sites
+```
+
+Because the manifest is hosted remotely, we use another repo [tippytop-service](https://github.com/mozilla-services/tippytop-service) for the version control and deployment. Ask :nanj or :r1cky for permission to access this private repo.
+
+## TippyTop manifest publishing
+For each new manifest release, firstly you should tag it in the tippytop-service repo, then publish it as follows:
+
+### For Firefox 62 and below
+File a deploy bug with the tagged version at Bugzilla as [Activity Streams: Application Servers](https://bugzilla.mozilla.org/enter_bug.cgi?product=Firefox&component=Activity%20Streams%3A%20Application%20Servers), assign it to our system engineer :jbuck, he will take care of the rest.
+
+### For Firefox 63 and beyond
+Activity Stream started using Remote Settings to manage TippyTop manifest since Firefox 63. To be able to publish new manifest, you need to be in the author&reviewer group of Remote Settings. See more details in this [mana page](https://mana.mozilla.org/wiki/pages/viewpage.action?pageId=66655528). You can also ask :nanj or :leplatram to get this set up for you.
+To publish the manifest to Remote Settings, go to the tippytop-service repo, and run the script as follows,
+
+```sh
+# set up the remote setting, only needed for the first time
+$ python3 -m venv .venv
+$ source .venv/bin/activate
+$ pip install -r requirements.txt
+
+# publish it to prod
+$ source .venv/bin/activate
+# It will ask you for your LDAP user name and password.
+$ ./upload2remotesettings.py prod
+```
+
+After uploading it to Remote Setting, you can request for review in the [dashboard](https://settings-writer.prod.mozaws.net/v1/admin/). Note that you will need to log in the Mozilla LDAP VPN for both uploading and accessing Remote Setting's dashboard. Once your request gets approved by the reviewer, the new manifest will be content signed and published to production.
+
+## TippyTop Viewer
+You can use this [viewer](https://mozilla.github.io/tippy-top-sites/manifest-viewer/) to load all the icons in the current manifest.
diff --git a/browser/components/newtab/docs/v2-system-addon/unit_testing_guide.md b/browser/components/newtab/docs/v2-system-addon/unit_testing_guide.md
new file mode 100644
index 0000000000..c3dd369a2d
--- /dev/null
+++ b/browser/components/newtab/docs/v2-system-addon/unit_testing_guide.md
@@ -0,0 +1,149 @@
+# Unit testing
+
+## Overview
+
+Our unit tests in Activity Stream are written with mocha, chai, and sinon, and run
+with karma. They include unit tests for both content code (React components, etc.)
+and `.jsm`s.
+
+You can find unit tests in `tests/unit`.
+
+## Execution
+
+To run the unit tests once, execute `npm test`.
+
+To run unit tests continuously (i.e. in "test-driven development" mode), you can
+run `npm run tddmc`.
+
+## Debugging
+
+To debug tests, you should run them in continuous mode with `npm run tddmc`.
+In the Firefox window that is opened (it should say "Karma... - connected"),
+click the "debug" button and open your console to see test output, set
+breakpoints, etc.
+
+Unfortunately, source maps for tests do not currently work in Firefox. If you need
+to see line numbers, you can run the tests with Chrome by running
+`npm install --save-dev karma-chrome-launcher && npm run tddmc -- --browsers Chrome`
+
+## Where to put new tests
+
+If you are creating a new test, add it to a subdirectory of the `tests/unit`
+that corresponds to the file you are testing. Tests should end with `.test.js` or
+`.test.jsx` if the test includes any jsx.
+
+For example, if the file you are testing is `lib/Foo.jsm`, the test
+file should be `test/unit/lib/Foo.test.js`
+
+## Mocha tests
+
+All our unit tests are written with [mocha](https://mochajs.org), which injects
+globals like `describe`, `it`, `beforeEach`, and others. It can be used to write
+synchronous or asynchronous tests:
+
+```js
+describe("FooModule", () => {
+ // A synchronous test
+ it("should create an instance", () => {
+ assert.instanceOf(new FooModule(), FooModule);
+ });
+ describe("#meaningOfLife", () => {
+ // An asynchronous test
+ it("should eventually get the meaning of life", async () => {
+ const foo = new FooModule();
+ const result = await foo.meaningOfLife();
+ assert.equal(result, 42);
+ });
+ });
+});
+```
+
+## Assertions
+
+To write assertions, use the globally available `assert` object (this is provided
+by karma-chai, so you do not need to `require` it).
+
+For example:
+
+```js
+assert.equal(foo, 3);
+assert.propertyVal(someObj, "foo", 3);
+assert.calledOnce(someStub);
+```
+
+You can use any of the assertions from:
+
+- [`chai`](http://chaijs.com/api/assert/).
+- [`sinon-chai`](https://github.com/domenic/sinon-chai#assertions)
+
+### Custom assertions
+
+We have some custom assertions for checking various types of actions:
+
+#### `.isUserEventAction(action)`
+
+Asserts that a given `action` is a valid User Event, i.e. that it contains only
+expected/valid properties for User Events in Activity Stream.
+
+```js
+// This will pass
+assert.isUserEventAction(ac.UserEvent({event: "CLICK"}));
+
+// This will fail
+assert.isUserEventAction({type: "FOO"});
+
+// This will fail because BLOOP is not a valid event type
+assert.isUserEventAction(ac.UserEvent({event: "BLOOP"}));
+```
+
+## Overriding globals in `.jsm`s
+
+Most `.jsm`s you will be testing use `Cu.import` or `XPCOMUtils` to inject globals.
+In order to add mocks/stubs/fakes for these globals, you should use the `GlobalOverrider`
+utility in `test/unit/utils`:
+
+```js
+const {GlobalOverrider} = require("test/unit/utils");
+describe("MyModule", () => {
+ let globals;
+ let sandbox;
+ beforeEach(() => {
+ globals = new GlobalOverrider();
+ sandbox = globals.sandbox; // this is a sinon sandbox
+ // This will inject a "AboutNewTab" global before each test
+ globals.set("AboutNewTab", {override: sandbox.stub()});
+ });
+ // globals.restore() clears any globals you added as well as the sinon sandbox
+ afterEach(() => globals.restore());
+});
+```
+
+## Testing React components
+
+You should use the [enzyme](https://github.com/airbnb/enzyme) suite of test utilities
+to test React Components for Activity Stream.
+
+Where possible, use the [shallow rendering method](https://github.com/airbnb/enzyme/blob/master/docs/api/shallow.md) (this will avoid unnecessarily
+rendering child components):
+
+```js
+const React = require("react");
+const {shallow} = require("enzyme");
+
+describe("<Foo>", () => {
+ it("should be hidden by default", () => {
+ const wrapper = shallow(<Foo />);
+ assert.isTrue(wrapper.find(".wrapper").props().hidden);
+ });
+});
+```
+
+If you need to, you can also do [Full DOM rendering](https://github.com/airbnb/enzyme/blob/master/docs/api/mount.md)
+with enzyme's `mount` utility.
+
+```js
+const React = require("react");
+const {mount} = require("enzyme");
+...
+const wrapper = mount(<Foo />);
+```
diff --git a/browser/components/newtab/jar.mn b/browser/components/newtab/jar.mn
new file mode 100644
index 0000000000..59ccd0ca57
--- /dev/null
+++ b/browser/components/newtab/jar.mn
@@ -0,0 +1,44 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+browser.jar:
+% resource activity-stream %res/activity-stream/ contentaccessible=yes
+% content activity-stream %content/activity-stream/ contentaccessible=yes
+ res/activity-stream/lib/ (./lib/*)
+ res/activity-stream/common/ (./common/*)
+ content/activity-stream/aboutwelcome/aboutwelcome.css (./aboutwelcome/content/aboutwelcome.css)
+ res/activity-stream/aboutwelcome/aboutwelcome.bundle.js (./aboutwelcome/content/aboutwelcome.bundle.js)
+ res/activity-stream/aboutwelcome/aboutwelcome.html (./aboutwelcome/content/aboutwelcome.html)
+ res/activity-stream/aboutwelcome/lib/ (./aboutwelcome/lib/*)
+ res/activity-stream/vendor/Redux.jsm (./vendor/Redux.jsm)
+ res/activity-stream/vendor/react.js (./vendor/react.js)
+ res/activity-stream/vendor/react-dom.js (./vendor/react-dom.js)
+ res/activity-stream/vendor/react-dom-server.js (./vendor/react-dom-server.js)
+#ifndef RELEASE_OR_BETA
+ res/activity-stream/vendor/react-dev.js (./vendor/react-dev.js)
+ res/activity-stream/vendor/react-dom-dev.js (./vendor/react-dom-dev.js)
+#endif
+ res/activity-stream/vendor/prop-types.js (./vendor/prop-types.js)
+ res/activity-stream/vendor/react-transition-group.js (./vendor/react-transition-group.js)
+ res/activity-stream/vendor/redux.js (./vendor/redux.js)
+ res/activity-stream/vendor/react-redux.js (./vendor/react-redux.js)
+* res/activity-stream/data/content/abouthomecache/page.html.template (./data/content/abouthomecache/page.html.template)
+* res/activity-stream/data/content/abouthomecache/script.js.template (./data/content/abouthomecache/script.js.template)
+ content/activity-stream/data/content/assets/ (./data/content/assets/*)
+ content/activity-stream/data/content/tippytop/ (./data/content/tippytop/*)
+ res/activity-stream/data/content/activity-stream.bundle.js (./data/content/activity-stream.bundle.js)
+ res/activity-stream/data/content/newtab-render.js (./data/content/newtab-render.js)
+ res/activity-stream/data/custom-elements/ (./components/CustomElements/*)
+#ifdef XP_MACOSX
+ content/activity-stream/css/activity-stream.css (./css/activity-stream-mac.css)
+#elifdef XP_WIN
+ content/activity-stream/css/activity-stream.css (./css/activity-stream-windows.css)
+#else
+ content/activity-stream/css/activity-stream.css (./css/activity-stream-linux.css)
+#endif
+ res/activity-stream/prerendered/activity-stream.html (./prerendered/activity-stream.html)
+#ifndef RELEASE_OR_BETA
+ res/activity-stream/prerendered/activity-stream-debug.html (./prerendered/activity-stream-debug.html)
+#endif
+ res/activity-stream/prerendered/activity-stream-noscripts.html (./prerendered/activity-stream-noscripts.html)
diff --git a/browser/components/newtab/karma.mc.config.js b/browser/components/newtab/karma.mc.config.js
new file mode 100644
index 0000000000..66e749232a
--- /dev/null
+++ b/browser/components/newtab/karma.mc.config.js
@@ -0,0 +1,299 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+const path = require("path");
+
+const PATHS = {
+ // Where is the entry point for the unit tests?
+ testEntryFile: path.resolve(__dirname, "test/unit/unit-entry.js"),
+
+ // A glob-style pattern matching all unit tests
+ testFilesPattern: "test/unit/**/*.js",
+
+ // The base directory of all source files (used for path resolution in webpack importing)
+ moduleResolveDirectory: __dirname,
+
+ // a RegEx matching all Cu.import statements of local files
+ resourcePathRegEx: /^resource:\/\/activity-stream\//,
+
+ coverageReportingPath: "logs/coverage/",
+};
+
+// When tweaking here, be sure to review the docs about the execution ordering
+// semantics of the preprocessors array, as they are somewhat odd.
+const preprocessors = {};
+preprocessors[PATHS.testFilesPattern] = [
+ "webpack", // require("karma-webpack")
+ "sourcemap", // require("karma-sourcemap-loader")
+];
+
+module.exports = function(config) {
+ const isTDD = config.tdd;
+ const browsers = isTDD ? ["Firefox"] : ["FirefoxHeadless"]; // require("karma-firefox-launcher")
+ config.set({
+ singleRun: !isTDD,
+ browsers,
+ customLaunchers: {
+ FirefoxHeadless: {
+ base: "Firefox",
+ flags: ["--headless"],
+ },
+ },
+ frameworks: [
+ "chai", // require("chai") require("karma-chai")
+ "mocha", // require("mocha") require("karma-mocha")
+ "sinon", // require("sinon") require("karma-sinon")
+ ],
+ reporters: [
+ "coverage-istanbul", // require("karma-coverage")
+ "mocha", // require("karma-mocha-reporter")
+
+ // for bin/try-runner.js to parse the output easily
+ "json", // require("karma-json-reporter")
+ ],
+ jsonReporter: {
+ // So this doesn't get interleaved with other karma output
+ stdout: false,
+ outputFile: path.join("logs", "karma-run-results.json"),
+ },
+ coverageIstanbulReporter: {
+ reports: ["html", "text-summary"],
+ dir: PATHS.coverageReportingPath,
+ // This will make karma fail if coverage reporting is less than the minimums here
+ thresholds: !isTDD && {
+ each: {
+ statements: 100,
+ lines: 100,
+ functions: 100,
+ branches: 66,
+ overrides: {
+ "lib/AboutPreferences.jsm": {
+ statements: 98,
+ lines: 98,
+ functions: 100,
+ branches: 66,
+ },
+ "lib/ASRouter.jsm": {
+ statements: 75,
+ lines: 75,
+ functions: 64,
+ branches: 66,
+ },
+ "lib/ASRouterDefaultConfig.jsm": {
+ statements: 0,
+ lines: 0,
+ functions: 0,
+ branches: 0,
+ },
+ "content-src/asrouter/asrouter-utils.js": {
+ statements: 66,
+ lines: 66,
+ functions: 100,
+ branches: 63,
+ },
+ "lib/TelemetryFeed.jsm": {
+ statements: 99,
+ lines: 99,
+ functions: 100,
+ branches: 96,
+ },
+ "lib/ASRouterParentProcessMessageHandler.jsm": {
+ statements: 98,
+ lines: 98,
+ functions: 100,
+ branches: 88,
+ },
+ "content-src/lib/init-store.js": {
+ statements: 98,
+ lines: 98,
+ functions: 100,
+ branches: 100,
+ },
+ "lib/ActivityStreamStorage.jsm": {
+ statements: 100,
+ lines: 100,
+ functions: 100,
+ branches: 83,
+ },
+ "lib/PlacesFeed.jsm": {
+ statements: 98,
+ lines: 98,
+ functions: 100,
+ branches: 84,
+ },
+ "lib/UTEventReporting.jsm": {
+ statements: 100,
+ lines: 100,
+ functions: 100,
+ branches: 75,
+ },
+ "lib/TopSitesFeed.jsm": {
+ statements: 75,
+ lines: 75,
+ functions: 80,
+ branches: 60,
+ },
+ "lib/Screenshots.jsm": {
+ statements: 94,
+ lines: 94,
+ functions: 100,
+ branches: 84,
+ },
+ "lib/*.jsm": {
+ statements: 100,
+ lines: 100,
+ functions: 100,
+ branches: 84,
+ },
+ "content-src/components/DiscoveryStreamComponents/**/*.jsx": {
+ statements: 90.48,
+ lines: 90.48,
+ functions: 85.71,
+ branches: 68.75,
+ },
+ "content-src/asrouter/**/*.jsx": {
+ statements: 57,
+ lines: 58,
+ functions: 60,
+ branches: 50,
+ },
+ "content-src/components/ASRouterAdmin/*.jsx": {
+ statements: 0,
+ lines: 0,
+ functions: 0,
+ branches: 0,
+ },
+ "content-src/components/CustomizeMenu/**/*.jsx": {
+ statements: 0,
+ lines: 0,
+ functions: 0,
+ branches: 0,
+ },
+ "content-src/components/CustomizeMenu/*.jsx": {
+ statements: 0,
+ lines: 0,
+ functions: 0,
+ branches: 0,
+ },
+ "content-src/lib/aboutwelcome-utils.js": {
+ statements: 50,
+ lines: 50,
+ functions: 100,
+ branches: 0,
+ },
+ "content-src/lib/link-menu-options.js": {
+ statements: 96,
+ lines: 96,
+ functions: 96,
+ branches: 70,
+ },
+ "content-src/aboutwelcome/**/*.jsx": {
+ statements: 50,
+ lines: 50,
+ functions: 76,
+ branches: 0,
+ },
+ "content-src/components/**/*.jsx": {
+ statements: 51.1,
+ lines: 52.38,
+ functions: 31.2,
+ branches: 31.2,
+ },
+ },
+ },
+ },
+ },
+ files: [PATHS.testEntryFile],
+ preprocessors,
+ webpack: {
+ mode: "none",
+ devtool: "inline-source-map",
+ // This loader allows us to override required files in tests
+ resolveLoader: {
+ alias: { inject: path.join(__dirname, "loaders/inject-loader") },
+ },
+ // This resolve config allows us to import with paths relative to the root directory, e.g. "lib/ActivityStream.jsm"
+ resolve: {
+ extensions: [".js", ".jsx"],
+ modules: [PATHS.moduleResolveDirectory, "node_modules"],
+ },
+ externals: {
+ // enzyme needs these for backwards compatibility with 0.13.
+ // see https://github.com/airbnb/enzyme/blob/master/docs/guides/webpack.md#using-enzyme-with-webpack
+ "react/addons": true,
+ "react/lib/ReactContext": true,
+ "react/lib/ExecutionEnvironment": true,
+ },
+ module: {
+ rules: [
+ // This rule rewrites importing/exporting in .jsm files to be compatible with esmodules
+ {
+ test: /\.jsm$/,
+ exclude: [/node_modules/],
+ use: [
+ {
+ loader: "babel-loader", // require("babel-core")
+ options: {
+ plugins: [
+ // Converts .jsm files into common-js modules
+ [
+ "jsm-to-commonjs",
+ {
+ basePath: PATHS.resourcePathRegEx,
+ removeOtherImports: true,
+ replace: true,
+ },
+ ], // require("babel-plugin-jsm-to-commonjs")
+ "@babel/plugin-proposal-nullish-coalescing-operator",
+ "@babel/plugin-proposal-optional-chaining",
+ "@babel/plugin-proposal-class-properties",
+ ],
+ },
+ },
+ ],
+ },
+ {
+ test: /\.js$/,
+ exclude: [/node_modules\/(?!(fluent|fluent-react)\/).*/, /test/],
+ loader: "babel-loader",
+ },
+ {
+ test: /\.jsx$/,
+ exclude: /node_modules/,
+ loader: "babel-loader",
+ options: {
+ presets: ["@babel/preset-react"],
+ },
+ },
+ {
+ test: /\.md$/,
+ use: "raw-loader",
+ },
+ {
+ enforce: "post",
+ test: /\.js[mx]?$/,
+ loader: "istanbul-instrumenter-loader",
+ options: { esModules: true },
+ include: [
+ path.resolve("content-src"),
+ path.resolve("lib"),
+ path.resolve("common"),
+ ],
+ exclude: [
+ path.resolve("test"),
+ path.resolve("vendor"),
+ path.resolve("lib/ASRouterTargeting.jsm"),
+ path.resolve("lib/ASRouterTriggerListeners.jsm"),
+ path.resolve("lib/OnboardingMessageProvider.jsm"),
+ path.resolve("lib/CFRMessageProvider.jsm"),
+ path.resolve("lib/CFRPageActions.jsm"),
+ ],
+ },
+ ],
+ },
+ },
+ // Silences some overly-verbose logging of individual module builds
+ webpackMiddleware: { noInfo: true },
+ });
+};
diff --git a/browser/components/newtab/lib/ASRouter.jsm b/browser/components/newtab/lib/ASRouter.jsm
new file mode 100644
index 0000000000..ea9b8fb5d0
--- /dev/null
+++ b/browser/components/newtab/lib/ASRouter.jsm
@@ -0,0 +1,1753 @@
+/* vim: set ts=2 sw=2 sts=2 et tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
+const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
+const { XPCOMUtils } = ChromeUtils.import(
+ "resource://gre/modules/XPCOMUtils.jsm"
+);
+XPCOMUtils.defineLazyGlobalGetters(this, ["fetch"]);
+XPCOMUtils.defineLazyModuleGetters(this, {
+ AppConstants: "resource://gre/modules/AppConstants.jsm",
+ BookmarkPanelHub: "resource://activity-stream/lib/BookmarkPanelHub.jsm",
+ SnippetsTestMessageProvider:
+ "resource://activity-stream/lib/SnippetsTestMessageProvider.jsm",
+ PanelTestProvider: "resource://activity-stream/lib/PanelTestProvider.jsm",
+ ToolbarBadgeHub: "resource://activity-stream/lib/ToolbarBadgeHub.jsm",
+ ToolbarPanelHub: "resource://activity-stream/lib/ToolbarPanelHub.jsm",
+ MomentsPageHub: "resource://activity-stream/lib/MomentsPageHub.jsm",
+ InfoBar: "resource://activity-stream/lib/InfoBar.jsm",
+ ASRouterTargeting: "resource://activity-stream/lib/ASRouterTargeting.jsm",
+ ASRouterPreferences: "resource://activity-stream/lib/ASRouterPreferences.jsm",
+ TARGETING_PREFERENCES:
+ "resource://activity-stream/lib/ASRouterPreferences.jsm",
+ ASRouterTriggerListeners:
+ "resource://activity-stream/lib/ASRouterTriggerListeners.jsm",
+ CFRMessageProvider: "resource://activity-stream/lib/CFRMessageProvider.jsm",
+ KintoHttpClient: "resource://services-common/kinto-http-client.js",
+ Downloader: "resource://services-settings/Attachments.jsm",
+ RemoteL10n: "resource://activity-stream/lib/RemoteL10n.jsm",
+ ExperimentAPI: "resource://messaging-system/experiments/ExperimentAPI.jsm",
+ SpecialMessageActions:
+ "resource://messaging-system/lib/SpecialMessageActions.jsm",
+ TargetingContext: "resource://messaging-system/targeting/Targeting.jsm",
+ MacAttribution: "resource:///modules/MacAttribution.jsm",
+});
+XPCOMUtils.defineLazyServiceGetters(this, {
+ BrowserHandler: ["@mozilla.org/browser/clh;1", "nsIBrowserHandler"],
+});
+const { actionCreators: ac } = ChromeUtils.import(
+ "resource://activity-stream/common/Actions.jsm"
+);
+
+const { CFRMessageProvider } = ChromeUtils.import(
+ "resource://activity-stream/lib/CFRMessageProvider.jsm"
+);
+const { OnboardingMessageProvider } = ChromeUtils.import(
+ "resource://activity-stream/lib/OnboardingMessageProvider.jsm"
+);
+const { RemoteSettings } = ChromeUtils.import(
+ "resource://services-settings/remote-settings.js"
+);
+const { CFRPageActions } = ChromeUtils.import(
+ "resource://activity-stream/lib/CFRPageActions.jsm"
+);
+const { AttributionCode } = ChromeUtils.import(
+ "resource:///modules/AttributionCode.jsm"
+);
+
+// List of hosts for endpoints that serve router messages.
+// Key is allowed host, value is a name for the endpoint host.
+const DEFAULT_ALLOWLIST_HOSTS = {
+ "activity-stream-icons.services.mozilla.com": "production",
+ "snippets-admin.mozilla.org": "preview",
+};
+const SNIPPETS_ENDPOINT_ALLOWLIST =
+ "browser.newtab.activity-stream.asrouter.allowHosts";
+// Max possible impressions cap for any message
+const MAX_MESSAGE_LIFETIME_CAP = 100;
+
+const LOCAL_MESSAGE_PROVIDERS = {
+ OnboardingMessageProvider,
+ CFRMessageProvider,
+};
+const STARTPAGE_VERSION = "6";
+
+// Remote Settings
+const RS_SERVER_PREF = "services.settings.server";
+const RS_MAIN_BUCKET = "main";
+const RS_COLLECTION_L10N = "ms-language-packs"; // "ms" stands for Messaging System
+const RS_PROVIDERS_WITH_L10N = ["cfr", "cfr-fxa", "whats-new-panel"];
+const RS_FLUENT_VERSION = "v1";
+const RS_FLUENT_RECORD_PREFIX = `cfr-${RS_FLUENT_VERSION}`;
+const RS_DOWNLOAD_MAX_RETRIES = 2;
+// This is the list of providers for which we want to cache the targeting
+// expression result and reuse between calls. Cache duration is defined in
+// ASRouterTargeting where evaluation takes place.
+const JEXL_PROVIDER_CACHE = new Set(["snippets"]);
+
+// To observe the app locale change notification.
+const TOPIC_INTL_LOCALE_CHANGED = "intl:app-locales-changed";
+// To observe the pref that controls if ASRouter should use the remote Fluent files for l10n.
+const USE_REMOTE_L10N_PREF =
+ "browser.newtabpage.activity-stream.asrouter.useRemoteL10n";
+
+// Experiment groups that need to report the reach event in Messaging-Experiments.
+// If you're adding new groups to it, make sure they're also added in the
+// `messaging_experiments.reach.objects` defined in "toolkit/components/telemetry/Events.yaml"
+const REACH_EVENT_GROUPS = ["cfr", "moments-page"];
+const REACH_EVENT_CATEGORY = "messaging_experiments";
+const REACH_EVENT_METHOD = "reach";
+
+const MessageLoaderUtils = {
+ STARTPAGE_VERSION,
+ REMOTE_LOADER_CACHE_KEY: "RemoteLoaderCache",
+ _errors: [],
+
+ reportError(e) {
+ Cu.reportError(e);
+ this._errors.push({
+ timestamp: new Date(),
+ error: { message: e.toString(), stack: e.stack },
+ });
+ },
+
+ get errors() {
+ const errors = this._errors;
+ this._errors = [];
+ return errors;
+ },
+
+ /**
+ * _localLoader - Loads messages for a local provider (i.e. one that lives in mozilla central)
+ *
+ * @param {obj} provider An AS router provider
+ * @param {Array} provider.messages An array of messages
+ * @returns {Array} the array of messages
+ */
+ _localLoader(provider) {
+ return provider.messages;
+ },
+
+ async _localJsonLoader(provider) {
+ let payload;
+ try {
+ payload = await (
+ await fetch(provider.location, {
+ credentials: "omit",
+ })
+ ).json();
+ } catch (e) {
+ return [];
+ }
+
+ return payload.messages;
+ },
+
+ async _remoteLoaderCache(storage) {
+ let allCached;
+ try {
+ allCached =
+ (await storage.get(MessageLoaderUtils.REMOTE_LOADER_CACHE_KEY)) || {};
+ } catch (e) {
+ // istanbul ignore next
+ MessageLoaderUtils.reportError(e);
+ // istanbul ignore next
+ allCached = {};
+ }
+ return allCached;
+ },
+
+ /**
+ * _remoteLoader - Loads messages for a remote provider
+ *
+ * @param {obj} provider An AS router provider
+ * @param {string} provider.url An endpoint that returns an array of messages as JSON
+ * @param {obj} options.storage A storage object with get() and set() methods for caching.
+ * @returns {Promise} resolves with an array of messages, or an empty array if none could be fetched
+ */
+ async _remoteLoader(provider, options) {
+ let remoteMessages = [];
+ if (provider.url) {
+ const allCached = await MessageLoaderUtils._remoteLoaderCache(
+ options.storage
+ );
+ const cached = allCached[provider.id];
+ let etag;
+
+ if (
+ cached &&
+ cached.url === provider.url &&
+ cached.version === STARTPAGE_VERSION
+ ) {
+ const { lastFetched, messages } = cached;
+ if (
+ !MessageLoaderUtils.shouldProviderUpdate({
+ ...provider,
+ lastUpdated: lastFetched,
+ })
+ ) {
+ // Cached messages haven't expired, return early.
+ return messages;
+ }
+ etag = cached.etag;
+ remoteMessages = messages;
+ }
+
+ let headers = new Headers();
+ if (etag) {
+ headers.set("If-None-Match", etag);
+ }
+
+ let response;
+ try {
+ response = await fetch(provider.url, { headers, credentials: "omit" });
+ } catch (e) {
+ MessageLoaderUtils.reportError(e);
+ }
+ if (
+ response &&
+ response.ok &&
+ response.status >= 200 &&
+ response.status < 400
+ ) {
+ let jsonResponse;
+ try {
+ jsonResponse = await response.json();
+ } catch (e) {
+ MessageLoaderUtils.reportError(e);
+ return remoteMessages;
+ }
+ if (jsonResponse && jsonResponse.messages) {
+ remoteMessages = jsonResponse.messages.map(msg => ({
+ ...msg,
+ provider_url: provider.url,
+ }));
+
+ // Cache the results if this isn't a preview URL.
+ if (provider.updateCycleInMs > 0) {
+ etag = response.headers.get("ETag");
+ const cacheInfo = {
+ messages: remoteMessages,
+ etag,
+ lastFetched: Date.now(),
+ version: STARTPAGE_VERSION,
+ };
+
+ options.storage.set(MessageLoaderUtils.REMOTE_LOADER_CACHE_KEY, {
+ ...allCached,
+ [provider.id]: cacheInfo,
+ });
+ }
+ } else {
+ MessageLoaderUtils.reportError(
+ `No messages returned from ${provider.url}.`
+ );
+ }
+ } else if (response) {
+ MessageLoaderUtils.reportError(
+ `Invalid response status ${response.status} from ${provider.url}.`
+ );
+ }
+ }
+ return remoteMessages;
+ },
+
+ /**
+ * _remoteSettingsLoader - Loads messages for a RemoteSettings provider
+ *
+ * Note:
+ * 1). Both "cfr" and "cfr-fxa" require the Fluent file for l10n, so there is
+ * another file downloading phase for those two providers after their messages
+ * are successfully fetched from Remote Settings. Currently, they share the same
+ * attachment of the record "${RS_FLUENT_RECORD_PREFIX}-${locale}" in the
+ * "ms-language-packs" collection. E.g. for "en-US" with version "v1",
+ * the Fluent file is attched to the record with ID "cfr-v1-en-US".
+ *
+ * 2). The Remote Settings downloader is able to detect the duplicate download
+ * requests for the same attachment and ignore the redundent requests automatically.
+ *
+ * @param {obj} provider An AS router provider
+ * @param {string} provider.id The id of the provider
+ * @param {string} provider.bucket The name of the Remote Settings bucket
+ * @param {func} options.dispatchCFRAction dispatch an action the main AS Store
+ * @returns {Promise} resolves with an array of messages, or an empty array if none could be fetched
+ */
+ async _remoteSettingsLoader(provider, options) {
+ let messages = [];
+ if (provider.bucket) {
+ try {
+ messages = await MessageLoaderUtils._getRemoteSettingsMessages(
+ provider.bucket
+ );
+ if (!messages.length) {
+ MessageLoaderUtils._handleRemoteSettingsUndesiredEvent(
+ "ASR_RS_NO_MESSAGES",
+ provider.id,
+ options.dispatchCFRAction
+ );
+ } else if (
+ RS_PROVIDERS_WITH_L10N.includes(provider.id) &&
+ (RemoteL10n.isLocaleSupported(Services.locale.appLocaleAsBCP47) ||
+ // While it's not a valid locale, "und" is commonly observed on
+ // Linux platforms. Per l10n team, it's reasonable to fallback to
+ // "en-US", therefore, we should allow the fetch for it.
+ Services.locale.appLocaleAsBCP47 === "und")
+ ) {
+ let locale = Services.locale.appLocaleAsBCP47;
+ // Fallback to "en-US" if locale is "und"
+ if (locale === "und") {
+ locale = "en-US";
+ }
+ const recordId = `${RS_FLUENT_RECORD_PREFIX}-${locale}`;
+ const kinto = new KintoHttpClient(
+ Services.prefs.getStringPref(RS_SERVER_PREF)
+ );
+ const record = await kinto
+ .bucket(RS_MAIN_BUCKET)
+ .collection(RS_COLLECTION_L10N)
+ .getRecord(recordId);
+ if (record && record.data) {
+ const downloader = new Downloader(
+ RS_MAIN_BUCKET,
+ RS_COLLECTION_L10N
+ );
+ // Await here in order to capture the exceptions for reporting.
+ await downloader.download(record.data, {
+ retries: RS_DOWNLOAD_MAX_RETRIES,
+ });
+ RemoteL10n.reloadL10n();
+ } else {
+ MessageLoaderUtils._handleRemoteSettingsUndesiredEvent(
+ "ASR_RS_NO_MESSAGES",
+ RS_COLLECTION_L10N,
+ options.dispatchCFRAction
+ );
+ }
+ }
+ } catch (e) {
+ MessageLoaderUtils._handleRemoteSettingsUndesiredEvent(
+ "ASR_RS_ERROR",
+ provider.id,
+ options.dispatchCFRAction
+ );
+ MessageLoaderUtils.reportError(e);
+ }
+ }
+ return messages;
+ },
+
+ _getRemoteSettingsMessages(bucket) {
+ return RemoteSettings(bucket).get();
+ },
+
+ async _experimentsAPILoader(provider, options) {
+ try {
+ await ExperimentAPI.ready();
+ } catch (e) {
+ MessageLoaderUtils.reportError(e);
+ return [];
+ }
+
+ let experiments = [];
+ for (const featureId of provider.messageGroups) {
+ let experimentData;
+ try {
+ experimentData = ExperimentAPI.getExperiment({
+ featureId,
+ sendExposurePing: false,
+ });
+ // Not enrolled in any experiment for this feature, we can skip
+ if (!experimentData) {
+ continue;
+ }
+ } catch (e) {
+ MessageLoaderUtils.reportError(e);
+ continue;
+ }
+
+ // If the feature is not enabled there is no message to send back.
+ // Other branches might be enabled so we check those as well in case we
+ // need to send a reach ping.
+ let featureData = experimentData.branch.feature;
+ if (featureData.enabled) {
+ experiments.push({
+ forExposureEvent: {
+ sent: experimentData.exposurePingSent,
+ experimentSlug: experimentData.slug,
+ branchSlug: experimentData.branch.slug,
+ },
+ ...featureData.value,
+ });
+ }
+
+ if (!REACH_EVENT_GROUPS.includes(featureId)) {
+ continue;
+ }
+ // Check other sibling branches for triggers, add them to the return
+ // array if found any. The `forReachEvent` label is used to identify
+ // those branches so that they would only used to record the Reach
+ // event.
+ const branches =
+ (await ExperimentAPI.getAllBranches(experimentData.slug)) || [];
+ for (const branch of branches) {
+ let branchValue = branch.feature.value;
+ if (branch.slug !== experimentData.branch.slug && branchValue.trigger) {
+ experiments.push({
+ forReachEvent: { sent: false, group: featureId },
+ experimentSlug: experimentData.slug,
+ branchSlug: branch.slug,
+ ...branchValue,
+ });
+ }
+ }
+ }
+
+ return experiments;
+ },
+
+ _handleRemoteSettingsUndesiredEvent(event, providerId, dispatchCFRAction) {
+ if (dispatchCFRAction) {
+ dispatchCFRAction(
+ ac.ASRouterUserEvent({
+ action: "asrouter_undesired_event",
+ event,
+ message_id: "n/a",
+ event_context: providerId,
+ })
+ );
+ }
+ },
+
+ /**
+ * _getMessageLoader - return the right loading function given the provider's type
+ *
+ * @param {obj} provider An AS Router provider
+ * @returns {func} A loading function
+ */
+ _getMessageLoader(provider) {
+ switch (provider.type) {
+ case "remote":
+ return this._remoteLoader;
+ case "remote-settings":
+ return this._remoteSettingsLoader;
+ case "json":
+ return this._localJsonLoader;
+ case "remote-experiments":
+ return this._experimentsAPILoader;
+ case "local":
+ default:
+ return this._localLoader;
+ }
+ },
+
+ /**
+ * shouldProviderUpdate - Given the current time, should a provider update its messages?
+ *
+ * @param {any} provider An AS Router provider
+ * @param {int} provider.updateCycleInMs The number of milliseconds we should wait between updates
+ * @param {Date} provider.lastUpdated If the provider has been updated, the time the last update occurred
+ * @param {Date} currentTime The time we should check against. (defaults to Date.now())
+ * @returns {bool} Should an update happen?
+ */
+ shouldProviderUpdate(provider, currentTime = Date.now()) {
+ return (
+ !(provider.lastUpdated >= 0) ||
+ currentTime - provider.lastUpdated > provider.updateCycleInMs
+ );
+ },
+
+ async _loadDataForProvider(provider, options) {
+ const loader = this._getMessageLoader(provider);
+ let messages = await loader(provider, options);
+ // istanbul ignore if
+ if (!messages) {
+ messages = [];
+ MessageLoaderUtils.reportError(
+ new Error(
+ `Tried to load messages for ${provider.id} but the result was not an Array.`
+ )
+ );
+ }
+
+ return { messages };
+ },
+
+ /**
+ * loadMessagesForProvider - Load messages for a provider, given the provider's type.
+ *
+ * @param {obj} provider An AS Router provider
+ * @param {string} provider.type An AS Router provider type (defaults to "local")
+ * @param {obj} options.storage A storage object with get() and set() methods for caching.
+ * @param {func} options.dispatchCFRAction dispatch an action the main AS Store
+ * @returns {obj} Returns an object with .messages (an array of messages) and .lastUpdated (the time the messages were updated)
+ */
+ async loadMessagesForProvider(provider, options) {
+ let { messages } = await this._loadDataForProvider(provider, options);
+ // Filter out messages we temporarily want to exclude
+ if (provider.exclude && provider.exclude.length) {
+ messages = messages.filter(
+ message => !provider.exclude.includes(message.id)
+ );
+ }
+ const lastUpdated = Date.now();
+ return {
+ messages: messages
+ .map(messageData => {
+ const message = {
+ weight: 100,
+ ...messageData,
+ groups: messageData.groups || [],
+ provider: provider.id,
+ };
+
+ // This is to support a personalization experiment
+ if (provider.personalized) {
+ const score = ASRouterPreferences.personalizedCfrScores[message.id];
+ if (score) {
+ message.score = score;
+ }
+ message.personalizedModelVersion =
+ provider.personalizedModelVersion;
+ }
+
+ return message;
+ })
+ .filter(message => message.weight > 0),
+ lastUpdated,
+ errors: MessageLoaderUtils.errors,
+ };
+ },
+
+ /**
+ * cleanupCache - Removes cached data of removed providers.
+ *
+ * @param {Array} providers A list of activer AS Router providers
+ */
+ async cleanupCache(providers, storage) {
+ const ids = providers.filter(p => p.type === "remote").map(p => p.id);
+ const cache = await MessageLoaderUtils._remoteLoaderCache(storage);
+ let dirty = false;
+ for (let id in cache) {
+ if (!ids.includes(id)) {
+ delete cache[id];
+ dirty = true;
+ }
+ }
+ if (dirty) {
+ await storage.set(MessageLoaderUtils.REMOTE_LOADER_CACHE_KEY, cache);
+ }
+ },
+};
+
+this.MessageLoaderUtils = MessageLoaderUtils;
+
+/**
+ * @class _ASRouter - Keeps track of all messages, UI surfaces, and
+ * handles blocking, rotation, etc. Inspecting ASRouter.state will
+ * tell you what the current displayed message is in all UI surfaces.
+ *
+ * Note: This is written as a constructor rather than just a plain object
+ * so that it can be more easily unit tested.
+ */
+class _ASRouter {
+ constructor(localProviders = LOCAL_MESSAGE_PROVIDERS) {
+ this.initialized = false;
+ this.clearChildMessages = null;
+ this.clearChildProviders = null;
+ this.updateAdminState = null;
+ this.sendTelemetry = null;
+ this.dispatchCFRAction = null;
+ this._storage = null;
+ this._resetInitialization();
+ this._state = {
+ providers: [],
+ messageBlockList: [],
+ messageImpressions: {},
+ messages: [],
+ groups: [],
+ errors: [],
+ localeInUse: Services.locale.appLocaleAsBCP47,
+ };
+ this._triggerHandler = this._triggerHandler.bind(this);
+ this._localProviders = localProviders;
+ this.blockMessageById = this.blockMessageById.bind(this);
+ this.unblockMessageById = this.unblockMessageById.bind(this);
+ this.handleMessageRequest = this.handleMessageRequest.bind(this);
+ this.addImpression = this.addImpression.bind(this);
+ this._handleTargetingError = this._handleTargetingError.bind(this);
+ this.onPrefChange = this.onPrefChange.bind(this);
+ this._onLocaleChanged = this._onLocaleChanged.bind(this);
+ this.isUnblockedMessage = this.isUnblockedMessage.bind(this);
+ this.unblockAll = this.unblockAll.bind(this);
+ this.forceWNPanel = this.forceWNPanel.bind(this);
+ Services.telemetry.setEventRecordingEnabled(REACH_EVENT_CATEGORY, true);
+ }
+
+ async onPrefChange(prefName) {
+ if (TARGETING_PREFERENCES.includes(prefName)) {
+ let invalidMessages = [];
+ // Notify all tabs of messages that have become invalid after pref change
+ const context = this._getMessagesContext();
+ const targetingContext = new TargetingContext(context);
+
+ for (const msg of this.state.messages.filter(this.isUnblockedMessage)) {
+ if (!msg.targeting) {
+ continue;
+ }
+ const isMatch = await targetingContext.evalWithDefault(msg.targeting);
+ if (!isMatch) {
+ invalidMessages.push(msg.id);
+ }
+ }
+ this.clearChildMessages(invalidMessages);
+ } else {
+ // Update message providers and fetch new messages on pref change
+ this._loadLocalProviders();
+ let invalidProviders = await this._updateMessageProviders();
+ if (invalidProviders.length) {
+ this.clearChildProviders(invalidProviders);
+ }
+ await this.loadMessagesFromAllProviders();
+ // Any change in user prefs can disable or enable groups
+ await this.setState(state => ({
+ groups: state.groups.map(this._checkGroupEnabled),
+ }));
+ }
+ }
+
+ // Fetch and decode the message provider pref JSON, and update the message providers
+ async _updateMessageProviders() {
+ const previousProviders = this.state.providers;
+ const providers = await Promise.all(
+ [
+ // If we have added a `preview` provider, hold onto it
+ ...previousProviders.filter(p => p.id === "preview"),
+ // The provider should be enabled and not have a user preference set to false
+ ...ASRouterPreferences.providers.filter(
+ p =>
+ p.enabled && ASRouterPreferences.getUserPreference(p.id) !== false
+ ),
+ ].map(async _provider => {
+ // make a copy so we don't modify the source of the pref
+ const provider = { ..._provider };
+
+ if (provider.type === "local" && !provider.messages) {
+ // Get the messages from the local message provider
+ const localProvider = this._localProviders[provider.localProvider];
+ provider.messages = [];
+ if (localProvider) {
+ provider.messages = await localProvider.getMessages();
+ }
+ }
+ if (provider.type === "remote" && provider.url) {
+ provider.url = provider.url.replace(
+ /%STARTPAGE_VERSION%/g,
+ STARTPAGE_VERSION
+ );
+ provider.url = Services.urlFormatter.formatURL(provider.url);
+ }
+ // Reset provider update timestamp to force message refresh
+ provider.lastUpdated = undefined;
+ return provider;
+ })
+ );
+
+ const providerIDs = providers.map(p => p.id);
+ let invalidProviders = [];
+
+ // Clear old messages for providers that are no longer enabled
+ for (const prevProvider of previousProviders) {
+ if (!providerIDs.includes(prevProvider.id)) {
+ invalidProviders.push(prevProvider.id);
+ }
+ }
+
+ return this.setState(prevState => ({
+ providers,
+ // Clear any messages from removed providers
+ messages: [
+ ...prevState.messages.filter(message =>
+ providerIDs.includes(message.provider)
+ ),
+ ],
+ })).then(() => invalidProviders);
+ }
+
+ get state() {
+ return this._state;
+ }
+
+ set state(value) {
+ throw new Error(
+ "Do not modify this.state directy. Instead, call this.setState(newState)"
+ );
+ }
+
+ /**
+ * _resetInitialization - adds the following to the instance:
+ * .initialized {bool} Has AS Router been initialized?
+ * .waitForInitialized {Promise} A promise that resolves when initializion is complete
+ * ._finishInitializing {func} A function that, when called, resolves the .waitForInitialized
+ * promise and sets .initialized to true.
+ * @memberof _ASRouter
+ */
+ _resetInitialization() {
+ this.initialized = false;
+ this.waitForInitialized = new Promise(resolve => {
+ this._finishInitializing = () => {
+ this.initialized = true;
+ resolve();
+ };
+ });
+ }
+
+ /**
+ * Check all provided groups are enabled.
+ * @param groups Set of groups to verify
+ * @returns bool
+ */
+ hasGroupsEnabled(groups = []) {
+ return this.state.groups
+ .filter(({ id }) => groups.includes(id))
+ .every(({ enabled }) => enabled);
+ }
+
+ /**
+ * Verify that the provider block the message through the `exclude` field
+ * @param message Message to verify
+ * @returns bool
+ */
+ isExcludedByProvider(message) {
+ // preview snippets are never excluded
+ if (message.provider === "preview") {
+ return false;
+ }
+ const provider = this.state.providers.find(p => p.id === message.provider);
+ if (!provider) {
+ return true;
+ }
+ if (provider.exclude) {
+ return provider.exclude.includes(message.id);
+ }
+ return false;
+ }
+
+ /**
+ * Takes a group and sets the correct `enabled` state based on message config
+ * and user preferences
+ *
+ * @param {GroupConfig} group
+ * @returns {GroupConfig}
+ */
+ _checkGroupEnabled(group) {
+ return {
+ ...group,
+ enabled:
+ group.enabled &&
+ // And if defined user preferences are true. If multiple prefs are
+ // defined then at least one has to be enabled.
+ (Array.isArray(group.userPreferences)
+ ? group.userPreferences.some(pref =>
+ ASRouterPreferences.getUserPreference(pref)
+ )
+ : true),
+ };
+ }
+
+ /**
+ * Fetch all message groups and update Router.state.groups.
+ * There are two cases to consider:
+ * 1. The provider needs to update as determined by the update cycle
+ * 2. Some pref change occured which could invalidate one of the existing
+ * groups.
+ */
+ async loadAllMessageGroups() {
+ const provider = this.state.providers.find(
+ p =>
+ p.id === "message-groups" && MessageLoaderUtils.shouldProviderUpdate(p)
+ );
+ let remoteMessages = null;
+ if (provider) {
+ const { messages } = await MessageLoaderUtils._loadDataForProvider(
+ provider,
+ {
+ storage: this._storage,
+ dispatchCFRAction: this.dispatchCFRAction,
+ }
+ );
+ remoteMessages = messages;
+ }
+ await this.setState(state => ({
+ // If fetching remote messages fails we default to existing state.groups.
+ groups: (remoteMessages || state.groups).map(this._checkGroupEnabled),
+ }));
+ }
+
+ /**
+ * loadMessagesFromAllProviders - Loads messages from all providers if they require updates.
+ * Checks the .lastUpdated field on each provider to see if updates are needed
+ * @memberof _ASRouter
+ */
+ async loadMessagesFromAllProviders() {
+ const needsUpdate = this.state.providers.filter(provider =>
+ MessageLoaderUtils.shouldProviderUpdate(provider)
+ );
+ await this.loadAllMessageGroups();
+ // Don't do extra work if we don't need any updates
+ if (needsUpdate.length) {
+ let newState = { messages: [], providers: [] };
+ for (const provider of this.state.providers) {
+ if (needsUpdate.includes(provider)) {
+ const {
+ messages,
+ lastUpdated,
+ errors,
+ } = await MessageLoaderUtils.loadMessagesForProvider(provider, {
+ storage: this._storage,
+ dispatchCFRAction: this.dispatchCFRAction,
+ });
+ newState.providers.push({ ...provider, lastUpdated, errors });
+ newState.messages = [...newState.messages, ...messages];
+ } else {
+ // Skip updating this provider's messages if no update is required
+ let messages = this.state.messages.filter(
+ msg => msg.provider === provider.id
+ );
+ newState.providers.push(provider);
+ newState.messages = [...newState.messages, ...messages];
+ }
+ }
+
+ // Some messages have triggers that require us to initalise trigger listeners
+ const unseenListeners = new Set(ASRouterTriggerListeners.keys());
+ for (const { trigger } of newState.messages) {
+ if (trigger && ASRouterTriggerListeners.has(trigger.id)) {
+ ASRouterTriggerListeners.get(trigger.id).init(
+ this._triggerHandler,
+ trigger.params,
+ trigger.patterns
+ );
+ unseenListeners.delete(trigger.id);
+ }
+ }
+ // We don't need these listeners, but they may have previously been
+ // initialised, so uninitialise them
+ for (const triggerID of unseenListeners) {
+ ASRouterTriggerListeners.get(triggerID).uninit();
+ }
+
+ // We don't want to cache preview endpoints, remove them after messages are fetched
+ await this.setState(this._removePreviewEndpoint(newState));
+ await this.cleanupImpressions();
+ }
+ return this.state;
+ }
+
+ async _maybeUpdateL10nAttachment() {
+ const { localeInUse } = this.state.localeInUse;
+ const newLocale = Services.locale.appLocaleAsBCP47;
+ if (newLocale !== localeInUse) {
+ const providers = [...this.state.providers];
+ let needsUpdate = false;
+ providers.forEach(provider => {
+ if (RS_PROVIDERS_WITH_L10N.includes(provider.id)) {
+ // Force to refresh the messages as well as the attachment.
+ provider.lastUpdated = undefined;
+ needsUpdate = true;
+ }
+ });
+ if (needsUpdate) {
+ await this.setState({
+ localeInUse: newLocale,
+ providers,
+ });
+ await this.loadMessagesFromAllProviders();
+ }
+ }
+ return this.state;
+ }
+
+ async _onLocaleChanged(subject, topic, data) {
+ await this._maybeUpdateL10nAttachment();
+ }
+
+ observe(aSubject, aTopic, aPrefName) {
+ switch (aPrefName) {
+ case USE_REMOTE_L10N_PREF:
+ CFRPageActions.reloadL10n();
+ break;
+ }
+ }
+
+ toWaitForInitFunc(func) {
+ return (...args) => this.waitForInitialized.then(() => func(...args));
+ }
+
+ /**
+ * init - Initializes the MessageRouter.
+ *
+ * @param {obj} parameters parameters to initialize ASRouter
+ * @memberof _ASRouter
+ */
+ async init({
+ storage,
+ sendTelemetry,
+ clearChildMessages,
+ clearChildProviders,
+ updateAdminState,
+ dispatchCFRAction,
+ }) {
+ this._storage = storage;
+ this.ALLOWLIST_HOSTS = this._loadSnippetsAllowHosts();
+ this.clearChildMessages = this.toWaitForInitFunc(clearChildMessages);
+ this.clearChildProviders = this.toWaitForInitFunc(clearChildProviders);
+ // NOTE: This is only necessary to sync devtools and snippets when devtools is active.
+ this.updateAdminState = this.toWaitForInitFunc(updateAdminState);
+ this.sendTelemetry = sendTelemetry;
+ this.dispatchCFRAction = this.toWaitForInitFunc(dispatchCFRAction);
+
+ ASRouterPreferences.init();
+ ASRouterPreferences.addListener(this.onPrefChange);
+ BookmarkPanelHub.init(
+ this.handleMessageRequest,
+ this.addImpression,
+ this.sendTelemetry
+ );
+ ToolbarBadgeHub.init(this.waitForInitialized, {
+ handleMessageRequest: this.handleMessageRequest,
+ addImpression: this.addImpression,
+ blockMessageById: this.blockMessageById,
+ unblockMessageById: this.unblockMessageById,
+ sendTelemetry: this.sendTelemetry,
+ });
+ ToolbarPanelHub.init(this.waitForInitialized, {
+ getMessages: this.handleMessageRequest,
+ sendTelemetry: this.sendTelemetry,
+ });
+ MomentsPageHub.init(this.waitForInitialized, {
+ handleMessageRequest: this.handleMessageRequest,
+ addImpression: this.addImpression,
+ blockMessageById: this.blockMessageById,
+ sendTelemetry: this.sendTelemetry,
+ });
+
+ this._loadLocalProviders();
+
+ const messageBlockList =
+ (await this._storage.get("messageBlockList")) || [];
+ const messageImpressions =
+ (await this._storage.get("messageImpressions")) || {};
+ const groupImpressions =
+ (await this._storage.get("groupImpressions")) || {};
+ const previousSessionEnd =
+ (await this._storage.get("previousSessionEnd")) || 0;
+
+ await this.setState({
+ messageBlockList,
+ groupImpressions,
+ messageImpressions,
+ previousSessionEnd,
+ ...(ASRouterPreferences.specialConditions || {}),
+ initialized: false,
+ });
+ await this._updateMessageProviders();
+ await this.loadMessagesFromAllProviders();
+ await MessageLoaderUtils.cleanupCache(this.state.providers, storage);
+
+ SpecialMessageActions.blockMessageById = this.blockMessageById;
+ Services.obs.addObserver(this._onLocaleChanged, TOPIC_INTL_LOCALE_CHANGED);
+ Services.prefs.addObserver(USE_REMOTE_L10N_PREF, this);
+ // sets .initialized to true and resolves .waitForInitialized promise
+ this._finishInitializing();
+ return this.state;
+ }
+
+ uninit() {
+ this._storage.set("previousSessionEnd", Date.now());
+
+ this.clearChildMessages = null;
+ this.clearChildProviders = null;
+ this.updateAdminState = null;
+ this.sendTelemetry = null;
+ this.dispatchCFRAction = null;
+
+ ASRouterPreferences.removeListener(this.onPrefChange);
+ ASRouterPreferences.uninit();
+ BookmarkPanelHub.uninit();
+ ToolbarPanelHub.uninit();
+ ToolbarBadgeHub.uninit();
+ MomentsPageHub.uninit();
+
+ // Uninitialise all trigger listeners
+ for (const listener of ASRouterTriggerListeners.values()) {
+ listener.uninit();
+ }
+ Services.obs.removeObserver(
+ this._onLocaleChanged,
+ TOPIC_INTL_LOCALE_CHANGED
+ );
+ Services.prefs.removeObserver(USE_REMOTE_L10N_PREF, this);
+ // If we added any CFR recommendations, they need to be removed
+ CFRPageActions.clearRecommendations();
+ this._resetInitialization();
+ }
+
+ setState(callbackOrObj) {
+ const newState =
+ typeof callbackOrObj === "function"
+ ? callbackOrObj(this.state)
+ : callbackOrObj;
+ this._state = {
+ ...this.state,
+ ...newState,
+ };
+ if (ASRouterPreferences.devtoolsEnabled) {
+ return this.updateTargetingParameters().then(state => {
+ this.updateAdminState(state);
+ return state;
+ });
+ }
+ return Promise.resolve(this.state);
+ }
+
+ updateTargetingParameters() {
+ return this.getTargetingParameters(
+ ASRouterTargeting.Environment,
+ this._getMessagesContext()
+ ).then(targetingParameters => ({
+ ...this.state,
+ providerPrefs: ASRouterPreferences.providers,
+ userPrefs: ASRouterPreferences.getAllUserPreferences(),
+ targetingParameters,
+ errors: this.errors,
+ }));
+ }
+
+ getMessageById(id) {
+ return this.state.messages.find(message => message.id === id);
+ }
+
+ _loadLocalProviders() {
+ // If we're in ASR debug mode add the local test providers
+ if (ASRouterPreferences.devtoolsEnabled) {
+ this._localProviders = {
+ ...this._localProviders,
+ SnippetsTestMessageProvider,
+ PanelTestProvider,
+ };
+ }
+ }
+
+ /**
+ * Used by ASRouter Admin returns all ASRouterTargeting.Environment
+ * and ASRouter._getMessagesContext parameters and values
+ */
+ async getTargetingParameters(environment, localContext) {
+ const targetingParameters = {};
+ for (const param of Object.keys(environment)) {
+ targetingParameters[param] = await environment[param];
+ }
+ for (const param of Object.keys(localContext)) {
+ targetingParameters[param] = await localContext[param];
+ }
+
+ return targetingParameters;
+ }
+
+ _handleTargetingError(error, message) {
+ Cu.reportError(error);
+ this.dispatchCFRAction(
+ ac.ASRouterUserEvent({
+ message_id: message.id,
+ action: "asrouter_undesired_event",
+ event: "TARGETING_EXPRESSION_ERROR",
+ event_context: {},
+ })
+ );
+ }
+
+ // Return an object containing targeting parameters used to select messages
+ _getMessagesContext() {
+ const { messageImpressions, previousSessionEnd } = this.state;
+
+ return {
+ get messageImpressions() {
+ return messageImpressions;
+ },
+ get previousSessionEnd() {
+ return previousSessionEnd;
+ },
+ };
+ }
+
+ async evaluateExpression({ expression, context }) {
+ const targetingContext = new TargetingContext(context);
+ let evaluationStatus;
+ try {
+ evaluationStatus = {
+ result: await targetingContext.evalWithDefault(expression),
+ success: true,
+ };
+ } catch (e) {
+ evaluationStatus = { result: e.message, success: false };
+ }
+ return Promise.resolve({ evaluationStatus });
+ }
+
+ unblockAll() {
+ return this.setState({ messageBlockList: [] });
+ }
+
+ isUnblockedMessage(message) {
+ let { state } = this;
+ return (
+ !state.messageBlockList.includes(message.id) &&
+ (!message.campaign ||
+ !state.messageBlockList.includes(message.campaign)) &&
+ this.hasGroupsEnabled(message.groups) &&
+ !this.isExcludedByProvider(message)
+ );
+ }
+
+ // Work out if a message can be shown based on its and its provider's frequency caps.
+ isBelowFrequencyCaps(message) {
+ const { messageImpressions, groupImpressions } = this.state;
+ const impressionsForMessage = messageImpressions[message.id];
+
+ return (
+ this._isBelowItemFrequencyCap(
+ message,
+ impressionsForMessage,
+ MAX_MESSAGE_LIFETIME_CAP
+ ) &&
+ message.groups.every(messageGroup =>
+ this._isBelowItemFrequencyCap(
+ this.state.groups.find(({ id }) => id === messageGroup),
+ groupImpressions[messageGroup]
+ )
+ )
+ );
+ }
+
+ // Helper for isBelowFrecencyCaps - work out if the frequency cap for the given
+ // item has been exceeded or not
+ _isBelowItemFrequencyCap(item, impressions, maxLifetimeCap = Infinity) {
+ if (item && item.frequency && impressions && impressions.length) {
+ if (
+ item.frequency.lifetime &&
+ impressions.length >= Math.min(item.frequency.lifetime, maxLifetimeCap)
+ ) {
+ return false;
+ }
+ if (item.frequency.custom) {
+ const now = Date.now();
+ for (const setting of item.frequency.custom) {
+ let { period } = setting;
+ const impressionsInPeriod = impressions.filter(t => now - t < period);
+ if (impressionsInPeriod.length >= setting.cap) {
+ return false;
+ }
+ }
+ }
+ }
+ return true;
+ }
+
+ async _extraTemplateStrings(originalMessage) {
+ let extraTemplateStrings;
+ let localProvider = this._findProvider(originalMessage.provider);
+ if (localProvider && localProvider.getExtraAttributes) {
+ extraTemplateStrings = await localProvider.getExtraAttributes();
+ }
+
+ return extraTemplateStrings;
+ }
+
+ _findProvider(providerID) {
+ return this._localProviders[
+ this.state.providers.find(i => i.id === providerID).localProvider
+ ];
+ }
+
+ routeCFRMessage(message, browser, trigger, force = false) {
+ if (!message) {
+ return { message: {} };
+ }
+
+ switch (message.template) {
+ case "whatsnew_panel_message":
+ if (force) {
+ ToolbarPanelHub.forceShowMessage(browser, message);
+ }
+ break;
+ case "cfr_doorhanger":
+ case "milestone_message":
+ if (force) {
+ CFRPageActions.forceRecommendation(
+ browser,
+ message,
+ this.dispatchCFRAction
+ );
+ } else {
+ CFRPageActions.addRecommendation(
+ browser,
+ trigger.param && trigger.param.host,
+ message,
+ this.dispatchCFRAction
+ );
+ }
+ break;
+ case "cfr_urlbar_chiclet":
+ if (force) {
+ CFRPageActions.forceRecommendation(
+ browser,
+ message,
+ this.dispatchCFRAction
+ );
+ } else {
+ CFRPageActions.addRecommendation(
+ browser,
+ null,
+ message,
+ this.dispatchCFRAction
+ );
+ }
+ break;
+ case "fxa_bookmark_panel":
+ if (force) {
+ BookmarkPanelHub.forceShowMessage(browser, message);
+ }
+ break;
+ case "toolbar_badge":
+ ToolbarBadgeHub.registerBadgeNotificationListener(message, { force });
+ break;
+ case "update_action":
+ MomentsPageHub.executeAction(message);
+ break;
+ case "infobar":
+ InfoBar.showInfoBarMessage(browser, message, this.dispatchCFRAction);
+ break;
+ }
+
+ return { message };
+ }
+
+ addImpression(message) {
+ const groupsWithFrequency = this.state.groups.filter(
+ ({ frequency, id }) => frequency && message.groups.includes(id)
+ );
+ // We only need to store impressions for messages that have frequency, or
+ // that have providers that have frequency
+ if (message.frequency || groupsWithFrequency.length) {
+ const time = Date.now();
+ return this.setState(state => {
+ const messageImpressions = this._addImpressionForItem(
+ state,
+ message,
+ "messageImpressions",
+ time
+ );
+ let { groupImpressions } = this.state;
+ for (const group of groupsWithFrequency) {
+ groupImpressions = this._addImpressionForItem(
+ state,
+ group,
+ "groupImpressions",
+ time
+ );
+ }
+ return { messageImpressions, groupImpressions };
+ });
+ }
+ return Promise.resolve();
+ }
+
+ // Helper for addImpression - calculate the updated impressions object for the given
+ // item, then store it and return it
+ _addImpressionForItem(state, item, impressionsString, time) {
+ // The destructuring here is to avoid mutating existing objects in state as in redux
+ // (see https://redux.js.org/recipes/structuring-reducers/prerequisite-concepts#immutable-data-management)
+ const impressions = { ...state[impressionsString] };
+ if (item.frequency) {
+ impressions[item.id] = impressions[item.id]
+ ? [...impressions[item.id]]
+ : [];
+ impressions[item.id].push(time);
+ this._storage.set(impressionsString, impressions);
+ }
+ return impressions;
+ }
+
+ /**
+ * getLongestPeriod
+ *
+ * @param {obj} item Either an ASRouter message or an ASRouter provider
+ * @returns {int|null} if the item has custom frequency caps, the longest period found in the list of caps.
+ if the item has no custom frequency caps, null
+ * @memberof _ASRouter
+ */
+ getLongestPeriod(item) {
+ if (!item.frequency || !item.frequency.custom) {
+ return null;
+ }
+ return item.frequency.custom.sort((a, b) => b.period - a.period)[0].period;
+ }
+
+ /**
+ * cleanupImpressions - this function cleans up obsolete impressions whenever
+ * messages are refreshed or fetched. It will likely need to be more sophisticated in the future,
+ * but the current behaviour for when both message impressions and provider impressions are
+ * cleared is as follows (where `item` is either `message` or `provider`):
+ *
+ * 1. If the item id for a list of item impressions no longer exists in the ASRouter state, it
+ * will be cleared.
+ * 2. If the item has time-bound frequency caps but no lifetime cap, any item impressions older
+ * than the longest time period will be cleared.
+ */
+ cleanupImpressions() {
+ return this.setState(state => {
+ const messageImpressions = this._cleanupImpressionsForItems(
+ state,
+ state.messages,
+ "messageImpressions"
+ );
+ const groupImpressions = this._cleanupImpressionsForItems(
+ state,
+ state.groups,
+ "groupImpressions"
+ );
+ return { messageImpressions, groupImpressions };
+ });
+ }
+
+ /** _cleanupImpressionsForItems - Helper for cleanupImpressions - calculate the updated
+ /* impressions object for the given items, then store it and return it
+ *
+ * @param {obj} state Reference to ASRouter internal state
+ * @param {array} items Can be messages, providers or groups that we count impressions for
+ * @param {string} impressionsString Key name for entry in state where impressions are stored
+ */
+ _cleanupImpressionsForItems(state, items, impressionsString) {
+ const impressions = { ...state[impressionsString] };
+ let needsUpdate = false;
+ Object.keys(impressions).forEach(id => {
+ const [item] = items.filter(x => x.id === id);
+ // Don't keep impressions for items that no longer exist
+ if (!item || !item.frequency || !Array.isArray(impressions[id])) {
+ delete impressions[id];
+ needsUpdate = true;
+ return;
+ }
+ if (!impressions[id].length) {
+ return;
+ }
+ // If we don't want to store impressions older than the longest period
+ if (item.frequency.custom && !item.frequency.lifetime) {
+ const now = Date.now();
+ impressions[id] = impressions[id].filter(
+ t => now - t < this.getLongestPeriod(item)
+ );
+ needsUpdate = true;
+ }
+ });
+ if (needsUpdate) {
+ this._storage.set(impressionsString, impressions);
+ }
+ return impressions;
+ }
+
+ handleMessageRequest({
+ messages: candidates,
+ triggerId,
+ triggerParam,
+ triggerContext,
+ template,
+ provider,
+ ordered = false,
+ returnAll = false,
+ }) {
+ let shouldCache;
+ const messages =
+ candidates ||
+ this.state.messages.filter(m => {
+ if (provider && m.provider !== provider) {
+ return false;
+ }
+ if (template && m.template !== template) {
+ return false;
+ }
+ if (triggerId && !m.trigger) {
+ return false;
+ }
+ if (triggerId && m.trigger.id !== triggerId) {
+ return false;
+ }
+ if (!this.isUnblockedMessage(m)) {
+ return false;
+ }
+ if (!this.isBelowFrequencyCaps(m)) {
+ return false;
+ }
+
+ if (shouldCache !== false) {
+ shouldCache = JEXL_PROVIDER_CACHE.has(m.provider);
+ }
+
+ return true;
+ });
+
+ if (!messages.length) {
+ return returnAll ? messages : null;
+ }
+
+ const context = this._getMessagesContext();
+
+ // Find a message that matches the targeting context as well as the trigger context (if one is provided)
+ // If no trigger is provided, we should find a message WITHOUT a trigger property defined.
+ return ASRouterTargeting.findMatchingMessage({
+ messages,
+ trigger: triggerId && {
+ id: triggerId,
+ param: triggerParam,
+ context: triggerContext,
+ },
+ context,
+ onError: this._handleTargetingError,
+ ordered,
+ shouldCache,
+ returnAll,
+ });
+ }
+
+ setMessageById({ id, ...data }, force, browser) {
+ return this.routeCFRMessage(this.getMessageById(id), browser, data, force);
+ }
+
+ blockMessageById(idOrIds) {
+ const idsToBlock = Array.isArray(idOrIds) ? idOrIds : [idOrIds];
+
+ return this.setState(state => {
+ const messageBlockList = [...state.messageBlockList];
+ const messageImpressions = { ...state.messageImpressions };
+
+ idsToBlock.forEach(id => {
+ const message = state.messages.find(m => m.id === id);
+ const idToBlock = message && message.campaign ? message.campaign : id;
+ if (!messageBlockList.includes(idToBlock)) {
+ messageBlockList.push(idToBlock);
+ }
+
+ // When a message is blocked, its impressions should be cleared as well
+ delete messageImpressions[id];
+ });
+
+ this._storage.set("messageBlockList", messageBlockList);
+ this._storage.set("messageImpressions", messageImpressions);
+ return { messageBlockList, messageImpressions };
+ });
+ }
+
+ unblockMessageById(idOrIds) {
+ const idsToUnblock = Array.isArray(idOrIds) ? idOrIds : [idOrIds];
+
+ return this.setState(state => {
+ const messageBlockList = [...state.messageBlockList];
+ idsToUnblock
+ .map(id => state.messages.find(m => m.id === id))
+ // Remove all `id`s (or `campaign`s for snippets) from the message
+ // block list
+ .forEach(message => {
+ const idToUnblock =
+ message && message.campaign ? message.campaign : message.id;
+ messageBlockList.splice(messageBlockList.indexOf(idToUnblock), 1);
+ });
+
+ this._storage.set("messageBlockList", messageBlockList);
+ return { messageBlockList };
+ });
+ }
+
+ resetGroupsState() {
+ const newGroupImpressions = {};
+ for (let { id } of this.state.groups) {
+ newGroupImpressions[id] = [];
+ }
+ // Update storage
+ this._storage.set("groupImpressions", newGroupImpressions);
+ return this.setState(({ groups }) => ({
+ groupImpressions: newGroupImpressions,
+ }));
+ }
+
+ _validPreviewEndpoint(url) {
+ try {
+ const endpoint = new URL(url);
+ if (!this.ALLOWLIST_HOSTS[endpoint.host]) {
+ Cu.reportError(
+ `The preview URL host ${endpoint.host} is not in the list of allowed hosts.`
+ );
+ }
+ if (endpoint.protocol !== "https:") {
+ Cu.reportError("The URL protocol is not https.");
+ }
+ return (
+ endpoint.protocol === "https:" && this.ALLOWLIST_HOSTS[endpoint.host]
+ );
+ } catch (e) {
+ return false;
+ }
+ }
+
+ // Ensure we switch to the Onboarding message after RTAMO addon was installed
+ _updateOnboardingState() {
+ let addonInstallObs = (subject, topic) => {
+ Services.obs.removeObserver(
+ addonInstallObs,
+ "webextension-install-notify"
+ );
+ };
+ Services.obs.addObserver(addonInstallObs, "webextension-install-notify");
+ }
+
+ _loadSnippetsAllowHosts() {
+ let additionalHosts = [];
+ const allowPrefValue = Services.prefs.getStringPref(
+ SNIPPETS_ENDPOINT_ALLOWLIST,
+ ""
+ );
+ try {
+ additionalHosts = JSON.parse(allowPrefValue);
+ } catch (e) {
+ if (allowPrefValue) {
+ Cu.reportError(
+ `Pref ${SNIPPETS_ENDPOINT_ALLOWLIST} value is not valid JSON`
+ );
+ }
+ }
+
+ if (!additionalHosts.length) {
+ return DEFAULT_ALLOWLIST_HOSTS;
+ }
+
+ // If there are additional hosts we want to allow, add them as
+ // `preview` so that the updateCycle is 0
+ return additionalHosts.reduce(
+ (allow_hosts, host) => {
+ allow_hosts[host] = "preview";
+ Services.console.logStringMessage(
+ `Adding ${host} to list of allowed hosts.`
+ );
+ return allow_hosts;
+ },
+ { ...DEFAULT_ALLOWLIST_HOSTS }
+ );
+ }
+
+ // To be passed to ASRouterTriggerListeners
+ _triggerHandler(browser, trigger) {
+ // Disable ASRouterTriggerListeners in kiosk mode.
+ if (BrowserHandler.kiosk) {
+ return Promise.resolve();
+ }
+ return this.sendTriggerMessage({ ...trigger, browser });
+ }
+
+ _removePreviewEndpoint(state) {
+ state.providers = state.providers.filter(p => p.id !== "preview");
+ return state;
+ }
+
+ addPreviewEndpoint(url, browser) {
+ const providers = [...this.state.providers];
+ if (
+ this._validPreviewEndpoint(url) &&
+ !providers.find(p => p.url === url)
+ ) {
+ // When you view a preview snippet we want to hide all real content -
+ // sending EnterSnippetsPreviewMode puts this browser tab in that state.
+ browser.sendMessageToActor("EnterSnippetsPreviewMode", {}, "ASRouter");
+ providers.push({
+ id: "preview",
+ type: "remote",
+ enabled: true,
+ url,
+ updateCycleInMs: 0,
+ });
+ return this.setState({ providers });
+ }
+ return Promise.resolve();
+ }
+
+ /**
+ * forceAttribution - this function should only be called from within about:newtab#asrouter.
+ * It forces the browser attribution to be set to something specified in asrouter admin
+ * tools, and reloads the providers in order to get messages that are dependant on this
+ * attribution data (see Return to AMO flow in bug 1475354 for example). Note - OSX and Windows only
+ * @param {data} Object an object containing the attribtion data that came from asrouter admin page
+ */
+ async forceAttribution(data) {
+ // Extract the parameters from data that will make up the referrer url
+ const attributionData = AttributionCode.allowedCodeKeys
+ .map(key => `${key}=${encodeURIComponent(data[key] || "")}`)
+ .join("&");
+ if (AppConstants.platform === "win") {
+ // The whole attribution data is encoded (again) for windows
+ await AttributionCode.writeAttributionFile(
+ encodeURIComponent(attributionData)
+ );
+ } else if (AppConstants.platform === "macosx") {
+ let appPath = MacAttribution.applicationPath;
+ let attributionSvc = Cc["@mozilla.org/mac-attribution;1"].getService(
+ Ci.nsIMacAttributionService
+ );
+
+ // The attribution data is treated as a url query for mac
+ let referrer = `https://www.mozilla.org/anything/?${attributionData}`;
+
+ // This sets the Attribution to be the referrer
+ attributionSvc.setReferrerUrl(appPath, referrer, true);
+
+ // Delete attribution data file
+ await AttributionCode.deleteFileAsync();
+ }
+
+ // Clear cache call is only possible in a testing environment
+ let env = Cc["@mozilla.org/process/environment;1"].getService(
+ Ci.nsIEnvironment
+ );
+ env.set("XPCSHELL_TEST_PROFILE_DIR", "testing");
+
+ // Clear and refresh Attribution, and then fetch the messages again to update
+ AttributionCode._clearCache();
+ await AttributionCode.getAttrDataAsync();
+ await this._updateMessageProviders();
+ return this.loadMessagesFromAllProviders();
+ }
+
+ async sendNewTabMessage({ endpoint, tabId, browser }) {
+ let message;
+
+ // Load preview endpoint for snippets if one is sent
+ if (endpoint) {
+ await this.addPreviewEndpoint(endpoint.url, browser);
+ }
+
+ // Load all messages
+ await this.loadMessagesFromAllProviders();
+
+ if (endpoint) {
+ message = await this.handleMessageRequest({ provider: "preview" });
+
+ // We don't want to cache preview messages, remove them after we selected the message to show
+ if (message) {
+ await this.setState(state => ({
+ messages: state.messages.filter(m => m.id !== message.id),
+ }));
+ }
+ } else {
+ const telemetryObject = { tabId };
+ TelemetryStopwatch.start("MS_MESSAGE_REQUEST_TIME_MS", telemetryObject);
+ message = await this.handleMessageRequest({ provider: "snippets" });
+ TelemetryStopwatch.finish("MS_MESSAGE_REQUEST_TIME_MS", telemetryObject);
+ }
+
+ return this.routeCFRMessage(message, browser, undefined, false);
+ }
+
+ _recordReachEvent(message) {
+ const messageGroup = message.forReachEvent.group;
+ // Events telemetry only accepts understores for the event `object`
+ const underscored = messageGroup.split("-").join("_");
+ const extra = { branches: message.branchSlug };
+ Services.telemetry.recordEvent(
+ REACH_EVENT_CATEGORY,
+ REACH_EVENT_METHOD,
+ underscored,
+ message.experimentSlug,
+ extra
+ );
+ }
+
+ async sendTriggerMessage({ tabId, browser, ...trigger }) {
+ await this.loadMessagesFromAllProviders();
+
+ const telemetryObject = { tabId };
+ TelemetryStopwatch.start("MS_MESSAGE_REQUEST_TIME_MS", telemetryObject);
+ // Return all the messages so that it can record the Reach event
+ const messages =
+ (await this.handleMessageRequest({
+ triggerId: trigger.id,
+ triggerParam: trigger.param,
+ triggerContext: trigger.context,
+ returnAll: true,
+ })) || [];
+ TelemetryStopwatch.finish("MS_MESSAGE_REQUEST_TIME_MS", telemetryObject);
+
+ // Record the Reach event for all the messages with `forReachEvent`,
+ // only send the first message without forReachEvent to the target
+ const nonReachMessages = [];
+ for (const message of messages) {
+ if (message.forReachEvent) {
+ if (!message.forReachEvent.sent) {
+ this._recordReachEvent(message);
+ message.forReachEvent.sent = true;
+ }
+ } else {
+ nonReachMessages.push(message);
+ }
+ }
+
+ // Exposure events only apply to messages that come from the
+ // messaging-experiments provider
+ if (nonReachMessages.length && nonReachMessages[0].forExposureEvent) {
+ ExperimentAPI.recordExposureEvent(
+ // Any message processed by ASRouter will report the exposure event
+ // as `cfr`
+ "cfr",
+ nonReachMessages[0].forExposureEvent
+ );
+ }
+
+ return this.routeCFRMessage(
+ nonReachMessages[0] || null,
+ browser,
+ trigger,
+ false
+ );
+ }
+
+ async forceWNPanel(browser) {
+ let win = browser.ownerGlobal;
+ await ToolbarPanelHub.enableToolbarButton();
+
+ win.PanelUI.showSubView(
+ "PanelUI-whatsNew",
+ win.document.getElementById("whats-new-menu-button")
+ );
+
+ let panel = win.document.getElementById("customizationui-widget-panel");
+ // Set the attribute to keep the panel open
+ panel.setAttribute("noautohide", true);
+ }
+
+ async closeWNPanel(browser) {
+ let win = browser.ownerGlobal;
+ let panel = win.document.getElementById("customizationui-widget-panel");
+ // Set the attribute to allow the panel to close
+ panel.setAttribute("noautohide", false);
+ // Removing the button is enough to close the panel.
+ await ToolbarPanelHub._hideToolbarButton(win);
+ }
+}
+this._ASRouter = _ASRouter;
+
+/**
+ * ASRouter - singleton instance of _ASRouter that controls all messages
+ * in the new tab page.
+ */
+this.ASRouter = new _ASRouter();
+
+const EXPORTED_SYMBOLS = ["_ASRouter", "ASRouter", "MessageLoaderUtils"];
diff --git a/browser/components/newtab/lib/ASRouterDefaultConfig.jsm b/browser/components/newtab/lib/ASRouterDefaultConfig.jsm
new file mode 100644
index 0000000000..6caff6f4a2
--- /dev/null
+++ b/browser/components/newtab/lib/ASRouterDefaultConfig.jsm
@@ -0,0 +1,65 @@
+/* vim: set ts=2 sw=2 sts=2 et tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+const EXPORTED_SYMBOLS = ["ASRouterDefaultConfig"];
+
+const { ASRouter } = ChromeUtils.import(
+ "resource://activity-stream/lib/ASRouter.jsm"
+);
+const { TelemetryFeed } = ChromeUtils.import(
+ "resource://activity-stream/lib/TelemetryFeed.jsm"
+);
+const { ASRouterParentProcessMessageHandler } = ChromeUtils.import(
+ "resource://activity-stream/lib/ASRouterParentProcessMessageHandler.jsm"
+);
+const { SpecialMessageActions } = ChromeUtils.import(
+ "resource://messaging-system/lib/SpecialMessageActions.jsm"
+);
+const { ASRouterPreferences } = ChromeUtils.import(
+ "resource://activity-stream/lib/ASRouterPreferences.jsm"
+);
+const { QueryCache } = ChromeUtils.import(
+ "resource://activity-stream/lib/ASRouterTargeting.jsm"
+);
+const { ActivityStreamStorage } = ChromeUtils.import(
+ "resource://activity-stream/lib/ActivityStreamStorage.jsm"
+);
+
+const createStorage = async telemetryFeed => {
+ const dbStore = new ActivityStreamStorage({
+ storeNames: ["sectionPrefs", "snippets"],
+ telemetry: {
+ handleUndesiredEvent: e => telemetryFeed.SendASRouterUndesiredEvent(e),
+ },
+ });
+ // Accessing the db causes the object stores to be created / migrated.
+ // This needs to happen before other instances try to access the db, which
+ // would update only a subset of the stores to the latest version.
+ try {
+ await dbStore.db; // eslint-disable-line no-unused-expressions
+ } catch (e) {
+ return Promise.reject(e);
+ }
+ return dbStore.getDbTable("snippets");
+};
+
+const ASRouterDefaultConfig = () => {
+ const router = ASRouter;
+ const telemetry = new TelemetryFeed();
+ const messageHandler = new ASRouterParentProcessMessageHandler({
+ router,
+ preferences: ASRouterPreferences,
+ specialMessageActions: SpecialMessageActions,
+ queryCache: QueryCache,
+ sendTelemetry: telemetry.onAction.bind(telemetry),
+ });
+ return {
+ router,
+ messageHandler,
+ createStorage: createStorage.bind(null, telemetry),
+ };
+};
diff --git a/browser/components/newtab/lib/ASRouterNewTabHook.jsm b/browser/components/newtab/lib/ASRouterNewTabHook.jsm
new file mode 100644
index 0000000000..779dc4f5c5
--- /dev/null
+++ b/browser/components/newtab/lib/ASRouterNewTabHook.jsm
@@ -0,0 +1,122 @@
+/* vim: set ts=2 sw=2 sts=2 et tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
+const EXPORTED_SYMBOLS = ["ASRouterNewTabHook"];
+
+class ASRouterNewTabHookInstance {
+ constructor() {
+ this._newTabMessageHandler = null;
+ this._parentProcessMessageHandler = null;
+ this._router = null;
+ this._clearChildMessages = (...params) =>
+ this._newTabMessageHandler === null
+ ? Promise.resolve()
+ : this._newTabMessageHandler.clearChildMessages(...params);
+ this._clearChildProviders = (...params) =>
+ this._newTabMessageHandler === null
+ ? Promise.resolve()
+ : this._newTabMessageHandler.clearChildProviders(...params);
+ this._updateAdminState = (...params) =>
+ this._newTabMessageHandler === null
+ ? Promise.resolve()
+ : this._newTabMessageHandler.updateAdminState(...params);
+ }
+
+ /**
+ * Params:
+ * object - {
+ * messageHandler: message handler for parent process messages
+ * {
+ * handleCFRAction: Responds to CFR action and returns a Promise
+ * handleTelemetry: Logs telemetry events and returns nothing
+ * },
+ * router: ASRouter instance
+ * createStorage: function to create DB storage for ASRouter
+ * }
+ */
+ async initialize({ messageHandler, router, createStorage }) {
+ this._parentProcessMessageHandler = messageHandler;
+ this._router = router;
+ if (!this._router.initialized) {
+ const storage = await createStorage();
+ await this._router.init({
+ storage,
+ sendTelemetry: this._parentProcessMessageHandler.handleTelemetry,
+ dispatchCFRAction: this._parentProcessMessageHandler.handleCFRAction,
+ clearChildMessages: this._clearChildMessages,
+ clearChildProviders: this._clearChildProviders,
+ updateAdminState: this._updateAdminState,
+ });
+ }
+ }
+
+ /**
+ * Note: Should only ever be called on an initialized instance
+ */
+ destroy() {
+ this.disconnect();
+ this._router.uninit();
+ }
+
+ /**
+ * Connects new tab message handler to hook.
+ * Note: Should only ever be called on an initialized instance
+ * Params:
+ * newTabMessageHandler - {
+ * clearChildMessages: clears child messages and returns Promise
+ * clearChildProviders: clears child providers and returns Promise.
+ * updateAdminState: updates admin state and returns Promise
+ * }
+ * Returns: parentProcessMessageHandler
+ */
+ connect(newTabMessageHandler) {
+ this._newTabMessageHandler = newTabMessageHandler;
+ return this._parentProcessMessageHandler;
+ }
+
+ /**
+ * Disconnects new tab message handler from hook.
+ * Note: Should only ever be called on an initialized instance
+ */
+ disconnect() {
+ this._newTabMessageHandler = null;
+ }
+}
+
+class AwaitSingleton {
+ constructor() {
+ this.instance = null;
+ const initialized = new Promise(resolve => {
+ this.setInstance = instance => {
+ this.setInstance = () => {};
+ this.instance = instance;
+ resolve(instance);
+ };
+ });
+ this.getInstance = () => initialized;
+ }
+}
+
+const ASRouterNewTabHook = (() => {
+ const singleton = new AwaitSingleton();
+ const instance = new ASRouterNewTabHookInstance();
+ return {
+ getInstance: singleton.getInstance,
+
+ /**
+ * Param:
+ * params - see ASRouterNewTabHookInstance.init
+ */
+ createInstance: async params => {
+ await instance.initialize(params);
+ singleton.setInstance(instance);
+ },
+
+ destroy: () => {
+ instance.destroy();
+ },
+ };
+})();
diff --git a/browser/components/newtab/lib/ASRouterParentProcessMessageHandler.jsm b/browser/components/newtab/lib/ASRouterParentProcessMessageHandler.jsm
new file mode 100644
index 0000000000..a3be564b7f
--- /dev/null
+++ b/browser/components/newtab/lib/ASRouterParentProcessMessageHandler.jsm
@@ -0,0 +1,161 @@
+/* vim: set ts=2 sw=2 sts=2 et tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+const EXPORTED_SYMBOLS = ["ASRouterParentProcessMessageHandler"];
+
+const { MESSAGE_TYPE_HASH: msg } = ChromeUtils.import(
+ "resource://activity-stream/common/ActorConstants.jsm"
+);
+
+class ASRouterParentProcessMessageHandler {
+ constructor({
+ router,
+ preferences,
+ specialMessageActions,
+ queryCache,
+ sendTelemetry,
+ }) {
+ this._router = router;
+ this._preferences = preferences;
+ this._specialMessageActions = specialMessageActions;
+ this._queryCache = queryCache;
+ this.handleTelemetry = sendTelemetry;
+ this.handleMessage = this.handleMessage.bind(this);
+ this.handleCFRAction = this.handleCFRAction.bind(this);
+ }
+
+ handleCFRAction({ type, data }, browser) {
+ switch (type) {
+ case msg.INFOBAR_TELEMETRY:
+ case msg.TOOLBAR_BADGE_TELEMETRY:
+ case msg.TOOLBAR_PANEL_TELEMETRY:
+ case msg.MOMENTS_PAGE_TELEMETRY:
+ case msg.DOORHANGER_TELEMETRY: {
+ return this.handleTelemetry({ type, data });
+ }
+ default: {
+ return this.handleMessage(type, data, { browser });
+ }
+ }
+ }
+
+ handleMessage(name, data, { id: tabId, browser } = { browser: null }) {
+ switch (name) {
+ case msg.AS_ROUTER_TELEMETRY_USER_EVENT:
+ return this.handleTelemetry({
+ type: msg.AS_ROUTER_TELEMETRY_USER_EVENT,
+ data,
+ });
+ case msg.BLOCK_MESSAGE_BY_ID: {
+ // Block the message but don't dismiss it in case the action taken has
+ // another state that needs to be visible
+ return this._router
+ .blockMessageById(data.id)
+ .then(() => !data.preventDismiss);
+ }
+ case msg.USER_ACTION: {
+ // This is to support ReturnToAMO
+ if (data.type === "INSTALL_ADDON_FROM_URL") {
+ this._router._updateOnboardingState();
+ }
+ return this._specialMessageActions.handleAction(data, browser);
+ }
+ case msg.IMPRESSION: {
+ return this._router.addImpression(data);
+ }
+ case msg.TRIGGER: {
+ return this._router.sendTriggerMessage({
+ ...(data && data.trigger),
+ tabId,
+ browser,
+ });
+ }
+ case msg.NEWTAB_MESSAGE_REQUEST: {
+ return this._router.sendNewTabMessage({
+ ...data,
+ tabId,
+ browser,
+ });
+ }
+
+ // ADMIN Messages
+ case msg.ADMIN_CONNECT_STATE: {
+ if (data && data.endpoint) {
+ return this._router
+ .addPreviewEndpoint(data.endpoint.url)
+ .then(() => this._router.loadMessagesFromAllProviders());
+ }
+ return this._router.updateTargetingParameters();
+ }
+ case msg.UNBLOCK_MESSAGE_BY_ID: {
+ return this._router.unblockMessageById(data.id);
+ }
+ case msg.UNBLOCK_ALL: {
+ return this._router.unblockAll();
+ }
+ case msg.BLOCK_BUNDLE: {
+ return this._router.blockMessageById(data.bundle.map(b => b.id));
+ }
+ case msg.UNBLOCK_BUNDLE: {
+ return this._router.setState(state => {
+ const messageBlockList = [...state.messageBlockList];
+ for (let message of data.bundle) {
+ messageBlockList.splice(messageBlockList.indexOf(message.id), 1);
+ }
+ this._router._storage.set("messageBlockList", messageBlockList);
+ return { messageBlockList };
+ });
+ }
+ case msg.DISABLE_PROVIDER: {
+ this._preferences.enableOrDisableProvider(data, false);
+ return Promise.resolve();
+ }
+ case msg.ENABLE_PROVIDER: {
+ this._preferences.enableOrDisableProvider(data, true);
+ return Promise.resolve();
+ }
+ case msg.EVALUATE_JEXL_EXPRESSION: {
+ return this._router.evaluateExpression(data);
+ }
+ case msg.EXPIRE_QUERY_CACHE: {
+ this._queryCache.expireAll();
+ return Promise.resolve();
+ }
+ case msg.FORCE_ATTRIBUTION: {
+ return this._router.forceAttribution(data);
+ }
+ case msg.FORCE_WHATSNEW_PANEL: {
+ return this._router.forceWNPanel(browser);
+ }
+ case msg.CLOSE_WHATSNEW_PANEL: {
+ return this._router.closeWNPanel(browser);
+ }
+ case msg.MODIFY_MESSAGE_JSON: {
+ return this._router.sendMessage(data.content, data, true, browser);
+ }
+ case msg.OVERRIDE_MESSAGE: {
+ return this._router.setMessageById(data, true, browser);
+ }
+ case msg.RESET_PROVIDER_PREF: {
+ this._preferences.resetProviderPref();
+ return Promise.resolve();
+ }
+ case msg.SET_PROVIDER_USER_PREF: {
+ this._preferences.setUserPreference(data.id, data.value);
+ return Promise.resolve();
+ }
+ case msg.RESET_GROUPS_STATE: {
+ return this._router
+ .resetGroupsState(data)
+ .then(() => this._router.loadMessagesFromAllProviders());
+ }
+ default: {
+ return Promise.reject(new Error(`Unknown message received: ${name}`));
+ }
+ }
+ }
+}
diff --git a/browser/components/newtab/lib/ASRouterPreferences.jsm b/browser/components/newtab/lib/ASRouterPreferences.jsm
new file mode 100644
index 0000000000..a992802a77
--- /dev/null
+++ b/browser/components/newtab/lib/ASRouterPreferences.jsm
@@ -0,0 +1,228 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
+const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
+const { XPCOMUtils } = ChromeUtils.import(
+ "resource://gre/modules/XPCOMUtils.jsm"
+);
+
+const PROVIDER_PREF_BRANCH =
+ "browser.newtabpage.activity-stream.asrouter.providers.";
+const DEVTOOLS_PREF =
+ "browser.newtabpage.activity-stream.asrouter.devtoolsEnabled";
+const FXA_USERNAME_PREF = "services.sync.username";
+
+const DEFAULT_STATE = {
+ _initialized: false,
+ _providers: null,
+ _providerPrefBranch: PROVIDER_PREF_BRANCH,
+ _devtoolsEnabled: null,
+ _devtoolsPref: DEVTOOLS_PREF,
+};
+
+const USER_PREFERENCES = {
+ snippets: "browser.newtabpage.activity-stream.feeds.snippets",
+ cfrAddons: "browser.newtabpage.activity-stream.asrouter.userprefs.cfr.addons",
+ cfrFeatures:
+ "browser.newtabpage.activity-stream.asrouter.userprefs.cfr.features",
+};
+
+// Preferences that influence targeting attributes. When these change we need
+// to re-evaluate if the message targeting still matches
+const TARGETING_PREFERENCES = [FXA_USERNAME_PREF];
+
+const TEST_PROVIDERS = [
+ {
+ id: "snippets_local_testing",
+ type: "local",
+ localProvider: "SnippetsTestMessageProvider",
+ enabled: true,
+ },
+ {
+ id: "panel_local_testing",
+ type: "local",
+ localProvider: "PanelTestProvider",
+ enabled: true,
+ },
+];
+
+class _ASRouterPreferences {
+ constructor() {
+ Object.assign(this, DEFAULT_STATE);
+ this._callbacks = new Set();
+
+ XPCOMUtils.defineLazyPreferenceGetter(
+ this,
+ "personalizedCfrScores",
+ "browser.messaging-system.personalized-cfr.scores",
+ "{}",
+ null,
+ this._transformPersonalizedCfrScores
+ );
+
+ XPCOMUtils.defineLazyPreferenceGetter(
+ this,
+ "personalizedCfrThreshold",
+ "browser.messaging-system.personalized-cfr.score-threshold",
+ 5000
+ );
+ }
+
+ _transformPersonalizedCfrScores(value) {
+ let result = {};
+ try {
+ result = JSON.parse(value);
+ } catch (e) {
+ Cu.reportError(e);
+ }
+ return result;
+ }
+
+ _getProviderConfig() {
+ const prefList = Services.prefs.getChildList(this._providerPrefBranch);
+ return prefList.reduce((filtered, pref) => {
+ let value;
+ try {
+ value = JSON.parse(Services.prefs.getStringPref(pref, ""));
+ } catch (e) {
+ Cu.reportError(
+ `Could not parse ASRouter preference. Try resetting ${pref} in about:config.`
+ );
+ }
+ if (value) {
+ filtered.push(value);
+ }
+ return filtered;
+ }, []);
+ }
+
+ get providers() {
+ if (!this._initialized || this._providers === null) {
+ const config = this._getProviderConfig();
+ const providers = config.map(provider => Object.freeze(provider));
+ if (this.devtoolsEnabled) {
+ providers.unshift(...TEST_PROVIDERS);
+ }
+ this._providers = Object.freeze(providers);
+ }
+
+ return this._providers;
+ }
+
+ enableOrDisableProvider(id, value) {
+ const providers = this._getProviderConfig();
+ const config = providers.find(p => p.id === id);
+ if (!config) {
+ Cu.reportError(
+ `Cannot set enabled state for '${id}' because the pref ${this._providerPrefBranch}${id} does not exist or is not correctly formatted.`
+ );
+ return;
+ }
+
+ Services.prefs.setStringPref(
+ this._providerPrefBranch + id,
+ JSON.stringify({ ...config, enabled: value })
+ );
+ }
+
+ resetProviderPref() {
+ for (const pref of Services.prefs.getChildList(this._providerPrefBranch)) {
+ Services.prefs.clearUserPref(pref);
+ }
+ for (const id of Object.keys(USER_PREFERENCES)) {
+ Services.prefs.clearUserPref(USER_PREFERENCES[id]);
+ }
+ }
+
+ get devtoolsEnabled() {
+ if (!this._initialized || this._devtoolsEnabled === null) {
+ this._devtoolsEnabled = Services.prefs.getBoolPref(
+ this._devtoolsPref,
+ false
+ );
+ }
+ return this._devtoolsEnabled;
+ }
+
+ observe(aSubject, aTopic, aPrefName) {
+ if (aPrefName && aPrefName.startsWith(this._providerPrefBranch)) {
+ this._providers = null;
+ } else if (aPrefName === this._devtoolsPref) {
+ this._providers = null;
+ this._devtoolsEnabled = null;
+ }
+ this._callbacks.forEach(cb => cb(aPrefName));
+ }
+
+ getUserPreference(name) {
+ const prefName = USER_PREFERENCES[name] || name;
+ return Services.prefs.getBoolPref(prefName, true);
+ }
+
+ getAllUserPreferences() {
+ const values = {};
+ for (const id of Object.keys(USER_PREFERENCES)) {
+ values[id] = this.getUserPreference(id);
+ }
+ return values;
+ }
+
+ setUserPreference(providerId, value) {
+ if (!USER_PREFERENCES[providerId]) {
+ return;
+ }
+ Services.prefs.setBoolPref(USER_PREFERENCES[providerId], value);
+ }
+
+ addListener(callback) {
+ this._callbacks.add(callback);
+ }
+
+ removeListener(callback) {
+ this._callbacks.delete(callback);
+ }
+
+ init() {
+ if (this._initialized) {
+ return;
+ }
+ Services.prefs.addObserver(this._providerPrefBranch, this);
+ Services.prefs.addObserver(this._devtoolsPref, this);
+ for (const id of Object.keys(USER_PREFERENCES)) {
+ Services.prefs.addObserver(USER_PREFERENCES[id], this);
+ }
+ for (const targetingPref of TARGETING_PREFERENCES) {
+ Services.prefs.addObserver(targetingPref, this);
+ }
+ this._initialized = true;
+ }
+
+ uninit() {
+ if (this._initialized) {
+ Services.prefs.removeObserver(this._providerPrefBranch, this);
+ Services.prefs.removeObserver(this._devtoolsPref, this);
+ for (const id of Object.keys(USER_PREFERENCES)) {
+ Services.prefs.removeObserver(USER_PREFERENCES[id], this);
+ }
+ for (const targetingPref of TARGETING_PREFERENCES) {
+ Services.prefs.removeObserver(targetingPref, this);
+ }
+ }
+ Object.assign(this, DEFAULT_STATE);
+ this._callbacks.clear();
+ }
+}
+this._ASRouterPreferences = _ASRouterPreferences;
+
+this.ASRouterPreferences = new _ASRouterPreferences();
+this.TEST_PROVIDERS = TEST_PROVIDERS;
+this.TARGETING_PREFERENCES = TARGETING_PREFERENCES;
+
+const EXPORTED_SYMBOLS = [
+ "_ASRouterPreferences",
+ "ASRouterPreferences",
+ "TEST_PROVIDERS",
+ "TARGETING_PREFERENCES",
+];
diff --git a/browser/components/newtab/lib/ASRouterTargeting.jsm b/browser/components/newtab/lib/ASRouterTargeting.jsm
new file mode 100644
index 0000000000..8546c0685c
--- /dev/null
+++ b/browser/components/newtab/lib/ASRouterTargeting.jsm
@@ -0,0 +1,837 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+const FXA_ENABLED_PREF = "identity.fxaccounts.enabled";
+const DISTRIBUTION_ID_PREF = "distribution.id";
+const DISTRIBUTION_ID_CHINA_REPACK = "MozillaOnline";
+
+const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
+const { XPCOMUtils } = ChromeUtils.import(
+ "resource://gre/modules/XPCOMUtils.jsm"
+);
+
+XPCOMUtils.defineLazyModuleGetters(this, {
+ ASRouterPreferences: "resource://activity-stream/lib/ASRouterPreferences.jsm",
+ AddonManager: "resource://gre/modules/AddonManager.jsm",
+ ClientEnvironment: "resource://normandy/lib/ClientEnvironment.jsm",
+ NewTabUtils: "resource://gre/modules/NewTabUtils.jsm",
+ ProfileAge: "resource://gre/modules/ProfileAge.jsm",
+ ShellService: "resource:///modules/ShellService.jsm",
+ TelemetryEnvironment: "resource://gre/modules/TelemetryEnvironment.jsm",
+ AppConstants: "resource://gre/modules/AppConstants.jsm",
+ AttributionCode: "resource:///modules/AttributionCode.jsm",
+ TargetingContext: "resource://messaging-system/targeting/Targeting.jsm",
+ fxAccounts: "resource://gre/modules/FxAccounts.jsm",
+ Region: "resource://gre/modules/Region.jsm",
+ TelemetrySession: "resource://gre/modules/TelemetrySession.jsm",
+ HomePage: "resource:///modules/HomePage.jsm",
+ AboutNewTab: "resource:///modules/AboutNewTab.jsm",
+ BrowserWindowTracker: "resource:///modules/BrowserWindowTracker.jsm",
+});
+
+XPCOMUtils.defineLazyPreferenceGetter(
+ this,
+ "cfrFeaturesUserPref",
+ "browser.newtabpage.activity-stream.asrouter.userprefs.cfr.features",
+ true
+);
+XPCOMUtils.defineLazyPreferenceGetter(
+ this,
+ "cfrAddonsUserPref",
+ "browser.newtabpage.activity-stream.asrouter.userprefs.cfr.addons",
+ true
+);
+XPCOMUtils.defineLazyPreferenceGetter(
+ this,
+ "isWhatsNewPanelEnabled",
+ "browser.messaging-system.whatsNewPanel.enabled",
+ false
+);
+XPCOMUtils.defineLazyPreferenceGetter(
+ this,
+ "hasAccessedFxAPanel",
+ "identity.fxaccounts.toolbar.accessed",
+ false
+);
+XPCOMUtils.defineLazyPreferenceGetter(
+ this,
+ "clientsDevicesDesktop",
+ "services.sync.clients.devices.desktop",
+ 0
+);
+XPCOMUtils.defineLazyPreferenceGetter(
+ this,
+ "clientsDevicesMobile",
+ "services.sync.clients.devices.mobile",
+ 0
+);
+XPCOMUtils.defineLazyPreferenceGetter(
+ this,
+ "syncNumClients",
+ "services.sync.numClients",
+ 0
+);
+XPCOMUtils.defineLazyPreferenceGetter(
+ this,
+ "devtoolsSelfXSSCount",
+ "devtools.selfxss.count",
+ 0
+);
+XPCOMUtils.defineLazyPreferenceGetter(
+ this,
+ "isFxAEnabled",
+ FXA_ENABLED_PREF,
+ true
+);
+XPCOMUtils.defineLazyPreferenceGetter(
+ this,
+ "isXPIInstallEnabled",
+ "xpinstall.enabled",
+ true
+);
+XPCOMUtils.defineLazyPreferenceGetter(
+ this,
+ "snippetsUserPref",
+ "browser.newtabpage.activity-stream.feeds.snippets",
+ true
+);
+XPCOMUtils.defineLazyServiceGetter(
+ this,
+ "TrackingDBService",
+ "@mozilla.org/tracking-db-service;1",
+ "nsITrackingDBService"
+);
+
+const FXA_USERNAME_PREF = "services.sync.username";
+
+const { activityStreamProvider: asProvider } = NewTabUtils;
+
+const FXA_ATTACHED_CLIENTS_UPDATE_INTERVAL = 4 * 60 * 60 * 1000; // Four hours
+const FRECENT_SITES_UPDATE_INTERVAL = 6 * 60 * 60 * 1000; // Six hours
+const FRECENT_SITES_IGNORE_BLOCKED = false;
+const FRECENT_SITES_NUM_ITEMS = 25;
+const FRECENT_SITES_MIN_FRECENCY = 100;
+
+const CACHE_EXPIRATION = 5 * 60 * 1000;
+const jexlEvaluationCache = new Map();
+
+/**
+ * CachedTargetingGetter
+ * @param property {string} Name of the method called on ActivityStreamProvider
+ * @param options {{}?} Options object passsed to ActivityStreamProvider method
+ * @param updateInterval {number?} Update interval for query. Defaults to FRECENT_SITES_UPDATE_INTERVAL
+ */
+function CachedTargetingGetter(
+ property,
+ options = null,
+ updateInterval = FRECENT_SITES_UPDATE_INTERVAL
+) {
+ return {
+ _lastUpdated: 0,
+ _value: null,
+ // For testing
+ expire() {
+ this._lastUpdated = 0;
+ this._value = null;
+ },
+ async get() {
+ const now = Date.now();
+ if (now - this._lastUpdated >= updateInterval) {
+ this._value = await asProvider[property](options);
+ this._lastUpdated = now;
+ }
+ return this._value;
+ },
+ };
+}
+
+function CacheListAttachedOAuthClients() {
+ return {
+ _lastUpdated: 0,
+ _value: null,
+ expire() {
+ this._lastUpdated = 0;
+ this._value = null;
+ },
+ get() {
+ const now = Date.now();
+ if (now - this._lastUpdated >= FXA_ATTACHED_CLIENTS_UPDATE_INTERVAL) {
+ this._value = new Promise(resolve => {
+ fxAccounts
+ .listAttachedOAuthClients()
+ .then(clients => {
+ resolve(clients);
+ })
+ .catch(() => resolve([]));
+ });
+ this._lastUpdated = now;
+ }
+ return this._value;
+ },
+ };
+}
+
+function CheckBrowserNeedsUpdate(
+ updateInterval = FRECENT_SITES_UPDATE_INTERVAL
+) {
+ const UpdateChecker = Cc["@mozilla.org/updates/update-checker;1"];
+ const checker = {
+ _lastUpdated: 0,
+ _value: null,
+ // For testing. Avoid update check network call.
+ setUp(value) {
+ this._lastUpdated = Date.now();
+ this._value = value;
+ },
+ expire() {
+ this._lastUpdated = 0;
+ this._value = null;
+ },
+ get() {
+ return new Promise((resolve, reject) => {
+ const now = Date.now();
+ const updateServiceListener = {
+ onCheckComplete(request, updates) {
+ checker._value = !!updates.length;
+ resolve(checker._value);
+ },
+ onError(request, update) {
+ reject(request);
+ },
+
+ QueryInterface: ChromeUtils.generateQI(["nsIUpdateCheckListener"]),
+ };
+
+ if (UpdateChecker && now - this._lastUpdated >= updateInterval) {
+ const checkerInstance = UpdateChecker.createInstance(
+ Ci.nsIUpdateChecker
+ );
+ checkerInstance.checkForUpdates(updateServiceListener, true);
+ this._lastUpdated = now;
+ } else {
+ resolve(this._value);
+ }
+ });
+ },
+ };
+
+ return checker;
+}
+
+const QueryCache = {
+ expireAll() {
+ Object.keys(this.queries).forEach(query => {
+ this.queries[query].expire();
+ });
+ },
+ queries: {
+ TopFrecentSites: new CachedTargetingGetter("getTopFrecentSites", {
+ ignoreBlocked: FRECENT_SITES_IGNORE_BLOCKED,
+ numItems: FRECENT_SITES_NUM_ITEMS,
+ topsiteFrecency: FRECENT_SITES_MIN_FRECENCY,
+ onePerDomain: true,
+ includeFavicon: false,
+ }),
+ TotalBookmarksCount: new CachedTargetingGetter("getTotalBookmarksCount"),
+ CheckBrowserNeedsUpdate: new CheckBrowserNeedsUpdate(),
+ RecentBookmarks: new CachedTargetingGetter("getRecentBookmarks"),
+ ListAttachedOAuthClients: new CacheListAttachedOAuthClients(),
+ },
+};
+
+/**
+ * sortMessagesByWeightedRank
+ *
+ * Each message has an associated weight, which is guaranteed to be strictly
+ * positive. Sort the messages so that higher weighted messages are more likely
+ * to come first.
+ *
+ * Specifically, sort them so that the probability of message x_1 with weight
+ * w_1 appearing before message x_2 with weight w_2 is (w_1 / (w_1 + w_2)).
+ *
+ * This is equivalent to requiring that x_1 appearing before x_2 is (w_1 / w_2)
+ * "times" as likely as x_2 appearing before x_1.
+ *
+ * See Bug 1484996, Comment 2 for a justification of the method.
+ *
+ * @param {Array} messages - A non-empty array of messages to sort, all with
+ * strictly positive weights
+ * @returns the sorted array
+ */
+function sortMessagesByWeightedRank(messages) {
+ return messages
+ .map(message => ({
+ message,
+ rank: Math.pow(Math.random(), 1 / message.weight),
+ }))
+ .sort((a, b) => b.rank - a.rank)
+ .map(({ message }) => message);
+}
+
+/**
+ * getSortedMessages - Given an array of Messages, applies sorting and filtering rules
+ * in expected order.
+ *
+ * @param {Array<Message>} messages
+ * @param {{}} options
+ * @param {boolean} options.ordered - Should .order be used instead of random weighted sorting?
+ * @returns {Array<Message>}
+ */
+function getSortedMessages(messages, options = {}) {
+ let { ordered } = { ordered: false, ...options };
+ let result = messages;
+ let hasScores;
+
+ if (!ordered) {
+ result = sortMessagesByWeightedRank(result);
+ }
+
+ result.sort((a, b) => {
+ // If we find at least one score, we need to apply filtering by threshold at the end.
+ if (!isNaN(a.score) || !isNaN(b.score)) {
+ hasScores = true;
+ }
+
+ // First sort by score if we're doing personalization:
+ if (a.score > b.score || (!isNaN(a.score) && isNaN(b.score))) {
+ return -1;
+ }
+ if (a.score < b.score || (isNaN(a.score) && !isNaN(b.score))) {
+ return 1;
+ }
+
+ // Next, sort by priority
+ if (a.priority > b.priority || (!isNaN(a.priority) && isNaN(b.priority))) {
+ return -1;
+ }
+ if (a.priority < b.priority || (isNaN(a.priority) && !isNaN(b.priority))) {
+ return 1;
+ }
+
+ // Sort messages with targeting expressions higher than those with none
+ if (a.targeting && !b.targeting) {
+ return -1;
+ }
+ if (!a.targeting && b.targeting) {
+ return 1;
+ }
+
+ // Next, sort by order *ascending* if ordered = true
+ if (ordered) {
+ if (a.order > b.order || (!isNaN(a.order) && isNaN(b.order))) {
+ return 1;
+ }
+ if (a.order < b.order || (isNaN(a.order) && !isNaN(b.order))) {
+ return -1;
+ }
+ }
+
+ return 0;
+ });
+
+ if (hasScores && !isNaN(ASRouterPreferences.personalizedCfrThreshold)) {
+ return result.filter(
+ message =>
+ isNaN(message.score) ||
+ message.score >= ASRouterPreferences.personalizedCfrThreshold
+ );
+ }
+
+ return result;
+}
+
+/**
+ * parseAboutPageURL - Parse a URL string retrieved from about:home and about:new, returns
+ * its type (web extenstion or custom url) and the parsed url(s)
+ *
+ * @param {string} url - A URL string for home page or newtab page
+ * @returns {Object} {
+ * isWebExt: boolean,
+ * isCustomUrl: boolean,
+ * urls: Array<{url: string, host: string}>
+ * }
+ */
+function parseAboutPageURL(url) {
+ let ret = {
+ isWebExt: false,
+ isCustomUrl: false,
+ urls: [],
+ };
+ if (url.startsWith("moz-extension://")) {
+ ret.isWebExt = true;
+ ret.urls.push({ url, host: "" });
+ } else {
+ // The home page URL could be either a single URL or a list of "|" separated URLs.
+ // Note that it should work with "about:home" and "about:blank", in which case the
+ // "host" is set as an empty string.
+ for (const _url of url.split("|")) {
+ if (!["about:home", "about:newtab", "about:blank"].includes(_url)) {
+ ret.isCustomUrl = true;
+ }
+ try {
+ const parsedURL = new URL(_url);
+ const host = parsedURL.hostname.replace(/^www\./i, "");
+ ret.urls.push({ url: _url, host });
+ } catch (e) {}
+ }
+ // If URL parsing failed, just return the given url with an empty host
+ if (!ret.urls.length) {
+ ret.urls.push({ url, host: "" });
+ }
+ }
+
+ return ret;
+}
+
+const TargetingGetters = {
+ get locale() {
+ return Services.locale.appLocaleAsBCP47;
+ },
+ get localeLanguageCode() {
+ return (
+ Services.locale.appLocaleAsBCP47 &&
+ Services.locale.appLocaleAsBCP47.substr(0, 2)
+ );
+ },
+ get browserSettings() {
+ const { settings } = TelemetryEnvironment.currentEnvironment;
+ return {
+ // This way of getting attribution is deprecated - use atttributionData instead
+ attribution: settings.attribution,
+ update: settings.update,
+ };
+ },
+ get attributionData() {
+ // Attribution is determined at startup - so we can use the cached attribution at this point
+ return AttributionCode.getCachedAttributionData();
+ },
+ get currentDate() {
+ return new Date();
+ },
+ get profileAgeCreated() {
+ return ProfileAge().then(times => times.created);
+ },
+ get profileAgeReset() {
+ return ProfileAge().then(times => times.reset);
+ },
+ get usesFirefoxSync() {
+ return Services.prefs.prefHasUserValue(FXA_USERNAME_PREF);
+ },
+ get isFxAEnabled() {
+ return isFxAEnabled;
+ },
+ get sync() {
+ return {
+ desktopDevices: clientsDevicesDesktop,
+ mobileDevices: clientsDevicesMobile,
+ totalDevices: syncNumClients,
+ };
+ },
+ get xpinstallEnabled() {
+ // This is needed for all add-on recommendations, to know if we allow xpi installs in the first place
+ return isXPIInstallEnabled;
+ },
+ get addonsInfo() {
+ return AddonManager.getActiveAddons(["extension", "service"]).then(
+ ({ addons, fullData }) => {
+ const info = {};
+ for (const addon of addons) {
+ info[addon.id] = {
+ version: addon.version,
+ type: addon.type,
+ isSystem: addon.isSystem,
+ isWebExtension: addon.isWebExtension,
+ };
+ if (fullData) {
+ Object.assign(info[addon.id], {
+ name: addon.name,
+ userDisabled: addon.userDisabled,
+ installDate: addon.installDate,
+ });
+ }
+ }
+ return { addons: info, isFullData: fullData };
+ }
+ );
+ },
+ get searchEngines() {
+ return new Promise(resolve => {
+ // Note: calling init ensures this code is only executed after Search has been initialized
+ Services.search
+ .getAppProvidedEngines()
+ .then(engines => {
+ resolve({
+ current: Services.search.defaultEngine.identifier,
+ installed: engines.map(engine => engine.identifier),
+ });
+ })
+ .catch(() => resolve({ installed: [], current: "" }));
+ });
+ },
+ get isDefaultBrowser() {
+ try {
+ return ShellService.isDefaultBrowser();
+ } catch (e) {}
+ return null;
+ },
+ get devToolsOpenedCount() {
+ return devtoolsSelfXSSCount;
+ },
+ get topFrecentSites() {
+ return QueryCache.queries.TopFrecentSites.get().then(sites =>
+ sites.map(site => ({
+ url: site.url,
+ host: new URL(site.url).hostname,
+ frecency: site.frecency,
+ lastVisitDate: site.lastVisitDate,
+ }))
+ );
+ },
+ get recentBookmarks() {
+ return QueryCache.queries.RecentBookmarks.get();
+ },
+ get pinnedSites() {
+ return NewTabUtils.pinnedLinks.links.map(site =>
+ site
+ ? {
+ url: site.url,
+ host: new URL(site.url).hostname,
+ searchTopSite: site.searchTopSite,
+ }
+ : {}
+ );
+ },
+ get providerCohorts() {
+ return ASRouterPreferences.providers.reduce((prev, current) => {
+ prev[current.id] = current.cohort || "";
+ return prev;
+ }, {});
+ },
+ get totalBookmarksCount() {
+ return QueryCache.queries.TotalBookmarksCount.get();
+ },
+ get firefoxVersion() {
+ return parseInt(AppConstants.MOZ_APP_VERSION.match(/\d+/), 10);
+ },
+ get region() {
+ return Region.home || "";
+ },
+ get needsUpdate() {
+ return QueryCache.queries.CheckBrowserNeedsUpdate.get();
+ },
+ get hasPinnedTabs() {
+ for (let win of Services.wm.getEnumerator("navigator:browser")) {
+ if (win.closed || !win.ownerGlobal.gBrowser) {
+ continue;
+ }
+ if (win.ownerGlobal.gBrowser.visibleTabs.filter(t => t.pinned).length) {
+ return true;
+ }
+ }
+
+ return false;
+ },
+ get hasAccessedFxAPanel() {
+ return hasAccessedFxAPanel;
+ },
+ get isWhatsNewPanelEnabled() {
+ return isWhatsNewPanelEnabled;
+ },
+ get userPrefs() {
+ return {
+ cfrFeatures: cfrFeaturesUserPref,
+ cfrAddons: cfrAddonsUserPref,
+ snippets: snippetsUserPref,
+ };
+ },
+ get totalBlockedCount() {
+ return TrackingDBService.sumAllEvents();
+ },
+ get blockedCountByType() {
+ const idToTextMap = new Map([
+ [Ci.nsITrackingDBService.TRACKERS_ID, "trackerCount"],
+ [Ci.nsITrackingDBService.TRACKING_COOKIES_ID, "cookieCount"],
+ [Ci.nsITrackingDBService.CRYPTOMINERS_ID, "cryptominerCount"],
+ [Ci.nsITrackingDBService.FINGERPRINTERS_ID, "fingerprinterCount"],
+ [Ci.nsITrackingDBService.SOCIAL_ID, "socialCount"],
+ ]);
+
+ const dateTo = new Date();
+ const dateFrom = new Date(dateTo.getTime() - 42 * 24 * 60 * 60 * 1000);
+ return TrackingDBService.getEventsByDateRange(dateFrom, dateTo).then(
+ eventsByDate => {
+ let totalEvents = {};
+ for (let blockedType of idToTextMap.values()) {
+ totalEvents[blockedType] = 0;
+ }
+
+ return eventsByDate.reduce((acc, day) => {
+ const type = day.getResultByName("type");
+ const count = day.getResultByName("count");
+ acc[idToTextMap.get(type)] = acc[idToTextMap.get(type)] + count;
+ return acc;
+ }, totalEvents);
+ }
+ );
+ },
+ get attachedFxAOAuthClients() {
+ return this.usesFirefoxSync
+ ? QueryCache.queries.ListAttachedOAuthClients.get()
+ : [];
+ },
+ get platformName() {
+ return AppConstants.platform;
+ },
+ get scores() {
+ return ASRouterPreferences.personalizedCfrScores;
+ },
+ get scoreThreshold() {
+ return ASRouterPreferences.personalizedCfrThreshold;
+ },
+ get isChinaRepack() {
+ return (
+ Services.prefs
+ .getDefaultBranch(null)
+ .getCharPref(DISTRIBUTION_ID_PREF, "default") ===
+ DISTRIBUTION_ID_CHINA_REPACK
+ );
+ },
+ get userId() {
+ return ClientEnvironment.userId;
+ },
+ get profileRestartCount() {
+ // Counter starts at 1 when a profile is created, substract 1 so the value
+ // returned matches expectations
+ return (
+ TelemetrySession.getMetadata("targeting").profileSubsessionCounter - 1
+ );
+ },
+ get homePageSettings() {
+ const url = HomePage.get();
+ const { isWebExt, isCustomUrl, urls } = parseAboutPageURL(url);
+
+ return {
+ isWebExt,
+ isCustomUrl,
+ urls,
+ isDefault: HomePage.isDefault,
+ isLocked: HomePage.locked,
+ };
+ },
+ get newtabSettings() {
+ const url = AboutNewTab.newTabURL;
+ const { isWebExt, isCustomUrl, urls } = parseAboutPageURL(url);
+
+ return {
+ isWebExt,
+ isCustomUrl,
+ isDefault: AboutNewTab.activityStreamEnabled,
+ url: urls[0].url,
+ host: urls[0].host,
+ };
+ },
+ get isFissionExperimentEnabled() {
+ return (
+ Services.appinfo.fissionExperimentStatus ===
+ Ci.nsIXULRuntime.eExperimentStatusTreatment
+ );
+ },
+ get activeNotifications() {
+ let window = BrowserWindowTracker.getTopWindow();
+
+ if (
+ window.gURLBar.view.isOpen ||
+ window.gHighPriorityNotificationBox.currentNotification ||
+ window.gBrowser.getNotificationBox().currentNotification
+ ) {
+ return true;
+ }
+
+ return false;
+ },
+};
+
+this.ASRouterTargeting = {
+ Environment: TargetingGetters,
+
+ isTriggerMatch(trigger = {}, candidateMessageTrigger = {}) {
+ if (trigger.id !== candidateMessageTrigger.id) {
+ return false;
+ } else if (
+ !candidateMessageTrigger.params &&
+ !candidateMessageTrigger.patterns
+ ) {
+ return true;
+ }
+
+ if (!trigger.param) {
+ return false;
+ }
+
+ return (
+ (candidateMessageTrigger.params &&
+ trigger.param.host &&
+ candidateMessageTrigger.params.includes(trigger.param.host)) ||
+ (candidateMessageTrigger.params &&
+ trigger.param.type &&
+ candidateMessageTrigger.params.filter(t => t === trigger.param.type)
+ .length) ||
+ (candidateMessageTrigger.params &&
+ trigger.param.type &&
+ candidateMessageTrigger.params.filter(
+ t => (t & trigger.param.type) === t
+ ).length) ||
+ (candidateMessageTrigger.patterns &&
+ trigger.param.url &&
+ new MatchPatternSet(candidateMessageTrigger.patterns).matches(
+ trigger.param.url
+ ))
+ );
+ },
+
+ /**
+ * getCachedEvaluation - Return a cached jexl evaluation if available
+ *
+ * @param {string} targeting JEXL expression to lookup
+ * @returns {obj|null} Object with value result or null if not available
+ */
+ getCachedEvaluation(targeting) {
+ if (jexlEvaluationCache.has(targeting)) {
+ const { timestamp, value } = jexlEvaluationCache.get(targeting);
+ if (Date.now() - timestamp <= CACHE_EXPIRATION) {
+ return { value };
+ }
+ jexlEvaluationCache.delete(targeting);
+ }
+
+ return null;
+ },
+
+ /**
+ * checkMessageTargeting - Checks is a message's targeting parameters are satisfied
+ *
+ * @param {*} message An AS router message
+ * @param {obj} targetingContext a TargetingContext instance complete with eval environment
+ * @param {func} onError A function to handle errors (takes two params; error, message)
+ * @param {boolean} shouldCache Should the JEXL evaluations be cached and reused.
+ * @returns
+ */
+ async checkMessageTargeting(message, targetingContext, onError, shouldCache) {
+ // If no targeting is specified,
+ if (!message.targeting) {
+ return true;
+ }
+ let result;
+ try {
+ if (shouldCache) {
+ result = this.getCachedEvaluation(message.targeting);
+ if (result) {
+ return result.value;
+ }
+ }
+ result = await targetingContext.evalWithDefault(message.targeting);
+ if (shouldCache) {
+ jexlEvaluationCache.set(message.targeting, {
+ timestamp: Date.now(),
+ value: result,
+ });
+ }
+ } catch (error) {
+ if (onError) {
+ onError(error, message);
+ }
+ Cu.reportError(error);
+ result = false;
+ }
+ return result;
+ },
+
+ _isMessageMatch(
+ message,
+ trigger,
+ targetingContext,
+ onError,
+ shouldCache = false
+ ) {
+ return (
+ message &&
+ (trigger
+ ? this.isTriggerMatch(trigger, message.trigger)
+ : !message.trigger) &&
+ // If a trigger expression was passed to this function, the message should match it.
+ // Otherwise, we should choose a message with no trigger property (i.e. a message that can show up at any time)
+ this.checkMessageTargeting(
+ message,
+ targetingContext,
+ onError,
+ shouldCache
+ )
+ );
+ },
+
+ /**
+ * findMatchingMessage - Given an array of messages, returns one message
+ * whos targeting expression evaluates to true
+ *
+ * @param {Array<Message>} messages An array of AS router messages
+ * @param {trigger} string A trigger expression if a message for that trigger is desired
+ * @param {obj|null} context A FilterExpression context. Defaults to TargetingGetters above.
+ * @param {func} onError A function to handle errors (takes two params; error, message)
+ * @param {func} ordered An optional param when true sort message by order specified in message
+ * @param {boolean} shouldCache Should the JEXL evaluations be cached and reused.
+ * @param {boolean} returnAll Should we return all matching messages, not just the first one found.
+ * @returns {obj|Array<Message>} If returnAll is false, a single message. If returnAll is true, an array of messages.
+ */
+ async findMatchingMessage({
+ messages,
+ trigger = {},
+ context = {},
+ onError,
+ ordered = false,
+ shouldCache = false,
+ returnAll = false,
+ }) {
+ const sortedMessages = getSortedMessages(messages, { ordered });
+ const matching = returnAll ? [] : null;
+ const targetingContext = new TargetingContext(
+ TargetingContext.combineContexts(
+ context,
+ this.Environment,
+ trigger.context || {}
+ )
+ );
+
+ const isMatch = candidate =>
+ this._isMessageMatch(
+ candidate,
+ trigger,
+ targetingContext,
+ onError,
+ shouldCache
+ );
+
+ for (const candidate of sortedMessages) {
+ if (await isMatch(candidate)) {
+ // If not returnAll, we should return the first message we find that matches.
+ if (!returnAll) {
+ return candidate;
+ }
+
+ matching.push(candidate);
+ }
+ }
+ return matching;
+ },
+};
+
+// Export for testing
+this.getSortedMessages = getSortedMessages;
+this.QueryCache = QueryCache;
+this.CachedTargetingGetter = CachedTargetingGetter;
+this.EXPORTED_SYMBOLS = [
+ "ASRouterTargeting",
+ "QueryCache",
+ "CachedTargetingGetter",
+ "getSortedMessages",
+];
diff --git a/browser/components/newtab/lib/ASRouterTriggerListeners.jsm b/browser/components/newtab/lib/ASRouterTriggerListeners.jsm
new file mode 100644
index 0000000000..c79f36ee25
--- /dev/null
+++ b/browser/components/newtab/lib/ASRouterTriggerListeners.jsm
@@ -0,0 +1,594 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
+const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
+const { XPCOMUtils } = ChromeUtils.import(
+ "resource://gre/modules/XPCOMUtils.jsm"
+);
+
+XPCOMUtils.defineLazyModuleGetters(this, {
+ PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.jsm",
+ EveryWindow: "resource:///modules/EveryWindow.jsm",
+ AboutReaderParent: "resource:///actors/AboutReaderParent.jsm",
+});
+
+const FEW_MINUTES = 15 * 60 * 1000; // 15 mins
+
+function isPrivateWindow(win) {
+ return (
+ !(win instanceof Ci.nsIDOMWindow) ||
+ win.closed ||
+ PrivateBrowsingUtils.isWindowPrivate(win)
+ );
+}
+
+/**
+ * Check current location against the list of allowed hosts
+ * Additionally verify for redirects and check original request URL against
+ * the list.
+ *
+ * @returns {object} - {host, url} pair that matched the list of allowed hosts
+ */
+function checkURLMatch(aLocationURI, { hosts, matchPatternSet }, aRequest) {
+ // If checks pass we return a match
+ let match;
+ try {
+ match = { host: aLocationURI.host, url: aLocationURI.spec };
+ } catch (e) {
+ // nsIURI.host can throw for non-nsStandardURL nsIURIs
+ return false;
+ }
+
+ // Check current location against allowed hosts
+ if (hosts.has(match.host)) {
+ return match;
+ }
+
+ if (matchPatternSet) {
+ if (matchPatternSet.matches(match.url)) {
+ return match;
+ }
+ }
+
+ // Nothing else to check, return early
+ if (!aRequest) {
+ return false;
+ }
+
+ // The original URL at the start of the request
+ const originalLocation = aRequest.QueryInterface(Ci.nsIChannel).originalURI;
+ // We have been redirected
+ if (originalLocation.spec !== aLocationURI.spec) {
+ return (
+ hosts.has(originalLocation.host) && {
+ host: originalLocation.host,
+ url: originalLocation.spec,
+ }
+ );
+ }
+
+ return false;
+}
+
+function createMatchPatternSet(patterns, flags) {
+ try {
+ return new MatchPatternSet(new Set(patterns), flags);
+ } catch (e) {
+ Cu.reportError(e);
+ }
+ return new MatchPatternSet([]);
+}
+
+/**
+ * A Map from trigger IDs to singleton trigger listeners. Each listener must
+ * have idempotent `init` and `uninit` methods.
+ */
+this.ASRouterTriggerListeners = new Map([
+ [
+ "openArticleURL",
+ {
+ id: "openArticleURL",
+ _initialized: false,
+ _triggerHandler: null,
+ _hosts: new Set(),
+ _matchPatternSet: null,
+ readerModeEvent: "Reader:UpdateReaderButton",
+
+ init(triggerHandler, hosts, patterns) {
+ if (!this._initialized) {
+ this.receiveMessage = this.receiveMessage.bind(this);
+ AboutReaderParent.addMessageListener(this.readerModeEvent, this);
+ this._triggerHandler = triggerHandler;
+ this._initialized = true;
+ }
+ if (patterns) {
+ this._matchPatternSet = createMatchPatternSet([
+ ...(this._matchPatternSet ? this._matchPatternSet.patterns : []),
+ ...patterns,
+ ]);
+ }
+ if (hosts) {
+ hosts.forEach(h => this._hosts.add(h));
+ }
+ },
+
+ receiveMessage({ data, target }) {
+ if (data && data.isArticle) {
+ const match = checkURLMatch(target.currentURI, {
+ hosts: this._hosts,
+ matchPatternSet: this._matchPatternSet,
+ });
+ if (match) {
+ this._triggerHandler(target, { id: this.id, param: match });
+ }
+ }
+ },
+
+ uninit() {
+ if (this._initialized) {
+ AboutReaderParent.removeMessageListener(this.readerModeEvent, this);
+ this._initialized = false;
+ this._triggerHandler = null;
+ this._hosts = new Set();
+ this._matchPatternSet = null;
+ }
+ },
+ },
+ ],
+ [
+ "openBookmarkedURL",
+ {
+ id: "openBookmarkedURL",
+ _initialized: false,
+ _triggerHandler: null,
+ _hosts: new Set(),
+ bookmarkEvent: "bookmark-icon-updated",
+
+ init(triggerHandler) {
+ if (!this._initialized) {
+ Services.obs.addObserver(this, this.bookmarkEvent);
+ this._triggerHandler = triggerHandler;
+ this._initialized = true;
+ }
+ },
+
+ observe(subject, topic, data) {
+ if (topic === this.bookmarkEvent && data === "starred") {
+ const browser = Services.wm.getMostRecentBrowserWindow();
+ if (browser) {
+ this._triggerHandler(browser.gBrowser.selectedBrowser, {
+ id: this.id,
+ });
+ }
+ }
+ },
+
+ uninit() {
+ if (this._initialized) {
+ Services.obs.removeObserver(this, this.bookmarkEvent);
+ this._initialized = false;
+ this._triggerHandler = null;
+ this._hosts = new Set();
+ }
+ },
+ },
+ ],
+ [
+ "frequentVisits",
+ {
+ id: "frequentVisits",
+ _initialized: false,
+ _triggerHandler: null,
+ _hosts: null,
+ _matchPatternSet: null,
+ _visits: null,
+
+ init(triggerHandler, hosts = [], patterns) {
+ if (!this._initialized) {
+ this.onTabSwitch = this.onTabSwitch.bind(this);
+ EveryWindow.registerCallback(
+ this.id,
+ win => {
+ if (!isPrivateWindow(win)) {
+ win.addEventListener("TabSelect", this.onTabSwitch);
+ win.gBrowser.addTabsProgressListener(this);
+ }
+ },
+ win => {
+ if (!isPrivateWindow(win)) {
+ win.removeEventListener("TabSelect", this.onTabSwitch);
+ win.gBrowser.removeTabsProgressListener(this);
+ }
+ }
+ );
+ this._visits = new Map();
+ this._initialized = true;
+ }
+ this._triggerHandler = triggerHandler;
+ if (patterns) {
+ this._matchPatternSet = createMatchPatternSet([
+ ...(this._matchPatternSet ? this._matchPatternSet.patterns : []),
+ ...patterns,
+ ]);
+ }
+ if (this._hosts) {
+ hosts.forEach(h => this._hosts.add(h));
+ } else {
+ this._hosts = new Set(hosts); // Clone the hosts to avoid unexpected behaviour
+ }
+ },
+
+ /* _updateVisits - Record visit timestamps for websites that match `this._hosts` and only
+ * if it's been more than FEW_MINUTES since the last visit.
+ * @param {string} host - Location host of current selected tab
+ * @returns {boolean} - If the new visit has been recorded
+ */
+ _updateVisits(host) {
+ const visits = this._visits.get(host);
+
+ if (visits && Date.now() - visits[0] > FEW_MINUTES) {
+ this._visits.set(host, [Date.now(), ...visits]);
+ return true;
+ }
+ if (!visits) {
+ this._visits.set(host, [Date.now()]);
+ return true;
+ }
+
+ return false;
+ },
+
+ onTabSwitch(event) {
+ if (!event.target.ownerGlobal.gBrowser) {
+ return;
+ }
+
+ const { gBrowser } = event.target.ownerGlobal;
+ const match = checkURLMatch(gBrowser.currentURI, {
+ hosts: this._hosts,
+ matchPatternSet: this._matchPatternSet,
+ });
+ if (match) {
+ this.triggerHandler(gBrowser.selectedBrowser, match);
+ }
+ },
+
+ triggerHandler(aBrowser, match) {
+ const updated = this._updateVisits(match.host);
+
+ // If the previous visit happend less than FEW_MINUTES ago
+ // no updates were made, no need to trigger the handler
+ if (!updated) {
+ return;
+ }
+
+ this._triggerHandler(aBrowser, {
+ id: this.id,
+ param: match,
+ context: {
+ // Remapped to {host, timestamp} because JEXL operators can only
+ // filter over collections (arrays of objects)
+ recentVisits: this._visits
+ .get(match.host)
+ .map(timestamp => ({ host: match.host, timestamp })),
+ },
+ });
+ },
+
+ onLocationChange(aBrowser, aWebProgress, aRequest, aLocationURI, aFlags) {
+ // Some websites trigger redirect events after they finish loading even
+ // though the location remains the same. This results in onLocationChange
+ // events to be fired twice.
+ const isSameDocument = !!(
+ aFlags & Ci.nsIWebProgressListener.LOCATION_CHANGE_SAME_DOCUMENT
+ );
+ if (aWebProgress.isTopLevel && !isSameDocument) {
+ const match = checkURLMatch(
+ aLocationURI,
+ { hosts: this._hosts, matchPatternSet: this._matchPatternSet },
+ aRequest
+ );
+ if (match) {
+ this.triggerHandler(aBrowser, match);
+ }
+ }
+ },
+
+ uninit() {
+ if (this._initialized) {
+ EveryWindow.unregisterCallback(this.id);
+
+ this._initialized = false;
+ this._triggerHandler = null;
+ this._hosts = null;
+ this._matchPatternSet = null;
+ this._visits = null;
+ }
+ },
+ },
+ ],
+
+ /**
+ * Attach listeners to every browser window to detect location changes, and
+ * notify the trigger handler whenever we navigate to a URL with a hostname
+ * we're looking for.
+ */
+ [
+ "openURL",
+ {
+ id: "openURL",
+ _initialized: false,
+ _triggerHandler: null,
+ _hosts: null,
+ _matchPatternSet: null,
+ _visits: null,
+
+ /*
+ * If the listener is already initialised, `init` will replace the trigger
+ * handler and add any new hosts to `this._hosts`.
+ */
+ init(triggerHandler, hosts = [], patterns) {
+ if (!this._initialized) {
+ this.onLocationChange = this.onLocationChange.bind(this);
+ EveryWindow.registerCallback(
+ this.id,
+ win => {
+ if (!isPrivateWindow(win)) {
+ win.addEventListener("TabSelect", this.onTabSwitch);
+ win.gBrowser.addTabsProgressListener(this);
+ }
+ },
+ win => {
+ if (!isPrivateWindow(win)) {
+ win.removeEventListener("TabSelect", this.onTabSwitch);
+ win.gBrowser.removeTabsProgressListener(this);
+ }
+ }
+ );
+
+ this._visits = new Map();
+ this._initialized = true;
+ }
+ this._triggerHandler = triggerHandler;
+ if (patterns) {
+ this._matchPatternSet = createMatchPatternSet([
+ ...(this._matchPatternSet ? this._matchPatternSet.patterns : []),
+ ...patterns,
+ ]);
+ }
+ if (this._hosts) {
+ hosts.forEach(h => this._hosts.add(h));
+ } else {
+ this._hosts = new Set(hosts); // Clone the hosts to avoid unexpected behaviour
+ }
+ },
+
+ uninit() {
+ if (this._initialized) {
+ EveryWindow.unregisterCallback(this.id);
+
+ this._initialized = false;
+ this._triggerHandler = null;
+ this._hosts = null;
+ this._matchPatternSet = null;
+ this._visits = null;
+ }
+ },
+
+ onLocationChange(aBrowser, aWebProgress, aRequest, aLocationURI, aFlags) {
+ // Some websites trigger redirect events after they finish loading even
+ // though the location remains the same. This results in onLocationChange
+ // events to be fired twice.
+ const isSameDocument = !!(
+ aFlags & Ci.nsIWebProgressListener.LOCATION_CHANGE_SAME_DOCUMENT
+ );
+ if (aWebProgress.isTopLevel && !isSameDocument) {
+ const match = checkURLMatch(
+ aLocationURI,
+ { hosts: this._hosts, matchPatternSet: this._matchPatternSet },
+ aRequest
+ );
+ if (match) {
+ let visitsCount = (this._visits.get(match.url) || 0) + 1;
+ this._visits.set(match.url, visitsCount);
+ this._triggerHandler(aBrowser, {
+ id: this.id,
+ param: match,
+ context: { visitsCount },
+ });
+ }
+ }
+ },
+ },
+ ],
+
+ /**
+ * Add an observer notification to notify the trigger handler whenever the user
+ * saves or updates a login via the login capture doorhanger.
+ */
+ [
+ "newSavedLogin",
+ {
+ _initialized: false,
+ _triggerHandler: null,
+
+ /**
+ * If the listener is already initialised, `init` will replace the trigger
+ * handler.
+ */
+ init(triggerHandler) {
+ if (!this._initialized) {
+ Services.obs.addObserver(this, "LoginStats:NewSavedPassword");
+ Services.obs.addObserver(this, "LoginStats:LoginUpdateSaved");
+ this._initialized = true;
+ }
+ this._triggerHandler = triggerHandler;
+ },
+
+ uninit() {
+ if (this._initialized) {
+ Services.obs.removeObserver(this, "LoginStats:NewSavedPassword");
+ Services.obs.removeObserver(this, "LoginStats:LoginUpdateSaved");
+
+ this._initialized = false;
+ this._triggerHandler = null;
+ }
+ },
+
+ observe(aSubject, aTopic, aData) {
+ if (aSubject.currentURI.asciiHost === "accounts.firefox.com") {
+ // Don't notify about saved logins on the FxA login origin since this
+ // trigger is used to promote login Sync and getting a recommendation
+ // to enable Sync during the sign up process is a bad UX.
+ return;
+ }
+
+ switch (aTopic) {
+ case "LoginStats:NewSavedPassword": {
+ this._triggerHandler(aSubject, {
+ id: "newSavedLogin",
+ context: { type: "save" },
+ });
+ break;
+ }
+ case "LoginStats:LoginUpdateSaved": {
+ this._triggerHandler(aSubject, {
+ id: "newSavedLogin",
+ context: { type: "update" },
+ });
+ break;
+ }
+ default: {
+ throw new Error(`Unexpected observer notification: ${aTopic}`);
+ }
+ }
+ },
+ },
+ ],
+
+ /**
+ * Attach listener to count location changes and notify the trigger handler
+ * on content blocked event
+ */
+ [
+ "contentBlocking",
+ {
+ _initialized: false,
+ _triggerHandler: null,
+ _events: [],
+ _sessionPageLoad: 0,
+ onLocationChange: null,
+
+ init(triggerHandler, params, patterns) {
+ params.forEach(p => this._events.push(p));
+
+ if (!this._initialized) {
+ Services.obs.addObserver(this, "SiteProtection:ContentBlockingEvent");
+ Services.obs.addObserver(
+ this,
+ "SiteProtection:ContentBlockingMilestone"
+ );
+ this.onLocationChange = this._onLocationChange.bind(this);
+ EveryWindow.registerCallback(
+ this.id,
+ win => {
+ if (!isPrivateWindow(win)) {
+ win.gBrowser.addTabsProgressListener(this);
+ }
+ },
+ win => {
+ if (!isPrivateWindow(win)) {
+ win.gBrowser.removeTabsProgressListener(this);
+ }
+ }
+ );
+
+ this._initialized = true;
+ }
+ this._triggerHandler = triggerHandler;
+ },
+
+ uninit() {
+ if (this._initialized) {
+ Services.obs.removeObserver(
+ this,
+ "SiteProtection:ContentBlockingEvent"
+ );
+ Services.obs.removeObserver(
+ this,
+ "SiteProtection:ContentBlockingMilestone"
+ );
+ EveryWindow.unregisterCallback(this.id);
+ this.onLocationChange = null;
+ this._initialized = false;
+ }
+ this._triggerHandler = null;
+ this._events = [];
+ this._sessionPageLoad = 0;
+ },
+
+ observe(aSubject, aTopic, aData) {
+ switch (aTopic) {
+ case "SiteProtection:ContentBlockingEvent":
+ const { browser, host, event } = aSubject.wrappedJSObject;
+ if (this._events.filter(e => (e & event) === e).length) {
+ this._triggerHandler(browser, {
+ id: "contentBlocking",
+ param: {
+ host,
+ type: event,
+ },
+ context: {
+ pageLoad: this._sessionPageLoad,
+ },
+ });
+ }
+ break;
+ case "SiteProtection:ContentBlockingMilestone":
+ if (this._events.includes(aSubject.wrappedJSObject.event)) {
+ this._triggerHandler(
+ Services.wm.getMostRecentBrowserWindow().gBrowser
+ .selectedBrowser,
+ {
+ id: "contentBlocking",
+ context: {
+ pageLoad: this._sessionPageLoad,
+ },
+ param: {
+ type: aSubject.wrappedJSObject.event,
+ },
+ }
+ );
+ }
+ break;
+ }
+ },
+
+ _onLocationChange(
+ aBrowser,
+ aWebProgress,
+ aRequest,
+ aLocationURI,
+ aFlags
+ ) {
+ // Some websites trigger redirect events after they finish loading even
+ // though the location remains the same. This results in onLocationChange
+ // events to be fired twice.
+ const isSameDocument = !!(
+ aFlags & Ci.nsIWebProgressListener.LOCATION_CHANGE_SAME_DOCUMENT
+ );
+ if (
+ ["http", "https"].includes(aLocationURI.scheme) &&
+ aWebProgress.isTopLevel &&
+ !isSameDocument
+ ) {
+ this._sessionPageLoad += 1;
+ }
+ },
+ },
+ ],
+]);
+
+const EXPORTED_SYMBOLS = ["ASRouterTriggerListeners"];
diff --git a/browser/components/newtab/lib/AboutPreferences.jsm b/browser/components/newtab/lib/AboutPreferences.jsm
new file mode 100644
index 0000000000..ae8cf497a3
--- /dev/null
+++ b/browser/components/newtab/lib/AboutPreferences.jsm
@@ -0,0 +1,334 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
+const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
+const { actionTypes: at, actionCreators: ac } = ChromeUtils.import(
+ "resource://activity-stream/common/Actions.jsm"
+);
+
+const HTML_NS = "http://www.w3.org/1999/xhtml";
+const PREFERENCES_LOADED_EVENT = "home-pane-loaded";
+
+// These "section" objects are formatted in a way to be similar to the ones from
+// SectionsManager to construct the preferences view.
+const PREFS_BEFORE_SECTIONS = [
+ {
+ id: "search",
+ pref: {
+ feed: "showSearch",
+ titleString: "home-prefs-search-header",
+ },
+ icon: "chrome://browser/skin/search-glass.svg",
+ },
+ {
+ id: "topsites",
+ pref: {
+ feed: "feeds.topsites",
+ titleString:
+ Services.prefs.getBoolPref(
+ "browser.newtabpage.activity-stream.newNewtabExperience.enabled"
+ ) ||
+ Services.prefs.getBoolPref(
+ "browser.newtabpage.activity-stream.customizationMenu.enabled"
+ )
+ ? "home-prefs-shortcuts-header"
+ : "home-prefs-topsites-header",
+ descString:
+ Services.prefs.getBoolPref(
+ "browser.newtabpage.activity-stream.newNewtabExperience.enabled"
+ ) ||
+ Services.prefs.getBoolPref(
+ "browser.newtabpage.activity-stream.customizationMenu.enabled"
+ )
+ ? "home-prefs-shortcuts-description"
+ : "home-prefs-topsites-description",
+ get nestedPrefs() {
+ return Services.prefs.getBoolPref("browser.topsites.useRemoteSetting")
+ ? [
+ {
+ name: "showSponsoredTopSites",
+ titleString:
+ Services.prefs.getBoolPref(
+ "browser.newtabpage.activity-stream.newNewtabExperience.enabled"
+ ) ||
+ Services.prefs.getBoolPref(
+ "browser.newtabpage.activity-stream.customizationMenu.enabled"
+ )
+ ? "home-prefs-shortcuts-by-option-sponsored"
+ : "home-prefs-topsites-by-option-sponsored",
+ eventSource: "SPONSORED_TOP_SITES",
+ },
+ ]
+ : [];
+ },
+ },
+ icon: "topsites",
+ maxRows: 4,
+ rowsPref: "topSitesRows",
+ eventSource: "TOP_SITES",
+ },
+];
+
+const PREFS_AFTER_SECTIONS = [
+ {
+ id: "snippets",
+ pref: {
+ feed: "feeds.snippets",
+ titleString: "home-prefs-snippets-header",
+ descString:
+ Services.prefs.getBoolPref(
+ "browser.newtabpage.activity-stream.newNewtabExperience.enabled"
+ ) ||
+ Services.prefs.getBoolPref(
+ "browser.newtabpage.activity-stream.customizationMenu.enabled"
+ )
+ ? "home-prefs-snippets-description-new"
+ : "home-prefs-snippets-description",
+ },
+ icon: "info",
+ eventSource: "SNIPPETS",
+ },
+];
+
+this.AboutPreferences = class AboutPreferences {
+ init() {
+ Services.obs.addObserver(this, PREFERENCES_LOADED_EVENT);
+ }
+
+ uninit() {
+ Services.obs.removeObserver(this, PREFERENCES_LOADED_EVENT);
+ }
+
+ onAction(action) {
+ switch (action.type) {
+ case at.INIT:
+ this.init();
+ break;
+ case at.UNINIT:
+ this.uninit();
+ break;
+ case at.SETTINGS_OPEN:
+ action._target.browser.ownerGlobal.openPreferences("paneHome");
+ break;
+ // This is used to open the web extension settings page for an extension
+ case at.OPEN_WEBEXT_SETTINGS:
+ action._target.browser.ownerGlobal.BrowserOpenAddonsMgr(
+ `addons://detail/${encodeURIComponent(action.data)}`
+ );
+ break;
+ }
+ }
+
+ handleDiscoverySettings(sections) {
+ // Deep copy object to not modify original Sections state in store
+ let sectionsCopy = JSON.parse(JSON.stringify(sections));
+ sectionsCopy.forEach(obj => {
+ if (obj.id === "topstories") {
+ obj.rowsPref = "";
+ }
+ });
+ return sectionsCopy;
+ }
+
+ setupUserEvent(element, eventSource) {
+ element.addEventListener("command", e => {
+ const { checked } = e.target;
+ if (typeof checked === "boolean") {
+ this.store.dispatch(
+ ac.UserEvent({
+ event: "PREF_CHANGED",
+ source: eventSource,
+ value: { status: checked, menu_source: "ABOUT_PREFERENCES" },
+ })
+ );
+ }
+ });
+ }
+
+ observe(window) {
+ const discoveryStreamConfig = this.store.getState().DiscoveryStream.config;
+ let sections = this.store.getState().Sections;
+
+ if (discoveryStreamConfig.enabled) {
+ sections = this.handleDiscoverySettings(sections);
+ }
+
+ this.renderPreferences(window, [
+ ...PREFS_BEFORE_SECTIONS,
+ ...sections,
+ ...PREFS_AFTER_SECTIONS,
+ ]);
+ }
+
+ /**
+ * Render preferences to an about:preferences content window with the provided
+ * preferences structure.
+ */
+ renderPreferences({ document, Preferences, gHomePane }, prefStructure) {
+ // Helper to create a new element and append it
+ const createAppend = (tag, parent, options) =>
+ parent.appendChild(document.createXULElement(tag, options));
+
+ // Helper to get fluentIDs sometimes encase in an object
+ const getString = message =>
+ typeof message !== "object" ? message : message.id;
+
+ // Helper to link a UI element to a preference for updating
+ const linkPref = (element, name, type) => {
+ const fullPref = `browser.newtabpage.activity-stream.${name}`;
+ element.setAttribute("preference", fullPref);
+ Preferences.add({ id: fullPref, type });
+
+ // Prevent changing the UI if the preference can't be changed
+ element.disabled = Preferences.get(fullPref).locked;
+ };
+
+ // Insert a new group immediately after the homepage one
+ const homeGroup = document.getElementById("homepageGroup");
+ const contentsGroup = homeGroup.insertAdjacentElement(
+ "afterend",
+ homeGroup.cloneNode()
+ );
+ contentsGroup.id = "homeContentsGroup";
+ contentsGroup.setAttribute("data-subcategory", "contents");
+ const homeHeader = createAppend("label", contentsGroup).appendChild(
+ document.createElementNS(HTML_NS, "h2")
+ );
+ document.l10n.setAttributes(homeHeader, "home-prefs-content-header");
+
+ const homeDescription = createAppend("description", contentsGroup);
+ document.l10n.setAttributes(
+ homeDescription,
+ "home-prefs-content-description"
+ );
+
+ // Add preferences for each section
+ prefStructure.forEach(sectionData => {
+ const {
+ id,
+ pref: prefData,
+ icon = "webextension",
+ maxRows,
+ rowsPref,
+ shouldHidePref,
+ eventSource,
+ } = sectionData;
+ const { feed: name, titleString = {}, descString, nestedPrefs = [] } =
+ prefData || {};
+
+ // Don't show any sections that we don't want to expose in preferences UI
+ if (shouldHidePref) {
+ return;
+ }
+
+ // Use full icon spec for certain protocols or fall back to packaged icon
+ const iconUrl = !icon.search(/^(chrome|moz-extension|resource):/)
+ ? icon
+ : `chrome://activity-stream/content/data/content/assets/glyph-${icon}-16.svg`;
+
+ // Add the main preference for turning on/off a section
+ const sectionVbox = createAppend("vbox", contentsGroup);
+ sectionVbox.setAttribute("data-subcategory", id);
+ const checkbox = createAppend("checkbox", sectionVbox);
+ checkbox.classList.add("section-checkbox");
+ checkbox.setAttribute("src", iconUrl);
+ // Setup a user event if we have an event source for this pref.
+ if (eventSource) {
+ this.setupUserEvent(checkbox, eventSource);
+ }
+ document.l10n.setAttributes(
+ checkbox,
+ getString(titleString),
+ titleString.values
+ );
+
+ linkPref(checkbox, name, "bool");
+
+ // Specially add a link for stories
+ if (id === "topstories") {
+ const sponsoredHbox = createAppend("hbox", sectionVbox);
+ sponsoredHbox.setAttribute("align", "center");
+ sponsoredHbox.appendChild(checkbox);
+ checkbox.classList.add("tail-with-learn-more");
+
+ const link = createAppend("label", sponsoredHbox, { is: "text-link" });
+ link.classList.add("learn-sponsored");
+ link.setAttribute("href", sectionData.pref.learnMore.link.href);
+ document.l10n.setAttributes(link, sectionData.pref.learnMore.link.id);
+ }
+
+ // Add more details for the section (e.g., description, more prefs)
+ const detailVbox = createAppend("vbox", sectionVbox);
+ detailVbox.classList.add("indent");
+ if (descString) {
+ const label = createAppend("label", detailVbox);
+ label.classList.add("indent");
+ document.l10n.setAttributes(
+ label,
+ getString(descString),
+ descString.values
+ );
+
+ // Add a rows dropdown if we have a pref to control and a maximum
+ if (rowsPref && maxRows) {
+ const detailHbox = createAppend("hbox", detailVbox);
+ detailHbox.setAttribute("align", "center");
+ label.setAttribute("flex", 1);
+ detailHbox.appendChild(label);
+
+ // Add box so the search tooltip is positioned correctly
+ const tooltipBox = createAppend("hbox", detailHbox);
+
+ // Add appropriate number of localized entries to the dropdown
+ const menulist = createAppend("menulist", tooltipBox);
+ menulist.setAttribute("crop", "none");
+ const menupopup = createAppend("menupopup", menulist);
+ for (let num = 1; num <= maxRows; num++) {
+ const item = createAppend("menuitem", menupopup);
+ document.l10n.setAttributes(
+ item,
+ "home-prefs-sections-rows-option",
+ { num }
+ );
+ item.setAttribute("value", num);
+ }
+ linkPref(menulist, rowsPref, "int");
+ }
+ }
+
+ const subChecks = [];
+ const fullName = `browser.newtabpage.activity-stream.${sectionData.pref.feed}`;
+ const pref = Preferences.get(fullName);
+
+ // Add a checkbox pref for any nested preferences
+ nestedPrefs.forEach(nested => {
+ const subcheck = createAppend("checkbox", detailVbox);
+ // Setup a user event if we have an event source for this pref.
+ if (nested.eventSource) {
+ this.setupUserEvent(subcheck, nested.eventSource);
+ }
+ subcheck.classList.add("indent");
+ document.l10n.setAttributes(subcheck, nested.titleString);
+ linkPref(subcheck, nested.name, "bool");
+ subChecks.push(subcheck);
+ subcheck.disabled = !pref._value;
+ subcheck.hidden = nested.hidden;
+ });
+
+ // Disable any nested checkboxes if the parent pref is not enabled.
+ pref.on("change", () => {
+ subChecks.forEach(subcheck => {
+ subcheck.disabled = !pref._value;
+ });
+ });
+ });
+
+ // Update the visibility of the Restore Defaults btn based on checked prefs
+ gHomePane.toggleRestoreDefaultsBtn();
+ }
+};
+
+this.PREFERENCES_LOADED_EVENT = PREFERENCES_LOADED_EVENT;
+const EXPORTED_SYMBOLS = ["AboutPreferences", "PREFERENCES_LOADED_EVENT"];
diff --git a/browser/components/newtab/lib/ActivityStream.jsm b/browser/components/newtab/lib/ActivityStream.jsm
new file mode 100644
index 0000000000..c180d6a3f3
--- /dev/null
+++ b/browser/components/newtab/lib/ActivityStream.jsm
@@ -0,0 +1,842 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
+const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
+
+ChromeUtils.defineModuleGetter(
+ this,
+ "AppConstants",
+ "resource://gre/modules/AppConstants.jsm"
+);
+
+ChromeUtils.defineModuleGetter(
+ this,
+ "DEFAULT_SITES",
+ "resource://activity-stream/lib/DefaultSites.jsm"
+);
+
+ChromeUtils.defineModuleGetter(
+ this,
+ "Region",
+ "resource://gre/modules/Region.jsm"
+);
+
+// NB: Eagerly load modules that will be loaded/constructed/initialized in the
+// common case to avoid the overhead of wrapping and detecting lazy loading.
+const { actionCreators: ac, actionTypes: at } = ChromeUtils.import(
+ "resource://activity-stream/common/Actions.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "AboutPreferences",
+ "resource://activity-stream/lib/AboutPreferences.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "DefaultPrefs",
+ "resource://activity-stream/lib/ActivityStreamPrefs.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "NewTabInit",
+ "resource://activity-stream/lib/NewTabInit.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "SectionsFeed",
+ "resource://activity-stream/lib/SectionsManager.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "RecommendationProviderSwitcher",
+ "resource://activity-stream/lib/RecommendationProviderSwitcher.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "PlacesFeed",
+ "resource://activity-stream/lib/PlacesFeed.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "PrefsFeed",
+ "resource://activity-stream/lib/PrefsFeed.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "Store",
+ "resource://activity-stream/lib/Store.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "SystemTickFeed",
+ "resource://activity-stream/lib/SystemTickFeed.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "TelemetryFeed",
+ "resource://activity-stream/lib/TelemetryFeed.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "FaviconFeed",
+ "resource://activity-stream/lib/FaviconFeed.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "TopSitesFeed",
+ "resource://activity-stream/lib/TopSitesFeed.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "TopStoriesFeed",
+ "resource://activity-stream/lib/TopStoriesFeed.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "HighlightsFeed",
+ "resource://activity-stream/lib/HighlightsFeed.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "DiscoveryStreamFeed",
+ "resource://activity-stream/lib/DiscoveryStreamFeed.jsm"
+);
+
+const REGION_STORIES_CONFIG =
+ "browser.newtabpage.activity-stream.discoverystream.region-stories-config";
+const REGION_STORIES_BLOCK =
+ "browser.newtabpage.activity-stream.discoverystream.region-stories-block";
+const REGION_SPOCS_CONFIG =
+ "browser.newtabpage.activity-stream.discoverystream.region-spocs-config";
+const REGION_BASIC_CONFIG =
+ "browser.newtabpage.activity-stream.discoverystream.region-basic-config";
+const LOCALE_LIST_CONFIG =
+ "browser.newtabpage.activity-stream.discoverystream.locale-list-config";
+
+// Determine if spocs should be shown for a geo/locale
+function showSpocs({ geo }) {
+ const spocsGeoString =
+ Services.prefs.getStringPref(REGION_SPOCS_CONFIG) || "";
+ const spocsGeo = spocsGeoString.split(",").map(s => s.trim());
+ return spocsGeo.includes(geo);
+}
+
+// Configure default Activity Stream prefs with a plain `value` or a `getValue`
+// that computes a value. A `value_local_dev` is used for development defaults.
+const PREFS_CONFIG = new Map([
+ [
+ "default.sites",
+ {
+ title:
+ "Comma-separated list of default top sites to fill in behind visited sites",
+ getValue: ({ geo }) =>
+ DEFAULT_SITES.get(DEFAULT_SITES.has(geo) ? geo : ""),
+ },
+ ],
+ [
+ "feeds.section.topstories.options",
+ {
+ title: "Configuration options for top stories feed",
+ // This is a dynamic pref as it depends on the feed being shown or not
+ getValue: args =>
+ JSON.stringify({
+ api_key_pref: "extensions.pocket.oAuthConsumerKey",
+ // Use the opposite value as what default value the feed would have used
+ hidden: !PREFS_CONFIG.get("feeds.system.topstories").getValue(args),
+ provider_icon: "pocket",
+ provider_name: "Pocket",
+ read_more_endpoint:
+ "https://getpocket.com/explore/trending?src=fx_new_tab",
+ stories_endpoint: `https://getpocket.cdn.mozilla.net/v3/firefox/global-recs?version=3&consumer_key=$apiKey&locale_lang=${
+ args.locale
+ }&feed_variant=${
+ showSpocs(args) ? "default_spocs_on" : "default_spocs_off"
+ }`,
+ stories_referrer: "https://getpocket.com/recommendations",
+ topics_endpoint: `https://getpocket.cdn.mozilla.net/v3/firefox/trending-topics?version=2&consumer_key=$apiKey&locale_lang=${args.locale}`,
+ model_keys: [
+ "nmf_model_animals",
+ "nmf_model_business",
+ "nmf_model_career",
+ "nmf_model_datascience",
+ "nmf_model_design",
+ "nmf_model_education",
+ "nmf_model_entertainment",
+ "nmf_model_environment",
+ "nmf_model_fashion",
+ "nmf_model_finance",
+ "nmf_model_food",
+ "nmf_model_health",
+ "nmf_model_home",
+ "nmf_model_life",
+ "nmf_model_marketing",
+ "nmf_model_politics",
+ "nmf_model_programming",
+ "nmf_model_science",
+ "nmf_model_shopping",
+ "nmf_model_sports",
+ "nmf_model_tech",
+ "nmf_model_travel",
+ "nb_model_animals",
+ "nb_model_books",
+ "nb_model_business",
+ "nb_model_career",
+ "nb_model_datascience",
+ "nb_model_design",
+ "nb_model_economics",
+ "nb_model_education",
+ "nb_model_entertainment",
+ "nb_model_environment",
+ "nb_model_fashion",
+ "nb_model_finance",
+ "nb_model_food",
+ "nb_model_game",
+ "nb_model_health",
+ "nb_model_history",
+ "nb_model_home",
+ "nb_model_life",
+ "nb_model_marketing",
+ "nb_model_military",
+ "nb_model_philosophy",
+ "nb_model_photography",
+ "nb_model_politics",
+ "nb_model_productivity",
+ "nb_model_programming",
+ "nb_model_psychology",
+ "nb_model_science",
+ "nb_model_shopping",
+ "nb_model_society",
+ "nb_model_space",
+ "nb_model_sports",
+ "nb_model_tech",
+ "nb_model_travel",
+ "nb_model_writing",
+ ],
+ show_spocs: showSpocs(args),
+ personalized: true,
+ version: 1,
+ }),
+ },
+ ],
+ [
+ "feeds.topsites",
+ {
+ title: "Displays Top Sites on the New Tab Page",
+ value: true,
+ },
+ ],
+ [
+ "hideTopSitesTitle",
+ {
+ title:
+ "Hide the top sites section's title, including the section and collapse icons",
+ value: false,
+ },
+ ],
+ [
+ "showSponsored",
+ {
+ title:
+ "Show sponsored cards in spoc experiment (show_spocs in topstories.options has to be set to true as well)",
+ value: true,
+ },
+ ],
+ [
+ "showSponsoredTopSites",
+ {
+ title: "Show sponsored top sites",
+ value: true,
+ },
+ ],
+ [
+ "pocketCta",
+ {
+ title: "Pocket cta and button for logged out users.",
+ value: JSON.stringify({
+ cta_button: "",
+ cta_text: "",
+ cta_url: "",
+ use_cta: false,
+ }),
+ },
+ ],
+ [
+ "filterAdult",
+ {
+ title: "Remove adult pages from sites, highlights, etc.",
+ value: true,
+ },
+ ],
+ [
+ "showSearch",
+ {
+ title: "Show the Search bar",
+ value: true,
+ },
+ ],
+ [
+ "feeds.snippets",
+ {
+ title: "Show snippets on activity stream",
+ value: true,
+ },
+ ],
+ [
+ "topSitesRows",
+ {
+ title: "Number of rows of Top Sites to display",
+ value: 1,
+ },
+ ],
+ [
+ "telemetry",
+ {
+ title: "Enable system error and usage data collection",
+ value: true,
+ value_local_dev: false,
+ },
+ ],
+ [
+ "telemetry.ut.events",
+ {
+ title: "Enable Unified Telemetry event data collection",
+ value: AppConstants.EARLY_BETA_OR_EARLIER,
+ value_local_dev: false,
+ },
+ ],
+ [
+ "telemetry.structuredIngestion.endpoint",
+ {
+ title: "Structured Ingestion telemetry server endpoint",
+ value: "https://incoming.telemetry.mozilla.org/submit",
+ },
+ ],
+ [
+ "section.highlights.includeVisited",
+ {
+ title:
+ "Boolean flag that decides whether or not to show visited pages in highlights.",
+ value: true,
+ },
+ ],
+ [
+ "section.highlights.includeBookmarks",
+ {
+ title:
+ "Boolean flag that decides whether or not to show bookmarks in highlights.",
+ value: true,
+ },
+ ],
+ [
+ "section.highlights.includePocket",
+ {
+ title:
+ "Boolean flag that decides whether or not to show saved Pocket stories in highlights.",
+ value: true,
+ },
+ ],
+ [
+ "section.highlights.includeDownloads",
+ {
+ title:
+ "Boolean flag that decides whether or not to show saved recent Downloads in highlights.",
+ value: true,
+ },
+ ],
+ [
+ "section.highlights.rows",
+ {
+ title: "Number of rows of Highlights to display",
+ value: 1,
+ },
+ ],
+ [
+ "section.topstories.rows",
+ {
+ title: "Number of rows of Top Stories to display",
+ value: 1,
+ },
+ ],
+ [
+ "sectionOrder",
+ {
+ title: "The rendering order for the sections",
+ value: "topsites,topstories,highlights",
+ },
+ ],
+ [
+ "improvesearch.noDefaultSearchTile",
+ {
+ title: "Remove tiles that are the same as the default search",
+ value: true,
+ },
+ ],
+ [
+ "improvesearch.topSiteSearchShortcuts.searchEngines",
+ {
+ title:
+ "An ordered, comma-delimited list of search shortcuts that we should try and pin",
+ // This pref is dynamic as the shortcuts vary depending on the region
+ getValue: ({ geo }) => {
+ if (!geo) {
+ return "";
+ }
+ const searchShortcuts = [];
+ if (geo === "CN") {
+ searchShortcuts.push("baidu");
+ } else if (["BY", "KZ", "RU", "TR"].includes(geo)) {
+ searchShortcuts.push("yandex");
+ } else {
+ searchShortcuts.push("google");
+ }
+ if (["DE", "FR", "GB", "IT", "JP", "US"].includes(geo)) {
+ searchShortcuts.push("amazon");
+ }
+ return searchShortcuts.join(",");
+ },
+ },
+ ],
+ [
+ "improvesearch.topSiteSearchShortcuts.havePinned",
+ {
+ title:
+ "A comma-delimited list of search shortcuts that have previously been pinned",
+ value: "",
+ },
+ ],
+ [
+ "asrouter.devtoolsEnabled",
+ {
+ title: "Are the asrouter devtools enabled?",
+ value: false,
+ },
+ ],
+ [
+ "asrouter.providers.onboarding",
+ {
+ title: "Configuration for onboarding provider",
+ value: JSON.stringify({
+ id: "onboarding",
+ type: "local",
+ localProvider: "OnboardingMessageProvider",
+ enabled: true,
+ // Block specific messages from this local provider
+ exclude: [],
+ }),
+ },
+ ],
+ [
+ "asrouter.providers.cfr-fxa",
+ {
+ title: "Configuration for CFR FxA Messages provider",
+ value: JSON.stringify({
+ id: "cfr-fxa",
+ enabled: true,
+ type: "remote-settings",
+ bucket: "cfr-fxa",
+ updateCycleInMs: 3600000,
+ }),
+ },
+ ],
+ // See browser/app/profile/firefox.js for other ASR preferences. They must be defined there to enable roll-outs.
+ [
+ "discoverystream.flight.blocks",
+ {
+ title: "Track flight blocks",
+ skipBroadcast: true,
+ value: "{}",
+ },
+ ],
+ [
+ "discoverystream.config",
+ {
+ title: "Configuration for the new pocket new tab",
+ getValue: ({ geo, locale }) => {
+ return JSON.stringify({
+ api_key_pref: "extensions.pocket.oAuthConsumerKey",
+ collapsible: true,
+ enabled: true,
+ show_spocs: showSpocs({ geo }),
+ hardcoded_layout: true,
+ personalized: true,
+ // This is currently an exmple layout used for dev purposes.
+ layout_endpoint:
+ "https://getpocket.cdn.mozilla.net/v3/newtab/layout?version=1&consumer_key=$apiKey&layout_variant=basic",
+ });
+ },
+ },
+ ],
+ [
+ "discoverystream.endpoints",
+ {
+ title:
+ "Endpoint prefixes (comma-separated) that are allowed to be requested",
+ value: "https://getpocket.cdn.mozilla.net/,https://spocs.getpocket.com/",
+ },
+ ],
+ [
+ "discoverystream.engagementLabelEnabled",
+ {
+ title:
+ "Allow the display of engagement labels for discovery stream components (eg: Trending, Popular, etc)",
+ value: false,
+ },
+ ],
+ [
+ "discoverystream.isCollectionDismissible",
+ {
+ title: "Allows Pocket story collections to be dismissed",
+ value: false,
+ },
+ ],
+ [
+ "discoverystream.region-basic-layout",
+ {
+ title: "Decision to use basic layout based on region.",
+ getValue: ({ geo }) => {
+ const preffedRegionsString =
+ Services.prefs.getStringPref(REGION_BASIC_CONFIG) || "";
+ // If no regions are set to basic,
+ // we don't need to bother checking against the region.
+ // We are also not concerned if geo is not set,
+ // because stories are going to be empty until we have geo.
+ if (!preffedRegionsString) {
+ return false;
+ }
+ const preffedRegions = preffedRegionsString
+ .split(",")
+ .map(s => s.trim());
+
+ return preffedRegions.includes(geo);
+ },
+ },
+ ],
+ [
+ "discoverystream.spoc.impressions",
+ {
+ title: "Track spoc impressions",
+ skipBroadcast: true,
+ value: "{}",
+ },
+ ],
+ [
+ "discoverystream.endpointSpocsClear",
+ {
+ title:
+ "Endpoint for when a user opts-out of sponsored content to delete the user's data from the ad server.",
+ value: "https://spocs.getpocket.com/user",
+ },
+ ],
+ [
+ "discoverystream.rec.impressions",
+ {
+ title: "Track rec impressions",
+ skipBroadcast: true,
+ value: "{}",
+ },
+ ],
+]);
+
+// Array of each feed's FEEDS_CONFIG factory and values to add to PREFS_CONFIG
+const FEEDS_DATA = [
+ {
+ name: "aboutpreferences",
+ factory: () => new AboutPreferences(),
+ title: "about:preferences rendering",
+ value: true,
+ },
+ {
+ name: "newtabinit",
+ factory: () => new NewTabInit(),
+ title: "Sends a copy of the state to each new tab that is opened",
+ value: true,
+ },
+ {
+ name: "places",
+ factory: () => new PlacesFeed(),
+ title: "Listens for and relays various Places-related events",
+ value: true,
+ },
+ {
+ name: "prefs",
+ factory: () => new PrefsFeed(PREFS_CONFIG),
+ title: "Preferences",
+ value: true,
+ },
+ {
+ name: "sections",
+ factory: () => new SectionsFeed(),
+ title: "Manages sections",
+ value: true,
+ },
+ {
+ name: "section.highlights",
+ factory: () => new HighlightsFeed(),
+ title: "Fetches content recommendations from places db",
+ value: true,
+ },
+ {
+ name: "system.topstories",
+ factory: () =>
+ new TopStoriesFeed(PREFS_CONFIG.get("discoverystream.config")),
+ title:
+ "System pref that fetches content recommendations from a configurable content provider",
+ // Dynamically determine if Pocket should be shown for a geo / locale
+ getValue: ({ geo, locale }) => {
+ // If we don't have geo, we don't want to flash the screen with stories while geo loads.
+ // Best to display nothing until geo is ready.
+ if (!geo) {
+ return false;
+ }
+ const preffedRegionsBlockString =
+ Services.prefs.getStringPref(REGION_STORIES_BLOCK) || "";
+ const preffedRegionsString =
+ Services.prefs.getStringPref(REGION_STORIES_CONFIG) || "";
+ const preffedLocaleListString =
+ Services.prefs.getStringPref(LOCALE_LIST_CONFIG) || "";
+ const preffedBlockRegions = preffedRegionsBlockString
+ .split(",")
+ .map(s => s.trim());
+ const preffedRegions = preffedRegionsString.split(",").map(s => s.trim());
+ const preffedLocales = preffedLocaleListString
+ .split(",")
+ .map(s => s.trim());
+ const locales = {
+ US: ["en-CA", "en-GB", "en-US"],
+ CA: ["en-CA", "en-GB", "en-US"],
+ GB: ["en-CA", "en-GB", "en-US"],
+ AU: ["en-CA", "en-GB", "en-US"],
+ NZ: ["en-CA", "en-GB", "en-US"],
+ IN: ["en-CA", "en-GB", "en-US"],
+ IE: ["en-CA", "en-GB", "en-US"],
+ ZA: ["en-CA", "en-GB", "en-US"],
+ CH: ["de"],
+ BE: ["de"],
+ DE: ["de"],
+ AT: ["de"],
+ IT: ["it"],
+ FR: ["fr"],
+ ES: ["es"],
+ PL: ["pl"],
+ JP: ["ja", "ja-JP-mac"],
+ }[geo];
+
+ const regionBlocked = preffedBlockRegions.includes(geo);
+ const localeEnabled = locale && preffedLocales.includes(locale);
+ const regionEnabled =
+ preffedRegions.includes(geo) && !!locales && locales.includes(locale);
+ return !regionBlocked && (localeEnabled || regionEnabled);
+ },
+ },
+ {
+ name: "systemtick",
+ factory: () => new SystemTickFeed(),
+ title: "Produces system tick events to periodically check for data expiry",
+ value: true,
+ },
+ {
+ name: "telemetry",
+ factory: () => new TelemetryFeed(),
+ title: "Relays telemetry-related actions to PingCentre",
+ value: true,
+ },
+ {
+ name: "favicon",
+ factory: () => new FaviconFeed(),
+ title: "Fetches tippy top manifests from remote service",
+ value: true,
+ },
+ {
+ name: "system.topsites",
+ factory: () => new TopSitesFeed(),
+ title: "Queries places and gets metadata for Top Sites section",
+ value: true,
+ },
+ {
+ name: "recommendationproviderswitcher",
+ factory: () => new RecommendationProviderSwitcher(),
+ title: "Handles switching between two types of personality providers",
+ value: true,
+ },
+ {
+ name: "discoverystreamfeed",
+ factory: () => new DiscoveryStreamFeed(),
+ title: "Handles new pocket ui for the new tab page",
+ value: true,
+ },
+];
+
+const FEEDS_CONFIG = new Map();
+for (const config of FEEDS_DATA) {
+ const pref = `feeds.${config.name}`;
+ FEEDS_CONFIG.set(pref, config.factory);
+ PREFS_CONFIG.set(pref, config);
+}
+
+this.ActivityStream = class ActivityStream {
+ /**
+ * constructor - Initializes an instance of ActivityStream
+ */
+ constructor() {
+ this.initialized = false;
+ this.store = new Store();
+ this.feeds = FEEDS_CONFIG;
+ this._defaultPrefs = new DefaultPrefs(PREFS_CONFIG);
+ }
+
+ init() {
+ try {
+ this._updateDynamicPrefs();
+ this._defaultPrefs.init();
+
+ // Look for outdated user pref values that might have been accidentally
+ // persisted when restoring the original pref value at the end of an
+ // experiment across versions with a different default value.
+ const DS_CONFIG =
+ "browser.newtabpage.activity-stream.discoverystream.config";
+ if (
+ Services.prefs.prefHasUserValue(DS_CONFIG) &&
+ [
+ // Firefox 66
+ `{"api_key_pref":"extensions.pocket.oAuthConsumerKey","enabled":false,"show_spocs":true,"layout_endpoint":"https://getpocket.com/v3/newtab/layout?version=1&consumer_key=$apiKey&layout_variant=basic"}`,
+ // Firefox 67
+ `{"api_key_pref":"extensions.pocket.oAuthConsumerKey","enabled":false,"show_spocs":true,"layout_endpoint":"https://getpocket.cdn.mozilla.net/v3/newtab/layout?version=1&consumer_key=$apiKey&layout_variant=basic"}`,
+ // Firefox 68
+ `{"api_key_pref":"extensions.pocket.oAuthConsumerKey","collapsible":true,"enabled":false,"show_spocs":true,"hardcoded_layout":true,"personalized":false,"layout_endpoint":"https://getpocket.cdn.mozilla.net/v3/newtab/layout?version=1&consumer_key=$apiKey&layout_variant=basic"}`,
+ ].includes(Services.prefs.getStringPref(DS_CONFIG))
+ ) {
+ Services.prefs.clearUserPref(DS_CONFIG);
+ }
+
+ // Hook up the store and let all feeds and pages initialize
+ this.store.init(
+ this.feeds,
+ ac.BroadcastToContent({
+ type: at.INIT,
+ data: {
+ locale: this.locale,
+ },
+ meta: {
+ isStartup: true,
+ },
+ }),
+ { type: at.UNINIT }
+ );
+
+ this.initialized = true;
+ } catch (e) {
+ // TelemetryFeed could be unavailable if the telemetry is disabled, or
+ // the telemetry feed is not yet initialized.
+ const telemetryFeed = this.store.feeds.get("feeds.telemetry");
+ if (telemetryFeed) {
+ telemetryFeed.handleUndesiredEvent({
+ data: { event: "ADDON_INIT_FAILED" },
+ });
+ }
+ throw e;
+ }
+ }
+
+ /**
+ * Check if an old pref has a custom value to migrate. Clears the pref so that
+ * it's the default after migrating (to avoid future need to migrate).
+ *
+ * @param oldPrefName {string} Pref to check and migrate
+ * @param cbIfNotDefault {function} Callback that gets the current pref value
+ */
+ _migratePref(oldPrefName, cbIfNotDefault) {
+ // Nothing to do if the user doesn't have a custom value
+ if (!Services.prefs.prefHasUserValue(oldPrefName)) {
+ return;
+ }
+
+ // Figure out what kind of pref getter to use
+ let prefGetter;
+ switch (Services.prefs.getPrefType(oldPrefName)) {
+ case Services.prefs.PREF_BOOL:
+ prefGetter = "getBoolPref";
+ break;
+ case Services.prefs.PREF_INT:
+ prefGetter = "getIntPref";
+ break;
+ case Services.prefs.PREF_STRING:
+ prefGetter = "getStringPref";
+ break;
+ }
+
+ // Give the callback the current value then clear the pref
+ cbIfNotDefault(Services.prefs[prefGetter](oldPrefName));
+ Services.prefs.clearUserPref(oldPrefName);
+ }
+
+ uninit() {
+ if (this.geo === "") {
+ Services.obs.removeObserver(this, Region.REGION_TOPIC);
+ }
+
+ this.store.uninit();
+ this.initialized = false;
+ }
+
+ _updateDynamicPrefs() {
+ // Save the geo pref if we have it
+ if (Region.home) {
+ this.geo = Region.home;
+ } else if (this.geo !== "") {
+ // Watch for geo changes and use a dummy value for now
+ Services.obs.addObserver(this, Region.REGION_TOPIC);
+ this.geo = "";
+ }
+
+ this.locale = Services.locale.appLocaleAsBCP47;
+
+ // Update the pref config of those with dynamic values
+ for (const pref of PREFS_CONFIG.keys()) {
+ // Only need to process dynamic prefs
+ const prefConfig = PREFS_CONFIG.get(pref);
+ if (!prefConfig.getValue) {
+ continue;
+ }
+
+ // Have the dynamic pref just reuse using existing default, e.g., those
+ // set via Autoconfig or policy
+ try {
+ const existingDefault = this._defaultPrefs.get(pref);
+ if (existingDefault !== undefined && prefConfig.value === undefined) {
+ prefConfig.getValue = () => existingDefault;
+ }
+ } catch (ex) {
+ // We get NS_ERROR_UNEXPECTED for prefs that have a user value (causing
+ // default branch to believe there's a type) but no actual default value
+ }
+
+ // Compute the dynamic value (potentially generic based on dummy geo)
+ const newValue = prefConfig.getValue({
+ geo: this.geo,
+ locale: this.locale,
+ });
+
+ // If there's an existing value and it has changed, that means we need to
+ // overwrite the default with the new value.
+ if (prefConfig.value !== undefined && prefConfig.value !== newValue) {
+ this._defaultPrefs.set(pref, newValue);
+ }
+
+ prefConfig.value = newValue;
+ }
+ }
+
+ observe(subject, topic, data) {
+ switch (topic) {
+ case Region.REGION_TOPIC:
+ if (data === Region.REGION_UPDATED) {
+ this._updateDynamicPrefs();
+ }
+ break;
+ }
+ }
+};
+
+const EXPORTED_SYMBOLS = ["ActivityStream", "PREFS_CONFIG"];
diff --git a/browser/components/newtab/lib/ActivityStreamMessageChannel.jsm b/browser/components/newtab/lib/ActivityStreamMessageChannel.jsm
new file mode 100644
index 0000000000..5d6ce82207
--- /dev/null
+++ b/browser/components/newtab/lib/ActivityStreamMessageChannel.jsm
@@ -0,0 +1,344 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+// TODO delete this?
+
+ChromeUtils.defineModuleGetter(
+ this,
+ "AboutNewTab",
+ "resource:///modules/AboutNewTab.jsm"
+);
+
+ChromeUtils.defineModuleGetter(
+ this,
+ "AboutHomeStartupCache",
+ "resource:///modules/BrowserGlue.jsm"
+);
+
+const { RemotePages } = ChromeUtils.import(
+ "resource://gre/modules/remotepagemanager/RemotePageManagerParent.jsm"
+);
+
+const {
+ actionCreators: ac,
+ actionTypes: at,
+ actionUtils: au,
+} = ChromeUtils.import("resource://activity-stream/common/Actions.jsm");
+
+const ABOUT_NEW_TAB_URL = "about:newtab";
+const ABOUT_HOME_URL = "about:home";
+
+const DEFAULT_OPTIONS = {
+ dispatch(action) {
+ throw new Error(
+ `\nMessageChannel: Received action ${action.type}, but no dispatcher was defined.\n`
+ );
+ },
+ pageURL: ABOUT_NEW_TAB_URL,
+ outgoingMessageName: "ActivityStream:MainToContent",
+ incomingMessageName: "ActivityStream:ContentToMain",
+};
+
+this.ActivityStreamMessageChannel = class ActivityStreamMessageChannel {
+ /**
+ * ActivityStreamMessageChannel - This module connects a Redux store to a RemotePageManager in Firefox.
+ * Call .createChannel to start the connection, and .destroyChannel to destroy it.
+ * You should use the BroadcastToContent, AlsoToOneContent, and AlsoToMain action creators
+ * in common/Actions.jsm to help you create actions that will be automatically routed
+ * to the correct location.
+ *
+ * @param {object} options
+ * @param {function} options.dispatch The dispatch method from a Redux store
+ * @param {string} options.pageURL The URL to which a RemotePageManager should be attached.
+ * Note that if it is about:newtab, the existing RemotePageManager
+ * for about:newtab will also be disabled
+ * @param {string} options.outgoingMessageName The name of the message sent to child processes
+ * @param {string} options.incomingMessageName The name of the message received from child processes
+ * @return {ActivityStreamMessageChannel}
+ */
+ constructor(options = {}) {
+ Object.assign(this, DEFAULT_OPTIONS, options);
+ this.channel = null;
+
+ this.middleware = this.middleware.bind(this);
+ this.onMessage = this.onMessage.bind(this);
+ this.onNewTabLoad = this.onNewTabLoad.bind(this);
+ this.onNewTabUnload = this.onNewTabUnload.bind(this);
+ this.onNewTabInit = this.onNewTabInit.bind(this);
+ }
+
+ /**
+ * middleware - Redux middleware that looks for AlsoToOneContent and BroadcastToContent type
+ * actions, and sends them out.
+ *
+ * @param {object} store A redux store
+ * @return {function} Redux middleware
+ */
+ middleware(store) {
+ return next => action => {
+ const skipMain = action.meta && action.meta.skipMain;
+ if (!this.channel && !skipMain) {
+ next(action);
+ return;
+ }
+ if (au.isSendToOneContent(action)) {
+ this.send(action);
+ } else if (au.isBroadcastToContent(action)) {
+ this.broadcast(action);
+ } else if (au.isSendToPreloaded(action)) {
+ this.sendToPreloaded(action);
+ }
+
+ if (!skipMain) {
+ next(action);
+ }
+ };
+ }
+
+ /**
+ * onActionFromContent - Handler for actions from a content processes
+ *
+ * @param {object} action A Redux action
+ * @param {string} targetId The portID of the port that sent the message
+ */
+ onActionFromContent(action, targetId) {
+ this.dispatch(ac.AlsoToMain(action, this.validatePortID(targetId)));
+ }
+
+ /**
+ * broadcast - Sends an action to all ports
+ *
+ * @param {object} action A Redux action
+ */
+ broadcast(action) {
+ // We're trying to update all tabs, so signal the AboutHomeStartupCache
+ // that its likely time to refresh the cache.
+ AboutHomeStartupCache.onPreloadedNewTabMessage();
+
+ this.channel.sendAsyncMessage(this.outgoingMessageName, action);
+ }
+
+ /**
+ * send - Sends an action to a specific port
+ *
+ * @param {obj} action A redux action; it should contain a portID in the meta.toTarget property
+ */
+ send(action) {
+ const targetId = action.meta && action.meta.toTarget;
+ const target = this.getTargetById(targetId);
+ try {
+ target.sendAsyncMessage(this.outgoingMessageName, action);
+ } catch (e) {
+ // The target page is closed/closing by the user or test, so just ignore.
+ }
+ }
+
+ /**
+ * A valid portID is a combination of process id and port
+ * https://searchfox.org/mozilla-central/rev/196560b95f191b48ff7cba7c2ba9237bba6b5b6a/toolkit/components/remotepagemanager/RemotePageManagerChild.jsm#14
+ */
+ validatePortID(id) {
+ if (typeof id !== "string" || !id.includes(":")) {
+ Cu.reportError("Invalid portID");
+ }
+
+ return id;
+ }
+
+ /**
+ * getIdByTarget - Retrieve the id of a message target, if it exists in this.targets
+ *
+ * @param {obj} targetObj A message target
+ * @return {string|null} The unique id of the target, if it exists.
+ */
+ getTargetById(id) {
+ this.validatePortID(id);
+ for (let port of this.channel.messagePorts) {
+ if (port.portID === id) {
+ return port;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * sendToPreloaded - Sends an action to each preloaded browser, if any
+ *
+ * @param {obj} action A redux action
+ */
+ sendToPreloaded(action) {
+ // We're trying to update the preloaded about:newtab, so signal
+ // the AboutHomeStartupCache that its likely time to refresh
+ // the cache.
+ AboutHomeStartupCache.onPreloadedNewTabMessage();
+
+ const preloadedBrowsers = this.getPreloadedBrowser();
+ if (preloadedBrowsers && action.data) {
+ for (let preloadedBrowser of preloadedBrowsers) {
+ try {
+ preloadedBrowser.sendAsyncMessage(this.outgoingMessageName, action);
+ } catch (e) {
+ // The preloaded page is no longer available, so just ignore.
+ }
+ }
+ }
+ }
+
+ /**
+ * getPreloadedBrowser - Retrieve the port of any preloaded browsers
+ *
+ * @return {Array|null} An array of ports belonging to the preloaded browsers, or null
+ * if there aren't any preloaded browsers
+ */
+ getPreloadedBrowser() {
+ let preloadedPorts = [];
+ for (let port of this.channel.messagePorts) {
+ if (this.isPreloadedBrowser(port.browser)) {
+ preloadedPorts.push(port);
+ }
+ }
+ return preloadedPorts.length ? preloadedPorts : null;
+ }
+
+ /**
+ * isPreloadedBrowser - Returns true if the passed browser has been preloaded
+ * for faster rendering of new tabs.
+ *
+ * @param {<browser>} A <browser> to check.
+ * @return {bool} True if the browser is preloaded.
+ * if there aren't any preloaded browsers
+ */
+ isPreloadedBrowser(browser) {
+ return browser.getAttribute("preloadedState") === "preloaded";
+ }
+
+ /**
+ * createChannel - Create RemotePages channel to establishing message passing
+ * between the main process and child pages
+ */
+ createChannel() {
+ // Receive AboutNewTab's Remote Pages instance, if it exists, on override
+ const channel =
+ this.pageURL === ABOUT_NEW_TAB_URL &&
+ AboutNewTab.overridePageListener(true);
+ this.channel =
+ channel || new RemotePages([ABOUT_HOME_URL, ABOUT_NEW_TAB_URL]);
+ this.channel.addMessageListener("RemotePage:Init", this.onNewTabInit);
+ this.channel.addMessageListener("RemotePage:Load", this.onNewTabLoad);
+ this.channel.addMessageListener("RemotePage:Unload", this.onNewTabUnload);
+ this.channel.addMessageListener(this.incomingMessageName, this.onMessage);
+ }
+
+ simulateMessagesForExistingTabs() {
+ // Some pages might have already loaded, so we won't get the usual message
+ for (const target of this.channel.messagePorts) {
+ const simulatedMsg = {
+ target: Object.assign({ simulated: true }, target),
+ };
+ this.onNewTabInit(simulatedMsg);
+ if (target.loaded) {
+ this.onNewTabLoad(simulatedMsg);
+ }
+ }
+ }
+
+ /**
+ * destroyChannel - Destroys the RemotePages channel
+ */
+ destroyChannel() {
+ this.channel.removeMessageListener("RemotePage:Init", this.onNewTabInit);
+ this.channel.removeMessageListener("RemotePage:Load", this.onNewTabLoad);
+ this.channel.removeMessageListener(
+ "RemotePage:Unload",
+ this.onNewTabUnload
+ );
+ this.channel.removeMessageListener(
+ this.incomingMessageName,
+ this.onMessage
+ );
+ if (this.pageURL === ABOUT_NEW_TAB_URL) {
+ AboutNewTab.reset(this.channel);
+ } else {
+ this.channel.destroy();
+ }
+ this.channel = null;
+ }
+
+ /**
+ * onNewTabInit - Handler for special RemotePage:Init message fired
+ * by RemotePages
+ *
+ * @param {obj} msg The messsage from a page that was just initialized
+ */
+ onNewTabInit(msg) {
+ this.onActionFromContent(
+ {
+ type: at.NEW_TAB_INIT,
+ data: msg.target,
+ },
+ msg.target.portID
+ );
+ }
+
+ /**
+ * onNewTabLoad - Handler for special RemotePage:Load message fired by RemotePages
+ *
+ * @param {obj} msg The messsage from a page that was just loaded
+ */
+ onNewTabLoad(msg) {
+ let { browser } = msg.target;
+ if (
+ this.isPreloadedBrowser(browser) &&
+ browser.ownerGlobal.windowState !== browser.ownerGlobal.STATE_MINIMIZED &&
+ !browser.ownerGlobal.isFullyOccluded
+ ) {
+ // As a perceived performance optimization, if this loaded Activity Stream
+ // happens to be a preloaded browser in a window that is not minimized or
+ // occluded, have it render its layers to the compositor now to increase
+ // the odds that by the time we switch to the tab, the layers are already
+ // ready to present to the user.
+ browser.renderLayers = true;
+ }
+
+ this.onActionFromContent({ type: at.NEW_TAB_LOAD }, msg.target.portID);
+ }
+
+ /**
+ * onNewTabUnloadLoad - Handler for special RemotePage:Unload message fired by RemotePages
+ *
+ * @param {obj} msg The messsage from a page that was just unloaded
+ */
+ onNewTabUnload(msg) {
+ this.onActionFromContent({ type: at.NEW_TAB_UNLOAD }, msg.target.portID);
+ }
+
+ /**
+ * onMessage - Handles custom messages from content. It expects all messages to
+ * be formatted as Redux actions, and dispatches them to this.store
+ *
+ * @param {obj} msg A custom message from content
+ * @param {obj} msg.action A Redux action (e.g. {type: "HELLO_WORLD"})
+ * @param {obj} msg.target A message target
+ */
+ onMessage(msg) {
+ const { portID } = msg.target;
+ if (!msg.data || !msg.data.type) {
+ Cu.reportError(
+ new Error(`Received an improperly formatted message from ${portID}`)
+ );
+ return;
+ }
+ let action = {};
+ Object.assign(action, msg.data);
+ // target is used to access a browser reference that came from the content
+ // and should only be used in feeds (not reducers)
+ action._target = msg.target;
+ this.onActionFromContent(action, portID);
+ }
+};
+
+this.DEFAULT_OPTIONS = DEFAULT_OPTIONS;
+const EXPORTED_SYMBOLS = ["ActivityStreamMessageChannel", "DEFAULT_OPTIONS"];
diff --git a/browser/components/newtab/lib/ActivityStreamPrefs.jsm b/browser/components/newtab/lib/ActivityStreamPrefs.jsm
new file mode 100644
index 0000000000..55d5b05d4b
--- /dev/null
+++ b/browser/components/newtab/lib/ActivityStreamPrefs.jsm
@@ -0,0 +1,95 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
+const { AppConstants } = ChromeUtils.import(
+ "resource://gre/modules/AppConstants.jsm"
+);
+const { Preferences } = ChromeUtils.import(
+ "resource://gre/modules/Preferences.jsm"
+);
+
+const ACTIVITY_STREAM_PREF_BRANCH = "browser.newtabpage.activity-stream.";
+
+this.Prefs = class Prefs extends Preferences {
+ /**
+ * Prefs - A wrapper around Preferences that always sets the branch to
+ * ACTIVITY_STREAM_PREF_BRANCH
+ */
+ constructor(branch = ACTIVITY_STREAM_PREF_BRANCH) {
+ super({ branch });
+ this._branchObservers = new Map();
+ }
+
+ ignoreBranch(listener) {
+ const observer = this._branchObservers.get(listener);
+ this._prefBranch.removeObserver("", observer);
+ this._branchObservers.delete(listener);
+ }
+
+ observeBranch(listener) {
+ const observer = (subject, topic, pref) => {
+ listener.onPrefChanged(pref, this.get(pref));
+ };
+ this._prefBranch.addObserver("", observer);
+ this._branchObservers.set(listener, observer);
+ }
+};
+
+this.DefaultPrefs = class DefaultPrefs extends Preferences {
+ /**
+ * DefaultPrefs - A helper for setting and resetting default prefs for the add-on
+ *
+ * @param {Map} config A Map with {string} key of the pref name and {object}
+ * value with the following pref properties:
+ * {string} .title (optional) A description of the pref
+ * {bool|string|number} .value The default value for the pref
+ * @param {string} branch (optional) The pref branch (defaults to ACTIVITY_STREAM_PREF_BRANCH)
+ */
+ constructor(config, branch = ACTIVITY_STREAM_PREF_BRANCH) {
+ super({
+ branch,
+ defaultBranch: true,
+ });
+ this._config = config;
+ }
+
+ /**
+ * init - Set default prefs for all prefs in the config
+ */
+ init() {
+ // Local developer builds (with the default mozconfig) aren't OFFICIAL
+ const IS_UNOFFICIAL_BUILD = !AppConstants.MOZILLA_OFFICIAL;
+
+ for (const pref of this._config.keys()) {
+ try {
+ // Avoid replacing existing valid default pref values, e.g., those set
+ // via Autoconfig or policy
+ if (this.get(pref) !== undefined) {
+ continue;
+ }
+ } catch (ex) {
+ // We get NS_ERROR_UNEXPECTED for prefs that have a user value (causing
+ // default branch to believe there's a type) but no actual default value
+ }
+
+ const prefConfig = this._config.get(pref);
+ let value;
+ if (IS_UNOFFICIAL_BUILD && "value_local_dev" in prefConfig) {
+ value = prefConfig.value_local_dev;
+ } else {
+ value = prefConfig.value;
+ }
+
+ try {
+ this.set(pref, value);
+ } catch (ex) {
+ // Potentially the user somehow set an unexpected value type, so we fail
+ // to set a default of our expected type
+ }
+ }
+ }
+};
+
+const EXPORTED_SYMBOLS = ["DefaultPrefs", "Prefs"];
diff --git a/browser/components/newtab/lib/ActivityStreamStorage.jsm b/browser/components/newtab/lib/ActivityStreamStorage.jsm
new file mode 100644
index 0000000000..489cb452c0
--- /dev/null
+++ b/browser/components/newtab/lib/ActivityStreamStorage.jsm
@@ -0,0 +1,121 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+ChromeUtils.defineModuleGetter(
+ this,
+ "IndexedDB",
+ "resource://gre/modules/IndexedDB.jsm"
+);
+
+this.ActivityStreamStorage = class ActivityStreamStorage {
+ /**
+ * @param storeNames Array of strings used to create all the required stores
+ */
+ constructor({ storeNames, telemetry }) {
+ if (!storeNames) {
+ throw new Error("storeNames required");
+ }
+
+ this.dbName = "ActivityStream";
+ this.dbVersion = 3;
+ this.storeNames = storeNames;
+ this.telemetry = telemetry;
+ }
+
+ get db() {
+ return this._db || (this._db = this.createOrOpenDb());
+ }
+
+ /**
+ * Public method that binds the store required by the consumer and exposes
+ * the private db getters and setters.
+ *
+ * @param storeName String name of desired store
+ */
+ getDbTable(storeName) {
+ if (this.storeNames.includes(storeName)) {
+ return {
+ get: this._get.bind(this, storeName),
+ getAll: this._getAll.bind(this, storeName),
+ set: this._set.bind(this, storeName),
+ };
+ }
+
+ throw new Error(`Store name ${storeName} does not exist.`);
+ }
+
+ async _getStore(storeName) {
+ return (await this.db).objectStore(storeName, "readwrite");
+ }
+
+ _get(storeName, key) {
+ return this._requestWrapper(async () =>
+ (await this._getStore(storeName)).get(key)
+ );
+ }
+
+ _getAll(storeName) {
+ return this._requestWrapper(async () =>
+ (await this._getStore(storeName)).getAll()
+ );
+ }
+
+ _set(storeName, key, value) {
+ return this._requestWrapper(async () =>
+ (await this._getStore(storeName)).put(value, key)
+ );
+ }
+
+ _openDatabase() {
+ return IndexedDB.open(this.dbName, { version: this.dbVersion }, db => {
+ // If provided with array of objectStore names we need to create all the
+ // individual stores
+ this.storeNames.forEach(store => {
+ if (!db.objectStoreNames.contains(store)) {
+ this._requestWrapper(() => db.createObjectStore(store));
+ }
+ });
+ });
+ }
+
+ /**
+ * createOrOpenDb - Open a db (with this.dbName) if it exists.
+ * If it does not exist, create it.
+ * If an error occurs, deleted the db and attempt to
+ * re-create it.
+ * @returns Promise that resolves with a db instance
+ */
+ async createOrOpenDb() {
+ try {
+ const db = await this._openDatabase();
+ return db;
+ } catch (e) {
+ if (this.telemetry) {
+ this.telemetry.handleUndesiredEvent({ event: "INDEXEDDB_OPEN_FAILED" });
+ }
+ await IndexedDB.deleteDatabase(this.dbName);
+ return this._openDatabase();
+ }
+ }
+
+ async _requestWrapper(request) {
+ let result = null;
+ try {
+ result = await request();
+ } catch (e) {
+ if (this.telemetry) {
+ this.telemetry.handleUndesiredEvent({ event: "TRANSACTION_FAILED" });
+ }
+ throw e;
+ }
+
+ return result;
+ }
+};
+
+function getDefaultOptions(options) {
+ return { collapsed: !!options.collapsed };
+}
+
+const EXPORTED_SYMBOLS = ["ActivityStreamStorage", "getDefaultOptions"];
diff --git a/browser/components/newtab/lib/BookmarkPanelHub.jsm b/browser/components/newtab/lib/BookmarkPanelHub.jsm
new file mode 100644
index 0000000000..e426ea7ed6
--- /dev/null
+++ b/browser/components/newtab/lib/BookmarkPanelHub.jsm
@@ -0,0 +1,332 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
+ChromeUtils.defineModuleGetter(
+ this,
+ "FxAccounts",
+ "resource://gre/modules/FxAccounts.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "Services",
+ "resource://gre/modules/Services.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "PrivateBrowsingUtils",
+ "resource://gre/modules/PrivateBrowsingUtils.jsm"
+);
+
+class _BookmarkPanelHub {
+ constructor() {
+ this._id = "BookmarkPanelHub";
+ this._trigger = { id: "bookmark-panel" };
+ this._handleMessageRequest = null;
+ this._addImpression = null;
+ this._sendTelemetry = null;
+ this._initialized = false;
+ this._response = null;
+ this._l10n = null;
+
+ this.messageRequest = this.messageRequest.bind(this);
+ this.toggleRecommendation = this.toggleRecommendation.bind(this);
+ this.sendUserEventTelemetry = this.sendUserEventTelemetry.bind(this);
+ this.collapseMessage = this.collapseMessage.bind(this);
+ }
+
+ /**
+ * @param {function} handleMessageRequest
+ * @param {function} addImpression
+ * @param {function} sendTelemetry - Used for sending user telemetry information
+ */
+ init(handleMessageRequest, addImpression, sendTelemetry) {
+ this._handleMessageRequest = handleMessageRequest;
+ this._addImpression = addImpression;
+ this._sendTelemetry = sendTelemetry;
+ this._l10n = new DOMLocalization([]);
+ this._initialized = true;
+ }
+
+ uninit() {
+ this._l10n = null;
+ this._initialized = false;
+ this._handleMessageRequest = null;
+ this._addImpression = null;
+ this._sendTelemetry = null;
+ this._response = null;
+ }
+
+ /**
+ * Checks if a similar cached requests exists before forwarding the request
+ * to ASRouter. Caches only 1 request, unique identifier is `request.url`.
+ * Caching ensures we don't duplicate requests and telemetry pings.
+ * Return value is important for the caller to know if a message will be
+ * shown.
+ *
+ * @returns {obj|null} response object or null if no messages matched
+ */
+ async messageRequest(target, win) {
+ if (!this._initialized) {
+ return false;
+ }
+
+ if (
+ this._response &&
+ this._response.win === win &&
+ this._response.url === target.url &&
+ this._response.content
+ ) {
+ this.showMessage(this._response.content, target, win);
+ return true;
+ }
+
+ // If we didn't match on a previously cached request then make sure
+ // the container is empty
+ this._removeContainer(target);
+ const response = await this._handleMessageRequest({
+ triggerId: this._trigger.id,
+ });
+
+ return this.onResponse(response, target, win);
+ }
+
+ /**
+ * If the response contains a message render it and send an impression.
+ * Otherwise we remove the message from the container.
+ */
+ onResponse(response, target, win) {
+ this._response = {
+ ...response,
+ collapsed: false,
+ target,
+ win,
+ url: target.url,
+ };
+
+ if (response && response.content) {
+ // Only insert localization files if we need to show a message
+ win.MozXULElement.insertFTLIfNeeded("browser/newtab/asrouter.ftl");
+ win.MozXULElement.insertFTLIfNeeded("browser/branding/sync-brand.ftl");
+ this.showMessage(response.content, target, win);
+ this.sendImpression();
+ this.sendUserEventTelemetry("IMPRESSION", win);
+ } else {
+ this.hideMessage(target);
+ }
+
+ target.infoButton.disabled = !response;
+
+ return !!response;
+ }
+
+ showMessage(message, target, win) {
+ if (this._response && this._response.collapsed) {
+ this.toggleRecommendation(false);
+ return;
+ }
+
+ const createElement = elem =>
+ target.document.createElementNS("http://www.w3.org/1999/xhtml", elem);
+ let recommendation = target.container.querySelector("#cfrMessageContainer");
+ if (!recommendation) {
+ recommendation = createElement("div");
+ const headerContainer = createElement("div");
+ headerContainer.classList.add("cfrMessageHeader");
+ recommendation.setAttribute("id", "cfrMessageContainer");
+ recommendation.addEventListener("click", async e => {
+ target.hidePopup();
+ const url = await FxAccounts.config.promiseConnectAccountURI(
+ "bookmark"
+ );
+ win.ownerGlobal.openLinkIn(url, "tabshifted", {
+ private: false,
+ triggeringPrincipal: Services.scriptSecurityManager.createNullPrincipal(
+ {}
+ ),
+ csp: null,
+ });
+ this.sendUserEventTelemetry("CLICK", win);
+ });
+ recommendation.style.color = message.color;
+ recommendation.style.background = `linear-gradient(135deg, ${message.background_color_1} 0%, ${message.background_color_2} 70%)`;
+ const close = createElement("button");
+ close.setAttribute("id", "cfrClose");
+ close.setAttribute("aria-label", "close");
+ close.addEventListener("click", e => {
+ this.sendUserEventTelemetry("DISMISS", win);
+ this.collapseMessage();
+ target.close(e);
+ });
+ const title = createElement("h1");
+ title.setAttribute("id", "editBookmarkPanelRecommendationTitle");
+ const content = createElement("p");
+ content.setAttribute("id", "editBookmarkPanelRecommendationContent");
+ const cta = createElement("button");
+ cta.setAttribute("id", "editBookmarkPanelRecommendationCta");
+
+ // If `string_id` is present it means we are relying on fluent for translations
+ if (message.text.string_id) {
+ this._l10n.setAttributes(
+ close,
+ message.close_button.tooltiptext.string_id
+ );
+ this._l10n.setAttributes(title, message.title.string_id);
+ this._l10n.setAttributes(content, message.text.string_id);
+ this._l10n.setAttributes(cta, message.cta.string_id);
+ } else {
+ close.setAttribute("title", message.close_button.tooltiptext);
+ title.textContent = message.title;
+ content.textContent = message.text;
+ cta.textContent = message.cta;
+ }
+
+ headerContainer.appendChild(title);
+ headerContainer.appendChild(close);
+ recommendation.appendChild(headerContainer);
+ recommendation.appendChild(content);
+ recommendation.appendChild(cta);
+ target.container.appendChild(recommendation);
+ }
+
+ this.toggleRecommendation(true);
+ this._adjustPanelHeight(win, recommendation);
+ }
+
+ /**
+ * Adjust the size of the container for locales where the message is
+ * longer than the fixed 150px set for height
+ */
+ async _adjustPanelHeight(window, messageContainer) {
+ const { document } = window;
+ // Contains the screenshot of the page we are bookmarking
+ const screenshotContainer = document.getElementById(
+ "editBookmarkPanelImage"
+ );
+ // Wait for strings to be added which can change element height
+ await document.l10n.translateElements([messageContainer]);
+ window.requestAnimationFrame(() => {
+ let { height } = messageContainer.getBoundingClientRect();
+ if (height > 150) {
+ messageContainer.classList.add("longMessagePadding");
+ // Get the new value with the added padding
+ height = messageContainer.getBoundingClientRect().height;
+ // Needs to be adjusted to match the message height
+ screenshotContainer.style.height = `${height}px`;
+ }
+ });
+ }
+
+ /**
+ * Restore the panel back to the original size so the slide in
+ * animation can run again
+ */
+ _restorePanelHeight(window) {
+ const { document } = window;
+ // Contains the screenshot of the page we are bookmarking
+ document.getElementById("editBookmarkPanelImage").style.height = "";
+ }
+
+ toggleRecommendation(visible) {
+ if (!this._response) {
+ return;
+ }
+
+ const { target } = this._response;
+ if (visible === undefined) {
+ // When called from the info button of the bookmark panel
+ target.infoButton.checked = !target.infoButton.checked;
+ } else {
+ target.infoButton.checked = visible;
+ }
+ if (target.infoButton.checked) {
+ // If it was ever collapsed we need to cancel the state
+ this._response.collapsed = false;
+ target.container.removeAttribute("disabled");
+ } else {
+ target.container.setAttribute("disabled", "disabled");
+ }
+ }
+
+ collapseMessage() {
+ this._response.collapsed = true;
+ this.toggleRecommendation(false);
+ }
+
+ _removeContainer(target) {
+ if (target || (this._response && this._response.target)) {
+ const container = (
+ target || this._response.target
+ ).container.querySelector("#cfrMessageContainer");
+ if (container) {
+ this._restorePanelHeight(this._response.win);
+ container.remove();
+ }
+ }
+ }
+
+ hideMessage(target) {
+ this._removeContainer(target);
+ this.toggleRecommendation(false);
+ this._response = null;
+ }
+
+ forceShowMessage(browser, message) {
+ const doc = browser.ownerGlobal.gBrowser.ownerDocument;
+ const win = browser.ownerGlobal.window;
+ const panelTarget = {
+ container: doc.getElementById("editBookmarkPanelRecommendation"),
+ infoButton: doc.getElementById("editBookmarkPanelInfoButton"),
+ document: doc,
+ close: e => {
+ e.stopPropagation();
+ this.toggleRecommendation(false);
+ },
+ };
+ // Remove any existing message
+ this.hideMessage(panelTarget);
+ // Reset the reference to the panel elements
+ this._response = { target: panelTarget, win };
+ // Required if we want to preview messages that include fluent strings
+ win.MozXULElement.insertFTLIfNeeded("browser/newtab/asrouter.ftl");
+ win.MozXULElement.insertFTLIfNeeded("browser/branding/sync-brand.ftl");
+ this.showMessage(message.content, panelTarget, win);
+ }
+
+ sendImpression() {
+ this._addImpression(this._response);
+ }
+
+ sendUserEventTelemetry(event, win) {
+ // Only send pings for non private browsing windows
+ if (
+ !PrivateBrowsingUtils.isBrowserPrivate(
+ win.ownerGlobal.gBrowser.selectedBrowser
+ )
+ ) {
+ this._sendPing({
+ message_id: this._response.id,
+ bucket_id: this._response.id,
+ event,
+ });
+ }
+ }
+
+ _sendPing(ping) {
+ this._sendTelemetry({
+ type: "DOORHANGER_TELEMETRY",
+ data: { action: "cfr_user_event", source: "CFR", ...ping },
+ });
+ }
+}
+
+this._BookmarkPanelHub = _BookmarkPanelHub;
+
+/**
+ * BookmarkPanelHub - singleton instance of _BookmarkPanelHub that can initiate
+ * message requests and render messages.
+ */
+this.BookmarkPanelHub = new _BookmarkPanelHub();
+
+const EXPORTED_SYMBOLS = ["BookmarkPanelHub", "_BookmarkPanelHub"];
diff --git a/browser/components/newtab/lib/CFRMessageProvider.jsm b/browser/components/newtab/lib/CFRMessageProvider.jsm
new file mode 100644
index 0000000000..01b2b963af
--- /dev/null
+++ b/browser/components/newtab/lib/CFRMessageProvider.jsm
@@ -0,0 +1,1076 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+const FACEBOOK_CONTAINER_PARAMS = {
+ existing_addons: [
+ "@contain-facebook",
+ "{bb1b80be-e6b3-40a1-9b6e-9d4073343f0b}",
+ "{a50d61ca-d27b-437a-8b52-5fd801a0a88b}",
+ ],
+ open_urls: ["www.facebook.com", "facebook.com"],
+ sumo_path: "extensionrecommendations",
+ min_frecency: 10000,
+};
+const GOOGLE_TRANSLATE_PARAMS = {
+ existing_addons: [
+ "jid1-93WyvpgvxzGATw@jetpack",
+ "{087ef4e1-4286-4be6-9aa3-8d6c420ee1db}",
+ "{4170faaa-ee87-4a0e-b57a-1aec49282887}",
+ "jid1-TMndP6cdKgxLcQ@jetpack",
+ "s3google@translator",
+ "{9c63d15c-b4d9-43bd-b223-37f0a1f22e2a}",
+ "translator@zoli.bod",
+ "{8cda9ce6-7893-4f47-ac70-a65215cec288}",
+ "simple-translate@sienori",
+ "@translatenow",
+ "{a79fafce-8da6-4685-923f-7ba1015b8748})",
+ "{8a802b5a-eeab-11e2-a41d-b0096288709b}",
+ "jid0-fbHwsGfb6kJyq2hj65KnbGte3yT@jetpack",
+ "storetranslate.plugin@gmail.com",
+ "jid1-r2tWDbSkq8AZK1@jetpack",
+ "{b384b75c-c978-4c4d-b3cf-62a82d8f8f12}",
+ "jid1-f7dnBeTj8ElpWQ@jetpack",
+ "{dac8a935-4775-4918-9205-5c0600087dc4}",
+ "gtranslation2@slam.com",
+ "{e20e0de5-1667-4df4-bd69-705720e37391}",
+ "{09e26ae9-e9c1-477c-80a6-99934212f2fe}",
+ "mgxtranslator@magemagix.com",
+ "gtranslatewins@mozilla.org",
+ ],
+ open_urls: ["translate.google.com"],
+ sumo_path: "extensionrecommendations",
+ min_frecency: 10000,
+};
+const YOUTUBE_ENHANCE_PARAMS = {
+ existing_addons: [
+ "enhancerforyoutube@maximerf.addons.mozilla.org",
+ "{dc8f61ab-5e98-4027-98ef-bb2ff6060d71}",
+ "{7b1bf0b6-a1b9-42b0-b75d-252036438bdc}",
+ "jid0-UVAeBCfd34Kk5usS8A1CBiobvM8@jetpack",
+ "iridium@particlecore.github.io",
+ "jid1-ss6kLNCbNz6u0g@jetpack",
+ "{1cf918d2-f4ea-4b4f-b34e-455283fef19f}",
+ ],
+ open_urls: ["www.youtube.com", "youtube.com"],
+ sumo_path: "extensionrecommendations",
+ min_frecency: 10000,
+};
+const WIKIPEDIA_CONTEXT_MENU_SEARCH_PARAMS = {
+ existing_addons: [
+ "@wikipediacontextmenusearch",
+ "{ebf47fc8-01d8-4dba-aa04-2118402f4b20}",
+ "{5737a280-b359-4e26-95b0-adec5915a854}",
+ "olivier.debroqueville@gmail.com",
+ "{3923146e-98cb-472b-9c13-f6849d34d6b8}",
+ ],
+ open_urls: ["www.wikipedia.org", "wikipedia.org"],
+ sumo_path: "extensionrecommendations",
+ min_frecency: 10000,
+};
+const REDDIT_ENHANCEMENT_PARAMS = {
+ existing_addons: ["jid1-xUfzOsOFlzSOXg@jetpack"],
+ open_urls: ["www.reddit.com", "reddit.com"],
+ sumo_path: "extensionrecommendations",
+ min_frecency: 10000,
+};
+const PINNED_TABS_TARGET_SITES = [
+ "docs.google.com",
+ "www.docs.google.com",
+ "calendar.google.com",
+ "messenger.com",
+ "www.messenger.com",
+ "web.whatsapp.com",
+ "mail.google.com",
+ "outlook.live.com",
+ "facebook.com",
+ "www.facebook.com",
+ "twitter.com",
+ "www.twitter.com",
+ "reddit.com",
+ "www.reddit.com",
+ "github.com",
+ "www.github.com",
+ "youtube.com",
+ "www.youtube.com",
+ "feedly.com",
+ "www.feedly.com",
+ "drive.google.com",
+ "amazon.com",
+ "www.amazon.com",
+ "messages.android.com",
+ "amazon.ca",
+ "www.amazon.ca",
+ "amazon.com.au",
+ "www.amazon.com.au",
+ "amazon.co.uk",
+ "www.amazon.co.uk",
+ "amazon.fr",
+ "www.amazon.fr",
+ "amazon.de",
+ "www.amazon.de",
+];
+const PINNED_TABS_TARGET_LOCALES = [
+ "en-US",
+ "en-CA",
+ "en-AU",
+ "en-GB",
+ "en-ZA",
+ "en-NZ",
+ "fr",
+ "de",
+];
+
+const CFR_MESSAGES = [
+ {
+ id: "FACEBOOK_CONTAINER_3",
+ template: "cfr_doorhanger",
+ content: {
+ layout: "addon_recommendation",
+ category: "cfrAddons",
+ bucket_id: "CFR_M1",
+ notification_text: {
+ string_id: "cfr-doorhanger-extension-notification2",
+ },
+ heading_text: { string_id: "cfr-doorhanger-extension-heading" },
+ info_icon: {
+ label: { string_id: "cfr-doorhanger-extension-sumo-link" },
+ sumo_path: FACEBOOK_CONTAINER_PARAMS.sumo_path,
+ },
+ addon: {
+ id: "954390",
+ title: "Facebook Container",
+ icon:
+ "chrome://activity-stream/content/data/content/assets/cfr_fb_container.png",
+ rating: 4.6,
+ users: 299019,
+ author: "Mozilla",
+ amo_url: "https://addons.mozilla.org/firefox/addon/facebook-container/",
+ },
+ text:
+ "Stop Facebook from tracking your activity across the web. Use Facebook the way you normally do without annoying ads following you around.",
+ buttons: {
+ primary: {
+ label: { string_id: "cfr-doorhanger-extension-ok-button" },
+ action: {
+ type: "INSTALL_ADDON_FROM_URL",
+ data: { url: "https://example.com", telemetrySource: "amo" },
+ },
+ },
+ secondary: [
+ {
+ label: { string_id: "cfr-doorhanger-extension-cancel-button" },
+ action: { type: "CANCEL" },
+ },
+ {
+ label: {
+ string_id: "cfr-doorhanger-extension-never-show-recommendation",
+ },
+ },
+ {
+ label: {
+ string_id: "cfr-doorhanger-extension-manage-settings-button",
+ },
+ action: {
+ type: "OPEN_PREFERENCES_PAGE",
+ data: { category: "general-cfraddons" },
+ },
+ },
+ ],
+ },
+ },
+ frequency: { lifetime: 3 },
+ targeting: `
+ localeLanguageCode == "en" &&
+ (xpinstallEnabled == true) &&
+ (${JSON.stringify(
+ FACEBOOK_CONTAINER_PARAMS.existing_addons
+ )} intersect addonsInfo.addons|keys)|length == 0 &&
+ (${JSON.stringify(
+ FACEBOOK_CONTAINER_PARAMS.open_urls
+ )} intersect topFrecentSites[.frecency >= ${
+ FACEBOOK_CONTAINER_PARAMS.min_frecency
+ }]|mapToProperty('host'))|length > 0`,
+ trigger: { id: "openURL", params: FACEBOOK_CONTAINER_PARAMS.open_urls },
+ },
+ {
+ id: "GOOGLE_TRANSLATE_3",
+ template: "cfr_doorhanger",
+ content: {
+ layout: "addon_recommendation",
+ category: "cfrAddons",
+ bucket_id: "CFR_M1",
+ notification_text: {
+ string_id: "cfr-doorhanger-extension-notification2",
+ },
+ heading_text: { string_id: "cfr-doorhanger-extension-heading" },
+ info_icon: {
+ label: { string_id: "cfr-doorhanger-extension-sumo-link" },
+ sumo_path: GOOGLE_TRANSLATE_PARAMS.sumo_path,
+ },
+ addon: {
+ id: "445852",
+ title: "To Google Translate",
+ icon:
+ "chrome://activity-stream/content/data/content/assets/cfr_google_translate.png",
+ rating: 4.1,
+ users: 313474,
+ author: "Juan Escobar",
+ amo_url:
+ "https://addons.mozilla.org/firefox/addon/to-google-translate/",
+ },
+ text:
+ "Instantly translate any webpage text. Simply highlight the text, right-click to open the context menu, and choose a text or aural translation.",
+ buttons: {
+ primary: {
+ label: { string_id: "cfr-doorhanger-extension-ok-button" },
+ action: {
+ type: "INSTALL_ADDON_FROM_URL",
+ data: { url: "https://example.com", telemetrySource: "amo" },
+ },
+ },
+ secondary: [
+ {
+ label: { string_id: "cfr-doorhanger-extension-cancel-button" },
+ action: { type: "CANCEL" },
+ },
+ {
+ label: {
+ string_id: "cfr-doorhanger-extension-never-show-recommendation",
+ },
+ },
+ {
+ label: {
+ string_id: "cfr-doorhanger-extension-manage-settings-button",
+ },
+ action: {
+ type: "OPEN_PREFERENCES_PAGE",
+ data: { category: "general-cfraddons" },
+ },
+ },
+ ],
+ },
+ },
+ frequency: { lifetime: 3 },
+ targeting: `
+ localeLanguageCode == "en" &&
+ (xpinstallEnabled == true) &&
+ (${JSON.stringify(
+ GOOGLE_TRANSLATE_PARAMS.existing_addons
+ )} intersect addonsInfo.addons|keys)|length == 0 &&
+ (${JSON.stringify(
+ GOOGLE_TRANSLATE_PARAMS.open_urls
+ )} intersect topFrecentSites[.frecency >= ${
+ GOOGLE_TRANSLATE_PARAMS.min_frecency
+ }]|mapToProperty('host'))|length > 0`,
+ trigger: { id: "openURL", params: GOOGLE_TRANSLATE_PARAMS.open_urls },
+ },
+ {
+ id: "YOUTUBE_ENHANCE_3",
+ template: "cfr_doorhanger",
+ content: {
+ layout: "addon_recommendation",
+ category: "cfrAddons",
+ bucket_id: "CFR_M1",
+ notification_text: {
+ string_id: "cfr-doorhanger-extension-notification2",
+ },
+ heading_text: { string_id: "cfr-doorhanger-extension-heading" },
+ info_icon: {
+ label: { string_id: "cfr-doorhanger-extension-sumo-link" },
+ sumo_path: YOUTUBE_ENHANCE_PARAMS.sumo_path,
+ },
+ addon: {
+ id: "700308",
+ title: "Enhancer for YouTube\u2122",
+ icon:
+ "chrome://activity-stream/content/data/content/assets/cfr_enhancer_youtube.png",
+ rating: 4.8,
+ users: 357328,
+ author: "Maxime RF",
+ amo_url:
+ "https://addons.mozilla.org/firefox/addon/enhancer-for-youtube/",
+ },
+ text:
+ "Take control of your YouTube experience. Automatically block annoying ads, set playback speed and volume, remove annotations, and more.",
+ buttons: {
+ primary: {
+ label: { string_id: "cfr-doorhanger-extension-ok-button" },
+ action: {
+ type: "INSTALL_ADDON_FROM_URL",
+ data: { url: "https://example.com", telemetrySource: "amo" },
+ },
+ },
+ secondary: [
+ {
+ label: { string_id: "cfr-doorhanger-extension-cancel-button" },
+ action: { type: "CANCEL" },
+ },
+ {
+ label: {
+ string_id: "cfr-doorhanger-extension-never-show-recommendation",
+ },
+ },
+ {
+ label: {
+ string_id: "cfr-doorhanger-extension-manage-settings-button",
+ },
+ action: {
+ type: "OPEN_PREFERENCES_PAGE",
+ data: { category: "general-cfraddons" },
+ },
+ },
+ ],
+ },
+ },
+ frequency: { lifetime: 3 },
+ targeting: `
+ localeLanguageCode == "en" &&
+ (xpinstallEnabled == true) &&
+ (${JSON.stringify(
+ YOUTUBE_ENHANCE_PARAMS.existing_addons
+ )} intersect addonsInfo.addons|keys)|length == 0 &&
+ (${JSON.stringify(
+ YOUTUBE_ENHANCE_PARAMS.open_urls
+ )} intersect topFrecentSites[.frecency >= ${
+ YOUTUBE_ENHANCE_PARAMS.min_frecency
+ }]|mapToProperty('host'))|length > 0`,
+ trigger: { id: "openURL", params: YOUTUBE_ENHANCE_PARAMS.open_urls },
+ },
+ {
+ id: "WIKIPEDIA_CONTEXT_MENU_SEARCH_3",
+ template: "cfr_doorhanger",
+ exclude: true,
+ content: {
+ layout: "addon_recommendation",
+ category: "cfrAddons",
+ bucket_id: "CFR_M1",
+ notification_text: {
+ string_id: "cfr-doorhanger-extension-notification2",
+ },
+ heading_text: { string_id: "cfr-doorhanger-extension-heading" },
+ info_icon: {
+ label: { string_id: "cfr-doorhanger-extension-sumo-link" },
+ sumo_path: WIKIPEDIA_CONTEXT_MENU_SEARCH_PARAMS.sumo_path,
+ },
+ addon: {
+ id: "659026",
+ title: "Wikipedia Context Menu Search",
+ icon:
+ "chrome://activity-stream/content/data/content/assets/cfr_wiki_search.png",
+ rating: 4.9,
+ users: 3095,
+ author: "Nick Diedrich",
+ amo_url:
+ "https://addons.mozilla.org/firefox/addon/wikipedia-context-menu-search/",
+ },
+ text:
+ "Get to a Wikipedia page fast, from anywhere on the web. Just highlight any webpage text and right-click to open the context menu to start a Wikipedia search.",
+ buttons: {
+ primary: {
+ label: { string_id: "cfr-doorhanger-extension-ok-button" },
+ action: {
+ type: "INSTALL_ADDON_FROM_URL",
+ data: { url: "https://example.com", telemetrySource: "amo" },
+ },
+ },
+ secondary: [
+ {
+ label: { string_id: "cfr-doorhanger-extension-cancel-button" },
+ action: { type: "CANCEL" },
+ },
+ {
+ label: {
+ string_id: "cfr-doorhanger-extension-never-show-recommendation",
+ },
+ },
+ {
+ label: {
+ string_id: "cfr-doorhanger-extension-manage-settings-button",
+ },
+ action: {
+ type: "OPEN_PREFERENCES_PAGE",
+ data: { category: "general-cfraddons" },
+ },
+ },
+ ],
+ },
+ },
+ frequency: { lifetime: 3 },
+ targeting: `
+ localeLanguageCode == "en" &&
+ (xpinstallEnabled == true) &&
+ (${JSON.stringify(
+ WIKIPEDIA_CONTEXT_MENU_SEARCH_PARAMS.existing_addons
+ )} intersect addonsInfo.addons|keys)|length == 0 &&
+ (${JSON.stringify(
+ WIKIPEDIA_CONTEXT_MENU_SEARCH_PARAMS.open_urls
+ )} intersect topFrecentSites[.frecency >= ${
+ WIKIPEDIA_CONTEXT_MENU_SEARCH_PARAMS.min_frecency
+ }]|mapToProperty('host'))|length > 0`,
+ trigger: {
+ id: "openURL",
+ params: WIKIPEDIA_CONTEXT_MENU_SEARCH_PARAMS.open_urls,
+ },
+ },
+ {
+ id: "REDDIT_ENHANCEMENT_3",
+ template: "cfr_doorhanger",
+ exclude: true,
+ content: {
+ layout: "addon_recommendation",
+ category: "cfrAddons",
+ bucket_id: "CFR_M1",
+ notification_text: {
+ string_id: "cfr-doorhanger-extension-notification2",
+ },
+ heading_text: { string_id: "cfr-doorhanger-extension-heading" },
+ info_icon: {
+ label: { string_id: "cfr-doorhanger-extension-sumo-link" },
+ sumo_path: REDDIT_ENHANCEMENT_PARAMS.sumo_path,
+ },
+ addon: {
+ id: "387429",
+ title: "Reddit Enhancement Suite",
+ icon:
+ "chrome://activity-stream/content/data/content/assets/cfr_reddit_enhancement.png",
+ rating: 4.6,
+ users: 258129,
+ author: "honestbleeps",
+ amo_url:
+ "https://addons.mozilla.org/firefox/addon/reddit-enhancement-suite/",
+ },
+ text:
+ "New features include Inline Image Viewer, Never Ending Reddit (never click 'next page' again), Keyboard Navigation, Account Switcher, and User Tagger.",
+ buttons: {
+ primary: {
+ label: { string_id: "cfr-doorhanger-extension-ok-button" },
+ action: {
+ type: "INSTALL_ADDON_FROM_URL",
+ data: { url: "https://example.com", telemetrySource: "amo" },
+ },
+ },
+ secondary: [
+ {
+ label: { string_id: "cfr-doorhanger-extension-cancel-button" },
+ action: { type: "CANCEL" },
+ },
+ {
+ label: {
+ string_id: "cfr-doorhanger-extension-never-show-recommendation",
+ },
+ },
+ {
+ label: {
+ string_id: "cfr-doorhanger-extension-manage-settings-button",
+ },
+ action: {
+ type: "OPEN_PREFERENCES_PAGE",
+ data: { category: "general-cfraddons" },
+ },
+ },
+ ],
+ },
+ },
+ frequency: { lifetime: 3 },
+ targeting: `
+ localeLanguageCode == "en" &&
+ (xpinstallEnabled == true) &&
+ (${JSON.stringify(
+ REDDIT_ENHANCEMENT_PARAMS.existing_addons
+ )} intersect addonsInfo.addons|keys)|length == 0 &&
+ (${JSON.stringify(
+ REDDIT_ENHANCEMENT_PARAMS.open_urls
+ )} intersect topFrecentSites[.frecency >= ${
+ REDDIT_ENHANCEMENT_PARAMS.min_frecency
+ }]|mapToProperty('host'))|length > 0`,
+ trigger: { id: "openURL", params: REDDIT_ENHANCEMENT_PARAMS.open_urls },
+ },
+ {
+ id: "PIN_TAB",
+ template: "cfr_doorhanger",
+ content: {
+ layout: "message_and_animation",
+ category: "cfrFeatures",
+ bucket_id: "CFR_PIN_TAB",
+ notification_text: { string_id: "cfr-doorhanger-feature-notification" },
+ heading_text: { string_id: "cfr-doorhanger-pintab-heading" },
+ info_icon: {
+ label: { string_id: "cfr-doorhanger-extension-sumo-link" },
+ sumo_path: REDDIT_ENHANCEMENT_PARAMS.sumo_path,
+ },
+ text: { string_id: "cfr-doorhanger-pintab-description" },
+ descriptionDetails: {
+ steps: [
+ { string_id: "cfr-doorhanger-pintab-step1" },
+ { string_id: "cfr-doorhanger-pintab-step2" },
+ { string_id: "cfr-doorhanger-pintab-step3" },
+ ],
+ },
+ buttons: {
+ primary: {
+ label: { string_id: "cfr-doorhanger-pintab-ok-button" },
+ action: {
+ type: "PIN_CURRENT_TAB",
+ },
+ },
+ secondary: [
+ {
+ label: { string_id: "cfr-doorhanger-extension-cancel-button" },
+ action: { type: "CANCEL" },
+ },
+ {
+ label: {
+ string_id: "cfr-doorhanger-extension-never-show-recommendation",
+ },
+ },
+ {
+ label: {
+ string_id: "cfr-doorhanger-extension-manage-settings-button",
+ },
+ action: {
+ type: "OPEN_PREFERENCES_PAGE",
+ data: { category: "general-cfrfeatures" },
+ },
+ },
+ ],
+ },
+ },
+ targeting: `locale in ${JSON.stringify(
+ PINNED_TABS_TARGET_LOCALES
+ )} && !hasPinnedTabs && recentVisits[.timestamp > (currentDate|date - 3600 * 1000 * 1)]|length >= 3`,
+ frequency: { lifetime: 3 },
+ trigger: { id: "frequentVisits", params: PINNED_TABS_TARGET_SITES },
+ },
+ {
+ id: "DOH_ROLLOUT_CONFIRMATION",
+ targeting: `
+ "doh-rollout.enabled"|preferenceValue &&
+ !"doh-rollout.disable-heuristics"|preferenceValue &&
+ !"doh-rollout.skipHeuristicsCheck"|preferenceValue &&
+ !"doh-rollout.doorhanger-decision"|preferenceValue
+ `,
+ template: "cfr_doorhanger",
+ content: {
+ skip_address_bar_notifier: true,
+ persistent_doorhanger: true,
+ anchor_id: "PanelUI-menu-button",
+ layout: "icon_and_message",
+ text: { string_id: "cfr-doorhanger-doh-body" },
+ icon: "chrome://browser/skin/connection-secure.svg",
+ buttons: {
+ secondary: [
+ {
+ label: { string_id: "cfr-doorhanger-doh-secondary-button" },
+ action: {
+ type: "DISABLE_DOH",
+ },
+ },
+ ],
+ primary: {
+ label: { string_id: "cfr-doorhanger-doh-primary-button" },
+ action: {
+ type: "ACCEPT_DOH",
+ },
+ },
+ },
+ bucket_id: "DOH_ROLLOUT_CONFIRMATION",
+ heading_text: { string_id: "cfr-doorhanger-doh-header" },
+ info_icon: {
+ label: {
+ string_id: "cfr-doorhanger-extension-sumo-link",
+ },
+ sumo_path: "extensionrecommendations",
+ },
+ notification_text: "Message from Firefox",
+ category: "cfrFeatures",
+ },
+ trigger: {
+ id: "openURL",
+ patterns: ["*://*/*"],
+ },
+ },
+ {
+ id: "SAVE_LOGIN",
+ frequency: {
+ lifetime: 3,
+ },
+ targeting:
+ "(!type || type == 'save') && isFxAEnabled == true && usesFirefoxSync == false",
+ template: "cfr_doorhanger",
+ content: {
+ layout: "icon_and_message",
+ text: {
+ string_id: "cfr-doorhanger-sync-logins-body",
+ },
+ icon: "chrome://browser/content/aboutlogins/icons/intro-illustration.svg",
+ icon_class: "cfr-doorhanger-large-icon",
+ buttons: {
+ secondary: [
+ {
+ label: {
+ string_id: "cfr-doorhanger-extension-cancel-button",
+ },
+ action: {
+ type: "CANCEL",
+ },
+ },
+ {
+ label: {
+ string_id: "cfr-doorhanger-extension-never-show-recommendation",
+ },
+ },
+ {
+ label: {
+ string_id: "cfr-doorhanger-extension-manage-settings-button",
+ },
+ action: {
+ type: "OPEN_PREFERENCES_PAGE",
+ data: {
+ category: "general-cfrfeatures",
+ },
+ },
+ },
+ ],
+ primary: {
+ label: {
+ string_id: "cfr-doorhanger-sync-logins-ok-button",
+ },
+ action: {
+ type: "OPEN_PREFERENCES_PAGE",
+ data: {
+ category: "sync",
+ entrypoint: "cfr-save-login",
+ },
+ },
+ },
+ },
+ bucket_id: "CFR_SAVE_LOGIN",
+ heading_text: {
+ string_id: "cfr-doorhanger-sync-logins-header",
+ },
+ info_icon: {
+ label: {
+ string_id: "cfr-doorhanger-extension-sumo-link",
+ },
+ sumo_path: "extensionrecommendations",
+ },
+ notification_text: {
+ string_id: "cfr-doorhanger-feature-notification",
+ },
+ category: "cfrFeatures",
+ },
+ trigger: {
+ id: "newSavedLogin",
+ },
+ },
+ {
+ id: "UPDATE_LOGIN",
+ frequency: {
+ lifetime: 3,
+ },
+ targeting:
+ "type == 'update' && isFxAEnabled == true && usesFirefoxSync == false",
+ template: "cfr_doorhanger",
+ content: {
+ layout: "icon_and_message",
+ text: {
+ string_id: "cfr-doorhanger-sync-logins-body",
+ },
+ icon: "chrome://browser/content/aboutlogins/icons/intro-illustration.svg",
+ icon_class: "cfr-doorhanger-large-icon",
+ buttons: {
+ secondary: [
+ {
+ label: {
+ string_id: "cfr-doorhanger-extension-cancel-button",
+ },
+ action: {
+ type: "CANCEL",
+ },
+ },
+ {
+ label: {
+ string_id: "cfr-doorhanger-extension-never-show-recommendation",
+ },
+ },
+ {
+ label: {
+ string_id: "cfr-doorhanger-extension-manage-settings-button",
+ },
+ action: {
+ type: "OPEN_PREFERENCES_PAGE",
+ data: {
+ category: "general-cfrfeatures",
+ },
+ },
+ },
+ ],
+ primary: {
+ label: {
+ string_id: "cfr-doorhanger-sync-logins-ok-button",
+ },
+ action: {
+ type: "OPEN_PREFERENCES_PAGE",
+ data: {
+ category: "sync",
+ entrypoint: "cfr-update-login",
+ },
+ },
+ },
+ },
+ bucket_id: "CFR_UPDATE_LOGIN",
+ heading_text: {
+ string_id: "cfr-doorhanger-sync-logins-header",
+ },
+ info_icon: {
+ label: {
+ string_id: "cfr-doorhanger-extension-sumo-link",
+ },
+ sumo_path: "extensionrecommendations",
+ },
+ notification_text: {
+ string_id: "cfr-doorhanger-feature-notification",
+ },
+ category: "cfrFeatures",
+ },
+ trigger: {
+ id: "newSavedLogin",
+ },
+ },
+ {
+ id: "SOCIAL_TRACKING_PROTECTION",
+ template: "cfr_doorhanger",
+ priority: 1,
+ content: {
+ layout: "icon_and_message",
+ category: "cfrFeatures",
+ anchor_id: "tracking-protection-icon-box",
+ skip_address_bar_notifier: true,
+ bucket_id: "CFR_SOCIAL_TRACKING_PROTECTION",
+ heading_text: { string_id: "cfr-doorhanger-socialtracking-heading" },
+ notification_text: "",
+ info_icon: {
+ label: {
+ string_id: "cfr-doorhanger-extension-sumo-link",
+ },
+ sumo_path: "extensionrecommendations",
+ },
+ learn_more: "social-media-tracking-report",
+ text: { string_id: "cfr-doorhanger-socialtracking-description" },
+ icon: "chrome://browser/skin/notification-icons/block-social.svg",
+ icon_dark_theme:
+ "chrome://browser/skin/notification-icons/block-social-dark.svg",
+ buttons: {
+ primary: {
+ label: { string_id: "cfr-doorhanger-socialtracking-ok-button" },
+ action: { type: "OPEN_PROTECTION_PANEL" },
+ event: "PROTECTION",
+ },
+ secondary: [
+ {
+ label: { string_id: "cfr-doorhanger-socialtracking-close-button" },
+ event: "BLOCK",
+ },
+ {
+ label: {
+ string_id: "cfr-doorhanger-socialtracking-dont-show-again",
+ },
+ action: { type: "DISABLE_STP_DOORHANGERS" },
+ event: "BLOCK",
+ },
+ ],
+ },
+ },
+ targeting: "pageLoad >= 4 && firefoxVersion >= 71",
+ frequency: {
+ lifetime: 2,
+ custom: [{ period: 2 * 86400 * 1000, cap: 1 }],
+ },
+ trigger: {
+ id: "contentBlocking",
+ params: [
+ Ci.nsIWebProgressListener.STATE_BLOCKED_SOCIALTRACKING_CONTENT,
+ Ci.nsIWebProgressListener.STATE_LOADED_SOCIALTRACKING_CONTENT |
+ Ci.nsIWebProgressListener.STATE_COOKIES_BLOCKED_TRACKER,
+ ],
+ },
+ },
+ {
+ id: "FINGERPRINTERS_PROTECTION",
+ template: "cfr_doorhanger",
+ priority: 2,
+ content: {
+ layout: "icon_and_message",
+ category: "cfrFeatures",
+ anchor_id: "tracking-protection-icon-box",
+ skip_address_bar_notifier: true,
+ bucket_id: "CFR_SOCIAL_TRACKING_PROTECTION",
+ heading_text: { string_id: "cfr-doorhanger-fingerprinters-heading" },
+ notification_text: "",
+ info_icon: {
+ label: {
+ string_id: "cfr-doorhanger-extension-sumo-link",
+ },
+ sumo_path: "extensionrecommendations",
+ },
+ learn_more: "fingerprinters-report",
+ text: { string_id: "cfr-doorhanger-fingerprinters-description" },
+ icon: "chrome://browser/skin/notification-icons/block-fingerprinter.svg",
+ icon_dark_theme:
+ "chrome://browser/skin/notification-icons/block-fingerprinter-dark.svg",
+ buttons: {
+ primary: {
+ label: { string_id: "cfr-doorhanger-socialtracking-ok-button" },
+ action: { type: "OPEN_PROTECTION_PANEL" },
+ event: "PROTECTION",
+ },
+ secondary: [
+ {
+ label: { string_id: "cfr-doorhanger-socialtracking-close-button" },
+ event: "BLOCK",
+ },
+ {
+ label: {
+ string_id: "cfr-doorhanger-socialtracking-dont-show-again",
+ },
+ action: { type: "DISABLE_STP_DOORHANGERS" },
+ event: "BLOCK",
+ },
+ ],
+ },
+ },
+ targeting: "pageLoad >= 0 && firefoxVersion >= 71",
+ frequency: {
+ lifetime: 2,
+ custom: [{ period: 2 * 86400 * 1000, cap: 1 }],
+ },
+ trigger: {
+ id: "contentBlocking",
+ params: [Ci.nsIWebProgressListener.STATE_BLOCKED_FINGERPRINTING_CONTENT],
+ },
+ },
+ {
+ id: "CRYPTOMINERS_PROTECTION",
+ template: "cfr_doorhanger",
+ priority: 3,
+ content: {
+ layout: "icon_and_message",
+ category: "cfrFeatures",
+ anchor_id: "tracking-protection-icon-box",
+ skip_address_bar_notifier: true,
+ bucket_id: "CFR_SOCIAL_TRACKING_PROTECTION",
+ heading_text: { string_id: "cfr-doorhanger-cryptominers-heading" },
+ notification_text: "",
+ info_icon: {
+ label: {
+ string_id: "cfr-doorhanger-extension-sumo-link",
+ },
+ sumo_path: "extensionrecommendations",
+ },
+ learn_more: "cryptominers-report",
+ text: { string_id: "cfr-doorhanger-cryptominers-description" },
+ icon: "chrome://browser/skin/notification-icons/block-cryptominer.svg",
+ icon_dark_theme:
+ "chrome://browser/skin/notification-icons/block-cryptominer-dark.svg",
+ buttons: {
+ primary: {
+ label: { string_id: "cfr-doorhanger-socialtracking-ok-button" },
+ action: { type: "OPEN_PROTECTION_PANEL" },
+ event: "PROTECTION",
+ },
+ secondary: [
+ {
+ label: { string_id: "cfr-doorhanger-socialtracking-close-button" },
+ event: "BLOCK",
+ },
+ {
+ label: {
+ string_id: "cfr-doorhanger-socialtracking-dont-show-again",
+ },
+ action: { type: "DISABLE_STP_DOORHANGERS" },
+ event: "BLOCK",
+ },
+ ],
+ },
+ },
+ targeting: "pageLoad >= 4 && firefoxVersion >= 71",
+ frequency: {
+ lifetime: 2,
+ custom: [{ period: 2 * 86400 * 1000, cap: 1 }],
+ },
+ trigger: {
+ id: "contentBlocking",
+ params: [Ci.nsIWebProgressListener.STATE_BLOCKED_CRYPTOMINING_CONTENT],
+ },
+ },
+ {
+ id: "MILESTONE_MESSAGE",
+ template: "milestone_message",
+ content: {
+ layout: "short_message",
+ category: "cfrFeatures",
+ anchor_id: "tracking-protection-icon-box",
+ skip_address_bar_notifier: true,
+ bucket_id: "CFR_MILESTONE_MESSAGE",
+ heading_text: { string_id: "cfr-doorhanger-milestone-heading" },
+ notification_text: "",
+ text: "",
+ buttons: {
+ primary: {
+ label: { string_id: "cfr-doorhanger-milestone-ok-button" },
+ action: { type: "OPEN_PROTECTION_REPORT" },
+ event: "PROTECTION",
+ },
+ secondary: [
+ {
+ label: { string_id: "cfr-doorhanger-milestone-close-button" },
+ action: { type: "CANCEL" },
+ event: "DISMISS",
+ },
+ ],
+ },
+ },
+ targeting: "pageLoad >= 1",
+ frequency: {
+ lifetime: 7, // Length of privacy.contentBlocking.cfr-milestone.milestones pref
+ },
+ trigger: {
+ id: "contentBlocking",
+ params: ["ContentBlockingMilestone"],
+ },
+ },
+ {
+ id: "HEARTBEAT_TACTIC_2",
+ template: "cfr_urlbar_chiclet",
+ content: {
+ layout: "chiclet_open_url",
+ category: "cfrHeartbeat",
+ bucket_id: "HEARTBEAT_TACTIC_2",
+ notification_text: "Improve Firefox",
+ active_color: "#595e91",
+ action: {
+ url: "http://example.com/%VERSION%/",
+ where: "tabshifted",
+ },
+ },
+ targeting: "false",
+ frequency: {
+ lifetime: 3,
+ },
+ trigger: {
+ id: "openURL",
+ patterns: ["*://*/*"],
+ },
+ },
+ {
+ id: "HOMEPAGE_REMEDIATION_82",
+ frequency: {
+ lifetime: 3,
+ },
+ targeting:
+ "!homePageSettings.isDefault && homePageSettings.isCustomUrl && homePageSettings.urls[.host == 'google.com']|length > 0 && visitsCount >= 3 && userPrefs.cfrFeatures",
+ template: "cfr_doorhanger",
+ content: {
+ layout: "icon_and_message",
+ text:
+ "Update your homepage to search Google while also being able to search your Firefox history and bookmarks.",
+ icon: "chrome://browser/skin/preferences/search.svg",
+ buttons: {
+ secondary: [
+ {
+ label: {
+ string_id: "cfr-doorhanger-extension-cancel-button",
+ },
+ action: {
+ type: "CANCEL",
+ },
+ },
+ {
+ label: {
+ string_id: "cfr-doorhanger-extension-never-show-recommendation",
+ },
+ },
+ {
+ label: {
+ string_id: "cfr-doorhanger-extension-manage-settings-button",
+ },
+ action: {
+ type: "OPEN_PREFERENCES_PAGE",
+ data: {
+ category: "general-cfrfeatures",
+ },
+ },
+ },
+ ],
+ primary: {
+ label: {
+ value: "Activate now",
+ attributes: {
+ accesskey: "A",
+ },
+ },
+ action: {
+ type: "CONFIGURE_HOMEPAGE",
+ data: {
+ homePage: "default",
+ newtab: "default",
+ layout: {
+ search: true,
+ topsites: false,
+ highlights: false,
+ topstories: false,
+ snippets: false,
+ },
+ },
+ },
+ },
+ },
+ bucket_id: "HOMEPAGE_REMEDIATION_82",
+ heading_text: "A better search experience",
+ info_icon: {
+ label: {
+ string_id: "cfr-doorhanger-extension-sumo-link",
+ },
+ sumo_path: "extensionrecommendations",
+ },
+ notification_text: {
+ string_id: "cfr-doorhanger-feature-notification",
+ },
+ category: "cfrFeatures",
+ },
+ trigger: {
+ id: "openURL",
+ params: ["google.com", "www.google.com"],
+ },
+ },
+ {
+ id: "INFOBAR_ACTION_86",
+ targeting: "false",
+ template: "infobar",
+ content: {
+ type: "global",
+ text: { string_id: "default-browser-notification-message" },
+ buttons: [
+ {
+ label: { string_id: "default-browser-notification-button" },
+ primary: true,
+ accessKey: "O",
+ action: {
+ type: "SET_DEFAULT_BROWSER",
+ },
+ },
+ ],
+ },
+ trigger: { id: "defaultBrowserCheck" },
+ },
+];
+
+const CFRMessageProvider = {
+ getMessages() {
+ return Promise.resolve(CFR_MESSAGES.filter(msg => !msg.exclude));
+ },
+};
+this.CFRMessageProvider = CFRMessageProvider;
+
+const EXPORTED_SYMBOLS = ["CFRMessageProvider"];
diff --git a/browser/components/newtab/lib/CFRPageActions.jsm b/browser/components/newtab/lib/CFRPageActions.jsm
new file mode 100644
index 0000000000..bba25c6db8
--- /dev/null
+++ b/browser/components/newtab/lib/CFRPageActions.jsm
@@ -0,0 +1,1194 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
+const { XPCOMUtils } = ChromeUtils.import(
+ "resource://gre/modules/XPCOMUtils.jsm"
+);
+const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
+
+XPCOMUtils.defineLazyGlobalGetters(this, ["fetch"]);
+
+XPCOMUtils.defineLazyModuleGetters(this, {
+ PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.jsm",
+ RemoteL10n: "resource://activity-stream/lib/RemoteL10n.jsm",
+});
+
+XPCOMUtils.defineLazyServiceGetter(
+ this,
+ "TrackingDBService",
+ "@mozilla.org/tracking-db-service;1",
+ "nsITrackingDBService"
+);
+XPCOMUtils.defineLazyPreferenceGetter(
+ this,
+ "milestones",
+ "browser.contentblocking.cfr-milestone.milestones",
+ "[]",
+ null,
+ JSON.parse
+);
+
+const POPUP_NOTIFICATION_ID = "contextual-feature-recommendation";
+const ANIMATION_BUTTON_ID = "cfr-notification-footer-animation-button";
+const ANIMATION_LABEL_ID = "cfr-notification-footer-animation-label";
+const SUMO_BASE_URL = Services.urlFormatter.formatURLPref(
+ "app.support.baseURL"
+);
+const ADDONS_API_URL =
+ "https://services.addons.mozilla.org/api/v4/addons/addon";
+
+const DELAY_BEFORE_EXPAND_MS = 1000;
+const CATEGORY_ICONS = {
+ cfrAddons: "webextensions-icon",
+ cfrFeatures: "recommendations-icon",
+ cfrHeartbeat: "highlights-icon",
+};
+
+/**
+ * A WeakMap from browsers to {host, recommendation} pairs. Recommendations are
+ * defined in the ExtensionDoorhanger.schema.json.
+ *
+ * A recommendation is specific to a browser and host and is active until the
+ * given browser is closed or the user navigates (within that browser) away from
+ * the host.
+ */
+let RecommendationMap = new WeakMap();
+
+/**
+ * A WeakMap from windows to their CFR PageAction.
+ */
+let PageActionMap = new WeakMap();
+
+/**
+ * We need one PageAction for each window
+ */
+class PageAction {
+ constructor(win, dispatchCFRAction) {
+ this.window = win;
+
+ this.urlbar = win.gURLBar; // The global URLBar object
+ this.urlbarinput = win.gURLBar.textbox; // The URLBar DOM node
+
+ this.container = win.document.getElementById(
+ "contextual-feature-recommendation"
+ );
+ this.button = win.document.getElementById("cfr-button");
+ this.label = win.document.getElementById("cfr-label");
+
+ // This should NOT be use directly to dispatch message-defined actions attached to buttons.
+ // Please use dispatchUserAction instead.
+ this._dispatchCFRAction = dispatchCFRAction;
+
+ this._popupStateChange = this._popupStateChange.bind(this);
+ this._collapse = this._collapse.bind(this);
+ this._cfrUrlbarButtonClick = this._cfrUrlbarButtonClick.bind(this);
+ this._executeNotifierAction = this._executeNotifierAction.bind(this);
+ this.dispatchUserAction = this.dispatchUserAction.bind(this);
+
+ // Saved timeout IDs for scheduled state changes, so they can be cancelled
+ this.stateTransitionTimeoutIDs = [];
+
+ XPCOMUtils.defineLazyGetter(this, "isDarkTheme", () => {
+ try {
+ return this.window.document.documentElement.hasAttribute(
+ "lwt-toolbar-field-brighttext"
+ );
+ } catch (e) {
+ return false;
+ }
+ });
+ }
+
+ addImpression(recommendation) {
+ this._dispatchImpression(recommendation);
+ // Only send an impression ping upon the first expansion.
+ // Note that when the user clicks on the "show" button on the asrouter admin
+ // page (both `bucket_id` and `id` will be set as null), we don't want to send
+ // the impression ping in that case.
+ if (!!recommendation.id && !!recommendation.content.bucket_id) {
+ this._sendTelemetry({
+ message_id: recommendation.id,
+ bucket_id: recommendation.content.bucket_id,
+ event: "IMPRESSION",
+ ...(recommendation.personalizedModelVersion
+ ? {
+ event_context: {
+ modelVersion: recommendation.personalizedModelVersion,
+ },
+ }
+ : {}),
+ });
+ }
+ }
+
+ reloadL10n() {
+ RemoteL10n.reloadL10n();
+ }
+
+ async showAddressBarNotifier(recommendation, shouldExpand = false) {
+ this.container.hidden = false;
+
+ let notificationText = await this.getStrings(
+ recommendation.content.notification_text
+ );
+ this.label.value = notificationText;
+ if (notificationText.attributes) {
+ this.button.setAttribute(
+ "tooltiptext",
+ notificationText.attributes.tooltiptext
+ );
+ // For a11y, we want the more descriptive text.
+ this.container.setAttribute(
+ "aria-label",
+ notificationText.attributes.tooltiptext
+ );
+ }
+ this.container.setAttribute(
+ "data-cfr-icon",
+ CATEGORY_ICONS[recommendation.content.category]
+ );
+ if (recommendation.content.active_color) {
+ this.container.style.setProperty(
+ "--cfr-active-color",
+ recommendation.content.active_color
+ );
+ }
+
+ // Wait for layout to flush to avoid a synchronous reflow then calculate the
+ // label width. We can safely get the width even though the recommendation is
+ // collapsed; the label itself remains full width (with its overflow hidden)
+ let [{ width }] = await this.window.promiseDocumentFlushed(() =>
+ this.label.getClientRects()
+ );
+ this.urlbarinput.style.setProperty("--cfr-label-width", `${width}px`);
+
+ this.container.addEventListener("click", this._cfrUrlbarButtonClick);
+ // Collapse the recommendation on url bar focus in order to free up more
+ // space to display and edit the url
+ this.urlbar.addEventListener("focus", this._collapse);
+
+ if (shouldExpand) {
+ this._clearScheduledStateChanges();
+
+ // After one second, expand
+ this._expand(DELAY_BEFORE_EXPAND_MS);
+
+ this.addImpression(recommendation);
+ }
+
+ if (notificationText.attributes) {
+ this.window.A11yUtils.announce({
+ raw: notificationText.attributes["a11y-announcement"],
+ source: this.container,
+ });
+ }
+ }
+
+ hideAddressBarNotifier() {
+ this.container.hidden = true;
+ this._clearScheduledStateChanges();
+ this.urlbarinput.removeAttribute("cfr-recommendation-state");
+ this.container.removeEventListener("click", this._cfrUrlbarButtonClick);
+ this.urlbar.removeEventListener("focus", this._collapse);
+ if (this.currentNotification) {
+ this.window.PopupNotifications.remove(this.currentNotification);
+ this.currentNotification = null;
+ }
+ }
+
+ _expand(delay) {
+ if (delay > 0) {
+ this.stateTransitionTimeoutIDs.push(
+ this.window.setTimeout(() => {
+ this.urlbarinput.setAttribute("cfr-recommendation-state", "expanded");
+ }, delay)
+ );
+ } else {
+ // Non-delayed state change overrides any scheduled state changes
+ this._clearScheduledStateChanges();
+ this.urlbarinput.setAttribute("cfr-recommendation-state", "expanded");
+ }
+ }
+
+ _collapse(delay) {
+ if (delay > 0) {
+ this.stateTransitionTimeoutIDs.push(
+ this.window.setTimeout(() => {
+ if (
+ this.urlbarinput.getAttribute("cfr-recommendation-state") ===
+ "expanded"
+ ) {
+ this.urlbarinput.setAttribute(
+ "cfr-recommendation-state",
+ "collapsed"
+ );
+ }
+ }, delay)
+ );
+ } else {
+ // Non-delayed state change overrides any scheduled state changes
+ this._clearScheduledStateChanges();
+ if (
+ this.urlbarinput.getAttribute("cfr-recommendation-state") === "expanded"
+ ) {
+ this.urlbarinput.setAttribute("cfr-recommendation-state", "collapsed");
+ }
+ }
+
+ // TODO: FIXME: find a nicer way of cleaning this up. Maybe listening to "popuphidden"?
+ // Remove click listener on pause button;
+ if (this.onAnimationButtonClick) {
+ this.window.document
+ .getElementById(ANIMATION_BUTTON_ID)
+ .removeEventListener("click", this.onAnimationButtonClick);
+ delete this.onAnimationButtonClick;
+ }
+ }
+
+ _clearScheduledStateChanges() {
+ while (this.stateTransitionTimeoutIDs.length) {
+ // clearTimeout is safe even with invalid/expired IDs
+ this.window.clearTimeout(this.stateTransitionTimeoutIDs.pop());
+ }
+ }
+
+ // This is called when the popup closes as a result of interaction _outside_
+ // the popup, e.g. by hitting <esc>
+ _popupStateChange(state) {
+ if (state === "shown") {
+ if (this._autoFocus) {
+ this.window.document.commandDispatcher.advanceFocusIntoSubtree(
+ this.currentNotification.owner.panel
+ );
+ this._autoFocus = false;
+ }
+ } else if (state === "removed") {
+ if (this.currentNotification) {
+ this.window.PopupNotifications.remove(this.currentNotification);
+ this.currentNotification = null;
+ }
+ } else if (state === "dismissed") {
+ this._collapse();
+ }
+ }
+
+ shouldShowDoorhanger(recommendation) {
+ if (recommendation.content.layout === "chiclet_open_url") {
+ return false;
+ }
+
+ return true;
+ }
+
+ dispatchUserAction(action) {
+ this._dispatchCFRAction(
+ { type: "USER_ACTION", data: action },
+ this.window.gBrowser.selectedBrowser
+ );
+ }
+
+ _dispatchImpression(message) {
+ this._dispatchCFRAction({ type: "IMPRESSION", data: message });
+ }
+
+ _sendTelemetry(ping) {
+ this._dispatchCFRAction({
+ type: "DOORHANGER_TELEMETRY",
+ data: { action: "cfr_user_event", source: "CFR", ...ping },
+ });
+ }
+
+ _blockMessage(messageID) {
+ this._dispatchCFRAction({
+ type: "BLOCK_MESSAGE_BY_ID",
+ data: { id: messageID },
+ });
+ }
+
+ maybeLoadCustomElement(win) {
+ if (!win.customElements.get("remote-text")) {
+ Services.scriptloader.loadSubScript(
+ "resource://activity-stream/data/custom-elements/paragraph.js",
+ win
+ );
+ }
+ }
+
+ /**
+ * getStrings - Handles getting the localized strings vs message overrides.
+ * If string_id is not defined it assumes you passed in an override
+ * message and it just returns it.
+ * If subAttribute is provided, the string for it is returned.
+ * @return A string. One of 1) passed in string 2) a String object with
+ * attributes property if there are attributes 3) the sub attribute.
+ */
+ async getStrings(string, subAttribute = "") {
+ if (!string.string_id) {
+ if (subAttribute) {
+ if (string.attributes) {
+ return string.attributes[subAttribute];
+ }
+
+ Cu.reportError(
+ `String ${string.value} does not contain any attributes`
+ );
+ return subAttribute;
+ }
+
+ if (typeof string.value === "string") {
+ const stringWithAttributes = new String(string.value); // eslint-disable-line no-new-wrappers
+ stringWithAttributes.attributes = string.attributes;
+ return stringWithAttributes;
+ }
+
+ return string;
+ }
+
+ const [localeStrings] = await RemoteL10n.l10n.formatMessages([
+ {
+ id: string.string_id,
+ args: string.args,
+ },
+ ]);
+
+ const mainString = new String(localeStrings.value); // eslint-disable-line no-new-wrappers
+ if (localeStrings.attributes) {
+ const attributes = localeStrings.attributes.reduce((acc, attribute) => {
+ acc[attribute.name] = attribute.value;
+ return acc;
+ }, {});
+ mainString.attributes = attributes;
+ }
+
+ return subAttribute ? mainString.attributes[subAttribute] : mainString;
+ }
+
+ async _setAddonAuthorAndRating(document, content) {
+ const author = this.window.document.getElementById(
+ "cfr-notification-author"
+ );
+ const footerFilledStars = this.window.document.getElementById(
+ "cfr-notification-footer-filled-stars"
+ );
+ const footerEmptyStars = this.window.document.getElementById(
+ "cfr-notification-footer-empty-stars"
+ );
+ const footerUsers = this.window.document.getElementById(
+ "cfr-notification-footer-users"
+ );
+ const footerSpacer = this.window.document.getElementById(
+ "cfr-notification-footer-spacer"
+ );
+
+ author.textContent = await this.getStrings({
+ string_id: "cfr-doorhanger-extension-author",
+ args: { name: content.addon.author },
+ });
+
+ const { rating } = content.addon;
+ if (rating) {
+ const MAX_RATING = 5;
+ const STARS_WIDTH = 17 * MAX_RATING;
+ const calcWidth = stars => `${(stars / MAX_RATING) * STARS_WIDTH}px`;
+ footerFilledStars.style.width = calcWidth(rating);
+ footerEmptyStars.style.width = calcWidth(MAX_RATING - rating);
+
+ const ratingString = await this.getStrings(
+ {
+ string_id: "cfr-doorhanger-extension-rating",
+ args: { total: rating },
+ },
+ "tooltiptext"
+ );
+ footerFilledStars.setAttribute("tooltiptext", ratingString);
+ footerEmptyStars.setAttribute("tooltiptext", ratingString);
+ } else {
+ footerFilledStars.style.width = "";
+ footerEmptyStars.style.width = "";
+ footerFilledStars.removeAttribute("tooltiptext");
+ footerEmptyStars.removeAttribute("tooltiptext");
+ }
+
+ const { users } = content.addon;
+ if (users) {
+ footerUsers.setAttribute(
+ "value",
+ await this.getStrings({
+ string_id: "cfr-doorhanger-extension-total-users",
+ args: { total: users },
+ })
+ );
+ footerUsers.removeAttribute("hidden");
+ } else {
+ // Prevent whitespace around empty label from affecting other spacing
+ footerUsers.setAttribute("hidden", true);
+ footerUsers.removeAttribute("value");
+ }
+
+ // Spacer pushes the link to the opposite end when there's other content
+ if (rating || users) {
+ footerSpacer.removeAttribute("hidden");
+ } else {
+ footerSpacer.setAttribute("hidden", true);
+ }
+ }
+
+ _createElementAndAppend({ type, id }, parent) {
+ let element = this.window.document.createXULElement(type);
+ if (id) {
+ element.setAttribute("id", id);
+ }
+ parent.appendChild(element);
+ return element;
+ }
+
+ async _renderPinTabAnimation() {
+ const ANIMATION_CONTAINER_ID =
+ "cfr-notification-footer-pintab-animation-container";
+ const footer = this.window.document.getElementById(
+ "cfr-notification-footer"
+ );
+ let animationContainer = this.window.document.getElementById(
+ ANIMATION_CONTAINER_ID
+ );
+ if (!animationContainer) {
+ animationContainer = this._createElementAndAppend(
+ { type: "vbox", id: ANIMATION_CONTAINER_ID },
+ footer
+ );
+
+ let controlsContainer = this._createElementAndAppend(
+ { type: "hbox", id: "cfr-notification-footer-animation-controls" },
+ animationContainer
+ );
+
+ // spacer
+ this._createElementAndAppend(
+ { type: "vbox" },
+ controlsContainer
+ ).setAttribute("flex", 1);
+
+ let animationButton = this._createElementAndAppend(
+ { type: "hbox", id: ANIMATION_BUTTON_ID },
+ controlsContainer
+ );
+
+ // animation button label
+ this._createElementAndAppend(
+ { type: "label", id: ANIMATION_LABEL_ID },
+ animationButton
+ );
+ }
+
+ animationContainer.toggleAttribute(
+ "animate",
+ !this.window.matchMedia("(prefers-reduced-motion: reduce)").matches
+ );
+ animationContainer.removeAttribute("paused");
+
+ this.window.document.getElementById(
+ ANIMATION_LABEL_ID
+ ).textContent = await this.getStrings({
+ string_id: "cfr-doorhanger-pintab-animation-pause",
+ });
+
+ if (!this.onAnimationButtonClick) {
+ let animationButton = this.window.document.getElementById(
+ ANIMATION_BUTTON_ID
+ );
+ this.onAnimationButtonClick = async () => {
+ let animationLabel = this.window.document.getElementById(
+ ANIMATION_LABEL_ID
+ );
+ if (animationContainer.toggleAttribute("paused")) {
+ animationLabel.textContent = await this.getStrings({
+ string_id: "cfr-doorhanger-pintab-animation-resume",
+ });
+ } else {
+ animationLabel.textContent = await this.getStrings({
+ string_id: "cfr-doorhanger-pintab-animation-pause",
+ });
+ }
+ };
+ animationButton.addEventListener("click", this.onAnimationButtonClick);
+ }
+ }
+
+ async _renderMilestonePopup(message, browser) {
+ this.maybeLoadCustomElement(this.window);
+
+ let { content, id } = message;
+ let { primary, secondary } = content.buttons;
+
+ let dateFormat = new Services.intl.DateTimeFormat(
+ this.window.gBrowser.ownerGlobal.navigator.language,
+ {
+ month: "long",
+ year: "numeric",
+ }
+ ).format;
+
+ let earliestDate = await TrackingDBService.getEarliestRecordedDate();
+ let monthName = dateFormat(new Date(earliestDate));
+ let panelTitle = "";
+ let headerLabel = this.window.document.getElementById(
+ "cfr-notification-header-label"
+ );
+ let reachedMilestone = 0;
+ let totalSaved = await TrackingDBService.sumAllEvents();
+ for (let milestone of milestones) {
+ if (totalSaved >= milestone) {
+ reachedMilestone = milestone;
+ }
+ }
+ if (headerLabel.firstChild) {
+ headerLabel.firstChild.remove();
+ }
+ headerLabel.appendChild(
+ RemoteL10n.createElement(this.window.document, "span", {
+ content: message.content.heading_text,
+ attributes: {
+ blockedCount: reachedMilestone,
+ date: monthName,
+ },
+ })
+ );
+
+ // Use the message layout as a CSS selector to hide different parts of the
+ // notification template markup
+ this.window.document
+ .getElementById("contextual-feature-recommendation-notification")
+ .setAttribute("data-notification-category", content.layout);
+ this.window.document
+ .getElementById("contextual-feature-recommendation-notification")
+ .setAttribute("data-notification-bucket", content.bucket_id);
+ let notification = this.window.document.getElementById(
+ "notification-popup"
+ );
+
+ let primaryBtnString = await this.getStrings(primary.label);
+ let primaryActionCallback = () => {
+ this.dispatchUserAction(primary.action);
+ this._sendTelemetry({
+ message_id: id,
+ bucket_id: content.bucket_id,
+ event: "CLICK_BUTTON",
+ });
+
+ RecommendationMap.delete(browser);
+ // Invalidate the pref after the user interacts with the button.
+ // We don't need to show the illustration in the privacy panel.
+ Services.prefs.clearUserPref(
+ "browser.contentblocking.cfr-milestone.milestone-shown-time"
+ );
+ };
+
+ let secondaryBtnString = await this.getStrings(secondary[0].label);
+ let secondaryActionsCallback = () => {
+ this.dispatchUserAction(secondary[0].action);
+ this._sendTelemetry({
+ message_id: id,
+ bucket_id: content.bucket_id,
+ event: "DISMISS",
+ });
+ RecommendationMap.delete(browser);
+ };
+
+ let mainAction = {
+ label: primaryBtnString,
+ accessKey: primaryBtnString.attributes.accesskey,
+ callback: primaryActionCallback,
+ };
+
+ let secondaryActions = [
+ {
+ label: secondaryBtnString,
+ accessKey: secondaryBtnString.attributes.accesskey,
+ callback: secondaryActionsCallback,
+ },
+ ];
+
+ let style = this.window.document.createElement("style");
+ style.textContent = `
+ .cfr-notification-milestone .panel-arrow {
+ fill: #0250BB !important;
+ }
+ `;
+ style.classList.add("milestone-style");
+
+ let arrow;
+ let manageClass = event => {
+ if (event === "dismissed" || event === "removed") {
+ style = notification.shadowRoot.querySelector(".milestone-style");
+ if (style) {
+ notification.shadowRoot.removeChild(style);
+ }
+ arrow.classList.remove("cfr-notification-milestone");
+ } else if (event === "showing") {
+ notification.shadowRoot.appendChild(style);
+ arrow = notification.shadowRoot.querySelector(".panel-arrowcontainer");
+ arrow.classList.add("cfr-notification-milestone");
+ }
+ };
+
+ // Actually show the notification
+ this.currentNotification = this.window.PopupNotifications.show(
+ browser,
+ POPUP_NOTIFICATION_ID,
+ panelTitle,
+ "cfr",
+ mainAction,
+ secondaryActions,
+ {
+ hideClose: true,
+ eventCallback: manageClass,
+ persistWhileVisible: true,
+ }
+ );
+ Services.prefs.setIntPref(
+ "browser.contentblocking.cfr-milestone.milestone-achieved",
+ reachedMilestone
+ );
+ Services.prefs.setStringPref(
+ "browser.contentblocking.cfr-milestone.milestone-shown-time",
+ Date.now().toString()
+ );
+ }
+
+ // eslint-disable-next-line max-statements
+ async _renderPopup(message, browser) {
+ this.maybeLoadCustomElement(this.window);
+
+ const { id, content, modelVersion } = message;
+
+ const headerLabel = this.window.document.getElementById(
+ "cfr-notification-header-label"
+ );
+ const headerLink = this.window.document.getElementById(
+ "cfr-notification-header-link"
+ );
+ const headerImage = this.window.document.getElementById(
+ "cfr-notification-header-image"
+ );
+ const footerText = this.window.document.getElementById(
+ "cfr-notification-footer-text"
+ );
+ const footerLink = this.window.document.getElementById(
+ "cfr-notification-footer-learn-more-link"
+ );
+ const { primary, secondary } = content.buttons;
+ let primaryActionCallback;
+ let options = { persistent: !!content.persistent_doorhanger };
+ let panelTitle;
+
+ headerLabel.value = await this.getStrings(content.heading_text);
+ headerLink.setAttribute(
+ "href",
+ SUMO_BASE_URL + content.info_icon.sumo_path
+ );
+ headerImage.setAttribute(
+ "tooltiptext",
+ await this.getStrings(content.info_icon.label, "tooltiptext")
+ );
+ headerLink.onclick = () =>
+ this._sendTelemetry({
+ message_id: id,
+ bucket_id: content.bucket_id,
+ event: "RATIONALE",
+ ...(modelVersion ? { event_context: { modelVersion } } : {}),
+ });
+ // Use the message layout as a CSS selector to hide different parts of the
+ // notification template markup
+ this.window.document
+ .getElementById("contextual-feature-recommendation-notification")
+ .setAttribute("data-notification-category", content.layout);
+ this.window.document
+ .getElementById("contextual-feature-recommendation-notification")
+ .setAttribute("data-notification-bucket", content.bucket_id);
+
+ switch (content.layout) {
+ case "icon_and_message":
+ const author = this.window.document.getElementById(
+ "cfr-notification-author"
+ );
+ if (author.firstChild) {
+ author.firstChild.remove();
+ }
+ author.appendChild(
+ RemoteL10n.createElement(this.window.document, "span", {
+ content: content.text,
+ })
+ );
+ primaryActionCallback = () => {
+ this._blockMessage(id);
+ this.dispatchUserAction(primary.action);
+ this.hideAddressBarNotifier();
+ this._sendTelemetry({
+ message_id: id,
+ bucket_id: content.bucket_id,
+ event: "ENABLE",
+ ...(modelVersion ? { event_context: { modelVersion } } : {}),
+ });
+ RecommendationMap.delete(browser);
+ };
+
+ let getIcon = () => {
+ if (content.icon_dark_theme && this.isDarkTheme) {
+ return content.icon_dark_theme;
+ }
+ return content.icon;
+ };
+
+ let learnMoreURL = content.learn_more
+ ? SUMO_BASE_URL + content.learn_more
+ : null;
+
+ panelTitle = await this.getStrings(content.heading_text);
+ options = {
+ popupIconURL: getIcon(),
+ popupIconClass: content.icon_class,
+ learnMoreURL,
+ ...options,
+ };
+ break;
+ case "message_and_animation":
+ footerText.textContent = await this.getStrings(content.text);
+ const stepsContainerId = "cfr-notification-feature-steps";
+ let stepsContainer = this.window.document.getElementById(
+ stepsContainerId
+ );
+ primaryActionCallback = () => {
+ this._blockMessage(id);
+ this.dispatchUserAction(primary.action);
+ this.hideAddressBarNotifier();
+ this._sendTelemetry({
+ message_id: id,
+ bucket_id: content.bucket_id,
+ event: "PIN",
+ ...(modelVersion ? { event_context: { modelVersion } } : {}),
+ });
+ RecommendationMap.delete(browser);
+ };
+ panelTitle = await this.getStrings(content.heading_text);
+
+ if (content.descriptionDetails) {
+ if (stepsContainer) {
+ // If it exists we need to empty it
+ stepsContainer.remove();
+ stepsContainer = stepsContainer.cloneNode(false);
+ } else {
+ stepsContainer = this.window.document.createXULElement("vbox");
+ stepsContainer.setAttribute("id", stepsContainerId);
+ }
+ footerText.parentNode.appendChild(stepsContainer);
+ for (let step of content.descriptionDetails.steps) {
+ // This li is a generic xul element with custom styling
+ const li = this.window.document.createXULElement("li");
+ li.appendChild(
+ RemoteL10n.createElement(this.window.document, "span", {
+ content: step,
+ })
+ );
+ stepsContainer.appendChild(li);
+ }
+ }
+
+ await this._renderPinTabAnimation();
+ break;
+ default:
+ panelTitle = await this.getStrings(content.addon.title);
+ await this._setAddonAuthorAndRating(this.window.document, content);
+ if (footerText.firstChild) {
+ footerText.firstChild.remove();
+ }
+ // Main body content of the dropdown
+ footerText.appendChild(
+ RemoteL10n.createElement(this.window.document, "span", {
+ content: content.text,
+ })
+ );
+ options = { popupIconURL: content.addon.icon, ...options };
+
+ footerLink.value = await this.getStrings({
+ string_id: "cfr-doorhanger-extension-learn-more-link",
+ });
+ footerLink.setAttribute("href", content.addon.amo_url);
+ footerLink.onclick = () =>
+ this._sendTelemetry({
+ message_id: id,
+ bucket_id: content.bucket_id,
+ event: "LEARN_MORE",
+ ...(modelVersion ? { event_context: { modelVersion } } : {}),
+ });
+
+ primaryActionCallback = async () => {
+ // eslint-disable-next-line no-use-before-define
+ primary.action.data.url = await CFRPageActions._fetchLatestAddonVersion(
+ content.addon.id
+ );
+ this._blockMessage(id);
+ this.dispatchUserAction(primary.action);
+ this.hideAddressBarNotifier();
+ this._sendTelemetry({
+ message_id: id,
+ bucket_id: content.bucket_id,
+ event: "INSTALL",
+ ...(modelVersion ? { event_context: { modelVersion } } : {}),
+ });
+ RecommendationMap.delete(browser);
+ };
+ }
+
+ const primaryBtnStrings = await this.getStrings(primary.label);
+ const mainAction = {
+ label: primaryBtnStrings,
+ accessKey: primaryBtnStrings.attributes.accesskey,
+ callback: primaryActionCallback,
+ };
+
+ let _renderSecondaryButtonAction = async (event, button) => {
+ let label = await this.getStrings(button.label);
+ let { attributes } = label;
+
+ return {
+ label,
+ accessKey: attributes.accesskey,
+ callback: () => {
+ if (button.action) {
+ this.dispatchUserAction(button.action);
+ } else {
+ this._blockMessage(id);
+ this.hideAddressBarNotifier();
+ RecommendationMap.delete(browser);
+ }
+
+ this._sendTelemetry({
+ message_id: id,
+ bucket_id: content.bucket_id,
+ event,
+ ...(modelVersion ? { event_context: { modelVersion } } : {}),
+ });
+ // We want to collapse if needed when we dismiss
+ this._collapse();
+ },
+ };
+ };
+
+ // For each secondary action, define default telemetry event
+ const defaultSecondaryEvent = ["DISMISS", "BLOCK", "MANAGE"];
+ const secondaryActions = await Promise.all(
+ secondary.map((button, i) => {
+ return _renderSecondaryButtonAction(
+ button.event || defaultSecondaryEvent[i],
+ button
+ );
+ })
+ );
+
+ // If the recommendation button is focused, it was probably activated via
+ // the keyboard. Therefore, focus the first element in the notification when
+ // it appears.
+ // We don't use the autofocus option provided by PopupNotifications.show
+ // because it doesn't focus the first element; i.e. the user still has to
+ // press tab once. That's not good enough, especially for screen reader
+ // users. Instead, we handle this ourselves in _popupStateChange.
+ this._autoFocus = this.window.document.activeElement === this.container;
+
+ // Actually show the notification
+ this.currentNotification = this.window.PopupNotifications.show(
+ browser,
+ POPUP_NOTIFICATION_ID,
+ panelTitle,
+ "cfr",
+ mainAction,
+ secondaryActions,
+ {
+ ...options,
+ hideClose: true,
+ eventCallback: this._popupStateChange,
+ }
+ );
+ }
+
+ _executeNotifierAction(browser, message) {
+ switch (message.content.layout) {
+ case "chiclet_open_url":
+ this._dispatchCFRAction(
+ {
+ type: "USER_ACTION",
+ data: {
+ type: "OPEN_URL",
+ data: {
+ args: message.content.action.url,
+ where: message.content.action.where,
+ },
+ },
+ },
+ this.window
+ );
+ break;
+ }
+
+ this._blockMessage(message.id);
+ this.hideAddressBarNotifier();
+ RecommendationMap.delete(browser);
+ }
+
+ /**
+ * Respond to a user click on the recommendation by showing a doorhanger/
+ * popup notification or running the action defined in the message
+ */
+ async _cfrUrlbarButtonClick(event) {
+ const browser = this.window.gBrowser.selectedBrowser;
+ if (!RecommendationMap.has(browser)) {
+ // There's no recommendation for this browser, so the user shouldn't have
+ // been able to click
+ this.hideAddressBarNotifier();
+ return;
+ }
+ const message = RecommendationMap.get(browser);
+ const { id, content, modelVersion } = message;
+
+ this._sendTelemetry({
+ message_id: id,
+ bucket_id: content.bucket_id,
+ event: "CLICK_DOORHANGER",
+ ...(modelVersion ? { event_context: { modelVersion } } : {}),
+ });
+
+ if (this.shouldShowDoorhanger(message)) {
+ // The recommendation should remain either collapsed or expanded while the
+ // doorhanger is showing
+ this._clearScheduledStateChanges(browser, message);
+ await this.showPopup();
+ } else {
+ await this._executeNotifierAction(browser, message);
+ }
+ }
+
+ async showPopup() {
+ const browser = this.window.gBrowser.selectedBrowser;
+ const message = RecommendationMap.get(browser);
+ const { content } = message;
+
+ // A hacky way of setting the popup anchor outside the usual url bar icon box
+ // See https://searchfox.org/mozilla-central/rev/847b64cc28b74b44c379f9bff4f415b97da1c6d7/toolkit/modules/PopupNotifications.jsm#42
+ browser.cfrpopupnotificationanchor =
+ this.window.document.getElementById(content.anchor_id) || this.container;
+
+ await this._renderPopup(message, browser);
+ }
+
+ async showMilestonePopup() {
+ const browser = this.window.gBrowser.selectedBrowser;
+ const message = RecommendationMap.get(browser);
+ const { content } = message;
+
+ // A hacky way of setting the popup anchor outside the usual url bar icon box
+ // See https://searchfox.org/mozilla-central/rev/847b64cc28b74b44c379f9bff4f415b97da1c6d7/toolkit/modules/PopupNotifications.jsm#42
+ browser.cfrpopupnotificationanchor =
+ this.window.document.getElementById(content.anchor_id) || this.container;
+
+ await this._renderMilestonePopup(message, browser);
+ return true;
+ }
+}
+
+function isHostMatch(browser, host) {
+ return (
+ browser.documentURI.scheme.startsWith("http") &&
+ browser.documentURI.host === host
+ );
+}
+
+const CFRPageActions = {
+ // For testing purposes
+ RecommendationMap,
+ PageActionMap,
+
+ /**
+ * To be called from browser.js on a location change, passing in the browser
+ * that's been updated
+ */
+ updatePageActions(browser) {
+ const win = browser.ownerGlobal;
+ const pageAction = PageActionMap.get(win);
+ if (!pageAction || browser !== win.gBrowser.selectedBrowser) {
+ return;
+ }
+ if (RecommendationMap.has(browser)) {
+ const recommendation = RecommendationMap.get(browser);
+ if (
+ !recommendation.content.skip_address_bar_notifier &&
+ (isHostMatch(browser, recommendation.host) ||
+ // If there is no host associated we assume we're back on a tab
+ // that had a CFR message so we should show it again
+ !recommendation.host)
+ ) {
+ // The browser has a recommendation specified with this host, so show
+ // the page action
+ pageAction.showAddressBarNotifier(recommendation);
+ } else if (recommendation.retain) {
+ // Keep the recommendation first time the user navigates away just in
+ // case they will go back to the previous page
+ pageAction.hideAddressBarNotifier();
+ recommendation.retain = false;
+ } else {
+ // The user has navigated away from the specified host in the given
+ // browser, so the recommendation is no longer valid and should be removed
+ RecommendationMap.delete(browser);
+ pageAction.hideAddressBarNotifier();
+ }
+ } else {
+ // There's no recommendation specified for this browser, so hide the page action
+ pageAction.hideAddressBarNotifier();
+ }
+ },
+
+ /**
+ * Fetch the URL to the latest add-on xpi so the recommendation can download it.
+ * @param id The add-on ID
+ * @return A string for the URL that was fetched
+ */
+ async _fetchLatestAddonVersion(id) {
+ let url = null;
+ try {
+ const response = await fetch(`${ADDONS_API_URL}/${id}/`, {
+ credentials: "omit",
+ });
+ if (response.status !== 204 && response.ok) {
+ const json = await response.json();
+ url = json.current_version.files[0].url;
+ }
+ } catch (e) {
+ Cu.reportError(
+ "Failed to get the latest add-on version for this recommendation"
+ );
+ }
+ return url;
+ },
+
+ /**
+ * Force a recommendation to be shown. Should only happen via the Admin page.
+ * @param browser The browser for the recommendation
+ * @param recommendation The recommendation to show
+ * @param dispatchCFRAction A function to dispatch resulting actions to
+ * @return Did adding the recommendation succeed?
+ */
+ async forceRecommendation(browser, recommendation, dispatchCFRAction) {
+ // If we are forcing via the Admin page, the browser comes in a different format
+ const win = browser.ownerGlobal;
+ const { id, content, personalizedModelVersion } = recommendation;
+ RecommendationMap.set(browser, {
+ id,
+ content,
+ retain: true,
+ modelVersion: personalizedModelVersion,
+ });
+ if (!PageActionMap.has(win)) {
+ PageActionMap.set(win, new PageAction(win, dispatchCFRAction));
+ }
+
+ if (content.skip_address_bar_notifier) {
+ if (recommendation.template === "milestone_message") {
+ await PageActionMap.get(win).showMilestonePopup();
+ PageActionMap.get(win).addImpression(recommendation);
+ } else {
+ await PageActionMap.get(win).showPopup();
+ PageActionMap.get(win).addImpression(recommendation);
+ }
+ } else {
+ await PageActionMap.get(win).showAddressBarNotifier(recommendation, true);
+ }
+ return true;
+ },
+
+ /**
+ * Add a recommendation specific to the given browser and host.
+ * @param browser The browser for the recommendation
+ * @param host The host for the recommendation
+ * @param recommendation The recommendation to show
+ * @param dispatchCFRAction A function to dispatch resulting actions to
+ * @return Did adding the recommendation succeed?
+ */
+ async addRecommendation(browser, host, recommendation, dispatchCFRAction) {
+ const win = browser.ownerGlobal;
+ if (PrivateBrowsingUtils.isWindowPrivate(win)) {
+ return false;
+ }
+ if (
+ browser !== win.gBrowser.selectedBrowser ||
+ // We can have recommendations without URL restrictions
+ (host && !isHostMatch(browser, host))
+ ) {
+ return false;
+ }
+ if (RecommendationMap.has(browser)) {
+ // Don't replace an existing message
+ return false;
+ }
+ const { id, content, personalizedModelVersion } = recommendation;
+ RecommendationMap.set(browser, {
+ id,
+ host,
+ content,
+ retain: true,
+ modelVersion: personalizedModelVersion,
+ });
+ if (!PageActionMap.has(win)) {
+ PageActionMap.set(win, new PageAction(win, dispatchCFRAction));
+ }
+
+ if (content.skip_address_bar_notifier) {
+ if (recommendation.template === "milestone_message") {
+ await PageActionMap.get(win).showMilestonePopup();
+ PageActionMap.get(win).addImpression(recommendation);
+ } else {
+ // Tracking protection messages
+ await PageActionMap.get(win).showPopup();
+ PageActionMap.get(win).addImpression(recommendation);
+ }
+ } else {
+ // Doorhanger messages
+ await PageActionMap.get(win).showAddressBarNotifier(recommendation, true);
+ }
+ return true;
+ },
+
+ /**
+ * Clear all recommendations and hide all PageActions
+ */
+ clearRecommendations() {
+ // WeakMaps aren't iterable so we have to test all existing windows
+ for (const win of Services.wm.getEnumerator("navigator:browser")) {
+ if (win.closed || !PageActionMap.has(win)) {
+ continue;
+ }
+ PageActionMap.get(win).hideAddressBarNotifier();
+ }
+ // WeakMaps don't have a `clear` method
+ PageActionMap = new WeakMap();
+ RecommendationMap = new WeakMap();
+ this.PageActionMap = PageActionMap;
+ this.RecommendationMap = RecommendationMap;
+ },
+
+ /**
+ * Reload the l10n Fluent files for all PageActions
+ */
+ reloadL10n() {
+ for (const win of Services.wm.getEnumerator("navigator:browser")) {
+ if (win.closed || !PageActionMap.has(win)) {
+ continue;
+ }
+ PageActionMap.get(win).reloadL10n();
+ }
+ },
+};
+
+this.PageAction = PageAction;
+this.CFRPageActions = CFRPageActions;
+
+const EXPORTED_SYMBOLS = ["CFRPageActions", "PageAction"];
diff --git a/browser/components/newtab/lib/DefaultSites.jsm b/browser/components/newtab/lib/DefaultSites.jsm
new file mode 100644
index 0000000000..9bb9ef66ce
--- /dev/null
+++ b/browser/components/newtab/lib/DefaultSites.jsm
@@ -0,0 +1,50 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+const DEFAULT_SITES_MAP = new Map([
+ // This first item is the global list fallback for any unexpected geos
+ [
+ "",
+ "https://www.youtube.com/,https://www.facebook.com/,https://www.wikipedia.org/,https://www.reddit.com/,https://www.amazon.com/,https://twitter.com/",
+ ],
+ [
+ "US",
+ "https://www.youtube.com/,https://www.facebook.com/,https://www.amazon.com/,https://www.reddit.com/,https://www.wikipedia.org/,https://twitter.com/",
+ ],
+ [
+ "CA",
+ "https://www.youtube.com/,https://www.facebook.com/,https://www.reddit.com/,https://www.wikipedia.org/,https://www.amazon.ca/,https://twitter.com/",
+ ],
+ [
+ "DE",
+ "https://www.youtube.com/,https://www.facebook.com/,https://www.amazon.de/,https://www.ebay.de/,https://www.wikipedia.org/,https://www.reddit.com/",
+ ],
+ [
+ "PL",
+ "https://www.youtube.com/,https://www.facebook.com/,https://allegro.pl/,https://www.wikipedia.org/,https://www.olx.pl/,https://www.wykop.pl/",
+ ],
+ [
+ "RU",
+ "https://vk.com/,https://www.youtube.com/,https://ok.ru/,https://www.avito.ru/,https://www.aliexpress.com/,https://www.wikipedia.org/",
+ ],
+ [
+ "GB",
+ "https://www.youtube.com/,https://www.facebook.com/,https://www.reddit.com/,https://www.amazon.co.uk/,https://www.bbc.co.uk/,https://www.ebay.co.uk/",
+ ],
+ [
+ "FR",
+ "https://www.youtube.com/,https://www.facebook.com/,https://www.wikipedia.org/,https://www.amazon.fr/,https://www.leboncoin.fr/,https://twitter.com/",
+ ],
+ [
+ "CN",
+ "https://www.baidu.com/,https://www.zhihu.com/,https://www.ifeng.com/,https://weibo.com/,https://www.ctrip.com/,https://www.iqiyi.com/",
+ ],
+]);
+
+this.EXPORTED_SYMBOLS = ["DEFAULT_SITES"];
+
+// Immutable for export.
+this.DEFAULT_SITES = Object.freeze(DEFAULT_SITES_MAP);
diff --git a/browser/components/newtab/lib/DiscoveryStreamFeed.jsm b/browser/components/newtab/lib/DiscoveryStreamFeed.jsm
new file mode 100644
index 0000000000..8bacb3c29e
--- /dev/null
+++ b/browser/components/newtab/lib/DiscoveryStreamFeed.jsm
@@ -0,0 +1,1945 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
+const { XPCOMUtils } = ChromeUtils.import(
+ "resource://gre/modules/XPCOMUtils.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "NewTabUtils",
+ "resource://gre/modules/NewTabUtils.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "RemoteSettings",
+ "resource://services-settings/remote-settings.js"
+);
+const { setTimeout, clearTimeout } = ChromeUtils.import(
+ "resource://gre/modules/Timer.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "Services",
+ "resource://gre/modules/Services.jsm"
+);
+XPCOMUtils.defineLazyGlobalGetters(this, ["fetch"]);
+const { actionTypes: at, actionCreators: ac } = ChromeUtils.import(
+ "resource://activity-stream/common/Actions.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "Region",
+ "resource://gre/modules/Region.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "PersistentCache",
+ "resource://activity-stream/lib/PersistentCache.jsm"
+);
+XPCOMUtils.defineLazyServiceGetters(this, {
+ gUUIDGenerator: ["@mozilla.org/uuid-generator;1", "nsIUUIDGenerator"],
+});
+
+const CACHE_KEY = "discovery_stream";
+const LAYOUT_UPDATE_TIME = 30 * 60 * 1000; // 30 minutes
+const STARTUP_CACHE_EXPIRE_TIME = 7 * 24 * 60 * 60 * 1000; // 1 week
+const COMPONENT_FEEDS_UPDATE_TIME = 30 * 60 * 1000; // 30 minutes
+const SPOCS_FEEDS_UPDATE_TIME = 30 * 60 * 1000; // 30 minutes
+const DEFAULT_RECS_EXPIRE_TIME = 60 * 60 * 1000; // 1 hour
+const MIN_DOMAIN_AFFINITIES_UPDATE_TIME = 12 * 60 * 60 * 1000; // 12 hours
+const MAX_LIFETIME_CAP = 500; // Guard against misconfiguration on the server
+const DEFAULT_MAX_HISTORY_QUERY_RESULTS = 1000;
+const FETCH_TIMEOUT = 45 * 1000;
+const PREF_CONFIG = "discoverystream.config";
+const PREF_ENDPOINTS = "discoverystream.endpoints";
+const PREF_IMPRESSION_ID = "browser.newtabpage.activity-stream.impressionId";
+const PREF_ENABLED = "discoverystream.enabled";
+const PREF_HARDCODED_BASIC_LAYOUT = "discoverystream.hardcoded-basic-layout";
+const PREF_SPOCS_ENDPOINT = "discoverystream.spocs-endpoint";
+const PREF_SPOCS_ENDPOINT_QUERY = "discoverystream.spocs-endpoint-query";
+const PREF_REGION_BASIC_LAYOUT = "discoverystream.region-basic-layout";
+const PREF_USER_TOPSTORIES = "feeds.section.topstories";
+const PREF_SYSTEM_TOPSTORIES = "feeds.system.topstories";
+const PREF_SPOCS_CLEAR_ENDPOINT = "discoverystream.endpointSpocsClear";
+const PREF_SHOW_SPONSORED = "showSponsored";
+const PREF_SPOC_IMPRESSIONS = "discoverystream.spoc.impressions";
+const PREF_FLIGHT_BLOCKS = "discoverystream.flight.blocks";
+const PREF_REC_IMPRESSIONS = "discoverystream.rec.impressions";
+const PREF_COLLECTION_DISMISSIBLE = "discoverystream.isCollectionDismissible";
+const PREF_RECS_PERSONALIZED = "discoverystream.recs.personalized";
+const PREF_SPOCS_PERSONALIZED = "discoverystream.spocs.personalized";
+const PREF_PERSONALIZATION_VERSION = "discoverystream.personalization.version";
+const PREF_PERSONALIZATION_OVERRIDE_VERSION =
+ "discoverystream.personalization.overrideVersion";
+
+let getHardcodedLayout;
+
+this.DiscoveryStreamFeed = class DiscoveryStreamFeed {
+ constructor() {
+ // Internal state for checking if we've intialized all our data
+ this.loaded = false;
+
+ // Persistent cache for remote endpoint data.
+ this.cache = new PersistentCache(CACHE_KEY, true);
+ this.locale = Services.locale.appLocaleAsBCP47;
+ this._impressionId = this.getOrCreateImpressionId();
+ // Internal in-memory cache for parsing json prefs.
+ this._prefCache = {};
+ }
+
+ getOrCreateImpressionId() {
+ let impressionId = Services.prefs.getCharPref(PREF_IMPRESSION_ID, "");
+ if (!impressionId) {
+ impressionId = String(gUUIDGenerator.generateUUID());
+ Services.prefs.setCharPref(PREF_IMPRESSION_ID, impressionId);
+ }
+ return impressionId;
+ }
+
+ finalLayoutEndpoint(url, apiKey) {
+ if (url.includes("$apiKey") && !apiKey) {
+ throw new Error(
+ `Layout Endpoint - An API key was specified but none configured: ${url}`
+ );
+ }
+ return url.replace("$apiKey", apiKey);
+ }
+
+ get config() {
+ if (this._prefCache.config) {
+ return this._prefCache.config;
+ }
+ try {
+ this._prefCache.config = JSON.parse(
+ this.store.getState().Prefs.values[PREF_CONFIG]
+ );
+ const layoutUrl = this._prefCache.config.layout_endpoint;
+
+ const apiKeyPref = this._prefCache.config.api_key_pref;
+ if (layoutUrl && apiKeyPref) {
+ const apiKey = Services.prefs.getCharPref(apiKeyPref, "");
+ this._prefCache.config.layout_endpoint = this.finalLayoutEndpoint(
+ layoutUrl,
+ apiKey
+ );
+ }
+ } catch (e) {
+ // istanbul ignore next
+ this._prefCache.config = {};
+ // istanbul ignore next
+ Cu.reportError(
+ `Could not parse preference. Try resetting ${PREF_CONFIG} in about:config. ${e}`
+ );
+ }
+ this._prefCache.config.enabled =
+ this._prefCache.config.enabled &&
+ this.store.getState().Prefs.values[PREF_ENABLED];
+
+ return this._prefCache.config;
+ }
+
+ resetConfigDefauts() {
+ this.store.dispatch({
+ type: at.CLEAR_PREF,
+ data: {
+ name: PREF_CONFIG,
+ },
+ });
+ }
+
+ get region() {
+ return Region.home;
+ }
+
+ get showSpocs() {
+ // Combine user-set sponsored opt-out with Mozilla-set config
+ return (
+ this.store.getState().Prefs.values[PREF_SHOW_SPONSORED] &&
+ this.config.show_spocs
+ );
+ }
+
+ get showStories() {
+ // Combine user-set sponsored opt-out with Mozilla-set config
+ return (
+ this.store.getState().Prefs.values[PREF_SYSTEM_TOPSTORIES] &&
+ this.store.getState().Prefs.values[PREF_USER_TOPSTORIES]
+ );
+ }
+
+ get personalized() {
+ // If both spocs and recs are not personalized, we might as well return false here.
+ const spocsPersonalized = this.store.getState().Prefs.values[
+ PREF_SPOCS_PERSONALIZED
+ ];
+ const recsPersonalized = this.store.getState().Prefs.values[
+ PREF_RECS_PERSONALIZED
+ ];
+
+ return (
+ this.config.personalized &&
+ !!this.providerSwitcher &&
+ (spocsPersonalized || recsPersonalized)
+ );
+ }
+
+ get providerSwitcher() {
+ if (this._providerSwitcher) {
+ return this._providerSwitcher;
+ }
+ this._providerSwitcher = this.store.feeds.get(
+ "feeds.recommendationproviderswitcher"
+ );
+ return this._providerSwitcher;
+ }
+
+ setupPrefs(isStartup = false) {
+ // Send the initial state of the pref on our reducer
+ this.store.dispatch(
+ ac.BroadcastToContent({
+ type: at.DISCOVERY_STREAM_CONFIG_SETUP,
+ data: this.config,
+ meta: {
+ isStartup,
+ },
+ })
+ );
+ this.store.dispatch(
+ ac.BroadcastToContent({
+ type: at.DISCOVERY_STREAM_COLLECTION_DISMISSIBLE_TOGGLE,
+ data: {
+ value: this.store.getState().Prefs.values[
+ PREF_COLLECTION_DISMISSIBLE
+ ],
+ },
+ meta: {
+ isStartup,
+ },
+ })
+ );
+ }
+
+ uninitPrefs() {
+ // Reset in-memory cache
+ this._prefCache = {};
+ }
+
+ async fetchFromEndpoint(rawEndpoint, options = {}) {
+ if (!rawEndpoint) {
+ Cu.reportError("Tried to fetch endpoint but none was configured.");
+ return null;
+ }
+
+ const apiKeyPref = this._prefCache.config.api_key_pref;
+ const apiKey = Services.prefs.getCharPref(apiKeyPref, "");
+
+ // The server somtimes returns this value already replaced, but we try this for two reasons:
+ // 1. Layout endpoints are not from the server.
+ // 2. Hardcoded layouts don't have this already done for us.
+ const endpoint = rawEndpoint
+ .replace("$apiKey", apiKey)
+ .replace("$locale", this.locale)
+ .replace("$region", this.region);
+
+ try {
+ // Make sure the requested endpoint is allowed
+ const allowed = this.store
+ .getState()
+ .Prefs.values[PREF_ENDPOINTS].split(",");
+ if (!allowed.some(prefix => endpoint.startsWith(prefix))) {
+ throw new Error(`Not one of allowed prefixes (${allowed})`);
+ }
+
+ const controller = new AbortController();
+ const { signal } = controller;
+
+ const fetchPromise = fetch(endpoint, {
+ ...options,
+ credentials: "omit",
+ signal,
+ });
+ // istanbul ignore next
+ const timeoutId = setTimeout(() => {
+ controller.abort();
+ }, FETCH_TIMEOUT);
+
+ const response = await fetchPromise;
+ if (!response.ok) {
+ throw new Error(`Unexpected status (${response.status})`);
+ }
+ clearTimeout(timeoutId);
+ return response.json();
+ } catch (error) {
+ Cu.reportError(`Failed to fetch ${endpoint}: ${error.message}`);
+ }
+ return null;
+ }
+
+ /**
+ * Returns true if data in the cache for a particular key has expired or is missing.
+ * @param {object} cachedData data returned from cache.get()
+ * @param {string} key a cache key
+ * @param {string?} url for "feed" only, the URL of the feed.
+ * @param {boolean} is this check done at initial browser load
+ */
+ isExpired({ cachedData, key, url, isStartup }) {
+ const { layout, spocs, feeds } = cachedData;
+ const updateTimePerComponent = {
+ layout: LAYOUT_UPDATE_TIME,
+ spocs: SPOCS_FEEDS_UPDATE_TIME,
+ feed: COMPONENT_FEEDS_UPDATE_TIME,
+ };
+ const EXPIRATION_TIME = isStartup
+ ? STARTUP_CACHE_EXPIRE_TIME
+ : updateTimePerComponent[key];
+ switch (key) {
+ case "layout":
+ // This never needs to expire, as it's not expected to change.
+ if (this.config.hardcoded_layout) {
+ return false;
+ }
+ return !layout || !(Date.now() - layout.lastUpdated < EXPIRATION_TIME);
+ case "spocs":
+ return !spocs || !(Date.now() - spocs.lastUpdated < EXPIRATION_TIME);
+ case "feed":
+ return (
+ !feeds ||
+ !feeds[url] ||
+ !(Date.now() - feeds[url].lastUpdated < EXPIRATION_TIME)
+ );
+ default:
+ // istanbul ignore next
+ throw new Error(`${key} is not a valid key`);
+ }
+ }
+
+ async _checkExpirationPerComponent() {
+ const cachedData = (await this.cache.get()) || {};
+ const { feeds } = cachedData;
+ return {
+ layout: this.isExpired({ cachedData, key: "layout" }),
+ spocs: this.isExpired({ cachedData, key: "spocs" }),
+ feeds:
+ !feeds ||
+ Object.keys(feeds).some(url =>
+ this.isExpired({ cachedData, key: "feed", url })
+ ),
+ };
+ }
+
+ /**
+ * Returns true if any data for the cached endpoints has expired or is missing.
+ */
+ async checkIfAnyCacheExpired() {
+ const expirationPerComponent = await this._checkExpirationPerComponent();
+ return (
+ expirationPerComponent.layout ||
+ expirationPerComponent.spocs ||
+ expirationPerComponent.feeds
+ );
+ }
+
+ async fetchLayout(isStartup) {
+ const cachedData = (await this.cache.get()) || {};
+ let { layout } = cachedData;
+ if (this.isExpired({ cachedData, key: "layout", isStartup })) {
+ const layoutResponse = await this.fetchFromEndpoint(
+ this.config.layout_endpoint
+ );
+ if (layoutResponse && layoutResponse.layout) {
+ layout = {
+ lastUpdated: Date.now(),
+ spocs: layoutResponse.spocs,
+ layout: layoutResponse.layout,
+ status: "success",
+ };
+
+ await this.cache.set("layout", layout);
+ } else {
+ Cu.reportError("No response for response.layout prop");
+ }
+ }
+ return layout;
+ }
+
+ updatePlacements(sendUpdate, layout, isStartup = false) {
+ const placements = [];
+ const placementsMap = {};
+ for (const row of layout.filter(r => r.components && r.components.length)) {
+ for (const component of row.components) {
+ if (component.placement) {
+ // Throw away any dupes for the request.
+ if (!placementsMap[component.placement.name]) {
+ placementsMap[component.placement.name] = component.placement;
+ placements.push(component.placement);
+ }
+ }
+ }
+ }
+ if (placements.length) {
+ sendUpdate({
+ type: at.DISCOVERY_STREAM_SPOCS_PLACEMENTS,
+ data: { placements },
+ meta: {
+ isStartup,
+ },
+ });
+ }
+ }
+
+ /**
+ * Adds a query string to a URL.
+ * A query can be any string literal accepted by https://developer.mozilla.org/docs/Web/API/URLSearchParams
+ * Examples: "?foo=1&bar=2", "&foo=1&bar=2", "foo=1&bar=2", "?bar=2" or "bar=2"
+ */
+ addEndpointQuery(url, query) {
+ if (!query) {
+ return url;
+ }
+
+ const urlObject = new URL(url);
+ const params = new URLSearchParams(query);
+
+ for (let [key, val] of params.entries()) {
+ urlObject.searchParams.append(key, val);
+ }
+
+ return urlObject.toString();
+ }
+
+ async loadLayout(sendUpdate, isStartup) {
+ let layoutResp = {};
+ let url = "";
+ if (!this.config.hardcoded_layout) {
+ layoutResp = await this.fetchLayout(isStartup);
+ }
+
+ if (!layoutResp || !layoutResp.layout) {
+ const isBasic =
+ this.config.hardcoded_basic_layout ||
+ this.store.getState().Prefs.values[PREF_HARDCODED_BASIC_LAYOUT] ||
+ this.store.getState().Prefs.values[PREF_REGION_BASIC_LAYOUT];
+
+ // Set a hardcoded layout if one is needed.
+ // Changing values in this layout in memory object is unnecessary.
+ layoutResp = getHardcodedLayout(isBasic);
+ }
+
+ sendUpdate({
+ type: at.DISCOVERY_STREAM_LAYOUT_UPDATE,
+ data: layoutResp,
+ meta: {
+ isStartup,
+ },
+ });
+
+ if (layoutResp.spocs) {
+ url =
+ this.store.getState().Prefs.values[PREF_SPOCS_ENDPOINT] ||
+ this.config.spocs_endpoint ||
+ layoutResp.spocs.url;
+
+ const spocsEndpointQuery = this.store.getState().Prefs.values[
+ PREF_SPOCS_ENDPOINT_QUERY
+ ];
+
+ // For QA, testing, or debugging purposes, there may be a query string to add.
+ url = this.addEndpointQuery(url, spocsEndpointQuery);
+
+ if (
+ url &&
+ url !== this.store.getState().DiscoveryStream.spocs.spocs_endpoint
+ ) {
+ sendUpdate({
+ type: at.DISCOVERY_STREAM_SPOCS_ENDPOINT,
+ data: {
+ url,
+ },
+ meta: {
+ isStartup,
+ },
+ });
+ this.updatePlacements(sendUpdate, layoutResp.layout, isStartup);
+ }
+ }
+ }
+
+ /**
+ * buildFeedPromise - Adds the promise result to newFeeds and
+ * pushes a promise to newsFeedsPromises.
+ * @param {Object} Has both newFeedsPromises (Array) and newFeeds (Object)
+ * @param {Boolean} isStartup We have different cache handling for startup.
+ * @returns {Function} We return a function so we can contain
+ * the scope for isStartup and the promises object.
+ * Combines feed results and promises for each component with a feed.
+ */
+ buildFeedPromise(
+ { newFeedsPromises, newFeeds },
+ isStartup = false,
+ sendUpdate
+ ) {
+ return component => {
+ const { url } = component.feed;
+
+ if (!newFeeds[url]) {
+ // We initially stub this out so we don't fetch dupes,
+ // we then fill in with the proper object inside the promise.
+ newFeeds[url] = {};
+ const feedPromise = this.getComponentFeed(url, isStartup);
+
+ feedPromise
+ .then(feed => {
+ // If we stored the result of filter in feed cache as it happened,
+ // I think we could reduce doing this for cache fetches.
+ // Bug https://bugzilla.mozilla.org/show_bug.cgi?id=1606277
+ newFeeds[url] = this.filterRecommendations(feed);
+ sendUpdate({
+ type: at.DISCOVERY_STREAM_FEED_UPDATE,
+ data: {
+ feed: newFeeds[url],
+ url,
+ },
+ meta: {
+ isStartup,
+ },
+ });
+
+ // We grab affinities off the first feed for the moment.
+ // Ideally this would be returned from the server on the layout,
+ // or from another endpoint.
+ if (!this.affinities) {
+ const { settings } = feed.data;
+ this.affinities = {
+ timeSegments: settings.timeSegments,
+ parameterSets: settings.domainAffinityParameterSets,
+ maxHistoryQueryResults:
+ settings.maxHistoryQueryResults ||
+ DEFAULT_MAX_HISTORY_QUERY_RESULTS,
+ version: settings.version,
+ };
+ }
+ })
+ .catch(
+ /* istanbul ignore next */ error => {
+ Cu.reportError(
+ `Error trying to load component feed ${url}: ${error}`
+ );
+ }
+ );
+ newFeedsPromises.push(feedPromise);
+ }
+ };
+ }
+
+ filterRecommendations(feed) {
+ if (
+ feed &&
+ feed.data &&
+ feed.data.recommendations &&
+ feed.data.recommendations.length
+ ) {
+ const { data: recommendations } = this.filterBlocked(
+ feed.data.recommendations
+ );
+ return {
+ ...feed,
+ data: {
+ ...feed.data,
+ recommendations,
+ },
+ };
+ }
+ return feed;
+ }
+
+ /**
+ * reduceFeedComponents - Filters out components with no feeds, and combines
+ * all feeds on this component with the feeds from other components.
+ * @param {Boolean} isStartup We have different cache handling for startup.
+ * @returns {Function} We return a function so we can contain the scope for isStartup.
+ * Reduces feeds into promises and feed data.
+ */
+ reduceFeedComponents(isStartup, sendUpdate) {
+ return (accumulator, row) => {
+ row.components
+ .filter(component => component && component.feed)
+ .forEach(this.buildFeedPromise(accumulator, isStartup, sendUpdate));
+ return accumulator;
+ };
+ }
+
+ /**
+ * buildFeedPromises - Filters out rows with no components,
+ * and gets us a promise for each unique feed.
+ * @param {Object} layout This is the Discovery Stream layout object.
+ * @param {Boolean} isStartup We have different cache handling for startup.
+ * @returns {Object} An object with newFeedsPromises (Array) and newFeeds (Object),
+ * we can Promise.all newFeedsPromises to get completed data in newFeeds.
+ */
+ buildFeedPromises(layout, isStartup, sendUpdate) {
+ const initialData = {
+ newFeedsPromises: [],
+ newFeeds: {},
+ };
+ return layout
+ .filter(row => row && row.components)
+ .reduce(this.reduceFeedComponents(isStartup, sendUpdate), initialData);
+ }
+
+ async loadComponentFeeds(sendUpdate, isStartup = false) {
+ const { DiscoveryStream } = this.store.getState();
+
+ if (!DiscoveryStream || !DiscoveryStream.layout) {
+ return;
+ }
+
+ // Reset the flag that indicates whether or not at least one API request
+ // was issued to fetch the component feed in `getComponentFeed()`.
+ this.componentFeedFetched = false;
+ const { newFeedsPromises, newFeeds } = this.buildFeedPromises(
+ DiscoveryStream.layout,
+ isStartup,
+ sendUpdate
+ );
+
+ // Each promise has a catch already built in, so no need to catch here.
+ await Promise.all(newFeedsPromises);
+
+ if (this.componentFeedFetched) {
+ this.cleanUpTopRecImpressionPref(newFeeds);
+ }
+ await this.cache.set("feeds", newFeeds);
+ sendUpdate({
+ type: at.DISCOVERY_STREAM_FEEDS_UPDATE,
+ meta: {
+ isStartup,
+ },
+ });
+ }
+
+ getPlacements() {
+ const { placements } = this.store.getState().DiscoveryStream.spocs;
+ // Backwards comp for before we had placements, assume just a single spocs placement.
+ if (!placements || !placements.length) {
+ return [{ name: "spocs" }];
+ }
+ return placements;
+ }
+
+ // I wonder, can this be better as a reducer?
+ // See Bug https://bugzilla.mozilla.org/show_bug.cgi?id=1606717
+ placementsForEach(callback) {
+ this.getPlacements().forEach(callback);
+ }
+
+ // Bug 1567271 introduced meta data on a list of spocs.
+ // This involved moving the spocs array into an items prop.
+ // However, old data could still be returned, and cached data might also be old.
+ // For ths reason, we want to ensure if we don't find an items array,
+ // we use the previous array placement, and then stub out title and context to empty strings.
+ // We need to do this *after* both fresh fetches and cached data to reduce repetition.
+ normalizeSpocsItems(spocs) {
+ const items = spocs.items || spocs;
+ const title = spocs.title || "";
+ const context = spocs.context || "";
+ const sponsor = spocs.sponsor || "";
+ // We do not stub sponsored_by_override with an empty string. It is an override, and an empty string
+ // explicitly means to override the client to display an empty string.
+ // An empty string is not an no op in this case. Undefined is the proper no op here.
+ const { sponsored_by_override } = spocs;
+ // Undefined is fine here. It's optional and only used by collections.
+ // If we leave it out, you get a collection that cannot be dismissed.
+ const { flight_id } = spocs;
+ return {
+ items,
+ title,
+ context,
+ sponsor,
+ sponsored_by_override,
+ ...(flight_id ? { flight_id } : {}),
+ };
+ }
+
+ // This sets an override pref for personalization version.
+ personalizationVersionOverride(spoc_v2) {
+ const overrideVersion = this.store.getState().Prefs.values[
+ PREF_PERSONALIZATION_OVERRIDE_VERSION
+ ];
+
+ const currentVersion = this.store.getState().Prefs.values[
+ PREF_PERSONALIZATION_VERSION
+ ];
+
+ // If we have a downgrade override, and the current version can be downgraded,
+ // and it hasn't already been downgraded, set it to 1.
+ if (spoc_v2 === false && currentVersion === 2 && overrideVersion !== 1) {
+ this.store.dispatch(ac.SetPref(PREF_PERSONALIZATION_OVERRIDE_VERSION, 1));
+ }
+
+ // This is if we need to revert the downgrade and do cleanup.
+ if (spoc_v2 && overrideVersion === 1) {
+ this.store.dispatch({
+ type: at.CLEAR_PREF,
+ data: { name: PREF_PERSONALIZATION_OVERRIDE_VERSION },
+ });
+ }
+ }
+
+ async loadSpocs(sendUpdate, isStartup) {
+ const cachedData = (await this.cache.get()) || {};
+ let spocsState;
+
+ const { placements } = this.store.getState().DiscoveryStream.spocs;
+
+ if (this.showSpocs) {
+ spocsState = cachedData.spocs;
+ if (this.isExpired({ cachedData, key: "spocs", isStartup })) {
+ const endpoint = this.store.getState().DiscoveryStream.spocs
+ .spocs_endpoint;
+
+ const headers = new Headers();
+ headers.append("content-type", "application/json");
+
+ const apiKeyPref = this._prefCache.config.api_key_pref;
+ const apiKey = Services.prefs.getCharPref(apiKeyPref, "");
+
+ const spocsResponse = await this.fetchFromEndpoint(endpoint, {
+ method: "POST",
+ headers,
+ body: JSON.stringify({
+ pocket_id: this._impressionId,
+ version: 2,
+ consumer_key: apiKey,
+ ...(placements.length ? { placements } : {}),
+ }),
+ });
+
+ if (spocsResponse) {
+ spocsState = {
+ lastUpdated: Date.now(),
+ spocs: {
+ ...spocsResponse,
+ },
+ };
+
+ if (spocsResponse.settings && spocsResponse.settings.feature_flags) {
+ this.personalizationVersionOverride(
+ spocsResponse.settings.feature_flags.spoc_v2
+ );
+ }
+
+ const spocsResultPromises = this.getPlacements().map(
+ async placement => {
+ const freshSpocs = spocsState.spocs[placement.name];
+
+ if (!freshSpocs) {
+ return;
+ }
+
+ // spocs can be returns as an array, or an object with an items array.
+ // We want to normalize this so all our spocs have an items array.
+ // There can also be some meta data for title and context.
+ // This is mostly because of backwards compat.
+ const {
+ items: normalizedSpocsItems,
+ title,
+ context,
+ sponsor,
+ sponsored_by_override,
+ } = this.normalizeSpocsItems(freshSpocs);
+
+ if (!normalizedSpocsItems || !normalizedSpocsItems.length) {
+ // In the case of old data, we still want to ensure we normalize the data structure,
+ // even if it's empty. We expect the empty data to be an object with items array,
+ // and not just an empty array.
+ spocsState.spocs = {
+ ...spocsState.spocs,
+ [placement.name]: {
+ title,
+ context,
+ items: [],
+ },
+ };
+ return;
+ }
+
+ // Migrate flight_id
+ const { data: migratedSpocs } = this.migrateFlightId(
+ normalizedSpocsItems
+ );
+
+ const { data: capResult } = this.frequencyCapSpocs(migratedSpocs);
+
+ const { data: blockedResults } = this.filterBlocked(capResult);
+
+ const { data: scoredResults } = await this.scoreItems(
+ blockedResults,
+ "spocs"
+ );
+
+ spocsState.spocs = {
+ ...spocsState.spocs,
+ [placement.name]: {
+ title,
+ context,
+ sponsor,
+ sponsored_by_override,
+ items: scoredResults,
+ },
+ };
+ }
+ );
+ await Promise.all(spocsResultPromises);
+
+ this.cleanUpFlightImpressionPref(spocsState.spocs);
+ await this.cache.set("spocs", {
+ lastUpdated: spocsState.lastUpdated,
+ spocs: spocsState.spocs,
+ });
+ } else {
+ Cu.reportError("No response for spocs_endpoint prop");
+ }
+ }
+ }
+
+ // Use good data if we have it, otherwise nothing.
+ // We can have no data if spocs set to off.
+ // We can have no data if request fails and there is no good cache.
+ // We want to send an update spocs or not, so client can render something.
+ spocsState =
+ spocsState && spocsState.spocs
+ ? spocsState
+ : {
+ lastUpdated: Date.now(),
+ spocs: {},
+ };
+
+ sendUpdate({
+ type: at.DISCOVERY_STREAM_SPOCS_UPDATE,
+ data: {
+ lastUpdated: spocsState.lastUpdated,
+ spocs: spocsState.spocs,
+ },
+ meta: {
+ isStartup,
+ },
+ });
+ }
+
+ async clearSpocs() {
+ const endpoint = this.store.getState().Prefs.values[
+ PREF_SPOCS_CLEAR_ENDPOINT
+ ];
+ if (!endpoint) {
+ return;
+ }
+ const headers = new Headers();
+ headers.append("content-type", "application/json");
+
+ await this.fetchFromEndpoint(endpoint, {
+ method: "DELETE",
+ headers,
+ body: JSON.stringify({
+ pocket_id: this._impressionId,
+ }),
+ });
+ }
+
+ /*
+ * This just re hydrates the provider from cache.
+ * We can call this on startup because it's generally fast.
+ * It reports to devtools the last time the data in the cache was updated.
+ */
+ async loadAffinityScoresCache(isStartup = false) {
+ const cachedData = (await this.cache.get()) || {};
+ const { affinities } = cachedData;
+ if (this.personalized && affinities && affinities.scores) {
+ this.providerSwitcher.setAffinityProvider(
+ affinities.timeSegments,
+ affinities.parameterSets,
+ affinities.maxHistoryQueryResults,
+ affinities.version,
+ affinities.scores
+ );
+
+ this.domainAffinitiesLastUpdated = affinities._timestamp;
+
+ this.store.dispatch(
+ ac.BroadcastToContent({
+ type: at.DISCOVERY_STREAM_PERSONALIZATION_LAST_UPDATED,
+ data: {
+ lastUpdated: this.domainAffinitiesLastUpdated,
+ },
+ meta: {
+ isStartup,
+ },
+ })
+ );
+ }
+ }
+
+ /*
+ * This creates a new affinityProvider using fresh affinities,
+ * It's run on a last updated timer. This is the opposite of loadAffinityScoresCache.
+ * This is also much slower so we only trigger this in the background on idle-daily.
+ * It causes new profiles to pick up personalization slowly because the first time
+ * a new profile is run you don't have any old cache to use, so it needs to wait for the first
+ * idle-daily. Older profiles can rely on cache during the idle-daily gap. Idle-daily is
+ * usually run once every 24 hours.
+ */
+ async updateDomainAffinityScores() {
+ if (
+ !this.personalized ||
+ !this.affinities ||
+ !this.affinities.parameterSets ||
+ Date.now() - this.domainAffinitiesLastUpdated <
+ MIN_DOMAIN_AFFINITIES_UPDATE_TIME
+ ) {
+ return;
+ }
+
+ this.providerSwitcher.setAffinityProvider(
+ this.affinities.timeSegments,
+ this.affinities.parameterSets,
+ this.affinities.maxHistoryQueryResults,
+ this.affinities.version,
+ undefined
+ );
+
+ await this.providerSwitcher.init();
+
+ const affinities = this.providerSwitcher.getAffinities();
+ this.domainAffinitiesLastUpdated = Date.now();
+
+ this.store.dispatch(
+ ac.BroadcastToContent({
+ type: at.DISCOVERY_STREAM_PERSONALIZATION_LAST_UPDATED,
+ data: {
+ lastUpdated: this.domainAffinitiesLastUpdated,
+ },
+ })
+ );
+ affinities._timestamp = this.domainAffinitiesLastUpdated;
+ this.cache.set("affinities", affinities);
+ }
+
+ observe(subject, topic, data) {
+ switch (topic) {
+ case "idle-daily":
+ this.updateDomainAffinityScores();
+ break;
+ }
+ }
+
+ /*
+ * This function is used to sort any type of story, both spocs and recs.
+ * This uses hierarchical sorting, first sorting by priority, then by score within a priority.
+ * This function could be sorting an array of spocs or an array of recs.
+ * A rec would have priority undefined, and a spoc would probably have a priority set.
+ * Priority is sorted ascending, so low numbers are the highest priority.
+ * Score is sorted descending, so high numbers are the highest score.
+ * Undefined priority values are considered the lowest priority.
+ * A negative priority is considered the same as undefined, lowest priority.
+ * A negative priority is unlikely and not currently supported or expected.
+ * A negative score is a possible use case.
+ */
+ sortItem(a, b) {
+ // If the priorities are the same, sort based on score.
+ // If both item priorities are undefined,
+ // we can safely sort via score.
+ if (a.priority === b.priority) {
+ return b.score - a.score;
+ } else if (!a.priority || a.priority <= 0) {
+ // If priority is undefined or an unexpected value,
+ // consider it lowest priority.
+ return 1;
+ } else if (!b.priority || b.priority <= 0) {
+ // Also consider this case lowest priority.
+ return -1;
+ }
+ // Our primary sort for items with priority.
+ return a.priority - b.priority;
+ }
+
+ async scoreItems(items, type) {
+ const spocsPersonalized = this.store.getState().Prefs.values[
+ PREF_SPOCS_PERSONALIZED
+ ];
+ const recsPersonalized = this.store.getState().Prefs.values[
+ PREF_RECS_PERSONALIZED
+ ];
+ const personalizedByType =
+ type === "feed" ? recsPersonalized : spocsPersonalized;
+
+ const data = (
+ await Promise.all(
+ items.map(item => this.scoreItem(item, personalizedByType))
+ )
+ )
+ // Remove spocs that are scored too low.
+ .filter(s => {
+ if (s.score >= s.min_score) {
+ return true;
+ }
+ return false;
+ })
+ // Sort by highest scores.
+ .sort(this.sortItem);
+
+ return { data };
+ }
+
+ async scoreItem(item, personalizedByType) {
+ item.score = item.item_score;
+ item.min_score = item.min_score || 0;
+ if (item.score !== 0 && !item.score) {
+ item.score = 1;
+ }
+ if (this.personalized && personalizedByType) {
+ await this.providerSwitcher.calculateItemRelevanceScore(item);
+ }
+ return item;
+ }
+
+ filterBlocked(data) {
+ if (data && data.length) {
+ let flights = this.readDataPref(PREF_FLIGHT_BLOCKS);
+ const filteredItems = data.filter(item => {
+ const blocked =
+ NewTabUtils.blockedLinks.isBlocked({ url: item.url }) ||
+ flights[item.flight_id];
+ return !blocked;
+ });
+ return { data: filteredItems };
+ }
+ return { data };
+ }
+
+ // For backwards compatibility, older spoc endpoint don't have flight_id,
+ // but instead had campaign_id we can use
+ //
+ // @param {Object} data An object that might have a SPOCS array.
+ // @returns {Object} An object with a property `data` as the result.
+ migrateFlightId(spocs) {
+ if (spocs && spocs.length) {
+ return {
+ data: spocs.map(s => {
+ return {
+ ...s,
+ ...(s.flight_id || s.campaign_id
+ ? {
+ flight_id: s.flight_id || s.campaign_id,
+ }
+ : {}),
+ ...(s.caps
+ ? {
+ caps: {
+ ...s.caps,
+ flight: s.caps.flight || s.caps.campaign,
+ },
+ }
+ : {}),
+ };
+ }),
+ };
+ }
+ return { data: spocs };
+ }
+
+ // Filter spocs based on frequency caps
+ //
+ // @param {Object} data An object that might have a SPOCS array.
+ // @returns {Object} An object with a property `data` as the result, and a property
+ // `filterItems` as the frequency capped items.
+ frequencyCapSpocs(spocs) {
+ if (spocs && spocs.length) {
+ const impressions = this.readDataPref(PREF_SPOC_IMPRESSIONS);
+ const caps = [];
+ const result = spocs.filter(s => {
+ const isBelow = this.isBelowFrequencyCap(impressions, s);
+ if (!isBelow) {
+ caps.push(s);
+ }
+ return isBelow;
+ });
+ // send caps to redux if any.
+ if (caps.length) {
+ this.store.dispatch({
+ type: at.DISCOVERY_STREAM_SPOCS_CAPS,
+ data: caps,
+ });
+ }
+ return { data: result, filtered: caps };
+ }
+ return { data: spocs, filtered: [] };
+ }
+
+ // Frequency caps are based on flight, which may include multiple spocs.
+ // We currently support two types of frequency caps:
+ // - lifetime: Indicates how many times spocs from a flight can be shown in total
+ // - period: Indicates how many times spocs from a flight can be shown within a period
+ //
+ // So, for example, the feed configuration below defines that for flight 1 no more
+ // than 5 spocs can be shown in total, and no more than 2 per hour.
+ // "flight_id": 1,
+ // "caps": {
+ // "lifetime": 5,
+ // "flight": {
+ // "count": 2,
+ // "period": 3600
+ // }
+ // }
+ isBelowFrequencyCap(impressions, spoc) {
+ const flightImpressions = impressions[spoc.flight_id];
+ if (!flightImpressions) {
+ return true;
+ }
+
+ const lifetime = spoc.caps && spoc.caps.lifetime;
+
+ const lifeTimeCap = Math.min(
+ lifetime || MAX_LIFETIME_CAP,
+ MAX_LIFETIME_CAP
+ );
+ const lifeTimeCapExceeded = flightImpressions.length >= lifeTimeCap;
+ if (lifeTimeCapExceeded) {
+ return false;
+ }
+
+ const flightCap = spoc.caps && spoc.caps.flight;
+ if (flightCap) {
+ const flightCapExceeded =
+ flightImpressions.filter(i => Date.now() - i < flightCap.period * 1000)
+ .length >= flightCap.count;
+ return !flightCapExceeded;
+ }
+ return true;
+ }
+
+ async retryFeed(feed) {
+ const { url } = feed;
+ const result = await this.getComponentFeed(url);
+ const newFeed = this.filterRecommendations(result);
+ this.store.dispatch(
+ ac.BroadcastToContent({
+ type: at.DISCOVERY_STREAM_FEED_UPDATE,
+ data: {
+ feed: newFeed,
+ url,
+ },
+ })
+ );
+ }
+
+ async getComponentFeed(feedUrl, isStartup) {
+ const cachedData = (await this.cache.get()) || {};
+ const { feeds } = cachedData;
+
+ let feed = feeds ? feeds[feedUrl] : null;
+ if (this.isExpired({ cachedData, key: "feed", url: feedUrl, isStartup })) {
+ const feedResponse = await this.fetchFromEndpoint(feedUrl);
+ if (feedResponse) {
+ const { data: scoredItems } = await this.scoreItems(
+ feedResponse.recommendations,
+ "feed"
+ );
+ const { recsExpireTime } = feedResponse.settings;
+ const recommendations = this.rotate(scoredItems, recsExpireTime);
+ this.componentFeedFetched = true;
+ feed = {
+ lastUpdated: Date.now(),
+ data: {
+ settings: feedResponse.settings,
+ recommendations,
+ status: "success",
+ },
+ };
+ } else {
+ Cu.reportError("No response for feed");
+ }
+ }
+
+ // If we have no feed at this point, both fetch and cache failed for some reason.
+ return (
+ feed || {
+ data: {
+ status: "failed",
+ },
+ }
+ );
+ }
+
+ /**
+ * Called at startup to update cached data in the background.
+ */
+ async _maybeUpdateCachedData() {
+ const expirationPerComponent = await this._checkExpirationPerComponent();
+ // Pass in `store.dispatch` to send the updates only to main
+ if (expirationPerComponent.layout) {
+ await this.loadLayout(this.store.dispatch);
+ }
+ if (expirationPerComponent.spocs) {
+ await this.loadSpocs(this.store.dispatch);
+ }
+ if (expirationPerComponent.feeds) {
+ await this.loadComponentFeeds(this.store.dispatch);
+ }
+ }
+
+ /**
+ * @typedef {Object} RefreshAll
+ * @property {boolean} updateOpenTabs - Sends updates to open tabs immediately if true,
+ * updates in background if false
+ * @property {boolean} isStartup - When the function is called at browser startup
+ *
+ * Refreshes layout, component feeds, and spocs in order if caches have expired.
+ * @param {RefreshAll} options
+ */
+ async refreshAll(options = {}) {
+ const affinityCacheLoadPromise = this.loadAffinityScoresCache(
+ options.isStartup
+ );
+
+ const spocsPersonalized = this.store.getState().Prefs.values[
+ PREF_SPOCS_PERSONALIZED
+ ];
+ const recsPersonalized = this.store.getState().Prefs.values[
+ PREF_RECS_PERSONALIZED
+ ];
+
+ let expirationPerComponent = {};
+ if (this.personalized) {
+ // We store this before we refresh content.
+ // This way, we can know what and if something got updated,
+ // so we can know to score the results.
+ expirationPerComponent = await this._checkExpirationPerComponent();
+ }
+ await this.refreshContent(options);
+
+ if (this.personalized) {
+ // affinityCacheLoadPromise is probably done, because of the refreshContent await above,
+ // but to be sure, we should check that it's done, without making the parent function wait.
+ affinityCacheLoadPromise.then(() => {
+ // If we don't have expired stories or feeds, we don't need to score after init.
+ // If we do have expired stories, we want to score after init.
+ // In both cases, we don't want these to block the parent function.
+ // This is why we store the promise, and call then to do our scoring work.
+ const initPromise = this.providerSwitcher.init();
+ initPromise.then(() => {
+ // Both scoreFeeds and scoreSpocs are promises,
+ // but they don't need to wait for each other.
+ // We can just fire them and forget at this point.
+ const { feeds, spocs } = this.store.getState().DiscoveryStream;
+ if (
+ recsPersonalized &&
+ feeds.loaded &&
+ expirationPerComponent.feeds
+ ) {
+ this.scoreFeeds(feeds);
+ }
+ if (
+ spocsPersonalized &&
+ spocs.loaded &&
+ expirationPerComponent.spocs
+ ) {
+ this.scoreSpocs(spocs);
+ }
+ });
+ });
+ }
+ }
+
+ async scoreFeeds(feedsState) {
+ if (feedsState.data) {
+ const feeds = {};
+ const feedsPromises = Object.keys(feedsState.data).map(url => {
+ let feed = feedsState.data[url];
+ const feedPromise = this.scoreItems(feed.data.recommendations, "feed");
+ feedPromise.then(({ data: scoredItems }) => {
+ const { recsExpireTime } = feed.data.settings;
+ const recommendations = this.rotate(scoredItems, recsExpireTime);
+ feed = {
+ ...feed,
+ data: {
+ ...feed.data,
+ recommendations,
+ },
+ };
+
+ feeds[url] = feed;
+
+ this.store.dispatch(
+ ac.AlsoToPreloaded({
+ type: at.DISCOVERY_STREAM_FEED_UPDATE,
+ data: {
+ feed,
+ url,
+ },
+ })
+ );
+ });
+ return feedPromise;
+ });
+ await Promise.all(feedsPromises);
+ await this.cache.set("feeds", feeds);
+ }
+ }
+
+ async scoreSpocs(spocsState) {
+ const spocsResultPromises = this.getPlacements().map(async placement => {
+ const nextSpocs = spocsState.data[placement.name] || {};
+ const { items } = nextSpocs;
+
+ if (!items || !items.length) {
+ return;
+ }
+
+ const { data: scoreResult } = await this.scoreItems(items, "spocs");
+
+ spocsState.data = {
+ ...spocsState.data,
+ [placement.name]: {
+ ...nextSpocs,
+ items: scoreResult,
+ },
+ };
+ });
+ await Promise.all(spocsResultPromises);
+
+ // Update cache here so we don't need to re calculate scores on loads from cache.
+ // Related Bug 1606276
+ await this.cache.set("spocs", {
+ lastUpdated: spocsState.lastUpdated,
+ spocs: spocsState.data,
+ });
+ this.store.dispatch(
+ ac.AlsoToPreloaded({
+ type: at.DISCOVERY_STREAM_SPOCS_UPDATE,
+ data: {
+ lastUpdated: spocsState.lastUpdated,
+ spocs: spocsState.data,
+ },
+ })
+ );
+ }
+
+ async refreshContent(options = {}) {
+ const { updateOpenTabs, isStartup } = options;
+
+ const dispatch = updateOpenTabs
+ ? action => this.store.dispatch(ac.BroadcastToContent(action))
+ : this.store.dispatch;
+
+ await this.loadLayout(dispatch, isStartup);
+ if (this.showStories) {
+ await Promise.all([
+ this.loadSpocs(dispatch, isStartup).catch(error =>
+ Cu.reportError(`Error trying to load spocs feeds: ${error}`)
+ ),
+ this.loadComponentFeeds(dispatch, isStartup).catch(error =>
+ Cu.reportError(`Error trying to load component feeds: ${error}`)
+ ),
+ ]);
+ if (isStartup) {
+ await this._maybeUpdateCachedData();
+ }
+ }
+ }
+
+ // We have to rotate stories on the client so that
+ // active stories are at the front of the list, followed by stories that have expired
+ // impressions i.e. have been displayed for longer than recsExpireTime.
+ rotate(recommendations, recsExpireTime) {
+ const maxImpressionAge = Math.max(
+ recsExpireTime * 1000 || DEFAULT_RECS_EXPIRE_TIME,
+ DEFAULT_RECS_EXPIRE_TIME
+ );
+ const impressions = this.readDataPref(PREF_REC_IMPRESSIONS);
+ const expired = [];
+ const active = [];
+ for (const item of recommendations) {
+ if (
+ impressions[item.id] &&
+ Date.now() - impressions[item.id] >= maxImpressionAge
+ ) {
+ expired.push(item);
+ } else {
+ active.push(item);
+ }
+ }
+ return active.concat(expired);
+ }
+
+ enableStories() {
+ if (this.config.enabled && this.loaded) {
+ // If stories are being re enabled, ensure we have stories.
+ this.refreshAll({ updateOpenTabs: true });
+ }
+ }
+
+ async enable() {
+ await this.refreshAll({ updateOpenTabs: true, isStartup: true });
+ Services.obs.addObserver(this, "idle-daily");
+ this.loaded = true;
+ }
+
+ async reset() {
+ this.resetDataPrefs();
+ await this.resetCache();
+ if (this.loaded) {
+ Services.obs.removeObserver(this, "idle-daily");
+ }
+ this.resetState();
+ }
+
+ async resetCache() {
+ await this.resetAllCache();
+ }
+
+ async resetContentCache() {
+ await this.cache.set("layout", {});
+ await this.cache.set("feeds", {});
+ await this.cache.set("spocs", {});
+ }
+
+ async resetAllCache() {
+ await this.resetContentCache();
+ await this.cache.set("affinities", {});
+ }
+
+ resetDataPrefs() {
+ this.writeDataPref(PREF_SPOC_IMPRESSIONS, {});
+ this.writeDataPref(PREF_REC_IMPRESSIONS, {});
+ this.writeDataPref(PREF_FLIGHT_BLOCKS, {});
+ }
+
+ resetState() {
+ // Reset reducer
+ this.store.dispatch(
+ ac.BroadcastToContent({ type: at.DISCOVERY_STREAM_LAYOUT_RESET })
+ );
+ this.store.dispatch(
+ ac.BroadcastToContent({
+ type: at.DISCOVERY_STREAM_COLLECTION_DISMISSIBLE_TOGGLE,
+ data: {
+ value: this.store.getState().Prefs.values[
+ PREF_COLLECTION_DISMISSIBLE
+ ],
+ },
+ })
+ );
+ this.domainAffinitiesLastUpdated = null;
+ this.loaded = false;
+ }
+
+ async onPrefChange() {
+ // We always want to clear the cache/state if the pref has changed
+ await this.reset();
+ if (this.config.enabled) {
+ // Load data from all endpoints
+ await this.enable();
+ }
+ }
+
+ // This is a request to change the config from somewhere.
+ // Can be from a spefic pref related to Discovery Stream,
+ // or can be a generic request from an external feed that
+ // something changed.
+ configReset() {
+ this._prefCache.config = null;
+ this.store.dispatch(
+ ac.BroadcastToContent({
+ type: at.DISCOVERY_STREAM_CONFIG_CHANGE,
+ data: this.config,
+ })
+ );
+ }
+
+ recordFlightImpression(flightId) {
+ let impressions = this.readDataPref(PREF_SPOC_IMPRESSIONS);
+
+ const timeStamps = impressions[flightId] || [];
+ timeStamps.push(Date.now());
+ impressions = { ...impressions, [flightId]: timeStamps };
+
+ this.writeDataPref(PREF_SPOC_IMPRESSIONS, impressions);
+ }
+
+ recordTopRecImpressions(recId) {
+ let impressions = this.readDataPref(PREF_REC_IMPRESSIONS);
+ if (!impressions[recId]) {
+ impressions = { ...impressions, [recId]: Date.now() };
+ this.writeDataPref(PREF_REC_IMPRESSIONS, impressions);
+ }
+ }
+
+ recordBlockFlightId(flightId) {
+ const flights = this.readDataPref(PREF_FLIGHT_BLOCKS);
+ if (!flights[flightId]) {
+ flights[flightId] = 1;
+ this.writeDataPref(PREF_FLIGHT_BLOCKS, flights);
+ }
+ }
+
+ cleanUpFlightImpressionPref(data) {
+ let flightIds = [];
+ this.placementsForEach(placement => {
+ const newSpocs = data[placement.name];
+ if (!newSpocs) {
+ return;
+ }
+
+ const items = newSpocs.items || [];
+ flightIds = [...flightIds, ...items.map(s => `${s.flight_id}`)];
+ });
+ if (flightIds && flightIds.length) {
+ this.cleanUpImpressionPref(
+ id => !flightIds.includes(id),
+ PREF_SPOC_IMPRESSIONS
+ );
+ }
+ }
+
+ // Clean up rec impression pref by removing all stories that are no
+ // longer part of the response.
+ cleanUpTopRecImpressionPref(newFeeds) {
+ // Need to build a single list of stories.
+ const activeStories = Object.keys(newFeeds)
+ .filter(currentValue => newFeeds[currentValue].data)
+ .reduce((accumulator, currentValue) => {
+ const { recommendations } = newFeeds[currentValue].data;
+ return accumulator.concat(recommendations.map(i => `${i.id}`));
+ }, []);
+ this.cleanUpImpressionPref(
+ id => !activeStories.includes(id),
+ PREF_REC_IMPRESSIONS
+ );
+ }
+
+ writeDataPref(pref, impressions) {
+ this.store.dispatch(ac.SetPref(pref, JSON.stringify(impressions)));
+ }
+
+ readDataPref(pref) {
+ const prefVal = this.store.getState().Prefs.values[pref];
+ return prefVal ? JSON.parse(prefVal) : {};
+ }
+
+ cleanUpImpressionPref(isExpired, pref) {
+ const impressions = this.readDataPref(pref);
+ let changed = false;
+
+ Object.keys(impressions).forEach(id => {
+ if (isExpired(id)) {
+ changed = true;
+ delete impressions[id];
+ }
+ });
+
+ if (changed) {
+ this.writeDataPref(pref, impressions);
+ }
+ }
+
+ async onPrefChangedAction(action) {
+ switch (action.data.name) {
+ case PREF_CONFIG:
+ case PREF_ENABLED:
+ case PREF_HARDCODED_BASIC_LAYOUT:
+ case PREF_SPOCS_ENDPOINT:
+ case PREF_SPOCS_ENDPOINT_QUERY:
+ // This is a config reset directly related to Discovery Stream pref.
+ this.configReset();
+ break;
+ case PREF_USER_TOPSTORIES:
+ case PREF_SYSTEM_TOPSTORIES:
+ if (!action.data.value) {
+ // Ensure we delete any remote data potentially related to spocs.
+ this.clearSpocs();
+ } else {
+ this.enableStories();
+ }
+ break;
+ // Check if spocs was disabled. Remove them if they were.
+ case PREF_SHOW_SPONSORED:
+ if (!action.data.value) {
+ // Ensure we delete any remote data potentially related to spocs.
+ this.clearSpocs();
+ }
+ await this.loadSpocs(update =>
+ this.store.dispatch(ac.BroadcastToContent(update))
+ );
+ break;
+ }
+ }
+
+ async onAction(action) {
+ switch (action.type) {
+ case at.INIT:
+ // During the initialization of Firefox:
+ // 1. Set-up listeners and initialize the redux state for config;
+ this.setupPrefs(true /* isStartup */);
+ // 2. If config.enabled is true, start loading data.
+ if (this.config.enabled) {
+ await this.enable();
+ }
+ break;
+ case at.DISCOVERY_STREAM_DEV_SYSTEM_TICK:
+ case at.SYSTEM_TICK:
+ // Only refresh if we loaded once in .enable()
+ if (
+ this.config.enabled &&
+ this.loaded &&
+ (await this.checkIfAnyCacheExpired())
+ ) {
+ await this.refreshAll({ updateOpenTabs: false });
+ }
+ break;
+ case at.DISCOVERY_STREAM_DEV_IDLE_DAILY:
+ Services.obs.notifyObservers(null, "idle-daily");
+ break;
+ case at.DISCOVERY_STREAM_DEV_SYNC_RS:
+ RemoteSettings.pollChanges();
+ break;
+ case at.DISCOVERY_STREAM_DEV_EXPIRE_CACHE:
+ // Affinities update at a slower interval than content, so in order to debug,
+ // we want to be able to expire just content to trigger the earlier expire times.
+ await this.resetContentCache();
+ break;
+ case at.DISCOVERY_STREAM_CONFIG_SET_VALUE:
+ // Use the original string pref to then set a value instead of
+ // this.config which has some modifications
+ this.store.dispatch(
+ ac.SetPref(
+ PREF_CONFIG,
+ JSON.stringify({
+ ...JSON.parse(this.store.getState().Prefs.values[PREF_CONFIG]),
+ [action.data.name]: action.data.value,
+ })
+ )
+ );
+ break;
+
+ case at.DISCOVERY_STREAM_CONFIG_RESET:
+ // This is a generic config reset likely related to an external feed pref.
+ this.configReset();
+ break;
+ case at.DISCOVERY_STREAM_CONFIG_RESET_DEFAULTS:
+ this.resetConfigDefauts();
+ break;
+ case at.DISCOVERY_STREAM_RETRY_FEED:
+ this.retryFeed(action.data.feed);
+ break;
+ case at.DISCOVERY_STREAM_CONFIG_CHANGE:
+ // When the config pref changes, load or unload data as needed.
+ await this.onPrefChange();
+ break;
+ case at.DISCOVERY_STREAM_IMPRESSION_STATS:
+ if (
+ action.data.tiles &&
+ action.data.tiles[0] &&
+ action.data.tiles[0].id
+ ) {
+ this.recordTopRecImpressions(action.data.tiles[0].id);
+ }
+ break;
+ case at.DISCOVERY_STREAM_SPOC_IMPRESSION:
+ if (this.showSpocs) {
+ this.recordFlightImpression(action.data.flightId);
+
+ // Apply frequency capping to SPOCs in the redux store, only update the
+ // store if the SPOCs are changed.
+ const spocsState = this.store.getState().DiscoveryStream.spocs;
+
+ let frequencyCapped = [];
+ this.placementsForEach(placement => {
+ const spocs = spocsState.data[placement.name];
+ if (!spocs || !spocs.items) {
+ return;
+ }
+
+ const { data: capResult, filtered } = this.frequencyCapSpocs(
+ spocs.items
+ );
+ frequencyCapped = [...frequencyCapped, ...filtered];
+
+ spocsState.data = {
+ ...spocsState.data,
+ [placement.name]: {
+ ...spocs,
+ items: capResult,
+ },
+ };
+ });
+
+ if (frequencyCapped.length) {
+ // Update cache here so we don't need to re calculate frequency caps on loads from cache.
+ await this.cache.set("spocs", {
+ lastUpdated: spocsState.lastUpdated,
+ spocs: spocsState.data,
+ });
+
+ this.store.dispatch(
+ ac.AlsoToPreloaded({
+ type: at.DISCOVERY_STREAM_SPOCS_UPDATE,
+ data: {
+ lastUpdated: spocsState.lastUpdated,
+ spocs: spocsState.data,
+ },
+ })
+ );
+ }
+ }
+ break;
+ // This is fired from the browser, it has no concept of spocs, flight or pocket.
+ // We match the blocked url with our available spoc urls to see if there is a match.
+ // I suspect we *could* instead do this in BLOCK_URL but I'm not sure.
+ case at.PLACES_LINK_BLOCKED:
+ if (this.showSpocs) {
+ let blockedItems = [];
+ const spocsState = this.store.getState().DiscoveryStream.spocs;
+
+ this.placementsForEach(placement => {
+ const spocs = spocsState.data[placement.name];
+ if (spocs && spocs.items && spocs.items.length) {
+ const blockedResults = [];
+ const blocks = spocs.items.filter(s => {
+ const blocked = s.url === action.data.url;
+ if (!blocked) {
+ blockedResults.push(s);
+ }
+ return blocked;
+ });
+
+ blockedItems = [...blockedItems, ...blocks];
+
+ spocsState.data = {
+ ...spocsState.data,
+ [placement.name]: {
+ ...spocs,
+ items: blockedResults,
+ },
+ };
+ }
+ });
+
+ if (blockedItems.length) {
+ // Update cache here so we don't need to re calculate blocks on loads from cache.
+ await this.cache.set("spocs", {
+ lastUpdated: spocsState.lastUpdated,
+ spocs: spocsState.data,
+ });
+
+ // If we're blocking a spoc, we want open tabs to have
+ // a slightly different treatment from future tabs.
+ // AlsoToPreloaded updates the source data and preloaded tabs with a new spoc.
+ // BroadcastToContent updates open tabs with a non spoc instead of a new spoc.
+ this.store.dispatch(
+ ac.AlsoToPreloaded({
+ type: at.DISCOVERY_STREAM_LINK_BLOCKED,
+ data: action.data,
+ })
+ );
+ this.store.dispatch(
+ ac.BroadcastToContent({
+ type: at.DISCOVERY_STREAM_SPOC_BLOCKED,
+ data: action.data,
+ })
+ );
+ break;
+ }
+ }
+
+ this.store.dispatch(
+ ac.BroadcastToContent({
+ type: at.DISCOVERY_STREAM_LINK_BLOCKED,
+ data: action.data,
+ })
+ );
+ break;
+ case at.UNINIT:
+ // When this feed is shutting down:
+ this.uninitPrefs();
+ this._providerSwitcher = null;
+ break;
+ case at.BLOCK_URL: {
+ // If we block a story that also has a flight_id
+ // we want to record that as blocked too.
+ // This is because a single flight might have slightly different urls.
+ action.data.forEach(site => {
+ const { flight_id } = site;
+ if (flight_id) {
+ this.recordBlockFlightId(flight_id);
+ }
+ });
+ break;
+ }
+ case at.PREF_CHANGED:
+ await this.onPrefChangedAction(action);
+ break;
+ }
+ }
+};
+
+// This function generates a hardcoded layout each call.
+// This is because modifying the original object would
+// persist across pref changes and system_tick updates.
+//
+// NOTE: There is some branching logic in the template based on `isBasicLayout`
+//
+getHardcodedLayout = isBasicLayout => ({
+ lastUpdate: Date.now(),
+ spocs: {
+ url: "https://spocs.getpocket.com/spocs",
+ },
+ layout: [
+ {
+ width: 12,
+ components: [
+ {
+ type: "TopSites",
+ header: {
+ title: {
+ id: "newtab-section-header-topsites",
+ },
+ },
+ properties: {},
+ },
+ {
+ type: "CollectionCardGrid",
+ properties: {
+ items: 3,
+ },
+ header: {
+ title: "",
+ },
+ placement: {
+ name: "sponsored-collection",
+ ad_types: [3617],
+ zone_ids: [217759, 218031],
+ },
+ spocs: {
+ probability: 1,
+ positions: [
+ {
+ index: 0,
+ },
+ {
+ index: 1,
+ },
+ {
+ index: 2,
+ },
+ ],
+ },
+ },
+ {
+ type: "Message",
+ header: {
+ title: {
+ id: "newtab-section-header-pocket",
+ values: { provider: "Pocket" },
+ },
+ subtitle: "",
+ link_text: {
+ id: "newtab-pocket-learn-more",
+ },
+ link_url: "https://getpocket.com/firefox/new_tab_learn_more",
+ icon:
+ "chrome://activity-stream/content/data/content/assets/glyph-pocket-16.svg",
+ },
+ properties: {},
+ styles: {
+ ".ds-message": "margin-bottom: -20px",
+ },
+ },
+ {
+ type: "CardGrid",
+ properties: {
+ items: isBasicLayout ? 3 : 21,
+ },
+ cta_variant: "link",
+ header: {
+ title: "",
+ },
+ placement: {
+ name: "spocs",
+ ad_types: [3617],
+ zone_ids: [217758, 217995],
+ },
+ feed: {
+ embed_reference: null,
+ url:
+ "https://getpocket.cdn.mozilla.net/v3/firefox/global-recs?version=3&consumer_key=$apiKey&locale_lang=$locale&region=$region&count=30",
+ },
+ spocs: {
+ probability: 1,
+ positions: [
+ {
+ index: 2,
+ },
+ {
+ index: 4,
+ },
+ {
+ index: 11,
+ },
+ {
+ index: 20,
+ },
+ ],
+ },
+ },
+ {
+ type: "Navigation",
+ properties: {
+ alignment: "left-align",
+ links: [
+ {
+ name: "Self Improvement",
+ url:
+ "https://getpocket.com/explore/self-improvement?utm_source=pocket-newtab",
+ },
+ {
+ name: "Food",
+ url:
+ "https://getpocket.com/explore/food?utm_source=pocket-newtab",
+ },
+ {
+ name: "Entertainment",
+ url:
+ "https://getpocket.com/explore/entertainment?utm_source=pocket-newtab",
+ },
+ {
+ name: "Health",
+ url:
+ "https://getpocket.com/explore/health?utm_source=pocket-newtab",
+ },
+ {
+ name: "Science",
+ url:
+ "https://getpocket.com/explore/science?utm_source=pocket-newtab",
+ },
+ {
+ name: "More Recommendations ›",
+ url: "https://getpocket.com/explore?utm_source=pocket-newtab",
+ },
+ ],
+ },
+ header: {
+ title: {
+ id: "newtab-pocket-read-more",
+ },
+ },
+ styles: {
+ ".ds-navigation": "margin-top: -10px;",
+ },
+ },
+ ],
+ },
+ ],
+});
+
+const EXPORTED_SYMBOLS = ["DiscoveryStreamFeed"];
diff --git a/browser/components/newtab/lib/DownloadsManager.jsm b/browser/components/newtab/lib/DownloadsManager.jsm
new file mode 100644
index 0000000000..ecec29ace2
--- /dev/null
+++ b/browser/components/newtab/lib/DownloadsManager.jsm
@@ -0,0 +1,194 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+const { XPCOMUtils } = ChromeUtils.import(
+ "resource://gre/modules/XPCOMUtils.jsm"
+);
+XPCOMUtils.defineLazyGlobalGetters(this, ["URL"]);
+
+const { actionTypes: at } = ChromeUtils.import(
+ "resource://activity-stream/common/Actions.jsm"
+);
+
+XPCOMUtils.defineLazyModuleGetters(this, {
+ DownloadsCommon: "resource:///modules/DownloadsCommon.jsm",
+ DownloadsViewUI: "resource:///modules/DownloadsViewUI.jsm",
+ FileUtils: "resource://gre/modules/FileUtils.jsm",
+ NewTabUtils: "resource://gre/modules/NewTabUtils.jsm",
+});
+
+const DOWNLOAD_CHANGED_DELAY_TIME = 1000; // time in ms to delay timer for downloads changed events
+
+this.DownloadsManager = class DownloadsManager {
+ constructor(store) {
+ this._downloadData = null;
+ this._store = null;
+ this._downloadItems = new Map();
+ this._downloadTimer = null;
+ }
+
+ setTimeout(callback, delay) {
+ let timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
+ timer.initWithCallback(callback, delay, Ci.nsITimer.TYPE_ONE_SHOT);
+ return timer;
+ }
+
+ formatDownload(download) {
+ let referrer = download.source.referrerInfo?.originalReferrer?.spec || null;
+ return {
+ hostname: new URL(download.source.url).hostname,
+ url: download.source.url,
+ path: download.target.path,
+ title: DownloadsViewUI.getDisplayName(download),
+ description:
+ DownloadsViewUI.getSizeWithUnits(download) ||
+ DownloadsCommon.strings.sizeUnknown,
+ referrer,
+ date_added: download.endTime,
+ };
+ }
+
+ init(store) {
+ this._store = store;
+ this._downloadData = DownloadsCommon.getData(
+ null /* null for non-private downloads */,
+ true,
+ false,
+ true
+ );
+ this._downloadData.addView(this);
+ }
+
+ onDownloadAdded(download) {
+ if (!this._downloadItems.has(download.source.url)) {
+ this._downloadItems.set(download.source.url, download);
+
+ // On startup, all existing downloads fire this notification, so debounce them
+ if (this._downloadTimer) {
+ this._downloadTimer.delay = DOWNLOAD_CHANGED_DELAY_TIME;
+ } else {
+ this._downloadTimer = this.setTimeout(() => {
+ this._downloadTimer = null;
+ this._store.dispatch({ type: at.DOWNLOAD_CHANGED });
+ }, DOWNLOAD_CHANGED_DELAY_TIME);
+ }
+ }
+ }
+
+ onDownloadRemoved(download) {
+ if (this._downloadItems.has(download.source.url)) {
+ this._downloadItems.delete(download.source.url);
+ this._store.dispatch({ type: at.DOWNLOAD_CHANGED });
+ }
+ }
+
+ async getDownloads(
+ threshold,
+ {
+ numItems = this._downloadItems.size,
+ onlySucceeded = false,
+ onlyExists = false,
+ }
+ ) {
+ if (!threshold) {
+ return [];
+ }
+ let results = [];
+
+ // Only get downloads within the time threshold specified and sort by recency
+ const downloadThreshold = Date.now() - threshold;
+ let downloads = [...this._downloadItems.values()]
+ .filter(download => download.endTime > downloadThreshold)
+ .sort((download1, download2) => download1.endTime < download2.endTime);
+
+ for (const download of downloads) {
+ // Ignore blocked links, but allow long (data:) uris to avoid high CPU
+ if (
+ download.source.url.length < 10000 &&
+ NewTabUtils.blockedLinks.isBlocked(download.source)
+ ) {
+ continue;
+ }
+
+ // Only include downloads where the file still exists
+ if (onlyExists) {
+ // Refresh download to ensure the 'exists' attribute is up to date
+ await download.refresh();
+ if (!download.target.exists) {
+ continue;
+ }
+ }
+ // Only include downloads that were completed successfully
+ if (onlySucceeded) {
+ if (!download.succeeded) {
+ continue;
+ }
+ }
+ const formattedDownloadForHighlights = this.formatDownload(download);
+ results.push(formattedDownloadForHighlights);
+ if (results.length === numItems) {
+ break;
+ }
+ }
+ return results;
+ }
+
+ uninit() {
+ if (this._downloadData) {
+ this._downloadData.removeView(this);
+ this._downloadData = null;
+ }
+ if (this._downloadTimer) {
+ this._downloadTimer.cancel();
+ this._downloadTimer = null;
+ }
+ }
+
+ onAction(action) {
+ let doDownloadAction = callback => {
+ let download = this._downloadItems.get(action.data.url);
+ if (download) {
+ callback(download);
+ }
+ };
+
+ switch (action.type) {
+ case at.COPY_DOWNLOAD_LINK:
+ doDownloadAction(download => {
+ DownloadsCommon.copyDownloadLink(download);
+ });
+ break;
+ case at.REMOVE_DOWNLOAD_FILE:
+ doDownloadAction(download => {
+ DownloadsCommon.deleteDownload(download).catch(Cu.reportError);
+ });
+ break;
+ case at.SHOW_DOWNLOAD_FILE:
+ doDownloadAction(download => {
+ DownloadsCommon.showDownloadedFile(
+ new FileUtils.File(download.target.path)
+ );
+ });
+ break;
+ case at.OPEN_DOWNLOAD_FILE:
+ const win = action._target.browser.ownerGlobal;
+ const openWhere =
+ action.data.event && win.whereToOpenLink(action.data.event);
+ doDownloadAction(download => {
+ DownloadsCommon.openDownload(download, {
+ // Replace "current" or unknown value with "tab" as the default behavior
+ // for opening downloads when handled internally
+ openWhere: ["window", "tab", "tabshifted"].includes(openWhere)
+ ? openWhere
+ : "tab",
+ });
+ });
+ break;
+ case at.UNINIT:
+ this.uninit();
+ break;
+ }
+ }
+};
+this.EXPORTED_SYMBOLS = ["DownloadsManager"];
diff --git a/browser/components/newtab/lib/FaviconFeed.jsm b/browser/components/newtab/lib/FaviconFeed.jsm
new file mode 100644
index 0000000000..6114cf889a
--- /dev/null
+++ b/browser/components/newtab/lib/FaviconFeed.jsm
@@ -0,0 +1,213 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
+const { actionTypes: at } = ChromeUtils.import(
+ "resource://activity-stream/common/Actions.jsm"
+);
+const { getDomain } = ChromeUtils.import(
+ "resource://activity-stream/lib/TippyTopProvider.jsm"
+);
+const { RemoteSettings } = ChromeUtils.import(
+ "resource://services-settings/remote-settings.js"
+);
+
+ChromeUtils.defineModuleGetter(
+ this,
+ "PlacesUtils",
+ "resource://gre/modules/PlacesUtils.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "Services",
+ "resource://gre/modules/Services.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "NewTabUtils",
+ "resource://gre/modules/NewTabUtils.jsm"
+);
+
+const MIN_FAVICON_SIZE = 96;
+
+/**
+ * Get favicon info (uri and size) for a uri from Places.
+ *
+ * @param uri {nsIURI} Page to check for favicon data
+ * @returns A promise of an object (possibly null) containing the data
+ */
+function getFaviconInfo(uri) {
+ // Use 0 to get the biggest width available
+ const preferredWidth = 0;
+ return new Promise(resolve =>
+ PlacesUtils.favicons.getFaviconDataForPage(
+ uri,
+ // Package up the icon data in an object if we have it; otherwise null
+ (iconUri, faviconLength, favicon, mimeType, faviconSize) =>
+ resolve(iconUri ? { iconUri, faviconSize } : null),
+ preferredWidth
+ )
+ );
+}
+
+/**
+ * Fetches visit paths for a given URL from its most recent visit in Places.
+ *
+ * Note that this includes the URL itself as well as all the following
+ * permenent&temporary redirected URLs if any.
+ *
+ * @param {String} a URL string
+ *
+ * @returns {Array} Returns an array containing objects as
+ * {int} visit_id: ID of the visit in moz_historyvisits.
+ * {String} url: URL of the redirected URL.
+ */
+async function fetchVisitPaths(url) {
+ const query = `
+ WITH RECURSIVE path(visit_id)
+ AS (
+ SELECT v.id
+ FROM moz_places h
+ JOIN moz_historyvisits v
+ ON v.place_id = h.id
+ WHERE h.url_hash = hash(:url) AND h.url = :url
+ AND v.visit_date = h.last_visit_date
+
+ UNION
+
+ SELECT id
+ FROM moz_historyvisits
+ JOIN path
+ ON visit_id = from_visit
+ WHERE visit_type IN
+ (${PlacesUtils.history.TRANSITIONS.REDIRECT_PERMANENT},
+ ${PlacesUtils.history.TRANSITIONS.REDIRECT_TEMPORARY})
+ )
+ SELECT visit_id, (
+ SELECT (
+ SELECT url
+ FROM moz_places
+ WHERE id = place_id)
+ FROM moz_historyvisits
+ WHERE id = visit_id) AS url
+ FROM path
+ `;
+
+ const visits = await NewTabUtils.activityStreamProvider.executePlacesQuery(
+ query,
+ {
+ columns: ["visit_id", "url"],
+ params: { url },
+ }
+ );
+ return visits;
+}
+
+/**
+ * Fetch favicon for a url by following its redirects in Places.
+ *
+ * This can improve the rich icon coverage for Top Sites since Places only
+ * associates the favicon to the final url if the original one gets redirected.
+ * Note this is not an urgent request, hence it is dispatched to the main
+ * thread idle handler to avoid any possible performance impact.
+ */
+async function fetchIconFromRedirects(url) {
+ const visitPaths = await fetchVisitPaths(url);
+ if (visitPaths.length > 1) {
+ const lastVisit = visitPaths.pop();
+ const redirectedUri = Services.io.newURI(lastVisit.url);
+ const iconInfo = await getFaviconInfo(redirectedUri);
+ if (iconInfo && iconInfo.faviconSize >= MIN_FAVICON_SIZE) {
+ PlacesUtils.favicons.setAndFetchFaviconForPage(
+ Services.io.newURI(url),
+ iconInfo.iconUri,
+ false,
+ PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
+ null,
+ Services.scriptSecurityManager.getSystemPrincipal()
+ );
+ }
+ }
+}
+
+this.FaviconFeed = class FaviconFeed {
+ constructor() {
+ this._queryForRedirects = new Set();
+ }
+
+ /**
+ * fetchIcon attempts to fetch a rich icon for the given url from two sources.
+ * First, it looks up the tippy top feed, if it's still missing, then it queries
+ * the places for rich icon with its most recent visit in order to deal with
+ * the redirected visit. See Bug 1421428 for more details.
+ */
+ async fetchIcon(url) {
+ // Avoid initializing and fetching icons if prefs are turned off
+ if (!this.shouldFetchIcons) {
+ return;
+ }
+
+ const site = await this.getSite(getDomain(url));
+ if (!site) {
+ if (!this._queryForRedirects.has(url)) {
+ this._queryForRedirects.add(url);
+ Services.tm.idleDispatchToMainThread(() => fetchIconFromRedirects(url));
+ }
+ return;
+ }
+
+ let iconUri = Services.io.newURI(site.image_url);
+ // The #tippytop is to be able to identify them for telemetry.
+ iconUri = iconUri
+ .mutate()
+ .setRef("tippytop")
+ .finalize();
+ PlacesUtils.favicons.setAndFetchFaviconForPage(
+ Services.io.newURI(url),
+ iconUri,
+ false,
+ PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
+ null,
+ Services.scriptSecurityManager.getSystemPrincipal()
+ );
+ }
+
+ /**
+ * Get the site tippy top data from Remote Settings.
+ */
+ async getSite(domain) {
+ const sites = await this.tippyTop.get({
+ filters: { domain },
+ syncIfEmpty: false,
+ });
+ return sites.length ? sites[0] : null;
+ }
+
+ /**
+ * Get the tippy top collection from Remote Settings.
+ */
+ get tippyTop() {
+ if (!this._tippyTop) {
+ this._tippyTop = RemoteSettings("tippytop");
+ }
+ return this._tippyTop;
+ }
+
+ /**
+ * Determine if we should be fetching and saving icons.
+ */
+ get shouldFetchIcons() {
+ return Services.prefs.getBoolPref("browser.chrome.site_icons");
+ }
+
+ onAction(action) {
+ switch (action.type) {
+ case at.RICH_ICON_MISSING:
+ this.fetchIcon(action.data.url);
+ break;
+ }
+ }
+};
+
+const EXPORTED_SYMBOLS = ["FaviconFeed", "fetchIconFromRedirects"];
diff --git a/browser/components/newtab/lib/FilterAdult.jsm b/browser/components/newtab/lib/FilterAdult.jsm
new file mode 100644
index 0000000000..52a21dfba8
--- /dev/null
+++ b/browser/components/newtab/lib/FilterAdult.jsm
@@ -0,0 +1,2980 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
+ChromeUtils.defineModuleGetter(
+ this,
+ "Services",
+ "resource://gre/modules/Services.jsm"
+);
+
+// Keep a Set of adult base domains for lookup (initialized at end of file)
+let gAdultSet;
+
+// Keep a hasher for repeated hashings
+let gCryptoHash = null;
+
+/**
+ * Run some text through md5 and return the base64 result.
+ */
+function md5Hash(text) {
+ // Lazily create a reusable hasher
+ if (gCryptoHash === null) {
+ gCryptoHash = Cc["@mozilla.org/security/hash;1"].createInstance(
+ Ci.nsICryptoHash
+ );
+ }
+
+ gCryptoHash.init(gCryptoHash.MD5);
+
+ // Convert the text to a byte array for hashing
+ gCryptoHash.update(
+ text.split("").map(c => c.charCodeAt(0)),
+ text.length
+ );
+
+ // Request the has result as ASCII base64
+ return gCryptoHash.finish(true);
+}
+
+/**
+ * Filter out any link objects that have a url with an adult base domain.
+ */
+function filterAdult(links) {
+ return links.filter(({ url }) => {
+ try {
+ const uri = Services.io.newURI(url);
+ return !gAdultSet.has(md5Hash(Services.eTLD.getBaseDomain(uri)));
+ } catch (ex) {
+ return true;
+ }
+ });
+}
+
+const EXPORTED_SYMBOLS = ["filterAdult"];
+
+// These are md5 hashes of base domains to be filtered out. Originally from:
+// https://hg.mozilla.org/mozilla-central/log/default/browser/base/content/newtab/newTab.inadjacent.json
+gAdultSet = new Set([
+ "+/UCpAhZhz368iGioEO8aQ==",
+ "+1e7jvUo8f2/2l0TFrQqfA==",
+ "+1gcqAqaRZwCj5BGiZp3CA==",
+ "+25t/2lo0FUEtWYK8LdQZQ==",
+ "+8PiQt6O7pJI/nIvQpDaAg==",
+ "+CLf5witKkuOvPCulTlkqw==",
+ "+CvLiih/gf2ugXAF+LgWqw==",
+ "+DWs0vvFGt6d3mzdcsdsyA==",
+ "+H0Rglt/HnhZwdty2hsDHg==",
+ "+L1FDsr5VQtuYc2Is5QGjw==",
+ "+LJYVZl1iPrdMU3L5+nxZw==",
+ "+Mp+JIyO0XC5urvMyi3wvQ==",
+ "+NMUaQ7XPsAi0rk7tTT9wQ==",
+ "+NmjwjsPhGJh9bM10SFkLw==",
+ "+OERSmo7OQUUjudkccSMOA==",
+ "+OLntmlsMBBYPREPnS6iVw==",
+ "+OXdvbTxHtSoLg7bZMho4w==",
+ "+P5q4YD1Rr5SX26Xr+tzlw==",
+ "+PUVXkoTqHxJHO18z4KMfw==",
+ "+Pl0bSMBAdXpRIA+zE02JA==",
+ "+QosBAnSM2h4lsKuBlqEZw==",
+ "+S+WXgVDSU1oGmCzGwuT3g==",
+ "+SclwwY8R2RPrnX54Z+A6w==",
+ "+VfRcTBQ80KSeJRdg0cDfw==",
+ "+WpF8+poKmHPUBB4UYh/ig==",
+ "+YVxSyViJfrme/ENe1zA7A==",
+ "+YrqTEJlJCv0A2RHQ8tr1A==",
+ "+ZozWaPWw8ws1cE5DJACeg==",
+ "+aF4ilbjQbLpAuFXQEYMWQ==",
+ "+dBv88reDrjEz6a2xX3Hzw==",
+ "+dIEf5FBrHpkjmwUmGS6eg==",
+ "+edqJYGvcy1AH2mEjJtSIg==",
+ "+fcjH2kZKNj8quOytUk4nQ==",
+ "+gO0bg8LY+py2dLM1sM7Ag==",
+ "+gbitI/gpxebN/rK7qj8Fw==",
+ "+gpHnUj2GWocP74t5XWz4w==",
+ "+jVN/3ASc2O44sX6ab8/cg==",
+ "+mJLK+6qq8xFv7O/mbILTw==",
+ "+n0K7OB2ItzhySZ4rhUrMg==",
+ "+p8pofUlwn8vV6Rp6+sz9g==",
+ "+tuUmnRDRWVLA+1k0dcUvg==",
+ "+zBkeHF4P8vLzk1iO1Zn3Q==",
+ "//eHwmDOQRSrv+k9C/k3ZQ==",
+ "/2Chaw2M9DzsadFFkCu6WQ==",
+ "/2c4oNniwhL3z5IOngfggg==",
+ "/2jGyMekNu7U136K+2N3Jg==",
+ "/Bwpt5fllzDHq2Ul6v86fA==",
+ "/DJgKE9ouibewuZ2QEnk6w==",
+ "/DiUApY7cVp5W9o24rkgRA==",
+ "/FchS2nPezycB8Bcqc2dbg==",
+ "/FdZzSprPnNDPwbhV1C0Cg==",
+ "/FsJYFNe+7UvsSkiotNJEQ==",
+ "/G26n5Xoviqldr5sg/Jl3w==",
+ "/HU2+fBqfWTEuqINc0UZSA==",
+ "/IarsLzJB8bf0AupJJ+/Eg==",
+ "/KYZdUWrkfxSsIrp46xxow==",
+ "/MEOgAhwb7F0nBnV4tIRZA==",
+ "/MeHciFhvFzQsCIw39xIZA==",
+ "/Ph/6l/lFNVqxAje1+PgFA==",
+ "/SP6pOdYFzcAl2OL05z4uQ==",
+ "/TSsi/AwKHtP6kQaeReI3w==",
+ "/VnKh/NDv7y/bfO6CWsLaQ==",
+ "/XC/FmMIOdhMTPqmy4DfUA==",
+ "/XjB6c5fxFGcKVAQ4o+OMw==",
+ "/YuQw7oAF08KDptxJEBS9g==",
+ "/a+bLXOq02sa/s8h7PhUTg==",
+ "/a9O7kWeXa0le45ab3+nVw==",
+ "/c34NtdUZAHWIwGl3JM8Tw==",
+ "/cJ0Nn5YbXeUpOHMfWXNHQ==",
+ "/cdR1i5TuQvO+u3Ov3b0KQ==",
+ "/gi3UZmunVOIXhZSktZ8zQ==",
+ "/hFhjFGJx2wRfz6hyrIpvA==",
+ "/jDVt9dRIn+o4IQ1DPwbsg==",
+ "/jH6imhTPZ/tHI4gYz2+HA==",
+ "/kGxvyEokQsVz0xlKzCn2A==",
+ "/mFp3GFkGNLhx2CiDvJv4A==",
+ "/mrqas0eDX+sFUNJvCQY8g==",
+ "/n1RLTTVpygre1dl36PDwQ==",
+ "/ngbFuKIAVpdSwsA3VxvNw==",
+ "/p/aCTIhi1bU0/liuO/a2Q==",
+ "/u5W2Gab4GgCMIc4KTp2mg==",
+ "/wIZAye9h1TUiZmDW0ZmYA==",
+ "/wiA2ltAuWyBhIvQAYBTQw==",
+ "/y/jHHEpUu5TR+R2o96kXA==",
+ "/zFLRvi75UL8qvg+a6zqGg==",
+ "00TVKawojyqrJkC7YqT41Q==",
+ "022B0oiRMx8Xb4Af98mTvQ==",
+ "02im2RooJQ/9UfUrh5LO+A==",
+ "0G93AxGPVwmr66ZOleM90A==",
+ "0HN6MIGtkdzNPsrGs611xA==",
+ "0K4NBxqEa3RYpnrkrD/XjQ==",
+ "0L0FVcH5Dlj3oL8+e9Na7g==",
+ "0NrvBuyjcJ2q6yaHpz/FOA==",
+ "0ODJyWKJSfObo+FNdRQkkA==",
+ "0QB0OUW5x2JLHfrtmpZQ+w==",
+ "0QCQORCYfLuSbq94Sbt0bQ==",
+ "0QbH4oI8IjZ9BRcqRyvvDQ==",
+ "0QxPAqRF8inBuFEEzNmLjA==",
+ "0SkC/4PtnX1bMYgD6r6CLA==",
+ "0TxcYwG72dT7Tg+eG8pP1w==",
+ "0UeRwDID2RBIikInqFI7uw==",
+ "0VsaJHR0Ms8zegsCpAKoyg==",
+ "0Y6iiZjCwPDwD/CwJzfioQ==",
+ "0ZEC3hy411LkOhKblvTcqg==",
+ "0ZRGz+oj2infCAkuKKuHiQ==",
+ "0a4SafpDIe8V4FlFWYkMHw==",
+ "0b/xj6fd0x+aB8EB0LC4SA==",
+ "0bj069wXgEJbw7dpiPr8Tg==",
+ "0dIeIM5Zvm5nSVWLy94LWg==",
+ "0e8hM3E5tnABRyy29A8yFw==",
+ "0egBaMnAf0CQEXf1pCIKnA==",
+ "0fN+eHlbRS6mVZBbH/B9FQ==",
+ "0fnruVOCxEczscBuv4yL9A==",
+ "0fpe9E6m3eLp/5j5rLrz2Q==",
+ "0klouNfZRHFFpdHi4ZR2hA==",
+ "0nOg18ZJ/NicqVUz5Jr0Hg==",
+ "0ofMbUCA3/v5L8lHnX4S5w==",
+ "0p1jMr06OyBoXQuSLYN4aQ==",
+ "0p8YbEMxeb73HbAfvPLQRw==",
+ "0q+erphtrB+6HBnnYg7O6w==",
+ "0rTYcuVYdilO7zEfKrxY3A==",
+ "0rfG4gRugAwVP0i3AGVxxg==",
+ "0u+0WHr7WI6IlVBBgiRi6w==",
+ "0yJ7TQYzcp3DXVSvwavr+w==",
+ "1+A9FCGP3bZhk6gU3LQtNg==",
+ "1+XWdu4qCqLLVjqkKz3nmA==",
+ "1+qmrbC8c7MJ6pxmDMcKuA==",
+ "1/Hxu8M9N/oNwk8bCj4FNQ==",
+ "1/SGIab+NnizimUmNDC4wA==",
+ "1/ZheMsbojazxt31j/l3iA==",
+ "10OltdxPXOvfatJuwPVKbQ==",
+ "11FE2kknwYi2Qu0JUKMn3A==",
+ "11U5XEwfMI7avx014LfC8g==",
+ "16d+fhFlgayu3ttKVV/pbg==",
+ "16iT/jCcPDrJEfi2bE5F+Q==",
+ "18RKixTv12q3xoBLz6eKiA==",
+ "18ndtDM9UaNfBR1cr3SHdA==",
+ "19yQHaBemtlgo2QkU5M6jQ==",
+ "1AeReq55UQotRQVKJ66pmg==",
+ "1ApqwW7pE+XUB2Cs2M6y7g==",
+ "1B5gxGQSGzVKoNd5Ol4N7g==",
+ "1BjsijOzgHt/0i36ZGffoQ==",
+ "1C50kisi9nvyVJNfq2hOEQ==",
+ "1E3pMgAHOnHx3ALdNoHr8Q==",
+ "1EI9aa955ejNo1dJepcZJw==",
+ "1FSrgkUXgZot2CsmbAtkPw==",
+ "1Gpj4TPXhdPEI4zfQFsOCg==",
+ "1HDgfU7xU7LWO/BXsODZAQ==",
+ "1I+UVx3krrD4NhzO7dgfHQ==",
+ "1JI9bT92UzxI8txjhst9LQ==",
+ "1JRgSHnfAQFQtSkFTttkqQ==",
+ "1LPC0BzhJbepHTSAiZ3QTw==",
+ "1MIn73MLroxXirrb+vyg2Q==",
+ "1Oykse0jQVbuR3MvW5ot4A==",
+ "1Pmnur6TbZ9cmemvu0+dSA==",
+ "1PvTn90xwZJPoVfyT5/uIQ==",
+ "1QGhj9NONF2rC44UdO+Izw==",
+ "1RQZ2pWSxT+RKyhBigtSFg==",
+ "1Vtrv6QUAfiYQjlLTpNovg==",
+ "1WIi4I62GqkjDXOYqHWJfQ==",
+ "1Wc8jQlDSB4Dp32wkL2odw==",
+ "1X14kHeKwGmLeYqpe60XEA==",
+ "1YO9G8qAhLIu2rShvekedw==",
+ "1Ym0lyBJ9aFjhJb/GdUPvQ==",
+ "1b2uf+CdVjufqiVpUShvHw==",
+ "1buQEv2YlH/ljTgH0uJEtw==",
+ "1cj1Fpd3+UiBAOahEhsluA==",
+ "1d7RPHdZ9qzAbG3Vi9BdFA==",
+ "1dhq3ozNCx0o4dV1syLVDA==",
+ "1dsKN1nG6upj7kKTKuJWsQ==",
+ "1eCHcz4swFH+uRhiilOinQ==",
+ "1eRUCdIJe3YGD5jOMbkkOg==",
+ "1fztTtQWNMIMSAc5Hr6jMQ==",
+ "1gA65t5FiBTEgMELTQFUPQ==",
+ "1jBaRO8Bg5l6TH7qJ8EPiw==",
+ "1k8tL2xmGFVYMgKUcmDcEw==",
+ "1lCcQWGDePPYco4vYrA5vw==",
+ "1m1yD4L9A7Q1Ot+wCsrxJQ==",
+ "1mw6LfTiirFyfjejf8QNGA==",
+ "1nXByug2eKq0kR3H3VjnWQ==",
+ "1tpM0qgdo7JDFwvT0TD78g==",
+ "1vqRt79ukuvdJNyIlIag8Q==",
+ "1wBuHqS1ciup31WTfm3NPg==",
+ "1xWx5V3G9murZP7srljFmA==",
+ "1zDfWw5LdG20ClNP1HYxgw==",
+ "203EqmJI9Q4tWxTJaBdSzA==",
+ "23C4eh3yBb5n/RNZeTyJkA==",
+ "23d9B9Gz5kUOi1I//EYsSQ==",
+ "24H9q+E8pgCEdFS7JO5kzQ==",
+ "25w3ZRUzCvJwAVHYCIO5uw==",
+ "26+yXbqI+fmIZsYl4UhUzw==",
+ "26Wmdp6SkKN74W0/XPcnmA==",
+ "29EybnMEO95Ng4l/qK4NWQ==",
+ "2Ct+pLXrK6Ku1f4qehjurQ==",
+ "2D6yhuABiaFFoXz0Lh0C+w==",
+ "2DNbXVgesUa7PgYQ4zX5Lw==",
+ "2E41e0MgM3WhFx2oasIQeA==",
+ "2HHqeGRMfzf3RXwVybx+ZQ==",
+ "2Hc5oyl0AYRy2VzcDKy+VA==",
+ "2QQtKtBAm2AjJ5c0WQ6BQA==",
+ "2QS/6OBA1T01NlIbfkTYJg==",
+ "2RFaMPlSbVuoEqKXgkIa5A==",
+ "2SI4F7Vvde2yjzMLAwxOog==",
+ "2SwIiUwT4vRZPrg7+vZqDA==",
+ "2W6lz1Z7PhkvObEAg2XKJw==",
+ "2Wvk/kouEEOY0evUkQLhOQ==",
+ "2XrR2hjDEvx8MQpHk9dnjw==",
+ "2aDK0tGNgMLyxT+BQPDE8Q==",
+ "2aIx9UdMxxZWvrfeJ+DcTw==",
+ "2abfl3N46tznOpr+94VONQ==",
+ "2bsIpvnGcFhTCSrK9EW1FQ==",
+ "2hEzujfG3mR5uQJXbvOPTQ==",
+ "2j83jrPwPfYlpJJ2clEBYQ==",
+ "2ksediOVrh4asSBxKcudTg==",
+ "2melaInV0wnhBpiI3da6/A==",
+ "2nSTEYzLK77h5Rgyti+ULQ==",
+ "2os5s7j7Tl46ZmoZJH8FjA==",
+ "2rOkEVl90EPqfHOF5q2FYw==",
+ "2rhjiY0O0Lo36wTHjmlNyw==",
+ "2vm7g3rk1ACJOTCXkLB3zA==",
+ "2wesXiib76wM9sqRZ7JYwQ==",
+ "2ywo4t5PPSVUCWDwUlOVwQ==",
+ "3++dZXzZ6AFEz7hK+i5hww==",
+ "3+9nURtBK3FKn0J9DQDa3g==",
+ "3+zsjCi7TnJhti//YXK35w==",
+ "3/1puZTGSrD9qNKPGaUZww==",
+ "300hoYyMR/mk1mfWJxS8/w==",
+ "301utVPZ93AnPLYbsiJggw==",
+ "312g8iTB9oJgk/OqcgR7Cw==",
+ "342VOUOxoLHUqtHANt83Hw==",
+ "36XDmX6j542q+Oei1/x0gw==",
+ "37Nkh06O979nt7xzspOFyQ==",
+ "3AKEYQqpkfW7CZMFQZoxOw==",
+ "3AVYtcIv7A5mVbVnQMaCeA==",
+ "3BjLFon1Il0SsjxHE2A1LQ==",
+ "3CJbrUdW68E3Drhe4ahUnQ==",
+ "3EhLkC9NqD3A6ApV6idmgg==",
+ "3Ejtsqw3Iep/UQd0tXnSlg==",
+ "3FH4D31nKV13sC9RpRZFIg==",
+ "3Gg9N7vjAfQEYOtQKuF/Eg==",
+ "3HPOzIZxoaQAmWRy9OkoSg==",
+ "3JhnM6G4L06NHt31lR0zXA==",
+ "3L3KEBHhgDwH615w4OvgZA==",
+ "3Leu2Sc+YOntJFlrvhaXeg==",
+ "3P2aJxV8Trll2GH9ptElYA==",
+ "3RTtSaMp1TZegJo5gFtwwA==",
+ "3TbRZtFtsh9ez8hqZuTDeA==",
+ "3TjntNWtpG7VqBt3729L6Q==",
+ "3UBYBMejKInSbCHRoJJ7dg==",
+ "3UNJ37f+gnNyYk9yLFeoYA==",
+ "3WVBP9fyAiBPZAq3DpMwOQ==",
+ "3Wfj05vCLFAB9vII5AU9tw==",
+ "3WwITQML938W9+MUM56a3A==",
+ "3XyoREdvhmSbyvAbgw2y/A==",
+ "3Y4w0nETru3SiSVUMcWXqw==",
+ "3Y6/HqS1trYc9Dh778sefg==",
+ "3YXp1PmMldUjBz3hC6ItbA==",
+ "3djRJvkZk9O2bZeUTe+7xQ==",
+ "3go7bJ9WqH/PPUTjNP3q/Q==",
+ "3hVslsq98QCDIiO40JNOuA==",
+ "3iC21ByW/YVL+pSyppanWw==",
+ "3itfXtlLPRmPCSYaSvc39Q==",
+ "3j0kFUZ6g+yeeEljx+WXGg==",
+ "3jmCreW5ytSuGfmeLv7NfQ==",
+ "3jqsY8/xTWELmu/az3Daug==",
+ "3kREs/qaMX0AwFXN0LO5ow==",
+ "3ltw31yJuAl4VT6MieEXXw==",
+ "3nthUmLZ30HxQrzr2d7xFA==",
+ "3oMTbWf7Bv83KRlfjNWQZA==",
+ "3pi3aNVq1QNJmu1j0iyL0g==",
+ "3rbml1D0gfXnwOs5jRZ3gA==",
+ "3sNJJIx1NnjYcgJhjOLJOg==",
+ "3v09RHCPTLUztqapThYaHg==",
+ "3xw8+0/WU51Yz4TWIMK8mw==",
+ "3y5Xk65ShGvWFbQxcZaQAQ==",
+ "3yDD+xT8iRfUVdxcc7RxKw==",
+ "3yavzOJ1mM44pOSFLLszgA==",
+ "4+htiqjEz9oq0YcI/ErBVg==",
+ "40HzgVKYnqIb6NJhpSIF0A==",
+ "40gCrW4YWi+2lkqMSPKBPg==",
+ "41WEjhYUlG6jp2UPGj11eQ==",
+ "444F9T6Y7J67Y9sULG81qg==",
+ "46FCwqh+eMkf+czjhjworw==",
+ "46piyANQVvvLqcoMq5G8tQ==",
+ "49jZr/mEW6fvnyzskyN40w==",
+ "49z/15Nx9Og7dN9ebVqIzg==",
+ "4A+RHIw+aDzw0rSRYfbc7g==",
+ "4BkqgraeXY7yaI1FE07Evw==",
+ "4CfEP8TeMKX33ktwgifGgA==",
+ "4DIPP/yWRgRuFqVeqIyxMQ==",
+ "4FBBtWPvqJ3dv4w25tRHiQ==",
+ "4ID0PHTzIMZz2rQqDGBVfA==",
+ "4KJZPCE9NKTfzFxl76GWjg==",
+ "4LtQrahKXVtsbXrEzYU1zQ==",
+ "4LvQSicqsgxQFWauqlcEjw==",
+ "4NHQwbb3zWq2klqbT/pG6g==",
+ "4NP8EFFJyPcuQKnBSxzKgQ==",
+ "4PBaoeEwUj79njftnYYqLg==",
+ "4Qinl7cWmVeLJgah8bcNkw==",
+ "4SdHWowXgCpCDL28jEFpAw==",
+ "4TQkMnRsXBobbtnBmfPKnA==",
+ "4VR5LiXLew6Nyn91zH9L4w==",
+ "4WO6eT0Rh6sokb29zSJQnQ==",
+ "4WRdAjiUmOQg2MahsunjAg==",
+ "4WcFEswYU/HHQPw77DYnyA==",
+ "4XNUmgwxsqDYsNmPkgNQYQ==",
+ "4Xh/B3C16rrjbES+FM1W8g==",
+ "4ZFYKa7ZgvHyZLS6WpM8gA==",
+ "4aPU6053cfMLHgLwAZJRNg==",
+ "4ekt4m38G9m599xJCmhlug==",
+ "4erEA42TqGA9K4iFKkxMMA==",
+ "4ifNsmjYf1iOn2YpMfzihg==",
+ "4iiCq+HhC+hPMldNQMt0NA==",
+ "4itEKfbRCJvqlgKnyEdIOQ==",
+ "4jeOFKuKpCmMXUVJSh9y0g==",
+ "4kXlJNuT79XXf1HuuFOlHw==",
+ "4kj0S8XlmhHXoUP7dQItUw==",
+ "4mQVNv7FHj+/O6XFqWFt/Q==",
+ "4mig4AMLUw+T/ect9p4CfA==",
+ "4qMSNAxichi3ori/pR+o0w==",
+ "4rrSL6N0wyucuxeRELfAmw==",
+ "4u3eyKc+y3uRnkASrgBVUw==",
+ "4wnUAbPT3AHRJrPwTTEjyw==",
+ "4xojeUxTFmMLGm6jiMYh/Q==",
+ "4yEkKp2FYZ09mAhw2IcrrA==",
+ "4yVqq66iHYQjiTSxGgX2oA==",
+ "4yrFNgqWq17zVCyffULocA==",
+ "50jASqzGm4VyHJbFv8qVRA==",
+ "50xwiYvGQytEDyVgeeOnMg==",
+ "51yLpfEdvqXmtB6+q27/AQ==",
+ "520wTzrysiRi2Td92Zq0HQ==",
+ "53UccFNzMi9mKmdeD82vAw==",
+ "54XELlPm8gBvx8D5bN3aUg==",
+ "59ipbMH7cKBsF9bNf4PLeQ==",
+ "5CMadLqS2KWwwMCpzlDmLw==",
+ "5DDb7fFJQEb3XTc3YyOTjg==",
+ "5HovoyHtul8lXh+z8ywq9A==",
+ "5I/heFSQG/UpWGx0uhAqGQ==",
+ "5KOgetfZR+O2wHQSKt41BQ==",
+ "5LJqHFRyIwQKA4HbtqAYQQ==",
+ "5LuFDNKzMd2BzpWEIYO2Ww==",
+ "5M3dFrAOemzQ0MAbA8bI5w==",
+ "5N2oi2pB69NxeNt08yPLhw==",
+ "5NEP7Xt7ynj6xCzWzt21hQ==",
+ "5Nk2Z94DhlIdfG5HNgvBbQ==",
+ "5PfGtbH9fmVuNnq83xIIgQ==",
+ "5Q/Y2V0iSVTK8HE8JerEig==",
+ "5S5/asYfWjOwnzYpbK6JDw==",
+ "5SbwLDNT6sBOy6nONtUcTg==",
+ "5T39s5CtSrK5awMPUcEWJg==",
+ "5VO1inwXMvLDBQSOahT6rg==",
+ "5VY++KiWgo7jXSdFJsPN3A==",
+ "5Wcq+6hgnWsQZ/bojERpUw==",
+ "5Yrj6uevT8wHRyqqgnSfeg==",
+ "5dUry23poD+0wxZ3hH6WmA==",
+ "5eHStFN7wEmIE+uuRwIlPQ==",
+ "5eXpiczlRdmqMYSaodOUiQ==",
+ "5gGoDPTc/sOIDLngmlEq4A==",
+ "5jHgQF4SfO/zy9xy9t+9dw==",
+ "5jyuDp82Fux+B0+zlx8EXw==",
+ "5kvyy902llnYGQdn2Py04w==",
+ "5l6kDfjtZjkTZPJvNNOVFw==",
+ "5lfLJAk1L3QzGMML3fOuSw==",
+ "5m1ijXEW+4RTNGZsDA/rxQ==",
+ "5oD/aGqoakxaezq43x0Tvw==",
+ "5pje7qyz8BRsa8U4a4rmoA==",
+ "5pqqzC/YmRIMA9tMFPi7rg==",
+ "5r1ZsGkrzNQEpgt/gENibw==",
+ "5u2PdDcIY3RQgtchSGDCGg==",
+ "5ugVOraop5P5z5XLlYPJyQ==",
+ "5w/c9WkI/FA+4lOtdPxoww==",
+ "5w4FbRhWACP7k2WnNitiHg==",
+ "6+jhreeBLfw64tJ+Nhyipw==",
+ "600bwlyhcy754W1E6tuyYg==",
+ "600mjiWke4u0CDaSQKLOOg==",
+ "60suecbWRfexSh7C67RENA==",
+ "61V74uIjaSfZM8au1dxr1A==",
+ "62RHCbpGU8Hb+Ubn+SCTBg==",
+ "63OTPaKM0xCfJOy9EDto+Q==",
+ "64AA4jLHXc1Dp15aMaGVcA==",
+ "64QzHOYX0A9++FqRzZRHlQ==",
+ "64YsV2qeDxk2Q6WK/h7OqA==",
+ "65KhGKUBFQubRRIEdh9SwQ==",
+ "6706ncrH1OANFnaK6DUMqQ==",
+ "68jPYo3znYoU4uWI7FH3/g==",
+ "68nqDtXOuxF7DSw6muEZvg==",
+ "6ACvJNfryPSjGOK39ov8Qg==",
+ "6CjtF1S2Y6RCbhl7hMsD+g==",
+ "6G2bD3Y7qbGmfPqH9TqLFA==",
+ "6GXHGF62/+jZ7PfIBlMxZw==",
+ "6HGeEPyTAu9oiKhNVLjQnA==",
+ "6HnWgYNKohqhoa1tnjjU3A==",
+ "6M6QapJ5xtMXfiD3bMaiLA==",
+ "6NP81geiL14BeQW6TpLnUA==",
+ "6PzjncEw2wHZg7SP7SQk9w==",
+ "6QAtjOK9enNLRhcVa2iaTg==",
+ "6QUGE2S8oFYx4T4nW56cCw==",
+ "6W79FmpUN1ByNtv5IEXY4w==",
+ "6WhHPWlqEUqXC52rHGRHjA==",
+ "6XYqR2WvDzx4fWO7BIOTjA==",
+ "6Z9myGCF5ylWljgIYAmhqw==",
+ "6ZKmm7IW7IdWuVytLr68CQ==",
+ "6ZMs9vCzK9lsbS6eyzZlIA==",
+ "6b7ue29cBDsvmj1VSa5njw==",
+ "6c0iuya20Ys8BsvoI4iQaQ==",
+ "6cTETZ9iebhWl+4W5CB+YQ==",
+ "6dshA8knH5qqD+KmR/kdSQ==",
+ "6e8boFcyc8iF0/tHVje4eQ==",
+ "6erpZS36qZRXeZ9RN9L+kw==",
+ "6fWom3YoKvW6NIg6y9o9CQ==",
+ "6k2cuk0McTThSMW/QRHfjA==",
+ "6lVSzYUQ/r0ep4W2eCzFpg==",
+ "6leyDVmC5jglAa98NQ3+Hg==",
+ "6nwR+e9Qw0qp8qIwH9S/Mg==",
+ "6o5g9JfKLKQ2vBPqKs6kjg==",
+ "6rIWazDEWU5WPZHLkqznuQ==",
+ "6rqK8sjLPJUIp7ohkEwfZg==",
+ "6sBemZt4qY/TBwqk3YcLOQ==",
+ "6sNP0rzCCm3w976I2q2s/w==",
+ "6tfM6dx3R5TiVKaqYQjnCg==",
+ "6txm8z4/LGCH0cpaet/Hsg==",
+ "6uMF5i0b/xsk55DlPumT7A==",
+ "6uT7LZiWjLnnqnnSEW4e/Q==",
+ "6v3eTZtPYBfKFSjfOo2UaA==",
+ "6wkfN8hyKmKU6tG3YetCmw==",
+ "6z8CRivao3IMyV4p4gMh7g==",
+ "71w3aSvuh2mBLtdqJCN3wA==",
+ "734u4Y1R3u7UNUnD+wWUoA==",
+ "74FW/QYTzr/P1k6QwVHMcw==",
+ "778O1hdVKHLG2q9dycUS0Q==",
+ "78b8sDBp28zUlYPV5UTnYw==",
+ "79uTykH43voFC3XhHHUzKg==",
+ "7E6V6/zSjbtqraG7Umj+Jw==",
+ "7Ephy+mklG2Y3MFdqmXqlA==",
+ "7Eqzyb+Kep+dIahYJWNNxQ==",
+ "7GgNLBppgAKcgJCDSsRqOQ==",
+ "7J3FoFGuTIW36q0PZkgBiw==",
+ "7K8l6KoP0BH82/WMLntfrg==",
+ "7R5rFaXCxM3moIUtoCfM2g==",
+ "7Tauesu7bgs5lJmQROVFiQ==",
+ "7VHlLw20dWck+I8tCEZilA==",
+ "7W9aF7dxnL+E8lbS/F7brg==",
+ "7XRiYvytcwscemlxd9iXIQ==",
+ "7Y87wVJok20UfuwkGbXxLg==",
+ "7b0oo4+qphu6HRvJq6qkHQ==",
+ "7bM/pn4G7g7Zl6Xf1r62Lg==",
+ "7br49X11xc2GxQLSpZWjKQ==",
+ "7btpMFgeGkUsiTtsmNxGQA==",
+ "7cnUHeaPO8txZGGWHL9tKg==",
+ "7dz+W494zwU5sg63v5flCg==",
+ "7k5rBuh8FbTTI4TP87wBPQ==",
+ "7l0RMKbONGS/goW/M+gnMQ==",
+ "7mxU5fJl/c6dXss9H3vGcQ==",
+ "7nr3zyWL+HHtJhRrCPhYZA==",
+ "7p4NpnoNSQR7ISg+w+4yFg==",
+ "7pkUY2UzSbGnwLvyRrbxfA==",
+ "7sCJ4RxbxRqVnF4MBoKfuQ==",
+ "7w3b73nN/fIBvuLuGZDCYQ==",
+ "7w4PDRJxptG8HMe/ijL6cQ==",
+ "7wgT9WIiMVcrj48PVAMIgw==",
+ "7xDIG/80SnhgxAYPL9YJtg==",
+ "7xTKFcog69nTmMfr5qFUTA==",
+ "80C9TB9/XT1gGFfQDJxRoA==",
+ "80PCwYh4llIKAplcDvMj4g==",
+ "80UE+Ivby3nwplO/HA7cPw==",
+ "81ZH3SO0NrOO+xoR/Ngw1g==",
+ "81iQLU+YwxNwq4of6e9z7A==",
+ "81nkjWtpBhqhvOp6K8dcWg==",
+ "81pAhreEPxcKse+++h1qBg==",
+ "82hTTe1Nr4N2g7zwgGjxkw==",
+ "83ERX2XJV3ST4XwvN7YWCg==",
+ "83WGpQGWyt6mCV+emaomog==",
+ "83wtvSoSP9FVBsdWaiWfpA==",
+ "861mBNvjIkVgkBiocCUj/Q==",
+ "88PNi9+yn3Bp4/upgxtWGA==",
+ "88tB/HgUIUnqWXEX++b5Aw==",
+ "897ptlztTjr7yk+pk8MT0Q==",
+ "8AfCSZC0uasVON9Y/0P2Pw==",
+ "8B12CamjOGzJDnQ+RkUf4w==",
+ "8BLkvEkfnOizJq0OTCYGzw==",
+ "8CjmgWQSAAGcXX9kz3kssw==",
+ "8Cm19vJW8ivhFPy0oQXVNA==",
+ "8DtgIyYiNFqDc5qVrpFUng==",
+ "8GyPup4QAiolFJ9v80/Nkw==",
+ "8JVHFRwAd/SCLU0CRJYofg==",
+ "8LNNoHe6rEQyJ0ebl151Mw==",
+ "8M0kSvjn5KN8bjsMdUqKZQ==",
+ "8N3mhHt29FZDHn1P2WH1wQ==",
+ "8OFxXwnPmrogpNoueZlC4Q==",
+ "8QK7emHS6rAcAF5QQemW/A==",
+ "8RtLlzkGEiisy1v9Xo0sbw==",
+ "8VqeoQELbCs232+Mu+HblA==",
+ "8WU1vLKV1GhrL7oS9PpABg==",
+ "8ZBiwr842ZMKphlqmNngHw==",
+ "8ZFPMJJYVJHsfRpU4DigSg==",
+ "8ZqmPJDnQSOFXvNMRQYG2Q==",
+ "8c+lvG5sZNimvx9NKNH3ug==",
+ "8cXqZub6rjgJXmh1CYJBOg==",
+ "8dBIsHMEAk7aoArLZKDZtg==",
+ "8dUcSkd2qnX5lD9B+fUe+Q==",
+ "8dbyfox/isKLsnVjQNsEXg==",
+ "8fJLQeIHaTnJ8wGqUiKU6g==",
+ "8g08gjG/QtvAYer32xgNAg==",
+ "8hsfXqi4uiuL+bV1VrHqCw==",
+ "8iYdEleTXGM+Wc85/7vU9w==",
+ "8j9GVPiFdfIRm/+ho7hpoA==",
+ "8nOTDhFyZ8YUA4b6M5p84w==",
+ "8snljTGo/uICl9q0Hxy7/A==",
+ "8uP4HUnSodw88yoiWXOIcw==",
+ "8vLA9MOdmLTo3Qg+/2GzLA==",
+ "8vr+ERVrM99dp+IGnCWDGQ==",
+ "8ylI1AS3QJpAi3I/NLMYdg==",
+ "9+hjTVMQUsvVKs7Tmp52tg==",
+ "90dtIMq0ozJXezT2r79vMQ==",
+ "91+Yms6Oy/rP0rVjha5z9w==",
+ "91LQuW6bMSxl10J/UDX23A==",
+ "91SdBFJEZ65M+ixGaprY/A==",
+ "91VcAVv7YDzkC1XtluPigw==",
+ "91vfsZ7Lx9x5gqWTOdM4sg==",
+ "96ORaz1JRHY1Gk8H74+C2g==",
+ "99+SBN45LwKCPfrjUKRPmw==",
+ "9Bet5waJF5/ZvsYaHUVEjQ==",
+ "9DRHdyX8ECKHUoEsGuqR4Q==",
+ "9DtM1vls4rFTdrSnQ7uWXw==",
+ "9FdpxlIFu11qIPdO7WC5nw==",
+ "9Gkw+hvsR/tFY1cO89topg==",
+ "9J53kk+InE3CKa7cPyCXMw==",
+ "9JKIJrlQjhNSC46H3Cstcw==",
+ "9L6yLO93sRN70+3qq3ObfA==",
+ "9MDG0WeBPpjGJLEmUJgBWg==",
+ "9QFYrCXsGsInUb4SClS3cQ==",
+ "9RGIQ2qyevNbSSEF36xk/A==",
+ "9RXymE9kCkDvBzWGyMgIWA==",
+ "9SUOfKtfKmkGICJnvbIDMg==",
+ "9SgfpAY0UhNC6sYGus9GgQ==",
+ "9T7gB0ZkdWB0VpbKIXiujQ==",
+ "9TalxEyFgy6hFCM73hgb7Q==",
+ "9UhKmKtr4vMzXTEn74BEhg==",
+ "9W57pTzc572EvSURqwrRhw==",
+ "9Y1ZmfiHJd9vCiZ6KfO1xQ==",
+ "9aKH1u5+4lgYhhLztQ4KWA==",
+ "9ajIS45NTicqRANzRhDWFA==",
+ "9bAWYElyRN1oJ6eJwPtCtQ==",
+ "9cvHJmim9e0pOaoUEtiM6A==",
+ "9dbn0Kzwr9adCEfBJh78uQ==",
+ "9iB7+VwXRbi6HLkWyh9/kg==",
+ "9inw7xzbqAnZDKOl/MfCqA==",
+ "9jxA/t3TQx8dQ+FBsn/YCg==",
+ "9k17UqdR1HzlF7OBAjpREA==",
+ "9k1u/5TgPmXrsx3/NsYUhg==",
+ "9lLhHcrPWI4EsA4fHIIXuw==",
+ "9nMltdrrBmM5ESBY2FRjGA==",
+ "9oQ/SVNJ4Ye9lq8AaguGAQ==",
+ "9oUawSwUGOmb0sDn3XS6og==",
+ "9onh6QKp70glZk9cX3s34A==",
+ "9pdeedz1UZUlv8jPfPeZ1g==",
+ "9pk75mBzhmcdT+koHvgDlw==",
+ "9qWLbRLXWIBJUXYjYhY2pg==",
+ "9rL8nC/VbSqrvnUtH9WsxQ==",
+ "9reBKZ1Rp6xcdH1pFQacjw==",
+ "9s3ar9q32Y5A3tla5GW/2Q==",
+ "9sYLg75/hudZaBA3FrzKHw==",
+ "9tiibT8V9VwnPOErWGNT3w==",
+ "9vEgJVJLEfed6wJ7hBUGgQ==",
+ "9viAzLFGYYudBYFu7kFamg==",
+ "9vmJUS7WIVOlhMqwipAknQ==",
+ "9wUIeSgNN36SFxy8v2unVg==",
+ "9xIgKpZGqq0/OU6wM5ZSHw==",
+ "9xmtuClkFlpz/X5E9JBWBA==",
+ "A+DLpIlYyCb9DaarpLN76g==",
+ "A2ODff+ImIkreJtDPUVrlg==",
+ "A3dX2ShyL9+WOi6MNJBoYQ==",
+ "A6TLWhipfymkjPYq8kaoDQ==",
+ "AChOz8avRYsvxlbWcorQ3w==",
+ "AEpTVUQhIEJGlXJB6rS26A==",
+ "AFdelaqvxRj6T3YdLgCFyg==",
+ "AGd0rcLnQ0n+meYyJur1Pw==",
+ "AGoVLd0QPcXnTedT5T95JQ==",
+ "ALJWKUImVE40MbEooqsrng==",
+ "ALlGgVDO8So71ccX0D6u2g==",
+ "AMfL0rH+g8c0VqOUSgNzQw==",
+ "ARCWkHAnVgBOIkCDQ19ZuA==",
+ "ARKIvf4+zRF8eCvUITWPng==",
+ "ATmMzriwGLl+M3ppkfcZNA==",
+ "AUGmvZkpkKBry5bHZn4DJA==",
+ "AV/YJfdoDUdRcrXVwinhQg==",
+ "AVjwqrTBQH1VREuBlOyUOg==",
+ "AX1HxQKXD12Yv5HWi39aPQ==",
+ "AYxGETZs477n2sa1Ulu/RQ==",
+ "AZs3v4KJYxdi8T1gjVjI2Q==",
+ "AcKwfS8FRVqb72uSkDNY/Q==",
+ "AcbG0e6xN8pZfYAv7QJe1Q==",
+ "Af9j1naGtnZf0u1LyYmK1w==",
+ "AfVPdxD3FyfwwNrQnVNQ7A==",
+ "AgDJsaW0LkpGE65Kxk5+IA==",
+ "Ahpi9+nl13kPTdzL+jgqMw==",
+ "AiMtfedwGcddA+XYNc+21g==",
+ "AjHz9GkRTFPjrqBokCDzFw==",
+ "Ak3rlzEOds6ykivfg39xmw==",
+ "AkAes5oErTaJiGD2I4A1Pw==",
+ "AklOdt9/2//3ylUhWebHRw==",
+ "Al8+d/dlOA5BXsUc5GL8Tg==",
+ "Ao1Zc0h5AdSHtYt1caWZnQ==",
+ "AoN/pnK4KEUaGw4V9SFjpg==",
+ "ApiuEPWr8UjuRyJjsYZQBw==",
+ "AqHVaj3JcR44hnMzUPvVYg==",
+ "Ar1Eb/f/LtuIjXnnVPYQlA==",
+ "Ar9N1VYgE7riwmcrM3bA2Q==",
+ "AsAHrIkMgc3RRWnklY9lJw==",
+ "AvdeYb9XNOUFWiiz+XGfng==",
+ "AwPTZpC28NJQhf5fNiJuLA==",
+ "AxEjImKz4tMFieSo7m60Sg==",
+ "AyWlT+EGzIXc395zTlEU5Q==",
+ "B+TsxQZf0IiQrU8X9S4dsQ==",
+ "B0TaUQ6dKhPfSc5V/MjLEQ==",
+ "B1VVUbl8pU0Phyl1RYrmBg==",
+ "B6reUwMkQFaCHb9BYZExpw==",
+ "BA18GEAOOyVXO2yZt2U35w==",
+ "BAJ+/jbk2HyobezZyB9LiQ==",
+ "BB/R8oQOcoE4j63Hrh8ifg==",
+ "BB9PTlwKAWkExt3kKC/Wog==",
+ "BDNM1u/9mefjuW1YM2DuBg==",
+ "BDbfe/xa9Mz1lVD82ZYRGA==",
+ "BH+rkZWQjTp7au6vtll/CQ==",
+ "BL3buzSCV78rCXNEhUhuKQ==",
+ "BLJk9wA88z6e0IQNrWJIVw==",
+ "BLbTFLSb4mkxMaq4/B2khg==",
+ "BMOi5JmFUg5sCkbTTffXHw==",
+ "BMZB1FwvAuEqyrd0rZrEzw==",
+ "BPT4PQxeQcsZsUQl33VGmg==",
+ "BTiGLT6XdZIpFBc91IJY6g==",
+ "BV1moliPL15M14xkL+H1zw==",
+ "BW0A06zoQw7S+YMGaegT7g==",
+ "BXGlq54wIH6R3OdYfSSDRw==",
+ "BYpHADmEnzBsegdYTv8B5Q==",
+ "BYz52gYI/Z6AbYbjWefcEA==",
+ "BZTzHJGhzhs3mCXHDqMjnQ==",
+ "BaRwTrc5ulyKbW4+QqD0dw==",
+ "BhKO1s1O693Fjy1LItR/Jw==",
+ "BjfOelfc1IBgmUxMJFjlbQ==",
+ "BlCgDd7EYDIqnoAiKOXX6Q==",
+ "BophnnMszW5o+ywgb+3Qbw==",
+ "Bq82MoMcDjIo/exqd/6UoA==",
+ "BuDVDLl0OGdomEcr+73XhQ==",
+ "BuENxPg7JNrWXcCxBltOPg==",
+ "Bv4mNIC72KppYw/nHQxfpQ==",
+ "Bvk8NX4l6WktLcRDRKsK/A==",
+ "BwRA+tMtwEvth28IwpZx+w==",
+ "BxFP+4o6PSlGN78eSVT1pA==",
+ "BxsDnI8jXr4lBwDbyHaYXw==",
+ "Byhi4ymFqqH8uIeoMRvPug==",
+ "BzkNYH03gF/mQY71RwO3VA==",
+ "C+Ssp+v1r+00+qiTy2d7kA==",
+ "C4QEzQKGxyRi2rjwioHttA==",
+ "C65PZm8rZxJ6tTEb6d08Eg==",
+ "C7UaoIEXsVRxjeA0u99Qmw==",
+ "CBAGa5l95f3hVzNi6MPWeQ==",
+ "CCK+6Dr72G3WlNCzV7nmqw==",
+ "CDsanJz7e3r/eQe+ZYFeVQ==",
+ "CF1sAlhjDQY/KWOBnSSveA==",
+ "CHLHizLruvCrVi9chj9sXA==",
+ "CHsFJfsvZkPWDXkA6ZMsDQ==",
+ "CJoZn5wdTXbhrWO5LkiW0g==",
+ "CLPzjXKGGpJ0VrkSJp7wPQ==",
+ "CPDs+We/1wvsGdaiqxzeCQ==",
+ "CQ0PPwgdG3N6Ohfwx1C8xA==",
+ "CQpJFrpOvcQhsTXIlJli+Q==",
+ "CRiL6zpjfznhGXhCIbz8pQ==",
+ "CRmAj3JcasAb4iZ9ZbNIbw==",
+ "CT3ldhWpS1SEEmPtjejR/Q==",
+ "CT9g8mKsIN/VeHLSTFJcNQ==",
+ "CUCjG2UaEBmiYWQc6+AS1Q==",
+ "CUEueo8QXRxkfVdfNIk/gg==",
+ "CWBGcRFYwZ0va6115vV/oQ==",
+ "CX/N/lHckmAtHKysYtGdZA==",
+ "CXMKIdGvm60bgfsNc+Imvg==",
+ "CYJB3qy5GalPLAv1KGFEZA==",
+ "CZNoTy26VUQirvYxSPc/5A==",
+ "CZbd+UoTz0Qu1kkCS3k8Xg==",
+ "CazLJMJjQMeHhYLwXW7YNg==",
+ "Ci7sS7Yi1+IwAM3VMAB4ew==",
+ "CiiUeJ0LeWfm7+gmEmYXtg==",
+ "CkDIoAFLlIRXra78bxT/ZA==",
+ "CkZUmKBAGu0FLpgPDrybpw==",
+ "Cl1u5nGyXaoGyDmNdt38Bw==",
+ "CmBf5qchS1V3C2mS6Rl4bw==",
+ "CmVD6nh8b/04/6JV9SovlA==",
+ "CmkmWcMK4eqPBcRbdnQvhw==",
+ "CnIwpRVC2URVfoiymnsdYQ==",
+ "CoLvjQDQGldGDqRxfQo+WQ==",
+ "CrJDgdfzOea2M2hVedTrIg==",
+ "CsPkyTZADMnKcgSuNu1qxg==",
+ "CtDj/h2Q/lRey20G8dzSgA==",
+ "CuGIxWhRLN7AalafBZLCKQ==",
+ "Cv079ZF55RnbsDT27MOQIA==",
+ "Cz1G77hsDtAjpe0WzEgQog==",
+ "CzP13PM/mNpJcJg8JD3s6w==",
+ "CzSumIcYrZlxOUwUnLR2Zw==",
+ "CzWhuxwYbNB/Ffj/uSCtbw==",
+ "D09afzGpwCEH0EgZUSmIZA==",
+ "D0Qt9sRlMaPnOv1xaq+XUg==",
+ "D0W5F7gKMljoG5rlue1jrg==",
+ "D175i+2bZ7aWa4quSSkQpA==",
+ "D2JcY4zWwqaCKebLM8lPiQ==",
+ "D31ZticrjGWAO45l5hFh7A==",
+ "D5ibbo8UJMfFZ48RffuhgQ==",
+ "D5jaV+HtXkSpSxJPmaBDXg==",
+ "D66Suu3tWBD+eurBpPXfjA==",
+ "D7piVoB2NJlBxK5owyo4+g==",
+ "D7wN7b5u5PKkMaLJBP9Ksw==",
+ "DA+3fjr7mgpwf6BZcExj0w==",
+ "DB706G73NpBSRS8TKQOVZw==",
+ "DBKrdpCE0awppxST4o/zzg==",
+ "DCjgaGV5hgSVtFY5tcwkuA==",
+ "DCvI9byhw0wOFwF1uP6xIQ==",
+ "DDitrRSvovaiXe2nfAtp4g==",
+ "DEaZD/8aWV6+zkiLSVN/gA==",
+ "DG2Qe2DqPs5MkZPOqX363Q==",
+ "DJ+a37tCaGF5OgUhG+T0NA==",
+ "DJmrmNRKARzsTCKSMLmcNA==",
+ "DJoy1NSZZw87oxWGlNHhfg==",
+ "DJscTYNFPyPmTb57g/1w+Q==",
+ "DKApp/alXiaPSRNm3MfSuA==",
+ "DLzHkTjjuH6LpWHo2ITD0Q==",
+ "DMHmyn2U2n+UXxkqdvKpnA==",
+ "DO1/jfP/xBI9N0RJNqB2Rw==",
+ "DQJRsUwO1fOuGlkgJavcwQ==",
+ "DQQB/l55iPN9XcySieNX3A==",
+ "DQeib845UqBMEl96sqsaSg==",
+ "DQlZWBgdTCoYB1tJrNS5YQ==",
+ "DRiFNojs7wM8sfkWcmLnhQ==",
+ "DWKsPfKDAtfuwgmc2dKUNg==",
+ "DY0IolKTYlW+jbKLPAlYjQ==",
+ "DYWCPUq/hpjr6puBE7KBHg==",
+ "DbWQI3H2tcJsVJThszfHGA==",
+ "DdaT4JLC7U0EkF50LzIj9w==",
+ "DdiNGiOSoIZxrMrGNvqkXw==",
+ "DinJuuBX9OKsK5fUtcaTcQ==",
+ "DjHszpS8Dgocv3oQkW/VZQ==",
+ "DjeSrUoWW2QAZOAybeLGJg==",
+ "Dk0L/lQizPEb3Qud6VHb1Q==",
+ "DmxgZsQg+Qy1GP0fPkW3VA==",
+ "Dmyb+a7/QFsU4d2cVQsxDw==",
+ "DnF6TYSJxlc+cwdfevLYng==",
+ "Do3aqbRKtmlQI2fXtSZfxQ==",
+ "DoiItHSms0B9gYmunVbRkQ==",
+ "DqzWt1gfyu/e7RQl5zWnuQ==",
+ "Dt6hvhPJu94CJpiyJ5uUkg==",
+ "Dt8Q5ORzTmpPR2Wdk0k+Aw==",
+ "DuEKxykezAvyaFO2/5ZmKQ==",
+ "Dulw855DfgIwiK7hr3X8vg==",
+ "Duz/8Ebbd0w6oHwOs0Wnwg==",
+ "DwOTyyCoUfaSShHZx9u6xg==",
+ "DwP0MQf71VsqvAbAMtC3QQ==",
+ "DwrNdmU5VFFf3TwCCcptPA==",
+ "Dz90OhYEjpaJ/pxwg1Qxhg==",
+ "E+02smwQGBIxv42LIF2Y4Q==",
+ "E1CvxFbuu9AYW604mnpGTw==",
+ "E2LR1aZ3DcdCBuVT7BhReA==",
+ "E2v8Kk60qVpQ232YzjS2ow==",
+ "E3jMjAgXwvwR8PA53g4+PQ==",
+ "E4NtzxQruLcetC23zKVIng==",
+ "E4ojRDwGsIiyuxBuXHsKBA==",
+ "E8yMPK7W0SIGTK6gIqhxiQ==",
+ "E9IlDyULLdeaVUzN6eky8g==",
+ "E9ajQQMe02gyUiW3YLjO/A==",
+ "E9yeifEZtpqlD0N3pomnGw==",
+ "EATnlYm0p3h04cLAL95JgA==",
+ "EC0+iUdSZvmIEzipXgj7Gg==",
+ "EGLOaMe6Nvzs/cmb7pNpbg==",
+ "EJgedRYsZPc4cT9rlwaZhg==",
+ "EKU3OVlT4b/8j3MTBqpMNg==",
+ "ENFfP93LA257G6pXQkmIdg==",
+ "EUXQZwLgnDG+C8qxVoBNdw==",
+ "EXveRXjzsjh8zbbQY2pM9g==",
+ "EZVQGsXTZvht1qedRLF8bQ==",
+ "EbGG4X18upaiVQmPfwKytg==",
+ "EdvIAKdRAXj7e42mMlFOGQ==",
+ "Ee4A3lTMLQ7iDQ7b8QP8Qg==",
+ "EfXDc6h69aBPE6qsB+6+Ig==",
+ "Egs14xVbRWjfBBX7X5Z60g==",
+ "Ej7W3+67kCIng3yulXGpRQ==",
+ "ElTNyMR4Rg8ApKrPw88WPg==",
+ "Epm0d/DvXkOFeM4hoPCBrg==",
+ "EqMlrz1to7HG4GIFTPaehQ==",
+ "EqYq2aVOrdX5r7hBqUJP7g==",
+ "Err1mbWJud80JNsDEmXcYg==",
+ "EuGWtIbyKToOe6DN3NkVpQ==",
+ "Ev/xjTi7akYBI7IeZJ4Igw==",
+ "EvSB+rCggob2RBeXyDQRvQ==",
+ "Ex3x5HeDPhgO2S9jjCFy4g==",
+ "EyIsYQxgFa4huyo/Lomv7g==",
+ "EzjbinBHx3Wr08eXpH3HXA==",
+ "F50iXjRo1aSTr37GQQXuJA==",
+ "F58ktE4O0f7C9HdsXYm+lw==",
+ "F5FcNti7lUa9DyF2iEpBug==",
+ "F5bs0GGWBx9eBwcJJpXbqg==",
+ "F8l+Qd9TZgzV+r8G584lKA==",
+ "F8tEIT5EhcvLNRU5f0zlXQ==",
+ "FA+nK6mpFWdD0kLFcEdhxA==",
+ "FAXzjjIr8l1nsQFPpgxM/g==",
+ "FCLQocqxxhJeleARZ6kSPg==",
+ "FH5Z60RXXUiDk+dSZBxD3g==",
+ "FHvI0IVNvih8tC7JgzvCOw==",
+ "FI2WhaSMb3guFLe3e9il8Q==",
+ "FIOCTEbzb2+KMCnEdJ7jZw==",
+ "FL/j3GJBuXdAo54JYiWklQ==",
+ "FLvED9nB9FEl9LqPn7OOrA==",
+ "FN7oLGBQGHXXn5dLnr/ElA==",
+ "FNvQqYoe0s/SogpAB7Hr1Q==",
+ "FUQySDFodnRhr+NUsWt0KA==",
+ "FV/D5uSco+Iz8L+5t7E8SA==",
+ "FWphIPZMumqnXr1glnbK4w==",
+ "FXzaxi3nAXBc8WZfFElQeA==",
+ "FbxScyuRacAQkdQ034ShTA==",
+ "FcFcn4qmPse5mJCX5yNlsA==",
+ "FcKjlHKfQAGoovtpf+DxWQ==",
+ "Fd0c8f2eykUp9GYhqOcKoA==",
+ "Fd2fYFs8vtjws2kx1gf6Rw==",
+ "FeRovookFQIsXmHXUJhGOw==",
+ "FhthAO5IkMyW4dFwpFS7RA==",
+ "Fiy3hkcGZQjNKSQP9vRqyA==",
+ "FltEN+7NKvzt+XAktHpfHA==",
+ "FnVNxl5AFH1AieYru2ZG+A==",
+ "FoJZ61VrU8i084pAuoWhDQ==",
+ "FpWDTLTDmkUhH/Sgo+g1Gg==",
+ "FpgdsQ2OG+bVEy3AeuLXFQ==",
+ "FqWLkhWl0iiD/u2cp+XK9A==",
+ "FrTgaF5YZCNkyfR1kVzTLQ==",
+ "Ft2wXUokFdUf6d2Y/lwriw==",
+ "FtxpWdhEmC6MT61qQv4DGA==",
+ "FuWspiqu5g8Eeli5Az+BkA==",
+ "FxnbKnuDct4OWcnFMT/a5w==",
+ "Fz8EI+ZpYlbcttSHs5PfpA==",
+ "FzqIpOcTsckSNHExrl+9jg==",
+ "Fzuq+Wg7clo6DTujNrxsSA==",
+ "G+sGF13VXPH4Ih6XgFEXxg==",
+ "G/PA+kt0N+jXDVKjR/054A==",
+ "G0LChrb0OE5YFqsfTpIL1Q==",
+ "G0MlFNCbRjXk4ekcPO/chQ==",
+ "G2UponGde3/Z+9b2m9abpQ==",
+ "G37U8XTFyshfCs7qzFxATg==",
+ "G3PmmPGHaWHpPW30xQgm3Q==",
+ "G4qzBI1sFP2faN+tlRL/Bw==",
+ "G736AX070whraDxChqUrqw==",
+ "G7J/za99BFbAZH+Q+/B8WA==",
+ "G8LFBop8u6IIng+gQuVg3w==",
+ "GA8k6GQ20DGduVoC+gieRA==",
+ "GCYI9Dn1h3gOuueKc7pdKA==",
+ "GDMqfhPQN0PxfJPnK1Bb9A==",
+ "GF0lY77rx1NQzAsZpFtXIQ==",
+ "GF2yvI9UWf1WY7V7HXmKPA==",
+ "GFRJoPcXlkKSvJRuBOAYHQ==",
+ "GG8a3BlwGrYIwZH9j3cnPA==",
+ "GHEdXgGWOeOa6RuPMF0xXg==",
+ "GIHKW6plyLra0BmMOurFgA==",
+ "GKzs8mlnQQc58CyOBTlfIg==",
+ "GLDNTSwygNBmuFwCIm7HtA==",
+ "GLmWLXURlUOJ+PMjpWEXVA==",
+ "GLnS9wDCje7TOMvBX9jJVA==",
+ "GNak/LFeoHWlTdLW1iU4eg==",
+ "GNrMvNXQkW7PydlyJa+f1w==",
+ "GQJxu1SoMBH14KPV/G/KrQ==",
+ "GSWncBq4nwomZCBoxCULww==",
+ "GT6WUDXiheKAM7tPg3he9A==",
+ "GTNttXfMniNhrbhn92Aykg==",
+ "GUiinC3vgBjbQC2ybMrMNQ==",
+ "GW1Uaq622QamiiF24QUA0g==",
+ "GWwJ32SZqD5wldrXUdNTLA==",
+ "GdTanUprpE3X/YjJDPpkhQ==",
+ "Gdf4VEDLBrKJNQ8qzDsIyw==",
+ "GglPoW5fvr4JSM3Zv99oiA==",
+ "GhpJfRSWZigLg/azTssyVA==",
+ "Ghuj9hAyfehmYgebBktfgA==",
+ "GmC+0rNDMIR+YbUudoNUXw==",
+ "GnJKlRzmgKN9vWyGfMq3aA==",
+ "GncGQgmWpI/fZyb/6zaFCg==",
+ "GrSbnecYAC3j5gtoKntL0A==",
+ "Gt4/MMrLBErhbFjGbiNqQQ==",
+ "GzbeM7snhe+M+J7X+gAsQw==",
+ "H+NHjk/GJDh/GaNzMQSzjg==",
+ "H+yPRiooEh5J7lAJB4RZ7Q==",
+ "H0UMAUfHFQH92A2AXRCBKA==",
+ "H1NJEI+fvOQbI51kaNQQjQ==",
+ "H1y2iXVaQYwP0SakN6sa+Q==",
+ "H1zH9I8RwfEy5DGz3z+dHw==",
+ "H6HPFAcdHFbQUNrYnB74dA==",
+ "H6j2nPbBaxHecXruxiWYkA==",
+ "HBRzLacCVYfwUVGzrefZYg==",
+ "HCbHUfsTDl6+bxPjT57lrA==",
+ "HCu4ZMrcLMZbPXbTlWuvvQ==",
+ "HDxGhvdQwGh0aLRYEGFqnw==",
+ "HEcOaEd9zCoOVbEmroSvJg==",
+ "HEghmKg3GN60K7otpeNhaA==",
+ "HFCQEiZf7/SNc+oNSkkwlA==",
+ "HFHMGgfOeO0UPrray1G+Zw==",
+ "HGxe+5/kkh6R9GXzEOOFHA==",
+ "HHxn4iIQ7m0tF1rSd+BZBg==",
+ "HI4ZIE5s8ez8Rb+Mv39FxA==",
+ "HITIVoFoWNg04NExe13dNA==",
+ "HJYgUxFZ66fRT8Ka73RaUg==",
+ "HK0yf7F97bkf1VYCrEFoWA==",
+ "HK9xG03FjgCy8vSR+hx8+Q==",
+ "HLesnV3DL+FhWF3h6RXe8g==",
+ "HLxROy6fx/mLXFTDSX4eLA==",
+ "HMQarkPWOUDIg5+5ja2dBQ==",
+ "HMWOlMmzocOIiJ7yG1YaDQ==",
+ "HOi+vsGAae4vhr+lJ5ATnQ==",
+ "HPvYV94ufwiNHEImu4OYvQ==",
+ "HRF3WL/ue3/QlYyu7NUTrA==",
+ "HRWYX2XOdsOqYzCcqkwIyw==",
+ "HYylUirJRqLm+dkp39fSOQ==",
+ "HaHTsLzx7V3G1SFknXpGxA==",
+ "HaIRV9SNPRTPDOSX9sK/bg==",
+ "HaSc7MZphCMysTy2JbTJkw==",
+ "Hb+pdSavvJ9lUXkSVZW8Og==",
+ "HbT6W1Ssd3W7ApKzrmsbcg==",
+ "HbXv8InyZqFT7i3VrllBgg==",
+ "HdB7Se47cWjPgpJN0pZuiA==",
+ "HdXg64DBy5WcL5fRRiUVOg==",
+ "HeQbUuBM9sqfXFXRBDISSw==",
+ "HfvsiCQN/3mT0FabCU5ygQ==",
+ "HgIFX42oUdRPu7sKAXhNWg==",
+ "HhBHt5lQauNl7EZXpsDHJA==",
+ "HiAgt86AyznvbI2pnLalVQ==",
+ "HjlPM2FQWdILUXHalIhQ5w==",
+ "HjyxyL0db2hGDq2ZjwOOhg==",
+ "HkbdaMuDTPBDnt3wAn5RpQ==",
+ "Hm6MG6BXbAGURVJKWRM6ZA==",
+ "HnVfyqgJ+1xSsN4deTXcIA==",
+ "HoaBBw2aPCyhh0f5GxF+/Q==",
+ "Hs3vUOOs2TWQdQZHs+FaQQ==",
+ "Hst3yfyTB7yBUinvVzYROQ==",
+ "HtDXgMuF8PJ1haWk88S0Ew==",
+ "HuDuxs2KiGqmeyY1s1PjpQ==",
+ "HwLSUie8bzH+pOJT3XQFyg==",
+ "HxEU37uBMeiR5y8q/pM42g==",
+ "Hy1nqC40l5ItxumkIC2LAA==",
+ "I+wVQA+jpPTJ6xEsAlYucg==",
+ "I07W2eDQwe6DVsm1zHKM8A==",
+ "I5qDndyelK4Njv4YrX7S6w==",
+ "I9KNZC1tijiG1T72C4cVqQ==",
+ "IA1jmtfpYkz/E2wD0+27WA==",
+ "IADk81pIu8NIL/+9Fi94pA==",
+ "IAMInfSYb76GxDlAr1dsTg==",
+ "ICPdBCdONUqPwD5BXU5lrw==",
+ "IEz72W2/W8xBx5aCobUFOQ==",
+ "IHhyR6+5sZXTH+/NrghIPg==",
+ "IHyIeMad23fSDisblwyfpA==",
+ "IKgNa2oPaFVGYnOsL+GC5Q==",
+ "INNBBin5ePwTyhPIyndHHg==",
+ "IPLD9nT5EEYG9ioaSIYuuA==",
+ "ITYL3tDwddEdWSD6J6ULaA==",
+ "ITZ3P47ALS0JguFms6/cDA==",
+ "IUZ5aGpkJ9rLgSg6oAmMlw==",
+ "IUwVHH6+8/0c+nOrjclOWA==",
+ "IWZnTJ3Hb9qw9HAK/M9gTw==",
+ "IYIP2UBRyWetVfYLRsi1SQ==",
+ "IYIbEaErHoFBn8sTT9ICIQ==",
+ "IbN736G1Px5bsYqE5gW1JQ==",
+ "IdadoCPmSgHDHzn1zyf8Jw==",
+ "IdmcpJXyVDajzeiGZixhSA==",
+ "IhHyHbHGyQS+VawxteLP0w==",
+ "IhpXs1TK7itQ3uTzZPRP5Q==",
+ "IindlAnepkazs5DssBCPhA==",
+ "IjmLaf3stWDAwvjzNbJpQA==",
+ "Ily2MKoFI1zr5LxBy93EmQ==",
+ "Iqszlv4R49UevjGxIPMhIA==",
+ "IrDuBrVu1HWm0BthAHyOLQ==",
+ "Is3uxoSNqoIo5I15z6Z2UQ==",
+ "IshzWega6zr3979khNVFQQ==",
+ "It+K/RCYMOfNrDZxo7lbcA==",
+ "IwLbkL33z+LdTjaFYh93kg==",
+ "IwfeA6d0cT4nDTCCRhK+pA==",
+ "J/PNYu4y6ZMWFFXsAhaoow==",
+ "J/eAtAPswMELIj8K2ai+Xg==",
+ "J0NauydfKsACUUEpMhQg8A==",
+ "J1nYqJ7tIQK1+a/3sMXI/Q==",
+ "J2NFyb8cXEpZyxWDthYQiA==",
+ "J4MC9He6oqjOWsYQh9nl3Q==",
+ "J8v2f6hWFu8oLuwhOeoQjA==",
+ "JATLdpQm//SQnkyCfI5x7Q==",
+ "JBkbaBiorCtFq9M9lSUdMg==",
+ "JC8Q+8yOJ52NvtVeyHo68w==",
+ "JFFeXsFsMA59iNtZey7LAA==",
+ "JFHutgSe1/SlcYKIbNNYwQ==",
+ "JFi6N1PlrpKaYECOnI7GFg==",
+ "JGEy6VP3sz3LHiyT2UwNHQ==",
+ "JGeqHRQpf4No74aCs+YTfA==",
+ "JGx8sTyvr4bLREIhSqpFkw==",
+ "JHBjKpCgSgrNNACZW1W+1w==",
+ "JIC8R48jGVqro6wmG2KXIw==",
+ "JJJkp1TpuDx5wrua2Wml7g==",
+ "JJbzQ/trOeqQomsKXKwUpQ==",
+ "JKg64m6mU7C/CkTwVn4ASg==",
+ "JKmZqz9cUnj6eTsWnFaB0A==",
+ "JKphO0UYjFqcbPr6EeBuqg==",
+ "JLq/DrW2f26NaRwfpDXIEA==",
+ "JPxEncA4IkfBDvpjHsQzig==",
+ "JQf9UmutPh3tAnu7FDk3nA==",
+ "JSr/lqDej81xqUvd/O2s7w==",
+ "JSyhTcHLTfzHsPrxJyiVrA==",
+ "JSyq2MIuObPnEgEUDyALjQ==",
+ "JVSLiwurnCelNBiG2nflpQ==",
+ "JXCYeWjFqcdSf6QwB54G+A==",
+ "JYJvOZ4CHktLrYJyAbdOnA==",
+ "JZRjdJLgZ+S0ieWVDj8IJg==",
+ "Ja3ECL7ClwDrWMTdcSQ6Ug==",
+ "JaYQXntiyznQzrTlEeZMIw==",
+ "Jbxl8Nw1vlHO9rtu0q/Fpg==",
+ "Jcxjli2tcIAjCe+5LyvqdQ==",
+ "Je1UESovkBa9T6wS0hevLw==",
+ "JgXSPXDqaS1G9NqmJXZG0A==",
+ "JgxNrUlL8wutG04ogKFPvw==",
+ "JipruVZx4ban3Zo5nNM37g==",
+ "Jit0X0srSNFnn8Ymi1EY+g==",
+ "Jj4IrSVpqQnhFrzNvylSzA==",
+ "Jm862vBTCYbv/V4T1t46+Q==",
+ "JnE6BK0vpWIhNkaeaYNUzw==",
+ "JoATsk/aJH0UcDchFMksWA==",
+ "JquDByOmaQEpFb47ZJ4+JA==",
+ "JrKGKAKdjfAaYeQH8Y2ZRQ==",
+ "Js7g8Dr6XsnGURA4UNF0Ug==",
+ "Jt4Eg6MJn8O4Ph/K2LeSUA==",
+ "Ju4YwtPw+MKzpbC0wJsZow==",
+ "JvXTdChcE3AqMbFYTT3/wg==",
+ "JyIDGL1m/w+pQDOyyeYupA==",
+ "JyUJEnU6hJu8x2NCnGrYFw==",
+ "JzW+yhrjXW1ivKu3mUXPXg==",
+ "K1CGbMfhlhIuS0YHLG30PQ==",
+ "K1RL+tLjICBvMupe7QppIQ==",
+ "K1RgR6HR5uDEQgZ32TAFgA==",
+ "K2gk9zWGd0lJFRMQ1AjQ/Q==",
+ "K3NBEG8jJTJbSrYSOC3FKw==",
+ "K4VS+DDkTdBblG93l2eNkA==",
+ "K4yZNVoqHjXNhrZzz2gTew==",
+ "K5lhaAIZkGeP5rH2ebSJFw==",
+ "K8PVQhEJCEH1ghwOdztjRw==",
+ "K9A87aMlJC8XB9LuFM913g==",
+ "KCJJfgLe00+tjSfP6EBcUg==",
+ "KGI/cXVz6v6CfL8H6akcUQ==",
+ "KI7tQFYW38zYHOzkKp9/lQ==",
+ "KO2XVYyNZadcQv8aCNn5JA==",
+ "KOm8PTa+ICgDrgK9QxCJZw==",
+ "KOmdvm+wJuZ/nT/o1+xOuw==",
+ "KPh6TwYpspne4KZA6NyMbw==",
+ "KQw25X4LnQ9is+qdqfxo0w==",
+ "KR401XBdgCrtVDSaXqPEiA==",
+ "KSorNz/PLR/YYkxaj1fuqw==",
+ "KSumhnbKxMXQDkZIpDSWmQ==",
+ "KTjwL+qswa+Bid8xLdjMTg==",
+ "KXuFON8tMBizNkCC48ICLA==",
+ "KXvdjZ3rRKn60djPTCENGA==",
+ "KYuUNrkTvjUWQovw9dNakA==",
+ "Kh/J1NpDBGoyDU+Mrnnxkg==",
+ "KhUT2buOXavGCpcDOcbOYg==",
+ "KhrIIHfqXl9zGE9aGrkRVg==",
+ "Kj1QI+s9261S3lTtPKd9eg==",
+ "KjfL7YyVqmCJGBGDFdJ0gw==",
+ "KjnL3x+56r3M2pDj1pPihA==",
+ "KkXlgPJPen6HLxbNn5llBw==",
+ "KkwQL0DeUM3nPFfHb2ej+A==",
+ "KlY5TGg0pR/57TVX+ik1KQ==",
+ "KmcGEE0pacQ/HDUgjlt7Pg==",
+ "KodYHHN62zESrXUye7M01g==",
+ "Koiog/hpN7ew5kgJbty34A==",
+ "Kt6BTG1zdeBZ3nlVk+BZKQ==",
+ "KuNY8qAJBce+yUIluW8AYw==",
+ "KujFdhhgB9q4oJfjYMSsLg==",
+ "KyLQxi5UP+qOiyZl0PoHNQ==",
+ "KzWdWPP2gH0DoMYV4ndJRg==",
+ "Kzs+/IZJO8v4uIv9mlyJ2Q==",
+ "L+N/6geuokiLPPSDXM9Qkg==",
+ "L2D7G0btrwxl9V4dP3XM5Q==",
+ "L2IeUnATZHqOPcrnW2APbA==",
+ "L2RofFWDO0fVgSz4D2mtdw==",
+ "L3Jt5dHQpWQk74IAuDOL8g==",
+ "L4+C6I7ausPl6JbIbmozAg==",
+ "LATQEY7f47i77M6p11wjWA==",
+ "LCj4hI520tA685Sscq6uLw==",
+ "LCvz/h9hbouXCmdWDPGWqg==",
+ "LDuBcL5r3PUuzKKZ9x6Kfw==",
+ "LEVYAE54618FrlXkDN01Kw==",
+ "LFcpCtnSnsCPD2gT/RA+Zg==",
+ "LGwcvetzQ3QqKjNh5vA8vw==",
+ "LHQETSI5zsejvDaPpsO29g==",
+ "LJeLdqmriyAQp+QjZGFkdQ==",
+ "LJtRcR70ug6UHiuqbT6NGw==",
+ "LKyOFgUKKGUU/PxpFYMILw==",
+ "LMCZqd3UoF/kHHwzTdj7Tw==",
+ "LMEtzh0+J27+4zORfcjITw==",
+ "LPYFDbTEp5nGtG6uO8epSw==",
+ "LQttmX92SI94+hDNVd8Gtw==",
+ "LSN9GmT6LUHlCAMFqpuPIA==",
+ "LUWxfy4lfgB5wUrqCOUisw==",
+ "LWWfRqgtph1XrpxF4N64TA==",
+ "LWd0+N3M94n81qd346LfJQ==",
+ "LZAKplVoNjeQgfaHqkyEJA==",
+ "La0gzdbDyXUq6YAXeKPuJA==",
+ "LawT9ZygiVtBk0XJ+KkQgQ==",
+ "LbPp1oL0t3K2BAlIN+l8DA==",
+ "LblwOqNiciHmt2NXjd89tg==",
+ "LcF0OqPWrcpHby8RwXz1Yg==",
+ "LcoJBEPTlSsQwfuoKQUxEw==",
+ "LhqRc9oewY4XaaXTcnXIHQ==",
+ "Lo1xTCEWSxVuIGEbBEkVxA==",
+ "LoUv/f2lcWpjftzpdivMww==",
+ "LpoayYsTO8WLFLCSh2kf2w==",
+ "Lqel4GdU0ZkfoJVXI5WC/Q==",
+ "LqgzKxbI6WTMz0AMIDJR5w==",
+ "LsmsPokAwWNCuC74MaqFCQ==",
+ "Lt/pVD4TFRoiikmgAxEWEw==",
+ "Lu02ic/E94s42A14m7NGCA==",
+ "LyPXOoOPMieqINtX8C9Zag==",
+ "LyYPOZKm8bBegMr5NTSBfg==",
+ "M/cQja3uIk1im9++brbBOA==",
+ "M0ESOGwJ4WZ4Ons1ljP0bQ==",
+ "M20iX2sUfw5SXaZLZYlTaA==",
+ "M2JMnViESVHTZaru6LDM6w==",
+ "M2suCoFHJ5fh9oKEpUG3xA==",
+ "M55eersiJuN9v61r8DoAjQ==",
+ "M98hjSxCwvZ27aBaJTGozQ==",
+ "M9oqlPb63e0kZE0zWOm+JQ==",
+ "MArbGuIAGnw4+fw6mZIxaw==",
+ "MBjMU/17AXBK0tqyARZP5w==",
+ "MFeXfNZy6Q9wBfZmPQy3xg==",
+ "MI+HSMRh8KTW+Afiaxd/Fw==",
+ "MJ1FuK8PXcmnBAG9meU84A==",
+ "MK7AqlJIGqK2+K5mCvMXRQ==",
+ "ML7ipnY/g8mA1PUIju1j8Q==",
+ "MLHt6Ak288G0RGhCVaOeqA==",
+ "MLlVniZ08FHAS5xe+ZKRaA==",
+ "MMaegl2Md9s/wOx5o9564w==",
+ "MN94B0r5CNAF9sl3Kccdbw==",
+ "MOrAbuJTyGKPC6MgYJlx5Q==",
+ "MQYM3BT77i35LG9HcqxY2Q==",
+ "MQvAr+OOfnYnr/Il/2Ubkg==",
+ "MUkRa/PjeWMhbCTq43g6Aw==",
+ "MVoxyIA+emaulH8Oks8Weg==",
+ "MWcV03ULc0vSt/pFPYPvFA==",
+ "MbI04HlTGCoc/6WDejwtaQ==",
+ "MdvhC1cuXqni/0mtQlSOCw==",
+ "MeKXnEfxeuQu9t3r/qWvcw==",
+ "MfkyURTBfkNZwB+wZKjP4g==",
+ "Mj87ajJ/yR41XwAbFzJbcA==",
+ "Ml3mi1lGS1IspHp3dYYClg==",
+ "MlKWxeEh8404vXenBLq4bw==",
+ "MlOOZOwcRGIkifaktEq0aQ==",
+ "MnStiFQAr3QlaRZ02SYGaQ==",
+ "Mofqu40zMRrlcGRLS42eBw==",
+ "MpAwWMt7bcs4eL7hCSLudQ==",
+ "MqqDg9Iyt4k3vYVW5F+LDw==",
+ "Mr5mCtC53+wwmwujOU/fWw==",
+ "MrbEUlTagbesBNg0OemHpw==",
+ "MrxR3cJaDHp0t3jQNThEyg==",
+ "MsCloSmTFoBpm7XWYb+ueQ==",
+ "Muf2Eafcf9G3U2ZvQ9OgtQ==",
+ "MvMbvZNKbXFe2XdN+HtnpQ==",
+ "N+K1ibXAOyMWdfYctNDSZQ==",
+ "N/HgDydvaXuJvTCBhG/KtA==",
+ "N2KovXW14hN/6+iWa1Yv3g==",
+ "N2X7KWekNN+fMmwyXgKD5w==",
+ "N3YDSkBUqSmrmNvZZx4a1Q==",
+ "N4/mQFyhDpPzmihjFJJn6w==",
+ "N65PqIWiQeS082D6qpfrAg==",
+ "N7fHwb397tuQHtBz1P80ZQ==",
+ "N8dXCawxSBX40fgRRSDqlQ==",
+ "N9nD7BGEM7LDwWIMDB+rEQ==",
+ "NBmB/cQfS+ipERd7j9+oVg==",
+ "ND2hYtAIQGMxBF7o7+u7nQ==",
+ "ND9l4JWcncRaSLATsq0LVw==",
+ "NDZWIhhixq7NT8baJUR4VQ==",
+ "NGApiVkDSwzO45GT57GDQw==",
+ "NKGY0ANVZ0gnUtzVx1pKSw==",
+ "NKRzJndo2uXNiNppVnqy1g==",
+ "NMbAjbnuK7EkVeY3CQI5VA==",
+ "NN/ymVQNa17JOTGr6ki3eQ==",
+ "NOmu8oZc6CcKLu+Wfz2YOQ==",
+ "NQVQfN3nIg9ipHiFh4BvfQ==",
+ "NRyFx6jqO/oo9ojvbYzsAg==",
+ "NSrzwNlB0bde3ph8k6ZQcQ==",
+ "NZtcY8fIpSKPso/KA6ZfzA==",
+ "Nc5kiwXCAyjpzt43G5RF1A==",
+ "NdULoUDGhIolzw1PyYKV0A==",
+ "NdVyHoTbBhX6Umz/9vbi0g==",
+ "Ndx5LDiVyyTz/Fh3oBTgvA==",
+ "Nf9fbRHm844KZ2sqUjNgkA==",
+ "NfxVYc3RNWZwzh2RmfXpiA==",
+ "Ng5v/B9Z10TTfsDFQ/XrXQ==",
+ "NhZbSq0CjDNOAIvBHBM9zA==",
+ "NiQ/m4DZXUbpca9aZdzWAw==",
+ "NiawWuMBDo0Q3P2xK/vnLQ==",
+ "NjeDgQ1nzH1XGRnLNqCmSg==",
+ "NmQrsmb8PVP05qnSulPe5Q==",
+ "NmWmDxwK5FpKlZbo0Rt8RA==",
+ "NoX8lkY+kd2GPuGjp+s0tQ==",
+ "NquRbPn8fFQhBrUCQeRRoQ==",
+ "Nr4zGo5VUrjXbI8Lr4YVWQ==",
+ "Nsd+DfRX6L54xs+iWeMjCQ==",
+ "NtwqUO3SKZE/9MXLbTJo/g==",
+ "NuBYjwlxadAH+vLWYRZ3bg==",
+ "NvkR0inSzAdetpI4SOXGhw==",
+ "NvurnIHin4O+wNP7MnrZ1w==",
+ "NxSdT2+MUkQN49pyNO2bJw==",
+ "NyF+4VRog7etp90B9FuEjA==",
+ "O/EizzJSuFY8MpusBRn7Tg==",
+ "O1ckWUwuhD44MswpaD6/rw==",
+ "O209ftgvu0vSr0UZywRFXA==",
+ "O538ibsrI4gkE5tfwjxjmg==",
+ "O5N2yd+QQggPBinQ+zIhtQ==",
+ "O7JiE0bbp583G6ZWRGBcfw==",
+ "O839JUrR+JS30/nOp428QA==",
+ "OChiB4BzcRE8Qxilu6TgJg==",
+ "OEJ40VmMDYzc2ESEMontRA==",
+ "OERGn45uzfDfglzFFn6JAg==",
+ "OFLn4wun6lq484I7f6yEwg==",
+ "OGpsXRHlaN8BvZftxh1e7A==",
+ "OHJBT2SEv5b5NxBpiAf7oQ==",
+ "OIwtfdq37eQ0qoXuB2j7Hw==",
+ "OMO4pqzfcbQ11YO4nkTXfg==",
+ "OONAvFS/kmH7+vPhAGTNSg==",
+ "OOS6wQCJsXH8CsWEidB35A==",
+ "OVHqwV8oQMC5KSMzd5VemA==",
+ "OaNpzwshdHUZMphQXa6i8w==",
+ "Oc3BqTF3ZBW3xE0QsnFn/A==",
+ "OlpA9HsF8MBh7b45WZSSlg==",
+ "OlwHO6Sg2zIwsCOCRu0HiQ==",
+ "Omi2ZB9kdR1HrVP2nueQkA==",
+ "Omr+zPWVucPCSfkgOzLmSQ==",
+ "OnmvXbyT2BYsSDJYZhLScA==",
+ "OpC/sL320wl5anx6AVEL+A==",
+ "OpL+vHwPasW30s2E1TYgpA==",
+ "OrqJKjRndcZ8OjE3cSQv7g==",
+ "Otz/PgYOEZ1CQDW54FWJIQ==",
+ "OwArFF1hpdBupCkanpwT+Q==",
+ "OwIGvTh8FPFqa4ijNkguAw==",
+ "Owg8qCpjZa+PmbhZew6/sw==",
+ "OzFRv+PzPqTNmOnvZGoo5g==",
+ "OzH7jTcyeM7RPVFtBdakpQ==",
+ "OzMR5D2LriC5yrVd5hchnA==",
+ "P0Pc8owrqt6spdf7FgBFSw==",
+ "P14k+fyz0TG9yIPdojp52w==",
+ "P3y5MoXrkRTSLhCdLlnc4A==",
+ "P430CeF2MDkuq11YdjvV8A==",
+ "P5WPQc5NOaK7WQiRtFabkw==",
+ "P5fucOJhtcRIoElFJS4ffg==",
+ "P5wS+xB8srW4a5KDp/JVkA==",
+ "P7eMlOz9YUcJO+pJy0Kpkw==",
+ "P8lUiLFoL100c9YSQWYqDA==",
+ "PAlx9+U+yQCAc5Fi0BOG0w==",
+ "PBULPuFXb6V3Di713n3Gug==",
+ "PCOGl7GIqbizAKj/sZmlwQ==",
+ "PD+yHtJxZJ2XEvjIPIJHsQ==",
+ "PF0lpolQQXlpc3qTLMBk8w==",
+ "PHwJ5ZAqqftZ4ypr8H1qiQ==",
+ "PKtXc4x4DEjM45dnmPWzyg==",
+ "PMCWKgog/G+GFZcIruSONw==",
+ "PMvG4NqJP76kMRAup6TSZA==",
+ "PPa7BDMpRdxJdBxkuWCxKA==",
+ "PTAm/jGkie7OlgVOvPKpaA==",
+ "PTW+fhZq/ErxHqpM0DZwHQ==",
+ "PXC6ZpdMH0ATis/jGW12iA==",
+ "PaROi5U16Tk35p0EKX5JpA==",
+ "ParhxI6RtLETBSwB0vwChQ==",
+ "PbDVq2Iw1eeM8c2o/XYdTA==",
+ "PbnxuVerGwHyshkumqAARg==",
+ "Pc+u0MAzp4lndTz4m6oQ5w==",
+ "PcdBtV8pfKU0YbDpsjPgwg==",
+ "PcoVtZrS1x1Q+6nfm4f80w==",
+ "PdBgXFq5mBqNxgCiqaRnkw==",
+ "PeJS+mXnAA6jQ0WxybRQ8w==",
+ "PfkWkSbAxIt1Iso0znW0+Q==",
+ "PggVPQL5YKqSU/1asihcrg==",
+ "PibGJQNw7VHPTgqeCzGUGA==",
+ "Po0lhBfiMaXhl+vYh1D8gA==",
+ "PolhKCedOsplEcaX4hQ0YQ==",
+ "Pp1ZMxJ8yajdbfKM4HAQxA==",
+ "PqLCd/pwc+q5GkL6MB0jTg==",
+ "Pt3i49uweYVgWze3OjkjJA==",
+ "Pu9pEf+Tek3J+3jmQNqrKw==",
+ "Pv9FWQEDLKnG/9K9EIz4Gw==",
+ "PwvPBc+4L73xK22S9kTrdA==",
+ "PxReytUUn/BbxYTFMu1r2Q==",
+ "PybPZhJErbRTuAafrrkb3g==",
+ "Q0TJZxpn3jk67L7N+YDaNA==",
+ "Q1pdQadt12anX1QRmU2Y/A==",
+ "Q3TpCE+wnmH/1h/EPWsBtQ==",
+ "Q4bfQslDSqU64MOQbBQEUw==",
+ "Q6vGRQiNwoyz7bDETGvi5g==",
+ "Q7Df6zGwvb4rC+EtIKfaSw==",
+ "Q7teXmTHAC5qBy+t7ugf0w==",
+ "Q8RVI/kRbKuXa8HAQD7zUA==",
+ "QAz7FA+jpz9GgLvwdoNTEQ==",
+ "QCpzCTReHxGm5lcLsgwPCA==",
+ "QGYFMpkv37CS2wmyp42ppg==",
+ "QH36wzyIhh6I56Vnx79hRA==",
+ "QH3lAwOYBAJ0Fd5pULAZqw==",
+ "QIKjir/ppRyS63BwUcHWmw==",
+ "QJEbr3+42P9yiAfrekKdRQ==",
+ "QTz21WkhpPjfK8YoBrpo+w==",
+ "QV0OG5bpjrjku4AzDvp9yw==",
+ "QVwuN66yPajcjiRnVk/V8g==",
+ "QWURrsEgxbJ8MWcaRmOWqw==",
+ "Qc+XYy2qyWJ5VVwd2PExbw==",
+ "Qf7JFJJuuacSzl6djUT2EQ==",
+ "Qg1ubGl+orphvT990e5ZPA==",
+ "QiozlNcQCbqXtwItWExqJQ==",
+ "QmSBVvdk0tqH9RAicXq2zA==",
+ "QmcURiMzmVeUNaYPSOtTTg==",
+ "QoUC9nyK1BAzoUVnBLV2zw==",
+ "QoqHzpHDHTwQD5UF30NruQ==",
+ "QozQL0DTtr+PXNKifv6l6g==",
+ "Qrh7OEHjp80IW+YzQwzlJg==",
+ "QsquNcCZL9wv7oZFqm64vQ==",
+ "QtD35QhE8sAccPrDnhtQmQ==",
+ "Qv6wWP4PpycDGxe7EZNSCw==",
+ "QvYZxsLdu+3nV/WhY1DsYg==",
+ "Qx6rVv9Xj8CBjqikWI9KFA==",
+ "QyyiJ5I/OZC50o89fa5EmQ==",
+ "R+beucURp/H5jLs4kW6wmg==",
+ "R/y6+JJP8rzz1KITJ4qWBw==",
+ "R1TCCfgltnXBvt5AiUnCtQ==",
+ "R2OOV18CV/YpWL1xzr/VQg==",
+ "R2Use39If2C0FVBP7KDerA==",
+ "R36O31Pj8jn0AWSuqI7X2Q==",
+ "R3ijnutzvK6IKV3AKHQZSA==",
+ "R5oOM58zdbVxFSDQnNWqeA==",
+ "R6Me6sSGP5xpNI8R0xGOWw==",
+ "R6cO8GzYfOGTIi773jtkXw==",
+ "R81DX/5a7DYKkS4CU+TL+w==",
+ "R8FxgXWKBpEVbnl41+tWEw==",
+ "R8ULpSNu9FcCwXZM0QedSg==",
+ "R906Kxp2VFVR3VD+o6Vxcw==",
+ "R97chlspND/sE9/HMScXjQ==",
+ "RAAw14BA1ws5Wu/rU7oegw==",
+ "RAECgYZmcF4WxcFcZ4A0Ww==",
+ "RBMv0IxXEO3o7MnV47Bzow==",
+ "RClzwwKh51rbB4ekl99EZA==",
+ "RDgGGxTtcPvRg/5KRRlz4w==",
+ "REnDNe9mGfqVGZt+GdsmjQ==",
+ "RHKCMAqrPjvUYt13BVcmvw==",
+ "RHToSGASrwEmvzjX6VPvNQ==",
+ "RIVYGO2smx9rmRoDVYMPXw==",
+ "RIZYDgXqsIdTf9o2Tp/S7g==",
+ "RJJqFMeiCZHdsqs72J17MQ==",
+ "RKVDdE1AkILTFndYWi9wFg==",
+ "RM5CpIiB94Sqxi462G7caA==",
+ "RNK9G1hfuz3ETY/RmA9+aA==",
+ "RNdyt6ZRGvwYG5Ws3QTuEA==",
+ "ROSt+NlEoiPFtpRqKtDUrQ==",
+ "RQOlmzHwQKFpafKPJj0D8w==",
+ "RQywrOLZEKw9+kG6qTzr3g==",
+ "RUmhye56tQu9xXs4SRJpOQ==",
+ "RVD3Ij6sRwwxTUDAxwELtA==",
+ "RWI0HfpP7643OSEZR8kxzw==",
+ "RYkDwwng6eeffPHxt8iD9A==",
+ "RZTpYKxOAH9JgF1QFGN+hw==",
+ "RfSwpO/ywQx4lfgeYlBr2w==",
+ "RgtwfY5pTolKrUGT+6Pp6g==",
+ "RhcqXY4OsZlVVF7ZlkTeRw==",
+ "RiahBXX2JbPzt8baPiP/8g==",
+ "RkQK9S1ezo+dFYHQP57qrw==",
+ "RlNPyhgYOIn28R4vKCVtYA==",
+ "RnOXOygwJFqrD+DlM3R5Ew==",
+ "RnxOYPSQdHS6fw4KkDJtrA==",
+ "RppDe/WGt1Ed6Vqg1+cCkQ==",
+ "RqYpA5AY7mKPaSxoQfI1CA==",
+ "RrE3B3X/SJi3CqCUlTYwaw==",
+ "Rrq0ak9YexLqqbSD4SSXlw==",
+ "Rs8deApkoosIJSfX7NXtAA==",
+ "RuLeQHP1wHsxhdmYMcgtrQ==",
+ "RvXWAFwM+mUAPW1MjPBaHA==",
+ "Rvchz/xjcY9uKiDAkRBMmA==",
+ "Rww3qkF3kWSd+AaMT0kfdw==",
+ "RxmdoO8ak8y/HzMSIm+yBQ==",
+ "Ry3zgZ6KHrpNyb7+Tt2Pkw==",
+ "RzeH+G3gvuK1z+nJGYqARQ==",
+ "S+b37XhKRm8cDwRb1gSsKQ==",
+ "S2MAIYeDQeJ1pl9vhtYtUg==",
+ "S3VQa6DH+BdlSrxT/g6B5g==",
+ "S47hklz3Ow+n5aY6+qsCoA==",
+ "S4RvORcJ3m6WhnAgV4YfYA==",
+ "S4rFuiKLFKZ+cL7ldiTwpg==",
+ "S7Vjy/gOWp0HozPP1RUOZw==",
+ "S8jlvuYuankCnvIvMVMzmg==",
+ "S9L29U2P5K8wNW+sWbiH7w==",
+ "SCO9nQncEcyVXGCtx30Jdg==",
+ "SChDh/Np1HyTPWfICfE1uA==",
+ "SDi5+FoP9bMyKYp+vVv1XA==",
+ "SEGu+cSbeeeZg4xWwsSErQ==",
+ "SEIZhyguLoyH7So0p1KY0A==",
+ "SESKbGF35rjO64gktmLTWA==",
+ "SElc2+YVi3afE1eG1MI7dQ==",
+ "SFn78uklZfMtKoz2N0xDaQ==",
+ "SIuKH/Qediq0TyvqUF93HQ==",
+ "SM7E98MyViSSS9G0Pwzwyw==",
+ "SNPYH4r/J9vpciGN2ybP5Q==",
+ "SOdpdrk2ayeyv0xWdNuy9g==",
+ "SPGpjEJrpflv1hF0qsFlPw==",
+ "SPHU6ES1WVm0Mu2LB+YjrA==",
+ "SSKhl2L3Mvy93DcZulADtA==",
+ "SUAwMWLMml8uGqagz5oqhQ==",
+ "SVFbcjXbV7HRg+7jUrzpwg==",
+ "SVLHWPCCH7GPVCF7QApPbw==",
+ "SVuEYfQ9FGyVMo1672n0Yg==",
+ "SbMjjI8/P8B9a9H2G0wHEQ==",
+ "Scto+9TWxj1eZgvNKo+a9A==",
+ "SfwnYZCKP1iUJyU1yq4eKg==",
+ "SiSlasZ+6U2IZYogqr2UPg==",
+ "Slu3z535ijcs5kzDnR7kfA==",
+ "SmRWEzqddY9ucGAP5jXjAg==",
+ "Sr9c0ReRpkDYGAiqSy683g==",
+ "Srl4HivgHMxMOUHyM3jvNw==",
+ "StDtLMlCI75g4XC59mESEQ==",
+ "StoXC7TBzyRViPzytAlzyQ==",
+ "StpQm/cQF8cT0LFzKUhC5w==",
+ "SusSOsWNoAerAIMBVWHtfA==",
+ "Swjn3YkWgj0uxbZ1Idtk+A==",
+ "SzCGM8ypE58FLaR1+1ccxQ==",
+ "Szko0IPE7RX2+mfsWczrMg==",
+ "T/6gSz2HwWJDFIVrmcm8Ug==",
+ "T1pMWdoNDpIsHF8nKuOn2A==",
+ "T6LA+daQqRI38iDKZTdg1A==",
+ "T7waQc3PvTFr0yWGKmFQdQ==",
+ "T9WoUJNwp8h4Yydixbx6nA==",
+ "TA9WjiLAFgJubLN4StPwLw==",
+ "TAD0Lk95CD86vbwrcRogaQ==",
+ "TBQpcKq2huNC5OmI2wzRQw==",
+ "TDrq23VUdzEU/8L5i8jRJQ==",
+ "TGB+FIzzKnouLh5bAiVOQg==",
+ "THfzE2G2NVKKfO+A2TjeFw==",
+ "THs1r8ZEPChSGrrhrNTlsA==",
+ "TI90EuS/bHq/CAlX32UFXg==",
+ "TIKadc6FAaRWSQUg5OATgg==",
+ "TIWSM78m0RprwgPGK/e0JA==",
+ "TLJbasOoVO435E5NE5JDcA==",
+ "TNyvLixb03aP2f8cDozzfA==",
+ "TSGL3iQYUgVg/O9SBKP9EA==",
+ "TSPFvkgw6uLsJh66Ou0H9w==",
+ "TVlHoi8J7sOZ2Ti7Dm92cQ==",
+ "TXab/hqNGWaSK+fXAoB2bg==",
+ "TYlnrwgyeZoRgOpBYneRAg==",
+ "TZ3ATPOFjNqFGSKY3vP2Hw==",
+ "TZT86wXfzFffjt0f95UF5w==",
+ "TafM7nTE5d+tBpRCsb8TjQ==",
+ "TahqPgS7kEg+y6Df0HBASw==",
+ "TcFinyBrUoAEcLzWdFymow==",
+ "TcGhAJHRr7eMwGeFgpFBhg==",
+ "TcyyXrSsQsnz0gJ36w4Dxw==",
+ "TeBGJCqSqbzvljIh9viAqA==",
+ "TfHvdbl2M4deg65QKBTPng==",
+ "TfNHjSTV8w6Pg6+FaGlxvA==",
+ "TgWe70YalDPyyUz6n88ujg==",
+ "Tk5MAqd1gyHpkYi8ErlbWg==",
+ "TlJizlASbPtShZhkPww4UA==",
+ "Tm4zk2Lmg8w4ITMI31NfTA==",
+ "Tmx0suRHzlUK4FdBivwOwA==",
+ "Tp52d1NndiC9w3crFqFm9g==",
+ "TrLmfgwaNATh24eSrOT+pw==",
+ "TrWS+reCJ0vbrDNT5HDR9w==",
+ "Tu6w6DtX2RJJ3Ym3o3QAWw==",
+ "TuaG3wRdM9BWKAxh2UmAsg==",
+ "Tud+AMyuFkWYYZ73yoJGpQ==",
+ "Tug3eh+28ttyf+U7jfpg5w==",
+ "U+bB5NjFIuQr/Y5UpXHwxA==",
+ "U+oTpcjhc0E+6UjP11OE/Q==",
+ "U0KmEI6e5zJkaI4YJyA5Ew==",
+ "U49SfOBeqQV9wzsNkboi8Q==",
+ "U6VQghxOXsydh3Naa5Nz4A==",
+ "U9kE50Wq5/EHO03c5hE4Ug==",
+ "UAqf4owQ+EmrE45hBcUMEw==",
+ "UEMwF4kwgIGxGT4jrBhMPQ==",
+ "UHpge5Bldt9oPGo2oxnYvQ==",
+ "UIXytIHyVODxlrg+eQoARA==",
+ "UK+R+hAoVeZ4xvsoZjdWpw==",
+ "UNRlg6+CYVOt68NwgufGNA==",
+ "UNdKik7Vy23LjjPzEdzNsg==",
+ "UNt7CNMtltJWq8giDciGyA==",
+ "UP7NXAE0uxHRXUAWPhto0w==",
+ "UP9mmAKzeQqGhod7NCqzhg==",
+ "UPYR575ASaBSZIR3aX1IgQ==",
+ "UPzS4LR3p/h0u69+7YemrQ==",
+ "UQTQk5rrs6lEb1a+nkLwfg==",
+ "USCvrMEm/Wqeu9oX6FrgcQ==",
+ "USq1iF90eUv41QBebs3bhw==",
+ "UTmTgvl+vGiCDQpLXyVgOg==",
+ "UVEZPoH9cysC+17MKHFraw==",
+ "UXUNYEOffgW3AdBs7zTMFA==",
+ "UZoibx+y1YJy/uRSa9Oa2w==",
+ "Ua6aO6HwM+rY4sPR19CNFA==",
+ "UbABE6ECnjB+9YvblE9CYw==",
+ "UbSFw5jtyLk5MealqJw++A==",
+ "Ugt8HVC/aUzyWpiHd0gCOQ==",
+ "UgvtdE2eBZBUCAJG/6c0og==",
+ "Uh1mvZNGehK1AaI4a1auKQ==",
+ "Uje3Ild84sN41JEg3PEHDg==",
+ "UjmDFO7uzjl4RZDPeMeNyg==",
+ "Um1ftRBycvb+363a90Osog==",
+ "Umd+5fTcxa3mzRFDL9Z8Ww==",
+ "Uo+FIhw1mfjF6/M8cE1c/Q==",
+ "Uo1ebgsOxc3eDRds1ah3ag==",
+ "UreSZCIdDgloih8KLeX7gg==",
+ "UtLYUlQJ02oKcjNR3l+ktg==",
+ "Uudn69Kcv2CGz2FbfJSSEA==",
+ "UvC1WADanMrhT+gPp/yVqA==",
+ "Uw6Iw+TP9ZdZGm2b/DAmkg==",
+ "UwqBVd4Wfias4ElOjk2BzQ==",
+ "Uy4QI8D2y1bq/HDNItCtAw==",
+ "UymZUnEEQWVnLDdRemv+Tw==",
+ "UzPPFSXgeV7KW4CN5GIQXA==",
+ "V+QzdKh5gxTPp2yPC9ZNEg==",
+ "V/xG5QFyx1pihimKmAo8ZA==",
+ "V1fvtnJ0L3sluj9nI5KzRw==",
+ "V2P75JFB4Se9h7TCUMfeNA==",
+ "V5HEaY3v9agOhsbYOAZgJA==",
+ "V5HKdaTHjA8IzvHNd9C51g==",
+ "V6CRKrKezPwsRdbm0DJ2Yg==",
+ "V6zyoX6MERIybGhhULnZiw==",
+ "V7eji28JSg3vTi30BCS7gw==",
+ "V8m51xgUgywRoV6BGKUrgg==",
+ "V8q+xz4ljszLZMrOMOngug==",
+ "V9G1we3DOIQGKXjjPqIppQ==",
+ "V9vkAanK+Pkc4FGAokJsTA==",
+ "VAg/aU5nl72O+cdNuPRO4g==",
+ "VCL3xfPVCL5RjihQM59fgg==",
+ "VE4sLM5bKlLdk85sslxiLQ==",
+ "VGRCSrgGTkBNb8sve0fYnQ==",
+ "VH70dN82yPCRctmAHMfCig==",
+ "VI8pgqBZeGWNaxkuqQVe7g==",
+ "VIC7inSiqzM6v9VqtXDyCw==",
+ "VIkS30v268x+M1GCcq/A8A==",
+ "VJt2kPVBLEBpGpgvuv1oUw==",
+ "VK95g27ws2C6J2h/7rC2qA==",
+ "VOB+9Bcfu8aHKGdNO0iMRw==",
+ "VOvrzqiZ1EHw+ZzzTWtpsw==",
+ "VPa7DG6v7KnzMvtJPb88LQ==",
+ "VPqyIomYm7HbK5biVDvlpw==",
+ "VQIpquUqmeyt/q6OgxzduQ==",
+ "VRnx+kd6VdxChwsfbo1oeQ==",
+ "VUDsc9RMS1fSM43c+Jo9dQ==",
+ "VWNDBOtjiiI4uVNntOlu/A==",
+ "VWb8U4jF/Ic0+wpoXi/y/g==",
+ "VWy9lB5t4fNCp4O/4n8S4w==",
+ "VX+cVXV8p9i5EBTMoiQOQQ==",
+ "VXu4ARjq7DS2IR/gT24Pfw==",
+ "VZX1FnyC8NS2k3W+RGQm4g==",
+ "VaJc9vtYlqJbRPGb5Tf0ow==",
+ "VbCoGr8apEcN7xfdaVwVXw==",
+ "VbHoWmtiiPdABvkbt+3XKQ==",
+ "Vg2E5qEDfC+QxZTZDCu9yQ==",
+ "VhYGC8KYe5Up+UJ2OTLKUw==",
+ "Vik8tGNxO0xfdV0pFmmFDw==",
+ "ViweSJuNWbx5Lc49ETEs/A==",
+ "VjclDY8HN4fSpB263jsEiQ==",
+ "VllbOAjeW3Dpbj5lp2OSmA==",
+ "VoPth5hDHhkQcrQTxHXbuw==",
+ "VpmBstwR7qPVqPgKYQTA3g==",
+ "VsXEBIaMkVftkxt1kIh7TA==",
+ "Vu0E+IJXBnc25x4n41kQig==",
+ "VzQ1NwNv9btxUzxwVqvHQg==",
+ "VznvTPAAwAev+yhl9oZT0w==",
+ "W+M4BcYNmjj7xAximDGWsA==",
+ "W/0s1x3Qm+wN8DhROk6FrQ==",
+ "W/5ThNLu43uT1O+fg0Fzwg==",
+ "W04GeDh+Tk/I1S85KlozRA==",
+ "W2x0SBzSIsTRgyWUCOZ/lg==",
+ "W4CfeVp9mXgk04flryL7iA==",
+ "W4utAK3ws0zjiba/3i91YA==",
+ "W5now3RWSzzMDAxsHSl++Q==",
+ "W8bATujVUT80v2XGJTKXDg==",
+ "W8y32OLHihfeV0XFw7LmOg==",
+ "WADmxH7R6B4LR+W6HqQQ6A==",
+ "WBu0gJmmjVdVbjDmQOkU6w==",
+ "WGKFTWJac8uehn3N59yHJw==",
+ "WHutPin+uUEqtrA7L8878A==",
+ "WKehT4nGF2T7aKuzABDMlA==",
+ "WLsh3UF4WXdHwgnbKEwRlQ==",
+ "WLwpjgr9KzevuogoHZaVUw==",
+ "WN7lFJfw4lSnTCcbmt5nsg==",
+ "WNfDNaWUOqABQ6c6kR+eyw==",
+ "WQMffxULFKJ+bun6NrCURA==",
+ "WQznrwqvMhUlM3CzmbhAOQ==",
+ "WRjYdKdtnd1G9e/vFXCt0g==",
+ "WRoJMO0BCJyn5V6qnpUi4Q==",
+ "WTr3q/gDkmB4Zyj7Ly20+w==",
+ "WVhfn2yJZ43qCTu0TVWJwA==",
+ "WWN44lbUnEdHmxSfMCZc6w==",
+ "WY7mCUGvpXrC8gkBB46euw==",
+ "WbAdlac/PhYUq7J2+n5f+w==",
+ "Wd0dOs7eIMqW5wnILTQBtg==",
+ "WdCWezJU4JK43EOZ9YHVdg==",
+ "Wf2olJCYZRGTTZxZoBePuQ==",
+ "WjDqf1LyFyhdd8qkwWk+MA==",
+ "WkSJpxBa45XJRWWZFee7hw==",
+ "Wn+Vj4eiWx0WPUHr3nFbyA==",
+ "WnHK5ZQDR6Da5cGODXeo0A==",
+ "WrJMOuXSLKKzgmIDALkyNw==",
+ "WtT0QAERZSiIt2SFDiAizg==",
+ "WwraoO97OTalvavjUsqhxQ==",
+ "Wx9jh/teM0LJHrvTScssyQ==",
+ "WyCFB4+6lVtlzu3ExHAGbQ==",
+ "WzjvUJ4jZAEK7sBqw+m07A==",
+ "X/Gha4Ajjm/GStp/tv+Jvw==",
+ "X1PaCfEDScclLtOTiF5JUw==",
+ "X2Tawm2Cra6H7WtXi1Z4Qw==",
+ "X2YfnPXgF2VHVX95ZcBaxQ==",
+ "X4hrgqMIcApsjA9qOWBoCw==",
+ "X4kdXUuhcUqMSduqhfLpxA==",
+ "X4o0OkTz0ec70mzgwRfltA==",
+ "X6Ln4si8G5aKar52ZH/FEQ==",
+ "X6ulLp4noBgefQTsbuIbYQ==",
+ "X9QAaNjgiOeAWSphrGtyVw==",
+ "XA2hUgq3GVPpxtRYiqnclg==",
+ "XAq/C+XyR6m3uzzLlMWO5Q==",
+ "XEwOJG24eaEtAuBWtMxhwg==",
+ "XF/yncdoT4ruPeXCxEhl9Q==",
+ "XGAXhUFjORwKmAq9gGEcRg==",
+ "XHHEg/8KZioW/4/wgSEkbQ==",
+ "XHjrTLXkm/bBY/BewmJcCQ==",
+ "XJihma9zSRrXLC+T+VcFDA==",
+ "XLq/nWX8lQqjxsK9jlCqUg==",
+ "XOG1PYgqoG8gVLIbVLTQgg==",
+ "XSb71ae0v+yDxNF5HJXGbQ==",
+ "XTCcsVfEvqxnjc0K5PLcyw==",
+ "XV13yK0QypJXmgI+dj4KYw==",
+ "XV5MYe0Q7YMtoBD6/iMdSw==",
+ "XVVy3e6dTnO3HpgD6BtwQw==",
+ "XXFr0WUuGsH5nXPas7hR3Q==",
+ "Xconi1dtldH90Wou9swggw==",
+ "XddlSluOH6VkR7spFIFmdQ==",
+ "XdkxmYYooeDKzy7PXVigBQ==",
+ "XePy/hhnQwHXFeXUQQ55Vg==",
+ "XfBOCJwi2dezYzLe316ivw==",
+ "XfY+QUriCAA1+3QAsswdgg==",
+ "XgPHx2+ULpm14IOZU2lrDg==",
+ "XjjrIpsmATV/lyln4tPb+g==",
+ "Xo8ZjXOIoXlBjFCGdlPuZw==",
+ "XpGXh76RDgXC4qnTCsnNHA==",
+ "XqFSbgvgZn0CpaZoZiRauQ==",
+ "XqTK/2QuGWj50tGmiDxysA==",
+ "XqUO7ULEYhDOuT/I2J8BOA==",
+ "XqW7UBTobbV4lt1yfh0LZw==",
+ "XrFDomoH2qFjQ2jJ2yp9lA==",
+ "XsF7R12agx/KkRWl0TyXRA==",
+ "Xv0mNYedaBc57RrcbHr9OA==",
+ "XwKWd03sAz8MmvJEuN08xA==",
+ "Y1Nm3omeWX2MXaCjDDYnWQ==",
+ "Y1flEyZZAYxauMo4cmtJ1w==",
+ "Y26jxXvl79RcffH8O8b9Ew==",
+ "Y5KKN7t/v9JSxG/m1GMPSA==",
+ "Y5XR8Igvau/h+c1pRgKayg==",
+ "Y5iDQySR2c3MK7RPMCgSrw==",
+ "Y78dviyBS3Jq9zoRD5sZtQ==",
+ "Y7OofF9eUvp7qlpgdrzvkg==",
+ "Y7XpxIwsGK3Lm/7jX/rRmg==",
+ "Y7iDCWYrO1coopM3RZWIPg==",
+ "YA+zdEC+yEgFWRIgS1Eiqw==",
+ "YA0kMTJ82PYuLA4pkn4rfw==",
+ "YHM6NNHjmodv+G0mRLK7kw==",
+ "YK+q7uJObkQZvOwQ9hplMg==",
+ "YLz+HA6qIneP+4naavq44Q==",
+ "YNqIHCmBp/EbCgaPKJ7phw==",
+ "YPgMthbpcBN2CMkugV60hQ==",
+ "YVlRQHQglkbj3J2nHiP/Hw==",
+ "YXHQ3JI9+oca8pc/jMH6mA==",
+ "YZ39RIXpeLAhyMgmW2vfkQ==",
+ "YZt6HwCvdI5DRQqndA/hBQ==",
+ "YaUKOTyByjUvp1XaoLiW5Q==",
+ "YfbfE3WyYOW7083Y8sGfwQ==",
+ "YgVpC5d5V6K/BpOD663yQA==",
+ "YhLEPsi/TNyeUJw69SPYzQ==",
+ "Yig+Wh18VIqdsmwtwfoUQw==",
+ "Yjm5tSq1ejZn3aWqqysNvA==",
+ "YmaksRzoU+OwlpiEaBDYaQ==",
+ "YmjZJyNfHN5FaTL/HAm8ww==",
+ "YodhkayN5wsgPZEYN7/KNA==",
+ "YrEP9z2WPQ8l7TY1qWncDA==",
+ "YtZ8CYfnIpMd2FFA5fJ+1Q==",
+ "Yw4ztKv6yqxK9U1L0noFXg==",
+ "Yy2pPhITTmkEwoudXizHqQ==",
+ "YzTV0esAxBFVls3e0qRsnA==",
+ "Z+bsbVP91KrJvxrujBLrrQ==",
+ "Z0sjccxzKylgEiPCFBqPSA==",
+ "Z2MkqmpQXdlctCTCUDPyzw==",
+ "Z2rwGmVEMCY6nCfHO3qOzw==",
+ "Z5B+uOmPZbpbFWHpI9WhPw==",
+ "Z8T1b9RsUWf59D06MUrXCQ==",
+ "Z9bDWIgcq6XwMoU2ECDR5Q==",
+ "ZAQHWU6RMg4IadOxuaukyw==",
+ "ZCdad3AwhVArttapWFwT/Q==",
+ "ZH5Es/4lJ+D5KEkF1BVSGg==",
+ "ZIZx4MehWTVXPN9cVQBmyA==",
+ "ZItMIn1vhGqAlpDHclg0Ig==",
+ "ZJY+hujfd58mTKTdsmHoQQ==",
+ "ZJc7GV0Yb6MrXkpDVIuc8g==",
+ "ZKXxq9yr7NGBOHidht34uQ==",
+ "ZKeTDCboOgCptrjSfgu0xw==",
+ "ZKvox7BaQg4/p5jIX69Umw==",
+ "ZNrjP1fLdQpGykFXoLBNPw==",
+ "ZQ0ZnTsZKWxbRj7Tilh24Q==",
+ "ZQSDYgpsimK+lYGdXBWE/w==",
+ "ZRWyfXyXqAaOEjkzWl949Q==",
+ "ZRnR6i+5WKMRfs3BDRBCJg==",
+ "ZSmN8mmI9lDEHkJqBBg0Nw==",
+ "ZV8mEgJweIYk0/l0BFKetA==",
+ "ZVnErH1Si4u51QoT0OT7pA==",
+ "ZWXfE3uGU91WpPMGyknmqw==",
+ "ZXeMG5eqQpZO/SGKC4WQkA==",
+ "ZYW30FfgwHmW6nAbUGmwzA==",
+ "ZZImGypBWwYOAW43xDRWCQ==",
+ "ZaPsR9X77SNt7dLjMJUh8A==",
+ "ZbLVNTQSVZQWTNgC4ZGfQg==",
+ "ZcuIvc8fDI+2uF0I0uLiVA==",
+ "ZfRlID+pC1Rr4IY14jolMw==",
+ "ZgdpqFrVGiaHkh9o3rDszg==",
+ "ZgjifTVKmxOieco81gnccQ==",
+ "ZiJ/kJ9GneF3TIEm08lfvQ==",
+ "ZlBNHAiYsfaEEiPQ1z+rCA==",
+ "ZlOAnCLV1PkR0kb3E+Nfuw==",
+ "ZmVpw1TUVuT13Zw/MNI5hQ==",
+ "ZmblZauRqO5tGysY3/0kDw==",
+ "ZoNSxARrRiKZF5Wvpg7bew==",
+ "Zqd6+81TwYuiIgLrToFOTQ==",
+ "ZqjnqxZE/BjOUY0CMdVl0g==",
+ "ZqkmoGB0p5uT5J6XBGh7Tw==",
+ "ZrCezGLz38xKmzAom6yCTQ==",
+ "ZrCnZB/U/vcqEtI1cSvnww==",
+ "ZtWvgitOSRDWq7LAKYYd4Q==",
+ "ZtmnX24AwYAXHb2ZDC6MeQ==",
+ "ZuayB6IpbeITokKGVi9R5w==",
+ "ZvvxwDd0I6MsYd7aobjLUA==",
+ "ZyDh3vCQWzS5DI1zSasXWA==",
+ "ZybIEGf1Rn/26vlHmuMxhw==",
+ "ZydKlOpn2ySBW0G3uAqwuw==",
+ "ZygAjaN62XhW5smlLkks+Q==",
+ "Zyo0fzewcqXiKe2mAwKx5g==",
+ "ZyoaR1cMiKAsElmYZqKjLA==",
+ "Zz/5VMbw1TqwazReplvsEg==",
+ "ZzT5b0dYQXkQHTXySpWEaA==",
+ "ZzduJxTnXLD9EPKMn1LI4Q==",
+ "a/Y6IAVFv0ykRs9WD+ming==",
+ "a1aL8zQ+ie3YPogE3hyFFg==",
+ "a4EYNljinYTx9vb1VvUA6A==",
+ "a4rPqbDWiMivVzaRxvAj7g==",
+ "a5gZ5uuRrXEAjgaoh7PXAg==",
+ "a6IszND1m+6w+W+CvseC7g==",
+ "a6vem8n6WmRZAalDrHNP0g==",
+ "a7Pv1SOWYnkhIUC22dhdDA==",
+ "aD4QvtMlr8Lk/zZgZ6zIMg==",
+ "aEnHUfn7UE/Euh6jsMuZ7g==",
+ "aFJuE/s+Kbge4ppn+wulkA==",
+ "aIPde9CtyZrhbHLK740bfw==",
+ "aJFbBhYtMbTyMFBFIz/dTA==",
+ "aK9nybtiIBUvxgs1iQFgsw==",
+ "aLY2pCT0WfFO5EJyinLpPg==",
+ "aLh1XEUrfR9W82gzusKcOg==",
+ "aMa1yVA71/w6Uf1Szc9rMA==",
+ "aMmrAzoRWLOMPHhBuxczKg==",
+ "aN5x46Gw1VihRalwCt1CGg==",
+ "aOeJZUIZM9YWjIEokFPnzQ==",
+ "aRpdnrOyu5mWB1P5YMbvOA==",
+ "aRrcmH+Ud3mF1vEXcpEm4w==",
+ "aTWiWjyeSDVY/q8y9xc2zg==",
+ "aWZRql2IUPVe9hS3dxgVfQ==",
+ "aXqiibI6BpW3qilV6izHaQ==",
+ "aXrbsro7KLV8s4I4NMi4Eg==",
+ "aXs9qTEXLTkN956ch3pnOA==",
+ "aY6B28XdPnuYnbOy9uSP8A==",
+ "adJAjAFyR2ne1puEgRiH+g==",
+ "adT+OjEB2kqpeYi4kQ6FPg==",
+ "afMd/Hr3rYz/l7a3CfdDjg==",
+ "ahAbmGJZvUOXrcK6OydNGQ==",
+ "alJtvTAD7dH/zss/Ek1DMQ==",
+ "alqHQBz8V446EdzuVfeY5Q==",
+ "anyANMnNkUqr3JuPJz5Qzw==",
+ "apWEPWUvMC24Y+2vTSLXoA==",
+ "aqcOby9QyEbizPsgO3g0yw==",
+ "ash1r2J6B0PUxJe8P0otVQ==",
+ "asouSfUjJa8yfMG7BBe+fA==",
+ "auvG6kWMnhCMi7c7e9eHrw==",
+ "avFTp3rS6z5zxQUZQuaBHQ==",
+ "avZp5K7zJvRvJvpLSldNAw==",
+ "aw4CzX8pYbPVMuNrGCEcWg==",
+ "axEl7xXt/bwlvxKhI7hx4g==",
+ "ayBGGPEy++biljvGcwIjXA==",
+ "aySnrShOW4/xRSzl/dtSKQ==",
+ "ays5/F7JANIgPHN0vp2dqQ==",
+ "b06KGv5zDYsTxyTbQ9/eyA==",
+ "b0vZfEyuTja2JYMa20Rtbg==",
+ "b16O4LF7sVqB7aLU2f3F1A==",
+ "b3BQG9/9qDNC/bNSTBY/sQ==",
+ "b3q8kjHJPj9DWrz3yNgwjQ==",
+ "b4BoZmzVErvuynxirLxn0w==",
+ "b4aFwwcWMXsSdgS1AdFOXA==",
+ "b53qqLnrTBthRXmmnuXWvw==",
+ "b6rrRA0W247O+FfvDHbVCQ==",
+ "b85nxzs8xiHxaqezuDVWvg==",
+ "b8BZV1NfBdLi70ir4vYvZg==",
+ "bA2kaTpeXflTElTnQRp6GQ==",
+ "bBEndaOStXBpAK79FrgHaw==",
+ "bG+P+p34t/IJ1ubRiWg6IA==",
+ "bGGUhiG9SqJMHQWitXTcYQ==",
+ "bIk7Fa6SW7X18hfDjTKowg==",
+ "bJ1cZW7KsXmoLw0BcoppJg==",
+ "bJgsuw29cO2WozqsGZxl7w==",
+ "bK045TkBlz+/3+6n6Qwvrg==",
+ "bL2FuwsPT7a7oserJQnPcw==",
+ "bLEntCrCHFy9pg3T3gbBzg==",
+ "bLd38ZNkVeuhf0joEAxnBQ==",
+ "bLsStF0DDebpO+xulqGNtg==",
+ "bMWFvjM8eVezU1ZXKmdgqw==",
+ "bMb1ia0rElr2ZpZVhva0Jw==",
+ "bNDKcFu8T5Y6OoLSV+o/Sw==",
+ "bNq/hj0Cjt4lkLQeVxDVdQ==",
+ "bO55S58bqDiRWXSAIUGJKw==",
+ "bPRX2zl+K1S0iWAWUn1DZw==",
+ "bQ7J5mebp38rfP/fuqQOsg==",
+ "bQKkL+/KUCsAXlwwIH0N3w==",
+ "bTNRjJm+FfSQVfd56nNNqQ==",
+ "bUF0JIfS4uKd3JZj2xotLQ==",
+ "bUxQBaqKyvlSHcuRL9whjg==",
+ "bV9r7j2kNJpDCEM5E2339Q==",
+ "bWwtTFlhO3xEh/pdw0uWaQ==",
+ "bb/U8UynPHwczew/hxLQxw==",
+ "bbBsi6tXMVWyq3SDVTIXUg==",
+ "beSrliUu0BOadCWmx+yZyA==",
+ "bfUD03N2PRDT+MZ+WFVtow==",
+ "bhVbgJ4Do4v56D9mBuR/EA==",
+ "birqO8GOwGEI97zYaHyAuw==",
+ "bjLZ7ot/X/vWSVx4EYwMCg==",
+ "bkRdUHAksJZGzE1gugizYQ==",
+ "blygTgAHZJ3NzyAT33Bfww==",
+ "bs2QG8yYWxPzhtyMqO6u3A==",
+ "bsHIShcLS134C+dTxFQHyA==",
+ "bvbMJZMHScwjJALxEyGIyg==",
+ "bvyB6OEwhwCIfJ6KRhjnRw==",
+ "bz294kSG4egZnH2dJ8HwEg==",
+ "bzVeU2qM9zHuzf7cVIsSZw==",
+ "bzXXzQGZs8ustv0K4leklA==",
+ "c1wbFbN7AdUERO/xVPJlgw==",
+ "c3WVxyC5ZFtzGeQlH5Gw+w==",
+ "c5Tc7rTFXNJqYyc0ppW+Iw==",
+ "c5q/8n7Oeffv3B1snHM/lA==",
+ "c5ymZKqx/td1MiS2ERiz9A==",
+ "c6Yhwy/q3j7skXq52l36Ww==",
+ "cBBOQn7ZjxDku0CUrxq2ng==",
+ "cFFE2R4GztNoftYkqalqUQ==",
+ "cHSj5dpQ04h/WyefjABfmQ==",
+ "cHkOsVd80Rgwepeweq4S1g==",
+ "cLR0Ry4/N5swqga1R6QDMw==",
+ "cMo6l1EQESx1rIo+R4Vogg==",
+ "cNsC9bH30eM1EZS6IdEdtQ==",
+ "cSHSg9xJz/3F6kc+hKXkwg==",
+ "cT3PwwS6ALZA/na9NjtdzA==",
+ "cTvDd8okNUx0RCMer6O8sw==",
+ "cUyqCa7Oue934riyC17F8g==",
+ "cVhdRFuZaW/09CYPmtNv5g==",
+ "cWUg7AfqhiiEmBIu+ryImA==",
+ "cWdlhVZD7NWHUGte24tMjg==",
+ "cXpfd6Io6Glj2/QzrDMCvA==",
+ "ca+kx+kf7JuZ3pfYKDwFlg==",
+ "caepyBOAFu0MxbcXrGf6TA==",
+ "catI+QUNk3uJ+mUBY3bY8Q==",
+ "cbBXgB1WQ/i8Xul0bYY2fg==",
+ "ccK42Lm8Tsv73YMVZRwL6A==",
+ "cchuqe+CWCJpoakjHLvUfA==",
+ "ccmy4GVuX967KaQyycmO0w==",
+ "ccy3Ke2k4+evIw0agHlh3w==",
+ "cdWUm6uLNzR/knuj2x75eA==",
+ "cffrYrBX3UQhfX1TbAF+GQ==",
+ "cfh5VZFmIqJH/bKboDvtlA==",
+ "cgSEbLqqvDsNUyeA3ryJ6Q==",
+ "chwv4+xbEAa93PHg8q9zgQ==",
+ "ck86G8HsbXflyrK7MBntLg==",
+ "ckugAisBNX18eQz+EnEjjw==",
+ "cl4t9FXabQg7tbh1g7a0OA==",
+ "coGEgMVs2b314qrXMjNumQ==",
+ "cszpMdGbsbe6BygqMlnC9Q==",
+ "ctJYJegZhG42i+vnPFWAWw==",
+ "cu4ZluwohhfIYLkWp72pqA==",
+ "cuQslgfqD2VOMhAdnApHrA==",
+ "cvMJ714elj/HUh89a9lzOQ==",
+ "cvOg7N4DmTM+ok1NBLyBiQ==",
+ "cvZT1pvNbIL8TWg+SoTZdA==",
+ "cvrGmub2LoJ+FaM5HTPt9A==",
+ "cw1gBLtxH/m4H7dSM7yvFg==",
+ "cwBNvZc0u4bGABo88YUsVQ==",
+ "cxpZ4bloGv734LBf4NpVhA==",
+ "cxqHS4UbPolcYUwMMzgoOA==",
+ "czBWiYsQtNFrksWwoQxlOw==",
+ "d+ctfXU0j07rpRRzb5/HDA==",
+ "d/Wd3Ma1xYyoMByPQnA9Cw==",
+ "d0NBFiwGlQNclKObRtGVMQ==",
+ "d0VAZLbLcDUgLgIfT1GmVQ==",
+ "d0qvm3bl38rRCpYdWqolCQ==",
+ "d13Rj3NJdcat0K/kxlHLFw==",
+ "dAq8/1JSQf1f4QPLUitp0g==",
+ "dCDaYYrgASXPMGFRV0RCGg==",
+ "dChBe9QR29ObPFu/9PusLg==",
+ "dFSavcNwGd8OaLUdWq3sng==",
+ "dFetwmFw+D6bPMAZodUMZQ==",
+ "dG98w8MynOoX7aWmkvt+jg==",
+ "dGjcKAOGBd4gIjJq7fL+qQ==",
+ "dGrf9SWJ13+eWS6BtmKCNw==",
+ "dJHKDkfMFJeoULg7U4wwDQ==",
+ "dK2DU3t1ns+DWDwfBvH3SQ==",
+ "dL6n/JsK+Iq6UTbQuo/GOw==",
+ "dM9up4vKQV5LeX82j//1jQ==",
+ "dMRx4Mf6LrN64tiJuyWmDw==",
+ "dNTU+/2DdZyGGTdc+3KMhQ==",
+ "dNq2InSVDGnYXjkxPNPRxA==",
+ "dOS+mVCy3rFX9FvpkTxGXA==",
+ "dRFCIbVu0Y8XbjG5i+UFCQ==",
+ "dTMoNd6DDr1Tu8tuZWLudw==",
+ "dUx1REyXKiDFAABooqrKEA==",
+ "dVh/XMTUIx1nYN4q1iH1bA==",
+ "dXDPnL1ggEoBqR13aaW9HA==",
+ "dZg5w8rFETMp9SgW7m0gfg==",
+ "dZgMquvZmfLqP4EcFaWCiA==",
+ "daBhAvmE9shDgmciDAC5eg==",
+ "dhTevyxTYAuKbdLWhG47Kw==",
+ "dihDsG7+6aocG6M9BWrCzQ==",
+ "dmAfbd9F0OJHRAhNMEkRsA==",
+ "dml2gqLPsKpbIZ93zTXwCQ==",
+ "dnvatwSEcl73ROwcZ4bbIQ==",
+ "dpSTNOCPFHN5yGoMpl1EUA==",
+ "dqVw2q2nhCvTcW82MT7z0g==",
+ "drfODfDI6GyMW7hzkmzQvA==",
+ "dsueq9eygFXILDC7ZpamuA==",
+ "dtnE401dC0zRWU0S/QOTAg==",
+ "duRFqmvqF93uf/vWn8aOmg==",
+ "dxWv00FN/2Cgmgq9U3NVDQ==",
+ "e/nWuo5YalCAFKsoJmFyFA==",
+ "e2xLFVavnZIUUtxJx+qa1g==",
+ "e369ZIQjxMZJtopA//G55Q==",
+ "e4B3HmWjW+6hQzcOLru6Xg==",
+ "e5KCqQ/1GAyVMRNgQpYf6g==",
+ "e5l9ZiNWXglpw6nVCtO8JQ==",
+ "e5txnNRcGs2a9+mBFcF1Qg==",
+ "e9GqAEnk8XI5ix6kJuieNQ==",
+ "eAOEgF5N80A/oDVnlZYRAw==",
+ "eBapvE+hdyFTsZ0y5yrahg==",
+ "eC/RcoCVQBlXdE9WtcgXIw==",
+ "eCy/T+a8kXggn1L8SQwgvA==",
+ "eDWsx4isnr2xPveBOGc7Hw==",
+ "eDcyiPaB954q5cPXcuxAQw==",
+ "eFimq+LuHi42byKnBeqnZQ==",
+ "eFkXKRd2dwu/KWI5ZFpEzw==",
+ "eJDUejE/Ez/7kV+S74PDYg==",
+ "eJFIQh/TR7JriMzYiTw4Sg==",
+ "eJLrGwPRa6NgWiOrw1pA7w==",
+ "eJlcN+gJnqAnctbWSIO9uA==",
+ "eKQCVzLuzoCLcB4im8147A==",
+ "eLYKLr4labZeLiRrDJ9mnA==",
+ "ePlsM/iOMme2jEUYwi15ng==",
+ "eQ45Mvf5in9xKrP6/qjYbg==",
+ "eRwaYiog2DdlGQyaltCMJg==",
+ "eS/vTdSlMUnpmnl1PbHjyw==",
+ "eTMPXa60OTGjSPmvR4IgGw==",
+ "eV+RwWPiGEB+76bqvw+hbA==",
+ "eWgLAqJOU+fdn8raHb9HCw==",
+ "eXFOya6x5inTdGwJx/xtUQ==",
+ "eYAQWuWZX2346VMCD6s7/A==",
+ "eYE9No9sN5kUZ5ePEyS3+Q==",
+ "eddhS+FkXxiUnbPoCd5JJw==",
+ "edlXkskLx287vOBZ9+gVYg==",
+ "ehfPlu6YctzzpQmFiQDxGA==",
+ "ehwc2vvwNUAI7MxU4MWQZw==",
+ "ejfikwrSPMqEHjZAk3DMkA==",
+ "emVLJVzha7ui5OFHPJzeRQ==",
+ "enj9VEzLbmeOyYugTmdGfQ==",
+ "epY+dsm5EMoXnZCnO4WSHw==",
+ "es/L9iW8wsyLeC5S4Q8t+g==",
+ "eshD40tvOA6bXb0Fs/cH3A==",
+ "etRjRvfL/IwceY/IJ1tgzQ==",
+ "euxzbIq4vfGYoY3s1QmLcw==",
+ "evaWFoxZNQcRszIRnxqB+A==",
+ "ewPT4dM12nDWEDoRfiZZnA==",
+ "ewe/P3pJLYu/kMb5tpvVog==",
+ "ezsm4aFd6+DO9FUxz0A8Pg==",
+ "f/BjtP5fmFw2dRHgocbFlg==",
+ "f07bdNVAe9x+cAMdF1bByQ==",
+ "f09F7+1LRolRL5nZTcfKGA==",
+ "f0H/AFSx2KLZi9kVx5BAZg==",
+ "f1+fHgR5rDPsCZOzqrHM7Q==",
+ "f1Gs++Iilgq9GHukcnBG3w==",
+ "f1h+Vp+xmdZsZIziHrB2+g==",
+ "f5Xo7F1uaiM760Qbt978iw==",
+ "f6Ye5F0Lkn34uLVDCzogFQ==",
+ "f6iLrMpxKhFxIlfRsFAuew==",
+ "f9ywiGXsz+PuEsLTV3zIbQ==",
+ "fAKFfwlCOyhtdBK6yNnsNg==",
+ "fDOUzPTU2ndpbH0vgkgrJQ==",
+ "fFvXa1dbMoOOoWZdHxPGjw==",
+ "fHL+fHtDxhALZFb9W/uHuw==",
+ "fHNpW230mNib08aB7IM3XQ==",
+ "fKalNdhsyxTt1w08bv9fJA==",
+ "fM5uYpkvJFArnYiQ3MrQnA==",
+ "fO0+6TsjL+45p9mSsMRiIg==",
+ "fOARCnIg/foF/6tm7m9+3w==",
+ "fQS0jnQMnHBn7+JZWkiE/g==",
+ "fS471/rN4K2m10mUwGFuLg==",
+ "fSANOaHD0Koaqg7AoieY9A==",
+ "fU32wmMeD44UsFSqFY0wBA==",
+ "fU5ZZ1bIVsV+eXxOpGWo/Q==",
+ "fUAy3f9bAglLvZWvkO2Lug==",
+ "fVCRaPsTCKEVLkoF4y3zEw==",
+ "fW3QZyq5UixIA1mP6eWgqQ==",
+ "fX4G68hFL7DmEmjbWlCBJQ==",
+ "fY9VATklOvceDfHZDDk57A==",
+ "fZrj3wGQSt8RXv0ykJROcQ==",
+ "fbTm027Ms0/tEzbGnKZMDA==",
+ "fdqt93OrpG13KAJ5cASvkg==",
+ "fgXfRuqFfAu8qxbTi4bmhA==",
+ "fgdUFvQPb5h+Rqz8pzLsmw==",
+ "fhcbn9xE/6zobqQ2niSBgA==",
+ "fiv0DJivQeqUkrzDNlluRw==",
+ "fmC+85h5WBuk8fDEUWPjtQ==",
+ "fo3JL+2kPgDWfP+CCrFlFw==",
+ "foPAmiABJ3IXBoed2EgQXA==",
+ "foXSDEUwMhfHWJSmSejsQg==",
+ "fpXijBOM3Ai1RkmHven5Ww==",
+ "fsW2DaKYTCC7gswCT+ByQQ==",
+ "fsoXIbq0T0nmSpW8b+bj+g==",
+ "fsrX00onlGvfsuiCc35pGg==",
+ "ftsf2qztw3NC78ep/CZXWQ==",
+ "fv/PW8oexJYWf5De30fdLQ==",
+ "fvm0IQfnbfZFETg9v3z/Fg==",
+ "fxg/vQq9WPpmQsqQ4RFYaA==",
+ "fy54Milpa7KZH/zgrDmMXQ==",
+ "fzkmVWKhJsxyCwiqB/ULnQ==",
+ "g/z9yk94XaeBRFj4hqPzdw==",
+ "g0GbRp2hFVIdc7ct7Ky7ag==",
+ "g0aTR8aJ0uVy3YvGYu5xrw==",
+ "g0kHTNRI7x/lAsr92EEppw==",
+ "g0lWrzEYMntVIahC7i0O2g==",
+ "g1ELwsk6hQ+RAY1BH640Pg==",
+ "g2nh2xENCFOpHZfdEXnoQA==",
+ "g5EzTJ0KA4sO3+Opss3LMg==",
+ "g6udffWh7qUnSIo1Ldn3eA==",
+ "g6zSo8BvLuKqdmBFM1ejLA==",
+ "g8TcogVxHpw7uhgNFt5VCQ==",
+ "gAoV4BZYdW1Wm712YXOhWQ==",
+ "gB8wkuIzvuDAIhDtNT1gyA==",
+ "gBgJF0PiGEfcUnXF0RO7/w==",
+ "gC7gUwGumN7GNlWwfIOjJQ==",
+ "gDLjxT7vm07arF4SRX5/Vg==",
+ "gDxqUdxxeXDYhJk9zcrNyA==",
+ "gEHGeR2F82OgBeAlnYhRSw==",
+ "gFEnTI8os2BfRGqx9p5x8w==",
+ "gGLz3Ss+amU7y6JF09jq7A==",
+ "gICaI06E9scnisonpvqCsA==",
+ "gK7dhke5ChQzlYc/bcIkcg==",
+ "gR0sgItXIH8hE4FVs9Q07w==",
+ "gR3B8usSEb0NLos51BmJQg==",
+ "gTB2zM3RPm27mUQRXc/YRg==",
+ "gTnsH3IzALFscTZ1JkA9pw==",
+ "gU3gu8Y5CYVPqHrZmLYHbQ==",
+ "gUNP5w7ANJm257qjFxSJrA==",
+ "gW0oKhtQQ7BxozxUWw5XvQ==",
+ "gXlb7bbRqHXusTE5deolGA==",
+ "gYGQBLo5TdMyXks0LsZhsQ==",
+ "gYgCu/qUpXWryubJauuPNw==",
+ "gYnznEt9r97haD/j2Cko7g==",
+ "gYvdNJCDDQmNhtJ6NKSuTA==",
+ "gZNJ1Qq6OcnwXqc+jXzMLQ==",
+ "gZWTFt5CuLqMz6OhWL+hqQ==",
+ "gaEtlJtD6ZjF5Ftx0IFt0A==",
+ "gf1Ypna/Tt+TZ08Y+GcvGg==",
+ "gfhkPuMvjoC3CGcnOvki3Q==",
+ "gfnbviaVhKvv1UvlRGznww==",
+ "ggIfX1J4dX3xQoHnHUI7VA==",
+ "gglLMohmJDPRGMY1XKndjQ==",
+ "ghp8sWGKWw20S/z1tbTxFg==",
+ "ginkFyNVMwkZLE49AbfqfA==",
+ "gkrg0NR0iCaL7edq0vtewA==",
+ "glnqaRfwm6NxivtB2nySzw==",
+ "gnAIpoCyl3mQytLFgBEgGA==",
+ "gnez1VrH+UHT8C/SB9qGdA==",
+ "gnkadeCgjdmLdlu/AjBZJg==",
+ "goSgZ8N5UbT5NMnW3PjIlQ==",
+ "gqehq46BhFX2YLknuMv02w==",
+ "gsC/mWD8KFblxB0JxNuqJw==",
+ "gvvyX5ATi4q9NhnwxRxC8w==",
+ "gwyVIrTk5o0YMKQq4lpJ+Q==",
+ "gxwbqZDHLbQVqXjaq42BCg==",
+ "h+KRDKIvyVUBmRjv1LcCyg==",
+ "h0MH5NGFfChgmRJ3E/R3HQ==",
+ "h13Xuonj+0dD1xH86IhSyQ==",
+ "h1NNwMy0RjQmLloSw1hvdg==",
+ "h2B0ty0GobQhDnFqmKOpKQ==",
+ "h2cnQQF2/R3Mq2hWdDdrTg==",
+ "h3vYYI9yhpSZV2MQMJtwFQ==",
+ "h5HsEsObPuPFqREfynVblw==",
+ "h7Fc+eT/GuC8iWI+YTD0UQ==",
+ "hCzsi1yDv9ja5/o7t94j9Q==",
+ "hDGa2yLwNvgBd/v6mxmQaQ==",
+ "hDILjSpTLqJpiSSSGu445A==",
+ "hIABph+vhtSF5kkZQtOCTA==",
+ "hIJA+1QGuKEj+3ijniyBSQ==",
+ "hIjgi20+km+Ks23NJ4VQ6Q==",
+ "hJ8leLNuJ6DK5V8scnDaZQ==",
+ "hJSP7CostefBkJrwVEjKHA==",
+ "hK8KhTFcR06onlIJjTji/Q==",
+ "hKOsXOBoFTl/K4xE+RNHDA==",
+ "hN9bmMHfmnVBVr+7Ibd2Ng==",
+ "hNHqznsrIVRSQdII6crkww==",
+ "hP7dSa8lLn9KTE/Z0s4GVQ==",
+ "hPnPQOhz4QKhZi02KD6C+A==",
+ "hRxbdeniAVFgKUgB9Q3Y+g==",
+ "hSNZWNKUtDtMo6otkXA/DA==",
+ "hSkY45CeB6Ilvh0Io4W6cg==",
+ "hUWqqG1QwYgGC5uXJpCvJw==",
+ "hW9DJA1YCxHmVUAF7rhSmQ==",
+ "hWoxz5HhE50oYBNRoPp1JQ==",
+ "hY82j+sUQQRpCi6CCGea5A==",
+ "hZlX6qOfwxW5SPfqtRqaMw==",
+ "hdzol5dk//Q6tCm4+OndIA==",
+ "hf9HFxWRNX2ucH8FLS7ytA==",
+ "hfcH5Az2M7rp+EjtVpPwsg==",
+ "hiYg+aVzdBUDCG0CXz9kCw==",
+ "hkOBNoHbno2iNR7t3/d4vg==",
+ "hlMumZ7RJFpILuKs09ABtw==",
+ "hlu7os0KtAkpBTBV6D2jyQ==",
+ "hlvtFGW8r0PkbUAYXEM+Hw==",
+ "hnCUnoxofUiqQvrxl73M8w==",
+ "hq35Fjgvrcx6I9e6egWS4w==",
+ "hqeSvwu8eqA072iidlJBAw==",
+ "htDbVu1xGhCRd8qoMlBoMg==",
+ "htNVAogFakQkTX6GHoCVXg==",
+ "hv5GrLEIjPb4bGOi8RSO0w==",
+ "hvsZ5JmVevK1zclFYmxHaw==",
+ "hy303iin+Wm7JA6MeelwiQ==",
+ "i2sSvrTh/RdLJX0uKhbrew==",
+ "i42XumprV/aDT5R0HcmfIQ==",
+ "i6ZYpFwsyWyMJNgqUMSV1A==",
+ "i6r+mZfyhZyqlYv56o0H+w==",
+ "i8XXN7jcrmhnrOVDV8a2Hw==",
+ "i9IRqAqKjBTppsxtPB7rdw==",
+ "iANKiuMqWzrHSk9nbPe3bQ==",
+ "iCF+GWw9/YGQXsOOPAnPHQ==",
+ "iCnm5fPmSmxsIzuRK6osrA==",
+ "iFtadcw8v6betKka9yaJfg==",
+ "iGI9uqMoBBAjPszpxjZBWQ==",
+ "iGuY4VxcotHvMFXuXum7KA==",
+ "iGykaF+h4p46HhrWqL8Ffg==",
+ "iIWxFdolLcnXqIjPMg+5kQ==",
+ "iIm8c9uDotr87Aij+4vnMw==",
+ "iJ2nT8w8LuK11IXYqBK+YA==",
+ "iK0dWKHjVVexuXvMWJV9pg==",
+ "iPwX3SbbG9ez9HoHsrHbKw==",
+ "iQ304I1hmLZktA1d1cuOJA==",
+ "iS9wumBV5ktCTefFzKYfkA==",
+ "iSeH0JFSGK73F470Rhtesw==",
+ "iUsUCB0mfRsE9KPEQctIzw==",
+ "iVDd2Zk7vwmEh97LkOONpQ==",
+ "iWNlSnwrtCmVF89B+DZqOQ==",
+ "ibsb1ncaLZXAYgGkMO7tjQ==",
+ "ieEAgvK9LsWh2t6DsQOpWA==",
+ "ifZM0gBm9g9L09YlL+vXBg==",
+ "ifuJCv9ZA84Vz1FYAPsyEA==",
+ "ilBBNK/IV69xKTShvI94fQ==",
+ "imZ+mwiT22sW2M9alcUFfg==",
+ "inrUwXyKikpOW0y2Kl1wGw==",
+ "ionqS0piAOY2LeSReAz4zg==",
+ "ipPPjxpXHS1tcykXmrHPMQ==",
+ "irnD9K8bsT+up/JUrxPw6A==",
+ "iruDC5MeywV4yA8o1tw/KQ==",
+ "isep9d+Q7DEUf0W7CJJYzw==",
+ "itPtn+JaO4i7wz2wOPOmDQ==",
+ "iu5csar0IQQBOTgw5OvJwQ==",
+ "iujlt9fXcUXEYc+T2s5UjA==",
+ "iwKBOGDTFzV4aXgDGfyUkw==",
+ "izeyFvXOumNgVyLrbKW45g==",
+ "j+8/VARfbQSYhHzj0KPurQ==",
+ "j+lDhAnWAyso+1N8cm85hQ==",
+ "j4FBMnNfdBwx0VsDeTvhFg==",
+ "j8nMH8mK/0Aae7ZkqyPgdg==",
+ "j8to4gtSIRYpCogv2TESuQ==",
+ "jCgdKXsBCgf7giUKnr6paQ==",
+ "jEdanvXKyZdZJG6mj/3FWw==",
+ "jEqP0dyHKHiUjZ9dNNGTlQ==",
+ "jGHMJqbj6X1NdTDyWmXYAQ==",
+ "jHOoSl3ldFYr9YErEBnD3w==",
+ "jKJn4czwUl/6wtZklcMsSg==",
+ "jLI3XpVfjJ6IzrwOc4g9Pw==",
+ "jLkmUZ6fV56GfhC0nkh4GA==",
+ "jMZKSMP2THqwpWqJNJRWdw==",
+ "jNJQ6otieHBYIXA9LjXprg==",
+ "jNcMS2zX1iSZN9uYnb2EIg==",
+ "jOPdd330tB6+7C29a9wn0Q==",
+ "jQVlDU+HjZ2OHSDBidxX5A==",
+ "jQjyjWCEo9nWFjP4O8lehw==",
+ "jS0JuioLGAVaHdo/96JFoQ==",
+ "jTg9Y6EfpON4CRFOq0QovA==",
+ "jTmPbq+wh30+yJ/dRXk1cA==",
+ "jV/D2B11NLXZRH77sG9lBw==",
+ "jWsC7kdp2YmIZpfXGUimiA==",
+ "jZMDIu95ITTjaUX0pk4V5g==",
+ "jd6IpPJwOJW1otHKtKZ5Gw==",
+ "jdRzkUJrWxrqoyNH9paHfQ==",
+ "jdVMQqApseHH3fd91NFhxg==",
+ "jfegbZSZWkDoPulFomVntA==",
+ "jgNijyoj2JrQNSlUv4gk4A==",
+ "ji+1YHlRvzevs3q5Uw1gfA==",
+ "ji306HRiq965zb8EZD2uig==",
+ "jiV+b/1EFMnHG6J0hHpzBg==",
+ "jjNMPXbmpFNsCpWY0cv3eg==",
+ "jkUpkLoIXuu7aSH8ZghIAQ==",
+ "joDXdLpXvRjOqkRiYaD/Sw==",
+ "jon1y9yMEGfiIBjsDeeJdA==",
+ "jp5Em/0Ml4Txr1ptTUQjpg==",
+ "jpNUgFnanr9Sxvj2xbBXZw==",
+ "jpjpNjL1IKzJdGqWujhxCw==",
+ "jqPQ0aOuvOJte/ghI1RVng==",
+ "jrRH0aTUYCOpPLZwzwPRfQ==",
+ "jrfRznO0nAz6tZM1mHOKIA==",
+ "jt9Ocr9D8EwGRgrXVz//aQ==",
+ "jx7rpxbm1NaUMcE2ktg5sA==",
+ "jz7QlwxCIzysP39Cgro8jg==",
+ "k+IBS52XdOe5/hLp28ufnA==",
+ "k/Aou2Jmyh8Bu3k8/+ndsQ==",
+ "k/OVIllJvW6BefaLEPq7DA==",
+ "k/pBSWE2BvUsvJhA9Zl5uw==",
+ "k0XIjxp2vFG7sTrKcfAihA==",
+ "k1DPiH6NkOFXP/r3N12GyA==",
+ "k2KP9oPMnHmFlZO6u6tgyw==",
+ "k6OmSlaSZ5CB0i7SD9LczQ==",
+ "k8eZxqwxiN/ievXdLSEL/w==",
+ "kBAB2PSjXwqoQOXNrv80AA==",
+ "kFrRjz7Cf2KvLtz9X6oD+w==",
+ "kGeXrHEN6o7h5qJYcThCPw==",
+ "kHcBZXoxnFJ+GMwBZ/xhfQ==",
+ "kIGxCUxSlNgsKZ45Al1lWw==",
+ "kJdY3XEdJS/hyHdR+IN0GA==",
+ "kMUdiwM7WR8KGOucLK4Brw==",
+ "kNGIV3+jQmJlZDTXy1pnyA==",
+ "kRnBEH6ILR5GNSmjHYOclw==",
+ "kSUectNPXpXNg+tIveTFRw==",
+ "kTCHqcb3Cos51o8cL+MXcg==",
+ "kUhyc3G8Zvx8+q5q5nVEhw==",
+ "kUudvRfA33uJDzHIShQd3Q==",
+ "kWPUUi7x9kKKa6nJ+FDR5Q==",
+ "kZ/mZZg9YSDmk2rCGChYAg==",
+ "kZ0D191c/uv4YMG15yVLDw==",
+ "kZkmDatUOdIqs7GzH3nI1A==",
+ "ka7pMp8eSiv92WgAsz2vdA==",
+ "kcJ1acgBv6FtUhV8KuWoow==",
+ "kgKWQJJQKLUuD2VYKIKvxA==",
+ "kggaIvN2tlbZdZRI8S5Apw==",
+ "kgyUtd8MFe0tuuxDEUZA9w==",
+ "kh51WUI5TRnKhur6ZEpRTQ==",
+ "kj5WqpRCjWAfjM7ULMcuPQ==",
+ "kjWYVC7Eok2w2YT4rrI+IA==",
+ "kkbX+a00dfiTgbMI+aJpMg==",
+ "kly/2kE4/7ffbO34WTgoGg==",
+ "knYKU74onR6NkGVjQLezZg==",
+ "kq26VyDyJTH/eM6QvS2cMw==",
+ "kr8tw1+3NxoPExnAtTmfxg==",
+ "ksOFI9C7IrDNk4OP6SpPgw==",
+ "kuWGANwzNRpG4XmY7KjjNg==",
+ "kvAaIJb+aRAfKK104dxFAA==",
+ "kwlAQhR2jPMmfLTAwcmoxw==",
+ "kydoXVaNcx1peR5g6i588g==",
+ "kzGNkWh3fz27cZer4BspUQ==",
+ "kzTl7WH/JXsX1fqgnuTOgw==",
+ "kzXsrxWRnWhkA82LsLRYog==",
+ "kzYddqiMsY3EYrpxve2/CQ==",
+ "l+x2QhxG8wb5AQbcRxXlmA==",
+ "l0E0U/CJsyCVSTsXW4Fp+w==",
+ "l2NppPcweAtmA1V2CNdk2Q==",
+ "l2ZB9TvT68rn8AAN4MdxWw==",
+ "l2mAbuFF3QBIUILDODiUHQ==",
+ "l4ddTxbTCW5UmZW+KRmx6A==",
+ "l5f3I6osM9oxLRAwnUnc5A==",
+ "l6QHU5JsJExNoOnqxBPVbw==",
+ "l6Ssc04/CnsqUua9ELu2iQ==",
+ "l8/KMItWaW3n4g1Yot/rcQ==",
+ "lC5EumoIcctvxYqwELqIqw==",
+ "lFUq6PGk9dBRtUuiEW7Cug==",
+ "lHN2dn2cUKJ8ocVL3vEhUQ==",
+ "lJFPmPWcDzDp5B2S8Ad8AA==",
+ "lK2xe+OuPutp4os0ZAZx5w==",
+ "lM/EhwTsbivA7MDecaVTPw==",
+ "lMaO8Yf+6YNowGyhDkPhQA==",
+ "lMjip5hbCjkD9JQjuhewDg==",
+ "lNF8PvUIN02NattcGi5u4g==",
+ "lON3WM0uMJ30F8poBMvAjQ==",
+ "lOPJhHqCtMRFZfWMX/vFZQ==",
+ "lTE6u9G/RzvmbuAzq2J2/Q==",
+ "lV70RNlE++04G1KFB3BMXA==",
+ "lY+tivtsfvU0LJzBQ6itYQ==",
+ "lacCCRiWdquNm4YRO7FoKA==",
+ "leDlMcM+B1mDE8k5SWtUeg==",
+ "lf1fwA0YoWUZaEybE+LyMQ==",
+ "lfOLLyZNbsWQgHRhicr4ag==",
+ "lffapwUUgaQOIqLz2QPbAg==",
+ "lhAOM81Ej6YZYBu45pQYgg==",
+ "lizovLQxu6L9sbafNQuShQ==",
+ "lkl6XkrTMUpXi46dPxTPxg==",
+ "lkzFdvtBx5bV6xZO0cxK7g==",
+ "ll2M0QQzBsj5OFi02fv3Yg==",
+ "llOvGOUDVfX68jKnAlvVRA==",
+ "llujnWE17U8MIHmx4SbrSA==",
+ "lqhgbgEqROAdfzEnJ17eXA==",
+ "lsBTMnse2BgPS6wvPbe7JA==",
+ "luO1R8dUM9gy1E2lojRQoA==",
+ "luR/kvHLwA6tSdLeTM4TzA==",
+ "lwYQm2ynA3ik2gE1m11IEg==",
+ "lyfqic/AbEJbCiw+wA01FA==",
+ "lz+SeifYXxamOLs1FsFmSQ==",
+ "lzUQ1o7JAbdJYpmEqi6KnQ==",
+ "m+eh+ZqS74w2q0vejBkjaw==",
+ "m/Lp4U75AQyk9c8cX14HJg==",
+ "m06wctjNc3o7iyBHDMZs2w==",
+ "m3XYojKO+I6PXlVRUQBC3w==",
+ "m416yrrAlv+YPClGvGh+qQ==",
+ "m5JIUETVXcRza4VL4xlJbg==",
+ "m6get5wjq5j1i5abnpXuZQ==",
+ "m6srF+pMehggHB1tdoxlPg==",
+ "m9iuy4UtsjmyPzy6FTTZvw==",
+ "mAiD16zf+rCc7Qzxjd5buA==",
+ "mAzsVkijuqihhmhNTTz65g==",
+ "mDXHuOmI4ayjy2kLSHku1Q==",
+ "mI0eT4Rlr7QerMIngcu/ng==",
+ "mMLhjdWNnZ8zts9q+a2v3g==",
+ "mMfn8OaKBxtetweulho+xQ==",
+ "mNlYGAOPc6KIMW8ITyBzIg==",
+ "mNv2Q67zePjk/jbQuvkAFA==",
+ "mPk1IsU5DmDFA/Ym5+1ojw==",
+ "mPwCyD0yrIDonVi+fhXyEQ==",
+ "mS99D+CXhwyfVt8xJ+dJZA==",
+ "mSJF9dJnxZ15lTC6ilbJ2A==",
+ "mSstwJq7IkJ0JBJ5T8xDKg==",
+ "mTAqtg6oi0iytHQCaSVUsA==",
+ "mTLBkP+yGHsdk5g7zLjVUw==",
+ "mU4CqbAwpwqegxJaOz9ofQ==",
+ "mUek9NkXm8HiVhQ6YXiyzA==",
+ "mVT74Eht+gAowINoMKV7IQ==",
+ "mW6TCje9Zg2Ep7nzmDjSYQ==",
+ "mXBfDUt/sBW5OUZs2sihvw==",
+ "mXPtbPaoNAAlGmUMmJEWBQ==",
+ "mXZ4JeBwT2WJQL4a/Tm4jQ==",
+ "mXycPfF5zOvcj1p4hnikWw==",
+ "mc45FSMtzdw2PTcEBwHWPw==",
+ "md6zNd7ZBn3qArYqQz7/fw==",
+ "me61ST+JrXM5k3/a11gRAA==",
+ "meHzY9dIF7llDpFQo1gyMg==",
+ "miiOqnhtef1ODjFzMHnxjA==",
+ "mjFBVRJ7TgnJx+Q74xllPg==",
+ "mjQS8CpyGnsZIDOIEdYUxg==",
+ "mk1CKDah7EzDJEdhL22B7w==",
+ "mmRob7iyTkTLDu8ObmTPow==",
+ "mnalaO6xJucSiZ0+99r3Cg==",
+ "mpOtwBvle+nyY6lUBwTemw==",
+ "mpWNaUH9kn4WY26DWNAh3Q==",
+ "mr1qjhliRfl87wPOrJbFQg==",
+ "mrinv7KooPQPrLCNTRWCFg==",
+ "mrxlFD3FBqpSZr1kuuwxGg==",
+ "msstzxq++XO0AqNTmA7Bmg==",
+ "mxug34EekabLz0JynutfBg==",
+ "myzvc+2MfxGD9uuvZYdnqQ==",
+ "n+xYzfKmMoB3lWkdZ+D3rg==",
+ "n1M2dgFPpmaICP+JwxHUug==",
+ "n1ixvP7SfwYT3L2iWpJg6A==",
+ "n5GA+pA9mO/f4RN9NL9lNg==",
+ "n6QVaozMGniCO0PCwGQZ6w==",
+ "n7Bns42aTungqxKkRfQ5OQ==",
+ "n7KL1Kv027TSxBVwzt9qeA==",
+ "n7h9v2N1gOcvMuBEf8uThw==",
+ "nDAsSla+9XfAlQSPsXtzPA==",
+ "nE72uQToQFVLOzcu/nMjww==",
+ "nFBXCPeiwxK9mLXPScXzTA==",
+ "nFPDZGZowr3XXLmDVpo7hg==",
+ "nGzPc0kI/EduVjiK7bzM6Q==",
+ "nHTsDl0xeQPC5zNRnoa0Rw==",
+ "nHUpYmfV59fe3RWaXhPs3Q==",
+ "nL4iEd3b5v4Y9fHWDs+Lrw==",
+ "nMuMtK/Zkb3Xr34oFuX/Lg==",
+ "nNaGqigseHw30DaAhjBU3g==",
+ "nOiwBFnXxCBfPCHYITgqNg==",
+ "nR3ACzeVF5YcLX6Gj6AGyQ==",
+ "nULSbtw2dXbfVjZh33pDiA==",
+ "nUgYO7/oVNSX8fJqP2dbdg==",
+ "nVDxVhaa2o38gd1XJgE3aw==",
+ "nW3zZshjZEoM8KVJoVfnuQ==",
+ "nY/H7vThZ+dDxoPRyql+Cg==",
+ "neQoa8pvETr07blVMN3pgA==",
+ "nf8x+F03kOpMhsCSUWEhVg==",
+ "ng1Q0A7ljho3TUWWYl46sw==",
+ "nhAnHuCGXcYlqzOxrrEe1g==",
+ "nkbLVLvh3ClKED97+nH+7Q==",
+ "nkedTagkmf6YE4tEY+0fKw==",
+ "nknBKPgb7US42v8A0fTl/w==",
+ "nmD7fEU4u7/4+W/pkC4/0Q==",
+ "nqpKfidczdgrNaAyPi7BOQ==",
+ "nqtQI1bSM7DCO9P1jGV97Q==",
+ "nsnX3tKkN1elr18E31tXDw==",
+ "nvLEpj6ZZF3LWH3wUB6lKg==",
+ "nvUKoKfC6j8fz3gEDQrc/w==",
+ "nvmBgp0YlUrdZ05INsEE8Q==",
+ "nwtCsN1xEYaHvEOPzBv+qQ==",
+ "nx/U4Tode5ILux4DSR+QMg==",
+ "nxDGRpePV3H4NChn4eLwag==",
+ "nyaekSYTKzfSeSfPrB114Q==",
+ "nykEOLL/o7h0cs0yvdeT2g==",
+ "o+areESiXgSO0Lby56cBeg==",
+ "o+nYS4TqJc6XOiuUzEpC3A==",
+ "o/Y4U6rWfsUCXJ72p5CUGw==",
+ "o1uhaQg5/zfne84BFAINUQ==",
+ "o1zeXHJEKevURAAbUE/Vog==",
+ "o5XVEpdP4OXH0NEO4Yfc/A==",
+ "o64LDtKq/Fulf1PkVfFcyg==",
+ "o7y4zQXQAryST2cak4gVbw==",
+ "o9tdzmIu+3J/EYU4YWyTkA==",
+ "oAHVGBSJ2cf4dVnb/KEYmw==",
+ "oDca3JEdRb4vONT9GUUsaQ==",
+ "oFNMOKbQXcydxnp8fUNOHw==",
+ "oFanDWdePmmZN0xqwpUukA==",
+ "oGH7SMLI2/qjd9Vnhi3s0A==",
+ "oIU19xAvLJwQSZzIH577aA==",
+ "oIWwTbkVS5DDL47mY9/1KQ==",
+ "oKt57TPe4PogmsGssc3Cbg==",
+ "oLWWIn/2AbKRHnddr2og9g==",
+ "oMJLQTH1wW7LvOV0KRx/dw==",
+ "oNOI17POQCAkDwj6lJsYOA==",
+ "oONlXCW4aAqGczQ/bUllBw==",
+ "oPcxgoismve6+jXyIKK6AQ==",
+ "oPlhC4ebXdkIDazeMSn1fQ==",
+ "oQjugfjraFziga1BcwRLRA==",
+ "oR8rvIZoeoaZ/ufpo0htfQ==",
+ "oSnrpW4UmmVXtUGWqLq+tQ==",
+ "oUqO4HrBvkpSL781qAC9+w==",
+ "oVlG+0rjrg2tdFImxIeVBA==",
+ "oad5SwflzN0vfNcyEyF4EA==",
+ "obW3kzv2KBvuckU7F+tfjA==",
+ "ocRh5LR1ZIN9Johnht8fhQ==",
+ "ocpLRASvTgqfkY20YlVFHQ==",
+ "ocvA1/NbyxM0hanwwY6EiA==",
+ "odGhKtO4bDW5R8SYiI5yCg==",
+ "ogcuGHUZJkmv+vCz567a2g==",
+ "ohK6EftXOqBzIMI+5XnESw==",
+ "ojZY7Gi2QJXE/fp6Wy31iA==",
+ "ojf6uL85EuEYgLvHoGhUrw==",
+ "ojugpLIfzflgU2lonfdGxA==",
+ "ol9xhVTG9e1wNo50JdZbOA==",
+ "olTSlmirL9MFhKORiOKYkQ==",
+ "omAjyj1l6gyQAlBGfdxJTw==",
+ "onFcHOO1c3pDdfCb5N4WkQ==",
+ "oqlkgrYe9aCOwHXddxuyag==",
+ "oxoZP897lgMg/KLcZAtkAg==",
+ "oyYtf08AkWLR52bXm5+sKw==",
+ "ozVqYsmUueKifb4lDyVyrg==",
+ "p+bx+/WQWALXEBCTnIMr4w==",
+ "p/48hurJ1kh2FFPpyChzJg==",
+ "p/7qM5+Lwzw1/lIPY91YxQ==",
+ "p0eNK7zJd7D/HEGaVOrtrQ==",
+ "p2JPOX8yDQ0agG+tUyyT/g==",
+ "p3V7NfveB6cNxFW7+XQNeQ==",
+ "p48i7AfSSAyTdJSyHvOONw==",
+ "p73gSu4d+4T/ZNNkIv9Nlw==",
+ "p8W1LgFuW6JSOKjHkx3+aA==",
+ "pCQmlnn3BxhsV2GwqjRhXg==",
+ "pFKzcRHSUBqSMtkEJvrR1Q==",
+ "pGQEWJ38hb/ZYy2P1+FIuw==",
+ "pHo1O5zrCHCiLvopP2xaWw==",
+ "pHozgRyMiEmyzThtJnY4MQ==",
+ "pKaTI+TfcV3p/sxbd2e7YQ==",
+ "pT1raq2fChffFSIBX3fRiA==",
+ "pUfWmRXo70yGkUD/x5oIvA==",
+ "pVG1hL96/+hQ+58rJJy6/A==",
+ "pVgjGg4TeTNhKimyOu3AAw==",
+ "pW4gDKtVLj48gNz6V17QdA==",
+ "pZfn6IiG+V28fN8E2hawDQ==",
+ "pa8nkpAAzDKUldWjIvYMYg==",
+ "pcoBh5ic7baSD4TZWb3BSw==",
+ "pdPwUHauXOowaq9hpL2yFw==",
+ "pdaY6kZ8+QqkMOInvvACNA==",
+ "peMW+rpwmXrSwplVuB/gTA==",
+ "pfGcaa49SM3S6yJIPk/EJQ==",
+ "plXHHzA8X9QGwWzlJxhLRw==",
+ "pnJnBzAJlO4j3IRqcfmhkQ==",
+ "prCOYlboBnzmLEBG/OeVrQ==",
+ "prOsOG0adI4o+oz50moipw==",
+ "pulldyBt2sw6QDvTrCh6zw==",
+ "pv/m2mA/RJiEQu2Qyfv9RA==",
+ "pvXHwJ3dwf9GDzfDD9JI3g==",
+ "pw1jplCdTC+b0ThX0FXOjw==",
+ "pxuSWn1u+bHtRjyh2Z8veA==",
+ "pyrUqiZ98gVXxlXQNXv5fA==",
+ "pzC8Y0Vj9MPBy3YXR32z6w==",
+ "q/siBRjx6wNu+OTvpFKDwA==",
+ "q4z6A4l3nhX3smTmXr+Sig==",
+ "q5g3c8tnQTW2EjNfb2sukw==",
+ "q6LG0VzO1oxiogAAU63hyg==",
+ "q7m/EtZySBjZNBjQ5m1hKw==",
+ "q8YF9G2jqydAxSqwyyys5Q==",
+ "qA0sTaeNPNIiQbjIe1bOgQ==",
+ "qCPfJTR8ecTw6u6b1yHibA==",
+ "qE/h/Z+6buZWf+cmPdhxog==",
+ "qIFpKKwUmztsBpJgMaVvSg==",
+ "qIUJPanWmGzTD1XxvHp+6w==",
+ "qNOSm15bdkIDSc/iUr+UTQ==",
+ "qNyy6Fc0b8oOMWqqaliZ/w==",
+ "qO4HlyHMK5ygX+6HbwQe8w==",
+ "qOEIUWtGm5vx/+fg4tuazg==",
+ "qP1cCE4zsKGTPhjbcpczMw==",
+ "qQQwJ/aF87BbnLu3okXxaw==",
+ "qYHdgFAXhF/XcW4lxqfvWQ==",
+ "qYuo5vY8V3tZx41Kh9/4Dw==",
+ "qZ2q5j2gH3O56xqxkNhlIA==",
+ "qaTdVEeZ6S8NMOxfm+wOMA==",
+ "qcpeZWUlPllQYZU6mHVwUw==",
+ "qenHZKKlTUiEFv6goKM/Mw==",
+ "qkvEep4vvXhc2ZJ6R449Mg==",
+ "qngzBJbiTB4fivrdnE5gOg==",
+ "qnkFUlJ8QT322JuCI3LQgg==",
+ "qnsBdl050y9cUaWxbCczRw==",
+ "qnzWszsyJhYtx8wkMN6b1g==",
+ "qoK2keBg3hdbn7Q24kkVXg==",
+ "qpFJZqzkklby+u1UT3c1iA==",
+ "qt5CsMts2aD4lw/4Q6bHYQ==",
+ "qxALQrqHoDq9d91nU0DckA==",
+ "qyRmvxh8p4j4f+61c10ZFQ==",
+ "r/b5px/UImGNjT/X5sYjuA==",
+ "r0QffVKB9OD9yGsOtqzlhA==",
+ "r0hAwlS0mPZVfCSB+2G6uQ==",
+ "r1VGXWeqGeGbfKjigaAS+Q==",
+ "r2f2MyT+ww1g9uEBzdYI1w==",
+ "r36kVMpF+9J+sfI3GeGqow==",
+ "r3lQAYOYhwlLnDWQIunKqg==",
+ "r95wJtP5rsTExKMS7QhHcw==",
+ "rBt6L/KLT7eybxKt5wtFdg==",
+ "rCxoo4TP/+fupXMuIM0sDA==",
+ "rHagXw+CkF3uEWPWDKXvog==",
+ "rIMXaCaozDvrdpvpWvyZOQ==",
+ "rJ9qVn8/2nOxexWzqIHlcQ==",
+ "rJCuanCy51ydVD4nInf9IQ==",
+ "rKAQxu80Q8g1EEhW5Wh8tg==",
+ "rKb3TBM4EPx/RErFOFVCnQ==",
+ "rLZII1R6EGus+tYCiUtm6g==",
+ "rM/BOovNgnvebKMxZQdk7g==",
+ "rMm9bHK69h0fcMkMdGgeeA==",
+ "rOYeIcB+Rg5V6JG2k4zS2w==",
+ "rSvhrHyIlnIBlfNJqemEbw==",
+ "rTwJggSxTbwIYdp07ly0LA==",
+ "rUp5Mfc57+A8Q29SPcvH/Q==",
+ "rWliqgfZ3/uCRBOZ9sMmdA==",
+ "rXGWY/Gq+ZEsmvBHUfFMmQ==",
+ "rXSbbRABEf4Ymtda45w8Fw==",
+ "rXfWkabSPN+23Ei1bdxfmQ==",
+ "rXtGpN17Onx8LnccJnXwJQ==",
+ "rZKD8oJnIj5fSNGiccfcvA==",
+ "raKMXnnX6PFFsbloDqyVzQ==",
+ "raYifKqev8pASjjuV+UTKQ==",
+ "rcY4Ot40678ByCfqvGOGdg==",
+ "rdeftHE7gwAT67wwhCmkYQ==",
+ "rfPTskbnoh3hRJH6ZAzQRg==",
+ "rgcXxjx3pDLotH7TTfAoZw==",
+ "rh7bzsTQ1UZjG7amysr0Gg==",
+ "rhgtLQh0F9bRA6IllM7AGw==",
+ "ri4AOITPdB1YHyXV+5S51g==",
+ "rkeLYwMZ1/pW2EmIibALfA==",
+ "rlXt6zKE7DswUl0oWGOQUQ==",
+ "rqHKB91H3qVuQAm+Ym5cUA==",
+ "rqucO37p86LpzehR/asCSQ==",
+ "rs2QrN4qzAHCHhkcrAvIfA==",
+ "rtJdfki8fG6CB36CADp0QA==",
+ "rtd6mqFgGe98mqO0pFGbSw==",
+ "rueNryrchijjmWaA3kljYg==",
+ "rvE64KQGkVkbl07y7JwBqw==",
+ "rwplpbNJz0ADUHTmzAj15Q==",
+ "rwtF86ZAbWyKI6kLn4+KBw==",
+ "rxfACPLtKXbYua18l3WlUw==",
+ "rzj6mjHCcMEouL66083BAg==",
+ "s+eHg5K9zZ2Jozu5Oya9ZQ==",
+ "s/BZAhh1cTV3JCDUQsV8mA==",
+ "s2AKVTwrY65/SWqQxDGJQg==",
+ "s5+78jS4hQYrFtxqTW3g1Q==",
+ "s5RUHVRNAoKMuPR/Jkfc2Q==",
+ "s7iW1M6gkAMp+D/3jHY58w==",
+ "s8NpalwgPdHPla7Zi9FJ3w==",
+ "sBpytpE38xz0zYeT+0qc2A==",
+ "sC11Rf/mau3FG5SnON4+vQ==",
+ "sCLMrLjEUQ6P1L8tz90Kxg==",
+ "sEeblUmISi1HK4omrWuPTA==",
+ "sGLPmr568+SalaQr8SE/PA==",
+ "sLJrshdEANp0qk2xOUtTnQ==",
+ "sLdxIKap0ZfC3GpUk3gjog==",
+ "sNmW2b2Ud7dZi3qOF8O8EQ==",
+ "sQAxqWXeiu/Su0pnnXgI9A==",
+ "sQskMBELEq86o1SJGQqfzg==",
+ "sQzCwNDlRsSH7iB9cTbBcg==",
+ "sS6QcitMPdvUBLiMXkWQkw==",
+ "sWLcS+m4aWk31BiBF+vfJQ==",
+ "sXlFMSTBFnq0STHj6cS/8w==",
+ "sa2DECaqYH1z1/AFhpHi+g==",
+ "saEpnDGBSZWqeXSJm34eOA==",
+ "scCQPl0em2Zmv/RQYar60g==",
+ "sfIClgTMtZo9CM9MHaoqhQ==",
+ "sfowXUMdN2mCoBVrUzulZg==",
+ "sfte/o9vVNyida/yLvqADA==",
+ "siHwJx6EgeB1gBT9z/vTyw==",
+ "skrQRB9xbOsiSA19YgAdIQ==",
+ "snGTzo540cCqgBjxrfNpKw==",
+ "soBA65OmZdfBGJkBmY/4Iw==",
+ "spHVvA/pc7nF9Q4ON020+w==",
+ "spJI3xFUlpCDqzg0XCxopA==",
+ "sr3UXbMg5zzkRduFx/as7g==",
+ "sw+bmpzqsM4gEQtnqocQLQ==",
+ "swJhrPwllq5JORWiP5EkDA==",
+ "swsVVsPi/5aPFBGP+jmPIw==",
+ "syeBfQBUmkXNWCZ1GV8xSA==",
+ "t+bYn9UqrzKiuxAYGF7RLA==",
+ "t0WN8TwMLgi8UVEImoFXKg==",
+ "t2EkpUsLOEOsrnep0nZSmA==",
+ "t2vWMIh2BvfDSQaz5T1TZw==",
+ "t3Txxjq43e/CtQmfQTKwWg==",
+ "t5U+VMsTtlWAAWSW+00SfQ==",
+ "t5wh9JGSkQO78QoQoEqvXA==",
+ "t7HaNlXL16fVwjgSXmeOAQ==",
+ "t8pjhdyNJirkvYgWIO/eKg==",
+ "tBQDfy48FnIOZI04rxfdcA==",
+ "tFMJRXfWE9g78O1uBUxeqQ==",
+ "tFmWYH82I3zb+ymk5dhepA==",
+ "tG+rpfJBXlyGXxTmkceiKA==",
+ "tHDbi43e6k6uBgO0hA+Uiw==",
+ "tIqwBotg052wGBL65DZ+yA==",
+ "tJt6VDdAPEemBUvnoc4viA==",
+ "tOdlnsE3L3XCBDJRmb/OqA==",
+ "tOkYq1BZY152/7IJ6ZYKUg==",
+ "tU31r8zla146sqczdKXufg==",
+ "tVhXk9Ff3wAg56FbdNtcFg==",
+ "tVvWdA+JqH0HR2OlNVRoag==",
+ "tVw8U1AsslIFmQs4H1xshg==",
+ "tX8X8KoxUQ8atFSCxgwE1Q==",
+ "tXVb5f90k9l3e1oK2NGXog==",
+ "tXuu7YpZOuMLTv87NjKerA==",
+ "tY916jrSySzrL+YTcVmYKQ==",
+ "tYeIZjIm0tVEsYxH1iIiUQ==",
+ "tb5+2dmYALJibez1W4zXgA==",
+ "td7nDgTDmKPSODRusMcupw==",
+ "tdgI9v7cqJsgCAeW1Fii1A==",
+ "tdiTXKrkqxstDasT0D5BPA==",
+ "tejpAZp7y32SO2+o4OGvwQ==",
+ "tfgO55QqUyayjDfQh+Zo1Q==",
+ "tj2rWvF2Fl+XIccctj8Mhw==",
+ "tnUtJ/DQX9WaVJyTgemsUA==",
+ "tq5xUJt8GtjDIh1b48SthQ==",
+ "tr+U/vt+MIGXPRQYYWJfRg==",
+ "trjM81KANPZrg9iSThWx6Q==",
+ "tsiqwelcBAMU/HpLGBtMGw==",
+ "twPn6wTGqI0aR//0wP3xtA==",
+ "twjiDKJM7528oIu/el4Zbg==",
+ "tzV7ixFH37ze4zuLILTlfA==",
+ "u/QxrP1NOM/bOJlJlsi/jQ==",
+ "u2WQlcMxOACy6VbJXK4FwA==",
+ "u5cUPxM6/spLIV8VidPrAA==",
+ "uC2lzm7HaMAoczJO6Z/IhQ==",
+ "uChFnF0oCwARhAOz/d47eA==",
+ "uESeJe/nYrHCq4RQbrNpGA==",
+ "uExgqZkkJnZj252l5dKAGg==",
+ "uIkVijg7RPi/1j7c18G1qA==",
+ "uJZGw3IY2nCcdVeWW1geNQ==",
+ "uMq8cDVWFD+tpn8aeP8Pqg==",
+ "uNWFZlP7DA96sf+LWiAhtQ==",
+ "uNzpptKjihEfKRo5A1nWmw==",
+ "uO+uK1DntCxVRr1KttfUIw==",
+ "uOHrw37yF9oLLVd16nUpeg==",
+ "uOkMpYy/7DYYoethJdixfQ==",
+ "uPdjKJIGzN7pbGZDZdCGaA==",
+ "uPi8TsGY3vQsMVo/nsbgVQ==",
+ "uPm+cF4Jq08S5pQhYFjU8A==",
+ "uPnL9tboMZo0Kl2fe24CmA==",
+ "uQs79rbD/wEakMUxqMI48A==",
+ "uSIiF1r9F18avZczmlEuMQ==",
+ "uT6WRh5UpVdeABssoP2VTg==",
+ "uTA0XbiH3fTeVV7u5z0b3w==",
+ "uTHBqApdKOAgdwX3cjrCYQ==",
+ "uU1TX5DoDg6EcFKgFcn0GA==",
+ "uXuPA/2KJbb7ZX+NymN3dw==",
+ "uXvr6vi5kazZ9BCg2PWPJA==",
+ "uZ2gUA74/7Q33tI2TcGQlg==",
+ "ucLMWnNDSqE4NOCGWvcGWw==",
+ "udU65VtsvJspYmamiOsgXw==",
+ "ueODvMv/f9ZD8O0aIHn4sg==",
+ "ugY8rTtJkN4CXWMVcRZiZw==",
+ "uhT12XY79CtbwhcSfAmAXQ==",
+ "ulLuTZqhEDkX0EJ3xwRP9A==",
+ "ulpDxLeQnIRPnq6oaah2AA==",
+ "up2MVDi9ve+s83/nwNtZ7Q==",
+ "uqe3rFveJ2JIkcZQ3ZMXHQ==",
+ "uqp92lAqjec8UQYfyjaEZw==",
+ "ur9JDCVNwzSH4q4ngDlHNQ==",
+ "uu+ncs63SdQIvG6z4r7Q3Q==",
+ "uuiJ+yB7JLDh2ulthM0mjg==",
+ "uvKYnKE01D5r7kR9UQyo5A==",
+ "uvzmRcvgepW6mZbMfYgcNw==",
+ "uwA6N5LptSXqIBkTO0Jd7Q==",
+ "uwGivY3/C9WK+dirRPJZ4A==",
+ "uzEgwx1iAXAvWPKSVwYSeQ==",
+ "uzkNhmo2d08tv5AmnyqkoQ==",
+ "v/PshI6JjkL9nojLlMNfhg==",
+ "v0Bvws1WYVoEgDt8xmVKew==",
+ "v1AWe5qb5y3vSKFb7ADeEw==",
+ "v4xIYrfPGILEbD/LwVDDzA==",
+ "v6jZicMNM3ysm3U5xu0HoQ==",
+ "v7BrkRmK0FfWSHunTRHQFQ==",
+ "vCekQ2nOQKiN/q8Be/qwZg==",
+ "vFFzkWgGyw6OPADONtEojQ==",
+ "vFox1d3llOeBeCUZGvTy0A==",
+ "vFtC0B2oe1gck28JOM1dyg==",
+ "vGKknndb4j6VTV8DxeT4fQ==",
+ "vHGjRRSlZHJIliCwIkCAmQ==",
+ "vHVXsAMQqc0qp7HA5Q+YkA==",
+ "vHmQUl4WHXs1E/Shh+TeyA==",
+ "vIORTYSHFIXk5E2NyIvWcQ==",
+ "vMuaLvAntJB5o7lmt/kVXA==",
+ "vOJ55zFdgPPauPyFYBf01w==",
+ "vRgkZZGVN7YZrlml0vxrKA==",
+ "vSKsa0JhLCe9QFZKkcj58Q==",
+ "vTAmgfq3GxL4+ubXpzwk5w==",
+ "vUC0HlTTHj6qNHwfviDtAw==",
+ "vUE8Iw3NyWXURpXyoNJdaw==",
+ "vWn9OPnrJgfPavg4D6T/HQ==",
+ "vX7RIhatQeXAMr1+OjzhZw==",
+ "vZtL0yWpSIA+9v8i23bZSg==",
+ "vb6Agwzk4JG0Nn7qRPPFMQ==",
+ "vbyiKeDCQ4q9dDRI1Q0Ong==",
+ "vg3jozLXEmAnmJwdfcEN0g==",
+ "vhdFtKVH4bVatb4n8KzeXw==",
+ "vjrSYGUpeKOtJ2cNgLFg2g==",
+ "vljJciS+uuIvL7XXm5688g==",
+ "vmqfGJE6r4yDahtU/HLrxw==",
+ "vnOJ3e9Zd4wPx8PX7QgZzQ==",
+ "voO3krg4sdy4Iu+MZEr8+g==",
+ "vqYHQ3MnHrAIAr1QHwfIag==",
+ "vsRNZx4thFFFPneubKq1Fw==",
+ "vvEH5A39TTe1AOC11rRCLA==",
+ "vvh9vAIrXjIwLVkuJb5oDQ==",
+ "vwno3vugCvt6ooT3CD4qIQ==",
+ "w+jzM0I5DRzoUiLS/9QIMQ==",
+ "w0PKdssv+Zc5J/BbphoxpA==",
+ "w1zN28mSrI/gqHsgs4ME3A==",
+ "w3G+qXXqqKi8F5s+qvkBUg==",
+ "w5N/aHbtOIKzcvG3GlMjGA==",
+ "wDiGoFEfIVEDyyc4VpwhWQ==",
+ "wEJDulZafLuXCvcqBYioFQ==",
+ "wHA+D5cObfV3kGORCdEknw==",
+ "wI7JrSPQwYHpv2lRsQu9nQ==",
+ "wIfvvLKC61gOpsddUFjVog==",
+ "wJ4uCrl4DPg70ltw1dZO3w==",
+ "wJKFMqh6MGctWfasjHrPEg==",
+ "wJpepvmtQQ3sz3tVFDnFqw==",
+ "wK6Srd83eLigZ11Q20XGrg==",
+ "wM8tnXO4PDlLVHspZFcjYw==",
+ "wMOE/pEKVIklE75xjt6b6w==",
+ "wMum67lfk5E1ohUObJgrOg==",
+ "wMyJLQJdmrC2TSeFkIuSvQ==",
+ "wOc4TbwQGUwOC1B3BEZ4OQ==",
+ "wOhbpTzmFla8R0kI9OiHaA==",
+ "wPhJcp7U7IVX83szbIOOxQ==",
+ "wQKL8Ga6JQkpZ7yymDkC3w==",
+ "wR2Gxb07nkaPcZHlEjr8iA==",
+ "wRqaDZVHHurp5whOQ1kDbQ==",
+ "wTO49YX/ePHMWtcoxUAHpw==",
+ "wUYhs4j3W9nIywu1HIv2JA==",
+ "wVfSZYjMjbTsD2gaSbwuqQ==",
+ "wX2URK6eDDHeEOF3cgPgHA==",
+ "wX70jKLKJApHnhyK0r6t3A==",
+ "wajwXfWz2J+O+NVaj6j2UQ==",
+ "wc+8ohFWgOF4VlSYiZIGwQ==",
+ "wdRyYjaM11VmqkkxV/5bsA==",
+ "wfwuxn+Vja1DNwiDwL2pcQ==",
+ "wgH1GlUxWi6/yLLFzE76uQ==",
+ "who8uUamlHWHXnBf7dwy4A==",
+ "wlWxtQDJ+siGhN2fJn3qtw==",
+ "wnfYUctNK+UPwefX5y4/Rw==",
+ "wpZqFkKafFpLcykN2IISqg==",
+ "wqUJ1Gq1Yz2cXFkbcCmzHQ==",
+ "wqWqe0KRjZlUIrGgEOG9Mg==",
+ "wrewZ0hoHODf7qmoGcOd7g==",
+ "wsp+vmW8sEqXYVURd/gjHA==",
+ "wt+qDLU38kzNU75ZYi3Hbw==",
+ "wtyAZIfhomcHe9dLbYoSvA==",
+ "wux5Y8AipBnc5tJapTzgEQ==",
+ "wv4NC9CIpwuGf/nOQYe/oA==",
+ "wxkb8evGEaGf/rg/1XUWiA==",
+ "wy/Z8505o4sVovk4UuBp1A==",
+ "wyqmQGB6vgRVrYtmB2vB7w==",
+ "wyx5mnUMgP5wjykjAfTO7w==",
+ "x+8rwkqKCv0juoT5m1A4eg==",
+ "x/BIDm6TKMhqu/gtb3kGyw==",
+ "x/MpsQvziUpW40nNUHDS5Q==",
+ "x0eIHCvQLd2jdDaXwSWTYQ==",
+ "x1A74vg/hwwjAx6GrkU8zw==",
+ "x2NpqNnqRihktNzpxmepkQ==",
+ "x2nSgcTjA3oGgI8mMgiqjw==",
+ "x5lyMArsv1MuJmEFlWCnNw==",
+ "x5zMDuW66467ofgL3spLUQ==",
+ "x6M66krXSi0EhppwmDmsxA==",
+ "x6lNRGgJcRxgKTlzhc1WPg==",
+ "x8kRVzohTdhkryvYeMvkMw==",
+ "x9TIZ9Ua++3BX+MpjgTuWA==",
+ "x9VwDdFPp/rJ+SF16ooWYg==",
+ "xAAipGfHTGTjp9Qk1MR8RQ==",
+ "xJi0T+psHOXMivSOVpMWeQ==",
+ "xLm/bJBonpTs0PwsF0DvRg==",
+ "xMIHeno2qj3V8q9H1xezeg==",
+ "xNilc7UOu1kyP0+nK5MrLw==",
+ "xPe76nHyHmald6kmMQsKdg==",
+ "xQpYjaAmrQudWgsdu24J0A==",
+ "xTizUioizbMQxD0T6fy/EQ==",
+ "xUXEE7OBBCudsQnuj5ycOA==",
+ "xWYecfzAtXT9WyQ8NYY/hw==",
+ "xX6atcCApI08oVLjjLteLg==",
+ "xYD8jrCDmuQna+p1ebnKDQ==",
+ "xbBxUP9JyY0wDgHDipBHeg==",
+ "xdCCdP8SNBOK3IsX6PiPQA==",
+ "xdmY+qyoxxuRZa9kuNpDEg==",
+ "xfYZ6qhWNBqqJ0PdWRjOwA==",
+ "xfjBQk3CrNjhufdPIhr91A==",
+ "xiFlcSfa/gnPiO+LwbixcQ==",
+ "xiyRfVG0EfBA+rCk+tgWRQ==",
+ "xjA21QjNdThLW3VV7SCnrg==",
+ "xjTMO2mvtpvwQrounD4e8g==",
+ "xktOghh1S9nIX6fXWnT+Ug==",
+ "xmGgK3W5y+oCd0K2u8XjZQ==",
+ "xmsYnsJq78/f9xuKuQ2pBQ==",
+ "xoPSM86Se+1hHX0y3hhdkw==",
+ "xs8J3cesq7lDhP/dNltqOw==",
+ "xsCZVhCk2qJmOqvUjK3Y8Q==",
+ "xsf0m31Am0W9eLhopAkfnA==",
+ "xukOAM0QVsA72qEy0yku9A==",
+ "xvipmmwKdYt4eoKvvRnjEg==",
+ "xweGAZf+Yb3TtwR/sGmGIA==",
+ "xzGzN5Hhbh0m/KezjNvXbQ==",
+ "y+1I05LDAYJ09tKMs3zW6g==",
+ "y+cl1/Knb9MZPz8nBB0M+w==",
+ "y/e3HSdg7T19FanRpJ7+7Q==",
+ "y1J+o6DC2sETFsySgpDZyA==",
+ "y2JOIoIiT9cV1VxplZPraQ==",
+ "y2Tn2gmhKs5WKc01ce74rg==",
+ "y4/HohCJxtt+cT7nLJB08w==",
+ "y4Y4mSSTw/WrIdRpktc5Hw==",
+ "y4iBxAMn/KzMmaWShdYiIw==",
+ "y4mfEDerrhaqApDdhP5vjA==",
+ "y7yS9x3yshVhMpDbQtfYOQ==",
+ "yCu+DVU/ceMTOZ5h/7wQTg==",
+ "yD3Dd4ToRrl53k/2NSCJiw==",
+ "yDrAd1ot38soBk7zKdnT8A==",
+ "yKLLiqzxfrCsr6+Rm6kx1Q==",
+ "yKrsKX4/1B1C0TyvciNz5w==",
+ "yL1DwlIIREPuyuCFULi0uw==",
+ "yLAhLNezvqVHmN1SfMRrPw==",
+ "yOE90OHQdyOfrAgwDvn2gA==",
+ "yPIeWcW8+3HjDagegrN8bw==",
+ "yQCLV9IoPyXEOaj3IdFMWw==",
+ "yQmNZnp/JZywbBiZs3gecA==",
+ "yS/yMnJDHW0iaOsbj4oPTg==",
+ "yTVJKBn72RjakMBXDoBKHg==",
+ "yTgN5xFIdz1MzFS6xMl5uQ==",
+ "yU3N0HMSP5etuHPNrVkZtg==",
+ "yV3IbbTWAbHMhMGVvgb/ZQ==",
+ "yYBIS9PZbKo7Gram7IXWPA==",
+ "yYVW07lOZHdgtX42xJONIA==",
+ "yYmnM/WOgi+48Rw7foGyXA==",
+ "yYp4iuI5f/y/l1AEJxYolQ==",
+ "ybpTgPr3SjJ12Rj5lC/IMA==",
+ "ycjv4XkS5O7zcF3sqq9MwQ==",
+ "yctId8ltkl3+xqi9bj+RqA==",
+ "ydVj2odhergi+2zGUwK4/A==",
+ "yf06Slv9l3IZEjVqvxP2aA==",
+ "yfAaL0MMtSXPQ37pBdmHxQ==",
+ "yhI5jHlfFJxu4eV5VJO2zQ==",
+ "yhRi5M9Etuu9HSu4d24i3w==",
+ "yhexr/OFKfZl0o3lS70e4w==",
+ "ylA6sU7Kaf9fMNIx1+sIlw==",
+ "ymtA8EMPMgmMcimWZZ0A1Q==",
+ "ynaj4XjU27b7XbqPyxI8Ig==",
+ "yqQPU4jT9XvRABZgNQXjgg==",
+ "yqtj8GfLaUHYv/BsdjxIVw==",
+ "ysRQ+7Aq7eVLOp88KnFVMA==",
+ "ytDXLDBqWiU1w3sTurYmaw==",
+ "yteeQr3ub2lDXgLziZV+DQ==",
+ "yxCyBXqGWA735JEyljDP7Q==",
+ "z+1oDVy8GJ5u/UDF+bIQdA==",
+ "z/e5M2lE9qh3bzB97jZCKA==",
+ "z0BU//aSjYHAkGGk3ZSGNg==",
+ "z20AAnvj7WsfJeOu3vemlA==",
+ "z3L2BNjQOMOfTVBUxcpnRA==",
+ "z4Bft++f72QeDh4PWGr/sw==",
+ "z4oKy2wKH+sbNSgGjbdHGw==",
+ "z5DveTu377UW8IHnsiUGZg==",
+ "z920R8eahJPiTsifrPYdxA==",
+ "z9cd+Qj+ueX34Zf3997MNQ==",
+ "zCRZgVsHbQZcVMHd9pGD3A==",
+ "zCpibjrZOA3FQ4lYt0WoVA==",
+ "zDSQ3NJuUGkVOlvVCATRwA==",
+ "zDUZCzQesFjO1JI3PwDjfg==",
+ "zEzWZ6l7EKoVUxvk/l78Mw==",
+ "zJ7ScHNxr2leCDNNcuDApA==",
+ "zNLlWGW/aKBhUwQZ4DZWoQ==",
+ "zVupSPz7cD0v/mD/eUIIjg==",
+ "zZtYkKU50PPEj6qSbO5/Sw==",
+ "za4rzveYVMFe3Gw531DQJQ==",
+ "zaqyy3GaJ7cp8qDoLJWcTw==",
+ "zbjXhZaeyMfdTb2zxvmRMg==",
+ "zeELfk015D5krExLKRUYtg==",
+ "zeHF6fdeqcOId3fRUGscRw==",
+ "zgEyxj/sCs63O98sZS94Yw==",
+ "zi04Yc01ZheuFAQc59E45A==",
+ "zirOtGUXeRL22ezfotZfQg==",
+ "zm+z+OOyHhljV2TjA3U9zw==",
+ "zrZWcqQsUE3ocWE0fG+SOA==",
+ "ztULoqHvCOE6qV7ocqa4/w==",
+ "zwQ/3MzTJ9rfBmrANIh14w==",
+ "zwY6tCjjya/bgrYaCncaag==",
+ "zxsSqovedB3HT99jVblCnQ==",
+ "zyA9f5J7mw5InjhcfeumAQ==",
+]);
diff --git a/browser/components/newtab/lib/HighlightsFeed.jsm b/browser/components/newtab/lib/HighlightsFeed.jsm
new file mode 100644
index 0000000000..54f83c9f29
--- /dev/null
+++ b/browser/components/newtab/lib/HighlightsFeed.jsm
@@ -0,0 +1,361 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
+const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
+
+const { actionTypes: at } = ChromeUtils.import(
+ "resource://activity-stream/common/Actions.jsm"
+);
+
+const { shortURL } = ChromeUtils.import(
+ "resource://activity-stream/lib/ShortURL.jsm"
+);
+const { SectionsManager } = ChromeUtils.import(
+ "resource://activity-stream/lib/SectionsManager.jsm"
+);
+const {
+ TOP_SITES_DEFAULT_ROWS,
+ TOP_SITES_MAX_SITES_PER_ROW,
+} = ChromeUtils.import("resource://activity-stream/common/Reducers.jsm");
+const { Dedupe } = ChromeUtils.import(
+ "resource://activity-stream/common/Dedupe.jsm"
+);
+
+ChromeUtils.defineModuleGetter(
+ this,
+ "filterAdult",
+ "resource://activity-stream/lib/FilterAdult.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "LinksCache",
+ "resource://activity-stream/lib/LinksCache.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "NewTabUtils",
+ "resource://gre/modules/NewTabUtils.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "Screenshots",
+ "resource://activity-stream/lib/Screenshots.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "PageThumbs",
+ "resource://gre/modules/PageThumbs.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "DownloadsManager",
+ "resource://activity-stream/lib/DownloadsManager.jsm"
+);
+
+const HIGHLIGHTS_MAX_LENGTH = 16;
+const MANY_EXTRA_LENGTH =
+ HIGHLIGHTS_MAX_LENGTH * 5 +
+ TOP_SITES_DEFAULT_ROWS * TOP_SITES_MAX_SITES_PER_ROW;
+const SECTION_ID = "highlights";
+const SYNC_BOOKMARKS_FINISHED_EVENT = "weave:engine:sync:applied";
+const BOOKMARKS_RESTORE_SUCCESS_EVENT = "bookmarks-restore-success";
+const BOOKMARKS_RESTORE_FAILED_EVENT = "bookmarks-restore-failed";
+const RECENT_DOWNLOAD_THRESHOLD = 36 * 60 * 60 * 1000;
+
+this.HighlightsFeed = class HighlightsFeed {
+ constructor() {
+ this.dedupe = new Dedupe(this._dedupeKey);
+ this.linksCache = new LinksCache(
+ NewTabUtils.activityStreamLinks,
+ "getHighlights",
+ ["image"]
+ );
+ PageThumbs.addExpirationFilter(this);
+ this.downloadsManager = new DownloadsManager();
+ }
+
+ _dedupeKey(site) {
+ // Treat bookmarks, pocket, and downloaded items as un-dedupable, otherwise show one of a url
+ return (
+ site &&
+ (site.pocket_id || site.type === "bookmark" || site.type === "download"
+ ? {}
+ : site.url)
+ );
+ }
+
+ init() {
+ Services.obs.addObserver(this, SYNC_BOOKMARKS_FINISHED_EVENT);
+ Services.obs.addObserver(this, BOOKMARKS_RESTORE_SUCCESS_EVENT);
+ Services.obs.addObserver(this, BOOKMARKS_RESTORE_FAILED_EVENT);
+ SectionsManager.onceInitialized(this.postInit.bind(this));
+ }
+
+ postInit() {
+ SectionsManager.enableSection(SECTION_ID, true /* isStartup */);
+ this.fetchHighlights({ broadcast: true, isStartup: true });
+ this.downloadsManager.init(this.store);
+ }
+
+ uninit() {
+ SectionsManager.disableSection(SECTION_ID);
+ PageThumbs.removeExpirationFilter(this);
+ Services.obs.removeObserver(this, SYNC_BOOKMARKS_FINISHED_EVENT);
+ Services.obs.removeObserver(this, BOOKMARKS_RESTORE_SUCCESS_EVENT);
+ Services.obs.removeObserver(this, BOOKMARKS_RESTORE_FAILED_EVENT);
+ }
+
+ observe(subject, topic, data) {
+ // When we receive a notification that a sync has happened for bookmarks,
+ // or Places finished importing or restoring bookmarks, refresh highlights
+ const manyBookmarksChanged =
+ (topic === SYNC_BOOKMARKS_FINISHED_EVENT && data === "bookmarks") ||
+ topic === BOOKMARKS_RESTORE_SUCCESS_EVENT ||
+ topic === BOOKMARKS_RESTORE_FAILED_EVENT;
+ if (manyBookmarksChanged) {
+ this.fetchHighlights({ broadcast: true });
+ }
+ }
+
+ filterForThumbnailExpiration(callback) {
+ const state = this.store
+ .getState()
+ .Sections.find(section => section.id === SECTION_ID);
+
+ callback(
+ state && state.initialized
+ ? state.rows.reduce((acc, site) => {
+ // Screenshots call in `fetchImage` will search for preview_image_url or
+ // fallback to URL, so we prevent both from being expired.
+ acc.push(site.url);
+ if (site.preview_image_url) {
+ acc.push(site.preview_image_url);
+ }
+ return acc;
+ }, [])
+ : []
+ );
+ }
+
+ /**
+ * Chronologically sort highlights of all types except 'visited'. Then just append
+ * the rest at the end of highlights.
+ * @param {Array} pages The full list of links to order.
+ * @return {Array} A sorted array of highlights
+ */
+ _orderHighlights(pages) {
+ const splitHighlights = { chronologicalCandidates: [], visited: [] };
+ for (let page of pages) {
+ if (page.type === "history") {
+ splitHighlights.visited.push(page);
+ } else {
+ splitHighlights.chronologicalCandidates.push(page);
+ }
+ }
+
+ return splitHighlights.chronologicalCandidates
+ .sort((a, b) => a.date_added < b.date_added)
+ .concat(splitHighlights.visited);
+ }
+
+ /**
+ * Refresh the highlights data for content.
+ * @param {bool} options.broadcast Should the update be broadcasted.
+ */
+ async fetchHighlights(options = {}) {
+ // If TopSites are enabled we need them for deduping, so wait for
+ // TOP_SITES_UPDATED. We also need the section to be registered to update
+ // state, so wait for postInit triggered by SectionsManager initializing.
+ if (
+ (!this.store.getState().TopSites.initialized &&
+ this.store.getState().Prefs.values["feeds.system.topsites"] &&
+ this.store.getState().Prefs.values["feeds.topsites"]) ||
+ !this.store.getState().Sections.length
+ ) {
+ return;
+ }
+
+ // We broadcast when we want to force an update, so get fresh links
+ if (options.broadcast) {
+ this.linksCache.expire();
+ }
+
+ // Request more than the expected length to allow for items being removed by
+ // deduping against Top Sites or multiple history from the same domain, etc.
+ const manyPages = await this.linksCache.request({
+ numItems: MANY_EXTRA_LENGTH,
+ excludeBookmarks: !this.store.getState().Prefs.values[
+ "section.highlights.includeBookmarks"
+ ],
+ excludeHistory: !this.store.getState().Prefs.values[
+ "section.highlights.includeVisited"
+ ],
+ excludePocket: !this.store.getState().Prefs.values[
+ "section.highlights.includePocket"
+ ],
+ });
+
+ if (
+ this.store.getState().Prefs.values["section.highlights.includeDownloads"]
+ ) {
+ // We only want 1 download that is less than 36 hours old, and the file currently exists
+ let results = await this.downloadsManager.getDownloads(
+ RECENT_DOWNLOAD_THRESHOLD,
+ { numItems: 1, onlySucceeded: true, onlyExists: true }
+ );
+ if (results.length) {
+ // We only want 1 download, the most recent one
+ manyPages.push({
+ ...results[0],
+ type: "download",
+ });
+ }
+ }
+
+ const orderedPages = this._orderHighlights(manyPages);
+
+ // Remove adult highlights if we need to
+ const checkedAdult = this.store.getState().Prefs.values.filterAdult
+ ? filterAdult(orderedPages)
+ : orderedPages;
+
+ // Remove any Highlights that are in Top Sites already
+ const [, deduped] = this.dedupe.group(
+ this.store.getState().TopSites.rows,
+ checkedAdult
+ );
+
+ // Keep all "bookmark"s and at most one (most recent) "history" per host
+ const highlights = [];
+ const hosts = new Set();
+ for (const page of deduped) {
+ const hostname = shortURL(page);
+ // Skip this history page if we already something from the same host
+ if (page.type === "history" && hosts.has(hostname)) {
+ continue;
+ }
+
+ // If we already have the image for the card, use that immediately. Else
+ // asynchronously fetch the image. NEVER fetch a screenshot for downloads
+ if (!page.image && page.type !== "download") {
+ this.fetchImage(page, options.isStartup);
+ }
+
+ // Adjust the type for 'history' items that are also 'bookmarked' when we
+ // want to include bookmarks
+ if (
+ page.type === "history" &&
+ page.bookmarkGuid &&
+ this.store.getState().Prefs.values[
+ "section.highlights.includeBookmarks"
+ ]
+ ) {
+ page.type = "bookmark";
+ }
+
+ // We want the page, so update various fields for UI
+ Object.assign(page, {
+ hasImage: page.type !== "download", // Downloads do not have an image - all else types fall back to a screenshot
+ hostname,
+ type: page.type,
+ pocket_id: page.pocket_id,
+ });
+
+ // Add the "bookmark", "pocket", or not-skipped "history"
+ highlights.push(page);
+ hosts.add(hostname);
+
+ // Remove internal properties that might be updated after dispatch
+ delete page.__sharedCache;
+
+ // Skip the rest if we have enough items
+ if (highlights.length === HIGHLIGHTS_MAX_LENGTH) {
+ break;
+ }
+ }
+
+ const { initialized } = this.store
+ .getState()
+ .Sections.find(section => section.id === SECTION_ID);
+ // Broadcast when required or if it is the first update.
+ const shouldBroadcast = options.broadcast || !initialized;
+
+ SectionsManager.updateSection(
+ SECTION_ID,
+ { rows: highlights },
+ shouldBroadcast,
+ options.isStartup
+ );
+ }
+
+ /**
+ * Fetch an image for a given highlight and update the card with it. If no
+ * image is available then fallback to fetching a screenshot.
+ */
+ fetchImage(page, isStartup = false) {
+ // Request a screenshot if we don't already have one pending
+ const { preview_image_url: imageUrl, url } = page;
+ return Screenshots.maybeCacheScreenshot(
+ page,
+ imageUrl || url,
+ "image",
+ image => {
+ SectionsManager.updateSectionCard(
+ SECTION_ID,
+ url,
+ { image },
+ true,
+ isStartup
+ );
+ }
+ );
+ }
+
+ onAction(action) {
+ // Relay the downloads actions to DownloadsManager - it is a child of HighlightsFeed
+ this.downloadsManager.onAction(action);
+ switch (action.type) {
+ case at.INIT:
+ this.init();
+ break;
+ case at.SYSTEM_TICK:
+ case at.TOP_SITES_UPDATED:
+ this.fetchHighlights({
+ broadcast: false,
+ isStartup: !!action.meta?.isStartup,
+ });
+ break;
+ case at.PREF_CHANGED:
+ // Update existing pages when the user changes what should be shown
+ if (action.data.name.startsWith("section.highlights.include")) {
+ this.fetchHighlights({ broadcast: true });
+ }
+ break;
+ case at.PLACES_HISTORY_CLEARED:
+ case at.PLACES_LINK_BLOCKED:
+ case at.DOWNLOAD_CHANGED:
+ case at.POCKET_LINK_DELETED_OR_ARCHIVED:
+ this.fetchHighlights({ broadcast: true });
+ break;
+ case at.PLACES_LINKS_CHANGED:
+ case at.PLACES_SAVED_TO_POCKET:
+ this.linksCache.expire();
+ this.fetchHighlights({ broadcast: false });
+ break;
+ case at.UNINIT:
+ this.uninit();
+ break;
+ }
+ }
+};
+
+const EXPORTED_SYMBOLS = [
+ "HighlightsFeed",
+ "SECTION_ID",
+ "MANY_EXTRA_LENGTH",
+ "SYNC_BOOKMARKS_FINISHED_EVENT",
+ "BOOKMARKS_RESTORE_SUCCESS_EVENT",
+ "BOOKMARKS_RESTORE_FAILED_EVENT",
+];
diff --git a/browser/components/newtab/lib/InfoBar.jsm b/browser/components/newtab/lib/InfoBar.jsm
new file mode 100644
index 0000000000..d71f9a7d6c
--- /dev/null
+++ b/browser/components/newtab/lib/InfoBar.jsm
@@ -0,0 +1,158 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
+const { XPCOMUtils } = ChromeUtils.import(
+ "resource://gre/modules/XPCOMUtils.jsm"
+);
+
+XPCOMUtils.defineLazyModuleGetters(this, {
+ PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.jsm",
+ RemoteL10n: "resource://activity-stream/lib/RemoteL10n.jsm",
+ Services: "resource://gre/modules/Services.jsm",
+});
+
+class InfoBarNotification {
+ constructor(message, dispatch) {
+ this._dispatch = dispatch;
+ this.dispatchUserAction = this.dispatchUserAction.bind(this);
+ this.buttonCallback = this.buttonCallback.bind(this);
+ this.infobarCallback = this.infobarCallback.bind(this);
+ this.message = message;
+ this.notification = null;
+ }
+
+ /**
+ * Show the infobar notification and send an impression ping
+ *
+ * @param {object} browser Browser reference for the currently selected tab
+ */
+ showNotification(browser) {
+ let { content } = this.message;
+ let { gBrowser } = browser.ownerGlobal;
+ let doc = gBrowser.ownerDocument;
+ let notificationContainer;
+ if (content.type === "global") {
+ notificationContainer = browser.ownerGlobal.gHighPriorityNotificationBox;
+ } else {
+ notificationContainer = gBrowser.getNotificationBox(browser);
+ }
+
+ this.notification = notificationContainer.appendNotification(
+ this.formatMessageConfig(doc, content.text),
+ this.message.id,
+ content.icon || "chrome://branding/content/icon64.png",
+ notificationContainer.PRIORITY_INFO_MEDIUM,
+ content.buttons.map(b => this.formatButtonConfig(b)),
+ this.infobarCallback
+ );
+
+ this.addImpression();
+ }
+
+ formatMessageConfig(doc, content) {
+ let docFragment = doc.createDocumentFragment();
+ // notificationbox will only `appendChild` for documentFragments
+ docFragment.appendChild(RemoteL10n.createElement(doc, "span", { content }));
+
+ return docFragment;
+ }
+
+ formatButtonConfig(button) {
+ let btnConfig = { callback: this.buttonCallback, ...button };
+ // notificationbox will set correct data-l10n-id attributes if passed in
+ // using the l10n-id key. Otherwise the `button.label` text is used.
+ if (button.label.string_id) {
+ btnConfig["l10n-id"] = button.label.string_id;
+ }
+
+ return btnConfig;
+ }
+
+ addImpression() {
+ // Record an impression in ASRouter for frequency capping
+ this._dispatch({ type: "IMPRESSION", data: this.message });
+ // Send a user impression telemetry ping
+ this.sendUserEventTelemetry("IMPRESSION");
+ }
+
+ /**
+ * Called when one of the infobar buttons is clicked
+ */
+ buttonCallback(notificationBox, btnDescription, target) {
+ this.dispatchUserAction(
+ btnDescription.action,
+ target.ownerGlobal.gBrowser.selectedBrowser
+ );
+ let isPrimary = target.classList.contains("primary");
+ let eventName = isPrimary
+ ? "CLICK_PRIMARY_BUTTON"
+ : "CLICK_SECONDARY_BUTTON";
+ this.sendUserEventTelemetry(eventName);
+ }
+
+ dispatchUserAction(action, selectedBrowser) {
+ this._dispatch({ type: "USER_ACTION", data: action }, selectedBrowser);
+ }
+
+ /**
+ * Called when interacting with the toolbar (but not through the buttons)
+ */
+ infobarCallback(eventType) {
+ if (eventType === "removed" || eventType === "disconnected") {
+ this.notification = null;
+ } else {
+ this.sendUserEventTelemetry(eventType.toUpperCase());
+ }
+ }
+
+ sendUserEventTelemetry(event) {
+ const ping = {
+ message_id: this.message.id,
+ event,
+ };
+ this._dispatch({
+ type: "INFOBAR_TELEMETRY",
+ data: { action: "infobar_user_event", ...ping },
+ });
+ }
+}
+
+const InfoBar = {
+ maybeLoadCustomElement(win) {
+ if (!win.customElements.get("remote-text")) {
+ Services.scriptloader.loadSubScript(
+ "resource://activity-stream/data/custom-elements/paragraph.js",
+ win
+ );
+ }
+ },
+
+ maybeInsertFTL(win) {
+ win.MozXULElement.insertFTLIfNeeded("browser/newtab/asrouter.ftl");
+ win.MozXULElement.insertFTLIfNeeded(
+ "browser/defaultBrowserNotification.ftl"
+ );
+ },
+
+ showInfoBarMessage(browser, message, dispatch) {
+ const win = browser.ownerGlobal;
+
+ if (PrivateBrowsingUtils.isWindowPrivate(win)) {
+ return null;
+ }
+
+ this.maybeLoadCustomElement(win);
+ this.maybeInsertFTL(win);
+
+ let notification = new InfoBarNotification(message, dispatch);
+ notification.showNotification(browser);
+
+ return notification;
+ },
+};
+
+this.InfoBar = InfoBar;
+
+const EXPORTED_SYMBOLS = ["InfoBar"];
diff --git a/browser/components/newtab/lib/LinksCache.jsm b/browser/components/newtab/lib/LinksCache.jsm
new file mode 100644
index 0000000000..aac16fcfea
--- /dev/null
+++ b/browser/components/newtab/lib/LinksCache.jsm
@@ -0,0 +1,136 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
+const EXPORTED_SYMBOLS = ["LinksCache"];
+
+// This should be slightly less than SYSTEM_TICK_INTERVAL as timer
+// comparisons are too exact while the async/await functionality will make the
+// last recorded time a little bit later. This causes the comparasion to skip
+// updates.
+// It should be 10% less than SYSTEM_TICK to update at least once every 5 mins.
+// https://github.com/mozilla/activity-stream/pull/3695#discussion_r144678214
+const EXPIRATION_TIME = 4.5 * 60 * 1000; // 4.5 minutes
+
+/**
+ * Cache link results from a provided object property and refresh after some
+ * amount of time has passed. Allows for migrating data from previously cached
+ * links to the new links with the same url.
+ */
+this.LinksCache = class LinksCache {
+ /**
+ * Create a links cache for a given object property.
+ *
+ * @param {object} linkObject Object containing the link property
+ * @param {string} linkProperty Name of property on object to access
+ * @param {array} properties Optional properties list to migrate to new links.
+ * @param {function} shouldRefresh Optional callback receiving the old and new
+ * options to refresh even when not expired.
+ */
+ constructor(
+ linkObject,
+ linkProperty,
+ properties = [],
+ shouldRefresh = () => {}
+ ) {
+ this.clear();
+
+ // Allow getting links from both methods and array properties
+ this.linkGetter = options => {
+ const ret = linkObject[linkProperty];
+ return typeof ret === "function" ? ret.call(linkObject, options) : ret;
+ };
+
+ // Always migrate the shared cache data in addition to any custom properties
+ this.migrateProperties = ["__sharedCache", ...properties];
+ this.shouldRefresh = shouldRefresh;
+ }
+
+ /**
+ * Clear the cached data.
+ */
+ clear() {
+ this.cache = Promise.resolve([]);
+ this.lastOptions = {};
+ this.expire();
+ }
+
+ /**
+ * Force the next request to update the cache.
+ */
+ expire() {
+ delete this.lastUpdate;
+ }
+
+ /**
+ * Request data and update the cache if necessary.
+ *
+ * @param {object} options Optional data to pass to the underlying method.
+ * @returns {promise(array)} Links array with objects that can be modified.
+ */
+ async request(options = {}) {
+ // Update the cache if the data has been expired
+ const now = Date.now();
+ if (
+ this.lastUpdate === undefined ||
+ now > this.lastUpdate + EXPIRATION_TIME ||
+ // Allow custom rules around refreshing based on options
+ this.shouldRefresh(this.lastOptions, options)
+ ) {
+ // Update request state early so concurrent requests can refer to it
+ this.lastOptions = options;
+ this.lastUpdate = now;
+
+ // Save a promise before awaits, so other requests wait for correct data
+ // eslint-disable-next-line no-async-promise-executor
+ this.cache = new Promise(async (resolve, reject) => {
+ try {
+ // Allow fast lookup of old links by url that might need to migrate
+ const toMigrate = new Map();
+ for (const oldLink of await this.cache) {
+ if (oldLink) {
+ toMigrate.set(oldLink.url, oldLink);
+ }
+ }
+
+ // Update the cache with migrated links without modifying source objects
+ resolve(
+ (await this.linkGetter(options)).map(link => {
+ // Keep original array hole positions
+ if (!link) {
+ return link;
+ }
+
+ // Migrate data to the new link copy if we have an old link
+ const newLink = Object.assign({}, link);
+ const oldLink = toMigrate.get(newLink.url);
+ if (oldLink) {
+ for (const property of this.migrateProperties) {
+ const oldValue = oldLink[property];
+ if (oldValue !== undefined) {
+ newLink[property] = oldValue;
+ }
+ }
+ } else {
+ // Share data among link copies and new links from future requests
+ newLink.__sharedCache = {};
+ }
+ // Provide a helper to update the cached link
+ newLink.__sharedCache.updateLink = (property, value) => {
+ newLink[property] = value;
+ };
+
+ return newLink;
+ })
+ );
+ } catch (error) {
+ reject(error);
+ }
+ });
+ }
+
+ // Provide a shallow copy of the cached link objects for callers to modify
+ return (await this.cache).map(link => link && Object.assign({}, link));
+ }
+};
diff --git a/browser/components/newtab/lib/MomentsPageHub.jsm b/browser/components/newtab/lib/MomentsPageHub.jsm
new file mode 100644
index 0000000000..6b3d088442
--- /dev/null
+++ b/browser/components/newtab/lib/MomentsPageHub.jsm
@@ -0,0 +1,179 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
+const { XPCOMUtils } = ChromeUtils.import(
+ "resource://gre/modules/XPCOMUtils.jsm"
+);
+
+XPCOMUtils.defineLazyModuleGetters(this, {
+ Services: "resource://gre/modules/Services.jsm",
+ setInterval: "resource://gre/modules/Timer.jsm",
+ clearInterval: "resource://gre/modules/Timer.jsm",
+});
+
+// Frequency at which to check for new messages
+const SYSTEM_TICK_INTERVAL = 5 * 60 * 1000;
+const HOMEPAGE_OVERRIDE_PREF = "browser.startup.homepage_override.once";
+
+// For the "reach" event of Messaging Experiments
+const REACH_EVENT_CATEGORY = "messaging_experiments";
+const REACH_EVENT_METHOD = "reach";
+// Note it's not "moments-page" as Telemetry Events only accepts understores
+// for the event `object`
+const REACH_EVENT_OBJECT = "moments_page";
+
+class _MomentsPageHub {
+ constructor() {
+ this.id = "moments-page-hub";
+ this.state = {};
+ this.checkHomepageOverridePref = this.checkHomepageOverridePref.bind(this);
+ this._initialized = false;
+ }
+
+ async init(
+ waitForInitialized,
+ { handleMessageRequest, addImpression, blockMessageById, sendTelemetry }
+ ) {
+ if (this._initialized) {
+ return;
+ }
+
+ this._initialized = true;
+ this._handleMessageRequest = handleMessageRequest;
+ this._addImpression = addImpression;
+ this._blockMessageById = blockMessageById;
+ this._sendTelemetry = sendTelemetry;
+
+ // Need to wait for ASRouter to initialize before trying to fetch messages
+ await waitForInitialized;
+
+ this.messageRequest({
+ triggerId: "momentsUpdate",
+ template: "update_action",
+ });
+
+ const _intervalId = setInterval(
+ () => this.checkHomepageOverridePref(),
+ SYSTEM_TICK_INTERVAL
+ );
+ this.state = { _intervalId };
+ }
+
+ _sendPing(ping) {
+ this._sendTelemetry({
+ type: "MOMENTS_PAGE_TELEMETRY",
+ data: { action: "moments_user_event", ...ping },
+ });
+ }
+
+ sendUserEventTelemetry(message) {
+ this._sendPing({
+ message_id: message.id,
+ bucket_id: message.id,
+ event: "MOMENTS_PAGE_SET",
+ });
+ }
+
+ /**
+ * If we don't have `expire` defined with the message it could be because
+ * it depends on user dependent parameters. Since the message matched
+ * targeting we calculate `expire` based on the current timestamp and the
+ * `expireDelta` which defines for how long it should be available.
+ * @param expireDelta {number} - Offset in milliseconds from the current date
+ */
+ getExpirationDate(expireDelta) {
+ return Date.now() + expireDelta;
+ }
+
+ executeAction(message) {
+ const { id, data } = message.content.action;
+ switch (id) {
+ case "moments-wnp":
+ const { url, expireDelta } = data;
+ let { expire } = data;
+ if (!expire) {
+ expire = this.getExpirationDate(expireDelta);
+ }
+ // In order to reset this action we can dispatch a new message that
+ // will overwrite the prev value with an expiration date from the past.
+ Services.prefs.setStringPref(
+ HOMEPAGE_OVERRIDE_PREF,
+ JSON.stringify({ message_id: message.id, url, expire })
+ );
+ // Add impression and block immediately after taking the action
+ this.sendUserEventTelemetry(message);
+ this._addImpression(message);
+ this._blockMessageById(message.id);
+ break;
+ }
+ }
+
+ _recordReachEvent(message) {
+ const extra = { branches: message.branchSlug };
+ Services.telemetry.recordEvent(
+ REACH_EVENT_CATEGORY,
+ REACH_EVENT_METHOD,
+ REACH_EVENT_OBJECT,
+ message.experimentSlug,
+ extra
+ );
+ }
+
+ async messageRequest({ triggerId, template }) {
+ const telemetryObject = { triggerId };
+ TelemetryStopwatch.start("MS_MESSAGE_REQUEST_TIME_MS", telemetryObject);
+ const messages = await this._handleMessageRequest({
+ triggerId,
+ template,
+ returnAll: true,
+ });
+ TelemetryStopwatch.finish("MS_MESSAGE_REQUEST_TIME_MS", telemetryObject);
+
+ // Record the "reach" event for all the messages with `forReachEvent`,
+ // only execute action for the first message without forReachEvent.
+ const nonReachMessages = [];
+ for (const message of messages) {
+ if (message.forReachEvent) {
+ if (!message.forReachEvent.sent) {
+ this._recordReachEvent(message);
+ message.forReachEvent.sent = true;
+ }
+ } else {
+ nonReachMessages.push(message);
+ }
+ }
+ if (nonReachMessages.length) {
+ this.executeAction(nonReachMessages[0]);
+ }
+ }
+
+ /**
+ * Pref is set via Remote Settings message. We want to continously
+ * monitor new messages that come in to ensure the one with the
+ * highest priority is set.
+ */
+ checkHomepageOverridePref() {
+ this.messageRequest({
+ triggerId: "momentsUpdate",
+ template: "update_action",
+ });
+ }
+
+ uninit() {
+ clearInterval(this.state._intervalId);
+ this.state = {};
+ this._initialized = false;
+ }
+}
+
+this._MomentsPageHub = _MomentsPageHub;
+
+/**
+ * ToolbarBadgeHub - singleton instance of _ToolbarBadgeHub that can initiate
+ * message requests and render messages.
+ */
+this.MomentsPageHub = new _MomentsPageHub();
+
+const EXPORTED_SYMBOLS = ["_MomentsPageHub", "MomentsPageHub"];
diff --git a/browser/components/newtab/lib/NewTabInit.jsm b/browser/components/newtab/lib/NewTabInit.jsm
new file mode 100644
index 0000000000..4a4e45cbe9
--- /dev/null
+++ b/browser/components/newtab/lib/NewTabInit.jsm
@@ -0,0 +1,57 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
+const { actionCreators: ac, actionTypes: at } = ChromeUtils.import(
+ "resource://activity-stream/common/Actions.jsm"
+);
+
+/**
+ * NewTabInit - A placeholder for now. This will send a copy of the state to all
+ * newly opened tabs.
+ */
+this.NewTabInit = class NewTabInit {
+ constructor() {
+ this._repliedEarlyTabs = new Map();
+ }
+
+ reply(target) {
+ // Skip this reply if we already replied to an early tab
+ if (this._repliedEarlyTabs.get(target)) {
+ return;
+ }
+
+ const action = {
+ type: at.NEW_TAB_INITIAL_STATE,
+ data: this.store.getState(),
+ };
+ this.store.dispatch(ac.AlsoToOneContent(action, target));
+
+ // Remember that this early tab has already gotten a rehydration response in
+ // case it thought we lost its initial REQUEST and asked again
+ if (this._repliedEarlyTabs.has(target)) {
+ this._repliedEarlyTabs.set(target, true);
+ }
+ }
+
+ onAction(action) {
+ switch (action.type) {
+ case at.NEW_TAB_STATE_REQUEST:
+ this.reply(action.meta.fromTarget);
+ break;
+ case at.NEW_TAB_INIT:
+ // Initialize data for early tabs that might REQUEST twice
+ if (action.data.simulated) {
+ this._repliedEarlyTabs.set(action.data.portID, false);
+ }
+ break;
+ case at.NEW_TAB_UNLOAD:
+ // Clean up for any tab (no-op if not an early tab)
+ this._repliedEarlyTabs.delete(action.meta.fromTarget);
+ break;
+ }
+ }
+};
+
+const EXPORTED_SYMBOLS = ["NewTabInit"];
diff --git a/browser/components/newtab/lib/OnboardingMessageProvider.jsm b/browser/components/newtab/lib/OnboardingMessageProvider.jsm
new file mode 100644
index 0000000000..d2219647c7
--- /dev/null
+++ b/browser/components/newtab/lib/OnboardingMessageProvider.jsm
@@ -0,0 +1,92 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+/* globals Localization */
+const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
+
+const L10N = new Localization([
+ "branding/brand.ftl",
+ "browser/branding/brandings.ftl",
+ "browser/branding/sync-brand.ftl",
+ "browser/newtab/onboarding.ftl",
+]);
+
+const ONBOARDING_MESSAGES = () => [
+ {
+ id: "FXA_ACCOUNTS_BADGE",
+ template: "toolbar_badge",
+ content: {
+ delay: 10000, // delay for 10 seconds
+ target: "fxa-toolbar-menu-button",
+ },
+ // Never accessed the FxA panel && doesn't use Firefox sync & has FxA enabled
+ targeting: `!hasAccessedFxAPanel && !usesFirefoxSync && isFxAEnabled == true`,
+ trigger: { id: "toolbarBadgeUpdate" },
+ },
+ {
+ id: "PROTECTIONS_PANEL_1",
+ template: "protections_panel",
+ content: {
+ title: { string_id: "cfr-protections-panel-header" },
+ body: { string_id: "cfr-protections-panel-body" },
+ link_text: { string_id: "cfr-protections-panel-link-text" },
+ cta_url: `${Services.urlFormatter.formatURLPref(
+ "app.support.baseURL"
+ )}etp-promotions?as=u&utm_source=inproduct`,
+ cta_type: "OPEN_URL",
+ },
+ trigger: { id: "protectionsPanelOpen" },
+ },
+];
+
+const OnboardingMessageProvider = {
+ async getExtraAttributes() {
+ const [header, button_label] = await L10N.formatMessages([
+ { id: "onboarding-welcome-header" },
+ { id: "onboarding-start-browsing-button-label" },
+ ]);
+ return { header: header.value, button_label: button_label.value };
+ },
+ async getMessages() {
+ const messages = await this.translateMessages(await ONBOARDING_MESSAGES());
+ return messages;
+ },
+ async getUntranslatedMessages() {
+ // This is helpful for jsonSchema testing - since we are localizing in the provider
+ const messages = await ONBOARDING_MESSAGES();
+ return messages;
+ },
+ async translateMessages(messages) {
+ let translatedMessages = [];
+ for (const msg of messages) {
+ let translatedMessage = { ...msg };
+
+ // If the message has no content, do not attempt to translate it
+ if (!translatedMessage.content) {
+ translatedMessages.push(translatedMessage);
+ continue;
+ }
+
+ // Translate any secondary buttons separately
+ if (msg.content.secondary_button) {
+ const [secondary_button_string] = await L10N.formatMessages([
+ { id: msg.content.secondary_button.label.string_id },
+ ]);
+ translatedMessage.content.secondary_button.label =
+ secondary_button_string.value;
+ }
+ if (msg.content.header) {
+ const [header_string] = await L10N.formatMessages([
+ { id: msg.content.header.string_id },
+ ]);
+ translatedMessage.content.header = header_string.value;
+ }
+ translatedMessages.push(translatedMessage);
+ }
+ return translatedMessages;
+ },
+};
+this.OnboardingMessageProvider = OnboardingMessageProvider;
+
+const EXPORTED_SYMBOLS = ["OnboardingMessageProvider"];
diff --git a/browser/components/newtab/lib/PanelTestProvider.jsm b/browser/components/newtab/lib/PanelTestProvider.jsm
new file mode 100644
index 0000000000..7cbcb14858
--- /dev/null
+++ b/browser/components/newtab/lib/PanelTestProvider.jsm
@@ -0,0 +1,355 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
+const TWO_DAYS = 2 * 24 * 3600 * 1000;
+
+const MESSAGES = () => [
+ {
+ id: "SIMPLE_FXA_BOOKMARK_TEST_FLUENT",
+ template: "fxa_bookmark_panel",
+ content: {
+ title: { string_id: "cfr-doorhanger-bookmark-fxa-header" },
+ text: { string_id: "cfr-doorhanger-bookmark-fxa-body" },
+ cta: { string_id: "cfr-doorhanger-bookmark-fxa-link-text" },
+ color: "white",
+ background_color_1: "#7d31ae",
+ background_color_2: "#5033be",
+ info_icon: {
+ tooltiptext: {
+ string_id: "cfr-doorhanger-bookmark-fxa-info-icon-tooltip",
+ },
+ },
+ close_button: {
+ tooltiptext: {
+ string_id: "cfr-doorhanger-bookmark-fxa-close-btn-tooltip",
+ },
+ },
+ },
+ trigger: { id: "bookmark-panel" },
+ },
+ {
+ id: "SIMPLE_FXA_BOOKMARK_TEST_NON_FLUENT",
+ template: "fxa_bookmark_panel",
+ content: {
+ title: "Bookmark Message Title",
+ text: "Bookmark Message Body",
+ cta: "Sync bookmarks now",
+ color: "white",
+ background_color_1: "#7d31ae",
+ background_color_2: "#5033be",
+ info_icon: {
+ tooltiptext: "Toggle tooltip",
+ },
+ close_button: {
+ tooltiptext: "Close tooltip",
+ },
+ },
+ trigger: { id: "bookmark-panel" },
+ },
+ {
+ id: "WNP_THANK_YOU",
+ template: "update_action",
+ content: {
+ action: {
+ id: "moments-wnp",
+ data: {
+ url:
+ "https://www.mozilla.org/%LOCALE%/etc/firefox/retention/thank-you-a/",
+ expireDelta: TWO_DAYS,
+ },
+ },
+ },
+ trigger: { id: "momentsUpdate" },
+ },
+ {
+ id: "WHATS_NEW_FINGERPRINTER_COUNTER_72",
+ template: "whatsnew_panel_message",
+ order: 6,
+ content: {
+ bucket_id: "WHATS_NEW_72",
+ published_date: 1574776601000,
+ layout: "tracking-protections",
+ layout_title_content_variable: "fingerprinterCount",
+ title: { string_id: "cfr-whatsnew-fingerprinter-counter-header" },
+ subtitle: { string_id: "cfr-whatsnew-tracking-blocked-subtitle" },
+ icon_url:
+ "chrome://activity-stream/content/data/content/assets/protection-report-icon.png",
+ icon_alt: "",
+ body: { string_id: "cfr-whatsnew-fingerprinter-counter-body" },
+ link_text: { string_id: "cfr-whatsnew-tracking-blocked-link-text" },
+ cta_url: "",
+ cta_type: "OPEN_PROTECTION_REPORT",
+ },
+ targeting: `firefoxVersion >= 72`,
+ trigger: { id: "whatsNewPanelOpened" },
+ },
+ {
+ id: "WHATS_NEW_FINGERPRINTER_COUNTER_ALT",
+ template: "whatsnew_panel_message",
+ order: 6,
+ content: {
+ bucket_id: "WHATS_NEW_72",
+ published_date: 1574776601000,
+ title: { string_id: "cfr-whatsnew-fingerprinter-counter-header-alt" },
+ icon_url:
+ "chrome://activity-stream/content/data/content/assets/protection-report-icon.png",
+ icon_alt: "",
+ body: { string_id: "cfr-whatsnew-fingerprinter-counter-body-alt" },
+ link_text: { string_id: "cfr-whatsnew-tracking-blocked-link-text" },
+ cta_url: "",
+ cta_type: "OPEN_PROTECTION_REPORT",
+ },
+ targeting: `firefoxVersion >= 72`,
+ trigger: { id: "whatsNewPanelOpened" },
+ },
+ {
+ id: "WHATS_NEW_70_1",
+ template: "whatsnew_panel_message",
+ order: 3,
+ content: {
+ bucket_id: "WHATS_NEW_70_1",
+ published_date: 1560969794394,
+ title: "Protection Is Our Focus",
+ icon_url:
+ "chrome://activity-stream/content/data/content/assets/whatsnew-send-icon.png",
+ icon_alt: "Firefox Send Logo",
+ body:
+ "The New Enhanced Tracking Protection, gives you the best level of protection and performance. Discover how this version is the safest version of firefox ever made.",
+ cta_url: "https://blog.mozilla.org/",
+ cta_type: "OPEN_URL",
+ },
+ targeting: `firefoxVersion > 69`,
+ trigger: { id: "whatsNewPanelOpened" },
+ },
+ {
+ id: "WHATS_NEW_70_2",
+ template: "whatsnew_panel_message",
+ order: 1,
+ content: {
+ bucket_id: "WHATS_NEW_70_1",
+ published_date: 1560969794394,
+ title: "Another thing new in Firefox 70",
+ body:
+ "The New Enhanced Tracking Protection, gives you the best level of protection and performance. Discover how this version is the safest version of firefox ever made.",
+ link_text: "Learn more on our blog",
+ cta_url: "https://blog.mozilla.org/",
+ cta_type: "OPEN_URL",
+ },
+ targeting: `firefoxVersion > 69`,
+ trigger: { id: "whatsNewPanelOpened" },
+ },
+ {
+ id: "WHATS_NEW_SEARCH_SHORTCUTS_84",
+ template: "whatsnew_panel_message",
+ order: 2,
+ content: {
+ bucket_id: "WHATS_NEW_SEARCH_SHORTCUTS_84",
+ published_date: 1560969794394,
+ title: {
+ string_id: "cfr-whatsnew-search-shortcuts-header",
+ },
+ icon_url: "chrome://global/skin/icons/check.svg",
+ icon_alt: {
+ string_id: "cfr-whatsnew-searchbar-icon-alt-text",
+ },
+ body: {
+ string_id: "cfr-whatsnew-search-shortcuts-body",
+ },
+ cta_url:
+ "https://support.mozilla.org/1/firefox/%VERSION%/%OS%/%LOCALE%/search-shortcuts",
+ cta_type: "OPEN_URL",
+ link_text: {
+ string_id: "cfr-whatsnew-pip-cta",
+ },
+ },
+ targeting: "firefoxVersion >= 84",
+ trigger: {
+ id: "whatsNewPanelOpened",
+ },
+ },
+ {
+ id: "WHATS_NEW_PIONEER_82",
+ template: "whatsnew_panel_message",
+ order: 1,
+ content: {
+ bucket_id: "WHATS_NEW_PIONEER_82",
+ published_date: 1603152000000,
+ title: "Put your data to work for a better internet",
+ icon_url: "",
+ icon_alt: "",
+ body:
+ "Contribute your data to Mozilla's Pioneer program to help researchers understand pressing technology issues like misinformation, data privacy, and ethical AI.",
+ cta_url: "pioneer",
+ cta_where: "tab",
+ cta_type: "OPEN_ABOUT_PAGE",
+ link_text: "Join Pioneer",
+ },
+ targeting: "firefoxVersion >= 82",
+ trigger: {
+ id: "whatsNewPanelOpened",
+ },
+ },
+ {
+ id: "WHATS_NEW_MEDIA_SESSION_82",
+ template: "whatsnew_panel_message",
+ order: 3,
+ content: {
+ bucket_id: "WHATS_NEW_MEDIA_SESSION_82",
+ published_date: 1603152000000,
+ title: {
+ string_id: "cfr-whatsnew-media-keys-header",
+ },
+ body: {
+ string_id: "cfr-whatsnew-media-keys-body",
+ },
+ cta_url:
+ "https://support.mozilla.org/1/firefox/%VERSION%/%OS%/%LOCALE%/media-keyboard-control",
+ cta_type: "OPEN_URL",
+ link_text: {
+ string_id: "cfr-whatsnew-media-keys-button",
+ },
+ },
+ targeting: "firefoxVersion >= 82",
+ trigger: {
+ id: "whatsNewPanelOpened",
+ },
+ },
+ {
+ id: "WHATS_NEW_69_1",
+ template: "whatsnew_panel_message",
+ order: 1,
+ content: {
+ bucket_id: "WHATS_NEW_69_1",
+ published_date: 1557346235089,
+ title: "Something new in Firefox 69",
+ body:
+ "The New Enhanced Tracking Protection, gives you the best level of protection and performance. Discover how this version is the safest version of firefox ever made.",
+ link_text: "Learn more on our blog",
+ cta_url: "https://blog.mozilla.org/",
+ cta_type: "OPEN_URL",
+ },
+ targeting: `firefoxVersion > 68`,
+ trigger: { id: "whatsNewPanelOpened" },
+ },
+ {
+ id: "BOOKMARK_CFR",
+ template: "cfr_doorhanger",
+ groups: ["cfr"],
+ content: {
+ layout: "icon_and_message",
+ category: "cfrFeatures",
+ notification_text: { string_id: "cfr-doorhanger-feature-notification" },
+ heading_text: { string_id: "cfr-doorhanger-sync-bookmarks-header" },
+ info_icon: {
+ label: { string_id: "cfr-doorhanger-extension-sumo-link" },
+ sumo_path: "https://example.com",
+ },
+ text: { string_id: "cfr-doorhanger-sync-bookmarks-body" },
+ icon: "chrome://branding/content/icon64.png",
+ buttons: {
+ primary: {
+ label: { string_id: "cfr-doorhanger-sync-bookmarks-ok-button" },
+ action: {
+ type: "OPEN_PREFERENCES_PAGE",
+ data: { category: "sync" },
+ },
+ },
+ secondary: [
+ {
+ label: { string_id: "cfr-doorhanger-extension-cancel-button" },
+ action: { type: "CANCEL" },
+ },
+ {
+ label: {
+ string_id: "cfr-doorhanger-extension-never-show-recommendation",
+ },
+ },
+ {
+ label: {
+ string_id: "cfr-doorhanger-extension-manage-settings-button",
+ },
+ action: {
+ type: "OPEN_PREFERENCES_PAGE",
+ data: { category: "general-cfrfeatures" },
+ },
+ },
+ ],
+ },
+ },
+ targeting: "true",
+ trigger: {
+ id: "openBookmarkedURL",
+ },
+ },
+ {
+ id: "PERSONALIZED_CFR_MESSAGE",
+ template: "cfr_doorhanger",
+ groups: ["cfr"],
+ content: {
+ layout: "icon_and_message",
+ category: "cfrFeatures",
+ notification_text: "Personalized CFR Recommendation",
+ heading_text: { string_id: "cfr-doorhanger-firefox-send-header" },
+ info_icon: {
+ label: { string_id: "cfr-doorhanger-extension-sumo-link" },
+ sumo_path: "https://example.com",
+ },
+ text: { string_id: "cfr-doorhanger-firefox-send-body" },
+ icon: "chrome://branding/content/icon64.png",
+ buttons: {
+ primary: {
+ label: { string_id: "cfr-doorhanger-firefox-send-ok-button" },
+ action: {
+ type: "OPEN_URL",
+ data: {
+ args:
+ "https://send.firefox.com/login/?utm_source=activity-stream&entrypoint=activity-stream-cfr-pdf",
+ where: "tabshifted",
+ },
+ },
+ },
+ secondary: [
+ {
+ label: { string_id: "cfr-doorhanger-extension-cancel-button" },
+ action: { type: "CANCEL" },
+ },
+ {
+ label: {
+ string_id: "cfr-doorhanger-extension-never-show-recommendation",
+ },
+ },
+ {
+ label: {
+ string_id: "cfr-doorhanger-extension-manage-settings-button",
+ },
+ action: {
+ type: "OPEN_PREFERENCES_PAGE",
+ data: { category: "general-cfrfeatures" },
+ },
+ },
+ ],
+ },
+ },
+ targeting: "scores.PERSONALIZED_CFR_MESSAGE.score > scoreThreshold",
+ trigger: {
+ id: "openURL",
+ patterns: ["*://*/*.pdf"],
+ },
+ },
+];
+
+const PanelTestProvider = {
+ getMessages() {
+ return Promise.resolve(
+ MESSAGES().map(message => ({
+ ...message,
+ targeting: `providerCohorts.panel_local_testing == "SHOW_TEST"`,
+ }))
+ );
+ },
+};
+this.PanelTestProvider = PanelTestProvider;
+
+const EXPORTED_SYMBOLS = ["PanelTestProvider"];
diff --git a/browser/components/newtab/lib/PersistentCache.jsm b/browser/components/newtab/lib/PersistentCache.jsm
new file mode 100644
index 0000000000..e8024e27bc
--- /dev/null
+++ b/browser/components/newtab/lib/PersistentCache.jsm
@@ -0,0 +1,108 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
+const { XPCOMUtils } = ChromeUtils.import(
+ "resource://gre/modules/XPCOMUtils.jsm"
+);
+
+ChromeUtils.defineModuleGetter(this, "OS", "resource://gre/modules/osfile.jsm");
+XPCOMUtils.defineLazyGlobalGetters(this, ["fetch"]);
+
+/**
+ * A file (disk) based persistent cache of a JSON serializable object.
+ */
+this.PersistentCache = class PersistentCache {
+ /**
+ * Create a cache object based on a name.
+ *
+ * @param {string} name Name of the cache. It will be used to create the filename.
+ * @param {boolean} preload (optional). Whether the cache should be preloaded from file. Defaults to false.
+ */
+ constructor(name, preload = false) {
+ this.name = name;
+ this._filename = `activity-stream.${name}.json`;
+ if (preload) {
+ this._load();
+ }
+ }
+
+ /**
+ * Set a value to be cached with the specified key.
+ *
+ * @param {string} key The cache key.
+ * @param {object} value The data to be cached.
+ */
+ async set(key, value) {
+ const data = await this._load();
+ data[key] = value;
+ await this._persist(data);
+ }
+
+ /**
+ * Get a value from the cache.
+ *
+ * @param {string} key (optional) The cache key. If not provided, we return the full cache.
+ * @returns {object} The cached data.
+ */
+ async get(key) {
+ const data = await this._load();
+ return key ? data[key] : data;
+ }
+
+ /**
+ * Load the cache into memory if it isn't already.
+ */
+ _load() {
+ return (
+ this._cache ||
+ // eslint-disable-next-line no-async-promise-executor
+ (this._cache = new Promise(async (resolve, reject) => {
+ let filepath;
+ try {
+ filepath = OS.Path.join(
+ OS.Constants.Path.localProfileDir,
+ this._filename
+ );
+ } catch (error) {
+ reject(error);
+ return;
+ }
+
+ let file;
+ try {
+ file = await fetch(`file://${filepath}`);
+ } catch (error) {} // Cache file doesn't exist yet.
+
+ let data = {};
+ if (file) {
+ try {
+ data = await file.json();
+ } catch (error) {
+ Cu.reportError(
+ `Failed to parse ${this._filename}: ${error.message}`
+ );
+ }
+ }
+
+ resolve(data);
+ }))
+ );
+ }
+
+ /**
+ * Persist the cache to file.
+ */
+ _persist(data) {
+ const filepath = OS.Path.join(
+ OS.Constants.Path.localProfileDir,
+ this._filename
+ );
+ return OS.File.writeAtomic(filepath, JSON.stringify(data), {
+ tmpPath: `${filepath}.tmp`,
+ });
+ }
+};
+
+const EXPORTED_SYMBOLS = ["PersistentCache"];
diff --git a/browser/components/newtab/lib/PersonalityProvider/NaiveBayesTextTagger.jsm b/browser/components/newtab/lib/PersonalityProvider/NaiveBayesTextTagger.jsm
new file mode 100644
index 0000000000..cc625076ba
--- /dev/null
+++ b/browser/components/newtab/lib/PersonalityProvider/NaiveBayesTextTagger.jsm
@@ -0,0 +1,67 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+// We load this into a worker using importScripts, and in tests using import.
+// We use var to avoid name collision errors.
+// eslint-disable-next-line no-var
+var EXPORTED_SYMBOLS = ["NaiveBayesTextTagger"];
+
+const NaiveBayesTextTagger = class NaiveBayesTextTagger {
+ constructor(model, toksToTfIdfVector) {
+ this.model = model;
+ this.toksToTfIdfVector = toksToTfIdfVector;
+ }
+
+ /**
+ * Determines if the tokenized text belongs to class according to binary naive Bayes
+ * classifier. Returns an object containing the class label ("label"), and
+ * the log probability ("logProb") that the text belongs to that class. If
+ * the positive class is more likely, then "label" is the positive class
+ * label. If the negative class is matched, then "label" is set to null.
+ */
+ tagTokens(tokens) {
+ let fv = this.toksToTfIdfVector(tokens, this.model.vocab_idfs);
+
+ let bestLogProb = null;
+ let bestClassId = -1;
+ let bestClassLabel = null;
+ let logSumExp = 0.0; // will be P(x). Used to create a proper probability
+ for (let classId = 0; classId < this.model.classes.length; classId++) {
+ let classModel = this.model.classes[classId];
+ let classLogProb = classModel.log_prior;
+
+ // dot fv with the class model
+ for (let pair of Object.values(fv)) {
+ let [termId, tfidf] = pair;
+ classLogProb += tfidf * classModel.feature_log_probs[termId];
+ }
+
+ if (bestLogProb === null || classLogProb > bestLogProb) {
+ bestLogProb = classLogProb;
+ bestClassId = classId;
+ }
+ logSumExp += Math.exp(classLogProb);
+ }
+
+ // now normalize the probability by dividing by P(x)
+ logSumExp = Math.log(logSumExp);
+ bestLogProb -= logSumExp;
+ if (bestClassId === this.model.positive_class_id) {
+ bestClassLabel = this.model.positive_class_label;
+ } else {
+ bestClassLabel = null;
+ }
+
+ let confident =
+ bestClassId === this.model.positive_class_id &&
+ bestLogProb > this.model.positive_class_threshold_log_prob;
+ return {
+ label: bestClassLabel,
+ logProb: bestLogProb,
+ confident,
+ };
+ }
+};
diff --git a/browser/components/newtab/lib/PersonalityProvider/NmfTextTagger.jsm b/browser/components/newtab/lib/PersonalityProvider/NmfTextTagger.jsm
new file mode 100644
index 0000000000..639c92b6e4
--- /dev/null
+++ b/browser/components/newtab/lib/PersonalityProvider/NmfTextTagger.jsm
@@ -0,0 +1,65 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+// We load this into a worker using importScripts, and in tests using import.
+// We use var to avoid name collision errors.
+// eslint-disable-next-line no-var
+var EXPORTED_SYMBOLS = ["NmfTextTagger"];
+
+const NmfTextTagger = class NmfTextTagger {
+ constructor(model, toksToTfIdfVector) {
+ this.model = model;
+ this.toksToTfIdfVector = toksToTfIdfVector;
+ }
+
+ /**
+ * A multiclass classifier that scores tokenized text against several classes through
+ * inference of a nonnegative matrix factorization of TF-IDF vectors and
+ * class labels. Returns a map of class labels as string keys to scores.
+ * (Higher is more confident.) All classes get scored, so it is up to
+ * consumer of this data determine what classes are most valuable.
+ */
+ tagTokens(tokens) {
+ let fv = this.toksToTfIdfVector(tokens, this.model.vocab_idfs);
+ let fve = Object.values(fv);
+
+ // normalize by the sum of the vector
+ let sum = 0.0;
+ for (let pair of fve) {
+ // eslint-disable-next-line prefer-destructuring
+ sum += pair[1];
+ }
+ for (let i = 0; i < fve.length; i++) {
+ // eslint-disable-next-line prefer-destructuring
+ fve[i][1] /= sum;
+ }
+
+ // dot the document with each topic vector so that we can transform it into
+ // the latent space
+ let toksInLatentSpace = [];
+ for (let topicVect of this.model.topic_word) {
+ let fvDotTwv = 0;
+ // dot fv with each topic word vector
+ for (let pair of fve) {
+ let [termId, tfidf] = pair;
+ fvDotTwv += tfidf * topicVect[termId];
+ }
+ toksInLatentSpace.push(fvDotTwv);
+ }
+
+ // now project toksInLatentSpace back into class space
+ let predictions = {};
+ Object.keys(this.model.document_topic).forEach(topic => {
+ let score = 0;
+ for (let i = 0; i < toksInLatentSpace.length; i++) {
+ score += toksInLatentSpace[i] * this.model.document_topic[topic][i];
+ }
+ predictions[topic] = score;
+ });
+
+ return predictions;
+ }
+};
diff --git a/browser/components/newtab/lib/PersonalityProvider/PersonalityProvider.jsm b/browser/components/newtab/lib/PersonalityProvider/PersonalityProvider.jsm
new file mode 100644
index 0000000000..7d10b3c9a8
--- /dev/null
+++ b/browser/components/newtab/lib/PersonalityProvider/PersonalityProvider.jsm
@@ -0,0 +1,315 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
+ChromeUtils.defineModuleGetter(
+ this,
+ "RemoteSettings",
+ "resource://services-settings/remote-settings.js"
+);
+
+ChromeUtils.defineModuleGetter(
+ this,
+ "NewTabUtils",
+ "resource://gre/modules/NewTabUtils.jsm"
+);
+
+const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
+const { XPCOMUtils } = ChromeUtils.import(
+ "resource://gre/modules/XPCOMUtils.jsm"
+);
+
+ChromeUtils.defineModuleGetter(this, "OS", "resource://gre/modules/osfile.jsm");
+XPCOMUtils.defineLazyGlobalGetters(this, ["fetch"]);
+
+const { BasePromiseWorker } = ChromeUtils.import(
+ "resource://gre/modules/PromiseWorker.jsm"
+);
+
+const RECIPE_NAME = "personality-provider-recipe";
+const MODELS_NAME = "personality-provider-models";
+
+this.PersonalityProvider = class PersonalityProvider {
+ constructor(v2Params) {
+ this.v2Params = v2Params || {};
+ this.modelKeys = this.v2Params.modelKeys;
+ this.onSync = this.onSync.bind(this);
+ this.setup();
+ }
+
+ setAffinities(
+ timeSegments,
+ parameterSets,
+ maxHistoryQueryResults,
+ version,
+ scores
+ ) {
+ this.timeSegments = timeSegments;
+ this.parameterSets = parameterSets;
+ this.maxHistoryQueryResults = maxHistoryQueryResults;
+ this.version = version;
+ this.scores = scores || {};
+ this.interestConfig = this.scores.interestConfig;
+ this.interestVector = this.scores.interestVector;
+ }
+
+ get personalityProviderWorker() {
+ if (this._personalityProviderWorker) {
+ return this._personalityProviderWorker;
+ }
+
+ this._personalityProviderWorker = new BasePromiseWorker(
+ "resource://activity-stream/lib/PersonalityProvider/PersonalityProviderWorker.js"
+ );
+
+ // As the PersonalityProviderWorker performs I/O, we can receive instances of
+ // OS.File.Error, so we need to install a decoder.
+ this._personalityProviderWorker.ExceptionHandlers["OS.File.Error"] =
+ OS.File.Error.fromMsg;
+ return this._personalityProviderWorker;
+ }
+
+ get baseAttachmentsURL() {
+ // Returning a promise, so we can have an async getter.
+ return this._getBaseAttachmentsURL();
+ }
+
+ async _getBaseAttachmentsURL() {
+ if (this._baseAttachmentsURL) {
+ return this._baseAttachmentsURL;
+ }
+ const server = Services.prefs.getCharPref("services.settings.server");
+ const serverInfo = await (
+ await fetch(`${server}/`, {
+ credentials: "omit",
+ })
+ ).json();
+ const {
+ capabilities: {
+ attachments: { base_url },
+ },
+ } = serverInfo;
+ this._baseAttachmentsURL = base_url;
+ return this._baseAttachmentsURL;
+ }
+
+ setup() {
+ this.setupSyncAttachment(RECIPE_NAME);
+ this.setupSyncAttachment(MODELS_NAME);
+ }
+
+ teardown() {
+ this.teardownSyncAttachment(RECIPE_NAME);
+ this.teardownSyncAttachment(MODELS_NAME);
+ if (this._personalityProviderWorker) {
+ this._personalityProviderWorker.terminate();
+ }
+ }
+
+ setupSyncAttachment(collection) {
+ RemoteSettings(collection).on("sync", this.onSync);
+ }
+
+ teardownSyncAttachment(collection) {
+ RemoteSettings(collection).off("sync", this.onSync);
+ }
+
+ onSync(event) {
+ this.personalityProviderWorker.post("onSync", [event]);
+ }
+
+ /**
+ * Gets contents of the attachment if it already exists on file,
+ * and if not attempts to download it.
+ */
+ getAttachment(record) {
+ return this.personalityProviderWorker.post("getAttachment", [record]);
+ }
+
+ /**
+ * Returns a Recipe from remote settings to be consumed by a RecipeExecutor.
+ * A Recipe is a set of instructions on how to processes a RecipeExecutor.
+ */
+ async getRecipe() {
+ if (!this.recipes || !this.recipes.length) {
+ const result = await RemoteSettings(RECIPE_NAME).get();
+ this.recipes = await Promise.all(
+ result.map(async record => ({
+ ...(await this.getAttachment(record)),
+ recordKey: record.key,
+ }))
+ );
+ }
+ return this.recipes[0];
+ }
+
+ /**
+ * Grabs a slice of browse history for building a interest vector
+ */
+ async fetchHistory(columns, beginTimeSecs, endTimeSecs) {
+ let sql = `SELECT url, title, visit_count, frecency, last_visit_date, description
+ FROM moz_places
+ WHERE last_visit_date >= ${beginTimeSecs * 1000000}
+ AND last_visit_date < ${endTimeSecs * 1000000}`;
+ columns.forEach(requiredColumn => {
+ sql += ` AND IFNULL(${requiredColumn}, '') <> ''`;
+ });
+ sql += " LIMIT 30000";
+
+ const { activityStreamProvider } = NewTabUtils;
+ const history = await activityStreamProvider.executePlacesQuery(sql, {
+ columns,
+ params: {},
+ });
+
+ return history;
+ }
+
+ /**
+ * Handles setup and metrics of history fetch.
+ */
+ async getHistory() {
+ let endTimeSecs = new Date().getTime() / 1000;
+ let beginTimeSecs = endTimeSecs - this.interestConfig.history_limit_secs;
+ if (
+ !this.interestConfig ||
+ !this.interestConfig.history_required_fields ||
+ !this.interestConfig.history_required_fields.length
+ ) {
+ return [];
+ }
+ let history = await this.fetchHistory(
+ this.interestConfig.history_required_fields,
+ beginTimeSecs,
+ endTimeSecs
+ );
+
+ return history;
+ }
+
+ async setBaseAttachmentsURL() {
+ await this.personalityProviderWorker.post("setBaseAttachmentsURL", [
+ await this.baseAttachmentsURL,
+ ]);
+ }
+
+ async setInterestConfig() {
+ this.interestConfig = this.interestConfig || (await this.getRecipe());
+ await this.personalityProviderWorker.post("setInterestConfig", [
+ this.interestConfig,
+ ]);
+ }
+
+ async setInterestVector() {
+ await this.personalityProviderWorker.post("setInterestVector", [
+ this.interestVector,
+ ]);
+ }
+
+ async fetchModels() {
+ const models = await RemoteSettings(MODELS_NAME).get();
+ return this.personalityProviderWorker.post("fetchModels", [models]);
+ }
+
+ async generateTaggers() {
+ await this.personalityProviderWorker.post("generateTaggers", [
+ this.modelKeys,
+ ]);
+ }
+
+ async generateRecipeExecutor() {
+ await this.personalityProviderWorker.post("generateRecipeExecutor");
+ }
+
+ async createInterestVector() {
+ const history = await this.getHistory();
+
+ const interestVectorResult = await this.personalityProviderWorker.post(
+ "createInterestVector",
+ [history]
+ );
+
+ return interestVectorResult;
+ }
+
+ async init(callback) {
+ await this.setBaseAttachmentsURL();
+ await this.setInterestConfig();
+ if (!this.interestConfig) {
+ return;
+ }
+
+ // We always generate a recipe executor, no cache used here.
+ // This is because the result of this is an object with
+ // functions (taggers) so storing it in cache is not possible.
+ // Thus we cannot use it to rehydrate anything.
+ const fetchModelsResult = await this.fetchModels();
+ // If this fails, log an error and return.
+ if (!fetchModelsResult.ok) {
+ return;
+ }
+ await this.generateTaggers();
+ await this.generateRecipeExecutor();
+
+ // If we don't have a cached vector, create a new one.
+ if (!this.interestVector) {
+ const interestVectorResult = await this.createInterestVector();
+ // If that failed, log an error and return.
+ if (!interestVectorResult.ok) {
+ return;
+ }
+ this.interestVector = interestVectorResult.interestVector;
+ }
+
+ // This happens outside the createInterestVector call above,
+ // because create can be skipped if rehydrating from cache.
+ // In that case, the interest vector is provided and not created, so we just set it.
+ await this.setInterestVector();
+
+ this.initialized = true;
+ if (callback) {
+ callback();
+ }
+ }
+
+ async calculateItemRelevanceScore(pocketItem) {
+ if (!this.initialized) {
+ return pocketItem.item_score || 1;
+ }
+ const itemRelevanceScore = await this.personalityProviderWorker.post(
+ "calculateItemRelevanceScore",
+ [pocketItem]
+ );
+ if (!itemRelevanceScore) {
+ return -1;
+ }
+ const { scorableItem, rankingVector } = itemRelevanceScore;
+ // Put the results on the item for debugging purposes.
+ pocketItem.scorableItem = scorableItem;
+ pocketItem.rankingVector = rankingVector;
+ return rankingVector.score;
+ }
+
+ /**
+ * Returns an object holding the settings and affinity scores of this provider instance.
+ */
+ getAffinities() {
+ return {
+ timeSegments: this.timeSegments,
+ parameterSets: this.parameterSets,
+ maxHistoryQueryResults: this.maxHistoryQueryResults,
+ version: this.version,
+ scores: {
+ // We cannot return taggers here.
+ // What we return here goes into persistent cache, and taggers have functions on it.
+ // If we attempted to save taggers into persistent cache, it would store it to disk,
+ // and the next time we load it, it would start thowing function is not defined.
+ interestConfig: this.interestConfig,
+ interestVector: this.interestVector,
+ },
+ };
+ }
+};
+
+const EXPORTED_SYMBOLS = ["PersonalityProvider"];
diff --git a/browser/components/newtab/lib/PersonalityProvider/PersonalityProviderWorker.js b/browser/components/newtab/lib/PersonalityProvider/PersonalityProviderWorker.js
new file mode 100644
index 0000000000..145b26e3ec
--- /dev/null
+++ b/browser/components/newtab/lib/PersonalityProvider/PersonalityProviderWorker.js
@@ -0,0 +1,37 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* eslint-env mozilla/chrome-worker */
+
+"use strict";
+
+// Order of these are important.
+importScripts(
+ "resource://gre/modules/workers/require.js",
+ "resource://gre/modules/osfile.jsm",
+ "resource://activity-stream/lib/PersonalityProvider/Tokenize.jsm",
+ "resource://activity-stream/lib/PersonalityProvider/NaiveBayesTextTagger.jsm",
+ "resource://activity-stream/lib/PersonalityProvider/NmfTextTagger.jsm",
+ "resource://activity-stream/lib/PersonalityProvider/RecipeExecutor.jsm",
+ "resource://activity-stream/lib/PersonalityProvider/PersonalityProviderWorkerClass.jsm"
+);
+
+const PromiseWorker = require("resource://gre/modules/workers/PromiseWorker.js");
+
+// eslint-disable-next-line no-undef
+const personalityProviderWorker = new PersonalityProviderWorker();
+
+// This is boiler plate worker stuff that connects it to the main thread PromiseWorker.
+const worker = new PromiseWorker.AbstractWorker();
+worker.dispatch = function(method, args = []) {
+ return personalityProviderWorker[method](...args);
+};
+worker.postMessage = function(message, ...transfers) {
+ self.postMessage(message, ...transfers);
+};
+worker.close = function() {
+ self.close();
+};
+
+self.addEventListener("message", msg => worker.handleMessage(msg));
diff --git a/browser/components/newtab/lib/PersonalityProvider/PersonalityProviderWorkerClass.jsm b/browser/components/newtab/lib/PersonalityProvider/PersonalityProviderWorkerClass.jsm
new file mode 100644
index 0000000000..efb415044a
--- /dev/null
+++ b/browser/components/newtab/lib/PersonalityProvider/PersonalityProviderWorkerClass.jsm
@@ -0,0 +1,279 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+// We load this into a worker using importScripts, and in tests using import.
+// We use var to avoid name collision errors.
+// eslint-disable-next-line no-var
+var EXPORTED_SYMBOLS = ["PersonalityProviderWorker"];
+
+const PERSONALITY_PROVIDER_DIR = OS.Path.join(
+ OS.Constants.Path.localProfileDir,
+ "personality-provider"
+);
+
+/**
+ * V2 provider builds and ranks an interest profile (also called an “interest vector”) off the browse history.
+ * This allows Firefox to classify pages into topics, by examining the text found on the page.
+ * It does this by looking at the history text content, title, and description.
+ */
+const PersonalityProviderWorker = class PersonalityProviderWorker {
+ // A helper function to read and decode a file, it isn't a stand alone function.
+ // If you use this, ensure you check the file exists and you have a try catch.
+ _getFileStr(filepath) {
+ const binaryData = OS.File.read(filepath);
+ const gTextDecoder = new TextDecoder();
+ return gTextDecoder.decode(binaryData);
+ }
+
+ setBaseAttachmentsURL(url) {
+ this.baseAttachmentsURL = url;
+ }
+
+ setInterestConfig(interestConfig) {
+ this.interestConfig = interestConfig;
+ }
+
+ setInterestVector(interestVector) {
+ this.interestVector = interestVector;
+ }
+
+ onSync(event) {
+ const {
+ data: { created, updated, deleted },
+ } = event;
+ // Remove every removed attachment.
+ const toRemove = deleted.concat(updated.map(u => u.old));
+ toRemove.map(record => this.deleteAttachment(record));
+
+ // Download every new/updated attachment.
+ const toDownload = created.concat(updated.map(u => u.new));
+ toDownload.map(record => this.maybeDownloadAttachment(record));
+ }
+
+ /**
+ * Attempts to download the attachment, but only if it doesn't already exist.
+ */
+ maybeDownloadAttachment(record, retries = 3) {
+ const {
+ attachment: { filename, size },
+ } = record;
+ OS.File.makeDir(PERSONALITY_PROVIDER_DIR);
+ const localFilePath = OS.Path.join(PERSONALITY_PROVIDER_DIR, filename);
+
+ let retry = 0;
+ while (
+ retry++ < retries &&
+ // exists is an issue for perf because I might not need to call it.
+ (!OS.File.exists(localFilePath) ||
+ OS.File.stat(localFilePath).size !== size)
+ ) {
+ this._downloadAttachment(record);
+ }
+ }
+
+ /**
+ * Downloads the attachment to disk assuming the dir already exists
+ * and any existing files matching the filename are clobbered.
+ */
+ _downloadAttachment(record) {
+ const {
+ attachment: { location, filename },
+ } = record;
+ const remoteFilePath = this.baseAttachmentsURL + location;
+ const localFilePath = OS.Path.join(PERSONALITY_PROVIDER_DIR, filename);
+
+ const xhr = new XMLHttpRequest();
+ // Set false here for a synchronous request, because we're in a worker.
+ xhr.open("GET", remoteFilePath, false);
+ xhr.setRequestHeader("Accept-Encoding", "gzip");
+ xhr.responseType = "arraybuffer";
+ xhr.withCredentials = false;
+ xhr.send(null);
+
+ if (xhr.status !== 200) {
+ console.error(`Failed to fetch ${remoteFilePath}: ${xhr.statusText}`);
+ return;
+ }
+
+ const buffer = xhr.response;
+ const bytes = new Uint8Array(buffer);
+
+ OS.File.writeAtomic(localFilePath, bytes, {
+ tmpPath: `${localFilePath}.tmp`,
+ });
+ }
+
+ deleteAttachment(record) {
+ const {
+ attachment: { filename },
+ } = record;
+ OS.File.makeDir(PERSONALITY_PROVIDER_DIR);
+ const path = OS.Path.join(PERSONALITY_PROVIDER_DIR, filename);
+
+ OS.File.remove(path, { ignoreAbsent: true });
+ OS.File.removeEmptyDir(PERSONALITY_PROVIDER_DIR, {
+ ignoreAbsent: true,
+ });
+ }
+
+ /**
+ * Gets contents of the attachment if it already exists on file,
+ * and if not attempts to download it.
+ */
+ getAttachment(record) {
+ const {
+ attachment: { filename },
+ } = record;
+ const filepath = OS.Path.join(PERSONALITY_PROVIDER_DIR, filename);
+
+ try {
+ this.maybeDownloadAttachment(record);
+ return JSON.parse(this._getFileStr(filepath));
+ } catch (error) {
+ console.error(`Failed to load ${filepath}: ${error.message}`);
+ }
+ return {};
+ }
+
+ fetchModels(models) {
+ this.models = models.map(record => ({
+ ...this.getAttachment(record),
+ recordKey: record.key,
+ }));
+ if (!this.models.length) {
+ return {
+ ok: false,
+ };
+ }
+ return {
+ ok: true,
+ };
+ }
+
+ generateTaggers(modelKeys) {
+ if (!this.taggers) {
+ let nbTaggers = [];
+ let nmfTaggers = {};
+
+ for (let model of this.models) {
+ if (!modelKeys.includes(model.recordKey)) {
+ continue;
+ }
+ if (model.model_type === "nb") {
+ // eslint-disable-next-line no-undef
+ nbTaggers.push(new NaiveBayesTextTagger(model, toksToTfIdfVector));
+ } else if (model.model_type === "nmf") {
+ // eslint-disable-next-line no-undef
+ nmfTaggers[model.parent_tag] = new NmfTextTagger(
+ model,
+ // eslint-disable-next-line no-undef
+ toksToTfIdfVector
+ );
+ }
+ }
+ this.taggers = { nbTaggers, nmfTaggers };
+ }
+ }
+
+ /**
+ * Sets and generates a Recipe Executor.
+ * A Recipe Executor is a set of actions that can be consumed by a Recipe.
+ * The Recipe determines the order and specifics of which the actions are called.
+ */
+ generateRecipeExecutor() {
+ // eslint-disable-next-line no-undef
+ const recipeExecutor = new RecipeExecutor(
+ this.taggers.nbTaggers,
+ this.taggers.nmfTaggers,
+ // eslint-disable-next-line no-undef
+ tokenize
+ );
+ this.recipeExecutor = recipeExecutor;
+ }
+
+ /**
+ * Examines the user's browse history and returns an interest vector that
+ * describes the topics the user frequently browses.
+ */
+ createInterestVector(history) {
+ let interestVector = {};
+
+ for (let historyRec of history) {
+ let ivItem = this.recipeExecutor.executeRecipe(
+ historyRec,
+ this.interestConfig.history_item_builder
+ );
+ if (ivItem === null) {
+ continue;
+ }
+ interestVector = this.recipeExecutor.executeCombinerRecipe(
+ interestVector,
+ ivItem,
+ this.interestConfig.interest_combiner
+ );
+ if (interestVector === null) {
+ return null;
+ }
+ }
+
+ const finalResult = this.recipeExecutor.executeRecipe(
+ interestVector,
+ this.interestConfig.interest_finalizer
+ );
+
+ return {
+ ok: true,
+ interestVector: finalResult,
+ };
+ }
+
+ /**
+ * Calculates a score of a Pocket item when compared to the user's interest
+ * vector. Returns the score. Higher scores are better. Assumes this.interestVector
+ * is populated.
+ */
+ calculateItemRelevanceScore(pocketItem) {
+ const { personalization_models } = pocketItem;
+ let scorableItem;
+
+ // If the server provides some models, we can just use them,
+ // and skip generating them.
+ if (personalization_models && Object.keys(personalization_models).length) {
+ scorableItem = {
+ id: pocketItem.id,
+ item_tags: personalization_models,
+ item_score: pocketItem.item_score,
+ item_sort_id: 1,
+ };
+ } else {
+ scorableItem = this.recipeExecutor.executeRecipe(
+ pocketItem,
+ this.interestConfig.item_to_rank_builder
+ );
+ if (scorableItem === null) {
+ return null;
+ }
+ }
+
+ // We're doing a deep copy on an object.
+ let rankingVector = JSON.parse(JSON.stringify(this.interestVector));
+
+ Object.keys(scorableItem).forEach(key => {
+ rankingVector[key] = scorableItem[key];
+ });
+
+ rankingVector = this.recipeExecutor.executeRecipe(
+ rankingVector,
+ this.interestConfig.item_ranker
+ );
+
+ if (rankingVector === null) {
+ return null;
+ }
+
+ return { scorableItem, rankingVector };
+ }
+};
diff --git a/browser/components/newtab/lib/PersonalityProvider/RecipeExecutor.jsm b/browser/components/newtab/lib/PersonalityProvider/RecipeExecutor.jsm
new file mode 100644
index 0000000000..9dbf8b802d
--- /dev/null
+++ b/browser/components/newtab/lib/PersonalityProvider/RecipeExecutor.jsm
@@ -0,0 +1,1126 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+// We load this into a worker using importScripts, and in tests using import.
+// We use var to avoid name collision errors.
+// eslint-disable-next-line no-var
+var EXPORTED_SYMBOLS = ["RecipeExecutor"];
+
+/**
+ * RecipeExecutor is the core feature engineering pipeline for the in-browser
+ * personalization work. These pipelines are called "recipes". A recipe is an
+ * array of objects that define a "step" in the recipe. A step is simply an
+ * object with a field "function" that specifies what is being done in the step
+ * along with other fields that are semantically defined for that step.
+ *
+ * There are two types of recipes "builder" recipes and "combiner" recipes. Builder
+ * recipes mutate an object until it matches some set of critera. Combiner
+ * recipes take two objects, (a "left" and a "right"), and specify the steps
+ * to merge the right object into the left object.
+ *
+ * A short nonsense example recipe is:
+ * [ {"function": "get_url_domain", "path_length": 1, "field": "url", "dest": "url_domain"},
+ * {"function": "nb_tag", "fields": ["title", "description"]},
+ * {"function": "conditionally_nmf_tag", "fields": ["title", "description"]} ]
+ *
+ * Recipes are sandboxed by the fact that the step functions must be explicitly
+ * allowed. Functions allowed for builder recipes are specifed in the
+ * RecipeExecutor.ITEM_BUILDER_REGISTRY, while combiner functions are allowed
+ * in RecipeExecutor.ITEM_COMBINER_REGISTRY .
+ */
+const RecipeExecutor = class RecipeExecutor {
+ constructor(nbTaggers, nmfTaggers, tokenize) {
+ this.ITEM_BUILDER_REGISTRY = {
+ nb_tag: this.naiveBayesTag,
+ conditionally_nmf_tag: this.conditionallyNmfTag,
+ accept_item_by_field_value: this.acceptItemByFieldValue,
+ tokenize_url: this.tokenizeUrl,
+ get_url_domain: this.getUrlDomain,
+ tokenize_field: this.tokenizeField,
+ copy_value: this.copyValue,
+ keep_top_k: this.keepTopK,
+ scalar_multiply: this.scalarMultiply,
+ elementwise_multiply: this.elementwiseMultiply,
+ vector_multiply: this.vectorMultiply,
+ scalar_add: this.scalarAdd,
+ vector_add: this.vectorAdd,
+ make_boolean: this.makeBoolean,
+ allow_fields: this.allowFields,
+ filter_by_value: this.filterByValue,
+ l2_normalize: this.l2Normalize,
+ prob_normalize: this.probNormalize,
+ set_default: this.setDefault,
+ lookup_value: this.lookupValue,
+ copy_to_map: this.copyToMap,
+ scalar_multiply_tag: this.scalarMultiplyTag,
+ apply_softmax_tags: this.applySoftmaxTags,
+ };
+ this.ITEM_COMBINER_REGISTRY = {
+ combiner_add: this.combinerAdd,
+ combiner_max: this.combinerMax,
+ combiner_collect_values: this.combinerCollectValues,
+ };
+ this.nbTaggers = nbTaggers;
+ this.nmfTaggers = nmfTaggers;
+ this.tokenize = tokenize;
+ }
+
+ /**
+ * Determines the type of a field. Valid types are:
+ * string
+ * number
+ * array
+ * map (strings to anything)
+ */
+ _typeOf(data) {
+ let t = typeof data;
+ if (t === "object") {
+ if (data === null) {
+ return "null";
+ }
+ if (Array.isArray(data)) {
+ return "array";
+ }
+ return "map";
+ }
+ return t;
+ }
+
+ /**
+ * Returns a scalar, either because it was a constant, or by
+ * looking it up from the item. Allows for a default value if the lookup
+ * fails.
+ */
+ _lookupScalar(item, k, dfault) {
+ if (this._typeOf(k) === "number") {
+ return k;
+ } else if (
+ this._typeOf(k) === "string" &&
+ k in item &&
+ this._typeOf(item[k]) === "number"
+ ) {
+ return item[k];
+ }
+ return dfault;
+ }
+
+ /**
+ * Simply appends all the strings from a set fields together. If the field
+ * is a list, then the cells of the list are append.
+ */
+ _assembleText(item, fields) {
+ let textArr = [];
+ for (let field of fields) {
+ if (field in item) {
+ let type = this._typeOf(item[field]);
+ if (type === "string") {
+ textArr.push(item[field]);
+ } else if (type === "array") {
+ for (let ele of item[field]) {
+ textArr.push(String(ele));
+ }
+ } else {
+ textArr.push(String(item[field]));
+ }
+ }
+ }
+ return textArr.join(" ");
+ }
+
+ /**
+ * Runs the naive bayes text taggers over a set of text fields. Stores the
+ * results in new fields:
+ * nb_tags: a map of text strings to probabilites
+ * nb_tokens: the tokenized text that was tagged
+ *
+ * Config:
+ * fields: an array containing a list of fields to concatenate and tag
+ */
+ naiveBayesTag(item, config) {
+ let text = this._assembleText(item, config.fields);
+ let tokens = this.tokenize(text);
+ let tags = {};
+ let extended_tags = {};
+
+ for (let nbTagger of this.nbTaggers) {
+ let result = nbTagger.tagTokens(tokens);
+ if (result.label !== null && result.confident) {
+ extended_tags[result.label] = result;
+ tags[result.label] = Math.exp(result.logProb);
+ }
+ }
+ item.nb_tags = tags;
+ item.nb_tags_extended = extended_tags;
+ item.nb_tokens = tokens;
+ return item;
+ }
+
+ /**
+ * Selectively runs NMF text taggers depending on which tags were found
+ * by the naive bayes taggers. Writes the results in into new fields:
+ * nmf_tags_parent_weights: map of pareent tags to probabilites of those parent tags
+ * nmf_tags: map of strings to maps of strings to probabilities
+ * nmf_tags_parent map of child tags to parent tags
+ *
+ * Config:
+ * Not configurable
+ */
+ conditionallyNmfTag(item, config) {
+ let nestedNmfTags = {};
+ let parentTags = {};
+ let parentWeights = {};
+
+ if (!("nb_tags" in item) || !("nb_tokens" in item)) {
+ return null;
+ }
+
+ Object.keys(item.nb_tags).forEach(parentTag => {
+ let nmfTagger = this.nmfTaggers[parentTag];
+ if (nmfTagger !== undefined) {
+ nestedNmfTags[parentTag] = {};
+ parentWeights[parentTag] = item.nb_tags[parentTag];
+ let nmfTags = nmfTagger.tagTokens(item.nb_tokens);
+ Object.keys(nmfTags).forEach(nmfTag => {
+ nestedNmfTags[parentTag][nmfTag] = nmfTags[nmfTag];
+ parentTags[nmfTag] = parentTag;
+ });
+ }
+ });
+
+ item.nmf_tags = nestedNmfTags;
+ item.nmf_tags_parent = parentTags;
+ item.nmf_tags_parent_weights = parentWeights;
+
+ return item;
+ }
+
+ /**
+ * Checks a field's value against another value (either from another field
+ * or a constant). If the test passes, then the item is emitted, otherwise
+ * the pipeline is aborted.
+ *
+ * Config:
+ * field Field to read the value to test. Left side of operator.
+ * op one of ==, !=, <, <=, >, >=
+ * rhsValue Constant value to compare against. Right side of operator.
+ * rhsField Field to read value to compare against. Right side of operator.
+ *
+ * NOTE: rhsValue takes precidence over rhsField.
+ */
+ acceptItemByFieldValue(item, config) {
+ if (!(config.field in item)) {
+ return null;
+ }
+ let rhs = null;
+ if ("rhsValue" in config) {
+ rhs = config.rhsValue;
+ } else if ("rhsField" in config && config.rhsField in item) {
+ rhs = item[config.rhsField];
+ }
+ if (rhs === null) {
+ return null;
+ }
+
+ if (
+ // eslint-disable-next-line eqeqeq
+ (config.op === "==" && item[config.field] == rhs) ||
+ // eslint-disable-next-line eqeqeq
+ (config.op === "!=" && item[config.field] != rhs) ||
+ (config.op === "<" && item[config.field] < rhs) ||
+ (config.op === "<=" && item[config.field] <= rhs) ||
+ (config.op === ">" && item[config.field] > rhs) ||
+ (config.op === ">=" && item[config.field] >= rhs)
+ ) {
+ return item;
+ }
+
+ return null;
+ }
+
+ /**
+ * Splits a URL into text-like tokens.
+ *
+ * Config:
+ * field Field containing a URL
+ * dest Field to write the tokens to as an array of strings
+ *
+ * NOTE: Any initial 'www' on the hostname is removed.
+ */
+ tokenizeUrl(item, config) {
+ if (!(config.field in item)) {
+ return null;
+ }
+
+ let url = new URL(item[config.field]);
+ let domain = url.hostname;
+ if (domain.startsWith("www.")) {
+ domain = domain.substring(4);
+ }
+ let toks = this.tokenize(domain);
+ let pathToks = this.tokenize(
+ decodeURIComponent(url.pathname.replace(/\+/g, " "))
+ );
+ for (let tok of pathToks) {
+ toks.push(tok);
+ }
+ for (let pair of url.searchParams.entries()) {
+ let k = this.tokenize(decodeURIComponent(pair[0].replace(/\+/g, " ")));
+ for (let tok of k) {
+ toks.push(tok);
+ }
+ if (pair[1] !== null && pair[1] !== "") {
+ let v = this.tokenize(decodeURIComponent(pair[1].replace(/\+/g, " ")));
+ for (let tok of v) {
+ toks.push(tok);
+ }
+ }
+ }
+ item[config.dest] = toks;
+
+ return item;
+ }
+
+ /**
+ * Gets the hostname (minus any initial "www." along with the left most
+ * directories on the path.
+ *
+ * Config:
+ * field Field containing the URL
+ * dest Field to write the array of strings to
+ * path_length OPTIONAL (DEFAULT: 0) Number of leftmost subdirectories to include
+ */
+ getUrlDomain(item, config) {
+ if (!(config.field in item)) {
+ return null;
+ }
+
+ let url = new URL(item[config.field]);
+ let domain = url.hostname.toLocaleLowerCase();
+ if (domain.startsWith("www.")) {
+ domain = domain.substring(4);
+ }
+ item[config.dest] = domain;
+ let pathLength = 0;
+ if ("path_length" in config) {
+ pathLength = config.path_length;
+ }
+ if (pathLength > 0) {
+ item[config.dest] += url.pathname
+ .toLocaleLowerCase()
+ .split("/")
+ .slice(0, pathLength + 1)
+ .join("/");
+ }
+
+ return item;
+ }
+
+ /**
+ * Splits a field into tokens.
+ * Config:
+ * field Field containing a string to tokenize
+ * dest Field to write the array of strings to
+ */
+ tokenizeField(item, config) {
+ if (!(config.field in item)) {
+ return null;
+ }
+
+ item[config.dest] = this.tokenize(item[config.field]);
+
+ return item;
+ }
+
+ /**
+ * Deep copy from one field to another.
+ * Config:
+ * src Field to read from
+ * dest Field to write to
+ */
+ copyValue(item, config) {
+ if (!(config.src in item)) {
+ return null;
+ }
+
+ item[config.dest] = JSON.parse(JSON.stringify(item[config.src]));
+
+ return item;
+ }
+
+ /**
+ * Converts a field containing a map of strings to a map of strings
+ * to numbers, to a map of strings to numbers containing at most k elements.
+ * This operation is performed by first, promoting all the subkeys up one
+ * level, and then taking the top (or bottom) k values.
+ *
+ * Config:
+ * field Points to a map of strings to a map of strings to numbers
+ * k Maximum number of items to keep
+ * descending OPTIONAL (DEFAULT: True) Sorts score in descending order
+ * (i.e. keeps maximum)
+ */
+ keepTopK(item, config) {
+ if (!(config.field in item)) {
+ return null;
+ }
+ let k = this._lookupScalar(item, config.k, 1048576);
+ let descending = !("descending" in config) || config.descending !== false;
+
+ // we can't sort by the values in the map, so we have to convert this
+ // to an array, and then sort.
+ let sortable = [];
+ Object.keys(item[config.field]).forEach(outerKey => {
+ let innerType = this._typeOf(item[config.field][outerKey]);
+ if (innerType === "map") {
+ Object.keys(item[config.field][outerKey]).forEach(innerKey => {
+ sortable.push({
+ key: innerKey,
+ value: item[config.field][outerKey][innerKey],
+ });
+ });
+ } else {
+ sortable.push({ key: outerKey, value: item[config.field][outerKey] });
+ }
+ });
+
+ sortable.sort((a, b) => {
+ if (descending) {
+ return b.value - a.value;
+ }
+ return a.value - b.value;
+ });
+
+ // now take the top k
+ let newMap = {};
+ let i = 0;
+ for (let pair of sortable) {
+ if (i >= k) {
+ break;
+ }
+ newMap[pair.key] = pair.value;
+ i++;
+ }
+ item[config.field] = newMap;
+
+ return item;
+ }
+
+ /**
+ * Scalar multiplies a vector by some constant
+ *
+ * Config:
+ * field Points to:
+ * a map of strings to numbers
+ * an array of numbers
+ * a number
+ * k Either a number, or a string. If it's a number then This
+ * is the scalar value to multiply by. If it's a string,
+ * the value in the pointed to field is used.
+ * default OPTIONAL (DEFAULT: 0), If k is a string, and no numeric
+ * value is found, then use this value.
+ */
+ scalarMultiply(item, config) {
+ if (!(config.field in item)) {
+ return null;
+ }
+ let k = this._lookupScalar(item, config.k, config.dfault);
+
+ let fieldType = this._typeOf(item[config.field]);
+ if (fieldType === "number") {
+ item[config.field] *= k;
+ } else if (fieldType === "array") {
+ for (let i = 0; i < item[config.field].length; i++) {
+ item[config.field][i] *= k;
+ }
+ } else if (fieldType === "map") {
+ Object.keys(item[config.field]).forEach(key => {
+ item[config.field][key] *= k;
+ });
+ } else {
+ return null;
+ }
+
+ return item;
+ }
+
+ /**
+ * Elementwise multiplies either two maps or two arrays together, storing
+ * the result in left. If left and right are of the same type, results in an
+ * error.
+ *
+ * Maps are special case. For maps the left must be a nested map such as:
+ * { k1: { k11: 1, k12: 2}, k2: { k21: 3, k22: 4 } } and right needs to be
+ * simple map such as: { k1: 5, k2: 6} . The operation is then to mulitply
+ * every value of every right key, to every value every subkey where the
+ * parent keys match. Using the previous examples, the result would be:
+ * { k1: { k11: 5, k12: 10 }, k2: { k21: 18, k22: 24 } } .
+ *
+ * Config:
+ * left
+ * right
+ */
+ elementwiseMultiply(item, config) {
+ if (!(config.left in item) || !(config.right in item)) {
+ return null;
+ }
+ let leftType = this._typeOf(item[config.left]);
+ if (leftType !== this._typeOf(item[config.right])) {
+ return null;
+ }
+ if (leftType === "array") {
+ if (item[config.left].length !== item[config.right].length) {
+ return null;
+ }
+ for (let i = 0; i < item[config.left].length; i++) {
+ item[config.left][i] *= item[config.right][i];
+ }
+ } else if (leftType === "map") {
+ Object.keys(item[config.left]).forEach(outerKey => {
+ let r = 0.0;
+ if (outerKey in item[config.right]) {
+ r = item[config.right][outerKey];
+ }
+ Object.keys(item[config.left][outerKey]).forEach(innerKey => {
+ item[config.left][outerKey][innerKey] *= r;
+ });
+ });
+ } else if (leftType === "number") {
+ item[config.left] *= item[config.right];
+ } else {
+ return null;
+ }
+
+ return item;
+ }
+
+ /**
+ * Vector multiplies (i.e. dot products) two vectors and stores the result in
+ * third field. Both vectors must either by maps, or arrays of numbers with
+ * the same length.
+ *
+ * Config:
+ * left A field pointing to either a map of strings to numbers,
+ * or an array of numbers
+ * right A field pointing to either a map of strings to numbers,
+ * or an array of numbers
+ * dest The field to store the dot product.
+ */
+ vectorMultiply(item, config) {
+ if (!(config.left in item) || !(config.right in item)) {
+ return null;
+ }
+
+ let leftType = this._typeOf(item[config.left]);
+ if (leftType !== this._typeOf(item[config.right])) {
+ return null;
+ }
+
+ let destVal = 0.0;
+ if (leftType === "array") {
+ if (item[config.left].length !== item[config.right].length) {
+ return null;
+ }
+ for (let i = 0; i < item[config.left].length; i++) {
+ destVal += item[config.left][i] * item[config.right][i];
+ }
+ } else if (leftType === "map") {
+ Object.keys(item[config.left]).forEach(key => {
+ if (key in item[config.right]) {
+ destVal += item[config.left][key] * item[config.right][key];
+ }
+ });
+ } else {
+ return null;
+ }
+
+ item[config.dest] = destVal;
+ return item;
+ }
+
+ /**
+ * Adds a constant value to all elements in the field. Mathematically,
+ * this is the same as taking a 1-vector, scalar multiplying it by k,
+ * and then vector adding it to a field.
+ *
+ * Config:
+ * field A field pointing to either a map of strings to numbers,
+ * or an array of numbers
+ * k Either a number, or a string. If it's a number then This
+ * is the scalar value to multiply by. If it's a string,
+ * the value in the pointed to field is used.
+ * default OPTIONAL (DEFAULT: 0), If k is a string, and no numeric
+ * value is found, then use this value.
+ */
+ scalarAdd(item, config) {
+ let k = this._lookupScalar(item, config.k, config.dfault);
+ if (!(config.field in item)) {
+ return null;
+ }
+
+ let fieldType = this._typeOf(item[config.field]);
+ if (fieldType === "array") {
+ for (let i = 0; i < item[config.field].length; i++) {
+ item[config.field][i] += k;
+ }
+ } else if (fieldType === "map") {
+ Object.keys(item[config.field]).forEach(key => {
+ item[config.field][key] += k;
+ });
+ } else if (fieldType === "number") {
+ item[config.field] += k;
+ } else {
+ return null;
+ }
+
+ return item;
+ }
+
+ /**
+ * Adds two vectors together and stores the result in left.
+ *
+ * Config:
+ * left A field pointing to either a map of strings to numbers,
+ * or an array of numbers
+ * right A field pointing to either a map of strings to numbers,
+ * or an array of numbers
+ */
+ vectorAdd(item, config) {
+ if (!(config.left in item)) {
+ return this.copyValue(item, { src: config.right, dest: config.left });
+ }
+ if (!(config.right in item)) {
+ return null;
+ }
+
+ let leftType = this._typeOf(item[config.left]);
+ if (leftType !== this._typeOf(item[config.right])) {
+ return null;
+ }
+ if (leftType === "array") {
+ if (item[config.left].length !== item[config.right].length) {
+ return null;
+ }
+ for (let i = 0; i < item[config.left].length; i++) {
+ item[config.left][i] += item[config.right][i];
+ }
+ return item;
+ } else if (leftType === "map") {
+ Object.keys(item[config.right]).forEach(key => {
+ let v = 0;
+ if (key in item[config.left]) {
+ v = item[config.left][key];
+ }
+ item[config.left][key] = v + item[config.right][key];
+ });
+ return item;
+ }
+
+ return null;
+ }
+
+ /**
+ * Converts a vector from real values to boolean integers. (i.e. either 1/0
+ * or 1/-1).
+ *
+ * Config:
+ * field Field containing either a map of strings to numbers or
+ * an array of numbers to convert.
+ * threshold OPTIONAL (DEFAULT: 0) Values above this will be replaced
+ * with 1.0. Those below will be converted to 0.
+ * keep_negative OPTIONAL (DEFAULT: False) If true, values below the
+ * threshold will be converted to -1 instead of 0.
+ */
+ makeBoolean(item, config) {
+ if (!(config.field in item)) {
+ return null;
+ }
+ let threshold = this._lookupScalar(item, config.threshold, 0.0);
+ let type = this._typeOf(item[config.field]);
+ if (type === "array") {
+ for (let i = 0; i < item[config.field].length; i++) {
+ if (item[config.field][i] > threshold) {
+ item[config.field][i] = 1.0;
+ } else if (config.keep_negative) {
+ item[config.field][i] = -1.0;
+ } else {
+ item[config.field][i] = 0.0;
+ }
+ }
+ } else if (type === "map") {
+ Object.keys(item[config.field]).forEach(key => {
+ let value = item[config.field][key];
+ if (value > threshold) {
+ item[config.field][key] = 1.0;
+ } else if (config.keep_negative) {
+ item[config.field][key] = -1.0;
+ } else {
+ item[config.field][key] = 0.0;
+ }
+ });
+ } else if (type === "number") {
+ let value = item[config.field];
+ if (value > threshold) {
+ item[config.field] = 1.0;
+ } else if (config.keep_negative) {
+ item[config.field] = -1.0;
+ } else {
+ item[config.field] = 0.0;
+ }
+ } else {
+ return null;
+ }
+
+ return item;
+ }
+
+ /**
+ * Removes all keys from the item except for the ones specified.
+ *
+ * fields An array of strings indicating the fields to keep
+ */
+ allowFields(item, config) {
+ let newItem = {};
+ for (let ele of config.fields) {
+ if (ele in item) {
+ newItem[ele] = item[ele];
+ }
+ }
+ return newItem;
+ }
+
+ /**
+ * Removes all keys whose value does not exceed some threshold.
+ *
+ * Config:
+ * field Points to a map of strings to numbers
+ * threshold Values must exceed this value, otherwise they are removed.
+ */
+ filterByValue(item, config) {
+ if (!(config.field in item)) {
+ return null;
+ }
+ let threshold = this._lookupScalar(item, config.threshold, 0.0);
+ let filtered = {};
+ Object.keys(item[config.field]).forEach(key => {
+ let value = item[config.field][key];
+ if (value > threshold) {
+ filtered[key] = value;
+ }
+ });
+ item[config.field] = filtered;
+
+ return item;
+ }
+
+ /**
+ * Rewrites a field so that its values are now L2 normed.
+ *
+ * Config:
+ * field Points to a map of strings to numbers, or an array of numbers
+ */
+ l2Normalize(item, config) {
+ if (!(config.field in item)) {
+ return null;
+ }
+ let data = item[config.field];
+ let type = this._typeOf(data);
+ if (type === "array") {
+ let norm = 0.0;
+ for (let datum of data) {
+ norm += datum * datum;
+ }
+ norm = Math.sqrt(norm);
+ if (norm !== 0) {
+ for (let i = 0; i < data.length; i++) {
+ data[i] /= norm;
+ }
+ }
+ } else if (type === "map") {
+ let norm = 0.0;
+ Object.keys(data).forEach(key => {
+ norm += data[key] * data[key];
+ });
+ norm = Math.sqrt(norm);
+ if (norm !== 0) {
+ Object.keys(data).forEach(key => {
+ data[key] /= norm;
+ });
+ }
+ } else {
+ return null;
+ }
+
+ item[config.field] = data;
+
+ return item;
+ }
+
+ /**
+ * Rewrites a field so that all of its values sum to 1.0
+ *
+ * Config:
+ * field Points to a map of strings to numbers, or an array of numbers
+ */
+ probNormalize(item, config) {
+ if (!(config.field in item)) {
+ return null;
+ }
+ let data = item[config.field];
+ let type = this._typeOf(data);
+ if (type === "array") {
+ let norm = 0.0;
+ for (let datum of data) {
+ norm += datum;
+ }
+ if (norm !== 0) {
+ for (let i = 0; i < data.length; i++) {
+ data[i] /= norm;
+ }
+ }
+ } else if (type === "map") {
+ let norm = 0.0;
+ Object.keys(item[config.field]).forEach(key => {
+ norm += item[config.field][key];
+ });
+ if (norm !== 0) {
+ Object.keys(item[config.field]).forEach(key => {
+ item[config.field][key] /= norm;
+ });
+ }
+ } else {
+ return null;
+ }
+
+ return item;
+ }
+
+ /**
+ * Stores a value, if it is not already present
+ *
+ * Config:
+ * field field to write to if it is missing
+ * value value to store in that field
+ */
+ setDefault(item, config) {
+ let val = this._lookupScalar(item, config.value, config.value);
+ if (!(config.field in item)) {
+ item[config.field] = val;
+ }
+
+ return item;
+ }
+
+ /**
+ * Selctively promotes an value from an inner map up to the outer map
+ *
+ * Config:
+ * haystack Points to a map of strings to values
+ * needle Key inside the map we should promote up
+ * dest Where we should write the value of haystack[needle]
+ */
+ lookupValue(item, config) {
+ if (config.haystack in item && config.needle in item[config.haystack]) {
+ item[config.dest] = item[config.haystack][config.needle];
+ }
+
+ return item;
+ }
+
+ /**
+ * Demotes a field into a map
+ *
+ * Config:
+ * src Field to copy
+ * dest_map Points to a map
+ * dest_key Key inside dest_map to copy src to
+ */
+ copyToMap(item, config) {
+ if (config.src in item) {
+ if (!(config.dest_map in item)) {
+ item[config.dest_map] = {};
+ }
+ item[config.dest_map][config.dest_key] = item[config.src];
+ }
+
+ return item;
+ }
+
+ /**
+ * Config:
+ * field Points to a string to number map
+ * k Scalar to multiply the values by
+ * log_scale Boolean, if true, then the values will be transformed
+ * by a logrithm prior to multiplications
+ */
+ scalarMultiplyTag(item, config) {
+ let EPSILON = 0.000001;
+ if (!(config.field in item)) {
+ return null;
+ }
+ let k = this._lookupScalar(item, config.k, 1);
+ let type = this._typeOf(item[config.field]);
+ if (type === "map") {
+ Object.keys(item[config.field]).forEach(parentKey => {
+ Object.keys(item[config.field][parentKey]).forEach(key => {
+ let v = item[config.field][parentKey][key];
+ if (config.log_scale) {
+ v = Math.log(v + EPSILON);
+ }
+ item[config.field][parentKey][key] = v * k;
+ });
+ });
+ } else {
+ return null;
+ }
+
+ return item;
+ }
+
+ /**
+ * Independently applies softmax across all subtags.
+ *
+ * Config:
+ * field Points to a map of strings with values being another map of strings
+ */
+ applySoftmaxTags(item, config) {
+ let type = this._typeOf(item[config.field]);
+ if (type !== "map") {
+ return null;
+ }
+
+ let abort = false;
+ let softmaxSum = {};
+ Object.keys(item[config.field]).forEach(tag => {
+ if (this._typeOf(item[config.field][tag]) !== "map") {
+ abort = true;
+ return;
+ }
+ if (abort) {
+ return;
+ }
+ softmaxSum[tag] = 0;
+ Object.keys(item[config.field][tag]).forEach(subtag => {
+ if (this._typeOf(item[config.field][tag][subtag]) !== "number") {
+ abort = true;
+ return;
+ }
+ let score = item[config.field][tag][subtag];
+ softmaxSum[tag] += Math.exp(score);
+ });
+ });
+ if (abort) {
+ return null;
+ }
+
+ Object.keys(item[config.field]).forEach(tag => {
+ Object.keys(item[config.field][tag]).forEach(subtag => {
+ item[config.field][tag][subtag] =
+ Math.exp(item[config.field][tag][subtag]) / softmaxSum[tag];
+ });
+ });
+
+ return item;
+ }
+
+ /**
+ * Vector adds a field and stores the result in left.
+ *
+ * Config:
+ * field The field to vector add
+ */
+ combinerAdd(left, right, config) {
+ if (!(config.field in right)) {
+ return left;
+ }
+ let type = this._typeOf(right[config.field]);
+ if (!(config.field in left)) {
+ if (type === "map") {
+ left[config.field] = {};
+ } else if (type === "array") {
+ left[config.field] = [];
+ } else if (type === "number") {
+ left[config.field] = 0;
+ } else {
+ return null;
+ }
+ }
+ if (type !== this._typeOf(left[config.field])) {
+ return null;
+ }
+ if (type === "map") {
+ Object.keys(right[config.field]).forEach(key => {
+ if (!(key in left[config.field])) {
+ left[config.field][key] = 0;
+ }
+ left[config.field][key] += right[config.field][key];
+ });
+ } else if (type === "array") {
+ for (let i = 0; i < right[config.field].length; i++) {
+ if (i < left[config.field].length) {
+ left[config.field][i] += right[config.field][i];
+ } else {
+ left[config.field].push(right[config.field][i]);
+ }
+ }
+ } else if (type === "number") {
+ left[config.field] += right[config.field];
+ } else {
+ return null;
+ }
+
+ return left;
+ }
+
+ /**
+ * Stores the maximum value of the field in left.
+ *
+ * Config:
+ * field The field to vector add
+ */
+ combinerMax(left, right, config) {
+ if (!(config.field in right)) {
+ return left;
+ }
+ let type = this._typeOf(right[config.field]);
+ if (!(config.field in left)) {
+ if (type === "map") {
+ left[config.field] = {};
+ } else if (type === "array") {
+ left[config.field] = [];
+ } else if (type === "number") {
+ left[config.field] = 0;
+ } else {
+ return null;
+ }
+ }
+ if (type !== this._typeOf(left[config.field])) {
+ return null;
+ }
+ if (type === "map") {
+ Object.keys(right[config.field]).forEach(key => {
+ if (
+ !(key in left[config.field]) ||
+ right[config.field][key] > left[config.field][key]
+ ) {
+ left[config.field][key] = right[config.field][key];
+ }
+ });
+ } else if (type === "array") {
+ for (let i = 0; i < right[config.field].length; i++) {
+ if (i < left[config.field].length) {
+ if (left[config.field][i] < right[config.field][i]) {
+ left[config.field][i] = right[config.field][i];
+ }
+ } else {
+ left[config.field].push(right[config.field][i]);
+ }
+ }
+ } else if (type === "number") {
+ if (left[config.field] < right[config.field]) {
+ left[config.field] = right[config.field];
+ }
+ } else {
+ return null;
+ }
+
+ return left;
+ }
+
+ /**
+ * Associates a value in right with another value in right. This association
+ * is then stored in a map in left.
+ *
+ * For example: If a sequence of rights is:
+ * { 'tags': {}, 'url_domain': 'maseratiusa.com/maserati', 'time': 41 }
+ * { 'tags': {}, 'url_domain': 'mbusa.com/mercedes', 'time': 21 }
+ * { 'tags': {}, 'url_domain': 'maseratiusa.com/maserati', 'time': 34 }
+ *
+ * Then assuming a 'sum' operation, left can build a map that would look like:
+ * {
+ * 'maseratiusa.com/maserati': 75,
+ * 'mbusa.com/mercedes': 21,
+ * }
+ *
+ * Fields:
+ * left_field field in the left to store / update the map
+ * right_key_field Field in the right to use as a key
+ * right_value_field Field in the right to use as a value
+ * operation One of "sum", "max", "overwrite", "count"
+ */
+ combinerCollectValues(left, right, config) {
+ let op;
+ if (config.operation === "sum") {
+ op = (a, b) => a + b;
+ } else if (config.operation === "max") {
+ op = (a, b) => (a > b ? a : b);
+ } else if (config.operation === "overwrite") {
+ op = (a, b) => b;
+ } else if (config.operation === "count") {
+ op = (a, b) => a + 1;
+ } else {
+ return null;
+ }
+ if (!(config.left_field in left)) {
+ left[config.left_field] = {};
+ }
+ if (
+ !(config.right_key_field in right) ||
+ !(config.right_value_field in right)
+ ) {
+ return left;
+ }
+
+ let key = right[config.right_key_field];
+ let rightValue = right[config.right_value_field];
+ let leftValue = 0.0;
+ if (key in left[config.left_field]) {
+ leftValue = left[config.left_field][key];
+ }
+
+ left[config.left_field][key] = op(leftValue, rightValue);
+
+ return left;
+ }
+
+ /**
+ * Executes a recipe. Returns an object on success, or null on failure.
+ */
+ executeRecipe(item, recipe) {
+ let newItem = item;
+ if (recipe) {
+ for (let step of recipe) {
+ let op = this.ITEM_BUILDER_REGISTRY[step.function];
+ if (op === undefined) {
+ return null;
+ }
+ newItem = op.call(this, newItem, step);
+ if (newItem === null) {
+ break;
+ }
+ }
+ }
+ return newItem;
+ }
+
+ /**
+ * Executes a recipe. Returns an object on success, or null on failure.
+ */
+ executeCombinerRecipe(item1, item2, recipe) {
+ let newItem1 = item1;
+ for (let step of recipe) {
+ let op = this.ITEM_COMBINER_REGISTRY[step.function];
+ if (op === undefined) {
+ return null;
+ }
+ newItem1 = op.call(this, newItem1, item2, step);
+ if (newItem1 === null) {
+ break;
+ }
+ }
+
+ return newItem1;
+ }
+};
diff --git a/browser/components/newtab/lib/PersonalityProvider/Tokenize.jsm b/browser/components/newtab/lib/PersonalityProvider/Tokenize.jsm
new file mode 100644
index 0000000000..94835557a6
--- /dev/null
+++ b/browser/components/newtab/lib/PersonalityProvider/Tokenize.jsm
@@ -0,0 +1,89 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
+// We load this into a worker using importScripts, and in tests using import.
+// We use var to avoid name collision errors.
+// eslint-disable-next-line no-var
+var EXPORTED_SYMBOLS = ["tokenize", "toksToTfIdfVector"];
+
+// Unicode specifies certain mnemonics for code pages and character classes.
+// They call them "character properties" https://en.wikipedia.org/wiki/Unicode_character_property .
+// These mnemonics are have been adopted by many regular expression libraries,
+// however the standard Javascript regexp system doesn't support unicode
+// character properties, so we have to define these ourself.
+//
+// Each of these sections contains the characters values / ranges for specific
+// character property: Whitespace, Symbol (S), Punctuation (P), Number (N),
+// Mark (M), and Letter (L).
+const UNICODE_SPACE =
+ "\x20\xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000";
+const UNICODE_SYMBOL =
+ "\\x24\\x2B\x3C-\x3E\\x5E\x60\\x7C\x7E\xA2-\xA6\xA8\xA9\xAC\xAE-\xB1\xB4\xB8\xD7\xF7\u02C2-\u02C5\u02D2-\u02DF\u02E5-\u02EB\u02ED\u02EF-\u02FF\u0375\u0384\u0385\u03F6\u0482\u058D-\u058F\u0606-\u0608\u060B\u060E\u060F\u06DE\u06E9\u06FD\u06FE\u07F6\u09F2\u09F3\u09FA\u09FB\u0AF1\u0B70\u0BF3-\u0BFA\u0C7F\u0D4F\u0D79\u0E3F\u0F01-\u0F03\u0F13\u0F15-\u0F17\u0F1A-\u0F1F\u0F34\u0F36\u0F38\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE\u0FCF\u0FD5-\u0FD8\u109E\u109F\u1390-\u1399\u17DB\u1940\u19DE-\u19FF\u1B61-\u1B6A\u1B74-\u1B7C\u1FBD\u1FBF-\u1FC1\u1FCD-\u1FCF\u1FDD-\u1FDF\u1FED-\u1FEF\u1FFD\u1FFE\u2044\u2052\u207A-\u207C\u208A-\u208C\u20A0-\u20BE\u2100\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u214F\u218A\u218B\u2190-\u2307\u230C-\u2328\u232B-\u23FE\u2400-\u2426\u2440-\u244A\u249C-\u24E9\u2500-\u2767\u2794-\u27C4\u27C7-\u27E5\u27F0-\u2982\u2999-\u29D7\u29DC-\u29FB\u29FE-\u2B73\u2B76-\u2B95\u2B98-\u2BB9\u2BBD-\u2BC8\u2BCA-\u2BD1\u2BEC-\u2BEF\u2CE5-\u2CEA\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFB\u3004\u3012\u3013\u3020\u3036\u3037\u303E\u303F\u309B\u309C\u3190\u3191\u3196-\u319F\u31C0-\u31E3\u3200-\u321E\u322A-\u3247\u3250\u3260-\u327F\u328A-\u32B0\u32C0-\u32FE\u3300-\u33FF\u4DC0-\u4DFF\uA490-\uA4C6\uA700-\uA716\uA720\uA721\uA789\uA78A\uA828-\uA82B\uA836-\uA839\uAA77-\uAA79\uAB5B\uFB29\uFBB2-\uFBC1\uFDFC\uFDFD\uFE62\uFE64-\uFE66\uFE69\uFF04\uFF0B\uFF1C-\uFF1E\uFF3E\uFF40\uFF5C\uFF5E\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFFC\uFFFD";
+const UNICODE_PUNCT =
+ "\x21-\x23\x25-\\x2A\x2C-\x2F\x3A\x3B\\x3F\x40\\x5B-\\x5D\x5F\\x7B\x7D\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u0AF0\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166D\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E44\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65";
+
+const UNICODE_NUMBER =
+ "0-9\xB2\xB3\xB9\xBC-\xBE\u0660-\u0669\u06F0-\u06F9\u07C0-\u07C9\u0966-\u096F\u09E6-\u09EF\u09F4-\u09F9\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0B72-\u0B77\u0BE6-\u0BF2\u0C66-\u0C6F\u0C78-\u0C7E\u0CE6-\u0CEF\u0D58-\u0D5E\u0D66-\u0D78\u0DE6-\u0DEF\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F33\u1040-\u1049\u1090-\u1099\u1369-\u137C\u16EE-\u16F0\u17E0-\u17E9\u17F0-\u17F9\u1810-\u1819\u1946-\u194F\u19D0-\u19DA\u1A80-\u1A89\u1A90-\u1A99\u1B50-\u1B59\u1BB0-\u1BB9\u1C40-\u1C49\u1C50-\u1C59\u2070\u2074-\u2079\u2080-\u2089\u2150-\u2182\u2185-\u2189\u2460-\u249B\u24EA-\u24FF\u2776-\u2793\u2CFD\u3007\u3021-\u3029\u3038-\u303A\u3192-\u3195\u3220-\u3229\u3248-\u324F\u3251-\u325F\u3280-\u3289\u32B1-\u32BF\uA620-\uA629\uA6E6-\uA6EF\uA830-\uA835\uA8D0-\uA8D9\uA900-\uA909\uA9D0-\uA9D9\uA9F0-\uA9F9\uAA50-\uAA59\uABF0-\uABF9\uFF10-\uFF19";
+const UNICODE_MARK =
+ "\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D4-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D01-\u0D03\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u192B\u1930-\u193B\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF5\u1DFB-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C5\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F";
+const UNICODE_LETTER =
+ "A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC";
+
+const REGEXP_SPLITS = new RegExp(
+ `[${UNICODE_SPACE}${UNICODE_SYMBOL}${UNICODE_PUNCT}]+`
+);
+// Match all token characters, so okay for regex to split multiple code points
+// eslint-disable-next-line no-misleading-character-class
+const REGEXP_ALPHANUMS = new RegExp(
+ `^[${UNICODE_NUMBER}${UNICODE_MARK}${UNICODE_LETTER}]+$`
+);
+
+/**
+ * Downcases the text, and splits it into consecutive alphanumeric characters.
+ * This is locale aware, and so will not strip accents. This uses "word
+ * breaks", and os is not appropriate for languages without them
+ * (e.g. Chinese).
+ */
+function tokenize(text) {
+ return text
+ .toLocaleLowerCase()
+ .split(REGEXP_SPLITS)
+ .filter(tok => tok.match(REGEXP_ALPHANUMS));
+}
+
+/**
+ * Converts a sequence of tokens into an L2 normed TF-IDF. Any terms that are
+ * not preindexed (i.e. does have a computed inverse document frequency) will
+ * be dropped.
+ */
+function toksToTfIdfVector(tokens, vocab_idfs) {
+ let tfidfs = {};
+
+ // calcualte the term frequencies
+ for (let tok of tokens) {
+ if (!(tok in vocab_idfs)) {
+ continue;
+ }
+ if (!(tok in tfidfs)) {
+ tfidfs[tok] = [vocab_idfs[tok][0], 1];
+ } else {
+ tfidfs[tok][1]++;
+ }
+ }
+
+ // now multiply by the log inverse document frequencies, then take
+ // the L2 norm of this.
+ let l2Norm = 0.0;
+ Object.keys(tfidfs).forEach(tok => {
+ tfidfs[tok][1] *= vocab_idfs[tok][1];
+ l2Norm += tfidfs[tok][1] * tfidfs[tok][1];
+ });
+ l2Norm = Math.sqrt(l2Norm);
+ Object.keys(tfidfs).forEach(tok => {
+ tfidfs[tok][1] /= l2Norm;
+ });
+
+ return tfidfs;
+}
diff --git a/browser/components/newtab/lib/PlacesFeed.jsm b/browser/components/newtab/lib/PlacesFeed.jsm
new file mode 100644
index 0000000000..e76fc78000
--- /dev/null
+++ b/browser/components/newtab/lib/PlacesFeed.jsm
@@ -0,0 +1,568 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
+const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
+
+const { actionCreators: ac, actionTypes: at } = ChromeUtils.import(
+ "resource://activity-stream/common/Actions.jsm"
+);
+
+ChromeUtils.defineModuleGetter(
+ this,
+ "NewTabUtils",
+ "resource://gre/modules/NewTabUtils.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "PartnerLinkAttribution",
+ "resource:///modules/PartnerLinkAttribution.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "PlacesUtils",
+ "resource://gre/modules/PlacesUtils.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "PrivateBrowsingUtils",
+ "resource://gre/modules/PrivateBrowsingUtils.jsm"
+);
+
+const LINK_BLOCKED_EVENT = "newtab-linkBlocked";
+const PLACES_LINKS_CHANGED_DELAY_TIME = 1000; // time in ms to delay timer for places links changed events
+
+/**
+ * Observer - a wrapper around history/bookmark observers to add the QueryInterface.
+ */
+class Observer {
+ constructor(dispatch, observerInterface) {
+ this.dispatch = dispatch;
+ this.QueryInterface = ChromeUtils.generateQI([
+ observerInterface,
+ "nsISupportsWeakReference",
+ ]);
+ }
+}
+
+/**
+ * HistoryObserver - observes events from PlacesUtils.history
+ */
+class HistoryObserver extends Observer {
+ constructor(dispatch) {
+ super(dispatch, Ci.nsINavHistoryObserver);
+ }
+
+ /**
+ * onDeleteURI - Called when an link is deleted from history.
+ *
+ * @param {obj} uri A URI object representing the link's url
+ * {str} uri.spec The URI as a string
+ */
+ onDeleteURI(uri) {
+ this.dispatch({ type: at.PLACES_LINKS_CHANGED });
+ this.dispatch({
+ type: at.PLACES_LINK_DELETED,
+ data: { url: uri.spec },
+ });
+ }
+
+ // Empty functions to make xpconnect happy
+ onBeginUpdateBatch() {}
+
+ onEndUpdateBatch() {}
+
+ onDeleteVisits() {}
+}
+
+/**
+ * BookmarksObserver - observes events from PlacesUtils.bookmarks
+ */
+class BookmarksObserver extends Observer {
+ constructor(dispatch) {
+ super(dispatch, Ci.nsINavBookmarkObserver);
+ this.skipTags = true;
+ }
+
+ // Empty functions to make xpconnect happy
+ onBeginUpdateBatch() {}
+
+ onEndUpdateBatch() {}
+
+ onItemMoved() {}
+
+ // Disabled due to performance cost, see Issue 3203 /
+ // https://bugzilla.mozilla.org/show_bug.cgi?id=1392267.
+ onItemChanged() {}
+}
+
+/**
+ * PlacesObserver - observes events from PlacesUtils.observers
+ */
+class PlacesObserver extends Observer {
+ constructor(dispatch) {
+ super(dispatch, Ci.nsINavBookmarkObserver);
+ this.handlePlacesEvent = this.handlePlacesEvent.bind(this);
+ }
+
+ handlePlacesEvent(events) {
+ for (const {
+ itemType,
+ source,
+ dateAdded,
+ guid,
+ title,
+ url,
+ isTagging,
+ type,
+ } of events) {
+ switch (type) {
+ case "history-cleared":
+ this.dispatch({ type: at.PLACES_HISTORY_CLEARED });
+ break;
+ case "bookmark-added":
+ // Skips items that are not bookmarks (like folders), about:* pages or
+ // default bookmarks, added when the profile is created.
+ if (
+ isTagging ||
+ itemType !== PlacesUtils.bookmarks.TYPE_BOOKMARK ||
+ source === PlacesUtils.bookmarks.SOURCES.IMPORT ||
+ source === PlacesUtils.bookmarks.SOURCES.RESTORE ||
+ source === PlacesUtils.bookmarks.SOURCES.RESTORE_ON_STARTUP ||
+ source === PlacesUtils.bookmarks.SOURCES.SYNC ||
+ (!url.startsWith("http://") && !url.startsWith("https://"))
+ ) {
+ return;
+ }
+
+ this.dispatch({ type: at.PLACES_LINKS_CHANGED });
+ this.dispatch({
+ type: at.PLACES_BOOKMARK_ADDED,
+ data: {
+ bookmarkGuid: guid,
+ bookmarkTitle: title,
+ dateAdded: dateAdded * 1000,
+ url,
+ },
+ });
+ break;
+ case "bookmark-removed":
+ if (
+ isTagging ||
+ (itemType === PlacesUtils.bookmarks.TYPE_BOOKMARK &&
+ source !== PlacesUtils.bookmarks.SOURCES.IMPORT &&
+ source !== PlacesUtils.bookmarks.SOURCES.RESTORE &&
+ source !== PlacesUtils.bookmarks.SOURCES.RESTORE_ON_STARTUP &&
+ source !== PlacesUtils.bookmarks.SOURCES.SYNC)
+ ) {
+ this.dispatch({ type: at.PLACES_LINKS_CHANGED });
+ this.dispatch({
+ type: at.PLACES_BOOKMARK_REMOVED,
+ data: { url, bookmarkGuid: guid },
+ });
+ }
+ break;
+ }
+ }
+ }
+}
+
+class PlacesFeed {
+ constructor() {
+ this.placesChangedTimer = null;
+ this.customDispatch = this.customDispatch.bind(this);
+ this.historyObserver = new HistoryObserver(this.customDispatch);
+ this.bookmarksObserver = new BookmarksObserver(this.customDispatch);
+ this.placesObserver = new PlacesObserver(this.customDispatch);
+ }
+
+ addObservers() {
+ // NB: Directly get services without importing the *BIG* PlacesUtils module
+ Cc["@mozilla.org/browser/nav-history-service;1"]
+ .getService(Ci.nsINavHistoryService)
+ .addObserver(this.historyObserver, true);
+ Cc["@mozilla.org/browser/nav-bookmarks-service;1"]
+ .getService(Ci.nsINavBookmarksService)
+ .addObserver(this.bookmarksObserver, true);
+ PlacesUtils.observers.addListener(
+ ["bookmark-added", "bookmark-removed", "history-cleared"],
+ this.placesObserver.handlePlacesEvent
+ );
+
+ Services.obs.addObserver(this, LINK_BLOCKED_EVENT);
+ }
+
+ /**
+ * setTimeout - A custom function that creates an nsITimer that can be cancelled
+ *
+ * @param {func} callback A function to be executed after the timer expires
+ * @param {int} delay The time (in ms) the timer should wait before the function is executed
+ */
+ setTimeout(callback, delay) {
+ let timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
+ timer.initWithCallback(callback, delay, Ci.nsITimer.TYPE_ONE_SHOT);
+ return timer;
+ }
+
+ customDispatch(action) {
+ // If we are changing many links at once, delay this action and only dispatch
+ // one action at the end
+ if (action.type === at.PLACES_LINKS_CHANGED) {
+ if (this.placesChangedTimer) {
+ this.placesChangedTimer.delay = PLACES_LINKS_CHANGED_DELAY_TIME;
+ } else {
+ this.placesChangedTimer = this.setTimeout(() => {
+ this.placesChangedTimer = null;
+ this.store.dispatch(ac.OnlyToMain(action));
+ }, PLACES_LINKS_CHANGED_DELAY_TIME);
+ }
+ } else {
+ this.store.dispatch(ac.BroadcastToContent(action));
+ }
+ }
+
+ removeObservers() {
+ if (this.placesChangedTimer) {
+ this.placesChangedTimer.cancel();
+ this.placesChangedTimer = null;
+ }
+ PlacesUtils.history.removeObserver(this.historyObserver);
+ PlacesUtils.bookmarks.removeObserver(this.bookmarksObserver);
+ PlacesUtils.observers.removeListener(
+ ["bookmark-added", "bookmark-removed", "history-cleared"],
+ this.placesObserver.handlePlacesEvent
+ );
+ Services.obs.removeObserver(this, LINK_BLOCKED_EVENT);
+ }
+
+ /**
+ * observe - An observer for the LINK_BLOCKED_EVENT.
+ * Called when a link is blocked.
+ * Links can be blocked outside of newtab,
+ * which is why we need to listen to this
+ * on such a generic level.
+ *
+ * @param {null} subject
+ * @param {str} topic The name of the event
+ * @param {str} value The data associated with the event
+ */
+ observe(subject, topic, value) {
+ if (topic === LINK_BLOCKED_EVENT) {
+ this.store.dispatch(
+ ac.BroadcastToContent({
+ type: at.PLACES_LINK_BLOCKED,
+ data: { url: value },
+ })
+ );
+ }
+ }
+
+ /**
+ * Open a link in a desired destination defaulting to action's event.
+ */
+ openLink(action, where = "", isPrivate = false) {
+ const params = {
+ private: isPrivate,
+ targetBrowser: action._target.browser,
+ fromChrome: false, // This ensure we maintain user preference for how to open new tabs.
+ };
+
+ // Always include the referrer (even for http links) if we have one
+ const { event, referrer, typedBonus } = action.data;
+ if (referrer) {
+ const ReferrerInfo = Components.Constructor(
+ "@mozilla.org/referrer-info;1",
+ "nsIReferrerInfo",
+ "init"
+ );
+ params.referrerInfo = new ReferrerInfo(
+ Ci.nsIReferrerInfo.UNSAFE_URL,
+ true,
+ Services.io.newURI(referrer)
+ );
+ }
+
+ // Pocket gives us a special reader URL to open their stories in
+ const urlToOpen =
+ action.data.type === "pocket" ? action.data.open_url : action.data.url;
+
+ try {
+ let uri = Services.io.newURI(urlToOpen);
+ if (!["http", "https"].includes(uri.scheme)) {
+ throw new Error(
+ `Can't open link using ${uri.scheme} protocol from the new tab page.`
+ );
+ }
+ } catch (e) {
+ Cu.reportError(e);
+ return;
+ }
+
+ // Mark the page as typed for frecency bonus before opening the link
+ if (typedBonus) {
+ PlacesUtils.history.markPageAsTyped(Services.io.newURI(urlToOpen));
+ }
+
+ const win = action._target.browser.ownerGlobal;
+ win.openTrustedLinkIn(
+ urlToOpen,
+ where || win.whereToOpenLink(event),
+ params
+ );
+
+ // If there's an original URL e.g. using the unprocessed %YYYYMMDDHH% tag,
+ // add a visit for that so it may become a frecent top site.
+ if (action.data.original_url) {
+ PlacesUtils.history.insert({
+ url: action.data.original_url,
+ visits: [{ transition: PlacesUtils.history.TRANSITION_TYPED }],
+ });
+ }
+ }
+
+ async saveToPocket(site, browser) {
+ const { url, title } = site;
+ try {
+ let data = await NewTabUtils.activityStreamLinks.addPocketEntry(
+ url,
+ title,
+ browser
+ );
+ if (data) {
+ this.store.dispatch(
+ ac.BroadcastToContent({
+ type: at.PLACES_SAVED_TO_POCKET,
+ data: {
+ url,
+ open_url: data.item.open_url,
+ title,
+ pocket_id: data.item.item_id,
+ },
+ })
+ );
+ }
+ } catch (err) {
+ Cu.reportError(err);
+ }
+ }
+
+ /**
+ * Deletes an item from a user's saved to Pocket feed
+ * @param {int} itemID
+ * The unique ID given by Pocket for that item; used to look the item up when deleting
+ */
+ async deleteFromPocket(itemID) {
+ try {
+ await NewTabUtils.activityStreamLinks.deletePocketEntry(itemID);
+ this.store.dispatch({ type: at.POCKET_LINK_DELETED_OR_ARCHIVED });
+ } catch (err) {
+ Cu.reportError(err);
+ }
+ }
+
+ /**
+ * Archives an item from a user's saved to Pocket feed
+ * @param {int} itemID
+ * The unique ID given by Pocket for that item; used to look the item up when archiving
+ */
+ async archiveFromPocket(itemID) {
+ try {
+ await NewTabUtils.activityStreamLinks.archivePocketEntry(itemID);
+ this.store.dispatch({ type: at.POCKET_LINK_DELETED_OR_ARCHIVED });
+ } catch (err) {
+ Cu.reportError(err);
+ }
+ }
+
+ /**
+ * Sends an attribution request for Top Sites interactions.
+ * @param {object} data
+ * Attribution paramters from a Top Site.
+ */
+ makeAttributionRequest(data) {
+ let args = Object.assign(
+ {
+ campaignID: Services.prefs.getStringPref(
+ "browser.partnerlink.campaign.topsites"
+ ),
+ },
+ data
+ );
+ PartnerLinkAttribution.makeRequest(args);
+ }
+
+ async fillSearchTopSiteTerm({ _target, data }) {
+ const searchEngine = await Services.search.getEngineByAlias(data.label);
+ _target.browser.ownerGlobal.gURLBar.search(data.label, {
+ searchEngine,
+ searchModeEntry: "topsites_newtab",
+ });
+ }
+
+ _getDefaultSearchEngine(isPrivateWindow) {
+ return Services.search[
+ isPrivateWindow ? "defaultPrivateEngine" : "defaultEngine"
+ ];
+ }
+
+ _getSearchPrefix(searchEngine) {
+ const searchAliases = searchEngine.aliases;
+ if (searchAliases && searchAliases.length) {
+ return `${searchAliases[0]} `;
+ }
+ return "";
+ }
+
+ handoffSearchToAwesomebar({ _target, data, meta }) {
+ const searchEngine = this._getDefaultSearchEngine(
+ PrivateBrowsingUtils.isBrowserPrivate(_target.browser)
+ );
+ const searchAlias = this._getSearchPrefix(searchEngine);
+ const urlBar = _target.browser.ownerGlobal.gURLBar;
+ let isFirstChange = true;
+
+ if (!data || !data.text) {
+ urlBar.setHiddenFocus();
+ } else {
+ urlBar.search(searchAlias + data.text, {
+ searchEngine,
+ searchModeEntry: "handoff",
+ });
+ isFirstChange = false;
+ }
+
+ const checkFirstChange = () => {
+ // Check if this is the first change since we hidden focused. If it is,
+ // remove hidden focus styles, prepend the search alias and hide the
+ // in-content search.
+ if (isFirstChange) {
+ isFirstChange = false;
+ urlBar.removeHiddenFocus();
+ urlBar.search(searchAlias, {
+ searchEngine,
+ searchModeEntry: "handoff",
+ });
+ this.store.dispatch(
+ ac.OnlyToOneContent({ type: at.HIDE_SEARCH }, meta.fromTarget)
+ );
+ urlBar.removeEventListener("compositionstart", checkFirstChange);
+ urlBar.removeEventListener("paste", checkFirstChange);
+ }
+ };
+
+ const onKeydown = ev => {
+ // Check if the keydown will cause a value change.
+ if (ev.key.length === 1 && !ev.altKey && !ev.ctrlKey && !ev.metaKey) {
+ checkFirstChange();
+ }
+ // If the Esc button is pressed, we are done. Show in-content search and cleanup.
+ if (ev.key === "Escape") {
+ onDone(); // eslint-disable-line no-use-before-define
+ }
+ };
+
+ const onDone = () => {
+ // We are done. Show in-content search again and cleanup.
+ this.store.dispatch(
+ ac.OnlyToOneContent({ type: at.SHOW_SEARCH }, meta.fromTarget)
+ );
+ urlBar.removeHiddenFocus();
+
+ urlBar.removeEventListener("keydown", onKeydown);
+ urlBar.removeEventListener("mousedown", onDone);
+ urlBar.removeEventListener("blur", onDone);
+ urlBar.removeEventListener("compositionstart", checkFirstChange);
+ urlBar.removeEventListener("paste", checkFirstChange);
+ };
+
+ urlBar.addEventListener("keydown", onKeydown);
+ urlBar.addEventListener("mousedown", onDone);
+ urlBar.addEventListener("blur", onDone);
+ urlBar.addEventListener("compositionstart", checkFirstChange);
+ urlBar.addEventListener("paste", checkFirstChange);
+ }
+
+ onAction(action) {
+ switch (action.type) {
+ case at.INIT:
+ // Briefly avoid loading services for observing for better startup timing
+ Services.tm.dispatchToMainThread(() => this.addObservers());
+ break;
+ case at.UNINIT:
+ this.removeObservers();
+ break;
+ case at.ABOUT_SPONSORED_TOP_SITES: {
+ const url = `${Services.urlFormatter.formatURLPref(
+ "app.support.baseURL"
+ )}sponsor-privacy`;
+ const win = action._target.browser.ownerGlobal;
+ win.openTrustedLinkIn(url, "tab");
+ break;
+ }
+ case at.BLOCK_URL: {
+ if (action.data) {
+ action.data.forEach(site => {
+ const { url, pocket_id } = site;
+ NewTabUtils.activityStreamLinks.blockURL({ url, pocket_id });
+ });
+ }
+ break;
+ }
+ case at.BOOKMARK_URL:
+ NewTabUtils.activityStreamLinks.addBookmark(
+ action.data,
+ action._target.browser.ownerGlobal
+ );
+ break;
+ case at.DELETE_BOOKMARK_BY_ID:
+ NewTabUtils.activityStreamLinks.deleteBookmark(action.data);
+ break;
+ case at.DELETE_HISTORY_URL: {
+ const { url, forceBlock, pocket_id } = action.data;
+ NewTabUtils.activityStreamLinks.deleteHistoryEntry(url);
+ if (forceBlock) {
+ NewTabUtils.activityStreamLinks.blockURL({ url, pocket_id });
+ }
+ break;
+ }
+ case at.OPEN_NEW_WINDOW:
+ this.openLink(action, "window");
+ break;
+ case at.OPEN_PRIVATE_WINDOW:
+ this.openLink(action, "window", true);
+ break;
+ case at.SAVE_TO_POCKET:
+ this.saveToPocket(action.data.site, action._target.browser);
+ break;
+ case at.DELETE_FROM_POCKET:
+ this.deleteFromPocket(action.data.pocket_id);
+ break;
+ case at.ARCHIVE_FROM_POCKET:
+ this.archiveFromPocket(action.data.pocket_id);
+ break;
+ case at.FILL_SEARCH_TERM:
+ this.fillSearchTopSiteTerm(action);
+ break;
+ case at.HANDOFF_SEARCH_TO_AWESOMEBAR:
+ this.handoffSearchToAwesomebar(action);
+ break;
+ case at.OPEN_LINK: {
+ this.openLink(action);
+ break;
+ }
+ case at.PARTNER_LINK_ATTRIBUTION:
+ this.makeAttributionRequest(action.data);
+ break;
+ }
+ }
+}
+
+this.PlacesFeed = PlacesFeed;
+
+// Exported for testing only
+PlacesFeed.HistoryObserver = HistoryObserver;
+PlacesFeed.BookmarksObserver = BookmarksObserver;
+PlacesFeed.PlacesObserver = PlacesObserver;
+
+const EXPORTED_SYMBOLS = ["PlacesFeed"];
diff --git a/browser/components/newtab/lib/PrefsFeed.jsm b/browser/components/newtab/lib/PrefsFeed.jsm
new file mode 100644
index 0000000000..9f858b9154
--- /dev/null
+++ b/browser/components/newtab/lib/PrefsFeed.jsm
@@ -0,0 +1,291 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
+const { actionCreators: ac, actionTypes: at } = ChromeUtils.import(
+ "resource://activity-stream/common/Actions.jsm"
+);
+const { Prefs } = ChromeUtils.import(
+ "resource://activity-stream/lib/ActivityStreamPrefs.jsm"
+);
+const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
+
+ChromeUtils.defineModuleGetter(
+ this,
+ "PrivateBrowsingUtils",
+ "resource://gre/modules/PrivateBrowsingUtils.jsm"
+);
+
+ChromeUtils.defineModuleGetter(
+ this,
+ "AppConstants",
+ "resource://gre/modules/AppConstants.jsm"
+);
+
+ChromeUtils.defineModuleGetter(
+ this,
+ "ExperimentAPI",
+ "resource://messaging-system/experiments/ExperimentAPI.jsm"
+);
+
+ChromeUtils.defineModuleGetter(
+ this,
+ "Region",
+ "resource://gre/modules/Region.jsm"
+);
+
+this.PrefsFeed = class PrefsFeed {
+ constructor(prefMap) {
+ this._prefMap = prefMap;
+ this._prefs = new Prefs();
+ this.onExperimentUpdated = this.onExperimentUpdated.bind(this);
+ }
+
+ onPrefChanged(name, value) {
+ const prefItem = this._prefMap.get(name);
+ if (prefItem) {
+ this.store.dispatch(
+ ac[prefItem.skipBroadcast ? "OnlyToMain" : "BroadcastToContent"]({
+ type: at.PREF_CHANGED,
+ data: { name, value },
+ })
+ );
+ }
+ }
+
+ _setStringPref(values, key, defaultValue) {
+ this._setPref(values, key, defaultValue, Services.prefs.getStringPref);
+ }
+
+ _setBoolPref(values, key, defaultValue) {
+ this._setPref(values, key, defaultValue, Services.prefs.getBoolPref);
+ }
+
+ _setIntPref(values, key, defaultValue) {
+ this._setPref(values, key, defaultValue, Services.prefs.getIntPref);
+ }
+
+ _setPref(values, key, defaultValue, getPrefFunction) {
+ let value = getPrefFunction(
+ `browser.newtabpage.activity-stream.${key}`,
+ defaultValue
+ );
+ values[key] = value;
+ this._prefMap.set(key, { value });
+ }
+
+ /**
+ * Combine default values with experiment values for
+ * the feature config.
+ * */
+ getFeatureConfigFromExperimentData(experimentData) {
+ return {
+ // Icon that shows up in the corner to link to preferences
+ prefsButtonIcon: "icon-settings",
+
+ // Override defaults with any experiment values, if any exist.
+ ...(experimentData?.branch?.feature?.value || {}),
+ };
+ }
+
+ /**
+ * Helper for initializing experiment and feature config data in .init()
+ * */
+ addExperimentDataToValues(values) {
+ let experimentData;
+ try {
+ experimentData = ExperimentAPI.getExperiment({
+ featureId: "newtab",
+ });
+ } catch (e) {
+ Cu.reportError(e);
+ }
+ values.experimentData = experimentData;
+ values.featureConfig = this.getFeatureConfigFromExperimentData(
+ experimentData
+ );
+ }
+
+ /**
+ * Handler for when experiment data updates.
+ */
+ onExperimentUpdated(event, experimentData) {
+ this.store.dispatch(
+ ac.BroadcastToContent({
+ type: at.PREF_CHANGED,
+ data: { name: "experimentData", value: experimentData },
+ })
+ );
+ this.store.dispatch(
+ ac.BroadcastToContent({
+ type: at.PREF_CHANGED,
+ data: {
+ name: "featureConfig",
+ value: this.getFeatureConfigFromExperimentData(experimentData),
+ },
+ })
+ );
+ }
+
+ init() {
+ this._prefs.observeBranch(this);
+ ExperimentAPI.on(
+ "update",
+ { featureId: "newtab" },
+ this.onExperimentUpdated
+ );
+
+ this._storage = this.store.dbStorage.getDbTable("sectionPrefs");
+
+ // Get the initial value of each activity stream pref
+ const values = {};
+ for (const name of this._prefMap.keys()) {
+ values[name] = this._prefs.get(name);
+ }
+
+ // These are not prefs, but are needed to determine stuff in content that can only be
+ // computed in main process
+ values.isPrivateBrowsingEnabled = PrivateBrowsingUtils.enabled;
+ values.platform = AppConstants.platform;
+
+ // Save the geo pref if we have it
+ if (Region.home) {
+ values.region = Region.home;
+ this.geo = values.region;
+ } else if (this.geo !== "") {
+ // Watch for geo changes and use a dummy value for now
+ Services.obs.addObserver(this, Region.REGION_TOPIC);
+ this.geo = "";
+ }
+
+ // Get the firefox accounts url for links and to send firstrun metrics to.
+ values.fxa_endpoint = Services.prefs.getStringPref(
+ "browser.newtabpage.activity-stream.fxaccounts.endpoint",
+ "https://accounts.firefox.com"
+ );
+
+ // Get the firefox update channel with values as default, nightly, beta or release
+ values.appUpdateChannel = Services.prefs.getStringPref(
+ "app.update.channel",
+ ""
+ );
+
+ // Read the pref for search shortcuts top sites experiment from firefox.js and store it
+ // in our interal list of prefs to watch
+ let searchTopSiteExperimentPrefValue = Services.prefs.getBoolPref(
+ "browser.newtabpage.activity-stream.improvesearch.topSiteSearchShortcuts"
+ );
+ values[
+ "improvesearch.topSiteSearchShortcuts"
+ ] = searchTopSiteExperimentPrefValue;
+ this._prefMap.set("improvesearch.topSiteSearchShortcuts", {
+ value: searchTopSiteExperimentPrefValue,
+ });
+
+ values.mayHaveSponsoredTopSites = Services.prefs.getBoolPref(
+ "browser.topsites.useRemoteSetting"
+ );
+
+ // Read the pref for search hand-off from firefox.js and store it
+ // in our interal list of prefs to watch
+ let handoffToAwesomebarPrefValue = Services.prefs.getBoolPref(
+ "browser.newtabpage.activity-stream.improvesearch.handoffToAwesomebar"
+ );
+ values["improvesearch.handoffToAwesomebar"] = handoffToAwesomebarPrefValue;
+ this._prefMap.set("improvesearch.handoffToAwesomebar", {
+ value: handoffToAwesomebarPrefValue,
+ });
+
+ this.addExperimentDataToValues(values);
+
+ this._setBoolPref(values, "newNewtabExperience.enabled", false);
+ this._setBoolPref(values, "customizationMenu.enabled", false);
+ this._setBoolPref(values, "logowordmark.alwaysVisible", false);
+ this._setBoolPref(values, "feeds.section.topstories", false);
+ this._setBoolPref(values, "discoverystream.enabled", false);
+ this._setBoolPref(values, "discoverystream.isCollectionDismissible", false);
+ this._setBoolPref(values, "discoverystream.hardcoded-basic-layout", false);
+ this._setBoolPref(values, "discoverystream.recs.personalized", false);
+ this._setBoolPref(values, "discoverystream.spocs.personalized", false);
+ this._setStringPref(
+ values,
+ "discoverystream.personalization.modelKeys",
+ ""
+ );
+ this._setIntPref(values, "discoverystream.personalization.version", 1);
+ this._setIntPref(values, "discoverystream.personalization.overrideVersion");
+ this._setStringPref(values, "discoverystream.spocs-endpoint", "");
+ this._setStringPref(values, "discoverystream.spocs-endpoint-query", "");
+ this._setStringPref(values, "newNewtabExperience.colors", "");
+
+ // Set the initial state of all prefs in redux
+ this.store.dispatch(
+ ac.BroadcastToContent({
+ type: at.PREFS_INITIAL_VALUES,
+ data: values,
+ meta: {
+ isStartup: true,
+ },
+ })
+ );
+ }
+
+ uninit() {
+ this.removeListeners();
+ }
+
+ removeListeners() {
+ this._prefs.ignoreBranch(this);
+ ExperimentAPI.off(this.onExperimentUpdated);
+ if (this.geo === "") {
+ Services.obs.removeObserver(this, Region.REGION_TOPIC);
+ }
+ }
+
+ async _setIndexedDBPref(id, value) {
+ const name = id === "topsites" ? id : `feeds.section.${id}`;
+ try {
+ await this._storage.set(name, value);
+ } catch (e) {
+ Cu.reportError("Could not set section preferences.");
+ }
+ }
+
+ observe(subject, topic, data) {
+ switch (topic) {
+ case Region.REGION_TOPIC:
+ if (data === Region.REGION_UPDATED) {
+ this.store.dispatch(
+ ac.BroadcastToContent({
+ type: at.PREF_CHANGED,
+ data: { name: "region", value: Region.home },
+ })
+ );
+ }
+ break;
+ }
+ }
+
+ onAction(action) {
+ switch (action.type) {
+ case at.INIT:
+ this.init();
+ break;
+ case at.UNINIT:
+ this.uninit();
+ break;
+ case at.CLEAR_PREF:
+ Services.prefs.clearUserPref(this._prefs._branchStr + action.data.name);
+ break;
+ case at.SET_PREF:
+ this._prefs.set(action.data.name, action.data.value);
+ break;
+ case at.UPDATE_SECTION_PREFS:
+ this._setIndexedDBPref(action.data.id, action.data.value);
+ break;
+ }
+ }
+};
+
+const EXPORTED_SYMBOLS = ["PrefsFeed"];
diff --git a/browser/components/newtab/lib/RecommendationProviderSwitcher.jsm b/browser/components/newtab/lib/RecommendationProviderSwitcher.jsm
new file mode 100644
index 0000000000..276fe0f7a1
--- /dev/null
+++ b/browser/components/newtab/lib/RecommendationProviderSwitcher.jsm
@@ -0,0 +1,195 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+ChromeUtils.defineModuleGetter(
+ this,
+ "UserDomainAffinityProvider",
+ "resource://activity-stream/lib/UserDomainAffinityProvider.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "PersonalityProvider",
+ "resource://activity-stream/lib/PersonalityProvider/PersonalityProvider.jsm"
+);
+const { actionTypes: at, actionCreators: ac } = ChromeUtils.import(
+ "resource://activity-stream/common/Actions.jsm"
+);
+const PREF_PERSONALIZATION_VERSION = "discoverystream.personalization.version";
+const PREF_PERSONALIZATION_OVERRIDE_VERSION =
+ "discoverystream.personalization.overrideVersion";
+const PREF_PERSONALIZATION_MODEL_KEYS =
+ "discoverystream.personalization.modelKeys";
+
+// The main purpose of this class is to handle interaction between one of the two providers.
+// So all calls to the providers, anything involved with the switching between either provider,
+// or anything involved with the setup or teardown of the switcher is contained in here.
+this.RecommendationProviderSwitcher = class RecommendationProviderSwitcher {
+ /**
+ * setAffinityProvider - This function switches between setting up a v1 or v2
+ * personalization provider.
+ * It checks for certain configuration on affinityProviderV2,
+ * which is setup in setAffinityProviderVersion.
+ * In the case of v1, it returns a UserDomainAffinityProvider,
+ * in the case of v2, it reutrns a PersonalityProvider.
+ *
+ * We need to do this swap because v2 is still being tested,
+ * so by default v1 should be enabled.
+ * This is why the function params are the same, as v2 has been
+ * written to accept a similar pattern.
+ *
+ * @param {Array} timeSegments Changes the weight of a score based on how recent it is.
+ * @param {Object} parameterSets Provides factors for weighting which allows for
+ * flexible targeting. The functionality to calculate final scores can
+ * be seen in UserDomainAffinityProvider#calculateScores
+ * @param {Number} maxHistoryQueryResults How far back in the history do we go.
+ * @param {Number} version What version of the provider does this use. Note, this is NOT
+ * the same as personalization v1/v2, this could be used to change between
+ * a configuration or value in the provider, not to enable/disable a whole
+ * new provider.
+ * @param {Object} scores This is used to re hydrate the provider based on cached results.
+ * @returns {Object} A provider, either a PersonalityProvider or
+ * UserDomainAffinityProvider.
+ */
+ setAffinityProvider(...args) {
+ const { affinityProviderV2 } = this;
+ if (affinityProviderV2 && affinityProviderV2.modelKeys) {
+ // A v2 provider is already set. This can happen when new stories come in
+ // and we need to update their scores.
+ // We can use the existing one, a fresh one is created after startup.
+ // Using the existing one might be a bit out of date,
+ // but it's fine for now. We can rely on restarts for updates.
+ // See bug 1629931 for improvements to this.
+ if (this.affinityProvider) {
+ return;
+ }
+ // At this point we've determined we can successfully create a v2 personalization provider.
+ if (!this.affinityProvider) {
+ this.affinityProvider = new PersonalityProvider({
+ modelKeys: affinityProviderV2.modelKeys,
+ dispatch: this.store.dispatch,
+ });
+ }
+ this.affinityProvider.setAffinities(...args);
+ return;
+ }
+
+ // Otherwise, if we get this far, we fallback to a v1 personalization provider.
+ this.affinityProvider = new UserDomainAffinityProvider(...args);
+ }
+
+ /*
+ * This calls any async initialization that's required,
+ * and then signals to devtools when that's done.
+ * This is not the same as the switcher feed init,
+ * this is to init the provider that the switcher controls.
+ * The switcher feed init just calls setVersion.
+ */
+ async init() {
+ if (this.affinityProvider && this.affinityProvider.init) {
+ await this.affinityProvider.init();
+ this.store.dispatch(
+ ac.BroadcastToContent({
+ type: at.DISCOVERY_STREAM_PERSONALIZATION_INIT,
+ })
+ );
+ }
+ }
+
+ /**
+ * Sets affinityProvider state to the correct version.
+ */
+ setVersion(isStartup = false) {
+ const version = this.store.getState().Prefs.values[
+ PREF_PERSONALIZATION_VERSION
+ ];
+ const overrideVersion = this.store.getState().Prefs.values[
+ PREF_PERSONALIZATION_OVERRIDE_VERSION
+ ];
+
+ const modelKeys = this.store.getState().Prefs.values[
+ PREF_PERSONALIZATION_MODEL_KEYS
+ ];
+ if (version === 2 && modelKeys && overrideVersion !== 1) {
+ this.affinityProviderV2 = {
+ modelKeys: modelKeys.split(",").map(i => i.trim()),
+ };
+ }
+
+ this.store.dispatch(
+ ac.BroadcastToContent({
+ type: at.DISCOVERY_STREAM_PERSONALIZATION_VERSION,
+ data: {
+ version,
+ },
+ meta: {
+ isStartup,
+ },
+ })
+ );
+ }
+
+ getAffinities() {
+ return this.affinityProvider.getAffinities();
+ }
+
+ async calculateItemRelevanceScore(item) {
+ if (this.affinityProvider) {
+ const scoreResult = await this.affinityProvider.calculateItemRelevanceScore(
+ item
+ );
+ if (scoreResult === 0 || scoreResult) {
+ item.score = scoreResult;
+ }
+ }
+ }
+
+ teardown() {
+ if (this.affinityProvider && this.affinityProvider.teardown) {
+ // This removes any in memory listeners if available.
+ this.affinityProvider.teardown();
+ }
+ }
+
+ resetState() {
+ this.affinityProviderV2 = null;
+ this.affinityProvider = null;
+ }
+
+ onAction(action) {
+ switch (action.type) {
+ case at.INIT:
+ this.setVersion(true /* isStartup */);
+ break;
+ case at.DISCOVERY_STREAM_CONFIG_CHANGE:
+ this.teardown();
+ this.resetState();
+ this.setVersion();
+ break;
+ case at.PREF_CHANGED:
+ switch (action.data.name) {
+ case PREF_PERSONALIZATION_VERSION:
+ case PREF_PERSONALIZATION_MODEL_KEYS:
+ this.store.dispatch(
+ ac.BroadcastToContent({
+ type: at.DISCOVERY_STREAM_CONFIG_RESET,
+ })
+ );
+ break;
+ }
+ break;
+ case at.DISCOVERY_STREAM_PERSONALIZATION_VERSION_TOGGLE:
+ let version = this.store.getState().Prefs.values[
+ PREF_PERSONALIZATION_VERSION
+ ];
+
+ // Toggle the version between 1 and 2.
+ this.store.dispatch(
+ ac.SetPref(PREF_PERSONALIZATION_VERSION, version === 1 ? 2 : 1)
+ );
+ break;
+ }
+ }
+};
+
+const EXPORTED_SYMBOLS = ["RecommendationProviderSwitcher"];
diff --git a/browser/components/newtab/lib/RemoteL10n.jsm b/browser/components/newtab/lib/RemoteL10n.jsm
new file mode 100644
index 0000000000..f2ec20323d
--- /dev/null
+++ b/browser/components/newtab/lib/RemoteL10n.jsm
@@ -0,0 +1,248 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
+/**
+ * The downloaded Fluent file is located in this sub-directory of the local
+ * profile directory.
+ */
+const RS_DOWNLOADED_FILE_SUBDIR = "settings/main/ms-language-packs";
+const USE_REMOTE_L10N_PREF =
+ "browser.newtabpage.activity-stream.asrouter.useRemoteL10n";
+
+const { XPCOMUtils } = ChromeUtils.import(
+ "resource://gre/modules/XPCOMUtils.jsm"
+);
+
+XPCOMUtils.defineLazyModuleGetters(this, {
+ L10nRegistry: "resource://gre/modules/L10nRegistry.jsm",
+ FileSource: "resource://gre/modules/L10nRegistry.jsm",
+ OS: "resource://gre/modules/osfile.jsm",
+ Services: "resource://gre/modules/Services.jsm",
+});
+
+/**
+ * All supported locales for remote l10n
+ *
+ * This is used by ASRouter.jsm to check if the locale is supported before
+ * issuing the request for remote fluent files to RemoteSettings.
+ *
+ * Note:
+ * * this is generated based on "browser/locales/all-locales" as l10n doesn't
+ * provide an API to fetch that list
+ *
+ * * this list doesn't include "en-US", though "en-US" is well supported and
+ * `_RemoteL10n.isLocaleSupported()` will handle it properly
+ */
+const ALL_LOCALES = new Set([
+ "ach",
+ "af",
+ "an",
+ "ar",
+ "ast",
+ "az",
+ "be",
+ "bg",
+ "bn",
+ "bo",
+ "br",
+ "brx",
+ "bs",
+ "ca",
+ "ca-valencia",
+ "cak",
+ "ckb",
+ "cs",
+ "cy",
+ "da",
+ "de",
+ "dsb",
+ "el",
+ "en-CA",
+ "en-GB",
+ "eo",
+ "es-AR",
+ "es-CL",
+ "es-ES",
+ "es-MX",
+ "et",
+ "eu",
+ "fa",
+ "ff",
+ "fi",
+ "fr",
+ "fy-NL",
+ "ga-IE",
+ "gd",
+ "gl",
+ "gn",
+ "gu-IN",
+ "he",
+ "hi-IN",
+ "hr",
+ "hsb",
+ "hu",
+ "hy-AM",
+ "hye",
+ "ia",
+ "id",
+ "is",
+ "it",
+ "ja",
+ "ja-JP-mac",
+ "ka",
+ "kab",
+ "kk",
+ "km",
+ "kn",
+ "ko",
+ "lij",
+ "lo",
+ "lt",
+ "ltg",
+ "lv",
+ "meh",
+ "mk",
+ "mr",
+ "ms",
+ "my",
+ "nb-NO",
+ "ne-NP",
+ "nl",
+ "nn-NO",
+ "oc",
+ "pa-IN",
+ "pl",
+ "pt-BR",
+ "pt-PT",
+ "rm",
+ "ro",
+ "ru",
+ "scn",
+ "si",
+ "sk",
+ "sl",
+ "son",
+ "sq",
+ "sr",
+ "sv-SE",
+ "szl",
+ "ta",
+ "te",
+ "th",
+ "tl",
+ "tr",
+ "trs",
+ "uk",
+ "ur",
+ "uz",
+ "vi",
+ "wo",
+ "xh",
+ "zh-CN",
+ "zh-TW",
+]);
+
+class _RemoteL10n {
+ constructor() {
+ this._l10n = null;
+ }
+
+ createElement(doc, elem, options = {}) {
+ let node;
+ if (options.content && options.content.string_id) {
+ node = doc.createElement("remote-text");
+ } else {
+ node = doc.createElementNS("http://www.w3.org/1999/xhtml", elem);
+ }
+ if (options.classList) {
+ node.classList.add(options.classList);
+ }
+ this.setString(node, options);
+
+ return node;
+ }
+
+ // If `string_id` is present it means we are relying on fluent for translations.
+ // Otherwise, we have a vanilla string.
+ setString(el, { content, attributes = {} }) {
+ if (content && content.string_id) {
+ for (let [fluentId, value] of Object.entries(attributes)) {
+ el.setAttribute(`fluent-variable-${fluentId}`, value);
+ }
+ el.setAttribute("fluent-remote-id", content.string_id);
+ } else {
+ el.textContent = content;
+ }
+ }
+
+ /**
+ * Creates a new DOMLocalization instance with the Fluent file from Remote Settings.
+ *
+ * Note: it will use the local Fluent file in any of following cases:
+ * * the remote Fluent file is not available
+ * * it was told to use the local Fluent file
+ */
+ _createDOML10n() {
+ /* istanbul ignore next */
+ async function* generateBundles(resourceIds) {
+ const appLocale = Services.locale.appLocaleAsBCP47;
+ const appLocales = Services.locale.appLocalesAsBCP47;
+ const l10nFluentDir = OS.Path.join(
+ OS.Constants.Path.localProfileDir,
+ RS_DOWNLOADED_FILE_SUBDIR
+ );
+ const fs = new FileSource("cfr", [appLocale], `file://${l10nFluentDir}/`);
+ // In the case that the Fluent file has not been downloaded from Remote Settings,
+ // `fetchFile` will return `false` and fall back to the packaged Fluent file.
+ const resource = await fs.fetchFile(appLocale, "asrouter.ftl");
+ for await (let bundle of L10nRegistry.generateBundles(
+ appLocales.slice(0, 1),
+ resourceIds
+ )) {
+ // Override built-in messages with the resource loaded from remote settings for
+ // the app locale, i.e. the first item of `appLocales`.
+ if (resource) {
+ bundle.addResource(resource, { allowOverrides: true });
+ }
+ yield bundle;
+ }
+ // Now generating bundles for the rest of locales of `appLocales`.
+ yield* L10nRegistry.generateBundles(appLocales.slice(1), resourceIds);
+ }
+
+ return new DOMLocalization(
+ [
+ "browser/newtab/asrouter.ftl",
+ "browser/branding/brandings.ftl",
+ "browser/branding/sync-brand.ftl",
+ "branding/brand.ftl",
+ "browser/defaultBrowserNotification.ftl",
+ ],
+ false,
+ Services.prefs.getBoolPref(USE_REMOTE_L10N_PREF, true)
+ ? { generateBundles }
+ : {}
+ );
+ }
+
+ get l10n() {
+ if (!this._l10n) {
+ this._l10n = this._createDOML10n();
+ }
+ return this._l10n;
+ }
+
+ reloadL10n() {
+ this._l10n = null;
+ }
+
+ isLocaleSupported(locale) {
+ return locale === "en-US" || ALL_LOCALES.has(locale);
+ }
+}
+
+this.RemoteL10n = new _RemoteL10n();
+
+const EXPORTED_SYMBOLS = ["RemoteL10n", "_RemoteL10n"];
diff --git a/browser/components/newtab/lib/Screenshots.jsm b/browser/components/newtab/lib/Screenshots.jsm
new file mode 100644
index 0000000000..4e8a552af0
--- /dev/null
+++ b/browser/components/newtab/lib/Screenshots.jsm
@@ -0,0 +1,151 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
+const EXPORTED_SYMBOLS = ["Screenshots"];
+
+const { XPCOMUtils } = ChromeUtils.import(
+ "resource://gre/modules/XPCOMUtils.jsm"
+);
+
+XPCOMUtils.defineLazyGlobalGetters(this, ["fetch"]);
+
+ChromeUtils.defineModuleGetter(
+ this,
+ "BackgroundPageThumbs",
+ "resource://gre/modules/BackgroundPageThumbs.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "PageThumbs",
+ "resource://gre/modules/PageThumbs.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "PrivateBrowsingUtils",
+ "resource://gre/modules/PrivateBrowsingUtils.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "Services",
+ "resource://gre/modules/Services.jsm"
+);
+
+const GREY_10 = "#F9F9FA";
+
+XPCOMUtils.defineLazyPreferenceGetter(
+ this,
+ "gPrivilegedAboutProcessEnabled",
+ "browser.tabs.remote.separatePrivilegedContentProcess",
+ false
+);
+
+this.Screenshots = {
+ /**
+ * Get a screenshot / thumbnail for a url. Either returns the disk cached
+ * image or initiates a background request for the url.
+ *
+ * @param url {string} The url to get a thumbnail
+ * @return {Promise} Resolves a custom object or null if failed
+ */
+ async getScreenshotForURL(url) {
+ try {
+ await BackgroundPageThumbs.captureIfMissing(url, {
+ backgroundColor: GREY_10,
+ });
+
+ // The privileged about content process is able to use the moz-page-thumb
+ // protocol, so if it's enabled, send that down.
+ if (gPrivilegedAboutProcessEnabled) {
+ return PageThumbs.getThumbnailURL(url);
+ }
+
+ // Otherwise, for normal content processes, we fallback to using
+ // Blob URIs for the screenshots.
+ const imgPath = PageThumbs.getThumbnailPath(url);
+
+ const filePathResponse = await fetch(`file://${imgPath}`);
+ const fileContents = await filePathResponse.blob();
+
+ // Check if the file is empty, which indicates there isn't actually a
+ // thumbnail, so callers can show a failure state.
+ if (fileContents.size === 0) {
+ return null;
+ }
+
+ return { path: imgPath, data: fileContents };
+ } catch (err) {
+ Cu.reportError(`getScreenshot(${url}) failed: ${err}`);
+ }
+
+ // We must have failed to get the screenshot, so persist the failure by
+ // storing an empty file. Future calls will then skip requesting and return
+ // failure, so do the same thing here. The empty file should not expire with
+ // the usual filtering process to avoid repeated background requests, which
+ // can cause unwanted high CPU, network and memory usage - Bug 1384094
+ try {
+ await PageThumbs._store(url, url, null, true);
+ } catch (err) {
+ // Probably failed to create the empty file, but not much more we can do.
+ }
+ return null;
+ },
+
+ /**
+ * Checks if all the open windows are private browsing windows. If so, we do not
+ * want to collect screenshots. If there exists at least 1 non-private window,
+ * we are ok to collect screenshots.
+ */
+ _shouldGetScreenshots() {
+ for (let win of Services.wm.getEnumerator("navigator:browser")) {
+ if (!PrivateBrowsingUtils.isWindowPrivate(win)) {
+ // As soon as we encounter 1 non-private window, screenshots are fair game.
+ return true;
+ }
+ }
+ return false;
+ },
+
+ /**
+ * Conditionally get a screenshot for a link if there's no existing pending
+ * screenshot. Updates the cached link's desired property with the result.
+ *
+ * @param link {object} Link object to update
+ * @param url {string} Url to get a screenshot of
+ * @param property {string} Name of property on object to set
+ @ @param onScreenshot {function} Callback for when the screenshot loads
+ */
+ async maybeCacheScreenshot(link, url, property, onScreenshot) {
+ // If there are only private windows open, do not collect screenshots
+ if (!this._shouldGetScreenshots()) {
+ return;
+ }
+ // __sharedCache may not exist yet for links from default top sites that
+ // don't have a default tippy top icon.
+ if (!link.__sharedCache) {
+ link.__sharedCache = {
+ updateLink(prop, val) {
+ link[prop] = val;
+ },
+ };
+ }
+ const cache = link.__sharedCache;
+ // Nothing to do if we already have a pending screenshot or
+ // if a previous request failed and returned null.
+ if (cache.fetchingScreenshot || link[property] !== undefined) {
+ return;
+ }
+
+ // Save the promise to the cache so other links get it immediately
+ cache.fetchingScreenshot = this.getScreenshotForURL(url);
+
+ // Clean up now that we got the screenshot
+ const screenshot = await cache.fetchingScreenshot;
+ delete cache.fetchingScreenshot;
+
+ // Update the cache for future links and call back for existing content
+ cache.updateLink(property, screenshot);
+ onScreenshot(screenshot);
+ },
+};
diff --git a/browser/components/newtab/lib/SearchShortcuts.jsm b/browser/components/newtab/lib/SearchShortcuts.jsm
new file mode 100644
index 0000000000..ef8985e81a
--- /dev/null
+++ b/browser/components/newtab/lib/SearchShortcuts.jsm
@@ -0,0 +1,82 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
+const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
+
+// List of sites we match against Topsites in order to identify sites
+// that should be converted to search Topsites
+const SEARCH_SHORTCUTS = [
+ { keyword: "@amazon", shortURL: "amazon", url: "https://amazon.com" },
+ { keyword: "@\u767E\u5EA6", shortURL: "baidu", url: "https://baidu.com" },
+ { keyword: "@google", shortURL: "google", url: "https://google.com" },
+ {
+ keyword: "@\u044F\u043D\u0434\u0435\u043A\u0441",
+ shortURL: "yandex",
+ url: "https://yandex.com",
+ },
+];
+this.SEARCH_SHORTCUTS = SEARCH_SHORTCUTS;
+
+// These can be added via the editor but will not be added organically
+this.CUSTOM_SEARCH_SHORTCUTS = [
+ ...SEARCH_SHORTCUTS,
+ { keyword: "@bing", shortURL: "bing", url: "https://bing.com" },
+ {
+ keyword: "@duckduckgo",
+ shortURL: "duckduckgo",
+ url: "https://duckduckgo.com",
+ },
+ { keyword: "@ebay", shortURL: "ebay", url: "https://ebay.com" },
+ { keyword: "@twitter", shortURL: "twitter", url: "https://twitter.com" },
+ {
+ keyword: "@wikipedia",
+ shortURL: "wikipedia",
+ url: "https://wikipedia.org",
+ },
+];
+
+// Note: you must add the activity stream branch to the beginning of this if using outside activity stream
+this.SEARCH_SHORTCUTS_EXPERIMENT = "improvesearch.topSiteSearchShortcuts";
+this.SEARCH_SHORTCUTS_SEARCH_ENGINES_PREF =
+ "improvesearch.topSiteSearchShortcuts.searchEngines";
+this.SEARCH_SHORTCUTS_HAVE_PINNED_PREF =
+ "improvesearch.topSiteSearchShortcuts.havePinned";
+
+function getSearchProvider(candidateShortURL) {
+ return (
+ SEARCH_SHORTCUTS.filter(match => candidateShortURL === match.shortURL)[0] ||
+ null
+ );
+}
+this.getSearchProvider = getSearchProvider;
+
+// Get the search form URL for a given search keyword. This allows us to pick
+// different tippytop icons for the different variants. Sush as yandex.com vs. yandex.ru.
+// See more details in bug 1643523.
+async function getSearchFormURL(keyword) {
+ const engine = await Services.search.getEngineByAlias(keyword);
+ return engine?.wrappedJSObject._searchForm;
+}
+this.getSearchFormURL = getSearchFormURL;
+
+// Check topsite against predefined list of valid search engines
+// https://searchfox.org/mozilla-central/rev/ca869724246f4230b272ed1c8b9944596e80d920/toolkit/components/search/nsSearchService.js#939
+async function checkHasSearchEngine(keyword) {
+ return (await Services.search.getAppProvidedEngines()).find(e =>
+ e.aliases.includes(keyword)
+ );
+}
+this.checkHasSearchEngine = checkHasSearchEngine;
+
+const EXPORTED_SYMBOLS = [
+ "checkHasSearchEngine",
+ "getSearchProvider",
+ "getSearchFormURL",
+ "SEARCH_SHORTCUTS",
+ "CUSTOM_SEARCH_SHORTCUTS",
+ "SEARCH_SHORTCUTS_EXPERIMENT",
+ "SEARCH_SHORTCUTS_SEARCH_ENGINES_PREF",
+ "SEARCH_SHORTCUTS_HAVE_PINNED_PREF",
+];
diff --git a/browser/components/newtab/lib/SectionsManager.jsm b/browser/components/newtab/lib/SectionsManager.jsm
new file mode 100644
index 0000000000..511da60c0b
--- /dev/null
+++ b/browser/components/newtab/lib/SectionsManager.jsm
@@ -0,0 +1,727 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
+const { EventEmitter } = ChromeUtils.import(
+ "resource://gre/modules/EventEmitter.jsm"
+);
+const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
+const { actionCreators: ac, actionTypes: at } = ChromeUtils.import(
+ "resource://activity-stream/common/Actions.jsm"
+);
+const { getDefaultOptions } = ChromeUtils.import(
+ "resource://activity-stream/lib/ActivityStreamStorage.jsm"
+);
+
+ChromeUtils.defineModuleGetter(
+ this,
+ "PlacesUtils",
+ "resource://gre/modules/PlacesUtils.jsm"
+);
+
+/*
+ * Generators for built in sections, keyed by the pref name for their feed.
+ * Built in sections may depend on options stored as serialised JSON in the pref
+ * `${feed_pref_name}.options`.
+ */
+const BUILT_IN_SECTIONS = {
+ "feeds.section.topstories": options => ({
+ id: "topstories",
+ pref: {
+ titleString: {
+ id: "home-prefs-recommended-by-header",
+ values: { provider: options.provider_name },
+ },
+ descString: {
+ id:
+ Services.prefs.getBoolPref(
+ "browser.newtabpage.activity-stream.newNewtabExperience.enabled"
+ ) ||
+ Services.prefs.getBoolPref(
+ "browser.newtabpage.activity-stream.customizationMenu.enabled"
+ )
+ ? "home-prefs-recommended-by-description-new"
+ : "home-prefs-recommended-by-description-update",
+ values: { provider: options.provider_name },
+ },
+ nestedPrefs: options.show_spocs
+ ? [
+ {
+ name: "showSponsored",
+ titleString: "home-prefs-recommended-by-option-sponsored-stories",
+ icon: "icon-info",
+ eventSource: "POCKET_SPOCS",
+ },
+ ]
+ : [],
+ learnMore: {
+ link: {
+ href: "https://getpocket.com/firefox/new_tab_learn_more",
+ id: "home-prefs-recommended-by-learn-more",
+ },
+ },
+ },
+ shouldHidePref: options.hidden,
+ eventSource: "TOP_STORIES",
+ icon: options.provider_icon,
+ title: {
+ id: "newtab-section-header-pocket",
+ values: { provider: options.provider_name },
+ },
+ learnMore: {
+ link: {
+ href: "https://getpocket.com/firefox/new_tab_learn_more",
+ message: { id: "newtab-pocket-learn-more" },
+ },
+ },
+ privacyNoticeURL:
+ "https://www.mozilla.org/privacy/firefox/#suggest-relevant-content",
+ compactCards: false,
+ rowsPref: "section.topstories.rows",
+ maxRows: 4,
+ availableLinkMenuOptions: [
+ "CheckBookmarkOrArchive",
+ "CheckSavedToPocket",
+ "Separator",
+ "OpenInNewWindow",
+ "OpenInPrivateWindow",
+ "Separator",
+ "BlockUrl",
+ ],
+ emptyState: {
+ message: {
+ id: "newtab-empty-section-topstories",
+ values: { provider: options.provider_name },
+ },
+ icon: "check",
+ },
+ shouldSendImpressionStats: true,
+ dedupeFrom: ["highlights"],
+ }),
+ "feeds.section.highlights": options => ({
+ id: "highlights",
+ pref: {
+ titleString: {
+ id:
+ Services.prefs.getBoolPref(
+ "browser.newtabpage.activity-stream.newNewtabExperience.enabled"
+ ) ||
+ Services.prefs.getBoolPref(
+ "browser.newtabpage.activity-stream.customizationMenu.enabled"
+ )
+ ? "home-prefs-recent-activity-header"
+ : "home-prefs-highlights-header",
+ },
+ descString: {
+ id:
+ Services.prefs.getBoolPref(
+ "browser.newtabpage.activity-stream.newNewtabExperience.enabled"
+ ) ||
+ Services.prefs.getBoolPref(
+ "browser.newtabpage.activity-stream.customizationMenu.enabled"
+ )
+ ? "home-prefs-recent-activity-description"
+ : "home-prefs-highlights-description",
+ },
+ nestedPrefs: [
+ {
+ name: "section.highlights.includeVisited",
+ titleString: "home-prefs-highlights-option-visited-pages",
+ },
+ {
+ name: "section.highlights.includeBookmarks",
+ titleString: "home-prefs-highlights-options-bookmarks",
+ },
+ {
+ name: "section.highlights.includeDownloads",
+ titleString: "home-prefs-highlights-option-most-recent-download",
+ },
+ {
+ name: "section.highlights.includePocket",
+ titleString: "home-prefs-highlights-option-saved-to-pocket",
+ hidden: !Services.prefs.getBoolPref(
+ "extensions.pocket.enabled",
+ true
+ ),
+ },
+ ],
+ },
+ shouldHidePref: false,
+ eventSource: "HIGHLIGHTS",
+ icon: "highlights",
+ title: {
+ id:
+ Services.prefs.getBoolPref(
+ "browser.newtabpage.activity-stream.newNewtabExperience.enabled"
+ ) ||
+ Services.prefs.getBoolPref(
+ "browser.newtabpage.activity-stream.customizationMenu.enabled"
+ )
+ ? "newtab-section-header-recent-activity"
+ : "newtab-section-header-highlights",
+ },
+ compactCards: true,
+ rowsPref: "section.highlights.rows",
+ maxRows: 4,
+ emptyState: {
+ message: { id: "newtab-empty-section-highlights" },
+ icon: "highlights",
+ },
+ shouldSendImpressionStats: false,
+ }),
+};
+
+const SectionsManager = {
+ ACTIONS_TO_PROXY: ["WEBEXT_CLICK", "WEBEXT_DISMISS"],
+ CONTEXT_MENU_PREFS: { CheckSavedToPocket: "extensions.pocket.enabled" },
+ CONTEXT_MENU_OPTIONS_FOR_HIGHLIGHT_TYPES: {
+ history: [
+ "CheckBookmark",
+ "CheckSavedToPocket",
+ "Separator",
+ "OpenInNewWindow",
+ "OpenInPrivateWindow",
+ "Separator",
+ "BlockUrl",
+ "DeleteUrl",
+ ],
+ bookmark: [
+ "CheckBookmark",
+ "CheckSavedToPocket",
+ "Separator",
+ "OpenInNewWindow",
+ "OpenInPrivateWindow",
+ "Separator",
+ "BlockUrl",
+ "DeleteUrl",
+ ],
+ pocket: [
+ "ArchiveFromPocket",
+ "CheckSavedToPocket",
+ "Separator",
+ "OpenInNewWindow",
+ "OpenInPrivateWindow",
+ "Separator",
+ "BlockUrl",
+ ],
+ download: [
+ "OpenFile",
+ "ShowFile",
+ "Separator",
+ "GoToDownloadPage",
+ "CopyDownloadLink",
+ "Separator",
+ "RemoveDownload",
+ "BlockUrl",
+ ],
+ },
+ initialized: false,
+ sections: new Map(),
+ async init(prefs = {}, storage) {
+ this._storage = storage;
+
+ for (const feedPrefName of Object.keys(BUILT_IN_SECTIONS)) {
+ const optionsPrefName = `${feedPrefName}.options`;
+ await this.addBuiltInSection(feedPrefName, prefs[optionsPrefName]);
+
+ this._dedupeConfiguration = [];
+ this.sections.forEach(section => {
+ if (section.dedupeFrom) {
+ this._dedupeConfiguration.push({
+ id: section.id,
+ dedupeFrom: section.dedupeFrom,
+ });
+ }
+ });
+ }
+
+ Object.keys(this.CONTEXT_MENU_PREFS).forEach(k =>
+ Services.prefs.addObserver(this.CONTEXT_MENU_PREFS[k], this)
+ );
+
+ this.initialized = true;
+ this.emit(this.INIT);
+ },
+ observe(subject, topic, data) {
+ switch (topic) {
+ case "nsPref:changed":
+ for (const pref of Object.keys(this.CONTEXT_MENU_PREFS)) {
+ if (data === this.CONTEXT_MENU_PREFS[pref]) {
+ this.updateSections();
+ }
+ }
+ break;
+ }
+ },
+ updateSectionPrefs(id, collapsed) {
+ const section = this.sections.get(id);
+ if (!section) {
+ return;
+ }
+
+ const updatedSection = Object.assign({}, section, {
+ pref: Object.assign({}, section.pref, collapsed),
+ });
+ this.updateSection(id, updatedSection, true);
+ },
+ async addBuiltInSection(feedPrefName, optionsPrefValue = "{}") {
+ let options;
+ let storedPrefs;
+ try {
+ options = JSON.parse(optionsPrefValue);
+ } catch (e) {
+ options = {};
+ Cu.reportError(`Problem parsing options pref for ${feedPrefName}`);
+ }
+ try {
+ storedPrefs = (await this._storage.get(feedPrefName)) || {};
+ } catch (e) {
+ storedPrefs = {};
+ Cu.reportError(`Problem getting stored prefs for ${feedPrefName}`);
+ }
+ const defaultSection = BUILT_IN_SECTIONS[feedPrefName](options);
+ const section = Object.assign({}, defaultSection, {
+ pref: Object.assign(
+ {},
+ defaultSection.pref,
+ getDefaultOptions(storedPrefs)
+ ),
+ });
+ section.pref.feed = feedPrefName;
+ this.addSection(section.id, Object.assign(section, { options }));
+ },
+ addSection(id, options) {
+ this.updateLinkMenuOptions(options, id);
+ this.sections.set(id, options);
+ this.emit(this.ADD_SECTION, id, options);
+ },
+ removeSection(id) {
+ this.emit(this.REMOVE_SECTION, id);
+ this.sections.delete(id);
+ },
+ enableSection(id, isStartup = false) {
+ this.updateSection(id, { enabled: true }, true, isStartup);
+ this.emit(this.ENABLE_SECTION, id);
+ },
+ disableSection(id) {
+ this.updateSection(
+ id,
+ { enabled: false, rows: [], initialized: false },
+ true
+ );
+ this.emit(this.DISABLE_SECTION, id);
+ },
+ updateSections() {
+ this.sections.forEach((section, id) =>
+ this.updateSection(id, section, true)
+ );
+ },
+ updateSection(id, options, shouldBroadcast, isStartup = false) {
+ this.updateLinkMenuOptions(options, id);
+ if (this.sections.has(id)) {
+ const optionsWithDedupe = Object.assign({}, options, {
+ dedupeConfigurations: this._dedupeConfiguration,
+ });
+ this.sections.set(id, Object.assign(this.sections.get(id), options));
+ this.emit(
+ this.UPDATE_SECTION,
+ id,
+ optionsWithDedupe,
+ shouldBroadcast,
+ isStartup
+ );
+ }
+ },
+
+ /**
+ * Save metadata to places db and add a visit for that URL.
+ */
+ updateBookmarkMetadata({ url }) {
+ this.sections.forEach((section, id) => {
+ if (id === "highlights") {
+ // Skip Highlights cards, we already have that metadata.
+ return;
+ }
+ if (section.rows) {
+ section.rows.forEach(card => {
+ if (
+ card.url === url &&
+ card.description &&
+ card.title &&
+ card.image
+ ) {
+ PlacesUtils.history.update({
+ url: card.url,
+ title: card.title,
+ description: card.description,
+ previewImageURL: card.image,
+ });
+ // Highlights query skips bookmarks with no visits.
+ PlacesUtils.history.insert({
+ url,
+ title: card.title,
+ visits: [{}],
+ });
+ }
+ });
+ }
+ });
+ },
+
+ /**
+ * Sets the section's context menu options. These are all available context menu
+ * options minus the ones that are tied to a pref (see CONTEXT_MENU_PREFS) set
+ * to false.
+ *
+ * @param options section options
+ * @param id section ID
+ */
+ updateLinkMenuOptions(options, id) {
+ if (options.availableLinkMenuOptions) {
+ options.contextMenuOptions = options.availableLinkMenuOptions.filter(
+ o =>
+ !this.CONTEXT_MENU_PREFS[o] ||
+ Services.prefs.getBoolPref(this.CONTEXT_MENU_PREFS[o])
+ );
+ }
+
+ // Once we have rows, we can give each card it's own context menu based on it's type.
+ // We only want to do this for highlights because those have different data types.
+ // All other sections (built by the web extension API) will have the same context menu per section
+ if (options.rows && id === "highlights") {
+ this._addCardTypeLinkMenuOptions(options.rows);
+ }
+ },
+
+ /**
+ * Sets each card in highlights' context menu options based on the card's type.
+ * (See types.js for a list of types)
+ *
+ * @param rows section rows containing a type for each card
+ */
+ _addCardTypeLinkMenuOptions(rows) {
+ for (let card of rows) {
+ if (!this.CONTEXT_MENU_OPTIONS_FOR_HIGHLIGHT_TYPES[card.type]) {
+ Cu.reportError(
+ `No context menu for highlight type ${card.type} is configured`
+ );
+ } else {
+ card.contextMenuOptions = this.CONTEXT_MENU_OPTIONS_FOR_HIGHLIGHT_TYPES[
+ card.type
+ ];
+
+ // Remove any options that shouldn't be there based on CONTEXT_MENU_PREFS.
+ // For example: If the Pocket extension is disabled, we should remove the CheckSavedToPocket option
+ // for each card that has it
+ card.contextMenuOptions = card.contextMenuOptions.filter(
+ o =>
+ !this.CONTEXT_MENU_PREFS[o] ||
+ Services.prefs.getBoolPref(this.CONTEXT_MENU_PREFS[o])
+ );
+ }
+ }
+ },
+
+ /**
+ * Update a specific section card by its url. This allows an action to be
+ * broadcast to all existing pages to update a specific card without having to
+ * also force-update the rest of the section's cards and state on those pages.
+ *
+ * @param id The id of the section with the card to be updated
+ * @param url The url of the card to update
+ * @param options The options to update for the card
+ * @param shouldBroadcast Whether or not to broadcast the update
+ * @param isStartup If this update is during startup.
+ */
+ updateSectionCard(id, url, options, shouldBroadcast, isStartup = false) {
+ if (this.sections.has(id)) {
+ const card = this.sections.get(id).rows.find(elem => elem.url === url);
+ if (card) {
+ Object.assign(card, options);
+ }
+ this.emit(
+ this.UPDATE_SECTION_CARD,
+ id,
+ url,
+ options,
+ shouldBroadcast,
+ isStartup
+ );
+ }
+ },
+ removeSectionCard(sectionId, url) {
+ if (!this.sections.has(sectionId)) {
+ return;
+ }
+ const rows = this.sections
+ .get(sectionId)
+ .rows.filter(row => row.url !== url);
+ this.updateSection(sectionId, { rows }, true);
+ },
+ onceInitialized(callback) {
+ if (this.initialized) {
+ callback();
+ } else {
+ this.once(this.INIT, callback);
+ }
+ },
+ uninit() {
+ Object.keys(this.CONTEXT_MENU_PREFS).forEach(k =>
+ Services.prefs.removeObserver(this.CONTEXT_MENU_PREFS[k], this)
+ );
+ SectionsManager.initialized = false;
+ },
+};
+
+for (const action of [
+ "ACTION_DISPATCHED",
+ "ADD_SECTION",
+ "REMOVE_SECTION",
+ "ENABLE_SECTION",
+ "DISABLE_SECTION",
+ "UPDATE_SECTION",
+ "UPDATE_SECTION_CARD",
+ "INIT",
+ "UNINIT",
+]) {
+ SectionsManager[action] = action;
+}
+
+EventEmitter.decorate(SectionsManager);
+
+class SectionsFeed {
+ constructor() {
+ this.init = this.init.bind(this);
+ this.onAddSection = this.onAddSection.bind(this);
+ this.onRemoveSection = this.onRemoveSection.bind(this);
+ this.onUpdateSection = this.onUpdateSection.bind(this);
+ this.onUpdateSectionCard = this.onUpdateSectionCard.bind(this);
+ }
+
+ init() {
+ SectionsManager.on(SectionsManager.ADD_SECTION, this.onAddSection);
+ SectionsManager.on(SectionsManager.REMOVE_SECTION, this.onRemoveSection);
+ SectionsManager.on(SectionsManager.UPDATE_SECTION, this.onUpdateSection);
+ SectionsManager.on(
+ SectionsManager.UPDATE_SECTION_CARD,
+ this.onUpdateSectionCard
+ );
+ // Catch any sections that have already been added
+ SectionsManager.sections.forEach((section, id) =>
+ this.onAddSection(
+ SectionsManager.ADD_SECTION,
+ id,
+ section,
+ true /* isStartup */
+ )
+ );
+ }
+
+ uninit() {
+ SectionsManager.uninit();
+ SectionsManager.emit(SectionsManager.UNINIT);
+ SectionsManager.off(SectionsManager.ADD_SECTION, this.onAddSection);
+ SectionsManager.off(SectionsManager.REMOVE_SECTION, this.onRemoveSection);
+ SectionsManager.off(SectionsManager.UPDATE_SECTION, this.onUpdateSection);
+ SectionsManager.off(
+ SectionsManager.UPDATE_SECTION_CARD,
+ this.onUpdateSectionCard
+ );
+ }
+
+ onAddSection(event, id, options, isStartup = false) {
+ if (options) {
+ this.store.dispatch(
+ ac.BroadcastToContent({
+ type: at.SECTION_REGISTER,
+ data: Object.assign({ id }, options),
+ meta: {
+ isStartup,
+ },
+ })
+ );
+
+ // Make sure the section is in sectionOrder pref. Otherwise, prepend it.
+ const orderedSections = this.orderedSectionIds;
+ if (!orderedSections.includes(id)) {
+ orderedSections.unshift(id);
+ this.store.dispatch(
+ ac.SetPref("sectionOrder", orderedSections.join(","))
+ );
+ }
+ }
+ }
+
+ onRemoveSection(event, id) {
+ this.store.dispatch(
+ ac.BroadcastToContent({ type: at.SECTION_DEREGISTER, data: id })
+ );
+ }
+
+ onUpdateSection(
+ event,
+ id,
+ options,
+ shouldBroadcast = false,
+ isStartup = false
+ ) {
+ if (options) {
+ const action = {
+ type: at.SECTION_UPDATE,
+ data: Object.assign(options, { id }),
+ meta: {
+ isStartup,
+ },
+ };
+ this.store.dispatch(
+ shouldBroadcast
+ ? ac.BroadcastToContent(action)
+ : ac.AlsoToPreloaded(action)
+ );
+ }
+ }
+
+ onUpdateSectionCard(
+ event,
+ id,
+ url,
+ options,
+ shouldBroadcast = false,
+ isStartup = false
+ ) {
+ if (options) {
+ const action = {
+ type: at.SECTION_UPDATE_CARD,
+ data: { id, url, options },
+ meta: {
+ isStartup,
+ },
+ };
+ this.store.dispatch(
+ shouldBroadcast
+ ? ac.BroadcastToContent(action)
+ : ac.AlsoToPreloaded(action)
+ );
+ }
+ }
+
+ get orderedSectionIds() {
+ return this.store.getState().Prefs.values.sectionOrder.split(",");
+ }
+
+ get enabledSectionIds() {
+ let sections = this.store
+ .getState()
+ .Sections.filter(section => section.enabled)
+ .map(s => s.id);
+ // Top Sites is a special case. Append if the feed is enabled.
+ if (this.store.getState().Prefs.values["feeds.topsites"]) {
+ sections.push("topsites");
+ }
+ return sections;
+ }
+
+ moveSection(id, direction) {
+ const orderedSections = this.orderedSectionIds;
+ const enabledSections = this.enabledSectionIds;
+ let index = orderedSections.indexOf(id);
+ orderedSections.splice(index, 1);
+ if (direction > 0) {
+ // "Move Down"
+ while (index < orderedSections.length) {
+ // If the section at the index is enabled/visible, insert moved section after.
+ // Otherwise, move on to the next spot and check it.
+ if (enabledSections.includes(orderedSections[index++])) {
+ break;
+ }
+ }
+ } else {
+ // "Move Up"
+ while (index > 0) {
+ // If the section at the previous index is enabled/visible, insert moved section there.
+ // Otherwise, move on to the previous spot and check it.
+ index--;
+ if (enabledSections.includes(orderedSections[index])) {
+ break;
+ }
+ }
+ }
+
+ orderedSections.splice(index, 0, id);
+ this.store.dispatch(ac.SetPref("sectionOrder", orderedSections.join(",")));
+ }
+
+ async onAction(action) {
+ switch (action.type) {
+ case at.INIT:
+ SectionsManager.onceInitialized(this.init);
+ break;
+ // Wait for pref values, as some sections have options stored in prefs
+ case at.PREFS_INITIAL_VALUES:
+ SectionsManager.init(
+ action.data,
+ this.store.dbStorage.getDbTable("sectionPrefs")
+ );
+ break;
+ case at.PREF_CHANGED: {
+ if (action.data) {
+ const matched = action.data.name.match(
+ /^(feeds.section.(\S+)).options$/i
+ );
+ if (matched) {
+ await SectionsManager.addBuiltInSection(
+ matched[1],
+ action.data.value
+ );
+ this.store.dispatch({
+ type: at.SECTION_OPTIONS_CHANGED,
+ data: matched[2],
+ });
+ }
+ }
+ break;
+ }
+ case at.UPDATE_SECTION_PREFS:
+ SectionsManager.updateSectionPrefs(action.data.id, action.data.value);
+ break;
+ case at.PLACES_BOOKMARK_ADDED:
+ SectionsManager.updateBookmarkMetadata(action.data);
+ break;
+ case at.WEBEXT_DISMISS:
+ if (action.data) {
+ SectionsManager.removeSectionCard(
+ action.data.source,
+ action.data.url
+ );
+ }
+ break;
+ case at.SECTION_DISABLE:
+ SectionsManager.disableSection(action.data);
+ break;
+ case at.SECTION_ENABLE:
+ SectionsManager.enableSection(action.data);
+ break;
+ case at.SECTION_MOVE:
+ this.moveSection(action.data.id, action.data.direction);
+ break;
+ case at.UNINIT:
+ this.uninit();
+ break;
+ }
+ if (
+ SectionsManager.ACTIONS_TO_PROXY.includes(action.type) &&
+ SectionsManager.sections.size > 0
+ ) {
+ SectionsManager.emit(
+ SectionsManager.ACTION_DISPATCHED,
+ action.type,
+ action.data
+ );
+ }
+ }
+}
+
+this.SectionsFeed = SectionsFeed;
+this.SectionsManager = SectionsManager;
+const EXPORTED_SYMBOLS = ["SectionsFeed", "SectionsManager"];
diff --git a/browser/components/newtab/lib/ShortURL.jsm b/browser/components/newtab/lib/ShortURL.jsm
new file mode 100644
index 0000000000..aa92576012
--- /dev/null
+++ b/browser/components/newtab/lib/ShortURL.jsm
@@ -0,0 +1,84 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+const { XPCOMUtils } = ChromeUtils.import(
+ "resource://gre/modules/XPCOMUtils.jsm"
+);
+const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
+
+XPCOMUtils.defineLazyServiceGetter(
+ this,
+ "IDNService",
+ "@mozilla.org/network/idn-service;1",
+ "nsIIDNService"
+);
+
+XPCOMUtils.defineLazyGlobalGetters(this, ["URL"]);
+
+/**
+ * Properly convert internationalized domain names.
+ * @param {string} host Domain hostname.
+ * @returns {string} Hostname suitable to be displayed.
+ */
+function handleIDNHost(hostname) {
+ try {
+ return IDNService.convertToDisplayIDN(hostname, {});
+ } catch (e) {
+ // If something goes wrong (e.g. host is an IP address) just fail back
+ // to the full domain.
+ return hostname;
+ }
+}
+
+/**
+ * Get the effective top level domain of a host.
+ * @param {string} host The host to be analyzed.
+ * @return {str} The suffix or empty string if there's no suffix.
+ */
+function getETLD(host) {
+ try {
+ return Services.eTLD.getPublicSuffixFromHost(host);
+ } catch (err) {
+ return "";
+ }
+}
+
+/**
+ * shortURL - Creates a short version of a link's url, used for display purposes
+ * e.g. {url: http://www.foosite.com} => "foosite"
+ *
+ * @param {obj} link A link object
+ * {str} link.url (required)- The url of the link
+ * @return {str} A short url
+ */
+function shortURL({ url }) {
+ if (!url) {
+ return "";
+ }
+
+ // Make sure we have a valid / parseable url
+ let parsed;
+ try {
+ parsed = new URL(url);
+ } catch (ex) {
+ // Not entirely sure what we have, but just give it back
+ return url;
+ }
+
+ // Clean up the url (lowercase hostname via URL and remove www.)
+ const hostname = parsed.hostname.replace(/^www\./i, "");
+
+ // Remove the eTLD (e.g., com, net) and the preceding period from the hostname
+ const eTLD = getETLD(hostname);
+ const eTLDExtra = eTLD.length ? -(eTLD.length + 1) : Infinity;
+
+ // Ideally get the short eTLD-less host but fall back to longer url parts
+ return (
+ handleIDNHost(hostname.slice(0, eTLDExtra) || hostname) ||
+ parsed.pathname ||
+ parsed.href
+ );
+}
+
+const EXPORTED_SYMBOLS = ["shortURL", "getETLD"];
diff --git a/browser/components/newtab/lib/SiteClassifier.jsm b/browser/components/newtab/lib/SiteClassifier.jsm
new file mode 100644
index 0000000000..9527745bef
--- /dev/null
+++ b/browser/components/newtab/lib/SiteClassifier.jsm
@@ -0,0 +1,99 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
+const { RemoteSettings } = ChromeUtils.import(
+ "resource://services-settings/remote-settings.js"
+);
+
+// Returns whether the passed in params match the criteria.
+// To match, they must contain all the params specified in criteria and the values
+// must match if a value is provided in criteria.
+function _hasParams(criteria, params) {
+ for (let param of criteria) {
+ const val = params.get(param.key);
+ if (
+ val === null ||
+ (param.value && param.value !== val) ||
+ (param.prefix && !val.startsWith(param.prefix))
+ ) {
+ return false;
+ }
+ }
+ return true;
+}
+
+/**
+ * classifySite
+ * Classifies a given URL into a category based on classification data from RemoteSettings.
+ * The data from remote settings can match a category by one of the following:
+ * - match the exact URL
+ * - match the hostname or second level domain (sld)
+ * - match query parameter(s), and optionally their values or prefixes
+ * - match both (hostname or sld) and query parameter(s)
+ *
+ * The data looks like:
+ * [{
+ * "type": "hostname-and-params-match",
+ * "criteria": [
+ * {
+ * "url": "https://matchurl.com",
+ * "hostname": "matchhostname.com",
+ * "sld": "secondleveldomain",
+ * "params": [
+ * {
+ * "key": "matchparam",
+ * "value": "matchvalue",
+ * "prefix": "matchpPrefix",
+ * },
+ * ],
+ * },
+ * ],
+ * "weight": 300,
+ * },...]
+ */
+async function classifySite(url, RS = RemoteSettings) {
+ let category = "other";
+ let parsedURL;
+
+ // Try to parse the url.
+ for (let _url of [url, `https://${url}`]) {
+ try {
+ parsedURL = new URL(_url);
+ break;
+ } catch (e) {}
+ }
+
+ if (parsedURL) {
+ // If we parsed successfully, find a match.
+ const hostname = parsedURL.hostname.replace(/^www\./i, "");
+ const params = parsedURL.searchParams;
+ // NOTE: there will be an initial/default local copy of the data in m-c.
+ // Therefore, this should never return an empty list [].
+ const siteTypes = await RS("sites-classification").get();
+ const sortedSiteTypes = siteTypes.sort(
+ (x, y) => (y.weight || 0) - (x.weight || 0)
+ );
+ for (let type of sortedSiteTypes) {
+ for (let criteria of type.criteria) {
+ if (criteria.url && criteria.url !== url) {
+ continue;
+ }
+ if (criteria.hostname && criteria.hostname !== hostname) {
+ continue;
+ }
+ if (criteria.sld && criteria.sld !== hostname.split(".")[0]) {
+ continue;
+ }
+ if (criteria.params && !_hasParams(criteria.params, params)) {
+ continue;
+ }
+ return type.type;
+ }
+ }
+ }
+ return category;
+}
+
+const EXPORTED_SYMBOLS = ["classifySite"];
diff --git a/browser/components/newtab/lib/SnippetsTestMessageProvider.jsm b/browser/components/newtab/lib/SnippetsTestMessageProvider.jsm
new file mode 100644
index 0000000000..25d5f703b4
--- /dev/null
+++ b/browser/components/newtab/lib/SnippetsTestMessageProvider.jsm
@@ -0,0 +1,721 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
+const TEST_ICON = "chrome://branding/content/icon64.png";
+const TEST_ICON_16 = "chrome://branding/content/icon16.png";
+const TEST_ICON_BW =
+ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAQAAAC1+jfqAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAAmJLR0QA/4ePzL8AAAAHdElNRQfjBQ8QDifrKGc/AAABf0lEQVQoz4WRO08UUQCFvztzd1AgG9jRgGwkhEoMIYGSygYt+A00tpZGY0jYxAJKEwkNjX9AK2xACx4dhFiQQCiMMRr2kYXdnQcz7L0z91qAMVac6hTfSU7OgVsk/prtyfSNfRb7ge2cd7dmVucP/wM2lwqVqoyICahRx9Nz71+8AnAAvlTct+dSYDBYcgJ+Fj68XFu/AfamnIoWFoHFYrAUuYMSn55/fAIOxIs1t4MhQpNxRYsUD0ld7r8DCfZph4QecrqkhCREgMLSeISQkAy0UBgE0CYgIkeRA9HdsCQhpEGCxichpItHigEcPH4XJLRbTf8STY0iiiuu60Ifxexx04F0N+aCgJCAhPQmD/cp/RC5A79WvUyhUHSIidAIoESv9VfAhW9n8+XqTCoyMsz1cviMMrGz9BrjAuboYHZajyXCInEocI8yvccbC+0muABanR4/tONjQz3DzgNKtj9sfv66XD9B/3tT9g/akb7h0bJwzxqqmlRHLr4rLPwBlYWoYj77l2AAAAAldEVYdGRhdGU6Y3JlYXRlADIwMTktMDUtMTVUMTY6MTQ6MzkrMDA6MDD5/4XBAAAAJXRFWHRkYXRlOm1vZGlmeQAyMDE5LTA1LTE1VDE2OjE0OjM5KzAwOjAwiKI9fQAAAABJRU5ErkJggg==";
+
+const MESSAGES = () => [
+ {
+ template: "simple_snippet",
+ template_version: "1.1.2",
+ content: {
+ text: "This is for <link0>preferences</link0> and <link1>about</link1>",
+ icon:
+ "https://snippets.cdn.mozilla.net/media/icons/1a8bb10e-8166-4e14-9e41-c1f85a41bcd2.png",
+ button_label: "Button Label",
+ section_title_icon:
+ "https://snippets.cdn.mozilla.net/media/icons/5878847e-a1fb-4204-aad9-09f6cf7f99ee.png",
+ section_title_text: "Messages from Firefox",
+ section_title_url:
+ "https://support.mozilla.org/kb/snippets-firefox-faq?utm_source=desktop-snippet&utm_medium=snippet&utm_campaign=&utm_term=&utm_content=",
+ tall: false,
+ block_button_text: "Remove this",
+ do_not_autoblock: true,
+ links: {
+ link0: {
+ action: "OPEN_PREFERENCES_PAGE",
+ entrypoint_value: "snippet",
+ args: "sync",
+ },
+ link1: {
+ action: "OPEN_ABOUT_PAGE",
+ args: "about",
+ entrypoint_name: "entryPoint",
+ entrypoint_value: "snippet",
+ },
+ },
+ button_action: "OPEN_PREFERENCES_PAGE",
+ button_entrypoint_value: "snippet",
+ },
+ id: "preview-13516_button_preferences",
+ },
+ {
+ template: "simple_snippet",
+ template_version: "1.1.2",
+ content: {
+ text: "This is for <link0>preferences</link0> and <link1>about</link1>",
+ icon:
+ "https://snippets.cdn.mozilla.net/media/icons/1a8bb10e-8166-4e14-9e41-c1f85a41bcd2.png",
+ button_label: "Button Label",
+ section_title_icon:
+ "https://snippets.cdn.mozilla.net/media/icons/5878847e-a1fb-4204-aad9-09f6cf7f99ee.png",
+ section_title_text: "Messages from Firefox",
+ section_title_url:
+ "https://support.mozilla.org/kb/snippets-firefox-faq?utm_source=desktop-snippet&utm_medium=snippet&utm_campaign=&utm_term=&utm_content=",
+ tall: false,
+ block_button_text: "Remove this",
+ do_not_autoblock: true,
+ links: {
+ link0: {
+ action: "OPEN_PREFERENCES_PAGE",
+ entrypoint_value: "snippet",
+ },
+ link1: {
+ action: "OPEN_ABOUT_PAGE",
+ args: "about",
+ entrypoint_name: "entryPoint",
+ entrypoint_value: "snippet",
+ },
+ },
+ button_action: "OPEN_ABOUT_PAGE",
+ button_action_args: "logins",
+ button_entrypoint_name: "entryPoint",
+ button_entrypoint_value: "snippet",
+ },
+ id: "preview-13517_button_about",
+ },
+ {
+ id: "SIMPLE_TEST_1",
+ template: "simple_snippet",
+ campaign: "test_campaign_blocking",
+ content: {
+ icon: TEST_ICON,
+ icon_dark_theme: TEST_ICON_BW,
+ title: "Firefox Account!",
+ title_icon: TEST_ICON_16,
+ title_icon_dark_theme: TEST_ICON_BW,
+ text:
+ "<syncLink>Sync it, link it, take it with you</syncLink>. All this and more with a Firefox Account.",
+ links: {
+ syncLink: { url: "https://www.mozilla.org/en-US/firefox/accounts" },
+ },
+ block_button_text: "Block",
+ },
+ },
+ {
+ id: "SIMPLE_TEST_1_NO_DARK_THEME",
+ template: "simple_snippet",
+ campaign: "test_campaign_blocking",
+ content: {
+ icon: TEST_ICON,
+ icon_dark_theme: "",
+ title: "Firefox Account!",
+ title_icon: TEST_ICON_16,
+ title_icon_dark_theme: "",
+ text:
+ "<syncLink>Sync it, link it, take it with you</syncLink>. All this and more with a Firefox Account.",
+ links: {
+ syncLink: { url: "https://www.mozilla.org/en-US/firefox/accounts" },
+ },
+ block_button_text: "Block",
+ },
+ },
+ {
+ id: "SIMPLE_TEST_1_SAME_CAMPAIGN",
+ template: "simple_snippet",
+ campaign: "test_campaign_blocking",
+ content: {
+ icon: TEST_ICON,
+ icon_dark_theme: TEST_ICON_BW,
+ text:
+ "<syncLink>Sync it, link it, take it with you</syncLink>. All this and more with a Firefox Account.",
+ links: {
+ syncLink: { url: "https://www.mozilla.org/en-US/firefox/accounts" },
+ },
+ block_button_text: "Block",
+ },
+ },
+ {
+ id: "SIMPLE_TEST_TALL",
+ template: "simple_snippet",
+ content: {
+ icon: TEST_ICON,
+ icon_dark_theme: TEST_ICON_BW,
+ text:
+ "<syncLink>Sync it, link it, take it with you</syncLink>. All this and more with a Firefox Account.",
+ links: {
+ syncLink: { url: "https://www.mozilla.org/en-US/firefox/accounts" },
+ },
+ button_label: "Get one now!",
+ button_url: "https://www.mozilla.org/en-US/firefox/accounts",
+ block_button_text: "Block",
+ tall: true,
+ },
+ },
+ {
+ id: "SIMPLE_TEST_BUTTON_URL_1",
+ template: "simple_snippet",
+ content: {
+ icon: TEST_ICON,
+ icon_dark_theme: TEST_ICON_BW,
+ button_label: "Get one now!",
+ button_url: "https://www.mozilla.org/en-US/firefox/accounts",
+ text:
+ "Sync it, link it, take it with you. All this and more with a Firefox Account.",
+ block_button_text: "Block",
+ },
+ },
+ {
+ id: "SIMPLE_TEST_BUTTON_ACTION_1",
+ template: "simple_snippet",
+ content: {
+ icon: TEST_ICON,
+ icon_dark_theme: TEST_ICON_BW,
+ button_label: "Open about:config",
+ button_action: "OPEN_ABOUT_PAGE",
+ button_action_args: "config",
+ text: "Testing the OPEN_ABOUT_PAGE action",
+ block_button_text: "Block",
+ },
+ },
+ {
+ id: "SIMPLE_WITH_TITLE_TEST_1",
+ template: "simple_snippet",
+ content: {
+ icon: TEST_ICON,
+ icon_dark_theme: TEST_ICON_BW,
+ title: "Ready to sync?",
+ text: "Get connected with a <syncLink>Firefox account</syncLink>.",
+ links: {
+ syncLink: { url: "https://www.mozilla.org/en-US/firefox/accounts" },
+ },
+ block_button_text: "Block",
+ },
+ },
+ {
+ id: "NEWSLETTER_TEST_DEFAULTS",
+ template: "newsletter_snippet",
+ content: {
+ scene1_icon: TEST_ICON,
+ scene1_icon_dark_theme: TEST_ICON_BW,
+ scene1_title: "Be a part of a movement.",
+ scene1_title_icon: TEST_ICON_16,
+ scene1_title_icon_dark_theme: TEST_ICON_BW,
+ scene1_text:
+ "Internet shutdowns, hackers, harassment &ndash; the health of the internet is on the line. Sign up and Mozilla will keep you updated on how you can help.",
+ scene1_button_label: "Continue",
+ scene1_button_color: "#712b00",
+ scene1_button_background_color: "#ff9400",
+ scene2_title: "Let's do this!",
+ locale: "en-CA",
+ scene2_dismiss_button_text: "Dismiss",
+ scene2_text:
+ "Sign up for the Mozilla newsletter and we will keep you updated on how you can help.",
+ scene2_privacy_html:
+ "I'm okay with Mozilla handling my info as explained in this <privacyLink>Privacy Notice</privacyLink>.",
+ scene2_newsletter: "mozilla-foundation",
+ success_text: "Check your inbox for the confirmation!",
+ error_text: "Error!",
+ retry_button_label: "Try again?",
+ links: {
+ privacyLink: {
+ url:
+ "https://www.mozilla.org/privacy/websites/?sample_rate=0.001&snippet_name=7894",
+ },
+ },
+ },
+ },
+ {
+ id: "NEWSLETTER_TEST_1",
+ template: "newsletter_snippet",
+ content: {
+ scene1_icon: TEST_ICON,
+ scene1_icon_dark_theme: TEST_ICON_BW,
+ scene1_title: "Be a part of a movement.",
+ scene1_title_icon: "",
+ scene1_text:
+ "Internet shutdowns, hackers, harassment &ndash; the health of the internet is on the line. Sign up and Mozilla will keep you updated on how you can help.",
+ scene1_button_label: "Continue",
+ scene1_button_color: "#712b00",
+ scene1_button_background_color: "#ff9400",
+ scene2_title: "Let's do this!",
+ locale: "en-CA",
+ scene2_dismiss_button_text: "Dismiss",
+ scene2_text:
+ "Sign up for the Mozilla newsletter and we will keep you updated on how you can help.",
+ scene2_privacy_html:
+ "I'm okay with Mozilla handling my info as explained in this <privacyLink>Privacy Notice</privacyLink>.",
+ scene2_button_label: "Sign Me up",
+ scene2_email_placeholder_text: "Your email here",
+ scene2_newsletter: "mozilla-foundation",
+ success_text: "Check your inbox for the confirmation!",
+ error_text: "Error!",
+ links: {
+ privacyLink: {
+ url:
+ "https://www.mozilla.org/privacy/websites/?sample_rate=0.001&snippet_name=7894",
+ },
+ },
+ },
+ },
+ {
+ id: "NEWSLETTER_TEST_SCENE1_SECTION_TITLE_ICON",
+ template: "newsletter_snippet",
+ content: {
+ scene1_icon: TEST_ICON,
+ scene1_icon_dark_theme: TEST_ICON_BW,
+ scene1_title: "Be a part of a movement.",
+ scene1_title_icon: "",
+ scene1_text:
+ "Internet shutdowns, hackers, harassment &ndash; the health of the internet is on the line. Sign up and Mozilla will keep you updated on how you can help.",
+ scene1_button_label: "Continue",
+ scene1_button_color: "#712b00",
+ scene1_button_background_color: "#ff9400",
+ scene1_section_title_icon:
+ "chrome://activity-stream/content/data/content/assets/glyph-pocket-16.svg",
+ scene1_section_title_text:
+ "All the Firefox news that's fit to Firefox print!",
+ scene2_title: "Let's do this!",
+ locale: "en-CA",
+ scene2_dismiss_button_text: "Dismiss",
+ scene2_text:
+ "Sign up for the Mozilla newsletter and we will keep you updated on how you can help.",
+ scene2_privacy_html:
+ "I'm okay with Mozilla handling my info as explained in this <privacyLink>Privacy Notice</privacyLink>.",
+ scene2_button_label: "Sign Me up",
+ scene2_email_placeholder_text: "Your email here",
+ scene2_newsletter: "mozilla-foundation",
+ success_text: "Check your inbox for the confirmation!",
+ error_text: "Error!",
+ links: {
+ privacyLink: {
+ url:
+ "https://www.mozilla.org/privacy/websites/?sample_rate=0.001&snippet_name=7894",
+ },
+ },
+ },
+ },
+ {
+ id: "FXA_SNIPPET_TEST_1",
+ template: "fxa_signup_snippet",
+ content: {
+ scene1_icon: TEST_ICON,
+ scene1_icon_dark_theme: TEST_ICON_BW,
+ scene1_button_label: "Get connected with sync!",
+ scene1_button_color: "#712b00",
+ scene1_button_background_color: "#ff9400",
+
+ scene1_text:
+ "Connect to Firefox by securely syncing passwords, bookmarks, and open tabs.",
+ scene1_title: "Browser better.",
+ scene1_title_icon: TEST_ICON_16,
+ scene1_title_icon_dark_theme: TEST_ICON_BW,
+
+ scene2_text:
+ "Connect to your Firefox account to securely sync passwords, bookmarks, and open tabs.",
+ scene2_title: "Title 123",
+ scene2_email_placeholder_text: "Your email",
+ scene2_button_label: "Continue",
+ scene2_dismiss_button_text: "Dismiss",
+ },
+ },
+ {
+ id: "FXA_SNIPPET_TEST_TITLE_ICON",
+ template: "fxa_signup_snippet",
+ content: {
+ scene1_icon: TEST_ICON,
+ scene1_icon_dark_theme: TEST_ICON_BW,
+ scene1_button_label: "Get connected with sync!",
+ scene1_button_color: "#712b00",
+ scene1_button_background_color: "#ff9400",
+
+ scene1_text:
+ "Connect to Firefox by securely syncing passwords, bookmarks, and open tabs.",
+ scene1_title: "Browser better.",
+ scene1_title_icon: TEST_ICON_16,
+ scene1_title_icon_dark_theme: TEST_ICON_BW,
+
+ scene1_section_title_icon:
+ "chrome://activity-stream/content/data/content/assets/glyph-pocket-16.svg",
+ scene1_section_title_text: "Firefox Accounts: Receivable benefits",
+
+ scene2_text:
+ "Connect to your Firefox account to securely sync passwords, bookmarks, and open tabs.",
+ scene2_title: "Title 123",
+ scene2_email_placeholder_text: "Your email",
+ scene2_button_label: "Continue",
+ scene2_dismiss_button_text: "Dismiss",
+ },
+ },
+ {
+ id: "SNIPPETS_SEND_TO_DEVICE_TEST",
+ template: "send_to_device_snippet",
+ content: {
+ include_sms: true,
+ locale: "en-CA",
+ country: "us",
+ message_id_sms: "ff-mobilesn-download",
+ message_id_email: "download-firefox-mobile",
+
+ scene1_button_background_color: "#6200a4",
+ scene1_button_color: "#FFFFFF",
+ scene1_button_label: "Install now",
+ scene1_icon: TEST_ICON,
+ scene1_icon_dark_theme: TEST_ICON_BW,
+ scene1_text: "Browse without compromise with Firefox Mobile.",
+ scene1_title: "Full-featured. Customizable. Lightning fast",
+ scene1_title_icon: TEST_ICON_16,
+ scene1_title_icon_dark_theme: TEST_ICON_BW,
+
+ scene2_button_label: "Send",
+ scene2_disclaimer_html:
+ "The intended recipient of the email must have consented. <privacyLink>Learn more</privacyLink>.",
+ scene2_dismiss_button_text: "Dismiss",
+ scene2_icon: TEST_ICON,
+ scene2_icon_dark_theme: TEST_ICON_BW,
+ scene2_input_placeholder: "Your email address or phone number",
+ scene2_text:
+ "Send Firefox to your phone and take a powerful independent browser with you.",
+ scene2_title: "Let's do this!",
+
+ error_text: "Oops, there was a problem.",
+ success_title: "Your download link was sent.",
+ success_text: "Check your device for the email message!",
+ links: {
+ privacyLink: {
+ url:
+ "https://www.mozilla.org/privacy/websites/?sample_rate=0.001&snippet_name=7894",
+ },
+ },
+ },
+ },
+ {
+ id: "SNIPPETS_SCENE2_SEND_TO_DEVICE_TEST",
+ template: "send_to_device_scene2_snippet",
+ content: {
+ include_sms: true,
+ locale: "en-CA",
+ country: "us",
+ message_id_sms: "ff-mobilesn-download",
+ message_id_email: "download-firefox-mobile",
+ scene2_icon: TEST_ICON,
+ section_title_icon:
+ "https://snippets.cdn.mozilla.net/media/icons/094b0707-ab65-4b2e-99a1-a84122b6ab26.png",
+ section_title_text: "Messages from Firefox",
+ section_title_url: "https://support.mozilla.org/kb",
+ scene2_button_label: "Send",
+ scene2_disclaimer_html:
+ "The intended recipient of the email must have consented. <privacyLink>Learn more</privacyLink>.",
+ scene2_input_placeholder: "Your email address or phone number",
+ scene2_text:
+ "Send Firefox to your phone and take a powerful independent browser with you.",
+ error_text: "Oops, there was a problem.",
+ success_title: "Your download link was sent.",
+ success_text: "Check your device for the email message!",
+ links: {
+ privacyLink: {
+ url:
+ "https://www.mozilla.org/privacy/websites/?sample_rate=0.001&snippet_name=7894",
+ },
+ },
+ },
+ },
+ {
+ id: "SNIPPETS_SEND_TO_DEVICE_TEST_NO_DARK_THEME",
+ template: "send_to_device_snippet",
+ content: {
+ include_sms: true,
+ locale: "en-CA",
+ country: "us",
+ message_id_sms: "ff-mobilesn-download",
+ message_id_email: "download-firefox-mobile",
+
+ scene1_button_background_color: "#6200a4",
+ scene1_button_color: "#FFFFFF",
+ scene1_button_label: "Install now",
+ scene1_icon: TEST_ICON,
+ scene1_icon_dark_theme: "",
+ scene1_text: "Browse without compromise with Firefox Mobile.",
+ scene1_title: "Full-featured. Customizable. Lightning fast",
+ scene1_title_icon: TEST_ICON_16,
+ scene1_title_icon_dark_theme: "",
+
+ scene2_button_label: "Send",
+ scene2_disclaimer_html:
+ "The intended recipient of the email must have consented. <privacyLink>Learn more</privacyLink>.",
+ scene2_dismiss_button_text: "Dismiss",
+ scene2_icon: TEST_ICON,
+ scene2_icon_dark_theme: "",
+ scene2_input_placeholder: "Your email address or phone number",
+ scene2_text:
+ "Send Firefox to your phone and take a powerful independent browser with you.",
+ scene2_title: "Let's do this!",
+
+ error_text: "Oops, there was a problem.",
+ success_title: "Your download link was sent.",
+ success_text: "Check your device for the email message!",
+ links: {
+ privacyLink: {
+ url:
+ "https://www.mozilla.org/privacy/websites/?sample_rate=0.001&snippet_name=7894",
+ },
+ },
+ },
+ },
+ {
+ id: "SNIPPETS_SEND_TO_DEVICE_TEST_SECTION_TITLE_ICON",
+ template: "send_to_device_snippet",
+ content: {
+ include_sms: true,
+ locale: "en-CA",
+ country: "us",
+ message_id_sms: "ff-mobilesn-download",
+ message_id_email: "download-firefox-mobile",
+
+ scene1_button_background_color: "#6200a4",
+ scene1_button_color: "#FFFFFF",
+ scene1_button_label: "Install now",
+ scene1_icon: TEST_ICON,
+ scene1_icon_dark_theme: TEST_ICON_BW,
+ scene1_text: "Browse without compromise with Firefox Mobile.",
+ scene1_title: "Full-featured. Customizable. Lightning fast",
+ scene1_title_icon: TEST_ICON_16,
+ scene1_title_icon_dark_theme: TEST_ICON_BW,
+ scene1_section_title_icon:
+ "chrome://activity-stream/content/data/content/assets/glyph-pocket-16.svg",
+ scene1_section_title_text: "Send Firefox to your mobile device!",
+
+ scene2_button_label: "Send",
+ scene2_disclaimer_html:
+ "The intended recipient of the email must have consented. <privacyLink>Learn more</privacyLink>.",
+ scene2_dismiss_button_text: "Dismiss",
+ scene2_icon: TEST_ICON,
+ scene2_icon_dark_theme: TEST_ICON_BW,
+ scene2_input_placeholder: "Your email address or phone number",
+ scene2_text:
+ "Send Firefox to your phone and take a powerful independent browser with you.",
+ scene2_title: "Let's do this!",
+
+ error_text: "Oops, there was a problem.",
+ success_title: "Your download link was sent.",
+ success_text: "Check your device for the email message!",
+ links: {
+ privacyLink: {
+ url:
+ "https://www.mozilla.org/privacy/websites/?sample_rate=0.001&snippet_name=7894",
+ },
+ },
+ },
+ },
+ {
+ id: "EOY_TEST_1",
+ template: "eoy_snippet",
+ content: {
+ highlight_color: "#f05",
+ background_color: "#ddd",
+ text_color: "yellow",
+ selected_button: "donation_amount_first",
+ icon: TEST_ICON,
+ icon_dark_theme: TEST_ICON_BW,
+ button_label: "Donate",
+ monthly_checkbox_label_text: "Make my donation monthly",
+ currency_code: "usd",
+ donation_amount_first: 50,
+ donation_amount_second: 25,
+ donation_amount_third: 10,
+ donation_amount_fourth: 5,
+ donation_form_url:
+ "https://donate.mozilla.org/pl/?utm_source=desktop-snippet&amp;utm_medium=snippet&amp;utm_campaign=donate&amp;utm_term=7556",
+ text:
+ "Big corporations want to restrict how we access the web. Fake news is making it harder for us to find the truth. Online bullies are silencing inspired voices. The <em>not-for-profit Mozilla Foundation</em> fights for a healthy internet with programs like our Tech Policy Fellowships and Internet Health Report; <b>will you donate today</b>?",
+ },
+ },
+ {
+ id: "EOY_BOLD_TEST_1",
+ template: "eoy_snippet",
+ content: {
+ icon: TEST_ICON,
+ icon_dark_theme: TEST_ICON_BW,
+ selected_button: "donation_amount_second",
+ button_label: "Donate",
+ monthly_checkbox_label_text: "Make my donation monthly",
+ currency_code: "usd",
+ donation_amount_first: 50,
+ donation_amount_second: 25,
+ donation_amount_third: 10,
+ donation_amount_fourth: 5,
+ donation_form_url: "https://donate.mozilla.org",
+ text:
+ "Big corporations want to restrict how we access the web. Fake news is making it harder for us to find the truth. Online bullies are silencing inspired voices. The <em>not-for-profit Mozilla Foundation</em> fights for a healthy internet with programs like our Tech Policy Fellowships and Internet Health Report; <b>will you donate today</b>?",
+ test: "bold",
+ },
+ },
+ {
+ id: "EOY_TAKEOVER_TEST_1",
+ template: "eoy_snippet",
+ content: {
+ icon: TEST_ICON,
+ icon_dark_theme: TEST_ICON_BW,
+ button_label: "Donate",
+ monthly_checkbox_label_text: "Make my donation monthly",
+ currency_code: "usd",
+ donation_amount_first: 50,
+ donation_amount_second: 25,
+ donation_amount_third: 10,
+ donation_amount_fourth: 5,
+ donation_form_url: "https://donate.mozilla.org",
+ text:
+ "Big corporations want to restrict how we access the web. Fake news is making it harder for us to find the truth. Online bullies are silencing inspired voices. The <em>not-for-profit Mozilla Foundation</em> fights for a healthy internet with programs like our Tech Policy Fellowships and Internet Health Report; <b>will you donate today</b>?",
+ test: "takeover",
+ },
+ },
+ {
+ id: "SIMPLE_TEST_WITH_SECTION_HEADING",
+ template: "simple_snippet",
+ content: {
+ button_label: "Get one now!",
+ button_url: "https://www.mozilla.org/en-US/firefox/accounts",
+ icon: TEST_ICON,
+ icon_dark_theme: TEST_ICON_BW,
+ title: "Firefox Account!",
+ text:
+ "<syncLink>Sync it, link it, take it with you</syncLink>. All this and more with a Firefox Account.",
+ links: {
+ syncLink: { url: "https://www.mozilla.org/en-US/firefox/accounts" },
+ },
+ block_button_text: "Block",
+ section_title_icon:
+ "chrome://activity-stream/content/data/content/assets/glyph-pocket-16.svg",
+ section_title_text: "Messages from Mozilla",
+ },
+ },
+ {
+ id: "SIMPLE_TEST_WITH_SECTION_HEADING_AND_LINK",
+ template: "simple_snippet",
+ content: {
+ icon: TEST_ICON,
+ icon_dark_theme: TEST_ICON_BW,
+ title: "Firefox Account!",
+ text:
+ "Sync it, link it, take it with you. All this and more with a Firefox Account.",
+ block_button_text: "Block",
+ section_title_icon:
+ "chrome://activity-stream/content/data/content/assets/glyph-pocket-16.svg",
+ section_title_text: "Messages from Mozilla (click for info)",
+ section_title_url: "https://www.mozilla.org/about",
+ },
+ },
+ {
+ id: "SIMPLE_BELOW_SEARCH_TEST_1",
+ template: "simple_below_search_snippet",
+ content: {
+ icon: TEST_ICON,
+ icon_dark_theme: TEST_ICON_BW,
+ text:
+ "Securely store passwords, bookmarks, and more with a Firefox Account. <syncLink>Sign up</syncLink>",
+ links: {
+ syncLink: { url: "https://www.mozilla.org/en-US/firefox/accounts" },
+ },
+ block_button_text: "Block",
+ },
+ },
+ {
+ id: "SIMPLE_BELOW_SEARCH_TEST_2",
+ template: "simple_below_search_snippet",
+ content: {
+ icon: TEST_ICON,
+ icon_dark_theme: TEST_ICON_BW,
+ text:
+ "<syncLink>Connect your Firefox Account to Sync</syncLink> your protected passwords, open tabs and bookmarks, and they'll always be available to you - on all of your devices.",
+ links: {
+ syncLink: { url: "https://www.mozilla.org/en-US/firefox/accounts" },
+ },
+ block_button_text: "Block",
+ },
+ },
+ {
+ id: "SIMPLE_BELOW_SEARCH_TEST_TITLE",
+ template: "simple_below_search_snippet",
+ content: {
+ icon: TEST_ICON,
+ icon_dark_theme: TEST_ICON_BW,
+ title: "See if you've been part of an online data breach.",
+ text:
+ "Securely store passwords, bookmarks, and more with a Firefox Account. <syncLink>Sign up</syncLink>",
+ links: {
+ syncLink: { url: "https://www.mozilla.org/en-US/firefox/accounts" },
+ },
+ block_button_text: "Block",
+ },
+ },
+ {
+ id: "SPECIAL_SNIPPET_BUTTON_1",
+ template: "simple_below_search_snippet",
+ content: {
+ icon: TEST_ICON,
+ icon_dark_theme: TEST_ICON_BW,
+ button_label: "Find Out Now",
+ button_url: "https://www.mozilla.org/en-US/firefox/accounts",
+ title: "See if you've been part of an online data breach.",
+ text: "Firefox Monitor tells you what hackers already know about you.",
+ block_button_text: "Block",
+ },
+ },
+ {
+ id: "SPECIAL_SNIPPET_LONG_CONTENT",
+ template: "simple_below_search_snippet",
+ content: {
+ icon: TEST_ICON,
+ icon_dark_theme: TEST_ICON_BW,
+ button_label: "Find Out Now",
+ button_url: "https://www.mozilla.org/en-US/firefox/accounts",
+ title: "See if you've been part of an online data breach.",
+ text:
+ "Firefox Monitor tells you what hackers already know about you. Here's some extra text to make the content really long.",
+ block_button_text: "Block",
+ },
+ },
+ {
+ id: "SPECIAL_SNIPPET_NO_TITLE",
+ template: "simple_below_search_snippet",
+ content: {
+ icon: TEST_ICON,
+ icon_dark_theme: TEST_ICON_BW,
+ button_label: "Find Out Now",
+ button_url: "https://www.mozilla.org/en-US/firefox/accounts",
+ text: "Firefox Monitor tells you what hackers already know about you.",
+ block_button_text: "Block",
+ },
+ },
+ {
+ id: "SPECIAL_SNIPPET_MONITOR",
+ template: "simple_below_search_snippet",
+ content: {
+ icon: TEST_ICON,
+ title: "See if you've been part of an online data breach.",
+ text: "Firefox Monitor tells you what hackers already know about you.",
+ button_label: "Get monitor",
+ button_action: "ENABLE_FIREFOX_MONITOR",
+ button_action_args: {
+ url:
+ "https://monitor.firefox.com/oauth/init?utm_source=snippets&utm_campaign=monitor-snippet-test&form_type=email&entrypoint=newtab",
+ flowRequestParams: {
+ entrypoint: "snippets",
+ utm_term: "monitor",
+ form_type: "email",
+ },
+ },
+ block_button_text: "Block",
+ },
+ },
+];
+
+const SnippetsTestMessageProvider = {
+ getMessages() {
+ return Promise.resolve(
+ MESSAGES()
+ // Ensures we never actually show test except when triggered by debug tools
+ .map(message => ({
+ ...message,
+ targeting: `providerCohorts.snippets_local_testing == "SHOW_TEST"`,
+ }))
+ );
+ },
+};
+this.SnippetsTestMessageProvider = SnippetsTestMessageProvider;
+
+const EXPORTED_SYMBOLS = ["SnippetsTestMessageProvider"];
diff --git a/browser/components/newtab/lib/Store.jsm b/browser/components/newtab/lib/Store.jsm
new file mode 100644
index 0000000000..261cf22803
--- /dev/null
+++ b/browser/components/newtab/lib/Store.jsm
@@ -0,0 +1,190 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
+const { ActivityStreamMessageChannel } = ChromeUtils.import(
+ "resource://activity-stream/lib/ActivityStreamMessageChannel.jsm"
+);
+const { ActivityStreamStorage } = ChromeUtils.import(
+ "resource://activity-stream/lib/ActivityStreamStorage.jsm"
+);
+const { Prefs } = ChromeUtils.import(
+ "resource://activity-stream/lib/ActivityStreamPrefs.jsm"
+);
+const { reducers } = ChromeUtils.import(
+ "resource://activity-stream/common/Reducers.jsm"
+);
+const { redux } = ChromeUtils.import(
+ "resource://activity-stream/vendor/Redux.jsm"
+);
+
+/**
+ * Store - This has a similar structure to a redux store, but includes some extra
+ * functionality to allow for routing of actions between the Main processes
+ * and child processes via a ActivityStreamMessageChannel.
+ * It also accepts an array of "Feeds" on inititalization, which
+ * can listen for any action that is dispatched through the store.
+ */
+this.Store = class Store {
+ /**
+ * constructor - The redux store and message manager are created here,
+ * but no listeners are added until "init" is called.
+ */
+ constructor() {
+ this._middleware = this._middleware.bind(this);
+ // Bind each redux method so we can call it directly from the Store. E.g.,
+ // store.dispatch() will call store._store.dispatch();
+ for (const method of ["dispatch", "getState", "subscribe"]) {
+ this[method] = (...args) => this._store[method](...args);
+ }
+ this.feeds = new Map();
+ this._prefs = new Prefs();
+ this._messageChannel = new ActivityStreamMessageChannel({
+ dispatch: this.dispatch,
+ });
+ this._store = redux.createStore(
+ redux.combineReducers(reducers),
+ redux.applyMiddleware(this._middleware, this._messageChannel.middleware)
+ );
+ this.storage = null;
+ }
+
+ /**
+ * _middleware - This is redux middleware consumed by redux.createStore.
+ * it calls each feed's .onAction method, if one
+ * is defined.
+ */
+ _middleware() {
+ return next => action => {
+ next(action);
+ for (const store of this.feeds.values()) {
+ if (store.onAction) {
+ store.onAction(action);
+ }
+ }
+ };
+ }
+
+ /**
+ * initFeed - Initializes a feed by calling its constructor function
+ *
+ * @param {string} feedName The name of a feed, as defined in the object
+ * passed to Store.init
+ * @param {Action} initAction An optional action to initialize the feed
+ */
+ initFeed(feedName, initAction) {
+ const feed = this._feedFactories.get(feedName)();
+ feed.store = this;
+ this.feeds.set(feedName, feed);
+ if (initAction && feed.onAction) {
+ feed.onAction(initAction);
+ }
+ }
+
+ /**
+ * uninitFeed - Removes a feed and calls its uninit function if defined
+ *
+ * @param {string} feedName The name of a feed, as defined in the object
+ * passed to Store.init
+ * @param {Action} uninitAction An optional action to uninitialize the feed
+ */
+ uninitFeed(feedName, uninitAction) {
+ const feed = this.feeds.get(feedName);
+ if (!feed) {
+ return;
+ }
+ if (uninitAction && feed.onAction) {
+ feed.onAction(uninitAction);
+ }
+ this.feeds.delete(feedName);
+ }
+
+ /**
+ * onPrefChanged - Listener for handling feed changes.
+ */
+ onPrefChanged(name, value) {
+ if (this._feedFactories.has(name)) {
+ if (value) {
+ this.initFeed(name, this._initAction);
+ } else {
+ this.uninitFeed(name, this._uninitAction);
+ }
+ }
+ }
+
+ /**
+ * init - Initializes the ActivityStreamMessageChannel channel, and adds feeds.
+ *
+ * Note that it intentionally initializes the TelemetryFeed first so that the
+ * addon is able to report the init errors from other feeds.
+ *
+ * @param {Map} feedFactories A Map of feeds with the name of the pref for
+ * the feed as the key and a function that
+ * constructs an instance of the feed.
+ * @param {Action} initAction An optional action that will be dispatched
+ * to feeds when they're created.
+ * @param {Action} uninitAction An optional action for when feeds uninit.
+ */
+ async init(feedFactories, initAction, uninitAction) {
+ this._feedFactories = feedFactories;
+ this._initAction = initAction;
+ this._uninitAction = uninitAction;
+
+ const telemetryKey = "feeds.telemetry";
+ if (feedFactories.has(telemetryKey) && this._prefs.get(telemetryKey)) {
+ this.initFeed(telemetryKey);
+ }
+
+ await this._initIndexedDB(telemetryKey);
+
+ for (const pref of feedFactories.keys()) {
+ if (pref !== telemetryKey && this._prefs.get(pref)) {
+ this.initFeed(pref);
+ }
+ }
+
+ this._prefs.observeBranch(this);
+ this._messageChannel.createChannel();
+
+ // Dispatch an initial action after all enabled feeds are ready
+ if (initAction) {
+ this.dispatch(initAction);
+ }
+
+ // Dispatch NEW_TAB_INIT/NEW_TAB_LOAD events after INIT event.
+ this._messageChannel.simulateMessagesForExistingTabs();
+ }
+
+ async _initIndexedDB(telemetryKey) {
+ this.dbStorage = new ActivityStreamStorage({
+ storeNames: ["sectionPrefs", "snippets"],
+ });
+ // Accessing the db causes the object stores to be created / migrated.
+ // This needs to happen before other instances try to access the db, which
+ // would update only a subset of the stores to the latest version.
+ try {
+ await this.dbStorage.db; // eslint-disable-line no-unused-expressions
+ } catch (e) {
+ this.dbStorage.telemetry = null;
+ }
+ }
+
+ /**
+ * uninit - Uninitalizes each feed, clears them, and destroys the message
+ * manager channel.
+ *
+ * @return {type} description
+ */
+ uninit() {
+ if (this._uninitAction) {
+ this.dispatch(this._uninitAction);
+ }
+ this._prefs.ignoreBranch(this);
+ this.feeds.clear();
+ this._feedFactories = null;
+ this._messageChannel.destroyChannel();
+ }
+};
+
+const EXPORTED_SYMBOLS = ["Store"];
diff --git a/browser/components/newtab/lib/SystemTickFeed.jsm b/browser/components/newtab/lib/SystemTickFeed.jsm
new file mode 100644
index 0000000000..0dfa46d4e9
--- /dev/null
+++ b/browser/components/newtab/lib/SystemTickFeed.jsm
@@ -0,0 +1,45 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
+const { actionTypes: at } = ChromeUtils.import(
+ "resource://activity-stream/common/Actions.jsm"
+);
+
+ChromeUtils.defineModuleGetter(
+ this,
+ "setInterval",
+ "resource://gre/modules/Timer.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "clearInterval",
+ "resource://gre/modules/Timer.jsm"
+);
+
+// Frequency at which SYSTEM_TICK events are fired
+const SYSTEM_TICK_INTERVAL = 5 * 60 * 1000;
+
+this.SystemTickFeed = class SystemTickFeed {
+ init() {
+ this.intervalId = setInterval(
+ () => this.store.dispatch({ type: at.SYSTEM_TICK }),
+ SYSTEM_TICK_INTERVAL
+ );
+ }
+
+ onAction(action) {
+ switch (action.type) {
+ case at.INIT:
+ this.init();
+ break;
+ case at.UNINIT:
+ clearInterval(this.intervalId);
+ break;
+ }
+ }
+};
+
+this.SYSTEM_TICK_INTERVAL = SYSTEM_TICK_INTERVAL;
+const EXPORTED_SYMBOLS = ["SystemTickFeed", "SYSTEM_TICK_INTERVAL"];
diff --git a/browser/components/newtab/lib/TelemetryFeed.jsm b/browser/components/newtab/lib/TelemetryFeed.jsm
new file mode 100644
index 0000000000..19f3f4f72d
--- /dev/null
+++ b/browser/components/newtab/lib/TelemetryFeed.jsm
@@ -0,0 +1,1112 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
+const { XPCOMUtils } = ChromeUtils.import(
+ "resource://gre/modules/XPCOMUtils.jsm"
+);
+const { MESSAGE_TYPE_HASH: msg } = ChromeUtils.import(
+ "resource://activity-stream/common/ActorConstants.jsm"
+);
+
+const { actionTypes: at, actionUtils: au } = ChromeUtils.import(
+ "resource://activity-stream/common/Actions.jsm"
+);
+const { Prefs } = ChromeUtils.import(
+ "resource://activity-stream/lib/ActivityStreamPrefs.jsm"
+);
+const { classifySite } = ChromeUtils.import(
+ "resource://activity-stream/lib/SiteClassifier.jsm"
+);
+
+ChromeUtils.defineModuleGetter(
+ this,
+ "AboutNewTab",
+ "resource:///modules/AboutNewTab.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "PingCentre",
+ "resource:///modules/PingCentre.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "UTEventReporting",
+ "resource://activity-stream/lib/UTEventReporting.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "UpdateUtils",
+ "resource://gre/modules/UpdateUtils.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "HomePage",
+ "resource:///modules/HomePage.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "ExtensionSettingsStore",
+ "resource://gre/modules/ExtensionSettingsStore.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "PrivateBrowsingUtils",
+ "resource://gre/modules/PrivateBrowsingUtils.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "ClientID",
+ "resource://gre/modules/ClientID.jsm"
+);
+
+XPCOMUtils.defineLazyModuleGetters(this, {
+ ExperimentAPI: "resource://messaging-system/experiments/ExperimentAPI.jsm",
+ TelemetryEnvironment: "resource://gre/modules/TelemetryEnvironment.jsm",
+ TelemetrySession: "resource://gre/modules/TelemetrySession.jsm",
+});
+
+XPCOMUtils.defineLazyServiceGetters(this, {
+ gUUIDGenerator: ["@mozilla.org/uuid-generator;1", "nsIUUIDGenerator"],
+});
+
+const ACTIVITY_STREAM_ID = "activity-stream";
+const DOMWINDOW_OPENED_TOPIC = "domwindowopened";
+const DOMWINDOW_UNLOAD_TOPIC = "unload";
+const TAB_PINNED_EVENT = "TabPinned";
+
+// This is a mapping table between the user preferences and its encoding code
+const USER_PREFS_ENCODING = {
+ showSearch: 1 << 0,
+ "feeds.topsites": 1 << 1,
+ "feeds.section.topstories": 1 << 2,
+ "feeds.section.highlights": 1 << 3,
+ "feeds.snippets": 1 << 4,
+ showSponsored: 1 << 5,
+ "asrouter.userprefs.cfr.addons": 1 << 6,
+ "asrouter.userprefs.cfr.features": 1 << 7,
+};
+
+const PREF_IMPRESSION_ID = "impressionId";
+const TELEMETRY_PREF = "telemetry";
+const EVENTS_TELEMETRY_PREF = "telemetry.ut.events";
+const STRUCTURED_INGESTION_ENDPOINT_PREF =
+ "telemetry.structuredIngestion.endpoint";
+// List of namespaces for the structured ingestion system.
+// They are defined in https://github.com/mozilla-services/mozilla-pipeline-schemas
+const STRUCTURED_INGESTION_NAMESPACE_AS = "activity-stream";
+const STRUCTURED_INGESTION_NAMESPACE_MS = "messaging-system";
+
+// Used as the missing value for timestamps in the session ping
+const TIMESTAMP_MISSING_VALUE = -1;
+
+// Page filter for onboarding telemetry, any value other than these will
+// be set as "other"
+const ONBOARDING_ALLOWED_PAGE_VALUES = [
+ "about:welcome",
+ "about:home",
+ "about:newtab",
+];
+
+XPCOMUtils.defineLazyGetter(
+ this,
+ "browserSessionId",
+ () => TelemetrySession.getMetadata("").sessionId
+);
+
+this.TelemetryFeed = class TelemetryFeed {
+ constructor() {
+ this.sessions = new Map();
+ this._prefs = new Prefs();
+ this._impressionId = this.getOrCreateImpressionId();
+ this._aboutHomeSeen = false;
+ this._classifySite = classifySite;
+ this._addWindowListeners = this._addWindowListeners.bind(this);
+ this._browserOpenNewtabStart = null;
+ this.handleEvent = this.handleEvent.bind(this);
+ }
+
+ get telemetryEnabled() {
+ return this._prefs.get(TELEMETRY_PREF);
+ }
+
+ get eventTelemetryEnabled() {
+ return this._prefs.get(EVENTS_TELEMETRY_PREF);
+ }
+
+ get structuredIngestionEndpointBase() {
+ return this._prefs.get(STRUCTURED_INGESTION_ENDPOINT_PREF);
+ }
+
+ get telemetryClientId() {
+ Object.defineProperty(this, "telemetryClientId", {
+ value: ClientID.getClientID(),
+ });
+ return this.telemetryClientId;
+ }
+
+ get processStartTs() {
+ let startupInfo = Services.startup.getStartupInfo();
+ let processStartTs = startupInfo.process.getTime();
+
+ Object.defineProperty(this, "processStartTs", {
+ value: processStartTs,
+ });
+ return this.processStartTs;
+ }
+
+ init() {
+ Services.obs.addObserver(
+ this.browserOpenNewtabStart,
+ "browser-open-newtab-start"
+ );
+ // Add pin tab event listeners on future windows
+ Services.obs.addObserver(this._addWindowListeners, DOMWINDOW_OPENED_TOPIC);
+ // Listen for pin tab events on all open windows
+ for (let win of Services.wm.getEnumerator("navigator:browser")) {
+ this._addWindowListeners(win);
+ }
+ // Set a scalar for the "deletion-request" ping (See bug 1602064)
+ Services.telemetry.scalarSet(
+ "deletion.request.impression_id",
+ this._impressionId
+ );
+ }
+
+ handleEvent(event) {
+ switch (event.type) {
+ case TAB_PINNED_EVENT:
+ this.countPinnedTab(event.target);
+ break;
+ case DOMWINDOW_UNLOAD_TOPIC:
+ this._removeWindowListeners(event.target);
+ break;
+ }
+ }
+
+ _removeWindowListeners(win) {
+ win.removeEventListener(DOMWINDOW_UNLOAD_TOPIC, this.handleEvent);
+ win.removeEventListener(TAB_PINNED_EVENT, this.handleEvent);
+ }
+
+ _addWindowListeners(win) {
+ win.addEventListener(DOMWINDOW_UNLOAD_TOPIC, this.handleEvent);
+ win.addEventListener(TAB_PINNED_EVENT, this.handleEvent);
+ }
+
+ countPinnedTab(target, source = "TAB_CONTEXT_MENU") {
+ const win = target.ownerGlobal;
+ if (PrivateBrowsingUtils.isWindowPrivate(win)) {
+ return;
+ }
+ const event = Object.assign(this.createPing(), {
+ action: "activity_stream_user_event",
+ event: TAB_PINNED_EVENT.toUpperCase(),
+ value: { total_pinned_tabs: this.countTotalPinnedTabs() },
+ source,
+ // These fields are required but not relevant for this ping
+ page: "n/a",
+ session_id: "n/a",
+ });
+ this.sendEvent(event);
+ }
+
+ countTotalPinnedTabs() {
+ let pinnedTabs = 0;
+ for (let win of Services.wm.getEnumerator("navigator:browser")) {
+ if (win.closed || PrivateBrowsingUtils.isWindowPrivate(win)) {
+ continue;
+ }
+ for (let tab of win.gBrowser.tabs) {
+ pinnedTabs += tab.pinned ? 1 : 0;
+ }
+ }
+
+ return pinnedTabs;
+ }
+
+ getOrCreateImpressionId() {
+ let impressionId = this._prefs.get(PREF_IMPRESSION_ID);
+ if (!impressionId) {
+ impressionId = String(gUUIDGenerator.generateUUID());
+ this._prefs.set(PREF_IMPRESSION_ID, impressionId);
+ }
+ return impressionId;
+ }
+
+ browserOpenNewtabStart() {
+ let now = Cu.now();
+ this._browserOpenNewtabStart = Math.round(this.processStartTs + now);
+
+ ChromeUtils.addProfilerMarker(
+ "UserTiming",
+ now,
+ "browser-open-newtab-start"
+ );
+ }
+
+ setLoadTriggerInfo(port) {
+ // XXX note that there is a race condition here; we're assuming that no
+ // other tab will be interleaving calls to browserOpenNewtabStart and
+ // when at.NEW_TAB_INIT gets triggered by RemotePages and calls this
+ // method. For manually created windows, it's hard to imagine us hitting
+ // this race condition.
+ //
+ // However, for session restore, where multiple windows with multiple tabs
+ // might be restored much closer together in time, it's somewhat less hard,
+ // though it should still be pretty rare.
+ //
+ // The fix to this would be making all of the load-trigger notifications
+ // return some data with their notifications, and somehow propagate that
+ // data through closures into the tab itself so that we could match them
+ //
+ // As of this writing (very early days of system add-on perf telemetry),
+ // the hypothesis is that hitting this race should be so rare that makes
+ // more sense to live with the slight data inaccuracy that it would
+ // introduce, rather than doing the correct but complicated thing. It may
+ // well be worth reexamining this hypothesis after we have more experience
+ // with the data.
+
+ let data_to_save;
+ try {
+ if (!this._browserOpenNewtabStart) {
+ throw new Error("No browser-open-newtab-start recorded.");
+ }
+ data_to_save = {
+ load_trigger_ts: this._browserOpenNewtabStart,
+ load_trigger_type: "menu_plus_or_keyboard",
+ };
+ } catch (e) {
+ // if no mark was returned, we have nothing to save
+ return;
+ }
+ this.saveSessionPerfData(port, data_to_save);
+ }
+
+ /**
+ * Lazily initialize PingCentre for Activity Stream to send pings
+ */
+ get pingCentre() {
+ Object.defineProperty(this, "pingCentre", {
+ value: new PingCentre({ topic: ACTIVITY_STREAM_ID }),
+ });
+ return this.pingCentre;
+ }
+
+ /**
+ * Lazily initialize UTEventReporting to send pings
+ */
+ get utEvents() {
+ Object.defineProperty(this, "utEvents", { value: new UTEventReporting() });
+ return this.utEvents;
+ }
+
+ /**
+ * Get encoded user preferences, multiple prefs will be combined via bitwise OR operator
+ */
+ get userPreferences() {
+ let prefs = 0;
+
+ for (const pref of Object.keys(USER_PREFS_ENCODING)) {
+ if (this._prefs.get(pref)) {
+ prefs |= USER_PREFS_ENCODING[pref];
+ }
+ }
+ return prefs;
+ }
+
+ /**
+ * Check if it is in the CFR experiment cohort by querying against the
+ * experiment manager of Messaging System
+ *
+ * @return {bool}
+ */
+ get isInCFRCohort() {
+ try {
+ const experimentData = ExperimentAPI.getExperimentMetaData({
+ featureId: "cfr",
+ });
+ if (experimentData && experimentData.slug) {
+ return true;
+ }
+ } catch (e) {}
+
+ return false;
+ }
+
+ /**
+ * addSession - Start tracking a new session
+ *
+ * @param {string} id the portID of the open session
+ * @param {string} the URL being loaded for this session (optional)
+ * @return {obj} Session object
+ */
+ addSession(id, url) {
+ // XXX refactor to use setLoadTriggerInfo or saveSessionPerfData
+
+ // "unexpected" will be overwritten when appropriate
+ let load_trigger_type = "unexpected";
+ let load_trigger_ts;
+
+ if (!this._aboutHomeSeen && url === "about:home") {
+ this._aboutHomeSeen = true;
+
+ // XXX note that this will be incorrectly set in the following cases:
+ // session_restore following by clicking on the toolbar button,
+ // or someone who has changed their default home page preference to
+ // something else and later clicks the toolbar. It will also be
+ // incorrectly unset if someone changes their "Home Page" preference to
+ // about:newtab.
+ //
+ // That said, the ratio of these mistakes to correct cases should
+ // be very small, and these issues should follow away as we implement
+ // the remaining load_trigger_type values for about:home in issue 3556.
+ //
+ // XXX file a bug to implement remaining about:home cases so this
+ // problem will go away and link to it here.
+ load_trigger_type = "first_window_opened";
+
+ // The real perceived trigger of first_window_opened is the OS-level
+ // clicking of the icon. We express this by using the process start
+ // absolute timestamp.
+ load_trigger_ts = this.processStartTs;
+ }
+
+ const session = {
+ session_id: String(gUUIDGenerator.generateUUID()),
+ // "unknown" will be overwritten when appropriate
+ page: url ? url : "unknown",
+ perf: {
+ load_trigger_type,
+ is_preloaded: false,
+ },
+ };
+
+ if (load_trigger_ts) {
+ session.perf.load_trigger_ts = load_trigger_ts;
+ }
+
+ this.sessions.set(id, session);
+ return session;
+ }
+
+ /**
+ * endSession - Stop tracking a session
+ *
+ * @param {string} portID the portID of the session that just closed
+ */
+ endSession(portID) {
+ const session = this.sessions.get(portID);
+
+ if (!session) {
+ // It's possible the tab was never visible – in which case, there was no user session.
+ return;
+ }
+
+ this.sendDiscoveryStreamLoadedContent(portID, session);
+ this.sendDiscoveryStreamImpressions(portID, session);
+
+ if (session.perf.visibility_event_rcvd_ts) {
+ let absNow = this.processStartTs + Cu.now();
+ session.session_duration = Math.round(
+ absNow - session.perf.visibility_event_rcvd_ts
+ );
+
+ // Rounding all timestamps in perf to ease the data processing on the backend.
+ // NB: use `TIMESTAMP_MISSING_VALUE` if the value is missing.
+ session.perf.visibility_event_rcvd_ts = Math.round(
+ session.perf.visibility_event_rcvd_ts
+ );
+ session.perf.load_trigger_ts = Math.round(
+ session.perf.load_trigger_ts || TIMESTAMP_MISSING_VALUE
+ );
+ session.perf.topsites_first_painted_ts = Math.round(
+ session.perf.topsites_first_painted_ts || TIMESTAMP_MISSING_VALUE
+ );
+ } else {
+ // This session was never shown (i.e. the hidden preloaded newtab), there was no user session either.
+ this.sessions.delete(portID);
+ return;
+ }
+
+ let sessionEndEvent = this.createSessionEndEvent(session);
+ this.sendEvent(sessionEndEvent);
+ this.sendUTEvent(sessionEndEvent, this.utEvents.sendSessionEndEvent);
+ this.sessions.delete(portID);
+ }
+
+ /**
+ * Send impression pings for Discovery Stream for a given session.
+ *
+ * @note the impression reports are stored in session.impressionSets for different
+ * sources, and will be sent separately accordingly.
+ *
+ * @param {String} port The session port with which this is associated
+ * @param {Object} session The session object
+ */
+ sendDiscoveryStreamImpressions(port, session) {
+ const { impressionSets } = session;
+
+ if (!impressionSets) {
+ return;
+ }
+
+ Object.keys(impressionSets).forEach(source => {
+ const payload = this.createImpressionStats(port, {
+ source,
+ tiles: impressionSets[source],
+ });
+ this.sendStructuredIngestionEvent(
+ payload,
+ STRUCTURED_INGESTION_NAMESPACE_AS,
+ "impression-stats",
+ "1"
+ );
+ });
+ }
+
+ /**
+ * Send loaded content pings for Discovery Stream for a given session.
+ *
+ * @note the loaded content reports are stored in session.loadedContentSets for different
+ * sources, and will be sent separately accordingly.
+ *
+ * @param {String} port The session port with which this is associated
+ * @param {Object} session The session object
+ */
+ sendDiscoveryStreamLoadedContent(port, session) {
+ const { loadedContentSets } = session;
+
+ if (!loadedContentSets) {
+ return;
+ }
+
+ Object.keys(loadedContentSets).forEach(source => {
+ const tiles = loadedContentSets[source];
+ const payload = this.createImpressionStats(port, {
+ source,
+ tiles,
+ loaded: tiles.length,
+ });
+ this.sendStructuredIngestionEvent(
+ payload,
+ STRUCTURED_INGESTION_NAMESPACE_AS,
+ "impression-stats",
+ "1"
+ );
+ });
+ }
+
+ /**
+ * handleNewTabInit - Handle NEW_TAB_INIT, which creates a new session and sets the a flag
+ * for session.perf based on whether or not this new tab is preloaded
+ *
+ * @param {obj} action the Action object
+ */
+ handleNewTabInit(action) {
+ const session = this.addSession(
+ au.getPortIdOfSender(action),
+ action.data.url
+ );
+ session.perf.is_preloaded =
+ action.data.browser.getAttribute("preloadedState") === "preloaded";
+ }
+
+ /**
+ * createPing - Create a ping with common properties
+ *
+ * @param {string} id The portID of the session, if a session is relevant (optional)
+ * @return {obj} A telemetry ping
+ */
+ createPing(portID) {
+ const ping = {
+ addon_version: Services.appinfo.appBuildID,
+ locale: Services.locale.appLocaleAsBCP47,
+ user_prefs: this.userPreferences,
+ };
+
+ // If the ping is part of a user session, add session-related info
+ if (portID) {
+ const session = this.sessions.get(portID) || this.addSession(portID);
+ Object.assign(ping, { session_id: session.session_id });
+
+ if (session.page) {
+ Object.assign(ping, { page: session.page });
+ }
+ }
+ return ping;
+ }
+
+ /**
+ * createImpressionStats - Create a ping for an impression stats
+ *
+ * @param {string} portID The portID of the open session
+ * @param {ob} data The data object to be included in the ping.
+ * @return {obj} A telemetry ping
+ */
+ createImpressionStats(portID, data) {
+ let ping = Object.assign(this.createPing(portID), data, {
+ impression_id: this._impressionId,
+ });
+ // Make sure `session_id` and `client_id` are not in the ping.
+ delete ping.session_id;
+ delete ping.client_id;
+ return ping;
+ }
+
+ createUserEvent(action) {
+ return Object.assign(
+ this.createPing(au.getPortIdOfSender(action)),
+ action.data,
+ { action: "activity_stream_user_event" }
+ );
+ }
+
+ createSessionEndEvent(session) {
+ return Object.assign(this.createPing(), {
+ session_id: session.session_id,
+ page: session.page,
+ session_duration: session.session_duration,
+ action: "activity_stream_session",
+ perf: session.perf,
+ profile_creation_date:
+ TelemetryEnvironment.currentEnvironment.profile.resetDate ||
+ TelemetryEnvironment.currentEnvironment.profile.creationDate,
+ });
+ }
+
+ /**
+ * Create a ping for AS router event. The client_id is set to "n/a" by default,
+ * different component can override this by its own telemetry collection policy.
+ */
+ async createASRouterEvent(action) {
+ let event = {
+ ...action.data,
+ addon_version: Services.appinfo.appBuildID,
+ locale: Services.locale.appLocaleAsBCP47,
+ };
+ const session = this.sessions.get(au.getPortIdOfSender(action));
+ if (event.event_context && typeof event.event_context === "object") {
+ event.event_context = JSON.stringify(event.event_context);
+ }
+ switch (event.action) {
+ case "cfr_user_event":
+ event = await this.applyCFRPolicy(event);
+ break;
+ case "snippets_local_testing_user_event":
+ case "snippets_user_event":
+ event = await this.applySnippetsPolicy(event);
+ break;
+ case "badge_user_event":
+ case "whats-new-panel_user_event":
+ event = await this.applyWhatsNewPolicy(event);
+ break;
+ case "infobar_user_event":
+ event = await this.applyInfoBarPolicy(event);
+ break;
+ case "moments_user_event":
+ event = await this.applyMomentsPolicy(event);
+ break;
+ case "onboarding_user_event":
+ event = await this.applyOnboardingPolicy(event, session);
+ break;
+ case "asrouter_undesired_event":
+ event = this.applyUndesiredEventPolicy(event);
+ break;
+ default:
+ event = { ping: event };
+ break;
+ }
+ return event;
+ }
+
+ /**
+ * Per Bug 1484035, CFR metrics comply with following policies:
+ * 1). In release, it collects impression_id, and treats bucket_id as message_id
+ * 2). In prerelease, it collects client_id and message_id
+ * 3). In shield experiments conducted in release, it collects client_id and message_id
+ */
+ async applyCFRPolicy(ping) {
+ if (
+ UpdateUtils.getUpdateChannel(true) === "release" &&
+ !this.isInCFRCohort
+ ) {
+ ping.message_id = "n/a";
+ ping.impression_id = this._impressionId;
+ } else {
+ ping.client_id = await this.telemetryClientId;
+ }
+ delete ping.action;
+ return { ping, pingType: "cfr" };
+ }
+
+ /**
+ * Per Bug 1482134, all the metrics for What's New panel use client_id in
+ * all the release channels
+ */
+ async applyWhatsNewPolicy(ping) {
+ ping.client_id = await this.telemetryClientId;
+ ping.browser_session_id = browserSessionId;
+ // Attach page info to `event_context` if there is a session associated with this ping
+ delete ping.action;
+ return { ping, pingType: "whats-new-panel" };
+ }
+
+ async applyInfoBarPolicy(ping) {
+ ping.client_id = await this.telemetryClientId;
+ ping.browser_session_id = browserSessionId;
+ delete ping.action;
+ return { ping, pingType: "infobar" };
+ }
+
+ /**
+ * Per Bug 1484035, Moments metrics comply with following policies:
+ * 1). In release, it collects impression_id, and treats bucket_id as message_id
+ * 2). In prerelease, it collects client_id and message_id
+ * 3). In shield experiments conducted in release, it collects client_id and message_id
+ */
+ async applyMomentsPolicy(ping) {
+ if (
+ UpdateUtils.getUpdateChannel(true) === "release" &&
+ !this.isInCFRCohort
+ ) {
+ ping.message_id = "n/a";
+ ping.impression_id = this._impressionId;
+ } else {
+ ping.client_id = await this.telemetryClientId;
+ }
+ delete ping.action;
+ return { ping, pingType: "moments" };
+ }
+
+ /**
+ * Per Bug 1485069, all the metrics for Snippets in AS router use client_id in
+ * all the release channels
+ */
+ async applySnippetsPolicy(ping) {
+ ping.client_id = await this.telemetryClientId;
+ delete ping.action;
+ return { ping, pingType: "snippets" };
+ }
+
+ /**
+ * Per Bug 1482134, all the metrics for Onboarding in AS router use client_id in
+ * all the release channels
+ */
+ async applyOnboardingPolicy(ping, session) {
+ ping.client_id = await this.telemetryClientId;
+ ping.browser_session_id = browserSessionId;
+ // Attach page info to `event_context` if there is a session associated with this ping
+ if (ping.action === "onboarding_user_event" && session && session.page) {
+ let event_context;
+
+ try {
+ event_context = ping.event_context
+ ? JSON.parse(ping.event_context)
+ : {};
+ } catch (e) {
+ // If `ping.event_context` is not a JSON serialized string, then we create a `value`
+ // key for it
+ event_context = { value: ping.event_context };
+ }
+
+ if (ONBOARDING_ALLOWED_PAGE_VALUES.includes(session.page)) {
+ event_context.page = session.page;
+ } else {
+ Cu.reportError(`Invalid 'page' for Onboarding event: ${session.page}`);
+ }
+ ping.event_context = JSON.stringify(event_context);
+ }
+ delete ping.action;
+ return { ping, pingType: "onboarding" };
+ }
+
+ applyUndesiredEventPolicy(ping) {
+ ping.impression_id = this._impressionId;
+ delete ping.action;
+ return { ping, pingType: "undesired-events" };
+ }
+
+ sendEvent(event_object) {
+ switch (event_object.action) {
+ case "activity_stream_user_event":
+ this.sendEventPing(event_object);
+ break;
+ case "activity_stream_session":
+ this.sendSessionPing(event_object);
+ break;
+ }
+ }
+
+ async sendEventPing(ping) {
+ delete ping.action;
+ ping.client_id = await this.telemetryClientId;
+ ping.browser_session_id = browserSessionId;
+ if (ping.value && typeof ping.value === "object") {
+ ping.value = JSON.stringify(ping.value);
+ }
+ this.sendStructuredIngestionEvent(
+ ping,
+ STRUCTURED_INGESTION_NAMESPACE_AS,
+ "events",
+ 1
+ );
+ }
+
+ async sendSessionPing(ping) {
+ delete ping.action;
+ ping.client_id = await this.telemetryClientId;
+ this.sendStructuredIngestionEvent(
+ ping,
+ STRUCTURED_INGESTION_NAMESPACE_AS,
+ "sessions",
+ 1
+ );
+ }
+
+ sendUTEvent(event_object, eventFunction) {
+ if (this.telemetryEnabled && this.eventTelemetryEnabled) {
+ eventFunction(event_object);
+ }
+ }
+
+ /**
+ * Generates an endpoint for Structured Ingestion telemetry pipeline. Note that
+ * Structured Ingestion requires a different endpoint for each ping. See more
+ * details about endpoint schema at:
+ * https://github.com/mozilla/gcp-ingestion/blob/master/docs/edge.md#postput-request
+ *
+ * @param {String} namespace Namespace of the ping, such as "activity-stream" or "messaging-system".
+ * @param {String} pingType Type of the ping, such as "impression-stats".
+ * @param {String} version Endpoint version for this ping type.
+ */
+ _generateStructuredIngestionEndpoint(namespace, pingType, version) {
+ const uuid = gUUIDGenerator.generateUUID().toString();
+ // Structured Ingestion does not support the UUID generated by gUUIDGenerator,
+ // because it contains leading and trailing braces. Need to trim them first.
+ const docID = uuid.slice(1, -1);
+ const extension = `${namespace}/${pingType}/${version}/${docID}`;
+ return `${this.structuredIngestionEndpointBase}/${extension}`;
+ }
+
+ sendStructuredIngestionEvent(eventObject, namespace, pingType, version) {
+ if (this.telemetryEnabled) {
+ this.pingCentre.sendStructuredIngestionPing(
+ eventObject,
+ this._generateStructuredIngestionEndpoint(namespace, pingType, version)
+ );
+ }
+ }
+
+ handleImpressionStats(action) {
+ const payload = this.createImpressionStats(
+ au.getPortIdOfSender(action),
+ action.data
+ );
+ this.sendStructuredIngestionEvent(
+ payload,
+ STRUCTURED_INGESTION_NAMESPACE_AS,
+ "impression-stats",
+ "1"
+ );
+ }
+
+ handleUserEvent(action) {
+ let userEvent = this.createUserEvent(action);
+ this.sendEvent(userEvent);
+ this.sendUTEvent(userEvent, this.utEvents.sendUserEvent);
+ }
+
+ async handleASRouterUserEvent(action) {
+ const { ping, pingType } = await this.createASRouterEvent(action);
+ if (!pingType) {
+ Cu.reportError("Unknown ping type for ASRouter telemetry");
+ return;
+ }
+ this.sendStructuredIngestionEvent(
+ ping,
+ STRUCTURED_INGESTION_NAMESPACE_MS,
+ pingType,
+ "1"
+ );
+ }
+
+ /**
+ * This function is used by ActivityStreamStorage to report errors
+ * trying to access IndexedDB.
+ */
+ SendASRouterUndesiredEvent(data) {
+ this.handleASRouterUserEvent({
+ data: { ...data, action: "asrouter_undesired_event" },
+ });
+ }
+
+ async sendPageTakeoverData() {
+ if (this.telemetryEnabled) {
+ const value = {};
+ let newtabAffected = false;
+ let homeAffected = false;
+
+ // Check whether or not about:home and about:newtab are set to a custom URL.
+ // If so, classify them.
+ if (
+ Services.prefs.getBoolPref("browser.newtabpage.enabled") &&
+ AboutNewTab.newTabURLOverridden &&
+ !AboutNewTab.newTabURL.startsWith("moz-extension://")
+ ) {
+ value.newtab_url_category = await this._classifySite(
+ AboutNewTab.newTabURL
+ );
+ newtabAffected = true;
+ }
+ // Check if the newtab page setting is controlled by an extension.
+ await ExtensionSettingsStore.initialize();
+ const newtabExtensionInfo = ExtensionSettingsStore.getSetting(
+ "url_overrides",
+ "newTabURL"
+ );
+ if (newtabExtensionInfo && newtabExtensionInfo.id) {
+ value.newtab_extension_id = newtabExtensionInfo.id;
+ newtabAffected = true;
+ }
+
+ const homePageURL = HomePage.get();
+ if (
+ !["about:home", "about:blank"].includes(homePageURL) &&
+ !homePageURL.startsWith("moz-extension://")
+ ) {
+ value.home_url_category = await this._classifySite(homePageURL);
+ homeAffected = true;
+ }
+ const homeExtensionInfo = ExtensionSettingsStore.getSetting(
+ "prefs",
+ "homepage_override"
+ );
+ if (homeExtensionInfo && homeExtensionInfo.id) {
+ value.home_extension_id = homeExtensionInfo.id;
+ homeAffected = true;
+ }
+
+ let page;
+ if (newtabAffected && homeAffected) {
+ page = "both";
+ } else if (newtabAffected) {
+ page = "about:newtab";
+ } else if (homeAffected) {
+ page = "about:home";
+ }
+
+ if (page) {
+ const event = Object.assign(this.createPing(), {
+ action: "activity_stream_user_event",
+ event: "PAGE_TAKEOVER_DATA",
+ value,
+ page,
+ session_id: "n/a",
+ });
+ this.sendEvent(event);
+ }
+ }
+ }
+
+ onAction(action) {
+ switch (action.type) {
+ case at.INIT:
+ this.init();
+ this.sendPageTakeoverData();
+ break;
+ case at.NEW_TAB_INIT:
+ this.handleNewTabInit(action);
+ break;
+ case at.NEW_TAB_UNLOAD:
+ this.endSession(au.getPortIdOfSender(action));
+ break;
+ case at.SAVE_SESSION_PERF_DATA:
+ this.saveSessionPerfData(au.getPortIdOfSender(action), action.data);
+ break;
+ case at.TELEMETRY_IMPRESSION_STATS:
+ this.handleImpressionStats(action);
+ break;
+ case at.DISCOVERY_STREAM_IMPRESSION_STATS:
+ this.handleDiscoveryStreamImpressionStats(
+ au.getPortIdOfSender(action),
+ action.data
+ );
+ break;
+ case at.DISCOVERY_STREAM_LOADED_CONTENT:
+ this.handleDiscoveryStreamLoadedContent(
+ au.getPortIdOfSender(action),
+ action.data
+ );
+ break;
+ case at.TELEMETRY_USER_EVENT:
+ this.handleUserEvent(action);
+ break;
+ // The next few action types come from ASRouter, which doesn't use
+ // Actions from Actions.jsm, but uses these other custom strings.
+ case msg.TOOLBAR_BADGE_TELEMETRY:
+ // Intentional fall-through
+ case msg.TOOLBAR_PANEL_TELEMETRY:
+ // Intentional fall-through
+ case msg.MOMENTS_PAGE_TELEMETRY:
+ // Intentional fall-through
+ case msg.DOORHANGER_TELEMETRY:
+ // Intentional fall-through
+ case msg.INFOBAR_TELEMETRY:
+ // Intentional fall-through
+ case at.AS_ROUTER_TELEMETRY_USER_EVENT:
+ this.handleASRouterUserEvent(action);
+ break;
+ case at.UNINIT:
+ this.uninit();
+ break;
+ }
+ }
+
+ /**
+ * Handle impression stats actions from Discovery Stream. The data will be
+ * stored into the session.impressionSets object for the given port, so that
+ * it is sent to the server when the session ends.
+ *
+ * @note session.impressionSets will be keyed on `source` of the `data`,
+ * all the data will be appended to an array for the same source.
+ *
+ * @param {String} port The session port with which this is associated
+ * @param {Object} data The impression data structured as {source: "SOURCE", tiles: [{id: 123}]}
+ *
+ */
+ handleDiscoveryStreamImpressionStats(port, data) {
+ let session = this.sessions.get(port);
+
+ if (!session) {
+ throw new Error("Session does not exist.");
+ }
+
+ const impressionSets = session.impressionSets || {};
+ const impressions = impressionSets[data.source] || [];
+ // The payload might contain other properties, we need `id`, `pos` and potentially `shim` here.
+ data.tiles.forEach(tile =>
+ impressions.push({
+ id: tile.id,
+ pos: tile.pos,
+ ...(tile.shim ? { shim: tile.shim } : {}),
+ })
+ );
+ impressionSets[data.source] = impressions;
+ session.impressionSets = impressionSets;
+ }
+
+ /**
+ * Handle loaded content actions from Discovery Stream. The data will be
+ * stored into the session.loadedContentSets object for the given port, so that
+ * it is sent to the server when the session ends.
+ *
+ * @note session.loadedContentSets will be keyed on `source` of the `data`,
+ * all the data will be appended to an array for the same source.
+ *
+ * @param {String} port The session port with which this is associated
+ * @param {Object} data The loaded content structured as {source: "SOURCE", tiles: [{id: 123}]}
+ *
+ */
+ handleDiscoveryStreamLoadedContent(port, data) {
+ let session = this.sessions.get(port);
+
+ if (!session) {
+ throw new Error("Session does not exist.");
+ }
+
+ const loadedContentSets = session.loadedContentSets || {};
+ const loadedContents = loadedContentSets[data.source] || [];
+ // The payload might contain other properties, we need `id` and `pos` here.
+ data.tiles.forEach(tile =>
+ loadedContents.push({ id: tile.id, pos: tile.pos })
+ );
+ loadedContentSets[data.source] = loadedContents;
+ session.loadedContentSets = loadedContentSets;
+ }
+
+ /**
+ * Take all enumerable members of the data object and merge them into
+ * the session.perf object for the given port, so that it is sent to the
+ * server when the session ends. All members of the data object should
+ * be valid values of the perf object, as defined in pings.js and the
+ * data*.md documentation.
+ *
+ * @note Any existing keys with the same names already in the
+ * session perf object will be overwritten by values passed in here.
+ *
+ * @param {String} port The session with which this is associated
+ * @param {Object} data The perf data to be
+ */
+ saveSessionPerfData(port, data) {
+ // XXX should use try/catch and send a bad state indicator if this
+ // get blows up.
+ let session = this.sessions.get(port);
+
+ // XXX Partial workaround for #3118; avoids the worst incorrect associations
+ // of times with browsers, by associating the load trigger with the
+ // visibility event as the user is most likely associating the trigger to
+ // the tab just shown. This helps avoid associating with a preloaded
+ // browser as those don't get the event until shown. Better fix for more
+ // cases forthcoming.
+ //
+ // XXX the about:home check (and the corresponding test) should go away
+ // once the load_trigger stuff in addSession is refactored into
+ // setLoadTriggerInfo.
+ //
+ if (data.visibility_event_rcvd_ts && session.page !== "about:home") {
+ this.setLoadTriggerInfo(port);
+ }
+
+ let timestamp = data.topsites_first_painted_ts;
+
+ if (
+ timestamp &&
+ session.page === "about:home" &&
+ !HomePage.overridden &&
+ Services.prefs.getIntPref("browser.startup.page") === 1
+ ) {
+ AboutNewTab.maybeRecordTopsitesPainted(timestamp);
+ }
+
+ Object.assign(session.perf, data);
+ }
+
+ uninit() {
+ try {
+ Services.obs.removeObserver(
+ this.browserOpenNewtabStart,
+ "browser-open-newtab-start"
+ );
+ Services.obs.removeObserver(
+ this._addWindowListeners,
+ DOMWINDOW_OPENED_TOPIC
+ );
+ } catch (e) {
+ // Operation can fail when uninit is called before
+ // init has finished setting up the observer
+ }
+
+ // Only uninit if the getter has initialized it
+ if (Object.prototype.hasOwnProperty.call(this, "pingCentre")) {
+ this.pingCentre.uninit();
+ }
+ if (Object.prototype.hasOwnProperty.call(this, "utEvents")) {
+ this.utEvents.uninit();
+ }
+
+ // TODO: Send any unfinished sessions
+ }
+};
+
+const EXPORTED_SYMBOLS = [
+ "TelemetryFeed",
+ "USER_PREFS_ENCODING",
+ "PREF_IMPRESSION_ID",
+ "TELEMETRY_PREF",
+ "EVENTS_TELEMETRY_PREF",
+ "STRUCTURED_INGESTION_ENDPOINT_PREF",
+];
diff --git a/browser/components/newtab/lib/TippyTopProvider.jsm b/browser/components/newtab/lib/TippyTopProvider.jsm
new file mode 100644
index 0000000000..cca184a035
--- /dev/null
+++ b/browser/components/newtab/lib/TippyTopProvider.jsm
@@ -0,0 +1,72 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+const { XPCOMUtils } = ChromeUtils.import(
+ "resource://gre/modules/XPCOMUtils.jsm"
+);
+
+XPCOMUtils.defineLazyModuleGetters(this, {
+ Services: "resource://gre/modules/Services.jsm",
+});
+
+XPCOMUtils.defineLazyGlobalGetters(this, ["fetch", "URL"]);
+
+const TIPPYTOP_PATH = "chrome://activity-stream/content/data/content/tippytop/";
+const TIPPYTOP_JSON_PATH =
+ "chrome://activity-stream/content/data/content/tippytop/top_sites.json";
+
+/*
+ * Get a domain from a url optionally stripping subdomains.
+ */
+function getDomain(url, strip = "www.") {
+ let domain = "";
+ try {
+ domain = new URL(url).hostname;
+ } catch (ex) {}
+ if (strip === "*") {
+ try {
+ domain = Services.eTLD.getBaseDomainFromHost(domain);
+ } catch (ex) {}
+ } else if (domain.startsWith(strip)) {
+ domain = domain.slice(strip.length);
+ }
+ return domain;
+}
+
+this.TippyTopProvider = class TippyTopProvider {
+ constructor() {
+ this._sitesByDomain = new Map();
+ this.initialized = false;
+ }
+
+ async init() {
+ // Load the Tippy Top sites from the json manifest.
+ try {
+ for (const site of await (
+ await fetch(TIPPYTOP_JSON_PATH, {
+ credentials: "omit",
+ })
+ ).json()) {
+ for (const domain of site.domains) {
+ this._sitesByDomain.set(domain, site);
+ }
+ }
+ this.initialized = true;
+ } catch (error) {
+ Cu.reportError("Failed to load tippy top manifest.");
+ }
+ }
+
+ processSite(site, strip) {
+ const tippyTop = this._sitesByDomain.get(getDomain(site.url, strip));
+ if (tippyTop) {
+ site.tippyTopIcon = TIPPYTOP_PATH + tippyTop.image_url;
+ site.smallFavicon = TIPPYTOP_PATH + tippyTop.favicon_url;
+ site.backgroundColor = tippyTop.background_color;
+ }
+ return site;
+ }
+};
+
+const EXPORTED_SYMBOLS = ["TippyTopProvider", "getDomain"];
diff --git a/browser/components/newtab/lib/ToolbarBadgeHub.jsm b/browser/components/newtab/lib/ToolbarBadgeHub.jsm
new file mode 100644
index 0000000000..4914d941f5
--- /dev/null
+++ b/browser/components/newtab/lib/ToolbarBadgeHub.jsm
@@ -0,0 +1,316 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
+const { XPCOMUtils } = ChromeUtils.import(
+ "resource://gre/modules/XPCOMUtils.jsm"
+);
+
+XPCOMUtils.defineLazyModuleGetters(this, {
+ EveryWindow: "resource:///modules/EveryWindow.jsm",
+ ToolbarPanelHub: "resource://activity-stream/lib/ToolbarPanelHub.jsm",
+ Services: "resource://gre/modules/Services.jsm",
+ PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.jsm",
+ requestIdleCallback: "resource://gre/modules/Timer.jsm",
+ setTimeout: "resource://gre/modules/Timer.jsm",
+ clearTimeout: "resource://gre/modules/Timer.jsm",
+});
+
+let notificationsByWindow = new WeakMap();
+
+class _ToolbarBadgeHub {
+ constructor() {
+ this.id = "toolbar-badge-hub";
+ this.state = {};
+ this.prefs = {
+ WHATSNEW_TOOLBAR_PANEL: "browser.messaging-system.whatsNewPanel.enabled",
+ };
+ this.removeAllNotifications = this.removeAllNotifications.bind(this);
+ this.removeToolbarNotification = this.removeToolbarNotification.bind(this);
+ this.addToolbarNotification = this.addToolbarNotification.bind(this);
+ this.registerBadgeToAllWindows = this.registerBadgeToAllWindows.bind(this);
+ this._sendPing = this._sendPing.bind(this);
+ this.sendUserEventTelemetry = this.sendUserEventTelemetry.bind(this);
+
+ this._handleMessageRequest = null;
+ this._addImpression = null;
+ this._blockMessageById = null;
+ this._sendTelemetry = null;
+ this._initialized = false;
+ }
+
+ async init(
+ waitForInitialized,
+ {
+ handleMessageRequest,
+ addImpression,
+ blockMessageById,
+ unblockMessageById,
+ sendTelemetry,
+ }
+ ) {
+ if (this._initialized) {
+ return;
+ }
+
+ this._initialized = true;
+ this._handleMessageRequest = handleMessageRequest;
+ this._blockMessageById = blockMessageById;
+ this._unblockMessageById = unblockMessageById;
+ this._addImpression = addImpression;
+ this._sendTelemetry = sendTelemetry;
+ // Need to wait for ASRouter to initialize before trying to fetch messages
+ await waitForInitialized;
+ this.messageRequest({
+ triggerId: "toolbarBadgeUpdate",
+ template: "toolbar_badge",
+ });
+ // Listen for pref changes that could trigger new badges
+ Services.prefs.addObserver(this.prefs.WHATSNEW_TOOLBAR_PANEL, this);
+ }
+
+ observe(aSubject, aTopic, aPrefName) {
+ switch (aPrefName) {
+ case this.prefs.WHATSNEW_TOOLBAR_PANEL:
+ this.messageRequest({
+ triggerId: "toolbarBadgeUpdate",
+ template: "toolbar_badge",
+ });
+ break;
+ }
+ }
+
+ maybeInsertFTL(win) {
+ win.MozXULElement.insertFTLIfNeeded("browser/newtab/asrouter.ftl");
+ }
+
+ executeAction({ id, data, message_id }) {
+ switch (id) {
+ case "show-whatsnew-button":
+ ToolbarPanelHub.enableToolbarButton();
+ ToolbarPanelHub.enableAppmenuButton();
+ break;
+ }
+ }
+
+ _clearBadgeTimeout() {
+ if (this.state.showBadgeTimeoutId) {
+ clearTimeout(this.state.showBadgeTimeoutId);
+ }
+ }
+
+ removeAllNotifications(event) {
+ if (event) {
+ // ignore right clicks
+ if (
+ (event.type === "mousedown" || event.type === "click") &&
+ event.button !== 0
+ ) {
+ return;
+ }
+ // ignore keyboard access that is not one of the usual accessor keys
+ if (
+ event.type === "keypress" &&
+ event.key !== " " &&
+ event.key !== "Enter"
+ ) {
+ return;
+ }
+
+ event.target.removeEventListener(
+ "mousedown",
+ this.removeAllNotifications
+ );
+ event.target.removeEventListener("keypress", this.removeAllNotifications);
+ // If we have an event it means the user interacted with the badge
+ // we should send telemetry
+ if (this.state.notification) {
+ this.sendUserEventTelemetry("CLICK", this.state.notification);
+ }
+ }
+ // Will call uninit on every window
+ EveryWindow.unregisterCallback(this.id);
+ if (this.state.notification) {
+ this._blockMessageById(this.state.notification.id);
+ }
+ this._clearBadgeTimeout();
+ this.state = {};
+ }
+
+ removeToolbarNotification(toolbarButton) {
+ // Remove it from the element that displays the badge
+ toolbarButton
+ .querySelector(".toolbarbutton-badge")
+ .classList.remove("feature-callout");
+ toolbarButton.removeAttribute("badged");
+ // Remove id used for for aria-label badge description
+ const notificationDescription = toolbarButton.querySelector(
+ "#toolbarbutton-notification-description"
+ );
+ if (notificationDescription) {
+ notificationDescription.remove();
+ toolbarButton.removeAttribute("aria-labelledby");
+ toolbarButton.removeAttribute("aria-describedby");
+ }
+ }
+
+ addToolbarNotification(win, message) {
+ const document = win.browser.ownerDocument;
+ if (message.content.action) {
+ this.executeAction({ ...message.content.action, message_id: message.id });
+ }
+ let toolbarbutton = document.getElementById(message.content.target);
+ if (toolbarbutton) {
+ const badge = toolbarbutton.querySelector(".toolbarbutton-badge");
+ badge.classList.add("feature-callout");
+ toolbarbutton.setAttribute("badged", true);
+ // If we have additional aria-label information for the notification
+ // we add this content to the hidden `toolbarbutton-text` node.
+ // We then use `aria-labelledby` to link this description to the button
+ // that received the notification badge.
+ if (message.content.badgeDescription) {
+ // Insert strings as soon as we know we're showing them
+ this.maybeInsertFTL(win);
+ toolbarbutton.setAttribute(
+ "aria-labelledby",
+ `toolbarbutton-notification-description ${message.content.target}`
+ );
+ // Because tooltiptext is different to the label, it gets duplicated as
+ // the description. Setting `describedby` to the same value as
+ // `labelledby` will be detected by the a11y code and the description
+ // will be removed.
+ toolbarbutton.setAttribute(
+ "aria-describedby",
+ `toolbarbutton-notification-description ${message.content.target}`
+ );
+ const descriptionEl = document.createElement("span");
+ descriptionEl.setAttribute(
+ "id",
+ "toolbarbutton-notification-description"
+ );
+ descriptionEl.setAttribute("hidden", true);
+ document.l10n.setAttributes(
+ descriptionEl,
+ message.content.badgeDescription.string_id
+ );
+ toolbarbutton.appendChild(descriptionEl);
+ }
+ // `mousedown` event required because of the `onmousedown` defined on
+ // the button that prevents `click` events from firing
+ toolbarbutton.addEventListener("mousedown", this.removeAllNotifications);
+ // `keypress` event required for keyboard accessibility
+ toolbarbutton.addEventListener("keypress", this.removeAllNotifications);
+ this.state = { notification: { id: message.id } };
+
+ // Impression should be added when the badge becomes visible
+ this._addImpression(message);
+ // Send a telemetry ping when adding the notification badge
+ this.sendUserEventTelemetry("IMPRESSION", message);
+
+ return toolbarbutton;
+ }
+
+ return null;
+ }
+
+ registerBadgeToAllWindows(message) {
+ if (message.template === "update_action") {
+ this.executeAction({ ...message.content.action, message_id: message.id });
+ // No badge to set only an action to execute
+ return;
+ }
+
+ EveryWindow.registerCallback(
+ this.id,
+ win => {
+ if (notificationsByWindow.has(win)) {
+ // nothing to do
+ return;
+ }
+ const el = this.addToolbarNotification(win, message);
+ notificationsByWindow.set(win, el);
+ },
+ win => {
+ const el = notificationsByWindow.get(win);
+ if (el) {
+ this.removeToolbarNotification(el);
+ }
+ notificationsByWindow.delete(win);
+ }
+ );
+ }
+
+ registerBadgeNotificationListener(message, options = {}) {
+ // We need to clear any existing notifications and only show
+ // the one set by devtools
+ if (options.force) {
+ this.removeAllNotifications();
+ // When debugging immediately show the badge
+ this.registerBadgeToAllWindows(message);
+ return;
+ }
+
+ if (message.content.delay) {
+ this.state.showBadgeTimeoutId = setTimeout(() => {
+ requestIdleCallback(() => this.registerBadgeToAllWindows(message));
+ }, message.content.delay);
+ } else {
+ this.registerBadgeToAllWindows(message);
+ }
+ }
+
+ async messageRequest({ triggerId, template }) {
+ const telemetryObject = { triggerId };
+ TelemetryStopwatch.start("MS_MESSAGE_REQUEST_TIME_MS", telemetryObject);
+ const message = await this._handleMessageRequest({
+ triggerId,
+ template,
+ });
+ TelemetryStopwatch.finish("MS_MESSAGE_REQUEST_TIME_MS", telemetryObject);
+ if (message) {
+ this.registerBadgeNotificationListener(message);
+ }
+ }
+
+ _sendPing(ping) {
+ this._sendTelemetry({
+ type: "TOOLBAR_BADGE_TELEMETRY",
+ data: { action: "badge_user_event", ...ping },
+ });
+ }
+
+ sendUserEventTelemetry(event, message) {
+ const win = Services.wm.getMostRecentWindow("navigator:browser");
+ // Only send pings for non private browsing windows
+ if (
+ win &&
+ !PrivateBrowsingUtils.isBrowserPrivate(
+ win.ownerGlobal.gBrowser.selectedBrowser
+ )
+ ) {
+ this._sendPing({
+ message_id: message.id,
+ event,
+ });
+ }
+ }
+
+ uninit() {
+ this._clearBadgeTimeout();
+ this.state = {};
+ this._initialized = false;
+ notificationsByWindow = new WeakMap();
+ Services.prefs.removeObserver(this.prefs.WHATSNEW_TOOLBAR_PANEL, this);
+ }
+}
+
+this._ToolbarBadgeHub = _ToolbarBadgeHub;
+
+/**
+ * ToolbarBadgeHub - singleton instance of _ToolbarBadgeHub that can initiate
+ * message requests and render messages.
+ */
+this.ToolbarBadgeHub = new _ToolbarBadgeHub();
+
+const EXPORTED_SYMBOLS = ["ToolbarBadgeHub", "_ToolbarBadgeHub"];
diff --git a/browser/components/newtab/lib/ToolbarPanelHub.jsm b/browser/components/newtab/lib/ToolbarPanelHub.jsm
new file mode 100644
index 0000000000..06d27ed090
--- /dev/null
+++ b/browser/components/newtab/lib/ToolbarPanelHub.jsm
@@ -0,0 +1,631 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
+const { XPCOMUtils } = ChromeUtils.import(
+ "resource://gre/modules/XPCOMUtils.jsm"
+);
+XPCOMUtils.defineLazyModuleGetters(this, {
+ Services: "resource://gre/modules/Services.jsm",
+ EveryWindow: "resource:///modules/EveryWindow.jsm",
+ PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.jsm",
+ Preferences: "resource://gre/modules/Preferences.jsm",
+ SpecialMessageActions:
+ "resource://messaging-system/lib/SpecialMessageActions.jsm",
+ RemoteL10n: "resource://activity-stream/lib/RemoteL10n.jsm",
+});
+ChromeUtils.defineModuleGetter(
+ this,
+ "PanelMultiView",
+ "resource:///modules/PanelMultiView.jsm"
+);
+XPCOMUtils.defineLazyServiceGetter(
+ this,
+ "TrackingDBService",
+ "@mozilla.org/tracking-db-service;1",
+ "nsITrackingDBService"
+);
+
+const idToTextMap = new Map([
+ [Ci.nsITrackingDBService.TRACKERS_ID, "trackerCount"],
+ [Ci.nsITrackingDBService.TRACKING_COOKIES_ID, "cookieCount"],
+ [Ci.nsITrackingDBService.CRYPTOMINERS_ID, "cryptominerCount"],
+ [Ci.nsITrackingDBService.FINGERPRINTERS_ID, "fingerprinterCount"],
+ [Ci.nsITrackingDBService.SOCIAL_ID, "socialCount"],
+]);
+
+const WHATSNEW_ENABLED_PREF = "browser.messaging-system.whatsNewPanel.enabled";
+const PROTECTIONS_PANEL_INFOMSG_PREF =
+ "browser.protections_panel.infoMessage.seen";
+
+const TOOLBAR_BUTTON_ID = "whats-new-menu-button";
+const APPMENU_BUTTON_ID = "appMenu-whatsnew-button";
+
+const BUTTON_STRING_ID = "cfr-whatsnew-button";
+const WHATS_NEW_PANEL_SELECTOR = "PanelUI-whatsNew-message-container";
+
+class _ToolbarPanelHub {
+ constructor() {
+ this.triggerId = "whatsNewPanelOpened";
+ this._showAppmenuButton = this._showAppmenuButton.bind(this);
+ this._hideAppmenuButton = this._hideAppmenuButton.bind(this);
+ this._showToolbarButton = this._showToolbarButton.bind(this);
+ this._hideToolbarButton = this._hideToolbarButton.bind(this);
+ this.insertProtectionPanelMessage = this.insertProtectionPanelMessage.bind(
+ this
+ );
+
+ this.state = {};
+ this._initialized = false;
+ }
+
+ async init(waitForInitialized, { getMessages, sendTelemetry }) {
+ if (this._initialized) {
+ return;
+ }
+
+ this._initialized = true;
+ this._getMessages = getMessages;
+ this._sendTelemetry = sendTelemetry;
+ // Wait for ASRouter messages to become available in order to know
+ // if we can show the What's New panel
+ await waitForInitialized;
+ // Enable the application menu button so that the user can access
+ // the panel outside of the toolbar button
+ await this.enableAppmenuButton();
+
+ this.state = {
+ protectionPanelMessageSeen: Services.prefs.getBoolPref(
+ PROTECTIONS_PANEL_INFOMSG_PREF,
+ false
+ ),
+ };
+ }
+
+ uninit() {
+ this._initialized = false;
+ EveryWindow.unregisterCallback(TOOLBAR_BUTTON_ID);
+ EveryWindow.unregisterCallback(APPMENU_BUTTON_ID);
+ }
+
+ get messages() {
+ return this._getMessages({
+ template: "whatsnew_panel_message",
+ triggerId: "whatsNewPanelOpened",
+ returnAll: true,
+ });
+ }
+
+ toggleWhatsNewPref(event) {
+ // Checkbox onclick handler gets called before the checkbox state gets toggled,
+ // so we have to call it with the opposite value.
+ let newValue = !event.target.checked;
+ Preferences.set(WHATSNEW_ENABLED_PREF, newValue);
+
+ this.sendUserEventTelemetry(
+ event.target.ownerGlobal,
+ "WNP_PREF_TOGGLE",
+ // Message id is not applicable in this case, the notification state
+ // is not related to a particular message
+ { id: "n/a" },
+ { value: { prefValue: newValue } }
+ );
+ }
+
+ maybeInsertFTL(win) {
+ win.MozXULElement.insertFTLIfNeeded("browser/newtab/asrouter.ftl");
+ win.MozXULElement.insertFTLIfNeeded("browser/branding/brandings.ftl");
+ win.MozXULElement.insertFTLIfNeeded("browser/branding/sync-brand.ftl");
+ }
+
+ maybeLoadCustomElement(win) {
+ if (!win.customElements.get("remote-text")) {
+ Services.scriptloader.loadSubScript(
+ "resource://activity-stream/data/custom-elements/paragraph.js",
+ win
+ );
+ }
+ }
+
+ // Turns on the Appmenu (hamburger menu) button for all open windows and future windows.
+ async enableAppmenuButton() {
+ if ((await this.messages).length) {
+ EveryWindow.registerCallback(
+ APPMENU_BUTTON_ID,
+ this._showAppmenuButton,
+ this._hideAppmenuButton
+ );
+ }
+ }
+
+ // Removes the button from the Appmenu.
+ // Only used in tests.
+ disableAppmenuButton() {
+ EveryWindow.unregisterCallback(APPMENU_BUTTON_ID);
+ }
+
+ // Turns on the Toolbar button for all open windows and future windows.
+ async enableToolbarButton() {
+ if ((await this.messages).length) {
+ EveryWindow.registerCallback(
+ TOOLBAR_BUTTON_ID,
+ this._showToolbarButton,
+ this._hideToolbarButton
+ );
+ }
+ }
+
+ // When the panel is hidden we want to run some cleanup
+ _onPanelHidden(win) {
+ const panelContainer = win.document.getElementById(
+ "customizationui-widget-panel"
+ );
+ // When the panel is hidden we want to remove any toolbar buttons that
+ // might have been added as an entry point to the panel
+ const removeToolbarButton = () => {
+ EveryWindow.unregisterCallback(TOOLBAR_BUTTON_ID);
+ };
+ if (!panelContainer) {
+ return;
+ }
+ panelContainer.addEventListener("popuphidden", removeToolbarButton, {
+ once: true,
+ });
+ }
+
+ // Newer messages first and use `order` field to decide between messages
+ // with the same timestamp
+ _sortWhatsNewMessages(m1, m2) {
+ // Sort by published_date in descending order.
+ if (m1.content.published_date === m2.content.published_date) {
+ // Ascending order
+ return m1.order - m2.order;
+ }
+ if (m1.content.published_date > m2.content.published_date) {
+ return -1;
+ }
+ return 1;
+ }
+
+ // Render what's new messages into the panel.
+ async renderMessages(win, doc, containerId, options = {}) {
+ // Set the checked status of the footer checkbox
+ let value = Preferences.get(WHATSNEW_ENABLED_PREF);
+ let checkbox = win.document.getElementById("panelMenu-toggleWhatsNew");
+
+ checkbox.checked = value;
+
+ this.maybeLoadCustomElement(win);
+ const messages =
+ (options.force && options.messages) ||
+ (await this.messages).sort(this._sortWhatsNewMessages);
+ const container = PanelMultiView.getViewNode(doc, containerId);
+
+ if (messages) {
+ // Targeting attribute state might have changed making new messages
+ // available and old messages invalid, we need to refresh
+ this.removeMessages(win, containerId);
+ let previousDate = 0;
+ // Get and store any variable part of the message content
+ this.state.contentArguments = await this._contentArguments();
+ for (let message of messages) {
+ container.appendChild(
+ this._createMessageElements(win, doc, message, previousDate)
+ );
+ previousDate = message.content.published_date;
+ }
+ }
+
+ this._onPanelHidden(win);
+
+ // Panel impressions are not associated with one particular message
+ // but with a set of messages. We concatenate message ids and send them
+ // back for every impression.
+ const eventId = {
+ id: messages
+ .map(({ id }) => id)
+ .sort()
+ .join(","),
+ };
+ // Check `mainview` attribute to determine if the panel is shown as a
+ // subview (inside the application menu) or as a toolbar dropdown.
+ // https://searchfox.org/mozilla-central/rev/07f7390618692fa4f2a674a96b9b677df3a13450/browser/components/customizableui/PanelMultiView.jsm#1268
+ const mainview = win.PanelUI.whatsNewPanel.hasAttribute("mainview");
+ this.sendUserEventTelemetry(win, "IMPRESSION", eventId, {
+ value: { view: mainview ? "toolbar_dropdown" : "application_menu" },
+ });
+ }
+
+ removeMessages(win, containerId) {
+ const doc = win.document;
+ const messageNodes = PanelMultiView.getViewNode(
+ doc,
+ containerId
+ ).querySelectorAll(".whatsNew-message");
+ for (const messageNode of messageNodes) {
+ messageNode.remove();
+ }
+ }
+
+ /**
+ * Dispatch the action defined in the message and user telemetry event.
+ */
+ _dispatchUserAction(win, message) {
+ let url;
+ try {
+ // Set platform specific path variables for SUMO articles
+ url = Services.urlFormatter.formatURL(message.content.cta_url);
+ } catch (e) {
+ Cu.reportError(e);
+ url = message.content.cta_url;
+ }
+ SpecialMessageActions.handleAction(
+ {
+ type: message.content.cta_type,
+ data: {
+ args: url,
+ where: message.content.cta_where || "tabshifted",
+ },
+ },
+ win.browser
+ );
+
+ this.sendUserEventTelemetry(win, "CLICK", message);
+ }
+
+ /**
+ * Attach event listener to dispatch message defined action.
+ */
+ _attachCommandListener(win, element, message) {
+ // Add event listener for `mouseup` not to overlap with the
+ // `mousedown` & `click` events dispatched from PanelMultiView.jsm
+ // https://searchfox.org/mozilla-central/rev/7531325c8660cfa61bf71725f83501028178cbb9/browser/components/customizableui/PanelMultiView.jsm#1830-1837
+ element.addEventListener("mouseup", () => {
+ this._dispatchUserAction(win, message);
+ });
+ element.addEventListener("keyup", e => {
+ if (e.key === "Enter" || e.key === " ") {
+ this._dispatchUserAction(win, message);
+ }
+ });
+ }
+
+ _createMessageElements(win, doc, message, previousDate) {
+ const { content } = message;
+ const messageEl = RemoteL10n.createElement(doc, "div");
+ messageEl.classList.add("whatsNew-message");
+
+ // Only render date if it is different from the one rendered before.
+ if (content.published_date !== previousDate) {
+ messageEl.appendChild(
+ RemoteL10n.createElement(doc, "p", {
+ classList: "whatsNew-message-date",
+ content: new Date(content.published_date).toLocaleDateString(
+ "default",
+ {
+ month: "long",
+ day: "numeric",
+ year: "numeric",
+ }
+ ),
+ })
+ );
+ }
+
+ const wrapperEl = RemoteL10n.createElement(doc, "div");
+ wrapperEl.doCommand = () => this._dispatchUserAction(win, message);
+ wrapperEl.classList.add("whatsNew-message-body");
+ messageEl.appendChild(wrapperEl);
+
+ if (content.icon_url) {
+ wrapperEl.classList.add("has-icon");
+ const iconEl = RemoteL10n.createElement(doc, "img");
+ iconEl.src = content.icon_url;
+ iconEl.classList.add("whatsNew-message-icon");
+ if (content.icon_alt && content.icon_alt.string_id) {
+ doc.l10n.setAttributes(iconEl, content.icon_alt.string_id);
+ } else {
+ iconEl.setAttribute("alt", content.icon_alt);
+ }
+ wrapperEl.appendChild(iconEl);
+ }
+
+ wrapperEl.appendChild(this._createMessageContent(win, doc, content));
+
+ if (content.link_text) {
+ const anchorEl = RemoteL10n.createElement(doc, "a", {
+ classList: "text-link",
+ content: content.link_text,
+ });
+ anchorEl.doCommand = () => this._dispatchUserAction(win, message);
+ wrapperEl.appendChild(anchorEl);
+ }
+
+ // Attach event listener on entire message container
+ this._attachCommandListener(win, messageEl, message);
+
+ return messageEl;
+ }
+
+ /**
+ * Return message title (optional subtitle) and body
+ */
+ _createMessageContent(win, doc, content) {
+ const wrapperEl = new win.DocumentFragment();
+
+ wrapperEl.appendChild(
+ RemoteL10n.createElement(doc, "h2", {
+ classList: "whatsNew-message-title",
+ content: content.title,
+ attributes: this.state.contentArguments,
+ })
+ );
+
+ switch (content.layout) {
+ case "tracking-protections":
+ wrapperEl.appendChild(
+ RemoteL10n.createElement(doc, "h4", {
+ classList: "whatsNew-message-subtitle",
+ content: content.subtitle,
+ attributes: this.state.contentArguments,
+ })
+ );
+ wrapperEl.appendChild(
+ RemoteL10n.createElement(doc, "h2", {
+ classList: "whatsNew-message-title-large",
+ content: this.state.contentArguments[
+ content.layout_title_content_variable
+ ],
+ attributes: this.state.contentArguments,
+ })
+ );
+ break;
+ }
+
+ wrapperEl.appendChild(
+ RemoteL10n.createElement(doc, "p", {
+ content: content.body,
+ classList: "whatsNew-message-content",
+ attributes: this.state.contentArguments,
+ })
+ );
+
+ return wrapperEl;
+ }
+
+ _createHeroElement(win, doc, message) {
+ this.maybeLoadCustomElement(win);
+
+ const messageEl = RemoteL10n.createElement(doc, "div");
+ messageEl.setAttribute("id", "protections-popup-message");
+ messageEl.classList.add("whatsNew-hero-message");
+ const wrapperEl = RemoteL10n.createElement(doc, "div");
+ wrapperEl.classList.add("whatsNew-message-body");
+ messageEl.appendChild(wrapperEl);
+
+ wrapperEl.appendChild(
+ RemoteL10n.createElement(doc, "h2", {
+ classList: "whatsNew-message-title",
+ content: message.content.title,
+ })
+ );
+ wrapperEl.appendChild(
+ RemoteL10n.createElement(doc, "p", {
+ classList: "protections-popup-content",
+ content: message.content.body,
+ })
+ );
+
+ if (message.content.link_text) {
+ let linkEl = RemoteL10n.createElement(doc, "a", {
+ classList: "text-link",
+ content: message.content.link_text,
+ });
+ linkEl.disabled = true;
+ wrapperEl.appendChild(linkEl);
+ this._attachCommandListener(win, linkEl, message);
+ } else {
+ this._attachCommandListener(win, wrapperEl, message);
+ }
+
+ return messageEl;
+ }
+
+ async _contentArguments() {
+ const { defaultEngine } = Services.search;
+ // Between now and 6 weeks ago
+ const dateTo = new Date();
+ const dateFrom = new Date(dateTo.getTime() - 42 * 24 * 60 * 60 * 1000);
+ const eventsByDate = await TrackingDBService.getEventsByDateRange(
+ dateFrom,
+ dateTo
+ );
+ // Make sure we set all types of possible values to 0 because they might
+ // be referenced by fluent strings
+ let totalEvents = { blockedCount: 0 };
+ for (let blockedType of idToTextMap.values()) {
+ totalEvents[blockedType] = 0;
+ }
+ // Count all events in the past 6 weeks. Returns an object with:
+ // `blockedCount` total number of blocked resources
+ // {tracker|cookie|social...} breakdown by event type as defined by `idToTextMap`
+ totalEvents = eventsByDate.reduce((acc, day) => {
+ const type = day.getResultByName("type");
+ const count = day.getResultByName("count");
+ acc[idToTextMap.get(type)] = (acc[idToTextMap.get(type)] || 0) + count;
+ acc.blockedCount += count;
+ return acc;
+ }, totalEvents);
+ return {
+ // Keys need to match variable names used in asrouter.ftl
+ // `earliestDate` will be either 6 weeks ago or when tracking recording
+ // started. Whichever is more recent.
+ earliestDate: Math.max(
+ new Date(await TrackingDBService.getEarliestRecordedDate()),
+ dateFrom
+ ),
+ ...totalEvents,
+ // Passing in `undefined` as string for the Fluent variable name
+ // in order to match and select the message that does not require
+ // the variable.
+ searchEngineName: defaultEngine ? defaultEngine.name : "undefined",
+ };
+ }
+
+ async _showAppmenuButton(win) {
+ this.maybeInsertFTL(win);
+ await this._showElement(
+ win.browser.ownerDocument,
+ APPMENU_BUTTON_ID,
+ BUTTON_STRING_ID
+ );
+ }
+
+ _hideAppmenuButton(win, windowClosed) {
+ // No need to do something if the window is going away
+ if (!windowClosed) {
+ this._hideElement(win.browser.ownerDocument, APPMENU_BUTTON_ID);
+ }
+ }
+
+ _showToolbarButton(win) {
+ const document = win.browser.ownerDocument;
+ this.maybeInsertFTL(win);
+ return this._showElement(document, TOOLBAR_BUTTON_ID, BUTTON_STRING_ID);
+ }
+
+ _hideToolbarButton(win) {
+ this._hideElement(win.browser.ownerDocument, TOOLBAR_BUTTON_ID);
+ }
+
+ _showElement(document, id, string_id) {
+ const el = PanelMultiView.getViewNode(document, id);
+ document.l10n.setAttributes(el, string_id);
+ el.removeAttribute("hidden");
+ }
+
+ _hideElement(document, id) {
+ const el = PanelMultiView.getViewNode(document, id);
+ if (el) {
+ el.setAttribute("hidden", true);
+ }
+ }
+
+ _sendPing(ping) {
+ this._sendTelemetry({
+ type: "TOOLBAR_PANEL_TELEMETRY",
+ data: { action: "whats-new-panel_user_event", ...ping },
+ });
+ }
+
+ sendUserEventTelemetry(win, event, message, options = {}) {
+ // Only send pings for non private browsing windows
+ if (
+ win &&
+ !PrivateBrowsingUtils.isBrowserPrivate(
+ win.ownerGlobal.gBrowser.selectedBrowser
+ )
+ ) {
+ this._sendPing({
+ message_id: message.id,
+ event,
+ event_context: options.value,
+ });
+ }
+ }
+
+ /**
+ * Inserts a message into the Protections Panel. The message is visible once
+ * and afterwards set in a collapsed state. It can be shown again using the
+ * info button in the panel header.
+ */
+ async insertProtectionPanelMessage(event) {
+ const win = event.target.ownerGlobal;
+ this.maybeInsertFTL(win);
+
+ const doc = event.target.ownerDocument;
+ const container = doc.getElementById("messaging-system-message-container");
+ const infoButton = doc.getElementById("protections-popup-info-button");
+ const panelContainer = doc.getElementById("protections-popup");
+ const toggleMessage = () => {
+ const learnMoreLink = doc.querySelector(
+ "#messaging-system-message-container .text-link"
+ );
+ if (learnMoreLink) {
+ container.toggleAttribute("disabled");
+ infoButton.toggleAttribute("checked");
+ panelContainer.toggleAttribute("infoMessageShowing");
+ learnMoreLink.disabled = !learnMoreLink.disabled;
+ }
+ };
+ if (!container.childElementCount) {
+ const message = await this._getMessages({
+ template: "protections_panel",
+ triggerId: "protectionsPanelOpen",
+ });
+ if (message) {
+ const messageEl = this._createHeroElement(win, doc, message);
+ container.appendChild(messageEl);
+ infoButton.addEventListener("click", toggleMessage);
+ this.sendUserEventTelemetry(win, "IMPRESSION", message);
+ }
+ }
+ // Message is collapsed by default. If it was never shown before we want
+ // to expand it
+ if (
+ !this.state.protectionPanelMessageSeen &&
+ container.hasAttribute("disabled")
+ ) {
+ toggleMessage();
+ }
+ // Save state that we displayed the message
+ if (!this.state.protectionPanelMessageSeen) {
+ Services.prefs.setBoolPref(PROTECTIONS_PANEL_INFOMSG_PREF, true);
+ this.state.protectionPanelMessageSeen = true;
+ }
+ // Collapse the message after the panel is hidden so we don't get the
+ // animation when opening the panel
+ panelContainer.addEventListener(
+ "popuphidden",
+ () => {
+ if (
+ this.state.protectionPanelMessageSeen &&
+ !container.hasAttribute("disabled")
+ ) {
+ toggleMessage();
+ }
+ },
+ {
+ once: true,
+ }
+ );
+ }
+
+ /**
+ * @param {object} browser MessageChannel target argument as a response to a user action
+ * @param {object[]} messages Messages selected from devtools page
+ */
+ forceShowMessage(browser, messages) {
+ const win = browser.ownerGlobal;
+ const doc = browser.ownerDocument;
+ this.removeMessages(win, WHATS_NEW_PANEL_SELECTOR);
+ this.renderMessages(win, doc, WHATS_NEW_PANEL_SELECTOR, {
+ force: true,
+ messages: Array.isArray(messages) ? messages : [messages],
+ });
+ win.PanelUI.panel.addEventListener("popuphidden", event =>
+ this.removeMessages(event.target.ownerGlobal, WHATS_NEW_PANEL_SELECTOR)
+ );
+ }
+}
+
+this._ToolbarPanelHub = _ToolbarPanelHub;
+
+/**
+ * ToolbarPanelHub - singleton instance of _ToolbarPanelHub that can initiate
+ * message requests and render messages.
+ */
+this.ToolbarPanelHub = new _ToolbarPanelHub();
+
+const EXPORTED_SYMBOLS = ["ToolbarPanelHub", "_ToolbarPanelHub"];
diff --git a/browser/components/newtab/lib/TopSitesFeed.jsm b/browser/components/newtab/lib/TopSitesFeed.jsm
new file mode 100644
index 0000000000..9699bef217
--- /dev/null
+++ b/browser/components/newtab/lib/TopSitesFeed.jsm
@@ -0,0 +1,1174 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
+const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
+const { XPCOMUtils } = ChromeUtils.import(
+ "resource://gre/modules/XPCOMUtils.jsm"
+);
+
+const { actionCreators: ac, actionTypes: at } = ChromeUtils.import(
+ "resource://activity-stream/common/Actions.jsm"
+);
+const { TippyTopProvider } = ChromeUtils.import(
+ "resource://activity-stream/lib/TippyTopProvider.jsm"
+);
+const { insertPinned, TOP_SITES_MAX_SITES_PER_ROW } = ChromeUtils.import(
+ "resource://activity-stream/common/Reducers.jsm"
+);
+const { Dedupe } = ChromeUtils.import(
+ "resource://activity-stream/common/Dedupe.jsm"
+);
+const { shortURL } = ChromeUtils.import(
+ "resource://activity-stream/lib/ShortURL.jsm"
+);
+const { getDefaultOptions } = ChromeUtils.import(
+ "resource://activity-stream/lib/ActivityStreamStorage.jsm"
+);
+const {
+ CUSTOM_SEARCH_SHORTCUTS,
+ SEARCH_SHORTCUTS_EXPERIMENT,
+ SEARCH_SHORTCUTS_SEARCH_ENGINES_PREF,
+ SEARCH_SHORTCUTS_HAVE_PINNED_PREF,
+ checkHasSearchEngine,
+ getSearchProvider,
+ getSearchFormURL,
+} = ChromeUtils.import("resource://activity-stream/lib/SearchShortcuts.jsm");
+
+ChromeUtils.defineModuleGetter(
+ this,
+ "filterAdult",
+ "resource://activity-stream/lib/FilterAdult.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "LinksCache",
+ "resource://activity-stream/lib/LinksCache.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "NewTabUtils",
+ "resource://gre/modules/NewTabUtils.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "Screenshots",
+ "resource://activity-stream/lib/Screenshots.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "PageThumbs",
+ "resource://gre/modules/PageThumbs.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "RemoteSettings",
+ "resource://services-settings/remote-settings.js"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "Region",
+ "resource://gre/modules/Region.jsm"
+);
+
+const DEFAULT_SITES_PREF = "default.sites";
+const SHOWN_ON_NEWTAB_PREF = "feeds.topsites";
+const DEFAULT_TOP_SITES = [];
+const FRECENCY_THRESHOLD = 100 + 1; // 1 visit (skip first-run/one-time pages)
+const MIN_FAVICON_SIZE = 96;
+const CACHED_LINK_PROPS_TO_MIGRATE = ["screenshot", "customScreenshot"];
+const PINNED_FAVICON_PROPS_TO_MIGRATE = [
+ "favicon",
+ "faviconRef",
+ "faviconSize",
+];
+const SECTION_ID = "topsites";
+const ROWS_PREF = "topSitesRows";
+const SHOW_SPONSORED_PREF = "showSponsoredTopSites";
+
+// Search experiment stuff
+const FILTER_DEFAULT_SEARCH_PREF = "improvesearch.noDefaultSearchTile";
+const SEARCH_FILTERS = [
+ "google",
+ "search.yahoo",
+ "yahoo",
+ "bing",
+ "ask",
+ "duckduckgo",
+];
+
+const REMOTE_SETTING_DEFAULTS_PREF = "browser.topsites.useRemoteSetting";
+const REMOTE_SETTING_MIGRATION_ID_PREF =
+ "browser.topsites.migratedToRemoteSetting.id";
+const DEFAULT_SITES_POLICY_PREF =
+ "browser.newtabpage.activity-stream.default.sites";
+const DEFAULT_SITES_EXPERIMENTS_PREF_BRANCH = "browser.topsites.experiment.";
+
+function getShortURLForCurrentSearch() {
+ const url = shortURL({ url: Services.search.defaultEngine.searchForm });
+ return url;
+}
+
+this.TopSitesFeed = class TopSitesFeed {
+ constructor() {
+ this._tippyTopProvider = new TippyTopProvider();
+ XPCOMUtils.defineLazyGetter(
+ this,
+ "_currentSearchHostname",
+ getShortURLForCurrentSearch
+ );
+ this.dedupe = new Dedupe(this._dedupeKey);
+ this.frecentCache = new LinksCache(
+ NewTabUtils.activityStreamLinks,
+ "getTopSites",
+ CACHED_LINK_PROPS_TO_MIGRATE,
+ (oldOptions, newOptions) =>
+ // Refresh if no old options or requesting more items
+ !(oldOptions.numItems >= newOptions.numItems)
+ );
+ this.pinnedCache = new LinksCache(NewTabUtils.pinnedLinks, "links", [
+ ...CACHED_LINK_PROPS_TO_MIGRATE,
+ ...PINNED_FAVICON_PROPS_TO_MIGRATE,
+ ]);
+ PageThumbs.addExpirationFilter(this);
+ }
+
+ init() {
+ // If the feed was previously disabled PREFS_INITIAL_VALUES was never received
+ this._readDefaults({ isStartup: true });
+ this._storage = this.store.dbStorage.getDbTable("sectionPrefs");
+ Services.obs.addObserver(this, "browser-search-engine-modified");
+ Services.obs.addObserver(this, "browser-region");
+ Services.prefs.addObserver(REMOTE_SETTING_DEFAULTS_PREF, this);
+ Services.prefs.addObserver(DEFAULT_SITES_POLICY_PREF, this);
+ Services.prefs.addObserver(DEFAULT_SITES_EXPERIMENTS_PREF_BRANCH, this);
+ }
+
+ uninit() {
+ PageThumbs.removeExpirationFilter(this);
+ Services.obs.removeObserver(this, "browser-search-engine-modified");
+ Services.obs.removeObserver(this, "browser-region");
+ Services.prefs.removeObserver(REMOTE_SETTING_DEFAULTS_PREF, this);
+ Services.prefs.removeObserver(DEFAULT_SITES_POLICY_PREF, this);
+ Services.prefs.removeObserver(DEFAULT_SITES_EXPERIMENTS_PREF_BRANCH, this);
+ }
+
+ observe(subj, topic, data) {
+ switch (topic) {
+ case "browser-search-engine-modified":
+ // We should update the current top sites if the search engine has been changed since
+ // the search engine that gets filtered out of top sites has changed.
+ if (
+ data === "engine-default" &&
+ this.store.getState().Prefs.values[FILTER_DEFAULT_SEARCH_PREF]
+ ) {
+ delete this._currentSearchHostname;
+ this._currentSearchHostname = getShortURLForCurrentSearch();
+ this.refresh({ broadcast: true });
+ }
+ break;
+ case "browser-region":
+ this._readDefaults();
+ break;
+ case "nsPref:changed":
+ if (
+ data === REMOTE_SETTING_DEFAULTS_PREF ||
+ data === DEFAULT_SITES_POLICY_PREF ||
+ data.startsWith(DEFAULT_SITES_EXPERIMENTS_PREF_BRANCH)
+ ) {
+ this._readDefaults();
+ }
+ break;
+ }
+ }
+
+ _dedupeKey(site) {
+ return site && site.hostname;
+ }
+
+ /**
+ * _readDefaults - sets DEFAULT_TOP_SITES
+ */
+ async _readDefaults({ isStartup = false } = {}) {
+ this._useRemoteSetting = Services.prefs.getBoolPref(
+ REMOTE_SETTING_DEFAULTS_PREF
+ );
+
+ if (!this._useRemoteSetting) {
+ this.refreshDefaults(
+ this.store.getState().Prefs.values[DEFAULT_SITES_PREF],
+ { isStartup }
+ );
+ Services.prefs.clearUserPref(REMOTE_SETTING_MIGRATION_ID_PREF);
+ return;
+ }
+
+ // Unpin old search shortcuts.
+ const remoteSettingMigrationID = 1;
+ if (
+ Services.prefs.getIntPref(REMOTE_SETTING_MIGRATION_ID_PREF, 0) <
+ remoteSettingMigrationID
+ ) {
+ this.unpinAllSearchShortcuts();
+ Services.prefs.setIntPref(
+ REMOTE_SETTING_MIGRATION_ID_PREF,
+ remoteSettingMigrationID
+ );
+ }
+
+ // Try using default top sites from enterprise policies. The pref is locked
+ // when set that way.
+ if (Services.prefs.prefIsLocked(DEFAULT_SITES_POLICY_PREF)) {
+ let sites;
+ try {
+ sites = Services.prefs.getStringPref(DEFAULT_SITES_POLICY_PREF);
+ } catch (e) {}
+ if (sites) {
+ this.refreshDefaults(sites, { isStartup });
+ return;
+ }
+ }
+
+ // Read defaults from remote settings.
+ let remoteSettingData = await this._getRemoteConfig();
+
+ // Clear out the array of any previous defaults.
+ DEFAULT_TOP_SITES.length = 0;
+
+ for (let siteData of remoteSettingData) {
+ let link = {
+ isDefault: true,
+ url: siteData.url,
+ hostname: shortURL(siteData),
+ sendAttributionRequest: !!siteData.send_attribution_request,
+ };
+ if (siteData.url_urlbar_override) {
+ link.url_urlbar = siteData.url_urlbar_override;
+ }
+ if (siteData.title) {
+ link.label = siteData.title;
+ }
+ if (siteData.search_shortcut) {
+ link = await this.topSiteToSearchTopSite(link);
+ } else if (siteData.sponsored_position) {
+ link.sponsored_position = siteData.sponsored_position;
+ }
+ DEFAULT_TOP_SITES.push(link);
+ }
+
+ this.refresh({ broadcast: true, isStartup });
+ }
+
+ refreshDefaults(sites, { isStartup = false } = {}) {
+ // Clear out the array of any previous defaults
+ DEFAULT_TOP_SITES.length = 0;
+
+ // Add default sites if any based on the pref
+ if (sites) {
+ for (const url of sites.split(",")) {
+ const site = {
+ isDefault: true,
+ url,
+ };
+ site.hostname = shortURL(site);
+ DEFAULT_TOP_SITES.push(site);
+ }
+ }
+
+ this.refresh({ broadcast: true, isStartup });
+ }
+
+ async _getRemoteConfig(firstTime = true) {
+ if (!this._remoteConfig) {
+ this._remoteConfig = await RemoteSettings("top-sites");
+ this._remoteConfig.on("sync", () => {
+ this._readDefaults();
+ });
+ }
+
+ let result = [];
+ let failed = false;
+ try {
+ result = await this._remoteConfig.get();
+ } catch (ex) {
+ Cu.reportError(ex);
+ failed = true;
+ }
+ if (!result.length) {
+ Cu.reportError("Received empty top sites configuration!");
+ failed = true;
+ }
+ // If we failed, or the result is empty, try loading from the local dump.
+ if (firstTime && failed) {
+ await this._remoteConfig.db.clear();
+ // Now call this again.
+ return this._getRemoteConfig(false);
+ }
+
+ // Sort sites based on the "order" attribute.
+ result.sort((a, b) => a.order - b.order);
+
+ result = result.filter(topsite => {
+ // Filter by region.
+ if (topsite.exclude_regions?.includes(Region.home)) {
+ return false;
+ }
+ if (
+ topsite.include_regions?.length &&
+ !topsite.include_regions.includes(Region.home)
+ ) {
+ return false;
+ }
+
+ // Filter by locale.
+ if (topsite.exclude_locales?.includes(Services.locale.appLocaleAsBCP47)) {
+ return false;
+ }
+ if (
+ topsite.include_locales?.length &&
+ !topsite.include_locales.includes(Services.locale.appLocaleAsBCP47)
+ ) {
+ return false;
+ }
+
+ // Filter by experiment.
+ // Exclude this top site if any of the specified experiments are running.
+ if (
+ topsite.exclude_experiments?.some(experimentID =>
+ Services.prefs.getBoolPref(
+ DEFAULT_SITES_EXPERIMENTS_PREF_BRANCH + experimentID,
+ false
+ )
+ )
+ ) {
+ return false;
+ }
+ // Exclude this top site if none of the specified experiments are running.
+ if (
+ topsite.include_experiments?.length &&
+ topsite.include_experiments.every(
+ experimentID =>
+ !Services.prefs.getBoolPref(
+ DEFAULT_SITES_EXPERIMENTS_PREF_BRANCH + experimentID,
+ false
+ )
+ )
+ ) {
+ return false;
+ }
+
+ return true;
+ });
+
+ return result;
+ }
+
+ filterForThumbnailExpiration(callback) {
+ const { rows } = this.store.getState().TopSites;
+ callback(
+ rows.reduce((acc, site) => {
+ acc.push(site.url);
+ if (site.customScreenshotURL) {
+ acc.push(site.customScreenshotURL);
+ }
+ return acc;
+ }, [])
+ );
+ }
+
+ /**
+ * shouldFilterSearchTile - is default filtering enabled and does a given hostname match the user's default search engine?
+ *
+ * @param {string} hostname a top site hostname, such as "amazon" or "foo"
+ * @returns {bool}
+ */
+ shouldFilterSearchTile(hostname) {
+ if (
+ this.store.getState().Prefs.values[FILTER_DEFAULT_SEARCH_PREF] &&
+ (SEARCH_FILTERS.includes(hostname) ||
+ hostname === this._currentSearchHostname)
+ ) {
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * _maybeInsertSearchShortcuts - if the search shortcuts experiment is running,
+ * insert search shortcuts if needed
+ * @param {Array} plainPinnedSites (from the pinnedSitesCache)
+ * @returns {Boolean} Did we insert any search shortcuts?
+ */
+ async _maybeInsertSearchShortcuts(plainPinnedSites) {
+ // Only insert shortcuts if the experiment is running
+ if (this.store.getState().Prefs.values[SEARCH_SHORTCUTS_EXPERIMENT]) {
+ // We don't want to insert shortcuts we've previously inserted
+ const prevInsertedShortcuts = this.store
+ .getState()
+ .Prefs.values[SEARCH_SHORTCUTS_HAVE_PINNED_PREF].split(",")
+ .filter(s => s); // Filter out empty strings
+ const newInsertedShortcuts = [];
+
+ let shouldPin = this._useRemoteSetting
+ ? DEFAULT_TOP_SITES.filter(s => s.searchTopSite).map(s => s.hostname)
+ : this.store
+ .getState()
+ .Prefs.values[SEARCH_SHORTCUTS_SEARCH_ENGINES_PREF].split(",");
+ shouldPin = shouldPin
+ .map(getSearchProvider)
+ .filter(s => s && s.shortURL !== this._currentSearchHostname);
+
+ // If we've previously inserted all search shortcuts return early
+ if (
+ shouldPin.every(shortcut =>
+ prevInsertedShortcuts.includes(shortcut.shortURL)
+ )
+ ) {
+ return false;
+ }
+
+ const numberOfSlots =
+ this.store.getState().Prefs.values[ROWS_PREF] *
+ TOP_SITES_MAX_SITES_PER_ROW;
+
+ // The plainPinnedSites array is populated with pinned sites at their
+ // respective indices, and null everywhere else, but is not always the
+ // right length
+ const emptySlots = Math.max(numberOfSlots - plainPinnedSites.length, 0);
+ const pinnedSites = [...plainPinnedSites].concat(
+ Array(emptySlots).fill(null)
+ );
+
+ const tryToInsertSearchShortcut = async shortcut => {
+ const nextAvailable = pinnedSites.indexOf(null);
+ // Only add a search shortcut if the site isn't already pinned, we
+ // haven't previously inserted it, there's space to pin it, and the
+ // search engine is available in Firefox
+ if (
+ !pinnedSites.find(s => s && s.hostname === shortcut.shortURL) &&
+ !prevInsertedShortcuts.includes(shortcut.shortURL) &&
+ nextAvailable > -1 &&
+ (await checkHasSearchEngine(shortcut.keyword))
+ ) {
+ const site = await this.topSiteToSearchTopSite({ url: shortcut.url });
+ this._pinSiteAt(site, nextAvailable);
+ pinnedSites[nextAvailable] = site;
+ newInsertedShortcuts.push(shortcut.shortURL);
+ }
+ };
+
+ for (let shortcut of shouldPin) {
+ await tryToInsertSearchShortcut(shortcut);
+ }
+
+ if (newInsertedShortcuts.length) {
+ this.store.dispatch(
+ ac.SetPref(
+ SEARCH_SHORTCUTS_HAVE_PINNED_PREF,
+ prevInsertedShortcuts.concat(newInsertedShortcuts).join(",")
+ )
+ );
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ // eslint-disable-next-line max-statements
+ async getLinksWithDefaults(isStartup = false) {
+ const prefValues = this.store.getState().Prefs.values;
+ const numItems = prefValues[ROWS_PREF] * TOP_SITES_MAX_SITES_PER_ROW;
+ const searchShortcutsExperiment =
+ !this._useRemoteSetting && prefValues[SEARCH_SHORTCUTS_EXPERIMENT];
+ // We must wait for search services to initialize in order to access default
+ // search engine properties without triggering a synchronous initialization
+ await Services.search.init();
+
+ // Get all frecent sites from history.
+ let frecent = [];
+ const cache = await this.frecentCache.request({
+ // We need to overquery due to the top 5 alexa search + default search possibly being removed
+ numItems: numItems + SEARCH_FILTERS.length + 1,
+ topsiteFrecency: FRECENCY_THRESHOLD,
+ });
+ for (let link of cache) {
+ const hostname = shortURL(link);
+ if (!this.shouldFilterSearchTile(hostname)) {
+ frecent.push({
+ ...(searchShortcutsExperiment
+ ? await this.topSiteToSearchTopSite(link)
+ : link),
+ hostname,
+ });
+ }
+ }
+
+ // Get defaults.
+ let date = new Date();
+ let pad = number => number.toString().padStart(2, "0");
+ let yyyymmddhh =
+ String(date.getFullYear()) +
+ pad(date.getMonth() + 1) +
+ pad(date.getDate()) +
+ pad(date.getHours());
+ let notBlockedDefaultSites = [];
+ let sponsored = [];
+ for (let link of DEFAULT_TOP_SITES) {
+ if (this.shouldFilterSearchTile(link.hostname)) {
+ continue;
+ }
+ // Drop blocked default sites.
+ if (
+ NewTabUtils.blockedLinks.isBlocked({
+ url: link.url,
+ })
+ ) {
+ continue;
+ }
+ // Process %YYYYMMDDHH% tag in the URL.
+ let url_end;
+ let url_start;
+ if (this._useRemoteSetting) {
+ [url_start, url_end] = link.url.split("%YYYYMMDDHH%");
+ }
+ if (typeof url_end === "string") {
+ link = {
+ ...link,
+ // Save original URL without %YYYYMMDDHH% replaced so it can be
+ // blocked properly.
+ original_url: link.url,
+ url: url_start + yyyymmddhh + url_end,
+ };
+ if (link.url_urlbar) {
+ link.url_urlbar = link.url_urlbar.replace("%YYYYMMDDHH%", yyyymmddhh);
+ }
+ }
+ // If we've previously blocked a search shortcut, remove the default top site
+ // that matches the hostname
+ const searchProvider = getSearchProvider(shortURL(link));
+ if (
+ searchProvider &&
+ NewTabUtils.blockedLinks.isBlocked({ url: searchProvider.url })
+ ) {
+ continue;
+ }
+ if (link.sponsored_position) {
+ if (!prefValues[SHOW_SPONSORED_PREF]) {
+ continue;
+ }
+ sponsored[link.sponsored_position - 1] = link;
+ } else {
+ notBlockedDefaultSites.push(
+ searchShortcutsExperiment
+ ? await this.topSiteToSearchTopSite(link)
+ : link
+ );
+ }
+ }
+
+ // Get pinned links augmented with desired properties
+ let plainPinned = await this.pinnedCache.request();
+
+ // Insert search shortcuts if we need to.
+ // _maybeInsertSearchShortcuts returns true if any search shortcuts are
+ // inserted, meaning we need to expire and refresh the pinnedCache
+ if (await this._maybeInsertSearchShortcuts(plainPinned)) {
+ this.pinnedCache.expire();
+ plainPinned = await this.pinnedCache.request();
+ }
+
+ const pinned = await Promise.all(
+ plainPinned.map(async link => {
+ if (!link) {
+ return link;
+ }
+
+ // Copy all properties from a frecent link and add more
+ const finder = other => other.url === link.url;
+
+ // Remove frecent link's screenshot if pinned link has a custom one
+ const frecentSite = frecent.find(finder);
+ if (frecentSite && link.customScreenshotURL) {
+ delete frecentSite.screenshot;
+ }
+ // If the link is a frecent site, do not copy over 'isDefault', else check
+ // if the site is a default site
+ const copy = Object.assign(
+ {},
+ frecentSite || { isDefault: !!notBlockedDefaultSites.find(finder) },
+ link,
+ { hostname: shortURL(link) },
+ { searchTopSite: !!link.searchTopSite }
+ );
+
+ // Add in favicons if we don't already have it
+ if (!copy.favicon) {
+ try {
+ NewTabUtils.activityStreamProvider._faviconBytesToDataURI(
+ await NewTabUtils.activityStreamProvider._addFavicons([copy])
+ );
+
+ for (const prop of PINNED_FAVICON_PROPS_TO_MIGRATE) {
+ copy.__sharedCache.updateLink(prop, copy[prop]);
+ }
+ } catch (e) {
+ // Some issue with favicon, so just continue without one
+ }
+ }
+
+ return copy;
+ })
+ );
+
+ // Remove any duplicates from frecent and default sites
+ const [
+ ,
+ dedupedSponsored,
+ dedupedFrecent,
+ dedupedDefaults,
+ ] = this.dedupe.group(pinned, sponsored, frecent, notBlockedDefaultSites);
+ const dedupedUnpinned = [...dedupedFrecent, ...dedupedDefaults];
+
+ // Remove adult sites if we need to
+ const checkedAdult = prefValues.filterAdult
+ ? filterAdult(dedupedUnpinned)
+ : dedupedUnpinned;
+
+ // Insert the original pinned sites into the deduped frecent and defaults.
+ let withPinned = insertPinned(checkedAdult, pinned);
+ // Insert sponsored sites at their desired position.
+ dedupedSponsored.forEach(link => {
+ if (!link) {
+ return;
+ }
+ let index = link.sponsored_position - 1;
+ if (index > withPinned.length) {
+ withPinned[index] = link;
+ } else {
+ withPinned.splice(index, 0, link);
+ }
+ });
+ // Remove excess items after we inserted sponsored ones.
+ withPinned = withPinned.slice(0, numItems);
+
+ // Now, get a tippy top icon, a rich icon, or screenshot for every item
+ for (const link of withPinned) {
+ if (link) {
+ // If there is a custom screenshot this is the only image we display
+ if (link.customScreenshotURL) {
+ this._fetchScreenshot(link, link.customScreenshotURL, isStartup);
+ } else if (link.searchTopSite && !link.isDefault) {
+ await this._attachTippyTopIconForSearchShortcut(link, link.label);
+ } else {
+ this._fetchIcon(link, isStartup);
+ }
+
+ // Remove internal properties that might be updated after dispatch
+ delete link.__sharedCache;
+
+ // Indicate that these links should get a frecency bonus when clicked
+ link.typedBonus = true;
+ }
+ }
+
+ this._linksWithDefaults = withPinned;
+
+ return withPinned;
+ }
+
+ /**
+ * Attach TippyTop icon to the given search shortcut
+ *
+ * Note that it queries the search form URL from search service For Yandex,
+ * and uses it to choose the best icon for its shortcut variants.
+ *
+ * @param {Object} link A link object with a `url` property
+ * @param {string} keyword Search keyword
+ */
+ async _attachTippyTopIconForSearchShortcut(link, keyword) {
+ if (
+ ["@\u044F\u043D\u0434\u0435\u043A\u0441", "@yandex"].includes(keyword)
+ ) {
+ let site = { url: link.url };
+ site.url = (await getSearchFormURL(keyword)) || site.url;
+ this._tippyTopProvider.processSite(site);
+ link.tippyTopIcon = site.tippyTopIcon;
+ link.smallFavicon = site.smallFavicon;
+ link.backgroundColor = site.backgroundColor;
+ } else {
+ this._tippyTopProvider.processSite(link);
+ }
+ }
+
+ /**
+ * Refresh the top sites data for content.
+ * @param {bool} options.broadcast Should the update be broadcasted.
+ * @param {bool} options.isStartup Being called while TopSitesFeed is initting.
+ */
+ async refresh(options = {}) {
+ if (!this._startedUp && !options.isStartup) {
+ // Initial refresh still pending.
+ return;
+ }
+ this._startedUp = true;
+
+ if (!this._tippyTopProvider.initialized) {
+ await this._tippyTopProvider.init();
+ }
+
+ const links = await this.getLinksWithDefaults({
+ isStartup: options.isStartup,
+ });
+ const newAction = { type: at.TOP_SITES_UPDATED, data: { links } };
+ let storedPrefs;
+ try {
+ storedPrefs = (await this._storage.get(SECTION_ID)) || {};
+ } catch (e) {
+ storedPrefs = {};
+ Cu.reportError("Problem getting stored prefs for TopSites");
+ }
+ newAction.data.pref = getDefaultOptions(storedPrefs);
+
+ if (options.isStartup) {
+ newAction.meta = {
+ isStartup: true,
+ };
+ }
+
+ if (options.broadcast) {
+ // Broadcast an update to all open content pages
+ this.store.dispatch(ac.BroadcastToContent(newAction));
+ } else {
+ // Don't broadcast only update the state and update the preloaded tab.
+ this.store.dispatch(ac.AlsoToPreloaded(newAction));
+ }
+ }
+
+ async updateCustomSearchShortcuts(isStartup = false) {
+ if (!this.store.getState().Prefs.values[SEARCH_SHORTCUTS_EXPERIMENT]) {
+ return;
+ }
+
+ if (!this._tippyTopProvider.initialized) {
+ await this._tippyTopProvider.init();
+ }
+
+ // Populate the state with available search shortcuts
+ let searchShortcuts = [];
+ for (const engine of await Services.search.getAppProvidedEngines()) {
+ const shortcut = CUSTOM_SEARCH_SHORTCUTS.find(s =>
+ engine.aliases.includes(s.keyword)
+ );
+ if (shortcut) {
+ let clone = { ...shortcut };
+ await this._attachTippyTopIconForSearchShortcut(clone, clone.keyword);
+ searchShortcuts.push(clone);
+ }
+ }
+
+ this.store.dispatch(
+ ac.BroadcastToContent({
+ type: at.UPDATE_SEARCH_SHORTCUTS,
+ data: { searchShortcuts },
+ meta: {
+ isStartup,
+ },
+ })
+ );
+ }
+
+ async topSiteToSearchTopSite(site) {
+ const searchProvider = getSearchProvider(shortURL(site));
+ if (
+ !searchProvider ||
+ !(await checkHasSearchEngine(searchProvider.keyword))
+ ) {
+ return site;
+ }
+ return {
+ ...site,
+ searchTopSite: true,
+ label: searchProvider.keyword,
+ };
+ }
+
+ /**
+ * Get an image for the link preferring tippy top, rich favicon, screenshots.
+ */
+ async _fetchIcon(link, isStartup = false) {
+ // Nothing to do if we already have a rich icon from the page
+ if (link.favicon && link.faviconSize >= MIN_FAVICON_SIZE) {
+ return;
+ }
+
+ // Nothing more to do if we can use a default tippy top icon
+ this._tippyTopProvider.processSite(link);
+ if (link.tippyTopIcon) {
+ return;
+ }
+
+ // Make a request for a better icon
+ this._requestRichIcon(link.url);
+
+ // Also request a screenshot if we don't have one yet
+ await this._fetchScreenshot(link, link.url, isStartup);
+ }
+
+ /**
+ * Fetch, cache and broadcast a screenshot for a specific topsite.
+ * @param link cached topsite object
+ * @param url where to fetch the image from
+ * @param isStartup Whether the screenshot is fetched while initting TopSitesFeed.
+ */
+ async _fetchScreenshot(link, url, isStartup = false) {
+ // We shouldn't bother caching screenshots if they won't be shown.
+ if (
+ link.screenshot ||
+ !this.store.getState().Prefs.values[SHOWN_ON_NEWTAB_PREF]
+ ) {
+ return;
+ }
+ await Screenshots.maybeCacheScreenshot(
+ link,
+ url,
+ "screenshot",
+ screenshot =>
+ this.store.dispatch(
+ ac.BroadcastToContent({
+ data: { screenshot, url: link.url },
+ type: at.SCREENSHOT_UPDATED,
+ meta: {
+ isStartup,
+ },
+ })
+ )
+ );
+ }
+
+ /**
+ * Dispatch screenshot preview to target or notify if request failed.
+ * @param customScreenshotURL {string} The URL used to capture the screenshot
+ * @param target {string} Id of content process where to dispatch the result
+ */
+ async getScreenshotPreview(url, target) {
+ const preview = (await Screenshots.getScreenshotForURL(url)) || "";
+ this.store.dispatch(
+ ac.OnlyToOneContent(
+ {
+ data: { url, preview },
+ type: at.PREVIEW_RESPONSE,
+ },
+ target
+ )
+ );
+ }
+
+ _requestRichIcon(url) {
+ this.store.dispatch({
+ type: at.RICH_ICON_MISSING,
+ data: { url },
+ });
+ }
+
+ updateSectionPrefs(collapsed) {
+ this.store.dispatch(
+ ac.BroadcastToContent({
+ type: at.TOP_SITES_PREFS_UPDATED,
+ data: { pref: collapsed },
+ })
+ );
+ }
+
+ /**
+ * Inform others that top sites data has been updated due to pinned changes.
+ */
+ _broadcastPinnedSitesUpdated() {
+ // Pinned data changed, so make sure we get latest
+ this.pinnedCache.expire();
+
+ // Refresh to update pinned sites with screenshots, trigger deduping, etc.
+ this.refresh({ broadcast: true });
+ }
+
+ /**
+ * Pin a site at a specific position saving only the desired keys.
+ * @param customScreenshotURL {string} User set URL of preview image for site
+ * @param label {string} User set string of custom site name
+ */
+ async _pinSiteAt({ customScreenshotURL, label, url, searchTopSite }, index) {
+ const toPin = { url };
+ if (label) {
+ toPin.label = label;
+ }
+ if (customScreenshotURL) {
+ toPin.customScreenshotURL = customScreenshotURL;
+ }
+ if (searchTopSite) {
+ toPin.searchTopSite = searchTopSite;
+ }
+ NewTabUtils.pinnedLinks.pin(toPin, index);
+
+ await this._clearLinkCustomScreenshot({ customScreenshotURL, url });
+ }
+
+ async _clearLinkCustomScreenshot(site) {
+ // If screenshot url changed or was removed we need to update the cached link obj
+ if (site.customScreenshotURL !== undefined) {
+ const pinned = await this.pinnedCache.request();
+ const link = pinned.find(pin => pin && pin.url === site.url);
+ if (link && link.customScreenshotURL !== site.customScreenshotURL) {
+ link.__sharedCache.updateLink("screenshot", undefined);
+ }
+ }
+ }
+
+ /**
+ * Handle a pin action of a site to a position.
+ */
+ async pin(action) {
+ let { site, index } = action.data;
+ index = this._adjustPinIndexForSponsoredLinks(site, index);
+ // If valid index provided, pin at that position
+ if (index >= 0) {
+ await this._pinSiteAt(site, index);
+ this._broadcastPinnedSitesUpdated();
+ } else {
+ // Bug 1458658. If the top site is being pinned from an 'Add a Top Site' option,
+ // then we want to make sure to unblock that link if it has previously been
+ // blocked. We know if the site has been added because the index will be -1.
+ if (index === -1) {
+ NewTabUtils.blockedLinks.unblock({ url: site.url });
+ this.frecentCache.expire();
+ }
+ this.insert(action);
+ }
+ }
+
+ /**
+ * Handle an unpin action of a site.
+ */
+ unpin(action) {
+ const { site } = action.data;
+ NewTabUtils.pinnedLinks.unpin(site);
+ this._broadcastPinnedSitesUpdated();
+ }
+
+ unpinAllSearchShortcuts() {
+ Services.prefs.clearUserPref(
+ `browser.newtabpage.activity-stream.${SEARCH_SHORTCUTS_HAVE_PINNED_PREF}`
+ );
+ for (let pinnedLink of NewTabUtils.pinnedLinks.links) {
+ if (pinnedLink && pinnedLink.searchTopSite) {
+ NewTabUtils.pinnedLinks.unpin(pinnedLink);
+ }
+ }
+ this.pinnedCache.expire();
+ }
+
+ /**
+ * Reduces the given pinning index by the number of preceding sponsored
+ * sites, to accomodate for sponsored sites pushing pinned ones to the side,
+ * effectively increasing their index again.
+ */
+ _adjustPinIndexForSponsoredLinks(site, index) {
+ if (!this._linksWithDefaults) {
+ return index;
+ }
+ // Adjust insertion index for sponsored sites since their position is
+ // fixed.
+ let adjustedIndex = index;
+ for (let i = 0; i < index; i++) {
+ if (
+ this._linksWithDefaults[i]?.sponsored_position &&
+ this._linksWithDefaults[i]?.url !== site.url
+ ) {
+ adjustedIndex--;
+ }
+ }
+ return adjustedIndex;
+ }
+
+ /**
+ * Insert a site to pin at a position shifting over any other pinned sites.
+ */
+ _insertPin(site, originalIndex, draggedFromIndex) {
+ let index = this._adjustPinIndexForSponsoredLinks(site, originalIndex);
+
+ // Don't insert any pins past the end of the visible top sites. Otherwise,
+ // we can end up with a bunch of pinned sites that can never be unpinned again
+ // from the UI.
+ const topSitesCount =
+ this.store.getState().Prefs.values[ROWS_PREF] *
+ TOP_SITES_MAX_SITES_PER_ROW;
+ if (index >= topSitesCount) {
+ return;
+ }
+
+ let pinned = NewTabUtils.pinnedLinks.links;
+ if (!pinned[index]) {
+ this._pinSiteAt(site, index);
+ } else {
+ pinned[draggedFromIndex] = null;
+ // Find the hole to shift the pinned site(s) towards. We shift towards the
+ // hole left by the site being dragged.
+ let holeIndex = index;
+ const indexStep = index > draggedFromIndex ? -1 : 1;
+ while (pinned[holeIndex]) {
+ holeIndex += indexStep;
+ }
+ if (holeIndex >= topSitesCount || holeIndex < 0) {
+ // There are no holes, so we will effectively unpin the last slot and shifting
+ // towards it. This only happens when adding a new top site to an already
+ // fully pinned grid.
+ holeIndex = topSitesCount - 1;
+ }
+
+ // Shift towards the hole.
+ const shiftingStep = holeIndex > index ? -1 : 1;
+ while (holeIndex !== index) {
+ const nextIndex = holeIndex + shiftingStep;
+ this._pinSiteAt(pinned[nextIndex], holeIndex);
+ holeIndex = nextIndex;
+ }
+ this._pinSiteAt(site, index);
+ }
+ }
+
+ /**
+ * Handle an insert (drop/add) action of a site.
+ */
+ async insert(action) {
+ let { index } = action.data;
+ // Treat invalid pin index values (e.g., -1, undefined) as insert in the first position
+ if (!(index > 0)) {
+ index = 0;
+ }
+
+ // Inserting a top site pins it in the specified slot, pushing over any link already
+ // pinned in the slot (unless it's the last slot, then it replaces).
+ this._insertPin(
+ action.data.site,
+ index,
+ action.data.draggedFromIndex !== undefined
+ ? action.data.draggedFromIndex
+ : this.store.getState().Prefs.values[ROWS_PREF] *
+ TOP_SITES_MAX_SITES_PER_ROW
+ );
+
+ await this._clearLinkCustomScreenshot(action.data.site);
+ this._broadcastPinnedSitesUpdated();
+ }
+
+ updatePinnedSearchShortcuts({ addedShortcuts, deletedShortcuts }) {
+ // Unpin the deletedShortcuts.
+ deletedShortcuts.forEach(({ url }) => {
+ NewTabUtils.pinnedLinks.unpin({ url });
+ });
+
+ // Pin the addedShortcuts.
+ const numberOfSlots =
+ this.store.getState().Prefs.values[ROWS_PREF] *
+ TOP_SITES_MAX_SITES_PER_ROW;
+ addedShortcuts.forEach(shortcut => {
+ // Find first hole in pinnedLinks.
+ let index = NewTabUtils.pinnedLinks.links.findIndex(link => !link);
+ if (
+ index < 0 &&
+ NewTabUtils.pinnedLinks.links.length + 1 < numberOfSlots
+ ) {
+ // pinnedLinks can have less slots than the total available.
+ index = NewTabUtils.pinnedLinks.links.length;
+ }
+ if (index >= 0) {
+ NewTabUtils.pinnedLinks.pin(shortcut, index);
+ } else {
+ // No slots available, we need to do an insert in first slot and push over other pinned links.
+ this._insertPin(shortcut, 0, numberOfSlots);
+ }
+ });
+
+ this._broadcastPinnedSitesUpdated();
+ }
+
+ onAction(action) {
+ switch (action.type) {
+ case at.INIT:
+ this.init();
+ this.updateCustomSearchShortcuts(true /* isStartup */);
+ break;
+ case at.SYSTEM_TICK:
+ this.refresh({ broadcast: false });
+ break;
+ // All these actions mean we need new top sites
+ case at.PLACES_HISTORY_CLEARED:
+ case at.PLACES_LINK_DELETED:
+ this.frecentCache.expire();
+ this.refresh({ broadcast: true });
+ break;
+ case at.PLACES_LINKS_CHANGED:
+ this.frecentCache.expire();
+ this.refresh({ broadcast: false });
+ break;
+ case at.PLACES_LINK_BLOCKED:
+ this.frecentCache.expire();
+ this.pinnedCache.expire();
+ this.refresh({ broadcast: true });
+ break;
+ case at.PREF_CHANGED:
+ switch (action.data.name) {
+ case DEFAULT_SITES_PREF:
+ if (!this._useRemoteSetting) {
+ this.refreshDefaults(action.data.value);
+ }
+ break;
+ case ROWS_PREF:
+ case FILTER_DEFAULT_SEARCH_PREF:
+ case SEARCH_SHORTCUTS_SEARCH_ENGINES_PREF:
+ case SHOW_SPONSORED_PREF:
+ this.refresh({ broadcast: true });
+ break;
+ case SEARCH_SHORTCUTS_EXPERIMENT:
+ if (action.data.value) {
+ this.updateCustomSearchShortcuts();
+ } else {
+ this.unpinAllSearchShortcuts();
+ }
+ this.refresh({ broadcast: true });
+ }
+ break;
+ case at.UPDATE_SECTION_PREFS:
+ if (action.data.id === SECTION_ID) {
+ this.updateSectionPrefs(action.data.value);
+ }
+ break;
+ case at.PREFS_INITIAL_VALUES:
+ if (!this._useRemoteSetting) {
+ this.refreshDefaults(action.data[DEFAULT_SITES_PREF]);
+ }
+ break;
+ case at.TOP_SITES_PIN:
+ this.pin(action);
+ break;
+ case at.TOP_SITES_UNPIN:
+ this.unpin(action);
+ break;
+ case at.TOP_SITES_INSERT:
+ this.insert(action);
+ break;
+ case at.PREVIEW_REQUEST:
+ this.getScreenshotPreview(action.data.url, action.meta.fromTarget);
+ break;
+ case at.UPDATE_PINNED_SEARCH_SHORTCUTS:
+ this.updatePinnedSearchShortcuts(action.data);
+ break;
+ case at.UNINIT:
+ this.uninit();
+ break;
+ }
+ }
+};
+
+this.DEFAULT_TOP_SITES = DEFAULT_TOP_SITES;
+const EXPORTED_SYMBOLS = ["TopSitesFeed", "DEFAULT_TOP_SITES"];
diff --git a/browser/components/newtab/lib/TopStoriesFeed.jsm b/browser/components/newtab/lib/TopStoriesFeed.jsm
new file mode 100644
index 0000000000..874944bb0e
--- /dev/null
+++ b/browser/components/newtab/lib/TopStoriesFeed.jsm
@@ -0,0 +1,929 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
+const { XPCOMUtils } = ChromeUtils.import(
+ "resource://gre/modules/XPCOMUtils.jsm"
+);
+const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
+const { NewTabUtils } = ChromeUtils.import(
+ "resource://gre/modules/NewTabUtils.jsm"
+);
+XPCOMUtils.defineLazyGlobalGetters(this, ["fetch"]);
+
+const { actionTypes: at, actionCreators: ac } = ChromeUtils.import(
+ "resource://activity-stream/common/Actions.jsm"
+);
+const { Prefs } = ChromeUtils.import(
+ "resource://activity-stream/lib/ActivityStreamPrefs.jsm"
+);
+const { shortURL } = ChromeUtils.import(
+ "resource://activity-stream/lib/ShortURL.jsm"
+);
+const { SectionsManager } = ChromeUtils.import(
+ "resource://activity-stream/lib/SectionsManager.jsm"
+);
+const { UserDomainAffinityProvider } = ChromeUtils.import(
+ "resource://activity-stream/lib/UserDomainAffinityProvider.jsm"
+);
+const { PersonalityProvider } = ChromeUtils.import(
+ "resource://activity-stream/lib/PersonalityProvider/PersonalityProvider.jsm"
+);
+const { PersistentCache } = ChromeUtils.import(
+ "resource://activity-stream/lib/PersistentCache.jsm"
+);
+
+ChromeUtils.defineModuleGetter(
+ this,
+ "pktApi",
+ "chrome://pocket/content/pktApi.jsm"
+);
+
+const STORIES_UPDATE_TIME = 30 * 60 * 1000; // 30 minutes
+const TOPICS_UPDATE_TIME = 3 * 60 * 60 * 1000; // 3 hours
+const STORIES_NOW_THRESHOLD = 24 * 60 * 60 * 1000; // 24 hours
+const MIN_DOMAIN_AFFINITIES_UPDATE_TIME = 12 * 60 * 60 * 1000; // 12 hours
+const DEFAULT_RECS_EXPIRE_TIME = 60 * 60 * 1000; // 1 hour
+const SECTION_ID = "topstories";
+const IMPRESSION_SOURCE = "TOP_STORIES";
+const SPOC_IMPRESSION_TRACKING_PREF =
+ "feeds.section.topstories.spoc.impressions";
+const DISCOVERY_STREAM_PREF_ENABLED = "discoverystream.enabled";
+const DISCOVERY_STREAM_PREF_ENABLED_PATH =
+ "browser.newtabpage.activity-stream.discoverystream.enabled";
+const REC_IMPRESSION_TRACKING_PREF = "feeds.section.topstories.rec.impressions";
+const OPTIONS_PREF = "feeds.section.topstories.options";
+const PREF_USER_TOPSTORIES = "feeds.section.topstories";
+const MAX_LIFETIME_CAP = 500; // Guard against misconfiguration on the server
+const DISCOVERY_STREAM_PREF = "discoverystream.config";
+
+this.TopStoriesFeed = class TopStoriesFeed {
+ constructor(ds) {
+ // Use discoverystream config pref default values for fast path and
+ // if needed lazy load activity stream top stories feed based on
+ // actual user preference when INIT and PREF_CHANGED is invoked
+ this.discoveryStreamEnabled =
+ ds &&
+ ds.value &&
+ JSON.parse(ds.value).enabled &&
+ Services.prefs.getBoolPref(DISCOVERY_STREAM_PREF_ENABLED_PATH, false);
+ if (!this.discoveryStreamEnabled) {
+ this.initializeProperties();
+ }
+ }
+
+ initializeProperties() {
+ this.contentUpdateQueue = [];
+ this.spocCampaignMap = new Map();
+ this.cache = new PersistentCache(SECTION_ID, true);
+ this._prefs = new Prefs();
+ this.propertiesInitialized = true;
+ }
+
+ async onInit() {
+ SectionsManager.enableSection(SECTION_ID, true /* isStartup */);
+ if (this.discoveryStreamEnabled) {
+ return;
+ }
+
+ try {
+ const { options } = SectionsManager.sections.get(SECTION_ID);
+ const apiKey = this.getApiKeyFromPref(options.api_key_pref);
+ this.stories_endpoint = this.produceFinalEndpointUrl(
+ options.stories_endpoint,
+ apiKey
+ );
+ this.topics_endpoint = this.produceFinalEndpointUrl(
+ options.topics_endpoint,
+ apiKey
+ );
+ this.read_more_endpoint = options.read_more_endpoint;
+ this.stories_referrer = options.stories_referrer;
+ this.personalized = options.personalized;
+ this.show_spocs = options.show_spocs;
+ this.maxHistoryQueryResults = options.maxHistoryQueryResults;
+ this.storiesLastUpdated = 0;
+ this.topicsLastUpdated = 0;
+ this.storiesLoaded = false;
+ this.domainAffinitiesLastUpdated = 0;
+ this.processAffinityProividerVersion(options);
+ this.dispatchPocketCta(this._prefs.get("pocketCta"), false);
+ Services.obs.addObserver(this, "idle-daily");
+
+ // Cache is used for new page loads, which shouldn't have changed data.
+ // If we have changed data, cache should be cleared,
+ // and last updated should be 0, and we can fetch.
+ let { stories, topics } = await this.loadCachedData();
+ if (this.storiesLastUpdated === 0) {
+ stories = await this.fetchStories();
+ }
+ if (this.topicsLastUpdated === 0) {
+ topics = await this.fetchTopics();
+ }
+ this.doContentUpdate({ stories, topics }, true);
+ this.storiesLoaded = true;
+
+ // This is filtered so an update function can return true to retry on the next run
+ this.contentUpdateQueue = this.contentUpdateQueue.filter(update =>
+ update()
+ );
+ } catch (e) {
+ Cu.reportError(`Problem initializing top stories feed: ${e.message}`);
+ }
+ }
+
+ init() {
+ SectionsManager.onceInitialized(this.onInit.bind(this));
+ }
+
+ observe(subject, topic, data) {
+ switch (topic) {
+ case "idle-daily":
+ this.updateDomainAffinityScores();
+ break;
+ }
+ }
+
+ async clearCache() {
+ await this.cache.set("stories", {});
+ await this.cache.set("topics", {});
+ await this.cache.set("spocs", {});
+ }
+
+ uninit() {
+ this.storiesLoaded = false;
+ try {
+ Services.obs.removeObserver(this, "idle-daily");
+ } catch (e) {
+ // Attempt to remove unassociated observer which is possible when discovery stream
+ // is enabled and user never used activity stream experience
+ }
+ SectionsManager.disableSection(SECTION_ID);
+ }
+
+ getPocketState(target) {
+ const action = { type: at.POCKET_LOGGED_IN, data: pktApi.isUserLoggedIn() };
+ this.store.dispatch(ac.OnlyToOneContent(action, target));
+ }
+
+ dispatchPocketCta(data, shouldBroadcast) {
+ const action = { type: at.POCKET_CTA, data: JSON.parse(data) };
+ this.store.dispatch(
+ shouldBroadcast
+ ? ac.BroadcastToContent(action)
+ : ac.AlsoToPreloaded(action)
+ );
+ }
+
+ /**
+ * doContentUpdate - Updates topics and stories in the topstories section.
+ *
+ * Sections have one update action for the whole section.
+ * Redux creates a state race condition if you call the same action,
+ * twice, concurrently. Because of this, doContentUpdate is
+ * one place to update both topics and stories in a single action.
+ *
+ * Section updates used old topics if none are available,
+ * but clear stories if none are available. Because of this, if no
+ * stories are passed, we instead use the existing stories in state.
+ *
+ * @param {Object} This is an object with potential new stories or topics.
+ * @param {Boolean} shouldBroadcast If we should update existing tabs or not. For first page
+ * loads or pref changes, we want to update existing tabs,
+ * for system tick or other updates we do not.
+ */
+ doContentUpdate({ stories, topics }, shouldBroadcast) {
+ let updateProps = {};
+ if (stories) {
+ updateProps.rows = stories;
+ } else {
+ const { Sections } = this.store.getState();
+ if (Sections && Sections.find) {
+ updateProps.rows = Sections.find(s => s.id === SECTION_ID).rows;
+ }
+ }
+ if (topics) {
+ Object.assign(updateProps, {
+ topics,
+ read_more_endpoint: this.read_more_endpoint,
+ });
+ }
+
+ // We should only be calling this once per init.
+ this.dispatchUpdateEvent(shouldBroadcast, updateProps);
+ }
+
+ async onPersonalityProviderInit() {
+ const data = await this.cache.get();
+ let stories = data.stories && data.stories.recommendations;
+ this.stories = this.rotate(this.transform(stories));
+ this.doContentUpdate({ stories: this.stories }, false);
+
+ const affinities = this.affinityProvider.getAffinities();
+ this.domainAffinitiesLastUpdated = Date.now();
+ affinities._timestamp = this.domainAffinitiesLastUpdated;
+ this.cache.set("domainAffinities", affinities);
+ }
+
+ affinityProividerSwitcher(...args) {
+ const { affinityProviderV2 } = this;
+ if (affinityProviderV2 && affinityProviderV2.use_v2) {
+ const provider = this.PersonalityProvider(...args, {
+ modelKeys: affinityProviderV2.model_keys,
+ dispatch: this.store.dispatch,
+ });
+ provider.init(this.onPersonalityProviderInit.bind(this));
+ return provider;
+ }
+
+ const v1Provider = this.UserDomainAffinityProvider(...args);
+
+ return v1Provider;
+ }
+
+ PersonalityProvider(...args) {
+ return new PersonalityProvider(...args);
+ }
+
+ UserDomainAffinityProvider(...args) {
+ return new UserDomainAffinityProvider(...args);
+ }
+
+ async fetchStories() {
+ if (!this.stories_endpoint) {
+ return null;
+ }
+ try {
+ const response = await fetch(this.stories_endpoint, {
+ credentials: "omit",
+ });
+ if (!response.ok) {
+ throw new Error(
+ `Stories endpoint returned unexpected status: ${response.status}`
+ );
+ }
+
+ const body = await response.json();
+ this.updateSettings(body.settings);
+ this.stories = this.rotate(this.transform(body.recommendations));
+ this.cleanUpTopRecImpressionPref();
+
+ if (this.show_spocs && body.spocs) {
+ this.spocCampaignMap = new Map(
+ body.spocs.map(s => [s.id, `${s.campaign_id}`])
+ );
+ this.spocs = this.transform(body.spocs).filter(
+ s => s.score >= s.min_score
+ );
+ this.cleanUpCampaignImpressionPref();
+ }
+ this.storiesLastUpdated = Date.now();
+ body._timestamp = this.storiesLastUpdated;
+ this.cache.set("stories", body);
+ } catch (error) {
+ Cu.reportError(`Failed to fetch content: ${error.message}`);
+ }
+ return this.stories;
+ }
+
+ async loadCachedData() {
+ const data = await this.cache.get();
+ let stories = data.stories && data.stories.recommendations;
+ let topics = data.topics && data.topics.topics;
+
+ let affinities = data.domainAffinities;
+ if (this.personalized && affinities && affinities.scores) {
+ this.affinityProvider = this.affinityProividerSwitcher(
+ affinities.timeSegments,
+ affinities.parameterSets,
+ affinities.maxHistoryQueryResults,
+ affinities.version,
+ affinities.scores
+ );
+ this.domainAffinitiesLastUpdated = affinities._timestamp;
+ }
+ if (stories && !!stories.length && this.storiesLastUpdated === 0) {
+ this.updateSettings(data.stories.settings);
+ this.stories = this.rotate(this.transform(stories));
+ this.storiesLastUpdated = data.stories._timestamp;
+ if (data.stories.spocs && data.stories.spocs.length) {
+ this.spocCampaignMap = new Map(
+ data.stories.spocs.map(s => [s.id, `${s.campaign_id}`])
+ );
+ this.spocs = this.transform(data.stories.spocs).filter(
+ s => s.score >= s.min_score
+ );
+ this.cleanUpCampaignImpressionPref();
+ }
+ }
+ if (topics && !!topics.length && this.topicsLastUpdated === 0) {
+ this.topics = topics;
+ this.topicsLastUpdated = data.topics._timestamp;
+ }
+
+ return { topics: this.topics, stories: this.stories };
+ }
+
+ transform(items) {
+ if (!items) {
+ return [];
+ }
+
+ const calcResult = items
+ .filter(s => !NewTabUtils.blockedLinks.isBlocked({ url: s.url }))
+ .map(s => {
+ let mapped = {
+ guid: s.id,
+ hostname: s.domain || shortURL(Object.assign({}, s, { url: s.url })),
+ type:
+ Date.now() - s.published_timestamp * 1000 <= STORIES_NOW_THRESHOLD
+ ? "now"
+ : "trending",
+ context: s.context,
+ icon: s.icon,
+ title: s.title,
+ description: s.excerpt,
+ image: this.normalizeUrl(s.image_src),
+ referrer: this.stories_referrer,
+ url: s.url,
+ min_score: s.min_score || 0,
+ score:
+ this.personalized && this.affinityProvider
+ ? this.affinityProvider.calculateItemRelevanceScore(s)
+ : s.item_score || 1,
+ spoc_meta: this.show_spocs
+ ? { campaign_id: s.campaign_id, caps: s.caps }
+ : {},
+ };
+
+ // Very old cached spocs may not contain an `expiration_timestamp` property
+ if (s.expiration_timestamp) {
+ mapped.expiration_timestamp = s.expiration_timestamp;
+ }
+
+ return mapped;
+ })
+ .sort(this.personalized ? this.compareScore : (a, b) => 0);
+
+ return calcResult;
+ }
+
+ async fetchTopics() {
+ if (!this.topics_endpoint) {
+ return null;
+ }
+ try {
+ const response = await fetch(this.topics_endpoint, {
+ credentials: "omit",
+ });
+ if (!response.ok) {
+ throw new Error(
+ `Topics endpoint returned unexpected status: ${response.status}`
+ );
+ }
+ const body = await response.json();
+ const { topics } = body;
+ if (topics) {
+ this.topics = topics;
+ this.topicsLastUpdated = Date.now();
+ body._timestamp = this.topicsLastUpdated;
+ this.cache.set("topics", body);
+ }
+ } catch (error) {
+ Cu.reportError(`Failed to fetch topics: ${error.message}`);
+ }
+ return this.topics;
+ }
+
+ dispatchUpdateEvent(shouldBroadcast, data) {
+ SectionsManager.updateSection(SECTION_ID, data, shouldBroadcast);
+ }
+
+ compareScore(a, b) {
+ return b.score - a.score;
+ }
+
+ updateSettings(settings) {
+ if (!this.personalized) {
+ return;
+ }
+
+ this.spocsPerNewTabs = settings.spocsPerNewTabs; // Probability of a new tab getting a spoc [0,1]
+ this.timeSegments = settings.timeSegments;
+ this.domainAffinityParameterSets = settings.domainAffinityParameterSets;
+ this.recsExpireTime = settings.recsExpireTime;
+ this.version = settings.version;
+
+ if (
+ this.affinityProvider &&
+ this.affinityProvider.version !== this.version
+ ) {
+ this.resetDomainAffinityScores();
+ }
+ }
+
+ updateDomainAffinityScores() {
+ if (
+ !this.personalized ||
+ !this.domainAffinityParameterSets ||
+ Date.now() - this.domainAffinitiesLastUpdated <
+ MIN_DOMAIN_AFFINITIES_UPDATE_TIME
+ ) {
+ return;
+ }
+
+ this.affinityProvider = this.affinityProividerSwitcher(
+ this.timeSegments,
+ this.domainAffinityParameterSets,
+ this.maxHistoryQueryResults,
+ this.version,
+ undefined
+ );
+
+ const affinities = this.affinityProvider.getAffinities();
+ this.domainAffinitiesLastUpdated = Date.now();
+ affinities._timestamp = this.domainAffinitiesLastUpdated;
+ this.cache.set("domainAffinities", affinities);
+ }
+
+ resetDomainAffinityScores() {
+ delete this.affinityProvider;
+ this.cache.set("domainAffinities", {});
+ }
+
+ // If personalization is turned on, we have to rotate stories on the client so that
+ // active stories are at the front of the list, followed by stories that have expired
+ // impressions i.e. have been displayed for longer than recsExpireTime.
+ rotate(items) {
+ if (!this.personalized || items.length <= 3) {
+ return items;
+ }
+
+ const maxImpressionAge = Math.max(
+ this.recsExpireTime * 1000 || DEFAULT_RECS_EXPIRE_TIME,
+ DEFAULT_RECS_EXPIRE_TIME
+ );
+ const impressions = this.readImpressionsPref(REC_IMPRESSION_TRACKING_PREF);
+ const expired = [];
+ const active = [];
+ for (const item of items) {
+ if (
+ impressions[item.guid] &&
+ Date.now() - impressions[item.guid] >= maxImpressionAge
+ ) {
+ expired.push(item);
+ } else {
+ active.push(item);
+ }
+ }
+ return active.concat(expired);
+ }
+
+ getApiKeyFromPref(apiKeyPref) {
+ if (!apiKeyPref) {
+ return apiKeyPref;
+ }
+
+ return (
+ this._prefs.get(apiKeyPref) || Services.prefs.getCharPref(apiKeyPref)
+ );
+ }
+
+ produceFinalEndpointUrl(url, apiKey) {
+ if (!url) {
+ return url;
+ }
+ if (url.includes("$apiKey") && !apiKey) {
+ throw new Error(`An API key was specified but none configured: ${url}`);
+ }
+ return url.replace("$apiKey", apiKey);
+ }
+
+ // Need to remove parenthesis from image URLs as React will otherwise
+ // fail to render them properly as part of the card template.
+ normalizeUrl(url) {
+ if (url) {
+ return url.replace(/\(/g, "%28").replace(/\)/g, "%29");
+ }
+ return url;
+ }
+
+ shouldShowSpocs() {
+ return this.show_spocs && this.store.getState().Prefs.values.showSponsored;
+ }
+
+ dispatchSpocDone(target) {
+ const action = { type: at.POCKET_WAITING_FOR_SPOC, data: false };
+ this.store.dispatch(ac.OnlyToOneContent(action, target));
+ }
+
+ filterSpocs() {
+ if (!this.shouldShowSpocs()) {
+ return [];
+ }
+
+ if (Math.random() > this.spocsPerNewTabs) {
+ return [];
+ }
+
+ if (!this.spocs || !this.spocs.length) {
+ // We have stories but no spocs so there's nothing to do and this update can be
+ // removed from the queue.
+ return [];
+ }
+
+ // Filter spocs based on frequency caps
+ const impressions = this.readImpressionsPref(SPOC_IMPRESSION_TRACKING_PREF);
+ let spocs = this.spocs.filter(s =>
+ this.isBelowFrequencyCap(impressions, s)
+ );
+
+ // Filter out expired spocs based on `expiration_timestamp`
+ spocs = spocs.filter(spoc => {
+ // If cached data is so old it doesn't contain this property, assume the spoc is ok to show
+ if (!(`expiration_timestamp` in spoc)) {
+ return true;
+ }
+ // `expiration_timestamp` is the number of seconds elapsed since January 1, 1970 00:00:00 UTC
+ return spoc.expiration_timestamp * 1000 > Date.now();
+ });
+
+ return spocs;
+ }
+
+ maybeAddSpoc(target) {
+ const updateContent = () => {
+ let spocs = this.filterSpocs();
+
+ if (!spocs.length) {
+ this.dispatchSpocDone(target);
+ return false;
+ }
+
+ // Create a new array with a spoc inserted at index 2
+ const section = this.store
+ .getState()
+ .Sections.find(s => s.id === SECTION_ID);
+ let rows = section.rows.slice(0, this.stories.length);
+ rows.splice(2, 0, Object.assign(spocs[0], { pinned: true }));
+
+ // Send a content update to the target tab
+ const action = {
+ type: at.SECTION_UPDATE,
+ data: Object.assign({ rows }, { id: SECTION_ID }),
+ };
+ this.store.dispatch(ac.OnlyToOneContent(action, target));
+ this.dispatchSpocDone(target);
+ return false;
+ };
+
+ if (this.storiesLoaded) {
+ updateContent();
+ } else {
+ // Delay updating tab content until initial data has been fetched
+ this.contentUpdateQueue.push(updateContent);
+ }
+ }
+
+ // Frequency caps are based on campaigns, which may include multiple spocs.
+ // We currently support two types of frequency caps:
+ // - lifetime: Indicates how many times spocs from a campaign can be shown in total
+ // - period: Indicates how many times spocs from a campaign can be shown within a period
+ //
+ // So, for example, the feed configuration below defines that for campaign 1 no more
+ // than 5 spocs can be show in total, and no more than 2 per hour.
+ // "campaign_id": 1,
+ // "caps": {
+ // "lifetime": 5,
+ // "campaign": {
+ // "count": 2,
+ // "period": 3600
+ // }
+ // }
+ isBelowFrequencyCap(impressions, spoc) {
+ const campaignImpressions = impressions[spoc.spoc_meta.campaign_id];
+ if (!campaignImpressions) {
+ return true;
+ }
+
+ const lifeTimeCap = Math.min(
+ spoc.spoc_meta.caps && spoc.spoc_meta.caps.lifetime,
+ MAX_LIFETIME_CAP
+ );
+ const lifeTimeCapExceeded = campaignImpressions.length >= lifeTimeCap;
+ if (lifeTimeCapExceeded) {
+ return false;
+ }
+
+ const campaignCap =
+ (spoc.spoc_meta.caps && spoc.spoc_meta.caps.campaign) || {};
+ const campaignCapExceeded =
+ campaignImpressions.filter(
+ i => Date.now() - i < campaignCap.period * 1000
+ ).length >= campaignCap.count;
+ return !campaignCapExceeded;
+ }
+
+ // Clean up campaign impression pref by removing all campaigns that are no
+ // longer part of the response, and are therefore considered inactive.
+ cleanUpCampaignImpressionPref() {
+ const campaignIds = new Set(this.spocCampaignMap.values());
+ this.cleanUpImpressionPref(
+ id => !campaignIds.has(id),
+ SPOC_IMPRESSION_TRACKING_PREF
+ );
+ }
+
+ // Clean up rec impression pref by removing all stories that are no
+ // longer part of the response.
+ cleanUpTopRecImpressionPref() {
+ const activeStories = new Set(this.stories.map(s => `${s.guid}`));
+ this.cleanUpImpressionPref(
+ id => !activeStories.has(id),
+ REC_IMPRESSION_TRACKING_PREF
+ );
+ }
+
+ /**
+ * Cleans up the provided impression pref (spocs or recs).
+ *
+ * @param isExpired predicate (boolean-valued function) that returns whether or not
+ * the impression for the given key is expired.
+ * @param pref the impression pref to clean up.
+ */
+ cleanUpImpressionPref(isExpired, pref) {
+ const impressions = this.readImpressionsPref(pref);
+ let changed = false;
+
+ Object.keys(impressions).forEach(id => {
+ if (isExpired(id)) {
+ changed = true;
+ delete impressions[id];
+ }
+ });
+
+ if (changed) {
+ this.writeImpressionsPref(pref, impressions);
+ }
+ }
+
+ // Sets a pref mapping campaign IDs to timestamp arrays.
+ // The timestamps represent impressions which are used to calculate frequency caps.
+ recordCampaignImpression(campaignId) {
+ let impressions = this.readImpressionsPref(SPOC_IMPRESSION_TRACKING_PREF);
+
+ const timeStamps = impressions[campaignId] || [];
+ timeStamps.push(Date.now());
+ impressions = Object.assign(impressions, { [campaignId]: timeStamps });
+
+ this.writeImpressionsPref(SPOC_IMPRESSION_TRACKING_PREF, impressions);
+ }
+
+ // Sets a pref mapping story (rec) IDs to a single timestamp (time of first impression).
+ // We use these timestamps to guarantee a story doesn't stay on top for longer than
+ // configured in the feed settings (settings.recsExpireTime).
+ recordTopRecImpressions(topItems) {
+ let impressions = this.readImpressionsPref(REC_IMPRESSION_TRACKING_PREF);
+ let changed = false;
+
+ topItems.forEach(t => {
+ if (!impressions[t]) {
+ changed = true;
+ impressions = Object.assign(impressions, { [t]: Date.now() });
+ }
+ });
+
+ if (changed) {
+ this.writeImpressionsPref(REC_IMPRESSION_TRACKING_PREF, impressions);
+ }
+ }
+
+ readImpressionsPref(pref) {
+ const prefVal = this._prefs.get(pref);
+ return prefVal ? JSON.parse(prefVal) : {};
+ }
+
+ writeImpressionsPref(pref, impressions) {
+ this._prefs.set(pref, JSON.stringify(impressions));
+ }
+
+ async removeSpocs() {
+ // Quick hack so that SPOCS are removed from all open and preloaded tabs when
+ // they are disabled. The longer term fix should probably be to remove them
+ // in the Reducer.
+ await this.clearCache();
+ this.uninit();
+ this.init();
+ }
+
+ /**
+ * Decides if we need to change the personality provider version or not.
+ * Changes the version if it determines we need to.
+ *
+ * @param data {object} The top stories pref, we need version and model_keys
+ * @return {boolean} Returns true only if the version was changed.
+ */
+ processAffinityProividerVersion(data) {
+ const version2 = data.version === 2 && !this.affinityProviderV2;
+ const version1 = data.version === 1 && this.affinityProviderV2;
+ if (version2 || version1) {
+ if (version1) {
+ this.affinityProviderV2 = null;
+ } else {
+ this.affinityProviderV2 = {
+ use_v2: true,
+ model_keys: data.model_keys,
+ };
+ }
+ return true;
+ }
+ return false;
+ }
+
+ lazyLoadTopStories(options = {}) {
+ let { dsPref, userPref } = options;
+ if (!dsPref) {
+ dsPref = this.store.getState().Prefs.values[DISCOVERY_STREAM_PREF];
+ }
+ if (!userPref) {
+ userPref = this.store.getState().Prefs.values[PREF_USER_TOPSTORIES];
+ }
+
+ try {
+ this.discoveryStreamEnabled =
+ JSON.parse(dsPref).enabled &&
+ this.store.getState().Prefs.values[DISCOVERY_STREAM_PREF_ENABLED];
+ } catch (e) {
+ // Load activity stream top stories if fail to determine discovery stream state
+ this.discoveryStreamEnabled = false;
+ }
+
+ // Return without invoking initialization if top stories are loaded, or preffed off.
+ if (this.storiesLoaded || !userPref) {
+ return;
+ }
+
+ if (!this.discoveryStreamEnabled && !this.propertiesInitialized) {
+ this.initializeProperties();
+ }
+ this.init();
+ }
+
+ handleDisabled(action) {
+ switch (action.type) {
+ case at.INIT:
+ this.lazyLoadTopStories();
+ break;
+ case at.PREF_CHANGED:
+ if (action.data.name === DISCOVERY_STREAM_PREF) {
+ this.lazyLoadTopStories({ dsPref: action.data.value });
+ }
+ if (action.data.name === DISCOVERY_STREAM_PREF_ENABLED) {
+ this.lazyLoadTopStories();
+ }
+ if (action.data.name === PREF_USER_TOPSTORIES) {
+ if (action.data.value) {
+ // init topstories if value if true.
+ this.lazyLoadTopStories({ userPref: action.data.value });
+ } else {
+ this.uninit();
+ }
+ }
+ break;
+ case at.UNINIT:
+ this.uninit();
+ break;
+ }
+ }
+
+ async onAction(action) {
+ if (this.discoveryStreamEnabled) {
+ this.handleDisabled(action);
+ return;
+ }
+ switch (action.type) {
+ // Check discoverystream pref and load activity stream top stories only if needed
+ case at.INIT:
+ this.lazyLoadTopStories();
+ break;
+ case at.SYSTEM_TICK:
+ let stories;
+ let topics;
+ if (Date.now() - this.storiesLastUpdated >= STORIES_UPDATE_TIME) {
+ stories = await this.fetchStories();
+ }
+ if (Date.now() - this.topicsLastUpdated >= TOPICS_UPDATE_TIME) {
+ topics = await this.fetchTopics();
+ }
+ this.doContentUpdate({ stories, topics }, false);
+ break;
+ case at.UNINIT:
+ this.uninit();
+ break;
+ case at.NEW_TAB_REHYDRATED:
+ this.getPocketState(action.meta.fromTarget);
+ this.maybeAddSpoc(action.meta.fromTarget);
+ break;
+ case at.SECTION_OPTIONS_CHANGED:
+ if (action.data === SECTION_ID) {
+ await this.clearCache();
+ this.uninit();
+ this.init();
+ }
+ break;
+ case at.PLACES_LINK_BLOCKED:
+ if (this.spocs) {
+ this.spocs = this.spocs.filter(s => s.url !== action.data.url);
+ }
+ break;
+ case at.PLACES_HISTORY_CLEARED:
+ if (this.personalized) {
+ this.resetDomainAffinityScores();
+ }
+ break;
+ case at.TELEMETRY_IMPRESSION_STATS: {
+ // We want to make sure we only track impressions from Top Stories,
+ // otherwise unexpected things that are not properly handled can happen.
+ // Example: Impressions from spocs on Discovery Stream can cause the
+ // Top Stories impressions pref to continuously grow, see bug #1523408
+ if (action.data.source === IMPRESSION_SOURCE) {
+ const payload = action.data;
+ const viewImpression = !(
+ "click" in payload ||
+ "block" in payload ||
+ "pocket" in payload
+ );
+ if (payload.tiles && viewImpression) {
+ if (this.shouldShowSpocs()) {
+ payload.tiles.forEach(t => {
+ if (this.spocCampaignMap.has(t.id)) {
+ this.recordCampaignImpression(this.spocCampaignMap.get(t.id));
+ }
+ });
+ }
+ if (this.personalized) {
+ const topRecs = payload.tiles
+ .filter(t => !this.spocCampaignMap.has(t.id))
+ .map(t => t.id);
+ this.recordTopRecImpressions(topRecs);
+ }
+ }
+ }
+ break;
+ }
+ case at.PREF_CHANGED:
+ if (action.data.name === DISCOVERY_STREAM_PREF) {
+ this.lazyLoadTopStories({ dsPref: action.data.value });
+ }
+ if (action.data.name === PREF_USER_TOPSTORIES) {
+ if (action.data.value) {
+ // init topstories if value if true.
+ this.lazyLoadTopStories({ userPref: action.data.value });
+ } else {
+ this.uninit();
+ }
+ }
+ // Check if spocs was disabled. Remove them if they were.
+ if (action.data.name === "showSponsored" && !action.data.value) {
+ await this.removeSpocs();
+ }
+ if (action.data.name === "pocketCta") {
+ this.dispatchPocketCta(action.data.value, true);
+ }
+ if (action.data.name === OPTIONS_PREF) {
+ try {
+ const options = JSON.parse(action.data.value);
+ if (this.processAffinityProividerVersion(options)) {
+ await this.clearCache();
+ this.uninit();
+ this.init();
+ }
+ } catch (e) {
+ Cu.reportError(
+ `Problem initializing affinity provider v2: ${e.message}`
+ );
+ }
+ }
+ break;
+ }
+ }
+};
+
+this.STORIES_UPDATE_TIME = STORIES_UPDATE_TIME;
+this.TOPICS_UPDATE_TIME = TOPICS_UPDATE_TIME;
+this.SECTION_ID = SECTION_ID;
+this.SPOC_IMPRESSION_TRACKING_PREF = SPOC_IMPRESSION_TRACKING_PREF;
+this.REC_IMPRESSION_TRACKING_PREF = REC_IMPRESSION_TRACKING_PREF;
+this.MIN_DOMAIN_AFFINITIES_UPDATE_TIME = MIN_DOMAIN_AFFINITIES_UPDATE_TIME;
+this.DEFAULT_RECS_EXPIRE_TIME = DEFAULT_RECS_EXPIRE_TIME;
+const EXPORTED_SYMBOLS = [
+ "TopStoriesFeed",
+ "STORIES_UPDATE_TIME",
+ "TOPICS_UPDATE_TIME",
+ "SECTION_ID",
+ "SPOC_IMPRESSION_TRACKING_PREF",
+ "MIN_DOMAIN_AFFINITIES_UPDATE_TIME",
+ "REC_IMPRESSION_TRACKING_PREF",
+ "DEFAULT_RECS_EXPIRE_TIME",
+];
diff --git a/browser/components/newtab/lib/UTEventReporting.jsm b/browser/components/newtab/lib/UTEventReporting.jsm
new file mode 100644
index 0000000000..2d6fe73ab1
--- /dev/null
+++ b/browser/components/newtab/lib/UTEventReporting.jsm
@@ -0,0 +1,68 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
+
+/**
+ * Note: the schema can be found in
+ * https://searchfox.org/mozilla-central/source/toolkit/components/telemetry/Events.yaml
+ */
+const EXTRAS_FIELD_NAMES = [
+ "addon_version",
+ "session_id",
+ "page",
+ "user_prefs",
+ "action_position",
+];
+
+this.UTEventReporting = class UTEventReporting {
+ constructor() {
+ Services.telemetry.setEventRecordingEnabled("activity_stream", true);
+ this.sendUserEvent = this.sendUserEvent.bind(this);
+ this.sendSessionEndEvent = this.sendSessionEndEvent.bind(this);
+ }
+
+ _createExtras(data) {
+ // Make a copy of the given data and delete/modify it as needed.
+ let utExtras = Object.assign({}, data);
+ for (let field of Object.keys(utExtras)) {
+ if (EXTRAS_FIELD_NAMES.includes(field)) {
+ utExtras[field] = String(utExtras[field]);
+ continue;
+ }
+ delete utExtras[field];
+ }
+ return utExtras;
+ }
+
+ sendUserEvent(data) {
+ let mainFields = ["event", "source"];
+ let eventFields = mainFields.map(field => String(data[field]) || null);
+
+ Services.telemetry.recordEvent(
+ "activity_stream",
+ "event",
+ ...eventFields,
+ this._createExtras(data)
+ );
+ }
+
+ sendSessionEndEvent(data) {
+ Services.telemetry.recordEvent(
+ "activity_stream",
+ "end",
+ "session",
+ String(data.session_duration),
+ this._createExtras(data)
+ );
+ }
+
+ uninit() {
+ Services.telemetry.setEventRecordingEnabled("activity_stream", false);
+ }
+};
+
+const EXPORTED_SYMBOLS = ["UTEventReporting"];
diff --git a/browser/components/newtab/lib/UserDomainAffinityProvider.jsm b/browser/components/newtab/lib/UserDomainAffinityProvider.jsm
new file mode 100644
index 0000000000..f165aad1e5
--- /dev/null
+++ b/browser/components/newtab/lib/UserDomainAffinityProvider.jsm
@@ -0,0 +1,390 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
+const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
+
+ChromeUtils.defineModuleGetter(
+ this,
+ "PlacesUtils",
+ "resource://gre/modules/PlacesUtils.jsm"
+);
+
+const DEFAULT_TIME_SEGMENTS = [
+ { id: "hour", startTime: 3600, endTime: 0, weightPosition: 1 },
+ { id: "day", startTime: 86400, endTime: 3600, weightPosition: 0.75 },
+ { id: "week", startTime: 604800, endTime: 86400, weightPosition: 0.5 },
+ { id: "weekPlus", startTime: 0, endTime: 604800, weightPosition: 0.25 },
+ { id: "alltime", startTime: 0, endTime: 0, weightPosition: 0.25 },
+];
+
+const DEFAULT_PARAMETER_SETS = {
+ "linear-frequency": {
+ recencyFactor: 0.4,
+ frequencyFactor: 0.5,
+ combinedDomainFactor: 0.5,
+ perfectFrequencyVisits: 10,
+ perfectCombinedDomainScore: 2,
+ multiDomainBoost: 0.1,
+ itemScoreFactor: 0,
+ },
+};
+
+const DEFAULT_MAX_HISTORY_QUERY_RESULTS = 1000;
+
+function merge(...args) {
+ return Object.assign.apply(this, args);
+}
+
+/**
+ * Provides functionality to personalize content recommendations by calculating
+ * user domain affinity scores. These scores are used to calculate relevance
+ * scores for items/recs/stories that have domain affinities.
+ *
+ * The algorithm works as follows:
+ *
+ * - The recommendation endpoint returns a settings object containing
+ * timeSegments and parametersets.
+ *
+ * - For every time segment we calculate the corresponding domain visit counts,
+ * yielding result objects of the following structure: {"mozilla.org": 12,
+ * "mozilla.com": 34} (see UserDomainAffinityProvider#queryVisits)
+ *
+ * - These visit counts are transformed to domain affinity scores for all
+ * provided parameter sets: {"mozilla.org": {"paramSet1": 0.8,
+ * "paramSet2": 0.9}, "mozilla.org": {"paramSet1": 1, "paramSet2": 0.9}}
+ * (see UserDomainAffinityProvider#calculateScoresForParameterSets)
+ *
+ * - The parameter sets provide factors for weighting which allows for
+ * flexible targeting. The functionality to calculate final scores can
+ * be seen in UserDomainAffinityProvider#calculateScores
+ *
+ * - The user domain affinity scores are summed up across all time segments
+ * see UserDomainAffinityProvider#calculateAllUserDomainAffinityScores
+ *
+ * - An item's domain affinities are matched to the user's domain affinity
+ * scores by calculating an item relevance score
+ * (see UserDomainAffinityProvider#calculateItemRelevanceScore)
+ *
+ * - The item relevance scores are used to sort items (see TopStoriesFeed for
+ * more details)
+ *
+ * - The data structure was chosen to allow for fast cache lookups during
+ * relevance score calculation. While user domain affinities are calculated
+ * infrequently (i.e. only once a day), the item relevance score (potentially)
+ * needs to be calculated every time the feed updates. Therefore allowing cache
+ * lookups of scores[domain][parameterSet] is beneficial
+ */
+this.UserDomainAffinityProvider = class UserDomainAffinityProvider {
+ constructor(
+ timeSegments = DEFAULT_TIME_SEGMENTS,
+ parameterSets = DEFAULT_PARAMETER_SETS,
+ maxHistoryQueryResults = DEFAULT_MAX_HISTORY_QUERY_RESULTS,
+ version,
+ scores
+ ) {
+ this.timeSegments = timeSegments;
+ this.maxHistoryQueryResults = maxHistoryQueryResults;
+ this.version = version;
+ if (scores) {
+ this.parameterSets = parameterSets;
+ this.scores = scores;
+ } else {
+ this.parameterSets = this.prepareParameterSets(parameterSets);
+ this.scores = this.calculateAllUserDomainAffinityScores();
+ }
+ }
+
+ /**
+ * Adds dynamic parameters to the given parameter sets that need to be
+ * computed based on time segments.
+ *
+ * @param ps The parameter sets
+ * @return Updated parameter sets with additional fields (i.e. timeSegmentWeights)
+ */
+ prepareParameterSets(ps) {
+ return (
+ Object.keys(ps)
+ // Add timeSegmentWeight fields to param sets e.g. timeSegmentWeights: {"hour": 1, "day": 0.8915, ...}
+ .map(k => ({
+ [k]: merge(ps[k], {
+ timeSegmentWeights: this.calculateTimeSegmentWeights(
+ ps[k].recencyFactor
+ ),
+ }),
+ }))
+ .reduce((acc, cur) => merge(acc, cur))
+ );
+ }
+
+ /**
+ * Calculates a time segment weight based on the provided recencyFactor.
+ *
+ * @param recencyFactor The recency factor indicating how to weigh recency
+ * @return An object containing time segment weights: {"hour": 0.987, "day": 1}
+ */
+ calculateTimeSegmentWeights(recencyFactor) {
+ return this.timeSegments.reduce(
+ (acc, cur) =>
+ merge(acc, {
+ [cur.id]: this.calculateScore(cur.weightPosition, 1, recencyFactor),
+ }),
+ {}
+ );
+ }
+
+ /**
+ * Calculates user domain affinity scores based on browsing history and the
+ * available times segments and parameter sets.
+ */
+ calculateAllUserDomainAffinityScores() {
+ return (
+ this.timeSegments
+ // Calculate parameter set specific domain scores for each time segment
+ // => [{"a.com": {"ps1": 12, "ps2": 34}, "b.com": {"ps1": 56, "ps2": 78}}, ...]
+ .map(ts => this.calculateUserDomainAffinityScores(ts))
+ // Keep format, but reduce to single object, with combined scores across all time segments
+ // => "{a.com":{"ps1":2,"ps2":2}, "b.com":{"ps1":3,"ps2":3}}""
+ .reduce((acc, cur) => this._combineScores(acc, cur))
+ );
+ }
+
+ /**
+ * Calculates the user domain affinity scores for the given time segment.
+ *
+ * @param ts The time segment
+ * @return The parameter specific scores for all domains with visits in
+ * this time segment: {"a.com": {"ps1": 12, "ps2": 34}, "b.com" ...}
+ */
+ calculateUserDomainAffinityScores(ts) {
+ // Returns domains and visit counts for this time segment: {"a.com": 1, "b.com": 2}
+ let visits = this.queryVisits(ts);
+
+ return Object.keys(visits).reduce(
+ (acc, d) =>
+ merge(acc, {
+ [d]: this.calculateScoresForParameterSets(ts, visits[d]),
+ }),
+ {}
+ );
+ }
+
+ /**
+ * Calculates the scores for all parameter sets for the given time segment
+ * and domain visit count.
+ *
+ * @param ts The time segment
+ * @param vc The domain visit count in the given time segment
+ * @return The parameter specific scores for the visit count in
+ * this time segment: {"ps1": 12, "ps2": 34}
+ */
+ calculateScoresForParameterSets(ts, vc) {
+ return Object.keys(this.parameterSets).reduce(
+ (acc, ps) =>
+ merge(acc, {
+ [ps]: this.calculateScoreForParameterSet(
+ ts,
+ vc,
+ this.parameterSets[ps]
+ ),
+ }),
+ {}
+ );
+ }
+
+ /**
+ * Calculates the final affinity score in the given time segment for the given parameter set
+ *
+ * @param timeSegment The time segment
+ * @param visitCount The domain visit count in the given time segment
+ * @param parameterSet The parameter set to use for scoring
+ * @return The final score
+ */
+ calculateScoreForParameterSet(timeSegment, visitCount, parameterSet) {
+ return this.calculateScore(
+ visitCount * parameterSet.timeSegmentWeights[timeSegment.id],
+ parameterSet.perfectFrequencyVisits,
+ parameterSet.frequencyFactor
+ );
+ }
+
+ /**
+ * Keeps the same format, but reduces the two objects to a single object, with
+ * combined scores across all time segments => {a.com":{"ps1":2,"ps2":2},
+ * "b.com":{"ps1":3,"ps2":3}}
+ */
+ _combineScores(a, b) {
+ // Merge both score objects so we get a combined object holding all domains.
+ // This is so we can combine them without missing domains that are in a and not in b and vice versa.
+ const c = merge({}, a, b);
+ return Object.keys(c).reduce(
+ (acc, d) => merge(acc, this._combine(a, b, c, d)),
+ {}
+ );
+ }
+
+ _combine(a, b, c, d) {
+ return (
+ Object.keys(c[d])
+ // Summing up the parameter set specific scores of each domain
+ .map(ps => ({
+ [d]: {
+ [ps]: Math.min(
+ 1,
+ ((a[d] && a[d][ps]) || 0) + ((b[d] && b[d][ps]) || 0)
+ ),
+ },
+ }))
+ // Reducing from an array of objects with a single parameter set to a single object
+ // [{"a.com":{"ps1":11}}, {"a.com: {"ps2":12}}] => {"a.com":{"ps1":11,"ps2":12}}
+ .reduce((acc, cur) => ({ [d]: merge(acc[d], cur[d]) }))
+ );
+ }
+
+ /**
+ * Calculates a value on the curve described by the provided parameters. The curve we're using is
+ * (a^(b*x) - 1) / (a^b - 1): https://www.desmos.com/calculator/maqhpttupp
+ *
+ * @param {number} score A value between 0 and maxScore, representing x.
+ * @param {number} maxScore Highest possible score.
+ * @param {number} factor The slope describing the curve to get to maxScore. A low slope value
+ * [0, 0.5] results in a log-shaped curve, a high slope [0.5, 1] results in a exp-shaped curve,
+ * a slope of exactly 0.5 is linear.
+ * @param {number} ease Adjusts how much bend is in the curve i.e. how dramatic the maximum
+ * effect of the slope can be. This represents b in the formula above.
+ * @return {number} the final score
+ */
+ calculateScore(score, maxScore, factor, ease = 2) {
+ let a = 0;
+ let x = Math.max(0, score / maxScore);
+
+ if (x >= 1) {
+ return 1;
+ }
+
+ if (factor === 0.5) {
+ return x;
+ }
+
+ if (factor < 0.5) {
+ // We want a log-shaped curve so we scale "a" between 0 and .99
+ a = (factor / 0.5) * 0.49;
+ } else if (factor > 0.5) {
+ // We want an exp-shaped curve so we scale "a" between 1.01 and 10
+ a = 1 + ((factor - 0.5) / 0.5) * 9;
+ }
+
+ return (Math.pow(a, ease * x) - 1) / (Math.pow(a, ease) - 1);
+ }
+
+ /**
+ * Queries the visit counts in the given time segment.
+ *
+ * @param ts the time segment
+ * @return the visit count object: {"a.com": 1, "b.com": 2}
+ */
+ queryVisits(ts) {
+ const visitCounts = {};
+ const query = PlacesUtils.history.getNewQuery();
+ if (!query) {
+ return visitCounts;
+ }
+ const wwwRegEx = /^www\./;
+
+ query.beginTimeReference = query.TIME_RELATIVE_NOW;
+ query.beginTime =
+ ts.startTime && ts.startTime !== 0
+ ? -(ts.startTime * 1000 * 1000)
+ : -(Date.now() * 1000);
+
+ query.endTimeReference = query.TIME_RELATIVE_NOW;
+ query.endTime =
+ ts.endTime && ts.endTime !== 0 ? -(ts.endTime * 1000 * 1000) : 0;
+
+ const options = PlacesUtils.history.getNewQueryOptions();
+ options.sortingMode = options.SORT_BY_VISITCOUNT_DESCENDING;
+ options.maxResults = this.maxHistoryQueryResults;
+
+ const { root } = PlacesUtils.history.executeQuery(query, options);
+ root.containerOpen = true;
+ for (let i = 0; i < root.childCount; i++) {
+ let node = root.getChild(i);
+ let host = Services.io.newURI(node.uri).host.replace(wwwRegEx, "");
+ if (!visitCounts[host]) {
+ visitCounts[host] = 0;
+ }
+ visitCounts[host] += node.accessCount;
+ }
+ root.containerOpen = false;
+ return visitCounts;
+ }
+
+ /**
+ * Calculates an item's relevance score.
+ *
+ * @param item the item (story), must contain domain affinities, otherwise a
+ * score of 1 is returned.
+ * @return the calculated item's score or 1 if item has no domain_affinities
+ * or references an unknown parameter set.
+ */
+ calculateItemRelevanceScore(item) {
+ const params = this.parameterSets[item.parameter_set];
+ if (!item.domain_affinities || !params) {
+ return item.item_score;
+ }
+
+ const scores = Object.keys(item.domain_affinities).reduce(
+ (acc, d) => {
+ let userDomainAffinityScore = this.scores[d]
+ ? this.scores[d][item.parameter_set]
+ : false;
+ if (userDomainAffinityScore) {
+ acc.combinedDomainScore +=
+ userDomainAffinityScore * item.domain_affinities[d];
+ acc.matchingDomainsCount++;
+ }
+ return acc;
+ },
+ { combinedDomainScore: 0, matchingDomainsCount: 0 }
+ );
+
+ // Boost the score as configured in the provided parameter set
+ const boostedCombinedDomainScore =
+ scores.combinedDomainScore *
+ Math.pow(params.multiDomainBoost + 1, scores.matchingDomainsCount);
+
+ // Calculate what the score would be if the item score is ignored
+ const normalizedCombinedDomainScore = this.calculateScore(
+ boostedCombinedDomainScore,
+ params.perfectCombinedDomainScore,
+ params.combinedDomainFactor
+ );
+
+ // Calculate the final relevance score using the itemScoreFactor. The itemScoreFactor
+ // allows weighting the item score in relation to the normalizedCombinedDomainScore:
+ // An itemScoreFactor of 1 results in the item score and ignores the combined domain score
+ // An itemScoreFactor of 0.5 results in the the average of item score and combined domain score
+ // An itemScoreFactor of 0 results in the combined domain score and ignores the item score
+ return (
+ params.itemScoreFactor *
+ (item.item_score - normalizedCombinedDomainScore) +
+ normalizedCombinedDomainScore
+ );
+ }
+
+ /**
+ * Returns an object holding the settings and affinity scores of this provider instance.
+ */
+ getAffinities() {
+ return {
+ timeSegments: this.timeSegments,
+ parameterSets: this.parameterSets,
+ maxHistoryQueryResults: this.maxHistoryQueryResults,
+ version: this.version,
+ scores: this.scores,
+ };
+ }
+};
+
+const EXPORTED_SYMBOLS = ["UserDomainAffinityProvider"];
diff --git a/browser/components/newtab/lib/cache-worker.js b/browser/components/newtab/lib/cache-worker.js
new file mode 100644
index 0000000000..2f6eed5f0e
--- /dev/null
+++ b/browser/components/newtab/lib/cache-worker.js
@@ -0,0 +1,193 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* eslint-env mozilla/chrome-worker */
+
+/* global ReactDOMServer, NewtabRenderUtils */
+
+const PAGE_TEMPLATE_RESOURCE_PATH =
+ "resource://activity-stream/data/content/abouthomecache/page.html.template";
+const SCRIPT_TEMPLATE_RESOURCE_PATH =
+ "resource://activity-stream/data/content/abouthomecache/script.js.template";
+
+// If we don't stub these functions out, React throws warnings in the console
+// upon being loaded.
+let window = self;
+window.requestAnimationFrame = () => {};
+window.cancelAnimationFrame = () => {};
+window.ASRouterMessage = () => {
+ return Promise.resolve();
+};
+window.ASRouterAddParentListener = () => {};
+window.ASRouterRemoveParentListener = () => {};
+
+importScripts("resource://gre/modules/workers/require.js");
+
+{
+ let oldChromeUtils = ChromeUtils;
+
+ // ChromeUtils is defined inside of a Worker, but we don't want the
+ // activity-stream.bundle.js to detect it when loading, since that results
+ // in it attempting to import `Services.jsm` on load, which is not allowed in
+ // a Worker. So we temporarily clear ChromeUtils so that activity-stream.bundle.js
+ // thinks its being loaded in content scope.
+ //
+ // eslint-disable-next-line no-global-assign
+ ChromeUtils = undefined;
+
+ importScripts(
+ "resource://activity-stream/vendor/react.js",
+ "resource://activity-stream/vendor/react-dom.js",
+ "resource://activity-stream/vendor/react-dom-server.js",
+ "resource://activity-stream/vendor/redux.js",
+ "resource://activity-stream/vendor/react-transition-group.js",
+ "resource://activity-stream/vendor/prop-types.js",
+ "resource://activity-stream/vendor/react-redux.js",
+ "resource://activity-stream/data/content/activity-stream.bundle.js"
+ );
+
+ // eslint-disable-next-line no-global-assign
+ ChromeUtils = oldChromeUtils;
+}
+
+let PromiseWorker = require("resource://gre/modules/workers/PromiseWorker.js");
+
+let Agent = {
+ _templates: null,
+
+ /**
+ * Synchronously loads the template files off of the file
+ * system, and returns them as an object. If the Worker has loaded
+ * these templates before, a cached copy of the templates is returned
+ * instead.
+ *
+ * @return Object
+ * An object with the following properties:
+ *
+ * pageTemplate (String):
+ * The template for the document markup.
+ *
+ * scriptTempate (String):
+ * The template for the script.
+ */
+ getOrCreateTemplates() {
+ if (this._templates) {
+ return this._templates;
+ }
+
+ const templateResources = new Map([
+ ["pageTemplate", PAGE_TEMPLATE_RESOURCE_PATH],
+ ["scriptTemplate", SCRIPT_TEMPLATE_RESOURCE_PATH],
+ ]);
+
+ this._templates = {};
+
+ for (let [name, path] of templateResources) {
+ const xhr = new XMLHttpRequest();
+ // Using a synchronous XHR in a worker is fine.
+ xhr.open("GET", path, false);
+ xhr.responseType = "text";
+ xhr.send(null);
+ this._templates[name] = xhr.responseText;
+ }
+
+ return this._templates;
+ },
+
+ /**
+ * Constructs the cached about:home document using ReactDOMServer. This will
+ * be called when "construct" messages are sent to this PromiseWorker.
+ *
+ * @param state (Object)
+ * The most recent Activity Stream Redux state.
+ * @return Object
+ * An object with the following properties:
+ *
+ * page (String):
+ * The generated markup for the document.
+ *
+ * script (String):
+ * The generated script for the document.
+ */
+ construct(state) {
+ // If anything in this function throws an exception, PromiseWorker
+ // runs the risk of leaving the Promise associated with this method
+ // forever unresolved. This is particularly bad when this method is
+ // called via AsyncShutdown, since the forever unresolved Promise can
+ // result in a AsyncShutdown timeout crash.
+ //
+ // To help ensure that no matter what, the Promise resolves with something,
+ // we wrap the whole operation in a try/catch.
+ try {
+ return this._construct(state);
+ } catch (e) {
+ console.error("about:home startup cache construction failed:", e);
+ return { page: null, script: null };
+ }
+ },
+
+ /**
+ * Internal method that actually does the work of constructing the cached
+ * about:home document using ReactDOMServer. This should be called from
+ * `construct` only.
+ *
+ * @param state (Object)
+ * The most recent Activity Stream Redux state.
+ * @return Object
+ * An object with the following properties:
+ *
+ * page (String):
+ * The generated markup for the document.
+ *
+ * script (String):
+ * The generated script for the document.
+ */
+ _construct(state) {
+ state.App.isForStartupCache = true;
+
+ // ReactDOMServer.renderToString expects a Redux store to pull
+ // the state from, so we mock out a minimal store implementation.
+ let fakeStore = {
+ getState() {
+ return state;
+ },
+ dispatch() {},
+ };
+
+ let markup = ReactDOMServer.renderToString(
+ NewtabRenderUtils.NewTab({
+ store: fakeStore,
+ isFirstrun: false,
+ })
+ );
+
+ let { pageTemplate, scriptTemplate } = this.getOrCreateTemplates();
+ let cacheTime = new Date().toUTCString();
+ let page = pageTemplate
+ .replace("{{ MARKUP }}", markup)
+ .replace("{{ CACHE_TIME }}", cacheTime);
+ let script = scriptTemplate.replace(
+ "{{ STATE }}",
+ JSON.stringify(state, null, "\t")
+ );
+
+ return { page, script };
+ },
+};
+
+// This boilerplate connects the PromiseWorker to the Agent so
+// that messages from the main thread map to methods on the
+// Agent.
+let worker = new PromiseWorker.AbstractWorker();
+worker.dispatch = function(method, args = []) {
+ return Agent[method](...args);
+};
+worker.postMessage = function(result, ...transfers) {
+ self.postMessage(result, ...transfers);
+};
+worker.close = function() {
+ self.close();
+};
+
+self.addEventListener("message", msg => worker.handleMessage(msg));
diff --git a/browser/components/newtab/loaders/inject-loader.js b/browser/components/newtab/loaders/inject-loader.js
new file mode 100644
index 0000000000..ae693ea0fc
--- /dev/null
+++ b/browser/components/newtab/loaders/inject-loader.js
@@ -0,0 +1,57 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+// Note: this is based on https://github.com/plasticine/inject-loader,
+// patched to make istanbul work properly
+
+const loaderUtils = require("loader-utils");
+const QUOTE_REGEX_STRING = "['|\"]{1}";
+
+const hasOnlyExcludeFlags = query =>
+ Object.keys(query).filter(key => query[key] === true).length === 0;
+const escapePath = path => path.replace("/", "\\/");
+
+function createRequireStringRegex(query) {
+ const regexArray = [];
+
+ // if there is no query then replace everything
+ if (Object.keys(query).length === 0) {
+ regexArray.push("([^\\)]+)");
+ } else if (hasOnlyExcludeFlags(query)) {
+ // if there are only negation matches in the query then replace everything
+ // except them
+ Object.keys(query).forEach(key =>
+ regexArray.push(`(?!${QUOTE_REGEX_STRING}${escapePath(key)})`)
+ );
+ regexArray.push("([^\\)]+)");
+ } else {
+ regexArray.push(`(${QUOTE_REGEX_STRING}(`);
+ regexArray.push(
+ Object.keys(query)
+ .map(key => escapePath(key))
+ .join("|")
+ );
+ regexArray.push(`)${QUOTE_REGEX_STRING})`);
+ }
+
+ // Wrap the regex to match `require()`
+ regexArray.unshift("require\\(");
+ regexArray.push("\\)");
+
+ return new RegExp(regexArray.join(""), "g");
+}
+
+module.exports = function inject(src) {
+ if (this.cacheable) {
+ this.cacheable();
+ }
+ const regex = createRequireStringRegex(loaderUtils.getOptions(this) || {});
+
+ return `module.exports = function inject(injections) {
+ var module = {exports: {}};
+ var exports = module.exports;
+ ${src.replace(regex, "(injections[$1] || /* istanbul ignore next */ $&)")}
+ return module.exports;
+}\n`;
+};
diff --git a/browser/components/newtab/moz.build b/browser/components/newtab/moz.build
new file mode 100644
index 0000000000..73a6d51284
--- /dev/null
+++ b/browser/components/newtab/moz.build
@@ -0,0 +1,43 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+with Files("**"):
+ BUG_COMPONENT = ("Firefox", "New Tab Page")
+
+BROWSER_CHROME_MANIFESTS += [
+ "test/browser/abouthomecache/browser.ini",
+ "test/browser/browser.ini",
+]
+
+SPHINX_TREES["docs"] = "docs"
+SPHINX_TREES["content-src/asrouter/docs"] = "content-src/asrouter/docs"
+
+XPCSHELL_TESTS_MANIFESTS += [
+ "test/xpcshell/xpcshell.ini",
+]
+
+XPIDL_SOURCES += [
+ "nsIAboutNewTabService.idl",
+]
+
+XPIDL_MODULE = "browser-newtab"
+
+EXTRA_JS_MODULES += [
+ "AboutNewTabService.jsm",
+]
+
+FINAL_TARGET_FILES.actors += [
+ "aboutwelcome/AboutWelcomeChild.jsm",
+ "aboutwelcome/AboutWelcomeParent.jsm",
+ "actors/ASRouterChild.jsm",
+ "actors/ASRouterParent.jsm",
+]
+
+XPCOM_MANIFESTS += [
+ "components.conf",
+]
+
+JAR_MANIFESTS += ["jar.mn"]
diff --git a/browser/components/newtab/nsIAboutNewTabService.idl b/browser/components/newtab/nsIAboutNewTabService.idl
new file mode 100644
index 0000000000..e8ddd0381f
--- /dev/null
+++ b/browser/components/newtab/nsIAboutNewTabService.idl
@@ -0,0 +1,39 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "nsISupports.idl"
+
+/**
+ * Allows to override about:newtab to point to a different location
+ * than the one specified within AboutRedirector.cpp
+ */
+
+interface nsIChannel;
+interface nsIURI;
+interface nsILoadInfo;
+
+[scriptable, uuid(dfcd2adc-7867-4d3a-ba70-17501f208142)]
+interface nsIAboutNewTabService : nsISupports
+{
+ /**
+ * Returns the default URL (local or activity stream depending on pref)
+ */
+ readonly attribute ACString defaultURL;
+
+ /**
+ * In the "privileged about content process", if about:home is being
+ * retrieved, the AboutRedirector will call this function to get the
+ * nsIChannel for the document. This gives the nsIAboutNewTabService
+ * the opportunity to provide a cached document for about:home. If
+ * no cache exists, the nsIChannel will be for the normal dynamically
+ * generated about:home document.
+ */
+ nsIChannel aboutHomeChannel(in nsIURI aURI,
+ in nsILoadInfo aLoadInfo);
+
+ /**
+ * Returns the about:welcome URL.
+ */
+ readonly attribute ACString welcomeURL;
+};
diff --git a/browser/components/newtab/package-lock.json b/browser/components/newtab/package-lock.json
new file mode 100644
index 0000000000..c20d8909c3
--- /dev/null
+++ b/browser/components/newtab/package-lock.json
@@ -0,0 +1,11820 @@
+{
+ "name": "activity-streams",
+ "version": "1.14.3",
+ "lockfileVersion": 1,
+ "requires": true,
+ "dependencies": {
+ "@babel/code-frame": {
+ "version": "7.8.3",
+ "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.8.3.tgz",
+ "integrity": "sha512-a9gxpmdXtZEInkCSHUJDLHZVBgb1QS0jhss4cPP93EW7s+uC5bikET2twEF3KV+7rDblJcmNvTR7VJejqd2C2g==",
+ "dev": true,
+ "requires": {
+ "@babel/highlight": "^7.8.3"
+ }
+ },
+ "@babel/core": {
+ "version": "7.8.4",
+ "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.8.4.tgz",
+ "integrity": "sha512-0LiLrB2PwrVI+a2/IEskBopDYSd8BCb3rOvH7D5tzoWd696TBEduBvuLVm4Nx6rltrLZqvI3MCalB2K2aVzQjA==",
+ "dev": true,
+ "requires": {
+ "@babel/code-frame": "^7.8.3",
+ "@babel/generator": "^7.8.4",
+ "@babel/helpers": "^7.8.4",
+ "@babel/parser": "^7.8.4",
+ "@babel/template": "^7.8.3",
+ "@babel/traverse": "^7.8.4",
+ "@babel/types": "^7.8.3",
+ "convert-source-map": "^1.7.0",
+ "debug": "^4.1.0",
+ "gensync": "^1.0.0-beta.1",
+ "json5": "^2.1.0",
+ "lodash": "^4.17.13",
+ "resolve": "^1.3.2",
+ "semver": "^5.4.1",
+ "source-map": "^0.5.0"
+ }
+ },
+ "@babel/generator": {
+ "version": "7.8.4",
+ "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.8.4.tgz",
+ "integrity": "sha512-PwhclGdRpNAf3IxZb0YVuITPZmmrXz9zf6fH8lT4XbrmfQKr6ryBzhv593P5C6poJRciFCL/eHGW2NuGrgEyxA==",
+ "dev": true,
+ "requires": {
+ "@babel/types": "^7.8.3",
+ "jsesc": "^2.5.1",
+ "lodash": "^4.17.13",
+ "source-map": "^0.5.0"
+ }
+ },
+ "@babel/helper-builder-react-jsx": {
+ "version": "7.8.3",
+ "resolved": "https://registry.npmjs.org/@babel/helper-builder-react-jsx/-/helper-builder-react-jsx-7.8.3.tgz",
+ "integrity": "sha512-JT8mfnpTkKNCboTqZsQTdGo3l3Ik3l7QIt9hh0O9DYiwVel37VoJpILKM4YFbP2euF32nkQSb+F9cUk9b7DDXQ==",
+ "dev": true,
+ "requires": {
+ "@babel/types": "^7.8.3",
+ "esutils": "^2.0.0"
+ }
+ },
+ "@babel/helper-create-class-features-plugin": {
+ "version": "7.12.1",
+ "resolved": "https://registry.npmjs.org/@babel/helper-create-class-features-plugin/-/helper-create-class-features-plugin-7.12.1.tgz",
+ "integrity": "sha512-hkL++rWeta/OVOBTRJc9a5Azh5mt5WgZUGAKMD8JM141YsE08K//bp1unBBieO6rUKkIPyUE0USQ30jAy3Sk1w==",
+ "dev": true,
+ "requires": {
+ "@babel/helper-function-name": "^7.10.4",
+ "@babel/helper-member-expression-to-functions": "^7.12.1",
+ "@babel/helper-optimise-call-expression": "^7.10.4",
+ "@babel/helper-replace-supers": "^7.12.1",
+ "@babel/helper-split-export-declaration": "^7.10.4"
+ },
+ "dependencies": {
+ "@babel/code-frame": {
+ "version": "7.10.4",
+ "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.10.4.tgz",
+ "integrity": "sha512-vG6SvB6oYEhvgisZNFRmRCUkLz11c7rp+tbNTynGqc6mS1d5ATd/sGyV6W0KZZnXRKMTzZDRgQT3Ou9jhpAfUg==",
+ "dev": true,
+ "requires": {
+ "@babel/highlight": "^7.10.4"
+ }
+ },
+ "@babel/helper-function-name": {
+ "version": "7.10.4",
+ "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.10.4.tgz",
+ "integrity": "sha512-YdaSyz1n8gY44EmN7x44zBn9zQ1Ry2Y+3GTA+3vH6Mizke1Vw0aWDM66FOYEPw8//qKkmqOckrGgTYa+6sceqQ==",
+ "dev": true,
+ "requires": {
+ "@babel/helper-get-function-arity": "^7.10.4",
+ "@babel/template": "^7.10.4",
+ "@babel/types": "^7.10.4"
+ }
+ },
+ "@babel/helper-get-function-arity": {
+ "version": "7.10.4",
+ "resolved": "https://registry.npmjs.org/@babel/helper-get-function-arity/-/helper-get-function-arity-7.10.4.tgz",
+ "integrity": "sha512-EkN3YDB+SRDgiIUnNgcmiD361ti+AVbL3f3Henf6dqqUyr5dMsorno0lJWJuLhDhkI5sYEpgj6y9kB8AOU1I2A==",
+ "dev": true,
+ "requires": {
+ "@babel/types": "^7.10.4"
+ }
+ },
+ "@babel/helper-split-export-declaration": {
+ "version": "7.11.0",
+ "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.11.0.tgz",
+ "integrity": "sha512-74Vejvp6mHkGE+m+k5vHY93FX2cAtrw1zXrZXRlG4l410Nm9PxfEiVTn1PjDPV5SnmieiueY4AFg2xqhNFuuZg==",
+ "dev": true,
+ "requires": {
+ "@babel/types": "^7.11.0"
+ }
+ },
+ "@babel/highlight": {
+ "version": "7.10.4",
+ "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.10.4.tgz",
+ "integrity": "sha512-i6rgnR/YgPEQzZZnbTHHuZdlE8qyoBNalD6F+q4vAFlcMEcqmkoG+mPqJYJCo63qPf74+Y1UZsl3l6f7/RIkmA==",
+ "dev": true,
+ "requires": {
+ "@babel/helper-validator-identifier": "^7.10.4",
+ "chalk": "^2.0.0",
+ "js-tokens": "^4.0.0"
+ }
+ },
+ "@babel/parser": {
+ "version": "7.12.3",
+ "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.12.3.tgz",
+ "integrity": "sha512-kFsOS0IbsuhO5ojF8Hc8z/8vEIOkylVBrjiZUbLTE3XFe0Qi+uu6HjzQixkFaqr0ZPAMZcBVxEwmsnsLPZ2Xsw==",
+ "dev": true
+ },
+ "@babel/template": {
+ "version": "7.10.4",
+ "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.10.4.tgz",
+ "integrity": "sha512-ZCjD27cGJFUB6nmCB1Enki3r+L5kJveX9pq1SvAUKoICy6CZ9yD8xO086YXdYhvNjBdnekm4ZnaP5yC8Cs/1tA==",
+ "dev": true,
+ "requires": {
+ "@babel/code-frame": "^7.10.4",
+ "@babel/parser": "^7.10.4",
+ "@babel/types": "^7.10.4"
+ }
+ },
+ "@babel/types": {
+ "version": "7.12.1",
+ "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.12.1.tgz",
+ "integrity": "sha512-BzSY3NJBKM4kyatSOWh3D/JJ2O3CVzBybHWxtgxnggaxEuaSTTDqeiSb/xk9lrkw2Tbqyivw5ZU4rT+EfznQsA==",
+ "dev": true,
+ "requires": {
+ "@babel/helper-validator-identifier": "^7.10.4",
+ "lodash": "^4.17.19",
+ "to-fast-properties": "^2.0.0"
+ }
+ },
+ "lodash": {
+ "version": "4.17.20",
+ "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.20.tgz",
+ "integrity": "sha512-PlhdFcillOINfeV7Ni6oF1TAEayyZBoZ8bcshTHqOYJYlrqzRK5hagpagky5o4HfCzzd1TRkXPMFq6cKk9rGmA==",
+ "dev": true
+ }
+ }
+ },
+ "@babel/helper-function-name": {
+ "version": "7.8.3",
+ "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.8.3.tgz",
+ "integrity": "sha512-BCxgX1BC2hD/oBlIFUgOCQDOPV8nSINxCwM3o93xP4P9Fq6aV5sgv2cOOITDMtCfQ+3PvHp3l689XZvAM9QyOA==",
+ "dev": true,
+ "requires": {
+ "@babel/helper-get-function-arity": "^7.8.3",
+ "@babel/template": "^7.8.3",
+ "@babel/types": "^7.8.3"
+ }
+ },
+ "@babel/helper-get-function-arity": {
+ "version": "7.8.3",
+ "resolved": "https://registry.npmjs.org/@babel/helper-get-function-arity/-/helper-get-function-arity-7.8.3.tgz",
+ "integrity": "sha512-FVDR+Gd9iLjUMY1fzE2SR0IuaJToR4RkCDARVfsBBPSP53GEqSFjD8gNyxg246VUyc/ALRxFaAK8rVG7UT7xRA==",
+ "dev": true,
+ "requires": {
+ "@babel/types": "^7.8.3"
+ }
+ },
+ "@babel/helper-member-expression-to-functions": {
+ "version": "7.12.1",
+ "resolved": "https://registry.npmjs.org/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.12.1.tgz",
+ "integrity": "sha512-k0CIe3tXUKTRSoEx1LQEPFU9vRQfqHtl+kf8eNnDqb4AUJEy5pz6aIiog+YWtVm2jpggjS1laH68bPsR+KWWPQ==",
+ "dev": true,
+ "requires": {
+ "@babel/types": "^7.12.1"
+ },
+ "dependencies": {
+ "@babel/types": {
+ "version": "7.12.1",
+ "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.12.1.tgz",
+ "integrity": "sha512-BzSY3NJBKM4kyatSOWh3D/JJ2O3CVzBybHWxtgxnggaxEuaSTTDqeiSb/xk9lrkw2Tbqyivw5ZU4rT+EfznQsA==",
+ "dev": true,
+ "requires": {
+ "@babel/helper-validator-identifier": "^7.10.4",
+ "lodash": "^4.17.19",
+ "to-fast-properties": "^2.0.0"
+ }
+ },
+ "lodash": {
+ "version": "4.17.20",
+ "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.20.tgz",
+ "integrity": "sha512-PlhdFcillOINfeV7Ni6oF1TAEayyZBoZ8bcshTHqOYJYlrqzRK5hagpagky5o4HfCzzd1TRkXPMFq6cKk9rGmA==",
+ "dev": true
+ }
+ }
+ },
+ "@babel/helper-optimise-call-expression": {
+ "version": "7.10.4",
+ "resolved": "https://registry.npmjs.org/@babel/helper-optimise-call-expression/-/helper-optimise-call-expression-7.10.4.tgz",
+ "integrity": "sha512-n3UGKY4VXwXThEiKrgRAoVPBMqeoPgHVqiHZOanAJCG9nQUL2pLRQirUzl0ioKclHGpGqRgIOkgcIJaIWLpygg==",
+ "dev": true,
+ "requires": {
+ "@babel/types": "^7.10.4"
+ },
+ "dependencies": {
+ "@babel/types": {
+ "version": "7.12.1",
+ "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.12.1.tgz",
+ "integrity": "sha512-BzSY3NJBKM4kyatSOWh3D/JJ2O3CVzBybHWxtgxnggaxEuaSTTDqeiSb/xk9lrkw2Tbqyivw5ZU4rT+EfznQsA==",
+ "dev": true,
+ "requires": {
+ "@babel/helper-validator-identifier": "^7.10.4",
+ "lodash": "^4.17.19",
+ "to-fast-properties": "^2.0.0"
+ }
+ },
+ "lodash": {
+ "version": "4.17.20",
+ "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.20.tgz",
+ "integrity": "sha512-PlhdFcillOINfeV7Ni6oF1TAEayyZBoZ8bcshTHqOYJYlrqzRK5hagpagky5o4HfCzzd1TRkXPMFq6cKk9rGmA==",
+ "dev": true
+ }
+ }
+ },
+ "@babel/helper-plugin-utils": {
+ "version": "7.8.3",
+ "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.8.3.tgz",
+ "integrity": "sha512-j+fq49Xds2smCUNYmEHF9kGNkhbet6yVIBp4e6oeQpH1RUs/Ir06xUKzDjDkGcaaokPiTNs2JBWHjaE4csUkZQ==",
+ "dev": true
+ },
+ "@babel/helper-replace-supers": {
+ "version": "7.12.1",
+ "resolved": "https://registry.npmjs.org/@babel/helper-replace-supers/-/helper-replace-supers-7.12.1.tgz",
+ "integrity": "sha512-zJjTvtNJnCFsCXVi5rUInstLd/EIVNmIKA1Q9ynESmMBWPWd+7sdR+G4/wdu+Mppfep0XLyG2m7EBPvjCeFyrw==",
+ "dev": true,
+ "requires": {
+ "@babel/helper-member-expression-to-functions": "^7.12.1",
+ "@babel/helper-optimise-call-expression": "^7.10.4",
+ "@babel/traverse": "^7.12.1",
+ "@babel/types": "^7.12.1"
+ },
+ "dependencies": {
+ "@babel/code-frame": {
+ "version": "7.10.4",
+ "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.10.4.tgz",
+ "integrity": "sha512-vG6SvB6oYEhvgisZNFRmRCUkLz11c7rp+tbNTynGqc6mS1d5ATd/sGyV6W0KZZnXRKMTzZDRgQT3Ou9jhpAfUg==",
+ "dev": true,
+ "requires": {
+ "@babel/highlight": "^7.10.4"
+ }
+ },
+ "@babel/generator": {
+ "version": "7.12.1",
+ "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.12.1.tgz",
+ "integrity": "sha512-DB+6rafIdc9o72Yc3/Ph5h+6hUjeOp66pF0naQBgUFFuPqzQwIlPTm3xZR7YNvduIMtkDIj2t21LSQwnbCrXvg==",
+ "dev": true,
+ "requires": {
+ "@babel/types": "^7.12.1",
+ "jsesc": "^2.5.1",
+ "source-map": "^0.5.0"
+ }
+ },
+ "@babel/helper-function-name": {
+ "version": "7.10.4",
+ "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.10.4.tgz",
+ "integrity": "sha512-YdaSyz1n8gY44EmN7x44zBn9zQ1Ry2Y+3GTA+3vH6Mizke1Vw0aWDM66FOYEPw8//qKkmqOckrGgTYa+6sceqQ==",
+ "dev": true,
+ "requires": {
+ "@babel/helper-get-function-arity": "^7.10.4",
+ "@babel/template": "^7.10.4",
+ "@babel/types": "^7.10.4"
+ }
+ },
+ "@babel/helper-get-function-arity": {
+ "version": "7.10.4",
+ "resolved": "https://registry.npmjs.org/@babel/helper-get-function-arity/-/helper-get-function-arity-7.10.4.tgz",
+ "integrity": "sha512-EkN3YDB+SRDgiIUnNgcmiD361ti+AVbL3f3Henf6dqqUyr5dMsorno0lJWJuLhDhkI5sYEpgj6y9kB8AOU1I2A==",
+ "dev": true,
+ "requires": {
+ "@babel/types": "^7.10.4"
+ }
+ },
+ "@babel/helper-split-export-declaration": {
+ "version": "7.11.0",
+ "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.11.0.tgz",
+ "integrity": "sha512-74Vejvp6mHkGE+m+k5vHY93FX2cAtrw1zXrZXRlG4l410Nm9PxfEiVTn1PjDPV5SnmieiueY4AFg2xqhNFuuZg==",
+ "dev": true,
+ "requires": {
+ "@babel/types": "^7.11.0"
+ }
+ },
+ "@babel/highlight": {
+ "version": "7.10.4",
+ "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.10.4.tgz",
+ "integrity": "sha512-i6rgnR/YgPEQzZZnbTHHuZdlE8qyoBNalD6F+q4vAFlcMEcqmkoG+mPqJYJCo63qPf74+Y1UZsl3l6f7/RIkmA==",
+ "dev": true,
+ "requires": {
+ "@babel/helper-validator-identifier": "^7.10.4",
+ "chalk": "^2.0.0",
+ "js-tokens": "^4.0.0"
+ }
+ },
+ "@babel/parser": {
+ "version": "7.12.3",
+ "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.12.3.tgz",
+ "integrity": "sha512-kFsOS0IbsuhO5ojF8Hc8z/8vEIOkylVBrjiZUbLTE3XFe0Qi+uu6HjzQixkFaqr0ZPAMZcBVxEwmsnsLPZ2Xsw==",
+ "dev": true
+ },
+ "@babel/template": {
+ "version": "7.10.4",
+ "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.10.4.tgz",
+ "integrity": "sha512-ZCjD27cGJFUB6nmCB1Enki3r+L5kJveX9pq1SvAUKoICy6CZ9yD8xO086YXdYhvNjBdnekm4ZnaP5yC8Cs/1tA==",
+ "dev": true,
+ "requires": {
+ "@babel/code-frame": "^7.10.4",
+ "@babel/parser": "^7.10.4",
+ "@babel/types": "^7.10.4"
+ }
+ },
+ "@babel/traverse": {
+ "version": "7.12.1",
+ "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.12.1.tgz",
+ "integrity": "sha512-MA3WPoRt1ZHo2ZmoGKNqi20YnPt0B1S0GTZEPhhd+hw2KGUzBlHuVunj6K4sNuK+reEvyiPwtp0cpaqLzJDmAw==",
+ "dev": true,
+ "requires": {
+ "@babel/code-frame": "^7.10.4",
+ "@babel/generator": "^7.12.1",
+ "@babel/helper-function-name": "^7.10.4",
+ "@babel/helper-split-export-declaration": "^7.11.0",
+ "@babel/parser": "^7.12.1",
+ "@babel/types": "^7.12.1",
+ "debug": "^4.1.0",
+ "globals": "^11.1.0",
+ "lodash": "^4.17.19"
+ }
+ },
+ "@babel/types": {
+ "version": "7.12.1",
+ "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.12.1.tgz",
+ "integrity": "sha512-BzSY3NJBKM4kyatSOWh3D/JJ2O3CVzBybHWxtgxnggaxEuaSTTDqeiSb/xk9lrkw2Tbqyivw5ZU4rT+EfznQsA==",
+ "dev": true,
+ "requires": {
+ "@babel/helper-validator-identifier": "^7.10.4",
+ "lodash": "^4.17.19",
+ "to-fast-properties": "^2.0.0"
+ }
+ },
+ "lodash": {
+ "version": "4.17.20",
+ "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.20.tgz",
+ "integrity": "sha512-PlhdFcillOINfeV7Ni6oF1TAEayyZBoZ8bcshTHqOYJYlrqzRK5hagpagky5o4HfCzzd1TRkXPMFq6cKk9rGmA==",
+ "dev": true
+ }
+ }
+ },
+ "@babel/helper-split-export-declaration": {
+ "version": "7.8.3",
+ "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.8.3.tgz",
+ "integrity": "sha512-3x3yOeyBhW851hroze7ElzdkeRXQYQbFIb7gLK1WQYsw2GWDay5gAJNw1sWJ0VFP6z5J1whqeXH/WCdCjZv6dA==",
+ "dev": true,
+ "requires": {
+ "@babel/types": "^7.8.3"
+ }
+ },
+ "@babel/helper-validator-identifier": {
+ "version": "7.10.4",
+ "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.10.4.tgz",
+ "integrity": "sha512-3U9y+43hz7ZM+rzG24Qe2mufW5KhvFg/NhnNph+i9mgCtdTCtMJuI1TMkrIUiK7Ix4PYlRF9I5dhqaLYA/ADXw==",
+ "dev": true
+ },
+ "@babel/helpers": {
+ "version": "7.8.4",
+ "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.8.4.tgz",
+ "integrity": "sha512-VPbe7wcQ4chu4TDQjimHv/5tj73qz88o12EPkO2ValS2QiQS/1F2SsjyIGNnAD0vF/nZS6Cf9i+vW6HIlnaR8w==",
+ "dev": true,
+ "requires": {
+ "@babel/template": "^7.8.3",
+ "@babel/traverse": "^7.8.4",
+ "@babel/types": "^7.8.3"
+ }
+ },
+ "@babel/highlight": {
+ "version": "7.8.3",
+ "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.8.3.tgz",
+ "integrity": "sha512-PX4y5xQUvy0fnEVHrYOarRPXVWafSjTW9T0Hab8gVIawpl2Sj0ORyrygANq+KjcNlSSTw0YCLSNA8OyZ1I4yEg==",
+ "dev": true,
+ "requires": {
+ "chalk": "^2.0.0",
+ "esutils": "^2.0.2",
+ "js-tokens": "^4.0.0"
+ }
+ },
+ "@babel/parser": {
+ "version": "7.8.4",
+ "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.8.4.tgz",
+ "integrity": "sha512-0fKu/QqildpXmPVaRBoXOlyBb3MC+J0A66x97qEfLOMkn3u6nfY5esWogQwi/K0BjASYy4DbnsEWnpNL6qT5Mw==",
+ "dev": true
+ },
+ "@babel/plugin-proposal-class-properties": {
+ "version": "7.10.4",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-class-properties/-/plugin-proposal-class-properties-7.10.4.tgz",
+ "integrity": "sha512-vhwkEROxzcHGNu2mzUC0OFFNXdZ4M23ib8aRRcJSsW8BZK9pQMD7QB7csl97NBbgGZO7ZyHUyKDnxzOaP4IrCg==",
+ "dev": true,
+ "requires": {
+ "@babel/helper-create-class-features-plugin": "^7.10.4",
+ "@babel/helper-plugin-utils": "^7.10.4"
+ },
+ "dependencies": {
+ "@babel/helper-plugin-utils": {
+ "version": "7.10.4",
+ "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.10.4.tgz",
+ "integrity": "sha512-O4KCvQA6lLiMU9l2eawBPMf1xPP8xPfB3iEQw150hOVTqj/rfXz0ThTb4HEzqQfs2Bmo5Ay8BzxfzVtBrr9dVg==",
+ "dev": true
+ }
+ }
+ },
+ "@babel/plugin-proposal-nullish-coalescing-operator": {
+ "version": "7.8.3",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-nullish-coalescing-operator/-/plugin-proposal-nullish-coalescing-operator-7.8.3.tgz",
+ "integrity": "sha512-TS9MlfzXpXKt6YYomudb/KU7nQI6/xnapG6in1uZxoxDghuSMZsPb6D2fyUwNYSAp4l1iR7QtFOjkqcRYcUsfw==",
+ "dev": true,
+ "requires": {
+ "@babel/helper-plugin-utils": "^7.8.3",
+ "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.0"
+ }
+ },
+ "@babel/plugin-proposal-optional-chaining": {
+ "version": "7.9.0",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-optional-chaining/-/plugin-proposal-optional-chaining-7.9.0.tgz",
+ "integrity": "sha512-NDn5tu3tcv4W30jNhmc2hyD5c56G6cXx4TesJubhxrJeCvuuMpttxr0OnNCqbZGhFjLrg+NIhxxC+BK5F6yS3w==",
+ "dev": true,
+ "requires": {
+ "@babel/helper-plugin-utils": "^7.8.3",
+ "@babel/plugin-syntax-optional-chaining": "^7.8.0"
+ }
+ },
+ "@babel/plugin-syntax-jsx": {
+ "version": "7.8.3",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.8.3.tgz",
+ "integrity": "sha512-WxdW9xyLgBdefoo0Ynn3MRSkhe5tFVxxKNVdnZSh318WrG2e2jH+E9wd/++JsqcLJZPfz87njQJ8j2Upjm0M0A==",
+ "dev": true,
+ "requires": {
+ "@babel/helper-plugin-utils": "^7.8.3"
+ }
+ },
+ "@babel/plugin-syntax-nullish-coalescing-operator": {
+ "version": "7.8.3",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-nullish-coalescing-operator/-/plugin-syntax-nullish-coalescing-operator-7.8.3.tgz",
+ "integrity": "sha512-aSff4zPII1u2QD7y+F8oDsz19ew4IGEJg9SVW+bqwpwtfFleiQDMdzA/R+UlWDzfnHFCxxleFT0PMIrR36XLNQ==",
+ "dev": true,
+ "requires": {
+ "@babel/helper-plugin-utils": "^7.8.0"
+ }
+ },
+ "@babel/plugin-syntax-optional-chaining": {
+ "version": "7.8.3",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-chaining/-/plugin-syntax-optional-chaining-7.8.3.tgz",
+ "integrity": "sha512-KoK9ErH1MBlCPxV0VANkXW2/dw4vlbGDrFgz8bmUsBGYkFRcbRwMh6cIJubdPrkxRwuGdtCk0v/wPTKbQgBjkg==",
+ "dev": true,
+ "requires": {
+ "@babel/helper-plugin-utils": "^7.8.0"
+ }
+ },
+ "@babel/plugin-transform-react-display-name": {
+ "version": "7.8.3",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-display-name/-/plugin-transform-react-display-name-7.8.3.tgz",
+ "integrity": "sha512-3Jy/PCw8Fe6uBKtEgz3M82ljt+lTg+xJaM4og+eyu83qLT87ZUSckn0wy7r31jflURWLO83TW6Ylf7lyXj3m5A==",
+ "dev": true,
+ "requires": {
+ "@babel/helper-plugin-utils": "^7.8.3"
+ }
+ },
+ "@babel/plugin-transform-react-jsx": {
+ "version": "7.8.3",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx/-/plugin-transform-react-jsx-7.8.3.tgz",
+ "integrity": "sha512-r0h+mUiyL595ikykci+fbwm9YzmuOrUBi0b+FDIKmi3fPQyFokWVEMJnRWHJPPQEjyFJyna9WZC6Viv6UHSv1g==",
+ "dev": true,
+ "requires": {
+ "@babel/helper-builder-react-jsx": "^7.8.3",
+ "@babel/helper-plugin-utils": "^7.8.3",
+ "@babel/plugin-syntax-jsx": "^7.8.3"
+ }
+ },
+ "@babel/plugin-transform-react-jsx-self": {
+ "version": "7.8.3",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-self/-/plugin-transform-react-jsx-self-7.8.3.tgz",
+ "integrity": "sha512-01OT7s5oa0XTLf2I8XGsL8+KqV9lx3EZV+jxn/L2LQ97CGKila2YMroTkCEIE0HV/FF7CMSRsIAybopdN9NTdg==",
+ "dev": true,
+ "requires": {
+ "@babel/helper-plugin-utils": "^7.8.3",
+ "@babel/plugin-syntax-jsx": "^7.8.3"
+ }
+ },
+ "@babel/plugin-transform-react-jsx-source": {
+ "version": "7.8.3",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.8.3.tgz",
+ "integrity": "sha512-PLMgdMGuVDtRS/SzjNEQYUT8f4z1xb2BAT54vM1X5efkVuYBf5WyGUMbpmARcfq3NaglIwz08UVQK4HHHbC6ag==",
+ "dev": true,
+ "requires": {
+ "@babel/helper-plugin-utils": "^7.8.3",
+ "@babel/plugin-syntax-jsx": "^7.8.3"
+ }
+ },
+ "@babel/preset-react": {
+ "version": "7.8.3",
+ "resolved": "https://registry.npmjs.org/@babel/preset-react/-/preset-react-7.8.3.tgz",
+ "integrity": "sha512-9hx0CwZg92jGb7iHYQVgi0tOEHP/kM60CtWJQnmbATSPIQQ2xYzfoCI3EdqAhFBeeJwYMdWQuDUHMsuDbH9hyQ==",
+ "dev": true,
+ "requires": {
+ "@babel/helper-plugin-utils": "^7.8.3",
+ "@babel/plugin-transform-react-display-name": "^7.8.3",
+ "@babel/plugin-transform-react-jsx": "^7.8.3",
+ "@babel/plugin-transform-react-jsx-self": "^7.8.3",
+ "@babel/plugin-transform-react-jsx-source": "^7.8.3"
+ }
+ },
+ "@babel/runtime": {
+ "version": "7.8.4",
+ "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.8.4.tgz",
+ "integrity": "sha512-neAp3zt80trRVBI1x0azq6c57aNBqYZH8KhMm3TaB7wEI5Q4A2SHfBHE8w9gOhI/lrqxtEbXZgQIrHP+wvSGwQ==",
+ "requires": {
+ "regenerator-runtime": "^0.13.2"
+ }
+ },
+ "@babel/template": {
+ "version": "7.8.3",
+ "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.8.3.tgz",
+ "integrity": "sha512-04m87AcQgAFdvuoyiQ2kgELr2tV8B4fP/xJAVUL3Yb3bkNdMedD3d0rlSQr3PegP0cms3eHjl1F7PWlvWbU8FQ==",
+ "dev": true,
+ "requires": {
+ "@babel/code-frame": "^7.8.3",
+ "@babel/parser": "^7.8.3",
+ "@babel/types": "^7.8.3"
+ }
+ },
+ "@babel/traverse": {
+ "version": "7.8.4",
+ "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.8.4.tgz",
+ "integrity": "sha512-NGLJPZwnVEyBPLI+bl9y9aSnxMhsKz42so7ApAv9D+b4vAFPpY013FTS9LdKxcABoIYFU52HcYga1pPlx454mg==",
+ "dev": true,
+ "requires": {
+ "@babel/code-frame": "^7.8.3",
+ "@babel/generator": "^7.8.4",
+ "@babel/helper-function-name": "^7.8.3",
+ "@babel/helper-split-export-declaration": "^7.8.3",
+ "@babel/parser": "^7.8.4",
+ "@babel/types": "^7.8.3",
+ "debug": "^4.1.0",
+ "globals": "^11.1.0",
+ "lodash": "^4.17.13"
+ }
+ },
+ "@babel/types": {
+ "version": "7.8.3",
+ "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.8.3.tgz",
+ "integrity": "sha512-jBD+G8+LWpMBBWvVcdr4QysjUE4mU/syrhN17o1u3gx0/WzJB1kwiVZAXRtWbsIPOwW8pF/YJV5+nmetPzepXg==",
+ "dev": true,
+ "requires": {
+ "esutils": "^2.0.2",
+ "lodash": "^4.17.13",
+ "to-fast-properties": "^2.0.0"
+ }
+ },
+ "@sinonjs/commons": {
+ "version": "1.7.1",
+ "resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-1.7.1.tgz",
+ "integrity": "sha512-Debi3Baff1Qu1Unc3mjJ96MgpbwTn43S1+9yJ0llWygPwDNu2aaWBD6yc9y/Z8XDRNhx7U+u2UDg2OGQXkclUQ==",
+ "dev": true,
+ "requires": {
+ "type-detect": "4.0.8"
+ }
+ },
+ "@sinonjs/formatio": {
+ "version": "3.2.2",
+ "resolved": "https://registry.npmjs.org/@sinonjs/formatio/-/formatio-3.2.2.tgz",
+ "integrity": "sha512-B8SEsgd8gArBLMD6zpRw3juQ2FVSsmdd7qlevyDqzS9WTCtvF55/gAL+h6gue8ZvPYcdiPdvueM/qm//9XzyTQ==",
+ "dev": true,
+ "requires": {
+ "@sinonjs/commons": "^1",
+ "@sinonjs/samsam": "^3.1.0"
+ }
+ },
+ "@sinonjs/samsam": {
+ "version": "3.3.3",
+ "resolved": "https://registry.npmjs.org/@sinonjs/samsam/-/samsam-3.3.3.tgz",
+ "integrity": "sha512-bKCMKZvWIjYD0BLGnNrxVuw4dkWCYsLqFOUWw8VgKF/+5Y+mE7LfHWPIYoDXowH+3a9LsWDMo0uAP8YDosPvHQ==",
+ "dev": true,
+ "requires": {
+ "@sinonjs/commons": "^1.3.0",
+ "array-from": "^2.1.1",
+ "lodash": "^4.17.15"
+ }
+ },
+ "@sinonjs/text-encoding": {
+ "version": "0.7.1",
+ "resolved": "https://registry.npmjs.org/@sinonjs/text-encoding/-/text-encoding-0.7.1.tgz",
+ "integrity": "sha512-+iTbntw2IZPb/anVDbypzfQa+ay64MW0Zo8aJ8gZPWMMK6/OubMVb6lUPMagqjOPnmtauXnFCACVl3O7ogjeqQ==",
+ "dev": true
+ },
+ "@types/node": {
+ "version": "13.7.4",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-13.7.4.tgz",
+ "integrity": "sha512-oVeL12C6gQS/GAExndigSaLxTrKpQPxewx9bOcwfvJiJge4rr7wNaph4J+ns5hrmIV2as5qxqN8YKthn9qh0jw==",
+ "dev": true
+ },
+ "@webassemblyjs/ast": {
+ "version": "1.8.5",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.8.5.tgz",
+ "integrity": "sha512-aJMfngIZ65+t71C3y2nBBg5FFG0Okt9m0XEgWZ7Ywgn1oMAT8cNwx00Uv1cQyHtidq0Xn94R4TAywO+LCQ+ZAQ==",
+ "dev": true,
+ "requires": {
+ "@webassemblyjs/helper-module-context": "1.8.5",
+ "@webassemblyjs/helper-wasm-bytecode": "1.8.5",
+ "@webassemblyjs/wast-parser": "1.8.5"
+ }
+ },
+ "@webassemblyjs/floating-point-hex-parser": {
+ "version": "1.8.5",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/floating-point-hex-parser/-/floating-point-hex-parser-1.8.5.tgz",
+ "integrity": "sha512-9p+79WHru1oqBh9ewP9zW95E3XAo+90oth7S5Re3eQnECGq59ly1Ri5tsIipKGpiStHsUYmY3zMLqtk3gTcOtQ==",
+ "dev": true
+ },
+ "@webassemblyjs/helper-api-error": {
+ "version": "1.8.5",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-api-error/-/helper-api-error-1.8.5.tgz",
+ "integrity": "sha512-Za/tnzsvnqdaSPOUXHyKJ2XI7PDX64kWtURyGiJJZKVEdFOsdKUCPTNEVFZq3zJ2R0G5wc2PZ5gvdTRFgm81zA==",
+ "dev": true
+ },
+ "@webassemblyjs/helper-buffer": {
+ "version": "1.8.5",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-buffer/-/helper-buffer-1.8.5.tgz",
+ "integrity": "sha512-Ri2R8nOS0U6G49Q86goFIPNgjyl6+oE1abW1pS84BuhP1Qcr5JqMwRFT3Ah3ADDDYGEgGs1iyb1DGX+kAi/c/Q==",
+ "dev": true
+ },
+ "@webassemblyjs/helper-code-frame": {
+ "version": "1.8.5",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-code-frame/-/helper-code-frame-1.8.5.tgz",
+ "integrity": "sha512-VQAadSubZIhNpH46IR3yWO4kZZjMxN1opDrzePLdVKAZ+DFjkGD/rf4v1jap744uPVU6yjL/smZbRIIJTOUnKQ==",
+ "dev": true,
+ "requires": {
+ "@webassemblyjs/wast-printer": "1.8.5"
+ }
+ },
+ "@webassemblyjs/helper-fsm": {
+ "version": "1.8.5",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-fsm/-/helper-fsm-1.8.5.tgz",
+ "integrity": "sha512-kRuX/saORcg8se/ft6Q2UbRpZwP4y7YrWsLXPbbmtepKr22i8Z4O3V5QE9DbZK908dh5Xya4Un57SDIKwB9eow==",
+ "dev": true
+ },
+ "@webassemblyjs/helper-module-context": {
+ "version": "1.8.5",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-module-context/-/helper-module-context-1.8.5.tgz",
+ "integrity": "sha512-/O1B236mN7UNEU4t9X7Pj38i4VoU8CcMHyy3l2cV/kIF4U5KoHXDVqcDuOs1ltkac90IM4vZdHc52t1x8Yfs3g==",
+ "dev": true,
+ "requires": {
+ "@webassemblyjs/ast": "1.8.5",
+ "mamacro": "^0.0.3"
+ }
+ },
+ "@webassemblyjs/helper-wasm-bytecode": {
+ "version": "1.8.5",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-bytecode/-/helper-wasm-bytecode-1.8.5.tgz",
+ "integrity": "sha512-Cu4YMYG3Ddl72CbmpjU/wbP6SACcOPVbHN1dI4VJNJVgFwaKf1ppeFJrwydOG3NDHxVGuCfPlLZNyEdIYlQ6QQ==",
+ "dev": true
+ },
+ "@webassemblyjs/helper-wasm-section": {
+ "version": "1.8.5",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-section/-/helper-wasm-section-1.8.5.tgz",
+ "integrity": "sha512-VV083zwR+VTrIWWtgIUpqfvVdK4ff38loRmrdDBgBT8ADXYsEZ5mPQ4Nde90N3UYatHdYoDIFb7oHzMncI02tA==",
+ "dev": true,
+ "requires": {
+ "@webassemblyjs/ast": "1.8.5",
+ "@webassemblyjs/helper-buffer": "1.8.5",
+ "@webassemblyjs/helper-wasm-bytecode": "1.8.5",
+ "@webassemblyjs/wasm-gen": "1.8.5"
+ }
+ },
+ "@webassemblyjs/ieee754": {
+ "version": "1.8.5",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/ieee754/-/ieee754-1.8.5.tgz",
+ "integrity": "sha512-aaCvQYrvKbY/n6wKHb/ylAJr27GglahUO89CcGXMItrOBqRarUMxWLJgxm9PJNuKULwN5n1csT9bYoMeZOGF3g==",
+ "dev": true,
+ "requires": {
+ "@xtuc/ieee754": "^1.2.0"
+ }
+ },
+ "@webassemblyjs/leb128": {
+ "version": "1.8.5",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/leb128/-/leb128-1.8.5.tgz",
+ "integrity": "sha512-plYUuUwleLIziknvlP8VpTgO4kqNaH57Y3JnNa6DLpu/sGcP6hbVdfdX5aHAV716pQBKrfuU26BJK29qY37J7A==",
+ "dev": true,
+ "requires": {
+ "@xtuc/long": "4.2.2"
+ }
+ },
+ "@webassemblyjs/utf8": {
+ "version": "1.8.5",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/utf8/-/utf8-1.8.5.tgz",
+ "integrity": "sha512-U7zgftmQriw37tfD934UNInokz6yTmn29inT2cAetAsaU9YeVCveWEwhKL1Mg4yS7q//NGdzy79nlXh3bT8Kjw==",
+ "dev": true
+ },
+ "@webassemblyjs/wasm-edit": {
+ "version": "1.8.5",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-edit/-/wasm-edit-1.8.5.tgz",
+ "integrity": "sha512-A41EMy8MWw5yvqj7MQzkDjU29K7UJq1VrX2vWLzfpRHt3ISftOXqrtojn7nlPsZ9Ijhp5NwuODuycSvfAO/26Q==",
+ "dev": true,
+ "requires": {
+ "@webassemblyjs/ast": "1.8.5",
+ "@webassemblyjs/helper-buffer": "1.8.5",
+ "@webassemblyjs/helper-wasm-bytecode": "1.8.5",
+ "@webassemblyjs/helper-wasm-section": "1.8.5",
+ "@webassemblyjs/wasm-gen": "1.8.5",
+ "@webassemblyjs/wasm-opt": "1.8.5",
+ "@webassemblyjs/wasm-parser": "1.8.5",
+ "@webassemblyjs/wast-printer": "1.8.5"
+ }
+ },
+ "@webassemblyjs/wasm-gen": {
+ "version": "1.8.5",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-gen/-/wasm-gen-1.8.5.tgz",
+ "integrity": "sha512-BCZBT0LURC0CXDzj5FXSc2FPTsxwp3nWcqXQdOZE4U7h7i8FqtFK5Egia6f9raQLpEKT1VL7zr4r3+QX6zArWg==",
+ "dev": true,
+ "requires": {
+ "@webassemblyjs/ast": "1.8.5",
+ "@webassemblyjs/helper-wasm-bytecode": "1.8.5",
+ "@webassemblyjs/ieee754": "1.8.5",
+ "@webassemblyjs/leb128": "1.8.5",
+ "@webassemblyjs/utf8": "1.8.5"
+ }
+ },
+ "@webassemblyjs/wasm-opt": {
+ "version": "1.8.5",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-opt/-/wasm-opt-1.8.5.tgz",
+ "integrity": "sha512-HKo2mO/Uh9A6ojzu7cjslGaHaUU14LdLbGEKqTR7PBKwT6LdPtLLh9fPY33rmr5wcOMrsWDbbdCHq4hQUdd37Q==",
+ "dev": true,
+ "requires": {
+ "@webassemblyjs/ast": "1.8.5",
+ "@webassemblyjs/helper-buffer": "1.8.5",
+ "@webassemblyjs/wasm-gen": "1.8.5",
+ "@webassemblyjs/wasm-parser": "1.8.5"
+ }
+ },
+ "@webassemblyjs/wasm-parser": {
+ "version": "1.8.5",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-parser/-/wasm-parser-1.8.5.tgz",
+ "integrity": "sha512-pi0SYE9T6tfcMkthwcgCpL0cM9nRYr6/6fjgDtL6q/ZqKHdMWvxitRi5JcZ7RI4SNJJYnYNaWy5UUrHQy998lw==",
+ "dev": true,
+ "requires": {
+ "@webassemblyjs/ast": "1.8.5",
+ "@webassemblyjs/helper-api-error": "1.8.5",
+ "@webassemblyjs/helper-wasm-bytecode": "1.8.5",
+ "@webassemblyjs/ieee754": "1.8.5",
+ "@webassemblyjs/leb128": "1.8.5",
+ "@webassemblyjs/utf8": "1.8.5"
+ }
+ },
+ "@webassemblyjs/wast-parser": {
+ "version": "1.8.5",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/wast-parser/-/wast-parser-1.8.5.tgz",
+ "integrity": "sha512-daXC1FyKWHF1i11obK086QRlsMsY4+tIOKgBqI1lxAnkp9xe9YMcgOxm9kLe+ttjs5aWV2KKE1TWJCN57/Btsg==",
+ "dev": true,
+ "requires": {
+ "@webassemblyjs/ast": "1.8.5",
+ "@webassemblyjs/floating-point-hex-parser": "1.8.5",
+ "@webassemblyjs/helper-api-error": "1.8.5",
+ "@webassemblyjs/helper-code-frame": "1.8.5",
+ "@webassemblyjs/helper-fsm": "1.8.5",
+ "@xtuc/long": "4.2.2"
+ }
+ },
+ "@webassemblyjs/wast-printer": {
+ "version": "1.8.5",
+ "resolved": "https://registry.npmjs.org/@webassemblyjs/wast-printer/-/wast-printer-1.8.5.tgz",
+ "integrity": "sha512-w0U0pD4EhlnvRyeJzBqaVSJAo9w/ce7/WPogeXLzGkO6hzhr4GnQIZ4W4uUt5b9ooAaXPtnXlj0gzsXEOUNYMg==",
+ "dev": true,
+ "requires": {
+ "@webassemblyjs/ast": "1.8.5",
+ "@webassemblyjs/wast-parser": "1.8.5",
+ "@xtuc/long": "4.2.2"
+ }
+ },
+ "@xtuc/ieee754": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/@xtuc/ieee754/-/ieee754-1.2.0.tgz",
+ "integrity": "sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA==",
+ "dev": true
+ },
+ "@xtuc/long": {
+ "version": "4.2.2",
+ "resolved": "https://registry.npmjs.org/@xtuc/long/-/long-4.2.2.tgz",
+ "integrity": "sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==",
+ "dev": true
+ },
+ "abbrev": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz",
+ "integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==",
+ "dev": true
+ },
+ "accepts": {
+ "version": "1.3.7",
+ "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.7.tgz",
+ "integrity": "sha512-Il80Qs2WjYlJIBNzNkK6KYqlVMTbZLXgHx2oT0pU/fjRHyEp+PEfEPY0R3WCwAGVOtauxh1hOxNgIf5bv7dQpA==",
+ "dev": true,
+ "requires": {
+ "mime-types": "~2.1.24",
+ "negotiator": "0.6.2"
+ }
+ },
+ "acorn": {
+ "version": "7.1.0",
+ "resolved": "https://registry.npmjs.org/acorn/-/acorn-7.1.0.tgz",
+ "integrity": "sha512-kL5CuoXA/dgxlBbVrflsflzQ3PAas7RYZB52NOm/6839iVYJgKMJ3cQJD+t2i5+qFa8h3MDpEOJiS64E8JLnSQ==",
+ "dev": true
+ },
+ "acorn-jsx": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-3.0.1.tgz",
+ "integrity": "sha1-r9+UiPsezvyDSPb7IvRk4ypYs2s=",
+ "dev": true,
+ "requires": {
+ "acorn": "^3.0.4"
+ },
+ "dependencies": {
+ "acorn": {
+ "version": "3.3.0",
+ "resolved": "https://registry.npmjs.org/acorn/-/acorn-3.3.0.tgz",
+ "integrity": "sha1-ReN/s56No/JbruP/U2niu18iAXo=",
+ "dev": true
+ }
+ }
+ },
+ "after": {
+ "version": "0.8.2",
+ "resolved": "https://registry.npmjs.org/after/-/after-0.8.2.tgz",
+ "integrity": "sha1-/ts5T58OAqqXaOcCvaI7UF+ufh8=",
+ "dev": true
+ },
+ "airbnb-prop-types": {
+ "version": "2.15.0",
+ "resolved": "https://registry.npmjs.org/airbnb-prop-types/-/airbnb-prop-types-2.15.0.tgz",
+ "integrity": "sha512-jUh2/hfKsRjNFC4XONQrxo/n/3GG4Tn6Hl0WlFQN5PY9OMC9loSCoAYKnZsWaP8wEfd5xcrPloK0Zg6iS1xwVA==",
+ "dev": true,
+ "requires": {
+ "array.prototype.find": "^2.1.0",
+ "function.prototype.name": "^1.1.1",
+ "has": "^1.0.3",
+ "is-regex": "^1.0.4",
+ "object-is": "^1.0.1",
+ "object.assign": "^4.1.0",
+ "object.entries": "^1.1.0",
+ "prop-types": "^15.7.2",
+ "prop-types-exact": "^1.2.0",
+ "react-is": "^16.9.0"
+ }
+ },
+ "ajv": {
+ "version": "5.5.2",
+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-5.5.2.tgz",
+ "integrity": "sha1-c7Xuyj+rZT49P5Qis0GtQiBdyWU=",
+ "dev": true,
+ "requires": {
+ "co": "^4.6.0",
+ "fast-deep-equal": "^1.0.0",
+ "fast-json-stable-stringify": "^2.0.0",
+ "json-schema-traverse": "^0.3.0"
+ }
+ },
+ "ajv-errors": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/ajv-errors/-/ajv-errors-1.0.1.tgz",
+ "integrity": "sha512-DCRfO/4nQ+89p/RK43i8Ezd41EqdGIU4ld7nGF8OQ14oc/we5rEntLCUa7+jrn3nn83BosfwZA0wb4pon2o8iQ==",
+ "dev": true
+ },
+ "ajv-keywords": {
+ "version": "3.4.1",
+ "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-3.4.1.tgz",
+ "integrity": "sha512-RO1ibKvd27e6FEShVFfPALuHI3WjSVNeK5FIsmme/LYRNxjKuNj+Dt7bucLa6NdSv3JcVTyMlm9kGR84z1XpaQ==",
+ "dev": true
+ },
+ "amdefine": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/amdefine/-/amdefine-1.0.1.tgz",
+ "integrity": "sha1-SlKCrBZHKek2Gbz9OtFR+BfOkfU=",
+ "dev": true
+ },
+ "ansi-colors": {
+ "version": "3.2.4",
+ "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-3.2.4.tgz",
+ "integrity": "sha512-hHUXGagefjN2iRrID63xckIvotOXOojhQKWIPUZ4mNUZ9nLZW+7FMNoE1lOkEhNWYsx/7ysGIuJYCiMAA9FnrA==",
+ "dev": true
+ },
+ "ansi-escapes": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-1.4.0.tgz",
+ "integrity": "sha1-06ioOzGapneTZisT52HHkRQiMG4=",
+ "dev": true
+ },
+ "ansi-regex": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz",
+ "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=",
+ "dev": true
+ },
+ "ansi-styles": {
+ "version": "3.2.1",
+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz",
+ "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==",
+ "dev": true,
+ "requires": {
+ "color-convert": "^1.9.0"
+ }
+ },
+ "anymatch": {
+ "version": "1.3.2",
+ "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-1.3.2.tgz",
+ "integrity": "sha512-0XNayC8lTHQ2OI8aljNCN3sSx6hsr/1+rlcDAotXJR7C1oZZHCNsfpbKwMjRA3Uqb5tF1Rae2oloTr4xpq+WjA==",
+ "dev": true,
+ "requires": {
+ "micromatch": "^2.1.5",
+ "normalize-path": "^2.0.0"
+ }
+ },
+ "append-transform": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/append-transform/-/append-transform-1.0.0.tgz",
+ "integrity": "sha512-P009oYkeHyU742iSZJzZZywj4QRJdnTWffaKuJQLablCZ1uz6/cW4yaRgcDaoQ+uwOxxnt0gRUcwfsNP2ri0gw==",
+ "dev": true,
+ "requires": {
+ "default-require-extensions": "^2.0.0"
+ }
+ },
+ "aproba": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/aproba/-/aproba-1.2.0.tgz",
+ "integrity": "sha512-Y9J6ZjXtoYh8RnXVCMOU/ttDmk1aBjunq9vO0ta5x85WDQiQfUF9sIPBITdbiiIVcBo03Hi3jMxigBtsddlXRw==",
+ "dev": true
+ },
+ "are-we-there-yet": {
+ "version": "1.1.5",
+ "resolved": "https://registry.npmjs.org/are-we-there-yet/-/are-we-there-yet-1.1.5.tgz",
+ "integrity": "sha512-5hYdAkZlcG8tOLujVDTgCT+uPX0VnpAH28gWsLfzpXYm7wP6mp5Q/gYyR7YQ0cKVJcXJnl3j2kpBan13PtQf6w==",
+ "dev": true,
+ "requires": {
+ "delegates": "^1.0.0",
+ "readable-stream": "^2.0.6"
+ }
+ },
+ "argparse": {
+ "version": "1.0.10",
+ "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz",
+ "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==",
+ "dev": true,
+ "requires": {
+ "sprintf-js": "~1.0.2"
+ }
+ },
+ "arr-diff": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-2.0.0.tgz",
+ "integrity": "sha1-jzuCf5Vai9ZpaX5KQlasPOrjVs8=",
+ "dev": true,
+ "requires": {
+ "arr-flatten": "^1.0.1"
+ }
+ },
+ "arr-flatten": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/arr-flatten/-/arr-flatten-1.1.0.tgz",
+ "integrity": "sha512-L3hKV5R/p5o81R7O02IGnwpDmkp6E982XhtbuwSe3O4qOtMMMtodicASA1Cny2U+aCXcNpml+m4dPsvsJ3jatg==",
+ "dev": true
+ },
+ "arr-union": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/arr-union/-/arr-union-3.1.0.tgz",
+ "integrity": "sha1-45sJrqne+Gao8gbiiK9jkZuuOcQ=",
+ "dev": true
+ },
+ "array-filter": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/array-filter/-/array-filter-1.0.0.tgz",
+ "integrity": "sha1-uveeYubvTCpMC4MSMtr/7CUfnYM=",
+ "dev": true
+ },
+ "array-find-index": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/array-find-index/-/array-find-index-1.0.2.tgz",
+ "integrity": "sha1-3wEKoSh+Fku9pvlyOwqWoexBh6E=",
+ "dev": true
+ },
+ "array-from": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/array-from/-/array-from-2.1.1.tgz",
+ "integrity": "sha1-z+nYwmYoudxa7MYqn12PHzUsEZU=",
+ "dev": true
+ },
+ "array-unique": {
+ "version": "0.2.1",
+ "resolved": "https://registry.npmjs.org/array-unique/-/array-unique-0.2.1.tgz",
+ "integrity": "sha1-odl8yvy8JiXMcPrc6zalDFiwGlM=",
+ "dev": true
+ },
+ "array.prototype.find": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/array.prototype.find/-/array.prototype.find-2.1.0.tgz",
+ "integrity": "sha512-Wn41+K1yuO5p7wRZDl7890c3xvv5UBrfVXTVIe28rSQb6LS0fZMDrQB6PAcxQFRFy6vJTLDc3A2+3CjQdzVKRg==",
+ "dev": true,
+ "requires": {
+ "define-properties": "^1.1.3",
+ "es-abstract": "^1.13.0"
+ }
+ },
+ "array.prototype.flat": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/array.prototype.flat/-/array.prototype.flat-1.2.3.tgz",
+ "integrity": "sha512-gBlRZV0VSmfPIeWfuuy56XZMvbVfbEUnOXUvt3F/eUUUSyzlgLxhEX4YAEpxNAogRGehPSnfXyPtYyKAhkzQhQ==",
+ "dev": true,
+ "requires": {
+ "define-properties": "^1.1.3",
+ "es-abstract": "^1.17.0-next.1"
+ }
+ },
+ "arraybuffer.slice": {
+ "version": "0.0.7",
+ "resolved": "https://registry.npmjs.org/arraybuffer.slice/-/arraybuffer.slice-0.0.7.tgz",
+ "integrity": "sha512-wGUIVQXuehL5TCqQun8OW81jGzAWycqzFF8lFp+GOM5BXLYj3bKNsYC4daB7n6XjCqxQA/qgTJ+8ANR3acjrog==",
+ "dev": true
+ },
+ "asn1": {
+ "version": "0.2.4",
+ "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.4.tgz",
+ "integrity": "sha512-jxwzQpLQjSmWXgwaCZE9Nz+glAG01yF1QnWgbhGwHI5A6FRIEY6IVqtHhIepHqI7/kyEyQEagBC5mBEFlIYvdg==",
+ "dev": true,
+ "requires": {
+ "safer-buffer": "~2.1.0"
+ }
+ },
+ "asn1.js": {
+ "version": "4.10.1",
+ "resolved": "https://registry.npmjs.org/asn1.js/-/asn1.js-4.10.1.tgz",
+ "integrity": "sha512-p32cOF5q0Zqs9uBiONKYLm6BClCoBCM5O9JfeUSlnQLBTxYdTK+pW+nXflm8UkKd2UYlEbYz5qEi0JuZR9ckSw==",
+ "dev": true,
+ "requires": {
+ "bn.js": "^4.0.0",
+ "inherits": "^2.0.1",
+ "minimalistic-assert": "^1.0.0"
+ }
+ },
+ "assert": {
+ "version": "1.5.0",
+ "resolved": "https://registry.npmjs.org/assert/-/assert-1.5.0.tgz",
+ "integrity": "sha512-EDsgawzwoun2CZkCgtxJbv392v4nbk9XDD06zI+kQYoBM/3RBWLlEyJARDOmhAAosBjWACEkKL6S+lIZtcAubA==",
+ "dev": true,
+ "requires": {
+ "object-assign": "^4.1.1",
+ "util": "0.10.3"
+ },
+ "dependencies": {
+ "inherits": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz",
+ "integrity": "sha1-sX0I0ya0Qj5Wjv9xn5GwscvfafE=",
+ "dev": true
+ },
+ "util": {
+ "version": "0.10.3",
+ "resolved": "https://registry.npmjs.org/util/-/util-0.10.3.tgz",
+ "integrity": "sha1-evsa/lCAUkZInj23/g7TeTNqwPk=",
+ "dev": true,
+ "requires": {
+ "inherits": "2.0.1"
+ }
+ }
+ }
+ },
+ "assert-plus": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz",
+ "integrity": "sha1-8S4PPF13sLHN2RRpQuTpbB5N1SU=",
+ "dev": true
+ },
+ "assertion-error": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-1.1.0.tgz",
+ "integrity": "sha512-jgsaNduz+ndvGyFt3uSuWqvy4lCnIJiovtouQN5JZHOKCS2QuhEdbcQHFhVksz2N2U9hXJo8odG7ETyWlEeuDw==",
+ "dev": true
+ },
+ "assign-symbols": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/assign-symbols/-/assign-symbols-1.0.0.tgz",
+ "integrity": "sha1-WWZ/QfrdTyDMvCu5a41Pf3jsA2c=",
+ "dev": true
+ },
+ "async": {
+ "version": "2.6.3",
+ "resolved": "https://registry.npmjs.org/async/-/async-2.6.3.tgz",
+ "integrity": "sha512-zflvls11DCy+dQWzTW2dzuilv8Z5X/pjfmZOWba6TNIVDm+2UDaJmXSOXlasHKfNBs8oo3M0aT50fDEWfKZjXg==",
+ "dev": true,
+ "requires": {
+ "lodash": "^4.17.14"
+ }
+ },
+ "async-each": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/async-each/-/async-each-1.0.3.tgz",
+ "integrity": "sha512-z/WhQ5FPySLdvREByI2vZiTWwCnF0moMJ1hK9YQwDTHKh6I7/uSckMetoRGb5UBZPC1z0jlw+n/XCgjeH7y1AQ==",
+ "dev": true
+ },
+ "async-foreach": {
+ "version": "0.1.3",
+ "resolved": "https://registry.npmjs.org/async-foreach/-/async-foreach-0.1.3.tgz",
+ "integrity": "sha1-NhIfhFwFeBct5Bmpfb6x0W7DRUI=",
+ "dev": true
+ },
+ "async-limiter": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/async-limiter/-/async-limiter-1.0.1.tgz",
+ "integrity": "sha512-csOlWGAcRFJaI6m+F2WKdnMKr4HhdhFVBk0H/QbJFMCr+uO2kwohwXQPxw/9OCxp05r5ghVBFSyioixx3gfkNQ==",
+ "dev": true
+ },
+ "asynckit": {
+ "version": "0.4.0",
+ "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
+ "integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k=",
+ "dev": true
+ },
+ "atob": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/atob/-/atob-2.1.2.tgz",
+ "integrity": "sha512-Wm6ukoaOGJi/73p/cl2GvLjTI5JM1k/O14isD73YML8StrH/7/lRFgmg8nICZgD3bZZvjwCGxtMOD3wWNAu8cg==",
+ "dev": true
+ },
+ "aws-sign2": {
+ "version": "0.7.0",
+ "resolved": "https://registry.npmjs.org/aws-sign2/-/aws-sign2-0.7.0.tgz",
+ "integrity": "sha1-tG6JCTSpWR8tL2+G1+ap8bP+dqg=",
+ "dev": true
+ },
+ "aws4": {
+ "version": "1.9.1",
+ "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.9.1.tgz",
+ "integrity": "sha512-wMHVg2EOHaMRxbzgFJ9gtjOOCrI80OHLG14rxi28XwOW8ux6IiEbRCGGGqCtdAIg4FQCbW20k9RsT4y3gJlFug==",
+ "dev": true
+ },
+ "babel-code-frame": {
+ "version": "6.26.0",
+ "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz",
+ "integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=",
+ "dev": true,
+ "requires": {
+ "chalk": "^1.1.3",
+ "esutils": "^2.0.2",
+ "js-tokens": "^3.0.2"
+ },
+ "dependencies": {
+ "ansi-styles": {
+ "version": "2.2.1",
+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz",
+ "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=",
+ "dev": true
+ },
+ "chalk": {
+ "version": "1.1.3",
+ "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz",
+ "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=",
+ "dev": true,
+ "requires": {
+ "ansi-styles": "^2.2.1",
+ "escape-string-regexp": "^1.0.2",
+ "has-ansi": "^2.0.0",
+ "strip-ansi": "^3.0.0",
+ "supports-color": "^2.0.0"
+ }
+ },
+ "js-tokens": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz",
+ "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=",
+ "dev": true
+ },
+ "supports-color": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz",
+ "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=",
+ "dev": true
+ }
+ }
+ },
+ "babel-generator": {
+ "version": "6.26.1",
+ "resolved": "https://registry.npmjs.org/babel-generator/-/babel-generator-6.26.1.tgz",
+ "integrity": "sha512-HyfwY6ApZj7BYTcJURpM5tznulaBvyio7/0d4zFOeMPUmfxkCjHocCuoLa2SAGzBI8AREcH3eP3758F672DppA==",
+ "dev": true,
+ "requires": {
+ "babel-messages": "^6.23.0",
+ "babel-runtime": "^6.26.0",
+ "babel-types": "^6.26.0",
+ "detect-indent": "^4.0.0",
+ "jsesc": "^1.3.0",
+ "lodash": "^4.17.4",
+ "source-map": "^0.5.7",
+ "trim-right": "^1.0.1"
+ },
+ "dependencies": {
+ "jsesc": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-1.3.0.tgz",
+ "integrity": "sha1-RsP+yMGJKxKwgz25vHYiF226s0s=",
+ "dev": true
+ }
+ }
+ },
+ "babel-loader": {
+ "version": "8.0.6",
+ "resolved": "https://registry.npmjs.org/babel-loader/-/babel-loader-8.0.6.tgz",
+ "integrity": "sha512-4BmWKtBOBm13uoUwd08UwjZlaw3O9GWf456R9j+5YykFZ6LUIjIKLc0zEZf+hauxPOJs96C8k6FvYD09vWzhYw==",
+ "dev": true,
+ "requires": {
+ "find-cache-dir": "^2.0.0",
+ "loader-utils": "^1.0.2",
+ "mkdirp": "^0.5.1",
+ "pify": "^4.0.1"
+ }
+ },
+ "babel-messages": {
+ "version": "6.23.0",
+ "resolved": "https://registry.npmjs.org/babel-messages/-/babel-messages-6.23.0.tgz",
+ "integrity": "sha1-8830cDhYA1sqKVHG7F7fbGLyYw4=",
+ "dev": true,
+ "requires": {
+ "babel-runtime": "^6.22.0"
+ }
+ },
+ "babel-plugin-jsm-to-commonjs": {
+ "version": "0.5.0",
+ "resolved": "https://registry.npmjs.org/babel-plugin-jsm-to-commonjs/-/babel-plugin-jsm-to-commonjs-0.5.0.tgz",
+ "integrity": "sha512-2+84X/eEYxs+ig3ZVfQhcnvFrYPKKCYmdTs6RZp00MKoIOZ2zET3+mK7gyO6IN922oIv6NGrizOtSEJqLxl/RA==",
+ "dev": true
+ },
+ "babel-plugin-jsm-to-esmodules": {
+ "version": "0.6.0",
+ "resolved": "https://registry.npmjs.org/babel-plugin-jsm-to-esmodules/-/babel-plugin-jsm-to-esmodules-0.6.0.tgz",
+ "integrity": "sha512-463Yuq2sLkjoGHl5vPYUQQONnDjxnmxZuhsR1swL5N76hDFGyYZAVd6HoS4E02jBF8bORpS4aFmdr1XjEZ0buQ==",
+ "dev": true
+ },
+ "babel-runtime": {
+ "version": "6.26.0",
+ "resolved": "https://registry.npmjs.org/babel-runtime/-/babel-runtime-6.26.0.tgz",
+ "integrity": "sha1-llxwWGaOgrVde/4E/yM3vItWR/4=",
+ "dev": true,
+ "requires": {
+ "core-js": "^2.4.0",
+ "regenerator-runtime": "^0.11.0"
+ },
+ "dependencies": {
+ "regenerator-runtime": {
+ "version": "0.11.1",
+ "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.11.1.tgz",
+ "integrity": "sha512-MguG95oij0fC3QV3URf4V2SDYGJhJnJGqvIIgdECeODCT98wSWDAJ94SSuVpYQUoTcGUIL6L4yNB7j1DFFHSBg==",
+ "dev": true
+ }
+ }
+ },
+ "babel-template": {
+ "version": "6.26.0",
+ "resolved": "https://registry.npmjs.org/babel-template/-/babel-template-6.26.0.tgz",
+ "integrity": "sha1-3gPi0WOWsGn0bdn/+FIfsaDjXgI=",
+ "dev": true,
+ "requires": {
+ "babel-runtime": "^6.26.0",
+ "babel-traverse": "^6.26.0",
+ "babel-types": "^6.26.0",
+ "babylon": "^6.18.0",
+ "lodash": "^4.17.4"
+ }
+ },
+ "babel-traverse": {
+ "version": "6.26.0",
+ "resolved": "https://registry.npmjs.org/babel-traverse/-/babel-traverse-6.26.0.tgz",
+ "integrity": "sha1-RqnL1+3MYsjlwGTi0tjQ9ANXZu4=",
+ "dev": true,
+ "requires": {
+ "babel-code-frame": "^6.26.0",
+ "babel-messages": "^6.23.0",
+ "babel-runtime": "^6.26.0",
+ "babel-types": "^6.26.0",
+ "babylon": "^6.18.0",
+ "debug": "^2.6.8",
+ "globals": "^9.18.0",
+ "invariant": "^2.2.2",
+ "lodash": "^4.17.4"
+ },
+ "dependencies": {
+ "debug": {
+ "version": "2.6.9",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
+ "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
+ "dev": true,
+ "requires": {
+ "ms": "2.0.0"
+ }
+ },
+ "globals": {
+ "version": "9.18.0",
+ "resolved": "https://registry.npmjs.org/globals/-/globals-9.18.0.tgz",
+ "integrity": "sha512-S0nG3CLEQiY/ILxqtztTWH/3iRRdyBLw6KMDxnKMchrtbj2OFmehVh0WUCfW3DUrIgx/qFrJPICrq4Z4sTR9UQ==",
+ "dev": true
+ },
+ "ms": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
+ "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=",
+ "dev": true
+ }
+ }
+ },
+ "babel-types": {
+ "version": "6.26.0",
+ "resolved": "https://registry.npmjs.org/babel-types/-/babel-types-6.26.0.tgz",
+ "integrity": "sha1-o7Bz+Uq0nrb6Vc1lInozQ4BjJJc=",
+ "dev": true,
+ "requires": {
+ "babel-runtime": "^6.26.0",
+ "esutils": "^2.0.2",
+ "lodash": "^4.17.4",
+ "to-fast-properties": "^1.0.3"
+ },
+ "dependencies": {
+ "to-fast-properties": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-1.0.3.tgz",
+ "integrity": "sha1-uDVx+k2MJbguIxsG46MFXeTKGkc=",
+ "dev": true
+ }
+ }
+ },
+ "babylon": {
+ "version": "6.18.0",
+ "resolved": "https://registry.npmjs.org/babylon/-/babylon-6.18.0.tgz",
+ "integrity": "sha512-q/UEjfGJ2Cm3oKV71DJz9d25TPnq5rhBVL2Q4fA5wcC3jcrdn7+SssEybFIxwAvvP+YCsCYNKughoF33GxgycQ==",
+ "dev": true
+ },
+ "backo2": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/backo2/-/backo2-1.0.2.tgz",
+ "integrity": "sha1-MasayLEpNjRj41s+u2n038+6eUc=",
+ "dev": true
+ },
+ "balanced-match": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz",
+ "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=",
+ "dev": true
+ },
+ "base": {
+ "version": "0.11.2",
+ "resolved": "https://registry.npmjs.org/base/-/base-0.11.2.tgz",
+ "integrity": "sha512-5T6P4xPgpp0YDFvSWwEZ4NoE3aM4QBQXDzmVbraCkFj8zHM+mba8SyqB5DbZWyR7mYHo6Y7BdQo3MoA4m0TeQg==",
+ "dev": true,
+ "requires": {
+ "cache-base": "^1.0.1",
+ "class-utils": "^0.3.5",
+ "component-emitter": "^1.2.1",
+ "define-property": "^1.0.0",
+ "isobject": "^3.0.1",
+ "mixin-deep": "^1.2.0",
+ "pascalcase": "^0.1.1"
+ },
+ "dependencies": {
+ "define-property": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/define-property/-/define-property-1.0.0.tgz",
+ "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=",
+ "dev": true,
+ "requires": {
+ "is-descriptor": "^1.0.0"
+ }
+ },
+ "is-accessor-descriptor": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz",
+ "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==",
+ "dev": true,
+ "requires": {
+ "kind-of": "^6.0.0"
+ }
+ },
+ "is-data-descriptor": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz",
+ "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==",
+ "dev": true,
+ "requires": {
+ "kind-of": "^6.0.0"
+ }
+ },
+ "is-descriptor": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz",
+ "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==",
+ "dev": true,
+ "requires": {
+ "is-accessor-descriptor": "^1.0.0",
+ "is-data-descriptor": "^1.0.0",
+ "kind-of": "^6.0.2"
+ }
+ },
+ "isobject": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz",
+ "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=",
+ "dev": true
+ },
+ "kind-of": {
+ "version": "6.0.3",
+ "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz",
+ "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==",
+ "dev": true
+ }
+ }
+ },
+ "base64-arraybuffer": {
+ "version": "0.1.5",
+ "resolved": "https://registry.npmjs.org/base64-arraybuffer/-/base64-arraybuffer-0.1.5.tgz",
+ "integrity": "sha1-c5JncZI7Whl0etZmqlzUv5xunOg=",
+ "dev": true
+ },
+ "base64-js": {
+ "version": "1.3.1",
+ "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.3.1.tgz",
+ "integrity": "sha512-mLQ4i2QO1ytvGWFWmcngKO//JXAQueZvwEKtjgQFM4jIK0kU+ytMfplL8j+n5mspOfjHwoAg+9yhb7BwAHm36g==",
+ "dev": true
+ },
+ "base64id": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/base64id/-/base64id-1.0.0.tgz",
+ "integrity": "sha1-R2iMuZu2gE8OBtPnY7HDLlfY5rY=",
+ "dev": true
+ },
+ "bcrypt-pbkdf": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz",
+ "integrity": "sha1-pDAdOJtqQ/m2f/PKEaP2Y342Dp4=",
+ "dev": true,
+ "requires": {
+ "tweetnacl": "^0.14.3"
+ }
+ },
+ "better-assert": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/better-assert/-/better-assert-1.0.2.tgz",
+ "integrity": "sha1-QIZrnhueC1W0gYlDEeaPr/rrxSI=",
+ "dev": true,
+ "requires": {
+ "callsite": "1.0.0"
+ }
+ },
+ "big.js": {
+ "version": "5.2.2",
+ "resolved": "https://registry.npmjs.org/big.js/-/big.js-5.2.2.tgz",
+ "integrity": "sha512-vyL2OymJxmarO8gxMr0mhChsO9QGwhynfuu4+MHTAW6czfq9humCB7rKpUjDd9YUiDPU4mzpyupFSvOClAwbmQ==",
+ "dev": true
+ },
+ "binary-extensions": {
+ "version": "1.13.1",
+ "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-1.13.1.tgz",
+ "integrity": "sha512-Un7MIEDdUC5gNpcGDV97op1Ywk748MpHcFTHoYs6qnj1Z3j7I53VG3nwZhKzoBZmbdRNnb6WRdFlwl7tSDuZGw==",
+ "dev": true
+ },
+ "bindings": {
+ "version": "1.5.0",
+ "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz",
+ "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==",
+ "dev": true,
+ "optional": true,
+ "requires": {
+ "file-uri-to-path": "1.0.0"
+ }
+ },
+ "blob": {
+ "version": "0.0.5",
+ "resolved": "https://registry.npmjs.org/blob/-/blob-0.0.5.tgz",
+ "integrity": "sha512-gaqbzQPqOoamawKg0LGVd7SzLgXS+JH61oWprSLH+P+abTczqJbhTR8CmJ2u9/bUYNmHTGJx/UEmn6doAvvuig==",
+ "dev": true
+ },
+ "block-stream": {
+ "version": "0.0.9",
+ "resolved": "https://registry.npmjs.org/block-stream/-/block-stream-0.0.9.tgz",
+ "integrity": "sha1-E+v+d4oDIFz+A3UUgeu0szAMEmo=",
+ "dev": true,
+ "requires": {
+ "inherits": "~2.0.0"
+ }
+ },
+ "bluebird": {
+ "version": "3.7.2",
+ "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.7.2.tgz",
+ "integrity": "sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==",
+ "dev": true
+ },
+ "bn.js": {
+ "version": "4.11.8",
+ "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.11.8.tgz",
+ "integrity": "sha512-ItfYfPLkWHUjckQCk8xC+LwxgK8NYcXywGigJgSwOP8Y2iyWT4f2vsZnoOXTTbo+o5yXmIUJ4gn5538SO5S3gA==",
+ "dev": true
+ },
+ "body-parser": {
+ "version": "1.19.0",
+ "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.19.0.tgz",
+ "integrity": "sha512-dhEPs72UPbDnAQJ9ZKMNTP6ptJaionhP5cBb541nXPlW60Jepo9RV/a4fX4XWW9CuFNK22krhrj1+rgzifNCsw==",
+ "dev": true,
+ "requires": {
+ "bytes": "3.1.0",
+ "content-type": "~1.0.4",
+ "debug": "2.6.9",
+ "depd": "~1.1.2",
+ "http-errors": "1.7.2",
+ "iconv-lite": "0.4.24",
+ "on-finished": "~2.3.0",
+ "qs": "6.7.0",
+ "raw-body": "2.4.0",
+ "type-is": "~1.6.17"
+ },
+ "dependencies": {
+ "debug": {
+ "version": "2.6.9",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
+ "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
+ "dev": true,
+ "requires": {
+ "ms": "2.0.0"
+ }
+ },
+ "ms": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
+ "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=",
+ "dev": true
+ }
+ }
+ },
+ "boolbase": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz",
+ "integrity": "sha1-aN/1++YMUes3cl6p4+0xDcwed24=",
+ "dev": true
+ },
+ "brace-expansion": {
+ "version": "1.1.11",
+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz",
+ "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==",
+ "dev": true,
+ "requires": {
+ "balanced-match": "^1.0.0",
+ "concat-map": "0.0.1"
+ }
+ },
+ "braces": {
+ "version": "1.8.5",
+ "resolved": "https://registry.npmjs.org/braces/-/braces-1.8.5.tgz",
+ "integrity": "sha1-uneWLhLf+WnWt2cR6RS3N4V79qc=",
+ "dev": true,
+ "requires": {
+ "expand-range": "^1.8.1",
+ "preserve": "^0.2.0",
+ "repeat-element": "^1.1.2"
+ }
+ },
+ "brorand": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/brorand/-/brorand-1.1.0.tgz",
+ "integrity": "sha1-EsJe/kCkXjwyPrhnWgoM5XsiNx8=",
+ "dev": true
+ },
+ "browser-stdout": {
+ "version": "1.3.1",
+ "resolved": "https://registry.npmjs.org/browser-stdout/-/browser-stdout-1.3.1.tgz",
+ "integrity": "sha512-qhAVI1+Av2X7qelOfAIYwXONood6XlZE/fXaBSmW/T5SzLAmCgzi+eiWE7fUvbHaeNBQH13UftjpXxsfLkMpgw==",
+ "dev": true
+ },
+ "browserify-aes": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/browserify-aes/-/browserify-aes-1.2.0.tgz",
+ "integrity": "sha512-+7CHXqGuspUn/Sl5aO7Ea0xWGAtETPXNSAjHo48JfLdPWcMng33Xe4znFvQweqc/uzk5zSOI3H52CYnjCfb5hA==",
+ "dev": true,
+ "requires": {
+ "buffer-xor": "^1.0.3",
+ "cipher-base": "^1.0.0",
+ "create-hash": "^1.1.0",
+ "evp_bytestokey": "^1.0.3",
+ "inherits": "^2.0.1",
+ "safe-buffer": "^5.0.1"
+ }
+ },
+ "browserify-cipher": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/browserify-cipher/-/browserify-cipher-1.0.1.tgz",
+ "integrity": "sha512-sPhkz0ARKbf4rRQt2hTpAHqn47X3llLkUGn+xEJzLjwY8LRs2p0v7ljvI5EyoRO/mexrNunNECisZs+gw2zz1w==",
+ "dev": true,
+ "requires": {
+ "browserify-aes": "^1.0.4",
+ "browserify-des": "^1.0.0",
+ "evp_bytestokey": "^1.0.0"
+ }
+ },
+ "browserify-des": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/browserify-des/-/browserify-des-1.0.2.tgz",
+ "integrity": "sha512-BioO1xf3hFwz4kc6iBhI3ieDFompMhrMlnDFC4/0/vd5MokpuAc3R+LYbwTA9A5Yc9pq9UYPqffKpW2ObuwX5A==",
+ "dev": true,
+ "requires": {
+ "cipher-base": "^1.0.1",
+ "des.js": "^1.0.0",
+ "inherits": "^2.0.1",
+ "safe-buffer": "^5.1.2"
+ }
+ },
+ "browserify-rsa": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/browserify-rsa/-/browserify-rsa-4.0.1.tgz",
+ "integrity": "sha1-IeCr+vbyApzy+vsTNWenAdQTVSQ=",
+ "dev": true,
+ "requires": {
+ "bn.js": "^4.1.0",
+ "randombytes": "^2.0.1"
+ }
+ },
+ "browserify-sign": {
+ "version": "4.0.4",
+ "resolved": "https://registry.npmjs.org/browserify-sign/-/browserify-sign-4.0.4.tgz",
+ "integrity": "sha1-qk62jl17ZYuqa/alfmMMvXqT0pg=",
+ "dev": true,
+ "requires": {
+ "bn.js": "^4.1.1",
+ "browserify-rsa": "^4.0.0",
+ "create-hash": "^1.1.0",
+ "create-hmac": "^1.1.2",
+ "elliptic": "^6.0.0",
+ "inherits": "^2.0.1",
+ "parse-asn1": "^5.0.0"
+ }
+ },
+ "browserify-zlib": {
+ "version": "0.2.0",
+ "resolved": "https://registry.npmjs.org/browserify-zlib/-/browserify-zlib-0.2.0.tgz",
+ "integrity": "sha512-Z942RysHXmJrhqk88FmKBVq/v5tqmSkDz7p54G/MGyjMnCFFnC79XWNbg+Vta8W6Wb2qtSZTSxIGkJrRpCFEiA==",
+ "dev": true,
+ "requires": {
+ "pako": "~1.0.5"
+ }
+ },
+ "buffer": {
+ "version": "4.9.2",
+ "resolved": "https://registry.npmjs.org/buffer/-/buffer-4.9.2.tgz",
+ "integrity": "sha512-xq+q3SRMOxGivLhBNaUdC64hDTQwejJ+H0T/NB1XMtTVEwNTrfFF3gAxiyW0Bu/xWEGhjVKgUcMhCrUy2+uCWg==",
+ "dev": true,
+ "requires": {
+ "base64-js": "^1.0.2",
+ "ieee754": "^1.1.4",
+ "isarray": "^1.0.0"
+ }
+ },
+ "buffer-alloc": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/buffer-alloc/-/buffer-alloc-1.2.0.tgz",
+ "integrity": "sha512-CFsHQgjtW1UChdXgbyJGtnm+O/uLQeZdtbDo8mfUgYXCHSM1wgrVxXm6bSyrUuErEb+4sYVGCzASBRot7zyrow==",
+ "dev": true,
+ "requires": {
+ "buffer-alloc-unsafe": "^1.1.0",
+ "buffer-fill": "^1.0.0"
+ }
+ },
+ "buffer-alloc-unsafe": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/buffer-alloc-unsafe/-/buffer-alloc-unsafe-1.1.0.tgz",
+ "integrity": "sha512-TEM2iMIEQdJ2yjPJoSIsldnleVaAk1oW3DBVUykyOLsEsFmEc9kn+SFFPz+gl54KQNxlDnAwCXosOS9Okx2xAg==",
+ "dev": true
+ },
+ "buffer-fill": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/buffer-fill/-/buffer-fill-1.0.0.tgz",
+ "integrity": "sha1-+PeLdniYiO858gXNY39o5wISKyw=",
+ "dev": true
+ },
+ "buffer-from": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.1.tgz",
+ "integrity": "sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A==",
+ "dev": true
+ },
+ "buffer-xor": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/buffer-xor/-/buffer-xor-1.0.3.tgz",
+ "integrity": "sha1-JuYe0UIvtw3ULm42cp7VHYVf6Nk=",
+ "dev": true
+ },
+ "builtin-status-codes": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/builtin-status-codes/-/builtin-status-codes-3.0.0.tgz",
+ "integrity": "sha1-hZgoeOIbmOHGZCXgPQF0eI9Wnug=",
+ "dev": true
+ },
+ "bytes": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.0.tgz",
+ "integrity": "sha512-zauLjrfCG+xvoyaqLoV8bLVXXNGC4JqlxFCutSDWA6fJrTo2ZuvLYTqZ7aHBLZSMOopbzwv8f+wZcVzfVTI2Dg==",
+ "dev": true
+ },
+ "cacache": {
+ "version": "12.0.3",
+ "resolved": "https://registry.npmjs.org/cacache/-/cacache-12.0.3.tgz",
+ "integrity": "sha512-kqdmfXEGFepesTuROHMs3MpFLWrPkSSpRqOw80RCflZXy/khxaArvFrQ7uJxSUduzAufc6G0g1VUCOZXxWavPw==",
+ "dev": true,
+ "requires": {
+ "bluebird": "^3.5.5",
+ "chownr": "^1.1.1",
+ "figgy-pudding": "^3.5.1",
+ "glob": "^7.1.4",
+ "graceful-fs": "^4.1.15",
+ "infer-owner": "^1.0.3",
+ "lru-cache": "^5.1.1",
+ "mississippi": "^3.0.0",
+ "mkdirp": "^0.5.1",
+ "move-concurrently": "^1.0.1",
+ "promise-inflight": "^1.0.1",
+ "rimraf": "^2.6.3",
+ "ssri": "^6.0.1",
+ "unique-filename": "^1.1.1",
+ "y18n": "^4.0.0"
+ },
+ "dependencies": {
+ "lru-cache": {
+ "version": "5.1.1",
+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",
+ "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==",
+ "dev": true,
+ "requires": {
+ "yallist": "^3.0.2"
+ }
+ },
+ "rimraf": {
+ "version": "2.7.1",
+ "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz",
+ "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==",
+ "dev": true,
+ "requires": {
+ "glob": "^7.1.3"
+ }
+ },
+ "yallist": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",
+ "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==",
+ "dev": true
+ }
+ }
+ },
+ "cache-base": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/cache-base/-/cache-base-1.0.1.tgz",
+ "integrity": "sha512-AKcdTnFSWATd5/GCPRxr2ChwIJ85CeyrEyjRHlKxQ56d4XJMGym0uAiKn0xbLOGOl3+yRpOTi484dVCEc5AUzQ==",
+ "dev": true,
+ "requires": {
+ "collection-visit": "^1.0.0",
+ "component-emitter": "^1.2.1",
+ "get-value": "^2.0.6",
+ "has-value": "^1.0.0",
+ "isobject": "^3.0.1",
+ "set-value": "^2.0.0",
+ "to-object-path": "^0.3.0",
+ "union-value": "^1.0.0",
+ "unset-value": "^1.0.0"
+ },
+ "dependencies": {
+ "isobject": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz",
+ "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=",
+ "dev": true
+ }
+ }
+ },
+ "cached-iterable": {
+ "version": "0.2.1",
+ "resolved": "https://registry.npmjs.org/cached-iterable/-/cached-iterable-0.2.1.tgz",
+ "integrity": "sha512-8zAVjMjdn/S/QXJaOnqsko0+ZJzXT2Dum2u9TMGg5YR9fxONPrUjuO9VYqnb1AoldXeYVAcNJLgT5Q8WaIJSgA=="
+ },
+ "caller-path": {
+ "version": "0.1.0",
+ "resolved": "https://registry.npmjs.org/caller-path/-/caller-path-0.1.0.tgz",
+ "integrity": "sha1-lAhe9jWB7NPaqSREqP6U6CV3dR8=",
+ "dev": true,
+ "requires": {
+ "callsites": "^0.2.0"
+ }
+ },
+ "callsite": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/callsite/-/callsite-1.0.0.tgz",
+ "integrity": "sha1-KAOY5dZkvXQDi28JBRU+borxvCA=",
+ "dev": true
+ },
+ "callsites": {
+ "version": "0.2.0",
+ "resolved": "https://registry.npmjs.org/callsites/-/callsites-0.2.0.tgz",
+ "integrity": "sha1-r6uWJikQp/M8GaV3WCXGnzTjUMo=",
+ "dev": true
+ },
+ "camelcase": {
+ "version": "5.3.1",
+ "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz",
+ "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==",
+ "dev": true
+ },
+ "camelcase-keys": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/camelcase-keys/-/camelcase-keys-2.1.0.tgz",
+ "integrity": "sha1-MIvur/3ygRkFHvodkyITyRuPkuc=",
+ "dev": true,
+ "requires": {
+ "camelcase": "^2.0.0",
+ "map-obj": "^1.0.0"
+ },
+ "dependencies": {
+ "camelcase": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-2.1.1.tgz",
+ "integrity": "sha1-fB0W1nmhu+WcoCys7PsBHiAfWh8=",
+ "dev": true
+ }
+ }
+ },
+ "caseless": {
+ "version": "0.12.0",
+ "resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz",
+ "integrity": "sha1-G2gcIf+EAzyCZUMJBolCDRhxUdw=",
+ "dev": true
+ },
+ "chai": {
+ "version": "4.2.0",
+ "resolved": "https://registry.npmjs.org/chai/-/chai-4.2.0.tgz",
+ "integrity": "sha512-XQU3bhBukrOsQCuwZndwGcCVQHyZi53fQ6Ys1Fym7E4olpIqqZZhhoFJoaKVvV17lWQoXYwgWN2nF5crA8J2jw==",
+ "dev": true,
+ "requires": {
+ "assertion-error": "^1.1.0",
+ "check-error": "^1.0.2",
+ "deep-eql": "^3.0.1",
+ "get-func-name": "^2.0.0",
+ "pathval": "^1.1.0",
+ "type-detect": "^4.0.5"
+ }
+ },
+ "chai-json-schema": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/chai-json-schema/-/chai-json-schema-1.5.1.tgz",
+ "integrity": "sha512-TR/xPDxRhqwFFCWg1HgL8nNWbpNfUwaib6pBN++QKpnd0t+o3+MBvAn5CM1mpdUMaM76oJAtUjGKdjGad01lIA==",
+ "dev": true,
+ "requires": {
+ "jsonpointer.js": "0.4.0",
+ "tv4": "^1.3.0"
+ }
+ },
+ "chalk": {
+ "version": "2.4.2",
+ "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz",
+ "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==",
+ "dev": true,
+ "requires": {
+ "ansi-styles": "^3.2.1",
+ "escape-string-regexp": "^1.0.5",
+ "supports-color": "^5.3.0"
+ }
+ },
+ "check-error": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/check-error/-/check-error-1.0.2.tgz",
+ "integrity": "sha1-V00xLt2Iu13YkS6Sht1sCu1KrII=",
+ "dev": true
+ },
+ "cheerio": {
+ "version": "1.0.0-rc.3",
+ "resolved": "https://registry.npmjs.org/cheerio/-/cheerio-1.0.0-rc.3.tgz",
+ "integrity": "sha512-0td5ijfUPuubwLUu0OBoe98gZj8C/AA+RW3v67GPlGOrvxWjZmBXiBCRU+I8VEiNyJzjth40POfHiz2RB3gImA==",
+ "dev": true,
+ "requires": {
+ "css-select": "~1.2.0",
+ "dom-serializer": "~0.1.1",
+ "entities": "~1.1.1",
+ "htmlparser2": "^3.9.1",
+ "lodash": "^4.15.0",
+ "parse5": "^3.0.1"
+ }
+ },
+ "chokidar": {
+ "version": "1.7.0",
+ "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-1.7.0.tgz",
+ "integrity": "sha1-eY5ol3gVHIB2tLNg5e3SjNortGg=",
+ "dev": true,
+ "requires": {
+ "anymatch": "^1.3.0",
+ "async-each": "^1.0.0",
+ "fsevents": "^1.0.0",
+ "glob-parent": "^2.0.0",
+ "inherits": "^2.0.1",
+ "is-binary-path": "^1.0.0",
+ "is-glob": "^2.0.0",
+ "path-is-absolute": "^1.0.0",
+ "readdirp": "^2.0.0"
+ }
+ },
+ "chownr": {
+ "version": "1.1.4",
+ "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz",
+ "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==",
+ "dev": true
+ },
+ "chrome-trace-event": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/chrome-trace-event/-/chrome-trace-event-1.0.2.tgz",
+ "integrity": "sha512-9e/zx1jw7B4CO+c/RXoCsfg/x1AfUBioy4owYH0bJprEYAx5hRFLRhWBqHAG57D0ZM4H7vxbP7bPe0VwhQRYDQ==",
+ "dev": true,
+ "requires": {
+ "tslib": "^1.9.0"
+ }
+ },
+ "cipher-base": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/cipher-base/-/cipher-base-1.0.4.tgz",
+ "integrity": "sha512-Kkht5ye6ZGmwv40uUDZztayT2ThLQGfnj/T71N/XzeZeo3nf8foyW7zGTsPYkEya3m5f3cAypH+qe7YOrM1U2Q==",
+ "dev": true,
+ "requires": {
+ "inherits": "^2.0.1",
+ "safe-buffer": "^5.0.1"
+ }
+ },
+ "circular-json": {
+ "version": "0.3.3",
+ "resolved": "https://registry.npmjs.org/circular-json/-/circular-json-0.3.3.tgz",
+ "integrity": "sha512-UZK3NBx2Mca+b5LsG7bY183pHWt5Y1xts4P3Pz7ENTwGVnJOUWbRb3ocjvX7hx9tq/yTAdclXm9sZ38gNuem4A==",
+ "dev": true
+ },
+ "class-utils": {
+ "version": "0.3.6",
+ "resolved": "https://registry.npmjs.org/class-utils/-/class-utils-0.3.6.tgz",
+ "integrity": "sha512-qOhPa/Fj7s6TY8H8esGu5QNpMMQxz79h+urzrNYN6mn+9BnxlDGf5QZ+XeCDsxSjPqsSR56XOZOJmpeurnLMeg==",
+ "dev": true,
+ "requires": {
+ "arr-union": "^3.1.0",
+ "define-property": "^0.2.5",
+ "isobject": "^3.0.0",
+ "static-extend": "^0.1.1"
+ },
+ "dependencies": {
+ "define-property": {
+ "version": "0.2.5",
+ "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz",
+ "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=",
+ "dev": true,
+ "requires": {
+ "is-descriptor": "^0.1.0"
+ }
+ },
+ "isobject": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz",
+ "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=",
+ "dev": true
+ }
+ }
+ },
+ "cli-cursor": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-1.0.2.tgz",
+ "integrity": "sha1-ZNo/fValRBLll5S9Ytw1KV6PKYc=",
+ "dev": true,
+ "requires": {
+ "restore-cursor": "^1.0.1"
+ }
+ },
+ "cli-width": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-2.2.0.tgz",
+ "integrity": "sha1-/xnt6Kml5XkyQUewwR8PvLq+1jk=",
+ "dev": true
+ },
+ "cliui": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/cliui/-/cliui-5.0.0.tgz",
+ "integrity": "sha512-PYeGSEmmHM6zvoef2w8TPzlrnNpXIjTipYK780YswmIP9vjxmd6Y2a3CB2Ks6/AU8NHjZugXvo8w3oWM2qnwXA==",
+ "dev": true,
+ "requires": {
+ "string-width": "^3.1.0",
+ "strip-ansi": "^5.2.0",
+ "wrap-ansi": "^5.1.0"
+ },
+ "dependencies": {
+ "ansi-regex": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz",
+ "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==",
+ "dev": true
+ },
+ "string-width": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz",
+ "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==",
+ "dev": true,
+ "requires": {
+ "emoji-regex": "^7.0.1",
+ "is-fullwidth-code-point": "^2.0.0",
+ "strip-ansi": "^5.1.0"
+ }
+ },
+ "strip-ansi": {
+ "version": "5.2.0",
+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz",
+ "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==",
+ "dev": true,
+ "requires": {
+ "ansi-regex": "^4.1.0"
+ }
+ }
+ }
+ },
+ "clone-deep": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/clone-deep/-/clone-deep-4.0.1.tgz",
+ "integrity": "sha512-neHB9xuzh/wk0dIHweyAXv2aPGZIVk3pLMe+/RNzINf17fe0OG96QroktYAUm7SM1PBnzTabaLboqqxDyMU+SQ==",
+ "dev": true,
+ "requires": {
+ "is-plain-object": "^2.0.4",
+ "kind-of": "^6.0.2",
+ "shallow-clone": "^3.0.0"
+ },
+ "dependencies": {
+ "kind-of": {
+ "version": "6.0.3",
+ "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz",
+ "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==",
+ "dev": true
+ }
+ }
+ },
+ "co": {
+ "version": "4.6.0",
+ "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz",
+ "integrity": "sha1-bqa989hTrlTMuOR7+gvz+QMfsYQ=",
+ "dev": true
+ },
+ "code-point-at": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/code-point-at/-/code-point-at-1.1.0.tgz",
+ "integrity": "sha1-DQcLTQQ6W+ozovGkDi7bPZpMz3c=",
+ "dev": true
+ },
+ "collection-visit": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/collection-visit/-/collection-visit-1.0.0.tgz",
+ "integrity": "sha1-S8A3PBZLwykbTTaMgpzxqApZ3KA=",
+ "dev": true,
+ "requires": {
+ "map-visit": "^1.0.0",
+ "object-visit": "^1.0.0"
+ }
+ },
+ "color-convert": {
+ "version": "1.9.3",
+ "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz",
+ "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==",
+ "dev": true,
+ "requires": {
+ "color-name": "1.1.3"
+ }
+ },
+ "color-name": {
+ "version": "1.1.3",
+ "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz",
+ "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=",
+ "dev": true
+ },
+ "colors": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/colors/-/colors-1.4.0.tgz",
+ "integrity": "sha512-a+UqTh4kgZg/SlGvfbzDHpgRu7AAQOmmqRHJnxhRZICKFUT91brVhNNt58CMWU9PsBbv3PDCZUHbVxuDiH2mtA==",
+ "dev": true
+ },
+ "combined-stream": {
+ "version": "1.0.8",
+ "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
+ "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
+ "dev": true,
+ "requires": {
+ "delayed-stream": "~1.0.0"
+ }
+ },
+ "commander": {
+ "version": "2.20.3",
+ "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz",
+ "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==",
+ "dev": true
+ },
+ "commondir": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz",
+ "integrity": "sha1-3dgA2gxmEnOTzKWVDqloo6rxJTs=",
+ "dev": true
+ },
+ "compare-versions": {
+ "version": "3.6.0",
+ "resolved": "https://registry.npmjs.org/compare-versions/-/compare-versions-3.6.0.tgz",
+ "integrity": "sha512-W6Af2Iw1z4CB7q4uU4hv646dW9GQuBM+YpC0UvUCWSD8w90SJjp+ujJuXaEMtAXBtSqGfMPuFOVn4/+FlaqfBA==",
+ "dev": true
+ },
+ "component-bind": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/component-bind/-/component-bind-1.0.0.tgz",
+ "integrity": "sha1-AMYIq33Nk4l8AAllGx06jh5zu9E=",
+ "dev": true
+ },
+ "component-emitter": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.3.0.tgz",
+ "integrity": "sha512-Rd3se6QB+sO1TwqZjscQrurpEPIfO0/yYnSin6Q/rD3mOutHvUrCAhJub3r90uNb+SESBuE0QYoB90YdfatsRg==",
+ "dev": true
+ },
+ "component-inherit": {
+ "version": "0.0.3",
+ "resolved": "https://registry.npmjs.org/component-inherit/-/component-inherit-0.0.3.tgz",
+ "integrity": "sha1-ZF/ErfWLcrZJ1crmUTVhnbJv8UM=",
+ "dev": true
+ },
+ "concat-map": {
+ "version": "0.0.1",
+ "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
+ "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=",
+ "dev": true
+ },
+ "concat-stream": {
+ "version": "1.6.2",
+ "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.2.tgz",
+ "integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==",
+ "dev": true,
+ "requires": {
+ "buffer-from": "^1.0.0",
+ "inherits": "^2.0.3",
+ "readable-stream": "^2.2.2",
+ "typedarray": "^0.0.6"
+ }
+ },
+ "connect": {
+ "version": "3.7.0",
+ "resolved": "https://registry.npmjs.org/connect/-/connect-3.7.0.tgz",
+ "integrity": "sha512-ZqRXc+tZukToSNmh5C2iWMSoV3X1YUcPbqEM4DkEG5tNQXrQUZCNVGGv3IuicnkMtPfGf3Xtp8WCXs295iQ1pQ==",
+ "dev": true,
+ "requires": {
+ "debug": "2.6.9",
+ "finalhandler": "1.1.2",
+ "parseurl": "~1.3.3",
+ "utils-merge": "1.0.1"
+ },
+ "dependencies": {
+ "debug": {
+ "version": "2.6.9",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
+ "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
+ "dev": true,
+ "requires": {
+ "ms": "2.0.0"
+ }
+ },
+ "ms": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
+ "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=",
+ "dev": true
+ }
+ }
+ },
+ "console-browserify": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/console-browserify/-/console-browserify-1.2.0.tgz",
+ "integrity": "sha512-ZMkYO/LkF17QvCPqM0gxw8yUzigAOZOSWSHg91FH6orS7vcEj5dVZTidN2fQ14yBSdg97RqhSNwLUXInd52OTA==",
+ "dev": true
+ },
+ "console-control-strings": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz",
+ "integrity": "sha1-PXz0Rk22RG6mRL9LOVB/mFEAjo4=",
+ "dev": true
+ },
+ "constants-browserify": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/constants-browserify/-/constants-browserify-1.0.0.tgz",
+ "integrity": "sha1-wguW2MYXdIqvHBYCF2DNJ/y4y3U=",
+ "dev": true
+ },
+ "content-type": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.4.tgz",
+ "integrity": "sha512-hIP3EEPs8tB9AT1L+NUqtwOAps4mk2Zob89MWXMHjHWg9milF/j4osnnQLXBCBFBk/tvIG/tUc9mOUJiPBhPXA==",
+ "dev": true
+ },
+ "convert-source-map": {
+ "version": "1.7.0",
+ "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.7.0.tgz",
+ "integrity": "sha512-4FJkXzKXEDB1snCFZlLP4gpC3JILicCpGbzG9f9G7tGqGCzETQ2hWPrcinA9oU4wtf2biUaEH5065UnMeR33oA==",
+ "dev": true,
+ "requires": {
+ "safe-buffer": "~5.1.1"
+ }
+ },
+ "cookie": {
+ "version": "0.3.1",
+ "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.3.1.tgz",
+ "integrity": "sha1-5+Ch+e9DtMi6klxcWpboBtFoc7s=",
+ "dev": true
+ },
+ "copy-concurrently": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/copy-concurrently/-/copy-concurrently-1.0.5.tgz",
+ "integrity": "sha512-f2domd9fsVDFtaFcbaRZuYXwtdmnzqbADSwhSWYxYB/Q8zsdUUFMXVRwXGDMWmbEzAn1kdRrtI1T/KTFOL4X2A==",
+ "dev": true,
+ "requires": {
+ "aproba": "^1.1.1",
+ "fs-write-stream-atomic": "^1.0.8",
+ "iferr": "^0.1.5",
+ "mkdirp": "^0.5.1",
+ "rimraf": "^2.5.4",
+ "run-queue": "^1.0.0"
+ },
+ "dependencies": {
+ "rimraf": {
+ "version": "2.7.1",
+ "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz",
+ "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==",
+ "dev": true,
+ "requires": {
+ "glob": "^7.1.3"
+ }
+ }
+ }
+ },
+ "copy-descriptor": {
+ "version": "0.1.1",
+ "resolved": "https://registry.npmjs.org/copy-descriptor/-/copy-descriptor-0.1.1.tgz",
+ "integrity": "sha1-Z29us8OZl8LuGsOpJP1hJHSPV40=",
+ "dev": true
+ },
+ "core-js": {
+ "version": "2.6.11",
+ "resolved": "https://registry.npmjs.org/core-js/-/core-js-2.6.11.tgz",
+ "integrity": "sha512-5wjnpaT/3dV+XB4borEsnAYQchn00XSgTAWKDkEqv+K8KevjbzmofK6hfJ9TZIlpj2N0xQpazy7PiRQiWHqzWg==",
+ "dev": true
+ },
+ "core-util-is": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz",
+ "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=",
+ "dev": true
+ },
+ "cpx": {
+ "version": "1.5.0",
+ "resolved": "https://registry.npmjs.org/cpx/-/cpx-1.5.0.tgz",
+ "integrity": "sha1-GFvgGFEdhycN7czCkxceN2VauI8=",
+ "dev": true,
+ "requires": {
+ "babel-runtime": "^6.9.2",
+ "chokidar": "^1.6.0",
+ "duplexer": "^0.1.1",
+ "glob": "^7.0.5",
+ "glob2base": "^0.0.12",
+ "minimatch": "^3.0.2",
+ "mkdirp": "^0.5.1",
+ "resolve": "^1.1.7",
+ "safe-buffer": "^5.0.1",
+ "shell-quote": "^1.6.1",
+ "subarg": "^1.0.0"
+ }
+ },
+ "create-ecdh": {
+ "version": "4.0.3",
+ "resolved": "https://registry.npmjs.org/create-ecdh/-/create-ecdh-4.0.3.tgz",
+ "integrity": "sha512-GbEHQPMOswGpKXM9kCWVrremUcBmjteUaQ01T9rkKCPDXfUHX0IoP9LpHYo2NPFampa4e+/pFDc3jQdxrxQLaw==",
+ "dev": true,
+ "requires": {
+ "bn.js": "^4.1.0",
+ "elliptic": "^6.0.0"
+ }
+ },
+ "create-hash": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/create-hash/-/create-hash-1.2.0.tgz",
+ "integrity": "sha512-z00bCGNHDG8mHAkP7CtT1qVu+bFQUPjYq/4Iv3C3kWjTFV10zIjfSoeqXo9Asws8gwSHDGj/hl2u4OGIjapeCg==",
+ "dev": true,
+ "requires": {
+ "cipher-base": "^1.0.1",
+ "inherits": "^2.0.1",
+ "md5.js": "^1.3.4",
+ "ripemd160": "^2.0.1",
+ "sha.js": "^2.4.0"
+ }
+ },
+ "create-hmac": {
+ "version": "1.1.7",
+ "resolved": "https://registry.npmjs.org/create-hmac/-/create-hmac-1.1.7.tgz",
+ "integrity": "sha512-MJG9liiZ+ogc4TzUwuvbER1JRdgvUFSB5+VR/g5h82fGaIRWMWddtKBHi7/sVhfjQZ6SehlyhvQYrcYkaUIpLg==",
+ "dev": true,
+ "requires": {
+ "cipher-base": "^1.0.3",
+ "create-hash": "^1.1.0",
+ "inherits": "^2.0.1",
+ "ripemd160": "^2.0.0",
+ "safe-buffer": "^5.0.1",
+ "sha.js": "^2.4.8"
+ }
+ },
+ "cross-spawn": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-3.0.1.tgz",
+ "integrity": "sha1-ElYDfsufDF9549bvE14wdwGEuYI=",
+ "dev": true,
+ "requires": {
+ "lru-cache": "^4.0.1",
+ "which": "^1.2.9"
+ }
+ },
+ "crypto-browserify": {
+ "version": "3.12.0",
+ "resolved": "https://registry.npmjs.org/crypto-browserify/-/crypto-browserify-3.12.0.tgz",
+ "integrity": "sha512-fz4spIh+znjO2VjL+IdhEpRJ3YN6sMzITSBijk6FK2UvTqruSQW+/cCZTSNsMiZNvUeq0CqurF+dAbyiGOY6Wg==",
+ "dev": true,
+ "requires": {
+ "browserify-cipher": "^1.0.0",
+ "browserify-sign": "^4.0.0",
+ "create-ecdh": "^4.0.0",
+ "create-hash": "^1.1.0",
+ "create-hmac": "^1.1.0",
+ "diffie-hellman": "^5.0.0",
+ "inherits": "^2.0.1",
+ "pbkdf2": "^3.0.3",
+ "public-encrypt": "^4.0.0",
+ "randombytes": "^2.0.0",
+ "randomfill": "^1.0.3"
+ }
+ },
+ "css-select": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/css-select/-/css-select-1.2.0.tgz",
+ "integrity": "sha1-KzoRBTnFNV8c2NMUYj6HCxIeyFg=",
+ "dev": true,
+ "requires": {
+ "boolbase": "~1.0.0",
+ "css-what": "2.1",
+ "domutils": "1.5.1",
+ "nth-check": "~1.0.1"
+ }
+ },
+ "css-what": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/css-what/-/css-what-2.1.3.tgz",
+ "integrity": "sha512-a+EPoD+uZiNfh+5fxw2nO9QwFa6nJe2Or35fGY6Ipw1R3R4AGz1d1TEZrCegvw2YTmZ0jXirGYlzxxpYSHwpEg==",
+ "dev": true
+ },
+ "csstype": {
+ "version": "2.6.9",
+ "resolved": "https://registry.npmjs.org/csstype/-/csstype-2.6.9.tgz",
+ "integrity": "sha512-xz39Sb4+OaTsULgUERcCk+TJj8ylkL4aSVDQiX/ksxbELSqwkgt4d4RD7fovIdgJGSuNYqwZEiVjYY5l0ask+Q=="
+ },
+ "currently-unhandled": {
+ "version": "0.4.1",
+ "resolved": "https://registry.npmjs.org/currently-unhandled/-/currently-unhandled-0.4.1.tgz",
+ "integrity": "sha1-mI3zP+qxke95mmE2nddsF635V+o=",
+ "dev": true,
+ "requires": {
+ "array-find-index": "^1.0.1"
+ }
+ },
+ "custom-event": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/custom-event/-/custom-event-1.0.1.tgz",
+ "integrity": "sha1-XQKkaFCt8bSjF5RqOSj8y1v9BCU=",
+ "dev": true
+ },
+ "cyclist": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/cyclist/-/cyclist-1.0.1.tgz",
+ "integrity": "sha1-WW6WmP0MgOEgOMK4LW6xs1tiJNk=",
+ "dev": true
+ },
+ "d": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/d/-/d-1.0.1.tgz",
+ "integrity": "sha512-m62ShEObQ39CfralilEQRjH6oAMtNCV1xJyEx5LpRYUVN+EviphDgUc/F3hnYbADmkiNs67Y+3ylmlG7Lnu+FA==",
+ "dev": true,
+ "requires": {
+ "es5-ext": "^0.10.50",
+ "type": "^1.0.1"
+ }
+ },
+ "dashdash": {
+ "version": "1.14.1",
+ "resolved": "https://registry.npmjs.org/dashdash/-/dashdash-1.14.1.tgz",
+ "integrity": "sha1-hTz6D3y+L+1d4gMmuN1YEDX24vA=",
+ "dev": true,
+ "requires": {
+ "assert-plus": "^1.0.0"
+ }
+ },
+ "date-format": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/date-format/-/date-format-2.1.0.tgz",
+ "integrity": "sha512-bYQuGLeFxhkxNOF3rcMtiZxvCBAquGzZm6oWA1oZ0g2THUzivaRhv8uOhdr19LmoobSOLoIAxeUK2RdbM8IFTA==",
+ "dev": true
+ },
+ "debug": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz",
+ "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==",
+ "dev": true,
+ "requires": {
+ "ms": "^2.1.1"
+ }
+ },
+ "decamelize": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz",
+ "integrity": "sha1-9lNNFRSCabIDUue+4m9QH5oZEpA=",
+ "dev": true
+ },
+ "decode-uri-component": {
+ "version": "0.2.0",
+ "resolved": "https://registry.npmjs.org/decode-uri-component/-/decode-uri-component-0.2.0.tgz",
+ "integrity": "sha1-6zkTMzRYd1y4TNGh+uBiEGu4dUU=",
+ "dev": true
+ },
+ "deep-eql": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-3.0.1.tgz",
+ "integrity": "sha512-+QeIQyN5ZuO+3Uk5DYh6/1eKO0m0YmJFGNmFHGACpf1ClL1nmlV/p4gNgbl2pJGxgXb4faqo6UE+M5ACEMyVcw==",
+ "dev": true,
+ "requires": {
+ "type-detect": "^4.0.0"
+ }
+ },
+ "deep-is": {
+ "version": "0.1.3",
+ "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz",
+ "integrity": "sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ=",
+ "dev": true
+ },
+ "default-require-extensions": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/default-require-extensions/-/default-require-extensions-2.0.0.tgz",
+ "integrity": "sha1-9fj7sYp9bVCyH2QfZJ67Uiz+JPc=",
+ "dev": true,
+ "requires": {
+ "strip-bom": "^3.0.0"
+ }
+ },
+ "define-properties": {
+ "version": "1.1.3",
+ "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.1.3.tgz",
+ "integrity": "sha512-3MqfYKj2lLzdMSf8ZIZE/V+Zuy+BgD6f164e8K2w7dgnpKArBDerGYpM46IYYcjnkdPNMjPk9A6VFB8+3SKlXQ==",
+ "dev": true,
+ "requires": {
+ "object-keys": "^1.0.12"
+ }
+ },
+ "define-property": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/define-property/-/define-property-2.0.2.tgz",
+ "integrity": "sha512-jwK2UV4cnPpbcG7+VRARKTZPUWowwXA8bzH5NP6ud0oeAxyYPuGZUAC7hMugpCdz4BeSZl2Dl9k66CHJ/46ZYQ==",
+ "dev": true,
+ "requires": {
+ "is-descriptor": "^1.0.2",
+ "isobject": "^3.0.1"
+ },
+ "dependencies": {
+ "is-accessor-descriptor": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz",
+ "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==",
+ "dev": true,
+ "requires": {
+ "kind-of": "^6.0.0"
+ }
+ },
+ "is-data-descriptor": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz",
+ "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==",
+ "dev": true,
+ "requires": {
+ "kind-of": "^6.0.0"
+ }
+ },
+ "is-descriptor": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz",
+ "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==",
+ "dev": true,
+ "requires": {
+ "is-accessor-descriptor": "^1.0.0",
+ "is-data-descriptor": "^1.0.0",
+ "kind-of": "^6.0.2"
+ }
+ },
+ "isobject": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz",
+ "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=",
+ "dev": true
+ },
+ "kind-of": {
+ "version": "6.0.3",
+ "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz",
+ "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==",
+ "dev": true
+ }
+ }
+ },
+ "delayed-stream": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
+ "integrity": "sha1-3zrhmayt+31ECqrgsp4icrJOxhk=",
+ "dev": true
+ },
+ "delegates": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/delegates/-/delegates-1.0.0.tgz",
+ "integrity": "sha1-hMbhWbgZBP3KWaDvRM2HDTElD5o=",
+ "dev": true
+ },
+ "depd": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz",
+ "integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=",
+ "dev": true
+ },
+ "des.js": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/des.js/-/des.js-1.0.1.tgz",
+ "integrity": "sha512-Q0I4pfFrv2VPd34/vfLrFOoRmlYj3OV50i7fskps1jZWK1kApMWWT9G6RRUeYedLcBDIhnSDaUvJMb3AhUlaEA==",
+ "dev": true,
+ "requires": {
+ "inherits": "^2.0.1",
+ "minimalistic-assert": "^1.0.0"
+ }
+ },
+ "detect-file": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/detect-file/-/detect-file-1.0.0.tgz",
+ "integrity": "sha1-8NZtA2cqglyxtzvbP+YjEMjlUrc=",
+ "dev": true
+ },
+ "detect-indent": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/detect-indent/-/detect-indent-4.0.0.tgz",
+ "integrity": "sha1-920GQ1LN9Docts5hnE7jqUdd4gg=",
+ "dev": true,
+ "requires": {
+ "repeating": "^2.0.0"
+ }
+ },
+ "di": {
+ "version": "0.0.1",
+ "resolved": "https://registry.npmjs.org/di/-/di-0.0.1.tgz",
+ "integrity": "sha1-gGZJMmzqp8qjMG112YXqJ0i6kTw=",
+ "dev": true
+ },
+ "diff": {
+ "version": "3.5.0",
+ "resolved": "https://registry.npmjs.org/diff/-/diff-3.5.0.tgz",
+ "integrity": "sha512-A46qtFgd+g7pDZinpnwiRJtxbC1hpgf0uzP3iG89scHk0AUC7A1TGxf5OiiOUv/JMZR8GOt8hL900hV0bOy5xA==",
+ "dev": true
+ },
+ "diffie-hellman": {
+ "version": "5.0.3",
+ "resolved": "https://registry.npmjs.org/diffie-hellman/-/diffie-hellman-5.0.3.tgz",
+ "integrity": "sha512-kqag/Nl+f3GwyK25fhUMYj81BUOrZ9IuJsjIcDE5icNM9FJHAVm3VcUDxdLPoQtTuUylWm6ZIknYJwwaPxsUzg==",
+ "dev": true,
+ "requires": {
+ "bn.js": "^4.1.0",
+ "miller-rabin": "^4.0.0",
+ "randombytes": "^2.0.0"
+ }
+ },
+ "discontinuous-range": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/discontinuous-range/-/discontinuous-range-1.0.0.tgz",
+ "integrity": "sha1-44Mx8IRLukm5qctxx3FYWqsbxlo=",
+ "dev": true
+ },
+ "doctrine": {
+ "version": "1.5.0",
+ "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-1.5.0.tgz",
+ "integrity": "sha1-N53Ocw9hZvds76TmcHoVmwLFpvo=",
+ "dev": true,
+ "requires": {
+ "esutils": "^2.0.2",
+ "isarray": "^1.0.0"
+ }
+ },
+ "dom-helpers": {
+ "version": "5.1.3",
+ "resolved": "https://registry.npmjs.org/dom-helpers/-/dom-helpers-5.1.3.tgz",
+ "integrity": "sha512-nZD1OtwfWGRBWlpANxacBEZrEuLa16o1nh7YopFWeoF68Zt8GGEmzHu6Xv4F3XaFIC+YXtTLrzgqKxFgLEe4jw==",
+ "requires": {
+ "@babel/runtime": "^7.6.3",
+ "csstype": "^2.6.7"
+ }
+ },
+ "dom-serialize": {
+ "version": "2.2.1",
+ "resolved": "https://registry.npmjs.org/dom-serialize/-/dom-serialize-2.2.1.tgz",
+ "integrity": "sha1-ViromZ9Evl6jB29UGdzVnrQ6yVs=",
+ "dev": true,
+ "requires": {
+ "custom-event": "~1.0.0",
+ "ent": "~2.2.0",
+ "extend": "^3.0.0",
+ "void-elements": "^2.0.0"
+ }
+ },
+ "dom-serializer": {
+ "version": "0.1.1",
+ "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-0.1.1.tgz",
+ "integrity": "sha512-l0IU0pPzLWSHBcieZbpOKgkIn3ts3vAh7ZuFyXNwJxJXk/c4Gwj9xaTJwIDVQCXawWD0qb3IzMGH5rglQaO0XA==",
+ "dev": true,
+ "requires": {
+ "domelementtype": "^1.3.0",
+ "entities": "^1.1.1"
+ }
+ },
+ "domain-browser": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/domain-browser/-/domain-browser-1.2.0.tgz",
+ "integrity": "sha512-jnjyiM6eRyZl2H+W8Q/zLMA481hzi0eszAaBUzIVnmYVDBbnLxVNnfu1HgEBvCbL+71FrxMl3E6lpKH7Ge3OXA==",
+ "dev": true
+ },
+ "domelementtype": {
+ "version": "1.3.1",
+ "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-1.3.1.tgz",
+ "integrity": "sha512-BSKB+TSpMpFI/HOxCNr1O8aMOTZ8hT3pM3GQ0w/mWRmkhEDSFJkkyzz4XQsBV44BChwGkrDfMyjVD0eA2aFV3w==",
+ "dev": true
+ },
+ "domhandler": {
+ "version": "2.4.2",
+ "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-2.4.2.tgz",
+ "integrity": "sha512-JiK04h0Ht5u/80fdLMCEmV4zkNh2BcoMFBmZ/91WtYZ8qVXSKjiw7fXMgFPnHcSZgOo3XdinHvmnDUeMf5R4wA==",
+ "dev": true,
+ "requires": {
+ "domelementtype": "1"
+ }
+ },
+ "domutils": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/domutils/-/domutils-1.5.1.tgz",
+ "integrity": "sha1-3NhIiib1Y9YQeeSMn3t+Mjc2gs8=",
+ "dev": true,
+ "requires": {
+ "dom-serializer": "0",
+ "domelementtype": "1"
+ }
+ },
+ "duplexer": {
+ "version": "0.1.1",
+ "resolved": "https://registry.npmjs.org/duplexer/-/duplexer-0.1.1.tgz",
+ "integrity": "sha1-rOb/gIwc5mtX0ev5eXessCM0z8E=",
+ "dev": true
+ },
+ "duplexify": {
+ "version": "3.7.1",
+ "resolved": "https://registry.npmjs.org/duplexify/-/duplexify-3.7.1.tgz",
+ "integrity": "sha512-07z8uv2wMyS51kKhD1KsdXJg5WQ6t93RneqRxUHnskXVtlYYkLqM0gqStQZ3pj073g687jPCHrqNfCzawLYh5g==",
+ "dev": true,
+ "requires": {
+ "end-of-stream": "^1.0.0",
+ "inherits": "^2.0.1",
+ "readable-stream": "^2.0.0",
+ "stream-shift": "^1.0.0"
+ }
+ },
+ "ecc-jsbn": {
+ "version": "0.1.2",
+ "resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.2.tgz",
+ "integrity": "sha1-OoOpBOVDUyh4dMVkt1SThoSamMk=",
+ "dev": true,
+ "requires": {
+ "jsbn": "~0.1.0",
+ "safer-buffer": "^2.1.0"
+ }
+ },
+ "ee-first": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
+ "integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0=",
+ "dev": true
+ },
+ "elliptic": {
+ "version": "6.5.2",
+ "resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.5.2.tgz",
+ "integrity": "sha512-f4x70okzZbIQl/NSRLkI/+tteV/9WqL98zx+SQ69KbXxmVrmjwsNUPn/gYJJ0sHvEak24cZgHIPegRePAtA/xw==",
+ "dev": true,
+ "requires": {
+ "bn.js": "^4.4.0",
+ "brorand": "^1.0.1",
+ "hash.js": "^1.0.0",
+ "hmac-drbg": "^1.0.0",
+ "inherits": "^2.0.1",
+ "minimalistic-assert": "^1.0.0",
+ "minimalistic-crypto-utils": "^1.0.0"
+ }
+ },
+ "emoji-regex": {
+ "version": "7.0.3",
+ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-7.0.3.tgz",
+ "integrity": "sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==",
+ "dev": true
+ },
+ "emojis-list": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/emojis-list/-/emojis-list-2.1.0.tgz",
+ "integrity": "sha1-TapNnbAPmBmIDHn6RXrlsJof04k=",
+ "dev": true
+ },
+ "encodeurl": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz",
+ "integrity": "sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k=",
+ "dev": true
+ },
+ "end-of-stream": {
+ "version": "1.4.4",
+ "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.4.tgz",
+ "integrity": "sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q==",
+ "dev": true,
+ "requires": {
+ "once": "^1.4.0"
+ }
+ },
+ "engine.io": {
+ "version": "3.2.1",
+ "resolved": "https://registry.npmjs.org/engine.io/-/engine.io-3.2.1.tgz",
+ "integrity": "sha512-+VlKzHzMhaU+GsCIg4AoXF1UdDFjHHwMmMKqMJNDNLlUlejz58FCy4LBqB2YVJskHGYl06BatYWKP2TVdVXE5w==",
+ "dev": true,
+ "requires": {
+ "accepts": "~1.3.4",
+ "base64id": "1.0.0",
+ "cookie": "0.3.1",
+ "debug": "~3.1.0",
+ "engine.io-parser": "~2.1.0",
+ "ws": "~3.3.1"
+ },
+ "dependencies": {
+ "debug": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz",
+ "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==",
+ "dev": true,
+ "requires": {
+ "ms": "2.0.0"
+ }
+ },
+ "ms": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
+ "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=",
+ "dev": true
+ }
+ }
+ },
+ "engine.io-client": {
+ "version": "3.2.1",
+ "resolved": "https://registry.npmjs.org/engine.io-client/-/engine.io-client-3.2.1.tgz",
+ "integrity": "sha512-y5AbkytWeM4jQr7m/koQLc5AxpRKC1hEVUb/s1FUAWEJq5AzJJ4NLvzuKPuxtDi5Mq755WuDvZ6Iv2rXj4PTzw==",
+ "dev": true,
+ "requires": {
+ "component-emitter": "1.2.1",
+ "component-inherit": "0.0.3",
+ "debug": "~3.1.0",
+ "engine.io-parser": "~2.1.1",
+ "has-cors": "1.1.0",
+ "indexof": "0.0.1",
+ "parseqs": "0.0.5",
+ "parseuri": "0.0.5",
+ "ws": "~3.3.1",
+ "xmlhttprequest-ssl": "~1.5.4",
+ "yeast": "0.1.2"
+ },
+ "dependencies": {
+ "component-emitter": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.2.1.tgz",
+ "integrity": "sha1-E3kY1teCg/ffemt8WmPhQOaUJeY=",
+ "dev": true
+ },
+ "debug": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz",
+ "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==",
+ "dev": true,
+ "requires": {
+ "ms": "2.0.0"
+ }
+ },
+ "ms": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
+ "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=",
+ "dev": true
+ }
+ }
+ },
+ "engine.io-parser": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-2.1.3.tgz",
+ "integrity": "sha512-6HXPre2O4Houl7c4g7Ic/XzPnHBvaEmN90vtRO9uLmwtRqQmTOw0QMevL1TOfL2Cpu1VzsaTmMotQgMdkzGkVA==",
+ "dev": true,
+ "requires": {
+ "after": "0.8.2",
+ "arraybuffer.slice": "~0.0.7",
+ "base64-arraybuffer": "0.1.5",
+ "blob": "0.0.5",
+ "has-binary2": "~1.0.2"
+ }
+ },
+ "enhanced-resolve": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-4.1.1.tgz",
+ "integrity": "sha512-98p2zE+rL7/g/DzMHMTF4zZlCgeVdJ7yr6xzEpJRYwFYrGi9ANdn5DnJURg6RpBkyk60XYDnWIv51VfIhfNGuA==",
+ "dev": true,
+ "requires": {
+ "graceful-fs": "^4.1.2",
+ "memory-fs": "^0.5.0",
+ "tapable": "^1.0.0"
+ },
+ "dependencies": {
+ "memory-fs": {
+ "version": "0.5.0",
+ "resolved": "https://registry.npmjs.org/memory-fs/-/memory-fs-0.5.0.tgz",
+ "integrity": "sha512-jA0rdU5KoQMC0e6ppoNRtpp6vjFq6+NY7r8hywnC7V+1Xj/MtHwGIbB1QaK/dunyjWteJzmkpd7ooeWg10T7GA==",
+ "dev": true,
+ "requires": {
+ "errno": "^0.1.3",
+ "readable-stream": "^2.0.1"
+ }
+ }
+ }
+ },
+ "ent": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/ent/-/ent-2.2.0.tgz",
+ "integrity": "sha1-6WQhkyWiHQX0RGai9obtbOX13R0=",
+ "dev": true
+ },
+ "entities": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/entities/-/entities-1.1.2.tgz",
+ "integrity": "sha512-f2LZMYl1Fzu7YSBKg+RoROelpOaNrcGmE9AZubeDfrCEia483oW4MI4VyFd5VNHIgQ/7qm1I0wUHK1eJnn2y2w==",
+ "dev": true
+ },
+ "enzyme": {
+ "version": "3.11.0",
+ "resolved": "https://registry.npmjs.org/enzyme/-/enzyme-3.11.0.tgz",
+ "integrity": "sha512-Dw8/Gs4vRjxY6/6i9wU0V+utmQO9kvh9XLnz3LIudviOnVYDEe2ec+0k+NQoMamn1VrjKgCUOWj5jG/5M5M0Qw==",
+ "dev": true,
+ "requires": {
+ "array.prototype.flat": "^1.2.3",
+ "cheerio": "^1.0.0-rc.3",
+ "enzyme-shallow-equal": "^1.0.1",
+ "function.prototype.name": "^1.1.2",
+ "has": "^1.0.3",
+ "html-element-map": "^1.2.0",
+ "is-boolean-object": "^1.0.1",
+ "is-callable": "^1.1.5",
+ "is-number-object": "^1.0.4",
+ "is-regex": "^1.0.5",
+ "is-string": "^1.0.5",
+ "is-subset": "^0.1.1",
+ "lodash.escape": "^4.0.1",
+ "lodash.isequal": "^4.5.0",
+ "object-inspect": "^1.7.0",
+ "object-is": "^1.0.2",
+ "object.assign": "^4.1.0",
+ "object.entries": "^1.1.1",
+ "object.values": "^1.1.1",
+ "raf": "^3.4.1",
+ "rst-selector-parser": "^2.2.3",
+ "string.prototype.trim": "^1.2.1"
+ }
+ },
+ "enzyme-adapter-react-16": {
+ "version": "1.15.2",
+ "resolved": "https://registry.npmjs.org/enzyme-adapter-react-16/-/enzyme-adapter-react-16-1.15.2.tgz",
+ "integrity": "sha512-SkvDrb8xU3lSxID8Qic9rB8pvevDbLybxPK6D/vW7PrT0s2Cl/zJYuXvsd1EBTz0q4o3iqG3FJhpYz3nUNpM2Q==",
+ "dev": true,
+ "requires": {
+ "enzyme-adapter-utils": "^1.13.0",
+ "enzyme-shallow-equal": "^1.0.1",
+ "has": "^1.0.3",
+ "object.assign": "^4.1.0",
+ "object.values": "^1.1.1",
+ "prop-types": "^15.7.2",
+ "react-is": "^16.12.0",
+ "react-test-renderer": "^16.0.0-0",
+ "semver": "^5.7.0"
+ }
+ },
+ "enzyme-adapter-utils": {
+ "version": "1.13.0",
+ "resolved": "https://registry.npmjs.org/enzyme-adapter-utils/-/enzyme-adapter-utils-1.13.0.tgz",
+ "integrity": "sha512-YuEtfQp76Lj5TG1NvtP2eGJnFKogk/zT70fyYHXK2j3v6CtuHqc8YmgH/vaiBfL8K1SgVVbQXtTcgQZFwzTVyQ==",
+ "dev": true,
+ "requires": {
+ "airbnb-prop-types": "^2.15.0",
+ "function.prototype.name": "^1.1.2",
+ "object.assign": "^4.1.0",
+ "object.fromentries": "^2.0.2",
+ "prop-types": "^15.7.2",
+ "semver": "^5.7.1"
+ }
+ },
+ "enzyme-shallow-equal": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/enzyme-shallow-equal/-/enzyme-shallow-equal-1.0.1.tgz",
+ "integrity": "sha512-hGA3i1so8OrYOZSM9whlkNmVHOicJpsjgTzC+wn2JMJXhq1oO4kA4bJ5MsfzSIcC71aLDKzJ6gZpIxrqt3QTAQ==",
+ "dev": true,
+ "requires": {
+ "has": "^1.0.3",
+ "object-is": "^1.0.2"
+ }
+ },
+ "errno": {
+ "version": "0.1.7",
+ "resolved": "https://registry.npmjs.org/errno/-/errno-0.1.7.tgz",
+ "integrity": "sha512-MfrRBDWzIWifgq6tJj60gkAwtLNb6sQPlcFrSOflcP1aFmmruKQ2wRnze/8V6kgyz7H3FF8Npzv78mZ7XLLflg==",
+ "dev": true,
+ "requires": {
+ "prr": "~1.0.1"
+ }
+ },
+ "error-ex": {
+ "version": "1.3.2",
+ "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz",
+ "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==",
+ "dev": true,
+ "requires": {
+ "is-arrayish": "^0.2.1"
+ }
+ },
+ "es-abstract": {
+ "version": "1.17.4",
+ "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.17.4.tgz",
+ "integrity": "sha512-Ae3um/gb8F0mui/jPL+QiqmglkUsaQf7FwBEHYIFkztkneosu9imhqHpBzQ3h1vit8t5iQ74t6PEVvphBZiuiQ==",
+ "dev": true,
+ "requires": {
+ "es-to-primitive": "^1.2.1",
+ "function-bind": "^1.1.1",
+ "has": "^1.0.3",
+ "has-symbols": "^1.0.1",
+ "is-callable": "^1.1.5",
+ "is-regex": "^1.0.5",
+ "object-inspect": "^1.7.0",
+ "object-keys": "^1.1.1",
+ "object.assign": "^4.1.0",
+ "string.prototype.trimleft": "^2.1.1",
+ "string.prototype.trimright": "^2.1.1"
+ }
+ },
+ "es-to-primitive": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.1.tgz",
+ "integrity": "sha512-QCOllgZJtaUo9miYBcLChTUaHNjJF3PYs1VidD7AwiEj1kYxKeQTctLAezAOH5ZKRH0g2IgPn6KwB4IT8iRpvA==",
+ "dev": true,
+ "requires": {
+ "is-callable": "^1.1.4",
+ "is-date-object": "^1.0.1",
+ "is-symbol": "^1.0.2"
+ }
+ },
+ "es5-ext": {
+ "version": "0.10.53",
+ "resolved": "https://registry.npmjs.org/es5-ext/-/es5-ext-0.10.53.tgz",
+ "integrity": "sha512-Xs2Stw6NiNHWypzRTY1MtaG/uJlwCk8kH81920ma8mvN8Xq1gsfhZvpkImLQArw8AHnv8MT2I45J3c0R8slE+Q==",
+ "dev": true,
+ "requires": {
+ "es6-iterator": "~2.0.3",
+ "es6-symbol": "~3.1.3",
+ "next-tick": "~1.0.0"
+ }
+ },
+ "es6-iterator": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/es6-iterator/-/es6-iterator-2.0.3.tgz",
+ "integrity": "sha1-p96IkUGgWpSwhUQDstCg+/qY87c=",
+ "dev": true,
+ "requires": {
+ "d": "1",
+ "es5-ext": "^0.10.35",
+ "es6-symbol": "^3.1.1"
+ }
+ },
+ "es6-map": {
+ "version": "0.1.5",
+ "resolved": "https://registry.npmjs.org/es6-map/-/es6-map-0.1.5.tgz",
+ "integrity": "sha1-kTbgUD3MBqMBaQ8LsU/042TpSfA=",
+ "dev": true,
+ "requires": {
+ "d": "1",
+ "es5-ext": "~0.10.14",
+ "es6-iterator": "~2.0.1",
+ "es6-set": "~0.1.5",
+ "es6-symbol": "~3.1.1",
+ "event-emitter": "~0.3.5"
+ }
+ },
+ "es6-set": {
+ "version": "0.1.5",
+ "resolved": "https://registry.npmjs.org/es6-set/-/es6-set-0.1.5.tgz",
+ "integrity": "sha1-0rPsXU2ADO2BjbU40ol02wpzzLE=",
+ "dev": true,
+ "requires": {
+ "d": "1",
+ "es5-ext": "~0.10.14",
+ "es6-iterator": "~2.0.1",
+ "es6-symbol": "3.1.1",
+ "event-emitter": "~0.3.5"
+ },
+ "dependencies": {
+ "es6-symbol": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/es6-symbol/-/es6-symbol-3.1.1.tgz",
+ "integrity": "sha1-vwDvT9q2uhtG7Le2KbTH7VcVzHc=",
+ "dev": true,
+ "requires": {
+ "d": "1",
+ "es5-ext": "~0.10.14"
+ }
+ }
+ }
+ },
+ "es6-symbol": {
+ "version": "3.1.3",
+ "resolved": "https://registry.npmjs.org/es6-symbol/-/es6-symbol-3.1.3.tgz",
+ "integrity": "sha512-NJ6Yn3FuDinBaBRWl/q5X/s4koRHBrgKAu+yGI6JCBeiu3qrcbJhwT2GeR/EXVfylRk8dpQVJoLEFhK+Mu31NA==",
+ "dev": true,
+ "requires": {
+ "d": "^1.0.1",
+ "ext": "^1.1.2"
+ }
+ },
+ "es6-weak-map": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/es6-weak-map/-/es6-weak-map-2.0.3.tgz",
+ "integrity": "sha512-p5um32HOTO1kP+w7PRnB+5lQ43Z6muuMuIMffvDN8ZB4GcnjLBV6zGStpbASIMk4DCAvEaamhe2zhyCb/QXXsA==",
+ "dev": true,
+ "requires": {
+ "d": "1",
+ "es5-ext": "^0.10.46",
+ "es6-iterator": "^2.0.3",
+ "es6-symbol": "^3.1.1"
+ }
+ },
+ "escape-html": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
+ "integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg=",
+ "dev": true
+ },
+ "escape-string-regexp": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz",
+ "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=",
+ "dev": true
+ },
+ "escope": {
+ "version": "3.6.0",
+ "resolved": "https://registry.npmjs.org/escope/-/escope-3.6.0.tgz",
+ "integrity": "sha1-4Bl16BJ4GhY6ba392AOY3GTIicM=",
+ "dev": true,
+ "requires": {
+ "es6-map": "^0.1.3",
+ "es6-weak-map": "^2.0.1",
+ "esrecurse": "^4.1.0",
+ "estraverse": "^4.1.1"
+ }
+ },
+ "eslint": {
+ "version": "2.13.1",
+ "resolved": "https://registry.npmjs.org/eslint/-/eslint-2.13.1.tgz",
+ "integrity": "sha1-5MyPoPAJ+4KaquI4VaKTYL4fbBE=",
+ "dev": true,
+ "requires": {
+ "chalk": "^1.1.3",
+ "concat-stream": "^1.4.6",
+ "debug": "^2.1.1",
+ "doctrine": "^1.2.2",
+ "es6-map": "^0.1.3",
+ "escope": "^3.6.0",
+ "espree": "^3.1.6",
+ "estraverse": "^4.2.0",
+ "esutils": "^2.0.2",
+ "file-entry-cache": "^1.1.1",
+ "glob": "^7.0.3",
+ "globals": "^9.2.0",
+ "ignore": "^3.1.2",
+ "imurmurhash": "^0.1.4",
+ "inquirer": "^0.12.0",
+ "is-my-json-valid": "^2.10.0",
+ "is-resolvable": "^1.0.0",
+ "js-yaml": "^3.5.1",
+ "json-stable-stringify": "^1.0.0",
+ "levn": "^0.3.0",
+ "lodash": "^4.0.0",
+ "mkdirp": "^0.5.0",
+ "optionator": "^0.8.1",
+ "path-is-absolute": "^1.0.0",
+ "path-is-inside": "^1.0.1",
+ "pluralize": "^1.2.1",
+ "progress": "^1.1.8",
+ "require-uncached": "^1.0.2",
+ "shelljs": "^0.6.0",
+ "strip-json-comments": "~1.0.1",
+ "table": "^3.7.8",
+ "text-table": "~0.2.0",
+ "user-home": "^2.0.0"
+ },
+ "dependencies": {
+ "ansi-styles": {
+ "version": "2.2.1",
+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz",
+ "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=",
+ "dev": true
+ },
+ "chalk": {
+ "version": "1.1.3",
+ "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz",
+ "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=",
+ "dev": true,
+ "requires": {
+ "ansi-styles": "^2.2.1",
+ "escape-string-regexp": "^1.0.2",
+ "has-ansi": "^2.0.0",
+ "strip-ansi": "^3.0.0",
+ "supports-color": "^2.0.0"
+ }
+ },
+ "debug": {
+ "version": "2.6.9",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
+ "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
+ "dev": true,
+ "requires": {
+ "ms": "2.0.0"
+ }
+ },
+ "globals": {
+ "version": "9.18.0",
+ "resolved": "https://registry.npmjs.org/globals/-/globals-9.18.0.tgz",
+ "integrity": "sha512-S0nG3CLEQiY/ILxqtztTWH/3iRRdyBLw6KMDxnKMchrtbj2OFmehVh0WUCfW3DUrIgx/qFrJPICrq4Z4sTR9UQ==",
+ "dev": true
+ },
+ "ms": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
+ "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=",
+ "dev": true
+ },
+ "shelljs": {
+ "version": "0.6.1",
+ "resolved": "https://registry.npmjs.org/shelljs/-/shelljs-0.6.1.tgz",
+ "integrity": "sha1-7GIRvtGSBEIIj+D3Cyg3Iy7SyKg=",
+ "dev": true
+ },
+ "strip-json-comments": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-1.0.4.tgz",
+ "integrity": "sha1-HhX7ysl9Pumb8tc7TGVrCCu6+5E=",
+ "dev": true
+ },
+ "supports-color": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz",
+ "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=",
+ "dev": true
+ }
+ }
+ },
+ "eslint-scope": {
+ "version": "4.0.3",
+ "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-4.0.3.tgz",
+ "integrity": "sha512-p7VutNr1O/QrxysMo3E45FjYDTeXBy0iTltPFNSqKAIfjDSXC+4dj+qfyuD8bfAXrW/y6lW3O76VaYNPKfpKrg==",
+ "dev": true,
+ "requires": {
+ "esrecurse": "^4.1.0",
+ "estraverse": "^4.1.1"
+ }
+ },
+ "espree": {
+ "version": "3.5.4",
+ "resolved": "https://registry.npmjs.org/espree/-/espree-3.5.4.tgz",
+ "integrity": "sha512-yAcIQxtmMiB/jL32dzEp2enBeidsB7xWPLNiw3IIkpVds1P+h7qF9YwJq1yUNzp2OKXgAprs4F61ih66UsoD1A==",
+ "dev": true,
+ "requires": {
+ "acorn": "^5.5.0",
+ "acorn-jsx": "^3.0.0"
+ },
+ "dependencies": {
+ "acorn": {
+ "version": "5.7.3",
+ "resolved": "https://registry.npmjs.org/acorn/-/acorn-5.7.3.tgz",
+ "integrity": "sha512-T/zvzYRfbVojPWahDsE5evJdHb3oJoQfFbsrKM7w5Zcs++Tr257tia3BmMP8XYVjp1S9RZXQMh7gao96BlqZOw==",
+ "dev": true
+ }
+ }
+ },
+ "esprima": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz",
+ "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==",
+ "dev": true
+ },
+ "esrecurse": {
+ "version": "4.2.1",
+ "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.2.1.tgz",
+ "integrity": "sha512-64RBB++fIOAXPw3P9cy89qfMlvZEXZkqqJkjqqXIvzP5ezRZjW+lPWjw35UX/3EhUPFYbg5ER4JYgDw4007/DQ==",
+ "dev": true,
+ "requires": {
+ "estraverse": "^4.1.0"
+ }
+ },
+ "estraverse": {
+ "version": "4.3.0",
+ "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz",
+ "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==",
+ "dev": true
+ },
+ "esutils": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz",
+ "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==",
+ "dev": true
+ },
+ "event-emitter": {
+ "version": "0.3.5",
+ "resolved": "https://registry.npmjs.org/event-emitter/-/event-emitter-0.3.5.tgz",
+ "integrity": "sha1-34xp7vFkeSPHFXuc6DhAYQsCzDk=",
+ "dev": true,
+ "requires": {
+ "d": "1",
+ "es5-ext": "~0.10.14"
+ }
+ },
+ "eventemitter3": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.0.tgz",
+ "integrity": "sha512-qerSRB0p+UDEssxTtm6EDKcE7W4OaoisfIMl4CngyEhjpYglocpNg6UEqCvemdGhosAsg4sO2dXJOdyBifPGCg==",
+ "dev": true
+ },
+ "events": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/events/-/events-3.1.0.tgz",
+ "integrity": "sha512-Rv+u8MLHNOdMjTAFeT3nCjHn2aGlx435FP/sDHNaRhDEMwyI/aB22Kj2qIN8R0cw3z28psEQLYwxVKLsKrMgWg==",
+ "dev": true
+ },
+ "evp_bytestokey": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/evp_bytestokey/-/evp_bytestokey-1.0.3.tgz",
+ "integrity": "sha512-/f2Go4TognH/KvCISP7OUsHn85hT9nUkxxA9BEWxFn+Oj9o8ZNLm/40hdlgSLyuOimsrTKLUMEorQexp/aPQeA==",
+ "dev": true,
+ "requires": {
+ "md5.js": "^1.3.4",
+ "safe-buffer": "^5.1.1"
+ }
+ },
+ "execa": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/execa/-/execa-1.0.0.tgz",
+ "integrity": "sha512-adbxcyWV46qiHyvSp50TKt05tB4tK3HcmF7/nxfAdhnox83seTDbwnaqKO4sXRy7roHAIFqJP/Rw/AuEbX61LA==",
+ "dev": true,
+ "requires": {
+ "cross-spawn": "^6.0.0",
+ "get-stream": "^4.0.0",
+ "is-stream": "^1.1.0",
+ "npm-run-path": "^2.0.0",
+ "p-finally": "^1.0.0",
+ "signal-exit": "^3.0.0",
+ "strip-eof": "^1.0.0"
+ },
+ "dependencies": {
+ "cross-spawn": {
+ "version": "6.0.5",
+ "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz",
+ "integrity": "sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==",
+ "dev": true,
+ "requires": {
+ "nice-try": "^1.0.4",
+ "path-key": "^2.0.1",
+ "semver": "^5.5.0",
+ "shebang-command": "^1.2.0",
+ "which": "^1.2.9"
+ }
+ }
+ }
+ },
+ "exit-hook": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/exit-hook/-/exit-hook-1.1.1.tgz",
+ "integrity": "sha1-8FyiM7SMBdVP/wd2XfhQfpXAL/g=",
+ "dev": true
+ },
+ "expand-brackets": {
+ "version": "0.1.5",
+ "resolved": "https://registry.npmjs.org/expand-brackets/-/expand-brackets-0.1.5.tgz",
+ "integrity": "sha1-3wcoTjQqgHzXM6xa9yQR5YHRF3s=",
+ "dev": true,
+ "requires": {
+ "is-posix-bracket": "^0.1.0"
+ }
+ },
+ "expand-range": {
+ "version": "1.8.2",
+ "resolved": "https://registry.npmjs.org/expand-range/-/expand-range-1.8.2.tgz",
+ "integrity": "sha1-opnv/TNf4nIeuujiV+x5ZE/IUzc=",
+ "dev": true,
+ "requires": {
+ "fill-range": "^2.1.0"
+ }
+ },
+ "expand-tilde": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/expand-tilde/-/expand-tilde-2.0.2.tgz",
+ "integrity": "sha1-l+gBqgUt8CRU3kawK/YhZCzchQI=",
+ "dev": true,
+ "requires": {
+ "homedir-polyfill": "^1.0.1"
+ }
+ },
+ "ext": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/ext/-/ext-1.4.0.tgz",
+ "integrity": "sha512-Key5NIsUxdqKg3vIsdw9dSuXpPCQ297y6wBjL30edxwPgt2E44WcWBZey/ZvUc6sERLTxKdyCu4gZFmUbk1Q7A==",
+ "dev": true,
+ "requires": {
+ "type": "^2.0.0"
+ },
+ "dependencies": {
+ "type": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/type/-/type-2.0.0.tgz",
+ "integrity": "sha512-KBt58xCHry4Cejnc2ISQAF7QY+ORngsWfxezO68+12hKV6lQY8P/psIkcbjeHWn7MqcgciWJyCCevFMJdIXpow==",
+ "dev": true
+ }
+ }
+ },
+ "extend": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz",
+ "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==",
+ "dev": true
+ },
+ "extend-shallow": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-3.0.2.tgz",
+ "integrity": "sha1-Jqcarwc7OfshJxcnRhMcJwQCjbg=",
+ "dev": true,
+ "requires": {
+ "assign-symbols": "^1.0.0",
+ "is-extendable": "^1.0.1"
+ },
+ "dependencies": {
+ "is-extendable": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-1.0.1.tgz",
+ "integrity": "sha512-arnXMxT1hhoKo9k1LZdmlNyJdDDfy2v0fXjFlmok4+i8ul/6WlbVge9bhM74OpNPQPMGUToDtz+KXa1PneJxOA==",
+ "dev": true,
+ "requires": {
+ "is-plain-object": "^2.0.4"
+ }
+ }
+ }
+ },
+ "extglob": {
+ "version": "0.3.2",
+ "resolved": "https://registry.npmjs.org/extglob/-/extglob-0.3.2.tgz",
+ "integrity": "sha1-Lhj/PS9JqydlzskCPwEdqo2DSaE=",
+ "dev": true,
+ "requires": {
+ "is-extglob": "^1.0.0"
+ }
+ },
+ "extsprintf": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.3.0.tgz",
+ "integrity": "sha1-lpGEQOMEGnpBT4xS48V06zw+HgU=",
+ "dev": true
+ },
+ "fast-deep-equal": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-1.1.0.tgz",
+ "integrity": "sha1-wFNHeBfIa1HaqFPIHgWbcz0CNhQ=",
+ "dev": true
+ },
+ "fast-json-stable-stringify": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz",
+ "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==",
+ "dev": true
+ },
+ "fast-levenshtein": {
+ "version": "2.0.6",
+ "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz",
+ "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=",
+ "dev": true
+ },
+ "figgy-pudding": {
+ "version": "3.5.1",
+ "resolved": "https://registry.npmjs.org/figgy-pudding/-/figgy-pudding-3.5.1.tgz",
+ "integrity": "sha512-vNKxJHTEKNThjfrdJwHc7brvM6eVevuO5nTj6ez8ZQ1qbXTvGthucRF7S4vf2cr71QVnT70V34v0S1DyQsti0w==",
+ "dev": true
+ },
+ "figures": {
+ "version": "1.7.0",
+ "resolved": "https://registry.npmjs.org/figures/-/figures-1.7.0.tgz",
+ "integrity": "sha1-y+Hjr/zxzUS4DK3+0o3Hk6lwHS4=",
+ "dev": true,
+ "requires": {
+ "escape-string-regexp": "^1.0.5",
+ "object-assign": "^4.1.0"
+ }
+ },
+ "file-entry-cache": {
+ "version": "1.3.1",
+ "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-1.3.1.tgz",
+ "integrity": "sha1-RMYepgeuS+nBQC9B9EJwy/4zT/g=",
+ "dev": true,
+ "requires": {
+ "flat-cache": "^1.2.1",
+ "object-assign": "^4.0.1"
+ }
+ },
+ "file-uri-to-path": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz",
+ "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==",
+ "dev": true,
+ "optional": true
+ },
+ "filename-regex": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/filename-regex/-/filename-regex-2.0.1.tgz",
+ "integrity": "sha1-wcS5vuPglyXdsQa3XB4wH+LxiyY=",
+ "dev": true
+ },
+ "fileset": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/fileset/-/fileset-2.0.3.tgz",
+ "integrity": "sha1-jnVIqW08wjJ+5eZ0FocjozO7oqA=",
+ "dev": true,
+ "requires": {
+ "glob": "^7.0.3",
+ "minimatch": "^3.0.3"
+ }
+ },
+ "fill-range": {
+ "version": "2.2.4",
+ "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-2.2.4.tgz",
+ "integrity": "sha512-cnrcCbj01+j2gTG921VZPnHbjmdAf8oQV/iGeV2kZxGSyfYjjTyY79ErsK1WJWMpw6DaApEX72binqJE+/d+5Q==",
+ "dev": true,
+ "requires": {
+ "is-number": "^2.1.0",
+ "isobject": "^2.0.0",
+ "randomatic": "^3.0.0",
+ "repeat-element": "^1.1.2",
+ "repeat-string": "^1.5.2"
+ }
+ },
+ "finalhandler": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.1.2.tgz",
+ "integrity": "sha512-aAWcW57uxVNrQZqFXjITpW3sIUQmHGG3qSb9mUah9MgMC4NeWhNOlNjXEYq3HjRAvL6arUviZGGJsBg6z0zsWA==",
+ "dev": true,
+ "requires": {
+ "debug": "2.6.9",
+ "encodeurl": "~1.0.2",
+ "escape-html": "~1.0.3",
+ "on-finished": "~2.3.0",
+ "parseurl": "~1.3.3",
+ "statuses": "~1.5.0",
+ "unpipe": "~1.0.0"
+ },
+ "dependencies": {
+ "debug": {
+ "version": "2.6.9",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
+ "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
+ "dev": true,
+ "requires": {
+ "ms": "2.0.0"
+ }
+ },
+ "ms": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
+ "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=",
+ "dev": true
+ }
+ }
+ },
+ "find-cache-dir": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/find-cache-dir/-/find-cache-dir-2.1.0.tgz",
+ "integrity": "sha512-Tq6PixE0w/VMFfCgbONnkiQIVol/JJL7nRMi20fqzA4NRs9AfeqMGeRdPi3wIhYkxjeBaWh2rxwapn5Tu3IqOQ==",
+ "dev": true,
+ "requires": {
+ "commondir": "^1.0.1",
+ "make-dir": "^2.0.0",
+ "pkg-dir": "^3.0.0"
+ }
+ },
+ "find-index": {
+ "version": "0.1.1",
+ "resolved": "https://registry.npmjs.org/find-index/-/find-index-0.1.1.tgz",
+ "integrity": "sha1-Z101iyyjiS15Whq0cjL4tuLg3eQ=",
+ "dev": true
+ },
+ "find-up": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz",
+ "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==",
+ "dev": true,
+ "requires": {
+ "locate-path": "^3.0.0"
+ }
+ },
+ "findup-sync": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/findup-sync/-/findup-sync-3.0.0.tgz",
+ "integrity": "sha512-YbffarhcicEhOrm4CtrwdKBdCuz576RLdhJDsIfvNtxUuhdRet1qZcsMjqbePtAseKdAnDyM/IyXbu7PRPRLYg==",
+ "dev": true,
+ "requires": {
+ "detect-file": "^1.0.0",
+ "is-glob": "^4.0.0",
+ "micromatch": "^3.0.4",
+ "resolve-dir": "^1.0.1"
+ },
+ "dependencies": {
+ "arr-diff": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-4.0.0.tgz",
+ "integrity": "sha1-1kYQdP6/7HHn4VI1dhoyml3HxSA=",
+ "dev": true
+ },
+ "array-unique": {
+ "version": "0.3.2",
+ "resolved": "https://registry.npmjs.org/array-unique/-/array-unique-0.3.2.tgz",
+ "integrity": "sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg=",
+ "dev": true
+ },
+ "braces": {
+ "version": "2.3.2",
+ "resolved": "https://registry.npmjs.org/braces/-/braces-2.3.2.tgz",
+ "integrity": "sha512-aNdbnj9P8PjdXU4ybaWLK2IF3jc/EoDYbC7AazW6to3TRsfXxscC9UXOB5iDiEQrkyIbWp2SLQda4+QAa7nc3w==",
+ "dev": true,
+ "requires": {
+ "arr-flatten": "^1.1.0",
+ "array-unique": "^0.3.2",
+ "extend-shallow": "^2.0.1",
+ "fill-range": "^4.0.0",
+ "isobject": "^3.0.1",
+ "repeat-element": "^1.1.2",
+ "snapdragon": "^0.8.1",
+ "snapdragon-node": "^2.0.1",
+ "split-string": "^3.0.2",
+ "to-regex": "^3.0.1"
+ },
+ "dependencies": {
+ "extend-shallow": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz",
+ "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=",
+ "dev": true,
+ "requires": {
+ "is-extendable": "^0.1.0"
+ }
+ }
+ }
+ },
+ "debug": {
+ "version": "2.6.9",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
+ "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
+ "dev": true,
+ "requires": {
+ "ms": "2.0.0"
+ }
+ },
+ "expand-brackets": {
+ "version": "2.1.4",
+ "resolved": "https://registry.npmjs.org/expand-brackets/-/expand-brackets-2.1.4.tgz",
+ "integrity": "sha1-t3c14xXOMPa27/D4OwQVGiJEliI=",
+ "dev": true,
+ "requires": {
+ "debug": "^2.3.3",
+ "define-property": "^0.2.5",
+ "extend-shallow": "^2.0.1",
+ "posix-character-classes": "^0.1.0",
+ "regex-not": "^1.0.0",
+ "snapdragon": "^0.8.1",
+ "to-regex": "^3.0.1"
+ },
+ "dependencies": {
+ "define-property": {
+ "version": "0.2.5",
+ "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz",
+ "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=",
+ "dev": true,
+ "requires": {
+ "is-descriptor": "^0.1.0"
+ }
+ },
+ "extend-shallow": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz",
+ "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=",
+ "dev": true,
+ "requires": {
+ "is-extendable": "^0.1.0"
+ }
+ },
+ "is-accessor-descriptor": {
+ "version": "0.1.6",
+ "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz",
+ "integrity": "sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=",
+ "dev": true,
+ "requires": {
+ "kind-of": "^3.0.2"
+ },
+ "dependencies": {
+ "kind-of": {
+ "version": "3.2.2",
+ "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz",
+ "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=",
+ "dev": true,
+ "requires": {
+ "is-buffer": "^1.1.5"
+ }
+ }
+ }
+ },
+ "is-data-descriptor": {
+ "version": "0.1.4",
+ "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz",
+ "integrity": "sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=",
+ "dev": true,
+ "requires": {
+ "kind-of": "^3.0.2"
+ },
+ "dependencies": {
+ "kind-of": {
+ "version": "3.2.2",
+ "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz",
+ "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=",
+ "dev": true,
+ "requires": {
+ "is-buffer": "^1.1.5"
+ }
+ }
+ }
+ },
+ "is-descriptor": {
+ "version": "0.1.6",
+ "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-0.1.6.tgz",
+ "integrity": "sha512-avDYr0SB3DwO9zsMov0gKCESFYqCnE4hq/4z3TdUlukEy5t9C0YRq7HLrsN52NAcqXKaepeCD0n+B0arnVG3Hg==",
+ "dev": true,
+ "requires": {
+ "is-accessor-descriptor": "^0.1.6",
+ "is-data-descriptor": "^0.1.4",
+ "kind-of": "^5.0.0"
+ }
+ },
+ "kind-of": {
+ "version": "5.1.0",
+ "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-5.1.0.tgz",
+ "integrity": "sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw==",
+ "dev": true
+ }
+ }
+ },
+ "extglob": {
+ "version": "2.0.4",
+ "resolved": "https://registry.npmjs.org/extglob/-/extglob-2.0.4.tgz",
+ "integrity": "sha512-Nmb6QXkELsuBr24CJSkilo6UHHgbekK5UiZgfE6UHD3Eb27YC6oD+bhcT+tJ6cl8dmsgdQxnWlcry8ksBIBLpw==",
+ "dev": true,
+ "requires": {
+ "array-unique": "^0.3.2",
+ "define-property": "^1.0.0",
+ "expand-brackets": "^2.1.4",
+ "extend-shallow": "^2.0.1",
+ "fragment-cache": "^0.2.1",
+ "regex-not": "^1.0.0",
+ "snapdragon": "^0.8.1",
+ "to-regex": "^3.0.1"
+ },
+ "dependencies": {
+ "define-property": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/define-property/-/define-property-1.0.0.tgz",
+ "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=",
+ "dev": true,
+ "requires": {
+ "is-descriptor": "^1.0.0"
+ }
+ },
+ "extend-shallow": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz",
+ "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=",
+ "dev": true,
+ "requires": {
+ "is-extendable": "^0.1.0"
+ }
+ }
+ }
+ },
+ "fill-range": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-4.0.0.tgz",
+ "integrity": "sha1-1USBHUKPmOsGpj3EAtJAPDKMOPc=",
+ "dev": true,
+ "requires": {
+ "extend-shallow": "^2.0.1",
+ "is-number": "^3.0.0",
+ "repeat-string": "^1.6.1",
+ "to-regex-range": "^2.1.0"
+ },
+ "dependencies": {
+ "extend-shallow": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz",
+ "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=",
+ "dev": true,
+ "requires": {
+ "is-extendable": "^0.1.0"
+ }
+ }
+ }
+ },
+ "is-accessor-descriptor": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz",
+ "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==",
+ "dev": true,
+ "requires": {
+ "kind-of": "^6.0.0"
+ }
+ },
+ "is-data-descriptor": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz",
+ "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==",
+ "dev": true,
+ "requires": {
+ "kind-of": "^6.0.0"
+ }
+ },
+ "is-descriptor": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz",
+ "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==",
+ "dev": true,
+ "requires": {
+ "is-accessor-descriptor": "^1.0.0",
+ "is-data-descriptor": "^1.0.0",
+ "kind-of": "^6.0.2"
+ }
+ },
+ "is-extglob": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",
+ "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=",
+ "dev": true
+ },
+ "is-glob": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.1.tgz",
+ "integrity": "sha512-5G0tKtBTFImOqDnLB2hG6Bp2qcKEFduo4tZu9MT/H6NQv/ghhy30o55ufafxJ/LdH79LLs2Kfrn85TLKyA7BUg==",
+ "dev": true,
+ "requires": {
+ "is-extglob": "^2.1.1"
+ }
+ },
+ "is-number": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/is-number/-/is-number-3.0.0.tgz",
+ "integrity": "sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=",
+ "dev": true,
+ "requires": {
+ "kind-of": "^3.0.2"
+ },
+ "dependencies": {
+ "kind-of": {
+ "version": "3.2.2",
+ "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz",
+ "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=",
+ "dev": true,
+ "requires": {
+ "is-buffer": "^1.1.5"
+ }
+ }
+ }
+ },
+ "isobject": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz",
+ "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=",
+ "dev": true
+ },
+ "kind-of": {
+ "version": "6.0.3",
+ "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz",
+ "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==",
+ "dev": true
+ },
+ "micromatch": {
+ "version": "3.1.10",
+ "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-3.1.10.tgz",
+ "integrity": "sha512-MWikgl9n9M3w+bpsY3He8L+w9eF9338xRl8IAO5viDizwSzziFEyUzo2xrrloB64ADbTf8uA8vRqqttDTOmccg==",
+ "dev": true,
+ "requires": {
+ "arr-diff": "^4.0.0",
+ "array-unique": "^0.3.2",
+ "braces": "^2.3.1",
+ "define-property": "^2.0.2",
+ "extend-shallow": "^3.0.2",
+ "extglob": "^2.0.4",
+ "fragment-cache": "^0.2.1",
+ "kind-of": "^6.0.2",
+ "nanomatch": "^1.2.9",
+ "object.pick": "^1.3.0",
+ "regex-not": "^1.0.0",
+ "snapdragon": "^0.8.1",
+ "to-regex": "^3.0.2"
+ }
+ },
+ "ms": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
+ "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=",
+ "dev": true
+ }
+ }
+ },
+ "flat": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/flat/-/flat-4.1.0.tgz",
+ "integrity": "sha512-Px/TiLIznH7gEDlPXcUD4KnBusa6kR6ayRUVcnEAbreRIuhkqow/mun59BuRXwoYk7ZQOLW1ZM05ilIvK38hFw==",
+ "dev": true,
+ "requires": {
+ "is-buffer": "~2.0.3"
+ },
+ "dependencies": {
+ "is-buffer": {
+ "version": "2.0.4",
+ "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-2.0.4.tgz",
+ "integrity": "sha512-Kq1rokWXOPXWuaMAqZiJW4XxsmD9zGx9q4aePabbn3qCRGedtH7Cm+zV8WETitMfu1wdh+Rvd6w5egwSngUX2A==",
+ "dev": true
+ }
+ }
+ },
+ "flat-cache": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-1.3.4.tgz",
+ "integrity": "sha512-VwyB3Lkgacfik2vhqR4uv2rvebqmDvFu4jlN/C1RzWoJEo8I7z4Q404oiqYCkq41mni8EzQnm95emU9seckwtg==",
+ "dev": true,
+ "requires": {
+ "circular-json": "^0.3.1",
+ "graceful-fs": "^4.1.2",
+ "rimraf": "~2.6.2",
+ "write": "^0.2.1"
+ },
+ "dependencies": {
+ "rimraf": {
+ "version": "2.6.3",
+ "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.3.tgz",
+ "integrity": "sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA==",
+ "dev": true,
+ "requires": {
+ "glob": "^7.1.3"
+ }
+ }
+ }
+ },
+ "flatted": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/flatted/-/flatted-2.0.1.tgz",
+ "integrity": "sha512-a1hQMktqW9Nmqr5aktAux3JMNqaucxGcjtjWnZLHX7yyPCmlSV3M54nGYbqT8K+0GhF3NBgmJCc3ma+WOgX8Jg==",
+ "dev": true
+ },
+ "fluent": {
+ "version": "0.13.0",
+ "resolved": "https://registry.npmjs.org/fluent/-/fluent-0.13.0.tgz",
+ "integrity": "sha512-veZ4VyzNiBnRAfUagBpXWVyOHPns7z00UtuYWoqWjlogFgHGzDo3b2v3+gNkxxyd44uPP6NBUkgLaHlC6sQm5g=="
+ },
+ "fluent-react": {
+ "version": "0.9.0",
+ "resolved": "https://registry.npmjs.org/fluent-react/-/fluent-react-0.9.0.tgz",
+ "integrity": "sha512-4Cd+5xwxPHn8b1ALleeMQH8CN+skh/86lWouED3tLPVXj7qFw+S/FCNmtKsY5JN4QH2QoOxH4FyM41PGCuvhGg==",
+ "requires": {
+ "cached-iterable": "^0.2.1",
+ "fluent-sequence": "^0.2.0",
+ "prop-types": "^15.6.0"
+ }
+ },
+ "fluent-sequence": {
+ "version": "0.2.0",
+ "resolved": "https://registry.npmjs.org/fluent-sequence/-/fluent-sequence-0.2.0.tgz",
+ "integrity": "sha512-t8fc4rHvzO9Yk8otP8LkTqWo6mzjdemooQcnHlDrNzrYAnwsSbVFIlthnkzK2pLsRnO9Ybmw4lXOYUx+fAIyJw=="
+ },
+ "flush-write-stream": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/flush-write-stream/-/flush-write-stream-1.1.1.tgz",
+ "integrity": "sha512-3Z4XhFZ3992uIq0XOqb9AreonueSYphE6oYbpt5+3u06JWklbsPkNv3ZKkP9Bz/r+1MWCaMoSQ28P85+1Yc77w==",
+ "dev": true,
+ "requires": {
+ "inherits": "^2.0.3",
+ "readable-stream": "^2.3.6"
+ }
+ },
+ "follow-redirects": {
+ "version": "1.10.0",
+ "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.10.0.tgz",
+ "integrity": "sha512-4eyLK6s6lH32nOvLLwlIOnr9zrL8Sm+OvW4pVTJNoXeGzYIkHVf+pADQi+OJ0E67hiuSLezPVPyBcIZO50TmmQ==",
+ "dev": true,
+ "requires": {
+ "debug": "^3.0.0"
+ },
+ "dependencies": {
+ "debug": {
+ "version": "3.2.6",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz",
+ "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==",
+ "dev": true,
+ "requires": {
+ "ms": "^2.1.1"
+ }
+ }
+ }
+ },
+ "for-in": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/for-in/-/for-in-1.0.2.tgz",
+ "integrity": "sha1-gQaNKVqBQuwKxybG4iAMMPttXoA=",
+ "dev": true
+ },
+ "for-own": {
+ "version": "0.1.5",
+ "resolved": "https://registry.npmjs.org/for-own/-/for-own-0.1.5.tgz",
+ "integrity": "sha1-UmXGgaTylNq78XyVCbZ2OqhFEM4=",
+ "dev": true,
+ "requires": {
+ "for-in": "^1.0.1"
+ }
+ },
+ "forever-agent": {
+ "version": "0.6.1",
+ "resolved": "https://registry.npmjs.org/forever-agent/-/forever-agent-0.6.1.tgz",
+ "integrity": "sha1-+8cfDEGt6zf5bFd60e1C2P2sypE=",
+ "dev": true
+ },
+ "form-data": {
+ "version": "2.3.3",
+ "resolved": "https://registry.npmjs.org/form-data/-/form-data-2.3.3.tgz",
+ "integrity": "sha512-1lLKB2Mu3aGP1Q/2eCOx0fNbRMe7XdwktwOruhfqqd0rIJWwN4Dh+E3hrPSlDCXnSR7UtZ1N38rVXm+6+MEhJQ==",
+ "dev": true,
+ "requires": {
+ "asynckit": "^0.4.0",
+ "combined-stream": "^1.0.6",
+ "mime-types": "^2.1.12"
+ }
+ },
+ "fragment-cache": {
+ "version": "0.2.1",
+ "resolved": "https://registry.npmjs.org/fragment-cache/-/fragment-cache-0.2.1.tgz",
+ "integrity": "sha1-QpD60n8T6Jvn8zeZxrxaCr//DRk=",
+ "dev": true,
+ "requires": {
+ "map-cache": "^0.2.2"
+ }
+ },
+ "from2": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/from2/-/from2-2.3.0.tgz",
+ "integrity": "sha1-i/tVAr3kpNNs/e6gB/zKIdfjgq8=",
+ "dev": true,
+ "requires": {
+ "inherits": "^2.0.1",
+ "readable-stream": "^2.0.0"
+ }
+ },
+ "front-matter": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/front-matter/-/front-matter-2.1.2.tgz",
+ "integrity": "sha1-91mDufL0E75ljJPf172M5AePXNs=",
+ "dev": true,
+ "requires": {
+ "js-yaml": "^3.4.6"
+ }
+ },
+ "fs-extra": {
+ "version": "7.0.1",
+ "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-7.0.1.tgz",
+ "integrity": "sha512-YJDaCJZEnBmcbw13fvdAM9AwNOJwOzrE4pqMqBq5nFiEqXUqHwlK4B+3pUw6JNvfSPtX05xFHtYy/1ni01eGCw==",
+ "dev": true,
+ "requires": {
+ "graceful-fs": "^4.1.2",
+ "jsonfile": "^4.0.0",
+ "universalify": "^0.1.0"
+ }
+ },
+ "fs-write-stream-atomic": {
+ "version": "1.0.10",
+ "resolved": "https://registry.npmjs.org/fs-write-stream-atomic/-/fs-write-stream-atomic-1.0.10.tgz",
+ "integrity": "sha1-tH31NJPvkR33VzHnCp3tAYnbQMk=",
+ "dev": true,
+ "requires": {
+ "graceful-fs": "^4.1.2",
+ "iferr": "^0.1.5",
+ "imurmurhash": "^0.1.4",
+ "readable-stream": "1 || 2"
+ }
+ },
+ "fs.realpath": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",
+ "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=",
+ "dev": true
+ },
+ "fsevents": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-1.2.11.tgz",
+ "integrity": "sha512-+ux3lx6peh0BpvY0JebGyZoiR4D+oYzdPZMKJwkZ+sFkNJzpL7tXc/wehS49gUAxg3tmMHPHZkA8JU2rhhgDHw==",
+ "dev": true,
+ "optional": true,
+ "requires": {
+ "bindings": "^1.5.0",
+ "nan": "^2.12.1",
+ "node-pre-gyp": "*"
+ },
+ "dependencies": {
+ "abbrev": {
+ "version": "1.1.1",
+ "bundled": true,
+ "dev": true,
+ "optional": true
+ },
+ "ansi-regex": {
+ "version": "2.1.1",
+ "bundled": true,
+ "dev": true,
+ "optional": true
+ },
+ "aproba": {
+ "version": "1.2.0",
+ "bundled": true,
+ "dev": true,
+ "optional": true
+ },
+ "are-we-there-yet": {
+ "version": "1.1.5",
+ "bundled": true,
+ "dev": true,
+ "optional": true,
+ "requires": {
+ "delegates": "^1.0.0",
+ "readable-stream": "^2.0.6"
+ }
+ },
+ "balanced-match": {
+ "version": "1.0.0",
+ "bundled": true,
+ "dev": true,
+ "optional": true
+ },
+ "brace-expansion": {
+ "version": "1.1.11",
+ "bundled": true,
+ "dev": true,
+ "optional": true,
+ "requires": {
+ "balanced-match": "^1.0.0",
+ "concat-map": "0.0.1"
+ }
+ },
+ "chownr": {
+ "version": "1.1.3",
+ "bundled": true,
+ "dev": true,
+ "optional": true
+ },
+ "code-point-at": {
+ "version": "1.1.0",
+ "bundled": true,
+ "dev": true,
+ "optional": true
+ },
+ "concat-map": {
+ "version": "0.0.1",
+ "bundled": true,
+ "dev": true,
+ "optional": true
+ },
+ "console-control-strings": {
+ "version": "1.1.0",
+ "bundled": true,
+ "dev": true,
+ "optional": true
+ },
+ "core-util-is": {
+ "version": "1.0.2",
+ "bundled": true,
+ "dev": true,
+ "optional": true
+ },
+ "debug": {
+ "version": "3.2.6",
+ "bundled": true,
+ "dev": true,
+ "optional": true,
+ "requires": {
+ "ms": "^2.1.1"
+ }
+ },
+ "deep-extend": {
+ "version": "0.6.0",
+ "bundled": true,
+ "dev": true,
+ "optional": true
+ },
+ "delegates": {
+ "version": "1.0.0",
+ "bundled": true,
+ "dev": true,
+ "optional": true
+ },
+ "detect-libc": {
+ "version": "1.0.3",
+ "bundled": true,
+ "dev": true,
+ "optional": true
+ },
+ "fs-minipass": {
+ "version": "1.2.7",
+ "bundled": true,
+ "dev": true,
+ "optional": true,
+ "requires": {
+ "minipass": "^2.6.0"
+ }
+ },
+ "fs.realpath": {
+ "version": "1.0.0",
+ "bundled": true,
+ "dev": true,
+ "optional": true
+ },
+ "gauge": {
+ "version": "2.7.4",
+ "bundled": true,
+ "dev": true,
+ "optional": true,
+ "requires": {
+ "aproba": "^1.0.3",
+ "console-control-strings": "^1.0.0",
+ "has-unicode": "^2.0.0",
+ "object-assign": "^4.1.0",
+ "signal-exit": "^3.0.0",
+ "string-width": "^1.0.1",
+ "strip-ansi": "^3.0.1",
+ "wide-align": "^1.1.0"
+ }
+ },
+ "glob": {
+ "version": "7.1.6",
+ "bundled": true,
+ "dev": true,
+ "optional": true,
+ "requires": {
+ "fs.realpath": "^1.0.0",
+ "inflight": "^1.0.4",
+ "inherits": "2",
+ "minimatch": "^3.0.4",
+ "once": "^1.3.0",
+ "path-is-absolute": "^1.0.0"
+ }
+ },
+ "has-unicode": {
+ "version": "2.0.1",
+ "bundled": true,
+ "dev": true,
+ "optional": true
+ },
+ "iconv-lite": {
+ "version": "0.4.24",
+ "bundled": true,
+ "dev": true,
+ "optional": true,
+ "requires": {
+ "safer-buffer": ">= 2.1.2 < 3"
+ }
+ },
+ "ignore-walk": {
+ "version": "3.0.3",
+ "bundled": true,
+ "dev": true,
+ "optional": true,
+ "requires": {
+ "minimatch": "^3.0.4"
+ }
+ },
+ "inflight": {
+ "version": "1.0.6",
+ "bundled": true,
+ "dev": true,
+ "optional": true,
+ "requires": {
+ "once": "^1.3.0",
+ "wrappy": "1"
+ }
+ },
+ "inherits": {
+ "version": "2.0.4",
+ "bundled": true,
+ "dev": true,
+ "optional": true
+ },
+ "ini": {
+ "version": "1.3.5",
+ "bundled": true,
+ "dev": true,
+ "optional": true
+ },
+ "is-fullwidth-code-point": {
+ "version": "1.0.0",
+ "bundled": true,
+ "dev": true,
+ "optional": true,
+ "requires": {
+ "number-is-nan": "^1.0.0"
+ }
+ },
+ "isarray": {
+ "version": "1.0.0",
+ "bundled": true,
+ "dev": true,
+ "optional": true
+ },
+ "minimatch": {
+ "version": "3.0.4",
+ "bundled": true,
+ "dev": true,
+ "optional": true,
+ "requires": {
+ "brace-expansion": "^1.1.7"
+ }
+ },
+ "minimist": {
+ "version": "0.0.8",
+ "bundled": true,
+ "dev": true,
+ "optional": true
+ },
+ "minipass": {
+ "version": "2.9.0",
+ "bundled": true,
+ "dev": true,
+ "optional": true,
+ "requires": {
+ "safe-buffer": "^5.1.2",
+ "yallist": "^3.0.0"
+ }
+ },
+ "minizlib": {
+ "version": "1.3.3",
+ "bundled": true,
+ "dev": true,
+ "optional": true,
+ "requires": {
+ "minipass": "^2.9.0"
+ }
+ },
+ "mkdirp": {
+ "version": "0.5.1",
+ "bundled": true,
+ "dev": true,
+ "optional": true,
+ "requires": {
+ "minimist": "0.0.8"
+ }
+ },
+ "ms": {
+ "version": "2.1.2",
+ "bundled": true,
+ "dev": true,
+ "optional": true
+ },
+ "needle": {
+ "version": "2.4.0",
+ "bundled": true,
+ "dev": true,
+ "optional": true,
+ "requires": {
+ "debug": "^3.2.6",
+ "iconv-lite": "^0.4.4",
+ "sax": "^1.2.4"
+ }
+ },
+ "node-pre-gyp": {
+ "version": "0.14.0",
+ "bundled": true,
+ "dev": true,
+ "optional": true,
+ "requires": {
+ "detect-libc": "^1.0.2",
+ "mkdirp": "^0.5.1",
+ "needle": "^2.2.1",
+ "nopt": "^4.0.1",
+ "npm-packlist": "^1.1.6",
+ "npmlog": "^4.0.2",
+ "rc": "^1.2.7",
+ "rimraf": "^2.6.1",
+ "semver": "^5.3.0",
+ "tar": "^4.4.2"
+ }
+ },
+ "nopt": {
+ "version": "4.0.1",
+ "bundled": true,
+ "dev": true,
+ "optional": true,
+ "requires": {
+ "abbrev": "1",
+ "osenv": "^0.1.4"
+ }
+ },
+ "npm-bundled": {
+ "version": "1.1.1",
+ "bundled": true,
+ "dev": true,
+ "optional": true,
+ "requires": {
+ "npm-normalize-package-bin": "^1.0.1"
+ }
+ },
+ "npm-normalize-package-bin": {
+ "version": "1.0.1",
+ "bundled": true,
+ "dev": true,
+ "optional": true
+ },
+ "npm-packlist": {
+ "version": "1.4.7",
+ "bundled": true,
+ "dev": true,
+ "optional": true,
+ "requires": {
+ "ignore-walk": "^3.0.1",
+ "npm-bundled": "^1.0.1"
+ }
+ },
+ "npmlog": {
+ "version": "4.1.2",
+ "bundled": true,
+ "dev": true,
+ "optional": true,
+ "requires": {
+ "are-we-there-yet": "~1.1.2",
+ "console-control-strings": "~1.1.0",
+ "gauge": "~2.7.3",
+ "set-blocking": "~2.0.0"
+ }
+ },
+ "number-is-nan": {
+ "version": "1.0.1",
+ "bundled": true,
+ "dev": true,
+ "optional": true
+ },
+ "object-assign": {
+ "version": "4.1.1",
+ "bundled": true,
+ "dev": true,
+ "optional": true
+ },
+ "once": {
+ "version": "1.4.0",
+ "bundled": true,
+ "dev": true,
+ "optional": true,
+ "requires": {
+ "wrappy": "1"
+ }
+ },
+ "os-homedir": {
+ "version": "1.0.2",
+ "bundled": true,
+ "dev": true,
+ "optional": true
+ },
+ "os-tmpdir": {
+ "version": "1.0.2",
+ "bundled": true,
+ "dev": true,
+ "optional": true
+ },
+ "osenv": {
+ "version": "0.1.5",
+ "bundled": true,
+ "dev": true,
+ "optional": true,
+ "requires": {
+ "os-homedir": "^1.0.0",
+ "os-tmpdir": "^1.0.0"
+ }
+ },
+ "path-is-absolute": {
+ "version": "1.0.1",
+ "bundled": true,
+ "dev": true,
+ "optional": true
+ },
+ "process-nextick-args": {
+ "version": "2.0.1",
+ "bundled": true,
+ "dev": true,
+ "optional": true
+ },
+ "rc": {
+ "version": "1.2.8",
+ "bundled": true,
+ "dev": true,
+ "optional": true,
+ "requires": {
+ "deep-extend": "^0.6.0",
+ "ini": "~1.3.0",
+ "minimist": "^1.2.0",
+ "strip-json-comments": "~2.0.1"
+ },
+ "dependencies": {
+ "minimist": {
+ "version": "1.2.0",
+ "bundled": true,
+ "dev": true,
+ "optional": true
+ }
+ }
+ },
+ "readable-stream": {
+ "version": "2.3.6",
+ "bundled": true,
+ "dev": true,
+ "optional": true,
+ "requires": {
+ "core-util-is": "~1.0.0",
+ "inherits": "~2.0.3",
+ "isarray": "~1.0.0",
+ "process-nextick-args": "~2.0.0",
+ "safe-buffer": "~5.1.1",
+ "string_decoder": "~1.1.1",
+ "util-deprecate": "~1.0.1"
+ }
+ },
+ "rimraf": {
+ "version": "2.7.1",
+ "bundled": true,
+ "dev": true,
+ "optional": true,
+ "requires": {
+ "glob": "^7.1.3"
+ }
+ },
+ "safe-buffer": {
+ "version": "5.1.2",
+ "bundled": true,
+ "dev": true,
+ "optional": true
+ },
+ "safer-buffer": {
+ "version": "2.1.2",
+ "bundled": true,
+ "dev": true,
+ "optional": true
+ },
+ "sax": {
+ "version": "1.2.4",
+ "bundled": true,
+ "dev": true,
+ "optional": true
+ },
+ "semver": {
+ "version": "5.7.1",
+ "bundled": true,
+ "dev": true,
+ "optional": true
+ },
+ "set-blocking": {
+ "version": "2.0.0",
+ "bundled": true,
+ "dev": true,
+ "optional": true
+ },
+ "signal-exit": {
+ "version": "3.0.2",
+ "bundled": true,
+ "dev": true,
+ "optional": true
+ },
+ "string-width": {
+ "version": "1.0.2",
+ "bundled": true,
+ "dev": true,
+ "optional": true,
+ "requires": {
+ "code-point-at": "^1.0.0",
+ "is-fullwidth-code-point": "^1.0.0",
+ "strip-ansi": "^3.0.0"
+ }
+ },
+ "string_decoder": {
+ "version": "1.1.1",
+ "bundled": true,
+ "dev": true,
+ "optional": true,
+ "requires": {
+ "safe-buffer": "~5.1.0"
+ }
+ },
+ "strip-ansi": {
+ "version": "3.0.1",
+ "bundled": true,
+ "dev": true,
+ "optional": true,
+ "requires": {
+ "ansi-regex": "^2.0.0"
+ }
+ },
+ "strip-json-comments": {
+ "version": "2.0.1",
+ "bundled": true,
+ "dev": true,
+ "optional": true
+ },
+ "tar": {
+ "version": "4.4.13",
+ "bundled": true,
+ "dev": true,
+ "optional": true,
+ "requires": {
+ "chownr": "^1.1.1",
+ "fs-minipass": "^1.2.5",
+ "minipass": "^2.8.6",
+ "minizlib": "^1.2.1",
+ "mkdirp": "^0.5.0",
+ "safe-buffer": "^5.1.2",
+ "yallist": "^3.0.3"
+ }
+ },
+ "util-deprecate": {
+ "version": "1.0.2",
+ "bundled": true,
+ "dev": true,
+ "optional": true
+ },
+ "wide-align": {
+ "version": "1.1.3",
+ "bundled": true,
+ "dev": true,
+ "optional": true,
+ "requires": {
+ "string-width": "^1.0.2 || 2"
+ }
+ },
+ "wrappy": {
+ "version": "1.0.2",
+ "bundled": true,
+ "dev": true,
+ "optional": true
+ },
+ "yallist": {
+ "version": "3.1.1",
+ "bundled": true,
+ "dev": true,
+ "optional": true
+ }
+ }
+ },
+ "fstream": {
+ "version": "1.0.12",
+ "resolved": "https://registry.npmjs.org/fstream/-/fstream-1.0.12.tgz",
+ "integrity": "sha512-WvJ193OHa0GHPEL+AycEJgxvBEwyfRkN1vhjca23OaPVMCaLCXTd5qAu82AjTcgP1UJmytkOKb63Ypde7raDIg==",
+ "dev": true,
+ "requires": {
+ "graceful-fs": "^4.1.2",
+ "inherits": "~2.0.0",
+ "mkdirp": ">=0.5 0",
+ "rimraf": "2"
+ },
+ "dependencies": {
+ "rimraf": {
+ "version": "2.7.1",
+ "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz",
+ "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==",
+ "dev": true,
+ "requires": {
+ "glob": "^7.1.3"
+ }
+ }
+ }
+ },
+ "function-bind": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz",
+ "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==",
+ "dev": true
+ },
+ "function.prototype.name": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/function.prototype.name/-/function.prototype.name-1.1.2.tgz",
+ "integrity": "sha512-C8A+LlHBJjB2AdcRPorc5JvJ5VUoWlXdEHLOJdCI7kjHEtGTpHQUiqMvCIKUwIsGwZX2jZJy761AXsn356bJQg==",
+ "dev": true,
+ "requires": {
+ "define-properties": "^1.1.3",
+ "es-abstract": "^1.17.0-next.1",
+ "functions-have-names": "^1.2.0"
+ }
+ },
+ "functions-have-names": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/functions-have-names/-/functions-have-names-1.2.1.tgz",
+ "integrity": "sha512-j48B/ZI7VKs3sgeI2cZp7WXWmZXu7Iq5pl5/vptV5N2mq+DGFuS/ulaDjtaoLpYzuD6u8UgrUKHfgo7fDTSiBA==",
+ "dev": true
+ },
+ "gauge": {
+ "version": "2.7.4",
+ "resolved": "https://registry.npmjs.org/gauge/-/gauge-2.7.4.tgz",
+ "integrity": "sha1-LANAXHU4w51+s3sxcCLjJfsBi/c=",
+ "dev": true,
+ "requires": {
+ "aproba": "^1.0.3",
+ "console-control-strings": "^1.0.0",
+ "has-unicode": "^2.0.0",
+ "object-assign": "^4.1.0",
+ "signal-exit": "^3.0.0",
+ "string-width": "^1.0.1",
+ "strip-ansi": "^3.0.1",
+ "wide-align": "^1.1.0"
+ },
+ "dependencies": {
+ "is-fullwidth-code-point": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz",
+ "integrity": "sha1-754xOG8DGn8NZDr4L95QxFfvAMs=",
+ "dev": true,
+ "requires": {
+ "number-is-nan": "^1.0.0"
+ }
+ },
+ "string-width": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-1.0.2.tgz",
+ "integrity": "sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=",
+ "dev": true,
+ "requires": {
+ "code-point-at": "^1.0.0",
+ "is-fullwidth-code-point": "^1.0.0",
+ "strip-ansi": "^3.0.0"
+ }
+ }
+ }
+ },
+ "gaze": {
+ "version": "1.1.3",
+ "resolved": "https://registry.npmjs.org/gaze/-/gaze-1.1.3.tgz",
+ "integrity": "sha512-BRdNm8hbWzFzWHERTrejLqwHDfS4GibPoq5wjTPIoJHoBtKGPg3xAFfxmM+9ztbXelxcf2hwQcaz1PtmFeue8g==",
+ "dev": true,
+ "requires": {
+ "globule": "^1.0.0"
+ }
+ },
+ "generate-function": {
+ "version": "2.3.1",
+ "resolved": "https://registry.npmjs.org/generate-function/-/generate-function-2.3.1.tgz",
+ "integrity": "sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==",
+ "dev": true,
+ "requires": {
+ "is-property": "^1.0.2"
+ }
+ },
+ "generate-object-property": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/generate-object-property/-/generate-object-property-1.2.0.tgz",
+ "integrity": "sha1-nA4cQDCM6AT0eDYYuTf6iPmdUNA=",
+ "dev": true,
+ "requires": {
+ "is-property": "^1.0.0"
+ }
+ },
+ "gensync": {
+ "version": "1.0.0-beta.1",
+ "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.1.tgz",
+ "integrity": "sha512-r8EC6NO1sngH/zdD9fiRDLdcgnbayXah+mLgManTaIZJqEC1MZstmnox8KpnI2/fxQwrp5OpCOYWLp4rBl4Jcg==",
+ "dev": true
+ },
+ "get-caller-file": {
+ "version": "2.0.5",
+ "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",
+ "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==",
+ "dev": true
+ },
+ "get-func-name": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/get-func-name/-/get-func-name-2.0.0.tgz",
+ "integrity": "sha1-6td0q+5y4gQJQzoGY2YCPdaIekE=",
+ "dev": true
+ },
+ "get-stdin": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/get-stdin/-/get-stdin-4.0.1.tgz",
+ "integrity": "sha1-uWjGsKBDhDJJAui/Gl3zJXmkUP4=",
+ "dev": true
+ },
+ "get-stream": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-4.1.0.tgz",
+ "integrity": "sha512-GMat4EJ5161kIy2HevLlr4luNjBgvmj413KaQA7jt4V8B4RDsfpHk7WQ9GVqfYyyx8OS/L66Kox+rJRNklLK7w==",
+ "dev": true,
+ "requires": {
+ "pump": "^3.0.0"
+ }
+ },
+ "get-value": {
+ "version": "2.0.6",
+ "resolved": "https://registry.npmjs.org/get-value/-/get-value-2.0.6.tgz",
+ "integrity": "sha1-3BXKHGcjh8p2vTesCjlbogQqLCg=",
+ "dev": true
+ },
+ "getpass": {
+ "version": "0.1.7",
+ "resolved": "https://registry.npmjs.org/getpass/-/getpass-0.1.7.tgz",
+ "integrity": "sha1-Xv+OPmhNVprkyysSgmBOi6YhSfo=",
+ "dev": true,
+ "requires": {
+ "assert-plus": "^1.0.0"
+ }
+ },
+ "glob": {
+ "version": "7.1.6",
+ "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.6.tgz",
+ "integrity": "sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA==",
+ "dev": true,
+ "requires": {
+ "fs.realpath": "^1.0.0",
+ "inflight": "^1.0.4",
+ "inherits": "2",
+ "minimatch": "^3.0.4",
+ "once": "^1.3.0",
+ "path-is-absolute": "^1.0.0"
+ }
+ },
+ "glob-base": {
+ "version": "0.3.0",
+ "resolved": "https://registry.npmjs.org/glob-base/-/glob-base-0.3.0.tgz",
+ "integrity": "sha1-27Fk9iIbHAscz4Kuoyi0l98Oo8Q=",
+ "dev": true,
+ "requires": {
+ "glob-parent": "^2.0.0",
+ "is-glob": "^2.0.0"
+ }
+ },
+ "glob-parent": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-2.0.0.tgz",
+ "integrity": "sha1-gTg9ctsFT8zPUzbaqQLxgvbtuyg=",
+ "dev": true,
+ "requires": {
+ "is-glob": "^2.0.0"
+ }
+ },
+ "glob2base": {
+ "version": "0.0.12",
+ "resolved": "https://registry.npmjs.org/glob2base/-/glob2base-0.0.12.tgz",
+ "integrity": "sha1-nUGbPijxLoOjYhZKJ3BVkiycDVY=",
+ "dev": true,
+ "requires": {
+ "find-index": "^0.1.1"
+ }
+ },
+ "global-modules": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/global-modules/-/global-modules-2.0.0.tgz",
+ "integrity": "sha512-NGbfmJBp9x8IxyJSd1P+otYK8vonoJactOogrVfFRIAEY1ukil8RSKDz2Yo7wh1oihl51l/r6W4epkeKJHqL8A==",
+ "dev": true,
+ "requires": {
+ "global-prefix": "^3.0.0"
+ },
+ "dependencies": {
+ "global-prefix": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/global-prefix/-/global-prefix-3.0.0.tgz",
+ "integrity": "sha512-awConJSVCHVGND6x3tmMaKcQvwXLhjdkmomy2W+Goaui8YPgYgXJZewhg3fWC+DlfqqQuWg8AwqjGTD2nAPVWg==",
+ "dev": true,
+ "requires": {
+ "ini": "^1.3.5",
+ "kind-of": "^6.0.2",
+ "which": "^1.3.1"
+ }
+ },
+ "kind-of": {
+ "version": "6.0.3",
+ "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz",
+ "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==",
+ "dev": true
+ }
+ }
+ },
+ "global-prefix": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/global-prefix/-/global-prefix-1.0.2.tgz",
+ "integrity": "sha1-2/dDxsFJklk8ZVVoy2btMsASLr4=",
+ "dev": true,
+ "requires": {
+ "expand-tilde": "^2.0.2",
+ "homedir-polyfill": "^1.0.1",
+ "ini": "^1.3.4",
+ "is-windows": "^1.0.1",
+ "which": "^1.2.14"
+ }
+ },
+ "globals": {
+ "version": "11.12.0",
+ "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz",
+ "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==",
+ "dev": true
+ },
+ "globule": {
+ "version": "1.3.1",
+ "resolved": "https://registry.npmjs.org/globule/-/globule-1.3.1.tgz",
+ "integrity": "sha512-OVyWOHgw29yosRHCHo7NncwR1hW5ew0W/UrvtwvjefVJeQ26q4/8r8FmPsSF1hJ93IgWkyv16pCTz6WblMzm/g==",
+ "dev": true,
+ "requires": {
+ "glob": "~7.1.1",
+ "lodash": "~4.17.12",
+ "minimatch": "~3.0.2"
+ }
+ },
+ "gonzales-pe-sl": {
+ "version": "4.2.3",
+ "resolved": "https://registry.npmjs.org/gonzales-pe-sl/-/gonzales-pe-sl-4.2.3.tgz",
+ "integrity": "sha1-aoaLw4BkXxQf7rBCxvl/zHG1n+Y=",
+ "dev": true,
+ "requires": {
+ "minimist": "1.1.x"
+ },
+ "dependencies": {
+ "minimist": {
+ "version": "1.1.3",
+ "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.1.3.tgz",
+ "integrity": "sha1-O+39kaktOQFvz6ocaB6Pqhoe/ag=",
+ "dev": true
+ }
+ }
+ },
+ "graceful-fs": {
+ "version": "4.2.3",
+ "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.3.tgz",
+ "integrity": "sha512-a30VEBm4PEdx1dRB7MFK7BejejvCvBronbLjht+sHuGYj8PHs7M/5Z+rt5lw551vZ7yfTCj4Vuyy3mSJytDWRQ==",
+ "dev": true
+ },
+ "growl": {
+ "version": "1.10.5",
+ "resolved": "https://registry.npmjs.org/growl/-/growl-1.10.5.tgz",
+ "integrity": "sha512-qBr4OuELkhPenW6goKVXiv47US3clb3/IbuWF9KNKEijAy9oeHxU9IgzjvJhHkUzhaj7rOUD7+YGWqUjLp5oSA==",
+ "dev": true
+ },
+ "har-schema": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/har-schema/-/har-schema-2.0.0.tgz",
+ "integrity": "sha1-qUwiJOvKwEeCoNkDVSHyRzW37JI=",
+ "dev": true
+ },
+ "har-validator": {
+ "version": "5.1.3",
+ "resolved": "https://registry.npmjs.org/har-validator/-/har-validator-5.1.3.tgz",
+ "integrity": "sha512-sNvOCzEQNr/qrvJgc3UG/kD4QtlHycrzwS+6mfTrrSq97BvaYcPZZI1ZSqGSPR73Cxn4LKTD4PttRwfU7jWq5g==",
+ "dev": true,
+ "requires": {
+ "ajv": "^6.5.5",
+ "har-schema": "^2.0.0"
+ },
+ "dependencies": {
+ "ajv": {
+ "version": "6.11.0",
+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.11.0.tgz",
+ "integrity": "sha512-nCprB/0syFYy9fVYU1ox1l2KN8S9I+tziH8D4zdZuLT3N6RMlGSGt5FSTpAiHB/Whv8Qs1cWHma1aMKZyaHRKA==",
+ "dev": true,
+ "requires": {
+ "fast-deep-equal": "^3.1.1",
+ "fast-json-stable-stringify": "^2.0.0",
+ "json-schema-traverse": "^0.4.1",
+ "uri-js": "^4.2.2"
+ }
+ },
+ "fast-deep-equal": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.1.tgz",
+ "integrity": "sha512-8UEa58QDLauDNfpbrX55Q9jrGHThw2ZMdOky5Gl1CDtVeJDPVrG4Jxx1N8jw2gkWaff5UUuX1KJd+9zGe2B+ZA==",
+ "dev": true
+ },
+ "json-schema-traverse": {
+ "version": "0.4.1",
+ "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz",
+ "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==",
+ "dev": true
+ }
+ }
+ },
+ "has": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz",
+ "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==",
+ "dev": true,
+ "requires": {
+ "function-bind": "^1.1.1"
+ }
+ },
+ "has-ansi": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz",
+ "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=",
+ "dev": true,
+ "requires": {
+ "ansi-regex": "^2.0.0"
+ }
+ },
+ "has-binary2": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/has-binary2/-/has-binary2-1.0.3.tgz",
+ "integrity": "sha512-G1LWKhDSvhGeAQ8mPVQlqNcOB2sJdwATtZKl2pDKKHfpf/rYj24lkinxf69blJbnsvtqqNU+L3SL50vzZhXOnw==",
+ "dev": true,
+ "requires": {
+ "isarray": "2.0.1"
+ },
+ "dependencies": {
+ "isarray": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.1.tgz",
+ "integrity": "sha1-o32U7ZzaLVmGXJ92/llu4fM4dB4=",
+ "dev": true
+ }
+ }
+ },
+ "has-cors": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/has-cors/-/has-cors-1.1.0.tgz",
+ "integrity": "sha1-XkdHk/fqmEPRu5nCPu9J/xJv/zk=",
+ "dev": true
+ },
+ "has-flag": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz",
+ "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=",
+ "dev": true
+ },
+ "has-symbols": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.1.tgz",
+ "integrity": "sha512-PLcsoqu++dmEIZB+6totNFKq/7Do+Z0u4oT0zKOJNl3lYK6vGwwu2hjHs+68OEZbTjiUE9bgOABXbP/GvrS0Kg==",
+ "dev": true
+ },
+ "has-unicode": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/has-unicode/-/has-unicode-2.0.1.tgz",
+ "integrity": "sha1-4Ob+aijPUROIVeCG0Wkedx3iqLk=",
+ "dev": true
+ },
+ "has-value": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/has-value/-/has-value-1.0.0.tgz",
+ "integrity": "sha1-GLKB2lhbHFxR3vJMkw7SmgvmsXc=",
+ "dev": true,
+ "requires": {
+ "get-value": "^2.0.6",
+ "has-values": "^1.0.0",
+ "isobject": "^3.0.0"
+ },
+ "dependencies": {
+ "isobject": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz",
+ "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=",
+ "dev": true
+ }
+ }
+ },
+ "has-values": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/has-values/-/has-values-1.0.0.tgz",
+ "integrity": "sha1-lbC2P+whRmGab+V/51Yo1aOe/k8=",
+ "dev": true,
+ "requires": {
+ "is-number": "^3.0.0",
+ "kind-of": "^4.0.0"
+ },
+ "dependencies": {
+ "is-number": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/is-number/-/is-number-3.0.0.tgz",
+ "integrity": "sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=",
+ "dev": true,
+ "requires": {
+ "kind-of": "^3.0.2"
+ },
+ "dependencies": {
+ "kind-of": {
+ "version": "3.2.2",
+ "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz",
+ "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=",
+ "dev": true,
+ "requires": {
+ "is-buffer": "^1.1.5"
+ }
+ }
+ }
+ },
+ "kind-of": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-4.0.0.tgz",
+ "integrity": "sha1-IIE989cSkosgc3hpGkUGb65y3Vc=",
+ "dev": true,
+ "requires": {
+ "is-buffer": "^1.1.5"
+ }
+ }
+ }
+ },
+ "hash-base": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/hash-base/-/hash-base-3.0.4.tgz",
+ "integrity": "sha1-X8hoaEfs1zSZQDMZprCj8/auSRg=",
+ "dev": true,
+ "requires": {
+ "inherits": "^2.0.1",
+ "safe-buffer": "^5.0.1"
+ }
+ },
+ "hash.js": {
+ "version": "1.1.7",
+ "resolved": "https://registry.npmjs.org/hash.js/-/hash.js-1.1.7.tgz",
+ "integrity": "sha512-taOaskGt4z4SOANNseOviYDvjEJinIkRgmp7LbKP2YTTmVxWBl87s/uzK9r+44BclBSp2X7K1hqeNfz9JbBeXA==",
+ "dev": true,
+ "requires": {
+ "inherits": "^2.0.3",
+ "minimalistic-assert": "^1.0.1"
+ }
+ },
+ "he": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz",
+ "integrity": "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==",
+ "dev": true
+ },
+ "hmac-drbg": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/hmac-drbg/-/hmac-drbg-1.0.1.tgz",
+ "integrity": "sha1-0nRXAQJabHdabFRXk+1QL8DGSaE=",
+ "dev": true,
+ "requires": {
+ "hash.js": "^1.0.3",
+ "minimalistic-assert": "^1.0.0",
+ "minimalistic-crypto-utils": "^1.0.1"
+ }
+ },
+ "hoist-non-react-statics": {
+ "version": "3.3.2",
+ "resolved": "https://registry.npmjs.org/hoist-non-react-statics/-/hoist-non-react-statics-3.3.2.tgz",
+ "integrity": "sha512-/gGivxi8JPKWNm/W0jSmzcMPpfpPLc3dY/6GxhX2hQ9iGj3aDfklV4ET7NjKpSinLpJ5vafa9iiGIEZg10SfBw==",
+ "requires": {
+ "react-is": "^16.7.0"
+ }
+ },
+ "homedir-polyfill": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/homedir-polyfill/-/homedir-polyfill-1.0.3.tgz",
+ "integrity": "sha512-eSmmWE5bZTK2Nou4g0AI3zZ9rswp7GRKoKXS1BLUkvPviOqs4YTN1djQIqrXy9k5gEtdLPy86JjRwsNM9tnDcA==",
+ "dev": true,
+ "requires": {
+ "parse-passwd": "^1.0.0"
+ }
+ },
+ "hosted-git-info": {
+ "version": "2.8.5",
+ "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-2.8.5.tgz",
+ "integrity": "sha512-kssjab8CvdXfcXMXVcvsXum4Hwdq9XGtRD3TteMEvEbq0LXyiNQr6AprqKqfeaDXze7SxWvRxdpwE6ku7ikLkg==",
+ "dev": true
+ },
+ "html-element-map": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/html-element-map/-/html-element-map-1.2.0.tgz",
+ "integrity": "sha512-0uXq8HsuG1v2TmQ8QkIhzbrqeskE4kn52Q18QJ9iAA/SnHoEKXWiUxHQtclRsCFWEUD2So34X+0+pZZu862nnw==",
+ "dev": true,
+ "requires": {
+ "array-filter": "^1.0.0"
+ }
+ },
+ "html-escaper": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.0.tgz",
+ "integrity": "sha512-a4u9BeERWGu/S8JiWEAQcdrg9v4QArtP9keViQjGMdff20fBdd8waotXaNmODqBe6uZ3Nafi7K/ho4gCQHV3Ig==",
+ "dev": true
+ },
+ "htmlparser2": {
+ "version": "3.10.1",
+ "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-3.10.1.tgz",
+ "integrity": "sha512-IgieNijUMbkDovyoKObU1DUhm1iwNYE/fuifEoEHfd1oZKZDaONBSkal7Y01shxsM49R4XaMdGez3WnF9UfiCQ==",
+ "dev": true,
+ "requires": {
+ "domelementtype": "^1.3.1",
+ "domhandler": "^2.3.0",
+ "domutils": "^1.5.1",
+ "entities": "^1.1.1",
+ "inherits": "^2.0.1",
+ "readable-stream": "^3.1.1"
+ },
+ "dependencies": {
+ "readable-stream": {
+ "version": "3.6.0",
+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.0.tgz",
+ "integrity": "sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA==",
+ "dev": true,
+ "requires": {
+ "inherits": "^2.0.3",
+ "string_decoder": "^1.1.1",
+ "util-deprecate": "^1.0.1"
+ }
+ }
+ }
+ },
+ "http-errors": {
+ "version": "1.7.2",
+ "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.7.2.tgz",
+ "integrity": "sha512-uUQBt3H/cSIVfch6i1EuPNy/YsRSOUBXTVfZ+yR7Zjez3qjBz6i9+i4zjNaoqcoFVI4lQJ5plg63TvGfRSDCRg==",
+ "dev": true,
+ "requires": {
+ "depd": "~1.1.2",
+ "inherits": "2.0.3",
+ "setprototypeof": "1.1.1",
+ "statuses": ">= 1.5.0 < 2",
+ "toidentifier": "1.0.0"
+ },
+ "dependencies": {
+ "inherits": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz",
+ "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=",
+ "dev": true
+ }
+ }
+ },
+ "http-proxy": {
+ "version": "1.18.0",
+ "resolved": "https://registry.npmjs.org/http-proxy/-/http-proxy-1.18.0.tgz",
+ "integrity": "sha512-84I2iJM/n1d4Hdgc6y2+qY5mDaz2PUVjlg9znE9byl+q0uC3DeByqBGReQu5tpLK0TAqTIXScRUV+dg7+bUPpQ==",
+ "dev": true,
+ "requires": {
+ "eventemitter3": "^4.0.0",
+ "follow-redirects": "^1.0.0",
+ "requires-port": "^1.0.0"
+ }
+ },
+ "http-signature": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.2.0.tgz",
+ "integrity": "sha1-muzZJRFHcvPZW2WmCruPfBj7rOE=",
+ "dev": true,
+ "requires": {
+ "assert-plus": "^1.0.0",
+ "jsprim": "^1.2.2",
+ "sshpk": "^1.7.0"
+ }
+ },
+ "https-browserify": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/https-browserify/-/https-browserify-1.0.0.tgz",
+ "integrity": "sha1-7AbBDgo0wPL68Zn3/X/Hj//QPHM=",
+ "dev": true
+ },
+ "iconv-lite": {
+ "version": "0.4.24",
+ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz",
+ "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==",
+ "dev": true,
+ "requires": {
+ "safer-buffer": ">= 2.1.2 < 3"
+ }
+ },
+ "ieee754": {
+ "version": "1.1.13",
+ "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.1.13.tgz",
+ "integrity": "sha512-4vf7I2LYV/HaWerSo3XmlMkp5eZ83i+/CDluXi/IGTs/O1sejBNhTtnxzmRZfvOUqj7lZjqHkeTvpgSFDlWZTg==",
+ "dev": true
+ },
+ "iferr": {
+ "version": "0.1.5",
+ "resolved": "https://registry.npmjs.org/iferr/-/iferr-0.1.5.tgz",
+ "integrity": "sha1-xg7taebY/bazEEofy8ocGS3FtQE=",
+ "dev": true
+ },
+ "ignore": {
+ "version": "3.3.10",
+ "resolved": "https://registry.npmjs.org/ignore/-/ignore-3.3.10.tgz",
+ "integrity": "sha512-Pgs951kaMm5GXP7MOvxERINe3gsaVjUWFm+UZPSq9xYriQAksyhg0csnS0KXSNRD5NmNdapXEpjxG49+AKh/ug==",
+ "dev": true
+ },
+ "import-local": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/import-local/-/import-local-2.0.0.tgz",
+ "integrity": "sha512-b6s04m3O+s3CGSbqDIyP4R6aAwAeYlVq9+WUWep6iHa8ETRf9yei1U48C5MmfJmV9AiLYYBKPMq/W+/WRpQmCQ==",
+ "dev": true,
+ "requires": {
+ "pkg-dir": "^3.0.0",
+ "resolve-cwd": "^2.0.0"
+ }
+ },
+ "imurmurhash": {
+ "version": "0.1.4",
+ "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz",
+ "integrity": "sha1-khi5srkoojixPcT7a21XbyMUU+o=",
+ "dev": true
+ },
+ "in-publish": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/in-publish/-/in-publish-2.0.0.tgz",
+ "integrity": "sha1-4g/146KvwmkDILbcVSaCqcf631E=",
+ "dev": true
+ },
+ "indent-string": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-2.1.0.tgz",
+ "integrity": "sha1-ji1INIdCEhtKghi3oTfppSBJ3IA=",
+ "dev": true,
+ "requires": {
+ "repeating": "^2.0.0"
+ }
+ },
+ "indexof": {
+ "version": "0.0.1",
+ "resolved": "https://registry.npmjs.org/indexof/-/indexof-0.0.1.tgz",
+ "integrity": "sha1-gtwzbSMrkGIXnQWrMpOmYFn9Q10=",
+ "dev": true
+ },
+ "infer-owner": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/infer-owner/-/infer-owner-1.0.4.tgz",
+ "integrity": "sha512-IClj+Xz94+d7irH5qRyfJonOdfTzuDaifE6ZPWfx0N0+/ATZCbuTPq2prFl526urkQd90WyUKIh1DfBQ2hMz9A==",
+ "dev": true
+ },
+ "inflight": {
+ "version": "1.0.6",
+ "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",
+ "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=",
+ "dev": true,
+ "requires": {
+ "once": "^1.3.0",
+ "wrappy": "1"
+ }
+ },
+ "inherits": {
+ "version": "2.0.4",
+ "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
+ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
+ "dev": true
+ },
+ "ini": {
+ "version": "1.3.5",
+ "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.5.tgz",
+ "integrity": "sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw==",
+ "dev": true
+ },
+ "inquirer": {
+ "version": "0.12.0",
+ "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-0.12.0.tgz",
+ "integrity": "sha1-HvK/1jUE3wvHV4X/+MLEHfEvB34=",
+ "dev": true,
+ "requires": {
+ "ansi-escapes": "^1.1.0",
+ "ansi-regex": "^2.0.0",
+ "chalk": "^1.0.0",
+ "cli-cursor": "^1.0.1",
+ "cli-width": "^2.0.0",
+ "figures": "^1.3.5",
+ "lodash": "^4.3.0",
+ "readline2": "^1.0.1",
+ "run-async": "^0.1.0",
+ "rx-lite": "^3.1.2",
+ "string-width": "^1.0.1",
+ "strip-ansi": "^3.0.0",
+ "through": "^2.3.6"
+ },
+ "dependencies": {
+ "ansi-styles": {
+ "version": "2.2.1",
+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz",
+ "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=",
+ "dev": true
+ },
+ "chalk": {
+ "version": "1.1.3",
+ "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz",
+ "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=",
+ "dev": true,
+ "requires": {
+ "ansi-styles": "^2.2.1",
+ "escape-string-regexp": "^1.0.2",
+ "has-ansi": "^2.0.0",
+ "strip-ansi": "^3.0.0",
+ "supports-color": "^2.0.0"
+ }
+ },
+ "is-fullwidth-code-point": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz",
+ "integrity": "sha1-754xOG8DGn8NZDr4L95QxFfvAMs=",
+ "dev": true,
+ "requires": {
+ "number-is-nan": "^1.0.0"
+ }
+ },
+ "string-width": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-1.0.2.tgz",
+ "integrity": "sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=",
+ "dev": true,
+ "requires": {
+ "code-point-at": "^1.0.0",
+ "is-fullwidth-code-point": "^1.0.0",
+ "strip-ansi": "^3.0.0"
+ }
+ },
+ "supports-color": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz",
+ "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=",
+ "dev": true
+ }
+ }
+ },
+ "interpret": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/interpret/-/interpret-1.2.0.tgz",
+ "integrity": "sha512-mT34yGKMNceBQUoVn7iCDKDntA7SC6gycMAWzGx1z/CMCTV7b2AAtXlo3nRyHZ1FelRkQbQjprHSYGwzLtkVbw==",
+ "dev": true
+ },
+ "invariant": {
+ "version": "2.2.4",
+ "resolved": "https://registry.npmjs.org/invariant/-/invariant-2.2.4.tgz",
+ "integrity": "sha512-phJfQVBuaJM5raOpJjSfkiD6BpbCE4Ns//LaXl6wGYtUBY83nWS6Rf9tXm2e8VaK60JEjYldbPif/A2B1C2gNA==",
+ "dev": true,
+ "requires": {
+ "loose-envify": "^1.0.0"
+ }
+ },
+ "invert-kv": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/invert-kv/-/invert-kv-1.0.0.tgz",
+ "integrity": "sha1-EEqOSqym09jNFXqO+L+rLXo//bY=",
+ "dev": true
+ },
+ "is-accessor-descriptor": {
+ "version": "0.1.6",
+ "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz",
+ "integrity": "sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=",
+ "dev": true,
+ "requires": {
+ "kind-of": "^3.0.2"
+ }
+ },
+ "is-arrayish": {
+ "version": "0.2.1",
+ "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz",
+ "integrity": "sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0=",
+ "dev": true
+ },
+ "is-binary-path": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-1.0.1.tgz",
+ "integrity": "sha1-dfFmQrSA8YenEcgUFh/TpKdlWJg=",
+ "dev": true,
+ "requires": {
+ "binary-extensions": "^1.0.0"
+ }
+ },
+ "is-boolean-object": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.0.1.tgz",
+ "integrity": "sha512-TqZuVwa/sppcrhUCAYkGBk7w0yxfQQnxq28fjkO53tnK9FQXmdwz2JS5+GjsWQ6RByES1K40nI+yDic5c9/aAQ==",
+ "dev": true
+ },
+ "is-buffer": {
+ "version": "1.1.6",
+ "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz",
+ "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==",
+ "dev": true
+ },
+ "is-callable": {
+ "version": "1.1.5",
+ "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.1.5.tgz",
+ "integrity": "sha512-ESKv5sMCJB2jnHTWZ3O5itG+O128Hsus4K4Qh1h2/cgn2vbgnLSVqfV46AeJA9D5EeeLa9w81KUXMtn34zhX+Q==",
+ "dev": true
+ },
+ "is-data-descriptor": {
+ "version": "0.1.4",
+ "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz",
+ "integrity": "sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=",
+ "dev": true,
+ "requires": {
+ "kind-of": "^3.0.2"
+ }
+ },
+ "is-date-object": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.2.tgz",
+ "integrity": "sha512-USlDT524woQ08aoZFzh3/Z6ch9Y/EWXEHQ/AaRN0SkKq4t2Jw2R2339tSXmwuVoY7LLlBCbOIlx2myP/L5zk0g==",
+ "dev": true
+ },
+ "is-descriptor": {
+ "version": "0.1.6",
+ "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-0.1.6.tgz",
+ "integrity": "sha512-avDYr0SB3DwO9zsMov0gKCESFYqCnE4hq/4z3TdUlukEy5t9C0YRq7HLrsN52NAcqXKaepeCD0n+B0arnVG3Hg==",
+ "dev": true,
+ "requires": {
+ "is-accessor-descriptor": "^0.1.6",
+ "is-data-descriptor": "^0.1.4",
+ "kind-of": "^5.0.0"
+ },
+ "dependencies": {
+ "kind-of": {
+ "version": "5.1.0",
+ "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-5.1.0.tgz",
+ "integrity": "sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw==",
+ "dev": true
+ }
+ }
+ },
+ "is-dotfile": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/is-dotfile/-/is-dotfile-1.0.3.tgz",
+ "integrity": "sha1-pqLzL/0t+wT1yiXs0Pa4PPeYoeE=",
+ "dev": true
+ },
+ "is-equal-shallow": {
+ "version": "0.1.3",
+ "resolved": "https://registry.npmjs.org/is-equal-shallow/-/is-equal-shallow-0.1.3.tgz",
+ "integrity": "sha1-IjgJj8Ih3gvPpdnqxMRdY4qhxTQ=",
+ "dev": true,
+ "requires": {
+ "is-primitive": "^2.0.0"
+ }
+ },
+ "is-extendable": {
+ "version": "0.1.1",
+ "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-0.1.1.tgz",
+ "integrity": "sha1-YrEQ4omkcUGOPsNqYX1HLjAd/Ik=",
+ "dev": true
+ },
+ "is-extglob": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-1.0.0.tgz",
+ "integrity": "sha1-rEaBd8SUNAWgkvyPKXYMb/xiBsA=",
+ "dev": true
+ },
+ "is-finite": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/is-finite/-/is-finite-1.1.0.tgz",
+ "integrity": "sha512-cdyMtqX/BOqqNBBiKlIVkytNHm49MtMlYyn1zxzvJKWmFMlGzm+ry5BBfYyeY9YmNKbRSo/o7OX9w9ale0wg3w==",
+ "dev": true
+ },
+ "is-fullwidth-code-point": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz",
+ "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=",
+ "dev": true
+ },
+ "is-glob": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-2.0.1.tgz",
+ "integrity": "sha1-0Jb5JqPe1WAPP9/ZEZjLCIjC2GM=",
+ "dev": true,
+ "requires": {
+ "is-extglob": "^1.0.0"
+ }
+ },
+ "is-my-ip-valid": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/is-my-ip-valid/-/is-my-ip-valid-1.0.0.tgz",
+ "integrity": "sha512-gmh/eWXROncUzRnIa1Ubrt5b8ep/MGSnfAUI3aRp+sqTCs1tv1Isl8d8F6JmkN3dXKc3ehZMrtiPN9eL03NuaQ==",
+ "dev": true
+ },
+ "is-my-json-valid": {
+ "version": "2.20.0",
+ "resolved": "https://registry.npmjs.org/is-my-json-valid/-/is-my-json-valid-2.20.0.tgz",
+ "integrity": "sha512-XTHBZSIIxNsIsZXg7XB5l8z/OBFosl1Wao4tXLpeC7eKU4Vm/kdop2azkPqULwnfGQjmeDIyey9g7afMMtdWAA==",
+ "dev": true,
+ "requires": {
+ "generate-function": "^2.0.0",
+ "generate-object-property": "^1.1.0",
+ "is-my-ip-valid": "^1.0.0",
+ "jsonpointer": "^4.0.0",
+ "xtend": "^4.0.0"
+ }
+ },
+ "is-number": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/is-number/-/is-number-2.1.0.tgz",
+ "integrity": "sha1-Afy7s5NGOlSPL0ZszhbezknbkI8=",
+ "dev": true,
+ "requires": {
+ "kind-of": "^3.0.2"
+ }
+ },
+ "is-number-object": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/is-number-object/-/is-number-object-1.0.4.tgz",
+ "integrity": "sha512-zohwelOAur+5uXtk8O3GPQ1eAcu4ZX3UwxQhUlfFFMNpUd83gXgjbhJh6HmB6LUNV/ieOLQuDwJO3dWJosUeMw==",
+ "dev": true
+ },
+ "is-plain-object": {
+ "version": "2.0.4",
+ "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-2.0.4.tgz",
+ "integrity": "sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==",
+ "dev": true,
+ "requires": {
+ "isobject": "^3.0.1"
+ },
+ "dependencies": {
+ "isobject": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz",
+ "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=",
+ "dev": true
+ }
+ }
+ },
+ "is-posix-bracket": {
+ "version": "0.1.1",
+ "resolved": "https://registry.npmjs.org/is-posix-bracket/-/is-posix-bracket-0.1.1.tgz",
+ "integrity": "sha1-MzTceXdDaOkvAW5vvAqI9c1ua8Q=",
+ "dev": true
+ },
+ "is-primitive": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/is-primitive/-/is-primitive-2.0.0.tgz",
+ "integrity": "sha1-IHurkWOEmcB7Kt8kCkGochADRXU=",
+ "dev": true
+ },
+ "is-property": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz",
+ "integrity": "sha1-V/4cTkhHTt1lsJkR8msc1Ald2oQ=",
+ "dev": true
+ },
+ "is-regex": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.0.5.tgz",
+ "integrity": "sha512-vlKW17SNq44owv5AQR3Cq0bQPEb8+kF3UKZ2fiZNOWtztYE5i0CzCZxFDwO58qAOWtxdBRVO/V5Qin1wjCqFYQ==",
+ "dev": true,
+ "requires": {
+ "has": "^1.0.3"
+ }
+ },
+ "is-resolvable": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/is-resolvable/-/is-resolvable-1.1.0.tgz",
+ "integrity": "sha512-qgDYXFSR5WvEfuS5dMj6oTMEbrrSaM0CrFk2Yiq/gXnBvD9pMa2jGXxyhGLfvhZpuMZe18CJpFxAt3CRs42NMg==",
+ "dev": true
+ },
+ "is-stream": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-1.1.0.tgz",
+ "integrity": "sha1-EtSj3U5o4Lec6428hBc66A2RykQ=",
+ "dev": true
+ },
+ "is-string": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/is-string/-/is-string-1.0.5.tgz",
+ "integrity": "sha512-buY6VNRjhQMiF1qWDouloZlQbRhDPCebwxSjxMjxgemYT46YMd2NR0/H+fBhEfWX4A/w9TBJ+ol+okqJKFE6vQ==",
+ "dev": true
+ },
+ "is-subset": {
+ "version": "0.1.1",
+ "resolved": "https://registry.npmjs.org/is-subset/-/is-subset-0.1.1.tgz",
+ "integrity": "sha1-ilkRfZMt4d4A8kX83TnOQ/HpOaY=",
+ "dev": true
+ },
+ "is-symbol": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.0.3.tgz",
+ "integrity": "sha512-OwijhaRSgqvhm/0ZdAcXNZt9lYdKFpcRDT5ULUuYXPoT794UNOdU+gpT6Rzo7b4V2HUl/op6GqY894AZwv9faQ==",
+ "dev": true,
+ "requires": {
+ "has-symbols": "^1.0.1"
+ }
+ },
+ "is-typedarray": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz",
+ "integrity": "sha1-5HnICFjfDBsR3dppQPlgEfzaSpo=",
+ "dev": true
+ },
+ "is-utf8": {
+ "version": "0.2.1",
+ "resolved": "https://registry.npmjs.org/is-utf8/-/is-utf8-0.2.1.tgz",
+ "integrity": "sha1-Sw2hRCEE0bM2NA6AeX6GXPOffXI=",
+ "dev": true
+ },
+ "is-windows": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/is-windows/-/is-windows-1.0.2.tgz",
+ "integrity": "sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA==",
+ "dev": true
+ },
+ "is-wsl": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-2.1.1.tgz",
+ "integrity": "sha512-umZHcSrwlDHo2TGMXv0DZ8dIUGunZ2Iv68YZnrmCiBPkZ4aaOhtv7pXJKeki9k3qJ3RJr0cDyitcl5wEH3AYog==",
+ "dev": true
+ },
+ "isarray": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
+ "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=",
+ "dev": true
+ },
+ "isbinaryfile": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/isbinaryfile/-/isbinaryfile-3.0.3.tgz",
+ "integrity": "sha512-8cJBL5tTd2OS0dM4jz07wQd5g0dCCqIhUxPIGtZfa5L6hWlvV5MHTITy/DBAsF+Oe2LS1X3krBUhNwaGUWpWxw==",
+ "dev": true,
+ "requires": {
+ "buffer-alloc": "^1.2.0"
+ }
+ },
+ "isexe": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
+ "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=",
+ "dev": true
+ },
+ "isobject": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/isobject/-/isobject-2.1.0.tgz",
+ "integrity": "sha1-8GVWEJaj8dou9GJy+BXIQNh+DIk=",
+ "dev": true,
+ "requires": {
+ "isarray": "1.0.0"
+ }
+ },
+ "isstream": {
+ "version": "0.1.2",
+ "resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz",
+ "integrity": "sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo=",
+ "dev": true
+ },
+ "istanbul-api": {
+ "version": "2.1.6",
+ "resolved": "https://registry.npmjs.org/istanbul-api/-/istanbul-api-2.1.6.tgz",
+ "integrity": "sha512-x0Eicp6KsShG1k1rMgBAi/1GgY7kFGEBwQpw3PXGEmu+rBcBNhqU8g2DgY9mlepAsLPzrzrbqSgCGANnki4POA==",
+ "dev": true,
+ "requires": {
+ "async": "^2.6.2",
+ "compare-versions": "^3.4.0",
+ "fileset": "^2.0.3",
+ "istanbul-lib-coverage": "^2.0.5",
+ "istanbul-lib-hook": "^2.0.7",
+ "istanbul-lib-instrument": "^3.3.0",
+ "istanbul-lib-report": "^2.0.8",
+ "istanbul-lib-source-maps": "^3.0.6",
+ "istanbul-reports": "^2.2.4",
+ "js-yaml": "^3.13.1",
+ "make-dir": "^2.1.0",
+ "minimatch": "^3.0.4",
+ "once": "^1.4.0"
+ },
+ "dependencies": {
+ "istanbul-lib-coverage": {
+ "version": "2.0.5",
+ "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.5.tgz",
+ "integrity": "sha512-8aXznuEPCJvGnMSRft4udDRDtb1V3pkQkMMI5LI+6HuQz5oQ4J2UFn1H82raA3qJtyOLkkwVqICBQkjnGtn5mA==",
+ "dev": true
+ },
+ "istanbul-lib-instrument": {
+ "version": "3.3.0",
+ "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-3.3.0.tgz",
+ "integrity": "sha512-5nnIN4vo5xQZHdXno/YDXJ0G+I3dAm4XgzfSVTPLQpj/zAV2dV6Juy0yaf10/zrJOJeHoN3fraFe+XRq2bFVZA==",
+ "dev": true,
+ "requires": {
+ "@babel/generator": "^7.4.0",
+ "@babel/parser": "^7.4.3",
+ "@babel/template": "^7.4.0",
+ "@babel/traverse": "^7.4.3",
+ "@babel/types": "^7.4.0",
+ "istanbul-lib-coverage": "^2.0.5",
+ "semver": "^6.0.0"
+ }
+ },
+ "semver": {
+ "version": "6.3.0",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz",
+ "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==",
+ "dev": true
+ }
+ }
+ },
+ "istanbul-instrumenter-loader": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/istanbul-instrumenter-loader/-/istanbul-instrumenter-loader-3.0.1.tgz",
+ "integrity": "sha512-a5SPObZgS0jB/ixaKSMdn6n/gXSrK2S6q/UfRJBT3e6gQmVjwZROTODQsYW5ZNwOu78hG62Y3fWlebaVOL0C+w==",
+ "dev": true,
+ "requires": {
+ "convert-source-map": "^1.5.0",
+ "istanbul-lib-instrument": "^1.7.3",
+ "loader-utils": "^1.1.0",
+ "schema-utils": "^0.3.0"
+ }
+ },
+ "istanbul-lib-coverage": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-1.2.1.tgz",
+ "integrity": "sha512-PzITeunAgyGbtY1ibVIUiV679EFChHjoMNRibEIobvmrCRaIgwLxNucOSimtNWUhEib/oO7QY2imD75JVgCJWQ==",
+ "dev": true
+ },
+ "istanbul-lib-hook": {
+ "version": "2.0.7",
+ "resolved": "https://registry.npmjs.org/istanbul-lib-hook/-/istanbul-lib-hook-2.0.7.tgz",
+ "integrity": "sha512-vrRztU9VRRFDyC+aklfLoeXyNdTfga2EI3udDGn4cZ6fpSXpHLV9X6CHvfoMCPtggg8zvDDmC4b9xfu0z6/llA==",
+ "dev": true,
+ "requires": {
+ "append-transform": "^1.0.0"
+ }
+ },
+ "istanbul-lib-instrument": {
+ "version": "1.10.2",
+ "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-1.10.2.tgz",
+ "integrity": "sha512-aWHxfxDqvh/ZlxR8BBaEPVSWDPUkGD63VjGQn3jcw8jCp7sHEMKcrj4xfJn/ABzdMEHiQNyvDQhqm5o8+SQg7A==",
+ "dev": true,
+ "requires": {
+ "babel-generator": "^6.18.0",
+ "babel-template": "^6.16.0",
+ "babel-traverse": "^6.18.0",
+ "babel-types": "^6.18.0",
+ "babylon": "^6.18.0",
+ "istanbul-lib-coverage": "^1.2.1",
+ "semver": "^5.3.0"
+ }
+ },
+ "istanbul-lib-report": {
+ "version": "2.0.8",
+ "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-2.0.8.tgz",
+ "integrity": "sha512-fHBeG573EIihhAblwgxrSenp0Dby6tJMFR/HvlerBsrCTD5bkUuoNtn3gVh29ZCS824cGGBPn7Sg7cNk+2xUsQ==",
+ "dev": true,
+ "requires": {
+ "istanbul-lib-coverage": "^2.0.5",
+ "make-dir": "^2.1.0",
+ "supports-color": "^6.1.0"
+ },
+ "dependencies": {
+ "istanbul-lib-coverage": {
+ "version": "2.0.5",
+ "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.5.tgz",
+ "integrity": "sha512-8aXznuEPCJvGnMSRft4udDRDtb1V3pkQkMMI5LI+6HuQz5oQ4J2UFn1H82raA3qJtyOLkkwVqICBQkjnGtn5mA==",
+ "dev": true
+ },
+ "supports-color": {
+ "version": "6.1.0",
+ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-6.1.0.tgz",
+ "integrity": "sha512-qe1jfm1Mg7Nq/NSh6XE24gPXROEVsWHxC1LIx//XNlD9iw7YZQGjZNjYN7xGaEG6iKdA8EtNFW6R0gjnVXp+wQ==",
+ "dev": true,
+ "requires": {
+ "has-flag": "^3.0.0"
+ }
+ }
+ }
+ },
+ "istanbul-lib-source-maps": {
+ "version": "3.0.6",
+ "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-3.0.6.tgz",
+ "integrity": "sha512-R47KzMtDJH6X4/YW9XTx+jrLnZnscW4VpNN+1PViSYTejLVPWv7oov+Duf8YQSPyVRUvueQqz1TcsC6mooZTXw==",
+ "dev": true,
+ "requires": {
+ "debug": "^4.1.1",
+ "istanbul-lib-coverage": "^2.0.5",
+ "make-dir": "^2.1.0",
+ "rimraf": "^2.6.3",
+ "source-map": "^0.6.1"
+ },
+ "dependencies": {
+ "istanbul-lib-coverage": {
+ "version": "2.0.5",
+ "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.5.tgz",
+ "integrity": "sha512-8aXznuEPCJvGnMSRft4udDRDtb1V3pkQkMMI5LI+6HuQz5oQ4J2UFn1H82raA3qJtyOLkkwVqICBQkjnGtn5mA==",
+ "dev": true
+ },
+ "rimraf": {
+ "version": "2.7.1",
+ "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz",
+ "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==",
+ "dev": true,
+ "requires": {
+ "glob": "^7.1.3"
+ }
+ },
+ "source-map": {
+ "version": "0.6.1",
+ "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
+ "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",
+ "dev": true
+ }
+ }
+ },
+ "istanbul-reports": {
+ "version": "2.2.7",
+ "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-2.2.7.tgz",
+ "integrity": "sha512-uu1F/L1o5Y6LzPVSVZXNOoD/KXpJue9aeLRd0sM9uMXfZvzomB0WxVamWb5ue8kA2vVWEmW7EG+A5n3f1kqHKg==",
+ "dev": true,
+ "requires": {
+ "html-escaper": "^2.0.0"
+ }
+ },
+ "joi-browser": {
+ "version": "13.4.0",
+ "resolved": "https://registry.npmjs.org/joi-browser/-/joi-browser-13.4.0.tgz",
+ "integrity": "sha512-TfzJd2JaJ/lg/gU+q5j9rLAjnfUNF9DUmXTP9w+GfmG79LjFOXFeM7hIFuXCBcZCivUDFwd9l1btTV9rhHumtQ==",
+ "dev": true
+ },
+ "js-base64": {
+ "version": "2.5.2",
+ "resolved": "https://registry.npmjs.org/js-base64/-/js-base64-2.5.2.tgz",
+ "integrity": "sha512-Vg8czh0Q7sFBSUMWWArX/miJeBWYBPpdU/3M/DKSaekLMqrqVPaedp+5mZhie/r0lgrcaYBfwXatEew6gwgiQQ==",
+ "dev": true
+ },
+ "js-tokens": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
+ "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="
+ },
+ "js-yaml": {
+ "version": "3.13.1",
+ "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.13.1.tgz",
+ "integrity": "sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw==",
+ "dev": true,
+ "requires": {
+ "argparse": "^1.0.7",
+ "esprima": "^4.0.0"
+ }
+ },
+ "jsbn": {
+ "version": "0.1.1",
+ "resolved": "https://registry.npmjs.org/jsbn/-/jsbn-0.1.1.tgz",
+ "integrity": "sha1-peZUwuWi3rXyAdls77yoDA7y9RM=",
+ "dev": true
+ },
+ "jsesc": {
+ "version": "2.5.2",
+ "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz",
+ "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==",
+ "dev": true
+ },
+ "json-parse-better-errors": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/json-parse-better-errors/-/json-parse-better-errors-1.0.2.tgz",
+ "integrity": "sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw==",
+ "dev": true
+ },
+ "json-schema": {
+ "version": "0.2.3",
+ "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.2.3.tgz",
+ "integrity": "sha1-tIDIkuWaLwWVTOcnvT8qTogvnhM=",
+ "dev": true
+ },
+ "json-schema-traverse": {
+ "version": "0.3.1",
+ "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.3.1.tgz",
+ "integrity": "sha1-NJptRMU6Ud6JtAgFxdXlm0F9M0A=",
+ "dev": true
+ },
+ "json-stable-stringify": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/json-stable-stringify/-/json-stable-stringify-1.0.1.tgz",
+ "integrity": "sha1-mnWdOcXy/1A/1TAGRu1EX4jE+a8=",
+ "dev": true,
+ "requires": {
+ "jsonify": "~0.0.0"
+ }
+ },
+ "json-stringify-safe": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz",
+ "integrity": "sha1-Epai1Y/UXxmg9s4B1lcB4sc1tus=",
+ "dev": true
+ },
+ "json5": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/json5/-/json5-2.1.1.tgz",
+ "integrity": "sha512-l+3HXD0GEI3huGq1njuqtzYK8OYJyXMkOLtQ53pjWh89tvWS2h6l+1zMkYWqlb57+SiQodKZyvMEFb2X+KrFhQ==",
+ "dev": true,
+ "requires": {
+ "minimist": "^1.2.0"
+ }
+ },
+ "jsonfile": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz",
+ "integrity": "sha1-h3Gq4HmbZAdrdmQPygWPnBDjPss=",
+ "dev": true,
+ "requires": {
+ "graceful-fs": "^4.1.6"
+ }
+ },
+ "jsonify": {
+ "version": "0.0.0",
+ "resolved": "https://registry.npmjs.org/jsonify/-/jsonify-0.0.0.tgz",
+ "integrity": "sha1-LHS27kHZPKUbe1qu6PUDYx0lKnM=",
+ "dev": true
+ },
+ "jsonpointer": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/jsonpointer/-/jsonpointer-4.0.1.tgz",
+ "integrity": "sha1-T9kss04OnbPInIYi7PUfm5eMbLk=",
+ "dev": true
+ },
+ "jsonpointer.js": {
+ "version": "0.4.0",
+ "resolved": "https://registry.npmjs.org/jsonpointer.js/-/jsonpointer.js-0.4.0.tgz",
+ "integrity": "sha1-ACyxI/dnqv3rAZYTLOXE+ZQcyro=",
+ "dev": true
+ },
+ "jsprim": {
+ "version": "1.4.1",
+ "resolved": "https://registry.npmjs.org/jsprim/-/jsprim-1.4.1.tgz",
+ "integrity": "sha1-MT5mvB5cwG5Di8G3SZwuXFastqI=",
+ "dev": true,
+ "requires": {
+ "assert-plus": "1.0.0",
+ "extsprintf": "1.3.0",
+ "json-schema": "0.2.3",
+ "verror": "1.10.0"
+ }
+ },
+ "just-extend": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/just-extend/-/just-extend-4.0.2.tgz",
+ "integrity": "sha512-FrLwOgm+iXrPV+5zDU6Jqu4gCRXbWEQg2O3SKONsWE4w7AXFRkryS53bpWdaL9cNol+AmR3AEYz6kn+o0fCPnw==",
+ "dev": true
+ },
+ "karma": {
+ "version": "4.4.1",
+ "resolved": "https://registry.npmjs.org/karma/-/karma-4.4.1.tgz",
+ "integrity": "sha512-L5SIaXEYqzrh6b1wqYC42tNsFMx2PWuxky84pK9coK09MvmL7mxii3G3bZBh/0rvD27lqDd0le9jyhzvwif73A==",
+ "dev": true,
+ "requires": {
+ "bluebird": "^3.3.0",
+ "body-parser": "^1.16.1",
+ "braces": "^3.0.2",
+ "chokidar": "^3.0.0",
+ "colors": "^1.1.0",
+ "connect": "^3.6.0",
+ "di": "^0.0.1",
+ "dom-serialize": "^2.2.0",
+ "flatted": "^2.0.0",
+ "glob": "^7.1.1",
+ "graceful-fs": "^4.1.2",
+ "http-proxy": "^1.13.0",
+ "isbinaryfile": "^3.0.0",
+ "lodash": "^4.17.14",
+ "log4js": "^4.0.0",
+ "mime": "^2.3.1",
+ "minimatch": "^3.0.2",
+ "optimist": "^0.6.1",
+ "qjobs": "^1.1.4",
+ "range-parser": "^1.2.0",
+ "rimraf": "^2.6.0",
+ "safe-buffer": "^5.0.1",
+ "socket.io": "2.1.1",
+ "source-map": "^0.6.1",
+ "tmp": "0.0.33",
+ "useragent": "2.3.0"
+ },
+ "dependencies": {
+ "anymatch": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.1.tgz",
+ "integrity": "sha512-mM8522psRCqzV+6LhomX5wgp25YVibjh8Wj23I5RPkPppSVSjyKD2A2mBJmWGa+KN7f2D6LNh9jkBCeyLktzjg==",
+ "dev": true,
+ "requires": {
+ "normalize-path": "^3.0.0",
+ "picomatch": "^2.0.4"
+ }
+ },
+ "binary-extensions": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.0.0.tgz",
+ "integrity": "sha512-Phlt0plgpIIBOGTT/ehfFnbNlfsDEiqmzE2KRXoX1bLIlir4X/MR+zSyBEkL05ffWgnRSf/DXv+WrUAVr93/ow==",
+ "dev": true
+ },
+ "braces": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz",
+ "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==",
+ "dev": true,
+ "requires": {
+ "fill-range": "^7.0.1"
+ }
+ },
+ "chokidar": {
+ "version": "3.3.1",
+ "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.3.1.tgz",
+ "integrity": "sha512-4QYCEWOcK3OJrxwvyyAOxFuhpvOVCYkr33LPfFNBjAD/w3sEzWsp2BUOkI4l9bHvWioAd0rc6NlHUOEaWkTeqg==",
+ "dev": true,
+ "requires": {
+ "anymatch": "~3.1.1",
+ "braces": "~3.0.2",
+ "fsevents": "~2.1.2",
+ "glob-parent": "~5.1.0",
+ "is-binary-path": "~2.1.0",
+ "is-glob": "~4.0.1",
+ "normalize-path": "~3.0.0",
+ "readdirp": "~3.3.0"
+ }
+ },
+ "fill-range": {
+ "version": "7.0.1",
+ "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz",
+ "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==",
+ "dev": true,
+ "requires": {
+ "to-regex-range": "^5.0.1"
+ }
+ },
+ "fsevents": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.1.2.tgz",
+ "integrity": "sha512-R4wDiBwZ0KzpgOWetKDug1FZcYhqYnUYKtfZYt4mD5SBz76q0KR4Q9o7GIPamsVPGmW3EYPPJ0dOOjvx32ldZA==",
+ "dev": true,
+ "optional": true
+ },
+ "glob-parent": {
+ "version": "5.1.0",
+ "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.0.tgz",
+ "integrity": "sha512-qjtRgnIVmOfnKUE3NJAQEdk+lKrxfw8t5ke7SXtfMTHcjsBfOfWXCQfdb30zfDoZQ2IRSIiidmjtbHZPZ++Ihw==",
+ "dev": true,
+ "requires": {
+ "is-glob": "^4.0.1"
+ }
+ },
+ "is-binary-path": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz",
+ "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==",
+ "dev": true,
+ "requires": {
+ "binary-extensions": "^2.0.0"
+ }
+ },
+ "is-extglob": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",
+ "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=",
+ "dev": true
+ },
+ "is-glob": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.1.tgz",
+ "integrity": "sha512-5G0tKtBTFImOqDnLB2hG6Bp2qcKEFduo4tZu9MT/H6NQv/ghhy30o55ufafxJ/LdH79LLs2Kfrn85TLKyA7BUg==",
+ "dev": true,
+ "requires": {
+ "is-extglob": "^2.1.1"
+ }
+ },
+ "is-number": {
+ "version": "7.0.0",
+ "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz",
+ "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==",
+ "dev": true
+ },
+ "normalize-path": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz",
+ "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==",
+ "dev": true
+ },
+ "readdirp": {
+ "version": "3.3.0",
+ "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.3.0.tgz",
+ "integrity": "sha512-zz0pAkSPOXXm1viEwygWIPSPkcBYjW1xU5j/JBh5t9bGCJwa6f9+BJa6VaB2g+b55yVrmXzqkyLf4xaWYM0IkQ==",
+ "dev": true,
+ "requires": {
+ "picomatch": "^2.0.7"
+ }
+ },
+ "rimraf": {
+ "version": "2.7.1",
+ "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz",
+ "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==",
+ "dev": true,
+ "requires": {
+ "glob": "^7.1.3"
+ }
+ },
+ "source-map": {
+ "version": "0.6.1",
+ "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
+ "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",
+ "dev": true
+ },
+ "to-regex-range": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",
+ "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==",
+ "dev": true,
+ "requires": {
+ "is-number": "^7.0.0"
+ }
+ }
+ }
+ },
+ "karma-chai": {
+ "version": "0.1.0",
+ "resolved": "https://registry.npmjs.org/karma-chai/-/karma-chai-0.1.0.tgz",
+ "integrity": "sha1-vuWtQEAFF4Ea40u5RfdikJEIt5o=",
+ "dev": true
+ },
+ "karma-coverage-istanbul-reporter": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/karma-coverage-istanbul-reporter/-/karma-coverage-istanbul-reporter-2.1.1.tgz",
+ "integrity": "sha512-CH8lTi8+kKXGvrhy94+EkEMldLCiUA0xMOiL31vvli9qK0T+qcXJAwWBRVJWnVWxYkTmyWar8lPz63dxX6/z1A==",
+ "dev": true,
+ "requires": {
+ "istanbul-api": "^2.1.6",
+ "minimatch": "^3.0.4"
+ }
+ },
+ "karma-firefox-launcher": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/karma-firefox-launcher/-/karma-firefox-launcher-1.3.0.tgz",
+ "integrity": "sha512-Fi7xPhwrRgr+94BnHX0F5dCl1miIW4RHnzjIGxF8GaIEp7rNqX7LSi7ok63VXs3PS/5MQaQMhGxw+bvD+pibBQ==",
+ "dev": true,
+ "requires": {
+ "is-wsl": "^2.1.0"
+ }
+ },
+ "karma-json-reporter": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/karma-json-reporter/-/karma-json-reporter-1.2.1.tgz",
+ "integrity": "sha512-ASmvranNhUN0ctSuAZKeWISW9Nf4AteMcVy8rJVjS7Qk+qWgssag/nw+yivHWKDROztVFn7TdamHOETMPCkvgA==",
+ "dev": true
+ },
+ "karma-mocha": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/karma-mocha/-/karma-mocha-1.3.0.tgz",
+ "integrity": "sha1-7qrH/8DiAetjxGdEDStpx883eL8=",
+ "dev": true,
+ "requires": {
+ "minimist": "1.2.0"
+ }
+ },
+ "karma-mocha-reporter": {
+ "version": "2.2.5",
+ "resolved": "https://registry.npmjs.org/karma-mocha-reporter/-/karma-mocha-reporter-2.2.5.tgz",
+ "integrity": "sha1-FRIAlejtgZGG5HoLAS8810GJVWA=",
+ "dev": true,
+ "requires": {
+ "chalk": "^2.1.0",
+ "log-symbols": "^2.1.0",
+ "strip-ansi": "^4.0.0"
+ },
+ "dependencies": {
+ "ansi-regex": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz",
+ "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=",
+ "dev": true
+ },
+ "strip-ansi": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz",
+ "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=",
+ "dev": true,
+ "requires": {
+ "ansi-regex": "^3.0.0"
+ }
+ }
+ }
+ },
+ "karma-sinon": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/karma-sinon/-/karma-sinon-1.0.5.tgz",
+ "integrity": "sha1-TjRD8oMP3s/2JNN0cWPxIX2qKpo=",
+ "dev": true
+ },
+ "karma-sourcemap-loader": {
+ "version": "0.3.7",
+ "resolved": "https://registry.npmjs.org/karma-sourcemap-loader/-/karma-sourcemap-loader-0.3.7.tgz",
+ "integrity": "sha1-kTIsd/jxPUb+0GKwQuEAnUxFBdg=",
+ "dev": true,
+ "requires": {
+ "graceful-fs": "^4.1.2"
+ }
+ },
+ "karma-webpack": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/karma-webpack/-/karma-webpack-4.0.2.tgz",
+ "integrity": "sha512-970/okAsdUOmiMOCY8sb17A2I8neS25Ad9uhyK3GHgmRSIFJbDcNEFE8dqqUhNe9OHiCC9k3DMrSmtd/0ymP1A==",
+ "dev": true,
+ "requires": {
+ "clone-deep": "^4.0.1",
+ "loader-utils": "^1.1.0",
+ "neo-async": "^2.6.1",
+ "schema-utils": "^1.0.0",
+ "source-map": "^0.7.3",
+ "webpack-dev-middleware": "^3.7.0"
+ },
+ "dependencies": {
+ "ajv": {
+ "version": "6.11.0",
+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.11.0.tgz",
+ "integrity": "sha512-nCprB/0syFYy9fVYU1ox1l2KN8S9I+tziH8D4zdZuLT3N6RMlGSGt5FSTpAiHB/Whv8Qs1cWHma1aMKZyaHRKA==",
+ "dev": true,
+ "requires": {
+ "fast-deep-equal": "^3.1.1",
+ "fast-json-stable-stringify": "^2.0.0",
+ "json-schema-traverse": "^0.4.1",
+ "uri-js": "^4.2.2"
+ }
+ },
+ "fast-deep-equal": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.1.tgz",
+ "integrity": "sha512-8UEa58QDLauDNfpbrX55Q9jrGHThw2ZMdOky5Gl1CDtVeJDPVrG4Jxx1N8jw2gkWaff5UUuX1KJd+9zGe2B+ZA==",
+ "dev": true
+ },
+ "json-schema-traverse": {
+ "version": "0.4.1",
+ "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz",
+ "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==",
+ "dev": true
+ },
+ "schema-utils": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-1.0.0.tgz",
+ "integrity": "sha512-i27Mic4KovM/lnGsy8whRCHhc7VicJajAjTrYg11K9zfZXnYIt4k5F+kZkwjnrhKzLic/HLU4j11mjsz2G/75g==",
+ "dev": true,
+ "requires": {
+ "ajv": "^6.1.0",
+ "ajv-errors": "^1.0.0",
+ "ajv-keywords": "^3.1.0"
+ }
+ },
+ "source-map": {
+ "version": "0.7.3",
+ "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.3.tgz",
+ "integrity": "sha512-CkCj6giN3S+n9qrYiBTX5gystlENnRW5jZeNLHpe6aue+SrHcG5VYwujhW9s4dY31mEGsxBDrHR6oI69fTXsaQ==",
+ "dev": true
+ }
+ }
+ },
+ "kind-of": {
+ "version": "3.2.2",
+ "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz",
+ "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=",
+ "dev": true,
+ "requires": {
+ "is-buffer": "^1.1.5"
+ }
+ },
+ "known-css-properties": {
+ "version": "0.3.0",
+ "resolved": "https://registry.npmjs.org/known-css-properties/-/known-css-properties-0.3.0.tgz",
+ "integrity": "sha512-QMQcnKAiQccfQTqtBh/qwquGZ2XK/DXND1jrcN9M8gMMy99Gwla7GQjndVUsEqIaRyP6bsFRuhwRj5poafBGJQ==",
+ "dev": true
+ },
+ "lcid": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/lcid/-/lcid-1.0.0.tgz",
+ "integrity": "sha1-MIrMr6C8SDo4Z7S28rlQYlHRuDU=",
+ "dev": true,
+ "requires": {
+ "invert-kv": "^1.0.0"
+ }
+ },
+ "levn": {
+ "version": "0.3.0",
+ "resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz",
+ "integrity": "sha1-OwmSTt+fCDwEkP3UwLxEIeBHZO4=",
+ "dev": true,
+ "requires": {
+ "prelude-ls": "~1.1.2",
+ "type-check": "~0.3.2"
+ }
+ },
+ "load-json-file": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-1.1.0.tgz",
+ "integrity": "sha1-lWkFcI1YtLq0wiYbBPWfMcmTdMA=",
+ "dev": true,
+ "requires": {
+ "graceful-fs": "^4.1.2",
+ "parse-json": "^2.2.0",
+ "pify": "^2.0.0",
+ "pinkie-promise": "^2.0.0",
+ "strip-bom": "^2.0.0"
+ },
+ "dependencies": {
+ "pify": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz",
+ "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=",
+ "dev": true
+ },
+ "strip-bom": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-2.0.0.tgz",
+ "integrity": "sha1-YhmoVhZSBJHzV4i9vxRHqZx+aw4=",
+ "dev": true,
+ "requires": {
+ "is-utf8": "^0.2.0"
+ }
+ }
+ }
+ },
+ "loader-runner": {
+ "version": "2.4.0",
+ "resolved": "https://registry.npmjs.org/loader-runner/-/loader-runner-2.4.0.tgz",
+ "integrity": "sha512-Jsmr89RcXGIwivFY21FcRrisYZfvLMTWx5kOLc+JTxtpBOG6xML0vzbc6SEQG2FO9/4Fc3wW4LVcB5DmGflaRw==",
+ "dev": true
+ },
+ "loader-utils": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-1.2.3.tgz",
+ "integrity": "sha512-fkpz8ejdnEMG3s37wGL07iSBDg99O9D5yflE9RGNH3hRdx9SOwYfnGYdZOUIZitN8E+E2vkq3MUMYMvPYl5ZZA==",
+ "dev": true,
+ "requires": {
+ "big.js": "^5.2.2",
+ "emojis-list": "^2.0.0",
+ "json5": "^1.0.1"
+ },
+ "dependencies": {
+ "json5": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.1.tgz",
+ "integrity": "sha512-aKS4WQjPenRxiQsC93MNfjx+nbF4PAdYzmd/1JIj8HYzqfbu86beTuNgXDzPknWk0n0uARlyewZo4s++ES36Ow==",
+ "dev": true,
+ "requires": {
+ "minimist": "^1.2.0"
+ }
+ }
+ }
+ },
+ "locate-path": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz",
+ "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==",
+ "dev": true,
+ "requires": {
+ "p-locate": "^3.0.0",
+ "path-exists": "^3.0.0"
+ }
+ },
+ "lodash": {
+ "version": "4.17.15",
+ "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.15.tgz",
+ "integrity": "sha512-8xOcRHvCjnocdS5cpwXQXVzmmh5e5+saE2QGoeQmbKmRS6J3VQppPOIt0MnmE+4xlZoumy0GPG0D0MVIQbNA1A==",
+ "dev": true
+ },
+ "lodash.capitalize": {
+ "version": "4.2.1",
+ "resolved": "https://registry.npmjs.org/lodash.capitalize/-/lodash.capitalize-4.2.1.tgz",
+ "integrity": "sha1-+CbJtOKoUR2E46yinbBeGk87cqk=",
+ "dev": true
+ },
+ "lodash.escape": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/lodash.escape/-/lodash.escape-4.0.1.tgz",
+ "integrity": "sha1-yQRGkMIeBClL6qUXcS/e0fqI3pg=",
+ "dev": true
+ },
+ "lodash.flattendeep": {
+ "version": "4.4.0",
+ "resolved": "https://registry.npmjs.org/lodash.flattendeep/-/lodash.flattendeep-4.4.0.tgz",
+ "integrity": "sha1-+wMJF/hqMTTlvJvsDWngAT3f7bI=",
+ "dev": true
+ },
+ "lodash.isequal": {
+ "version": "4.5.0",
+ "resolved": "https://registry.npmjs.org/lodash.isequal/-/lodash.isequal-4.5.0.tgz",
+ "integrity": "sha1-QVxEePK8wwEgwizhDtMib30+GOA=",
+ "dev": true
+ },
+ "lodash.kebabcase": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/lodash.kebabcase/-/lodash.kebabcase-4.1.1.tgz",
+ "integrity": "sha1-hImxyw0p/4gZXM7KRI/21swpXDY=",
+ "dev": true
+ },
+ "log-symbols": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-2.2.0.tgz",
+ "integrity": "sha512-VeIAFslyIerEJLXHziedo2basKbMKtTw3vfn5IzG0XTjhAVEJyNHnL2p7vc+wBDSdQuUpNw3M2u6xb9QsAY5Eg==",
+ "dev": true,
+ "requires": {
+ "chalk": "^2.0.1"
+ }
+ },
+ "log4js": {
+ "version": "4.5.1",
+ "resolved": "https://registry.npmjs.org/log4js/-/log4js-4.5.1.tgz",
+ "integrity": "sha512-EEEgFcE9bLgaYUKuozyFfytQM2wDHtXn4tAN41pkaxpNjAykv11GVdeI4tHtmPWW4Xrgh9R/2d7XYghDVjbKKw==",
+ "dev": true,
+ "requires": {
+ "date-format": "^2.0.0",
+ "debug": "^4.1.1",
+ "flatted": "^2.0.0",
+ "rfdc": "^1.1.4",
+ "streamroller": "^1.0.6"
+ }
+ },
+ "lolex": {
+ "version": "4.2.0",
+ "resolved": "https://registry.npmjs.org/lolex/-/lolex-4.2.0.tgz",
+ "integrity": "sha512-gKO5uExCXvSm6zbF562EvM+rd1kQDnB9AZBbiQVzf1ZmdDpxUSvpnAaVOP83N/31mRK8Ml8/VE8DMvsAZQ+7wg==",
+ "dev": true
+ },
+ "loose-envify": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
+ "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
+ "requires": {
+ "js-tokens": "^3.0.0 || ^4.0.0"
+ }
+ },
+ "loud-rejection": {
+ "version": "1.6.0",
+ "resolved": "https://registry.npmjs.org/loud-rejection/-/loud-rejection-1.6.0.tgz",
+ "integrity": "sha1-W0b4AUft7leIcPCG0Eghz5mOVR8=",
+ "dev": true,
+ "requires": {
+ "currently-unhandled": "^0.4.1",
+ "signal-exit": "^3.0.0"
+ }
+ },
+ "lru-cache": {
+ "version": "4.1.5",
+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-4.1.5.tgz",
+ "integrity": "sha512-sWZlbEP2OsHNkXrMl5GYk/jKk70MBng6UU4YI/qGDYbgf6YbP4EvmqISbXCoJiRKs+1bSpFHVgQxvJ17F2li5g==",
+ "dev": true,
+ "requires": {
+ "pseudomap": "^1.0.2",
+ "yallist": "^2.1.2"
+ }
+ },
+ "make-dir": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-2.1.0.tgz",
+ "integrity": "sha512-LS9X+dc8KLxXCb8dni79fLIIUA5VyZoyjSMCwTluaXA0o27cCK0bhXkpgw+sTXVpPy/lSO57ilRixqk0vDmtRA==",
+ "dev": true,
+ "requires": {
+ "pify": "^4.0.1",
+ "semver": "^5.6.0"
+ }
+ },
+ "mamacro": {
+ "version": "0.0.3",
+ "resolved": "https://registry.npmjs.org/mamacro/-/mamacro-0.0.3.tgz",
+ "integrity": "sha512-qMEwh+UujcQ+kbz3T6V+wAmO2U8veoq2w+3wY8MquqwVA3jChfwY+Tk52GZKDfACEPjuZ7r2oJLejwpt8jtwTA==",
+ "dev": true
+ },
+ "map-age-cleaner": {
+ "version": "0.1.3",
+ "resolved": "https://registry.npmjs.org/map-age-cleaner/-/map-age-cleaner-0.1.3.tgz",
+ "integrity": "sha512-bJzx6nMoP6PDLPBFmg7+xRKeFZvFboMrGlxmNj9ClvX53KrmvM5bXFXEWjbz4cz1AFn+jWJ9z/DJSz7hrs0w3w==",
+ "dev": true,
+ "requires": {
+ "p-defer": "^1.0.0"
+ }
+ },
+ "map-cache": {
+ "version": "0.2.2",
+ "resolved": "https://registry.npmjs.org/map-cache/-/map-cache-0.2.2.tgz",
+ "integrity": "sha1-wyq9C9ZSXZsFFkW7TyasXcmKDb8=",
+ "dev": true
+ },
+ "map-obj": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/map-obj/-/map-obj-1.0.1.tgz",
+ "integrity": "sha1-2TPOuSBdgr3PSIb2dCvcK03qFG0=",
+ "dev": true
+ },
+ "map-visit": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/map-visit/-/map-visit-1.0.0.tgz",
+ "integrity": "sha1-7Nyo8TFE5mDxtb1B8S80edmN+48=",
+ "dev": true,
+ "requires": {
+ "object-visit": "^1.0.0"
+ }
+ },
+ "math-random": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/math-random/-/math-random-1.0.4.tgz",
+ "integrity": "sha512-rUxjysqif/BZQH2yhd5Aaq7vXMSx9NdEsQcyA07uEzIvxgI7zIr33gGsh+RU0/XjmQpCW7RsVof1vlkvQVCK5A==",
+ "dev": true
+ },
+ "md5.js": {
+ "version": "1.3.5",
+ "resolved": "https://registry.npmjs.org/md5.js/-/md5.js-1.3.5.tgz",
+ "integrity": "sha512-xitP+WxNPcTTOgnTJcrhM0xvdPepipPSf3I8EIpGKeFLjt3PlJLIDG3u8EX53ZIubkb+5U2+3rELYpEhHhzdkg==",
+ "dev": true,
+ "requires": {
+ "hash-base": "^3.0.0",
+ "inherits": "^2.0.1",
+ "safe-buffer": "^5.1.2"
+ }
+ },
+ "media-typer": {
+ "version": "0.3.0",
+ "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
+ "integrity": "sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g=",
+ "dev": true
+ },
+ "mem": {
+ "version": "4.3.0",
+ "resolved": "https://registry.npmjs.org/mem/-/mem-4.3.0.tgz",
+ "integrity": "sha512-qX2bG48pTqYRVmDB37rn/6PT7LcR8T7oAX3bf99u1Tt1nzxYfxkgqDwUwolPlXweM0XzBOBFzSx4kfp7KP1s/w==",
+ "dev": true,
+ "requires": {
+ "map-age-cleaner": "^0.1.1",
+ "mimic-fn": "^2.0.0",
+ "p-is-promise": "^2.0.0"
+ }
+ },
+ "memory-fs": {
+ "version": "0.4.1",
+ "resolved": "https://registry.npmjs.org/memory-fs/-/memory-fs-0.4.1.tgz",
+ "integrity": "sha1-OpoguEYlI+RHz7x+i7gO1me/xVI=",
+ "dev": true,
+ "requires": {
+ "errno": "^0.1.3",
+ "readable-stream": "^2.0.1"
+ }
+ },
+ "memorystream": {
+ "version": "0.3.1",
+ "resolved": "https://registry.npmjs.org/memorystream/-/memorystream-0.3.1.tgz",
+ "integrity": "sha1-htcJCzDORV1j+64S3aUaR93K+bI=",
+ "dev": true
+ },
+ "meow": {
+ "version": "3.7.0",
+ "resolved": "https://registry.npmjs.org/meow/-/meow-3.7.0.tgz",
+ "integrity": "sha1-cstmi0JSKCkKu/qFaJJYcwioAfs=",
+ "dev": true,
+ "requires": {
+ "camelcase-keys": "^2.0.0",
+ "decamelize": "^1.1.2",
+ "loud-rejection": "^1.0.0",
+ "map-obj": "^1.0.1",
+ "minimist": "^1.1.3",
+ "normalize-package-data": "^2.3.4",
+ "object-assign": "^4.0.1",
+ "read-pkg-up": "^1.0.1",
+ "redent": "^1.0.0",
+ "trim-newlines": "^1.0.0"
+ }
+ },
+ "merge": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/merge/-/merge-1.2.1.tgz",
+ "integrity": "sha512-VjFo4P5Whtj4vsLzsYBu5ayHhoHJ0UqNm7ibvShmbmoz7tGi0vXaoJbGdB+GmDMLUdg8DpQXEIeVDAe8MaABvQ==",
+ "dev": true
+ },
+ "micromatch": {
+ "version": "2.3.11",
+ "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-2.3.11.tgz",
+ "integrity": "sha1-hmd8l9FyCzY0MdBNDRUpO9OMFWU=",
+ "dev": true,
+ "requires": {
+ "arr-diff": "^2.0.0",
+ "array-unique": "^0.2.1",
+ "braces": "^1.8.2",
+ "expand-brackets": "^0.1.4",
+ "extglob": "^0.3.1",
+ "filename-regex": "^2.0.0",
+ "is-extglob": "^1.0.0",
+ "is-glob": "^2.0.1",
+ "kind-of": "^3.0.2",
+ "normalize-path": "^2.0.1",
+ "object.omit": "^2.0.0",
+ "parse-glob": "^3.0.4",
+ "regex-cache": "^0.4.2"
+ }
+ },
+ "miller-rabin": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/miller-rabin/-/miller-rabin-4.0.1.tgz",
+ "integrity": "sha512-115fLhvZVqWwHPbClyntxEVfVDfl9DLLTuJvq3g2O/Oxi8AiNouAHvDSzHS0viUJc+V5vm3eq91Xwqn9dp4jRA==",
+ "dev": true,
+ "requires": {
+ "bn.js": "^4.0.0",
+ "brorand": "^1.0.1"
+ }
+ },
+ "mime": {
+ "version": "2.4.4",
+ "resolved": "https://registry.npmjs.org/mime/-/mime-2.4.4.tgz",
+ "integrity": "sha512-LRxmNwziLPT828z+4YkNzloCFC2YM4wrB99k+AV5ZbEyfGNWfG8SO1FUXLmLDBSo89NrJZ4DIWeLjy1CHGhMGA==",
+ "dev": true
+ },
+ "mime-db": {
+ "version": "1.43.0",
+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.43.0.tgz",
+ "integrity": "sha512-+5dsGEEovYbT8UY9yD7eE4XTc4UwJ1jBYlgaQQF38ENsKR3wj/8q8RFZrF9WIZpB2V1ArTVFUva8sAul1NzRzQ==",
+ "dev": true
+ },
+ "mime-types": {
+ "version": "2.1.26",
+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.26.tgz",
+ "integrity": "sha512-01paPWYgLrkqAyrlDorC1uDwl2p3qZT7yl806vW7DvDoxwXi46jsjFbg+WdwotBIk6/MbEhO/dh5aZ5sNj/dWQ==",
+ "dev": true,
+ "requires": {
+ "mime-db": "1.43.0"
+ }
+ },
+ "mimic-fn": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz",
+ "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==",
+ "dev": true
+ },
+ "minimalistic-assert": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz",
+ "integrity": "sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A==",
+ "dev": true
+ },
+ "minimalistic-crypto-utils": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/minimalistic-crypto-utils/-/minimalistic-crypto-utils-1.0.1.tgz",
+ "integrity": "sha1-9sAMHAsIIkblxNmd+4x8CDsrWCo=",
+ "dev": true
+ },
+ "minimatch": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz",
+ "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==",
+ "dev": true,
+ "requires": {
+ "brace-expansion": "^1.1.7"
+ }
+ },
+ "minimist": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz",
+ "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=",
+ "dev": true
+ },
+ "mississippi": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/mississippi/-/mississippi-3.0.0.tgz",
+ "integrity": "sha512-x471SsVjUtBRtcvd4BzKE9kFC+/2TeWgKCgw0bZcw1b9l2X3QX5vCWgF+KaZaYm87Ss//rHnWryupDrgLvmSkA==",
+ "dev": true,
+ "requires": {
+ "concat-stream": "^1.5.0",
+ "duplexify": "^3.4.2",
+ "end-of-stream": "^1.1.0",
+ "flush-write-stream": "^1.0.0",
+ "from2": "^2.1.0",
+ "parallel-transform": "^1.1.0",
+ "pump": "^3.0.0",
+ "pumpify": "^1.3.3",
+ "stream-each": "^1.1.0",
+ "through2": "^2.0.0"
+ }
+ },
+ "mixin-deep": {
+ "version": "1.3.2",
+ "resolved": "https://registry.npmjs.org/mixin-deep/-/mixin-deep-1.3.2.tgz",
+ "integrity": "sha512-WRoDn//mXBiJ1H40rqa3vH0toePwSsGb45iInWlTySa+Uu4k3tYUSxa2v1KqAiLtvlrSzaExqS1gtk96A9zvEA==",
+ "dev": true,
+ "requires": {
+ "for-in": "^1.0.2",
+ "is-extendable": "^1.0.1"
+ },
+ "dependencies": {
+ "is-extendable": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-1.0.1.tgz",
+ "integrity": "sha512-arnXMxT1hhoKo9k1LZdmlNyJdDDfy2v0fXjFlmok4+i8ul/6WlbVge9bhM74OpNPQPMGUToDtz+KXa1PneJxOA==",
+ "dev": true,
+ "requires": {
+ "is-plain-object": "^2.0.4"
+ }
+ }
+ }
+ },
+ "mkdirp": {
+ "version": "0.5.1",
+ "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz",
+ "integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=",
+ "dev": true,
+ "requires": {
+ "minimist": "0.0.8"
+ },
+ "dependencies": {
+ "minimist": {
+ "version": "0.0.8",
+ "resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz",
+ "integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=",
+ "dev": true
+ }
+ }
+ },
+ "mocha": {
+ "version": "7.0.1",
+ "resolved": "https://registry.npmjs.org/mocha/-/mocha-7.0.1.tgz",
+ "integrity": "sha512-9eWmWTdHLXh72rGrdZjNbG3aa1/3NRPpul1z0D979QpEnFdCG0Q5tv834N+94QEN2cysfV72YocQ3fn87s70fg==",
+ "dev": true,
+ "requires": {
+ "ansi-colors": "3.2.3",
+ "browser-stdout": "1.3.1",
+ "chokidar": "3.3.0",
+ "debug": "3.2.6",
+ "diff": "3.5.0",
+ "escape-string-regexp": "1.0.5",
+ "find-up": "3.0.0",
+ "glob": "7.1.3",
+ "growl": "1.10.5",
+ "he": "1.2.0",
+ "js-yaml": "3.13.1",
+ "log-symbols": "2.2.0",
+ "minimatch": "3.0.4",
+ "mkdirp": "0.5.1",
+ "ms": "2.1.1",
+ "node-environment-flags": "1.0.6",
+ "object.assign": "4.1.0",
+ "strip-json-comments": "2.0.1",
+ "supports-color": "6.0.0",
+ "which": "1.3.1",
+ "wide-align": "1.1.3",
+ "yargs": "13.3.0",
+ "yargs-parser": "13.1.1",
+ "yargs-unparser": "1.6.0"
+ },
+ "dependencies": {
+ "ansi-colors": {
+ "version": "3.2.3",
+ "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-3.2.3.tgz",
+ "integrity": "sha512-LEHHyuhlPY3TmuUYMh2oz89lTShfvgbmzaBcxve9t/9Wuy7Dwf4yoAKcND7KFT1HAQfqZ12qtc+DUrBMeKF9nw==",
+ "dev": true
+ },
+ "anymatch": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.1.tgz",
+ "integrity": "sha512-mM8522psRCqzV+6LhomX5wgp25YVibjh8Wj23I5RPkPppSVSjyKD2A2mBJmWGa+KN7f2D6LNh9jkBCeyLktzjg==",
+ "dev": true,
+ "requires": {
+ "normalize-path": "^3.0.0",
+ "picomatch": "^2.0.4"
+ }
+ },
+ "binary-extensions": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.0.0.tgz",
+ "integrity": "sha512-Phlt0plgpIIBOGTT/ehfFnbNlfsDEiqmzE2KRXoX1bLIlir4X/MR+zSyBEkL05ffWgnRSf/DXv+WrUAVr93/ow==",
+ "dev": true
+ },
+ "braces": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz",
+ "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==",
+ "dev": true,
+ "requires": {
+ "fill-range": "^7.0.1"
+ }
+ },
+ "chokidar": {
+ "version": "3.3.0",
+ "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.3.0.tgz",
+ "integrity": "sha512-dGmKLDdT3Gdl7fBUe8XK+gAtGmzy5Fn0XkkWQuYxGIgWVPPse2CxFA5mtrlD0TOHaHjEUqkWNyP1XdHoJES/4A==",
+ "dev": true,
+ "requires": {
+ "anymatch": "~3.1.1",
+ "braces": "~3.0.2",
+ "fsevents": "~2.1.1",
+ "glob-parent": "~5.1.0",
+ "is-binary-path": "~2.1.0",
+ "is-glob": "~4.0.1",
+ "normalize-path": "~3.0.0",
+ "readdirp": "~3.2.0"
+ }
+ },
+ "debug": {
+ "version": "3.2.6",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz",
+ "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==",
+ "dev": true,
+ "requires": {
+ "ms": "^2.1.1"
+ }
+ },
+ "fill-range": {
+ "version": "7.0.1",
+ "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz",
+ "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==",
+ "dev": true,
+ "requires": {
+ "to-regex-range": "^5.0.1"
+ }
+ },
+ "fsevents": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.1.2.tgz",
+ "integrity": "sha512-R4wDiBwZ0KzpgOWetKDug1FZcYhqYnUYKtfZYt4mD5SBz76q0KR4Q9o7GIPamsVPGmW3EYPPJ0dOOjvx32ldZA==",
+ "dev": true,
+ "optional": true
+ },
+ "glob": {
+ "version": "7.1.3",
+ "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.3.tgz",
+ "integrity": "sha512-vcfuiIxogLV4DlGBHIUOwI0IbrJ8HWPc4MU7HzviGeNho/UJDfi6B5p3sHeWIQ0KGIU0Jpxi5ZHxemQfLkkAwQ==",
+ "dev": true,
+ "requires": {
+ "fs.realpath": "^1.0.0",
+ "inflight": "^1.0.4",
+ "inherits": "2",
+ "minimatch": "^3.0.4",
+ "once": "^1.3.0",
+ "path-is-absolute": "^1.0.0"
+ }
+ },
+ "glob-parent": {
+ "version": "5.1.0",
+ "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.0.tgz",
+ "integrity": "sha512-qjtRgnIVmOfnKUE3NJAQEdk+lKrxfw8t5ke7SXtfMTHcjsBfOfWXCQfdb30zfDoZQ2IRSIiidmjtbHZPZ++Ihw==",
+ "dev": true,
+ "requires": {
+ "is-glob": "^4.0.1"
+ }
+ },
+ "is-binary-path": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz",
+ "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==",
+ "dev": true,
+ "requires": {
+ "binary-extensions": "^2.0.0"
+ }
+ },
+ "is-extglob": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",
+ "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=",
+ "dev": true
+ },
+ "is-glob": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.1.tgz",
+ "integrity": "sha512-5G0tKtBTFImOqDnLB2hG6Bp2qcKEFduo4tZu9MT/H6NQv/ghhy30o55ufafxJ/LdH79LLs2Kfrn85TLKyA7BUg==",
+ "dev": true,
+ "requires": {
+ "is-extglob": "^2.1.1"
+ }
+ },
+ "is-number": {
+ "version": "7.0.0",
+ "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz",
+ "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==",
+ "dev": true
+ },
+ "ms": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz",
+ "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==",
+ "dev": true
+ },
+ "normalize-path": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz",
+ "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==",
+ "dev": true
+ },
+ "readdirp": {
+ "version": "3.2.0",
+ "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.2.0.tgz",
+ "integrity": "sha512-crk4Qu3pmXwgxdSgGhgA/eXiJAPQiX4GMOZZMXnqKxHX7TaoL+3gQVo/WeuAiogr07DpnfjIMpXXa+PAIvwPGQ==",
+ "dev": true,
+ "requires": {
+ "picomatch": "^2.0.4"
+ }
+ },
+ "supports-color": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-6.0.0.tgz",
+ "integrity": "sha512-on9Kwidc1IUQo+bQdhi8+Tijpo0e1SS6RoGo2guUwn5vdaxw8RXOF9Vb2ws+ihWOmh4JnCJOvaziZWP1VABaLg==",
+ "dev": true,
+ "requires": {
+ "has-flag": "^3.0.0"
+ }
+ },
+ "to-regex-range": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",
+ "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==",
+ "dev": true,
+ "requires": {
+ "is-number": "^7.0.0"
+ }
+ }
+ }
+ },
+ "mock-raf": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/mock-raf/-/mock-raf-1.0.1.tgz",
+ "integrity": "sha512-+25y56bblLzEnv+G4ODsHNck07A5uP5HFfu/1VBKeFrUXoFT9oru+R+jLxLz6rwdM5drUHFdqX9LYBsMP4dz/w==",
+ "dev": true,
+ "requires": {
+ "object-assign": "^3.0.0"
+ },
+ "dependencies": {
+ "object-assign": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-3.0.0.tgz",
+ "integrity": "sha1-m+3VygiXlJvKR+f/QIBi1Un1h/I=",
+ "dev": true
+ }
+ }
+ },
+ "moo": {
+ "version": "0.5.1",
+ "resolved": "https://registry.npmjs.org/moo/-/moo-0.5.1.tgz",
+ "integrity": "sha512-I1mnb5xn4fO80BH9BLcF0yLypy2UKl+Cb01Fu0hJRkJjlCRtxZMWkTdAtDd5ZqCOxtCkhmRwyI57vWT+1iZ67w==",
+ "dev": true
+ },
+ "move-concurrently": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/move-concurrently/-/move-concurrently-1.0.1.tgz",
+ "integrity": "sha1-viwAX9oy4LKa8fBdfEszIUxwH5I=",
+ "dev": true,
+ "requires": {
+ "aproba": "^1.1.1",
+ "copy-concurrently": "^1.0.0",
+ "fs-write-stream-atomic": "^1.0.8",
+ "mkdirp": "^0.5.1",
+ "rimraf": "^2.5.4",
+ "run-queue": "^1.0.3"
+ },
+ "dependencies": {
+ "rimraf": {
+ "version": "2.7.1",
+ "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz",
+ "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==",
+ "dev": true,
+ "requires": {
+ "glob": "^7.1.3"
+ }
+ }
+ }
+ },
+ "ms": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
+ "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==",
+ "dev": true
+ },
+ "mute-stream": {
+ "version": "0.0.5",
+ "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.5.tgz",
+ "integrity": "sha1-j7+rsKmKJT0xhDMfno3rc3L6xsA=",
+ "dev": true
+ },
+ "nan": {
+ "version": "2.14.0",
+ "resolved": "https://registry.npmjs.org/nan/-/nan-2.14.0.tgz",
+ "integrity": "sha512-INOFj37C7k3AfaNTtX8RhsTw7qRy7eLET14cROi9+5HAVbbHuIWUHEauBv5qT4Av2tWasiTY1Jw6puUNqRJXQg==",
+ "dev": true
+ },
+ "nanomatch": {
+ "version": "1.2.13",
+ "resolved": "https://registry.npmjs.org/nanomatch/-/nanomatch-1.2.13.tgz",
+ "integrity": "sha512-fpoe2T0RbHwBTBUOftAfBPaDEi06ufaUai0mE6Yn1kacc3SnTErfb/h+X94VXzI64rKFHYImXSvdwGGCmwOqCA==",
+ "dev": true,
+ "requires": {
+ "arr-diff": "^4.0.0",
+ "array-unique": "^0.3.2",
+ "define-property": "^2.0.2",
+ "extend-shallow": "^3.0.2",
+ "fragment-cache": "^0.2.1",
+ "is-windows": "^1.0.2",
+ "kind-of": "^6.0.2",
+ "object.pick": "^1.3.0",
+ "regex-not": "^1.0.0",
+ "snapdragon": "^0.8.1",
+ "to-regex": "^3.0.1"
+ },
+ "dependencies": {
+ "arr-diff": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-4.0.0.tgz",
+ "integrity": "sha1-1kYQdP6/7HHn4VI1dhoyml3HxSA=",
+ "dev": true
+ },
+ "array-unique": {
+ "version": "0.3.2",
+ "resolved": "https://registry.npmjs.org/array-unique/-/array-unique-0.3.2.tgz",
+ "integrity": "sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg=",
+ "dev": true
+ },
+ "kind-of": {
+ "version": "6.0.3",
+ "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz",
+ "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==",
+ "dev": true
+ }
+ }
+ },
+ "nearley": {
+ "version": "2.19.1",
+ "resolved": "https://registry.npmjs.org/nearley/-/nearley-2.19.1.tgz",
+ "integrity": "sha512-xq47GIUGXxU9vQg7g/y1o1xuKnkO7ev4nRWqftmQrLkfnE/FjRqDaGOUakM8XHPn/6pW3bGjU2wgoJyId90rqg==",
+ "dev": true,
+ "requires": {
+ "commander": "^2.19.0",
+ "moo": "^0.5.0",
+ "railroad-diagrams": "^1.0.0",
+ "randexp": "0.4.6",
+ "semver": "^5.4.1"
+ }
+ },
+ "negotiator": {
+ "version": "0.6.2",
+ "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.2.tgz",
+ "integrity": "sha512-hZXc7K2e+PgeI1eDBe/10Ard4ekbfrrqG8Ep+8Jmf4JID2bNg7NvCPOZN+kfF574pFQI7mum2AUqDidoKqcTOw==",
+ "dev": true
+ },
+ "neo-async": {
+ "version": "2.6.1",
+ "resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.1.tgz",
+ "integrity": "sha512-iyam8fBuCUpWeKPGpaNMetEocMt364qkCsfL9JuhjXX6dRnguRVOfk2GZaDpPjcOKiiXCPINZC1GczQ7iTq3Zw==",
+ "dev": true
+ },
+ "next-tick": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/next-tick/-/next-tick-1.0.0.tgz",
+ "integrity": "sha1-yobR/ogoFpsBICCOPchCS524NCw=",
+ "dev": true
+ },
+ "nice-try": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/nice-try/-/nice-try-1.0.5.tgz",
+ "integrity": "sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==",
+ "dev": true
+ },
+ "nise": {
+ "version": "1.5.3",
+ "resolved": "https://registry.npmjs.org/nise/-/nise-1.5.3.tgz",
+ "integrity": "sha512-Ymbac/94xeIrMf59REBPOv0thr+CJVFMhrlAkW/gjCIE58BGQdCj0x7KRCb3yz+Ga2Rz3E9XXSvUyyxqqhjQAQ==",
+ "dev": true,
+ "requires": {
+ "@sinonjs/formatio": "^3.2.1",
+ "@sinonjs/text-encoding": "^0.7.1",
+ "just-extend": "^4.0.2",
+ "lolex": "^5.0.1",
+ "path-to-regexp": "^1.7.0"
+ },
+ "dependencies": {
+ "lolex": {
+ "version": "5.1.2",
+ "resolved": "https://registry.npmjs.org/lolex/-/lolex-5.1.2.tgz",
+ "integrity": "sha512-h4hmjAvHTmd+25JSwrtTIuwbKdwg5NzZVRMLn9saij4SZaepCrTCxPr35H/3bjwfMJtN+t3CX8672UIkglz28A==",
+ "dev": true,
+ "requires": {
+ "@sinonjs/commons": "^1.7.0"
+ }
+ }
+ }
+ },
+ "node-environment-flags": {
+ "version": "1.0.6",
+ "resolved": "https://registry.npmjs.org/node-environment-flags/-/node-environment-flags-1.0.6.tgz",
+ "integrity": "sha512-5Evy2epuL+6TM0lCQGpFIj6KwiEsGh1SrHUhTbNX+sLbBtjidPZFAnVK9y5yU1+h//RitLbRHTIMyxQPtxMdHw==",
+ "dev": true,
+ "requires": {
+ "object.getownpropertydescriptors": "^2.0.3",
+ "semver": "^5.7.0"
+ }
+ },
+ "node-fetch": {
+ "version": "2.6.0",
+ "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.0.tgz",
+ "integrity": "sha512-8dG4H5ujfvFiqDmVu9fQ5bOHUC15JMjMY/Zumv26oOvvVJjM67KF8koCWIabKQ1GJIa9r2mMZscBq/TbdOcmNA==",
+ "dev": true
+ },
+ "node-gyp": {
+ "version": "3.8.0",
+ "resolved": "https://registry.npmjs.org/node-gyp/-/node-gyp-3.8.0.tgz",
+ "integrity": "sha512-3g8lYefrRRzvGeSowdJKAKyks8oUpLEd/DyPV4eMhVlhJ0aNaZqIrNUIPuEWWTAoPqyFkfGrM67MC69baqn6vA==",
+ "dev": true,
+ "requires": {
+ "fstream": "^1.0.0",
+ "glob": "^7.0.3",
+ "graceful-fs": "^4.1.2",
+ "mkdirp": "^0.5.0",
+ "nopt": "2 || 3",
+ "npmlog": "0 || 1 || 2 || 3 || 4",
+ "osenv": "0",
+ "request": "^2.87.0",
+ "rimraf": "2",
+ "semver": "~5.3.0",
+ "tar": "^2.0.0",
+ "which": "1"
+ },
+ "dependencies": {
+ "rimraf": {
+ "version": "2.7.1",
+ "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz",
+ "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==",
+ "dev": true,
+ "requires": {
+ "glob": "^7.1.3"
+ }
+ },
+ "semver": {
+ "version": "5.3.0",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-5.3.0.tgz",
+ "integrity": "sha1-myzl094C0XxgEq0yaqa00M9U+U8=",
+ "dev": true
+ }
+ }
+ },
+ "node-libs-browser": {
+ "version": "2.2.1",
+ "resolved": "https://registry.npmjs.org/node-libs-browser/-/node-libs-browser-2.2.1.tgz",
+ "integrity": "sha512-h/zcD8H9kaDZ9ALUWwlBUDo6TKF8a7qBSCSEGfjTVIYeqsioSKaAX+BN7NgiMGp6iSIXZ3PxgCu8KS3b71YK5Q==",
+ "dev": true,
+ "requires": {
+ "assert": "^1.1.1",
+ "browserify-zlib": "^0.2.0",
+ "buffer": "^4.3.0",
+ "console-browserify": "^1.1.0",
+ "constants-browserify": "^1.0.0",
+ "crypto-browserify": "^3.11.0",
+ "domain-browser": "^1.1.1",
+ "events": "^3.0.0",
+ "https-browserify": "^1.0.0",
+ "os-browserify": "^0.3.0",
+ "path-browserify": "0.0.1",
+ "process": "^0.11.10",
+ "punycode": "^1.2.4",
+ "querystring-es3": "^0.2.0",
+ "readable-stream": "^2.3.3",
+ "stream-browserify": "^2.0.1",
+ "stream-http": "^2.7.2",
+ "string_decoder": "^1.0.0",
+ "timers-browserify": "^2.0.4",
+ "tty-browserify": "0.0.0",
+ "url": "^0.11.0",
+ "util": "^0.11.0",
+ "vm-browserify": "^1.0.1"
+ },
+ "dependencies": {
+ "inherits": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz",
+ "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=",
+ "dev": true
+ },
+ "punycode": {
+ "version": "1.4.1",
+ "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.4.1.tgz",
+ "integrity": "sha1-wNWmOycYgArY4esPpSachN1BhF4=",
+ "dev": true
+ },
+ "util": {
+ "version": "0.11.1",
+ "resolved": "https://registry.npmjs.org/util/-/util-0.11.1.tgz",
+ "integrity": "sha512-HShAsny+zS2TZfaXxD9tYj4HQGlBezXZMZuM/S5PKLLoZkShZiGk9o5CzukI1LVHZvjdvZ2Sj1aW/Ndn2NB/HQ==",
+ "dev": true,
+ "requires": {
+ "inherits": "2.0.3"
+ }
+ }
+ }
+ },
+ "node-sass": {
+ "version": "4.13.1",
+ "resolved": "https://registry.npmjs.org/node-sass/-/node-sass-4.13.1.tgz",
+ "integrity": "sha512-TTWFx+ZhyDx1Biiez2nB0L3YrCZ/8oHagaDalbuBSlqXgUPsdkUSzJsVxeDO9LtPB49+Fh3WQl3slABo6AotNw==",
+ "dev": true,
+ "requires": {
+ "async-foreach": "^0.1.3",
+ "chalk": "^1.1.1",
+ "cross-spawn": "^3.0.0",
+ "gaze": "^1.0.0",
+ "get-stdin": "^4.0.1",
+ "glob": "^7.0.3",
+ "in-publish": "^2.0.0",
+ "lodash": "^4.17.15",
+ "meow": "^3.7.0",
+ "mkdirp": "^0.5.1",
+ "nan": "^2.13.2",
+ "node-gyp": "^3.8.0",
+ "npmlog": "^4.0.0",
+ "request": "^2.88.0",
+ "sass-graph": "^2.2.4",
+ "stdout-stream": "^1.4.0",
+ "true-case-path": "^1.0.2"
+ },
+ "dependencies": {
+ "ansi-styles": {
+ "version": "2.2.1",
+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz",
+ "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=",
+ "dev": true
+ },
+ "chalk": {
+ "version": "1.1.3",
+ "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz",
+ "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=",
+ "dev": true,
+ "requires": {
+ "ansi-styles": "^2.2.1",
+ "escape-string-regexp": "^1.0.2",
+ "has-ansi": "^2.0.0",
+ "strip-ansi": "^3.0.0",
+ "supports-color": "^2.0.0"
+ }
+ },
+ "supports-color": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz",
+ "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=",
+ "dev": true
+ }
+ }
+ },
+ "nopt": {
+ "version": "3.0.6",
+ "resolved": "https://registry.npmjs.org/nopt/-/nopt-3.0.6.tgz",
+ "integrity": "sha1-xkZdvwirzU2zWTF/eaxopkayj/k=",
+ "dev": true,
+ "requires": {
+ "abbrev": "1"
+ }
+ },
+ "normalize-package-data": {
+ "version": "2.5.0",
+ "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-2.5.0.tgz",
+ "integrity": "sha512-/5CMN3T0R4XTj4DcGaexo+roZSdSFW/0AOOTROrjxzCG1wrWXEsGbRKevjlIL+ZDE4sZlJr5ED4YW0yqmkK+eA==",
+ "dev": true,
+ "requires": {
+ "hosted-git-info": "^2.1.4",
+ "resolve": "^1.10.0",
+ "semver": "2 || 3 || 4 || 5",
+ "validate-npm-package-license": "^3.0.1"
+ }
+ },
+ "normalize-path": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-2.1.1.tgz",
+ "integrity": "sha1-GrKLVW4Zg2Oowab35vogE3/mrtk=",
+ "dev": true,
+ "requires": {
+ "remove-trailing-separator": "^1.0.1"
+ }
+ },
+ "npm-run-all": {
+ "version": "4.1.5",
+ "resolved": "https://registry.npmjs.org/npm-run-all/-/npm-run-all-4.1.5.tgz",
+ "integrity": "sha512-Oo82gJDAVcaMdi3nuoKFavkIHBRVqQ1qvMb+9LHk/cF4P6B2m8aP04hGf7oL6wZ9BuGwX1onlLhpuoofSyoQDQ==",
+ "dev": true,
+ "requires": {
+ "ansi-styles": "^3.2.1",
+ "chalk": "^2.4.1",
+ "cross-spawn": "^6.0.5",
+ "memorystream": "^0.3.1",
+ "minimatch": "^3.0.4",
+ "pidtree": "^0.3.0",
+ "read-pkg": "^3.0.0",
+ "shell-quote": "^1.6.1",
+ "string.prototype.padend": "^3.0.0"
+ },
+ "dependencies": {
+ "cross-spawn": {
+ "version": "6.0.5",
+ "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz",
+ "integrity": "sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==",
+ "dev": true,
+ "requires": {
+ "nice-try": "^1.0.4",
+ "path-key": "^2.0.1",
+ "semver": "^5.5.0",
+ "shebang-command": "^1.2.0",
+ "which": "^1.2.9"
+ }
+ },
+ "load-json-file": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-4.0.0.tgz",
+ "integrity": "sha1-L19Fq5HjMhYjT9U62rZo607AmTs=",
+ "dev": true,
+ "requires": {
+ "graceful-fs": "^4.1.2",
+ "parse-json": "^4.0.0",
+ "pify": "^3.0.0",
+ "strip-bom": "^3.0.0"
+ }
+ },
+ "parse-json": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-4.0.0.tgz",
+ "integrity": "sha1-vjX1Qlvh9/bHRxhPmKeIy5lHfuA=",
+ "dev": true,
+ "requires": {
+ "error-ex": "^1.3.1",
+ "json-parse-better-errors": "^1.0.1"
+ }
+ },
+ "path-type": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/path-type/-/path-type-3.0.0.tgz",
+ "integrity": "sha512-T2ZUsdZFHgA3u4e5PfPbjd7HDDpxPnQb5jN0SrDsjNSuVXHJqtwTnWqG0B1jZrgmJ/7lj1EmVIByWt1gxGkWvg==",
+ "dev": true,
+ "requires": {
+ "pify": "^3.0.0"
+ }
+ },
+ "pify": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz",
+ "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=",
+ "dev": true
+ },
+ "read-pkg": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-3.0.0.tgz",
+ "integrity": "sha1-nLxoaXj+5l0WwA4rGcI3/Pbjg4k=",
+ "dev": true,
+ "requires": {
+ "load-json-file": "^4.0.0",
+ "normalize-package-data": "^2.3.2",
+ "path-type": "^3.0.0"
+ }
+ }
+ }
+ },
+ "npm-run-path": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-2.0.2.tgz",
+ "integrity": "sha1-NakjLfo11wZ7TLLd8jV7GHFTbF8=",
+ "dev": true,
+ "requires": {
+ "path-key": "^2.0.0"
+ }
+ },
+ "npmlog": {
+ "version": "4.1.2",
+ "resolved": "https://registry.npmjs.org/npmlog/-/npmlog-4.1.2.tgz",
+ "integrity": "sha512-2uUqazuKlTaSI/dC8AzicUck7+IrEaOnN/e0jd3Xtt1KcGpwx30v50mL7oPyr/h9bL3E4aZccVwpwP+5W9Vjkg==",
+ "dev": true,
+ "requires": {
+ "are-we-there-yet": "~1.1.2",
+ "console-control-strings": "~1.1.0",
+ "gauge": "~2.7.3",
+ "set-blocking": "~2.0.0"
+ }
+ },
+ "nth-check": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/nth-check/-/nth-check-1.0.2.tgz",
+ "integrity": "sha512-WeBOdju8SnzPN5vTUJYxYUxLeXpCaVP5i5e0LF8fg7WORF2Wd7wFX/pk0tYZk7s8T+J7VLy0Da6J1+wCT0AtHg==",
+ "dev": true,
+ "requires": {
+ "boolbase": "~1.0.0"
+ }
+ },
+ "number-is-nan": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/number-is-nan/-/number-is-nan-1.0.1.tgz",
+ "integrity": "sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0=",
+ "dev": true
+ },
+ "oauth-sign": {
+ "version": "0.9.0",
+ "resolved": "https://registry.npmjs.org/oauth-sign/-/oauth-sign-0.9.0.tgz",
+ "integrity": "sha512-fexhUFFPTGV8ybAtSIGbV6gOkSv8UtRbDBnAyLQw4QPKkgNlsH2ByPGtMUqdWkos6YCRmAqViwgZrJc/mRDzZQ==",
+ "dev": true
+ },
+ "object-assign": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
+ "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM="
+ },
+ "object-component": {
+ "version": "0.0.3",
+ "resolved": "https://registry.npmjs.org/object-component/-/object-component-0.0.3.tgz",
+ "integrity": "sha1-8MaapQ78lbhmwYb0AKM3acsvEpE=",
+ "dev": true
+ },
+ "object-copy": {
+ "version": "0.1.0",
+ "resolved": "https://registry.npmjs.org/object-copy/-/object-copy-0.1.0.tgz",
+ "integrity": "sha1-fn2Fi3gb18mRpBupde04EnVOmYw=",
+ "dev": true,
+ "requires": {
+ "copy-descriptor": "^0.1.0",
+ "define-property": "^0.2.5",
+ "kind-of": "^3.0.3"
+ },
+ "dependencies": {
+ "define-property": {
+ "version": "0.2.5",
+ "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz",
+ "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=",
+ "dev": true,
+ "requires": {
+ "is-descriptor": "^0.1.0"
+ }
+ }
+ }
+ },
+ "object-inspect": {
+ "version": "1.7.0",
+ "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.7.0.tgz",
+ "integrity": "sha512-a7pEHdh1xKIAgTySUGgLMx/xwDZskN1Ud6egYYN3EdRW4ZMPNEDUTF+hwy2LUC+Bl+SyLXANnwz/jyh/qutKUw==",
+ "dev": true
+ },
+ "object-is": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/object-is/-/object-is-1.0.2.tgz",
+ "integrity": "sha512-Epah+btZd5wrrfjkJZq1AOB9O6OxUQto45hzFd7lXGrpHPGE0W1k+426yrZV+k6NJOzLNNW/nVsmZdIWsAqoOQ==",
+ "dev": true
+ },
+ "object-keys": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz",
+ "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==",
+ "dev": true
+ },
+ "object-visit": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/object-visit/-/object-visit-1.0.1.tgz",
+ "integrity": "sha1-95xEk68MU3e1n+OdOV5BBC3QRbs=",
+ "dev": true,
+ "requires": {
+ "isobject": "^3.0.0"
+ },
+ "dependencies": {
+ "isobject": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz",
+ "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=",
+ "dev": true
+ }
+ }
+ },
+ "object.assign": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.0.tgz",
+ "integrity": "sha512-exHJeq6kBKj58mqGyTQ9DFvrZC/eR6OwxzoM9YRoGBqrXYonaFyGiFMuc9VZrXf7DarreEwMpurG3dd+CNyW5w==",
+ "dev": true,
+ "requires": {
+ "define-properties": "^1.1.2",
+ "function-bind": "^1.1.1",
+ "has-symbols": "^1.0.0",
+ "object-keys": "^1.0.11"
+ }
+ },
+ "object.entries": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/object.entries/-/object.entries-1.1.1.tgz",
+ "integrity": "sha512-ilqR7BgdyZetJutmDPfXCDffGa0/Yzl2ivVNpbx/g4UeWrCdRnFDUBrKJGLhGieRHDATnyZXWBeCb29k9CJysQ==",
+ "dev": true,
+ "requires": {
+ "define-properties": "^1.1.3",
+ "es-abstract": "^1.17.0-next.1",
+ "function-bind": "^1.1.1",
+ "has": "^1.0.3"
+ }
+ },
+ "object.fromentries": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/object.fromentries/-/object.fromentries-2.0.2.tgz",
+ "integrity": "sha512-r3ZiBH7MQppDJVLx6fhD618GKNG40CZYH9wgwdhKxBDDbQgjeWGGd4AtkZad84d291YxvWe7bJGuE65Anh0dxQ==",
+ "dev": true,
+ "requires": {
+ "define-properties": "^1.1.3",
+ "es-abstract": "^1.17.0-next.1",
+ "function-bind": "^1.1.1",
+ "has": "^1.0.3"
+ }
+ },
+ "object.getownpropertydescriptors": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/object.getownpropertydescriptors/-/object.getownpropertydescriptors-2.1.0.tgz",
+ "integrity": "sha512-Z53Oah9A3TdLoblT7VKJaTDdXdT+lQO+cNpKVnya5JDe9uLvzu1YyY1yFDFrcxrlRgWrEFH0jJtD/IbuwjcEVg==",
+ "dev": true,
+ "requires": {
+ "define-properties": "^1.1.3",
+ "es-abstract": "^1.17.0-next.1"
+ }
+ },
+ "object.omit": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/object.omit/-/object.omit-2.0.1.tgz",
+ "integrity": "sha1-Gpx0SCnznbuFjHbKNXmuKlTr0fo=",
+ "dev": true,
+ "requires": {
+ "for-own": "^0.1.4",
+ "is-extendable": "^0.1.1"
+ }
+ },
+ "object.pick": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/object.pick/-/object.pick-1.3.0.tgz",
+ "integrity": "sha1-h6EKxMFpS9Lhy/U1kaZhQftd10c=",
+ "dev": true,
+ "requires": {
+ "isobject": "^3.0.1"
+ },
+ "dependencies": {
+ "isobject": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz",
+ "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=",
+ "dev": true
+ }
+ }
+ },
+ "object.values": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/object.values/-/object.values-1.1.1.tgz",
+ "integrity": "sha512-WTa54g2K8iu0kmS/us18jEmdv1a4Wi//BZ/DTVYEcH0XhLM5NYdpDHja3gt57VrZLcNAO2WGA+KpWsDBaHt6eA==",
+ "dev": true,
+ "requires": {
+ "define-properties": "^1.1.3",
+ "es-abstract": "^1.17.0-next.1",
+ "function-bind": "^1.1.1",
+ "has": "^1.0.3"
+ }
+ },
+ "on-finished": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz",
+ "integrity": "sha1-IPEzZIGwg811M3mSoWlxqi2QaUc=",
+ "dev": true,
+ "requires": {
+ "ee-first": "1.1.1"
+ }
+ },
+ "once": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
+ "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=",
+ "dev": true,
+ "requires": {
+ "wrappy": "1"
+ }
+ },
+ "onetime": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/onetime/-/onetime-1.1.0.tgz",
+ "integrity": "sha1-ofeDj4MUxRbwXs78vEzP4EtO14k=",
+ "dev": true
+ },
+ "optimist": {
+ "version": "0.6.1",
+ "resolved": "https://registry.npmjs.org/optimist/-/optimist-0.6.1.tgz",
+ "integrity": "sha1-2j6nRob6IaGaERwybpDrFaAZZoY=",
+ "dev": true,
+ "requires": {
+ "minimist": "~0.0.1",
+ "wordwrap": "~0.0.2"
+ },
+ "dependencies": {
+ "minimist": {
+ "version": "0.0.10",
+ "resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.10.tgz",
+ "integrity": "sha1-3j+YVD2/lggr5IrRoMfNqDYwHc8=",
+ "dev": true
+ }
+ }
+ },
+ "optionator": {
+ "version": "0.8.3",
+ "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.8.3.tgz",
+ "integrity": "sha512-+IW9pACdk3XWmmTXG8m3upGUJst5XRGzxMRjXzAuJ1XnIFNvfhjjIuYkDvysnPQ7qzqVzLt78BCruntqRhWQbA==",
+ "dev": true,
+ "requires": {
+ "deep-is": "~0.1.3",
+ "fast-levenshtein": "~2.0.6",
+ "levn": "~0.3.0",
+ "prelude-ls": "~1.1.2",
+ "type-check": "~0.3.2",
+ "word-wrap": "~1.2.3"
+ }
+ },
+ "os-browserify": {
+ "version": "0.3.0",
+ "resolved": "https://registry.npmjs.org/os-browserify/-/os-browserify-0.3.0.tgz",
+ "integrity": "sha1-hUNzx/XCMVkU/Jv8a9gjj92h7Cc=",
+ "dev": true
+ },
+ "os-homedir": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/os-homedir/-/os-homedir-1.0.2.tgz",
+ "integrity": "sha1-/7xJiDNuDoM94MFox+8VISGqf7M=",
+ "dev": true
+ },
+ "os-locale": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/os-locale/-/os-locale-1.4.0.tgz",
+ "integrity": "sha1-IPnxeuKe00XoveWDsT0gCYA8FNk=",
+ "dev": true,
+ "requires": {
+ "lcid": "^1.0.0"
+ }
+ },
+ "os-tmpdir": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz",
+ "integrity": "sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ=",
+ "dev": true
+ },
+ "osenv": {
+ "version": "0.1.5",
+ "resolved": "https://registry.npmjs.org/osenv/-/osenv-0.1.5.tgz",
+ "integrity": "sha512-0CWcCECdMVc2Rw3U5w9ZjqX6ga6ubk1xDVKxtBQPK7wis/0F2r9T6k4ydGYhecl7YUBxBVxhL5oisPsNxAPe2g==",
+ "dev": true,
+ "requires": {
+ "os-homedir": "^1.0.0",
+ "os-tmpdir": "^1.0.0"
+ }
+ },
+ "p-defer": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/p-defer/-/p-defer-1.0.0.tgz",
+ "integrity": "sha1-n26xgvbJqozXQwBKfU+WsZaw+ww=",
+ "dev": true
+ },
+ "p-finally": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/p-finally/-/p-finally-1.0.0.tgz",
+ "integrity": "sha1-P7z7FbiZpEEjs0ttzBi3JDNqLK4=",
+ "dev": true
+ },
+ "p-is-promise": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/p-is-promise/-/p-is-promise-2.1.0.tgz",
+ "integrity": "sha512-Y3W0wlRPK8ZMRbNq97l4M5otioeA5lm1z7bkNkxCka8HSPjR0xRWmpCmc9utiaLP9Jb1eD8BgeIxTW4AIF45Pg==",
+ "dev": true
+ },
+ "p-limit": {
+ "version": "2.2.2",
+ "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.2.2.tgz",
+ "integrity": "sha512-WGR+xHecKTr7EbUEhyLSh5Dube9JtdiG78ufaeLxTgpudf/20KqyMioIUZJAezlTIi6evxuoUs9YXc11cU+yzQ==",
+ "dev": true,
+ "requires": {
+ "p-try": "^2.0.0"
+ }
+ },
+ "p-locate": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz",
+ "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==",
+ "dev": true,
+ "requires": {
+ "p-limit": "^2.0.0"
+ }
+ },
+ "p-try": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz",
+ "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==",
+ "dev": true
+ },
+ "pako": {
+ "version": "1.0.11",
+ "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz",
+ "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==",
+ "dev": true
+ },
+ "parallel-transform": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/parallel-transform/-/parallel-transform-1.2.0.tgz",
+ "integrity": "sha512-P2vSmIu38uIlvdcU7fDkyrxj33gTUy/ABO5ZUbGowxNCopBq/OoD42bP4UmMrJoPyk4Uqf0mu3mtWBhHCZD8yg==",
+ "dev": true,
+ "requires": {
+ "cyclist": "^1.0.1",
+ "inherits": "^2.0.3",
+ "readable-stream": "^2.1.5"
+ }
+ },
+ "parse-asn1": {
+ "version": "5.1.5",
+ "resolved": "https://registry.npmjs.org/parse-asn1/-/parse-asn1-5.1.5.tgz",
+ "integrity": "sha512-jkMYn1dcJqF6d5CpU689bq7w/b5ALS9ROVSpQDPrZsqqesUJii9qutvoT5ltGedNXMO2e16YUWIghG9KxaViTQ==",
+ "dev": true,
+ "requires": {
+ "asn1.js": "^4.0.0",
+ "browserify-aes": "^1.0.0",
+ "create-hash": "^1.1.0",
+ "evp_bytestokey": "^1.0.0",
+ "pbkdf2": "^3.0.3",
+ "safe-buffer": "^5.1.1"
+ }
+ },
+ "parse-glob": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/parse-glob/-/parse-glob-3.0.4.tgz",
+ "integrity": "sha1-ssN2z7EfNVE7rdFz7wu246OIORw=",
+ "dev": true,
+ "requires": {
+ "glob-base": "^0.3.0",
+ "is-dotfile": "^1.0.0",
+ "is-extglob": "^1.0.0",
+ "is-glob": "^2.0.0"
+ }
+ },
+ "parse-json": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-2.2.0.tgz",
+ "integrity": "sha1-9ID0BDTvgHQfhGkJn43qGPVaTck=",
+ "dev": true,
+ "requires": {
+ "error-ex": "^1.2.0"
+ }
+ },
+ "parse-passwd": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/parse-passwd/-/parse-passwd-1.0.0.tgz",
+ "integrity": "sha1-bVuTSkVpk7I9N/QKOC1vFmao5cY=",
+ "dev": true
+ },
+ "parse5": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/parse5/-/parse5-3.0.3.tgz",
+ "integrity": "sha512-rgO9Zg5LLLkfJF9E6CCmXlSE4UVceloys8JrFqCcHloC3usd/kJCyPDwH2SOlzix2j3xaP9sUX3e8+kvkuleAA==",
+ "dev": true,
+ "requires": {
+ "@types/node": "*"
+ }
+ },
+ "parseqs": {
+ "version": "0.0.5",
+ "resolved": "https://registry.npmjs.org/parseqs/-/parseqs-0.0.5.tgz",
+ "integrity": "sha1-1SCKNzjkZ2bikbouoXNoSSGouJ0=",
+ "dev": true,
+ "requires": {
+ "better-assert": "~1.0.0"
+ }
+ },
+ "parseuri": {
+ "version": "0.0.5",
+ "resolved": "https://registry.npmjs.org/parseuri/-/parseuri-0.0.5.tgz",
+ "integrity": "sha1-gCBKUNTbt3m/3G6+J3jZDkvOMgo=",
+ "dev": true,
+ "requires": {
+ "better-assert": "~1.0.0"
+ }
+ },
+ "parseurl": {
+ "version": "1.3.3",
+ "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
+ "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",
+ "dev": true
+ },
+ "pascalcase": {
+ "version": "0.1.1",
+ "resolved": "https://registry.npmjs.org/pascalcase/-/pascalcase-0.1.1.tgz",
+ "integrity": "sha1-s2PlXoAGym/iF4TS2yK9FdeRfxQ=",
+ "dev": true
+ },
+ "path-browserify": {
+ "version": "0.0.1",
+ "resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-0.0.1.tgz",
+ "integrity": "sha512-BapA40NHICOS+USX9SN4tyhq+A2RrN/Ws5F0Z5aMHDp98Fl86lX8Oti8B7uN93L4Ifv4fHOEA+pQw87gmMO/lQ==",
+ "dev": true
+ },
+ "path-dirname": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/path-dirname/-/path-dirname-1.0.2.tgz",
+ "integrity": "sha1-zDPSTVJeCZpTiMAzbG4yuRYGCeA=",
+ "dev": true
+ },
+ "path-exists": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-3.0.0.tgz",
+ "integrity": "sha1-zg6+ql94yxiSXqfYENe1mwEP1RU=",
+ "dev": true
+ },
+ "path-is-absolute": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz",
+ "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=",
+ "dev": true
+ },
+ "path-is-inside": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/path-is-inside/-/path-is-inside-1.0.2.tgz",
+ "integrity": "sha1-NlQX3t5EQw0cEa9hAn+s8HS9/FM=",
+ "dev": true
+ },
+ "path-key": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz",
+ "integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=",
+ "dev": true
+ },
+ "path-parse": {
+ "version": "1.0.6",
+ "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.6.tgz",
+ "integrity": "sha512-GSmOT2EbHrINBf9SR7CDELwlJ8AENk3Qn7OikK4nFYAu3Ote2+JYNVvkpAEQm3/TLNEJFD/xZJjzyxg3KBWOzw==",
+ "dev": true
+ },
+ "path-to-regexp": {
+ "version": "1.8.0",
+ "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-1.8.0.tgz",
+ "integrity": "sha512-n43JRhlUKUAlibEJhPeir1ncUID16QnEjNpwzNdO3Lm4ywrBpBZ5oLD0I6br9evr1Y9JTqwRtAh7JLoOzAQdVA==",
+ "dev": true,
+ "requires": {
+ "isarray": "0.0.1"
+ },
+ "dependencies": {
+ "isarray": {
+ "version": "0.0.1",
+ "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz",
+ "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=",
+ "dev": true
+ }
+ }
+ },
+ "path-type": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/path-type/-/path-type-1.1.0.tgz",
+ "integrity": "sha1-WcRPfuSR2nBNpBXaWkBwuk+P5EE=",
+ "dev": true,
+ "requires": {
+ "graceful-fs": "^4.1.2",
+ "pify": "^2.0.0",
+ "pinkie-promise": "^2.0.0"
+ },
+ "dependencies": {
+ "pify": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz",
+ "integrity": "sha1-7RQaasBDqEnqWISY59yosVMw6Qw=",
+ "dev": true
+ }
+ }
+ },
+ "pathval": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/pathval/-/pathval-1.1.0.tgz",
+ "integrity": "sha1-uULm1L3mUwBe9rcTYd74cn0GReA=",
+ "dev": true
+ },
+ "pbkdf2": {
+ "version": "3.0.17",
+ "resolved": "https://registry.npmjs.org/pbkdf2/-/pbkdf2-3.0.17.tgz",
+ "integrity": "sha512-U/il5MsrZp7mGg3mSQfn742na2T+1/vHDCG5/iTI3X9MKUuYUZVLQhyRsg06mCgDBTd57TxzgZt7P+fYfjRLtA==",
+ "dev": true,
+ "requires": {
+ "create-hash": "^1.1.2",
+ "create-hmac": "^1.1.4",
+ "ripemd160": "^2.0.1",
+ "safe-buffer": "^5.0.1",
+ "sha.js": "^2.4.8"
+ }
+ },
+ "performance-now": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/performance-now/-/performance-now-2.1.0.tgz",
+ "integrity": "sha1-Ywn04OX6kT7BxpMHrjZLSzd8nns=",
+ "dev": true
+ },
+ "picomatch": {
+ "version": "2.2.1",
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.2.1.tgz",
+ "integrity": "sha512-ISBaA8xQNmwELC7eOjqFKMESB2VIqt4PPDD0nsS95b/9dZXvVKOlz9keMSnoGGKcOHXfTvDD6WMaRoSc9UuhRA==",
+ "dev": true
+ },
+ "pidtree": {
+ "version": "0.3.0",
+ "resolved": "https://registry.npmjs.org/pidtree/-/pidtree-0.3.0.tgz",
+ "integrity": "sha512-9CT4NFlDcosssyg8KVFltgokyKZIFjoBxw8CTGy+5F38Y1eQWrt8tRayiUOXE+zVKQnYu5BR8JjCtvK3BcnBhg==",
+ "dev": true
+ },
+ "pify": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/pify/-/pify-4.0.1.tgz",
+ "integrity": "sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g==",
+ "dev": true
+ },
+ "pinkie": {
+ "version": "2.0.4",
+ "resolved": "https://registry.npmjs.org/pinkie/-/pinkie-2.0.4.tgz",
+ "integrity": "sha1-clVrgM+g1IqXToDnckjoDtT3+HA=",
+ "dev": true
+ },
+ "pinkie-promise": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/pinkie-promise/-/pinkie-promise-2.0.1.tgz",
+ "integrity": "sha1-ITXW36ejWMBprJsXh3YogihFD/o=",
+ "dev": true,
+ "requires": {
+ "pinkie": "^2.0.0"
+ }
+ },
+ "pkg-dir": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-3.0.0.tgz",
+ "integrity": "sha512-/E57AYkoeQ25qkxMj5PBOVgF8Kiu/h7cYS30Z5+R7WaiCCBfLq58ZI/dSeaEKb9WVJV5n/03QwrN3IeWIFllvw==",
+ "dev": true,
+ "requires": {
+ "find-up": "^3.0.0"
+ }
+ },
+ "pluralize": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/pluralize/-/pluralize-1.2.1.tgz",
+ "integrity": "sha1-0aIUg/0iu0HlihL6NCGCMUCJfEU=",
+ "dev": true
+ },
+ "posix-character-classes": {
+ "version": "0.1.1",
+ "resolved": "https://registry.npmjs.org/posix-character-classes/-/posix-character-classes-0.1.1.tgz",
+ "integrity": "sha1-AerA/jta9xoqbAL+q7jB/vfgDqs=",
+ "dev": true
+ },
+ "prelude-ls": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz",
+ "integrity": "sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ=",
+ "dev": true
+ },
+ "preserve": {
+ "version": "0.2.0",
+ "resolved": "https://registry.npmjs.org/preserve/-/preserve-0.2.0.tgz",
+ "integrity": "sha1-gV7R9uvGWSb4ZbMQwHE7yzMVzks=",
+ "dev": true
+ },
+ "process": {
+ "version": "0.11.10",
+ "resolved": "https://registry.npmjs.org/process/-/process-0.11.10.tgz",
+ "integrity": "sha1-czIwDoQBYb2j5podHZGn1LwW8YI=",
+ "dev": true
+ },
+ "process-nextick-args": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz",
+ "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==",
+ "dev": true
+ },
+ "progress": {
+ "version": "1.1.8",
+ "resolved": "https://registry.npmjs.org/progress/-/progress-1.1.8.tgz",
+ "integrity": "sha1-4mDHj2Fhzdmw5WzD4Khd4Xx6V74=",
+ "dev": true
+ },
+ "promise-inflight": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/promise-inflight/-/promise-inflight-1.0.1.tgz",
+ "integrity": "sha1-mEcocL8igTL8vdhoEputEsPAKeM=",
+ "dev": true
+ },
+ "prop-types": {
+ "version": "15.7.2",
+ "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.7.2.tgz",
+ "integrity": "sha512-8QQikdH7//R2vurIJSutZ1smHYTcLpRWEOlHnzcWHmBYrOGUysKwSsrC89BCiFj3CbrfJ/nXFdJepOVrY1GCHQ==",
+ "requires": {
+ "loose-envify": "^1.4.0",
+ "object-assign": "^4.1.1",
+ "react-is": "^16.8.1"
+ }
+ },
+ "prop-types-exact": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/prop-types-exact/-/prop-types-exact-1.2.0.tgz",
+ "integrity": "sha512-K+Tk3Kd9V0odiXFP9fwDHUYRyvK3Nun3GVyPapSIs5OBkITAm15W0CPFD/YKTkMUAbc0b9CUwRQp2ybiBIq+eA==",
+ "dev": true,
+ "requires": {
+ "has": "^1.0.3",
+ "object.assign": "^4.1.0",
+ "reflect.ownkeys": "^0.2.0"
+ }
+ },
+ "prr": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/prr/-/prr-1.0.1.tgz",
+ "integrity": "sha1-0/wRS6BplaRexok/SEzrHXj19HY=",
+ "dev": true
+ },
+ "pseudomap": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/pseudomap/-/pseudomap-1.0.2.tgz",
+ "integrity": "sha1-8FKijacOYYkX7wqKw0wa5aaChrM=",
+ "dev": true
+ },
+ "psl": {
+ "version": "1.7.0",
+ "resolved": "https://registry.npmjs.org/psl/-/psl-1.7.0.tgz",
+ "integrity": "sha512-5NsSEDv8zY70ScRnOTn7bK7eanl2MvFrOrS/R6x+dBt5g1ghnj9Zv90kO8GwT8gxcu2ANyFprnFYB85IogIJOQ==",
+ "dev": true
+ },
+ "public-encrypt": {
+ "version": "4.0.3",
+ "resolved": "https://registry.npmjs.org/public-encrypt/-/public-encrypt-4.0.3.tgz",
+ "integrity": "sha512-zVpa8oKZSz5bTMTFClc1fQOnyyEzpl5ozpi1B5YcvBrdohMjH2rfsBtyXcuNuwjsDIXmBYlF2N5FlJYhR29t8Q==",
+ "dev": true,
+ "requires": {
+ "bn.js": "^4.1.0",
+ "browserify-rsa": "^4.0.0",
+ "create-hash": "^1.1.0",
+ "parse-asn1": "^5.0.0",
+ "randombytes": "^2.0.1",
+ "safe-buffer": "^5.1.2"
+ }
+ },
+ "pump": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.0.tgz",
+ "integrity": "sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==",
+ "dev": true,
+ "requires": {
+ "end-of-stream": "^1.1.0",
+ "once": "^1.3.1"
+ }
+ },
+ "pumpify": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/pumpify/-/pumpify-1.5.1.tgz",
+ "integrity": "sha512-oClZI37HvuUJJxSKKrC17bZ9Cu0ZYhEAGPsPUy9KlMUmv9dKX2o77RUmq7f3XjIxbwyGwYzbzQ1L2Ks8sIradQ==",
+ "dev": true,
+ "requires": {
+ "duplexify": "^3.6.0",
+ "inherits": "^2.0.3",
+ "pump": "^2.0.0"
+ },
+ "dependencies": {
+ "pump": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/pump/-/pump-2.0.1.tgz",
+ "integrity": "sha512-ruPMNRkN3MHP1cWJc9OWr+T/xDP0jhXYCLfJcBuX54hhfIBnaQmAUMfDcG4DM5UMWByBbJY69QSphm3jtDKIkA==",
+ "dev": true,
+ "requires": {
+ "end-of-stream": "^1.1.0",
+ "once": "^1.3.1"
+ }
+ }
+ }
+ },
+ "punycode": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz",
+ "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==",
+ "dev": true
+ },
+ "qjobs": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/qjobs/-/qjobs-1.2.0.tgz",
+ "integrity": "sha512-8YOJEHtxpySA3fFDyCRxA+UUV+fA+rTWnuWvylOK/NCjhY+b4ocCtmu8TtsWb+mYeU+GCHf/S66KZF/AsteKHg==",
+ "dev": true
+ },
+ "qs": {
+ "version": "6.7.0",
+ "resolved": "https://registry.npmjs.org/qs/-/qs-6.7.0.tgz",
+ "integrity": "sha512-VCdBRNFTX1fyE7Nb6FYoURo/SPe62QCaAyzJvUjwRaIsc+NePBEniHlvxFmmX56+HZphIGtV0XeCirBtpDrTyQ==",
+ "dev": true
+ },
+ "querystring": {
+ "version": "0.2.0",
+ "resolved": "https://registry.npmjs.org/querystring/-/querystring-0.2.0.tgz",
+ "integrity": "sha1-sgmEkgO7Jd+CDadW50cAWHhSFiA=",
+ "dev": true
+ },
+ "querystring-es3": {
+ "version": "0.2.1",
+ "resolved": "https://registry.npmjs.org/querystring-es3/-/querystring-es3-0.2.1.tgz",
+ "integrity": "sha1-nsYfeQSYdXB9aUFFlv2Qek1xHnM=",
+ "dev": true
+ },
+ "raf": {
+ "version": "3.4.1",
+ "resolved": "https://registry.npmjs.org/raf/-/raf-3.4.1.tgz",
+ "integrity": "sha512-Sq4CW4QhwOHE8ucn6J34MqtZCeWFP2aQSmrlroYgqAV1PjStIhJXxYuTgUIfkEk7zTLjmIjLmU5q+fbD1NnOJA==",
+ "dev": true,
+ "requires": {
+ "performance-now": "^2.1.0"
+ }
+ },
+ "railroad-diagrams": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/railroad-diagrams/-/railroad-diagrams-1.0.0.tgz",
+ "integrity": "sha1-635iZ1SN3t+4mcG5Dlc3RVnN234=",
+ "dev": true
+ },
+ "randexp": {
+ "version": "0.4.6",
+ "resolved": "https://registry.npmjs.org/randexp/-/randexp-0.4.6.tgz",
+ "integrity": "sha512-80WNmd9DA0tmZrw9qQa62GPPWfuXJknrmVmLcxvq4uZBdYqb1wYoKTmnlGUchvVWe0XiLupYkBoXVOxz3C8DYQ==",
+ "dev": true,
+ "requires": {
+ "discontinuous-range": "1.0.0",
+ "ret": "~0.1.10"
+ }
+ },
+ "randomatic": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/randomatic/-/randomatic-3.1.1.tgz",
+ "integrity": "sha512-TuDE5KxZ0J461RVjrJZCJc+J+zCkTb1MbH9AQUq68sMhOMcy9jLcb3BrZKgp9q9Ncltdg4QVqWrH02W2EFFVYw==",
+ "dev": true,
+ "requires": {
+ "is-number": "^4.0.0",
+ "kind-of": "^6.0.0",
+ "math-random": "^1.0.1"
+ },
+ "dependencies": {
+ "is-number": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/is-number/-/is-number-4.0.0.tgz",
+ "integrity": "sha512-rSklcAIlf1OmFdyAqbnWTLVelsQ58uvZ66S/ZyawjWqIviTWCjg2PzVGw8WUA+nNuPTqb4wgA+NszrJ+08LlgQ==",
+ "dev": true
+ },
+ "kind-of": {
+ "version": "6.0.3",
+ "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz",
+ "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==",
+ "dev": true
+ }
+ }
+ },
+ "randombytes": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz",
+ "integrity": "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==",
+ "dev": true,
+ "requires": {
+ "safe-buffer": "^5.1.0"
+ }
+ },
+ "randomfill": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/randomfill/-/randomfill-1.0.4.tgz",
+ "integrity": "sha512-87lcbR8+MhcWcUiQ+9e+Rwx8MyR2P7qnt15ynUlbm3TU/fjbgz4GsvfSUDTemtCCtVCqb4ZcEFlyPNTh9bBTLw==",
+ "dev": true,
+ "requires": {
+ "randombytes": "^2.0.5",
+ "safe-buffer": "^5.1.0"
+ }
+ },
+ "range-parser": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",
+ "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==",
+ "dev": true
+ },
+ "raw-body": {
+ "version": "2.4.0",
+ "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.4.0.tgz",
+ "integrity": "sha512-4Oz8DUIwdvoa5qMJelxipzi/iJIi40O5cGV1wNYp5hvZP8ZN0T+jiNkL0QepXs+EsQ9XJ8ipEDoiH70ySUJP3Q==",
+ "dev": true,
+ "requires": {
+ "bytes": "3.1.0",
+ "http-errors": "1.7.2",
+ "iconv-lite": "0.4.24",
+ "unpipe": "1.0.0"
+ }
+ },
+ "raw-loader": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/raw-loader/-/raw-loader-4.0.0.tgz",
+ "integrity": "sha512-iINUOYvl1cGEmfoaLjnZXt4bKfT2LJnZZib5N/LLyAphC+Dd11vNP9CNVb38j+SAJpFI1uo8j9frmih53ASy7Q==",
+ "dev": true,
+ "requires": {
+ "loader-utils": "^1.2.3",
+ "schema-utils": "^2.5.0"
+ },
+ "dependencies": {
+ "ajv": {
+ "version": "6.11.0",
+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.11.0.tgz",
+ "integrity": "sha512-nCprB/0syFYy9fVYU1ox1l2KN8S9I+tziH8D4zdZuLT3N6RMlGSGt5FSTpAiHB/Whv8Qs1cWHma1aMKZyaHRKA==",
+ "dev": true,
+ "requires": {
+ "fast-deep-equal": "^3.1.1",
+ "fast-json-stable-stringify": "^2.0.0",
+ "json-schema-traverse": "^0.4.1",
+ "uri-js": "^4.2.2"
+ }
+ },
+ "fast-deep-equal": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.1.tgz",
+ "integrity": "sha512-8UEa58QDLauDNfpbrX55Q9jrGHThw2ZMdOky5Gl1CDtVeJDPVrG4Jxx1N8jw2gkWaff5UUuX1KJd+9zGe2B+ZA==",
+ "dev": true
+ },
+ "json-schema-traverse": {
+ "version": "0.4.1",
+ "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz",
+ "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==",
+ "dev": true
+ },
+ "schema-utils": {
+ "version": "2.6.4",
+ "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-2.6.4.tgz",
+ "integrity": "sha512-VNjcaUxVnEeun6B2fiiUDjXXBtD4ZSH7pdbfIu1pOFwgptDPLMo/z9jr4sUfsjFVPqDCEin/F7IYlq7/E6yDbQ==",
+ "dev": true,
+ "requires": {
+ "ajv": "^6.10.2",
+ "ajv-keywords": "^3.4.1"
+ }
+ }
+ }
+ },
+ "react": {
+ "version": "16.13.1",
+ "resolved": "https://registry.npmjs.org/react/-/react-16.13.1.tgz",
+ "integrity": "sha512-YMZQQq32xHLX0bz5Mnibv1/LHb3Sqzngu7xstSM+vrkE5Kzr9xE0yMByK5kMoTK30YVJE61WfbxIFFvfeDKT1w==",
+ "requires": {
+ "loose-envify": "^1.1.0",
+ "object-assign": "^4.1.1",
+ "prop-types": "^15.6.2"
+ }
+ },
+ "react-dom": {
+ "version": "16.13.1",
+ "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-16.13.1.tgz",
+ "integrity": "sha512-81PIMmVLnCNLO/fFOQxdQkvEq/+Hfpv24XNJfpyZhTRfO0QcmQIF/PgCa1zCOj2w1hrn12MFLyaJ/G0+Mxtfag==",
+ "requires": {
+ "loose-envify": "^1.1.0",
+ "object-assign": "^4.1.1",
+ "prop-types": "^15.6.2",
+ "scheduler": "^0.19.1"
+ },
+ "dependencies": {
+ "scheduler": {
+ "version": "0.19.1",
+ "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.19.1.tgz",
+ "integrity": "sha512-n/zwRWRYSUj0/3g/otKDRPMh6qv2SYMWNq85IEa8iZyAv8od9zDYpGSnpBEjNgcMNq6Scbu5KfIPxNF72R/2EA==",
+ "requires": {
+ "loose-envify": "^1.1.0",
+ "object-assign": "^4.1.1"
+ }
+ }
+ }
+ },
+ "react-is": {
+ "version": "16.12.0",
+ "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.12.0.tgz",
+ "integrity": "sha512-rPCkf/mWBtKc97aLL9/txD8DZdemK0vkA3JMLShjlJB3Pj3s+lpf1KaBzMfQrAmhMQB0n1cU/SUGgKKBCe837Q=="
+ },
+ "react-redux": {
+ "version": "7.2.0",
+ "resolved": "https://registry.npmjs.org/react-redux/-/react-redux-7.2.0.tgz",
+ "integrity": "sha512-EvCAZYGfOLqwV7gh849xy9/pt55rJXPwmYvI4lilPM5rUT/1NxuuN59ipdBksRVSvz0KInbPnp4IfoXJXCqiDA==",
+ "requires": {
+ "@babel/runtime": "^7.5.5",
+ "hoist-non-react-statics": "^3.3.0",
+ "loose-envify": "^1.4.0",
+ "prop-types": "^15.7.2",
+ "react-is": "^16.9.0"
+ }
+ },
+ "react-test-renderer": {
+ "version": "16.12.0",
+ "resolved": "https://registry.npmjs.org/react-test-renderer/-/react-test-renderer-16.12.0.tgz",
+ "integrity": "sha512-Vj/teSqt2oayaWxkbhQ6gKis+t5JrknXfPVo+aIJ8QwYAqMPH77uptOdrlphyxl8eQI/rtkOYg86i/UWkpFu0w==",
+ "dev": true,
+ "requires": {
+ "object-assign": "^4.1.1",
+ "prop-types": "^15.6.2",
+ "react-is": "^16.8.6",
+ "scheduler": "^0.18.0"
+ }
+ },
+ "react-transition-group": {
+ "version": "4.3.0",
+ "resolved": "https://registry.npmjs.org/react-transition-group/-/react-transition-group-4.3.0.tgz",
+ "integrity": "sha512-1qRV1ZuVSdxPlPf4O8t7inxUGpdyO5zG9IoNfJxSO0ImU2A1YWkEQvFPuIPZmMLkg5hYs7vv5mMOyfgSkvAwvw==",
+ "requires": {
+ "@babel/runtime": "^7.5.5",
+ "dom-helpers": "^5.0.1",
+ "loose-envify": "^1.4.0",
+ "prop-types": "^15.6.2"
+ }
+ },
+ "read-pkg": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-1.1.0.tgz",
+ "integrity": "sha1-9f+qXs0pyzHAR0vKfXVra7KePyg=",
+ "dev": true,
+ "requires": {
+ "load-json-file": "^1.0.0",
+ "normalize-package-data": "^2.3.2",
+ "path-type": "^1.0.0"
+ }
+ },
+ "read-pkg-up": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-1.0.1.tgz",
+ "integrity": "sha1-nWPBMnbAZZGNV/ACpX9AobZD+wI=",
+ "dev": true,
+ "requires": {
+ "find-up": "^1.0.0",
+ "read-pkg": "^1.0.0"
+ },
+ "dependencies": {
+ "find-up": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/find-up/-/find-up-1.1.2.tgz",
+ "integrity": "sha1-ay6YIrGizgpgq2TWEOzK1TyyTQ8=",
+ "dev": true,
+ "requires": {
+ "path-exists": "^2.0.0",
+ "pinkie-promise": "^2.0.0"
+ }
+ },
+ "path-exists": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-2.1.0.tgz",
+ "integrity": "sha1-D+tsZPD8UY2adU3V77YscCJ2H0s=",
+ "dev": true,
+ "requires": {
+ "pinkie-promise": "^2.0.0"
+ }
+ }
+ }
+ },
+ "readable-stream": {
+ "version": "2.3.7",
+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz",
+ "integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==",
+ "dev": true,
+ "requires": {
+ "core-util-is": "~1.0.0",
+ "inherits": "~2.0.3",
+ "isarray": "~1.0.0",
+ "process-nextick-args": "~2.0.0",
+ "safe-buffer": "~5.1.1",
+ "string_decoder": "~1.1.1",
+ "util-deprecate": "~1.0.1"
+ }
+ },
+ "readdirp": {
+ "version": "2.2.1",
+ "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-2.2.1.tgz",
+ "integrity": "sha512-1JU/8q+VgFZyxwrJ+SVIOsh+KywWGpds3NTqikiKpDMZWScmAYyKIgqkO+ARvNWJfXeXR1zxz7aHF4u4CyH6vQ==",
+ "dev": true,
+ "requires": {
+ "graceful-fs": "^4.1.11",
+ "micromatch": "^3.1.10",
+ "readable-stream": "^2.0.2"
+ },
+ "dependencies": {
+ "arr-diff": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-4.0.0.tgz",
+ "integrity": "sha1-1kYQdP6/7HHn4VI1dhoyml3HxSA=",
+ "dev": true
+ },
+ "array-unique": {
+ "version": "0.3.2",
+ "resolved": "https://registry.npmjs.org/array-unique/-/array-unique-0.3.2.tgz",
+ "integrity": "sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg=",
+ "dev": true
+ },
+ "braces": {
+ "version": "2.3.2",
+ "resolved": "https://registry.npmjs.org/braces/-/braces-2.3.2.tgz",
+ "integrity": "sha512-aNdbnj9P8PjdXU4ybaWLK2IF3jc/EoDYbC7AazW6to3TRsfXxscC9UXOB5iDiEQrkyIbWp2SLQda4+QAa7nc3w==",
+ "dev": true,
+ "requires": {
+ "arr-flatten": "^1.1.0",
+ "array-unique": "^0.3.2",
+ "extend-shallow": "^2.0.1",
+ "fill-range": "^4.0.0",
+ "isobject": "^3.0.1",
+ "repeat-element": "^1.1.2",
+ "snapdragon": "^0.8.1",
+ "snapdragon-node": "^2.0.1",
+ "split-string": "^3.0.2",
+ "to-regex": "^3.0.1"
+ },
+ "dependencies": {
+ "extend-shallow": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz",
+ "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=",
+ "dev": true,
+ "requires": {
+ "is-extendable": "^0.1.0"
+ }
+ }
+ }
+ },
+ "debug": {
+ "version": "2.6.9",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
+ "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
+ "dev": true,
+ "requires": {
+ "ms": "2.0.0"
+ }
+ },
+ "expand-brackets": {
+ "version": "2.1.4",
+ "resolved": "https://registry.npmjs.org/expand-brackets/-/expand-brackets-2.1.4.tgz",
+ "integrity": "sha1-t3c14xXOMPa27/D4OwQVGiJEliI=",
+ "dev": true,
+ "requires": {
+ "debug": "^2.3.3",
+ "define-property": "^0.2.5",
+ "extend-shallow": "^2.0.1",
+ "posix-character-classes": "^0.1.0",
+ "regex-not": "^1.0.0",
+ "snapdragon": "^0.8.1",
+ "to-regex": "^3.0.1"
+ },
+ "dependencies": {
+ "define-property": {
+ "version": "0.2.5",
+ "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz",
+ "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=",
+ "dev": true,
+ "requires": {
+ "is-descriptor": "^0.1.0"
+ }
+ },
+ "extend-shallow": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz",
+ "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=",
+ "dev": true,
+ "requires": {
+ "is-extendable": "^0.1.0"
+ }
+ },
+ "is-accessor-descriptor": {
+ "version": "0.1.6",
+ "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz",
+ "integrity": "sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=",
+ "dev": true,
+ "requires": {
+ "kind-of": "^3.0.2"
+ },
+ "dependencies": {
+ "kind-of": {
+ "version": "3.2.2",
+ "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz",
+ "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=",
+ "dev": true,
+ "requires": {
+ "is-buffer": "^1.1.5"
+ }
+ }
+ }
+ },
+ "is-data-descriptor": {
+ "version": "0.1.4",
+ "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz",
+ "integrity": "sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=",
+ "dev": true,
+ "requires": {
+ "kind-of": "^3.0.2"
+ },
+ "dependencies": {
+ "kind-of": {
+ "version": "3.2.2",
+ "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz",
+ "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=",
+ "dev": true,
+ "requires": {
+ "is-buffer": "^1.1.5"
+ }
+ }
+ }
+ },
+ "is-descriptor": {
+ "version": "0.1.6",
+ "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-0.1.6.tgz",
+ "integrity": "sha512-avDYr0SB3DwO9zsMov0gKCESFYqCnE4hq/4z3TdUlukEy5t9C0YRq7HLrsN52NAcqXKaepeCD0n+B0arnVG3Hg==",
+ "dev": true,
+ "requires": {
+ "is-accessor-descriptor": "^0.1.6",
+ "is-data-descriptor": "^0.1.4",
+ "kind-of": "^5.0.0"
+ }
+ },
+ "kind-of": {
+ "version": "5.1.0",
+ "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-5.1.0.tgz",
+ "integrity": "sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw==",
+ "dev": true
+ }
+ }
+ },
+ "extglob": {
+ "version": "2.0.4",
+ "resolved": "https://registry.npmjs.org/extglob/-/extglob-2.0.4.tgz",
+ "integrity": "sha512-Nmb6QXkELsuBr24CJSkilo6UHHgbekK5UiZgfE6UHD3Eb27YC6oD+bhcT+tJ6cl8dmsgdQxnWlcry8ksBIBLpw==",
+ "dev": true,
+ "requires": {
+ "array-unique": "^0.3.2",
+ "define-property": "^1.0.0",
+ "expand-brackets": "^2.1.4",
+ "extend-shallow": "^2.0.1",
+ "fragment-cache": "^0.2.1",
+ "regex-not": "^1.0.0",
+ "snapdragon": "^0.8.1",
+ "to-regex": "^3.0.1"
+ },
+ "dependencies": {
+ "define-property": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/define-property/-/define-property-1.0.0.tgz",
+ "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=",
+ "dev": true,
+ "requires": {
+ "is-descriptor": "^1.0.0"
+ }
+ },
+ "extend-shallow": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz",
+ "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=",
+ "dev": true,
+ "requires": {
+ "is-extendable": "^0.1.0"
+ }
+ }
+ }
+ },
+ "fill-range": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-4.0.0.tgz",
+ "integrity": "sha1-1USBHUKPmOsGpj3EAtJAPDKMOPc=",
+ "dev": true,
+ "requires": {
+ "extend-shallow": "^2.0.1",
+ "is-number": "^3.0.0",
+ "repeat-string": "^1.6.1",
+ "to-regex-range": "^2.1.0"
+ },
+ "dependencies": {
+ "extend-shallow": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz",
+ "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=",
+ "dev": true,
+ "requires": {
+ "is-extendable": "^0.1.0"
+ }
+ }
+ }
+ },
+ "is-accessor-descriptor": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz",
+ "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==",
+ "dev": true,
+ "requires": {
+ "kind-of": "^6.0.0"
+ }
+ },
+ "is-data-descriptor": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz",
+ "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==",
+ "dev": true,
+ "requires": {
+ "kind-of": "^6.0.0"
+ }
+ },
+ "is-descriptor": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz",
+ "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==",
+ "dev": true,
+ "requires": {
+ "is-accessor-descriptor": "^1.0.0",
+ "is-data-descriptor": "^1.0.0",
+ "kind-of": "^6.0.2"
+ }
+ },
+ "is-number": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/is-number/-/is-number-3.0.0.tgz",
+ "integrity": "sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=",
+ "dev": true,
+ "requires": {
+ "kind-of": "^3.0.2"
+ },
+ "dependencies": {
+ "kind-of": {
+ "version": "3.2.2",
+ "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz",
+ "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=",
+ "dev": true,
+ "requires": {
+ "is-buffer": "^1.1.5"
+ }
+ }
+ }
+ },
+ "isobject": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz",
+ "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=",
+ "dev": true
+ },
+ "kind-of": {
+ "version": "6.0.3",
+ "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz",
+ "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==",
+ "dev": true
+ },
+ "micromatch": {
+ "version": "3.1.10",
+ "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-3.1.10.tgz",
+ "integrity": "sha512-MWikgl9n9M3w+bpsY3He8L+w9eF9338xRl8IAO5viDizwSzziFEyUzo2xrrloB64ADbTf8uA8vRqqttDTOmccg==",
+ "dev": true,
+ "requires": {
+ "arr-diff": "^4.0.0",
+ "array-unique": "^0.3.2",
+ "braces": "^2.3.1",
+ "define-property": "^2.0.2",
+ "extend-shallow": "^3.0.2",
+ "extglob": "^2.0.4",
+ "fragment-cache": "^0.2.1",
+ "kind-of": "^6.0.2",
+ "nanomatch": "^1.2.9",
+ "object.pick": "^1.3.0",
+ "regex-not": "^1.0.0",
+ "snapdragon": "^0.8.1",
+ "to-regex": "^3.0.2"
+ }
+ },
+ "ms": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
+ "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=",
+ "dev": true
+ }
+ }
+ },
+ "readline2": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/readline2/-/readline2-1.0.1.tgz",
+ "integrity": "sha1-QQWWCP/BVHV7cV2ZidGZ/783LjU=",
+ "dev": true,
+ "requires": {
+ "code-point-at": "^1.0.0",
+ "is-fullwidth-code-point": "^1.0.0",
+ "mute-stream": "0.0.5"
+ },
+ "dependencies": {
+ "is-fullwidth-code-point": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz",
+ "integrity": "sha1-754xOG8DGn8NZDr4L95QxFfvAMs=",
+ "dev": true,
+ "requires": {
+ "number-is-nan": "^1.0.0"
+ }
+ }
+ }
+ },
+ "rechoir": {
+ "version": "0.6.2",
+ "resolved": "https://registry.npmjs.org/rechoir/-/rechoir-0.6.2.tgz",
+ "integrity": "sha1-hSBLVNuoLVdC4oyWdW70OvUOM4Q=",
+ "dev": true,
+ "requires": {
+ "resolve": "^1.1.6"
+ }
+ },
+ "redent": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/redent/-/redent-1.0.0.tgz",
+ "integrity": "sha1-z5Fqsf1fHxbfsggi3W7H9zDCr94=",
+ "dev": true,
+ "requires": {
+ "indent-string": "^2.1.0",
+ "strip-indent": "^1.0.1"
+ }
+ },
+ "redux": {
+ "version": "4.0.5",
+ "resolved": "https://registry.npmjs.org/redux/-/redux-4.0.5.tgz",
+ "integrity": "sha512-VSz1uMAH24DM6MF72vcojpYPtrTUu3ByVWfPL1nPfVRb5mZVTve5GnNCUV53QM/BZ66xfWrm0CTWoM+Xlz8V1w==",
+ "requires": {
+ "loose-envify": "^1.4.0",
+ "symbol-observable": "^1.2.0"
+ }
+ },
+ "reflect.ownkeys": {
+ "version": "0.2.0",
+ "resolved": "https://registry.npmjs.org/reflect.ownkeys/-/reflect.ownkeys-0.2.0.tgz",
+ "integrity": "sha1-dJrO7H8/34tj+SegSAnpDFwLNGA=",
+ "dev": true
+ },
+ "regenerator-runtime": {
+ "version": "0.13.3",
+ "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.3.tgz",
+ "integrity": "sha512-naKIZz2GQ8JWh///G7L3X6LaQUAMp2lvb1rvwwsURe/VXwD6VMfr+/1NuNw3ag8v2kY1aQ/go5SNn79O9JU7yw=="
+ },
+ "regex-cache": {
+ "version": "0.4.4",
+ "resolved": "https://registry.npmjs.org/regex-cache/-/regex-cache-0.4.4.tgz",
+ "integrity": "sha512-nVIZwtCjkC9YgvWkpM55B5rBhBYRZhAaJbgcFYXXsHnbZ9UZI9nnVWYZpBlCqv9ho2eZryPnWrZGsOdPwVWXWQ==",
+ "dev": true,
+ "requires": {
+ "is-equal-shallow": "^0.1.3"
+ }
+ },
+ "regex-not": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/regex-not/-/regex-not-1.0.2.tgz",
+ "integrity": "sha512-J6SDjUgDxQj5NusnOtdFxDwN/+HWykR8GELwctJ7mdqhcyy1xEc4SRFHUXvxTp661YaVKAjfRLZ9cCqS6tn32A==",
+ "dev": true,
+ "requires": {
+ "extend-shallow": "^3.0.2",
+ "safe-regex": "^1.1.0"
+ }
+ },
+ "remove-trailing-separator": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/remove-trailing-separator/-/remove-trailing-separator-1.1.0.tgz",
+ "integrity": "sha1-wkvOKig62tW8P1jg1IJJuSN52O8=",
+ "dev": true
+ },
+ "repeat-element": {
+ "version": "1.1.3",
+ "resolved": "https://registry.npmjs.org/repeat-element/-/repeat-element-1.1.3.tgz",
+ "integrity": "sha512-ahGq0ZnV5m5XtZLMb+vP76kcAM5nkLqk0lpqAuojSKGgQtn4eRi4ZZGm2olo2zKFH+sMsWaqOCW1dqAnOru72g==",
+ "dev": true
+ },
+ "repeat-string": {
+ "version": "1.6.1",
+ "resolved": "https://registry.npmjs.org/repeat-string/-/repeat-string-1.6.1.tgz",
+ "integrity": "sha1-jcrkcOHIirwtYA//Sndihtp15jc=",
+ "dev": true
+ },
+ "repeating": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/repeating/-/repeating-2.0.1.tgz",
+ "integrity": "sha1-UhTFOpJtNVJwdSf7q0FdvAjQbdo=",
+ "dev": true,
+ "requires": {
+ "is-finite": "^1.0.0"
+ }
+ },
+ "request": {
+ "version": "2.88.2",
+ "resolved": "https://registry.npmjs.org/request/-/request-2.88.2.tgz",
+ "integrity": "sha512-MsvtOrfG9ZcrOwAW+Qi+F6HbD0CWXEh9ou77uOb7FM2WPhwT7smM833PzanhJLsgXjN89Ir6V2PczXNnMpwKhw==",
+ "dev": true,
+ "requires": {
+ "aws-sign2": "~0.7.0",
+ "aws4": "^1.8.0",
+ "caseless": "~0.12.0",
+ "combined-stream": "~1.0.6",
+ "extend": "~3.0.2",
+ "forever-agent": "~0.6.1",
+ "form-data": "~2.3.2",
+ "har-validator": "~5.1.3",
+ "http-signature": "~1.2.0",
+ "is-typedarray": "~1.0.0",
+ "isstream": "~0.1.2",
+ "json-stringify-safe": "~5.0.1",
+ "mime-types": "~2.1.19",
+ "oauth-sign": "~0.9.0",
+ "performance-now": "^2.1.0",
+ "qs": "~6.5.2",
+ "safe-buffer": "^5.1.2",
+ "tough-cookie": "~2.5.0",
+ "tunnel-agent": "^0.6.0",
+ "uuid": "^3.3.2"
+ },
+ "dependencies": {
+ "qs": {
+ "version": "6.5.2",
+ "resolved": "https://registry.npmjs.org/qs/-/qs-6.5.2.tgz",
+ "integrity": "sha512-N5ZAX4/LxJmF+7wN74pUD6qAh9/wnvdQcjq9TZjevvXzSUo7bfmw91saqMjzGS2xq91/odN2dW/WOl7qQHNDGA==",
+ "dev": true
+ }
+ }
+ },
+ "require-directory": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",
+ "integrity": "sha1-jGStX9MNqxyXbiNE/+f3kqam30I=",
+ "dev": true
+ },
+ "require-main-filename": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz",
+ "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==",
+ "dev": true
+ },
+ "require-uncached": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/require-uncached/-/require-uncached-1.0.3.tgz",
+ "integrity": "sha1-Tg1W1slmL9MeQwEcS5WqSZVUIdM=",
+ "dev": true,
+ "requires": {
+ "caller-path": "^0.1.0",
+ "resolve-from": "^1.0.0"
+ }
+ },
+ "requires-port": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz",
+ "integrity": "sha1-kl0mAdOaxIXgkc8NpcbmlNw9yv8=",
+ "dev": true
+ },
+ "reselect": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/reselect/-/reselect-4.0.0.tgz",
+ "integrity": "sha512-qUgANli03jjAyGlnbYVAV5vvnOmJnODyABz51RdBN7M4WaVu8mecZWgyQNkG8Yqe3KRGRt0l4K4B3XVEULC4CA=="
+ },
+ "resolve": {
+ "version": "1.15.1",
+ "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.15.1.tgz",
+ "integrity": "sha512-84oo6ZTtoTUpjgNEr5SJyzQhzL72gaRodsSfyxC/AXRvwu0Yse9H8eF9IpGo7b8YetZhlI6v7ZQ6bKBFV/6S7w==",
+ "dev": true,
+ "requires": {
+ "path-parse": "^1.0.6"
+ }
+ },
+ "resolve-cwd": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/resolve-cwd/-/resolve-cwd-2.0.0.tgz",
+ "integrity": "sha1-AKn3OHVW4nA46uIyyqNypqWbZlo=",
+ "dev": true,
+ "requires": {
+ "resolve-from": "^3.0.0"
+ },
+ "dependencies": {
+ "resolve-from": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-3.0.0.tgz",
+ "integrity": "sha1-six699nWiBvItuZTM17rywoYh0g=",
+ "dev": true
+ }
+ }
+ },
+ "resolve-dir": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/resolve-dir/-/resolve-dir-1.0.1.tgz",
+ "integrity": "sha1-eaQGRMNivoLybv/nOcm7U4IEb0M=",
+ "dev": true,
+ "requires": {
+ "expand-tilde": "^2.0.0",
+ "global-modules": "^1.0.0"
+ },
+ "dependencies": {
+ "global-modules": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/global-modules/-/global-modules-1.0.0.tgz",
+ "integrity": "sha512-sKzpEkf11GpOFuw0Zzjzmt4B4UZwjOcG757PPvrfhxcLFbq0wpsgpOqxpxtxFiCG4DtG93M6XRVbF2oGdev7bg==",
+ "dev": true,
+ "requires": {
+ "global-prefix": "^1.0.1",
+ "is-windows": "^1.0.1",
+ "resolve-dir": "^1.0.0"
+ }
+ }
+ }
+ },
+ "resolve-from": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-1.0.1.tgz",
+ "integrity": "sha1-Jsv+k10a7uq7Kbw/5a6wHpPUQiY=",
+ "dev": true
+ },
+ "resolve-url": {
+ "version": "0.2.1",
+ "resolved": "https://registry.npmjs.org/resolve-url/-/resolve-url-0.2.1.tgz",
+ "integrity": "sha1-LGN/53yJOv0qZj/iGqkIAGjiBSo=",
+ "dev": true
+ },
+ "restore-cursor": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-1.0.1.tgz",
+ "integrity": "sha1-NGYfRohjJ/7SmRR5FSJS35LapUE=",
+ "dev": true,
+ "requires": {
+ "exit-hook": "^1.0.0",
+ "onetime": "^1.0.0"
+ }
+ },
+ "ret": {
+ "version": "0.1.15",
+ "resolved": "https://registry.npmjs.org/ret/-/ret-0.1.15.tgz",
+ "integrity": "sha512-TTlYpa+OL+vMMNG24xSlQGEJ3B/RzEfUlLct7b5G/ytav+wPrplCpVMFuwzXbkecJrb6IYo1iFb0S9v37754mg==",
+ "dev": true
+ },
+ "rfdc": {
+ "version": "1.1.4",
+ "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.1.4.tgz",
+ "integrity": "sha512-5C9HXdzK8EAqN7JDif30jqsBzavB7wLpaubisuQIGHWf2gUXSpzy6ArX/+Da8RjFpagWsCn+pIgxTMAmKw9Zug==",
+ "dev": true
+ },
+ "rimraf": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz",
+ "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==",
+ "dev": true,
+ "requires": {
+ "glob": "^7.1.3"
+ }
+ },
+ "ripemd160": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/ripemd160/-/ripemd160-2.0.2.tgz",
+ "integrity": "sha512-ii4iagi25WusVoiC4B4lq7pbXfAp3D9v5CwfkY33vffw2+pkDjY1D8GaN7spsxvCSx8dkPqOZCEZyfxcmJG2IA==",
+ "dev": true,
+ "requires": {
+ "hash-base": "^3.0.0",
+ "inherits": "^2.0.1"
+ }
+ },
+ "rst-selector-parser": {
+ "version": "2.2.3",
+ "resolved": "https://registry.npmjs.org/rst-selector-parser/-/rst-selector-parser-2.2.3.tgz",
+ "integrity": "sha1-gbIw6i/MYGbInjRy3nlChdmwPZE=",
+ "dev": true,
+ "requires": {
+ "lodash.flattendeep": "^4.4.0",
+ "nearley": "^2.7.10"
+ }
+ },
+ "run-async": {
+ "version": "0.1.0",
+ "resolved": "https://registry.npmjs.org/run-async/-/run-async-0.1.0.tgz",
+ "integrity": "sha1-yK1KXhEGYeQCp9IbUw4AnyX444k=",
+ "dev": true,
+ "requires": {
+ "once": "^1.3.0"
+ }
+ },
+ "run-queue": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/run-queue/-/run-queue-1.0.3.tgz",
+ "integrity": "sha1-6Eg5bwV9Ij8kOGkkYY4laUFh7Ec=",
+ "dev": true,
+ "requires": {
+ "aproba": "^1.1.1"
+ }
+ },
+ "rx-lite": {
+ "version": "3.1.2",
+ "resolved": "https://registry.npmjs.org/rx-lite/-/rx-lite-3.1.2.tgz",
+ "integrity": "sha1-Gc5QLKVyZl87ZHsQk5+X/RYV8QI=",
+ "dev": true
+ },
+ "safe-buffer": {
+ "version": "5.1.2",
+ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
+ "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",
+ "dev": true
+ },
+ "safe-regex": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/safe-regex/-/safe-regex-1.1.0.tgz",
+ "integrity": "sha1-QKNmnzsHfR6UPURinhV91IAjvy4=",
+ "dev": true,
+ "requires": {
+ "ret": "~0.1.10"
+ }
+ },
+ "safer-buffer": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
+ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
+ "dev": true
+ },
+ "sass": {
+ "version": "1.25.0",
+ "resolved": "https://registry.npmjs.org/sass/-/sass-1.25.0.tgz",
+ "integrity": "sha512-uQMjye0Y70SEDGO56n0j91tauqS9E1BmpKHtiYNQScXDHeaE9uHwNEqQNFf4Bes/3DHMNinB6u79JsG10XWNyw==",
+ "dev": true,
+ "requires": {
+ "chokidar": ">=2.0.0 <4.0.0"
+ },
+ "dependencies": {
+ "anymatch": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.1.tgz",
+ "integrity": "sha512-mM8522psRCqzV+6LhomX5wgp25YVibjh8Wj23I5RPkPppSVSjyKD2A2mBJmWGa+KN7f2D6LNh9jkBCeyLktzjg==",
+ "dev": true,
+ "requires": {
+ "normalize-path": "^3.0.0",
+ "picomatch": "^2.0.4"
+ }
+ },
+ "binary-extensions": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.0.0.tgz",
+ "integrity": "sha512-Phlt0plgpIIBOGTT/ehfFnbNlfsDEiqmzE2KRXoX1bLIlir4X/MR+zSyBEkL05ffWgnRSf/DXv+WrUAVr93/ow==",
+ "dev": true
+ },
+ "braces": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz",
+ "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==",
+ "dev": true,
+ "requires": {
+ "fill-range": "^7.0.1"
+ }
+ },
+ "chokidar": {
+ "version": "3.3.1",
+ "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.3.1.tgz",
+ "integrity": "sha512-4QYCEWOcK3OJrxwvyyAOxFuhpvOVCYkr33LPfFNBjAD/w3sEzWsp2BUOkI4l9bHvWioAd0rc6NlHUOEaWkTeqg==",
+ "dev": true,
+ "requires": {
+ "anymatch": "~3.1.1",
+ "braces": "~3.0.2",
+ "fsevents": "~2.1.2",
+ "glob-parent": "~5.1.0",
+ "is-binary-path": "~2.1.0",
+ "is-glob": "~4.0.1",
+ "normalize-path": "~3.0.0",
+ "readdirp": "~3.3.0"
+ }
+ },
+ "fill-range": {
+ "version": "7.0.1",
+ "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz",
+ "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==",
+ "dev": true,
+ "requires": {
+ "to-regex-range": "^5.0.1"
+ }
+ },
+ "fsevents": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.1.2.tgz",
+ "integrity": "sha512-R4wDiBwZ0KzpgOWetKDug1FZcYhqYnUYKtfZYt4mD5SBz76q0KR4Q9o7GIPamsVPGmW3EYPPJ0dOOjvx32ldZA==",
+ "dev": true,
+ "optional": true
+ },
+ "glob-parent": {
+ "version": "5.1.0",
+ "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.0.tgz",
+ "integrity": "sha512-qjtRgnIVmOfnKUE3NJAQEdk+lKrxfw8t5ke7SXtfMTHcjsBfOfWXCQfdb30zfDoZQ2IRSIiidmjtbHZPZ++Ihw==",
+ "dev": true,
+ "requires": {
+ "is-glob": "^4.0.1"
+ }
+ },
+ "is-binary-path": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz",
+ "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==",
+ "dev": true,
+ "requires": {
+ "binary-extensions": "^2.0.0"
+ }
+ },
+ "is-extglob": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",
+ "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=",
+ "dev": true
+ },
+ "is-glob": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.1.tgz",
+ "integrity": "sha512-5G0tKtBTFImOqDnLB2hG6Bp2qcKEFduo4tZu9MT/H6NQv/ghhy30o55ufafxJ/LdH79LLs2Kfrn85TLKyA7BUg==",
+ "dev": true,
+ "requires": {
+ "is-extglob": "^2.1.1"
+ }
+ },
+ "is-number": {
+ "version": "7.0.0",
+ "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz",
+ "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==",
+ "dev": true
+ },
+ "normalize-path": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz",
+ "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==",
+ "dev": true
+ },
+ "readdirp": {
+ "version": "3.3.0",
+ "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.3.0.tgz",
+ "integrity": "sha512-zz0pAkSPOXXm1viEwygWIPSPkcBYjW1xU5j/JBh5t9bGCJwa6f9+BJa6VaB2g+b55yVrmXzqkyLf4xaWYM0IkQ==",
+ "dev": true,
+ "requires": {
+ "picomatch": "^2.0.7"
+ }
+ },
+ "to-regex-range": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",
+ "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==",
+ "dev": true,
+ "requires": {
+ "is-number": "^7.0.0"
+ }
+ }
+ }
+ },
+ "sass-graph": {
+ "version": "2.2.4",
+ "resolved": "https://registry.npmjs.org/sass-graph/-/sass-graph-2.2.4.tgz",
+ "integrity": "sha1-E/vWPNHK8JCLn9k0dq1DpR0eC0k=",
+ "dev": true,
+ "requires": {
+ "glob": "^7.0.0",
+ "lodash": "^4.0.0",
+ "scss-tokenizer": "^0.2.3",
+ "yargs": "^7.0.0"
+ },
+ "dependencies": {
+ "camelcase": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-3.0.0.tgz",
+ "integrity": "sha1-MvxLn82vhF/N9+c7uXysImHwqwo=",
+ "dev": true
+ },
+ "cliui": {
+ "version": "3.2.0",
+ "resolved": "https://registry.npmjs.org/cliui/-/cliui-3.2.0.tgz",
+ "integrity": "sha1-EgYBU3qRbSmUD5NNo7SNWFo5IT0=",
+ "dev": true,
+ "requires": {
+ "string-width": "^1.0.1",
+ "strip-ansi": "^3.0.1",
+ "wrap-ansi": "^2.0.0"
+ }
+ },
+ "get-caller-file": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-1.0.3.tgz",
+ "integrity": "sha512-3t6rVToeoZfYSGd8YoLFR2DJkiQrIiUrGcjvFX2mDw3bn6k2OtwHN0TNCLbBO+w8qTvimhDkv+LSscbJY1vE6w==",
+ "dev": true
+ },
+ "is-fullwidth-code-point": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz",
+ "integrity": "sha1-754xOG8DGn8NZDr4L95QxFfvAMs=",
+ "dev": true,
+ "requires": {
+ "number-is-nan": "^1.0.0"
+ }
+ },
+ "require-main-filename": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-1.0.1.tgz",
+ "integrity": "sha1-l/cXtp1IeE9fUmpsWqj/3aBVpNE=",
+ "dev": true
+ },
+ "string-width": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-1.0.2.tgz",
+ "integrity": "sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=",
+ "dev": true,
+ "requires": {
+ "code-point-at": "^1.0.0",
+ "is-fullwidth-code-point": "^1.0.0",
+ "strip-ansi": "^3.0.0"
+ }
+ },
+ "which-module": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/which-module/-/which-module-1.0.0.tgz",
+ "integrity": "sha1-u6Y8qGGUiZT/MHc2CJ47lgJsKk8=",
+ "dev": true
+ },
+ "wrap-ansi": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-2.1.0.tgz",
+ "integrity": "sha1-2Pw9KE3QV5T+hJc8rs3Rz4JP3YU=",
+ "dev": true,
+ "requires": {
+ "string-width": "^1.0.1",
+ "strip-ansi": "^3.0.1"
+ }
+ },
+ "y18n": {
+ "version": "3.2.1",
+ "resolved": "https://registry.npmjs.org/y18n/-/y18n-3.2.1.tgz",
+ "integrity": "sha1-bRX7qITAhnnA136I53WegR4H+kE=",
+ "dev": true
+ },
+ "yargs": {
+ "version": "7.1.0",
+ "resolved": "https://registry.npmjs.org/yargs/-/yargs-7.1.0.tgz",
+ "integrity": "sha1-a6MY6xaWFyf10oT46gA+jWFU0Mg=",
+ "dev": true,
+ "requires": {
+ "camelcase": "^3.0.0",
+ "cliui": "^3.2.0",
+ "decamelize": "^1.1.1",
+ "get-caller-file": "^1.0.1",
+ "os-locale": "^1.4.0",
+ "read-pkg-up": "^1.0.1",
+ "require-directory": "^2.1.1",
+ "require-main-filename": "^1.0.1",
+ "set-blocking": "^2.0.0",
+ "string-width": "^1.0.2",
+ "which-module": "^1.0.0",
+ "y18n": "^3.2.1",
+ "yargs-parser": "^5.0.0"
+ }
+ },
+ "yargs-parser": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-5.0.0.tgz",
+ "integrity": "sha1-J17PDX/+Bcd+ZOfIbkzZS/DhIoo=",
+ "dev": true,
+ "requires": {
+ "camelcase": "^3.0.0"
+ }
+ }
+ }
+ },
+ "sass-lint": {
+ "version": "1.13.1",
+ "resolved": "https://registry.npmjs.org/sass-lint/-/sass-lint-1.13.1.tgz",
+ "integrity": "sha512-DSyah8/MyjzW2BWYmQWekYEKir44BpLqrCFsgs9iaWiVTcwZfwXHF586hh3D1n+/9ihUNMfd8iHAyb9KkGgs7Q==",
+ "dev": true,
+ "requires": {
+ "commander": "^2.8.1",
+ "eslint": "^2.7.0",
+ "front-matter": "2.1.2",
+ "fs-extra": "^3.0.1",
+ "glob": "^7.0.0",
+ "globule": "^1.0.0",
+ "gonzales-pe-sl": "^4.2.3",
+ "js-yaml": "^3.5.4",
+ "known-css-properties": "^0.3.0",
+ "lodash.capitalize": "^4.1.0",
+ "lodash.kebabcase": "^4.0.0",
+ "merge": "^1.2.0",
+ "path-is-absolute": "^1.0.0",
+ "util": "^0.10.3"
+ },
+ "dependencies": {
+ "fs-extra": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-3.0.1.tgz",
+ "integrity": "sha1-N5TzeMWLNC6n27sjCVEJxLO2IpE=",
+ "dev": true,
+ "requires": {
+ "graceful-fs": "^4.1.2",
+ "jsonfile": "^3.0.0",
+ "universalify": "^0.1.0"
+ }
+ },
+ "jsonfile": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-3.0.1.tgz",
+ "integrity": "sha1-pezG9l9T9mLEQVx2daAzHQmS7GY=",
+ "dev": true,
+ "requires": {
+ "graceful-fs": "^4.1.6"
+ }
+ }
+ }
+ },
+ "scheduler": {
+ "version": "0.18.0",
+ "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.18.0.tgz",
+ "integrity": "sha512-agTSHR1Nbfi6ulI0kYNK0203joW2Y5W4po4l+v03tOoiJKpTBbxpNhWDvqc/4IcOw+KLmSiQLTasZ4cab2/UWQ==",
+ "dev": true,
+ "requires": {
+ "loose-envify": "^1.1.0",
+ "object-assign": "^4.1.1"
+ }
+ },
+ "schema-utils": {
+ "version": "0.3.0",
+ "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-0.3.0.tgz",
+ "integrity": "sha1-9YdyIs4+kx7a4DnxfrNxbnE3+M8=",
+ "dev": true,
+ "requires": {
+ "ajv": "^5.0.0"
+ }
+ },
+ "scss-tokenizer": {
+ "version": "0.2.3",
+ "resolved": "https://registry.npmjs.org/scss-tokenizer/-/scss-tokenizer-0.2.3.tgz",
+ "integrity": "sha1-jrBtualyMzOCTT9VMGQRSYR85dE=",
+ "dev": true,
+ "requires": {
+ "js-base64": "^2.1.8",
+ "source-map": "^0.4.2"
+ },
+ "dependencies": {
+ "source-map": {
+ "version": "0.4.4",
+ "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.4.4.tgz",
+ "integrity": "sha1-66T12pwNyZneaAMti092FzZSA2s=",
+ "dev": true,
+ "requires": {
+ "amdefine": ">=0.0.4"
+ }
+ }
+ }
+ },
+ "semver": {
+ "version": "5.7.1",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz",
+ "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==",
+ "dev": true
+ },
+ "serialize-javascript": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-2.1.2.tgz",
+ "integrity": "sha512-rs9OggEUF0V4jUSecXazOYsLfu7OGK2qIn3c7IPBiffz32XniEp/TX9Xmc9LQfK2nQ2QKHvZ2oygKUGU0lG4jQ==",
+ "dev": true
+ },
+ "set-blocking": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz",
+ "integrity": "sha1-BF+XgtARrppoA93TgrJDkrPYkPc=",
+ "dev": true
+ },
+ "set-value": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/set-value/-/set-value-2.0.1.tgz",
+ "integrity": "sha512-JxHc1weCN68wRY0fhCoXpyK55m/XPHafOmK4UWD7m2CI14GMcFypt4w/0+NV5f/ZMby2F6S2wwA7fgynh9gWSw==",
+ "dev": true,
+ "requires": {
+ "extend-shallow": "^2.0.1",
+ "is-extendable": "^0.1.1",
+ "is-plain-object": "^2.0.3",
+ "split-string": "^3.0.1"
+ },
+ "dependencies": {
+ "extend-shallow": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz",
+ "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=",
+ "dev": true,
+ "requires": {
+ "is-extendable": "^0.1.0"
+ }
+ }
+ }
+ },
+ "setimmediate": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz",
+ "integrity": "sha1-KQy7Iy4waULX1+qbg3Mqt4VvgoU=",
+ "dev": true
+ },
+ "setprototypeof": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.1.tgz",
+ "integrity": "sha512-JvdAWfbXeIGaZ9cILp38HntZSFSo3mWg6xGcJJsd+d4aRMOqauag1C63dJfDw7OaMYwEbHMOxEZ1lqVRYP2OAw==",
+ "dev": true
+ },
+ "sha.js": {
+ "version": "2.4.11",
+ "resolved": "https://registry.npmjs.org/sha.js/-/sha.js-2.4.11.tgz",
+ "integrity": "sha512-QMEp5B7cftE7APOjk5Y6xgrbWu+WkLVQwk8JNjZ8nKRciZaByEW6MubieAiToS7+dwvrjGhH8jRXz3MVd0AYqQ==",
+ "dev": true,
+ "requires": {
+ "inherits": "^2.0.1",
+ "safe-buffer": "^5.0.1"
+ }
+ },
+ "shallow-clone": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/shallow-clone/-/shallow-clone-3.0.1.tgz",
+ "integrity": "sha512-/6KqX+GVUdqPuPPd2LxDDxzX6CAbjJehAAOKlNpqqUpAqPM6HeL8f+o3a+JsyGjn2lv0WY8UsTgUJjU9Ok55NA==",
+ "dev": true,
+ "requires": {
+ "kind-of": "^6.0.2"
+ },
+ "dependencies": {
+ "kind-of": {
+ "version": "6.0.3",
+ "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz",
+ "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==",
+ "dev": true
+ }
+ }
+ },
+ "shebang-command": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-1.2.0.tgz",
+ "integrity": "sha1-RKrGW2lbAzmJaMOfNj/uXer98eo=",
+ "dev": true,
+ "requires": {
+ "shebang-regex": "^1.0.0"
+ }
+ },
+ "shebang-regex": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-1.0.0.tgz",
+ "integrity": "sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM=",
+ "dev": true
+ },
+ "shell-quote": {
+ "version": "1.7.2",
+ "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.7.2.tgz",
+ "integrity": "sha512-mRz/m/JVscCrkMyPqHc/bczi3OQHkLTqXHEFu0zDhK/qfv3UcOA4SVmRCLmos4bhjr9ekVQubj/R7waKapmiQg==",
+ "dev": true
+ },
+ "shelljs": {
+ "version": "0.8.3",
+ "resolved": "https://registry.npmjs.org/shelljs/-/shelljs-0.8.3.tgz",
+ "integrity": "sha512-fc0BKlAWiLpwZljmOvAOTE/gXawtCoNrP5oaY7KIaQbbyHeQVg01pSEuEGvGh3HEdBU4baCD7wQBwADmM/7f7A==",
+ "dev": true,
+ "requires": {
+ "glob": "^7.0.0",
+ "interpret": "^1.0.0",
+ "rechoir": "^0.6.2"
+ }
+ },
+ "signal-exit": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.2.tgz",
+ "integrity": "sha1-tf3AjxKH6hF4Yo5BXiUTK3NkbG0=",
+ "dev": true
+ },
+ "sinon": {
+ "version": "7.3.2",
+ "resolved": "https://registry.npmjs.org/sinon/-/sinon-7.3.2.tgz",
+ "integrity": "sha512-thErC1z64BeyGiPvF8aoSg0LEnptSaWE7YhdWWbWXgelOyThent7uKOnnEh9zBxDbKixtr5dEko+ws1sZMuFMA==",
+ "dev": true,
+ "requires": {
+ "@sinonjs/commons": "^1.4.0",
+ "@sinonjs/formatio": "^3.2.1",
+ "@sinonjs/samsam": "^3.3.1",
+ "diff": "^3.5.0",
+ "lolex": "^4.0.1",
+ "nise": "^1.4.10",
+ "supports-color": "^5.5.0"
+ }
+ },
+ "slice-ansi": {
+ "version": "0.0.4",
+ "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-0.0.4.tgz",
+ "integrity": "sha1-7b+JA/ZvfOL46v1s7tZeJkyDGzU=",
+ "dev": true
+ },
+ "snapdragon": {
+ "version": "0.8.2",
+ "resolved": "https://registry.npmjs.org/snapdragon/-/snapdragon-0.8.2.tgz",
+ "integrity": "sha512-FtyOnWN/wCHTVXOMwvSv26d+ko5vWlIDD6zoUJ7LW8vh+ZBC8QdljveRP+crNrtBwioEUWy/4dMtbBjA4ioNlg==",
+ "dev": true,
+ "requires": {
+ "base": "^0.11.1",
+ "debug": "^2.2.0",
+ "define-property": "^0.2.5",
+ "extend-shallow": "^2.0.1",
+ "map-cache": "^0.2.2",
+ "source-map": "^0.5.6",
+ "source-map-resolve": "^0.5.0",
+ "use": "^3.1.0"
+ },
+ "dependencies": {
+ "debug": {
+ "version": "2.6.9",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
+ "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
+ "dev": true,
+ "requires": {
+ "ms": "2.0.0"
+ }
+ },
+ "define-property": {
+ "version": "0.2.5",
+ "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz",
+ "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=",
+ "dev": true,
+ "requires": {
+ "is-descriptor": "^0.1.0"
+ }
+ },
+ "extend-shallow": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz",
+ "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=",
+ "dev": true,
+ "requires": {
+ "is-extendable": "^0.1.0"
+ }
+ },
+ "ms": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
+ "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=",
+ "dev": true
+ }
+ }
+ },
+ "snapdragon-node": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/snapdragon-node/-/snapdragon-node-2.1.1.tgz",
+ "integrity": "sha512-O27l4xaMYt/RSQ5TR3vpWCAB5Kb/czIcqUFOM/C4fYcLnbZUc1PkjTAMjof2pBWaSTwOUd6qUHcFGVGj7aIwnw==",
+ "dev": true,
+ "requires": {
+ "define-property": "^1.0.0",
+ "isobject": "^3.0.0",
+ "snapdragon-util": "^3.0.1"
+ },
+ "dependencies": {
+ "define-property": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/define-property/-/define-property-1.0.0.tgz",
+ "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=",
+ "dev": true,
+ "requires": {
+ "is-descriptor": "^1.0.0"
+ }
+ },
+ "is-accessor-descriptor": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz",
+ "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==",
+ "dev": true,
+ "requires": {
+ "kind-of": "^6.0.0"
+ }
+ },
+ "is-data-descriptor": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz",
+ "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==",
+ "dev": true,
+ "requires": {
+ "kind-of": "^6.0.0"
+ }
+ },
+ "is-descriptor": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz",
+ "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==",
+ "dev": true,
+ "requires": {
+ "is-accessor-descriptor": "^1.0.0",
+ "is-data-descriptor": "^1.0.0",
+ "kind-of": "^6.0.2"
+ }
+ },
+ "isobject": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz",
+ "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=",
+ "dev": true
+ },
+ "kind-of": {
+ "version": "6.0.3",
+ "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz",
+ "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==",
+ "dev": true
+ }
+ }
+ },
+ "snapdragon-util": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/snapdragon-util/-/snapdragon-util-3.0.1.tgz",
+ "integrity": "sha512-mbKkMdQKsjX4BAL4bRYTj21edOf8cN7XHdYUJEe+Zn99hVEYcMvKPct1IqNe7+AZPirn8BCDOQBHQZknqmKlZQ==",
+ "dev": true,
+ "requires": {
+ "kind-of": "^3.2.0"
+ }
+ },
+ "socket.io": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/socket.io/-/socket.io-2.1.1.tgz",
+ "integrity": "sha512-rORqq9c+7W0DAK3cleWNSyfv/qKXV99hV4tZe+gGLfBECw3XEhBy7x85F3wypA9688LKjtwO9pX9L33/xQI8yA==",
+ "dev": true,
+ "requires": {
+ "debug": "~3.1.0",
+ "engine.io": "~3.2.0",
+ "has-binary2": "~1.0.2",
+ "socket.io-adapter": "~1.1.0",
+ "socket.io-client": "2.1.1",
+ "socket.io-parser": "~3.2.0"
+ },
+ "dependencies": {
+ "debug": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz",
+ "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==",
+ "dev": true,
+ "requires": {
+ "ms": "2.0.0"
+ }
+ },
+ "ms": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
+ "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=",
+ "dev": true
+ }
+ }
+ },
+ "socket.io-adapter": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/socket.io-adapter/-/socket.io-adapter-1.1.2.tgz",
+ "integrity": "sha512-WzZRUj1kUjrTIrUKpZLEzFZ1OLj5FwLlAFQs9kuZJzJi5DKdU7FsWc36SNmA8iDOtwBQyT8FkrriRM8vXLYz8g==",
+ "dev": true
+ },
+ "socket.io-client": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/socket.io-client/-/socket.io-client-2.1.1.tgz",
+ "integrity": "sha512-jxnFyhAuFxYfjqIgduQlhzqTcOEQSn+OHKVfAxWaNWa7ecP7xSNk2Dx/3UEsDcY7NcFafxvNvKPmmO7HTwTxGQ==",
+ "dev": true,
+ "requires": {
+ "backo2": "1.0.2",
+ "base64-arraybuffer": "0.1.5",
+ "component-bind": "1.0.0",
+ "component-emitter": "1.2.1",
+ "debug": "~3.1.0",
+ "engine.io-client": "~3.2.0",
+ "has-binary2": "~1.0.2",
+ "has-cors": "1.1.0",
+ "indexof": "0.0.1",
+ "object-component": "0.0.3",
+ "parseqs": "0.0.5",
+ "parseuri": "0.0.5",
+ "socket.io-parser": "~3.2.0",
+ "to-array": "0.1.4"
+ },
+ "dependencies": {
+ "component-emitter": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.2.1.tgz",
+ "integrity": "sha1-E3kY1teCg/ffemt8WmPhQOaUJeY=",
+ "dev": true
+ },
+ "debug": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz",
+ "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==",
+ "dev": true,
+ "requires": {
+ "ms": "2.0.0"
+ }
+ },
+ "ms": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
+ "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=",
+ "dev": true
+ }
+ }
+ },
+ "socket.io-parser": {
+ "version": "3.2.0",
+ "resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-3.2.0.tgz",
+ "integrity": "sha512-FYiBx7rc/KORMJlgsXysflWx/RIvtqZbyGLlHZvjfmPTPeuD/I8MaW7cfFrj5tRltICJdgwflhfZ3NVVbVLFQA==",
+ "dev": true,
+ "requires": {
+ "component-emitter": "1.2.1",
+ "debug": "~3.1.0",
+ "isarray": "2.0.1"
+ },
+ "dependencies": {
+ "component-emitter": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.2.1.tgz",
+ "integrity": "sha1-E3kY1teCg/ffemt8WmPhQOaUJeY=",
+ "dev": true
+ },
+ "debug": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz",
+ "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==",
+ "dev": true,
+ "requires": {
+ "ms": "2.0.0"
+ }
+ },
+ "isarray": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.1.tgz",
+ "integrity": "sha1-o32U7ZzaLVmGXJ92/llu4fM4dB4=",
+ "dev": true
+ },
+ "ms": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
+ "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=",
+ "dev": true
+ }
+ }
+ },
+ "source-list-map": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/source-list-map/-/source-list-map-2.0.1.tgz",
+ "integrity": "sha512-qnQ7gVMxGNxsiL4lEuJwe/To8UnK7fAnmbGEEH8RpLouuKbeEm0lhbQVFIrNSuB+G7tVrAlVsZgETT5nljf+Iw==",
+ "dev": true
+ },
+ "source-map": {
+ "version": "0.5.7",
+ "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz",
+ "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=",
+ "dev": true
+ },
+ "source-map-resolve": {
+ "version": "0.5.3",
+ "resolved": "https://registry.npmjs.org/source-map-resolve/-/source-map-resolve-0.5.3.tgz",
+ "integrity": "sha512-Htz+RnsXWk5+P2slx5Jh3Q66vhQj1Cllm0zvnaY98+NFx+Dv2CF/f5O/t8x+KaNdrdIAsruNzoh/KpialbqAnw==",
+ "dev": true,
+ "requires": {
+ "atob": "^2.1.2",
+ "decode-uri-component": "^0.2.0",
+ "resolve-url": "^0.2.1",
+ "source-map-url": "^0.4.0",
+ "urix": "^0.1.0"
+ }
+ },
+ "source-map-support": {
+ "version": "0.5.16",
+ "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.16.tgz",
+ "integrity": "sha512-efyLRJDr68D9hBBNIPWFjhpFzURh+KJykQwvMyW5UiZzYwoF6l4YMMDIJJEyFWxWCqfyxLzz6tSfUFR+kXXsVQ==",
+ "dev": true,
+ "requires": {
+ "buffer-from": "^1.0.0",
+ "source-map": "^0.6.0"
+ },
+ "dependencies": {
+ "source-map": {
+ "version": "0.6.1",
+ "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
+ "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",
+ "dev": true
+ }
+ }
+ },
+ "source-map-url": {
+ "version": "0.4.0",
+ "resolved": "https://registry.npmjs.org/source-map-url/-/source-map-url-0.4.0.tgz",
+ "integrity": "sha1-PpNdfd1zYxuXZZlW1VEo6HtQhKM=",
+ "dev": true
+ },
+ "spdx-correct": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/spdx-correct/-/spdx-correct-3.1.0.tgz",
+ "integrity": "sha512-lr2EZCctC2BNR7j7WzJ2FpDznxky1sjfxvvYEyzxNyb6lZXHODmEoJeFu4JupYlkfha1KZpJyoqiJ7pgA1qq8Q==",
+ "dev": true,
+ "requires": {
+ "spdx-expression-parse": "^3.0.0",
+ "spdx-license-ids": "^3.0.0"
+ }
+ },
+ "spdx-exceptions": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/spdx-exceptions/-/spdx-exceptions-2.2.0.tgz",
+ "integrity": "sha512-2XQACfElKi9SlVb1CYadKDXvoajPgBVPn/gOQLrTvHdElaVhr7ZEbqJaRnJLVNeaI4cMEAgVCeBMKF6MWRDCRA==",
+ "dev": true
+ },
+ "spdx-expression-parse": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-3.0.0.tgz",
+ "integrity": "sha512-Yg6D3XpRD4kkOmTpdgbUiEJFKghJH03fiC1OPll5h/0sO6neh2jqRDVHOQ4o/LMea0tgCkbMgea5ip/e+MkWyg==",
+ "dev": true,
+ "requires": {
+ "spdx-exceptions": "^2.1.0",
+ "spdx-license-ids": "^3.0.0"
+ }
+ },
+ "spdx-license-ids": {
+ "version": "3.0.5",
+ "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-3.0.5.tgz",
+ "integrity": "sha512-J+FWzZoynJEXGphVIS+XEh3kFSjZX/1i9gFBaWQcB+/tmpe2qUsSBABpcxqxnAxFdiUFEgAX1bjYGQvIZmoz9Q==",
+ "dev": true
+ },
+ "split-string": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/split-string/-/split-string-3.1.0.tgz",
+ "integrity": "sha512-NzNVhJDYpwceVVii8/Hu6DKfD2G+NrQHlS/V/qgv763EYudVwEcMQNxd2lh+0VrUByXN/oJkl5grOhYWvQUYiw==",
+ "dev": true,
+ "requires": {
+ "extend-shallow": "^3.0.0"
+ }
+ },
+ "sprintf-js": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz",
+ "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=",
+ "dev": true
+ },
+ "sshpk": {
+ "version": "1.16.1",
+ "resolved": "https://registry.npmjs.org/sshpk/-/sshpk-1.16.1.tgz",
+ "integrity": "sha512-HXXqVUq7+pcKeLqqZj6mHFUMvXtOJt1uoUx09pFW6011inTMxqI8BA8PM95myrIyyKwdnzjdFjLiE6KBPVtJIg==",
+ "dev": true,
+ "requires": {
+ "asn1": "~0.2.3",
+ "assert-plus": "^1.0.0",
+ "bcrypt-pbkdf": "^1.0.0",
+ "dashdash": "^1.12.0",
+ "ecc-jsbn": "~0.1.1",
+ "getpass": "^0.1.1",
+ "jsbn": "~0.1.0",
+ "safer-buffer": "^2.0.2",
+ "tweetnacl": "~0.14.0"
+ }
+ },
+ "ssri": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/ssri/-/ssri-6.0.1.tgz",
+ "integrity": "sha512-3Wge10hNcT1Kur4PDFwEieXSCMCJs/7WvSACcrMYrNp+b8kDL1/0wJch5Ni2WrtwEa2IO8OsVfeKIciKCDx/QA==",
+ "dev": true,
+ "requires": {
+ "figgy-pudding": "^3.5.1"
+ }
+ },
+ "static-extend": {
+ "version": "0.1.2",
+ "resolved": "https://registry.npmjs.org/static-extend/-/static-extend-0.1.2.tgz",
+ "integrity": "sha1-YICcOcv/VTNyJv1eC1IPNB8ftcY=",
+ "dev": true,
+ "requires": {
+ "define-property": "^0.2.5",
+ "object-copy": "^0.1.0"
+ },
+ "dependencies": {
+ "define-property": {
+ "version": "0.2.5",
+ "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz",
+ "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=",
+ "dev": true,
+ "requires": {
+ "is-descriptor": "^0.1.0"
+ }
+ }
+ }
+ },
+ "statuses": {
+ "version": "1.5.0",
+ "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz",
+ "integrity": "sha1-Fhx9rBd2Wf2YEfQ3cfqZOBR4Yow=",
+ "dev": true
+ },
+ "stdout-stream": {
+ "version": "1.4.1",
+ "resolved": "https://registry.npmjs.org/stdout-stream/-/stdout-stream-1.4.1.tgz",
+ "integrity": "sha512-j4emi03KXqJWcIeF8eIXkjMFN1Cmb8gUlDYGeBALLPo5qdyTfA9bOtl8m33lRoC+vFMkP3gl0WsDr6+gzxbbTA==",
+ "dev": true,
+ "requires": {
+ "readable-stream": "^2.0.1"
+ }
+ },
+ "stream-browserify": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/stream-browserify/-/stream-browserify-2.0.2.tgz",
+ "integrity": "sha512-nX6hmklHs/gr2FuxYDltq8fJA1GDlxKQCz8O/IM4atRqBH8OORmBNgfvW5gG10GT/qQ9u0CzIvr2X5Pkt6ntqg==",
+ "dev": true,
+ "requires": {
+ "inherits": "~2.0.1",
+ "readable-stream": "^2.0.2"
+ }
+ },
+ "stream-each": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/stream-each/-/stream-each-1.2.3.tgz",
+ "integrity": "sha512-vlMC2f8I2u/bZGqkdfLQW/13Zihpej/7PmSiMQsbYddxuTsJp8vRe2x2FvVExZg7FaOds43ROAuFJwPR4MTZLw==",
+ "dev": true,
+ "requires": {
+ "end-of-stream": "^1.1.0",
+ "stream-shift": "^1.0.0"
+ }
+ },
+ "stream-http": {
+ "version": "2.8.3",
+ "resolved": "https://registry.npmjs.org/stream-http/-/stream-http-2.8.3.tgz",
+ "integrity": "sha512-+TSkfINHDo4J+ZobQLWiMouQYB+UVYFttRA94FpEzzJ7ZdqcL4uUUQ7WkdkI4DSozGmgBUE/a47L+38PenXhUw==",
+ "dev": true,
+ "requires": {
+ "builtin-status-codes": "^3.0.0",
+ "inherits": "^2.0.1",
+ "readable-stream": "^2.3.6",
+ "to-arraybuffer": "^1.0.0",
+ "xtend": "^4.0.0"
+ }
+ },
+ "stream-shift": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/stream-shift/-/stream-shift-1.0.1.tgz",
+ "integrity": "sha512-AiisoFqQ0vbGcZgQPY1cdP2I76glaVA/RauYR4G4thNFgkTqr90yXTo4LYX60Jl+sIlPNHHdGSwo01AvbKUSVQ==",
+ "dev": true
+ },
+ "streamroller": {
+ "version": "1.0.6",
+ "resolved": "https://registry.npmjs.org/streamroller/-/streamroller-1.0.6.tgz",
+ "integrity": "sha512-3QC47Mhv3/aZNFpDDVO44qQb9gwB9QggMEE0sQmkTAwBVYdBRWISdsywlkfm5II1Q5y/pmrHflti/IgmIzdDBg==",
+ "dev": true,
+ "requires": {
+ "async": "^2.6.2",
+ "date-format": "^2.0.0",
+ "debug": "^3.2.6",
+ "fs-extra": "^7.0.1",
+ "lodash": "^4.17.14"
+ },
+ "dependencies": {
+ "debug": {
+ "version": "3.2.6",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz",
+ "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==",
+ "dev": true,
+ "requires": {
+ "ms": "^2.1.1"
+ }
+ }
+ }
+ },
+ "string-width": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-2.1.1.tgz",
+ "integrity": "sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw==",
+ "dev": true,
+ "requires": {
+ "is-fullwidth-code-point": "^2.0.0",
+ "strip-ansi": "^4.0.0"
+ },
+ "dependencies": {
+ "ansi-regex": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz",
+ "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=",
+ "dev": true
+ },
+ "strip-ansi": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz",
+ "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=",
+ "dev": true,
+ "requires": {
+ "ansi-regex": "^3.0.0"
+ }
+ }
+ }
+ },
+ "string.prototype.padend": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/string.prototype.padend/-/string.prototype.padend-3.1.0.tgz",
+ "integrity": "sha512-3aIv8Ffdp8EZj8iLwREGpQaUZiPyrWrpzMBHvkiSW/bK/EGve9np07Vwy7IJ5waydpGXzQZu/F8Oze2/IWkBaA==",
+ "dev": true,
+ "requires": {
+ "define-properties": "^1.1.3",
+ "es-abstract": "^1.17.0-next.1"
+ }
+ },
+ "string.prototype.trim": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/string.prototype.trim/-/string.prototype.trim-1.2.1.tgz",
+ "integrity": "sha512-MjGFEeqixw47dAMFMtgUro/I0+wNqZB5GKXGt1fFr24u3TzDXCPu7J9Buppzoe3r/LqkSDLDDJzE15RGWDGAVw==",
+ "dev": true,
+ "requires": {
+ "define-properties": "^1.1.3",
+ "es-abstract": "^1.17.0-next.1",
+ "function-bind": "^1.1.1"
+ }
+ },
+ "string.prototype.trimleft": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/string.prototype.trimleft/-/string.prototype.trimleft-2.1.1.tgz",
+ "integrity": "sha512-iu2AGd3PuP5Rp7x2kEZCrB2Nf41ehzh+goo8TV7z8/XDBbsvc6HQIlUl9RjkZ4oyrW1XM5UwlGl1oVEaDjg6Ag==",
+ "dev": true,
+ "requires": {
+ "define-properties": "^1.1.3",
+ "function-bind": "^1.1.1"
+ }
+ },
+ "string.prototype.trimright": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/string.prototype.trimright/-/string.prototype.trimright-2.1.1.tgz",
+ "integrity": "sha512-qFvWL3/+QIgZXVmJBfpHmxLB7xsUXz6HsUmP8+5dRaC3Q7oKUv9Vo6aMCRZC1smrtyECFsIT30PqBJ1gTjAs+g==",
+ "dev": true,
+ "requires": {
+ "define-properties": "^1.1.3",
+ "function-bind": "^1.1.1"
+ }
+ },
+ "string_decoder": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz",
+ "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",
+ "dev": true,
+ "requires": {
+ "safe-buffer": "~5.1.0"
+ }
+ },
+ "strip-ansi": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz",
+ "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=",
+ "dev": true,
+ "requires": {
+ "ansi-regex": "^2.0.0"
+ }
+ },
+ "strip-bom": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz",
+ "integrity": "sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM=",
+ "dev": true
+ },
+ "strip-eof": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/strip-eof/-/strip-eof-1.0.0.tgz",
+ "integrity": "sha1-u0P/VZim6wXYm1n80SnJgzE2Br8=",
+ "dev": true
+ },
+ "strip-indent": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-1.0.1.tgz",
+ "integrity": "sha1-DHlipq3vp7vUrDZkYKY4VSrhoKI=",
+ "dev": true,
+ "requires": {
+ "get-stdin": "^4.0.1"
+ }
+ },
+ "strip-json-comments": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz",
+ "integrity": "sha1-PFMZQukIwml8DsNEhYwobHygpgo=",
+ "dev": true
+ },
+ "subarg": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/subarg/-/subarg-1.0.0.tgz",
+ "integrity": "sha1-9izxdYHplrSPyWVpn1TAauJouNI=",
+ "dev": true,
+ "requires": {
+ "minimist": "^1.1.0"
+ }
+ },
+ "supports-color": {
+ "version": "5.5.0",
+ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz",
+ "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==",
+ "dev": true,
+ "requires": {
+ "has-flag": "^3.0.0"
+ }
+ },
+ "symbol-observable": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/symbol-observable/-/symbol-observable-1.2.0.tgz",
+ "integrity": "sha512-e900nM8RRtGhlV36KGEU9k65K3mPb1WV70OdjfxlG2EAuM1noi/E/BaW/uMhL7bPEssK8QV57vN3esixjUvcXQ=="
+ },
+ "table": {
+ "version": "3.8.3",
+ "resolved": "https://registry.npmjs.org/table/-/table-3.8.3.tgz",
+ "integrity": "sha1-K7xULw/amGGnVdOUf+/Ys/UThV8=",
+ "dev": true,
+ "requires": {
+ "ajv": "^4.7.0",
+ "ajv-keywords": "^1.0.0",
+ "chalk": "^1.1.1",
+ "lodash": "^4.0.0",
+ "slice-ansi": "0.0.4",
+ "string-width": "^2.0.0"
+ },
+ "dependencies": {
+ "ajv": {
+ "version": "4.11.8",
+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-4.11.8.tgz",
+ "integrity": "sha1-gv+wKynmYq5TvcIK8VlHcGc5xTY=",
+ "dev": true,
+ "requires": {
+ "co": "^4.6.0",
+ "json-stable-stringify": "^1.0.1"
+ }
+ },
+ "ajv-keywords": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-1.5.1.tgz",
+ "integrity": "sha1-MU3QpLM2j609/NxU7eYXG4htrzw=",
+ "dev": true
+ },
+ "ansi-styles": {
+ "version": "2.2.1",
+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz",
+ "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=",
+ "dev": true
+ },
+ "chalk": {
+ "version": "1.1.3",
+ "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz",
+ "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=",
+ "dev": true,
+ "requires": {
+ "ansi-styles": "^2.2.1",
+ "escape-string-regexp": "^1.0.2",
+ "has-ansi": "^2.0.0",
+ "strip-ansi": "^3.0.0",
+ "supports-color": "^2.0.0"
+ }
+ },
+ "supports-color": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz",
+ "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=",
+ "dev": true
+ }
+ }
+ },
+ "tapable": {
+ "version": "1.1.3",
+ "resolved": "https://registry.npmjs.org/tapable/-/tapable-1.1.3.tgz",
+ "integrity": "sha512-4WK/bYZmj8xLr+HUCODHGF1ZFzsYffasLUgEiMBY4fgtltdO6B4WJtlSbPaDTLpYTcGVwM2qLnFTICEcNxs3kA==",
+ "dev": true
+ },
+ "tar": {
+ "version": "2.2.2",
+ "resolved": "https://registry.npmjs.org/tar/-/tar-2.2.2.tgz",
+ "integrity": "sha512-FCEhQ/4rE1zYv9rYXJw/msRqsnmlje5jHP6huWeBZ704jUTy02c5AZyWujpMR1ax6mVw9NyJMfuK2CMDWVIfgA==",
+ "dev": true,
+ "requires": {
+ "block-stream": "*",
+ "fstream": "^1.0.12",
+ "inherits": "2"
+ }
+ },
+ "terser": {
+ "version": "4.6.3",
+ "resolved": "https://registry.npmjs.org/terser/-/terser-4.6.3.tgz",
+ "integrity": "sha512-Lw+ieAXmY69d09IIc/yqeBqXpEQIpDGZqT34ui1QWXIUpR2RjbqEkT8X7Lgex19hslSqcWM5iMN2kM11eMsESQ==",
+ "dev": true,
+ "requires": {
+ "commander": "^2.20.0",
+ "source-map": "~0.6.1",
+ "source-map-support": "~0.5.12"
+ },
+ "dependencies": {
+ "source-map": {
+ "version": "0.6.1",
+ "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
+ "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",
+ "dev": true
+ }
+ }
+ },
+ "terser-webpack-plugin": {
+ "version": "1.4.3",
+ "resolved": "https://registry.npmjs.org/terser-webpack-plugin/-/terser-webpack-plugin-1.4.3.tgz",
+ "integrity": "sha512-QMxecFz/gHQwteWwSo5nTc6UaICqN1bMedC5sMtUc7y3Ha3Q8y6ZO0iCR8pq4RJC8Hjf0FEPEHZqcMB/+DFCrA==",
+ "dev": true,
+ "requires": {
+ "cacache": "^12.0.2",
+ "find-cache-dir": "^2.1.0",
+ "is-wsl": "^1.1.0",
+ "schema-utils": "^1.0.0",
+ "serialize-javascript": "^2.1.2",
+ "source-map": "^0.6.1",
+ "terser": "^4.1.2",
+ "webpack-sources": "^1.4.0",
+ "worker-farm": "^1.7.0"
+ },
+ "dependencies": {
+ "ajv": {
+ "version": "6.11.0",
+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.11.0.tgz",
+ "integrity": "sha512-nCprB/0syFYy9fVYU1ox1l2KN8S9I+tziH8D4zdZuLT3N6RMlGSGt5FSTpAiHB/Whv8Qs1cWHma1aMKZyaHRKA==",
+ "dev": true,
+ "requires": {
+ "fast-deep-equal": "^3.1.1",
+ "fast-json-stable-stringify": "^2.0.0",
+ "json-schema-traverse": "^0.4.1",
+ "uri-js": "^4.2.2"
+ }
+ },
+ "fast-deep-equal": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.1.tgz",
+ "integrity": "sha512-8UEa58QDLauDNfpbrX55Q9jrGHThw2ZMdOky5Gl1CDtVeJDPVrG4Jxx1N8jw2gkWaff5UUuX1KJd+9zGe2B+ZA==",
+ "dev": true
+ },
+ "is-wsl": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-1.1.0.tgz",
+ "integrity": "sha1-HxbkqiKwTRM2tmGIpmrzxgDDpm0=",
+ "dev": true
+ },
+ "json-schema-traverse": {
+ "version": "0.4.1",
+ "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz",
+ "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==",
+ "dev": true
+ },
+ "schema-utils": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-1.0.0.tgz",
+ "integrity": "sha512-i27Mic4KovM/lnGsy8whRCHhc7VicJajAjTrYg11K9zfZXnYIt4k5F+kZkwjnrhKzLic/HLU4j11mjsz2G/75g==",
+ "dev": true,
+ "requires": {
+ "ajv": "^6.1.0",
+ "ajv-errors": "^1.0.0",
+ "ajv-keywords": "^3.1.0"
+ }
+ },
+ "source-map": {
+ "version": "0.6.1",
+ "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
+ "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",
+ "dev": true
+ }
+ }
+ },
+ "text-table": {
+ "version": "0.2.0",
+ "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz",
+ "integrity": "sha1-f17oI66AUgfACvLfSoTsP8+lcLQ=",
+ "dev": true
+ },
+ "through": {
+ "version": "2.3.8",
+ "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz",
+ "integrity": "sha1-DdTJ/6q8NXlgsbckEV1+Doai4fU=",
+ "dev": true
+ },
+ "through2": {
+ "version": "2.0.5",
+ "resolved": "https://registry.npmjs.org/through2/-/through2-2.0.5.tgz",
+ "integrity": "sha512-/mrRod8xqpA+IHSLyGCQ2s8SPHiCDEeQJSep1jqLYeEUClOFG2Qsh+4FU6G9VeqpZnGW/Su8LQGc4YKni5rYSQ==",
+ "dev": true,
+ "requires": {
+ "readable-stream": "~2.3.6",
+ "xtend": "~4.0.1"
+ }
+ },
+ "timers-browserify": {
+ "version": "2.0.11",
+ "resolved": "https://registry.npmjs.org/timers-browserify/-/timers-browserify-2.0.11.tgz",
+ "integrity": "sha512-60aV6sgJ5YEbzUdn9c8kYGIqOubPoUdqQCul3SBAsRCZ40s6Y5cMcrW4dt3/k/EsbLVJNl9n6Vz3fTc+k2GeKQ==",
+ "dev": true,
+ "requires": {
+ "setimmediate": "^1.0.4"
+ }
+ },
+ "tmp": {
+ "version": "0.0.33",
+ "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.33.tgz",
+ "integrity": "sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw==",
+ "dev": true,
+ "requires": {
+ "os-tmpdir": "~1.0.2"
+ }
+ },
+ "to-array": {
+ "version": "0.1.4",
+ "resolved": "https://registry.npmjs.org/to-array/-/to-array-0.1.4.tgz",
+ "integrity": "sha1-F+bBH3PdTz10zaek/zI46a2b+JA=",
+ "dev": true
+ },
+ "to-arraybuffer": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/to-arraybuffer/-/to-arraybuffer-1.0.1.tgz",
+ "integrity": "sha1-fSKbH8xjfkZsoIEYCDanqr/4P0M=",
+ "dev": true
+ },
+ "to-fast-properties": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz",
+ "integrity": "sha1-3F5pjL0HkmW8c+A3doGk5Og/YW4=",
+ "dev": true
+ },
+ "to-object-path": {
+ "version": "0.3.0",
+ "resolved": "https://registry.npmjs.org/to-object-path/-/to-object-path-0.3.0.tgz",
+ "integrity": "sha1-KXWIt7Dn4KwI4E5nL4XB9JmeF68=",
+ "dev": true,
+ "requires": {
+ "kind-of": "^3.0.2"
+ }
+ },
+ "to-regex": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/to-regex/-/to-regex-3.0.2.tgz",
+ "integrity": "sha512-FWtleNAtZ/Ki2qtqej2CXTOayOH9bHDQF+Q48VpWyDXjbYxA4Yz8iDB31zXOBUlOHHKidDbqGVrTUvQMPmBGBw==",
+ "dev": true,
+ "requires": {
+ "define-property": "^2.0.2",
+ "extend-shallow": "^3.0.2",
+ "regex-not": "^1.0.2",
+ "safe-regex": "^1.1.0"
+ }
+ },
+ "to-regex-range": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-2.1.1.tgz",
+ "integrity": "sha1-fIDBe53+vlmeJzZ+DU3VWQFB2zg=",
+ "dev": true,
+ "requires": {
+ "is-number": "^3.0.0",
+ "repeat-string": "^1.6.1"
+ },
+ "dependencies": {
+ "is-number": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/is-number/-/is-number-3.0.0.tgz",
+ "integrity": "sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=",
+ "dev": true,
+ "requires": {
+ "kind-of": "^3.0.2"
+ }
+ }
+ }
+ },
+ "toidentifier": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.0.tgz",
+ "integrity": "sha512-yaOH/Pk/VEhBWWTlhI+qXxDFXlejDGcQipMlyxda9nthulaxLZUNcUqFxokp0vcYnvteJln5FNQDRrxj3YcbVw==",
+ "dev": true
+ },
+ "tough-cookie": {
+ "version": "2.5.0",
+ "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.5.0.tgz",
+ "integrity": "sha512-nlLsUzgm1kfLXSXfRZMc1KLAugd4hqJHDTvc2hDIwS3mZAfMEuMbc03SujMF+GEcpaX/qboeycw6iO8JwVv2+g==",
+ "dev": true,
+ "requires": {
+ "psl": "^1.1.28",
+ "punycode": "^2.1.1"
+ }
+ },
+ "trim-newlines": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/trim-newlines/-/trim-newlines-1.0.0.tgz",
+ "integrity": "sha1-WIeWa7WCpFA6QetST301ARgVphM=",
+ "dev": true
+ },
+ "trim-right": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/trim-right/-/trim-right-1.0.1.tgz",
+ "integrity": "sha1-yy4SAwZ+DI3h9hQJS5/kVwTqYAM=",
+ "dev": true
+ },
+ "true-case-path": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/true-case-path/-/true-case-path-1.0.3.tgz",
+ "integrity": "sha512-m6s2OdQe5wgpFMC+pAJ+q9djG82O2jcHPOI6RNg1yy9rCYR+WD6Nbpl32fDpfC56nirdRy+opFa/Vk7HYhqaew==",
+ "dev": true,
+ "requires": {
+ "glob": "^7.1.2"
+ }
+ },
+ "tslib": {
+ "version": "1.10.0",
+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.10.0.tgz",
+ "integrity": "sha512-qOebF53frne81cf0S9B41ByenJ3/IuH8yJKngAX35CmiZySA0khhkovshKK+jGCaMnVomla7gVlIcc3EvKPbTQ==",
+ "dev": true
+ },
+ "tty-browserify": {
+ "version": "0.0.0",
+ "resolved": "https://registry.npmjs.org/tty-browserify/-/tty-browserify-0.0.0.tgz",
+ "integrity": "sha1-oVe6QC2iTpv5V/mqadUk7tQpAaY=",
+ "dev": true
+ },
+ "tunnel-agent": {
+ "version": "0.6.0",
+ "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz",
+ "integrity": "sha1-J6XeoGs2sEoKmWZ3SykIaPD8QP0=",
+ "dev": true,
+ "requires": {
+ "safe-buffer": "^5.0.1"
+ }
+ },
+ "tv4": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/tv4/-/tv4-1.3.0.tgz",
+ "integrity": "sha1-0CDIRvrdUMhVq7JeuuzGj8EPeWM=",
+ "dev": true
+ },
+ "tweetnacl": {
+ "version": "0.14.5",
+ "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz",
+ "integrity": "sha1-WuaBd/GS1EViadEIr6k/+HQ/T2Q=",
+ "dev": true
+ },
+ "type": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/type/-/type-1.2.0.tgz",
+ "integrity": "sha512-+5nt5AAniqsCnu2cEQQdpzCAh33kVx8n0VoFidKpB1dVVLAN/F+bgVOqOJqOnEnrhp222clB5p3vUlD+1QAnfg==",
+ "dev": true
+ },
+ "type-check": {
+ "version": "0.3.2",
+ "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.3.2.tgz",
+ "integrity": "sha1-WITKtRLPHTVeP7eE8wgEsrUg23I=",
+ "dev": true,
+ "requires": {
+ "prelude-ls": "~1.1.2"
+ }
+ },
+ "type-detect": {
+ "version": "4.0.8",
+ "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz",
+ "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==",
+ "dev": true
+ },
+ "type-is": {
+ "version": "1.6.18",
+ "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz",
+ "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==",
+ "dev": true,
+ "requires": {
+ "media-typer": "0.3.0",
+ "mime-types": "~2.1.24"
+ }
+ },
+ "typedarray": {
+ "version": "0.0.6",
+ "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz",
+ "integrity": "sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c=",
+ "dev": true
+ },
+ "ultron": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/ultron/-/ultron-1.1.1.tgz",
+ "integrity": "sha512-UIEXBNeYmKptWH6z8ZnqTeS8fV74zG0/eRU9VGkpzz+LIJNs8W/zM/L+7ctCkRrgbNnnR0xxw4bKOr0cW0N0Og==",
+ "dev": true
+ },
+ "union-value": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/union-value/-/union-value-1.0.1.tgz",
+ "integrity": "sha512-tJfXmxMeWYnczCVs7XAEvIV7ieppALdyepWMkHkwciRpZraG/xwT+s2JN8+pr1+8jCRf80FFzvr+MpQeeoF4Xg==",
+ "dev": true,
+ "requires": {
+ "arr-union": "^3.1.0",
+ "get-value": "^2.0.6",
+ "is-extendable": "^0.1.1",
+ "set-value": "^2.0.1"
+ }
+ },
+ "unique-filename": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/unique-filename/-/unique-filename-1.1.1.tgz",
+ "integrity": "sha512-Vmp0jIp2ln35UTXuryvjzkjGdRyf9b2lTXuSYUiPmzRcl3FDtYqAwOnTJkAngD9SWhnoJzDbTKwaOrZ+STtxNQ==",
+ "dev": true,
+ "requires": {
+ "unique-slug": "^2.0.0"
+ }
+ },
+ "unique-slug": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/unique-slug/-/unique-slug-2.0.2.tgz",
+ "integrity": "sha512-zoWr9ObaxALD3DOPfjPSqxt4fnZiWblxHIgeWqW8x7UqDzEtHEQLzji2cuJYQFCU6KmoJikOYAZlrTHHebjx2w==",
+ "dev": true,
+ "requires": {
+ "imurmurhash": "^0.1.4"
+ }
+ },
+ "universalify": {
+ "version": "0.1.2",
+ "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz",
+ "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==",
+ "dev": true
+ },
+ "unpipe": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
+ "integrity": "sha1-sr9O6FFKrmFltIF4KdIbLvSZBOw=",
+ "dev": true
+ },
+ "unset-value": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/unset-value/-/unset-value-1.0.0.tgz",
+ "integrity": "sha1-g3aHP30jNRef+x5vw6jtDfyKtVk=",
+ "dev": true,
+ "requires": {
+ "has-value": "^0.3.1",
+ "isobject": "^3.0.0"
+ },
+ "dependencies": {
+ "has-value": {
+ "version": "0.3.1",
+ "resolved": "https://registry.npmjs.org/has-value/-/has-value-0.3.1.tgz",
+ "integrity": "sha1-ex9YutpiyoJ+wKIHgCVlSEWZXh8=",
+ "dev": true,
+ "requires": {
+ "get-value": "^2.0.3",
+ "has-values": "^0.1.4",
+ "isobject": "^2.0.0"
+ },
+ "dependencies": {
+ "isobject": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/isobject/-/isobject-2.1.0.tgz",
+ "integrity": "sha1-8GVWEJaj8dou9GJy+BXIQNh+DIk=",
+ "dev": true,
+ "requires": {
+ "isarray": "1.0.0"
+ }
+ }
+ }
+ },
+ "has-values": {
+ "version": "0.1.4",
+ "resolved": "https://registry.npmjs.org/has-values/-/has-values-0.1.4.tgz",
+ "integrity": "sha1-bWHeldkd/Km5oCCJrThL/49it3E=",
+ "dev": true
+ },
+ "isobject": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz",
+ "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=",
+ "dev": true
+ }
+ }
+ },
+ "upath": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/upath/-/upath-1.2.0.tgz",
+ "integrity": "sha512-aZwGpamFO61g3OlfT7OQCHqhGnW43ieH9WZeP7QxN/G/jS4jfqUkZxoryvJgVPEcrl5NL/ggHsSmLMHuH64Lhg==",
+ "dev": true
+ },
+ "uri-js": {
+ "version": "4.2.2",
+ "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.2.2.tgz",
+ "integrity": "sha512-KY9Frmirql91X2Qgjry0Wd4Y+YTdrdZheS8TFwvkbLWf/G5KNJDCh6pKL5OZctEW4+0Baa5idK2ZQuELRwPznQ==",
+ "dev": true,
+ "requires": {
+ "punycode": "^2.1.0"
+ }
+ },
+ "urix": {
+ "version": "0.1.0",
+ "resolved": "https://registry.npmjs.org/urix/-/urix-0.1.0.tgz",
+ "integrity": "sha1-2pN/emLiH+wf0Y1Js1wpNQZ6bHI=",
+ "dev": true
+ },
+ "url": {
+ "version": "0.11.0",
+ "resolved": "https://registry.npmjs.org/url/-/url-0.11.0.tgz",
+ "integrity": "sha1-ODjpfPxgUh63PFJajlW/3Z4uKPE=",
+ "dev": true,
+ "requires": {
+ "punycode": "1.3.2",
+ "querystring": "0.2.0"
+ },
+ "dependencies": {
+ "punycode": {
+ "version": "1.3.2",
+ "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.3.2.tgz",
+ "integrity": "sha1-llOgNvt8HuQjQvIyXM7v6jkmxI0=",
+ "dev": true
+ }
+ }
+ },
+ "use": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/use/-/use-3.1.1.tgz",
+ "integrity": "sha512-cwESVXlO3url9YWlFW/TA9cshCEhtu7IKJ/p5soJ/gGpj7vbvFrAY/eIioQ6Dw23KjZhYgiIo8HOs1nQ2vr/oQ==",
+ "dev": true
+ },
+ "user-home": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/user-home/-/user-home-2.0.0.tgz",
+ "integrity": "sha1-nHC/2Babwdy/SGBODwS4tJzenp8=",
+ "dev": true,
+ "requires": {
+ "os-homedir": "^1.0.0"
+ }
+ },
+ "useragent": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/useragent/-/useragent-2.3.0.tgz",
+ "integrity": "sha512-4AoH4pxuSvHCjqLO04sU6U/uE65BYza8l/KKBS0b0hnUPWi+cQ2BpeTEwejCSx9SPV5/U03nniDTrWx5NrmKdw==",
+ "dev": true,
+ "requires": {
+ "lru-cache": "4.1.x",
+ "tmp": "0.0.x"
+ }
+ },
+ "util": {
+ "version": "0.10.4",
+ "resolved": "https://registry.npmjs.org/util/-/util-0.10.4.tgz",
+ "integrity": "sha512-0Pm9hTQ3se5ll1XihRic3FDIku70C+iHUdT/W926rSgHV5QgXsYbKZN8MSC3tJtSkhuROzvsQjAaFENRXr+19A==",
+ "dev": true,
+ "requires": {
+ "inherits": "2.0.3"
+ },
+ "dependencies": {
+ "inherits": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz",
+ "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=",
+ "dev": true
+ }
+ }
+ },
+ "util-deprecate": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
+ "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=",
+ "dev": true
+ },
+ "utils-merge": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
+ "integrity": "sha1-n5VxD1CiZ5R7LMwSR0HBAoQn5xM=",
+ "dev": true
+ },
+ "uuid": {
+ "version": "3.4.0",
+ "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.4.0.tgz",
+ "integrity": "sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==",
+ "dev": true
+ },
+ "v8-compile-cache": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/v8-compile-cache/-/v8-compile-cache-2.0.3.tgz",
+ "integrity": "sha512-CNmdbwQMBjwr9Gsmohvm0pbL954tJrNzf6gWL3K+QMQf00PF7ERGrEiLgjuU3mKreLC2MeGhUsNV9ybTbLgd3w==",
+ "dev": true
+ },
+ "validate-npm-package-license": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz",
+ "integrity": "sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew==",
+ "dev": true,
+ "requires": {
+ "spdx-correct": "^3.0.0",
+ "spdx-expression-parse": "^3.0.0"
+ }
+ },
+ "verror": {
+ "version": "1.10.0",
+ "resolved": "https://registry.npmjs.org/verror/-/verror-1.10.0.tgz",
+ "integrity": "sha1-OhBcoXBTr1XW4nDB+CiGguGNpAA=",
+ "dev": true,
+ "requires": {
+ "assert-plus": "^1.0.0",
+ "core-util-is": "1.0.2",
+ "extsprintf": "^1.2.0"
+ }
+ },
+ "vm-browserify": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/vm-browserify/-/vm-browserify-1.1.2.tgz",
+ "integrity": "sha512-2ham8XPWTONajOR0ohOKOHXkm3+gaBmGut3SRuu75xLd/RRaY6vqgh8NBYYk7+RW3u5AtzPQZG8F10LHkl0lAQ==",
+ "dev": true
+ },
+ "void-elements": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/void-elements/-/void-elements-2.0.1.tgz",
+ "integrity": "sha1-wGavtYK7HLQSjWDqkjkulNXp2+w=",
+ "dev": true
+ },
+ "watchpack": {
+ "version": "1.6.0",
+ "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-1.6.0.tgz",
+ "integrity": "sha512-i6dHe3EyLjMmDlU1/bGQpEw25XSjkJULPuAVKCbNRefQVq48yXKUpwg538F7AZTf9kyr57zj++pQFltUa5H7yA==",
+ "dev": true,
+ "requires": {
+ "chokidar": "^2.0.2",
+ "graceful-fs": "^4.1.2",
+ "neo-async": "^2.5.0"
+ },
+ "dependencies": {
+ "anymatch": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-2.0.0.tgz",
+ "integrity": "sha512-5teOsQWABXHHBFP9y3skS5P3d/WfWXpv3FUpy+LorMrNYaT9pI4oLMQX7jzQ2KklNpGpWHzdCXTDT2Y3XGlZBw==",
+ "dev": true,
+ "requires": {
+ "micromatch": "^3.1.4",
+ "normalize-path": "^2.1.1"
+ },
+ "dependencies": {
+ "normalize-path": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-2.1.1.tgz",
+ "integrity": "sha1-GrKLVW4Zg2Oowab35vogE3/mrtk=",
+ "dev": true,
+ "requires": {
+ "remove-trailing-separator": "^1.0.1"
+ }
+ }
+ }
+ },
+ "arr-diff": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-4.0.0.tgz",
+ "integrity": "sha1-1kYQdP6/7HHn4VI1dhoyml3HxSA=",
+ "dev": true
+ },
+ "array-unique": {
+ "version": "0.3.2",
+ "resolved": "https://registry.npmjs.org/array-unique/-/array-unique-0.3.2.tgz",
+ "integrity": "sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg=",
+ "dev": true
+ },
+ "braces": {
+ "version": "2.3.2",
+ "resolved": "https://registry.npmjs.org/braces/-/braces-2.3.2.tgz",
+ "integrity": "sha512-aNdbnj9P8PjdXU4ybaWLK2IF3jc/EoDYbC7AazW6to3TRsfXxscC9UXOB5iDiEQrkyIbWp2SLQda4+QAa7nc3w==",
+ "dev": true,
+ "requires": {
+ "arr-flatten": "^1.1.0",
+ "array-unique": "^0.3.2",
+ "extend-shallow": "^2.0.1",
+ "fill-range": "^4.0.0",
+ "isobject": "^3.0.1",
+ "repeat-element": "^1.1.2",
+ "snapdragon": "^0.8.1",
+ "snapdragon-node": "^2.0.1",
+ "split-string": "^3.0.2",
+ "to-regex": "^3.0.1"
+ },
+ "dependencies": {
+ "extend-shallow": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz",
+ "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=",
+ "dev": true,
+ "requires": {
+ "is-extendable": "^0.1.0"
+ }
+ }
+ }
+ },
+ "chokidar": {
+ "version": "2.1.8",
+ "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-2.1.8.tgz",
+ "integrity": "sha512-ZmZUazfOzf0Nve7duiCKD23PFSCs4JPoYyccjUFF3aQkQadqBhfzhjkwBH2mNOG9cTBwhamM37EIsIkZw3nRgg==",
+ "dev": true,
+ "requires": {
+ "anymatch": "^2.0.0",
+ "async-each": "^1.0.1",
+ "braces": "^2.3.2",
+ "fsevents": "^1.2.7",
+ "glob-parent": "^3.1.0",
+ "inherits": "^2.0.3",
+ "is-binary-path": "^1.0.0",
+ "is-glob": "^4.0.0",
+ "normalize-path": "^3.0.0",
+ "path-is-absolute": "^1.0.0",
+ "readdirp": "^2.2.1",
+ "upath": "^1.1.1"
+ }
+ },
+ "debug": {
+ "version": "2.6.9",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
+ "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
+ "dev": true,
+ "requires": {
+ "ms": "2.0.0"
+ }
+ },
+ "expand-brackets": {
+ "version": "2.1.4",
+ "resolved": "https://registry.npmjs.org/expand-brackets/-/expand-brackets-2.1.4.tgz",
+ "integrity": "sha1-t3c14xXOMPa27/D4OwQVGiJEliI=",
+ "dev": true,
+ "requires": {
+ "debug": "^2.3.3",
+ "define-property": "^0.2.5",
+ "extend-shallow": "^2.0.1",
+ "posix-character-classes": "^0.1.0",
+ "regex-not": "^1.0.0",
+ "snapdragon": "^0.8.1",
+ "to-regex": "^3.0.1"
+ },
+ "dependencies": {
+ "define-property": {
+ "version": "0.2.5",
+ "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz",
+ "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=",
+ "dev": true,
+ "requires": {
+ "is-descriptor": "^0.1.0"
+ }
+ },
+ "extend-shallow": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz",
+ "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=",
+ "dev": true,
+ "requires": {
+ "is-extendable": "^0.1.0"
+ }
+ },
+ "is-accessor-descriptor": {
+ "version": "0.1.6",
+ "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz",
+ "integrity": "sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=",
+ "dev": true,
+ "requires": {
+ "kind-of": "^3.0.2"
+ },
+ "dependencies": {
+ "kind-of": {
+ "version": "3.2.2",
+ "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz",
+ "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=",
+ "dev": true,
+ "requires": {
+ "is-buffer": "^1.1.5"
+ }
+ }
+ }
+ },
+ "is-data-descriptor": {
+ "version": "0.1.4",
+ "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz",
+ "integrity": "sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=",
+ "dev": true,
+ "requires": {
+ "kind-of": "^3.0.2"
+ },
+ "dependencies": {
+ "kind-of": {
+ "version": "3.2.2",
+ "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz",
+ "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=",
+ "dev": true,
+ "requires": {
+ "is-buffer": "^1.1.5"
+ }
+ }
+ }
+ },
+ "is-descriptor": {
+ "version": "0.1.6",
+ "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-0.1.6.tgz",
+ "integrity": "sha512-avDYr0SB3DwO9zsMov0gKCESFYqCnE4hq/4z3TdUlukEy5t9C0YRq7HLrsN52NAcqXKaepeCD0n+B0arnVG3Hg==",
+ "dev": true,
+ "requires": {
+ "is-accessor-descriptor": "^0.1.6",
+ "is-data-descriptor": "^0.1.4",
+ "kind-of": "^5.0.0"
+ }
+ },
+ "kind-of": {
+ "version": "5.1.0",
+ "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-5.1.0.tgz",
+ "integrity": "sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw==",
+ "dev": true
+ }
+ }
+ },
+ "extglob": {
+ "version": "2.0.4",
+ "resolved": "https://registry.npmjs.org/extglob/-/extglob-2.0.4.tgz",
+ "integrity": "sha512-Nmb6QXkELsuBr24CJSkilo6UHHgbekK5UiZgfE6UHD3Eb27YC6oD+bhcT+tJ6cl8dmsgdQxnWlcry8ksBIBLpw==",
+ "dev": true,
+ "requires": {
+ "array-unique": "^0.3.2",
+ "define-property": "^1.0.0",
+ "expand-brackets": "^2.1.4",
+ "extend-shallow": "^2.0.1",
+ "fragment-cache": "^0.2.1",
+ "regex-not": "^1.0.0",
+ "snapdragon": "^0.8.1",
+ "to-regex": "^3.0.1"
+ },
+ "dependencies": {
+ "define-property": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/define-property/-/define-property-1.0.0.tgz",
+ "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=",
+ "dev": true,
+ "requires": {
+ "is-descriptor": "^1.0.0"
+ }
+ },
+ "extend-shallow": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz",
+ "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=",
+ "dev": true,
+ "requires": {
+ "is-extendable": "^0.1.0"
+ }
+ }
+ }
+ },
+ "fill-range": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-4.0.0.tgz",
+ "integrity": "sha1-1USBHUKPmOsGpj3EAtJAPDKMOPc=",
+ "dev": true,
+ "requires": {
+ "extend-shallow": "^2.0.1",
+ "is-number": "^3.0.0",
+ "repeat-string": "^1.6.1",
+ "to-regex-range": "^2.1.0"
+ },
+ "dependencies": {
+ "extend-shallow": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz",
+ "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=",
+ "dev": true,
+ "requires": {
+ "is-extendable": "^0.1.0"
+ }
+ }
+ }
+ },
+ "glob-parent": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-3.1.0.tgz",
+ "integrity": "sha1-nmr2KZ2NO9K9QEMIMr0RPfkGxa4=",
+ "dev": true,
+ "requires": {
+ "is-glob": "^3.1.0",
+ "path-dirname": "^1.0.0"
+ },
+ "dependencies": {
+ "is-glob": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-3.1.0.tgz",
+ "integrity": "sha1-e6WuJCF4BKxwcHuWkiVnSGzD6Eo=",
+ "dev": true,
+ "requires": {
+ "is-extglob": "^2.1.0"
+ }
+ }
+ }
+ },
+ "is-accessor-descriptor": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz",
+ "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==",
+ "dev": true,
+ "requires": {
+ "kind-of": "^6.0.0"
+ }
+ },
+ "is-data-descriptor": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz",
+ "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==",
+ "dev": true,
+ "requires": {
+ "kind-of": "^6.0.0"
+ }
+ },
+ "is-descriptor": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz",
+ "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==",
+ "dev": true,
+ "requires": {
+ "is-accessor-descriptor": "^1.0.0",
+ "is-data-descriptor": "^1.0.0",
+ "kind-of": "^6.0.2"
+ }
+ },
+ "is-extglob": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",
+ "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=",
+ "dev": true
+ },
+ "is-glob": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.1.tgz",
+ "integrity": "sha512-5G0tKtBTFImOqDnLB2hG6Bp2qcKEFduo4tZu9MT/H6NQv/ghhy30o55ufafxJ/LdH79LLs2Kfrn85TLKyA7BUg==",
+ "dev": true,
+ "requires": {
+ "is-extglob": "^2.1.1"
+ }
+ },
+ "is-number": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/is-number/-/is-number-3.0.0.tgz",
+ "integrity": "sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=",
+ "dev": true,
+ "requires": {
+ "kind-of": "^3.0.2"
+ },
+ "dependencies": {
+ "kind-of": {
+ "version": "3.2.2",
+ "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz",
+ "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=",
+ "dev": true,
+ "requires": {
+ "is-buffer": "^1.1.5"
+ }
+ }
+ }
+ },
+ "isobject": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz",
+ "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=",
+ "dev": true
+ },
+ "kind-of": {
+ "version": "6.0.3",
+ "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz",
+ "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==",
+ "dev": true
+ },
+ "micromatch": {
+ "version": "3.1.10",
+ "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-3.1.10.tgz",
+ "integrity": "sha512-MWikgl9n9M3w+bpsY3He8L+w9eF9338xRl8IAO5viDizwSzziFEyUzo2xrrloB64ADbTf8uA8vRqqttDTOmccg==",
+ "dev": true,
+ "requires": {
+ "arr-diff": "^4.0.0",
+ "array-unique": "^0.3.2",
+ "braces": "^2.3.1",
+ "define-property": "^2.0.2",
+ "extend-shallow": "^3.0.2",
+ "extglob": "^2.0.4",
+ "fragment-cache": "^0.2.1",
+ "kind-of": "^6.0.2",
+ "nanomatch": "^1.2.9",
+ "object.pick": "^1.3.0",
+ "regex-not": "^1.0.0",
+ "snapdragon": "^0.8.1",
+ "to-regex": "^3.0.2"
+ }
+ },
+ "ms": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
+ "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=",
+ "dev": true
+ },
+ "normalize-path": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz",
+ "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==",
+ "dev": true
+ }
+ }
+ },
+ "webpack": {
+ "version": "4.41.6",
+ "resolved": "https://registry.npmjs.org/webpack/-/webpack-4.41.6.tgz",
+ "integrity": "sha512-yxXfV0Zv9WMGRD+QexkZzmGIh54bsvEs+9aRWxnN8erLWEOehAKUTeNBoUbA6HPEZPlRo7KDi2ZcNveoZgK9MA==",
+ "dev": true,
+ "requires": {
+ "@webassemblyjs/ast": "1.8.5",
+ "@webassemblyjs/helper-module-context": "1.8.5",
+ "@webassemblyjs/wasm-edit": "1.8.5",
+ "@webassemblyjs/wasm-parser": "1.8.5",
+ "acorn": "^6.2.1",
+ "ajv": "^6.10.2",
+ "ajv-keywords": "^3.4.1",
+ "chrome-trace-event": "^1.0.2",
+ "enhanced-resolve": "^4.1.0",
+ "eslint-scope": "^4.0.3",
+ "json-parse-better-errors": "^1.0.2",
+ "loader-runner": "^2.4.0",
+ "loader-utils": "^1.2.3",
+ "memory-fs": "^0.4.1",
+ "micromatch": "^3.1.10",
+ "mkdirp": "^0.5.1",
+ "neo-async": "^2.6.1",
+ "node-libs-browser": "^2.2.1",
+ "schema-utils": "^1.0.0",
+ "tapable": "^1.1.3",
+ "terser-webpack-plugin": "^1.4.3",
+ "watchpack": "^1.6.0",
+ "webpack-sources": "^1.4.1"
+ },
+ "dependencies": {
+ "acorn": {
+ "version": "6.4.0",
+ "resolved": "https://registry.npmjs.org/acorn/-/acorn-6.4.0.tgz",
+ "integrity": "sha512-gac8OEcQ2Li1dxIEWGZzsp2BitJxwkwcOm0zHAJLcPJaVvm58FRnk6RkuLRpU1EujipU2ZFODv2P9DLMfnV8mw==",
+ "dev": true
+ },
+ "ajv": {
+ "version": "6.11.0",
+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.11.0.tgz",
+ "integrity": "sha512-nCprB/0syFYy9fVYU1ox1l2KN8S9I+tziH8D4zdZuLT3N6RMlGSGt5FSTpAiHB/Whv8Qs1cWHma1aMKZyaHRKA==",
+ "dev": true,
+ "requires": {
+ "fast-deep-equal": "^3.1.1",
+ "fast-json-stable-stringify": "^2.0.0",
+ "json-schema-traverse": "^0.4.1",
+ "uri-js": "^4.2.2"
+ }
+ },
+ "arr-diff": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-4.0.0.tgz",
+ "integrity": "sha1-1kYQdP6/7HHn4VI1dhoyml3HxSA=",
+ "dev": true
+ },
+ "array-unique": {
+ "version": "0.3.2",
+ "resolved": "https://registry.npmjs.org/array-unique/-/array-unique-0.3.2.tgz",
+ "integrity": "sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg=",
+ "dev": true
+ },
+ "braces": {
+ "version": "2.3.2",
+ "resolved": "https://registry.npmjs.org/braces/-/braces-2.3.2.tgz",
+ "integrity": "sha512-aNdbnj9P8PjdXU4ybaWLK2IF3jc/EoDYbC7AazW6to3TRsfXxscC9UXOB5iDiEQrkyIbWp2SLQda4+QAa7nc3w==",
+ "dev": true,
+ "requires": {
+ "arr-flatten": "^1.1.0",
+ "array-unique": "^0.3.2",
+ "extend-shallow": "^2.0.1",
+ "fill-range": "^4.0.0",
+ "isobject": "^3.0.1",
+ "repeat-element": "^1.1.2",
+ "snapdragon": "^0.8.1",
+ "snapdragon-node": "^2.0.1",
+ "split-string": "^3.0.2",
+ "to-regex": "^3.0.1"
+ },
+ "dependencies": {
+ "extend-shallow": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz",
+ "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=",
+ "dev": true,
+ "requires": {
+ "is-extendable": "^0.1.0"
+ }
+ }
+ }
+ },
+ "debug": {
+ "version": "2.6.9",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
+ "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
+ "dev": true,
+ "requires": {
+ "ms": "2.0.0"
+ }
+ },
+ "expand-brackets": {
+ "version": "2.1.4",
+ "resolved": "https://registry.npmjs.org/expand-brackets/-/expand-brackets-2.1.4.tgz",
+ "integrity": "sha1-t3c14xXOMPa27/D4OwQVGiJEliI=",
+ "dev": true,
+ "requires": {
+ "debug": "^2.3.3",
+ "define-property": "^0.2.5",
+ "extend-shallow": "^2.0.1",
+ "posix-character-classes": "^0.1.0",
+ "regex-not": "^1.0.0",
+ "snapdragon": "^0.8.1",
+ "to-regex": "^3.0.1"
+ },
+ "dependencies": {
+ "define-property": {
+ "version": "0.2.5",
+ "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz",
+ "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=",
+ "dev": true,
+ "requires": {
+ "is-descriptor": "^0.1.0"
+ }
+ },
+ "extend-shallow": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz",
+ "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=",
+ "dev": true,
+ "requires": {
+ "is-extendable": "^0.1.0"
+ }
+ },
+ "is-accessor-descriptor": {
+ "version": "0.1.6",
+ "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz",
+ "integrity": "sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=",
+ "dev": true,
+ "requires": {
+ "kind-of": "^3.0.2"
+ },
+ "dependencies": {
+ "kind-of": {
+ "version": "3.2.2",
+ "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz",
+ "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=",
+ "dev": true,
+ "requires": {
+ "is-buffer": "^1.1.5"
+ }
+ }
+ }
+ },
+ "is-data-descriptor": {
+ "version": "0.1.4",
+ "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz",
+ "integrity": "sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=",
+ "dev": true,
+ "requires": {
+ "kind-of": "^3.0.2"
+ },
+ "dependencies": {
+ "kind-of": {
+ "version": "3.2.2",
+ "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz",
+ "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=",
+ "dev": true,
+ "requires": {
+ "is-buffer": "^1.1.5"
+ }
+ }
+ }
+ },
+ "is-descriptor": {
+ "version": "0.1.6",
+ "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-0.1.6.tgz",
+ "integrity": "sha512-avDYr0SB3DwO9zsMov0gKCESFYqCnE4hq/4z3TdUlukEy5t9C0YRq7HLrsN52NAcqXKaepeCD0n+B0arnVG3Hg==",
+ "dev": true,
+ "requires": {
+ "is-accessor-descriptor": "^0.1.6",
+ "is-data-descriptor": "^0.1.4",
+ "kind-of": "^5.0.0"
+ }
+ },
+ "kind-of": {
+ "version": "5.1.0",
+ "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-5.1.0.tgz",
+ "integrity": "sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw==",
+ "dev": true
+ }
+ }
+ },
+ "extglob": {
+ "version": "2.0.4",
+ "resolved": "https://registry.npmjs.org/extglob/-/extglob-2.0.4.tgz",
+ "integrity": "sha512-Nmb6QXkELsuBr24CJSkilo6UHHgbekK5UiZgfE6UHD3Eb27YC6oD+bhcT+tJ6cl8dmsgdQxnWlcry8ksBIBLpw==",
+ "dev": true,
+ "requires": {
+ "array-unique": "^0.3.2",
+ "define-property": "^1.0.0",
+ "expand-brackets": "^2.1.4",
+ "extend-shallow": "^2.0.1",
+ "fragment-cache": "^0.2.1",
+ "regex-not": "^1.0.0",
+ "snapdragon": "^0.8.1",
+ "to-regex": "^3.0.1"
+ },
+ "dependencies": {
+ "define-property": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/define-property/-/define-property-1.0.0.tgz",
+ "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=",
+ "dev": true,
+ "requires": {
+ "is-descriptor": "^1.0.0"
+ }
+ },
+ "extend-shallow": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz",
+ "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=",
+ "dev": true,
+ "requires": {
+ "is-extendable": "^0.1.0"
+ }
+ }
+ }
+ },
+ "fast-deep-equal": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.1.tgz",
+ "integrity": "sha512-8UEa58QDLauDNfpbrX55Q9jrGHThw2ZMdOky5Gl1CDtVeJDPVrG4Jxx1N8jw2gkWaff5UUuX1KJd+9zGe2B+ZA==",
+ "dev": true
+ },
+ "fill-range": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-4.0.0.tgz",
+ "integrity": "sha1-1USBHUKPmOsGpj3EAtJAPDKMOPc=",
+ "dev": true,
+ "requires": {
+ "extend-shallow": "^2.0.1",
+ "is-number": "^3.0.0",
+ "repeat-string": "^1.6.1",
+ "to-regex-range": "^2.1.0"
+ },
+ "dependencies": {
+ "extend-shallow": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz",
+ "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=",
+ "dev": true,
+ "requires": {
+ "is-extendable": "^0.1.0"
+ }
+ }
+ }
+ },
+ "is-accessor-descriptor": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz",
+ "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==",
+ "dev": true,
+ "requires": {
+ "kind-of": "^6.0.0"
+ }
+ },
+ "is-data-descriptor": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz",
+ "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==",
+ "dev": true,
+ "requires": {
+ "kind-of": "^6.0.0"
+ }
+ },
+ "is-descriptor": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz",
+ "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==",
+ "dev": true,
+ "requires": {
+ "is-accessor-descriptor": "^1.0.0",
+ "is-data-descriptor": "^1.0.0",
+ "kind-of": "^6.0.2"
+ }
+ },
+ "is-number": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/is-number/-/is-number-3.0.0.tgz",
+ "integrity": "sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=",
+ "dev": true,
+ "requires": {
+ "kind-of": "^3.0.2"
+ },
+ "dependencies": {
+ "kind-of": {
+ "version": "3.2.2",
+ "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz",
+ "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=",
+ "dev": true,
+ "requires": {
+ "is-buffer": "^1.1.5"
+ }
+ }
+ }
+ },
+ "isobject": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz",
+ "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=",
+ "dev": true
+ },
+ "json-schema-traverse": {
+ "version": "0.4.1",
+ "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz",
+ "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==",
+ "dev": true
+ },
+ "kind-of": {
+ "version": "6.0.3",
+ "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz",
+ "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==",
+ "dev": true
+ },
+ "micromatch": {
+ "version": "3.1.10",
+ "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-3.1.10.tgz",
+ "integrity": "sha512-MWikgl9n9M3w+bpsY3He8L+w9eF9338xRl8IAO5viDizwSzziFEyUzo2xrrloB64ADbTf8uA8vRqqttDTOmccg==",
+ "dev": true,
+ "requires": {
+ "arr-diff": "^4.0.0",
+ "array-unique": "^0.3.2",
+ "braces": "^2.3.1",
+ "define-property": "^2.0.2",
+ "extend-shallow": "^3.0.2",
+ "extglob": "^2.0.4",
+ "fragment-cache": "^0.2.1",
+ "kind-of": "^6.0.2",
+ "nanomatch": "^1.2.9",
+ "object.pick": "^1.3.0",
+ "regex-not": "^1.0.0",
+ "snapdragon": "^0.8.1",
+ "to-regex": "^3.0.2"
+ }
+ },
+ "ms": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
+ "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=",
+ "dev": true
+ },
+ "schema-utils": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-1.0.0.tgz",
+ "integrity": "sha512-i27Mic4KovM/lnGsy8whRCHhc7VicJajAjTrYg11K9zfZXnYIt4k5F+kZkwjnrhKzLic/HLU4j11mjsz2G/75g==",
+ "dev": true,
+ "requires": {
+ "ajv": "^6.1.0",
+ "ajv-errors": "^1.0.0",
+ "ajv-keywords": "^3.1.0"
+ }
+ }
+ }
+ },
+ "webpack-cli": {
+ "version": "3.3.11",
+ "resolved": "https://registry.npmjs.org/webpack-cli/-/webpack-cli-3.3.11.tgz",
+ "integrity": "sha512-dXlfuml7xvAFwYUPsrtQAA9e4DOe58gnzSxhgrO/ZM/gyXTBowrsYeubyN4mqGhYdpXMFNyQ6emjJS9M7OBd4g==",
+ "dev": true,
+ "requires": {
+ "chalk": "2.4.2",
+ "cross-spawn": "6.0.5",
+ "enhanced-resolve": "4.1.0",
+ "findup-sync": "3.0.0",
+ "global-modules": "2.0.0",
+ "import-local": "2.0.0",
+ "interpret": "1.2.0",
+ "loader-utils": "1.2.3",
+ "supports-color": "6.1.0",
+ "v8-compile-cache": "2.0.3",
+ "yargs": "13.2.4"
+ },
+ "dependencies": {
+ "ansi-regex": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz",
+ "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==",
+ "dev": true
+ },
+ "cross-spawn": {
+ "version": "6.0.5",
+ "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz",
+ "integrity": "sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==",
+ "dev": true,
+ "requires": {
+ "nice-try": "^1.0.4",
+ "path-key": "^2.0.1",
+ "semver": "^5.5.0",
+ "shebang-command": "^1.2.0",
+ "which": "^1.2.9"
+ }
+ },
+ "enhanced-resolve": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-4.1.0.tgz",
+ "integrity": "sha512-F/7vkyTtyc/llOIn8oWclcB25KdRaiPBpZYDgJHgh/UHtpgT2p2eldQgtQnLtUvfMKPKxbRaQM/hHkvLHt1Vng==",
+ "dev": true,
+ "requires": {
+ "graceful-fs": "^4.1.2",
+ "memory-fs": "^0.4.0",
+ "tapable": "^1.0.0"
+ }
+ },
+ "invert-kv": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/invert-kv/-/invert-kv-2.0.0.tgz",
+ "integrity": "sha512-wPVv/y/QQ/Uiirj/vh3oP+1Ww+AWehmi1g5fFWGPF6IpCBCDVrhgHRMvrLfdYcwDh3QJbGXDW4JAuzxElLSqKA==",
+ "dev": true
+ },
+ "lcid": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/lcid/-/lcid-2.0.0.tgz",
+ "integrity": "sha512-avPEb8P8EGnwXKClwsNUgryVjllcRqtMYa49NTsbQagYuT1DcXnl1915oxWjoyGrXR6zH/Y0Zc96xWsPcoDKeA==",
+ "dev": true,
+ "requires": {
+ "invert-kv": "^2.0.0"
+ }
+ },
+ "os-locale": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/os-locale/-/os-locale-3.1.0.tgz",
+ "integrity": "sha512-Z8l3R4wYWM40/52Z+S265okfFj8Kt2cC2MKY+xNi3kFs+XGI7WXu/I309QQQYbRW4ijiZ+yxs9pqEhJh0DqW3Q==",
+ "dev": true,
+ "requires": {
+ "execa": "^1.0.0",
+ "lcid": "^2.0.0",
+ "mem": "^4.0.0"
+ }
+ },
+ "string-width": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz",
+ "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==",
+ "dev": true,
+ "requires": {
+ "emoji-regex": "^7.0.1",
+ "is-fullwidth-code-point": "^2.0.0",
+ "strip-ansi": "^5.1.0"
+ }
+ },
+ "strip-ansi": {
+ "version": "5.2.0",
+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz",
+ "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==",
+ "dev": true,
+ "requires": {
+ "ansi-regex": "^4.1.0"
+ }
+ },
+ "supports-color": {
+ "version": "6.1.0",
+ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-6.1.0.tgz",
+ "integrity": "sha512-qe1jfm1Mg7Nq/NSh6XE24gPXROEVsWHxC1LIx//XNlD9iw7YZQGjZNjYN7xGaEG6iKdA8EtNFW6R0gjnVXp+wQ==",
+ "dev": true,
+ "requires": {
+ "has-flag": "^3.0.0"
+ }
+ },
+ "yargs": {
+ "version": "13.2.4",
+ "resolved": "https://registry.npmjs.org/yargs/-/yargs-13.2.4.tgz",
+ "integrity": "sha512-HG/DWAJa1PAnHT9JAhNa8AbAv3FPaiLzioSjCcmuXXhP8MlpHO5vwls4g4j6n30Z74GVQj8Xa62dWVx1QCGklg==",
+ "dev": true,
+ "requires": {
+ "cliui": "^5.0.0",
+ "find-up": "^3.0.0",
+ "get-caller-file": "^2.0.1",
+ "os-locale": "^3.1.0",
+ "require-directory": "^2.1.1",
+ "require-main-filename": "^2.0.0",
+ "set-blocking": "^2.0.0",
+ "string-width": "^3.0.0",
+ "which-module": "^2.0.0",
+ "y18n": "^4.0.0",
+ "yargs-parser": "^13.1.0"
+ }
+ }
+ }
+ },
+ "webpack-dev-middleware": {
+ "version": "3.7.2",
+ "resolved": "https://registry.npmjs.org/webpack-dev-middleware/-/webpack-dev-middleware-3.7.2.tgz",
+ "integrity": "sha512-1xC42LxbYoqLNAhV6YzTYacicgMZQTqRd27Sim9wn5hJrX3I5nxYy1SxSd4+gjUFsz1dQFj+yEe6zEVmSkeJjw==",
+ "dev": true,
+ "requires": {
+ "memory-fs": "^0.4.1",
+ "mime": "^2.4.4",
+ "mkdirp": "^0.5.1",
+ "range-parser": "^1.2.1",
+ "webpack-log": "^2.0.0"
+ }
+ },
+ "webpack-log": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/webpack-log/-/webpack-log-2.0.0.tgz",
+ "integrity": "sha512-cX8G2vR/85UYG59FgkoMamwHUIkSSlV3bBMRsbxVXVUk2j6NleCKjQ/WE9eYg9WY4w25O9w8wKP4rzNZFmUcUg==",
+ "dev": true,
+ "requires": {
+ "ansi-colors": "^3.0.0",
+ "uuid": "^3.3.2"
+ }
+ },
+ "webpack-sources": {
+ "version": "1.4.3",
+ "resolved": "https://registry.npmjs.org/webpack-sources/-/webpack-sources-1.4.3.tgz",
+ "integrity": "sha512-lgTS3Xhv1lCOKo7SA5TjKXMjpSM4sBjNV5+q2bqesbSPs5FjGmU6jjtBSkX9b4qW87vDIsCIlUPOEhbZrMdjeQ==",
+ "dev": true,
+ "requires": {
+ "source-list-map": "^2.0.0",
+ "source-map": "~0.6.1"
+ },
+ "dependencies": {
+ "source-map": {
+ "version": "0.6.1",
+ "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
+ "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",
+ "dev": true
+ }
+ }
+ },
+ "which": {
+ "version": "1.3.1",
+ "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz",
+ "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==",
+ "dev": true,
+ "requires": {
+ "isexe": "^2.0.0"
+ }
+ },
+ "which-module": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.0.tgz",
+ "integrity": "sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho=",
+ "dev": true
+ },
+ "wide-align": {
+ "version": "1.1.3",
+ "resolved": "https://registry.npmjs.org/wide-align/-/wide-align-1.1.3.tgz",
+ "integrity": "sha512-QGkOQc8XL6Bt5PwnsExKBPuMKBxnGxWWW3fU55Xt4feHozMUhdUMaBCk290qpm/wG5u/RSKzwdAC4i51YigihA==",
+ "dev": true,
+ "requires": {
+ "string-width": "^1.0.2 || 2"
+ }
+ },
+ "word-wrap": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.3.tgz",
+ "integrity": "sha512-Hz/mrNwitNRh/HUAtM/VT/5VH+ygD6DV7mYKZAtHOrbs8U7lvPS6xf7EJKMF0uW1KJCl0H701g3ZGus+muE5vQ==",
+ "dev": true
+ },
+ "wordwrap": {
+ "version": "0.0.3",
+ "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-0.0.3.tgz",
+ "integrity": "sha1-o9XabNXAvAAI03I0u68b7WMFkQc=",
+ "dev": true
+ },
+ "worker-farm": {
+ "version": "1.7.0",
+ "resolved": "https://registry.npmjs.org/worker-farm/-/worker-farm-1.7.0.tgz",
+ "integrity": "sha512-rvw3QTZc8lAxyVrqcSGVm5yP/IJ2UcB3U0graE3LCFoZ0Yn2x4EoVSqJKdB/T5M+FLcRPjz4TDacRf3OCfNUzw==",
+ "dev": true,
+ "requires": {
+ "errno": "~0.1.7"
+ }
+ },
+ "wrap-ansi": {
+ "version": "5.1.0",
+ "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-5.1.0.tgz",
+ "integrity": "sha512-QC1/iN/2/RPVJ5jYK8BGttj5z83LmSKmvbvrXPNCLZSEb32KKVDJDl/MOt2N01qU2H/FkzEa9PKto1BqDjtd7Q==",
+ "dev": true,
+ "requires": {
+ "ansi-styles": "^3.2.0",
+ "string-width": "^3.0.0",
+ "strip-ansi": "^5.0.0"
+ },
+ "dependencies": {
+ "ansi-regex": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz",
+ "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==",
+ "dev": true
+ },
+ "string-width": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz",
+ "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==",
+ "dev": true,
+ "requires": {
+ "emoji-regex": "^7.0.1",
+ "is-fullwidth-code-point": "^2.0.0",
+ "strip-ansi": "^5.1.0"
+ }
+ },
+ "strip-ansi": {
+ "version": "5.2.0",
+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz",
+ "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==",
+ "dev": true,
+ "requires": {
+ "ansi-regex": "^4.1.0"
+ }
+ }
+ }
+ },
+ "wrappy": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
+ "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=",
+ "dev": true
+ },
+ "write": {
+ "version": "0.2.1",
+ "resolved": "https://registry.npmjs.org/write/-/write-0.2.1.tgz",
+ "integrity": "sha1-X8A4KOJkzqP+kUVUdvejxWbLB1c=",
+ "dev": true,
+ "requires": {
+ "mkdirp": "^0.5.1"
+ }
+ },
+ "ws": {
+ "version": "3.3.3",
+ "resolved": "https://registry.npmjs.org/ws/-/ws-3.3.3.tgz",
+ "integrity": "sha512-nnWLa/NwZSt4KQJu51MYlCcSQ5g7INpOrOMt4XV8j4dqTXdmlUmSHQ8/oLC069ckre0fRsgfvsKwbTdtKLCDkA==",
+ "dev": true,
+ "requires": {
+ "async-limiter": "~1.0.0",
+ "safe-buffer": "~5.1.0",
+ "ultron": "~1.1.0"
+ }
+ },
+ "xmlhttprequest-ssl": {
+ "version": "1.5.5",
+ "resolved": "https://registry.npmjs.org/xmlhttprequest-ssl/-/xmlhttprequest-ssl-1.5.5.tgz",
+ "integrity": "sha1-wodrBhaKrcQOV9l+gRkayPQ5iz4=",
+ "dev": true
+ },
+ "xtend": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
+ "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==",
+ "dev": true
+ },
+ "y18n": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.0.tgz",
+ "integrity": "sha512-r9S/ZyXu/Xu9q1tYlpsLIsa3EeLXXk0VwlxqTcFRfg9EhMW+17kbt9G0NrgCmhGb5vT2hyhJZLfDGx+7+5Uj/w==",
+ "dev": true
+ },
+ "yallist": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/yallist/-/yallist-2.1.2.tgz",
+ "integrity": "sha1-HBH5IY8HYImkfdUS+TxmmaaoHVI=",
+ "dev": true
+ },
+ "yamljs": {
+ "version": "0.3.0",
+ "resolved": "https://registry.npmjs.org/yamljs/-/yamljs-0.3.0.tgz",
+ "integrity": "sha512-C/FsVVhht4iPQYXOInoxUM/1ELSf9EsgKH34FofQOp6hwCPrW4vG4w5++TED3xRUo8gD7l0P1J1dLlDYzODsTQ==",
+ "dev": true,
+ "requires": {
+ "argparse": "^1.0.7",
+ "glob": "^7.0.5"
+ }
+ },
+ "yamscripts": {
+ "version": "0.1.0",
+ "resolved": "https://registry.npmjs.org/yamscripts/-/yamscripts-0.1.0.tgz",
+ "integrity": "sha512-i4ThS58KwsK83qSrrc8YZiBqgdl3WewWcWZ4fPdrh7A+qiRU9kXMcIKzngOC7VpJ2nTsWvHG6TcK3JHXpBxACA==",
+ "dev": true,
+ "requires": {
+ "colors": "^1.3.2",
+ "fs-extra": "^7.0.0",
+ "minimist": "^1.2.0",
+ "yamljs": "^0.3.0"
+ }
+ },
+ "yargs": {
+ "version": "13.3.0",
+ "resolved": "https://registry.npmjs.org/yargs/-/yargs-13.3.0.tgz",
+ "integrity": "sha512-2eehun/8ALW8TLoIl7MVaRUrg+yCnenu8B4kBlRxj3GJGDKU1Og7sMXPNm1BYyM1DOJmTZ4YeN/Nwxv+8XJsUA==",
+ "dev": true,
+ "requires": {
+ "cliui": "^5.0.0",
+ "find-up": "^3.0.0",
+ "get-caller-file": "^2.0.1",
+ "require-directory": "^2.1.1",
+ "require-main-filename": "^2.0.0",
+ "set-blocking": "^2.0.0",
+ "string-width": "^3.0.0",
+ "which-module": "^2.0.0",
+ "y18n": "^4.0.0",
+ "yargs-parser": "^13.1.1"
+ },
+ "dependencies": {
+ "ansi-regex": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz",
+ "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==",
+ "dev": true
+ },
+ "string-width": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz",
+ "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==",
+ "dev": true,
+ "requires": {
+ "emoji-regex": "^7.0.1",
+ "is-fullwidth-code-point": "^2.0.0",
+ "strip-ansi": "^5.1.0"
+ }
+ },
+ "strip-ansi": {
+ "version": "5.2.0",
+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz",
+ "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==",
+ "dev": true,
+ "requires": {
+ "ansi-regex": "^4.1.0"
+ }
+ }
+ }
+ },
+ "yargs-parser": {
+ "version": "13.1.1",
+ "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-13.1.1.tgz",
+ "integrity": "sha512-oVAVsHz6uFrg3XQheFII8ESO2ssAf9luWuAd6Wexsu4F3OtIW0o8IribPXYrD4WC24LWtPrJlGy87y5udK+dxQ==",
+ "dev": true,
+ "requires": {
+ "camelcase": "^5.0.0",
+ "decamelize": "^1.2.0"
+ }
+ },
+ "yargs-unparser": {
+ "version": "1.6.0",
+ "resolved": "https://registry.npmjs.org/yargs-unparser/-/yargs-unparser-1.6.0.tgz",
+ "integrity": "sha512-W9tKgmSn0DpSatfri0nx52Joq5hVXgeLiqR/5G0sZNDoLZFOr/xjBUDcShCOGNsBnEMNo1KAMBkTej1Hm62HTw==",
+ "dev": true,
+ "requires": {
+ "flat": "^4.1.0",
+ "lodash": "^4.17.15",
+ "yargs": "^13.3.0"
+ }
+ },
+ "yeast": {
+ "version": "0.1.2",
+ "resolved": "https://registry.npmjs.org/yeast/-/yeast-0.1.2.tgz",
+ "integrity": "sha1-AI4G2AlDIMNy28L47XagymyKxBk=",
+ "dev": true
+ }
+ }
+}
diff --git a/browser/components/newtab/package.json b/browser/components/newtab/package.json
new file mode 100644
index 0000000000..e7faa86a3b
--- /dev/null
+++ b/browser/components/newtab/package.json
@@ -0,0 +1,126 @@
+{
+ "name": "activity-streams",
+ "description": "A rich visual history feed and a reimagined home page make it easier than ever to find exactly what you're looking for in Firefox.\n\nLearn more about this Test Pilot experiment at https://testpilot.firefox.com/.",
+ "version": "1.14.3",
+ "author": "Mozilla (https://mozilla.org/)",
+ "bugs": {
+ "url": "https://github.com/mozilla/activity-stream/issues"
+ },
+ "dependencies": {
+ "fluent": "0.13.0",
+ "fluent-react": "0.9.0",
+ "react": "16.13.1",
+ "react-dom": "16.13.1",
+ "react-redux": "7.2.0",
+ "react-transition-group": "4.3.0",
+ "redux": "4.0.5",
+ "reselect": "4.0.0"
+ },
+ "devDependencies": {
+ "@babel/core": "7.8.4",
+ "@babel/plugin-proposal-class-properties": "7.10.4",
+ "@babel/plugin-proposal-nullish-coalescing-operator": "7.8.3",
+ "@babel/plugin-proposal-optional-chaining": "7.9.0",
+ "@babel/preset-react": "7.8.3",
+ "acorn": "7.1.0",
+ "babel-loader": "8.0.6",
+ "babel-plugin-jsm-to-commonjs": "0.5.0",
+ "babel-plugin-jsm-to-esmodules": "0.6.0",
+ "chai": "4.2.0",
+ "chai-json-schema": "1.5.1",
+ "cpx": "1.5.0",
+ "enzyme": "3.11.0",
+ "enzyme-adapter-react-16": "1.15.2",
+ "istanbul-instrumenter-loader": "3.0.1",
+ "joi-browser": "13.4.0",
+ "karma": "4.4.1",
+ "karma-chai": "0.1.0",
+ "karma-coverage-istanbul-reporter": "2.1.1",
+ "karma-firefox-launcher": "1.3.0",
+ "karma-json-reporter": "1.2.1",
+ "karma-mocha": "1.3.0",
+ "karma-mocha-reporter": "2.2.5",
+ "karma-sinon": "1.0.5",
+ "karma-sourcemap-loader": "0.3.7",
+ "karma-webpack": "4.0.2",
+ "loader-utils": "1.2.3",
+ "lodash": "4.17.15",
+ "minimist": "1.2.0",
+ "mocha": "7.0.1",
+ "mock-raf": "1.0.1",
+ "node-fetch": "2.6.0",
+ "node-sass": "4.13.1",
+ "npm-run-all": "4.1.5",
+ "prop-types": "15.7.2",
+ "raw-loader": "4.0.0",
+ "react-test-renderer": "16.12.0",
+ "rimraf": "3.0.2",
+ "sass": "1.25.0",
+ "sass-lint": "1.13.1",
+ "shelljs": "0.8.3",
+ "sinon": "7.3.2",
+ "webpack": "4.41.6",
+ "webpack-cli": "3.3.11",
+ "yamscripts": "0.1.0"
+ },
+ "engines": {
+ "firefox": ">=45.0 <=*",
+ "//": "when changing node versions, also edit .nvmrc",
+ "node": "10.23.*",
+ "npm": "6.14.10"
+ },
+ "homepage": "https://github.com/mozilla/activity-stream",
+ "keywords": [
+ "mozilla",
+ "firefox",
+ "activity-stream"
+ ],
+ "license": "MPL-2.0",
+ "main": "bootstrap.js",
+ "repository": "mozilla/activity-stream",
+ "config": {
+ "mc_root": "../../..",
+ "newtab_path": "browser/components/newtab",
+ "mc_dir": "../mozilla-central"
+ },
+ "scripts": {
+ "mochitest": "(cd $npm_package_config_mc_dir && ./mach mochitest browser/components/newtab/test/browser --headless)",
+ "mochitest-debug": "(cd $npm_package_config_mc_dir && ./mach mochitest --jsdebugger browser/components/newtab/test/browser)",
+ "bundle": "npm-run-all bundle:*",
+ "bundle:webpack": "webpack --config webpack.system-addon.config.js",
+ "bundle:css": "node-sass content-src/styles -o css && node-sass content-src/aboutwelcome -o aboutwelcome/content",
+ "bundle:welcomeBundle": "webpack --config webpack.aboutwelcome.config.js",
+ "bundle:html": "rimraf prerendered && node ./bin/render-activity-stream-html.js",
+ "buildmc": "npm-run-all buildmc:*",
+ "buildmc:bundle": "npm run bundle",
+ "watchmc": "npm-run-all --parallel watchmc:*",
+ "watchmc:webpack": "npm run bundle:webpack -- --env.development -w",
+ "watchmc:welcomeBundle": "npm run bundle:welcomeBundle -- --env.development -w",
+ "watchmc:css": "npm run bundle:css && npm run bundle:css -- --source-map-embed --source-map-contents -w",
+ "testmc": "npm-run-all testmc:*",
+ "testmc:lint": "npm run lint",
+ "testmc:build": "npm run bundle:webpack",
+ "testmc:unit": "karma start karma.mc.config.js",
+ "tddmc": "karma start karma.mc.config.js --tdd",
+ "debugcoverage": "open logs/coverage/index.html",
+ "lint": "npm-run-all lint:*",
+ "lint:codespell": "(cd $npm_package_config_mc_root && ./mach lint -l codespell $npm_package_config_newtab_path)",
+ "lint:eslint": "(cd $npm_package_config_mc_root && ./mach lint -l eslint $npm_package_config_newtab_path)",
+ "lint:l10n": "(cd $npm_package_config_mc_root && ./mach lint -l l10n --warnings browser/locales/en-US/browser/newtab)",
+ "lint:license": "(cd $npm_package_config_mc_root && ./mach lint -l license $npm_package_config_newtab_path)",
+ "lint:sasslint": "sass-lint -v -q",
+ "test": "npm run testmc",
+ "tdd": "npm run tddmc",
+ "vendor": "node ./bin/vendor.js",
+ "fix": "npm-run-all fix:*",
+ "fix:eslint": "npm run lint:eslint -- --fix",
+ "help": "yamscripts help",
+ "yamscripts": "yamscripts compile",
+ "__": "# NOTE: THESE SCRIPTS ARE COMPILED!!! EDIT yamscripts.yml instead!!!"
+ },
+ "title": "Activity Stream",
+ "permissions": {
+ "multiprocess": true,
+ "private-browsing": true
+ }
+}
diff --git a/browser/components/newtab/prerendered/activity-stream-debug.html b/browser/components/newtab/prerendered/activity-stream-debug.html
new file mode 100644
index 0000000000..7f99220ba1
--- /dev/null
+++ b/browser/components/newtab/prerendered/activity-stream-debug.html
@@ -0,0 +1,33 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ - You can obtain one at http://mozilla.org/MPL/2.0/. -->
+
+<!doctype html>
+<html>
+ <head>
+ <meta charset="utf-8">
+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; object-src 'none'; script-src resource: chrome:; connect-src https:; img-src https: data: blob:; style-src 'unsafe-inline';">
+ <title data-l10n-id="newtab-page-title"></title>
+ <link rel="icon" type="image/png" href="chrome://branding/content/icon32.png"/>
+ <link rel="localization" href="branding/brand.ftl" />
+ <link rel="localization" href="browser/branding/brandings.ftl" />
+ <link rel="localization" href="browser/newtab/newtab.ftl" />
+ <link rel="stylesheet" href="chrome://browser/content/contentSearchUI.css" />
+ <link rel="stylesheet" href="chrome://activity-stream/content/css/activity-stream.css" />
+ </head>
+ <body class="activity-stream">
+ <div id="root"></div>
+ <div id="footer-asrouter-container" role="presentation"></div>
+ <script src="chrome://browser/content/contentSearchUI.js"></script>
+ <script src="chrome://browser/content/contentSearchHandoffUI.js"></script>
+ <script src="chrome://browser/content/contentTheme.js"></script>
+ <script src="resource://activity-stream/vendor/react-dev.js"></script>
+ <script src="resource://activity-stream/vendor/react-dom-dev.js"></script>
+ <script src="resource://activity-stream/vendor/prop-types.js"></script>
+ <script src="resource://activity-stream/vendor/redux.js"></script>
+ <script src="resource://activity-stream/vendor/react-redux.js"></script>
+ <script src="resource://activity-stream/vendor/react-transition-group.js"></script>
+ <script src="resource://activity-stream/data/content/activity-stream.bundle.js"></script>
+ <script src="resource://activity-stream/data/content/newtab-render.js"></script>
+ </body>
+</html>
diff --git a/browser/components/newtab/prerendered/activity-stream-noscripts.html b/browser/components/newtab/prerendered/activity-stream-noscripts.html
new file mode 100644
index 0000000000..0eaaeeec07
--- /dev/null
+++ b/browser/components/newtab/prerendered/activity-stream-noscripts.html
@@ -0,0 +1,22 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ - You can obtain one at http://mozilla.org/MPL/2.0/. -->
+
+<!doctype html>
+<html>
+ <head>
+ <meta charset="utf-8">
+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; object-src 'none'; script-src resource: chrome:; connect-src https:; img-src https: data: blob:; style-src 'unsafe-inline';">
+ <title data-l10n-id="newtab-page-title"></title>
+ <link rel="icon" type="image/png" href="chrome://branding/content/icon32.png"/>
+ <link rel="localization" href="branding/brand.ftl" />
+ <link rel="localization" href="browser/branding/brandings.ftl" />
+ <link rel="localization" href="browser/newtab/newtab.ftl" />
+ <link rel="stylesheet" href="chrome://browser/content/contentSearchUI.css" />
+ <link rel="stylesheet" href="chrome://activity-stream/content/css/activity-stream.css" />
+ </head>
+ <body class="activity-stream">
+ <div id="root"></div>
+ <div id="footer-asrouter-container" role="presentation"></div>
+ </body>
+</html>
diff --git a/browser/components/newtab/prerendered/activity-stream.html b/browser/components/newtab/prerendered/activity-stream.html
new file mode 100644
index 0000000000..381ae79701
--- /dev/null
+++ b/browser/components/newtab/prerendered/activity-stream.html
@@ -0,0 +1,33 @@
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ - You can obtain one at http://mozilla.org/MPL/2.0/. -->
+
+<!doctype html>
+<html>
+ <head>
+ <meta charset="utf-8">
+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; object-src 'none'; script-src resource: chrome:; connect-src https:; img-src https: data: blob:; style-src 'unsafe-inline';">
+ <title data-l10n-id="newtab-page-title"></title>
+ <link rel="icon" type="image/png" href="chrome://branding/content/icon32.png"/>
+ <link rel="localization" href="branding/brand.ftl" />
+ <link rel="localization" href="browser/branding/brandings.ftl" />
+ <link rel="localization" href="browser/newtab/newtab.ftl" />
+ <link rel="stylesheet" href="chrome://browser/content/contentSearchUI.css" />
+ <link rel="stylesheet" href="chrome://activity-stream/content/css/activity-stream.css" />
+ </head>
+ <body class="activity-stream">
+ <div id="root"></div>
+ <div id="footer-asrouter-container" role="presentation"></div>
+ <script src="chrome://browser/content/contentSearchUI.js"></script>
+ <script src="chrome://browser/content/contentSearchHandoffUI.js"></script>
+ <script src="chrome://browser/content/contentTheme.js"></script>
+ <script src="resource://activity-stream/vendor/react.js"></script>
+ <script src="resource://activity-stream/vendor/react-dom.js"></script>
+ <script src="resource://activity-stream/vendor/prop-types.js"></script>
+ <script src="resource://activity-stream/vendor/redux.js"></script>
+ <script src="resource://activity-stream/vendor/react-redux.js"></script>
+ <script src="resource://activity-stream/vendor/react-transition-group.js"></script>
+ <script src="resource://activity-stream/data/content/activity-stream.bundle.js"></script>
+ <script src="resource://activity-stream/data/content/newtab-render.js"></script>
+ </body>
+</html>
diff --git a/browser/components/newtab/test/.eslintrc.js b/browser/components/newtab/test/.eslintrc.js
new file mode 100644
index 0000000000..621f781337
--- /dev/null
+++ b/browser/components/newtab/test/.eslintrc.js
@@ -0,0 +1,19 @@
+/* eslint-disable import/no-commonjs */
+
+module.exports = {
+ env: {
+ mocha: true,
+ },
+ globals: {
+ assert: true,
+ chai: true,
+ sinon: true,
+ },
+ rules: {
+ "func-name-matching": 0,
+ "import/no-commonjs": 2,
+ "lines-between-class-members": 0,
+ "react/jsx-no-bind": 0,
+ "require-await": 0,
+ },
+};
diff --git a/browser/components/newtab/test/browser/abouthomecache/browser.ini b/browser/components/newtab/test/browser/abouthomecache/browser.ini
new file mode 100644
index 0000000000..2bc08808c9
--- /dev/null
+++ b/browser/components/newtab/test/browser/abouthomecache/browser.ini
@@ -0,0 +1,35 @@
+[DEFAULT]
+skip-if = tsan #Bug 1677049
+support-files =
+ head.js
+ ../ds_layout.json
+ ../topstories.json
+prefs =
+ browser.tabs.remote.separatePrivilegedContentProcess=true
+ browser.startup.homepage.abouthome_cache.enabled=true
+ browser.startup.homepage.abouthome_cache.cache_on_shutdown=false
+ browser.startup.homepage.abouthome_cache.loglevel=All
+ browser.startup.homepage.abouthome_cache.testing=true
+ browser.startup.page=1
+ browser.newtabpage.activity-stream.discoverystream.endpoints=data:
+ browser.newtabpage.activity-stream.feeds.system.topstories=true
+ browser.newtabpage.activity-stream.feeds.section.topstories=true
+ browser.newtabpage.activity-stream.feeds.system.topstories=true
+ browser.newtabpage.activity-stream.feeds.section.topstories.options={"provider_name":""}
+ browser.newtabpage.activity-stream.telemetry.structuredIngestion=false
+ browser.ping-centre.telemetry=false
+ browser.newtabpage.activity-stream.discoverystream.endpoints=https://example.com
+
+[browser_basic_endtoend.js]
+skip-if = asan || tsan || debug #Bug 1651277
+[browser_bump_version.js]
+[browser_disabled.js]
+[browser_locale_change.js]
+[browser_no_cache.js]
+[browser_no_startup_actions.js]
+[browser_overwrite_cache.js]
+[browser_process_crash.js]
+skip-if = !e10s || !crashreporter
+[browser_same_consumer.js]
+[browser_sanitize.js]
+[browser_shutdown_timeout.js]
diff --git a/browser/components/newtab/test/browser/abouthomecache/browser_basic_endtoend.js b/browser/components/newtab/test/browser/abouthomecache/browser_basic_endtoend.js
new file mode 100644
index 0000000000..a2e984509d
--- /dev/null
+++ b/browser/components/newtab/test/browser/abouthomecache/browser_basic_endtoend.js
@@ -0,0 +1,22 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests that the about:home cache gets written on shutdown, and read
+ * from in the subsequent startup.
+ */
+add_task(async function test_basic_behaviour() {
+ await BrowserTestUtils.withNewTab("about:home", async browser => {
+ // First, clear the cache to test the base case.
+ await clearCache();
+ await simulateRestart(browser);
+ await ensureCachedAboutHome(browser);
+
+ // Next, test that a subsequent restart also shows the cached
+ // about:home.
+ await simulateRestart(browser);
+ await ensureCachedAboutHome(browser);
+ });
+});
diff --git a/browser/components/newtab/test/browser/abouthomecache/browser_bump_version.js b/browser/components/newtab/test/browser/abouthomecache/browser_bump_version.js
new file mode 100644
index 0000000000..daedcfa3e7
--- /dev/null
+++ b/browser/components/newtab/test/browser/abouthomecache/browser_bump_version.js
@@ -0,0 +1,29 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test that if the "version" metadata on the cache entry doesn't match
+ * the expectation that we ignore the cache and load the dynamic about:home
+ * document.
+ */
+add_task(async function test_bump_version() {
+ await BrowserTestUtils.withNewTab("about:home", async browser => {
+ // First, ensure that a pre-existing cache exists.
+ await simulateRestart(browser);
+
+ let cacheEntry = await AboutHomeStartupCache.ensureCacheEntry();
+ Assert.equal(
+ cacheEntry.getMetaDataElement("version"),
+ Services.appinfo.appBuildID,
+ "Cache entry should be versioned on the build ID"
+ );
+ cacheEntry.setMetaDataElement("version", "somethingnew");
+ await simulateRestart(browser, false /* withAutoShutdownWrite */);
+ await ensureDynamicAboutHome(
+ browser,
+ AboutHomeStartupCache.CACHE_RESULT_SCALARS.INVALIDATED
+ );
+ });
+});
diff --git a/browser/components/newtab/test/browser/abouthomecache/browser_disabled.js b/browser/components/newtab/test/browser/abouthomecache/browser_disabled.js
new file mode 100644
index 0000000000..6b2f999e12
--- /dev/null
+++ b/browser/components/newtab/test/browser/abouthomecache/browser_disabled.js
@@ -0,0 +1,97 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * This file tests scenarios where the cache is disabled due to user
+ * configuration.
+ */
+
+registerCleanupFunction(async () => {
+ // When the test completes, make sure we cleanup with a populated cache,
+ // since this is the default starting state for these tests.
+ await BrowserTestUtils.withNewTab("about:home", async browser => {
+ await simulateRestart(browser);
+ });
+});
+
+/**
+ * Tests the case where the cache is disabled via the pref.
+ */
+add_task(async function test_cache_disabled() {
+ await BrowserTestUtils.withNewTab("about:home", async browser => {
+ await SpecialPowers.pushPrefEnv({
+ set: [["browser.startup.homepage.abouthome_cache.enabled", false]],
+ });
+
+ await simulateRestart(browser);
+
+ await ensureDynamicAboutHome(
+ browser,
+ AboutHomeStartupCache.CACHE_RESULT_SCALARS.DISABLED
+ );
+
+ await SpecialPowers.popPrefEnv();
+ });
+});
+
+/**
+ * Tests the case where the cache is disabled because the home page is
+ * not set at about:home.
+ */
+add_task(async function test_cache_custom_homepage() {
+ await BrowserTestUtils.withNewTab("about:home", async browser => {
+ await HomePage.set("https://example.com");
+ await simulateRestart(browser);
+
+ await ensureDynamicAboutHome(
+ browser,
+ AboutHomeStartupCache.CACHE_RESULT_SCALARS.NOT_LOADING_ABOUTHOME
+ );
+
+ HomePage.reset();
+ });
+});
+
+/**
+ * Tests the case where the cache is disabled because the session is
+ * configured to automatically be restored.
+ */
+add_task(async function test_cache_restore_session() {
+ await BrowserTestUtils.withNewTab("about:home", async browser => {
+ await SpecialPowers.pushPrefEnv({
+ set: [["browser.startup.page", 3]],
+ });
+
+ await simulateRestart(browser);
+
+ await ensureDynamicAboutHome(
+ browser,
+ AboutHomeStartupCache.CACHE_RESULT_SCALARS.NOT_LOADING_ABOUTHOME
+ );
+
+ await SpecialPowers.popPrefEnv();
+ });
+});
+
+/**
+ * Tests the case where the cache is disabled because about:newtab
+ * preloading is disabled.
+ */
+add_task(async function test_cache_no_preloading() {
+ await BrowserTestUtils.withNewTab("about:home", async browser => {
+ await SpecialPowers.pushPrefEnv({
+ set: [["browser.newtab.preload", false]],
+ });
+
+ await simulateRestart(browser);
+
+ await ensureDynamicAboutHome(
+ browser,
+ AboutHomeStartupCache.CACHE_RESULT_SCALARS.PRELOADING_DISABLED
+ );
+
+ await SpecialPowers.popPrefEnv();
+ });
+});
diff --git a/browser/components/newtab/test/browser/abouthomecache/browser_locale_change.js b/browser/components/newtab/test/browser/abouthomecache/browser_locale_change.js
new file mode 100644
index 0000000000..c47895f9e8
--- /dev/null
+++ b/browser/components/newtab/test/browser/abouthomecache/browser_locale_change.js
@@ -0,0 +1,23 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests that the about:home startup cache is cleared if the app
+ * locale changes.
+ */
+add_task(async function test_locale_change() {
+ await BrowserTestUtils.withNewTab("about:home", async browser => {
+ await simulateRestart(browser);
+ await ensureCachedAboutHome(browser);
+
+ Services.obs.notifyObservers(null, "intl:app-locales-changed");
+
+ await simulateRestart(browser, false);
+ await ensureDynamicAboutHome(
+ browser,
+ AboutHomeStartupCache.CACHE_RESULT_SCALARS.DOES_NOT_EXIST
+ );
+ });
+});
diff --git a/browser/components/newtab/test/browser/abouthomecache/browser_no_cache.js b/browser/components/newtab/test/browser/abouthomecache/browser_no_cache.js
new file mode 100644
index 0000000000..5638fc1584
--- /dev/null
+++ b/browser/components/newtab/test/browser/abouthomecache/browser_no_cache.js
@@ -0,0 +1,21 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+requestLongerTimeout(2);
+
+/**
+ * Test that if there's no cache written, that we load the dynamic
+ * about:home document on startup.
+ */
+add_task(async function test_no_cache() {
+ await BrowserTestUtils.withNewTab("about:home", async browser => {
+ await clearCache();
+ await simulateRestart(browser, false /* withAutoShutdownWrite */);
+ await ensureDynamicAboutHome(
+ browser,
+ AboutHomeStartupCache.CACHE_RESULT_SCALARS.DOES_NOT_EXIST
+ );
+ });
+});
diff --git a/browser/components/newtab/test/browser/abouthomecache/browser_no_startup_actions.js b/browser/components/newtab/test/browser/abouthomecache/browser_no_startup_actions.js
new file mode 100644
index 0000000000..ea47a8b388
--- /dev/null
+++ b/browser/components/newtab/test/browser/abouthomecache/browser_no_startup_actions.js
@@ -0,0 +1,79 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests that upon initializing Activity Stream, the cached about:home
+ * document does not process any actions caused by that initialization.
+ * This is because the restored Redux state from the cache should be enough,
+ * and processing any of the initialization messages from Activity Stream
+ * could wipe out that state and cause flicker / unnecessary redraws.
+ */
+add_task(async function test_no_startup_actions() {
+ await BrowserTestUtils.withNewTab("about:home", async browser => {
+ // Make sure we have a cached document.
+ await clearCache();
+ await simulateRestart(browser);
+ await ensureCachedAboutHome(browser);
+
+ // Set up a RemotePageManager listener to monitor for actions
+ // that get dispatched in the browser when we fire Activity Stream
+ // up again.
+ await SpecialPowers.spawn(browser, [], async () => {
+ let xrayWindow = ChromeUtils.waiveXrays(content);
+ xrayWindow.nonStartupActions = [];
+ xrayWindow.startupActions = [];
+ xrayWindow.RPMAddMessageListener("ActivityStream:MainToContent", msg => {
+ if (msg.data.meta.isStartup) {
+ xrayWindow.startupActions.push(msg.data);
+ } else {
+ xrayWindow.nonStartupActions.push(msg.data);
+ }
+ });
+ });
+
+ // The following two statements seem to be enough to simulate Activity
+ // Stream starting up.
+ AboutNewTab.activityStream.uninit();
+ AboutNewTab.onBrowserReady();
+
+ // Much of Activity Stream initializes asynchronously. This is the easiest way
+ // I could find to ensure that enough of the feeds had initialized to produce
+ // a meaningful cached document.
+ await TestUtils.waitForCondition(() => {
+ let feed = AboutNewTab.activityStream.store.feeds.get(
+ "feeds.discoverystreamfeed"
+ );
+ return feed?.loaded;
+ });
+
+ // Wait an additional few seconds for any other actions to get displayed.
+ // eslint-disable-next-line mozilla/no-arbitrary-setTimeout
+ await new Promise(resolve => setTimeout(resolve, 2000));
+
+ let [startupActions, nonStartupActions] = await SpecialPowers.spawn(
+ browser,
+ [],
+ async () => {
+ let xrayWindow = ChromeUtils.waiveXrays(content);
+ return [xrayWindow.startupActions, xrayWindow.nonStartupActions];
+ }
+ );
+
+ Assert.ok(!!startupActions.length, "Should have seen startup actions.");
+ info(`Saw ${startupActions.length} startup actions.`);
+
+ Assert.equal(
+ nonStartupActions.length,
+ 0,
+ "Should be no non-startup actions."
+ );
+
+ if (nonStartupActions.length) {
+ for (let action of nonStartupActions) {
+ info(`Non-startup action: ${action.type}`);
+ }
+ }
+ });
+});
diff --git a/browser/components/newtab/test/browser/abouthomecache/browser_overwrite_cache.js b/browser/components/newtab/test/browser/abouthomecache/browser_overwrite_cache.js
new file mode 100644
index 0000000000..921e8f228f
--- /dev/null
+++ b/browser/components/newtab/test/browser/abouthomecache/browser_overwrite_cache.js
@@ -0,0 +1,38 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests that if a pre-existing about:home cache exists, that it can
+ * be overwritten with new information.
+ */
+add_task(async function test_overwrite_cache() {
+ await BrowserTestUtils.withNewTab("about:home", async browser => {
+ await simulateRestart(browser);
+ const TEST_ID = "test_overwrite_cache_h1";
+
+ // We need the CSP meta tag in about: pages, otherwise we hit assertions in
+ // debug builds.
+ await injectIntoCache(
+ `
+ <html>
+ <head>
+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; object-src 'none'; script-src resource: chrome:; connect-src https:; img-src https: data: blob:; style-src 'unsafe-inline';">
+ </head>
+ <body>
+ <h1 id="${TEST_ID}">Something new</h1>
+ <div id="root"></div>
+ </body>
+ <script src="about:home?jscache"></script>
+ </html>`,
+ "window.__FROM_STARTUP_CACHE__ = true;"
+ );
+ await simulateRestart(browser, false /* withAutoShutdownWrite */);
+
+ await SpecialPowers.spawn(browser, [TEST_ID], async testID => {
+ let target = content.document.getElementById(testID);
+ Assert.ok(target, "Found the target element");
+ });
+ });
+});
diff --git a/browser/components/newtab/test/browser/abouthomecache/browser_process_crash.js b/browser/components/newtab/test/browser/abouthomecache/browser_process_crash.js
new file mode 100644
index 0000000000..8311eb7c35
--- /dev/null
+++ b/browser/components/newtab/test/browser/abouthomecache/browser_process_crash.js
@@ -0,0 +1,81 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Test that if the "privileged about content process" crashes, that it
+ * drops its internal reference to the "privileged about content process"
+ * process manager, and that a subsequent restart of that process type
+ * results in a dynamic document load. Also tests that crashing of
+ * any other content process type doesn't clear the process manager
+ * reference.
+ */
+add_task(async function test_process_crash() {
+ await BrowserTestUtils.withNewTab("about:home", async browser => {
+ await simulateRestart(browser);
+ let origProcManager = AboutHomeStartupCache._procManager;
+
+ await BrowserTestUtils.crashFrame(browser);
+ Assert.notEqual(
+ origProcManager,
+ AboutHomeStartupCache._procManager,
+ "Should have dropped the reference to the crashed process"
+ );
+ });
+
+ await BrowserTestUtils.withNewTab("about:home", async browser => {
+ // The cache should still be considered "valid and used", since it was
+ // used successfully before the crash.
+ await ensureDynamicAboutHome(
+ browser,
+ AboutHomeStartupCache.CACHE_RESULT_SCALARS.VALID_AND_USED
+ );
+
+ // Now simulate a restart to attach the AboutHomeStartupCache to
+ // the new privileged about content process.
+ await simulateRestart(browser);
+ });
+
+ let latestProcManager = AboutHomeStartupCache._procManager;
+
+ await BrowserTestUtils.withNewTab("http://example.com", async browser => {
+ await BrowserTestUtils.crashFrame(browser);
+ Assert.equal(
+ latestProcManager,
+ AboutHomeStartupCache._procManager,
+ "Should still have the reference to the privileged about process"
+ );
+ });
+});
+
+/**
+ * Tests that if the "privileged about content process" crashes while
+ * a cache request is still underway, that the cache request resolves with
+ * null input streams.
+ */
+add_task(async function test_process_crash_while_requesting_streams() {
+ await BrowserTestUtils.withNewTab("about:home", async browser => {
+ await simulateRestart(browser);
+ let cacheStreamsPromise = AboutHomeStartupCache.requestCache();
+ await BrowserTestUtils.crashFrame(browser);
+ let cacheStreams = await cacheStreamsPromise;
+
+ if (!cacheStreams.pageInputStream && !cacheStreams.scriptInputStream) {
+ Assert.ok(true, "Page and script input streams are null.");
+ } else {
+ // It's possible (but probably rare) the parent was able to receive the
+ // streams before the crash occurred. In that case, we'll make sure that
+ // we can still read the streams.
+ info("Received the streams. Checking that they're readable.");
+ Assert.ok(
+ cacheStreams.pageInputStream.available(),
+ "Bytes available for page stream"
+ );
+ Assert.ok(
+ cacheStreams.scriptInputStream.available(),
+ "Bytes available for script stream"
+ );
+ }
+ });
+});
diff --git a/browser/components/newtab/test/browser/abouthomecache/browser_same_consumer.js b/browser/components/newtab/test/browser/abouthomecache/browser_same_consumer.js
new file mode 100644
index 0000000000..28e3925b33
--- /dev/null
+++ b/browser/components/newtab/test/browser/abouthomecache/browser_same_consumer.js
@@ -0,0 +1,52 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests that if a page attempts to load the script stream without
+ * having also loaded the page stream, that it will fail and get
+ * the default non-cached script.
+ */
+add_task(async function test_same_consumer() {
+ await BrowserTestUtils.withNewTab("about:home", async browser => {
+ await simulateRestart(browser);
+
+ // We need the CSP meta tag in about: pages, otherwise we hit assertions in
+ // debug builds.
+ //
+ // We inject a script that sets a __CACHE_CONSUMED__ property to true on
+ // the window element. We'll test to ensure that if we try to load the
+ // script cache from a different BrowsingContext that this property is
+ // not set.
+ await injectIntoCache(
+ `
+ <html>
+ <head>
+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; object-src 'none'; script-src resource: chrome:; connect-src https:; img-src https: data: blob:; style-src 'unsafe-inline';">
+ </head>
+ <body>
+ <h1>A fake about:home page</h1>
+ <div id="root"></div>
+ </body>
+ </html>`,
+ "window.__CACHE_CONSUMED__ = true;"
+ );
+ await simulateRestart(browser, false /* withAutoShutdownWrite */);
+
+ // Attempting to load the script from the cache should fail, and instead load
+ // the markup.
+ await BrowserTestUtils.withNewTab("about:home?jscache", async browser2 => {
+ await SpecialPowers.spawn(browser2, [], async () => {
+ Assert.ok(
+ !Cu.waiveXrays(content).__CACHE_CONSUMED__,
+ "Should not have found __CACHE_CONSUMED__ property"
+ );
+ Assert.ok(
+ content.document.body.classList.contains("activity-stream"),
+ "Should have found activity-stream class on <body> element"
+ );
+ });
+ });
+ });
+});
diff --git a/browser/components/newtab/test/browser/abouthomecache/browser_sanitize.js b/browser/components/newtab/test/browser/abouthomecache/browser_sanitize.js
new file mode 100644
index 0000000000..efec66296c
--- /dev/null
+++ b/browser/components/newtab/test/browser/abouthomecache/browser_sanitize.js
@@ -0,0 +1,47 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests that when sanitizing places history, session store or downloads, that
+ * the about:home cache gets blown away.
+ */
+
+add_task(async function test_sanitize() {
+ let testFlags = [
+ ["downloads", Ci.nsIClearDataService.CLEAR_DOWNLOADS],
+ ["places history", Ci.nsIClearDataService.CLEAR_HISTORY],
+ ["session history", Ci.nsIClearDataService.CLEAR_SESSION_HISTORY],
+ ];
+
+ await BrowserTestUtils.withNewTab("about:home", async browser => {
+ for (let [type, flag] of testFlags) {
+ await simulateRestart(browser);
+ await ensureCachedAboutHome(browser);
+
+ info(
+ "Testing that the about:home startup cache is cleared when " +
+ `clearing ${type}`
+ );
+
+ await new Promise((resolve, reject) => {
+ Services.clearData.deleteData(flag, {
+ onDataDeleted(resultFlags) {
+ if (!resultFlags) {
+ resolve();
+ } else {
+ reject(new Error(`Failed with flags: ${resultFlags}`));
+ }
+ },
+ });
+ });
+
+ await simulateRestart(browser, { withAutoShutdownWrite: false });
+ await ensureDynamicAboutHome(
+ browser,
+ AboutHomeStartupCache.CACHE_RESULT_SCALARS.DOES_NOT_EXIST
+ );
+ }
+ });
+});
diff --git a/browser/components/newtab/test/browser/abouthomecache/browser_shutdown_timeout.js b/browser/components/newtab/test/browser/abouthomecache/browser_shutdown_timeout.js
new file mode 100644
index 0000000000..0ef0a6eb65
--- /dev/null
+++ b/browser/components/newtab/test/browser/abouthomecache/browser_shutdown_timeout.js
@@ -0,0 +1,45 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * Tests that if there's a substantial delay in getting the cache
+ * streams from the privileged about content process for any reason
+ * during shutdown, that we timeout and let the AsyncShutdown proceed,
+ * rather than letting it block until AsyncShutdown causes a shutdown
+ * hang crash.
+ */
+add_task(async function test_shutdown_timeout() {
+ await BrowserTestUtils.withNewTab("about:home", async browser => {
+ // First, make sure the cache is populated so that later on, after
+ // the timeout, simulateRestart doesn't complain about not finding
+ // a pre-existing cache. This complaining only happens if this test
+ // is run in isolation.
+ await clearCache();
+ await simulateRestart(browser);
+
+ // Next, manually shutdown the AboutHomeStartupCacheChild so that
+ // it doesn't respond to requests to the cache streams.
+ await SpecialPowers.spawn(browser, [], async () => {
+ let { AboutHomeStartupCacheChild } = ChromeUtils.import(
+ "resource:///modules/AboutNewTabService.jsm"
+ );
+ AboutHomeStartupCacheChild.uninit();
+ });
+
+ // Then, manually dirty the cache state so that we attempt to write
+ // on shutdown.
+ AboutHomeStartupCache.onPreloadedNewTabMessage();
+
+ await simulateRestart(browser, { expectTimeout: true });
+
+ Assert.ok(
+ true,
+ "We reached here, which means shutdown didn't block forever."
+ );
+
+ // Clear the cache so that we're not in a half-persisted state.
+ await clearCache();
+ });
+});
diff --git a/browser/components/newtab/test/browser/abouthomecache/head.js b/browser/components/newtab/test/browser/abouthomecache/head.js
new file mode 100644
index 0000000000..7e16cfd403
--- /dev/null
+++ b/browser/components/newtab/test/browser/abouthomecache/head.js
@@ -0,0 +1,325 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+let { AboutHomeStartupCache } = ChromeUtils.import(
+ "resource:///modules/BrowserGlue.jsm"
+);
+
+// Some Activity Stream preferences are JSON encoded, and quite complex.
+// Hard-coding them here or in browser.ini makes them brittle to change.
+// Instead, we pull the default prefs structures and set the values that
+// we need and write them to preferences here dynamically. We do this in
+// its own scope to avoid polluting the global scope.
+{
+ const { PREFS_CONFIG } = ChromeUtils.import(
+ "resource://activity-stream/lib/ActivityStream.jsm"
+ );
+
+ let defaultDSConfig = JSON.parse(
+ PREFS_CONFIG.get("discoverystream.config").getValue({
+ geo: "US",
+ locale: "en-US",
+ })
+ );
+
+ let newConfig = Object.assign(defaultDSConfig, {
+ show_spocs: false,
+ hardcoded_layout: false,
+ layout_endpoint:
+ "https://example.com/browser/browser/components/newtab/test/browser/ds_layout.json",
+ });
+
+ // Configure Activity Stream to query for the layout JSON file that points
+ // at the local top stories feed.
+ Services.prefs.setCharPref(
+ "browser.newtabpage.activity-stream.discoverystream.config",
+ JSON.stringify(newConfig)
+ );
+}
+
+/**
+ * Shuts down the AboutHomeStartupCache components in the parent process
+ * and privileged about content process, and then restarts them, simulating
+ * the parent process having restarted.
+ *
+ * @param browser (<xul:browser>)
+ * A <xul:browser> with about:home running in it. This will be reloaded
+ * after the restart simultion is complete, and that reload will attempt
+ * to read any about:home cache contents.
+ * @param options (object, optional)
+ *
+ * An object with the following properties:
+ *
+ * withAutoShutdownWrite (boolean, optional):
+ * Whether or not the shutdown part of the simulation should cause the
+ * shutdown handler to run, which normally causes the cache to be
+ * written. Setting this to false is handy if the cache has been
+ * specially prepared for the subsequent startup, and we don't want to
+ * overwrite it. This defaults to true.
+ *
+ * ensureCacheWinsRace (boolean, optional):
+ * Ensures that the privileged about content process will be able to
+ * read the bytes from the streams sent down from the HTTP cache. Use
+ * this to avoid the HTTP cache "losing the race" against reading the
+ * about:home document from the omni.ja. This defaults to true.
+ *
+ * expectTimeout (boolean, optional):
+ * If true, indicates that it's expected that AboutHomeStartupCache will
+ * timeout when shutting down. If false, such timeouts will result in
+ * test failures. Defaults to false.
+ *
+ * @returns Promise
+ * @resolves undefined
+ * Resolves once the restart simulation is complete, and the <xul:browser>
+ * pointed at about:home finishes reloading.
+ */
+// eslint-disable-next-line no-unused-vars
+async function simulateRestart(
+ browser,
+ { withAutoShutdownWrite, ensureCacheWinsRace, expectTimeout } = {
+ withAutoShutdownWrite: true,
+ ensureCacheWinsRace: true,
+ expectTimeout: false,
+ }
+) {
+ info("Simulating restart of the browser");
+ if (browser.remoteType !== E10SUtils.PRIVILEGEDABOUT_REMOTE_TYPE) {
+ throw new Error(
+ "prepareLoadFromCache should only be called on a browser " +
+ "loaded in the privileged about content process."
+ );
+ }
+
+ if (withAutoShutdownWrite && AboutHomeStartupCache.initted) {
+ info("Simulating shutdown write");
+ let timedOut = !(await AboutHomeStartupCache.onShutdown(expectTimeout));
+ if (timedOut && !expectTimeout) {
+ Assert.ok(
+ false,
+ "AboutHomeStartupCache shutdown unexpectedly timed out."
+ );
+ } else if (!timedOut && expectTimeout) {
+ Assert.ok(false, "AboutHomeStartupCache shutdown failed to time out.");
+ }
+ info("Shutdown write done");
+ } else {
+ info("Intentionally skipping shutdown write");
+ }
+
+ AboutHomeStartupCache.uninit();
+
+ info("Waiting for AboutHomeStartupCacheChild to uninit");
+ await SpecialPowers.spawn(browser, [], async () => {
+ let { AboutHomeStartupCacheChild } = ChromeUtils.import(
+ "resource:///modules/AboutNewTabService.jsm"
+ );
+ AboutHomeStartupCacheChild.uninit();
+ });
+ info("AboutHomeStartupCacheChild uninitted");
+
+ AboutHomeStartupCache.init();
+
+ if (AboutHomeStartupCache.initted) {
+ let processManager = browser.messageManager.processMessageManager;
+ let pp = browser.browsingContext.currentWindowGlobal.domProcess;
+ let { childID } = pp;
+ AboutHomeStartupCache.onContentProcessCreated(childID, processManager, pp);
+
+ info("Waiting for AboutHomeStartupCache cache entry");
+ await AboutHomeStartupCache.ensureCacheEntry();
+ info("Got AboutHomeStartupCache cache entry");
+
+ if (ensureCacheWinsRace) {
+ info("Ensuring cache bytes are available");
+ await SpecialPowers.spawn(browser, [], async () => {
+ let { AboutHomeStartupCacheChild } = ChromeUtils.import(
+ "resource:///modules/AboutNewTabService.jsm"
+ );
+ let pageStream = AboutHomeStartupCacheChild._pageInputStream;
+ let scriptStream = AboutHomeStartupCacheChild._scriptInputStream;
+ await ContentTaskUtils.waitForCondition(() => {
+ return pageStream.available() && scriptStream.available();
+ });
+ });
+ }
+ }
+
+ info("Waiting for about:home to load");
+ let loaded = BrowserTestUtils.browserLoaded(browser, false, "about:home");
+ BrowserTestUtils.loadURI(browser, "about:home");
+ await loaded;
+ info("about:home loaded");
+}
+
+/**
+ * Writes a page string and a script string into the cache for
+ * the next about:home load.
+ *
+ * @param page (String)
+ * The HTML content to write into the cache. This cannot be the empty
+ * string. Note that this string should contain a node that has an
+ * id of "root", in order for the newtab scripts to attach correctly.
+ * Otherwise, an exception might get thrown which can cause shutdown
+ * leaks.
+ * @param script (String)
+ * The JS content to write into the cache that can be loaded via
+ * about:home?jscache. This cannot be the empty string.
+ * @returns Promise
+ * @resolves undefined
+ * When the page and script content has been successfully written.
+ */
+// eslint-disable-next-line no-unused-vars
+async function injectIntoCache(page, script) {
+ if (!page || !script) {
+ throw new Error("Cannot injectIntoCache with falsey values");
+ }
+
+ if (!page.includes(`id="root"`)) {
+ throw new Error("Page markup must include a root node.");
+ }
+
+ await AboutHomeStartupCache.ensureCacheEntry();
+
+ let pageInputStream = Cc[
+ "@mozilla.org/io/string-input-stream;1"
+ ].createInstance(Ci.nsIStringInputStream);
+
+ pageInputStream.setUTF8Data(page);
+
+ let scriptInputStream = Cc[
+ "@mozilla.org/io/string-input-stream;1"
+ ].createInstance(Ci.nsIStringInputStream);
+
+ scriptInputStream.setUTF8Data(script);
+
+ await AboutHomeStartupCache.populateCache(pageInputStream, scriptInputStream);
+}
+
+/**
+ * Clears out any pre-existing about:home cache.
+ * @returns Promise
+ * @resolves undefined
+ * Resolves when the cache is cleared.
+ */
+// eslint-disable-next-line no-unused-vars
+async function clearCache() {
+ info("Test is clearing the cache");
+ AboutHomeStartupCache.clearCache();
+ await AboutHomeStartupCache.ensureCacheEntry();
+ info("Test has cleared the cache.");
+}
+
+/**
+ * Checks that the browser.startup.abouthome_cache_result scalar was
+ * recorded at a particular value.
+ *
+ * @param cacheResultScalar (Number)
+ * One of the AboutHomeStartupCache.CACHE_RESULT_SCALARS values.
+ */
+function assertCacheResultScalar(cacheResultScalar) {
+ let parentScalars = Services.telemetry.getSnapshotForScalars("main").parent;
+ Assert.equal(
+ parentScalars["browser.startup.abouthome_cache_result"],
+ cacheResultScalar,
+ "Expected the right value set to browser.startup.abouthome_cache_result " +
+ "scalar."
+ );
+}
+
+/**
+ * Tests that the about:home document loaded in a passed <xul:browser> was
+ * one from the cache.
+ *
+ * We test for this by looking for some tell-tale signs of the cached
+ * document:
+ *
+ * 1. The about:home?jscache <script> element
+ * 2. The __FROM_STARTUP_CACHE__ expando on the window
+ * 3. The "activity-stream" class on the document body
+ * 4. The top sites section
+ *
+ * @param browser (<xul:browser>)
+ * A <xul:browser> with about:home running in it.
+ * @returns Promise
+ * @resolves undefined
+ * Resolves once the cache entry has been destroyed.
+ */
+// eslint-disable-next-line no-unused-vars
+async function ensureCachedAboutHome(browser) {
+ await SpecialPowers.spawn(browser, [], async () => {
+ let scripts = Array.from(content.document.querySelectorAll("script"));
+ Assert.ok(!!scripts.length, "There should be page scripts.");
+ let [lastScript] = scripts.reverse();
+ Assert.equal(
+ lastScript.src,
+ "about:home?jscache",
+ "Found about:home?jscache script tag, indicating the cached doc"
+ );
+ Assert.ok(
+ Cu.waiveXrays(content).__FROM_STARTUP_CACHE__,
+ "Should have found window.__FROM_STARTUP_CACHE__"
+ );
+ Assert.ok(
+ content.document.body.classList.contains("activity-stream"),
+ "Should have found activity-stream class on <body> element"
+ );
+ Assert.ok(
+ content.document.querySelector("[data-section-id='topsites']"),
+ "Should have found the Discovery Stream top sites."
+ );
+ });
+ assertCacheResultScalar(
+ AboutHomeStartupCache.CACHE_RESULT_SCALARS.VALID_AND_USED
+ );
+}
+
+/**
+ * Tests that the about:home document loaded in a passed <xul:browser> was
+ * dynamically generated, and _not_ from the cache.
+ *
+ * We test for this by looking for some tell-tale signs of the dynamically
+ * generated document:
+ *
+ * 1. No <script> elements (the scripts are loaded from the ScriptPreloader
+ * via AboutNewTabChild when the "privileged about content process" is
+ * enabled)
+ * 2. No __FROM_STARTUP_CACHE__ expando on the window
+ * 3. The "activity-stream" class on the document body
+ * 4. The top sites section
+ *
+ * @param browser (<xul:browser>)
+ * A <xul:browser> with about:home running in it.
+ * @param expectedResultScalar (Number)
+ * One of the AboutHomeStartupCache.CACHE_RESULT_SCALARS values. It is
+ * asserted that the cache result Telemetry scalar will have been set
+ * to this value to explain why the dynamic about:home was used.
+ * @returns Promise
+ * @resolves undefined
+ * Resolves once the cache entry has been destroyed.
+ */
+// eslint-disable-next-line no-unused-vars
+async function ensureDynamicAboutHome(browser, expectedResultScalar) {
+ await SpecialPowers.spawn(browser, [], async () => {
+ let scripts = Array.from(content.document.querySelectorAll("script"));
+ Assert.equal(scripts.length, 0, "There should be no page scripts.");
+
+ Assert.equal(
+ Cu.waiveXrays(content).__FROM_STARTUP_CACHE__,
+ undefined,
+ "Should not have found window.__FROM_STARTUP_CACHE__"
+ );
+
+ Assert.ok(
+ content.document.body.classList.contains("activity-stream"),
+ "Should have found activity-stream class on <body> element"
+ );
+ Assert.ok(
+ content.document.querySelector("[data-section-id='topsites']"),
+ "Should have found the Discovery Stream top sites."
+ );
+ });
+
+ assertCacheResultScalar(expectedResultScalar);
+}
diff --git a/browser/components/newtab/test/browser/blue_page.html b/browser/components/newtab/test/browser/blue_page.html
new file mode 100644
index 0000000000..e7eaba1e1c
--- /dev/null
+++ b/browser/components/newtab/test/browser/blue_page.html
@@ -0,0 +1,6 @@
+<html>
+ <head>
+ <meta charset="utf-8">
+ </head>
+ <body style="background-color: blue" />
+</html>
diff --git a/browser/components/newtab/test/browser/browser.ini b/browser/components/newtab/test/browser/browser.ini
new file mode 100644
index 0000000000..f95f00c6a1
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser.ini
@@ -0,0 +1,58 @@
+[DEFAULT]
+support-files =
+ blue_page.html
+ red_page.html
+ head.js
+ snippet.json
+ snippet_below_search_test.json
+ snippet_simple_test.json
+ topstories.json
+ ds_layout.json
+prefs =
+ browser.newtabpage.activity-stream.debug=false
+ browser.newtabpage.activity-stream.discoverystream.enabled=true
+ browser.newtabpage.activity-stream.discoverystream.endpoints=data:
+ browser.newtabpage.activity-stream.feeds.system.topstories=true
+ browser.newtabpage.activity-stream.feeds.section.topstories=true
+ browser.newtabpage.activity-stream.feeds.section.topstories.options={"provider_name":""}
+ messaging-system.log=all
+
+[browser_aboutwelcome_actors.js]
+[browser_aboutwelcome_simplified.js]
+[browser_aboutwelcome_multistage.js]
+[browser_aboutwelcome_rtamo.js]
+[browser_aboutwelcome_attribution.js]
+skip-if = (os == "linux") # Test setup only implemented for OSX and Windows
+[browser_aboutwelcome_observer.js]
+[browser_as_load_location.js]
+[browser_as_render.js]
+[browser_asrouter_snippets.js]
+[browser_asrouter_targeting.js]
+[browser_context_menu_item.js]
+[browser_discovery_render.js]
+[browser_discovery_styles.js]
+[browser_enabled_newtabpage.js]
+[browser_highlights_section.js]
+[browser_newtab_experiment_api.js]
+[browser_discovery_card.js]
+[browser_getScreenshots.js]
+[browser_newtab_overrides.js]
+[browser_newtab_header.js]
+[browser_open_tab_focus.js]
+skip-if = (os == "linux") # Test setup only implemented for OSX and Windows
+[browser_topsites_contextMenu_options.js]
+[browser_topsites_section.js]
+[browser_asrouter_cfr.js]
+[browser_asrouter_infobar.js]
+[browser_asrouter_bookmarkpanel.js]
+[browser_asrouter_toolbarbadge.js]
+[browser_asrouter_whatsnewpanel.js]
+tags = remote-settings
+[browser_asrouter_momentspagehub.js]
+tags = remote-settings
+[browser_asrouter_experimentsAPILoader.js]
+[browser_asrouter_group_frequency.js]
+[browser_asrouter_group_userprefs.js]
+[browser_trigger_listeners.js]
+[browser_customize_menu_render.js]
+[browser_customize_menu_content.js]
diff --git a/browser/components/newtab/test/browser/browser_aboutwelcome_actors.js b/browser/components/newtab/test/browser/browser_aboutwelcome_actors.js
new file mode 100644
index 0000000000..74a7eea8c9
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_aboutwelcome_actors.js
@@ -0,0 +1,237 @@
+"use strict";
+
+const SEPARATE_ABOUT_WELCOME_PREF = "browser.aboutwelcome.enabled";
+const DID_SEE_ABOUT_WELCOME_PREF = "trailhead.firstrun.didSeeAboutWelcome";
+const ABOUT_WELCOME_OVERRIDE_CONTENT = "browser.aboutwelcome.overrideContent";
+
+const { PrivateBrowsingUtils } = ChromeUtils.import(
+ "resource://gre/modules/PrivateBrowsingUtils.jsm"
+);
+
+const { FxAccounts } = ChromeUtils.import(
+ "resource://gre/modules/FxAccounts.jsm"
+);
+
+const SIMPLIFIED_WELCOME_CONTENT = {
+ template: "simplified",
+ title: {
+ string_id: "onboarding-welcome-header",
+ },
+ startButton: {
+ label: {
+ string_id: "onboarding-start-browsing-button-label",
+ },
+ message_id: "START_BROWSING_BUTTON",
+ action: {
+ type: "OPEN_AWESOME_BAR",
+ },
+ },
+ cards: [
+ {
+ content: {
+ title: {
+ string_id: "onboarding-data-sync-title",
+ },
+ text: {
+ string_id: "onboarding-data-sync-text2",
+ },
+ icon: "devices",
+ primary_button: {
+ label: {
+ string_id: "onboarding-data-sync-button2",
+ },
+ action: {
+ type: "OPEN_URL",
+ addFlowParams: true,
+ data: {
+ args:
+ "https://accounts.firefox.com/?service=sync&action=email&context=fx_desktop_v3&entrypoint=activity-stream-firstrun&style=trailhead",
+ where: "tabshifted",
+ },
+ },
+ },
+ },
+ id: "TRAILHEAD_CARD_2",
+ order: 1,
+ blockOnClick: false,
+ },
+ {
+ content: {
+ title: {
+ string_id: "onboarding-firefox-monitor-title",
+ },
+ text: {
+ string_id: "onboarding-firefox-monitor-text2",
+ },
+ icon: "ffmonitor",
+ primary_button: {
+ label: {
+ string_id: "onboarding-firefox-monitor-button",
+ },
+ action: {
+ type: "OPEN_URL",
+ data: {
+ args: "https://monitor.firefox.com/",
+ where: "tabshifted",
+ },
+ },
+ },
+ },
+ id: "TRAILHEAD_CARD_3",
+ order: 2,
+ blockOnClick: false,
+ },
+ {
+ content: {
+ title: {
+ string_id: "onboarding-browse-privately-title",
+ },
+ text: {
+ string_id: "onboarding-browse-privately-text",
+ },
+ icon: "private",
+ primary_button: {
+ label: {
+ string_id: "onboarding-browse-privately-button",
+ },
+ action: {
+ type: "OPEN_PRIVATE_BROWSER_WINDOW",
+ },
+ },
+ },
+ id: "TRAILHEAD_CARD_4",
+ order: 3,
+ blockOnClick: true,
+ },
+ ],
+};
+
+/**
+ * Sets the aboutwelcome pref to enabled simplified welcome UI
+ */
+async function setAboutWelcomePref(value) {
+ await pushPrefs([
+ ABOUT_WELCOME_OVERRIDE_CONTENT,
+ JSON.stringify(SIMPLIFIED_WELCOME_CONTENT),
+ ]);
+ return pushPrefs([SEPARATE_ABOUT_WELCOME_PREF, value]);
+}
+
+async function openAboutWelcome() {
+ let tab = await BrowserTestUtils.openNewForegroundTab(
+ gBrowser,
+ "about:welcome",
+ true
+ );
+ registerCleanupFunction(() => {
+ BrowserTestUtils.removeTab(tab);
+ });
+ return tab.linkedBrowser;
+}
+
+// Test events from AboutWelcomeUtils
+async function test_set_message() {
+ Services.prefs.setBoolPref(DID_SEE_ABOUT_WELCOME_PREF, false);
+ await openAboutWelcome();
+ Assert.equal(
+ Services.prefs.getBoolPref(DID_SEE_ABOUT_WELCOME_PREF, false),
+ true,
+ "Pref was set"
+ );
+}
+
+async function test_open_awesome_bar(browser, message) {
+ await ContentTask.spawn(browser, message, async () => {
+ await ContentTaskUtils.waitForCondition(
+ () =>
+ content.document.querySelector(
+ "button[data-l10n-id=onboarding-start-browsing-button-label]"
+ ),
+ "Wait for start browsing button to load"
+ );
+ let button = content.document.querySelector(
+ "button[data-l10n-id=onboarding-start-browsing-button-label]"
+ );
+ button.click();
+ });
+ Assert.ok(gURLBar.focused, "Focus should be on awesome bar");
+}
+
+async function test_open_private_browser(browser, message) {
+ let newWindowPromise = BrowserTestUtils.waitForNewWindow();
+ await ContentTask.spawn(browser, message, async () => {
+ await ContentTaskUtils.waitForCondition(
+ () =>
+ content.document.querySelector(
+ "button[data-l10n-id=onboarding-browse-privately-button]"
+ ),
+ "Wait for private browsing button to load"
+ );
+ let button = content.document.querySelector(
+ "button[data-l10n-id=onboarding-browse-privately-button]"
+ );
+ button.click();
+ });
+ let win = await newWindowPromise;
+ Assert.ok(PrivateBrowsingUtils.isWindowPrivate(win));
+ await BrowserTestUtils.closeWindow(win);
+}
+
+// Test Fxaccounts MetricsFlowURI
+
+add_task(async function setup() {
+ const sandbox = sinon.createSandbox();
+ sandbox.stub(FxAccounts.config, "promiseMetricsFlowURI").resolves("");
+
+ await pushPrefs([
+ ABOUT_WELCOME_OVERRIDE_CONTENT,
+ JSON.stringify(SIMPLIFIED_WELCOME_CONTENT),
+ ]);
+
+ registerCleanupFunction(() => {
+ sandbox.restore();
+ });
+});
+
+test_newtab(
+ {
+ async before({ pushPrefs }) {
+ await pushPrefs(["browser.aboutwelcome.enabled", true]);
+ },
+ test: async function test_startBrowsing() {
+ await ContentTaskUtils.waitForCondition(
+ () =>
+ content.document.querySelector(
+ "button[data-l10n-id=onboarding-start-browsing-button-label]"
+ ),
+ "Wait for start browsing button to load"
+ );
+ },
+ after() {
+ ok(
+ FxAccounts.config.promiseMetricsFlowURI.callCount === 1,
+ "Stub was called"
+ );
+ Assert.equal(
+ FxAccounts.config.promiseMetricsFlowURI.firstCall.args[0],
+ "aboutwelcome",
+ "Called by AboutWelcomeParent"
+ );
+ },
+ },
+ "about:welcome"
+);
+
+add_task(async function test_onContentMessage() {
+ await setAboutWelcomePref(true);
+ let browser = await openAboutWelcome();
+
+ //case "SET_WELCOME_MESSAGE_SEEN"
+ await test_set_message();
+
+ // //case "OPEN_AWESOME_BAR"
+ await test_open_awesome_bar(browser, "Open awesome bar");
+
+ //case "OPEN_PRIVATE_BROWSER_WINDOW"
+ await test_open_private_browser(browser, "Open private window");
+});
diff --git a/browser/components/newtab/test/browser/browser_aboutwelcome_attribution.js b/browser/components/newtab/test/browser/browser_aboutwelcome_attribution.js
new file mode 100644
index 0000000000..ae92ecc3ed
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_aboutwelcome_attribution.js
@@ -0,0 +1,113 @@
+"use strict";
+
+const { ASRouter } = ChromeUtils.import(
+ "resource://activity-stream/lib/ASRouter.jsm"
+);
+const { AttributionCode } = ChromeUtils.import(
+ "resource:///modules/AttributionCode.jsm"
+);
+const { AddonRepository } = ChromeUtils.import(
+ "resource://gre/modules/addons/AddonRepository.jsm"
+);
+
+const TEST_ATTRIBUTION_DATA = {
+ source: "addons.mozilla.org",
+ medium: "referral",
+ campaign: "non-fx-button",
+ content: "iridium@particlecore.github.io",
+};
+
+const TEST_ADDON_INFO = [
+ {
+ name: "Test Add-on",
+ sourceURI: { scheme: "https", spec: "https://test.xpi" },
+ icons: { 32: "https://test.png", 64: "https://test.png" },
+ },
+];
+
+async function openRTAMOWithAttribution() {
+ const sandbox = sinon.createSandbox();
+ sandbox.stub(AddonRepository, "getAddonsByIDs").resolves(TEST_ADDON_INFO);
+
+ await AttributionCode.deleteFileAsync();
+ await ASRouter.forceAttribution(TEST_ATTRIBUTION_DATA);
+
+ AttributionCode._clearCache();
+ const data = await AttributionCode.getAttrDataAsync();
+
+ Assert.equal(
+ data.source,
+ "addons.mozilla.org",
+ "Attribution data should be set"
+ );
+
+ let tab = await BrowserTestUtils.openNewForegroundTab(
+ gBrowser,
+ "about:welcome",
+ true
+ );
+ registerCleanupFunction(async () => {
+ BrowserTestUtils.removeTab(tab);
+ await ASRouter.forceAttribution("");
+ sandbox.restore();
+ });
+ return tab.linkedBrowser;
+}
+
+/**
+ * Setup and test RTAMO welcome UI
+ */
+async function test_screen_content(
+ browser,
+ experiment,
+ expectedSelectors = [],
+ unexpectedSelectors = []
+) {
+ await ContentTask.spawn(
+ browser,
+ { expectedSelectors, experiment, unexpectedSelectors },
+ async ({
+ expectedSelectors: expected,
+ experiment: experimentName,
+ unexpectedSelectors: unexpected,
+ }) => {
+ for (let selector of expected) {
+ await ContentTaskUtils.waitForCondition(
+ () => content.document.querySelector(selector),
+ `Should render ${selector} in ${experimentName}`
+ );
+ }
+ for (let selector of unexpected) {
+ ok(
+ !content.document.querySelector(selector),
+ `Should not render ${selector} in ${experimentName}`
+ );
+ }
+ }
+ );
+}
+
+add_task(async function test_rtamo_attribution() {
+ let browser = await openRTAMOWithAttribution();
+
+ await test_screen_content(
+ browser,
+ "RTAMO UI",
+ // Expected selectors:
+ [
+ "div.onboardingContainer",
+ "div.brand-logo",
+ "h2[data-l10n-id='return-to-amo-addon-title']",
+ "img[data-l10n-name='icon']",
+ "button.primary",
+ "button.secondary",
+ ],
+ // Unexpected selectors:
+ [
+ "main.AW_STEP1",
+ "main.AW_STEP2",
+ "main.AW_STEP3",
+ "div.tiles-container.info",
+ ]
+ );
+});
diff --git a/browser/components/newtab/test/browser/browser_aboutwelcome_multistage.js b/browser/components/newtab/test/browser/browser_aboutwelcome_multistage.js
new file mode 100644
index 0000000000..0344fc456b
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_aboutwelcome_multistage.js
@@ -0,0 +1,779 @@
+"use strict";
+
+const { ExperimentAPI } = ChromeUtils.import(
+ "resource://messaging-system/experiments/ExperimentAPI.jsm"
+);
+const { ExperimentFakes } = ChromeUtils.import(
+ "resource://testing-common/MSTestUtils.jsm"
+);
+
+const SEPARATE_ABOUT_WELCOME_PREF = "browser.aboutwelcome.enabled";
+const ABOUT_WELCOME_OVERRIDE_CONTENT_PREF =
+ "browser.aboutwelcome.overrideContent";
+
+const TEST_MULTISTAGE_CONTENT = {
+ id: "multi-stage-welcome",
+ template: "multistage",
+ screens: [
+ {
+ id: "AW_STEP1",
+ order: 0,
+ content: {
+ zap: true,
+ title: "Step 1",
+ tiles: {
+ type: "theme",
+ action: {
+ theme: "<event>",
+ },
+ data: [
+ {
+ theme: "automatic",
+ label: "theme-1",
+ tooltip: "test-tooltip",
+ },
+ {
+ theme: "dark",
+ label: "theme-2",
+ },
+ ],
+ },
+ primary_button: {
+ label: "Next",
+ action: {
+ navigate: true,
+ },
+ },
+ secondary_button: {
+ label: "link top",
+ position: "top",
+ action: {
+ type: "SHOW_FIREFOX_ACCOUNTS",
+ data: { entrypoint: "test" },
+ },
+ },
+ },
+ },
+ {
+ id: "AW_STEP2",
+ order: 1,
+ content: {
+ zap: true,
+ title: "Step 2 longzaptest",
+ tiles: {
+ type: "topsites",
+ info: true,
+ },
+ primary_button: {
+ label: "Next",
+ action: {
+ navigate: true,
+ },
+ },
+ secondary_button: {
+ label: "link",
+ position: "bottom",
+ },
+ },
+ },
+ {
+ id: "AW_STEP3",
+ order: 2,
+ content: {
+ title: "Step 3",
+ tiles: {
+ type: "image",
+ media_type: "test-img",
+ source: {
+ default:
+ "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiI+PHBhdGggZmlsbD0iIzQ1YTFmZiIgZmlsbC1vcGFjaXR5PSJjb250ZXh0LWZpbGwtb3BhY2l0eSIgZD0iTTE1Ljg0NSA2LjA2NEExLjEgMS4xIDAgMCAwIDE1IDUuMzMxTDEwLjkxMSA0LjYgOC45ODUuNzM1YTEuMSAxLjEgMCAwIDAtMS45NjkgMEw1LjA4OSA0LjZsLTQuMDgxLjcyOWExLjEgMS4xIDAgMCAwLS42MTUgMS44MzRMMy4zMiAxMC4zMWwtLjYwOSA0LjM2YTEuMSAxLjEgMCAwIDAgMS42IDEuMTI3TDggMTMuODczbDMuNjkgMS45MjdhMS4xIDEuMSAwIDAgMCAxLjYtMS4xMjdsLS42MS00LjM2MyAyLjkyNi0zLjE0NmExLjEgMS4xIDAgMCAwIC4yMzktMS4xeiIvPjwvc3ZnPg==",
+ },
+ },
+ primary_button: {
+ label: "Next",
+ action: {
+ navigate: true,
+ },
+ },
+ secondary_button: {
+ label: "Import",
+ action: {
+ type: "SHOW_MIGRATION_WIZARD",
+ data: { source: "chrome" },
+ },
+ },
+ help_text: {
+ text: "Here's some sample help text",
+ position: "default",
+ },
+ },
+ },
+ ],
+};
+const TEST_MULTISTAGE_JSON = JSON.stringify(TEST_MULTISTAGE_CONTENT);
+/**
+ * Sets the aboutwelcome pref to enabled simplified welcome UI
+ */
+async function setAboutWelcomePref(value) {
+ return pushPrefs([SEPARATE_ABOUT_WELCOME_PREF, value]);
+}
+
+async function setAboutWelcomeMultiStage(value) {
+ return pushPrefs([ABOUT_WELCOME_OVERRIDE_CONTENT_PREF, value]);
+}
+
+async function openAboutWelcome() {
+ await setAboutWelcomePref(true);
+ await setAboutWelcomeMultiStage(TEST_MULTISTAGE_JSON);
+
+ let tab = await BrowserTestUtils.openNewForegroundTab(
+ gBrowser,
+ "about:welcome",
+ true
+ );
+ registerCleanupFunction(() => {
+ BrowserTestUtils.removeTab(tab);
+ });
+ return tab.linkedBrowser;
+}
+
+/**
+ * Setup and test simplified welcome UI
+ */
+async function test_screen_content(
+ browser,
+ experiment,
+ expectedSelectors = [],
+ unexpectedSelectors = []
+) {
+ await ContentTask.spawn(
+ browser,
+ { expectedSelectors, experiment, unexpectedSelectors },
+ async ({
+ expectedSelectors: expected,
+ experiment: experimentName,
+ unexpectedSelectors: unexpected,
+ }) => {
+ for (let selector of expected) {
+ await ContentTaskUtils.waitForCondition(
+ () => content.document.querySelector(selector),
+ `Should render ${selector} in ${experimentName}`
+ );
+ }
+ for (let selector of unexpected) {
+ ok(
+ !content.document.querySelector(selector),
+ `Should not render ${selector} in ${experimentName}`
+ );
+ }
+
+ if (experimentName === "home") {
+ Assert.equal(
+ content.document.location.href,
+ "about:home",
+ "Navigated to about:home"
+ );
+ } else {
+ Assert.equal(
+ content.document.location.href,
+ "about:welcome",
+ "Navigated to a welcome screen"
+ );
+ }
+ }
+ );
+}
+
+async function onButtonClick(browser, elementId) {
+ await ContentTask.spawn(
+ browser,
+ { elementId },
+ async ({ elementId: buttonId }) => {
+ await ContentTaskUtils.waitForCondition(
+ () => content.document.querySelector(buttonId),
+ buttonId
+ );
+ let button = content.document.querySelector(buttonId);
+ button.click();
+ }
+ );
+}
+
+/**
+ * Test the zero onboarding using ExperimentAPI
+ */
+add_task(async function test_multistage_zeroOnboarding_experimentAPI() {
+ await setAboutWelcomePref(true);
+ let updatePromise = ExperimentFakes.waitForExperimentUpdate(ExperimentAPI, {
+ slug: "mochitest-1-aboutwelcome",
+ });
+ ExperimentAPI._store.addExperiment({
+ slug: "mochitest-1-aboutwelcome",
+ branch: {
+ slug: "mochitest-1-aboutwelcome",
+ feature: {
+ enabled: false,
+ featureId: "aboutwelcome",
+ value: null,
+ },
+ },
+ active: true,
+ });
+
+ await updatePromise;
+ ExperimentAPI._store._syncToChildren({ flush: true });
+
+ let tab = await BrowserTestUtils.openNewForegroundTab(
+ gBrowser,
+ "about:welcome",
+ true
+ );
+ registerCleanupFunction(() => {
+ BrowserTestUtils.removeTab(tab);
+ });
+
+ const browser = tab.linkedBrowser;
+
+ await test_screen_content(
+ browser,
+ "Opens new tab",
+ // Expected selectors:
+ ["div.search-wrapper", "body.activity-stream"],
+ // Unexpected selectors:
+ ["div.onboardingContainer", "main.AW_STEP1"]
+ );
+
+ ExperimentAPI._store._deleteForTests("mochitest-1-aboutwelcome");
+ Assert.equal(ExperimentAPI._store.getAll().length, 0, "Cleanup done");
+});
+
+/**
+ * Test the multistage welcome UI using ExperimentAPI
+ */
+add_task(async function test_multistage_aboutwelcome_experimentAPI() {
+ await setAboutWelcomePref(true);
+ await setAboutWelcomeMultiStage({});
+ let updatePromise = ExperimentFakes.waitForExperimentUpdate(ExperimentAPI, {
+ slug: "mochitest-aboutwelcome",
+ });
+ ExperimentAPI._store.addExperiment({
+ slug: "mochitest-aboutwelcome",
+ branch: {
+ slug: "mochitest-aboutwelcome",
+ feature: {
+ enabled: true,
+ featureId: "aboutwelcome",
+ value: TEST_MULTISTAGE_CONTENT,
+ },
+ },
+ active: true,
+ });
+
+ await updatePromise;
+ ExperimentAPI._store._syncToChildren({ flush: true });
+
+ let tab = await BrowserTestUtils.openNewForegroundTab(
+ gBrowser,
+ "about:welcome",
+ true
+ );
+ registerCleanupFunction(() => {
+ BrowserTestUtils.removeTab(tab);
+ });
+
+ const browser = tab.linkedBrowser;
+
+ await test_screen_content(
+ browser,
+ "multistage step 1",
+ // Expected selectors:
+ [
+ "div.onboardingContainer",
+ "main.AW_STEP1",
+ "h1.welcomeZap",
+ "span.zap.short",
+ "div.secondary-cta.top",
+ "button.secondary",
+ "label.theme",
+ "input[type='radio']",
+ "div.indicator.current",
+ ],
+ // Unexpected selectors:
+ ["main.AW_STEP2", "main.AW_STEP3", "div.tiles-container.info"]
+ );
+
+ await onButtonClick(browser, "button.primary");
+ await test_screen_content(
+ browser,
+ "multistage step 2",
+ // Expected selectors:
+ [
+ "div.onboardingContainer",
+ "main.AW_STEP2",
+ "button.secondary",
+ "h1.welcomeZap",
+ "span.zap.long",
+ "div.tiles-container.info",
+ ],
+ // Unexpected selectors:
+ ["main.AW_STEP1", "main.AW_STEP3", "div.secondary-cta.top", "div.test-img"]
+ );
+ await onButtonClick(browser, "button.primary");
+ await test_screen_content(
+ browser,
+ "multistage step 3",
+ // Expected selectors:
+ [
+ "div.onboardingContainer",
+ "main.AW_STEP3",
+ "div.brand-logo",
+ "div.welcome-text",
+ "p.helptext",
+ "div.test-img",
+ ],
+ // Unexpected selectors:
+ ["main.AW_STEP1", "main.AW_STEP2"]
+ );
+ await onButtonClick(browser, "button.primary");
+ await test_screen_content(
+ browser,
+ "home",
+ // Expected selectors:
+ ["body.activity-stream"],
+ // Unexpected selectors:
+ ["div.onboardingContainer"]
+ );
+
+ ExperimentAPI._store._deleteForTests("mochitest-aboutwelcome");
+ Assert.equal(ExperimentAPI._store.getAll().length, 0, "Cleanup done");
+});
+
+/**
+ * Test the multistage welcome UI rendered using TEST_MULTISTAGE_JSON
+ */
+add_task(async function test_Multistage_About_Welcome_branches() {
+ let browser = await openAboutWelcome();
+
+ await test_screen_content(
+ browser,
+ "multistage step 1",
+ // Expected selectors:
+ [
+ "div.onboardingContainer",
+ "main.AW_STEP1",
+ "h1.welcomeZap",
+ "span.zap.short",
+ "div.secondary-cta.top",
+ "button.secondary",
+ "label.theme",
+ "input[type='radio']",
+ "div.indicator.current",
+ ],
+ // Unexpected selectors:
+ ["main.AW_STEP2", "main.AW_STEP3", "div.tiles-container.info"]
+ );
+
+ await onButtonClick(browser, "button.primary");
+ await test_screen_content(
+ browser,
+ "multistage step 2",
+ // Expected selectors:
+ [
+ "div.onboardingContainer",
+ "main.AW_STEP2",
+ "h1.welcomeZap",
+ "span.zap.long",
+ "button.secondary",
+ "div.tiles-container.info",
+ ],
+ // Unexpected selectors:
+ ["main.AW_STEP1", "main.AW_STEP3", "div.secondary-cta.top"]
+ );
+ await onButtonClick(browser, "button.primary");
+ await test_screen_content(
+ browser,
+ "multistage step 3",
+ // Expected selectors:
+ [
+ "div.onboardingContainer",
+ "main.AW_STEP3",
+ "div.brand-logo",
+ "div.welcome-text",
+ ],
+ // Unexpected selectors:
+ ["main.AW_STEP1", "main.AW_STEP2", "h1.welcomeZap"]
+ );
+ await onButtonClick(browser, "button.primary");
+ await test_screen_content(
+ browser,
+ "home",
+ // Expected selectors:
+ ["body.activity-stream"],
+ // Unexpected selectors:
+ ["div.onboardingContainer"]
+ );
+});
+
+/**
+ * Test navigating back/forward between screens
+ */
+add_task(async function test_Multistage_About_Welcome_navigation() {
+ let browser = await openAboutWelcome();
+
+ await onButtonClick(browser, "button.primary");
+ await BrowserTestUtils.waitForCondition(() => browser.canGoBack);
+ browser.goBack();
+
+ await test_screen_content(
+ browser,
+ "multistage step 1",
+ // Expected selectors:
+ [
+ "div.onboardingContainer",
+ "main.AW_STEP1",
+ "div.secondary-cta.top",
+ "button.secondary",
+ "div.indicator.current",
+ ],
+ // Unexpected selectors:
+ ["main.AW_STEP2", "main.AW_STEP3"]
+ );
+
+ await document.getElementById("forward-button").click();
+ await test_screen_content(
+ browser,
+ "multistage step 2",
+ // Expected selectors:
+ ["div.onboardingContainer", "main.AW_STEP2", "button.secondary"],
+ // Unexpected selectors:
+ ["main.AW_STEP1", "main.AW_STEP3", "div.secondary-cta.top"]
+ );
+});
+
+async function getAboutWelcomeParent(browser) {
+ let windowGlobalParent = browser.browsingContext.currentWindowGlobal;
+ return windowGlobalParent.getActor("AboutWelcome");
+}
+
+/**
+ * Test the multistage welcome UI primary button action
+ */
+add_task(async function test_AWMultistage_Primary_Action() {
+ let browser = await openAboutWelcome();
+ let aboutWelcomeActor = await getAboutWelcomeParent(browser);
+ const sandbox = sinon.createSandbox();
+ // Stub AboutWelcomeParent Content Message Handler
+ sandbox
+ .stub(aboutWelcomeActor, "onContentMessage")
+ .resolves("")
+ .withArgs("AWPage:IMPORTABLE_SITES")
+ .resolves([]);
+ registerCleanupFunction(() => {
+ sandbox.restore();
+ });
+
+ await onButtonClick(browser, "button.primary");
+ const { callCount } = aboutWelcomeActor.onContentMessage;
+ ok(callCount >= 1, `${callCount} Stub was called`);
+
+ let clickCall;
+ let impressionCall;
+ let performanceCall;
+ for (let i = 0; i < callCount; i++) {
+ const call = aboutWelcomeActor.onContentMessage.getCall(i);
+ info(`Call #${i}: ${call.args[0]} ${JSON.stringify(call.args[1])}`);
+ if (call.calledWithMatch("", { event: "CLICK_BUTTON" })) {
+ clickCall = call;
+ } else if (
+ call.calledWithMatch("", {
+ event_context: { importable: sinon.match.number },
+ })
+ ) {
+ impressionCall = call;
+ } else if (
+ call.calledWithMatch("", {
+ event_context: { mountStart: sinon.match.number },
+ })
+ ) {
+ performanceCall = call;
+ }
+ }
+
+ // For some builds, we can stub fast enough to catch the impression
+ if (impressionCall) {
+ Assert.equal(
+ impressionCall.args[0],
+ "AWPage:TELEMETRY_EVENT",
+ "send telemetry event"
+ );
+ Assert.equal(
+ impressionCall.args[1].event,
+ "IMPRESSION",
+ "impression event recorded in telemetry"
+ );
+ Assert.equal(
+ impressionCall.args[1].event_context.display,
+ "static",
+ "static sites display recorded in telemetry"
+ );
+ Assert.equal(
+ typeof impressionCall.args[1].event_context.importable,
+ "number",
+ "numeric importable sites recorded in telemetry"
+ );
+ Assert.equal(
+ impressionCall.args[1].message_id,
+ `${TEST_MULTISTAGE_CONTENT.id}_SITES`.toUpperCase(),
+ "SITES MessageId sent in impression event telemetry"
+ );
+ }
+
+ // For some builds, we can stub fast enough to catch the performance
+ if (performanceCall) {
+ Assert.equal(
+ performanceCall.args[0],
+ "AWPage:TELEMETRY_EVENT",
+ "send telemetry event"
+ );
+ Assert.equal(
+ performanceCall.args[1].event,
+ "IMPRESSION",
+ "performance impression event recorded in telemetry"
+ );
+ Assert.equal(
+ typeof performanceCall.args[1].event_context.domComplete,
+ "number",
+ "numeric domComplete recorded in telemetry"
+ );
+ Assert.equal(
+ typeof performanceCall.args[1].event_context.domInteractive,
+ "number",
+ "numeric domInteractive recorded in telemetry"
+ );
+ Assert.equal(
+ typeof performanceCall.args[1].event_context.mountStart,
+ "number",
+ "numeric mountStart recorded in telemetry"
+ );
+ Assert.equal(
+ performanceCall.args[1].message_id,
+ TEST_MULTISTAGE_CONTENT.id.toUpperCase(),
+ "MessageId sent in performance event telemetry"
+ );
+ }
+
+ Assert.equal(
+ clickCall.args[0],
+ "AWPage:TELEMETRY_EVENT",
+ "send telemetry event"
+ );
+ Assert.equal(
+ clickCall.args[1].event,
+ "CLICK_BUTTON",
+ "click button event recorded in telemetry"
+ );
+ Assert.equal(
+ clickCall.args[1].event_context.source,
+ "primary_button",
+ "primary button click source recorded in telemetry"
+ );
+ Assert.equal(
+ clickCall.args[1].message_id,
+ `${TEST_MULTISTAGE_CONTENT.id}_${TEST_MULTISTAGE_CONTENT.screens[0].id}`.toUpperCase(),
+ "MessageId sent in click event telemetry"
+ );
+});
+
+add_task(async function test_AWMultistage_Secondary_Open_URL_Action() {
+ let browser = await openAboutWelcome();
+ let aboutWelcomeActor = await getAboutWelcomeParent(browser);
+ const sandbox = sinon.createSandbox();
+ // Stub AboutWelcomeParent Content Message Handler
+ sandbox
+ .stub(aboutWelcomeActor, "onContentMessage")
+ .resolves("")
+ .withArgs("AWPage:IMPORTABLE_SITES")
+ .resolves([]);
+ registerCleanupFunction(() => {
+ sandbox.restore();
+ });
+
+ await onButtonClick(browser, "button.secondary");
+ const { callCount } = aboutWelcomeActor.onContentMessage;
+ ok(
+ callCount >= 2,
+ `${callCount} Stub called twice to handle FxA open URL and Telemetry`
+ );
+
+ let actionCall;
+ let eventCall;
+ for (let i = 0; i < callCount; i++) {
+ const call = aboutWelcomeActor.onContentMessage.getCall(i);
+ info(`Call #${i}: ${call.args[0]} ${JSON.stringify(call.args[1])}`);
+ if (call.calledWithMatch("SPECIAL")) {
+ actionCall = call;
+ } else if (call.calledWithMatch("", { event: "CLICK_BUTTON" })) {
+ eventCall = call;
+ }
+ }
+
+ Assert.equal(
+ actionCall.args[0],
+ "AWPage:SPECIAL_ACTION",
+ "Got call to handle special action"
+ );
+ Assert.equal(
+ actionCall.args[1].type,
+ "SHOW_FIREFOX_ACCOUNTS",
+ "Special action SHOW_FIREFOX_ACCOUNTS event handled"
+ );
+ Assert.equal(
+ actionCall.args[1].data.extraParams.utm_term,
+ "aboutwelcome-default-screen",
+ "UTMTerm set in FxA URL"
+ );
+ Assert.equal(
+ actionCall.args[1].data.entrypoint,
+ "test",
+ "EntryPoint set in FxA URL"
+ );
+ Assert.equal(
+ eventCall.args[0],
+ "AWPage:TELEMETRY_EVENT",
+ "Got call to handle Telemetry event"
+ );
+ Assert.equal(
+ eventCall.args[1].event,
+ "CLICK_BUTTON",
+ "click button event recorded in Telemetry"
+ );
+ Assert.equal(
+ eventCall.args[1].event_context.source,
+ "secondary_button",
+ "secondary button click source recorded in Telemetry"
+ );
+});
+
+add_task(async function test_AWMultistage_Themes() {
+ let browser = await openAboutWelcome();
+ let aboutWelcomeActor = await getAboutWelcomeParent(browser);
+
+ const sandbox = sinon.createSandbox();
+ // Stub AboutWelcomeParent Content Message Handler
+ sandbox
+ .stub(aboutWelcomeActor, "onContentMessage")
+ .resolves("")
+ .withArgs("AWPage:IMPORTABLE_SITES")
+ .resolves([]);
+ registerCleanupFunction(() => {
+ sandbox.restore();
+ });
+
+ await ContentTask.spawn(browser, "Themes", async () => {
+ await ContentTaskUtils.waitForCondition(
+ () => content.document.querySelector("label.theme"),
+ "Theme Icons"
+ );
+ let themes = content.document.querySelectorAll("label.theme");
+ Assert.equal(themes.length, 2, "Two themes displayed");
+ });
+
+ await onButtonClick(browser, "input[value=automatic]");
+
+ const { callCount } = aboutWelcomeActor.onContentMessage;
+ ok(callCount >= 1, `${callCount} Stub was called`);
+
+ let actionCall;
+ let eventCall;
+ for (let i = 0; i < callCount; i++) {
+ const call = aboutWelcomeActor.onContentMessage.getCall(i);
+ info(`Call #${i}: ${call.args[0]} ${JSON.stringify(call.args[1])}`);
+ if (call.calledWithMatch("SELECT_THEME")) {
+ actionCall = call;
+ } else if (call.calledWithMatch("", { event: "CLICK_BUTTON" })) {
+ eventCall = call;
+ }
+ }
+
+ Assert.equal(
+ actionCall.args[0],
+ "AWPage:SELECT_THEME",
+ "Got call to handle select theme"
+ );
+ Assert.equal(
+ actionCall.args[1],
+ "AUTOMATIC",
+ "Theme value passed as AUTOMATIC"
+ );
+ Assert.equal(
+ eventCall.args[0],
+ "AWPage:TELEMETRY_EVENT",
+ "Got call to handle Telemetry event when theme tile clicked"
+ );
+ Assert.equal(
+ eventCall.args[1].event,
+ "CLICK_BUTTON",
+ "click button event recorded in Telemetry"
+ );
+ Assert.equal(
+ eventCall.args[1].event_context.source,
+ "automatic",
+ "automatic click source recorded in Telemetry"
+ );
+});
+
+add_task(async function test_AWMultistage_Import() {
+ let browser = await openAboutWelcome();
+ let aboutWelcomeActor = await getAboutWelcomeParent(browser);
+
+ // click twice to advance to screen 3
+ await onButtonClick(browser, "button.primary");
+ await onButtonClick(browser, "button.primary");
+
+ const sandbox = sinon.createSandbox();
+ // Stub AboutWelcomeParent Content Message Handler
+ sandbox
+ .stub(aboutWelcomeActor, "onContentMessage")
+ .resolves("")
+ .withArgs("AWPage:IMPORTABLE_SITES")
+ .resolves([]);
+ registerCleanupFunction(() => {
+ sandbox.restore();
+ });
+
+ await onButtonClick(browser, "button.secondary");
+ const { callCount } = aboutWelcomeActor.onContentMessage;
+
+ let actionCall;
+ let eventCall;
+ for (let i = 0; i < callCount; i++) {
+ const call = aboutWelcomeActor.onContentMessage.getCall(i);
+ info(`Call #${i}: ${call.args[0]} ${JSON.stringify(call.args[1])}`);
+ if (call.calledWithMatch("SPECIAL")) {
+ actionCall = call;
+ } else if (call.calledWithMatch("", { event: "CLICK_BUTTON" })) {
+ eventCall = call;
+ }
+ }
+
+ Assert.equal(
+ actionCall.args[0],
+ "AWPage:SPECIAL_ACTION",
+ "Got call to handle special action"
+ );
+ Assert.equal(
+ actionCall.args[1].type,
+ "SHOW_MIGRATION_WIZARD",
+ "Special action SHOW_MIGRATION_WIZARD event handled"
+ );
+ Assert.equal(
+ actionCall.args[1].data.source,
+ "chrome",
+ "Source passed to event handler"
+ );
+ Assert.equal(
+ eventCall.args[0],
+ "AWPage:TELEMETRY_EVENT",
+ "Got call to handle Telemetry event"
+ );
+});
diff --git a/browser/components/newtab/test/browser/browser_aboutwelcome_observer.js b/browser/components/newtab/test/browser/browser_aboutwelcome_observer.js
new file mode 100644
index 0000000000..1586d2c51f
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_aboutwelcome_observer.js
@@ -0,0 +1,76 @@
+"use strict";
+
+const SEPARATE_ABOUT_WELCOME_PREF = "browser.aboutwelcome.enabled";
+const { AboutWelcomeParent } = ChromeUtils.import(
+ "resource:///actors/AboutWelcomeParent.jsm"
+);
+
+/**
+ * Sets the aboutwelcome pref to enabled simplified welcome UI
+ */
+async function setAboutWelcomePref(value) {
+ return pushPrefs([SEPARATE_ABOUT_WELCOME_PREF, value]);
+}
+
+async function openAboutWelcomeTab() {
+ await setAboutWelcomePref(true);
+ let tab = await BrowserTestUtils.openNewForegroundTab(
+ gBrowser,
+ "about:welcome"
+ );
+ registerCleanupFunction(() => {
+ BrowserTestUtils.removeTab(tab);
+ });
+ return tab;
+}
+
+/**
+ * Test simplified welcome UI tab closed terminate reason
+ */
+add_task(async function test_About_Welcome_Tab_Close() {
+ await setAboutWelcomePref(true);
+
+ let tab = await BrowserTestUtils.openNewForegroundTab(
+ gBrowser,
+ "about:welcome",
+ false
+ );
+
+ Assert.ok(Services.focus.activeWindow, "Active window is not null");
+ let AWP = new AboutWelcomeParent();
+ Assert.ok(AWP.AboutWelcomeObserver, "AboutWelcomeObserver is not null");
+
+ BrowserTestUtils.removeTab(tab);
+ Assert.equal(
+ AWP.AboutWelcomeObserver.terminateReason,
+ AWP.AboutWelcomeObserver.AWTerminate.TAB_CLOSED,
+ "Terminated due to tab closed"
+ );
+});
+
+/**
+ * Test simplified welcome UI closed due to change in location uri
+ */
+add_task(async function test_About_Welcome_Location_Change() {
+ await openAboutWelcomeTab();
+ let windowGlobalParent =
+ gBrowser.selectedBrowser.browsingContext.currentWindowGlobal;
+
+ let aboutWelcomeActor = await windowGlobalParent.getActor("AboutWelcome");
+
+ Assert.ok(
+ aboutWelcomeActor.AboutWelcomeObserver,
+ "AboutWelcomeObserver is not null"
+ );
+ BrowserTestUtils.loadURI(gBrowser.selectedBrowser, "http://example.com/#foo");
+ await BrowserTestUtils.waitForLocationChange(
+ gBrowser,
+ "http://example.com/#foo"
+ );
+
+ Assert.equal(
+ aboutWelcomeActor.AboutWelcomeObserver.terminateReason,
+ aboutWelcomeActor.AboutWelcomeObserver.AWTerminate.ADDRESS_BAR_NAVIGATED,
+ "Terminated due to location uri changed"
+ );
+});
diff --git a/browser/components/newtab/test/browser/browser_aboutwelcome_rtamo.js b/browser/components/newtab/test/browser/browser_aboutwelcome_rtamo.js
new file mode 100644
index 0000000000..e48832447b
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_aboutwelcome_rtamo.js
@@ -0,0 +1,193 @@
+"use strict";
+
+const ABOUT_WELCOME_OVERRIDE_CONTENT_PREF =
+ "browser.aboutwelcome.overrideContent";
+
+const TEST_RTAMO_WELCOME_CONTENT = {
+ template: "return_to_amo",
+ name: "Test add on",
+ url: "https://test.xpi",
+ iconURL: "https://test.svg",
+ content: {
+ header: { string_id: "onboarding-welcome-header" },
+ subtitle: { string_id: "return-to-amo-subtitle" },
+ text: {
+ string_id: "return-to-amo-addon-title",
+ },
+ primary_button: {
+ label: { string_id: "return-to-amo-add-extension-label" },
+ action: {
+ type: "INSTALL_ADDON_FROM_URL",
+ data: { url: null, telemetrySource: "rtamo" },
+ },
+ },
+ startButton: {
+ label: {
+ string_id: "onboarding-start-browsing-button-label",
+ },
+ message_id: "RTAMO_START_BROWSING_BUTTON",
+ action: {
+ type: "OPEN_AWESOME_BAR",
+ },
+ },
+ },
+};
+
+const TEST_RTAMO_WELCOME_JSON = JSON.stringify(TEST_RTAMO_WELCOME_CONTENT);
+
+async function setAboutWelcomeOverride(value) {
+ return pushPrefs([ABOUT_WELCOME_OVERRIDE_CONTENT_PREF, value]);
+}
+
+async function openRTAMOWelcomePage() {
+ await setAboutWelcomeOverride(TEST_RTAMO_WELCOME_JSON);
+
+ let tab = await BrowserTestUtils.openNewForegroundTab(
+ gBrowser,
+ "about:welcome",
+ true
+ );
+ registerCleanupFunction(() => {
+ BrowserTestUtils.removeTab(tab);
+ pushPrefs([ABOUT_WELCOME_OVERRIDE_CONTENT_PREF, ""]);
+ });
+ return tab.linkedBrowser;
+}
+
+/**
+ * Setup and test RTAMO welcome UI
+ */
+async function test_screen_content(
+ browser,
+ experiment,
+ expectedSelectors = [],
+ unexpectedSelectors = []
+) {
+ await ContentTask.spawn(
+ browser,
+ { expectedSelectors, experiment, unexpectedSelectors },
+ async ({
+ expectedSelectors: expected,
+ experiment: experimentName,
+ unexpectedSelectors: unexpected,
+ }) => {
+ for (let selector of expected) {
+ await ContentTaskUtils.waitForCondition(
+ () => content.document.querySelector(selector),
+ `Should render ${selector} in ${experimentName}`
+ );
+ }
+ for (let selector of unexpected) {
+ ok(
+ !content.document.querySelector(selector),
+ `Should not render ${selector} in ${experimentName}`
+ );
+ }
+ }
+ );
+}
+
+async function onButtonClick(browser, elementId) {
+ await ContentTask.spawn(
+ browser,
+ { elementId },
+ async ({ elementId: buttonId }) => {
+ await ContentTaskUtils.waitForCondition(
+ () => content.document.querySelector(buttonId),
+ buttonId
+ );
+ let button = content.document.querySelector(buttonId);
+ button.click();
+ }
+ );
+}
+
+/**
+ * Test the RTAMO welcome UI
+ */
+add_task(async function test_rtamo_aboutwelcome() {
+ let browser = await openRTAMOWelcomePage();
+
+ await test_screen_content(
+ browser,
+ "RTAMO UI",
+ // Expected selectors:
+ [
+ "div.onboardingContainer",
+ "div.brand-logo",
+ "h2[data-l10n-id='return-to-amo-addon-title']",
+ "img[data-l10n-name='icon']",
+ "button.primary",
+ "button.secondary",
+ ],
+ // Unexpected selectors:
+ [
+ "main.AW_STEP1",
+ "main.AW_STEP2",
+ "main.AW_STEP3",
+ "div.tiles-container.info",
+ ]
+ );
+
+ await onButtonClick(browser, "button.secondary");
+ Assert.ok(gURLBar.focused, "Focus should be on awesome bar");
+
+ let windowGlobalParent = browser.browsingContext.currentWindowGlobal;
+ let aboutWelcomeActor = windowGlobalParent.getActor("AboutWelcome");
+ const sandbox = sinon.createSandbox();
+ // Stub AboutWelcomeParent Content Message Handler
+ sandbox.stub(aboutWelcomeActor, "onContentMessage");
+ registerCleanupFunction(() => {
+ sandbox.restore();
+ });
+
+ await onButtonClick(browser, "button.primary");
+ const { callCount } = aboutWelcomeActor.onContentMessage;
+ ok(
+ callCount === 2,
+ `${callCount} Stub called twice to install extension and send telemetry`
+ );
+
+ const installExtensionCall = aboutWelcomeActor.onContentMessage.getCall(0);
+ Assert.equal(
+ installExtensionCall.args[0],
+ "AWPage:SPECIAL_ACTION",
+ "send special action to install add on"
+ );
+ Assert.equal(
+ installExtensionCall.args[1].type,
+ "INSTALL_ADDON_FROM_URL",
+ "Special action type is INSTALL_ADDON_FROM_URL"
+ );
+ Assert.equal(
+ installExtensionCall.args[1].data.url,
+ "https://test.xpi",
+ "Install add on url"
+ );
+ Assert.equal(
+ installExtensionCall.args[1].data.telemetrySource,
+ "rtamo",
+ "Install add on telemetry source"
+ );
+ const telemetryCall = aboutWelcomeActor.onContentMessage.getCall(1);
+ Assert.equal(
+ telemetryCall.args[0],
+ "AWPage:TELEMETRY_EVENT",
+ "send add extension telemetry"
+ );
+ Assert.equal(
+ telemetryCall.args[1].event,
+ "INSTALL",
+ "Telemetry event sent as INSTALL"
+ );
+ Assert.equal(
+ telemetryCall.args[1].event_context.source,
+ "ADD_EXTENSION_BUTTON",
+ "Source of the event is Add Extension Button"
+ );
+ Assert.equal(
+ telemetryCall.args[1].message_id,
+ "RTAMO_DEFAULT_WELCOME",
+ "Message Id sent in telemetry for default RTAMO"
+ );
+});
diff --git a/browser/components/newtab/test/browser/browser_aboutwelcome_simplified.js b/browser/components/newtab/test/browser/browser_aboutwelcome_simplified.js
new file mode 100644
index 0000000000..652d9d7cba
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_aboutwelcome_simplified.js
@@ -0,0 +1,77 @@
+"use strict";
+
+const SEPARATE_ABOUT_WELCOME_PREF = "browser.aboutwelcome.enabled";
+
+/**
+ * Sets the aboutwelcome pref to enabled simplified welcome UI
+ */
+async function setAboutWelcomePref(value) {
+ return pushPrefs([SEPARATE_ABOUT_WELCOME_PREF, value]);
+}
+
+async function openAboutWelcome() {
+ let tab = await BrowserTestUtils.openNewForegroundTab(
+ gBrowser,
+ "about:welcome",
+ false
+ );
+ registerCleanupFunction(() => {
+ BrowserTestUtils.removeTab(tab);
+ });
+ return tab.linkedBrowser;
+}
+
+/**
+ * Setup and test simplified welcome UI
+ */
+async function test_about_welcome(
+ experiment,
+ expectedSelectors = [],
+ unexpectedSelectors = []
+) {
+ await setAboutWelcomePref(true);
+ let browser = await openAboutWelcome();
+
+ await ContentTask.spawn(
+ browser,
+ { expectedSelectors, experiment, unexpectedSelectors },
+ async ({
+ expectedSelectors: expected,
+ experiment: experimentName,
+ unexpectedSelectors: unexpected,
+ }) => {
+ for (let selector of expected) {
+ await ContentTaskUtils.waitForCondition(
+ () => content.document.querySelector(selector),
+ `Should render ${selector} in ${experimentName}`
+ );
+ }
+ for (let selector of unexpected) {
+ ok(
+ !content.document.querySelector(selector),
+ `Should not render ${selector} in ${experimentName}`
+ );
+ }
+ }
+ );
+}
+
+/**
+ * Test the the various simplified welcome UI experiment values.
+ * For now we have default content in place, UI content should be tested
+ * for respective strings as we set content via experiment API
+ */
+add_task(async function test_Separate_About_Welcome_branches() {
+ await test_about_welcome(
+ "default",
+ // Expected selectors:
+ [
+ "div.onboardingContainer",
+ "nav.steps",
+ "button.primary",
+ "button.secondary",
+ ],
+ // Unexpected selectors:
+ [".trailhead.welcomeCohort", ".welcome-subtitle"]
+ );
+});
diff --git a/browser/components/newtab/test/browser/browser_as_load_location.js b/browser/components/newtab/test/browser/browser_as_load_location.js
new file mode 100644
index 0000000000..f11b6cf503
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_as_load_location.js
@@ -0,0 +1,44 @@
+"use strict";
+
+/**
+ * Helper to test that a newtab page loads its html document.
+ *
+ * @param selector {String} CSS selector to find an element in newtab content
+ * @param message {String} Description of the test printed with the assertion
+ */
+async function checkNewtabLoads(selector, message) {
+ // simulate a newtab open as a user would
+ BrowserOpenTab();
+
+ // wait until the browser loads
+ let browser = gBrowser.selectedBrowser;
+ await waitForPreloaded(browser);
+
+ // check what the content task thinks has been loaded.
+ let found = await ContentTask.spawn(
+ browser,
+ selector,
+ arg => content.document.querySelector(arg) !== null
+ );
+ ok(found, message);
+
+ // avoid leakage
+ BrowserTestUtils.removeTab(gBrowser.selectedTab);
+}
+
+// Test with activity stream on
+async function checkActivityStreamLoads() {
+ await checkNewtabLoads(
+ "body.activity-stream",
+ "Got <body class='activity-stream'> Element"
+ );
+}
+
+// Run a first time not from a preloaded browser
+add_task(async function checkActivityStreamNotPreloadedLoad() {
+ NewTabPagePreloading.removePreloadedBrowser(window);
+ await checkActivityStreamLoads();
+});
+
+// Run a second time from a preloaded browser
+add_task(checkActivityStreamLoads);
diff --git a/browser/components/newtab/test/browser/browser_as_render.js b/browser/components/newtab/test/browser/browser_as_render.js
new file mode 100644
index 0000000000..2e82786b16
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_as_render.js
@@ -0,0 +1,83 @@
+"use strict";
+
+test_newtab({
+ async before({ pushPrefs }) {
+ await pushPrefs([
+ "browser.newtabpage.activity-stream.improvesearch.handoffToAwesomebar",
+ false,
+ ]);
+ },
+ test: function test_render_search() {
+ let search = content.document.getElementById("newtab-search-text");
+ ok(search, "Got the search box");
+ isnot(
+ search.placeholder,
+ "search_web_placeholder",
+ "Search box is localized"
+ );
+ },
+});
+
+test_newtab({
+ async before({ pushPrefs }) {
+ await pushPrefs([
+ "browser.newtabpage.activity-stream.improvesearch.handoffToAwesomebar",
+ true,
+ ]);
+ },
+ test: function test_render_search_handoff() {
+ let search = content.document.querySelector(".search-handoff-button");
+ ok(search, "Got the search handoff button");
+ },
+});
+
+test_newtab(function test_render_topsites() {
+ let topSites = content.document.querySelector(".top-sites-list");
+ ok(topSites, "Got the top sites section");
+});
+
+test_newtab({
+ async before({ pushPrefs }) {
+ await pushPrefs([
+ "browser.newtabpage.activity-stream.feeds.topsites",
+ false,
+ ]);
+ },
+ test: function test_render_no_topsites() {
+ let topSites = content.document.querySelector(".top-sites-list");
+ ok(!topSites, "No top sites section");
+ },
+});
+
+// This next test runs immediately after test_render_no_topsites to make sure
+// the topsites pref is restored
+test_newtab(function test_render_topsites_again() {
+ let topSites = content.document.querySelector(".top-sites-list");
+ ok(topSites, "Got the top sites section again");
+});
+
+test_newtab({
+ async before({ pushPrefs }) {
+ await pushPrefs([
+ "browser.newtabpage.activity-stream.logowordmark.alwaysVisible",
+ false,
+ ]);
+ },
+ test: function test_render_logo_false() {
+ let logoWordmark = content.document.querySelector(".logo-and-wordmark");
+ ok(!logoWordmark, "The logo is not rendered when pref is false");
+ },
+});
+
+test_newtab({
+ async before({ pushPrefs }) {
+ await pushPrefs([
+ "browser.newtabpage.activity-stream.logowordmark.alwaysVisible",
+ true,
+ ]);
+ },
+ test: function test_render_logo() {
+ let logoWordmark = content.document.querySelector(".logo-and-wordmark");
+ ok(logoWordmark, "The logo is rendered when pref is true");
+ },
+});
diff --git a/browser/components/newtab/test/browser/browser_asrouter_bookmarkpanel.js b/browser/components/newtab/test/browser/browser_asrouter_bookmarkpanel.js
new file mode 100644
index 0000000000..1a70df8285
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_asrouter_bookmarkpanel.js
@@ -0,0 +1,94 @@
+const { PanelTestProvider } = ChromeUtils.import(
+ "resource://activity-stream/lib/PanelTestProvider.jsm"
+);
+const { BookmarkPanelHub } = ChromeUtils.import(
+ "resource://activity-stream/lib/BookmarkPanelHub.jsm"
+);
+
+add_task(async function test_fxa_message_shown() {
+ const tab = await BrowserTestUtils.openNewForegroundTab(gBrowser);
+
+ registerCleanupFunction(async () => {
+ await clearHistoryAndBookmarks();
+ BrowserTestUtils.removeTab(tab);
+ });
+
+ const testURL = "data:text/plain,test cfr fxa bookmark panel message";
+ const browser = gBrowser.selectedBrowser;
+
+ StarUI._createPanelIfNeeded();
+
+ BrowserTestUtils.loadURI(browser, testURL);
+ await BrowserTestUtils.browserLoaded(browser, false, testURL);
+
+ const [msg] = await PanelTestProvider.getMessages();
+ const response = BookmarkPanelHub.onResponse(
+ msg,
+ {
+ container: document.getElementById("editBookmarkPanelRecommendation"),
+ infoButton: document.getElementById("editBookmarkPanelInfoButton"),
+ recommendationContainer: document.getElementById(
+ "editBookmarkPanelRecommendation"
+ ),
+ url: testURL,
+ document,
+ },
+ window
+ );
+
+ Assert.ok(response, "We sent a valid message");
+
+ const popupShownPromise = BrowserTestUtils.waitForEvent(
+ StarUI.panel,
+ "popupshown"
+ );
+
+ // Wait for the bookmark panel state to settle and be ready to open the panel
+ await BrowserTestUtils.waitForCondition(
+ () => BookmarkingUI.status !== BookmarkingUI.STATUS_UPDATING
+ );
+
+ BookmarkingUI.star.click();
+
+ await popupShownPromise;
+
+ await BrowserTestUtils.waitForCondition(
+ () => document.getElementById("cfrMessageContainer"),
+ `Should create a
+ container for the message`
+ );
+ for (const selector of [
+ "#cfrClose",
+ "#editBookmarkPanelRecommendationTitle",
+ "#editBookmarkPanelRecommendationContent",
+ "#editBookmarkPanelRecommendationCta",
+ ]) {
+ Assert.ok(
+ document.getElementById("cfrMessageContainer").querySelector(selector),
+ `Should contain ${selector}`
+ );
+ }
+
+ const ftlFiles = Array.from(document.querySelectorAll("link")).filter(
+ l =>
+ l.getAttribute("href") === "browser/newtab/asrouter.ftl" ||
+ l.getAttribute("href") === "browser/branding/sync-brand.ftl"
+ );
+
+ Assert.equal(
+ ftlFiles.length,
+ 2,
+ "Two fluent files required for translating the message"
+ );
+
+ const popupHiddenPromise = BrowserTestUtils.waitForEvent(
+ StarUI.panel,
+ "popuphidden"
+ );
+
+ let removeButton = document.getElementById("editBookmarkPanelRemoveButton");
+
+ removeButton.click();
+
+ await popupHiddenPromise;
+});
diff --git a/browser/components/newtab/test/browser/browser_asrouter_cfr.js b/browser/components/newtab/test/browser/browser_asrouter_cfr.js
new file mode 100644
index 0000000000..0e8637cb1b
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_asrouter_cfr.js
@@ -0,0 +1,1134 @@
+const { CFRPageActions } = ChromeUtils.import(
+ "resource://activity-stream/lib/CFRPageActions.jsm"
+);
+const { ASRouterTriggerListeners } = ChromeUtils.import(
+ "resource://activity-stream/lib/ASRouterTriggerListeners.jsm"
+);
+const { ASRouter } = ChromeUtils.import(
+ "resource://activity-stream/lib/ASRouter.jsm"
+);
+const { CFRMessageProvider } = ChromeUtils.import(
+ "resource://activity-stream/lib/CFRMessageProvider.jsm"
+);
+
+const { TelemetryFeed } = ChromeUtils.import(
+ "resource://activity-stream/lib/TelemetryFeed.jsm"
+);
+
+const createDummyRecommendation = ({
+ action,
+ category,
+ heading_text,
+ layout,
+ skip_address_bar_notifier,
+ template,
+}) => {
+ let recommendation = {
+ template,
+ groups: ["mochitest-group"],
+ content: {
+ layout: layout || "addon_recommendation",
+ category,
+ anchor_id: "page-action-buttons",
+ skip_address_bar_notifier,
+ heading_text: heading_text || "Mochitest",
+ info_icon: {
+ label: { attributes: { tooltiptext: "Why am I seeing this" } },
+ sumo_path: "extensionrecommendations",
+ },
+ icon: "foo",
+ icon_dark_theme: "bar",
+ learn_more: "extensionrecommendations",
+ addon: {
+ id: "addon-id",
+ title: "Addon name",
+ icon: "foo",
+ author: "Author name",
+ amo_url: "https://example.com",
+ },
+ descriptionDetails: { steps: [] },
+ text: "Mochitest",
+ buttons: {
+ primary: {
+ label: {
+ value: "OK",
+ attributes: { accesskey: "O" },
+ },
+ action: {
+ type: action.type,
+ data: {},
+ },
+ },
+ secondary: [
+ {
+ label: {
+ value: "Cancel",
+ attributes: { accesskey: "C" },
+ },
+ action: {
+ type: "CANCEL",
+ },
+ },
+ {
+ label: {
+ value: "Cancel 1",
+ attributes: { accesskey: "A" },
+ },
+ },
+ {
+ label: {
+ value: "Cancel 2",
+ attributes: { accesskey: "B" },
+ },
+ },
+ ],
+ },
+ },
+ };
+ recommendation.content.notification_text = new String("Mochitest"); // eslint-disable-line
+ recommendation.content.notification_text.attributes = {
+ tooltiptext: "Mochitest tooltip",
+ "a11y-announcement": "Mochitest announcement",
+ };
+ return recommendation;
+};
+
+function checkCFRFeaturesElements(notification) {
+ Assert.ok(notification.hidden === false, "Panel should be visible");
+ Assert.equal(
+ notification.getAttribute("data-notification-category"),
+ "message_and_animation",
+ "Panel have correct data attribute"
+ );
+ Assert.ok(
+ notification.querySelector(
+ "#cfr-notification-footer-pintab-animation-container"
+ ),
+ "Pin tab animation exists"
+ );
+ Assert.ok(
+ notification.querySelector("#cfr-notification-feature-steps"),
+ "Pin tab steps"
+ );
+}
+
+function checkCFRAddonsElements(notification) {
+ Assert.ok(notification.hidden === false, "Panel should be visible");
+ Assert.equal(
+ notification.getAttribute("data-notification-category"),
+ "addon_recommendation",
+ "Panel have correct data attribute"
+ );
+ Assert.ok(
+ notification.querySelector("#cfr-notification-footer-text-and-addon-info"),
+ "Panel should have addon info container"
+ );
+ Assert.ok(
+ notification.querySelector("#cfr-notification-footer-filled-stars"),
+ "Panel should have addon rating info"
+ );
+ Assert.ok(
+ notification.querySelector("#cfr-notification-author"),
+ "Panel should have author info"
+ );
+}
+
+function checkCFRSocialTrackingProtection(notification) {
+ Assert.ok(notification.hidden === false, "Panel should be visible");
+ Assert.ok(
+ notification.getAttribute("data-notification-category") ===
+ "icon_and_message",
+ "Panel have corret data attribute"
+ );
+ Assert.ok(
+ notification.querySelector("#cfr-notification-footer-learn-more-link"),
+ "Panel should have learn more link"
+ );
+}
+
+function checkCFRTrackingProtectionMilestone(notification) {
+ Assert.ok(notification.hidden === false, "Panel should be visible");
+ Assert.ok(
+ notification.getAttribute("data-notification-category") === "short_message",
+ "Panel have correct data attribute"
+ );
+}
+
+function clearNotifications() {
+ for (let notification of PopupNotifications._currentNotifications) {
+ notification.remove();
+ }
+
+ // Clicking the primary action also removes the notification
+ Assert.equal(
+ PopupNotifications._currentNotifications.length,
+ 0,
+ "Should have removed the notification"
+ );
+}
+
+function trigger_cfr_panel(
+ browser,
+ trigger,
+ {
+ action = { type: "CANCEL" },
+ heading_text,
+ category = "cfrAddons",
+ layout,
+ skip_address_bar_notifier = false,
+ use_single_secondary_button = false,
+ template = "cfr_doorhanger",
+ } = {}
+) {
+ // a fake action type will result in the action being ignored
+ const recommendation = createDummyRecommendation({
+ action,
+ category,
+ heading_text,
+ layout,
+ skip_address_bar_notifier,
+ template,
+ });
+ if (category !== "cfrAddons") {
+ delete recommendation.content.addon;
+ }
+ if (use_single_secondary_button) {
+ recommendation.content.buttons.secondary = [
+ recommendation.content.buttons.secondary[0],
+ ];
+ }
+
+ clearNotifications();
+ return CFRPageActions.addRecommendation(
+ browser,
+ trigger,
+ recommendation,
+ // Use the real AS dispatch method to trigger real notifications
+ ASRouter.dispatchCFRAction
+ );
+}
+
+add_task(async function setup() {
+ // Store it in order to restore to the original value
+ const { _fetchLatestAddonVersion } = CFRPageActions;
+ // Prevent fetching the real addon url and making a network request
+ CFRPageActions._fetchLatestAddonVersion = x => "http://example.com";
+
+ registerCleanupFunction(() => {
+ CFRPageActions._fetchLatestAddonVersion = _fetchLatestAddonVersion;
+ clearNotifications();
+ CFRPageActions.clearRecommendations();
+ });
+});
+
+add_task(async function test_cfr_notification_show() {
+ const sendPingStub = sinon.stub(
+ TelemetryFeed.prototype,
+ "sendStructuredIngestionEvent"
+ );
+ // addRecommendation checks that scheme starts with http and host matches
+ let browser = gBrowser.selectedBrowser;
+ BrowserTestUtils.loadURI(browser, "http://example.com/");
+ await BrowserTestUtils.browserLoaded(browser, false, "http://example.com/");
+
+ const response = await trigger_cfr_panel(browser, "example.com");
+ Assert.ok(
+ response,
+ "Should return true if addRecommendation checks were successful"
+ );
+
+ const oldFocus = document.activeElement;
+ const showPanel = BrowserTestUtils.waitForEvent(
+ PopupNotifications.panel,
+ "popupshown"
+ );
+ // Open the panel
+ document.getElementById("contextual-feature-recommendation").click();
+ await showPanel;
+
+ Assert.ok(
+ document.getElementById("contextual-feature-recommendation-notification")
+ .hidden === false,
+ "Panel should be visible"
+ );
+ Assert.equal(
+ document.activeElement,
+ oldFocus,
+ "Focus didn't move when panel was shown"
+ );
+
+ // Check there is a primary button and click it. It will trigger the callback.
+ Assert.ok(
+ document.getElementById("contextual-feature-recommendation-notification")
+ .button
+ );
+ let hidePanel = BrowserTestUtils.waitForEvent(
+ PopupNotifications.panel,
+ "popuphidden"
+ );
+ document
+ .getElementById("contextual-feature-recommendation-notification")
+ .button.click();
+ await hidePanel;
+
+ // Clicking the primary action also removes the notification
+ Assert.equal(
+ PopupNotifications._currentNotifications.length,
+ 0,
+ "Should have removed the notification"
+ );
+
+ Assert.ok(sendPingStub.callCount >= 1, "Recorded some events");
+ let cfrPing = sendPingStub.args.find(args => args[2] === "cfr");
+ Assert.equal(cfrPing[0].source, "CFR", "Got a CFR event");
+ sendPingStub.restore();
+});
+
+add_task(async function test_cfr_notification_show() {
+ // addRecommendation checks that scheme starts with http and host matches
+ let browser = gBrowser.selectedBrowser;
+ BrowserTestUtils.loadURI(browser, "http://example.com/");
+ await BrowserTestUtils.browserLoaded(browser, false, "http://example.com/");
+
+ let response = await trigger_cfr_panel(browser, "example.com", {
+ heading_text: "First Message",
+ });
+ Assert.ok(
+ response,
+ "Should return true if addRecommendation checks were successful"
+ );
+ const showPanel = BrowserTestUtils.waitForEvent(
+ PopupNotifications.panel,
+ "popupshown"
+ );
+
+ // Try adding another message
+ response = await trigger_cfr_panel(browser, "example.com", {
+ heading_text: "Second Message",
+ });
+ Assert.equal(
+ response,
+ false,
+ "Should return false if second call did not add the message"
+ );
+
+ // Open the panel
+ document.getElementById("contextual-feature-recommendation").click();
+ await showPanel;
+
+ Assert.ok(
+ document.getElementById("contextual-feature-recommendation-notification")
+ .hidden === false,
+ "Panel should be visible"
+ );
+
+ Assert.equal(
+ document.getElementById("cfr-notification-header-label").value,
+ "First Message",
+ "The first message should be visible"
+ );
+
+ // Check there is a primary button and click it. It will trigger the callback.
+ Assert.ok(
+ document.getElementById("contextual-feature-recommendation-notification")
+ .button
+ );
+ let hidePanel = BrowserTestUtils.waitForEvent(
+ PopupNotifications.panel,
+ "popuphidden"
+ );
+ document
+ .getElementById("contextual-feature-recommendation-notification")
+ .button.click();
+ await hidePanel;
+
+ // Clicking the primary action also removes the notification
+ Assert.equal(
+ PopupNotifications._currentNotifications.length,
+ 0,
+ "Should have removed the notification"
+ );
+});
+
+add_task(async function test_cfr_notification_minimize() {
+ // addRecommendation checks that scheme starts with http and host matches
+ let browser = gBrowser.selectedBrowser;
+ BrowserTestUtils.loadURI(browser, "http://example.com/");
+ await BrowserTestUtils.browserLoaded(browser, false, "http://example.com/");
+
+ let response = await trigger_cfr_panel(browser, "example.com");
+ Assert.ok(
+ response,
+ "Should return true if addRecommendation checks were successful"
+ );
+
+ await BrowserTestUtils.waitForCondition(
+ () => gURLBar.hasAttribute("cfr-recommendation-state"),
+ "Wait for the notification to show up and have a state"
+ );
+ Assert.ok(
+ gURLBar.getAttribute("cfr-recommendation-state") === "expanded",
+ "CFR recomendation state is correct"
+ );
+
+ gURLBar.focus();
+
+ await BrowserTestUtils.waitForCondition(
+ () => gURLBar.getAttribute("cfr-recommendation-state") === "collapsed",
+ "After urlbar focus the CFR notification should collapse"
+ );
+
+ // Open the panel and click to dismiss to ensure cleanup
+ const showPanel = BrowserTestUtils.waitForEvent(
+ PopupNotifications.panel,
+ "popupshown"
+ );
+ // Open the panel
+ document.getElementById("contextual-feature-recommendation").click();
+ await showPanel;
+
+ let hidePanel = BrowserTestUtils.waitForEvent(
+ PopupNotifications.panel,
+ "popuphidden"
+ );
+ document
+ .getElementById("contextual-feature-recommendation-notification")
+ .button.click();
+ await hidePanel;
+});
+
+add_task(async function test_cfr_notification_minimize_2() {
+ // addRecommendation checks that scheme starts with http and host matches
+ let browser = gBrowser.selectedBrowser;
+ BrowserTestUtils.loadURI(browser, "http://example.com/");
+ await BrowserTestUtils.browserLoaded(browser, false, "http://example.com/");
+
+ let response = await trigger_cfr_panel(browser, "example.com");
+ Assert.ok(
+ response,
+ "Should return true if addRecommendation checks were successful"
+ );
+
+ await BrowserTestUtils.waitForCondition(
+ () => gURLBar.hasAttribute("cfr-recommendation-state"),
+ "Wait for the notification to show up and have a state"
+ );
+ Assert.ok(
+ gURLBar.getAttribute("cfr-recommendation-state") === "expanded",
+ "CFR recomendation state is correct"
+ );
+
+ // Open the panel and click to dismiss to ensure cleanup
+ const showPanel = BrowserTestUtils.waitForEvent(
+ PopupNotifications.panel,
+ "popupshown"
+ );
+ // Open the panel
+ document.getElementById("contextual-feature-recommendation").click();
+ await showPanel;
+
+ let hidePanel = BrowserTestUtils.waitForEvent(
+ PopupNotifications.panel,
+ "popuphidden"
+ );
+
+ Assert.ok(
+ document.getElementById("contextual-feature-recommendation-notification")
+ .secondaryButton,
+ "There should be a cancel button"
+ );
+
+ // Click the Not Now button
+ document
+ .getElementById("contextual-feature-recommendation-notification")
+ .secondaryButton.click();
+
+ await hidePanel;
+
+ Assert.ok(
+ document.getElementById("contextual-feature-recommendation-notification"),
+ "The notification should not dissapear"
+ );
+
+ await BrowserTestUtils.waitForCondition(
+ () => gURLBar.getAttribute("cfr-recommendation-state") === "collapsed",
+ "Clicking the secondary button should collapse the notification"
+ );
+
+ clearNotifications();
+ CFRPageActions.clearRecommendations();
+});
+
+add_task(async function test_cfr_addon_install() {
+ // addRecommendation checks that scheme starts with http and host matches
+ const browser = gBrowser.selectedBrowser;
+ BrowserTestUtils.loadURI(browser, "http://example.com/");
+ await BrowserTestUtils.browserLoaded(browser, false, "http://example.com/");
+
+ const response = await trigger_cfr_panel(browser, "example.com", {
+ action: { type: "INSTALL_ADDON_FROM_URL" },
+ });
+ Assert.ok(
+ response,
+ "Should return true if addRecommendation checks were successful"
+ );
+
+ const showPanel = BrowserTestUtils.waitForEvent(
+ PopupNotifications.panel,
+ "popupshown"
+ );
+ // Open the panel
+ document.getElementById("contextual-feature-recommendation").click();
+ await showPanel;
+
+ Assert.ok(
+ document.getElementById("contextual-feature-recommendation-notification")
+ .hidden === false,
+ "Panel should be visible"
+ );
+ checkCFRAddonsElements(
+ document.getElementById("contextual-feature-recommendation-notification")
+ );
+
+ // Check there is a primary button and click it. It will trigger the callback.
+ Assert.ok(
+ document.getElementById("contextual-feature-recommendation-notification")
+ .button
+ );
+ const hidePanel = BrowserTestUtils.waitForEvent(
+ PopupNotifications.panel,
+ "popuphidden"
+ );
+ document
+ .getElementById("contextual-feature-recommendation-notification")
+ .button.click();
+ await hidePanel;
+
+ await BrowserTestUtils.waitForEvent(PopupNotifications.panel, "popupshown");
+
+ let [notification] = PopupNotifications.panel.childNodes;
+ // Trying to install the addon will trigger a progress popup or an error popup if
+ // running the test multiple times in a row
+ Assert.ok(
+ notification.id === "addon-progress-notification" ||
+ notification.id === "addon-install-failed-notification",
+ "Should try to install the addon"
+ );
+
+ clearNotifications();
+});
+
+add_task(async function test_cfr_pin_tab_notification_show() {
+ // addRecommendation checks that scheme starts with http and host matches
+ let browser = gBrowser.selectedBrowser;
+ BrowserTestUtils.loadURI(browser, "http://example.com/");
+ await BrowserTestUtils.browserLoaded(browser, false, "http://example.com/");
+
+ const response = await trigger_cfr_panel(browser, "example.com", {
+ action: { type: "PIN_CURRENT_TAB" },
+ category: "cfrFeatures",
+ layout: "message_and_animation",
+ });
+ Assert.ok(
+ response,
+ "Should return true if addRecommendation checks were successful"
+ );
+
+ const showPanel = BrowserTestUtils.waitForEvent(
+ PopupNotifications.panel,
+ "popupshown"
+ );
+ // Open the panel
+ document.getElementById("contextual-feature-recommendation").click();
+ await showPanel;
+
+ const notification = document.getElementById(
+ "contextual-feature-recommendation-notification"
+ );
+ checkCFRFeaturesElements(notification);
+
+ // Check there is a primary button and click it. It will trigger the callback.
+ Assert.ok(notification.button);
+ let hidePanel = BrowserTestUtils.waitForEvent(
+ PopupNotifications.panel,
+ "popuphidden"
+ );
+ document
+ .getElementById("contextual-feature-recommendation-notification")
+ .button.click();
+ await hidePanel;
+
+ await BrowserTestUtils.waitForCondition(
+ () => gBrowser.selectedTab.pinned,
+ "Primary action should pin tab"
+ );
+ Assert.ok(gBrowser.selectedTab.pinned, "Current tab should be pinned");
+ gBrowser.unpinTab(gBrowser.selectedTab);
+
+ // Clicking the primary action also removes the notification
+ Assert.equal(
+ PopupNotifications._currentNotifications.length,
+ 0,
+ "Should have removed the notification"
+ );
+});
+
+add_task(
+ async function test_cfr_social_tracking_protection_notification_show() {
+ // addRecommendation checks that scheme starts with http and host matches
+ let browser = gBrowser.selectedBrowser;
+ BrowserTestUtils.loadURI(browser, "http://example.com/");
+ await BrowserTestUtils.browserLoaded(browser, false, "http://example.com/");
+
+ const showPanel = BrowserTestUtils.waitForEvent(
+ PopupNotifications.panel,
+ "popupshown"
+ );
+
+ const response = await trigger_cfr_panel(browser, "example.com", {
+ action: { type: "OPEN_PROTECTION_PANEL" },
+ category: "cfrFeatures",
+ layout: "icon_and_message",
+ skip_address_bar_notifier: true,
+ use_single_secondary_button: true,
+ });
+ Assert.ok(
+ response,
+ "Should return true if addRecommendation checks were successful"
+ );
+ await showPanel;
+
+ const notification = document.getElementById(
+ "contextual-feature-recommendation-notification"
+ );
+ checkCFRSocialTrackingProtection(notification);
+
+ // Check there is a primary button and click it. It will trigger the callback.
+ Assert.ok(notification.button);
+ let hidePanel = BrowserTestUtils.waitForEvent(
+ PopupNotifications.panel,
+ "popuphidden"
+ );
+ document
+ .getElementById("contextual-feature-recommendation-notification")
+ .button.click();
+ await hidePanel;
+ }
+);
+
+add_task(
+ async function test_cfr_tracking_protection_milestone_notification_remove() {
+ await SpecialPowers.pushPrefEnv({
+ set: [
+ ["browser.contentblocking.cfr-milestone.milestone-achieved", 1000],
+ [
+ "browser.newtabpage.activity-stream.asrouter.providers.cfr",
+ `{"id":"cfr","enabled":true,"type":"local","localProvider":"CFRMessageProvider","updateCycleInMs":3600000}`,
+ ],
+ ],
+ });
+
+ // addRecommendation checks that scheme starts with http and host matches
+ let browser = gBrowser.selectedBrowser;
+ BrowserTestUtils.loadURI(browser, "http://example.com/");
+ await BrowserTestUtils.browserLoaded(browser, false, "http://example.com/");
+
+ const showPanel = BrowserTestUtils.waitForEvent(
+ PopupNotifications.panel,
+ "popupshown"
+ );
+
+ Services.obs.notifyObservers(
+ {
+ wrappedJSObject: {
+ event: "ContentBlockingMilestone",
+ },
+ },
+ "SiteProtection:ContentBlockingMilestone"
+ );
+
+ await showPanel;
+
+ const notification = document.getElementById(
+ "contextual-feature-recommendation-notification"
+ );
+
+ checkCFRTrackingProtectionMilestone(notification);
+
+ Assert.ok(notification.secondaryButton);
+ let hidePanel = BrowserTestUtils.waitForEvent(
+ PopupNotifications.panel,
+ "popuphidden"
+ );
+
+ document
+ .getElementById("contextual-feature-recommendation-notification")
+ .secondaryButton.click();
+ await hidePanel;
+ Assert.equal(
+ PopupNotifications._currentNotifications.length,
+ 0,
+ "Should have removed the notification"
+ );
+ await SpecialPowers.popPrefEnv();
+ }
+);
+
+add_task(async function test_cfr_features_and_addon_show() {
+ // addRecommendation checks that scheme starts with http and host matches
+ let browser = gBrowser.selectedBrowser;
+ BrowserTestUtils.loadURI(browser, "http://example.com/");
+ await BrowserTestUtils.browserLoaded(browser, false, "http://example.com/");
+
+ // Trigger Feature CFR
+ let response = await trigger_cfr_panel(browser, "example.com", {
+ action: { type: "PIN_CURRENT_TAB" },
+ category: "cfrFeatures",
+ layout: "message_and_animation",
+ });
+ Assert.ok(
+ response,
+ "Should return true if addRecommendation checks were successful"
+ );
+
+ let showPanel = BrowserTestUtils.waitForEvent(
+ PopupNotifications.panel,
+ "popupshown"
+ );
+ // Open the panel
+ document.getElementById("contextual-feature-recommendation").click();
+ await showPanel;
+
+ const notification = document.getElementById(
+ "contextual-feature-recommendation-notification"
+ );
+ checkCFRFeaturesElements(notification);
+
+ // Check there is a primary button and click it. It will trigger the callback.
+ Assert.ok(notification.button);
+ let hidePanel = BrowserTestUtils.waitForEvent(
+ PopupNotifications.panel,
+ "popuphidden"
+ );
+ document
+ .getElementById("contextual-feature-recommendation-notification")
+ .button.click();
+ await hidePanel;
+
+ // Clicking the primary action also removes the notification
+ Assert.equal(
+ PopupNotifications._currentNotifications.length,
+ 0,
+ "Should have removed the notification"
+ );
+
+ // Trigger Addon CFR
+ response = await trigger_cfr_panel(browser, "example.com");
+ Assert.ok(
+ response,
+ "Should return true if addRecommendation checks were successful"
+ );
+
+ showPanel = BrowserTestUtils.waitForEvent(
+ PopupNotifications.panel,
+ "popupshown"
+ );
+ // Open the panel
+ document.getElementById("contextual-feature-recommendation").click();
+ await showPanel;
+
+ Assert.ok(
+ document.getElementById("contextual-feature-recommendation-notification")
+ .hidden === false,
+ "Panel should be visible"
+ );
+ checkCFRAddonsElements(
+ document.getElementById("contextual-feature-recommendation-notification")
+ );
+
+ // Check there is a primary button and click it. It will trigger the callback.
+ Assert.ok(notification.button);
+ hidePanel = BrowserTestUtils.waitForEvent(
+ PopupNotifications.panel,
+ "popuphidden"
+ );
+ document
+ .getElementById("contextual-feature-recommendation-notification")
+ .button.click();
+ await hidePanel;
+
+ // Clicking the primary action also removes the notification
+ Assert.equal(
+ PopupNotifications._currentNotifications.length,
+ 0,
+ "Should have removed the notification"
+ );
+});
+
+add_task(async function test_cfr_addon_and_features_show() {
+ // addRecommendation checks that scheme starts with http and host matches
+ let browser = gBrowser.selectedBrowser;
+ BrowserTestUtils.loadURI(browser, "http://example.com/");
+ await BrowserTestUtils.browserLoaded(browser, false, "http://example.com/");
+
+ // Trigger Feature CFR
+ let response = await trigger_cfr_panel(browser, "example.com");
+ Assert.ok(
+ response,
+ "Should return true if addRecommendation checks were successful"
+ );
+
+ let showPanel = BrowserTestUtils.waitForEvent(
+ PopupNotifications.panel,
+ "popupshown"
+ );
+ // Open the panel
+ document.getElementById("contextual-feature-recommendation").click();
+ await showPanel;
+
+ const notification = document.getElementById(
+ "contextual-feature-recommendation-notification"
+ );
+ checkCFRAddonsElements(notification);
+
+ // Check there is a primary button and click it. It will trigger the callback.
+ Assert.ok(notification.button);
+ let hidePanel = BrowserTestUtils.waitForEvent(
+ PopupNotifications.panel,
+ "popuphidden"
+ );
+ document
+ .getElementById("contextual-feature-recommendation-notification")
+ .button.click();
+ await hidePanel;
+
+ // Clicking the primary action also removes the notification
+ Assert.equal(
+ PopupNotifications._currentNotifications.length,
+ 0,
+ "Should have removed the notification"
+ );
+
+ // Trigger Addon CFR
+ response = await trigger_cfr_panel(browser, "example.com", {
+ action: { type: "PIN_CURRENT_TAB" },
+ category: "cfrAddons",
+ });
+ Assert.ok(
+ response,
+ "Should return true if addRecommendation checks were successful"
+ );
+
+ showPanel = BrowserTestUtils.waitForEvent(
+ PopupNotifications.panel,
+ "popupshown"
+ );
+ // Open the panel
+ document.getElementById("contextual-feature-recommendation").click();
+ await showPanel;
+
+ Assert.ok(
+ document.getElementById("contextual-feature-recommendation-notification")
+ .hidden === false,
+ "Panel should be visible"
+ );
+ checkCFRAddonsElements(
+ document.getElementById("contextual-feature-recommendation-notification")
+ );
+
+ // Check there is a primary button and click it. It will trigger the callback.
+ Assert.ok(notification.button);
+ hidePanel = BrowserTestUtils.waitForEvent(
+ PopupNotifications.panel,
+ "popuphidden"
+ );
+ document
+ .getElementById("contextual-feature-recommendation-notification")
+ .button.click();
+ await hidePanel;
+
+ // Clicking the primary action also removes the notification
+ Assert.equal(
+ PopupNotifications._currentNotifications.length,
+ 0,
+ "Should have removed the notification"
+ );
+});
+
+add_task(async function test_onLocationChange_cb() {
+ let count = 0;
+ const triggerHandler = () => ++count;
+ const TEST_URL =
+ "https://example.com/browser/browser/components/newtab/test/browser/blue_page.html";
+ const browser = gBrowser.selectedBrowser;
+
+ await ASRouterTriggerListeners.get("openURL").init(triggerHandler, [
+ "example.com",
+ ]);
+
+ BrowserTestUtils.loadURI(browser, "about:blank");
+ await BrowserTestUtils.browserLoaded(browser, false, "about:blank");
+
+ BrowserTestUtils.loadURI(browser, "http://example.com/");
+ await BrowserTestUtils.browserLoaded(browser, false, "http://example.com/");
+
+ Assert.equal(count, 1, "Count navigation to example.com");
+
+ // Anchor scroll triggers a location change event with the same document
+ // https://searchfox.org/mozilla-central/rev/8848b9741fc4ee4e9bc3ae83ea0fc048da39979f/uriloader/base/nsIWebProgressListener.idl#400-403
+ BrowserTestUtils.loadURI(browser, "http://example.com/#foo");
+ await BrowserTestUtils.waitForLocationChange(
+ gBrowser,
+ "http://example.com/#foo"
+ );
+
+ Assert.equal(count, 1, "It should ignore same page navigation");
+
+ BrowserTestUtils.loadURI(browser, TEST_URL);
+ await BrowserTestUtils.browserLoaded(browser, false, TEST_URL);
+
+ Assert.equal(count, 2, "We moved to a new document");
+
+ registerCleanupFunction(() => {
+ ASRouterTriggerListeners.get("openURL").uninit();
+ });
+});
+
+add_task(async function test_matchPattern() {
+ let count = 0;
+ const triggerHandler = () => ++count;
+ const frequentVisitsTrigger = ASRouterTriggerListeners.get("frequentVisits");
+ await frequentVisitsTrigger.init(triggerHandler, [], ["*://*.example.com/"]);
+
+ const browser = gBrowser.selectedBrowser;
+ BrowserTestUtils.loadURI(browser, "http://example.com/");
+ await BrowserTestUtils.browserLoaded(browser, false, "http://example.com/");
+
+ await BrowserTestUtils.waitForCondition(
+ () => frequentVisitsTrigger._visits.get("example.com").length === 1,
+ "Registered pattern matched the current location"
+ );
+
+ BrowserTestUtils.loadURI(browser, "about:config");
+ await BrowserTestUtils.browserLoaded(browser, false, "about:config");
+
+ await BrowserTestUtils.waitForCondition(
+ () => frequentVisitsTrigger._visits.get("example.com").length === 1,
+ "Navigated to a new page but not a match"
+ );
+
+ BrowserTestUtils.loadURI(browser, "http://example.com/");
+ await BrowserTestUtils.browserLoaded(browser, false, "http://example.com/");
+
+ await BrowserTestUtils.waitForCondition(
+ () => frequentVisitsTrigger._visits.get("example.com").length === 1,
+ "Navigated to a location that matches the pattern but within 15 mins"
+ );
+
+ BrowserTestUtils.loadURI(browser, "http://www.example.com/");
+ await BrowserTestUtils.browserLoaded(
+ browser,
+ false,
+ "http://www.example.com/"
+ );
+
+ await BrowserTestUtils.waitForCondition(
+ () => frequentVisitsTrigger._visits.get("www.example.com").length === 1,
+ "www.example.com is a different host that also matches the pattern."
+ );
+ await BrowserTestUtils.waitForCondition(
+ () => frequentVisitsTrigger._visits.get("example.com").length === 1,
+ "www.example.com is a different host that also matches the pattern."
+ );
+
+ registerCleanupFunction(() => {
+ ASRouterTriggerListeners.get("frequentVisits").uninit();
+ });
+});
+
+add_task(async function test_providerNames() {
+ const providersBranch =
+ "browser.newtabpage.activity-stream.asrouter.providers.";
+ const cfrProviderPrefs = Services.prefs.getChildList(providersBranch);
+ for (const prefName of cfrProviderPrefs) {
+ const prefValue = JSON.parse(Services.prefs.getStringPref(prefName));
+ if (prefValue && prefValue.id) {
+ // Snippets are disabled in tests and value is set to []
+ Assert.equal(
+ prefValue.id,
+ prefName.slice(providersBranch.length),
+ "Provider id and pref name do not match"
+ );
+ }
+ }
+});
+
+add_task(async function test_cfr_notification_keyboard() {
+ // addRecommendation checks that scheme starts with http and host matches
+ const browser = gBrowser.selectedBrowser;
+ BrowserTestUtils.loadURI(browser, "http://example.com/");
+ await BrowserTestUtils.browserLoaded(browser, false, "http://example.com/");
+
+ const response = await trigger_cfr_panel(browser, "example.com");
+ Assert.ok(
+ response,
+ "Should return true if addRecommendation checks were successful"
+ );
+
+ // Open the panel with the keyboard.
+ // Toolbar buttons aren't always focusable; toolbar keyboard navigation
+ // makes them focusable on demand. Therefore, we must force focus.
+ const button = document.getElementById("contextual-feature-recommendation");
+ button.setAttribute("tabindex", "-1");
+ button.focus();
+ button.removeAttribute("tabindex");
+
+ let focused = BrowserTestUtils.waitForEvent(
+ PopupNotifications.panel,
+ "focus",
+ true
+ );
+ EventUtils.synthesizeKey(" ");
+ await focused;
+ Assert.ok(true, "Focus inside panel after button pressed");
+
+ let hidden = BrowserTestUtils.waitForEvent(
+ PopupNotifications.panel,
+ "popuphidden"
+ );
+ EventUtils.synthesizeKey("KEY_Escape");
+ await hidden;
+ Assert.ok(true, "Panel hidden after Escape pressed");
+
+ const showPanel = BrowserTestUtils.waitForEvent(
+ PopupNotifications.panel,
+ "popupshown"
+ );
+ // Need to dismiss the notification to clear the RecommendationMap
+ document.getElementById("contextual-feature-recommendation").click();
+ await showPanel;
+
+ const hidePanel = BrowserTestUtils.waitForEvent(
+ PopupNotifications.panel,
+ "popuphidden"
+ );
+ document
+ .getElementById("contextual-feature-recommendation-notification")
+ .button.click();
+ await hidePanel;
+});
+
+add_task(function test_updateCycleForProviders() {
+ Services.prefs
+ .getChildList("browser.newtabpage.activity-stream.asrouter.providers.")
+ .forEach(provider => {
+ const prefValue = JSON.parse(Services.prefs.getStringPref(provider, ""));
+ if (prefValue && prefValue.type === "remote-settings") {
+ Assert.ok(prefValue.updateCycleInMs);
+ }
+ });
+});
+
+add_task(async function test_heartbeat_tactic_2() {
+ clearNotifications();
+ registerCleanupFunction(() => {
+ // Remove the tab opened by clicking the heartbeat message
+ gBrowser.removeCurrentTab();
+ clearNotifications();
+ });
+
+ const msg = (await CFRMessageProvider.getMessages()).find(
+ m => m.id === "HEARTBEAT_TACTIC_2"
+ );
+ const shown = await CFRPageActions.addRecommendation(
+ gBrowser.selectedBrowser,
+ null,
+ {
+ ...msg,
+ id: `HEARTBEAT_MOCHITEST_${Date.now()}`,
+ groups: ["mochitest-group"],
+ targeting: true,
+ },
+ // Use the real AS dispatch method to trigger real notifications
+ ASRouter.dispatchCFRAction
+ );
+
+ Assert.ok(shown, "Heartbeat CFR added");
+
+ // Wait for visibility change
+ BrowserTestUtils.waitForCondition(
+ () => document.getElementById("contextual-feature-recommendation"),
+ "Heartbeat button exists"
+ );
+
+ let newTabPromise = BrowserTestUtils.waitForNewTab(
+ gBrowser,
+ Services.urlFormatter.formatURL(msg.content.action.url),
+ true
+ );
+
+ document.getElementById("contextual-feature-recommendation").click();
+
+ await newTabPromise;
+});
+
+add_task(async function test_cfr_tracking_protection_fingerprint_doorhanger() {
+ await SpecialPowers.pushPrefEnv({
+ set: [
+ [
+ "browser.newtabpage.activity-stream.asrouter.providers.cfr",
+ `{"id":"cfr","enabled":true,"type":"local","localProvider":"CFRMessageProvider","updateCycleInMs":0}`,
+ ],
+ ],
+ });
+
+ // addRecommendation checks that scheme starts with http and host matches
+ let browser = gBrowser.selectedBrowser;
+ BrowserTestUtils.loadURI(browser, "http://example.com/");
+ await BrowserTestUtils.browserLoaded(browser, false, "http://example.com/");
+
+ const showPanel = BrowserTestUtils.waitForEvent(
+ PopupNotifications.panel,
+ "popupshown"
+ );
+
+ Services.obs.notifyObservers(
+ {
+ wrappedJSObject: {
+ // Combination of multiple content blocking events
+ // https://searchfox.org/mozilla-central/rev/2fcab997046ba9e068c5391dc7d8848e121d84f8/uriloader/base/nsIWebProgressListener.idl#340
+ event: 538091584,
+ host: "example.com",
+ browser,
+ },
+ },
+ "SiteProtection:ContentBlockingEvent"
+ );
+
+ await showPanel;
+
+ const notification = document.getElementById(
+ "contextual-feature-recommendation-notification"
+ );
+
+ checkCFRSocialTrackingProtection(notification);
+
+ Assert.ok(notification.secondaryButton);
+ let hidePanel = BrowserTestUtils.waitForEvent(
+ PopupNotifications.panel,
+ "popuphidden"
+ );
+
+ document
+ .getElementById("contextual-feature-recommendation-notification")
+ .secondaryButton.click();
+ await hidePanel;
+ Assert.equal(
+ PopupNotifications._currentNotifications.length,
+ 0,
+ "Should have removed the notification"
+ );
+ // Secondary button will block the message, we need to undo
+ await ASRouter.unblockMessageById("FINGERPRINTERS_PROTECTION");
+ await SpecialPowers.popPrefEnv();
+});
diff --git a/browser/components/newtab/test/browser/browser_asrouter_experimentsAPILoader.js b/browser/components/newtab/test/browser/browser_asrouter_experimentsAPILoader.js
new file mode 100644
index 0000000000..15d9cc6ea0
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_asrouter_experimentsAPILoader.js
@@ -0,0 +1,268 @@
+const { RemoteSettings } = ChromeUtils.import(
+ "resource://services-settings/remote-settings.js"
+);
+const { ASRouter } = ChromeUtils.import(
+ "resource://activity-stream/lib/ASRouter.jsm"
+);
+const { RemoteSettingsExperimentLoader } = ChromeUtils.import(
+ "resource://messaging-system/lib/RemoteSettingsExperimentLoader.jsm"
+);
+const { ExperimentAPI } = ChromeUtils.import(
+ "resource://messaging-system/experiments/ExperimentAPI.jsm"
+);
+const { ExperimentFakes } = ChromeUtils.import(
+ "resource://testing-common/MSTestUtils.jsm"
+);
+const { TelemetryFeed } = ChromeUtils.import(
+ "resource://activity-stream/lib/TelemetryFeed.jsm"
+);
+const { TelemetryTestUtils } = ChromeUtils.import(
+ "resource://testing-common/TelemetryTestUtils.jsm"
+);
+
+const EXPERIMENT_PAYLOAD = () =>
+ ExperimentFakes.recipe(
+ // In tests by default studies/experiments are turned off. We turn them on
+ // to run the test and rollback at the end. Cleanup causes unenrollment so
+ // for cases where the test runs multiple times we need unique ids.
+ `test_xman_cfr_${Date.now()}`,
+ {
+ id: "xman_test_message",
+ bucketConfig: {
+ count: 100,
+ start: 0,
+ total: 100,
+ namespace: "mochitest",
+ randomizationUnit: "normandy_id",
+ },
+ branches: [
+ {
+ slug: "control",
+ ratio: 1,
+ feature: {
+ featureId: "cfr",
+ enabled: true,
+ value: {
+ id: "xman_test_message",
+ content: {
+ text: "This is a test CFR",
+ addon: {
+ id: "954390",
+ icon:
+ "chrome://activity-stream/content/data/content/assets/cfr_fb_container.png",
+ title: "Facebook Container",
+ users: 1455872,
+ author: "Mozilla",
+ rating: 4.5,
+ amo_url:
+ "https://addons.mozilla.org/firefox/addon/facebook-container/",
+ },
+ buttons: {
+ primary: {
+ label: {
+ string_id: "cfr-doorhanger-extension-ok-button",
+ },
+ action: {
+ data: {
+ url: null,
+ },
+ type: "INSTALL_ADDON_FROM_URL",
+ },
+ },
+ secondary: [
+ {
+ label: {
+ string_id: "cfr-doorhanger-extension-cancel-button",
+ },
+ action: {
+ type: "CANCEL",
+ },
+ },
+ {
+ label: {
+ string_id:
+ "cfr-doorhanger-extension-never-show-recommendation",
+ },
+ },
+ {
+ label: {
+ string_id:
+ "cfr-doorhanger-extension-manage-settings-button",
+ },
+ action: {
+ data: {
+ origin: "CFR",
+ category: "general-cfraddons",
+ },
+ type: "OPEN_PREFERENCES_PAGE",
+ },
+ },
+ ],
+ },
+ category: "cfrAddons",
+ bucket_id: "CFR_M1",
+ info_icon: {
+ label: {
+ string_id: "cfr-doorhanger-extension-sumo-link",
+ },
+ sumo_path: "extensionrecommendations",
+ },
+ heading_text: "Welcome to the experiment",
+ notification_text: {
+ string_id: "cfr-doorhanger-extension-notification2",
+ },
+ },
+ trigger: {
+ id: "openURL",
+ params: [
+ "www.facebook.com",
+ "facebook.com",
+ "www.instagram.com",
+ "instagram.com",
+ "www.whatsapp.com",
+ "whatsapp.com",
+ "web.whatsapp.com",
+ "www.messenger.com",
+ "messenger.com",
+ ],
+ },
+ template: "cfr_doorhanger",
+ frequency: {
+ lifetime: 3,
+ },
+ targeting: "true",
+ },
+ },
+ },
+ ],
+ userFacingName: "About:Welcome Pull Factor Reinforcement",
+ isEnrollmentPaused: false,
+ experimentDocumentUrl:
+ "https://experimenter.services.mozilla.com/experiments/aboutwelcome-pull-factor-reinforcement/",
+ userFacingDescription:
+ "This study uses 4 different variants of about:welcome with a goal of testing new experiment framework and get insights on whether reinforcing pull-factors improves retention.",
+ }
+ );
+
+const client = RemoteSettings("nimbus-desktop-experiments");
+
+// no `add_task` because we want to run this setup before each test not before
+// the entire test suite.
+async function setup(getPayload = EXPERIMENT_PAYLOAD) {
+ await SpecialPowers.pushPrefEnv({
+ set: [
+ ["app.shield.optoutstudies.enabled", true],
+ [
+ "browser.newtabpage.activity-stream.asrouter.providers.messaging-experiments",
+ `{"id":"messaging-experiments","enabled":true,"type":"remote-experiments","messageGroups":["cfr","whats-new-panel","moments-page","snippets","cfr-fxa"],"updateCycleInMs":0}`,
+ ],
+ ],
+ });
+
+ await client.db.importChanges(
+ {},
+ 42,
+ [
+ // Modify targeting to ensure the messages always show up
+ { ...getPayload() },
+ ],
+ { clear: true }
+ );
+}
+
+async function cleanup() {
+ await client.db.clear();
+ await SpecialPowers.popPrefEnv();
+ // Reload the provider
+ await ASRouter._updateMessageProviders();
+}
+
+add_task(async function test_loading_experimentsAPI() {
+ await setup();
+ // Fetch the new recipe from RS
+ await RemoteSettingsExperimentLoader.updateRecipes();
+ await BrowserTestUtils.waitForCondition(
+ () => ExperimentAPI.getExperiment({ featureId: "cfr" }),
+ "ExperimentAPI should return an experiment"
+ );
+
+ const telemetryFeedInstance = new TelemetryFeed();
+ Assert.ok(
+ telemetryFeedInstance.isInCFRCohort,
+ "Telemetry should return true"
+ );
+
+ // Reload the provider
+ await ASRouter._updateMessageProviders();
+ // Wait to load the messages from the messaging-experiments provider
+ await ASRouter.loadMessagesFromAllProviders();
+
+ Assert.ok(
+ ASRouter.state.messages.find(m => m.id === "xman_test_message"),
+ "Experiment message found in ASRouter state"
+ );
+
+ await cleanup();
+});
+
+add_task(async function test_exposure_ping() {
+ await setup();
+ Services.telemetry.clearScalars();
+ // Fetch the new recipe from RS
+ await RemoteSettingsExperimentLoader.updateRecipes();
+ await BrowserTestUtils.waitForCondition(
+ () => ExperimentAPI.getExperiment({ featureId: "cfr" }),
+ "ExperimentAPI should return an experiment"
+ );
+
+ // Reload the provider
+ await ASRouter._updateMessageProviders();
+ // Wait to load the messages from the messaging-experiments provider
+ await ASRouter.loadMessagesFromAllProviders();
+
+ Assert.ok(
+ ASRouter.state.messages.find(m => m.id === "xman_test_message"),
+ "Experiment message found in ASRouter state"
+ );
+
+ const exposureSpy = sinon.spy(ExperimentAPI, "recordExposureEvent");
+
+ await ASRouter.sendTriggerMessage({
+ tabId: 1,
+ browser: gBrowser.selectedBrowser,
+ id: "openURL",
+ param: { host: "messenger.com" },
+ });
+
+ Assert.ok(exposureSpy.callCount === 1, "Should send exposure ping");
+ const scalars = TelemetryTestUtils.getProcessScalars("parent", true, true);
+ TelemetryTestUtils.assertKeyedScalar(
+ scalars,
+ "telemetry.event_counts",
+ "normandy#expose#feature_study",
+ 1
+ );
+
+ exposureSpy.restore();
+ await cleanup();
+});
+
+add_task(async function test_featureless_experiment() {
+ const payload = () => {
+ let experiment = EXPERIMENT_PAYLOAD();
+ // Remove the feature property from the branch
+ experiment.branches.forEach(branch => delete branch.feature);
+ return experiment;
+ };
+ Assert.ok(ExperimentAPI._store.getAllActive().length === 0, "Empty store");
+ await setup(payload);
+ // Fetch the new recipe from RS
+ await RemoteSettingsExperimentLoader.updateRecipes();
+ // Enrollment was successful; featureless experiments shouldn't break anything
+ await BrowserTestUtils.waitForCondition(
+ () => ExperimentAPI._store.getAllActive().length === 1,
+ "ExperimentAPI should return an experiment"
+ );
+
+ await cleanup();
+});
diff --git a/browser/components/newtab/test/browser/browser_asrouter_group_frequency.js b/browser/components/newtab/test/browser/browser_asrouter_group_frequency.js
new file mode 100644
index 0000000000..f6cef72e65
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_asrouter_group_frequency.js
@@ -0,0 +1,188 @@
+const { ASRouter } = ChromeUtils.import(
+ "resource://activity-stream/lib/ASRouter.jsm"
+);
+const { RemoteSettings } = ChromeUtils.import(
+ "resource://services-settings/remote-settings.js"
+);
+const { CFRMessageProvider } = ChromeUtils.import(
+ "resource://activity-stream/lib/CFRMessageProvider.jsm"
+);
+const { CFRPageActions } = ChromeUtils.import(
+ "resource://activity-stream/lib/CFRPageActions.jsm"
+);
+
+/**
+ * Load and modify a message for the test.
+ */
+add_task(async function setup() {
+ const initialMsgCount = ASRouter.state.messages.length;
+ const heartbeatMsg = (await CFRMessageProvider.getMessages()).find(
+ m => m.id === "HEARTBEAT_TACTIC_2"
+ );
+ const testMessage = {
+ ...heartbeatMsg,
+ groups: ["messaging-experiments"],
+ targeting: "true",
+ // Ensure no overlap due to frequency capping with other tests
+ id: `HEARTBEAT_MESSAGE_${Date.now()}`,
+ };
+ const client = RemoteSettings("cfr");
+ await client.db.importChanges({}, 42, [testMessage], {
+ clear: true,
+ });
+
+ // Force the CFR provider cache to 0 by modifying updateCycleInMs
+ await SpecialPowers.pushPrefEnv({
+ set: [
+ [
+ "browser.newtabpage.activity-stream.asrouter.providers.cfr",
+ `{"id":"cfr","enabled":true,"type":"remote-settings","bucket":"cfr","updateCycleInMs":0}`,
+ ],
+ ],
+ });
+
+ // Reload the providers
+ await BrowserTestUtils.waitForCondition(async () => {
+ await ASRouter._updateMessageProviders();
+ await ASRouter.loadMessagesFromAllProviders();
+ return ASRouter.state.messages.length > initialMsgCount;
+ }, "Should load the extra heartbeat message");
+
+ BrowserTestUtils.waitForCondition(
+ () => ASRouter.state.messages.find(m => m.id === testMessage.id),
+ "Wait to load the message"
+ );
+
+ const msg = ASRouter.state.messages.find(m => m.id === testMessage.id);
+ Assert.equal(msg.targeting, "true");
+ Assert.equal(msg.groups[0], "messaging-experiments");
+
+ registerCleanupFunction(async () => {
+ await client.db.clear();
+ // Reload the providers
+ await BrowserTestUtils.waitForCondition(async () => {
+ await ASRouter._updateMessageProviders();
+ await ASRouter.loadMessagesFromAllProviders();
+ return ASRouter.state.messages.length === initialMsgCount;
+ }, "Should reset messages");
+ await SpecialPowers.popPrefEnv();
+ });
+});
+
+/**
+ * Test group frequency capping.
+ * Message has a lifetime frequency of 3 but it's group has a lifetime frequency
+ * of 2. It should only show up twice.
+ * We update the provider to remove any daily limitations so it should show up
+ * on every new tab load.
+ */
+add_task(async function test_heartbeat_tactic_2() {
+ const TEST_URL = "http://example.com";
+ const msg = ASRouter.state.messages.find(m =>
+ m.groups.includes("messaging-experiments")
+ );
+ Assert.ok(msg, "Message found");
+ const groupConfiguration = {
+ id: "messaging-experiments",
+ enabled: true,
+ frequency: { lifetime: 2 },
+ };
+ const client = RemoteSettings("message-groups");
+ await client.db.importChanges({}, 42, [groupConfiguration], {
+ clear: true,
+ });
+
+ // Force the WNPanel provider cache to 0 by modifying updateCycleInMs
+ await SpecialPowers.pushPrefEnv({
+ set: [
+ [
+ "browser.newtabpage.activity-stream.asrouter.providers.message-groups",
+ `{"id":"message-groups","enabled":true,"type":"remote-settings","bucket":"message-groups","updateCycleInMs":0}`,
+ ],
+ ],
+ });
+
+ await BrowserTestUtils.waitForCondition(async () => {
+ const msgs = await client.get();
+ return msgs.find(m => m.id === groupConfiguration.id);
+ }, "Wait for RS message");
+
+ // Reload the providers
+ await ASRouter._updateMessageProviders();
+ await ASRouter.loadAllMessageGroups();
+
+ let groupState = await BrowserTestUtils.waitForCondition(
+ () => ASRouter.state.groups.find(g => g.id === groupConfiguration.id),
+ "Wait for group config to load"
+ );
+ Assert.ok(groupState, "Group config found");
+ Assert.ok(groupState.enabled, "Group is enabled");
+
+ let tab1 = await BrowserTestUtils.openNewForegroundTab(gBrowser, TEST_URL);
+ BrowserTestUtils.loadURI(tab1.linkedBrowser, TEST_URL);
+
+ let chiclet = document.getElementById("contextual-feature-recommendation");
+ Assert.ok(chiclet, "CFR chiclet element found (tab1)");
+ await BrowserTestUtils.waitForCondition(
+ () => !chiclet.hidden,
+ "Chiclet should be visible (tab1)"
+ );
+
+ await BrowserTestUtils.waitForCondition(
+ () =>
+ ASRouter.state.messageImpressions[msg.id] &&
+ ASRouter.state.messageImpressions[msg.id].length === 1,
+ "First impression recorded"
+ );
+
+ BrowserTestUtils.removeTab(tab1);
+
+ let tab2 = await BrowserTestUtils.openNewForegroundTab(gBrowser, TEST_URL);
+ BrowserTestUtils.loadURI(tab2.linkedBrowser, TEST_URL);
+
+ Assert.ok(chiclet, "CFR chiclet element found (tab2)");
+ await BrowserTestUtils.waitForCondition(
+ () => !chiclet.hidden,
+ "Chiclet should be visible (tab2)"
+ );
+
+ await BrowserTestUtils.waitForCondition(
+ () =>
+ ASRouter.state.messageImpressions[msg.id] &&
+ ASRouter.state.messageImpressions[msg.id].length === 2,
+ "Second impression recorded"
+ );
+
+ Assert.ok(
+ !ASRouter.isBelowFrequencyCaps(msg),
+ "Should have reached freq limit"
+ );
+
+ BrowserTestUtils.removeTab(tab2);
+
+ let tab3 = await BrowserTestUtils.openNewForegroundTab(gBrowser, TEST_URL);
+ BrowserTestUtils.loadURI(tab3.linkedBrowser, TEST_URL);
+
+ await BrowserTestUtils.waitForCondition(
+ () => chiclet.hidden,
+ "Heartbeat button should be hidden"
+ );
+ Assert.equal(
+ ASRouter.state.messageImpressions[msg.id] &&
+ ASRouter.state.messageImpressions[msg.id].length,
+ 2,
+ "Number of impressions did not increase"
+ );
+
+ BrowserTestUtils.removeTab(tab3);
+
+ info("Cleanup");
+ await client.db.clear();
+ // Reset group impressions
+ await ASRouter.resetGroupsState();
+ // Reload the providers
+ await ASRouter._updateMessageProviders();
+ await ASRouter.loadMessagesFromAllProviders();
+ await SpecialPowers.popPrefEnv();
+ CFRPageActions.clearRecommendations();
+});
diff --git a/browser/components/newtab/test/browser/browser_asrouter_group_userprefs.js b/browser/components/newtab/test/browser/browser_asrouter_group_userprefs.js
new file mode 100644
index 0000000000..172bfdb47c
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_asrouter_group_userprefs.js
@@ -0,0 +1,156 @@
+const { ASRouter } = ChromeUtils.import(
+ "resource://activity-stream/lib/ASRouter.jsm"
+);
+const { RemoteSettings } = ChromeUtils.import(
+ "resource://services-settings/remote-settings.js"
+);
+const { CFRMessageProvider } = ChromeUtils.import(
+ "resource://activity-stream/lib/CFRMessageProvider.jsm"
+);
+const { CFRPageActions } = ChromeUtils.import(
+ "resource://activity-stream/lib/CFRPageActions.jsm"
+);
+
+/**
+ * Load and modify a message for the test.
+ */
+add_task(async function setup() {
+ const initialMsgCount = ASRouter.state.messages.length;
+ const heartbeatMsg = (await CFRMessageProvider.getMessages()).find(
+ m => m.id === "HEARTBEAT_TACTIC_2"
+ );
+ const testMessage = {
+ ...heartbeatMsg,
+ groups: ["messaging-experiments"],
+ targeting: "true",
+ // Ensure no overlap due to frequency capping with other tests
+ id: `HEARTBEAT_MESSAGE_${Date.now()}`,
+ };
+ const client = RemoteSettings("cfr");
+ await client.db.importChanges({}, 42, [testMessage], { clear: true });
+
+ // Force the CFR provider cache to 0 by modifying updateCycleInMs
+ await SpecialPowers.pushPrefEnv({
+ set: [
+ [
+ "browser.newtabpage.activity-stream.asrouter.providers.cfr",
+ `{"id":"cfr","enabled":true,"type":"remote-settings","bucket":"cfr","updateCycleInMs":0}`,
+ ],
+ ],
+ });
+
+ // Reload the providers
+ await BrowserTestUtils.waitForCondition(async () => {
+ await ASRouter._updateMessageProviders();
+ await ASRouter.loadMessagesFromAllProviders();
+ return ASRouter.state.messages.length > initialMsgCount;
+ }, "Should load the extra heartbeat message");
+
+ BrowserTestUtils.waitForCondition(
+ () => ASRouter.state.messages.find(m => m.id === testMessage.id),
+ "Wait to load the message"
+ );
+
+ const msg = ASRouter.state.messages.find(m => m.id === testMessage.id);
+ Assert.equal(msg.targeting, "true");
+ Assert.equal(msg.groups[0], "messaging-experiments");
+
+ registerCleanupFunction(async () => {
+ await client.db.clear();
+ // Reload the providers
+ await BrowserTestUtils.waitForCondition(async () => {
+ await ASRouter._updateMessageProviders();
+ await ASRouter.loadMessagesFromAllProviders();
+ return ASRouter.state.messages.length === initialMsgCount;
+ }, "Should reset messages");
+ await SpecialPowers.popPrefEnv();
+ });
+});
+
+/**
+ * Test group user preferences.
+ * Group is enabled if both user preferences are enabled.
+ */
+add_task(async function test_heartbeat_tactic_2() {
+ const TEST_URL = "http://example.com";
+ const msg = ASRouter.state.messages.find(m =>
+ m.groups.includes("messaging-experiments")
+ );
+ Assert.ok(msg, "Message found");
+ const groupConfiguration = {
+ id: "messaging-experiments",
+ enabled: true,
+ userPreferences: ["browser.userPreference.messaging-experiments"],
+ };
+ const client = RemoteSettings("message-groups");
+ await client.db.importChanges({}, 42, [groupConfiguration], { clear: true });
+
+ await SpecialPowers.pushPrefEnv({
+ set: [
+ [
+ "browser.newtabpage.activity-stream.asrouter.providers.message-groups",
+ `{"id":"message-groups","enabled":true,"type":"remote-settings","bucket":"message-groups","updateCycleInMs":0}`,
+ ],
+ ["browser.userPreference.messaging-experiments", true],
+ ],
+ });
+
+ await BrowserTestUtils.waitForCondition(async () => {
+ const msgs = await client.get();
+ return msgs.find(m => m.id === groupConfiguration.id);
+ }, "Wait for RS message");
+
+ // Reload the providers
+ await ASRouter._updateMessageProviders();
+ await ASRouter.loadAllMessageGroups();
+
+ let groupState = await BrowserTestUtils.waitForCondition(
+ () => ASRouter.state.groups.find(g => g.id === groupConfiguration.id),
+ "Wait for group config to load"
+ );
+ Assert.ok(groupState, "Group config found");
+ Assert.ok(groupState.enabled, "Group is enabled");
+ Assert.ok(ASRouter.isUnblockedMessage(msg), "Message is unblocked");
+
+ let tab1 = await BrowserTestUtils.openNewForegroundTab(gBrowser, TEST_URL);
+ BrowserTestUtils.loadURI(tab1.linkedBrowser, TEST_URL);
+
+ let chiclet = document.getElementById("contextual-feature-recommendation");
+ Assert.ok(chiclet, "CFR chiclet element found");
+ await BrowserTestUtils.waitForCondition(
+ () => !chiclet.hidden,
+ "Chiclet should be visible (userprefs enabled)"
+ );
+
+ await SpecialPowers.pushPrefEnv({
+ set: [["browser.userPreference.messaging-experiments", false]],
+ });
+
+ await BrowserTestUtils.waitForCondition(
+ () =>
+ ASRouter.state.groups.find(
+ g => g.id === groupConfiguration.id && !g.enable
+ ),
+ "Wait for group config to load"
+ );
+
+ let tab2 = await BrowserTestUtils.openNewForegroundTab(gBrowser, TEST_URL);
+ BrowserTestUtils.loadURI(tab2.linkedBrowser, TEST_URL);
+
+ await BrowserTestUtils.waitForCondition(
+ () => chiclet.hidden,
+ "Heartbeat button should not be visible (userprefs disabled)"
+ );
+
+ info("Cleanup");
+ BrowserTestUtils.removeTab(tab1);
+ BrowserTestUtils.removeTab(tab2);
+ await client.db.clear();
+ // Reset group impressions
+ await ASRouter.resetGroupsState();
+ // Reload the providers
+ await ASRouter._updateMessageProviders();
+ await ASRouter.loadMessagesFromAllProviders();
+ await SpecialPowers.popPrefEnv();
+ CFRPageActions.clearRecommendations();
+});
diff --git a/browser/components/newtab/test/browser/browser_asrouter_infobar.js b/browser/components/newtab/test/browser/browser_asrouter_infobar.js
new file mode 100644
index 0000000000..f19025c6df
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_asrouter_infobar.js
@@ -0,0 +1,85 @@
+const { InfoBar } = ChromeUtils.import(
+ "resource://activity-stream/lib/InfoBar.jsm"
+);
+const { CFRMessageProvider } = ChromeUtils.import(
+ "resource://activity-stream/lib/CFRMessageProvider.jsm"
+);
+const { ASRouter } = ChromeUtils.import(
+ "resource://activity-stream/lib/ASRouter.jsm"
+);
+const { BrowserWindowTracker } = ChromeUtils.import(
+ "resource:///modules/BrowserWindowTracker.jsm"
+);
+
+add_task(async function show_and_send_telemetry() {
+ let message = (await CFRMessageProvider.getMessages()).find(
+ m => m.id === "INFOBAR_ACTION_86"
+ );
+
+ Assert.ok(message.id, "Found the message");
+
+ let dispatchStub = sinon.stub();
+ let infobar = InfoBar.showInfoBarMessage(
+ BrowserWindowTracker.getTopWindow().gBrowser.selectedBrowser,
+ message,
+ dispatchStub
+ );
+
+ Assert.equal(dispatchStub.callCount, 2, "Called twice with IMPRESSION");
+ // This is the call to increment impressions for frequency capping
+ Assert.equal(dispatchStub.firstCall.args[0].type, "IMPRESSION");
+ Assert.equal(dispatchStub.firstCall.args[0].data.id, message.id);
+ // This is the telemetry ping
+ Assert.equal(dispatchStub.secondCall.args[0].data.event, "IMPRESSION");
+ Assert.equal(dispatchStub.secondCall.args[0].data.message_id, message.id);
+
+ let primaryBtn = infobar.notification.querySelector(
+ ".notification-button.primary"
+ );
+
+ Assert.ok(primaryBtn, "Has a primary button");
+ primaryBtn.click();
+
+ Assert.equal(dispatchStub.callCount, 4, "Called again with CLICK + removed");
+ Assert.equal(dispatchStub.thirdCall.args[0].type, "USER_ACTION");
+ Assert.equal(
+ dispatchStub.lastCall.args[0].data.event,
+ "CLICK_PRIMARY_BUTTON"
+ );
+});
+
+add_task(async function react_to_trigger() {
+ let message = {
+ ...(await CFRMessageProvider.getMessages()).find(
+ m => m.id === "INFOBAR_ACTION_86"
+ ),
+ };
+ message.targeting = "true";
+ message.content.type = "tab";
+ message.groups = [];
+ message.provider = ASRouter.state.providers[0].id;
+ message.content.message = "Infobar Mochitest";
+ await ASRouter.setState({ messages: [message] });
+
+ let notificationStack = gBrowser.getNotificationBox(gBrowser.selectedBrowser);
+ Assert.ok(
+ !notificationStack.currentNotification,
+ "No notification to start with"
+ );
+
+ await ASRouter.sendTriggerMessage({
+ browser: BrowserWindowTracker.getTopWindow().gBrowser.selectedBrowser,
+ id: "defaultBrowserCheck",
+ });
+
+ await BrowserTestUtils.waitForCondition(
+ () => notificationStack.currentNotification,
+ "Wait for notification to show"
+ );
+
+ Assert.equal(
+ notificationStack.currentNotification.getAttribute("value"),
+ message.id,
+ "Notification id should match"
+ );
+});
diff --git a/browser/components/newtab/test/browser/browser_asrouter_momentspagehub.js b/browser/components/newtab/test/browser/browser_asrouter_momentspagehub.js
new file mode 100644
index 0000000000..d16a86233c
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_asrouter_momentspagehub.js
@@ -0,0 +1,113 @@
+const { PanelTestProvider } = ChromeUtils.import(
+ "resource://activity-stream/lib/PanelTestProvider.jsm"
+);
+const { MomentsPageHub } = ChromeUtils.import(
+ "resource://activity-stream/lib/MomentsPageHub.jsm"
+);
+const { RemoteSettings } = ChromeUtils.import(
+ "resource://services-settings/remote-settings.js"
+);
+const { ASRouter } = ChromeUtils.import(
+ "resource://activity-stream/lib/ASRouter.jsm"
+);
+
+const HOMEPAGE_OVERRIDE_PREF = "browser.startup.homepage_override.once";
+
+add_task(async function test_with_rs_messages() {
+ // Force the WNPanel provider cache to 0 by modifying updateCycleInMs
+ await SpecialPowers.pushPrefEnv({
+ set: [
+ [
+ "browser.newtabpage.activity-stream.asrouter.providers.whats-new-panel",
+ `{"id":"cfr","enabled":true,"type":"remote-settings","bucket":"cfr","updateCycleInMs":0}`,
+ ],
+ ],
+ });
+ const [msg] = (await PanelTestProvider.getMessages()).filter(
+ ({ template }) => template === "update_action"
+ );
+ const initialMessageCount = ASRouter.state.messages.length;
+ const client = RemoteSettings("cfr");
+ await client.db.importChanges(
+ {},
+ 42,
+ [
+ {
+ // Modify targeting and randomize message name to work around the message
+ // getting blocked (for --verify)
+ ...msg,
+ id: `MOMENTS_MOCHITEST_${Date.now()}`,
+ targeting: "true",
+ },
+ ],
+ { clear: true }
+ );
+ // Reload the provider
+ await ASRouter._updateMessageProviders();
+ // Wait to load the WNPanel messages
+ await BrowserTestUtils.waitForCondition(async () => {
+ await ASRouter.loadMessagesFromAllProviders();
+ return ASRouter.state.messages.length > initialMessageCount;
+ }, "Messages did not load");
+
+ await MomentsPageHub.messageRequest({
+ triggerId: "momentsUpdate",
+ template: "update_action",
+ });
+
+ await BrowserTestUtils.waitForCondition(() => {
+ return Services.prefs.getStringPref(HOMEPAGE_OVERRIDE_PREF, "").length;
+ }, "Pref value was not set");
+
+ let value = Services.prefs.getStringPref(HOMEPAGE_OVERRIDE_PREF, "");
+ is(JSON.parse(value).url, msg.content.action.data.url, "Correct value set");
+
+ // Insert a new message and test that priority override works as expected
+ msg.content.action.data.url = "https://www.mozilla.org/#mochitest";
+ await client.db.create(
+ // Modify targeting to ensure the messages always show up
+ {
+ ...msg,
+ id: `MOMENTS_MOCHITEST_${Date.now()}`,
+ priority: 2,
+ targeting: "true",
+ }
+ );
+
+ // Reset so we can `await` for the pref value to be set again
+ Services.prefs.clearUserPref(HOMEPAGE_OVERRIDE_PREF);
+
+ let prevLength = ASRouter.state.messages.length;
+ // Wait to load the messages
+ await BrowserTestUtils.waitForCondition(async () => {
+ await ASRouter.loadMessagesFromAllProviders();
+ return ASRouter.state.messages.length > prevLength;
+ }, "Messages did not load");
+
+ await MomentsPageHub.messageRequest({
+ triggerId: "momentsUpdate",
+ template: "update_action",
+ });
+
+ await BrowserTestUtils.waitForCondition(() => {
+ return Services.prefs.getStringPref(HOMEPAGE_OVERRIDE_PREF, "").length;
+ }, "Pref value was not set");
+
+ value = Services.prefs.getStringPref(HOMEPAGE_OVERRIDE_PREF, "");
+ is(
+ JSON.parse(value).url,
+ msg.content.action.data.url,
+ "Correct value set for higher priority message"
+ );
+
+ await client.db.clear();
+ // Wait to reset the WNPanel messages from state
+ const previousMessageCount = ASRouter.state.messages.length;
+ await BrowserTestUtils.waitForCondition(async () => {
+ await ASRouter.loadMessagesFromAllProviders();
+ return ASRouter.state.messages.length < previousMessageCount;
+ }, "ASRouter messages should have been removed");
+ await SpecialPowers.popPrefEnv();
+ // Reload the provider
+ await ASRouter._updateMessageProviders();
+});
diff --git a/browser/components/newtab/test/browser/browser_asrouter_snippets.js b/browser/components/newtab/test/browser/browser_asrouter_snippets.js
new file mode 100644
index 0000000000..8fac8b5d59
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_asrouter_snippets.js
@@ -0,0 +1,193 @@
+"use strict";
+
+const { ASRouter } = ChromeUtils.import(
+ "resource://activity-stream/lib/ASRouter.jsm"
+);
+
+const { TelemetryFeed } = ChromeUtils.import(
+ "resource://activity-stream/lib/TelemetryFeed.jsm"
+);
+
+add_task(async function render_below_search_snippet() {
+ ASRouter._validPreviewEndpoint = () => true;
+ await BrowserTestUtils.withNewTab(
+ {
+ gBrowser,
+ url:
+ "about:newtab?endpoint=https://example.com/browser/browser/components/newtab/test/browser/snippet_below_search_test.json",
+ },
+ async browser => {
+ await waitForPreloaded(browser);
+
+ const complete = await SpecialPowers.spawn(browser, [], async () => {
+ // Verify the simple_below_search_snippet renders in container below searchbox
+ // and nothing is rendered in the footer.
+ await ContentTaskUtils.waitForCondition(
+ () =>
+ content.document.querySelector(
+ ".below-search-snippet .SimpleBelowSearchSnippet"
+ ),
+ "Should find the snippet inside the below search container"
+ );
+
+ is(
+ 0,
+ content.document.querySelector("#footer-asrouter-container")
+ .childNodes.length,
+ "Should not find any snippets in the footer container"
+ );
+
+ return true;
+ });
+
+ Assert.ok(complete, "Test complete.");
+ }
+ );
+});
+
+add_task(async function render_snippets_icon_and_link() {
+ await BrowserTestUtils.withNewTab(
+ {
+ gBrowser,
+ url:
+ "about:newtab?endpoint=https://example.com/browser/browser/components/newtab/test/browser/snippet_simple_test.json",
+ },
+ async browser => {
+ await waitForPreloaded(browser);
+
+ const complete = await SpecialPowers.spawn(browser, [], async () => {
+ const syncLink = "https://www.mozilla.org/en-US/firefox/accounts";
+ // Verify the simple_snippet renders in the footer and the container below
+ // searchbox is not rendered.
+ await ContentTaskUtils.waitForCondition(
+ () =>
+ content.document.querySelector(
+ "#footer-asrouter-container .SimpleSnippet"
+ ),
+ "Should find the snippet inside the footer container"
+ );
+ await ContentTaskUtils.waitForCondition(
+ () =>
+ content.document.querySelector(
+ "#footer-asrouter-container .SimpleSnippet .icon"
+ ),
+ "Should render an icon"
+ );
+ await ContentTaskUtils.waitForCondition(
+ () =>
+ content.document.querySelector(
+ `#footer-asrouter-container .SimpleSnippet a[href='${syncLink}']`
+ ),
+ "Should render an anchor with the correct href"
+ );
+
+ ok(
+ !content.document.querySelector(".below-search-snippet"),
+ "Should not find any snippets below search"
+ );
+
+ return true;
+ });
+
+ Assert.ok(complete, "Test complete.");
+ }
+ );
+});
+
+add_task(async function render_preview_snippet() {
+ ASRouter._validPreviewEndpoint = () => true;
+ await BrowserTestUtils.withNewTab(
+ {
+ gBrowser,
+ url:
+ "about:newtab?endpoint=https://example.com/browser/browser/components/newtab/test/browser/snippet.json",
+ },
+ async browser => {
+ let text = await SpecialPowers.spawn(browser, [], async () => {
+ await ContentTaskUtils.waitForCondition(
+ () => content.document.querySelector(".activity-stream"),
+ `Should render Activity Stream`
+ );
+ await ContentTaskUtils.waitForCondition(
+ () =>
+ content.document.querySelector(
+ "#footer-asrouter-container .SimpleSnippet"
+ ),
+ "Should find the snippet inside the footer container"
+ );
+
+ return content.document.querySelector(
+ "#footer-asrouter-container .SimpleSnippet"
+ ).innerText;
+ });
+
+ Assert.equal(
+ text,
+ "On January 30th Nightly will introduce dedicated profiles, making it simpler to run different installations of Firefox side by side. Learn what this means for you.",
+ "Snippet content match"
+ );
+ }
+ );
+});
+
+add_task(async function test_snippets_telemetry() {
+ await SpecialPowers.pushPrefEnv({
+ set: [
+ [
+ "browser.newtabpage.activity-stream.asrouter.providers.snippets",
+ `{"id":"snippets","enabled":true,"type":"remote","url":"https://example.com/browser/browser/components/newtab/test/browser/snippet.json","updateCycleInMs":0}`,
+ ],
+ ["browser.newtabpage.activity-stream.feeds.snippets", true],
+ ],
+ });
+ const sendPingStub = sinon.stub(
+ TelemetryFeed.prototype,
+ "sendStructuredIngestionEvent"
+ );
+ await BrowserTestUtils.withNewTab(
+ {
+ gBrowser,
+ // Work around any issues caching might introduce by navigating to
+ // about blank first
+ url: "about:blank",
+ },
+ async browser => {
+ await BrowserTestUtils.loadURI(browser, "about:home");
+ await BrowserTestUtils.browserLoaded(browser);
+ let text = await SpecialPowers.spawn(browser, [], async () => {
+ await ContentTaskUtils.waitForCondition(
+ () => content.document.querySelector(".activity-stream"),
+ `Should render Activity Stream`
+ );
+ await ContentTaskUtils.waitForCondition(
+ () =>
+ content.document.querySelector(
+ "#footer-asrouter-container .SimpleSnippet"
+ ),
+ "Should find the snippet inside the footer container"
+ );
+
+ return content.document.querySelector(
+ "#footer-asrouter-container .SimpleSnippet"
+ ).innerText;
+ });
+
+ Assert.equal(
+ text,
+ "On January 30th Nightly will introduce dedicated profiles, making it simpler to run different installations of Firefox side by side. Learn what this means for you.",
+ "Snippet content match"
+ );
+ }
+ );
+
+ Assert.ok(sendPingStub.callCount >= 1, "We registered some pings");
+ const snippetsPing = sendPingStub.args.find(args => args[2] === "snippets");
+ Assert.ok(snippetsPing, "Found the snippets ping");
+ Assert.equal(
+ snippetsPing[0].event,
+ "IMPRESSION",
+ "It's the correct ping type"
+ );
+
+ sendPingStub.restore();
+});
diff --git a/browser/components/newtab/test/browser/browser_asrouter_targeting.js b/browser/components/newtab/test/browser/browser_asrouter_targeting.js
new file mode 100644
index 0000000000..f8a8f35dc7
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_asrouter_targeting.js
@@ -0,0 +1,1137 @@
+const { ASRouterTargeting, QueryCache } = ChromeUtils.import(
+ "resource://activity-stream/lib/ASRouterTargeting.jsm"
+);
+const { AddonTestUtils } = ChromeUtils.import(
+ "resource://testing-common/AddonTestUtils.jsm"
+);
+const { CFRMessageProvider } = ChromeUtils.import(
+ "resource://activity-stream/lib/CFRMessageProvider.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "ProfileAge",
+ "resource://gre/modules/ProfileAge.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "AddonManager",
+ "resource://gre/modules/AddonManager.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "ShellService",
+ "resource:///modules/ShellService.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "NewTabUtils",
+ "resource://gre/modules/NewTabUtils.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "PlacesTestUtils",
+ "resource://testing-common/PlacesTestUtils.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "TelemetryEnvironment",
+ "resource://gre/modules/TelemetryEnvironment.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "AppConstants",
+ "resource://gre/modules/AppConstants.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "Region",
+ "resource://gre/modules/Region.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "HomePage",
+ "resource:///modules/HomePage.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "AboutNewTab",
+ "resource:///modules/AboutNewTab.jsm"
+);
+
+// ASRouterTargeting.findMatchingMessage
+add_task(async function find_matching_message() {
+ const messages = [
+ { id: "foo", targeting: "FOO" },
+ { id: "bar", targeting: "!FOO" },
+ ];
+ const context = { FOO: true };
+
+ const match = await ASRouterTargeting.findMatchingMessage({
+ messages,
+ context,
+ });
+
+ is(match, messages[0], "should match and return the correct message");
+});
+
+add_task(async function return_nothing_for_no_matching_message() {
+ const messages = [{ id: "bar", targeting: "!FOO" }];
+ const context = { FOO: true };
+
+ const match = await ASRouterTargeting.findMatchingMessage({
+ messages,
+ context,
+ });
+
+ ok(!match, "should return nothing since no matching message exists");
+});
+
+add_task(async function check_other_error_handling() {
+ let called = false;
+ function onError(...args) {
+ called = true;
+ }
+
+ const messages = [{ id: "foo", targeting: "foo" }];
+ const context = {
+ get foo() {
+ throw new Error("test error");
+ },
+ };
+ const match = await ASRouterTargeting.findMatchingMessage({
+ messages,
+ context,
+ onError,
+ });
+
+ ok(!match, "should return nothing since no valid matching message exists");
+
+ Assert.ok(called, "Attribute error caught");
+});
+
+// ASRouterTargeting.Environment
+add_task(async function check_locale() {
+ ok(
+ Services.locale.appLocaleAsBCP47,
+ "Services.locale.appLocaleAsBCP47 exists"
+ );
+ const message = {
+ id: "foo",
+ targeting: `locale == "${Services.locale.appLocaleAsBCP47}"`,
+ };
+ is(
+ await ASRouterTargeting.findMatchingMessage({ messages: [message] }),
+ message,
+ "should select correct item when filtering by locale"
+ );
+});
+add_task(async function check_localeLanguageCode() {
+ const currentLanguageCode = Services.locale.appLocaleAsBCP47.substr(0, 2);
+ is(
+ Services.locale.negotiateLanguages(
+ [currentLanguageCode],
+ [Services.locale.appLocaleAsBCP47]
+ )[0],
+ Services.locale.appLocaleAsBCP47,
+ "currentLanguageCode should resolve to the current locale (e.g en => en-US)"
+ );
+ const message = {
+ id: "foo",
+ targeting: `localeLanguageCode == "${currentLanguageCode}"`,
+ };
+ is(
+ await ASRouterTargeting.findMatchingMessage({ messages: [message] }),
+ message,
+ "should select correct item when filtering by localeLanguageCode"
+ );
+});
+
+add_task(async function checkProfileAgeCreated() {
+ let profileAccessor = await ProfileAge();
+ is(
+ await ASRouterTargeting.Environment.profileAgeCreated,
+ await profileAccessor.created,
+ "should return correct profile age creation date"
+ );
+
+ const message = {
+ id: "foo",
+ targeting: `profileAgeCreated > ${(await profileAccessor.created) - 100}`,
+ };
+ is(
+ await ASRouterTargeting.findMatchingMessage({ messages: [message] }),
+ message,
+ "should select correct item by profile age created"
+ );
+});
+
+add_task(async function checkProfileAgeReset() {
+ let profileAccessor = await ProfileAge();
+ is(
+ await ASRouterTargeting.Environment.profileAgeReset,
+ await profileAccessor.reset,
+ "should return correct profile age reset"
+ );
+
+ const message = {
+ id: "foo",
+ targeting: `profileAgeReset == ${await profileAccessor.reset}`,
+ };
+ is(
+ await ASRouterTargeting.findMatchingMessage({ messages: [message] }),
+ message,
+ "should select correct item by profile age reset"
+ );
+});
+
+add_task(async function checkCurrentDate() {
+ let message = {
+ id: "foo",
+ targeting: `currentDate < '${new Date(Date.now() + 5000)}'|date`,
+ };
+ is(
+ await ASRouterTargeting.findMatchingMessage({ messages: [message] }),
+ message,
+ "should select message based on currentDate < timestamp"
+ );
+
+ message = {
+ id: "foo",
+ targeting: `currentDate > '${new Date(Date.now() - 5000)}'|date`,
+ };
+ is(
+ await ASRouterTargeting.findMatchingMessage({ messages: [message] }),
+ message,
+ "should select message based on currentDate > timestamp"
+ );
+});
+
+add_task(async function check_usesFirefoxSync() {
+ await pushPrefs(["services.sync.username", "someone@foo.com"]);
+ is(
+ await ASRouterTargeting.Environment.usesFirefoxSync,
+ true,
+ "should return true if a fx account is set"
+ );
+
+ const message = { id: "foo", targeting: "usesFirefoxSync" };
+ is(
+ await ASRouterTargeting.findMatchingMessage({ messages: [message] }),
+ message,
+ "should select correct item by usesFirefoxSync"
+ );
+});
+
+add_task(async function check_isFxAEnabled() {
+ await pushPrefs(["identity.fxaccounts.enabled", false]);
+ is(
+ await ASRouterTargeting.Environment.isFxAEnabled,
+ false,
+ "should return false if fxa is disabled"
+ );
+
+ const message = { id: "foo", targeting: "isFxAEnabled" };
+ ok(
+ !(await ASRouterTargeting.findMatchingMessage({ messages: [message] })),
+ "should not select a message if fxa is disabled"
+ );
+});
+
+add_task(async function check_isFxAEnabled() {
+ await pushPrefs(["identity.fxaccounts.enabled", true]);
+ is(
+ await ASRouterTargeting.Environment.isFxAEnabled,
+ true,
+ "should return true if fxa is enabled"
+ );
+
+ const message = { id: "foo", targeting: "isFxAEnabled" };
+ is(
+ await ASRouterTargeting.findMatchingMessage({ messages: [message] }),
+ message,
+ "should select the correct message"
+ );
+});
+
+add_task(async function check_totalBookmarksCount() {
+ // Make sure we remove default bookmarks so they don't interfere
+ await clearHistoryAndBookmarks();
+ const message = { id: "foo", targeting: "totalBookmarksCount > 0" };
+
+ const results = await ASRouterTargeting.findMatchingMessage({
+ messages: [message],
+ });
+ ok(
+ !(results ? JSON.stringify(results) : results),
+ "Should not select any message because bookmarks count is not 0"
+ );
+
+ const bookmark = await PlacesUtils.bookmarks.insert({
+ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
+ title: "foo",
+ url: "https://mozilla1.com/nowNew",
+ });
+
+ QueryCache.queries.TotalBookmarksCount.expire();
+
+ is(
+ await ASRouterTargeting.findMatchingMessage({ messages: [message] }),
+ message,
+ "Should select correct item after bookmarks are added."
+ );
+
+ // Cleanup
+ await PlacesUtils.bookmarks.remove(bookmark.guid);
+});
+
+add_task(async function check_needsUpdate() {
+ QueryCache.queries.CheckBrowserNeedsUpdate.setUp(true);
+
+ const message = { id: "foo", targeting: "needsUpdate" };
+
+ is(
+ await ASRouterTargeting.findMatchingMessage({ messages: [message] }),
+ message,
+ "Should select message because update count > 0"
+ );
+
+ QueryCache.queries.CheckBrowserNeedsUpdate.setUp(false);
+
+ is(
+ await ASRouterTargeting.findMatchingMessage({ messages: [message] }),
+ null,
+ "Should not select message because update count == 0"
+ );
+});
+
+add_task(async function checksearchEngines() {
+ const result = await ASRouterTargeting.Environment.searchEngines;
+ const expectedInstalled = (await Services.search.getAppProvidedEngines())
+ .map(engine => engine.identifier)
+ .sort()
+ .join(",");
+ ok(
+ result.installed.length,
+ "searchEngines.installed should be a non-empty array"
+ );
+ is(
+ result.installed.sort().join(","),
+ expectedInstalled,
+ "searchEngines.installed should be an array of visible search engines"
+ );
+ ok(
+ result.current && typeof result.current === "string",
+ "searchEngines.current should be a truthy string"
+ );
+ is(
+ result.current,
+ (await Services.search.getDefault()).identifier,
+ "searchEngines.current should be the current engine name"
+ );
+
+ const message = {
+ id: "foo",
+ targeting: `searchEngines[.current == ${
+ (await Services.search.getDefault()).identifier
+ }]`,
+ };
+ is(
+ await ASRouterTargeting.findMatchingMessage({ messages: [message] }),
+ message,
+ "should select correct item by searchEngines.current"
+ );
+
+ const message2 = {
+ id: "foo",
+ targeting: `searchEngines[${
+ (await Services.search.getAppProvidedEngines())[0].identifier
+ } in .installed]`,
+ };
+ is(
+ await ASRouterTargeting.findMatchingMessage({ messages: [message2] }),
+ message2,
+ "should select correct item by searchEngines.installed"
+ );
+});
+
+add_task(async function checkisDefaultBrowser() {
+ const expected = ShellService.isDefaultBrowser();
+ const result = ASRouterTargeting.Environment.isDefaultBrowser;
+ is(typeof result, "boolean", "isDefaultBrowser should be a boolean value");
+ is(
+ result,
+ expected,
+ "isDefaultBrowser should be equal to ShellService.isDefaultBrowser()"
+ );
+ const message = {
+ id: "foo",
+ targeting: `isDefaultBrowser == ${expected.toString()}`,
+ };
+ is(
+ await ASRouterTargeting.findMatchingMessage({ messages: [message] }),
+ message,
+ "should select correct item by isDefaultBrowser"
+ );
+});
+
+add_task(async function checkdevToolsOpenedCount() {
+ await pushPrefs(["devtools.selfxss.count", 5]);
+ is(
+ ASRouterTargeting.Environment.devToolsOpenedCount,
+ 5,
+ "devToolsOpenedCount should be equal to devtools.selfxss.count pref value"
+ );
+ const message = { id: "foo", targeting: "devToolsOpenedCount >= 5" };
+ is(
+ await ASRouterTargeting.findMatchingMessage({ messages: [message] }),
+ message,
+ "should select correct item by devToolsOpenedCount"
+ );
+});
+
+add_task(async function check_platformName() {
+ const message = {
+ id: "foo",
+ targeting: `platformName == "${AppConstants.platform}"`,
+ };
+ is(
+ await ASRouterTargeting.findMatchingMessage({ messages: [message] }),
+ message,
+ "should select correct item by platformName"
+ );
+});
+
+AddonTestUtils.initMochitest(this);
+
+add_task(async function checkAddonsInfo() {
+ const FAKE_ID = "testaddon@tests.mozilla.org";
+ const FAKE_NAME = "Test Addon";
+ const FAKE_VERSION = "0.5.7";
+
+ const xpi = AddonTestUtils.createTempWebExtensionFile({
+ manifest: {
+ applications: { gecko: { id: FAKE_ID } },
+ name: FAKE_NAME,
+ version: FAKE_VERSION,
+ },
+ });
+
+ await Promise.all([
+ AddonTestUtils.promiseWebExtensionStartup(FAKE_ID),
+ AddonManager.installTemporaryAddon(xpi),
+ ]);
+
+ const { addons } = await AddonManager.getActiveAddons([
+ "extension",
+ "service",
+ ]);
+
+ const { addons: asRouterAddons, isFullData } = await ASRouterTargeting
+ .Environment.addonsInfo;
+
+ ok(
+ addons.every(({ id }) => asRouterAddons[id]),
+ "should contain every addon"
+ );
+
+ ok(
+ Object.getOwnPropertyNames(asRouterAddons).every(id =>
+ addons.some(addon => addon.id === id)
+ ),
+ "should contain no incorrect addons"
+ );
+
+ const testAddon = asRouterAddons[FAKE_ID];
+
+ ok(
+ Object.prototype.hasOwnProperty.call(testAddon, "version") &&
+ testAddon.version === FAKE_VERSION,
+ "should correctly provide `version` property"
+ );
+
+ ok(
+ Object.prototype.hasOwnProperty.call(testAddon, "type") &&
+ testAddon.type === "extension",
+ "should correctly provide `type` property"
+ );
+
+ ok(
+ Object.prototype.hasOwnProperty.call(testAddon, "isSystem") &&
+ testAddon.isSystem === false,
+ "should correctly provide `isSystem` property"
+ );
+
+ ok(
+ Object.prototype.hasOwnProperty.call(testAddon, "isWebExtension") &&
+ testAddon.isWebExtension === true,
+ "should correctly provide `isWebExtension` property"
+ );
+
+ // As we installed our test addon the addons database must be initialised, so
+ // (in this test environment) we expect to receive "full" data
+
+ ok(isFullData, "should receive full data");
+
+ ok(
+ Object.prototype.hasOwnProperty.call(testAddon, "name") &&
+ testAddon.name === FAKE_NAME,
+ "should correctly provide `name` property from full data"
+ );
+
+ ok(
+ Object.prototype.hasOwnProperty.call(testAddon, "userDisabled") &&
+ testAddon.userDisabled === false,
+ "should correctly provide `userDisabled` property from full data"
+ );
+
+ ok(
+ Object.prototype.hasOwnProperty.call(testAddon, "installDate") &&
+ Math.abs(Date.now() - new Date(testAddon.installDate)) < 60 * 1000,
+ "should correctly provide `installDate` property from full data"
+ );
+});
+
+add_task(async function checkFrecentSites() {
+ const now = Date.now();
+ const timeDaysAgo = numDays => now - numDays * 24 * 60 * 60 * 1000;
+
+ const visits = [];
+ for (const [uri, count, visitDate] of [
+ ["https://mozilla1.com/", 10, timeDaysAgo(0)], // frecency 1000
+ ["https://mozilla2.com/", 5, timeDaysAgo(1)], // frecency 500
+ ["https://mozilla3.com/", 1, timeDaysAgo(2)], // frecency 100
+ ]) {
+ [...Array(count).keys()].forEach(() =>
+ visits.push({
+ uri,
+ visitDate: visitDate * 1000, // Places expects microseconds
+ })
+ );
+ }
+
+ await PlacesTestUtils.addVisits(visits);
+
+ let message = {
+ id: "foo",
+ targeting: "'mozilla3.com' in topFrecentSites|mapToProperty('host')",
+ };
+ is(
+ await ASRouterTargeting.findMatchingMessage({ messages: [message] }),
+ message,
+ "should select correct item by host in topFrecentSites"
+ );
+
+ message = {
+ id: "foo",
+ targeting: "'non-existent.com' in topFrecentSites|mapToProperty('host')",
+ };
+ ok(
+ !(await ASRouterTargeting.findMatchingMessage({ messages: [message] })),
+ "should not select incorrect item by host in topFrecentSites"
+ );
+
+ message = {
+ id: "foo",
+ targeting:
+ "'mozilla2.com' in topFrecentSites[.frecency >= 400]|mapToProperty('host')",
+ };
+ is(
+ await ASRouterTargeting.findMatchingMessage({ messages: [message] }),
+ message,
+ "should select correct item when filtering by frecency"
+ );
+
+ message = {
+ id: "foo",
+ targeting:
+ "'mozilla2.com' in topFrecentSites[.frecency >= 600]|mapToProperty('host')",
+ };
+ ok(
+ !(await ASRouterTargeting.findMatchingMessage({ messages: [message] })),
+ "should not select incorrect item when filtering by frecency"
+ );
+
+ message = {
+ id: "foo",
+ targeting: `'mozilla2.com' in topFrecentSites[.lastVisitDate >= ${timeDaysAgo(
+ 1
+ ) - 1}]|mapToProperty('host')`,
+ };
+ is(
+ await ASRouterTargeting.findMatchingMessage({ messages: [message] }),
+ message,
+ "should select correct item when filtering by lastVisitDate"
+ );
+
+ message = {
+ id: "foo",
+ targeting: `'mozilla2.com' in topFrecentSites[.lastVisitDate >= ${timeDaysAgo(
+ 0
+ ) - 1}]|mapToProperty('host')`,
+ };
+ ok(
+ !(await ASRouterTargeting.findMatchingMessage({ messages: [message] })),
+ "should not select incorrect item when filtering by lastVisitDate"
+ );
+
+ message = {
+ id: "foo",
+ targeting: `(topFrecentSites[.frecency >= 900 && .lastVisitDate >= ${timeDaysAgo(
+ 1
+ ) -
+ 1}]|mapToProperty('host') intersect ['mozilla3.com', 'mozilla2.com', 'mozilla1.com'])|length > 0`,
+ };
+ is(
+ await ASRouterTargeting.findMatchingMessage({ messages: [message] }),
+ message,
+ "should select correct item when filtering by frecency and lastVisitDate with multiple candidate domains"
+ );
+
+ // Cleanup
+ await clearHistoryAndBookmarks();
+});
+
+add_task(async function check_pinned_sites() {
+ // Fresh profiles come with an empty set of pinned websites (pref doesn't
+ // exist). Search shortcut topsites make this test more complicated because
+ // the feature pins a new website on startup. Behaviour can vary when running
+ // with --verify so it's more predictable to clear pins entirely.
+ Services.prefs.clearUserPref("browser.newtabpage.pinned");
+ NewTabUtils.pinnedLinks.resetCache();
+ const originalPin = JSON.stringify(NewTabUtils.pinnedLinks.links);
+ const sitesToPin = [
+ { url: "https://foo.com" },
+ { url: "https://bloo.com" },
+ { url: "https://floogle.com", searchTopSite: true },
+ ];
+ sitesToPin.forEach(site =>
+ NewTabUtils.pinnedLinks.pin(site, NewTabUtils.pinnedLinks.links.length)
+ );
+
+ // Unpinning adds null to the list of pinned sites, which we should test that we handle gracefully for our targeting
+ NewTabUtils.pinnedLinks.unpin(sitesToPin[1]);
+ ok(
+ NewTabUtils.pinnedLinks.links.includes(null),
+ "should have set an item in pinned links to null via unpinning for testing"
+ );
+
+ let message;
+
+ message = {
+ id: "foo",
+ targeting: "'https://foo.com' in pinnedSites|mapToProperty('url')",
+ };
+ is(
+ await ASRouterTargeting.findMatchingMessage({ messages: [message] }),
+ message,
+ "should select correct item by url in pinnedSites"
+ );
+
+ message = {
+ id: "foo",
+ targeting: "'foo.com' in pinnedSites|mapToProperty('host')",
+ };
+ is(
+ await ASRouterTargeting.findMatchingMessage({ messages: [message] }),
+ message,
+ "should select correct item by host in pinnedSites"
+ );
+
+ message = {
+ id: "foo",
+ targeting:
+ "'floogle.com' in pinnedSites[.searchTopSite == true]|mapToProperty('host')",
+ };
+ is(
+ await ASRouterTargeting.findMatchingMessage({ messages: [message] }),
+ message,
+ "should select correct item by host and searchTopSite in pinnedSites"
+ );
+
+ // Cleanup
+ sitesToPin.forEach(site => NewTabUtils.pinnedLinks.unpin(site));
+
+ await clearHistoryAndBookmarks();
+ Services.prefs.clearUserPref("browser.newtabpage.pinned");
+ NewTabUtils.pinnedLinks.resetCache();
+ is(
+ JSON.stringify(NewTabUtils.pinnedLinks.links),
+ originalPin,
+ "should restore pinned sites to its original state"
+ );
+});
+
+add_task(async function check_firefox_version() {
+ const message = { id: "foo", targeting: "firefoxVersion > 0" };
+ is(
+ await ASRouterTargeting.findMatchingMessage({ messages: [message] }),
+ message,
+ "should select correct item when filtering by firefox version"
+ );
+});
+
+add_task(async function check_region() {
+ Region._setHomeRegion("DE", false);
+ const message = { id: "foo", targeting: "region in ['DE']" };
+ is(
+ await ASRouterTargeting.findMatchingMessage({ messages: [message] }),
+ message,
+ "should select correct item when filtering by firefox geo"
+ );
+});
+
+add_task(async function check_browserSettings() {
+ is(
+ await JSON.stringify(ASRouterTargeting.Environment.browserSettings.update),
+ JSON.stringify(TelemetryEnvironment.currentEnvironment.settings.update),
+ "should return correct update info"
+ );
+});
+
+add_task(async function check_sync() {
+ is(
+ await ASRouterTargeting.Environment.sync.desktopDevices,
+ Services.prefs.getIntPref("services.sync.clients.devices.desktop", 0),
+ "should return correct desktopDevices info"
+ );
+ is(
+ await ASRouterTargeting.Environment.sync.mobileDevices,
+ Services.prefs.getIntPref("services.sync.clients.devices.mobile", 0),
+ "should return correct mobileDevices info"
+ );
+ is(
+ await ASRouterTargeting.Environment.sync.totalDevices,
+ Services.prefs.getIntPref("services.sync.numClients", 0),
+ "should return correct mobileDevices info"
+ );
+});
+
+add_task(async function check_provider_cohorts() {
+ await pushPrefs([
+ "browser.newtabpage.activity-stream.asrouter.providers.onboarding",
+ JSON.stringify({
+ id: "onboarding",
+ messages: [],
+ enabled: true,
+ cohort: "foo",
+ }),
+ ]);
+ await pushPrefs([
+ "browser.newtabpage.activity-stream.asrouter.providers.cfr",
+ JSON.stringify({ id: "cfr", enabled: true, cohort: "bar" }),
+ ]);
+ is(
+ await ASRouterTargeting.Environment.providerCohorts.onboarding,
+ "foo",
+ "should have cohort foo for onboarding"
+ );
+ is(
+ await ASRouterTargeting.Environment.providerCohorts.cfr,
+ "bar",
+ "should have cohort bar for cfr"
+ );
+});
+
+add_task(async function check_xpinstall_enabled() {
+ // should default to true if pref doesn't exist
+ is(await ASRouterTargeting.Environment.xpinstallEnabled, true);
+ // flip to false, check targeting reflects that
+ await pushPrefs(["xpinstall.enabled", false]);
+ is(await ASRouterTargeting.Environment.xpinstallEnabled, false);
+ // flip to true, check targeting reflects that
+ await pushPrefs(["xpinstall.enabled", true]);
+ is(await ASRouterTargeting.Environment.xpinstallEnabled, true);
+});
+
+add_task(async function check_pinned_tabs() {
+ await BrowserTestUtils.withNewTab(
+ { gBrowser, url: "about:blank" },
+ async browser => {
+ is(
+ await ASRouterTargeting.Environment.hasPinnedTabs,
+ false,
+ "No pin tabs yet"
+ );
+
+ let tab = gBrowser.getTabForBrowser(browser);
+ gBrowser.pinTab(tab);
+
+ is(
+ await ASRouterTargeting.Environment.hasPinnedTabs,
+ true,
+ "Should detect pinned tab"
+ );
+
+ gBrowser.unpinTab(tab);
+ }
+ );
+});
+
+add_task(async function check_hasAccessedFxAPanel() {
+ is(
+ await ASRouterTargeting.Environment.hasAccessedFxAPanel,
+ false,
+ "Not accessed yet"
+ );
+
+ await pushPrefs(["identity.fxaccounts.toolbar.accessed", true]);
+
+ is(
+ await ASRouterTargeting.Environment.hasAccessedFxAPanel,
+ true,
+ "Should detect panel access"
+ );
+});
+
+add_task(async function checkCFRFeaturesUserPref() {
+ await pushPrefs([
+ "browser.newtabpage.activity-stream.asrouter.userprefs.cfr.features",
+ false,
+ ]);
+ is(
+ ASRouterTargeting.Environment.userPrefs.cfrFeatures,
+ false,
+ "cfrFeature should be false according to pref"
+ );
+ const message = { id: "foo", targeting: "userPrefs.cfrFeatures == false" };
+ is(
+ await ASRouterTargeting.findMatchingMessage({ messages: [message] }),
+ message,
+ "should select correct item by cfrFeature"
+ );
+});
+
+add_task(async function checkCFRAddonsUserPref() {
+ await pushPrefs([
+ "browser.newtabpage.activity-stream.asrouter.userprefs.cfr.addons",
+ false,
+ ]);
+ is(
+ ASRouterTargeting.Environment.userPrefs.cfrAddons,
+ false,
+ "cfrFeature should be false according to pref"
+ );
+ const message = { id: "foo", targeting: "userPrefs.cfrAddons == false" };
+ is(
+ await ASRouterTargeting.findMatchingMessage({ messages: [message] }),
+ message,
+ "should select correct item by cfrAddons"
+ );
+});
+
+add_task(async function check_blockedCountByType() {
+ const message = {
+ id: "foo",
+ targeting:
+ "blockedCountByType.cryptominerCount == 0 && blockedCountByType.socialCount == 0",
+ };
+
+ is(
+ await ASRouterTargeting.findMatchingMessage({ messages: [message] }),
+ message,
+ "should select correct item"
+ );
+});
+
+add_task(async function checkCFRPinnedTabsTargetting() {
+ const now = Date.now();
+ const timeMinutesAgo = numMinutes => now - numMinutes * 60 * 1000;
+ const messages = await CFRMessageProvider.getMessages();
+ const trigger = {
+ id: "frequentVisits",
+ context: {
+ recentVisits: [
+ { timestamp: timeMinutesAgo(61) },
+ { timestamp: timeMinutesAgo(30) },
+ { timestamp: timeMinutesAgo(1) },
+ ],
+ },
+ param: { host: "github.com", url: "https://google.com" },
+ };
+
+ ok(
+ !(await ASRouterTargeting.findMatchingMessage({ messages, trigger })),
+ "should not select PIN_TAB mesage with only 2 visits in past hour"
+ );
+
+ trigger.context.recentVisits.push({ timestamp: timeMinutesAgo(59) });
+ is(
+ (await ASRouterTargeting.findMatchingMessage({ messages, trigger })).id,
+ "PIN_TAB",
+ "should select PIN_TAB mesage"
+ );
+
+ await BrowserTestUtils.withNewTab(
+ { gBrowser, url: "about:blank" },
+ async browser => {
+ let tab = gBrowser.getTabForBrowser(browser);
+ gBrowser.pinTab(tab);
+ ok(
+ !(await ASRouterTargeting.findMatchingMessage({ messages, trigger })),
+ "should not select PIN_TAB mesage if there is a pinned tab already"
+ );
+ gBrowser.unpinTab(tab);
+ }
+ );
+
+ trigger.param = { host: "foo.bar", url: "https://foo.bar" };
+ ok(
+ !(await ASRouterTargeting.findMatchingMessage({ messages, trigger })),
+ "should not select PIN_TAB mesage with a trigger param/host not in our hostlist"
+ );
+});
+
+add_task(async function checkPatternMatches() {
+ const now = Date.now();
+ const timeMinutesAgo = numMinutes => now - numMinutes * 60 * 1000;
+ const messages = [
+ {
+ id: "message_with_pattern",
+ targeting: "true",
+ trigger: { id: "frequentVisits", patterns: ["*://*.github.com/"] },
+ },
+ ];
+ const trigger = {
+ id: "frequentVisits",
+ context: {
+ recentVisits: [
+ { timestamp: timeMinutesAgo(33) },
+ { timestamp: timeMinutesAgo(17) },
+ { timestamp: timeMinutesAgo(1) },
+ ],
+ },
+ param: { host: "github.com", url: "https://gist.github.com" },
+ };
+
+ is(
+ (await ASRouterTargeting.findMatchingMessage({ messages, trigger })).id,
+ "message_with_pattern",
+ "should select PIN_TAB mesage"
+ );
+});
+
+add_task(async function checkPatternsValid() {
+ const messages = (await CFRMessageProvider.getMessages()).filter(
+ m => m.trigger?.patterns
+ );
+
+ for (const message of messages) {
+ Assert.ok(new MatchPatternSet(message.trigger.patterns));
+ }
+});
+
+add_task(async function check_isChinaRepack() {
+ const prefDefaultBranch = Services.prefs.getDefaultBranch("distribution.");
+ const messages = [
+ { id: "msg_for_china_repack", targeting: "isChinaRepack == true" },
+ { id: "msg_for_everyone_else", targeting: "isChinaRepack == false" },
+ ];
+
+ is(
+ await ASRouterTargeting.Environment.isChinaRepack,
+ false,
+ "Fx w/o partner repack info set is not China repack"
+ );
+ is(
+ (await ASRouterTargeting.findMatchingMessage({ messages })).id,
+ "msg_for_everyone_else",
+ "should select the message for non China repack users"
+ );
+
+ prefDefaultBranch.setCharPref("id", "MozillaOnline");
+
+ is(
+ await ASRouterTargeting.Environment.isChinaRepack,
+ true,
+ "Fx with `distribution.id` set to `MozillaOnline` is China repack"
+ );
+ is(
+ (await ASRouterTargeting.findMatchingMessage({ messages })).id,
+ "msg_for_china_repack",
+ "should select the message for China repack users"
+ );
+
+ prefDefaultBranch.setCharPref("id", "Example");
+
+ is(
+ await ASRouterTargeting.Environment.isChinaRepack,
+ false,
+ "Fx with `distribution.id` set to other string is not China repack"
+ );
+ is(
+ (await ASRouterTargeting.findMatchingMessage({ messages })).id,
+ "msg_for_everyone_else",
+ "should select the message for non China repack users"
+ );
+
+ prefDefaultBranch.deleteBranch("");
+});
+
+add_task(async function check_userId() {
+ await SpecialPowers.pushPrefEnv({
+ set: [["app.normandy.user_id", "foo123"]],
+ });
+ is(
+ await ASRouterTargeting.Environment.userId,
+ "foo123",
+ "should read userID from normandy user id pref"
+ );
+});
+
+add_task(async function check_profileRestartCount() {
+ ok(
+ !isNaN(ASRouterTargeting.Environment.profileRestartCount),
+ "it should return a number"
+ );
+});
+
+add_task(async function check_homePageSettings_default() {
+ let settings = ASRouterTargeting.Environment.homePageSettings;
+
+ ok(settings.isDefault, "should set as default");
+ ok(!settings.isLocked, "should not set as locked");
+ ok(!settings.isWebExt, "should not be web extension");
+ ok(!settings.isCustomUrl, "should not be custom URL");
+ is(settings.urls.length, 1, "should be an 1-entry array");
+ is(settings.urls[0].url, "about:home", "should be about:home");
+ is(settings.urls[0].host, "", "should be an empty string");
+});
+
+add_task(async function check_homePageSettings_locked() {
+ const PREF = "browser.startup.homepage";
+ Services.prefs.lockPref(PREF);
+ let settings = ASRouterTargeting.Environment.homePageSettings;
+
+ ok(settings.isDefault, "should set as default");
+ ok(settings.isLocked, "should set as locked");
+ ok(!settings.isWebExt, "should not be web extension");
+ ok(!settings.isCustomUrl, "should not be custom URL");
+ is(settings.urls.length, 1, "should be an 1-entry array");
+ is(settings.urls[0].url, "about:home", "should be about:home");
+ is(settings.urls[0].host, "", "should be an empty string");
+ Services.prefs.unlockPref(PREF);
+});
+
+add_task(async function check_homePageSettings_customURL() {
+ await HomePage.set("https://www.google.com");
+ let settings = ASRouterTargeting.Environment.homePageSettings;
+
+ ok(!settings.isDefault, "should not be the default");
+ ok(!settings.isLocked, "should set as locked");
+ ok(!settings.isWebExt, "should not be web extension");
+ ok(settings.isCustomUrl, "should be custom URL");
+ is(settings.urls.length, 1, "should be an 1-entry array");
+ is(settings.urls[0].url, "https://www.google.com", "should be a custom URL");
+ is(
+ settings.urls[0].host,
+ "google.com",
+ "should be the host name without 'www.'"
+ );
+
+ HomePage.reset();
+});
+
+add_task(async function check_homePageSettings_customURL_multiple() {
+ await HomePage.set("https://www.google.com|https://www.youtube.com");
+ let settings = ASRouterTargeting.Environment.homePageSettings;
+
+ ok(!settings.isDefault, "should not be the default");
+ ok(!settings.isLocked, "should not set as locked");
+ ok(!settings.isWebExt, "should not be web extension");
+ ok(settings.isCustomUrl, "should be custom URL");
+ is(settings.urls.length, 2, "should be a 2-entry array");
+ is(settings.urls[0].url, "https://www.google.com", "should be a custom URL");
+ is(
+ settings.urls[0].host,
+ "google.com",
+ "should be the host name without 'www.'"
+ );
+ is(settings.urls[1].url, "https://www.youtube.com", "should be a custom URL");
+ is(
+ settings.urls[1].host,
+ "youtube.com",
+ "should be the host name without 'www.'"
+ );
+
+ HomePage.reset();
+});
+
+add_task(async function check_homePageSettings_webExtension() {
+ const extURI =
+ "moz-extension://0d735548-ba3c-aa43-a0e4-7089584fbb53/homepage.html";
+ await HomePage.set(extURI);
+ let settings = ASRouterTargeting.Environment.homePageSettings;
+
+ ok(!settings.isDefault, "should not be the default");
+ ok(!settings.isLocked, "should not set as locked");
+ ok(settings.isWebExt, "should be a web extension");
+ ok(!settings.isCustomUrl, "should be custom URL");
+ is(settings.urls.length, 1, "should be an 1-entry array");
+ is(settings.urls[0].url, extURI, "should be a webExtension URI");
+ is(settings.urls[0].host, "", "should be an empty string");
+
+ HomePage.reset();
+});
+
+add_task(async function check_newtabSettings_default() {
+ let settings = ASRouterTargeting.Environment.newtabSettings;
+
+ ok(settings.isDefault, "should set as default");
+ ok(!settings.isWebExt, "should not be web extension");
+ ok(!settings.isCustomUrl, "should not be custom URL");
+ is(settings.url, "about:newtab", "should be about:home");
+ is(settings.host, "", "should be an empty string");
+});
+
+add_task(async function check_newTabSettings_customURL() {
+ AboutNewTab.newTabURL = "https://www.google.com";
+ let settings = ASRouterTargeting.Environment.newtabSettings;
+
+ ok(!settings.isDefault, "should not be the default");
+ ok(!settings.isWebExt, "should not be web extension");
+ ok(settings.isCustomUrl, "should be custom URL");
+ is(settings.url, "https://www.google.com", "should be a custom URL");
+ is(settings.host, "google.com", "should be the host name without 'www.'");
+
+ AboutNewTab.resetNewTabURL();
+});
+
+add_task(async function check_newTabSettings_webExtension() {
+ const extURI =
+ "moz-extension://0d735548-ba3c-aa43-a0e4-7089584fbb53/homepage.html";
+ AboutNewTab.newTabURL = extURI;
+ let settings = ASRouterTargeting.Environment.newtabSettings;
+
+ ok(!settings.isDefault, "should not be the default");
+ ok(settings.isWebExt, "should not be web extension");
+ ok(!settings.isCustomUrl, "should be custom URL");
+ is(settings.url, extURI, "should be the web extension URI");
+ is(settings.host, "", "should be an empty string");
+
+ AboutNewTab.resetNewTabURL();
+});
+
+add_task(async function check_openUrlTrigger_context() {
+ const message = {
+ ...(await CFRMessageProvider.getMessages()).find(
+ m => m.id === "YOUTUBE_ENHANCE_3"
+ ),
+ targeting: "visitsCount == 3",
+ };
+ const trigger = {
+ id: "openURL",
+ context: { visitsCount: 3 },
+ param: { host: "youtube.com", url: "https://www.youtube.com" },
+ };
+
+ is(
+ (
+ await ASRouterTargeting.findMatchingMessage({
+ messages: [message],
+ trigger,
+ })
+ ).id,
+ message.id,
+ `should select ${message.id} mesage`
+ );
+});
diff --git a/browser/components/newtab/test/browser/browser_asrouter_toolbarbadge.js b/browser/components/newtab/test/browser/browser_asrouter_toolbarbadge.js
new file mode 100644
index 0000000000..98a36f5e00
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_asrouter_toolbarbadge.js
@@ -0,0 +1,143 @@
+const { OnboardingMessageProvider } = ChromeUtils.import(
+ "resource://activity-stream/lib/OnboardingMessageProvider.jsm"
+);
+const { ToolbarBadgeHub } = ChromeUtils.import(
+ "resource://activity-stream/lib/ToolbarBadgeHub.jsm"
+);
+
+add_task(async function test_setup() {
+ // Cleanup pref value because we click the fxa accounts button.
+ // This is not required during tests because we "force show" the message
+ // by sending it directly to the Hub bypassing targeting.
+ registerCleanupFunction(() => {
+ Services.prefs.clearUserPref("identity.fxaccounts.toolbar.accessed");
+ });
+});
+
+add_task(async function test_fxa_badge_shown_nodelay() {
+ const [msg] = (await OnboardingMessageProvider.getMessages()).filter(
+ ({ id }) => id === "FXA_ACCOUNTS_BADGE"
+ );
+
+ Assert.ok(msg, "FxA test message exists");
+
+ // Ensure we badge immediately
+ msg.content.delay = undefined;
+
+ let browserWindow = Services.wm.getMostRecentWindow("navigator:browser");
+ // Click the button and clear the badge that occurs normally at startup
+ let fxaButton = browserWindow.document.getElementById(msg.content.target);
+ fxaButton.click();
+
+ await BrowserTestUtils.waitForCondition(
+ () =>
+ !browserWindow.document
+ .getElementById(msg.content.target)
+ .querySelector(".toolbarbutton-badge")
+ .classList.contains("feature-callout"),
+ "Initially element is not badged"
+ );
+
+ ToolbarBadgeHub.registerBadgeNotificationListener(msg);
+
+ await BrowserTestUtils.waitForCondition(
+ () =>
+ browserWindow.document
+ .getElementById(msg.content.target)
+ .querySelector(".toolbarbutton-badge")
+ .classList.contains("feature-callout"),
+ "Wait for element to be badged"
+ );
+
+ let newWin = await BrowserTestUtils.openNewBrowserWindow();
+ browserWindow = Services.wm.getMostRecentWindow("navigator:browser");
+
+ await BrowserTestUtils.waitForCondition(
+ () =>
+ browserWindow.document
+ .getElementById(msg.content.target)
+ .querySelector(".toolbarbutton-badge")
+ .classList.contains("feature-callout"),
+ "Wait for element to be badged"
+ );
+
+ await BrowserTestUtils.closeWindow(newWin);
+ browserWindow = Services.wm.getMostRecentWindow("navigator:browser");
+
+ // Click the button and clear the badge
+ fxaButton = document.getElementById(msg.content.target);
+ fxaButton.click();
+
+ await BrowserTestUtils.waitForCondition(
+ () =>
+ !browserWindow.document
+ .getElementById(msg.content.target)
+ .querySelector(".toolbarbutton-badge")
+ .classList.contains("feature-callout"),
+ "Button should no longer be badged"
+ );
+});
+
+add_task(async function test_fxa_badge_shown_withdelay() {
+ const [msg] = (await OnboardingMessageProvider.getMessages()).filter(
+ ({ id }) => id === "FXA_ACCOUNTS_BADGE"
+ );
+
+ Assert.ok(msg, "FxA test message exists");
+
+ // Enough to trigger the setTimeout badging
+ msg.content.delay = 1;
+
+ let browserWindow = Services.wm.getMostRecentWindow("navigator:browser");
+ // Click the button and clear the badge that occurs normally at startup
+ let fxaButton = browserWindow.document.getElementById(msg.content.target);
+ fxaButton.click();
+
+ await BrowserTestUtils.waitForCondition(
+ () =>
+ !browserWindow.document
+ .getElementById(msg.content.target)
+ .querySelector(".toolbarbutton-badge")
+ .classList.contains("feature-callout"),
+ "Initially element is not badged"
+ );
+
+ ToolbarBadgeHub.registerBadgeNotificationListener(msg);
+
+ await BrowserTestUtils.waitForCondition(
+ () =>
+ browserWindow.document
+ .getElementById(msg.content.target)
+ .querySelector(".toolbarbutton-badge")
+ .classList.contains("feature-callout"),
+ "Wait for element to be badged"
+ );
+
+ let newWin = await BrowserTestUtils.openNewBrowserWindow();
+ browserWindow = Services.wm.getMostRecentWindow("navigator:browser");
+
+ await BrowserTestUtils.waitForCondition(
+ () =>
+ browserWindow.document
+ .getElementById(msg.content.target)
+ .querySelector(".toolbarbutton-badge")
+ .classList.contains("feature-callout"),
+ "Wait for element to be badged"
+ );
+
+ await BrowserTestUtils.closeWindow(newWin);
+ browserWindow = Services.wm.getMostRecentWindow("navigator:browser");
+
+ // Click the button and clear the badge
+ fxaButton = document.getElementById(msg.content.target);
+ fxaButton.click();
+
+ await BrowserTestUtils.waitForCondition(
+ () =>
+ !browserWindow.document
+ .getElementById(msg.content.target)
+ .querySelector(".toolbarbutton-badge")
+ .classList.contains("feature-callout"),
+ "Button should no longer be badged"
+ );
+});
diff --git a/browser/components/newtab/test/browser/browser_asrouter_whatsnewpanel.js b/browser/components/newtab/test/browser/browser_asrouter_whatsnewpanel.js
new file mode 100644
index 0000000000..1f77206e00
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_asrouter_whatsnewpanel.js
@@ -0,0 +1,99 @@
+const { PanelTestProvider } = ChromeUtils.import(
+ "resource://activity-stream/lib/PanelTestProvider.jsm"
+);
+const { ToolbarPanelHub } = ChromeUtils.import(
+ "resource://activity-stream/lib/ToolbarPanelHub.jsm"
+);
+const { RemoteSettings } = ChromeUtils.import(
+ "resource://services-settings/remote-settings.js"
+);
+const { ASRouter } = ChromeUtils.import(
+ "resource://activity-stream/lib/ASRouter.jsm"
+);
+
+add_task(async function test_with_rs_messages() {
+ // Force the WNPanel provider cache to 0 by modifying updateCycleInMs
+ await SpecialPowers.pushPrefEnv({
+ set: [
+ [
+ "browser.newtabpage.activity-stream.asrouter.providers.whats-new-panel",
+ `{"id":"whats-new-panel","enabled":true,"type":"remote-settings","bucket":"whats-new-panel","updateCycleInMs":0}`,
+ ],
+ ],
+ });
+ const msgs = (await PanelTestProvider.getMessages()).filter(
+ ({ template }) => template === "whatsnew_panel_message"
+ );
+ const initialMessageCount = ASRouter.state.messages.length;
+ const client = RemoteSettings("whats-new-panel");
+ await client.db.importChanges(
+ {},
+ 42,
+ msgs.map(record => ({
+ // Modify targeting to ensure the messages always show up
+ ...record,
+ targeting: "true",
+ })),
+ { clear: true }
+ );
+
+ UITour.showMenu(window, "appMenu");
+ await BrowserTestUtils.waitForEvent(window.PanelUI.mainView, "ViewShown");
+ const mainView = document.getElementById("appMenu-mainView");
+
+ const whatsNewBtn = document.getElementById("appMenu-whatsnew-button");
+ Assert.equal(whatsNewBtn.hidden, true, "What's New btn doesn't exist");
+
+ // Reload the provider
+ await ASRouter._updateMessageProviders();
+ // Wait to load the WNPanel messages
+ await BrowserTestUtils.waitForCondition(async () => {
+ await ASRouter.loadMessagesFromAllProviders();
+ return ASRouter.state.messages.length > initialMessageCount;
+ }, "Messages did not load");
+ await ToolbarPanelHub.enableAppmenuButton();
+
+ Assert.equal(mainView.hidden, false, "Panel is visible");
+ await BrowserTestUtils.waitForCondition(
+ () => !whatsNewBtn.hidden,
+ "What's new menu entry did not become visible"
+ );
+ Assert.equal(whatsNewBtn.hidden, false, "What's New btn is visible");
+
+ // Show the What's New Messages
+ whatsNewBtn.click();
+
+ await BrowserTestUtils.waitForCondition(
+ () => document.getElementById("PanelUI-whatsNew-message-container"),
+ "The message container did not show"
+ );
+ await BrowserTestUtils.waitForCondition(
+ () =>
+ document.querySelectorAll(
+ "#PanelUI-whatsNew-message-container .whatsNew-message"
+ ).length === msgs.length,
+ "The message container was not populated with the expected number of msgs"
+ );
+
+ await BrowserTestUtils.waitForCondition(
+ () =>
+ document.querySelector(
+ "#PanelUI-whatsNew-message-container .whatsNew-message-body remote-text"
+ ).shadowRoot.innerHTML,
+ "Ensure messages have content"
+ );
+
+ UITour.hideMenu(window, "appMenu");
+ // Clean up and remove messages
+ ToolbarPanelHub.disableAppmenuButton();
+ await client.db.clear();
+ // Wait to reset the WNPanel messages from state
+ const previousMessageCount = ASRouter.state.messages.length;
+ await BrowserTestUtils.waitForCondition(async () => {
+ await ASRouter.loadMessagesFromAllProviders();
+ return ASRouter.state.messages.length < previousMessageCount;
+ }, "WNPanel messages should have been removed");
+ await SpecialPowers.popPrefEnv();
+ // Reload the provider
+ await ASRouter._updateMessageProviders();
+});
diff --git a/browser/components/newtab/test/browser/browser_context_menu_item.js b/browser/components/newtab/test/browser/browser_context_menu_item.js
new file mode 100644
index 0000000000..10997824fa
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_context_menu_item.js
@@ -0,0 +1,29 @@
+"use strict";
+
+// Test that setting the newNewtabExperience.enabled pref to true does not
+// set icons in individual tile and card context menus on newtab page.
+test_newtab({
+ async before({ pushPrefs }) {
+ await pushPrefs([
+ "browser.newtabpage.activity-stream.newNewtabExperience.enabled",
+ true,
+ ]);
+ },
+ test: async function test_contextMenuIcons() {
+ const siteSelector = ".top-sites-list:not(.search-shortcut, .placeholder)";
+ await ContentTaskUtils.waitForCondition(
+ () => content.document.querySelector(siteSelector),
+ "Topsites have loaded"
+ );
+ const contextMenuItems = await content.openContextMenuAndGetOptions(
+ siteSelector
+ );
+ let icon = contextMenuItems[0].querySelector(".icon");
+ ok(!icon, "icon was not rendered");
+ },
+ async after() {
+ Services.prefs.clearUserPref(
+ "browser.newtabpage.activity-stream.newNewtabExperience.enabled"
+ );
+ },
+});
diff --git a/browser/components/newtab/test/browser/browser_customize_menu_content.js b/browser/components/newtab/test/browser/browser_customize_menu_content.js
new file mode 100644
index 0000000000..8854cb366f
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_customize_menu_content.js
@@ -0,0 +1,243 @@
+"use strict";
+
+test_newtab({
+ async before({ pushPrefs }) {
+ await pushPrefs(
+ ["browser.newtabpage.activity-stream.newNewtabExperience.enabled", true],
+ ["browser.newtabpage.activity-stream.customizationMenu.enabled", true],
+ ["browser.newtabpage.activity-stream.feeds.topsites", false],
+ ["browser.newtabpage.activity-stream.feeds.section.topstories", false],
+ ["browser.newtabpage.activity-stream.feeds.section.highlights", false],
+ ["browser.newtabpage.activity-stream.feeds.snippets", false]
+ );
+ },
+ test: async function test_render_customizeMenu() {
+ const TOPSITES_PREF = "browser.newtabpage.activity-stream.feeds.topsites";
+ const HIGHLIGHTS_PREF =
+ "browser.newtabpage.activity-stream.feeds.section.highlights";
+ const SNIPPETS_PREF = "browser.newtabpage.activity-stream.feeds.snippets";
+ const TOPSTORIES_PREF =
+ "browser.newtabpage.activity-stream.feeds.section.topstories";
+
+ await ContentTaskUtils.waitForCondition(
+ () => content.document.querySelector(".personalize-button"),
+ "Wait for prefs button to load on the newtab page"
+ );
+
+ let customizeButton = content.document.querySelector(".personalize-button");
+ customizeButton.click();
+
+ let defaultPos = "matrix(1, 0, 0, 1, 0, 0)";
+ await ContentTaskUtils.waitForCondition(
+ () =>
+ content.getComputedStyle(
+ content.document.querySelector(".customize-menu")
+ ).transform === defaultPos,
+ "Customize Menu should be visible on screen"
+ );
+
+ // Test that clicking the shortcuts toggle will make the section appear on the newtab page.
+ let shortcutsSwitch = content.document.querySelector(
+ "#shortcuts-section .switch"
+ );
+ let shortcutsSection = content.document.querySelector(
+ "section[data-section-id='topsites']"
+ );
+ Assert.ok(
+ !Services.prefs.getBoolPref(TOPSITES_PREF),
+ "Topsites are turned off"
+ );
+ Assert.ok(!shortcutsSection, "Shortcuts section is not rendered");
+
+ let prefPromise = ContentTaskUtils.waitForCondition(
+ () => Services.prefs.getBoolPref(TOPSITES_PREF),
+ "TopSites pref is turned on"
+ );
+ shortcutsSwitch.click();
+ await prefPromise;
+
+ Assert.ok(
+ content.document.querySelector("section[data-section-id='topsites']"),
+ "Shortcuts section is rendered"
+ );
+
+ // Test that clicking the pocket toggle will make the pocket section appear on the newtab page
+ let pocketSwitch = content.document.querySelector(
+ "#pocket-section .switch"
+ );
+ Assert.ok(
+ !Services.prefs.getBoolPref(TOPSTORIES_PREF),
+ "Pocket pref is turned off"
+ );
+ Assert.ok(
+ !content.document.querySelector("section[data-section-id='topstories']"),
+ "Pocket section is not rendered"
+ );
+
+ prefPromise = ContentTaskUtils.waitForCondition(
+ () => Services.prefs.getBoolPref(TOPSTORIES_PREF),
+ "Pocket pref is turned on"
+ );
+ pocketSwitch.click();
+ await prefPromise;
+
+ Assert.ok(
+ content.document.querySelector("section[data-section-id='topstories']"),
+ "Pocket section is rendered"
+ );
+
+ // Test that clicking the recent activity toggle will make the recent activity section appear on the newtab page
+ let highlightsSwitch = content.document.querySelector(
+ "#recent-section .switch"
+ );
+ Assert.ok(
+ !Services.prefs.getBoolPref(HIGHLIGHTS_PREF),
+ "Highlights pref is turned off"
+ );
+ Assert.ok(
+ !content.document.querySelector("section[data-section-id='highlights']"),
+ "Highlights section is not rendered"
+ );
+
+ prefPromise = ContentTaskUtils.waitForCondition(
+ () => Services.prefs.getBoolPref(HIGHLIGHTS_PREF),
+ "Highlights pref is turned on"
+ );
+ highlightsSwitch.click();
+ await prefPromise;
+
+ Assert.ok(
+ content.document.querySelector("section[data-section-id='highlights']"),
+ "Highlights section is rendered"
+ );
+
+ // Test that clicking the snippets toggle will flip the snippets pref
+ // note: Snippets are disabled in tests.
+ let snippetsSwitch = content.document.querySelector(
+ "#snippets-section .switch"
+ );
+ Assert.ok(
+ !Services.prefs.getBoolPref(SNIPPETS_PREF),
+ "Snippets pref is turned off"
+ );
+
+ prefPromise = ContentTaskUtils.waitForCondition(
+ () => Services.prefs.getBoolPref(SNIPPETS_PREF),
+ "Snippets pref is turned on after click"
+ );
+ snippetsSwitch.click();
+ await prefPromise;
+
+ prefPromise = ContentTaskUtils.waitForCondition(
+ () => !Services.prefs.getBoolPref(SNIPPETS_PREF),
+ "Snippets pref is turned on after click"
+ );
+ snippetsSwitch.click();
+ await prefPromise;
+ },
+ async after() {
+ Services.prefs.clearUserPref(
+ "browser.newtabpage.activity-stream.newNewtabExperience.enabled"
+ );
+ Services.prefs.clearUserPref(
+ "browser.newtabpage.activity-stream.customizationMenu.enabled"
+ );
+ Services.prefs.clearUserPref(
+ "browser.newtabpage.activity-stream.feeds.topsites"
+ );
+ Services.prefs.clearUserPref(
+ "browser.newtabpage.activity-stream.feeds.section.topstories"
+ );
+ Services.prefs.clearUserPref(
+ "browser.newtabpage.activity-stream.feeds.section.highlights"
+ );
+ Services.prefs.clearUserPref(
+ "browser.newtabpage.activity-stream.feeds.snippets"
+ );
+ },
+});
+
+test_newtab({
+ async before({ pushPrefs }) {
+ await pushPrefs([
+ "browser.newtabpage.activity-stream.newNewtabExperience.enabled",
+ true,
+ ]);
+ },
+ test: async function test_open_close_customizeMenu() {
+ const EventUtils = ContentTaskUtils.getEventUtils(content);
+ await ContentTaskUtils.waitForCondition(
+ () => content.document.querySelector(".personalize-button"),
+ "Wait for prefs button to load on the newtab page"
+ );
+
+ let customizeButton = content.document.querySelector(".personalize-button");
+ customizeButton.click();
+
+ let defaultPos = "matrix(1, 0, 0, 1, 0, 0)";
+ await ContentTaskUtils.waitForCondition(
+ () =>
+ content.getComputedStyle(
+ content.document.querySelector(".customize-menu")
+ ).transform === defaultPos,
+ "Customize Menu should be visible on screen"
+ );
+
+ // Test close button.
+ let closeButton = content.document.querySelector(".close-button");
+ closeButton.click();
+ await ContentTaskUtils.waitForCondition(
+ () =>
+ content.getComputedStyle(
+ content.document.querySelector(".customize-menu")
+ ).transform !== defaultPos,
+ "Customize Menu should not be visible anymore"
+ );
+
+ // Reopen the customize menu
+ customizeButton.click();
+ await ContentTaskUtils.waitForCondition(
+ () =>
+ content.getComputedStyle(
+ content.document.querySelector(".customize-menu")
+ ).transform === defaultPos,
+ "Customize Menu should be visible on screen now"
+ );
+
+ // Test closing with esc key.
+ EventUtils.synthesizeKey("VK_ESCAPE", {}, content);
+ await ContentTaskUtils.waitForCondition(
+ () =>
+ content.getComputedStyle(
+ content.document.querySelector(".customize-menu")
+ ).transform !== defaultPos,
+ "Customize Menu should not be visible anymore"
+ );
+
+ // Reopen the customize menu
+ customizeButton.click();
+ await ContentTaskUtils.waitForCondition(
+ () =>
+ content.getComputedStyle(
+ content.document.querySelector(".customize-menu")
+ ).transform === defaultPos,
+ "Customize Menu should be visible on screen now"
+ );
+
+ // Test closing with external click.
+ let outerWrapper = content.document.querySelector(".outer-wrapper");
+ outerWrapper.click();
+ await ContentTaskUtils.waitForCondition(
+ () =>
+ content.getComputedStyle(
+ content.document.querySelector(".customize-menu")
+ ).transform !== defaultPos,
+ "Customize Menu should not be visible anymore"
+ );
+ },
+ async after() {
+ Services.prefs.clearUserPref(
+ "browser.newtabpage.activity-stream.newNewtabExperience.enabled"
+ );
+ },
+});
diff --git a/browser/components/newtab/test/browser/browser_customize_menu_render.js b/browser/components/newtab/test/browser/browser_customize_menu_render.js
new file mode 100644
index 0000000000..8c5ef60692
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_customize_menu_render.js
@@ -0,0 +1,183 @@
+"use strict";
+
+// Test that the customization menu is rendered when
+// the parent pref is set to true even if the customize
+// menu specific pref is false.
+test_newtab({
+ async before({ pushPrefs }) {
+ await pushPrefs([
+ "browser.newtabpage.activity-stream.newNewtabExperience.enabled",
+ true,
+ ]);
+ await pushPrefs([
+ "browser.newtabpage.activity-stream.customizationMenu.enabled",
+ false,
+ ]);
+ },
+ test: async function test_render_customizeMenu() {
+ await ContentTaskUtils.waitForCondition(
+ () => content.document.querySelector(".personalize-button"),
+ "Wait for personalize button to load on the newtab page"
+ );
+
+ let defaultPos = "matrix(1, 0, 0, 1, 0, 0)";
+ ok(
+ content.getComputedStyle(
+ content.document.querySelector(".customize-menu")
+ ).transform !== defaultPos,
+ "Customize Menu should be rendered, but not visible yet"
+ );
+
+ let customizeButton = content.document.querySelector(".personalize-button");
+ customizeButton.click();
+
+ await ContentTaskUtils.waitForCondition(
+ () =>
+ content.getComputedStyle(
+ content.document.querySelector(".customize-menu")
+ ).transform === defaultPos,
+ "Customize Menu should be visible now"
+ );
+ },
+ async after() {
+ Services.prefs.clearUserPref(
+ "browser.newtabpage.activity-stream.newNewtabExperience.enabled"
+ );
+ Services.prefs.clearUserPref(
+ "browser.newtabpage.activity-stream.customizationMenu.enabled"
+ );
+ },
+});
+
+// Test that the customization menu is rendered when the parent
+// pref is set to false and the customize menu specific pref is
+// set to true.
+test_newtab({
+ async before({ pushPrefs }) {
+ await pushPrefs([
+ "browser.newtabpage.activity-stream.newNewtabExperience.enabled",
+ false,
+ ]);
+ await pushPrefs([
+ "browser.newtabpage.activity-stream.customizationMenu.enabled",
+ true,
+ ]);
+ },
+ test: async function test_render_customizeMenu() {
+ await ContentTaskUtils.waitForCondition(
+ () => content.document.querySelector(".personalize-button"),
+ "Wait for personalize button to load on the newtab page"
+ );
+
+ let defaultPos = "matrix(1, 0, 0, 1, 0, 0)";
+ ok(
+ content.getComputedStyle(
+ content.document.querySelector(".customize-menu")
+ ).transform !== defaultPos,
+ "Customize Menu should be rendered, but not visible"
+ );
+
+ let customizeButton = content.document.querySelector(".personalize-button");
+ customizeButton.click();
+
+ await ContentTaskUtils.waitForCondition(
+ () =>
+ content.getComputedStyle(
+ content.document.querySelector(".customize-menu")
+ ).transform === defaultPos,
+ "Customize Menu should be visible now"
+ );
+ },
+ async after() {
+ Services.prefs.clearUserPref(
+ "browser.newtabpage.activity-stream.newNewtabExperience.enabled"
+ );
+ Services.prefs.clearUserPref(
+ "browser.newtabpage.activity-stream.customizationMenu.enabled"
+ );
+ },
+});
+
+// Test that the customization menu is rendered when both the parent pref and
+// the customize menu specific pref is set to true.
+test_newtab({
+ async before({ pushPrefs }) {
+ await pushPrefs([
+ "browser.newtabpage.activity-stream.newNewtabExperience.enabled",
+ true,
+ ]);
+ await pushPrefs([
+ "browser.newtabpage.activity-stream.customizationMenu.enabled",
+ true,
+ ]);
+ },
+ test: async function test_render_customizeMenu() {
+ await ContentTaskUtils.waitForCondition(
+ () => content.document.querySelector(".personalize-button"),
+ "Wait for personalize button to load on the newtab page"
+ );
+
+ let defaultPos = "matrix(1, 0, 0, 1, 0, 0)";
+ ok(
+ content.getComputedStyle(
+ content.document.querySelector(".customize-menu")
+ ).transform !== defaultPos,
+ "Customize Menu should be rendered, but not visible"
+ );
+
+ let customizeButton = content.document.querySelector(".personalize-button");
+ customizeButton.click();
+
+ await ContentTaskUtils.waitForCondition(
+ () => content.document.querySelector(".customize-menu"),
+ "Customize Menu should be rendered now"
+ );
+ },
+ async after() {
+ Services.prefs.clearUserPref(
+ "browser.newtabpage.activity-stream.newNewtabExperience.enabled"
+ );
+ Services.prefs.clearUserPref(
+ "browser.newtabpage.activity-stream.customizationMenu.enabled"
+ );
+ },
+});
+
+// Test that the customization menu is not rendered when both the parent pref and
+// the customize menu specific pref is set to false.
+test_newtab({
+ async before({ pushPrefs }) {
+ await pushPrefs([
+ "browser.newtabpage.activity-stream.newNewtabExperience.enabled",
+ false,
+ ]);
+ await pushPrefs([
+ "browser.newtabpage.activity-stream.customizationMenu.enabled",
+ false,
+ ]);
+ },
+ test: async function test_render_customizeMenu() {
+ await ContentTaskUtils.waitForCondition(
+ () => content.document.querySelector(".prefs-button .icon"),
+ "Prefs button should exist"
+ );
+
+ ok(
+ !content.document.querySelector(".personalize-button"),
+ "personalize button should not be rendered"
+ );
+
+ ok(
+ !content.document.querySelector(".customize-menu"),
+ "Customize Menu should not be rendered"
+ );
+ },
+ async after() {
+ Services.prefs.clearUserPref(
+ "browser.newtabpage.activity-stream.newNewtabExperience.enabled"
+ );
+ Services.prefs.clearUserPref(
+ "browser.newtabpage.activity-stream.customizationMenu.enabled"
+ );
+ },
+});
diff --git a/browser/components/newtab/test/browser/browser_discovery_card.js b/browser/components/newtab/test/browser/browser_discovery_card.js
new file mode 100644
index 0000000000..c1d9ec6b4c
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_discovery_card.js
@@ -0,0 +1,44 @@
+// If this fails it could be because of schema changes.
+// `ds_layout.json` defines the newtab page format
+// `topstories.json` defines the stories shown
+test_newtab({
+ async before({ pushPrefs }) {
+ await pushPrefs([
+ "browser.newtabpage.activity-stream.discoverystream.config",
+ JSON.stringify({
+ api_key_pref: "extensions.pocket.oAuthConsumerKey",
+ collapsible: true,
+ enabled: true,
+ show_spocs: false,
+ hardcoded_layout: false,
+ personalized: true,
+ layout_endpoint:
+ "https://example.com/browser/browser/components/newtab/test/browser/ds_layout.json",
+ }),
+ ]);
+ await pushPrefs([
+ "browser.newtabpage.activity-stream.discoverystream.endpoints",
+ "https://example.com",
+ ]);
+ },
+ test: async function test_card_render() {
+ await ContentTaskUtils.waitForCondition(
+ () =>
+ content.document.querySelectorAll(
+ "[data-section-id='topstories'] .ds-card-link"
+ ).length
+ );
+ let found = content.document.querySelectorAll(
+ "[data-section-id='topstories'] .ds-card-link"
+ ).length;
+ is(found, 1, "there should be 1 topstory card");
+ let cardHostname = content.document.querySelector(
+ "[data-section-id='topstories'] .source"
+ ).innerText;
+ is(
+ cardHostname,
+ "bbc.com",
+ `Card hostname is ${cardHostname} instead of bbc.com`
+ );
+ },
+});
diff --git a/browser/components/newtab/test/browser/browser_discovery_render.js b/browser/components/newtab/test/browser/browser_discovery_render.js
new file mode 100644
index 0000000000..86b0410698
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_discovery_render.js
@@ -0,0 +1,32 @@
+"use strict";
+
+async function before({ pushPrefs }) {
+ await pushPrefs([
+ "browser.newtabpage.activity-stream.discoverystream.config",
+ JSON.stringify({
+ collapsible: true,
+ enabled: true,
+ hardcoded_layout: true,
+ }),
+ ]);
+}
+
+test_newtab({
+ before,
+ test: async function test_render_hardcoded_topsites() {
+ const topSites = await ContentTaskUtils.waitForCondition(() =>
+ content.document.querySelector(".ds-top-sites")
+ );
+ ok(topSites, "Got the discovery stream top sites section");
+ },
+});
+
+test_newtab({
+ before,
+ test: async function test_render_hardcoded_learnmore() {
+ const learnMoreLink = await ContentTaskUtils.waitForCondition(() =>
+ content.document.querySelector(".ds-layout .learn-more-link > a")
+ );
+ ok(learnMoreLink, "Got the discovery stream learn more link");
+ },
+});
diff --git a/browser/components/newtab/test/browser/browser_discovery_styles.js b/browser/components/newtab/test/browser/browser_discovery_styles.js
new file mode 100644
index 0000000000..03f830d2ee
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_discovery_styles.js
@@ -0,0 +1,171 @@
+"use strict";
+
+function fakePref(layout) {
+ return [
+ "browser.newtabpage.activity-stream.discoverystream.config",
+ JSON.stringify({
+ enabled: true,
+ layout_endpoint: `data:,${encodeURIComponent(JSON.stringify(layout))}`,
+ }),
+ ];
+}
+
+test_newtab({
+ async before({ pushPrefs }) {
+ await pushPrefs(
+ fakePref({
+ layout: [
+ {
+ width: 12,
+ components: [
+ {
+ type: "TopSites",
+ },
+ {
+ type: "HorizontalRule",
+ styles: {
+ hr: "border-width: 3.14159mm",
+ },
+ },
+ ],
+ },
+ ],
+ })
+ );
+ },
+ test: async function test_hr_override() {
+ const hr = await ContentTaskUtils.waitForCondition(() =>
+ content.document.querySelector("hr")
+ );
+ ok(
+ content.getComputedStyle(hr).borderTopWidth.match(/11.?\d*px/),
+ "applied and normalized hr component width override"
+ );
+ },
+});
+
+test_newtab({
+ async before({ pushPrefs }) {
+ await pushPrefs(
+ fakePref({
+ layout: [
+ {
+ width: 12,
+ components: [
+ {
+ type: "TopSites",
+ },
+ {
+ type: "HorizontalRule",
+ styles: {
+ "*": "color: #f00",
+ "": "font-size: 1.2345cm",
+ hr: "font-weight: 12345",
+ },
+ },
+ ],
+ },
+ ],
+ })
+ );
+ },
+ test: async function test_multiple_overrides() {
+ const hr = await ContentTaskUtils.waitForCondition(() =>
+ content.document.querySelector("hr")
+ );
+ const styles = content.getComputedStyle(hr);
+ is(styles.color, "rgb(255, 0, 0)", "applied and normalized color");
+ is(styles.fontSize, "46.6583px", "applied and normalized font size");
+ is(styles.fontWeight, "400", "applied and normalized font weight");
+ },
+});
+
+test_newtab({
+ async before({ pushPrefs }) {
+ await pushPrefs(
+ fakePref({
+ layout: [
+ {
+ width: 12,
+ components: [
+ {
+ type: "HorizontalRule",
+ styles: {
+ // NB: Use display: none to avoid network requests to unfiltered urls
+ hr: `display: none;
+ background-image: url(https://example.com/background);
+ content: url(chrome://browser/content);
+ cursor: url( resource://activity-stream/cursor ), auto;
+ list-style-image: url('https://img-getpocket.cdn.mozilla.net/list');`,
+ },
+ },
+ ],
+ },
+ ],
+ })
+ );
+ },
+ test: async function test_url_filtering() {
+ const hr = await ContentTaskUtils.waitForCondition(() =>
+ content.document.querySelector("hr")
+ );
+ const styles = content.getComputedStyle(hr);
+ is(
+ styles.backgroundImage,
+ "none",
+ "filtered out invalid background image url"
+ );
+ is(
+ styles.content,
+ `url("chrome://browser/content/browser.xul")`,
+ "applied, normalized and allowed content url"
+ );
+ is(
+ styles.cursor,
+ `url("resource://activity-stream/cursor"), auto`,
+ "applied, normalized and allowed cursor url"
+ );
+ is(
+ styles.listStyleImage,
+ `url("https://img-getpocket.cdn.mozilla.net/list")`,
+ "applied, normalized and allowed list style image url"
+ );
+ },
+});
+
+test_newtab({
+ async before({ pushPrefs }) {
+ await pushPrefs(
+ fakePref({
+ layout: [
+ {
+ width: 12,
+ components: [
+ {
+ type: "HorizontalRule",
+ styles: {
+ "@media (min-width: 0)":
+ "content: url(chrome://browser/content)",
+ "@media (min-width: 0) *":
+ "content: url(chrome://browser/content)",
+ "@media (min-width: 0) { * }":
+ "content: url(chrome://browser/content)",
+ },
+ },
+ ],
+ },
+ ],
+ })
+ );
+ },
+ test: async function test_atrule_filtering() {
+ const hr = await ContentTaskUtils.waitForCondition(() =>
+ content.document.querySelector("hr")
+ );
+ is(
+ content.getComputedStyle(hr).content,
+ "normal",
+ "filtered out attempted @media query"
+ );
+ },
+});
diff --git a/browser/components/newtab/test/browser/browser_enabled_newtabpage.js b/browser/components/newtab/test/browser/browser_enabled_newtabpage.js
new file mode 100644
index 0000000000..1c003198ed
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_enabled_newtabpage.js
@@ -0,0 +1,25 @@
+function checkSpec(uri, check, message) {
+ const { spec } = NetUtil.newChannel({
+ loadUsingSystemPrincipal: true,
+ uri,
+ }).URI;
+
+ info(`got ${spec} for ${uri}`);
+ check(spec, "about:blank", message);
+}
+
+add_task(async function test_newtab_enabled() {
+ checkSpec(
+ "about:newtab",
+ isnot,
+ "did not get blank for default about:newtab"
+ );
+ checkSpec("about:home", isnot, "did not get blank for default about:home");
+
+ await SpecialPowers.pushPrefEnv({
+ set: [["browser.newtabpage.enabled", false]],
+ });
+
+ checkSpec("about:newtab", is, "got blank when newtab is not enabled");
+ checkSpec("about:home", isnot, "still did not get blank for about:home");
+});
diff --git a/browser/components/newtab/test/browser/browser_getScreenshots.js b/browser/components/newtab/test/browser/browser_getScreenshots.js
new file mode 100644
index 0000000000..6e285c2114
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_getScreenshots.js
@@ -0,0 +1,90 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
+// a blue page
+const TEST_URL =
+ "https://example.com/browser/browser/components/newtab/test/browser/blue_page.html";
+const XHTMLNS = "http://www.w3.org/1999/xhtml";
+
+ChromeUtils.defineModuleGetter(
+ this,
+ "Screenshots",
+ "resource://activity-stream/lib/Screenshots.jsm"
+);
+
+function get_pixels(stringOrObject, width, height) {
+ return new Promise(resolve => {
+ // get the pixels out of the screenshot that we just took
+ let img = document.createElementNS(XHTMLNS, "img");
+ let imgPath;
+
+ if (typeof stringOrObject === "string") {
+ Assert.ok(
+ Services.prefs.getBoolPref(
+ "browser.tabs.remote.separatePrivilegedContentProcess"
+ ),
+ "The privileged about content process should be enabled."
+ );
+ imgPath = stringOrObject;
+ Assert.ok(
+ imgPath.startsWith("moz-page-thumb://"),
+ "Thumbnails should be retrieved using moz-page-thumb://"
+ );
+ } else {
+ imgPath = URL.createObjectURL(stringOrObject.data);
+ }
+
+ img.setAttribute("src", imgPath);
+ img.addEventListener(
+ "load",
+ () => {
+ let canvas = document.createElementNS(XHTMLNS, "canvas");
+ canvas.setAttribute("width", width);
+ canvas.setAttribute("height", height);
+ let ctx = canvas.getContext("2d");
+ ctx.drawImage(img, 0, 0, width, height);
+ const result = ctx.getImageData(0, 0, width, height).data;
+ URL.revokeObjectURL(imgPath);
+ resolve(result);
+ },
+ { once: true }
+ );
+ });
+}
+
+add_task(async function test_screenshot() {
+ await SpecialPowers.pushPrefEnv({
+ set: [["browser.pagethumbnails.capturing_disabled", false]],
+ });
+
+ // take a screenshot of a blue page and save it as a blob
+ const screenshotAsObject = await Screenshots.getScreenshotForURL(TEST_URL);
+ let pixels = await get_pixels(screenshotAsObject, 10, 10);
+ let rgbaCount = { r: 0, g: 0, b: 0, a: 0 };
+ while (pixels.length) {
+ // break the pixels into arrays of 4 components [red, green, blue, alpha]
+ let [r, g, b, a, ...rest] = pixels;
+ pixels = rest;
+ // count the number of each coloured pixels
+ if (r === 255) {
+ rgbaCount.r += 1;
+ }
+ if (g === 255) {
+ rgbaCount.g += 1;
+ }
+ if (b === 255) {
+ rgbaCount.b += 1;
+ }
+ if (a === 255) {
+ rgbaCount.a += 1;
+ }
+ }
+
+ // in the end, we should only have 100 blue pixels (10 x 10) with full opacity
+ Assert.equal(rgbaCount.b, 100, "Has 100 blue pixels");
+ Assert.equal(rgbaCount.a, 100, "Has full opacity");
+ Assert.equal(rgbaCount.r, 0, "Does not have any red pixels");
+ Assert.equal(rgbaCount.g, 0, "Does not have any green pixels");
+});
diff --git a/browser/components/newtab/test/browser/browser_highlights_section.js b/browser/components/newtab/test/browser/browser_highlights_section.js
new file mode 100644
index 0000000000..55a513f538
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_highlights_section.js
@@ -0,0 +1,101 @@
+"use strict";
+
+/**
+ * Helper for setup and cleanup of Highlights section tests.
+ * @param bookmarkCount Number of bookmark higlights to add
+ * @param test The test case
+ */
+function test_highlights(bookmarkCount, test) {
+ test_newtab({
+ async before({ tab }) {
+ if (bookmarkCount) {
+ await addHighlightsBookmarks(bookmarkCount);
+ // Wait for HighlightsFeed to update and display the items.
+ await SpecialPowers.spawn(tab.linkedBrowser, [], async () => {
+ await ContentTaskUtils.waitForCondition(
+ () =>
+ content.document.querySelector(
+ "[data-section-id='highlights'] .card-outer:not(.placeholder)"
+ ),
+ "No highlights cards found."
+ );
+ });
+ }
+ },
+ test,
+ async after() {
+ await clearHistoryAndBookmarks();
+ },
+ });
+}
+
+test_highlights(
+ 2, // Number of highlights cards
+ function check_highlights_cards() {
+ let found = content.document.querySelectorAll(
+ "[data-section-id='highlights'] .card-outer:not(.placeholder)"
+ ).length;
+ is(found, 2, "there should be 2 highlights cards");
+
+ found = content.document.querySelectorAll(
+ "[data-section-id='highlights'] .section-list .placeholder"
+ ).length;
+ is(found, 2, "there should be 1 row * 4 - 2 = 2 highlights placeholder");
+
+ found = content.document.querySelectorAll(
+ "[data-section-id='highlights'] .card-context-icon.icon-bookmark-added"
+ ).length;
+ is(found, 2, "there should be 2 bookmark icons");
+ }
+);
+
+test_highlights(
+ 1, // Number of highlights cards
+ function check_highlights_context_menu() {
+ const menuButton = content.document.querySelector(
+ "[data-section-id='highlights'] .card-outer .context-menu-button"
+ );
+ // Open the menu.
+ menuButton.click();
+ const found = content.document.querySelector(
+ "[data-section-id='highlights'] .card-outer .context-menu"
+ );
+ ok(found && !found.hidden, "Should find a visible context menu");
+ }
+);
+
+test_highlights(
+ 1, // Number of highlights cards
+ async function check_highlights_context_menu() {
+ let found = content.document.querySelectorAll(
+ "[data-section-id='highlights'] .card-context-icon.icon-bookmark-added"
+ ).length;
+ is(found, 1, "there should be 1 bookmark icon");
+
+ const menuButton = content.document.querySelector(
+ "[data-section-id='highlights'] .card-outer .context-menu-button"
+ );
+ // Open the menu.
+ menuButton.click();
+ const contextMenu = content.document.querySelector(
+ "[data-section-id='highlights'] .card-outer .context-menu"
+ );
+ ok(
+ contextMenu && !contextMenu.hidden,
+ "Should find a visible context menu"
+ );
+
+ const removeBookmarkBtn = contextMenu.querySelector(
+ "[data-section-id='highlights'] button .icon-bookmark-added"
+ );
+ removeBookmarkBtn.click();
+
+ await ContentTaskUtils.waitForCondition(
+ () =>
+ content.document.querySelectorAll(
+ "[data-section-id='highlights'] .card-context-icon.icon-bookmark-added"
+ ).length === 0,
+ "no more bookmark cards should be visible"
+ );
+ }
+);
diff --git a/browser/components/newtab/test/browser/browser_newtab_experiment_api.js b/browser/components/newtab/test/browser/browser_newtab_experiment_api.js
new file mode 100644
index 0000000000..e02ab92cbc
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_newtab_experiment_api.js
@@ -0,0 +1,90 @@
+"use strict";
+
+const { ExperimentAPI } = ChromeUtils.import(
+ "resource://messaging-system/experiments/ExperimentAPI.jsm"
+);
+const { ExperimentFakes } = ChromeUtils.import(
+ "resource://testing-common/MSTestUtils.jsm"
+);
+
+/**
+ * Enrolls browser in an experiment with value featureValue and
+ * runs a test in newtab content
+ *
+ * @param {string} slug A slug
+ * @param {NewTabFeatureConfig} featureValue A feature config
+ * @param {NewTabTest} test A new tab test compatible with test_newtab (see head.js)
+ */
+async function testWithExperimentFeatureValue(slug, featureValue, test) {
+ test_newtab({
+ async before() {
+ let updatePromise = ExperimentFakes.waitForExperimentUpdate(
+ ExperimentAPI,
+ {
+ slug,
+ }
+ );
+
+ ExperimentAPI._store.addExperiment({
+ slug,
+ branch: {
+ slug: `${slug}-treatment`,
+ feature: {
+ enabled: true,
+ featureId: "newtab",
+ value: featureValue,
+ },
+ },
+ active: true,
+ });
+
+ await updatePromise;
+ },
+ test,
+ async after() {
+ ExperimentAPI._store._deleteForTests(slug);
+ is(ExperimentAPI._store.getAll().includes(slug), false, "Cleanup done");
+ },
+ });
+}
+
+/**
+ * Test the ExperimentAPI overrides default values.
+ */
+testWithExperimentFeatureValue(
+ `mochitest-newtab-${Date.now()}`,
+ { prefsButtonIcon: "icon-info" },
+ async function check_icon_changes_with_experiment() {
+ let el = content.document.querySelector(".prefs-button .icon");
+ ok(el, "there should be a settings icon");
+
+ await ContentTaskUtils.waitForCondition(
+ () =>
+ content.document
+ .querySelector(".prefs-button .icon")
+ .classList.contains("icon-info"),
+ "settings icon uses prefsButtonIcon value set in the experiment"
+ );
+ }
+);
+
+/**
+ * Test the ExperimentAPI uses default values for an empty feature config.
+ */
+testWithExperimentFeatureValue(
+ `mochitest-newtab-${Date.now()}`,
+ // Empty feature value should result in using all defaults
+ null,
+ async function check_icon_uses_default() {
+ let el = content.document.querySelector(".prefs-button .icon");
+ ok(el, "there should be a settings icon");
+
+ await ContentTaskUtils.waitForCondition(
+ () =>
+ content.document
+ .querySelector(".prefs-button .icon")
+ .classList.contains("icon-settings"),
+ "settings icon uses default value"
+ );
+ }
+);
diff --git a/browser/components/newtab/test/browser/browser_newtab_header.js b/browser/components/newtab/test/browser/browser_newtab_header.js
new file mode 100644
index 0000000000..daf7f5d9c2
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_newtab_header.js
@@ -0,0 +1,296 @@
+"use strict";
+
+// If the pref `browser.newtabpage.activity-stream.newNewtabExperience.enabled`
+// is set to true, test that:
+// 1. Top sites header is hidden and the topsites section is not collapsed on load".
+// 2. Pocket header and section are visible and not collapsed on load.
+// 3. Recent activity section and header are visible and not collapsed on load.
+test_newtab({
+ async before({ pushPrefs }) {
+ await pushPrefs([
+ "browser.newtabpage.activity-stream.newNewtabExperience.enabled",
+ true,
+ ]);
+ await pushPrefs([
+ "browser.newtabpage.activity-stream.customizationMenu.enabled",
+ false,
+ ]);
+ },
+ test: async function test_render_customizeMenu() {
+ // Top sites section
+ await ContentTaskUtils.waitForCondition(
+ () => content.document.querySelector(".top-sites"),
+ "Wait for the top sites section to load"
+ );
+
+ let topSitesHeader = content.document.querySelector(
+ ".top-sites .section-title"
+ );
+ ok(
+ topSitesHeader && topSitesHeader.style.visibility === "hidden",
+ "Top sites header should not be visible"
+ );
+
+ let topSitesSection = content.document.querySelector(".top-sites");
+ let isTopSitesCollapsed = topSitesSection.className.includes("collapsed");
+ ok(!isTopSitesCollapsed, "Top sites should not be collapsed on load");
+
+ // Pocket section
+ await ContentTaskUtils.waitForCondition(
+ () =>
+ content.document.querySelector("section[data-section-id='topstories']"),
+ "Wait for the pocket section to load"
+ );
+
+ let pocketSection = content.document.querySelector(
+ "section[data-section-id='topstories']"
+ );
+ let isPocketSectionCollapsed = pocketSection.className.includes(
+ "collapsed"
+ );
+ ok(
+ !isPocketSectionCollapsed,
+ "Pocket section should not be collapsed on load"
+ );
+
+ let pocketHeader = content.document.querySelector(
+ "section[data-section-id='topstories'] .section-title"
+ );
+ ok(
+ pocketHeader && !pocketHeader.style.visibility,
+ "Pocket header should be visible"
+ );
+
+ // Highlights (Recent activity) section.
+ await ContentTaskUtils.waitForCondition(
+ () =>
+ content.document.querySelector("section[data-section-id='highlights']"),
+ "Wait for the highlights section to load"
+ );
+ let highlightsSection = content.document.querySelector(
+ "section[data-section-id='topstories']"
+ );
+ let isHighlightsSectionCollapsed = highlightsSection.className.includes(
+ "collapsed"
+ );
+ ok(
+ !isHighlightsSectionCollapsed,
+ "Highlights section should not be collapsed on load"
+ );
+
+ let highlightsHeader = content.document.querySelector(
+ "section[data-section-id='highlights'] .section-title"
+ );
+ ok(
+ highlightsHeader && !highlightsHeader.style.visibility,
+ "Highlights header should be visible"
+ );
+ },
+ async after() {
+ Services.prefs.clearUserPref(
+ "browser.newtabpage.activity-stream.newNewtabExperience.enabled"
+ );
+ Services.prefs.clearUserPref(
+ "browser.newtabpage.activity-stream.customizationMenu.enabled"
+ );
+ },
+});
+
+// If the pref `browser.newtabpage.activity-stream.customizationMenu.enabled`
+// is set to true, test that:
+// 1. Top sites header is hidden and the section is not collapsed on load.
+// 2. Pocket header and section are visible.
+// 3. Recent activity section and header are visible.
+test_newtab({
+ async before({ pushPrefs }) {
+ await pushPrefs([
+ "browser.newtabpage.activity-stream.newNewtabExperience.enabled",
+ false,
+ ]);
+ await pushPrefs([
+ "browser.newtabpage.activity-stream.customizationMenu.enabled",
+ true,
+ ]);
+ },
+ test: async function test_render_customizeMenu() {
+ // Top sites section
+ await ContentTaskUtils.waitForCondition(
+ () => content.document.querySelector(".top-sites"),
+ "Wait for the top sites section to load"
+ );
+
+ let topSitesHeader = content.document.querySelector(
+ ".top-sites .section-title"
+ );
+ ok(
+ topSitesHeader && topSitesHeader.style.visibility === "hidden",
+ "Top sites header should not be visible"
+ );
+
+ let topSitesSection = content.document.querySelector(".top-sites");
+ let isTopSitesCollapsed = topSitesSection.className.includes("collapsed");
+ ok(!isTopSitesCollapsed, "Top sites should not be collapsed on load");
+
+ // Pocket section
+ await ContentTaskUtils.waitForCondition(
+ () =>
+ content.document.querySelector("section[data-section-id='topstories']"),
+ "Wait for the pocket section to load"
+ );
+
+ let pocketHeader = content.document.querySelector(
+ "section[data-section-id='topstories'] .section-title"
+ );
+ ok(
+ pocketHeader && !pocketHeader.style.visibility,
+ "Pocket header should be visible"
+ );
+
+ // Highlights (Recent activity) section.
+ await ContentTaskUtils.waitForCondition(
+ () =>
+ content.document.querySelector("section[data-section-id='highlights']"),
+ "Wait for the highlights section to load"
+ );
+
+ let highlightsHeader = content.document.querySelector(
+ "section[data-section-id='highlights'] .section-title"
+ );
+ ok(
+ highlightsHeader && !highlightsHeader.style.visibility,
+ "Highlights header should be visible"
+ );
+ },
+ async after() {
+ Services.prefs.clearUserPref(
+ "browser.newtabpage.activity-stream.newNewtabExperience.enabled"
+ );
+ Services.prefs.clearUserPref(
+ "browser.newtabpage.activity-stream.customizationMenu.enabled"
+ );
+ },
+});
+
+// If the pref `browser.newtabpage.activity-stream.newNewtabExperience.enabled`
+// and `browser.newtabpage.activity-stream.customizationMenu.enabled` are set to
+// false, test that:
+// 1. Top sites header is shown and it is collapsible.
+// 2. Pocket header and section are visible and the section is collapsible.
+// 3. Recent activity section and header are visible and the section is collapsible.
+test_newtab({
+ async before({ pushPrefs }) {
+ await pushPrefs([
+ "browser.newtabpage.activity-stream.newNewtabExperience.enabled",
+ false,
+ ]);
+ await pushPrefs([
+ "browser.newtabpage.activity-stream.customizationMenu.enabled",
+ false,
+ ]);
+ },
+ test: async function test_render_customizeMenu() {
+ // Top sites section
+ await ContentTaskUtils.waitForCondition(
+ () => content.document.querySelector(".top-sites"),
+ "Wait for the top sites section to load"
+ );
+
+ let topSitesHeader = content.document.querySelector(
+ ".top-sites .section-title"
+ );
+ ok(
+ topSitesHeader && !topSitesHeader.style.visibility,
+ "Top sites header should be visible"
+ );
+
+ let topSitesSection = content.document.querySelector(".top-sites");
+ let topSitesHeaderClickTarget = content.document.querySelector(
+ ".top-sites .section-title .click-target"
+ );
+ topSitesHeaderClickTarget.click();
+ await ContentTaskUtils.waitForCondition(
+ () => topSitesSection.className.includes("collapsed"),
+ "Top sites section is collapsible on click"
+ );
+
+ topSitesHeaderClickTarget.click();
+ await ContentTaskUtils.waitForCondition(
+ () => !topSitesSection.className.includes("collapsed"),
+ "Top sites section is expandable on click"
+ );
+
+ // Pocket section
+ await ContentTaskUtils.waitForCondition(
+ () =>
+ content.document.querySelector("section[data-section-id='topstories']"),
+ "Wait for the pocket section to load"
+ );
+
+ let pocketHeader = content.document.querySelector(
+ "section[data-section-id='topstories'] .section-title"
+ );
+ ok(
+ pocketHeader && !pocketHeader.style.visibility,
+ "Pocket header should be visible"
+ );
+
+ let pocketSection = content.document.querySelector(
+ "section[data-section-id='topstories']"
+ );
+ let pocketHeaderClickTarget = content.document.querySelector(
+ "section[data-section-id='topstories'] .section-title .click-target"
+ );
+ pocketHeaderClickTarget.click();
+ await ContentTaskUtils.waitForCondition(
+ () => pocketSection.className.includes("collapsed"),
+ "Pocket section is collapsible on click"
+ );
+
+ pocketHeaderClickTarget.click();
+ await ContentTaskUtils.waitForCondition(
+ () => !pocketSection.className.includes("collapsed"),
+ "Pocket section is expandable on click"
+ );
+
+ // Highlights (Recent activity) section.
+ await ContentTaskUtils.waitForCondition(
+ () =>
+ content.document.querySelector("section[data-section-id='highlights']"),
+ "Wait for the highlights section to load"
+ );
+
+ let highlightsHeader = content.document.querySelector(
+ "section[data-section-id='highlights'] .section-title"
+ );
+ ok(
+ highlightsHeader && !highlightsHeader.style.visibility,
+ "Highlights header should be visible on load"
+ );
+
+ let highlightsSection = content.document.querySelector(
+ "section[data-section-id='highlights']"
+ );
+ let highlightsHeaderClickTarget = content.document.querySelector(
+ "section[data-section-id='highlights'] .section-title .click-target"
+ );
+ highlightsHeaderClickTarget.click();
+ await ContentTaskUtils.waitForCondition(
+ () => highlightsSection.className.includes("collapsed"),
+ "Highlights section is collapsible on click"
+ );
+
+ highlightsHeaderClickTarget.click();
+ await ContentTaskUtils.waitForCondition(
+ () => !highlightsSection.className.includes("collapsed"),
+ "Highlights section is expandable on click"
+ );
+ },
+ async after() {
+ Services.prefs.clearUserPref(
+ "browser.newtabpage.activity-stream.newNewtabExperience.enabled"
+ );
+ Services.prefs.clearUserPref(
+ "browser.newtabpage.activity-stream.customizationMenu.enabled"
+ );
+ },
+});
diff --git a/browser/components/newtab/test/browser/browser_newtab_overrides.js b/browser/components/newtab/test/browser/browser_newtab_overrides.js
new file mode 100644
index 0000000000..a8f79b6765
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_newtab_overrides.js
@@ -0,0 +1,138 @@
+"use strict";
+
+const { AboutNewTab } = ChromeUtils.import(
+ "resource:///modules/AboutNewTab.jsm"
+);
+
+registerCleanupFunction(() => {
+ AboutNewTab.resetNewTabURL();
+});
+
+function nextChangeNotificationPromise(aNewURL, testMessage) {
+ return TestUtils.topicObserved("newtab-url-changed", function observer(
+ aSubject,
+ aData
+ ) {
+ Assert.equal(aData, aNewURL, testMessage);
+ return true;
+ });
+}
+
+/*
+ * Tests that the default newtab page is always returned when one types "about:newtab" in the URL bar,
+ * even when overridden.
+ */
+add_task(async function redirector_ignores_override() {
+ let overrides = ["chrome://browser/content/aboutRobots.xhtml", "about:home"];
+
+ for (let overrideURL of overrides) {
+ let notificationPromise = nextChangeNotificationPromise(
+ overrideURL,
+ `newtab page now points to ${overrideURL}`
+ );
+ AboutNewTab.newTabURL = overrideURL;
+
+ await notificationPromise;
+ Assert.ok(AboutNewTab.newTabURLOverridden, "url has been overridden");
+
+ let tabOptions = {
+ gBrowser,
+ url: "about:newtab",
+ };
+
+ /*
+ * Simulate typing "about:newtab" in the url bar.
+ *
+ * Bug 1240169 - We expect the redirector to lead the user to "about:newtab", the default URL,
+ * due to invoking AboutRedirector. A user interacting with the chrome otherwise would lead
+ * to the overriding URLs.
+ */
+ await BrowserTestUtils.withNewTab(tabOptions, async browser => {
+ await SpecialPowers.spawn(browser, [], async () => {
+ Assert.equal(content.location.href, "about:newtab", "Got right URL");
+ Assert.equal(
+ content.document.location.href,
+ "about:newtab",
+ "Got right URL"
+ );
+ Assert.notEqual(
+ content.document.nodePrincipal,
+ Services.scriptSecurityManager.getSystemPrincipal(),
+ "activity stream principal should not match systemPrincipal"
+ );
+ });
+ });
+ }
+});
+
+/*
+ * Tests loading an overridden newtab page by simulating opening a newtab page from chrome
+ */
+add_task(async function override_loads_in_browser() {
+ let overrides = [
+ "chrome://browser/content/aboutRobots.xhtml",
+ "about:home",
+ " about:home",
+ ];
+
+ for (let overrideURL of overrides) {
+ let notificationPromise = nextChangeNotificationPromise(
+ overrideURL.trim(),
+ `newtab page now points to ${overrideURL}`
+ );
+ AboutNewTab.newTabURL = overrideURL;
+
+ await notificationPromise;
+ Assert.ok(AboutNewTab.newTabURLOverridden, "url has been overridden");
+
+ // simulate a newtab open as a user would
+ BrowserOpenTab();
+
+ let browser = gBrowser.selectedBrowser;
+ await BrowserTestUtils.browserLoaded(browser);
+
+ await SpecialPowers.spawn(browser, [{ url: overrideURL }], async args => {
+ Assert.equal(content.location.href, args.url.trim(), "Got right URL");
+ Assert.equal(
+ content.document.location.href,
+ args.url.trim(),
+ "Got right URL"
+ );
+ });
+ BrowserTestUtils.removeTab(gBrowser.selectedTab);
+ }
+});
+
+/*
+ * Tests edge cases when someone overrides the newtabpage with whitespace
+ */
+add_task(async function override_blank_loads_in_browser() {
+ let overrides = ["", " ", "\n\t", " about:blank"];
+
+ for (let overrideURL of overrides) {
+ let notificationPromise = nextChangeNotificationPromise(
+ "about:blank",
+ "newtab page now points to about:blank"
+ );
+ AboutNewTab.newTabURL = overrideURL;
+
+ await notificationPromise;
+ Assert.ok(AboutNewTab.newTabURLOverridden, "url has been overridden");
+
+ // simulate a newtab open as a user would
+ BrowserOpenTab();
+
+ let browser = gBrowser.selectedBrowser;
+ await BrowserTestUtils.browserLoaded(browser);
+
+ await SpecialPowers.spawn(browser, [], async () => {
+ Assert.equal(content.location.href, "about:blank", "Got right URL");
+ Assert.equal(
+ content.document.location.href,
+ "about:blank",
+ "Got right URL"
+ );
+ });
+ BrowserTestUtils.removeTab(gBrowser.selectedTab);
+ }
+});
diff --git a/browser/components/newtab/test/browser/browser_open_tab_focus.js b/browser/components/newtab/test/browser/browser_open_tab_focus.js
new file mode 100644
index 0000000000..5eea955260
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_open_tab_focus.js
@@ -0,0 +1,37 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+add_task(async function test_open_tab_focus() {
+ await setTestTopSites();
+ let tab = await BrowserTestUtils.openNewForegroundTab(
+ gBrowser,
+ "about:newtab",
+ false
+ );
+ // Specially wait for potentially preloaded browsers
+ let browser = tab.linkedBrowser;
+ await waitForPreloaded(browser);
+ // Wait for React to render something
+ await SpecialPowers.spawn(browser, [], async () => {
+ await ContentTaskUtils.waitForCondition(() =>
+ content.document.querySelector(".top-sites-list .top-site-button .title")
+ );
+ });
+
+ await BrowserTestUtils.synthesizeMouse(
+ `.top-sites-list .top-site-button .title`,
+ 2,
+ 2,
+ { accelKey: true },
+ browser
+ );
+
+ ok(
+ gBrowser.selectedTab === tab,
+ "The original tab is still the selected tab"
+ );
+ BrowserTestUtils.removeTab(gBrowser.tabs[2]); // example.org tab
+ BrowserTestUtils.removeTab(tab); // The original tab
+});
diff --git a/browser/components/newtab/test/browser/browser_topsites_contextMenu_options.js b/browser/components/newtab/test/browser/browser_topsites_contextMenu_options.js
new file mode 100644
index 0000000000..4044c617d5
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_topsites_contextMenu_options.js
@@ -0,0 +1,129 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+test_newtab({
+ before: setDefaultTopSites,
+ // Test verifies the menu options for a default top site.
+ test: async function defaultTopSites_menuOptions() {
+ const siteSelector = ".top-site-outer:not(.search-shortcut, .placeholder)";
+ await ContentTaskUtils.waitForCondition(
+ () => content.document.querySelector(siteSelector),
+ "Topsite tippytop icon not found"
+ );
+
+ const contextMenuItems = await content.openContextMenuAndGetOptions(
+ siteSelector
+ );
+ const contextMenuItemsText = contextMenuItems.map(v => v.textContent);
+
+ Assert.equal(
+ contextMenuItemsText.length,
+ 5,
+ "Number of options is correct"
+ );
+
+ const expectedItemsText = [
+ "Pin",
+ "Edit",
+ "Open in a New Window",
+ "Open in a New Private Window",
+ "Dismiss",
+ ];
+
+ for (let i = 0; i < contextMenuItemsText.length; i++) {
+ Assert.equal(
+ contextMenuItemsText[i],
+ expectedItemsText[i],
+ "Name option is correct"
+ );
+ }
+ },
+});
+
+test_newtab({
+ before: setDefaultTopSites,
+ // Test verifies that the next top site in queue replaces a dismissed top site.
+ test: async function defaultTopSites_dismiss() {
+ const siteSelector = ".top-site-outer:not(.search-shortcut, .placeholder)";
+ await ContentTaskUtils.waitForCondition(
+ () => content.document.querySelector(siteSelector),
+ "Topsite tippytop icon not found"
+ );
+
+ // Don't count search topsites
+ const defaultTopSitesNumber = content.document.querySelectorAll(
+ siteSelector
+ ).length;
+ Assert.equal(defaultTopSitesNumber, 5, "5 top sites are loaded by default");
+
+ // Skip the search topsites select the second default topsite
+ const secondTopSite = content.document
+ .querySelectorAll(siteSelector)[1]
+ .getAttribute("href");
+
+ const contextMenuItems = await content.openContextMenuAndGetOptions(
+ siteSelector
+ );
+ Assert.equal(
+ contextMenuItems[4].textContent,
+ "Dismiss",
+ "'Dismiss' is the 5th item in the context menu list"
+ );
+
+ contextMenuItems[4].querySelector("button").click();
+
+ // Wait for the topsite to be dismissed and the second one to replace it
+ await ContentTaskUtils.waitForCondition(
+ () =>
+ content.document.querySelector(siteSelector).getAttribute("href") ===
+ secondTopSite,
+ "First default topsite was dismissed"
+ );
+
+ await ContentTaskUtils.waitForCondition(
+ () => content.document.querySelectorAll(siteSelector).length === 4,
+ "4 top sites are displayed after one of them is dismissed"
+ );
+ },
+ async after() {
+ await new Promise(resolve => NewTabUtils.undoAll(resolve));
+ },
+});
+
+test_newtab({
+ before: setDefaultTopSites,
+ test: async function searchTopSites_dismiss() {
+ const siteSelector = ".search-shortcut";
+ await ContentTaskUtils.waitForCondition(
+ () => content.document.querySelectorAll(siteSelector).length === 1,
+ "1 search topsites is loaded by default"
+ );
+
+ const contextMenuItems = await content.openContextMenuAndGetOptions(
+ siteSelector
+ );
+ is(
+ contextMenuItems.length,
+ 2,
+ "Search TopSites should only have Unpin and Dismiss"
+ );
+
+ // Unpin
+ contextMenuItems[0].querySelector("button").click();
+
+ await ContentTaskUtils.waitForCondition(
+ () => content.document.querySelectorAll(siteSelector).length === 1,
+ "1 search topsite displayed after we unpin the other one"
+ );
+ },
+ after: () => {
+ // Required for multiple test runs in the same browser, pref is used to
+ // prevent pinning the same search topsite twice
+ Services.prefs.clearUserPref(
+ "browser.newtabpage.activity-stream.improvesearch.topSiteSearchShortcuts.havePinned"
+ );
+ },
+});
diff --git a/browser/components/newtab/test/browser/browser_topsites_section.js b/browser/components/newtab/test/browser/browser_topsites_section.js
new file mode 100644
index 0000000000..a4f1b24c0a
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_topsites_section.js
@@ -0,0 +1,213 @@
+"use strict";
+
+// Check TopSites edit modal and overlay show up.
+test_newtab(
+ // it should be able to click the topsites add button to reveal the add top site modal and overlay.
+ function topsites_edit() {
+ // Open the section context menu.
+ content.document
+ .querySelector(".top-sites .section-top-bar .context-menu-button")
+ .click();
+ let contextMenu = content.document.querySelector(
+ ".top-sites .section-top-bar .context-menu"
+ );
+ ok(contextMenu, "Should find a visible topsite context menu");
+
+ const topsitesAddBtn = content.document.querySelector(
+ ".top-sites .context-menu-item button"
+ );
+ topsitesAddBtn.click();
+
+ let found = content.document.querySelector(".topsite-form");
+ ok(found && !found.hidden, "Should find a visible topsite form");
+
+ found = content.document.querySelector(".modalOverlayOuter");
+ ok(found && !found.hidden, "Should find a visible overlay");
+ }
+);
+
+// Test pin/unpin context menu options.
+test_newtab({
+ before: setDefaultTopSites,
+ // it should pin the website when we click the first option of the topsite context menu.
+ test: async function topsites_pin_unpin() {
+ const siteSelector = ".top-site-outer:not(.search-shortcut, .placeholder)";
+ await ContentTaskUtils.waitForCondition(
+ () => content.document.querySelector(siteSelector),
+ "Topsite tippytop icon not found"
+ );
+ // There are only topsites on the page, the selector with find the first topsite menu button.
+ let topsiteEl = content.document.querySelector(siteSelector);
+ let topsiteContextBtn = topsiteEl.querySelector(".context-menu-button");
+ topsiteContextBtn.click();
+
+ await ContentTaskUtils.waitForCondition(
+ () => topsiteEl.querySelector(".top-sites-list .context-menu"),
+ "No context menu found"
+ );
+
+ let contextMenu = topsiteEl.querySelector(".top-sites-list .context-menu");
+ ok(contextMenu, "Should find a topsite context menu");
+
+ const pinUnpinTopsiteBtn = contextMenu.querySelector(
+ ".top-sites .context-menu-item button"
+ );
+ // Pin the topsite.
+ pinUnpinTopsiteBtn.click();
+
+ // Need to wait for pin action.
+ await ContentTaskUtils.waitForCondition(
+ () => topsiteEl.querySelector(".icon-pin-small"),
+ "No pinned icon found"
+ );
+
+ let pinnedIcon = topsiteEl.querySelectorAll(".icon-pin-small").length;
+ is(pinnedIcon, 1, "should find 1 pinned topsite");
+
+ // Unpin the topsite.
+ topsiteContextBtn = topsiteEl.querySelector(".context-menu-button");
+ ok(topsiteContextBtn, "Should find a context menu button");
+ topsiteContextBtn.click();
+ topsiteEl.querySelector(".context-menu-item button").click();
+
+ // Need to wait for unpin action.
+ await ContentTaskUtils.waitForCondition(
+ () => !topsiteEl.querySelector(".icon-pin-small"),
+ "Topsite should be unpinned"
+ );
+ },
+});
+
+// Check Topsites add
+test_newtab({
+ before: setDefaultTopSites,
+ // it should be able to click the topsites edit button to reveal the edit topsites modal and overlay.
+ test: async function topsites_add() {
+ let nativeInputValueSetter = Object.getOwnPropertyDescriptor(
+ content.window.HTMLInputElement.prototype,
+ "value"
+ ).set;
+ let event = new content.Event("input", { bubbles: true });
+
+ // Find the add topsites button
+ content.document
+ .querySelector(".top-sites .section-top-bar .context-menu-button")
+ .click();
+ let contextMenu = content.document.querySelector(
+ ".top-sites .section-top-bar .context-menu"
+ );
+ ok(contextMenu, "Should find a visible topsite context menu");
+
+ const topsitesAddBtn = content.document.querySelector(
+ ".top-sites .context-menu-item button"
+ );
+ topsitesAddBtn.click();
+
+ let found = content.document.querySelector(".modalOverlayOuter");
+ ok(found && !found.hidden, "Should find a visible overlay");
+
+ // Write field title
+ let fieldTitle = content.document.querySelector(".field input");
+ ok(fieldTitle && !fieldTitle.hidden, "Should find field title input");
+
+ nativeInputValueSetter.call(fieldTitle, "Bugzilla");
+ fieldTitle.dispatchEvent(event);
+ is(fieldTitle.value, "Bugzilla", "The field title should match");
+
+ // Write field url
+ let fieldURL = content.document.querySelector(".field.url input");
+ ok(fieldURL && !fieldURL.hidden, "Should find field url input");
+
+ nativeInputValueSetter.call(fieldURL, "https://bugzilla.mozilla.org");
+ fieldURL.dispatchEvent(event);
+ is(
+ fieldURL.value,
+ "https://bugzilla.mozilla.org",
+ "The field url should match"
+ );
+
+ // Click the "Add" button
+ let addBtn = content.document.querySelector(".done");
+ addBtn.click();
+
+ // Wait for Topsite to be populated
+ await ContentTaskUtils.waitForCondition(
+ () =>
+ content.document
+ .querySelector(".top-site-outer:first-child a")
+ .getAttribute("href") === "https://bugzilla.mozilla.org",
+ "No Topsite found"
+ );
+
+ // Remove topsite after test is complete
+ let topsiteContextBtn = content.document.querySelector(
+ ".top-sites-list .context-menu-button"
+ );
+ topsiteContextBtn.click();
+ await ContentTaskUtils.waitForCondition(
+ () => content.document.querySelector(".top-sites-list .context-menu"),
+ "No context menu found"
+ );
+
+ let contextMen = content.document.querySelector(
+ ".top-sites-list .context-menu"
+ );
+
+ const dismissBtn = contextMen.querySelector(
+ ".top-sites .context-menu-item button .icon-dismiss"
+ );
+ dismissBtn.click();
+
+ // Wait for Topsite to be removed
+ await ContentTaskUtils.waitForCondition(
+ () =>
+ content.document
+ .querySelector(".top-site-outer:first-child a")
+ .getAttribute("href") !== "https://bugzilla.mozilla.org",
+ "Topsite not removed"
+ );
+ },
+});
+
+test_newtab({
+ before: setDefaultTopSites,
+ test: async function test_search_topsite_keyword() {
+ await ContentTaskUtils.waitForCondition(
+ () => content.document.querySelector(".search-shortcut .title.pinned"),
+ "Wait for pinned search topsites"
+ );
+
+ const searchTopSites = content.document.querySelectorAll(".title.pinned");
+ ok(
+ searchTopSites.length >= 1,
+ "There should be at least 2 search topsites"
+ );
+
+ searchTopSites[0].click();
+
+ return searchTopSites[0].innerText.trim();
+ },
+ async after(searchTopSiteTag) {
+ ok(
+ gURLBar.focused,
+ "We clicked a search topsite the focus should be in location bar"
+ );
+ let engine = await Services.search.getEngineByAlias(searchTopSiteTag);
+
+ // We don't use UrlbarTestUtils.assertSearchMode here since the newtab
+ // testing scope doesn't integrate well with UrlbarTestUtils.
+ Assert.deepEqual(
+ gURLBar.searchMode,
+ {
+ engineName: engine.name,
+ entry: "topsites_newtab",
+ isPreview: false,
+ },
+ "The Urlbar is in search mode."
+ );
+ ok(
+ gURLBar.hasAttribute("searchmode"),
+ "The Urlbar has the searchmode attribute."
+ );
+ },
+});
diff --git a/browser/components/newtab/test/browser/browser_trigger_listeners.js b/browser/components/newtab/test/browser/browser_trigger_listeners.js
new file mode 100644
index 0000000000..c10eafa326
--- /dev/null
+++ b/browser/components/newtab/test/browser/browser_trigger_listeners.js
@@ -0,0 +1,65 @@
+const { ASRouterTriggerListeners } = ChromeUtils.import(
+ "resource://activity-stream/lib/ASRouterTriggerListeners.jsm"
+);
+
+add_task(async function setup() {
+ registerCleanupFunction(() => {
+ const trigger = ASRouterTriggerListeners.get("openURL");
+ trigger.uninit();
+ });
+});
+
+add_task(async function test_openURL_visit_counter() {
+ const trigger = ASRouterTriggerListeners.get("openURL");
+ const stub = sinon.stub();
+ trigger.uninit();
+
+ trigger.init(stub, ["example.com"]);
+
+ await waitForUrlLoad("about:blank");
+ await waitForUrlLoad("https://example.com/");
+ await waitForUrlLoad("about:blank");
+ await waitForUrlLoad("http://example.com/");
+ await waitForUrlLoad("about:blank");
+ await waitForUrlLoad("http://example.com/");
+
+ Assert.equal(stub.callCount, 3, "Stub called 3 times for example.com host");
+ Assert.equal(
+ stub.firstCall.args[1].context.visitsCount,
+ 1,
+ "First call should have count 1"
+ );
+ Assert.equal(
+ stub.thirdCall.args[1].context.visitsCount,
+ 2,
+ "Third call should have count 2 for http://example.com"
+ );
+});
+
+add_task(async function test_openURL_visit_counter_withPattern() {
+ const trigger = ASRouterTriggerListeners.get("openURL");
+ const stub = sinon.stub();
+ trigger.uninit();
+
+ // Match any valid URL
+ trigger.init(stub, [], ["*://*/*"]);
+
+ await waitForUrlLoad("about:blank");
+ await waitForUrlLoad("https://example.com/");
+ await waitForUrlLoad("about:blank");
+ await waitForUrlLoad("http://example.com/");
+ await waitForUrlLoad("about:blank");
+ await waitForUrlLoad("http://example.com/");
+
+ Assert.equal(stub.callCount, 3, "Stub called 3 times for example.com host");
+ Assert.equal(
+ stub.firstCall.args[1].context.visitsCount,
+ 1,
+ "First call should have count 1"
+ );
+ Assert.equal(
+ stub.thirdCall.args[1].context.visitsCount,
+ 2,
+ "Third call should have count 2 for http://example.com"
+ );
+});
diff --git a/browser/components/newtab/test/browser/ds_layout.json b/browser/components/newtab/test/browser/ds_layout.json
new file mode 100644
index 0000000000..54a2216f84
--- /dev/null
+++ b/browser/components/newtab/test/browser/ds_layout.json
@@ -0,0 +1,89 @@
+{
+ "spocs": {
+ "url": ""
+ },
+ "layout": [
+ {
+ "width": 12,
+ "components": [
+ {
+ "type": "TopSites",
+ "header": {
+ "title": "Top Sites"
+ },
+ "properties": null
+ },
+ {
+ "type": "Message",
+ "header": {
+ "title": "Recommended by Pocket",
+ "subtitle": "",
+ "link_text": "How it works",
+ "link_url": "https://getpocket.com/firefox/new_tab_learn_more",
+ "icon": "chrome://activity-stream/content/data/content/assets/glyph-pocket-16.svg"
+ },
+ "properties": null,
+ "styles": {
+ ".ds-message": "margin-bottom: -20px"
+ }
+ },
+ {
+ "type": "CardGrid",
+ "properties": {
+ "items": 3
+ },
+ "header": {
+ "title": ""
+ },
+ "feed": {
+ "embed_reference": null,
+ "url": "https://example.com/browser/browser/components/newtab/test/browser/topstories.json"
+ },
+ "spocs": {
+ "probability": 1,
+ "positions": [
+ {
+ "index": 2
+ }
+ ]
+ }
+ },
+ {
+ "type": "Navigation",
+ "properties": {
+ "alignment": "left-align",
+ "links": [
+ {
+ "name": "Must Reads",
+ "url": "https://getpocket.com/explore/must-reads?src=fx_new_tab"
+ },
+ {
+ "name": "Productivity",
+ "url": "https://getpocket.com/explore/productivity?src=fx_new_tab"
+ },
+ {
+ "name": "Health",
+ "url": "https://getpocket.com/explore/health?src=fx_new_tab"
+ },
+ {
+ "name": "Finance",
+ "url": "https://getpocket.com/explore/finance?src=fx_new_tab"
+ },
+ {
+ "name": "Technology",
+ "url": "https://getpocket.com/explore/technology?src=fx_new_tab"
+ },
+ {
+ "name": "More Recommendations ›",
+ "url": "https://getpocket.com/explore/trending?src=fx_new_tab"
+ }
+ ]
+ }
+ }
+ ]
+ }
+ ],
+ "feeds": {},
+ "error": 0,
+ "status": 1
+}
diff --git a/browser/components/newtab/test/browser/head.js b/browser/components/newtab/test/browser/head.js
new file mode 100644
index 0000000000..fa1dd25dd1
--- /dev/null
+++ b/browser/components/newtab/test/browser/head.js
@@ -0,0 +1,256 @@
+"use strict";
+
+ChromeUtils.defineModuleGetter(
+ this,
+ "ObjectUtils",
+ "resource://gre/modules/ObjectUtils.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "PlacesTestUtils",
+ "resource://testing-common/PlacesTestUtils.jsm"
+);
+ChromeUtils.defineModuleGetter(
+ this,
+ "QueryCache",
+ "resource://activity-stream/lib/ASRouterTargeting.jsm"
+);
+
+// We import sinon here to make it available across all mochitest test files
+// eslint-disable-next-line no-unused-vars
+const { sinon } = ChromeUtils.import("resource://testing-common/Sinon.jsm");
+
+function popPrefs() {
+ return SpecialPowers.popPrefEnv();
+}
+function pushPrefs(...prefs) {
+ return SpecialPowers.pushPrefEnv({ set: prefs });
+}
+
+// Toggle the feed off and on as a workaround to read the new prefs.
+async function toggleTopsitesPref() {
+ await pushPrefs([
+ "browser.newtabpage.activity-stream.feeds.system.topsites",
+ false,
+ ]);
+ await pushPrefs([
+ "browser.newtabpage.activity-stream.feeds.system.topsites",
+ true,
+ ]);
+}
+
+// eslint-disable-next-line no-unused-vars
+async function setDefaultTopSites() {
+ // The pref for TopSites is empty by default.
+ await pushPrefs([
+ "browser.newtabpage.activity-stream.default.sites",
+ "https://www.youtube.com/,https://www.facebook.com/,https://www.amazon.com/,https://www.reddit.com/,https://www.wikipedia.org/,https://twitter.com/",
+ ]);
+ await toggleTopsitesPref();
+ await pushPrefs([
+ "browser.newtabpage.activity-stream.improvesearch.topSiteSearchShortcuts",
+ true,
+ ]);
+}
+
+// eslint-disable-next-line no-unused-vars
+async function setTestTopSites() {
+ await pushPrefs([
+ "browser.newtabpage.activity-stream.improvesearch.topSiteSearchShortcuts",
+ false,
+ ]);
+ // The pref for TopSites is empty by default.
+ // Using a topsite with example.com allows us to open the topsite without a network request.
+ await pushPrefs([
+ "browser.newtabpage.activity-stream.default.sites",
+ "https://example.com/",
+ ]);
+ await toggleTopsitesPref();
+}
+
+// eslint-disable-next-line no-unused-vars
+async function clearHistoryAndBookmarks() {
+ await PlacesUtils.bookmarks.eraseEverything();
+ await PlacesUtils.history.clear();
+ QueryCache.expireAll();
+}
+
+/**
+ * Helper to wait for potentially preloaded browsers to "load" where a preloaded
+ * page has already loaded and won't trigger "load", and a "load"ed page might
+ * not necessarily have had all its javascript/render logic executed.
+ */
+async function waitForPreloaded(browser) {
+ let readyState = await ContentTask.spawn(
+ browser,
+ null,
+ () => content.document.readyState
+ );
+ if (readyState !== "complete") {
+ await BrowserTestUtils.browserLoaded(browser);
+ }
+}
+
+/**
+ * Helper function to navigate and wait for page to load
+ * https://searchfox.org/mozilla-central/rev/b2716c233e9b4398fc5923cbe150e7f83c7c6c5b/testing/mochitest/BrowserTestUtils/BrowserTestUtils.jsm#383
+ */
+// eslint-disable-next-line no-unused-vars
+async function waitForUrlLoad(url) {
+ let browser = gBrowser.selectedBrowser;
+ BrowserTestUtils.loadURI(browser, url);
+ await BrowserTestUtils.browserLoaded(browser, false, url);
+}
+
+/**
+ * Helper to force the HighlightsFeed to update.
+ */
+function refreshHighlightsFeed() {
+ // Toggling the pref will clear the feed cache and force a places query.
+ Services.prefs.setBoolPref(
+ "browser.newtabpage.activity-stream.feeds.section.highlights",
+ false
+ );
+ Services.prefs.setBoolPref(
+ "browser.newtabpage.activity-stream.feeds.section.highlights",
+ true
+ );
+}
+
+/**
+ * Helper to populate the Highlights section with bookmark cards.
+ * @param count Number of items to add.
+ */
+// eslint-disable-next-line no-unused-vars
+async function addHighlightsBookmarks(count) {
+ const bookmarks = new Array(count).fill(null).map((entry, i) => ({
+ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
+ title: "foo",
+ url: `https://mozilla${i}.com/nowNew`,
+ }));
+
+ for (let placeInfo of bookmarks) {
+ await PlacesUtils.bookmarks.insert(placeInfo);
+ // Bookmarks need at least one visit to show up as highlights.
+ await PlacesTestUtils.addVisits(placeInfo.url);
+ }
+
+ // Force HighlightsFeed to make a request for the new items.
+ refreshHighlightsFeed();
+}
+
+/**
+ * Helper to add various helpers to the content process by injecting variables
+ * and functions to the `content` global.
+ */
+function addContentHelpers() {
+ const { document } = content;
+ Object.assign(content, {
+ /**
+ * Click the context menu button for an item and get its options list.
+ *
+ * @param selector {String} Selector to get an item (e.g., top site, card)
+ * @return {Array} The nodes for the options.
+ */
+ async openContextMenuAndGetOptions(selector) {
+ const item = document.querySelector(selector);
+ const contextButton = item.querySelector(".context-menu-button");
+ contextButton.click();
+ // Gives fluent-dom the time to render strings
+ await new Promise(r => content.requestAnimationFrame(r));
+
+ const contextMenu = item.querySelector(".context-menu");
+ const contextMenuList = contextMenu.querySelector(".context-menu-list");
+ return [...contextMenuList.getElementsByClassName("context-menu-item")];
+ },
+ });
+}
+
+/**
+ * Helper to run Activity Stream about:newtab test tasks in content.
+ *
+ * @param testInfo {Function|Object}
+ * {Function} This parameter will be used as if the function were called with
+ * an Object with this parameter as "test" key's value.
+ * {Object} The following keys are expected:
+ * before {Function} Optional. Runs before and returns an arg for "test"
+ * test {Function} The test to run in the about:newtab content task taking
+ * an arg from "before" and returns a result to "after"
+ * after {Function} Optional. Runs after and with the result of "test"
+ * @param browserURL {optional String}
+ * {String} This parameter is used to explicitly specify URL opened in new tab
+ */
+// eslint-disable-next-line no-unused-vars
+function test_newtab(testInfo, browserURL = "about:newtab") {
+ // Extract any test parts or default to just the single content task
+ let { before, test: contentTask, after } = testInfo;
+ if (!before) {
+ before = () => ({});
+ }
+ if (!contentTask) {
+ contentTask = testInfo;
+ }
+ if (!after) {
+ after = () => {};
+ }
+
+ // Helper to push prefs for just this test and pop them when done
+ let needPopPrefs = false;
+ let scopedPushPrefs = async (...args) => {
+ needPopPrefs = true;
+ await pushPrefs(...args);
+ };
+ let scopedPopPrefs = async () => {
+ if (needPopPrefs) {
+ await popPrefs();
+ }
+ };
+
+ // Make the test task with optional before/after and content task to run in a
+ // new tab that opens and closes.
+ let testTask = async () => {
+ // Open about:newtab without using the default load listener
+ let tab = await BrowserTestUtils.openNewForegroundTab(
+ gBrowser,
+ browserURL,
+ false
+ );
+
+ // Specially wait for potentially preloaded browsers
+ let browser = tab.linkedBrowser;
+ await waitForPreloaded(browser);
+
+ // Add shared helpers to the content process
+ SpecialPowers.spawn(browser, [], addContentHelpers);
+
+ // Wait for React to render something
+ await BrowserTestUtils.waitForCondition(
+ () =>
+ SpecialPowers.spawn(
+ browser,
+ [],
+ () => content.document.getElementById("root").children.length
+ ),
+ "Should render activity stream content"
+ );
+
+ // Chain together before -> contentTask -> after data passing
+ try {
+ let contentArg = await before({ pushPrefs: scopedPushPrefs, tab });
+ let contentResult = await SpecialPowers.spawn(
+ browser,
+ [contentArg],
+ contentTask
+ );
+ await after(contentResult);
+ } finally {
+ // Clean up for next tests
+ await scopedPopPrefs();
+ BrowserTestUtils.removeTab(tab);
+ }
+ };
+
+ // Copy the name of the content task to identify the test
+ Object.defineProperty(testTask, "name", { value: contentTask.name });
+ add_task(testTask);
+}
diff --git a/browser/components/newtab/test/browser/red_page.html b/browser/components/newtab/test/browser/red_page.html
new file mode 100644
index 0000000000..733a1f0d4a
--- /dev/null
+++ b/browser/components/newtab/test/browser/red_page.html
@@ -0,0 +1,6 @@
+<html>
+ <head>
+ <meta charset="utf-8">
+ </head>
+ <body style="background-color: red" />
+</html>
diff --git a/browser/components/newtab/test/browser/snippet.json b/browser/components/newtab/test/browser/snippet.json
new file mode 100644
index 0000000000..7b92288b0f
--- /dev/null
+++ b/browser/components/newtab/test/browser/snippet.json
@@ -0,0 +1,25 @@
+{
+ "messages": [
+ {
+ "weight": 50,
+ "id": "10533",
+ "template": "simple_snippet",
+ "template_version": "1.0.0",
+ "content": {
+ "icon": "",
+ "text": "On January 30th Nightly will introduce dedicated profiles, making it simpler to run different installations of Firefox side by side. <link0> Learn what this means for you</link0>.",
+ "tall": false,
+ "do_not_autoblock": false,
+ "links": {
+ "link0": {
+ "url": "https://support.mozilla.org/kb/dedicated-profiles-firefox-installation/?utm_source=desktop-snippet&utm_medium=snippet&utm_campaign=nightly_profile_management&utm_term=10533&utm_content=nightly"
+ }
+ }
+ },
+ "campaign": "nightly-profile-management",
+ "targeting": "true",
+ "provider_url": "https://snippets.cdn.mozilla.net/6/Firefox/66.0a1/20190122215349/Darwin_x86_64-gcc3/en-US/default/Darwin%2018.0.0/default/default/",
+ "provider": "snippets"
+ }
+ ]
+}
diff --git a/browser/components/newtab/test/browser/snippet_below_search_test.json b/browser/components/newtab/test/browser/snippet_below_search_test.json
new file mode 100644
index 0000000000..935ef9d6c2
--- /dev/null
+++ b/browser/components/newtab/test/browser/snippet_below_search_test.json
@@ -0,0 +1,20 @@
+{
+ "messages": [
+ {
+ "id": "SIMPLE_BELOW_SEARCH_TEST_1",
+ "template": "simple_below_search_snippet",
+ "content": {
+ "icon": "chrome://branding/content/icon64.png",
+ "icon_dark_theme": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAQAAAC1+jfqAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAAmJLR0QA/4ePzL8AAAAHdElNRQfjBQ8QDifrKGc/AAABf0lEQVQoz4WRO08UUQCFvztzd1AgG9jRgGwkhEoMIYGSygYt+A00tpZGY0jYxAJKEwkNjX9AK2xACx4dhFiQQCiMMRr2kYXdnQcz7L0z91qAMVac6hTfSU7OgVsk/prtyfSNfRb7ge2cd7dmVucP/wM2lwqVqoyICahRx9Nz71+8AnAAvlTct+dSYDBYcgJ+Fj68XFu/AfamnIoWFoHFYrAUuYMSn55/fAIOxIs1t4MhQpNxRYsUD0ld7r8DCfZph4QecrqkhCREgMLSeISQkAy0UBgE0CYgIkeRA9HdsCQhpEGCxichpItHigEcPH4XJLRbTf8STY0iiiuu60Ifxexx04F0N+aCgJCAhPQmD/cp/RC5A79WvUyhUHSIidAIoESv9VfAhW9n8+XqTCoyMsz1cviMMrGz9BrjAuboYHZajyXCInEocI8yvccbC+0muABanR4/tONjQz3DzgNKtj9sfv66XD9B/3tT9g/akb7h0bJwzxqqmlRHLr4rLPwBlYWoYj77l2AAAAAldEVYdGRhdGU6Y3JlYXRlADIwMTktMDUtMTVUMTY6MTQ6MzkrMDA6MDD5/4XBAAAAJXRFWHRkYXRlOm1vZGlmeQAyMDE5LTA1LTE1VDE2OjE0OjM5KzAwOjAwiKI9fQAAAABJRU5ErkJggg==",
+ "text": "Securely store passwords, bookmarks, and more with a Firefox Account. <syncLink>Sign up</syncLink>",
+ "links": {
+ "syncLink": {
+ "url": "https://www.mozilla.org/en-US/firefox/accounts"
+ }
+ },
+ "block_button_text": "Block"
+ },
+ "targeting": "true"
+ }
+ ]
+}
diff --git a/browser/components/newtab/test/browser/snippet_simple_test.json b/browser/components/newtab/test/browser/snippet_simple_test.json
new file mode 100644
index 0000000000..585e78f8fd
--- /dev/null
+++ b/browser/components/newtab/test/browser/snippet_simple_test.json
@@ -0,0 +1,24 @@
+{
+ "messages": [
+ {
+ "id": "SIMPLE_TEST_1",
+ "template": "simple_snippet",
+ "campaign": "test_campaign_blocking",
+ "content": {
+ "icon": "chrome://branding/content/icon64.png",
+ "icon_dark_theme": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAQAAAC1+jfqAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAAmJLR0QA/4ePzL8AAAAHdElNRQfjBQ8QDifrKGc/AAABf0lEQVQoz4WRO08UUQCFvztzd1AgG9jRgGwkhEoMIYGSygYt+A00tpZGY0jYxAJKEwkNjX9AK2xACx4dhFiQQCiMMRr2kYXdnQcz7L0z91qAMVac6hTfSU7OgVsk/prtyfSNfRb7ge2cd7dmVucP/wM2lwqVqoyICahRx9Nz71+8AnAAvlTct+dSYDBYcgJ+Fj68XFu/AfamnIoWFoHFYrAUuYMSn55/fAIOxIs1t4MhQpNxRYsUD0ld7r8DCfZph4QecrqkhCREgMLSeISQkAy0UBgE0CYgIkeRA9HdsCQhpEGCxichpItHigEcPH4XJLRbTf8STY0iiiuu60Ifxexx04F0N+aCgJCAhPQmD/cp/RC5A79WvUyhUHSIidAIoESv9VfAhW9n8+XqTCoyMsz1cviMMrGz9BrjAuboYHZajyXCInEocI8yvccbC+0muABanR4/tONjQz3DzgNKtj9sfv66XD9B/3tT9g/akb7h0bJwzxqqmlRHLr4rLPwBlYWoYj77l2AAAAAldEVYdGRhdGU6Y3JlYXRlADIwMTktMDUtMTVUMTY6MTQ6MzkrMDA6MDD5/4XBAAAAJXRFWHRkYXRlOm1vZGlmeQAyMDE5LTA1LTE1VDE2OjE0OjM5KzAwOjAwiKI9fQAAAABJRU5ErkJggg==",
+ "title": "Firefox Account!",
+ "title_icon": "chrome://branding/content/icon16.png",
+ "title_icon_dark_theme": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAQAAAC1+jfqAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAAmJLR0QA/4ePzL8AAAAHdElNRQfjBQ8QDifrKGc/AAABf0lEQVQoz4WRO08UUQCFvztzd1AgG9jRgGwkhEoMIYGSygYt+A00tpZGY0jYxAJKEwkNjX9AK2xACx4dhFiQQCiMMRr2kYXdnQcz7L0z91qAMVac6hTfSU7OgVsk/prtyfSNfRb7ge2cd7dmVucP/wM2lwqVqoyICahRx9Nz71+8AnAAvlTct+dSYDBYcgJ+Fj68XFu/AfamnIoWFoHFYrAUuYMSn55/fAIOxIs1t4MhQpNxRYsUD0ld7r8DCfZph4QecrqkhCREgMLSeISQkAy0UBgE0CYgIkeRA9HdsCQhpEGCxichpItHigEcPH4XJLRbTf8STY0iiiuu60Ifxexx04F0N+aCgJCAhPQmD/cp/RC5A79WvUyhUHSIidAIoESv9VfAhW9n8+XqTCoyMsz1cviMMrGz9BrjAuboYHZajyXCInEocI8yvccbC+0muABanR4/tONjQz3DzgNKtj9sfv66XD9B/3tT9g/akb7h0bJwzxqqmlRHLr4rLPwBlYWoYj77l2AAAAAldEVYdGRhdGU6Y3JlYXRlADIwMTktMDUtMTVUMTY6MTQ6MzkrMDA6MDD5/4XBAAAAJXRFWHRkYXRlOm1vZGlmeQAyMDE5LTA1LTE1VDE2OjE0OjM5KzAwOjAwiKI9fQAAAABJRU5ErkJggg==",
+ "text": "<syncLink>Sync it, link it, take it with you</syncLink>. All this and more with a Firefox Account.",
+ "links": {
+ "syncLink": {
+ "url": "https://www.mozilla.org/en-US/firefox/accounts"
+ }
+ },
+ "block_button_text": "Block"
+ },
+ "targeting": "true"
+ }
+ ]
+}
diff --git a/browser/components/newtab/test/browser/topstories.json b/browser/components/newtab/test/browser/topstories.json
new file mode 100644
index 0000000000..6cecd94028
--- /dev/null
+++ b/browser/components/newtab/test/browser/topstories.json
@@ -0,0 +1 @@
+{"status":1,"settings":{"spocsPerNewTabs":0.5,"domainAffinityParameterSets":{"default":{"recencyFactor":0.5,"frequencyFactor":0.5,"combinedDomainFactor":0.5,"perfectFrequencyVisits":10,"perfectCombinedDomainScore":2,"multiDomainBoost":0,"itemScoreFactor":1},"fully-personalized":{"recencyFactor":0.5,"frequencyFactor":0.5,"combinedDomainFactor":0.5,"perfectFrequencyVisits":10,"perfectCombinedDomainScore":2,"itemScoreFactor":0.01,"multiDomainBoost":0}},"timeSegments":[{"id":"week","startTime":604800,"endTime":0,"weightPosition":1},{"id":"month","startTime":2592000,"endTime":604800,"weightPosition":0.5}],"recsExpireTime":5400,"version":"2c2aa06dac65ddb647d8902aaa60263c8e119ff2"},"spocs":[],"recommendations":[{"id":53093,"url":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAA/UlEQVR4nO3RMQ0AMAzAsPIn3d5DsBw2gkiZJWV+B/AyJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQmAP4K6zWNUjE4wAAAABJRU5ErkJggg==","domain":"bbc.com","title":"Why vegan junk food may be even worse for your health","excerpt":"While we might switch to a plant-based diet with the best intentions, the unseen risks of vegan fast foods might not show up for years.","image_src":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAA/UlEQVR4nO3RMQ0AMAzAsPIn3d5DsBw2gkiZJWV+B/AyJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQmAP4K6zWNUjE4wAAAABJRU5ErkJggg==","published_timestamp":"1580277600","engagement":"","parameter_set":"default","domain_affinities":{},"item_score":1}]}
diff --git a/browser/components/newtab/test/schemas/pings.js b/browser/components/newtab/test/schemas/pings.js
new file mode 100644
index 0000000000..f0644f4185
--- /dev/null
+++ b/browser/components/newtab/test/schemas/pings.js
@@ -0,0 +1,317 @@
+import { CONTENT_MESSAGE_TYPE, MAIN_MESSAGE_TYPE } from "common/Actions.jsm";
+import Joi from "joi-browser";
+
+export const baseKeys = {
+ // client_id will be set by PingCentre if it doesn't exist.
+ client_id: Joi.string().optional(),
+ addon_version: Joi.string().required(),
+ locale: Joi.string().required(),
+ session_id: Joi.string(),
+ page: Joi.valid([
+ "about:home",
+ "about:newtab",
+ "about:welcome",
+ "both",
+ "unknown",
+ ]),
+ user_prefs: Joi.number()
+ .integer()
+ .required(),
+};
+
+export const BasePing = Joi.object()
+ .keys(baseKeys)
+ .options({ allowUnknown: true });
+
+export const eventsTelemetryExtraKeys = Joi.object()
+ .keys({
+ session_id: baseKeys.session_id.required(),
+ page: baseKeys.page.required(),
+ addon_version: baseKeys.addon_version.required(),
+ user_prefs: baseKeys.user_prefs.required(),
+ action_position: Joi.string().optional(),
+ })
+ .options({ allowUnknown: false });
+
+export const UserEventPing = Joi.object().keys(
+ Object.assign({}, baseKeys, {
+ session_id: baseKeys.session_id.required(),
+ page: baseKeys.page.required(),
+ source: Joi.string(),
+ event: Joi.string().required(),
+ action: Joi.valid("activity_stream_user_event").required(),
+ metadata_source: Joi.string(),
+ highlight_type: Joi.valid(["bookmarks", "recommendation", "history"]),
+ recommender_type: Joi.string(),
+ value: Joi.object().keys({
+ newtab_url_category: Joi.string(),
+ newtab_extension_id: Joi.string(),
+ home_url_category: Joi.string(),
+ home_extension_id: Joi.string(),
+ }),
+ })
+);
+
+export const UTUserEventPing = Joi.array().items(
+ Joi.string()
+ .required()
+ .valid("activity_stream"),
+ Joi.string()
+ .required()
+ .valid("event"),
+ Joi.string()
+ .required()
+ .valid([
+ "CLICK",
+ "SEARCH",
+ "BLOCK",
+ "DELETE",
+ "DELETE_CONFIRM",
+ "DIALOG_CANCEL",
+ "DIALOG_OPEN",
+ "OPEN_NEW_WINDOW",
+ "OPEN_PRIVATE_WINDOW",
+ "OPEN_NEWTAB_PREFS",
+ "CLOSE_NEWTAB_PREFS",
+ "BOOKMARK_DELETE",
+ "BOOKMARK_ADD",
+ "PIN",
+ "UNPIN",
+ "SAVE_TO_POCKET",
+ ]),
+ Joi.string().required(),
+ eventsTelemetryExtraKeys
+);
+
+// Use this to validate actions generated from Redux
+export const UserEventAction = Joi.object().keys({
+ type: Joi.string().required(),
+ data: Joi.object()
+ .keys({
+ event: Joi.valid([
+ "CLICK",
+ "SEARCH",
+ "SEARCH_HANDOFF",
+ "BLOCK",
+ "DELETE",
+ "DELETE_CONFIRM",
+ "DIALOG_CANCEL",
+ "DIALOG_OPEN",
+ "OPEN_NEW_WINDOW",
+ "OPEN_PRIVATE_WINDOW",
+ "OPEN_NEWTAB_PREFS",
+ "CLOSE_NEWTAB_PREFS",
+ "BOOKMARK_DELETE",
+ "BOOKMARK_ADD",
+ "PIN",
+ "PREVIEW_REQUEST",
+ "UNPIN",
+ "SAVE_TO_POCKET",
+ "MENU_MOVE_UP",
+ "MENU_MOVE_DOWN",
+ "SCREENSHOT_REQUEST",
+ "MENU_REMOVE",
+ "MENU_COLLAPSE",
+ "MENU_EXPAND",
+ "MENU_MANAGE",
+ "MENU_ADD_TOPSITE",
+ "MENU_PRIVACY_NOTICE",
+ "DELETE_FROM_POCKET",
+ "ARCHIVE_FROM_POCKET",
+ "SKIPPED_SIGNIN",
+ "SUBMIT_EMAIL",
+ "SUBMIT_SIGNIN",
+ "SHOW_PRIVACY_INFO",
+ "CLICK_PRIVACY_INFO",
+ ]).required(),
+ source: Joi.valid(["TOP_SITES", "TOP_STORIES", "HIGHLIGHTS"]),
+ action_position: Joi.number().integer(),
+ value: Joi.object().keys({
+ icon_type: Joi.valid([
+ "tippytop",
+ "rich_icon",
+ "screenshot_with_icon",
+ "screenshot",
+ "no_image",
+ "custom_screenshot",
+ ]),
+ card_type: Joi.valid([
+ "bookmark",
+ "trending",
+ "pinned",
+ "pocket",
+ "search",
+ "spoc",
+ "organic",
+ ]),
+ search_vendor: Joi.valid(["google", "amazon"]),
+ has_flow_params: Joi.bool(),
+ }),
+ })
+ .required(),
+ meta: Joi.object()
+ .keys({
+ to: Joi.valid(MAIN_MESSAGE_TYPE).required(),
+ from: Joi.valid(CONTENT_MESSAGE_TYPE).required(),
+ })
+ .required(),
+});
+
+export const TileSchema = Joi.object().keys({
+ id: Joi.number()
+ .integer()
+ .required(),
+ pos: Joi.number().integer(),
+});
+
+export const ImpressionStatsPing = Joi.object().keys(
+ Object.assign({}, baseKeys, {
+ source: Joi.string().required(),
+ impression_id: Joi.string().required(),
+ tiles: Joi.array()
+ .items(TileSchema)
+ .required(),
+ click: Joi.number().integer(),
+ block: Joi.number().integer(),
+ pocket: Joi.number().integer(),
+ })
+);
+
+export const SessionPing = Joi.object().keys(
+ Object.assign({}, baseKeys, {
+ session_id: baseKeys.session_id.required(),
+ page: baseKeys.page.required(),
+ session_duration: Joi.number().integer(),
+ action: Joi.valid("activity_stream_session").required(),
+ profile_creation_date: Joi.number().integer(),
+ perf: Joi.object()
+ .keys({
+ // How long it took in ms for data to be ready for display.
+ highlights_data_late_by_ms: Joi.number().positive(),
+
+ // Timestamp of the action perceived by the user to trigger the load
+ // of this page.
+ //
+ // Not required at least for the error cases where the
+ // observer event doesn't fire
+ load_trigger_ts: Joi.number()
+ .integer()
+ .notes(["server counter", "server counter alert"]),
+
+ // What was the perceived trigger of the load action?
+ //
+ // Not required at least for the error cases where the observer event
+ // doesn't fire
+ load_trigger_type: Joi.valid([
+ "first_window_opened",
+ "menu_plus_or_keyboard",
+ "unexpected",
+ ])
+ .notes(["server counter", "server counter alert"])
+ .required(),
+
+ // How long it took in ms for data to be ready for display.
+ topsites_data_late_by_ms: Joi.number().positive(),
+
+ // When did the topsites element finish painting? Note that, at least for
+ // the first tab to be loaded, and maybe some others, this will be before
+ // topsites has yet to receive screenshots updates from the add-on code,
+ // and is therefore just showing placeholder screenshots.
+ topsites_first_painted_ts: Joi.number()
+ .integer()
+ .notes(["server counter", "server counter alert"]),
+
+ // Information about the quality of TopSites images and icons.
+ topsites_icon_stats: Joi.object().keys({
+ custom_screenshot: Joi.number(),
+ rich_icon: Joi.number(),
+ screenshot: Joi.number(),
+ screenshot_with_icon: Joi.number(),
+ tippytop: Joi.number(),
+ no_image: Joi.number(),
+ }),
+
+ // The count of pinned Top Sites.
+ topsites_pinned: Joi.number(),
+
+ // The count of search shortcut Top Sites.
+ topsites_search_shortcuts: Joi.number(),
+
+ // When the page itself receives an event that document.visibilityState
+ // == visible.
+ //
+ // Not required at least for the (error?) case where the
+ // visibility_event doesn't fire. (It's not clear whether this
+ // can happen in practice, but if it does, we'd like to know about it).
+ visibility_event_rcvd_ts: Joi.number()
+ .integer()
+ .notes(["server counter", "server counter alert"]),
+
+ // The boolean to signify whether the page is preloaded or not.
+ is_preloaded: Joi.bool().required(),
+ })
+ .required(),
+ })
+);
+
+export const ASRouterEventPing = Joi.object()
+ .keys({
+ addon_version: Joi.string().required(),
+ locale: Joi.string().required(),
+ message_id: Joi.string().required(),
+ event: Joi.string().required(),
+ client_id: Joi.string(),
+ impression_id: Joi.string(),
+ })
+ .or("client_id", "impression_id");
+
+export const UTSessionPing = Joi.array().items(
+ Joi.string()
+ .required()
+ .valid("activity_stream"),
+ Joi.string()
+ .required()
+ .valid("end"),
+ Joi.string()
+ .required()
+ .valid("session"),
+ Joi.string().required(),
+ eventsTelemetryExtraKeys
+);
+
+export function chaiAssertions(_chai, utils) {
+ const { Assertion } = _chai;
+
+ Assertion.addMethod("validate", function(schema, schemaName) {
+ const { error } = Joi.validate(this._obj, schema, { allowUnknown: false });
+ this.assert(
+ !error,
+ `Expected to be ${
+ schemaName ? `a valid ${schemaName}` : "valid"
+ } but there were errors: ${error}`
+ );
+ });
+
+ const assertions = {
+ /**
+ * assert.validate - Validates an item given a Joi schema
+ *
+ * @param {any} actual The item to validate
+ * @param {obj} schema A Joi schema
+ */
+ validate(actual, schema, schemaName) {
+ new Assertion(actual).validate(schema, schemaName);
+ },
+
+ /**
+ * isUserEventAction - Passes if the item is a valid UserEvent action
+ *
+ * @param {any} actual The item to validate
+ */
+ isUserEventAction(actual) {
+ new Assertion(actual).validate(UserEventAction, "UserEventAction");
+ },
+ };
+
+ Object.assign(_chai.assert, assertions);
+}
diff --git a/browser/components/newtab/test/unit/aboutwelcome/MultiStageAboutWelcome.test.jsx b/browser/components/newtab/test/unit/aboutwelcome/MultiStageAboutWelcome.test.jsx
new file mode 100644
index 0000000000..ed176f3bdc
--- /dev/null
+++ b/browser/components/newtab/test/unit/aboutwelcome/MultiStageAboutWelcome.test.jsx
@@ -0,0 +1,186 @@
+import { GlobalOverrider } from "test/unit/utils";
+import {
+ MultiStageAboutWelcome,
+ WelcomeScreen,
+} from "content-src/aboutwelcome/components/MultiStageAboutWelcome";
+import React from "react";
+import { shallow, mount } from "enzyme";
+import {
+ DEFAULT_WELCOME_CONTENT,
+ AboutWelcomeUtils,
+} from "content-src/lib/aboutwelcome-utils";
+
+describe("MultiStageAboutWelcome module", () => {
+ let globals;
+ let sandbox;
+
+ const DEFAULT_PROPS = {
+ screens: DEFAULT_WELCOME_CONTENT.screens,
+ metricsFlowUri: "http://localhost/",
+ message_id: "DEFAULT_ABOUTWELCOME",
+ utm_term: "default",
+ };
+
+ beforeEach(async () => {
+ globals = new GlobalOverrider();
+ globals.set({
+ AWGetDefaultSites: () => Promise.resolve([]),
+ AWGetImportableSites: () => Promise.resolve("{}"),
+ AWGetSelectedTheme: () => Promise.resolve("automatic"),
+ AWSendEventTelemetry: () => {},
+ AWWaitForRegionChange: () => Promise.resolve(),
+ AWGetRegion: () => Promise.resolve(),
+ });
+ sandbox = sinon.createSandbox();
+ });
+
+ afterEach(() => {
+ sandbox.restore();
+ globals.restore();
+ });
+
+ describe("MultiStageAboutWelcome functional component", () => {
+ it("should render MultiStageAboutWelcome", () => {
+ const wrapper = shallow(<MultiStageAboutWelcome {...DEFAULT_PROPS} />);
+
+ assert.ok(wrapper.exists());
+ });
+
+ it("should send <MESSAGEID>_SITES impression telemetry ", async () => {
+ const impressionSpy = sandbox.spy(
+ AboutWelcomeUtils,
+ "sendImpressionTelemetry"
+ );
+ globals.set({
+ AWGetImportableSites: () =>
+ Promise.resolve('["site-1","site-2","site-3","site-4","site-5"]'),
+ });
+
+ mount(<MultiStageAboutWelcome {...DEFAULT_PROPS} />);
+ // Delay slightly to make sure we've finished executing any promise
+ await new Promise(resolve => setTimeout(resolve, 0));
+
+ assert.calledTwice(impressionSpy);
+ assert.equal(
+ impressionSpy.firstCall.args[0],
+ `${DEFAULT_PROPS.message_id}_${DEFAULT_PROPS.screens[0].id}`
+ );
+ assert.equal(
+ impressionSpy.secondCall.args[0],
+ `${DEFAULT_PROPS.message_id}_SITES`
+ );
+ assert.equal(impressionSpy.secondCall.lastArg.display, "static");
+ assert.equal(impressionSpy.secondCall.lastArg.importable, 5);
+ });
+
+ it("should pass activeTheme and initialTheme props to WelcomeScreen", async () => {
+ let wrapper = mount(<MultiStageAboutWelcome {...DEFAULT_PROPS} />);
+ // Spin the event loop to allow the useEffect hooks to execute,
+ // any promises to resolve, and re-rendering to happen after the
+ // promises have updated the state/props
+ await new Promise(resolve => setTimeout(resolve, 0));
+ // sync up enzyme's representation with the real DOM
+ wrapper.update();
+
+ let welcomeScreenWrapper = wrapper.find(WelcomeScreen);
+ assert.strictEqual(welcomeScreenWrapper.prop("activeTheme"), "automatic");
+ assert.strictEqual(
+ welcomeScreenWrapper.prop("initialTheme"),
+ "automatic"
+ );
+ });
+
+ it("should handle primary Action", () => {
+ const stub = sinon.stub(AboutWelcomeUtils, "sendActionTelemetry");
+ let wrapper = mount(<MultiStageAboutWelcome {...DEFAULT_PROPS} />);
+ wrapper.update();
+
+ let welcomeScreenWrapper = wrapper.find(WelcomeScreen);
+ const btnPrimary = welcomeScreenWrapper.find(".primary");
+ btnPrimary.simulate("click");
+ assert.calledOnce(stub);
+ assert.equal(
+ stub.firstCall.args[0],
+ welcomeScreenWrapper.props().messageId
+ );
+ assert.equal(stub.firstCall.args[1], "primary_button");
+ });
+ });
+
+ describe("WelcomeScreen component", () => {
+ describe("get started screen", () => {
+ const startScreen = DEFAULT_WELCOME_CONTENT.screens.find(screen => {
+ return screen.id === "AW_GET_STARTED";
+ });
+
+ const GET_STARTED_SCREEN_PROPS = {
+ id: startScreen.id,
+ totalNumberofScreens: 1,
+ order: startScreen.order,
+ content: startScreen.content,
+ topSites: [],
+ messageId: `${DEFAULT_PROPS.message_id}_${startScreen.id}`,
+ UTMTerm: DEFAULT_PROPS.utm_term,
+ flowParams: null,
+ };
+
+ it("should render GetStarted Screen", () => {
+ const wrapper = shallow(
+ <WelcomeScreen {...GET_STARTED_SCREEN_PROPS} />
+ );
+ assert.ok(wrapper.exists());
+ });
+
+ it("should have primary and secondary button in the rendered input", () => {
+ const wrapper = mount(<WelcomeScreen {...GET_STARTED_SCREEN_PROPS} />);
+ assert.ok(wrapper.find(".primary"));
+ assert.isTrue(wrapper.find("div.secondary-cta").hasClass("top"));
+ assert.ok(wrapper.find(".secondary"));
+ });
+ });
+ describe("theme screen", () => {
+ const themeScreen = DEFAULT_WELCOME_CONTENT.screens.find(screen => {
+ return screen.id === "AW_CHOOSE_THEME";
+ });
+
+ const THEME_SCREEN_PROPS = {
+ id: themeScreen.id,
+ totalNumberofScreens: 1,
+ order: themeScreen.order,
+ content: themeScreen.content,
+ navigate: null,
+ topSites: [],
+ messageId: `${DEFAULT_PROPS.message_id}_${themeScreen.id}`,
+ UTMTerm: DEFAULT_PROPS.utm_term,
+ flowParams: null,
+ activeTheme: "automatic",
+ };
+
+ it("should render WelcomeScreen", () => {
+ const wrapper = shallow(<WelcomeScreen {...THEME_SCREEN_PROPS} />);
+
+ assert.ok(wrapper.exists());
+ });
+
+ it("should select this.props.activeTheme in the rendered input", () => {
+ const wrapper = shallow(<WelcomeScreen {...THEME_SCREEN_PROPS} />);
+
+ const selectedThemeInput = wrapper.find(".theme.selected input");
+ assert.strictEqual(
+ selectedThemeInput.prop("value"),
+ THEME_SCREEN_PROPS.activeTheme
+ );
+ });
+
+ it("should check this.props.activeTheme in the rendered input", () => {
+ const wrapper = shallow(<WelcomeScreen {...THEME_SCREEN_PROPS} />);
+
+ const selectedThemeInput = wrapper.find(".theme input[checked=true]");
+ assert.strictEqual(
+ selectedThemeInput.prop("value"),
+ THEME_SCREEN_PROPS.activeTheme
+ );
+ });
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/asrouter/ASRouter.test.js b/browser/components/newtab/test/unit/asrouter/ASRouter.test.js
new file mode 100644
index 0000000000..ba881d81db
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/ASRouter.test.js
@@ -0,0 +1,2898 @@
+import { _ASRouter, MessageLoaderUtils } from "lib/ASRouter.jsm";
+import { QueryCache } from "lib/ASRouterTargeting.jsm";
+import {
+ FAKE_LOCAL_MESSAGES,
+ FAKE_LOCAL_PROVIDER,
+ FAKE_LOCAL_PROVIDERS,
+ FAKE_REMOTE_MESSAGES,
+ FAKE_REMOTE_PROVIDER,
+ FAKE_REMOTE_SETTINGS_PROVIDER,
+} from "./constants";
+import {
+ ASRouterPreferences,
+ TARGETING_PREFERENCES,
+} from "lib/ASRouterPreferences.jsm";
+import { ASRouterTriggerListeners } from "lib/ASRouterTriggerListeners.jsm";
+import { CFRPageActions } from "lib/CFRPageActions.jsm";
+import { GlobalOverrider } from "test/unit/utils";
+import { PanelTestProvider } from "lib/PanelTestProvider.jsm";
+import ProviderResponseSchema from "content-src/asrouter/schemas/provider-response.schema.json";
+import { SnippetsTestMessageProvider } from "lib/SnippetsTestMessageProvider.jsm";
+
+const MESSAGE_PROVIDER_PREF_NAME =
+ "browser.newtabpage.activity-stream.asrouter.providers.snippets";
+const FAKE_PROVIDERS = [
+ FAKE_LOCAL_PROVIDER,
+ FAKE_REMOTE_PROVIDER,
+ FAKE_REMOTE_SETTINGS_PROVIDER,
+];
+const ONE_DAY_IN_MS = 24 * 60 * 60 * 1000;
+const FAKE_RESPONSE_HEADERS = { get() {} };
+const FAKE_BUNDLE = [FAKE_LOCAL_MESSAGES[1], FAKE_LOCAL_MESSAGES[2]];
+
+const USE_REMOTE_L10N_PREF =
+ "browser.newtabpage.activity-stream.asrouter.useRemoteL10n";
+
+// eslint-disable-next-line max-statements
+describe("ASRouter", () => {
+ let Router;
+ let globals;
+ let sandbox;
+ let initParams;
+ let messageBlockList;
+ let providerBlockList;
+ let messageImpressions;
+ let groupImpressions;
+ let previousSessionEnd;
+ let fetchStub;
+ let clock;
+ let getStringPrefStub;
+ let fakeAttributionCode;
+ let fakeTargetingContext;
+ let FakeBookmarkPanelHub;
+ let FakeToolbarBadgeHub;
+ let FakeToolbarPanelHub;
+ let FakeMomentsPageHub;
+ let personalizedCfrScores;
+ let ASRouterTargeting;
+
+ function setMessageProviderPref(value) {
+ sandbox.stub(ASRouterPreferences, "providers").get(() => value);
+ }
+
+ function initASRouter(router) {
+ const getStub = sandbox.stub();
+ getStub.returns(Promise.resolve());
+ getStub
+ .withArgs("messageBlockList")
+ .returns(Promise.resolve(messageBlockList));
+ getStub
+ .withArgs("providerBlockList")
+ .returns(Promise.resolve(providerBlockList));
+ getStub
+ .withArgs("messageImpressions")
+ .returns(Promise.resolve(messageImpressions));
+ getStub.withArgs("groupImpressions").resolves(groupImpressions);
+ getStub
+ .withArgs("previousSessionEnd")
+ .returns(Promise.resolve(previousSessionEnd));
+ initParams = {
+ storage: {
+ get: getStub,
+ set: sandbox.stub().returns(Promise.resolve()),
+ },
+ sendTelemetry: sandbox.stub().resolves(),
+ clearChildMessages: sandbox.stub().resolves(),
+ clearChildProviders: sandbox.stub().resolves(),
+ updateAdminState: sandbox.stub().resolves(),
+ dispatchCFRAction: sandbox.stub().resolves(),
+ };
+ sandbox.stub(router, "loadMessagesFromAllProviders").callThrough();
+ return router.init(initParams);
+ }
+
+ async function createRouterAndInit(providers = FAKE_PROVIDERS) {
+ setMessageProviderPref(providers);
+ // `.freeze` to catch any attempts at modifying the object
+ Router = new _ASRouter(Object.freeze(FAKE_LOCAL_PROVIDERS));
+ await initASRouter(Router);
+ }
+
+ beforeEach(async () => {
+ globals = new GlobalOverrider();
+ messageBlockList = [];
+ providerBlockList = [];
+ messageImpressions = {};
+ groupImpressions = {};
+ previousSessionEnd = 100;
+ sandbox = sinon.createSandbox();
+ personalizedCfrScores = {};
+ ASRouterTargeting = {
+ isMatch: sandbox.stub(),
+ findMatchingMessage: sandbox.stub(),
+ Environment: {
+ locale: "en-US",
+ localeLanguageCode: "en",
+ browserSettings: {
+ update: {
+ channel: "default",
+ enabled: true,
+ autoDownload: true,
+ },
+ },
+ attributionData: {},
+ currentDate: "2000-01-01T10:00:0.001Z",
+ profileAgeCreated: {},
+ profileAgeReset: {},
+ usesFirefoxSync: false,
+ isFxAEnabled: true,
+ sync: {
+ desktopDevices: 0,
+ mobileDevices: 0,
+ totalDevices: 0,
+ },
+ xpinstallEnabled: true,
+ addonsInfo: {},
+ searchEngines: {},
+ isDefaultBrowser: false,
+ devToolsOpenedCount: 5,
+ topFrecentSites: {},
+ recentBookmarks: {},
+ pinnedSites: [
+ {
+ url: "https://amazon.com",
+ host: "amazon.com",
+ searchTopSite: true,
+ },
+ ],
+ providerCohorts: {
+ onboarding: "",
+ "cfr-fxa": "",
+ cfr: "",
+ "message-groups": "",
+ "messaging-experiments": "",
+ snippets: "",
+ "whats-new-panel": "",
+ },
+ totalBookmarksCount: {},
+ firefoxVersion: 80,
+ region: "US",
+ needsUpdate: {},
+ hasPinnedTabs: false,
+ hasAccessedFxAPanel: false,
+ isWhatsNewPanelEnabled: true,
+ userPrefs: {
+ cfrFeatures: true,
+ cfrAddons: true,
+ snippets: true,
+ },
+ totalBlockedCount: {},
+ blockedCountByType: {},
+ attachedFxAOAuthClients: [],
+ platformName: "macosx",
+ scores: {},
+ scoreThreshold: 5000,
+ isChinaRepack: false,
+ userId: "adsf",
+ },
+ };
+
+ ASRouterPreferences.specialConditions = {
+ someCondition: true,
+ };
+ sandbox.spy(ASRouterPreferences, "init");
+ sandbox.spy(ASRouterPreferences, "uninit");
+ sandbox.spy(ASRouterPreferences, "addListener");
+ sandbox.spy(ASRouterPreferences, "removeListener");
+ sandbox.replaceGetter(
+ ASRouterPreferences,
+ "personalizedCfrScores",
+ () => personalizedCfrScores
+ );
+
+ clock = sandbox.useFakeTimers();
+ fetchStub = sandbox
+ .stub(global, "fetch")
+ .withArgs("http://fake.com/endpoint")
+ .resolves({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve({ messages: FAKE_REMOTE_MESSAGES }),
+ headers: FAKE_RESPONSE_HEADERS,
+ });
+ getStringPrefStub = sandbox.stub(global.Services.prefs, "getStringPref");
+
+ fakeAttributionCode = {
+ allowedCodeKeys: ["foo", "bar", "baz"],
+ _clearCache: () => sinon.stub(),
+ getAttrDataAsync: () => Promise.resolve({ content: "addonID" }),
+ deleteFileAsync: () => Promise.resolve(),
+ writeAttributionFile: () => Promise.resolve(),
+ getCachedAttributionData: sinon.stub(),
+ };
+ FakeBookmarkPanelHub = {
+ init: sandbox.stub(),
+ uninit: sandbox.stub(),
+ forceShowMessage: sandbox.stub(),
+ };
+ FakeToolbarPanelHub = {
+ init: sandbox.stub(),
+ uninit: sandbox.stub(),
+ forceShowMessage: sandbox.stub(),
+ enableToolbarButton: sandbox.stub(),
+ };
+ FakeToolbarBadgeHub = {
+ init: sandbox.stub(),
+ uninit: sandbox.stub(),
+ registerBadgeNotificationListener: sandbox.stub(),
+ };
+ FakeMomentsPageHub = {
+ init: sandbox.stub(),
+ uninit: sandbox.stub(),
+ executeAction: sandbox.stub(),
+ };
+ fakeTargetingContext = {
+ combineContexts: sandbox.stub(),
+ evalWithDefault: sandbox.stub().resolves(),
+ };
+ globals.set({
+ // Testing framework doesn't know how to `defineLazyModuleGetter` so we're
+ // importing these modules into the global scope ourselves.
+ GroupsConfigurationProvider: { getMessages: () => Promise.resolve([]) },
+ ASRouterPreferences,
+ TARGETING_PREFERENCES,
+ ASRouterTargeting,
+ ASRouterTriggerListeners,
+ QueryCache,
+ gURLBar: {},
+ isSeparateAboutWelcome: true,
+ AttributionCode: fakeAttributionCode,
+ SnippetsTestMessageProvider,
+ PanelTestProvider,
+ MacAttribution: { applicationPath: "" },
+ BookmarkPanelHub: FakeBookmarkPanelHub,
+ ToolbarBadgeHub: FakeToolbarBadgeHub,
+ ToolbarPanelHub: FakeToolbarPanelHub,
+ MomentsPageHub: FakeMomentsPageHub,
+ KintoHttpClient: class {
+ bucket() {
+ return this;
+ }
+ collection() {
+ return this;
+ }
+ getRecord() {
+ return Promise.resolve({ data: {} });
+ }
+ },
+ Downloader: class {
+ download() {
+ return Promise.resolve("/path/to/download");
+ }
+ },
+ ExperimentAPI: {
+ getExperiment: sandbox.stub().returns({
+ branch: {
+ slug: "unit-slug",
+ feature: {
+ featureId: "foo",
+ enabled: true,
+ value: { id: "test-message" },
+ },
+ },
+ }),
+ recordExposureEvent: sandbox.stub(),
+ getAllBranches: sandbox.stub().resolves([
+ {
+ branch: {
+ slug: "unit-slug",
+ feature: {
+ featureId: "bar",
+ enabled: true,
+ value: { id: "test-message" },
+ },
+ },
+ },
+ ]),
+ ready: sandbox.stub().resolves(),
+ },
+ SpecialMessageActions: {
+ handleAction: sandbox.stub(),
+ },
+ TargetingContext: class {
+ static combineContexts(...args) {
+ return fakeTargetingContext.combineContexts.apply(sandbox, args);
+ }
+
+ evalWithDefault(expr) {
+ return fakeTargetingContext.evalWithDefault(expr);
+ }
+ },
+ RemoteL10n: {
+ isLocaleSupported: () => true,
+ },
+ });
+ await createRouterAndInit();
+ });
+ afterEach(() => {
+ Router.uninit();
+ ASRouterPreferences.uninit();
+ sandbox.restore();
+ globals.restore();
+ });
+
+ describe(".state", () => {
+ it("should throw if an attempt to set .state was made", () => {
+ assert.throws(() => {
+ Router.state = {};
+ });
+ });
+ });
+
+ describe("#init", () => {
+ it("should set state.messageBlockList to the block list in persistent storage", async () => {
+ messageBlockList = ["foo"];
+ Router = new _ASRouter();
+ await initASRouter(Router);
+
+ assert.deepEqual(Router.state.messageBlockList, ["foo"]);
+ });
+ it("should initialize all the hub providers", async () => {
+ // ASRouter init called in `beforeEach` block above
+
+ assert.calledOnce(FakeToolbarBadgeHub.init);
+ assert.calledOnce(FakeToolbarPanelHub.init);
+ assert.calledOnce(FakeBookmarkPanelHub.init);
+ assert.calledOnce(FakeMomentsPageHub.init);
+
+ assert.calledWithExactly(
+ FakeToolbarBadgeHub.init,
+ Router.waitForInitialized,
+ {
+ handleMessageRequest: Router.handleMessageRequest,
+ addImpression: Router.addImpression,
+ blockMessageById: Router.blockMessageById,
+ sendTelemetry: Router.sendTelemetry,
+ unblockMessageById: Router.unblockMessageById,
+ }
+ );
+
+ assert.calledWithExactly(
+ FakeToolbarPanelHub.init,
+ Router.waitForInitialized,
+ {
+ getMessages: Router.handleMessageRequest,
+ sendTelemetry: Router.sendTelemetry,
+ }
+ );
+
+ assert.calledWithExactly(
+ FakeMomentsPageHub.init,
+ Router.waitForInitialized,
+ {
+ handleMessageRequest: Router.handleMessageRequest,
+ addImpression: Router.addImpression,
+ blockMessageById: Router.blockMessageById,
+ sendTelemetry: Router.sendTelemetry,
+ }
+ );
+
+ assert.calledWithExactly(
+ FakeBookmarkPanelHub.init,
+ Router.handleMessageRequest,
+ Router.addImpression,
+ Router.sendTelemetry
+ );
+ });
+ it("should set state.messageImpressions to the messageImpressions object in persistent storage", async () => {
+ // Note that messageImpressions are only kept if a message exists in router and has a .frequency property,
+ // otherwise they will be cleaned up by .cleanupImpressions()
+ const testMessage = { id: "foo", frequency: { lifetimeCap: 10 } };
+ messageImpressions = { foo: [0, 1, 2] };
+ setMessageProviderPref([
+ { id: "onboarding", type: "local", messages: [testMessage] },
+ ]);
+ Router = new _ASRouter();
+ await initASRouter(Router);
+
+ assert.deepEqual(Router.state.messageImpressions, messageImpressions);
+ });
+ it("should clear impressions for groups that are not active", async () => {
+ groupImpressions = { foo: [0, 1, 2] };
+ Router = new _ASRouter();
+ await initASRouter(Router);
+
+ assert.notProperty(Router.state.groupImpressions, "foo");
+ });
+ it("should keep impressions for groups that are active", async () => {
+ Router = new _ASRouter();
+ await initASRouter(Router);
+ await Router.setState(() => {
+ return {
+ groups: [
+ {
+ id: "foo",
+ enabled: true,
+ frequency: {
+ custom: [{ period: ONE_DAY_IN_MS, cap: 10 }],
+ lifetime: Infinity,
+ },
+ },
+ ],
+ groupImpressions: { foo: [Date.now()] },
+ };
+ });
+ Router.cleanupImpressions();
+
+ assert.property(Router.state.groupImpressions, "foo");
+ assert.lengthOf(Router.state.groupImpressions.foo, 1);
+ });
+ it("should remove old impressions for a group", async () => {
+ Router = new _ASRouter();
+ await initASRouter(Router);
+ await Router.setState(() => {
+ return {
+ groups: [
+ {
+ id: "foo",
+ enabled: true,
+ frequency: {
+ custom: [{ period: ONE_DAY_IN_MS, cap: 10 }],
+ },
+ },
+ ],
+ groupImpressions: {
+ foo: [Date.now() - ONE_DAY_IN_MS - 1, Date.now()],
+ },
+ };
+ });
+ Router.cleanupImpressions();
+
+ assert.property(Router.state.groupImpressions, "foo");
+ assert.lengthOf(Router.state.groupImpressions.foo, 1);
+ });
+ it("should await .loadMessagesFromAllProviders() and add messages from providers to state.messages", async () => {
+ Router = new _ASRouter(Object.freeze(FAKE_LOCAL_PROVIDERS));
+
+ await initASRouter(Router);
+
+ assert.calledOnce(Router.loadMessagesFromAllProviders);
+ assert.isArray(Router.state.messages);
+ assert.lengthOf(
+ Router.state.messages,
+ FAKE_LOCAL_MESSAGES.length + FAKE_REMOTE_MESSAGES.length
+ );
+ });
+ it("should load additional allowed hosts", async () => {
+ getStringPrefStub.returns('["allow.com"]');
+ await createRouterAndInit();
+
+ assert.propertyVal(Router.ALLOWLIST_HOSTS, "allow.com", "preview");
+ // Should still include the defaults
+ assert.lengthOf(Object.keys(Router.ALLOWLIST_HOSTS), 3);
+ });
+ it("should fallback to defaults if pref parsing fails", async () => {
+ getStringPrefStub.returns("err");
+ await createRouterAndInit();
+
+ assert.lengthOf(Object.keys(Router.ALLOWLIST_HOSTS), 2);
+ assert.propertyVal(
+ Router.ALLOWLIST_HOSTS,
+ "snippets-admin.mozilla.org",
+ "preview"
+ );
+ assert.propertyVal(
+ Router.ALLOWLIST_HOSTS,
+ "activity-stream-icons.services.mozilla.com",
+ "production"
+ );
+ });
+ it("should set state.previousSessionEnd from IndexedDB", async () => {
+ previousSessionEnd = 200;
+ await createRouterAndInit();
+
+ assert.equal(Router.state.previousSessionEnd, previousSessionEnd);
+ });
+ it("should assign ASRouterPreferences.specialConditions to state", async () => {
+ assert.isTrue(ASRouterPreferences.specialConditions.someCondition);
+ assert.isTrue(Router.state.someCondition);
+ });
+ it("should add observer for `intl:app-locales-changed`", async () => {
+ sandbox.spy(global.Services.obs, "addObserver");
+ await createRouterAndInit();
+
+ assert.calledOnce(global.Services.obs.addObserver);
+ assert.equal(
+ global.Services.obs.addObserver.args[0][1],
+ "intl:app-locales-changed"
+ );
+ });
+ it("should add a pref observer", async () => {
+ sandbox.spy(global.Services.prefs, "addObserver");
+ await createRouterAndInit();
+
+ assert.calledOnce(global.Services.prefs.addObserver);
+ assert.calledWithExactly(
+ global.Services.prefs.addObserver,
+ USE_REMOTE_L10N_PREF,
+ Router
+ );
+ });
+ describe("lazily loading local test providers", () => {
+ afterEach(() => {
+ Router.uninit();
+ });
+ it("should add the local test providers on init if devtools are enabled", async () => {
+ sandbox.stub(ASRouterPreferences, "devtoolsEnabled").get(() => true);
+
+ await createRouterAndInit();
+
+ assert.property(Router._localProviders, "SnippetsTestMessageProvider");
+ assert.property(Router._localProviders, "PanelTestProvider");
+ });
+ it("should not add the local test providers on init if devtools are disabled", async () => {
+ sandbox.stub(ASRouterPreferences, "devtoolsEnabled").get(() => false);
+
+ await createRouterAndInit();
+
+ assert.notProperty(
+ Router._localProviders,
+ "SnippetsTestMessageProvider"
+ );
+ assert.notProperty(Router._localProviders, "PanelTestProvider");
+ });
+ });
+ });
+
+ describe("preference changes", () => {
+ it("should call ASRouterPreferences.init and add a listener on init", () => {
+ assert.calledOnce(ASRouterPreferences.init);
+ assert.calledWith(ASRouterPreferences.addListener, Router.onPrefChange);
+ });
+ it("should call ASRouterPreferences.uninit and remove the listener on uninit", () => {
+ Router.uninit();
+ assert.calledOnce(ASRouterPreferences.uninit);
+ assert.calledWith(
+ ASRouterPreferences.removeListener,
+ Router.onPrefChange
+ );
+ });
+ it("should send a AS_ROUTER_TARGETING_UPDATE message", async () => {
+ const messageTargeted = {
+ id: "1",
+ campaign: "foocampaign",
+ targeting: "true",
+ groups: ["snippets"],
+ provider: "snippets",
+ };
+ const messageNotTargeted = {
+ id: "2",
+ campaign: "foocampaign",
+ groups: ["snippets"],
+ provider: "snippets",
+ };
+ await Router.setState({
+ messages: [messageTargeted, messageNotTargeted],
+ providers: [{ id: "snippets" }],
+ });
+ fakeTargetingContext.evalWithDefault.resolves(false);
+
+ await Router.onPrefChange("services.sync.username");
+
+ assert.calledOnce(initParams.clearChildMessages);
+ assert.calledWith(initParams.clearChildMessages, [messageTargeted.id]);
+ });
+ it("should call loadMessagesFromAllProviders on pref change", () => {
+ ASRouterPreferences.observe(null, null, MESSAGE_PROVIDER_PREF_NAME);
+ assert.calledOnce(Router.loadMessagesFromAllProviders);
+ });
+ it("should update groups state if a user pref changes", async () => {
+ await Router.setState({
+ groups: [{ id: "foo", userPreferences: ["bar"], enabled: true }],
+ });
+ sandbox.stub(ASRouterPreferences, "getUserPreference");
+
+ await Router.onPrefChange(MESSAGE_PROVIDER_PREF_NAME);
+
+ assert.calledWithExactly(ASRouterPreferences.getUserPreference, "bar");
+ });
+ it("should update the list of providers on pref change", async () => {
+ const modifiedRemoteProvider = Object.assign({}, FAKE_REMOTE_PROVIDER, {
+ url: "baz.com",
+ });
+ setMessageProviderPref([
+ FAKE_LOCAL_PROVIDER,
+ modifiedRemoteProvider,
+ FAKE_REMOTE_SETTINGS_PROVIDER,
+ ]);
+
+ const { length } = Router.state.providers;
+
+ ASRouterPreferences.observe(null, null, MESSAGE_PROVIDER_PREF_NAME);
+ await Router._updateMessageProviders();
+
+ const provider = Router.state.providers.find(p => p.url === "baz.com");
+ assert.lengthOf(Router.state.providers, length);
+ assert.isDefined(provider);
+ });
+ it("should clear disabled providers on pref change", async () => {
+ const TEST_PROVIDER_ID = "some_provider_id";
+ await Router.setState({
+ providers: [{ id: TEST_PROVIDER_ID }],
+ });
+ const modifiedRemoteProvider = Object.assign({}, FAKE_REMOTE_PROVIDER, {
+ id: TEST_PROVIDER_ID,
+ enabled: false,
+ });
+ setMessageProviderPref([
+ FAKE_LOCAL_PROVIDER,
+ modifiedRemoteProvider,
+ FAKE_REMOTE_SETTINGS_PROVIDER,
+ ]);
+ await Router.onPrefChange(MESSAGE_PROVIDER_PREF_NAME);
+
+ assert.calledOnce(initParams.clearChildProviders);
+ assert.calledWith(initParams.clearChildProviders, [TEST_PROVIDER_ID]);
+ });
+ });
+
+ describe("setState", () => {
+ it("should broadcast a message to update the admin tool on a state change if the asrouter.devtoolsEnabled pref is", async () => {
+ sandbox.stub(ASRouterPreferences, "devtoolsEnabled").get(() => true);
+ sandbox.stub(Router, "getTargetingParameters").resolves({});
+ const state = await Router.setState({ foo: 123 });
+
+ assert.calledOnce(initParams.updateAdminState);
+ assert.deepEqual(state.providerPrefs, ASRouterPreferences.providers);
+ assert.deepEqual(
+ state.userPrefs,
+ ASRouterPreferences.getAllUserPreferences()
+ );
+ assert.deepEqual(state.targetingParameters, {});
+ assert.deepEqual(state.errors, Router.errors);
+ });
+ it("should not send a message on a state change asrouter.devtoolsEnabled pref is on", async () => {
+ sandbox.stub(ASRouterPreferences, "devtoolsEnabled").get(() => false);
+ await Router.setState({ foo: 123 });
+
+ assert.notCalled(initParams.updateAdminState);
+ });
+ });
+
+ describe("getTargetingParameters", () => {
+ it("should return the targeting parameters", async () => {
+ const stub = sandbox.stub().resolves("foo");
+ const obj = { foo: 1 };
+ sandbox.stub(obj, "foo").get(stub);
+ const result = await Router.getTargetingParameters(obj, obj);
+
+ assert.calledTwice(stub);
+ assert.propertyVal(result, "foo", "foo");
+ });
+ });
+
+ describe("evaluateExpression", () => {
+ it("should call ASRouterTargeting to evaluate", async () => {
+ fakeTargetingContext.evalWithDefault.resolves("foo");
+ const response = await Router.evaluateExpression({});
+ assert.equal(response.evaluationStatus.result, "foo");
+ assert.isTrue(response.evaluationStatus.success);
+ });
+ it("should catch evaluation errors", async () => {
+ fakeTargetingContext.evalWithDefault.returns(
+ Promise.reject(new Error("fake error"))
+ );
+ const response = await Router.evaluateExpression({});
+ assert.isFalse(response.evaluationStatus.success);
+ });
+ });
+
+ describe("#routeCFRMessage", () => {
+ let browser;
+ beforeEach(() => {
+ sandbox.stub(CFRPageActions, "forceRecommendation");
+ sandbox.stub(CFRPageActions, "addRecommendation");
+ browser = {};
+ });
+ it("should route whatsnew_panel_message message to the right hub", () => {
+ Router.routeCFRMessage(
+ { template: "whatsnew_panel_message" },
+ browser,
+ "",
+ true
+ );
+
+ assert.calledOnce(FakeToolbarPanelHub.forceShowMessage);
+ assert.notCalled(FakeToolbarBadgeHub.registerBadgeNotificationListener);
+ assert.notCalled(FakeBookmarkPanelHub.forceShowMessage);
+ assert.notCalled(CFRPageActions.addRecommendation);
+ assert.notCalled(CFRPageActions.forceRecommendation);
+ assert.notCalled(FakeMomentsPageHub.executeAction);
+ });
+ it("should route moments messages to the right hub", () => {
+ Router.routeCFRMessage({ template: "update_action" }, browser, "", true);
+
+ assert.calledOnce(FakeMomentsPageHub.executeAction);
+ assert.notCalled(FakeToolbarPanelHub.forceShowMessage);
+ assert.notCalled(FakeToolbarBadgeHub.registerBadgeNotificationListener);
+ assert.notCalled(FakeBookmarkPanelHub.forceShowMessage);
+ assert.notCalled(CFRPageActions.addRecommendation);
+ assert.notCalled(CFRPageActions.forceRecommendation);
+ });
+ it("should route toolbar_badge message to the right hub", () => {
+ Router.routeCFRMessage({ template: "toolbar_badge" }, browser);
+
+ assert.calledOnce(FakeToolbarBadgeHub.registerBadgeNotificationListener);
+ assert.notCalled(FakeToolbarPanelHub.forceShowMessage);
+ assert.notCalled(FakeBookmarkPanelHub.forceShowMessage);
+ assert.notCalled(CFRPageActions.addRecommendation);
+ assert.notCalled(CFRPageActions.forceRecommendation);
+ assert.notCalled(FakeMomentsPageHub.executeAction);
+ });
+ it("should route milestone_message to the right hub", () => {
+ Router.routeCFRMessage(
+ { template: "milestone_message" },
+ browser,
+ "",
+ false
+ );
+
+ assert.calledOnce(CFRPageActions.addRecommendation);
+ assert.notCalled(CFRPageActions.forceRecommendation);
+ assert.notCalled(FakeBookmarkPanelHub.forceShowMessage);
+ assert.notCalled(FakeToolbarBadgeHub.registerBadgeNotificationListener);
+ assert.notCalled(FakeToolbarPanelHub.forceShowMessage);
+ assert.notCalled(FakeMomentsPageHub.executeAction);
+ });
+ it("should route fxa_bookmark_panel message to the right hub force = true", () => {
+ Router.routeCFRMessage(
+ { template: "fxa_bookmark_panel" },
+ browser,
+ {},
+ true
+ );
+
+ assert.calledOnce(FakeBookmarkPanelHub.forceShowMessage);
+ assert.notCalled(FakeToolbarPanelHub.forceShowMessage);
+ assert.notCalled(FakeToolbarBadgeHub.registerBadgeNotificationListener);
+ assert.notCalled(CFRPageActions.addRecommendation);
+ assert.notCalled(CFRPageActions.forceRecommendation);
+ assert.notCalled(FakeMomentsPageHub.executeAction);
+ });
+ it("should route cfr_doorhanger message to the right hub force = false", () => {
+ Router.routeCFRMessage(
+ { template: "cfr_doorhanger" },
+ browser,
+ { param: {} },
+ false
+ );
+
+ assert.calledOnce(CFRPageActions.addRecommendation);
+ assert.notCalled(FakeToolbarPanelHub.forceShowMessage);
+ assert.notCalled(FakeBookmarkPanelHub.forceShowMessage);
+ assert.notCalled(FakeToolbarBadgeHub.registerBadgeNotificationListener);
+ assert.notCalled(CFRPageActions.forceRecommendation);
+ assert.notCalled(FakeMomentsPageHub.executeAction);
+ });
+ it("should route cfr_doorhanger message to the right hub force = true", () => {
+ Router.routeCFRMessage({ template: "cfr_doorhanger" }, browser, {}, true);
+
+ assert.calledOnce(CFRPageActions.forceRecommendation);
+ assert.notCalled(FakeToolbarPanelHub.forceShowMessage);
+ assert.notCalled(CFRPageActions.addRecommendation);
+ assert.notCalled(FakeBookmarkPanelHub.forceShowMessage);
+ assert.notCalled(FakeToolbarBadgeHub.registerBadgeNotificationListener);
+ assert.notCalled(FakeMomentsPageHub.executeAction);
+ });
+ it("should route cfr_urlbar_chiclet message to the right hub force = false", () => {
+ Router.routeCFRMessage(
+ { template: "cfr_urlbar_chiclet" },
+ browser,
+ { param: {} },
+ false
+ );
+
+ assert.calledOnce(CFRPageActions.addRecommendation);
+ const { args } = CFRPageActions.addRecommendation.firstCall;
+ // Host should be null
+ assert.isNull(args[1]);
+ assert.notCalled(FakeToolbarPanelHub.forceShowMessage);
+ assert.notCalled(FakeBookmarkPanelHub.forceShowMessage);
+ assert.notCalled(FakeToolbarBadgeHub.registerBadgeNotificationListener);
+ assert.notCalled(CFRPageActions.forceRecommendation);
+ assert.notCalled(FakeMomentsPageHub.executeAction);
+ });
+ it("should route cfr_urlbar_chiclet message to the right hub force = true", () => {
+ Router.routeCFRMessage(
+ { template: "cfr_urlbar_chiclet" },
+ browser,
+ {},
+ true
+ );
+
+ assert.calledOnce(CFRPageActions.forceRecommendation);
+ assert.notCalled(FakeToolbarPanelHub.forceShowMessage);
+ assert.notCalled(CFRPageActions.addRecommendation);
+ assert.notCalled(FakeBookmarkPanelHub.forceShowMessage);
+ assert.notCalled(FakeToolbarBadgeHub.registerBadgeNotificationListener);
+ assert.notCalled(FakeMomentsPageHub.executeAction);
+ });
+ it("should route default to sending to content", () => {
+ Router.routeCFRMessage({ template: "snippets" }, browser, {}, true);
+
+ assert.notCalled(FakeToolbarPanelHub.forceShowMessage);
+ assert.notCalled(CFRPageActions.forceRecommendation);
+ assert.notCalled(CFRPageActions.addRecommendation);
+ assert.notCalled(FakeBookmarkPanelHub.forceShowMessage);
+ assert.notCalled(FakeToolbarBadgeHub.registerBadgeNotificationListener);
+ assert.notCalled(FakeMomentsPageHub.executeAction);
+ });
+ });
+
+ describe("#loadMessagesFromAllProviders", () => {
+ function assertRouterContainsMessages(messages) {
+ const messageIdsInRouter = Router.state.messages.map(m => m.id);
+ for (const message of messages) {
+ assert.include(messageIdsInRouter, message.id);
+ }
+ }
+
+ it("should not trigger an update if not enough time has passed for a provider", async () => {
+ await createRouterAndInit([
+ {
+ id: "remotey",
+ type: "remote",
+ enabled: true,
+ url: "http://fake.com/endpoint",
+ updateCycleInMs: 300,
+ },
+ ]);
+
+ const previousState = Router.state;
+
+ // Since we've previously gotten messages during init and we haven't advanced our fake timer,
+ // no updates should be triggered.
+ await Router.loadMessagesFromAllProviders();
+ assert.deepEqual(Router.state, previousState);
+ });
+ it("should not trigger an update if we only have local providers", async () => {
+ await createRouterAndInit([
+ {
+ id: "foo",
+ type: "local",
+ enabled: true,
+ messages: FAKE_LOCAL_MESSAGES,
+ },
+ ]);
+
+ const previousState = Router.state;
+ const stub = sandbox.stub(MessageLoaderUtils, "loadMessagesForProvider");
+
+ clock.tick(300);
+
+ await Router.loadMessagesFromAllProviders();
+
+ assert.deepEqual(Router.state, previousState);
+ assert.notCalled(stub);
+ });
+ it("should apply personalization if defined", async () => {
+ personalizedCfrScores = { FOO: 1, BAR: 2 };
+ const NEW_MESSAGES = [{ id: "FOO" }, { id: "BAR" }];
+
+ fetchStub.withArgs("http://foo.com").resolves({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve({ messages: NEW_MESSAGES }),
+ headers: FAKE_RESPONSE_HEADERS,
+ });
+
+ await createRouterAndInit([
+ {
+ id: "cfr",
+ personalized: true,
+ personalizedModelVersion: "42",
+ type: "remote",
+ url: "http://foo.com",
+ enabled: true,
+ updateCycleInMs: 300,
+ },
+ ]);
+
+ await Router.loadMessagesFromAllProviders();
+
+ // Make sure messages are there
+ assertRouterContainsMessages(NEW_MESSAGES);
+
+ // Make sure they have a score and personalizedModelVersion
+ for (const expectedMessage of NEW_MESSAGES) {
+ const { id } = expectedMessage;
+ const message = Router.state.messages.find(msg => msg.id === id);
+ assert.propertyVal(message, "score", personalizedCfrScores[message.id]);
+ assert.propertyVal(message, "personalizedModelVersion", "42");
+ }
+ });
+ it("should update messages for a provider if enough time has passed, without removing messages for other providers", async () => {
+ const NEW_MESSAGES = [{ id: "new_123" }];
+ await createRouterAndInit([
+ {
+ id: "remotey",
+ type: "remote",
+ url: "http://fake.com/endpoint",
+ enabled: true,
+ updateCycleInMs: 300,
+ },
+ {
+ id: "alocalprovider",
+ type: "local",
+ enabled: true,
+ messages: FAKE_LOCAL_MESSAGES,
+ },
+ ]);
+ fetchStub.withArgs("http://fake.com/endpoint").resolves({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve({ messages: NEW_MESSAGES }),
+ headers: FAKE_RESPONSE_HEADERS,
+ });
+
+ clock.tick(301);
+ await Router.loadMessagesFromAllProviders();
+
+ // These are the new messages
+ assertRouterContainsMessages(NEW_MESSAGES);
+ // These are the local messages that should not have been deleted
+ assertRouterContainsMessages(FAKE_LOCAL_MESSAGES);
+ });
+ it("should parse the triggers in the messages and register the trigger listeners", async () => {
+ sandbox.spy(
+ ASRouterTriggerListeners.get("openURL"),
+ "init"
+ ); /* eslint-disable object-property-newline */
+
+ /* eslint-disable object-curly-newline */ await createRouterAndInit([
+ {
+ id: "foo",
+ type: "local",
+ enabled: true,
+ messages: [
+ {
+ id: "foo",
+ template: "simple_template",
+ trigger: { id: "firstRun" },
+ content: { title: "Foo", body: "Foo123" },
+ },
+ {
+ id: "bar1",
+ template: "simple_template",
+ trigger: {
+ id: "openURL",
+ params: ["www.mozilla.org", "www.mozilla.com"],
+ },
+ content: { title: "Bar1", body: "Bar123" },
+ },
+ {
+ id: "bar2",
+ template: "simple_template",
+ trigger: { id: "openURL", params: ["www.example.com"] },
+ content: { title: "Bar2", body: "Bar123" },
+ },
+ ],
+ },
+ ]); /* eslint-enable object-property-newline */
+ /* eslint-enable object-curly-newline */ assert.calledTwice(
+ ASRouterTriggerListeners.get("openURL").init
+ );
+ assert.calledWithExactly(
+ ASRouterTriggerListeners.get("openURL").init,
+ Router._triggerHandler,
+ ["www.mozilla.org", "www.mozilla.com"],
+ undefined
+ );
+ assert.calledWithExactly(
+ ASRouterTriggerListeners.get("openURL").init,
+ Router._triggerHandler,
+ ["www.example.com"],
+ undefined
+ );
+ });
+ it("should gracefully handle RemoteSettings blowing up and dispatch undesired event", async () => {
+ sandbox
+ .stub(MessageLoaderUtils, "_getRemoteSettingsMessages")
+ .rejects("fake error");
+ await createRouterAndInit();
+ assert.calledWith(initParams.dispatchCFRAction, {
+ data: {
+ action: "asrouter_undesired_event",
+ event: "ASR_RS_ERROR",
+ event_context: "remotey-settingsy",
+ message_id: "n/a",
+ },
+ meta: { from: "ActivityStream:Content", to: "ActivityStream:Main" },
+ type: "AS_ROUTER_TELEMETRY_USER_EVENT",
+ });
+ });
+ it("should dispatch undesired event if RemoteSettings returns no messages", async () => {
+ sandbox
+ .stub(MessageLoaderUtils, "_getRemoteSettingsMessages")
+ .resolves([]);
+ assert.calledWith(initParams.dispatchCFRAction, {
+ data: {
+ action: "asrouter_undesired_event",
+ event: "ASR_RS_NO_MESSAGES",
+ event_context: "remotey-settingsy",
+ message_id: "n/a",
+ },
+ meta: { from: "ActivityStream:Content", to: "ActivityStream:Main" },
+ type: "AS_ROUTER_TELEMETRY_USER_EVENT",
+ });
+ });
+ it("should download the attachment if RemoteSettings returns some messages", async () => {
+ sandbox
+ .stub(global.Services.locale, "appLocaleAsBCP47")
+ .get(() => "en-US");
+ sandbox
+ .stub(MessageLoaderUtils, "_getRemoteSettingsMessages")
+ .resolves([{ id: "message_1" }]);
+ const spy = sandbox.spy();
+ global.Downloader.prototype.download = spy;
+ const provider = {
+ id: "cfr",
+ enabled: true,
+ type: "remote-settings",
+ bucket: "cfr",
+ };
+ await createRouterAndInit([provider]);
+
+ assert.calledOnce(spy);
+ });
+ it("should dispatch undesired event if the ms-language-packs returns no messages", async () => {
+ sandbox
+ .stub(global.Services.locale, "appLocaleAsBCP47")
+ .get(() => "en-US");
+ sandbox
+ .stub(MessageLoaderUtils, "_getRemoteSettingsMessages")
+ .resolves([{ id: "message_1" }]);
+ sandbox
+ .stub(global.KintoHttpClient.prototype, "getRecord")
+ .resolves(null);
+ const provider = {
+ id: "cfr",
+ enabled: true,
+ type: "remote-settings",
+ bucket: "cfr",
+ };
+ await createRouterAndInit([provider]);
+
+ assert.calledWith(initParams.dispatchCFRAction, {
+ data: {
+ action: "asrouter_undesired_event",
+ event: "ASR_RS_NO_MESSAGES",
+ event_context: "ms-language-packs",
+ message_id: "n/a",
+ },
+ meta: { from: "ActivityStream:Content", to: "ActivityStream:Main" },
+ type: "AS_ROUTER_TELEMETRY_USER_EVENT",
+ });
+ });
+ });
+
+ describe("#_updateMessageProviders", () => {
+ it("should correctly replace %STARTPAGE_VERSION% in remote provider urls", async () => {
+ // If this test fails, you need to update the constant STARTPAGE_VERSION in
+ // ASRouter.jsm to match the `version` property of provider-response-schema.json
+ const expectedStartpageVersion = ProviderResponseSchema.version;
+ const provider = {
+ id: "foo",
+ enabled: true,
+ type: "remote",
+ url: "https://www.mozilla.org/%STARTPAGE_VERSION%/",
+ };
+ setMessageProviderPref([provider]);
+ await Router._updateMessageProviders();
+ assert.equal(
+ Router.state.providers[0].url,
+ `https://www.mozilla.org/${parseInt(expectedStartpageVersion, 10)}/`
+ );
+ });
+ it("should replace other params in remote provider urls by calling Services.urlFormater.formatURL", async () => {
+ const url = "https://www.example.com/";
+ const replacedUrl = "https://www.foo.bar/";
+ const stub = sandbox
+ .stub(global.Services.urlFormatter, "formatURL")
+ .withArgs(url)
+ .returns(replacedUrl);
+ const provider = { id: "foo", enabled: true, type: "remote", url };
+ setMessageProviderPref([provider]);
+ await Router._updateMessageProviders();
+ assert.calledOnce(stub);
+ assert.calledWithExactly(stub, url);
+ assert.equal(Router.state.providers[0].url, replacedUrl);
+ });
+ it("should only add the providers that are enabled", async () => {
+ const providers = [
+ {
+ id: "foo",
+ enabled: false,
+ type: "remote",
+ url: "https://www.foo.com/",
+ },
+ {
+ id: "bar",
+ enabled: true,
+ type: "remote",
+ url: "https://www.bar.com/",
+ },
+ ];
+ setMessageProviderPref(providers);
+ await Router._updateMessageProviders();
+ assert.equal(Router.state.providers.length, 1);
+ assert.equal(Router.state.providers[0].id, providers[1].id);
+ });
+ });
+
+ describe("#handleMessageRequest", () => {
+ beforeEach(async () => {
+ await Router.setState(() => ({
+ providers: [{ id: "snippets" }, { id: "badge" }],
+ }));
+ });
+ it("should not return a blocked message", async () => {
+ // Block all messages except the first
+ await Router.setState(() => ({
+ messages: [
+ { id: "foo", provider: "snippets", groups: ["snippets"] },
+ { id: "bar", provider: "snippets", groups: ["snippets"] },
+ ],
+ messageBlockList: ["foo"],
+ }));
+ await Router.handleMessageRequest({
+ provider: "snippets",
+ });
+ assert.calledWithMatch(ASRouterTargeting.findMatchingMessage, {
+ messages: [{ id: "bar", provider: "snippets", groups: ["snippets"] }],
+ });
+ });
+ it("should not return a message from a disabled group", async () => {
+ ASRouterTargeting.findMatchingMessage.callsFake(
+ ({ messages }) => messages[0]
+ );
+ // Block all messages except the first
+ await Router.setState(() => ({
+ messages: [
+ { id: "foo", provider: "snippets", groups: ["snippets"] },
+ { id: "bar", provider: "snippets", groups: ["snippets"] },
+ ],
+ groups: [{ id: "snippets", enabled: false }],
+ }));
+ const result = await Router.handleMessageRequest({
+ provider: "snippets",
+ });
+ assert.isNull(result);
+ });
+ it("should not return a message from a blocked campaign", async () => {
+ // Block all messages except the first
+ await Router.setState(() => ({
+ messages: [
+ {
+ id: "foo",
+ provider: "snippets",
+ campaign: "foocampaign",
+ groups: ["snippets"],
+ },
+ { id: "bar", provider: "snippets", groups: ["snippets"] },
+ ],
+ messageBlockList: ["foocampaign"],
+ }));
+
+ await Router.handleMessageRequest({
+ provider: "snippets",
+ });
+ assert.calledWithMatch(ASRouterTargeting.findMatchingMessage, {
+ messages: [{ id: "bar", provider: "snippets", groups: ["snippets"] }],
+ });
+ });
+ it("should not return a message excluded by the provider", async () => {
+ // There are only two providers; block the FAKE_LOCAL_PROVIDER, leaving
+ // only FAKE_REMOTE_PROVIDER unblocked, which provides only one message
+ await Router.setState(() => ({
+ providers: [{ id: "snippets", exclude: ["foo"] }],
+ }));
+
+ await Router.setState(() => ({
+ messages: [{ id: "foo", provider: "snippets" }],
+ messageBlockList: ["foocampaign"],
+ }));
+
+ const result = await Router.handleMessageRequest({
+ provider: "snippets",
+ });
+ assert.isNull(result);
+ });
+ it("should not return a message if the frequency cap has been hit", async () => {
+ sandbox.stub(Router, "isBelowFrequencyCaps").returns(false);
+ await Router.setState(() => ({
+ messages: [{ id: "foo", provider: "snippets" }],
+ }));
+ const result = await Router.handleMessageRequest({
+ provider: "snippets",
+ });
+ assert.isNull(result);
+ });
+ it("should get unblocked messages that match the trigger", async () => {
+ const message1 = {
+ id: "1",
+ campaign: "foocampaign",
+ trigger: { id: "foo" },
+ groups: ["snippets"],
+ provider: "snippets",
+ };
+ const message2 = {
+ id: "2",
+ campaign: "foocampaign",
+ trigger: { id: "bar" },
+ groups: ["snippets"],
+ provider: "snippets",
+ };
+ await Router.setState({ messages: [message2, message1] });
+ // Just return the first message provided as arg
+ ASRouterTargeting.findMatchingMessage.callsFake(
+ ({ messages }) => messages[0]
+ );
+
+ const result = Router.handleMessageRequest({ triggerId: "foo" });
+
+ assert.deepEqual(result, message1);
+ });
+ it("should get unblocked messages that match trigger and template", async () => {
+ const message1 = {
+ id: "1",
+ campaign: "foocampaign",
+ template: "badge",
+ trigger: { id: "foo" },
+ groups: ["badge"],
+ provider: "badge",
+ };
+ const message2 = {
+ id: "2",
+ campaign: "foocampaign",
+ template: "snippet",
+ trigger: { id: "foo" },
+ groups: ["snippets"],
+ provider: "snippets",
+ };
+ await Router.setState({ messages: [message2, message1] });
+ // Just return the first message provided as arg
+ ASRouterTargeting.findMatchingMessage.callsFake(
+ ({ messages }) => messages[0]
+ );
+
+ const result = Router.handleMessageRequest({
+ triggerId: "foo",
+ template: "badge",
+ });
+
+ assert.deepEqual(result, message1);
+ });
+ it("should have messageImpressions in the message context", () => {
+ assert.propertyVal(
+ Router._getMessagesContext(),
+ "messageImpressions",
+ Router.state.messageImpressions
+ );
+ });
+ it("should return all unblocked messages that match the template, trigger if returnAll=true", async () => {
+ const message1 = {
+ provider: "whats_new",
+ id: "1",
+ template: "whatsnew_panel_message",
+ trigger: { id: "whatsNewPanelOpened" },
+ groups: ["whats_new"],
+ };
+ const message2 = {
+ provider: "whats_new",
+ id: "2",
+ template: "whatsnew_panel_message",
+ trigger: { id: "whatsNewPanelOpened" },
+ groups: ["whats_new"],
+ };
+ const message3 = {
+ provider: "whats_new",
+ id: "3",
+ template: "badge",
+ groups: ["whats_new"],
+ };
+ ASRouterTargeting.findMatchingMessage.callsFake(() => [
+ message2,
+ message1,
+ ]);
+ await Router.setState({
+ messages: [message3, message2, message1],
+ providers: [{ id: "whats_new" }],
+ });
+ const result = await Router.handleMessageRequest({
+ template: "whatsnew_panel_message",
+ triggerId: "whatsNewPanelOpened",
+ returnAll: true,
+ });
+
+ assert.deepEqual(result, [message2, message1]);
+ });
+ it("should forward trigger param info", async () => {
+ const trigger = {
+ triggerId: "foo",
+ triggerParam: "bar",
+ triggerContext: "context",
+ };
+ const message1 = {
+ id: "1",
+ campaign: "foocampaign",
+ trigger: { id: "foo" },
+ groups: ["snippets"],
+ provider: "snippets",
+ };
+ const message2 = {
+ id: "2",
+ campaign: "foocampaign",
+ trigger: { id: "bar" },
+ groups: ["badge"],
+ provider: "badge",
+ };
+ await Router.setState({ messages: [message2, message1] });
+ // Just return the first message provided as arg
+
+ Router.handleMessageRequest(trigger);
+
+ assert.calledOnce(ASRouterTargeting.findMatchingMessage);
+
+ const [options] = ASRouterTargeting.findMatchingMessage.firstCall.args;
+ assert.propertyVal(options.trigger, "id", trigger.triggerId);
+ assert.propertyVal(options.trigger, "param", trigger.triggerParam);
+ assert.propertyVal(options.trigger, "context", trigger.triggerContext);
+ });
+ it("should cache snippets messages", async () => {
+ const trigger = {
+ triggerId: "foo",
+ triggerParam: "bar",
+ triggerContext: "context",
+ };
+ const message1 = {
+ id: "1",
+ provider: "snippets",
+ campaign: "foocampaign",
+ trigger: { id: "foo" },
+ groups: ["snippets"],
+ };
+ const message2 = {
+ id: "2",
+ campaign: "foocampaign",
+ trigger: { id: "bar" },
+ groups: ["snippets"],
+ };
+ await Router.setState({ messages: [message2, message1] });
+
+ Router.handleMessageRequest(trigger);
+
+ assert.calledOnce(ASRouterTargeting.findMatchingMessage);
+
+ const [options] = ASRouterTargeting.findMatchingMessage.firstCall.args;
+ assert.propertyVal(options, "shouldCache", true);
+ });
+ it("should not cache badge messages", async () => {
+ const trigger = {
+ triggerId: "bar",
+ triggerParam: "bar",
+ triggerContext: "context",
+ };
+ const message1 = {
+ id: "1",
+ provider: "snippets",
+ campaign: "foocampaign",
+ trigger: { id: "foo" },
+ groups: ["snippets"],
+ };
+ const message2 = {
+ id: "2",
+ campaign: "foocampaign",
+ trigger: { id: "bar" },
+ groups: ["badge"],
+ provider: "badge",
+ };
+ await Router.setState({ messages: [message2, message1] });
+ // Just return the first message provided as arg
+
+ Router.handleMessageRequest(trigger);
+
+ assert.calledOnce(ASRouterTargeting.findMatchingMessage);
+
+ const [options] = ASRouterTargeting.findMatchingMessage.firstCall.args;
+ assert.propertyVal(options, "shouldCache", false);
+ });
+ it("should filter out messages without a trigger (or different) when a triggerId is defined", async () => {
+ const trigger = { triggerId: "foo" };
+ const message1 = {
+ id: "1",
+ campaign: "foocampaign",
+ trigger: { id: "foo" },
+ groups: ["snippets"],
+ provider: "snippets",
+ };
+ const message2 = {
+ id: "2",
+ campaign: "foocampaign",
+ trigger: { id: "bar" },
+ groups: ["snippets"],
+ provider: "snippets",
+ };
+ const message3 = {
+ id: "3",
+ campaign: "bazcampaign",
+ groups: ["snippets"],
+ provider: "snippets",
+ };
+ await Router.setState({
+ messages: [message2, message1, message3],
+ groups: [{ id: "snippets", enabled: true }],
+ });
+ // Just return the first message provided as arg
+ ASRouterTargeting.findMatchingMessage.callsFake(args => args.messages);
+
+ const result = Router.handleMessageRequest(trigger);
+
+ assert.lengthOf(result, 1);
+ assert.deepEqual(result[0], message1);
+ });
+ });
+
+ describe("#uninit", () => {
+ it("should unregister the trigger listeners", () => {
+ for (const listener of ASRouterTriggerListeners.values()) {
+ sandbox.spy(listener, "uninit");
+ }
+
+ Router.uninit();
+
+ for (const listener of ASRouterTriggerListeners.values()) {
+ assert.calledOnce(listener.uninit);
+ }
+ });
+ it("should set .dispatchCFRAction to null", () => {
+ Router.uninit();
+ assert.isNull(Router.dispatchCFRAction);
+ assert.isNull(Router.clearChildMessages);
+ assert.isNull(Router.sendTelemetry);
+ });
+ it("should save previousSessionEnd", () => {
+ Router.uninit();
+
+ assert.calledOnce(Router._storage.set);
+ assert.calledWithExactly(
+ Router._storage.set,
+ "previousSessionEnd",
+ sinon.match.number
+ );
+ });
+ it("should remove the observer for `intl:app-locales-changed`", () => {
+ sandbox.spy(global.Services.obs, "removeObserver");
+ Router.uninit();
+
+ assert.calledOnce(global.Services.obs.removeObserver);
+ assert.equal(
+ global.Services.obs.removeObserver.args[0][1],
+ "intl:app-locales-changed"
+ );
+ });
+ it("should remove the pref observer for `USE_REMOTE_L10N_PREF`", async () => {
+ sandbox.spy(global.Services.prefs, "removeObserver");
+ Router.uninit();
+
+ // Grab the last call as #uninit() also involves multiple calls of `Services.prefs.removeObserver`.
+ const call = global.Services.prefs.removeObserver.lastCall;
+ assert.calledWithExactly(call, USE_REMOTE_L10N_PREF, Router);
+ });
+ });
+
+ describe("sendNewTabMessage", () => {
+ it("should construct an appropriate response message", async () => {
+ Router.loadMessagesFromAllProviders.resetHistory();
+ Router.loadMessagesFromAllProviders.onFirstCall().resolves();
+
+ let message = {
+ id: "foo",
+ provider: "snippets",
+ groups: ["snippets"],
+ };
+
+ await Router.setState({
+ messages: [message],
+ providers: [{ id: "snippets" }],
+ });
+
+ ASRouterTargeting.findMatchingMessage.callsFake(
+ ({ messages }) => messages[0]
+ );
+
+ let response = await Router.sendNewTabMessage({
+ tabId: 0,
+ browser: {},
+ });
+
+ assert.deepEqual(response.message, message);
+ });
+ it("should send an empty object message if no messages are available", async () => {
+ await Router.setState({ messages: [] });
+ let response = await Router.sendNewTabMessage({
+ tabId: 0,
+ browser: {},
+ });
+
+ assert.deepEqual(response.message, {});
+ });
+
+ describe("#addPreviewEndpoint", () => {
+ it("should make a request to the provided endpoint", async () => {
+ const url = "https://snippets-admin.mozilla.org/foo";
+ const browser = {};
+ browser.sendMessageToActor = sandbox.stub();
+
+ await Router.sendNewTabMessage({
+ endpoint: { url },
+ tabId: 0,
+ browser,
+ });
+
+ assert.calledWith(global.fetch, url);
+ assert.lengthOf(
+ Router.state.providers.filter(p => p.url === url),
+ 0
+ );
+ });
+ it("should send EnterSnippetPreviewMode when adding a preview endpoint", async () => {
+ const url = "https://snippets-admin.mozilla.org/foo";
+ const browser = {};
+ browser.sendMessageToActor = sandbox.stub();
+
+ await Router.addPreviewEndpoint(url, browser);
+
+ assert.calledWithExactly(
+ browser.sendMessageToActor,
+ "EnterSnippetsPreviewMode",
+ {},
+ "ASRouter"
+ );
+ });
+ it("should not add a url that is not from an allowed host", async () => {
+ const url = "https://mozilla.org";
+ const browser = {};
+ browser.sendMessageToActor = sandbox.stub();
+
+ await Router.addPreviewEndpoint(url, browser);
+
+ assert.lengthOf(
+ Router.state.providers.filter(p => p.url === url),
+ 0
+ );
+ });
+ it("should reject bad urls", async () => {
+ const url = "foo";
+ const browser = {};
+ browser.sendMessageToActor = sandbox.stub();
+
+ await Router.addPreviewEndpoint(url, browser);
+
+ assert.lengthOf(
+ Router.state.providers.filter(p => p.url === url),
+ 0
+ );
+ });
+ });
+
+ it("should record telemetry for message request duration", async () => {
+ const startTelemetryStopwatch = sandbox.stub(
+ global.TelemetryStopwatch,
+ "start"
+ );
+ const finishTelemetryStopwatch = sandbox.stub(
+ global.TelemetryStopwatch,
+ "finish"
+ );
+ sandbox.stub(Router, "handleMessageRequest");
+ const tabId = 123;
+ await Router.sendNewTabMessage({
+ tabId,
+ browser: {},
+ });
+
+ assert.calledOnce(startTelemetryStopwatch);
+ assert.calledWithExactly(
+ startTelemetryStopwatch,
+ "MS_MESSAGE_REQUEST_TIME_MS",
+ { tabId }
+ );
+ assert.calledOnce(finishTelemetryStopwatch);
+ assert.calledWithExactly(
+ finishTelemetryStopwatch,
+ "MS_MESSAGE_REQUEST_TIME_MS",
+ { tabId }
+ );
+ });
+ it("should return the preview message if that's available and remove it from Router.state", async () => {
+ const expectedObj = {
+ id: "foo",
+ groups: ["preview"],
+ provider: "preview",
+ };
+ await Router.setState({
+ messages: [expectedObj],
+ providers: [{ id: "preview" }],
+ });
+
+ ASRouterTargeting.findMatchingMessage.callsFake(
+ ({ messages }) => expectedObj
+ );
+
+ Router.loadMessagesFromAllProviders.resetHistory();
+ Router.loadMessagesFromAllProviders.onFirstCall().resolves();
+
+ let response = await Router.sendNewTabMessage({
+ endpoint: { url: "foo.com" },
+ tabId: 0,
+ browser: {},
+ });
+
+ assert.deepEqual(response.message, expectedObj);
+
+ assert.isUndefined(
+ Router.state.messages.find(m => m.provider === "preview")
+ );
+ });
+ });
+
+ describe("#setMessageById", async () => {
+ it("should send an empty message if provided id did not resolve to a message", async () => {
+ let response = await Router.setMessageById({ id: -1 }, true, {});
+ assert.deepEqual(response.message, {});
+ });
+ });
+
+ describe("#isUnblockedMessage", () => {
+ it("should block a message if the group is blocked", async () => {
+ const msg = { id: "msg1", groups: ["foo"], provider: "unit-test" };
+ await Router.setState({
+ groups: [{ id: "foo", enabled: false }],
+ messages: [msg],
+ providers: [{ id: "unit-test" }],
+ });
+ assert.isFalse(Router.isUnblockedMessage(msg));
+
+ await Router.setState({ groups: [{ id: "foo", enabled: true }] });
+
+ assert.isTrue(Router.isUnblockedMessage(msg));
+ });
+ it("should block a message if at least one group is blocked", async () => {
+ const msg = {
+ id: "msg1",
+ groups: ["foo", "bar"],
+ provider: "unit-test",
+ };
+ await Router.setState({
+ groups: [
+ { id: "foo", enabled: false },
+ { id: "bar", enabled: false },
+ ],
+ messages: [msg],
+ providers: [{ id: "unit-test" }],
+ });
+ assert.isFalse(Router.isUnblockedMessage(msg));
+
+ await Router.setState({
+ groups: [
+ { id: "foo", enabled: true },
+ { id: "bar", enabled: false },
+ ],
+ });
+
+ assert.isFalse(Router.isUnblockedMessage(msg));
+ });
+ });
+
+ describe("#blockMessageById", () => {
+ it("should add the id to the messageBlockList", async () => {
+ await Router.blockMessageById("foo");
+ assert.isTrue(Router.state.messageBlockList.includes("foo"));
+ });
+ it("should add the campaign to the messageBlockList instead of id if .campaign is specified and not select messages of that campaign again", async () => {
+ await Router.setState({
+ messages: [
+ { id: "1", campaign: "foocampaign" },
+ { id: "2", campaign: "foocampaign" },
+ ],
+ });
+ await Router.blockMessageById("1");
+
+ assert.isTrue(Router.state.messageBlockList.includes("foocampaign"));
+ assert.isEmpty(Router.state.messages.filter(Router.isUnblockedMessage));
+ });
+ it("should be able to add multiple items to the messageBlockList", async () => {
+ await await Router.blockMessageById(FAKE_BUNDLE.map(b => b.id));
+ assert.isTrue(Router.state.messageBlockList.includes(FAKE_BUNDLE[0].id));
+ assert.isTrue(Router.state.messageBlockList.includes(FAKE_BUNDLE[1].id));
+ });
+ it("should save the messageBlockList", async () => {
+ await await Router.blockMessageById(FAKE_BUNDLE.map(b => b.id));
+ assert.calledWithExactly(Router._storage.set, "messageBlockList", [
+ FAKE_BUNDLE[0].id,
+ FAKE_BUNDLE[1].id,
+ ]);
+ });
+ });
+
+ describe("#unblockMessageById", () => {
+ it("should remove the id from the messageBlockList", async () => {
+ await Router.blockMessageById("foo");
+ assert.isTrue(Router.state.messageBlockList.includes("foo"));
+ await Router.unblockMessageById("foo");
+ assert.isFalse(Router.state.messageBlockList.includes("foo"));
+ });
+ it("should remove the campaign from the messageBlockList if it is defined", async () => {
+ await Router.setState({ messages: [{ id: "1", campaign: "foo" }] });
+ await Router.blockMessageById("1");
+ assert.isTrue(
+ Router.state.messageBlockList.includes("foo"),
+ "blocklist has campaign id"
+ );
+ await Router.unblockMessageById("1");
+ assert.isFalse(
+ Router.state.messageBlockList.includes("foo"),
+ "campaign id removed from blocklist"
+ );
+ });
+ it("should save the messageBlockList", async () => {
+ await Router.unblockMessageById("foo");
+ assert.calledWithExactly(Router._storage.set, "messageBlockList", []);
+ });
+ });
+
+ describe("#routeCFRMessage", () => {
+ it("should allow for echoing back message modifications", () => {
+ const message = { somekey: "some value" };
+ const data = { content: message };
+ const browser = {};
+ let msg = Router.routeCFRMessage(data.content, browser, data, false);
+ assert.deepEqual(msg.message, message);
+ });
+ it("should call CFRPageActions.forceRecommendation if the template is cfr_action and force is true", async () => {
+ sandbox.stub(CFRPageActions, "forceRecommendation");
+ const testMessage = { id: "foo", template: "cfr_doorhanger" };
+ await Router.setState({ messages: [testMessage] });
+ Router.routeCFRMessage(testMessage, {}, null, true);
+
+ assert.calledOnce(CFRPageActions.forceRecommendation);
+ });
+ it("should call BookmarkPanelHub.forceShowMessage the provider is cfr-fxa", async () => {
+ const testMessage = { id: "foo", template: "fxa_bookmark_panel" };
+ await Router.setState({ messages: [testMessage] });
+ Router.routeCFRMessage(testMessage, {}, null, true);
+ assert.calledOnce(FakeBookmarkPanelHub.forceShowMessage);
+ });
+ it("should call CFRPageActions.addRecommendation if the template is cfr_action and force is false", async () => {
+ sandbox.stub(CFRPageActions, "addRecommendation");
+ const testMessage = { id: "foo", template: "cfr_doorhanger" };
+ await Router.setState({ messages: [testMessage] });
+ Router.routeCFRMessage(testMessage, {}, {}, false);
+ assert.calledOnce(CFRPageActions.addRecommendation);
+ });
+ });
+
+ describe("#updateTargetingParameters", () => {
+ it("should return an object containing the whole state", async () => {
+ sandbox.stub(Router, "getTargetingParameters").resolves({});
+ let msg = await Router.updateTargetingParameters();
+ let expected = Object.assign({}, Router.state, {
+ providerPrefs: ASRouterPreferences.providers,
+ userPrefs: ASRouterPreferences.getAllUserPreferences(),
+ targetingParameters: {},
+ errors: Router.errors,
+ });
+
+ assert.deepEqual(msg, expected);
+ });
+ });
+
+ describe("#sendTriggerMessage", () => {
+ it("should pass the trigger to ASRouterTargeting when sending trigger message", async () => {
+ await Router.setState({
+ messages: [
+ {
+ id: "foo1",
+ provider: "onboarding",
+ template: "onboarding",
+ trigger: { id: "firstRun" },
+ content: { title: "Foo1", body: "Foo123-1" },
+ groups: ["onboarding"],
+ },
+ ],
+ providers: [{ id: "onboarding" }],
+ });
+
+ Router.loadMessagesFromAllProviders.resetHistory();
+ Router.loadMessagesFromAllProviders.onFirstCall().resolves();
+
+ await Router.sendTriggerMessage({
+ tabId: 0,
+ browser: {},
+ id: "firstRun",
+ });
+
+ assert.calledOnce(ASRouterTargeting.findMatchingMessage);
+ assert.deepEqual(
+ ASRouterTargeting.findMatchingMessage.firstCall.args[0].trigger,
+ {
+ id: "firstRun",
+ param: undefined,
+ context: undefined,
+ }
+ );
+ });
+ it("should record telemetry information", async () => {
+ const startTelemetryStopwatch = sandbox.stub(
+ global.TelemetryStopwatch,
+ "start"
+ );
+ const finishTelemetryStopwatch = sandbox.stub(
+ global.TelemetryStopwatch,
+ "finish"
+ );
+
+ const tabId = 123;
+
+ await Router.sendTriggerMessage({
+ tabId,
+ browser: {},
+ id: "firstRun",
+ });
+
+ assert.calledOnce(startTelemetryStopwatch);
+ assert.calledWithExactly(
+ startTelemetryStopwatch,
+ "MS_MESSAGE_REQUEST_TIME_MS",
+ { tabId }
+ );
+ assert.calledOnce(finishTelemetryStopwatch);
+ assert.calledWithExactly(
+ finishTelemetryStopwatch,
+ "MS_MESSAGE_REQUEST_TIME_MS",
+ { tabId }
+ );
+ });
+ it("should have previousSessionEnd in the message context", () => {
+ assert.propertyVal(
+ Router._getMessagesContext(),
+ "previousSessionEnd",
+ 100
+ );
+ });
+ it("should record the Reach event if found any", async () => {
+ let messages = [
+ {
+ id: "foo1",
+ forReachEvent: { sent: false, group: "cfr" },
+ experimentSlug: "exp01",
+ branchSlug: "branch01",
+ template: "simple_template",
+ trigger: { id: "foo" },
+ content: { title: "Foo1", body: "Foo123-1" },
+ },
+ {
+ id: "foo2",
+ template: "simple_template",
+ trigger: { id: "bar" },
+ content: { title: "Foo2", body: "Foo123-2" },
+ provider: "onboarding",
+ },
+ {
+ id: "foo3",
+ forReachEvent: { sent: false, group: "cfr" },
+ experimentSlug: "exp02",
+ branchSlug: "branch02",
+ template: "simple_template",
+ trigger: { id: "foo" },
+ content: { title: "Foo1", body: "Foo123-1" },
+ },
+ ];
+ sandbox.stub(Router, "handleMessageRequest").resolves(messages);
+ sandbox.spy(Services.telemetry, "recordEvent");
+
+ await Router.sendTriggerMessage({
+ tabId: 0,
+ browser: {},
+ id: "foo",
+ });
+
+ assert.calledTwice(Services.telemetry.recordEvent);
+ });
+ it("should not record the Reach event if it's already sent", async () => {
+ let messages = [
+ {
+ id: "foo1",
+ forReachEvent: { sent: true, group: "cfr" },
+ experimentSlug: "exp01",
+ branchSlug: "branch01",
+ template: "simple_template",
+ trigger: { id: "foo" },
+ content: { title: "Foo1", body: "Foo123-1" },
+ },
+ ];
+ sandbox.stub(Router, "handleMessageRequest").resolves(messages);
+ sandbox.spy(Services.telemetry, "recordEvent");
+
+ await Router.sendTriggerMessage({
+ tabId: 0,
+ browser: {},
+ id: "foo",
+ });
+ assert.notCalled(Services.telemetry.recordEvent);
+ });
+ it("should record the Exposure event if found any", async () => {
+ let messages = [
+ {
+ id: "foo1",
+ forExposureEvent: {
+ sent: false,
+ experimentSlug: "foo",
+ branchSlug: "bar",
+ },
+ experimentSlug: "exp01",
+ branchSlug: "branch01",
+ template: "simple_template",
+ trigger: { id: "foo" },
+ content: { title: "Foo1", body: "Foo123-1" },
+ },
+ ];
+ sandbox.stub(Router, "handleMessageRequest").resolves(messages);
+ sandbox.spy(Services.telemetry, "recordEvent");
+
+ await Router.sendTriggerMessage({
+ tabId: 0,
+ browser: {},
+ id: "foo",
+ });
+
+ assert.calledOnce(global.ExperimentAPI.recordExposureEvent);
+ assert.calledWithExactly(
+ global.ExperimentAPI.recordExposureEvent,
+ "cfr",
+ messages[0].forExposureEvent
+ );
+ });
+ });
+
+ describe("forceAttribution", () => {
+ let setReferrerUrl;
+ beforeEach(() => {
+ setReferrerUrl = sinon.spy();
+ global.Cc["@mozilla.org/mac-attribution;1"] = {
+ getService: () => ({ setReferrerUrl }),
+ };
+ global.Cc["@mozilla.org/process/environment;1"] = {
+ getService: () => ({ set: sandbox.stub() }),
+ };
+ });
+ it("should double encode on windows", async () => {
+ sandbox.stub(fakeAttributionCode, "writeAttributionFile");
+
+ Router.forceAttribution({ foo: "FOO!", eh: "NOPE", bar: "BAR?" });
+
+ assert.notCalled(setReferrerUrl);
+ assert.calledWithMatch(
+ fakeAttributionCode.writeAttributionFile,
+ "foo%3DFOO!%26bar%3DBAR%253F"
+ );
+ });
+ it("should set referrer on mac", async () => {
+ sandbox.stub(AppConstants, "platform").value("macosx");
+
+ Router.forceAttribution({ foo: "FOO!", eh: "NOPE", bar: "BAR?" });
+
+ assert.calledOnce(setReferrerUrl);
+ assert.calledWithMatch(setReferrerUrl, "", "?foo=FOO!&bar=BAR%3F");
+ });
+ });
+
+ describe("#forceWNPanel", () => {
+ let browser = {
+ ownerGlobal: {
+ document: new Document(),
+ PanelUI: {
+ showSubView: sinon.stub(),
+ panel: {
+ setAttribute: sinon.stub(),
+ },
+ },
+ },
+ };
+ let fakePanel = {
+ setAttribute: sinon.stub(),
+ };
+ sinon
+ .stub(browser.ownerGlobal.document, "getElementById")
+ .returns(fakePanel);
+
+ it("should call enableToolbarButton", async () => {
+ await Router.forceWNPanel(browser);
+ assert.calledOnce(FakeToolbarPanelHub.enableToolbarButton);
+ assert.calledOnce(browser.ownerGlobal.PanelUI.showSubView);
+ assert.calledWith(fakePanel.setAttribute, "noautohide", true);
+ });
+ });
+
+ describe("_triggerHandler", () => {
+ it("should call #sendTriggerMessage with the correct trigger", () => {
+ const getter = sandbox.stub();
+ getter.returns(false);
+ sandbox.stub(global.BrowserHandler, "kiosk").get(getter);
+ sinon.spy(Router, "sendTriggerMessage");
+ const browser = {};
+ const trigger = { id: "FAKE_TRIGGER", param: "some fake param" };
+ Router._triggerHandler(browser, trigger);
+ assert.calledOnce(Router.sendTriggerMessage);
+ assert.calledWith(
+ Router.sendTriggerMessage,
+ sandbox.match({
+ id: "FAKE_TRIGGER",
+ param: "some fake param",
+ })
+ );
+ });
+ });
+
+ describe("_triggerHandler_kiosk", () => {
+ it("should not call #sendTriggerMessage", () => {
+ const getter = sandbox.stub();
+ getter.returns(true);
+ sandbox.stub(global.BrowserHandler, "kiosk").get(getter);
+ sinon.spy(Router, "sendTriggerMessage");
+ const browser = {};
+ const trigger = { id: "FAKE_TRIGGER", param: "some fake param" };
+ Router._triggerHandler(browser, trigger);
+ assert.notCalled(Router.sendTriggerMessage);
+ });
+ });
+
+ describe("valid preview endpoint", () => {
+ it("should report an error if url protocol is not https", () => {
+ sandbox.stub(Cu, "reportError");
+
+ assert.equal(false, Router._validPreviewEndpoint("http://foo.com"));
+ assert.calledTwice(Cu.reportError);
+ });
+ });
+
+ describe("impressions", () => {
+ describe("frequency normalisation", () => {
+ beforeEach(async () => {
+ const messages = [
+ { frequency: { custom: [{ period: "daily", cap: 10 }] } },
+ ];
+ const provider = {
+ id: "foo",
+ frequency: { custom: [{ period: "daily", cap: 100 }] },
+ messages,
+ enabled: true,
+ };
+ await createRouterAndInit([provider]);
+ });
+ it("period aliases in provider frequency caps should be normalised", () => {
+ const [provider] = Router.state.providers;
+ assert.equal(provider.frequency.custom[0].period, "daily");
+ });
+ it("period aliases in message frequency caps should be normalised", async () => {
+ const [message] = Router.state.messages;
+ assert.equal(message.frequency.custom[0].period, "daily");
+ });
+ });
+
+ describe("#isBelowFrequencyCaps", () => {
+ it("should call #_isBelowItemFrequencyCap for the message and for the provider with the correct impressions and arguments", async () => {
+ sinon.spy(Router, "_isBelowItemFrequencyCap");
+
+ const MAX_MESSAGE_LIFETIME_CAP = 100; // Defined in ASRouter
+ const fooMessageImpressions = [0, 1];
+ const barGroupImpressions = [0, 1, 2];
+
+ const message = {
+ id: "foo",
+ provider: "bar",
+ groups: ["bar"],
+ frequency: { lifetime: 3 },
+ };
+ const groups = [{ id: "bar", frequency: { lifetime: 5 } }];
+
+ await Router.setState(state => {
+ // Add provider
+ const providers = [...state.providers];
+ // Add fooMessageImpressions
+ // eslint-disable-next-line no-shadow
+ const messageImpressions = Object.assign(
+ {},
+ state.messageImpressions
+ );
+ let gImpressions = {};
+ gImpressions.bar = barGroupImpressions;
+ messageImpressions.foo = fooMessageImpressions;
+ return {
+ providers,
+ messageImpressions,
+ groups,
+ groupImpressions: gImpressions,
+ };
+ });
+
+ await Router.isBelowFrequencyCaps(message);
+
+ assert.calledTwice(Router._isBelowItemFrequencyCap);
+ assert.calledWithExactly(
+ Router._isBelowItemFrequencyCap,
+ message,
+ fooMessageImpressions,
+ MAX_MESSAGE_LIFETIME_CAP
+ );
+ assert.calledWithExactly(
+ Router._isBelowItemFrequencyCap,
+ groups[0],
+ barGroupImpressions
+ );
+ });
+ });
+
+ describe("#_isBelowItemFrequencyCap", () => {
+ it("should return false if the # of impressions exceeds the maxLifetimeCap", () => {
+ const item = { id: "foo", frequency: { lifetime: 5 } };
+ const impressions = [0, 1];
+ const maxLifetimeCap = 1;
+ const result = Router._isBelowItemFrequencyCap(
+ item,
+ impressions,
+ maxLifetimeCap
+ );
+ assert.isFalse(result);
+ });
+
+ describe("lifetime frequency caps", () => {
+ it("should return true if .frequency is not defined on the item", () => {
+ const item = { id: "foo" };
+ const impressions = [0, 1];
+ const result = Router._isBelowItemFrequencyCap(item, impressions);
+ assert.isTrue(result);
+ });
+ it("should return true if there are no impressions", () => {
+ const item = {
+ id: "foo",
+ frequency: {
+ lifetime: 10,
+ custom: [{ period: ONE_DAY_IN_MS, cap: 2 }],
+ },
+ };
+ const impressions = [];
+ const result = Router._isBelowItemFrequencyCap(item, impressions);
+ assert.isTrue(result);
+ });
+ it("should return true if the # of impressions is less than .frequency.lifetime of the item", () => {
+ const item = { id: "foo", frequency: { lifetime: 3 } };
+ const impressions = [0, 1];
+ const result = Router._isBelowItemFrequencyCap(item, impressions);
+ assert.isTrue(result);
+ });
+ it("should return false if the # of impressions is equal to .frequency.lifetime of the item", async () => {
+ const item = { id: "foo", frequency: { lifetime: 3 } };
+ const impressions = [0, 1, 2];
+ const result = Router._isBelowItemFrequencyCap(item, impressions);
+ assert.isFalse(result);
+ });
+ it("should return false if the # of impressions is greater than .frequency.lifetime of the item", async () => {
+ const item = { id: "foo", frequency: { lifetime: 3 } };
+ const impressions = [0, 1, 2, 3];
+ const result = Router._isBelowItemFrequencyCap(item, impressions);
+ assert.isFalse(result);
+ });
+ });
+
+ describe("custom frequency caps", () => {
+ it("should return true if impressions in the time period < the cap and total impressions < the lifetime cap", () => {
+ clock.tick(ONE_DAY_IN_MS + 10);
+ const item = {
+ id: "foo",
+ frequency: {
+ custom: [{ period: ONE_DAY_IN_MS, cap: 2 }],
+ lifetime: 3,
+ },
+ };
+ const impressions = [0, ONE_DAY_IN_MS + 1];
+ const result = Router._isBelowItemFrequencyCap(item, impressions);
+ assert.isTrue(result);
+ });
+ it("should return false if impressions in the time period > the cap and total impressions < the lifetime cap", () => {
+ clock.tick(200);
+ const item = {
+ id: "msg1",
+ frequency: { custom: [{ period: 100, cap: 2 }], lifetime: 3 },
+ };
+ const impressions = [0, 160, 161];
+ const result = Router._isBelowItemFrequencyCap(item, impressions);
+ assert.isFalse(result);
+ });
+ it("should return false if impressions in one of the time periods > the cap and total impressions < the lifetime cap", () => {
+ clock.tick(ONE_DAY_IN_MS + 200);
+ const itemTrue = {
+ id: "msg2",
+ frequency: { custom: [{ period: 100, cap: 2 }] },
+ };
+ const itemFalse = {
+ id: "msg1",
+ frequency: {
+ custom: [
+ { period: 100, cap: 2 },
+ { period: ONE_DAY_IN_MS, cap: 3 },
+ ],
+ },
+ };
+ const impressions = [
+ 0,
+ ONE_DAY_IN_MS + 160,
+ ONE_DAY_IN_MS - 100,
+ ONE_DAY_IN_MS - 200,
+ ];
+ assert.isTrue(Router._isBelowItemFrequencyCap(itemTrue, impressions));
+ assert.isFalse(
+ Router._isBelowItemFrequencyCap(itemFalse, impressions)
+ );
+ });
+ it("should return false if impressions in the time period < the cap and total impressions > the lifetime cap", () => {
+ clock.tick(ONE_DAY_IN_MS + 10);
+ const item = {
+ id: "msg1",
+ frequency: {
+ custom: [{ period: ONE_DAY_IN_MS, cap: 2 }],
+ lifetime: 3,
+ },
+ };
+ const impressions = [0, 1, 2, 3, ONE_DAY_IN_MS + 1];
+ const result = Router._isBelowItemFrequencyCap(item, impressions);
+ assert.isFalse(result);
+ });
+ it("should return true if daily impressions < the daily cap and there is no lifetime cap", () => {
+ clock.tick(ONE_DAY_IN_MS + 10);
+ const item = {
+ id: "msg1",
+ frequency: { custom: [{ period: ONE_DAY_IN_MS, cap: 2 }] },
+ };
+ const impressions = [0, 1, 2, 3, ONE_DAY_IN_MS + 1];
+ const result = Router._isBelowItemFrequencyCap(item, impressions);
+ assert.isTrue(result);
+ });
+ it("should return false if daily impressions > the daily cap and there is no lifetime cap", () => {
+ clock.tick(ONE_DAY_IN_MS + 10);
+ const item = {
+ id: "msg1",
+ frequency: { custom: [{ period: ONE_DAY_IN_MS, cap: 2 }] },
+ };
+ const impressions = [
+ 0,
+ 1,
+ 2,
+ 3,
+ ONE_DAY_IN_MS + 1,
+ ONE_DAY_IN_MS + 2,
+ ONE_DAY_IN_MS + 3,
+ ];
+ const result = Router._isBelowItemFrequencyCap(item, impressions);
+ assert.isFalse(result);
+ });
+ });
+ });
+
+ describe("#getLongestPeriod", () => {
+ it("should return the period if there is only one definition", () => {
+ const message = {
+ id: "foo",
+ frequency: { custom: [{ period: 200, cap: 2 }] },
+ };
+ assert.equal(Router.getLongestPeriod(message), 200);
+ });
+ it("should return the longest period if there are more than one definitions", () => {
+ const message = {
+ id: "foo",
+ frequency: {
+ custom: [
+ { period: 1000, cap: 3 },
+ { period: ONE_DAY_IN_MS, cap: 5 },
+ { period: 100, cap: 2 },
+ ],
+ },
+ };
+ assert.equal(Router.getLongestPeriod(message), ONE_DAY_IN_MS);
+ });
+ it("should return null if there are is no .frequency", () => {
+ const message = { id: "foo" };
+ assert.isNull(Router.getLongestPeriod(message));
+ });
+ it("should return null if there are is no .frequency.custom", () => {
+ const message = { id: "foo", frequency: { lifetime: 10 } };
+ assert.isNull(Router.getLongestPeriod(message));
+ });
+ });
+
+ describe("cleanup on init", () => {
+ it("should clear messageImpressions for messages which do not exist in state.messages", async () => {
+ const messages = [{ id: "foo", frequency: { lifetime: 10 } }];
+ messageImpressions = { foo: [0], bar: [0, 1] };
+ // Impressions for "bar" should be removed since that id does not exist in messages
+ const result = { foo: [0] };
+
+ await createRouterAndInit([
+ { id: "onboarding", type: "local", messages, enabled: true },
+ ]);
+ assert.calledWith(Router._storage.set, "messageImpressions", result);
+ assert.deepEqual(Router.state.messageImpressions, result);
+ });
+ it("should clear messageImpressions older than the period if no lifetime impression cap is included", async () => {
+ const CURRENT_TIME = ONE_DAY_IN_MS * 2;
+ clock.tick(CURRENT_TIME);
+ const messages = [
+ {
+ id: "foo",
+ frequency: { custom: [{ period: ONE_DAY_IN_MS, cap: 5 }] },
+ },
+ ];
+ messageImpressions = { foo: [0, 1, CURRENT_TIME - 10] };
+ // Only 0 and 1 are more than 24 hours before CURRENT_TIME
+ const result = { foo: [CURRENT_TIME - 10] };
+
+ await createRouterAndInit([
+ { id: "onboarding", type: "local", messages, enabled: true },
+ ]);
+ assert.calledWith(Router._storage.set, "messageImpressions", result);
+ assert.deepEqual(Router.state.messageImpressions, result);
+ });
+ it("should clear messageImpressions older than the longest period if no lifetime impression cap is included", async () => {
+ const CURRENT_TIME = ONE_DAY_IN_MS * 2;
+ clock.tick(CURRENT_TIME);
+ const messages = [
+ {
+ id: "foo",
+ frequency: {
+ custom: [
+ { period: ONE_DAY_IN_MS, cap: 5 },
+ { period: 100, cap: 2 },
+ ],
+ },
+ },
+ ];
+ messageImpressions = { foo: [0, 1, CURRENT_TIME - 10] };
+ // Only 0 and 1 are more than 24 hours before CURRENT_TIME
+ const result = { foo: [CURRENT_TIME - 10] };
+
+ await createRouterAndInit([
+ { id: "onboarding", type: "local", messages, enabled: true },
+ ]);
+ assert.calledWith(Router._storage.set, "messageImpressions", result);
+ assert.deepEqual(Router.state.messageImpressions, result);
+ });
+ it("should clear messageImpressions if they are not properly formatted", async () => {
+ const messages = [{ id: "foo", frequency: { lifetime: 10 } }];
+ // this is impromperly formatted since messageImpressions are supposed to be an array
+ messageImpressions = { foo: 0 };
+ const result = {};
+
+ await createRouterAndInit([
+ { id: "onboarding", type: "local", messages, enabled: true },
+ ]);
+ assert.calledWith(Router._storage.set, "messageImpressions", result);
+ assert.deepEqual(Router.state.messageImpressions, result);
+ });
+ it("should not clear messageImpressions for messages which do exist in state.messages", async () => {
+ const messages = [
+ { id: "foo", frequency: { lifetime: 10 } },
+ { id: "bar", frequency: { lifetime: 10 } },
+ ];
+ messageImpressions = { foo: [0], bar: [] };
+
+ await createRouterAndInit([
+ { id: "onboarding", type: "local", messages, enabled: true },
+ ]);
+ assert.notCalled(Router._storage.set);
+ assert.deepEqual(Router.state.messageImpressions, messageImpressions);
+ });
+ });
+ });
+
+ describe("#_onLocaleChanged", () => {
+ it("should call _maybeUpdateL10nAttachment in the handler", async () => {
+ sandbox.spy(Router, "_maybeUpdateL10nAttachment");
+ await Router._onLocaleChanged();
+
+ assert.calledOnce(Router._maybeUpdateL10nAttachment);
+ });
+ });
+
+ describe("#_maybeUpdateL10nAttachment", () => {
+ it("should update the l10n attachment if the locale was changed", async () => {
+ const getter = sandbox.stub();
+ getter.onFirstCall().returns("en-US");
+ getter.onSecondCall().returns("fr");
+ sandbox.stub(global.Services.locale, "appLocaleAsBCP47").get(getter);
+ const provider = {
+ id: "cfr",
+ enabled: true,
+ type: "remote-settings",
+ bucket: "cfr",
+ };
+ await createRouterAndInit([provider]);
+ sandbox.spy(Router, "setState");
+ Router.loadMessagesFromAllProviders.resetHistory();
+
+ await Router._maybeUpdateL10nAttachment();
+
+ assert.calledWith(Router.setState, {
+ localeInUse: "fr",
+ providers: [
+ {
+ id: "cfr",
+ enabled: true,
+ type: "remote-settings",
+ bucket: "cfr",
+ lastUpdated: undefined,
+ errors: [],
+ },
+ ],
+ });
+ assert.calledOnce(Router.loadMessagesFromAllProviders);
+ });
+ it("should not update the l10n attachment if the provider doesn't need l10n attachment", async () => {
+ const getter = sandbox.stub();
+ getter.onFirstCall().returns("en-US");
+ getter.onSecondCall().returns("fr");
+ sandbox.stub(global.Services.locale, "appLocaleAsBCP47").get(getter);
+ const provider = {
+ id: "localProvider",
+ enabled: true,
+ type: "local",
+ };
+ await createRouterAndInit([provider]);
+ Router.loadMessagesFromAllProviders.resetHistory();
+ sandbox.spy(Router, "setState");
+
+ await Router._maybeUpdateL10nAttachment();
+
+ assert.notCalled(Router.setState);
+ assert.notCalled(Router.loadMessagesFromAllProviders);
+ });
+ });
+ describe("#observe", () => {
+ it("should reload l10n for CFRPageActions when the `USE_REMOTE_L10N_PREF` pref is changed", () => {
+ sandbox.spy(CFRPageActions, "reloadL10n");
+
+ Router.observe("", "", USE_REMOTE_L10N_PREF);
+
+ assert.calledOnce(CFRPageActions.reloadL10n);
+ });
+ it("should not react to other pref changes", () => {
+ sandbox.spy(CFRPageActions, "reloadL10n");
+
+ Router.observe("", "", "foo");
+
+ assert.notCalled(CFRPageActions.reloadL10n);
+ });
+ });
+ describe("#loadAllMessageGroups", () => {
+ it("should disable the group if the pref is false", async () => {
+ sandbox.stub(ASRouterPreferences, "getUserPreference").returns(false);
+ sandbox.stub(MessageLoaderUtils, "_getRemoteSettingsMessages").resolves([
+ {
+ id: "provider-group",
+ enabled: true,
+ type: "remote",
+ userPreferences: ["cfrAddons"],
+ },
+ ]);
+ await Router.setState({
+ providers: [
+ {
+ id: "message-groups",
+ enabled: true,
+ bucket: "bucket",
+ type: "remote-settings",
+ },
+ ],
+ });
+
+ await Router.loadAllMessageGroups();
+
+ const group = Router.state.groups.find(g => g.id === "provider-group");
+
+ assert.ok(group);
+ assert.propertyVal(group, "enabled", false);
+ });
+ it("should enable the group if at least one pref is true", async () => {
+ sandbox
+ .stub(ASRouterPreferences, "getUserPreference")
+ .withArgs("cfrAddons")
+ .returns(false)
+ .withArgs("cfrFeatures")
+ .returns(true);
+ sandbox.stub(MessageLoaderUtils, "_getRemoteSettingsMessages").resolves([
+ {
+ id: "provider-group",
+ enabled: true,
+ type: "remote",
+ userPreferences: ["cfrAddons", "cfrFeatures"],
+ },
+ ]);
+ await Router.setState({
+ providers: [
+ {
+ id: "message-groups",
+ enabled: true,
+ bucket: "bucket",
+ type: "remote-settings",
+ },
+ ],
+ });
+
+ await Router.loadAllMessageGroups();
+
+ const group = Router.state.groups.find(g => g.id === "provider-group");
+
+ assert.ok(group);
+ assert.propertyVal(group, "enabled", true);
+ });
+ it("should be keep the group disabled if disabled is true", async () => {
+ sandbox.stub(ASRouterPreferences, "getUserPreference").returns(true);
+ sandbox.stub(MessageLoaderUtils, "_getRemoteSettingsMessages").resolves([
+ {
+ id: "provider-group",
+ enabled: false,
+ type: "remote",
+ userPreferences: ["cfrAddons"],
+ },
+ ]);
+ await Router.setState({
+ providers: [
+ {
+ id: "message-groups",
+ enabled: true,
+ bucket: "bucket",
+ type: "remote-settings",
+ },
+ ],
+ });
+
+ await Router.loadAllMessageGroups();
+
+ const group = Router.state.groups.find(g => g.id === "provider-group");
+
+ assert.ok(group);
+ assert.propertyVal(group, "enabled", false);
+ });
+ it("should keep local groups unchanged if provider doesn't require an update", async () => {
+ sandbox.stub(MessageLoaderUtils, "shouldProviderUpdate").returns(false);
+ sandbox.stub(MessageLoaderUtils, "_loadDataForProvider");
+ await Router.setState({
+ groups: [
+ {
+ id: "cfr",
+ enabled: true,
+ bucket: "bucket",
+ type: "remote-settings",
+ },
+ ],
+ });
+
+ await Router.loadAllMessageGroups();
+
+ const group = Router.state.groups.find(g => g.id === "cfr");
+
+ assert.ok(group);
+ assert.propertyVal(group, "enabled", true);
+ // Because it should not have updated
+ assert.notCalled(MessageLoaderUtils._loadDataForProvider);
+ });
+ it("should update local groups on pref change (no RS update)", async () => {
+ sandbox.stub(MessageLoaderUtils, "shouldProviderUpdate").returns(false);
+ sandbox.stub(ASRouterPreferences, "getUserPreference").returns(false);
+ await Router.setState({
+ groups: [
+ {
+ id: "cfr",
+ enabled: true,
+ bucket: "bucket",
+ type: "remote-settings",
+ userPreferences: ["cfrAddons"],
+ },
+ ],
+ });
+
+ await Router.loadAllMessageGroups();
+
+ const group = Router.state.groups.find(g => g.id === "cfr");
+
+ assert.ok(group);
+ // Pref changed, updated the group state
+ assert.propertyVal(group, "enabled", false);
+ });
+ });
+ describe("unblockAll", () => {
+ it("Clears the message block list and returns the state value", async () => {
+ await Router.setState({ messageBlockList: ["one", "two", "three"] });
+ assert.equal(Router.state.messageBlockList.length, 3);
+ const state = await Router.unblockAll();
+ assert.equal(Router.state.messageBlockList.length, 0);
+ assert.equal(state.messageBlockList.length, 0);
+ });
+ });
+ describe("#loadMessagesForProvider", () => {
+ it("should fetch messages from the ExperimentAPI", async () => {
+ const args = {
+ type: "remote-experiments",
+ messageGroups: ["asrouter"],
+ };
+
+ await MessageLoaderUtils.loadMessagesForProvider(args);
+
+ assert.calledOnce(global.ExperimentAPI.getExperiment);
+ assert.calledWithExactly(global.ExperimentAPI.getExperiment, {
+ featureId: "asrouter",
+ sendExposurePing: false,
+ });
+ });
+ it("should handle the case of no experiments in the ExperimentAPI", async () => {
+ const args = {
+ type: "remote-experiments",
+ messageGroups: ["asrouter"],
+ };
+
+ global.ExperimentAPI.getExperiment.throws();
+ const stub = sandbox.stub(MessageLoaderUtils, "reportError");
+
+ await MessageLoaderUtils.loadMessagesForProvider(args);
+
+ assert.calledOnce(stub);
+ });
+ it("should handle the case of no experiments in the ExperimentAPI", async () => {
+ const args = {
+ type: "remote-experiments",
+ messageGroups: ["asrouter"],
+ };
+
+ global.ExperimentAPI.getExperiment.returns(null);
+
+ const result = await MessageLoaderUtils.loadMessagesForProvider(args);
+
+ assert.lengthOf(result.messages, 0);
+ });
+ it("should normally load ExperimentAPI messages", async () => {
+ const args = {
+ type: "remote-experiments",
+ messageGroups: ["asrouter"],
+ };
+ const enrollment = {
+ branch: {
+ slug: "branch01",
+ feature: {
+ featureId: "asrouter",
+ enabled: true,
+ value: { id: "id01", trigger: { id: "openURL" } },
+ },
+ },
+ };
+
+ global.ExperimentAPI.getExperiment.returns(enrollment);
+
+ const result = await MessageLoaderUtils.loadMessagesForProvider(args);
+
+ assert.lengthOf(result.messages, 1);
+ });
+ it("should skip disabled features and not load the messages", async () => {
+ const args = {
+ type: "remote-experiments",
+ messageGroups: ["asrouter"],
+ };
+ const enrollment = {
+ branch: {
+ slug: "branch01",
+ feature: {
+ featureId: "asrouter",
+ enabled: false,
+ value: { id: "id01", trigger: { id: "openURL" } },
+ },
+ },
+ };
+
+ global.ExperimentAPI.getExperiment.returns(enrollment);
+
+ const result = await MessageLoaderUtils.loadMessagesForProvider(args);
+
+ assert.lengthOf(result.messages, 0);
+ });
+ it("should fetch messages from the ExperimentAPI", async () => {
+ global.ExperimentAPI.ready.throws();
+ const args = {
+ type: "remote-experiments",
+ messageGroups: ["asrouter"],
+ };
+ const stub = sandbox.stub(MessageLoaderUtils, "reportError");
+
+ await MessageLoaderUtils.loadMessagesForProvider(args);
+
+ assert.notCalled(global.ExperimentAPI.getExperiment);
+ assert.calledOnce(stub);
+ });
+ it("should fetch branches with trigger", async () => {
+ const args = {
+ type: "remote-experiments",
+ messageGroups: ["cfr"],
+ };
+ const enrollment = {
+ slug: "exp01",
+ branch: {
+ slug: "branch01",
+ feature: {
+ featureId: "cfr",
+ enabled: true,
+ value: { id: "id01", trigger: { id: "openURL" } },
+ },
+ },
+ };
+
+ global.ExperimentAPI.getExperiment.returns(enrollment);
+ global.ExperimentAPI.getAllBranches.resolves([
+ enrollment.branch,
+ {
+ slug: "branch02",
+ feature: {
+ featureId: "cfr",
+ enabled: true,
+ value: { id: "id02", trigger: { id: "openURL" } },
+ },
+ },
+ {
+ // This branch should not be loaded as it doesn't have the trigger
+ slug: "branch03",
+ feature: {
+ featureId: "cfr",
+ enabled: true,
+ value: { id: "id03" },
+ },
+ },
+ ]);
+
+ const result = await MessageLoaderUtils.loadMessagesForProvider(args);
+
+ assert.equal(result.messages.length, 2);
+ assert.equal(result.messages[0].id, "id01");
+ assert.equal(result.messages[1].id, "id02");
+ assert.equal(result.messages[1].experimentSlug, "exp01");
+ assert.equal(result.messages[1].branchSlug, "branch02");
+ assert.deepEqual(result.messages[1].forReachEvent, {
+ sent: false,
+ group: "cfr",
+ });
+ });
+ it("should fetch branches with trigger even if enrolled branch is disabled", async () => {
+ const args = {
+ type: "remote-experiments",
+ messageGroups: ["cfr"],
+ };
+ const enrollment = {
+ slug: "exp01",
+ branch: {
+ slug: "branch01",
+ feature: {
+ featureId: "cfr",
+ enabled: false,
+ value: { id: "id01", trigger: { id: "openURL" } },
+ },
+ },
+ };
+
+ global.ExperimentAPI.getExperiment.returns(enrollment);
+ global.ExperimentAPI.getAllBranches.resolves([
+ enrollment.branch,
+ {
+ slug: "branch02",
+ feature: {
+ featureId: "cfr",
+ enabled: true,
+ value: { id: "id02", trigger: { id: "openURL" } },
+ },
+ },
+ {
+ // This branch should not be loaded as it doesn't have the trigger
+ slug: "branch03",
+ feature: {
+ featureId: "cfr",
+ enabled: true,
+ value: { id: "id03" },
+ },
+ },
+ ]);
+
+ const result = await MessageLoaderUtils.loadMessagesForProvider(args);
+
+ assert.equal(result.messages.length, 1);
+ assert.equal(result.messages[0].id, "id02");
+ assert.equal(result.messages[0].experimentSlug, "exp01");
+ assert.equal(result.messages[0].branchSlug, "branch02");
+ assert.deepEqual(result.messages[0].forReachEvent, {
+ sent: false,
+ group: "cfr",
+ });
+ });
+ it("should fetch json from url", async () => {
+ let result = await MessageLoaderUtils.loadMessagesForProvider({
+ location: "http://fake.com/endpoint",
+ type: "json",
+ });
+
+ assert.property(result, "messages");
+ assert.lengthOf(result.messages, FAKE_REMOTE_MESSAGES.length);
+ });
+ it("should catch errors", async () => {
+ fetchStub.throws();
+ let result = await MessageLoaderUtils.loadMessagesForProvider({
+ location: "http://fake.com/endpoint",
+ type: "json",
+ });
+
+ assert.property(result, "messages");
+ assert.lengthOf(result.messages, 0);
+ });
+ });
+ describe("#_remoteSettingsLoader", () => {
+ let provider;
+ let spy;
+ beforeEach(() => {
+ provider = {
+ id: "cfr",
+ bucket: "cfr",
+ };
+ sandbox
+ .stub(MessageLoaderUtils, "_getRemoteSettingsMessages")
+ .resolves([{ id: "message_1" }]);
+ spy = sandbox.spy();
+ global.Downloader.prototype.download = spy;
+ });
+ it("should allow fetch for known locales", async () => {
+ sandbox
+ .stub(global.Services.locale, "appLocaleAsBCP47")
+ .get(() => "en-US");
+ sandbox.stub(global.RemoteL10n, "isLocaleSupported").returns(true);
+
+ await MessageLoaderUtils._remoteSettingsLoader(provider, {});
+
+ assert.calledOnce(spy);
+ });
+ it("should fallback to 'en-US' for locale 'und' ", async () => {
+ sandbox.stub(global.Services.locale, "appLocaleAsBCP47").get(() => "und");
+ sandbox.stub(global.RemoteL10n, "isLocaleSupported").returns(false);
+ const getRecordSpy = sandbox.spy(
+ global.KintoHttpClient.prototype,
+ "getRecord"
+ );
+
+ await MessageLoaderUtils._remoteSettingsLoader(provider, {});
+
+ assert.ok(getRecordSpy.args[0][0].includes("en-US"));
+ assert.calledOnce(spy);
+ });
+ it("should not allow fetch for unsupported locales", async () => {
+ sandbox
+ .stub(global.Services.locale, "appLocaleAsBCP47")
+ .get(() => "unkown");
+ sandbox.stub(global.RemoteL10n, "isLocaleSupported").returns(false);
+
+ await MessageLoaderUtils._remoteSettingsLoader(provider, {});
+
+ assert.notCalled(spy);
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/asrouter/ASRouterChild.test.js b/browser/components/newtab/test/unit/asrouter/ASRouterChild.test.js
new file mode 100644
index 0000000000..526bb33db4
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/ASRouterChild.test.js
@@ -0,0 +1,74 @@
+/*eslint max-nested-callbacks: ["error", 10]*/
+import { ASRouterChild } from "actors/ASRouterChild.jsm";
+import { MESSAGE_TYPE_HASH as msg } from "common/ActorConstants.jsm";
+import { GlobalOverrider } from "test/unit/utils";
+
+describe("ASRouterChild", () => {
+ let asRouterChild = null;
+ let globals = null;
+ let overrider = null;
+ let sandbox = null;
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ globals = {
+ Cu: {
+ cloneInto: sandbox.stub().returns(Promise.resolve()),
+ },
+ };
+ overrider = new GlobalOverrider();
+ overrider.set(globals);
+ asRouterChild = new ASRouterChild();
+ asRouterChild.telemetry = {
+ sendTelemetry: sandbox.stub(),
+ };
+ sandbox.stub(asRouterChild, "sendAsyncMessage");
+ sandbox.stub(asRouterChild, "sendQuery").returns(Promise.resolve());
+ });
+ afterEach(() => {
+ sandbox.restore();
+ overrider.restore();
+ asRouterChild = null;
+ });
+ describe("asRouterMessage", () => {
+ describe("uses sendAsyncMessage for types that don't need an async response", () => {
+ [
+ msg.DISABLE_PROVIDER,
+ msg.ENABLE_PROVIDER,
+ msg.EXPIRE_QUERY_CACHE,
+ msg.FORCE_WHATSNEW_PANEL,
+ msg.IMPRESSION,
+ msg.RESET_PROVIDER_PREF,
+ msg.SET_PROVIDER_USER_PREF,
+ msg.USER_ACTION,
+ ].forEach(type => {
+ it(`type ${type}`, () => {
+ asRouterChild.asRouterMessage({
+ type,
+ data: {
+ something: 1,
+ },
+ });
+ sandbox.assert.calledOnce(asRouterChild.sendAsyncMessage);
+ sandbox.assert.calledWith(asRouterChild.sendAsyncMessage, type, {
+ something: 1,
+ });
+ });
+ });
+ });
+ describe("use sends messages that need a response using sendQuery", () => {
+ it("NEWTAB_MESSAGE_REQUEST", () => {
+ const type = msg.NEWTAB_MESSAGE_REQUEST;
+ asRouterChild.asRouterMessage({
+ type,
+ data: {
+ something: 1,
+ },
+ });
+ sandbox.assert.calledOnce(asRouterChild.sendQuery);
+ sandbox.assert.calledWith(asRouterChild.sendQuery, type, {
+ something: 1,
+ });
+ });
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/asrouter/ASRouterNewTabHook.test.js b/browser/components/newtab/test/unit/asrouter/ASRouterNewTabHook.test.js
new file mode 100644
index 0000000000..ffc709c607
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/ASRouterNewTabHook.test.js
@@ -0,0 +1,151 @@
+/*eslint max-nested-callbacks: ["error", 10]*/
+import { ASRouterNewTabHook } from "lib/ASRouterNewTabHook.jsm";
+
+describe("ASRouterNewTabHook", () => {
+ let sandbox = null;
+ let initParams = null;
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ initParams = {
+ router: {
+ init: sandbox.stub().resolves(),
+ uninit: sandbox.stub(),
+ },
+ messageHandler: {
+ handleCFRAction: {},
+ handleTelemetry: {},
+ },
+ createStorage: () => Promise.resolve({}),
+ };
+ });
+ afterEach(() => {
+ sandbox.restore();
+ });
+ describe("ASRouterNewTabHook", () => {
+ describe("getInstance", () => {
+ it("awaits createInstance and router init before returning instance", async () => {
+ const getInstanceCall = sandbox.spy();
+ const waitForInstance = ASRouterNewTabHook.getInstance().then(
+ getInstanceCall
+ );
+ await ASRouterNewTabHook.createInstance(initParams);
+ await waitForInstance;
+ assert.callOrder(initParams.router.init, getInstanceCall);
+ });
+ });
+ describe("createInstance", () => {
+ it("calls router init", async () => {
+ await ASRouterNewTabHook.createInstance(initParams);
+ assert.calledOnce(initParams.router.init);
+ });
+ it("only calls router init once", async () => {
+ initParams.router.init.callsFake(() => {
+ initParams.router.initialized = true;
+ });
+ await ASRouterNewTabHook.createInstance(initParams);
+ await ASRouterNewTabHook.createInstance(initParams);
+ assert.calledOnce(initParams.router.init);
+ });
+ });
+ describe("destroy", () => {
+ it("disconnects new tab, uninits ASRouter, and destroys instance", async () => {
+ await ASRouterNewTabHook.createInstance(initParams);
+ const instance = await ASRouterNewTabHook.getInstance();
+ const destroy = instance.destroy.bind(instance);
+ sandbox.stub(instance, "destroy").callsFake(destroy);
+ ASRouterNewTabHook.destroy();
+ assert.calledOnce(initParams.router.uninit);
+ assert.calledOnce(instance.destroy);
+ assert.isNotNull(instance);
+ assert.isNull(instance._newTabMessageHandler);
+ });
+ });
+ describe("instance", () => {
+ let routerParams = null;
+ let messageHandler = null;
+ let instance = null;
+ beforeEach(async () => {
+ messageHandler = {
+ clearChildMessages: sandbox.stub().resolves(),
+ clearChildProviders: sandbox.stub().resolves(),
+ updateAdminState: sandbox.stub().resolves(),
+ };
+ initParams.router.init.callsFake(params => {
+ routerParams = params;
+ });
+ await ASRouterNewTabHook.createInstance(initParams);
+ instance = await ASRouterNewTabHook.getInstance();
+ });
+ describe("connect", () => {
+ it("before connection messageHandler methods are not called", async () => {
+ routerParams.clearChildMessages([1]);
+ routerParams.clearChildProviders(["snippets"]);
+ routerParams.updateAdminState({ messages: {} });
+ assert.notCalled(messageHandler.clearChildMessages);
+ assert.notCalled(messageHandler.clearChildProviders);
+ assert.notCalled(messageHandler.updateAdminState);
+ });
+ it("after connect updateAdminState and clearChildMessages calls are forwarded to handler", async () => {
+ instance.connect(messageHandler);
+ routerParams.clearChildMessages([1]);
+ routerParams.clearChildProviders(["snippets"]);
+ routerParams.updateAdminState({ messages: {} });
+ assert.called(messageHandler.clearChildMessages);
+ assert.called(messageHandler.clearChildProviders);
+ assert.called(messageHandler.updateAdminState);
+ });
+ it("calls from before connection are dropped", async () => {
+ routerParams.clearChildMessages([1]);
+ routerParams.clearChildProviders(["snippets"]);
+ routerParams.updateAdminState({ messages: {} });
+ instance.connect(messageHandler);
+ routerParams.clearChildMessages([1]);
+ routerParams.clearChildProviders(["snippets"]);
+ routerParams.updateAdminState({ messages: {} });
+ assert.calledOnce(messageHandler.clearChildMessages);
+ assert.calledOnce(messageHandler.clearChildProviders);
+ assert.calledOnce(messageHandler.updateAdminState);
+ });
+ });
+ describe("disconnect", () => {
+ it("calls after disconnect are dropped", async () => {
+ instance.connect(messageHandler);
+ instance.disconnect();
+ routerParams.clearChildMessages([1]);
+ routerParams.clearChildProviders(["snippets"]);
+ routerParams.updateAdminState({ messages: {} });
+ assert.notCalled(messageHandler.clearChildMessages);
+ assert.notCalled(messageHandler.clearChildProviders);
+ assert.notCalled(messageHandler.updateAdminState);
+ });
+ it("only calls from when there is a connection are forwarded", async () => {
+ routerParams.clearChildMessages([1]);
+ routerParams.clearChildProviders(["foo"]);
+ routerParams.updateAdminState({ messages: {} });
+ instance.connect(messageHandler);
+ routerParams.clearChildMessages([200]);
+ routerParams.clearChildProviders(["bar"]);
+ routerParams.updateAdminState({
+ messages: {
+ data: "accept",
+ },
+ });
+ instance.disconnect();
+ routerParams.clearChildMessages([1]);
+ routerParams.clearChildProviders(["foo"]);
+ routerParams.updateAdminState({ messages: {} });
+ assert.calledOnce(messageHandler.clearChildMessages);
+ assert.calledOnce(messageHandler.clearChildProviders);
+ assert.calledOnce(messageHandler.updateAdminState);
+ assert.calledWith(messageHandler.clearChildMessages, [200]);
+ assert.calledWith(messageHandler.clearChildProviders, ["bar"]);
+ assert.calledWith(messageHandler.updateAdminState, {
+ messages: {
+ data: "accept",
+ },
+ });
+ });
+ });
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/asrouter/ASRouterParent.test.js b/browser/components/newtab/test/unit/asrouter/ASRouterParent.test.js
new file mode 100644
index 0000000000..a4e205fee8
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/ASRouterParent.test.js
@@ -0,0 +1,103 @@
+import { ASRouterParent } from "actors/ASRouterParent.jsm";
+import { MESSAGE_TYPE_HASH as msg } from "common/ActorConstants.jsm";
+
+describe("ASRouterParent", () => {
+ let asRouterParent = null;
+ let sandbox = null;
+ let handleMessage = null;
+ let tabs = null;
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ handleMessage = sandbox.stub().resolves("handle-message-result");
+ ASRouterParent.nextTabId = 1;
+ const methods = {
+ destroy: sandbox.stub(),
+ size: 1,
+ messageAll: sandbox.stub().resolves(),
+ messagePreloaded: sandbox.stub().resolves(),
+ registerActor: sandbox.stub(),
+ unregisterActor: sandbox.stub(),
+ loadingMessageHandler: Promise.resolve({
+ handleMessage,
+ }),
+ };
+ tabs = {
+ methods,
+ factory: sandbox.stub().returns(methods),
+ };
+ asRouterParent = new ASRouterParent({ tabsFactory: tabs.factory });
+ ASRouterParent.tabs = tabs.methods;
+ asRouterParent.browsingContext = {
+ embedderElement: {
+ getAttribute: () => true,
+ },
+ };
+ });
+ afterEach(() => {
+ sandbox.restore();
+ asRouterParent = null;
+ });
+ describe("actorCreated", () => {
+ it("after ASRouterTabs is instanced", () => {
+ asRouterParent.actorCreated();
+ assert.equal(asRouterParent.tabId, 2);
+ assert.notCalled(tabs.factory);
+ assert.calledOnce(tabs.methods.registerActor);
+ });
+ it("before ASRouterTabs is instanced", () => {
+ ASRouterParent.tabs = null;
+ ASRouterParent.nextTabId = 0;
+ asRouterParent.actorCreated();
+ assert.calledOnce(tabs.factory);
+ assert.isNotNull(ASRouterParent.tabs);
+ assert.equal(asRouterParent.tabId, 1);
+ });
+ });
+ describe("didDestroy", () => {
+ it("one still remains", () => {
+ ASRouterParent.tabs.size = 1;
+ asRouterParent.didDestroy();
+ assert.isNotNull(ASRouterParent.tabs);
+ assert.calledOnce(ASRouterParent.tabs.unregisterActor);
+ assert.notCalled(ASRouterParent.tabs.destroy);
+ });
+ it("none remain", () => {
+ ASRouterParent.tabs.size = 0;
+ const tabsCopy = ASRouterParent.tabs;
+ asRouterParent.didDestroy();
+ assert.isNull(ASRouterParent.tabs);
+ assert.calledOnce(tabsCopy.unregisterActor);
+ assert.calledOnce(tabsCopy.destroy);
+ });
+ });
+ describe("receiveMessage", async () => {
+ it("passes call to parentProcessMessageHandler and returns the result from handler", async () => {
+ const result = await asRouterParent.receiveMessage({
+ name: msg.BLOCK_MESSAGE_BY_ID,
+ data: { id: 1 },
+ });
+ assert.calledOnce(handleMessage);
+ // No "ClearMessages" message should be sent.
+ assert.notCalled(ASRouterParent.tabs.messagePreloaded);
+ assert.equal(result, "handle-message-result");
+ });
+ it(
+ "passes preloadedOnly BLOCK_MESSAGE_BY_ID calls to messagePreloaded, sends " +
+ "a message to clear messages, and then returns false",
+ async () => {
+ const MESSAGE_ID = 1;
+ const result = await asRouterParent.receiveMessage({
+ name: msg.BLOCK_MESSAGE_BY_ID,
+ data: { id: MESSAGE_ID, preloadedOnly: true },
+ });
+ assert.calledOnce(handleMessage);
+ assert.calledWithExactly(
+ ASRouterParent.tabs.messagePreloaded,
+ "ClearMessages",
+ [MESSAGE_ID]
+ );
+ assert.equal(result, false);
+ }
+ );
+ });
+});
diff --git a/browser/components/newtab/test/unit/asrouter/ASRouterParentProcessMessageHandler.test.js b/browser/components/newtab/test/unit/asrouter/ASRouterParentProcessMessageHandler.test.js
new file mode 100644
index 0000000000..671dced6ea
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/ASRouterParentProcessMessageHandler.test.js
@@ -0,0 +1,418 @@
+import { ASRouterParentProcessMessageHandler } from "lib/ASRouterParentProcessMessageHandler.jsm";
+import { MESSAGE_TYPE_HASH as msg } from "common/ActorConstants.jsm";
+
+describe("ASRouterParentProcessMessageHandler", () => {
+ let handler = null;
+ let sandbox = null;
+ let config = null;
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ const returnValue = { value: 1 };
+ const router = {
+ _storage: {
+ set: sandbox.stub().resolves(),
+ get: sandbox.stub().resolves(),
+ },
+ _updateOnboardingState: sandbox.stub().resolves(),
+ addImpression: sandbox.stub().resolves(),
+ addPreviewEndpoint: sandbox.stub().resolves(),
+ blockMessageById: sandbox.stub().resolves(returnValue),
+ evaluateExpression: sandbox.stub().resolves(),
+ forceAttribution: sandbox.stub().resolves(),
+ forceWNPanel: sandbox.stub().resolves(),
+ closeWNPanel: sandbox.stub().resolves(),
+ loadMessagesFromAllProviders: sandbox.stub().resolves(returnValue),
+ sendNewTabMessage: sandbox.stub().resolves(returnValue),
+ sendTriggerMessage: sandbox.stub().resolves(returnValue),
+ sendMessage: sandbox.stub().resolves(returnValue),
+ setMessageById: sandbox.stub().resolves(returnValue),
+ resetGroupsState: sandbox.stub().resolves(),
+ setState: sandbox.stub().callsFake(callback => {
+ if (typeof callback === "function") {
+ callback({
+ messageBlockList: [
+ {
+ id: 0,
+ },
+ {
+ id: 1,
+ },
+ {
+ id: 2,
+ },
+ {
+ id: 3,
+ },
+ {
+ id: 4,
+ },
+ ],
+ });
+ }
+ return Promise.resolve(returnValue);
+ }),
+ updateTargetingParameters: sandbox.stub().resolves(returnValue),
+ unblockMessageById: sandbox.stub().resolves(returnValue),
+ unblockAll: sandbox.stub().resolves(returnValue),
+ };
+ const preferences = {
+ enableOrDisableProvider: sandbox.stub(),
+ resetProviderPref: sandbox.stub(),
+ setUserPreference: sandbox.stub(),
+ };
+ const specialMessageActions = {
+ handleAction: sandbox.stub(),
+ };
+ const queryCache = {
+ expireAll: sandbox.stub(),
+ };
+ const sendTelemetry = sandbox.stub();
+ config = {
+ router,
+ preferences,
+ specialMessageActions,
+ queryCache,
+ sendTelemetry,
+ };
+ handler = new ASRouterParentProcessMessageHandler(config);
+ });
+ afterEach(() => {
+ sandbox.restore();
+ handler = null;
+ config = null;
+ });
+ describe("constructor", () => {
+ it("does not throw", () => {
+ assert.isNotNull(handler);
+ assert.isNotNull(config);
+ });
+ });
+ describe("handleCFRAction", () => {
+ it("non-telemetry type isn't sent to telemetry", () => {
+ handler.handleCFRAction({
+ type: msg.BLOCK_MESSAGE_BY_ID,
+ data: { id: 1 },
+ });
+ assert.notCalled(config.sendTelemetry);
+ assert.calledOnce(config.router.blockMessageById);
+ });
+ it("passes browser to handleMessage", async () => {
+ await handler.handleCFRAction(
+ {
+ type: msg.USER_ACTION,
+ data: { id: 1 },
+ },
+ { ownerGlobal: {} }
+ );
+ assert.notCalled(config.sendTelemetry);
+ assert.calledOnce(config.specialMessageActions.handleAction);
+ assert.calledWith(
+ config.specialMessageActions.handleAction,
+ { id: 1 },
+ { ownerGlobal: {} }
+ );
+ });
+ [
+ msg.AS_ROUTER_TELEMETRY_USER_EVENT,
+ msg.TOOLBAR_BADGE_TELEMETRY,
+ msg.TOOLBAR_PANEL_TELEMETRY,
+ msg.MOMENTS_PAGE_TELEMETRY,
+ msg.DOORHANGER_TELEMETRY,
+ ].forEach(type => {
+ it(`telemetry type "${type}" is sent to telemetry`, () => {
+ handler.handleCFRAction({
+ type,
+ data: { id: 1 },
+ });
+ assert.calledOnce(config.sendTelemetry);
+ assert.notCalled(config.router.blockMessageById);
+ });
+ });
+ });
+ describe("#handleMessage", () => {
+ it("#default: should throw for unknown msg types", () => {
+ handler.handleMessage("err").then(
+ () => assert.fail("It should not succeed"),
+ () => assert.ok(true)
+ );
+ });
+ describe("#AS_ROUTER_TELEMETRY_USER_EVENT", () => {
+ it("should route AS_ROUTER_TELEMETRY_USER_EVENT to handleTelemetry", async () => {
+ const data = { data: "foo" };
+ await handler.handleMessage(msg.AS_ROUTER_TELEMETRY_USER_EVENT, data);
+
+ assert.calledOnce(handler.handleTelemetry);
+ assert.calledWithExactly(handler.handleTelemetry, {
+ type: msg.AS_ROUTER_TELEMETRY_USER_EVENT,
+ data,
+ });
+ });
+ });
+ describe("BLOCK_MESSAGE_BY_ID action", () => {
+ it("with preventDismiss returns false", async () => {
+ const result = await handler.handleMessage(msg.BLOCK_MESSAGE_BY_ID, {
+ id: 1,
+ preventDismiss: true,
+ });
+ assert.calledOnce(config.router.blockMessageById);
+ assert.isFalse(result);
+ });
+ it("by default returns true", async () => {
+ const result = await handler.handleMessage(msg.BLOCK_MESSAGE_BY_ID, {
+ id: 1,
+ });
+ assert.calledOnce(config.router.blockMessageById);
+ assert.isTrue(result);
+ });
+ });
+ describe("USER_ACTION action", () => {
+ it("with INSTALL_ADDON_FROM_URL calls _updateOnboardingState", () => {
+ handler.handleMessage(msg.USER_ACTION, {
+ type: "INSTALL_ADDON_FROM_URL",
+ });
+ assert.calledOnce(config.router._updateOnboardingState);
+ });
+ it("default calls SpecialMessageActions.handleAction", async () => {
+ await handler.handleMessage(
+ msg.USER_ACTION,
+ {
+ type: "SOMETHING",
+ },
+ { browser: { ownerGlobal: {} } }
+ );
+ assert.notCalled(config.router._updateOnboardingState);
+ assert.calledOnce(config.specialMessageActions.handleAction);
+ assert.calledWith(
+ config.specialMessageActions.handleAction,
+ { type: "SOMETHING" },
+ { ownerGlobal: {} }
+ );
+ });
+ });
+ describe("IMPRESSION action", () => {
+ it("default calls addImpression", () => {
+ handler.handleMessage(msg.IMPRESSION, {
+ id: 1,
+ });
+ assert.calledOnce(config.router.addImpression);
+ });
+ });
+ describe("TRIGGER action", () => {
+ it("default calls sendTriggerMessage and returns state", async () => {
+ const result = await handler.handleMessage(
+ msg.TRIGGER,
+ {
+ trigger: { stuff: {} },
+ },
+ { id: 100, browser: { ownerGlobal: {} } }
+ );
+ assert.calledOnce(config.router.sendTriggerMessage);
+ assert.calledWith(config.router.sendTriggerMessage, {
+ stuff: {},
+ tabId: 100,
+ browser: { ownerGlobal: {} },
+ });
+ assert.deepEqual(result, { value: 1 });
+ });
+ });
+ describe("NEWTAB_MESSAGE_REQUEST action", () => {
+ it("default calls sendNewTabMessage and returns state", async () => {
+ const result = await handler.handleMessage(
+ msg.NEWTAB_MESSAGE_REQUEST,
+ {
+ stuff: {},
+ },
+ { id: 100, browser: { ownerGlobal: {} } }
+ );
+ assert.calledOnce(config.router.sendNewTabMessage);
+ assert.calledWith(config.router.sendNewTabMessage, {
+ stuff: {},
+ tabId: 100,
+ browser: { ownerGlobal: {} },
+ });
+ assert.deepEqual(result, { value: 1 });
+ });
+ });
+ describe("ADMIN_CONNECT_STATE action", () => {
+ it("with endpoint url calls addPreviewEndpoint, loadMessagesFromAllProviders, and returns state", async () => {
+ const result = await handler.handleMessage(msg.ADMIN_CONNECT_STATE, {
+ endpoint: {
+ url: "test",
+ },
+ });
+ assert.calledOnce(config.router.addPreviewEndpoint);
+ assert.calledOnce(config.router.loadMessagesFromAllProviders);
+ assert.deepEqual(result, { value: 1 });
+ });
+ it("default returns state", async () => {
+ const result = await handler.handleMessage(msg.ADMIN_CONNECT_STATE);
+ assert.calledOnce(config.router.updateTargetingParameters);
+ assert.deepEqual(result, { value: 1 });
+ });
+ });
+ describe("UNBLOCK_MESSAGE_BY_ID action", () => {
+ it("default calls unblockMessageById", async () => {
+ const result = await handler.handleMessage(msg.UNBLOCK_MESSAGE_BY_ID, {
+ id: 1,
+ });
+ assert.calledOnce(config.router.unblockMessageById);
+ assert.deepEqual(result, { value: 1 });
+ });
+ });
+ describe("UNBLOCK_ALL action", () => {
+ it("default calls unblockAll", async () => {
+ const result = await handler.handleMessage(msg.UNBLOCK_ALL);
+ assert.calledOnce(config.router.unblockAll);
+ assert.deepEqual(result, { value: 1 });
+ });
+ });
+ describe("BLOCK_BUNDLE action", () => {
+ it("default calls unblockMessageById", async () => {
+ const result = await handler.handleMessage(msg.BLOCK_BUNDLE, {
+ bundle: [
+ {
+ id: 8,
+ },
+ {
+ id: 13,
+ },
+ ],
+ });
+ assert.calledOnce(config.router.blockMessageById);
+ assert.deepEqual(result, { value: 1 });
+ });
+ });
+ describe("UNBLOCK_BUNDLE action", () => {
+ it("default calls setState", async () => {
+ const result = await handler.handleMessage(msg.UNBLOCK_BUNDLE, {
+ bundle: [
+ {
+ id: 1,
+ },
+ {
+ id: 3,
+ },
+ ],
+ });
+ assert.calledOnce(config.router.setState);
+ assert.deepEqual(result, { value: 1 });
+ });
+ });
+ describe("DISABLE_PROVIDER action", () => {
+ it("default calls ASRouterPreferences.enableOrDisableProvider", () => {
+ handler.handleMessage(msg.DISABLE_PROVIDER, {});
+ assert.calledOnce(config.preferences.enableOrDisableProvider);
+ });
+ });
+ describe("ENABLE_PROVIDER action", () => {
+ it("default calls ASRouterPreferences.enableOrDisableProvider", () => {
+ handler.handleMessage(msg.ENABLE_PROVIDER, {});
+ assert.calledOnce(config.preferences.enableOrDisableProvider);
+ });
+ });
+ describe("EVALUATE_JEXL_EXPRESSION action", () => {
+ it("default calls evaluateExpression", () => {
+ handler.handleMessage(msg.EVALUATE_JEXL_EXPRESSION, {});
+ assert.calledOnce(config.router.evaluateExpression);
+ });
+ });
+ describe("EXPIRE_QUERY_CACHE action", () => {
+ it("default calls QueryCache.expireAll", () => {
+ handler.handleMessage(msg.EXPIRE_QUERY_CACHE);
+ assert.calledOnce(config.queryCache.expireAll);
+ });
+ });
+ describe("FORCE_ATTRIBUTION action", () => {
+ it("default calls forceAttribution", () => {
+ handler.handleMessage(msg.FORCE_ATTRIBUTION, {});
+ assert.calledOnce(config.router.forceAttribution);
+ });
+ });
+ describe("FORCE_WHATSNEW_PANEL action", () => {
+ it("default calls forceWNPanel", () => {
+ handler.handleMessage(
+ msg.FORCE_WHATSNEW_PANEL,
+ {},
+ { browser: { ownerGlobal: {} } }
+ );
+ assert.calledOnce(config.router.forceWNPanel);
+ assert.calledWith(config.router.forceWNPanel, { ownerGlobal: {} });
+ });
+ });
+ describe("CLOSE_WHATSNEW_PANEL action", () => {
+ it("default calls closeWNPanel", () => {
+ handler.handleMessage(
+ msg.CLOSE_WHATSNEW_PANEL,
+ {},
+ { browser: { ownerGlobal: {} } }
+ );
+ assert.calledOnce(config.router.closeWNPanel);
+ assert.calledWith(config.router.closeWNPanel, { ownerGlobal: {} });
+ });
+ });
+ describe("MODIFY_MESSAGE_JSON action", () => {
+ it("default calls sendMessage", async () => {
+ const result = await handler.handleMessage(
+ msg.MODIFY_MESSAGE_JSON,
+ {
+ content: {
+ text: "something",
+ },
+ },
+ { id: 100, browser: { ownerGlobal: {} } }
+ );
+ assert.calledOnce(config.router.sendMessage);
+ assert.calledWith(
+ config.router.sendMessage,
+ { text: "something" },
+ { content: { text: "something" } },
+ true,
+ { ownerGlobal: {} }
+ );
+ assert.deepEqual(result, { value: 1 });
+ });
+ });
+ describe("OVERRIDE_MESSAGE action", () => {
+ it("default calls sendMessage", async () => {
+ const result = await handler.handleMessage(
+ msg.OVERRIDE_MESSAGE,
+ {
+ id: 1,
+ },
+ { id: 100, browser: { ownerGlobal: {} } }
+ );
+ assert.calledOnce(config.router.setMessageById);
+ assert.calledWith(config.router.setMessageById, { id: 1 }, true, {
+ ownerGlobal: {},
+ });
+ assert.deepEqual(result, { value: 1 });
+ });
+ });
+ describe("RESET_PROVIDER_PREF action", () => {
+ it("default calls ASRouterPreferences.resetProviderPref", () => {
+ handler.handleMessage(msg.RESET_PROVIDER_PREF);
+ assert.calledOnce(config.preferences.resetProviderPref);
+ });
+ });
+ describe("SET_PROVIDER_USER_PREF action", () => {
+ it("default calls ASRouterPreferences.setUserPreference", () => {
+ handler.handleMessage(msg.SET_PROVIDER_USER_PREF, {
+ id: 1,
+ value: true,
+ });
+ assert.calledOnce(config.preferences.setUserPreference);
+ assert.calledWith(config.preferences.setUserPreference, 1, true);
+ });
+ });
+ describe("RESET_GROUPS_STATE action", () => {
+ it("default calls resetGroupsState, loadMessagesFromAllProviders, and returns state", async () => {
+ const result = await handler.handleMessage(msg.RESET_GROUPS_STATE, {
+ property: "value",
+ });
+ assert.calledOnce(config.router.resetGroupsState);
+ assert.calledOnce(config.router.loadMessagesFromAllProviders);
+ assert.deepEqual(result, { value: 1 });
+ });
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/asrouter/ASRouterPreferences.test.js b/browser/components/newtab/test/unit/asrouter/ASRouterPreferences.test.js
new file mode 100644
index 0000000000..c241bc4308
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/ASRouterPreferences.test.js
@@ -0,0 +1,377 @@
+import {
+ _ASRouterPreferences,
+ ASRouterPreferences as ASRouterPreferencesSingleton,
+ TEST_PROVIDERS,
+} from "lib/ASRouterPreferences.jsm";
+const FAKE_PROVIDERS = [{ id: "foo" }, { id: "bar" }];
+
+const PROVIDER_PREF_BRANCH =
+ "browser.newtabpage.activity-stream.asrouter.providers.";
+const DEVTOOLS_PREF =
+ "browser.newtabpage.activity-stream.asrouter.devtoolsEnabled";
+const SNIPPETS_USER_PREF = "browser.newtabpage.activity-stream.feeds.snippets";
+const CFR_USER_PREF_ADDONS =
+ "browser.newtabpage.activity-stream.asrouter.userprefs.cfr.addons";
+const CFR_USER_PREF_FEATURES =
+ "browser.newtabpage.activity-stream.asrouter.userprefs.cfr.features";
+
+/** NUMBER_OF_PREFS_TO_OBSERVE includes:
+ * 1. asrouter.providers. pref branch
+ * 2. asrouter.devtoolsEnabled
+ * 3. browser.newtabpage.activity-stream.feeds.snippets (user preference - snippets)
+ * 4. browser.newtabpage.activity-stream.asrouter.userprefs.cfr.addons (user preference - cfr)
+ * 4. browser.newtabpage.activity-stream.asrouter.userprefs.cfr.features (user preference - cfr)
+ * 5. services.sync.username
+ */
+const NUMBER_OF_PREFS_TO_OBSERVE = 6;
+
+describe("ASRouterPreferences", () => {
+ let ASRouterPreferences;
+ let sandbox;
+ let addObserverStub;
+ let stringPrefStub;
+ let boolPrefStub;
+
+ beforeEach(() => {
+ ASRouterPreferences = new _ASRouterPreferences();
+
+ sandbox = sinon.createSandbox();
+ addObserverStub = sandbox.stub(global.Services.prefs, "addObserver");
+ stringPrefStub = sandbox.stub(global.Services.prefs, "getStringPref");
+ FAKE_PROVIDERS.forEach(provider => {
+ stringPrefStub
+ .withArgs(`${PROVIDER_PREF_BRANCH}${provider.id}`)
+ .returns(JSON.stringify(provider));
+ });
+ sandbox
+ .stub(global.Services.prefs, "getChildList")
+ .withArgs(PROVIDER_PREF_BRANCH)
+ .returns(
+ FAKE_PROVIDERS.map(provider => `${PROVIDER_PREF_BRANCH}${provider.id}`)
+ );
+
+ boolPrefStub = sandbox
+ .stub(global.Services.prefs, "getBoolPref")
+ .returns(false);
+ });
+
+ afterEach(() => {
+ sandbox.restore();
+ });
+
+ function getPrefNameForProvider(providerId) {
+ return `${PROVIDER_PREF_BRANCH}${providerId}`;
+ }
+
+ function setPrefForProvider(providerId, value) {
+ stringPrefStub
+ .withArgs(getPrefNameForProvider(providerId))
+ .returns(JSON.stringify(value));
+ }
+
+ it("ASRouterPreferences should be an instance of _ASRouterPreferences", () => {
+ assert.instanceOf(ASRouterPreferencesSingleton, _ASRouterPreferences);
+ });
+ describe("#init", () => {
+ it("should set ._initialized to true", () => {
+ ASRouterPreferences.init();
+ assert.isTrue(ASRouterPreferences._initialized);
+ });
+ it(`should set ${NUMBER_OF_PREFS_TO_OBSERVE} observers and not re-initialize if already initialized`, () => {
+ ASRouterPreferences.init();
+ assert.callCount(addObserverStub, NUMBER_OF_PREFS_TO_OBSERVE);
+ ASRouterPreferences.init();
+ ASRouterPreferences.init();
+ assert.callCount(addObserverStub, NUMBER_OF_PREFS_TO_OBSERVE);
+ });
+ });
+ describe("#uninit", () => {
+ it("should set ._initialized to false", () => {
+ ASRouterPreferences.init();
+ ASRouterPreferences.uninit();
+ assert.isFalse(ASRouterPreferences._initialized);
+ });
+ it("should clear cached values for ._initialized, .devtoolsEnabled", () => {
+ ASRouterPreferences.init();
+ // trigger caching
+ // eslint-disable-next-line no-unused-vars
+ const result = [
+ ASRouterPreferences.providers,
+ ASRouterPreferences.devtoolsEnabled,
+ ];
+ assert.isNotNull(
+ ASRouterPreferences._providers,
+ "providers should not be null"
+ );
+ assert.isNotNull(
+ ASRouterPreferences._devtoolsEnabled,
+ "devtolosEnabled should not be null"
+ );
+
+ ASRouterPreferences.uninit();
+ assert.isNull(ASRouterPreferences._providers);
+ assert.isNull(ASRouterPreferences._devtoolsEnabled);
+ });
+ it("should clear all listeners and remove observers (only once)", () => {
+ const removeStub = sandbox.stub(global.Services.prefs, "removeObserver");
+ ASRouterPreferences.init();
+ ASRouterPreferences.addListener(() => {});
+ ASRouterPreferences.addListener(() => {});
+ assert.equal(ASRouterPreferences._callbacks.size, 2);
+ ASRouterPreferences.uninit();
+ // Tests to make sure we don't remove observers that weren't set
+ ASRouterPreferences.uninit();
+
+ assert.callCount(removeStub, NUMBER_OF_PREFS_TO_OBSERVE);
+ assert.calledWith(removeStub, PROVIDER_PREF_BRANCH);
+ assert.calledWith(removeStub, DEVTOOLS_PREF);
+ assert.isEmpty(ASRouterPreferences._callbacks);
+ });
+ });
+ describe(".providers", () => {
+ it("should return the value the first time .providers is accessed", () => {
+ ASRouterPreferences.init();
+
+ const result = ASRouterPreferences.providers;
+ assert.deepEqual(result, FAKE_PROVIDERS);
+ // once per pref
+ assert.calledTwice(stringPrefStub);
+ });
+ it("should return the cached value the second time .providers is accessed", () => {
+ ASRouterPreferences.init();
+ const [, secondCall] = [
+ ASRouterPreferences.providers,
+ ASRouterPreferences.providers,
+ ];
+
+ assert.deepEqual(secondCall, FAKE_PROVIDERS);
+ // once per pref
+ assert.calledTwice(stringPrefStub);
+ });
+ it("should just parse the pref each time if ASRouterPreferences hasn't been initialized yet", () => {
+ // Intentionally not initialized
+ const [firstCall, secondCall] = [
+ ASRouterPreferences.providers,
+ ASRouterPreferences.providers,
+ ];
+
+ assert.deepEqual(firstCall, FAKE_PROVIDERS);
+ assert.deepEqual(secondCall, FAKE_PROVIDERS);
+ assert.callCount(stringPrefStub, 4);
+ });
+ it("should skip the pref without throwing if a pref is not parsable", () => {
+ stringPrefStub.withArgs(`${PROVIDER_PREF_BRANCH}foo`).returns("not json");
+ ASRouterPreferences.init();
+
+ assert.deepEqual(ASRouterPreferences.providers, [{ id: "bar" }]);
+ });
+ it("should include TEST_PROVIDERS if devtools is turned on", () => {
+ boolPrefStub.withArgs(DEVTOOLS_PREF).returns(true);
+ ASRouterPreferences.init();
+
+ assert.deepEqual(ASRouterPreferences.providers, [
+ ...TEST_PROVIDERS,
+ ...FAKE_PROVIDERS,
+ ]);
+ });
+ });
+ describe(".devtoolsEnabled", () => {
+ it("should read the pref the first time .devtoolsEnabled is accessed", () => {
+ ASRouterPreferences.init();
+
+ const result = ASRouterPreferences.devtoolsEnabled;
+ assert.deepEqual(result, false);
+ assert.calledOnce(boolPrefStub);
+ });
+ it("should return the cached value the second time .devtoolsEnabled is accessed", () => {
+ ASRouterPreferences.init();
+ const [, secondCall] = [
+ ASRouterPreferences.devtoolsEnabled,
+ ASRouterPreferences.devtoolsEnabled,
+ ];
+
+ assert.deepEqual(secondCall, false);
+ assert.calledOnce(boolPrefStub);
+ });
+ it("should just parse the pref each time if ASRouterPreferences hasn't been initialized yet", () => {
+ // Intentionally not initialized
+ const [firstCall, secondCall] = [
+ ASRouterPreferences.devtoolsEnabled,
+ ASRouterPreferences.devtoolsEnabled,
+ ];
+
+ assert.deepEqual(firstCall, false);
+ assert.deepEqual(secondCall, false);
+ assert.calledTwice(boolPrefStub);
+ });
+ });
+ describe("#getUserPreference(providerId)", () => {
+ it("should return the user preference for snippets", () => {
+ boolPrefStub.withArgs(SNIPPETS_USER_PREF).returns(true);
+ assert.isTrue(ASRouterPreferences.getUserPreference("snippets"));
+ });
+ });
+ describe("#getAllUserPreferences", () => {
+ it("should return all user preferences", () => {
+ boolPrefStub.withArgs(SNIPPETS_USER_PREF).returns(true);
+ boolPrefStub.withArgs(CFR_USER_PREF_ADDONS).returns(false);
+ boolPrefStub.withArgs(CFR_USER_PREF_FEATURES).returns(true);
+ const result = ASRouterPreferences.getAllUserPreferences();
+ assert.deepEqual(result, {
+ snippets: true,
+ cfrAddons: false,
+ cfrFeatures: true,
+ });
+ });
+ });
+ describe("#enableOrDisableProvider", () => {
+ it("should enable an existing provider if second param is true", () => {
+ const setStub = sandbox.stub(global.Services.prefs, "setStringPref");
+ setPrefForProvider("foo", { id: "foo", enabled: false });
+ assert.isFalse(ASRouterPreferences.providers[0].enabled);
+
+ ASRouterPreferences.enableOrDisableProvider("foo", true);
+
+ assert.calledWith(
+ setStub,
+ getPrefNameForProvider("foo"),
+ JSON.stringify({ id: "foo", enabled: true })
+ );
+ });
+ it("should disable an existing provider if second param is false", () => {
+ const setStub = sandbox.stub(global.Services.prefs, "setStringPref");
+ setPrefForProvider("foo", { id: "foo", enabled: true });
+ assert.isTrue(ASRouterPreferences.providers[0].enabled);
+
+ ASRouterPreferences.enableOrDisableProvider("foo", false);
+
+ assert.calledWith(
+ setStub,
+ getPrefNameForProvider("foo"),
+ JSON.stringify({ id: "foo", enabled: false })
+ );
+ });
+ it("should not throw if the id does not exist", () => {
+ assert.doesNotThrow(() => {
+ ASRouterPreferences.enableOrDisableProvider("does_not_exist", true);
+ });
+ });
+ it("should not throw if pref is not parseable", () => {
+ stringPrefStub
+ .withArgs(getPrefNameForProvider("foo"))
+ .returns("not valid");
+ assert.doesNotThrow(() => {
+ ASRouterPreferences.enableOrDisableProvider("foo", true);
+ });
+ });
+ });
+ describe("#setUserPreference", () => {
+ it("should do nothing if the pref doesn't exist", () => {
+ ASRouterPreferences.setUserPreference("foo", true);
+ assert.notCalled(boolPrefStub);
+ });
+ it("should set the given pref", () => {
+ const setStub = sandbox.stub(global.Services.prefs, "setBoolPref");
+ ASRouterPreferences.setUserPreference("snippets", true);
+ assert.calledWith(setStub, SNIPPETS_USER_PREF, true);
+ });
+ });
+ describe("#resetProviderPref", () => {
+ it("should reset the pref and user prefs", () => {
+ const resetStub = sandbox.stub(global.Services.prefs, "clearUserPref");
+ ASRouterPreferences.resetProviderPref();
+ FAKE_PROVIDERS.forEach(provider => {
+ assert.calledWith(resetStub, getPrefNameForProvider(provider.id));
+ });
+ assert.calledWith(resetStub, SNIPPETS_USER_PREF);
+ assert.calledWith(resetStub, CFR_USER_PREF_ADDONS);
+ assert.calledWith(resetStub, CFR_USER_PREF_FEATURES);
+ });
+ });
+ describe("observer, listeners", () => {
+ it("should invalidate .providers when the pref is changed", () => {
+ const testProvider = { id: "newstuff" };
+ const newProviders = [...FAKE_PROVIDERS, testProvider];
+
+ ASRouterPreferences.init();
+
+ assert.deepEqual(ASRouterPreferences.providers, FAKE_PROVIDERS);
+ stringPrefStub
+ .withArgs(getPrefNameForProvider(testProvider.id))
+ .returns(JSON.stringify(testProvider));
+ global.Services.prefs.getChildList
+ .withArgs(PROVIDER_PREF_BRANCH)
+ .returns(
+ newProviders.map(provider => getPrefNameForProvider(provider.id))
+ );
+ ASRouterPreferences.observe(
+ null,
+ null,
+ getPrefNameForProvider(testProvider.id)
+ );
+
+ // Cache should be invalidated so we access the new value of the pref now
+ assert.deepEqual(ASRouterPreferences.providers, newProviders);
+ });
+ it("should invalidate .devtoolsEnabled and .providers when the pref is changed", () => {
+ ASRouterPreferences.init();
+
+ assert.isFalse(ASRouterPreferences.devtoolsEnabled);
+ boolPrefStub.withArgs(DEVTOOLS_PREF).returns(true);
+ global.Services.prefs.getChildList
+ .withArgs(PROVIDER_PREF_BRANCH)
+ .returns([]);
+ ASRouterPreferences.observe(null, null, DEVTOOLS_PREF);
+
+ // Cache should be invalidated so we access the new value of the pref now
+ // Note that providers needs to be invalidated because devtools adds test content to it.
+ assert.isTrue(ASRouterPreferences.devtoolsEnabled);
+ assert.deepEqual(ASRouterPreferences.providers, TEST_PROVIDERS);
+ });
+ it("should call listeners added with .addListener", () => {
+ const callback1 = sinon.stub();
+ const callback2 = sinon.stub();
+ ASRouterPreferences.init();
+ ASRouterPreferences.addListener(callback1);
+ ASRouterPreferences.addListener(callback2);
+
+ ASRouterPreferences.observe(null, null, getPrefNameForProvider("foo"));
+ assert.calledWith(callback1, getPrefNameForProvider("foo"));
+
+ ASRouterPreferences.observe(null, null, DEVTOOLS_PREF);
+ assert.calledWith(callback2, DEVTOOLS_PREF);
+ });
+ it("should not call listeners after they are removed with .removeListeners", () => {
+ const callback = sinon.stub();
+ ASRouterPreferences.init();
+ ASRouterPreferences.addListener(callback);
+
+ ASRouterPreferences.observe(null, null, getPrefNameForProvider("foo"));
+ assert.calledWith(callback, getPrefNameForProvider("foo"));
+
+ callback.reset();
+ ASRouterPreferences.removeListener(callback);
+
+ ASRouterPreferences.observe(null, null, DEVTOOLS_PREF);
+ assert.notCalled(callback);
+ });
+ });
+ describe("#_transformPersonalizedCfrScores", () => {
+ it("should report JSON.parse errors", () => {
+ sandbox.stub(global.Cu, "reportError");
+
+ ASRouterPreferences._transformPersonalizedCfrScores("");
+
+ assert.calledOnce(global.Cu.reportError);
+ });
+ it("should return an object parsed from a string", () => {
+ const scores = { FOO: 3000, BAR: 4000 };
+ assert.deepEqual(
+ ASRouterPreferences._transformPersonalizedCfrScores(
+ JSON.stringify(scores)
+ ),
+ scores
+ );
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/asrouter/ASRouterTargeting.test.js b/browser/components/newtab/test/unit/asrouter/ASRouterTargeting.test.js
new file mode 100644
index 0000000000..e7810dc51a
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/ASRouterTargeting.test.js
@@ -0,0 +1,546 @@
+import {
+ ASRouterTargeting,
+ CachedTargetingGetter,
+ getSortedMessages,
+ QueryCache,
+} from "lib/ASRouterTargeting.jsm";
+import { OnboardingMessageProvider } from "lib/OnboardingMessageProvider.jsm";
+import { ASRouterPreferences } from "lib/ASRouterPreferences.jsm";
+import { GlobalOverrider } from "test/unit/utils";
+
+// Note that tests for the ASRouterTargeting environment can be found in
+// test/functional/mochitest/browser_asrouter_targeting.js
+
+describe("#CachedTargetingGetter", () => {
+ const sixHours = 6 * 60 * 60 * 1000;
+ let sandbox;
+ let clock;
+ let frecentStub;
+ let topsitesCache;
+ let globals;
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ clock = sinon.useFakeTimers();
+ frecentStub = sandbox.stub(
+ global.NewTabUtils.activityStreamProvider,
+ "getTopFrecentSites"
+ );
+ sandbox.stub(global.Cu, "reportError");
+ topsitesCache = new CachedTargetingGetter("getTopFrecentSites");
+ globals = new GlobalOverrider();
+ globals.set(
+ "TargetingContext",
+ class {
+ static combineContexts(...args) {
+ return sinon.stub();
+ }
+
+ evalWithDefault(expr) {
+ return sinon.stub();
+ }
+ }
+ );
+ });
+
+ afterEach(() => {
+ sandbox.restore();
+ clock.restore();
+ globals.restore();
+ });
+
+ it("should only make a request every 6 hours", async () => {
+ frecentStub.resolves();
+ clock.tick(sixHours);
+
+ await topsitesCache.get();
+ await topsitesCache.get();
+
+ assert.calledOnce(
+ global.NewTabUtils.activityStreamProvider.getTopFrecentSites
+ );
+
+ clock.tick(sixHours);
+
+ await topsitesCache.get();
+
+ assert.calledTwice(
+ global.NewTabUtils.activityStreamProvider.getTopFrecentSites
+ );
+ });
+ it("throws when failing getter", async () => {
+ frecentStub.rejects(new Error("fake error"));
+ clock.tick(sixHours);
+
+ // assert.throws expect a function as the first parameter, try/catch is a
+ // workaround
+ let rejected = false;
+ try {
+ await topsitesCache.get();
+ } catch (e) {
+ rejected = true;
+ }
+
+ assert(rejected);
+ });
+ describe("sortMessagesByPriority", () => {
+ it("should sort messages in descending priority order", async () => {
+ const [
+ m1,
+ m2,
+ m3 = { id: "m3" },
+ ] = await OnboardingMessageProvider.getUntranslatedMessages();
+ const checkMessageTargetingStub = sandbox
+ .stub(ASRouterTargeting, "checkMessageTargeting")
+ .resolves(false);
+ sandbox.stub(ASRouterTargeting, "isTriggerMatch").resolves(true);
+
+ await ASRouterTargeting.findMatchingMessage({
+ messages: [
+ { ...m1, priority: 0 },
+ { ...m2, priority: 1 },
+ { ...m3, priority: 2 },
+ ],
+ trigger: "testing",
+ });
+
+ assert.equal(checkMessageTargetingStub.callCount, 3);
+
+ const [arg_m1] = checkMessageTargetingStub.firstCall.args;
+ assert.equal(arg_m1.id, m3.id);
+
+ const [arg_m2] = checkMessageTargetingStub.secondCall.args;
+ assert.equal(arg_m2.id, m2.id);
+
+ const [arg_m3] = checkMessageTargetingStub.thirdCall.args;
+ assert.equal(arg_m3.id, m1.id);
+ });
+ it("should sort messages with no priority last", async () => {
+ const [
+ m1,
+ m2,
+ m3 = { id: "m3" },
+ ] = await OnboardingMessageProvider.getUntranslatedMessages();
+ const checkMessageTargetingStub = sandbox
+ .stub(ASRouterTargeting, "checkMessageTargeting")
+ .resolves(false);
+ sandbox.stub(ASRouterTargeting, "isTriggerMatch").resolves(true);
+
+ await ASRouterTargeting.findMatchingMessage({
+ messages: [
+ { ...m1, priority: 0 },
+ { ...m2, priority: undefined },
+ { ...m3, priority: 2 },
+ ],
+ trigger: "testing",
+ });
+
+ assert.equal(checkMessageTargetingStub.callCount, 3);
+
+ const [arg_m1] = checkMessageTargetingStub.firstCall.args;
+ assert.equal(arg_m1.id, m3.id);
+
+ const [arg_m2] = checkMessageTargetingStub.secondCall.args;
+ assert.equal(arg_m2.id, m1.id);
+
+ const [arg_m3] = checkMessageTargetingStub.thirdCall.args;
+ assert.equal(arg_m3.id, m2.id);
+ });
+ it("should keep the order of messages with same priority unchanged", async () => {
+ const [
+ m1,
+ m2,
+ m3 = { id: "m3" },
+ ] = await OnboardingMessageProvider.getUntranslatedMessages();
+ const checkMessageTargetingStub = sandbox
+ .stub(ASRouterTargeting, "checkMessageTargeting")
+ .resolves(false);
+ sandbox.stub(ASRouterTargeting, "isTriggerMatch").resolves(true);
+
+ await ASRouterTargeting.findMatchingMessage({
+ messages: [
+ { ...m1, priority: 2, targeting: undefined, rank: 1 },
+ { ...m2, priority: undefined, targeting: undefined, rank: 1 },
+ { ...m3, priority: 2, targeting: undefined, rank: 1 },
+ ],
+ trigger: "testing",
+ });
+
+ assert.equal(checkMessageTargetingStub.callCount, 3);
+
+ const [arg_m1] = checkMessageTargetingStub.firstCall.args;
+ assert.equal(arg_m1.id, m1.id);
+
+ const [arg_m2] = checkMessageTargetingStub.secondCall.args;
+ assert.equal(arg_m2.id, m3.id);
+
+ const [arg_m3] = checkMessageTargetingStub.thirdCall.args;
+ assert.equal(arg_m3.id, m2.id);
+ });
+ });
+});
+describe("#isTriggerMatch", () => {
+ let trigger;
+ let message;
+ beforeEach(() => {
+ trigger = { id: "openURL" };
+ message = { id: "openURL" };
+ });
+ it("should return false if trigger and candidate ids are different", () => {
+ trigger.id = "trigger";
+ message.id = "message";
+
+ assert.isFalse(ASRouterTargeting.isTriggerMatch(trigger, message));
+ assert.isTrue(
+ ASRouterTargeting.isTriggerMatch({ id: "foo" }, { id: "foo" })
+ );
+ });
+ it("should return true if the message we check doesn't have trigger params or patterns", () => {
+ // No params or patterns defined
+ assert.isTrue(ASRouterTargeting.isTriggerMatch(trigger, message));
+ });
+ it("should return false if the trigger does not have params defined", () => {
+ message.params = {};
+
+ // trigger.param is undefined
+ assert.isFalse(ASRouterTargeting.isTriggerMatch(trigger, message));
+ });
+ it("should return true if message params includes trigger host", () => {
+ message.params = ["mozilla.org"];
+ trigger.param = { host: "mozilla.org" };
+
+ assert.isTrue(ASRouterTargeting.isTriggerMatch(trigger, message));
+ });
+ it("should return true if message params includes trigger param.type", () => {
+ message.params = ["ContentBlockingMilestone"];
+ trigger.param = { type: "ContentBlockingMilestone" };
+
+ assert.isTrue(Boolean(ASRouterTargeting.isTriggerMatch(trigger, message)));
+ });
+ it("should return true if message params match trigger mask", () => {
+ // STATE_BLOCKED_FINGERPRINTING_CONTENT
+ message.params = [0x00000040];
+ trigger.param = { type: 538091584 };
+
+ assert.isTrue(Boolean(ASRouterTargeting.isTriggerMatch(trigger, message)));
+ });
+});
+describe("#CacheListAttachedOAuthClients", () => {
+ const fourHours = 4 * 60 * 60 * 1000;
+ let sandbox;
+ let clock;
+ let fakeFxAccount;
+ let authClientsCache;
+ let globals;
+
+ beforeEach(() => {
+ globals = new GlobalOverrider();
+ sandbox = sinon.createSandbox();
+ clock = sinon.useFakeTimers();
+ fakeFxAccount = {
+ listAttachedOAuthClients: () => {},
+ };
+ globals.set("fxAccounts", fakeFxAccount);
+ authClientsCache = QueryCache.queries.ListAttachedOAuthClients;
+ sandbox
+ .stub(fxAccounts, "listAttachedOAuthClients")
+ .returns(Promise.resolve({}));
+ });
+
+ afterEach(() => {
+ authClientsCache.expire();
+ sandbox.restore();
+ clock.restore();
+ });
+
+ it("should only make additional request every 4 hours", async () => {
+ clock.tick(fourHours);
+
+ await authClientsCache.get();
+ assert.calledOnce(fxAccounts.listAttachedOAuthClients);
+
+ clock.tick(fourHours);
+ await authClientsCache.get();
+ assert.calledTwice(fxAccounts.listAttachedOAuthClients);
+ });
+
+ it("should not make additional request before 4 hours", async () => {
+ clock.tick(fourHours);
+
+ await authClientsCache.get();
+ assert.calledOnce(fxAccounts.listAttachedOAuthClients);
+
+ await authClientsCache.get();
+ assert.calledOnce(fxAccounts.listAttachedOAuthClients);
+ });
+});
+describe("ASRouterTargeting", () => {
+ let evalStub;
+ let sandbox;
+ let clock;
+ let globals;
+ let fakeTargetingContext;
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ sandbox.replace(ASRouterTargeting, "Environment", {});
+ clock = sinon.useFakeTimers();
+ fakeTargetingContext = {
+ combineContexts: sandbox.stub(),
+ evalWithDefault: sandbox.stub().resolves(),
+ };
+ globals = new GlobalOverrider();
+ globals.set(
+ "TargetingContext",
+ class {
+ static combineContexts(...args) {
+ return fakeTargetingContext.combineContexts.apply(sandbox, args);
+ }
+
+ evalWithDefault(expr) {
+ return fakeTargetingContext.evalWithDefault(expr);
+ }
+ }
+ );
+ evalStub = fakeTargetingContext.evalWithDefault;
+ });
+ afterEach(() => {
+ clock.restore();
+ sandbox.restore();
+ globals.restore();
+ });
+ it("should cache evaluation result", async () => {
+ evalStub.resolves(true);
+ let targetingContext = new global.TargetingContext();
+
+ await ASRouterTargeting.checkMessageTargeting(
+ { targeting: "jexl1" },
+ targetingContext,
+ sandbox.stub(),
+ true
+ );
+ await ASRouterTargeting.checkMessageTargeting(
+ { targeting: "jexl2" },
+ targetingContext,
+ sandbox.stub(),
+ true
+ );
+ await ASRouterTargeting.checkMessageTargeting(
+ { targeting: "jexl1" },
+ targetingContext,
+ sandbox.stub(),
+ true
+ );
+
+ assert.calledTwice(evalStub);
+ });
+ it("should not cache evaluation result", async () => {
+ evalStub.resolves(true);
+ let targetingContext = new global.TargetingContext();
+
+ await ASRouterTargeting.checkMessageTargeting(
+ { targeting: "jexl" },
+ targetingContext,
+ sandbox.stub(),
+ false
+ );
+ await ASRouterTargeting.checkMessageTargeting(
+ { targeting: "jexl" },
+ targetingContext,
+ sandbox.stub(),
+ false
+ );
+ await ASRouterTargeting.checkMessageTargeting(
+ { targeting: "jexl" },
+ targetingContext,
+ sandbox.stub(),
+ false
+ );
+
+ assert.calledThrice(evalStub);
+ });
+ it("should expire cache entries", async () => {
+ evalStub.resolves(true);
+ let targetingContext = new global.TargetingContext();
+
+ await ASRouterTargeting.checkMessageTargeting(
+ { targeting: "jexl" },
+ targetingContext,
+ sandbox.stub(),
+ true
+ );
+ await ASRouterTargeting.checkMessageTargeting(
+ { targeting: "jexl" },
+ targetingContext,
+ sandbox.stub(),
+ true
+ );
+ clock.tick(5 * 60 * 1000 + 1);
+ await ASRouterTargeting.checkMessageTargeting(
+ { targeting: "jexl" },
+ targetingContext,
+ sandbox.stub(),
+ true
+ );
+
+ assert.calledTwice(evalStub);
+ });
+
+ describe("#findMatchingMessage", () => {
+ let matchStub;
+ let messages = [
+ { id: "FOO", targeting: "match" },
+ { id: "BAR", targeting: "match" },
+ { id: "BAZ" },
+ ];
+ beforeEach(() => {
+ matchStub = sandbox
+ .stub(ASRouterTargeting, "_isMessageMatch")
+ .callsFake(message => message.targeting === "match");
+ });
+ it("should return an array of matches if returnAll is true", async () => {
+ assert.deepEqual(
+ await ASRouterTargeting.findMatchingMessage({
+ messages,
+ returnAll: true,
+ }),
+ [
+ { id: "FOO", targeting: "match" },
+ { id: "BAR", targeting: "match" },
+ ]
+ );
+ });
+ it("should return an empty array if no matches were found and returnAll is true", async () => {
+ matchStub.returns(false);
+ assert.deepEqual(
+ await ASRouterTargeting.findMatchingMessage({
+ messages,
+ returnAll: true,
+ }),
+ []
+ );
+ });
+ it("should return the first match if returnAll is false", async () => {
+ assert.deepEqual(
+ await ASRouterTargeting.findMatchingMessage({
+ messages,
+ }),
+ messages[0]
+ );
+ });
+ it("should return null if if no matches were found and returnAll is false", async () => {
+ matchStub.returns(false);
+ assert.deepEqual(
+ await ASRouterTargeting.findMatchingMessage({
+ messages,
+ }),
+ null
+ );
+ });
+ });
+});
+
+/**
+ * Messages should be sorted in the following order:
+ * 1. Rank
+ * 2. Priority
+ * 3. If the message has targeting
+ * 4. Order or randomization, depending on input
+ */
+describe("getSortedMessages", () => {
+ let globals = new GlobalOverrider();
+ let sandbox;
+ let thresholdStub;
+ beforeEach(() => {
+ globals.set({ ASRouterPreferences });
+ sandbox = sinon.createSandbox();
+ thresholdStub = sandbox.stub();
+ sandbox.replaceGetter(
+ ASRouterPreferences,
+ "personalizedCfrThreshold",
+ thresholdStub
+ );
+ });
+ afterEach(() => {
+ sandbox.restore();
+ globals.restore();
+ });
+
+ /**
+ * assertSortsCorrectly - Tests to see if an array, when sorted with getSortedMessages,
+ * returns the items in the expected order.
+ *
+ * @param {Message[]} expectedOrderArray - The array of messages in its expected order
+ * @param {{}} options - The options param for getSortedMessages
+ * @returns
+ */
+ function assertSortsCorrectly(expectedOrderArray, options) {
+ const input = [...expectedOrderArray].reverse();
+ const result = getSortedMessages(input, options);
+ const indexes = result.map(message => expectedOrderArray.indexOf(message));
+ return assert.equal(
+ indexes.join(","),
+ [...expectedOrderArray.keys()].join(","),
+ "Messsages are out of order"
+ );
+ }
+
+ it("should sort messages by priority, then by targeting", () => {
+ assertSortsCorrectly([
+ { priority: 100, targeting: "isFoo" },
+ { priority: 100 },
+ { priority: 99 },
+ { priority: 1, targeting: "isFoo" },
+ { priority: 1 },
+ {},
+ ]);
+ });
+ it("should sort messages by score first if defined", () => {
+ assertSortsCorrectly([
+ { score: 7001 },
+ { score: 7000, priority: 1 },
+ { score: 7000, targeting: "isFoo" },
+ { score: 7000 },
+ { score: 6000, priority: 1000 },
+ { priority: 99999 },
+ {},
+ ]);
+ });
+ it("should sort messages by priority, then targeting, then order if ordered param is true", () => {
+ assertSortsCorrectly(
+ [
+ { priority: 100, order: 4 },
+ { priority: 100, order: 5 },
+ { priority: 1, order: 3, targeting: "isFoo" },
+ { priority: 1, order: 0 },
+ { priority: 1, order: 1 },
+ { priority: 1, order: 2 },
+ { order: 0 },
+ ],
+ { ordered: true }
+ );
+ });
+ it("should filter messages below the personalizedCfrThreshold", () => {
+ thresholdStub.returns(5000);
+ const result = getSortedMessages([{ score: 5000 }, { score: 4999 }, {}]);
+ assert.deepEqual(result, [{ score: 5000 }, {}]);
+ });
+ it("should not filter out messages without a score", () => {
+ thresholdStub.returns(5000);
+ const result = getSortedMessages([{ score: 4999 }, { id: "FOO" }]);
+ assert.deepEqual(result, [{ id: "FOO" }]);
+ });
+ it("should not apply filter if the threshold is an invalid value", () => {
+ let result;
+
+ thresholdStub.returns(undefined);
+ result = getSortedMessages([{ score: 5000 }, { score: 4999 }]);
+ assert.deepEqual(result, [{ score: 5000 }, { score: 4999 }]);
+
+ thresholdStub.returns("foo");
+ result = getSortedMessages([{ score: 5000 }, { score: 4999 }]);
+ assert.deepEqual(result, [{ score: 5000 }, { score: 4999 }]);
+
+ thresholdStub.returns(5000);
+ result = getSortedMessages([{ score: 5000 }, { score: 4999 }]);
+ assert.deepEqual(result, [{ score: 5000 }]);
+ });
+});
diff --git a/browser/components/newtab/test/unit/asrouter/ASRouterTriggerListeners.test.js b/browser/components/newtab/test/unit/asrouter/ASRouterTriggerListeners.test.js
new file mode 100644
index 0000000000..ed7137f1da
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/ASRouterTriggerListeners.test.js
@@ -0,0 +1,506 @@
+import { ASRouterTriggerListeners } from "lib/ASRouterTriggerListeners.jsm";
+import { GlobalOverrider } from "test/unit/utils";
+
+describe("ASRouterTriggerListeners", () => {
+ let sandbox;
+ let globals;
+ let existingWindow;
+ let isWindowPrivateStub;
+ const triggerHandler = () => {};
+ const openURLListener = ASRouterTriggerListeners.get("openURL");
+ const frequentVisitsListener = ASRouterTriggerListeners.get("frequentVisits");
+ const bookmarkedURLListener = ASRouterTriggerListeners.get(
+ "openBookmarkedURL"
+ );
+ const openArticleURLListener = ASRouterTriggerListeners.get("openArticleURL");
+ const hosts = ["www.mozilla.com", "www.mozilla.org"];
+
+ beforeEach(async () => {
+ sandbox = sinon.createSandbox();
+ globals = new GlobalOverrider();
+ existingWindow = {
+ gBrowser: {
+ addTabsProgressListener: sandbox.stub(),
+ removeTabsProgressListener: sandbox.stub(),
+ currentURI: { host: "" },
+ },
+ addEventListener: sinon.stub(),
+ removeEventListener: sinon.stub(),
+ };
+ sandbox.spy(openURLListener, "init");
+ sandbox.spy(openURLListener, "uninit");
+ isWindowPrivateStub = sandbox.stub();
+ // Assume no window is private so that we execute the action
+ isWindowPrivateStub.returns(false);
+ globals.set("PrivateBrowsingUtils", {
+ isWindowPrivate: isWindowPrivateStub,
+ });
+ const ewUninit = new Map();
+ globals.set("EveryWindow", {
+ registerCallback: (id, init, uninit) => {
+ init(existingWindow);
+ ewUninit.set(id, uninit);
+ },
+ unregisterCallback: id => {
+ ewUninit.get(id)(existingWindow);
+ },
+ });
+ });
+ afterEach(() => {
+ sandbox.restore();
+ globals.restore();
+ });
+
+ describe("openBookmarkedURL", () => {
+ let observerStub;
+ describe("#init", () => {
+ beforeEach(() => {
+ observerStub = sandbox.stub(global.Services.obs, "addObserver");
+ sandbox
+ .stub(global.Services.wm, "getMostRecentBrowserWindow")
+ .returns({ gBrowser: { selectedBrowser: {} } });
+ });
+ afterEach(() => {
+ bookmarkedURLListener.uninit();
+ });
+ it("should set hosts to the recentBookmarks", async () => {
+ await bookmarkedURLListener.init(sandbox.stub());
+
+ assert.calledOnce(observerStub);
+ assert.calledWithExactly(
+ observerStub,
+ bookmarkedURLListener,
+ "bookmark-icon-updated"
+ );
+ });
+ it("should provide id to triggerHandler", async () => {
+ const newTriggerHandler = sinon.stub();
+ const subject = {};
+ await bookmarkedURLListener.init(newTriggerHandler);
+
+ bookmarkedURLListener.observe(
+ subject,
+ "bookmark-icon-updated",
+ "starred"
+ );
+
+ assert.calledOnce(newTriggerHandler);
+ assert.calledWithExactly(newTriggerHandler, subject, {
+ id: bookmarkedURLListener.id,
+ });
+ });
+ });
+ });
+
+ describe("openArticleURL", () => {
+ describe("#init", () => {
+ beforeEach(() => {
+ globals.set(
+ "MatchPatternSet",
+ sandbox.stub().callsFake(patterns => ({
+ patterns,
+ matches: url => patterns.has(url),
+ }))
+ );
+ sandbox.stub(global.AboutReaderParent, "addMessageListener");
+ sandbox.stub(global.AboutReaderParent, "removeMessageListener");
+ });
+ afterEach(() => {
+ openArticleURLListener.uninit();
+ });
+ it("setup an event listener on init", () => {
+ openArticleURLListener.init(sandbox.stub(), hosts, hosts);
+
+ assert.calledOnce(global.AboutReaderParent.addMessageListener);
+ assert.calledWithExactly(
+ global.AboutReaderParent.addMessageListener,
+ openArticleURLListener.readerModeEvent,
+ sinon.match.object
+ );
+ });
+ it("should call triggerHandler correctly for matches [host match]", () => {
+ const stub = sandbox.stub();
+ const target = { currentURI: { host: hosts[0], spec: hosts[1] } };
+ openArticleURLListener.init(stub, hosts, hosts);
+
+ const [
+ ,
+ { receiveMessage },
+ ] = global.AboutReaderParent.addMessageListener.firstCall.args;
+ receiveMessage({ data: { isArticle: true }, target });
+
+ assert.calledOnce(stub);
+ assert.calledWithExactly(stub, target, {
+ id: openArticleURLListener.id,
+ param: { host: hosts[0], url: hosts[1] },
+ });
+ });
+ it("should call triggerHandler correctly for matches [pattern match]", () => {
+ const stub = sandbox.stub();
+ const target = { currentURI: { host: null, spec: hosts[1] } };
+ openArticleURLListener.init(stub, hosts, hosts);
+
+ const [
+ ,
+ { receiveMessage },
+ ] = global.AboutReaderParent.addMessageListener.firstCall.args;
+ receiveMessage({ data: { isArticle: true }, target });
+
+ assert.calledOnce(stub);
+ assert.calledWithExactly(stub, target, {
+ id: openArticleURLListener.id,
+ param: { host: null, url: hosts[1] },
+ });
+ });
+ it("should remove the message listener", () => {
+ openArticleURLListener.init(sandbox.stub(), hosts, hosts);
+ openArticleURLListener.uninit();
+
+ assert.calledOnce(global.AboutReaderParent.removeMessageListener);
+ });
+ });
+ });
+
+ describe("frequentVisits", () => {
+ let _triggerHandler;
+ beforeEach(() => {
+ _triggerHandler = sandbox.stub();
+ sandbox.useFakeTimers();
+ frequentVisitsListener.init(_triggerHandler, hosts);
+ });
+ afterEach(() => {
+ sandbox.clock.restore();
+ frequentVisitsListener.uninit();
+ });
+ it("should be initialized", () => {
+ assert.isTrue(frequentVisitsListener._initialized);
+ });
+ it("should listen for TabSelect events", () => {
+ assert.calledOnce(existingWindow.addEventListener);
+ assert.calledWith(
+ existingWindow.addEventListener,
+ "TabSelect",
+ frequentVisitsListener.onTabSwitch
+ );
+ });
+ it("should call _triggerHandler if the visit is valid (is recoreded)", () => {
+ frequentVisitsListener.triggerHandler({}, "www.mozilla.com");
+
+ assert.calledOnce(_triggerHandler);
+ });
+ it("should call _triggerHandler only once", () => {
+ frequentVisitsListener.triggerHandler({}, "www.mozilla.com");
+ frequentVisitsListener.triggerHandler({}, "www.mozilla.com");
+
+ assert.calledOnce(_triggerHandler);
+ });
+ it("should call _triggerHandler again after 15 minutes", () => {
+ frequentVisitsListener.triggerHandler({}, "www.mozilla.com");
+ sandbox.clock.tick(15 * 60 * 1000 + 1);
+ frequentVisitsListener.triggerHandler({}, "www.mozilla.com");
+
+ assert.calledTwice(_triggerHandler);
+ });
+ it("should call triggerHandler on valid hosts", () => {
+ const stub = sandbox.stub(frequentVisitsListener, "triggerHandler");
+ existingWindow.gBrowser.currentURI.host = hosts[0]; // eslint-disable-line prefer-destructuring
+
+ frequentVisitsListener.onTabSwitch({
+ target: { ownerGlobal: existingWindow },
+ });
+
+ assert.calledOnce(stub);
+ });
+ it("should not call triggerHandler on invalid hosts", () => {
+ const stub = sandbox.stub(frequentVisitsListener, "triggerHandler");
+ existingWindow.gBrowser.currentURI.host = "foo.com";
+
+ frequentVisitsListener.onTabSwitch({
+ target: { ownerGlobal: existingWindow },
+ });
+
+ assert.notCalled(stub);
+ });
+ describe("MatchPattern", () => {
+ beforeEach(() => {
+ globals.set(
+ "MatchPatternSet",
+ sandbox.stub().callsFake(patterns => ({ patterns: patterns || [] }))
+ );
+ });
+ afterEach(() => {
+ frequentVisitsListener.uninit();
+ });
+ it("should create a matchPatternSet", () => {
+ frequentVisitsListener.init(_triggerHandler, hosts, ["pattern"]);
+
+ assert.calledOnce(window.MatchPatternSet);
+ assert.calledWithExactly(
+ window.MatchPatternSet,
+ new Set(["pattern"]),
+ undefined
+ );
+ });
+ it("should allow to add multiple patterns and dedupe", () => {
+ frequentVisitsListener.init(_triggerHandler, hosts, ["pattern"]);
+ frequentVisitsListener.init(_triggerHandler, hosts, ["foo"]);
+
+ assert.calledTwice(window.MatchPatternSet);
+ assert.calledWithExactly(
+ window.MatchPatternSet,
+ new Set(["pattern", "foo"]),
+ undefined
+ );
+ });
+ it("should handle bad arguments to MatchPatternSet", () => {
+ const badArgs = ["www.example.com"];
+ window.MatchPatternSet.withArgs(new Set(badArgs)).throws();
+ frequentVisitsListener.init(_triggerHandler, hosts, badArgs);
+
+ // Fails with an empty MatchPatternSet
+ assert.property(frequentVisitsListener._matchPatternSet, "patterns");
+
+ // Second try is succesful
+ frequentVisitsListener.init(_triggerHandler, hosts, ["foo"]);
+
+ assert.property(frequentVisitsListener._matchPatternSet, "patterns");
+ assert.isTrue(
+ frequentVisitsListener._matchPatternSet.patterns.has("foo")
+ );
+ });
+ });
+ });
+
+ describe("openURL listener", () => {
+ it("should exist and initially be uninitialised", () => {
+ assert.ok(openURLListener);
+ assert.notOk(openURLListener._initialized);
+ });
+
+ describe("#init", () => {
+ beforeEach(() => {
+ openURLListener.init(triggerHandler, hosts);
+ });
+ afterEach(() => {
+ openURLListener.uninit();
+ });
+
+ it("should set ._initialized to true and save the triggerHandler and hosts", () => {
+ assert.ok(openURLListener._initialized);
+ assert.deepEqual(openURLListener._hosts, new Set(hosts));
+ assert.equal(openURLListener._triggerHandler, triggerHandler);
+ });
+
+ it("should add tab progress listeners to all existing browser windows", () => {
+ assert.calledOnce(existingWindow.gBrowser.addTabsProgressListener);
+ assert.calledWithExactly(
+ existingWindow.gBrowser.addTabsProgressListener,
+ openURLListener
+ );
+ });
+
+ it("if already initialised, should only update the trigger handler and add the new hosts", () => {
+ const newHosts = ["www.example.com"];
+ const newTriggerHandler = () => {};
+ existingWindow.gBrowser.addTabsProgressListener.reset();
+
+ openURLListener.init(newTriggerHandler, newHosts);
+ assert.ok(openURLListener._initialized);
+ assert.deepEqual(
+ openURLListener._hosts,
+ new Set([...hosts, ...newHosts])
+ );
+ assert.equal(openURLListener._triggerHandler, newTriggerHandler);
+ assert.notCalled(existingWindow.gBrowser.addTabsProgressListener);
+ });
+ });
+
+ describe("#uninit", () => {
+ beforeEach(async () => {
+ openURLListener.init(triggerHandler, hosts);
+ openURLListener.uninit();
+ });
+
+ it("should set ._initialized to false and clear the triggerHandler and hosts", () => {
+ assert.notOk(openURLListener._initialized);
+ assert.equal(openURLListener._hosts, null);
+ assert.equal(openURLListener._triggerHandler, null);
+ });
+
+ it("should remove tab progress listeners from all existing browser windows", () => {
+ assert.calledOnce(existingWindow.gBrowser.removeTabsProgressListener);
+ assert.calledWithExactly(
+ existingWindow.gBrowser.removeTabsProgressListener,
+ openURLListener
+ );
+ });
+
+ it("should do nothing if already uninitialised", () => {
+ existingWindow.gBrowser.removeTabsProgressListener.reset();
+
+ openURLListener.uninit();
+ assert.notOk(openURLListener._initialized);
+ assert.notCalled(existingWindow.gBrowser.removeTabsProgressListener);
+ });
+ });
+
+ describe("#onLocationChange", () => {
+ afterEach(() => {
+ openURLListener.uninit();
+ frequentVisitsListener.uninit();
+ });
+
+ it("should call the ._triggerHandler with the right arguments", () => {
+ const newTriggerHandler = sinon.stub();
+ openURLListener.init(newTriggerHandler, hosts);
+
+ const browser = {};
+ const webProgress = { isTopLevel: true };
+ const location = "www.mozilla.org";
+ openURLListener.onLocationChange(browser, webProgress, undefined, {
+ host: location,
+ spec: location,
+ });
+ assert.calledOnce(newTriggerHandler);
+ assert.calledWithExactly(newTriggerHandler, browser, {
+ id: "openURL",
+ param: { host: "www.mozilla.org", url: "www.mozilla.org" },
+ context: { visitsCount: 1 },
+ });
+ });
+ it("should call triggerHandler for a redirect (openURL + frequentVisits)", () => {
+ for (let trigger of [openURLListener, frequentVisitsListener]) {
+ const newTriggerHandler = sinon.stub();
+ trigger.init(newTriggerHandler, hosts);
+
+ const browser = {};
+ const webProgress = { isTopLevel: true };
+ const aLocationURI = {
+ host: "subdomain.mozilla.org",
+ spec: "subdomain.mozilla.org",
+ };
+ const aRequest = {
+ QueryInterface: sandbox.stub().returns({
+ originalURI: { spec: "www.mozilla.org", host: "www.mozilla.org" },
+ }),
+ };
+ trigger.onLocationChange(
+ browser,
+ webProgress,
+ aRequest,
+ aLocationURI
+ );
+ assert.calledOnce(aRequest.QueryInterface);
+ assert.calledOnce(newTriggerHandler);
+ }
+ });
+ it("should call triggerHandler with the right arguments (redirect)", () => {
+ const newTriggerHandler = sinon.stub();
+ openURLListener.init(newTriggerHandler, hosts);
+
+ const browser = {};
+ const webProgress = { isTopLevel: true };
+ const aLocationURI = {
+ host: "subdomain.mozilla.org",
+ spec: "subdomain.mozilla.org",
+ };
+ const aRequest = {
+ QueryInterface: sandbox.stub().returns({
+ originalURI: { spec: "www.mozilla.org", host: "www.mozilla.org" },
+ }),
+ };
+ openURLListener.onLocationChange(
+ browser,
+ webProgress,
+ aRequest,
+ aLocationURI
+ );
+ assert.calledWithExactly(newTriggerHandler, browser, {
+ id: "openURL",
+ param: { host: "www.mozilla.org", url: "www.mozilla.org" },
+ context: { visitsCount: 1 },
+ });
+ });
+ it("should call triggerHandler for a redirect (openURL + frequentVisits)", () => {
+ for (let trigger of [openURLListener, frequentVisitsListener]) {
+ const newTriggerHandler = sinon.stub();
+ trigger.init(newTriggerHandler, hosts);
+
+ const browser = {};
+ const webProgress = { isTopLevel: true };
+ const aLocationURI = {
+ host: "subdomain.mozilla.org",
+ spec: "subdomain.mozilla.org",
+ };
+ const aRequest = {
+ QueryInterface: sandbox.stub().returns({
+ originalURI: { spec: "www.mozilla.org", host: "www.mozilla.org" },
+ }),
+ };
+ trigger.onLocationChange(
+ browser,
+ webProgress,
+ aRequest,
+ aLocationURI
+ );
+ assert.calledOnce(aRequest.QueryInterface);
+ assert.calledOnce(newTriggerHandler);
+ }
+ });
+ it("should call triggerHandler with the right arguments (redirect)", () => {
+ const newTriggerHandler = sinon.stub();
+ openURLListener.init(newTriggerHandler, hosts);
+
+ const browser = {};
+ const webProgress = { isTopLevel: true };
+ const aLocationURI = {
+ host: "subdomain.mozilla.org",
+ spec: "subdomain.mozilla.org",
+ };
+ const aRequest = {
+ QueryInterface: sandbox.stub().returns({
+ originalURI: { spec: "www.mozilla.org", host: "www.mozilla.org" },
+ }),
+ };
+ openURLListener.onLocationChange(
+ browser,
+ webProgress,
+ aRequest,
+ aLocationURI
+ );
+ assert.calledWithExactly(newTriggerHandler, browser, {
+ id: "openURL",
+ param: { host: "www.mozilla.org", url: "www.mozilla.org" },
+ context: { visitsCount: 1 },
+ });
+ });
+ it("should fail for subdomains (not redirect)", () => {
+ const newTriggerHandler = sinon.stub();
+ openURLListener.init(newTriggerHandler, hosts);
+
+ const browser = {};
+ const webProgress = { isTopLevel: true };
+ const aLocationURI = {
+ host: "subdomain.mozilla.org",
+ spec: "subdomain.mozilla.org",
+ };
+ const aRequest = {
+ QueryInterface: sandbox.stub().returns({
+ originalURI: {
+ spec: "subdomain.mozilla.org",
+ host: "subdomain.mozilla.org",
+ },
+ }),
+ };
+ openURLListener.onLocationChange(
+ browser,
+ webProgress,
+ aRequest,
+ aLocationURI
+ );
+ assert.calledOnce(aRequest.QueryInterface);
+ assert.notCalled(newTriggerHandler);
+ });
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/asrouter/CFRMessageProvider.test.js b/browser/components/newtab/test/unit/asrouter/CFRMessageProvider.test.js
new file mode 100644
index 0000000000..0b4f97d265
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/CFRMessageProvider.test.js
@@ -0,0 +1,46 @@
+import { CFRMessageProvider } from "lib/CFRMessageProvider.jsm";
+
+const REGULAR_IDS = [
+ "FACEBOOK_CONTAINER",
+ "GOOGLE_TRANSLATE",
+ "YOUTUBE_ENHANCE",
+ // These are excluded for now.
+ // "WIKIPEDIA_CONTEXT_MENU_SEARCH",
+ // "REDDIT_ENHANCEMENT",
+];
+
+describe("CFRMessageProvider", () => {
+ let messages;
+ beforeEach(async () => {
+ messages = await CFRMessageProvider.getMessages();
+ });
+ it("should have a total of 14 messages", () => {
+ assert.lengthOf(messages, 14);
+ });
+ it("should have one message each for the three regular addons", () => {
+ for (const id of REGULAR_IDS) {
+ const cohort3 = messages.find(msg => msg.id === `${id}_3`);
+ assert.ok(cohort3, `contains three day cohort for ${id}`);
+ assert.deepEqual(
+ cohort3.frequency,
+ { lifetime: 3 },
+ "three day cohort has the right frequency cap"
+ );
+ assert.notInclude(cohort3.targeting, `providerCohorts.cfr`);
+ }
+ });
+ it("should restrict locale for PIN_TAB message", () => {
+ const pinTabMessage = messages.find(m => m.id === "PIN_TAB");
+
+ // 6 en-* locales, fr and de
+ assert.lengthOf(pinTabMessage.targeting.match(/en-|fr|de/g), 8);
+ });
+ it("should contain `www.` version of the hosts", () => {
+ const pinTabMessage = messages.find(m => m.id === "PIN_TAB");
+
+ assert.isTrue(
+ !!pinTabMessage.trigger.params.filter(host => host.startsWith("www."))
+ .length
+ );
+ });
+});
diff --git a/browser/components/newtab/test/unit/asrouter/CFRPageActions.test.js b/browser/components/newtab/test/unit/asrouter/CFRPageActions.test.js
new file mode 100644
index 0000000000..97bc8ecb03
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/CFRPageActions.test.js
@@ -0,0 +1,1241 @@
+/* eslint max-nested-callbacks: ["error", 100] */
+
+import { CFRPageActions, PageAction } from "lib/CFRPageActions.jsm";
+import { FAKE_RECOMMENDATION } from "./constants";
+import { GlobalOverrider } from "test/unit/utils";
+import { CFRMessageProvider } from "lib/CFRMessageProvider.jsm";
+
+describe("CFRPageActions", () => {
+ let sandbox;
+ let clock;
+ let fakeRecommendation;
+ let fakeHost;
+ let fakeBrowser;
+ let dispatchStub;
+ let globals;
+ let containerElem;
+ let elements;
+ let announceStub;
+ let fakeRemoteL10n;
+
+ const elementIDs = [
+ "urlbar",
+ "urlbar-input",
+ "contextual-feature-recommendation",
+ "cfr-button",
+ "cfr-label",
+ "contextual-feature-recommendation-notification",
+ "cfr-notification-header-label",
+ "cfr-notification-header-link",
+ "cfr-notification-header-image",
+ "cfr-notification-author",
+ "cfr-notification-footer",
+ "cfr-notification-footer-text",
+ "cfr-notification-footer-filled-stars",
+ "cfr-notification-footer-empty-stars",
+ "cfr-notification-footer-users",
+ "cfr-notification-footer-spacer",
+ "cfr-notification-footer-learn-more-link",
+ "cfr-notification-footer-pintab-animation-container",
+ "cfr-notification-footer-animation-button",
+ "cfr-notification-footer-animation-label",
+ ];
+ const elementClassNames = ["popup-notification-body-container"];
+
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ clock = sandbox.useFakeTimers();
+
+ announceStub = sandbox.stub();
+ const A11yUtils = { announce: announceStub };
+ fakeRecommendation = { ...FAKE_RECOMMENDATION };
+ fakeHost = "mozilla.org";
+ fakeBrowser = {
+ documentURI: {
+ scheme: "https",
+ host: fakeHost,
+ },
+ ownerGlobal: window,
+ };
+ dispatchStub = sandbox.stub();
+
+ fakeRemoteL10n = {
+ l10n: {},
+ reloadL10n: sandbox.stub(),
+ createElement: sandbox.stub().returns(document.createElement("div")),
+ };
+
+ const gURLBar = document.createElement("div");
+ gURLBar.textbox = document.createElement("div");
+
+ globals = new GlobalOverrider();
+ globals.set({
+ RemoteL10n: fakeRemoteL10n,
+ promiseDocumentFlushed: sandbox
+ .stub()
+ .callsFake(fn => Promise.resolve(fn())),
+ PopupNotifications: {
+ show: sandbox.stub(),
+ remove: sandbox.stub(),
+ },
+ PrivateBrowsingUtils: { isWindowPrivate: sandbox.stub().returns(false) },
+ gBrowser: { selectedBrowser: fakeBrowser },
+ A11yUtils,
+ gURLBar,
+ });
+ document.createXULElement = document.createElement;
+
+ elements = {};
+ const [body] = document.getElementsByTagName("body");
+ containerElem = document.createElement("div");
+ body.appendChild(containerElem);
+ for (const id of elementIDs) {
+ const elem = document.createElement("div");
+ elem.setAttribute("id", id);
+ containerElem.appendChild(elem);
+ elements[id] = elem;
+ }
+ for (const className of elementClassNames) {
+ const elem = document.createElement("div");
+ elem.setAttribute("class", className);
+ containerElem.appendChild(elem);
+ elements[className] = elem;
+ }
+ });
+
+ afterEach(() => {
+ CFRPageActions.clearRecommendations();
+ containerElem.remove();
+ sandbox.restore();
+ globals.restore();
+ });
+
+ describe("PageAction", () => {
+ let pageAction;
+
+ beforeEach(() => {
+ pageAction = new PageAction(window, dispatchStub);
+ });
+
+ describe("#addImpression", () => {
+ it("should call _sendTelemetry with the impression payload", () => {
+ const recommendation = {
+ id: "foo",
+ content: { bucket_id: "bar" },
+ };
+ sandbox.spy(pageAction, "_sendTelemetry");
+
+ pageAction.addImpression(recommendation);
+
+ assert.calledWith(pageAction._sendTelemetry, {
+ message_id: "foo",
+ bucket_id: "bar",
+ event: "IMPRESSION",
+ });
+ });
+ it("should include modelVersion if presented in the message", () => {
+ const recommendation = {
+ id: "foo",
+ content: { bucket_id: "bar" },
+ personalizedModelVersion: "model_version_1",
+ };
+ sandbox.spy(pageAction, "_sendTelemetry");
+
+ pageAction.addImpression(recommendation);
+
+ assert.calledWith(pageAction._sendTelemetry, {
+ message_id: "foo",
+ bucket_id: "bar",
+ event: "IMPRESSION",
+ event_context: {
+ modelVersion: "model_version_1",
+ },
+ });
+ });
+ });
+
+ describe("#showAddressBarNotifier", () => {
+ it("should un-hideAddressBarNotifier the element and set the right label value", async () => {
+ await pageAction.showAddressBarNotifier(fakeRecommendation);
+ assert.isFalse(pageAction.container.hidden);
+ assert.equal(
+ pageAction.label.value,
+ fakeRecommendation.content.notification_text
+ );
+ });
+ it("should wait for the document layout to flush", async () => {
+ sandbox.spy(pageAction.label, "getClientRects");
+ await pageAction.showAddressBarNotifier(fakeRecommendation);
+ assert.calledOnce(global.promiseDocumentFlushed);
+ assert.callOrder(
+ global.promiseDocumentFlushed,
+ pageAction.label.getClientRects
+ );
+ });
+ it("should set the CSS variable --cfr-label-width correctly", async () => {
+ await pageAction.showAddressBarNotifier(fakeRecommendation);
+ const expectedWidth = pageAction.label.getClientRects()[0].width;
+ assert.equal(
+ pageAction.urlbarinput.style.getPropertyValue("--cfr-label-width"),
+ `${expectedWidth}px`
+ );
+ });
+ it("should cause an expansion, and dispatch an impression if `expand` is true", async () => {
+ sandbox.spy(pageAction, "_clearScheduledStateChanges");
+ sandbox.spy(pageAction, "_expand");
+ sandbox.spy(pageAction, "_dispatchImpression");
+
+ await pageAction.showAddressBarNotifier(fakeRecommendation);
+ assert.notCalled(pageAction._dispatchImpression);
+ clock.tick(1001);
+ assert.notEqual(
+ pageAction.urlbarinput.getAttribute("cfr-recommendation-state"),
+ "expanded"
+ );
+
+ await pageAction.showAddressBarNotifier(fakeRecommendation, true);
+ assert.calledOnce(pageAction._clearScheduledStateChanges);
+ clock.tick(1001);
+ assert.equal(
+ pageAction.urlbarinput.getAttribute("cfr-recommendation-state"),
+ "expanded"
+ );
+ assert.calledOnce(pageAction._dispatchImpression);
+ assert.calledWith(pageAction._dispatchImpression, fakeRecommendation);
+ });
+ it("should send telemetry if `expand` is true and the id and bucket_id are provided", async () => {
+ await pageAction.showAddressBarNotifier(fakeRecommendation, true);
+ assert.calledWith(dispatchStub, {
+ type: "DOORHANGER_TELEMETRY",
+ data: {
+ action: "cfr_user_event",
+ source: "CFR",
+ message_id: fakeRecommendation.id,
+ bucket_id: fakeRecommendation.content.bucket_id,
+ event: "IMPRESSION",
+ },
+ });
+ });
+ });
+
+ describe("#hideAddressBarNotifier", () => {
+ it("should hideAddressBarNotifier the container, cancel any state changes, and remove the state attribute", () => {
+ sandbox.spy(pageAction, "_clearScheduledStateChanges");
+ pageAction.hideAddressBarNotifier();
+ assert.isTrue(pageAction.container.hidden);
+ assert.calledOnce(pageAction._clearScheduledStateChanges);
+ assert.isNull(
+ pageAction.urlbar.getAttribute("cfr-recommendation-state")
+ );
+ });
+ it("should remove the `currentNotification`", () => {
+ const notification = {};
+ pageAction.currentNotification = notification;
+ pageAction.hideAddressBarNotifier();
+ assert.calledWith(global.PopupNotifications.remove, notification);
+ });
+ });
+
+ describe("#_expand", () => {
+ beforeEach(() => {
+ pageAction._clearScheduledStateChanges();
+ pageAction.urlbar.removeAttribute("cfr-recommendation-state");
+ });
+ it("without a delay, should clear other state changes and set the state to 'expanded'", () => {
+ sandbox.spy(pageAction, "_clearScheduledStateChanges");
+ pageAction._expand();
+ assert.calledOnce(pageAction._clearScheduledStateChanges);
+ assert.equal(
+ pageAction.urlbarinput.getAttribute("cfr-recommendation-state"),
+ "expanded"
+ );
+ });
+ it("with a delay, should set the expanded state after the correct amount of time", () => {
+ const delay = 1234;
+ pageAction._expand(delay);
+ // We expect that an expansion has been scheduled
+ assert.lengthOf(pageAction.stateTransitionTimeoutIDs, 1);
+ clock.tick(delay + 1);
+ assert.equal(
+ pageAction.urlbarinput.getAttribute("cfr-recommendation-state"),
+ "expanded"
+ );
+ });
+ });
+
+ describe("#_collapse", () => {
+ beforeEach(() => {
+ pageAction._clearScheduledStateChanges();
+ pageAction.urlbar.removeAttribute("cfr-recommendation-state");
+ });
+ it("without a delay, should clear other state changes and set the state to collapsed only if it's already expanded", () => {
+ sandbox.spy(pageAction, "_clearScheduledStateChanges");
+ pageAction._collapse();
+ assert.calledOnce(pageAction._clearScheduledStateChanges);
+ assert.isNull(
+ pageAction.urlbarinput.getAttribute("cfr-recommendation-state")
+ );
+ pageAction.urlbarinput.setAttribute(
+ "cfr-recommendation-state",
+ "expanded"
+ );
+ pageAction._collapse();
+ assert.equal(
+ pageAction.urlbarinput.getAttribute("cfr-recommendation-state"),
+ "collapsed"
+ );
+ });
+ it("with a delay, should set the collapsed state after the correct amount of time", () => {
+ const delay = 1234;
+ pageAction._collapse(delay);
+ clock.tick(delay + 1);
+ // The state was _not_ "expanded" and so should not have been set to "collapsed"
+ assert.isNull(
+ pageAction.urlbar.getAttribute("cfr-recommendation-state")
+ );
+
+ pageAction._expand();
+ pageAction._collapse(delay);
+ // We expect that a collapse has been scheduled
+ assert.lengthOf(pageAction.stateTransitionTimeoutIDs, 1);
+ clock.tick(delay + 1);
+ // This time it was "expanded" so should now (after the delay) be "collapsed"
+ assert.equal(
+ pageAction.urlbarinput.getAttribute("cfr-recommendation-state"),
+ "collapsed"
+ );
+ });
+ });
+
+ describe("#_clearScheduledStateChanges", () => {
+ it("should call .clearTimeout on all stored timeoutIDs", () => {
+ pageAction.stateTransitionTimeoutIDs = [42, 73, 1997];
+ sandbox.spy(pageAction.window, "clearTimeout");
+ pageAction._clearScheduledStateChanges();
+ assert.calledThrice(pageAction.window.clearTimeout);
+ assert.calledWith(pageAction.window.clearTimeout, 42);
+ assert.calledWith(pageAction.window.clearTimeout, 73);
+ assert.calledWith(pageAction.window.clearTimeout, 1997);
+ });
+ });
+
+ describe("#_popupStateChange", () => {
+ it("should collapse the notification on 'dismissed'", () => {
+ pageAction._expand();
+
+ pageAction._popupStateChange("dismissed");
+ assert.equal(
+ pageAction.urlbarinput.getAttribute("cfr-recommendation-state"),
+ "collapsed"
+ );
+ });
+ it("should remove the notification on 'removed'", () => {
+ pageAction._expand();
+ const fakeNotification = {};
+
+ pageAction.currentNotification = fakeNotification;
+ pageAction._popupStateChange("removed");
+ assert.calledOnce(global.PopupNotifications.remove);
+ assert.calledWith(global.PopupNotifications.remove, fakeNotification);
+ });
+ it("should do nothing for other states", () => {
+ pageAction._popupStateChange("opened");
+ assert.notCalled(global.PopupNotifications.remove);
+ });
+ });
+
+ describe("#dispatchUserAction", () => {
+ it("should call ._dispatchCFRAction with the right action", () => {
+ const fakeAction = {};
+ pageAction.dispatchUserAction(fakeAction);
+ assert.calledOnce(dispatchStub);
+ assert.calledWith(
+ dispatchStub,
+ { type: "USER_ACTION", data: fakeAction },
+ fakeBrowser
+ );
+ });
+ });
+
+ describe("#_dispatchImpression", () => {
+ it("should call ._dispatchCFRAction with the right action", () => {
+ pageAction._dispatchImpression("fake impression");
+ assert.calledWith(dispatchStub, {
+ type: "IMPRESSION",
+ data: "fake impression",
+ });
+ });
+ });
+
+ describe("#_sendTelemetry", () => {
+ it("should call ._dispatchCFRAction with the right action", () => {
+ const fakePing = { message_id: 42 };
+ pageAction._sendTelemetry(fakePing);
+ assert.calledWith(dispatchStub, {
+ type: "DOORHANGER_TELEMETRY",
+ data: { action: "cfr_user_event", source: "CFR", message_id: 42 },
+ });
+ });
+ });
+
+ describe("#_blockMessage", () => {
+ it("should call ._dispatchCFRAction with the right action", () => {
+ pageAction._blockMessage("fake id");
+ assert.calledOnce(dispatchStub);
+ assert.calledWith(dispatchStub, {
+ type: "BLOCK_MESSAGE_BY_ID",
+ data: { id: "fake id" },
+ });
+ });
+ });
+
+ describe("#getStrings", () => {
+ let formatMessagesStub;
+ const localeStrings = [
+ {
+ value: "你好世界",
+ attributes: [
+ { name: "first_attr", value: 42 },
+ { name: "second_attr", value: "some string" },
+ { name: "third_attr", value: [1, 2, 3] },
+ ],
+ },
+ ];
+
+ beforeEach(() => {
+ formatMessagesStub = sandbox
+ .stub()
+ .withArgs({ id: "hello_world" })
+ .resolves(localeStrings);
+ global.RemoteL10n.l10n.formatMessages = formatMessagesStub;
+ });
+
+ it("should return the argument if a string_id is not defined", async () => {
+ assert.deepEqual(await pageAction.getStrings({}), {});
+ assert.equal(await pageAction.getStrings("some string"), "some string");
+ });
+ it("should get the right locale string", async () => {
+ assert.equal(
+ await pageAction.getStrings({ string_id: "hello_world" }),
+ localeStrings[0].value
+ );
+ });
+ it("should return the right sub-attribute if specified", async () => {
+ assert.equal(
+ await pageAction.getStrings(
+ { string_id: "hello_world" },
+ "second_attr"
+ ),
+ "some string"
+ );
+ });
+ it("should attach attributes to string overrides", async () => {
+ const fromJson = { value: "Add Now", attributes: { accesskey: "A" } };
+
+ const result = await pageAction.getStrings(fromJson);
+
+ assert.equal(result, fromJson.value);
+ assert.propertyVal(result.attributes, "accesskey", "A");
+ });
+ it("should return subAttributes when doing string overrides", async () => {
+ const fromJson = { value: "Add Now", attributes: { accesskey: "A" } };
+
+ const result = await pageAction.getStrings(fromJson, "accesskey");
+
+ assert.equal(result, "A");
+ });
+ it("should resolve ftl strings and attach subAttributes", async () => {
+ const fromFtl = { string_id: "cfr-doorhanger-extension-ok-button" };
+ formatMessagesStub.resolves([
+ { value: "Add Now", attributes: [{ name: "accesskey", value: "A" }] },
+ ]);
+
+ const result = await pageAction.getStrings(fromFtl);
+
+ assert.equal(result, "Add Now");
+ assert.propertyVal(result.attributes, "accesskey", "A");
+ });
+ it("should return subAttributes from ftl ids", async () => {
+ const fromFtl = { string_id: "cfr-doorhanger-extension-ok-button" };
+ formatMessagesStub.resolves([
+ { value: "Add Now", attributes: [{ name: "accesskey", value: "A" }] },
+ ]);
+
+ const result = await pageAction.getStrings(fromFtl, "accesskey");
+
+ assert.equal(result, "A");
+ });
+ it("should report an error when no attributes are present but subAttribute is requested", async () => {
+ const fromJson = { value: "Foo" };
+ const stub = sandbox.stub(global.Cu, "reportError");
+
+ await pageAction.getStrings(fromJson, "accesskey");
+
+ assert.calledOnce(stub);
+ stub.restore();
+ });
+ });
+
+ describe("#_cfrUrlbarButtonClick", () => {
+ let translateElementsStub;
+ let setAttributesStub;
+ let getStringsStub;
+ beforeEach(async () => {
+ CFRPageActions.PageActionMap.set(fakeBrowser.ownerGlobal, pageAction);
+ await CFRPageActions.addRecommendation(
+ fakeBrowser,
+ fakeHost,
+ fakeRecommendation,
+ dispatchStub
+ );
+ getStringsStub = sandbox.stub(pageAction, "getStrings").resolves("");
+ getStringsStub
+ .callsFake(async a => a) // eslint-disable-line max-nested-callbacks
+ .withArgs({ string_id: "primary_button_id" })
+ .resolves({ value: "Primary Button", attributes: { accesskey: "p" } })
+ .withArgs({ string_id: "secondary_button_id" })
+ .resolves({
+ value: "Secondary Button",
+ attributes: { accesskey: "s" },
+ })
+ .withArgs({ string_id: "secondary_button_id_2" })
+ .resolves({
+ value: "Secondary Button 2",
+ attributes: { accesskey: "a" },
+ })
+ .withArgs({ string_id: "secondary_button_id_3" })
+ .resolves({
+ value: "Secondary Button 3",
+ attributes: { accesskey: "g" },
+ })
+ .withArgs(
+ sinon.match({
+ string_id: "cfr-doorhanger-extension-learn-more-link",
+ })
+ )
+ .resolves("Learn more")
+ .withArgs(
+ sinon.match({ string_id: "cfr-doorhanger-extension-total-users" })
+ )
+ .callsFake(async ({ args }) => `${args.total} users`); // eslint-disable-line max-nested-callbacks
+
+ translateElementsStub = sandbox.stub().resolves();
+ setAttributesStub = sandbox.stub();
+ global.RemoteL10n.l10n.setAttributes = setAttributesStub;
+ global.RemoteL10n.l10n.translateElements = translateElementsStub;
+ });
+
+ it("should call `.hideAddressBarNotifier` and do nothing if there is no recommendation for the selected browser", async () => {
+ sandbox.spy(pageAction, "hideAddressBarNotifier");
+ CFRPageActions.RecommendationMap.delete(fakeBrowser);
+ await pageAction._cfrUrlbarButtonClick({});
+ assert.calledOnce(pageAction.hideAddressBarNotifier);
+ assert.notCalled(global.PopupNotifications.show);
+ });
+ it("should cancel any planned state changes", async () => {
+ sandbox.spy(pageAction, "_clearScheduledStateChanges");
+ assert.notCalled(pageAction._clearScheduledStateChanges);
+ await pageAction._cfrUrlbarButtonClick({});
+ assert.calledOnce(pageAction._clearScheduledStateChanges);
+ });
+ it("should set the right text values", async () => {
+ await pageAction._cfrUrlbarButtonClick({});
+ const headerLabel = elements["cfr-notification-header-label"];
+ const headerLink = elements["cfr-notification-header-link"];
+ const headerImage = elements["cfr-notification-header-image"];
+ const footerLink = elements["cfr-notification-footer-learn-more-link"];
+ assert.equal(
+ headerLabel.value,
+ fakeRecommendation.content.heading_text
+ );
+ assert.isTrue(
+ headerLink
+ .getAttribute("href")
+ .endsWith(fakeRecommendation.content.info_icon.sumo_path)
+ );
+ assert.equal(
+ headerImage.getAttribute("tooltiptext"),
+ fakeRecommendation.content.info_icon.label
+ );
+ const htmlFooterEl = fakeRemoteL10n.createElement.args.find(
+ /* eslint-disable-next-line max-nested-callbacks */
+ ([doc, el, args]) =>
+ args && args.content === fakeRecommendation.content.text
+ );
+ assert.ok(htmlFooterEl);
+ assert.equal(footerLink.value, "Learn more");
+ assert.equal(
+ footerLink.getAttribute("href"),
+ fakeRecommendation.content.addon.amo_url
+ );
+ });
+ it("should add the rating correctly", async () => {
+ await pageAction._cfrUrlbarButtonClick();
+ const footerFilledStars =
+ elements["cfr-notification-footer-filled-stars"];
+ const footerEmptyStars =
+ elements["cfr-notification-footer-empty-stars"];
+ // .toFixed to sort out some floating precision errors
+ assert.equal(
+ footerFilledStars.style.width,
+ `${(4.2 * 17).toFixed(1)}px`
+ );
+ assert.equal(
+ footerEmptyStars.style.width,
+ `${(0.8 * 17).toFixed(1)}px`
+ );
+ });
+ it("should add the number of users correctly", async () => {
+ await pageAction._cfrUrlbarButtonClick();
+ const footerUsers = elements["cfr-notification-footer-users"];
+ assert.isNull(footerUsers.getAttribute("hidden"));
+ assert.equal(
+ footerUsers.getAttribute("value"),
+ `${fakeRecommendation.content.addon.users} users`
+ );
+ });
+ it("should send the right telemetry", async () => {
+ await pageAction._cfrUrlbarButtonClick();
+ assert.calledWith(dispatchStub, {
+ type: "DOORHANGER_TELEMETRY",
+ data: {
+ action: "cfr_user_event",
+ source: "CFR",
+ message_id: fakeRecommendation.id,
+ bucket_id: fakeRecommendation.content.bucket_id,
+ event: "CLICK_DOORHANGER",
+ },
+ });
+ });
+ it("should send modelVersion if presented in the message", async () => {
+ const recommendationWithModelVersion = {
+ ...fakeRecommendation,
+ personalizedModelVersion: "model_version_1",
+ };
+ CFRPageActions.clearRecommendations();
+ await CFRPageActions.addRecommendation(
+ fakeBrowser,
+ fakeHost,
+ recommendationWithModelVersion,
+ dispatchStub
+ );
+ await pageAction._cfrUrlbarButtonClick();
+
+ assert.calledWith(dispatchStub, {
+ type: "DOORHANGER_TELEMETRY",
+ data: {
+ action: "cfr_user_event",
+ source: "CFR",
+ message_id: fakeRecommendation.id,
+ bucket_id: fakeRecommendation.content.bucket_id,
+ event: "CLICK_DOORHANGER",
+ event_context: { modelVersion: "model_version_1" },
+ },
+ });
+ });
+ it("should set the main action correctly", async () => {
+ sinon
+ .stub(CFRPageActions, "_fetchLatestAddonVersion")
+ .resolves("latest-addon.xpi");
+ await pageAction._cfrUrlbarButtonClick();
+ const mainAction = global.PopupNotifications.show.firstCall.args[4]; // eslint-disable-line prefer-destructuring
+ assert.deepEqual(mainAction.label, {
+ value: "Primary Button",
+ attributes: { accesskey: "p" },
+ });
+ sandbox.spy(pageAction, "hideAddressBarNotifier");
+ await mainAction.callback();
+ assert.calledOnce(pageAction.hideAddressBarNotifier);
+ // Should block the message
+ assert.calledWith(dispatchStub, {
+ type: "BLOCK_MESSAGE_BY_ID",
+ data: { id: fakeRecommendation.id },
+ });
+ // Should trigger the action
+ assert.calledWith(
+ dispatchStub,
+ {
+ type: "USER_ACTION",
+ data: { id: "primary_action", data: { url: "latest-addon.xpi" } },
+ },
+ fakeBrowser
+ );
+ // Should send telemetry
+ assert.calledWith(dispatchStub, {
+ type: "DOORHANGER_TELEMETRY",
+ data: {
+ action: "cfr_user_event",
+ source: "CFR",
+ message_id: fakeRecommendation.id,
+ bucket_id: fakeRecommendation.content.bucket_id,
+ event: "INSTALL",
+ },
+ });
+ // Should remove the recommendation
+ assert.isFalse(CFRPageActions.RecommendationMap.has(fakeBrowser));
+ });
+ it("should set the secondary action correctly", async () => {
+ await pageAction._cfrUrlbarButtonClick();
+ // eslint-disable-next-line prefer-destructuring
+ const [
+ secondaryAction,
+ ] = global.PopupNotifications.show.firstCall.args[5];
+
+ assert.deepEqual(secondaryAction.label, {
+ value: "Secondary Button",
+ attributes: { accesskey: "s" },
+ });
+ sandbox.spy(pageAction, "hideAddressBarNotifier");
+ CFRPageActions.RecommendationMap.set(fakeBrowser, {});
+ secondaryAction.callback();
+ // Should send telemetry
+ assert.calledWith(dispatchStub, {
+ type: "DOORHANGER_TELEMETRY",
+ data: {
+ action: "cfr_user_event",
+ source: "CFR",
+ message_id: fakeRecommendation.id,
+ bucket_id: fakeRecommendation.content.bucket_id,
+ event: "DISMISS",
+ },
+ });
+ // Don't remove the recommendation on `DISMISS` action
+ assert.isTrue(CFRPageActions.RecommendationMap.has(fakeBrowser));
+ assert.notCalled(pageAction.hideAddressBarNotifier);
+ });
+ it("should send right telemetry for BLOCK secondary action", async () => {
+ await pageAction._cfrUrlbarButtonClick();
+ // eslint-disable-next-line prefer-destructuring
+ const blockAction = global.PopupNotifications.show.firstCall.args[5][1];
+
+ assert.deepEqual(blockAction.label, {
+ value: "Secondary Button 2",
+ attributes: { accesskey: "a" },
+ });
+ sandbox.spy(pageAction, "hideAddressBarNotifier");
+ sandbox.spy(pageAction, "_blockMessage");
+ CFRPageActions.RecommendationMap.set(fakeBrowser, {});
+ blockAction.callback();
+ assert.calledOnce(pageAction.hideAddressBarNotifier);
+ assert.calledOnce(pageAction._blockMessage);
+ // Should send telemetry
+ assert.calledWith(dispatchStub, {
+ type: "DOORHANGER_TELEMETRY",
+ data: {
+ action: "cfr_user_event",
+ source: "CFR",
+ message_id: fakeRecommendation.id,
+ bucket_id: fakeRecommendation.content.bucket_id,
+ event: "BLOCK",
+ },
+ });
+ // Should remove the recommendation
+ assert.isFalse(CFRPageActions.RecommendationMap.has(fakeBrowser));
+ });
+ it("should send right telemetry for MANAGE secondary action", async () => {
+ await pageAction._cfrUrlbarButtonClick();
+ // eslint-disable-next-line prefer-destructuring
+ const manageAction =
+ global.PopupNotifications.show.firstCall.args[5][2];
+
+ assert.deepEqual(manageAction.label, {
+ value: "Secondary Button 3",
+ attributes: { accesskey: "g" },
+ });
+ sandbox.spy(pageAction, "hideAddressBarNotifier");
+ CFRPageActions.RecommendationMap.set(fakeBrowser, {});
+ manageAction.callback();
+ // Should send telemetry
+ assert.calledWith(dispatchStub, {
+ type: "DOORHANGER_TELEMETRY",
+ data: {
+ action: "cfr_user_event",
+ source: "CFR",
+ message_id: fakeRecommendation.id,
+ bucket_id: fakeRecommendation.content.bucket_id,
+ event: "MANAGE",
+ },
+ });
+ // Don't remove the recommendation on `MANAGE` action
+ assert.isTrue(CFRPageActions.RecommendationMap.has(fakeBrowser));
+ assert.notCalled(pageAction.hideAddressBarNotifier);
+ });
+ it("should call PopupNotifications.show with the right arguments", async () => {
+ await pageAction._cfrUrlbarButtonClick();
+ assert.calledWith(
+ global.PopupNotifications.show,
+ fakeBrowser,
+ "contextual-feature-recommendation",
+ fakeRecommendation.content.addon.title,
+ "cfr",
+ sinon.match.any, // Corresponds to the main action, tested above
+ sinon.match.any, // Corresponds to the secondary action, tested above
+ {
+ popupIconURL: fakeRecommendation.content.addon.icon,
+ hideClose: true,
+ eventCallback: pageAction._popupStateChange,
+ persistent: false,
+ }
+ );
+ });
+ it("should show the bullet list details", async () => {
+ fakeRecommendation.content.layout = "message_and_animation";
+ await pageAction._cfrUrlbarButtonClick();
+
+ assert.ok(
+ fakeRemoteL10n.createElement.args.find(
+ /* eslint-disable-next-line max-nested-callbacks */
+ ([doc, el, args]) => el === "span" && args && args.content
+ )
+ );
+ });
+ it("should set the data-l10n-id on the list element", async () => {
+ fakeRecommendation.content.layout = "message_and_animation";
+ await pageAction._cfrUrlbarButtonClick();
+
+ for (let step of fakeRecommendation.content.descriptionDetails.steps) {
+ fakeRemoteL10n.createElement.args.find(
+ /* eslint-disable-next-line max-nested-callbacks */
+ ([doc, el, args]) => el === "span" && args && args.content === step
+ );
+ }
+ });
+ it("should set the correct data-notification-category", async () => {
+ fakeRecommendation.content.layout = "message_and_animation";
+ await pageAction._cfrUrlbarButtonClick();
+
+ assert.equal(
+ elements["contextual-feature-recommendation-notification"].dataset
+ .notificationCategory,
+ fakeRecommendation.content.layout
+ );
+ });
+ it("should send PIN event on primary action click", async () => {
+ fakeRecommendation.content.layout = "message_and_animation";
+ sandbox.stub(pageAction, "_sendTelemetry");
+ await pageAction._cfrUrlbarButtonClick();
+
+ const [
+ ,
+ ,
+ ,
+ ,
+ { callback },
+ ] = global.PopupNotifications.show.firstCall.args;
+ callback();
+
+ // First call is triggered by `_cfrUrlbarButtonClick`
+ assert.propertyVal(
+ pageAction._sendTelemetry.secondCall.args[0],
+ "event",
+ "PIN"
+ );
+ });
+ });
+ describe("#_cfrUrlbarButtonClick/cfr_urlbar_chiclet", () => {
+ let heartbeatRecommendation;
+ beforeEach(async () => {
+ heartbeatRecommendation = (await CFRMessageProvider.getMessages()).find(
+ m => m.template === "cfr_urlbar_chiclet"
+ );
+ CFRPageActions.PageActionMap.set(fakeBrowser.ownerGlobal, pageAction);
+ await CFRPageActions.addRecommendation(
+ fakeBrowser,
+ fakeHost,
+ heartbeatRecommendation,
+ dispatchStub
+ );
+ });
+ it("should dispatch a click event", async () => {
+ await pageAction._cfrUrlbarButtonClick({});
+
+ assert.calledWith(dispatchStub, {
+ type: "DOORHANGER_TELEMETRY",
+ data: {
+ action: "cfr_user_event",
+ source: "CFR",
+ message_id: heartbeatRecommendation.id,
+ bucket_id: heartbeatRecommendation.content.bucket_id,
+ event: "CLICK_DOORHANGER",
+ },
+ });
+ });
+ it("should dispatch a USER_ACTION for chiclet_open_url layout", async () => {
+ await pageAction._cfrUrlbarButtonClick({});
+
+ assert.calledWith(dispatchStub, {
+ type: "USER_ACTION",
+ data: {
+ data: {
+ args: heartbeatRecommendation.content.action.url,
+ where: heartbeatRecommendation.content.action.where,
+ },
+ type: "OPEN_URL",
+ },
+ });
+ });
+ it("should block the message after the click", async () => {
+ await pageAction._cfrUrlbarButtonClick({});
+
+ assert.calledWith(dispatchStub, {
+ type: "BLOCK_MESSAGE_BY_ID",
+ data: { id: heartbeatRecommendation.id },
+ });
+ });
+ it("should remove the button and browser entry", async () => {
+ sandbox.spy(pageAction, "hideAddressBarNotifier");
+
+ await pageAction._cfrUrlbarButtonClick({});
+
+ assert.calledOnce(pageAction.hideAddressBarNotifier);
+ assert.isFalse(CFRPageActions.RecommendationMap.has(fakeBrowser));
+ });
+ });
+ });
+
+ describe("CFRPageActions", () => {
+ beforeEach(() => {
+ // Spy on the prototype methods to inspect calls for any PageAction instance
+ sandbox.spy(PageAction.prototype, "showAddressBarNotifier");
+ sandbox.spy(PageAction.prototype, "hideAddressBarNotifier");
+ });
+
+ describe("updatePageActions", () => {
+ let savedRec;
+
+ beforeEach(() => {
+ const win = fakeBrowser.ownerGlobal;
+ CFRPageActions.PageActionMap.set(
+ win,
+ new PageAction(win, dispatchStub)
+ );
+ const { id, content } = fakeRecommendation;
+ savedRec = {
+ id,
+ host: fakeHost,
+ content,
+ };
+ CFRPageActions.RecommendationMap.set(fakeBrowser, savedRec);
+ });
+
+ it("should do nothing if a pageAction doesn't exist for the window", () => {
+ const win = fakeBrowser.ownerGlobal;
+ CFRPageActions.PageActionMap.delete(win);
+ CFRPageActions.updatePageActions(fakeBrowser);
+ assert.notCalled(PageAction.prototype.showAddressBarNotifier);
+ assert.notCalled(PageAction.prototype.hideAddressBarNotifier);
+ });
+ it("should do nothing if the browser is not the `selectedBrowser`", () => {
+ const someOtherFakeBrowser = {};
+ CFRPageActions.updatePageActions(someOtherFakeBrowser);
+ assert.notCalled(PageAction.prototype.showAddressBarNotifier);
+ assert.notCalled(PageAction.prototype.hideAddressBarNotifier);
+ });
+ it("should hideAddressBarNotifier the pageAction if a recommendation doesn't exist for the given browser", () => {
+ CFRPageActions.RecommendationMap.delete(fakeBrowser);
+ CFRPageActions.updatePageActions(fakeBrowser);
+ assert.calledOnce(PageAction.prototype.hideAddressBarNotifier);
+ });
+ it("should show the pageAction if a recommendation exists and the host matches", () => {
+ CFRPageActions.updatePageActions(fakeBrowser);
+ assert.calledOnce(PageAction.prototype.showAddressBarNotifier);
+ assert.calledWith(
+ PageAction.prototype.showAddressBarNotifier,
+ savedRec
+ );
+ });
+ it("should show the pageAction if a recommendation exists and it doesn't have a host defined", () => {
+ const recNoHost = { ...savedRec, host: undefined };
+ CFRPageActions.RecommendationMap.set(fakeBrowser, recNoHost);
+ CFRPageActions.updatePageActions(fakeBrowser);
+ assert.calledOnce(PageAction.prototype.showAddressBarNotifier);
+ assert.calledWith(
+ PageAction.prototype.showAddressBarNotifier,
+ recNoHost
+ );
+ });
+ it("should hideAddressBarNotifier the pageAction and delete the recommendation if the recommendation exists but the host doesn't match", () => {
+ const someOtherFakeHost = "subdomain.mozilla.com";
+ fakeBrowser.documentURI.host = someOtherFakeHost;
+ assert.isTrue(CFRPageActions.RecommendationMap.has(fakeBrowser));
+ CFRPageActions.updatePageActions(fakeBrowser);
+ assert.calledOnce(PageAction.prototype.hideAddressBarNotifier);
+ assert.isFalse(CFRPageActions.RecommendationMap.has(fakeBrowser));
+ });
+ it("should not call `delete` if retain is true", () => {
+ savedRec.retain = true;
+ fakeBrowser.documentURI.host = "subdomain.mozilla.com";
+ assert.isTrue(CFRPageActions.RecommendationMap.has(fakeBrowser));
+
+ CFRPageActions.updatePageActions(fakeBrowser);
+ assert.propertyVal(savedRec, "retain", false);
+ assert.calledOnce(PageAction.prototype.hideAddressBarNotifier);
+ assert.isTrue(CFRPageActions.RecommendationMap.has(fakeBrowser));
+ });
+ it("should call `delete` if retain is false", () => {
+ savedRec.retain = false;
+ fakeBrowser.documentURI.host = "subdomain.mozilla.com";
+ assert.isTrue(CFRPageActions.RecommendationMap.has(fakeBrowser));
+
+ CFRPageActions.updatePageActions(fakeBrowser);
+ assert.propertyVal(savedRec, "retain", false);
+ assert.calledOnce(PageAction.prototype.hideAddressBarNotifier);
+ assert.isFalse(CFRPageActions.RecommendationMap.has(fakeBrowser));
+ });
+ });
+
+ describe("forceRecommendation", () => {
+ it("should succeed and add an element to the RecommendationMap", async () => {
+ assert.isTrue(
+ await CFRPageActions.forceRecommendation(
+ fakeBrowser,
+ fakeRecommendation,
+ dispatchStub
+ )
+ );
+ assert.deepInclude(CFRPageActions.RecommendationMap.get(fakeBrowser), {
+ id: fakeRecommendation.id,
+ content: fakeRecommendation.content,
+ });
+ });
+ it("should create a PageAction if one doesn't exist for the window, save it in the PageActionMap, and call `show`", async () => {
+ const win = fakeBrowser.ownerGlobal;
+ assert.isFalse(CFRPageActions.PageActionMap.has(win));
+ await CFRPageActions.forceRecommendation(
+ fakeBrowser,
+ fakeRecommendation,
+ dispatchStub
+ );
+ const pageAction = CFRPageActions.PageActionMap.get(win);
+ assert.equal(win, pageAction.window);
+ assert.equal(dispatchStub, pageAction._dispatchCFRAction);
+ assert.calledOnce(PageAction.prototype.showAddressBarNotifier);
+ });
+ });
+
+ describe("addRecommendation", () => {
+ it("should fail and not add a recommendation if the browser is part of a private window", async () => {
+ global.PrivateBrowsingUtils.isWindowPrivate.returns(true);
+ assert.isFalse(
+ await CFRPageActions.addRecommendation(
+ fakeBrowser,
+ fakeHost,
+ fakeRecommendation,
+ dispatchStub
+ )
+ );
+ assert.isFalse(CFRPageActions.RecommendationMap.has(fakeBrowser));
+ });
+ it("should fail and not add a recommendation if the browser is not the selected browser", async () => {
+ global.gBrowser.selectedBrowser = {}; // Some other browser
+ assert.isFalse(
+ await CFRPageActions.addRecommendation(
+ fakeBrowser,
+ fakeHost,
+ fakeRecommendation,
+ dispatchStub
+ )
+ );
+ });
+ it("should fail and not add a recommendation if the host doesn't match", async () => {
+ const someOtherFakeHost = "subdomain.mozilla.com";
+ assert.isFalse(
+ await CFRPageActions.addRecommendation(
+ fakeBrowser,
+ someOtherFakeHost,
+ fakeRecommendation,
+ dispatchStub
+ )
+ );
+ });
+ it("should otherwise succeed and add an element to the RecommendationMap", async () => {
+ assert.isTrue(
+ await CFRPageActions.addRecommendation(
+ fakeBrowser,
+ fakeHost,
+ fakeRecommendation,
+ dispatchStub
+ )
+ );
+ assert.deepInclude(CFRPageActions.RecommendationMap.get(fakeBrowser), {
+ id: fakeRecommendation.id,
+ host: fakeHost,
+ content: fakeRecommendation.content,
+ });
+ });
+ it("should create a PageAction if one doesn't exist for the window, save it in the PageActionMap, and call `show`", async () => {
+ const win = fakeBrowser.ownerGlobal;
+ assert.isFalse(CFRPageActions.PageActionMap.has(win));
+ await CFRPageActions.addRecommendation(
+ fakeBrowser,
+ fakeHost,
+ fakeRecommendation,
+ dispatchStub
+ );
+ const pageAction = CFRPageActions.PageActionMap.get(win);
+ assert.equal(win, pageAction.window);
+ assert.equal(dispatchStub, pageAction._dispatchCFRAction);
+ assert.calledOnce(PageAction.prototype.showAddressBarNotifier);
+ });
+ it("should add the right url if we fetched and addon install URL", async () => {
+ fakeRecommendation.template = "cfr_doorhanger";
+ await CFRPageActions.addRecommendation(
+ fakeBrowser,
+ fakeHost,
+ fakeRecommendation,
+ dispatchStub
+ );
+ const recommendation = CFRPageActions.RecommendationMap.get(
+ fakeBrowser
+ );
+
+ // sanity check - just go through some of the rest of the attributes to make sure they were untouched
+ assert.equal(recommendation.id, fakeRecommendation.id);
+ assert.equal(
+ recommendation.content.heading_text,
+ fakeRecommendation.content.heading_text
+ );
+ assert.equal(
+ recommendation.content.addon,
+ fakeRecommendation.content.addon
+ );
+ assert.equal(
+ recommendation.content.text,
+ fakeRecommendation.content.text
+ );
+ assert.equal(
+ recommendation.content.buttons.secondary,
+ fakeRecommendation.content.buttons.secondary
+ );
+ assert.equal(
+ recommendation.content.buttons.primary.action.id,
+ fakeRecommendation.content.buttons.primary.action.id
+ );
+
+ delete fakeRecommendation.template;
+ });
+ it("should prevent a second message if one is currently displayed", async () => {
+ const secondMessage = { ...fakeRecommendation, id: "second_message" };
+ let messageAdded = await CFRPageActions.addRecommendation(
+ fakeBrowser,
+ fakeHost,
+ fakeRecommendation,
+ dispatchStub
+ );
+
+ assert.isTrue(messageAdded);
+ assert.deepInclude(CFRPageActions.RecommendationMap.get(fakeBrowser), {
+ id: fakeRecommendation.id,
+ host: fakeHost,
+ content: fakeRecommendation.content,
+ });
+
+ messageAdded = await CFRPageActions.addRecommendation(
+ fakeBrowser,
+ fakeHost,
+ secondMessage,
+ dispatchStub
+ );
+ // Adding failed
+ assert.isFalse(messageAdded);
+ // First message is still there
+ assert.deepInclude(CFRPageActions.RecommendationMap.get(fakeBrowser), {
+ id: fakeRecommendation.id,
+ host: fakeHost,
+ content: fakeRecommendation.content,
+ });
+ });
+ it("should send impressions just for the first message", async () => {
+ const secondMessage = { ...fakeRecommendation, id: "second_message" };
+ await CFRPageActions.addRecommendation(
+ fakeBrowser,
+ fakeHost,
+ fakeRecommendation,
+ dispatchStub
+ );
+ await CFRPageActions.addRecommendation(
+ fakeBrowser,
+ fakeHost,
+ secondMessage,
+ dispatchStub
+ );
+
+ // Doorhanger telemetry + Impression for just 1 message
+ assert.calledTwice(dispatchStub);
+ const [firstArgs] = dispatchStub.firstCall.args;
+ const [secondArgs] = dispatchStub.secondCall.args;
+ assert.equal(firstArgs.data.id, secondArgs.data.message_id);
+ });
+ });
+
+ describe("clearRecommendations", () => {
+ const createFakePageAction = () => ({
+ hideAddressBarNotifier: sandbox.stub(),
+ });
+ const windows = [{}, {}, { closed: true }];
+ const browsers = [{}, {}, {}, {}];
+
+ beforeEach(() => {
+ CFRPageActions.PageActionMap.set(windows[0], createFakePageAction());
+ CFRPageActions.PageActionMap.set(windows[2], createFakePageAction());
+ for (const browser of browsers) {
+ CFRPageActions.RecommendationMap.set(browser, {});
+ }
+ globals.set({ Services: { wm: { getEnumerator: () => windows } } });
+ });
+
+ it("should hideAddressBarNotifier the PageActions of any existing, non-closed windows", () => {
+ const pageActions = windows.map(win =>
+ CFRPageActions.PageActionMap.get(win)
+ );
+ CFRPageActions.clearRecommendations();
+
+ // Only the first window had a PageAction and wasn't closed
+ assert.calledOnce(pageActions[0].hideAddressBarNotifier);
+ assert.isUndefined(pageActions[1]);
+ assert.notCalled(pageActions[2].hideAddressBarNotifier);
+ });
+ it("should clear the PageActionMap and the RecommendationMap", () => {
+ CFRPageActions.clearRecommendations();
+
+ // Both are WeakMaps and so are not iterable, cannot be cleared, and
+ // cannot have their length queried directly, so we have to check
+ // whether previous elements still exist
+ assert.lengthOf(windows, 3);
+ for (const win of windows) {
+ assert.isFalse(CFRPageActions.PageActionMap.has(win));
+ }
+ assert.lengthOf(browsers, 4);
+ for (const browser of browsers) {
+ assert.isFalse(CFRPageActions.RecommendationMap.has(browser));
+ }
+ });
+ });
+
+ describe("reloadL10n", () => {
+ const createFakePageAction = () => ({
+ hideAddressBarNotifier() {},
+ reloadL10n: sandbox.stub(),
+ });
+ const windows = [{}, {}, { closed: true }];
+
+ beforeEach(() => {
+ CFRPageActions.PageActionMap.set(windows[0], createFakePageAction());
+ CFRPageActions.PageActionMap.set(windows[2], createFakePageAction());
+ globals.set({ Services: { wm: { getEnumerator: () => windows } } });
+ });
+
+ it("should call reloadL10n for all the PageActions of any existing, non-closed windows", () => {
+ const pageActions = windows.map(win =>
+ CFRPageActions.PageActionMap.get(win)
+ );
+ CFRPageActions.reloadL10n();
+
+ // Only the first window had a PageAction and wasn't closed
+ assert.calledOnce(pageActions[0].reloadL10n);
+ assert.isUndefined(pageActions[1]);
+ assert.notCalled(pageActions[2].reloadL10n);
+ });
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/asrouter/MessageLoaderUtils.test.js b/browser/components/newtab/test/unit/asrouter/MessageLoaderUtils.test.js
new file mode 100644
index 0000000000..d855f89d27
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/MessageLoaderUtils.test.js
@@ -0,0 +1,459 @@
+import { MessageLoaderUtils } from "lib/ASRouter.jsm";
+const { STARTPAGE_VERSION } = MessageLoaderUtils;
+
+const FAKE_OPTIONS = {
+ storage: {
+ set() {
+ return Promise.resolve();
+ },
+ get() {
+ return Promise.resolve();
+ },
+ },
+ dispatchToAS: () => {},
+};
+const FAKE_RESPONSE_HEADERS = { get() {} };
+
+describe("MessageLoaderUtils", () => {
+ let fetchStub;
+ let clock;
+ let sandbox;
+
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ clock = sinon.useFakeTimers();
+ fetchStub = sinon.stub(global, "fetch");
+ });
+ afterEach(() => {
+ sandbox.restore();
+ clock.restore();
+ fetchStub.restore();
+ });
+
+ describe("#loadMessagesForProvider", () => {
+ it("should return messages for a local provider with hardcoded messages", async () => {
+ const sourceMessage = { id: "foo" };
+ const provider = {
+ id: "provider123",
+ type: "local",
+ messages: [sourceMessage],
+ };
+
+ const result = await MessageLoaderUtils.loadMessagesForProvider(
+ provider,
+ FAKE_OPTIONS
+ );
+
+ assert.isArray(result.messages);
+ // Does the message have the right properties?
+ const [message] = result.messages;
+ assert.propertyVal(message, "id", "foo");
+ assert.propertyVal(message, "provider", "provider123");
+ });
+ it("should filter out local messages listed in the `exclude` field", async () => {
+ const sourceMessage = { id: "foo" };
+ const provider = {
+ id: "provider123",
+ type: "local",
+ messages: [sourceMessage],
+ exclude: ["foo"],
+ };
+
+ const result = await MessageLoaderUtils.loadMessagesForProvider(
+ provider,
+ FAKE_OPTIONS
+ );
+
+ assert.lengthOf(result.messages, 0);
+ });
+ it("should return messages for remote provider", async () => {
+ const sourceMessage = { id: "foo" };
+ fetchStub.resolves({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve({ messages: [sourceMessage] }),
+ headers: FAKE_RESPONSE_HEADERS,
+ });
+ const provider = {
+ id: "provider123",
+ type: "remote",
+ url: "https://foo.com",
+ };
+
+ const result = await MessageLoaderUtils.loadMessagesForProvider(
+ provider,
+ FAKE_OPTIONS
+ );
+ assert.isArray(result.messages);
+ // Does the message have the right properties?
+ const [message] = result.messages;
+ assert.propertyVal(message, "id", "foo");
+ assert.propertyVal(message, "provider", "provider123");
+ assert.propertyVal(message, "provider_url", "https://foo.com");
+ });
+ describe("remote provider HTTP codes", () => {
+ const testMessage = { id: "foo" };
+ const provider = {
+ id: "provider123",
+ type: "remote",
+ url: "https://foo.com",
+ updateCycleInMs: 300,
+ };
+ const respJson = { messages: [testMessage] };
+
+ function assertReturnsCorrectMessages(actual) {
+ assert.isArray(actual.messages);
+ // Does the message have the right properties?
+ const [message] = actual.messages;
+ assert.propertyVal(message, "id", testMessage.id);
+ assert.propertyVal(message, "provider", provider.id);
+ assert.propertyVal(message, "provider_url", provider.url);
+ }
+
+ it("should return messages for 200 response", async () => {
+ fetchStub.resolves({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve(respJson),
+ headers: FAKE_RESPONSE_HEADERS,
+ });
+ assertReturnsCorrectMessages(
+ await MessageLoaderUtils.loadMessagesForProvider(
+ provider,
+ FAKE_OPTIONS
+ )
+ );
+ });
+
+ it("should return messages for a 302 response with json", async () => {
+ fetchStub.resolves({
+ ok: true,
+ status: 302,
+ json: () => Promise.resolve(respJson),
+ headers: FAKE_RESPONSE_HEADERS,
+ });
+ assertReturnsCorrectMessages(
+ await MessageLoaderUtils.loadMessagesForProvider(
+ provider,
+ FAKE_OPTIONS
+ )
+ );
+ });
+
+ it("should return an empty array for a 204 response", async () => {
+ fetchStub.resolves({
+ ok: true,
+ status: 204,
+ json: () => "",
+ headers: FAKE_RESPONSE_HEADERS,
+ });
+ const result = await MessageLoaderUtils.loadMessagesForProvider(
+ provider,
+ FAKE_OPTIONS
+ );
+ assert.deepEqual(result.messages, []);
+ });
+
+ it("should return an empty array for a 500 response", async () => {
+ fetchStub.resolves({
+ ok: false,
+ status: 500,
+ json: () => "",
+ headers: FAKE_RESPONSE_HEADERS,
+ });
+ const result = await MessageLoaderUtils.loadMessagesForProvider(
+ provider,
+ FAKE_OPTIONS
+ );
+ assert.deepEqual(result.messages, []);
+ });
+
+ it("should return cached messages for a 304 response", async () => {
+ clock.tick(302);
+ const messages = [{ id: "message-1" }, { id: "message-2" }];
+ const fakeStorage = {
+ set() {
+ return Promise.resolve();
+ },
+ get() {
+ return Promise.resolve({
+ [provider.id]: {
+ version: STARTPAGE_VERSION,
+ url: provider.url,
+ messages,
+ etag: "etag0987654321",
+ lastFetched: 1,
+ },
+ });
+ },
+ };
+ fetchStub.resolves({
+ ok: true,
+ status: 304,
+ json: () => "",
+ headers: FAKE_RESPONSE_HEADERS,
+ });
+ const result = await MessageLoaderUtils.loadMessagesForProvider(
+ provider,
+ { ...FAKE_OPTIONS, storage: fakeStorage }
+ );
+ assert.equal(result.messages.length, messages.length);
+ messages.forEach(message => {
+ assert.ok(result.messages.find(m => m.id === message.id));
+ });
+ });
+
+ it("should return an empty array if json doesn't parse properly", async () => {
+ fetchStub.resolves({
+ ok: false,
+ status: 200,
+ json: () => "",
+ headers: FAKE_RESPONSE_HEADERS,
+ });
+ const result = await MessageLoaderUtils.loadMessagesForProvider(
+ provider,
+ FAKE_OPTIONS
+ );
+ assert.deepEqual(result.messages, []);
+ });
+
+ it("should report response parsing errors with MessageLoaderUtils.reportError", async () => {
+ const err = {};
+ sandbox.spy(MessageLoaderUtils, "reportError");
+ fetchStub.resolves({
+ ok: true,
+ status: 200,
+ json: sandbox.stub().rejects(err),
+ headers: FAKE_RESPONSE_HEADERS,
+ });
+ await MessageLoaderUtils.loadMessagesForProvider(
+ provider,
+ FAKE_OPTIONS
+ );
+
+ assert.calledOnce(MessageLoaderUtils.reportError);
+ // Report that json parsing failed
+ assert.calledWith(MessageLoaderUtils.reportError, err);
+ });
+
+ it("should report missing `messages` with MessageLoaderUtils.reportError", async () => {
+ sandbox.spy(MessageLoaderUtils, "reportError");
+ fetchStub.resolves({
+ ok: true,
+ status: 200,
+ json: sandbox.stub().resolves({}),
+ headers: FAKE_RESPONSE_HEADERS,
+ });
+ await MessageLoaderUtils.loadMessagesForProvider(
+ provider,
+ FAKE_OPTIONS
+ );
+
+ assert.calledOnce(MessageLoaderUtils.reportError);
+ // Report no messages returned
+ assert.calledWith(
+ MessageLoaderUtils.reportError,
+ "No messages returned from https://foo.com."
+ );
+ });
+
+ it("should report bad status responses with MessageLoaderUtils.reportError", async () => {
+ sandbox.spy(MessageLoaderUtils, "reportError");
+ fetchStub.resolves({
+ ok: false,
+ status: 500,
+ json: sandbox.stub().resolves({}),
+ headers: FAKE_RESPONSE_HEADERS,
+ });
+ await MessageLoaderUtils.loadMessagesForProvider(
+ provider,
+ FAKE_OPTIONS
+ );
+
+ assert.calledOnce(MessageLoaderUtils.reportError);
+ // Report no messages returned
+ assert.calledWith(
+ MessageLoaderUtils.reportError,
+ "Invalid response status 500 from https://foo.com."
+ );
+ });
+
+ it("should return an empty array if the request rejects", async () => {
+ fetchStub.rejects(new Error("something went wrong"));
+ const result = await MessageLoaderUtils.loadMessagesForProvider(
+ provider,
+ FAKE_OPTIONS
+ );
+ assert.deepEqual(result.messages, []);
+ });
+ });
+ describe("remote provider caching", () => {
+ const provider = {
+ id: "provider123",
+ type: "remote",
+ url: "https://foo.com",
+ updateCycleInMs: 300,
+ };
+
+ it("should return cached results if they aren't expired", async () => {
+ clock.tick(1);
+ const messages = [{ id: "message-1" }, { id: "message-2" }];
+ const fakeStorage = {
+ set() {
+ return Promise.resolve();
+ },
+ get() {
+ return Promise.resolve({
+ [provider.id]: {
+ version: STARTPAGE_VERSION,
+ url: provider.url,
+ messages,
+ etag: "etag0987654321",
+ lastFetched: Date.now(),
+ },
+ });
+ },
+ };
+ const result = await MessageLoaderUtils.loadMessagesForProvider(
+ provider,
+ { ...FAKE_OPTIONS, storage: fakeStorage }
+ );
+ assert.equal(result.messages.length, messages.length);
+ messages.forEach(message => {
+ assert.ok(result.messages.find(m => m.id === message.id));
+ });
+ });
+
+ it("should return fetch results if the cache messages are expired", async () => {
+ clock.tick(302);
+ const testMessage = { id: "foo" };
+ const respJson = { messages: [testMessage] };
+ const fakeStorage = {
+ set() {
+ return Promise.resolve();
+ },
+ get() {
+ return Promise.resolve({
+ [provider.id]: {
+ version: STARTPAGE_VERSION,
+ url: provider.url,
+ messages: [{ id: "message-1" }, { id: "message-2" }],
+ etag: "etag0987654321",
+ lastFetched: 1,
+ },
+ });
+ },
+ };
+ fetchStub.resolves({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve(respJson),
+ headers: FAKE_RESPONSE_HEADERS,
+ });
+ const result = await MessageLoaderUtils.loadMessagesForProvider(
+ provider,
+ { ...FAKE_OPTIONS, storage: fakeStorage }
+ );
+ assert.equal(result.messages.length, 1);
+ assert.equal(result.messages[0].id, testMessage.id);
+ });
+ });
+ it("should return an empty array for a remote provider with a blank URL without attempting a request", async () => {
+ const provider = { id: "provider123", type: "remote", url: "" };
+
+ const result = await MessageLoaderUtils.loadMessagesForProvider(
+ provider,
+ FAKE_OPTIONS
+ );
+
+ assert.notCalled(fetchStub);
+ assert.deepEqual(result.messages, []);
+ });
+ it("should return .lastUpdated with the time at which the messages were fetched", async () => {
+ const sourceMessage = { id: "foo" };
+ const provider = {
+ id: "provider123",
+ type: "remote",
+ url: "foo.com",
+ };
+
+ fetchStub.resolves({
+ ok: true,
+ status: 200,
+ json: () =>
+ new Promise(resolve => {
+ clock.tick(42);
+ resolve({ messages: [sourceMessage] });
+ }),
+ headers: FAKE_RESPONSE_HEADERS,
+ });
+
+ const result = await MessageLoaderUtils.loadMessagesForProvider(
+ provider,
+ FAKE_OPTIONS
+ );
+
+ assert.propertyVal(result, "lastUpdated", 42);
+ });
+ });
+
+ describe("#shouldProviderUpdate", () => {
+ it("should return true if the provider does not had a .lastUpdated property", () => {
+ assert.isTrue(MessageLoaderUtils.shouldProviderUpdate({ id: "foo" }));
+ });
+ it("should return false if the provider does not had a .updateCycleInMs property and has a .lastUpdated", () => {
+ clock.tick(1);
+ assert.isFalse(
+ MessageLoaderUtils.shouldProviderUpdate({ id: "foo", lastUpdated: 0 })
+ );
+ });
+ it("should return true if the time since .lastUpdated is greater than .updateCycleInMs", () => {
+ clock.tick(301);
+ assert.isTrue(
+ MessageLoaderUtils.shouldProviderUpdate({
+ id: "foo",
+ lastUpdated: 0,
+ updateCycleInMs: 300,
+ })
+ );
+ });
+ it("should return false if the time since .lastUpdated is less than .updateCycleInMs", () => {
+ clock.tick(299);
+ assert.isFalse(
+ MessageLoaderUtils.shouldProviderUpdate({
+ id: "foo",
+ lastUpdated: 0,
+ updateCycleInMs: 300,
+ })
+ );
+ });
+ });
+
+ describe("#cleanupCache", () => {
+ it("should remove data for providers no longer active", async () => {
+ const fakeStorage = {
+ get: sinon.stub().returns(
+ Promise.resolve({
+ "id-1": {},
+ "id-2": {},
+ "id-3": {},
+ })
+ ),
+ set: sinon.stub().returns(Promise.resolve()),
+ };
+ const fakeProviders = [
+ { id: "id-1", type: "remote" },
+ { id: "id-3", type: "remote" },
+ ];
+
+ await MessageLoaderUtils.cleanupCache(fakeProviders, fakeStorage);
+
+ assert.calledOnce(fakeStorage.set);
+ assert.calledWith(
+ fakeStorage.set,
+ MessageLoaderUtils.REMOTE_LOADER_CACHE_KEY,
+ { "id-1": {}, "id-3": {} }
+ );
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/asrouter/ModalOverlay.test.jsx b/browser/components/newtab/test/unit/asrouter/ModalOverlay.test.jsx
new file mode 100644
index 0000000000..889d26a9d3
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/ModalOverlay.test.jsx
@@ -0,0 +1,69 @@
+import { ModalOverlayWrapper } from "content-src/asrouter/components/ModalOverlay/ModalOverlay";
+import { mount } from "enzyme";
+import React from "react";
+
+describe("ModalOverlayWrapper", () => {
+ let fakeDoc;
+ let sandbox;
+ let header;
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ header = document.createElement("div");
+
+ fakeDoc = {
+ addEventListener: sandbox.stub(),
+ removeEventListener: sandbox.stub(),
+ body: { classList: { add: sandbox.stub(), remove: sandbox.stub() } },
+ getElementById() {
+ return header;
+ },
+ };
+ });
+ afterEach(() => {
+ sandbox.restore();
+ });
+ it("should add eventListener and a class on mount", async () => {
+ mount(<ModalOverlayWrapper document={fakeDoc} />);
+ assert.calledOnce(fakeDoc.addEventListener);
+ assert.calledWith(fakeDoc.body.classList.add, "modal-open");
+ });
+
+ it("should remove eventListener on unmount", async () => {
+ const wrapper = mount(<ModalOverlayWrapper document={fakeDoc} />);
+ wrapper.unmount();
+ assert.calledOnce(fakeDoc.addEventListener);
+ assert.calledOnce(fakeDoc.removeEventListener);
+ assert.calledWith(fakeDoc.body.classList.remove, "modal-open");
+ });
+
+ it("should call props.onClose on an Escape key", async () => {
+ const onClose = sandbox.stub();
+ mount(<ModalOverlayWrapper document={fakeDoc} onClose={onClose} />);
+
+ // Simulate onkeydown being called
+ const [, callback] = fakeDoc.addEventListener.firstCall.args;
+ callback({ key: "Escape" });
+
+ assert.calledOnce(onClose);
+ });
+
+ it("should not call props.onClose on other keys than Escape", async () => {
+ const onClose = sandbox.stub();
+ mount(<ModalOverlayWrapper document={fakeDoc} onClose={onClose} />);
+
+ // Simulate onkeydown being called
+ const [, callback] = fakeDoc.addEventListener.firstCall.args;
+ callback({ key: "Ctrl" });
+
+ assert.notCalled(onClose);
+ });
+
+ it("should not call props.onClose when clicked outside dialog", async () => {
+ const onClose = sandbox.stub();
+ const wrapper = mount(
+ <ModalOverlayWrapper document={fakeDoc} onClose={onClose} />
+ );
+ wrapper.find("div.modalOverlayOuter.active").simulate("click");
+ assert.notCalled(onClose);
+ });
+});
diff --git a/browser/components/newtab/test/unit/asrouter/PanelTestProvider.test.js b/browser/components/newtab/test/unit/asrouter/PanelTestProvider.test.js
new file mode 100644
index 0000000000..1a15f705ee
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/PanelTestProvider.test.js
@@ -0,0 +1,42 @@
+import { PanelTestProvider } from "lib/PanelTestProvider.jsm";
+import schema from "content-src/asrouter/schemas/panel/cfr-fxa-bookmark.schema.json";
+import update_schema from "content-src/asrouter/templates/OnboardingMessage/UpdateAction.schema.json";
+import whats_new_schema from "content-src/asrouter/templates/OnboardingMessage/WhatsNewMessage.schema.json";
+
+describe("PanelTestProvider", () => {
+ let messages;
+ beforeEach(async () => {
+ messages = await PanelTestProvider.getMessages();
+ });
+ it("should have a message", () => {
+ // Careful: when changing this number make sure that new messages also go
+ // through schema verifications.
+ assert.lengthOf(messages, 13);
+ });
+ it("should be a valid message", () => {
+ const fxaMessages = messages.filter(
+ ({ template }) => template === "fxa_bookmark_panel"
+ );
+ for (let message of fxaMessages) {
+ assert.jsonSchema(message.content, schema);
+ }
+ });
+ it("should be a valid message", () => {
+ const updateMessages = messages.filter(
+ ({ template }) => template === "update_action"
+ );
+ for (let message of updateMessages) {
+ assert.jsonSchema(message.content, update_schema);
+ }
+ });
+ it("should be a valid message", () => {
+ const whatsNewMessages = messages.filter(
+ ({ template }) => template === "whatsnew_panel_message"
+ );
+ for (let message of whatsNewMessages) {
+ assert.jsonSchema(message.content, whats_new_schema);
+ // Not part of `message.content` so it can't be enforced through schema
+ assert.property(message, "order");
+ }
+ });
+});
diff --git a/browser/components/newtab/test/unit/asrouter/RemoteL10n.test.js b/browser/components/newtab/test/unit/asrouter/RemoteL10n.test.js
new file mode 100644
index 0000000000..184362fe2c
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/RemoteL10n.test.js
@@ -0,0 +1,165 @@
+import { RemoteL10n, _RemoteL10n } from "lib/RemoteL10n.jsm";
+import { GlobalOverrider } from "test/unit/utils";
+
+describe("RemoteL10n", () => {
+ let sandbox;
+ let globals;
+ let domL10nStub;
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ globals = new GlobalOverrider();
+ domL10nStub = sandbox.stub();
+ globals.set("DOMLocalization", domL10nStub);
+ });
+ afterEach(() => {
+ sandbox.restore();
+ globals.restore();
+ });
+ describe("#RemoteL10n", () => {
+ it("should create a new instance", () => {
+ assert.ok(new _RemoteL10n());
+ });
+ it("should create a DOMLocalization instance", () => {
+ domL10nStub.returns({ instance: true });
+ const instance = new _RemoteL10n();
+
+ assert.propertyVal(instance._createDOML10n(), "instance", true);
+ assert.calledOnce(domL10nStub);
+ });
+ it("should create a new instance", () => {
+ domL10nStub.returns({ instance: true });
+ const instance = new _RemoteL10n();
+
+ assert.ok(instance.l10n);
+
+ instance.reloadL10n();
+
+ assert.ok(instance.l10n);
+
+ assert.calledTwice(domL10nStub);
+ });
+ it("should reuse the instance", () => {
+ domL10nStub.returns({ instance: true });
+ const instance = new _RemoteL10n();
+
+ assert.ok(instance.l10n);
+ assert.ok(instance.l10n);
+
+ assert.calledOnce(domL10nStub);
+ });
+ });
+ describe("#_createDOML10n", () => {
+ it("should load the remote Fluent file if USE_REMOTE_L10N_PREF is true", async () => {
+ sandbox.stub(global.Services.prefs, "getBoolPref").returns(true);
+ RemoteL10n._createDOML10n();
+
+ assert.calledOnce(domL10nStub);
+ const { args } = domL10nStub.firstCall;
+ // The first arg is the resource array,
+ // the second one is false (use async),
+ // and the third one is the bundle generator.
+ assert.equal(args.length, 3);
+ assert.deepEqual(args[0], [
+ "browser/newtab/asrouter.ftl",
+ "browser/branding/brandings.ftl",
+ "browser/branding/sync-brand.ftl",
+ "branding/brand.ftl",
+ "browser/defaultBrowserNotification.ftl",
+ ]);
+ assert.isFalse(args[1]);
+ assert.isFunction(args[2].generateBundles);
+ });
+ it("should load the local Fluent file if USE_REMOTE_L10N_PREF is false", () => {
+ sandbox.stub(global.Services.prefs, "getBoolPref").returns(false);
+ RemoteL10n._createDOML10n();
+
+ const { args } = domL10nStub.firstCall;
+ // The first arg is the resource array,
+ // the second one is false (use async),
+ // and the third one is null.
+ assert.equal(args.length, 3);
+ assert.deepEqual(args[0], [
+ "browser/newtab/asrouter.ftl",
+ "browser/branding/brandings.ftl",
+ "browser/branding/sync-brand.ftl",
+ "branding/brand.ftl",
+ "browser/defaultBrowserNotification.ftl",
+ ]);
+ assert.isFalse(args[1]);
+ assert.isEmpty(args[2]);
+ });
+ });
+ describe("#createElement", () => {
+ let doc;
+ let instance;
+ let setStringStub;
+ let elem;
+ beforeEach(() => {
+ elem = document.createElement("div");
+ doc = {
+ createElement: sandbox.stub().returns(elem),
+ createElementNS: sandbox.stub().returns(elem),
+ };
+ instance = new _RemoteL10n();
+ setStringStub = sandbox.stub(instance, "setString");
+ });
+ it("should call createElement if string_id is defined", () => {
+ instance.createElement(doc, "span", { content: { string_id: "foo" } });
+
+ assert.calledOnce(doc.createElement);
+ });
+ it("should call createElementNS if string_id is not present", () => {
+ instance.createElement(doc, "span", { content: "foo" });
+
+ assert.calledOnce(doc.createElementNS);
+ });
+ it("should set classList", () => {
+ instance.createElement(doc, "span", { classList: "foo" });
+
+ assert.isTrue(elem.classList.contains("foo"));
+ });
+ it("should call setString", () => {
+ const options = { classList: "foo" };
+ instance.createElement(doc, "span", options);
+
+ assert.calledOnce(setStringStub);
+ assert.calledWithExactly(setStringStub, elem, options);
+ });
+ });
+ describe("#setString", () => {
+ let instance;
+ beforeEach(() => {
+ instance = new _RemoteL10n();
+ });
+ it("should set fluent variables and id", () => {
+ let el = { setAttribute: sandbox.stub() };
+ instance.setString(el, {
+ content: { string_id: "foo" },
+ attributes: { bar: "bar", baz: "baz" },
+ });
+
+ assert.calledThrice(el.setAttribute);
+ assert.calledWithExactly(el.setAttribute, "fluent-variable-bar", "bar");
+ assert.calledWithExactly(el.setAttribute, "fluent-variable-baz", "baz");
+ assert.calledWithExactly(el.setAttribute, "fluent-remote-id", "foo");
+ });
+ it("should set content if no string_id", () => {
+ let el = { setAttribute: sandbox.stub() };
+ instance.setString(el, { content: "foo" });
+
+ assert.notCalled(el.setAttribute);
+ assert.equal(el.textContent, "foo");
+ });
+ });
+ describe("#isLocaleSupported", () => {
+ it("should return true if the locale is en-US", () => {
+ assert.ok(RemoteL10n.isLocaleSupported("en-US"));
+ });
+ it("should return true if the locale is in all-locales", () => {
+ assert.ok(RemoteL10n.isLocaleSupported("en-CA"));
+ });
+ it("should return false if the locale is not in all-locales", () => {
+ assert.ok(!RemoteL10n.isLocaleSupported("und"));
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/asrouter/RichText.test.jsx b/browser/components/newtab/test/unit/asrouter/RichText.test.jsx
new file mode 100644
index 0000000000..c3b885bfe4
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/RichText.test.jsx
@@ -0,0 +1,81 @@
+import {
+ convertLinks,
+ RichText,
+} from "content-src/asrouter/components/RichText/RichText";
+import { Localized } from "fluent-react";
+import { mount } from "enzyme";
+import React from "react";
+
+describe("convertLinks", () => {
+ let sandbox;
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ });
+ afterEach(() => {
+ sandbox.restore();
+ });
+ it("should return an object with anchor elements", () => {
+ const cta = {
+ url: "https://foo.com",
+ metric: "foo",
+ };
+ const stub = sandbox.stub();
+ const result = convertLinks({ cta }, stub);
+
+ assert.property(result, "cta");
+ assert.propertyVal(result.cta, "type", "a");
+ assert.propertyVal(result.cta.props, "href", cta.url);
+ assert.propertyVal(result.cta.props, "data-metric", cta.metric);
+ assert.propertyVal(result.cta.props, "onClick", stub);
+ });
+ it("should return an anchor element without href", () => {
+ const cta = {
+ url: "https://foo.com",
+ metric: "foo",
+ action: "OPEN_MENU",
+ args: "appMenu",
+ entrypoint_name: "entrypoint_name",
+ entrypoint_value: "entrypoint_value",
+ };
+ const stub = sandbox.stub();
+ const result = convertLinks({ cta }, stub);
+
+ assert.property(result, "cta");
+ assert.propertyVal(result.cta, "type", "a");
+ assert.propertyVal(result.cta.props, "href", false);
+ assert.propertyVal(result.cta.props, "data-metric", cta.metric);
+ assert.propertyVal(result.cta.props, "data-action", cta.action);
+ assert.propertyVal(result.cta.props, "data-args", cta.args);
+ assert.propertyVal(
+ result.cta.props,
+ "data-entrypoint_name",
+ cta.entrypoint_name
+ );
+ assert.propertyVal(
+ result.cta.props,
+ "data-entrypoint_value",
+ cta.entrypoint_value
+ );
+ assert.propertyVal(result.cta.props, "onClick", stub);
+ });
+ it("should follow openNewWindow prop", () => {
+ const cta = { url: "https://foo.com" };
+ const newWindow = convertLinks({ cta }, sandbox.stub(), false, true);
+ const sameWindow = convertLinks({ cta }, sandbox.stub(), false);
+
+ assert.propertyVal(newWindow.cta.props, "target", "_blank");
+ assert.propertyVal(sameWindow.cta.props, "target", "");
+ });
+ it("should allow for custom elements & styles", () => {
+ const wrapper = mount(
+ <RichText
+ customElements={{ em: <em style={{ color: "#f05" }} /> }}
+ text="<em>foo</em>"
+ localization_id="text"
+ />
+ );
+
+ const localized = wrapper.find(Localized);
+ assert.propertyVal(localized.props().em.props.style, "color", "#f05");
+ });
+});
diff --git a/browser/components/newtab/test/unit/asrouter/SnippetsTestMessageProvider.test.js b/browser/components/newtab/test/unit/asrouter/SnippetsTestMessageProvider.test.js
new file mode 100644
index 0000000000..0b9263ddec
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/SnippetsTestMessageProvider.test.js
@@ -0,0 +1,43 @@
+import EOYSnippetSchema from "../../../content-src/asrouter/templates/EOYSnippet/EOYSnippet.schema.json";
+import SimpleBelowSearchSnippetSchema from "../../../content-src/asrouter/templates/SimpleBelowSearchSnippet/SimpleBelowSearchSnippet.schema.json";
+import SimpleSnippetSchema from "../../../content-src/asrouter/templates/SimpleSnippet/SimpleSnippet.schema.json";
+import { SnippetsTestMessageProvider } from "../../../lib/SnippetsTestMessageProvider.jsm";
+import SubmitFormSnippetSchema from "../../../content-src/asrouter/templates/SubmitFormSnippet/SubmitFormSnippet.schema.json";
+import SubmitFormScene2SnippetSchema from "../../../content-src/asrouter/templates/SubmitFormSnippet/SubmitFormScene2Snippet.schema.json";
+
+const schemas = {
+ simple_snippet: SimpleSnippetSchema,
+ newsletter_snippet: SubmitFormSnippetSchema,
+ fxa_signup_snippet: SubmitFormSnippetSchema,
+ send_to_device_snippet: SubmitFormSnippetSchema,
+ send_to_device_scene2_snippet: SubmitFormScene2SnippetSchema,
+ eoy_snippet: EOYSnippetSchema,
+ simple_below_search_snippet: SimpleBelowSearchSnippetSchema,
+};
+
+describe("SnippetsTestMessageProvider", async () => {
+ let messages = await SnippetsTestMessageProvider.getMessages();
+
+ it("should return an array of messages", () => {
+ assert.isArray(messages);
+ });
+
+ it("should have a valid example of each schema", () => {
+ Object.keys(schemas).forEach(templateName => {
+ const example = messages.find(
+ message => message.template === templateName
+ );
+ assert.ok(example, `has a ${templateName} example`);
+ });
+ });
+
+ it("should have examples that are valid", () => {
+ messages.forEach(example => {
+ assert.jsonSchema(
+ example.content,
+ schemas[example.template],
+ `${example.id} should be valid`
+ );
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/asrouter/TargetingDocs.test.js b/browser/components/newtab/test/unit/asrouter/TargetingDocs.test.js
new file mode 100644
index 0000000000..6177489b75
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/TargetingDocs.test.js
@@ -0,0 +1,92 @@
+import { ASRouterTargeting } from "lib/ASRouterTargeting.jsm";
+import docs from "content-src/asrouter/docs/targeting-attributes.md";
+
+// The following targeting parameters are either deprecated or should not be included in the docs for some reason.
+const SKIP_DOCS = [];
+// These are extra message context attributes via ASRouter.jsm
+const MESSAGE_CONTEXT_ATTRIBUTES = ["previousSessionEnd"];
+
+function getHeadingsFromDocs() {
+ const re = /### `(\w+)`/g;
+ const found = [];
+ let match = 1;
+ while (match) {
+ match = re.exec(docs);
+ if (match) {
+ found.push(match[1]);
+ }
+ }
+ return found;
+}
+
+function getTOCFromDocs() {
+ const re = /## Available attributes\n+([^]+)\n+## Detailed usage/;
+ const sectionMatch = docs.match(re);
+ if (!sectionMatch) {
+ return [];
+ }
+ const [, listText] = sectionMatch;
+ const re2 = /\[(\w+)\]/g;
+ const found = [];
+ let match = 1;
+ while (match) {
+ match = re2.exec(listText);
+ if (match) {
+ found.push(match[1]);
+ }
+ }
+ return found;
+}
+
+describe("ASRTargeting docs", () => {
+ const DOCS_TARGETING_HEADINGS = getHeadingsFromDocs();
+ const DOCS_TOC = getTOCFromDocs();
+ const ASRTargetingAttributes = [
+ ...Object.keys(ASRouterTargeting.Environment).filter(
+ attribute => !SKIP_DOCS.includes(attribute)
+ ),
+ ...MESSAGE_CONTEXT_ATTRIBUTES,
+ ];
+
+ describe("All targeting params documented in targeting-attributes.md", () => {
+ for (const targetingParam of ASRTargetingAttributes) {
+ // If this test is failing, you probably forgot to add docs to content-src/asrouter/targeting-attributes.md
+ // for a new targeting attribute, or you forgot to put it in the table of contents up top.
+ it(`should have docs and table of contents entry for ${targetingParam}`, () => {
+ assert.include(
+ DOCS_TARGETING_HEADINGS,
+ targetingParam,
+ `Didn't find the heading: ### \`${targetingParam}\``
+ );
+ assert.include(
+ DOCS_TOC,
+ targetingParam,
+ `Didn't find a table of contents entry for ${targetingParam}`
+ );
+ });
+ }
+ });
+ describe("No extra attributes in targeting-attributes.md", () => {
+ // "allow" includes targeting attributes that are not implemented by
+ // ASRTargetingAttributes. For example trigger context passed to the evaluation
+ // context in when a trigger runs or ASRouter state used in the evaluation.
+ const allow = [
+ "personalizedCfrThreshold",
+ "personalizedCfrScores",
+ "messageImpressions",
+ ];
+ for (const targetingParam of DOCS_TARGETING_HEADINGS.filter(
+ doc => !allow.includes(doc)
+ )) {
+ // If this test is failing, you might have spelled something wrong or removed a targeting param without
+ // removing its docs.
+ it(`should have an implementation for ${targetingParam} in ASRouterTargeting.Environment`, () => {
+ assert.include(
+ ASRTargetingAttributes,
+ targetingParam,
+ `Didn't find an implementation for ${targetingParam}`
+ );
+ });
+ }
+ });
+});
diff --git a/browser/components/newtab/test/unit/asrouter/asrouter-content.test.jsx b/browser/components/newtab/test/unit/asrouter/asrouter-content.test.jsx
new file mode 100644
index 0000000000..b581886111
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/asrouter-content.test.jsx
@@ -0,0 +1,516 @@
+import { ASRouterUISurface } from "content-src/asrouter/asrouter-content";
+import { ASRouterUtils } from "content-src/asrouter/asrouter-utils";
+import { GlobalOverrider } from "test/unit/utils";
+import { FAKE_LOCAL_MESSAGES } from "./constants";
+import React from "react";
+import { mount } from "enzyme";
+
+let [FAKE_MESSAGE] = FAKE_LOCAL_MESSAGES;
+const FAKE_NEWSLETTER_SNIPPET = FAKE_LOCAL_MESSAGES.find(
+ msg => msg.id === "newsletter"
+);
+const FAKE_FXA_SNIPPET = FAKE_LOCAL_MESSAGES.find(msg => msg.id === "fxa");
+const FAKE_BELOW_SEARCH_SNIPPET = FAKE_LOCAL_MESSAGES.find(
+ msg => msg.id === "belowsearch"
+);
+
+FAKE_MESSAGE = Object.assign({}, FAKE_MESSAGE, { provider: "fakeprovider" });
+
+describe("ASRouterUtils", () => {
+ let globalOverrider;
+ let sandbox;
+ let globals;
+ beforeEach(() => {
+ globalOverrider = new GlobalOverrider();
+ sandbox = sinon.createSandbox();
+ globals = {
+ ASRouterMessage: sandbox.stub(),
+ };
+ globalOverrider.set(globals);
+ });
+ afterEach(() => {
+ sandbox.restore();
+ globalOverrider.restore();
+ });
+ it("should send a message with the right payload data", () => {
+ ASRouterUtils.sendTelemetry({ id: 1, event: "CLICK" });
+
+ assert.calledOnce(globals.ASRouterMessage);
+ assert.calledWith(globals.ASRouterMessage, {
+ type: "AS_ROUTER_TELEMETRY_USER_EVENT",
+ meta: { from: "ActivityStream:Content", to: "ActivityStream:Main" },
+ data: {
+ id: 1,
+ event: "CLICK",
+ },
+ });
+ });
+});
+
+describe("ASRouterUISurface", () => {
+ let wrapper;
+ let globalOverrider;
+ let sandbox;
+ let headerPortal;
+ let footerPortal;
+ let root;
+ let fakeDocument;
+ let globals;
+
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ headerPortal = document.createElement("div");
+ footerPortal = document.createElement("div");
+ root = document.createElement("div");
+ sandbox.stub(footerPortal, "querySelector").returns(footerPortal);
+ fakeDocument = {
+ location: { href: "" },
+ _listeners: new Set(),
+ _visibilityState: "hidden",
+ head: {
+ appendChild(el) {
+ return el;
+ },
+ },
+ get visibilityState() {
+ return this._visibilityState;
+ },
+ set visibilityState(value) {
+ if (this._visibilityState === value) {
+ return;
+ }
+ this._visibilityState = value;
+ this._listeners.forEach(l => l());
+ },
+ addEventListener(event, listener) {
+ this._listeners.add(listener);
+ },
+ removeEventListener(event, listener) {
+ this._listeners.delete(listener);
+ },
+ get body() {
+ return document.createElement("body");
+ },
+ getElementById(id) {
+ switch (id) {
+ case "header-asrouter-container":
+ return headerPortal;
+ case "root":
+ return root;
+ default:
+ return footerPortal;
+ }
+ },
+ createElement(tag) {
+ return document.createElement(tag);
+ },
+ };
+ globals = {
+ ASRouterMessage: sandbox.stub().resolves(),
+ ASRouterAddParentListener: sandbox.stub(),
+ ASRouterRemoveParentListener: sandbox.stub(),
+ fetch: sandbox.stub().resolves({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve({}),
+ }),
+ };
+ globalOverrider = new GlobalOverrider();
+ globalOverrider.set(globals);
+ sandbox.stub(ASRouterUtils, "sendTelemetry");
+
+ wrapper = mount(<ASRouterUISurface document={fakeDocument} />);
+ });
+
+ afterEach(() => {
+ sandbox.restore();
+ globalOverrider.restore();
+ });
+
+ it("should render the component if a message id is defined", () => {
+ wrapper.setState({ message: FAKE_MESSAGE });
+ assert.isTrue(wrapper.exists());
+ });
+
+ it("should pass in the correct form_method for newsletter snippets", () => {
+ wrapper.setState({ message: FAKE_NEWSLETTER_SNIPPET });
+
+ assert.isTrue(wrapper.find("SubmitFormSnippet").exists());
+ assert.propertyVal(
+ wrapper.find("SubmitFormSnippet").props(),
+ "form_method",
+ "POST"
+ );
+ });
+
+ it("should pass in the correct form_method for fxa snippets", () => {
+ wrapper.setState({ message: FAKE_FXA_SNIPPET });
+
+ assert.isTrue(wrapper.find("SubmitFormSnippet").exists());
+ assert.propertyVal(
+ wrapper.find("SubmitFormSnippet").props(),
+ "form_method",
+ "GET"
+ );
+ });
+
+ it("should render a preview banner if message provider is preview", () => {
+ wrapper.setState({ message: { ...FAKE_MESSAGE, provider: "preview" } });
+ assert.isTrue(wrapper.find(".snippets-preview-banner").exists());
+ });
+
+ it("should not render a preview banner if message provider is not preview", () => {
+ wrapper.setState({ message: FAKE_MESSAGE });
+ assert.isFalse(wrapper.find(".snippets-preview-banner").exists());
+ });
+
+ it("should render a SimpleSnippet in the footer portal", () => {
+ wrapper.setState({ message: FAKE_MESSAGE });
+ assert.isTrue(footerPortal.childElementCount > 0);
+ assert.equal(headerPortal.childElementCount, 0);
+ });
+
+ it("should not render a SimpleBelowSearchSnippet in a portal", () => {
+ wrapper.setState({ message: FAKE_BELOW_SEARCH_SNIPPET });
+ assert.equal(headerPortal.childElementCount, 0);
+ assert.equal(footerPortal.childElementCount, 0);
+ });
+
+ it("should dispatch an event to select the correct theme", () => {
+ const stub = sandbox.stub(window, "dispatchEvent");
+ sandbox
+ .stub(ASRouterUtils, "getPreviewEndpoint")
+ .returns({ theme: "dark" });
+
+ wrapper = mount(<ASRouterUISurface document={fakeDocument} />);
+
+ assert.calledOnce(stub);
+ assert.property(stub.firstCall.args[0].detail.data, "ntp_background");
+ assert.property(stub.firstCall.args[0].detail.data, "ntp_text");
+ assert.property(stub.firstCall.args[0].detail.data, "sidebar");
+ assert.property(stub.firstCall.args[0].detail.data, "sidebar_text");
+ });
+
+ it("should set `dir=rtl` on the page's <html> element if the dir param is set", () => {
+ assert.notPropertyVal(fakeDocument, "dir", "rtl");
+ sandbox.stub(ASRouterUtils, "getPreviewEndpoint").returns({ dir: "rtl" });
+
+ wrapper = mount(<ASRouterUISurface document={fakeDocument} />);
+ assert.propertyVal(fakeDocument, "dir", "rtl");
+ });
+
+ describe("snippets", () => {
+ it("should send correct event and source when snippet is blocked", () => {
+ wrapper.setState({ message: FAKE_MESSAGE });
+
+ wrapper.find(".blockButton").simulate("click");
+ assert.propertyVal(
+ ASRouterUtils.sendTelemetry.firstCall.args[0],
+ "event",
+ "BLOCK"
+ );
+ assert.propertyVal(
+ ASRouterUtils.sendTelemetry.firstCall.args[0],
+ "source",
+ "NEWTAB_FOOTER_BAR"
+ );
+ });
+
+ it("should not send telemetry when a preview snippet is blocked", () => {
+ wrapper.setState({ message: { ...FAKE_MESSAGE, provider: "preview" } });
+
+ wrapper.find(".blockButton").simulate("click");
+ assert.notCalled(ASRouterUtils.sendTelemetry);
+ });
+ });
+
+ describe("impressions", () => {
+ function simulateVisibilityChange(value) {
+ fakeDocument.visibilityState = value;
+ }
+
+ it("should call blockById after CTA link is clicked", () => {
+ wrapper.setState({ message: FAKE_MESSAGE });
+ sandbox.stub(ASRouterUtils, "blockById").resolves();
+ wrapper.instance().sendClick({ target: { dataset: { metric: "" } } });
+
+ assert.calledOnce(ASRouterUtils.blockById);
+ assert.calledWith(ASRouterUtils.blockById, FAKE_MESSAGE.id);
+ });
+
+ it("should executeAction if defined on the anchor", () => {
+ wrapper.setState({ message: FAKE_MESSAGE });
+ sandbox.spy(ASRouterUtils, "executeAction");
+ wrapper.instance().sendClick({
+ target: { dataset: { action: "OPEN_MENU", args: "appMenu" } },
+ });
+
+ assert.calledOnce(ASRouterUtils.executeAction);
+ assert.calledWithExactly(ASRouterUtils.executeAction, {
+ type: "OPEN_MENU",
+ data: { args: "appMenu" },
+ });
+ });
+
+ it("should not call blockById if do_not_autoblock is true", () => {
+ wrapper.setState({
+ message: {
+ ...FAKE_MESSAGE,
+ ...{ content: { ...FAKE_MESSAGE.content, do_not_autoblock: true } },
+ },
+ });
+ sandbox.stub(ASRouterUtils, "blockById");
+ wrapper.instance().sendClick({ target: { dataset: { metric: "" } } });
+
+ assert.notCalled(ASRouterUtils.blockById);
+ });
+
+ it("should not send an impression if no message exists", () => {
+ simulateVisibilityChange("visible");
+
+ assert.notCalled(ASRouterUtils.sendTelemetry);
+ });
+
+ it("should not send an impression if the page is not visible", () => {
+ simulateVisibilityChange("hidden");
+ wrapper.setState({ message: FAKE_MESSAGE });
+
+ assert.notCalled(ASRouterUtils.sendTelemetry);
+ });
+
+ it("should not send an impression for a preview message", () => {
+ wrapper.setState({ message: { ...FAKE_MESSAGE, provider: "preview" } });
+ assert.notCalled(ASRouterUtils.sendTelemetry);
+
+ simulateVisibilityChange("visible");
+ assert.notCalled(ASRouterUtils.sendTelemetry);
+ });
+
+ it("should send an impression ping when there is a message and the page becomes visible", () => {
+ wrapper.setState({ message: FAKE_MESSAGE });
+ assert.notCalled(ASRouterUtils.sendTelemetry);
+
+ simulateVisibilityChange("visible");
+ assert.calledOnce(ASRouterUtils.sendTelemetry);
+ });
+
+ it("should send the correct impression source", () => {
+ wrapper.setState({ message: FAKE_MESSAGE });
+ simulateVisibilityChange("visible");
+
+ assert.calledOnce(ASRouterUtils.sendTelemetry);
+ assert.propertyVal(
+ ASRouterUtils.sendTelemetry.firstCall.args[0],
+ "event",
+ "IMPRESSION"
+ );
+ assert.propertyVal(
+ ASRouterUtils.sendTelemetry.firstCall.args[0],
+ "source",
+ "NEWTAB_FOOTER_BAR"
+ );
+ });
+
+ it("should send an impression ping when the page is visible and a message gets loaded", () => {
+ simulateVisibilityChange("visible");
+ wrapper.setState({ message: {} });
+ assert.notCalled(ASRouterUtils.sendTelemetry);
+
+ wrapper.setState({ message: FAKE_MESSAGE });
+ assert.calledOnce(ASRouterUtils.sendTelemetry);
+ });
+
+ it("should send another impression ping if the message id changes", () => {
+ simulateVisibilityChange("visible");
+ wrapper.setState({ message: FAKE_MESSAGE });
+ assert.calledOnce(ASRouterUtils.sendTelemetry);
+
+ wrapper.setState({ message: FAKE_LOCAL_MESSAGES[1] });
+ assert.calledTwice(ASRouterUtils.sendTelemetry);
+ });
+
+ it("should not send another impression ping if the message id has not changed", () => {
+ simulateVisibilityChange("visible");
+ wrapper.setState({ message: FAKE_MESSAGE });
+ assert.calledOnce(ASRouterUtils.sendTelemetry);
+
+ wrapper.setState({ somethingElse: 123 });
+ assert.calledOnce(ASRouterUtils.sendTelemetry);
+ });
+
+ it("should not send another impression ping if the message is cleared", () => {
+ simulateVisibilityChange("visible");
+ wrapper.setState({ message: FAKE_MESSAGE });
+ assert.calledOnce(ASRouterUtils.sendTelemetry);
+
+ wrapper.setState({ message: {} });
+ assert.calledOnce(ASRouterUtils.sendTelemetry);
+ });
+
+ it("should call .sendTelemetry with the right message data", () => {
+ simulateVisibilityChange("visible");
+ wrapper.setState({ message: FAKE_MESSAGE });
+
+ assert.calledOnce(ASRouterUtils.sendTelemetry);
+ const [payload] = ASRouterUtils.sendTelemetry.firstCall.args;
+
+ assert.propertyVal(payload, "message_id", FAKE_MESSAGE.id);
+ assert.propertyVal(payload, "event", "IMPRESSION");
+ assert.propertyVal(
+ payload,
+ "action",
+ `${FAKE_MESSAGE.provider}_user_event`
+ );
+ assert.propertyVal(payload, "source", "NEWTAB_FOOTER_BAR");
+ });
+
+ it("should construct a OPEN_ABOUT_PAGE action with attribution", () => {
+ wrapper.setState({ message: FAKE_MESSAGE });
+ const stub = sandbox.stub(ASRouterUtils, "executeAction");
+
+ wrapper.instance().sendClick({
+ target: {
+ dataset: {
+ metric: "",
+ entrypoint_value: "snippet",
+ action: "OPEN_PREFERENCES_PAGE",
+ args: "home",
+ },
+ },
+ });
+
+ assert.calledOnce(stub);
+ assert.calledWithExactly(stub, {
+ type: "OPEN_PREFERENCES_PAGE",
+ data: { args: "home", entrypoint: "snippet" },
+ });
+ });
+
+ it("should construct a OPEN_ABOUT_PAGE action with attribution", () => {
+ wrapper.setState({ message: FAKE_MESSAGE });
+ const stub = sandbox.stub(ASRouterUtils, "executeAction");
+
+ wrapper.instance().sendClick({
+ target: {
+ dataset: {
+ metric: "",
+ entrypoint_name: "entryPoint",
+ entrypoint_value: "snippet",
+ action: "OPEN_ABOUT_PAGE",
+ args: "logins",
+ },
+ },
+ });
+
+ assert.calledOnce(stub);
+ assert.calledWithExactly(stub, {
+ type: "OPEN_ABOUT_PAGE",
+ data: { args: "logins", entrypoint: "entryPoint=snippet" },
+ });
+ });
+ });
+
+ describe(".fetchFlowParams", () => {
+ let dispatchStub;
+ const assertCalledWithURL = url =>
+ assert.calledWith(globals.fetch, new URL(url).toString(), {
+ credentials: "omit",
+ });
+ beforeEach(() => {
+ dispatchStub = sandbox.stub();
+ wrapper = mount(
+ <ASRouterUISurface
+ dispatch={dispatchStub}
+ fxaEndpoint="https://accounts.firefox.com"
+ />
+ );
+ });
+ it("should use the base url returned from the endpoint pref", async () => {
+ wrapper = mount(
+ <ASRouterUISurface
+ dispatch={dispatchStub}
+ fxaEndpoint="https://foo.com"
+ />
+ );
+ await wrapper.instance().fetchFlowParams();
+
+ assertCalledWithURL("https://foo.com/metrics-flow");
+ });
+ it("should add given search params to the URL", async () => {
+ const params = { foo: "1", bar: "2" };
+
+ await wrapper.instance().fetchFlowParams(params);
+
+ assertCalledWithURL(
+ "https://accounts.firefox.com/metrics-flow?foo=1&bar=2"
+ );
+ });
+ it("should return flowId, flowBeginTime, deviceId on a 200 response", async () => {
+ const flowInfo = { flowId: "foo", flowBeginTime: 123, deviceId: "bar" };
+ globals.fetch
+ .withArgs("https://accounts.firefox.com/metrics-flow")
+ .resolves({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve(flowInfo),
+ });
+
+ const result = await wrapper.instance().fetchFlowParams();
+ assert.deepEqual(result, flowInfo);
+ });
+
+ describe(".onUserAction", () => {
+ it("if the action.type is ENABLE_FIREFOX_MONITOR, it should generate the right monitor URL given some flowParams", async () => {
+ const flowInfo = { flowId: "foo", flowBeginTime: 123, deviceId: "bar" };
+ globals.fetch
+ .withArgs(
+ "https://accounts.firefox.com/metrics-flow?utm_term=avocado"
+ )
+ .resolves({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve(flowInfo),
+ });
+
+ sandbox.spy(ASRouterUtils, "executeAction");
+
+ const msg = {
+ type: "ENABLE_FIREFOX_MONITOR",
+ data: {
+ args: {
+ url: "https://monitor.firefox.com?foo=bar",
+ flowRequestParams: {
+ utm_term: "avocado",
+ },
+ },
+ },
+ };
+
+ await wrapper.instance().onUserAction(msg);
+
+ assertCalledWithURL(
+ "https://accounts.firefox.com/metrics-flow?utm_term=avocado"
+ );
+ assert.calledWith(ASRouterUtils.executeAction, {
+ type: "OPEN_URL",
+ data: {
+ args: new URL(
+ "https://monitor.firefox.com?foo=bar&deviceId=bar&flowId=foo&flowBeginTime=123"
+ ).toString(),
+ },
+ });
+ });
+ it("if the action.type is not ENABLE_FIREFOX_MONITOR, it should just call ASRouterUtils.executeAction", async () => {
+ const msg = {
+ type: "FOO",
+ data: {
+ args: "bar",
+ },
+ };
+ sandbox.spy(ASRouterUtils, "executeAction");
+ await wrapper.instance().onUserAction(msg);
+ assert.calledWith(ASRouterUtils.executeAction, msg);
+ });
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/asrouter/asrouter-utils.test.js b/browser/components/newtab/test/unit/asrouter/asrouter-utils.test.js
new file mode 100644
index 0000000000..1027b8ddab
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/asrouter-utils.test.js
@@ -0,0 +1,100 @@
+import { ASRouterUtils } from "content-src/asrouter/asrouter-utils";
+import { GlobalOverrider } from "test/unit/utils";
+
+describe("ASRouterUtils", () => {
+ let globals = null;
+ let overrider = null;
+ let sandbox = null;
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ globals = {
+ ASRouterMessage: sandbox.stub().resolves({}),
+ };
+ overrider = new GlobalOverrider();
+ overrider.set(globals);
+ });
+ afterEach(() => {
+ sandbox.restore();
+ overrider.restore();
+ });
+ describe("sendMessage", () => {
+ it("default", () => {
+ ASRouterUtils.sendMessage({ foo: "bar" });
+ assert.calledOnce(globals.ASRouterMessage);
+ assert.calledWith(globals.ASRouterMessage, { foo: "bar" });
+ });
+ it("throws if ASRouterMessage is not defined", () => {
+ overrider.set("ASRouterMessage", undefined);
+ assert.throws(() => ASRouterUtils.sendMessage({ foo: "bar" }));
+ });
+ });
+ describe("blockById", () => {
+ it("default", () => {
+ ASRouterUtils.blockById(1, { foo: "bar" });
+ assert.calledWith(
+ globals.ASRouterMessage,
+ sinon.match({ data: { foo: "bar", id: 1 } })
+ );
+ });
+ });
+ describe("modifyMessageJson", () => {
+ it("default", () => {
+ ASRouterUtils.modifyMessageJson({ foo: "bar" });
+ assert.calledWith(
+ globals.ASRouterMessage,
+ sinon.match({ data: { content: { foo: "bar" } } })
+ );
+ });
+ });
+ describe("executeAction", () => {
+ it("default", () => {
+ ASRouterUtils.executeAction({ foo: "bar" });
+ assert.calledWith(
+ globals.ASRouterMessage,
+ sinon.match({ data: { foo: "bar" } })
+ );
+ });
+ });
+ describe("unblockById", () => {
+ it("default", () => {
+ ASRouterUtils.unblockById(2);
+ assert.calledWith(
+ globals.ASRouterMessage,
+ sinon.match({ data: { id: 2 } })
+ );
+ });
+ });
+ describe("blockBundle", () => {
+ it("default", () => {
+ ASRouterUtils.blockBundle(2);
+ assert.calledWith(
+ globals.ASRouterMessage,
+ sinon.match({ data: { bundle: 2 } })
+ );
+ });
+ });
+ describe("unblockBundle", () => {
+ it("default", () => {
+ ASRouterUtils.unblockBundle(2);
+ assert.calledWith(
+ globals.ASRouterMessage,
+ sinon.match({ data: { bundle: 2 } })
+ );
+ });
+ });
+ describe("overrideMessage", () => {
+ it("default", () => {
+ ASRouterUtils.overrideMessage(12);
+ assert.calledWith(
+ globals.ASRouterMessage,
+ sinon.match({ data: { id: 12 } })
+ );
+ });
+ });
+ describe("sendTelemetry", () => {
+ it("default", () => {
+ ASRouterUtils.sendTelemetry({ foo: "bar" });
+ assert.calledOnce(globals.ASRouterMessage);
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/asrouter/compatibility-reference/fx57-compat.test.js b/browser/components/newtab/test/unit/asrouter/compatibility-reference/fx57-compat.test.js
new file mode 100644
index 0000000000..335318d9c6
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/compatibility-reference/fx57-compat.test.js
@@ -0,0 +1,26 @@
+import EOYSnippetSchema from "content-src/asrouter/templates/EOYSnippet/EOYSnippet.schema.json";
+import { expectedValues } from "./snippets-fx57";
+import SimpleSnippetSchema from "content-src/asrouter/templates/SimpleSnippet/SimpleSnippet.schema.json";
+import SubmitFormSchema from "content-src/asrouter/templates/SubmitFormSnippet/SubmitFormSnippet.schema.json";
+
+export const SnippetsSchemas = {
+ eoy_snippet: EOYSnippetSchema,
+ simple_snippet: SimpleSnippetSchema,
+ newsletter_snippet: SubmitFormSchema,
+ fxa_signup_snippet: SubmitFormSchema,
+ send_to_device_snippet: SubmitFormSchema,
+};
+
+describe("Firefox 57 compatibility test", () => {
+ Object.keys(expectedValues).forEach(template => {
+ describe(template, () => {
+ const schema = SnippetsSchemas[template];
+ it(`should have a schema for ${template}`, () => {
+ assert.ok(schema);
+ });
+ it(`should validate with the schema for ${template}`, () => {
+ assert.jsonSchema(expectedValues[template], schema);
+ });
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/asrouter/compatibility-reference/snippets-fx57.js b/browser/components/newtab/test/unit/asrouter/compatibility-reference/snippets-fx57.js
new file mode 100644
index 0000000000..0f0d6a7c3a
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/compatibility-reference/snippets-fx57.js
@@ -0,0 +1,126 @@
+/**
+ * IMPORTANT NOTE!!!
+ *
+ * Please DO NOT introduce breaking changes file without contacting snippets endpoint engineers
+ * and changing the schema version to reflect a breaking change.
+ *
+ */
+
+const DATA_URI_IMAGE =
+ "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
+
+export const expectedValues = {
+ // Simple Snippet (https://github.com/mozmeao/snippets/blob/master/activity-stream/simple-snippet.html)
+ simple_snippet: {
+ icon: DATA_URI_IMAGE,
+ button_label: "Click me",
+ button_url: "https://mozilla.org",
+ button_background_color: "#FF0000",
+ button_color: "#FFFFFF",
+ text: "Hello world",
+ title: "Hi!",
+ title_icon: DATA_URI_IMAGE,
+ tall: true,
+ },
+
+ // FXA Snippet (https://github.com/mozmeao/snippets/blob/master/activity-stream/fxa.html)
+ fxa_signup_snippet: {
+ scene1_icon: DATA_URI_IMAGE,
+ scene1_button_label: "Click me",
+ scene1_button_background_color: "#FF0000",
+ scene1_button_color: "#FFFFFF",
+ scene1_text: "Hello <em>world</em>",
+ scene1_title: "Hi!",
+ scene1_title_icon: DATA_URI_IMAGE,
+
+ scene2_text: "Second scene",
+ scene2_title: "Second scene title",
+ scene2_email_placeholder_text: "Email here",
+ scene2_button_label: "Sign Me Up",
+ scene2_dismiss_button_text: "Dismiss",
+
+ utm_campaign: "snippets123",
+ utm_term: "123term",
+ },
+
+ // Send To Device Snippet (https://github.com/mozmeao/snippets/blob/master/activity-stream/send-to-device.html)
+ send_to_device_snippet: {
+ include_sms: true,
+ locale: "de",
+ country: "DE",
+ message_id_sms: "foo",
+ message_id_email: "foo",
+ scene1_button_background_color: "#FF0000",
+ scene1_button_color: "#FFFFFF",
+ scene1_button_label: "Click me",
+ scene1_icon: DATA_URI_IMAGE,
+ scene1_text: "Hello world",
+ scene1_title: "Hi!",
+ scene1_title_icon: DATA_URI_IMAGE,
+
+ scene2_button_label: "Sign Me Up",
+ scene2_disclaimer_html: "Hello <em>world</em>",
+ scene2_dismiss_button_text: "Dismiss",
+ scene2_icon: DATA_URI_IMAGE,
+ scene2_input_placeholder: "Email here",
+
+ scene2_text: "Second scene",
+ scene2_title: "Second scene title",
+
+ error_text: "error",
+ success_text: "all good",
+ success_title: "Ok!",
+ },
+
+ // Newsletter Snippet (https://github.com/mozmeao/snippets/blob/master/activity-stream/newsletter-subscribe.html)
+ newsletter_snippet: {
+ scene1_icon: DATA_URI_IMAGE,
+ scene1_button_label: "Click me",
+ scene1_button_background_color: "#FF0000",
+ scene1_button_color: "#FFFFFF",
+ scene1_text: "Hello world",
+ scene1_title: "Hi!",
+ scene1_title_icon: DATA_URI_IMAGE,
+
+ scene2_text: "Second scene",
+ scene2_title: "Second scene title",
+ scene2_newsletter: "foo",
+ scene2_email_placeholder_text: "Email here",
+ scene2_button_label: "Sign Me Up",
+ scene2_privacy_html: "Hello <em>world</em>",
+ scene2_dismiss_button_text: "Dismiss",
+
+ locale: "de",
+
+ error_text: "error",
+ success_text: "all good",
+ },
+
+ // EOY Snippet (https://github.com/mozmeao/snippets/blob/master/activity-stream/mofo-eoy-2017.html)
+ eoy_snippet: {
+ block_button_text: "Block",
+
+ donation_form_url: "https://donate.mozilla.org/",
+ text:
+ "Big corporations want to restrict how we access the web. Fake news is making it harder for us to find the truth. Online bullies are silencing inspired voices. The not-for-profit Mozilla Foundation fights for a healthy internet with programs like our Tech Policy Fellowships and Internet Health Report; will you donate today?",
+ icon: DATA_URI_IMAGE,
+ button_label: "Donate",
+ monthly_checkbox_label_text: "Make my donation monthly",
+ button_background_color: "#0060DF",
+ button_color: "#FFFFFF",
+ background_color: "#FFFFFF",
+ text_color: "#000000",
+ highlight_color: "#FFE900",
+
+ locale: "en-US",
+ currency_code: "usd",
+
+ donation_amount_first: 50,
+ donation_amount_second: 25,
+ donation_amount_third: 10,
+ donation_amount_fourth: 3,
+ selected_button: "donation_amount_second",
+
+ test: "bold",
+ },
+};
diff --git a/browser/components/newtab/test/unit/asrouter/constants.js b/browser/components/newtab/test/unit/asrouter/constants.js
new file mode 100644
index 0000000000..ba8172febd
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/constants.js
@@ -0,0 +1,166 @@
+export const CHILD_TO_PARENT_MESSAGE_NAME = "ASRouter:child-to-parent";
+export const PARENT_TO_CHILD_MESSAGE_NAME = "ASRouter:parent-to-child";
+
+export const FAKE_LOCAL_MESSAGES = [
+ {
+ id: "foo",
+ provider: "snippets",
+ template: "simple_snippet",
+ content: { title: "Foo", body: "Foo123" },
+ },
+ {
+ id: "foo1",
+ template: "simple_snippet",
+ provider: "snippets",
+ bundled: 2,
+ order: 1,
+ content: { title: "Foo1", body: "Foo123-1" },
+ },
+ {
+ id: "foo2",
+ template: "simple_snippet",
+ provider: "snippets",
+ bundled: 2,
+ order: 2,
+ content: { title: "Foo2", body: "Foo123-2" },
+ },
+ {
+ id: "bar",
+ template: "fancy_template",
+ content: { title: "Foo", body: "Foo123" },
+ },
+ { id: "baz", content: { title: "Foo", body: "Foo123" } },
+ {
+ id: "newsletter",
+ provider: "snippets",
+ template: "newsletter_snippet",
+ content: { title: "Foo", body: "Foo123" },
+ },
+ {
+ id: "fxa",
+ provider: "snippets",
+ template: "fxa_signup_snippet",
+ content: { title: "Foo", body: "Foo123" },
+ },
+ {
+ id: "belowsearch",
+ provider: "snippets",
+ template: "simple_below_search_snippet",
+ content: { text: "Foo" },
+ },
+];
+export const FAKE_LOCAL_PROVIDER = {
+ id: "onboarding",
+ type: "local",
+ localProvider: "FAKE_LOCAL_PROVIDER",
+ enabled: true,
+ cohort: 0,
+};
+export const FAKE_LOCAL_PROVIDERS = {
+ FAKE_LOCAL_PROVIDER: {
+ getMessages: () => Promise.resolve(FAKE_LOCAL_MESSAGES),
+ },
+};
+
+export const FAKE_REMOTE_MESSAGES = [
+ {
+ id: "qux",
+ template: "simple_snippet",
+ content: { title: "Qux", body: "hello world" },
+ },
+];
+export const FAKE_REMOTE_PROVIDER = {
+ id: "remotey",
+ type: "remote",
+ url: "http://fake.com/endpoint",
+ enabled: true,
+};
+
+export const FAKE_REMOTE_SETTINGS_PROVIDER = {
+ id: "remotey-settingsy",
+ type: "remote-settings",
+ bucket: "bucketname",
+ enabled: true,
+};
+
+const notificationText = new String("Fake notification text"); // eslint-disable-line
+notificationText.attributes = { tooltiptext: "Fake tooltip text" };
+
+export const FAKE_RECOMMENDATION = {
+ id: "fake_id",
+ template: "cfr_doorhanger",
+ content: {
+ category: "cfrDummy",
+ bucket_id: "fake_bucket_id",
+ notification_text: notificationText,
+ info_icon: {
+ label: "Fake Info Icon Label",
+ sumo_path: "a_help_path_fragment",
+ },
+ heading_text: "Fake Heading Text",
+ addon: {
+ title: "Fake Addon Title",
+ author: "Fake Addon Author",
+ icon: "a_path_to_some_icon",
+ rating: 4.2,
+ users: 1234,
+ amo_url: "a_path_to_amo",
+ },
+ descriptionDetails: {
+ steps: [{ string_id: "cfr-features-step1" }],
+ },
+ text: "Here is the recommendation text body",
+ buttons: {
+ primary: {
+ label: { string_id: "primary_button_id" },
+ action: {
+ id: "primary_action",
+ data: {},
+ },
+ },
+ secondary: [
+ {
+ label: { string_id: "secondary_button_id" },
+ action: { id: "secondary_action" },
+ },
+ {
+ label: { string_id: "secondary_button_id_2" },
+ },
+ {
+ label: { string_id: "secondary_button_id_3" },
+ action: { id: "secondary_action" },
+ },
+ ],
+ },
+ },
+};
+
+// Stubs methods on RemotePageManager
+export class FakeRemotePageManager {
+ constructor() {
+ this.messagePorts = [];
+ this.addMessageListener = sinon.stub();
+ this.sendAsyncMessage = sinon.stub();
+ this.removeMessageListener = sinon.stub();
+ this.browser = {
+ ownerGlobal: {
+ openTrustedLinkIn: sinon.stub(),
+ openLinkIn: sinon.stub(),
+ OpenBrowserWindow: sinon.stub(),
+ openPreferences: sinon.stub(),
+ gBrowser: {
+ pinTab: sinon.stub(),
+ selectedTab: {},
+ },
+ ConfirmationHint: {
+ show: sinon.stub(),
+ },
+ gProtectionsHandler: {
+ showProtectionsPopup: sinon.stub(),
+ openProtections: sinon.stub(),
+ },
+ },
+ };
+ this.portID = "6000:2";
+ }
+}
diff --git a/browser/components/newtab/test/unit/asrouter/schemas/panel/cfr-fxa-bookmark.schema.test.js b/browser/components/newtab/test/unit/asrouter/schemas/panel/cfr-fxa-bookmark.schema.test.js
new file mode 100644
index 0000000000..915a8c05c4
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/schemas/panel/cfr-fxa-bookmark.schema.test.js
@@ -0,0 +1,28 @@
+import schema from "content-src/asrouter/schemas/panel/cfr-fxa-bookmark.schema.json";
+
+const DEFAULT_CONTENT = {
+ title: "Sync your bookmarks everywhere",
+ text: "Great find! Now don't be left without this bookmark.",
+ cta: "Sync bookmarks now",
+ info_icon: {
+ tooltiptext: "Learn more",
+ },
+};
+
+const L10N_CONTENT = {
+ title: { string_id: "cfr-bookmark-title" },
+ text: { string_id: "cfr-bookmark-body" },
+ cta: { string_id: "cfr-bookmark-link-text" },
+ info_icon: {
+ tooltiptext: { string_id: "cfr-bookmark-tooltip-text" },
+ },
+};
+
+describe("CFR FxA Message Schema", () => {
+ it("should validate DEFAULT_CONTENT", () => {
+ assert.jsonSchema(DEFAULT_CONTENT, schema);
+ });
+ it("should validate L10N_CONTENT", () => {
+ assert.jsonSchema(L10N_CONTENT, schema);
+ });
+});
diff --git a/browser/components/newtab/test/unit/asrouter/template-utils.test.js b/browser/components/newtab/test/unit/asrouter/template-utils.test.js
new file mode 100644
index 0000000000..e5f4b5ef4d
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/template-utils.test.js
@@ -0,0 +1,31 @@
+import { safeURI } from "content-src/asrouter/template-utils";
+
+describe("safeURI", () => {
+ let warnStub;
+ beforeEach(() => {
+ warnStub = sinon.stub(console, "warn");
+ });
+ afterEach(() => {
+ warnStub.restore();
+ });
+ it("should allow http: URIs", () => {
+ assert.equal(safeURI("http://foo.com"), "http://foo.com");
+ });
+ it("should allow https: URIs", () => {
+ assert.equal(safeURI("https://foo.com"), "https://foo.com");
+ });
+ it("should allow data URIs", () => {
+ assert.equal(
+ safeURI("data:image/png;base64,iVBO"),
+ "data:image/png;base64,iVBO"
+ );
+ });
+ it("should not allow javascript: URIs", () => {
+ assert.equal(safeURI("javascript:foo()"), ""); // eslint-disable-line no-script-url
+ assert.calledOnce(warnStub);
+ });
+ it("should not warn if the URL is falsey ", () => {
+ assert.equal(safeURI(), "");
+ assert.notCalled(warnStub);
+ });
+});
diff --git a/browser/components/newtab/test/unit/asrouter/templates/EOYSnippet.test.jsx b/browser/components/newtab/test/unit/asrouter/templates/EOYSnippet.test.jsx
new file mode 100644
index 0000000000..1b5b1ce204
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/templates/EOYSnippet.test.jsx
@@ -0,0 +1,194 @@
+import { EOYSnippet } from "content-src/asrouter/templates/EOYSnippet/EOYSnippet";
+import { GlobalOverrider } from "test/unit/utils";
+import { mount } from "enzyme";
+import React from "react";
+import schema from "content-src/asrouter/templates/EOYSnippet/EOYSnippet.schema.json";
+
+const DEFAULT_CONTENT = {
+ text: "foo",
+ donation_amount_first: 50,
+ donation_amount_second: 25,
+ donation_amount_third: 10,
+ donation_amount_fourth: 5,
+ donation_form_url: "https://submit.form",
+ button_label: "Donate",
+};
+
+describe("EOYSnippet", () => {
+ let sandbox;
+ let wrapper;
+
+ /**
+ * mountAndCheckProps - Mounts a EOYSnippet with DEFAULT_CONTENT extended with any props
+ * passed in the content param and validates props against the schema.
+ * @param {obj} content Object containing custom message content (e.g. {text, icon, title})
+ * @returns enzyme wrapper for EOYSnippet
+ */
+ function mountAndCheckProps(content = {}, provider = "test-provider") {
+ const props = {
+ content: Object.assign({}, DEFAULT_CONTENT, content),
+ provider,
+ onAction: sandbox.stub(),
+ onBlock: sandbox.stub(),
+ sendClick: sandbox.stub(),
+ };
+ const comp = mount(<EOYSnippet {...props} />);
+ // Check schema with the final props the component receives (including defaults)
+ assert.jsonSchema(comp.children().get(0).props.content, schema);
+ return comp;
+ }
+
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ wrapper = mountAndCheckProps();
+ });
+
+ afterEach(() => {
+ sandbox.restore();
+ });
+
+ it("should have the correct defaults", () => {
+ wrapper = mountAndCheckProps();
+ // SendToDeviceSnippet is a wrapper around SubmitFormSnippet
+ const { props } = wrapper.children().get(0);
+
+ const defaultProperties = Object.keys(schema.properties).filter(
+ prop => schema.properties[prop].default
+ );
+ assert.lengthOf(defaultProperties, 4);
+ defaultProperties.forEach(prop =>
+ assert.propertyVal(props.content, prop, schema.properties[prop].default)
+ );
+ });
+
+ it("should render 4 donation options", () => {
+ assert.lengthOf(wrapper.find("input[type='radio']"), 4);
+ });
+
+ it("should have a data-metric field", () => {
+ assert.ok(wrapper.find("form[data-metric='EOYSnippetForm']"));
+ });
+
+ it("should select the second donation option", () => {
+ wrapper = mountAndCheckProps({ selected_button: "donation_amount_second" });
+
+ assert.propertyVal(
+ wrapper.find("input[type='radio']").get(1).props,
+ "defaultChecked",
+ true
+ );
+ });
+
+ it("should set frequency value to monthly", () => {
+ const form = wrapper.find("form").instance();
+ assert.equal(form.querySelector("[name='frequency']").value, "single");
+
+ form.querySelector("#monthly-checkbox").checked = true;
+ wrapper.find("form").simulate("submit");
+
+ assert.equal(form.querySelector("[name='frequency']").value, "monthly");
+ });
+
+ it("should block after submitting the form", () => {
+ const onBlockStub = sandbox.stub();
+ wrapper.setProps({ onBlock: onBlockStub });
+
+ wrapper.find("form").simulate("submit");
+
+ assert.calledOnce(onBlockStub);
+ });
+
+ it("should not block if do_not_autoblock is true", () => {
+ const onBlockStub = sandbox.stub();
+ wrapper = mountAndCheckProps({ do_not_autoblock: true });
+ wrapper.setProps({ onBlock: onBlockStub });
+
+ wrapper.find("form").simulate("submit");
+
+ assert.notCalled(onBlockStub);
+ });
+
+ it("should report form submissions", () => {
+ wrapper = mountAndCheckProps();
+ const { sendClick } = wrapper.props();
+
+ wrapper.find("form").simulate("submit");
+
+ assert.calledOnce(sendClick);
+ assert.equal(
+ sendClick.firstCall.args[0].target.dataset.metric,
+ "EOYSnippetForm"
+ );
+ });
+
+ it("it should preserve URL GET params as hidden inputs", () => {
+ wrapper = mountAndCheckProps({
+ donation_form_url:
+ "https://donate.mozilla.org/pl/?utm_source=desktop-snippet&amp;utm_medium=snippet&amp;utm_campaign=donate&amp;utm_term=7556",
+ });
+
+ const hiddenInputs = wrapper.find("input[type='hidden']");
+
+ assert.propertyVal(
+ hiddenInputs.find("[name='utm_source']").props(),
+ "value",
+ "desktop-snippet"
+ );
+ assert.propertyVal(
+ hiddenInputs.find("[name='amp;utm_medium']").props(),
+ "value",
+ "snippet"
+ );
+ assert.propertyVal(
+ hiddenInputs.find("[name='amp;utm_campaign']").props(),
+ "value",
+ "donate"
+ );
+ assert.propertyVal(
+ hiddenInputs.find("[name='amp;utm_term']").props(),
+ "value",
+ "7556"
+ );
+ });
+
+ describe("locale", () => {
+ let stub;
+ let globals;
+ beforeEach(() => {
+ globals = new GlobalOverrider();
+ stub = sandbox.stub().returns({ format: () => {} });
+
+ globals = new GlobalOverrider();
+ globals.set({ Intl: { NumberFormat: stub } });
+ });
+ afterEach(() => {
+ globals.restore();
+ });
+
+ it("should use content.locale for Intl", () => {
+ // triggers component rendering and calls the function we're testing
+ wrapper.setProps({
+ content: {
+ locale: "locale-foo",
+ donation_form_url: DEFAULT_CONTENT.donation_form_url,
+ },
+ });
+
+ assert.calledOnce(stub);
+ assert.calledWithExactly(stub, "locale-foo", sinon.match.object);
+ });
+
+ it("should use navigator.language as locale fallback", () => {
+ // triggers component rendering and calls the function we're testing
+ wrapper.setProps({
+ content: {
+ locale: null,
+ donation_form_url: DEFAULT_CONTENT.donation_form_url,
+ },
+ });
+
+ assert.calledOnce(stub);
+ assert.calledWithExactly(stub, navigator.language, sinon.match.object);
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/asrouter/templates/ExtensionDoorhanger.test.jsx b/browser/components/newtab/test/unit/asrouter/templates/ExtensionDoorhanger.test.jsx
new file mode 100644
index 0000000000..2e02323690
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/templates/ExtensionDoorhanger.test.jsx
@@ -0,0 +1,98 @@
+import { CFRMessageProvider } from "lib/CFRMessageProvider.jsm";
+import CFRDoorhangerSchema from "content-src/asrouter/templates/CFR/templates/ExtensionDoorhanger.schema.json";
+import CFRChicletSchema from "content-src/asrouter/templates/CFR/templates/CFRUrlbarChiclet.schema.json";
+import InfoBarSchema from "content-src/asrouter/templates/CFR/templates/InfoBar.schema.json";
+
+const SCHEMAS = {
+ cfr_urlbar_chiclet: CFRChicletSchema,
+ cfr_doorhanger: CFRDoorhangerSchema,
+ milestone_message: CFRDoorhangerSchema,
+ infobar: InfoBarSchema,
+};
+
+const DEFAULT_CONTENT = {
+ layout: "addon_recommendation",
+ category: "dummyCategory",
+ bucket_id: "some_bucket_id",
+ notification_text: "Recommendation",
+ heading_text: "Recommended Extension",
+ info_icon: {
+ label: { attributes: { tooltiptext: "Why am I seeing this" } },
+ sumo_path: "extensionrecommendations",
+ },
+ addon: {
+ id: "1234",
+ title: "Addon name",
+ icon: "https://mozilla.org/icon",
+ author: "Author name",
+ amo_url: "https://example.com",
+ },
+ text: "Description of addon",
+ buttons: {
+ primary: {
+ label: {
+ value: "Add Now",
+ attributes: { accesskey: "A" },
+ },
+ action: {
+ type: "INSTALL_ADDON_FROM_URL",
+ data: { url: "https://example.com" },
+ },
+ },
+ secondary: {
+ label: {
+ value: "Not Now",
+ attributes: { accesskey: "N" },
+ },
+ action: { type: "CANCEL" },
+ },
+ },
+};
+
+const L10N_CONTENT = {
+ layout: "addon_recommendation",
+ category: "dummyL10NCategory",
+ bucket_id: "some_bucket_id",
+ notification_text: { string_id: "notification_text_id" },
+ heading_text: { string_id: "heading_text_id" },
+ info_icon: {
+ label: { string_id: "why_seeing_this" },
+ sumo_path: "extensionrecommendations",
+ },
+ addon: {
+ id: "1234",
+ title: "Addon name",
+ icon: "https://mozilla.org/icon",
+ author: "Author name",
+ amo_url: "https://example.com",
+ },
+ text: { string_id: "text_id" },
+ buttons: {
+ primary: {
+ label: { string_id: "btn_ok_id" },
+ action: {
+ type: "INSTALL_ADDON_FROM_URL",
+ data: { url: "https://example.com" },
+ },
+ },
+ secondary: {
+ label: { string_id: "btn_cancel_id" },
+ action: { type: "CANCEL" },
+ },
+ },
+};
+
+describe("ExtensionDoorhanger", () => {
+ it("should validate DEFAULT_CONTENT", () => {
+ assert.jsonSchema(DEFAULT_CONTENT, CFRDoorhangerSchema);
+ });
+ it("should validate L10N_CONTENT", () => {
+ assert.jsonSchema(L10N_CONTENT, CFRDoorhangerSchema);
+ });
+ it("should validate all messages from CFRMessageProvider", async () => {
+ const messages = await CFRMessageProvider.getMessages();
+ messages.forEach(msg =>
+ assert.jsonSchema(msg.content, SCHEMAS[msg.template])
+ );
+ });
+});
diff --git a/browser/components/newtab/test/unit/asrouter/templates/FXASignupSnippet.test.jsx b/browser/components/newtab/test/unit/asrouter/templates/FXASignupSnippet.test.jsx
new file mode 100644
index 0000000000..3833a7511c
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/templates/FXASignupSnippet.test.jsx
@@ -0,0 +1,84 @@
+import { FXASignupSnippet } from "content-src/asrouter/templates/FXASignupSnippet/FXASignupSnippet";
+import { mount } from "enzyme";
+import React from "react";
+import schema from "content-src/asrouter/templates/FXASignupSnippet/FXASignupSnippet.schema.json";
+import { SnippetsTestMessageProvider } from "lib/SnippetsTestMessageProvider.jsm";
+
+describe("FXASignupSnippet", () => {
+ let DEFAULT_CONTENT;
+ let sandbox;
+
+ function mountAndCheckProps(content = {}) {
+ const props = {
+ id: "foo123",
+ content: Object.assign(
+ { utm_campaign: "foo", utm_term: "bar" },
+ DEFAULT_CONTENT,
+ content
+ ),
+ onBlock() {},
+ onDismiss: sandbox.stub(),
+ sendUserActionTelemetry: sandbox.stub(),
+ onAction: sandbox.stub(),
+ };
+ const comp = mount(<FXASignupSnippet {...props} />);
+ // Check schema with the final props the component receives (including defaults)
+ assert.jsonSchema(comp.children().get(0).props.content, schema);
+ return comp;
+ }
+
+ beforeEach(async () => {
+ sandbox = sinon.createSandbox();
+ DEFAULT_CONTENT = (await SnippetsTestMessageProvider.getMessages()).find(
+ msg => msg.template === "fxa_signup_snippet"
+ ).content;
+ });
+ afterEach(() => {
+ sandbox.restore();
+ });
+
+ it("should have the correct defaults", () => {
+ const defaults = {
+ id: "foo123",
+ onBlock() {},
+ content: {},
+ onDismiss: sandbox.stub(),
+ sendUserActionTelemetry: sandbox.stub(),
+ onAction: sandbox.stub(),
+ };
+ const wrapper = mount(<FXASignupSnippet {...defaults} />);
+ // FXASignupSnippet is a wrapper around SubmitFormSnippet
+ const { props } = wrapper.children().get(0);
+
+ const defaultProperties = Object.keys(schema.properties).filter(
+ prop => schema.properties[prop].default
+ );
+ assert.lengthOf(defaultProperties, 5);
+ defaultProperties.forEach(prop =>
+ assert.propertyVal(props.content, prop, schema.properties[prop].default)
+ );
+
+ const defaultHiddenProperties = Object.keys(
+ schema.properties.hidden_inputs.properties
+ ).filter(prop => schema.properties.hidden_inputs.properties[prop].default);
+ assert.lengthOf(defaultHiddenProperties, 0);
+ });
+
+ it("should have a form_action", () => {
+ const wrapper = mountAndCheckProps();
+
+ assert.propertyVal(
+ wrapper.children().get(0).props,
+ "form_action",
+ "https://accounts.firefox.com/"
+ );
+ });
+
+ it("should navigate to scene2", () => {
+ const wrapper = mountAndCheckProps({});
+
+ wrapper.find(".ASRouterButton").simulate("click");
+
+ assert.lengthOf(wrapper.find(".mainInput"), 1);
+ });
+});
diff --git a/browser/components/newtab/test/unit/asrouter/templates/NewsletterSnippet.test.jsx b/browser/components/newtab/test/unit/asrouter/templates/NewsletterSnippet.test.jsx
new file mode 100644
index 0000000000..99410eb879
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/templates/NewsletterSnippet.test.jsx
@@ -0,0 +1,86 @@
+import { mount } from "enzyme";
+import { NewsletterSnippet } from "content-src/asrouter/templates/NewsletterSnippet/NewsletterSnippet";
+import React from "react";
+import schema from "content-src/asrouter/templates/NewsletterSnippet/NewsletterSnippet.schema.json";
+import { SnippetsTestMessageProvider } from "lib/SnippetsTestMessageProvider.jsm";
+
+describe("NewsletterSnippet", () => {
+ let sandbox;
+ let DEFAULT_CONTENT;
+
+ function mountAndCheckProps(content = {}) {
+ const props = {
+ id: "foo123",
+ content: Object.assign({}, DEFAULT_CONTENT, content),
+ onBlock() {},
+ onDismiss: sandbox.stub(),
+ sendUserActionTelemetry: sandbox.stub(),
+ onAction: sandbox.stub(),
+ };
+ const comp = mount(<NewsletterSnippet {...props} />);
+ // Check schema with the final props the component receives (including defaults)
+ assert.jsonSchema(comp.children().get(0).props.content, schema);
+ return comp;
+ }
+
+ beforeEach(async () => {
+ sandbox = sinon.createSandbox();
+ DEFAULT_CONTENT = (await SnippetsTestMessageProvider.getMessages()).find(
+ msg => msg.template === "newsletter_snippet"
+ ).content;
+ });
+ afterEach(() => {
+ sandbox.restore();
+ });
+
+ describe("schema test", () => {
+ it("should validate the schema and defaults", () => {
+ const wrapper = mountAndCheckProps();
+ wrapper.find(".ASRouterButton").simulate("click");
+ assert.equal(wrapper.find(".mainInput").instance().type, "email");
+ });
+
+ it("should have all of the default fields", () => {
+ const defaults = {
+ id: "foo123",
+ content: {},
+ onBlock() {},
+ onDismiss: sandbox.stub(),
+ sendUserActionTelemetry: sandbox.stub(),
+ onAction: sandbox.stub(),
+ };
+ const wrapper = mount(<NewsletterSnippet {...defaults} />);
+ // NewsletterSnippet is a wrapper around SubmitFormSnippet
+ const { props } = wrapper.children().get(0);
+
+ // the `locale` properties gets used as part of hidden_fields so we
+ // check for it separately
+ const properties = { ...schema.properties };
+ const { locale } = properties;
+ delete properties.locale;
+
+ const defaultProperties = Object.keys(properties).filter(
+ prop => properties[prop].default
+ );
+ assert.lengthOf(defaultProperties, 6);
+ defaultProperties.forEach(prop =>
+ assert.propertyVal(props.content, prop, properties[prop].default)
+ );
+
+ const defaultHiddenProperties = Object.keys(
+ schema.properties.hidden_inputs.properties
+ ).filter(
+ prop => schema.properties.hidden_inputs.properties[prop].default
+ );
+ assert.lengthOf(defaultHiddenProperties, 1);
+ defaultHiddenProperties.forEach(prop =>
+ assert.propertyVal(
+ props.content.hidden_inputs,
+ prop,
+ schema.properties.hidden_inputs.properties[prop].default
+ )
+ );
+ assert.propertyVal(props.content.hidden_inputs, "lang", locale.default);
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/asrouter/templates/OnboardingMessage.test.jsx b/browser/components/newtab/test/unit/asrouter/templates/OnboardingMessage.test.jsx
new file mode 100644
index 0000000000..0927e9109b
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/templates/OnboardingMessage.test.jsx
@@ -0,0 +1,80 @@
+import { GlobalOverrider } from "test/unit/utils";
+import { OnboardingMessageProvider } from "lib/OnboardingMessageProvider.jsm";
+import schema from "content-src/asrouter/templates/OnboardingMessage/OnboardingMessage.schema.json";
+import badgeSchema from "content-src/asrouter/templates/OnboardingMessage/ToolbarBadgeMessage.schema.json";
+import whatsNewSchema from "content-src/asrouter/templates/OnboardingMessage/WhatsNewMessage.schema.json";
+
+const DEFAULT_CONTENT = {
+ title: "A title",
+ text: "A description",
+ icon: "icon",
+ primary_button: {
+ label: "some_button_label",
+ action: {
+ type: "SOME_TYPE",
+ data: { args: "example.com" },
+ },
+ },
+};
+
+const L10N_CONTENT = {
+ title: { string_id: "onboarding-private-browsing-title" },
+ text: { string_id: "onboarding-private-browsing-text" },
+ icon: "icon",
+ primary_button: {
+ label: { string_id: "onboarding-button-label-get-started" },
+ action: { type: "SOME_TYPE" },
+ },
+};
+
+describe("OnboardingMessage", () => {
+ let globals;
+ let sandbox;
+ beforeEach(() => {
+ globals = new GlobalOverrider();
+ sandbox = sinon.createSandbox();
+ globals.set("FxAccountsConfig", {
+ promiseConnectAccountURI: sandbox.stub().resolves("some/url"),
+ });
+ globals.set("AddonRepository", {
+ getAddonsByIDs: ([content]) => [
+ {
+ name: content,
+ sourceURI: { spec: "foo", scheme: "https" },
+ icons: { 64: "icon" },
+ },
+ ],
+ });
+ });
+ afterEach(() => {
+ sandbox.restore();
+ globals.restore();
+ });
+ it("should validate DEFAULT_CONTENT", () => {
+ assert.jsonSchema(DEFAULT_CONTENT, schema);
+ });
+ it("should validate L10N_CONTENT", () => {
+ assert.jsonSchema(L10N_CONTENT, schema);
+ });
+ it("should validate all messages from OnboardingMessageProvider", async () => {
+ const messages = await OnboardingMessageProvider.getUntranslatedMessages();
+ // FXA_1 doesn't have content - so filter it out
+ messages
+ .filter(msg => msg.template in ["onboarding", "return_to_amo_overlay"])
+ .forEach(msg => assert.jsonSchema(msg.content, schema));
+ });
+ it("should validate all badge template messages", async () => {
+ const messages = await OnboardingMessageProvider.getUntranslatedMessages();
+
+ messages
+ .filter(msg => msg.template === "toolbar_badge")
+ .forEach(msg => assert.jsonSchema(msg.content, badgeSchema));
+ });
+ it("should validate all What's New template messages", async () => {
+ const messages = await OnboardingMessageProvider.getUntranslatedMessages();
+
+ messages
+ .filter(msg => msg.template === "whatsnew_panel_message")
+ .forEach(msg => assert.jsonSchema(msg.content, whatsNewSchema));
+ });
+});
diff --git a/browser/components/newtab/test/unit/asrouter/templates/SendToDeviceSnippet.test.jsx b/browser/components/newtab/test/unit/asrouter/templates/SendToDeviceSnippet.test.jsx
new file mode 100644
index 0000000000..7f8a6dec24
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/templates/SendToDeviceSnippet.test.jsx
@@ -0,0 +1,252 @@
+import { mount } from "enzyme";
+import React from "react";
+import schema from "content-src/asrouter/templates/SendToDeviceSnippet/SendToDeviceSnippet.schema.json";
+import {
+ SendToDeviceSnippet,
+ SendToDeviceScene2Snippet,
+} from "content-src/asrouter/templates/SendToDeviceSnippet/SendToDeviceSnippet";
+import { SnippetsTestMessageProvider } from "lib/SnippetsTestMessageProvider.jsm";
+
+async function testBodyContains(body, key, value) {
+ const regex = new RegExp(
+ `Content-Disposition: form-data; name="${key}"${value}`
+ );
+ const match = regex.exec(body);
+ return match;
+}
+
+/**
+ * Simulates opening the second panel (form view), filling in the input, and submitting
+ * @param {EnzymeWrapper} wrapper A SendToDevice wrapper
+ * @param {string} value Email or phone number
+ * @param {function?} setCustomValidity setCustomValidity stub
+ */
+function openFormAndSetValue(wrapper, value, setCustomValidity = () => {}) {
+ // expand
+ wrapper.find(".ASRouterButton").simulate("click");
+ // Fill in email
+ const input = wrapper.find(".mainInput");
+ input.instance().value = value;
+ input.simulate("change", { target: { value, setCustomValidity } });
+ wrapper.find("form").simulate("submit");
+}
+
+describe("SendToDeviceSnippet", () => {
+ let sandbox;
+ let fetchStub;
+ let jsonResponse;
+ let DEFAULT_CONTENT;
+ let DEFAULT_SCENE2_CONTENT;
+
+ function mountAndCheckProps(content = {}) {
+ const props = {
+ id: "foo123",
+ content: Object.assign({}, DEFAULT_CONTENT, content),
+ onBlock() {},
+ onDismiss: sandbox.stub(),
+ sendUserActionTelemetry: sandbox.stub(),
+ onAction: sandbox.stub(),
+ };
+ const comp = mount(<SendToDeviceSnippet {...props} />);
+ // Check schema with the final props the component receives (including defaults)
+ assert.jsonSchema(comp.children().get(0).props.content, schema);
+ return comp;
+ }
+
+ beforeEach(async () => {
+ DEFAULT_CONTENT = (await SnippetsTestMessageProvider.getMessages()).find(
+ msg => msg.template === "send_to_device_snippet"
+ ).content;
+ DEFAULT_SCENE2_CONTENT = (
+ await SnippetsTestMessageProvider.getMessages()
+ ).find(msg => msg.template === "send_to_device_scene2_snippet").content;
+ sandbox = sinon.createSandbox();
+ jsonResponse = { status: "ok" };
+ fetchStub = sandbox
+ .stub(global, "fetch")
+ .returns(Promise.resolve({ json: () => Promise.resolve(jsonResponse) }));
+ });
+ afterEach(() => {
+ sandbox.restore();
+ });
+
+ it("should have the correct defaults", () => {
+ const defaults = {
+ id: "foo123",
+ onBlock() {},
+ content: {},
+ onDismiss: sandbox.stub(),
+ sendUserActionTelemetry: sandbox.stub(),
+ onAction: sandbox.stub(),
+ form_method: "POST",
+ };
+ const wrapper = mount(<SendToDeviceSnippet {...defaults} />);
+ // SendToDeviceSnippet is a wrapper around SubmitFormSnippet
+ const { props } = wrapper.children().get(0);
+
+ const defaultProperties = Object.keys(schema.properties).filter(
+ prop => schema.properties[prop].default
+ );
+ assert.lengthOf(defaultProperties, 7);
+ defaultProperties.forEach(prop =>
+ assert.propertyVal(props.content, prop, schema.properties[prop].default)
+ );
+
+ const defaultHiddenProperties = Object.keys(
+ schema.properties.hidden_inputs.properties
+ ).filter(prop => schema.properties.hidden_inputs.properties[prop].default);
+ assert.lengthOf(defaultHiddenProperties, 0);
+ });
+
+ describe("form input", () => {
+ it("should set the input type to text if content.include_sms is true", () => {
+ const wrapper = mountAndCheckProps({ include_sms: true });
+ wrapper.find(".ASRouterButton").simulate("click");
+ assert.equal(wrapper.find(".mainInput").instance().type, "text");
+ });
+ it("should set the input type to email if content.include_sms is false", () => {
+ const wrapper = mountAndCheckProps({ include_sms: false });
+ wrapper.find(".ASRouterButton").simulate("click");
+ assert.equal(wrapper.find(".mainInput").instance().type, "email");
+ });
+ it("should validate the input with isEmailOrPhoneNumber if include_sms is true", () => {
+ const wrapper = mountAndCheckProps({ include_sms: true });
+ const setCustomValidity = sandbox.stub();
+ openFormAndSetValue(wrapper, "foo", setCustomValidity);
+ assert.calledWith(
+ setCustomValidity,
+ "Must be an email or a phone number."
+ );
+ });
+ it("should not custom validate the input if include_sms is false", () => {
+ const wrapper = mountAndCheckProps({ include_sms: false });
+ const setCustomValidity = sandbox.stub();
+ openFormAndSetValue(wrapper, "foo", setCustomValidity);
+ assert.notCalled(setCustomValidity);
+ });
+ });
+
+ describe("submitting", () => {
+ it("should send the right information to basket.mozilla.org/news/subscribe for an email", async () => {
+ const wrapper = mountAndCheckProps({
+ locale: "fr-CA",
+ include_sms: true,
+ message_id_email: "foo",
+ });
+
+ openFormAndSetValue(wrapper, "foo@bar.com");
+ wrapper.find("form").simulate("submit");
+
+ assert.calledOnce(fetchStub);
+ const [request] = fetchStub.firstCall.args;
+
+ assert.equal(request.url, "https://basket.mozilla.org/news/subscribe/");
+ const body = await request.text();
+ assert.ok(testBodyContains(body, "email", "foo@bar.com"), "has email");
+ assert.ok(testBodyContains(body, "lang", "fr-CA"), "has lang");
+ assert.ok(
+ testBodyContains(body, "newsletters", "foo"),
+ "has newsletters"
+ );
+ assert.ok(
+ testBodyContains(body, "source_url", "foo"),
+ "https%3A%2F%2Fsnippets.mozilla.com%2Fshow%2Ffoo123"
+ );
+ });
+ it("should send the right information for an sms", async () => {
+ const wrapper = mountAndCheckProps({
+ locale: "fr-CA",
+ include_sms: true,
+ message_id_sms: "foo",
+ country: "CA",
+ });
+
+ openFormAndSetValue(wrapper, "5371283767");
+ wrapper.find("form").simulate("submit");
+
+ assert.calledOnce(fetchStub);
+ const [request] = fetchStub.firstCall.args;
+
+ assert.equal(
+ request.url,
+ "https://basket.mozilla.org/news/subscribe_sms/"
+ );
+ const body = await request.text();
+ assert.ok(
+ testBodyContains(body, "mobile_number", "5371283767"),
+ "has number"
+ );
+ assert.ok(testBodyContains(body, "lang", "fr-CA"), "has lang");
+ assert.ok(testBodyContains(body, "country", "CA"), "CA");
+ assert.ok(testBodyContains(body, "msg_name", "foo"), "has msg_name");
+ });
+ });
+
+ describe("SendToDeviceScene2Snippet", () => {
+ function mountWithProps(content = {}) {
+ const props = {
+ id: "foo123",
+ content: Object.assign({}, DEFAULT_SCENE2_CONTENT, content),
+ onBlock() {},
+ onDismiss: sandbox.stub(),
+ sendUserActionTelemetry: sandbox.stub(),
+ onAction: sandbox.stub(),
+ };
+ return mount(<SendToDeviceScene2Snippet {...props} />);
+ }
+
+ it("should render scene 2", () => {
+ const wrapper = mountWithProps();
+
+ assert.lengthOf(wrapper.find(".scene2Icon"), 1, "Found scene 2 icon");
+ assert.lengthOf(
+ wrapper.find(".scene2Title"),
+ 0,
+ "Should not have a large header"
+ );
+ });
+ it("should have block button", () => {
+ const wrapper = mountWithProps();
+
+ assert.lengthOf(
+ wrapper.find(".blockButton"),
+ 1,
+ "Found the block button"
+ );
+ });
+ it("should render title text", () => {
+ const wrapper = mountWithProps();
+
+ assert.lengthOf(
+ wrapper.find(".section-title-text"),
+ 1,
+ "Found the section title"
+ );
+ assert.lengthOf(
+ wrapper.find(".section-title .icon"),
+ 2, // light and dark theme
+ "Found scene 2 title"
+ );
+ });
+ it("should wrap the header in an anchor tag if condition is defined", () => {
+ const sectionTitleProp = {
+ section_title_url: "https://support.mozilla.org",
+ };
+ let wrapper = mountWithProps(sectionTitleProp);
+
+ const element = wrapper.find(".section-title a");
+ assert.lengthOf(element, 1);
+ });
+ it("should render a header without an anchor", () => {
+ const sectionTitleProp = {
+ section_title_url: undefined,
+ };
+ let wrapper = mountWithProps(sectionTitleProp);
+ assert.lengthOf(wrapper.find(".section-title a"), 0);
+ assert.equal(
+ wrapper.find(".section-title").instance().innerText,
+ DEFAULT_SCENE2_CONTENT.section_title_text
+ );
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/asrouter/templates/SimpleBelowSearchSnippet.test.jsx b/browser/components/newtab/test/unit/asrouter/templates/SimpleBelowSearchSnippet.test.jsx
new file mode 100644
index 0000000000..d8e46d603c
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/templates/SimpleBelowSearchSnippet.test.jsx
@@ -0,0 +1,62 @@
+import { mount } from "enzyme";
+import React from "react";
+import schema from "content-src/asrouter/templates/SimpleBelowSearchSnippet/SimpleBelowSearchSnippet.schema.json";
+import { SimpleBelowSearchSnippet } from "content-src/asrouter/templates/SimpleBelowSearchSnippet/SimpleBelowSearchSnippet.jsx";
+
+const DEFAULT_CONTENT = { text: "foo" };
+
+describe("SimpleBelowSearchSnippet", () => {
+ let sandbox;
+ let sendUserActionTelemetryStub;
+
+ /**
+ * mountAndCheckProps - Mounts a SimpleBelowSearchSnippet with DEFAULT_CONTENT extended with any props
+ * passed in the content param and validates props against the schema.
+ * @param {obj} content Object containing custom message content (e.g. {text, icon})
+ * @returns enzyme wrapper for SimpleSnippet
+ */
+ function mountAndCheckProps(content = {}, provider = "test-provider") {
+ const props = {
+ content: { ...DEFAULT_CONTENT, ...content },
+ provider,
+ sendUserActionTelemetry: sendUserActionTelemetryStub,
+ onAction: sandbox.stub(),
+ };
+ assert.jsonSchema(props.content, schema);
+ return mount(<SimpleBelowSearchSnippet {...props} />);
+ }
+
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ sendUserActionTelemetryStub = sandbox.stub();
+ });
+
+ afterEach(() => {
+ sandbox.restore();
+ });
+
+ it("should render .text", () => {
+ const wrapper = mountAndCheckProps({ text: "bar" });
+ assert.equal(wrapper.find(".body").text(), "bar");
+ });
+
+ it("should render .icon (light theme)", () => {
+ const wrapper = mountAndCheckProps({
+ icon: "data:image/gif;base64,R0lGODl",
+ });
+ assert.equal(
+ wrapper.find(".icon-light-theme").prop("src"),
+ "data:image/gif;base64,R0lGODl"
+ );
+ });
+
+ it("should render .icon (dark theme)", () => {
+ const wrapper = mountAndCheckProps({
+ icon_dark_theme: "data:image/gif;base64,R0lGODl",
+ });
+ assert.equal(
+ wrapper.find(".icon-dark-theme").prop("src"),
+ "data:image/gif;base64,R0lGODl"
+ );
+ });
+});
diff --git a/browser/components/newtab/test/unit/asrouter/templates/SimpleSnippet.test.jsx b/browser/components/newtab/test/unit/asrouter/templates/SimpleSnippet.test.jsx
new file mode 100644
index 0000000000..cc3601cc54
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/templates/SimpleSnippet.test.jsx
@@ -0,0 +1,255 @@
+import { mount } from "enzyme";
+import React from "react";
+import schema from "content-src/asrouter/templates/SimpleSnippet/SimpleSnippet.schema.json";
+import { SimpleSnippet } from "content-src/asrouter/templates/SimpleSnippet/SimpleSnippet.jsx";
+
+const DEFAULT_CONTENT = { text: "foo" };
+
+describe("SimpleSnippet", () => {
+ let sandbox;
+ let onBlockStub;
+ let sendUserActionTelemetryStub;
+
+ /**
+ * mountAndCheckProps - Mounts a SimpleSnippet with DEFAULT_CONTENT extended with any props
+ * passed in the content param and validates props against the schema.
+ * @param {obj} content Object containing custom message content (e.g. {text, icon, title})
+ * @returns enzyme wrapper for SimpleSnippet
+ */
+ function mountAndCheckProps(content = {}, provider = "test-provider") {
+ const props = {
+ content: Object.assign({}, DEFAULT_CONTENT, content),
+ provider,
+ onBlock: onBlockStub,
+ sendUserActionTelemetry: sendUserActionTelemetryStub,
+ onAction: sandbox.stub(),
+ };
+ assert.jsonSchema(props.content, schema);
+ return mount(<SimpleSnippet {...props} />);
+ }
+
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ onBlockStub = sandbox.stub();
+ sendUserActionTelemetryStub = sandbox.stub();
+ });
+
+ afterEach(() => {
+ sandbox.restore();
+ });
+
+ it("should have the correct defaults", () => {
+ const wrapper = mountAndCheckProps();
+ [["button", "title", "block_button_text"]].forEach(prop => {
+ const props = wrapper.find(prop[0]).props();
+ assert.propertyVal(props, prop[1], schema.properties[prop[2]].default);
+ });
+ });
+
+ it("should render .text", () => {
+ const wrapper = mountAndCheckProps({ text: "bar" });
+ assert.equal(wrapper.find(".body").text(), "bar");
+ });
+ it("should not render title element if no .title prop is supplied", () => {
+ const wrapper = mountAndCheckProps();
+ assert.lengthOf(wrapper.find(".title"), 0);
+ });
+ it("should render .title", () => {
+ const wrapper = mountAndCheckProps({ title: "Foo" });
+ assert.equal(
+ wrapper
+ .find(".title")
+ .text()
+ .trim(),
+ "Foo"
+ );
+ });
+ it("should render a light theme variant .icon", () => {
+ const wrapper = mountAndCheckProps({
+ icon: "data:image/gif;base64,R0lGODl",
+ });
+ assert.equal(
+ wrapper.find(".icon-light-theme").prop("src"),
+ "data:image/gif;base64,R0lGODl"
+ );
+ });
+ it("should render a dark theme variant .icon", () => {
+ const wrapper = mountAndCheckProps({
+ icon_dark_theme: "data:image/gif;base64,R0lGODl",
+ });
+ assert.equal(
+ wrapper.find(".icon-dark-theme").prop("src"),
+ "data:image/gif;base64,R0lGODl"
+ );
+ });
+ it("should render a light theme variant .icon as fallback", () => {
+ const wrapper = mountAndCheckProps({
+ icon_dark_theme: "",
+ icon: "data:image/gif;base64,R0lGODp",
+ });
+ assert.equal(
+ wrapper.find(".icon-dark-theme").prop("src"),
+ "data:image/gif;base64,R0lGODp"
+ );
+ });
+ it("should render .button_label and default className", () => {
+ const wrapper = mountAndCheckProps({
+ button_label: "Click here",
+ button_action: "OPEN_APPLICATIONS_MENU",
+ button_action_args: "appMenu",
+ });
+
+ const button = wrapper.find("button.ASRouterButton");
+ button.simulate("click");
+
+ assert.equal(button.text(), "Click here");
+ assert.equal(button.prop("className"), "ASRouterButton secondary");
+ assert.calledOnce(wrapper.props().onAction);
+ assert.calledWithExactly(wrapper.props().onAction, {
+ type: "OPEN_APPLICATIONS_MENU",
+ data: { args: "appMenu" },
+ });
+ });
+ it("should not wrap the main content if a section header is not present", () => {
+ const wrapper = mountAndCheckProps({ text: "bar" });
+ assert.lengthOf(wrapper.find(".innerContentWrapper"), 0);
+ });
+ it("should wrap the main content if a section header is present", () => {
+ const wrapper = mountAndCheckProps({
+ section_title_icon: "data:image/gif;base64,R0lGODl",
+ section_title_text: "Messages from Mozilla",
+ });
+
+ assert.lengthOf(wrapper.find(".innerContentWrapper"), 1);
+ });
+ it("should render a section header if text and icon (light-theme) are specified", () => {
+ const wrapper = mountAndCheckProps({
+ section_title_icon: "data:image/gif;base64,R0lGODl",
+ section_title_text: "Messages from Mozilla",
+ });
+
+ assert.equal(
+ wrapper.find(".section-title .icon-light-theme").prop("style")
+ .backgroundImage,
+ 'url("data:image/gif;base64,R0lGODl")'
+ );
+ assert.equal(
+ wrapper
+ .find(".section-title-text")
+ .text()
+ .trim(),
+ "Messages from Mozilla"
+ );
+ // ensure there is no <a> when a section_title_url is not specified
+ assert.lengthOf(wrapper.find(".section-title a"), 0);
+ });
+ it("should render a section header if text and icon (light-theme) are specified", () => {
+ const wrapper = mountAndCheckProps({
+ section_title_icon: "data:image/gif;base64,R0lGODl",
+ section_title_icon_dark_theme: "data:image/gif;base64,R0lGODl",
+ section_title_text: "Messages from Mozilla",
+ });
+
+ assert.equal(
+ wrapper.find(".section-title .icon-dark-theme").prop("style")
+ .backgroundImage,
+ 'url("data:image/gif;base64,R0lGODl")'
+ );
+ assert.equal(
+ wrapper
+ .find(".section-title-text")
+ .text()
+ .trim(),
+ "Messages from Mozilla"
+ );
+ // ensure there is no <a> when a section_title_url is not specified
+ assert.lengthOf(wrapper.find(".section-title a"), 0);
+ });
+ it("should render a section header wrapped in an <a> tag if a url is provided", () => {
+ const wrapper = mountAndCheckProps({
+ section_title_icon: "data:image/gif;base64,R0lGODl",
+ section_title_text: "Messages from Mozilla",
+ section_title_url: "https://www.mozilla.org",
+ });
+
+ assert.equal(
+ wrapper.find(".section-title a").prop("href"),
+ "https://www.mozilla.org"
+ );
+ });
+ it("should send an OPEN_URL action when button_url is defined and button is clicked", () => {
+ const wrapper = mountAndCheckProps({
+ button_label: "Button",
+ button_url: "https://mozilla.org",
+ });
+
+ const button = wrapper.find("button.ASRouterButton");
+ button.simulate("click");
+
+ assert.calledOnce(wrapper.props().onAction);
+ assert.calledWithExactly(wrapper.props().onAction, {
+ type: "OPEN_URL",
+ data: { args: "https://mozilla.org" },
+ });
+ });
+ it("should send an OPEN_ABOUT_PAGE action with entrypoint when the button is clicked", () => {
+ const wrapper = mountAndCheckProps({
+ button_label: "Button",
+ button_action: "OPEN_ABOUT_PAGE",
+ button_entrypoint_value: "snippet",
+ button_entrypoint_name: "entryPoint",
+ button_action_args: "logins",
+ });
+
+ const button = wrapper.find("button.ASRouterButton");
+ button.simulate("click");
+
+ assert.calledOnce(wrapper.props().onAction);
+ assert.calledWithExactly(wrapper.props().onAction, {
+ type: "OPEN_ABOUT_PAGE",
+ data: { args: "logins", entrypoint: "entryPoint=snippet" },
+ });
+ });
+ it("should send an OPEN_PREFERENCE_PAGE action with entrypoint when the button is clicked", () => {
+ const wrapper = mountAndCheckProps({
+ button_label: "Button",
+ button_action: "OPEN_PREFERENCE_PAGE",
+ button_entrypoint_value: "entry=snippet",
+ button_action_args: "home",
+ });
+
+ const button = wrapper.find("button.ASRouterButton");
+ button.simulate("click");
+
+ assert.calledOnce(wrapper.props().onAction);
+ assert.calledWithExactly(wrapper.props().onAction, {
+ type: "OPEN_PREFERENCE_PAGE",
+ data: { args: "home", entrypoint: "entry=snippet" },
+ });
+ });
+ it("should call props.onBlock and sendUserActionTelemetry when CTA button is clicked", () => {
+ const wrapper = mountAndCheckProps({ text: "bar" });
+
+ wrapper.instance().onButtonClick();
+
+ assert.calledOnce(onBlockStub);
+ assert.calledOnce(sendUserActionTelemetryStub);
+ });
+
+ it("should not call props.onBlock if do_not_autoblock is true", () => {
+ const wrapper = mountAndCheckProps({ text: "bar", do_not_autoblock: true });
+
+ wrapper.instance().onButtonClick();
+
+ assert.notCalled(onBlockStub);
+ });
+
+ it("should not call sendUserActionTelemetry for preview message when CTA button is clicked", () => {
+ const wrapper = mountAndCheckProps({ text: "bar" }, "preview");
+
+ wrapper.instance().onButtonClick();
+
+ assert.calledOnce(onBlockStub);
+ assert.notCalled(sendUserActionTelemetryStub);
+ });
+});
diff --git a/browser/components/newtab/test/unit/asrouter/templates/SubmitFormSnippet.test.jsx b/browser/components/newtab/test/unit/asrouter/templates/SubmitFormSnippet.test.jsx
new file mode 100644
index 0000000000..0620e8c1e7
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/templates/SubmitFormSnippet.test.jsx
@@ -0,0 +1,341 @@
+import { mount } from "enzyme";
+import React from "react";
+import { RichText } from "content-src/asrouter/components/RichText/RichText.jsx";
+import schema from "content-src/asrouter/templates/SubmitFormSnippet/SubmitFormSnippet.schema.json";
+import { SubmitFormSnippet } from "content-src/asrouter/templates/SubmitFormSnippet/SubmitFormSnippet.jsx";
+
+const DEFAULT_CONTENT = {
+ scene1_text: "foo",
+ scene2_text: "bar",
+ scene1_button_label: "Sign Up",
+ retry_button_label: "Try again",
+ form_action: "foo.com",
+ hidden_inputs: { foo: "foo" },
+ error_text: "error",
+ success_text: "success",
+};
+
+describe("SubmitFormSnippet", () => {
+ let sandbox;
+ let onBlockStub;
+
+ /**
+ * mountAndCheckProps - Mounts a SubmitFormSnippet with DEFAULT_CONTENT extended with any props
+ * passed in the content param and validates props against the schema.
+ * @param {obj} content Object containing custom message content (e.g. {text, icon, title})
+ * @returns enzyme wrapper for SubmitFormSnippet
+ */
+ function mountAndCheckProps(content = {}) {
+ const props = {
+ content: Object.assign({}, DEFAULT_CONTENT, content),
+ onBlock: onBlockStub,
+ onDismiss: sandbox.stub(),
+ sendUserActionTelemetry: sandbox.stub(),
+ onAction: sandbox.stub(),
+ form_method: "POST",
+ };
+ assert.jsonSchema(props.content, schema);
+ return mount(<SubmitFormSnippet {...props} />);
+ }
+
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ onBlockStub = sandbox.stub();
+ });
+
+ afterEach(() => {
+ sandbox.restore();
+ });
+
+ it("should render .text", () => {
+ const wrapper = mountAndCheckProps({ scene1_text: "bar" });
+ assert.equal(wrapper.find(".body").text(), "bar");
+ });
+ it("should not render title element if no .title prop is supplied", () => {
+ const wrapper = mountAndCheckProps();
+ assert.lengthOf(wrapper.find(".title"), 0);
+ });
+ it("should render .title", () => {
+ const wrapper = mountAndCheckProps({ scene1_title: "Foo" });
+ assert.equal(
+ wrapper
+ .find(".title")
+ .text()
+ .trim(),
+ "Foo"
+ );
+ });
+ it("should render light-theme .icon", () => {
+ const wrapper = mountAndCheckProps({
+ scene1_icon: "data:image/gif;base64,R0lGODl",
+ });
+ assert.equal(
+ wrapper.find(".icon-light-theme").prop("src"),
+ "data:image/gif;base64,R0lGODl"
+ );
+ });
+ it("should render dark-theme .icon", () => {
+ const wrapper = mountAndCheckProps({
+ scene1_icon_dark_theme: "data:image/gif;base64,R0lGODl",
+ });
+ assert.equal(
+ wrapper.find(".icon-dark-theme").prop("src"),
+ "data:image/gif;base64,R0lGODl"
+ );
+ });
+ it("should render .button_label and default className", () => {
+ const wrapper = mountAndCheckProps({ scene1_button_label: "Click here" });
+
+ const button = wrapper.find("button.ASRouterButton");
+ assert.equal(button.text(), "Click here");
+ assert.equal(button.prop("className"), "ASRouterButton secondary");
+ });
+
+ describe("#SignupView", () => {
+ let wrapper;
+ const fetchOk = { json: () => Promise.resolve({ status: "ok" }) };
+ const fetchFail = { json: () => Promise.resolve({ status: "fail" }) };
+
+ beforeEach(() => {
+ wrapper = mountAndCheckProps({
+ scene1_text: "bar",
+ scene2_email_placeholder_text: "Email",
+ scene2_text: "signup",
+ });
+ });
+
+ it("should set the input type if provided through props.inputType", () => {
+ wrapper.setProps({ inputType: "number" });
+ wrapper.setState({ expanded: true });
+ assert.equal(wrapper.find(".mainInput").instance().type, "number");
+ });
+
+ it("should validate via props.validateInput if provided", () => {
+ function validateInput(value, content) {
+ if (content.country === "CA" && value === "poutine") {
+ return "";
+ }
+ return "Must be poutine";
+ }
+ const setCustomValidity = sandbox.stub();
+ wrapper.setProps({
+ validateInput,
+ content: { ...DEFAULT_CONTENT, country: "CA" },
+ });
+ wrapper.setState({ expanded: true });
+ const input = wrapper.find(".mainInput");
+ input.instance().value = "poutine";
+ input.simulate("change", {
+ target: { value: "poutine", setCustomValidity },
+ });
+ assert.calledWith(setCustomValidity, "");
+
+ input.instance().value = "fried chicken";
+ input.simulate("change", {
+ target: { value: "fried chicken", setCustomValidity },
+ });
+ assert.calledWith(setCustomValidity, "Must be poutine");
+ });
+
+ it("should show the signup form if state.expanded is true", () => {
+ wrapper.setState({ expanded: true });
+
+ assert.isTrue(wrapper.find("form").exists());
+ });
+ it("should dismiss the snippet", () => {
+ wrapper.setState({ expanded: true });
+
+ wrapper.find(".ASRouterButton.secondary").simulate("click");
+
+ assert.calledOnce(wrapper.props().onDismiss);
+ });
+ it("should send a DISMISS event ping", () => {
+ wrapper.setState({ expanded: true });
+
+ wrapper.find(".ASRouterButton.secondary").simulate("click");
+
+ assert.equal(
+ wrapper.props().sendUserActionTelemetry.firstCall.args[0].event,
+ "DISMISS"
+ );
+ });
+ it("should render hidden inputs + email input", () => {
+ wrapper.setState({ expanded: true });
+
+ assert.lengthOf(wrapper.find("input[type='hidden']"), 1);
+ });
+ it("should open the SignupView when the action button is clicked", () => {
+ assert.isFalse(wrapper.find("form").exists());
+
+ wrapper.find(".ASRouterButton").simulate("click");
+
+ assert.isTrue(wrapper.state().expanded);
+ assert.isTrue(wrapper.find("form").exists());
+ });
+ it("should submit telemetry when the action button is clicked", () => {
+ assert.isFalse(wrapper.find("form").exists());
+
+ wrapper.find(".ASRouterButton").simulate("click");
+
+ assert.equal(
+ wrapper.props().sendUserActionTelemetry.firstCall.args[0].event_context,
+ "scene1-button-learn-more"
+ );
+ });
+ it("should submit form data when submitted", () => {
+ sandbox.stub(window, "fetch").resolves(fetchOk);
+ wrapper.setState({ expanded: true });
+
+ wrapper.find("form").simulate("submit");
+ assert.calledOnce(window.fetch);
+ });
+ it("should send user telemetry when submitted", () => {
+ wrapper.setState({ expanded: true });
+
+ wrapper.find("form").simulate("submit");
+
+ assert.equal(
+ wrapper.props().sendUserActionTelemetry.firstCall.args[0].event_context,
+ "conversion-subscribe-activation"
+ );
+ });
+ it("should set signupSuccess when submission status is ok", async () => {
+ sandbox.stub(window, "fetch").resolves(fetchOk);
+ wrapper.setState({ expanded: true });
+ await wrapper.instance().handleSubmit({ preventDefault: sandbox.stub() });
+
+ assert.equal(wrapper.state().signupSuccess, true);
+ assert.equal(wrapper.state().signupSubmitted, true);
+ assert.calledOnce(onBlockStub);
+ assert.calledWithExactly(onBlockStub, { preventDismiss: true });
+ });
+ it("should send user telemetry when submission status is ok", async () => {
+ sandbox.stub(window, "fetch").resolves(fetchOk);
+ wrapper.setState({ expanded: true });
+ await wrapper.instance().handleSubmit({ preventDefault: sandbox.stub() });
+
+ assert.equal(
+ wrapper.props().sendUserActionTelemetry.secondCall.args[0]
+ .event_context,
+ "subscribe-success"
+ );
+ });
+ it("should not block the snippet if submission failed", async () => {
+ sandbox.stub(window, "fetch").resolves(fetchFail);
+ wrapper.setState({ expanded: true });
+ await wrapper.instance().handleSubmit({ preventDefault: sandbox.stub() });
+
+ assert.equal(wrapper.state().signupSuccess, false);
+ assert.equal(wrapper.state().signupSubmitted, true);
+ assert.notCalled(onBlockStub);
+ });
+ it("should not block if do_not_autoblock is true", async () => {
+ sandbox.stub(window, "fetch").resolves(fetchOk);
+ wrapper = mountAndCheckProps({
+ scene1_text: "bar",
+ scene2_email_placeholder_text: "Email",
+ scene2_text: "signup",
+ do_not_autoblock: true,
+ });
+ wrapper.setState({ expanded: true });
+ await wrapper.instance().handleSubmit({ preventDefault: sandbox.stub() });
+
+ assert.equal(wrapper.state().signupSuccess, true);
+ assert.equal(wrapper.state().signupSubmitted, true);
+ assert.notCalled(onBlockStub);
+ });
+ it("should send user telemetry if submission failed", async () => {
+ sandbox.stub(window, "fetch").resolves(fetchFail);
+ wrapper.setState({ expanded: true });
+ await wrapper.instance().handleSubmit({ preventDefault: sandbox.stub() });
+
+ assert.equal(
+ wrapper.props().sendUserActionTelemetry.secondCall.args[0]
+ .event_context,
+ "subscribe-error"
+ );
+ });
+ it("should render the signup success message", () => {
+ wrapper.setProps({ content: { success_text: "success" } });
+ wrapper.setState({ signupSuccess: true, signupSubmitted: true });
+
+ assert.isTrue(wrapper.find(".submissionStatus").exists());
+ assert.propertyVal(
+ wrapper.find(RichText).props(),
+ "localization_id",
+ "success_text"
+ );
+ assert.propertyVal(
+ wrapper.find(RichText).props(),
+ "success_text",
+ "success"
+ );
+ assert.isFalse(wrapper.find(".ASRouterButton").exists());
+ });
+ it("should render the signup error message", () => {
+ wrapper.setProps({ content: { error_text: "trouble" } });
+ wrapper.setState({ signupSuccess: false, signupSubmitted: true });
+
+ assert.isTrue(wrapper.find(".submissionStatus").exists());
+ assert.propertyVal(
+ wrapper.find(RichText).props(),
+ "localization_id",
+ "error_text"
+ );
+ assert.propertyVal(
+ wrapper.find(RichText).props(),
+ "error_text",
+ "trouble"
+ );
+ assert.isTrue(wrapper.find(".ASRouterButton").exists());
+ });
+ it("should render the button to return to the signup form if there was an error", () => {
+ wrapper.setState({ signupSubmitted: true, signupSuccess: false });
+
+ const button = wrapper.find("button.ASRouterButton");
+ assert.equal(button.text(), "Try again");
+ wrapper.find(".ASRouterButton").simulate("click");
+
+ assert.equal(wrapper.state().signupSubmitted, false);
+ });
+ it("should not render the privacy notice checkbox if prop is missing", () => {
+ wrapper.setState({ expanded: true });
+
+ assert.isFalse(wrapper.find(".privacyNotice").exists());
+ });
+ it("should render the privacy notice checkbox if prop is provided", () => {
+ wrapper.setProps({
+ content: { ...DEFAULT_CONTENT, scene2_privacy_html: "privacy notice" },
+ });
+ wrapper.setState({ expanded: true });
+
+ assert.isTrue(wrapper.find(".privacyNotice").exists());
+ });
+ it("should not call fetch if form_method is GET", async () => {
+ sandbox.stub(window, "fetch").resolves(fetchOk);
+ wrapper.setProps({ form_method: "GET" });
+ wrapper.setState({ expanded: true });
+
+ await wrapper.instance().handleSubmit({ preventDefault: sandbox.stub() });
+
+ assert.notCalled(window.fetch);
+ });
+ it("should block the snippet when form_method is GET", () => {
+ wrapper.setProps({ form_method: "GET" });
+ wrapper.setState({ expanded: true });
+
+ wrapper.instance().handleSubmit({ preventDefault: sandbox.stub() });
+
+ assert.calledOnce(onBlockStub);
+ assert.calledWithExactly(onBlockStub, { preventDismiss: true });
+ });
+ it("should return to scene 2 alt when clicking the retry button", async () => {
+ wrapper.setState({ signupSubmitted: true });
+ wrapper.setProps({ expandedAlt: true });
+
+ wrapper.find(".ASRouterButton").simulate("click");
+
+ assert.isTrue(wrapper.find(".scene2Alt").exists());
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/asrouter/templates/isEmailOrPhoneNumber.test.js b/browser/components/newtab/test/unit/asrouter/templates/isEmailOrPhoneNumber.test.js
new file mode 100644
index 0000000000..32eaf2160e
--- /dev/null
+++ b/browser/components/newtab/test/unit/asrouter/templates/isEmailOrPhoneNumber.test.js
@@ -0,0 +1,56 @@
+import { isEmailOrPhoneNumber } from "content-src/asrouter/templates/SendToDeviceSnippet/isEmailOrPhoneNumber";
+
+const CONTENT = {};
+
+describe("isEmailOrPhoneNumber", () => {
+ it("should return 'email' for emails", () => {
+ assert.equal(isEmailOrPhoneNumber("foobar@asd.com", CONTENT), "email");
+ assert.equal(isEmailOrPhoneNumber("foobar@asd.co.uk", CONTENT), "email");
+ });
+ it("should return 'phone' for valid en-US/en-CA phone numbers", () => {
+ assert.equal(
+ isEmailOrPhoneNumber("14582731273", { locale: "en-US" }),
+ "phone"
+ );
+ assert.equal(
+ isEmailOrPhoneNumber("4582731273", { locale: "en-CA" }),
+ "phone"
+ );
+ });
+ it("should return an empty string for invalid phone number lengths in en-US/en-CA", () => {
+ // Not enough digits
+ assert.equal(isEmailOrPhoneNumber("4522", { locale: "en-US" }), "");
+ assert.equal(isEmailOrPhoneNumber("4522", { locale: "en-CA" }), "");
+ });
+ it("should return 'phone' for valid German phone numbers", () => {
+ assert.equal(
+ isEmailOrPhoneNumber("145827312732", { locale: "de" }),
+ "phone"
+ );
+ });
+ it("should return 'phone' for any number of digits in other locales", () => {
+ assert.equal(isEmailOrPhoneNumber("4", CONTENT), "phone");
+ });
+ it("should return an empty string for other invalid inputs", () => {
+ assert.equal(
+ isEmailOrPhoneNumber("abc", CONTENT),
+ "",
+ "abc should be invalid"
+ );
+ assert.equal(
+ isEmailOrPhoneNumber("abc@", CONTENT),
+ "",
+ "abc@ should be invalid"
+ );
+ assert.equal(
+ isEmailOrPhoneNumber("abc@foo", CONTENT),
+ "",
+ "abc@foo should be invalid"
+ );
+ assert.equal(
+ isEmailOrPhoneNumber("123d1232", CONTENT),
+ "",
+ "123d1232 should be invalid"
+ );
+ });
+});
diff --git a/browser/components/newtab/test/unit/common/Actions.test.js b/browser/components/newtab/test/unit/common/Actions.test.js
new file mode 100644
index 0000000000..47aa047dab
--- /dev/null
+++ b/browser/components/newtab/test/unit/common/Actions.test.js
@@ -0,0 +1,241 @@
+import {
+ actionCreators as ac,
+ actionTypes as at,
+ actionUtils as au,
+ BACKGROUND_PROCESS,
+ CONTENT_MESSAGE_TYPE,
+ globalImportContext,
+ MAIN_MESSAGE_TYPE,
+ PRELOAD_MESSAGE_TYPE,
+ UI_CODE,
+} from "common/Actions.jsm";
+
+describe("Actions", () => {
+ it("should set globalImportContext to UI_CODE", () => {
+ assert.equal(globalImportContext, UI_CODE);
+ });
+});
+
+describe("ActionTypes", () => {
+ it("should be in alpha order", () => {
+ assert.equal(
+ Object.keys(at).join(", "),
+ Object.keys(at)
+ .sort()
+ .join(", ")
+ );
+ });
+});
+
+describe("ActionCreators", () => {
+ describe("_RouteMessage", () => {
+ it("should throw if options are not passed as the second param", () => {
+ assert.throws(() => {
+ au._RouteMessage({ type: "FOO" });
+ });
+ });
+ it("should set all defined options on the .meta property of the new action", () => {
+ assert.deepEqual(
+ au._RouteMessage(
+ { type: "FOO", meta: { hello: "world" } },
+ { from: "foo", to: "bar" }
+ ),
+ { type: "FOO", meta: { hello: "world", from: "foo", to: "bar" } }
+ );
+ });
+ it("should remove any undefined options related to message routing", () => {
+ const action = au._RouteMessage(
+ { type: "FOO", meta: { fromTarget: "bar" } },
+ { from: "foo", to: "bar" }
+ );
+ assert.isUndefined(action.meta.fromTarget);
+ });
+ });
+ describe("AlsoToMain", () => {
+ it("should create the right action", () => {
+ const action = { type: "FOO", data: "BAR" };
+ const newAction = ac.AlsoToMain(action);
+ assert.deepEqual(newAction, {
+ type: "FOO",
+ data: "BAR",
+ meta: { from: CONTENT_MESSAGE_TYPE, to: MAIN_MESSAGE_TYPE },
+ });
+ });
+ it("should add the fromTarget if it was supplied", () => {
+ const action = { type: "FOO", data: "BAR" };
+ const newAction = ac.AlsoToMain(action, "port123");
+ assert.equal(newAction.meta.fromTarget, "port123");
+ });
+ describe("isSendToMain", () => {
+ it("should return true if action is AlsoToMain", () => {
+ const newAction = ac.AlsoToMain({ type: "FOO" });
+ assert.isTrue(au.isSendToMain(newAction));
+ });
+ it("should return false if action is not AlsoToMain", () => {
+ assert.isFalse(au.isSendToMain({ type: "FOO" }));
+ });
+ });
+ });
+ describe("AlsoToOneContent", () => {
+ it("should create the right action", () => {
+ const action = { type: "FOO", data: "BAR" };
+ const targetId = "abc123";
+ const newAction = ac.AlsoToOneContent(action, targetId);
+ assert.deepEqual(newAction, {
+ type: "FOO",
+ data: "BAR",
+ meta: {
+ from: MAIN_MESSAGE_TYPE,
+ to: CONTENT_MESSAGE_TYPE,
+ toTarget: targetId,
+ },
+ });
+ });
+ it("should throw if no targetId is provided", () => {
+ assert.throws(() => {
+ ac.AlsoToOneContent({ type: "FOO" });
+ });
+ });
+ describe("isSendToOneContent", () => {
+ it("should return true if action is AlsoToOneContent", () => {
+ const newAction = ac.AlsoToOneContent({ type: "FOO" }, "foo123");
+ assert.isTrue(au.isSendToOneContent(newAction));
+ });
+ it("should return false if action is not AlsoToMain", () => {
+ assert.isFalse(au.isSendToOneContent({ type: "FOO" }));
+ assert.isFalse(
+ au.isSendToOneContent(ac.BroadcastToContent({ type: "FOO" }))
+ );
+ });
+ });
+ describe("isFromMain", () => {
+ it("should return true if action is AlsoToOneContent", () => {
+ const newAction = ac.AlsoToOneContent({ type: "FOO" }, "foo123");
+ assert.isTrue(au.isFromMain(newAction));
+ });
+ it("should return true if action is BroadcastToContent", () => {
+ const newAction = ac.BroadcastToContent({ type: "FOO" });
+ assert.isTrue(au.isFromMain(newAction));
+ });
+ it("should return false if action is AlsoToMain", () => {
+ const newAction = ac.AlsoToMain({ type: "FOO" });
+ assert.isFalse(au.isFromMain(newAction));
+ });
+ });
+ });
+ describe("BroadcastToContent", () => {
+ it("should create the right action", () => {
+ const action = { type: "FOO", data: "BAR" };
+ const newAction = ac.BroadcastToContent(action);
+ assert.deepEqual(newAction, {
+ type: "FOO",
+ data: "BAR",
+ meta: { from: MAIN_MESSAGE_TYPE, to: CONTENT_MESSAGE_TYPE },
+ });
+ });
+ describe("isBroadcastToContent", () => {
+ it("should return true if action is BroadcastToContent", () => {
+ assert.isTrue(
+ au.isBroadcastToContent(ac.BroadcastToContent({ type: "FOO" }))
+ );
+ });
+ it("should return false if action is not BroadcastToContent", () => {
+ assert.isFalse(au.isBroadcastToContent({ type: "FOO" }));
+ assert.isFalse(
+ au.isBroadcastToContent(
+ ac.AlsoToOneContent({ type: "FOO" }, "foo123")
+ )
+ );
+ });
+ });
+ });
+ describe("AlsoToPreloaded", () => {
+ it("should create the right action", () => {
+ const action = { type: "FOO", data: "BAR" };
+ const newAction = ac.AlsoToPreloaded(action);
+ assert.deepEqual(newAction, {
+ type: "FOO",
+ data: "BAR",
+ meta: { from: MAIN_MESSAGE_TYPE, to: PRELOAD_MESSAGE_TYPE },
+ });
+ });
+ });
+ describe("isSendToPreloaded", () => {
+ it("should return true if action is AlsoToPreloaded", () => {
+ assert.isTrue(au.isSendToPreloaded(ac.AlsoToPreloaded({ type: "FOO" })));
+ });
+ it("should return false if action is not AlsoToPreloaded", () => {
+ assert.isFalse(au.isSendToPreloaded({ type: "FOO" }));
+ assert.isFalse(
+ au.isSendToPreloaded(ac.BroadcastToContent({ type: "FOO" }))
+ );
+ });
+ });
+ describe("UserEvent", () => {
+ it("should include the given data", () => {
+ const data = { action: "foo" };
+ assert.equal(ac.UserEvent(data).data, data);
+ });
+ it("should wrap with AlsoToMain", () => {
+ const action = ac.UserEvent({ action: "foo" });
+ assert.isTrue(au.isSendToMain(action), "isSendToMain");
+ });
+ });
+ describe("ASRouterUserEvent", () => {
+ it("should include the given data", () => {
+ const data = { action: "foo" };
+ assert.equal(ac.ASRouterUserEvent(data).data, data);
+ });
+ it("should wrap with AlsoToMain", () => {
+ const action = ac.ASRouterUserEvent({ action: "foo" });
+ assert.isTrue(au.isSendToMain(action), "isSendToMain");
+ });
+ });
+ describe("ImpressionStats", () => {
+ it("should include the right data", () => {
+ const data = { action: "foo" };
+ assert.equal(ac.ImpressionStats(data).data, data);
+ });
+ it("should wrap with AlsoToMain if in UI code", () => {
+ assert.isTrue(
+ au.isSendToMain(ac.ImpressionStats({ action: "foo" })),
+ "isSendToMain"
+ );
+ });
+ it("should not wrap with AlsoToMain if not in UI code", () => {
+ const action = ac.ImpressionStats({ action: "foo" }, BACKGROUND_PROCESS);
+ assert.isFalse(au.isSendToMain(action), "isSendToMain");
+ });
+ });
+ describe("WebExtEvent", () => {
+ it("should set the provided type", () => {
+ const action = ac.WebExtEvent(at.WEBEXT_CLICK, {
+ source: "MyExtension",
+ url: "foo.com",
+ });
+ assert.equal(action.type, at.WEBEXT_CLICK);
+ });
+ it("should set the provided data", () => {
+ const data = { source: "MyExtension", url: "foo.com" };
+ const action = ac.WebExtEvent(at.WEBEXT_CLICK, data);
+ assert.equal(action.data, data);
+ });
+ it("should throw if the 'source' property is missing", () => {
+ assert.throws(() => {
+ ac.WebExtEvent(at.WEBEXT_CLICK, {});
+ });
+ });
+ });
+});
+
+describe("ActionUtils", () => {
+ describe("getPortIdOfSender", () => {
+ it("should return the PortID from a AlsoToMain action", () => {
+ const portID = "foo123";
+ const result = au.getPortIdOfSender(
+ ac.AlsoToMain({ type: "FOO" }, portID)
+ );
+ assert.equal(result, portID);
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/common/Dedupe.test.js b/browser/components/newtab/test/unit/common/Dedupe.test.js
new file mode 100644
index 0000000000..7efb9d386b
--- /dev/null
+++ b/browser/components/newtab/test/unit/common/Dedupe.test.js
@@ -0,0 +1,38 @@
+import { Dedupe } from "common/Dedupe.jsm";
+
+describe("Dedupe", () => {
+ let instance;
+ beforeEach(() => {
+ instance = new Dedupe();
+ });
+ describe("group", () => {
+ it("should remove duplicates inside the groups", () => {
+ const beforeItems = [
+ [1, 1, 1],
+ [2, 2, 2],
+ [3, 3, 3],
+ ];
+ const afterItems = [[1], [2], [3]];
+ assert.deepEqual(instance.group(...beforeItems), afterItems);
+ });
+ it("should remove duplicates between groups, favouring earlier groups", () => {
+ const beforeItems = [
+ [1, 2, 3],
+ [2, 3, 4],
+ [3, 4, 5],
+ ];
+ const afterItems = [[1, 2, 3], [4], [5]];
+ assert.deepEqual(instance.group(...beforeItems), afterItems);
+ });
+ it("should remove duplicates from groups of objects", () => {
+ instance = new Dedupe(item => item.id);
+ const beforeItems = [
+ [{ id: 1 }, { id: 1 }, { id: 2 }],
+ [{ id: 1 }, { id: 3 }, { id: 2 }],
+ [{ id: 1 }, { id: 2 }, { id: 5 }],
+ ];
+ const afterItems = [[{ id: 1 }, { id: 2 }], [{ id: 3 }], [{ id: 5 }]];
+ assert.deepEqual(instance.group(...beforeItems), afterItems);
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/common/Reducers.test.js b/browser/components/newtab/test/unit/common/Reducers.test.js
new file mode 100644
index 0000000000..de388b4a68
--- /dev/null
+++ b/browser/components/newtab/test/unit/common/Reducers.test.js
@@ -0,0 +1,1560 @@
+import { INITIAL_STATE, insertPinned, reducers } from "common/Reducers.jsm";
+const {
+ TopSites,
+ App,
+ Snippets,
+ Prefs,
+ Dialog,
+ Sections,
+ Pocket,
+ Personalization,
+ DiscoveryStream,
+ Search,
+ ASRouter,
+} = reducers;
+import { actionTypes as at } from "common/Actions.jsm";
+
+describe("Reducers", () => {
+ describe("App", () => {
+ it("should return the initial state", () => {
+ const nextState = App(undefined, { type: "FOO" });
+ assert.equal(nextState, INITIAL_STATE.App);
+ });
+ it("should set initialized to true on INIT", () => {
+ const nextState = App(undefined, { type: "INIT" });
+
+ assert.propertyVal(nextState, "initialized", true);
+ });
+ });
+ describe("TopSites", () => {
+ it("should return the initial state", () => {
+ const nextState = TopSites(undefined, { type: "FOO" });
+ assert.equal(nextState, INITIAL_STATE.TopSites);
+ });
+ it("should add top sites on TOP_SITES_UPDATED", () => {
+ const newRows = [{ url: "foo.com" }, { url: "bar.com" }];
+ const nextState = TopSites(undefined, {
+ type: at.TOP_SITES_UPDATED,
+ data: { links: newRows },
+ });
+ assert.equal(nextState.rows, newRows);
+ });
+ it("should not update state for empty action.data on TOP_SITES_UPDATED", () => {
+ const nextState = TopSites(undefined, { type: at.TOP_SITES_UPDATED });
+ assert.equal(nextState, INITIAL_STATE.TopSites);
+ });
+ it("should initialize prefs on TOP_SITES_UPDATED", () => {
+ const nextState = TopSites(undefined, {
+ type: at.TOP_SITES_UPDATED,
+ data: { links: [], pref: "foo" },
+ });
+
+ assert.equal(nextState.pref, "foo");
+ });
+ it("should pass prevState.prefs if not present in TOP_SITES_UPDATED", () => {
+ const nextState = TopSites(
+ { prefs: "foo" },
+ { type: at.TOP_SITES_UPDATED, data: { links: [] } }
+ );
+
+ assert.equal(nextState.prefs, "foo");
+ });
+ it("should set editForm.site to action.data on TOP_SITES_EDIT", () => {
+ const data = { index: 7 };
+ const nextState = TopSites(undefined, { type: at.TOP_SITES_EDIT, data });
+ assert.equal(nextState.editForm.index, data.index);
+ });
+ it("should set editForm to null on TOP_SITES_CANCEL_EDIT", () => {
+ const nextState = TopSites(undefined, { type: at.TOP_SITES_CANCEL_EDIT });
+ assert.isNull(nextState.editForm);
+ });
+ it("should preserve the editForm.index", () => {
+ const actionTypes = [
+ at.PREVIEW_RESPONSE,
+ at.PREVIEW_REQUEST,
+ at.PREVIEW_REQUEST_CANCEL,
+ ];
+ actionTypes.forEach(type => {
+ const oldState = { editForm: { index: 0, previewUrl: "foo" } };
+ const action = { type, data: { url: "foo" } };
+ const nextState = TopSites(oldState, action);
+ assert.equal(nextState.editForm.index, 0);
+ });
+ });
+ it("should set previewResponse on PREVIEW_RESPONSE", () => {
+ const oldState = { editForm: { previewUrl: "url" } };
+ const action = {
+ type: at.PREVIEW_RESPONSE,
+ data: { preview: "data:123", url: "url" },
+ };
+ const nextState = TopSites(oldState, action);
+ assert.propertyVal(nextState.editForm, "previewResponse", "data:123");
+ });
+ it("should return previous state if action url does not match expected", () => {
+ const oldState = { editForm: { previewUrl: "foo" } };
+ const action = { type: at.PREVIEW_RESPONSE, data: { url: "bar" } };
+ const nextState = TopSites(oldState, action);
+ assert.equal(nextState, oldState);
+ });
+ it("should return previous state if editForm is not set", () => {
+ const actionTypes = [
+ at.PREVIEW_RESPONSE,
+ at.PREVIEW_REQUEST,
+ at.PREVIEW_REQUEST_CANCEL,
+ ];
+ actionTypes.forEach(type => {
+ const oldState = { editForm: null };
+ const action = { type, data: { url: "bar" } };
+ const nextState = TopSites(oldState, action);
+ assert.equal(nextState, oldState, type);
+ });
+ });
+ it("should set previewResponse to null on PREVIEW_REQUEST", () => {
+ const oldState = { editForm: { previewResponse: "foo" } };
+ const action = { type: at.PREVIEW_REQUEST, data: {} };
+ const nextState = TopSites(oldState, action);
+ assert.propertyVal(nextState.editForm, "previewResponse", null);
+ });
+ it("should set previewUrl on PREVIEW_REQUEST", () => {
+ const oldState = { editForm: {} };
+ const action = { type: at.PREVIEW_REQUEST, data: { url: "bar" } };
+ const nextState = TopSites(oldState, action);
+ assert.propertyVal(nextState.editForm, "previewUrl", "bar");
+ });
+ it("should add screenshots for SCREENSHOT_UPDATED", () => {
+ const oldState = { rows: [{ url: "foo.com" }, { url: "bar.com" }] };
+ const action = {
+ type: at.SCREENSHOT_UPDATED,
+ data: { url: "bar.com", screenshot: "data:123" },
+ };
+ const nextState = TopSites(oldState, action);
+ assert.deepEqual(nextState.rows, [
+ { url: "foo.com" },
+ { url: "bar.com", screenshot: "data:123" },
+ ]);
+ });
+ it("should not modify rows if nothing matches the url for SCREENSHOT_UPDATED", () => {
+ const oldState = { rows: [{ url: "foo.com" }, { url: "bar.com" }] };
+ const action = {
+ type: at.SCREENSHOT_UPDATED,
+ data: { url: "baz.com", screenshot: "data:123" },
+ };
+ const nextState = TopSites(oldState, action);
+ assert.deepEqual(nextState, oldState);
+ });
+ it("should bookmark an item on PLACES_BOOKMARK_ADDED", () => {
+ const oldState = { rows: [{ url: "foo.com" }, { url: "bar.com" }] };
+ const action = {
+ type: at.PLACES_BOOKMARK_ADDED,
+ data: {
+ url: "bar.com",
+ bookmarkGuid: "bookmark123",
+ bookmarkTitle: "Title for bar.com",
+ dateAdded: 1234567,
+ },
+ };
+ const nextState = TopSites(oldState, action);
+ const [, newRow] = nextState.rows;
+ // new row has bookmark data
+ assert.equal(newRow.url, action.data.url);
+ assert.equal(newRow.bookmarkGuid, action.data.bookmarkGuid);
+ assert.equal(newRow.bookmarkTitle, action.data.bookmarkTitle);
+ assert.equal(newRow.bookmarkDateCreated, action.data.dateAdded);
+
+ // old row is unchanged
+ assert.equal(nextState.rows[0], oldState.rows[0]);
+ });
+ it("should not update state for empty action.data on PLACES_BOOKMARK_ADDED", () => {
+ const nextState = TopSites(undefined, { type: at.PLACES_BOOKMARK_ADDED });
+ assert.equal(nextState, INITIAL_STATE.TopSites);
+ });
+ it("should remove a bookmark on PLACES_BOOKMARK_REMOVED", () => {
+ const oldState = {
+ rows: [
+ { url: "foo.com" },
+ {
+ url: "bar.com",
+ bookmarkGuid: "bookmark123",
+ bookmarkTitle: "Title for bar.com",
+ dateAdded: 123456,
+ },
+ ],
+ };
+ const action = {
+ type: at.PLACES_BOOKMARK_REMOVED,
+ data: { url: "bar.com" },
+ };
+ const nextState = TopSites(oldState, action);
+ const [, newRow] = nextState.rows;
+ // new row no longer has bookmark data
+ assert.equal(newRow.url, oldState.rows[1].url);
+ assert.isUndefined(newRow.bookmarkGuid);
+ assert.isUndefined(newRow.bookmarkTitle);
+ assert.isUndefined(newRow.bookmarkDateCreated);
+
+ // old row is unchanged
+ assert.deepEqual(nextState.rows[0], oldState.rows[0]);
+ });
+ it("should not update state for empty action.data on PLACES_BOOKMARK_REMOVED", () => {
+ const nextState = TopSites(undefined, {
+ type: at.PLACES_BOOKMARK_REMOVED,
+ });
+ assert.equal(nextState, INITIAL_STATE.TopSites);
+ });
+ it("should update prefs on TOP_SITES_PREFS_UPDATED", () => {
+ const state = TopSites(
+ {},
+ { type: at.TOP_SITES_PREFS_UPDATED, data: { pref: "foo" } }
+ );
+
+ assert.equal(state.pref, "foo");
+ });
+ it("should not update state for empty action.data on PLACES_LINK_DELETED", () => {
+ const nextState = TopSites(undefined, { type: at.PLACES_LINK_DELETED });
+ assert.equal(nextState, INITIAL_STATE.TopSites);
+ });
+ it("should remove the site on PLACES_LINK_DELETED", () => {
+ const oldState = { rows: [{ url: "foo.com" }, { url: "bar.com" }] };
+ const deleteAction = {
+ type: at.PLACES_LINK_DELETED,
+ data: { url: "foo.com" },
+ };
+ const nextState = TopSites(oldState, deleteAction);
+ assert.deepEqual(nextState.rows, [{ url: "bar.com" }]);
+ });
+ it("should set showSearchShortcutsForm to true on TOP_SITES_OPEN_SEARCH_SHORTCUTS_MODAL", () => {
+ const data = { index: 7 };
+ const nextState = TopSites(undefined, {
+ type: at.TOP_SITES_OPEN_SEARCH_SHORTCUTS_MODAL,
+ data,
+ });
+ assert.isTrue(nextState.showSearchShortcutsForm);
+ });
+ it("should set showSearchShortcutsForm to false on TOP_SITES_CLOSE_SEARCH_SHORTCUTS_MODAL", () => {
+ const nextState = TopSites(undefined, {
+ type: at.TOP_SITES_CLOSE_SEARCH_SHORTCUTS_MODAL,
+ });
+ assert.isFalse(nextState.showSearchShortcutsForm);
+ });
+ it("should update searchShortcuts on UPDATE_SEARCH_SHORTCUTS", () => {
+ const shortcuts = [
+ {
+ keyword: "@google",
+ shortURL: "google",
+ url: "https://google.com",
+ searchIdentifier: /^google/,
+ },
+ {
+ keyword: "@baidu",
+ shortURL: "baidu",
+ url: "https://baidu.com",
+ searchIdentifier: /^baidu/,
+ },
+ ];
+ const nextState = TopSites(undefined, {
+ type: at.UPDATE_SEARCH_SHORTCUTS,
+ data: { searchShortcuts: shortcuts },
+ });
+ assert.deepEqual(shortcuts, nextState.searchShortcuts);
+ });
+ it("should remove all content on SNIPPETS_PREVIEW_MODE", () => {
+ const oldState = { rows: [{ url: "foo.com" }, { url: "bar.com" }] };
+ const nextState = TopSites(oldState, { type: at.SNIPPETS_PREVIEW_MODE });
+ assert.lengthOf(nextState.rows, 0);
+ });
+ });
+ describe("Prefs", () => {
+ function prevState(custom = {}) {
+ return Object.assign({}, INITIAL_STATE.Prefs, custom);
+ }
+ it("should have the correct initial state", () => {
+ const state = Prefs(undefined, {});
+ assert.deepEqual(state, INITIAL_STATE.Prefs);
+ });
+ describe("PREFS_INITIAL_VALUES", () => {
+ it("should return a new object", () => {
+ const state = Prefs(undefined, {
+ type: at.PREFS_INITIAL_VALUES,
+ data: {},
+ });
+ assert.notEqual(
+ INITIAL_STATE.Prefs,
+ state,
+ "should not modify INITIAL_STATE"
+ );
+ });
+ it("should set initalized to true", () => {
+ const state = Prefs(undefined, {
+ type: at.PREFS_INITIAL_VALUES,
+ data: {},
+ });
+ assert.isTrue(state.initialized);
+ });
+ it("should set .values", () => {
+ const newValues = { foo: 1, bar: 2 };
+ const state = Prefs(undefined, {
+ type: at.PREFS_INITIAL_VALUES,
+ data: newValues,
+ });
+ assert.equal(state.values, newValues);
+ });
+ });
+ describe("PREF_CHANGED", () => {
+ it("should return a new Prefs object", () => {
+ const state = Prefs(undefined, {
+ type: at.PREF_CHANGED,
+ data: { name: "foo", value: 2 },
+ });
+ assert.notEqual(
+ INITIAL_STATE.Prefs,
+ state,
+ "should not modify INITIAL_STATE"
+ );
+ });
+ it("should set the changed pref", () => {
+ const state = Prefs(prevState({ foo: 1 }), {
+ type: at.PREF_CHANGED,
+ data: { name: "foo", value: 2 },
+ });
+ assert.equal(state.values.foo, 2);
+ });
+ it("should return a new .pref object instead of mutating", () => {
+ const oldState = prevState({ foo: 1 });
+ const state = Prefs(oldState, {
+ type: at.PREF_CHANGED,
+ data: { name: "foo", value: 2 },
+ });
+ assert.notEqual(oldState.values, state.values);
+ });
+ });
+ });
+ describe("Dialog", () => {
+ it("should return INITIAL_STATE by default", () => {
+ assert.equal(
+ INITIAL_STATE.Dialog,
+ Dialog(undefined, { type: "non_existent" })
+ );
+ });
+ it("should toggle visible to true on DIALOG_OPEN", () => {
+ const action = { type: at.DIALOG_OPEN };
+ const nextState = Dialog(INITIAL_STATE.Dialog, action);
+ assert.isTrue(nextState.visible);
+ });
+ it("should pass url data on DIALOG_OPEN", () => {
+ const action = { type: at.DIALOG_OPEN, data: "some url" };
+ const nextState = Dialog(INITIAL_STATE.Dialog, action);
+ assert.equal(nextState.data, action.data);
+ });
+ it("should toggle visible to false on DIALOG_CANCEL", () => {
+ const action = { type: at.DIALOG_CANCEL, data: "some url" };
+ const nextState = Dialog(INITIAL_STATE.Dialog, action);
+ assert.isFalse(nextState.visible);
+ });
+ it("should return inital state on DELETE_HISTORY_URL", () => {
+ const action = { type: at.DELETE_HISTORY_URL };
+ const nextState = Dialog(INITIAL_STATE.Dialog, action);
+
+ assert.deepEqual(INITIAL_STATE.Dialog, nextState);
+ });
+ });
+ describe("Sections", () => {
+ let oldState;
+
+ beforeEach(() => {
+ oldState = new Array(5).fill(null).map((v, i) => ({
+ id: `foo_bar_${i}`,
+ title: `Foo Bar ${i}`,
+ initialized: false,
+ rows: [
+ { url: "www.foo.bar", pocket_id: 123 },
+ { url: "www.other.url" },
+ ],
+ order: i,
+ type: "history",
+ }));
+ });
+
+ it("should return INITIAL_STATE by default", () => {
+ assert.equal(
+ INITIAL_STATE.Sections,
+ Sections(undefined, { type: "non_existent" })
+ );
+ });
+ it("should remove the correct section on SECTION_DEREGISTER", () => {
+ const newState = Sections(oldState, {
+ type: at.SECTION_DEREGISTER,
+ data: "foo_bar_2",
+ });
+ assert.lengthOf(newState, 4);
+ const expectedNewState = oldState.splice(2, 1) && oldState;
+ assert.deepEqual(newState, expectedNewState);
+ });
+ it("should add a section on SECTION_REGISTER if it doesn't already exist", () => {
+ const action = {
+ type: at.SECTION_REGISTER,
+ data: { id: "foo_bar_5", title: "Foo Bar 5" },
+ };
+ const newState = Sections(oldState, action);
+ assert.lengthOf(newState, 6);
+ const insertedSection = newState.find(
+ section => section.id === "foo_bar_5"
+ );
+ assert.propertyVal(insertedSection, "title", action.data.title);
+ });
+ it("should set newSection.rows === [] if no rows are provided on SECTION_REGISTER", () => {
+ const action = {
+ type: at.SECTION_REGISTER,
+ data: { id: "foo_bar_5", title: "Foo Bar 5" },
+ };
+ const newState = Sections(oldState, action);
+ const insertedSection = newState.find(
+ section => section.id === "foo_bar_5"
+ );
+ assert.deepEqual(insertedSection.rows, []);
+ });
+ it("should update a section on SECTION_REGISTER if it already exists", () => {
+ const NEW_TITLE = "New Title";
+ const action = {
+ type: at.SECTION_REGISTER,
+ data: { id: "foo_bar_2", title: NEW_TITLE },
+ };
+ const newState = Sections(oldState, action);
+ assert.lengthOf(newState, 5);
+ const updatedSection = newState.find(
+ section => section.id === "foo_bar_2"
+ );
+ assert.ok(updatedSection && updatedSection.title === NEW_TITLE);
+ });
+ it("should set initialized to false on SECTION_REGISTER if there are no rows", () => {
+ const NEW_TITLE = "New Title";
+ const action = {
+ type: at.SECTION_REGISTER,
+ data: { id: "bloop", title: NEW_TITLE },
+ };
+ const newState = Sections(oldState, action);
+ const updatedSection = newState.find(section => section.id === "bloop");
+ assert.propertyVal(updatedSection, "initialized", false);
+ });
+ it("should set initialized to true on SECTION_REGISTER if there are rows", () => {
+ const NEW_TITLE = "New Title";
+ const action = {
+ type: at.SECTION_REGISTER,
+ data: { id: "bloop", title: NEW_TITLE, rows: [{}, {}] },
+ };
+ const newState = Sections(oldState, action);
+ const updatedSection = newState.find(section => section.id === "bloop");
+ assert.propertyVal(updatedSection, "initialized", true);
+ });
+ it("should have no effect on SECTION_UPDATE if the id doesn't exist", () => {
+ const action = {
+ type: at.SECTION_UPDATE,
+ data: { id: "fake_id", data: "fake_data" },
+ };
+ const newState = Sections(oldState, action);
+ assert.deepEqual(oldState, newState);
+ });
+ it("should update the section with the correct data on SECTION_UPDATE", () => {
+ const FAKE_DATA = { rows: ["some", "fake", "data"], foo: "bar" };
+ const action = {
+ type: at.SECTION_UPDATE,
+ data: Object.assign(FAKE_DATA, { id: "foo_bar_2" }),
+ };
+ const newState = Sections(oldState, action);
+ const updatedSection = newState.find(
+ section => section.id === "foo_bar_2"
+ );
+ assert.include(updatedSection, FAKE_DATA);
+ });
+ it("should set initialized to true on SECTION_UPDATE if rows is defined on action.data", () => {
+ const data = { rows: [], id: "foo_bar_2" };
+ const action = { type: at.SECTION_UPDATE, data };
+ const newState = Sections(oldState, action);
+ const updatedSection = newState.find(
+ section => section.id === "foo_bar_2"
+ );
+ assert.propertyVal(updatedSection, "initialized", true);
+ });
+ it("should retain pinned cards on SECTION_UPDATE", () => {
+ const ROW = { id: "row" };
+ let newState = Sections(oldState, {
+ type: at.SECTION_UPDATE,
+ data: Object.assign({ rows: [ROW] }, { id: "foo_bar_2" }),
+ });
+ let updatedSection = newState.find(section => section.id === "foo_bar_2");
+ assert.deepEqual(updatedSection.rows, [ROW]);
+
+ const PINNED_ROW = { id: "pinned", pinned: true, guid: "pinned" };
+ newState = Sections(newState, {
+ type: at.SECTION_UPDATE,
+ data: Object.assign({ rows: [PINNED_ROW] }, { id: "foo_bar_2" }),
+ });
+ updatedSection = newState.find(section => section.id === "foo_bar_2");
+ assert.deepEqual(updatedSection.rows, [PINNED_ROW]);
+
+ // Updating the section again should not duplicate pinned cards
+ newState = Sections(newState, {
+ type: at.SECTION_UPDATE,
+ data: Object.assign({ rows: [PINNED_ROW] }, { id: "foo_bar_2" }),
+ });
+ updatedSection = newState.find(section => section.id === "foo_bar_2");
+ assert.deepEqual(updatedSection.rows, [PINNED_ROW]);
+
+ // Updating the section should retain pinned card at its index
+ newState = Sections(newState, {
+ type: at.SECTION_UPDATE,
+ data: Object.assign({ rows: [ROW] }, { id: "foo_bar_2" }),
+ });
+ updatedSection = newState.find(section => section.id === "foo_bar_2");
+ assert.deepEqual(updatedSection.rows, [PINNED_ROW, ROW]);
+
+ // Clearing/Resetting the section should clear pinned cards
+ newState = Sections(newState, {
+ type: at.SECTION_UPDATE,
+ data: Object.assign({ rows: [] }, { id: "foo_bar_2" }),
+ });
+ updatedSection = newState.find(section => section.id === "foo_bar_2");
+ assert.deepEqual(updatedSection.rows, []);
+ });
+ it("should have no effect on SECTION_UPDATE_CARD if the id or url doesn't exist", () => {
+ const noIdAction = {
+ type: at.SECTION_UPDATE_CARD,
+ data: {
+ id: "non-existent",
+ url: "www.foo.bar",
+ options: { title: "New title" },
+ },
+ };
+ const noIdState = Sections(oldState, noIdAction);
+ const noUrlAction = {
+ type: at.SECTION_UPDATE_CARD,
+ data: {
+ id: "foo_bar_2",
+ url: "www.non-existent.url",
+ options: { title: "New title" },
+ },
+ };
+ const noUrlState = Sections(oldState, noUrlAction);
+ assert.deepEqual(noIdState, oldState);
+ assert.deepEqual(noUrlState, oldState);
+ });
+ it("should update the card with the correct data on SECTION_UPDATE_CARD", () => {
+ const action = {
+ type: at.SECTION_UPDATE_CARD,
+ data: {
+ id: "foo_bar_2",
+ url: "www.other.url",
+ options: { title: "Fake new title" },
+ },
+ };
+ const newState = Sections(oldState, action);
+ const updatedSection = newState.find(
+ section => section.id === "foo_bar_2"
+ );
+ const updatedCard = updatedSection.rows.find(
+ card => card.url === "www.other.url"
+ );
+ assert.propertyVal(updatedCard, "title", "Fake new title");
+ });
+ it("should only update the cards belonging to the right section on SECTION_UPDATE_CARD", () => {
+ const action = {
+ type: at.SECTION_UPDATE_CARD,
+ data: {
+ id: "foo_bar_2",
+ url: "www.other.url",
+ options: { title: "Fake new title" },
+ },
+ };
+ const newState = Sections(oldState, action);
+ newState.forEach((section, i) => {
+ if (section.id !== "foo_bar_2") {
+ assert.deepEqual(section, oldState[i]);
+ }
+ });
+ });
+ it("should allow action.data to set .initialized", () => {
+ const data = { rows: [], initialized: false, id: "foo_bar_2" };
+ const action = { type: at.SECTION_UPDATE, data };
+ const newState = Sections(oldState, action);
+ const updatedSection = newState.find(
+ section => section.id === "foo_bar_2"
+ );
+ assert.propertyVal(updatedSection, "initialized", false);
+ });
+ it("should dedupe based on dedupeConfigurations", () => {
+ const site = { url: "foo.com" };
+ const highlights = { rows: [site], id: "highlights" };
+ const topstories = { rows: [site], id: "topstories" };
+ const dedupeConfigurations = [
+ { id: "topstories", dedupeFrom: ["highlights"] },
+ ];
+ const action = { data: { dedupeConfigurations }, type: "SECTION_UPDATE" };
+ const state = [highlights, topstories];
+
+ const nextState = Sections(state, action);
+
+ assert.equal(nextState.find(s => s.id === "highlights").rows.length, 1);
+ assert.equal(nextState.find(s => s.id === "topstories").rows.length, 0);
+ });
+ it("should remove blocked and deleted urls from all rows in all sections", () => {
+ const blockAction = {
+ type: at.PLACES_LINK_BLOCKED,
+ data: { url: "www.foo.bar" },
+ };
+ const deleteAction = {
+ type: at.PLACES_LINK_DELETED,
+ data: { url: "www.foo.bar" },
+ };
+ const newBlockState = Sections(oldState, blockAction);
+ const newDeleteState = Sections(oldState, deleteAction);
+ newBlockState.concat(newDeleteState).forEach(section => {
+ assert.deepEqual(section.rows, [{ url: "www.other.url" }]);
+ });
+ });
+ it("should not update state for empty action.data on PLACES_LINK_DELETED", () => {
+ const nextState = Sections(undefined, { type: at.PLACES_LINK_DELETED });
+ assert.equal(nextState, INITIAL_STATE.Sections);
+ });
+ it("should remove all removed pocket urls", () => {
+ const removeAction = {
+ type: at.DELETE_FROM_POCKET,
+ data: { pocket_id: 123 },
+ };
+ const newBlockState = Sections(oldState, removeAction);
+ newBlockState.forEach(section => {
+ assert.deepEqual(section.rows, [{ url: "www.other.url" }]);
+ });
+ });
+ it("should archive all archived pocket urls", () => {
+ const removeAction = {
+ type: at.ARCHIVE_FROM_POCKET,
+ data: { pocket_id: 123 },
+ };
+ const newBlockState = Sections(oldState, removeAction);
+ newBlockState.forEach(section => {
+ assert.deepEqual(section.rows, [{ url: "www.other.url" }]);
+ });
+ });
+ it("should not update state for empty action.data on PLACES_BOOKMARK_ADDED", () => {
+ const nextState = Sections(undefined, { type: at.PLACES_BOOKMARK_ADDED });
+ assert.equal(nextState, INITIAL_STATE.Sections);
+ });
+ it("should bookmark an item when PLACES_BOOKMARK_ADDED is received", () => {
+ const action = {
+ type: at.PLACES_BOOKMARK_ADDED,
+ data: {
+ url: "www.foo.bar",
+ bookmarkGuid: "bookmark123",
+ bookmarkTitle: "Title for bar.com",
+ dateAdded: 1234567,
+ },
+ };
+ const nextState = Sections(oldState, action);
+ // check a section to ensure the correct url was bookmarked
+ const [newRow, oldRow] = nextState[0].rows;
+
+ // new row has bookmark data
+ assert.equal(newRow.url, action.data.url);
+ assert.equal(newRow.type, "bookmark");
+ assert.equal(newRow.bookmarkGuid, action.data.bookmarkGuid);
+ assert.equal(newRow.bookmarkTitle, action.data.bookmarkTitle);
+ assert.equal(newRow.bookmarkDateCreated, action.data.dateAdded);
+
+ // old row is unchanged
+ assert.equal(oldRow, oldState[0].rows[1]);
+ });
+ it("should not update state for empty action.data on PLACES_BOOKMARK_REMOVED", () => {
+ const nextState = Sections(undefined, {
+ type: at.PLACES_BOOKMARK_REMOVED,
+ });
+ assert.equal(nextState, INITIAL_STATE.Sections);
+ });
+ it("should remove the bookmark when PLACES_BOOKMARK_REMOVED is received", () => {
+ const action = {
+ type: at.PLACES_BOOKMARK_REMOVED,
+ data: {
+ url: "www.foo.bar",
+ bookmarkGuid: "bookmark123",
+ },
+ };
+ // add some bookmark data for the first url in rows
+ oldState.forEach(item => {
+ item.rows[0].bookmarkGuid = "bookmark123";
+ item.rows[0].bookmarkTitle = "Title for bar.com";
+ item.rows[0].bookmarkDateCreated = 1234567;
+ item.rows[0].type = "bookmark";
+ });
+ const nextState = Sections(oldState, action);
+ // check a section to ensure the correct bookmark was removed
+ const [newRow, oldRow] = nextState[0].rows;
+
+ // new row isn't a bookmark
+ assert.equal(newRow.url, action.data.url);
+ assert.equal(newRow.type, "history");
+ assert.isUndefined(newRow.bookmarkGuid);
+ assert.isUndefined(newRow.bookmarkTitle);
+ assert.isUndefined(newRow.bookmarkDateCreated);
+
+ // old row is unchanged
+ assert.equal(oldRow, oldState[0].rows[1]);
+ });
+ it("should not update state for empty action.data on PLACES_SAVED_TO_POCKET", () => {
+ const nextState = Sections(undefined, {
+ type: at.PLACES_SAVED_TO_POCKET,
+ });
+ assert.equal(nextState, INITIAL_STATE.Sections);
+ });
+ it("should add a pocked item on PLACES_SAVED_TO_POCKET", () => {
+ const action = {
+ type: at.PLACES_SAVED_TO_POCKET,
+ data: {
+ url: "www.foo.bar",
+ pocket_id: 1234,
+ title: "Title for bar.com",
+ },
+ };
+ const nextState = Sections(oldState, action);
+ // check a section to ensure the correct url was saved to pocket
+ const [newRow, oldRow] = nextState[0].rows;
+
+ // new row has pocket data
+ assert.equal(newRow.url, action.data.url);
+ assert.equal(newRow.type, "pocket");
+ assert.equal(newRow.pocket_id, action.data.pocket_id);
+ assert.equal(newRow.title, action.data.title);
+
+ // old row is unchanged
+ assert.equal(oldRow, oldState[0].rows[1]);
+ });
+ it("should remove all content on SNIPPETS_PREVIEW_MODE", () => {
+ const previewMode = { type: at.SNIPPETS_PREVIEW_MODE };
+ const newState = Sections(oldState, previewMode);
+ newState.forEach(section => {
+ assert.lengthOf(section.rows, 0);
+ });
+ });
+ });
+ describe("#insertPinned", () => {
+ let links;
+
+ beforeEach(() => {
+ links = new Array(12).fill(null).map((v, i) => ({ url: `site${i}.com` }));
+ });
+
+ it("should place pinned links where they belong", () => {
+ const pinned = [
+ { url: "http://github.com/mozilla/activity-stream", title: "moz/a-s" },
+ { url: "http://example.com", title: "example" },
+ ];
+ const result = insertPinned(links, pinned);
+ for (let index of [0, 1]) {
+ assert.equal(result[index].url, pinned[index].url);
+ assert.ok(result[index].isPinned);
+ assert.equal(result[index].pinIndex, index);
+ }
+ assert.deepEqual(result.slice(2), links);
+ });
+ it("should handle empty slots in the pinned list", () => {
+ const pinned = [
+ null,
+ { url: "http://github.com/mozilla/activity-stream", title: "moz/a-s" },
+ null,
+ null,
+ { url: "http://example.com", title: "example" },
+ ];
+ const result = insertPinned(links, pinned);
+ for (let index of [1, 4]) {
+ assert.equal(result[index].url, pinned[index].url);
+ assert.ok(result[index].isPinned);
+ assert.equal(result[index].pinIndex, index);
+ }
+ result.splice(4, 1);
+ result.splice(1, 1);
+ assert.deepEqual(result, links);
+ });
+ it("should handle a pinned site past the end of the list of links", () => {
+ const pinned = [];
+ pinned[11] = {
+ url: "http://github.com/mozilla/activity-stream",
+ title: "moz/a-s",
+ };
+ const result = insertPinned([], pinned);
+ assert.equal(result[11].url, pinned[11].url);
+ assert.isTrue(result[11].isPinned);
+ assert.equal(result[11].pinIndex, 11);
+ });
+ it("should unpin previously pinned links no longer in the pinned list", () => {
+ const pinned = [];
+ links[2].isPinned = true;
+ links[2].pinIndex = 2;
+ const result = insertPinned(links, pinned);
+ assert.notProperty(result[2], "isPinned");
+ assert.notProperty(result[2], "pinIndex");
+ });
+ it("should handle a link present in both the links and pinned list", () => {
+ const pinned = [links[7]];
+ const result = insertPinned(links, pinned);
+ assert.equal(links.length, result.length);
+ });
+ it("should not modify the original data", () => {
+ const pinned = [{ url: "http://example.com" }];
+
+ insertPinned(links, pinned);
+
+ assert.equal(typeof pinned[0].isPinned, "undefined");
+ });
+ });
+ describe("Snippets", () => {
+ it("should return INITIAL_STATE by default", () => {
+ assert.equal(
+ Snippets(undefined, { type: "some_action" }),
+ INITIAL_STATE.Snippets
+ );
+ });
+ it("should set initialized to true on a SNIPPETS_DATA action", () => {
+ const state = Snippets(undefined, { type: at.SNIPPETS_DATA, data: {} });
+ assert.isTrue(state.initialized);
+ });
+ it("should set the snippet data on a SNIPPETS_DATA action", () => {
+ const data = { snippetsURL: "foo.com", version: 4 };
+ const state = Snippets(undefined, { type: at.SNIPPETS_DATA, data });
+ assert.propertyVal(state, "snippetsURL", data.snippetsURL);
+ assert.propertyVal(state, "version", data.version);
+ });
+ it("should reset to the initial state on a SNIPPETS_RESET action", () => {
+ const state = Snippets(
+ { initialized: true, foo: "bar" },
+ { type: at.SNIPPETS_RESET }
+ );
+ assert.equal(state, INITIAL_STATE.Snippets);
+ });
+ it("should set the new blocklist on SNIPPET_BLOCKED", () => {
+ const state = Snippets(
+ { blockList: [] },
+ { type: at.SNIPPET_BLOCKED, data: 1 }
+ );
+ assert.deepEqual(state.blockList, [1]);
+ });
+ it("should clear the blocklist on SNIPPETS_BLOCKLIST_CLEARED", () => {
+ const state = Snippets(
+ { blockList: [1, 2] },
+ { type: at.SNIPPETS_BLOCKLIST_CLEARED }
+ );
+ assert.deepEqual(state.blockList, []);
+ });
+ });
+ describe("Pocket", () => {
+ it("should return INITIAL_STATE by default", () => {
+ assert.equal(
+ Pocket(undefined, { type: "some_action" }),
+ INITIAL_STATE.Pocket
+ );
+ });
+ it("should set waitingForSpoc on a POCKET_WAITING_FOR_SPOC action", () => {
+ const state = Pocket(undefined, {
+ type: at.POCKET_WAITING_FOR_SPOC,
+ data: false,
+ });
+ assert.isFalse(state.waitingForSpoc);
+ });
+ it("should have undefined for initial isUserLoggedIn state", () => {
+ assert.isNull(Pocket(undefined, { type: "some_action" }).isUserLoggedIn);
+ });
+ it("should set isUserLoggedIn to false on a POCKET_LOGGED_IN with null", () => {
+ const state = Pocket(undefined, {
+ type: at.POCKET_LOGGED_IN,
+ data: null,
+ });
+ assert.isFalse(state.isUserLoggedIn);
+ });
+ it("should set isUserLoggedIn to false on a POCKET_LOGGED_IN with false", () => {
+ const state = Pocket(undefined, {
+ type: at.POCKET_LOGGED_IN,
+ data: false,
+ });
+ assert.isFalse(state.isUserLoggedIn);
+ });
+ it("should set isUserLoggedIn to true on a POCKET_LOGGED_IN with true", () => {
+ const state = Pocket(undefined, {
+ type: at.POCKET_LOGGED_IN,
+ data: true,
+ });
+ assert.isTrue(state.isUserLoggedIn);
+ });
+ it("should set pocketCta with correct object on a POCKET_CTA", () => {
+ const data = {
+ cta_button: "cta button",
+ cta_text: "cta text",
+ cta_url: "https://cta-url.com",
+ use_cta: true,
+ };
+ const state = Pocket(undefined, { type: at.POCKET_CTA, data });
+ assert.equal(state.pocketCta.ctaButton, data.cta_button);
+ assert.equal(state.pocketCta.ctaText, data.cta_text);
+ assert.equal(state.pocketCta.ctaUrl, data.cta_url);
+ assert.equal(state.pocketCta.useCta, data.use_cta);
+ });
+ });
+ describe("Personalization", () => {
+ it("should return INITIAL_STATE by default", () => {
+ assert.equal(
+ Personalization(undefined, { type: "some_action" }),
+ INITIAL_STATE.Personalization
+ );
+ });
+ it("should set version to 2 with DISCOVERY_STREAM_PERSONALIZATION_VERSION", () => {
+ const state = Personalization(undefined, {
+ type: at.DISCOVERY_STREAM_PERSONALIZATION_VERSION,
+ data: {
+ version: 2,
+ },
+ });
+ assert.equal(state.version, 2);
+ });
+ it("should set version to 2 with PREF_CHANGED", () => {
+ const state = Personalization(undefined, {
+ type: at.PREF_CHANGED,
+ data: {
+ name: "discoverystream.personalization.version",
+ value: 2,
+ },
+ });
+ assert.equal(state.version, 2);
+ });
+ it("should set lastUpdated with DISCOVERY_STREAM_PERSONALIZATION_LAST_UPDATED", () => {
+ const state = Personalization(undefined, {
+ type: at.DISCOVERY_STREAM_PERSONALIZATION_LAST_UPDATED,
+ data: {
+ lastUpdated: 123,
+ },
+ });
+ assert.equal(state.lastUpdated, 123);
+ });
+ it("should set initialized to true with DISCOVERY_STREAM_PERSONALIZATION_INIT", () => {
+ const state = Personalization(undefined, {
+ type: at.DISCOVERY_STREAM_PERSONALIZATION_INIT,
+ });
+ assert.equal(state.initialized, true);
+ });
+ });
+ describe("DiscoveryStream", () => {
+ it("should return INITIAL_STATE by default", () => {
+ assert.equal(
+ DiscoveryStream(undefined, { type: "some_action" }),
+ INITIAL_STATE.DiscoveryStream
+ );
+ });
+ it("should set isPrivacyInfoModalVisible to true with SHOW_PRIVACY_INFO", () => {
+ const state = DiscoveryStream(undefined, {
+ type: at.SHOW_PRIVACY_INFO,
+ });
+ assert.equal(state.isPrivacyInfoModalVisible, true);
+ });
+ it("should set isPrivacyInfoModalVisible to false with HIDE_PRIVACY_INFO", () => {
+ const state = DiscoveryStream(undefined, {
+ type: at.HIDE_PRIVACY_INFO,
+ });
+ assert.equal(state.isPrivacyInfoModalVisible, false);
+ });
+ it("should set layout data with DISCOVERY_STREAM_LAYOUT_UPDATE", () => {
+ const state = DiscoveryStream(undefined, {
+ type: at.DISCOVERY_STREAM_LAYOUT_UPDATE,
+ data: { layout: ["test"], lastUpdated: 123 },
+ });
+ assert.equal(state.layout[0], "test");
+ assert.equal(state.lastUpdated, 123);
+ });
+ it("should reset layout data with DISCOVERY_STREAM_LAYOUT_RESET", () => {
+ const layoutData = { layout: ["test"], lastUpdated: 123 };
+ const feedsData = {
+ "https://foo.com/feed1": { lastUpdated: 123, data: [1, 2, 3] },
+ };
+ const spocsData = {
+ lastUpdated: 123,
+ spocs: [1, 2, 3],
+ };
+ let state = DiscoveryStream(undefined, {
+ type: at.DISCOVERY_STREAM_LAYOUT_UPDATE,
+ data: layoutData,
+ });
+ state = DiscoveryStream(state, {
+ type: at.DISCOVERY_STREAM_FEEDS_UPDATE,
+ data: feedsData,
+ });
+ state = DiscoveryStream(state, {
+ type: at.DISCOVERY_STREAM_SPOCS_UPDATE,
+ data: spocsData,
+ });
+ state = DiscoveryStream(state, {
+ type: at.DISCOVERY_STREAM_LAYOUT_RESET,
+ });
+
+ assert.deepEqual(state, INITIAL_STATE.DiscoveryStream);
+ });
+ it("should set config data with DISCOVERY_STREAM_CONFIG_CHANGE", () => {
+ const state = DiscoveryStream(undefined, {
+ type: at.DISCOVERY_STREAM_CONFIG_CHANGE,
+ data: { enabled: true },
+ });
+ assert.deepEqual(state.config, { enabled: true });
+ });
+ it("should set feeds as loaded with DISCOVERY_STREAM_FEEDS_UPDATE", () => {
+ const state = DiscoveryStream(undefined, {
+ type: at.DISCOVERY_STREAM_FEEDS_UPDATE,
+ });
+ assert.isTrue(state.feeds.loaded);
+ });
+ it("should set spoc_endpoint with DISCOVERY_STREAM_SPOCS_ENDPOINT", () => {
+ const state = DiscoveryStream(undefined, {
+ type: at.DISCOVERY_STREAM_SPOCS_ENDPOINT,
+ data: { url: "foo.com" },
+ });
+ assert.equal(state.spocs.spocs_endpoint, "foo.com");
+ });
+ it("should use initial state with DISCOVERY_STREAM_SPOCS_PLACEMENTS", () => {
+ const state = DiscoveryStream(undefined, {
+ type: at.DISCOVERY_STREAM_SPOCS_PLACEMENTS,
+ data: {},
+ });
+ assert.deepEqual(state.spocs.placements, []);
+ });
+ it("should set placements with DISCOVERY_STREAM_SPOCS_PLACEMENTS", () => {
+ const state = DiscoveryStream(undefined, {
+ type: at.DISCOVERY_STREAM_SPOCS_PLACEMENTS,
+ data: {
+ placements: [1, 2, 3],
+ },
+ });
+ assert.deepEqual(state.spocs.placements, [1, 2, 3]);
+ });
+ it("should set spocs with DISCOVERY_STREAM_SPOCS_UPDATE", () => {
+ const data = {
+ lastUpdated: 123,
+ spocs: [1, 2, 3],
+ };
+ const state = DiscoveryStream(undefined, {
+ type: at.DISCOVERY_STREAM_SPOCS_UPDATE,
+ data,
+ });
+ assert.deepEqual(state.spocs, {
+ spocs_endpoint: "",
+ data: [1, 2, 3],
+ lastUpdated: 123,
+ loaded: true,
+ frequency_caps: [],
+ blocked: [],
+ placements: [],
+ });
+ });
+ it("should default to a single spoc placement", () => {
+ const deleteAction = {
+ type: at.DISCOVERY_STREAM_LINK_BLOCKED,
+ data: { url: "https://foo.com" },
+ };
+ const oldState = {
+ spocs: {
+ data: {
+ spocs: {
+ items: [
+ {
+ url: "test-spoc.com",
+ },
+ ],
+ },
+ },
+ loaded: true,
+ },
+ feeds: {
+ data: {},
+ loaded: true,
+ },
+ };
+
+ const newState = DiscoveryStream(oldState, deleteAction);
+
+ assert.equal(newState.spocs.data.spocs.items.length, 1);
+ });
+ it("should handle no data from DISCOVERY_STREAM_SPOCS_UPDATE", () => {
+ const data = null;
+ const state = DiscoveryStream(undefined, {
+ type: at.DISCOVERY_STREAM_SPOCS_UPDATE,
+ data,
+ });
+ assert.deepEqual(state.spocs, INITIAL_STATE.DiscoveryStream.spocs);
+ });
+ it("should add blocked spocs to blocked array with DISCOVERY_STREAM_SPOC_BLOCKED", () => {
+ const firstState = DiscoveryStream(undefined, {
+ type: at.DISCOVERY_STREAM_SPOC_BLOCKED,
+ data: { url: "https://foo.com" },
+ });
+ const secondState = DiscoveryStream(firstState, {
+ type: at.DISCOVERY_STREAM_SPOC_BLOCKED,
+ data: { url: "https://bar.com" },
+ });
+ assert.deepEqual(firstState.spocs.blocked, ["https://foo.com"]);
+ assert.deepEqual(secondState.spocs.blocked, [
+ "https://foo.com",
+ "https://bar.com",
+ ]);
+ });
+ it("should not update state for empty action.data on DISCOVERY_STREAM_LINK_BLOCKED", () => {
+ const newState = DiscoveryStream(undefined, {
+ type: at.DISCOVERY_STREAM_LINK_BLOCKED,
+ });
+ assert.equal(newState, INITIAL_STATE.DiscoveryStream);
+ });
+ it("should not update state if feeds are not loaded", () => {
+ const deleteAction = {
+ type: at.DISCOVERY_STREAM_LINK_BLOCKED,
+ data: { url: "foo.com" },
+ };
+ const newState = DiscoveryStream(undefined, deleteAction);
+ assert.equal(newState, INITIAL_STATE.DiscoveryStream);
+ });
+ it("should not update state if spocs and feeds data is undefined", () => {
+ const deleteAction = {
+ type: at.DISCOVERY_STREAM_LINK_BLOCKED,
+ data: { url: "foo.com" },
+ };
+ const oldState = {
+ spocs: {
+ data: {},
+ loaded: true,
+ placements: [{ name: "spocs" }],
+ },
+ feeds: {
+ data: {},
+ loaded: true,
+ },
+ };
+ const newState = DiscoveryStream(oldState, deleteAction);
+ assert.deepEqual(newState, oldState);
+ });
+ it("should remove the site on DISCOVERY_STREAM_LINK_BLOCKED from spocs if feeds data is empty", () => {
+ const deleteAction = {
+ type: at.DISCOVERY_STREAM_LINK_BLOCKED,
+ data: { url: "https://foo.com" },
+ };
+ const oldState = {
+ spocs: {
+ data: {
+ spocs: {
+ items: [{ url: "https://foo.com" }, { url: "test-spoc.com" }],
+ },
+ },
+ loaded: true,
+ placements: [{ name: "spocs" }],
+ },
+ feeds: {
+ data: {},
+ loaded: true,
+ },
+ };
+ const newState = DiscoveryStream(oldState, deleteAction);
+ assert.deepEqual(newState.spocs.data.spocs.items, [
+ { url: "test-spoc.com" },
+ ]);
+ });
+ it("should remove the site on DISCOVERY_STREAM_LINK_BLOCKED from feeds if spocs data is empty", () => {
+ const deleteAction = {
+ type: at.DISCOVERY_STREAM_LINK_BLOCKED,
+ data: { url: "https://foo.com" },
+ };
+ const oldState = {
+ spocs: {
+ data: {},
+ loaded: true,
+ placements: [{ name: "spocs" }],
+ },
+ feeds: {
+ data: {
+ "https://foo.com/feed1": {
+ data: {
+ recommendations: [
+ { url: "https://foo.com" },
+ { url: "test.com" },
+ ],
+ },
+ },
+ },
+ loaded: true,
+ },
+ };
+ const newState = DiscoveryStream(oldState, deleteAction);
+ assert.deepEqual(
+ newState.feeds.data["https://foo.com/feed1"].data.recommendations,
+ [{ url: "test.com" }]
+ );
+ });
+ it("should remove the site on DISCOVERY_STREAM_LINK_BLOCKED from both feeds and spocs", () => {
+ const oldState = {
+ feeds: {
+ data: {
+ "https://foo.com/feed1": {
+ data: {
+ recommendations: [
+ { url: "https://foo.com" },
+ { url: "test.com" },
+ ],
+ },
+ },
+ },
+ loaded: true,
+ },
+ spocs: {
+ data: {
+ spocs: {
+ items: [{ url: "https://foo.com" }, { url: "test-spoc.com" }],
+ },
+ },
+ loaded: true,
+ placements: [{ name: "spocs" }],
+ },
+ };
+ const deleteAction = {
+ type: at.DISCOVERY_STREAM_LINK_BLOCKED,
+ data: { url: "https://foo.com" },
+ };
+ const newState = DiscoveryStream(oldState, deleteAction);
+ assert.deepEqual(newState.spocs.data.spocs.items, [
+ { url: "test-spoc.com" },
+ ]);
+ assert.deepEqual(
+ newState.feeds.data["https://foo.com/feed1"].data.recommendations,
+ [{ url: "test.com" }]
+ );
+ });
+ it("should not update state for empty action.data on PLACES_SAVED_TO_POCKET", () => {
+ const newState = DiscoveryStream(undefined, {
+ type: at.PLACES_SAVED_TO_POCKET,
+ });
+ assert.equal(newState, INITIAL_STATE.DiscoveryStream);
+ });
+ it("should add pocket_id on PLACES_SAVED_TO_POCKET in both feeds and spocs", () => {
+ const oldState = {
+ feeds: {
+ data: {
+ "https://foo.com/feed1": {
+ data: {
+ recommendations: [
+ { url: "https://foo.com" },
+ { url: "test.com" },
+ ],
+ },
+ },
+ },
+ loaded: true,
+ },
+ spocs: {
+ data: {
+ spocs: {
+ items: [{ url: "https://foo.com" }, { url: "test-spoc.com" }],
+ },
+ },
+ placements: [{ name: "spocs" }],
+ loaded: true,
+ },
+ };
+ const action = {
+ type: at.PLACES_SAVED_TO_POCKET,
+ data: {
+ url: "https://foo.com",
+ pocket_id: 1234,
+ open_url: "https://foo-1234",
+ },
+ };
+
+ const newState = DiscoveryStream(oldState, action);
+
+ assert.lengthOf(newState.spocs.data.spocs.items, 2);
+ assert.equal(
+ newState.spocs.data.spocs.items[0].pocket_id,
+ action.data.pocket_id
+ );
+ assert.equal(
+ newState.spocs.data.spocs.items[0].open_url,
+ action.data.open_url
+ );
+ assert.isUndefined(newState.spocs.data.spocs.items[1].pocket_id);
+
+ assert.lengthOf(
+ newState.feeds.data["https://foo.com/feed1"].data.recommendations,
+ 2
+ );
+ assert.equal(
+ newState.feeds.data["https://foo.com/feed1"].data.recommendations[0]
+ .pocket_id,
+ action.data.pocket_id
+ );
+ assert.equal(
+ newState.feeds.data["https://foo.com/feed1"].data.recommendations[0]
+ .open_url,
+ action.data.open_url
+ );
+ assert.isUndefined(
+ newState.feeds.data["https://foo.com/feed1"].data.recommendations[1]
+ .pocket_id
+ );
+ });
+ it("should not update state for empty action.data on DELETE_FROM_POCKET", () => {
+ const newState = DiscoveryStream(undefined, {
+ type: at.DELETE_FROM_POCKET,
+ });
+ assert.equal(newState, INITIAL_STATE.DiscoveryStream);
+ });
+ it("should remove site on DELETE_FROM_POCKET in both feeds and spocs", () => {
+ const oldState = {
+ feeds: {
+ data: {
+ "https://foo.com/feed1": {
+ data: {
+ recommendations: [
+ { url: "https://foo.com", pocket_id: 1234 },
+ { url: "test.com" },
+ ],
+ },
+ },
+ },
+ loaded: true,
+ },
+ spocs: {
+ data: {
+ spocs: {
+ items: [
+ { url: "https://foo.com", pocket_id: 1234 },
+ { url: "test-spoc.com" },
+ ],
+ },
+ },
+ loaded: true,
+ placements: [{ name: "spocs" }],
+ },
+ };
+ const deleteAction = {
+ type: at.DELETE_FROM_POCKET,
+ data: {
+ pocket_id: 1234,
+ },
+ };
+
+ const newState = DiscoveryStream(oldState, deleteAction);
+ assert.deepEqual(newState.spocs.data.spocs.items, [
+ { url: "test-spoc.com" },
+ ]);
+ assert.deepEqual(
+ newState.feeds.data["https://foo.com/feed1"].data.recommendations,
+ [{ url: "test.com" }]
+ );
+ });
+ it("should remove site on ARCHIVE_FROM_POCKET in both feeds and spocs", () => {
+ const oldState = {
+ feeds: {
+ data: {
+ "https://foo.com/feed1": {
+ data: {
+ recommendations: [
+ { url: "https://foo.com", pocket_id: 1234 },
+ { url: "test.com" },
+ ],
+ },
+ },
+ },
+ loaded: true,
+ },
+ spocs: {
+ data: {
+ spocs: {
+ items: [
+ { url: "https://foo.com", pocket_id: 1234 },
+ { url: "test-spoc.com" },
+ ],
+ },
+ },
+ loaded: true,
+ placements: [{ name: "spocs" }],
+ },
+ };
+ const deleteAction = {
+ type: at.ARCHIVE_FROM_POCKET,
+ data: {
+ pocket_id: 1234,
+ },
+ };
+
+ const newState = DiscoveryStream(oldState, deleteAction);
+ assert.deepEqual(newState.spocs.data.spocs.items, [
+ { url: "test-spoc.com" },
+ ]);
+ assert.deepEqual(
+ newState.feeds.data["https://foo.com/feed1"].data.recommendations,
+ [{ url: "test.com" }]
+ );
+ });
+ it("should add boookmark details on PLACES_BOOKMARK_ADDED in both feeds and spocs", () => {
+ const oldState = {
+ feeds: {
+ data: {
+ "https://foo.com/feed1": {
+ data: {
+ recommendations: [
+ { url: "https://foo.com" },
+ { url: "test.com" },
+ ],
+ },
+ },
+ },
+ loaded: true,
+ },
+ spocs: {
+ data: {
+ spocs: {
+ items: [{ url: "https://foo.com" }, { url: "test-spoc.com" }],
+ },
+ },
+ loaded: true,
+ placements: [{ name: "spocs" }],
+ },
+ };
+ const bookmarkAction = {
+ type: at.PLACES_BOOKMARK_ADDED,
+ data: {
+ url: "https://foo.com",
+ bookmarkGuid: "bookmark123",
+ bookmarkTitle: "Title for bar.com",
+ dateAdded: 1234567,
+ },
+ };
+
+ const newState = DiscoveryStream(oldState, bookmarkAction);
+
+ assert.lengthOf(newState.spocs.data.spocs.items, 2);
+ assert.equal(
+ newState.spocs.data.spocs.items[0].bookmarkGuid,
+ bookmarkAction.data.bookmarkGuid
+ );
+ assert.equal(
+ newState.spocs.data.spocs.items[0].bookmarkTitle,
+ bookmarkAction.data.bookmarkTitle
+ );
+ assert.isUndefined(newState.spocs.data.spocs.items[1].bookmarkGuid);
+
+ assert.lengthOf(
+ newState.feeds.data["https://foo.com/feed1"].data.recommendations,
+ 2
+ );
+ assert.equal(
+ newState.feeds.data["https://foo.com/feed1"].data.recommendations[0]
+ .bookmarkGuid,
+ bookmarkAction.data.bookmarkGuid
+ );
+ assert.equal(
+ newState.feeds.data["https://foo.com/feed1"].data.recommendations[0]
+ .bookmarkTitle,
+ bookmarkAction.data.bookmarkTitle
+ );
+ assert.isUndefined(
+ newState.feeds.data["https://foo.com/feed1"].data.recommendations[1]
+ .bookmarkGuid
+ );
+ });
+
+ it("should remove boookmark details on PLACES_BOOKMARK_REMOVED in both feeds and spocs", () => {
+ const oldState = {
+ feeds: {
+ data: {
+ "https://foo.com/feed1": {
+ data: {
+ recommendations: [
+ {
+ url: "https://foo.com",
+ bookmarkGuid: "bookmark123",
+ bookmarkTitle: "Title for bar.com",
+ },
+ { url: "test.com" },
+ ],
+ },
+ },
+ },
+ loaded: true,
+ },
+ spocs: {
+ data: {
+ spocs: {
+ items: [
+ {
+ url: "https://foo.com",
+ bookmarkGuid: "bookmark123",
+ bookmarkTitle: "Title for bar.com",
+ },
+ { url: "test-spoc.com" },
+ ],
+ },
+ },
+ loaded: true,
+ placements: [{ name: "spocs" }],
+ },
+ };
+ const action = {
+ type: at.PLACES_BOOKMARK_REMOVED,
+ data: {
+ url: "https://foo.com",
+ },
+ };
+
+ const newState = DiscoveryStream(oldState, action);
+
+ assert.lengthOf(newState.spocs.data.spocs.items, 2);
+ assert.isUndefined(newState.spocs.data.spocs.items[0].bookmarkGuid);
+ assert.isUndefined(newState.spocs.data.spocs.items[0].bookmarkTitle);
+
+ assert.lengthOf(
+ newState.feeds.data["https://foo.com/feed1"].data.recommendations,
+ 2
+ );
+ assert.isUndefined(
+ newState.feeds.data["https://foo.com/feed1"].data.recommendations[0]
+ .bookmarkGuid
+ );
+ assert.isUndefined(
+ newState.feeds.data["https://foo.com/feed1"].data.recommendations[0]
+ .bookmarkTitle
+ );
+ });
+ describe("PREF_CHANGED", () => {
+ it("should set isCollectionDismissible", () => {
+ const state = DiscoveryStream(undefined, {
+ type: at.PREF_CHANGED,
+ data: {
+ name: "discoverystream.isCollectionDismissible",
+ value: true,
+ },
+ });
+ assert.equal(state.isCollectionDismissible, true);
+ });
+ });
+ });
+ describe("Search", () => {
+ it("should return INITIAL_STATE by default", () => {
+ assert.equal(
+ Search(undefined, { type: "some_action" }),
+ INITIAL_STATE.Search
+ );
+ });
+ it("should set hide to true on HIDE_SEARCH", () => {
+ const nextState = Search(undefined, { type: "HIDE_SEARCH" });
+ assert.propertyVal(nextState, "hide", true);
+ });
+ it("should set focus to true on FAKE_FOCUS_SEARCH", () => {
+ const nextState = Search(undefined, { type: "FAKE_FOCUS_SEARCH" });
+ assert.propertyVal(nextState, "fakeFocus", true);
+ });
+ it("should set focus and hide to false on SHOW_SEARCH", () => {
+ const nextState = Search(undefined, { type: "SHOW_SEARCH" });
+ assert.propertyVal(nextState, "fakeFocus", false);
+ assert.propertyVal(nextState, "hide", false);
+ });
+ });
+ it("should set initialized to true on AS_ROUTER_INITIALIZED", () => {
+ const nextState = ASRouter(undefined, { type: "AS_ROUTER_INITIALIZED" });
+ assert.propertyVal(nextState, "initialized", true);
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/components/ASRouterAdmin.test.jsx b/browser/components/newtab/test/unit/content-src/components/ASRouterAdmin.test.jsx
new file mode 100644
index 0000000000..1ec846ce5f
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/ASRouterAdmin.test.jsx
@@ -0,0 +1,610 @@
+import { actionCreators as ac, actionTypes as at } from "common/Actions.jsm";
+import {
+ ASRouterAdminInner,
+ CollapseToggle,
+ DiscoveryStreamAdmin,
+ Personalization,
+ ToggleStoryButton,
+} from "content-src/components/ASRouterAdmin/ASRouterAdmin";
+import { ASRouterUtils } from "content-src/asrouter/asrouter-utils";
+import { GlobalOverrider } from "test/unit/utils";
+import React from "react";
+import { shallow } from "enzyme";
+
+describe("ASRouterAdmin", () => {
+ let globalOverrider;
+ let sandbox;
+ let wrapper;
+ let globals;
+ let FAKE_PROVIDER_PREF = [
+ {
+ enabled: true,
+ id: "snippets_local_testing",
+ localProvider: "SnippetsProvider",
+ type: "local",
+ },
+ ];
+ let FAKE_PROVIDER = [
+ {
+ enabled: true,
+ id: "snippets_local_testing",
+ localProvider: "SnippetsProvider",
+ messages: [],
+ type: "local",
+ },
+ ];
+ beforeEach(() => {
+ globalOverrider = new GlobalOverrider();
+ sandbox = sinon.createSandbox();
+ sandbox.stub(ASRouterUtils, "getPreviewEndpoint").returns("foo");
+ globals = {
+ ASRouterMessage: sandbox.stub().resolves(),
+ ASRouterAddParentListener: sandbox.stub(),
+ ASRouterRemoveParentListener: sandbox.stub(),
+ };
+ globalOverrider.set(globals);
+ wrapper = shallow(
+ <ASRouterAdminInner collapsed={false} location={{ routes: [""] }} />
+ );
+ });
+ afterEach(() => {
+ sandbox.restore();
+ globalOverrider.restore();
+ });
+ it("should render ASRouterAdmin component", () => {
+ assert.ok(wrapper.exists());
+ });
+ it("should send ADMIN_CONNECT_STATE on mount", () => {
+ assert.calledOnce(globals.ASRouterMessage);
+ assert.calledWith(globals.ASRouterMessage, {
+ type: "ADMIN_CONNECT_STATE",
+ data: { endpoint: "foo" },
+ });
+ });
+ it("should set a .collapsed class on the outer div if props.collapsed is true", () => {
+ wrapper.setProps({ collapsed: true });
+ assert.isTrue(wrapper.find(".asrouter-admin").hasClass("collapsed"));
+ });
+ it("should set a .expanded class on the outer div if props.collapsed is false", () => {
+ wrapper.setProps({ collapsed: false });
+ assert.isTrue(wrapper.find(".asrouter-admin").hasClass("expanded"));
+ assert.isFalse(wrapper.find(".asrouter-admin").hasClass("collapsed"));
+ });
+ describe("#getSection", () => {
+ it("should render a message provider section by default", () => {
+ assert.equal(
+ wrapper
+ .find("h2")
+ .at(1)
+ .text(),
+ "Messages"
+ );
+ });
+ it("should render a targeting section for targeting route", () => {
+ wrapper = shallow(
+ <ASRouterAdminInner location={{ routes: ["targeting"] }} />
+ );
+ assert.equal(
+ wrapper
+ .find("h2")
+ .at(0)
+ .text(),
+ "Targeting Utilities"
+ );
+ });
+ it("should render a DS section for DS route", () => {
+ wrapper = shallow(
+ <ASRouterAdminInner
+ location={{ routes: ["ds"] }}
+ Sections={[]}
+ Prefs={{}}
+ />
+ );
+ assert.equal(
+ wrapper
+ .find("h2")
+ .at(0)
+ .text(),
+ "Discovery Stream"
+ );
+ });
+ it("should render two error messages", () => {
+ wrapper = shallow(
+ <ASRouterAdminInner location={{ routes: ["errors"] }} Sections={[]} />
+ );
+ const firstError = {
+ timestamp: Date.now() + 100,
+ error: { message: "first" },
+ };
+ const secondError = {
+ timestamp: Date.now(),
+ error: { message: "second" },
+ };
+ wrapper.setState({
+ providers: [{ id: "foo", errors: [firstError, secondError] }],
+ });
+
+ assert.equal(
+ wrapper
+ .find("tbody tr")
+ .at(0)
+ .find("td")
+ .at(0)
+ .text(),
+ "foo"
+ );
+ assert.lengthOf(wrapper.find("tbody tr"), 2);
+ assert.equal(
+ wrapper
+ .find("tbody tr")
+ .at(0)
+ .find("td")
+ .at(1)
+ .text(),
+ secondError.error.message
+ );
+ });
+ });
+ describe("#render", () => {
+ beforeEach(() => {
+ wrapper.setState({
+ providerPrefs: [],
+ providers: [],
+ userPrefs: {},
+ });
+ });
+ describe("#renderProviders", () => {
+ it("should render the provider", () => {
+ wrapper.setState({
+ providerPrefs: FAKE_PROVIDER_PREF,
+ providers: FAKE_PROVIDER,
+ });
+
+ // Header + 1 item
+ assert.lengthOf(wrapper.find(".message-item"), 2);
+ });
+ });
+ describe("#renderMessages", () => {
+ beforeEach(() => {
+ sandbox.stub(ASRouterUtils, "blockById").resolves();
+ sandbox.stub(ASRouterUtils, "unblockById").resolves();
+ sandbox.stub(ASRouterUtils, "overrideMessage").resolves({ foo: "bar" });
+ sandbox.stub(ASRouterUtils, "sendMessage").resolves();
+ wrapper.setState({
+ messageFilter: "all",
+ messageBlockList: [],
+ messageImpressions: { foo: 2 },
+ groups: [{ id: "messageProvider", enabled: true }],
+ providers: [{ id: "messageProvider", enabled: true }],
+ });
+ });
+ it("should render a message when no filtering is applied", () => {
+ wrapper.setState({
+ messages: [
+ {
+ id: "foo",
+ provider: "messageProvider",
+ groups: ["messageProvider"],
+ },
+ ],
+ });
+
+ assert.lengthOf(wrapper.find(".message-id"), 1);
+ wrapper.find(".message-item button.primary").simulate("click");
+ assert.calledOnce(ASRouterUtils.blockById);
+ assert.calledWith(ASRouterUtils.blockById, "foo");
+ });
+ it("should render a blocked message", () => {
+ wrapper.setState({
+ messages: [
+ {
+ id: "foo",
+ groups: ["messageProvider"],
+ provider: "messageProvider",
+ },
+ ],
+ messageBlockList: ["foo"],
+ });
+ assert.lengthOf(wrapper.find(".message-item.blocked"), 1);
+ wrapper.find(".message-item.blocked button").simulate("click");
+ assert.calledOnce(ASRouterUtils.unblockById);
+ assert.calledWith(ASRouterUtils.unblockById, "foo");
+ });
+ it("should render a message if provider matches filter", () => {
+ wrapper.setState({
+ messageFilter: "messageProvider",
+ messages: [
+ {
+ id: "foo",
+ provider: "messageProvider",
+ groups: ["messageProvider"],
+ },
+ ],
+ });
+
+ assert.lengthOf(wrapper.find(".message-id"), 1);
+ });
+ it("should override with the selected message", async () => {
+ wrapper.setState({
+ messageFilter: "messageProvider",
+ messages: [
+ {
+ id: "foo",
+ provider: "messageProvider",
+ groups: ["messageProvider"],
+ },
+ ],
+ });
+
+ assert.lengthOf(wrapper.find(".message-id"), 1);
+ wrapper.find(".message-item button.show").simulate("click");
+ assert.calledOnce(ASRouterUtils.overrideMessage);
+ assert.calledWith(ASRouterUtils.overrideMessage, "foo");
+ await ASRouterUtils.overrideMessage();
+ assert.equal(wrapper.state().foo, "bar");
+ });
+ it("should hide message if provider filter changes", () => {
+ wrapper.setState({
+ messageFilter: "messageProvider",
+ messages: [
+ {
+ id: "foo",
+ provider: "messageProvider",
+ groups: ["messageProvider"],
+ },
+ ],
+ });
+
+ assert.lengthOf(wrapper.find(".message-id"), 1);
+
+ wrapper.find("select").simulate("change", { target: { value: "bar" } });
+
+ assert.lengthOf(wrapper.find(".message-id"), 0);
+ });
+ it("should not display Reset All button if provider filter value is set to all or test providers", () => {
+ wrapper.setState({
+ messageFilter: "messageProvider",
+ messages: [
+ {
+ id: "foo",
+ provider: "messageProvider",
+ groups: ["messageProvider"],
+ },
+ ],
+ });
+
+ assert.lengthOf(wrapper.find(".messages-reset"), 1);
+ wrapper.find("select").simulate("change", { target: { value: "all" } });
+
+ assert.lengthOf(wrapper.find(".messages-reset"), 0);
+
+ wrapper
+ .find("select")
+ .simulate("change", { target: { value: "test_local_testing" } });
+ assert.lengthOf(wrapper.find(".messages-reset"), 0);
+ });
+ it("should trigger disable and enable provider on Reset All button click", () => {
+ wrapper.setState({
+ messageFilter: "messageProvider",
+ messages: [
+ {
+ id: "foo",
+ provider: "messageProvider",
+ groups: ["messageProvider"],
+ },
+ ],
+ providerPrefs: [
+ {
+ id: "messageProvider",
+ },
+ ],
+ });
+ wrapper.find(".messages-reset").simulate("click");
+ assert.calledTwice(ASRouterUtils.sendMessage);
+ assert.calledWith(ASRouterUtils.sendMessage, {
+ type: "DISABLE_PROVIDER",
+ data: "messageProvider",
+ });
+ assert.calledWith(ASRouterUtils.sendMessage, {
+ type: "ENABLE_PROVIDER",
+ data: "messageProvider",
+ });
+ });
+ });
+ });
+ describe("#DiscoveryStream", () => {
+ let state = {};
+ let dispatch;
+ beforeEach(() => {
+ dispatch = sandbox.stub();
+ state = {
+ config: {
+ enabled: true,
+ layout_endpoint: "",
+ },
+ layout: [],
+ spocs: {
+ frequency_caps: [],
+ },
+ feeds: {
+ data: {},
+ },
+ };
+ wrapper = shallow(
+ <DiscoveryStreamAdmin
+ dispatch={dispatch}
+ otherPrefs={{}}
+ state={{
+ DiscoveryStream: state,
+ }}
+ />
+ );
+ });
+ it("should render a DiscoveryStreamAdmin component", () => {
+ assert.equal(
+ wrapper
+ .find("h3")
+ .at(0)
+ .text(),
+ "Endpoint variant"
+ );
+ });
+ it("should render a spoc in DiscoveryStreamAdmin component", () => {
+ state.spocs = {
+ frequency_caps: [],
+ data: {
+ spocs: {
+ items: [
+ {
+ id: 12345,
+ },
+ ],
+ },
+ },
+ };
+ wrapper = shallow(
+ <DiscoveryStreamAdmin
+ otherPrefs={{}}
+ state={{ DiscoveryStream: state }}
+ />
+ );
+ wrapper.instance().onStoryToggle({ id: 12345 });
+ const messageSummary = wrapper.find(".message-summary").at(0);
+ const pre = messageSummary.find("pre").at(0);
+ const spocText = pre.text();
+ assert.equal(spocText, '{\n "id": 12345\n}');
+ });
+ it("should fire restorePrefDefaults with DISCOVERY_STREAM_CONFIG_RESET_DEFAULTS", () => {
+ wrapper
+ .find("button")
+ .at(0)
+ .simulate("click");
+ assert.calledWith(
+ dispatch,
+ ac.OnlyToMain({
+ type: at.DISCOVERY_STREAM_CONFIG_RESET_DEFAULTS,
+ })
+ );
+ });
+ it("should fire config change with DISCOVERY_STREAM_CONFIG_CHANGE", () => {
+ wrapper
+ .find("button")
+ .at(1)
+ .simulate("click");
+ assert.calledWith(
+ dispatch,
+ ac.OnlyToMain({
+ type: at.DISCOVERY_STREAM_CONFIG_CHANGE,
+ data: { enabled: true, layout_endpoint: "" },
+ })
+ );
+ });
+ it("should fire expireCache with DISCOVERY_STREAM_DEV_EXPIRE_CACHE", () => {
+ wrapper
+ .find("button")
+ .at(2)
+ .simulate("click");
+ assert.calledWith(
+ dispatch,
+ ac.OnlyToMain({
+ type: at.DISCOVERY_STREAM_DEV_EXPIRE_CACHE,
+ })
+ );
+ });
+ it("should fire systemTick with DISCOVERY_STREAM_DEV_SYSTEM_TICK", () => {
+ wrapper
+ .find("button")
+ .at(3)
+ .simulate("click");
+ assert.calledWith(
+ dispatch,
+ ac.OnlyToMain({
+ type: at.DISCOVERY_STREAM_DEV_SYSTEM_TICK,
+ })
+ );
+ });
+ it("should fire idleDaily with DISCOVERY_STREAM_DEV_IDLE_DAILY", () => {
+ wrapper
+ .find("button")
+ .at(4)
+ .simulate("click");
+ assert.calledWith(
+ dispatch,
+ ac.OnlyToMain({
+ type: at.DISCOVERY_STREAM_DEV_IDLE_DAILY,
+ })
+ );
+ });
+ it("should fire syncRemoteSettings with DISCOVERY_STREAM_DEV_SYNC_RS", () => {
+ wrapper
+ .find("button")
+ .at(5)
+ .simulate("click");
+ assert.calledWith(
+ dispatch,
+ ac.OnlyToMain({
+ type: at.DISCOVERY_STREAM_DEV_SYNC_RS,
+ })
+ );
+ });
+ it("should fire setConfigValue with DISCOVERY_STREAM_CONFIG_SET_VALUE", () => {
+ const name = "name";
+ const value = "value";
+ wrapper.instance().setConfigValue(name, value);
+ assert.calledWith(
+ dispatch,
+ ac.OnlyToMain({
+ type: at.DISCOVERY_STREAM_CONFIG_SET_VALUE,
+ data: { name, value },
+ })
+ );
+ });
+ });
+
+ describe("#Personalization", () => {
+ let dispatch;
+ beforeEach(() => {
+ dispatch = sandbox.stub();
+ wrapper = shallow(
+ <Personalization
+ dispatch={dispatch}
+ state={{
+ Personalization: {
+ version: 1,
+ lastUpdated: 1000,
+ initialized: true,
+ },
+ }}
+ />
+ );
+ });
+ it("should render with buttons, version, and lastUpdated", () => {
+ assert.equal(
+ wrapper
+ .find("button")
+ .at(0)
+ .text(),
+ "Enable V2 Personalization"
+ );
+ assert.equal(
+ wrapper
+ .find("td")
+ .at(1)
+ .text(),
+ "1"
+ );
+ assert.equal(
+ wrapper
+ .find("td")
+ .at(3)
+ .text(),
+ new Date(1000).toLocaleString()
+ );
+ });
+ it("should render with proper version 2 state", () => {
+ wrapper = shallow(
+ <Personalization
+ dispatch={dispatch}
+ state={{
+ Personalization: {
+ version: 2,
+ lastUpdated: 1000,
+ initialized: true,
+ },
+ }}
+ />
+ );
+ assert.equal(
+ wrapper
+ .find("button")
+ .at(0)
+ .text(),
+ "Enable V1 Personalization"
+ );
+ assert.equal(
+ wrapper
+ .find("td")
+ .at(1)
+ .text(),
+ "2"
+ );
+ });
+ it("should render with no data with no last updated", () => {
+ wrapper = shallow(
+ <Personalization
+ dispatch={dispatch}
+ state={{
+ Personalization: {
+ version: 2,
+ lastUpdated: 0,
+ initialized: true,
+ },
+ }}
+ />
+ );
+ assert.equal(
+ wrapper
+ .find("td")
+ .at(3)
+ .text(),
+ "(no data)"
+ );
+ });
+ it("should fire DISCOVERY_STREAM_PERSONALIZATION_VERSION_TOGGLE with version", () => {
+ wrapper
+ .find("button")
+ .at(0)
+ .simulate("click");
+ assert.calledWith(
+ dispatch,
+ ac.OnlyToMain({
+ type: at.DISCOVERY_STREAM_PERSONALIZATION_VERSION_TOGGLE,
+ })
+ );
+ });
+ });
+
+ describe("#ToggleStoryButton", () => {
+ it("should fire onClick in toggle button", async () => {
+ let result = "";
+ function onClick(spoc) {
+ result = spoc;
+ }
+
+ wrapper = shallow(<ToggleStoryButton story="spoc" onClick={onClick} />);
+ wrapper.find("button").simulate("click");
+
+ assert.equal(result, "spoc");
+ });
+ });
+});
+
+describe("CollapseToggle", () => {
+ let wrapper;
+ beforeEach(() => {
+ wrapper = shallow(<CollapseToggle location={{ routes: [""] }} />);
+ });
+
+ describe("rendering inner content", () => {
+ it("should not render ASRouterAdminInner for about:newtab (no hash)", () => {
+ wrapper.setProps({ location: { hash: "", routes: [""] } });
+ assert.lengthOf(wrapper.find(ASRouterAdminInner), 0);
+ });
+
+ it("should render ASRouterAdminInner for about:newtab#asrouter and subroutes", () => {
+ wrapper.setProps({ location: { hash: "#asrouter", routes: [""] } });
+ assert.lengthOf(wrapper.find(ASRouterAdminInner), 1);
+
+ wrapper.setProps({ location: { hash: "#asrouter-foo", routes: [""] } });
+ assert.lengthOf(wrapper.find(ASRouterAdminInner), 1);
+ });
+
+ it("should render ASRouterAdminInner for about:newtab#devtools and subroutes", () => {
+ wrapper.setProps({ location: { hash: "#devtools", routes: [""] } });
+ assert.lengthOf(wrapper.find(ASRouterAdminInner), 1);
+
+ wrapper.setProps({ location: { hash: "#devtools-foo", routes: [""] } });
+ assert.lengthOf(wrapper.find(ASRouterAdminInner), 1);
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/components/Base.test.jsx b/browser/components/newtab/test/unit/content-src/components/Base.test.jsx
new file mode 100644
index 0000000000..72eb3143e3
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/Base.test.jsx
@@ -0,0 +1,147 @@
+import {
+ _Base as Base,
+ BaseContent,
+ PrefsButton,
+} from "content-src/components/Base/Base";
+import { ASRouterAdmin } from "content-src/components/ASRouterAdmin/ASRouterAdmin";
+import { ErrorBoundary } from "content-src/components/ErrorBoundary/ErrorBoundary";
+import React from "react";
+import { Search } from "content-src/components/Search/Search";
+import { shallow } from "enzyme";
+import { actionCreators as ac } from "common/Actions.jsm";
+
+describe("<Base>", () => {
+ let DEFAULT_PROPS = {
+ store: { getState: () => {} },
+ App: { initialized: true },
+ Prefs: { values: {} },
+ Sections: [],
+ DiscoveryStream: { config: { enabled: false } },
+ dispatch: () => {},
+ adminContent: {
+ message: {},
+ },
+ };
+
+ it("should render Base component", () => {
+ const wrapper = shallow(<Base {...DEFAULT_PROPS} />);
+ assert.ok(wrapper.exists());
+ });
+
+ it("should render the BaseContent component, passing through all props", () => {
+ const wrapper = shallow(<Base {...DEFAULT_PROPS} />);
+ const props = wrapper.find(BaseContent).props();
+ assert.deepEqual(
+ props,
+ DEFAULT_PROPS,
+ JSON.stringify([props, DEFAULT_PROPS], null, 3)
+ );
+ });
+
+ it("should render an ErrorBoundary with class base-content-fallback", () => {
+ const wrapper = shallow(<Base {...DEFAULT_PROPS} />);
+
+ assert.equal(
+ wrapper
+ .find(ErrorBoundary)
+ .first()
+ .prop("className"),
+ "base-content-fallback"
+ );
+ });
+
+ it("should render an ASRouterAdmin if the devtools pref is true", () => {
+ const wrapper = shallow(
+ <Base
+ {...DEFAULT_PROPS}
+ Prefs={{ values: { "asrouter.devtoolsEnabled": true } }}
+ />
+ );
+ assert.lengthOf(wrapper.find(ASRouterAdmin), 1);
+ });
+
+ it("should not render an ASRouterAdmin if the devtools pref is false", () => {
+ const wrapper = shallow(
+ <Base
+ {...DEFAULT_PROPS}
+ Prefs={{ values: { "asrouter.devtoolsEnabled": false } }}
+ />
+ );
+ assert.lengthOf(wrapper.find(ASRouterAdmin), 0);
+ });
+});
+
+describe("<BaseContent>", () => {
+ let DEFAULT_PROPS = {
+ store: { getState: () => {} },
+ App: { initialized: true },
+ Prefs: { values: {} },
+ Sections: [],
+ DiscoveryStream: { config: { enabled: false } },
+ dispatch: () => {},
+ };
+
+ it("should render an ErrorBoundary with a Search child", () => {
+ const searchEnabledProps = Object.assign({}, DEFAULT_PROPS, {
+ Prefs: { values: { showSearch: true } },
+ });
+
+ const wrapper = shallow(<BaseContent {...searchEnabledProps} />);
+
+ assert.isTrue(
+ wrapper
+ .find(Search)
+ .parent()
+ .is(ErrorBoundary)
+ );
+ });
+
+ it("should render the PrefsButton component with featureConfig values", () => {
+ const wrapper = shallow(
+ <BaseContent
+ {...DEFAULT_PROPS}
+ Prefs={{ values: { featureConfig: { prefsButtonIcon: "icon-foo" } } }}
+ />
+ );
+ assert.lengthOf(wrapper.find(PrefsButton), 1);
+ assert.equal(wrapper.find(PrefsButton).prop("icon"), "icon-foo");
+ });
+
+ it("should dispatch a user event when the customize menu is opened or closed", () => {
+ const dispatch = sinon.stub();
+ const wrapper = shallow(
+ <BaseContent
+ {...DEFAULT_PROPS}
+ Prefs={{ values: { "newNewtabExperience.enabled": "true" } }}
+ dispatch={dispatch}
+ />
+ );
+ wrapper.instance().openCustomizationMenu();
+ assert.calledWith(dispatch, ac.UserEvent({ event: "SHOW_PERSONALIZE" }));
+ wrapper.instance().closeCustomizationMenu();
+ assert.calledWith(dispatch, ac.UserEvent({ event: "HIDE_PERSONALIZE" }));
+ });
+
+ it("should render only search if no Sections are enabled", () => {
+ const onlySearchProps = Object.assign({}, DEFAULT_PROPS, {
+ Sections: [{ id: "highlights", enabled: false }],
+ Prefs: { values: { showSearch: true } },
+ });
+
+ const wrapper = shallow(<BaseContent {...onlySearchProps} />);
+ assert.lengthOf(wrapper.find(".only-search"), 1);
+ });
+});
+
+describe("<PrefsButton>", () => {
+ it("should render icon-settings if props.icon is empty", () => {
+ const wrapper = shallow(<PrefsButton icon="" />);
+
+ assert.isTrue(wrapper.find("button").hasClass("icon-settings"));
+ });
+ it("should render props.icon as a className", () => {
+ const wrapper = shallow(<PrefsButton icon="icon-happy" />);
+
+ assert.isTrue(wrapper.find("button").hasClass("icon-happy"));
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/components/Card.test.jsx b/browser/components/newtab/test/unit/content-src/components/Card.test.jsx
new file mode 100644
index 0000000000..4f9072a3f9
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/Card.test.jsx
@@ -0,0 +1,507 @@
+import { actionCreators as ac, actionTypes as at } from "common/Actions.jsm";
+import {
+ _Card as Card,
+ PlaceholderCard,
+} from "content-src/components/Card/Card";
+import { combineReducers, createStore } from "redux";
+import { GlobalOverrider } from "test/unit/utils";
+import { INITIAL_STATE, reducers } from "common/Reducers.jsm";
+import { cardContextTypes } from "content-src/components/Card/types";
+import { ContextMenuButton } from "content-src/components/ContextMenu/ContextMenuButton";
+import { LinkMenu } from "content-src/components/LinkMenu/LinkMenu";
+import { Provider } from "react-redux";
+import React from "react";
+import { shallow, mount } from "enzyme";
+
+let DEFAULT_PROPS = {
+ dispatch: sinon.stub(),
+ index: 0,
+ link: {
+ hostname: "foo",
+ title: "A title for foo",
+ url: "http://www.foo.com",
+ type: "history",
+ description: "A description for foo",
+ image: "http://www.foo.com/img.png",
+ guid: 1,
+ },
+ eventSource: "TOP_STORIES",
+ shouldSendImpressionStats: true,
+ contextMenuOptions: ["Separator"],
+};
+
+let DEFAULT_BLOB_IMAGE = {
+ path: "/testpath",
+ data: new Blob([0]),
+};
+
+function mountCardWithProps(props) {
+ const store = createStore(combineReducers(reducers), INITIAL_STATE);
+ return mount(
+ <Provider store={store}>
+ <Card {...props} />
+ </Provider>
+ );
+}
+
+describe("<Card>", () => {
+ let globals;
+ let wrapper;
+ beforeEach(() => {
+ globals = new GlobalOverrider();
+ wrapper = mountCardWithProps(DEFAULT_PROPS);
+ });
+ afterEach(() => {
+ DEFAULT_PROPS.dispatch.reset();
+ globals.restore();
+ });
+ it("should render a Card component", () => assert.ok(wrapper.exists()));
+ it("should add the right url", () => {
+ assert.propertyVal(
+ wrapper.find("a").props(),
+ "href",
+ DEFAULT_PROPS.link.url
+ );
+
+ // test that pocket cards get a special open_url href
+ const pocketLink = Object.assign({}, DEFAULT_PROPS.link, {
+ open_url: "getpocket.com/foo",
+ type: "pocket",
+ });
+ wrapper = mount(
+ <Card {...Object.assign({}, DEFAULT_PROPS, { link: pocketLink })} />
+ );
+ assert.propertyVal(wrapper.find("a").props(), "href", pocketLink.open_url);
+ });
+ it("should display a title", () =>
+ assert.equal(wrapper.find(".card-title").text(), DEFAULT_PROPS.link.title));
+ it("should display a description", () =>
+ assert.equal(
+ wrapper.find(".card-description").text(),
+ DEFAULT_PROPS.link.description
+ ));
+ it("should display a host name", () =>
+ assert.equal(wrapper.find(".card-host-name").text(), "foo"));
+ it("should have a link menu button", () =>
+ assert.ok(wrapper.find(".context-menu-button").exists()));
+ it("should render a link menu when button is clicked", () => {
+ const button = wrapper.find(".context-menu-button");
+ assert.equal(wrapper.find(LinkMenu).length, 0);
+ button.simulate("click", { preventDefault: () => {} });
+ assert.equal(wrapper.find(LinkMenu).length, 1);
+ });
+ it("should pass dispatch, source, onUpdate, site, options, and index to LinkMenu", () => {
+ wrapper
+ .find(".context-menu-button")
+ .simulate("click", { preventDefault: () => {} });
+ const { dispatch, source, onUpdate, site, options, index } = wrapper
+ .find(LinkMenu)
+ .props();
+ assert.equal(dispatch, DEFAULT_PROPS.dispatch);
+ assert.equal(source, DEFAULT_PROPS.eventSource);
+ assert.ok(onUpdate);
+ assert.equal(site, DEFAULT_PROPS.link);
+ assert.equal(options, DEFAULT_PROPS.contextMenuOptions);
+ assert.equal(index, DEFAULT_PROPS.index);
+ });
+ it("should pass through the correct menu options to LinkMenu if overridden by individual card", () => {
+ const link = Object.assign({}, DEFAULT_PROPS.link);
+ link.contextMenuOptions = ["CheckBookmark"];
+
+ wrapper = mountCardWithProps(Object.assign({}, DEFAULT_PROPS, { link }));
+ wrapper
+ .find(".context-menu-button")
+ .simulate("click", { preventDefault: () => {} });
+ const { options } = wrapper.find(LinkMenu).props();
+ assert.equal(options, link.contextMenuOptions);
+ });
+ it("should have a context based on type", () => {
+ wrapper = shallow(<Card {...DEFAULT_PROPS} />);
+ const context = wrapper.find(".card-context");
+ const { icon, fluentID } = cardContextTypes[DEFAULT_PROPS.link.type];
+ assert.isTrue(context.childAt(0).hasClass(`icon-${icon}`));
+ assert.isTrue(context.childAt(1).hasClass("card-context-label"));
+ assert.equal(context.childAt(1).prop("data-l10n-id"), fluentID);
+ });
+ it("should support setting custom context", () => {
+ const linkWithCustomContext = {
+ type: "history",
+ context: "Custom",
+ icon: "icon-url",
+ };
+
+ wrapper = shallow(
+ <Card
+ {...Object.assign({}, DEFAULT_PROPS, { link: linkWithCustomContext })}
+ />
+ );
+ const context = wrapper.find(".card-context");
+ const { icon } = cardContextTypes[DEFAULT_PROPS.link.type];
+ assert.isFalse(context.childAt(0).hasClass(`icon-${icon}`));
+ assert.equal(
+ context.childAt(0).props().style.backgroundImage,
+ "url('icon-url')"
+ );
+
+ assert.isTrue(context.childAt(1).hasClass("card-context-label"));
+ assert.equal(context.childAt(1).text(), linkWithCustomContext.context);
+ });
+ it("should parse args for fluent correctly", () => {
+ const title = '"fluent"';
+ const link = { ...DEFAULT_PROPS.link, title };
+
+ wrapper = mountCardWithProps({ ...DEFAULT_PROPS, link });
+ let button = wrapper.find(ContextMenuButton).find("button");
+
+ assert.equal(button.prop("data-l10n-args"), JSON.stringify({ title }));
+ });
+ it("should have .active class, on card-outer if context menu is open", () => {
+ const button = wrapper.find(ContextMenuButton);
+ assert.isFalse(
+ wrapper.find(".card-outer").hasClass("active"),
+ "does not have active class"
+ );
+ button.simulate("click", { preventDefault: () => {} });
+ assert.isTrue(
+ wrapper.find(".card-outer").hasClass("active"),
+ "has active class"
+ );
+ });
+ it("should send OPEN_DOWNLOAD_FILE if we clicked on a download", () => {
+ const downloadLink = {
+ type: "download",
+ url: "download.mov",
+ };
+ wrapper = mountCardWithProps(
+ Object.assign({}, DEFAULT_PROPS, { link: downloadLink })
+ );
+ const card = wrapper.find(".card");
+ card.simulate("click", { preventDefault: () => {} });
+ assert.calledThrice(DEFAULT_PROPS.dispatch);
+
+ assert.equal(
+ DEFAULT_PROPS.dispatch.firstCall.args[0].type,
+ at.OPEN_DOWNLOAD_FILE
+ );
+ assert.deepEqual(
+ DEFAULT_PROPS.dispatch.firstCall.args[0].data,
+ downloadLink
+ );
+ });
+ it("should send OPEN_LINK if we clicked on anything other than a download", () => {
+ const nonDownloadLink = {
+ type: "history",
+ url: "download.mov",
+ };
+ wrapper = mountCardWithProps(
+ Object.assign({}, DEFAULT_PROPS, { link: nonDownloadLink })
+ );
+ const card = wrapper.find(".card");
+ const event = {
+ altKey: "1",
+ button: "2",
+ ctrlKey: "3",
+ metaKey: "4",
+ shiftKey: "5",
+ };
+ card.simulate(
+ "click",
+ Object.assign({}, event, { preventDefault: () => {} })
+ );
+ assert.calledThrice(DEFAULT_PROPS.dispatch);
+
+ assert.equal(DEFAULT_PROPS.dispatch.firstCall.args[0].type, at.OPEN_LINK);
+ });
+ describe("card image display", () => {
+ const DEFAULT_BLOB_URL = "blob://test";
+ let url;
+ beforeEach(() => {
+ url = {
+ createObjectURL: globals.sandbox.stub().returns(DEFAULT_BLOB_URL),
+ revokeObjectURL: globals.sandbox.spy(),
+ };
+ globals.set("URL", url);
+ });
+ afterEach(() => {
+ globals.restore();
+ });
+ it("should display a regular image correctly and not call revokeObjectURL when unmounted", () => {
+ wrapper = shallow(<Card {...DEFAULT_PROPS} />);
+
+ assert.isUndefined(wrapper.state("cardImage").path);
+ assert.equal(wrapper.state("cardImage").url, DEFAULT_PROPS.link.image);
+ assert.equal(
+ wrapper.find(".card-preview-image").props().style.backgroundImage,
+ `url(${wrapper.state("cardImage").url})`
+ );
+
+ wrapper.unmount();
+ assert.notCalled(url.revokeObjectURL);
+ });
+ it("should display a blob image correctly and revoke blob url when unmounted", () => {
+ const link = Object.assign({}, DEFAULT_PROPS.link, {
+ image: DEFAULT_BLOB_IMAGE,
+ });
+ wrapper = shallow(<Card {...DEFAULT_PROPS} link={link} />);
+
+ assert.equal(wrapper.state("cardImage").path, DEFAULT_BLOB_IMAGE.path);
+ assert.equal(wrapper.state("cardImage").url, DEFAULT_BLOB_URL);
+ assert.equal(
+ wrapper.find(".card-preview-image").props().style.backgroundImage,
+ `url(${wrapper.state("cardImage").url})`
+ );
+
+ wrapper.unmount();
+ assert.calledOnce(url.revokeObjectURL);
+ });
+ it("should not show an image if there isn't one and not call revokeObjectURL when unmounted", () => {
+ const link = Object.assign({}, DEFAULT_PROPS.link);
+ delete link.image;
+
+ wrapper = shallow(<Card {...DEFAULT_PROPS} link={link} />);
+
+ assert.isNull(wrapper.state("cardImage"));
+ assert.lengthOf(wrapper.find(".card-preview-image"), 0);
+
+ wrapper.unmount();
+ assert.notCalled(url.revokeObjectURL);
+ });
+ it("should remove current card image if new image is not present", () => {
+ wrapper = shallow(<Card {...DEFAULT_PROPS} />);
+
+ const otherLink = Object.assign({}, DEFAULT_PROPS.link);
+ delete otherLink.image;
+ wrapper.setProps(Object.assign({}, DEFAULT_PROPS, { link: otherLink }));
+
+ assert.isNull(wrapper.state("cardImage"));
+ });
+ it("should not create or revoke urls if normal image is already in state", () => {
+ wrapper = shallow(<Card {...DEFAULT_PROPS} />);
+
+ wrapper.setProps(DEFAULT_PROPS);
+
+ assert.notCalled(url.createObjectURL);
+ assert.notCalled(url.revokeObjectURL);
+ });
+ it("should not create or revoke more urls if blob image is already in state", () => {
+ const link = Object.assign({}, DEFAULT_PROPS.link, {
+ image: DEFAULT_BLOB_IMAGE,
+ });
+ wrapper = shallow(<Card {...DEFAULT_PROPS} link={link} />);
+
+ assert.calledOnce(url.createObjectURL);
+ assert.notCalled(url.revokeObjectURL);
+
+ wrapper.setProps(Object.assign({}, DEFAULT_PROPS, { link }));
+
+ assert.calledOnce(url.createObjectURL);
+ assert.notCalled(url.revokeObjectURL);
+ });
+ it("should create blob urls for new blobs and revoke existing ones", () => {
+ const link = Object.assign({}, DEFAULT_PROPS.link, {
+ image: DEFAULT_BLOB_IMAGE,
+ });
+ wrapper = shallow(<Card {...DEFAULT_PROPS} link={link} />);
+
+ assert.calledOnce(url.createObjectURL);
+ assert.notCalled(url.revokeObjectURL);
+
+ const otherLink = Object.assign({}, DEFAULT_PROPS.link, {
+ image: { path: "/newpath", data: new Blob([0]) },
+ });
+ wrapper.setProps(Object.assign({}, DEFAULT_PROPS, { link: otherLink }));
+
+ assert.calledTwice(url.createObjectURL);
+ assert.calledOnce(url.revokeObjectURL);
+ });
+ it("should not call createObjectURL and revokeObjectURL for normal images", () => {
+ wrapper = shallow(<Card {...DEFAULT_PROPS} />);
+
+ assert.notCalled(url.createObjectURL);
+ assert.notCalled(url.revokeObjectURL);
+
+ const otherLink = Object.assign({}, DEFAULT_PROPS.link, {
+ image: "https://other/image",
+ });
+ wrapper.setProps(Object.assign({}, DEFAULT_PROPS, { link: otherLink }));
+
+ assert.notCalled(url.createObjectURL);
+ assert.notCalled(url.revokeObjectURL);
+ });
+ });
+ describe("image loading", () => {
+ let link;
+ let triggerImage = {};
+ let uniqueLink = 0;
+ beforeEach(() => {
+ global.Image.prototype = {
+ addEventListener(event, callback) {
+ triggerImage[event] = () => Promise.resolve(callback());
+ },
+ };
+
+ link = Object.assign({}, DEFAULT_PROPS.link);
+ link.image += uniqueLink++;
+ wrapper = shallow(<Card {...DEFAULT_PROPS} link={link} />);
+ });
+ it("should have a loaded preview image when the image is loaded", () => {
+ assert.isFalse(wrapper.find(".card-preview-image").hasClass("loaded"));
+
+ wrapper.setState({ imageLoaded: true });
+
+ assert.isTrue(wrapper.find(".card-preview-image").hasClass("loaded"));
+ });
+ it("should start not loaded", () => {
+ assert.isFalse(wrapper.state("imageLoaded"));
+ });
+ it("should be loaded after load", async () => {
+ await triggerImage.load();
+
+ assert.isTrue(wrapper.state("imageLoaded"));
+ });
+ it("should be not be loaded after error ", async () => {
+ await triggerImage.error();
+
+ assert.isFalse(wrapper.state("imageLoaded"));
+ });
+ it("should be not be loaded if image changes", async () => {
+ await triggerImage.load();
+ const otherLink = Object.assign({}, link, {
+ image: "https://other/image",
+ });
+
+ wrapper.setProps(Object.assign({}, DEFAULT_PROPS, { link: otherLink }));
+
+ assert.isFalse(wrapper.state("imageLoaded"));
+ });
+ });
+ describe("placeholder=true", () => {
+ beforeEach(() => {
+ wrapper = mount(<Card placeholder={true} />);
+ });
+ it("should render when placeholder=true", () => {
+ assert.ok(wrapper.exists());
+ });
+ it("should add a placeholder class to the outer element", () => {
+ assert.isTrue(wrapper.find(".card-outer").hasClass("placeholder"));
+ });
+ it("should not have a context menu button or LinkMenu", () => {
+ assert.isFalse(
+ wrapper.find(ContextMenuButton).exists(),
+ "context menu button"
+ );
+ assert.isFalse(wrapper.find(LinkMenu).exists(), "LinkMenu");
+ });
+ it("should not call onLinkClick when the link is clicked", () => {
+ const spy = sinon.spy(wrapper.instance(), "onLinkClick");
+ const card = wrapper.find(".card");
+ card.simulate("click");
+ assert.notCalled(spy);
+ });
+ });
+ describe("#trackClick", () => {
+ it("should call dispatch when the link is clicked with the right data", () => {
+ const card = wrapper.find(".card");
+ const event = {
+ altKey: "1",
+ button: "2",
+ ctrlKey: "3",
+ metaKey: "4",
+ shiftKey: "5",
+ };
+ card.simulate(
+ "click",
+ Object.assign({}, event, { preventDefault: () => {} })
+ );
+ assert.calledThrice(DEFAULT_PROPS.dispatch);
+
+ // first dispatch call is the AlsoToMain message which will open a link in a window, and send some event data
+ assert.equal(DEFAULT_PROPS.dispatch.firstCall.args[0].type, at.OPEN_LINK);
+ assert.deepEqual(
+ DEFAULT_PROPS.dispatch.firstCall.args[0].data.event,
+ event
+ );
+
+ // second dispatch call is a UserEvent action for telemetry
+ assert.isUserEventAction(DEFAULT_PROPS.dispatch.secondCall.args[0]);
+ assert.calledWith(
+ DEFAULT_PROPS.dispatch.secondCall,
+ ac.UserEvent({
+ event: "CLICK",
+ source: DEFAULT_PROPS.eventSource,
+ action_position: DEFAULT_PROPS.index,
+ })
+ );
+
+ // third dispatch call is to send impression stats
+ assert.calledWith(
+ DEFAULT_PROPS.dispatch.thirdCall,
+ ac.ImpressionStats({
+ source: DEFAULT_PROPS.eventSource,
+ click: 0,
+ tiles: [{ id: DEFAULT_PROPS.link.guid, pos: DEFAULT_PROPS.index }],
+ })
+ );
+ });
+ it("should provide card_type to telemetry info if type is not history", () => {
+ const link = Object.assign({}, DEFAULT_PROPS.link);
+ link.type = "bookmark";
+ wrapper = mount(<Card {...Object.assign({}, DEFAULT_PROPS, { link })} />);
+ const card = wrapper.find(".card");
+ const event = {
+ altKey: "1",
+ button: "2",
+ ctrlKey: "3",
+ metaKey: "4",
+ shiftKey: "5",
+ };
+
+ card.simulate(
+ "click",
+ Object.assign({}, event, { preventDefault: () => {} })
+ );
+
+ assert.isUserEventAction(DEFAULT_PROPS.dispatch.secondCall.args[0]);
+ assert.calledWith(
+ DEFAULT_PROPS.dispatch.secondCall,
+ ac.UserEvent({
+ event: "CLICK",
+ source: DEFAULT_PROPS.eventSource,
+ action_position: DEFAULT_PROPS.index,
+ value: { card_type: link.type },
+ })
+ );
+ });
+ it("should notify Web Extensions with WEBEXT_CLICK if props.isWebExtension is true", () => {
+ wrapper = mountCardWithProps(
+ Object.assign({}, DEFAULT_PROPS, {
+ isWebExtension: true,
+ eventSource: "MyExtension",
+ index: 3,
+ })
+ );
+ const card = wrapper.find(".card");
+ const event = { preventDefault() {} };
+ card.simulate("click", event);
+ assert.calledWith(
+ DEFAULT_PROPS.dispatch,
+ ac.WebExtEvent(at.WEBEXT_CLICK, {
+ source: "MyExtension",
+ url: DEFAULT_PROPS.link.url,
+ action_position: 3,
+ })
+ );
+ });
+ });
+});
+
+describe("<PlaceholderCard />", () => {
+ it("should render a Card with placeholder=true", () => {
+ const wrapper = mount(
+ <Provider store={createStore(combineReducers(reducers), INITIAL_STATE)}>
+ <PlaceholderCard />
+ </Provider>
+ );
+ assert.isTrue(wrapper.find(Card).props().placeholder);
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/components/CollapsibleSection.test.jsx b/browser/components/newtab/test/unit/content-src/components/CollapsibleSection.test.jsx
new file mode 100644
index 0000000000..2824280721
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/CollapsibleSection.test.jsx
@@ -0,0 +1,224 @@
+import { actionTypes as at } from "common/Actions.jsm";
+import { _CollapsibleSection as CollapsibleSection } from "content-src/components/CollapsibleSection/CollapsibleSection";
+import { ErrorBoundary } from "content-src/components/ErrorBoundary/ErrorBoundary";
+import { mount } from "enzyme";
+import React from "react";
+
+const DEFAULT_PROPS = {
+ id: "cool",
+ className: "cool-section",
+ title: "Cool Section",
+ prefName: "collapseSection",
+ collapsed: false,
+ eventSource: "foo",
+ document: {
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ visibilityState: "visible",
+ },
+ dispatch: () => {},
+ Prefs: { values: {} },
+};
+
+describe("CollapsibleSection", () => {
+ let wrapper;
+
+ function setup(props = {}) {
+ const customProps = Object.assign({}, DEFAULT_PROPS, props);
+ wrapper = mount(
+ <CollapsibleSection {...customProps}>foo</CollapsibleSection>
+ );
+ }
+
+ beforeEach(() => setup());
+
+ it("should render the component", () => {
+ assert.ok(wrapper.exists());
+ });
+
+ it("should render an ErrorBoundary with class section-body-fallback", () => {
+ assert.equal(
+ wrapper
+ .find(ErrorBoundary)
+ .first()
+ .prop("className"),
+ "section-body-fallback"
+ );
+ });
+
+ it("should have collapsed class if 'prefName' pref is true", () => {
+ setup({ collapsed: true });
+ assert.ok(
+ wrapper
+ .find(".collapsible-section")
+ .first()
+ .hasClass("collapsed")
+ );
+ });
+
+ it("should fire a MENU_COLLAPSE user event when section title is clicked", done => {
+ function dispatch(a) {
+ if (a.type === "TELEMETRY_USER_EVENT") {
+ assert.equal(a.data.event, "MENU_COLLAPSE");
+ assert.equal(a.data.source, "foo");
+ done();
+ }
+ }
+
+ setup({ dispatch });
+ wrapper
+ .find(".click-target")
+ .at(0)
+ .simulate("click");
+ });
+
+ it("should fire a MENU_EXPAND user event when section title is collapsed", done => {
+ function dispatch(a) {
+ if (a.type === "TELEMETRY_USER_EVENT") {
+ assert.equal(a.data.event, "MENU_EXPAND");
+ assert.equal(a.data.source, "foo");
+ done();
+ }
+ }
+
+ setup({ dispatch, collapsed: true });
+ wrapper
+ .find(".click-target")
+ .at(0)
+ .simulate("click");
+ });
+
+ it("should fire a pref change event when section title is clicked", done => {
+ function dispatch(a) {
+ if (a.type === at.UPDATE_SECTION_PREFS) {
+ assert.equal(a.data.id, DEFAULT_PROPS.id);
+ assert.equal(a.data.value.collapsed, true);
+ done();
+ }
+ }
+ setup({ dispatch });
+ wrapper
+ .find(".click-target")
+ .at(0)
+ .simulate("click");
+ });
+
+ it("should not fire a pref change when section title is clicked if sectionBody is falsy", () => {
+ const dispatch = sinon.spy();
+ setup({ dispatch });
+ delete wrapper.find(CollapsibleSection).instance().sectionBody;
+
+ wrapper
+ .find(".click-target")
+ .at(0)
+ .simulate("click");
+
+ assert.notCalled(dispatch);
+ });
+
+ it("should enable animations if the tab is visible", () => {
+ wrapper.instance().enableOrDisableAnimation();
+ assert.ok(wrapper.instance().state.enableAnimation);
+ });
+
+ it("should disable animations if the tab is in the background", () => {
+ const doc = Object.assign({}, DEFAULT_PROPS.document, {
+ visibilityState: "hidden",
+ });
+ setup({ document: doc });
+ wrapper.instance().enableOrDisableAnimation();
+ assert.isFalse(wrapper.instance().state.enableAnimation);
+ });
+
+ describe("without collapsible pref", () => {
+ let dispatch;
+ beforeEach(() => {
+ dispatch = sinon.stub();
+ setup({ collapsed: undefined, dispatch });
+ });
+ it("should render the section uncollapsed", () => {
+ assert.isFalse(
+ wrapper
+ .find(".collapsible-section")
+ .first()
+ .hasClass("collapsed")
+ );
+ });
+
+ it("should not render the arrow if no collapsible pref exists for the section", () => {
+ assert.lengthOf(wrapper.find(".click-target .collapsible-arrow"), 0);
+ });
+
+ it("should not trigger a dispatch when the section title is clicked ", () => {
+ wrapper
+ .find(".click-target")
+ .at(0)
+ .simulate("click");
+
+ assert.notCalled(dispatch);
+ });
+ });
+
+ describe("icon", () => {
+ it("should use the icon prop value as the url if it starts with `moz-extension://`", () => {
+ const icon = "moz-extension://some/extension/path";
+ setup({ icon });
+ const props = wrapper
+ .find(".icon")
+ .first()
+ .props();
+ assert.equal(props.style.backgroundImage, `url('${icon}')`);
+ });
+ it("should use set the icon-* class if a string that doesn't start with `moz-extension://` is provided", () => {
+ setup({ icon: "cool" });
+ assert.ok(
+ wrapper
+ .find(".icon")
+ .first()
+ .hasClass("icon-cool")
+ );
+ });
+ it("should use the icon `webextension` if no other is provided", () => {
+ setup({ icon: undefined });
+ assert.ok(
+ wrapper
+ .find(".icon")
+ .first()
+ .hasClass("icon-webextension")
+ );
+ });
+ });
+
+ describe("maxHeight", () => {
+ const maxHeight = "123px";
+ const setState = state =>
+ wrapper.setState(Object.assign({ maxHeight }, state || {}));
+ const checkHeight = val =>
+ assert.equal(
+ wrapper.find(".section-body").instance().style.maxHeight,
+ val
+ );
+
+ it("should have no max-height normally to avoid unexpected cropping", () => {
+ setState();
+
+ checkHeight("");
+ });
+ it("should have a max-height when animating open to a target height", () => {
+ setState({ isAnimating: true });
+
+ checkHeight(maxHeight);
+ });
+ it("should not have a max-height when already collapsed", () => {
+ setup({ collapsed: true });
+
+ checkHeight("");
+ });
+ it("should not have a max-height when animating closed to a css-set 0", () => {
+ setup({ collapsed: true });
+ setState({ isAnimating: true });
+
+ checkHeight("");
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/components/ComponentPerfTimer.test.jsx b/browser/components/newtab/test/unit/content-src/components/ComponentPerfTimer.test.jsx
new file mode 100644
index 0000000000..763c08c684
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/ComponentPerfTimer.test.jsx
@@ -0,0 +1,444 @@
+import { actionCreators as ac, actionTypes as at } from "common/Actions.jsm";
+import { ComponentPerfTimer } from "content-src/components/ComponentPerfTimer/ComponentPerfTimer";
+import createMockRaf from "mock-raf";
+import React from "react";
+
+import { shallow } from "enzyme";
+
+const perfSvc = {
+ mark() {},
+ getMostRecentAbsMarkStartByName() {},
+};
+
+let DEFAULT_PROPS = {
+ initialized: true,
+ rows: [],
+ id: "highlights",
+ dispatch() {},
+ perfSvc,
+};
+
+describe("<ComponentPerfTimer>", () => {
+ let mockRaf;
+ let sandbox;
+ let wrapper;
+
+ const InnerEl = () => <div>Inner Element</div>;
+
+ beforeEach(() => {
+ mockRaf = createMockRaf();
+ sandbox = sinon.createSandbox();
+ sandbox.stub(window, "requestAnimationFrame").callsFake(mockRaf.raf);
+ wrapper = shallow(
+ <ComponentPerfTimer {...DEFAULT_PROPS}>
+ <InnerEl />
+ </ComponentPerfTimer>
+ );
+ });
+ afterEach(() => {
+ sandbox.restore();
+ });
+
+ it("should render props.children", () => {
+ assert.ok(wrapper.contains(<InnerEl />));
+ });
+
+ describe("#constructor", () => {
+ beforeEach(() => {
+ sandbox.stub(ComponentPerfTimer.prototype, "_maybeSendBadStateEvent");
+ sandbox.stub(
+ ComponentPerfTimer.prototype,
+ "_ensureFirstRenderTsRecorded"
+ );
+ wrapper = shallow(
+ <ComponentPerfTimer {...DEFAULT_PROPS}>
+ <InnerEl />
+ </ComponentPerfTimer>,
+ { disableLifecycleMethods: true }
+ );
+ });
+
+ it("should have the correct defaults", () => {
+ const instance = wrapper.instance();
+
+ assert.isFalse(instance._reportMissingData);
+ assert.isFalse(instance._timestampHandled);
+ assert.isFalse(instance._recordedFirstRender);
+ });
+ });
+
+ describe("#render", () => {
+ beforeEach(() => {
+ sandbox.stub(DEFAULT_PROPS, "id").value("fake_section");
+ sandbox.stub(ComponentPerfTimer.prototype, "_maybeSendBadStateEvent");
+ sandbox.stub(
+ ComponentPerfTimer.prototype,
+ "_ensureFirstRenderTsRecorded"
+ );
+ wrapper = shallow(
+ <ComponentPerfTimer {...DEFAULT_PROPS}>
+ <InnerEl />
+ </ComponentPerfTimer>
+ );
+ });
+
+ it("should not call telemetry on sections that we don't want to record", () => {
+ const instance = wrapper.instance();
+
+ assert.notCalled(instance._maybeSendBadStateEvent);
+ assert.notCalled(instance._ensureFirstRenderTsRecorded);
+ });
+ });
+
+ describe("#_componentDidMount", () => {
+ it("should call _maybeSendPaintedEvent", () => {
+ const instance = wrapper.instance();
+ const stub = sandbox.stub(instance, "_maybeSendPaintedEvent");
+
+ instance.componentDidMount();
+
+ assert.calledOnce(stub);
+ });
+
+ it("should not call _maybeSendPaintedEvent if id not in RECORDED_SECTIONS", () => {
+ sandbox.stub(DEFAULT_PROPS, "id").value("topstories");
+ wrapper = shallow(
+ <ComponentPerfTimer {...DEFAULT_PROPS}>
+ <InnerEl />
+ </ComponentPerfTimer>
+ );
+ const instance = wrapper.instance();
+ const stub = sandbox.stub(instance, "_maybeSendPaintedEvent");
+
+ instance.componentDidMount();
+
+ assert.notCalled(stub);
+ });
+ });
+
+ describe("#_componentDidUpdate", () => {
+ it("should call _maybeSendPaintedEvent", () => {
+ const instance = wrapper.instance();
+ const maybeSendPaintStub = sandbox.stub(
+ instance,
+ "_maybeSendPaintedEvent"
+ );
+
+ instance.componentDidUpdate();
+
+ assert.calledOnce(maybeSendPaintStub);
+ });
+
+ it("should not call _maybeSendPaintedEvent if id not in RECORDED_SECTIONS", () => {
+ sandbox.stub(DEFAULT_PROPS, "id").value("topstories");
+ wrapper = shallow(
+ <ComponentPerfTimer {...DEFAULT_PROPS}>
+ <InnerEl />
+ </ComponentPerfTimer>
+ );
+ const instance = wrapper.instance();
+ const stub = sandbox.stub(instance, "_maybeSendPaintedEvent");
+
+ instance.componentDidUpdate();
+
+ assert.notCalled(stub);
+ });
+ });
+
+ describe("_ensureFirstRenderTsRecorded", () => {
+ let recordFirstRenderStub;
+ beforeEach(() => {
+ sandbox.stub(ComponentPerfTimer.prototype, "_maybeSendBadStateEvent");
+ recordFirstRenderStub = sandbox.stub(
+ ComponentPerfTimer.prototype,
+ "_ensureFirstRenderTsRecorded"
+ );
+ });
+
+ it("should set _recordedFirstRender", () => {
+ sandbox.stub(DEFAULT_PROPS, "initialized").value(false);
+ wrapper = shallow(
+ <ComponentPerfTimer {...DEFAULT_PROPS}>
+ <InnerEl />
+ </ComponentPerfTimer>
+ );
+ const instance = wrapper.instance();
+
+ assert.isFalse(instance._recordedFirstRender);
+
+ recordFirstRenderStub.callThrough();
+ instance._ensureFirstRenderTsRecorded();
+
+ assert.isTrue(instance._recordedFirstRender);
+ });
+
+ it("should mark first_render_ts", () => {
+ sandbox.stub(DEFAULT_PROPS, "initialized").value(false);
+ wrapper = shallow(
+ <ComponentPerfTimer {...DEFAULT_PROPS}>
+ <InnerEl />
+ </ComponentPerfTimer>
+ );
+ const instance = wrapper.instance();
+ const stub = sandbox.stub(perfSvc, "mark");
+
+ recordFirstRenderStub.callThrough();
+ instance._ensureFirstRenderTsRecorded();
+
+ assert.calledOnce(stub);
+ assert.calledWithExactly(stub, `${DEFAULT_PROPS.id}_first_render_ts`);
+ });
+ });
+
+ describe("#_maybeSendBadStateEvent", () => {
+ let sendBadStateStub;
+ beforeEach(() => {
+ sendBadStateStub = sandbox.stub(
+ ComponentPerfTimer.prototype,
+ "_maybeSendBadStateEvent"
+ );
+ sandbox.stub(
+ ComponentPerfTimer.prototype,
+ "_ensureFirstRenderTsRecorded"
+ );
+ });
+
+ it("should set this._reportMissingData=true when called with initialized === false", () => {
+ sandbox.stub(DEFAULT_PROPS, "initialized").value(false);
+ wrapper = shallow(
+ <ComponentPerfTimer {...DEFAULT_PROPS}>
+ <InnerEl />
+ </ComponentPerfTimer>
+ );
+ const instance = wrapper.instance();
+
+ assert.isFalse(instance._reportMissingData);
+
+ sendBadStateStub.callThrough();
+ instance._maybeSendBadStateEvent();
+
+ assert.isTrue(instance._reportMissingData);
+ });
+
+ it("should call _sendBadStateEvent if initialized & other metrics have been recorded", () => {
+ const instance = wrapper.instance();
+ const stub = sandbox.stub(instance, "_sendBadStateEvent");
+ instance._reportMissingData = true;
+ instance._timestampHandled = true;
+ instance._recordedFirstRender = true;
+
+ sendBadStateStub.callThrough();
+ instance._maybeSendBadStateEvent();
+
+ assert.calledOnce(stub);
+ assert.isFalse(instance._reportMissingData);
+ });
+ });
+
+ describe("#_maybeSendPaintedEvent", () => {
+ it("should call _sendPaintedEvent if props.initialized is true", () => {
+ sandbox.stub(DEFAULT_PROPS, "initialized").value(true);
+ wrapper = shallow(
+ <ComponentPerfTimer {...DEFAULT_PROPS}>
+ <InnerEl />
+ </ComponentPerfTimer>,
+ { disableLifecycleMethods: true }
+ );
+ const instance = wrapper.instance();
+ const stub = sandbox.stub(instance, "_afterFramePaint");
+
+ assert.isFalse(instance._timestampHandled);
+
+ instance._maybeSendPaintedEvent();
+
+ assert.calledOnce(stub);
+ assert.calledWithExactly(stub, instance._sendPaintedEvent);
+ assert.isTrue(wrapper.instance()._timestampHandled);
+ });
+ it("should not call _sendPaintedEvent if this._timestampHandled is true", () => {
+ const instance = wrapper.instance();
+ const spy = sinon.spy(instance, "_afterFramePaint");
+ instance._timestampHandled = true;
+
+ instance._maybeSendPaintedEvent();
+ spy.neverCalledWith(instance._sendPaintedEvent);
+ });
+ it("should not call _sendPaintedEvent if component not initialized", () => {
+ sandbox.stub(DEFAULT_PROPS, "initialized").value(false);
+ wrapper = shallow(
+ <ComponentPerfTimer {...DEFAULT_PROPS}>
+ <InnerEl />
+ </ComponentPerfTimer>
+ );
+ const instance = wrapper.instance();
+ const spy = sinon.spy(instance, "_afterFramePaint");
+
+ instance._maybeSendPaintedEvent();
+
+ spy.neverCalledWith(instance._sendPaintedEvent);
+ });
+ });
+
+ describe("#_afterFramePaint", () => {
+ it("should call callback after the requestAnimationFrame callback returns", () =>
+ new Promise(resolve => {
+ // Setting the callback to resolve is the test that it does finally get
+ // called at the correct time, after the event loop ticks again.
+ // If it doesn't get called, this test will time out.
+ const callback = sandbox.spy(resolve);
+
+ const instance = wrapper.instance();
+
+ instance._afterFramePaint(callback);
+
+ assert.notCalled(callback);
+ mockRaf.step({ count: 1 });
+ }));
+ });
+
+ describe("#_sendBadStateEvent", () => {
+ it("should call perfSvc.mark", () => {
+ sandbox.spy(perfSvc, "mark");
+ const key = `${DEFAULT_PROPS.id}_data_ready_ts`;
+
+ wrapper.instance()._sendBadStateEvent();
+
+ assert.calledOnce(perfSvc.mark);
+ assert.calledWithExactly(perfSvc.mark, key);
+ });
+
+ it("should call compute the delta from first render to data ready", () => {
+ sandbox.stub(perfSvc, "getMostRecentAbsMarkStartByName");
+
+ wrapper
+ .instance()
+ ._sendBadStateEvent(`${DEFAULT_PROPS.id}_data_ready_ts`);
+
+ assert.calledTwice(perfSvc.getMostRecentAbsMarkStartByName);
+ assert.calledWithExactly(
+ perfSvc.getMostRecentAbsMarkStartByName,
+ `${DEFAULT_PROPS.id}_data_ready_ts`
+ );
+ assert.calledWithExactly(
+ perfSvc.getMostRecentAbsMarkStartByName,
+ `${DEFAULT_PROPS.id}_first_render_ts`
+ );
+ });
+
+ it("should call dispatch SAVE_SESSION_PERF_DATA", () => {
+ sandbox
+ .stub(perfSvc, "getMostRecentAbsMarkStartByName")
+ .withArgs("highlights_first_render_ts")
+ .returns(0.5)
+ .withArgs("highlights_data_ready_ts")
+ .returns(3.2);
+
+ const dispatch = sandbox.spy(DEFAULT_PROPS, "dispatch");
+ wrapper = shallow(
+ <ComponentPerfTimer {...DEFAULT_PROPS}>
+ <InnerEl />
+ </ComponentPerfTimer>
+ );
+
+ wrapper.instance()._sendBadStateEvent();
+
+ assert.calledOnce(dispatch);
+ assert.calledWithExactly(
+ dispatch,
+ ac.OnlyToMain({
+ type: at.SAVE_SESSION_PERF_DATA,
+ data: { [`${DEFAULT_PROPS.id}_data_late_by_ms`]: 2 },
+ })
+ );
+ });
+ });
+
+ describe("#_sendPaintedEvent", () => {
+ beforeEach(() => {
+ sandbox.stub(ComponentPerfTimer.prototype, "_maybeSendBadStateEvent");
+ sandbox.stub(
+ ComponentPerfTimer.prototype,
+ "_ensureFirstRenderTsRecorded"
+ );
+ });
+
+ it("should not call mark with the wrong id", () => {
+ sandbox.stub(perfSvc, "mark");
+ sandbox.stub(DEFAULT_PROPS, "id").value("fake_id");
+ wrapper = shallow(
+ <ComponentPerfTimer {...DEFAULT_PROPS}>
+ <InnerEl />
+ </ComponentPerfTimer>
+ );
+
+ wrapper.instance()._sendPaintedEvent();
+
+ assert.notCalled(perfSvc.mark);
+ });
+ it("should call mark with the correct topsites", () => {
+ sandbox.stub(perfSvc, "mark");
+ sandbox.stub(DEFAULT_PROPS, "id").value("topsites");
+ wrapper = shallow(
+ <ComponentPerfTimer {...DEFAULT_PROPS}>
+ <InnerEl />
+ </ComponentPerfTimer>
+ );
+
+ wrapper.instance()._sendPaintedEvent();
+
+ assert.calledOnce(perfSvc.mark);
+ assert.calledWithExactly(perfSvc.mark, "topsites_first_painted_ts");
+ });
+ it("should not call getMostRecentAbsMarkStartByName if id!=topsites", () => {
+ sandbox.stub(perfSvc, "getMostRecentAbsMarkStartByName");
+ sandbox.stub(DEFAULT_PROPS, "id").value("fake_id");
+ wrapper = shallow(
+ <ComponentPerfTimer {...DEFAULT_PROPS}>
+ <InnerEl />
+ </ComponentPerfTimer>
+ );
+
+ wrapper.instance()._sendPaintedEvent();
+
+ assert.notCalled(perfSvc.getMostRecentAbsMarkStartByName);
+ });
+ it("should call getMostRecentAbsMarkStartByName for topsites", () => {
+ sandbox.stub(perfSvc, "getMostRecentAbsMarkStartByName");
+ sandbox.stub(DEFAULT_PROPS, "id").value("topsites");
+ wrapper = shallow(
+ <ComponentPerfTimer {...DEFAULT_PROPS}>
+ <InnerEl />
+ </ComponentPerfTimer>
+ );
+
+ wrapper.instance()._sendPaintedEvent();
+
+ assert.calledOnce(perfSvc.getMostRecentAbsMarkStartByName);
+ assert.calledWithExactly(
+ perfSvc.getMostRecentAbsMarkStartByName,
+ "topsites_first_painted_ts"
+ );
+ });
+ it("should dispatch SAVE_SESSION_PERF_DATA", () => {
+ sandbox.stub(perfSvc, "getMostRecentAbsMarkStartByName").returns(42);
+ sandbox.stub(DEFAULT_PROPS, "id").value("topsites");
+ const dispatch = sandbox.spy(DEFAULT_PROPS, "dispatch");
+ wrapper = shallow(
+ <ComponentPerfTimer {...DEFAULT_PROPS}>
+ <InnerEl />
+ </ComponentPerfTimer>
+ );
+
+ wrapper.instance()._sendPaintedEvent();
+
+ assert.calledOnce(dispatch);
+ assert.calledWithExactly(
+ dispatch,
+ ac.OnlyToMain({
+ type: at.SAVE_SESSION_PERF_DATA,
+ data: { topsites_first_painted_ts: 42 },
+ })
+ );
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/components/ConfirmDialog.test.jsx b/browser/components/newtab/test/unit/content-src/components/ConfirmDialog.test.jsx
new file mode 100644
index 0000000000..ca0b4a3587
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/ConfirmDialog.test.jsx
@@ -0,0 +1,179 @@
+import { actionCreators as ac, actionTypes as at } from "common/Actions.jsm";
+import { _ConfirmDialog as ConfirmDialog } from "content-src/components/ConfirmDialog/ConfirmDialog";
+import React from "react";
+import { shallow } from "enzyme";
+
+describe("<ConfirmDialog>", () => {
+ let wrapper;
+ let dispatch;
+ let ConfirmDialogProps;
+ beforeEach(() => {
+ dispatch = sinon.stub();
+ ConfirmDialogProps = {
+ visible: true,
+ data: {
+ onConfirm: [],
+ cancel_button_string_id: "newtab-topsites-delete-history-button",
+ confirm_button_string_id: "newtab-topsites-cancel-button",
+ eventSource: "HIGHLIGHTS",
+ },
+ };
+ wrapper = shallow(
+ <ConfirmDialog dispatch={dispatch} {...ConfirmDialogProps} />
+ );
+ });
+ it("should render an overlay", () => {
+ assert.ok(wrapper.find(".modal-overlay").exists());
+ });
+ it("should render a modal", () => {
+ assert.ok(wrapper.find(".confirmation-dialog").exists());
+ });
+ it("should not render if visible is false", () => {
+ ConfirmDialogProps.visible = false;
+ wrapper = shallow(
+ <ConfirmDialog dispatch={dispatch} {...ConfirmDialogProps} />
+ );
+
+ assert.lengthOf(wrapper.find(".confirmation-dialog"), 0);
+ });
+ it("should display an icon if we provide one in props", () => {
+ const iconName = "modal-icon";
+ // If there is no icon in the props, we shouldn't display an icon
+ assert.lengthOf(wrapper.find(`.icon-${iconName}`), 0);
+
+ ConfirmDialogProps.data.icon = iconName;
+ wrapper = shallow(
+ <ConfirmDialog dispatch={dispatch} {...ConfirmDialogProps} />
+ );
+
+ // But if we do provide an icon - we should show it
+ assert.lengthOf(wrapper.find(`.icon-${iconName}`), 1);
+ });
+ describe("fluent message check", () => {
+ it("should render the message body sent via props", () => {
+ Object.assign(ConfirmDialogProps.data, {
+ body_string_id: ["foo", "bar"],
+ });
+ wrapper = shallow(
+ <ConfirmDialog dispatch={dispatch} {...ConfirmDialogProps} />
+ );
+ let msgs = wrapper.find(".modal-message").find("p");
+ assert.equal(msgs.length, ConfirmDialogProps.data.body_string_id.length);
+ msgs.forEach((fm, i) =>
+ assert.equal(
+ fm.prop("data-l10n-id"),
+ ConfirmDialogProps.data.body_string_id[i]
+ )
+ );
+ });
+ it("should render the correct primary button text", () => {
+ Object.assign(ConfirmDialogProps.data, {
+ confirm_button_string_id: "primary_foo",
+ });
+ wrapper = shallow(
+ <ConfirmDialog dispatch={dispatch} {...ConfirmDialogProps} />
+ );
+
+ let doneLabel = wrapper.find(".actions").childAt(1);
+ assert.ok(doneLabel.exists());
+ assert.equal(
+ doneLabel.prop("data-l10n-id"),
+ ConfirmDialogProps.data.confirm_button_string_id
+ );
+ });
+ });
+ describe("click events", () => {
+ it("should emit AlsoToMain DIALOG_CANCEL when you click the overlay", () => {
+ let overlay = wrapper.find(".modal-overlay");
+
+ assert.ok(overlay.exists());
+ overlay.simulate("click");
+
+ // Two events are emitted: UserEvent+AlsoToMain.
+ assert.calledTwice(dispatch);
+ assert.propertyVal(dispatch.firstCall.args[0], "type", at.DIALOG_CANCEL);
+ assert.calledWith(dispatch, { type: at.DIALOG_CANCEL });
+ });
+ it("should emit UserEvent DIALOG_CANCEL when you click the overlay", () => {
+ let overlay = wrapper.find(".modal-overlay");
+
+ assert.ok(overlay);
+ overlay.simulate("click");
+
+ // Two events are emitted: UserEvent+AlsoToMain.
+ assert.calledTwice(dispatch);
+ assert.isUserEventAction(dispatch.secondCall.args[0]);
+ assert.calledWith(
+ dispatch,
+ ac.UserEvent({ event: at.DIALOG_CANCEL, source: "HIGHLIGHTS" })
+ );
+ });
+ it("should emit AlsoToMain DIALOG_CANCEL on cancel", () => {
+ let cancelButton = wrapper.find(".actions").childAt(0);
+
+ assert.ok(cancelButton);
+ cancelButton.simulate("click");
+
+ // Two events are emitted: UserEvent+AlsoToMain.
+ assert.calledTwice(dispatch);
+ assert.propertyVal(dispatch.firstCall.args[0], "type", at.DIALOG_CANCEL);
+ assert.calledWith(dispatch, { type: at.DIALOG_CANCEL });
+ });
+ it("should emit UserEvent DIALOG_CANCEL on cancel", () => {
+ let cancelButton = wrapper.find(".actions").childAt(0);
+
+ assert.ok(cancelButton);
+ cancelButton.simulate("click");
+
+ // Two events are emitted: UserEvent+AlsoToMain.
+ assert.calledTwice(dispatch);
+ assert.isUserEventAction(dispatch.secondCall.args[0]);
+ assert.calledWith(
+ dispatch,
+ ac.UserEvent({ event: at.DIALOG_CANCEL, source: "HIGHLIGHTS" })
+ );
+ });
+ it("should emit UserEvent on primary button", () => {
+ Object.assign(ConfirmDialogProps.data, {
+ body_string_id: ["foo", "bar"],
+ onConfirm: [
+ ac.AlsoToMain({ type: at.DELETE_URL, data: "foo.bar" }),
+ ac.UserEvent({ event: "DELETE" }),
+ ],
+ });
+ wrapper = shallow(
+ <ConfirmDialog dispatch={dispatch} {...ConfirmDialogProps} />
+ );
+ let doneButton = wrapper.find(".actions").childAt(1);
+
+ assert.ok(doneButton);
+ doneButton.simulate("click");
+
+ // Two events are emitted: UserEvent+AlsoToMain.
+ assert.isUserEventAction(dispatch.secondCall.args[0]);
+
+ assert.calledTwice(dispatch);
+ assert.calledWith(dispatch, ConfirmDialogProps.data.onConfirm[1]);
+ });
+ it("should emit AlsoToMain on primary button", () => {
+ Object.assign(ConfirmDialogProps.data, {
+ body_string_id: ["foo", "bar"],
+ onConfirm: [
+ ac.AlsoToMain({ type: at.DELETE_URL, data: "foo.bar" }),
+ ac.UserEvent({ event: "DELETE" }),
+ ],
+ });
+ wrapper = shallow(
+ <ConfirmDialog dispatch={dispatch} {...ConfirmDialogProps} />
+ );
+ let doneButton = wrapper.find(".actions").childAt(1);
+
+ assert.ok(doneButton);
+ doneButton.simulate("click");
+
+ // Two events are emitted: UserEvent+AlsoToMain.
+ assert.calledTwice(dispatch);
+ assert.calledWith(dispatch, ConfirmDialogProps.data.onConfirm[0]);
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/components/ContextMenu.test.jsx b/browser/components/newtab/test/unit/content-src/components/ContextMenu.test.jsx
new file mode 100644
index 0000000000..397f1a1c90
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/ContextMenu.test.jsx
@@ -0,0 +1,230 @@
+import {
+ ContextMenu,
+ ContextMenuItem,
+ _ContextMenuItem,
+} from "content-src/components/ContextMenu/ContextMenu";
+import { ContextMenuButton } from "content-src/components/ContextMenu/ContextMenuButton";
+import { mount, shallow } from "enzyme";
+import React from "react";
+import { INITIAL_STATE, reducers } from "common/Reducers.jsm";
+import { Provider } from "react-redux";
+import { combineReducers, createStore } from "redux";
+
+const DEFAULT_PROPS = {
+ onUpdate: () => {},
+ options: [],
+ tabbableOptionsLength: 0,
+};
+
+const DEFAULT_MENU_OPTIONS = [
+ "MoveUp",
+ "MoveDown",
+ "Separator",
+ "RemoveSection",
+ "CheckCollapsed",
+ "Separator",
+ "ManageSection",
+];
+
+const FakeMenu = props => {
+ return <div>{props.children}</div>;
+};
+
+describe("<ContextMenuButton>", () => {
+ function mountWithProps(options) {
+ const store = createStore(combineReducers(reducers), INITIAL_STATE);
+ return mount(
+ <Provider store={store}>
+ <ContextMenuButton>
+ <ContextMenu options={options} />
+ </ContextMenuButton>
+ </Provider>
+ );
+ }
+
+ let sandbox;
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ });
+ afterEach(() => {
+ sandbox.restore();
+ });
+ it("should call onUpdate when clicked", () => {
+ const onUpdate = sandbox.spy();
+ const wrapper = mount(
+ <ContextMenuButton onUpdate={onUpdate}>
+ <FakeMenu />
+ </ContextMenuButton>
+ );
+ wrapper.find(".context-menu-button").simulate("click");
+ assert.calledOnce(onUpdate);
+ });
+ it("should call onUpdate when activated with Enter", () => {
+ const onUpdate = sandbox.spy();
+ const wrapper = mount(
+ <ContextMenuButton onUpdate={onUpdate}>
+ <FakeMenu />
+ </ContextMenuButton>
+ );
+ wrapper.find(".context-menu-button").simulate("keydown", { key: "Enter" });
+ assert.calledOnce(onUpdate);
+ });
+ it("should call onClick", () => {
+ const onClick = sandbox.spy(ContextMenuButton.prototype, "onClick");
+ const wrapper = mount(
+ <ContextMenuButton>
+ <FakeMenu />
+ </ContextMenuButton>
+ );
+ wrapper.find("button").simulate("click");
+ assert.calledOnce(onClick);
+ });
+ it("should have a default keyboardAccess prop of false", () => {
+ const wrapper = mountWithProps(DEFAULT_MENU_OPTIONS);
+ wrapper.find(ContextMenuButton).setState({ showContextMenu: true });
+ assert.equal(wrapper.find(ContextMenu).prop("keyboardAccess"), false);
+ });
+ it("should pass the keyboardAccess prop down to ContextMenu", () => {
+ const wrapper = mountWithProps(DEFAULT_MENU_OPTIONS);
+ wrapper
+ .find(ContextMenuButton)
+ .setState({ showContextMenu: true, contextMenuKeyboard: true });
+ assert.equal(wrapper.find(ContextMenu).prop("keyboardAccess"), true);
+ });
+ it("should call focusFirst when keyboardAccess is true", () => {
+ const options = [{ label: "item1", first: true }];
+ const wrapper = mountWithProps(options);
+ const focusFirst = sandbox.spy(_ContextMenuItem.prototype, "focusFirst");
+ wrapper
+ .find(ContextMenuButton)
+ .setState({ showContextMenu: true, contextMenuKeyboard: true });
+ assert.calledOnce(focusFirst);
+ });
+});
+
+describe("<ContextMenu>", () => {
+ function mountWithProps(props) {
+ const store = createStore(combineReducers(reducers), INITIAL_STATE);
+ return mount(
+ <Provider store={store}>
+ <ContextMenu {...props} />
+ </Provider>
+ );
+ }
+
+ it("should render all the options provided", () => {
+ const options = [
+ { label: "item1" },
+ { type: "separator" },
+ { label: "item2" },
+ ];
+ const wrapper = shallow(
+ <ContextMenu {...DEFAULT_PROPS} options={options} />
+ );
+ assert.lengthOf(wrapper.find(".context-menu-list").children(), 3);
+ });
+ it("should not add a link for a separator", () => {
+ const options = [{ label: "item1" }, { type: "separator" }];
+ const wrapper = shallow(
+ <ContextMenu {...DEFAULT_PROPS} options={options} />
+ );
+ assert.lengthOf(wrapper.find(".separator"), 1);
+ });
+ it("should add a link for all types that are not separators", () => {
+ const options = [{ label: "item1" }, { type: "separator" }];
+ const wrapper = shallow(
+ <ContextMenu {...DEFAULT_PROPS} options={options} />
+ );
+ assert.lengthOf(wrapper.find(ContextMenuItem), 1);
+ });
+ it("should add an icon to items that need icons", () => {
+ const props = Object.assign({}, DEFAULT_PROPS, {
+ options: [{ label: "item1", icon: "icon1" }, { type: "separator" }],
+ });
+ const wrapper = mountWithProps(props);
+ assert.lengthOf(wrapper.find(".icon-icon1"), 1);
+ });
+ it("should be tabbable", () => {
+ const props = {
+ options: [{ label: "item1", icon: "icon1" }, { type: "separator" }],
+ };
+ const wrapper = mountWithProps(props);
+ assert.equal(
+ wrapper.find(".context-menu-item").props().role,
+ "presentation"
+ );
+ });
+ it("should call onUpdate with false when an option is clicked", () => {
+ const onUpdate = sinon.spy();
+ const onClick = sinon.spy();
+ const props = Object.assign({}, DEFAULT_PROPS, {
+ onUpdate,
+ options: [{ label: "item1", onClick }],
+ });
+ const wrapper = mountWithProps(props);
+ wrapper.find(".context-menu-item button").simulate("click");
+ assert.calledOnce(onUpdate);
+ assert.calledOnce(onClick);
+ });
+ it("should not have disabled className by default", () => {
+ const props = Object.assign({}, DEFAULT_PROPS, {
+ options: [{ label: "item1", icon: "icon1" }, { type: "separator" }],
+ });
+ const wrapper = mountWithProps(props);
+ assert.lengthOf(wrapper.find(".context-menu-item a.disabled"), 0);
+ });
+ it("should add disabled className to any disabled options", () => {
+ const options = [
+ { label: "item1", icon: "icon1", disabled: true },
+ { type: "separator" },
+ ];
+ const props = Object.assign({}, DEFAULT_PROPS, { options });
+ const wrapper = mountWithProps(props);
+ assert.lengthOf(wrapper.find(".context-menu-item button.disabled"), 1);
+ });
+ it("should have the context-menu-item class", () => {
+ const options = [{ label: "item1", icon: "icon1" }];
+ const props = Object.assign({}, DEFAULT_PROPS, { options });
+ const wrapper = mountWithProps(props);
+ assert.lengthOf(wrapper.find(".context-menu-item"), 1);
+ });
+ it("should call onClick when onKeyDown is called with Enter", () => {
+ const onClick = sinon.spy();
+ const props = Object.assign({}, DEFAULT_PROPS, {
+ options: [{ label: "item1", onClick }],
+ });
+ const wrapper = mountWithProps(props);
+ wrapper
+ .find(".context-menu-item button")
+ .simulate("keydown", { key: "Enter" });
+ assert.calledOnce(onClick);
+ });
+ it("should call focusSibling when onKeyDown is called with ArrowUp", () => {
+ const props = Object.assign({}, DEFAULT_PROPS, {
+ options: [{ label: "item1" }],
+ });
+ const wrapper = mountWithProps(props);
+ const focusSibling = sinon.stub(
+ wrapper.find(_ContextMenuItem).instance(),
+ "focusSibling"
+ );
+ wrapper
+ .find(".context-menu-item button")
+ .simulate("keydown", { key: "ArrowUp" });
+ assert.calledOnce(focusSibling);
+ });
+ it("should call focusSibling when onKeyDown is called with ArrowDown", () => {
+ const props = Object.assign({}, DEFAULT_PROPS, {
+ options: [{ label: "item1" }],
+ });
+ const wrapper = mountWithProps(props);
+ const focusSibling = sinon.stub(
+ wrapper.find(_ContextMenuItem).instance(),
+ "focusSibling"
+ );
+ wrapper
+ .find(".context-menu-item button")
+ .simulate("keydown", { key: "ArrowDown" });
+ assert.calledOnce(focusSibling);
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/components/CustomiseMenu.test.jsx b/browser/components/newtab/test/unit/content-src/components/CustomiseMenu.test.jsx
new file mode 100644
index 0000000000..d56d9a305a
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/CustomiseMenu.test.jsx
@@ -0,0 +1,76 @@
+import { actionCreators as ac } from "common/Actions.jsm";
+import { ContentSection } from "content-src/components/CustomizeMenu/ContentSection/ContentSection";
+import { mount } from "enzyme";
+import React from "react";
+
+const DEFAULT_PROPS = {
+ enabledSections: {
+ pocketEnabled: true,
+ topSitesEnabled: true,
+ },
+ mayHaveSponsoredTopSites: true,
+ mayHaveSponsoredStories: true,
+ pocketRegion: true,
+ dispatch: sinon.stub(),
+ setPref: sinon.stub(),
+};
+
+describe("ContentSection", () => {
+ let wrapper;
+ beforeEach(() => {
+ wrapper = mount(<ContentSection {...DEFAULT_PROPS} />);
+ });
+
+ it("should render the component", () => {
+ assert.ok(wrapper.exists());
+ });
+
+ it("should look for an eventSource attribute and dispatch an event for INPUT", () => {
+ wrapper.instance().onPreferenceSelect({
+ target: {
+ nodeName: "INPUT",
+ checked: true,
+ getAttribute: eventSource =>
+ eventSource === "eventSource" ? "foo" : null,
+ },
+ });
+
+ assert.calledWith(
+ DEFAULT_PROPS.dispatch,
+ ac.UserEvent({
+ event: "PREF_CHANGED",
+ source: "foo",
+ value: { status: true, menu_source: "CUSTOMIZE_MENU" },
+ })
+ );
+ wrapper.unmount();
+ });
+
+ it("should have eventSource attributes on relevent pref changing inputs", () => {
+ wrapper = mount(<ContentSection {...DEFAULT_PROPS} />);
+ assert.equal(
+ wrapper.find("#shortcuts-toggle").prop("eventSource"),
+ "TOP_SITES"
+ );
+ assert.equal(
+ wrapper.find("#sponsored-shortcuts").prop("eventSource"),
+ "SPONSORED_TOP_SITES"
+ );
+ assert.equal(
+ wrapper.find("#pocket-toggle").prop("eventSource"),
+ "TOP_STORIES"
+ );
+ assert.equal(
+ wrapper.find("#sponsored-pocket").prop("eventSource"),
+ "POCKET_SPOCS"
+ );
+ assert.equal(
+ wrapper.find("#highlights-toggle").prop("eventSource"),
+ "HIGHLIGHTS"
+ );
+ assert.equal(
+ wrapper.find("#snippets-toggle").prop("eventSource"),
+ "SNIPPETS"
+ );
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamBase.test.jsx b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamBase.test.jsx
new file mode 100644
index 0000000000..4681ef73c3
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamBase.test.jsx
@@ -0,0 +1,377 @@
+import {
+ _DiscoveryStreamBase as DiscoveryStreamBase,
+ isAllowedCSS,
+} from "content-src/components/DiscoveryStreamBase/DiscoveryStreamBase";
+import { GlobalOverrider } from "test/unit/utils";
+import { CardGrid } from "content-src/components/DiscoveryStreamComponents/CardGrid/CardGrid";
+import { CollapsibleSection } from "content-src/components/CollapsibleSection/CollapsibleSection";
+import { DSMessage } from "content-src/components/DiscoveryStreamComponents/DSMessage/DSMessage";
+import { Hero } from "content-src/components/DiscoveryStreamComponents/Hero/Hero";
+import { HorizontalRule } from "content-src/components/DiscoveryStreamComponents/HorizontalRule/HorizontalRule";
+import { List } from "content-src/components/DiscoveryStreamComponents/List/List";
+import { Navigation } from "content-src/components/DiscoveryStreamComponents/Navigation/Navigation";
+import React from "react";
+import { shallow } from "enzyme";
+import { SectionTitle } from "content-src/components/DiscoveryStreamComponents/SectionTitle/SectionTitle";
+import { TopSites } from "content-src/components/DiscoveryStreamComponents/TopSites/TopSites";
+
+describe("<isAllowedCSS>", () => {
+ it("should allow colors", () => {
+ assert.isTrue(isAllowedCSS("color", "red"));
+ });
+
+ it("should allow chrome urls", () => {
+ assert.isTrue(
+ isAllowedCSS(
+ "background-image",
+ `url("chrome://activity-stream/content/data/content/assets/glyph-info-16.svg")`
+ )
+ );
+ });
+
+ it("should allow chrome urls", () => {
+ assert.isTrue(
+ isAllowedCSS(
+ "background-image",
+ `url("chrome://browser/skin/history.svg")`
+ )
+ );
+ });
+
+ it("should allow allowed https urls", () => {
+ assert.isTrue(
+ isAllowedCSS(
+ "background-image",
+ `url("https://img-getpocket.cdn.mozilla.net/media/image.png")`
+ )
+ );
+ });
+
+ it("should disallow other https urls", () => {
+ assert.isFalse(
+ isAllowedCSS(
+ "background-image",
+ `url("https://mozilla.org/media/image.png")`
+ )
+ );
+ });
+
+ it("should disallow other protocols", () => {
+ assert.isFalse(
+ isAllowedCSS(
+ "background-image",
+ `url("ftp://mozilla.org/media/image.png")`
+ )
+ );
+ });
+
+ it("should allow allowed multiple valid urls", () => {
+ assert.isTrue(
+ isAllowedCSS(
+ "background-image",
+ `url("https://img-getpocket.cdn.mozilla.net/media/image.png"), url("chrome://browser/skin/history.svg")`
+ )
+ );
+ });
+
+ it("should disallow if any invaild", () => {
+ assert.isFalse(
+ isAllowedCSS(
+ "background-image",
+ `url("chrome://browser/skin/history.svg"), url("ftp://mozilla.org/media/image.png")`
+ )
+ );
+ });
+});
+
+describe("<DiscoveryStreamBase>", () => {
+ let wrapper;
+ let globals;
+ let sandbox;
+
+ function mountComponent(props = {}) {
+ const defaultProps = {
+ config: { collapsible: true },
+ layout: [],
+ feeds: { loaded: true },
+ spocs: {
+ loaded: true,
+ data: { spocs: null },
+ },
+ ...props,
+ };
+ return shallow(
+ <DiscoveryStreamBase
+ locale="en-US"
+ DiscoveryStream={defaultProps}
+ Prefs={{
+ values: {
+ "feeds.section.topstories": true,
+ "feeds.system.topstories": true,
+ "feeds.topsites": true,
+ },
+ }}
+ document={{
+ documentElement: { lang: "en-US" },
+ }}
+ Sections={[
+ {
+ id: "topstories",
+ learnMore: { link: {} },
+ pref: {},
+ },
+ ]}
+ />
+ );
+ }
+
+ beforeEach(() => {
+ globals = new GlobalOverrider();
+ sandbox = sinon.createSandbox();
+ wrapper = mountComponent();
+ });
+
+ afterEach(() => {
+ sandbox.restore();
+ globals.restore();
+ });
+
+ it("should render something if spocs are not loaded", () => {
+ wrapper = mountComponent({
+ spocs: { loaded: false, data: { spocs: null } },
+ });
+
+ assert.notEqual(wrapper.type(), null);
+ });
+
+ it("should render something if feeds are not loaded", () => {
+ wrapper = mountComponent({ feeds: { loaded: false } });
+
+ assert.notEqual(wrapper.type(), null);
+ });
+
+ it("should render nothing with no layout", () => {
+ assert.ok(wrapper.exists());
+ assert.isEmpty(wrapper.children());
+ });
+
+ it("should render a HorizontalRule component", () => {
+ wrapper = mountComponent({
+ layout: [{ components: [{ type: "HorizontalRule" }] }],
+ });
+
+ assert.equal(
+ wrapper
+ .find(".ds-column-grid div")
+ .children()
+ .at(0)
+ .type(),
+ HorizontalRule
+ );
+ });
+
+ it("should render a List component", () => {
+ wrapper = mountComponent({
+ layout: [{ components: [{ properties: {}, type: "List" }] }],
+ });
+
+ assert.equal(
+ wrapper
+ .find(".ds-column-grid div")
+ .children()
+ .at(0)
+ .type(),
+ List
+ );
+ });
+
+ it("should render a Hero component", () => {
+ wrapper = mountComponent({
+ layout: [{ components: [{ properties: {}, type: "Hero" }] }],
+ });
+
+ assert.equal(
+ wrapper
+ .find(".ds-column-grid div")
+ .children()
+ .at(0)
+ .type(),
+ Hero
+ );
+ });
+
+ it("should render a CardGrid component", () => {
+ wrapper = mountComponent({
+ layout: [{ components: [{ properties: {}, type: "CardGrid" }] }],
+ });
+
+ assert.equal(
+ wrapper
+ .find(".ds-column-grid div")
+ .children()
+ .at(0)
+ .type(),
+ CardGrid
+ );
+ });
+
+ it("should render a Navigation component", () => {
+ wrapper = mountComponent({
+ layout: [{ components: [{ properties: {}, type: "Navigation" }] }],
+ });
+
+ assert.equal(
+ wrapper
+ .find(".ds-column-grid div")
+ .children()
+ .at(0)
+ .type(),
+ Navigation
+ );
+ });
+
+ it("should render nothing if there was only a Message", () => {
+ wrapper = mountComponent({
+ layout: [
+ { components: [{ header: {}, properties: {}, type: "Message" }] },
+ ],
+ });
+
+ assert.isEmpty(wrapper.children());
+ });
+
+ it("should render a regular Message when not collapsible", () => {
+ wrapper = mountComponent({
+ config: { collapsible: false },
+ layout: [
+ { components: [{ header: {}, properties: {}, type: "Message" }] },
+ ],
+ });
+
+ assert.equal(
+ wrapper
+ .find(".ds-column-grid div")
+ .children()
+ .at(0)
+ .type(),
+ DSMessage
+ );
+ });
+
+ it("should convert first Message component to CollapsibleSection", () => {
+ wrapper = mountComponent({
+ layout: [
+ {
+ components: [
+ { header: {}, properties: {}, type: "Message" },
+ { type: "HorizontalRule" },
+ ],
+ },
+ ],
+ });
+
+ assert.equal(
+ wrapper
+ .children()
+ .at(0)
+ .type(),
+ CollapsibleSection
+ );
+ assert.equal(
+ wrapper
+ .children()
+ .at(0)
+ .props().eventSource,
+ "CARDGRID"
+ );
+ });
+
+ it("should render a Message component", () => {
+ wrapper = mountComponent({
+ layout: [
+ {
+ components: [
+ { header: {}, type: "Message" },
+ { properties: {}, type: "Message" },
+ ],
+ },
+ ],
+ });
+
+ assert.equal(
+ wrapper
+ .find(".ds-column-grid div")
+ .children()
+ .at(0)
+ .type(),
+ DSMessage
+ );
+ });
+
+ it("should render a SectionTitle component", () => {
+ wrapper = mountComponent({
+ layout: [{ components: [{ properties: {}, type: "SectionTitle" }] }],
+ });
+
+ assert.equal(
+ wrapper
+ .find(".ds-column-grid div")
+ .children()
+ .at(0)
+ .type(),
+ SectionTitle
+ );
+ });
+
+ it("should render TopSites", () => {
+ wrapper = mountComponent({
+ layout: [{ components: [{ properties: {}, type: "TopSites" }] }],
+ });
+
+ assert.equal(
+ wrapper
+ .find(".ds-column-grid div")
+ .children()
+ .at(0)
+ .type(),
+ TopSites
+ );
+ });
+
+ describe("#onStyleMount", () => {
+ let parseStub;
+
+ beforeEach(() => {
+ parseStub = sandbox.stub();
+ globals.set("JSON", { parse: parseStub });
+ });
+
+ afterEach(() => {
+ sandbox.restore();
+ globals.restore();
+ });
+
+ it("should return if no style", () => {
+ assert.isUndefined(wrapper.instance().onStyleMount());
+ assert.notCalled(parseStub);
+ });
+
+ it("should insert rules", () => {
+ const sheetStub = { insertRule: sandbox.stub(), cssRules: [{}] };
+ parseStub.returns([
+ [
+ null,
+ {
+ ".ds-message": "margin-bottom: -20px",
+ },
+ null,
+ null,
+ ],
+ ]);
+ wrapper.instance().onStyleMount({ sheet: sheetStub, dataset: {} });
+
+ assert.calledOnce(sheetStub.insertRule);
+ assert.calledWithExactly(sheetStub.insertRule, "DUMMY#CSS.SELECTOR {}");
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/CardGrid.test.jsx b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/CardGrid.test.jsx
new file mode 100644
index 0000000000..7b029f9e15
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/CardGrid.test.jsx
@@ -0,0 +1,40 @@
+import { CardGrid } from "content-src/components/DiscoveryStreamComponents/CardGrid/CardGrid";
+import { DSCard } from "content-src/components/DiscoveryStreamComponents/DSCard/DSCard";
+import React from "react";
+import { shallow } from "enzyme";
+
+describe("<CardGrid>", () => {
+ let wrapper;
+
+ beforeEach(() => {
+ wrapper = shallow(<CardGrid />);
+ });
+
+ it("should render an empty div", () => {
+ assert.ok(wrapper.exists());
+ assert.lengthOf(wrapper.children(), 0);
+ });
+
+ it("should render DSCards", () => {
+ wrapper.setProps({ items: 2, data: { recommendations: [{}, {}] } });
+
+ assert.lengthOf(wrapper.find(".ds-card-grid").children(), 2);
+ assert.equal(
+ wrapper
+ .find(".ds-card-grid")
+ .children()
+ .at(0)
+ .type(),
+ DSCard
+ );
+ });
+
+ it("should add hero classname to card grid", () => {
+ wrapper.setProps({
+ display_variant: "hero",
+ data: { recommendations: [{}, {}] },
+ });
+
+ assert.ok(wrapper.find(".ds-card-grid-hero").exists());
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/CollectionCardGrid.test.jsx b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/CollectionCardGrid.test.jsx
new file mode 100644
index 0000000000..a0e9d69d18
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/CollectionCardGrid.test.jsx
@@ -0,0 +1,149 @@
+import { CollectionCardGrid } from "content-src/components/DiscoveryStreamComponents/CollectionCardGrid/CollectionCardGrid";
+import { CardGrid } from "content-src/components/DiscoveryStreamComponents/CardGrid/CardGrid";
+import React from "react";
+import { shallow } from "enzyme";
+
+describe("<CollectionCardGrid>", () => {
+ let wrapper;
+ let sandbox;
+ let dispatchStub;
+ const initialSpocs = [
+ { id: 123, url: "123" },
+ { id: 456, url: "456" },
+ { id: 789, url: "789" },
+ ];
+
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ dispatchStub = sandbox.stub();
+ wrapper = shallow(
+ <CollectionCardGrid
+ dispatch={dispatchStub}
+ type="COLLECTIONCARDGRID"
+ placement={{
+ name: "spocs",
+ }}
+ data={{
+ spocs: initialSpocs,
+ }}
+ spocs={{
+ data: {
+ spocs: {
+ title: "title",
+ context: "context",
+ items: initialSpocs,
+ },
+ },
+ }}
+ />
+ );
+ });
+
+ it("should render an empty div", () => {
+ wrapper = shallow(<CollectionCardGrid />);
+ assert.ok(wrapper.exists());
+ assert.ok(!wrapper.exists(".ds-collection-card-grid"));
+ });
+
+ it("should render a CardGrid", () => {
+ assert.lengthOf(wrapper.find(".ds-collection-card-grid").children(), 1);
+ assert.equal(
+ wrapper
+ .find(".ds-collection-card-grid")
+ .children()
+ .at(0)
+ .type(),
+ CardGrid
+ );
+ });
+
+ it("should inject spocs in every CardGrid rec position", () => {
+ assert.lengthOf(
+ wrapper
+ .find(".ds-collection-card-grid")
+ .children()
+ .at(0)
+ .props().data.recommendations,
+ 3
+ );
+ });
+
+ it("should pass along title and context to CardGrid", () => {
+ assert.equal(
+ wrapper
+ .find(".ds-collection-card-grid")
+ .children()
+ .at(0)
+ .props().title,
+ "title"
+ );
+
+ assert.equal(
+ wrapper
+ .find(".ds-collection-card-grid")
+ .children()
+ .at(0)
+ .props().context,
+ "context"
+ );
+ });
+
+ it("should render nothing without a title", () => {
+ wrapper = shallow(
+ <CollectionCardGrid
+ dispatch={dispatchStub}
+ placement={{
+ name: "spocs",
+ }}
+ data={{
+ spocs: initialSpocs,
+ }}
+ spocs={{
+ data: {
+ spocs: {
+ title: "",
+ context: "context",
+ items: initialSpocs,
+ },
+ },
+ }}
+ />
+ );
+
+ assert.ok(wrapper.exists());
+ assert.ok(!wrapper.exists(".ds-collection-card-grid"));
+ });
+
+ it("should dispath telemety events on dismiss", () => {
+ wrapper.instance().onDismissClick();
+
+ const firstCall = dispatchStub.getCall(0);
+ const secondCall = dispatchStub.getCall(1);
+ const thirdCall = dispatchStub.getCall(2);
+
+ assert.equal(firstCall.args[0].type, "BLOCK_URL");
+ assert.deepEqual(firstCall.args[0].data, [
+ { url: "123", pocket_id: undefined },
+ { url: "456", pocket_id: undefined },
+ { url: "789", pocket_id: undefined },
+ ]);
+
+ assert.equal(secondCall.args[0].type, "TELEMETRY_USER_EVENT");
+ assert.deepEqual(secondCall.args[0].data, {
+ event: "BLOCK",
+ source: "COLLECTIONCARDGRID",
+ action_position: 0,
+ });
+
+ assert.equal(thirdCall.args[0].type, "TELEMETRY_IMPRESSION_STATS");
+ assert.deepEqual(thirdCall.args[0].data, {
+ source: "COLLECTIONCARDGRID",
+ block: 0,
+ tiles: [
+ { id: 123, pos: 0 },
+ { id: 456, pos: 1 },
+ { id: 789, pos: 2 },
+ ],
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSCard.test.jsx b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSCard.test.jsx
new file mode 100644
index 0000000000..717f64cd14
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSCard.test.jsx
@@ -0,0 +1,373 @@
+import {
+ _DSCard as DSCard,
+ DefaultMeta,
+ PlaceholderDSCard,
+ CTAButtonMeta,
+} from "content-src/components/DiscoveryStreamComponents/DSCard/DSCard";
+import {
+ DSContextFooter,
+ StatusMessage,
+} from "content-src/components/DiscoveryStreamComponents/DSContextFooter/DSContextFooter";
+import { actionCreators as ac } from "common/Actions.jsm";
+import { DSLinkMenu } from "content-src/components/DiscoveryStreamComponents/DSLinkMenu/DSLinkMenu";
+import React from "react";
+import { SafeAnchor } from "content-src/components/DiscoveryStreamComponents/SafeAnchor/SafeAnchor";
+import { shallow, mount } from "enzyme";
+import { FluentOrText } from "content-src/components/FluentOrText/FluentOrText";
+
+const DEFAULT_PROPS = {
+ App: {
+ isForStartupCache: false,
+ },
+};
+
+describe("<DSCard>", () => {
+ let wrapper;
+ let sandbox;
+
+ beforeEach(() => {
+ wrapper = shallow(<DSCard {...DEFAULT_PROPS} />);
+ wrapper.setState({ isSeen: true });
+ sandbox = sinon.createSandbox();
+ });
+
+ afterEach(() => {
+ sandbox.restore();
+ });
+
+ it("should render", () => {
+ assert.ok(wrapper.exists());
+ assert.ok(wrapper.find(".ds-card"));
+ });
+
+ it("should render a SafeAnchor", () => {
+ wrapper.setProps({ url: "https://foo.com" });
+
+ assert.equal(
+ wrapper
+ .children()
+ .at(0)
+ .type(),
+ SafeAnchor
+ );
+ assert.propertyVal(
+ wrapper
+ .children()
+ .at(0)
+ .props(),
+ "url",
+ "https://foo.com"
+ );
+ });
+
+ it("should pass onLinkClick prop", () => {
+ assert.propertyVal(
+ wrapper
+ .children()
+ .at(0)
+ .props(),
+ "onLinkClick",
+ wrapper.instance().onLinkClick
+ );
+ });
+
+ it("should render DSLinkMenu", () => {
+ assert.equal(
+ wrapper
+ .children()
+ .at(1)
+ .type(),
+ DSLinkMenu
+ );
+ });
+
+ it("should start with no .active class", () => {
+ assert.equal(wrapper.find(".active").length, 0);
+ });
+
+ it("should render badges for pocket, bookmark when not a spoc element ", () => {
+ wrapper = mount(<DSCard context_type="bookmark" {...DEFAULT_PROPS} />);
+ wrapper.setState({ isSeen: true });
+ const contextFooter = wrapper.find(DSContextFooter);
+
+ assert.lengthOf(contextFooter.find(StatusMessage), 1);
+ });
+
+ it("should render Sponsored Context for a spoc element", () => {
+ const context = "Sponsored by Foo";
+ wrapper = mount(
+ <DSCard context_type="bookmark" context={context} {...DEFAULT_PROPS} />
+ );
+ wrapper.setState({ isSeen: true });
+ const contextFooter = wrapper.find(DSContextFooter);
+
+ assert.lengthOf(contextFooter.find(StatusMessage), 0);
+ assert.equal(contextFooter.find(".story-sponsored-label").text(), context);
+ });
+
+ describe("onLinkClick", () => {
+ let dispatch;
+
+ beforeEach(() => {
+ dispatch = sandbox.stub();
+ wrapper = shallow(<DSCard dispatch={dispatch} {...DEFAULT_PROPS} />);
+ wrapper.setState({ isSeen: true });
+ });
+
+ it("should call dispatch with the correct events", () => {
+ wrapper.setProps({ id: "fooidx", pos: 1, type: "foo" });
+
+ wrapper.instance().onLinkClick();
+
+ assert.calledTwice(dispatch);
+ assert.calledWith(
+ dispatch,
+ ac.UserEvent({
+ event: "CLICK",
+ source: "FOO",
+ action_position: 1,
+ value: { card_type: "organic" },
+ })
+ );
+ assert.calledWith(
+ dispatch,
+ ac.ImpressionStats({
+ click: 0,
+ source: "FOO",
+ tiles: [{ id: "fooidx", pos: 1 }],
+ })
+ );
+ });
+
+ it("should set the right card_type on spocs", () => {
+ wrapper.setProps({ id: "fooidx", pos: 1, type: "foo", flightId: 12345 });
+
+ wrapper.instance().onLinkClick();
+
+ assert.calledTwice(dispatch);
+ assert.calledWith(
+ dispatch,
+ ac.UserEvent({
+ event: "CLICK",
+ source: "FOO",
+ action_position: 1,
+ value: { card_type: "spoc" },
+ })
+ );
+ assert.calledWith(
+ dispatch,
+ ac.ImpressionStats({
+ click: 0,
+ source: "FOO",
+ tiles: [{ id: "fooidx", pos: 1 }],
+ })
+ );
+ });
+
+ it("should call dispatch with a shim", () => {
+ wrapper.setProps({
+ id: "fooidx",
+ pos: 1,
+ type: "foo",
+ shim: {
+ click: "click shim",
+ },
+ });
+
+ wrapper.instance().onLinkClick();
+
+ assert.calledTwice(dispatch);
+ assert.calledWith(
+ dispatch,
+ ac.UserEvent({
+ event: "CLICK",
+ source: "FOO",
+ action_position: 1,
+ value: { card_type: "organic" },
+ })
+ );
+ assert.calledWith(
+ dispatch,
+ ac.ImpressionStats({
+ click: 0,
+ source: "FOO",
+ tiles: [{ id: "fooidx", pos: 1, shim: "click shim" }],
+ })
+ );
+ });
+ });
+
+ describe("DSCard with CTA", () => {
+ beforeEach(() => {
+ wrapper = mount(<DSCard {...DEFAULT_PROPS} />);
+ wrapper.setState({ isSeen: true });
+ });
+
+ it("should render Default Meta", () => {
+ const default_meta = wrapper.find(DefaultMeta);
+ assert.ok(default_meta.exists());
+ });
+
+ it("should not render cta-link for item with no cta", () => {
+ const meta = wrapper.find(DefaultMeta);
+ assert.notOk(meta.find(".cta-link").exists());
+ });
+
+ it("should not render cta-link by default when item has cta and cta_variant not link", () => {
+ wrapper.setProps({ cta: "test" });
+ const meta = wrapper.find(DefaultMeta);
+ assert.notOk(meta.find(".cta-link").exists());
+ });
+
+ it("should render cta-link by default when item has cta and cta_variant as link", () => {
+ wrapper.setProps({ cta: "test", cta_variant: "link" });
+ const meta = wrapper.find(DefaultMeta);
+ assert.equal(meta.find(".cta-link").text(), "test");
+ });
+
+ it("should not render cta-button for non spoc content", () => {
+ wrapper.setProps({ cta: "test", cta_variant: "button" });
+ const meta = wrapper.find(CTAButtonMeta);
+ assert.lengthOf(meta.find(".cta-button"), 0);
+ });
+
+ it("should render cta-button when item has cta and cta_variant is button and is spoc", () => {
+ wrapper.setProps({
+ cta: "test",
+ cta_variant: "button",
+ context: "Sponsored by Foo",
+ });
+ const meta = wrapper.find(CTAButtonMeta);
+ assert.equal(meta.find(".cta-button").text(), "test");
+ });
+
+ it("should not render Sponsored by label in footer for spoc item with cta_variant button", () => {
+ wrapper.setProps({
+ cta: "test",
+ context: "Sponsored by test",
+ cta_variant: "button",
+ });
+
+ assert.ok(wrapper.find(CTAButtonMeta).exists());
+ assert.notOk(wrapper.find(DSContextFooter).exists());
+ });
+
+ it("should render sponsor text as fluent element on top for spoc item and cta button variant", () => {
+ wrapper.setProps({
+ sponsor: "Test",
+ context: "Sponsored by test",
+ cta_variant: "button",
+ });
+
+ assert.ok(wrapper.find(CTAButtonMeta).exists());
+ const meta = wrapper.find(CTAButtonMeta);
+ assert.equal(
+ meta
+ .find(".source")
+ .children()
+ .at(0)
+ .type(),
+ FluentOrText
+ );
+ });
+ });
+ describe("DSCard with Intersection Observer", () => {
+ beforeEach(() => {
+ wrapper = shallow(<DSCard {...DEFAULT_PROPS} />);
+ });
+
+ it("should render card when seen", () => {
+ let card = wrapper.find("div.ds-card.placeholder");
+ assert.lengthOf(card, 1);
+
+ wrapper.instance().observer = {
+ unobserve: sandbox.stub(),
+ };
+ wrapper.instance().placeholderElement = "element";
+
+ wrapper.instance().onSeen([
+ {
+ isIntersecting: true,
+ },
+ ]);
+
+ assert.isTrue(wrapper.instance().state.isSeen);
+ card = wrapper.find("div.ds-card.placeholder");
+ assert.lengthOf(card, 0);
+ assert.lengthOf(wrapper.find(SafeAnchor), 1);
+ assert.calledOnce(wrapper.instance().observer.unobserve);
+ assert.calledWith(wrapper.instance().observer.unobserve, "element");
+ });
+
+ it("should setup proper placholder ref for isSeen", () => {
+ wrapper.instance().setPlaceholderRef("element");
+ assert.equal(wrapper.instance().placeholderElement, "element");
+ });
+
+ it("should setup observer on componentDidMount", () => {
+ wrapper = mount(<DSCard {...DEFAULT_PROPS} />);
+ assert.isTrue(!!wrapper.instance().observer);
+ });
+ });
+ describe("DSCard with Idle Callback", () => {
+ let windowStub = {
+ requestIdleCallback: sinon.stub().returns(1),
+ cancelIdleCallback: sinon.stub(),
+ };
+ beforeEach(() => {
+ wrapper = shallow(<DSCard windowObj={windowStub} {...DEFAULT_PROPS} />);
+ });
+
+ it("should call requestIdleCallback on componentDidMount", () => {
+ assert.calledOnce(windowStub.requestIdleCallback);
+ });
+
+ it("should call cancelIdleCallback on componentWillUnmount", () => {
+ wrapper.instance().componentWillUnmount();
+ assert.calledOnce(windowStub.cancelIdleCallback);
+ });
+ });
+ describe("DSCard when rendered for about:home startup cache", () => {
+ beforeEach(() => {
+ const props = {
+ App: {
+ isForStartupCache: true,
+ },
+ };
+ wrapper = mount(<DSCard {...props} />);
+ });
+
+ it("should be set as isSeen automatically", () => {
+ assert.isTrue(wrapper.instance().state.isSeen);
+ });
+ });
+});
+
+describe("<PlaceholderDSCard> component", () => {
+ it("should have placeholder prop", () => {
+ const wrapper = shallow(<PlaceholderDSCard />);
+ const placeholder = wrapper.prop("placeholder");
+ assert.isTrue(placeholder);
+ });
+
+ it("should contain placeholder div", () => {
+ const wrapper = shallow(<DSCard placeholder={true} {...DEFAULT_PROPS} />);
+ wrapper.setState({ isSeen: true });
+ const card = wrapper.find("div.ds-card.placeholder");
+ assert.lengthOf(card, 1);
+ });
+
+ it("should not be clickable", () => {
+ const wrapper = shallow(<DSCard placeholder={true} {...DEFAULT_PROPS} />);
+ wrapper.setState({ isSeen: true });
+ const anchor = wrapper.find("SafeAnchor.ds-card-link");
+ assert.lengthOf(anchor, 0);
+ });
+
+ it("should not have context menu", () => {
+ const wrapper = shallow(<DSCard placeholder={true} {...DEFAULT_PROPS} />);
+ wrapper.setState({ isSeen: true });
+ const linkMenu = wrapper.find(DSLinkMenu);
+ assert.lengthOf(linkMenu, 0);
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSContextFooter.test.jsx b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSContextFooter.test.jsx
new file mode 100644
index 0000000000..53e129eeef
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSContextFooter.test.jsx
@@ -0,0 +1,145 @@
+import {
+ DSContextFooter,
+ StatusMessage,
+} from "content-src/components/DiscoveryStreamComponents/DSContextFooter/DSContextFooter";
+import React from "react";
+import { mount } from "enzyme";
+import { cardContextTypes } from "content-src/components/Card/types.js";
+import { FluentOrText } from "content-src/components/FluentOrText/FluentOrText.jsx";
+
+describe("<DSContextFooter>", () => {
+ let wrapper;
+ let sandbox;
+ const bookmarkBadge = "bookmark";
+ const removeBookmarkBadge = "removedBookmark";
+ const context = "Sponsored by Babel";
+ const sponsored_by_override = "Sponsored override";
+ const engagement = "Popular";
+
+ beforeEach(() => {
+ wrapper = mount(<DSContextFooter />);
+ sandbox = sinon.createSandbox();
+ });
+
+ afterEach(() => {
+ sandbox.restore();
+ });
+
+ it("should render", () => {
+ assert.isTrue(wrapper.exists());
+ assert.isOk(wrapper.find(".story-footer"));
+ });
+ it("should not render an engagement status if display_engagement_labels is false", () => {
+ wrapper = mount(
+ <DSContextFooter
+ display_engagement_labels={false}
+ engagement={engagement}
+ />
+ );
+
+ const engagementLabel = wrapper.find(".story-view-count");
+ assert.equal(engagementLabel.length, 0);
+ });
+ it("should render an engagement status if no badge and spoc passed", () => {
+ wrapper = mount(
+ <DSContextFooter
+ display_engagement_labels={true}
+ engagement={engagement}
+ />
+ );
+
+ const engagementLabel = wrapper.find(".story-view-count");
+ assert.equal(engagementLabel.text(), engagement);
+ });
+ it("should render a badge if a proper badge prop is passed", () => {
+ wrapper = mount(
+ <DSContextFooter context_type={bookmarkBadge} engagement={engagement} />
+ );
+ const { fluentID } = cardContextTypes[bookmarkBadge];
+
+ assert.lengthOf(wrapper.find(".story-view-count"), 0);
+ const statusLabel = wrapper.find(".story-context-label");
+ assert.equal(statusLabel.prop("data-l10n-id"), fluentID);
+ });
+ it("should only render a sponsored context if pass a sponsored context", async () => {
+ wrapper = mount(
+ <DSContextFooter
+ context_type={bookmarkBadge}
+ context={context}
+ engagement={engagement}
+ />
+ );
+
+ assert.lengthOf(wrapper.find(".story-view-count"), 0);
+ assert.lengthOf(wrapper.find(StatusMessage), 0);
+ assert.equal(wrapper.find(".story-sponsored-label").text(), context);
+ });
+ it("should render a sponsored_by_override if passed a sponsored_by_override", async () => {
+ wrapper = mount(
+ <DSContextFooter
+ context_type={bookmarkBadge}
+ context={context}
+ sponsored_by_override={sponsored_by_override}
+ engagement={engagement}
+ />
+ );
+
+ assert.equal(
+ wrapper.find(".story-sponsored-label").text(),
+ sponsored_by_override
+ );
+ });
+ it("should render nothing with a sponsored_by_override empty string", async () => {
+ wrapper = mount(
+ <DSContextFooter
+ context_type={bookmarkBadge}
+ context={context}
+ sponsored_by_override=""
+ engagement={engagement}
+ />
+ );
+
+ assert.isFalse(wrapper.find(".story-sponsored-label").exists());
+ });
+ it("should render localized string with sponsor with no sponsored_by_override", async () => {
+ wrapper = mount(
+ <DSContextFooter
+ context_type={bookmarkBadge}
+ context={context}
+ sponsor="Nimoy"
+ engagement={engagement}
+ />
+ );
+
+ assert.equal(
+ wrapper
+ .find(".story-sponsored-label")
+ .children()
+ .at(0)
+ .type(),
+ FluentOrText
+ );
+ });
+ it("should render a new badge if props change from an old badge to a new one", async () => {
+ wrapper = mount(<DSContextFooter context_type={bookmarkBadge} />);
+
+ const { fluentID: bookmarkFluentID } = cardContextTypes[bookmarkBadge];
+ const bookmarkStatusMessage = wrapper.find(
+ `div[data-l10n-id='${bookmarkFluentID}']`
+ );
+ assert.isTrue(bookmarkStatusMessage.exists());
+
+ const { fluentID: removeBookmarkFluentID } = cardContextTypes[
+ removeBookmarkBadge
+ ];
+
+ wrapper.setProps({ context_type: removeBookmarkBadge });
+ await wrapper.update();
+
+ assert.isEmpty(bookmarkStatusMessage);
+ const removedBookmarkStatusMessage = wrapper.find(
+ `div[data-l10n-id='${removeBookmarkFluentID}']`
+ );
+ assert.isTrue(removedBookmarkStatusMessage.exists());
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSDismiss.test.jsx b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSDismiss.test.jsx
new file mode 100644
index 0000000000..2f7e206b4f
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSDismiss.test.jsx
@@ -0,0 +1,51 @@
+import { DSDismiss } from "content-src/components/DiscoveryStreamComponents/DSDismiss/DSDismiss";
+import React from "react";
+import { shallow } from "enzyme";
+
+describe("<DSDismiss>", () => {
+ const fakeSpoc = {
+ url: "https://foo.com",
+ guid: "1234",
+ };
+ let wrapper;
+ let sandbox;
+ let onDismissClickStub;
+
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ onDismissClickStub = sandbox.stub();
+ wrapper = shallow(
+ <DSDismiss
+ data={fakeSpoc}
+ onDismissClick={onDismissClickStub}
+ shouldSendImpressionStats={true}
+ />
+ );
+ });
+
+ afterEach(() => {
+ sandbox.restore();
+ });
+
+ it("should render", () => {
+ assert.ok(wrapper.exists());
+ assert.ok(wrapper.find(".ds-dismiss").exists());
+ });
+
+ it("should render proper hover state", () => {
+ wrapper.instance().onHover();
+ assert.ok(wrapper.find(".hovering").exists());
+ wrapper.instance().offHover();
+ assert.ok(!wrapper.find(".hovering").exists());
+ });
+
+ it("should dispatch call onDismissClick", () => {
+ wrapper.instance().onDismissClick();
+ assert.calledOnce(onDismissClickStub);
+ });
+
+ it("should add extra classes", () => {
+ wrapper = shallow(<DSDismiss extraClasses="extra-class" />);
+ assert.ok(wrapper.find(".extra-class").exists());
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSEmptyState.test.jsx b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSEmptyState.test.jsx
new file mode 100644
index 0000000000..6aa8045299
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSEmptyState.test.jsx
@@ -0,0 +1,73 @@
+import { DSEmptyState } from "content-src/components/DiscoveryStreamComponents/DSEmptyState/DSEmptyState";
+import React from "react";
+import { shallow } from "enzyme";
+
+describe("<DSEmptyState>", () => {
+ let wrapper;
+
+ beforeEach(() => {
+ wrapper = shallow(<DSEmptyState />);
+ });
+
+ it("should render", () => {
+ assert.ok(wrapper.exists());
+ assert.ok(wrapper.find(".section-empty-state").exists());
+ });
+
+ it("should render defaultempty state message", () => {
+ assert.ok(wrapper.find(".empty-state-message").exists());
+ const header = wrapper.find(
+ "h2[data-l10n-id='newtab-discovery-empty-section-topstories-header']"
+ );
+ const paragraph = wrapper.find(
+ "p[data-l10n-id='newtab-discovery-empty-section-topstories-content']"
+ );
+
+ assert.ok(header.exists());
+ assert.ok(paragraph.exists());
+ });
+
+ it("should render failed state message", () => {
+ wrapper = shallow(<DSEmptyState status="failed" />);
+ const button = wrapper.find(
+ "button[data-l10n-id='newtab-discovery-empty-section-topstories-try-again-button']"
+ );
+
+ assert.ok(button.exists());
+ });
+
+ it("should render waiting state message", () => {
+ wrapper = shallow(<DSEmptyState status="waiting" />);
+ const button = wrapper.find(
+ "button[data-l10n-id='newtab-discovery-empty-section-topstories-loading']"
+ );
+
+ assert.ok(button.exists());
+ });
+
+ it("should dispatch DISCOVERY_STREAM_RETRY_FEED on failed state button click", () => {
+ const dispatch = sinon.spy();
+
+ wrapper = shallow(
+ <DSEmptyState
+ status="failed"
+ dispatch={dispatch}
+ feed={{ url: "https://foo.com", data: {} }}
+ />
+ );
+ wrapper.find("button.try-again-button").simulate("click");
+
+ assert.calledTwice(dispatch);
+ let [action] = dispatch.firstCall.args;
+ assert.equal(action.type, "DISCOVERY_STREAM_FEED_UPDATE");
+ assert.deepEqual(action.data.feed, {
+ url: "https://foo.com",
+ data: { status: "waiting" },
+ });
+
+ [action] = dispatch.secondCall.args;
+
+ assert.equal(action.type, "DISCOVERY_STREAM_RETRY_FEED");
+ assert.deepEqual(action.data.feed, { url: "https://foo.com", data: {} });
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSImage.test.jsx b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSImage.test.jsx
new file mode 100644
index 0000000000..9f257b400a
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSImage.test.jsx
@@ -0,0 +1,127 @@
+import { DSImage } from "content-src/components/DiscoveryStreamComponents/DSImage/DSImage";
+import { mount } from "enzyme";
+import React from "react";
+
+describe("Discovery Stream <DSImage>", () => {
+ it("should have a child with class ds-image", () => {
+ const img = mount(<DSImage />);
+ const child = img.find(".ds-image");
+
+ assert.lengthOf(child, 1);
+ });
+
+ it("should set proper sources if only `source` is available", () => {
+ const img = mount(<DSImage source="https://placekitten.com/g/640/480" />);
+
+ assert.equal(
+ img.find("img").prop("src"),
+ "https://placekitten.com/g/640/480"
+ );
+ });
+
+ it("should set proper sources if `rawSource` is available", () => {
+ const testSizes = [
+ {
+ mediaMatcher: "(min-width: 1122px)",
+ width: 296,
+ height: 148,
+ },
+
+ {
+ mediaMatcher: "(min-width: 866px)",
+ width: 218,
+ height: 109,
+ },
+
+ {
+ mediaMatcher: "(max-width: 610px)",
+ width: 202,
+ height: 101,
+ },
+ ];
+
+ const img = mount(
+ <DSImage
+ rawSource="https://placekitten.com/g/640/480"
+ sizes={testSizes}
+ />
+ );
+
+ assert.equal(
+ img.find("img").prop("src"),
+ "https://placekitten.com/g/640/480"
+ );
+ assert.equal(
+ img.find("img").prop("srcSet"),
+ [
+ "https://img-getpocket.cdn.mozilla.net/296x148/filters:format(jpeg):quality(60):no_upscale():strip_exif()/https%3A%2F%2Fplacekitten.com%2Fg%2F640%2F480 296w",
+ "https://img-getpocket.cdn.mozilla.net/592x296/filters:format(jpeg):quality(60):no_upscale():strip_exif()/https%3A%2F%2Fplacekitten.com%2Fg%2F640%2F480 592w",
+ "https://img-getpocket.cdn.mozilla.net/218x109/filters:format(jpeg):quality(60):no_upscale():strip_exif()/https%3A%2F%2Fplacekitten.com%2Fg%2F640%2F480 218w",
+ "https://img-getpocket.cdn.mozilla.net/436x218/filters:format(jpeg):quality(60):no_upscale():strip_exif()/https%3A%2F%2Fplacekitten.com%2Fg%2F640%2F480 436w",
+ "https://img-getpocket.cdn.mozilla.net/202x101/filters:format(jpeg):quality(60):no_upscale():strip_exif()/https%3A%2F%2Fplacekitten.com%2Fg%2F640%2F480 202w",
+ "https://img-getpocket.cdn.mozilla.net/404x202/filters:format(jpeg):quality(60):no_upscale():strip_exif()/https%3A%2F%2Fplacekitten.com%2Fg%2F640%2F480 404w",
+ ].join(",")
+ );
+ });
+
+ it("should fall back to unoptimized when optimized failed", () => {
+ const img = mount(
+ <DSImage
+ source="https://placekitten.com/g/640/480"
+ rawSource="https://placekitten.com/g/640/480"
+ />
+ );
+ img.setState({
+ isSeen: true,
+ containerWidth: 640,
+ containerHeight: 480,
+ });
+
+ img.instance().onOptimizedImageError();
+ img.update();
+
+ assert.equal(
+ img.find("img").prop("src"),
+ "https://placekitten.com/g/640/480"
+ );
+ });
+
+ it("should render a placeholder broken image when image failed", () => {
+ const img = mount(<DSImage />);
+ img.setState({ isSeen: true });
+
+ img.instance().onNonOptimizedImageError();
+ img.update();
+
+ assert.equal(img.find("div").prop("className"), "broken-image");
+ });
+
+ it("should update loaded state when seen", () => {
+ const img = mount(
+ <DSImage rawSource="https://placekitten.com/g/640/480" />
+ );
+
+ img.instance().onLoad();
+ assert.propertyVal(img.state(), "isLoaded", true);
+ });
+
+ describe("DSImage with Idle Callback", () => {
+ let wrapper;
+ let windowStub = {
+ requestIdleCallback: sinon.stub().returns(1),
+ cancelIdleCallback: sinon.stub(),
+ };
+ beforeEach(() => {
+ wrapper = mount(<DSImage windowObj={windowStub} />);
+ });
+
+ it("should call requestIdleCallback on componentDidMount", () => {
+ assert.calledOnce(windowStub.requestIdleCallback);
+ });
+
+ it("should call cancelIdleCallback on componentWillUnmount", () => {
+ wrapper.instance().componentWillUnmount();
+ assert.calledOnce(windowStub.cancelIdleCallback);
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSLinkMenu.test.jsx b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSLinkMenu.test.jsx
new file mode 100644
index 0000000000..ba17f99e3a
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSLinkMenu.test.jsx
@@ -0,0 +1,171 @@
+import { mount, shallow } from "enzyme";
+import { DSLinkMenu } from "content-src/components/DiscoveryStreamComponents/DSLinkMenu/DSLinkMenu";
+import { ContextMenuButton } from "content-src/components/ContextMenu/ContextMenuButton";
+import { LinkMenu } from "content-src/components/LinkMenu/LinkMenu";
+import React from "react";
+
+describe("<DSLinkMenu>", () => {
+ let wrapper;
+ let parentNode;
+
+ describe("DS link menu actions", () => {
+ beforeEach(() => {
+ wrapper = mount(<DSLinkMenu />);
+ parentNode = wrapper.getDOMNode().parentNode;
+ });
+
+ afterEach(() => {
+ wrapper.unmount();
+ });
+
+ it("Should remove active on Menu Update", () => {
+ // Add active class name to DSLinkMenu parent node
+ // to simulate menu open state
+ parentNode.classList.add("active");
+ assert.equal(parentNode.className, "active");
+
+ wrapper.instance().onMenuUpdate(false);
+ wrapper.update();
+
+ assert.isEmpty(parentNode.className);
+ });
+
+ it("Should add active on Menu Show", async () => {
+ wrapper.instance().nextAnimationFrame = () => {};
+ await wrapper.instance().onMenuShow();
+ wrapper.update();
+ assert.equal(parentNode.className, "active");
+ });
+
+ it("Should add last-item to support resized window", async () => {
+ const fakeWindow = { scrollMaxX: "20" };
+ wrapper = mount(<DSLinkMenu windowObj={fakeWindow} />);
+ parentNode = wrapper.getDOMNode().parentNode;
+ wrapper.instance().nextAnimationFrame = () => {};
+ await wrapper.instance().onMenuShow();
+ wrapper.update();
+ assert.equal(parentNode.className, "last-item active");
+ });
+
+ it("Should call rAF from nextAnimationFrame", () => {
+ const fakeWindow = { requestAnimationFrame: sinon.stub() };
+ wrapper = mount(<DSLinkMenu windowObj={fakeWindow} />);
+
+ wrapper.instance().nextAnimationFrame();
+ assert.calledOnce(fakeWindow.requestAnimationFrame);
+ });
+
+ it("should remove .active and .last-item classes from the parent component", () => {
+ const instance = wrapper.instance();
+ const remove = sinon.stub();
+ instance.contextMenuButtonRef = {
+ current: {
+ parentElement: { parentElement: { classList: { remove } } },
+ },
+ };
+ instance.onMenuUpdate();
+ assert.calledOnce(remove);
+ });
+
+ it("should add .active and .last-item classes to the parent component", async () => {
+ const instance = wrapper.instance();
+ const add = sinon.stub();
+ instance.nextAnimationFrame = () => {};
+ instance.contextMenuButtonRef = {
+ current: { parentElement: { parentElement: { classList: { add } } } },
+ };
+ await instance.onMenuShow();
+ assert.calledOnce(add);
+ });
+
+ it("should parse args for fluent correctly ", () => {
+ const title = '"fluent"';
+ wrapper = mount(<DSLinkMenu title={title} />);
+
+ const button = wrapper.find(
+ "button[data-l10n-id='newtab-menu-content-tooltip']"
+ );
+ assert.equal(button.prop("data-l10n-args"), JSON.stringify({ title }));
+ });
+ });
+
+ describe("DS context menu options", () => {
+ const ValidDSLinkMenuProps = {
+ site: {},
+ };
+
+ beforeEach(() => {
+ wrapper = shallow(<DSLinkMenu {...ValidDSLinkMenuProps} />);
+ });
+
+ it("should render a context menu button", () => {
+ assert.ok(wrapper.exists());
+ assert.ok(
+ wrapper.find(ContextMenuButton).exists(),
+ "context menu button exists"
+ );
+ });
+
+ it("should render LinkMenu when context menu button is clicked", () => {
+ let button = wrapper.find(ContextMenuButton);
+ button.simulate("click", { preventDefault: () => {} });
+ assert.equal(wrapper.find(LinkMenu).length, 1);
+ });
+
+ it("should pass dispatch, onShow, site, options, shouldSendImpressionStats, source and index to LinkMenu", () => {
+ wrapper
+ .find(ContextMenuButton)
+ .simulate("click", { preventDefault: () => {} });
+ const linkMenuProps = wrapper.find(LinkMenu).props();
+ [
+ "dispatch",
+ "onShow",
+ "site",
+ "index",
+ "options",
+ "source",
+ "shouldSendImpressionStats",
+ ].forEach(prop => assert.property(linkMenuProps, prop));
+ });
+
+ it("should pass through the correct menu options to LinkMenu", () => {
+ wrapper
+ .find(ContextMenuButton)
+ .simulate("click", { preventDefault: () => {} });
+ const linkMenuProps = wrapper.find(LinkMenu).props();
+ assert.deepEqual(linkMenuProps.options, [
+ "CheckBookmarkOrArchive",
+ "CheckSavedToPocket",
+ "Separator",
+ "OpenInNewWindow",
+ "OpenInPrivateWindow",
+ "Separator",
+ "BlockUrl",
+ ]);
+ });
+
+ it("should pass through the correct menu options to LinkMenu for spocs", () => {
+ wrapper = shallow(
+ <DSLinkMenu
+ {...ValidDSLinkMenuProps}
+ flightId="1234"
+ showPrivacyInfo={true}
+ />
+ );
+ wrapper
+ .find(ContextMenuButton)
+ .simulate("click", { preventDefault: () => {} });
+ const linkMenuProps = wrapper.find(LinkMenu).props();
+ assert.deepEqual(linkMenuProps.options, [
+ "CheckBookmarkOrArchive",
+ "CheckSavedToPocket",
+ "Separator",
+ "OpenInNewWindow",
+ "OpenInPrivateWindow",
+ "Separator",
+ "BlockUrl",
+ "ShowPrivacyInfo",
+ ]);
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSMessage.test.jsx b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSMessage.test.jsx
new file mode 100644
index 0000000000..23efa069c9
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSMessage.test.jsx
@@ -0,0 +1,75 @@
+import { DSMessage } from "content-src/components/DiscoveryStreamComponents/DSMessage/DSMessage";
+import React from "react";
+import { SafeAnchor } from "content-src/components/DiscoveryStreamComponents/SafeAnchor/SafeAnchor";
+import { FluentOrText } from "content-src/components/FluentOrText/FluentOrText";
+import { mount } from "enzyme";
+
+describe("<DSMessage>", () => {
+ let wrapper;
+
+ beforeEach(() => {
+ wrapper = mount(<DSMessage />);
+ });
+
+ it("should render", () => {
+ assert.ok(wrapper.exists());
+ assert.ok(wrapper.find(".ds-message").exists());
+ });
+
+ it("should render an icon", () => {
+ wrapper.setProps({ icon: "foo" });
+
+ assert.ok(wrapper.find(".glyph").exists());
+ assert.propertyVal(
+ wrapper.find(".glyph").props().style,
+ "backgroundImage",
+ `url(foo)`
+ );
+ });
+
+ it("should render a title", () => {
+ wrapper.setProps({ title: "foo" });
+
+ assert.ok(wrapper.find(".title-text").exists());
+ assert.equal(wrapper.find(".title-text").text(), "foo");
+ });
+
+ it("should render a SafeAnchor", () => {
+ wrapper.setProps({ link_text: "foo", link_url: "https://foo.com" });
+
+ assert.equal(
+ wrapper
+ .find(".title")
+ .children()
+ .at(0)
+ .type(),
+ SafeAnchor
+ );
+ });
+
+ it("should render a FluentOrText", () => {
+ wrapper.setProps({
+ link_text: "link_text",
+ title: "title",
+ link_url: "https://link_url.com",
+ });
+
+ assert.equal(
+ wrapper
+ .find(".title-text")
+ .children()
+ .at(0)
+ .type(),
+ FluentOrText
+ );
+
+ assert.equal(
+ wrapper
+ .find(".link a")
+ .children()
+ .at(0)
+ .type(),
+ FluentOrText
+ );
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSPrivacyModal.test.jsx b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSPrivacyModal.test.jsx
new file mode 100644
index 0000000000..9db088d7e7
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSPrivacyModal.test.jsx
@@ -0,0 +1,50 @@
+import { DSPrivacyModal } from "content-src/components/DiscoveryStreamComponents/DSPrivacyModal/DSPrivacyModal";
+import { shallow, mount } from "enzyme";
+import { actionCreators as ac } from "common/Actions.jsm";
+import React from "react";
+
+describe("Discovery Stream <DSPrivacyModal>", () => {
+ let sandbox;
+ let dispatch;
+ let wrapper;
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ dispatch = sandbox.stub();
+ wrapper = shallow(<DSPrivacyModal dispatch={dispatch} />);
+ });
+
+ afterEach(() => {
+ sandbox.restore();
+ });
+
+ it("should contain a privacy notice", () => {
+ const modal = mount(<DSPrivacyModal />);
+ const child = modal.find(".privacy-notice");
+
+ assert.lengthOf(child, 1);
+ });
+
+ it("should call dispatch when modal is closed", () => {
+ wrapper.instance().closeModal();
+ assert.calledOnce(dispatch);
+ });
+
+ it("should call dispatch with the correct events for onLearnLinkClick", () => {
+ wrapper.instance().onLearnLinkClick();
+
+ assert.calledOnce(dispatch);
+ assert.calledWith(
+ dispatch,
+ ac.UserEvent({
+ event: "CLICK_PRIVACY_INFO",
+ source: "DS_PRIVACY_MODAL",
+ })
+ );
+ });
+
+ it("should call dispatch with the correct events for onManageLinkClick", () => {
+ wrapper.instance().onManageLinkClick();
+
+ assert.calledOnce(dispatch);
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSSignup.test.jsx b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSSignup.test.jsx
new file mode 100644
index 0000000000..904f98e439
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSSignup.test.jsx
@@ -0,0 +1,92 @@
+import { DSSignup } from "content-src/components/DiscoveryStreamComponents/DSSignup/DSSignup";
+import React from "react";
+import { shallow } from "enzyme";
+
+describe("<DSSignup>", () => {
+ let wrapper;
+ let sandbox;
+ let dispatchStub;
+
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ dispatchStub = sandbox.stub();
+ wrapper = shallow(
+ <DSSignup
+ data={{
+ spocs: [
+ {
+ shim: { impression: "1234" },
+ id: "1234",
+ },
+ ],
+ }}
+ type="SIGNUP"
+ dispatch={dispatchStub}
+ />
+ );
+ });
+
+ afterEach(() => {
+ sandbox.restore();
+ });
+
+ it("should render", () => {
+ assert.ok(wrapper.exists());
+ assert.ok(wrapper.find(".ds-signup").exists());
+ });
+
+ it("should dispatch a click event on click", () => {
+ wrapper.instance().onLinkClick();
+
+ assert.calledTwice(dispatchStub);
+ assert.deepEqual(dispatchStub.firstCall.args[0].data, {
+ event: "CLICK",
+ source: "SIGNUP",
+ action_position: 0,
+ });
+ assert.deepEqual(dispatchStub.secondCall.args[0].data, {
+ source: "SIGNUP",
+ click: 0,
+ tiles: [{ id: "1234", pos: 0 }],
+ });
+ });
+
+ it("Should remove active on Menu Update", () => {
+ wrapper.setState = sandbox.stub();
+ wrapper.instance().onMenuButtonUpdate(false);
+ assert.calledWith(wrapper.setState, { active: false, lastItem: false });
+ });
+
+ it("Should add active on Menu Show", async () => {
+ wrapper.setState = sandbox.stub();
+ wrapper.instance().nextAnimationFrame = () => {};
+ await wrapper.instance().onMenuShow();
+ assert.calledWith(wrapper.setState, { active: true, lastItem: false });
+ });
+
+ it("Should add last-item to support resized window", async () => {
+ const fakeWindow = { scrollMaxX: "20" };
+ wrapper = shallow(<DSSignup windowObj={fakeWindow} />);
+ wrapper.setState = sandbox.stub();
+ wrapper.instance().nextAnimationFrame = () => {};
+ await wrapper.instance().onMenuShow();
+ assert.calledWith(wrapper.setState, { active: true, lastItem: true });
+ });
+
+ it("Should add last-item and active classes", () => {
+ wrapper.setState({
+ active: true,
+ lastItem: true,
+ });
+ assert.ok(wrapper.find(".last-item").exists());
+ assert.ok(wrapper.find(".active").exists());
+ });
+
+ it("Should call rAF from nextAnimationFrame", () => {
+ const fakeWindow = { requestAnimationFrame: sinon.stub() };
+ wrapper = shallow(<DSSignup windowObj={fakeWindow} />);
+
+ wrapper.instance().nextAnimationFrame();
+ assert.calledOnce(fakeWindow.requestAnimationFrame);
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSTextPromo.test.jsx b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSTextPromo.test.jsx
new file mode 100644
index 0000000000..e1e4b6bedf
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/DSTextPromo.test.jsx
@@ -0,0 +1,93 @@
+import { DSTextPromo } from "content-src/components/DiscoveryStreamComponents/DSTextPromo/DSTextPromo";
+import React from "react";
+import { shallow } from "enzyme";
+
+describe("<DSTextPromo>", () => {
+ let wrapper;
+ let sandbox;
+ let dispatchStub;
+
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ dispatchStub = sandbox.stub();
+ wrapper = shallow(
+ <DSTextPromo
+ data={{
+ spocs: [
+ {
+ shim: { impression: "1234" },
+ id: "1234",
+ },
+ ],
+ }}
+ type="TEXTPROMO"
+ dispatch={dispatchStub}
+ />
+ );
+ });
+
+ afterEach(() => {
+ sandbox.restore();
+ });
+
+ it("should render", () => {
+ assert.ok(wrapper.exists());
+ assert.ok(wrapper.find(".ds-text-promo").exists());
+ });
+
+ it("should render a header", () => {
+ wrapper.setProps({ header: "foo" });
+ assert.ok(wrapper.find(".text").exists());
+ });
+
+ it("should render a subtitle", () => {
+ wrapper.setProps({ subtitle: "foo" });
+ assert.ok(wrapper.find(".subtitle").exists());
+ });
+
+ it("should dispatch a click event on click", () => {
+ wrapper.instance().onLinkClick();
+
+ assert.calledTwice(dispatchStub);
+ assert.deepEqual(dispatchStub.firstCall.args[0].data, {
+ event: "CLICK",
+ source: "TEXTPROMO",
+ action_position: 0,
+ });
+ assert.deepEqual(dispatchStub.secondCall.args[0].data, {
+ source: "TEXTPROMO",
+ click: 0,
+ tiles: [{ id: "1234", pos: 0 }],
+ });
+ });
+
+ it("should dispath telemety events on dismiss", () => {
+ wrapper.instance().onDismissClick();
+
+ const firstCall = dispatchStub.getCall(0);
+ const secondCall = dispatchStub.getCall(1);
+ const thirdCall = dispatchStub.getCall(2);
+
+ assert.equal(firstCall.args[0].type, "BLOCK_URL");
+ assert.deepEqual(firstCall.args[0].data, [
+ {
+ url: undefined,
+ pocket_id: undefined,
+ },
+ ]);
+
+ assert.equal(secondCall.args[0].type, "TELEMETRY_USER_EVENT");
+ assert.deepEqual(secondCall.args[0].data, {
+ event: "BLOCK",
+ source: "TEXTPROMO",
+ action_position: 0,
+ });
+
+ assert.equal(thirdCall.args[0].type, "TELEMETRY_IMPRESSION_STATS");
+ assert.deepEqual(thirdCall.args[0].data, {
+ source: "TEXTPROMO",
+ block: 0,
+ tiles: [{ id: "1234", pos: 0 }],
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/Hero.test.jsx b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/Hero.test.jsx
new file mode 100644
index 0000000000..4cfab18b2e
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/Hero.test.jsx
@@ -0,0 +1,179 @@
+import {
+ DSCard,
+ PlaceholderDSCard,
+} from "content-src/components/DiscoveryStreamComponents/DSCard/DSCard";
+import {
+ DSContextFooter,
+ StatusMessage,
+} from "content-src/components/DiscoveryStreamComponents/DSContextFooter/DSContextFooter";
+import { actionCreators as ac } from "common/Actions.jsm";
+import { DSEmptyState } from "content-src/components/DiscoveryStreamComponents/DSEmptyState/DSEmptyState";
+import { Hero } from "content-src/components/DiscoveryStreamComponents/Hero/Hero";
+import { List } from "content-src/components/DiscoveryStreamComponents/List/List";
+import React from "react";
+import { shallow } from "enzyme";
+
+describe("<Hero>", () => {
+ let DEFAULT_PROPS;
+ beforeEach(() => {
+ DEFAULT_PROPS = {
+ data: {
+ recommendations: [{ url: 1 }, { url: 2 }, { url: 3 }],
+ },
+ };
+ });
+
+ it("should render with nothing", () => {
+ const wrapper = shallow(<Hero />);
+
+ assert.lengthOf(wrapper.find("a"), 0);
+ });
+
+ it("should return Empty State for no recommendations", () => {
+ const heroProps = {
+ data: { recommendations: [] },
+ header: { title: "headerTitle" },
+ };
+
+ const wrapper = shallow(<Hero {...heroProps} />);
+ const dsEmptyState = wrapper.find(DSEmptyState);
+ const dsHeader = wrapper.find(".ds-header");
+ const dsHero = wrapper.find(".ds-hero.empty");
+
+ assert.ok(wrapper.exists());
+ assert.lengthOf(dsEmptyState, 1);
+ assert.lengthOf(dsHeader, 1);
+ assert.lengthOf(dsHero, 1);
+ });
+
+ it("should render a hero link with expected url", () => {
+ const wrapper = shallow(<Hero {...DEFAULT_PROPS} />);
+
+ assert.equal(
+ wrapper.find("SafeAnchor").prop("url"),
+ DEFAULT_PROPS.data.recommendations[0].url
+ );
+ });
+
+ it("should render badges for pocket, bookmark when not a spoc element ", () => {
+ const heroProps = {
+ data: { recommendations: [{ context_type: "bookmark" }] },
+ header: { title: "headerTitle" },
+ };
+
+ const wrapper = shallow(<Hero {...heroProps} />);
+ const contextFooter = wrapper.find(DSContextFooter).shallow();
+ assert.lengthOf(contextFooter.find(StatusMessage), 1);
+ });
+
+ it("should render Sponsored Context for a spoc element", () => {
+ const heroProps = {
+ data: {
+ recommendations: [
+ { context_type: "bookmark", context: "Sponsored by Foo" },
+ ],
+ },
+ header: { title: "headerTitle" },
+ };
+ const wrapper = shallow(<Hero {...heroProps} />);
+ const contextFooter = wrapper.find(DSContextFooter).shallow();
+
+ assert.lengthOf(contextFooter.find(StatusMessage), 0);
+ assert.equal(
+ contextFooter.find(".story-sponsored-label").text(),
+ heroProps.data.recommendations[0].context
+ );
+ });
+
+ describe("subComponent: cards", () => {
+ beforeEach(() => {
+ DEFAULT_PROPS.subComponentType = "cards";
+ });
+
+ it("should render no cards for 1 hero item", () => {
+ const wrapper = shallow(<Hero {...DEFAULT_PROPS} items={1} />);
+
+ assert.lengthOf(wrapper.find(DSCard), 0);
+ });
+
+ it("should render 1 card with expected url for 2 hero items", () => {
+ const wrapper = shallow(<Hero {...DEFAULT_PROPS} items={2} />);
+
+ assert.equal(
+ wrapper.find(DSCard).prop("url"),
+ DEFAULT_PROPS.data.recommendations[1].url
+ );
+ });
+
+ it("should return PlaceholderDSCard for recommendations less than items", () => {
+ const wrapper = shallow(<Hero {...DEFAULT_PROPS} items={4} />);
+
+ const dsCard = wrapper.find(DSCard);
+ assert.lengthOf(dsCard, 2);
+
+ const placeholderDSCard = wrapper.find(PlaceholderDSCard);
+ assert.lengthOf(placeholderDSCard, 1);
+ });
+ });
+
+ describe("subComponent: list", () => {
+ beforeEach(() => {
+ DEFAULT_PROPS.subComponentType = "list";
+ });
+
+ it("should render list with no items for 1 hero item", () => {
+ const wrapper = shallow(<Hero {...DEFAULT_PROPS} items={1} />);
+
+ assert.equal(wrapper.find(List).prop("items"), 0);
+ });
+
+ it("should render list with 1 item for 2 hero items", () => {
+ const wrapper = shallow(<Hero {...DEFAULT_PROPS} items={2} />);
+
+ assert.equal(wrapper.find(List).prop("items"), 1);
+ });
+ });
+
+ describe("onLinkClick", () => {
+ let dispatch;
+ let sandbox;
+ let wrapper;
+ const heroProps = {
+ data: { recommendations: [{ url: 1, id: "foo-id", pos: 1 }] },
+ type: "foo",
+ items: 1,
+ };
+
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ dispatch = sandbox.stub();
+ wrapper = shallow(<Hero dispatch={dispatch} {...heroProps} />);
+ });
+
+ afterEach(() => {
+ sandbox.restore();
+ });
+
+ it("should call dispatch with the correct events", () => {
+ wrapper.instance().onLinkClick();
+
+ assert.calledTwice(dispatch);
+ assert.calledWith(
+ dispatch,
+ ac.UserEvent({
+ event: "CLICK",
+ source: "FOO",
+ action_position: 1,
+ })
+ );
+ assert.calledWith(
+ dispatch,
+ ac.ImpressionStats({
+ click: 0,
+ source: "FOO",
+ tiles: [{ id: "foo-id", pos: 1 }],
+ })
+ );
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/Highlights.test.jsx b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/Highlights.test.jsx
new file mode 100644
index 0000000000..99264ecde0
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/Highlights.test.jsx
@@ -0,0 +1,41 @@
+import { combineReducers, createStore } from "redux";
+import { INITIAL_STATE, reducers } from "common/Reducers.jsm";
+import { Highlights } from "content-src/components/DiscoveryStreamComponents/Highlights/Highlights";
+import { mount } from "enzyme";
+import { Provider } from "react-redux";
+import React from "react";
+
+describe("Discovery Stream <Highlights>", () => {
+ let wrapper;
+
+ afterEach(() => {
+ wrapper.unmount();
+ });
+
+ it("should render nothing with no highlights data", () => {
+ const store = createStore(combineReducers(reducers), { ...INITIAL_STATE });
+
+ wrapper = mount(
+ <Provider store={store}>
+ <Highlights />
+ </Provider>
+ );
+
+ assert.ok(wrapper.isEmptyRender());
+ });
+
+ it("should render highlights", () => {
+ const store = createStore(combineReducers(reducers), {
+ ...INITIAL_STATE,
+ Sections: [{ id: "highlights", enabled: true }],
+ });
+
+ wrapper = mount(
+ <Provider store={store}>
+ <Highlights />
+ </Provider>
+ );
+
+ assert.lengthOf(wrapper.find(".ds-highlights"), 1);
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/HorizontalRule.test.jsx b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/HorizontalRule.test.jsx
new file mode 100644
index 0000000000..03538df6f2
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/HorizontalRule.test.jsx
@@ -0,0 +1,16 @@
+import { HorizontalRule } from "content-src/components/DiscoveryStreamComponents/HorizontalRule/HorizontalRule";
+import React from "react";
+import { shallow } from "enzyme";
+
+describe("<HorizontalRule>", () => {
+ let wrapper;
+
+ beforeEach(() => {
+ wrapper = shallow(<HorizontalRule />);
+ });
+
+ it("should render", () => {
+ assert.ok(wrapper.exists());
+ assert.ok(wrapper.find(".ds-hr").exists());
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/ImpressionStats.test.jsx b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/ImpressionStats.test.jsx
new file mode 100644
index 0000000000..8fc3bceeb1
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/ImpressionStats.test.jsx
@@ -0,0 +1,252 @@
+"use strict";
+
+import {
+ ImpressionStats,
+ INTERSECTION_RATIO,
+} from "content-src/components/DiscoveryStreamImpressionStats/ImpressionStats";
+import { actionTypes as at } from "common/Actions.jsm";
+import React from "react";
+import { shallow } from "enzyme";
+
+describe("<ImpressionStats>", () => {
+ const SOURCE = "TEST_SOURCE";
+ const FullIntersectEntries = [
+ { isIntersecting: true, intersectionRatio: INTERSECTION_RATIO },
+ ];
+ const ZeroIntersectEntries = [
+ { isIntersecting: false, intersectionRatio: 0 },
+ ];
+ const PartialIntersectEntries = [
+ { isIntersecting: true, intersectionRatio: INTERSECTION_RATIO / 2 },
+ ];
+
+ // Build IntersectionObserver class with the arg `entries` for the intersect callback.
+ function buildIntersectionObserver(entries) {
+ return class {
+ constructor(callback) {
+ this.callback = callback;
+ }
+
+ observe() {
+ this.callback(entries);
+ }
+
+ unobserve() {}
+ };
+ }
+
+ const DEFAULT_PROPS = {
+ rows: [
+ { id: 1, pos: 0 },
+ { id: 2, pos: 1 },
+ { id: 3, pos: 2 },
+ ],
+ source: SOURCE,
+ IntersectionObserver: buildIntersectionObserver(FullIntersectEntries),
+ document: {
+ visibilityState: "visible",
+ addEventListener: sinon.stub(),
+ removeEventListener: sinon.stub(),
+ },
+ };
+
+ const InnerEl = () => <div>Inner Element</div>;
+
+ function renderImpressionStats(props = {}) {
+ return shallow(
+ <ImpressionStats {...DEFAULT_PROPS} {...props}>
+ <InnerEl />
+ </ImpressionStats>
+ );
+ }
+
+ it("should render props.children", () => {
+ const wrapper = renderImpressionStats();
+ assert.ok(wrapper.contains(<InnerEl />));
+ });
+ it("should not send loaded content nor impression when the page is not visible", () => {
+ const dispatch = sinon.spy();
+ const props = {
+ dispatch,
+ document: {
+ visibilityState: "hidden",
+ addEventListener: sinon.spy(),
+ removeEventListener: sinon.spy(),
+ },
+ };
+ renderImpressionStats(props);
+
+ assert.notCalled(dispatch);
+ });
+ it("should noly send loaded content but not impression when the wrapped item is not visbible", () => {
+ const dispatch = sinon.spy();
+ const props = {
+ dispatch,
+ IntersectionObserver: buildIntersectionObserver(ZeroIntersectEntries),
+ };
+ renderImpressionStats(props);
+
+ // This one is for loaded content.
+ assert.calledOnce(dispatch);
+ const [action] = dispatch.firstCall.args;
+ assert.equal(action.type, at.DISCOVERY_STREAM_LOADED_CONTENT);
+ assert.equal(action.data.source, SOURCE);
+ assert.deepEqual(action.data.tiles, [
+ { id: 1, pos: 0 },
+ { id: 2, pos: 1 },
+ { id: 3, pos: 2 },
+ ]);
+ });
+ it("should not send impression when the wrapped item is visbible but below the ratio", () => {
+ const dispatch = sinon.spy();
+ const props = {
+ dispatch,
+ IntersectionObserver: buildIntersectionObserver(PartialIntersectEntries),
+ };
+ renderImpressionStats(props);
+
+ // This one is for loaded content.
+ assert.calledOnce(dispatch);
+ });
+ it("should send a loaded content and an impression when the page is visible and the wrapped item meets the visibility ratio", () => {
+ const dispatch = sinon.spy();
+ const props = {
+ dispatch,
+ IntersectionObserver: buildIntersectionObserver(FullIntersectEntries),
+ };
+ renderImpressionStats(props);
+
+ assert.calledTwice(dispatch);
+
+ let [action] = dispatch.firstCall.args;
+ assert.equal(action.type, at.DISCOVERY_STREAM_LOADED_CONTENT);
+ assert.equal(action.data.source, SOURCE);
+ assert.deepEqual(action.data.tiles, [
+ { id: 1, pos: 0 },
+ { id: 2, pos: 1 },
+ { id: 3, pos: 2 },
+ ]);
+
+ [action] = dispatch.secondCall.args;
+ assert.equal(action.type, at.DISCOVERY_STREAM_IMPRESSION_STATS);
+ assert.equal(action.data.source, SOURCE);
+ assert.deepEqual(action.data.tiles, [
+ { id: 1, pos: 0 },
+ { id: 2, pos: 1 },
+ { id: 3, pos: 2 },
+ ]);
+ });
+ it("should send a DISCOVERY_STREAM_SPOC_IMPRESSION when the wrapped item has a flightId", () => {
+ const dispatch = sinon.spy();
+ const flightId = "a_flight_id";
+ const props = {
+ dispatch,
+ flightId,
+ IntersectionObserver: buildIntersectionObserver(FullIntersectEntries),
+ };
+ renderImpressionStats(props);
+
+ // Loaded content + DISCOVERY_STREAM_SPOC_IMPRESSION + impression
+ assert.calledThrice(dispatch);
+
+ const [action] = dispatch.secondCall.args;
+ assert.equal(action.type, at.DISCOVERY_STREAM_SPOC_IMPRESSION);
+ assert.deepEqual(action.data, { flightId });
+ });
+ it("should send an impression when the wrapped item transiting from invisible to visible", () => {
+ const dispatch = sinon.spy();
+ const props = {
+ dispatch,
+ IntersectionObserver: buildIntersectionObserver(ZeroIntersectEntries),
+ };
+ const wrapper = renderImpressionStats(props);
+
+ // For the loaded content
+ assert.calledOnce(dispatch);
+
+ let [action] = dispatch.firstCall.args;
+ assert.equal(action.type, at.DISCOVERY_STREAM_LOADED_CONTENT);
+ assert.equal(action.data.source, SOURCE);
+ assert.deepEqual(action.data.tiles, [
+ { id: 1, pos: 0 },
+ { id: 2, pos: 1 },
+ { id: 3, pos: 2 },
+ ]);
+
+ dispatch.resetHistory();
+ wrapper.instance().impressionObserver.callback(FullIntersectEntries);
+
+ // For the impression
+ assert.calledOnce(dispatch);
+
+ [action] = dispatch.firstCall.args;
+ assert.equal(action.type, at.DISCOVERY_STREAM_IMPRESSION_STATS);
+ assert.deepEqual(action.data.tiles, [
+ { id: 1, pos: 0 },
+ { id: 2, pos: 1 },
+ { id: 3, pos: 2 },
+ ]);
+ });
+ it("should remove visibility change listener when the wrapper is removed", () => {
+ const props = {
+ dispatch: sinon.spy(),
+ document: {
+ visibilityState: "hidden",
+ addEventListener: sinon.spy(),
+ removeEventListener: sinon.spy(),
+ },
+ IntersectionObserver,
+ };
+
+ const wrapper = renderImpressionStats(props);
+ assert.calledWith(props.document.addEventListener, "visibilitychange");
+ const [, listener] = props.document.addEventListener.firstCall.args;
+
+ wrapper.unmount();
+ assert.calledWith(
+ props.document.removeEventListener,
+ "visibilitychange",
+ listener
+ );
+ });
+ it("should unobserve the intersection observer when the wrapper is removed", () => {
+ const IntersectionObserver = buildIntersectionObserver(
+ ZeroIntersectEntries
+ );
+ const spy = sinon.spy(IntersectionObserver.prototype, "unobserve");
+ const props = { dispatch: sinon.spy(), IntersectionObserver };
+
+ const wrapper = renderImpressionStats(props);
+ wrapper.unmount();
+
+ assert.calledOnce(spy);
+ });
+ it("should only send the latest impression on a visibility change", () => {
+ const listeners = new Set();
+ const props = {
+ dispatch: sinon.spy(),
+ document: {
+ visibilityState: "hidden",
+ addEventListener: (ev, cb) => listeners.add(cb),
+ removeEventListener: (ev, cb) => listeners.delete(cb),
+ },
+ };
+
+ const wrapper = renderImpressionStats(props);
+
+ // Update twice
+ wrapper.setProps({ ...props, ...{ rows: [{ id: 123, pos: 4 }] } });
+ wrapper.setProps({ ...props, ...{ rows: [{ id: 2432, pos: 5 }] } });
+
+ assert.notCalled(props.dispatch);
+
+ // Simulate listeners getting called
+ props.document.visibilityState = "visible";
+ listeners.forEach(l => l());
+
+ // Make sure we only sent the latest event
+ assert.calledTwice(props.dispatch);
+ const [action] = props.dispatch.firstCall.args;
+ assert.deepEqual(action.data.tiles, [{ id: 2432, pos: 5 }]);
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/List.test.jsx b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/List.test.jsx
new file mode 100644
index 0000000000..38ef76adf3
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/List.test.jsx
@@ -0,0 +1,278 @@
+import {
+ _List as List,
+ ListItem,
+ PlaceholderListItem,
+} from "content-src/components/DiscoveryStreamComponents/List/List";
+import { actionCreators as ac } from "common/Actions.jsm";
+import {
+ DSContextFooter,
+ StatusMessage,
+} from "content-src/components/DiscoveryStreamComponents/DSContextFooter/DSContextFooter";
+import { DSEmptyState } from "content-src/components/DiscoveryStreamComponents/DSEmptyState/DSEmptyState";
+import { DSLinkMenu } from "content-src/components/DiscoveryStreamComponents/DSLinkMenu/DSLinkMenu";
+import { GlobalOverrider } from "test/unit/utils";
+import React from "react";
+import { shallow } from "enzyme";
+
+describe("<List> presentation component", () => {
+ const ValidRecommendations = [
+ { url: 1 },
+ { url: 2 },
+ { context: "test spoc", url: 3 },
+ ];
+ const ValidListProps = {
+ data: {
+ recommendations: ValidRecommendations,
+ },
+ feed: {
+ url: "fakeFeedUrl",
+ },
+ header: {
+ title: "fakeFeedTitle",
+ },
+ };
+
+ it("should return null if feed.data is falsy", () => {
+ const ListProps = {
+ data: { feeds: { a: "stuff" } },
+ };
+
+ const wrapper = shallow(<List {...ListProps} />);
+ assert.isNull(wrapper.getElement());
+ });
+
+ it("should return Empty State for no recommendations", () => {
+ const ListProps = {
+ data: { recommendations: [] },
+ header: { title: "headerTitle" },
+ };
+
+ const wrapper = shallow(<List {...ListProps} />);
+ const dsEmptyState = wrapper.find(DSEmptyState);
+ const dsHeader = wrapper.find(".ds-header");
+ const dsList = wrapper.find(".ds-list.empty");
+
+ assert.ok(wrapper.exists());
+ assert.lengthOf(dsEmptyState, 1);
+ assert.lengthOf(dsHeader, 1);
+ assert.lengthOf(dsList, 1);
+ });
+
+ it("should return something containing a <ul> if props are valid", () => {
+ const wrapper = shallow(<List {...ValidListProps} />);
+
+ const list = wrapper.find("ul");
+ assert.ok(wrapper.exists());
+ assert.lengthOf(list, 1);
+ });
+
+ it("should return the right number of ListItems if props are valid", () => {
+ const wrapper = shallow(<List {...ValidListProps} />);
+
+ const listItem = wrapper.find(ListItem);
+ assert.lengthOf(listItem, ValidRecommendations.length);
+ });
+
+ it("should return fewer ListItems for fewer items", () => {
+ const wrapper = shallow(<List {...ValidListProps} items={1} />);
+
+ const listItem = wrapper.find(ListItem);
+ assert.lengthOf(listItem, 1);
+ });
+
+ it("should return PlaceHolderListItem for recommendations less than items", () => {
+ const wrapper = shallow(<List {...ValidListProps} items={4} />);
+
+ const listItem = wrapper.find(ListItem);
+ assert.lengthOf(listItem, 3);
+
+ const placeholderListItem = wrapper.find(PlaceholderListItem);
+ assert.lengthOf(placeholderListItem, 1);
+ });
+
+ it("should return fewer ListItems for starting point", () => {
+ const wrapper = shallow(<List {...ValidListProps} recStartingPoint={1} />);
+
+ const listItem = wrapper.find(ListItem);
+ assert.lengthOf(listItem, ValidRecommendations.length - 1);
+ });
+
+ it("should return expected ListItems when offset", () => {
+ const wrapper = shallow(
+ <List {...ValidListProps} items={2} recStartingPoint={1} />
+ );
+
+ const listItemUrls = wrapper.find(ListItem).map(i => i.prop("url"));
+ assert.sameOrderedMembers(listItemUrls, [
+ ValidRecommendations[1].url,
+ ValidRecommendations[2].url,
+ ]);
+ });
+
+ it("should return expected spoc ListItem", () => {
+ const wrapper = shallow(
+ <List {...ValidListProps} items={3} recStartingPoint={0} />
+ );
+
+ const listItemContext = wrapper.find(ListItem).map(i => i.prop("context"));
+ assert.sameOrderedMembers(listItemContext, [
+ undefined,
+ undefined,
+ ValidRecommendations[2].context,
+ ]);
+ });
+});
+
+describe("<ListItem> presentation component", () => {
+ const ValidListItemProps = {
+ url: "FAKE_URL",
+ title: "FAKE_TITLE",
+ domain: "example.com",
+ image_src: "FAKE_IMAGE_SRC",
+ context_type: "pocket",
+ };
+ const ValidSpocListItemProps = {
+ url: "FAKE_URL",
+ title: "FAKE_TITLE",
+ domain: "example.com",
+ image_src: "FAKE_IMAGE_SRC",
+ context_type: "pocket",
+ context: "FAKE_CONTEXT",
+ };
+ let globals;
+
+ beforeEach(() => {
+ globals = new GlobalOverrider();
+ });
+
+ afterEach(() => {
+ globals.sandbox.restore();
+ });
+
+ it("should contain 'a.ds-list-item-link' with the props.url set", () => {
+ const wrapper = shallow(<ListItem {...ValidListItemProps} />);
+
+ const anchors = wrapper.find(
+ `SafeAnchor.ds-list-item-link[url="${ValidListItemProps.url}"]`
+ );
+ assert.lengthOf(anchors, 1);
+ });
+
+ it("should render badges for pocket, bookmark when not a spoc element ", () => {
+ const wrapper = shallow(<ListItem {...ValidListItemProps} />);
+ const contextFooter = wrapper.find(DSContextFooter).shallow();
+
+ assert.lengthOf(contextFooter.find(StatusMessage), 1);
+ });
+
+ it("should render Sponsored Context for a spoc element", () => {
+ const wrapper = shallow(<ListItem {...ValidSpocListItemProps} />);
+ const contextFooter = wrapper.find(DSContextFooter).shallow();
+
+ assert.lengthOf(contextFooter.find(StatusMessage), 0);
+ assert.equal(
+ contextFooter.find(".story-sponsored-label").text(),
+ ValidSpocListItemProps.context
+ );
+ });
+
+ describe("onLinkClick", () => {
+ let dispatch;
+ let sandbox;
+ let wrapper;
+
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ dispatch = sandbox.stub();
+ wrapper = shallow(
+ <ListItem dispatch={dispatch} {...ValidListItemProps} />
+ );
+ });
+
+ afterEach(() => {
+ sandbox.restore();
+ });
+
+ it("should call dispatch with the correct events", () => {
+ wrapper.setProps({ id: "foo-id", pos: 1, type: "foo" });
+
+ wrapper.instance().onLinkClick();
+
+ assert.calledTwice(dispatch);
+ assert.calledWith(
+ dispatch,
+ ac.UserEvent({
+ event: "CLICK",
+ source: "FOO",
+ action_position: 1,
+ value: { card_type: "organic" },
+ })
+ );
+ assert.calledWith(
+ dispatch,
+ ac.ImpressionStats({
+ click: 0,
+ source: "FOO",
+ tiles: [{ id: "foo-id", pos: 1 }],
+ })
+ );
+ });
+
+ it("should set the right card_type on spocs", () => {
+ wrapper.setProps({ id: "foo-id", pos: 1, type: "foo", flightId: 12345 });
+
+ wrapper.instance().onLinkClick();
+
+ assert.calledTwice(dispatch);
+ assert.calledWith(
+ dispatch,
+ ac.UserEvent({
+ event: "CLICK",
+ source: "FOO",
+ action_position: 1,
+ value: { card_type: "spoc" },
+ })
+ );
+ assert.calledWith(
+ dispatch,
+ ac.ImpressionStats({
+ click: 0,
+ source: "FOO",
+ tiles: [{ id: "foo-id", pos: 1 }],
+ })
+ );
+ });
+ });
+});
+
+describe("<PlaceholderListItem> component", () => {
+ it("should have placeholder prop", () => {
+ const wrapper = shallow(<PlaceholderListItem />);
+ const listItem = wrapper.find(ListItem);
+ assert.lengthOf(listItem, 1);
+
+ const placeholder = wrapper.find(ListItem).prop("placeholder");
+ assert.isTrue(placeholder);
+ });
+
+ it("should contain placeholder listitem", () => {
+ const wrapper = shallow(<ListItem placeholder={true} />);
+ const listItem = wrapper.find("li.ds-list-item.placeholder");
+ assert.lengthOf(listItem, 1);
+ });
+
+ it("should not be clickable", () => {
+ const wrapper = shallow(<ListItem placeholder={true} />);
+ const anchor = wrapper.find("SafeAnchor.ds-list-item-link");
+ assert.lengthOf(anchor, 1);
+
+ const linkClick = anchor.prop("onLinkClick");
+ assert.isUndefined(linkClick);
+ });
+
+ it("should not have context menu", () => {
+ const wrapper = shallow(<ListItem placeholder={true} />);
+ const linkMenu = wrapper.find(DSLinkMenu);
+ assert.lengthOf(linkMenu, 0);
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/Navigation.test.jsx b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/Navigation.test.jsx
new file mode 100644
index 0000000000..2d19ef45f8
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/Navigation.test.jsx
@@ -0,0 +1,119 @@
+import {
+ Navigation,
+ Topic,
+} from "content-src/components/DiscoveryStreamComponents/Navigation/Navigation";
+import React from "react";
+import { SafeAnchor } from "content-src/components/DiscoveryStreamComponents/SafeAnchor/SafeAnchor";
+import { FluentOrText } from "content-src/components/FluentOrText/FluentOrText";
+import { shallow, mount } from "enzyme";
+
+const DEFAULT_PROPS = {
+ App: {
+ isForStartupCache: false,
+ },
+};
+
+describe("<Navigation>", () => {
+ let wrapper;
+
+ beforeEach(() => {
+ wrapper = mount(<Navigation header={{}} />);
+ });
+
+ it("should render", () => {
+ assert.ok(wrapper.exists());
+ });
+
+ it("should render a title", () => {
+ wrapper.setProps({ header: { title: "Foo" } });
+
+ assert.equal(wrapper.find(".ds-navigation-header").text(), "Foo");
+ });
+
+ it("should not render a title", () => {
+ wrapper.setProps({ header: null });
+
+ assert.lengthOf(wrapper.find(".ds-navigation-header"), 0);
+ });
+
+ it("should set default alignment", () => {
+ assert.lengthOf(wrapper.find(".ds-navigation-centered"), 1);
+ });
+
+ it("should set custom alignment", () => {
+ wrapper.setProps({ alignment: "left-align" });
+
+ assert.lengthOf(wrapper.find(".ds-navigation-left-align"), 1);
+ });
+
+ it("should set default of no links", () => {
+ assert.lengthOf(wrapper.find("ul").children(), 0);
+ });
+
+ it("should render a FluentOrText", () => {
+ wrapper.setProps({ header: { title: "Foo" } });
+
+ assert.equal(
+ wrapper
+ .find(".ds-navigation")
+ .children()
+ .at(0)
+ .type(),
+ FluentOrText
+ );
+ });
+
+ it("should render 2 Topics", () => {
+ wrapper.setProps({
+ links: [
+ { url: "https://foo.com", name: "foo" },
+ { url: "https://bar.com", name: "bar" },
+ ],
+ });
+
+ assert.lengthOf(wrapper.find("ul").children(), 2);
+ });
+});
+
+describe("<Topic>", () => {
+ let wrapper;
+ let sandbox;
+
+ beforeEach(() => {
+ wrapper = shallow(<Topic url="https://foo.com" name="foo" />);
+ sandbox = sinon.createSandbox();
+ });
+
+ afterEach(() => {
+ sandbox.restore();
+ });
+
+ it("should pass onLinkClick prop", () => {
+ assert.propertyVal(
+ wrapper.at(0).props(),
+ "onLinkClick",
+ wrapper.instance().onLinkClick
+ );
+ });
+
+ it("should render", () => {
+ assert.ok(wrapper.exists());
+ assert.equal(wrapper.type(), SafeAnchor);
+ });
+
+ describe("onLinkClick", () => {
+ let dispatch;
+
+ beforeEach(() => {
+ dispatch = sandbox.stub();
+ wrapper = shallow(<Topic dispatch={dispatch} {...DEFAULT_PROPS} />);
+ wrapper.setState({ isSeen: true });
+ });
+
+ it("should call dispatch", () => {
+ wrapper.instance().onLinkClick({ target: { text: `Must Reads` } });
+
+ assert.calledOnce(dispatch);
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/SafeAnchor.test.jsx b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/SafeAnchor.test.jsx
new file mode 100644
index 0000000000..5d643869b8
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/SafeAnchor.test.jsx
@@ -0,0 +1,56 @@
+import React from "react";
+import { SafeAnchor } from "content-src/components/DiscoveryStreamComponents/SafeAnchor/SafeAnchor";
+import { shallow } from "enzyme";
+
+describe("Discovery Stream <SafeAnchor>", () => {
+ let warnStub;
+ let sandbox;
+ beforeEach(() => {
+ warnStub = sinon.stub(console, "warn");
+ sandbox = sinon.createSandbox();
+ });
+ afterEach(() => {
+ warnStub.restore();
+ sandbox.restore();
+ });
+ it("should render with anchor", () => {
+ const wrapper = shallow(<SafeAnchor />);
+ assert.lengthOf(wrapper.find("a"), 1);
+ });
+ it("should render with anchor target for http", () => {
+ const wrapper = shallow(<SafeAnchor url="http://example.com" />);
+ assert.equal(wrapper.find("a").prop("href"), "http://example.com");
+ });
+ it("should render with anchor target for https", () => {
+ const wrapper = shallow(<SafeAnchor url="https://example.com" />);
+ assert.equal(wrapper.find("a").prop("href"), "https://example.com");
+ });
+ it("should not allow javascript: URIs", () => {
+ const wrapper = shallow(<SafeAnchor url="javascript:foo()" />); // eslint-disable-line no-script-url
+ assert.equal(wrapper.find("a").prop("href"), "");
+ assert.calledOnce(warnStub);
+ });
+ it("should not warn if the URL is falsey ", () => {
+ const wrapper = shallow(<SafeAnchor url="" />);
+ assert.equal(wrapper.find("a").prop("href"), "");
+ assert.notCalled(warnStub);
+ });
+ it("should dispatch an event on click", () => {
+ const dispatchStub = sandbox.stub();
+ const fakeEvent = { preventDefault: sandbox.stub(), currentTarget: {} };
+ const wrapper = shallow(<SafeAnchor dispatch={dispatchStub} />);
+
+ wrapper.find("a").simulate("click", fakeEvent);
+
+ assert.calledOnce(dispatchStub);
+ assert.calledOnce(fakeEvent.preventDefault);
+ });
+ it("should call onLinkClick if provided", () => {
+ const onLinkClickStub = sandbox.stub();
+ const wrapper = shallow(<SafeAnchor onLinkClick={onLinkClickStub} />);
+
+ wrapper.find("a").simulate("click");
+
+ assert.calledOnce(onLinkClickStub);
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/SectionTitle.test.jsx b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/SectionTitle.test.jsx
new file mode 100644
index 0000000000..b5ea007022
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/SectionTitle.test.jsx
@@ -0,0 +1,22 @@
+import React from "react";
+import { SectionTitle } from "content-src/components/DiscoveryStreamComponents/SectionTitle/SectionTitle";
+import { shallow } from "enzyme";
+
+describe("<SectionTitle>", () => {
+ let wrapper;
+
+ beforeEach(() => {
+ wrapper = shallow(<SectionTitle header={{}} />);
+ });
+
+ it("should render", () => {
+ assert.ok(wrapper.exists());
+ assert.ok(wrapper.find(".ds-section-title").exists());
+ });
+
+ it("should render a subtitle", () => {
+ wrapper.setProps({ header: { title: "Foo", subtitle: "Bar" } });
+
+ assert.equal(wrapper.find(".subtitle").text(), "Bar");
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/TopSites.test.jsx b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/TopSites.test.jsx
new file mode 100644
index 0000000000..4c944010be
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/DiscoveryStreamComponents/TopSites.test.jsx
@@ -0,0 +1,247 @@
+import { combineReducers, createStore } from "redux";
+import {
+ INITIAL_STATE,
+ reducers,
+ TOP_SITES_DEFAULT_ROWS,
+} from "common/Reducers.jsm";
+import { mount } from "enzyme";
+import { TopSites as OldTopSites } from "content-src/components/TopSites/TopSites";
+import { Provider } from "react-redux";
+import React from "react";
+import {
+ TopSites as TopSitesContainer,
+ _TopSites as TopSites,
+} from "content-src/components/DiscoveryStreamComponents/TopSites/TopSites";
+
+describe("Discovery Stream <TopSites>", () => {
+ let wrapper;
+ let store;
+ const defaultTopSiteRows = [
+ { label: "facebook" },
+ { label: "amazon" },
+ { label: "google" },
+ { label: "apple" },
+ ];
+ const defaultTopSites = {
+ rows: defaultTopSiteRows,
+ };
+
+ beforeEach(() => {
+ INITIAL_STATE.Prefs.values.topSitesRows = TOP_SITES_DEFAULT_ROWS;
+ store = createStore(combineReducers(reducers), INITIAL_STATE);
+ wrapper = mount(
+ <Provider store={store}>
+ <TopSitesContainer TopSites={defaultTopSites} />
+ </Provider>
+ );
+ });
+
+ afterEach(() => {
+ wrapper.unmount();
+ });
+
+ it("should return a wrapper around old TopSites", () => {
+ const oldTopSites = wrapper.find(OldTopSites);
+ const dsTopSitesWrapper = wrapper.find(".ds-top-sites");
+
+ assert.ok(wrapper.exists());
+ assert.lengthOf(oldTopSites, 1);
+ assert.lengthOf(dsTopSitesWrapper, 1);
+ });
+
+ describe("TopSites header", () => {
+ it("should have header title undefined by default", () => {
+ const oldTopSites = wrapper.find(OldTopSites);
+ assert.isUndefined(oldTopSites.props().title);
+ });
+
+ it("should set header title on old TopSites", () => {
+ let DEFAULT_PROPS = {
+ header: { title: "test" },
+ };
+ wrapper = mount(
+ <Provider store={store}>
+ <TopSitesContainer {...DEFAULT_PROPS} />
+ </Provider>
+ );
+ const oldTopSites = wrapper.find(OldTopSites);
+ assert.equal(oldTopSites.props().title, "test");
+ });
+ });
+
+ describe("insertSpocContent", () => {
+ let insertSpocContent;
+ const topSiteSpoc = {
+ url: "foo",
+ sponsor: "bar",
+ image_src: "foobar",
+ flight_id: "1234",
+ id: "5678",
+ shim: { impression: "1011" },
+ };
+ const data = { spocs: [topSiteSpoc] };
+ const resultSpocLeft = {
+ customScreenshotURL: "foobar",
+ type: "SPOC",
+ label: "bar",
+ title: "bar",
+ url: "foo",
+ flightId: "1234",
+ id: "5678",
+ guid: "5678",
+ shim: {
+ impression: "1011",
+ },
+ pos: 0,
+ };
+ const resultSpocRight = {
+ customScreenshotURL: "foobar",
+ type: "SPOC",
+ label: "bar",
+ title: "bar",
+ url: "foo",
+ flightId: "1234",
+ id: "5678",
+ guid: "5678",
+ shim: {
+ impression: "1011",
+ },
+ pos: 7,
+ };
+ const pinnedSite = {
+ label: "pinnedSite",
+ isPinned: true,
+ };
+
+ beforeEach(() => {
+ const instance = wrapper.find(TopSites).instance();
+ insertSpocContent = instance.insertSpocContent.bind(instance);
+ });
+
+ it("Should return null if no data or no TopSites", () => {
+ assert.isNull(insertSpocContent(defaultTopSites, {}, "right"));
+ assert.isNull(insertSpocContent({}, data, "right"));
+ });
+
+ it("Should return null if an organic SPOC topsite exists", () => {
+ const topSitesWithOrganicSpoc = {
+ rows: [...defaultTopSiteRows, topSiteSpoc],
+ };
+
+ assert.isNull(insertSpocContent(topSitesWithOrganicSpoc, data, "right"));
+ });
+
+ it("Should return next spoc if the first SPOC is an existing organic top site", () => {
+ const topSitesWithOrganicSpoc = {
+ rows: [...defaultTopSiteRows, topSiteSpoc],
+ };
+ const extraSpocData = {
+ spocs: [
+ topSiteSpoc,
+ {
+ url: "foo2",
+ sponsor: "bar2",
+ image_src: "foobar2",
+ flight_id: "1234",
+ id: "5678",
+ shim: { impression: "1011" },
+ },
+ ],
+ };
+
+ const result = insertSpocContent(
+ topSitesWithOrganicSpoc,
+ extraSpocData,
+ "right"
+ );
+
+ const availableSpoc = {
+ customScreenshotURL: "foobar2",
+ type: "SPOC",
+ label: "bar2",
+ title: "bar2",
+ url: "foo2",
+ flightId: "1234",
+ id: "5678",
+ guid: "5678",
+ shim: {
+ impression: "1011",
+ },
+ pos: 7,
+ };
+ const expectedResult = {
+ rows: [...topSitesWithOrganicSpoc.rows, availableSpoc],
+ };
+
+ assert.deepEqual(result, expectedResult);
+ });
+
+ it("should add to end of row if the row is not full and alignment is right", () => {
+ const result = insertSpocContent(defaultTopSites, data, "right");
+
+ const expectedResult = {
+ rows: [...defaultTopSiteRows, resultSpocRight],
+ };
+ assert.deepEqual(result, expectedResult);
+ });
+
+ it("should add to front of row if the row is not full and alignment is left", () => {
+ const result = insertSpocContent(defaultTopSites, data, "left");
+ assert.deepEqual(result, {
+ rows: [resultSpocLeft, ...defaultTopSiteRows],
+ });
+ });
+
+ it("should add to first available in the front row if alignment is left and there are pins", () => {
+ const topSiteRowsWithPins = [
+ pinnedSite,
+ pinnedSite,
+ ...defaultTopSiteRows,
+ ];
+
+ const result = insertSpocContent(
+ { rows: topSiteRowsWithPins },
+ data,
+ "left"
+ );
+
+ assert.deepEqual(result, {
+ rows: [pinnedSite, pinnedSite, resultSpocLeft, ...defaultTopSiteRows],
+ });
+ });
+
+ it("should add to first available in the next row if alignment is right and there are all pins in the front row", () => {
+ const pinnedArray = new Array(8).fill(pinnedSite);
+ const result = insertSpocContent({ rows: pinnedArray }, data, "right");
+
+ assert.deepEqual(result, {
+ rows: [...pinnedArray, resultSpocRight],
+ });
+ });
+
+ it("should add to first available in the current row if alignment is right and there are some pins in the front row", () => {
+ const pinnedArray = new Array(6).fill(pinnedSite);
+ const topSite = { label: "foo" };
+
+ const rowsWithPins = [topSite, topSite, ...pinnedArray];
+
+ const result = insertSpocContent({ rows: rowsWithPins }, data, "right");
+
+ assert.deepEqual(result, {
+ rows: [topSite, resultSpocRight, ...pinnedArray, topSite],
+ });
+ });
+
+ it("should preserve the indices of pinned items", () => {
+ const topSite = { label: "foo" };
+ const rowsWithPins = [pinnedSite, topSite, topSite, pinnedSite];
+
+ const result = insertSpocContent({ rows: rowsWithPins }, data, "left");
+
+ // Pinned items should retain in Index 0 and Index 3 like defined in rowsWithPins
+ assert.deepEqual(result, {
+ rows: [pinnedSite, resultSpocLeft, topSite, pinnedSite, topSite],
+ });
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/components/ErrorBoundary.test.jsx b/browser/components/newtab/test/unit/content-src/components/ErrorBoundary.test.jsx
new file mode 100644
index 0000000000..99cc8b0ca7
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/ErrorBoundary.test.jsx
@@ -0,0 +1,110 @@
+import { A11yLinkButton } from "content-src/components/A11yLinkButton/A11yLinkButton";
+import {
+ ErrorBoundary,
+ ErrorBoundaryFallback,
+} from "content-src/components/ErrorBoundary/ErrorBoundary";
+import React from "react";
+import { shallow } from "enzyme";
+
+describe("<ErrorBoundary>", () => {
+ it("should render its children if componentDidCatch wasn't called", () => {
+ const wrapper = shallow(
+ <ErrorBoundary>
+ <div className="kids" />
+ </ErrorBoundary>
+ );
+
+ assert.lengthOf(wrapper.find(".kids"), 1);
+ });
+
+ it("should render ErrorBoundaryFallback if componentDidCatch called", () => {
+ const wrapper = shallow(<ErrorBoundary />);
+
+ wrapper.instance().componentDidCatch();
+ // since shallow wrappers don't automatically manage lifecycle semantics:
+ wrapper.update();
+
+ assert.lengthOf(wrapper.find(ErrorBoundaryFallback), 1);
+ });
+
+ it("should render the given FallbackComponent if componentDidCatch called", () => {
+ class TestFallback extends React.PureComponent {
+ render() {
+ return <div className="my-fallback">doh!</div>;
+ }
+ }
+
+ const wrapper = shallow(<ErrorBoundary FallbackComponent={TestFallback} />);
+ wrapper.instance().componentDidCatch();
+ // since shallow wrappers don't automatically manage lifecycle semantics:
+ wrapper.update();
+
+ assert.lengthOf(wrapper.find(TestFallback), 1);
+ });
+
+ it("should pass the given className prop to the FallbackComponent", () => {
+ class TestFallback extends React.PureComponent {
+ render() {
+ return <div className={this.props.className}>doh!</div>;
+ }
+ }
+
+ const wrapper = shallow(
+ <ErrorBoundary FallbackComponent={TestFallback} className="sheep" />
+ );
+ wrapper.instance().componentDidCatch();
+ // since shallow wrappers don't automatically manage lifecycle semantics:
+ wrapper.update();
+
+ assert.lengthOf(wrapper.find(".sheep"), 1);
+ });
+});
+
+describe("ErrorBoundaryFallback", () => {
+ it("should render a <div> with a class of as-error-fallback", () => {
+ const wrapper = shallow(<ErrorBoundaryFallback />);
+
+ assert.lengthOf(wrapper.find("div.as-error-fallback"), 1);
+ });
+
+ it("should render a <div> with the props.className and .as-error-fallback", () => {
+ const wrapper = shallow(<ErrorBoundaryFallback className="monkeys" />);
+
+ assert.lengthOf(wrapper.find("div.monkeys.as-error-fallback"), 1);
+ });
+
+ it("should call window.location.reload(true) if .reload-button clicked", () => {
+ const fakeWindow = { location: { reload: sinon.spy() } };
+ const wrapper = shallow(<ErrorBoundaryFallback windowObj={fakeWindow} />);
+
+ wrapper.find(".reload-button").simulate("click");
+
+ assert.calledOnce(fakeWindow.location.reload);
+ assert.calledWithExactly(fakeWindow.location.reload, true);
+ });
+
+ it("should render .reload-button as an <A11yLinkButton>", () => {
+ const wrapper = shallow(<ErrorBoundaryFallback />);
+
+ assert.lengthOf(wrapper.find("A11yLinkButton.reload-button"), 1);
+ });
+
+ it("should render newtab-error-fallback-refresh-link node", () => {
+ const wrapper = shallow(<ErrorBoundaryFallback />);
+
+ const msgWrapper = wrapper.find(
+ '[data-l10n-id="newtab-error-fallback-refresh-link"]'
+ );
+ assert.lengthOf(msgWrapper, 1);
+ assert.isTrue(msgWrapper.is(A11yLinkButton));
+ });
+
+ it("should render newtab-error-fallback-info node", () => {
+ const wrapper = shallow(<ErrorBoundaryFallback />);
+
+ const msgWrapper = wrapper.find(
+ '[data-l10n-id="newtab-error-fallback-info"]'
+ );
+ assert.lengthOf(msgWrapper, 1);
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/components/FluentOrText.test.jsx b/browser/components/newtab/test/unit/content-src/components/FluentOrText.test.jsx
new file mode 100644
index 0000000000..b4bbfae260
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/FluentOrText.test.jsx
@@ -0,0 +1,66 @@
+import { FluentOrText } from "content-src/components/FluentOrText/FluentOrText";
+import React from "react";
+import { shallow } from "enzyme";
+
+describe("<FluentOrText>", () => {
+ it("should create span with no children", () => {
+ const wrapper = shallow(<FluentOrText />);
+
+ assert.ok(wrapper.find("span"));
+ });
+ it("should set plain text", () => {
+ const wrapper = shallow(<FluentOrText message={"hello"} />);
+
+ assert.equal(wrapper.text(), "hello");
+ });
+ it("should use fluent id on automatic span", () => {
+ const wrapper = shallow(<FluentOrText message={{ id: "fluent" }} />);
+
+ assert.ok(wrapper.find("span[data-l10n-id='fluent']"));
+ });
+ it("should also allow string_id", () => {
+ const wrapper = shallow(<FluentOrText message={{ string_id: "fluent" }} />);
+
+ assert.ok(wrapper.find("span[data-l10n-id='fluent']"));
+ });
+ it("should use fluent id on child", () => {
+ const wrapper = shallow(
+ <FluentOrText message={{ id: "fluent" }}>
+ <p />
+ </FluentOrText>
+ );
+
+ assert.ok(wrapper.find("p[data-l10n-id='fluent']"));
+ });
+ it("should set args for fluent", () => {
+ const wrapper = shallow(<FluentOrText message={{ args: { num: 5 } }} />);
+
+ assert.ok(wrapper.find("span[data-l10n-args='{num: 5}']"));
+ });
+ it("should also allow values", () => {
+ const wrapper = shallow(<FluentOrText message={{ values: { num: 5 } }} />);
+
+ assert.ok(wrapper.find("span[data-l10n-args='{num: 5}']"));
+ });
+ it("should preserve original children with fluent", () => {
+ const wrapper = shallow(
+ <FluentOrText message={{ id: "fluent" }}>
+ <p>
+ <b data-l10n-name="bold" />
+ </p>
+ </FluentOrText>
+ );
+
+ assert.ok(wrapper.find("b[data-l10n-name='bold']"));
+ });
+ it("should only allow a single child", () => {
+ assert.throws(() =>
+ shallow(
+ <FluentOrText>
+ <p />
+ <p />
+ </FluentOrText>
+ )
+ );
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/components/LinkMenu.test.jsx b/browser/components/newtab/test/unit/content-src/components/LinkMenu.test.jsx
new file mode 100644
index 0000000000..5b214f0dbc
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/LinkMenu.test.jsx
@@ -0,0 +1,523 @@
+import { ContextMenu } from "content-src/components/ContextMenu/ContextMenu";
+import { _LinkMenu as LinkMenu } from "content-src/components/LinkMenu/LinkMenu";
+import React from "react";
+import { shallow } from "enzyme";
+
+describe("<LinkMenu>", () => {
+ let wrapper;
+ beforeEach(() => {
+ wrapper = shallow(
+ <LinkMenu
+ site={{ url: "" }}
+ options={["CheckPinTopSite", "CheckBookmark", "OpenInNewWindow"]}
+ dispatch={() => {}}
+ />
+ );
+ });
+ it("should render a ContextMenu element", () => {
+ assert.ok(wrapper.find(ContextMenu).exists());
+ });
+ it("should pass onUpdate, and options to ContextMenu", () => {
+ assert.ok(wrapper.find(ContextMenu).exists());
+ const contextMenuProps = wrapper.find(ContextMenu).props();
+ ["onUpdate", "options"].forEach(prop =>
+ assert.property(contextMenuProps, prop)
+ );
+ });
+ it("should give ContextMenu the correct tabbable options length for a11y", () => {
+ const { options } = wrapper.find(ContextMenu).props();
+ const [firstItem] = options;
+ const lastItem = options[options.length - 1];
+
+ // first item should have {first: true}
+ assert.isTrue(firstItem.first);
+ assert.ok(!firstItem.last);
+
+ // last item should have {last: true}
+ assert.isTrue(lastItem.last);
+ assert.ok(!lastItem.first);
+
+ // middle items should have neither
+ for (let i = 1; i < options.length - 1; i++) {
+ assert.ok(!options[i].first && !options[i].last);
+ }
+ });
+ it("should show the correct options for default sites", () => {
+ wrapper = shallow(
+ <LinkMenu
+ site={{ url: "", isDefault: true }}
+ options={["CheckBookmark"]}
+ source={"TOP_SITES"}
+ isPrivateBrowsingEnabled={true}
+ dispatch={() => {}}
+ />
+ );
+ const { options } = wrapper.find(ContextMenu).props();
+ let i = 0;
+ assert.propertyVal(options[i++], "id", "newtab-menu-pin");
+ assert.propertyVal(options[i++], "id", "newtab-menu-edit-topsites");
+ assert.propertyVal(options[i++], "type", "separator");
+ assert.propertyVal(options[i++], "id", "newtab-menu-open-new-window");
+ assert.propertyVal(
+ options[i++],
+ "id",
+ "newtab-menu-open-new-private-window"
+ );
+ assert.propertyVal(options[i++], "type", "separator");
+ assert.propertyVal(options[i++], "id", "newtab-menu-dismiss");
+ assert.propertyVal(options, "length", i);
+ // Double check that delete options are not included for default top sites
+ options
+ .filter(o => o.type !== "separator")
+ .forEach(o => {
+ assert.notInclude(["newtab-menu-delete-history"], o.id);
+ });
+ });
+ it("should show Unpin option for a pinned site if CheckPinTopSite in options list", () => {
+ wrapper = shallow(
+ <LinkMenu
+ site={{ url: "", isPinned: true }}
+ source={"TOP_SITES"}
+ options={["CheckPinTopSite"]}
+ dispatch={() => {}}
+ />
+ );
+ const { options } = wrapper.find(ContextMenu).props();
+ assert.isDefined(options.find(o => o.id && o.id === "newtab-menu-unpin"));
+ });
+ it("should show Pin option for an unpinned site if CheckPinTopSite in options list", () => {
+ wrapper = shallow(
+ <LinkMenu
+ site={{ url: "", isPinned: false }}
+ source={"TOP_SITES"}
+ options={["CheckPinTopSite"]}
+ dispatch={() => {}}
+ />
+ );
+ const { options } = wrapper.find(ContextMenu).props();
+ assert.isDefined(options.find(o => o.id && o.id === "newtab-menu-pin"));
+ });
+ it("should show Unbookmark option for a bookmarked site if CheckBookmark in options list", () => {
+ wrapper = shallow(
+ <LinkMenu
+ site={{ url: "", bookmarkGuid: 1234 }}
+ source={"TOP_SITES"}
+ options={["CheckBookmark"]}
+ dispatch={() => {}}
+ />
+ );
+ const { options } = wrapper.find(ContextMenu).props();
+ assert.isDefined(
+ options.find(o => o.id && o.id === "newtab-menu-remove-bookmark")
+ );
+ });
+ it("should show Bookmark option for an unbookmarked site if CheckBookmark in options list", () => {
+ wrapper = shallow(
+ <LinkMenu
+ site={{ url: "", bookmarkGuid: 0 }}
+ source={"TOP_SITES"}
+ options={["CheckBookmark"]}
+ dispatch={() => {}}
+ />
+ );
+ const { options } = wrapper.find(ContextMenu).props();
+ assert.isDefined(
+ options.find(o => o.id && o.id === "newtab-menu-bookmark")
+ );
+ });
+ it("should show Save to Pocket option for an unsaved Pocket item if CheckSavedToPocket in options list", () => {
+ wrapper = shallow(
+ <LinkMenu
+ site={{ url: "", bookmarkGuid: 0 }}
+ source={"HIGHLIGHTS"}
+ options={["CheckSavedToPocket"]}
+ dispatch={() => {}}
+ />
+ );
+ const { options } = wrapper.find(ContextMenu).props();
+ assert.isDefined(
+ options.find(o => o.id && o.id === "newtab-menu-save-to-pocket")
+ );
+ });
+ it("should show Delete from Pocket option for a saved Pocket item if CheckSavedToPocket in options list", () => {
+ wrapper = shallow(
+ <LinkMenu
+ site={{ url: "", pocket_id: 1234 }}
+ source={"HIGHLIGHTS"}
+ options={["CheckSavedToPocket"]}
+ dispatch={() => {}}
+ />
+ );
+ const { options } = wrapper.find(ContextMenu).props();
+ assert.isDefined(
+ options.find(o => o.id && o.id === "newtab-menu-delete-pocket")
+ );
+ });
+ it("should show Archive from Pocket option for a saved Pocket item if CheckBookmarkOrArchive", () => {
+ wrapper = shallow(
+ <LinkMenu
+ site={{ url: "", pocket_id: 1234 }}
+ source={"HIGHLIGHTS"}
+ options={["CheckBookmarkOrArchive"]}
+ dispatch={() => {}}
+ />
+ );
+ const { options } = wrapper.find(ContextMenu).props();
+ assert.isDefined(
+ options.find(o => o.id && o.id === "newtab-menu-archive-pocket")
+ );
+ });
+ it("should show Bookmark option for an unbookmarked site if CheckBookmarkOrArchive in options list and no pocket_id", () => {
+ wrapper = shallow(
+ <LinkMenu
+ site={{ url: "" }}
+ source={"HIGHLIGHTS"}
+ options={["CheckBookmarkOrArchive"]}
+ dispatch={() => {}}
+ />
+ );
+ const { options } = wrapper.find(ContextMenu).props();
+ assert.isDefined(
+ options.find(o => o.id && o.id === "newtab-menu-bookmark")
+ );
+ });
+ it("should show Unbookmark option for a bookmarked site if CheckBookmarkOrArchive in options list and no pocket_id", () => {
+ wrapper = shallow(
+ <LinkMenu
+ site={{ url: "", bookmarkGuid: 1234 }}
+ source={"HIGHLIGHTS"}
+ options={["CheckBookmarkOrArchive"]}
+ dispatch={() => {}}
+ />
+ );
+ const { options } = wrapper.find(ContextMenu).props();
+ assert.isDefined(
+ options.find(o => o.id && o.id === "newtab-menu-remove-bookmark")
+ );
+ });
+ it("should show Open File option for a downloaded item", () => {
+ wrapper = shallow(
+ <LinkMenu
+ site={{ url: "", type: "download", path: "foo" }}
+ source={"HIGHLIGHTS"}
+ options={["OpenFile"]}
+ dispatch={() => {}}
+ />
+ );
+ const { options } = wrapper.find(ContextMenu).props();
+ assert.isDefined(
+ options.find(o => o.id && o.id === "newtab-menu-open-file")
+ );
+ });
+ it("should show Show File option for a downloaded item on a default platform", () => {
+ wrapper = shallow(
+ <LinkMenu
+ site={{ url: "", type: "download", path: "foo" }}
+ source={"HIGHLIGHTS"}
+ options={["ShowFile"]}
+ platform={"default"}
+ dispatch={() => {}}
+ />
+ );
+ const { options } = wrapper.find(ContextMenu).props();
+ assert.isDefined(
+ options.find(o => o.id && o.id === "newtab-menu-show-file")
+ );
+ });
+ it("should show Copy Downlad Link option for a downloaded item when CopyDownloadLink", () => {
+ wrapper = shallow(
+ <LinkMenu
+ site={{ url: "", type: "download" }}
+ source={"HIGHLIGHTS"}
+ options={["CopyDownloadLink"]}
+ dispatch={() => {}}
+ />
+ );
+ const { options } = wrapper.find(ContextMenu).props();
+ assert.isDefined(
+ options.find(o => o.id && o.id === "newtab-menu-copy-download-link")
+ );
+ });
+ it("should show Go To Download Page option for a downloaded item when GoToDownloadPage", () => {
+ wrapper = shallow(
+ <LinkMenu
+ site={{ url: "", type: "download", referrer: "foo" }}
+ source={"HIGHLIGHTS"}
+ options={["GoToDownloadPage"]}
+ dispatch={() => {}}
+ />
+ );
+ const { options } = wrapper.find(ContextMenu).props();
+ assert.isDefined(
+ options.find(o => o.id && o.id === "newtab-menu-go-to-download-page")
+ );
+ assert.isFalse(options[0].disabled);
+ });
+ it("should show Go To Download Page option as disabled for a downloaded item when GoToDownloadPage if no referrer exists", () => {
+ wrapper = shallow(
+ <LinkMenu
+ site={{ url: "", type: "download", referrer: null }}
+ source={"HIGHLIGHTS"}
+ options={["GoToDownloadPage"]}
+ dispatch={() => {}}
+ />
+ );
+ const { options } = wrapper.find(ContextMenu).props();
+ assert.isDefined(
+ options.find(o => o.id && o.id === "newtab-menu-go-to-download-page")
+ );
+ assert.isTrue(options[0].disabled);
+ });
+ it("should show Remove Download Link option for a downloaded item when RemoveDownload", () => {
+ wrapper = shallow(
+ <LinkMenu
+ site={{ url: "", type: "download" }}
+ source={"HIGHLIGHTS"}
+ options={["RemoveDownload"]}
+ dispatch={() => {}}
+ />
+ );
+ const { options } = wrapper.find(ContextMenu).props();
+ assert.isDefined(
+ options.find(o => o.id && o.id === "newtab-menu-remove-download")
+ );
+ });
+ it("should show Edit option", () => {
+ const props = { url: "foo", label: "label" };
+ const index = 5;
+ wrapper = shallow(
+ <LinkMenu
+ site={props}
+ index={5}
+ source={"TOP_SITES"}
+ options={["EditTopSite"]}
+ dispatch={() => {}}
+ />
+ );
+ const { options } = wrapper.find(ContextMenu).props();
+ const option = options.find(
+ o => o.id && o.id === "newtab-menu-edit-topsites"
+ );
+ assert.isDefined(option);
+ assert.equal(option.action.data.index, index);
+ });
+ describe(".onClick", () => {
+ const FAKE_EVENT = {};
+ const FAKE_INDEX = 3;
+ const FAKE_SOURCE = "TOP_SITES";
+ const FAKE_SITE = {
+ bookmarkGuid: 1234,
+ hostname: "foo",
+ path: "foo",
+ pocket_id: "1234",
+ referrer: "https://foo.com/ref",
+ title: "bar",
+ type: "bookmark",
+ typedBonus: true,
+ url: "https://foo.com",
+ };
+ const dispatch = sinon.stub();
+ const propOptions = [
+ "ShowFile",
+ "CopyDownloadLink",
+ "GoToDownloadPage",
+ "RemoveDownload",
+ "Separator",
+ "ShowPrivacyInfo",
+ "RemoveBookmark",
+ "AddBookmark",
+ "OpenInNewWindow",
+ "OpenInPrivateWindow",
+ "BlockUrl",
+ "DeleteUrl",
+ "PinTopSite",
+ "UnpinTopSite",
+ "SaveToPocket",
+ "DeleteFromPocket",
+ "ArchiveFromPocket",
+ "WebExtDismiss",
+ ];
+ const expectedActionData = {
+ "newtab-menu-remove-bookmark": FAKE_SITE.bookmarkGuid,
+ "newtab-menu-bookmark": {
+ url: FAKE_SITE.url,
+ title: FAKE_SITE.title,
+ type: FAKE_SITE.type,
+ },
+ "newtab-menu-open-new-window": {
+ url: FAKE_SITE.url,
+ referrer: FAKE_SITE.referrer,
+ typedBonus: FAKE_SITE.typedBonus,
+ },
+ "newtab-menu-open-new-private-window": {
+ url: FAKE_SITE.url,
+ referrer: FAKE_SITE.referrer,
+ },
+ "newtab-menu-dismiss": [
+ {
+ url: FAKE_SITE.url,
+ pocket_id: FAKE_SITE.pocket_id,
+ },
+ ],
+ menu_action_webext_dismiss: {
+ source: "TOP_SITES",
+ url: FAKE_SITE.url,
+ action_position: 3,
+ },
+ "newtab-menu-delete-history": {
+ url: FAKE_SITE.url,
+ pocket_id: FAKE_SITE.pocket_id,
+ forceBlock: FAKE_SITE.bookmarkGuid,
+ },
+ "newtab-menu-pin": { site: FAKE_SITE, index: FAKE_INDEX },
+ "newtab-menu-unpin": { site: { url: FAKE_SITE.url } },
+ "newtab-menu-save-to-pocket": {
+ site: { url: FAKE_SITE.url, title: FAKE_SITE.title },
+ },
+ "newtab-menu-delete-pocket": { pocket_id: "1234" },
+ "newtab-menu-archive-pocket": { pocket_id: "1234" },
+ "newtab-menu-show-file": { url: FAKE_SITE.url },
+ "newtab-menu-copy-download-link": { url: FAKE_SITE.url },
+ "newtab-menu-go-to-download-page": { url: FAKE_SITE.referrer },
+ "newtab-menu-remove-download": { url: FAKE_SITE.url },
+ };
+ const { options } = shallow(
+ <LinkMenu
+ site={FAKE_SITE}
+ siteInfo={{ value: { card_type: FAKE_SITE.type } }}
+ dispatch={dispatch}
+ index={FAKE_INDEX}
+ isPrivateBrowsingEnabled={true}
+ platform={"default"}
+ options={propOptions}
+ source={FAKE_SOURCE}
+ shouldSendImpressionStats={true}
+ />
+ )
+ .find(ContextMenu)
+ .props();
+ afterEach(() => dispatch.reset());
+ options
+ .filter(o => o.type !== "separator")
+ .forEach(option => {
+ it(`should fire a ${option.action.type} action for ${option.id} with the expected data`, () => {
+ option.onClick(FAKE_EVENT);
+
+ if (option.impression && option.userEvent) {
+ assert.calledThrice(dispatch);
+ } else if (option.impression || option.userEvent) {
+ assert.calledTwice(dispatch);
+ } else {
+ assert.calledOnce(dispatch);
+ }
+
+ // option.action is dispatched
+ assert.ok(dispatch.firstCall.calledWith(option.action));
+
+ // option.action has correct data
+ // (delete is a special case as it dispatches a nested DIALOG_OPEN-type action)
+ // in the case of this FAKE_SITE, we send a bookmarkGuid therefore we also want
+ // to block this if we delete it
+ if (option.id === "newtab-menu-delete-history") {
+ assert.deepEqual(
+ option.action.data.onConfirm[0].data,
+ expectedActionData[option.id]
+ );
+ // Test UserEvent send correct meta about item deleted
+ assert.propertyVal(
+ option.action.data.onConfirm[1].data,
+ "action_position",
+ FAKE_INDEX
+ );
+ assert.propertyVal(
+ option.action.data.onConfirm[1].data,
+ "source",
+ FAKE_SOURCE
+ );
+ } else {
+ assert.deepEqual(option.action.data, expectedActionData[option.id]);
+ }
+ });
+ it(`should fire a UserEvent action for ${option.id} if configured`, () => {
+ if (option.userEvent) {
+ option.onClick(FAKE_EVENT);
+ const [action] = dispatch.secondCall.args;
+ assert.isUserEventAction(action);
+ assert.propertyVal(action.data, "source", FAKE_SOURCE);
+ assert.propertyVal(action.data, "action_position", FAKE_INDEX);
+ assert.propertyVal(action.data.value, "card_type", FAKE_SITE.type);
+ }
+ });
+ it(`should send impression stats for ${option.id}`, () => {
+ if (option.impression) {
+ option.onClick(FAKE_EVENT);
+ const [action] = dispatch.thirdCall.args;
+ assert.deepEqual(action, option.impression);
+ }
+ });
+ });
+ it(`should not send impression stats if not configured`, () => {
+ const fakeOptions = shallow(
+ <LinkMenu
+ site={FAKE_SITE}
+ dispatch={dispatch}
+ index={FAKE_INDEX}
+ options={propOptions}
+ source={FAKE_SOURCE}
+ shouldSendImpressionStats={false}
+ />
+ )
+ .find(ContextMenu)
+ .props().options;
+
+ fakeOptions
+ .filter(o => o.type !== "separator")
+ .forEach(option => {
+ if (option.impression) {
+ option.onClick(FAKE_EVENT);
+ assert.calledTwice(dispatch);
+ assert.notEqual(dispatch.firstCall.args[0], option.impression);
+ assert.notEqual(dispatch.secondCall.args[0], option.impression);
+ dispatch.reset();
+ }
+ });
+ });
+ it(`should pin a SPOC with all of the site details sent`, () => {
+ const pinSpocTopSite = "PinTopSite";
+ const { options: spocOptions } = shallow(
+ <LinkMenu
+ site={FAKE_SITE}
+ siteInfo={{ value: { card_type: FAKE_SITE.type } }}
+ dispatch={dispatch}
+ index={FAKE_INDEX}
+ isPrivateBrowsingEnabled={true}
+ platform={"default"}
+ options={[pinSpocTopSite]}
+ source={FAKE_SOURCE}
+ shouldSendImpressionStats={true}
+ />
+ )
+ .find(ContextMenu)
+ .props();
+
+ const [pinSpocOption] = spocOptions;
+ pinSpocOption.onClick(FAKE_EVENT);
+
+ if (pinSpocOption.impression && pinSpocOption.userEvent) {
+ assert.calledThrice(dispatch);
+ } else if (pinSpocOption.impression || pinSpocOption.userEvent) {
+ assert.calledTwice(dispatch);
+ } else {
+ assert.calledOnce(dispatch);
+ }
+
+ // option.action is dispatched
+ assert.ok(dispatch.firstCall.calledWith(pinSpocOption.action));
+
+ assert.deepEqual(pinSpocOption.action.data, {
+ site: FAKE_SITE,
+ index: FAKE_INDEX,
+ });
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/components/MSLocalized.test.jsx b/browser/components/newtab/test/unit/content-src/components/MSLocalized.test.jsx
new file mode 100644
index 0000000000..6cbfce6505
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/MSLocalized.test.jsx
@@ -0,0 +1,46 @@
+import { Localized } from "content-src/aboutwelcome/components/MSLocalized";
+import React from "react";
+import { shallow } from "enzyme";
+
+describe("<MSLocalized>", () => {
+ it("should render span with no children", () => {
+ const shallowWrapper = shallow(<Localized text="test" />);
+
+ assert.ok(shallowWrapper.find("span"));
+ assert.equal(shallowWrapper.text(), "test");
+ });
+ it("should render span when using string_id with no children", () => {
+ const shallowWrapper = shallow(
+ <Localized text={{ string_id: "test_id" }} />
+ );
+
+ assert.ok(shallowWrapper.find("span[data-l10n-id='test_id']"));
+ });
+ it("should render text inside child", () => {
+ const shallowWrapper = shallow(
+ <Localized text="test">
+ <div />
+ </Localized>
+ );
+ assert.ok(shallowWrapper.find("div").text(), "test");
+ });
+ it("should use l10n id on child", () => {
+ const shallowWrapper = shallow(
+ <Localized text={{ string_id: "test_id" }}>
+ <div />
+ </Localized>
+ );
+ assert.ok(shallowWrapper.find("div[data-l10n-id='test_id']"));
+ });
+ it("should keep original children", () => {
+ const shallowWrapper = shallow(
+ <Localized text={{ string_id: "test_id" }}>
+ <h1>
+ <span data-l10n-name="test" />
+ </h1>
+ </Localized>
+ );
+
+ assert.ok(shallowWrapper.find("span[data-l10n-name='test']"));
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/components/MoreRecommendations.test.jsx b/browser/components/newtab/test/unit/content-src/components/MoreRecommendations.test.jsx
new file mode 100644
index 0000000000..2b3c06b6bf
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/MoreRecommendations.test.jsx
@@ -0,0 +1,24 @@
+import { MoreRecommendations } from "content-src/components/MoreRecommendations/MoreRecommendations";
+import React from "react";
+import { shallow } from "enzyme";
+
+describe("<MoreRecommendations>", () => {
+ it("should render a MoreRecommendations element", () => {
+ const wrapper = shallow(<MoreRecommendations />);
+ assert.ok(wrapper.exists());
+ });
+ it("should render a link when provided with read_more_endpoint prop", () => {
+ const wrapper = shallow(
+ <MoreRecommendations read_more_endpoint="https://endpoint.com" />
+ );
+
+ const link = wrapper.find(".more-recommendations");
+ assert.lengthOf(link, 1);
+ });
+ it("should not render a link when provided with read_more_endpoint prop", () => {
+ const wrapper = shallow(<MoreRecommendations read_more_endpoint="" />);
+
+ const link = wrapper.find(".more-recommendations");
+ assert.lengthOf(link, 0);
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/components/PocketLoggedInCta.test.jsx b/browser/components/newtab/test/unit/content-src/components/PocketLoggedInCta.test.jsx
new file mode 100644
index 0000000000..7289058390
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/PocketLoggedInCta.test.jsx
@@ -0,0 +1,46 @@
+import { combineReducers, createStore } from "redux";
+import { INITIAL_STATE, reducers } from "common/Reducers.jsm";
+import { mount, shallow } from "enzyme";
+import {
+ PocketLoggedInCta,
+ _PocketLoggedInCta as PocketLoggedInCtaRaw,
+} from "content-src/components/PocketLoggedInCta/PocketLoggedInCta";
+import { Provider } from "react-redux";
+import React from "react";
+
+function mountSectionWithProps(props) {
+ const store = createStore(combineReducers(reducers), INITIAL_STATE);
+ return mount(
+ <Provider store={store}>
+ <PocketLoggedInCta {...props} />
+ </Provider>
+ );
+}
+
+describe("<PocketLoggedInCta>", () => {
+ it("should render a PocketLoggedInCta element", () => {
+ const wrapper = mountSectionWithProps({});
+ assert.ok(wrapper.exists());
+ });
+ it("should render Fluent spans when rendered without props", () => {
+ const wrapper = mountSectionWithProps({});
+
+ const message = wrapper.find("span[data-l10n-id]");
+ assert.lengthOf(message, 2);
+ });
+ it("should not render Fluent spans when rendered with props", () => {
+ const wrapper = shallow(
+ <PocketLoggedInCtaRaw
+ Pocket={{
+ pocketCta: {
+ ctaButton: "button",
+ ctaText: "text",
+ },
+ }}
+ />
+ );
+
+ const message = wrapper.find("span[data-l10n-id]");
+ assert.lengthOf(message, 0);
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/components/Search.test.jsx b/browser/components/newtab/test/unit/content-src/components/Search.test.jsx
new file mode 100644
index 0000000000..93d1c9457b
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/Search.test.jsx
@@ -0,0 +1,176 @@
+import { GlobalOverrider } from "test/unit/utils";
+import { mount, shallow } from "enzyme";
+import React from "react";
+import { _Search as Search } from "content-src/components/Search/Search";
+
+const DEFAULT_PROPS = { dispatch() {}, Prefs: { values: {} } };
+
+describe("<Search>", () => {
+ let globals;
+ let sandbox;
+ beforeEach(() => {
+ globals = new GlobalOverrider();
+ sandbox = globals.sandbox;
+
+ global.ContentSearchUIController.prototype = { search: sandbox.spy() };
+ });
+ afterEach(() => {
+ globals.restore();
+ });
+
+ it("should render a Search element", () => {
+ const wrapper = shallow(<Search {...DEFAULT_PROPS} />);
+ assert.ok(wrapper.exists());
+ });
+ it("should not use a <form> element", () => {
+ const wrapper = mount(<Search {...DEFAULT_PROPS} />);
+
+ assert.equal(wrapper.find("form").length, 0);
+ });
+ it("should listen for ContentSearchClient on render", () => {
+ const spy = globals.set("addEventListener", sandbox.spy());
+
+ const wrapper = mount(<Search {...DEFAULT_PROPS} />);
+
+ assert.calledOnce(spy.withArgs("ContentSearchClient", wrapper.instance()));
+ });
+ it("should stop listening for ContentSearchClient on unmount", () => {
+ const spy = globals.set("removeEventListener", sandbox.spy());
+ const wrapper = mount(<Search {...DEFAULT_PROPS} />);
+ // cache the instance as we can't call this method after unmount is called
+ const instance = wrapper.instance();
+
+ wrapper.unmount();
+
+ assert.calledOnce(spy.withArgs("ContentSearchClient", instance));
+ });
+ it("should add gContentSearchController as a global", () => {
+ // current about:home tests need gContentSearchController to exist as a global
+ // so let's test it here too to ensure we don't break this behaviour
+ mount(<Search {...DEFAULT_PROPS} />);
+ assert.property(window, "gContentSearchController");
+ assert.ok(window.gContentSearchController);
+ });
+ it("should pass along search when clicking the search button", () => {
+ const wrapper = mount(<Search {...DEFAULT_PROPS} />);
+
+ wrapper.find(".search-button").simulate("click");
+
+ const { search } = window.gContentSearchController;
+ assert.calledOnce(search);
+ assert.propertyVal(search.firstCall.args[0], "type", "click");
+ });
+ it("should send a UserEvent action", () => {
+ global.ContentSearchUIController.prototype.search = () => {
+ dispatchEvent(
+ new CustomEvent("ContentSearchClient", { detail: { type: "Search" } })
+ );
+ };
+ const dispatch = sinon.spy();
+ const wrapper = mount(<Search {...DEFAULT_PROPS} dispatch={dispatch} />);
+
+ wrapper.find(".search-button").simulate("click");
+
+ assert.calledOnce(dispatch);
+ const [action] = dispatch.firstCall.args;
+ assert.isUserEventAction(action);
+ assert.propertyVal(action.data, "event", "SEARCH");
+ });
+ it("should show our logo when the prop exists.", () => {
+ const showLogoProps = Object.assign({}, DEFAULT_PROPS, { showLogo: true });
+
+ const wrapper = shallow(<Search {...showLogoProps} />);
+ assert.lengthOf(wrapper.find(".logo-and-wordmark"), 1);
+ });
+ it("should not show our logo when the prop does not exist.", () => {
+ const hideLogoProps = Object.assign({}, DEFAULT_PROPS, { showLogo: false });
+
+ const wrapper = shallow(<Search {...hideLogoProps} />);
+ assert.lengthOf(wrapper.find(".logo-and-wordmark"), 0);
+ });
+
+ describe("Search Hand-off", () => {
+ it("should render a Search element when hand-off is enabled", () => {
+ const wrapper = shallow(
+ <Search {...DEFAULT_PROPS} handoffEnabled={true} />
+ );
+ assert.ok(wrapper.exists());
+ assert.equal(wrapper.find(".search-handoff-button").length, 1);
+ });
+ it("should hand-off search when button is clicked", () => {
+ const dispatch = sinon.spy();
+ const wrapper = shallow(
+ <Search {...DEFAULT_PROPS} handoffEnabled={true} dispatch={dispatch} />
+ );
+ wrapper
+ .find(".search-handoff-button")
+ .simulate("click", { preventDefault: () => {} });
+ assert.calledThrice(dispatch);
+ assert.calledWith(dispatch, {
+ data: { text: undefined },
+ meta: {
+ from: "ActivityStream:Content",
+ skipLocal: true,
+ to: "ActivityStream:Main",
+ },
+ type: "HANDOFF_SEARCH_TO_AWESOMEBAR",
+ });
+ assert.calledWith(dispatch, { type: "FAKE_FOCUS_SEARCH" });
+ const [action] = dispatch.thirdCall.args;
+ assert.isUserEventAction(action);
+ assert.propertyVal(action.data, "event", "SEARCH_HANDOFF");
+ });
+ it("should hand-off search on paste", () => {
+ const dispatch = sinon.spy();
+ const wrapper = mount(
+ <Search {...DEFAULT_PROPS} handoffEnabled={true} dispatch={dispatch} />
+ );
+ wrapper.instance()._searchHandoffButton = { contains: () => true };
+ wrapper.instance().onSearchHandoffPaste({
+ clipboardData: {
+ getData: () => "some copied text",
+ },
+ preventDefault: () => {},
+ });
+ assert.equal(dispatch.callCount, 4);
+ assert.calledWith(dispatch, {
+ data: { text: "some copied text" },
+ meta: {
+ from: "ActivityStream:Content",
+ skipLocal: true,
+ to: "ActivityStream:Main",
+ },
+ type: "HANDOFF_SEARCH_TO_AWESOMEBAR",
+ });
+ assert.calledWith(dispatch, { type: "HIDE_SEARCH" });
+ const [action] = dispatch.thirdCall.args;
+ assert.isUserEventAction(action);
+ assert.propertyVal(action.data, "event", "SEARCH_HANDOFF");
+ });
+ it("should properly handle drop events", () => {
+ const dispatch = sinon.spy();
+ const wrapper = mount(
+ <Search {...DEFAULT_PROPS} handoffEnabled={true} dispatch={dispatch} />
+ );
+ const preventDefault = sinon.spy();
+ wrapper.find(".fake-editable").simulate("drop", {
+ dataTransfer: { getData: () => "dropped text" },
+ preventDefault,
+ });
+ assert.equal(dispatch.callCount, 4);
+ assert.calledWith(dispatch, {
+ data: { text: "dropped text" },
+ meta: {
+ from: "ActivityStream:Content",
+ skipLocal: true,
+ to: "ActivityStream:Main",
+ },
+ type: "HANDOFF_SEARCH_TO_AWESOMEBAR",
+ });
+ assert.calledWith(dispatch, { type: "HIDE_SEARCH" });
+ const [action] = dispatch.thirdCall.args;
+ assert.isUserEventAction(action);
+ assert.propertyVal(action.data, "event", "SEARCH_HANDOFF");
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/components/SectionMenu.test.jsx b/browser/components/newtab/test/unit/content-src/components/SectionMenu.test.jsx
new file mode 100644
index 0000000000..2e987c6b54
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/SectionMenu.test.jsx
@@ -0,0 +1,273 @@
+import { ContextMenu } from "content-src/components/ContextMenu/ContextMenu";
+import React from "react";
+import { _SectionMenu as SectionMenu } from "content-src/components/SectionMenu/SectionMenu";
+import { shallow } from "enzyme";
+
+const DEFAULT_PROPS = {
+ Prefs: { values: {} },
+ name: "Section Name",
+ id: "sectionId",
+ source: "TOP_SITES",
+ showPrefName: "showSection",
+ collapsePrefName: "collapseSection",
+ collapsed: false,
+ onUpdate: () => {},
+ visible: false,
+ dispatch: () => {},
+};
+
+describe("<SectionMenu>", () => {
+ let wrapper;
+ beforeEach(() => {
+ wrapper = shallow(<SectionMenu {...DEFAULT_PROPS} />);
+ });
+ it("should render a ContextMenu element", () => {
+ assert.ok(wrapper.find(ContextMenu).exists());
+ });
+ it("should pass onUpdate, and options to ContextMenu", () => {
+ assert.ok(wrapper.find(ContextMenu).exists());
+ const contextMenuProps = wrapper.find(ContextMenu).props();
+ ["onUpdate", "options"].forEach(prop =>
+ assert.property(contextMenuProps, prop)
+ );
+ });
+ it("should give ContextMenu the correct tabbable options length for a11y", () => {
+ const { options } = wrapper.find(ContextMenu).props();
+ const [firstItem] = options;
+ const lastItem = options[options.length - 1];
+
+ // first item should have {first: true}
+ assert.isTrue(firstItem.first);
+ assert.ok(!firstItem.last);
+
+ // last item should have {last: true}
+ assert.isTrue(lastItem.last);
+ assert.ok(!lastItem.first);
+
+ // middle items should have neither
+ for (let i = 1; i < options.length - 1; i++) {
+ assert.ok(!options[i].first && !options[i].last);
+ }
+ });
+ it("should show the correct default options", () => {
+ wrapper = shallow(<SectionMenu {...DEFAULT_PROPS} />);
+ const { options } = wrapper.find(ContextMenu).props();
+ let i = 0;
+ assert.propertyVal(options[i++], "id", "newtab-section-menu-move-up");
+ assert.propertyVal(options[i++], "id", "newtab-section-menu-move-down");
+ assert.propertyVal(options[i++], "type", "separator");
+ assert.propertyVal(
+ options[i++],
+ "id",
+ "newtab-section-menu-remove-section"
+ );
+ assert.propertyVal(
+ options[i++],
+ "id",
+ "newtab-section-menu-collapse-section"
+ );
+ assert.propertyVal(options[i++], "type", "separator");
+ assert.propertyVal(
+ options[i++],
+ "id",
+ "newtab-section-menu-manage-section"
+ );
+ assert.propertyVal(options, "length", i);
+ });
+ it("should show the correct default options for a web extension", () => {
+ wrapper = shallow(<SectionMenu {...DEFAULT_PROPS} isWebExtension={true} />);
+ const { options } = wrapper.find(ContextMenu).props();
+ let i = 0;
+ assert.propertyVal(options[i++], "id", "newtab-section-menu-move-up");
+ assert.propertyVal(options[i++], "id", "newtab-section-menu-move-down");
+ assert.propertyVal(options[i++], "type", "separator");
+ assert.propertyVal(
+ options[i++],
+ "id",
+ "newtab-section-menu-collapse-section"
+ );
+ assert.propertyVal(options[i++], "type", "separator");
+ assert.propertyVal(options[i++], "id", "newtab-section-menu-manage-webext");
+ assert.propertyVal(options, "length", i);
+ });
+ it("should show Collapse option for an expanded section if CheckCollapsed in options list", () => {
+ wrapper = shallow(<SectionMenu {...DEFAULT_PROPS} collapsed={false} />);
+ const { options } = wrapper.find(ContextMenu).props();
+ assert.isDefined(
+ options.find(o => o.id && o.id === "newtab-section-menu-collapse-section")
+ );
+ });
+ it("should show Expand option for a collapsed section if CheckCollapsed in options list", () => {
+ wrapper = shallow(<SectionMenu {...DEFAULT_PROPS} collapsed={true} />);
+ const { options } = wrapper.find(ContextMenu).props();
+ assert.isDefined(
+ options.find(o => o.id && o.id === "newtab-section-menu-expand-section")
+ );
+ });
+ it("should show Add Top Site option", () => {
+ wrapper = shallow(
+ <SectionMenu {...DEFAULT_PROPS} extraOptions={["AddTopSite"]} />
+ );
+ const { options } = wrapper.find(ContextMenu).props();
+ assert.equal(options[0].id, "newtab-section-menu-add-topsite");
+ });
+ it("should show Add Search Engine option", () => {
+ wrapper = shallow(
+ <SectionMenu {...DEFAULT_PROPS} extraOptions={["AddSearchShortcut"]} />
+ );
+ const { options } = wrapper.find(ContextMenu).props();
+ assert.equal(options[0].id, "newtab-section-menu-add-search-engine");
+ });
+ it("should show Privacy Notice option if privacyNoticeURL is passed", () => {
+ wrapper = shallow(
+ <SectionMenu
+ {...DEFAULT_PROPS}
+ privacyNoticeURL="https://mozilla.org/privacy"
+ />
+ );
+ const { options } = wrapper.find(ContextMenu).props();
+ let i = 0;
+ assert.propertyVal(options[i++], "id", "newtab-section-menu-move-up");
+ assert.propertyVal(options[i++], "id", "newtab-section-menu-move-down");
+ assert.propertyVal(options[i++], "type", "separator");
+ assert.propertyVal(
+ options[i++],
+ "id",
+ "newtab-section-menu-remove-section"
+ );
+ assert.propertyVal(
+ options[i++],
+ "id",
+ "newtab-section-menu-collapse-section"
+ );
+ assert.propertyVal(options[i++], "type", "separator");
+ assert.propertyVal(
+ options[i++],
+ "id",
+ "newtab-section-menu-privacy-notice"
+ );
+ assert.propertyVal(
+ options[i++],
+ "id",
+ "newtab-section-menu-manage-section"
+ );
+ assert.propertyVal(options, "length", i);
+ });
+ it("should disable Move Up on first section", () => {
+ wrapper = shallow(<SectionMenu {...DEFAULT_PROPS} isFirst={true} />);
+ const { options } = wrapper.find(ContextMenu).props();
+ assert.ok(options[0].disabled);
+ });
+ it("should disable Move Down on last section", () => {
+ wrapper = shallow(<SectionMenu {...DEFAULT_PROPS} isLast={true} />);
+ const { options } = wrapper.find(ContextMenu).props();
+ assert.ok(options[1].disabled);
+ });
+ describe(".onClick", () => {
+ const dispatch = sinon.stub();
+ const expectedActionData = {
+ "newtab-section-menu-move-up": { id: "sectionId", direction: -1 },
+ "newtab-section-menu-move-down": { id: "sectionId", direction: +1 },
+ "newtab-section-menu-remove-section": {
+ name: "showSection",
+ value: false,
+ },
+ "newtab-section-menu-collapse-section": {
+ id: DEFAULT_PROPS.id,
+ value: { collapsed: true },
+ },
+ "newtab-section-menu-expand-section": {
+ id: DEFAULT_PROPS.id,
+ value: { collapsed: false },
+ },
+ "newtab-section-menu-manage-section": undefined,
+ "newtab-section-menu-add-topsite": { index: -1 },
+ "newtab-section-menu-privacy-notice": {
+ url: DEFAULT_PROPS.privacyNoticeURL,
+ },
+ };
+ const { options } = shallow(
+ <SectionMenu {...DEFAULT_PROPS} dispatch={dispatch} />
+ )
+ .find(ContextMenu)
+ .props();
+ afterEach(() => dispatch.reset());
+ options
+ .filter(o => o.type !== "separator")
+ .forEach(option => {
+ it(`should fire a ${option.action.type} action for ${option.id} with the expected data`, () => {
+ option.onClick();
+
+ if (option.userEvent && option.action) {
+ assert.calledTwice(dispatch);
+ } else if (option.userEvent || option.action) {
+ assert.calledOnce(dispatch);
+ } else {
+ assert.notCalled(dispatch);
+ }
+
+ // option.action is dispatched
+ assert.ok(dispatch.firstCall.calledWith(option.action));
+ assert.deepEqual(option.action.data, expectedActionData[option.id]);
+ });
+ it(`should fire a UserEvent action for ${option.id} if configured`, () => {
+ if (option.userEvent) {
+ option.onClick();
+ const [action] = dispatch.secondCall.args;
+ assert.isUserEventAction(action);
+ assert.propertyVal(action.data, "source", DEFAULT_PROPS.source);
+ }
+ });
+ });
+ });
+ describe("dispatch expand section if section is collapsed and adding top site", () => {
+ const dispatch = sinon.stub();
+ const expectedExpandData = {
+ id: DEFAULT_PROPS.id,
+ value: { collapsed: false },
+ };
+ const expectedAddData = { index: -1 };
+ const { options } = shallow(
+ <SectionMenu
+ {...DEFAULT_PROPS}
+ collapsed={true}
+ dispatch={dispatch}
+ extraOptions={["AddTopSite"]}
+ />
+ )
+ .find(ContextMenu)
+ .props();
+ afterEach(() => dispatch.reset());
+
+ assert.equal(options[0].id, "newtab-section-menu-add-topsite");
+ options
+ .filter(o => o.id === "newtab-section-menu-add-topsite")
+ .forEach(option => {
+ it(`should dispatch an action to expand the section and to add a topsite after expanding`, () => {
+ option.onClick();
+
+ const [expandAction] = dispatch.firstCall.args;
+ assert.deepEqual(expandAction.data, expectedExpandData);
+
+ const [addAction] = dispatch.thirdCall.args;
+ assert.deepEqual(addAction.data, expectedAddData);
+ });
+ it(`should dispatch the expand userEvent and add topsite userEvent after expanding`, () => {
+ option.onClick();
+ assert.ok(dispatch.thirdCall.calledWith(option.action));
+
+ const [expandUserEvent] = dispatch.secondCall.args;
+ assert.isUserEventAction(expandUserEvent);
+ assert.propertyVal(
+ expandUserEvent.data,
+ "source",
+ DEFAULT_PROPS.source
+ );
+
+ const [addUserEvent] = dispatch.lastCall.args;
+ assert.isUserEventAction(addUserEvent);
+ assert.propertyVal(addUserEvent.data, "source", DEFAULT_PROPS.source);
+ });
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/components/Sections.test.jsx b/browser/components/newtab/test/unit/content-src/components/Sections.test.jsx
new file mode 100644
index 0000000000..e6a358b47a
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/Sections.test.jsx
@@ -0,0 +1,633 @@
+import { combineReducers, createStore } from "redux";
+import { INITIAL_STATE, reducers } from "common/Reducers.jsm";
+import {
+ Section,
+ SectionIntl,
+ _Sections as Sections,
+} from "content-src/components/Sections/Sections";
+import { actionTypes as at } from "common/Actions.jsm";
+import { mount, shallow } from "enzyme";
+import { PlaceholderCard } from "content-src/components/Card/Card";
+import { PocketLoggedInCta } from "content-src/components/PocketLoggedInCta/PocketLoggedInCta";
+import { Provider } from "react-redux";
+import React from "react";
+import { SectionMenu } from "content-src/components/SectionMenu/SectionMenu";
+import { Topics } from "content-src/components/Topics/Topics";
+import { TopSites } from "content-src/components/TopSites/TopSites";
+
+function mountSectionWithProps(props) {
+ const store = createStore(combineReducers(reducers), INITIAL_STATE);
+ return mount(
+ <Provider store={store}>
+ <Section {...props} />
+ </Provider>
+ );
+}
+
+function mountSectionIntlWithProps(props) {
+ const store = createStore(combineReducers(reducers), INITIAL_STATE);
+ return mount(
+ <Provider store={store}>
+ <SectionIntl {...props} />
+ </Provider>
+ );
+}
+
+describe("<Sections>", () => {
+ let wrapper;
+ let FAKE_SECTIONS;
+ beforeEach(() => {
+ FAKE_SECTIONS = new Array(5).fill(null).map((v, i) => ({
+ id: `foo_bar_${i}`,
+ title: `Foo Bar ${i}`,
+ enabled: !!(i % 2),
+ rows: [],
+ }));
+ wrapper = shallow(
+ <Sections
+ Sections={FAKE_SECTIONS}
+ Prefs={{
+ values: { sectionOrder: FAKE_SECTIONS.map(i => i.id).join(",") },
+ }}
+ />
+ );
+ });
+ it("should render a Sections element", () => {
+ assert.ok(wrapper.exists());
+ });
+ it("should render a Section for each one passed in props.Sections with .enabled === true", () => {
+ const sectionElems = wrapper.find(SectionIntl);
+ assert.lengthOf(sectionElems, 2);
+ sectionElems.forEach((section, i) => {
+ assert.equal(section.props().id, FAKE_SECTIONS[2 * i + 1].id);
+ assert.equal(section.props().enabled, true);
+ });
+ });
+ it("should render Top Sites if feeds.topsites pref is true", () => {
+ wrapper = shallow(
+ <Sections
+ Sections={FAKE_SECTIONS}
+ Prefs={{
+ values: {
+ "feeds.topsites": true,
+ sectionOrder: "topsites,topstories,highlights",
+ },
+ }}
+ />
+ );
+ assert.equal(wrapper.find(TopSites).length, 1);
+ });
+ it("should NOT render Top Sites if feeds.topsites pref is false", () => {
+ wrapper = shallow(
+ <Sections
+ Sections={FAKE_SECTIONS}
+ Prefs={{
+ values: {
+ "feeds.topsites": false,
+ sectionOrder: "topsites,topstories,highlights",
+ },
+ }}
+ />
+ );
+ assert.equal(wrapper.find(TopSites).length, 0);
+ });
+ it("should render the sections in the order specifed by sectionOrder pref", () => {
+ wrapper = shallow(
+ <Sections
+ Sections={FAKE_SECTIONS}
+ Prefs={{ values: { sectionOrder: "foo_bar_1,foo_bar_3" } }}
+ />
+ );
+ let sections = wrapper.find(SectionIntl);
+ assert.lengthOf(sections, 2);
+ assert.equal(sections.first().props().id, "foo_bar_1");
+ assert.equal(sections.last().props().id, "foo_bar_3");
+ wrapper = shallow(
+ <Sections
+ Sections={FAKE_SECTIONS}
+ Prefs={{ values: { sectionOrder: "foo_bar_3,foo_bar_1" } }}
+ />
+ );
+ sections = wrapper.find(SectionIntl);
+ assert.lengthOf(sections, 2);
+ assert.equal(sections.first().props().id, "foo_bar_3");
+ assert.equal(sections.last().props().id, "foo_bar_1");
+ });
+});
+
+describe("<Section>", () => {
+ let wrapper;
+ let FAKE_SECTION;
+
+ beforeEach(() => {
+ FAKE_SECTION = {
+ id: `foo_bar_1`,
+ pref: { collapsed: false },
+ title: `Foo Bar 1`,
+ rows: [{ link: "http://localhost", index: 0 }],
+ emptyState: {
+ icon: "check",
+ message: "Some message",
+ },
+ rowsPref: "section.rows",
+ maxRows: 4,
+ Prefs: { values: { "section.rows": 2 } },
+ };
+ wrapper = mountSectionIntlWithProps(FAKE_SECTION);
+ });
+
+ describe("context menu", () => {
+ it("should render a context menu button", () => {
+ wrapper = mountSectionIntlWithProps(FAKE_SECTION);
+
+ assert.equal(
+ wrapper.find(".section-top-bar .context-menu-button").length,
+ 1
+ );
+ });
+ it("should render a section menu when button is clicked", () => {
+ wrapper = mountSectionIntlWithProps(FAKE_SECTION);
+
+ const button = wrapper.find(".section-top-bar .context-menu-button");
+ assert.equal(wrapper.find(SectionMenu).length, 0);
+ button.simulate("click", { preventDefault: () => {} });
+ assert.equal(wrapper.find(SectionMenu).length, 1);
+ });
+ it("should not render a section menu by default", () => {
+ wrapper = shallow(<Section {...FAKE_SECTION} />);
+ assert.equal(wrapper.find(SectionMenu).length, 0);
+ });
+ });
+
+ describe("placeholders", () => {
+ const CARDS_PER_ROW = 3;
+ const fakeSite = { link: "http://localhost" };
+ function renderWithSites(rows) {
+ const store = createStore(combineReducers(reducers), INITIAL_STATE);
+ return mount(
+ <Provider store={store}>
+ <Section {...FAKE_SECTION} rows={rows} />
+ </Provider>
+ );
+ }
+
+ it("should return 2 row of placeholders if realRows is 0", () => {
+ wrapper = renderWithSites([]);
+ assert.lengthOf(wrapper.find(PlaceholderCard), 6);
+ });
+ it("should fill in the rest of the rows", () => {
+ wrapper = renderWithSites(new Array(CARDS_PER_ROW).fill(fakeSite));
+ assert.lengthOf(
+ wrapper.find(PlaceholderCard),
+ CARDS_PER_ROW,
+ "CARDS_PER_ROW"
+ );
+
+ wrapper = renderWithSites(new Array(CARDS_PER_ROW + 1).fill(fakeSite));
+ assert.lengthOf(wrapper.find(PlaceholderCard), 2, "CARDS_PER_ROW + 1");
+
+ wrapper = renderWithSites(new Array(CARDS_PER_ROW + 2).fill(fakeSite));
+ assert.lengthOf(wrapper.find(PlaceholderCard), 1, "CARDS_PER_ROW + 2");
+
+ wrapper = renderWithSites(
+ new Array(2 * CARDS_PER_ROW - 1).fill(fakeSite)
+ );
+ assert.lengthOf(wrapper.find(PlaceholderCard), 1, "CARDS_PER_ROW - 1");
+ });
+ it("should not add placeholders all the rows are full", () => {
+ wrapper = renderWithSites(new Array(2 * CARDS_PER_ROW).fill(fakeSite));
+ assert.lengthOf(wrapper.find(PlaceholderCard), 0, "2 rows");
+ });
+ });
+
+ describe("empty state", () => {
+ beforeEach(() => {
+ Object.assign(FAKE_SECTION, {
+ initialized: true,
+ dispatch: () => {},
+ rows: [],
+ emptyState: {
+ message: "Some message",
+ icon: "moz-extension://some/extension/path",
+ },
+ });
+ wrapper = shallow(<Section {...FAKE_SECTION} />);
+ });
+ it("should be shown when rows is empty and initialized is true", () => {
+ assert.ok(wrapper.find(".empty-state").exists());
+ });
+ it("should not be shown in initialized is false", () => {
+ Object.assign(FAKE_SECTION, {
+ initialized: false,
+ rows: [],
+ emptyState: {
+ message: "Some message",
+ icon: "moz-extension://some/extension/path",
+ },
+ });
+ wrapper = shallow(<Section {...FAKE_SECTION} />);
+ assert.isFalse(wrapper.find(".empty-state").exists());
+ });
+ it("should use the icon prop as the icon url if it starts with `moz-extension://`", () => {
+ const props = wrapper
+ .find(".empty-state-icon")
+ .first()
+ .props();
+ assert.equal(
+ props.style["background-image"],
+ `url('${FAKE_SECTION.emptyState.icon}')`
+ );
+ });
+ });
+
+ describe("topics component", () => {
+ let TOP_STORIES_SECTION;
+ beforeEach(() => {
+ TOP_STORIES_SECTION = {
+ id: "topstories",
+ title: "TopStories",
+ pref: { collapsed: false },
+ rows: [{ guid: 1, link: "http://localhost", isDefault: true }],
+ topics: [],
+ read_more_endpoint: "http://localhost/read-more",
+ maxRows: 1,
+ eventSource: "TOP_STORIES",
+ };
+ });
+ it("should not render for empty topics", () => {
+ wrapper = mountSectionIntlWithProps(TOP_STORIES_SECTION);
+
+ assert.lengthOf(wrapper.find(".topic"), 0);
+ });
+ it("should render for non-empty topics", () => {
+ TOP_STORIES_SECTION.topics = [{ name: "topic1", url: "topic-url1" }];
+ wrapper = shallow(
+ <Section
+ Pocket={{ pocketCta: { useCta: true }, isUserLoggedIn: true }}
+ {...TOP_STORIES_SECTION}
+ />
+ );
+
+ assert.lengthOf(wrapper.find(Topics), 1);
+ assert.lengthOf(wrapper.find(PocketLoggedInCta), 0);
+ });
+ it("should delay render of third rec to give time for potential spoc", async () => {
+ TOP_STORIES_SECTION.rows = [
+ { guid: 1, link: "http://localhost" },
+ { guid: 2, link: "http://localhost" },
+ { guid: 3, link: "http://localhost" },
+ ];
+ wrapper = shallow(
+ <Section
+ Pocket={{ waitingForSpoc: true, pocketCta: {} }}
+ {...TOP_STORIES_SECTION}
+ />
+ );
+ assert.lengthOf(wrapper.find(PlaceholderCard), 1);
+
+ wrapper.setProps({
+ Pocket: {
+ waitingForSpoc: false,
+ pocketCta: {},
+ },
+ });
+ assert.lengthOf(wrapper.find(PlaceholderCard), 0);
+ });
+ it("should render container for uninitialized topics to ensure content doesn't shift", () => {
+ delete TOP_STORIES_SECTION.topics;
+
+ wrapper = mountSectionIntlWithProps(TOP_STORIES_SECTION);
+
+ assert.lengthOf(wrapper.find(".top-stories-bottom-container"), 1);
+ assert.lengthOf(wrapper.find(Topics), 0);
+ assert.lengthOf(wrapper.find(PocketLoggedInCta), 0);
+ });
+
+ it("should render a pocket cta if not logged in and set to display cta", () => {
+ TOP_STORIES_SECTION.topics = [{ name: "topic1", url: "topic-url1" }];
+ wrapper = shallow(
+ <Section
+ Pocket={{ pocketCta: { useCta: true }, isUserLoggedIn: false }}
+ {...TOP_STORIES_SECTION}
+ />
+ );
+
+ assert.lengthOf(wrapper.find(Topics), 0);
+ assert.lengthOf(wrapper.find(PocketLoggedInCta), 1);
+ });
+ it("should render nothing while loading to avoid a flicker of log in state", () => {
+ TOP_STORIES_SECTION.topics = [{ name: "topic1", url: "topic-url1" }];
+ wrapper = shallow(
+ <Section
+ Pocket={{ pocketCta: { useCta: false } }}
+ {...TOP_STORIES_SECTION}
+ />
+ );
+
+ assert.lengthOf(wrapper.find(Topics), 0);
+ assert.lengthOf(wrapper.find(PocketLoggedInCta), 0);
+ });
+ it("should render a topics list if set to not display cta with either logged or out", () => {
+ TOP_STORIES_SECTION.topics = [{ name: "topic1", url: "topic-url1" }];
+ wrapper = shallow(
+ <Section
+ Pocket={{ pocketCta: { useCta: false }, isUserLoggedIn: false }}
+ {...TOP_STORIES_SECTION}
+ />
+ );
+
+ assert.lengthOf(wrapper.find(Topics), 1);
+ assert.lengthOf(wrapper.find(PocketLoggedInCta), 0);
+
+ wrapper = shallow(
+ <Section
+ Pocket={{ pocketCta: { useCta: false }, isUserLoggedIn: true }}
+ {...TOP_STORIES_SECTION}
+ />
+ );
+
+ assert.lengthOf(wrapper.find(Topics), 1);
+ assert.lengthOf(wrapper.find(PocketLoggedInCta), 0);
+ });
+ it("should render nothing if set to display a cta and not logged in or out (waiting for state)", () => {
+ TOP_STORIES_SECTION.topics = [{ name: "topic1", url: "topic-url1" }];
+ wrapper = shallow(
+ <Section
+ Pocket={{ pocketCta: { useCta: true } }}
+ {...TOP_STORIES_SECTION}
+ />
+ );
+
+ assert.lengthOf(wrapper.find(Topics), 0);
+ assert.lengthOf(wrapper.find(PocketLoggedInCta), 0);
+ });
+ });
+
+ describe("impression stats", () => {
+ const FAKE_TOPSTORIES_SECTION_PROPS = {
+ id: "TopStories",
+ title: "Foo Bar 1",
+ pref: { collapsed: false },
+ maxRows: 1,
+ rows: [{ guid: 1 }, { guid: 2 }],
+ shouldSendImpressionStats: true,
+
+ document: {
+ visibilityState: "visible",
+ addEventListener: sinon.stub(),
+ removeEventListener: sinon.stub(),
+ },
+ eventSource: "TOP_STORIES",
+ options: { personalized: false },
+ };
+
+ function renderSection(props = {}) {
+ return shallow(<Section {...FAKE_TOPSTORIES_SECTION_PROPS} {...props} />);
+ }
+
+ it("should send impression with the right stats when the page loads", () => {
+ const dispatch = sinon.spy();
+ renderSection({ dispatch });
+
+ assert.calledOnce(dispatch);
+
+ const [action] = dispatch.firstCall.args;
+ assert.equal(action.type, at.TELEMETRY_IMPRESSION_STATS);
+ assert.equal(action.data.source, "TOP_STORIES");
+ assert.deepEqual(action.data.tiles, [{ id: 1 }, { id: 2 }]);
+ });
+ it("should not send impression stats if not configured", () => {
+ const dispatch = sinon.spy();
+ const props = Object.assign({}, FAKE_TOPSTORIES_SECTION_PROPS, {
+ shouldSendImpressionStats: false,
+ dispatch,
+ });
+ renderSection(props);
+ assert.notCalled(dispatch);
+ });
+ it("should not send impression stats if the section is collapsed", () => {
+ const dispatch = sinon.spy();
+ const props = Object.assign({}, FAKE_TOPSTORIES_SECTION_PROPS, {
+ pref: { collapsed: true },
+ });
+ renderSection(props);
+ assert.notCalled(dispatch);
+ });
+ it("should send 1 impression when the page becomes visibile after loading", () => {
+ const props = {
+ dispatch: sinon.spy(),
+ document: {
+ visibilityState: "hidden",
+ addEventListener: sinon.spy(),
+ removeEventListener: sinon.spy(),
+ },
+ };
+
+ renderSection(props);
+
+ // Was the event listener added?
+ assert.calledWith(props.document.addEventListener, "visibilitychange");
+
+ // Make sure dispatch wasn't called yet
+ assert.notCalled(props.dispatch);
+
+ // Simulate a visibilityChange event
+ const [, listener] = props.document.addEventListener.firstCall.args;
+ props.document.visibilityState = "visible";
+ listener();
+
+ // Did we actually dispatch an event?
+ assert.calledOnce(props.dispatch);
+ assert.equal(
+ props.dispatch.firstCall.args[0].type,
+ at.TELEMETRY_IMPRESSION_STATS
+ );
+
+ // Did we remove the event listener?
+ assert.calledWith(
+ props.document.removeEventListener,
+ "visibilitychange",
+ listener
+ );
+ });
+ it("should remove visibility change listener when section is removed", () => {
+ const props = {
+ dispatch: sinon.spy(),
+ document: {
+ visibilityState: "hidden",
+ addEventListener: sinon.spy(),
+ removeEventListener: sinon.spy(),
+ },
+ };
+
+ const section = renderSection(props);
+ assert.calledWith(props.document.addEventListener, "visibilitychange");
+ const [, listener] = props.document.addEventListener.firstCall.args;
+
+ section.unmount();
+ assert.calledWith(
+ props.document.removeEventListener,
+ "visibilitychange",
+ listener
+ );
+ });
+ it("should send an impression if props are updated and props.rows are different", () => {
+ const props = { dispatch: sinon.spy() };
+ wrapper = renderSection(props);
+ props.dispatch.resetHistory();
+
+ // New rows
+ wrapper.setProps(
+ Object.assign({}, FAKE_TOPSTORIES_SECTION_PROPS, {
+ rows: [{ guid: 123 }],
+ })
+ );
+
+ assert.calledOnce(props.dispatch);
+ });
+ it("should not send an impression if props are updated but props.rows are the same", () => {
+ const props = { dispatch: sinon.spy() };
+ wrapper = renderSection(props);
+ props.dispatch.resetHistory();
+
+ // Only update the disclaimer prop
+ wrapper.setProps(
+ Object.assign({}, FAKE_TOPSTORIES_SECTION_PROPS, {
+ disclaimer: { id: "bar" },
+ })
+ );
+
+ assert.notCalled(props.dispatch);
+ });
+ it("should not send an impression if props are updated and props.rows are the same but section is collapsed", () => {
+ const props = { dispatch: sinon.spy() };
+ wrapper = renderSection(props);
+ props.dispatch.resetHistory();
+
+ // New rows and collapsed
+ wrapper.setProps(
+ Object.assign({}, FAKE_TOPSTORIES_SECTION_PROPS, {
+ rows: [{ guid: 123 }],
+ pref: { collapsed: true },
+ })
+ );
+
+ assert.notCalled(props.dispatch);
+
+ // Expand the section. Now the impression stats should be sent
+ wrapper.setProps(
+ Object.assign({}, FAKE_TOPSTORIES_SECTION_PROPS, {
+ rows: [{ guid: 123 }],
+ pref: { collapsed: false },
+ })
+ );
+
+ assert.calledOnce(props.dispatch);
+ });
+ it("should not send an impression if props are updated but GUIDs are the same", () => {
+ const props = { dispatch: sinon.spy() };
+ wrapper = renderSection(props);
+ props.dispatch.resetHistory();
+
+ wrapper.setProps(
+ Object.assign({}, FAKE_TOPSTORIES_SECTION_PROPS, {
+ rows: [{ guid: 1 }, { guid: 2 }],
+ })
+ );
+
+ assert.notCalled(props.dispatch);
+ });
+ it("should only send the latest impression on a visibility change", () => {
+ const listeners = new Set();
+ const props = {
+ dispatch: sinon.spy(),
+ document: {
+ visibilityState: "hidden",
+ addEventListener: (ev, cb) => listeners.add(cb),
+ removeEventListener: (ev, cb) => listeners.delete(cb),
+ },
+ };
+
+ wrapper = renderSection(props);
+
+ // Update twice
+ wrapper.setProps(Object.assign({}, props, { rows: [{ guid: 123 }] }));
+ wrapper.setProps(Object.assign({}, props, { rows: [{ guid: 2432 }] }));
+
+ assert.notCalled(props.dispatch);
+
+ // Simulate listeners getting called
+ props.document.visibilityState = "visible";
+ listeners.forEach(l => l());
+
+ // Make sure we only sent the latest event
+ assert.calledOnce(props.dispatch);
+ const [action] = props.dispatch.firstCall.args;
+ assert.deepEqual(action.data.tiles, [{ id: 2432 }]);
+ });
+ });
+
+ describe("tab rehydrated", () => {
+ it("should fire NEW_TAB_REHYDRATED event", () => {
+ const dispatch = sinon.spy();
+ const TOP_STORIES_SECTION = {
+ id: "topstories",
+ title: "TopStories",
+ pref: { collapsed: false },
+ initialized: false,
+ rows: [{ guid: 1, link: "http://localhost", isDefault: true }],
+ topics: [],
+ read_more_endpoint: "http://localhost/read-more",
+ maxRows: 1,
+ eventSource: "TOP_STORIES",
+ };
+ wrapper = shallow(
+ <Section
+ Pocket={{ waitingForSpoc: true, pocketCta: {} }}
+ {...TOP_STORIES_SECTION}
+ dispatch={dispatch}
+ />
+ );
+ assert.notCalled(dispatch);
+
+ wrapper.setProps({ initialized: true });
+
+ assert.calledOnce(dispatch);
+ const [action] = dispatch.firstCall.args;
+ assert.equal("NEW_TAB_REHYDRATED", action.type);
+ });
+ });
+
+ describe("#numRows", () => {
+ it("should return maxRows if there is no rowsPref set", () => {
+ delete FAKE_SECTION.rowsPref;
+ wrapper = mountSectionIntlWithProps(FAKE_SECTION);
+ assert.equal(
+ wrapper.find(Section).instance().numRows,
+ FAKE_SECTION.maxRows
+ );
+ });
+
+ it("should return number of rows set in Pref if rowsPref is set", () => {
+ const numRows = 2;
+ Object.assign(FAKE_SECTION, {
+ rowsPref: "section.rows",
+ maxRows: 4,
+ Prefs: { values: { "section.rows": numRows } },
+ });
+ wrapper = mountSectionWithProps(FAKE_SECTION);
+ assert.equal(wrapper.find(Section).instance().numRows, numRows);
+ });
+
+ it("should return number of rows set in Pref even if higher than maxRows value", () => {
+ const numRows = 10;
+ Object.assign(FAKE_SECTION, {
+ rowsPref: "section.rows",
+ maxRows: 4,
+ Prefs: { values: { "section.rows": numRows } },
+ });
+ wrapper = mountSectionWithProps(FAKE_SECTION);
+ assert.equal(wrapper.find(Section).instance().numRows, numRows);
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/components/TopSites.test.jsx b/browser/components/newtab/test/unit/content-src/components/TopSites.test.jsx
new file mode 100644
index 0000000000..f5658d0b4e
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/TopSites.test.jsx
@@ -0,0 +1,1833 @@
+import { actionCreators as ac, actionTypes as at } from "common/Actions.jsm";
+import { GlobalOverrider } from "test/unit/utils";
+import {
+ MIN_CORNER_FAVICON_SIZE,
+ MIN_RICH_FAVICON_SIZE,
+} from "content-src/components/TopSites/TopSitesConstants";
+import {
+ INITIAL_STATE,
+ reducers,
+ TOP_SITES_DEFAULT_ROWS,
+ TOP_SITES_MAX_SITES_PER_ROW,
+} from "common/Reducers.jsm";
+import {
+ TopSite,
+ TopSiteLink,
+ TopSiteList,
+ TopSitePlaceholder,
+} from "content-src/components/TopSites/TopSite";
+import { A11yLinkButton } from "content-src/components/A11yLinkButton/A11yLinkButton";
+import { LinkMenu } from "content-src/components/LinkMenu/LinkMenu";
+import React from "react";
+import { SectionMenu } from "content-src/components/SectionMenu/SectionMenu";
+import { mount, shallow } from "enzyme";
+import { TopSiteForm } from "content-src/components/TopSites/TopSiteForm";
+import { TopSiteFormInput } from "content-src/components/TopSites/TopSiteFormInput";
+import { _TopSites as TopSites } from "content-src/components/TopSites/TopSites";
+import { ContextMenuButton } from "content-src/components/ContextMenu/ContextMenuButton";
+import { Provider } from "react-redux";
+import { combineReducers, createStore } from "redux";
+
+const perfSvc = {
+ mark() {},
+ getMostRecentAbsMarkStartByName() {},
+};
+
+const DEFAULT_PROPS = {
+ Prefs: { values: {} },
+ TopSites: { initialized: true, rows: [] },
+ TopSitesRows: TOP_SITES_DEFAULT_ROWS,
+ topSiteIconType: () => "no_image",
+ dispatch() {},
+ perfSvc,
+};
+
+const DEFAULT_BLOB_URL = "blob://test";
+
+describe("<TopSites>", () => {
+ let sandbox;
+
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ });
+
+ afterEach(() => {
+ sandbox.restore();
+ });
+
+ it("should render a TopSites element", () => {
+ const wrapper = shallow(<TopSites {...DEFAULT_PROPS} />);
+ assert.ok(wrapper.exists());
+ });
+ describe("context menu", () => {
+ function mountWithProps(props) {
+ const store = createStore(combineReducers(reducers), INITIAL_STATE);
+ return mount(
+ <Provider store={store}>
+ <TopSites {...props} />
+ </Provider>
+ );
+ }
+
+ it("should render a context menu button", () => {
+ const wrapper = mountWithProps(DEFAULT_PROPS);
+ assert.equal(
+ wrapper.find(".section-top-bar .context-menu-button").length,
+ 1
+ );
+ });
+ it("should render a section menu when button is clicked", () => {
+ const wrapper = mountWithProps(DEFAULT_PROPS);
+ const button = wrapper.find(".section-top-bar .context-menu-button");
+ assert.equal(wrapper.find(SectionMenu).length, 0);
+ button.simulate("click", { preventDefault: () => {} });
+ assert.equal(wrapper.find(SectionMenu).length, 1);
+ });
+ it("should not render a section menu by default", () => {
+ const wrapper = mountWithProps(DEFAULT_PROPS);
+ assert.equal(wrapper.find(SectionMenu).length, 0);
+ });
+ it("should pass through the correct menu extraOptions to SectionMenu", () => {
+ const wrapper = mountWithProps(DEFAULT_PROPS);
+ wrapper
+ .find(".section-top-bar .context-menu-button")
+ .simulate("click", { preventDefault: () => {} });
+ const sectionMenuProps = wrapper.find(SectionMenu).props();
+ assert.deepEqual(sectionMenuProps.extraOptions, ["AddTopSite"]);
+ });
+ });
+ describe("#_dispatchTopSitesStats", () => {
+ let globals;
+ let wrapper;
+ let dispatchStatsSpy;
+
+ beforeEach(() => {
+ globals = new GlobalOverrider();
+ sandbox.stub(DEFAULT_PROPS, "dispatch");
+ wrapper = shallow(<TopSites {...DEFAULT_PROPS} />, {
+ disableLifecycleMethods: true,
+ });
+ dispatchStatsSpy = sandbox.spy(
+ wrapper.instance(),
+ "_dispatchTopSitesStats"
+ );
+ });
+ afterEach(() => {
+ globals.restore();
+ sandbox.restore();
+ });
+ it("should call _dispatchTopSitesStats on componentDidMount", () => {
+ wrapper.instance().componentDidMount();
+
+ assert.calledOnce(dispatchStatsSpy);
+ });
+ it("should call _dispatchTopSitesStats on componentDidUpdate", () => {
+ wrapper.instance().componentDidUpdate();
+
+ assert.calledOnce(dispatchStatsSpy);
+ });
+ it("should dispatch SAVE_SESSION_PERF_DATA", () => {
+ wrapper.instance()._dispatchTopSitesStats();
+
+ assert.calledOnce(DEFAULT_PROPS.dispatch);
+ assert.calledWithExactly(
+ DEFAULT_PROPS.dispatch,
+ ac.AlsoToMain({
+ type: at.SAVE_SESSION_PERF_DATA,
+ data: {
+ topsites_icon_stats: {
+ custom_screenshot: 0,
+ screenshot_with_icon: 0,
+ screenshot: 0,
+ tippytop: 0,
+ rich_icon: 0,
+ no_image: 0,
+ },
+ topsites_pinned: 0,
+ topsites_search_shortcuts: 0,
+ },
+ })
+ );
+ });
+ it("should correctly count TopSite images - just screenshot", () => {
+ const rows = [{ screenshot: true }];
+ sandbox.stub(DEFAULT_PROPS.TopSites, "rows").value(rows);
+ wrapper.instance()._dispatchTopSitesStats();
+
+ assert.calledOnce(DEFAULT_PROPS.dispatch);
+ assert.calledWithExactly(
+ DEFAULT_PROPS.dispatch,
+ ac.AlsoToMain({
+ type: at.SAVE_SESSION_PERF_DATA,
+ data: {
+ topsites_icon_stats: {
+ custom_screenshot: 0,
+ screenshot_with_icon: 0,
+ screenshot: 1,
+ tippytop: 0,
+ rich_icon: 0,
+ no_image: 0,
+ },
+ topsites_pinned: 0,
+ topsites_search_shortcuts: 0,
+ },
+ })
+ );
+ });
+ it("should correctly count TopSite images - custom_screenshot", () => {
+ const rows = [{ customScreenshotURL: true }];
+ sandbox.stub(DEFAULT_PROPS.TopSites, "rows").value(rows);
+ wrapper.instance()._dispatchTopSitesStats();
+
+ assert.calledOnce(DEFAULT_PROPS.dispatch);
+ assert.calledWithExactly(
+ DEFAULT_PROPS.dispatch,
+ ac.AlsoToMain({
+ type: at.SAVE_SESSION_PERF_DATA,
+ data: {
+ topsites_icon_stats: {
+ custom_screenshot: 1,
+ screenshot_with_icon: 0,
+ screenshot: 0,
+ tippytop: 0,
+ rich_icon: 0,
+ no_image: 0,
+ },
+ topsites_pinned: 0,
+ topsites_search_shortcuts: 0,
+ },
+ })
+ );
+ });
+ it("should correctly count TopSite images - screenshot + favicon", () => {
+ const rows = [{ screenshot: true, faviconSize: MIN_CORNER_FAVICON_SIZE }];
+ sandbox.stub(DEFAULT_PROPS.TopSites, "rows").value(rows);
+ wrapper.instance()._dispatchTopSitesStats();
+
+ assert.calledOnce(DEFAULT_PROPS.dispatch);
+ assert.calledWithExactly(
+ DEFAULT_PROPS.dispatch,
+ ac.AlsoToMain({
+ type: at.SAVE_SESSION_PERF_DATA,
+ data: {
+ topsites_icon_stats: {
+ custom_screenshot: 0,
+ screenshot_with_icon: 1,
+ screenshot: 0,
+ tippytop: 0,
+ rich_icon: 0,
+ no_image: 0,
+ },
+ topsites_pinned: 0,
+ topsites_search_shortcuts: 0,
+ },
+ })
+ );
+ });
+ it("should correctly count TopSite images - rich_icon", () => {
+ const rows = [{ faviconSize: MIN_RICH_FAVICON_SIZE }];
+ sandbox.stub(DEFAULT_PROPS.TopSites, "rows").value(rows);
+ wrapper.instance()._dispatchTopSitesStats();
+
+ assert.calledOnce(DEFAULT_PROPS.dispatch);
+ assert.calledWithExactly(
+ DEFAULT_PROPS.dispatch,
+ ac.AlsoToMain({
+ type: at.SAVE_SESSION_PERF_DATA,
+ data: {
+ topsites_icon_stats: {
+ custom_screenshot: 0,
+ screenshot_with_icon: 0,
+ screenshot: 0,
+ tippytop: 0,
+ rich_icon: 1,
+ no_image: 0,
+ },
+ topsites_pinned: 0,
+ topsites_search_shortcuts: 0,
+ },
+ })
+ );
+ });
+ it("should correctly count TopSite images - tippytop", () => {
+ const rows = [
+ { tippyTopIcon: "foo" },
+ { faviconRef: "tippytop" },
+ { faviconRef: "foobar" },
+ ];
+ sandbox.stub(DEFAULT_PROPS.TopSites, "rows").value(rows);
+ wrapper.instance()._dispatchTopSitesStats();
+
+ assert.calledOnce(DEFAULT_PROPS.dispatch);
+ assert.calledWithExactly(
+ DEFAULT_PROPS.dispatch,
+ ac.AlsoToMain({
+ type: at.SAVE_SESSION_PERF_DATA,
+ data: {
+ topsites_icon_stats: {
+ custom_screenshot: 0,
+ screenshot_with_icon: 0,
+ screenshot: 0,
+ tippytop: 2,
+ rich_icon: 0,
+ no_image: 1,
+ },
+ topsites_pinned: 0,
+ topsites_search_shortcuts: 0,
+ },
+ })
+ );
+ });
+ it("should correctly count TopSite images - no image", () => {
+ const rows = [{}];
+ sandbox.stub(DEFAULT_PROPS.TopSites, "rows").value(rows);
+ wrapper.instance()._dispatchTopSitesStats();
+
+ assert.calledOnce(DEFAULT_PROPS.dispatch);
+ assert.calledWithExactly(
+ DEFAULT_PROPS.dispatch,
+ ac.AlsoToMain({
+ type: at.SAVE_SESSION_PERF_DATA,
+ data: {
+ topsites_icon_stats: {
+ custom_screenshot: 0,
+ screenshot_with_icon: 0,
+ screenshot: 0,
+ tippytop: 0,
+ rich_icon: 0,
+ no_image: 1,
+ },
+ topsites_pinned: 0,
+ topsites_search_shortcuts: 0,
+ },
+ })
+ );
+ });
+ it("should correctly count pinned Top Sites", () => {
+ const rows = [
+ { isPinned: true },
+ { isPinned: false },
+ { isPinned: true },
+ ];
+ sandbox.stub(DEFAULT_PROPS.TopSites, "rows").value(rows);
+ wrapper.instance()._dispatchTopSitesStats();
+
+ assert.calledOnce(DEFAULT_PROPS.dispatch);
+ assert.calledWithExactly(
+ DEFAULT_PROPS.dispatch,
+ ac.AlsoToMain({
+ type: at.SAVE_SESSION_PERF_DATA,
+ data: {
+ topsites_icon_stats: {
+ custom_screenshot: 0,
+ screenshot_with_icon: 0,
+ screenshot: 0,
+ tippytop: 0,
+ rich_icon: 0,
+ no_image: 3,
+ },
+ topsites_pinned: 2,
+ topsites_search_shortcuts: 0,
+ },
+ })
+ );
+ });
+ it("should correctly count search shortcut Top Sites", () => {
+ const rows = [{ searchTopSite: true }, { searchTopSite: true }];
+ sandbox.stub(DEFAULT_PROPS.TopSites, "rows").value(rows);
+ wrapper.instance()._dispatchTopSitesStats();
+
+ assert.calledOnce(DEFAULT_PROPS.dispatch);
+ assert.calledWithExactly(
+ DEFAULT_PROPS.dispatch,
+ ac.AlsoToMain({
+ type: at.SAVE_SESSION_PERF_DATA,
+ data: {
+ topsites_icon_stats: {
+ custom_screenshot: 0,
+ screenshot_with_icon: 0,
+ screenshot: 0,
+ tippytop: 0,
+ rich_icon: 0,
+ no_image: 2,
+ },
+ topsites_pinned: 0,
+ topsites_search_shortcuts: 2,
+ },
+ })
+ );
+ });
+ it("should only count visible top sites on wide layout", () => {
+ globals.set("matchMedia", () => ({ matches: true }));
+ const rows = [
+ {},
+ {},
+ {},
+ {},
+ {},
+ {},
+ {},
+ {},
+ {},
+ {},
+ {},
+ {},
+ {},
+ {},
+ {},
+ {},
+ ];
+ sandbox.stub(DEFAULT_PROPS.TopSites, "rows").value(rows);
+
+ wrapper.instance()._dispatchTopSitesStats();
+ assert.calledOnce(DEFAULT_PROPS.dispatch);
+ assert.calledWithExactly(
+ DEFAULT_PROPS.dispatch,
+ ac.AlsoToMain({
+ type: at.SAVE_SESSION_PERF_DATA,
+ data: {
+ topsites_icon_stats: {
+ custom_screenshot: 0,
+ screenshot_with_icon: 0,
+ screenshot: 0,
+ tippytop: 0,
+ rich_icon: 0,
+ no_image: 8,
+ },
+ topsites_pinned: 0,
+ topsites_search_shortcuts: 0,
+ },
+ })
+ );
+ });
+ it("should only count visible top sites on normal layout", () => {
+ globals.set("matchMedia", () => ({ matches: false }));
+ const rows = [
+ {},
+ {},
+ {},
+ {},
+ {},
+ {},
+ {},
+ {},
+ {},
+ {},
+ {},
+ {},
+ {},
+ {},
+ {},
+ {},
+ ];
+ sandbox.stub(DEFAULT_PROPS.TopSites, "rows").value(rows);
+ wrapper.instance()._dispatchTopSitesStats();
+ assert.calledOnce(DEFAULT_PROPS.dispatch);
+ assert.calledWithExactly(
+ DEFAULT_PROPS.dispatch,
+ ac.AlsoToMain({
+ type: at.SAVE_SESSION_PERF_DATA,
+ data: {
+ topsites_icon_stats: {
+ custom_screenshot: 0,
+ screenshot_with_icon: 0,
+ screenshot: 0,
+ tippytop: 0,
+ rich_icon: 0,
+ no_image: 6,
+ },
+ topsites_pinned: 0,
+ topsites_search_shortcuts: 0,
+ },
+ })
+ );
+ });
+ });
+});
+
+describe("<TopSiteLink>", () => {
+ let globals;
+ let link;
+ let url;
+ beforeEach(() => {
+ globals = new GlobalOverrider();
+ url = {
+ createObjectURL: globals.sandbox.stub().returns(DEFAULT_BLOB_URL),
+ revokeObjectURL: globals.sandbox.spy(),
+ };
+ globals.set("URL", url);
+ link = { url: "https://foo.com", screenshot: "foo.jpg", hostname: "foo" };
+ });
+ afterEach(() => globals.restore());
+ it("should add the right url", () => {
+ link.url = "https://www.foobar.org";
+ const wrapper = shallow(<TopSiteLink link={link} />);
+ assert.propertyVal(
+ wrapper.find("a").props(),
+ "href",
+ "https://www.foobar.org"
+ );
+ });
+ it("should not add the url to the href if it a search shortcut", () => {
+ link.searchTopSite = true;
+ const wrapper = shallow(<TopSiteLink link={link} />);
+ assert.isUndefined(wrapper.find("a").props().href);
+ });
+ it("should have rtl direction automatically set for text", () => {
+ const wrapper = shallow(<TopSiteLink link={link} />);
+
+ assert.isTrue(!!wrapper.find("[dir='auto']").length);
+ });
+ it("should render a title", () => {
+ const wrapper = shallow(<TopSiteLink link={link} title="foobar" />);
+ const titleEl = wrapper.find(".title");
+
+ assert.equal(titleEl.text(), "foobar");
+ });
+ it("should have only the title as the text of the link", () => {
+ const wrapper = shallow(<TopSiteLink link={link} title="foobar" />);
+
+ assert.equal(wrapper.find("a").text(), "foobar");
+ });
+ it("should render the pin icon for pinned links", () => {
+ link.isPinned = true;
+ link.pinnedIndex = 7;
+ const wrapper = shallow(<TopSiteLink link={link} />);
+ assert.equal(wrapper.find(".icon-pin-small").length, 1);
+ });
+ it("should not render the pin icon for non pinned links", () => {
+ link.isPinned = false;
+ const wrapper = shallow(<TopSiteLink link={link} />);
+ assert.equal(wrapper.find(".icon-pin-small").length, 0);
+ });
+ it("should render the first letter of the title as a fallback for missing screenshots", () => {
+ const wrapper = shallow(<TopSiteLink link={link} title={"foo"} />);
+ assert.equal(wrapper.find(".tile").prop("data-fallback"), "f");
+ });
+ it("should render a normal image screenshot with the .active class, if it is provided", () => {
+ const wrapper = shallow(<TopSiteLink link={link} />);
+ const screenshotEl = wrapper.find(".screenshot");
+
+ assert.propertyVal(
+ screenshotEl.props().style,
+ "backgroundImage",
+ "url(foo.jpg)"
+ );
+ assert.isTrue(screenshotEl.hasClass("active"));
+ });
+ it("should render a blob image screenshot with the .active class, if it is provided", () => {
+ link.screenshot = { path: "/test_path", data: new Blob([0]) };
+
+ const wrapper = shallow(<TopSiteLink link={link} />);
+ const screenshotEl = wrapper.find(".screenshot");
+
+ assert.propertyVal(
+ screenshotEl.props().style,
+ "backgroundImage",
+ `url(${DEFAULT_BLOB_URL})`
+ );
+ assert.isTrue(screenshotEl.hasClass("active"));
+ });
+ it("should render a small icon with fallback letter with the screenshot if the icon is smaller than 16x16", () => {
+ link.favicon = "too-small-icon.png";
+ link.faviconSize = 10;
+ const wrapper = shallow(<TopSiteLink link={link} title="foo" />);
+ const screenshotEl = wrapper.find(".screenshot");
+ const defaultIconEl = wrapper.find(".default-icon");
+
+ assert.propertyVal(
+ screenshotEl.props().style,
+ "backgroundImage",
+ "url(foo.jpg)"
+ );
+ assert.isTrue(screenshotEl.hasClass("active"));
+ assert.lengthOf(defaultIconEl, 1);
+ assert.equal(defaultIconEl.prop("data-fallback"), "f");
+ });
+ it("should render a small icon with fallback letter with the screenshot if the icon is missing", () => {
+ const wrapper = shallow(<TopSiteLink link={link} title="foo" />);
+ const screenshotEl = wrapper.find(".screenshot");
+ const defaultIconEl = wrapper.find(".default-icon");
+
+ assert.propertyVal(
+ screenshotEl.props().style,
+ "backgroundImage",
+ "url(foo.jpg)"
+ );
+ assert.isTrue(screenshotEl.hasClass("active"));
+ assert.lengthOf(defaultIconEl, 1);
+ assert.equal(defaultIconEl.prop("data-fallback"), "f");
+ });
+ it("should render a small icon with the screenshot if the icon is bigger than 32x32", () => {
+ link.favicon = "small-icon.png";
+ link.faviconSize = 32;
+
+ const wrapper = shallow(<TopSiteLink link={link} />);
+ const screenshotEl = wrapper.find(".screenshot");
+ const defaultIconEl = wrapper.find(".default-icon");
+
+ assert.propertyVal(
+ screenshotEl.props().style,
+ "backgroundImage",
+ "url(foo.jpg)"
+ );
+ assert.isTrue(screenshotEl.hasClass("active"));
+ assert.propertyVal(
+ defaultIconEl.props().style,
+ "backgroundImage",
+ `url(${link.favicon})`
+ );
+ assert.lengthOf(wrapper.find(".rich-icon"), 0);
+ });
+ it("should not add the .active class to the screenshot element if no screenshot prop is provided", () => {
+ link.screenshot = null;
+ const wrapper = shallow(<TopSiteLink link={link} />);
+ assert.isFalse(wrapper.find(".screenshot").hasClass("active"));
+ });
+ it("should render the tippy top icon if provided and not a small icon", () => {
+ link.tippyTopIcon = "foo.png";
+ link.backgroundColor = "#FFFFFF";
+ const wrapper = shallow(<TopSiteLink link={link} />);
+ assert.lengthOf(wrapper.find(".screenshot"), 0);
+ assert.lengthOf(wrapper.find(".default-icon"), 0);
+ const tippyTop = wrapper.find(".rich-icon");
+ assert.propertyVal(
+ tippyTop.props().style,
+ "backgroundImage",
+ "url(foo.png)"
+ );
+ assert.propertyVal(tippyTop.props().style, "backgroundColor", "#FFFFFF");
+ });
+ it("should render a rich icon if provided and not a small icon", () => {
+ link.favicon = "foo.png";
+ link.faviconSize = 196;
+ link.backgroundColor = "#FFFFFF";
+ const wrapper = shallow(<TopSiteLink link={link} />);
+ assert.lengthOf(wrapper.find(".screenshot"), 0);
+ assert.lengthOf(wrapper.find(".default-icon"), 0);
+ const richIcon = wrapper.find(".rich-icon");
+ assert.propertyVal(
+ richIcon.props().style,
+ "backgroundImage",
+ "url(foo.png)"
+ );
+ assert.propertyVal(richIcon.props().style, "backgroundColor", "#FFFFFF");
+ });
+ it("should not render a rich icon if it is smaller than 96x96", () => {
+ link.favicon = "foo.png";
+ link.faviconSize = 48;
+ link.backgroundColor = "#FFFFFF";
+ const wrapper = shallow(<TopSiteLink link={link} />);
+ assert.equal(wrapper.find(".screenshot").length, 1);
+ assert.equal(wrapper.find(".rich-icon").length, 0);
+ });
+ it("should apply just the default class name to the outer link if props.className is falsey", () => {
+ const wrapper = shallow(<TopSiteLink className={false} />);
+ assert.ok(wrapper.find("li").hasClass("top-site-outer"));
+ });
+ it("should add props.className to the outer link element", () => {
+ const wrapper = shallow(<TopSiteLink className="foo bar" />);
+ assert.ok(wrapper.find("li").hasClass("top-site-outer foo bar"));
+ });
+ describe("#onDragEvent", () => {
+ let simulate;
+ let wrapper;
+ beforeEach(() => {
+ wrapper = shallow(
+ <TopSiteLink isDraggable={true} onDragEvent={() => {}} />
+ );
+ simulate = type => {
+ const event = {
+ dataTransfer: { setData() {}, types: { includes() {} } },
+ preventDefault() {
+ this.prevented = true;
+ },
+ target: { blur() {} },
+ type,
+ };
+ wrapper.simulate(type, event);
+ return event;
+ };
+ });
+ it("should allow clicks without dragging", () => {
+ simulate("mousedown");
+ simulate("mouseup");
+
+ const event = simulate("click");
+
+ assert.notOk(event.prevented);
+ });
+ it("should prevent clicks after dragging", () => {
+ simulate("mousedown");
+ simulate("dragstart");
+ simulate("dragenter");
+ simulate("drop");
+ simulate("dragend");
+ simulate("mouseup");
+
+ const event = simulate("click");
+
+ assert.ok(event.prevented);
+ });
+ it("should allow clicks after dragging then clicking", () => {
+ simulate("mousedown");
+ simulate("dragstart");
+ simulate("dragenter");
+ simulate("drop");
+ simulate("dragend");
+ simulate("mouseup");
+ simulate("click");
+
+ simulate("mousedown");
+ simulate("mouseup");
+
+ const event = simulate("click");
+
+ assert.notOk(event.prevented);
+ });
+ });
+
+ describe("#generateColor", () => {
+ let colors;
+ beforeEach(() => {
+ colors = "#0090ED,#FF4F5F,#2AC3A2";
+ });
+
+ it("should generate a random color but always pick the same color for the same string", async () => {
+ let wrapper = shallow(
+ <TopSiteLink
+ newNewtabExperienceEnabled={true}
+ colors={colors}
+ title={"food"}
+ link={link}
+ />
+ );
+
+ assert.equal(wrapper.find(".icon-wrapper").prop("data-fallback"), "f");
+ assert.equal(
+ wrapper.find(".icon-wrapper").prop("style").backgroundColor,
+ colors.split(",")[1]
+ );
+ assert.ok(true);
+ });
+
+ it("should generate a different random color", async () => {
+ let wrapper = shallow(
+ <TopSiteLink
+ newNewtabExperienceEnabled={true}
+ colors={colors}
+ title={"fam"}
+ link={link}
+ />
+ );
+
+ assert.equal(
+ wrapper.find(".icon-wrapper").prop("style").backgroundColor,
+ colors.split(",")[2]
+ );
+ assert.ok(true);
+ });
+
+ it("should generate a third random color", async () => {
+ let wrapper = shallow(
+ <TopSiteLink
+ newNewtabExperienceEnabled={true}
+ colors={colors}
+ title={"foo"}
+ />
+ );
+
+ assert.equal(wrapper.find(".icon-wrapper").prop("data-fallback"), "f");
+ assert.equal(
+ wrapper.find(".icon-wrapper").prop("style").backgroundColor,
+ colors.split(",")[0]
+ );
+ assert.ok(true);
+ });
+ });
+});
+
+describe("<TopSite>", () => {
+ let link;
+ beforeEach(() => {
+ link = { url: "https://foo.com", screenshot: "foo.jpg", hostname: "foo" };
+ });
+
+ it("should render a TopSite", () => {
+ const wrapper = shallow(<TopSite link={link} />);
+ assert.ok(wrapper.exists());
+ });
+
+ it("should render a shortened title based off the url", () => {
+ link.url = "https://www.foobar.org";
+ link.hostname = "foobar";
+ link.eTLD = "org";
+ const wrapper = shallow(<TopSite link={link} />);
+
+ assert.equal(wrapper.find(TopSiteLink).props().title, "foobar");
+ });
+
+ it("should parse args for fluent correctly", () => {
+ const title = '"fluent"';
+ link.hostname = title;
+
+ const wrapper = mount(<TopSite link={link} />);
+ const button = wrapper.find(
+ "button[data-l10n-id='newtab-menu-content-tooltip']"
+ );
+ assert.equal(button.prop("data-l10n-args"), JSON.stringify({ title }));
+ });
+
+ it("should have .active class, on top-site-outer if context menu is open", () => {
+ const wrapper = shallow(<TopSite link={link} index={1} activeIndex={1} />);
+ wrapper.setState({ showContextMenu: true });
+
+ assert.equal(
+ wrapper
+ .find(TopSiteLink)
+ .props()
+ .className.trim(),
+ "active"
+ );
+ });
+ it("should not add .active class, on top-site-outer if context menu is closed", () => {
+ const wrapper = shallow(<TopSite link={link} index={1} />);
+ wrapper.setState({ showContextMenu: false, activeTile: 1 });
+ assert.equal(wrapper.find(TopSiteLink).props().className, "");
+ });
+ it("should render a context menu button", () => {
+ const wrapper = shallow(<TopSite link={link} />);
+ assert.equal(wrapper.find(ContextMenuButton).length, 1);
+ });
+ it("should render a link menu", () => {
+ const wrapper = shallow(<TopSite link={link} />);
+ assert.equal(wrapper.find(LinkMenu).length, 1);
+ });
+ it("should pass onUpdate, site, options, and index to LinkMenu", () => {
+ const wrapper = shallow(<TopSite link={link} />);
+ const linkMenuProps = wrapper.find(LinkMenu).props();
+ ["onUpdate", "site", "index", "options"].forEach(prop =>
+ assert.property(linkMenuProps, prop)
+ );
+ });
+ it("should pass through the correct menu options to LinkMenu", () => {
+ const wrapper = shallow(<TopSite link={link} />);
+ const linkMenuProps = wrapper.find(LinkMenu).props();
+ assert.deepEqual(linkMenuProps.options, [
+ "CheckPinTopSite",
+ "EditTopSite",
+ "Separator",
+ "OpenInNewWindow",
+ "OpenInPrivateWindow",
+ "Separator",
+ "BlockUrl",
+ "DeleteUrl",
+ ]);
+ });
+
+ describe("#onLinkClick", () => {
+ it("should call dispatch when the link is clicked", () => {
+ const dispatch = sinon.stub();
+ const wrapper = shallow(
+ <TopSite link={link} index={3} dispatch={dispatch} />
+ );
+
+ wrapper.find(TopSiteLink).simulate("click", { preventDefault() {} });
+
+ assert.calledTwice(dispatch);
+ });
+ it("should dispatch a UserEventAction with the right data", () => {
+ const dispatch = sinon.stub();
+ const wrapper = shallow(
+ <TopSite
+ link={Object.assign({}, link, {
+ iconType: "rich_icon",
+ isPinned: true,
+ })}
+ index={3}
+ dispatch={dispatch}
+ />
+ );
+
+ wrapper.find(TopSiteLink).simulate("click", { preventDefault() {} });
+
+ const [action] = dispatch.firstCall.args;
+ assert.isUserEventAction(action);
+
+ assert.propertyVal(action.data, "event", "CLICK");
+ assert.propertyVal(action.data, "source", "TOP_SITES");
+ assert.propertyVal(action.data, "action_position", 3);
+ assert.propertyVal(action.data.value, "card_type", "pinned");
+ assert.propertyVal(action.data.value, "icon_type", "rich_icon");
+ });
+ it("should dispatch a UserEventAction with the right data for search top site", () => {
+ const dispatch = sinon.stub();
+ const siteInfo = {
+ iconType: "tippytop",
+ isPinned: true,
+ searchTopSite: true,
+ hostname: "google",
+ label: "@google",
+ };
+ const wrapper = shallow(
+ <TopSite
+ link={Object.assign({}, link, siteInfo)}
+ index={3}
+ dispatch={dispatch}
+ />
+ );
+
+ wrapper.find(TopSiteLink).simulate("click", { preventDefault() {} });
+
+ const [action] = dispatch.firstCall.args;
+ assert.isUserEventAction(action);
+
+ assert.propertyVal(action.data, "event", "CLICK");
+ assert.propertyVal(action.data, "source", "TOP_SITES");
+ assert.propertyVal(action.data, "action_position", 3);
+ assert.propertyVal(action.data.value, "card_type", "search");
+ assert.propertyVal(action.data.value, "icon_type", "tippytop");
+ assert.propertyVal(action.data.value, "search_vendor", "google");
+ });
+ it("should dispatch a UserEventAction with the right data for SPOC top site", () => {
+ const dispatch = sinon.stub();
+ const siteInfo = {
+ iconType: "custom_screenshot",
+ type: "SPOC",
+ };
+ const wrapper = shallow(
+ <TopSite
+ link={Object.assign({}, link, siteInfo)}
+ index={0}
+ dispatch={dispatch}
+ />
+ );
+
+ wrapper.find(TopSiteLink).simulate("click", { preventDefault() {} });
+
+ const [action] = dispatch.firstCall.args;
+ assert.isUserEventAction(action);
+
+ assert.propertyVal(action.data, "event", "CLICK");
+ assert.propertyVal(action.data, "source", "TOP_SITES");
+ assert.propertyVal(action.data, "action_position", 0);
+ assert.propertyVal(action.data.value, "card_type", "spoc");
+ assert.propertyVal(action.data.value, "icon_type", "custom_screenshot");
+ });
+ it("should dispatch OPEN_LINK with the right data", () => {
+ const dispatch = sinon.stub();
+ const wrapper = shallow(
+ <TopSite
+ link={Object.assign({}, link, { typedBonus: true })}
+ index={3}
+ dispatch={dispatch}
+ />
+ );
+
+ wrapper.find(TopSiteLink).simulate("click", { preventDefault() {} });
+
+ const [action] = dispatch.secondCall.args;
+ assert.propertyVal(action, "type", at.OPEN_LINK);
+ assert.propertyVal(action.data, "typedBonus", true);
+ });
+ });
+});
+
+describe("<TopSiteForm>", () => {
+ let wrapper;
+ let sandbox;
+
+ function setup(props = {}) {
+ sandbox = sinon.createSandbox();
+ const customProps = Object.assign(
+ {},
+ { onClose: sandbox.spy(), dispatch: sandbox.spy() },
+ props
+ );
+ wrapper = mount(<TopSiteForm {...customProps} />);
+ }
+
+ describe("validateForm", () => {
+ beforeEach(() => setup({ site: { url: "http://foo" } }));
+
+ it("should return true for a correct URL", () => {
+ wrapper.setState({ url: "foo" });
+
+ assert.isTrue(wrapper.instance().validateForm());
+ });
+
+ it("should return false for a incorrect URL", () => {
+ wrapper.setState({ url: " " });
+
+ assert.isNull(wrapper.instance().validateForm());
+ assert.isTrue(wrapper.state().validationError);
+ });
+
+ it("should return true for a correct custom screenshot URL", () => {
+ wrapper.setState({ customScreenshotUrl: "foo" });
+
+ assert.isTrue(wrapper.instance().validateForm());
+ });
+
+ it("should return false for a incorrect custom screenshot URL", () => {
+ wrapper.setState({ customScreenshotUrl: " " });
+
+ assert.isNull(wrapper.instance().validateForm());
+ });
+
+ it("should return true for an empty custom screenshot URL", () => {
+ wrapper.setState({ customScreenshotUrl: "" });
+
+ assert.isTrue(wrapper.instance().validateForm());
+ });
+
+ it("should return false for file: protocol", () => {
+ wrapper.setState({ customScreenshotUrl: "file:///C:/Users/foo" });
+
+ assert.isFalse(wrapper.instance().validateForm());
+ });
+ });
+
+ describe("#previewButton", () => {
+ beforeEach(() =>
+ setup({
+ site: { customScreenshotURL: "http://foo.com" },
+ previewResponse: null,
+ })
+ );
+
+ it("should render the preview button on invalid urls", () => {
+ assert.equal(0, wrapper.find(".preview").length);
+
+ wrapper.setState({ customScreenshotUrl: " " });
+
+ assert.equal(1, wrapper.find(".preview").length);
+ });
+
+ it("should render the preview button when input value updated", () => {
+ assert.equal(0, wrapper.find(".preview").length);
+
+ wrapper.setState({
+ customScreenshotUrl: "http://baz.com",
+ screenshotPreview: null,
+ });
+
+ assert.equal(1, wrapper.find(".preview").length);
+ });
+ });
+
+ describe("preview request", () => {
+ beforeEach(() => {
+ setup({
+ site: { customScreenshotURL: "http://foo.com", url: "http://foo.com" },
+ previewResponse: null,
+ });
+ });
+
+ it("shouldn't dispatch a request for invalid urls", () => {
+ wrapper.setState({ customScreenshotUrl: " ", url: "foo" });
+
+ wrapper.find(".preview").simulate("click");
+
+ assert.notCalled(wrapper.props().dispatch);
+ });
+
+ it("should dispatch a PREVIEW_REQUEST", () => {
+ wrapper.setState({ customScreenshotUrl: "screenshot" });
+ wrapper.find(".preview").simulate("submit");
+
+ assert.calledTwice(wrapper.props().dispatch);
+ assert.calledWith(
+ wrapper.props().dispatch,
+ ac.AlsoToMain({
+ type: at.PREVIEW_REQUEST,
+ data: { url: "http://screenshot" },
+ })
+ );
+ assert.calledWith(
+ wrapper.props().dispatch,
+ ac.UserEvent({
+ event: "PREVIEW_REQUEST",
+ source: "TOP_SITES",
+ })
+ );
+ });
+ });
+
+ describe("#TopSiteLink", () => {
+ beforeEach(() => {
+ setup();
+ });
+
+ it("should display a TopSiteLink preview", () => {
+ assert.equal(wrapper.find(TopSiteLink).length, 1);
+ });
+
+ it("should display the preview screenshot", () => {
+ wrapper.setProps({ site: { tippyTopIcon: "bar" } });
+
+ assert.equal(
+ wrapper.find(".top-site-icon").getDOMNode().style["background-image"],
+ 'url("bar")'
+ );
+
+ wrapper.setProps({ previewResponse: "foo", previewUrl: "foo" });
+
+ assert.equal(
+ wrapper.find(".top-site-icon").getDOMNode().style["background-image"],
+ 'url("foo")'
+ );
+ });
+
+ it("should not render any icon on error", () => {
+ wrapper.setProps({ previewResponse: "" });
+
+ assert.equal(wrapper.find(".top-site-icon").length, 0);
+ });
+
+ it("should render the search icon when searchTopSite is true", () => {
+ wrapper.setProps({ site: { tippyTopIcon: "bar", searchTopSite: true } });
+
+ assert.equal(
+ wrapper.find(".rich-icon").getDOMNode().style["background-image"],
+ 'url("bar")'
+ );
+ assert.isTrue(wrapper.find(".search-topsite").exists());
+ });
+ });
+
+ describe("#addMode", () => {
+ beforeEach(() => setup());
+
+ it("should render the component", () => {
+ assert.ok(wrapper.find(TopSiteForm).exists());
+ });
+ it("should have the correct header", () => {
+ assert.equal(
+ wrapper.findWhere(
+ n =>
+ n.length &&
+ n.prop("data-l10n-id") === "newtab-topsites-add-topsites-header"
+ ).length,
+ 1
+ );
+ });
+ it("should have the correct button text", () => {
+ assert.equal(
+ wrapper.findWhere(
+ n =>
+ n.length && n.prop("data-l10n-id") === "newtab-topsites-save-button"
+ ).length,
+ 0
+ );
+ assert.equal(
+ wrapper.findWhere(
+ n =>
+ n.length && n.prop("data-l10n-id") === "newtab-topsites-add-button"
+ ).length,
+ 1
+ );
+ });
+ it("should not render a preview button", () => {
+ assert.equal(0, wrapper.find(".custom-image-input-container").length);
+ });
+ it("should call onClose if Cancel button is clicked", () => {
+ wrapper.find(".cancel").simulate("click");
+ assert.calledOnce(wrapper.instance().props.onClose);
+ });
+ it("should set validationError if url is empty", () => {
+ assert.equal(wrapper.state().validationError, false);
+ wrapper.find(".done").simulate("submit");
+ assert.equal(wrapper.state().validationError, true);
+ });
+ it("should set validationError if url is invalid", () => {
+ wrapper.setState({ url: "not valid" });
+ assert.equal(wrapper.state().validationError, false);
+ wrapper.find(".done").simulate("submit");
+ assert.equal(wrapper.state().validationError, true);
+ });
+ it("should call onClose and dispatch with right args if URL is valid", () => {
+ wrapper.setState({ url: "valid.com", label: "a label" });
+ wrapper.find(".done").simulate("submit");
+ assert.calledOnce(wrapper.instance().props.onClose);
+ assert.calledWith(wrapper.instance().props.dispatch, {
+ data: {
+ site: { label: "a label", url: "http://valid.com" },
+ index: -1,
+ },
+ meta: { from: "ActivityStream:Content", to: "ActivityStream:Main" },
+ type: at.TOP_SITES_PIN,
+ });
+ assert.calledWith(wrapper.instance().props.dispatch, {
+ data: {
+ action_position: -1,
+ source: "TOP_SITES",
+ event: "TOP_SITES_EDIT",
+ },
+ meta: { from: "ActivityStream:Content", to: "ActivityStream:Main" },
+ type: at.TELEMETRY_USER_EVENT,
+ });
+ });
+ it("should not pass empty string label in dispatch data", () => {
+ wrapper.setState({ url: "valid.com", label: "" });
+ wrapper.find(".done").simulate("submit");
+ assert.calledWith(wrapper.instance().props.dispatch, {
+ data: { site: { url: "http://valid.com" }, index: -1 },
+ meta: { from: "ActivityStream:Content", to: "ActivityStream:Main" },
+ type: at.TOP_SITES_PIN,
+ });
+ });
+ it("should open the custom screenshot input", () => {
+ assert.isFalse(wrapper.state().showCustomScreenshotForm);
+
+ wrapper.find(A11yLinkButton).simulate("click");
+
+ assert.isTrue(wrapper.state().showCustomScreenshotForm);
+ });
+ });
+
+ describe("edit existing Topsite", () => {
+ beforeEach(() =>
+ setup({
+ site: {
+ url: "https://foo.bar",
+ label: "baz",
+ customScreenshotURL: "http://foo",
+ },
+ index: 7,
+ })
+ );
+
+ it("should render the component", () => {
+ assert.ok(wrapper.find(TopSiteForm).exists());
+ });
+ it("should have the correct header", () => {
+ assert.equal(
+ wrapper.findWhere(
+ n => n.prop("data-l10n-id") === "newtab-topsites-edit-topsites-header"
+ ).length,
+ 1
+ );
+ });
+ it("should have the correct button text", () => {
+ assert.equal(
+ wrapper.findWhere(
+ n => n.prop("data-l10n-id") === "newtab-topsites-add-button"
+ ).length,
+ 0
+ );
+ assert.equal(
+ wrapper.findWhere(
+ n => n.prop("data-l10n-id") === "newtab-topsites-save-button"
+ ).length,
+ 1
+ );
+ });
+ it("should call onClose if Cancel button is clicked", () => {
+ wrapper.find(".cancel").simulate("click");
+ assert.calledOnce(wrapper.instance().props.onClose);
+ });
+ it("should show error and not call onClose or dispatch if URL is empty", () => {
+ wrapper.setState({ url: "" });
+ assert.equal(wrapper.state().validationError, false);
+ wrapper.find(".done").simulate("submit");
+ assert.equal(wrapper.state().validationError, true);
+ assert.notCalled(wrapper.instance().props.onClose);
+ assert.notCalled(wrapper.instance().props.dispatch);
+ });
+ it("should show error and not call onClose or dispatch if URL is invalid", () => {
+ wrapper.setState({ url: "not valid" });
+ assert.equal(wrapper.state().validationError, false);
+ wrapper.find(".done").simulate("submit");
+ assert.equal(wrapper.state().validationError, true);
+ assert.notCalled(wrapper.instance().props.onClose);
+ assert.notCalled(wrapper.instance().props.dispatch);
+ });
+ it("should call onClose and dispatch with right args if URL is valid", () => {
+ wrapper.find(".done").simulate("submit");
+ assert.calledOnce(wrapper.instance().props.onClose);
+ assert.calledTwice(wrapper.instance().props.dispatch);
+ assert.calledWith(wrapper.instance().props.dispatch, {
+ data: {
+ site: {
+ label: "baz",
+ url: "https://foo.bar",
+ customScreenshotURL: "http://foo",
+ },
+ index: 7,
+ },
+ meta: { from: "ActivityStream:Content", to: "ActivityStream:Main" },
+ type: at.TOP_SITES_PIN,
+ });
+ assert.calledWith(wrapper.instance().props.dispatch, {
+ data: {
+ action_position: 7,
+ source: "TOP_SITES",
+ event: "TOP_SITES_EDIT",
+ },
+ meta: { from: "ActivityStream:Content", to: "ActivityStream:Main" },
+ type: at.TELEMETRY_USER_EVENT,
+ });
+ });
+ it("should set customScreenshotURL to null if it was removed", () => {
+ wrapper.setState({ customScreenshotUrl: "" });
+
+ wrapper.find(".done").simulate("submit");
+
+ assert.calledWith(wrapper.instance().props.dispatch, {
+ data: {
+ site: {
+ label: "baz",
+ url: "https://foo.bar",
+ customScreenshotURL: null,
+ },
+ index: 7,
+ },
+ meta: { from: "ActivityStream:Content", to: "ActivityStream:Main" },
+ type: at.TOP_SITES_PIN,
+ });
+ });
+ it("should call onClose and dispatch with right args if URL is valid (negative index)", () => {
+ wrapper.setProps({ index: -1 });
+ wrapper.find(".done").simulate("submit");
+ assert.calledOnce(wrapper.instance().props.onClose);
+ assert.calledTwice(wrapper.instance().props.dispatch);
+ assert.calledWith(wrapper.instance().props.dispatch, {
+ data: {
+ site: {
+ label: "baz",
+ url: "https://foo.bar",
+ customScreenshotURL: "http://foo",
+ },
+ index: -1,
+ },
+ meta: { from: "ActivityStream:Content", to: "ActivityStream:Main" },
+ type: at.TOP_SITES_PIN,
+ });
+ });
+ it("should not pass empty string label in dispatch data", () => {
+ wrapper.setState({ label: "" });
+ wrapper.find(".done").simulate("submit");
+ assert.calledWith(wrapper.instance().props.dispatch, {
+ data: {
+ site: { url: "https://foo.bar", customScreenshotURL: "http://foo" },
+ index: 7,
+ },
+ meta: { from: "ActivityStream:Content", to: "ActivityStream:Main" },
+ type: at.TOP_SITES_PIN,
+ });
+ });
+ it("should render the save button if custom screenshot request finished", () => {
+ wrapper.setState({
+ customScreenshotUrl: "foo",
+ screenshotPreview: "custom",
+ });
+ assert.equal(0, wrapper.find(".preview").length);
+ assert.equal(1, wrapper.find(".done").length);
+ });
+ it("should render the save button if custom screenshot url was cleared", () => {
+ wrapper.setState({ customScreenshotUrl: "" });
+ wrapper.setProps({ site: { customScreenshotURL: "foo" } });
+ assert.equal(0, wrapper.find(".preview").length);
+ assert.equal(1, wrapper.find(".done").length);
+ });
+ });
+
+ describe("#previewMode", () => {
+ beforeEach(() => setup({ previewResponse: null }));
+
+ it("should transition from save to preview", () => {
+ wrapper.setProps({
+ site: { url: "https://foo.bar", customScreenshotURL: "baz" },
+ index: 7,
+ });
+
+ assert.equal(
+ wrapper.findWhere(
+ n =>
+ n.length && n.prop("data-l10n-id") === "newtab-topsites-save-button"
+ ).length,
+ 1
+ );
+
+ wrapper.setState({ customScreenshotUrl: "foo" });
+
+ assert.equal(
+ wrapper.findWhere(
+ n =>
+ n.length &&
+ n.prop("data-l10n-id") === "newtab-topsites-preview-button"
+ ).length,
+ 1
+ );
+ });
+
+ it("should transition from add to preview", () => {
+ assert.equal(
+ wrapper.findWhere(
+ n =>
+ n.length && n.prop("data-l10n-id") === "newtab-topsites-add-button"
+ ).length,
+ 1
+ );
+
+ wrapper.setState({ customScreenshotUrl: "foo" });
+
+ assert.equal(
+ wrapper.findWhere(
+ n =>
+ n.length &&
+ n.prop("data-l10n-id") === "newtab-topsites-preview-button"
+ ).length,
+ 1
+ );
+ });
+ });
+
+ describe("#validateUrl", () => {
+ it("should properly validate URLs", () => {
+ setup();
+ assert.ok(wrapper.instance().validateUrl("mozilla.org"));
+ assert.ok(wrapper.instance().validateUrl("https://mozilla.org"));
+ assert.ok(wrapper.instance().validateUrl("http://mozilla.org"));
+ assert.ok(
+ wrapper
+ .instance()
+ .validateUrl(
+ "https://mozilla.invisionapp.com/d/main/#/projects/prototypes"
+ )
+ );
+ assert.ok(wrapper.instance().validateUrl("httpfoobar"));
+ assert.ok(wrapper.instance().validateUrl("httpsfoo.bar"));
+ assert.isNull(wrapper.instance().validateUrl("mozilla org"));
+ assert.isNull(wrapper.instance().validateUrl(""));
+ });
+ });
+
+ describe("#cleanUrl", () => {
+ it("should properly prepend http:// to URLs when required", () => {
+ setup();
+ assert.equal(
+ "http://mozilla.org",
+ wrapper.instance().cleanUrl("mozilla.org")
+ );
+ assert.equal(
+ "http://https.org",
+ wrapper.instance().cleanUrl("https.org")
+ );
+ assert.equal("http://httpcom", wrapper.instance().cleanUrl("httpcom"));
+ assert.equal(
+ "http://mozilla.org",
+ wrapper.instance().cleanUrl("http://mozilla.org")
+ );
+ assert.equal(
+ "https://firefox.com",
+ wrapper.instance().cleanUrl("https://firefox.com")
+ );
+ });
+ });
+});
+
+describe("<TopSiteList>", () => {
+ it("should render a TopSiteList element", () => {
+ const wrapper = shallow(<TopSiteList {...DEFAULT_PROPS} />);
+ assert.ok(wrapper.exists());
+ });
+ it("should render a TopSite for each link with the right url", () => {
+ const rows = [{ url: "https://foo.com" }, { url: "https://bar.com" }];
+ const wrapper = shallow(
+ <TopSiteList {...DEFAULT_PROPS} TopSites={{ rows }} />
+ );
+ const links = wrapper.find(TopSite);
+ assert.lengthOf(links, 2);
+ rows.forEach((row, i) =>
+ assert.equal(links.get(i).props.link.url, row.url)
+ );
+ });
+ it("should slice the TopSite rows to the TopSitesRows pref", () => {
+ const rows = [];
+ for (
+ let i = 0;
+ i < TOP_SITES_DEFAULT_ROWS * TOP_SITES_MAX_SITES_PER_ROW + 3;
+ i++
+ ) {
+ rows.push({ url: `https://foo${i}.com` });
+ }
+ const wrapper = shallow(
+ <TopSiteList
+ {...DEFAULT_PROPS}
+ TopSites={{ rows }}
+ TopSitesRows={TOP_SITES_DEFAULT_ROWS}
+ />
+ );
+ const links = wrapper.find(TopSite);
+ assert.lengthOf(
+ links,
+ TOP_SITES_DEFAULT_ROWS * TOP_SITES_MAX_SITES_PER_ROW
+ );
+ });
+ it("should fill with placeholders if TopSites rows is less than TopSitesRows", () => {
+ const rows = [{ url: "https://foo.com" }, { url: "https://bar.com" }];
+ const wrapper = shallow(
+ <TopSiteList {...DEFAULT_PROPS} TopSites={{ rows }} TopSitesRows={1} />
+ );
+ assert.lengthOf(wrapper.find(TopSite), 2, "topSites");
+ assert.lengthOf(
+ wrapper.find(TopSitePlaceholder),
+ TOP_SITES_MAX_SITES_PER_ROW - 2,
+ "placeholders"
+ );
+ });
+ it("should fill any holes in TopSites with placeholders", () => {
+ const rows = [{ url: "https://foo.com" }];
+ rows[3] = { url: "https://bar.com" };
+ const wrapper = shallow(
+ <TopSiteList {...DEFAULT_PROPS} TopSites={{ rows }} TopSitesRows={1} />
+ );
+ assert.lengthOf(wrapper.find(TopSite), 2, "topSites");
+ assert.lengthOf(
+ wrapper.find(TopSitePlaceholder),
+ TOP_SITES_MAX_SITES_PER_ROW - 2,
+ "placeholders"
+ );
+ });
+ it("should update state onDragStart and clear it onDragEnd", () => {
+ const wrapper = shallow(<TopSiteList {...DEFAULT_PROPS} />);
+ const instance = wrapper.instance();
+ const index = 7;
+ const link = { url: "https://foo.com" };
+ const title = "foo";
+ instance.onDragEvent({ type: "dragstart" }, index, link, title);
+ assert.equal(instance.state.draggedIndex, index);
+ assert.equal(instance.state.draggedSite, link);
+ assert.equal(instance.state.draggedTitle, title);
+ instance.onDragEvent({ type: "dragend" });
+ assert.deepEqual(instance.state, TopSiteList.DEFAULT_STATE);
+ });
+ it("should clear state when new props arrive after a drop", () => {
+ const site1 = { url: "https://foo.com" };
+ const site2 = { url: "https://bar.com" };
+ const rows = [site1, site2];
+ const wrapper = shallow(
+ <TopSiteList {...DEFAULT_PROPS} TopSites={{ rows }} />
+ );
+ const instance = wrapper.instance();
+ instance.setState({
+ draggedIndex: 1,
+ draggedSite: site2,
+ draggedTitle: "bar",
+ topSitesPreview: [],
+ });
+ wrapper.setProps({ TopSites: { rows: [site2, site1] } });
+ assert.deepEqual(instance.state, TopSiteList.DEFAULT_STATE);
+ });
+ it("should dispatch events on drop", () => {
+ const dispatch = sinon.spy();
+ const wrapper = shallow(
+ <TopSiteList {...DEFAULT_PROPS} dispatch={dispatch} />
+ );
+ const instance = wrapper.instance();
+ const index = 7;
+ const link = { url: "https://foo.com", customScreenshotURL: "foo" };
+ const title = "foo";
+ instance.onDragEvent({ type: "dragstart" }, index, link, title);
+ dispatch.resetHistory();
+ instance.onDragEvent({ type: "drop" }, 3);
+ assert.calledTwice(dispatch);
+ assert.calledWith(dispatch, {
+ data: {
+ draggedFromIndex: 7,
+ index: 3,
+ site: {
+ label: "foo",
+ url: "https://foo.com",
+ customScreenshotURL: "foo",
+ },
+ },
+ meta: { from: "ActivityStream:Content", to: "ActivityStream:Main" },
+ type: "TOP_SITES_INSERT",
+ });
+ assert.calledWith(dispatch, {
+ data: { action_position: 3, event: "DROP", source: "TOP_SITES" },
+ meta: { from: "ActivityStream:Content", to: "ActivityStream:Main" },
+ type: "TELEMETRY_USER_EVENT",
+ });
+ });
+ it("should make a topSitesPreview onDragEnter", () => {
+ const wrapper = shallow(<TopSiteList {...DEFAULT_PROPS} />);
+ const instance = wrapper.instance();
+ const site = { url: "https://foo.com" };
+ instance.setState({
+ draggedIndex: 4,
+ draggedSite: site,
+ draggedTitle: "foo",
+ });
+ const draggedSite = Object.assign({}, site, {
+ isPinned: true,
+ isDragged: true,
+ });
+ instance.onDragEvent({ type: "dragenter" }, 2);
+ assert.ok(instance.state.topSitesPreview);
+ assert.deepEqual(instance.state.topSitesPreview[2], draggedSite);
+ });
+ it("should _makeTopSitesPreview correctly", () => {
+ const site1 = { url: "https://foo.com" };
+ const site2 = { url: "https://bar.com" };
+ const site3 = { url: "https://baz.com" };
+ const rows = [site1, site2, site3];
+ let wrapper = shallow(
+ <TopSiteList {...DEFAULT_PROPS} TopSites={{ rows }} TopSitesRows={1} />
+ );
+ let instance = wrapper.instance();
+ instance.setState({
+ draggedIndex: 0,
+ draggedSite: site1,
+ draggedTitle: "foo",
+ });
+ let draggedSite = Object.assign({}, site1, {
+ isPinned: true,
+ isDragged: true,
+ });
+ assert.deepEqual(instance._makeTopSitesPreview(1), [
+ site2,
+ draggedSite,
+ site3,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ]);
+ assert.deepEqual(instance._makeTopSitesPreview(2), [
+ site2,
+ site3,
+ draggedSite,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ]);
+ assert.deepEqual(instance._makeTopSitesPreview(3), [
+ site2,
+ site3,
+ null,
+ draggedSite,
+ null,
+ null,
+ null,
+ null,
+ ]);
+ site2.isPinned = true;
+ assert.deepEqual(instance._makeTopSitesPreview(1), [
+ site2,
+ draggedSite,
+ site3,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ]);
+ assert.deepEqual(instance._makeTopSitesPreview(2), [
+ site3,
+ site2,
+ draggedSite,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ]);
+ site3.isPinned = true;
+ assert.deepEqual(instance._makeTopSitesPreview(1), [
+ site2,
+ draggedSite,
+ site3,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ]);
+ assert.deepEqual(instance._makeTopSitesPreview(2), [
+ site2,
+ site3,
+ draggedSite,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ]);
+ site2.isPinned = false;
+ assert.deepEqual(instance._makeTopSitesPreview(1), [
+ site2,
+ draggedSite,
+ site3,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ]);
+ assert.deepEqual(instance._makeTopSitesPreview(2), [
+ site2,
+ site3,
+ draggedSite,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ]);
+ site3.isPinned = false;
+ instance.setState({
+ draggedIndex: 1,
+ draggedSite: site2,
+ draggedTitle: "bar",
+ });
+ draggedSite = Object.assign({}, site2, { isPinned: true, isDragged: true });
+ assert.deepEqual(instance._makeTopSitesPreview(0), [
+ draggedSite,
+ site1,
+ site3,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ]);
+ assert.deepEqual(instance._makeTopSitesPreview(2), [
+ site1,
+ site3,
+ draggedSite,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ]);
+ });
+ it("should add a className hide-for-narrow to sites after 6/row", () => {
+ const rows = [];
+ for (let i = 0; i < TOP_SITES_MAX_SITES_PER_ROW; i++) {
+ rows.push({ url: `https://foo${i}.com` });
+ }
+ const wrapper = mount(
+ <TopSiteList {...DEFAULT_PROPS} TopSites={{ rows }} TopSitesRows={1} />
+ );
+ assert.lengthOf(wrapper.find("li.hide-for-narrow"), 2);
+ });
+});
+
+describe("TopSitePlaceholder", () => {
+ it("should dispatch a TOP_SITES_EDIT action when edit-button is clicked", () => {
+ const dispatch = sinon.spy();
+ const wrapper = shallow(
+ <TopSitePlaceholder dispatch={dispatch} index={7} />
+ );
+
+ wrapper
+ .find(".edit-button")
+ .first()
+ .simulate("click");
+
+ assert.calledOnce(dispatch);
+ assert.calledWithExactly(dispatch, {
+ type: at.TOP_SITES_EDIT,
+ data: { index: 7 },
+ });
+ });
+});
+
+describe("#TopSiteFormInput", () => {
+ let wrapper;
+ let onChangeStub;
+
+ describe("no errors", () => {
+ beforeEach(() => {
+ onChangeStub = sinon.stub();
+
+ wrapper = mount(
+ <TopSiteFormInput
+ titleId="newtab-topsites-title-label"
+ placeholderId="newtab-topsites-title-input"
+ errorMessageId="newtab-topsites-url-validation"
+ onChange={onChangeStub}
+ value="foo"
+ />
+ );
+ });
+
+ it("should render the provided title", () => {
+ const title = wrapper.find("span");
+ assert.propertyVal(
+ title.props(),
+ "data-l10n-id",
+ "newtab-topsites-title-label"
+ );
+ });
+
+ it("should render the provided value", () => {
+ const input = wrapper.find("input");
+
+ assert.equal(input.getDOMNode().value, "foo");
+ });
+
+ it("should render the clear button if cb is provided", () => {
+ assert.equal(wrapper.find(".icon-clear-input").length, 0);
+
+ wrapper.setProps({ onClear: sinon.stub() });
+
+ assert.equal(wrapper.find(".icon-clear-input").length, 1);
+ });
+
+ it("should show the loading indicator", () => {
+ assert.equal(wrapper.find(".loading-container").length, 0);
+
+ wrapper.setProps({ loading: true });
+
+ assert.equal(wrapper.find(".loading-container").length, 1);
+ });
+ it("should disable the input when loading indicator is present", () => {
+ assert.isFalse(wrapper.find("input").getDOMNode().disabled);
+
+ wrapper.setProps({ loading: true });
+
+ assert.isTrue(wrapper.find("input").getDOMNode().disabled);
+ });
+ });
+
+ describe("with error", () => {
+ beforeEach(() => {
+ onChangeStub = sinon.stub();
+
+ wrapper = mount(
+ <TopSiteFormInput
+ titleId="newtab-topsites-title-label"
+ placeholderId="newtab-topsites-title-input"
+ onChange={onChangeStub}
+ validationError={true}
+ errorMessageId="newtab-topsites-url-validation"
+ value="foo"
+ />
+ );
+ });
+
+ it("should render the error message", () => {
+ assert.equal(
+ wrapper.findWhere(
+ n => n.prop("data-l10n-id") === "newtab-topsites-url-validation"
+ ).length,
+ 1
+ );
+ });
+
+ it("should reset the error state on value change", () => {
+ wrapper.find("input").simulate("change", { target: { value: "bar" } });
+
+ assert.isFalse(wrapper.state().validationError);
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/components/TopSites/SearchShortcutsForm.test.jsx b/browser/components/newtab/test/unit/content-src/components/TopSites/SearchShortcutsForm.test.jsx
new file mode 100644
index 0000000000..2db35a71d8
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/TopSites/SearchShortcutsForm.test.jsx
@@ -0,0 +1,60 @@
+import {
+ SearchShortcutsForm,
+ SelectableSearchShortcut,
+} from "content-src/components/TopSites/SearchShortcutsForm";
+import React from "react";
+import { shallow } from "enzyme";
+
+describe("<SearchShortcutsForm>", () => {
+ let wrapper;
+ let sandbox;
+ let dispatchStub;
+
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ dispatchStub = sandbox.stub();
+ const defaultProps = { rows: [], searchShortcuts: [] };
+ wrapper = shallow(
+ <SearchShortcutsForm TopSites={defaultProps} dispatch={dispatchStub} />
+ );
+ });
+
+ afterEach(() => {
+ sandbox.restore();
+ });
+
+ it("should render", () => {
+ assert.ok(wrapper.exists());
+ assert.ok(wrapper.find(".topsite-form").exists());
+ });
+
+ it("should render SelectableSearchShortcut components", () => {
+ wrapper.setState({ shortcuts: [{}, {}] });
+
+ assert.lengthOf(
+ wrapper.find(".search-shortcuts-container div").children(),
+ 2
+ );
+ assert.equal(
+ wrapper
+ .find(".search-shortcuts-container div")
+ .children()
+ .at(0)
+ .type(),
+ SelectableSearchShortcut
+ );
+ });
+
+ it("should render SelectableSearchShortcut components", () => {
+ const onCloseStub = sandbox.stub();
+ const fakeEvent = { preventDefault: sandbox.stub() };
+ wrapper.setState({ shortcuts: [{}, {}] });
+ wrapper.setProps({ onClose: onCloseStub });
+
+ wrapper.find(".done").simulate("click", fakeEvent);
+
+ assert.calledOnce(dispatchStub);
+ assert.calledOnce(fakeEvent.preventDefault);
+ assert.calledOnce(onCloseStub);
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/components/Topics.test.jsx b/browser/components/newtab/test/unit/content-src/components/Topics.test.jsx
new file mode 100644
index 0000000000..91d15c5d4e
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/Topics.test.jsx
@@ -0,0 +1,22 @@
+import { Topic, Topics } from "content-src/components/Topics/Topics";
+import React from "react";
+import { shallow } from "enzyme";
+
+describe("<Topics>", () => {
+ it("should render a Topics element", () => {
+ const wrapper = shallow(<Topics topics={[]} />);
+ assert.ok(wrapper.exists());
+ });
+ it("should render a Topic element for each topic with the right url", () => {
+ const data = [
+ { name: "topic1", url: "https://topic1.com" },
+ { name: "topic2", url: "https://topic2.com" },
+ ];
+
+ const wrapper = shallow(<Topics topics={data} />);
+
+ const topics = wrapper.find(Topic);
+ assert.lengthOf(topics, 2);
+ topics.forEach((topic, i) => assert.equal(topic.props().url, data[i].url));
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/components/addUtmParams.test.js b/browser/components/newtab/test/unit/content-src/components/addUtmParams.test.js
new file mode 100644
index 0000000000..b3526bc192
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/components/addUtmParams.test.js
@@ -0,0 +1,28 @@
+import {
+ addUtmParams,
+ BASE_PARAMS,
+} from "content-src/asrouter/templates/FirstRun/addUtmParams";
+
+describe("addUtmParams", () => {
+ it("should convert a string URL", () => {
+ const result = addUtmParams("https://foo.com", "foo");
+ assert.equal(result.hostname, "foo.com");
+ });
+ it("should add all base params", () => {
+ assert.match(
+ addUtmParams(new URL("https://foo.com"), "foo").toString(),
+ /utm_source=activity-stream&utm_campaign=firstrun&utm_medium=referral/
+ );
+ });
+ it("should allow updating base params utm values", () => {
+ BASE_PARAMS.utm_campaign = "firstrun-default";
+ assert.match(
+ addUtmParams(new URL("https://foo.com"), "foo", "default").toString(),
+ /utm_source=activity-stream&utm_campaign=firstrun-default&utm_medium=referral/
+ );
+ });
+ it("should add utm_term", () => {
+ const params = addUtmParams(new URL("https://foo.com"), "foo").searchParams;
+ assert.equal(params.get("utm_term"), "foo", "utm_term");
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/lib/detect-user-session-start.test.js b/browser/components/newtab/test/unit/content-src/lib/detect-user-session-start.test.js
new file mode 100644
index 0000000000..7677c5990d
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/lib/detect-user-session-start.test.js
@@ -0,0 +1,117 @@
+import { actionCreators as ac, actionTypes as at } from "common/Actions.jsm";
+import { DetectUserSessionStart } from "content-src/lib/detect-user-session-start";
+
+describe("detectUserSessionStart", () => {
+ let store;
+ class PerfService {
+ getMostRecentAbsMarkStartByName() {
+ return 1234;
+ }
+ mark() {}
+ }
+
+ beforeEach(() => {
+ store = { dispatch: () => {} };
+ });
+ describe("#sendEventOrAddListener", () => {
+ it("should call ._sendEvent immediately if the document is visible", () => {
+ const mockDocument = { visibilityState: "visible" };
+ const instance = new DetectUserSessionStart(store, {
+ document: mockDocument,
+ });
+ sinon.stub(instance, "_sendEvent");
+
+ instance.sendEventOrAddListener();
+
+ assert.calledOnce(instance._sendEvent);
+ });
+ it("should add an event listener on visibility changes the document is not visible", () => {
+ const mockDocument = {
+ visibilityState: "hidden",
+ addEventListener: sinon.spy(),
+ };
+ const instance = new DetectUserSessionStart(store, {
+ document: mockDocument,
+ });
+ sinon.stub(instance, "_sendEvent");
+
+ instance.sendEventOrAddListener();
+
+ assert.notCalled(instance._sendEvent);
+ assert.calledWith(
+ mockDocument.addEventListener,
+ "visibilitychange",
+ instance._onVisibilityChange
+ );
+ });
+ });
+ describe("#_sendEvent", () => {
+ it("should dispatch an action with the SAVE_SESSION_PERF_DATA", () => {
+ const dispatch = sinon.spy(store, "dispatch");
+ const instance = new DetectUserSessionStart(store);
+
+ instance._sendEvent();
+
+ assert.calledWith(
+ dispatch,
+ ac.AlsoToMain({
+ type: at.SAVE_SESSION_PERF_DATA,
+ data: { visibility_event_rcvd_ts: sinon.match.number },
+ })
+ );
+ });
+
+ it("shouldn't send a message if getMostRecentAbsMarkStartByName throws", () => {
+ let perfService = new PerfService();
+ sinon.stub(perfService, "getMostRecentAbsMarkStartByName").throws();
+ const dispatch = sinon.spy(store, "dispatch");
+ const instance = new DetectUserSessionStart(store, { perfService });
+
+ instance._sendEvent();
+
+ assert.notCalled(dispatch);
+ });
+
+ it('should call perfService.mark("visibility_event_rcvd_ts")', () => {
+ let perfService = new PerfService();
+ sinon.stub(perfService, "mark");
+ const instance = new DetectUserSessionStart(store, { perfService });
+
+ instance._sendEvent();
+
+ assert.calledWith(perfService.mark, "visibility_event_rcvd_ts");
+ });
+ });
+
+ describe("_onVisibilityChange", () => {
+ it("should not send an event if visiblity is not visible", () => {
+ const instance = new DetectUserSessionStart(store, {
+ document: { visibilityState: "hidden" },
+ });
+ sinon.stub(instance, "_sendEvent");
+
+ instance._onVisibilityChange();
+
+ assert.notCalled(instance._sendEvent);
+ });
+ it("should send an event and remove the event listener if visibility is visible", () => {
+ const mockDocument = {
+ visibilityState: "visible",
+ removeEventListener: sinon.spy(),
+ };
+ const instance = new DetectUserSessionStart(store, {
+ document: mockDocument,
+ });
+ sinon.stub(instance, "_sendEvent");
+
+ instance._onVisibilityChange();
+
+ assert.calledOnce(instance._sendEvent);
+ assert.calledWith(
+ mockDocument.removeEventListener,
+ "visibilitychange",
+ instance._onVisibilityChange
+ );
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/lib/init-store.test.js b/browser/components/newtab/test/unit/content-src/lib/init-store.test.js
new file mode 100644
index 0000000000..685df40a3d
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/lib/init-store.test.js
@@ -0,0 +1,204 @@
+import { actionCreators as ac, actionTypes as at } from "common/Actions.jsm";
+import { addNumberReducer, GlobalOverrider } from "test/unit/utils";
+import {
+ EARLY_QUEUED_ACTIONS,
+ INCOMING_MESSAGE_NAME,
+ initStore,
+ MERGE_STORE_ACTION,
+ OUTGOING_MESSAGE_NAME,
+ queueEarlyMessageMiddleware,
+ rehydrationMiddleware,
+} from "content-src/lib/init-store";
+
+describe("initStore", () => {
+ let globals;
+ let store;
+ beforeEach(() => {
+ globals = new GlobalOverrider();
+ globals.set("RPMSendAsyncMessage", globals.sandbox.spy());
+ globals.set("RPMAddMessageListener", globals.sandbox.spy());
+ store = initStore({ number: addNumberReducer });
+ });
+ afterEach(() => globals.restore());
+ it("should create a store with the provided reducers", () => {
+ assert.ok(store);
+ assert.property(store.getState(), "number");
+ });
+ it("should add a listener that dispatches actions", () => {
+ assert.calledWith(global.RPMAddMessageListener, INCOMING_MESSAGE_NAME);
+ const [, listener] = global.RPMAddMessageListener.firstCall.args;
+ globals.sandbox.spy(store, "dispatch");
+ const message = { name: INCOMING_MESSAGE_NAME, data: { type: "FOO" } };
+
+ listener(message);
+
+ assert.calledWith(store.dispatch, message.data);
+ });
+ it("should not throw if RPMAddMessageListener is not defined", () => {
+ // Note: this is being set/restored by GlobalOverrider
+ delete global.RPMAddMessageListener;
+
+ assert.doesNotThrow(() => initStore({ number: addNumberReducer }));
+ });
+ it("should log errors from failed messages", () => {
+ const [, callback] = global.RPMAddMessageListener.firstCall.args;
+ globals.sandbox.stub(global.console, "error");
+ globals.sandbox.stub(store, "dispatch").throws(Error("failed"));
+
+ const message = {
+ name: INCOMING_MESSAGE_NAME,
+ data: { type: MERGE_STORE_ACTION },
+ };
+ callback(message);
+
+ assert.calledOnce(global.console.error);
+ });
+ it("should replace the state if a MERGE_STORE_ACTION is dispatched", () => {
+ store.dispatch({ type: MERGE_STORE_ACTION, data: { number: 42 } });
+ assert.deepEqual(store.getState(), { number: 42 });
+ });
+ it("should call .send and update the local store if an AlsoToMain action is dispatched", () => {
+ const subscriber = sinon.spy();
+ const action = ac.AlsoToMain({ type: "FOO" });
+
+ store.subscribe(subscriber);
+ store.dispatch(action);
+
+ assert.calledWith(
+ global.RPMSendAsyncMessage,
+ OUTGOING_MESSAGE_NAME,
+ action
+ );
+ assert.calledOnce(subscriber);
+ });
+ it("should call .send but not update the local store if an OnlyToMain action is dispatched", () => {
+ const subscriber = sinon.spy();
+ const action = ac.OnlyToMain({ type: "FOO" });
+
+ store.subscribe(subscriber);
+ store.dispatch(action);
+
+ assert.calledWith(
+ global.RPMSendAsyncMessage,
+ OUTGOING_MESSAGE_NAME,
+ action
+ );
+ assert.notCalled(subscriber);
+ });
+ it("should not send out other types of actions", () => {
+ store.dispatch({ type: "FOO" });
+ assert.notCalled(global.RPMSendAsyncMessage);
+ });
+ describe("rehydrationMiddleware", () => {
+ it("should allow NEW_TAB_STATE_REQUEST to go through", () => {
+ const action = ac.AlsoToMain({ type: at.NEW_TAB_STATE_REQUEST });
+ const next = sinon.spy();
+ rehydrationMiddleware(store)(next)(action);
+ assert.calledWith(next, action);
+ });
+ it("should dispatch an additional NEW_TAB_STATE_REQUEST if INIT was received after a request", () => {
+ const requestAction = ac.AlsoToMain({ type: at.NEW_TAB_STATE_REQUEST });
+ const next = sinon.spy();
+ const dispatch = rehydrationMiddleware(store)(next);
+
+ dispatch(requestAction);
+ next.resetHistory();
+ dispatch({ type: at.INIT });
+
+ assert.calledWith(next, requestAction);
+ });
+ it("should allow MERGE_STORE_ACTION to go through", () => {
+ const action = { type: MERGE_STORE_ACTION };
+ const next = sinon.spy();
+ rehydrationMiddleware(store)(next)(action);
+ assert.calledWith(next, action);
+ });
+ it("should not allow actions from main to go through before MERGE_STORE_ACTION was received", () => {
+ const next = sinon.spy();
+ const dispatch = rehydrationMiddleware(store)(next);
+
+ dispatch(ac.BroadcastToContent({ type: "FOO" }));
+ dispatch(ac.AlsoToOneContent({ type: "FOO" }, 123));
+
+ assert.notCalled(next);
+ });
+ it("should allow all local actions to go through", () => {
+ const action = { type: "FOO" };
+ const next = sinon.spy();
+ rehydrationMiddleware(store)(next)(action);
+ assert.calledWith(next, action);
+ });
+ it("should allow actions from main to go through after MERGE_STORE_ACTION has been received", () => {
+ const next = sinon.spy();
+ const dispatch = rehydrationMiddleware(store)(next);
+
+ dispatch({ type: MERGE_STORE_ACTION });
+ next.resetHistory();
+
+ const action = ac.AlsoToOneContent({ type: "FOO" }, 123);
+ dispatch(action);
+ assert.calledWith(next, action);
+ });
+ it("should not let startup actions go through for the preloaded about:home document", () => {
+ globals.set("__FROM_STARTUP_CACHE__", true);
+ const next = sinon.spy();
+ const dispatch = rehydrationMiddleware(store)(next);
+ const action = ac.BroadcastToContent(
+ { type: "FOO", meta: { isStartup: true } },
+ 123
+ );
+ dispatch(action);
+ assert.notCalled(next);
+ });
+ });
+ describe("queueEarlyMessageMiddleware", () => {
+ it("should allow all local actions to go through", () => {
+ const action = { type: "FOO" };
+ const next = sinon.spy();
+
+ queueEarlyMessageMiddleware(store)(next)(action);
+
+ assert.calledWith(next, action);
+ });
+ it("should allow action to main that does not belong to EARLY_QUEUED_ACTIONS to go through", () => {
+ const action = ac.AlsoToMain({ type: "FOO" });
+ const next = sinon.spy();
+
+ queueEarlyMessageMiddleware(store)(next)(action);
+
+ assert.calledWith(next, action);
+ });
+ it(`should line up EARLY_QUEUED_ACTIONS only let them go through after it receives the action from main`, () => {
+ EARLY_QUEUED_ACTIONS.forEach(actionType => {
+ const testStore = initStore({ number: addNumberReducer });
+ const next = sinon.spy();
+ const dispatch = queueEarlyMessageMiddleware(testStore)(next);
+ const action = ac.AlsoToMain({ type: actionType });
+ const fromMainAction = ac.AlsoToOneContent({ type: "FOO" }, 123);
+
+ // Early actions should be added to the queue
+ dispatch(action);
+ dispatch(action);
+
+ assert.notCalled(next);
+ assert.equal(testStore.getState.earlyActionQueue.length, 2);
+ next.resetHistory();
+
+ // Receiving action from main would empty the queue
+ dispatch(fromMainAction);
+
+ assert.calledThrice(next);
+ assert.equal(next.firstCall.args[0], fromMainAction);
+ assert.equal(next.secondCall.args[0], action);
+ assert.equal(next.thirdCall.args[0], action);
+ assert.equal(testStore.getState.earlyActionQueue.length, 0);
+ next.resetHistory();
+
+ // New action should go through immediately
+ dispatch(action);
+ assert.calledOnce(next);
+ assert.calledWith(next, action);
+ });
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/lib/perf-service.test.js b/browser/components/newtab/test/unit/content-src/lib/perf-service.test.js
new file mode 100644
index 0000000000..9cabfb5029
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/lib/perf-service.test.js
@@ -0,0 +1,89 @@
+/* globals assert, beforeEach, describe, it */
+import { _PerfService } from "content-src/lib/perf-service";
+import { FakePerformance } from "test/unit/utils.js";
+
+let perfService;
+
+describe("_PerfService", () => {
+ let sandbox;
+ let fakePerfObj;
+
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ fakePerfObj = new FakePerformance();
+ perfService = new _PerfService({ performanceObj: fakePerfObj });
+ });
+
+ afterEach(() => {
+ sandbox.restore();
+ });
+
+ describe("#absNow", () => {
+ it("should return a number > the time origin", () => {
+ const absNow = perfService.absNow();
+
+ assert.isAbove(absNow, perfService.timeOrigin);
+ });
+ });
+ describe("#getEntriesByName", () => {
+ it("should call getEntriesByName on the appropriate Window.performance", () => {
+ sandbox.spy(fakePerfObj, "getEntriesByName");
+
+ perfService.getEntriesByName("monkey", "mark");
+
+ assert.calledOnce(fakePerfObj.getEntriesByName);
+ assert.calledWithExactly(fakePerfObj.getEntriesByName, "monkey", "mark");
+ });
+
+ it("should return entries with the given name", () => {
+ sandbox.spy(fakePerfObj, "getEntriesByName");
+ perfService.mark("monkey");
+ perfService.mark("dog");
+
+ let marks = perfService.getEntriesByName("monkey", "mark");
+
+ assert.isArray(marks);
+ assert.lengthOf(marks, 1);
+ assert.propertyVal(marks[0], "name", "monkey");
+ });
+ });
+
+ describe("#getMostRecentAbsMarkStartByName", () => {
+ it("should throw an error if there is no mark with the given name", () => {
+ function bogusGet() {
+ perfService.getMostRecentAbsMarkStartByName("rheeeet");
+ }
+
+ assert.throws(bogusGet, Error, /No marks with the name/);
+ });
+
+ it("should return the Number from the most recent mark with the given name + the time origin", () => {
+ perfService.mark("dog");
+ perfService.mark("dog");
+
+ let absMarkStart = perfService.getMostRecentAbsMarkStartByName("dog");
+
+ // 2 because we want the result of the 2nd call to mark, and an instance
+ // of FakePerformance just returns the number of time mark has been
+ // called.
+ assert.equal(absMarkStart - perfService.timeOrigin, 2);
+ });
+ });
+
+ describe("#mark", () => {
+ it("should call the wrapped version of mark", () => {
+ sandbox.spy(fakePerfObj, "mark");
+
+ perfService.mark("monkey");
+
+ assert.calledOnce(fakePerfObj.mark);
+ assert.calledWithExactly(fakePerfObj.mark, "monkey");
+ });
+ });
+
+ describe("#timeOrigin", () => {
+ it("should get the origin of the wrapped performance object", () => {
+ assert.equal(perfService.timeOrigin, fakePerfObj.timeOrigin);
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/lib/screenshot-utils.test.js b/browser/components/newtab/test/unit/content-src/lib/screenshot-utils.test.js
new file mode 100644
index 0000000000..ef7e7cf5f6
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/lib/screenshot-utils.test.js
@@ -0,0 +1,147 @@
+import { GlobalOverrider } from "test/unit/utils";
+import { ScreenshotUtils } from "content-src/lib/screenshot-utils";
+
+const DEFAULT_BLOB_URL = "blob://test";
+
+describe("ScreenshotUtils", () => {
+ let globals;
+ let url;
+ beforeEach(() => {
+ globals = new GlobalOverrider();
+ url = {
+ createObjectURL: globals.sandbox.stub().returns(DEFAULT_BLOB_URL),
+ revokeObjectURL: globals.sandbox.spy(),
+ };
+ globals.set("URL", url);
+ });
+ afterEach(() => globals.restore());
+ describe("#createLocalImageObject", () => {
+ it("should return null if no remoteImage is supplied", () => {
+ let localImageObject = ScreenshotUtils.createLocalImageObject(null);
+
+ assert.notCalled(url.createObjectURL);
+ assert.equal(localImageObject, null);
+ });
+ it("should create a local image object with the correct properties if remoteImage is a blob", () => {
+ let localImageObject = ScreenshotUtils.createLocalImageObject({
+ path: "/path1",
+ data: new Blob([0]),
+ });
+
+ assert.calledOnce(url.createObjectURL);
+ assert.deepEqual(localImageObject, {
+ path: "/path1",
+ url: DEFAULT_BLOB_URL,
+ });
+ });
+ it("should create a local image object with the correct properties if remoteImage is a normal image", () => {
+ const imageUrl = "https://test-url";
+ let localImageObject = ScreenshotUtils.createLocalImageObject(imageUrl);
+
+ assert.notCalled(url.createObjectURL);
+ assert.deepEqual(localImageObject, { url: imageUrl });
+ });
+ });
+ describe("#maybeRevokeBlobObjectURL", () => {
+ // Note that we should also ensure that all the tests for #isBlob are green.
+ it("should call revokeObjectURL if image is a blob", () => {
+ ScreenshotUtils.maybeRevokeBlobObjectURL({
+ path: "/path1",
+ url: "blob://test",
+ });
+
+ assert.calledOnce(url.revokeObjectURL);
+ });
+ it("should not call revokeObjectURL if image is not a blob", () => {
+ ScreenshotUtils.maybeRevokeBlobObjectURL({ url: "https://test-url" });
+
+ assert.notCalled(url.revokeObjectURL);
+ });
+ });
+ describe("#isRemoteImageLocal", () => {
+ it("should return true if both propsImage and stateImage are not present", () => {
+ assert.isTrue(ScreenshotUtils.isRemoteImageLocal(null, null));
+ });
+ it("should return false if propsImage is present and stateImage is not present", () => {
+ assert.isFalse(ScreenshotUtils.isRemoteImageLocal(null, {}));
+ });
+ it("should return false if propsImage is not present and stateImage is present", () => {
+ assert.isFalse(ScreenshotUtils.isRemoteImageLocal({}, null));
+ });
+ it("should return true if both propsImage and stateImage are equal blobs", () => {
+ const blobPath = "/test-blob-path/test.png";
+ assert.isTrue(
+ ScreenshotUtils.isRemoteImageLocal(
+ { path: blobPath, url: "blob://test" }, // state
+ { path: blobPath, data: new Blob([0]) } // props
+ )
+ );
+ });
+ it("should return false if both propsImage and stateImage are different blobs", () => {
+ assert.isFalse(
+ ScreenshotUtils.isRemoteImageLocal(
+ { path: "/path1", url: "blob://test" }, // state
+ { path: "/path2", data: new Blob([0]) } // props
+ )
+ );
+ });
+ it("should return true if both propsImage and stateImage are equal normal images", () => {
+ assert.isTrue(
+ ScreenshotUtils.isRemoteImageLocal(
+ { url: "test url" }, // state
+ "test url" // props
+ )
+ );
+ });
+ it("should return false if both propsImage and stateImage are different normal images", () => {
+ assert.isFalse(
+ ScreenshotUtils.isRemoteImageLocal(
+ { url: "test url 1" }, // state
+ "test url 2" // props
+ )
+ );
+ });
+ it("should return false if both propsImage and stateImage are different type of images", () => {
+ assert.isFalse(
+ ScreenshotUtils.isRemoteImageLocal(
+ { path: "/path1", url: "blob://test" }, // state
+ "test url 2" // props
+ )
+ );
+ assert.isFalse(
+ ScreenshotUtils.isRemoteImageLocal(
+ { url: "https://test-url" }, // state
+ { path: "/path1", data: new Blob([0]) } // props
+ )
+ );
+ });
+ });
+ describe("#isBlob", () => {
+ let state = {
+ blobImage: { path: "/test", url: "blob://test" },
+ normalImage: { url: "https://test-url" },
+ };
+ let props = {
+ blobImage: { path: "/test", data: new Blob([0]) },
+ normalImage: "https://test-url",
+ };
+ it("should return false if image is null", () => {
+ assert.isFalse(ScreenshotUtils.isBlob(true, null));
+ assert.isFalse(ScreenshotUtils.isBlob(false, null));
+ });
+ it("should return true if image is a blob and type matches", () => {
+ assert.isTrue(ScreenshotUtils.isBlob(true, state.blobImage));
+ assert.isTrue(ScreenshotUtils.isBlob(false, props.blobImage));
+ });
+ it("should return false if image is not a blob and type matches", () => {
+ assert.isFalse(ScreenshotUtils.isBlob(true, state.normalImage));
+ assert.isFalse(ScreenshotUtils.isBlob(false, props.normalImage));
+ });
+ it("should return false if type does not match", () => {
+ assert.isFalse(ScreenshotUtils.isBlob(false, state.blobImage));
+ assert.isFalse(ScreenshotUtils.isBlob(false, state.normalImage));
+ assert.isFalse(ScreenshotUtils.isBlob(true, props.blobImage));
+ assert.isFalse(ScreenshotUtils.isBlob(true, props.normalImage));
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/content-src/lib/selectLayoutRender.test.js b/browser/components/newtab/test/unit/content-src/lib/selectLayoutRender.test.js
new file mode 100644
index 0000000000..ae12782eee
--- /dev/null
+++ b/browser/components/newtab/test/unit/content-src/lib/selectLayoutRender.test.js
@@ -0,0 +1,605 @@
+import { combineReducers, createStore } from "redux";
+import { actionTypes as at } from "common/Actions.jsm";
+import { GlobalOverrider } from "test/unit/utils";
+import { reducers } from "common/Reducers.jsm";
+import { selectLayoutRender } from "content-src/lib/selectLayoutRender";
+const FAKE_LAYOUT = [
+ {
+ width: 3,
+ components: [
+ { type: "foo", feed: { url: "foo.com" }, properties: { items: 2 } },
+ ],
+ },
+];
+const FAKE_FEEDS = {
+ "foo.com": { data: { recommendations: [{ id: "foo" }, { id: "bar" }] } },
+};
+
+describe("selectLayoutRender", () => {
+ let store;
+ let globals;
+
+ beforeEach(() => {
+ globals = new GlobalOverrider();
+ store = createStore(combineReducers(reducers));
+ });
+
+ afterEach(() => {
+ globals.restore();
+ });
+
+ it("should return an empty array given initial state", () => {
+ const { layoutRender } = selectLayoutRender({
+ state: store.getState().DiscoveryStream,
+ prefs: {},
+ rollCache: [],
+ });
+ assert.deepEqual(layoutRender, []);
+ });
+
+ it("should add .data property from feeds to each compontent in .layout", () => {
+ store.dispatch({
+ type: at.DISCOVERY_STREAM_LAYOUT_UPDATE,
+ data: { layout: FAKE_LAYOUT },
+ });
+ store.dispatch({
+ type: at.DISCOVERY_STREAM_FEED_UPDATE,
+ data: { feed: FAKE_FEEDS["foo.com"], url: "foo.com" },
+ });
+ store.dispatch({ type: at.DISCOVERY_STREAM_FEEDS_UPDATE });
+
+ const { layoutRender } = selectLayoutRender({
+ state: store.getState().DiscoveryStream,
+ });
+
+ assert.lengthOf(layoutRender, 1);
+ assert.propertyVal(layoutRender[0], "width", 3);
+ assert.deepEqual(layoutRender[0].components[0], {
+ type: "foo",
+ feed: { url: "foo.com" },
+ properties: { items: 2 },
+ data: {
+ recommendations: [
+ { id: "foo", pos: 0 },
+ { id: "bar", pos: 1 },
+ ],
+ },
+ });
+ });
+
+ it("should return layout with placeholder data if feed doesn't have data", () => {
+ store.dispatch({
+ type: at.DISCOVERY_STREAM_LAYOUT_UPDATE,
+ data: { layout: FAKE_LAYOUT },
+ });
+ store.dispatch({ type: at.DISCOVERY_STREAM_FEEDS_UPDATE });
+
+ const { layoutRender } = selectLayoutRender({
+ state: store.getState().DiscoveryStream,
+ });
+
+ assert.lengthOf(layoutRender, 1);
+ assert.propertyVal(layoutRender[0], "width", 3);
+ assert.deepEqual(layoutRender[0].components[0].data.recommendations, [
+ { placeholder: true },
+ { placeholder: true },
+ ]);
+ });
+
+ it("should return layout with empty spocs data if feed isn't defined but spocs is", () => {
+ const fakeLayout = [
+ {
+ width: 3,
+ components: [{ type: "foo", spocs: { positions: [{ index: 2 }] } }],
+ },
+ ];
+ store.dispatch({
+ type: at.DISCOVERY_STREAM_LAYOUT_UPDATE,
+ data: { layout: fakeLayout },
+ });
+ store.dispatch({ type: at.DISCOVERY_STREAM_FEEDS_UPDATE });
+
+ const { layoutRender } = selectLayoutRender({
+ state: store.getState().DiscoveryStream,
+ });
+
+ assert.lengthOf(layoutRender, 1);
+ assert.propertyVal(layoutRender[0], "width", 3);
+ assert.deepEqual(layoutRender[0].components[0].data.spocs, []);
+ });
+
+ it("should return layout with spocs data if feed isn't defined but spocs is", () => {
+ const fakeLayout = [
+ {
+ width: 3,
+ components: [{ type: "foo", spocs: { positions: [{ index: 0 }] } }],
+ },
+ ];
+ store.dispatch({
+ type: at.DISCOVERY_STREAM_LAYOUT_UPDATE,
+ data: { layout: fakeLayout },
+ });
+ store.dispatch({ type: at.DISCOVERY_STREAM_FEEDS_UPDATE });
+ store.dispatch({
+ type: at.DISCOVERY_STREAM_SPOCS_UPDATE,
+ data: {
+ lastUpdated: 0,
+ spocs: {
+ spocs: {
+ items: [{ id: 1 }, { id: 2 }, { id: 3 }],
+ },
+ },
+ },
+ });
+
+ const { layoutRender } = selectLayoutRender({
+ state: store.getState().DiscoveryStream,
+ });
+
+ assert.lengthOf(layoutRender, 1);
+ assert.propertyVal(layoutRender[0], "width", 3);
+ assert.deepEqual(layoutRender[0].components[0].data.spocs, [
+ { id: 1, pos: 0 },
+ { id: 2, pos: 1 },
+ { id: 3, pos: 2 },
+ ]);
+ });
+
+ it("should return layout with no spocs data if feed and spocs are unavailable", () => {
+ const fakeLayout = [
+ {
+ width: 3,
+ components: [{ type: "foo", spocs: { positions: [{ index: 0 }] } }],
+ },
+ ];
+ store.dispatch({
+ type: at.DISCOVERY_STREAM_LAYOUT_UPDATE,
+ data: { layout: fakeLayout },
+ });
+ store.dispatch({ type: at.DISCOVERY_STREAM_FEEDS_UPDATE });
+ store.dispatch({
+ type: at.DISCOVERY_STREAM_SPOCS_UPDATE,
+ data: {
+ lastUpdated: 0,
+ spocs: {
+ spocs: {
+ items: [],
+ },
+ },
+ },
+ });
+
+ const { layoutRender } = selectLayoutRender({
+ state: store.getState().DiscoveryStream,
+ });
+
+ assert.lengthOf(layoutRender, 1);
+ assert.propertyVal(layoutRender[0], "width", 3);
+ assert.equal(layoutRender[0].components[0].data.spocs.length, 0);
+ });
+
+ it("should return feed data offset by layout set prop", () => {
+ const fakeLayout = [
+ {
+ width: 3,
+ components: [
+ { type: "foo", properties: { offset: 1 }, feed: { url: "foo.com" } },
+ ],
+ },
+ ];
+ store.dispatch({
+ type: at.DISCOVERY_STREAM_LAYOUT_UPDATE,
+ data: { layout: fakeLayout },
+ });
+ store.dispatch({
+ type: at.DISCOVERY_STREAM_FEED_UPDATE,
+ data: { feed: FAKE_FEEDS["foo.com"], url: "foo.com" },
+ });
+ store.dispatch({ type: at.DISCOVERY_STREAM_FEEDS_UPDATE });
+
+ const { layoutRender } = selectLayoutRender({
+ state: store.getState().DiscoveryStream,
+ });
+
+ assert.deepEqual(layoutRender[0].components[0].data, {
+ recommendations: [{ id: "bar" }],
+ });
+ });
+
+ it("should return spoc result when there are more positions than spocs", () => {
+ const fakeSpocConfig = {
+ positions: [{ index: 0 }, { index: 1 }, { index: 2 }],
+ };
+ const fakeLayout = [
+ {
+ width: 3,
+ components: [
+ { type: "foo", feed: { url: "foo.com" }, spocs: fakeSpocConfig },
+ ],
+ },
+ ];
+ const fakeSpocsData = {
+ lastUpdated: 0,
+ spocs: { spocs: { items: ["fooSpoc", "barSpoc"] } },
+ };
+
+ store.dispatch({
+ type: at.DISCOVERY_STREAM_LAYOUT_UPDATE,
+ data: { layout: fakeLayout },
+ });
+ store.dispatch({
+ type: at.DISCOVERY_STREAM_FEED_UPDATE,
+ data: { feed: FAKE_FEEDS["foo.com"], url: "foo.com" },
+ });
+ store.dispatch({ type: at.DISCOVERY_STREAM_FEEDS_UPDATE });
+ store.dispatch({
+ type: at.DISCOVERY_STREAM_SPOCS_UPDATE,
+ data: fakeSpocsData,
+ });
+
+ const { layoutRender } = selectLayoutRender({
+ state: store.getState().DiscoveryStream,
+ });
+
+ assert.lengthOf(layoutRender, 1);
+ assert.deepEqual(
+ layoutRender[0].components[0].data.recommendations[0],
+ "fooSpoc"
+ );
+ assert.deepEqual(
+ layoutRender[0].components[0].data.recommendations[1],
+ "barSpoc"
+ );
+ assert.deepEqual(layoutRender[0].components[0].data.recommendations[2], {
+ id: "foo",
+ });
+ assert.deepEqual(layoutRender[0].components[0].data.recommendations[3], {
+ id: "bar",
+ });
+ });
+
+ it("should return a layout with feeds of items length with positions", () => {
+ const fakeLayout = [
+ {
+ width: 3,
+ components: [
+ { type: "foo", properties: { items: 3 }, feed: { url: "foo.com" } },
+ ],
+ },
+ ];
+ const fakeRecommendations = [
+ { name: "item1" },
+ { name: "item2" },
+ { name: "item3" },
+ { name: "item4" },
+ ];
+ const fakeFeeds = {
+ "foo.com": { data: { recommendations: fakeRecommendations } },
+ };
+ store.dispatch({
+ type: at.DISCOVERY_STREAM_LAYOUT_UPDATE,
+ data: { layout: fakeLayout },
+ });
+ store.dispatch({
+ type: at.DISCOVERY_STREAM_FEED_UPDATE,
+ data: { feed: fakeFeeds["foo.com"], url: "foo.com" },
+ });
+ store.dispatch({ type: at.DISCOVERY_STREAM_FEEDS_UPDATE });
+
+ const { layoutRender } = selectLayoutRender({
+ state: store.getState().DiscoveryStream,
+ });
+
+ const { recommendations } = layoutRender[0].components[0].data;
+ assert.equal(recommendations.length, 4);
+ assert.equal(recommendations[0].pos, 0);
+ assert.equal(recommendations[1].pos, 1);
+ assert.equal(recommendations[2].pos, 2);
+ assert.equal(recommendations[3].pos, undefined);
+ });
+ it("should stop rendering feeds if we hit one that's not ready", () => {
+ const fakeLayout = [
+ {
+ width: 3,
+ components: [
+ { type: "foo1" },
+ { type: "foo2", properties: { items: 3 }, feed: { url: "foo2.com" } },
+ { type: "foo3", properties: { items: 3 }, feed: { url: "foo3.com" } },
+ { type: "foo4", properties: { items: 3 }, feed: { url: "foo4.com" } },
+ { type: "foo5" },
+ ],
+ },
+ ];
+ store.dispatch({
+ type: at.DISCOVERY_STREAM_LAYOUT_UPDATE,
+ data: { layout: fakeLayout },
+ });
+ store.dispatch({
+ type: at.DISCOVERY_STREAM_FEED_UPDATE,
+ data: { feed: { data: { recommendations: [] } }, url: "foo2.com" },
+ });
+
+ const { layoutRender } = selectLayoutRender({
+ state: store.getState().DiscoveryStream,
+ });
+
+ assert.equal(layoutRender[0].components[0].type, "foo1");
+ assert.equal(layoutRender[0].components[1].type, "foo2");
+ assert.isTrue(
+ layoutRender[0].components[2].data.recommendations[0].placeholder
+ );
+ assert.lengthOf(layoutRender[0].components, 3);
+ assert.isUndefined(layoutRender[0].components[3]);
+ });
+ it("should render everything if everything is ready", () => {
+ const fakeLayout = [
+ {
+ width: 3,
+ components: [
+ { type: "foo1" },
+ { type: "foo2", properties: { items: 3 }, feed: { url: "foo2.com" } },
+ { type: "foo3", properties: { items: 3 }, feed: { url: "foo3.com" } },
+ { type: "foo4", properties: { items: 3 }, feed: { url: "foo4.com" } },
+ { type: "foo5" },
+ ],
+ },
+ ];
+ store.dispatch({
+ type: at.DISCOVERY_STREAM_LAYOUT_UPDATE,
+ data: { layout: fakeLayout },
+ });
+ store.dispatch({
+ type: at.DISCOVERY_STREAM_FEED_UPDATE,
+ data: { feed: { data: { recommendations: [] } }, url: "foo2.com" },
+ });
+ store.dispatch({
+ type: at.DISCOVERY_STREAM_FEED_UPDATE,
+ data: { feed: { data: { recommendations: [] } }, url: "foo3.com" },
+ });
+ store.dispatch({
+ type: at.DISCOVERY_STREAM_FEED_UPDATE,
+ data: { feed: { data: { recommendations: [] } }, url: "foo4.com" },
+ });
+
+ const { layoutRender } = selectLayoutRender({
+ state: store.getState().DiscoveryStream,
+ });
+
+ assert.equal(layoutRender[0].components[0].type, "foo1");
+ assert.equal(layoutRender[0].components[1].type, "foo2");
+ assert.equal(layoutRender[0].components[2].type, "foo3");
+ assert.equal(layoutRender[0].components[3].type, "foo4");
+ assert.equal(layoutRender[0].components[4].type, "foo5");
+ });
+ it("should stop rendering feeds if we hit a not ready spoc", () => {
+ const fakeLayout = [
+ {
+ width: 3,
+ components: [
+ { type: "foo1" },
+ { type: "foo2", properties: { items: 3 }, feed: { url: "foo2.com" } },
+ {
+ type: "foo3",
+ properties: { items: 3 },
+ feed: { url: "foo3.com" },
+ spocs: { positions: [{ index: 0 }] },
+ },
+ { type: "foo4", properties: { items: 3 }, feed: { url: "foo4.com" } },
+ { type: "foo5" },
+ ],
+ },
+ ];
+ store.dispatch({
+ type: at.DISCOVERY_STREAM_LAYOUT_UPDATE,
+ data: { layout: fakeLayout },
+ });
+ store.dispatch({
+ type: at.DISCOVERY_STREAM_FEED_UPDATE,
+ data: { feed: { data: { recommendations: [] } }, url: "foo2.com" },
+ });
+ store.dispatch({
+ type: at.DISCOVERY_STREAM_FEED_UPDATE,
+ data: { feed: { data: { recommendations: [] } }, url: "foo3.com" },
+ });
+ store.dispatch({
+ type: at.DISCOVERY_STREAM_FEED_UPDATE,
+ data: { feed: { data: { recommendations: [] } }, url: "foo4.com" },
+ });
+
+ const { layoutRender } = selectLayoutRender({
+ state: store.getState().DiscoveryStream,
+ });
+
+ assert.equal(layoutRender[0].components[0].type, "foo1");
+ assert.equal(layoutRender[0].components[1].type, "foo2");
+ assert.deepEqual(layoutRender[0].components[2].data.recommendations, [
+ { placeholder: true },
+ { placeholder: true },
+ { placeholder: true },
+ ]);
+ });
+ it("should not render a spoc if there are no available spocs", () => {
+ const fakeLayout = [
+ {
+ width: 3,
+ components: [
+ { type: "foo1" },
+ { type: "foo2", properties: { items: 3 }, feed: { url: "foo2.com" } },
+ {
+ type: "foo3",
+ properties: { items: 3 },
+ feed: { url: "foo3.com" },
+ spocs: { positions: [{ index: 0 }] },
+ },
+ { type: "foo4", properties: { items: 3 }, feed: { url: "foo4.com" } },
+ { type: "foo5" },
+ ],
+ },
+ ];
+ const fakeSpocsData = { lastUpdated: 0, spocs: { spocs: [] } };
+ store.dispatch({
+ type: at.DISCOVERY_STREAM_LAYOUT_UPDATE,
+ data: { layout: fakeLayout },
+ });
+ store.dispatch({
+ type: at.DISCOVERY_STREAM_FEED_UPDATE,
+ data: { feed: { data: { recommendations: [] } }, url: "foo2.com" },
+ });
+ store.dispatch({
+ type: at.DISCOVERY_STREAM_FEED_UPDATE,
+ data: {
+ feed: { data: { recommendations: [{ name: "rec" }] } },
+ url: "foo3.com",
+ },
+ });
+ store.dispatch({
+ type: at.DISCOVERY_STREAM_FEED_UPDATE,
+ data: { feed: { data: { recommendations: [] } }, url: "foo4.com" },
+ });
+ store.dispatch({
+ type: at.DISCOVERY_STREAM_SPOCS_UPDATE,
+ data: fakeSpocsData,
+ });
+
+ const { layoutRender } = selectLayoutRender({
+ state: store.getState().DiscoveryStream,
+ });
+
+ assert.deepEqual(layoutRender[0].components[2].data.recommendations[0], {
+ name: "rec",
+ pos: 0,
+ });
+ });
+ it("should not render a row if no components exist after filter in that row", () => {
+ const fakeLayout = [
+ {
+ width: 3,
+ components: [{ type: "TopSites" }],
+ },
+ {
+ width: 3,
+ components: [{ type: "Message" }],
+ },
+ ];
+ store.dispatch({
+ type: at.DISCOVERY_STREAM_LAYOUT_UPDATE,
+ data: { layout: fakeLayout },
+ });
+
+ const { layoutRender } = selectLayoutRender({
+ state: store.getState().DiscoveryStream,
+ prefs: { "feeds.topsites": true },
+ });
+
+ assert.equal(layoutRender[0].components[0].type, "TopSites");
+ assert.equal(layoutRender[1], undefined);
+ });
+ it("should not render a component if filtered", () => {
+ const fakeLayout = [
+ {
+ width: 3,
+ components: [{ type: "Message" }, { type: "TopSites" }],
+ },
+ ];
+ store.dispatch({
+ type: at.DISCOVERY_STREAM_LAYOUT_UPDATE,
+ data: { layout: fakeLayout },
+ });
+
+ const { layoutRender } = selectLayoutRender({
+ state: store.getState().DiscoveryStream,
+ prefs: { "feeds.topsites": true },
+ });
+
+ assert.equal(layoutRender[0].components[0].type, "TopSites");
+ assert.equal(layoutRender[0].components[1], undefined);
+ });
+ it("should not render a Navigation if not en-*", () => {
+ const fakeLayout = [
+ {
+ width: 3,
+ components: [
+ { type: "Navigation" },
+ { type: "Message" },
+ { type: "TopSites" },
+ ],
+ },
+ ];
+ store.dispatch({
+ type: at.DISCOVERY_STREAM_LAYOUT_UPDATE,
+ data: { layout: fakeLayout },
+ });
+
+ const { layoutRender } = selectLayoutRender({
+ state: store.getState().DiscoveryStream,
+ prefs: {
+ "feeds.topsites": true,
+ "feeds.system.topstories": true,
+ "feeds.section.topstories": true,
+ },
+ });
+
+ assert.equal(layoutRender[0].components[0].type, "Message");
+ assert.equal(layoutRender[0].components[1].type, "TopSites");
+ assert.equal(layoutRender[0].components[2], undefined);
+ });
+ it("should skip rendering a spoc in position if that spoc is blocked for that session", () => {
+ const fakeLayout = [
+ {
+ width: 3,
+ components: [
+ {
+ type: "foo1",
+ properties: { items: 3 },
+ feed: { url: "foo1.com" },
+ spocs: { positions: [{ index: 0 }] },
+ },
+ ],
+ },
+ ];
+ const fakeSpocsData = {
+ lastUpdated: 0,
+ spocs: {
+ spocs: { items: [{ name: "spoc", url: "https://foo.com" }] },
+ },
+ };
+ store.dispatch({
+ type: at.DISCOVERY_STREAM_LAYOUT_UPDATE,
+ data: { layout: fakeLayout },
+ });
+ store.dispatch({
+ type: at.DISCOVERY_STREAM_FEED_UPDATE,
+ data: {
+ feed: { data: { recommendations: [{ name: "rec" }] } },
+ url: "foo1.com",
+ },
+ });
+ store.dispatch({
+ type: at.DISCOVERY_STREAM_SPOCS_UPDATE,
+ data: fakeSpocsData,
+ });
+
+ const { layoutRender: layout1 } = selectLayoutRender({
+ state: store.getState().DiscoveryStream,
+ });
+
+ store.dispatch({
+ type: at.DISCOVERY_STREAM_SPOC_BLOCKED,
+ data: { url: "https://foo.com" },
+ });
+
+ const { layoutRender: layout2 } = selectLayoutRender({
+ state: store.getState().DiscoveryStream,
+ });
+
+ assert.deepEqual(layout1[0].components[0].data.recommendations[0], {
+ name: "spoc",
+ url: "https://foo.com",
+ pos: 0,
+ });
+ assert.deepEqual(layout2[0].components[0].data.recommendations[0], {
+ name: "rec",
+ pos: 0,
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/lib/AboutPreferences.test.js b/browser/components/newtab/test/unit/lib/AboutPreferences.test.js
new file mode 100644
index 0000000000..27b7410165
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/AboutPreferences.test.js
@@ -0,0 +1,423 @@
+/* global Services */
+import {
+ AboutPreferences,
+ PREFERENCES_LOADED_EVENT,
+} from "lib/AboutPreferences.jsm";
+import { actionTypes as at, actionCreators as ac } from "common/Actions.jsm";
+import { GlobalOverrider } from "test/unit/utils";
+
+describe("AboutPreferences Feed", () => {
+ let globals;
+ let sandbox;
+ let Sections;
+ let DiscoveryStream;
+ let instance;
+
+ beforeEach(() => {
+ globals = new GlobalOverrider();
+ sandbox = globals.sandbox;
+ Sections = [];
+ DiscoveryStream = { config: { enabled: false } };
+ instance = new AboutPreferences();
+ instance.store = {
+ dispatch: sandbox.stub(),
+ getState: () => ({ Sections, DiscoveryStream }),
+ };
+ });
+ afterEach(() => {
+ globals.restore();
+ });
+
+ describe("#onAction", () => {
+ it("should call .init() on an INIT action", () => {
+ const stub = sandbox.stub(instance, "init");
+
+ instance.onAction({ type: at.INIT });
+
+ assert.calledOnce(stub);
+ });
+ it("should call .uninit() on an UNINIT action", () => {
+ const stub = sandbox.stub(instance, "uninit");
+
+ instance.onAction({ type: at.UNINIT });
+
+ assert.calledOnce(stub);
+ });
+ it("should call .openPreferences on SETTINGS_OPEN", () => {
+ const action = {
+ type: at.SETTINGS_OPEN,
+ _target: { browser: { ownerGlobal: { openPreferences: sinon.spy() } } },
+ };
+ instance.onAction(action);
+ assert.calledOnce(action._target.browser.ownerGlobal.openPreferences);
+ });
+ it("should call .BrowserOpenAddonsMgr with the extension id on OPEN_WEBEXT_SETTINGS", () => {
+ const action = {
+ type: at.OPEN_WEBEXT_SETTINGS,
+ data: "foo",
+ _target: {
+ browser: { ownerGlobal: { BrowserOpenAddonsMgr: sinon.spy() } },
+ },
+ };
+ instance.onAction(action);
+ assert.calledWith(
+ action._target.browser.ownerGlobal.BrowserOpenAddonsMgr,
+ "addons://detail/foo"
+ );
+ });
+ });
+ describe("#observe", () => {
+ it("should watch for about:preferences loading", () => {
+ sandbox.stub(Services.obs, "addObserver");
+
+ instance.init();
+
+ assert.calledOnce(Services.obs.addObserver);
+ assert.calledWith(
+ Services.obs.addObserver,
+ instance,
+ PREFERENCES_LOADED_EVENT
+ );
+ });
+ it("should stop watching on uninit", () => {
+ sandbox.stub(Services.obs, "removeObserver");
+
+ instance.uninit();
+
+ assert.calledOnce(Services.obs.removeObserver);
+ assert.calledWith(
+ Services.obs.removeObserver,
+ instance,
+ PREFERENCES_LOADED_EVENT
+ );
+ });
+ it("should try to render on event", async () => {
+ const stub = sandbox.stub(instance, "renderPreferences");
+ Sections.push({});
+
+ await instance.observe(window, PREFERENCES_LOADED_EVENT);
+
+ assert.calledOnce(stub);
+ assert.equal(stub.firstCall.args[0], window);
+ assert.include(stub.firstCall.args[1], Sections[0]);
+ });
+ it("Hide topstories rows select in sections if discovery stream is enabled", async () => {
+ const stub = sandbox.stub(instance, "renderPreferences");
+
+ Sections.push({
+ rowsPref: "row_pref",
+ maxRows: 3,
+ pref: { descString: "foo" },
+ learnMore: { link: "https://foo.com" },
+ id: "topstories",
+ });
+ DiscoveryStream = { config: { enabled: true } };
+
+ await instance.observe(window, PREFERENCES_LOADED_EVENT);
+
+ assert.calledOnce(stub);
+ const [, structure] = stub.firstCall.args;
+ assert.equal(structure[0].id, "search");
+ assert.equal(structure[1].id, "topsites");
+ assert.equal(structure[2].id, "topstories");
+ assert.isEmpty(structure[2].rowsPref);
+ });
+ });
+ describe("#renderPreferences", () => {
+ let node;
+ let prefStructure;
+ let Preferences;
+ let gHomePane;
+ const testRender = () =>
+ instance.renderPreferences(
+ {
+ document: {
+ createXULElement: sandbox.stub().returns(node),
+ l10n: {
+ setAttributes(el, id, args) {
+ el.setAttribute("data-l10n-id", id);
+ el.setAttribute("data-l10n-args", JSON.stringify(args));
+ },
+ },
+ createProcessingInstruction: sandbox.stub(),
+ createElementNS: sandbox.stub().callsFake((NS, el) => node),
+ getElementById: sandbox.stub().returns(node),
+ insertBefore: sandbox.stub().returnsArg(0),
+ querySelector: sandbox
+ .stub()
+ .returns({ appendChild: sandbox.stub() }),
+ },
+ Preferences,
+ gHomePane,
+ },
+ prefStructure,
+ DiscoveryStream.config
+ );
+ beforeEach(() => {
+ node = {
+ appendChild: sandbox.stub().returnsArg(0),
+ addEventListener: sandbox.stub(),
+ classList: { add: sandbox.stub(), remove: sandbox.stub() },
+ cloneNode: sandbox.stub().returnsThis(),
+ insertAdjacentElement: sandbox.stub().returnsArg(1),
+ setAttribute: sandbox.stub(),
+ remove: sandbox.stub(),
+ style: {},
+ };
+ prefStructure = [];
+ Preferences = {
+ add: sandbox.stub(),
+ get: sandbox.stub().returns({
+ on: sandbox.stub(),
+ }),
+ };
+ gHomePane = { toggleRestoreDefaultsBtn: sandbox.stub() };
+ });
+ describe("#getString", () => {
+ it("should not fail if titleString is not provided", () => {
+ prefStructure = [{ pref: {} }];
+
+ testRender();
+ assert.calledWith(
+ node.setAttribute,
+ "data-l10n-id",
+ sinon.match.typeOf("undefined")
+ );
+ });
+ it("should return the string id if titleString is just a string", () => {
+ const titleString = "foo";
+ prefStructure = [{ pref: { titleString } }];
+
+ testRender();
+ assert.calledWith(node.setAttribute, "data-l10n-id", titleString);
+ });
+ it("should set id and args if titleString is an object with id and values", () => {
+ const titleString = { id: "foo", values: { provider: "bar" } };
+ prefStructure = [{ pref: { titleString } }];
+
+ testRender();
+ assert.calledWith(node.setAttribute, "data-l10n-id", titleString.id);
+ assert.calledWith(
+ node.setAttribute,
+ "data-l10n-args",
+ JSON.stringify(titleString.values)
+ );
+ });
+ });
+ describe("#linkPref", () => {
+ it("should add a pref to the global", () => {
+ prefStructure = [{ pref: { feed: "feed" } }];
+
+ testRender();
+
+ assert.calledOnce(Preferences.add);
+ });
+ it("should skip adding if not shown", () => {
+ prefStructure = [{ shouldHidePref: true }];
+
+ testRender();
+
+ assert.notCalled(Preferences.add);
+ });
+ });
+ describe("pref icon", () => {
+ it("should default to webextension icon", () => {
+ prefStructure = [{ pref: { feed: "feed" } }];
+
+ testRender();
+
+ assert.calledWith(
+ node.setAttribute,
+ "src",
+ "chrome://activity-stream/content/data/content/assets/glyph-webextension-16.svg"
+ );
+ });
+ it("should use desired glyph icon", () => {
+ prefStructure = [{ icon: "highlights", pref: { feed: "feed" } }];
+
+ testRender();
+
+ assert.calledWith(
+ node.setAttribute,
+ "src",
+ "chrome://activity-stream/content/data/content/assets/glyph-highlights-16.svg"
+ );
+ });
+ it("should use specified chrome icon", () => {
+ const icon = "chrome://the/icon.svg";
+ prefStructure = [{ icon, pref: { feed: "feed" } }];
+
+ testRender();
+
+ assert.calledWith(node.setAttribute, "src", icon);
+ });
+ });
+ describe("title line", () => {
+ it("should render a title", () => {
+ const titleString = "the_title";
+ prefStructure = [{ pref: { titleString } }];
+
+ testRender();
+
+ assert.calledWith(node.setAttribute, "data-l10n-id", titleString);
+ });
+ });
+ describe("top stories", () => {
+ const href = "https://disclaimer/";
+ const eventSource = "https://disclaimer/";
+ beforeEach(() => {
+ prefStructure = [
+ {
+ id: "topstories",
+ pref: { feed: "feed", learnMore: { link: { href } } },
+ eventSource,
+ },
+ ];
+ });
+ it("should add a link for top stories", () => {
+ testRender();
+ assert.calledWith(node.setAttribute, "href", href);
+ });
+ it("should setup a user event for top stories eventSource", () => {
+ sinon.spy(instance, "setupUserEvent");
+ testRender();
+ assert.calledWith(node.addEventListener, "command");
+ assert.calledWith(instance.setupUserEvent, node, eventSource);
+ });
+ it("should setup a user event for top stories nested pref eventSource", () => {
+ sinon.spy(instance, "setupUserEvent");
+ prefStructure = [
+ {
+ id: "topstories",
+ pref: {
+ feed: "feed",
+ learnMore: { link: { href } },
+ nestedPrefs: [
+ {
+ name: "showSponsored",
+ titleString:
+ "home-prefs-recommended-by-option-sponsored-stories",
+ icon: "icon-info",
+ eventSource: "POCKET_SPOCS",
+ },
+ ],
+ },
+ },
+ ];
+ testRender();
+ assert.calledWith(node.addEventListener, "command");
+ assert.calledWith(instance.setupUserEvent, node, "POCKET_SPOCS");
+ });
+ it("should fire store dispatch with onCommand", () => {
+ const element = {
+ addEventListener: (command, action) => {
+ // Trigger the action right away because we only care about testing the action here.
+ action({ target: { checked: true } });
+ },
+ };
+ instance.setupUserEvent(element, eventSource);
+ assert.calledWith(
+ instance.store.dispatch,
+ ac.UserEvent({
+ event: "PREF_CHANGED",
+ source: eventSource,
+ value: { menu_source: "ABOUT_PREFERENCES", status: true },
+ })
+ );
+ });
+ });
+ describe("description line", () => {
+ it("should render a description", () => {
+ const descString = "the_desc";
+ prefStructure = [{ pref: { descString } }];
+
+ testRender();
+
+ assert.calledWith(node.setAttribute, "data-l10n-id", descString);
+ });
+ it("should render rows dropdown with appropriate number", () => {
+ prefStructure = [
+ { rowsPref: "row_pref", maxRows: 3, pref: { descString: "foo" } },
+ ];
+
+ testRender();
+
+ assert.calledWith(node.setAttribute, "value", 1);
+ assert.calledWith(node.setAttribute, "value", 2);
+ assert.calledWith(node.setAttribute, "value", 3);
+ });
+ });
+ describe("nested prefs", () => {
+ const titleString = "im_nested";
+ beforeEach(() => {
+ prefStructure = [{ pref: { nestedPrefs: [{ titleString }] } }];
+ });
+ it("should render a nested pref", () => {
+ testRender();
+
+ assert.calledWith(node.setAttribute, "data-l10n-id", titleString);
+ });
+ it("should set node hidden to true", () => {
+ prefStructure[0].pref.nestedPrefs[0].hidden = true;
+
+ testRender();
+
+ assert.isTrue(node.hidden);
+ });
+ it("should add a change event", () => {
+ testRender();
+
+ assert.calledOnce(Preferences.get().on);
+ assert.calledWith(Preferences.get().on, "change");
+ });
+ it("should default node disabled to false", async () => {
+ Preferences.get = sandbox.stub().returns({
+ on: sandbox.stub(),
+ _value: true,
+ });
+
+ testRender();
+
+ assert.isFalse(node.disabled);
+ });
+ it("should default node disabled to true", async () => {
+ testRender();
+
+ assert.isTrue(node.disabled);
+ });
+ it("should set node disabled to true", async () => {
+ const pref = {
+ on: sandbox.stub(),
+ _value: true,
+ };
+ Preferences.get = sandbox.stub().returns(pref);
+
+ testRender();
+ pref._value = !pref._value;
+ await Preferences.get().on.firstCall.args[1]();
+
+ assert.isTrue(node.disabled);
+ });
+ it("should set node disabled to false", async () => {
+ const pref = {
+ on: sandbox.stub(),
+ _value: false,
+ };
+ Preferences.get = sandbox.stub().returns(pref);
+
+ testRender();
+ pref._value = !pref._value;
+ await Preferences.get().on.firstCall.args[1]();
+
+ assert.isFalse(node.disabled);
+ });
+ });
+ describe("restore defaults btn", () => {
+ it("should call toggleRestoreDefaultsBtn", () => {
+ testRender();
+
+ assert.calledOnce(gHomePane.toggleRestoreDefaultsBtn);
+ });
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/lib/ActivityStream.test.js b/browser/components/newtab/test/unit/lib/ActivityStream.test.js
new file mode 100644
index 0000000000..668afebd37
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/ActivityStream.test.js
@@ -0,0 +1,531 @@
+import { CONTENT_MESSAGE_TYPE } from "common/Actions.jsm";
+import { ActivityStream, PREFS_CONFIG } from "lib/ActivityStream.jsm";
+
+describe("ActivityStream", () => {
+ let sandbox;
+ let as;
+ function FakeStore() {
+ return { init: () => {}, uninit: () => {}, feeds: { get: () => {} } };
+ }
+
+ beforeEach(() => {
+ as = new ActivityStream();
+ as.store = new FakeStore();
+ sandbox = sinon.createSandbox();
+ sandbox.stub(as.store, "init");
+ sandbox.stub(as.store, "uninit");
+ sandbox.stub(as._defaultPrefs, "init");
+ PREFS_CONFIG.get("feeds.system.topstories").value = undefined;
+ });
+
+ afterEach(() => sandbox.restore());
+
+ it("should exist", () => {
+ assert.ok(ActivityStream);
+ });
+ it("should initialize with .initialized=false", () => {
+ assert.isFalse(as.initialized, ".initialized");
+ });
+ describe("#init", () => {
+ beforeEach(() => {
+ as.init();
+ });
+ it("should initialize default prefs", () => {
+ assert.calledOnce(as._defaultPrefs.init);
+ });
+ it("should set .initialized to true", () => {
+ assert.isTrue(as.initialized, ".initialized");
+ });
+ it("should call .store.init", () => {
+ assert.calledOnce(as.store.init);
+ });
+ it("should pass to Store an INIT event for content", () => {
+ as.init();
+
+ const [, action] = as.store.init.firstCall.args;
+ assert.equal(action.meta.to, CONTENT_MESSAGE_TYPE);
+ });
+ it("should pass to Store an UNINIT event", () => {
+ as.init();
+
+ const [, , action] = as.store.init.firstCall.args;
+ assert.equal(action.type, "UNINIT");
+ });
+ it("should clear old default discoverystream config pref", () => {
+ sandbox.stub(global.Services.prefs, "prefHasUserValue").returns(true);
+ sandbox
+ .stub(global.Services.prefs, "getStringPref")
+ .returns(
+ `{"api_key_pref":"extensions.pocket.oAuthConsumerKey","enabled":false,"show_spocs":true,"layout_endpoint":"https://getpocket.cdn.mozilla.net/v3/newtab/layout?version=1&consumer_key=$apiKey&layout_variant=basic"}`
+ );
+ sandbox.stub(global.Services.prefs, "clearUserPref");
+
+ as.init();
+
+ assert.calledWith(
+ global.Services.prefs.clearUserPref,
+ "browser.newtabpage.activity-stream.discoverystream.config"
+ );
+ });
+ });
+ describe("#uninit", () => {
+ beforeEach(() => {
+ as.init();
+ as.uninit();
+ });
+ it("should set .initialized to false", () => {
+ assert.isFalse(as.initialized, ".initialized");
+ });
+ it("should call .store.uninit", () => {
+ assert.calledOnce(as.store.uninit);
+ });
+ it("should call removeObserver", () => {
+ sandbox.stub(global.Services.obs, "removeObserver");
+ as.geo = "";
+ as.uninit();
+ assert.calledWith(
+ global.Services.obs.removeObserver,
+ as,
+ global.Region.REGION_TOPIC
+ );
+ });
+ });
+ describe("#observe", () => {
+ it("should call _updateDynamicPrefs from observe", () => {
+ sandbox.stub(as, "_updateDynamicPrefs");
+ as.observe(
+ undefined,
+ global.Region.REGION_TOPIC,
+ global.Region.REGION_UPDATED
+ );
+ assert.calledOnce(as._updateDynamicPrefs);
+ });
+ });
+ describe("feeds", () => {
+ it("should create a NewTabInit feed", () => {
+ const feed = as.feeds.get("feeds.newtabinit")();
+ assert.ok(feed, "feed should exist");
+ });
+ it("should create a Places feed", () => {
+ const feed = as.feeds.get("feeds.places")();
+ assert.ok(feed, "feed should exist");
+ });
+ it("should create a TopSites feed", () => {
+ const feed = as.feeds.get("feeds.system.topsites")();
+ assert.ok(feed, "feed should exist");
+ });
+ it("should create a Telemetry feed", () => {
+ const feed = as.feeds.get("feeds.telemetry")();
+ assert.ok(feed, "feed should exist");
+ });
+ it("should create a Prefs feed", () => {
+ const feed = as.feeds.get("feeds.prefs")();
+ assert.ok(feed, "feed should exist");
+ });
+ it("should create a HighlightsFeed feed", () => {
+ const feed = as.feeds.get("feeds.section.highlights")();
+ assert.ok(feed, "feed should exist");
+ });
+ it("should create a TopStoriesFeed feed", () => {
+ const feed = as.feeds.get("feeds.system.topstories")();
+ assert.ok(feed, "feed should exist");
+ });
+ it("should create a AboutPreferences feed", () => {
+ const feed = as.feeds.get("feeds.aboutpreferences")();
+ assert.ok(feed, "feed should exist");
+ });
+ it("should create a SectionsFeed", () => {
+ const feed = as.feeds.get("feeds.sections")();
+ assert.ok(feed, "feed should exist");
+ });
+ it("should create a SystemTick feed", () => {
+ const feed = as.feeds.get("feeds.systemtick")();
+ assert.ok(feed, "feed should exist");
+ });
+ it("should create a Favicon feed", () => {
+ const feed = as.feeds.get("feeds.favicon")();
+ assert.ok(feed, "feed should exist");
+ });
+ it("should create a RecommendationProviderSwitcher feed", () => {
+ const feed = as.feeds.get("feeds.recommendationproviderswitcher")();
+ assert.ok(feed, "feed should exist");
+ });
+ it("should create a DiscoveryStreamFeed feed", () => {
+ const feed = as.feeds.get("feeds.discoverystreamfeed")();
+ assert.ok(feed, "feed should exist");
+ });
+ });
+ describe("_migratePref", () => {
+ it("should migrate a pref if the user has set a custom value", () => {
+ sandbox.stub(global.Services.prefs, "prefHasUserValue").returns(true);
+ sandbox.stub(global.Services.prefs, "getPrefType").returns("integer");
+ sandbox.stub(global.Services.prefs, "getIntPref").returns(10);
+ as._migratePref("oldPrefName", result => assert.equal(10, result));
+ });
+ it("should not migrate a pref if the user has not set a custom value", () => {
+ // we bailed out early so we don't check the pref type later
+ sandbox.stub(global.Services.prefs, "prefHasUserValue").returns(false);
+ sandbox.stub(global.Services.prefs, "getPrefType");
+ as._migratePref("oldPrefName");
+ assert.notCalled(global.Services.prefs.getPrefType);
+ });
+ it("should use the proper pref getter for each type", () => {
+ sandbox.stub(global.Services.prefs, "prefHasUserValue").returns(true);
+
+ // Integer
+ sandbox.stub(global.Services.prefs, "getIntPref");
+ sandbox.stub(global.Services.prefs, "getPrefType").returns("integer");
+ as._migratePref("oldPrefName", () => {});
+ assert.calledWith(global.Services.prefs.getIntPref, "oldPrefName");
+
+ // Boolean
+ sandbox.stub(global.Services.prefs, "getBoolPref");
+ global.Services.prefs.getPrefType.returns("boolean");
+ as._migratePref("oldPrefName", () => {});
+ assert.calledWith(global.Services.prefs.getBoolPref, "oldPrefName");
+
+ // String
+ sandbox.stub(global.Services.prefs, "getStringPref");
+ global.Services.prefs.getPrefType.returns("string");
+ as._migratePref("oldPrefName", () => {});
+ assert.calledWith(global.Services.prefs.getStringPref, "oldPrefName");
+ });
+ it("should clear the old pref after setting the new one", () => {
+ sandbox.stub(global.Services.prefs, "prefHasUserValue").returns(true);
+ sandbox.stub(global.Services.prefs, "clearUserPref");
+ sandbox.stub(global.Services.prefs, "getPrefType").returns("integer");
+ as._migratePref("oldPrefName", () => {});
+ assert.calledWith(global.Services.prefs.clearUserPref, "oldPrefName");
+ });
+ });
+ describe("discoverystream.region-basic-layout config", () => {
+ let getStringPrefStub;
+ beforeEach(() => {
+ getStringPrefStub = sandbox.stub(global.Services.prefs, "getStringPref");
+ sandbox.stub(global.Region, "home").get(() => "CA");
+ sandbox
+ .stub(global.Services.locale, "appLocaleAsBCP47")
+ .get(() => "en-CA");
+ });
+ it("should enable 7 row layout pref if no basic config is set and no geo is set", () => {
+ getStringPrefStub
+ .withArgs(
+ "browser.newtabpage.activity-stream.discoverystream.region-basic-config"
+ )
+ .returns("");
+ sandbox.stub(global.Region, "home").get(() => "");
+
+ as._updateDynamicPrefs();
+
+ assert.isFalse(
+ PREFS_CONFIG.get("discoverystream.region-basic-layout").value
+ );
+ });
+ it("should enable 1 row layout pref based on region layout pref", () => {
+ getStringPrefStub
+ .withArgs(
+ "browser.newtabpage.activity-stream.discoverystream.region-basic-config"
+ )
+ .returns("CA");
+
+ as._updateDynamicPrefs();
+
+ assert.isTrue(
+ PREFS_CONFIG.get("discoverystream.region-basic-layout").value
+ );
+ });
+ it("should enable 7 row layout pref based on region layout pref", () => {
+ getStringPrefStub
+ .withArgs(
+ "browser.newtabpage.activity-stream.discoverystream.region-basic-config"
+ )
+ .returns("");
+
+ as._updateDynamicPrefs();
+
+ assert.isFalse(
+ PREFS_CONFIG.get("discoverystream.region-basic-layout").value
+ );
+ });
+ });
+ describe("_updateDynamicPrefs topstories default value", () => {
+ let getStringPrefStub;
+ let getBoolPrefStub;
+ let appLocaleAsBCP47Stub;
+ beforeEach(() => {
+ getStringPrefStub = sandbox.stub(global.Services.prefs, "getStringPref");
+ appLocaleAsBCP47Stub = sandbox.stub(
+ global.Services.locale,
+ "appLocaleAsBCP47"
+ );
+
+ getBoolPrefStub = sandbox.stub(global.Services.prefs, "getBoolPref");
+ getBoolPrefStub
+ .withArgs("browser.newtabpage.activity-stream.feeds.section.topstories")
+ .returns(true);
+
+ appLocaleAsBCP47Stub.get(() => "en-US");
+
+ sandbox.stub(global.Region, "home").get(() => "US");
+
+ getStringPrefStub
+ .withArgs(
+ "browser.newtabpage.activity-stream.discoverystream.region-stories-config"
+ )
+ .returns("US,CA");
+ });
+ it("should be false with no geo/locale", () => {
+ appLocaleAsBCP47Stub.get(() => "");
+ sandbox.stub(global.Region, "home").get(() => "");
+
+ as._updateDynamicPrefs();
+
+ assert.isFalse(PREFS_CONFIG.get("feeds.system.topstories").value);
+ });
+ it("should be false with no geo but an allowed locale", () => {
+ appLocaleAsBCP47Stub.get(() => "");
+ sandbox.stub(global.Region, "home").get(() => "");
+ appLocaleAsBCP47Stub.get(() => "en-US");
+ getStringPrefStub
+ .withArgs(
+ "browser.newtabpage.activity-stream.discoverystream.locale-list-config"
+ )
+ .returns("en-US,en-CA,en-GB")
+ // We only have this pref set to trigger a close to real situation.
+ .withArgs(
+ "browser.newtabpage.activity-stream.discoverystream.region-stories-block"
+ )
+ .returns("FR");
+
+ as._updateDynamicPrefs();
+
+ assert.isFalse(PREFS_CONFIG.get("feeds.system.topstories").value);
+ });
+ it("should be false with unexpected geo", () => {
+ sandbox.stub(global.Region, "home").get(() => "NOGEO");
+
+ as._updateDynamicPrefs();
+
+ assert.isFalse(PREFS_CONFIG.get("feeds.system.topstories").value);
+ });
+ it("should be false with expected geo and unexpected locale", () => {
+ appLocaleAsBCP47Stub.get(() => "no-LOCALE");
+
+ as._updateDynamicPrefs();
+
+ assert.isFalse(PREFS_CONFIG.get("feeds.system.topstories").value);
+ });
+ it("should be true with expected geo and locale", () => {
+ as._updateDynamicPrefs();
+ assert.isTrue(PREFS_CONFIG.get("feeds.system.topstories").value);
+ });
+ it("should be false after expected geo and locale then unexpected", () => {
+ sandbox
+ .stub(global.Region, "home")
+ .onFirstCall()
+ .get(() => "US")
+ .onSecondCall()
+ .get(() => "NOGEO");
+
+ as._updateDynamicPrefs();
+ as._updateDynamicPrefs();
+
+ assert.isFalse(PREFS_CONFIG.get("feeds.system.topstories").value);
+ });
+ it("should be true with updated pref change", () => {
+ appLocaleAsBCP47Stub.get(() => "en-GB");
+ sandbox.stub(global.Region, "home").get(() => "GB");
+ getStringPrefStub
+ .withArgs(
+ "browser.newtabpage.activity-stream.discoverystream.region-stories-config"
+ )
+ .returns("GB");
+
+ as._updateDynamicPrefs();
+
+ assert.isTrue(PREFS_CONFIG.get("feeds.system.topstories").value);
+ });
+ it("should be true with allowed locale in non US region", () => {
+ appLocaleAsBCP47Stub.get(() => "en-CA");
+ sandbox.stub(global.Region, "home").get(() => "DE");
+ getStringPrefStub
+ .withArgs(
+ "browser.newtabpage.activity-stream.discoverystream.locale-list-config"
+ )
+ .returns("en-US,en-CA,en-GB");
+
+ as._updateDynamicPrefs();
+
+ assert.isTrue(PREFS_CONFIG.get("feeds.system.topstories").value);
+ });
+ });
+ describe("_updateDynamicPrefs topstories delayed default value", () => {
+ let clock;
+ beforeEach(() => {
+ clock = sinon.useFakeTimers();
+
+ // Have addObserver cause prefHasUserValue to now return true then observe
+ sandbox
+ .stub(global.Services.obs, "addObserver")
+ .callsFake((pref, obs) => {
+ setTimeout(() => {
+ Services.obs.notifyObservers(
+ null,
+ "browser-region",
+ "region-updated",
+ "US"
+ );
+ });
+ });
+ });
+ afterEach(() => clock.restore());
+
+ it("should set false with unexpected geo", () => {
+ sandbox
+ .stub(global.Services.prefs, "getStringPref")
+ .withArgs("browser.search.region")
+ .returns("NOGEO");
+
+ as._updateDynamicPrefs();
+
+ clock.tick(1);
+
+ assert.isFalse(PREFS_CONFIG.get("feeds.system.topstories").value);
+ });
+ it("should set true with expected geo and locale", () => {
+ sandbox
+ .stub(global.Services.prefs, "getStringPref")
+ .withArgs(
+ "browser.newtabpage.activity-stream.discoverystream.region-stories-config"
+ )
+ .returns("US");
+
+ sandbox.stub(global.Services.prefs, "getBoolPref").returns(true);
+ sandbox
+ .stub(global.Services.locale, "appLocaleAsBCP47")
+ .get(() => "en-US");
+
+ as._updateDynamicPrefs();
+ clock.tick(1);
+
+ assert.isTrue(PREFS_CONFIG.get("feeds.system.topstories").value);
+ });
+ it("should not change default even with expected geo and locale", () => {
+ as._defaultPrefs.set("feeds.system.topstories", false);
+ sandbox
+ .stub(global.Services.prefs, "getStringPref")
+ .withArgs(
+ "browser.newtabpage.activity-stream.discoverystream.region-stories-config"
+ )
+ .returns("US");
+
+ sandbox
+ .stub(global.Services.locale, "appLocaleAsBCP47")
+ .get(() => "en-US");
+
+ as._updateDynamicPrefs();
+ clock.tick(1);
+
+ assert.isFalse(PREFS_CONFIG.get("feeds.system.topstories").value);
+ });
+ it("should set false with geo blocked", () => {
+ sandbox
+ .stub(global.Services.prefs, "getStringPref")
+ .withArgs(
+ "browser.newtabpage.activity-stream.discoverystream.region-stories-config"
+ )
+ .returns("US")
+ .withArgs(
+ "browser.newtabpage.activity-stream.discoverystream.region-stories-block"
+ )
+ .returns("US");
+
+ sandbox.stub(global.Services.prefs, "getBoolPref").returns(true);
+ sandbox
+ .stub(global.Services.locale, "appLocaleAsBCP47")
+ .get(() => "en-US");
+
+ as._updateDynamicPrefs();
+ clock.tick(1);
+
+ assert.isFalse(PREFS_CONFIG.get("feeds.system.topstories").value);
+ });
+ });
+ describe("telemetry reporting on init failure", () => {
+ it("should send a ping on init error", () => {
+ as = new ActivityStream();
+ const telemetry = { handleUndesiredEvent: sandbox.spy() };
+ sandbox.stub(as.store, "init").throws();
+ sandbox.stub(as.store.feeds, "get").returns(telemetry);
+ try {
+ as.init();
+ } catch (e) {}
+ assert.calledOnce(telemetry.handleUndesiredEvent);
+ });
+ });
+
+ describe("searchs shortcuts shouldPin pref", () => {
+ const SEARCH_SHORTCUTS_SEARCH_ENGINES_PREF =
+ "improvesearch.topSiteSearchShortcuts.searchEngines";
+ let stub;
+
+ beforeEach(() => {
+ stub = sandbox.stub(global.Region, "home");
+ });
+
+ it("should be an empty string when no geo is available", () => {
+ stub.get(() => "");
+ as._updateDynamicPrefs();
+ assert.equal(
+ PREFS_CONFIG.get(SEARCH_SHORTCUTS_SEARCH_ENGINES_PREF).value,
+ ""
+ );
+ });
+
+ it("should be 'baidu' in China", () => {
+ stub.get(() => "CN");
+ as._updateDynamicPrefs();
+ assert.equal(
+ PREFS_CONFIG.get(SEARCH_SHORTCUTS_SEARCH_ENGINES_PREF).value,
+ "baidu"
+ );
+ });
+
+ it("should be 'yandex' in Russia, Belarus, Kazakhstan, and Turkey", () => {
+ const geos = ["BY", "KZ", "RU", "TR"];
+ for (const geo of geos) {
+ stub.get(() => geo);
+ as._updateDynamicPrefs();
+ assert.equal(
+ PREFS_CONFIG.get(SEARCH_SHORTCUTS_SEARCH_ENGINES_PREF).value,
+ "yandex"
+ );
+ }
+ });
+
+ it("should be 'google,amazon' in Germany, France, the UK, Japan, Italy, and the US", () => {
+ const geos = ["DE", "FR", "GB", "IT", "JP", "US"];
+ for (const geo of geos) {
+ stub.returns(geo);
+ as._updateDynamicPrefs();
+ assert.equal(
+ PREFS_CONFIG.get(SEARCH_SHORTCUTS_SEARCH_ENGINES_PREF).value,
+ "google,amazon"
+ );
+ }
+ });
+
+ it("should be 'google' elsewhere", () => {
+ // A selection of other geos
+ const geos = ["BR", "CA", "ES", "ID", "IN"];
+ for (const geo of geos) {
+ stub.get(() => geo);
+ as._updateDynamicPrefs();
+ assert.equal(
+ PREFS_CONFIG.get(SEARCH_SHORTCUTS_SEARCH_ENGINES_PREF).value,
+ "google"
+ );
+ }
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/lib/ActivityStreamMessageChannel.test.js b/browser/components/newtab/test/unit/lib/ActivityStreamMessageChannel.test.js
new file mode 100644
index 0000000000..93d9b44a4b
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/ActivityStreamMessageChannel.test.js
@@ -0,0 +1,508 @@
+import { actionCreators as ac, actionTypes as at } from "common/Actions.jsm";
+import {
+ ActivityStreamMessageChannel,
+ DEFAULT_OPTIONS,
+} from "lib/ActivityStreamMessageChannel.jsm";
+import { addNumberReducer, GlobalOverrider } from "test/unit/utils";
+import { applyMiddleware, createStore } from "redux";
+
+const OPTIONS = [
+ "pageURL, outgoingMessageName",
+ "incomingMessageName",
+ "dispatch",
+];
+
+describe("ActivityStreamMessageChannel", () => {
+ let globals;
+ let dispatch;
+ let mm;
+ let RPmessagePorts;
+ beforeEach(() => {
+ RPmessagePorts = [];
+ function RP(url, isFromAboutNewTab = false) {
+ this.url = url;
+ this.messagePorts = RPmessagePorts;
+ this.addMessageListener = globals.sandbox.spy();
+ this.removeMessageListener = globals.sandbox.spy();
+ this.sendAsyncMessage = globals.sandbox.spy();
+ this.destroy = globals.sandbox.spy();
+ this.isFromAboutNewTab = isFromAboutNewTab;
+ }
+ globals = new GlobalOverrider();
+ const overridePageListener = globals.sandbox.stub();
+ overridePageListener.withArgs(true).returns(new RP("about:newtab", true));
+ overridePageListener.withArgs(false).returns(null);
+ globals.set("AboutNewTab", {
+ overridePageListener,
+ reset: globals.sandbox.spy(),
+ });
+ globals.set("RemotePages", RP);
+ globals.set("AboutHomeStartupCache", { onPreloadedNewTabMessage() {} });
+ dispatch = globals.sandbox.spy();
+ mm = new ActivityStreamMessageChannel({ dispatch });
+ });
+
+ afterEach(() => globals.restore());
+
+ describe("portID validation", () => {
+ let sandbox;
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ sandbox.spy(global.Cu, "reportError");
+ });
+ afterEach(() => {
+ sandbox.restore();
+ });
+ it("should log errors for an invalid portID", () => {
+ mm.validatePortID({});
+ mm.validatePortID({});
+ mm.validatePortID({});
+
+ assert.equal(global.Cu.reportError.callCount, 3);
+ });
+ });
+
+ it("should exist", () => {
+ assert.ok(ActivityStreamMessageChannel);
+ });
+ it("should apply default options", () => {
+ mm = new ActivityStreamMessageChannel();
+ OPTIONS.forEach(o => assert.equal(mm[o], DEFAULT_OPTIONS[o], o));
+ });
+ it("should add options", () => {
+ const options = {
+ dispatch: () => {},
+ pageURL: "FOO.html",
+ outgoingMessageName: "OUT",
+ incomingMessageName: "IN",
+ };
+ mm = new ActivityStreamMessageChannel(options);
+ OPTIONS.forEach(o => assert.equal(mm[o], options[o], o));
+ });
+ it("should throw an error if no dispatcher was provided", () => {
+ mm = new ActivityStreamMessageChannel();
+ assert.throws(() => mm.dispatch({ type: "FOO" }));
+ });
+ describe("Creating/destroying the channel", () => {
+ describe("#createChannel", () => {
+ it("should create .channel with the correct URL", () => {
+ mm.createChannel();
+ assert.ok(mm.channel);
+ assert.equal(mm.channel.url, mm.pageURL);
+ });
+ it("should add 4 message listeners", () => {
+ mm.createChannel();
+ assert.callCount(mm.channel.addMessageListener, 4);
+ });
+ it("should add the custom message listener to the channel", () => {
+ mm.createChannel();
+ assert.calledWith(
+ mm.channel.addMessageListener,
+ mm.incomingMessageName,
+ mm.onMessage
+ );
+ });
+ it("should override AboutNewTab", () => {
+ mm.createChannel();
+ assert.calledOnce(global.AboutNewTab.overridePageListener);
+ });
+ it("should use the channel passed by AboutNewTab on override", () => {
+ mm.createChannel();
+ assert.ok(mm.channel.isFromAboutNewTab);
+ });
+ it("should not override AboutNewTab if the pageURL is not about:newtab", () => {
+ mm = new ActivityStreamMessageChannel({ pageURL: "foo.html" });
+ mm.createChannel();
+ assert.notCalled(global.AboutNewTab.overridePageListener);
+ });
+ });
+ describe("#simulateMessagesForExistingTabs", () => {
+ beforeEach(() => {
+ sinon.stub(mm, "onActionFromContent");
+ mm.createChannel();
+ });
+ it("should simulate init for existing ports", () => {
+ RPmessagePorts.push({
+ url: "about:monkeys",
+ loaded: false,
+ portID: "inited",
+ simulated: true,
+ browser: {
+ getAttribute: () => "preloaded",
+ ownerGlobal: {},
+ },
+ });
+ RPmessagePorts.push({
+ url: "about:sheep",
+ loaded: true,
+ portID: "loaded",
+ simulated: true,
+ browser: {
+ getAttribute: () => "preloaded",
+ ownerGlobal: {},
+ },
+ });
+
+ mm.simulateMessagesForExistingTabs();
+
+ assert.calledWith(mm.onActionFromContent.firstCall, {
+ type: at.NEW_TAB_INIT,
+ data: RPmessagePorts[0],
+ });
+ assert.calledWith(mm.onActionFromContent.secondCall, {
+ type: at.NEW_TAB_INIT,
+ data: RPmessagePorts[1],
+ });
+ });
+ it("should simulate load for loaded ports", () => {
+ RPmessagePorts.push({
+ loaded: true,
+ portID: "foo",
+ browser: {
+ getAttribute: () => "preloaded",
+ ownerGlobal: {},
+ },
+ });
+
+ mm.simulateMessagesForExistingTabs();
+
+ assert.calledWith(
+ mm.onActionFromContent,
+ { type: at.NEW_TAB_LOAD },
+ "foo"
+ );
+ });
+ it("should set renderLayers on preloaded browsers after load", () => {
+ RPmessagePorts.push({
+ loaded: true,
+ portID: "foo",
+ browser: {
+ getAttribute: () => "preloaded",
+ ownerGlobal: {
+ STATE_MAXIMIZED: 1,
+ STATE_MINIMIZED: 2,
+ STATE_NORMAL: 3,
+ STATE_FULLSCREEN: 4,
+ windowState: 3,
+ isFullyOccluded: false,
+ },
+ },
+ });
+ mm.simulateMessagesForExistingTabs();
+ assert.equal(RPmessagePorts[0].browser.renderLayers, true);
+ });
+ });
+ describe("#destroyChannel", () => {
+ let channel;
+ beforeEach(() => {
+ mm.createChannel();
+ channel = mm.channel;
+ });
+ it("should set .channel to null", () => {
+ mm.destroyChannel();
+ assert.isNull(mm.channel);
+ });
+ it("should reset AboutNewTab, and pass back its channel", () => {
+ mm.destroyChannel();
+ assert.calledOnce(global.AboutNewTab.reset);
+ assert.calledWith(global.AboutNewTab.reset, channel);
+ });
+ it("should not reset AboutNewTab if the pageURL is not about:newtab", () => {
+ mm = new ActivityStreamMessageChannel({ pageURL: "foo.html" });
+ mm.createChannel();
+ mm.destroyChannel();
+ assert.notCalled(global.AboutNewTab.reset);
+ });
+ it("should call channel.destroy() if pageURL is not about:newtab", () => {
+ mm = new ActivityStreamMessageChannel({ pageURL: "foo.html" });
+ mm.createChannel();
+ channel = mm.channel;
+ mm.destroyChannel();
+ assert.calledOnce(channel.destroy);
+ });
+ });
+ });
+ describe("Message handling", () => {
+ describe("#getTargetById", () => {
+ it("should get an id if it exists", () => {
+ const t = { portID: "foo:1" };
+ mm.createChannel();
+ mm.channel.messagePorts.push(t);
+ assert.equal(mm.getTargetById("foo:1"), t);
+ });
+ it("should return null if the target doesn't exist", () => {
+ const t = { portID: "foo:2" };
+ mm.createChannel();
+ mm.channel.messagePorts.push(t);
+ assert.equal(mm.getTargetById("bar:3"), null);
+ });
+ });
+ describe("#getPreloadedBrowser", () => {
+ it("should get a preloaded browser if it exists", () => {
+ const port = {
+ browser: {
+ getAttribute: () => "preloaded",
+ ownerGlobal: {},
+ },
+ };
+ mm.createChannel();
+ mm.channel.messagePorts.push(port);
+ assert.equal(mm.getPreloadedBrowser()[0], port);
+ });
+ it("should get all the preloaded browsers across windows if they exist", () => {
+ const port = {
+ browser: {
+ getAttribute: () => "preloaded",
+ ownerGlobal: {},
+ },
+ };
+ mm.createChannel();
+ mm.channel.messagePorts.push(port);
+ mm.channel.messagePorts.push(port);
+ assert.equal(mm.getPreloadedBrowser().length, 2);
+ });
+ it("should return null if there is no preloaded browser", () => {
+ const port = {
+ browser: {
+ getAttribute: () => "consumed",
+ ownerGlobal: {},
+ },
+ };
+ mm.createChannel();
+ mm.channel.messagePorts.push(port);
+ assert.equal(mm.getPreloadedBrowser(), null);
+ });
+ });
+ describe("#onNewTabInit", () => {
+ it("should dispatch a NEW_TAB_INIT action", () => {
+ const t = { portID: "foo", url: "about:monkeys" };
+ sinon.stub(mm, "onActionFromContent");
+
+ mm.onNewTabInit({ target: t });
+
+ assert.calledWith(mm.onActionFromContent, {
+ type: at.NEW_TAB_INIT,
+ data: t,
+ });
+ });
+ });
+ describe("#onNewTabLoad", () => {
+ it("should dispatch a NEW_TAB_LOAD action", () => {
+ const t = {
+ portID: "foo",
+ browser: {
+ getAttribute: () => "preloaded",
+ ownerGlobal: {},
+ },
+ };
+ sinon.stub(mm, "onActionFromContent");
+ mm.onNewTabLoad({ target: t });
+ assert.calledWith(
+ mm.onActionFromContent,
+ { type: at.NEW_TAB_LOAD },
+ "foo"
+ );
+ });
+ });
+ describe("#onNewTabUnload", () => {
+ it("should dispatch a NEW_TAB_UNLOAD action", () => {
+ const t = { portID: "foo" };
+ sinon.stub(mm, "onActionFromContent");
+ mm.onNewTabUnload({ target: t });
+ assert.calledWith(
+ mm.onActionFromContent,
+ { type: at.NEW_TAB_UNLOAD },
+ "foo"
+ );
+ });
+ });
+ describe("#onMessage", () => {
+ let sandbox;
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ sandbox.spy(global.Cu, "reportError");
+ });
+ afterEach(() => sandbox.restore());
+ it("should report an error if the msg.data is missing", () => {
+ mm.onMessage({ target: { portID: "foo" } });
+ assert.calledOnce(global.Cu.reportError);
+ });
+ it("should report an error if the msg.data.type is missing", () => {
+ mm.onMessage({ target: { portID: "foo" }, data: "foo" });
+ assert.calledOnce(global.Cu.reportError);
+ });
+ it("should call onActionFromContent", () => {
+ sinon.stub(mm, "onActionFromContent");
+ const action = {
+ data: { data: {}, type: "FOO" },
+ target: { portID: "foo" },
+ };
+ const expectedAction = {
+ type: action.data.type,
+ data: action.data.data,
+ _target: { portID: "foo" },
+ };
+ mm.onMessage(action);
+ assert.calledWith(mm.onActionFromContent, expectedAction, "foo");
+ });
+ });
+ });
+ describe("Sending and broadcasting", () => {
+ describe("#send", () => {
+ it("should send a message on the right port", () => {
+ const t = { portID: "foo:3", sendAsyncMessage: sinon.spy() };
+ mm.createChannel();
+ mm.channel.messagePorts = [t];
+ const action = ac.AlsoToOneContent({ type: "HELLO" }, "foo:3");
+ mm.send(action);
+ assert.calledWith(
+ t.sendAsyncMessage,
+ DEFAULT_OPTIONS.outgoingMessageName,
+ action
+ );
+ });
+ it("should not throw if the target isn't around", () => {
+ mm.createChannel();
+ // port is not added to the channel
+ const action = ac.AlsoToOneContent({ type: "HELLO" }, "foo:4");
+
+ assert.doesNotThrow(() => mm.send(action));
+ });
+ });
+ describe("#broadcast", () => {
+ it("should send a message on the channel", () => {
+ mm.createChannel();
+ const action = ac.BroadcastToContent({ type: "HELLO" });
+ mm.broadcast(action);
+ assert.calledWith(
+ mm.channel.sendAsyncMessage,
+ DEFAULT_OPTIONS.outgoingMessageName,
+ action
+ );
+ });
+ });
+ describe("#preloaded browser", () => {
+ it("should send the message to the preloaded browser if there's data and a preloaded browser exists", () => {
+ const port = {
+ browser: {
+ getAttribute: () => "preloaded",
+ ownerGlobal: {},
+ },
+ sendAsyncMessage: sinon.spy(),
+ };
+ mm.createChannel();
+ mm.channel.messagePorts.push(port);
+ const action = ac.AlsoToPreloaded({ type: "HELLO", data: 10 });
+ mm.sendToPreloaded(action);
+ assert.calledWith(
+ port.sendAsyncMessage,
+ DEFAULT_OPTIONS.outgoingMessageName,
+ action
+ );
+ });
+ it("should send the message to all the preloaded browsers if there's data and they exist", () => {
+ const port = {
+ browser: {
+ getAttribute: () => "preloaded",
+ ownerGlobal: {},
+ },
+ sendAsyncMessage: sinon.spy(),
+ };
+ mm.createChannel();
+ mm.channel.messagePorts.push(port);
+ mm.channel.messagePorts.push(port);
+ mm.sendToPreloaded(ac.AlsoToPreloaded({ type: "HELLO", data: 10 }));
+ assert.calledTwice(port.sendAsyncMessage);
+ });
+ it("should not send the message to the preloaded browser if there's no data and a preloaded browser does not exists", () => {
+ const port = {
+ browser: {
+ getAttribute: () => "consumed",
+ ownerGlobal: {},
+ },
+ sendAsyncMessage: sinon.spy(),
+ };
+ mm.createChannel();
+ mm.channel.messagePorts.push(port);
+ const action = ac.AlsoToPreloaded({ type: "HELLO" });
+ mm.sendToPreloaded(action);
+ assert.notCalled(port.sendAsyncMessage);
+ });
+ });
+ });
+ describe("Handling actions", () => {
+ describe("#onActionFromContent", () => {
+ beforeEach(() => mm.onActionFromContent({ type: "FOO" }, "foo:5"));
+ it("should dispatch a AlsoToMain action", () => {
+ assert.calledOnce(dispatch);
+ const [action] = dispatch.firstCall.args;
+ assert.equal(action.type, "FOO", "action.type");
+ });
+ it("should have the right fromTarget", () => {
+ const [action] = dispatch.firstCall.args;
+ assert.equal(action.meta.fromTarget, "foo:5", "meta.fromTarget");
+ });
+ });
+ describe("#middleware", () => {
+ let store;
+ beforeEach(() => {
+ store = createStore(addNumberReducer, applyMiddleware(mm.middleware));
+ });
+ it("should just call next if no channel is found", () => {
+ store.dispatch({ type: "ADD", data: 10 });
+ assert.equal(store.getState(), 10);
+ });
+ it("should call .send but not affect the main store if an OnlyToOneContent action is dispatched", () => {
+ sinon.stub(mm, "send");
+ const action = ac.OnlyToOneContent({ type: "ADD", data: 10 }, "foo");
+ mm.createChannel();
+
+ store.dispatch(action);
+
+ assert.calledWith(mm.send, action);
+ assert.equal(store.getState(), 0);
+ });
+ it("should call .send and update the main store if an AlsoToOneContent action is dispatched", () => {
+ sinon.stub(mm, "send");
+ const action = ac.AlsoToOneContent({ type: "ADD", data: 10 }, "foo");
+ mm.createChannel();
+
+ store.dispatch(action);
+
+ assert.calledWith(mm.send, action);
+ assert.equal(store.getState(), 10);
+ });
+ it("should call .broadcast if the action is BroadcastToContent", () => {
+ sinon.stub(mm, "broadcast");
+ const action = ac.BroadcastToContent({ type: "FOO" });
+
+ mm.createChannel();
+ store.dispatch(action);
+
+ assert.calledWith(mm.broadcast, action);
+ });
+ it("should call .sendToPreloaded if the action is AlsoToPreloaded", () => {
+ sinon.stub(mm, "sendToPreloaded");
+ const action = ac.AlsoToPreloaded({ type: "FOO" });
+
+ mm.createChannel();
+ store.dispatch(action);
+
+ assert.calledWith(mm.sendToPreloaded, action);
+ });
+ it("should dispatch other actions normally", () => {
+ sinon.stub(mm, "send");
+ sinon.stub(mm, "broadcast");
+ sinon.stub(mm, "sendToPreloaded");
+
+ mm.createChannel();
+ store.dispatch({ type: "ADD", data: 1 });
+
+ assert.equal(store.getState(), 1);
+ assert.notCalled(mm.send);
+ assert.notCalled(mm.broadcast);
+ assert.notCalled(mm.sendToPreloaded);
+ });
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/lib/ActivityStreamPrefs.test.js b/browser/components/newtab/test/unit/lib/ActivityStreamPrefs.test.js
new file mode 100644
index 0000000000..57ec72de8d
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/ActivityStreamPrefs.test.js
@@ -0,0 +1,113 @@
+import { DefaultPrefs, Prefs } from "lib/ActivityStreamPrefs.jsm";
+
+const TEST_PREF_CONFIG = new Map([
+ ["foo", { value: true }],
+ ["bar", { value: "BAR" }],
+ ["baz", { value: 1 }],
+ ["qux", { value: "foo", value_local_dev: "foofoo" }],
+]);
+
+describe("ActivityStreamPrefs", () => {
+ describe("Prefs", () => {
+ let p;
+ beforeEach(() => {
+ p = new Prefs();
+ });
+ it("should have get, set, and observe methods", () => {
+ assert.property(p, "get");
+ assert.property(p, "set");
+ assert.property(p, "observe");
+ });
+ describe("#observeBranch", () => {
+ let listener;
+ beforeEach(() => {
+ p._prefBranch = { addObserver: sinon.stub() };
+ listener = { onPrefChanged: sinon.stub() };
+ p.observeBranch(listener);
+ });
+ it("should add an observer", () => {
+ assert.calledOnce(p._prefBranch.addObserver);
+ assert.calledWith(p._prefBranch.addObserver, "");
+ });
+ it("should store the listener", () => {
+ assert.equal(p._branchObservers.size, 1);
+ assert.ok(p._branchObservers.has(listener));
+ });
+ it("should call listener's onPrefChanged", () => {
+ p._branchObservers.get(listener)();
+
+ assert.calledOnce(listener.onPrefChanged);
+ });
+ });
+ describe("#ignoreBranch", () => {
+ let listener;
+ beforeEach(() => {
+ p._prefBranch = {
+ addObserver: sinon.stub(),
+ removeObserver: sinon.stub(),
+ };
+ listener = {};
+ p.observeBranch(listener);
+ });
+ it("should remove the observer", () => {
+ p.ignoreBranch(listener);
+
+ assert.calledOnce(p._prefBranch.removeObserver);
+ assert.calledWith(
+ p._prefBranch.removeObserver,
+ p._prefBranch.addObserver.firstCall.args[0]
+ );
+ });
+ it("should remove the listener", () => {
+ assert.equal(p._branchObservers.size, 1);
+
+ p.ignoreBranch(listener);
+
+ assert.equal(p._branchObservers.size, 0);
+ });
+ });
+ });
+
+ describe("DefaultPrefs", () => {
+ describe("#init", () => {
+ let defaultPrefs;
+ let sandbox;
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ defaultPrefs = new DefaultPrefs(TEST_PREF_CONFIG);
+ sinon.stub(defaultPrefs, "set");
+ });
+ afterEach(() => {
+ sandbox.restore();
+ });
+ it("should initialize a boolean pref", () => {
+ defaultPrefs.init();
+ assert.calledWith(defaultPrefs.set, "foo", true);
+ });
+ it("should not initialize a pref if a default exists", () => {
+ defaultPrefs.prefs.foo = false;
+
+ defaultPrefs.init();
+
+ assert.neverCalledWith(defaultPrefs.set, "foo", true);
+ });
+ it("should initialize a string pref", () => {
+ defaultPrefs.init();
+ assert.calledWith(defaultPrefs.set, "bar", "BAR");
+ });
+ it("should initialize a integer pref", () => {
+ defaultPrefs.init();
+ assert.calledWith(defaultPrefs.set, "baz", 1);
+ });
+ it("should initialize a pref with value if Firefox is not a local build", () => {
+ defaultPrefs.init();
+ assert.calledWith(defaultPrefs.set, "qux", "foo");
+ });
+ it("should initialize a pref with value_local_dev if Firefox is a local build", () => {
+ sandbox.stub(global.AppConstants, "MOZILLA_OFFICIAL").value(false);
+ defaultPrefs.init();
+ assert.calledWith(defaultPrefs.set, "qux", "foofoo");
+ });
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/lib/ActivityStreamStorage.test.js b/browser/components/newtab/test/unit/lib/ActivityStreamStorage.test.js
new file mode 100644
index 0000000000..f13dfd07ad
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/ActivityStreamStorage.test.js
@@ -0,0 +1,161 @@
+import { ActivityStreamStorage } from "lib/ActivityStreamStorage.jsm";
+import { GlobalOverrider } from "test/unit/utils";
+
+let overrider = new GlobalOverrider();
+
+describe("ActivityStreamStorage", () => {
+ let sandbox;
+ let indexedDB;
+ let storage;
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ indexedDB = {
+ open: sandbox.stub().resolves({}),
+ deleteDatabase: sandbox.stub().resolves(),
+ };
+ overrider.set({ IndexedDB: indexedDB });
+ storage = new ActivityStreamStorage({
+ storeNames: ["storage_test"],
+ telemetry: { handleUndesiredEvent: sandbox.stub() },
+ });
+ });
+ afterEach(() => {
+ sandbox.restore();
+ });
+ it("should throw if required arguments not provided", () => {
+ assert.throws(() => new ActivityStreamStorage({ telemetry: true }));
+ });
+ describe(".db", () => {
+ it("should not throw an error when accessing db", async () => {
+ assert.ok(storage.db);
+ });
+
+ it("should delete and recreate the db if opening db fails", async () => {
+ const newDb = {};
+ indexedDB.open.onFirstCall().rejects(new Error("fake error"));
+ indexedDB.open.onSecondCall().resolves(newDb);
+
+ const db = await storage.db;
+ assert.calledOnce(indexedDB.deleteDatabase);
+ assert.calledTwice(indexedDB.open);
+ assert.equal(db, newDb);
+ });
+ });
+ describe("#getDbTable", () => {
+ let testStorage;
+ let storeStub;
+ beforeEach(() => {
+ storeStub = {
+ getAll: sandbox.stub().resolves(),
+ get: sandbox.stub().resolves(),
+ put: sandbox.stub().resolves(),
+ };
+ sandbox.stub(storage, "_getStore").resolves(storeStub);
+ testStorage = storage.getDbTable("storage_test");
+ });
+ it("should reverse key value parameters for put", async () => {
+ await testStorage.set("key", "value");
+
+ assert.calledOnce(storeStub.put);
+ assert.calledWith(storeStub.put, "value", "key");
+ });
+ it("should return the correct value for get", async () => {
+ storeStub.get.withArgs("foo").resolves("foo");
+
+ const result = await testStorage.get("foo");
+
+ assert.calledOnce(storeStub.get);
+ assert.equal(result, "foo");
+ });
+ it("should return the correct value for getAll", async () => {
+ storeStub.getAll.resolves(["bar"]);
+
+ const result = await testStorage.getAll();
+
+ assert.calledOnce(storeStub.getAll);
+ assert.deepEqual(result, ["bar"]);
+ });
+ it("should query the correct object store", async () => {
+ await testStorage.get();
+
+ assert.calledOnce(storage._getStore);
+ assert.calledWithExactly(storage._getStore, "storage_test");
+ });
+ it("should throw if table is not found", () => {
+ assert.throws(() => storage.getDbTable("undefined_store"));
+ });
+ });
+ it("should get the correct objectStore when calling _getStore", async () => {
+ const objectStoreStub = sandbox.stub();
+ indexedDB.open.resolves({ objectStore: objectStoreStub });
+
+ await storage._getStore("foo");
+
+ assert.calledOnce(objectStoreStub);
+ assert.calledWithExactly(objectStoreStub, "foo", "readwrite");
+ });
+ it("should create a db with the correct store name", async () => {
+ const dbStub = {
+ createObjectStore: sandbox.stub(),
+ objectStoreNames: { contains: sandbox.stub().returns(false) },
+ };
+ await storage.db;
+
+ // call the cb with a stub
+ indexedDB.open.args[0][2](dbStub);
+
+ assert.calledOnce(dbStub.createObjectStore);
+ assert.calledWithExactly(dbStub.createObjectStore, "storage_test");
+ });
+ it("should handle an array of object store names", async () => {
+ storage = new ActivityStreamStorage({
+ storeNames: ["store1", "store2"],
+ telemetry: {},
+ });
+ const dbStub = {
+ createObjectStore: sandbox.stub(),
+ objectStoreNames: { contains: sandbox.stub().returns(false) },
+ };
+ await storage.db;
+
+ // call the cb with a stub
+ indexedDB.open.args[0][2](dbStub);
+
+ assert.calledTwice(dbStub.createObjectStore);
+ assert.calledWith(dbStub.createObjectStore, "store1");
+ assert.calledWith(dbStub.createObjectStore, "store2");
+ });
+ it("should skip creating existing stores", async () => {
+ storage = new ActivityStreamStorage({
+ storeNames: ["store1", "store2"],
+ telemetry: {},
+ });
+ const dbStub = {
+ createObjectStore: sandbox.stub(),
+ objectStoreNames: { contains: sandbox.stub().returns(true) },
+ };
+ await storage.db;
+
+ // call the cb with a stub
+ indexedDB.open.args[0][2](dbStub);
+
+ assert.notCalled(dbStub.createObjectStore);
+ });
+ describe("#_requestWrapper", () => {
+ it("should return a successful result", async () => {
+ const result = await storage._requestWrapper(() =>
+ Promise.resolve("foo")
+ );
+
+ assert.equal(result, "foo");
+ assert.notCalled(storage.telemetry.handleUndesiredEvent);
+ });
+ it("should report failures", async () => {
+ try {
+ await storage._requestWrapper(() => Promise.reject(new Error()));
+ } catch (e) {
+ assert.calledOnce(storage.telemetry.handleUndesiredEvent);
+ }
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/lib/BookmarkPanelHub.test.js b/browser/components/newtab/test/unit/lib/BookmarkPanelHub.test.js
new file mode 100644
index 0000000000..dfcfecb2be
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/BookmarkPanelHub.test.js
@@ -0,0 +1,514 @@
+import { _BookmarkPanelHub } from "lib/BookmarkPanelHub.jsm";
+import { GlobalOverrider } from "test/unit/utils";
+import { PanelTestProvider } from "lib/PanelTestProvider.jsm";
+
+describe("BookmarkPanelHub", () => {
+ let globals;
+ let sandbox;
+ let instance;
+ let fakeAddImpression;
+ let fakeHandleMessageRequest;
+ let fakeL10n;
+ let fakeMessage;
+ let fakeMessageFluent;
+ let fakeTarget;
+ let fakeContainer;
+ let fakeSendTelemetry;
+ let fakeWindow;
+ let isBrowserPrivateStub;
+ beforeEach(async () => {
+ sandbox = sinon.createSandbox();
+ globals = new GlobalOverrider();
+
+ fakeL10n = {
+ setAttributes: sandbox.stub(),
+ translateElements: sandbox.stub().resolves(),
+ };
+ globals.set("DOMLocalization", function() {
+ return fakeL10n;
+ }); // eslint-disable-line prefer-arrow-callback
+ globals.set("FxAccounts", {
+ config: { promiseConnectAccountURI: sandbox.stub() },
+ });
+ isBrowserPrivateStub = sandbox.stub().returns(false);
+ globals.set("PrivateBrowsingUtils", {
+ isBrowserPrivate: isBrowserPrivateStub,
+ });
+
+ instance = new _BookmarkPanelHub();
+ fakeAddImpression = sandbox.stub();
+ fakeHandleMessageRequest = sandbox.stub();
+ [
+ { content: fakeMessageFluent },
+ { content: fakeMessage },
+ ] = await PanelTestProvider.getMessages();
+ fakeContainer = {
+ addEventListener: sandbox.stub(),
+ setAttribute: sandbox.stub(),
+ removeAttribute: sandbox.stub(),
+ classList: { add: sandbox.stub() },
+ appendChild: sandbox.stub(),
+ querySelector: sandbox.stub(),
+ children: [],
+ style: {},
+ getBoundingClientRect: sandbox.stub(),
+ };
+ const document = {
+ createElementNS: sandbox.stub().returns(fakeContainer),
+ getElementById: sandbox.stub().returns(fakeContainer),
+ l10n: fakeL10n,
+ };
+ fakeWindow = {
+ ownerGlobal: {
+ openLinkIn: sandbox.stub(),
+ gBrowser: { selectedBrowser: "browser" },
+ },
+ MozXULElement: { insertFTLIfNeeded: sandbox.stub() },
+ document,
+ requestAnimationFrame: x => x(),
+ };
+ fakeTarget = {
+ document,
+ container: {
+ querySelector: sandbox.stub(),
+ appendChild: sandbox.stub(),
+ setAttribute: sandbox.stub(),
+ removeAttribute: sandbox.stub(),
+ },
+ hidePopup: sandbox.stub(),
+ infoButton: {},
+ close: sandbox.stub(),
+ browser: {
+ ownerGlobal: {
+ gBrowser: { ownerDocument: document },
+ window: fakeWindow,
+ },
+ },
+ };
+ fakeSendTelemetry = sandbox.stub();
+ });
+ afterEach(() => {
+ instance.uninit();
+ sandbox.restore();
+ globals.restore();
+ });
+ it("should create an instance", () => {
+ assert.ok(instance);
+ });
+ it("should uninit", () => {
+ instance.uninit();
+
+ assert.isFalse(instance._initialized);
+ assert.isNull(instance._addImpression);
+ assert.isNull(instance._handleMessageRequest);
+ });
+ it("should instantiate handleMessageRequest and addImpression and l10n", () => {
+ instance.init(
+ fakeHandleMessageRequest,
+ fakeAddImpression,
+ fakeSendTelemetry
+ );
+
+ assert.equal(instance._addImpression, fakeAddImpression);
+ assert.equal(instance._handleMessageRequest, fakeHandleMessageRequest);
+ assert.equal(instance._sendTelemetry, fakeSendTelemetry);
+ assert.ok(instance._l10n);
+ assert.isTrue(instance._initialized);
+ });
+ it("should return early if not initialized", async () => {
+ assert.isFalse(await instance.messageRequest());
+ });
+ describe("#messageRequest", () => {
+ beforeEach(() => {
+ sandbox.stub(instance, "onResponse");
+ instance.init(
+ fakeHandleMessageRequest,
+ fakeAddImpression,
+ fakeSendTelemetry
+ );
+ });
+ afterEach(() => {
+ sandbox.restore();
+ });
+ it("should not re-request messages for the same URL", async () => {
+ instance._response = { url: "foo.com", content: true };
+ fakeTarget.url = "foo.com";
+ sandbox.stub(instance, "showMessage");
+
+ await instance.messageRequest(fakeTarget);
+
+ assert.notCalled(fakeHandleMessageRequest);
+ assert.calledOnce(instance.showMessage);
+ });
+ it("should call handleMessageRequest", async () => {
+ fakeHandleMessageRequest.resolves(fakeMessage);
+
+ await instance.messageRequest(fakeTarget, {});
+
+ assert.calledOnce(fakeHandleMessageRequest);
+ assert.calledWithExactly(fakeHandleMessageRequest, {
+ triggerId: instance._trigger.id,
+ });
+ });
+ it("should call onResponse", async () => {
+ fakeHandleMessageRequest.resolves(fakeMessage);
+
+ await instance.messageRequest(fakeTarget, {});
+
+ assert.calledOnce(instance.onResponse);
+ assert.calledWithExactly(
+ instance.onResponse,
+ fakeMessage,
+ fakeTarget,
+ {}
+ );
+ });
+ });
+ describe("#onResponse", () => {
+ beforeEach(() => {
+ instance.init(
+ fakeHandleMessageRequest,
+ fakeAddImpression,
+ fakeSendTelemetry
+ );
+ sandbox.stub(instance, "showMessage");
+ sandbox.stub(instance, "sendImpression");
+ sandbox.stub(instance, "hideMessage");
+ fakeTarget = { infoButton: { disabled: true } };
+ });
+ it("should show a message when called with a response", () => {
+ instance.onResponse({ content: "content" }, fakeTarget, fakeWindow);
+
+ assert.calledOnce(instance.showMessage);
+ assert.calledWithExactly(
+ instance.showMessage,
+ "content",
+ fakeTarget,
+ fakeWindow
+ );
+ assert.calledOnce(instance.sendImpression);
+ });
+ it("should insert the appropriate ftl files with translations", () => {
+ instance.onResponse({ content: "content" }, fakeTarget, fakeWindow);
+
+ assert.calledTwice(fakeWindow.MozXULElement.insertFTLIfNeeded);
+ assert.calledWith(
+ fakeWindow.MozXULElement.insertFTLIfNeeded,
+ "browser/newtab/asrouter.ftl"
+ );
+ assert.calledWith(
+ fakeWindow.MozXULElement.insertFTLIfNeeded,
+ "browser/branding/sync-brand.ftl"
+ );
+ });
+ it("should dispatch a user impression", () => {
+ sandbox.spy(instance, "sendUserEventTelemetry");
+
+ instance.onResponse({ content: "content" }, fakeTarget, fakeWindow);
+
+ assert.calledOnce(instance.sendUserEventTelemetry);
+ assert.calledWithExactly(
+ instance.sendUserEventTelemetry,
+ "IMPRESSION",
+ fakeWindow
+ );
+ assert.calledOnce(fakeSendTelemetry);
+
+ const [ping] = fakeSendTelemetry.firstCall.args;
+
+ assert.equal(ping.type, "DOORHANGER_TELEMETRY");
+ assert.equal(ping.data.event, "IMPRESSION");
+ });
+ it("should not dispatch a user impression if the window is private", () => {
+ isBrowserPrivateStub.returns(true);
+ sandbox.spy(instance, "sendUserEventTelemetry");
+
+ instance.onResponse({ content: "content" }, fakeTarget, fakeWindow);
+
+ assert.calledOnce(instance.sendUserEventTelemetry);
+ assert.calledWithExactly(
+ instance.sendUserEventTelemetry,
+ "IMPRESSION",
+ fakeWindow
+ );
+ assert.notCalled(fakeSendTelemetry);
+ });
+ it("should hide existing messages if no response is provided", () => {
+ instance.onResponse(null, fakeTarget);
+
+ assert.calledOnce(instance.hideMessage);
+ assert.calledWithExactly(instance.hideMessage, fakeTarget);
+ });
+ });
+ describe("#showMessage.collapsed=false", () => {
+ beforeEach(() => {
+ instance.init(
+ fakeHandleMessageRequest,
+ fakeAddImpression,
+ fakeSendTelemetry
+ );
+ sandbox.stub(instance, "toggleRecommendation");
+ sandbox.stub(instance, "_response").value({ collapsed: false });
+ });
+ it("should create a container", () => {
+ fakeTarget.container.querySelector.returns(false);
+
+ instance.showMessage(fakeMessage, fakeTarget);
+
+ assert.equal(fakeTarget.document.createElementNS.callCount, 6);
+ assert.calledOnce(fakeTarget.container.appendChild);
+ assert.notCalled(fakeL10n.setAttributes);
+ });
+ it("should create a container (fluent message)", () => {
+ fakeTarget.container.querySelector.returns(false);
+
+ instance.showMessage(fakeMessageFluent, fakeTarget);
+
+ assert.equal(fakeTarget.document.createElementNS.callCount, 6);
+ assert.calledOnce(fakeTarget.container.appendChild);
+ });
+ it("should set l10n attributes", () => {
+ fakeTarget.container.querySelector.returns(false);
+
+ instance.showMessage(fakeMessageFluent, fakeTarget);
+
+ assert.equal(fakeL10n.setAttributes.callCount, 4);
+ });
+ it("call adjust panel height when height is > 150px", async () => {
+ fakeTarget.container.querySelector.returns(false);
+ fakeContainer.getBoundingClientRect.returns({ height: 160 });
+
+ await instance._adjustPanelHeight(fakeWindow, fakeContainer);
+
+ assert.calledOnce(fakeWindow.document.l10n.translateElements);
+ assert.calledTwice(fakeContainer.getBoundingClientRect);
+ assert.calledWithExactly(
+ fakeContainer.classList.add,
+ "longMessagePadding"
+ );
+ });
+ it("should reuse the container", () => {
+ fakeTarget.container.querySelector.returns(true);
+
+ instance.showMessage(fakeMessage, fakeTarget);
+
+ assert.notCalled(fakeTarget.container.appendChild);
+ });
+ it("should open a tab with FxA signup", async () => {
+ fakeTarget.container.querySelector.returns(false);
+
+ instance.showMessage(fakeMessage, fakeTarget, fakeWindow);
+ // Call the event listener cb
+ await fakeContainer.addEventListener.firstCall.args[1]();
+
+ assert.calledOnce(fakeWindow.ownerGlobal.openLinkIn);
+ });
+ it("should send a click event", async () => {
+ sandbox.stub(instance, "sendUserEventTelemetry");
+ fakeTarget.container.querySelector.returns(false);
+
+ instance.showMessage(fakeMessage, fakeTarget, fakeWindow);
+ // Call the event listener cb
+ await fakeContainer.addEventListener.firstCall.args[1]();
+
+ assert.calledOnce(instance.sendUserEventTelemetry);
+ assert.calledWithExactly(
+ instance.sendUserEventTelemetry,
+ "CLICK",
+ fakeWindow
+ );
+ });
+ it("should send a click event", async () => {
+ sandbox.stub(instance, "sendUserEventTelemetry");
+ fakeTarget.container.querySelector.returns(false);
+
+ instance.showMessage(fakeMessage, fakeTarget, fakeWindow);
+ // Call the event listener cb
+ await fakeContainer.addEventListener.firstCall.args[1]();
+
+ assert.calledOnce(instance.sendUserEventTelemetry);
+ assert.calledWithExactly(
+ instance.sendUserEventTelemetry,
+ "CLICK",
+ fakeWindow
+ );
+ });
+ it("should collapse the message", () => {
+ fakeTarget.container.querySelector.returns(false);
+ sandbox.spy(instance, "collapseMessage");
+ instance._response.collapsed = false;
+
+ instance.showMessage(fakeMessage, fakeTarget, fakeWindow);
+ // Show message calls it once so we need to reset
+ instance.toggleRecommendation.reset();
+ // Call the event listener cb
+ fakeContainer.addEventListener.secondCall.args[1]();
+
+ assert.calledOnce(instance.collapseMessage);
+ assert.calledOnce(fakeTarget.close);
+ assert.isTrue(instance._response.collapsed);
+ assert.calledOnce(instance.toggleRecommendation);
+ });
+ it("should send a dismiss event", () => {
+ sandbox.stub(instance, "sendUserEventTelemetry");
+ sandbox.spy(instance, "collapseMessage");
+ instance._response.collapsed = false;
+
+ instance.showMessage(fakeMessage, fakeTarget, fakeWindow);
+ // Call the event listener cb
+ fakeContainer.addEventListener.secondCall.args[1]();
+
+ assert.calledOnce(instance.sendUserEventTelemetry);
+ assert.calledWithExactly(
+ instance.sendUserEventTelemetry,
+ "DISMISS",
+ fakeWindow
+ );
+ });
+ it("should call toggleRecommendation `true`", () => {
+ instance.showMessage(fakeMessage, fakeTarget, fakeWindow);
+
+ assert.calledOnce(instance.toggleRecommendation);
+ assert.calledWithExactly(instance.toggleRecommendation, true);
+ });
+ });
+ describe("#showMessage.collapsed=true", () => {
+ beforeEach(() => {
+ sandbox
+ .stub(instance, "_response")
+ .value({ collapsed: true, target: fakeTarget });
+ sandbox.stub(instance, "toggleRecommendation");
+ });
+ it("should return early if the message is collapsed", () => {
+ instance.showMessage();
+
+ assert.calledOnce(instance.toggleRecommendation);
+ assert.calledWithExactly(instance.toggleRecommendation, false);
+ });
+ });
+ describe("#hideMessage", () => {
+ let removeStub;
+ beforeEach(() => {
+ sandbox.stub(instance, "toggleRecommendation");
+ removeStub = sandbox.stub();
+ fakeTarget = {
+ container: {
+ querySelector: sandbox.stub().returns({ remove: removeStub }),
+ },
+ };
+ instance._response = { win: fakeWindow };
+ });
+ it("should remove the message", () => {
+ instance.hideMessage(fakeTarget);
+
+ assert.calledOnce(removeStub);
+ });
+ it("should call toggleRecommendation `false`", () => {
+ instance.hideMessage(fakeTarget);
+
+ assert.calledOnce(instance.toggleRecommendation);
+ assert.calledWithExactly(instance.toggleRecommendation, false);
+ });
+ });
+ describe("#toggleRecommendation", () => {
+ let target;
+ beforeEach(() => {
+ target = {
+ infoButton: {},
+ container: {
+ setAttribute: sandbox.stub(),
+ removeAttribute: sandbox.stub(),
+ },
+ };
+ sandbox.stub(instance, "_response").value({ target });
+ });
+ it("should check infoButton", () => {
+ instance.toggleRecommendation(true);
+
+ assert.isTrue(target.infoButton.checked);
+ });
+ it("should uncheck infoButton", () => {
+ instance.toggleRecommendation(false);
+
+ assert.isFalse(target.infoButton.checked);
+ });
+ it("should uncheck infoButton", () => {
+ target.infoButton.checked = true;
+
+ instance.toggleRecommendation();
+
+ assert.isFalse(target.infoButton.checked);
+ });
+ it("should disable the container", () => {
+ target.infoButton.checked = true;
+
+ instance.toggleRecommendation();
+
+ assert.calledOnce(target.container.setAttribute);
+ });
+ it("should enable container", () => {
+ target.infoButton.checked = false;
+
+ instance.toggleRecommendation();
+
+ assert.calledOnce(target.container.removeAttribute);
+ });
+ });
+ describe("#forceShowMessage", () => {
+ it("should call showMessage with the correct args", () => {
+ sandbox.spy(instance, "showMessage");
+ sandbox.stub(instance, "hideMessage");
+
+ instance.forceShowMessage(fakeTarget.browser, { content: fakeMessage });
+
+ assert.calledOnce(instance.showMessage);
+ assert.calledOnce(instance.hideMessage);
+ assert.calledWithExactly(
+ instance.showMessage,
+ fakeMessage,
+ sinon.match.object,
+ fakeWindow
+ );
+ });
+ it("should insert required fluent files", () => {
+ sandbox.stub(instance, "showMessage");
+
+ instance.forceShowMessage(fakeTarget.browser, { content: fakeMessage });
+
+ assert.calledTwice(fakeWindow.MozXULElement.insertFTLIfNeeded);
+ });
+ it("should insert a message you can collapse", () => {
+ sandbox.spy(instance, "showMessage");
+ sandbox.stub(instance, "toggleRecommendation");
+ sandbox.stub(instance, "sendUserEventTelemetry");
+
+ instance.forceShowMessage(fakeTarget.browser, { content: fakeMessage });
+
+ const [
+ ,
+ eventListenerCb,
+ ] = fakeContainer.addEventListener.secondCall.args;
+ // Called with `true` to show the message
+ instance.toggleRecommendation.reset();
+ eventListenerCb({ stopPropagation: sandbox.stub() });
+
+ assert.calledWithExactly(instance.toggleRecommendation, false);
+ });
+ });
+ describe("#sendImpression", () => {
+ beforeEach(() => {
+ instance.init(
+ fakeHandleMessageRequest,
+ fakeAddImpression,
+ fakeSendTelemetry
+ );
+ instance._response = "foo";
+ });
+ it("should dispatch an impression", () => {
+ instance.sendImpression();
+
+ assert.calledOnce(fakeAddImpression);
+ assert.equal(fakeAddImpression.firstCall.args[0], "foo");
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/lib/DiscoveryStreamFeed.test.js b/browser/components/newtab/test/unit/lib/DiscoveryStreamFeed.test.js
new file mode 100644
index 0000000000..d5a70da0ea
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/DiscoveryStreamFeed.test.js
@@ -0,0 +1,2915 @@
+import {
+ actionCreators as ac,
+ actionTypes as at,
+ actionUtils as au,
+} from "common/Actions.jsm";
+import { combineReducers, createStore } from "redux";
+import { GlobalOverrider } from "test/unit/utils";
+import { DiscoveryStreamFeed } from "lib/DiscoveryStreamFeed.jsm";
+import { RecommendationProviderSwitcher } from "lib/RecommendationProviderSwitcher.jsm";
+import { reducers } from "common/Reducers.jsm";
+
+const CONFIG_PREF_NAME = "discoverystream.config";
+const DUMMY_ENDPOINT = "https://getpocket.cdn.mozilla.net/dummy";
+const ENDPOINTS_PREF_NAME = "discoverystream.endpoints";
+const SPOC_IMPRESSION_TRACKING_PREF = "discoverystream.spoc.impressions";
+const REC_IMPRESSION_TRACKING_PREF = "discoverystream.rec.impressions";
+const THIRTY_MINUTES = 30 * 60 * 1000;
+const ONE_WEEK = 7 * 24 * 60 * 60 * 1000; // 1 week
+
+const FAKE_UUID = "{foo-123-foo}";
+
+// eslint-disable-next-line max-statements
+describe("DiscoveryStreamFeed", () => {
+ let feed;
+ let feeds;
+ let recommendationProviderSwitcher;
+ let sandbox;
+ let fetchStub;
+ let clock;
+ let fakeNewTabUtils;
+ let globals;
+
+ const setPref = (name, value) => {
+ const action = {
+ type: at.PREF_CHANGED,
+ data: {
+ name,
+ value: typeof value === "object" ? JSON.stringify(value) : value,
+ },
+ };
+ feed.store.dispatch(action);
+ feed.onAction(action);
+ };
+
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+
+ // Fetch
+ fetchStub = sandbox.stub(global, "fetch");
+
+ // Time
+ clock = sinon.useFakeTimers();
+
+ globals = new GlobalOverrider();
+ globals.set("gUUIDGenerator", { generateUUID: () => FAKE_UUID });
+
+ sandbox
+ .stub(global.Services.prefs, "getBoolPref")
+ .withArgs("browser.newtabpage.activity-stream.discoverystream.enabled")
+ .returns(true);
+
+ recommendationProviderSwitcher = new RecommendationProviderSwitcher();
+ recommendationProviderSwitcher.store = createStore(
+ combineReducers(reducers),
+ {}
+ );
+ feeds = {
+ "feeds.recommendationproviderswitcher": recommendationProviderSwitcher,
+ };
+
+ // Feed
+ feed = new DiscoveryStreamFeed();
+ feed.store = createStore(combineReducers(reducers), {
+ Prefs: {
+ values: {
+ [CONFIG_PREF_NAME]: JSON.stringify({
+ enabled: false,
+ show_spocs: false,
+ layout_endpoint: DUMMY_ENDPOINT,
+ }),
+ [ENDPOINTS_PREF_NAME]: DUMMY_ENDPOINT,
+ "discoverystream.enabled": true,
+ "feeds.section.topstories": true,
+ "feeds.system.topstories": true,
+ "discoverystream.spocs.personalized": true,
+ "discoverystream.recs.personalized": true,
+ },
+ },
+ });
+ feed.store.feeds = {
+ get: name => feeds[name],
+ };
+ global.fetch.resetHistory();
+
+ sandbox.stub(feed, "_maybeUpdateCachedData").resolves();
+
+ globals.set("setTimeout", callback => {
+ callback();
+ });
+
+ fakeNewTabUtils = {
+ blockedLinks: {
+ links: [],
+ isBlocked: () => false,
+ },
+ };
+ globals.set("NewTabUtils", fakeNewTabUtils);
+ });
+
+ afterEach(() => {
+ clock.restore();
+ sandbox.restore();
+ globals.restore();
+ });
+
+ describe("#fetchFromEndpoint", () => {
+ beforeEach(() => {
+ feed._prefCache = {
+ config: {
+ api_key_pref: "",
+ },
+ };
+ fetchStub.resolves({
+ json: () => Promise.resolve("hi"),
+ ok: true,
+ });
+ });
+ it("should get a response", async () => {
+ const response = await feed.fetchFromEndpoint(DUMMY_ENDPOINT);
+
+ assert.equal(response, "hi");
+ });
+ it("should not send cookies", async () => {
+ await feed.fetchFromEndpoint(DUMMY_ENDPOINT);
+
+ assert.propertyVal(fetchStub.firstCall.args[1], "credentials", "omit");
+ });
+ it("should allow unexpected response", async () => {
+ fetchStub.resolves({ ok: false });
+
+ const response = await feed.fetchFromEndpoint(DUMMY_ENDPOINT);
+
+ assert.equal(response, null);
+ });
+ it("should disallow unexpected endpoints", async () => {
+ feed.store.getState = () => ({
+ Prefs: { values: { [ENDPOINTS_PREF_NAME]: "https://other.site" } },
+ });
+
+ const response = await feed.fetchFromEndpoint(DUMMY_ENDPOINT);
+
+ assert.equal(response, null);
+ });
+ it("should allow multiple endpoints", async () => {
+ feed.store.getState = () => ({
+ Prefs: {
+ values: {
+ [ENDPOINTS_PREF_NAME]: `https://other.site,${DUMMY_ENDPOINT}`,
+ },
+ },
+ });
+
+ const response = await feed.fetchFromEndpoint(DUMMY_ENDPOINT);
+
+ assert.equal(response, "hi");
+ });
+ it("should replace urls with $apiKey", async () => {
+ sandbox.stub(global.Services.prefs, "getCharPref").returns("replaced");
+
+ await feed.fetchFromEndpoint(
+ "https://getpocket.cdn.mozilla.net/dummy?consumer_key=$apiKey"
+ );
+
+ assert.calledWithMatch(
+ fetchStub,
+ "https://getpocket.cdn.mozilla.net/dummy?consumer_key=replaced",
+ { credentials: "omit" }
+ );
+ });
+ it("should replace locales with $locale", async () => {
+ feed.locale = "replaced";
+ await feed.fetchFromEndpoint(
+ "https://getpocket.cdn.mozilla.net/dummy?locale_lang=$locale"
+ );
+
+ assert.calledWithMatch(
+ fetchStub,
+ "https://getpocket.cdn.mozilla.net/dummy?locale_lang=replaced",
+ { credentials: "omit" }
+ );
+ });
+ it("should allow POST and with other options", async () => {
+ await feed.fetchFromEndpoint("https://getpocket.cdn.mozilla.net/dummy", {
+ method: "POST",
+ body: "{}",
+ });
+
+ assert.calledWithMatch(
+ fetchStub,
+ "https://getpocket.cdn.mozilla.net/dummy",
+ {
+ credentials: "omit",
+ method: "POST",
+ body: "{}",
+ }
+ );
+ });
+ });
+
+ describe("#getOrCreateImpressionId", () => {
+ it("should create impression id in constructor", async () => {
+ assert.equal(feed._impressionId, FAKE_UUID);
+ });
+ it("should create impression id if none exists", async () => {
+ sandbox.stub(global.Services.prefs, "setCharPref").returns();
+
+ const result = feed.getOrCreateImpressionId();
+
+ assert.equal(result, FAKE_UUID);
+ assert.calledOnce(global.Services.prefs.setCharPref);
+ });
+ it("should use impression id if exists", async () => {
+ sandbox.stub(global.Services.prefs, "getCharPref").returns("from get");
+
+ const result = feed.getOrCreateImpressionId();
+
+ assert.equal(result, "from get");
+ assert.calledOnce(global.Services.prefs.getCharPref);
+ });
+ });
+
+ describe("#loadLayout", () => {
+ it("should fetch data and populate the cache if it is empty", async () => {
+ const resp = { layout: ["foo", "bar"] };
+ const fakeCache = {};
+ sandbox.stub(feed.cache, "get").returns(Promise.resolve(fakeCache));
+ sandbox.stub(feed.cache, "set").returns(Promise.resolve());
+
+ fetchStub.resolves({ ok: true, json: () => Promise.resolve(resp) });
+
+ await feed.loadLayout(feed.store.dispatch);
+
+ assert.calledOnce(fetchStub);
+ assert.equal(feed.cache.set.firstCall.args[0], "layout");
+ assert.deepEqual(feed.cache.set.firstCall.args[1].layout, resp.layout);
+ });
+ it("should fetch data and populate the cache if the cached data is older than 30 mins", async () => {
+ const resp = { layout: ["foo", "bar"] };
+ const fakeCache = {
+ layout: { layout: ["hello"], lastUpdated: Date.now() },
+ };
+
+ sandbox.stub(feed.cache, "get").returns(Promise.resolve(fakeCache));
+ sandbox.stub(feed.cache, "set").returns(Promise.resolve());
+
+ fetchStub.resolves({ ok: true, json: () => Promise.resolve(resp) });
+
+ clock.tick(THIRTY_MINUTES + 1);
+ await feed.loadLayout(feed.store.dispatch);
+
+ assert.calledOnce(fetchStub);
+ assert.equal(feed.cache.set.firstCall.args[0], "layout");
+ assert.deepEqual(feed.cache.set.firstCall.args[1].layout, resp.layout);
+ });
+ it("should use the cached data and not fetch if the cached data is less than 30 mins old", async () => {
+ const fakeCache = {
+ layout: { layout: ["hello"], lastUpdated: Date.now() },
+ };
+
+ sandbox.stub(feed.cache, "get").returns(Promise.resolve(fakeCache));
+ sandbox.stub(feed.cache, "set").returns(Promise.resolve());
+
+ clock.tick(THIRTY_MINUTES - 1);
+ await feed.loadLayout(feed.store.dispatch);
+
+ assert.notCalled(fetchStub);
+ assert.notCalled(feed.cache.set);
+ });
+ it("should set spocs_endpoint from layout", async () => {
+ const resp = { layout: ["foo", "bar"], spocs: { url: "foo.com" } };
+ const fakeCache = {};
+ sandbox.stub(feed.cache, "get").returns(Promise.resolve(fakeCache));
+ sandbox.stub(feed.cache, "set").returns(Promise.resolve());
+
+ fetchStub.resolves({ ok: true, json: () => Promise.resolve(resp) });
+
+ await feed.loadLayout(feed.store.dispatch);
+
+ assert.equal(
+ feed.store.getState().DiscoveryStream.spocs.spocs_endpoint,
+ "foo.com"
+ );
+ });
+ it("should use local layout with hardcoded_layout being true", async () => {
+ feed.config.hardcoded_layout = true;
+ sandbox.stub(feed, "fetchLayout").returns(Promise.resolve(""));
+
+ await feed.loadLayout(feed.store.dispatch);
+
+ assert.notCalled(feed.fetchLayout);
+ assert.equal(
+ feed.store.getState().DiscoveryStream.spocs.spocs_endpoint,
+ "https://spocs.getpocket.com/spocs"
+ );
+ });
+ it("should use local basic layout with hardcoded_layout and hardcoded_basic_layout being true", async () => {
+ feed.config.hardcoded_layout = true;
+ feed.config.hardcoded_basic_layout = true;
+ sandbox.stub(feed, "fetchLayout").returns(Promise.resolve(""));
+
+ await feed.loadLayout(feed.store.dispatch);
+
+ assert.notCalled(feed.fetchLayout);
+ assert.equal(
+ feed.store.getState().DiscoveryStream.spocs.spocs_endpoint,
+ "https://spocs.getpocket.com/spocs"
+ );
+ const { layout } = feed.store.getState().DiscoveryStream;
+ assert.equal(layout[0].components[3].properties.items, 3);
+ });
+ it("should use 1 row layout if specified", async () => {
+ feed.config.hardcoded_layout = true;
+ feed.store = createStore(combineReducers(reducers), {
+ Prefs: {
+ values: {
+ [CONFIG_PREF_NAME]: JSON.stringify({
+ enabled: true,
+ show_spocs: false,
+ layout_endpoint: DUMMY_ENDPOINT,
+ }),
+ [ENDPOINTS_PREF_NAME]: DUMMY_ENDPOINT,
+ "discoverystream.enabled": true,
+ "discoverystream.region-basic-layout": true,
+ },
+ },
+ });
+ sandbox.stub(feed, "fetchLayout").returns(Promise.resolve(""));
+
+ await feed.loadLayout(feed.store.dispatch);
+
+ const { layout } = feed.store.getState().DiscoveryStream;
+ assert.equal(layout[0].components[3].properties.items, 3);
+ });
+ it("should use 7 row layout if specified", async () => {
+ feed.config.hardcoded_layout = true;
+ feed.store = createStore(combineReducers(reducers), {
+ Prefs: {
+ values: {
+ [CONFIG_PREF_NAME]: JSON.stringify({
+ enabled: true,
+ show_spocs: false,
+ layout_endpoint: DUMMY_ENDPOINT,
+ }),
+ [ENDPOINTS_PREF_NAME]: DUMMY_ENDPOINT,
+ "discoverystream.enabled": true,
+ "discoverystream.region-basic-layout": false,
+ },
+ },
+ });
+ sandbox.stub(feed, "fetchLayout").returns(Promise.resolve(""));
+
+ await feed.loadLayout(feed.store.dispatch);
+
+ const { layout } = feed.store.getState().DiscoveryStream;
+ assert.equal(layout[0].components[3].properties.items, 21);
+ });
+ it("should use new spocs endpoint if in the config", async () => {
+ feed.config.spocs_endpoint = "https://spocs.getpocket.com/spocs2";
+
+ await feed.loadLayout(feed.store.dispatch);
+
+ assert.equal(
+ feed.store.getState().DiscoveryStream.spocs.spocs_endpoint,
+ "https://spocs.getpocket.com/spocs2"
+ );
+ });
+ it("should use local basic layout with hardcoded_layout and FF pref hardcoded_basic_layout", async () => {
+ feed.config.hardcoded_layout = true;
+ feed.store = createStore(combineReducers(reducers), {
+ Prefs: {
+ values: {
+ [CONFIG_PREF_NAME]: JSON.stringify({
+ enabled: false,
+ show_spocs: false,
+ layout_endpoint: DUMMY_ENDPOINT,
+ }),
+ [ENDPOINTS_PREF_NAME]: DUMMY_ENDPOINT,
+ "discoverystream.enabled": true,
+ "discoverystream.hardcoded-basic-layout": true,
+ },
+ },
+ });
+
+ sandbox.stub(feed, "fetchLayout").returns(Promise.resolve(""));
+
+ await feed.loadLayout(feed.store.dispatch);
+
+ assert.notCalled(feed.fetchLayout);
+ assert.equal(
+ feed.store.getState().DiscoveryStream.spocs.spocs_endpoint,
+ "https://spocs.getpocket.com/spocs"
+ );
+ const { layout } = feed.store.getState().DiscoveryStream;
+ assert.equal(layout[0].components[3].properties.items, 3);
+ });
+ it("should use new spocs endpoint if in a FF pref", async () => {
+ feed.store = createStore(combineReducers(reducers), {
+ Prefs: {
+ values: {
+ [CONFIG_PREF_NAME]: JSON.stringify({
+ enabled: false,
+ show_spocs: false,
+ layout_endpoint: DUMMY_ENDPOINT,
+ }),
+ [ENDPOINTS_PREF_NAME]: DUMMY_ENDPOINT,
+ "discoverystream.enabled": true,
+ "discoverystream.spocs-endpoint":
+ "https://spocs.getpocket.com/spocs2",
+ },
+ },
+ });
+
+ await feed.loadLayout(feed.store.dispatch);
+
+ assert.equal(
+ feed.store.getState().DiscoveryStream.spocs.spocs_endpoint,
+ "https://spocs.getpocket.com/spocs2"
+ );
+ });
+ it("should fetch local layout for invalid layout endpoint or when fetch layout fails", async () => {
+ feed.config.hardcoded_layout = false;
+ fetchStub.resolves({ ok: false });
+
+ await feed.loadLayout(feed.store.dispatch, true);
+
+ assert.calledOnce(fetchStub);
+ assert.equal(
+ feed.store.getState().DiscoveryStream.spocs.spocs_endpoint,
+ "https://spocs.getpocket.com/spocs"
+ );
+ });
+ });
+
+ describe("#updatePlacements", () => {
+ it("should fire update placements without dupes with updatePlacements", () => {
+ sandbox.spy(feed.store, "dispatch");
+ const fakeComponents = {
+ components: [
+ { placement: { name: "first" } },
+ { placement: { name: "second" } },
+ ],
+ };
+ const fakeLayout = [fakeComponents];
+
+ feed.updatePlacements(feed.store.dispatch, fakeLayout);
+
+ assert.calledOnce(feed.store.dispatch);
+ assert.calledWith(feed.store.dispatch, {
+ type: "DISCOVERY_STREAM_SPOCS_PLACEMENTS",
+ data: { placements: [{ name: "first" }, { name: "second" }] },
+ meta: { isStartup: false },
+ });
+ });
+ it("should fire update placements from loadLayout", async () => {
+ sandbox.spy(feed, "updatePlacements");
+
+ await feed.loadLayout(feed.store.dispatch);
+
+ assert.calledOnce(feed.updatePlacements);
+ });
+ });
+
+ describe("#placementsForEach", () => {
+ it("should forEach through placements", () => {
+ const fakeComponents = {
+ components: [
+ { placement: { name: "first" } },
+ { placement: { name: "second" } },
+ ],
+ };
+ const fakeLayout = [fakeComponents];
+ feed.updatePlacements(feed.store.dispatch, fakeLayout);
+ let items = [];
+
+ feed.placementsForEach(item => items.push(item.name));
+
+ assert.deepEqual(items, ["first", "second"]);
+ });
+ it("should forEach through placements for just spocs if no placements exist", () => {
+ let items = [];
+
+ feed.placementsForEach(item => items.push(item.name));
+
+ assert.deepEqual(items, ["spocs"]);
+ });
+ });
+
+ describe("#loadLayoutEndPointUsingPref", () => {
+ it("should return endpoint if valid key", async () => {
+ const endpoint = feed.finalLayoutEndpoint(
+ "https://somedomain.org/stories?consumer_key=$apiKey",
+ "test_key_val"
+ );
+ assert.equal(
+ "https://somedomain.org/stories?consumer_key=test_key_val",
+ endpoint
+ );
+ });
+
+ it("should throw error if key is empty", async () => {
+ assert.throws(() => {
+ feed.finalLayoutEndpoint(
+ "https://somedomain.org/stories?consumer_key=$apiKey",
+ ""
+ );
+ });
+ });
+
+ it("should return url if $apiKey is missing in layout_endpoint", async () => {
+ const endpoint = feed.finalLayoutEndpoint(
+ "https://somedomain.org/stories?consumer_key=",
+ "test_key_val"
+ );
+ assert.equal("https://somedomain.org/stories?consumer_key=", endpoint);
+ });
+
+ it("should update config layout_endpoint based on api_key_pref value", async () => {
+ feed.store.getState = () => ({
+ Prefs: {
+ values: {
+ [CONFIG_PREF_NAME]: JSON.stringify({
+ api_key_pref: "test_api_key_pref",
+ enabled: true,
+ layout_endpoint:
+ "https://somedomain.org/stories?consumer_key=$apiKey",
+ }),
+ },
+ },
+ });
+ sandbox
+ .stub(global.Services.prefs, "getCharPref")
+ .returns("test_api_key_val");
+ assert.equal(
+ "https://somedomain.org/stories?consumer_key=test_api_key_val",
+ feed.config.layout_endpoint
+ );
+ });
+
+ it("should not update config layout_endpoint if api_key_pref missing", async () => {
+ feed.store.getState = () => ({
+ Prefs: {
+ values: {
+ [CONFIG_PREF_NAME]: JSON.stringify({
+ enabled: true,
+ layout_endpoint:
+ "https://somedomain.org/stories?consumer_key=1234",
+ }),
+ },
+ },
+ });
+ sandbox
+ .stub(global.Services.prefs, "getCharPref")
+ .returns("test_api_key_val");
+ assert.notCalled(global.Services.prefs.getCharPref);
+ assert.equal(
+ "https://somedomain.org/stories?consumer_key=1234",
+ feed.config.layout_endpoint
+ );
+ });
+
+ it("should not set config layout_endpoint if layout_endpoint missing in prefs", async () => {
+ feed.store.getState = () => ({
+ Prefs: {
+ values: {
+ [CONFIG_PREF_NAME]: JSON.stringify({
+ enabled: true,
+ }),
+ },
+ },
+ });
+ sandbox
+ .stub(global.Services.prefs, "getCharPref")
+ .returns("test_api_key_val");
+ assert.notCalled(global.Services.prefs.getCharPref);
+ assert.isUndefined(feed.config.layout_endpoint);
+ });
+ });
+
+ describe("#loadComponentFeeds", () => {
+ let fakeCache;
+ let fakeDiscoveryStream;
+ beforeEach(() => {
+ fakeDiscoveryStream = {
+ DiscoveryStream: {
+ layout: [
+ { components: [{ feed: { url: "foo.com" } }] },
+ { components: [{}] },
+ {},
+ ],
+ },
+ };
+ fakeCache = {};
+ sandbox.stub(feed.store, "getState").returns(fakeDiscoveryStream);
+ sandbox.stub(feed.cache, "set").returns(Promise.resolve());
+ });
+
+ afterEach(() => {
+ sandbox.restore();
+ });
+
+ it("should not dispatch updates when layout is not defined", async () => {
+ fakeDiscoveryStream = {
+ DiscoveryStream: {},
+ };
+ feed.store.getState.returns(fakeDiscoveryStream);
+ sandbox.spy(feed.store, "dispatch");
+
+ await feed.loadComponentFeeds(feed.store.dispatch);
+
+ assert.notCalled(feed.store.dispatch);
+ });
+
+ it("should populate feeds cache", async () => {
+ fakeCache = {
+ feeds: { "foo.com": { lastUpdated: Date.now(), data: "data" } },
+ };
+ sandbox.stub(feed.cache, "get").returns(Promise.resolve(fakeCache));
+
+ await feed.loadComponentFeeds(feed.store.dispatch);
+
+ assert.calledWith(feed.cache.set, "feeds", {
+ "foo.com": { data: "data", lastUpdated: 0 },
+ });
+ });
+
+ it("should send feed update events with new feed data", async () => {
+ sandbox.stub(feed.cache, "get").returns(Promise.resolve(fakeCache));
+ sandbox.spy(feed.store, "dispatch");
+ feed._prefCache = {
+ config: {
+ api_key_pref: "",
+ },
+ };
+
+ await feed.loadComponentFeeds(feed.store.dispatch);
+
+ assert.calledWith(feed.store.dispatch.firstCall, {
+ type: at.DISCOVERY_STREAM_FEED_UPDATE,
+ data: { feed: { data: { status: "failed" } }, url: "foo.com" },
+ meta: { isStartup: false },
+ });
+ assert.calledWith(feed.store.dispatch.secondCall, {
+ type: at.DISCOVERY_STREAM_FEEDS_UPDATE,
+ meta: { isStartup: false },
+ });
+ });
+
+ it("should return number of promises equal to unique urls", async () => {
+ sandbox.stub(feed.cache, "get").returns(Promise.resolve(fakeCache));
+ sandbox.stub(global.Promise, "all").resolves();
+ fakeDiscoveryStream = {
+ DiscoveryStream: {
+ layout: [
+ {
+ components: [
+ { feed: { url: "foo.com" } },
+ { feed: { url: "bar.com" } },
+ ],
+ },
+ { components: [{ feed: { url: "foo.com" } }] },
+ {},
+ { components: [{ feed: { url: "baz.com" } }] },
+ ],
+ },
+ };
+ feed.store.getState.returns(fakeDiscoveryStream);
+
+ await feed.loadComponentFeeds(feed.store.dispatch);
+
+ assert.calledOnce(global.Promise.all);
+ const { args } = global.Promise.all.firstCall;
+ assert.equal(args[0].length, 3);
+ });
+ });
+
+ describe("#getComponentFeed", () => {
+ it("should fetch fresh feed data if cache is empty", async () => {
+ const fakeCache = {};
+ sandbox.stub(feed.cache, "get").returns(Promise.resolve(fakeCache));
+ sandbox.stub(feed, "rotate").callsFake(val => val);
+ sandbox
+ .stub(feed, "scoreItems")
+ .callsFake(val => ({ data: val, filtered: [] }));
+ sandbox.stub(feed, "fetchFromEndpoint").resolves({
+ recommendations: "data",
+ settings: {
+ recsExpireTime: 1,
+ },
+ });
+
+ const feedResp = await feed.getComponentFeed("foo.com");
+
+ assert.equal(feedResp.data.recommendations, "data");
+ });
+ it("should fetch fresh feed data if cache is old", async () => {
+ const fakeCache = { feeds: { "foo.com": { lastUpdated: Date.now() } } };
+ sandbox.stub(feed.cache, "get").returns(Promise.resolve(fakeCache));
+ sandbox.stub(feed, "fetchFromEndpoint").resolves({
+ recommendations: "data",
+ settings: {
+ recsExpireTime: 1,
+ },
+ });
+ sandbox.stub(feed, "rotate").callsFake(val => val);
+ sandbox
+ .stub(feed, "scoreItems")
+ .callsFake(val => ({ data: val, filtered: [] }));
+ clock.tick(THIRTY_MINUTES + 1);
+
+ const feedResp = await feed.getComponentFeed("foo.com");
+
+ assert.equal(feedResp.data.recommendations, "data");
+ });
+ it("should return feed data from cache if it is fresh", async () => {
+ const fakeCache = {
+ feeds: { "foo.com": { lastUpdated: Date.now(), data: "data" } },
+ };
+ sandbox.stub(feed.cache, "get").resolves(fakeCache);
+ sandbox.stub(feed, "fetchFromEndpoint").resolves("old data");
+ clock.tick(THIRTY_MINUTES - 1);
+
+ const feedResp = await feed.getComponentFeed("foo.com");
+
+ assert.equal(feedResp.data, "data");
+ });
+ it("should return null if no response was received", async () => {
+ sandbox.stub(feed, "fetchFromEndpoint").resolves(null);
+
+ const feedResp = await feed.getComponentFeed("foo.com");
+
+ assert.deepEqual(feedResp, { data: { status: "failed" } });
+ });
+ });
+
+ describe("#personalizationVersionOverride", () => {
+ it("should dispatch setPref", async () => {
+ sandbox.spy(feed.store, "dispatch");
+ feed.store.getState = () => ({
+ Prefs: {
+ values: {
+ "discoverystream.personalization.version": 2,
+ },
+ },
+ });
+
+ feed.personalizationVersionOverride(false);
+
+ assert.calledWithMatch(feed.store.dispatch, {
+ data: {
+ name: "discoverystream.personalization.overrideVersion",
+ value: 1,
+ },
+ type: at.SET_PREF,
+ });
+ });
+ it("should dispatch CLEAR_PREF", async () => {
+ sandbox.spy(feed.store, "dispatch");
+ feed.store.getState = () => ({
+ Prefs: {
+ values: {
+ "discoverystream.personalization.version": 2,
+ "discoverystream.personalization.overrideVersion": 1,
+ },
+ },
+ });
+
+ feed.personalizationVersionOverride(true);
+
+ assert.calledWithMatch(feed.store.dispatch, {
+ data: {
+ name: "discoverystream.personalization.overrideVersion",
+ },
+ type: at.CLEAR_PREF,
+ });
+ });
+ });
+
+ describe("#loadSpocs", () => {
+ beforeEach(() => {
+ feed._prefCache = {
+ config: {
+ api_key_pref: "",
+ },
+ };
+ Object.defineProperty(feed, "showSpocs", { get: () => true });
+ });
+ it("should not fetch or update cache if no spocs endpoint is defined", async () => {
+ feed.store.dispatch(
+ ac.BroadcastToContent({
+ type: at.DISCOVERY_STREAM_SPOCS_ENDPOINT,
+ data: "",
+ })
+ );
+
+ sandbox.spy(feed.cache, "set");
+
+ await feed.loadSpocs(feed.store.dispatch);
+
+ assert.notCalled(global.fetch);
+ assert.notCalled(feed.cache.set);
+ });
+ it("should fetch fresh spocs data if cache is empty", async () => {
+ sandbox.stub(feed.cache, "get").returns(Promise.resolve());
+ sandbox.stub(feed, "fetchFromEndpoint").resolves({ placement: "data" });
+ sandbox.stub(feed.cache, "set").returns(Promise.resolve());
+
+ await feed.loadSpocs(feed.store.dispatch);
+
+ assert.calledWith(feed.cache.set, "spocs", {
+ spocs: { placement: "data" },
+ lastUpdated: 0,
+ });
+ assert.equal(
+ feed.store.getState().DiscoveryStream.spocs.data.placement,
+ "data"
+ );
+ });
+ it("should fetch fresh data if cache is old", async () => {
+ const cachedSpoc = {
+ spocs: { placement: "old" },
+ lastUpdated: Date.now(),
+ };
+ const cachedData = { spocs: cachedSpoc };
+ sandbox.stub(feed.cache, "get").returns(Promise.resolve(cachedData));
+ sandbox.stub(feed, "fetchFromEndpoint").resolves({ placement: "new" });
+ sandbox.stub(feed.cache, "set").returns(Promise.resolve());
+ clock.tick(THIRTY_MINUTES + 1);
+
+ await feed.loadSpocs(feed.store.dispatch);
+
+ assert.equal(
+ feed.store.getState().DiscoveryStream.spocs.data.placement,
+ "new"
+ );
+ });
+ it("should return spoc data from cache if it is fresh", async () => {
+ const cachedSpoc = {
+ spocs: { placement: "old" },
+ lastUpdated: Date.now(),
+ };
+ const cachedData = { spocs: cachedSpoc };
+ sandbox.stub(feed.cache, "get").returns(Promise.resolve(cachedData));
+ sandbox.stub(feed, "fetchFromEndpoint").resolves({ placement: "new" });
+ sandbox.stub(feed.cache, "set").returns(Promise.resolve());
+ clock.tick(THIRTY_MINUTES - 1);
+
+ await feed.loadSpocs(feed.store.dispatch);
+
+ assert.equal(
+ feed.store.getState().DiscoveryStream.spocs.data.placement,
+ "old"
+ );
+ });
+ it("should properly transform spocs using placements", async () => {
+ sandbox.stub(feed.cache, "get").returns(Promise.resolve());
+ sandbox
+ .stub(feed, "fetchFromEndpoint")
+ .resolves({ spocs: { items: [{ id: "data" }] } });
+ sandbox.stub(feed.cache, "set").returns(Promise.resolve());
+
+ await feed.loadSpocs(feed.store.dispatch);
+
+ assert.calledWith(feed.cache.set, "spocs", {
+ spocs: {
+ spocs: {
+ context: "",
+ title: "",
+ sponsor: "",
+ sponsored_by_override: undefined,
+ items: [{ id: "data", min_score: 0, score: 1 }],
+ },
+ },
+ lastUpdated: 0,
+ });
+
+ assert.deepEqual(
+ feed.store.getState().DiscoveryStream.spocs.data.spocs.items[0],
+ { id: "data", min_score: 0, score: 1 }
+ );
+ });
+ it("should normalizeSpocsItems for older spoc data", async () => {
+ sandbox.stub(feed.cache, "get").returns(Promise.resolve());
+ sandbox
+ .stub(feed, "fetchFromEndpoint")
+ .resolves({ spocs: [{ id: "data" }] });
+ sandbox.stub(feed.cache, "set").returns(Promise.resolve());
+
+ await feed.loadSpocs(feed.store.dispatch);
+
+ assert.deepEqual(
+ feed.store.getState().DiscoveryStream.spocs.data.spocs.items[0],
+ { id: "data", min_score: 0, score: 1 }
+ );
+ });
+ it("should call personalizationVersionOverride with feature_flags", async () => {
+ sandbox.stub(feed.cache, "get").returns(Promise.resolve());
+ sandbox.stub(feed, "personalizationVersionOverride").returns();
+ sandbox
+ .stub(feed, "fetchFromEndpoint")
+ .resolves({ settings: { feature_flags: {} }, spocs: [{ id: "data" }] });
+ sandbox.stub(feed.cache, "set").returns(Promise.resolve());
+
+ await feed.loadSpocs(feed.store.dispatch);
+
+ assert.calledOnce(feed.personalizationVersionOverride);
+ });
+ it("should return expected data if normalizeSpocsItems returns no spoc data", async () => {
+ sandbox.stub(feed.cache, "get").returns(Promise.resolve());
+ sandbox
+ .stub(feed, "fetchFromEndpoint")
+ .resolves({ placement1: [{ id: "data" }], placement2: [] });
+ sandbox.stub(feed.cache, "set").returns(Promise.resolve());
+
+ const fakeComponents = {
+ components: [
+ { placement: { name: "placement1" } },
+ { placement: { name: "placement2" } },
+ ],
+ };
+ feed.updatePlacements(feed.store.dispatch, [fakeComponents]);
+
+ await feed.loadSpocs(feed.store.dispatch);
+
+ assert.deepEqual(feed.store.getState().DiscoveryStream.spocs.data, {
+ placement1: {
+ title: "",
+ context: "",
+ sponsor: "",
+ sponsored_by_override: undefined,
+ items: [{ id: "data", score: 1, min_score: 0 }],
+ },
+ placement2: {
+ title: "",
+ context: "",
+ items: [],
+ },
+ });
+ });
+ it("should use title and context on spoc data", async () => {
+ sandbox.stub(feed.cache, "get").returns(Promise.resolve());
+ sandbox.stub(feed, "fetchFromEndpoint").resolves({
+ placement1: {
+ title: "title",
+ context: "context",
+ sponsor: "",
+ sponsored_by_override: undefined,
+ items: [{ id: "data" }],
+ },
+ });
+ sandbox.stub(feed.cache, "set").returns(Promise.resolve());
+
+ const fakeComponents = {
+ components: [{ placement: { name: "placement1" } }],
+ };
+ feed.updatePlacements(feed.store.dispatch, [fakeComponents]);
+
+ await feed.loadSpocs(feed.store.dispatch);
+
+ assert.deepEqual(feed.store.getState().DiscoveryStream.spocs.data, {
+ placement1: {
+ title: "title",
+ context: "context",
+ sponsor: "",
+ sponsored_by_override: undefined,
+ items: [{ id: "data", score: 1, min_score: 0 }],
+ },
+ });
+ });
+ });
+
+ describe("#normalizeSpocsItems", () => {
+ it("should return correct data if new data passed in", async () => {
+ const spocs = {
+ title: "title",
+ context: "context",
+ sponsor: "sponsor",
+ sponsored_by_override: "override",
+ items: [{ id: "id" }],
+ };
+ const result = feed.normalizeSpocsItems(spocs);
+ assert.deepEqual(result, spocs);
+ });
+ it("should return normalized data if new data passed in without title or context", async () => {
+ const spocs = {
+ items: [{ id: "id" }],
+ };
+ const result = feed.normalizeSpocsItems(spocs);
+ assert.deepEqual(result, {
+ title: "",
+ context: "",
+ sponsor: "",
+ sponsored_by_override: undefined,
+ items: [{ id: "id" }],
+ });
+ });
+ it("should return normalized data if old data passed in", async () => {
+ const spocs = [{ id: "id" }];
+ const result = feed.normalizeSpocsItems(spocs);
+ assert.deepEqual(result, {
+ title: "",
+ context: "",
+ sponsor: "",
+ sponsored_by_override: undefined,
+ items: [{ id: "id" }],
+ });
+ });
+ });
+
+ describe("#showSpocs", () => {
+ it("should return false from showSpocs if user pref showSponsored is false", async () => {
+ feed.store.getState = () => ({
+ Prefs: { values: { showSponsored: false } },
+ });
+ Object.defineProperty(feed, "config", {
+ get: () => ({ show_spocs: true }),
+ });
+
+ assert.isFalse(feed.showSpocs);
+ });
+ it("should return false from showSpocs if DiscoveryStream pref show_spocs is false", async () => {
+ feed.store.getState = () => ({
+ Prefs: { values: { showSponsored: true } },
+ });
+ Object.defineProperty(feed, "config", {
+ get: () => ({ show_spocs: false }),
+ });
+
+ assert.isFalse(feed.showSpocs);
+ });
+ it("should return true from showSpocs if both prefs are true", async () => {
+ feed.store.getState = () => ({
+ Prefs: { values: { showSponsored: true } },
+ });
+ Object.defineProperty(feed, "config", {
+ get: () => ({ show_spocs: true }),
+ });
+
+ assert.isTrue(feed.showSpocs);
+ });
+ });
+
+ describe("#clearSpocs", () => {
+ it("should not fail with no endpoint", async () => {
+ sandbox.stub(feed.store, "getState").returns({
+ Prefs: {
+ values: { "discoverystream.endpointSpocsClear": null },
+ },
+ });
+ sandbox.stub(feed, "fetchFromEndpoint").resolves(null);
+
+ await feed.clearSpocs();
+
+ assert.notCalled(feed.fetchFromEndpoint);
+ });
+ it("should call DELETE with endpoint", async () => {
+ sandbox.stub(feed.store, "getState").returns({
+ Prefs: {
+ values: {
+ "discoverystream.endpointSpocsClear": "https://spocs/user",
+ },
+ },
+ });
+ sandbox.stub(feed, "fetchFromEndpoint").resolves(null);
+ feed._impressionId = "1234";
+
+ await feed.clearSpocs();
+
+ assert.equal(
+ feed.fetchFromEndpoint.firstCall.args[0],
+ "https://spocs/user"
+ );
+ assert.equal(feed.fetchFromEndpoint.firstCall.args[1].method, "DELETE");
+ assert.equal(
+ feed.fetchFromEndpoint.firstCall.args[1].body,
+ '{"pocket_id":"1234"}'
+ );
+ });
+ });
+
+ describe("#rotate", () => {
+ it("should move seen first story to the back of the response", () => {
+ const recsExpireTime = 5600;
+ const feedResponse = {
+ recommendations: [
+ {
+ id: "first",
+ },
+ {
+ id: "second",
+ },
+ {
+ id: "third",
+ },
+ {
+ id: "fourth",
+ },
+ ],
+ settings: {
+ recsExpireTime,
+ },
+ };
+ const fakeImpressions = {
+ first: Date.now() - recsExpireTime * 1000,
+ third: Date.now(),
+ };
+ sandbox.stub(feed, "readDataPref").returns(fakeImpressions);
+
+ const result = feed.rotate(
+ feedResponse.recommendations,
+ feedResponse.settings.recsExpireTime
+ );
+
+ assert.equal(result[3].id, "first");
+ });
+ });
+
+ describe("#reset", () => {
+ it("should fire all teardown based functions", async () => {
+ sandbox.stub(global.Services.obs, "removeObserver").returns();
+
+ sandbox.stub(feed, "resetDataPrefs").returns();
+ sandbox.stub(feed, "resetCache").returns(Promise.resolve());
+ sandbox.stub(feed, "resetState").returns();
+
+ feed.affinityProvider = {
+ teardown: sandbox.stub().returns(),
+ };
+ feed.loaded = true;
+
+ await feed.reset();
+
+ assert.calledOnce(feed.resetDataPrefs);
+ assert.calledOnce(feed.resetCache);
+ assert.calledOnce(feed.resetState);
+ assert.calledOnce(global.Services.obs.removeObserver);
+ });
+ });
+
+ describe("#resetCache", () => {
+ it("should set .layout, .feeds .spocs and .affinities to {}", async () => {
+ sandbox.stub(feed.cache, "set").returns(Promise.resolve());
+
+ await feed.resetCache();
+
+ assert.callCount(feed.cache.set, 4);
+ const firstCall = feed.cache.set.getCall(0);
+ const secondCall = feed.cache.set.getCall(1);
+ const thirdCall = feed.cache.set.getCall(2);
+ const fourthCall = feed.cache.set.getCall(3);
+ assert.deepEqual(firstCall.args, ["layout", {}]);
+ assert.deepEqual(secondCall.args, ["feeds", {}]);
+ assert.deepEqual(thirdCall.args, ["spocs", {}]);
+ assert.deepEqual(fourthCall.args, ["affinities", {}]);
+ });
+ });
+
+ describe("#scoreItems", () => {
+ it("should return initial data if spocs are empty", async () => {
+ const { data: result } = await feed.scoreItems([]);
+
+ assert.equal(result.length, 0);
+ });
+
+ it("should sort based on item_score", async () => {
+ const { data: result } = await feed.scoreItems([
+ { id: 2, flight_id: 2, item_score: 0.8, min_score: 0.1 },
+ { id: 3, flight_id: 3, item_score: 0.7, min_score: 0.1 },
+ { id: 1, flight_id: 1, item_score: 0.9, min_score: 0.1 },
+ ]);
+
+ assert.deepEqual(result, [
+ { id: 1, flight_id: 1, item_score: 0.9, score: 0.9, min_score: 0.1 },
+ { id: 2, flight_id: 2, item_score: 0.8, score: 0.8, min_score: 0.1 },
+ { id: 3, flight_id: 3, item_score: 0.7, score: 0.7, min_score: 0.1 },
+ ]);
+ });
+
+ it("should sort based on priority", async () => {
+ const { data: result } = await feed.scoreItems([
+ { id: 6, flight_id: 6, priority: 2, item_score: 0.7, min_score: 0.1 },
+ { id: 2, flight_id: 3, priority: 1, item_score: 0.2, min_score: 0.1 },
+ { id: 4, flight_id: 4, item_score: 0.6, min_score: 0.1 },
+ { id: 5, flight_id: 5, priority: 2, item_score: 0.8, min_score: 0.1 },
+ { id: 3, flight_id: 3, item_score: 0.8, min_score: 0.1 },
+ { id: 1, flight_id: 1, priority: 1, item_score: 0.3, min_score: 0.1 },
+ ]);
+
+ assert.deepEqual(result, [
+ {
+ id: 1,
+ flight_id: 1,
+ priority: 1,
+ score: 0.3,
+ item_score: 0.3,
+ min_score: 0.1,
+ },
+ {
+ id: 2,
+ flight_id: 3,
+ priority: 1,
+ score: 0.2,
+ item_score: 0.2,
+ min_score: 0.1,
+ },
+ {
+ id: 5,
+ flight_id: 5,
+ priority: 2,
+ score: 0.8,
+ item_score: 0.8,
+ min_score: 0.1,
+ },
+ {
+ id: 6,
+ flight_id: 6,
+ priority: 2,
+ score: 0.7,
+ item_score: 0.7,
+ min_score: 0.1,
+ },
+ { id: 3, flight_id: 3, item_score: 0.8, score: 0.8, min_score: 0.1 },
+ { id: 4, flight_id: 4, item_score: 0.6, score: 0.6, min_score: 0.1 },
+ ]);
+ });
+
+ it("should remove items with scores lower than min_score", async () => {
+ const { data: result } = await feed.scoreItems([
+ { id: 2, flight_id: 2, item_score: 0.8, min_score: 0.9 },
+ { id: 3, flight_id: 3, item_score: 0.7, min_score: 0.7 },
+ { id: 1, flight_id: 1, item_score: 0.9, min_score: 0.8 },
+ ]);
+
+ assert.deepEqual(result, [
+ { id: 1, flight_id: 1, item_score: 0.9, score: 0.9, min_score: 0.8 },
+ { id: 3, flight_id: 3, item_score: 0.7, score: 0.7, min_score: 0.7 },
+ ]);
+ });
+
+ it("should add a score prop to spocs", async () => {
+ const { data: result } = await feed.scoreItems([
+ { flight_id: 1, item_score: 0.9, min_score: 0.1 },
+ ]);
+
+ assert.equal(result[0].score, 0.9);
+ });
+ it("should score items using item_score and min_score", async () => {
+ const { data: result } = await feed.scoreItems([
+ { item_score: 0.8, min_score: 0.1 },
+ { item_score: 0.5, min_score: 0.6 },
+ { item_score: 0.7, min_score: 0.1 },
+ { item_score: 0.9, min_score: 0.1 },
+ ]);
+ assert.deepEqual(result, [
+ { item_score: 0.9, score: 0.9, min_score: 0.1 },
+ { item_score: 0.8, score: 0.8, min_score: 0.1 },
+ { item_score: 0.7, score: 0.7, min_score: 0.1 },
+ ]);
+ });
+ });
+
+ describe("#filterBlocked", () => {
+ it("should return initial data if spocs are empty", () => {
+ const { data: result } = feed.filterBlocked([]);
+
+ assert.equal(result.length, 0);
+ });
+ it("should return initial data if links are not blocked", () => {
+ const { data: result } = feed.filterBlocked([
+ { url: "https://foo.com" },
+ { url: "test.com" },
+ ]);
+ assert.equal(result.length, 2);
+ });
+ it("should return initial recommendations data if links are not blocked", () => {
+ const { data: result } = feed.filterBlocked([
+ { url: "https://foo.com" },
+ { url: "test.com" },
+ ]);
+ assert.equal(result.length, 2);
+ });
+ it("filterRecommendations based on blockedlist by passing feed data", () => {
+ fakeNewTabUtils.blockedLinks.links = [{ url: "https://foo.com" }];
+ fakeNewTabUtils.blockedLinks.isBlocked = site =>
+ fakeNewTabUtils.blockedLinks.links[0].url === site.url;
+
+ const result = feed.filterRecommendations({
+ lastUpdated: 4,
+ data: {
+ recommendations: [{ url: "https://foo.com" }, { url: "test.com" }],
+ },
+ });
+
+ assert.equal(result.lastUpdated, 4);
+ assert.lengthOf(result.data.recommendations, 1);
+ assert.equal(result.data.recommendations[0].url, "test.com");
+ assert.notInclude(
+ result.data.recommendations,
+ fakeNewTabUtils.blockedLinks.links[0]
+ );
+ });
+ });
+
+ describe("#frequencyCapSpocs", () => {
+ it("should return filtered out spocs based on frequency caps", () => {
+ const fakeSpocs = [
+ {
+ id: 1,
+ flight_id: "seen",
+ caps: {
+ lifetime: 3,
+ flight: {
+ count: 1,
+ period: 1,
+ },
+ },
+ },
+ {
+ id: 2,
+ flight_id: "not-seen",
+ caps: {
+ lifetime: 3,
+ flight: {
+ count: 1,
+ period: 1,
+ },
+ },
+ },
+ ];
+ const fakeImpressions = {
+ seen: [Date.now() - 1],
+ };
+ sandbox.stub(feed, "readDataPref").returns(fakeImpressions);
+
+ const { data: result, filtered } = feed.frequencyCapSpocs(fakeSpocs);
+
+ assert.equal(result.length, 1);
+ assert.equal(result[0].flight_id, "not-seen");
+ assert.deepEqual(filtered, [fakeSpocs[0]]);
+ });
+ it("should return simple structure and do nothing with no spocs", () => {
+ const { data: result, filtered } = feed.frequencyCapSpocs([]);
+
+ assert.equal(result.length, 0);
+ assert.equal(filtered.length, 0);
+ });
+ });
+
+ describe("#migrateFlightId", () => {
+ it("should migrate campaign to flight if no flight exists", () => {
+ const fakeSpocs = [
+ {
+ id: 1,
+ campaign_id: "campaign",
+ caps: {
+ lifetime: 3,
+ campaign: {
+ count: 1,
+ period: 1,
+ },
+ },
+ },
+ ];
+ const { data: result } = feed.migrateFlightId(fakeSpocs);
+
+ assert.deepEqual(result[0], {
+ id: 1,
+ flight_id: "campaign",
+ campaign_id: "campaign",
+ caps: {
+ lifetime: 3,
+ flight: {
+ count: 1,
+ period: 1,
+ },
+ campaign: {
+ count: 1,
+ period: 1,
+ },
+ },
+ });
+ });
+ it("should not migrate campaign to flight if caps or id don't exist", () => {
+ const fakeSpocs = [{ id: 1 }];
+ const { data: result } = feed.migrateFlightId(fakeSpocs);
+
+ assert.deepEqual(result[0], { id: 1 });
+ });
+ it("should return simple structure and do nothing with no spocs", () => {
+ const { data: result } = feed.migrateFlightId([]);
+
+ assert.equal(result.length, 0);
+ });
+ });
+
+ describe("#isBelowFrequencyCap", () => {
+ it("should return true if there are no flight impressions", () => {
+ const fakeImpressions = {
+ seen: [Date.now() - 1],
+ };
+ const fakeSpoc = {
+ flight_id: "not-seen",
+ caps: {
+ lifetime: 3,
+ flight: {
+ count: 1,
+ period: 1,
+ },
+ },
+ };
+
+ const result = feed.isBelowFrequencyCap(fakeImpressions, fakeSpoc);
+
+ assert.isTrue(result);
+ });
+ it("should return true if there are no flight caps", () => {
+ const fakeImpressions = {
+ seen: [Date.now() - 1],
+ };
+ const fakeSpoc = {
+ flight_id: "seen",
+ caps: {
+ lifetime: 3,
+ },
+ };
+
+ const result = feed.isBelowFrequencyCap(fakeImpressions, fakeSpoc);
+
+ assert.isTrue(result);
+ });
+
+ it("should return false if lifetime cap is hit", () => {
+ const fakeImpressions = {
+ seen: [Date.now() - 1],
+ };
+ const fakeSpoc = {
+ flight_id: "seen",
+ caps: {
+ lifetime: 1,
+ flight: {
+ count: 3,
+ period: 1,
+ },
+ },
+ };
+
+ const result = feed.isBelowFrequencyCap(fakeImpressions, fakeSpoc);
+
+ assert.isFalse(result);
+ });
+
+ it("should return false if time based cap is hit", () => {
+ const fakeImpressions = {
+ seen: [Date.now() - 1],
+ };
+ const fakeSpoc = {
+ flight_id: "seen",
+ caps: {
+ lifetime: 3,
+ flight: {
+ count: 1,
+ period: 1,
+ },
+ },
+ };
+
+ const result = feed.isBelowFrequencyCap(fakeImpressions, fakeSpoc);
+
+ assert.isFalse(result);
+ });
+ });
+
+ describe("#retryFeed", () => {
+ it("should retry a feed fetch", async () => {
+ sandbox.stub(feed, "getComponentFeed").returns(Promise.resolve({}));
+ sandbox.stub(feed, "filterRecommendations").returns({});
+ sandbox.spy(feed.store, "dispatch");
+
+ await feed.retryFeed({ url: "https://feed.com" });
+
+ assert.calledOnce(feed.getComponentFeed);
+ assert.calledOnce(feed.filterRecommendations);
+ assert.calledOnce(feed.store.dispatch);
+ assert.equal(
+ feed.store.dispatch.firstCall.args[0].type,
+ "DISCOVERY_STREAM_FEED_UPDATE"
+ );
+ assert.deepEqual(feed.store.dispatch.firstCall.args[0].data, {
+ feed: {},
+ url: "https://feed.com",
+ });
+ });
+ });
+
+ describe("#recordFlightImpression", () => {
+ it("should return false if time based cap is hit", () => {
+ sandbox.stub(feed, "readDataPref").returns({});
+ sandbox.stub(feed, "writeDataPref").returns();
+
+ feed.recordFlightImpression("seen");
+
+ assert.calledWith(feed.writeDataPref, SPOC_IMPRESSION_TRACKING_PREF, {
+ seen: [0],
+ });
+ });
+ });
+
+ describe("#recordBlockFlightId", () => {
+ it("should call writeDataPref with new flight id added", () => {
+ sandbox.stub(feed, "readDataPref").returns({ "1234": 1 });
+ sandbox.stub(feed, "writeDataPref").returns();
+
+ feed.recordBlockFlightId("5678");
+
+ assert.calledOnce(feed.readDataPref);
+ assert.calledWith(feed.writeDataPref, "discoverystream.flight.blocks", {
+ "1234": 1,
+ "5678": 1,
+ });
+ });
+ });
+
+ describe("#cleanUpFlightImpressionPref", () => {
+ it("should remove flight-3 because it is no longer being used", async () => {
+ const fakeSpocs = {
+ spocs: {
+ items: [
+ {
+ flight_id: "flight-1",
+ caps: {
+ lifetime: 3,
+ flight: {
+ count: 1,
+ period: 1,
+ },
+ },
+ },
+ {
+ flight_id: "flight-2",
+ caps: {
+ lifetime: 3,
+ flight: {
+ count: 1,
+ period: 1,
+ },
+ },
+ },
+ ],
+ },
+ };
+ const fakeImpressions = {
+ "flight-2": [Date.now() - 1],
+ "flight-3": [Date.now() - 1],
+ };
+ sandbox.stub(feed, "readDataPref").returns(fakeImpressions);
+ sandbox.stub(feed, "writeDataPref").returns();
+
+ feed.cleanUpFlightImpressionPref(fakeSpocs);
+
+ assert.calledWith(feed.writeDataPref, SPOC_IMPRESSION_TRACKING_PREF, {
+ "flight-2": [-1],
+ });
+ });
+ });
+
+ describe("#recordTopRecImpressions", () => {
+ it("should add a rec id to the rec impression pref", () => {
+ sandbox.stub(feed, "readDataPref").returns({});
+ sandbox.stub(feed, "writeDataPref");
+
+ feed.recordTopRecImpressions("rec");
+
+ assert.calledWith(feed.writeDataPref, REC_IMPRESSION_TRACKING_PREF, {
+ rec: 0,
+ });
+ });
+ it("should not add an impression if it already exists", () => {
+ sandbox.stub(feed, "readDataPref").returns({ rec: 4 });
+ sandbox.stub(feed, "writeDataPref");
+
+ feed.recordTopRecImpressions("rec");
+
+ assert.notCalled(feed.writeDataPref);
+ });
+ });
+
+ describe("#cleanUpTopRecImpressionPref", () => {
+ it("should remove recs no longer being used", () => {
+ const newFeeds = {
+ "https://foo.com": {
+ data: {
+ recommendations: [
+ {
+ id: "rec1",
+ },
+ {
+ id: "rec2",
+ },
+ ],
+ },
+ },
+ "https://bar.com": {
+ data: {
+ recommendations: [
+ {
+ id: "rec3",
+ },
+ {
+ id: "rec4",
+ },
+ ],
+ },
+ },
+ };
+ const fakeImpressions = {
+ rec2: Date.now() - 1,
+ rec3: Date.now() - 1,
+ rec5: Date.now() - 1,
+ };
+ sandbox.stub(feed, "readDataPref").returns(fakeImpressions);
+ sandbox.stub(feed, "writeDataPref").returns();
+
+ feed.cleanUpTopRecImpressionPref(newFeeds);
+
+ assert.calledWith(feed.writeDataPref, REC_IMPRESSION_TRACKING_PREF, {
+ rec2: -1,
+ rec3: -1,
+ });
+ });
+ });
+
+ describe("#writeDataPref", () => {
+ it("should call Services.prefs.setStringPref", () => {
+ sandbox.spy(feed.store, "dispatch");
+ const fakeImpressions = {
+ foo: [Date.now() - 1],
+ bar: [Date.now() - 1],
+ };
+
+ feed.writeDataPref(SPOC_IMPRESSION_TRACKING_PREF, fakeImpressions);
+
+ assert.calledWithMatch(feed.store.dispatch, {
+ data: {
+ name: SPOC_IMPRESSION_TRACKING_PREF,
+ value: JSON.stringify(fakeImpressions),
+ },
+ type: at.SET_PREF,
+ });
+ });
+ });
+
+ describe("#addEndpointQuery", () => {
+ const url = "https://spocs.getpocket.com/spocs";
+
+ it("should return same url with no query", () => {
+ const result = feed.addEndpointQuery(url, "");
+ assert.equal(result, url);
+ });
+
+ it("should add multiple query params to standard url", () => {
+ const params = "?first=first&second=second";
+ const result = feed.addEndpointQuery(url, params);
+ assert.equal(result, url + params);
+ });
+
+ it("should add multiple query params to url with a query already", () => {
+ const params = "first=first&second=second";
+ const initialParams = "?zero=zero";
+ const result = feed.addEndpointQuery(
+ `${url}${initialParams}`,
+ `?${params}`
+ );
+ assert.equal(result, `${url}${initialParams}&${params}`);
+ });
+ });
+
+ describe("#readDataPref", () => {
+ it("should return what's in Services.prefs.getStringPref", () => {
+ const fakeImpressions = {
+ foo: [Date.now() - 1],
+ bar: [Date.now() - 1],
+ };
+ setPref(SPOC_IMPRESSION_TRACKING_PREF, fakeImpressions);
+
+ const result = feed.readDataPref(SPOC_IMPRESSION_TRACKING_PREF);
+
+ assert.deepEqual(result, fakeImpressions);
+ });
+ });
+
+ describe("#onAction: DISCOVERY_STREAM_IMPRESSION_STATS", () => {
+ it("should call recordTopRecImpressions from DISCOVERY_STREAM_IMPRESSION_STATS", async () => {
+ sandbox.stub(feed, "recordTopRecImpressions").returns();
+ await feed.onAction({
+ type: at.DISCOVERY_STREAM_IMPRESSION_STATS,
+ data: { tiles: [{ id: "seen" }] },
+ });
+
+ assert.calledWith(feed.recordTopRecImpressions, "seen");
+ });
+ });
+
+ describe("#onAction: DISCOVERY_STREAM_SPOC_IMPRESSION", () => {
+ beforeEach(() => {
+ const data = {
+ spocs: {
+ items: [
+ {
+ id: 1,
+ flight_id: "seen",
+ caps: {
+ lifetime: 3,
+ flight: {
+ count: 1,
+ period: 1,
+ },
+ },
+ },
+ {
+ id: 2,
+ flight_id: "not-seen",
+ caps: {
+ lifetime: 3,
+ flight: {
+ count: 1,
+ period: 1,
+ },
+ },
+ },
+ ],
+ },
+ };
+ sandbox.stub(feed.store, "getState").returns({
+ DiscoveryStream: {
+ spocs: {
+ data,
+ },
+ },
+ });
+ });
+
+ it("should call dispatch to ac.AlsoToPreloaded with filtered spoc data", async () => {
+ Object.defineProperty(feed, "showSpocs", { get: () => true });
+ const fakeImpressions = {
+ seen: [Date.now() - 1],
+ };
+ const result = {
+ spocs: {
+ items: [
+ {
+ id: 2,
+ flight_id: "not-seen",
+ caps: {
+ lifetime: 3,
+ flight: {
+ count: 1,
+ period: 1,
+ },
+ },
+ },
+ ],
+ },
+ };
+ sandbox.stub(feed, "recordFlightImpression").returns();
+ sandbox.stub(feed, "readDataPref").returns(fakeImpressions);
+ sandbox.spy(feed.store, "dispatch");
+
+ await feed.onAction({
+ type: at.DISCOVERY_STREAM_SPOC_IMPRESSION,
+ data: { flightId: "seen" },
+ });
+
+ assert.deepEqual(
+ feed.store.dispatch.secondCall.args[0].data.spocs,
+ result
+ );
+ });
+ it("should not call dispatch to ac.AlsoToPreloaded if spocs were not changed by frequency capping", async () => {
+ Object.defineProperty(feed, "showSpocs", { get: () => true });
+ const fakeImpressions = {};
+ sandbox.stub(feed, "recordFlightImpression").returns();
+ sandbox.stub(feed, "readDataPref").returns(fakeImpressions);
+ sandbox.spy(feed.store, "dispatch");
+
+ await feed.onAction({
+ type: at.DISCOVERY_STREAM_SPOC_IMPRESSION,
+ data: { flight_id: "seen" },
+ });
+
+ assert.notCalled(feed.store.dispatch);
+ });
+ it("should attempt feq cap on valid spocs with placements on impression", async () => {
+ sandbox.restore();
+ Object.defineProperty(feed, "showSpocs", { get: () => true });
+ const fakeImpressions = {};
+ sandbox.stub(feed, "recordFlightImpression").returns();
+ sandbox.stub(feed, "readDataPref").returns(fakeImpressions);
+ sandbox.spy(feed.store, "dispatch");
+ sandbox.spy(feed, "frequencyCapSpocs");
+
+ const data = {
+ spocs: {
+ items: [
+ {
+ id: 2,
+ flight_id: "seen-2",
+ caps: {
+ lifetime: 3,
+ flight: {
+ count: 1,
+ period: 1,
+ },
+ },
+ },
+ ],
+ },
+ };
+ sandbox.stub(feed.store, "getState").returns({
+ DiscoveryStream: {
+ spocs: {
+ data,
+ placements: [{ name: "spocs" }, { name: "notSpocs" }],
+ },
+ },
+ });
+
+ await feed.onAction({
+ type: at.DISCOVERY_STREAM_SPOC_IMPRESSION,
+ data: { flight_id: "doesn't matter" },
+ });
+
+ assert.calledOnce(feed.frequencyCapSpocs);
+ assert.calledWith(feed.frequencyCapSpocs, data.spocs.items);
+ });
+ });
+
+ describe("#onAction: PLACES_LINK_BLOCKED", () => {
+ beforeEach(() => {
+ const data = {
+ spocs: {
+ items: [
+ {
+ id: 1,
+ flight_id: "foo",
+ url: "foo.com",
+ },
+ {
+ id: 2,
+ flight_id: "bar",
+ url: "bar.com",
+ },
+ ],
+ },
+ };
+ sandbox.stub(feed.store, "getState").returns({
+ DiscoveryStream: {
+ spocs: {
+ data,
+ placements: [{ name: "spocs" }],
+ },
+ },
+ });
+ });
+
+ it("should call dispatch if found a blocked spoc", async () => {
+ Object.defineProperty(feed, "showSpocs", { get: () => true });
+
+ sandbox.spy(feed.store, "dispatch");
+
+ await feed.onAction({
+ type: at.PLACES_LINK_BLOCKED,
+ data: { url: "foo.com" },
+ });
+
+ assert.deepEqual(
+ feed.store.dispatch.firstCall.args[0].data.url,
+ "foo.com"
+ );
+ });
+ it("should dispatch once if the blocked is not a SPOC", async () => {
+ Object.defineProperty(feed, "showSpocs", { get: () => true });
+ sandbox.spy(feed.store, "dispatch");
+
+ await feed.onAction({
+ type: at.PLACES_LINK_BLOCKED,
+ data: { url: "not_a_spoc.com" },
+ });
+
+ assert.calledOnce(feed.store.dispatch);
+ assert.deepEqual(
+ feed.store.dispatch.firstCall.args[0].data.url,
+ "not_a_spoc.com"
+ );
+ });
+ it("should dispatch a DISCOVERY_STREAM_SPOC_BLOCKED for a blocked spoc", async () => {
+ Object.defineProperty(feed, "showSpocs", { get: () => true });
+ sandbox.spy(feed.store, "dispatch");
+
+ await feed.onAction({
+ type: at.PLACES_LINK_BLOCKED,
+ data: { url: "foo.com" },
+ });
+
+ assert.equal(
+ feed.store.dispatch.secondCall.args[0].type,
+ "DISCOVERY_STREAM_SPOC_BLOCKED"
+ );
+ });
+ });
+
+ describe("#onAction: BLOCK_URL", () => {
+ it("should call recordBlockFlightId whith BLOCK_URL", async () => {
+ sandbox.stub(feed, "recordBlockFlightId").returns();
+
+ await feed.onAction({
+ type: at.BLOCK_URL,
+ data: [
+ {
+ flight_id: "1234",
+ },
+ ],
+ });
+
+ assert.calledWith(feed.recordBlockFlightId, "1234");
+ });
+ });
+
+ describe("#onAction: INIT", () => {
+ it("should be .loaded=false before initialization", () => {
+ assert.isFalse(feed.loaded);
+ });
+ it("should load data and set .loaded=true if config.enabled is true", async () => {
+ sandbox.stub(feed.cache, "set").returns(Promise.resolve());
+ setPref(CONFIG_PREF_NAME, { enabled: true });
+ sandbox.stub(feed, "loadLayout").returns(Promise.resolve());
+
+ await feed.onAction({ type: at.INIT });
+
+ assert.calledOnce(feed.loadLayout);
+ assert.isTrue(feed.loaded);
+ });
+ });
+
+ describe("#onAction: DISCOVERY_STREAM_CONFIG_SET_VALUE", async () => {
+ it("should add the new value to the pref without changing the existing values", async () => {
+ sandbox.spy(feed.store, "dispatch");
+ setPref(CONFIG_PREF_NAME, { enabled: true, other: "value" });
+
+ await feed.onAction({
+ type: at.DISCOVERY_STREAM_CONFIG_SET_VALUE,
+ data: { name: "layout_endpoint", value: "foo.com" },
+ });
+
+ assert.calledWithMatch(feed.store.dispatch, {
+ data: {
+ name: CONFIG_PREF_NAME,
+ value: JSON.stringify({
+ enabled: true,
+ other: "value",
+ layout_endpoint: "foo.com",
+ }),
+ },
+ type: at.SET_PREF,
+ });
+ });
+ });
+
+ describe("#onAction: DISCOVERY_STREAM_CONFIG_RESET", async () => {
+ it("should call configReset", async () => {
+ sandbox.spy(feed, "configReset");
+ feed.onAction({
+ type: at.DISCOVERY_STREAM_CONFIG_RESET,
+ });
+ assert.calledOnce(feed.configReset);
+ });
+ });
+
+ describe("#onAction: DISCOVERY_STREAM_CONFIG_RESET_DEFAULTS", async () => {
+ it("Should dispatch CLEAR_PREF with pref name", async () => {
+ sandbox.spy(feed.store, "dispatch");
+ await feed.onAction({
+ type: at.DISCOVERY_STREAM_CONFIG_RESET_DEFAULTS,
+ });
+
+ assert.calledWithMatch(feed.store.dispatch, {
+ data: {
+ name: CONFIG_PREF_NAME,
+ },
+ type: at.CLEAR_PREF,
+ });
+ });
+ });
+
+ describe("#onAction: DISCOVERY_STREAM_RETRY_FEED", async () => {
+ it("should call retryFeed", async () => {
+ sandbox.spy(feed, "retryFeed");
+ feed.onAction({
+ type: at.DISCOVERY_STREAM_RETRY_FEED,
+ data: { feed: { url: "https://feed.com" } },
+ });
+ assert.calledOnce(feed.retryFeed);
+ assert.calledWith(feed.retryFeed, { url: "https://feed.com" });
+ });
+ });
+
+ describe("#onAction: DISCOVERY_STREAM_CONFIG_CHANGE", () => {
+ it("should call this.loadLayout if config.enabled changes to true ", async () => {
+ sandbox.stub(feed.cache, "set").returns(Promise.resolve());
+ // First initialize
+ await feed.onAction({ type: at.INIT });
+ assert.isFalse(feed.loaded);
+
+ // force clear cached pref value
+ feed._prefCache = {};
+ setPref(CONFIG_PREF_NAME, { enabled: true });
+
+ sandbox.stub(feed, "resetCache").returns(Promise.resolve());
+ sandbox.stub(feed, "loadLayout").returns(Promise.resolve());
+ await feed.onAction({ type: at.DISCOVERY_STREAM_CONFIG_CHANGE });
+
+ assert.calledOnce(feed.loadLayout);
+ assert.calledOnce(feed.resetCache);
+ assert.isTrue(feed.loaded);
+ });
+ it("should clear the cache if a config change happens and config.enabled is true", async () => {
+ sandbox.stub(feed.cache, "set").returns(Promise.resolve());
+ // force clear cached pref value
+ feed._prefCache = {};
+ setPref(CONFIG_PREF_NAME, { enabled: true });
+
+ sandbox.stub(feed, "resetCache").returns(Promise.resolve());
+ await feed.onAction({ type: at.DISCOVERY_STREAM_CONFIG_CHANGE });
+
+ assert.calledOnce(feed.resetCache);
+ });
+ it("should dispatch DISCOVERY_STREAM_LAYOUT_RESET from DISCOVERY_STREAM_CONFIG_CHANGE", async () => {
+ sandbox.stub(feed, "resetDataPrefs");
+ sandbox.stub(feed, "resetCache").resolves();
+ sandbox.stub(feed, "enable").resolves();
+ setPref(CONFIG_PREF_NAME, { enabled: true });
+ sandbox.spy(feed.store, "dispatch");
+
+ await feed.onAction({ type: at.DISCOVERY_STREAM_CONFIG_CHANGE });
+
+ assert.calledWithMatch(feed.store.dispatch, {
+ type: at.DISCOVERY_STREAM_LAYOUT_RESET,
+ });
+ });
+ it("should not call this.loadLayout if config.enabled changes to false", async () => {
+ sandbox.stub(feed.cache, "set").returns(Promise.resolve());
+ // force clear cached pref value
+ feed._prefCache = {};
+ setPref(CONFIG_PREF_NAME, { enabled: true });
+
+ await feed.onAction({ type: at.INIT });
+ assert.isTrue(feed.loaded);
+
+ feed._prefCache = {};
+ setPref(CONFIG_PREF_NAME, { enabled: false });
+ sandbox.stub(feed, "resetCache").returns(Promise.resolve());
+ sandbox.stub(feed, "loadLayout").returns(Promise.resolve());
+ await feed.onAction({ type: at.DISCOVERY_STREAM_CONFIG_CHANGE });
+
+ assert.notCalled(feed.loadLayout);
+ assert.calledOnce(feed.resetCache);
+ assert.isFalse(feed.loaded);
+ });
+ });
+
+ describe("#onAction: UNINIT", () => {
+ it("should reset pref cache", async () => {
+ feed._prefCache = { cached: "value" };
+
+ await feed.onAction({ type: at.UNINIT });
+
+ assert.deepEqual(feed._prefCache, {});
+ });
+ });
+
+ describe("#onAction: PREF_CHANGED", () => {
+ it("should update state.DiscoveryStream.config when the pref changes", async () => {
+ setPref(CONFIG_PREF_NAME, {
+ enabled: true,
+ show_spocs: false,
+ layout_endpoint: "foo",
+ });
+
+ assert.deepEqual(feed.store.getState().DiscoveryStream.config, {
+ enabled: true,
+ show_spocs: false,
+ layout_endpoint: "foo",
+ });
+ });
+ it("should fire loadSpocs is showSponsored pref changes", async () => {
+ sandbox.stub(feed, "loadSpocs").returns(Promise.resolve());
+
+ await feed.onAction({
+ type: at.PREF_CHANGED,
+ data: { name: "showSponsored" },
+ });
+
+ assert.calledOnce(feed.loadSpocs);
+ });
+ it("should call clearSpocs when sponsored content is turned off", async () => {
+ sandbox.stub(feed, "clearSpocs").returns(Promise.resolve());
+
+ await feed.onAction({
+ type: at.PREF_CHANGED,
+ data: { name: "showSponsored", value: false },
+ });
+
+ assert.calledOnce(feed.clearSpocs);
+ });
+ it("should call clearSpocs when top stories is turned off", async () => {
+ sandbox.stub(feed, "clearSpocs").returns(Promise.resolve());
+
+ await feed.onAction({
+ type: at.PREF_CHANGED,
+ data: { name: "feeds.section.topstories", value: false },
+ });
+
+ assert.calledOnce(feed.clearSpocs);
+ });
+ it("should re enable stories when top stories is turned on", async () => {
+ sandbox.stub(feed, "refreshAll").returns(Promise.resolve());
+ feed.loaded = true;
+ setPref(CONFIG_PREF_NAME, {
+ enabled: true,
+ });
+
+ await feed.onAction({
+ type: at.PREF_CHANGED,
+ data: { name: "feeds.section.topstories", value: true },
+ });
+
+ assert.calledOnce(feed.refreshAll);
+ });
+ });
+
+ describe("#onAction: SYSTEM_TICK", () => {
+ it("should not refresh if DiscoveryStream has not been loaded", async () => {
+ sandbox.stub(feed, "refreshAll").resolves();
+ setPref(CONFIG_PREF_NAME, { enabled: true });
+
+ await feed.onAction({ type: at.SYSTEM_TICK });
+ assert.notCalled(feed.refreshAll);
+ });
+
+ it("should not refresh if no caches are expired", async () => {
+ sandbox.stub(feed.cache, "set").resolves();
+ setPref(CONFIG_PREF_NAME, { enabled: true });
+
+ await feed.onAction({ type: at.INIT });
+
+ sandbox.stub(feed, "checkIfAnyCacheExpired").resolves(false);
+ sandbox.stub(feed, "refreshAll").resolves();
+
+ await feed.onAction({ type: at.SYSTEM_TICK });
+ assert.notCalled(feed.refreshAll);
+ });
+
+ it("should refresh if DiscoveryStream has been loaded at least once and a cache has expired", async () => {
+ sandbox.stub(feed.cache, "set").resolves();
+ setPref(CONFIG_PREF_NAME, { enabled: true });
+
+ await feed.onAction({ type: at.INIT });
+
+ sandbox.stub(feed, "checkIfAnyCacheExpired").resolves(true);
+ sandbox.stub(feed, "refreshAll").resolves();
+
+ await feed.onAction({ type: at.SYSTEM_TICK });
+ assert.calledOnce(feed.refreshAll);
+ });
+
+ it("should refresh and not update open tabs if DiscoveryStream has been loaded at least once", async () => {
+ sandbox.stub(feed.cache, "set").resolves();
+ setPref(CONFIG_PREF_NAME, { enabled: true });
+
+ await feed.onAction({ type: at.INIT });
+
+ sandbox.stub(feed, "checkIfAnyCacheExpired").resolves(true);
+ sandbox.stub(feed, "refreshAll").resolves();
+
+ await feed.onAction({ type: at.SYSTEM_TICK });
+ assert.calledWith(feed.refreshAll, { updateOpenTabs: false });
+ });
+ });
+
+ describe("#onAction: PREF_SHOW_SPONSORED", () => {
+ it("should call loadSpocs when preference changes", async () => {
+ sandbox.stub(feed, "loadSpocs").resolves();
+ sandbox.stub(feed.store, "dispatch");
+
+ await feed.onAction({
+ type: at.PREF_CHANGED,
+ data: { name: "showSponsored" },
+ });
+
+ assert.calledOnce(feed.loadSpocs);
+ const [dispatchFn] = feed.loadSpocs.firstCall.args;
+ dispatchFn({});
+ assert.calledWith(feed.store.dispatch, ac.BroadcastToContent({}));
+ });
+ });
+
+ describe("#onAction: DISCOVERY_STREAM_DEV_IDLE_DAILY", () => {
+ it("should trigger idle-daily observer", async () => {
+ sandbox.stub(global.Services.obs, "notifyObservers").returns();
+ await feed.onAction({
+ type: at.DISCOVERY_STREAM_DEV_IDLE_DAILY,
+ });
+ assert.calledWith(
+ global.Services.obs.notifyObservers,
+ null,
+ "idle-daily"
+ );
+ });
+ });
+
+ describe("#onAction: DISCOVERY_STREAM_DEV_SYNC_RS", () => {
+ it("should fire remote settings pollChanges", async () => {
+ sandbox.stub(global.RemoteSettings, "pollChanges").returns();
+ await feed.onAction({
+ type: at.DISCOVERY_STREAM_DEV_SYNC_RS,
+ });
+ assert.calledOnce(global.RemoteSettings.pollChanges);
+ });
+ });
+
+ describe("#onAction: DISCOVERY_STREAM_DEV_SYSTEM_TICK", () => {
+ it("should refresh if DiscoveryStream has been loaded at least once and a cache has expired", async () => {
+ sandbox.stub(feed.cache, "set").resolves();
+ setPref(CONFIG_PREF_NAME, { enabled: true });
+
+ await feed.onAction({ type: at.INIT });
+
+ sandbox.stub(feed, "checkIfAnyCacheExpired").resolves(true);
+ sandbox.stub(feed, "refreshAll").resolves();
+
+ await feed.onAction({ type: at.DISCOVERY_STREAM_DEV_SYSTEM_TICK });
+ assert.calledOnce(feed.refreshAll);
+ });
+ });
+
+ describe("#onAction: DISCOVERY_STREAM_DEV_EXPIRE_CACHE", () => {
+ it("should fire resetCache", async () => {
+ sandbox.stub(feed, "resetContentCache").returns();
+ await feed.onAction({
+ type: at.DISCOVERY_STREAM_DEV_EXPIRE_CACHE,
+ });
+ assert.calledOnce(feed.resetContentCache);
+ });
+ });
+
+ describe("#isExpired", () => {
+ it("should throw if the key is not valid", () => {
+ assert.throws(() => {
+ feed.isExpired({}, "foo");
+ });
+ });
+ it("should return false for layout on startup for content under 1 week", () => {
+ const layout = { lastUpdated: Date.now() };
+ const result = feed.isExpired({
+ cachedData: { layout },
+ key: "layout",
+ isStartup: true,
+ });
+
+ assert.isFalse(result);
+ });
+ it("should return true for layout for isStartup=false after 30 mins", () => {
+ const layout = { lastUpdated: Date.now() };
+ clock.tick(THIRTY_MINUTES + 1);
+ const result = feed.isExpired({ cachedData: { layout }, key: "layout" });
+
+ assert.isTrue(result);
+ });
+ it("should return true for layout on startup for content over 1 week", () => {
+ const layout = { lastUpdated: Date.now() };
+ clock.tick(ONE_WEEK + 1);
+ const result = feed.isExpired({
+ cachedData: { layout },
+ key: "layout",
+ isStartup: true,
+ });
+
+ assert.isTrue(result);
+ });
+ it("should return false for hardcoded layout on startup for content over 1 week", () => {
+ feed._prefCache.config = {
+ hardcoded_layout: true,
+ };
+ const layout = { lastUpdated: Date.now() };
+ clock.tick(ONE_WEEK + 1);
+ const result = feed.isExpired({
+ cachedData: { layout },
+ key: "layout",
+ isStartup: true,
+ });
+
+ assert.isFalse(result);
+ });
+ });
+
+ describe("#checkIfAnyCacheExpired", () => {
+ let cache;
+ beforeEach(() => {
+ cache = {
+ layout: { lastUpdated: Date.now() },
+ feeds: { "foo.com": { lastUpdated: Date.now() } },
+ spocs: { lastUpdated: Date.now() },
+ };
+ sandbox.stub(feed.cache, "get").resolves(cache);
+ });
+
+ it("should return false if nothing in the cache is expired", async () => {
+ const result = await feed.checkIfAnyCacheExpired();
+ assert.isFalse(result);
+ });
+
+ it("should return true if .layout is missing", async () => {
+ delete cache.layout;
+ assert.isTrue(await feed.checkIfAnyCacheExpired());
+ });
+ it("should return true if .layout is expired", async () => {
+ clock.tick(THIRTY_MINUTES + 1);
+ // Update other caches we aren't testing
+ cache.feeds["foo.com"].lastUpdate = Date.now();
+ cache.spocs.lastUpdate = Date.now();
+
+ assert.isTrue(await feed.checkIfAnyCacheExpired());
+ });
+
+ it("should return true if .spocs is missing", async () => {
+ delete cache.spocs;
+ assert.isTrue(await feed.checkIfAnyCacheExpired());
+ });
+ it("should return true if .spocs is expired", async () => {
+ clock.tick(THIRTY_MINUTES + 1);
+ // Update other caches we aren't testing
+ cache.layout.lastUpdated = Date.now();
+ cache.feeds["foo.com"].lastUpdate = Date.now();
+
+ assert.isTrue(await feed.checkIfAnyCacheExpired());
+ });
+
+ it("should return true if .feeds is missing", async () => {
+ delete cache.feeds;
+ assert.isTrue(await feed.checkIfAnyCacheExpired());
+ });
+ it("should return true if data for .feeds[url] is missing", async () => {
+ cache.feeds["foo.com"] = null;
+ assert.isTrue(await feed.checkIfAnyCacheExpired());
+ });
+ it("should return true if data for .feeds[url] is expired", async () => {
+ clock.tick(THIRTY_MINUTES + 1);
+ // Update other caches we aren't testing
+ cache.layout.lastUpdated = Date.now();
+ cache.spocs.lastUpdate = Date.now();
+ assert.isTrue(await feed.checkIfAnyCacheExpired());
+ });
+ });
+
+ describe("#refreshAll", () => {
+ beforeEach(() => {
+ sandbox.stub(feed, "loadLayout").resolves();
+ sandbox.stub(feed, "loadComponentFeeds").resolves();
+ sandbox.stub(feed, "loadSpocs").resolves();
+ sandbox.spy(feed.store, "dispatch");
+ Object.defineProperty(feed, "showSpocs", { get: () => true });
+ });
+
+ it("should call layout, component, spocs update and telemetry reporting functions", async () => {
+ await feed.refreshAll();
+
+ assert.calledOnce(feed.loadLayout);
+ assert.calledOnce(feed.loadComponentFeeds);
+ assert.calledOnce(feed.loadSpocs);
+ });
+ it("should pass in dispatch wrapped with broadcast if options.updateOpenTabs is true", async () => {
+ await feed.refreshAll({ updateOpenTabs: true });
+ [feed.loadLayout, feed.loadComponentFeeds, feed.loadSpocs].forEach(fn => {
+ assert.calledOnce(fn);
+ const result = fn.firstCall.args[0]({ type: "FOO" });
+ assert.isTrue(au.isBroadcastToContent(result));
+ });
+ });
+ it("should pass in dispatch with regular actions if options.updateOpenTabs is false", async () => {
+ await feed.refreshAll({ updateOpenTabs: false });
+ [feed.loadLayout, feed.loadComponentFeeds, feed.loadSpocs].forEach(fn => {
+ assert.calledOnce(fn);
+ const result = fn.firstCall.args[0]({ type: "FOO" });
+ assert.deepEqual(result, { type: "FOO" });
+ });
+ });
+ it("should set loaded to true if loadSpocs and loadComponentFeeds fails", async () => {
+ feed.loadComponentFeeds.rejects("loadComponentFeeds error");
+ feed.loadSpocs.rejects("loadSpocs error");
+
+ await feed.enable();
+
+ assert.isTrue(feed.loaded);
+ });
+ it("should call loadComponentFeeds and loadSpocs in Promise.all", async () => {
+ sandbox.stub(global.Promise, "all").resolves();
+
+ await feed.refreshAll();
+
+ assert.calledOnce(global.Promise.all);
+ const { args } = global.Promise.all.firstCall;
+ assert.equal(args[0].length, 2);
+ });
+ describe("test startup cache behaviour", () => {
+ beforeEach(() => {
+ feed._maybeUpdateCachedData.restore();
+ sandbox.stub(feed.cache, "set").resolves();
+ });
+ it("should refresh layout on startup if it was served from cache", async () => {
+ feed.loadLayout.restore();
+ sandbox
+ .stub(feed.cache, "get")
+ .resolves({ layout: { lastUpdated: Date.now(), layout: {} } });
+ sandbox.stub(feed, "fetchFromEndpoint").resolves({ layout: {} });
+ clock.tick(THIRTY_MINUTES + 1);
+
+ await feed.refreshAll({ isStartup: true });
+
+ assert.calledOnce(feed.fetchFromEndpoint);
+ // Once from cache, once to update the store
+ assert.calledTwice(feed.store.dispatch);
+ assert.equal(
+ feed.store.dispatch.firstCall.args[0].type,
+ at.DISCOVERY_STREAM_LAYOUT_UPDATE
+ );
+ });
+ it("should not refresh layout on startup if it is under THIRTY_MINUTES", async () => {
+ feed.loadLayout.restore();
+ sandbox
+ .stub(feed.cache, "get")
+ .resolves({ layout: { lastUpdated: Date.now(), layout: {} } });
+ sandbox.stub(feed, "fetchFromEndpoint").resolves({ layout: {} });
+
+ await feed.refreshAll({ isStartup: true });
+
+ assert.notCalled(feed.fetchFromEndpoint);
+ });
+ it("should refresh spocs on startup if it was served from cache", async () => {
+ feed.loadSpocs.restore();
+ sandbox
+ .stub(feed.cache, "get")
+ .resolves({ spocs: { lastUpdated: Date.now() } });
+ sandbox.stub(feed, "fetchFromEndpoint").resolves("data");
+ clock.tick(THIRTY_MINUTES + 1);
+
+ await feed.refreshAll({ isStartup: true });
+
+ assert.calledOnce(feed.fetchFromEndpoint);
+ // Once from cache, once to update the store
+ assert.calledTwice(feed.store.dispatch);
+ assert.equal(
+ feed.store.dispatch.firstCall.args[0].type,
+ at.DISCOVERY_STREAM_SPOCS_UPDATE
+ );
+ });
+ it("should not refresh spocs on startup if it is under THIRTY_MINUTES", async () => {
+ feed.loadSpocs.restore();
+ sandbox
+ .stub(feed.cache, "get")
+ .resolves({ spocs: { lastUpdated: Date.now() } });
+ sandbox.stub(feed, "fetchFromEndpoint").resolves("data");
+
+ await feed.refreshAll({ isStartup: true });
+
+ assert.notCalled(feed.fetchFromEndpoint);
+ });
+ it("should refresh feeds on startup if it was served from cache", async () => {
+ feed.loadComponentFeeds.restore();
+
+ const fakeComponents = { components: [{ feed: { url: "foo.com" } }] };
+ const fakeLayout = [fakeComponents];
+ const fakeDiscoveryStream = {
+ DiscoveryStream: {
+ layout: fakeLayout,
+ },
+ Prefs: {
+ values: {
+ "feeds.section.topstories": true,
+ "feeds.system.topstories": true,
+ },
+ },
+ };
+ sandbox.stub(feed.store, "getState").returns(fakeDiscoveryStream);
+ sandbox.stub(feed, "rotate").callsFake(val => val);
+ sandbox
+ .stub(feed, "scoreItems")
+ .callsFake(val => ({ data: val, filtered: [] }));
+ sandbox.stub(feed, "cleanUpTopRecImpressionPref").callsFake(val => val);
+
+ const fakeCache = {
+ feeds: { "foo.com": { lastUpdated: Date.now(), data: "data" } },
+ };
+ sandbox.stub(feed.cache, "get").resolves(fakeCache);
+ clock.tick(THIRTY_MINUTES + 1);
+ sandbox.stub(feed, "fetchFromEndpoint").resolves({
+ recommendations: "data",
+ settings: {
+ recsExpireTime: 1,
+ },
+ });
+
+ await feed.refreshAll({ isStartup: true });
+
+ assert.calledOnce(feed.fetchFromEndpoint);
+ // Once from cache, once to update the feed, once to update that all feeds are done.
+ assert.calledThrice(feed.store.dispatch);
+ assert.equal(
+ feed.store.dispatch.secondCall.args[0].type,
+ at.DISCOVERY_STREAM_FEEDS_UPDATE
+ );
+ });
+ });
+ });
+
+ describe("#scoreFeeds", () => {
+ it("should score feeds and set cache, and dispatch", async () => {
+ sandbox.stub(feed.cache, "set").resolves();
+ sandbox.spy(feed.store, "dispatch");
+ const recsExpireTime = 5600;
+ const fakeImpressions = {
+ first: Date.now() - recsExpireTime * 1000,
+ third: Date.now(),
+ };
+ sandbox.stub(feed, "readDataPref").returns(fakeImpressions);
+ const fakeFeeds = {
+ data: {
+ "https://foo.com": {
+ data: {
+ recommendations: [
+ {
+ id: "first",
+ min_score: 0.5,
+ item_score: 0.7,
+ },
+ {
+ id: "second",
+ min_score: 0.5,
+ item_score: 0.6,
+ },
+ ],
+ settings: {
+ recsExpireTime,
+ },
+ },
+ },
+ "https://bar.com": {
+ data: {
+ recommendations: [
+ {
+ id: "third",
+ min_score: 0.5,
+ item_score: 0.4,
+ },
+ {
+ id: "fourth",
+ min_score: 0.5,
+ item_score: 0.6,
+ },
+ {
+ id: "fifth",
+ min_score: 0.5,
+ item_score: 0.8,
+ },
+ ],
+ settings: {
+ recsExpireTime,
+ },
+ },
+ },
+ },
+ };
+ const feedsTestResult = {
+ "https://foo.com": {
+ data: {
+ recommendations: [
+ {
+ id: "second",
+ min_score: 0.5,
+ item_score: 0.6,
+ score: 0.6,
+ },
+ {
+ id: "first",
+ min_score: 0.5,
+ item_score: 0.7,
+ score: 0.7,
+ },
+ ],
+ settings: {
+ recsExpireTime,
+ },
+ },
+ },
+ "https://bar.com": {
+ data: {
+ recommendations: [
+ {
+ id: "fifth",
+ min_score: 0.5,
+ item_score: 0.8,
+ score: 0.8,
+ },
+ {
+ id: "fourth",
+ min_score: 0.5,
+ item_score: 0.6,
+ score: 0.6,
+ },
+ ],
+ settings: {
+ recsExpireTime,
+ },
+ },
+ },
+ };
+
+ await feed.scoreFeeds(fakeFeeds);
+
+ assert.calledWith(feed.cache.set, "feeds", feedsTestResult);
+ assert.equal(
+ feed.store.dispatch.firstCall.args[0].type,
+ at.DISCOVERY_STREAM_FEED_UPDATE
+ );
+ assert.deepEqual(feed.store.dispatch.firstCall.args[0].data, {
+ url: "https://foo.com",
+ feed: feedsTestResult["https://foo.com"],
+ });
+ assert.equal(
+ feed.store.dispatch.secondCall.args[0].type,
+ at.DISCOVERY_STREAM_FEED_UPDATE
+ );
+ assert.deepEqual(feed.store.dispatch.secondCall.args[0].data, {
+ url: "https://bar.com",
+ feed: feedsTestResult["https://bar.com"],
+ });
+ });
+ });
+
+ describe("#scoreSpocs", () => {
+ it("should score spocs and set cache, dispatch", async () => {
+ sandbox.stub(feed.cache, "set").resolves();
+ sandbox.spy(feed.store, "dispatch");
+ const fakeDiscoveryStream = {
+ Prefs: {
+ values: {
+ "discoverystream.spocs.personalized": true,
+ "discoverystream.recs.personalized": false,
+ },
+ },
+ DiscoveryStream: {
+ spocs: {
+ placements: [
+ { name: "placement1" },
+ { name: "placement2" },
+ { name: "placement3" },
+ ],
+ },
+ },
+ };
+ sandbox.stub(feed.store, "getState").returns(fakeDiscoveryStream);
+ const fakeSpocs = {
+ lastUpdated: 1234,
+ data: {
+ placement1: {
+ items: [
+ {
+ min_score: 0.5,
+ item_score: 0.6,
+ },
+ {
+ min_score: 0.5,
+ item_score: 0.4,
+ },
+ {
+ min_score: 0.5,
+ item_score: 0.8,
+ },
+ ],
+ },
+ placement2: {
+ items: [
+ {
+ min_score: 0.5,
+ item_score: 0.6,
+ },
+ {
+ min_score: 0.5,
+ item_score: 0.8,
+ },
+ ],
+ },
+ placement3: { items: [] },
+ },
+ };
+
+ await feed.scoreSpocs(fakeSpocs);
+
+ const spocsTestResult = {
+ lastUpdated: 1234,
+ spocs: {
+ placement1: {
+ items: [
+ {
+ min_score: 0.5,
+ score: 0.8,
+ item_score: 0.8,
+ },
+ {
+ min_score: 0.5,
+ score: 0.6,
+ item_score: 0.6,
+ },
+ ],
+ },
+ placement2: {
+ items: [
+ {
+ min_score: 0.5,
+ score: 0.8,
+ item_score: 0.8,
+ },
+ {
+ min_score: 0.5,
+ score: 0.6,
+ item_score: 0.6,
+ },
+ ],
+ },
+ placement3: { items: [] },
+ },
+ };
+ assert.calledWith(feed.cache.set, "spocs", spocsTestResult);
+ assert.equal(
+ feed.store.dispatch.firstCall.args[0].type,
+ at.DISCOVERY_STREAM_SPOCS_UPDATE
+ );
+ assert.deepEqual(
+ feed.store.dispatch.firstCall.args[0].data,
+ spocsTestResult
+ );
+ });
+ });
+
+ describe("#scoreContent", () => {
+ it("should call scoreFeeds and scoreSpocs if loaded", async () => {
+ const fakeDiscoveryStream = {
+ Prefs: {
+ values: {
+ "discoverystream.spocs.personalized": true,
+ "discoverystream.recs.personalized": true,
+ },
+ },
+ DiscoveryStream: {
+ feeds: { loaded: false },
+ spocs: { loaded: false },
+ },
+ };
+ sandbox.stub(feed, "scoreFeeds").resolves();
+ sandbox.stub(feed, "scoreSpocs").resolves();
+ sandbox.stub(feed, "refreshContent").resolves();
+ sandbox.stub(feed, "loadAffinityScoresCache").resolves();
+ sandbox.stub(feed.store, "getState").returns(fakeDiscoveryStream);
+ sandbox.stub(feed, "_checkExpirationPerComponent").resolves({
+ feeds: true,
+ spocs: true,
+ });
+ feed._prefCache.config = {
+ personalized: true,
+ };
+
+ await feed.refreshAll();
+
+ assert.notCalled(feed.scoreFeeds);
+ assert.notCalled(feed.scoreSpocs);
+
+ fakeDiscoveryStream.DiscoveryStream.feeds.loaded = true;
+ fakeDiscoveryStream.DiscoveryStream.spocs.loaded = true;
+
+ await feed.refreshAll();
+
+ assert.calledOnce(feed.scoreFeeds);
+ assert.calledOnce(feed.scoreSpocs);
+ });
+ });
+
+ describe("#loadAffinityScoresCache", () => {
+ it("should create an affinity provider from cached affinities", async () => {
+ feed._prefCache.config = {
+ personalized: true,
+ };
+ const fakeCache = {
+ affinities: {
+ scores: 123,
+ _timestamp: 456,
+ },
+ };
+ sandbox.stub(feed.cache, "get").returns(Promise.resolve(fakeCache));
+
+ await feed.loadAffinityScoresCache();
+
+ assert.equal(feed.domainAffinitiesLastUpdated, 456);
+ });
+ });
+
+ describe("#updateDomainAffinityScores", () => {
+ it("should call updateDomainAffinityScores on idle daily", async () => {
+ sandbox.stub(feed, "updateDomainAffinityScores").returns();
+ feed.observe(null, "idle-daily");
+ assert.calledOnce(feed.updateDomainAffinityScores);
+ });
+ it("should update affinity provider on updateDomainAffinityScores", async () => {
+ feed._prefCache.config = {
+ personalized: true,
+ };
+ const DEFAULT_TIME_SEGMENTS = [
+ { id: "hour", startTime: 3600, endTime: 0, weightPosition: 1 },
+ { id: "day", startTime: 86400, endTime: 3600, weightPosition: 0.75 },
+ { id: "week", startTime: 604800, endTime: 86400, weightPosition: 0.5 },
+ { id: "weekPlus", startTime: 0, endTime: 604800, weightPosition: 0.25 },
+ { id: "alltime", startTime: 0, endTime: 0, weightPosition: 0.25 },
+ ];
+ feed.affinities = {
+ parameterSets: {
+ default: {},
+ },
+ maxHistoryQueryResults: 1000,
+ timeSegments: DEFAULT_TIME_SEGMENTS,
+ version: "123",
+ };
+
+ await feed.updateDomainAffinityScores();
+
+ assert.equal(feed.providerSwitcher.affinityProvider.version, "123");
+ });
+ it("should not update affinity provider on updateDomainAffinityScores", async () => {
+ feed._prefCache.config = {
+ personalized: false,
+ };
+
+ await feed.updateDomainAffinityScores();
+
+ assert.isTrue(!feed.affinityProvider);
+ });
+ });
+ describe("#scoreItems", () => {
+ it("should score items using item_score and min_score", async () => {
+ const { data: result } = await feed.scoreItems([
+ { item_score: 0.8, min_score: 0.1 },
+ { item_score: 0.5, min_score: 0.6 },
+ { item_score: 0.7, min_score: 0.1 },
+ { item_score: 0.9, min_score: 0.1 },
+ ]);
+ assert.deepEqual(result, [
+ { item_score: 0.9, score: 0.9, min_score: 0.1 },
+ { item_score: 0.8, score: 0.8, min_score: 0.1 },
+ { item_score: 0.7, score: 0.7, min_score: 0.1 },
+ ]);
+ });
+ });
+ describe("#scoreItem", () => {
+ it("should call calculateItemRelevanceScore with affinity provider", async () => {
+ const item = {};
+ feed._prefCache.config = {
+ personalized: true,
+ };
+ feed.providerSwitcher.calculateItemRelevanceScore = sandbox
+ .stub()
+ .returns();
+ await feed.scoreItem(item, true);
+ assert.calledOnce(feed.providerSwitcher.calculateItemRelevanceScore);
+ });
+ it("should use item_score score without affinity provider score", async () => {
+ const item = {
+ item_score: 0.6,
+ };
+ feed._prefCache.config = {
+ personalized: true,
+ };
+ feed.affinityProvider = {
+ calculateItemRelevanceScore: () => {},
+ };
+ const result = await feed.scoreItem(item);
+ assert.equal(result.score, 0.6);
+ });
+ it("should add min_score of 0 if undefined", async () => {
+ const item = {};
+ feed._prefCache.config = {
+ personalized: true,
+ };
+ feed.affinityProvider = {
+ calculateItemRelevanceScore: () => 0.5,
+ };
+ const result = await feed.scoreItem(item);
+ assert.equal(result.min_score, 0);
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/lib/DownloadsManager.test.js b/browser/components/newtab/test/unit/lib/DownloadsManager.test.js
new file mode 100644
index 0000000000..c8543da90b
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/DownloadsManager.test.js
@@ -0,0 +1,373 @@
+import { actionTypes as at } from "common/Actions.jsm";
+import { DownloadsManager } from "lib/DownloadsManager.jsm";
+import { GlobalOverrider } from "test/unit/utils";
+
+describe("Downloads Manager", () => {
+ let downloadsManager;
+ let globals;
+ const DOWNLOAD_URL = "https://site.com/download.mov";
+
+ beforeEach(() => {
+ globals = new GlobalOverrider();
+ global.Cc["@mozilla.org/timer;1"] = {
+ createInstance() {
+ return {
+ initWithCallback: sinon.stub().callsFake(callback => callback()),
+ cancel: sinon.spy(),
+ };
+ },
+ };
+
+ globals.set("DownloadsCommon", {
+ getData: sinon.stub().returns({
+ addView: sinon.stub(),
+ removeView: sinon.stub(),
+ }),
+ copyDownloadLink: sinon.stub(),
+ deleteDownload: sinon.stub().returns(Promise.resolve()),
+ openDownload: sinon.stub(),
+ showDownloadedFile: sinon.stub(),
+ });
+
+ downloadsManager = new DownloadsManager();
+ downloadsManager.init({ dispatch() {} });
+ downloadsManager.onDownloadAdded({
+ source: { url: DOWNLOAD_URL },
+ endTime: Date.now(),
+ target: { path: "/path/to/download.mov", exists: true },
+ succeeded: true,
+ refresh: async () => {},
+ });
+ assert.ok(downloadsManager._downloadItems.has(DOWNLOAD_URL));
+
+ globals.set("NewTabUtils", { blockedLinks: { isBlocked() {} } });
+ });
+ afterEach(() => {
+ downloadsManager._downloadItems.clear();
+ globals.restore();
+ });
+ describe("#init", () => {
+ it("should add a DownloadsCommon view on init", () => {
+ downloadsManager.init({ dispatch() {} });
+ assert.calledTwice(global.DownloadsCommon.getData().addView);
+ });
+ });
+ describe("#onAction", () => {
+ it("should copy the file on COPY_DOWNLOAD_LINK", () => {
+ downloadsManager.onAction({
+ type: at.COPY_DOWNLOAD_LINK,
+ data: { url: DOWNLOAD_URL },
+ });
+ assert.calledOnce(global.DownloadsCommon.copyDownloadLink);
+ });
+ it("should remove the file on REMOVE_DOWNLOAD_FILE", () => {
+ downloadsManager.onAction({
+ type: at.REMOVE_DOWNLOAD_FILE,
+ data: { url: DOWNLOAD_URL },
+ });
+ assert.calledOnce(global.DownloadsCommon.deleteDownload);
+ });
+ it("should show the file on SHOW_DOWNLOAD_FILE", () => {
+ downloadsManager.onAction({
+ type: at.SHOW_DOWNLOAD_FILE,
+ data: { url: DOWNLOAD_URL },
+ });
+ assert.calledOnce(global.DownloadsCommon.showDownloadedFile);
+ });
+ it("should open the file on OPEN_DOWNLOAD_FILE if the type is download", () => {
+ downloadsManager.onAction({
+ type: at.OPEN_DOWNLOAD_FILE,
+ data: { url: DOWNLOAD_URL, type: "download" },
+ _target: { browser: {} },
+ });
+ assert.calledOnce(global.DownloadsCommon.openDownload);
+ });
+ it("should copy the file on UNINIT", () => {
+ // DownloadsManager._downloadData needs to exist first
+ downloadsManager.onAction({ type: at.UNINIT });
+ assert.calledOnce(global.DownloadsCommon.getData().removeView);
+ });
+ it("should not execute a download command if we do not have the correct url", () => {
+ downloadsManager.onAction({
+ type: at.SHOW_DOWNLOAD_FILE,
+ data: { url: "unknown_url" },
+ });
+ assert.notCalled(global.DownloadsCommon.showDownloadedFile);
+ });
+ });
+ describe("#onDownloadAdded", () => {
+ let newDownload;
+ beforeEach(() => {
+ downloadsManager._downloadItems.clear();
+ newDownload = {
+ source: { url: "https://site.com/newDownload.mov" },
+ endTime: Date.now(),
+ target: { path: "/path/to/newDownload.mov", exists: true },
+ succeeded: true,
+ refresh: async () => {},
+ };
+ });
+ afterEach(() => {
+ downloadsManager._downloadItems.clear();
+ });
+ it("should add a download on onDownloadAdded", () => {
+ downloadsManager.onDownloadAdded(newDownload);
+ assert.ok(
+ downloadsManager._downloadItems.has("https://site.com/newDownload.mov")
+ );
+ });
+ it("should not add a download if it already exists", () => {
+ downloadsManager.onDownloadAdded(newDownload);
+ downloadsManager.onDownloadAdded(newDownload);
+ downloadsManager.onDownloadAdded(newDownload);
+ downloadsManager.onDownloadAdded(newDownload);
+ const results = downloadsManager._downloadItems;
+ assert.equal(results.size, 1);
+ });
+ it("should not return any downloads if no threshold is provided", async () => {
+ downloadsManager.onDownloadAdded(newDownload);
+ const results = await downloadsManager.getDownloads(null, {});
+ assert.equal(results.length, 0);
+ });
+ it("should stop at numItems when it found one it's looking for", async () => {
+ const aDownload = {
+ source: { url: "https://site.com/aDownload.pdf" },
+ endTime: Date.now(),
+ target: { path: "/path/to/aDownload.pdf", exists: true },
+ succeeded: true,
+ refresh: async () => {},
+ };
+ downloadsManager.onDownloadAdded(aDownload);
+ downloadsManager.onDownloadAdded(newDownload);
+ const results = await downloadsManager.getDownloads(Infinity, {
+ numItems: 1,
+ onlySucceeded: true,
+ onlyExists: true,
+ });
+ assert.equal(results.length, 1);
+ assert.equal(results[0].url, aDownload.source.url);
+ });
+ it("should get all the downloads younger than the threshold provided", async () => {
+ const oldDownload = {
+ source: { url: "https://site.com/oldDownload.pdf" },
+ endTime: Date.now() - 40 * 60 * 60 * 1000,
+ target: { path: "/path/to/oldDownload.pdf", exists: true },
+ succeeded: true,
+ refresh: async () => {},
+ };
+ // Add an old download (older than 36 hours in this case)
+ downloadsManager.onDownloadAdded(oldDownload);
+ downloadsManager.onDownloadAdded(newDownload);
+ const RECENT_DOWNLOAD_THRESHOLD = 36 * 60 * 60 * 1000;
+ const results = await downloadsManager.getDownloads(
+ RECENT_DOWNLOAD_THRESHOLD,
+ { numItems: 5, onlySucceeded: true, onlyExists: true }
+ );
+ assert.equal(results.length, 1);
+ assert.equal(results[0].url, newDownload.source.url);
+ });
+ it("should dispatch DOWNLOAD_CHANGED when adding a download", () => {
+ downloadsManager._store.dispatch = sinon.spy();
+ downloadsManager._downloadTimer = null; // Nuke the timer
+ downloadsManager.onDownloadAdded(newDownload);
+ assert.calledOnce(downloadsManager._store.dispatch);
+ });
+ it("should refresh the downloads if onlyExists is true", async () => {
+ const aDownload = {
+ source: { url: "https://site.com/aDownload.pdf" },
+ endTime: Date.now() - 40 * 60 * 60 * 1000,
+ target: { path: "/path/to/aDownload.pdf", exists: true },
+ succeeded: true,
+ refresh: () => {},
+ };
+ sinon.stub(aDownload, "refresh").returns(Promise.resolve());
+ downloadsManager.onDownloadAdded(aDownload);
+ await downloadsManager.getDownloads(Infinity, {
+ numItems: 5,
+ onlySucceeded: true,
+ onlyExists: true,
+ });
+ assert.calledOnce(aDownload.refresh);
+ });
+ it("should not refresh the downloads if onlyExists is false (by default)", async () => {
+ const aDownload = {
+ source: { url: "https://site.com/aDownload.pdf" },
+ endTime: Date.now() - 40 * 60 * 60 * 1000,
+ target: { path: "/path/to/aDownload.pdf", exists: true },
+ succeeded: true,
+ refresh: () => {},
+ };
+ sinon.stub(aDownload, "refresh").returns(Promise.resolve());
+ downloadsManager.onDownloadAdded(aDownload);
+ await downloadsManager.getDownloads(Infinity, {
+ numItems: 5,
+ onlySucceeded: true,
+ });
+ assert.notCalled(aDownload.refresh);
+ });
+ it("should only return downloads that exist if specified", async () => {
+ const nonExistantDownload = {
+ source: { url: "https://site.com/nonExistantDownload.pdf" },
+ endTime: Date.now() - 40 * 60 * 60 * 1000,
+ target: { path: "/path/to/nonExistantDownload.pdf", exists: false },
+ succeeded: true,
+ refresh: async () => {},
+ };
+ downloadsManager.onDownloadAdded(newDownload);
+ downloadsManager.onDownloadAdded(nonExistantDownload);
+ const results = await downloadsManager.getDownloads(Infinity, {
+ numItems: 5,
+ onlySucceeded: true,
+ onlyExists: true,
+ });
+ assert.equal(results.length, 1);
+ assert.equal(results[0].url, newDownload.source.url);
+ });
+ it("should return all downloads that either exist or don't exist if not specified", async () => {
+ const nonExistantDownload = {
+ source: { url: "https://site.com/nonExistantDownload.pdf" },
+ endTime: Date.now() - 40 * 60 * 60 * 1000,
+ target: { path: "/path/to/nonExistantDownload.pdf", exists: false },
+ succeeded: true,
+ refresh: async () => {},
+ };
+ downloadsManager.onDownloadAdded(newDownload);
+ downloadsManager.onDownloadAdded(nonExistantDownload);
+ const results = await downloadsManager.getDownloads(Infinity, {
+ numItems: 5,
+ onlySucceeded: true,
+ });
+ assert.equal(results.length, 2);
+ assert.equal(results[0].url, newDownload.source.url);
+ assert.equal(results[1].url, nonExistantDownload.source.url);
+ });
+ it("should return only unblocked downloads", async () => {
+ const nonExistantDownload = {
+ source: { url: "https://site.com/nonExistantDownload.pdf" },
+ endTime: Date.now() - 40 * 60 * 60 * 1000,
+ target: { path: "/path/to/nonExistantDownload.pdf", exists: false },
+ succeeded: true,
+ refresh: async () => {},
+ };
+ downloadsManager.onDownloadAdded(newDownload);
+ downloadsManager.onDownloadAdded(nonExistantDownload);
+ globals.set("NewTabUtils", {
+ blockedLinks: {
+ isBlocked: item => item.url === nonExistantDownload.source.url,
+ },
+ });
+
+ const results = await downloadsManager.getDownloads(Infinity, {
+ numItems: 5,
+ onlySucceeded: true,
+ });
+
+ assert.equal(results.length, 1);
+ assert.propertyVal(results[0], "url", newDownload.source.url);
+ });
+ it("should only return downloads that were successful if specified", async () => {
+ const nonSuccessfulDownload = {
+ source: { url: "https://site.com/nonSuccessfulDownload.pdf" },
+ endTime: Date.now() - 40 * 60 * 60 * 1000,
+ target: { path: "/path/to/nonSuccessfulDownload.pdf", exists: false },
+ succeeded: false,
+ refresh: async () => {},
+ };
+ downloadsManager.onDownloadAdded(newDownload);
+ downloadsManager.onDownloadAdded(nonSuccessfulDownload);
+ const results = await downloadsManager.getDownloads(Infinity, {
+ numItems: 5,
+ onlySucceeded: true,
+ });
+ assert.equal(results.length, 1);
+ assert.equal(results[0].url, newDownload.source.url);
+ });
+ it("should return all downloads that were either successful or not if not specified", async () => {
+ const nonExistantDownload = {
+ source: { url: "https://site.com/nonExistantDownload.pdf" },
+ endTime: Date.now() - 40 * 60 * 60 * 1000,
+ target: { path: "/path/to/nonExistantDownload.pdf", exists: true },
+ succeeded: false,
+ refresh: async () => {},
+ };
+ downloadsManager.onDownloadAdded(newDownload);
+ downloadsManager.onDownloadAdded(nonExistantDownload);
+ const results = await downloadsManager.getDownloads(Infinity, {
+ numItems: 5,
+ });
+ assert.equal(results.length, 2);
+ assert.equal(results[0].url, newDownload.source.url);
+ assert.equal(results[1].url, nonExistantDownload.source.url);
+ });
+ it("should sort the downloads by recency", async () => {
+ const olderDownload1 = {
+ source: { url: "https://site.com/oldDownload1.pdf" },
+ endTime: Date.now() - 2 * 60 * 60 * 1000, // 2 hours ago
+ target: { path: "/path/to/oldDownload1.pdf", exists: true },
+ succeeded: true,
+ refresh: async () => {},
+ };
+ const olderDownload2 = {
+ source: { url: "https://site.com/oldDownload2.pdf" },
+ endTime: Date.now() - 60 * 60 * 1000, // 1 hour ago
+ target: { path: "/path/to/oldDownload2.pdf", exists: true },
+ succeeded: true,
+ refresh: async () => {},
+ };
+ // Add some older downloads and check that they are in order
+ downloadsManager.onDownloadAdded(olderDownload1);
+ downloadsManager.onDownloadAdded(olderDownload2);
+ downloadsManager.onDownloadAdded(newDownload);
+ const results = await downloadsManager.getDownloads(Infinity, {
+ numItems: 5,
+ onlySucceeded: true,
+ onlyExists: true,
+ });
+ assert.equal(results.length, 3);
+ assert.equal(results[0].url, newDownload.source.url);
+ assert.equal(results[1].url, olderDownload2.source.url);
+ assert.equal(results[2].url, olderDownload1.source.url);
+ });
+ it("should format the description properly if there is no file type", async () => {
+ newDownload.target.path = null;
+ downloadsManager.onDownloadAdded(newDownload);
+ const results = await downloadsManager.getDownloads(Infinity, {
+ numItems: 5,
+ onlySucceeded: true,
+ onlyExists: true,
+ });
+ assert.equal(results.length, 1);
+ assert.equal(results[0].description, "1.5 MB"); // see unit-entry.js to see where this comes from
+ });
+ });
+ describe("#onDownloadRemoved", () => {
+ let newDownload;
+ beforeEach(() => {
+ downloadsManager._downloadItems.clear();
+ newDownload = {
+ source: { url: "https://site.com/removeMe.mov" },
+ endTime: Date.now(),
+ target: { path: "/path/to/removeMe.mov", exists: true },
+ succeeded: true,
+ refresh: async () => {},
+ };
+ downloadsManager.onDownloadAdded(newDownload);
+ });
+ it("should remove a download if it exists on onDownloadRemoved", async () => {
+ downloadsManager.onDownloadRemoved({
+ source: { url: "https://site.com/removeMe.mov" },
+ });
+ const results = await downloadsManager.getDownloads(Infinity, {
+ numItems: 5,
+ });
+ assert.deepEqual(results, []);
+ });
+ it("should dispatch DOWNLOAD_CHANGED when removing a download", () => {
+ downloadsManager._store.dispatch = sinon.spy();
+ downloadsManager.onDownloadRemoved({
+ source: { url: "https://site.com/removeMe.mov" },
+ });
+ assert.calledOnce(downloadsManager._store.dispatch);
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/lib/FaviconFeed.test.js b/browser/components/newtab/test/unit/lib/FaviconFeed.test.js
new file mode 100644
index 0000000000..9e73a97e44
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/FaviconFeed.test.js
@@ -0,0 +1,233 @@
+"use strict";
+import { FaviconFeed, fetchIconFromRedirects } from "lib/FaviconFeed.jsm";
+import { actionTypes as at } from "common/Actions.jsm";
+import { GlobalOverrider } from "test/unit/utils";
+
+const FAKE_ENDPOINT = "https://foo.com/";
+
+describe("FaviconFeed", () => {
+ let feed;
+ let globals;
+ let sandbox;
+ let clock;
+ let siteIconsPref;
+
+ beforeEach(() => {
+ clock = sinon.useFakeTimers();
+ globals = new GlobalOverrider();
+ sandbox = globals.sandbox;
+ globals.set("PlacesUtils", {
+ favicons: {
+ setAndFetchFaviconForPage: sandbox.spy(),
+ getFaviconDataForPage: () => Promise.resolve(null),
+ FAVICON_LOAD_NON_PRIVATE: 1,
+ },
+ history: {
+ TRANSITIONS: {
+ REDIRECT_TEMPORARY: 1,
+ REDIRECT_PERMANENT: 2,
+ },
+ },
+ });
+ globals.set("NewTabUtils", {
+ activityStreamProvider: { executePlacesQuery: () => Promise.resolve([]) },
+ });
+ siteIconsPref = true;
+ sandbox
+ .stub(global.Services.prefs, "getBoolPref")
+ .withArgs("browser.chrome.site_icons")
+ .callsFake(() => siteIconsPref);
+
+ feed = new FaviconFeed();
+ feed.store = {
+ dispatch: sinon.spy(),
+ getState() {
+ return this.state;
+ },
+ state: {
+ Prefs: { values: { "tippyTop.service.endpoint": FAKE_ENDPOINT } },
+ },
+ };
+ });
+ afterEach(() => {
+ clock.restore();
+ globals.restore();
+ });
+
+ it("should create a FaviconFeed", () => {
+ assert.instanceOf(feed, FaviconFeed);
+ });
+
+ describe("#fetchIcon", () => {
+ let domain;
+ let url;
+ beforeEach(() => {
+ domain = "mozilla.org";
+ url = `https://${domain}/`;
+ feed.getSite = sandbox
+ .stub()
+ .returns(Promise.resolve({ domain, image_url: `${url}/icon.png` }));
+ feed._queryForRedirects.clear();
+ });
+
+ it("should setAndFetchFaviconForPage if the url is in the TippyTop data", async () => {
+ await feed.fetchIcon(url);
+
+ assert.calledOnce(global.PlacesUtils.favicons.setAndFetchFaviconForPage);
+ assert.calledWith(
+ global.PlacesUtils.favicons.setAndFetchFaviconForPage,
+ sinon.match({ spec: url }),
+ { ref: "tippytop", spec: `${url}/icon.png` },
+ false,
+ global.PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
+ null,
+ undefined
+ );
+ });
+ it("should NOT setAndFetchFaviconForPage if site_icons pref is false", async () => {
+ siteIconsPref = false;
+
+ await feed.fetchIcon(url);
+
+ assert.notCalled(global.PlacesUtils.favicons.setAndFetchFaviconForPage);
+ });
+ it("should NOT setAndFetchFaviconForPage if the url is NOT in the TippyTop data", async () => {
+ feed.getSite = sandbox.stub().returns(Promise.resolve(null));
+ await feed.fetchIcon("https://example.com");
+
+ assert.notCalled(global.PlacesUtils.favicons.setAndFetchFaviconForPage);
+ });
+ it("should issue a fetchIconFromRedirects if the url is NOT in the TippyTop data", async () => {
+ feed.getSite = sandbox.stub().returns(Promise.resolve(null));
+ sandbox.spy(global.Services.tm, "idleDispatchToMainThread");
+
+ await feed.fetchIcon("https://example.com");
+
+ assert.calledOnce(global.Services.tm.idleDispatchToMainThread);
+ });
+ it("should only issue fetchIconFromRedirects once on the same url", async () => {
+ feed.getSite = sandbox.stub().returns(Promise.resolve(null));
+ sandbox.spy(global.Services.tm, "idleDispatchToMainThread");
+
+ await feed.fetchIcon("https://example.com");
+ await feed.fetchIcon("https://example.com");
+
+ assert.calledOnce(global.Services.tm.idleDispatchToMainThread);
+ });
+ it("should issue fetchIconFromRedirects twice on two different urls", async () => {
+ feed.getSite = sandbox.stub().returns(Promise.resolve(null));
+ sandbox.spy(global.Services.tm, "idleDispatchToMainThread");
+
+ await feed.fetchIcon("https://example.com");
+ await feed.fetchIcon("https://another.example.com");
+
+ assert.calledTwice(global.Services.tm.idleDispatchToMainThread);
+ });
+ });
+
+ describe("#getSite", () => {
+ it("should return site data if RemoteSettings has an entry for the domain", async () => {
+ const get = () =>
+ Promise.resolve([{ domain: "example.com", image_url: "foo.img" }]);
+ feed._tippyTop = { get };
+ const site = await feed.getSite("example.com");
+ assert.equal(site.domain, "example.com");
+ });
+ it("should return null if RemoteSettings doesn't have an entry for the domain", async () => {
+ const get = () => Promise.resolve([]);
+ feed._tippyTop = { get };
+ const site = await feed.getSite("example.com");
+ assert.isNull(site);
+ });
+ it("should lazy init _tippyTop", async () => {
+ assert.isUndefined(feed._tippyTop);
+ await feed.getSite("example.com");
+ assert.ok(feed._tippyTop);
+ });
+ });
+
+ describe("#onAction", () => {
+ it("should fetchIcon on RICH_ICON_MISSING", async () => {
+ feed.fetchIcon = sinon.spy();
+ const url = "https://mozilla.org";
+ feed.onAction({ type: at.RICH_ICON_MISSING, data: { url } });
+ assert.calledOnce(feed.fetchIcon);
+ assert.calledWith(feed.fetchIcon, url);
+ });
+ });
+
+ describe("#fetchIconFromRedirects", () => {
+ let domain;
+ let url;
+ let iconUrl;
+
+ beforeEach(() => {
+ domain = "mozilla.org";
+ url = `https://${domain}/`;
+ iconUrl = `${url}/icon.png`;
+ });
+ it("should setAndFetchFaviconForPage if the url was redirected with a icon", async () => {
+ sandbox
+ .stub(global.NewTabUtils.activityStreamProvider, "executePlacesQuery")
+ .resolves([
+ { visit_id: 1, url: domain },
+ { visit_id: 2, url },
+ ]);
+ sandbox
+ .stub(global.PlacesUtils.favicons, "getFaviconDataForPage")
+ .callsArgWith(1, { spec: iconUrl }, 0, null, null, 96);
+
+ await fetchIconFromRedirects(domain);
+
+ assert.calledOnce(global.PlacesUtils.favicons.setAndFetchFaviconForPage);
+ assert.calledWith(
+ global.PlacesUtils.favicons.setAndFetchFaviconForPage,
+ sinon.match({ spec: domain }),
+ { spec: iconUrl },
+ false,
+ global.PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE,
+ null,
+ undefined
+ );
+ });
+ it("should NOT setAndFetchFaviconForPage if the url doesn't have any redirect", async () => {
+ sandbox
+ .stub(global.NewTabUtils.activityStreamProvider, "executePlacesQuery")
+ .resolves([]);
+
+ await fetchIconFromRedirects(domain);
+
+ assert.notCalled(global.PlacesUtils.favicons.setAndFetchFaviconForPage);
+ });
+ it("should NOT setAndFetchFaviconForPage if the original url doesn't have a icon", async () => {
+ sandbox
+ .stub(global.NewTabUtils.activityStreamProvider, "executePlacesQuery")
+ .resolves([
+ { visit_id: 1, url: domain },
+ { visit_id: 2, url },
+ ]);
+ sandbox
+ .stub(global.PlacesUtils.favicons, "getFaviconDataForPage")
+ .callsArgWith(1, null, null, null, null, null);
+
+ await fetchIconFromRedirects(domain);
+
+ assert.notCalled(global.PlacesUtils.favicons.setAndFetchFaviconForPage);
+ });
+ it("should NOT setAndFetchFaviconForPage if the original url doesn't have a rich icon", async () => {
+ sandbox
+ .stub(global.NewTabUtils.activityStreamProvider, "executePlacesQuery")
+ .resolves([
+ { visit_id: 1, url: domain },
+ { visit_id: 2, url },
+ ]);
+ sandbox
+ .stub(global.PlacesUtils.favicons, "getFaviconDataForPage")
+ .callsArgWith(1, { spec: iconUrl }, 0, null, null, 16);
+
+ await fetchIconFromRedirects(domain);
+
+ assert.notCalled(global.PlacesUtils.favicons.setAndFetchFaviconForPage);
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/lib/FilterAdult.test.js b/browser/components/newtab/test/unit/lib/FilterAdult.test.js
new file mode 100644
index 0000000000..69590de54e
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/FilterAdult.test.js
@@ -0,0 +1,54 @@
+import { filterAdult } from "lib/FilterAdult.jsm";
+import { GlobalOverrider } from "test/unit/utils";
+
+describe("filterAdult", () => {
+ let hashStub;
+ let hashValue;
+ let globals;
+
+ beforeEach(() => {
+ globals = new GlobalOverrider();
+ hashStub = {
+ finish: sinon.stub().callsFake(() => hashValue),
+ init: sinon.stub(),
+ update: sinon.stub(),
+ };
+ globals.set("Cc", {
+ "@mozilla.org/security/hash;1": {
+ createInstance() {
+ return hashStub;
+ },
+ },
+ });
+ });
+
+ afterEach(() => {
+ globals.restore();
+ });
+
+ it("should default to include on unexpected urls", () => {
+ const empty = {};
+
+ const result = filterAdult([empty]);
+
+ assert.equal(result.length, 1);
+ assert.equal(result[0], empty);
+ });
+ it("should not filter out non-adult urls", () => {
+ const link = { url: "https://mozilla.org/" };
+
+ const result = filterAdult([link]);
+
+ assert.equal(result.length, 1);
+ assert.equal(result[0], link);
+ });
+ it("should filter out adult urls", () => {
+ // Use a hash value that is in the adult set
+ hashValue = "+/UCpAhZhz368iGioEO8aQ==";
+ const link = { url: "https://some-adult-site/" };
+
+ const result = filterAdult([link]);
+
+ assert.equal(result.length, 0);
+ });
+});
diff --git a/browser/components/newtab/test/unit/lib/HighlightsFeed.test.js b/browser/components/newtab/test/unit/lib/HighlightsFeed.test.js
new file mode 100644
index 0000000000..2b93e6e008
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/HighlightsFeed.test.js
@@ -0,0 +1,819 @@
+"use strict";
+
+import { actionTypes as at } from "common/Actions.jsm";
+import { Dedupe } from "common/Dedupe.jsm";
+import { GlobalOverrider } from "test/unit/utils";
+import injector from "inject!lib/HighlightsFeed.jsm";
+import { Screenshots } from "lib/Screenshots.jsm";
+
+const FAKE_LINKS = new Array(20)
+ .fill(null)
+ .map((v, i) => ({ url: `http://www.site${i}.com` }));
+const FAKE_IMAGE = "data123";
+
+describe("Highlights Feed", () => {
+ let HighlightsFeed;
+ let SECTION_ID;
+ let SYNC_BOOKMARKS_FINISHED_EVENT;
+ let BOOKMARKS_RESTORE_SUCCESS_EVENT;
+ let BOOKMARKS_RESTORE_FAILED_EVENT;
+ let feed;
+ let globals;
+ let sandbox;
+ let links;
+ let fakeScreenshot;
+ let fakeNewTabUtils;
+ let filterAdultStub;
+ let sectionsManagerStub;
+ let downloadsManagerStub;
+ let shortURLStub;
+ let fakePageThumbs;
+
+ beforeEach(() => {
+ globals = new GlobalOverrider();
+ sandbox = globals.sandbox;
+ fakeNewTabUtils = {
+ activityStreamLinks: {
+ getHighlights: sandbox.spy(() => Promise.resolve(links)),
+ deletePocketEntry: sandbox.spy(() => Promise.resolve({})),
+ archivePocketEntry: sandbox.spy(() => Promise.resolve({})),
+ },
+ activityStreamProvider: {
+ _processHighlights: sandbox.spy(l => l.slice(0, 1)),
+ },
+ };
+ sectionsManagerStub = {
+ onceInitialized: sinon.stub().callsFake(callback => callback()),
+ enableSection: sinon.spy(),
+ disableSection: sinon.spy(),
+ updateSection: sinon.spy(),
+ updateSectionCard: sinon.spy(),
+ sections: new Map([["highlights", { id: "highlights" }]]),
+ };
+ downloadsManagerStub = sinon.stub().returns({
+ getDownloads: () => [{ url: "https://site.com/download" }],
+ onAction: sinon.spy(),
+ init: sinon.spy(),
+ });
+ fakeScreenshot = {
+ getScreenshotForURL: sandbox.spy(() => Promise.resolve(FAKE_IMAGE)),
+ maybeCacheScreenshot: Screenshots.maybeCacheScreenshot,
+ _shouldGetScreenshots: sinon.stub().returns(true),
+ };
+ filterAdultStub = sinon.stub().returns([]);
+ shortURLStub = sinon
+ .stub()
+ .callsFake(site => site.url.match(/\/([^/]+)/)[1]);
+ fakePageThumbs = {
+ addExpirationFilter: sinon.stub(),
+ removeExpirationFilter: sinon.stub(),
+ };
+
+ globals.set("NewTabUtils", fakeNewTabUtils);
+ globals.set("PageThumbs", fakePageThumbs);
+ ({
+ HighlightsFeed,
+ SECTION_ID,
+ SYNC_BOOKMARKS_FINISHED_EVENT,
+ BOOKMARKS_RESTORE_SUCCESS_EVENT,
+ BOOKMARKS_RESTORE_FAILED_EVENT,
+ } = injector({
+ "lib/FilterAdult.jsm": { filterAdult: filterAdultStub },
+ "lib/ShortURL.jsm": { shortURL: shortURLStub },
+ "lib/SectionsManager.jsm": { SectionsManager: sectionsManagerStub },
+ "lib/Screenshots.jsm": { Screenshots: fakeScreenshot },
+ "common/Dedupe.jsm": { Dedupe },
+ "lib/DownloadsManager.jsm": { DownloadsManager: downloadsManagerStub },
+ }));
+ sandbox.spy(global.Services.obs, "addObserver");
+ sandbox.spy(global.Services.obs, "removeObserver");
+ feed = new HighlightsFeed();
+ feed.store = {
+ dispatch: sinon.spy(),
+ getState() {
+ return this.state;
+ },
+ state: {
+ Prefs: {
+ values: {
+ filterAdult: false,
+ "section.highlights.includePocket": false,
+ "section.highlights.includeDownloads": false,
+ },
+ },
+ TopSites: {
+ initialized: true,
+ rows: Array(12)
+ .fill(null)
+ .map((v, i) => ({ url: `http://www.topsite${i}.com` })),
+ },
+ Sections: [{ id: "highlights", initialized: false }],
+ },
+ subscribe: sinon.stub().callsFake(cb => {
+ cb();
+ return () => {};
+ }),
+ };
+ links = FAKE_LINKS;
+ });
+ afterEach(() => {
+ globals.restore();
+ });
+
+ describe("#init", () => {
+ it("should create a HighlightsFeed", () => {
+ assert.instanceOf(feed, HighlightsFeed);
+ });
+ it("should register a expiration filter", () => {
+ assert.calledOnce(fakePageThumbs.addExpirationFilter);
+ });
+ it("should add the sync observer", () => {
+ feed.onAction({ type: at.INIT });
+ assert.calledWith(
+ global.Services.obs.addObserver,
+ feed,
+ SYNC_BOOKMARKS_FINISHED_EVENT
+ );
+ assert.calledWith(
+ global.Services.obs.addObserver,
+ feed,
+ BOOKMARKS_RESTORE_SUCCESS_EVENT
+ );
+ assert.calledWith(
+ global.Services.obs.addObserver,
+ feed,
+ BOOKMARKS_RESTORE_FAILED_EVENT
+ );
+ });
+ it("should call SectionsManager.onceInitialized on INIT", () => {
+ feed.onAction({ type: at.INIT });
+ assert.calledOnce(sectionsManagerStub.onceInitialized);
+ });
+ it("should enable its section", () => {
+ feed.onAction({ type: at.INIT });
+ assert.calledOnce(sectionsManagerStub.enableSection);
+ assert.calledWith(sectionsManagerStub.enableSection, SECTION_ID);
+ });
+ it("should fetch highlights on postInit", () => {
+ feed.fetchHighlights = sinon.spy();
+ feed.postInit();
+ assert.calledOnce(feed.fetchHighlights);
+ });
+ it("should hook up the store for the DownloadsManager", () => {
+ feed.onAction({ type: at.INIT });
+ assert.calledOnce(feed.downloadsManager.init);
+ });
+ });
+ describe("#observe", () => {
+ beforeEach(() => {
+ feed.fetchHighlights = sinon.spy();
+ });
+ it("should fetch higlights when we are done a sync for bookmarks", () => {
+ feed.observe(null, SYNC_BOOKMARKS_FINISHED_EVENT, "bookmarks");
+ assert.calledWith(feed.fetchHighlights, { broadcast: true });
+ });
+ it("should fetch highlights after a successful import", () => {
+ feed.observe(null, BOOKMARKS_RESTORE_SUCCESS_EVENT, "html");
+ assert.calledWith(feed.fetchHighlights, { broadcast: true });
+ });
+ it("should fetch highlights after a failed import", () => {
+ feed.observe(null, BOOKMARKS_RESTORE_FAILED_EVENT, "json");
+ assert.calledWith(feed.fetchHighlights, { broadcast: true });
+ });
+ it("should not fetch higlights when we are doing a sync for something that is not bookmarks", () => {
+ feed.observe(null, SYNC_BOOKMARKS_FINISHED_EVENT, "tabs");
+ assert.notCalled(feed.fetchHighlights);
+ });
+ it("should not fetch higlights for other events", () => {
+ feed.observe(null, "someotherevent", "bookmarks");
+ assert.notCalled(feed.fetchHighlights);
+ });
+ });
+ describe("#filterForThumbnailExpiration", () => {
+ it("should pass rows.urls to the callback provided", () => {
+ const rows = [{ url: "foo.com" }, { url: "bar.com" }];
+ feed.store.state.Sections = [
+ { id: "highlights", rows, initialized: true },
+ ];
+ const stub = sinon.stub();
+
+ feed.filterForThumbnailExpiration(stub);
+
+ assert.calledOnce(stub);
+ assert.calledWithExactly(
+ stub,
+ rows.map(r => r.url)
+ );
+ });
+ it("should include preview_image_url (if present) in the callback results", () => {
+ const rows = [
+ { url: "foo.com" },
+ { url: "bar.com", preview_image_url: "bar.jpg" },
+ ];
+ feed.store.state.Sections = [
+ { id: "highlights", rows, initialized: true },
+ ];
+ const stub = sinon.stub();
+
+ feed.filterForThumbnailExpiration(stub);
+
+ assert.calledOnce(stub);
+ assert.calledWithExactly(stub, ["foo.com", "bar.com", "bar.jpg"]);
+ });
+ it("should pass an empty array if not initialized", () => {
+ const rows = [{ url: "foo.com" }, { url: "bar.com" }];
+ feed.store.state.Sections = [{ rows, initialized: false }];
+ const stub = sinon.stub();
+
+ feed.filterForThumbnailExpiration(stub);
+
+ assert.calledOnce(stub);
+ assert.calledWithExactly(stub, []);
+ });
+ });
+ describe("#fetchHighlights", () => {
+ const fetchHighlights = async options => {
+ await feed.fetchHighlights(options);
+ return sectionsManagerStub.updateSection.firstCall.args[1].rows;
+ };
+ it("should return early if TopSites are not initialised", async () => {
+ sandbox.spy(feed.linksCache, "request");
+ feed.store.state.TopSites.initialized = false;
+ feed.store.state.Prefs.values["feeds.topsites"] = true;
+ feed.store.state.Prefs.values["feeds.system.topsites"] = true;
+
+ // Initially TopSites is uninitialised and fetchHighlights should return.
+ await feed.fetchHighlights();
+
+ assert.notCalled(fakeNewTabUtils.activityStreamLinks.getHighlights);
+ assert.notCalled(feed.linksCache.request);
+ });
+ it("should return early if Sections are not initialised", async () => {
+ sandbox.spy(feed.linksCache, "request");
+ feed.store.state.TopSites.initialized = true;
+ feed.store.state.Prefs.values["feeds.topsites"] = true;
+ feed.store.state.Prefs.values["feeds.system.topsites"] = true;
+ feed.store.state.Sections = [];
+
+ await feed.fetchHighlights();
+
+ assert.notCalled(fakeNewTabUtils.activityStreamLinks.getHighlights);
+ assert.notCalled(feed.linksCache.request);
+ });
+ it("should fetch Highlights if TopSites are initialised", async () => {
+ sandbox.spy(feed.linksCache, "request");
+ // fetchHighlights should continue
+ feed.store.state.TopSites.initialized = true;
+
+ await feed.fetchHighlights();
+
+ assert.calledOnce(feed.linksCache.request);
+ assert.calledOnce(fakeNewTabUtils.activityStreamLinks.getHighlights);
+ });
+ it("should chronologically order highlight data types", async () => {
+ links = [
+ {
+ url: "https://site0.com",
+ type: "bookmark",
+ bookmarkGuid: "1234",
+ date_added: Date.now() - 80,
+ }, // 3rd newest
+ {
+ url: "https://site1.com",
+ type: "history",
+ bookmarkGuid: "1234",
+ date_added: Date.now() - 60,
+ }, // append at the end
+ {
+ url: "https://site2.com",
+ type: "history",
+ date_added: Date.now() - 160,
+ }, // append at the end
+ {
+ url: "https://site3.com",
+ type: "history",
+ date_added: Date.now() - 60,
+ }, // append at the end
+ { url: "https://site4.com", type: "pocket", date_added: Date.now() }, // newest highlight
+ {
+ url: "https://site5.com",
+ type: "pocket",
+ date_added: Date.now() - 100,
+ }, // 4th newest
+ {
+ url: "https://site6.com",
+ type: "bookmark",
+ bookmarkGuid: "1234",
+ date_added: Date.now() - 40,
+ }, // 2nd newest
+ ];
+ const expectedChronological = [4, 6, 0, 5];
+ const expectedHistory = [1, 2, 3];
+
+ let highlights = await fetchHighlights();
+
+ [...expectedChronological, ...expectedHistory].forEach((link, index) => {
+ assert.propertyVal(
+ highlights[index],
+ "url",
+ links[link].url,
+ `highlight[${index}] should be link[${link}]`
+ );
+ });
+ });
+ it("should fetch Highlights if TopSites are not enabled", async () => {
+ sandbox.spy(feed.linksCache, "request");
+ feed.store.state.Prefs.values["feeds.system.topsites"] = false;
+
+ await feed.fetchHighlights();
+
+ assert.calledOnce(feed.linksCache.request);
+ assert.calledOnce(fakeNewTabUtils.activityStreamLinks.getHighlights);
+ });
+ it("should fetch Highlights if TopSites are not shown on NTP", async () => {
+ sandbox.spy(feed.linksCache, "request");
+ feed.store.state.Prefs.values["feeds.topsites"] = false;
+
+ await feed.fetchHighlights();
+
+ assert.calledOnce(feed.linksCache.request);
+ assert.calledOnce(fakeNewTabUtils.activityStreamLinks.getHighlights);
+ });
+ it("should add hostname and hasImage to each link", async () => {
+ links = [{ url: "https://mozilla.org" }];
+
+ const highlights = await fetchHighlights();
+
+ assert.equal(highlights[0].hostname, "mozilla.org");
+ assert.equal(highlights[0].hasImage, true);
+ });
+ it("should add an existing image if it exists to the link without calling fetchImage", async () => {
+ links = [{ url: "https://mozilla.org", image: FAKE_IMAGE }];
+ sinon.spy(feed, "fetchImage");
+
+ const highlights = await fetchHighlights();
+
+ assert.equal(highlights[0].image, FAKE_IMAGE);
+ assert.notCalled(feed.fetchImage);
+ });
+ it("should call fetchImage with the correct arguments for new links", async () => {
+ links = [
+ {
+ url: "https://mozilla.org",
+ preview_image_url: "https://mozilla.org/preview.jog",
+ },
+ ];
+ sinon.spy(feed, "fetchImage");
+
+ await feed.fetchHighlights();
+
+ assert.calledOnce(feed.fetchImage);
+ const [arg] = feed.fetchImage.firstCall.args;
+ assert.propertyVal(arg, "url", links[0].url);
+ assert.propertyVal(arg, "preview_image_url", links[0].preview_image_url);
+ });
+ it("should not include any links already in Top Sites", async () => {
+ links = [
+ { url: "https://mozilla.org" },
+ { url: "http://www.topsite0.com" },
+ { url: "http://www.topsite1.com" },
+ { url: "http://www.topsite2.com" },
+ ];
+
+ const highlights = await fetchHighlights();
+
+ assert.equal(highlights.length, 1);
+ assert.equal(highlights[0].url, links[0].url);
+ });
+ it("should include bookmark but not history already in Top Sites", async () => {
+ links = [
+ { url: "http://www.topsite0.com", type: "bookmark" },
+ { url: "http://www.topsite1.com", type: "history" },
+ ];
+
+ const highlights = await fetchHighlights();
+
+ assert.equal(highlights.length, 1);
+ assert.equal(highlights[0].url, links[0].url);
+ });
+ it("should not include history of same hostname as a bookmark", async () => {
+ links = [
+ { url: "https://site.com/bookmark", type: "bookmark" },
+ { url: "https://site.com/history", type: "history" },
+ ];
+
+ const highlights = await fetchHighlights();
+
+ assert.equal(highlights.length, 1);
+ assert.equal(highlights[0].url, links[0].url);
+ });
+ it("should take the first history of a hostname", async () => {
+ links = [
+ { url: "https://site.com/first", type: "history" },
+ { url: "https://site.com/second", type: "history" },
+ { url: "https://other", type: "history" },
+ ];
+
+ const highlights = await fetchHighlights();
+
+ assert.equal(highlights.length, 2);
+ assert.equal(highlights[0].url, links[0].url);
+ assert.equal(highlights[1].url, links[2].url);
+ });
+ it("should take a bookmark, a pocket, and downloaded item of the same hostname", async () => {
+ links = [
+ { url: "https://site.com/bookmark", type: "bookmark" },
+ { url: "https://site.com/pocket", type: "pocket" },
+ { url: "https://site.com/download", type: "download" },
+ ];
+
+ const highlights = await fetchHighlights();
+
+ assert.equal(highlights.length, 3);
+ assert.equal(highlights[0].url, links[0].url);
+ assert.equal(highlights[1].url, links[1].url);
+ assert.equal(highlights[2].url, links[2].url);
+ });
+ it("should includePocket pocket items when pref is true", async () => {
+ feed.store.state.Prefs.values["section.highlights.includePocket"] = true;
+ sandbox.spy(feed.linksCache, "request");
+ await feed.fetchHighlights();
+
+ assert.propertyVal(
+ feed.linksCache.request.firstCall.args[0],
+ "excludePocket",
+ false
+ );
+ });
+ it("should not includePocket pocket items when pref is false", async () => {
+ sandbox.spy(feed.linksCache, "request");
+ await feed.fetchHighlights();
+
+ assert.propertyVal(
+ feed.linksCache.request.firstCall.args[0],
+ "excludePocket",
+ true
+ );
+ });
+ it("should not include downloads when includeDownloads pref is false", async () => {
+ links = [
+ { url: "https://site.com/bookmark", type: "bookmark" },
+ { url: "https://site.com/pocket", type: "pocket" },
+ ];
+
+ // Check that we don't have the downloaded item in highlights
+ const highlights = await fetchHighlights();
+ assert.equal(highlights.length, 2);
+ assert.equal(highlights[0].url, links[0].url);
+ assert.equal(highlights[1].url, links[1].url);
+ });
+ it("should include downloads when includeDownloads pref is true", async () => {
+ feed.store.state.Prefs.values[
+ "section.highlights.includeDownloads"
+ ] = true;
+ links = [
+ { url: "https://site.com/bookmark", type: "bookmark" },
+ { url: "https://site.com/pocket", type: "pocket" },
+ ];
+
+ // Check that we did get the downloaded item in highlights
+ const highlights = await fetchHighlights();
+ assert.equal(highlights.length, 3);
+ assert.equal(highlights[0].url, links[0].url);
+ assert.equal(highlights[1].url, links[1].url);
+ assert.equal(highlights[2].url, "https://site.com/download");
+
+ assert.propertyVal(highlights[2], "type", "download");
+ });
+ it("should only take 1 download", async () => {
+ feed.store.state.Prefs.values[
+ "section.highlights.includeDownloads"
+ ] = true;
+ feed.downloadsManager.getDownloads = () => [
+ { url: "https://site1.com/download" },
+ { url: "https://site2.com/download" },
+ ];
+ links = [{ url: "https://site.com/bookmark", type: "bookmark" }];
+
+ // Check that we did get the most single recent downloaded item in highlights
+ const highlights = await fetchHighlights();
+ assert.equal(highlights.length, 2);
+ assert.equal(highlights[0].url, links[0].url);
+ assert.equal(highlights[1].url, "https://site1.com/download");
+ });
+ it("should sort bookmarks, pocket, and downloads chronologically", async () => {
+ feed.store.state.Prefs.values[
+ "section.highlights.includeDownloads"
+ ] = true;
+ feed.downloadsManager.getDownloads = () => [
+ {
+ url: "https://site1.com/download",
+ type: "download",
+ date_added: Date.now(),
+ },
+ ];
+ links = [
+ {
+ url: "https://site.com/bookmark",
+ type: "bookmark",
+ date_added: Date.now() - 10000,
+ },
+ {
+ url: "https://site2.com/pocket",
+ type: "pocket",
+ date_added: Date.now() - 5000,
+ },
+ {
+ url: "https://site3.com/visited",
+ type: "history",
+ date_added: Date.now(),
+ },
+ ];
+
+ // Check that the higlights are ordered chronologically by their 'date_added'
+ const highlights = await fetchHighlights();
+ assert.equal(highlights.length, 4);
+ assert.equal(highlights[0].url, "https://site1.com/download");
+ assert.equal(highlights[1].url, links[1].url);
+ assert.equal(highlights[2].url, links[0].url);
+ assert.equal(highlights[3].url, links[2].url); // history item goes last
+ });
+ it("should set type to bookmark if there is a bookmarkGuid", async () => {
+ feed.store.state.Prefs.values[
+ "section.highlights.includeBookmarks"
+ ] = true;
+ links = [
+ {
+ url: "https://mozilla.org",
+ type: "history",
+ bookmarkGuid: "1234567890",
+ },
+ ];
+
+ const highlights = await fetchHighlights();
+
+ assert.equal(highlights[0].type, "bookmark");
+ });
+ it("should keep history type if there is a bookmarkGuid but don't include bookmarks", async () => {
+ feed.store.state.Prefs.values[
+ "section.highlights.includeBookmarks"
+ ] = false;
+ links = [
+ {
+ url: "https://mozilla.org",
+ type: "history",
+ bookmarkGuid: "1234567890",
+ },
+ ];
+
+ const highlights = await fetchHighlights();
+
+ assert.propertyVal(highlights[0], "type", "history");
+ });
+ it("should not filter out adult pages when pref is false", async () => {
+ await feed.fetchHighlights();
+
+ assert.notCalled(filterAdultStub);
+ });
+ it("should filter out adult pages when pref is true", async () => {
+ feed.store.state.Prefs.values.filterAdult = true;
+
+ const highlights = await fetchHighlights();
+
+ // The stub filters out everything
+ assert.calledOnce(filterAdultStub);
+ assert.equal(highlights.length, 0);
+ });
+ it("should not expose internal link properties", async () => {
+ const highlights = await fetchHighlights();
+
+ const internal = Object.keys(highlights[0]).filter(key =>
+ key.startsWith("__")
+ );
+ assert.equal(internal.join(""), "");
+ });
+ it("should broadcast if feed is not initialized", async () => {
+ links = [];
+ await fetchHighlights();
+
+ assert.calledOnce(sectionsManagerStub.updateSection);
+ assert.calledWithExactly(
+ sectionsManagerStub.updateSection,
+ SECTION_ID,
+ { rows: [] },
+ true,
+ undefined
+ );
+ });
+ it("should broadcast if options.broadcast is true", async () => {
+ links = [];
+ feed.store.state.Sections[0].initialized = true;
+ await fetchHighlights({ broadcast: true });
+
+ assert.calledOnce(sectionsManagerStub.updateSection);
+ assert.calledWithExactly(
+ sectionsManagerStub.updateSection,
+ SECTION_ID,
+ { rows: [] },
+ true,
+ undefined
+ );
+ });
+ it("should not broadcast if options.broadcast is false and initialized is true", async () => {
+ links = [];
+ feed.store.state.Sections[0].initialized = true;
+ await fetchHighlights({ broadcast: false });
+
+ assert.calledOnce(sectionsManagerStub.updateSection);
+ assert.calledWithExactly(
+ sectionsManagerStub.updateSection,
+ SECTION_ID,
+ { rows: [] },
+ false,
+ undefined
+ );
+ });
+ });
+ describe("#fetchImage", () => {
+ const FAKE_URL = "https://mozilla.org";
+ const FAKE_IMAGE_URL = "https://mozilla.org/preview.jpg";
+ function fetchImage(page) {
+ return feed.fetchImage(
+ Object.assign({ __sharedCache: { updateLink() {} } }, page)
+ );
+ }
+ it("should capture the image, if available", async () => {
+ await fetchImage({
+ preview_image_url: FAKE_IMAGE_URL,
+ url: FAKE_URL,
+ });
+
+ assert.calledOnce(fakeScreenshot.getScreenshotForURL);
+ assert.calledWith(fakeScreenshot.getScreenshotForURL, FAKE_IMAGE_URL);
+ });
+ it("should fall back to capturing a screenshot", async () => {
+ await fetchImage({ url: FAKE_URL });
+
+ assert.calledOnce(fakeScreenshot.getScreenshotForURL);
+ assert.calledWith(fakeScreenshot.getScreenshotForURL, FAKE_URL);
+ });
+ it("should call SectionsManager.updateSectionCard with the right arguments", async () => {
+ await fetchImage({
+ preview_image_url: FAKE_IMAGE_URL,
+ url: FAKE_URL,
+ });
+
+ assert.calledOnce(sectionsManagerStub.updateSectionCard);
+ assert.calledWith(
+ sectionsManagerStub.updateSectionCard,
+ "highlights",
+ FAKE_URL,
+ { image: FAKE_IMAGE },
+ true
+ );
+ });
+ it("should not update the card with the image", async () => {
+ const card = {
+ preview_image_url: FAKE_IMAGE_URL,
+ url: FAKE_URL,
+ };
+
+ await fetchImage(card);
+
+ assert.notProperty(card, "image");
+ });
+ });
+ describe("#uninit", () => {
+ it("should disable its section", () => {
+ feed.onAction({ type: at.UNINIT });
+ assert.calledOnce(sectionsManagerStub.disableSection);
+ assert.calledWith(sectionsManagerStub.disableSection, SECTION_ID);
+ });
+ it("should remove the expiration filter", () => {
+ feed.onAction({ type: at.UNINIT });
+ assert.calledOnce(fakePageThumbs.removeExpirationFilter);
+ });
+ it("should remove the sync and Places observers", () => {
+ feed.onAction({ type: at.UNINIT });
+ assert.calledWith(
+ global.Services.obs.removeObserver,
+ feed,
+ SYNC_BOOKMARKS_FINISHED_EVENT
+ );
+ assert.calledWith(
+ global.Services.obs.removeObserver,
+ feed,
+ BOOKMARKS_RESTORE_SUCCESS_EVENT
+ );
+ assert.calledWith(
+ global.Services.obs.removeObserver,
+ feed,
+ BOOKMARKS_RESTORE_FAILED_EVENT
+ );
+ });
+ });
+ describe("#onAction", () => {
+ it("should relay all actions to DownloadsManager.onAction", () => {
+ let action = {
+ type: at.COPY_DOWNLOAD_LINK,
+ data: { url: "foo.png" },
+ _target: {},
+ };
+ feed.onAction(action);
+ assert.calledWith(feed.downloadsManager.onAction, action);
+ });
+ it("should fetch highlights on SYSTEM_TICK", async () => {
+ await feed.fetchHighlights();
+ feed.fetchHighlights = sinon.spy();
+ feed.onAction({ type: at.SYSTEM_TICK });
+
+ assert.calledOnce(feed.fetchHighlights);
+ assert.calledWithExactly(feed.fetchHighlights, {
+ broadcast: false,
+ isStartup: false,
+ });
+ });
+ it("should fetch highlights on PREF_CHANGED for include prefs", async () => {
+ feed.fetchHighlights = sinon.spy();
+
+ feed.onAction({
+ type: at.PREF_CHANGED,
+ data: { name: "section.highlights.includeBookmarks" },
+ });
+
+ assert.calledOnce(feed.fetchHighlights);
+ assert.calledWith(feed.fetchHighlights, { broadcast: true });
+ });
+ it("should not fetch highlights on PREF_CHANGED for other prefs", async () => {
+ feed.fetchHighlights = sinon.spy();
+
+ feed.onAction({
+ type: at.PREF_CHANGED,
+ data: { name: "section.topstories.pocketCta" },
+ });
+
+ assert.notCalled(feed.fetchHighlights);
+ });
+ it("should fetch highlights on PLACES_HISTORY_CLEARED", async () => {
+ await feed.fetchHighlights();
+ feed.fetchHighlights = sinon.spy();
+ feed.onAction({ type: at.PLACES_HISTORY_CLEARED });
+ assert.calledOnce(feed.fetchHighlights);
+ assert.calledWith(feed.fetchHighlights, { broadcast: true });
+ });
+ it("should fetch highlights on DOWNLOAD_CHANGED", async () => {
+ await feed.fetchHighlights();
+ feed.fetchHighlights = sinon.spy();
+ feed.onAction({ type: at.DOWNLOAD_CHANGED });
+ assert.calledOnce(feed.fetchHighlights);
+ assert.calledWith(feed.fetchHighlights, { broadcast: true });
+ });
+ it("should fetch highlights on PLACES_LINKS_CHANGED", async () => {
+ await feed.fetchHighlights();
+ feed.fetchHighlights = sinon.spy();
+ sandbox.stub(feed.linksCache, "expire");
+
+ feed.onAction({ type: at.PLACES_LINKS_CHANGED });
+ assert.calledOnce(feed.fetchHighlights);
+ assert.calledWith(feed.fetchHighlights, { broadcast: false });
+ assert.calledOnce(feed.linksCache.expire);
+ });
+ it("should fetch highlights on PLACES_LINK_BLOCKED", async () => {
+ await feed.fetchHighlights();
+ feed.fetchHighlights = sinon.spy();
+ feed.onAction({ type: at.PLACES_LINK_BLOCKED });
+ assert.calledOnce(feed.fetchHighlights);
+ assert.calledWith(feed.fetchHighlights, { broadcast: true });
+ });
+ it("should fetch highlights and expire the cache on PLACES_SAVED_TO_POCKET", async () => {
+ await feed.fetchHighlights();
+ feed.fetchHighlights = sinon.spy();
+ sandbox.stub(feed.linksCache, "expire");
+
+ feed.onAction({ type: at.PLACES_SAVED_TO_POCKET });
+ assert.calledOnce(feed.fetchHighlights);
+ assert.calledWith(feed.fetchHighlights, { broadcast: false });
+ assert.calledOnce(feed.linksCache.expire);
+ });
+ it("should call fetchHighlights with broadcast false on TOP_SITES_UPDATED", () => {
+ sandbox.stub(feed, "fetchHighlights");
+ feed.onAction({ type: at.TOP_SITES_UPDATED });
+
+ assert.calledOnce(feed.fetchHighlights);
+ assert.calledWithExactly(feed.fetchHighlights, {
+ broadcast: false,
+ isStartup: false,
+ });
+ });
+ it("should call fetchHighlights when deleting or archiving from Pocket", async () => {
+ feed.fetchHighlights = sinon.spy();
+ feed.onAction({
+ type: at.POCKET_LINK_DELETED_OR_ARCHIVED,
+ data: { pocket_id: 12345 },
+ });
+
+ assert.calledOnce(feed.fetchHighlights);
+ assert.calledWithExactly(feed.fetchHighlights, { broadcast: true });
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/lib/LinksCache.test.js b/browser/components/newtab/test/unit/lib/LinksCache.test.js
new file mode 100644
index 0000000000..44c8c74a93
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/LinksCache.test.js
@@ -0,0 +1,16 @@
+import { LinksCache } from "lib/LinksCache.jsm";
+
+describe("LinksCache", () => {
+ it("throws when failing request", async () => {
+ const cache = new LinksCache();
+
+ let rejected = false;
+ try {
+ await cache.request();
+ } catch (error) {
+ rejected = true;
+ }
+
+ assert(rejected);
+ });
+});
diff --git a/browser/components/newtab/test/unit/lib/MomentsPageHub.test.js b/browser/components/newtab/test/unit/lib/MomentsPageHub.test.js
new file mode 100644
index 0000000000..e4ec5fe483
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/MomentsPageHub.test.js
@@ -0,0 +1,336 @@
+import { GlobalOverrider } from "test/unit/utils";
+import { PanelTestProvider } from "lib/PanelTestProvider.jsm";
+import { _MomentsPageHub } from "lib/MomentsPageHub.jsm";
+const HOMEPAGE_OVERRIDE_PREF = "browser.startup.homepage_override.once";
+
+describe("MomentsPageHub", () => {
+ let globals;
+ let sandbox;
+ let instance;
+ let handleMessageRequestStub;
+ let addImpressionStub;
+ let blockMessageByIdStub;
+ let sendTelemetryStub;
+ let getStringPrefStub;
+ let setStringPrefStub;
+ let setIntervalStub;
+ let clearIntervalStub;
+
+ beforeEach(async () => {
+ globals = new GlobalOverrider();
+ sandbox = sinon.createSandbox();
+ instance = new _MomentsPageHub();
+ const messages = (await PanelTestProvider.getMessages()).filter(
+ ({ template }) => template === "update_action"
+ );
+ handleMessageRequestStub = sandbox.stub().resolves(messages);
+ addImpressionStub = sandbox.stub();
+ blockMessageByIdStub = sandbox.stub();
+ getStringPrefStub = sandbox.stub();
+ setStringPrefStub = sandbox.stub();
+ setIntervalStub = sandbox.stub();
+ clearIntervalStub = sandbox.stub();
+ sendTelemetryStub = sandbox.stub();
+ globals.set({
+ setInterval: setIntervalStub,
+ clearInterval: clearIntervalStub,
+ Services: {
+ prefs: {
+ getStringPref: getStringPrefStub,
+ setStringPref: setStringPrefStub,
+ },
+ telemetry: {
+ recordEvent: () => {},
+ },
+ },
+ });
+ });
+
+ afterEach(() => {
+ sandbox.restore();
+ globals.restore();
+ });
+
+ it("should create an instance", async () => {
+ setIntervalStub.returns(42);
+ assert.ok(instance);
+ await instance.init(Promise.resolve(), {
+ handleMessageRequest: handleMessageRequestStub,
+ addImpression: addImpressionStub,
+ blockMessageById: blockMessageByIdStub,
+ });
+ assert.equal(instance.state._intervalId, 42);
+ });
+
+ it("should init only once", async () => {
+ assert.notCalled(handleMessageRequestStub);
+
+ await instance.init(Promise.resolve(), {
+ handleMessageRequest: handleMessageRequestStub,
+ addImpression: addImpressionStub,
+ blockMessageById: blockMessageByIdStub,
+ });
+ await instance.init(Promise.resolve(), {
+ handleMessageRequest: handleMessageRequestStub,
+ addImpression: addImpressionStub,
+ blockMessageById: blockMessageByIdStub,
+ });
+
+ assert.calledOnce(handleMessageRequestStub);
+
+ instance.uninit();
+
+ await instance.init(Promise.resolve(), {
+ handleMessageRequest: handleMessageRequestStub,
+ addImpression: addImpressionStub,
+ blockMessageById: blockMessageByIdStub,
+ });
+
+ assert.calledTwice(handleMessageRequestStub);
+ });
+
+ it("should uninit the instance", () => {
+ instance.uninit();
+ assert.calledOnce(clearIntervalStub);
+ });
+
+ it("should setInterval for `checkHomepageOverridePref`", async () => {
+ await instance.init(sandbox.stub().resolves(), {});
+ sandbox.stub(instance, "checkHomepageOverridePref");
+
+ assert.calledOnce(setIntervalStub);
+ assert.calledWithExactly(setIntervalStub, sinon.match.func, 5 * 60 * 1000);
+
+ assert.notCalled(instance.checkHomepageOverridePref);
+ const [cb] = setIntervalStub.firstCall.args;
+
+ cb();
+
+ assert.calledOnce(instance.checkHomepageOverridePref);
+ });
+
+ describe("#messageRequest", () => {
+ beforeEach(async () => {
+ await instance.init(Promise.resolve(), {
+ handleMessageRequest: handleMessageRequestStub,
+ addImpression: addImpressionStub,
+ blockMessageById: blockMessageByIdStub,
+ sendTelemetry: sendTelemetryStub,
+ });
+ });
+ afterEach(() => {
+ instance.uninit();
+ });
+ it("should fetch a message with the provided trigger and template", async () => {
+ await instance.messageRequest({
+ triggerId: "trigger",
+ template: "template",
+ });
+
+ assert.calledTwice(handleMessageRequestStub);
+ assert.calledWithExactly(handleMessageRequestStub, {
+ triggerId: "trigger",
+ template: "template",
+ returnAll: true,
+ });
+ });
+ it("shouldn't do anything if no message is provided", async () => {
+ // Reset the call from `instance.init`
+ setStringPrefStub.reset();
+ handleMessageRequestStub.resolves([]);
+ await instance.messageRequest({ triggerId: "trigger" });
+
+ assert.notCalled(setStringPrefStub);
+ });
+ it("should record telemetry events", async () => {
+ const startTelemetryStopwatch = sandbox.stub(
+ global.TelemetryStopwatch,
+ "start"
+ );
+ const finishTelemetryStopwatch = sandbox.stub(
+ global.TelemetryStopwatch,
+ "finish"
+ );
+
+ await instance.messageRequest({ triggerId: "trigger" });
+
+ assert.calledOnce(startTelemetryStopwatch);
+ assert.calledWithExactly(
+ startTelemetryStopwatch,
+ "MS_MESSAGE_REQUEST_TIME_MS",
+ { triggerId: "trigger" }
+ );
+ assert.calledOnce(finishTelemetryStopwatch);
+ assert.calledWithExactly(
+ finishTelemetryStopwatch,
+ "MS_MESSAGE_REQUEST_TIME_MS",
+ { triggerId: "trigger" }
+ );
+ });
+ it("should record Reach event for the Moments page experiment", async () => {
+ const momentsMessages = (await PanelTestProvider.getMessages()).filter(
+ ({ template }) => template === "update_action"
+ );
+ const messages = [
+ {
+ forReachEvent: { sent: false },
+ experimentSlug: "foo",
+ branchSlug: "bar",
+ },
+ ...momentsMessages,
+ ];
+ handleMessageRequestStub.resolves(messages);
+ sandbox.spy(global.Services.telemetry, "recordEvent");
+ sandbox.spy(instance, "executeAction");
+
+ await instance.messageRequest({ triggerId: "trigger" });
+
+ assert.calledOnce(global.Services.telemetry.recordEvent);
+ assert.calledOnce(instance.executeAction);
+ });
+ it("should not record the Reach event if it's already sent", async () => {
+ const messages = [
+ {
+ forReachEvent: { sent: true },
+ experimentSlug: "foo",
+ branchSlug: "bar",
+ },
+ ];
+ handleMessageRequestStub.resolves(messages);
+ sandbox.spy(global.Services.telemetry, "recordEvent");
+
+ await instance.messageRequest({ triggerId: "trigger" });
+
+ assert.notCalled(global.Services.telemetry.recordEvent);
+ });
+ it("should not trigger the action if it's only for the Reach event", async () => {
+ const messages = [
+ {
+ forReachEvent: { sent: false },
+ experimentSlug: "foo",
+ branchSlug: "bar",
+ },
+ ];
+ handleMessageRequestStub.resolves(messages);
+ sandbox.spy(global.Services.telemetry, "recordEvent");
+ sandbox.spy(instance, "executeAction");
+
+ await instance.messageRequest({ triggerId: "trigger" });
+
+ assert.calledOnce(global.Services.telemetry.recordEvent);
+ assert.notCalled(instance.executeAction);
+ });
+ });
+ describe("executeAction", () => {
+ beforeEach(async () => {
+ blockMessageByIdStub = sandbox.stub();
+ await instance.init(sandbox.stub().resolves(), {
+ addImpression: addImpressionStub,
+ blockMessageById: blockMessageByIdStub,
+ sendTelemetry: sendTelemetryStub,
+ });
+ });
+ it("should set HOMEPAGE_OVERRIDE_PREF on `moments-wnp` action", async () => {
+ const [msg] = await handleMessageRequestStub();
+ sandbox.useFakeTimers();
+ instance.executeAction(msg);
+
+ assert.calledOnce(setStringPrefStub);
+ assert.calledWithExactly(
+ setStringPrefStub,
+ HOMEPAGE_OVERRIDE_PREF,
+ JSON.stringify({
+ message_id: msg.id,
+ url: msg.content.action.data.url,
+ expire: instance.getExpirationDate(
+ msg.content.action.data.expireDelta
+ ),
+ })
+ );
+ });
+ it("should block after taking the action", async () => {
+ const [msg] = await handleMessageRequestStub();
+ instance.executeAction(msg);
+
+ assert.calledOnce(blockMessageByIdStub);
+ assert.calledWithExactly(blockMessageByIdStub, msg.id);
+ });
+ it("should compute expire based on expireDelta", async () => {
+ sandbox.spy(instance, "getExpirationDate");
+
+ const [msg] = await handleMessageRequestStub();
+ instance.executeAction(msg);
+
+ assert.calledOnce(instance.getExpirationDate);
+ assert.calledWithExactly(
+ instance.getExpirationDate,
+ msg.content.action.data.expireDelta
+ );
+ });
+ it("should compute expire based on expireDelta", async () => {
+ sandbox.spy(instance, "getExpirationDate");
+
+ const [msg] = await handleMessageRequestStub();
+ const msgWithExpire = {
+ ...msg,
+ content: {
+ ...msg.content,
+ action: {
+ ...msg.content.action,
+ data: { ...msg.content.action.data, expire: 41 },
+ },
+ },
+ };
+ instance.executeAction(msgWithExpire);
+
+ assert.notCalled(instance.getExpirationDate);
+ assert.calledOnce(setStringPrefStub);
+ assert.calledWithExactly(
+ setStringPrefStub,
+ HOMEPAGE_OVERRIDE_PREF,
+ JSON.stringify({
+ message_id: msg.id,
+ url: msg.content.action.data.url,
+ expire: 41,
+ })
+ );
+ });
+ it("should send user telemetry", async () => {
+ const [msg] = await handleMessageRequestStub();
+ const sendUserEventTelemetrySpy = sandbox.spy(
+ instance,
+ "sendUserEventTelemetry"
+ );
+ instance.executeAction(msg);
+
+ assert.calledOnce(sendTelemetryStub);
+ assert.calledWithExactly(sendUserEventTelemetrySpy, msg);
+ assert.calledWithExactly(sendTelemetryStub, {
+ type: "MOMENTS_PAGE_TELEMETRY",
+ data: {
+ action: "moments_user_event",
+ bucket_id: "WNP_THANK_YOU",
+ event: "MOMENTS_PAGE_SET",
+ message_id: "WNP_THANK_YOU",
+ },
+ });
+ });
+ });
+ describe("#checkHomepageOverridePref", () => {
+ let messageRequestStub;
+ beforeEach(() => {
+ messageRequestStub = sandbox.stub(instance, "messageRequest");
+ });
+ it("should catch parse errors", () => {
+ getStringPrefStub.returns({});
+
+ instance.checkHomepageOverridePref();
+
+ assert.calledOnce(messageRequestStub);
+ assert.calledWithExactly(messageRequestStub, {
+ template: "update_action",
+ triggerId: "momentsUpdate",
+ });
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/lib/NewTabInit.test.js b/browser/components/newtab/test/unit/lib/NewTabInit.test.js
new file mode 100644
index 0000000000..4fd93595ec
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/NewTabInit.test.js
@@ -0,0 +1,78 @@
+import { actionCreators as ac, actionTypes as at } from "common/Actions.jsm";
+import { NewTabInit } from "lib/NewTabInit.jsm";
+
+describe("NewTabInit", () => {
+ let instance;
+ let store;
+ let STATE;
+ const requestFromTab = portID =>
+ instance.onAction(
+ ac.AlsoToMain({ type: at.NEW_TAB_STATE_REQUEST }, portID)
+ );
+ beforeEach(() => {
+ STATE = {};
+ store = { getState: sinon.stub().returns(STATE), dispatch: sinon.stub() };
+ instance = new NewTabInit();
+ instance.store = store;
+ });
+ it("should reply with a copy of the state immediately", () => {
+ requestFromTab(123);
+
+ const resp = ac.AlsoToOneContent(
+ { type: at.NEW_TAB_INITIAL_STATE, data: STATE },
+ 123
+ );
+ assert.calledWith(store.dispatch, resp);
+ });
+ describe("early / simulated new tabs", () => {
+ const simulateTabInit = portID =>
+ instance.onAction({
+ type: at.NEW_TAB_INIT,
+ data: { portID, simulated: true },
+ });
+ beforeEach(() => {
+ simulateTabInit("foo");
+ });
+ it("should dispatch if not replied yet", () => {
+ requestFromTab("foo");
+
+ assert.calledWith(
+ store.dispatch,
+ ac.AlsoToOneContent(
+ { type: at.NEW_TAB_INITIAL_STATE, data: STATE },
+ "foo"
+ )
+ );
+ });
+ it("should dispatch once for multiple requests", () => {
+ requestFromTab("foo");
+ requestFromTab("foo");
+ requestFromTab("foo");
+
+ assert.calledOnce(store.dispatch);
+ });
+ describe("multiple tabs", () => {
+ beforeEach(() => {
+ simulateTabInit("bar");
+ });
+ it("should dispatch once to each tab", () => {
+ requestFromTab("foo");
+ requestFromTab("bar");
+ assert.calledTwice(store.dispatch);
+ requestFromTab("foo");
+ requestFromTab("bar");
+
+ assert.calledTwice(store.dispatch);
+ });
+ it("should clean up when tabs close", () => {
+ assert.propertyVal(instance._repliedEarlyTabs, "size", 2);
+ instance.onAction(ac.AlsoToMain({ type: at.NEW_TAB_UNLOAD }, "foo"));
+ assert.propertyVal(instance._repliedEarlyTabs, "size", 1);
+ instance.onAction(ac.AlsoToMain({ type: at.NEW_TAB_UNLOAD }, "foo"));
+ assert.propertyVal(instance._repliedEarlyTabs, "size", 1);
+ instance.onAction(ac.AlsoToMain({ type: at.NEW_TAB_UNLOAD }, "bar"));
+ assert.propertyVal(instance._repliedEarlyTabs, "size", 0);
+ });
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/lib/PersistentCache.test.js b/browser/components/newtab/test/unit/lib/PersistentCache.test.js
new file mode 100644
index 0000000000..dd39d246e6
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/PersistentCache.test.js
@@ -0,0 +1,131 @@
+import { GlobalOverrider } from "test/unit/utils";
+import { PersistentCache } from "lib/PersistentCache.jsm";
+
+describe("PersistentCache", () => {
+ let fakeOS;
+ let fakeJsonParse;
+ let fakeFetch;
+ let cache;
+ let filename = "cache.json";
+ let reportErrorStub;
+ let globals;
+ let sandbox;
+
+ beforeEach(() => {
+ globals = new GlobalOverrider();
+ sandbox = sinon.createSandbox();
+ fakeOS = {
+ Constants: { Path: { localProfileDir: "/foo/bar" } },
+ File: {
+ writeAtomic: sinon.stub().returns(Promise.resolve()),
+ },
+ Path: { join: () => filename },
+ };
+ fakeJsonParse = sandbox.stub().resolves({});
+ fakeFetch = sandbox.stub().resolves({ json: fakeJsonParse });
+ reportErrorStub = sandbox.stub();
+ globals.set("OS", fakeOS);
+ globals.set("Cu", { reportError: reportErrorStub });
+ globals.set("fetch", fakeFetch);
+
+ cache = new PersistentCache(filename);
+ });
+ afterEach(() => {
+ globals.restore();
+ sandbox.restore();
+ });
+
+ describe("#get", () => {
+ it("tries to fetch the file", async () => {
+ await cache.get("foo");
+ assert.calledOnce(fakeFetch);
+ });
+ it("doesnt try to parse file if it doesn't exist", async () => {
+ fakeFetch.throws();
+ await cache.get("foo");
+ assert.notCalled(fakeJsonParse);
+ });
+ it("doesnt try to fetch the file if it was already loaded", async () => {
+ await cache._load();
+ fakeFetch.resetHistory();
+ await cache.get("foo");
+ assert.notCalled(fakeFetch);
+ });
+ it("should catch and report errors", async () => {
+ fakeJsonParse.throws();
+ await cache._load();
+ assert.calledOnce(reportErrorStub);
+ });
+ it("returns data for a given cache key", async () => {
+ fakeJsonParse.resolves({ foo: "bar" });
+ let value = await cache.get("foo");
+ assert.equal(value, "bar");
+ });
+ it("returns undefined for a cache key that doesn't exist", async () => {
+ let value = await cache.get("baz");
+ assert.equal(value, undefined);
+ });
+ it("returns all the data if no cache key is specified", async () => {
+ fakeJsonParse.resolves({ foo: "bar" });
+ let value = await cache.get();
+ assert.deepEqual(value, { foo: "bar" });
+ });
+ });
+
+ describe("#set", () => {
+ it("tries to fetch the file on the first set", async () => {
+ await cache.set("foo", { x: 42 });
+ assert.calledOnce(fakeFetch);
+ });
+ it("doesnt try to fetch the file if it was already loaded", async () => {
+ cache = new PersistentCache(filename, true);
+ await cache._load();
+ fakeFetch.resetHistory();
+ await cache.set("foo", { x: 42 });
+ assert.notCalled(fakeFetch);
+ });
+ it("tries to fetch the file on the first set", async () => {
+ await cache.set("foo", { x: 42 });
+ assert.calledOnce(fakeFetch);
+ });
+ it("sets a string value", async () => {
+ const key = "testkey";
+ const value = "testvalue";
+ await cache.set(key, value);
+ const cachedValue = await cache.get(key);
+ assert.equal(cachedValue, value);
+ });
+ it("sets an object value", async () => {
+ const key = "testkey";
+ const value = { x: 1, y: 2, z: 3 };
+ await cache.set(key, value);
+ const cachedValue = await cache.get(key);
+ assert.deepEqual(cachedValue, value);
+ });
+ it("writes the data to file", async () => {
+ const key = "testkey";
+ const value = { x: 1, y: 2, z: 3 };
+ fakeOS.File.exists = async () => false;
+ await cache.set(key, value);
+ assert.calledOnce(fakeOS.File.writeAtomic);
+ assert.calledWith(
+ fakeOS.File.writeAtomic,
+ filename,
+ `{"testkey":{"x":1,"y":2,"z":3}}`,
+ { tmpPath: `${filename}.tmp` }
+ );
+ });
+ it("throws when failing the file", async () => {
+ sandbox.stub(OS.Path, "join").throws("bad file");
+
+ let rejected = false;
+ try {
+ await cache.set("key", "val");
+ } catch (error) {
+ rejected = true;
+ }
+
+ assert(rejected);
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/lib/PersonalityProvider/NaiveBayesTextTagger.test.js b/browser/components/newtab/test/unit/lib/PersonalityProvider/NaiveBayesTextTagger.test.js
new file mode 100644
index 0000000000..7aef43fff9
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/PersonalityProvider/NaiveBayesTextTagger.test.js
@@ -0,0 +1,109 @@
+import { NaiveBayesTextTagger } from "lib/PersonalityProvider/NaiveBayesTextTagger.jsm";
+import {
+ tokenize,
+ toksToTfIdfVector,
+} from "lib/PersonalityProvider/Tokenize.jsm";
+
+const EPSILON = 0.00001;
+
+describe("Naive Bayes Tagger", () => {
+ describe("#tag", () => {
+ let model = {
+ model_type: "nb",
+ positive_class_label: "military",
+ positive_class_id: 0,
+ positive_class_threshold_log_prob: -0.5108256237659907,
+ classes: [
+ {
+ log_prior: -0.6881346387364013,
+ feature_log_probs: [
+ -6.2149425847276,
+ -6.829869141665873,
+ -7.124856122235796,
+ -7.116661287797188,
+ -6.694751331313906,
+ -7.11798266787003,
+ -6.5094904366004185,
+ -7.1639509366900604,
+ -7.218981434452414,
+ -6.854842907887801,
+ -7.080328841624584,
+ ],
+ },
+ {
+ log_prior: -0.6981849745899025,
+ feature_log_probs: [
+ -7.0575941199203465,
+ -6.632333513597953,
+ -7.382756370680115,
+ -7.1160793981275905,
+ -8.467120918791892,
+ -8.369201274990882,
+ -8.518506617006922,
+ -7.015756380369387,
+ -7.739036845511857,
+ -9.748294397894645,
+ -3.9353548206941955,
+ ],
+ },
+ ],
+ vocab_idfs: {
+ deal: [0, 5.5058519847862275],
+ easy: [1, 5.5058519847862275],
+ tanks: [2, 5.601162164590552],
+ sites: [3, 5.957837108529285],
+ care: [4, 5.957837108529285],
+ needs: [5, 5.824305715904762],
+ finally: [6, 5.706522680248379],
+ super: [7, 5.264689927969339],
+ heard: [8, 5.5058519847862275],
+ reached: [9, 5.957837108529285],
+ words: [10, 5.070533913528382],
+ },
+ };
+ let instance = new NaiveBayesTextTagger(model, toksToTfIdfVector);
+
+ let testCases = [
+ {
+ input: "Finally! Super easy care for your tanks!",
+ expected: {
+ label: "military",
+ logProb: -0.16299510296630082,
+ confident: true,
+ },
+ },
+ {
+ input: "heard",
+ expected: {
+ label: "military",
+ logProb: -0.4628170738373294,
+ confident: false,
+ },
+ },
+ {
+ input: "words",
+ expected: {
+ label: null,
+ logProb: -0.04258339303757985,
+ confident: false,
+ },
+ },
+ ];
+
+ let checkTag = tc => {
+ let actual = instance.tagTokens(tokenize(tc.input));
+ it(`should tag ${tc.input} with ${tc.expected.label}`, () => {
+ assert.equal(tc.expected.label, actual.label);
+ });
+ it(`should give ${tc.input} the correct probability`, () => {
+ let delta = Math.abs(tc.expected.logProb - actual.logProb);
+ assert.isTrue(delta <= EPSILON);
+ });
+ };
+
+ // RELEASE THE TESTS!
+ for (let tc of testCases) {
+ checkTag(tc);
+ }
+ });
+});
diff --git a/browser/components/newtab/test/unit/lib/PersonalityProvider/NmfTextTagger.test.js b/browser/components/newtab/test/unit/lib/PersonalityProvider/NmfTextTagger.test.js
new file mode 100644
index 0000000000..ba0122096e
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/PersonalityProvider/NmfTextTagger.test.js
@@ -0,0 +1,1083 @@
+import { NmfTextTagger } from "lib/PersonalityProvider/NmfTextTagger.jsm";
+import {
+ tokenize,
+ toksToTfIdfVector,
+} from "lib/PersonalityProvider/Tokenize.jsm";
+
+const EPSILON = 0.00001;
+
+describe("NMF Tagger", () => {
+ describe("#tag", () => {
+ // The numbers in this model were pulled from existing trained model.
+ let model = {
+ document_topic: {
+ environment: [
+ 0.05313956429537541,
+ 0.07314019377743895,
+ 0.03247190024863182,
+ 0.016189529772591395,
+ 0.003812317145412572,
+ 0.03863075834647775,
+ 0.007495425135831521,
+ 0.005100298003919777,
+ 0.005245622179405364,
+ 0.036196010766427554,
+ 0.02189970342121833,
+ 0.03514130992119014,
+ 0.001248114096050196,
+ 0.0030908722594824665,
+ 0.0023874256586350626,
+ 0.008533674814792993,
+ 0.0009424690250135675,
+ 0.01603124888144218,
+ 0.00752822798092765,
+ 0.0039046678154748796,
+ 0.03521776907836766,
+ 0.00614546613169027,
+ 0.0008272200196643818,
+ 0.01405638079154697,
+ 0.001990670259485496,
+ 0.002803666919676377,
+ 0.013841677883061631,
+ 0.004093362693745272,
+ 0.009310678536276432,
+ 0.006158920150866703,
+ 0.006821027337091937,
+ 0.002712031105462971,
+ 0.009093298611644996,
+ 0.014642160500331744,
+ 0.0067239941045715386,
+ 0.007150418784462898,
+ 0.0064652818600521265,
+ 0.0006735690394489199,
+ 0.02063188588742841,
+ 0.003213083349614106,
+ 0.0031998068360970093,
+ 0.00264520606931871,
+ 0.008854824468146531,
+ 0.0024170562884908786,
+ 0.0013705390639746128,
+ 0.0030575940757273288,
+ 0.010417378215688392,
+ 0.002356164040132228,
+ 0.0026710154645455007,
+ 0.0007295327370144145,
+ 0.0585307418954327,
+ 0.0037987763460599574,
+ 0.003199095437138493,
+ 0.004368800434950577,
+ 0.005087168372751965,
+ 0.0011100904433965942,
+ 0.01700096791869979,
+ 0.01929226435023826,
+ 0.010536397909643058,
+ 0.001734999985783697,
+ 0.003852807194017686,
+ 0.007916805773686475,
+ 0.028375307444815964,
+ 0.0012422599635274355,
+ 0.0009298594944844238,
+ 0.02095410849846837,
+ 0.0017269844428419192,
+ 0.002152880993141985,
+ 0.0030226616228192387,
+ 0.004804812297400959,
+ 0.0012383636748462198,
+ 0.006991278216261148,
+ 0.0013747035300597538,
+ 0.002041541234639563,
+ 0.012076270996247411,
+ 0.006643837514421182,
+ 0.003974012776560734,
+ 0.015794539051705442,
+ 0.007601190171659186,
+ 0.016474925942594837,
+ 0.002729423078513777,
+ 0.007635146179880609,
+ 0.013457547041824648,
+ 0.0007592338429017099,
+ 0.002947096673767141,
+ 0.006371935735541048,
+ 0.003356178481568716,
+ 0.00451933490245723,
+ 0.0019006306992329104,
+ 0.013048046603391707,
+ 0.023541628496101297,
+ 0.027659066125377194,
+ 0.002312727786055524,
+ 0.0014189157259186062,
+ 0.01963766030236683,
+ 0.0026014761547439634,
+ 0.002333697870992923,
+ 0.003401734295211338,
+ 0.002522073778255918,
+ 0.0015769783084977752,
+ ],
+ space: [
+ 0.045976774394786174,
+ 0.04386532305052323,
+ 0.03346748817597193,
+ 0.008498345884036708,
+ 0.005802390890667938,
+ 0.0017673346473868704,
+ 0.00468037374691276,
+ 0.0036807899985757367,
+ 0.0034951488381868424,
+ 0.015073756869093244,
+ 0.006784747891785806,
+ 0.03069702365741547,
+ 0.004945214461908244,
+ 0.002527030239506901,
+ 0.0012201743197690308,
+ 0.010191409658936534,
+ 0.0013882500616525532,
+ 0.014559679471816162,
+ 0.005308140956577744,
+ 0.002067005832569046,
+ 0.006092496689239475,
+ 0.0029308442356851265,
+ 0.0006407392160713908,
+ 0.01669972147417425,
+ 0.0018920321527190246,
+ 0.002436089537269062,
+ 0.05542174181989591,
+ 0.006448761215865303,
+ 0.012804154851567844,
+ 0.014553974971946687,
+ 0.004927456148063145,
+ 0.006085620881900181,
+ 0.011626122370522652,
+ 0.002994267915422563,
+ 0.0038291031528493898,
+ 0.006987917175322377,
+ 0.00719289436611732,
+ 0.0008398926158042337,
+ 0.019068654506361523,
+ 0.004453895285397824,
+ 0.00401164781243836,
+ 0.0031309255764704544,
+ 0.013210118660087334,
+ 0.0015542151889036313,
+ 0.0013951089590218057,
+ 0.002790924761398501,
+ 0.008739250167366135,
+ 0.0027834569638271025,
+ 0.09198161284531065,
+ 0.0019488047187835441,
+ 0.001739971582806101,
+ 0.005113637251322287,
+ 0.12140493794373561,
+ 0.005535368890812829,
+ 0.004198222617607059,
+ 0.0010670629105233682,
+ 0.005298717616708989,
+ 0.0048291586850982855,
+ 0.005140125537186181,
+ 0.0011663683373124493,
+ 0.0024499638218810943,
+ 0.012532772497286819,
+ 0.0015564613278042862,
+ 0.0012252899339204029,
+ 0.0005095187051357676,
+ 0.0035442657060978655,
+ 0.014030578705118285,
+ 0.0017653534252553718,
+ 0.004026729875153457,
+ 0.004002067082856801,
+ 0.00809773970333208,
+ 0.017160384509220625,
+ 0.002981945110677171,
+ 0.0018338446554387704,
+ 0.0031886913904107484,
+ 0.004654622711785796,
+ 0.0053886727821435415,
+ 0.009023511029300392,
+ 0.005246967669202147,
+ 0.022806469628558337,
+ 0.0035142224878495355,
+ 0.006793295047927272,
+ 0.017396620747821886,
+ 0.000922278971300957,
+ 0.001695889413253992,
+ 0.007015197552957029,
+ 0.003908581792868586,
+ 0.010136260994789877,
+ 0.0032880552208979508,
+ 0.0039712539426523625,
+ 0.009672046620728448,
+ 0.007290428293346,
+ 0.0017814796852793386,
+ 0.0005388988974780036,
+ 0.013936726486762537,
+ 0.003427738251710856,
+ 0.002206664729558829,
+ 0.05072392472622557,
+ 0.004424158921356747,
+ 0.0003680061331891622,
+ ],
+ biology: [
+ 0.054433533850037796,
+ 0.039689474154513994,
+ 0.027661000660240884,
+ 0.021655563357213067,
+ 0.007862624595639219,
+ 0.006280655377019006,
+ 0.013407714984668861,
+ 0.004038592819712647,
+ 0.009652765217013826,
+ 0.0011353987945632667,
+ 0.00925298156804724,
+ 0.004870163054917538,
+ 0.04911204317171355,
+ 0.006921538451191124,
+ 0.004003624507234068,
+ 0.016600722822360296,
+ 0.002179735905957767,
+ 0.010801493818182368,
+ 0.00918922860910538,
+ 0.022115576350545514,
+ 0.0027720850555002148,
+ 0.003290714340925284,
+ 0.0006359939927595049,
+ 0.020564054347194806,
+ 0.019590591011010666,
+ 0.0029008397180383077,
+ 0.030414664509122412,
+ 0.002864704837438281,
+ 0.030933936414333993,
+ 0.00222576969791357,
+ 0.007077232390623289,
+ 0.005876547862506722,
+ 0.016917705934608753,
+ 0.016466207380001166,
+ 0.006648808144677746,
+ 0.017876914915160164,
+ 0.008216930648675583,
+ 0.0026813239798232098,
+ 0.012171904585413245,
+ 0.012319763594831614,
+ 0.003909608203628946,
+ 0.003205613981613637,
+ 0.027729523430009183,
+ 0.0019938396819227074,
+ 0.002752482544417343,
+ 0.0016746657427111145,
+ 0.019564250521109314,
+ 0.027250898086440583,
+ 0.000954251437229793,
+ 0.0020431321836649734,
+ 0.0014636128217840221,
+ 0.006821766389705783,
+ 0.003272989792090916,
+ 0.011086677363737012,
+ 0.0044279892365732595,
+ 0.0029213721398486203,
+ 0.013081117655947345,
+ 0.012102962176204816,
+ 0.0029165848047082825,
+ 0.002363073972325097,
+ 0.0028567640089643695,
+ 0.013692951578614878,
+ 0.0013189478722657382,
+ 0.0030662419379415885,
+ 0.001688218039583749,
+ 0.0007806438728749603,
+ 0.025458033834110355,
+ 0.009584308792578437,
+ 0.0033243840056188263,
+ 0.0068361098488461045,
+ 0.005178034666939756,
+ 0.006831575853694424,
+ 0.010170774789130092,
+ 0.004639315532453418,
+ 0.00655511046953238,
+ 0.005661100806175219,
+ 0.006238755352678196,
+ 0.023282136482285103,
+ 0.007790828526461584,
+ 0.011840304456780202,
+ 0.0021953903460442225,
+ 0.011205225479328193,
+ 0.01665869590158306,
+ 0.0009257333679666402,
+ 0.0032380769616003604,
+ 0.007379754534437712,
+ 0.01804771060116468,
+ 0.02540492978451049,
+ 0.0027900782593570507,
+ 0.0029721824342474694,
+ 0.005666888959879564,
+ 0.003629523931553047,
+ 0.0017838703067849428,
+ 0.004996486217852931,
+ 0.006086510142627035,
+ 0.0023570031997685236,
+ 0.002718397814380002,
+ 0.003908858478916721,
+ 0.02080129902865465,
+ 0.005591305783253238,
+ ],
+ },
+ topic_word: [
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.003173633134427233,
+ 0.0,
+ 0.0,
+ 0.0019409914586816176,
+ 0.0,
+ ],
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 5.135548639746091e-5,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.00015384770766669982,
+ ],
+ [
+ 0.0,
+ 0.0,
+ 0.0005001441880557176,
+ 0.0,
+ 0.0,
+ 0.0012069823147301646,
+ 0.02401141538644239,
+ 8.831990149479376e-5,
+ 0.001813504147854849,
+ 0.0,
+ ],
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0003577161362340021,
+ 0.0005744157863408606,
+ 0.0,
+ 0.0,
+ 0.0,
+ ],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.002662246533243532,
+ 0.0,
+ 0.0,
+ 0.0008394369973758684,
+ 0.0,
+ ],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [
+ 0.0,
+ 4.768637450522633e-5,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0010421065429755969,
+ 0.0,
+ 0.0,
+ 2.3210938729937306e-5,
+ ],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0006034363278588148,
+ 0.001690622339085902,
+ 0.0,
+ 0.0,
+ ],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.004257728522853072, 0.0, 0.0, 0.0, 0.0],
+ [
+ 0.0007238839225620208,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0009507496006759083,
+ 0.0012635532859311572,
+ 0.0,
+ 0.0,
+ 0.0,
+ ],
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 1.2699264109324263e-5,
+ 0.00032868342552128994,
+ 0.0,
+ ],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0011157667743487598,
+ 0.001278875789622101,
+ 9.011724853181247e-6,
+ 0.0,
+ 3.22069766200917e-5,
+ 0.004124963644732435,
+ ],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.00011961487736485771],
+ [0.0, 0.0, 0.0, 5.734703813314615e-5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 4.0340264022466226e-5, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.00039701897786057513, 0.0, 0.0, 0.0, 0.0],
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.19635202968946042,
+ 0.0,
+ 0.0008873887898279083,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ ],
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 1.552973162326247e-5,
+ 0.0,
+ 0.002284331845105356,
+ 0.0,
+ 0.0,
+ ],
+ [
+ 0.0,
+ 0.0,
+ 0.005561738919282601,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.010700323065082812,
+ 0.0,
+ 0.0005795117202094265,
+ 0.0,
+ ],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0005085828329663487, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.029261090049475084,
+ 0.0020864946050332834,
+ 0.0018513709831557076,
+ 0.0,
+ 0.0,
+ 0.0,
+ ],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0008328286790309667, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0013227647245223537, 0.0, 0.0, 0.0, 0.0],
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0024010554774254685,
+ 5.357245317969706e-5,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ ],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0014484032312145462, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0012081428144960678, 0.0, 0.0, 0.0, 0.0],
+ [
+ 0.0,
+ 0.0,
+ 0.000616488580813398,
+ 0.0,
+ 0.0,
+ 0.0017954524796671627,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ ],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0006660554263924299, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0011891151421092303, 0.0, 0.0],
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0024885434472066534,
+ 0.0,
+ 0.0010165824086743897,
+ 0.0,
+ 0.0,
+ ],
+ [
+ 0.0,
+ 5.692292246819767e-5,
+ 0.0,
+ 0.0,
+ 0.001006289633741549,
+ 0.0,
+ 0.0,
+ 0.001897882990870404,
+ 0.0,
+ 0.0,
+ ],
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.00010646854330751878,
+ 0.0,
+ 0.0013480243353754932,
+ 0.0,
+ ],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0002608785715957589, 0.0],
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0010620422134845085,
+ 0.0,
+ 0.0,
+ 0.0002032215308376943,
+ 0.0,
+ ],
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0008928062238389307,
+ 0.0,
+ 0.0,
+ 5.727265080002417e-5,
+ 0.0,
+ ],
+ [
+ 0.0,
+ 0.0,
+ 0.06061253593083364,
+ 0.0,
+ 0.02739898181912798,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ ],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0014338134220455178,
+ 0.0,
+ 0.0011276871850520397,
+ 0.002840121913315777,
+ ],
+ [0.0008014293374641945, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [
+ 0.0,
+ 0.000345858724152025,
+ 0.013078498367906305,
+ 0.0,
+ 0.002815596608197659,
+ 0.0,
+ 0.0,
+ 0.0030778986683343023,
+ 0.0,
+ 0.0,
+ ],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0010177321509216356, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.00015333347872060042, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0009655934464519347, 0.0],
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0008542046515290346,
+ 0.0,
+ 0.0,
+ 0.00016472517230317488,
+ 0.0,
+ ],
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0007759590139787148,
+ 0.0037535348789227703,
+ 0.0007205740927611773,
+ ],
+ [
+ 0.0,
+ 0.0,
+ 0.0010313963595627862,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0069665132800572115,
+ 0.0,
+ ],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0006880323929924655,
+ 9.207429290830475e-5,
+ 0.0,
+ 0.0,
+ 0.0,
+ ],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0008404475484102756, 0.0, 0.0, 0.0, 0.0],
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.00016603822882009137,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0004386724451378034,
+ ],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.003971386830918022, 0.0, 0.0, 0.0, 0.0],
+ [0.000983926199078037, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.001299108775819868, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [
+ 0.16326515307916822,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0028677496385613155,
+ 0.023677620702293598,
+ 0.0,
+ 0.0,
+ 0.0,
+ ],
+ [0.0, 0.0, 5.737710913345495e-6, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [
+ 0.0,
+ 0.0,
+ 0.0002081792662367579,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0002840163488982256,
+ ],
+ [0.0, 0.0, 0.0, 0.0, 0.0005021534925351664, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.001057424953719077,
+ 0.0,
+ 0.003578658690485632,
+ 0.0,
+ 0.0,
+ ],
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.00022950619982206556,
+ 0.0018791783657735252,
+ 0.0008530683004027156,
+ 4.5513911743540586e-5,
+ 0.0,
+ ],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0045523319463242765, 0.0, 0.0, 0.0, 0.0],
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0006160628426134845,
+ 0.0,
+ 0.0023393152617350653,
+ 0.0,
+ 0.0,
+ 0.0012979890699731222,
+ ],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [
+ 0.0,
+ 0.0,
+ 0.003391399407584813,
+ 0.0,
+ 0.0,
+ 0.000719659722017165,
+ 0.0,
+ 0.004722518573572638,
+ 0.002758841738663124,
+ 0.0,
+ ],
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.002127862313876461,
+ 0.0,
+ 0.005031998155190167,
+ 0.0,
+ 0.0,
+ 0.0,
+ ],
+ [
+ 0.0,
+ 0.0,
+ 0.00055401373160389,
+ 0.0,
+ 0.0,
+ 0.000333325450244618,
+ 0.0017824446558959168,
+ 0.0011398506826041158,
+ 0.0,
+ 0.0006366915431430632,
+ ],
+ [
+ 0.0,
+ 0.21687336139378274,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0030345303266644387,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ ],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0012637173523723526,
+ 0.0,
+ 0.0010158476831041915,
+ 0.0035425832276585615,
+ 0.0,
+ ],
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0015451984659512325,
+ 0.019909953764629045,
+ 0.0013484737840911303,
+ 0.0033472098053086113,
+ 0.0016951819626954759,
+ ],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.00015923419851654453,
+ 0.0,
+ 0.0024056492047359367,
+ ],
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.01305313280419075,
+ 0.00014197157780982973,
+ 0.0,
+ 0.0,
+ ],
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.000746430999979358,
+ 0.0,
+ 0.0010041202546700189,
+ 0.004557016648181857,
+ 0.0,
+ ],
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.00021372865758801545,
+ 0.00025925151316940747,
+ 0.0,
+ ],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.001658746582791234, 0.0],
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.00973640859923001,
+ 0.0012404719999980969,
+ 0.0006365355864806626,
+ 0.0008291013715577852,
+ 0.0,
+ 0.0,
+ ],
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.001473459191608214,
+ 0.0,
+ 0.0,
+ 0.0009195459918865811,
+ 0.002012929485852207,
+ ],
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0005850456523130979,
+ 0.0,
+ 0.00014396718214395852,
+ 0.0,
+ ],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0011858302272740567, 0.0],
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0046803403116507545,
+ 0.002083219444498354,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.006104495765365948,
+ ],
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.005456944646675863,
+ 0.0,
+ 0.00011428354610339084,
+ 0.0,
+ 0.0,
+ ],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0013384597578988894, 0.0, 0.0, 0.0, 0.0],
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0018450592044551373,
+ 0.0,
+ 0.005182965872305058,
+ 0.0,
+ 0.0,
+ ],
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0003041074021307749,
+ 0.0,
+ 0.0020827735275448823,
+ 0.0,
+ 0.0008494429669380388,
+ ],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ ],
+ vocab_idfs: {
+ blood: [0, 5.0948820521571045],
+ earth: [1, 4.2248041634380815],
+ rocket: [2, 5.666668375712782],
+ brain: [3, 4.616846251214104],
+ mars: [4, 6.226284163648205],
+ nothing: [5, 5.270772718620769],
+ nada: [6, 4.815297189937943],
+ star: [7, 6.38880309314598],
+ zilch: [8, 5.889811927026992],
+ soil: [9, 7.14257489552236],
+ },
+ };
+
+ let instance = new NmfTextTagger(model, toksToTfIdfVector);
+
+ let testCases = [
+ {
+ input: "blood is in the brain",
+ expected: {
+ environment: 0.00037336337061919943,
+ space: 0.0003307690554984028,
+ biology: 0.0026549079818439627,
+ },
+ },
+
+ {
+ input: "rocket to the star",
+ expected: {
+ environment: 0.0002855180592590448,
+ space: 0.004006242743506598,
+ biology: 0.0003094182371360131,
+ },
+ },
+ {
+ input: "rocket to the star mars",
+ expected: {
+ environment: 0.0004180326651780644,
+ space: 0.003844259295376754,
+ biology: 0.0003135623817729136,
+ },
+ },
+ {
+ input: "rocket rocket rocket",
+ expected: {
+ environment: 0.00033052002469507015,
+ space: 0.007519787053895712,
+ biology: 0.00031862864995569246,
+ },
+ },
+ {
+ input: "nothing nada rocket",
+ expected: {
+ environment: 0.0008597524218029812,
+ space: 0.0035401031629944506,
+ biology: 0.000950627767326667,
+ },
+ },
+ {
+ input: "rocket",
+ expected: {
+ environment: 0.00033052002469507015,
+ space: 0.007519787053895712,
+ biology: 0.00031862864995569246,
+ },
+ },
+ {
+ input: "this sentence is out of vocabulary",
+ expected: {
+ environment: 0.0,
+ space: 0.0,
+ biology: 0.0,
+ },
+ },
+ {
+ input: "this sentence is out of vocabulary except for rocket",
+ expected: {
+ environment: 0.00033052002469507015,
+ space: 0.007519787053895712,
+ biology: 0.00031862864995569246,
+ },
+ },
+ ];
+
+ let checkTag = tc => {
+ let actual = instance.tagTokens(tokenize(tc.input));
+ it(`should score ${tc.input} correctly`, () => {
+ Object.keys(actual).forEach(tag => {
+ let delta = Math.abs(tc.expected[tag] - actual[tag]);
+ assert.isTrue(delta <= EPSILON);
+ });
+ });
+ };
+
+ // RELEASE THE TESTS!
+ for (let tc of testCases) {
+ checkTag(tc);
+ }
+ });
+});
diff --git a/browser/components/newtab/test/unit/lib/PersonalityProvider/PersonalityProvider.test.js b/browser/components/newtab/test/unit/lib/PersonalityProvider/PersonalityProvider.test.js
new file mode 100644
index 0000000000..c5d6e720c9
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/PersonalityProvider/PersonalityProvider.test.js
@@ -0,0 +1,389 @@
+import { GlobalOverrider } from "test/unit/utils";
+import { PersonalityProvider } from "lib/PersonalityProvider/PersonalityProvider.jsm";
+
+const TIME_SEGMENTS = [
+ { id: "hour", startTime: 3600, endTime: 0, weightPosition: 1 },
+ { id: "day", startTime: 86400, endTime: 3600, weightPosition: 0.75 },
+ { id: "week", startTime: 604800, endTime: 86400, weightPosition: 0.5 },
+ { id: "weekPlus", startTime: null, endTime: 604800, weightPosition: 0.25 },
+];
+
+const PARAMETER_SETS = {
+ paramSet1: {
+ recencyFactor: 0.5,
+ frequencyFactor: 0.5,
+ combinedDomainFactor: 0.5,
+ perfectFrequencyVisits: 10,
+ perfectCombinedDomainScore: 2,
+ multiDomainBoost: 0.1,
+ itemScoreFactor: 0,
+ },
+ paramSet2: {
+ recencyFactor: 1,
+ frequencyFactor: 0.7,
+ combinedDomainFactor: 0.8,
+ perfectFrequencyVisits: 10,
+ perfectCombinedDomainScore: 2,
+ multiDomainBoost: 0.1,
+ itemScoreFactor: 0,
+ },
+};
+
+describe("Personality Provider", () => {
+ let instance;
+ let RemoteSettingsStub;
+ let RemoteSettingsOnStub;
+ let RemoteSettingsOffStub;
+ let RemoteSettingsGetStub;
+ let sandbox;
+ let globals;
+ let baseURLStub;
+
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ globals = new GlobalOverrider();
+
+ RemoteSettingsOnStub = sandbox.stub().returns();
+ RemoteSettingsOffStub = sandbox.stub().returns();
+ RemoteSettingsGetStub = sandbox.stub().returns([]);
+
+ RemoteSettingsStub = name => ({
+ get: RemoteSettingsGetStub,
+ on: RemoteSettingsOnStub,
+ off: RemoteSettingsOffStub,
+ });
+
+ sinon.spy(global, "BasePromiseWorker");
+ sinon.spy(global.BasePromiseWorker.prototype, "post");
+
+ baseURLStub = "https://baseattachmentsurl";
+ global.fetch = async server => ({
+ ok: true,
+ json: async () => {
+ if (server === "services.settings.server/") {
+ return { capabilities: { attachments: { base_url: baseURLStub } } };
+ }
+ return {};
+ },
+ });
+ globals.sandbox
+ .stub(global.Services.prefs, "getCharPref")
+ .callsFake(pref => pref);
+ globals.set("RemoteSettings", RemoteSettingsStub);
+
+ instance = new PersonalityProvider();
+ instance.setAffinities(TIME_SEGMENTS, PARAMETER_SETS);
+ instance.interestConfig = {
+ history_item_builder: "history_item_builder",
+ history_required_fields: ["a", "b", "c"],
+ interest_finalizer: "interest_finalizer",
+ item_to_rank_builder: "item_to_rank_builder",
+ item_ranker: "item_ranker",
+ interest_combiner: "interest_combiner",
+ };
+ });
+ afterEach(() => {
+ sinon.restore();
+ sandbox.restore();
+ globals.restore();
+ });
+ describe("#personalityProviderWorker", () => {
+ it("should create a new promise worker on first call", async () => {
+ const { personalityProviderWorker } = instance;
+ assert.calledOnce(global.BasePromiseWorker);
+ assert.isDefined(personalityProviderWorker);
+ });
+ it("should cache _personalityProviderWorker on first call", async () => {
+ instance._personalityProviderWorker = null;
+ const { personalityProviderWorker } = instance;
+ assert.isDefined(instance._personalityProviderWorker);
+ assert.isDefined(personalityProviderWorker);
+ });
+ it("should use old promise worker on second call", async () => {
+ let { personalityProviderWorker } = instance;
+ personalityProviderWorker = instance.personalityProviderWorker;
+ assert.calledOnce(global.BasePromiseWorker);
+ assert.isDefined(personalityProviderWorker);
+ });
+ });
+ describe("#_getBaseAttachmentsURL", () => {
+ it("should return a fresh value", async () => {
+ await instance._getBaseAttachmentsURL();
+ assert.equal(instance._baseAttachmentsURL, baseURLStub);
+ });
+ it("should return a cached value", async () => {
+ const cachedURL = "cached";
+ instance._baseAttachmentsURL = cachedURL;
+ await instance._getBaseAttachmentsURL();
+ assert.equal(instance._baseAttachmentsURL, cachedURL);
+ });
+ });
+ describe("#setup", () => {
+ it("should setup two sync attachments", () => {
+ sinon.spy(instance, "setupSyncAttachment");
+ instance.setup();
+ assert.calledTwice(instance.setupSyncAttachment);
+ });
+ });
+ describe("#teardown", () => {
+ it("should teardown two sync attachments", () => {
+ sinon.spy(instance, "teardownSyncAttachment");
+ instance.teardown();
+ assert.calledTwice(instance.teardownSyncAttachment);
+ });
+ it("should terminate worker", () => {
+ const terminateStub = sandbox.stub().returns();
+ instance._personalityProviderWorker = {
+ terminate: terminateStub,
+ };
+ instance.teardown();
+ assert.calledOnce(terminateStub);
+ });
+ });
+ describe("#setupSyncAttachment", () => {
+ it("should call remote settings on twice for setupSyncAttachment", () => {
+ assert.calledTwice(RemoteSettingsOnStub);
+ });
+ });
+ describe("#teardownSyncAttachment", () => {
+ it("should call remote settings off for teardownSyncAttachment", () => {
+ instance.teardownSyncAttachment();
+ assert.calledOnce(RemoteSettingsOffStub);
+ });
+ });
+ describe("#onSync", () => {
+ it("should call worker onSync", () => {
+ instance.onSync();
+ assert.calledWith(global.BasePromiseWorker.prototype.post, "onSync");
+ });
+ });
+ describe("#getAttachment", () => {
+ it("should call worker onSync", () => {
+ instance.getAttachment();
+ assert.calledWith(
+ global.BasePromiseWorker.prototype.post,
+ "getAttachment"
+ );
+ });
+ });
+ describe("#getRecipe", () => {
+ it("should call worker getRecipe and remote settings get", async () => {
+ RemoteSettingsGetStub = sandbox.stub().returns([
+ {
+ key: 1,
+ },
+ ]);
+ sinon.spy(instance, "getAttachment");
+ RemoteSettingsStub = name => ({
+ get: RemoteSettingsGetStub,
+ on: RemoteSettingsOnStub,
+ off: RemoteSettingsOffStub,
+ });
+ globals.set("RemoteSettings", RemoteSettingsStub);
+
+ const result = await instance.getRecipe();
+ assert.calledOnce(RemoteSettingsGetStub);
+ assert.calledOnce(instance.getAttachment);
+ assert.equal(result.recordKey, 1);
+ });
+ });
+ describe("#fetchHistory", () => {
+ it("should return a history object for fetchHistory", async () => {
+ const history = await instance.fetchHistory(["requiredColumn"], 1, 1);
+ assert.equal(
+ history.sql,
+ `SELECT url, title, visit_count, frecency, last_visit_date, description\n FROM moz_places\n WHERE last_visit_date >= 1000000\n AND last_visit_date < 1000000 AND IFNULL(requiredColumn, '') <> '' LIMIT 30000`
+ );
+ assert.equal(history.options.columns.length, 1);
+ assert.equal(Object.keys(history.options.params).length, 0);
+ });
+ });
+ describe("#getHistory", () => {
+ it("should return an empty array", async () => {
+ instance.interestConfig = {
+ history_required_fields: [],
+ };
+ const result = await instance.getHistory();
+ assert.equal(result.length, 0);
+ });
+ it("should call fetchHistory", async () => {
+ sinon.spy(instance, "fetchHistory");
+ await instance.getHistory();
+ });
+ });
+ describe("#setBaseAttachmentsURL", () => {
+ it("should call worker setBaseAttachmentsURL", async () => {
+ await instance.setBaseAttachmentsURL();
+ assert.calledWith(
+ global.BasePromiseWorker.prototype.post,
+ "setBaseAttachmentsURL"
+ );
+ });
+ });
+ describe("#setInterestConfig", () => {
+ it("should call worker setInterestConfig", async () => {
+ await instance.setInterestConfig();
+ assert.calledWith(
+ global.BasePromiseWorker.prototype.post,
+ "setInterestConfig"
+ );
+ });
+ });
+ describe("#setInterestVector", () => {
+ it("should call worker setInterestVector", async () => {
+ await instance.setInterestVector();
+ assert.calledWith(
+ global.BasePromiseWorker.prototype.post,
+ "setInterestVector"
+ );
+ });
+ });
+ describe("#fetchModels", () => {
+ it("should call worker fetchModels and remote settings get", async () => {
+ await instance.fetchModels();
+ assert.calledOnce(RemoteSettingsGetStub);
+ assert.calledWith(global.BasePromiseWorker.prototype.post, "fetchModels");
+ });
+ });
+ describe("#generateTaggers", () => {
+ it("should call worker generateTaggers", async () => {
+ await instance.generateTaggers();
+ assert.calledWith(
+ global.BasePromiseWorker.prototype.post,
+ "generateTaggers"
+ );
+ });
+ });
+ describe("#generateRecipeExecutor", () => {
+ it("should call worker generateRecipeExecutor", async () => {
+ await instance.generateRecipeExecutor();
+ assert.calledWith(
+ global.BasePromiseWorker.prototype.post,
+ "generateRecipeExecutor"
+ );
+ });
+ });
+ describe("#createInterestVector", () => {
+ it("should call worker createInterestVector", async () => {
+ await instance.createInterestVector();
+ assert.calledWith(
+ global.BasePromiseWorker.prototype.post,
+ "createInterestVector"
+ );
+ });
+ });
+ describe("#init", () => {
+ it("should return early if setInterestConfig fails", async () => {
+ sandbox.stub(instance, "setBaseAttachmentsURL").returns();
+ sandbox.stub(instance, "setInterestConfig").returns();
+ instance.interestConfig = null;
+ const callback = globals.sandbox.stub();
+ await instance.init(callback);
+ assert.notCalled(callback);
+ });
+ it("should return early if fetchModels fails", async () => {
+ sandbox.stub(instance, "setBaseAttachmentsURL").returns();
+ sandbox.stub(instance, "setInterestConfig").returns();
+ sandbox.stub(instance, "fetchModels").resolves({
+ ok: false,
+ });
+ const callback = globals.sandbox.stub();
+ await instance.init(callback);
+ assert.notCalled(callback);
+ });
+ it("should return early if createInterestVector fails", async () => {
+ sandbox.stub(instance, "setBaseAttachmentsURL").returns();
+ sandbox.stub(instance, "setInterestConfig").returns();
+ sandbox.stub(instance, "fetchModels").resolves({
+ ok: true,
+ });
+ sandbox.stub(instance, "generateRecipeExecutor").resolves({
+ ok: true,
+ });
+ sandbox.stub(instance, "createInterestVector").resolves({
+ ok: false,
+ });
+ const callback = globals.sandbox.stub();
+ await instance.init(callback);
+ assert.notCalled(callback);
+ });
+ it("should call callback on successful init", async () => {
+ sandbox.stub(instance, "setBaseAttachmentsURL").returns();
+ sandbox.stub(instance, "setInterestConfig").returns();
+ sandbox.stub(instance, "fetchModels").resolves({
+ ok: true,
+ });
+ sandbox.stub(instance, "generateRecipeExecutor").resolves({
+ ok: true,
+ });
+ sandbox.stub(instance, "createInterestVector").resolves({
+ ok: true,
+ });
+ sandbox.stub(instance, "setInterestVector").resolves();
+ const callback = globals.sandbox.stub();
+ await instance.init(callback);
+ assert.calledOnce(callback);
+ assert.isTrue(instance.initialized);
+ });
+ it("should do generic init stuff when calling init with no cache", async () => {
+ sandbox.stub(instance, "setBaseAttachmentsURL").returns();
+ sandbox.stub(instance, "setInterestConfig").returns();
+ sandbox.stub(instance, "fetchModels").resolves({
+ ok: true,
+ });
+ sandbox.stub(instance, "generateRecipeExecutor").resolves({
+ ok: true,
+ });
+ sandbox.stub(instance, "createInterestVector").resolves({
+ ok: true,
+ interestVector: "interestVector",
+ });
+ sandbox.stub(instance, "setInterestVector").resolves();
+ await instance.init();
+ assert.calledOnce(instance.setBaseAttachmentsURL);
+ assert.calledOnce(instance.setInterestConfig);
+ assert.calledOnce(instance.fetchModels);
+ assert.calledOnce(instance.generateRecipeExecutor);
+ assert.calledOnce(instance.createInterestVector);
+ assert.calledOnce(instance.setInterestVector);
+ });
+ });
+ describe("#calculateItemRelevanceScore", () => {
+ it("should return score for uninitialized provider", async () => {
+ instance.initialized = false;
+ assert.equal(
+ await instance.calculateItemRelevanceScore({ item_score: 2 }),
+ 2
+ );
+ });
+ it("should return score for initialized provider", async () => {
+ instance.initialized = true;
+
+ instance._personalityProviderWorker = {
+ post: (postName, [item]) => ({
+ rankingVector: { score: item.item_score },
+ }),
+ };
+
+ assert.equal(
+ await instance.calculateItemRelevanceScore({ item_score: 2 }),
+ 2
+ );
+ });
+ it("should post calculateItemRelevanceScore to PersonalityProviderWorker", async () => {
+ instance.initialized = true;
+ await instance.calculateItemRelevanceScore({ item_score: 2 });
+ assert.calledWith(
+ global.BasePromiseWorker.prototype.post,
+ "calculateItemRelevanceScore"
+ );
+ });
+ });
+ describe("#getAffinities", () => {
+ it("should return correct data for getAffinities", () => {
+ const affinities = instance.getAffinities();
+ assert.isDefined(affinities.timeSegments);
+ assert.isDefined(affinities.parameterSets);
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/lib/PersonalityProvider/PersonalityProviderWorkerClass.test.js b/browser/components/newtab/test/unit/lib/PersonalityProvider/PersonalityProviderWorkerClass.test.js
new file mode 100644
index 0000000000..d16ae16587
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/PersonalityProvider/PersonalityProviderWorkerClass.test.js
@@ -0,0 +1,450 @@
+import { GlobalOverrider } from "test/unit/utils";
+import { PersonalityProviderWorker } from "lib/PersonalityProvider/PersonalityProviderWorkerClass.jsm";
+import {
+ tokenize,
+ toksToTfIdfVector,
+} from "lib/PersonalityProvider/Tokenize.jsm";
+import { RecipeExecutor } from "lib/PersonalityProvider/RecipeExecutor.jsm";
+import { NmfTextTagger } from "lib/PersonalityProvider/NmfTextTagger.jsm";
+import { NaiveBayesTextTagger } from "lib/PersonalityProvider/NaiveBayesTextTagger.jsm";
+
+describe("Personality Provider Worker Class", () => {
+ let instance;
+ let globals;
+ let sandbox;
+
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ globals = new GlobalOverrider();
+ globals.set("tokenize", tokenize);
+ globals.set("toksToTfIdfVector", toksToTfIdfVector);
+ globals.set("NaiveBayesTextTagger", NaiveBayesTextTagger);
+ globals.set("NmfTextTagger", NmfTextTagger);
+ globals.set("RecipeExecutor", RecipeExecutor);
+ instance = new PersonalityProviderWorker();
+
+ // mock the RecipeExecutor
+ instance.recipeExecutor = {
+ executeRecipe: (item, recipe) => {
+ if (recipe === "history_item_builder") {
+ if (item.title === "fail") {
+ return null;
+ }
+ return {
+ title: item.title,
+ score: item.frecency,
+ type: "history_item",
+ };
+ } else if (recipe === "interest_finalizer") {
+ return {
+ title: item.title,
+ score: item.score * 100,
+ type: "interest_vector",
+ };
+ } else if (recipe === "item_to_rank_builder") {
+ if (item.title === "fail") {
+ return null;
+ }
+ return {
+ item_title: item.title,
+ item_score: item.score,
+ type: "item_to_rank",
+ };
+ } else if (recipe === "item_ranker") {
+ if (item.title === "fail" || item.item_title === "fail") {
+ return null;
+ }
+ return {
+ title: item.title,
+ score: item.item_score * item.score,
+ type: "ranked_item",
+ };
+ }
+ return null;
+ },
+ executeCombinerRecipe: (item1, item2, recipe) => {
+ if (recipe === "interest_combiner") {
+ if (
+ item1.title === "combiner_fail" ||
+ item2.title === "combiner_fail"
+ ) {
+ return null;
+ }
+ if (item1.type === undefined) {
+ item1.type = "combined_iv";
+ }
+ if (item1.score === undefined) {
+ item1.score = 0;
+ }
+ return { type: item1.type, score: item1.score + item2.score };
+ }
+ return null;
+ },
+ };
+
+ instance.interestConfig = {
+ history_item_builder: "history_item_builder",
+ history_required_fields: ["a", "b", "c"],
+ interest_finalizer: "interest_finalizer",
+ item_to_rank_builder: "item_to_rank_builder",
+ item_ranker: "item_ranker",
+ interest_combiner: "interest_combiner",
+ };
+ });
+ afterEach(() => {
+ sinon.restore();
+ sandbox.restore();
+ globals.restore();
+ });
+ describe("#_getFileStr", () => {
+ it("should decode file from filepath", () => {
+ globals.set(
+ "TextDecoder",
+ class {
+ decode() {
+ return "DECODED!";
+ }
+ }
+ );
+ const result = instance._getFileStr("filepath");
+ assert.equal(result, "DECODED!");
+ });
+ });
+ describe("#setBaseAttachmentsURL", () => {
+ it("should set baseAttachmentsURL", () => {
+ instance.setBaseAttachmentsURL("url");
+ assert.equal(instance.baseAttachmentsURL, "url");
+ });
+ });
+ describe("#setInterestConfig", () => {
+ it("should set interestConfig", () => {
+ instance.setInterestConfig("config");
+ assert.equal(instance.interestConfig, "config");
+ });
+ });
+ describe("#setInterestVector", () => {
+ it("should set interestVector", () => {
+ instance.setInterestVector("vector");
+ assert.equal(instance.interestVector, "vector");
+ });
+ });
+ describe("#onSync", () => {
+ it("should sync remote settings collection from onSync", () => {
+ sinon.stub(instance, "deleteAttachment").returns({});
+ sinon.stub(instance, "maybeDownloadAttachment").returns({});
+
+ instance.onSync({
+ data: {
+ created: ["create-1", "create-2"],
+ updated: [
+ { old: "update-old-1", new: "update-new-1" },
+ { old: "update-old-2", new: "update-new-2" },
+ ],
+ deleted: ["delete-2", "delete-1"],
+ },
+ });
+
+ assert(instance.maybeDownloadAttachment.withArgs("create-1").calledOnce);
+ assert(instance.maybeDownloadAttachment.withArgs("create-2").calledOnce);
+ assert(
+ instance.maybeDownloadAttachment.withArgs("update-new-1").calledOnce
+ );
+ assert(
+ instance.maybeDownloadAttachment.withArgs("update-new-2").calledOnce
+ );
+
+ assert(instance.deleteAttachment.withArgs("delete-1").calledOnce);
+ assert(instance.deleteAttachment.withArgs("delete-2").calledOnce);
+ assert(instance.deleteAttachment.withArgs("update-old-1").calledOnce);
+ assert(instance.deleteAttachment.withArgs("update-old-2").calledOnce);
+ });
+ });
+ describe("#maybeDownloadAttachment", () => {
+ it("should attempt _downloadAttachment three times for maybeDownloadAttachment", () => {
+ let existsStub;
+ let statStub;
+ let attachmentStub;
+ sinon.stub(instance, "_downloadAttachment").returns();
+ const makeDirStub = globals.sandbox
+ .stub(global.OS.File, "makeDir")
+ .returns();
+ globals.sandbox
+ .stub(global.OS.Path, "join")
+ .callsFake((first, second) => first + second);
+
+ existsStub = globals.sandbox.stub(global.OS.File, "exists").returns(true);
+ statStub = globals.sandbox
+ .stub(global.OS.File, "stat")
+ .returns({ size: "1" });
+
+ attachmentStub = {
+ attachment: {
+ filename: "file",
+ size: "1",
+ },
+ };
+
+ instance.maybeDownloadAttachment(attachmentStub);
+ assert.calledWith(makeDirStub, "/");
+ assert.calledOnce(existsStub);
+ assert.calledOnce(statStub);
+ assert.notCalled(instance._downloadAttachment);
+
+ existsStub.resetHistory();
+ statStub.resetHistory();
+
+ attachmentStub = {
+ attachment: {
+ filename: "file",
+ size: "2",
+ },
+ };
+
+ instance.maybeDownloadAttachment(attachmentStub);
+ assert.calledThrice(existsStub);
+ assert.calledThrice(statStub);
+ assert.calledThrice(instance._downloadAttachment);
+ });
+ });
+ describe("#_downloadAttachment", () => {
+ beforeEach(() => {
+ globals.sandbox
+ .stub(global.OS.Path, "join")
+ .callsFake((first, second) => first + second);
+ globals.set("Uint8Array", class Uint8Array {});
+ });
+ it("should write a file from _downloadAttachment", () => {
+ globals.set(
+ "XMLHttpRequest",
+ class {
+ constructor() {
+ this.status = 200;
+ this.response = "response!";
+ }
+ open() {}
+ setRequestHeader() {}
+ send() {}
+ }
+ );
+
+ const writeAtomicStub = globals.sandbox
+ .stub(global.OS.File, "writeAtomic")
+ .resolves();
+
+ instance._downloadAttachment({
+ attachment: { location: "location", filename: "filename" },
+ });
+
+ const writeArgs = writeAtomicStub.firstCall.args;
+ assert.equal(writeArgs[0], "/filename");
+ assert.equal(writeArgs[2].tmpPath, "/filename.tmp");
+ });
+ it("should call console.error from _downloadAttachment if not valid response", () => {
+ globals.set(
+ "XMLHttpRequest",
+ class {
+ constructor() {
+ this.status = 0;
+ this.response = "response!";
+ }
+ open() {}
+ setRequestHeader() {}
+ send() {}
+ }
+ );
+
+ const writeAtomicStub = globals.sandbox
+ .stub(global.OS.File, "writeAtomic")
+ .resolves();
+
+ instance._downloadAttachment({
+ attachment: { location: "location", filename: "filename" },
+ });
+
+ assert.notCalled(writeAtomicStub);
+ });
+ });
+ describe("#deleteAttachment", () => {
+ it("should remove attachments when calling deleteAttachment", () => {
+ const makeDirStub = globals.sandbox
+ .stub(global.OS.File, "makeDir")
+ .returns();
+ const removeStub = globals.sandbox
+ .stub(global.OS.File, "remove")
+ .returns();
+ const removeEmptyDirStub = globals.sandbox
+ .stub(global.OS.File, "removeEmptyDir")
+ .returns();
+ globals.sandbox
+ .stub(global.OS.Path, "join")
+ .callsFake((first, second) => first + second);
+ instance.deleteAttachment({ attachment: { filename: "filename" } });
+ assert.calledOnce(makeDirStub);
+ assert.calledOnce(removeStub);
+ assert.calledOnce(removeEmptyDirStub);
+ assert.calledWith(removeStub, "/filename", { ignoreAbsent: true });
+ });
+ });
+ describe("#getAttachment", () => {
+ it("should return JSON when calling getAttachment", () => {
+ sinon.stub(instance, "maybeDownloadAttachment").returns();
+ sinon.stub(instance, "_getFileStr").returns("{}");
+ globals.sandbox
+ .stub(global.OS.Path, "join")
+ .callsFake((first, second) => first + second);
+ const record = { attachment: { filename: "filename" } };
+ let returnValue = instance.getAttachment(record);
+
+ assert.calledOnce(instance._getFileStr);
+ assert.calledWith(instance._getFileStr, "/filename");
+ assert.calledOnce(instance.maybeDownloadAttachment);
+ assert.calledWith(instance.maybeDownloadAttachment, record);
+ assert.deepEqual(returnValue, {});
+
+ instance._getFileStr.restore();
+ sinon.stub(instance, "_getFileStr").returns({});
+ returnValue = instance.getAttachment(record);
+ assert.deepEqual(returnValue, {});
+ });
+ });
+ describe("#fetchModels", () => {
+ it("should return ok true", () => {
+ sinon.stub(instance, "getAttachment").returns();
+ const result = instance.fetchModels([{ key: 1234 }]);
+ assert.isTrue(result.ok);
+ assert.deepEqual(instance.models, [{ recordKey: 1234 }]);
+ });
+ it("should return ok false", () => {
+ sinon.stub(instance, "getAttachment").returns();
+ const result = instance.fetchModels([]);
+ assert.isTrue(!result.ok);
+ });
+ });
+ describe("#generateTaggers", () => {
+ it("should generate taggers from modelKeys", () => {
+ const modelKeys = ["nb_model_sports", "nmf_model_sports"];
+
+ instance.models = [
+ { recordKey: "nb_model_sports", model_type: "nb" },
+ {
+ recordKey: "nmf_model_sports",
+ model_type: "nmf",
+ parent_tag: "nmf_sports_parent_tag",
+ },
+ ];
+
+ instance.generateTaggers(modelKeys);
+ assert.equal(instance.taggers.nbTaggers.length, 1);
+ assert.equal(Object.keys(instance.taggers.nmfTaggers).length, 1);
+ });
+ it("should skip any models not in modelKeys", () => {
+ const modelKeys = ["nb_model_sports"];
+
+ instance.models = [
+ { recordKey: "nb_model_sports", model_type: "nb" },
+ {
+ recordKey: "nmf_model_sports",
+ model_type: "nmf",
+ parent_tag: "nmf_sports_parent_tag",
+ },
+ ];
+
+ instance.generateTaggers(modelKeys);
+ assert.equal(instance.taggers.nbTaggers.length, 1);
+ assert.equal(Object.keys(instance.taggers.nmfTaggers).length, 0);
+ });
+ it("should skip any models not defined", () => {
+ const modelKeys = ["nb_model_sports", "nmf_model_sports"];
+
+ instance.models = [{ recordKey: "nb_model_sports", model_type: "nb" }];
+ instance.generateTaggers(modelKeys);
+ assert.equal(instance.taggers.nbTaggers.length, 1);
+ assert.equal(Object.keys(instance.taggers.nmfTaggers).length, 0);
+ });
+ });
+ describe("#generateRecipeExecutor", () => {
+ it("should generate a recipeExecutor", () => {
+ instance.recipeExecutor = null;
+ instance.taggers = {};
+ instance.generateRecipeExecutor();
+ assert.isNotNull(instance.recipeExecutor);
+ });
+ });
+ describe("#createInterestVector", () => {
+ let mockHistory = [];
+ beforeEach(() => {
+ mockHistory = [
+ {
+ title: "automotive",
+ description: "something about automotive",
+ url: "http://example.com/automotive",
+ frecency: 10,
+ },
+ {
+ title: "fashion",
+ description: "something about fashion",
+ url: "http://example.com/fashion",
+ frecency: 5,
+ },
+ {
+ title: "tech",
+ description: "something about tech",
+ url: "http://example.com/tech",
+ frecency: 1,
+ },
+ ];
+ });
+ it("should gracefully handle history entries that fail", () => {
+ mockHistory.push({ title: "fail" });
+ assert.isNotNull(instance.createInterestVector(mockHistory));
+ });
+
+ it("should fail if the combiner fails", () => {
+ mockHistory.push({ title: "combiner_fail", frecency: 111 });
+ let actual = instance.createInterestVector(mockHistory);
+ assert.isNull(actual);
+ });
+
+ it("should process history, combine, and finalize", () => {
+ let actual = instance.createInterestVector(mockHistory);
+ assert.equal(actual.interestVector.score, 1600);
+ });
+ });
+ describe("#calculateItemRelevanceScore", () => {
+ it("should return null for busted item", () => {
+ assert.equal(
+ instance.calculateItemRelevanceScore({ title: "fail" }),
+ null
+ );
+ });
+ it("should return null for a busted ranking", () => {
+ instance.interestVector = { title: "fail", score: 10 };
+ assert.equal(
+ instance.calculateItemRelevanceScore({ title: "some item", score: 6 }),
+ null
+ );
+ });
+ it("should return a score, and not change with interestVector", () => {
+ instance.interestVector = { score: 10 };
+ assert.equal(
+ instance.calculateItemRelevanceScore({ score: 2 }).rankingVector.score,
+ 20
+ );
+ assert.deepEqual(instance.interestVector, { score: 10 });
+ });
+ it("should use defined personalization_models if available", () => {
+ instance.interestVector = { score: 10 };
+ const item = {
+ score: 2,
+ personalization_models: {
+ entertainment: 1,
+ },
+ };
+ assert.equal(
+ instance.calculateItemRelevanceScore(item).scorableItem.item_tags
+ .entertainment,
+ 1
+ );
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/lib/PersonalityProvider/RecipeExecutor.test.js b/browser/components/newtab/test/unit/lib/PersonalityProvider/RecipeExecutor.test.js
new file mode 100644
index 0000000000..f1c54334bc
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/PersonalityProvider/RecipeExecutor.test.js
@@ -0,0 +1,1547 @@
+import { RecipeExecutor } from "lib/PersonalityProvider/RecipeExecutor.jsm";
+import { tokenize } from "lib/PersonalityProvider/Tokenize.jsm";
+
+class MockTagger {
+ constructor(mode, tagScoreMap) {
+ this.mode = mode;
+ this.tagScoreMap = tagScoreMap;
+ }
+ tagTokens(tokens) {
+ if (this.mode === "nb") {
+ // eslint-disable-next-line prefer-destructuring
+ let tag = Object.keys(this.tagScoreMap)[0];
+ // eslint-disable-next-line prefer-destructuring
+ let prob = this.tagScoreMap[tag];
+ let conf = prob >= 0.85;
+ return {
+ label: tag,
+ logProb: Math.log(prob),
+ confident: conf,
+ };
+ }
+ return this.tagScoreMap;
+ }
+ tag(text) {
+ return this.tagTokens([text]);
+ }
+}
+
+describe("RecipeExecutor", () => {
+ let makeItem = () => {
+ let x = {
+ lhs: 2,
+ one: 1,
+ two: 2,
+ three: 3,
+ foo: "FOO",
+ bar: "BAR",
+ baz: ["one", "two", "three"],
+ qux: 42,
+ text: "This Is A_sentence.",
+ url:
+ "http://www.wonder.example.com/dir1/dir2a-dir2b/dir3+4?key1&key2=val2&key3&%26amp=%3D3+4",
+ url2:
+ "http://wonder.example.com/dir1/dir2a-dir2b/dir3+4?key1&key2=val2&key3&%26amp=%3D3+4",
+ map: {
+ c: 3,
+ a: 1,
+ b: 2,
+ },
+ map2: {
+ b: 2,
+ c: 3,
+ d: 4,
+ },
+ arr1: [2, 3, 4],
+ arr2: [3, 4, 5],
+ long: [3, 4, 5, 6, 7],
+ tags: {
+ a: {
+ aa: 0.1,
+ ab: 0.2,
+ ac: 0.3,
+ },
+ b: {
+ ba: 4,
+ bb: 5,
+ bc: 6,
+ },
+ },
+ bogus: {
+ a: {
+ aa: "0.1",
+ ab: "0.2",
+ ac: "0.3",
+ },
+ b: {
+ ba: "4",
+ bb: "5",
+ bc: "6",
+ },
+ },
+ zero: {
+ a: 0,
+ b: 0,
+ },
+ zaro: [0, 0],
+ };
+ return x;
+ };
+
+ let EPSILON = 0.00001;
+
+ let instance = new RecipeExecutor(
+ [
+ new MockTagger("nb", { tag1: 0.7 }),
+ new MockTagger("nb", { tag2: 0.86 }),
+ new MockTagger("nb", { tag3: 0.9 }),
+ new MockTagger("nb", { tag5: 0.9 }),
+ ],
+ {
+ tag1: new MockTagger("nmf", {
+ tag11: 0.9,
+ tag12: 0.8,
+ tag13: 0.7,
+ }),
+ tag2: new MockTagger("nmf", {
+ tag21: 0.8,
+ tag22: 0.7,
+ tag23: 0.6,
+ }),
+ tag3: new MockTagger("nmf", {
+ tag31: 0.7,
+ tag32: 0.6,
+ tag33: 0.5,
+ }),
+ tag4: new MockTagger("nmf", { tag41: 0.99 }),
+ },
+ tokenize
+ );
+ let item = null;
+
+ beforeEach(() => {
+ item = makeItem();
+ });
+
+ describe("#_assembleText", () => {
+ it("should simply copy a single string", () => {
+ assert.equal(instance._assembleText(item, ["foo"]), "FOO");
+ });
+ it("should append some strings with a space", () => {
+ assert.equal(instance._assembleText(item, ["foo", "bar"]), "FOO BAR");
+ });
+ it("should give an empty string for a missing field", () => {
+ assert.equal(instance._assembleText(item, ["missing"]), "");
+ });
+ it("should not double space an interior missing field", () => {
+ assert.equal(
+ instance._assembleText(item, ["foo", "missing", "bar"]),
+ "FOO BAR"
+ );
+ });
+ it("should splice in an array of strings", () => {
+ assert.equal(
+ instance._assembleText(item, ["foo", "baz", "bar"]),
+ "FOO one two three BAR"
+ );
+ });
+ it("should handle numbers", () => {
+ assert.equal(
+ instance._assembleText(item, ["foo", "qux", "bar"]),
+ "FOO 42 BAR"
+ );
+ });
+ });
+
+ describe("#naiveBayesTag", () => {
+ it("should understand NaiveBayesTextTagger", () => {
+ item = instance.naiveBayesTag(item, { fields: ["text"] });
+ assert.isTrue("nb_tags" in item);
+ assert.isTrue(!("tag1" in item.nb_tags));
+ assert.equal(item.nb_tags.tag2, 0.86);
+ assert.equal(item.nb_tags.tag3, 0.9);
+ assert.equal(item.nb_tags.tag5, 0.9);
+ assert.isTrue("nb_tokens" in item);
+ assert.deepEqual(item.nb_tokens, ["this", "is", "a", "sentence"]);
+ assert.isTrue("nb_tags_extended" in item);
+ assert.isTrue(!("tag1" in item.nb_tags_extended));
+ assert.deepEqual(item.nb_tags_extended.tag2, {
+ label: "tag2",
+ logProb: Math.log(0.86),
+ confident: true,
+ });
+ assert.deepEqual(item.nb_tags_extended.tag3, {
+ label: "tag3",
+ logProb: Math.log(0.9),
+ confident: true,
+ });
+ assert.deepEqual(item.nb_tags_extended.tag5, {
+ label: "tag5",
+ logProb: Math.log(0.9),
+ confident: true,
+ });
+ assert.isTrue("nb_tokens" in item);
+ assert.deepEqual(item.nb_tokens, ["this", "is", "a", "sentence"]);
+ });
+ });
+
+ describe("#conditionallyNmfTag", () => {
+ it("should do nothing if it's not nb tagged", () => {
+ item = instance.conditionallyNmfTag(item, {});
+ assert.equal(item, null);
+ });
+ it("should populate nmf tags for the nb tags", () => {
+ item = instance.naiveBayesTag(item, { fields: ["text"] });
+ item = instance.conditionallyNmfTag(item, {});
+ assert.isTrue("nb_tags" in item);
+ assert.deepEqual(item.nmf_tags, {
+ tag2: {
+ tag21: 0.8,
+ tag22: 0.7,
+ tag23: 0.6,
+ },
+ tag3: {
+ tag31: 0.7,
+ tag32: 0.6,
+ tag33: 0.5,
+ },
+ });
+ assert.deepEqual(item.nmf_tags_parent, {
+ tag21: "tag2",
+ tag22: "tag2",
+ tag23: "tag2",
+ tag31: "tag3",
+ tag32: "tag3",
+ tag33: "tag3",
+ });
+ });
+ it("should not populate nmf tags for things that were not nb tagged", () => {
+ item = instance.naiveBayesTag(item, { fields: ["text"] });
+ item = instance.conditionallyNmfTag(item, {});
+ assert.isTrue("nmf_tags" in item);
+ assert.isTrue(!("tag4" in item.nmf_tags));
+ assert.isTrue("nmf_tags_parent" in item);
+ assert.isTrue(!("tag4" in item.nmf_tags_parent));
+ });
+ });
+
+ describe("#acceptItemByFieldValue", () => {
+ it("should implement ==", () => {
+ assert.isTrue(
+ instance.acceptItemByFieldValue(item, {
+ field: "lhs",
+ op: "==",
+ rhsValue: 2,
+ }) !== null
+ );
+ assert.isTrue(
+ instance.acceptItemByFieldValue(item, {
+ field: "lhs",
+ op: "==",
+ rhsValue: 3,
+ }) === null
+ );
+ assert.isTrue(
+ instance.acceptItemByFieldValue(item, {
+ field: "lhs",
+ op: "==",
+ rhsField: "two",
+ }) !== null
+ );
+ assert.isTrue(
+ instance.acceptItemByFieldValue(item, {
+ field: "lhs",
+ op: "==",
+ rhsField: "three",
+ }) === null
+ );
+ });
+ it("should implement !=", () => {
+ assert.isTrue(
+ instance.acceptItemByFieldValue(item, {
+ field: "lhs",
+ op: "!=",
+ rhsValue: 2,
+ }) === null
+ );
+ assert.isTrue(
+ instance.acceptItemByFieldValue(item, {
+ field: "lhs",
+ op: "!=",
+ rhsValue: 3,
+ }) !== null
+ );
+ });
+ it("should implement < ", () => {
+ assert.isTrue(
+ instance.acceptItemByFieldValue(item, {
+ field: "lhs",
+ op: "<",
+ rhsValue: 1,
+ }) === null
+ );
+ assert.isTrue(
+ instance.acceptItemByFieldValue(item, {
+ field: "lhs",
+ op: "<",
+ rhsValue: 2,
+ }) === null
+ );
+ assert.isTrue(
+ instance.acceptItemByFieldValue(item, {
+ field: "lhs",
+ op: "<",
+ rhsValue: 3,
+ }) !== null
+ );
+ });
+ it("should implement <= ", () => {
+ assert.isTrue(
+ instance.acceptItemByFieldValue(item, {
+ field: "lhs",
+ op: "<=",
+ rhsValue: 1,
+ }) === null
+ );
+ assert.isTrue(
+ instance.acceptItemByFieldValue(item, {
+ field: "lhs",
+ op: "<=",
+ rhsValue: 2,
+ }) !== null
+ );
+ assert.isTrue(
+ instance.acceptItemByFieldValue(item, {
+ field: "lhs",
+ op: "<=",
+ rhsValue: 3,
+ }) !== null
+ );
+ });
+ it("should implement > ", () => {
+ assert.isTrue(
+ instance.acceptItemByFieldValue(item, {
+ field: "lhs",
+ op: ">",
+ rhsValue: 1,
+ }) !== null
+ );
+ assert.isTrue(
+ instance.acceptItemByFieldValue(item, {
+ field: "lhs",
+ op: ">",
+ rhsValue: 2,
+ }) === null
+ );
+ assert.isTrue(
+ instance.acceptItemByFieldValue(item, {
+ field: "lhs",
+ op: ">",
+ rhsValue: 3,
+ }) === null
+ );
+ });
+ it("should implement >= ", () => {
+ assert.isTrue(
+ instance.acceptItemByFieldValue(item, {
+ field: "lhs",
+ op: ">=",
+ rhsValue: 1,
+ }) !== null
+ );
+ assert.isTrue(
+ instance.acceptItemByFieldValue(item, {
+ field: "lhs",
+ op: ">=",
+ rhsValue: 2,
+ }) !== null
+ );
+ assert.isTrue(
+ instance.acceptItemByFieldValue(item, {
+ field: "lhs",
+ op: ">=",
+ rhsValue: 3,
+ }) === null
+ );
+ });
+ it("should skip items with missing fields", () => {
+ assert.isTrue(
+ instance.acceptItemByFieldValue(item, {
+ field: "no-left",
+ op: "==",
+ rhsValue: 1,
+ }) === null
+ );
+ assert.isTrue(
+ instance.acceptItemByFieldValue(item, {
+ field: "lhs",
+ op: "==",
+ rhsField: "no-right",
+ }) === null
+ );
+ assert.isTrue(
+ instance.acceptItemByFieldValue(item, { field: "lhs", op: "==" }) ===
+ null
+ );
+ });
+ it("should skip items with bogus operators", () => {
+ assert.isTrue(
+ instance.acceptItemByFieldValue(item, {
+ field: "lhs",
+ op: "bogus",
+ rhsField: "two",
+ }) === null
+ );
+ });
+ });
+
+ describe("#tokenizeUrl", () => {
+ it("should strip the leading www from a url", () => {
+ item = instance.tokenizeUrl(item, { field: "url", dest: "url_toks" });
+ assert.deepEqual(
+ [
+ "wonder",
+ "example",
+ "com",
+ "dir1",
+ "dir2a",
+ "dir2b",
+ "dir3",
+ "4",
+ "key1",
+ "key2",
+ "val2",
+ "key3",
+ "amp",
+ "3",
+ "4",
+ ],
+ item.url_toks
+ );
+ });
+ it("should tokenize the not strip the leading non-wwww token from a url", () => {
+ item = instance.tokenizeUrl(item, { field: "url2", dest: "url_toks" });
+ assert.deepEqual(
+ [
+ "wonder",
+ "example",
+ "com",
+ "dir1",
+ "dir2a",
+ "dir2b",
+ "dir3",
+ "4",
+ "key1",
+ "key2",
+ "val2",
+ "key3",
+ "amp",
+ "3",
+ "4",
+ ],
+ item.url_toks
+ );
+ });
+ it("should error for a missing url", () => {
+ item = instance.tokenizeUrl(item, { field: "missing", dest: "url_toks" });
+ assert.equal(item, null);
+ });
+ });
+
+ describe("#getUrlDomain", () => {
+ it("should get only the hostname skipping the www", () => {
+ item = instance.getUrlDomain(item, { field: "url", dest: "url_domain" });
+ assert.isTrue("url_domain" in item);
+ assert.deepEqual("wonder.example.com", item.url_domain);
+ });
+ it("should get only the hostname", () => {
+ item = instance.getUrlDomain(item, { field: "url2", dest: "url_domain" });
+ assert.isTrue("url_domain" in item);
+ assert.deepEqual("wonder.example.com", item.url_domain);
+ });
+ it("should get the hostname and 2 levels of directories", () => {
+ item = instance.getUrlDomain(item, {
+ field: "url",
+ path_length: 2,
+ dest: "url_plus_2",
+ });
+ assert.isTrue("url_plus_2" in item);
+ assert.deepEqual("wonder.example.com/dir1/dir2a-dir2b", item.url_plus_2);
+ });
+ it("should error for a missing url", () => {
+ item = instance.getUrlDomain(item, {
+ field: "missing",
+ dest: "url_domain",
+ });
+ assert.equal(item, null);
+ });
+ });
+
+ describe("#tokenizeField", () => {
+ it("should tokenize the field", () => {
+ item = instance.tokenizeField(item, { field: "text", dest: "toks" });
+ assert.isTrue("toks" in item);
+ assert.deepEqual(["this", "is", "a", "sentence"], item.toks);
+ });
+ it("should error for a missing field", () => {
+ item = instance.tokenizeField(item, { field: "missing", dest: "toks" });
+ assert.equal(item, null);
+ });
+ it("should error for a broken config", () => {
+ item = instance.tokenizeField(item, {});
+ assert.equal(item, null);
+ });
+ });
+
+ describe("#_typeOf", () => {
+ it("should know this is a map", () => {
+ assert.equal(instance._typeOf({}), "map");
+ });
+ it("should know this is an array", () => {
+ assert.equal(instance._typeOf([]), "array");
+ });
+ it("should know this is a string", () => {
+ assert.equal(instance._typeOf("blah"), "string");
+ });
+ it("should know this is a boolean", () => {
+ assert.equal(instance._typeOf(true), "boolean");
+ });
+
+ it("should know this is a null", () => {
+ assert.equal(instance._typeOf(null), "null");
+ });
+ });
+
+ describe("#_lookupScalar", () => {
+ it("should return the constant", () => {
+ assert.equal(instance._lookupScalar({}, 1, 0), 1);
+ });
+ it("should return the default", () => {
+ assert.equal(instance._lookupScalar({}, "blah", 42), 42);
+ });
+ it("should return the field's value", () => {
+ assert.equal(instance._lookupScalar({ blah: 11 }, "blah", 42), 11);
+ });
+ });
+
+ describe("#copyValue", () => {
+ it("should copy values", () => {
+ item = instance.copyValue(item, { src: "one", dest: "again" });
+ assert.isTrue("again" in item);
+ assert.equal(item.again, 1);
+ item.one = 100;
+ assert.equal(item.one, 100);
+ assert.equal(item.again, 1);
+ });
+ it("should handle maps corrects", () => {
+ item = instance.copyValue(item, { src: "map", dest: "again" });
+ assert.deepEqual(item.again, { a: 1, b: 2, c: 3 });
+ item.map.c = 100;
+ assert.deepEqual(item.again, { a: 1, b: 2, c: 3 });
+ item.map = 342;
+ assert.deepEqual(item.again, { a: 1, b: 2, c: 3 });
+ });
+ it("should error for a missing field", () => {
+ item = instance.copyValue(item, { src: "missing", dest: "toks" });
+ assert.equal(item, null);
+ });
+ });
+
+ describe("#keepTopK", () => {
+ it("should keep the 2 smallest", () => {
+ item = instance.keepTopK(item, { field: "map", k: 2, descending: false });
+ assert.equal(Object.keys(item.map).length, 2);
+ assert.isTrue("a" in item.map);
+ assert.equal(item.map.a, 1);
+ assert.isTrue("b" in item.map);
+ assert.equal(item.map.b, 2);
+ assert.isTrue(!("c" in item.map));
+ });
+ it("should keep the 2 largest", () => {
+ item = instance.keepTopK(item, { field: "map", k: 2, descending: true });
+ assert.equal(Object.keys(item.map).length, 2);
+ assert.isTrue(!("a" in item.map));
+ assert.isTrue("b" in item.map);
+ assert.equal(item.map.b, 2);
+ assert.isTrue("c" in item.map);
+ assert.equal(item.map.c, 3);
+ });
+ it("should still keep the 2 largest", () => {
+ item = instance.keepTopK(item, { field: "map", k: 2 });
+ assert.equal(Object.keys(item.map).length, 2);
+ assert.isTrue(!("a" in item.map));
+ assert.isTrue("b" in item.map);
+ assert.equal(item.map.b, 2);
+ assert.isTrue("c" in item.map);
+ assert.equal(item.map.c, 3);
+ });
+ it("should promote up nested fields", () => {
+ item = instance.keepTopK(item, { field: "tags", k: 2 });
+ assert.equal(Object.keys(item.tags).length, 2);
+ assert.deepEqual(item.tags, { bb: 5, bc: 6 });
+ });
+ it("should error for a missing field", () => {
+ item = instance.keepTopK(item, { field: "missing", k: 3 });
+ assert.equal(item, null);
+ });
+ });
+
+ describe("#scalarMultiply", () => {
+ it("should use constants", () => {
+ item = instance.scalarMultiply(item, { field: "map", k: 2 });
+ assert.equal(item.map.a, 2);
+ assert.equal(item.map.b, 4);
+ assert.equal(item.map.c, 6);
+ });
+ it("should use fields", () => {
+ item = instance.scalarMultiply(item, { field: "map", k: "three" });
+ assert.equal(item.map.a, 3);
+ assert.equal(item.map.b, 6);
+ assert.equal(item.map.c, 9);
+ });
+ it("should use default", () => {
+ item = instance.scalarMultiply(item, {
+ field: "map",
+ k: "missing",
+ dfault: 4,
+ });
+ assert.equal(item.map.a, 4);
+ assert.equal(item.map.b, 8);
+ assert.equal(item.map.c, 12);
+ });
+ it("should error for a missing field", () => {
+ item = instance.scalarMultiply(item, { field: "missing", k: 3 });
+ assert.equal(item, null);
+ });
+ it("should multiply numbers", () => {
+ item = instance.scalarMultiply(item, { field: "lhs", k: 2 });
+ assert.equal(item.lhs, 4);
+ });
+ it("should multiply arrays", () => {
+ item = instance.scalarMultiply(item, { field: "arr1", k: 2 });
+ assert.deepEqual(item.arr1, [4, 6, 8]);
+ });
+ it("should should error on strings", () => {
+ item = instance.scalarMultiply(item, { field: "foo", k: 2 });
+ assert.equal(item, null);
+ });
+ });
+
+ describe("#elementwiseMultiply", () => {
+ it("should handle maps", () => {
+ item = instance.elementwiseMultiply(item, {
+ left: "tags",
+ right: "map2",
+ });
+ assert.deepEqual(item.tags, {
+ a: { aa: 0, ab: 0, ac: 0 },
+ b: { ba: 8, bb: 10, bc: 12 },
+ });
+ });
+ it("should handle arrays of same length", () => {
+ item = instance.elementwiseMultiply(item, {
+ left: "arr1",
+ right: "arr2",
+ });
+ assert.deepEqual(item.arr1, [6, 12, 20]);
+ });
+ it("should error for arrays of different lengths", () => {
+ item = instance.elementwiseMultiply(item, {
+ left: "arr1",
+ right: "long",
+ });
+ assert.equal(item, null);
+ });
+ it("should error for a missing left", () => {
+ item = instance.elementwiseMultiply(item, {
+ left: "missing",
+ right: "arr2",
+ });
+ assert.equal(item, null);
+ });
+ it("should error for a missing right", () => {
+ item = instance.elementwiseMultiply(item, {
+ left: "arr1",
+ right: "missing",
+ });
+ assert.equal(item, null);
+ });
+ it("should handle numbers", () => {
+ item = instance.elementwiseMultiply(item, {
+ left: "three",
+ right: "two",
+ });
+ assert.equal(item.three, 6);
+ });
+ it("should error for mismatched types", () => {
+ item = instance.elementwiseMultiply(item, { left: "arr1", right: "two" });
+ assert.equal(item, null);
+ });
+ it("should error for strings", () => {
+ item = instance.elementwiseMultiply(item, { left: "foo", right: "bar" });
+ assert.equal(item, null);
+ });
+ });
+
+ describe("#vectorMultiply", () => {
+ it("should calculate dot products from maps", () => {
+ item = instance.vectorMultiply(item, {
+ left: "map",
+ right: "map2",
+ dest: "dot",
+ });
+ assert.equal(item.dot, 13);
+ });
+ it("should calculate dot products from arrays", () => {
+ item = instance.vectorMultiply(item, {
+ left: "arr1",
+ right: "arr2",
+ dest: "dot",
+ });
+ assert.equal(item.dot, 38);
+ });
+ it("should error for arrays of different lengths", () => {
+ item = instance.vectorMultiply(item, { left: "arr1", right: "long" });
+ assert.equal(item, null);
+ });
+ it("should error for a missing left", () => {
+ item = instance.vectorMultiply(item, { left: "missing", right: "arr2" });
+ assert.equal(item, null);
+ });
+ it("should error for a missing right", () => {
+ item = instance.vectorMultiply(item, { left: "arr1", right: "missing" });
+ assert.equal(item, null);
+ });
+ it("should error for mismatched types", () => {
+ item = instance.vectorMultiply(item, { left: "arr1", right: "two" });
+ assert.equal(item, null);
+ });
+ it("should error for strings", () => {
+ item = instance.vectorMultiply(item, { left: "foo", right: "bar" });
+ assert.equal(item, null);
+ });
+ });
+
+ describe("#scalarAdd", () => {
+ it("should error for a missing field", () => {
+ item = instance.scalarAdd(item, { field: "missing", k: 10 });
+ assert.equal(item, null);
+ });
+ it("should error for strings", () => {
+ item = instance.scalarAdd(item, { field: "foo", k: 10 });
+ assert.equal(item, null);
+ });
+ it("should work for numbers", () => {
+ item = instance.scalarAdd(item, { field: "one", k: 10 });
+ assert.equal(item.one, 11);
+ });
+ it("should add a constant to every cell on a map", () => {
+ item = instance.scalarAdd(item, { field: "map", k: 10 });
+ assert.deepEqual(item.map, { a: 11, b: 12, c: 13 });
+ });
+ it("should add a value from a field to every cell on a map", () => {
+ item = instance.scalarAdd(item, { field: "map", k: "qux" });
+ assert.deepEqual(item.map, { a: 43, b: 44, c: 45 });
+ });
+ it("should add a constant to every cell on an array", () => {
+ item = instance.scalarAdd(item, { field: "arr1", k: 10 });
+ assert.deepEqual(item.arr1, [12, 13, 14]);
+ });
+ });
+
+ describe("#vectorAdd", () => {
+ it("should calculate add vectors from maps", () => {
+ item = instance.vectorAdd(item, { left: "map", right: "map2" });
+ assert.equal(Object.keys(item.map).length, 4);
+ assert.isTrue("a" in item.map);
+ assert.equal(item.map.a, 1);
+ assert.isTrue("b" in item.map);
+ assert.equal(item.map.b, 4);
+ assert.isTrue("c" in item.map);
+ assert.equal(item.map.c, 6);
+ assert.isTrue("d" in item.map);
+ assert.equal(item.map.d, 4);
+ });
+ it("should work for missing left", () => {
+ item = instance.vectorAdd(item, { left: "missing", right: "arr2" });
+ assert.deepEqual(item.missing, [3, 4, 5]);
+ });
+ it("should error for missing right", () => {
+ item = instance.vectorAdd(item, { left: "arr2", right: "missing" });
+ assert.equal(item, null);
+ });
+ it("should error error for strings", () => {
+ item = instance.vectorAdd(item, { left: "foo", right: "bar" });
+ assert.equal(item, null);
+ });
+ it("should error for different types", () => {
+ item = instance.vectorAdd(item, { left: "arr2", right: "map" });
+ assert.equal(item, null);
+ });
+ it("should calculate add vectors from arrays", () => {
+ item = instance.vectorAdd(item, { left: "arr1", right: "arr2" });
+ assert.deepEqual(item.arr1, [5, 7, 9]);
+ });
+ it("should abort on different sized arrays", () => {
+ item = instance.vectorAdd(item, { left: "arr1", right: "long" });
+ assert.equal(item, null);
+ });
+ it("should calculate add vectors from arrays", () => {
+ item = instance.vectorAdd(item, { left: "arr1", right: "arr2" });
+ assert.deepEqual(item.arr1, [5, 7, 9]);
+ });
+ });
+
+ describe("#makeBoolean", () => {
+ it("should error for missing field", () => {
+ item = instance.makeBoolean(item, { field: "missing", threshold: 2 });
+ assert.equal(item, null);
+ });
+ it("should 0/1 a map", () => {
+ item = instance.makeBoolean(item, { field: "map", threshold: 2 });
+ assert.deepEqual(item.map, { a: 0, b: 0, c: 1 });
+ });
+ it("should a map of all 1s", () => {
+ item = instance.makeBoolean(item, { field: "map" });
+ assert.deepEqual(item.map, { a: 1, b: 1, c: 1 });
+ });
+ it("should -1/1 a map", () => {
+ item = instance.makeBoolean(item, {
+ field: "map",
+ threshold: 2,
+ keep_negative: true,
+ });
+ assert.deepEqual(item.map, { a: -1, b: -1, c: 1 });
+ });
+ it("should work an array", () => {
+ item = instance.makeBoolean(item, { field: "arr1", threshold: 3 });
+ assert.deepEqual(item.arr1, [0, 0, 1]);
+ });
+ it("should -1/1 an array", () => {
+ item = instance.makeBoolean(item, {
+ field: "arr1",
+ threshold: 3,
+ keep_negative: true,
+ });
+ assert.deepEqual(item.arr1, [-1, -1, 1]);
+ });
+ it("should 1 a high number", () => {
+ item = instance.makeBoolean(item, { field: "qux", threshold: 3 });
+ assert.equal(item.qux, 1);
+ });
+ it("should 0 a low number", () => {
+ item = instance.makeBoolean(item, { field: "qux", threshold: 70 });
+ assert.equal(item.qux, 0);
+ });
+ it("should -1 a low number", () => {
+ item = instance.makeBoolean(item, {
+ field: "qux",
+ threshold: 83,
+ keep_negative: true,
+ });
+ assert.equal(item.qux, -1);
+ });
+ it("should fail a string", () => {
+ item = instance.makeBoolean(item, { field: "foo", threshold: 3 });
+ assert.equal(item, null);
+ });
+ });
+
+ describe("#allowFields", () => {
+ it("should filter the keys out of a map", () => {
+ item = instance.allowFields(item, {
+ fields: ["foo", "missing", "bar"],
+ });
+ assert.deepEqual(item, { foo: "FOO", bar: "BAR" });
+ });
+ });
+
+ describe("#filterByValue", () => {
+ it("should fail on missing field", () => {
+ item = instance.filterByValue(item, { field: "missing", threshold: 2 });
+ assert.equal(item, null);
+ });
+ it("should filter the keys out of a map", () => {
+ item = instance.filterByValue(item, { field: "map", threshold: 2 });
+ assert.deepEqual(item.map, { c: 3 });
+ });
+ });
+
+ describe("#l2Normalize", () => {
+ it("should fail on missing field", () => {
+ item = instance.l2Normalize(item, { field: "missing" });
+ assert.equal(item, null);
+ });
+ it("should L2 normalize an array", () => {
+ item = instance.l2Normalize(item, { field: "arr1" });
+ assert.deepEqual(item.arr1, [
+ 0.3713906763541037,
+ 0.5570860145311556,
+ 0.7427813527082074,
+ ]);
+ });
+ it("should L2 normalize a map", () => {
+ item = instance.l2Normalize(item, { field: "map" });
+ assert.deepEqual(item.map, {
+ a: 0.2672612419124244,
+ b: 0.5345224838248488,
+ c: 0.8017837257372732,
+ });
+ });
+ it("should fail a string", () => {
+ item = instance.l2Normalize(item, { field: "foo" });
+ assert.equal(item, null);
+ });
+ it("should not bomb on a zero vector", () => {
+ item = instance.l2Normalize(item, { field: "zero" });
+ assert.deepEqual(item.zero, { a: 0, b: 0 });
+ item = instance.l2Normalize(item, { field: "zaro" });
+ assert.deepEqual(item.zaro, [0, 0]);
+ });
+ });
+
+ describe("#probNormalize", () => {
+ it("should fail on missing field", () => {
+ item = instance.probNormalize(item, { field: "missing" });
+ assert.equal(item, null);
+ });
+ it("should normalize an array to sum to 1", () => {
+ item = instance.probNormalize(item, { field: "arr1" });
+ assert.deepEqual(item.arr1, [
+ 0.2222222222222222,
+ 0.3333333333333333,
+ 0.4444444444444444,
+ ]);
+ });
+ it("should normalize a map to sum to 1", () => {
+ item = instance.probNormalize(item, { field: "map" });
+ assert.equal(Object.keys(item.map).length, 3);
+ assert.isTrue("a" in item.map);
+ assert.isTrue(Math.abs(item.map.a - 0.16667) <= EPSILON);
+ assert.isTrue("b" in item.map);
+ assert.isTrue(Math.abs(item.map.b - 0.33333) <= EPSILON);
+ assert.isTrue("c" in item.map);
+ assert.isTrue(Math.abs(item.map.c - 0.5) <= EPSILON);
+ });
+ it("should fail a string", () => {
+ item = instance.probNormalize(item, { field: "foo" });
+ assert.equal(item, null);
+ });
+ it("should not bomb on a zero vector", () => {
+ item = instance.probNormalize(item, { field: "zero" });
+ assert.deepEqual(item.zero, { a: 0, b: 0 });
+ item = instance.probNormalize(item, { field: "zaro" });
+ assert.deepEqual(item.zaro, [0, 0]);
+ });
+ });
+
+ describe("#scalarMultiplyTag", () => {
+ it("should fail on missing field", () => {
+ item = instance.scalarMultiplyTag(item, { field: "missing", k: 3 });
+ assert.equal(item, null);
+ });
+ it("should scalar multiply a nested map", () => {
+ item = instance.scalarMultiplyTag(item, {
+ field: "tags",
+ k: 3,
+ log_scale: false,
+ });
+ assert.isTrue(Math.abs(item.tags.a.aa - 0.3) <= EPSILON);
+ assert.isTrue(Math.abs(item.tags.a.ab - 0.6) <= EPSILON);
+ assert.isTrue(Math.abs(item.tags.a.ac - 0.9) <= EPSILON);
+ assert.isTrue(Math.abs(item.tags.b.ba - 12) <= EPSILON);
+ assert.isTrue(Math.abs(item.tags.b.bb - 15) <= EPSILON);
+ assert.isTrue(Math.abs(item.tags.b.bc - 18) <= EPSILON);
+ });
+ it("should scalar multiply a nested map with logrithms", () => {
+ item = instance.scalarMultiplyTag(item, {
+ field: "tags",
+ k: 3,
+ log_scale: true,
+ });
+ assert.isTrue(
+ Math.abs(item.tags.a.aa - Math.log(0.1 + 0.000001) * 3) <= EPSILON
+ );
+ assert.isTrue(
+ Math.abs(item.tags.a.ab - Math.log(0.2 + 0.000001) * 3) <= EPSILON
+ );
+ assert.isTrue(
+ Math.abs(item.tags.a.ac - Math.log(0.3 + 0.000001) * 3) <= EPSILON
+ );
+ assert.isTrue(
+ Math.abs(item.tags.b.ba - Math.log(4.0 + 0.000001) * 3) <= EPSILON
+ );
+ assert.isTrue(
+ Math.abs(item.tags.b.bb - Math.log(5.0 + 0.000001) * 3) <= EPSILON
+ );
+ assert.isTrue(
+ Math.abs(item.tags.b.bc - Math.log(6.0 + 0.000001) * 3) <= EPSILON
+ );
+ });
+ it("should fail a string", () => {
+ item = instance.scalarMultiplyTag(item, { field: "foo", k: 3 });
+ assert.equal(item, null);
+ });
+ });
+
+ describe("#setDefault", () => {
+ it("should store a missing value", () => {
+ item = instance.setDefault(item, { field: "missing", value: 1111 });
+ assert.equal(item.missing, 1111);
+ });
+ it("should not overwrite an existing value", () => {
+ item = instance.setDefault(item, { field: "lhs", value: 1111 });
+ assert.equal(item.lhs, 2);
+ });
+ it("should store a complex value", () => {
+ item = instance.setDefault(item, { field: "missing", value: { a: 1 } });
+ assert.deepEqual(item.missing, { a: 1 });
+ });
+ });
+
+ describe("#lookupValue", () => {
+ it("should promote a value", () => {
+ item = instance.lookupValue(item, {
+ haystack: "map",
+ needle: "c",
+ dest: "ccc",
+ });
+ assert.equal(item.ccc, 3);
+ });
+ it("should handle a missing haystack", () => {
+ item = instance.lookupValue(item, {
+ haystack: "missing",
+ needle: "c",
+ dest: "ccc",
+ });
+ assert.isTrue(!("ccc" in item));
+ });
+ it("should handle a missing needle", () => {
+ item = instance.lookupValue(item, {
+ haystack: "map",
+ needle: "missing",
+ dest: "ccc",
+ });
+ assert.isTrue(!("ccc" in item));
+ });
+ });
+
+ describe("#copyToMap", () => {
+ it("should copy a value to a map", () => {
+ item = instance.copyToMap(item, {
+ src: "qux",
+ dest_map: "map",
+ dest_key: "zzz",
+ });
+ assert.isTrue("zzz" in item.map);
+ assert.equal(item.map.zzz, item.qux);
+ });
+ it("should create a new map to hold the key", () => {
+ item = instance.copyToMap(item, {
+ src: "qux",
+ dest_map: "missing",
+ dest_key: "zzz",
+ });
+ assert.equal(Object.keys(item.missing).length, 1);
+ assert.equal(item.missing.zzz, item.qux);
+ });
+ it("should not create an empty map if the src is missing", () => {
+ item = instance.copyToMap(item, {
+ src: "missing",
+ dest_map: "no_map",
+ dest_key: "zzz",
+ });
+ assert.isTrue(!("no_map" in item));
+ });
+ });
+
+ describe("#applySoftmaxTags", () => {
+ it("should error on missing field", () => {
+ item = instance.applySoftmaxTags(item, { field: "missing" });
+ assert.equal(item, null);
+ });
+ it("should error on nonmaps", () => {
+ item = instance.applySoftmaxTags(item, { field: "arr1" });
+ assert.equal(item, null);
+ });
+ it("should error on unnested maps", () => {
+ item = instance.applySoftmaxTags(item, { field: "map" });
+ assert.equal(item, null);
+ });
+ it("should error on wrong nested maps", () => {
+ item = instance.applySoftmaxTags(item, { field: "bogus" });
+ assert.equal(item, null);
+ });
+ it("should apply softmax across the subtags", () => {
+ item = instance.applySoftmaxTags(item, { field: "tags" });
+ assert.isTrue("a" in item.tags);
+ assert.isTrue("aa" in item.tags.a);
+ assert.isTrue("ab" in item.tags.a);
+ assert.isTrue("ac" in item.tags.a);
+ assert.isTrue(Math.abs(item.tags.a.aa - 0.30061) <= EPSILON);
+ assert.isTrue(Math.abs(item.tags.a.ab - 0.33222) <= EPSILON);
+ assert.isTrue(Math.abs(item.tags.a.ac - 0.36717) <= EPSILON);
+
+ assert.isTrue("b" in item.tags);
+ assert.isTrue("ba" in item.tags.b);
+ assert.isTrue("bb" in item.tags.b);
+ assert.isTrue("bc" in item.tags.b);
+ assert.isTrue(Math.abs(item.tags.b.ba - 0.09003) <= EPSILON);
+ assert.isTrue(Math.abs(item.tags.b.bb - 0.24473) <= EPSILON);
+ assert.isTrue(Math.abs(item.tags.b.bc - 0.66524) <= EPSILON);
+ });
+ });
+
+ describe("#combinerAdd", () => {
+ it("should do nothing when right field is missing", () => {
+ let right = makeItem();
+ let combined = instance.combinerAdd(item, right, { field: "missing" });
+ assert.deepEqual(combined, item);
+ });
+ it("should handle missing left maps", () => {
+ let right = makeItem();
+ right.missingmap = { a: 5, b: -1, c: 3 };
+ let combined = instance.combinerAdd(item, right, { field: "missingmap" });
+ assert.deepEqual(combined.missingmap, { a: 5, b: -1, c: 3 });
+ });
+ it("should add equal sized maps", () => {
+ let right = makeItem();
+ let combined = instance.combinerAdd(item, right, { field: "map" });
+ assert.deepEqual(combined.map, { a: 2, b: 4, c: 6 });
+ });
+ it("should add long map to short map", () => {
+ let right = makeItem();
+ right.map.d = 999;
+ let combined = instance.combinerAdd(item, right, { field: "map" });
+ assert.deepEqual(combined.map, { a: 2, b: 4, c: 6, d: 999 });
+ });
+ it("should add short map to long map", () => {
+ let right = makeItem();
+ item.map.d = 999;
+ let combined = instance.combinerAdd(item, right, { field: "map" });
+ assert.deepEqual(combined.map, { a: 2, b: 4, c: 6, d: 999 });
+ });
+ it("should add equal sized arrays", () => {
+ let right = makeItem();
+ let combined = instance.combinerAdd(item, right, { field: "arr1" });
+ assert.deepEqual(combined.arr1, [4, 6, 8]);
+ });
+ it("should handle missing left arrays", () => {
+ let right = makeItem();
+ right.missingarray = [5, 1, 4];
+ let combined = instance.combinerAdd(item, right, {
+ field: "missingarray",
+ });
+ assert.deepEqual(combined.missingarray, [5, 1, 4]);
+ });
+ it("should add long array to short array", () => {
+ let right = makeItem();
+ right.arr1 = [2, 3, 4, 12];
+ let combined = instance.combinerAdd(item, right, { field: "arr1" });
+ assert.deepEqual(combined.arr1, [4, 6, 8, 12]);
+ });
+ it("should add short array to long array", () => {
+ let right = makeItem();
+ item.arr1 = [2, 3, 4, 12];
+ let combined = instance.combinerAdd(item, right, { field: "arr1" });
+ assert.deepEqual(combined.arr1, [4, 6, 8, 12]);
+ });
+ it("should handle missing left number", () => {
+ let right = makeItem();
+ right.missingnumber = 999;
+ let combined = instance.combinerAdd(item, right, {
+ field: "missingnumber",
+ });
+ assert.deepEqual(combined.missingnumber, 999);
+ });
+ it("should add numbers", () => {
+ let right = makeItem();
+ let combined = instance.combinerAdd(item, right, { field: "lhs" });
+ assert.equal(combined.lhs, 4);
+ });
+ it("should error on missing left, and right is a string", () => {
+ let right = makeItem();
+ right.error = "error";
+ let combined = instance.combinerAdd(item, right, { field: "error" });
+ assert.equal(combined, null);
+ });
+ it("should error on left string", () => {
+ let right = makeItem();
+ let combined = instance.combinerAdd(item, right, { field: "foo" });
+ assert.equal(combined, null);
+ });
+ it("should error on mismatch types", () => {
+ let right = makeItem();
+ right.lhs = [1, 2, 3];
+ let combined = instance.combinerAdd(item, right, { field: "lhs" });
+ assert.equal(combined, null);
+ });
+ });
+
+ describe("#combinerMax", () => {
+ it("should do nothing when right field is missing", () => {
+ let right = makeItem();
+ let combined = instance.combinerMax(item, right, { field: "missing" });
+ assert.deepEqual(combined, item);
+ });
+ it("should handle missing left maps", () => {
+ let right = makeItem();
+ right.missingmap = { a: 5, b: -1, c: 3 };
+ let combined = instance.combinerMax(item, right, { field: "missingmap" });
+ assert.deepEqual(combined.missingmap, { a: 5, b: -1, c: 3 });
+ });
+ it("should handle equal sized maps", () => {
+ let right = makeItem();
+ right.map = { a: 5, b: -1, c: 3 };
+ let combined = instance.combinerMax(item, right, { field: "map" });
+ assert.deepEqual(combined.map, { a: 5, b: 2, c: 3 });
+ });
+ it("should handle short map to long map", () => {
+ let right = makeItem();
+ right.map = { a: 5, b: -1, c: 3, d: 999 };
+ let combined = instance.combinerMax(item, right, { field: "map" });
+ assert.deepEqual(combined.map, { a: 5, b: 2, c: 3, d: 999 });
+ });
+ it("should handle long map to short map", () => {
+ let right = makeItem();
+ right.map = { a: 5, b: -1, c: 3 };
+ item.map.d = 999;
+ let combined = instance.combinerMax(item, right, { field: "map" });
+ assert.deepEqual(combined.map, { a: 5, b: 2, c: 3, d: 999 });
+ });
+ it("should handle equal sized arrays", () => {
+ let right = makeItem();
+ right.arr1 = [5, 1, 4];
+ let combined = instance.combinerMax(item, right, { field: "arr1" });
+ assert.deepEqual(combined.arr1, [5, 3, 4]);
+ });
+ it("should handle missing left arrays", () => {
+ let right = makeItem();
+ right.missingarray = [5, 1, 4];
+ let combined = instance.combinerMax(item, right, {
+ field: "missingarray",
+ });
+ assert.deepEqual(combined.missingarray, [5, 1, 4]);
+ });
+ it("should handle short array to long array", () => {
+ let right = makeItem();
+ right.arr1 = [5, 1, 4, 7];
+ let combined = instance.combinerMax(item, right, { field: "arr1" });
+ assert.deepEqual(combined.arr1, [5, 3, 4, 7]);
+ });
+ it("should handle long array to short array", () => {
+ let right = makeItem();
+ right.arr1 = [5, 1, 4];
+ item.arr1.push(7);
+ let combined = instance.combinerMax(item, right, { field: "arr1" });
+ assert.deepEqual(combined.arr1, [5, 3, 4, 7]);
+ });
+ it("should handle missing left number", () => {
+ let right = makeItem();
+ right.missingnumber = 999;
+ let combined = instance.combinerMax(item, right, {
+ field: "missingnumber",
+ });
+ assert.deepEqual(combined.missingnumber, 999);
+ });
+ it("should handle big number", () => {
+ let right = makeItem();
+ right.lhs = 99;
+ let combined = instance.combinerMax(item, right, { field: "lhs" });
+ assert.equal(combined.lhs, 99);
+ });
+ it("should handle small number", () => {
+ let right = makeItem();
+ item.lhs = 99;
+ let combined = instance.combinerMax(item, right, { field: "lhs" });
+ assert.equal(combined.lhs, 99);
+ });
+ it("should error on missing left, and right is a string", () => {
+ let right = makeItem();
+ right.error = "error";
+ let combined = instance.combinerMax(item, right, { field: "error" });
+ assert.equal(combined, null);
+ });
+ it("should error on left string", () => {
+ let right = makeItem();
+ let combined = instance.combinerMax(item, right, { field: "foo" });
+ assert.equal(combined, null);
+ });
+ it("should error on mismatch types", () => {
+ let right = makeItem();
+ right.lhs = [1, 2, 3];
+ let combined = instance.combinerMax(item, right, { field: "lhs" });
+ assert.equal(combined, null);
+ });
+ });
+
+ describe("#combinerCollectValues", () => {
+ it("should error on bogus operation", () => {
+ let right = makeItem();
+ right.url_domain = "maseratiusa.com/maserati";
+ right.time = 41;
+ let combined = instance.combinerCollectValues(item, right, {
+ left_field: "combined_map",
+ right_key_field: "url_domain",
+ right_value_field: "time",
+ operation: "missing",
+ });
+ assert.equal(combined, null);
+ });
+ it("should sum when missing left", () => {
+ let right = makeItem();
+ right.url_domain = "maseratiusa.com/maserati";
+ right.time = 41;
+ let combined = instance.combinerCollectValues(item, right, {
+ left_field: "combined_map",
+ right_key_field: "url_domain",
+ right_value_field: "time",
+ operation: "sum",
+ });
+ assert.deepEqual(combined.combined_map, {
+ "maseratiusa.com/maserati": 41,
+ });
+ });
+ it("should sum when missing right", () => {
+ let right = makeItem();
+ item.combined_map = { fake: 42 };
+ let combined = instance.combinerCollectValues(item, right, {
+ left_field: "combined_map",
+ right_key_field: "url_domain",
+ right_value_field: "time",
+ operation: "sum",
+ });
+ assert.deepEqual(combined.combined_map, { fake: 42 });
+ });
+ it("should sum when both", () => {
+ let right = makeItem();
+ right.url_domain = "maseratiusa.com/maserati";
+ right.time = 41;
+ item.combined_map = { fake: 42, "maseratiusa.com/maserati": 41 };
+ let combined = instance.combinerCollectValues(item, right, {
+ left_field: "combined_map",
+ right_key_field: "url_domain",
+ right_value_field: "time",
+ operation: "sum",
+ });
+ assert.deepEqual(combined.combined_map, {
+ fake: 42,
+ "maseratiusa.com/maserati": 82,
+ });
+ });
+
+ it("should max when missing left", () => {
+ let right = makeItem();
+ right.url_domain = "maseratiusa.com/maserati";
+ right.time = 41;
+ let combined = instance.combinerCollectValues(item, right, {
+ left_field: "combined_map",
+ right_key_field: "url_domain",
+ right_value_field: "time",
+ operation: "max",
+ });
+ assert.deepEqual(combined.combined_map, {
+ "maseratiusa.com/maserati": 41,
+ });
+ });
+ it("should max when missing right", () => {
+ let right = makeItem();
+ item.combined_map = { fake: 42 };
+ let combined = instance.combinerCollectValues(item, right, {
+ left_field: "combined_map",
+ right_key_field: "url_domain",
+ right_value_field: "time",
+ operation: "max",
+ });
+ assert.deepEqual(combined.combined_map, { fake: 42 });
+ });
+ it("should max when both (right)", () => {
+ let right = makeItem();
+ right.url_domain = "maseratiusa.com/maserati";
+ right.time = 99;
+ item.combined_map = { fake: 42, "maseratiusa.com/maserati": 41 };
+ let combined = instance.combinerCollectValues(item, right, {
+ left_field: "combined_map",
+ right_key_field: "url_domain",
+ right_value_field: "time",
+ operation: "max",
+ });
+ assert.deepEqual(combined.combined_map, {
+ fake: 42,
+ "maseratiusa.com/maserati": 99,
+ });
+ });
+ it("should max when both (left)", () => {
+ let right = makeItem();
+ right.url_domain = "maseratiusa.com/maserati";
+ right.time = -99;
+ item.combined_map = { fake: 42, "maseratiusa.com/maserati": 41 };
+ let combined = instance.combinerCollectValues(item, right, {
+ left_field: "combined_map",
+ right_key_field: "url_domain",
+ right_value_field: "time",
+ operation: "max",
+ });
+ assert.deepEqual(combined.combined_map, {
+ fake: 42,
+ "maseratiusa.com/maserati": 41,
+ });
+ });
+
+ it("should overwrite when missing left", () => {
+ let right = makeItem();
+ right.url_domain = "maseratiusa.com/maserati";
+ right.time = 41;
+ let combined = instance.combinerCollectValues(item, right, {
+ left_field: "combined_map",
+ right_key_field: "url_domain",
+ right_value_field: "time",
+ operation: "overwrite",
+ });
+ assert.deepEqual(combined.combined_map, {
+ "maseratiusa.com/maserati": 41,
+ });
+ });
+ it("should overwrite when missing right", () => {
+ let right = makeItem();
+ item.combined_map = { fake: 42 };
+ let combined = instance.combinerCollectValues(item, right, {
+ left_field: "combined_map",
+ right_key_field: "url_domain",
+ right_value_field: "time",
+ operation: "overwrite",
+ });
+ assert.deepEqual(combined.combined_map, { fake: 42 });
+ });
+ it("should overwrite when both", () => {
+ let right = makeItem();
+ right.url_domain = "maseratiusa.com/maserati";
+ right.time = 41;
+ item.combined_map = { fake: 42, "maseratiusa.com/maserati": 77 };
+ let combined = instance.combinerCollectValues(item, right, {
+ left_field: "combined_map",
+ right_key_field: "url_domain",
+ right_value_field: "time",
+ operation: "overwrite",
+ });
+ assert.deepEqual(combined.combined_map, {
+ fake: 42,
+ "maseratiusa.com/maserati": 41,
+ });
+ });
+
+ it("should count when missing left", () => {
+ let right = makeItem();
+ right.url_domain = "maseratiusa.com/maserati";
+ right.time = 41;
+ let combined = instance.combinerCollectValues(item, right, {
+ left_field: "combined_map",
+ right_key_field: "url_domain",
+ right_value_field: "time",
+ operation: "count",
+ });
+ assert.deepEqual(combined.combined_map, {
+ "maseratiusa.com/maserati": 1,
+ });
+ });
+ it("should count when missing right", () => {
+ let right = makeItem();
+ item.combined_map = { fake: 42 };
+ let combined = instance.combinerCollectValues(item, right, {
+ left_field: "combined_map",
+ right_key_field: "url_domain",
+ right_value_field: "time",
+ operation: "count",
+ });
+ assert.deepEqual(combined.combined_map, { fake: 42 });
+ });
+ it("should count when both", () => {
+ let right = makeItem();
+ right.url_domain = "maseratiusa.com/maserati";
+ right.time = 41;
+ item.combined_map = { fake: 42, "maseratiusa.com/maserati": 1 };
+ let combined = instance.combinerCollectValues(item, right, {
+ left_field: "combined_map",
+ right_key_field: "url_domain",
+ right_value_field: "time",
+ operation: "count",
+ });
+ assert.deepEqual(combined.combined_map, {
+ fake: 42,
+ "maseratiusa.com/maserati": 2,
+ });
+ });
+ });
+
+ describe("#executeRecipe", () => {
+ it("should handle working steps", () => {
+ let final = instance.executeRecipe({}, [
+ { function: "set_default", field: "foo", value: 1 },
+ { function: "set_default", field: "bar", value: 10 },
+ ]);
+ assert.equal(final.foo, 1);
+ assert.equal(final.bar, 10);
+ });
+ it("should handle unknown steps", () => {
+ let final = instance.executeRecipe({}, [
+ { function: "set_default", field: "foo", value: 1 },
+ { function: "missing" },
+ { function: "set_default", field: "bar", value: 10 },
+ ]);
+ assert.equal(final, null);
+ });
+ it("should handle erroring steps", () => {
+ let final = instance.executeRecipe({}, [
+ { function: "set_default", field: "foo", value: 1 },
+ {
+ function: "accept_item_by_field_value",
+ field: "missing",
+ op: "invalid",
+ rhsField: "moot",
+ rhsValue: "m00t",
+ },
+ { function: "set_default", field: "bar", value: 10 },
+ ]);
+ assert.equal(final, null);
+ });
+ });
+
+ describe("#executeCombinerRecipe", () => {
+ it("should handle working steps", () => {
+ let final = instance.executeCombinerRecipe(
+ { foo: 1, bar: 10 },
+ { foo: 1, bar: 10 },
+ [
+ { function: "combiner_add", field: "foo" },
+ { function: "combiner_add", field: "bar" },
+ ]
+ );
+ assert.equal(final.foo, 2);
+ assert.equal(final.bar, 20);
+ });
+ it("should handle unknown steps", () => {
+ let final = instance.executeCombinerRecipe(
+ { foo: 1, bar: 10 },
+ { foo: 1, bar: 10 },
+ [
+ { function: "combiner_add", field: "foo" },
+ { function: "missing" },
+ { function: "combiner_add", field: "bar" },
+ ]
+ );
+ assert.equal(final, null);
+ });
+ it("should handle erroring steps", () => {
+ let final = instance.executeCombinerRecipe(
+ { foo: 1, bar: 10, baz: 0 },
+ { foo: 1, bar: 10, baz: "hundred" },
+ [
+ { function: "combiner_add", field: "foo" },
+ { function: "combiner_add", field: "baz" },
+ { function: "combiner_add", field: "bar" },
+ ]
+ );
+ assert.equal(final, null);
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/lib/PersonalityProvider/Tokenize.test.js b/browser/components/newtab/test/unit/lib/PersonalityProvider/Tokenize.test.js
new file mode 100644
index 0000000000..8503c2903b
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/PersonalityProvider/Tokenize.test.js
@@ -0,0 +1,134 @@
+import {
+ tokenize,
+ toksToTfIdfVector,
+} from "lib/PersonalityProvider/Tokenize.jsm";
+
+const EPSILON = 0.00001;
+
+describe("TF-IDF Term Vectorizer", () => {
+ describe("#tokenize", () => {
+ let testCases = [
+ { input: "HELLO there", expected: ["hello", "there"] },
+ { input: "blah,,,blah,blah", expected: ["blah", "blah", "blah"] },
+ {
+ input: "Call Jenny: 967-5309",
+ expected: ["call", "jenny", "967", "5309"],
+ },
+ {
+ input: "Yo(what)[[hello]]{{jim}}}bob{1:2:1+2=$3",
+ expected: [
+ "yo",
+ "what",
+ "hello",
+ "jim",
+ "bob",
+ "1",
+ "2",
+ "1",
+ "2",
+ "3",
+ ],
+ },
+ { input: "čÄfė 80's", expected: ["čäfė", "80", "s"] },
+ { input: "我知道很多东西。", expected: ["我知道很多东西"] },
+ ];
+ let checkTokenization = tc => {
+ it(`${tc.input} should tokenize to ${tc.expected}`, () => {
+ assert.deepEqual(tc.expected, tokenize(tc.input));
+ });
+ };
+
+ for (let i = 0; i < testCases.length; i++) {
+ checkTokenization(testCases[i]);
+ }
+ });
+
+ describe("#tfidf", () => {
+ let vocab_idfs = {
+ deal: [221, 5.5058519847862275],
+ easy: [269, 5.5058519847862275],
+ tanks: [867, 5.601162164590552],
+ sites: [792, 5.957837108529285],
+ care: [153, 5.957837108529285],
+ needs: [596, 5.824305715904762],
+ finally: [334, 5.706522680248379],
+ };
+ let testCases = [
+ {
+ input: "Finally! Easy care for your tanks!",
+ expected: {
+ finally: [334, 0.5009816295853761],
+ easy: [269, 0.48336453811728713],
+ care: [153, 0.5230447876368227],
+ tanks: [867, 0.49173191907236774],
+ },
+ },
+ {
+ input: "Easy easy EASY",
+ expected: { easy: [269, 1.0] },
+ },
+ {
+ input: "Easy easy care",
+ expected: {
+ easy: [269, 0.8795205218806832],
+ care: [153, 0.4758609582543317],
+ },
+ },
+ {
+ input: "easy care",
+ expected: {
+ easy: [269, 0.6786999710383944],
+ care: [153, 0.7344156515982504],
+ },
+ },
+ {
+ input: "这个空间故意留空。",
+ expected: {
+ /* This space is left intentionally blank. */
+ },
+ },
+ ];
+ let checkTokenGeneration = tc => {
+ describe(`${tc.input} should have only vocabulary tokens`, () => {
+ let actual = toksToTfIdfVector(tokenize(tc.input), vocab_idfs);
+
+ it(`${tc.input} should generate exactly ${Object.keys(
+ tc.expected
+ )}`, () => {
+ let seen = {};
+ Object.keys(actual).forEach(actualTok => {
+ assert.isTrue(actualTok in tc.expected);
+ seen[actualTok] = true;
+ });
+ Object.keys(tc.expected).forEach(expectedTok => {
+ assert.isTrue(expectedTok in seen);
+ });
+ });
+
+ it(`${tc.input} should have the correct token ids`, () => {
+ Object.keys(actual).forEach(actualTok => {
+ assert.equal(tc.expected[actualTok][0], actual[actualTok][0]);
+ });
+ });
+ });
+ };
+
+ let checkTfIdfVector = tc => {
+ let actual = toksToTfIdfVector(tokenize(tc.input), vocab_idfs);
+ it(`${tc.input} should have the correct tf-idf`, () => {
+ Object.keys(actual).forEach(actualTok => {
+ let delta = Math.abs(
+ tc.expected[actualTok][1] - actual[actualTok][1]
+ );
+ assert.isTrue(delta <= EPSILON);
+ });
+ });
+ };
+
+ // run the tests
+ for (let i = 0; i < testCases.length; i++) {
+ checkTokenGeneration(testCases[i]);
+ checkTfIdfVector(testCases[i]);
+ }
+ });
+});
diff --git a/browser/components/newtab/test/unit/lib/PlacesFeed.test.js b/browser/components/newtab/test/unit/lib/PlacesFeed.test.js
new file mode 100644
index 0000000000..3790fc99b8
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/PlacesFeed.test.js
@@ -0,0 +1,1139 @@
+import { actionCreators as ac, actionTypes as at } from "common/Actions.jsm";
+import { GlobalOverrider } from "test/unit/utils";
+import { PlacesFeed } from "lib/PlacesFeed.jsm";
+const { HistoryObserver, BookmarksObserver, PlacesObserver } = PlacesFeed;
+
+const FAKE_BOOKMARK = {
+ bookmarkGuid: "xi31",
+ bookmarkTitle: "Foo",
+ dateAdded: 123214232,
+ url: "foo.com",
+};
+const TYPE_BOOKMARK = 0; // This is fake, for testing
+const SOURCES = {
+ DEFAULT: 0,
+ SYNC: 1,
+ IMPORT: 2,
+ RESTORE: 5,
+ RESTORE_ON_STARTUP: 6,
+};
+
+const BLOCKED_EVENT = "newtab-linkBlocked"; // The event dispatched in NewTabUtils when a link is blocked;
+
+describe("PlacesFeed", () => {
+ let globals;
+ let sandbox;
+ let feed;
+ beforeEach(() => {
+ globals = new GlobalOverrider();
+ sandbox = globals.sandbox;
+ globals.set("NewTabUtils", {
+ activityStreamProvider: { getBookmark() {} },
+ activityStreamLinks: {
+ addBookmark: sandbox.spy(),
+ deleteBookmark: sandbox.spy(),
+ deleteHistoryEntry: sandbox.spy(),
+ blockURL: sandbox.spy(),
+ addPocketEntry: sandbox.spy(() => Promise.resolve()),
+ deletePocketEntry: sandbox.spy(() => Promise.resolve()),
+ archivePocketEntry: sandbox.spy(() => Promise.resolve()),
+ },
+ });
+ globals.set("PartnerLinkAttribution", {
+ makeRequest: sandbox.spy(),
+ });
+ sandbox
+ .stub(global.PlacesUtils.bookmarks, "TYPE_BOOKMARK")
+ .value(TYPE_BOOKMARK);
+ sandbox.stub(global.PlacesUtils.bookmarks, "SOURCES").value(SOURCES);
+ sandbox.spy(global.PlacesUtils.bookmarks, "addObserver");
+ sandbox.spy(global.PlacesUtils.bookmarks, "removeObserver");
+ sandbox.spy(global.PlacesUtils.history, "addObserver");
+ sandbox.spy(global.PlacesUtils.history, "removeObserver");
+ sandbox.spy(global.PlacesUtils.observers, "addListener");
+ sandbox.spy(global.PlacesUtils.observers, "removeListener");
+ sandbox.spy(global.Services.obs, "addObserver");
+ sandbox.spy(global.Services.obs, "removeObserver");
+ sandbox.spy(global.Cu, "reportError");
+
+ global.Services.io.newURI = spec => ({
+ mutate: () => ({
+ setRef: ref => ({
+ finalize: () => ({
+ ref,
+ spec,
+ }),
+ }),
+ }),
+ spec,
+ scheme: "https",
+ });
+
+ global.Cc["@mozilla.org/timer;1"] = {
+ createInstance() {
+ return {
+ initWithCallback: sinon.stub().callsFake(callback => callback()),
+ cancel: sinon.spy(),
+ };
+ },
+ };
+ feed = new PlacesFeed();
+ feed.store = { dispatch: sinon.spy() };
+ });
+ afterEach(() => globals.restore());
+
+ it("should have a HistoryObserver that dispatches to the store", () => {
+ assert.instanceOf(feed.historyObserver, HistoryObserver);
+ const action = { type: "FOO" };
+
+ feed.historyObserver.dispatch(action);
+
+ assert.calledOnce(feed.store.dispatch);
+ assert.equal(feed.store.dispatch.firstCall.args[0].type, action.type);
+ });
+
+ it("should have a BookmarksObserver that dispatch to the store", () => {
+ assert.instanceOf(feed.bookmarksObserver, BookmarksObserver);
+ const action = { type: "FOO" };
+
+ feed.bookmarksObserver.dispatch(action);
+
+ assert.calledOnce(feed.store.dispatch);
+ assert.equal(feed.store.dispatch.firstCall.args[0].type, action.type);
+ });
+
+ it("should have a PlacesObserver that dispatches to the store", () => {
+ assert.instanceOf(feed.placesObserver, PlacesObserver);
+ const action = { type: "FOO" };
+
+ feed.placesObserver.dispatch(action);
+
+ assert.calledOnce(feed.store.dispatch);
+ assert.equal(feed.store.dispatch.firstCall.args[0].type, action.type);
+ });
+ describe("#onAction", () => {
+ it("should add bookmark, history, places, blocked observers on INIT", () => {
+ feed.onAction({ type: at.INIT });
+
+ assert.calledWith(
+ global.PlacesUtils.history.addObserver,
+ feed.historyObserver,
+ true
+ );
+ assert.calledWith(
+ global.PlacesUtils.bookmarks.addObserver,
+ feed.bookmarksObserver,
+ true
+ );
+ assert.calledWith(
+ global.PlacesUtils.observers.addListener,
+ ["bookmark-added", "bookmark-removed", "history-cleared"],
+ feed.placesObserver.handlePlacesEvent
+ );
+ assert.calledWith(global.Services.obs.addObserver, feed, BLOCKED_EVENT);
+ });
+ it("should remove bookmark, history, places, blocked observers, and timers on UNINIT", () => {
+ feed.placesChangedTimer = global.Cc[
+ "@mozilla.org/timer;1"
+ ].createInstance();
+ let spy = feed.placesChangedTimer.cancel;
+ feed.onAction({ type: at.UNINIT });
+
+ assert.calledWith(
+ global.PlacesUtils.history.removeObserver,
+ feed.historyObserver
+ );
+ assert.calledWith(
+ global.PlacesUtils.bookmarks.removeObserver,
+ feed.bookmarksObserver
+ );
+ assert.calledWith(
+ global.PlacesUtils.observers.removeListener,
+ ["bookmark-added", "bookmark-removed", "history-cleared"],
+ feed.placesObserver.handlePlacesEvent
+ );
+ assert.calledWith(
+ global.Services.obs.removeObserver,
+ feed,
+ BLOCKED_EVENT
+ );
+ assert.equal(feed.placesChangedTimer, null);
+ assert.calledOnce(spy);
+ });
+ it("should block a url on BLOCK_URL", () => {
+ feed.onAction({
+ type: at.BLOCK_URL,
+ data: [{ url: "apple.com", pocket_id: 1234 }],
+ });
+ assert.calledWith(global.NewTabUtils.activityStreamLinks.blockURL, {
+ url: "apple.com",
+ pocket_id: 1234,
+ });
+ });
+ it("should bookmark a url on BOOKMARK_URL", () => {
+ const data = { url: "pear.com", title: "A pear" };
+ const _target = { browser: { ownerGlobal() {} } };
+ feed.onAction({ type: at.BOOKMARK_URL, data, _target });
+ assert.calledWith(
+ global.NewTabUtils.activityStreamLinks.addBookmark,
+ data,
+ _target.browser.ownerGlobal
+ );
+ });
+ it("should delete a bookmark on DELETE_BOOKMARK_BY_ID", () => {
+ feed.onAction({ type: at.DELETE_BOOKMARK_BY_ID, data: "g123kd" });
+ assert.calledWith(
+ global.NewTabUtils.activityStreamLinks.deleteBookmark,
+ "g123kd"
+ );
+ });
+ it("should delete a history entry on DELETE_HISTORY_URL", () => {
+ feed.onAction({
+ type: at.DELETE_HISTORY_URL,
+ data: { url: "guava.com", forceBlock: null },
+ });
+ assert.calledWith(
+ global.NewTabUtils.activityStreamLinks.deleteHistoryEntry,
+ "guava.com"
+ );
+ assert.notCalled(global.NewTabUtils.activityStreamLinks.blockURL);
+ });
+ it("should delete a history entry on DELETE_HISTORY_URL and force a site to be blocked if specified", () => {
+ feed.onAction({
+ type: at.DELETE_HISTORY_URL,
+ data: { url: "guava.com", forceBlock: "g123kd" },
+ });
+ assert.calledWith(
+ global.NewTabUtils.activityStreamLinks.deleteHistoryEntry,
+ "guava.com"
+ );
+ assert.calledWith(global.NewTabUtils.activityStreamLinks.blockURL, {
+ url: "guava.com",
+ pocket_id: undefined,
+ });
+ });
+ it("should call openTrustedLinkIn with the correct url, where and params on OPEN_NEW_WINDOW", () => {
+ const openTrustedLinkIn = sinon.stub();
+ const openWindowAction = {
+ type: at.OPEN_NEW_WINDOW,
+ data: { url: "https://foo.com" },
+ _target: { browser: { ownerGlobal: { openTrustedLinkIn } } },
+ };
+
+ feed.onAction(openWindowAction);
+
+ assert.calledOnce(openTrustedLinkIn);
+ const [url, where, params] = openTrustedLinkIn.firstCall.args;
+ assert.equal(url, "https://foo.com");
+ assert.equal(where, "window");
+ assert.propertyVal(params, "private", false);
+ assert.propertyVal(params, "fromChrome", false);
+ });
+ it("should call openTrustedLinkIn with the correct url, where, params and privacy args on OPEN_PRIVATE_WINDOW", () => {
+ const openTrustedLinkIn = sinon.stub();
+ const openWindowAction = {
+ type: at.OPEN_PRIVATE_WINDOW,
+ data: { url: "https://foo.com" },
+ _target: { browser: { ownerGlobal: { openTrustedLinkIn } } },
+ };
+
+ feed.onAction(openWindowAction);
+
+ assert.calledOnce(openTrustedLinkIn);
+ const [url, where, params] = openTrustedLinkIn.firstCall.args;
+ assert.equal(url, "https://foo.com");
+ assert.equal(where, "window");
+ assert.propertyVal(params, "private", true);
+ assert.propertyVal(params, "fromChrome", false);
+ });
+ it("should call openTrustedLinkIn with the correct url, where and params on OPEN_LINK", () => {
+ const openTrustedLinkIn = sinon.stub();
+ const openLinkAction = {
+ type: at.OPEN_LINK,
+ data: { url: "https://foo.com" },
+ _target: {
+ browser: {
+ ownerGlobal: { openTrustedLinkIn, whereToOpenLink: e => "current" },
+ },
+ },
+ };
+
+ feed.onAction(openLinkAction);
+
+ assert.calledOnce(openTrustedLinkIn);
+ const [url, where, params] = openTrustedLinkIn.firstCall.args;
+ assert.equal(url, "https://foo.com");
+ assert.equal(where, "current");
+ assert.propertyVal(params, "private", false);
+ assert.propertyVal(params, "fromChrome", false);
+ });
+ it("should open link with referrer on OPEN_LINK", () => {
+ const openTrustedLinkIn = sinon.stub();
+ const openLinkAction = {
+ type: at.OPEN_LINK,
+ data: { url: "https://foo.com", referrer: "https://foo.com/ref" },
+ _target: {
+ browser: {
+ ownerGlobal: { openTrustedLinkIn, whereToOpenLink: e => "tab" },
+ },
+ },
+ };
+
+ feed.onAction(openLinkAction);
+
+ const [, , params] = openTrustedLinkIn.firstCall.args;
+ assert.nestedPropertyVal(params, "referrerInfo.referrerPolicy", 5);
+ assert.nestedPropertyVal(
+ params,
+ "referrerInfo.originalReferrer.spec",
+ "https://foo.com/ref"
+ );
+ });
+ it("should mark link with typed bonus as typed before opening OPEN_LINK", () => {
+ const callOrder = [];
+ sinon
+ .stub(global.PlacesUtils.history, "markPageAsTyped")
+ .callsFake(() => {
+ callOrder.push("markPageAsTyped");
+ });
+ const openTrustedLinkIn = sinon.stub().callsFake(() => {
+ callOrder.push("openTrustedLinkIn");
+ });
+ const openLinkAction = {
+ type: at.OPEN_LINK,
+ data: {
+ typedBonus: true,
+ url: "https://foo.com",
+ },
+ _target: {
+ browser: {
+ ownerGlobal: { openTrustedLinkIn, whereToOpenLink: e => "tab" },
+ },
+ },
+ };
+
+ feed.onAction(openLinkAction);
+
+ assert.sameOrderedMembers(callOrder, [
+ "markPageAsTyped",
+ "openTrustedLinkIn",
+ ]);
+ });
+ it("should open the pocket link if it's a pocket story on OPEN_LINK", () => {
+ const openTrustedLinkIn = sinon.stub();
+ const openLinkAction = {
+ type: at.OPEN_LINK,
+ data: {
+ url: "https://foo.com",
+ open_url: "getpocket.com/foo",
+ type: "pocket",
+ },
+ _target: {
+ browser: {
+ ownerGlobal: { openTrustedLinkIn, whereToOpenLink: e => "current" },
+ },
+ },
+ };
+
+ feed.onAction(openLinkAction);
+
+ assert.calledOnce(openTrustedLinkIn);
+ const [url, where, params] = openTrustedLinkIn.firstCall.args;
+ assert.equal(url, "getpocket.com/foo");
+ assert.equal(where, "current");
+ assert.propertyVal(params, "private", false);
+ });
+ it("should not open link if not http", () => {
+ const openTrustedLinkIn = sinon.stub();
+ global.Services.io.newURI = spec => ({
+ mutate: () => ({
+ setRef: ref => ({
+ finalize: () => ({
+ ref,
+ spec,
+ }),
+ }),
+ }),
+ spec,
+ scheme: "file",
+ });
+ const openLinkAction = {
+ type: at.OPEN_LINK,
+ data: { url: "file:///foo.com" },
+ _target: {
+ browser: {
+ ownerGlobal: { openTrustedLinkIn, whereToOpenLink: e => "current" },
+ },
+ },
+ };
+
+ feed.onAction(openLinkAction);
+ const [e] = global.Cu.reportError.firstCall.args;
+ assert.equal(
+ e.message,
+ "Can't open link using file protocol from the new tab page."
+ );
+ });
+ it("should call fillSearchTopSiteTerm on FILL_SEARCH_TERM", () => {
+ sinon.stub(feed, "fillSearchTopSiteTerm");
+
+ feed.onAction({ type: at.FILL_SEARCH_TERM });
+
+ assert.calledOnce(feed.fillSearchTopSiteTerm);
+ });
+ it("should call openTrustedLinkIn with the correct SUMO url on ABOUT_SPONSORED_TOP_SITES", () => {
+ const openTrustedLinkIn = sinon.stub();
+ const openLinkAction = {
+ type: at.ABOUT_SPONSORED_TOP_SITES,
+ _target: {
+ browser: {
+ ownerGlobal: { openTrustedLinkIn },
+ },
+ },
+ };
+
+ feed.onAction(openLinkAction);
+
+ assert.calledOnce(openTrustedLinkIn);
+ const [url, where] = openTrustedLinkIn.firstCall.args;
+ assert.equal(url.endsWith("sponsor-privacy"), true);
+ assert.equal(where, "tab");
+ });
+ it("should set the URL bar value to the label value", async () => {
+ const locationBar = { search: sandbox.stub() };
+ const action = {
+ type: at.FILL_SEARCH_TERM,
+ data: { label: "@Foo" },
+ _target: { browser: { ownerGlobal: { gURLBar: locationBar } } },
+ };
+
+ await feed.fillSearchTopSiteTerm(action);
+
+ assert.calledOnce(locationBar.search);
+ assert.calledWithExactly(locationBar.search, "@Foo", {
+ searchEngine: null,
+ searchModeEntry: "topsites_newtab",
+ });
+ });
+ it("should call saveToPocket on SAVE_TO_POCKET", () => {
+ const action = {
+ type: at.SAVE_TO_POCKET,
+ data: { site: { url: "raspberry.com", title: "raspberry" } },
+ _target: { browser: {} },
+ };
+ sinon.stub(feed, "saveToPocket");
+ feed.onAction(action);
+ assert.calledWithExactly(
+ feed.saveToPocket,
+ action.data.site,
+ action._target.browser
+ );
+ });
+ it("should call NewTabUtils.activityStreamLinks.addPocketEntry if we are saving a pocket story", async () => {
+ const action = {
+ data: { site: { url: "raspberry.com", title: "raspberry" } },
+ _target: { browser: {} },
+ };
+ await feed.saveToPocket(action.data.site, action._target.browser);
+ assert.calledOnce(global.NewTabUtils.activityStreamLinks.addPocketEntry);
+ assert.calledWithExactly(
+ global.NewTabUtils.activityStreamLinks.addPocketEntry,
+ action.data.site.url,
+ action.data.site.title,
+ action._target.browser
+ );
+ });
+ it("should reject the promise if NewTabUtils.activityStreamLinks.addPocketEntry rejects", async () => {
+ const e = new Error("Error");
+ const action = {
+ data: { site: { url: "raspberry.com", title: "raspberry" } },
+ _target: { browser: {} },
+ };
+ global.NewTabUtils.activityStreamLinks.addPocketEntry = sandbox
+ .stub()
+ .rejects(e);
+ await feed.saveToPocket(action.data.site, action._target.browser);
+ assert.calledWith(global.Cu.reportError, e);
+ });
+ it("should broadcast to content if we successfully added a link to Pocket", async () => {
+ // test in the form that the API returns data based on: https://getpocket.com/developer/docs/v3/add
+ global.NewTabUtils.activityStreamLinks.addPocketEntry = sandbox
+ .stub()
+ .resolves({ item: { open_url: "pocket.com/itemID", item_id: 1234 } });
+ const action = {
+ data: { site: { url: "raspberry.com", title: "raspberry" } },
+ _target: { browser: {} },
+ };
+ await feed.saveToPocket(action.data.site, action._target.browser);
+ assert.equal(
+ feed.store.dispatch.firstCall.args[0].type,
+ at.PLACES_SAVED_TO_POCKET
+ );
+ assert.deepEqual(feed.store.dispatch.firstCall.args[0].data, {
+ url: "raspberry.com",
+ title: "raspberry",
+ pocket_id: 1234,
+ open_url: "pocket.com/itemID",
+ });
+ });
+ it("should only broadcast if we got some data back from addPocketEntry", async () => {
+ global.NewTabUtils.activityStreamLinks.addPocketEntry = sandbox
+ .stub()
+ .resolves(null);
+ const action = {
+ data: { site: { url: "raspberry.com", title: "raspberry" } },
+ _target: { browser: {} },
+ };
+ await feed.saveToPocket(action.data.site, action._target.browser);
+ assert.notCalled(feed.store.dispatch);
+ });
+ it("should call deleteFromPocket on DELETE_FROM_POCKET", () => {
+ sandbox.stub(feed, "deleteFromPocket");
+ feed.onAction({
+ type: at.DELETE_FROM_POCKET,
+ data: { pocket_id: 12345 },
+ });
+
+ assert.calledOnce(feed.deleteFromPocket);
+ assert.calledWithExactly(feed.deleteFromPocket, 12345);
+ });
+ it("should catch if deletePocketEntry throws", async () => {
+ const e = new Error("Error");
+ global.NewTabUtils.activityStreamLinks.deletePocketEntry = sandbox
+ .stub()
+ .rejects(e);
+ await feed.deleteFromPocket(12345);
+
+ assert.calledWith(global.Cu.reportError, e);
+ });
+ it("should call NewTabUtils.deletePocketEntry and dispatch POCKET_LINK_DELETED_OR_ARCHIVED when deleting from Pocket", async () => {
+ await feed.deleteFromPocket(12345);
+
+ assert.calledOnce(
+ global.NewTabUtils.activityStreamLinks.deletePocketEntry
+ );
+ assert.calledWith(
+ global.NewTabUtils.activityStreamLinks.deletePocketEntry,
+ 12345
+ );
+
+ assert.calledOnce(feed.store.dispatch);
+ assert.calledWith(feed.store.dispatch, {
+ type: at.POCKET_LINK_DELETED_OR_ARCHIVED,
+ });
+ });
+ it("should call archiveFromPocket on ARCHIVE_FROM_POCKET", async () => {
+ sandbox.stub(feed, "archiveFromPocket");
+ await feed.onAction({
+ type: at.ARCHIVE_FROM_POCKET,
+ data: { pocket_id: 12345 },
+ });
+
+ assert.calledOnce(feed.archiveFromPocket);
+ assert.calledWithExactly(feed.archiveFromPocket, 12345);
+ });
+ it("should catch if archiveFromPocket throws", async () => {
+ const e = new Error("Error");
+ global.NewTabUtils.activityStreamLinks.archivePocketEntry = sandbox
+ .stub()
+ .rejects(e);
+ await feed.archiveFromPocket(12345);
+
+ assert.calledWith(global.Cu.reportError, e);
+ });
+ it("should call NewTabUtils.archivePocketEntry and dispatch POCKET_LINK_DELETED_OR_ARCHIVED when archiving from Pocket", async () => {
+ await feed.archiveFromPocket(12345);
+
+ assert.calledOnce(
+ global.NewTabUtils.activityStreamLinks.archivePocketEntry
+ );
+ assert.calledWith(
+ global.NewTabUtils.activityStreamLinks.archivePocketEntry,
+ 12345
+ );
+
+ assert.calledOnce(feed.store.dispatch);
+ assert.calledWith(feed.store.dispatch, {
+ type: at.POCKET_LINK_DELETED_OR_ARCHIVED,
+ });
+ });
+ it("should call handoffSearchToAwesomebar on HANDOFF_SEARCH_TO_AWESOMEBAR", () => {
+ const action = {
+ type: at.HANDOFF_SEARCH_TO_AWESOMEBAR,
+ data: { text: "f" },
+ meta: { fromTarget: {} },
+ _target: { browser: { ownerGlobal: { gURLBar: { focus: () => {} } } } },
+ };
+ sinon.stub(feed, "handoffSearchToAwesomebar");
+ feed.onAction(action);
+ assert.calledWith(feed.handoffSearchToAwesomebar, action);
+ });
+ it("should call makeAttributionRequest on PARTNER_LINK_ATTRIBUTION", () => {
+ sinon.stub(feed, "makeAttributionRequest");
+ let data = { targetURL: "https://partnersite.com", source: "topsites" };
+ feed.onAction({
+ type: at.PARTNER_LINK_ATTRIBUTION,
+ data,
+ });
+
+ assert.calledOnce(feed.makeAttributionRequest);
+ assert.calledWithExactly(feed.makeAttributionRequest, data);
+ });
+ it("should call PartnerLinkAttribution.makeRequest when calling makeAttributionRequest", () => {
+ let data = { targetURL: "https://partnersite.com", source: "topsites" };
+ feed.makeAttributionRequest(data);
+ assert.calledOnce(global.PartnerLinkAttribution.makeRequest);
+ });
+ });
+
+ describe("handoffSearchToAwesomebar", () => {
+ let fakeUrlBar;
+ let listeners;
+
+ beforeEach(() => {
+ fakeUrlBar = {
+ focus: sinon.spy(),
+ search: sinon.spy(),
+ setHiddenFocus: sinon.spy(),
+ removeHiddenFocus: sinon.spy(),
+ addEventListener: (ev, cb) => {
+ listeners[ev] = cb;
+ },
+ removeEventListener: sinon.spy(),
+ };
+ listeners = {};
+ });
+ it("should properly handle handoff with no text passed in", () => {
+ feed.handoffSearchToAwesomebar({
+ _target: { browser: { ownerGlobal: { gURLBar: fakeUrlBar } } },
+ data: {},
+ meta: { fromTarget: {} },
+ });
+ assert.calledOnce(fakeUrlBar.setHiddenFocus);
+ assert.notCalled(fakeUrlBar.search);
+ assert.notCalled(feed.store.dispatch);
+
+ // Now type a character.
+ listeners.keydown({ key: "f" });
+ assert.calledOnce(fakeUrlBar.search);
+ assert.calledOnce(fakeUrlBar.removeHiddenFocus);
+ assert.calledOnce(feed.store.dispatch);
+ assert.calledWith(feed.store.dispatch, {
+ meta: {
+ from: "ActivityStream:Main",
+ skipMain: true,
+ to: "ActivityStream:Content",
+ toTarget: {},
+ },
+ type: "HIDE_SEARCH",
+ });
+ });
+ it("should properly handle handoff with text data passed in", () => {
+ feed.handoffSearchToAwesomebar({
+ _target: { browser: { ownerGlobal: { gURLBar: fakeUrlBar } } },
+ data: { text: "foo" },
+ meta: { fromTarget: {} },
+ });
+ assert.calledOnce(fakeUrlBar.search);
+ assert.calledWith(fakeUrlBar.search, "@google foo", {
+ searchEngine: global.Services.search.defaultEngine,
+ searchModeEntry: "handoff",
+ });
+ assert.notCalled(fakeUrlBar.focus);
+ assert.notCalled(fakeUrlBar.setHiddenFocus);
+
+ // Now call blur listener.
+ listeners.blur();
+ assert.calledOnce(feed.store.dispatch);
+ assert.calledWith(feed.store.dispatch, {
+ meta: {
+ from: "ActivityStream:Main",
+ skipMain: true,
+ to: "ActivityStream:Content",
+ toTarget: {},
+ },
+ type: "SHOW_SEARCH",
+ });
+ });
+ it("should properly handle handoff with text data passed in, in private browsing mode", () => {
+ global.PrivateBrowsingUtils.isBrowserPrivate = () => true;
+ feed.handoffSearchToAwesomebar({
+ _target: { browser: { ownerGlobal: { gURLBar: fakeUrlBar } } },
+ data: { text: "foo" },
+ meta: { fromTarget: {} },
+ });
+ assert.calledOnce(fakeUrlBar.search);
+ assert.calledWith(fakeUrlBar.search, "@bing foo", {
+ searchEngine: global.Services.search.defaultPrivateEngine,
+ searchModeEntry: "handoff",
+ });
+ assert.notCalled(fakeUrlBar.focus);
+ assert.notCalled(fakeUrlBar.setHiddenFocus);
+
+ // Now call blur listener.
+ listeners.blur();
+ assert.calledOnce(feed.store.dispatch);
+ assert.calledWith(feed.store.dispatch, {
+ meta: {
+ from: "ActivityStream:Main",
+ skipMain: true,
+ to: "ActivityStream:Content",
+ toTarget: {},
+ },
+ type: "SHOW_SEARCH",
+ });
+ global.PrivateBrowsingUtils.isBrowserPrivate = () => false;
+ });
+ it("should SHOW_SEARCH on ESC keydown", () => {
+ feed.handoffSearchToAwesomebar({
+ _target: { browser: { ownerGlobal: { gURLBar: fakeUrlBar } } },
+ data: { text: "foo" },
+ meta: { fromTarget: {} },
+ });
+ assert.calledOnce(fakeUrlBar.search);
+ assert.calledWithExactly(fakeUrlBar.search, "@google foo", {
+ searchEngine: global.Services.search.defaultEngine,
+ searchModeEntry: "handoff",
+ });
+ assert.notCalled(fakeUrlBar.focus);
+
+ // Now call ESC keydown.
+ listeners.keydown({ key: "Escape" });
+ assert.calledOnce(feed.store.dispatch);
+ assert.calledWith(feed.store.dispatch, {
+ meta: {
+ from: "ActivityStream:Main",
+ skipMain: true,
+ to: "ActivityStream:Content",
+ toTarget: {},
+ },
+ type: "SHOW_SEARCH",
+ });
+ });
+ it("should properly handle no defined search alias", () => {
+ global.Services.search.defaultEngine.aliases = [];
+ feed.handoffSearchToAwesomebar({
+ _target: { browser: { ownerGlobal: { gURLBar: fakeUrlBar } } },
+ data: { text: "foo" },
+ meta: { fromTarget: {} },
+ });
+ assert.calledOnce(fakeUrlBar.search);
+ assert.calledWithExactly(fakeUrlBar.search, "foo", {
+ searchEngine: global.Services.search.defaultEngine,
+ searchModeEntry: "handoff",
+ });
+ });
+ });
+
+ describe("#observe", () => {
+ it("should dispatch a PLACES_LINK_BLOCKED action with the url of the blocked link", () => {
+ feed.observe(null, BLOCKED_EVENT, "foo123.com");
+ assert.equal(
+ feed.store.dispatch.firstCall.args[0].type,
+ at.PLACES_LINK_BLOCKED
+ );
+ assert.deepEqual(feed.store.dispatch.firstCall.args[0].data, {
+ url: "foo123.com",
+ });
+ });
+ it("should not call dispatch if the topic is something other than BLOCKED_EVENT", () => {
+ feed.observe(null, "someotherevent");
+ assert.notCalled(feed.store.dispatch);
+ });
+ });
+
+ describe("HistoryObserver", () => {
+ let dispatch;
+ let observer;
+ beforeEach(() => {
+ dispatch = sandbox.spy();
+ observer = new HistoryObserver(dispatch);
+ });
+ it("should have a QueryInterface property", () => {
+ assert.property(observer, "QueryInterface");
+ });
+ describe("#onDeleteURI", () => {
+ it("should dispatch a PLACES_LINK_DELETED action with the right url", async () => {
+ await observer.onDeleteURI({ spec: "foo.com" });
+
+ assert.calledWith(dispatch, {
+ type: at.PLACES_LINK_DELETED,
+ data: { url: "foo.com" },
+ });
+ });
+ });
+ describe("Other empty methods (to keep code coverage happy)", () => {
+ it("should have a various empty functions for xpconnect happiness", () => {
+ observer.onBeginUpdateBatch();
+ observer.onEndUpdateBatch();
+ observer.onDeleteVisits();
+ });
+ });
+ });
+
+ describe("Custom dispatch", () => {
+ it("should only dispatch 1 PLACES_LINKS_CHANGED action if many bookmark-added notifications happened at once", async () => {
+ // Yes, onItemAdded has at least 8 arguments. See function definition for docs.
+ const args = [
+ {
+ itemType: TYPE_BOOKMARK,
+ source: SOURCES.DEFAULT,
+ dateAdded: FAKE_BOOKMARK.dateAdded,
+ guid: FAKE_BOOKMARK.bookmarkGuid,
+ title: FAKE_BOOKMARK.bookmarkTitle,
+ url: "https://www.foo.com",
+ isTagging: false,
+ type: "bookmark-added",
+ },
+ ];
+ await feed.placesObserver.handlePlacesEvent(args);
+ await feed.placesObserver.handlePlacesEvent(args);
+ await feed.placesObserver.handlePlacesEvent(args);
+ await feed.placesObserver.handlePlacesEvent(args);
+ assert.calledOnce(
+ feed.store.dispatch.withArgs(
+ ac.OnlyToMain({ type: at.PLACES_LINKS_CHANGED })
+ )
+ );
+ });
+ it("should only dispatch 1 PLACES_LINKS_CHANGED action if many onItemRemoved notifications happened at once", async () => {
+ const args = [
+ {
+ id: null,
+ parentId: null,
+ index: null,
+ itemType: TYPE_BOOKMARK,
+ url: "foo.com",
+ guid: "123foo",
+ parentGuid: "",
+ source: SOURCES.DEFAULT,
+ type: "bookmark-removed",
+ },
+ ];
+ await feed.placesObserver.handlePlacesEvent(args);
+ await feed.placesObserver.handlePlacesEvent(args);
+ await feed.placesObserver.handlePlacesEvent(args);
+ await feed.placesObserver.handlePlacesEvent(args);
+
+ assert.calledOnce(
+ feed.store.dispatch.withArgs(
+ ac.OnlyToMain({ type: at.PLACES_LINKS_CHANGED })
+ )
+ );
+ });
+ it("should only dispatch 1 PLACES_LINKS_CHANGED action if any onDeleteURI notifications happened at once", async () => {
+ await feed.historyObserver.onDeleteURI({ spec: "foo.com" });
+ await feed.historyObserver.onDeleteURI({ spec: "foo1.com" });
+ await feed.historyObserver.onDeleteURI({ spec: "foo2.com" });
+
+ assert.calledOnce(
+ feed.store.dispatch.withArgs(
+ ac.OnlyToMain({ type: at.PLACES_LINKS_CHANGED })
+ )
+ );
+ });
+ });
+
+ describe("PlacesObserver", () => {
+ let dispatch;
+ let observer;
+ beforeEach(() => {
+ dispatch = sandbox.spy();
+ observer = new PlacesObserver(dispatch);
+ });
+
+ describe("#history-cleared", () => {
+ it("should dispatch a PLACES_HISTORY_CLEARED action", async () => {
+ const args = [{ type: "history-cleared" }];
+ await observer.handlePlacesEvent(args);
+ assert.calledWith(dispatch, { type: at.PLACES_HISTORY_CLEARED });
+ });
+ });
+
+ describe("#bookmark-added", () => {
+ it("should dispatch a PLACES_BOOKMARK_ADDED action with the bookmark data - http", async () => {
+ const args = [
+ {
+ itemType: TYPE_BOOKMARK,
+ source: SOURCES.DEFAULT,
+ dateAdded: FAKE_BOOKMARK.dateAdded,
+ guid: FAKE_BOOKMARK.bookmarkGuid,
+ title: FAKE_BOOKMARK.bookmarkTitle,
+ url: "http://www.foo.com",
+ isTagging: false,
+ type: "bookmark-added",
+ },
+ ];
+ await observer.handlePlacesEvent(args);
+
+ assert.calledWith(dispatch.secondCall, {
+ type: at.PLACES_BOOKMARK_ADDED,
+ data: {
+ bookmarkGuid: FAKE_BOOKMARK.bookmarkGuid,
+ bookmarkTitle: FAKE_BOOKMARK.bookmarkTitle,
+ dateAdded: FAKE_BOOKMARK.dateAdded * 1000,
+ url: "http://www.foo.com",
+ },
+ });
+ });
+ it("should dispatch a PLACES_BOOKMARK_ADDED action with the bookmark data - https", async () => {
+ const args = [
+ {
+ itemType: TYPE_BOOKMARK,
+ source: SOURCES.DEFAULT,
+ dateAdded: FAKE_BOOKMARK.dateAdded,
+ guid: FAKE_BOOKMARK.bookmarkGuid,
+ title: FAKE_BOOKMARK.bookmarkTitle,
+ url: "https://www.foo.com",
+ isTagging: false,
+ type: "bookmark-added",
+ },
+ ];
+ await observer.handlePlacesEvent(args);
+
+ assert.calledWith(dispatch.secondCall, {
+ type: at.PLACES_BOOKMARK_ADDED,
+ data: {
+ bookmarkGuid: FAKE_BOOKMARK.bookmarkGuid,
+ bookmarkTitle: FAKE_BOOKMARK.bookmarkTitle,
+ dateAdded: FAKE_BOOKMARK.dateAdded * 1000,
+ url: "https://www.foo.com",
+ },
+ });
+ });
+ it("should not dispatch a PLACES_BOOKMARK_ADDED action - not http/https", async () => {
+ const args = [
+ {
+ itemType: TYPE_BOOKMARK,
+ source: SOURCES.DEFAULT,
+ dateAdded: FAKE_BOOKMARK.dateAdded,
+ guid: FAKE_BOOKMARK.bookmarkGuid,
+ title: FAKE_BOOKMARK.bookmarkTitle,
+ url: "foo.com",
+ isTagging: false,
+ type: "bookmark-added",
+ },
+ ];
+ await observer.handlePlacesEvent(args);
+
+ assert.notCalled(dispatch);
+ });
+ it("should not dispatch a PLACES_BOOKMARK_ADDED action - has IMPORT source", async () => {
+ const args = [
+ {
+ itemType: TYPE_BOOKMARK,
+ source: SOURCES.IMPORT,
+ dateAdded: FAKE_BOOKMARK.dateAdded,
+ guid: FAKE_BOOKMARK.bookmarkGuid,
+ title: FAKE_BOOKMARK.bookmarkTitle,
+ url: "foo.com",
+ isTagging: false,
+ type: "bookmark-added",
+ },
+ ];
+ await observer.handlePlacesEvent(args);
+
+ assert.notCalled(dispatch);
+ });
+ it("should not dispatch a PLACES_BOOKMARK_ADDED action - has RESTORE source", async () => {
+ const args = [
+ {
+ itemType: TYPE_BOOKMARK,
+ source: SOURCES.RESTORE,
+ dateAdded: FAKE_BOOKMARK.dateAdded,
+ guid: FAKE_BOOKMARK.bookmarkGuid,
+ title: FAKE_BOOKMARK.bookmarkTitle,
+ url: "foo.com",
+ isTagging: false,
+ type: "bookmark-added",
+ },
+ ];
+ await observer.handlePlacesEvent(args);
+
+ assert.notCalled(dispatch);
+ });
+ it("should not dispatch a PLACES_BOOKMARK_ADDED action - has RESTORE_ON_STARTUP source", async () => {
+ const args = [
+ {
+ itemType: TYPE_BOOKMARK,
+ source: SOURCES.RESTORE_ON_STARTUP,
+ dateAdded: FAKE_BOOKMARK.dateAdded,
+ guid: FAKE_BOOKMARK.bookmarkGuid,
+ title: FAKE_BOOKMARK.bookmarkTitle,
+ url: "foo.com",
+ isTagging: false,
+ type: "bookmark-added",
+ },
+ ];
+ await observer.handlePlacesEvent(args);
+
+ assert.notCalled(dispatch);
+ });
+ it("should not dispatch a PLACES_BOOKMARK_ADDED action - has SYNC source", async () => {
+ const args = [
+ {
+ itemType: TYPE_BOOKMARK,
+ source: SOURCES.SYNC,
+ dateAdded: FAKE_BOOKMARK.dateAdded,
+ guid: FAKE_BOOKMARK.bookmarkGuid,
+ title: FAKE_BOOKMARK.bookmarkTitle,
+ url: "foo.com",
+ isTagging: false,
+ type: "bookmark-added",
+ },
+ ];
+ await observer.handlePlacesEvent(args);
+
+ assert.notCalled(dispatch);
+ });
+ it("should ignore events that are not of TYPE_BOOKMARK", async () => {
+ const args = [
+ {
+ itemType: "nottypebookmark",
+ source: SOURCES.DEFAULT,
+ dateAdded: FAKE_BOOKMARK.dateAdded,
+ guid: FAKE_BOOKMARK.bookmarkGuid,
+ title: FAKE_BOOKMARK.bookmarkTitle,
+ url: "https://www.foo.com",
+ isTagging: false,
+ type: "bookmark-added",
+ },
+ ];
+ await observer.handlePlacesEvent(args);
+
+ assert.notCalled(dispatch);
+ });
+ });
+ describe("#bookmark-removed", () => {
+ it("should ignore events that are not of TYPE_BOOKMARK", async () => {
+ const args = [
+ {
+ id: null,
+ parentId: null,
+ index: null,
+ itemType: "nottypebookmark",
+ url: null,
+ guid: "123foo",
+ parentGuid: "",
+ source: SOURCES.DEFAULT,
+ type: "bookmark-removed",
+ },
+ ];
+ await observer.handlePlacesEvent(args);
+ assert.notCalled(dispatch);
+ });
+ it("should not dispatch a PLACES_BOOKMARK_REMOVED action - has SYNC source", async () => {
+ const args = [
+ {
+ id: null,
+ parentId: null,
+ index: null,
+ itemType: TYPE_BOOKMARK,
+ url: "foo.com",
+ guid: "123foo",
+ parentGuid: "",
+ source: SOURCES.SYNC,
+ type: "bookmark-removed",
+ },
+ ];
+ await observer.handlePlacesEvent(args);
+
+ assert.notCalled(dispatch);
+ });
+ it("should not dispatch a PLACES_BOOKMARK_REMOVED action - has IMPORT source", async () => {
+ const args = [
+ {
+ id: null,
+ parentId: null,
+ index: null,
+ itemType: TYPE_BOOKMARK,
+ url: "foo.com",
+ guid: "123foo",
+ parentGuid: "",
+ source: SOURCES.IMPORT,
+ type: "bookmark-removed",
+ },
+ ];
+ await observer.handlePlacesEvent(args);
+
+ assert.notCalled(dispatch);
+ });
+ it("should not dispatch a PLACES_BOOKMARK_REMOVED action - has RESTORE source", async () => {
+ const args = [
+ {
+ id: null,
+ parentId: null,
+ index: null,
+ itemType: TYPE_BOOKMARK,
+ url: "foo.com",
+ guid: "123foo",
+ parentGuid: "",
+ source: SOURCES.RESTORE,
+ type: "bookmark-removed",
+ },
+ ];
+ await observer.handlePlacesEvent(args);
+
+ assert.notCalled(dispatch);
+ });
+ it("should not dispatch a PLACES_BOOKMARK_REMOVED action - has RESTORE_ON_STARTUP source", async () => {
+ const args = [
+ {
+ id: null,
+ parentId: null,
+ index: null,
+ itemType: TYPE_BOOKMARK,
+ url: "foo.com",
+ guid: "123foo",
+ parentGuid: "",
+ source: SOURCES.RESTORE_ON_STARTUP,
+ type: "bookmark-removed",
+ },
+ ];
+ await observer.handlePlacesEvent(args);
+
+ assert.notCalled(dispatch);
+ });
+ it("should dispatch a PLACES_BOOKMARK_REMOVED action with the right URL and bookmarkGuid", async () => {
+ const args = [
+ {
+ id: null,
+ parentId: null,
+ index: null,
+ itemType: TYPE_BOOKMARK,
+ url: "foo.com",
+ guid: "123foo",
+ parentGuid: "",
+ source: SOURCES.DEFAULT,
+ type: "bookmark-removed",
+ },
+ ];
+ await observer.handlePlacesEvent(args);
+ assert.calledWith(dispatch, {
+ type: at.PLACES_BOOKMARK_REMOVED,
+ data: { bookmarkGuid: "123foo", url: "foo.com" },
+ });
+ });
+ });
+ });
+
+ describe("BookmarksObserver", () => {
+ let dispatch;
+ let observer;
+ beforeEach(() => {
+ dispatch = sandbox.spy();
+ observer = new BookmarksObserver(dispatch);
+ });
+ it("should have a QueryInterface property", () => {
+ assert.property(observer, "QueryInterface");
+ });
+ describe("Other empty methods (to keep code coverage happy)", () => {
+ it("should have a various empty functions for xpconnect happiness", () => {
+ observer.onBeginUpdateBatch();
+ observer.onEndUpdateBatch();
+ observer.onItemMoved();
+ observer.onItemChanged();
+ });
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/lib/PrefsFeed.test.js b/browser/components/newtab/test/unit/lib/PrefsFeed.test.js
new file mode 100644
index 0000000000..471a09c38e
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/PrefsFeed.test.js
@@ -0,0 +1,248 @@
+import { actionCreators as ac, actionTypes as at } from "common/Actions.jsm";
+import { GlobalOverrider } from "test/unit/utils";
+import { PrefsFeed } from "lib/PrefsFeed.jsm";
+
+let overrider = new GlobalOverrider();
+
+describe("PrefsFeed", () => {
+ let feed;
+ let FAKE_PREFS;
+ let sandbox;
+ let ServicesStub;
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ FAKE_PREFS = new Map([
+ ["foo", 1],
+ ["bar", 2],
+ ["baz", { value: 1, skipBroadcast: true }],
+ ]);
+ feed = new PrefsFeed(FAKE_PREFS);
+ const storage = {
+ getAll: sandbox.stub().resolves(),
+ set: sandbox.stub().resolves(),
+ };
+ ServicesStub = {
+ prefs: {
+ clearUserPref: sinon.spy(),
+ getStringPref: sinon.spy(),
+ getIntPref: sinon.spy(),
+ getBoolPref: sinon.spy(),
+ },
+ obs: {
+ removeObserver: sinon.spy(),
+ addObserver: sinon.spy(),
+ },
+ };
+ feed.store = {
+ dispatch: sinon.spy(),
+ getState() {
+ return this.state;
+ },
+ dbStorage: { getDbTable: sandbox.stub().returns(storage) },
+ };
+ // Setup for tests that don't call `init`
+ feed._storage = storage;
+ feed._prefs = {
+ get: sinon.spy(item => FAKE_PREFS.get(item)),
+ set: sinon.spy((name, value) => FAKE_PREFS.set(name, value)),
+ observe: sinon.spy(),
+ observeBranch: sinon.spy(),
+ ignore: sinon.spy(),
+ ignoreBranch: sinon.spy(),
+ reset: sinon.stub(),
+ _branchStr: "branch.str.",
+ };
+ overrider.set({
+ PrivateBrowsingUtils: { enabled: true },
+ Services: ServicesStub,
+ });
+ });
+ afterEach(() => {
+ overrider.restore();
+ sandbox.restore();
+ });
+
+ it("should set a pref when a SET_PREF action is received", () => {
+ feed.onAction(ac.SetPref("foo", 2));
+ assert.calledWith(feed._prefs.set, "foo", 2);
+ });
+ it("should call clearUserPref with action CLEAR_PREF", () => {
+ feed.onAction({ type: at.CLEAR_PREF, data: { name: "pref.test" } });
+ assert.calledWith(ServicesStub.prefs.clearUserPref, "branch.str.pref.test");
+ });
+ it("should dispatch PREFS_INITIAL_VALUES on init with pref values and .isPrivateBrowsingEnabled", () => {
+ feed.onAction({ type: at.INIT });
+ assert.calledOnce(feed.store.dispatch);
+ assert.equal(
+ feed.store.dispatch.firstCall.args[0].type,
+ at.PREFS_INITIAL_VALUES
+ );
+ const [{ data }] = feed.store.dispatch.firstCall.args;
+ assert.equal(data.foo, 1);
+ assert.equal(data.bar, 2);
+ assert.isTrue(data.isPrivateBrowsingEnabled);
+ });
+ it("should dispatch PREFS_INITIAL_VALUES with a .featureConfig", () => {
+ sandbox.stub(global.ExperimentAPI, "getExperiment").returns({
+ active: true,
+ branch: {
+ slug: "foo",
+ feature: {
+ featureId: "newtab",
+ value: { prefsButtonIcon: "icon-foo" },
+ },
+ },
+ });
+ feed.onAction({ type: at.INIT });
+ assert.equal(
+ feed.store.dispatch.firstCall.args[0].type,
+ at.PREFS_INITIAL_VALUES
+ );
+ const [{ data }] = feed.store.dispatch.firstCall.args;
+ assert.deepEqual(data.featureConfig, { prefsButtonIcon: "icon-foo" });
+ });
+ it("should dispatch PREFS_INITIAL_VALUES with a default feature config if no experiment is returned", () => {
+ sandbox.stub(global.ExperimentAPI, "getExperiment").returns(null);
+ feed.onAction({ type: at.INIT });
+ assert.equal(
+ feed.store.dispatch.firstCall.args[0].type,
+ at.PREFS_INITIAL_VALUES
+ );
+ const [{ data }] = feed.store.dispatch.firstCall.args;
+ assert.deepEqual(data.featureConfig, { prefsButtonIcon: "icon-settings" });
+ });
+ it("should dispatch PREFS_INITIAL_VALUES with a default feature config ExperimentAPI throws", () => {
+ sandbox.stub(global.ExperimentAPI, "getExperiment").throws();
+ feed.onAction({ type: at.INIT });
+ assert.equal(
+ feed.store.dispatch.firstCall.args[0].type,
+ at.PREFS_INITIAL_VALUES
+ );
+ const [{ data }] = feed.store.dispatch.firstCall.args;
+ assert.deepEqual(data.featureConfig, { prefsButtonIcon: "icon-settings" });
+ });
+ it("should add one branch observer on init", () => {
+ feed.onAction({ type: at.INIT });
+ assert.calledOnce(feed._prefs.observeBranch);
+ assert.calledWith(feed._prefs.observeBranch, feed);
+ });
+ it("should initialise the storage on init", () => {
+ feed.init();
+
+ assert.calledOnce(feed.store.dbStorage.getDbTable);
+ assert.calledWithExactly(feed.store.dbStorage.getDbTable, "sectionPrefs");
+ });
+ it("should handle region on init", () => {
+ feed.init();
+ assert.equal(feed.geo, "US");
+ });
+ it("should add region observer on init", () => {
+ sandbox.stub(global.Region, "home").get(() => "");
+ feed.init();
+ assert.equal(feed.geo, "");
+ assert.calledWith(
+ ServicesStub.obs.addObserver,
+ feed,
+ global.Region.REGION_TOPIC
+ );
+ });
+ it("should remove the branch observer on uninit", () => {
+ feed.onAction({ type: at.UNINIT });
+ assert.calledOnce(feed._prefs.ignoreBranch);
+ assert.calledWith(feed._prefs.ignoreBranch, feed);
+ });
+ it("should call removeObserver", () => {
+ feed.geo = "";
+ feed.uninit();
+ assert.calledWith(
+ ServicesStub.obs.removeObserver,
+ feed,
+ global.Region.REGION_TOPIC
+ );
+ });
+ it("should send a PREF_CHANGED action when onPrefChanged is called", () => {
+ feed.onPrefChanged("foo", 2);
+ assert.calledWith(
+ feed.store.dispatch,
+ ac.BroadcastToContent({
+ type: at.PREF_CHANGED,
+ data: { name: "foo", value: 2 },
+ })
+ );
+ });
+ it("should send 2 PREF_CHANGED actions when onExperimentUpdated is called", () => {
+ const experimentData = {
+ active: true,
+ slug: "foo",
+ branch: {
+ slug: "boo",
+ feature: {
+ featureId: "newtab",
+ value: { prefsButtonIcon: "icon-boo" },
+ },
+ },
+ };
+ feed.onExperimentUpdated({}, experimentData);
+ assert.calledTwice(feed.store.dispatch);
+ assert.calledWith(
+ feed.store.dispatch,
+ ac.BroadcastToContent({
+ type: at.PREF_CHANGED,
+ data: { name: "experimentData", value: experimentData },
+ })
+ );
+ assert.calledWith(
+ feed.store.dispatch,
+ ac.BroadcastToContent({
+ type: at.PREF_CHANGED,
+ data: { name: "featureConfig", value: { prefsButtonIcon: "icon-boo" } },
+ })
+ );
+ });
+
+ it("should set storage pref on UPDATE_SECTION_PREFS", async () => {
+ await feed.onAction({
+ type: at.UPDATE_SECTION_PREFS,
+ data: { id: "topsites", value: { collapsed: false } },
+ });
+ assert.calledWith(feed._storage.set, "topsites", { collapsed: false });
+ });
+ it("should set storage pref with section prefix on UPDATE_SECTION_PREFS", async () => {
+ await feed.onAction({
+ type: at.UPDATE_SECTION_PREFS,
+ data: { id: "topstories", value: { collapsed: false } },
+ });
+ assert.calledWith(feed._storage.set, "feeds.section.topstories", {
+ collapsed: false,
+ });
+ });
+ it("should catch errors on UPDATE_SECTION_PREFS", async () => {
+ feed._storage.set.throws(new Error("foo"));
+ assert.doesNotThrow(async () => {
+ await feed.onAction({
+ type: at.UPDATE_SECTION_PREFS,
+ data: { id: "topstories", value: { collapsed: false } },
+ });
+ });
+ });
+ it("should send OnlyToMain pref update if config for pref has skipBroadcast: true", async () => {
+ feed.onPrefChanged("baz", { value: 2, skipBroadcast: true });
+ assert.calledWith(
+ feed.store.dispatch,
+ ac.OnlyToMain({
+ type: at.PREF_CHANGED,
+ data: { name: "baz", value: { value: 2, skipBroadcast: true } },
+ })
+ );
+ });
+ describe("#observe", () => {
+ it("should call dispatch from observe", () => {
+ feed.observe(
+ undefined,
+ global.Region.REGION_TOPIC,
+ global.Region.REGION_UPDATED
+ );
+ assert.calledOnce(feed.store.dispatch);
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/lib/RecommendationProviderSwitcher.test.js b/browser/components/newtab/test/unit/lib/RecommendationProviderSwitcher.test.js
new file mode 100644
index 0000000000..a39408fe87
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/RecommendationProviderSwitcher.test.js
@@ -0,0 +1,243 @@
+import { actionCreators as ac, actionTypes as at } from "common/Actions.jsm";
+import { RecommendationProviderSwitcher } from "lib/RecommendationProviderSwitcher.jsm";
+import { combineReducers, createStore } from "redux";
+import { reducers } from "common/Reducers.jsm";
+const PREF_PERSONALIZATION_VERSION = "discoverystream.personalization.version";
+const PREF_PERSONALIZATION_MODEL_KEYS =
+ "discoverystream.personalization.modelKeys";
+describe("RecommendationProviderSwitcher", () => {
+ let feed;
+ let sandbox;
+
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ feed = new RecommendationProviderSwitcher();
+ feed.store = createStore(combineReducers(reducers), {});
+ });
+
+ afterEach(() => {
+ sandbox.restore();
+ });
+
+ describe("#setAffinityProvider", () => {
+ it("should setup proper affnity provider with modelKeys", async () => {
+ feed.setAffinityProvider();
+
+ assert.equal(feed.affinityProvider.modelKeys, undefined);
+
+ feed.affinityProvider = null;
+ feed.affinityProviderV2 = {
+ modelKeys: "1234",
+ };
+
+ feed.setAffinityProvider();
+
+ assert.equal(feed.affinityProvider.modelKeys, "1234");
+ });
+ it("should use old provider", async () => {
+ feed.setAffinityProvider(
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined
+ );
+
+ assert.equal(feed.affinityProvider.modelKeys, undefined);
+
+ feed.affinityProviderV2 = {
+ modelKeys: "1234",
+ };
+
+ feed.setAffinityProvider(
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined
+ );
+
+ assert.equal(feed.affinityProvider.modelKeys, undefined);
+ });
+ });
+
+ describe("#init", () => {
+ it("should init affinityProvider then refreshContent", async () => {
+ feed.affinityProvider = {
+ init: sandbox.stub().resolves(),
+ };
+ await feed.init();
+ assert.calledOnce(feed.affinityProvider.init);
+ });
+ });
+
+ describe("#setVersion", () => {
+ beforeEach(() => {
+ sandbox.spy(feed.store, "dispatch");
+ });
+ it("should properly set affinity provider with version 1", async () => {
+ feed.store.getState = () => ({
+ Prefs: {
+ values: {
+ [PREF_PERSONALIZATION_MODEL_KEYS]: "1,2,3,4",
+ [PREF_PERSONALIZATION_VERSION]: 1,
+ },
+ },
+ });
+ feed.setVersion();
+ assert.calledWith(
+ feed.store.dispatch,
+ ac.BroadcastToContent({
+ type: at.DISCOVERY_STREAM_PERSONALIZATION_VERSION,
+ data: { version: 1 },
+ meta: { isStartup: false },
+ })
+ );
+ assert.equal(feed.affinityProviderV2, null);
+ });
+ it("should properly set affinity provider with version 2", async () => {
+ feed.store.getState = () => ({
+ Prefs: {
+ values: {
+ [PREF_PERSONALIZATION_MODEL_KEYS]: "1,2,3,4",
+ [PREF_PERSONALIZATION_VERSION]: 2,
+ },
+ },
+ });
+ feed.setVersion();
+ assert.calledWith(
+ feed.store.dispatch,
+ ac.BroadcastToContent({
+ type: at.DISCOVERY_STREAM_PERSONALIZATION_VERSION,
+ data: { version: 2 },
+ meta: { isStartup: false },
+ })
+ );
+ assert.deepEqual(feed.affinityProviderV2.modelKeys, ["1", "2", "3", "4"]);
+ });
+ });
+
+ describe("#getAffinities", () => {
+ it("should call affinityProvider.getAffinities", () => {
+ feed.affinityProvider = {
+ getAffinities: sandbox.stub().resolves(),
+ };
+ feed.getAffinities();
+ assert.calledOnce(feed.affinityProvider.getAffinities);
+ });
+ });
+
+ describe("#calculateItemRelevanceScore", () => {
+ it("should use personalized score with affinity provider", async () => {
+ const item = {};
+ feed.affinityProvider = {
+ calculateItemRelevanceScore: async () => 0.5,
+ };
+ await feed.calculateItemRelevanceScore(item);
+ assert.equal(item.score, 0.5);
+ });
+ });
+
+ describe("#teardown", () => {
+ it("should call affinityProvider.teardown ", () => {
+ feed.affinityProvider = {
+ teardown: sandbox.stub().resolves(),
+ };
+ feed.teardown();
+ assert.calledOnce(feed.affinityProvider.teardown);
+ });
+ });
+
+ describe("#resetState", () => {
+ it("should null affinityProviderV2 and affinityProvider", () => {
+ feed.affinityProviderV2 = {};
+ feed.affinityProvider = {};
+
+ feed.resetState();
+
+ assert.equal(feed.affinityProviderV2, null);
+ assert.equal(feed.affinityProvider, null);
+ });
+ });
+
+ describe("#onAction: INIT", () => {
+ it("should fire setVersion", async () => {
+ sandbox.spy(feed, "setVersion");
+ feed.onAction({
+ type: at.INIT,
+ });
+ assert.calledOnce(feed.setVersion);
+ });
+ });
+
+ describe("#onAction: DISCOVERY_STREAM_CONFIG_CHANGE", () => {
+ it("should call teardown, resetState, and setVersion", async () => {
+ sandbox.spy(feed, "teardown");
+ sandbox.spy(feed, "resetState");
+ sandbox.spy(feed, "setVersion");
+ feed.onAction({
+ type: at.DISCOVERY_STREAM_CONFIG_CHANGE,
+ });
+ assert.calledOnce(feed.teardown);
+ assert.calledOnce(feed.resetState);
+ assert.calledOnce(feed.setVersion);
+ });
+ });
+
+ describe("#onAction: PREF_CHANGED", () => {
+ beforeEach(() => {
+ sandbox.spy(feed.store, "dispatch");
+ });
+ it("should dispatch to DISCOVERY_STREAM_CONFIG_RESET from PREF_PERSONALIZATION_VERSION", async () => {
+ feed.onAction({
+ type: at.PREF_CHANGED,
+ data: {
+ name: PREF_PERSONALIZATION_VERSION,
+ },
+ });
+
+ assert.calledWith(
+ feed.store.dispatch,
+ ac.BroadcastToContent({
+ type: at.DISCOVERY_STREAM_CONFIG_RESET,
+ })
+ );
+ });
+ it("should dispatch to DISCOVERY_STREAM_CONFIG_RESET PREF_PERSONALIZATION_MODEL_KEYS", async () => {
+ feed.onAction({
+ type: at.PREF_CHANGED,
+ data: {
+ name: PREF_PERSONALIZATION_MODEL_KEYS,
+ },
+ });
+
+ assert.calledWith(
+ feed.store.dispatch,
+ ac.BroadcastToContent({
+ type: at.DISCOVERY_STREAM_CONFIG_RESET,
+ })
+ );
+ });
+ });
+
+ describe("#onAction: DISCOVERY_STREAM_PERSONALIZATION_VERSION_TOGGLE", () => {
+ it("should fire SET_PREF with version", async () => {
+ sandbox.spy(feed.store, "dispatch");
+ feed.store.getState = () => ({
+ Prefs: {
+ values: {
+ [PREF_PERSONALIZATION_VERSION]: 1,
+ },
+ },
+ });
+
+ await feed.onAction({
+ type: at.DISCOVERY_STREAM_PERSONALIZATION_VERSION_TOGGLE,
+ });
+ assert.calledWith(
+ feed.store.dispatch,
+ ac.SetPref(PREF_PERSONALIZATION_VERSION, 2)
+ );
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/lib/Screenshots.test.js b/browser/components/newtab/test/unit/lib/Screenshots.test.js
new file mode 100644
index 0000000000..272c7ff7d3
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/Screenshots.test.js
@@ -0,0 +1,209 @@
+"use strict";
+import { GlobalOverrider } from "test/unit/utils";
+import { Screenshots } from "lib/Screenshots.jsm";
+
+const URL = "foo.com";
+const FAKE_THUMBNAIL_PATH = "fake/path/thumb.jpg";
+const FAKE_THUMBNAIL_THUMB =
+ "moz-page-thumb://thumbnail?url=http%3A%2F%2Ffoo.com%2F";
+
+describe("Screenshots", () => {
+ let globals;
+ let sandbox;
+ let fakeServices;
+ let testFile;
+
+ beforeEach(() => {
+ globals = new GlobalOverrider();
+ sandbox = globals.sandbox;
+ fakeServices = {
+ wm: {
+ getEnumerator() {
+ return Array(10);
+ },
+ },
+ };
+ globals.set("BackgroundPageThumbs", {
+ captureIfMissing: sandbox.spy(() => Promise.resolve()),
+ });
+ globals.set("PageThumbs", {
+ _store: sandbox.stub(),
+ getThumbnailPath: sandbox.spy(() => FAKE_THUMBNAIL_PATH),
+ getThumbnailURL: sandbox.spy(() => FAKE_THUMBNAIL_THUMB),
+ });
+ globals.set("PrivateBrowsingUtils", {
+ isWindowPrivate: sandbox.spy(() => false),
+ });
+ testFile = { size: 1 };
+ globals.set("Services", fakeServices);
+ globals.set(
+ "fetch",
+ sandbox.spy(() =>
+ Promise.resolve({ blob: () => Promise.resolve(testFile) })
+ )
+ );
+ });
+ afterEach(() => {
+ globals.restore();
+ });
+
+ describe("#getScreenshotForURL", () => {
+ it("should call BackgroundPageThumbs.captureIfMissing with the correct url", async () => {
+ await Screenshots.getScreenshotForURL(URL);
+ assert.calledWith(global.BackgroundPageThumbs.captureIfMissing, URL);
+ });
+ it("should call PageThumbs.getThumbnailPath with the correct url", async () => {
+ globals.set("gPrivilegedAboutProcessEnabled", false);
+ await Screenshots.getScreenshotForURL(URL);
+ assert.calledWith(global.PageThumbs.getThumbnailPath, URL);
+ });
+ it("should call fetch", async () => {
+ await Screenshots.getScreenshotForURL(URL);
+ assert.calledOnce(global.fetch);
+ });
+ it("should have the necessary keys in the response object", async () => {
+ const screenshot = await Screenshots.getScreenshotForURL(URL);
+
+ assert.notEqual(screenshot.path, undefined);
+ assert.notEqual(screenshot.data, undefined);
+ });
+ it("should get null if something goes wrong", async () => {
+ globals.set("BackgroundPageThumbs", {
+ captureIfMissing: () =>
+ Promise.reject(new Error("Cannot capture thumbnail")),
+ });
+
+ const screenshot = await Screenshots.getScreenshotForURL(URL);
+
+ assert.calledOnce(global.PageThumbs._store);
+ assert.equal(screenshot, null);
+ });
+ it("should get direct thumbnail url for privileged process", async () => {
+ globals.set("gPrivilegedAboutProcessEnabled", true);
+ await Screenshots.getScreenshotForURL(URL);
+ assert.calledWith(global.PageThumbs.getThumbnailURL, URL);
+ });
+ it("should get null without storing if existing thumbnail is empty", async () => {
+ testFile.size = 0;
+
+ const screenshot = await Screenshots.getScreenshotForURL(URL);
+
+ assert.notCalled(global.PageThumbs._store);
+ assert.equal(screenshot, null);
+ });
+ });
+
+ describe("#maybeCacheScreenshot", () => {
+ let link;
+ beforeEach(() => {
+ link = {
+ __sharedCache: {
+ updateLink: (prop, val) => {
+ link[prop] = val;
+ },
+ },
+ };
+ });
+ it("should call getScreenshotForURL", () => {
+ sandbox.stub(Screenshots, "getScreenshotForURL");
+ sandbox.stub(Screenshots, "_shouldGetScreenshots").returns(true);
+ Screenshots.maybeCacheScreenshot(
+ link,
+ "mozilla.com",
+ "image",
+ sinon.stub()
+ );
+
+ assert.calledOnce(Screenshots.getScreenshotForURL);
+ assert.calledWithExactly(Screenshots.getScreenshotForURL, "mozilla.com");
+ });
+ it("should not call getScreenshotForURL twice if a fetch is in progress", () => {
+ sandbox
+ .stub(Screenshots, "getScreenshotForURL")
+ .returns(new Promise(() => {}));
+ sandbox.stub(Screenshots, "_shouldGetScreenshots").returns(true);
+ Screenshots.maybeCacheScreenshot(
+ link,
+ "mozilla.com",
+ "image",
+ sinon.stub()
+ );
+ Screenshots.maybeCacheScreenshot(
+ link,
+ "mozilla.org",
+ "image",
+ sinon.stub()
+ );
+
+ assert.calledOnce(Screenshots.getScreenshotForURL);
+ assert.calledWithExactly(Screenshots.getScreenshotForURL, "mozilla.com");
+ });
+ it("should not call getScreenshotsForURL if property !== undefined", async () => {
+ sandbox
+ .stub(Screenshots, "getScreenshotForURL")
+ .returns(Promise.resolve(null));
+ sandbox.stub(Screenshots, "_shouldGetScreenshots").returns(true);
+ await Screenshots.maybeCacheScreenshot(
+ link,
+ "mozilla.com",
+ "image",
+ sinon.stub()
+ );
+ await Screenshots.maybeCacheScreenshot(
+ link,
+ "mozilla.org",
+ "image",
+ sinon.stub()
+ );
+
+ assert.calledOnce(Screenshots.getScreenshotForURL);
+ assert.calledWithExactly(Screenshots.getScreenshotForURL, "mozilla.com");
+ });
+ it("should check if we are in private browsing before getting screenshots", async () => {
+ sandbox.stub(Screenshots, "_shouldGetScreenshots").returns(true);
+ await Screenshots.maybeCacheScreenshot(
+ link,
+ "mozilla.com",
+ "image",
+ sinon.stub()
+ );
+
+ assert.calledOnce(Screenshots._shouldGetScreenshots);
+ });
+ it("should not get a screenshot if we are in private browsing", async () => {
+ sandbox.stub(Screenshots, "getScreenshotForURL");
+ sandbox.stub(Screenshots, "_shouldGetScreenshots").returns(false);
+ await Screenshots.maybeCacheScreenshot(
+ link,
+ "mozilla.com",
+ "image",
+ sinon.stub()
+ );
+
+ assert.notCalled(Screenshots.getScreenshotForURL);
+ });
+ });
+
+ describe("#_shouldGetScreenshots", () => {
+ beforeEach(() => {
+ let more = 2;
+ sandbox
+ .stub(global.Services.wm, "getEnumerator")
+ .callsFake(() => Array(Math.max(more--, 0)));
+ });
+ it("should use private browsing utils to determine if a window is private", () => {
+ Screenshots._shouldGetScreenshots();
+ assert.calledOnce(global.PrivateBrowsingUtils.isWindowPrivate);
+ });
+ it("should return true if there exists at least 1 non-private window", () => {
+ assert.isTrue(Screenshots._shouldGetScreenshots());
+ });
+ it("should return false if there exists private windows", () => {
+ global.PrivateBrowsingUtils = {
+ isWindowPrivate: sandbox.spy(() => true),
+ };
+ assert.isFalse(Screenshots._shouldGetScreenshots());
+ assert.calledTwice(global.PrivateBrowsingUtils.isWindowPrivate);
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/lib/SectionsManager.test.js b/browser/components/newtab/test/unit/lib/SectionsManager.test.js
new file mode 100644
index 0000000000..7a4bed9340
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/SectionsManager.test.js
@@ -0,0 +1,884 @@
+"use strict";
+import {
+ actionCreators as ac,
+ actionTypes as at,
+ CONTENT_MESSAGE_TYPE,
+ MAIN_MESSAGE_TYPE,
+ PRELOAD_MESSAGE_TYPE,
+} from "common/Actions.jsm";
+import { EventEmitter, GlobalOverrider } from "test/unit/utils";
+import { SectionsFeed, SectionsManager } from "lib/SectionsManager.jsm";
+
+const FAKE_ID = "FAKE_ID";
+const FAKE_OPTIONS = { icon: "FAKE_ICON", title: "FAKE_TITLE" };
+const FAKE_ROWS = [
+ { url: "1.example.com", type: "bookmark" },
+ { url: "2.example.com", type: "pocket" },
+ { url: "3.example.com", type: "history" },
+];
+const FAKE_TRENDING_ROWS = [{ url: "bar", type: "trending" }];
+const FAKE_URL = "2.example.com";
+const FAKE_CARD_OPTIONS = { title: "Some fake title" };
+
+describe("SectionsManager", () => {
+ let globals;
+ let fakeServices;
+ let fakePlacesUtils;
+ let sandbox;
+ let storage;
+
+ beforeEach(async () => {
+ sandbox = sinon.createSandbox();
+ globals = new GlobalOverrider();
+ fakeServices = {
+ prefs: {
+ getBoolPref: sandbox.stub(),
+ addObserver: sandbox.stub(),
+ removeObserver: sandbox.stub(),
+ },
+ };
+ fakePlacesUtils = {
+ history: { update: sinon.stub(), insert: sinon.stub() },
+ };
+ globals.set({
+ Services: fakeServices,
+ PlacesUtils: fakePlacesUtils,
+ });
+ // Redecorate SectionsManager to remove any listeners that have been added
+ EventEmitter.decorate(SectionsManager);
+ storage = {
+ get: sandbox.stub().resolves(),
+ set: sandbox.stub().resolves(),
+ };
+ });
+
+ afterEach(() => {
+ globals.restore();
+ sandbox.restore();
+ });
+
+ describe("#init", () => {
+ it("should initialise the sections map with the built in sections", async () => {
+ SectionsManager.sections.clear();
+ SectionsManager.initialized = false;
+ await SectionsManager.init({}, storage);
+ assert.equal(SectionsManager.sections.size, 2);
+ assert.ok(SectionsManager.sections.has("topstories"));
+ assert.ok(SectionsManager.sections.has("highlights"));
+ });
+ it("should set .initialized to true", async () => {
+ SectionsManager.sections.clear();
+ SectionsManager.initialized = false;
+ await SectionsManager.init({}, storage);
+ assert.ok(SectionsManager.initialized);
+ });
+ it("should add observer for context menu prefs", async () => {
+ SectionsManager.CONTEXT_MENU_PREFS = { MENU_ITEM: "MENU_ITEM_PREF" };
+ await SectionsManager.init({}, storage);
+ assert.calledOnce(fakeServices.prefs.addObserver);
+ assert.calledWith(
+ fakeServices.prefs.addObserver,
+ "MENU_ITEM_PREF",
+ SectionsManager
+ );
+ });
+ it("should save the reference to `storage` passed in", async () => {
+ await SectionsManager.init({}, storage);
+
+ assert.equal(SectionsManager._storage, storage);
+ });
+ });
+ describe("#uninit", () => {
+ it("should remove observer for context menu prefs", () => {
+ SectionsManager.CONTEXT_MENU_PREFS = { MENU_ITEM: "MENU_ITEM_PREF" };
+ SectionsManager.initialized = true;
+ SectionsManager.uninit();
+ assert.calledOnce(fakeServices.prefs.removeObserver);
+ assert.calledWith(
+ fakeServices.prefs.removeObserver,
+ "MENU_ITEM_PREF",
+ SectionsManager
+ );
+ assert.isFalse(SectionsManager.initialized);
+ });
+ });
+ describe("#addBuiltInSection", () => {
+ it("should not report an error if options is undefined", async () => {
+ globals.sandbox.spy(global.Cu, "reportError");
+ SectionsManager._storage.get = sandbox.stub().returns(Promise.resolve());
+ await SectionsManager.addBuiltInSection(
+ "feeds.section.topstories",
+ undefined
+ );
+
+ assert.notCalled(Cu.reportError);
+ });
+ it("should report an error if options is malformed", async () => {
+ globals.sandbox.spy(global.Cu, "reportError");
+ SectionsManager._storage.get = sandbox.stub().returns(Promise.resolve());
+ await SectionsManager.addBuiltInSection(
+ "feeds.section.topstories",
+ "invalid"
+ );
+
+ assert.calledOnce(Cu.reportError);
+ });
+ it("should not throw if the indexedDB operation fails", async () => {
+ globals.sandbox.spy(global.Cu, "reportError");
+ storage.get = sandbox.stub().throws();
+ SectionsManager._storage = storage;
+
+ try {
+ await SectionsManager.addBuiltInSection("feeds.section.topstories");
+ } catch (e) {
+ assert.fail();
+ }
+
+ assert.calledOnce(storage.get);
+ assert.calledOnce(Cu.reportError);
+ });
+ });
+ describe("#updateSectionPrefs", () => {
+ it("should update the collapsed value of the section", async () => {
+ sandbox.stub(SectionsManager, "updateSection");
+ let topstories = SectionsManager.sections.get("topstories");
+ assert.isFalse(topstories.pref.collapsed);
+
+ await SectionsManager.updateSectionPrefs("topstories", {
+ collapsed: true,
+ });
+ topstories = SectionsManager.sections.get("topstories");
+
+ assert.isTrue(SectionsManager.updateSection.args[0][1].pref.collapsed);
+ });
+ it("should ignore invalid ids", async () => {
+ sandbox.stub(SectionsManager, "updateSection");
+ await SectionsManager.updateSectionPrefs("foo", { collapsed: true });
+
+ assert.notCalled(SectionsManager.updateSection);
+ });
+ });
+ describe("#addSection", () => {
+ it("should add the id to sections and emit an ADD_SECTION event", () => {
+ const spy = sinon.spy();
+ SectionsManager.on(SectionsManager.ADD_SECTION, spy);
+ SectionsManager.addSection(FAKE_ID, FAKE_OPTIONS);
+ assert.ok(SectionsManager.sections.has(FAKE_ID));
+ assert.calledOnce(spy);
+ assert.calledWith(
+ spy,
+ SectionsManager.ADD_SECTION,
+ FAKE_ID,
+ FAKE_OPTIONS
+ );
+ });
+ });
+ describe("#removeSection", () => {
+ it("should remove the id from sections and emit an REMOVE_SECTION event", () => {
+ // Ensure we start with the id in the set
+ assert.ok(SectionsManager.sections.has(FAKE_ID));
+ const spy = sinon.spy();
+ SectionsManager.on(SectionsManager.REMOVE_SECTION, spy);
+ SectionsManager.removeSection(FAKE_ID);
+ assert.notOk(SectionsManager.sections.has(FAKE_ID));
+ assert.calledOnce(spy);
+ assert.calledWith(spy, SectionsManager.REMOVE_SECTION, FAKE_ID);
+ });
+ });
+ describe("#enableSection", () => {
+ it("should call updateSection with {enabled: true}", () => {
+ sinon.spy(SectionsManager, "updateSection");
+ SectionsManager.addSection(FAKE_ID, FAKE_OPTIONS);
+ SectionsManager.enableSection(FAKE_ID);
+ assert.calledOnce(SectionsManager.updateSection);
+ assert.calledWith(
+ SectionsManager.updateSection,
+ FAKE_ID,
+ { enabled: true },
+ true
+ );
+ SectionsManager.updateSection.restore();
+ });
+ it("should emit an ENABLE_SECTION event", () => {
+ const spy = sinon.spy();
+ SectionsManager.on(SectionsManager.ENABLE_SECTION, spy);
+ SectionsManager.enableSection(FAKE_ID);
+ assert.calledOnce(spy);
+ assert.calledWith(spy, SectionsManager.ENABLE_SECTION, FAKE_ID);
+ });
+ });
+ describe("#disableSection", () => {
+ it("should call updateSection with {enabled: false, rows: [], initialized: false}", () => {
+ sinon.spy(SectionsManager, "updateSection");
+ SectionsManager.addSection(FAKE_ID, FAKE_OPTIONS);
+ SectionsManager.disableSection(FAKE_ID);
+ assert.calledOnce(SectionsManager.updateSection);
+ assert.calledWith(
+ SectionsManager.updateSection,
+ FAKE_ID,
+ { enabled: false, rows: [], initialized: false },
+ true
+ );
+ SectionsManager.updateSection.restore();
+ });
+ it("should emit a DISABLE_SECTION event", () => {
+ const spy = sinon.spy();
+ SectionsManager.on(SectionsManager.DISABLE_SECTION, spy);
+ SectionsManager.disableSection(FAKE_ID);
+ assert.calledOnce(spy);
+ assert.calledWith(spy, SectionsManager.DISABLE_SECTION, FAKE_ID);
+ });
+ });
+ describe("#updateSection", () => {
+ it("should emit an UPDATE_SECTION event with correct arguments", () => {
+ SectionsManager.addSection(FAKE_ID, FAKE_OPTIONS);
+ const spy = sinon.spy();
+ const dedupeConfigurations = [
+ { id: "topstories", dedupeFrom: ["highlights"] },
+ ];
+ SectionsManager.on(SectionsManager.UPDATE_SECTION, spy);
+ SectionsManager.updateSection(FAKE_ID, { rows: FAKE_ROWS }, true);
+ assert.calledOnce(spy);
+ assert.calledWith(
+ spy,
+ SectionsManager.UPDATE_SECTION,
+ FAKE_ID,
+ { rows: FAKE_ROWS, dedupeConfigurations },
+ true
+ );
+ });
+ it("should do nothing if the section doesn't exist", () => {
+ SectionsManager.removeSection(FAKE_ID);
+ const spy = sinon.spy();
+ SectionsManager.on(SectionsManager.UPDATE_SECTION, spy);
+ SectionsManager.updateSection(FAKE_ID, { rows: FAKE_ROWS }, true);
+ assert.notCalled(spy);
+ });
+ it("should update all sections", () => {
+ SectionsManager.sections.clear();
+ const updateSectionOrig = SectionsManager.updateSection;
+ SectionsManager.updateSection = sinon.spy();
+
+ SectionsManager.addSection("ID1", { title: "FAKE_TITLE_1" });
+ SectionsManager.addSection("ID2", { title: "FAKE_TITLE_2" });
+ SectionsManager.updateSections();
+
+ assert.calledTwice(SectionsManager.updateSection);
+ assert.calledWith(
+ SectionsManager.updateSection,
+ "ID1",
+ { title: "FAKE_TITLE_1" },
+ true
+ );
+ assert.calledWith(
+ SectionsManager.updateSection,
+ "ID2",
+ { title: "FAKE_TITLE_2" },
+ true
+ );
+ SectionsManager.updateSection = updateSectionOrig;
+ });
+ it("context menu pref change should update sections", async () => {
+ let observer;
+ const services = {
+ prefs: {
+ getBoolPref: sinon.spy(),
+ addObserver: (pref, o) => (observer = o),
+ removeObserver: sinon.spy(),
+ },
+ };
+ globals.set("Services", services);
+
+ SectionsManager.updateSections = sinon.spy();
+ SectionsManager.CONTEXT_MENU_PREFS = { MENU_ITEM: "MENU_ITEM_PREF" };
+ await SectionsManager.init({}, storage);
+ observer.observe("", "nsPref:changed", "MENU_ITEM_PREF");
+
+ assert.calledOnce(SectionsManager.updateSections);
+ });
+ });
+ describe("#_addCardTypeLinkMenuOptions", () => {
+ const addCardTypeLinkMenuOptionsOrig =
+ SectionsManager._addCardTypeLinkMenuOptions;
+ const contextMenuOptionsOrig =
+ SectionsManager.CONTEXT_MENU_OPTIONS_FOR_HIGHLIGHT_TYPES;
+ beforeEach(() => {
+ // Add a topstories section and a highlights section, with types for each card
+ SectionsManager.addSection("topstories", { FAKE_TRENDING_ROWS });
+ SectionsManager.addSection("highlights", { FAKE_ROWS });
+ });
+ it("should only call _addCardTypeLinkMenuOptions if the section update is for highlights", () => {
+ SectionsManager._addCardTypeLinkMenuOptions = sinon.spy();
+ SectionsManager.updateSection("topstories", { rows: FAKE_ROWS }, false);
+ assert.notCalled(SectionsManager._addCardTypeLinkMenuOptions);
+
+ SectionsManager.updateSection("highlights", { rows: FAKE_ROWS }, false);
+ assert.calledWith(SectionsManager._addCardTypeLinkMenuOptions, FAKE_ROWS);
+ });
+ it("should only call _addCardTypeLinkMenuOptions if the section update has rows", () => {
+ SectionsManager._addCardTypeLinkMenuOptions = sinon.spy();
+ SectionsManager.updateSection("highlights", {}, false);
+ assert.notCalled(SectionsManager._addCardTypeLinkMenuOptions);
+ });
+ it("should assign the correct context menu options based on the type of highlight", () => {
+ SectionsManager._addCardTypeLinkMenuOptions = addCardTypeLinkMenuOptionsOrig;
+
+ SectionsManager.updateSection("highlights", { rows: FAKE_ROWS }, false);
+ const highlights = SectionsManager.sections.get("highlights").FAKE_ROWS;
+
+ // FAKE_ROWS was added in the following order: bookmark, pocket, history
+ assert.deepEqual(
+ highlights[0].contextMenuOptions,
+ SectionsManager.CONTEXT_MENU_OPTIONS_FOR_HIGHLIGHT_TYPES.bookmark
+ );
+ assert.deepEqual(
+ highlights[1].contextMenuOptions,
+ SectionsManager.CONTEXT_MENU_OPTIONS_FOR_HIGHLIGHT_TYPES.pocket
+ );
+ assert.deepEqual(
+ highlights[2].contextMenuOptions,
+ SectionsManager.CONTEXT_MENU_OPTIONS_FOR_HIGHLIGHT_TYPES.history
+ );
+ });
+ it("should throw an error if you are assigning a context menu to a non-existant highlight type", () => {
+ globals.sandbox.spy(global.Cu, "reportError");
+ SectionsManager.updateSection(
+ "highlights",
+ { rows: [{ url: "foo", type: "badtype" }] },
+ false
+ );
+ const highlights = SectionsManager.sections.get("highlights").rows;
+ assert.calledOnce(Cu.reportError);
+ assert.equal(highlights[0].contextMenuOptions, undefined);
+ });
+ it("should filter out context menu options that are in CONTEXT_MENU_PREFS", () => {
+ const services = {
+ prefs: {
+ getBoolPref: o =>
+ SectionsManager.CONTEXT_MENU_PREFS[o] !== "RemoveMe",
+ addObserver() {},
+ removeObserver() {},
+ },
+ };
+ globals.set("Services", services);
+ SectionsManager.CONTEXT_MENU_PREFS = { RemoveMe: "RemoveMe" };
+ SectionsManager.CONTEXT_MENU_OPTIONS_FOR_HIGHLIGHT_TYPES = {
+ bookmark: ["KeepMe", "RemoveMe"],
+ pocket: ["KeepMe", "RemoveMe"],
+ history: ["KeepMe", "RemoveMe"],
+ };
+ SectionsManager.updateSection("highlights", { rows: FAKE_ROWS }, false);
+ const highlights = SectionsManager.sections.get("highlights").FAKE_ROWS;
+
+ // Only keep context menu options that were not supposed to be removed based on CONTEXT_MENU_PREFS
+ assert.deepEqual(highlights[0].contextMenuOptions, ["KeepMe"]);
+ assert.deepEqual(highlights[1].contextMenuOptions, ["KeepMe"]);
+ assert.deepEqual(highlights[2].contextMenuOptions, ["KeepMe"]);
+ SectionsManager.CONTEXT_MENU_OPTIONS_FOR_HIGHLIGHT_TYPES = contextMenuOptionsOrig;
+ globals.restore();
+ });
+ });
+ describe("#onceInitialized", () => {
+ it("should call the callback immediately if SectionsManager is initialised", () => {
+ SectionsManager.initialized = true;
+ const callback = sinon.spy();
+ SectionsManager.onceInitialized(callback);
+ assert.calledOnce(callback);
+ });
+ it("should bind the callback to .once(INIT) if SectionsManager is not initialised", () => {
+ SectionsManager.initialized = false;
+ sinon.spy(SectionsManager, "once");
+ const callback = () => {};
+ SectionsManager.onceInitialized(callback);
+ assert.calledOnce(SectionsManager.once);
+ assert.calledWith(SectionsManager.once, SectionsManager.INIT, callback);
+ });
+ });
+ describe("#updateSectionCard", () => {
+ it("should emit an UPDATE_SECTION_CARD event with correct arguments", () => {
+ SectionsManager.addSection(
+ FAKE_ID,
+ Object.assign({}, FAKE_OPTIONS, { rows: FAKE_ROWS })
+ );
+ const spy = sinon.spy();
+ SectionsManager.on(SectionsManager.UPDATE_SECTION_CARD, spy);
+ SectionsManager.updateSectionCard(
+ FAKE_ID,
+ FAKE_URL,
+ FAKE_CARD_OPTIONS,
+ true
+ );
+ assert.calledOnce(spy);
+ assert.calledWith(
+ spy,
+ SectionsManager.UPDATE_SECTION_CARD,
+ FAKE_ID,
+ FAKE_URL,
+ FAKE_CARD_OPTIONS,
+ true
+ );
+ });
+ it("should do nothing if the section doesn't exist", () => {
+ SectionsManager.removeSection(FAKE_ID);
+ const spy = sinon.spy();
+ SectionsManager.on(SectionsManager.UPDATE_SECTION_CARD, spy);
+ SectionsManager.updateSectionCard(
+ FAKE_ID,
+ FAKE_URL,
+ FAKE_CARD_OPTIONS,
+ true
+ );
+ assert.notCalled(spy);
+ });
+ });
+ describe("#removeSectionCard", () => {
+ it("should dispatch an SECTION_UPDATE action in which cards corresponding to the given url are removed", () => {
+ const rows = [{ url: "foo.com" }, { url: "bar.com" }];
+
+ SectionsManager.addSection(
+ FAKE_ID,
+ Object.assign({}, FAKE_OPTIONS, { rows })
+ );
+ const spy = sinon.spy();
+ SectionsManager.on(SectionsManager.UPDATE_SECTION, spy);
+ SectionsManager.removeSectionCard(FAKE_ID, "foo.com");
+
+ assert.calledOnce(spy);
+ assert.equal(spy.firstCall.args[1], FAKE_ID);
+ assert.deepEqual(spy.firstCall.args[2].rows, [{ url: "bar.com" }]);
+ });
+ it("should do nothing if the section doesn't exist", () => {
+ SectionsManager.removeSection(FAKE_ID);
+ const spy = sinon.spy();
+ SectionsManager.on(SectionsManager.UPDATE_SECTION, spy);
+ SectionsManager.removeSectionCard(FAKE_ID, "bar.com");
+ assert.notCalled(spy);
+ });
+ });
+ describe("#updateBookmarkMetadata", () => {
+ beforeEach(() => {
+ let rows = [
+ {
+ url: "bar",
+ title: "title",
+ description: "description",
+ image: "image",
+ type: "trending",
+ },
+ ];
+ SectionsManager.addSection("topstories", { rows });
+ // Simulate 2 sections.
+ rows = [
+ {
+ url: "foo",
+ title: "title",
+ description: "description",
+ image: "image",
+ type: "bookmark",
+ },
+ ];
+ SectionsManager.addSection("highlights", { rows });
+ });
+
+ it("shouldn't call PlacesUtils if URL is not in topstories", () => {
+ SectionsManager.updateBookmarkMetadata({ url: "foo" });
+
+ assert.notCalled(fakePlacesUtils.history.update);
+ });
+ it("should call PlacesUtils.history.update", () => {
+ SectionsManager.updateBookmarkMetadata({ url: "bar" });
+
+ assert.calledOnce(fakePlacesUtils.history.update);
+ assert.calledWithExactly(fakePlacesUtils.history.update, {
+ url: "bar",
+ title: "title",
+ description: "description",
+ previewImageURL: "image",
+ });
+ });
+ it("should call PlacesUtils.history.insert", () => {
+ SectionsManager.updateBookmarkMetadata({ url: "bar" });
+
+ assert.calledOnce(fakePlacesUtils.history.insert);
+ assert.calledWithExactly(fakePlacesUtils.history.insert, {
+ url: "bar",
+ title: "title",
+ visits: [{}],
+ });
+ });
+ });
+});
+
+describe("SectionsFeed", () => {
+ let feed;
+ let sandbox;
+ let storage;
+
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ SectionsManager.sections.clear();
+ SectionsManager.initialized = false;
+ storage = {
+ get: sandbox.stub().resolves(),
+ set: sandbox.stub().resolves(),
+ };
+ feed = new SectionsFeed();
+ feed.store = { dispatch: sinon.spy() };
+ feed.store = {
+ dispatch: sinon.spy(),
+ getState() {
+ return this.state;
+ },
+ state: {
+ Prefs: {
+ values: {
+ sectionOrder: "topsites,topstories,highlights",
+ "feeds.topsites": true,
+ },
+ },
+ Sections: [{ initialized: false }],
+ },
+ dbStorage: { getDbTable: sandbox.stub().returns(storage) },
+ };
+ });
+ afterEach(() => {
+ feed.uninit();
+ });
+ describe("#init", () => {
+ it("should create a SectionsFeed", () => {
+ assert.instanceOf(feed, SectionsFeed);
+ });
+ it("should bind appropriate listeners", () => {
+ sinon.spy(SectionsManager, "on");
+ feed.init();
+ assert.callCount(SectionsManager.on, 4);
+ for (const [event, listener] of [
+ [SectionsManager.ADD_SECTION, feed.onAddSection],
+ [SectionsManager.REMOVE_SECTION, feed.onRemoveSection],
+ [SectionsManager.UPDATE_SECTION, feed.onUpdateSection],
+ [SectionsManager.UPDATE_SECTION_CARD, feed.onUpdateSectionCard],
+ ]) {
+ assert.calledWith(SectionsManager.on, event, listener);
+ }
+ });
+ it("should call onAddSection for any already added sections in SectionsManager", async () => {
+ await SectionsManager.init({}, storage);
+ assert.ok(SectionsManager.sections.has("topstories"));
+ assert.ok(SectionsManager.sections.has("highlights"));
+ const topstories = SectionsManager.sections.get("topstories");
+ const highlights = SectionsManager.sections.get("highlights");
+ sinon.spy(feed, "onAddSection");
+ feed.init();
+ assert.calledTwice(feed.onAddSection);
+ assert.calledWith(
+ feed.onAddSection,
+ SectionsManager.ADD_SECTION,
+ "topstories",
+ topstories
+ );
+ assert.calledWith(
+ feed.onAddSection,
+ SectionsManager.ADD_SECTION,
+ "highlights",
+ highlights
+ );
+ });
+ });
+ describe("#uninit", () => {
+ it("should unbind all listeners", () => {
+ sinon.spy(SectionsManager, "off");
+ feed.init();
+ feed.uninit();
+ assert.callCount(SectionsManager.off, 4);
+ for (const [event, listener] of [
+ [SectionsManager.ADD_SECTION, feed.onAddSection],
+ [SectionsManager.REMOVE_SECTION, feed.onRemoveSection],
+ [SectionsManager.UPDATE_SECTION, feed.onUpdateSection],
+ [SectionsManager.UPDATE_SECTION_CARD, feed.onUpdateSectionCard],
+ ]) {
+ assert.calledWith(SectionsManager.off, event, listener);
+ }
+ });
+ it("should emit an UNINIT event and set SectionsManager.initialized to false", () => {
+ const spy = sinon.spy();
+ SectionsManager.on(SectionsManager.UNINIT, spy);
+ feed.init();
+ feed.uninit();
+ assert.calledOnce(spy);
+ assert.notOk(SectionsManager.initialized);
+ });
+ });
+ describe("#onAddSection", () => {
+ it("should broadcast a SECTION_REGISTER action with the correct data", () => {
+ feed.onAddSection(null, FAKE_ID, FAKE_OPTIONS);
+ const [action] = feed.store.dispatch.firstCall.args;
+ assert.equal(action.type, "SECTION_REGISTER");
+ assert.deepEqual(
+ action.data,
+ Object.assign({ id: FAKE_ID }, FAKE_OPTIONS)
+ );
+ assert.equal(action.meta.from, MAIN_MESSAGE_TYPE);
+ assert.equal(action.meta.to, CONTENT_MESSAGE_TYPE);
+ });
+ it("should prepend id to sectionOrder pref if not already included", () => {
+ feed.store.state.Sections = [
+ { id: "topstories", enabled: true },
+ { id: "highlights", enabled: true },
+ ];
+ feed.onAddSection(null, FAKE_ID, FAKE_OPTIONS);
+ assert.calledWith(feed.store.dispatch, {
+ data: {
+ name: "sectionOrder",
+ value: `${FAKE_ID},topsites,topstories,highlights`,
+ },
+ meta: { from: "ActivityStream:Content", to: "ActivityStream:Main" },
+ type: "SET_PREF",
+ });
+ });
+ });
+ describe("#onRemoveSection", () => {
+ it("should broadcast a SECTION_DEREGISTER action with the correct data", () => {
+ feed.onRemoveSection(null, FAKE_ID);
+ const [action] = feed.store.dispatch.firstCall.args;
+ assert.equal(action.type, "SECTION_DEREGISTER");
+ assert.deepEqual(action.data, FAKE_ID);
+ // Should be broadcast
+ assert.equal(action.meta.from, MAIN_MESSAGE_TYPE);
+ assert.equal(action.meta.to, CONTENT_MESSAGE_TYPE);
+ });
+ });
+ describe("#onUpdateSection", () => {
+ it("should do nothing if no options are provided", () => {
+ feed.onUpdateSection(null, FAKE_ID, null);
+ assert.notCalled(feed.store.dispatch);
+ });
+ it("should dispatch a SECTION_UPDATE action with the correct data", () => {
+ feed.onUpdateSection(null, FAKE_ID, { rows: FAKE_ROWS });
+ const [action] = feed.store.dispatch.firstCall.args;
+ assert.equal(action.type, "SECTION_UPDATE");
+ assert.deepEqual(action.data, { id: FAKE_ID, rows: FAKE_ROWS });
+ // Should be not broadcast by default, but should update the preloaded tab, so check meta
+ assert.equal(action.meta.from, MAIN_MESSAGE_TYPE);
+ assert.equal(action.meta.to, PRELOAD_MESSAGE_TYPE);
+ });
+ it("should broadcast the action only if shouldBroadcast is true", () => {
+ feed.onUpdateSection(null, FAKE_ID, { rows: FAKE_ROWS }, true);
+ const [action] = feed.store.dispatch.firstCall.args;
+ // Should be broadcast
+ assert.equal(action.meta.from, MAIN_MESSAGE_TYPE);
+ assert.equal(action.meta.to, CONTENT_MESSAGE_TYPE);
+ });
+ });
+ describe("#onUpdateSectionCard", () => {
+ it("should do nothing if no options are provided", () => {
+ feed.onUpdateSectionCard(null, FAKE_ID, FAKE_URL, null);
+ assert.notCalled(feed.store.dispatch);
+ });
+ it("should dispatch a SECTION_UPDATE_CARD action with the correct data", () => {
+ feed.onUpdateSectionCard(null, FAKE_ID, FAKE_URL, FAKE_CARD_OPTIONS);
+ const [action] = feed.store.dispatch.firstCall.args;
+ assert.equal(action.type, "SECTION_UPDATE_CARD");
+ assert.deepEqual(action.data, {
+ id: FAKE_ID,
+ url: FAKE_URL,
+ options: FAKE_CARD_OPTIONS,
+ });
+ // Should be not broadcast by default, but should update the preloaded tab, so check meta
+ assert.equal(action.meta.from, MAIN_MESSAGE_TYPE);
+ assert.equal(action.meta.to, PRELOAD_MESSAGE_TYPE);
+ });
+ it("should broadcast the action only if shouldBroadcast is true", () => {
+ feed.onUpdateSectionCard(
+ null,
+ FAKE_ID,
+ FAKE_URL,
+ FAKE_CARD_OPTIONS,
+ true
+ );
+ const [action] = feed.store.dispatch.firstCall.args;
+ // Should be broadcast
+ assert.equal(action.meta.from, MAIN_MESSAGE_TYPE);
+ assert.equal(action.meta.to, CONTENT_MESSAGE_TYPE);
+ });
+ });
+ describe("#onAction", () => {
+ it("should bind this.init to SectionsManager.INIT on INIT", () => {
+ sinon.spy(SectionsManager, "once");
+ feed.onAction({ type: "INIT" });
+ assert.calledOnce(SectionsManager.once);
+ assert.calledWith(SectionsManager.once, SectionsManager.INIT, feed.init);
+ });
+ it("should call SectionsManager.init on action PREFS_INITIAL_VALUES", () => {
+ sinon.spy(SectionsManager, "init");
+ feed.onAction({ type: "PREFS_INITIAL_VALUES", data: { foo: "bar" } });
+ assert.calledOnce(SectionsManager.init);
+ assert.calledWith(SectionsManager.init, { foo: "bar" });
+ assert.calledOnce(feed.store.dbStorage.getDbTable);
+ assert.calledWithExactly(feed.store.dbStorage.getDbTable, "sectionPrefs");
+ });
+ it("should call SectionsManager.addBuiltInSection on suitable PREF_CHANGED events", () => {
+ sinon.spy(SectionsManager, "addBuiltInSection");
+ feed.onAction({
+ type: "PREF_CHANGED",
+ data: { name: "feeds.section.topstories.options", value: "foo" },
+ });
+ assert.calledOnce(SectionsManager.addBuiltInSection);
+ assert.calledWith(
+ SectionsManager.addBuiltInSection,
+ "feeds.section.topstories",
+ "foo"
+ );
+ });
+ it("should fire SECTION_OPTIONS_UPDATED on suitable PREF_CHANGED events", async () => {
+ await feed.onAction({
+ type: "PREF_CHANGED",
+ data: { name: "feeds.section.topstories.options", value: "foo" },
+ });
+ assert.calledOnce(feed.store.dispatch);
+ const [action] = feed.store.dispatch.firstCall.args;
+ assert.equal(action.type, "SECTION_OPTIONS_CHANGED");
+ assert.equal(action.data, "topstories");
+ });
+ it("should call SectionsManager.disableSection on SECTION_DISABLE", () => {
+ sinon.spy(SectionsManager, "disableSection");
+ feed.onAction({ type: "SECTION_DISABLE", data: 1234 });
+ assert.calledOnce(SectionsManager.disableSection);
+ assert.calledWith(SectionsManager.disableSection, 1234);
+ SectionsManager.disableSection.restore();
+ });
+ it("should call SectionsManager.enableSection on SECTION_ENABLE", () => {
+ sinon.spy(SectionsManager, "enableSection");
+ feed.onAction({ type: "SECTION_ENABLE", data: 1234 });
+ assert.calledOnce(SectionsManager.enableSection);
+ assert.calledWith(SectionsManager.enableSection, 1234);
+ SectionsManager.enableSection.restore();
+ });
+ it("should call the feed's uninit on UNINIT", () => {
+ sinon.stub(feed, "uninit");
+
+ feed.onAction({ type: "UNINIT" });
+
+ assert.calledOnce(feed.uninit);
+ });
+ it("should emit a ACTION_DISPATCHED event and forward any action in ACTIONS_TO_PROXY if there are any sections", () => {
+ const spy = sinon.spy();
+ const allowedActions = SectionsManager.ACTIONS_TO_PROXY;
+ const disallowedActions = ["PREF_CHANGED", "OPEN_PRIVATE_WINDOW"];
+ feed.init();
+ SectionsManager.on(SectionsManager.ACTION_DISPATCHED, spy);
+ // Make sure we start with no sections - no event should be emitted
+ SectionsManager.sections.clear();
+ feed.onAction({ type: allowedActions[0] });
+ assert.notCalled(spy);
+ // Then add a section and check correct behaviour
+ SectionsManager.addSection(FAKE_ID, FAKE_OPTIONS);
+ for (const action of allowedActions.concat(disallowedActions)) {
+ feed.onAction({ type: action });
+ }
+ for (const action of allowedActions) {
+ assert.calledWith(spy, "ACTION_DISPATCHED", action);
+ }
+ for (const action of disallowedActions) {
+ assert.neverCalledWith(spy, "ACTION_DISPATCHED", action);
+ }
+ });
+ it("should call updateBookmarkMetadata on PLACES_BOOKMARK_ADDED", () => {
+ const stub = sinon.stub(SectionsManager, "updateBookmarkMetadata");
+
+ feed.onAction({ type: "PLACES_BOOKMARK_ADDED", data: {} });
+
+ assert.calledOnce(stub);
+ });
+ it("should call updateSectionPrefs on UPDATE_SECTION_PREFS", () => {
+ const stub = sinon.stub(SectionsManager, "updateSectionPrefs");
+
+ feed.onAction({ type: "UPDATE_SECTION_PREFS", data: {} });
+
+ assert.calledOnce(stub);
+ });
+ it("should call SectionManager.removeSectionCard on WEBEXT_DISMISS", () => {
+ const stub = sinon.stub(SectionsManager, "removeSectionCard");
+
+ feed.onAction(
+ ac.WebExtEvent(at.WEBEXT_DISMISS, { source: "Foo", url: "bar.com" })
+ );
+
+ assert.calledOnce(stub);
+ assert.calledWith(stub, "Foo", "bar.com");
+ });
+ it("should call the feed's moveSection on SECTION_MOVE", () => {
+ sinon.stub(feed, "moveSection");
+ const id = "topsites";
+ const direction = +1;
+ feed.onAction({ type: "SECTION_MOVE", data: { id, direction } });
+
+ assert.calledOnce(feed.moveSection);
+ assert.calledWith(feed.moveSection, id, direction);
+ });
+ });
+ describe("#moveSection", () => {
+ it("should Move Down correctly", () => {
+ feed.store.state.Sections = [
+ { id: "topstories", enabled: true },
+ { id: "highlights", enabled: true },
+ ];
+ feed.moveSection("topsites", +1);
+ assert.calledOnce(feed.store.dispatch);
+ assert.calledWith(feed.store.dispatch, {
+ data: { name: "sectionOrder", value: "topstories,topsites,highlights" },
+ meta: { from: "ActivityStream:Content", to: "ActivityStream:Main" },
+ type: "SET_PREF",
+ });
+ feed.store.dispatch.resetHistory();
+ feed.moveSection("topstories", +1);
+ assert.calledOnce(feed.store.dispatch);
+ assert.calledWith(feed.store.dispatch, {
+ data: { name: "sectionOrder", value: "topsites,highlights,topstories" },
+ meta: { from: "ActivityStream:Content", to: "ActivityStream:Main" },
+ type: "SET_PREF",
+ });
+ });
+ it("should Move Up correctly", () => {
+ feed.store.state.Sections = [
+ { id: "topstories", enabled: true },
+ { id: "highlights", enabled: true },
+ ];
+ feed.moveSection("topstories", -1);
+ assert.calledOnce(feed.store.dispatch);
+ assert.calledWith(feed.store.dispatch, {
+ data: { name: "sectionOrder", value: "topstories,topsites,highlights" },
+ meta: { from: "ActivityStream:Content", to: "ActivityStream:Main" },
+ type: "SET_PREF",
+ });
+ feed.store.dispatch.resetHistory();
+ feed.moveSection("highlights", -1);
+ assert.calledOnce(feed.store.dispatch);
+ assert.calledWith(feed.store.dispatch, {
+ data: { name: "sectionOrder", value: "topsites,highlights,topstories" },
+ meta: { from: "ActivityStream:Content", to: "ActivityStream:Main" },
+ type: "SET_PREF",
+ });
+ });
+ it("should skip over sections that aren't enabled", () => {
+ feed.store.state.Sections = [
+ { id: "topstories", enabled: false },
+ { id: "highlights", enabled: true },
+ ];
+ feed.moveSection("highlights", -1);
+ assert.calledOnce(feed.store.dispatch);
+ assert.calledWith(feed.store.dispatch, {
+ data: { name: "sectionOrder", value: "highlights,topsites,topstories" },
+ meta: { from: "ActivityStream:Content", to: "ActivityStream:Main" },
+ type: "SET_PREF",
+ });
+ feed.store.dispatch.resetHistory();
+ feed.moveSection("topsites", +1);
+ assert.calledOnce(feed.store.dispatch);
+ assert.calledWith(feed.store.dispatch, {
+ data: { name: "sectionOrder", value: "topstories,highlights,topsites" },
+ meta: { from: "ActivityStream:Content", to: "ActivityStream:Main" },
+ type: "SET_PREF",
+ });
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/lib/ShortUrl.test.js b/browser/components/newtab/test/unit/lib/ShortUrl.test.js
new file mode 100644
index 0000000000..e0f6688db8
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/ShortUrl.test.js
@@ -0,0 +1,104 @@
+import { GlobalOverrider } from "test/unit/utils";
+import { shortURL } from "lib/ShortURL.jsm";
+
+const puny = "xn--kpry57d";
+const idn = "台灣";
+
+describe("shortURL", () => {
+ let globals;
+ let IDNStub;
+ let getPublicSuffixFromHostStub;
+
+ beforeEach(() => {
+ IDNStub = sinon.stub().callsFake(host => host.replace(puny, idn));
+ getPublicSuffixFromHostStub = sinon.stub().returns("com");
+
+ globals = new GlobalOverrider();
+ globals.set("IDNService", { convertToDisplayIDN: IDNStub });
+ globals.set("Services", {
+ eTLD: { getPublicSuffixFromHost: getPublicSuffixFromHostStub },
+ });
+ });
+
+ afterEach(() => {
+ globals.restore();
+ });
+
+ it("should return a blank string if url is falsey", () => {
+ assert.equal(shortURL({ url: false }), "");
+ assert.equal(shortURL({ url: "" }), "");
+ assert.equal(shortURL({}), "");
+ });
+
+ it("should return the 'url' if not a valid url", () => {
+ const checkInvalid = url => assert.equal(shortURL({ url }), url);
+ checkInvalid(true);
+ checkInvalid("something");
+ checkInvalid("http:");
+ checkInvalid("http::double");
+ checkInvalid("http://badport:65536/");
+ });
+
+ it("should remove the eTLD", () => {
+ assert.equal(shortURL({ url: "http://com.blah.com" }), "com.blah");
+ });
+
+ it("should convert host to idn when calling shortURL", () => {
+ assert.equal(shortURL({ url: `http://${puny}.blah.com` }), `${idn}.blah`);
+ });
+
+ it("should get the hostname from .url", () => {
+ assert.equal(shortURL({ url: "http://bar.com" }), "bar");
+ });
+
+ it("should not strip out www if not first subdomain", () => {
+ assert.equal(shortURL({ url: "http://foo.www.com" }), "foo.www");
+ });
+
+ it("should convert to lowercase", () => {
+ assert.equal(shortURL({ url: "HTTP://FOO.COM" }), "foo");
+ });
+
+ it("should not include the port", () => {
+ assert.equal(shortURL({ url: "http://foo.com:8888" }), "foo");
+ });
+
+ it("should return hostname for localhost", () => {
+ getPublicSuffixFromHostStub.throws("insufficient domain levels");
+
+ assert.equal(shortURL({ url: "http://localhost:8000/" }), "localhost");
+ });
+
+ it("should return hostname for ip address", () => {
+ getPublicSuffixFromHostStub.throws("host is ip address");
+
+ assert.equal(shortURL({ url: "http://127.0.0.1/foo" }), "127.0.0.1");
+ });
+
+ it("should return etld for www.gov.uk (www-only non-etld)", () => {
+ getPublicSuffixFromHostStub.returns("gov.uk");
+
+ assert.equal(
+ shortURL({ url: "https://www.gov.uk/countersigning" }),
+ "gov.uk"
+ );
+ });
+
+ it("should return idn etld for www-only non-etld", () => {
+ getPublicSuffixFromHostStub.returns(puny);
+
+ assert.equal(shortURL({ url: `https://www.${puny}/foo` }), idn);
+ });
+
+ it("should return not the protocol for file:", () => {
+ assert.equal(shortURL({ url: "file:///foo/bar.txt" }), "/foo/bar.txt");
+ });
+
+ it("should return not the protocol for about:", () => {
+ assert.equal(shortURL({ url: "about:newtab" }), "newtab");
+ });
+
+ it("should fall back to full url as a last resort", () => {
+ assert.equal(shortURL({ url: "about:" }), "about:");
+ });
+});
diff --git a/browser/components/newtab/test/unit/lib/SiteClassifier.test.js b/browser/components/newtab/test/unit/lib/SiteClassifier.test.js
new file mode 100644
index 0000000000..a8b09ce1f0
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/SiteClassifier.test.js
@@ -0,0 +1,252 @@
+import { classifySite } from "lib/SiteClassifier.jsm";
+
+const FAKE_CLASSIFIER_DATA = [
+ {
+ type: "hostname-and-params-match",
+ criteria: [
+ {
+ hostname: "hostnameandparams.com",
+ params: [
+ {
+ key: "param1",
+ value: "val1",
+ },
+ ],
+ },
+ ],
+ weight: 300,
+ },
+ {
+ type: "url-match",
+ criteria: [{ url: "https://fullurl.com/must/match" }],
+ weight: 400,
+ },
+ {
+ type: "params-match",
+ criteria: [
+ {
+ params: [
+ {
+ key: "param1",
+ value: "val1",
+ },
+ {
+ key: "param2",
+ value: "val2",
+ },
+ ],
+ },
+ ],
+ weight: 200,
+ },
+ {
+ type: "params-prefix-match",
+ criteria: [
+ {
+ params: [
+ {
+ key: "client",
+ prefix: "fir",
+ },
+ ],
+ },
+ ],
+ weight: 200,
+ },
+ {
+ type: "has-params",
+ criteria: [
+ {
+ params: [{ key: "has-param1" }, { key: "has-param2" }],
+ },
+ ],
+ weight: 100,
+ },
+ {
+ type: "search-engine",
+ criteria: [
+ { sld: "google" },
+ { hostname: "bing.com" },
+ { hostname: "duckduckgo.com" },
+ ],
+ weight: 1,
+ },
+ {
+ type: "news-portal",
+ criteria: [
+ { hostname: "yahoo.com" },
+ { hostname: "aol.com" },
+ { hostname: "msn.com" },
+ ],
+ weight: 1,
+ },
+ {
+ type: "social-media",
+ criteria: [{ hostname: "facebook.com" }, { hostname: "twitter.com" }],
+ weight: 1,
+ },
+ {
+ type: "ecommerce",
+ criteria: [{ sld: "amazon" }, { hostname: "ebay.com" }],
+ weight: 1,
+ },
+];
+
+describe("SiteClassifier", () => {
+ function RemoteSettings() {
+ return {
+ get() {
+ return Promise.resolve(FAKE_CLASSIFIER_DATA);
+ },
+ };
+ }
+
+ it("should return the right category", async () => {
+ assert.equal(
+ "hostname-and-params-match",
+ await classifySite(
+ "https://hostnameandparams.com?param1=val1",
+ RemoteSettings
+ )
+ );
+ assert.equal(
+ "other",
+ await classifySite(
+ "https://hostnameandparams.com?param1=val",
+ RemoteSettings
+ )
+ );
+ assert.equal(
+ "other",
+ await classifySite(
+ "https://hostnameandparams.com?param=val1",
+ RemoteSettings
+ )
+ );
+ assert.equal(
+ "other",
+ await classifySite("https://hostnameandparams.com", RemoteSettings)
+ );
+ assert.equal(
+ "other",
+ await classifySite("https://params.com?param1=val1", RemoteSettings)
+ );
+
+ assert.equal(
+ "url-match",
+ await classifySite("https://fullurl.com/must/match", RemoteSettings)
+ );
+ assert.equal(
+ "other",
+ await classifySite("http://fullurl.com/must/match", RemoteSettings)
+ );
+
+ assert.equal(
+ "params-match",
+ await classifySite(
+ "https://example.com?param1=val1&param2=val2",
+ RemoteSettings
+ )
+ );
+ assert.equal(
+ "params-match",
+ await classifySite(
+ "https://example.com?param1=val1&param2=val2&other=other",
+ RemoteSettings
+ )
+ );
+ assert.equal(
+ "other",
+ await classifySite(
+ "https://example.com?param1=val2&param2=val1",
+ RemoteSettings
+ )
+ );
+ assert.equal(
+ "other",
+ await classifySite("https://example.com?param1&param2", RemoteSettings)
+ );
+
+ assert.equal(
+ "params-prefix-match",
+ await classifySite("https://search.com?client=firefox", RemoteSettings)
+ );
+ assert.equal(
+ "params-prefix-match",
+ await classifySite("https://search.com?client=fir", RemoteSettings)
+ );
+ assert.equal(
+ "other",
+ await classifySite(
+ "https://search.com?client=mozillafirefox",
+ RemoteSettings
+ )
+ );
+
+ assert.equal(
+ "has-params",
+ await classifySite(
+ "https://example.com?has-param1=val1&has-param2=val2",
+ RemoteSettings
+ )
+ );
+ assert.equal(
+ "has-params",
+ await classifySite(
+ "https://example.com?has-param1&has-param2",
+ RemoteSettings
+ )
+ );
+ assert.equal(
+ "has-params",
+ await classifySite(
+ "https://example.com?has-param1&has-param2&other=other",
+ RemoteSettings
+ )
+ );
+ assert.equal(
+ "other",
+ await classifySite("https://example.com?has-param1", RemoteSettings)
+ );
+ assert.equal(
+ "other",
+ await classifySite("https://example.com?has-param2", RemoteSettings)
+ );
+
+ assert.equal(
+ "search-engine",
+ await classifySite("https://google.com", RemoteSettings)
+ );
+ assert.equal(
+ "search-engine",
+ await classifySite("https://google.de", RemoteSettings)
+ );
+ assert.equal(
+ "search-engine",
+ await classifySite("http://bing.com/?q=firefox", RemoteSettings)
+ );
+
+ assert.equal(
+ "news-portal",
+ await classifySite("https://yahoo.com", RemoteSettings)
+ );
+
+ assert.equal(
+ "social-media",
+ await classifySite("http://twitter.com/firefox", RemoteSettings)
+ );
+
+ assert.equal(
+ "ecommerce",
+ await classifySite("https://amazon.com", RemoteSettings)
+ );
+ assert.equal(
+ "ecommerce",
+ await classifySite("https://amazon.ca", RemoteSettings)
+ );
+ assert.equal(
+ "ecommerce",
+ await classifySite("https://ebay.com", RemoteSettings)
+ );
+ });
+});
diff --git a/browser/components/newtab/test/unit/lib/Store.test.js b/browser/components/newtab/test/unit/lib/Store.test.js
new file mode 100644
index 0000000000..9e5e5d362a
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/Store.test.js
@@ -0,0 +1,307 @@
+import { addNumberReducer, FakePrefs } from "test/unit/utils";
+import { createStore } from "redux";
+import injector from "inject!lib/Store.jsm";
+
+describe("Store", () => {
+ let Store;
+ let sandbox;
+ let store;
+ let dbStub;
+ beforeEach(() => {
+ sandbox = sinon.createSandbox();
+ function ActivityStreamMessageChannel(options) {
+ this.dispatch = options.dispatch;
+ this.createChannel = sandbox.spy();
+ this.destroyChannel = sandbox.spy();
+ this.middleware = sandbox.spy(s => next => action => next(action));
+ this.simulateMessagesForExistingTabs = sandbox.stub();
+ }
+ dbStub = sandbox.stub().resolves();
+ function FakeActivityStreamStorage() {
+ this.db = {};
+ sinon.stub(this, "db").get(dbStub);
+ }
+ ({ Store } = injector({
+ "lib/ActivityStreamMessageChannel.jsm": { ActivityStreamMessageChannel },
+ "lib/ActivityStreamPrefs.jsm": { Prefs: FakePrefs },
+ "lib/ActivityStreamStorage.jsm": {
+ ActivityStreamStorage: FakeActivityStreamStorage,
+ },
+ }));
+ store = new Store();
+ sandbox.stub(store, "_initIndexedDB").resolves();
+ });
+ afterEach(() => {
+ sandbox.restore();
+ });
+ it("should have a .feeds property that is a Map", () => {
+ assert.instanceOf(store.feeds, Map);
+ assert.equal(store.feeds.size, 0, ".feeds.size");
+ });
+ it("should have a redux store at ._store", () => {
+ assert.ok(store._store);
+ assert.property(store, "dispatch");
+ assert.property(store, "getState");
+ });
+ it("should create a ActivityStreamMessageChannel with the right dispatcher", () => {
+ assert.ok(store._messageChannel);
+ assert.equal(store._messageChannel.dispatch, store.dispatch);
+ });
+ it("should connect the ActivityStreamMessageChannel's middleware", () => {
+ store.dispatch({ type: "FOO" });
+ assert.calledOnce(store._messageChannel.middleware);
+ });
+ describe("#initFeed", () => {
+ it("should add an instance of the feed to .feeds", () => {
+ class Foo {}
+ store._prefs.set("foo", true);
+ store.init(new Map([["foo", () => new Foo()]]));
+ store.initFeed("foo");
+
+ assert.isTrue(store.feeds.has("foo"), "foo is set");
+ assert.instanceOf(store.feeds.get("foo"), Foo);
+ });
+ it("should call the feed's onAction with uninit action if it exists", () => {
+ let feed;
+ function createFeed() {
+ feed = { onAction: sinon.spy() };
+ return feed;
+ }
+ const action = { type: "FOO" };
+ store._feedFactories = new Map([["foo", createFeed]]);
+
+ store.initFeed("foo", action);
+
+ assert.calledOnce(feed.onAction);
+ assert.calledWith(feed.onAction, action);
+ });
+ it("should add a .store property to the feed", () => {
+ class Foo {}
+ store._feedFactories = new Map([["foo", () => new Foo()]]);
+ store.initFeed("foo");
+
+ assert.propertyVal(store.feeds.get("foo"), "store", store);
+ });
+ });
+ describe("#uninitFeed", () => {
+ it("should not throw if no feed with that name exists", () => {
+ assert.doesNotThrow(() => {
+ store.uninitFeed("bar");
+ });
+ });
+ it("should call the feed's onAction with uninit action if it exists", () => {
+ let feed;
+ function createFeed() {
+ feed = { onAction: sinon.spy() };
+ return feed;
+ }
+ const action = { type: "BAR" };
+ store._feedFactories = new Map([["foo", createFeed]]);
+ store.initFeed("foo");
+
+ store.uninitFeed("foo", action);
+
+ assert.calledOnce(feed.onAction);
+ assert.calledWith(feed.onAction, action);
+ });
+ it("should remove the feed from .feeds", () => {
+ class Foo {}
+ store._feedFactories = new Map([["foo", () => new Foo()]]);
+
+ store.initFeed("foo");
+ store.uninitFeed("foo");
+
+ assert.isFalse(store.feeds.has("foo"), "foo is not in .feeds");
+ });
+ });
+ describe("onPrefChanged", () => {
+ beforeEach(() => {
+ sinon.stub(store, "initFeed");
+ sinon.stub(store, "uninitFeed");
+ store._prefs.set("foo", false);
+ store.init(new Map([["foo", () => ({})]]));
+ });
+ it("should initialize the feed if called with true", () => {
+ store.onPrefChanged("foo", true);
+
+ assert.calledWith(store.initFeed, "foo");
+ assert.notCalled(store.uninitFeed);
+ });
+ it("should uninitialize the feed if called with false", () => {
+ store.onPrefChanged("foo", false);
+
+ assert.calledWith(store.uninitFeed, "foo");
+ assert.notCalled(store.initFeed);
+ });
+ it("should do nothing if not an expected feed", () => {
+ store.onPrefChanged("bar", false);
+
+ assert.notCalled(store.initFeed);
+ assert.notCalled(store.uninitFeed);
+ });
+ });
+ describe("#init", () => {
+ it("should call .initFeed with each key", async () => {
+ sinon.stub(store, "initFeed");
+ store._prefs.set("foo", true);
+ store._prefs.set("bar", true);
+ await store.init(
+ new Map([
+ ["foo", () => {}],
+ ["bar", () => {}],
+ ])
+ );
+ assert.calledWith(store.initFeed, "foo");
+ assert.calledWith(store.initFeed, "bar");
+ });
+ it("should call _initIndexedDB", async () => {
+ await store.init(new Map());
+
+ assert.calledOnce(store._initIndexedDB);
+ assert.calledWithExactly(store._initIndexedDB, "feeds.telemetry");
+ });
+ it("should access the db property of indexedDB", async () => {
+ store._initIndexedDB.restore();
+ await store.init(new Map());
+
+ assert.calledOnce(dbStub);
+ });
+ it("should reset ActivityStreamStorage telemetry if opening the db fails", async () => {
+ store._initIndexedDB.restore();
+ // Force an IndexedDB error
+ dbStub.rejects();
+
+ await store.init(new Map());
+
+ assert.calledOnce(dbStub);
+ assert.isNull(store.dbStorage.telemetry);
+ });
+ it("should not initialize the feed if the Pref is set to false", async () => {
+ sinon.stub(store, "initFeed");
+ store._prefs.set("foo", false);
+ await store.init(new Map([["foo", () => {}]]));
+ assert.notCalled(store.initFeed);
+ });
+ it("should observe the pref branch", async () => {
+ sinon.stub(store._prefs, "observeBranch");
+ await store.init(new Map());
+ assert.calledOnce(store._prefs.observeBranch);
+ assert.calledWith(store._prefs.observeBranch, store);
+ });
+ it("should initialize the ActivityStreamMessageChannel channel", async () => {
+ await store.init(new Map());
+ assert.calledOnce(store._messageChannel.createChannel);
+ });
+ it("should emit an initial event if provided", async () => {
+ sinon.stub(store, "dispatch");
+ const action = { type: "FOO" };
+
+ await store.init(new Map(), action);
+
+ assert.calledOnce(store.dispatch);
+ assert.calledWith(store.dispatch, action);
+ });
+ it("should initialize the telemtry feed first", () => {
+ store._prefs.set("feeds.foo", true);
+ store._prefs.set("feeds.telemetry", true);
+ const telemetrySpy = sandbox.stub().returns({});
+ const fooSpy = sandbox.stub().returns({});
+ // Intentionally put the telemetry feed as the second item.
+ const feedFactories = new Map([
+ ["feeds.foo", fooSpy],
+ ["feeds.telemetry", telemetrySpy],
+ ]);
+ store.init(feedFactories);
+ assert.ok(telemetrySpy.calledBefore(fooSpy));
+ });
+ it("should dispatch init/load events", async () => {
+ await store.init(new Map(), { type: "FOO" });
+
+ assert.calledOnce(store._messageChannel.simulateMessagesForExistingTabs);
+ });
+ it("should dispatch INIT before LOAD", async () => {
+ const init = { type: "INIT" };
+ const load = { type: "TAB_LOAD" };
+ sandbox.stub(store, "dispatch");
+ store._messageChannel.simulateMessagesForExistingTabs.callsFake(() =>
+ store.dispatch(load)
+ );
+ await store.init(new Map(), init);
+
+ assert.calledTwice(store.dispatch);
+ assert.equal(store.dispatch.firstCall.args[0], init);
+ assert.equal(store.dispatch.secondCall.args[0], load);
+ });
+ });
+ describe("#uninit", () => {
+ it("should emit an uninit event if provided on init", () => {
+ sinon.stub(store, "dispatch");
+ const action = { type: "BAR" };
+ store.init(new Map(), null, action);
+
+ store.uninit();
+
+ assert.calledOnce(store.dispatch);
+ assert.calledWith(store.dispatch, action);
+ });
+ it("should clear .feeds and ._feedFactories", () => {
+ store._prefs.set("a", true);
+ store.init(
+ new Map([
+ ["a", () => ({})],
+ ["b", () => ({})],
+ ["c", () => ({})],
+ ])
+ );
+
+ store.uninit();
+
+ assert.equal(store.feeds.size, 0);
+ assert.isNull(store._feedFactories);
+ });
+ it("should destroy the ActivityStreamMessageChannel channel", () => {
+ store.uninit();
+ assert.calledOnce(store._messageChannel.destroyChannel);
+ });
+ });
+ describe("#getState", () => {
+ it("should return the redux state", () => {
+ store._store = createStore((prevState = 123) => prevState);
+ const { getState } = store;
+ assert.equal(getState(), 123);
+ });
+ });
+ describe("#dispatch", () => {
+ it("should call .onAction of each feed", async () => {
+ const { dispatch } = store;
+ const sub = { onAction: sinon.spy() };
+ const action = { type: "FOO" };
+
+ store._prefs.set("sub", true);
+ await store.init(new Map([["sub", () => sub]]));
+
+ dispatch(action);
+
+ assert.calledWith(sub.onAction, action);
+ });
+ it("should call the reducers", () => {
+ const { dispatch } = store;
+ store._store = createStore(addNumberReducer);
+
+ dispatch({ type: "ADD", data: 14 });
+
+ assert.equal(store.getState(), 14);
+ });
+ });
+ describe("#subscribe", () => {
+ it("should subscribe to changes to the store", () => {
+ const sub = sinon.spy();
+ const action = { type: "FOO" };
+
+ store.subscribe(sub);
+ store.dispatch(action);
+
+ assert.calledOnce(sub);
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/lib/SystemTickFeed.test.js b/browser/components/newtab/test/unit/lib/SystemTickFeed.test.js
new file mode 100644
index 0000000000..39d358c305
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/SystemTickFeed.test.js
@@ -0,0 +1,46 @@
+import { SYSTEM_TICK_INTERVAL, SystemTickFeed } from "lib/SystemTickFeed.jsm";
+import { actionTypes as at } from "common/Actions.jsm";
+
+describe("System Tick Feed", () => {
+ let instance;
+ let clock;
+
+ beforeEach(() => {
+ clock = sinon.useFakeTimers();
+
+ instance = new SystemTickFeed();
+ instance.store = {
+ getState() {
+ return {};
+ },
+ dispatch() {},
+ };
+ });
+ afterEach(() => {
+ clock.restore();
+ });
+ it("should create a SystemTickFeed", () => {
+ assert.instanceOf(instance, SystemTickFeed);
+ });
+ it("should fire SYSTEM_TICK events at configured interval", () => {
+ let expectation = sinon
+ .mock(instance.store)
+ .expects("dispatch")
+ .twice()
+ .withExactArgs({ type: at.SYSTEM_TICK });
+
+ instance.onAction({ type: at.INIT });
+ clock.tick(SYSTEM_TICK_INTERVAL * 2);
+ expectation.verify();
+ });
+ it("should not fire SYSTEM_TICK events after UNINIT", () => {
+ let expectation = sinon
+ .mock(instance.store)
+ .expects("dispatch")
+ .never();
+
+ instance.onAction({ type: at.UNINIT });
+ clock.tick(SYSTEM_TICK_INTERVAL * 2);
+ expectation.verify();
+ });
+});
diff --git a/browser/components/newtab/test/unit/lib/TelemetryFeed.test.js b/browser/components/newtab/test/unit/lib/TelemetryFeed.test.js
new file mode 100644
index 0000000000..01959b9dbb
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/TelemetryFeed.test.js
@@ -0,0 +1,1816 @@
+/* global Services */
+import {
+ actionCreators as ac,
+ actionTypes as at,
+ actionUtils as au,
+} from "common/Actions.jsm";
+import {
+ ASRouterEventPing,
+ BasePing,
+ ImpressionStatsPing,
+ SessionPing,
+ UserEventPing,
+} from "test/schemas/pings";
+import { FakePrefs, GlobalOverrider } from "test/unit/utils";
+import { ASRouterPreferences } from "lib/ASRouterPreferences.jsm";
+import injector from "inject!lib/TelemetryFeed.jsm";
+import { MESSAGE_TYPE_HASH as msg } from "common/ActorConstants.jsm";
+
+const FAKE_UUID = "{foo-123-foo}";
+const FAKE_ROUTER_MESSAGE_PROVIDER = [{ id: "cfr", enabled: true }];
+const FAKE_TELEMETRY_ID = "foo123";
+
+describe("TelemetryFeed", () => {
+ let globals;
+ let sandbox;
+ let expectedUserPrefs;
+ let browser = {
+ getAttribute() {
+ return "true";
+ },
+ };
+ let instance;
+ let clock;
+ let fakeHomePageUrl;
+ let fakeHomePage;
+ let fakeExtensionSettingsStore;
+ let ExperimentAPI = { getExperimentMetaData: () => {} };
+ class PingCentre {
+ sendPing() {}
+ uninit() {}
+ sendStructuredIngestionPing() {}
+ }
+ class UTEventReporting {
+ sendUserEvent() {}
+ sendSessionEndEvent() {}
+ uninit() {}
+ }
+
+ const {
+ TelemetryFeed,
+ USER_PREFS_ENCODING,
+ PREF_IMPRESSION_ID,
+ TELEMETRY_PREF,
+ EVENTS_TELEMETRY_PREF,
+ STRUCTURED_INGESTION_ENDPOINT_PREF,
+ } = injector({
+ "lib/UTEventReporting.jsm": { UTEventReporting },
+ });
+
+ beforeEach(() => {
+ globals = new GlobalOverrider();
+ sandbox = globals.sandbox;
+ clock = sinon.useFakeTimers();
+ fakeHomePageUrl = "about:home";
+ fakeHomePage = {
+ get() {
+ return fakeHomePageUrl;
+ },
+ };
+ fakeExtensionSettingsStore = {
+ initialize() {
+ return Promise.resolve();
+ },
+ getSetting() {},
+ };
+ sandbox.spy(global.Cu, "reportError");
+ globals.set("AboutNewTab", {
+ newTabURLOverridden: false,
+ newTabURL: "",
+ });
+ globals.set("HomePage", fakeHomePage);
+ globals.set("ExtensionSettingsStore", fakeExtensionSettingsStore);
+ globals.set("PingCentre", PingCentre);
+ globals.set("UTEventReporting", UTEventReporting);
+ globals.set("ClientID", {
+ getClientID: sandbox.spy(async () => FAKE_TELEMETRY_ID),
+ });
+ globals.set("ExperimentAPI", ExperimentAPI);
+
+ sandbox
+ .stub(ASRouterPreferences, "providers")
+ .get(() => FAKE_ROUTER_MESSAGE_PROVIDER);
+ instance = new TelemetryFeed();
+ });
+ afterEach(() => {
+ clock.restore();
+ globals.restore();
+ FakePrefs.prototype.prefs = {};
+ ASRouterPreferences.uninit();
+ });
+ describe("#init", () => {
+ it("should create an instance", () => {
+ const testInstance = new TelemetryFeed();
+ assert.isDefined(testInstance);
+ });
+ it("should add .pingCentre, a PingCentre instance", () => {
+ assert.instanceOf(instance.pingCentre, PingCentre);
+ });
+ it("should add .utEvents, a UTEventReporting instance", () => {
+ assert.instanceOf(instance.utEvents, UTEventReporting);
+ });
+ it("should make this.browserOpenNewtabStart() observe browser-open-newtab-start", () => {
+ sandbox.spy(Services.obs, "addObserver");
+
+ instance.init();
+
+ assert.calledTwice(Services.obs.addObserver);
+ assert.calledWithExactly(
+ Services.obs.addObserver,
+ instance.browserOpenNewtabStart,
+ "browser-open-newtab-start"
+ );
+ });
+ it("should add window open listener", () => {
+ sandbox.spy(Services.obs, "addObserver");
+
+ instance.init();
+
+ assert.calledTwice(Services.obs.addObserver);
+ assert.calledWithExactly(
+ Services.obs.addObserver,
+ instance._addWindowListeners,
+ "domwindowopened"
+ );
+ });
+ it("should add TabPinned event listener on new windows", () => {
+ const stub = { addEventListener: sandbox.stub() };
+ sandbox.spy(Services.obs, "addObserver");
+
+ instance.init();
+
+ assert.calledTwice(Services.obs.addObserver);
+ const [cb] = Services.obs.addObserver.secondCall.args;
+ cb(stub);
+ assert.calledTwice(stub.addEventListener);
+ assert.calledWithExactly(
+ stub.addEventListener,
+ "unload",
+ instance.handleEvent
+ );
+ assert.calledWithExactly(
+ stub.addEventListener,
+ "TabPinned",
+ instance.handleEvent
+ );
+ });
+ it("should create impression id if none exists", () => {
+ assert.equal(instance._impressionId, FAKE_UUID);
+ });
+ it("should set impression id if it exists", () => {
+ FakePrefs.prototype.prefs = {};
+ FakePrefs.prototype.prefs[PREF_IMPRESSION_ID] = "fakeImpressionId";
+ assert.equal(new TelemetryFeed()._impressionId, "fakeImpressionId");
+ });
+ it("should register listeners on existing windows", () => {
+ const stub = sandbox.stub();
+ globals.set({
+ Services: {
+ ...Services,
+ wm: { getEnumerator: () => [{ addEventListener: stub }] },
+ },
+ });
+
+ instance.init();
+
+ assert.calledTwice(stub);
+ assert.calledWithExactly(stub, "unload", instance.handleEvent);
+ assert.calledWithExactly(stub, "TabPinned", instance.handleEvent);
+ });
+ describe("telemetry pref changes from false to true", () => {
+ beforeEach(() => {
+ FakePrefs.prototype.prefs = {};
+ FakePrefs.prototype.prefs[TELEMETRY_PREF] = false;
+ instance = new TelemetryFeed();
+
+ assert.propertyVal(instance, "telemetryEnabled", false);
+ });
+
+ it("should set the enabled property to true", () => {
+ instance._prefs.set(TELEMETRY_PREF, true);
+
+ assert.propertyVal(instance, "telemetryEnabled", true);
+ });
+ });
+ describe("events telemetry pref changes from false to true", () => {
+ beforeEach(() => {
+ FakePrefs.prototype.prefs = {};
+ FakePrefs.prototype.prefs[EVENTS_TELEMETRY_PREF] = false;
+ instance = new TelemetryFeed();
+
+ assert.propertyVal(instance, "eventTelemetryEnabled", false);
+ });
+
+ it("should set the enabled property to true", () => {
+ instance._prefs.set(EVENTS_TELEMETRY_PREF, true);
+
+ assert.propertyVal(instance, "eventTelemetryEnabled", true);
+ });
+ });
+ it("should set a scalar for deletion-request", () => {
+ sandbox.spy(Services.telemetry, "scalarSet");
+
+ instance.init();
+
+ assert.calledOnce(Services.telemetry.scalarSet);
+ assert.calledWith(
+ Services.telemetry.scalarSet,
+ "deletion.request.impression_id",
+ instance._impressionId
+ );
+ });
+ });
+ describe("#handleEvent", () => {
+ it("should dispatch a TAB_PINNED_EVENT", () => {
+ sandbox.stub(instance, "sendEvent");
+ globals.set({
+ Services: {
+ ...Services,
+ wm: {
+ getEnumerator: () => [{ gBrowser: { tabs: [{ pinned: true }] } }],
+ },
+ },
+ });
+
+ instance.handleEvent({ type: "TabPinned", target: {} });
+
+ assert.calledOnce(instance.sendEvent);
+ const [ping] = instance.sendEvent.firstCall.args;
+ assert.propertyVal(ping, "event", "TABPINNED");
+ assert.propertyVal(ping, "source", "TAB_CONTEXT_MENU");
+ assert.propertyVal(ping, "session_id", "n/a");
+ assert.propertyVal(ping.value, "total_pinned_tabs", 1);
+ });
+ it("should skip private windows", () => {
+ sandbox.stub(instance, "sendEvent");
+ globals.set({ PrivateBrowsingUtils: { isWindowPrivate: () => true } });
+
+ instance.handleEvent({ type: "TabPinned", target: {} });
+
+ assert.notCalled(instance.sendEvent);
+ });
+ it("should return the correct value for total_pinned_tabs", () => {
+ sandbox.stub(instance, "sendEvent");
+ globals.set({
+ Services: {
+ ...Services,
+ wm: {
+ getEnumerator: () => [
+ {
+ gBrowser: { tabs: [{ pinned: true }, { pinned: false }] },
+ },
+ ],
+ },
+ },
+ });
+
+ instance.handleEvent({ type: "TabPinned", target: {} });
+
+ assert.calledOnce(instance.sendEvent);
+ const [ping] = instance.sendEvent.firstCall.args;
+ assert.propertyVal(ping, "event", "TABPINNED");
+ assert.propertyVal(ping, "source", "TAB_CONTEXT_MENU");
+ assert.propertyVal(ping, "session_id", "n/a");
+ assert.propertyVal(ping.value, "total_pinned_tabs", 1);
+ });
+ it("should return the correct value for total_pinned_tabs (when private windows are open)", () => {
+ sandbox.stub(instance, "sendEvent");
+ const privateWinStub = sandbox
+ .stub()
+ .onCall(0)
+ .returns(false)
+ .onCall(1)
+ .returns(true);
+ globals.set({
+ PrivateBrowsingUtils: { isWindowPrivate: privateWinStub },
+ });
+ globals.set({
+ Services: {
+ ...Services,
+ wm: {
+ getEnumerator: () => [
+ {
+ gBrowser: { tabs: [{ pinned: true }, { pinned: true }] },
+ },
+ ],
+ },
+ },
+ });
+
+ instance.handleEvent({ type: "TabPinned", target: {} });
+
+ assert.calledOnce(instance.sendEvent);
+ const [ping] = instance.sendEvent.firstCall.args;
+ assert.propertyVal(ping.value, "total_pinned_tabs", 0);
+ });
+ it("should unregister the event listeners", () => {
+ const stub = { removeEventListener: sandbox.stub() };
+
+ instance.handleEvent({ type: "unload", target: stub });
+
+ assert.calledTwice(stub.removeEventListener);
+ assert.calledWithExactly(
+ stub.removeEventListener,
+ "unload",
+ instance.handleEvent
+ );
+ assert.calledWithExactly(
+ stub.removeEventListener,
+ "TabPinned",
+ instance.handleEvent
+ );
+ });
+ });
+ describe("#addSession", () => {
+ it("should add a session and return it", () => {
+ const session = instance.addSession("foo");
+
+ assert.equal(instance.sessions.get("foo"), session);
+ });
+ it("should set the session_id", () => {
+ sandbox.spy(global.gUUIDGenerator, "generateUUID");
+
+ const session = instance.addSession("foo");
+
+ assert.calledOnce(global.gUUIDGenerator.generateUUID);
+ assert.equal(
+ session.session_id,
+ global.gUUIDGenerator.generateUUID.firstCall.returnValue
+ );
+ });
+ it("should set the page if a url parameter is given", () => {
+ const session = instance.addSession("foo", "about:monkeys");
+
+ assert.propertyVal(session, "page", "about:monkeys");
+ });
+ it("should set the page prop to 'unknown' if no URL parameter given", () => {
+ const session = instance.addSession("foo");
+
+ assert.propertyVal(session, "page", "unknown");
+ });
+ it("should set the perf type when lacking timestamp", () => {
+ const session = instance.addSession("foo");
+
+ assert.propertyVal(session.perf, "load_trigger_type", "unexpected");
+ });
+ it("should set load_trigger_type to first_window_opened on the first about:home seen", () => {
+ const session = instance.addSession("foo", "about:home");
+
+ assert.propertyVal(
+ session.perf,
+ "load_trigger_type",
+ "first_window_opened"
+ );
+ });
+ it("should not set load_trigger_type to first_window_opened on the second about:home seen", () => {
+ instance.addSession("foo", "about:home");
+
+ const session2 = instance.addSession("foo", "about:home");
+
+ assert.notPropertyVal(
+ session2.perf,
+ "load_trigger_type",
+ "first_window_opened"
+ );
+ });
+ it("should set load_trigger_ts to the value of the process start timestamp", () => {
+ const session = instance.addSession("foo", "about:home");
+
+ assert.propertyVal(session.perf, "load_trigger_ts", 1588010448000);
+ });
+ it("should create a valid session ping on the first about:home seen", () => {
+ // Add a session
+ const portID = "foo";
+ const session = instance.addSession(portID, "about:home");
+
+ // Create a ping referencing the session
+ const ping = instance.createSessionEndEvent(session);
+ assert.validate(ping, SessionPing);
+ });
+ it("should be a valid ping with the data_late_by_ms perf", () => {
+ // Add a session
+ const portID = "foo";
+ const session = instance.addSession(portID, "about:home");
+ instance.saveSessionPerfData("foo", { topsites_data_late_by_ms: 10 });
+ instance.saveSessionPerfData("foo", { highlights_data_late_by_ms: 20 });
+
+ // Create a ping referencing the session
+ const ping = instance.createSessionEndEvent(session);
+ assert.validate(ping, SessionPing);
+ assert.propertyVal(
+ instance.sessions.get("foo").perf,
+ "highlights_data_late_by_ms",
+ 20
+ );
+ assert.propertyVal(
+ instance.sessions.get("foo").perf,
+ "topsites_data_late_by_ms",
+ 10
+ );
+ });
+ it("should be a valid ping with the topsites stats perf", () => {
+ // Add a session
+ const portID = "foo";
+ const session = instance.addSession(portID, "about:home");
+ instance.saveSessionPerfData("foo", {
+ topsites_icon_stats: {
+ custom_screenshot: 0,
+ screenshot_with_icon: 2,
+ screenshot: 1,
+ tippytop: 2,
+ rich_icon: 1,
+ no_image: 0,
+ },
+ topsites_pinned: 3,
+ topsites_search_shortcuts: 2,
+ });
+
+ // Create a ping referencing the session
+ const ping = instance.createSessionEndEvent(session);
+ assert.validate(ping, SessionPing);
+ assert.propertyVal(
+ instance.sessions.get("foo").perf.topsites_icon_stats,
+ "screenshot_with_icon",
+ 2
+ );
+ assert.equal(instance.sessions.get("foo").perf.topsites_pinned, 3);
+ assert.equal(
+ instance.sessions.get("foo").perf.topsites_search_shortcuts,
+ 2
+ );
+ });
+ });
+
+ describe("#browserOpenNewtabStart", () => {
+ it("should call ChromeUtils.addProfilerMarker with browser-open-newtab-start", () => {
+ globals.set("ChromeUtils", {
+ addProfilerMarker: sandbox.stub(),
+ });
+
+ sandbox.stub(global.Cu, "now").returns(12345);
+
+ instance.browserOpenNewtabStart();
+
+ assert.calledOnce(ChromeUtils.addProfilerMarker);
+ assert.calledWithExactly(
+ ChromeUtils.addProfilerMarker,
+ "UserTiming",
+ 12345,
+ "browser-open-newtab-start"
+ );
+ });
+ });
+
+ describe("#endSession", () => {
+ it("should not throw if there is no session for the given port ID", () => {
+ assert.doesNotThrow(() => instance.endSession("doesn't exist"));
+ });
+ it("should add a session_duration integer if there is a visibility_event_rcvd_ts", () => {
+ sandbox.stub(instance, "sendEvent");
+ const session = instance.addSession("foo");
+ session.perf.visibility_event_rcvd_ts = 444.4732;
+
+ instance.endSession("foo");
+
+ assert.isNumber(session.session_duration);
+ assert.ok(
+ Number.isInteger(session.session_duration),
+ "session_duration should be an integer"
+ );
+ });
+ it("shouldn't send session ping if there's no visibility_event_rcvd_ts", () => {
+ sandbox.stub(instance, "sendEvent");
+ instance.addSession("foo");
+
+ instance.endSession("foo");
+
+ assert.notCalled(instance.sendEvent);
+ assert.isFalse(instance.sessions.has("foo"));
+ });
+ it("should remove the session from .sessions", () => {
+ sandbox.stub(instance, "sendEvent");
+ instance.addSession("foo");
+
+ instance.endSession("foo");
+
+ assert.isFalse(instance.sessions.has("foo"));
+ });
+ it("should call createSessionSendEvent and sendEvent with the sesssion", () => {
+ FakePrefs.prototype.prefs[TELEMETRY_PREF] = true;
+ FakePrefs.prototype.prefs[EVENTS_TELEMETRY_PREF] = true;
+ instance = new TelemetryFeed();
+
+ sandbox.stub(instance, "sendEvent");
+ sandbox.stub(instance, "createSessionEndEvent");
+ sandbox.stub(instance.utEvents, "sendSessionEndEvent");
+ const session = instance.addSession("foo");
+ session.perf.visibility_event_rcvd_ts = 444.4732;
+
+ instance.endSession("foo");
+
+ // Did we call sendEvent with the result of createSessionEndEvent?
+ assert.calledWith(instance.createSessionEndEvent, session);
+
+ let sessionEndEvent =
+ instance.createSessionEndEvent.firstCall.returnValue;
+ assert.calledWith(instance.sendEvent, sessionEndEvent);
+ assert.calledWith(instance.utEvents.sendSessionEndEvent, sessionEndEvent);
+ });
+ });
+ describe("ping creators", () => {
+ beforeEach(() => {
+ FakePrefs.prototype.prefs = {};
+ for (const pref of Object.keys(USER_PREFS_ENCODING)) {
+ FakePrefs.prototype.prefs[pref] = true;
+ expectedUserPrefs |= USER_PREFS_ENCODING[pref];
+ }
+ instance.init();
+ });
+ describe("#createPing", () => {
+ it("should create a valid base ping without a session if no portID is supplied", async () => {
+ const ping = await instance.createPing();
+ assert.validate(ping, BasePing);
+ assert.notProperty(ping, "session_id");
+ assert.notProperty(ping, "page");
+ });
+ it("should create a valid base ping with session info if a portID is supplied", async () => {
+ // Add a session
+ const portID = "foo";
+ instance.addSession(portID, "about:home");
+ const sessionID = instance.sessions.get(portID).session_id;
+
+ // Create a ping referencing the session
+ const ping = await instance.createPing(portID);
+ assert.validate(ping, BasePing);
+
+ // Make sure we added the right session-related stuff to the ping
+ assert.propertyVal(ping, "session_id", sessionID);
+ assert.propertyVal(ping, "page", "about:home");
+ });
+ it("should create an unexpected base ping if no session yet portID is supplied", async () => {
+ const ping = await instance.createPing("foo");
+
+ assert.validate(ping, BasePing);
+ assert.propertyVal(ping, "page", "unknown");
+ assert.propertyVal(
+ instance.sessions.get("foo").perf,
+ "load_trigger_type",
+ "unexpected"
+ );
+ });
+ it("should create a base ping with user_prefs", async () => {
+ const ping = await instance.createPing("foo");
+
+ assert.validate(ping, BasePing);
+ assert.propertyVal(ping, "user_prefs", expectedUserPrefs);
+ });
+ });
+ describe("#createUserEvent", () => {
+ it("should create a valid event", async () => {
+ const portID = "foo";
+ const data = { source: "TOP_SITES", event: "CLICK" };
+ const action = ac.AlsoToMain(ac.UserEvent(data), portID);
+ const session = instance.addSession(portID);
+
+ const ping = await instance.createUserEvent(action);
+
+ // Is it valid?
+ assert.validate(ping, UserEventPing);
+ // Does it have the right session_id?
+ assert.propertyVal(ping, "session_id", session.session_id);
+ });
+ });
+ describe("#createSessionEndEvent", () => {
+ it("should create a valid event", async () => {
+ const ping = await instance.createSessionEndEvent({
+ session_id: FAKE_UUID,
+ page: "about:newtab",
+ session_duration: 12345,
+ perf: {
+ load_trigger_ts: 10,
+ load_trigger_type: "menu_plus_or_keyboard",
+ visibility_event_rcvd_ts: 20,
+ is_preloaded: true,
+ },
+ });
+
+ // Is it valid?
+ assert.validate(ping, SessionPing);
+ assert.propertyVal(ping, "session_id", FAKE_UUID);
+ assert.propertyVal(ping, "page", "about:newtab");
+ assert.propertyVal(ping, "session_duration", 12345);
+ });
+ it("should create a valid unexpected session event", async () => {
+ const ping = await instance.createSessionEndEvent({
+ session_id: FAKE_UUID,
+ page: "about:newtab",
+ session_duration: 12345,
+ perf: {
+ load_trigger_type: "unexpected",
+ is_preloaded: true,
+ },
+ });
+
+ // Is it valid?
+ assert.validate(ping, SessionPing);
+ assert.propertyVal(ping, "session_id", FAKE_UUID);
+ assert.propertyVal(ping, "page", "about:newtab");
+ assert.propertyVal(ping, "session_duration", 12345);
+ assert.propertyVal(ping.perf, "load_trigger_type", "unexpected");
+ });
+ });
+ });
+ describe("#createImpressionStats", () => {
+ it("should create a valid impression stats ping", async () => {
+ const tiles = [{ id: 10001 }, { id: 10002 }, { id: 10003 }];
+ const action = ac.ImpressionStats({ source: "POCKET", tiles });
+ const ping = await instance.createImpressionStats(
+ au.getPortIdOfSender(action),
+ action.data
+ );
+
+ assert.validate(ping, ImpressionStatsPing);
+ assert.propertyVal(ping, "source", "POCKET");
+ assert.propertyVal(ping, "tiles", tiles);
+ });
+ it("should create a valid click ping", async () => {
+ const tiles = [{ id: 10001, pos: 2 }];
+ const action = ac.ImpressionStats({ source: "POCKET", tiles, click: 0 });
+ const ping = await instance.createImpressionStats(
+ au.getPortIdOfSender(action),
+ action.data
+ );
+
+ assert.validate(ping, ImpressionStatsPing);
+ assert.propertyVal(ping, "click", 0);
+ assert.propertyVal(ping, "tiles", tiles);
+ });
+ it("should create a valid block ping", async () => {
+ const tiles = [{ id: 10001, pos: 2 }];
+ const action = ac.ImpressionStats({ source: "POCKET", tiles, block: 0 });
+ const ping = await instance.createImpressionStats(
+ au.getPortIdOfSender(action),
+ action.data
+ );
+
+ assert.validate(ping, ImpressionStatsPing);
+ assert.propertyVal(ping, "block", 0);
+ assert.propertyVal(ping, "tiles", tiles);
+ });
+ it("should create a valid pocket ping", async () => {
+ const tiles = [{ id: 10001, pos: 2 }];
+ const action = ac.ImpressionStats({ source: "POCKET", tiles, pocket: 0 });
+ const ping = await instance.createImpressionStats(
+ au.getPortIdOfSender(action),
+ action.data
+ );
+
+ assert.validate(ping, ImpressionStatsPing);
+ assert.propertyVal(ping, "pocket", 0);
+ assert.propertyVal(ping, "tiles", tiles);
+ });
+ it("should pass shim if it is available to impression ping", async () => {
+ const tiles = [{ id: 10001, pos: 2, shim: 1234 }];
+ const action = ac.ImpressionStats({ source: "POCKET", tiles });
+ const ping = await instance.createImpressionStats(
+ au.getPortIdOfSender(action),
+ action.data
+ );
+
+ assert.propertyVal(ping, "tiles", tiles);
+ assert.propertyVal(ping.tiles[0], "shim", tiles[0].shim);
+ });
+ it("should not include client_id and session_id", async () => {
+ const tiles = [{ id: 10001 }, { id: 10002 }, { id: 10003 }];
+ const action = ac.ImpressionStats({ source: "POCKET", tiles });
+ const ping = await instance.createImpressionStats(
+ au.getPortIdOfSender(action),
+ action.data
+ );
+
+ assert.validate(ping, ImpressionStatsPing);
+ assert.notProperty(ping, "client_id");
+ assert.notProperty(ping, "session_id");
+ });
+ });
+ describe("#applyCFRPolicy", () => {
+ it("should use client_id and message_id in prerelease", async () => {
+ globals.set("UpdateUtils", {
+ getUpdateChannel() {
+ return "nightly";
+ },
+ });
+ const data = {
+ action: "cfr_user_event",
+ event: "IMPRESSION",
+ message_id: "cfr_message_01",
+ bucket_id: "cfr_bucket_01",
+ };
+ const { ping, pingType } = await instance.applyCFRPolicy(data);
+
+ assert.equal(pingType, "cfr");
+ assert.isUndefined(ping.impression_id);
+ assert.propertyVal(ping, "client_id", FAKE_TELEMETRY_ID);
+ assert.propertyVal(ping, "bucket_id", "cfr_bucket_01");
+ assert.propertyVal(ping, "message_id", "cfr_message_01");
+ });
+ it("should use impression_id and bucket_id in release", async () => {
+ globals.set("UpdateUtils", {
+ getUpdateChannel() {
+ return "release";
+ },
+ });
+ const data = {
+ action: "cfr_user_event",
+ event: "IMPRESSION",
+ message_id: "cfr_message_01",
+ bucket_id: "cfr_bucket_01",
+ };
+ const { ping, pingType } = await instance.applyCFRPolicy(data);
+
+ assert.equal(pingType, "cfr");
+ assert.isUndefined(ping.client_id);
+ assert.propertyVal(ping, "impression_id", FAKE_UUID);
+ assert.propertyVal(ping, "message_id", "n/a");
+ assert.propertyVal(ping, "bucket_id", "cfr_bucket_01");
+ });
+ it("should use client_id and message_id in the experiment cohort in release", async () => {
+ globals.set("UpdateUtils", {
+ getUpdateChannel() {
+ return "release";
+ },
+ });
+ sandbox.stub(ExperimentAPI, "getExperimentMetaData").returns({
+ slug: "SOME-CFR-EXP",
+ });
+ const data = {
+ action: "cfr_user_event",
+ event: "IMPRESSION",
+ message_id: "cfr_message_01",
+ bucket_id: "cfr_bucket_01",
+ };
+ const { ping, pingType } = await instance.applyCFRPolicy(data);
+
+ assert.equal(pingType, "cfr");
+ assert.isUndefined(ping.impression_id);
+ assert.propertyVal(ping, "client_id", FAKE_TELEMETRY_ID);
+ assert.propertyVal(ping, "bucket_id", "cfr_bucket_01");
+ assert.propertyVal(ping, "message_id", "cfr_message_01");
+ });
+ });
+ describe("#applyWhatsNewPolicy", () => {
+ it("should set client_id and set pingType", async () => {
+ const { ping, pingType } = await instance.applyWhatsNewPolicy({});
+
+ assert.propertyVal(ping, "client_id", FAKE_TELEMETRY_ID);
+ assert.equal(pingType, "whats-new-panel");
+ });
+ });
+ describe("#applyInfoBarPolicy", () => {
+ it("should set client_id and set pingType", async () => {
+ const { ping, pingType } = await instance.applyInfoBarPolicy({});
+
+ assert.propertyVal(ping, "client_id", FAKE_TELEMETRY_ID);
+ assert.equal(pingType, "infobar");
+ });
+ });
+ describe("#applyMomentsPolicy", () => {
+ it("should use client_id and message_id in prerelease", async () => {
+ globals.set("UpdateUtils", {
+ getUpdateChannel() {
+ return "nightly";
+ },
+ });
+ const data = {
+ action: "moments_user_event",
+ event: "IMPRESSION",
+ message_id: "moments_message_01",
+ bucket_id: "moments_bucket_01",
+ };
+ const { ping, pingType } = await instance.applyMomentsPolicy(data);
+
+ assert.equal(pingType, "moments");
+ assert.isUndefined(ping.impression_id);
+ assert.propertyVal(ping, "client_id", FAKE_TELEMETRY_ID);
+ assert.propertyVal(ping, "bucket_id", "moments_bucket_01");
+ assert.propertyVal(ping, "message_id", "moments_message_01");
+ });
+ it("should use impression_id and bucket_id in release", async () => {
+ globals.set("UpdateUtils", {
+ getUpdateChannel() {
+ return "release";
+ },
+ });
+ const data = {
+ action: "moments_user_event",
+ event: "IMPRESSION",
+ message_id: "moments_message_01",
+ bucket_id: "moments_bucket_01",
+ };
+ const { ping, pingType } = await instance.applyMomentsPolicy(data);
+
+ assert.equal(pingType, "moments");
+ assert.isUndefined(ping.client_id);
+ assert.propertyVal(ping, "impression_id", FAKE_UUID);
+ assert.propertyVal(ping, "message_id", "n/a");
+ assert.propertyVal(ping, "bucket_id", "moments_bucket_01");
+ });
+ it("should use client_id and message_id in the experiment cohort in release", async () => {
+ globals.set("UpdateUtils", {
+ getUpdateChannel() {
+ return "release";
+ },
+ });
+ sandbox.stub(ExperimentAPI, "getExperimentMetaData").returns({
+ slug: "SOME-CFR-EXP",
+ });
+ const data = {
+ action: "moments_user_event",
+ event: "IMPRESSION",
+ message_id: "moments_message_01",
+ bucket_id: "moments_bucket_01",
+ };
+ const { ping, pingType } = await instance.applyMomentsPolicy(data);
+
+ assert.equal(pingType, "moments");
+ assert.isUndefined(ping.impression_id);
+ assert.propertyVal(ping, "client_id", FAKE_TELEMETRY_ID);
+ assert.propertyVal(ping, "bucket_id", "moments_bucket_01");
+ assert.propertyVal(ping, "message_id", "moments_message_01");
+ });
+ });
+ describe("#applySnippetsPolicy", () => {
+ it("should include client_id", async () => {
+ const data = {
+ action: "snippets_user_event",
+ event: "IMPRESSION",
+ message_id: "snippets_message_01",
+ };
+ const { ping, pingType } = await instance.applySnippetsPolicy(data);
+
+ assert.equal(pingType, "snippets");
+ assert.propertyVal(ping, "client_id", FAKE_TELEMETRY_ID);
+ assert.propertyVal(ping, "message_id", "snippets_message_01");
+ });
+ });
+ describe("#applyOnboardingPolicy", () => {
+ it("should include client_id", async () => {
+ const data = {
+ action: "onboarding_user_event",
+ event: "CLICK_BUTTION",
+ message_id: "onboarding_message_01",
+ };
+ const { ping, pingType } = await instance.applyOnboardingPolicy(data);
+
+ assert.equal(pingType, "onboarding");
+ assert.propertyVal(ping, "client_id", FAKE_TELEMETRY_ID);
+ assert.propertyVal(ping, "message_id", "onboarding_message_01");
+ assert.propertyVal(ping, "browser_session_id", "fake_session_id");
+ });
+ it("should include page to event_context if there is a session", async () => {
+ const data = {
+ action: "onboarding_user_event",
+ event: "CLICK_BUTTION",
+ message_id: "onboarding_message_01",
+ };
+ const session = { page: "about:welcome" };
+ const { ping, pingType } = await instance.applyOnboardingPolicy(
+ data,
+ session
+ );
+
+ assert.equal(pingType, "onboarding");
+ assert.propertyVal(
+ ping,
+ "event_context",
+ JSON.stringify({ page: "about:welcome" })
+ );
+ assert.propertyVal(ping, "message_id", "onboarding_message_01");
+ });
+ it("should not set page if it is not in ONBOARDING_ALLOWED_PAGE_VALUES", async () => {
+ const data = {
+ action: "onboarding_user_event",
+ event: "CLICK_BUTTION",
+ message_id: "onboarding_message_01",
+ };
+ const session = { page: "foo" };
+ const { ping, pingType } = await instance.applyOnboardingPolicy(
+ data,
+ session
+ );
+
+ assert.calledOnce(global.Cu.reportError);
+ assert.equal(pingType, "onboarding");
+ assert.propertyVal(ping, "event_context", JSON.stringify({}));
+ assert.propertyVal(ping, "message_id", "onboarding_message_01");
+ });
+ it("should append page to event_context if it is not empty", async () => {
+ const data = {
+ action: "onboarding_user_event",
+ event: "CLICK_BUTTION",
+ message_id: "onboarding_message_01",
+ event_context: JSON.stringify({ foo: "bar" }),
+ };
+ const session = { page: "about:welcome" };
+ const { ping, pingType } = await instance.applyOnboardingPolicy(
+ data,
+ session
+ );
+
+ assert.equal(pingType, "onboarding");
+ assert.propertyVal(
+ ping,
+ "event_context",
+ JSON.stringify({ foo: "bar", page: "about:welcome" })
+ );
+ assert.propertyVal(ping, "message_id", "onboarding_message_01");
+ });
+ it("should append page to event_context if it is not a JSON serialized string", async () => {
+ const data = {
+ action: "onboarding_user_event",
+ event: "CLICK_BUTTION",
+ message_id: "onboarding_message_01",
+ event_context: "foo",
+ };
+ const session = { page: "about:welcome" };
+ const { ping, pingType } = await instance.applyOnboardingPolicy(
+ data,
+ session
+ );
+
+ assert.equal(pingType, "onboarding");
+ assert.propertyVal(
+ ping,
+ "event_context",
+ JSON.stringify({ value: "foo", page: "about:welcome" })
+ );
+ assert.propertyVal(ping, "message_id", "onboarding_message_01");
+ });
+ });
+ describe("#applyUndesiredEventPolicy", () => {
+ it("should exclude client_id and use impression_id", () => {
+ const data = {
+ action: "asrouter_undesired_event",
+ event: "RS_MISSING_DATA",
+ };
+ const { ping, pingType } = instance.applyUndesiredEventPolicy(data);
+
+ assert.equal(pingType, "undesired-events");
+ assert.isUndefined(ping.client_id);
+ assert.propertyVal(ping, "impression_id", FAKE_UUID);
+ });
+ });
+ describe("#createASRouterEvent", () => {
+ it("should create a valid AS Router event", async () => {
+ const data = {
+ action: "snippets_user_event",
+ event: "CLICK",
+ message_id: "snippets_message_01",
+ };
+ const action = ac.ASRouterUserEvent(data);
+ const { ping } = await instance.createASRouterEvent(action);
+
+ assert.validate(ping, ASRouterEventPing);
+ assert.propertyVal(ping, "event", "CLICK");
+ });
+ it("should call applyCFRPolicy if action equals to cfr_user_event", async () => {
+ const data = {
+ action: "cfr_user_event",
+ event: "IMPRESSION",
+ message_id: "cfr_message_01",
+ };
+ sandbox.stub(instance, "applyCFRPolicy");
+ const action = ac.ASRouterUserEvent(data);
+ await instance.createASRouterEvent(action);
+
+ assert.calledOnce(instance.applyCFRPolicy);
+ });
+ it("should call applySnippetsPolicy if action equals to snippets_user_event", async () => {
+ const data = {
+ action: "snippets_user_event",
+ event: "IMPRESSION",
+ message_id: "snippets_message_01",
+ };
+ sandbox.stub(instance, "applySnippetsPolicy");
+ const action = ac.ASRouterUserEvent(data);
+ await instance.createASRouterEvent(action);
+
+ assert.calledOnce(instance.applySnippetsPolicy);
+ });
+ it("should call applySnippetsPolicy if action equals to snippets_local_testing_user_event", async () => {
+ const data = {
+ action: "snippets_local_testing_user_event",
+ event: "IMPRESSION",
+ message_id: "snippets_message_01",
+ };
+ sandbox.stub(instance, "applySnippetsPolicy");
+ const action = ac.ASRouterUserEvent(data);
+ await instance.createASRouterEvent(action);
+
+ assert.calledOnce(instance.applySnippetsPolicy);
+ });
+ it("should call applyOnboardingPolicy if action equals to onboarding_user_event", async () => {
+ const data = {
+ action: "onboarding_user_event",
+ event: "CLICK_BUTTON",
+ message_id: "onboarding_message_01",
+ };
+ sandbox.stub(instance, "applyOnboardingPolicy");
+ const action = ac.ASRouterUserEvent(data);
+ await instance.createASRouterEvent(action);
+
+ assert.calledOnce(instance.applyOnboardingPolicy);
+ });
+ it("should call applyWhatsNewPolicy if action equals to whats-new-panel_user_event", async () => {
+ const data = {
+ action: "whats-new-panel_user_event",
+ event: "CLICK_BUTTON",
+ message_id: "whats-new-panel_message_01",
+ };
+ sandbox.stub(instance, "applyWhatsNewPolicy");
+ const action = ac.ASRouterUserEvent(data);
+ await instance.createASRouterEvent(action);
+
+ assert.calledOnce(instance.applyWhatsNewPolicy);
+ });
+ it("should call applyMomentsPolicy if action equals to moments_user_event", async () => {
+ const data = {
+ action: "moments_user_event",
+ event: "CLICK_BUTTON",
+ message_id: "moments_message_01",
+ };
+ sandbox.stub(instance, "applyMomentsPolicy");
+ const action = ac.ASRouterUserEvent(data);
+ await instance.createASRouterEvent(action);
+
+ assert.calledOnce(instance.applyMomentsPolicy);
+ });
+ it("should call applyUndesiredEventPolicy if action equals to asrouter_undesired_event", async () => {
+ const data = {
+ action: "asrouter_undesired_event",
+ event: "UNDESIRED_EVENT",
+ };
+ sandbox.stub(instance, "applyUndesiredEventPolicy");
+ const action = ac.ASRouterUserEvent(data);
+ await instance.createASRouterEvent(action);
+
+ assert.calledOnce(instance.applyUndesiredEventPolicy);
+ });
+ it("should stringify event_context if it is an Object", async () => {
+ const data = {
+ action: "asrouter_undesired_event",
+ event: "UNDESIRED_EVENT",
+ event_context: { foo: "bar" },
+ };
+ const action = ac.ASRouterUserEvent(data);
+ const { ping } = await instance.createASRouterEvent(action);
+
+ assert.propertyVal(ping, "event_context", JSON.stringify({ foo: "bar" }));
+ });
+ it("should not stringify event_context if it is a String", async () => {
+ const data = {
+ action: "asrouter_undesired_event",
+ event: "UNDESIRED_EVENT",
+ event_context: "foo",
+ };
+ const action = ac.ASRouterUserEvent(data);
+ const { ping } = await instance.createASRouterEvent(action);
+
+ assert.propertyVal(ping, "event_context", "foo");
+ });
+ });
+ describe("#sendEventPing", () => {
+ it("should call sendStructuredIngestionEvent", async () => {
+ const data = {
+ action: "activity_stream_user_event",
+ event: "CLICK",
+ };
+ instance = new TelemetryFeed();
+ sandbox.spy(instance, "sendStructuredIngestionEvent");
+
+ await instance.sendEventPing(data);
+
+ const expectedPayload = {
+ client_id: FAKE_TELEMETRY_ID,
+ event: "CLICK",
+ browser_session_id: "fake_session_id",
+ };
+ assert.calledWith(instance.sendStructuredIngestionEvent, expectedPayload);
+ });
+ it("should stringify value if it is an Object", async () => {
+ const data = {
+ action: "activity_stream_user_event",
+ event: "CLICK",
+ value: { foo: "bar" },
+ };
+ instance = new TelemetryFeed();
+ sandbox.spy(instance, "sendStructuredIngestionEvent");
+
+ await instance.sendEventPing(data);
+
+ const expectedPayload = {
+ client_id: FAKE_TELEMETRY_ID,
+ event: "CLICK",
+ browser_session_id: "fake_session_id",
+ value: JSON.stringify({ foo: "bar" }),
+ };
+ assert.calledWith(instance.sendStructuredIngestionEvent, expectedPayload);
+ });
+ });
+ describe("#sendSessionPing", () => {
+ it("should call sendStructuredIngestionEvent", async () => {
+ const data = {
+ action: "activity_stream_session",
+ page: "about:home",
+ session_duration: 10000,
+ };
+ instance = new TelemetryFeed();
+ sandbox.spy(instance, "sendStructuredIngestionEvent");
+
+ await instance.sendSessionPing(data);
+
+ const expectedPayload = {
+ client_id: FAKE_TELEMETRY_ID,
+ page: "about:home",
+ session_duration: 10000,
+ };
+ assert.calledWith(instance.sendStructuredIngestionEvent, expectedPayload);
+ });
+ });
+ describe("#sendEvent", () => {
+ it("should call sendEventPing on activity_stream_user_event", () => {
+ FakePrefs.prototype.prefs.telemetry = true;
+ const event = { action: "activity_stream_user_event" };
+ instance = new TelemetryFeed();
+ sandbox.spy(instance, "sendEventPing");
+
+ instance.sendEvent(event);
+
+ assert.calledOnce(instance.sendEventPing);
+ });
+ it("should call sendSessionPing on activity_stream_session", () => {
+ FakePrefs.prototype.prefs.telemetry = true;
+ const event = { action: "activity_stream_session" };
+ instance = new TelemetryFeed();
+ sandbox.spy(instance, "sendSessionPing");
+
+ instance.sendEvent(event);
+
+ assert.calledOnce(instance.sendSessionPing);
+ });
+ });
+ describe("#sendUTEvent", () => {
+ it("should call the UT event function passed in", async () => {
+ FakePrefs.prototype.prefs[TELEMETRY_PREF] = true;
+ FakePrefs.prototype.prefs[EVENTS_TELEMETRY_PREF] = true;
+ const event = {};
+ instance = new TelemetryFeed();
+ sandbox.stub(instance.utEvents, "sendUserEvent");
+
+ await instance.sendUTEvent(event, instance.utEvents.sendUserEvent);
+
+ assert.calledWith(instance.utEvents.sendUserEvent, event);
+ });
+ });
+ describe("#sendStructuredIngestionEvent", () => {
+ it("should call PingCentre sendStructuredIngestionPing", async () => {
+ FakePrefs.prototype.prefs[TELEMETRY_PREF] = true;
+ const event = {};
+ instance = new TelemetryFeed();
+ sandbox.stub(instance.pingCentre, "sendStructuredIngestionPing");
+
+ await instance.sendStructuredIngestionEvent(
+ event,
+ "http://foo.com/base/"
+ );
+
+ assert.calledWith(instance.pingCentre.sendStructuredIngestionPing, event);
+ });
+ });
+ describe("#setLoadTriggerInfo", () => {
+ it("should call saveSessionPerfData w/load_trigger_{ts,type} data", () => {
+ sandbox.stub(global.Cu, "now").returns(12345);
+
+ globals.set("ChromeUtils", {
+ addProfilerMarker: sandbox.stub(),
+ });
+
+ instance.browserOpenNewtabStart();
+
+ const stub = sandbox.stub(instance, "saveSessionPerfData");
+ instance.addSession("port123");
+
+ instance.setLoadTriggerInfo("port123");
+
+ assert.calledWith(stub, "port123", {
+ load_trigger_ts: 1588010448000 + 12345,
+ load_trigger_type: "menu_plus_or_keyboard",
+ });
+ });
+
+ it("should not call saveSessionPerfData when getting mark throws", () => {
+ const stub = sandbox.stub(instance, "saveSessionPerfData");
+ instance.addSession("port123");
+
+ instance.setLoadTriggerInfo("port123");
+
+ assert.notCalled(stub);
+ });
+ });
+
+ describe("#saveSessionPerfData", () => {
+ it("should update the given session with the given data", () => {
+ instance.addSession("port123");
+ assert.notProperty(instance.sessions.get("port123"), "fake_ts");
+ const data = { fake_ts: 456, other_fake_ts: 789 };
+
+ instance.saveSessionPerfData("port123", data);
+
+ assert.include(instance.sessions.get("port123").perf, data);
+ });
+
+ it("should call setLoadTriggerInfo if data has visibility_event_rcvd_ts", () => {
+ sandbox.stub(instance, "setLoadTriggerInfo");
+ instance.addSession("port123");
+ const data = { visibility_event_rcvd_ts: 444455 };
+
+ instance.saveSessionPerfData("port123", data);
+
+ assert.calledOnce(instance.setLoadTriggerInfo);
+ assert.calledWithExactly(instance.setLoadTriggerInfo, "port123");
+ assert.include(instance.sessions.get("port123").perf, data);
+ });
+
+ it("shouldn't call setLoadTriggerInfo if data has no visibility_event_rcvd_ts", () => {
+ sandbox.stub(instance, "setLoadTriggerInfo");
+ instance.addSession("port123");
+
+ instance.saveSessionPerfData("port123", { monkeys_ts: 444455 });
+
+ assert.notCalled(instance.setLoadTriggerInfo);
+ });
+
+ it("should not call setLoadTriggerInfo when url is about:home", () => {
+ sandbox.stub(instance, "setLoadTriggerInfo");
+ instance.addSession("port123", "about:home");
+ const data = { visibility_event_rcvd_ts: 444455 };
+
+ instance.saveSessionPerfData("port123", data);
+
+ assert.notCalled(instance.setLoadTriggerInfo);
+ });
+
+ it("should call maybeRecordTopsitesPainted when url is about:home and topsites_first_painted_ts is given", () => {
+ const topsites_first_painted_ts = 44455;
+ const data = { topsites_first_painted_ts };
+ const spy = sandbox.spy();
+
+ sandbox.stub(Services.prefs, "getIntPref").returns(1);
+ globals.set("AboutNewTab", {
+ maybeRecordTopsitesPainted: spy,
+ });
+ instance.addSession("port123", "about:home");
+ instance.saveSessionPerfData("port123", data);
+
+ assert.calledOnce(spy);
+ assert.calledWith(spy, topsites_first_painted_ts);
+ });
+ });
+ describe("#uninit", () => {
+ it("should call .pingCentre.uninit", () => {
+ const stub = sandbox.stub(instance.pingCentre, "uninit");
+
+ instance.uninit();
+
+ assert.calledOnce(stub);
+ });
+ it("should call .utEvents.uninit", () => {
+ const stub = sandbox.stub(instance.utEvents, "uninit");
+
+ instance.uninit();
+
+ assert.calledOnce(stub);
+ });
+ it("should make this.browserOpenNewtabStart() stop observing browser-open-newtab-start and domwindowopened", async () => {
+ await instance.init();
+ sandbox.spy(Services.obs, "removeObserver");
+ sandbox.stub(instance.pingCentre, "uninit");
+
+ await instance.uninit();
+
+ assert.calledTwice(Services.obs.removeObserver);
+ assert.calledWithExactly(
+ Services.obs.removeObserver,
+ instance.browserOpenNewtabStart,
+ "browser-open-newtab-start"
+ );
+ assert.calledWithExactly(
+ Services.obs.removeObserver,
+ instance._addWindowListeners,
+ "domwindowopened"
+ );
+ });
+ });
+ describe("#onAction", () => {
+ beforeEach(() => {
+ FakePrefs.prototype.prefs = {};
+ });
+ it("should call .init() on an INIT action", () => {
+ const init = sandbox.stub(instance, "init");
+ const sendPageTakeoverData = sandbox.stub(
+ instance,
+ "sendPageTakeoverData"
+ );
+
+ instance.onAction({ type: at.INIT });
+
+ assert.calledOnce(init);
+ assert.calledOnce(sendPageTakeoverData);
+ });
+ it("should call .uninit() on an UNINIT action", () => {
+ const stub = sandbox.stub(instance, "uninit");
+
+ instance.onAction({ type: at.UNINIT });
+
+ assert.calledOnce(stub);
+ });
+ it("should call .handleNewTabInit on a NEW_TAB_INIT action", () => {
+ sandbox.spy(instance, "handleNewTabInit");
+
+ instance.onAction(
+ ac.AlsoToMain({
+ type: at.NEW_TAB_INIT,
+ data: { url: "about:newtab", browser },
+ })
+ );
+
+ assert.calledOnce(instance.handleNewTabInit);
+ });
+ it("should call .addSession() on a NEW_TAB_INIT action", () => {
+ const stub = sandbox.stub(instance, "addSession").returns({ perf: {} });
+ sandbox.stub(instance, "setLoadTriggerInfo");
+
+ instance.onAction(
+ ac.AlsoToMain(
+ {
+ type: at.NEW_TAB_INIT,
+ data: { url: "about:monkeys", browser },
+ },
+ "port123"
+ )
+ );
+
+ assert.calledOnce(stub);
+ assert.calledWith(stub, "port123", "about:monkeys");
+ });
+ it("should call .endSession() on a NEW_TAB_UNLOAD action", () => {
+ const stub = sandbox.stub(instance, "endSession");
+
+ instance.onAction(ac.AlsoToMain({ type: at.NEW_TAB_UNLOAD }, "port123"));
+
+ assert.calledWith(stub, "port123");
+ });
+ it("should call .saveSessionPerfData on SAVE_SESSION_PERF_DATA", () => {
+ const stub = sandbox.stub(instance, "saveSessionPerfData");
+ const data = { some_ts: 10 };
+ const action = { type: at.SAVE_SESSION_PERF_DATA, data };
+
+ instance.onAction(ac.AlsoToMain(action, "port123"));
+
+ assert.calledWith(stub, "port123", data);
+ });
+ it("should send an event on a TELEMETRY_USER_EVENT action", () => {
+ FakePrefs.prototype.prefs[TELEMETRY_PREF] = true;
+ FakePrefs.prototype.prefs[EVENTS_TELEMETRY_PREF] = true;
+ instance = new TelemetryFeed();
+
+ const sendEvent = sandbox.stub(instance, "sendEvent");
+ const utSendUserEvent = sandbox.stub(instance.utEvents, "sendUserEvent");
+ const eventCreator = sandbox.stub(instance, "createUserEvent");
+ const action = { type: at.TELEMETRY_USER_EVENT };
+
+ instance.onAction(action);
+
+ assert.calledWith(eventCreator, action);
+ assert.calledWith(sendEvent, eventCreator.returnValue);
+ assert.calledWith(utSendUserEvent, eventCreator.returnValue);
+ });
+ describe("should call handleASRouterUserEvent on x action", () => {
+ const actions = [
+ at.AS_ROUTER_TELEMETRY_USER_EVENT,
+ msg.TOOLBAR_BADGE_TELEMETRY,
+ msg.TOOLBAR_PANEL_TELEMETRY,
+ msg.MOMENTS_PAGE_TELEMETRY,
+ msg.DOORHANGER_TELEMETRY,
+ ];
+ actions.forEach(type => {
+ it(`${type} action`, () => {
+ FakePrefs.prototype.prefs[TELEMETRY_PREF] = true;
+ FakePrefs.prototype.prefs[EVENTS_TELEMETRY_PREF] = true;
+ instance = new TelemetryFeed();
+
+ const eventHandler = sandbox.spy(instance, "handleASRouterUserEvent");
+ const action = {
+ type,
+ data: { event: "CLICK" },
+ };
+
+ instance.onAction(action);
+
+ assert.calledWith(eventHandler, action);
+ });
+ });
+ });
+ it("should send an event on a TELEMETRY_IMPRESSION_STATS action", () => {
+ const sendEvent = sandbox.stub(instance, "sendStructuredIngestionEvent");
+ const eventCreator = sandbox.stub(instance, "createImpressionStats");
+ const tiles = [{ id: 10001 }, { id: 10002 }, { id: 10003 }];
+ const action = ac.ImpressionStats({ source: "POCKET", tiles });
+
+ instance.onAction(action);
+
+ assert.calledWith(
+ eventCreator,
+ au.getPortIdOfSender(action),
+ action.data
+ );
+ assert.calledWith(sendEvent, eventCreator.returnValue);
+ });
+ it("should call .handleDiscoveryStreamImpressionStats on a DISCOVERY_STREAM_IMPRESSION_STATS action", () => {
+ const session = {};
+ sandbox.stub(instance.sessions, "get").returns(session);
+ const data = { source: "foo", tiles: [{ id: 1 }] };
+ const action = { type: at.DISCOVERY_STREAM_IMPRESSION_STATS, data };
+ sandbox.spy(instance, "handleDiscoveryStreamImpressionStats");
+
+ instance.onAction(ac.AlsoToMain(action, "port123"));
+
+ assert.calledWith(
+ instance.handleDiscoveryStreamImpressionStats,
+ "port123",
+ data
+ );
+ });
+ it("should call .handleDiscoveryStreamLoadedContent on a DISCOVERY_STREAM_LOADED_CONTENT action", () => {
+ const session = {};
+ sandbox.stub(instance.sessions, "get").returns(session);
+ const data = { source: "foo", tiles: [{ id: 1 }] };
+ const action = { type: at.DISCOVERY_STREAM_LOADED_CONTENT, data };
+ sandbox.spy(instance, "handleDiscoveryStreamLoadedContent");
+
+ instance.onAction(ac.AlsoToMain(action, "port123"));
+
+ assert.calledWith(
+ instance.handleDiscoveryStreamLoadedContent,
+ "port123",
+ data
+ );
+ });
+ });
+ describe("#handleNewTabInit", () => {
+ it("should set the session as preloaded if the browser is preloaded", () => {
+ const session = { perf: {} };
+ let preloadedBrowser = {
+ getAttribute() {
+ return "preloaded";
+ },
+ };
+ sandbox.stub(instance, "addSession").returns(session);
+
+ instance.onAction(
+ ac.AlsoToMain({
+ type: at.NEW_TAB_INIT,
+ data: { url: "about:newtab", browser: preloadedBrowser },
+ })
+ );
+
+ assert.ok(session.perf.is_preloaded);
+ });
+ it("should set the session as non-preloaded if the browser is non-preloaded", () => {
+ const session = { perf: {} };
+ let nonPreloadedBrowser = {
+ getAttribute() {
+ return "";
+ },
+ };
+ sandbox.stub(instance, "addSession").returns(session);
+
+ instance.onAction(
+ ac.AlsoToMain({
+ type: at.NEW_TAB_INIT,
+ data: { url: "about:newtab", browser: nonPreloadedBrowser },
+ })
+ );
+
+ assert.ok(!session.perf.is_preloaded);
+ });
+ });
+ describe("#SendASRouterUndesiredEvent", () => {
+ it("should call handleASRouterUserEvent", () => {
+ let stub = sandbox.stub(instance, "handleASRouterUserEvent");
+
+ instance.SendASRouterUndesiredEvent({ foo: "bar" });
+
+ assert.calledOnce(stub);
+ let [payload] = stub.firstCall.args;
+ assert.propertyVal(payload.data, "action", "asrouter_undesired_event");
+ assert.propertyVal(payload.data, "foo", "bar");
+ });
+ });
+ describe("#sendPageTakeoverData", () => {
+ let fakePrefs = { "browser.newtabpage.enabled": true };
+
+ beforeEach(() => {
+ globals.set(
+ "Services",
+ Object.assign({}, Services, {
+ prefs: { getBoolPref: key => fakePrefs[key] },
+ })
+ );
+ // Services.prefs = {getBoolPref: key => fakePrefs[key]};
+ });
+ it("should send correct event data for about:home set to custom URL", async () => {
+ fakeHomePageUrl = "https://searchprovider.com";
+ instance._prefs.set(TELEMETRY_PREF, true);
+ instance._classifySite = () => Promise.resolve("other");
+ const sendEvent = sandbox.stub(instance, "sendEvent");
+
+ await instance.sendPageTakeoverData();
+ assert.calledOnce(sendEvent);
+ assert.equal(sendEvent.firstCall.args[0].event, "PAGE_TAKEOVER_DATA");
+ assert.deepEqual(sendEvent.firstCall.args[0].value, {
+ home_url_category: "other",
+ });
+ assert.validate(sendEvent.firstCall.args[0], UserEventPing);
+ });
+ it("should send correct event data for about:newtab set to custom URL", async () => {
+ globals.set("AboutNewTab", {
+ newTabURLOverridden: true,
+ newTabURL: "https://searchprovider.com",
+ });
+ instance._prefs.set(TELEMETRY_PREF, true);
+ instance._classifySite = () => Promise.resolve("other");
+ const sendEvent = sandbox.stub(instance, "sendEvent");
+
+ await instance.sendPageTakeoverData();
+ assert.calledOnce(sendEvent);
+ assert.equal(sendEvent.firstCall.args[0].event, "PAGE_TAKEOVER_DATA");
+ assert.deepEqual(sendEvent.firstCall.args[0].value, {
+ newtab_url_category: "other",
+ });
+ assert.validate(sendEvent.firstCall.args[0], UserEventPing);
+ });
+ it("should not send an event if neither about:{home,newtab} are set to custom URL", async () => {
+ instance._prefs.set(TELEMETRY_PREF, true);
+ const sendEvent = sandbox.stub(instance, "sendEvent");
+
+ await instance.sendPageTakeoverData();
+ assert.notCalled(sendEvent);
+ });
+ it("should send home_extension_id and newtab_extension_id when appropriate", async () => {
+ const ID = "{abc-foo-bar}";
+ fakeExtensionSettingsStore.getSetting = () => ({ id: ID });
+ instance._prefs.set(TELEMETRY_PREF, true);
+ instance._classifySite = () => Promise.resolve("other");
+ const sendEvent = sandbox.stub(instance, "sendEvent");
+
+ await instance.sendPageTakeoverData();
+ assert.calledOnce(sendEvent);
+ assert.equal(sendEvent.firstCall.args[0].event, "PAGE_TAKEOVER_DATA");
+ assert.deepEqual(sendEvent.firstCall.args[0].value, {
+ home_extension_id: ID,
+ newtab_extension_id: ID,
+ });
+ assert.validate(sendEvent.firstCall.args[0], UserEventPing);
+ });
+ });
+ describe("#sendDiscoveryStreamImpressions", () => {
+ it("should not send impression pings if there is no impression data", () => {
+ const spy = sandbox.spy(instance, "sendEvent");
+ const session = {};
+ instance.sendDiscoveryStreamImpressions("foo", session);
+
+ assert.notCalled(spy);
+ });
+ it("should send impression pings if there is impression data", () => {
+ const spy = sandbox.spy(instance, "sendStructuredIngestionEvent");
+ const session = {
+ impressionSets: {
+ source_foo: [
+ { id: 1, pos: 0 },
+ { id: 2, pos: 1 },
+ ],
+ source_bar: [
+ { id: 3, pos: 0 },
+ { id: 4, pos: 1 },
+ ],
+ },
+ };
+ instance.sendDiscoveryStreamImpressions("foo", session);
+
+ assert.calledTwice(spy);
+ });
+ });
+ describe("#sendDiscoveryStreamLoadedContent", () => {
+ it("should not send loaded content pings if there is no loaded content data", () => {
+ const spy = sandbox.spy(instance, "sendEvent");
+ const session = {};
+ instance.sendDiscoveryStreamLoadedContent("foo", session);
+
+ assert.notCalled(spy);
+ });
+ it("should send loaded content pings if there is loaded content data", () => {
+ const spy = sandbox.spy(instance, "sendStructuredIngestionEvent");
+ const session = {
+ loadedContentSets: {
+ source_foo: [
+ { id: 1, pos: 0 },
+ { id: 2, pos: 1 },
+ ],
+ source_bar: [
+ { id: 3, pos: 0 },
+ { id: 4, pos: 1 },
+ ],
+ },
+ };
+ instance.sendDiscoveryStreamLoadedContent("foo", session);
+
+ assert.calledTwice(spy);
+
+ let [payload] = spy.firstCall.args;
+ let sources = new Set([]);
+ sources.add(payload.source);
+ assert.equal(payload.loaded, 2);
+ assert.deepEqual(
+ payload.tiles,
+ session.loadedContentSets[payload.source]
+ );
+
+ [payload] = spy.secondCall.args;
+ sources.add(payload.source);
+ assert.equal(payload.loaded, 2);
+ assert.deepEqual(
+ payload.tiles,
+ session.loadedContentSets[payload.source]
+ );
+
+ assert.deepEqual(sources, new Set(["source_foo", "source_bar"]));
+ });
+ });
+ describe("#handleDiscoveryStreamImpressionStats", () => {
+ it("should throw for a missing session", () => {
+ assert.throws(() => {
+ instance.handleDiscoveryStreamImpressionStats("a_missing_port", {});
+ }, "Session does not exist.");
+ });
+ it("should store impression to impressionSets", () => {
+ const session = instance.addSession("new_session", "about:newtab");
+ instance.handleDiscoveryStreamImpressionStats("new_session", {
+ source: "foo",
+ tiles: [{ id: 1, pos: 0 }],
+ });
+
+ assert.equal(Object.keys(session.impressionSets).length, 1);
+ assert.deepEqual(session.impressionSets.foo, [{ id: 1, pos: 0 }]);
+
+ // Add another ping with the same source
+ instance.handleDiscoveryStreamImpressionStats("new_session", {
+ source: "foo",
+ tiles: [{ id: 2, pos: 1 }],
+ });
+
+ assert.deepEqual(session.impressionSets.foo, [
+ { id: 1, pos: 0 },
+ { id: 2, pos: 1 },
+ ]);
+
+ // Add another ping with a different source
+ instance.handleDiscoveryStreamImpressionStats("new_session", {
+ source: "bar",
+ tiles: [{ id: 3, pos: 2 }],
+ });
+
+ assert.equal(Object.keys(session.impressionSets).length, 2);
+ assert.deepEqual(session.impressionSets.foo, [
+ { id: 1, pos: 0 },
+ { id: 2, pos: 1 },
+ ]);
+ assert.deepEqual(session.impressionSets.bar, [{ id: 3, pos: 2 }]);
+ });
+ });
+ describe("#handleDiscoveryStreamLoadedContent", () => {
+ it("should throw for a missing session", () => {
+ assert.throws(() => {
+ instance.handleDiscoveryStreamLoadedContent("a_missing_port", {});
+ }, "Session does not exist.");
+ });
+ it("should store loaded content to loadedContentSets", () => {
+ const session = instance.addSession("new_session", "about:newtab");
+ instance.handleDiscoveryStreamLoadedContent("new_session", {
+ source: "foo",
+ tiles: [{ id: 1, pos: 0 }],
+ });
+
+ assert.equal(Object.keys(session.loadedContentSets).length, 1);
+ assert.deepEqual(session.loadedContentSets.foo, [{ id: 1, pos: 0 }]);
+
+ // Add another ping with the same source
+ instance.handleDiscoveryStreamLoadedContent("new_session", {
+ source: "foo",
+ tiles: [{ id: 2, pos: 1 }],
+ });
+
+ assert.deepEqual(session.loadedContentSets.foo, [
+ { id: 1, pos: 0 },
+ { id: 2, pos: 1 },
+ ]);
+
+ // Add another ping with a different source
+ instance.handleDiscoveryStreamLoadedContent("new_session", {
+ source: "bar",
+ tiles: [{ id: 3, pos: 2 }],
+ });
+
+ assert.equal(Object.keys(session.loadedContentSets).length, 2);
+ assert.deepEqual(session.loadedContentSets.foo, [
+ { id: 1, pos: 0 },
+ { id: 2, pos: 1 },
+ ]);
+ assert.deepEqual(session.loadedContentSets.bar, [{ id: 3, pos: 2 }]);
+ });
+ });
+ describe("#_generateStructuredIngestionEndpoint", () => {
+ it("should generate a valid endpoint", () => {
+ const fakeEndpoint = "http://fakeendpoint.com/base/";
+ const fakeUUID = "{34f24486-f01a-9749-9c5b-21476af1fa77}";
+ const fakeUUIDWithoutBraces = fakeUUID.substring(1, fakeUUID.length - 1);
+ FakePrefs.prototype.prefs = {};
+ FakePrefs.prototype.prefs[
+ STRUCTURED_INGESTION_ENDPOINT_PREF
+ ] = fakeEndpoint;
+ sandbox.stub(global.gUUIDGenerator, "generateUUID").returns(fakeUUID);
+ const feed = new TelemetryFeed();
+ const url = feed._generateStructuredIngestionEndpoint(
+ "testNameSpace",
+ "testPingType",
+ "1"
+ );
+
+ assert.equal(
+ url,
+ `${fakeEndpoint}/testNameSpace/testPingType/1/${fakeUUIDWithoutBraces}`
+ );
+ });
+ });
+ describe("#handleASRouterUserEvent", () => {
+ it("should call sendStructuredIngestionEvent on known pingTypes", async () => {
+ const data = {
+ action: "onboarding_user_event",
+ event: "IMPRESSION",
+ message_id: "12345",
+ };
+ instance = new TelemetryFeed();
+ sandbox.spy(instance, "sendStructuredIngestionEvent");
+
+ await instance.handleASRouterUserEvent({ data });
+
+ assert.calledOnce(instance.sendStructuredIngestionEvent);
+ });
+ it("should reportError on unknown pingTypes", async () => {
+ const data = {
+ action: "unknown_event",
+ event: "IMPRESSION",
+ message_id: "12345",
+ };
+ instance = new TelemetryFeed();
+ sandbox.spy(instance, "sendStructuredIngestionEvent");
+
+ await instance.handleASRouterUserEvent({ data });
+
+ assert.calledOnce(global.Cu.reportError);
+ assert.notCalled(instance.sendStructuredIngestionEvent);
+ });
+ });
+ describe("#isInCFRCohort", () => {
+ it("should return false if there is no CFR experiment registered", () => {
+ assert.ok(!instance.isInCFRCohort);
+ });
+ it("should return false if getExperimentMetaData throws", () => {
+ sandbox.stub(ExperimentAPI, "getExperimentMetaData").throws();
+
+ assert.ok(!instance.isInCFRCohort);
+ });
+ it("should return true if there is a CFR experiment registered", () => {
+ sandbox.stub(ExperimentAPI, "getExperimentMetaData").returns({
+ slug: "SOME-CFR-EXP",
+ });
+
+ assert.ok(instance.isInCFRCohort);
+ assert.propertyVal(
+ ExperimentAPI.getExperimentMetaData.firstCall.args[0],
+ "featureId",
+ "cfr"
+ );
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/lib/TippyTopProvider.test.js b/browser/components/newtab/test/unit/lib/TippyTopProvider.test.js
new file mode 100644
index 0000000000..5e6f82b2e0
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/TippyTopProvider.test.js
@@ -0,0 +1,121 @@
+import { GlobalOverrider } from "test/unit/utils";
+import { TippyTopProvider } from "lib/TippyTopProvider.jsm";
+
+describe("TippyTopProvider", () => {
+ let instance;
+ let globals;
+ beforeEach(async () => {
+ globals = new GlobalOverrider();
+ let fetchStub = globals.sandbox.stub();
+ globals.set("fetch", fetchStub);
+ fetchStub.resolves({
+ ok: true,
+ status: 200,
+ json: () =>
+ Promise.resolve([
+ {
+ domains: ["facebook.com"],
+ image_url: "images/facebook-com.png",
+ favicon_url: "images/facebook-com.png",
+ background_color: "#3b5998",
+ },
+ {
+ domains: ["gmail.com", "mail.google.com"],
+ image_url: "images/gmail-com.png",
+ favicon_url: "images/gmail-com.png",
+ background_color: "#000000",
+ },
+ ]),
+ });
+ instance = new TippyTopProvider();
+ await instance.init();
+ });
+ it("should provide an icon for facebook.com", () => {
+ const site = instance.processSite({ url: "https://facebook.com" });
+ assert.equal(
+ site.tippyTopIcon,
+ "chrome://activity-stream/content/data/content/tippytop/images/facebook-com.png"
+ );
+ assert.equal(
+ site.smallFavicon,
+ "chrome://activity-stream/content/data/content/tippytop/images/facebook-com.png"
+ );
+ assert.equal(site.backgroundColor, "#3b5998");
+ });
+ it("should provide an icon for www.facebook.com", () => {
+ const site = instance.processSite({ url: "https://www.facebook.com" });
+ assert.equal(
+ site.tippyTopIcon,
+ "chrome://activity-stream/content/data/content/tippytop/images/facebook-com.png"
+ );
+ assert.equal(
+ site.smallFavicon,
+ "chrome://activity-stream/content/data/content/tippytop/images/facebook-com.png"
+ );
+ assert.equal(site.backgroundColor, "#3b5998");
+ });
+ it("should not provide an icon for other.facebook.com", () => {
+ const site = instance.processSite({ url: "https://other.facebook.com" });
+ assert.isUndefined(site.tippyTopIcon);
+ });
+ it("should provide an icon for other.facebook.com with stripping", () => {
+ const site = instance.processSite(
+ { url: "https://other.facebook.com" },
+ "*"
+ );
+ assert.equal(
+ site.tippyTopIcon,
+ "chrome://activity-stream/content/data/content/tippytop/images/facebook-com.png"
+ );
+ });
+ it("should provide an icon for facebook.com/foobar", () => {
+ const site = instance.processSite({ url: "https://facebook.com/foobar" });
+ assert.equal(
+ site.tippyTopIcon,
+ "chrome://activity-stream/content/data/content/tippytop/images/facebook-com.png"
+ );
+ assert.equal(
+ site.smallFavicon,
+ "chrome://activity-stream/content/data/content/tippytop/images/facebook-com.png"
+ );
+ assert.equal(site.backgroundColor, "#3b5998");
+ });
+ it("should provide an icon for gmail.com", () => {
+ const site = instance.processSite({ url: "https://gmail.com" });
+ assert.equal(
+ site.tippyTopIcon,
+ "chrome://activity-stream/content/data/content/tippytop/images/gmail-com.png"
+ );
+ assert.equal(
+ site.smallFavicon,
+ "chrome://activity-stream/content/data/content/tippytop/images/gmail-com.png"
+ );
+ assert.equal(site.backgroundColor, "#000000");
+ });
+ it("should provide an icon for mail.google.com", () => {
+ const site = instance.processSite({ url: "https://mail.google.com" });
+ assert.equal(
+ site.tippyTopIcon,
+ "chrome://activity-stream/content/data/content/tippytop/images/gmail-com.png"
+ );
+ assert.equal(
+ site.smallFavicon,
+ "chrome://activity-stream/content/data/content/tippytop/images/gmail-com.png"
+ );
+ assert.equal(site.backgroundColor, "#000000");
+ });
+ it("should handle garbage URLs gracefully", () => {
+ const site = instance.processSite({ url: "garbagejlfkdsa" });
+ assert.isUndefined(site.tippyTopIcon);
+ assert.isUndefined(site.backgroundColor);
+ });
+ it("should handle error when fetching and parsing manifest", async () => {
+ globals = new GlobalOverrider();
+ let fetchStub = globals.sandbox.stub();
+ globals.set("fetch", fetchStub);
+ fetchStub.rejects("whaaaa");
+ instance = new TippyTopProvider();
+ await instance.init();
+ instance.processSite({ url: "https://facebook.com" });
+ });
+});
diff --git a/browser/components/newtab/test/unit/lib/ToolbarBadgeHub.test.js b/browser/components/newtab/test/unit/lib/ToolbarBadgeHub.test.js
new file mode 100644
index 0000000000..4ecac857ea
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/ToolbarBadgeHub.test.js
@@ -0,0 +1,651 @@
+import { _ToolbarBadgeHub } from "lib/ToolbarBadgeHub.jsm";
+import { GlobalOverrider } from "test/unit/utils";
+import { OnboardingMessageProvider } from "lib/OnboardingMessageProvider.jsm";
+import { _ToolbarPanelHub, ToolbarPanelHub } from "lib/ToolbarPanelHub.jsm";
+
+describe("ToolbarBadgeHub", () => {
+ let sandbox;
+ let instance;
+ let fakeAddImpression;
+ let fakeSendTelemetry;
+ let isBrowserPrivateStub;
+ let fxaMessage;
+ let whatsnewMessage;
+ let fakeElement;
+ let globals;
+ let everyWindowStub;
+ let clearTimeoutStub;
+ let setTimeoutStub;
+ let addObserverStub;
+ let removeObserverStub;
+ let getStringPrefStub;
+ let clearUserPrefStub;
+ let setStringPrefStub;
+ let requestIdleCallbackStub;
+ let fakeWindow;
+ beforeEach(async () => {
+ globals = new GlobalOverrider();
+ sandbox = sinon.createSandbox();
+ instance = new _ToolbarBadgeHub();
+ fakeAddImpression = sandbox.stub();
+ fakeSendTelemetry = sandbox.stub();
+ isBrowserPrivateStub = sandbox.stub();
+ const onboardingMsgs = await OnboardingMessageProvider.getUntranslatedMessages();
+ fxaMessage = onboardingMsgs.find(({ id }) => id === "FXA_ACCOUNTS_BADGE");
+ whatsnewMessage = {
+ id: `WHATS_NEW_BADGE_71`,
+ template: "toolbar_badge",
+ content: {
+ delay: 1000,
+ target: "whats-new-menu-button",
+ action: { id: "show-whatsnew-button" },
+ badgeDescription: { string_id: "cfr-badge-reader-label-newfeature" },
+ },
+ priority: 1,
+ trigger: { id: "toolbarBadgeUpdate" },
+ frequency: {
+ // Makes it so that we track impressions for this message while at the
+ // same time it can have unlimited impressions
+ lifetime: Infinity,
+ },
+ // Never saw this message or saw it in the past 4 days or more recent
+ targeting: `isWhatsNewPanelEnabled &&
+ (!messageImpressions['WHATS_NEW_BADGE_71'] ||
+ (messageImpressions['WHATS_NEW_BADGE_71']|length >= 1 &&
+ currentDate|date - messageImpressions['WHATS_NEW_BADGE_71'][0] <= 4 * 24 * 3600 * 1000))`,
+ };
+ fakeElement = {
+ classList: {
+ add: sandbox.stub(),
+ remove: sandbox.stub(),
+ },
+ setAttribute: sandbox.stub(),
+ removeAttribute: sandbox.stub(),
+ querySelector: sandbox.stub(),
+ addEventListener: sandbox.stub(),
+ remove: sandbox.stub(),
+ appendChild: sandbox.stub(),
+ };
+ // Share the same element when selecting child nodes
+ fakeElement.querySelector.returns(fakeElement);
+ everyWindowStub = {
+ registerCallback: sandbox.stub(),
+ unregisterCallback: sandbox.stub(),
+ };
+ clearTimeoutStub = sandbox.stub();
+ setTimeoutStub = sandbox.stub();
+ fakeWindow = {
+ MozXULElement: { insertFTLIfNeeded: sandbox.stub() },
+ ownerGlobal: {
+ gBrowser: {
+ selectedBrowser: "browser",
+ },
+ },
+ };
+ addObserverStub = sandbox.stub();
+ removeObserverStub = sandbox.stub();
+ getStringPrefStub = sandbox.stub();
+ clearUserPrefStub = sandbox.stub();
+ setStringPrefStub = sandbox.stub();
+ requestIdleCallbackStub = sandbox.stub().callsFake(fn => fn());
+ globals.set({
+ ToolbarPanelHub,
+ requestIdleCallback: requestIdleCallbackStub,
+ EveryWindow: everyWindowStub,
+ PrivateBrowsingUtils: { isBrowserPrivate: isBrowserPrivateStub },
+ setTimeout: setTimeoutStub,
+ clearTimeout: clearTimeoutStub,
+ Services: {
+ wm: {
+ getMostRecentWindow: () => fakeWindow,
+ },
+ prefs: {
+ addObserver: addObserverStub,
+ removeObserver: removeObserverStub,
+ getStringPref: getStringPrefStub,
+ clearUserPref: clearUserPrefStub,
+ setStringPref: setStringPrefStub,
+ },
+ },
+ });
+ });
+ afterEach(() => {
+ sandbox.restore();
+ globals.restore();
+ });
+ it("should create an instance", () => {
+ assert.ok(instance);
+ });
+ describe("#init", () => {
+ it("should make a single messageRequest on init", async () => {
+ sandbox.stub(instance, "messageRequest");
+ const waitForInitialized = sandbox.stub().resolves();
+
+ await instance.init(waitForInitialized, {});
+ await instance.init(waitForInitialized, {});
+ assert.calledOnce(instance.messageRequest);
+ assert.calledWithExactly(instance.messageRequest, {
+ template: "toolbar_badge",
+ triggerId: "toolbarBadgeUpdate",
+ });
+
+ instance.uninit();
+
+ await instance.init(waitForInitialized, {});
+
+ assert.calledTwice(instance.messageRequest);
+ });
+ it("should add a pref observer", async () => {
+ await instance.init(sandbox.stub().resolves(), {});
+
+ assert.calledOnce(addObserverStub);
+ assert.calledWithExactly(
+ addObserverStub,
+ instance.prefs.WHATSNEW_TOOLBAR_PANEL,
+ instance
+ );
+ });
+ });
+ describe("#uninit", () => {
+ beforeEach(async () => {
+ await instance.init(sandbox.stub().resolves(), {});
+ });
+ it("should clear any setTimeout cbs", async () => {
+ await instance.init(sandbox.stub().resolves(), {});
+
+ instance.state.showBadgeTimeoutId = 2;
+
+ instance.uninit();
+
+ assert.calledOnce(clearTimeoutStub);
+ assert.calledWithExactly(clearTimeoutStub, 2);
+ });
+ it("should remove the pref observer", () => {
+ instance.uninit();
+
+ assert.calledOnce(removeObserverStub);
+ assert.calledWithExactly(
+ removeObserverStub,
+ instance.prefs.WHATSNEW_TOOLBAR_PANEL,
+ instance
+ );
+ });
+ });
+ describe("messageRequest", () => {
+ let handleMessageRequestStub;
+ beforeEach(() => {
+ handleMessageRequestStub = sandbox.stub().returns(fxaMessage);
+ sandbox
+ .stub(instance, "_handleMessageRequest")
+ .value(handleMessageRequestStub);
+ sandbox.stub(instance, "registerBadgeNotificationListener");
+ });
+ it("should fetch a message with the provided trigger and template", async () => {
+ await instance.messageRequest({
+ triggerId: "trigger",
+ template: "template",
+ });
+
+ assert.calledOnce(handleMessageRequestStub);
+ assert.calledWithExactly(handleMessageRequestStub, {
+ triggerId: "trigger",
+ template: "template",
+ });
+ });
+ it("should call addToolbarNotification with browser window and message", async () => {
+ await instance.messageRequest("trigger");
+
+ assert.calledOnce(instance.registerBadgeNotificationListener);
+ assert.calledWithExactly(
+ instance.registerBadgeNotificationListener,
+ fxaMessage
+ );
+ });
+ it("shouldn't do anything if no message is provided", async () => {
+ handleMessageRequestStub.resolves(null);
+ await instance.messageRequest({ triggerId: "trigger" });
+
+ assert.notCalled(instance.registerBadgeNotificationListener);
+ });
+ it("should record telemetry events", async () => {
+ const startTelemetryStopwatch = sandbox.stub(
+ global.TelemetryStopwatch,
+ "start"
+ );
+ const finishTelemetryStopwatch = sandbox.stub(
+ global.TelemetryStopwatch,
+ "finish"
+ );
+ handleMessageRequestStub.returns(null);
+
+ await instance.messageRequest({ triggerId: "trigger" });
+
+ assert.calledOnce(startTelemetryStopwatch);
+ assert.calledWithExactly(
+ startTelemetryStopwatch,
+ "MS_MESSAGE_REQUEST_TIME_MS",
+ { triggerId: "trigger" }
+ );
+ assert.calledOnce(finishTelemetryStopwatch);
+ assert.calledWithExactly(
+ finishTelemetryStopwatch,
+ "MS_MESSAGE_REQUEST_TIME_MS",
+ { triggerId: "trigger" }
+ );
+ });
+ });
+ describe("addToolbarNotification", () => {
+ let target;
+ let fakeDocument;
+ beforeEach(async () => {
+ await instance.init(sandbox.stub().resolves(), {
+ addImpression: fakeAddImpression,
+ sendTelemetry: fakeSendTelemetry,
+ });
+ fakeDocument = {
+ getElementById: sandbox.stub().returns(fakeElement),
+ createElement: sandbox.stub().returns(fakeElement),
+ l10n: { setAttributes: sandbox.stub() },
+ };
+ target = { ...fakeWindow, browser: { ownerDocument: fakeDocument } };
+ });
+ afterEach(() => {
+ instance.uninit();
+ });
+ it("shouldn't do anything if target element is not found", () => {
+ fakeDocument.getElementById.returns(null);
+ instance.addToolbarNotification(target, fxaMessage);
+
+ assert.notCalled(fakeElement.setAttribute);
+ });
+ it("should target the element specified in the message", () => {
+ instance.addToolbarNotification(target, fxaMessage);
+
+ assert.calledOnce(fakeDocument.getElementById);
+ assert.calledWithExactly(
+ fakeDocument.getElementById,
+ fxaMessage.content.target
+ );
+ });
+ it("should show a notification", () => {
+ instance.addToolbarNotification(target, fxaMessage);
+
+ assert.calledOnce(fakeElement.setAttribute);
+ assert.calledWithExactly(fakeElement.setAttribute, "badged", true);
+ assert.calledWithExactly(fakeElement.classList.add, "feature-callout");
+ });
+ it("should attach a cb on the notification", () => {
+ instance.addToolbarNotification(target, fxaMessage);
+
+ assert.calledTwice(fakeElement.addEventListener);
+ assert.calledWithExactly(
+ fakeElement.addEventListener,
+ "mousedown",
+ instance.removeAllNotifications
+ );
+ assert.calledWithExactly(
+ fakeElement.addEventListener,
+ "keypress",
+ instance.removeAllNotifications
+ );
+ });
+ it("should execute actions if they exist", () => {
+ sandbox.stub(instance, "executeAction");
+ instance.addToolbarNotification(target, whatsnewMessage);
+
+ assert.calledOnce(instance.executeAction);
+ assert.calledWithExactly(instance.executeAction, {
+ ...whatsnewMessage.content.action,
+ message_id: whatsnewMessage.id,
+ });
+ });
+ it("should create a description element", () => {
+ sandbox.stub(instance, "executeAction");
+ instance.addToolbarNotification(target, whatsnewMessage);
+
+ assert.calledOnce(fakeDocument.createElement);
+ assert.calledWithExactly(fakeDocument.createElement, "span");
+ });
+ it("should set description id to element and to button", () => {
+ sandbox.stub(instance, "executeAction");
+ instance.addToolbarNotification(target, whatsnewMessage);
+
+ assert.calledWithExactly(
+ fakeElement.setAttribute,
+ "id",
+ "toolbarbutton-notification-description"
+ );
+ assert.calledWithExactly(
+ fakeElement.setAttribute,
+ "aria-labelledby",
+ `toolbarbutton-notification-description ${whatsnewMessage.content.target}`
+ );
+ });
+ it("should attach fluent id to description", () => {
+ sandbox.stub(instance, "executeAction");
+ instance.addToolbarNotification(target, whatsnewMessage);
+
+ assert.calledOnce(fakeDocument.l10n.setAttributes);
+ assert.calledWithExactly(
+ fakeDocument.l10n.setAttributes,
+ fakeElement,
+ whatsnewMessage.content.badgeDescription.string_id
+ );
+ });
+ it("should add an impression for the message", () => {
+ instance.addToolbarNotification(target, whatsnewMessage);
+
+ assert.calledOnce(instance._addImpression);
+ assert.calledWithExactly(instance._addImpression, whatsnewMessage);
+ });
+ it("should send an impression ping", async () => {
+ sandbox.stub(instance, "sendUserEventTelemetry");
+ instance.addToolbarNotification(target, whatsnewMessage);
+
+ assert.calledOnce(instance.sendUserEventTelemetry);
+ assert.calledWithExactly(
+ instance.sendUserEventTelemetry,
+ "IMPRESSION",
+ whatsnewMessage
+ );
+ });
+ });
+ describe("registerBadgeNotificationListener", () => {
+ let msg_no_delay;
+ beforeEach(async () => {
+ await instance.init(sandbox.stub().resolves(), {
+ addImpression: fakeAddImpression,
+ sendTelemetry: fakeSendTelemetry,
+ });
+ sandbox.stub(instance, "addToolbarNotification").returns(fakeElement);
+ sandbox.stub(instance, "removeToolbarNotification");
+ msg_no_delay = {
+ ...fxaMessage,
+ content: {
+ ...fxaMessage.content,
+ delay: 0,
+ },
+ };
+ });
+ afterEach(() => {
+ instance.uninit();
+ });
+ it("should register a callback that adds/removes the notification", () => {
+ instance.registerBadgeNotificationListener(msg_no_delay);
+
+ assert.calledOnce(everyWindowStub.registerCallback);
+ assert.calledWithExactly(
+ everyWindowStub.registerCallback,
+ instance.id,
+ sinon.match.func,
+ sinon.match.func
+ );
+
+ const [
+ ,
+ initFn,
+ uninitFn,
+ ] = everyWindowStub.registerCallback.firstCall.args;
+
+ initFn(window);
+ // Test that it doesn't try to add a second notification
+ initFn(window);
+
+ assert.calledOnce(instance.addToolbarNotification);
+ assert.calledWithExactly(
+ instance.addToolbarNotification,
+ window,
+ msg_no_delay
+ );
+
+ uninitFn(window);
+
+ assert.calledOnce(instance.removeToolbarNotification);
+ assert.calledWithExactly(instance.removeToolbarNotification, fakeElement);
+ });
+ it("should unregister notifications when forcing a badge via devtools", () => {
+ instance.registerBadgeNotificationListener(msg_no_delay, { force: true });
+
+ assert.calledOnce(everyWindowStub.unregisterCallback);
+ assert.calledWithExactly(everyWindowStub.unregisterCallback, instance.id);
+ });
+ it("should only call executeAction for 'update_action' messages", () => {
+ const stub = sandbox.stub(instance, "executeAction");
+ const updateActionMsg = { ...msg_no_delay, template: "update_action" };
+
+ instance.registerBadgeNotificationListener(updateActionMsg);
+
+ assert.notCalled(everyWindowStub.registerCallback);
+ assert.calledOnce(stub);
+ });
+ });
+ describe("executeAction", () => {
+ let blockMessageByIdStub;
+ beforeEach(async () => {
+ blockMessageByIdStub = sandbox.stub();
+ await instance.init(sandbox.stub().resolves(), {
+ blockMessageById: blockMessageByIdStub,
+ });
+ });
+ it("should call ToolbarPanelHub.enableToolbarButton", () => {
+ const stub = sandbox.stub(
+ _ToolbarPanelHub.prototype,
+ "enableToolbarButton"
+ );
+
+ instance.executeAction({ id: "show-whatsnew-button" });
+
+ assert.calledOnce(stub);
+ });
+ it("should call ToolbarPanelHub.enableAppmenuButton", () => {
+ const stub = sandbox.stub(
+ _ToolbarPanelHub.prototype,
+ "enableAppmenuButton"
+ );
+
+ instance.executeAction({ id: "show-whatsnew-button" });
+
+ assert.calledOnce(stub);
+ });
+ });
+ describe("removeToolbarNotification", () => {
+ it("should remove the notification", () => {
+ instance.removeToolbarNotification(fakeElement);
+
+ assert.calledThrice(fakeElement.removeAttribute);
+ assert.calledWithExactly(fakeElement.removeAttribute, "badged");
+ assert.calledWithExactly(fakeElement.removeAttribute, "aria-labelledby");
+ assert.calledWithExactly(fakeElement.removeAttribute, "aria-describedby");
+ assert.calledOnce(fakeElement.classList.remove);
+ assert.calledWithExactly(fakeElement.classList.remove, "feature-callout");
+ assert.calledOnce(fakeElement.remove);
+ });
+ });
+ describe("removeAllNotifications", () => {
+ let blockMessageByIdStub;
+ let fakeEvent;
+ beforeEach(async () => {
+ await instance.init(sandbox.stub().resolves(), {
+ sendTelemetry: fakeSendTelemetry,
+ });
+ blockMessageByIdStub = sandbox.stub();
+ sandbox.stub(instance, "_blockMessageById").value(blockMessageByIdStub);
+ instance.state = { notification: { id: fxaMessage.id } };
+ fakeEvent = { target: { removeEventListener: sandbox.stub() } };
+ });
+ it("should call to block the message", () => {
+ instance.removeAllNotifications();
+
+ assert.calledOnce(blockMessageByIdStub);
+ assert.calledWithExactly(blockMessageByIdStub, fxaMessage.id);
+ });
+ it("should remove the window listener", () => {
+ instance.removeAllNotifications();
+
+ assert.calledOnce(everyWindowStub.unregisterCallback);
+ assert.calledWithExactly(everyWindowStub.unregisterCallback, instance.id);
+ });
+ it("should ignore right mouse button (mousedown event)", () => {
+ fakeEvent.type = "mousedown";
+ fakeEvent.button = 1; // not left click
+
+ instance.removeAllNotifications(fakeEvent);
+
+ assert.notCalled(fakeEvent.target.removeEventListener);
+ assert.notCalled(everyWindowStub.unregisterCallback);
+ });
+ it("should ignore right mouse button (click event)", () => {
+ fakeEvent.type = "click";
+ fakeEvent.button = 1; // not left click
+
+ instance.removeAllNotifications(fakeEvent);
+
+ assert.notCalled(fakeEvent.target.removeEventListener);
+ assert.notCalled(everyWindowStub.unregisterCallback);
+ });
+ it("should ignore keypresses that are not meant to focus the target", () => {
+ fakeEvent.type = "keypress";
+ fakeEvent.key = "\t"; // not enter
+
+ instance.removeAllNotifications(fakeEvent);
+
+ assert.notCalled(fakeEvent.target.removeEventListener);
+ assert.notCalled(everyWindowStub.unregisterCallback);
+ });
+ it("should remove the event listeners after succesfully focusing the element", () => {
+ fakeEvent.type = "click";
+ fakeEvent.button = 0;
+
+ instance.removeAllNotifications(fakeEvent);
+
+ assert.calledTwice(fakeEvent.target.removeEventListener);
+ assert.calledWithExactly(
+ fakeEvent.target.removeEventListener,
+ "mousedown",
+ instance.removeAllNotifications
+ );
+ assert.calledWithExactly(
+ fakeEvent.target.removeEventListener,
+ "keypress",
+ instance.removeAllNotifications
+ );
+ });
+ it("should send telemetry", () => {
+ fakeEvent.type = "click";
+ fakeEvent.button = 0;
+ sandbox.stub(instance, "sendUserEventTelemetry");
+
+ instance.removeAllNotifications(fakeEvent);
+
+ assert.calledOnce(instance.sendUserEventTelemetry);
+ assert.calledWithExactly(instance.sendUserEventTelemetry, "CLICK", {
+ id: "FXA_ACCOUNTS_BADGE",
+ });
+ });
+ it("should remove the event listeners after succesfully focusing the element", () => {
+ fakeEvent.type = "keypress";
+ fakeEvent.key = "Enter";
+
+ instance.removeAllNotifications(fakeEvent);
+
+ assert.calledTwice(fakeEvent.target.removeEventListener);
+ assert.calledWithExactly(
+ fakeEvent.target.removeEventListener,
+ "mousedown",
+ instance.removeAllNotifications
+ );
+ assert.calledWithExactly(
+ fakeEvent.target.removeEventListener,
+ "keypress",
+ instance.removeAllNotifications
+ );
+ });
+ });
+ describe("message with delay", () => {
+ let msg_with_delay;
+ beforeEach(async () => {
+ await instance.init(sandbox.stub().resolves(), {
+ addImpression: fakeAddImpression,
+ });
+ msg_with_delay = {
+ ...fxaMessage,
+ content: {
+ ...fxaMessage.content,
+ delay: 500,
+ },
+ };
+ sandbox.stub(instance, "registerBadgeToAllWindows");
+ });
+ afterEach(() => {
+ instance.uninit();
+ });
+ it("should register a cb to fire after msg.content.delay ms", () => {
+ instance.registerBadgeNotificationListener(msg_with_delay);
+
+ assert.calledOnce(setTimeoutStub);
+ assert.calledWithExactly(
+ setTimeoutStub,
+ sinon.match.func,
+ msg_with_delay.content.delay
+ );
+
+ const [cb] = setTimeoutStub.firstCall.args;
+
+ assert.notCalled(instance.registerBadgeToAllWindows);
+
+ cb();
+
+ assert.calledOnce(instance.registerBadgeToAllWindows);
+ assert.calledWithExactly(
+ instance.registerBadgeToAllWindows,
+ msg_with_delay
+ );
+ // Delayed actions should be executed inside requestIdleCallback
+ assert.calledOnce(requestIdleCallbackStub);
+ });
+ });
+ describe("#sendUserEventTelemetry", () => {
+ beforeEach(async () => {
+ await instance.init(sandbox.stub().resolves(), {
+ sendTelemetry: fakeSendTelemetry,
+ });
+ });
+ it("should check for private window and not send", () => {
+ isBrowserPrivateStub.returns(true);
+
+ instance.sendUserEventTelemetry("CLICK", { id: fxaMessage });
+
+ assert.notCalled(instance._sendTelemetry);
+ });
+ it("should check for private window and send", () => {
+ isBrowserPrivateStub.returns(false);
+
+ instance.sendUserEventTelemetry("CLICK", { id: fxaMessage });
+
+ assert.calledOnce(fakeSendTelemetry);
+ const [ping] = instance._sendTelemetry.firstCall.args;
+ assert.propertyVal(ping, "type", "TOOLBAR_BADGE_TELEMETRY");
+ assert.propertyVal(ping.data, "event", "CLICK");
+ });
+ });
+ describe("#observe", () => {
+ it("should make a message request when the whats new pref is changed", () => {
+ sandbox.stub(instance, "messageRequest");
+
+ instance.observe("", "", instance.prefs.WHATSNEW_TOOLBAR_PANEL);
+
+ assert.calledOnce(instance.messageRequest);
+ assert.calledWithExactly(instance.messageRequest, {
+ template: "toolbar_badge",
+ triggerId: "toolbarBadgeUpdate",
+ });
+ });
+ it("should not react to other pref changes", () => {
+ sandbox.stub(instance, "messageRequest");
+
+ instance.observe("", "", "foo");
+
+ assert.notCalled(instance.messageRequest);
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/lib/ToolbarPanelHub.test.js b/browser/components/newtab/test/unit/lib/ToolbarPanelHub.test.js
new file mode 100644
index 0000000000..b614716efa
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/ToolbarPanelHub.test.js
@@ -0,0 +1,927 @@
+import { _ToolbarPanelHub } from "lib/ToolbarPanelHub.jsm";
+import { GlobalOverrider } from "test/unit/utils";
+import { OnboardingMessageProvider } from "lib/OnboardingMessageProvider.jsm";
+import { PanelTestProvider } from "lib/PanelTestProvider.jsm";
+
+describe("ToolbarPanelHub", () => {
+ let globals;
+ let sandbox;
+ let instance;
+ let everyWindowStub;
+ let preferencesStub;
+ let fakeDocument;
+ let fakeWindow;
+ let fakeElementById;
+ let fakeElementByTagName;
+ let createdCustomElements = [];
+ let eventListeners = {};
+ let addObserverStub;
+ let removeObserverStub;
+ let getBoolPrefStub;
+ let setBoolPrefStub;
+ let waitForInitializedStub;
+ let isBrowserPrivateStub;
+ let fakeSendTelemetry;
+ let getEarliestRecordedDateStub;
+ let getEventsByDateRangeStub;
+ let defaultSearchStub;
+ let scriptloaderStub;
+ let fakeRemoteL10n;
+ let getViewNodeStub;
+
+ beforeEach(async () => {
+ sandbox = sinon.createSandbox();
+ globals = new GlobalOverrider();
+ instance = new _ToolbarPanelHub();
+ waitForInitializedStub = sandbox.stub().resolves();
+ fakeElementById = {
+ setAttribute: sandbox.stub(),
+ removeAttribute: sandbox.stub(),
+ querySelector: sandbox.stub().returns(null),
+ querySelectorAll: sandbox.stub().returns([]),
+ appendChild: sandbox.stub(),
+ addEventListener: sandbox.stub(),
+ hasAttribute: sandbox.stub(),
+ toggleAttribute: sandbox.stub(),
+ remove: sandbox.stub(),
+ removeChild: sandbox.stub(),
+ };
+ fakeElementByTagName = {
+ setAttribute: sandbox.stub(),
+ removeAttribute: sandbox.stub(),
+ querySelector: sandbox.stub().returns(null),
+ querySelectorAll: sandbox.stub().returns([]),
+ appendChild: sandbox.stub(),
+ addEventListener: sandbox.stub(),
+ hasAttribute: sandbox.stub(),
+ toggleAttribute: sandbox.stub(),
+ remove: sandbox.stub(),
+ removeChild: sandbox.stub(),
+ };
+ fakeDocument = {
+ getElementById: sandbox.stub().returns(fakeElementById),
+ getElementsByTagName: sandbox.stub().returns(fakeElementByTagName),
+ querySelector: sandbox.stub().returns({}),
+ createElement: tagName => {
+ const element = {
+ tagName,
+ classList: {},
+ addEventListener: (ev, fn) => {
+ eventListeners[ev] = fn;
+ },
+ appendChild: sandbox.stub(),
+ setAttribute: sandbox.stub(),
+ textContent: "",
+ };
+ element.classList.add = sandbox.stub();
+ element.classList.includes = className =>
+ element.classList.add.firstCall.args[0] === className;
+ createdCustomElements.push(element);
+ return element;
+ },
+ l10n: {
+ translateElements: sandbox.stub(),
+ translateFragment: sandbox.stub(),
+ formatMessages: sandbox.stub().resolves([{}]),
+ setAttributes: sandbox.stub(),
+ },
+ };
+ fakeWindow = {
+ // eslint-disable-next-line object-shorthand
+ DocumentFragment: function() {
+ return fakeElementById;
+ },
+ document: fakeDocument,
+ browser: {
+ ownerDocument: fakeDocument,
+ },
+ MozXULElement: { insertFTLIfNeeded: sandbox.stub() },
+ ownerGlobal: {
+ openLinkIn: sandbox.stub(),
+ gBrowser: "gBrowser",
+ },
+ PanelUI: {
+ panel: fakeElementById,
+ whatsNewPanel: fakeElementById,
+ },
+ customElements: { get: sandbox.stub() },
+ };
+ everyWindowStub = {
+ registerCallback: sandbox.stub(),
+ unregisterCallback: sandbox.stub(),
+ };
+ preferencesStub = {
+ get: sandbox.stub(),
+ set: sandbox.stub(),
+ };
+ scriptloaderStub = { loadSubScript: sandbox.stub() };
+ addObserverStub = sandbox.stub();
+ removeObserverStub = sandbox.stub();
+ getBoolPrefStub = sandbox.stub();
+ setBoolPrefStub = sandbox.stub();
+ fakeSendTelemetry = sandbox.stub();
+ isBrowserPrivateStub = sandbox.stub();
+ getEarliestRecordedDateStub = sandbox.stub().returns(
+ // A random date that's not the current timestamp
+ new Date() - 500
+ );
+ getEventsByDateRangeStub = sandbox.stub().returns([]);
+ getViewNodeStub = sandbox.stub().returns(fakeElementById);
+ defaultSearchStub = { defaultEngine: { name: "DDG" } };
+ fakeRemoteL10n = {
+ l10n: {},
+ reloadL10n: sandbox.stub(),
+ createElement: sandbox
+ .stub()
+ .callsFake((doc, el) => fakeDocument.createElement(el)),
+ };
+ globals.set({
+ EveryWindow: everyWindowStub,
+ Services: {
+ ...Services,
+ prefs: {
+ addObserver: addObserverStub,
+ removeObserver: removeObserverStub,
+ getBoolPref: getBoolPrefStub,
+ setBoolPref: setBoolPrefStub,
+ },
+ search: defaultSearchStub,
+ scriptloader: scriptloaderStub,
+ },
+ PrivateBrowsingUtils: {
+ isBrowserPrivate: isBrowserPrivateStub,
+ },
+ Preferences: preferencesStub,
+ TrackingDBService: {
+ getEarliestRecordedDate: getEarliestRecordedDateStub,
+ getEventsByDateRange: getEventsByDateRangeStub,
+ },
+ SpecialMessageActions: {
+ handleAction: sandbox.stub(),
+ },
+ RemoteL10n: fakeRemoteL10n,
+ PanelMultiView: {
+ getViewNode: getViewNodeStub,
+ },
+ });
+ });
+ afterEach(() => {
+ instance.uninit();
+ sandbox.restore();
+ globals.restore();
+ eventListeners = {};
+ createdCustomElements = [];
+ });
+ it("should create an instance", () => {
+ assert.ok(instance);
+ });
+ it("should enableAppmenuButton() on init() just once", async () => {
+ instance.enableAppmenuButton = sandbox.stub();
+
+ await instance.init(waitForInitializedStub, { getMessages: () => {} });
+ await instance.init(waitForInitializedStub, { getMessages: () => {} });
+
+ assert.calledOnce(instance.enableAppmenuButton);
+
+ instance.uninit();
+
+ await instance.init(waitForInitializedStub, { getMessages: () => {} });
+
+ assert.calledTwice(instance.enableAppmenuButton);
+ });
+ it("should unregisterCallback on uninit()", () => {
+ instance.uninit();
+ assert.calledTwice(everyWindowStub.unregisterCallback);
+ });
+ describe("#maybeLoadCustomElement", () => {
+ it("should not load customElements a second time", () => {
+ instance.maybeLoadCustomElement({ customElements: new Map() });
+ instance.maybeLoadCustomElement({
+ customElements: new Map([["remote-text", true]]),
+ });
+
+ assert.calledOnce(scriptloaderStub.loadSubScript);
+ });
+ });
+ describe("#toggleWhatsNewPref", () => {
+ it("should call Preferences.set() with the opposite value", () => {
+ let checkbox = {};
+ let event = { target: checkbox };
+ // checkbox starts false
+ checkbox.checked = false;
+
+ // toggling the checkbox to set the value to true;
+ // Preferences.set() gets called before the checkbox changes,
+ // so we have to call it with the opposite value.
+ instance.toggleWhatsNewPref(event);
+
+ assert.calledOnce(preferencesStub.set);
+ assert.calledWith(
+ preferencesStub.set,
+ "browser.messaging-system.whatsNewPanel.enabled",
+ !checkbox.checked
+ );
+ });
+ it("should report telemetry with the opposite value", () => {
+ let sendUserEventTelemetryStub = sandbox.stub(
+ instance,
+ "sendUserEventTelemetry"
+ );
+ let event = {
+ target: { checked: true, ownerGlobal: fakeWindow },
+ };
+
+ instance.toggleWhatsNewPref(event);
+
+ assert.calledOnce(sendUserEventTelemetryStub);
+ const { args } = sendUserEventTelemetryStub.firstCall;
+ assert.equal(args[1], "WNP_PREF_TOGGLE");
+ assert.propertyVal(args[3].value, "prefValue", false);
+ });
+ });
+ describe("#enableAppmenuButton", () => {
+ it("should registerCallback on enableAppmenuButton() if there are messages", async () => {
+ await instance.init(waitForInitializedStub, {
+ getMessages: sandbox.stub().resolves([{}, {}]),
+ });
+ // init calls `enableAppmenuButton`
+ everyWindowStub.registerCallback.resetHistory();
+
+ await instance.enableAppmenuButton();
+
+ assert.calledOnce(everyWindowStub.registerCallback);
+ assert.calledWithExactly(
+ everyWindowStub.registerCallback,
+ "appMenu-whatsnew-button",
+ sinon.match.func,
+ sinon.match.func
+ );
+ });
+ it("should not registerCallback on enableAppmenuButton() if there are no messages", async () => {
+ instance.init(waitForInitializedStub, {
+ getMessages: sandbox.stub().resolves([]),
+ });
+ // init calls `enableAppmenuButton`
+ everyWindowStub.registerCallback.resetHistory();
+
+ await instance.enableAppmenuButton();
+
+ assert.notCalled(everyWindowStub.registerCallback);
+ });
+ });
+ describe("#disableAppmenuButton", () => {
+ it("should call the unregisterCallback", () => {
+ assert.notCalled(everyWindowStub.unregisterCallback);
+
+ instance.disableAppmenuButton();
+
+ assert.calledOnce(everyWindowStub.unregisterCallback);
+ assert.calledWithExactly(
+ everyWindowStub.unregisterCallback,
+ "appMenu-whatsnew-button"
+ );
+ });
+ });
+ describe("#enableToolbarButton", () => {
+ it("should registerCallback on enableToolbarButton if messages.length", async () => {
+ await instance.init(waitForInitializedStub, {
+ getMessages: sandbox.stub().resolves([{}, {}]),
+ });
+ // init calls `enableAppmenuButton`
+ everyWindowStub.registerCallback.resetHistory();
+
+ await instance.enableToolbarButton();
+
+ assert.calledOnce(everyWindowStub.registerCallback);
+ assert.calledWithExactly(
+ everyWindowStub.registerCallback,
+ "whats-new-menu-button",
+ sinon.match.func,
+ sinon.match.func
+ );
+ });
+ it("should not registerCallback on enableToolbarButton if no messages", async () => {
+ await instance.init(waitForInitializedStub, {
+ getMessages: sandbox.stub().resolves([]),
+ });
+
+ await instance.enableToolbarButton();
+
+ assert.notCalled(everyWindowStub.registerCallback);
+ });
+ });
+ describe("Show/Hide functions", () => {
+ it("should unhide appmenu button on _showAppmenuButton()", async () => {
+ await instance._showAppmenuButton(fakeWindow);
+
+ assert.calledWith(fakeElementById.removeAttribute, "hidden");
+ });
+ it("should hide appmenu button on _hideAppmenuButton()", () => {
+ instance._hideAppmenuButton(fakeWindow);
+ assert.calledWith(fakeElementById.setAttribute, "hidden", true);
+ });
+ it("should not do anything if the window is closed", () => {
+ instance._hideAppmenuButton(fakeWindow, true);
+ assert.notCalled(PanelMultiView.getViewNode);
+ });
+ it("should not throw if the element does not exist", () => {
+ let fn = instance._hideAppmenuButton.bind(null, {
+ browser: { ownerDocument: {} },
+ });
+ getViewNodeStub.returns(undefined);
+ assert.doesNotThrow(fn);
+ });
+ it("should unhide toolbar button on _showToolbarButton()", async () => {
+ await instance._showToolbarButton(fakeWindow);
+
+ assert.calledWith(fakeElementById.removeAttribute, "hidden");
+ });
+ it("should hide toolbar button on _hideToolbarButton()", () => {
+ instance._hideToolbarButton(fakeWindow);
+ assert.calledWith(fakeElementById.setAttribute, "hidden", true);
+ });
+ });
+ describe("#renderMessages", () => {
+ let getMessagesStub;
+ beforeEach(() => {
+ getMessagesStub = sandbox.stub();
+ instance.init(waitForInitializedStub, {
+ getMessages: getMessagesStub,
+ sendTelemetry: fakeSendTelemetry,
+ });
+ });
+ it("should have correct state", async () => {
+ const messages = (await PanelTestProvider.getMessages()).filter(
+ m => m.template === "whatsnew_panel_message"
+ );
+
+ getMessagesStub.returns(messages);
+ const ev1 = sandbox.stub();
+ ev1.withArgs("type").returns(1); // tracker
+ ev1.withArgs("count").returns(4);
+ const ev2 = sandbox.stub();
+ ev2.withArgs("type").returns(4); // fingerprinter
+ ev2.withArgs("count").returns(3);
+ getEventsByDateRangeStub.returns([
+ { getResultByName: ev1 },
+ { getResultByName: ev2 },
+ ]);
+
+ await instance.renderMessages(fakeWindow, fakeDocument, "container-id");
+
+ assert.propertyVal(instance.state.contentArguments, "trackerCount", 4);
+ assert.propertyVal(
+ instance.state.contentArguments,
+ "fingerprinterCount",
+ 3
+ );
+ });
+ it("should render messages to the panel on renderMessages()", async () => {
+ const messages = (await PanelTestProvider.getMessages()).filter(
+ m => m.template === "whatsnew_panel_message"
+ );
+ messages[0].content.link_text = { string_id: "link_text_id" };
+
+ getMessagesStub.returns(messages);
+ const ev1 = sandbox.stub();
+ ev1.withArgs("type").returns(1); // tracker
+ ev1.withArgs("count").returns(4);
+ const ev2 = sandbox.stub();
+ ev2.withArgs("type").returns(4); // fingerprinter
+ ev2.withArgs("count").returns(3);
+ getEventsByDateRangeStub.returns([
+ { getResultByName: ev1 },
+ { getResultByName: ev2 },
+ ]);
+
+ await instance.renderMessages(fakeWindow, fakeDocument, "container-id");
+
+ for (let message of messages) {
+ assert.ok(
+ fakeRemoteL10n.createElement.args.find(
+ ([doc, el, args]) =>
+ args && args.classList === "whatsNew-message-title"
+ )
+ );
+ if (message.content.layout === "tracking-protections") {
+ assert.ok(
+ fakeRemoteL10n.createElement.args.find(
+ ([doc, el, args]) =>
+ args && args.classList === "whatsNew-message-subtitle"
+ )
+ );
+ }
+ if (message.id === "WHATS_NEW_FINGERPRINTER_COUNTER_72") {
+ assert.ok(
+ fakeRemoteL10n.createElement.args.find(
+ ([doc, el, args]) => el === "h2" && args.content === 3
+ )
+ );
+ }
+ assert.ok(
+ fakeRemoteL10n.createElement.args.find(
+ ([doc, el, args]) =>
+ args && args.classList === "whatsNew-message-content"
+ )
+ );
+ }
+ // Call the click handler to make coverage happy.
+ eventListeners.mouseup();
+ assert.calledOnce(global.SpecialMessageActions.handleAction);
+ });
+ it("should clear previous messages on 2nd renderMessages()", async () => {
+ const messages = (await PanelTestProvider.getMessages()).filter(
+ m => m.template === "whatsnew_panel_message"
+ );
+ const removeStub = sandbox.stub();
+ fakeElementById.querySelectorAll.onCall(0).returns([]);
+ fakeElementById.querySelectorAll
+ .onCall(1)
+ .returns([{ remove: removeStub }, { remove: removeStub }]);
+
+ getMessagesStub.returns(messages);
+
+ await instance.renderMessages(fakeWindow, fakeDocument, "container-id");
+ await instance.renderMessages(fakeWindow, fakeDocument, "container-id");
+
+ assert.calledTwice(removeStub);
+ });
+ it("should sort based on order field value", async () => {
+ const messages = (await PanelTestProvider.getMessages()).filter(
+ m =>
+ m.template === "whatsnew_panel_message" &&
+ m.content.published_date === 1560969794394
+ );
+
+ messages.forEach(m => (m.content.title = m.order));
+
+ getMessagesStub.returns(messages);
+
+ await instance.renderMessages(fakeWindow, fakeDocument, "container-id");
+
+ // Select the title elements that are supposed to be set to the same
+ // value as the `order` field of the message
+ const titleEls = fakeRemoteL10n.createElement.args
+ .filter(
+ ([doc, el, args]) =>
+ args && args.classList === "whatsNew-message-title"
+ )
+ .map(([doc, el, args]) => args.content);
+ assert.deepEqual(titleEls, [1, 2, 3]);
+ });
+ it("should accept string for image attributes", async () => {
+ const messages = (await PanelTestProvider.getMessages()).filter(
+ m => m.id === "WHATS_NEW_70_1"
+ );
+ getMessagesStub.returns(messages);
+
+ await instance.renderMessages(fakeWindow, fakeDocument, "container-id");
+
+ const imageEl = createdCustomElements.find(el => el.tagName === "img");
+ assert.calledOnce(imageEl.setAttribute);
+ assert.calledWithExactly(
+ imageEl.setAttribute,
+ "alt",
+ "Firefox Send Logo"
+ );
+ });
+ it("should set state values as data-attribute", async () => {
+ const [message] = (await PanelTestProvider.getMessages()).filter(
+ m =>
+ m.template === "whatsnew_panel_message" &&
+ m.content.layout === "tracking-protections"
+ );
+ getMessagesStub.returns([message]);
+ instance.state.contentArguments = { foo: "foo", bar: "bar" };
+
+ await instance.renderMessages(fakeWindow, fakeDocument, "container-id");
+
+ const [, , args] = fakeRemoteL10n.createElement.args.find(
+ ([doc, el, elArgs]) => elArgs && elArgs.attributes
+ );
+ assert.ok(args);
+ // Currently this.state.contentArguments has 8 different entries
+ assert.lengthOf(Object.keys(args.attributes), 8);
+ assert.equal(
+ args.attributes.searchEngineName,
+ defaultSearchStub.defaultEngine.name
+ );
+ });
+ it("should only render unique dates (no duplicates)", async () => {
+ const messages = (await PanelTestProvider.getMessages()).filter(
+ m => m.template === "whatsnew_panel_message"
+ );
+ const uniqueDates = [
+ ...new Set(messages.map(m => m.content.published_date)),
+ ];
+ getMessagesStub.returns(messages);
+
+ await instance.renderMessages(fakeWindow, fakeDocument, "container-id");
+
+ const dateElements = fakeRemoteL10n.createElement.args.filter(
+ ([doc, el, args]) =>
+ el === "p" && args.classList === "whatsNew-message-date"
+ );
+ assert.lengthOf(dateElements, uniqueDates.length);
+ });
+ it("should listen for panelhidden and remove the toolbar button", async () => {
+ getMessagesStub.returns([]);
+ fakeDocument.getElementById
+ .withArgs("customizationui-widget-panel")
+ .returns(null);
+
+ await instance.renderMessages(fakeWindow, fakeDocument, "container-id");
+
+ assert.notCalled(fakeElementById.addEventListener);
+ });
+ it("should attach doCommand cbs that handle user actions", async () => {
+ const messages = (await PanelTestProvider.getMessages()).filter(
+ m => m.template === "whatsnew_panel_message"
+ );
+ getMessagesStub.returns(messages);
+
+ await instance.renderMessages(fakeWindow, fakeDocument, "container-id");
+
+ const messageEl = createdCustomElements.find(
+ el =>
+ el.tagName === "div" && el.classList.includes("whatsNew-message-body")
+ );
+ const anchorEl = createdCustomElements.find(el => el.tagName === "a");
+
+ assert.notCalled(global.SpecialMessageActions.handleAction);
+
+ messageEl.doCommand();
+ anchorEl.doCommand();
+
+ assert.calledTwice(global.SpecialMessageActions.handleAction);
+ });
+ it("should listen for panelhidden and remove the toolbar button", async () => {
+ getMessagesStub.returns([]);
+
+ await instance.renderMessages(fakeWindow, fakeDocument, "container-id");
+
+ assert.calledOnce(fakeElementById.addEventListener);
+ assert.calledWithExactly(
+ fakeElementById.addEventListener,
+ "popuphidden",
+ sinon.match.func,
+ {
+ once: true,
+ }
+ );
+ const [, cb] = fakeElementById.addEventListener.firstCall.args;
+
+ assert.notCalled(everyWindowStub.unregisterCallback);
+
+ cb();
+
+ assert.calledOnce(everyWindowStub.unregisterCallback);
+ assert.calledWithExactly(
+ everyWindowStub.unregisterCallback,
+ "whats-new-menu-button"
+ );
+ });
+ describe("#IMPRESSION", () => {
+ it("should dispatch a IMPRESSION for messages", async () => {
+ // means panel is triggered from the toolbar button
+ fakeElementById.hasAttribute.returns(true);
+ const messages = (await PanelTestProvider.getMessages()).filter(
+ m => m.template === "whatsnew_panel_message"
+ );
+ getMessagesStub.returns(messages);
+ const spy = sandbox.spy(instance, "sendUserEventTelemetry");
+
+ await instance.renderMessages(fakeWindow, fakeDocument, "container-id");
+
+ assert.calledOnce(spy);
+ assert.calledOnce(fakeSendTelemetry);
+ assert.propertyVal(
+ spy.firstCall.args[2],
+ "id",
+ messages
+ .map(({ id }) => id)
+ .sort()
+ .join(",")
+ );
+ });
+ it("should dispatch a CLICK for clicking a message", async () => {
+ // means panel is triggered from the toolbar button
+ fakeElementById.hasAttribute.returns(true);
+ // Force to render the message
+ fakeElementById.querySelector.returns(null);
+ const messages = (await PanelTestProvider.getMessages()).filter(
+ m => m.template === "whatsnew_panel_message"
+ );
+ getMessagesStub.returns([messages[0]]);
+ const spy = sandbox.spy(instance, "sendUserEventTelemetry");
+
+ await instance.renderMessages(fakeWindow, fakeDocument, "container-id");
+
+ assert.calledOnce(spy);
+ assert.calledOnce(fakeSendTelemetry);
+
+ spy.resetHistory();
+
+ // Message click event listener cb
+ eventListeners.mouseup();
+
+ assert.calledOnce(spy);
+ assert.calledWithExactly(spy, fakeWindow, "CLICK", messages[0]);
+ });
+ it("should dispatch a IMPRESSION with toolbar_dropdown", async () => {
+ // means panel is triggered from the toolbar button
+ fakeElementById.hasAttribute.returns(true);
+ const messages = (await PanelTestProvider.getMessages()).filter(
+ m => m.template === "whatsnew_panel_message"
+ );
+ getMessagesStub.resolves(messages);
+ const spy = sandbox.spy(instance, "sendUserEventTelemetry");
+ const panelPingId = messages
+ .map(({ id }) => id)
+ .sort()
+ .join(",");
+
+ await instance.renderMessages(fakeWindow, fakeDocument, "container-id");
+
+ assert.calledOnce(spy);
+ assert.calledWithExactly(
+ spy,
+ fakeWindow,
+ "IMPRESSION",
+ {
+ id: panelPingId,
+ },
+ {
+ value: {
+ view: "toolbar_dropdown",
+ },
+ }
+ );
+ assert.calledOnce(fakeSendTelemetry);
+ const {
+ args: [dispatchPayload],
+ } = fakeSendTelemetry.lastCall;
+ assert.propertyVal(dispatchPayload, "type", "TOOLBAR_PANEL_TELEMETRY");
+ assert.propertyVal(dispatchPayload.data, "message_id", panelPingId);
+ assert.deepEqual(dispatchPayload.data.event_context, {
+ view: "toolbar_dropdown",
+ });
+ });
+ it("should dispatch a IMPRESSION with application_menu", async () => {
+ // means panel is triggered as a subview in the application menu
+ fakeElementById.hasAttribute.returns(false);
+ const messages = (await PanelTestProvider.getMessages()).filter(
+ m => m.template === "whatsnew_panel_message"
+ );
+ getMessagesStub.resolves(messages);
+ const spy = sandbox.spy(instance, "sendUserEventTelemetry");
+ const panelPingId = messages
+ .map(({ id }) => id)
+ .sort()
+ .join(",");
+
+ await instance.renderMessages(fakeWindow, fakeDocument, "container-id");
+
+ assert.calledOnce(spy);
+ assert.calledWithExactly(
+ spy,
+ fakeWindow,
+ "IMPRESSION",
+ {
+ id: panelPingId,
+ },
+ {
+ value: {
+ view: "application_menu",
+ },
+ }
+ );
+ assert.calledOnce(fakeSendTelemetry);
+ const {
+ args: [dispatchPayload],
+ } = fakeSendTelemetry.lastCall;
+ assert.propertyVal(dispatchPayload, "type", "TOOLBAR_PANEL_TELEMETRY");
+ assert.propertyVal(dispatchPayload.data, "message_id", panelPingId);
+ assert.deepEqual(dispatchPayload.data.event_context, {
+ view: "application_menu",
+ });
+ });
+ });
+ describe("#forceShowMessage", () => {
+ const panelSelector = "PanelUI-whatsNew-message-container";
+ let removeMessagesSpy;
+ let renderMessagesStub;
+ let addEventListenerStub;
+ let messages;
+ let browser;
+ beforeEach(async () => {
+ messages = (await PanelTestProvider.getMessages()).find(
+ m => m.id === "WHATS_NEW_70_1"
+ );
+ removeMessagesSpy = sandbox.spy(instance, "removeMessages");
+ renderMessagesStub = sandbox.spy(instance, "renderMessages");
+ addEventListenerStub = fakeElementById.addEventListener;
+ browser = { ownerGlobal: fakeWindow, ownerDocument: fakeDocument };
+ fakeElementById.querySelectorAll.returns([fakeElementById]);
+ });
+ it("should call removeMessages when forcing a message to show", () => {
+ instance.forceShowMessage(browser, messages);
+
+ assert.calledWithExactly(removeMessagesSpy, fakeWindow, panelSelector);
+ });
+ it("should call renderMessages when forcing a message to show", () => {
+ instance.forceShowMessage(browser, messages);
+
+ assert.calledOnce(renderMessagesStub);
+ assert.calledWithExactly(
+ renderMessagesStub,
+ fakeWindow,
+ fakeDocument,
+ panelSelector,
+ {
+ force: true,
+ messages: Array.isArray(messages) ? messages : [messages],
+ }
+ );
+ });
+ it("should cleanup after the panel is hidden when forcing a message to show", () => {
+ instance.forceShowMessage(browser, messages);
+
+ assert.calledOnce(addEventListenerStub);
+ assert.calledWithExactly(
+ addEventListenerStub,
+ "popuphidden",
+ sinon.match.func
+ );
+
+ const [, cb] = addEventListenerStub.firstCall.args;
+ // Reset the call count from the first `forceShowMessage` call
+ removeMessagesSpy.resetHistory();
+ cb({ target: { ownerGlobal: fakeWindow } });
+
+ assert.calledOnce(removeMessagesSpy);
+ assert.calledWithExactly(removeMessagesSpy, fakeWindow, panelSelector);
+ });
+ });
+ });
+ describe("#insertProtectionPanelMessage", () => {
+ const fakeInsert = () =>
+ instance.insertProtectionPanelMessage({
+ target: { ownerGlobal: fakeWindow, ownerDocument: fakeDocument },
+ });
+ let getMessagesStub;
+ beforeEach(async () => {
+ const onboardingMsgs = await OnboardingMessageProvider.getUntranslatedMessages();
+ getMessagesStub = sandbox
+ .stub()
+ .resolves(
+ onboardingMsgs.find(msg => msg.template === "protections_panel")
+ );
+ await instance.init(waitForInitializedStub, {
+ sendTelemetry: fakeSendTelemetry,
+ getMessages: getMessagesStub,
+ });
+ });
+ it("should remember it showed", async () => {
+ await fakeInsert();
+
+ assert.calledWithExactly(
+ setBoolPrefStub,
+ "browser.protections_panel.infoMessage.seen",
+ true
+ );
+ });
+ it("should toggle/expand when default collapsed/disabled", async () => {
+ fakeElementById.hasAttribute.returns(true);
+
+ await fakeInsert();
+
+ assert.calledThrice(fakeElementById.toggleAttribute);
+ });
+ it("should toggle again when popup hides", async () => {
+ fakeElementById.addEventListener.callsArg(1);
+
+ await fakeInsert();
+
+ assert.callCount(fakeElementById.toggleAttribute, 6);
+ });
+ it("should open link on click (separate link element)", async () => {
+ const sendTelemetryStub = sandbox.stub(
+ instance,
+ "sendUserEventTelemetry"
+ );
+ const onboardingMsgs = await OnboardingMessageProvider.getUntranslatedMessages();
+ const msg = onboardingMsgs.find(m => m.template === "protections_panel");
+
+ await fakeInsert();
+
+ assert.calledOnce(sendTelemetryStub);
+ assert.calledWithExactly(
+ sendTelemetryStub,
+ fakeWindow,
+ "IMPRESSION",
+ msg
+ );
+
+ eventListeners.mouseup();
+
+ assert.calledOnce(global.SpecialMessageActions.handleAction);
+ assert.calledWithExactly(
+ global.SpecialMessageActions.handleAction,
+ {
+ type: "OPEN_URL",
+ data: {
+ args: sinon.match.string,
+ where: "tabshifted",
+ },
+ },
+ fakeWindow.browser
+ );
+ });
+ it("should format the url", async () => {
+ const stub = sandbox
+ .stub(global.Services.urlFormatter, "formatURL")
+ .returns("formattedURL");
+ const onboardingMsgs = await OnboardingMessageProvider.getUntranslatedMessages();
+ const msg = onboardingMsgs.find(m => m.template === "protections_panel");
+
+ await fakeInsert();
+
+ eventListeners.mouseup();
+
+ assert.calledOnce(stub);
+ assert.calledWithExactly(stub, msg.content.cta_url);
+ assert.calledOnce(global.SpecialMessageActions.handleAction);
+ assert.calledWithExactly(
+ global.SpecialMessageActions.handleAction,
+ {
+ type: "OPEN_URL",
+ data: {
+ args: "formattedURL",
+ where: "tabshifted",
+ },
+ },
+ fakeWindow.browser
+ );
+ });
+ it("should report format url errors", async () => {
+ const stub = sandbox
+ .stub(global.Services.urlFormatter, "formatURL")
+ .throws();
+ const onboardingMsgs = await OnboardingMessageProvider.getUntranslatedMessages();
+ const msg = onboardingMsgs.find(m => m.template === "protections_panel");
+ sandbox.spy(global.Cu, "reportError");
+
+ await fakeInsert();
+
+ eventListeners.mouseup();
+
+ assert.calledOnce(stub);
+ assert.calledOnce(global.Cu.reportError);
+ assert.calledOnce(global.SpecialMessageActions.handleAction);
+ assert.calledWithExactly(
+ global.SpecialMessageActions.handleAction,
+ {
+ type: "OPEN_URL",
+ data: {
+ args: msg.content.cta_url,
+ where: "tabshifted",
+ },
+ },
+ fakeWindow.browser
+ );
+ });
+ it("should open link on click (directly attached to the message)", async () => {
+ const onboardingMsgs = await OnboardingMessageProvider.getUntranslatedMessages();
+ const msg = onboardingMsgs.find(m => m.template === "protections_panel");
+ getMessagesStub.resolves({
+ ...msg,
+ content: { ...msg.content, link_text: null },
+ });
+ await fakeInsert();
+
+ eventListeners.mouseup();
+
+ assert.calledOnce(global.SpecialMessageActions.handleAction);
+ assert.calledWithExactly(
+ global.SpecialMessageActions.handleAction,
+ {
+ type: "OPEN_URL",
+ data: {
+ args: sinon.match.string,
+ where: "tabshifted",
+ },
+ },
+ fakeWindow.browser
+ );
+ });
+ it("should handle user actions from mouseup and keyup", async () => {
+ await fakeInsert();
+
+ eventListeners.mouseup();
+ eventListeners.keyup({ key: "Enter" });
+ eventListeners.keyup({ key: " " });
+ assert.calledThrice(global.SpecialMessageActions.handleAction);
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/lib/TopSitesFeed.test.js b/browser/components/newtab/test/unit/lib/TopSitesFeed.test.js
new file mode 100644
index 0000000000..319eb8d799
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/TopSitesFeed.test.js
@@ -0,0 +1,2015 @@
+"use strict";
+
+import { actionCreators as ac, actionTypes as at } from "common/Actions.jsm";
+import { FakePrefs, GlobalOverrider } from "test/unit/utils";
+import {
+ insertPinned,
+ TOP_SITES_DEFAULT_ROWS,
+ TOP_SITES_MAX_SITES_PER_ROW,
+} from "common/Reducers.jsm";
+import { getDefaultOptions } from "lib/ActivityStreamStorage.jsm";
+import injector from "inject!lib/TopSitesFeed.jsm";
+import { Screenshots } from "lib/Screenshots.jsm";
+
+const FAKE_FAVICON = "data987";
+const FAKE_FAVICON_SIZE = 128;
+const FAKE_FRECENCY = 200;
+const FAKE_LINKS = new Array(2 * TOP_SITES_MAX_SITES_PER_ROW)
+ .fill(null)
+ .map((v, i) => ({
+ frecency: FAKE_FRECENCY,
+ url: `http://www.site${i}.com`,
+ }));
+const FAKE_SCREENSHOT = "data123";
+const SEARCH_SHORTCUTS_EXPERIMENT_PREF = "improvesearch.topSiteSearchShortcuts";
+const SEARCH_SHORTCUTS_SEARCH_ENGINES_PREF =
+ "improvesearch.topSiteSearchShortcuts.searchEngines";
+const SEARCH_SHORTCUTS_HAVE_PINNED_PREF =
+ "improvesearch.topSiteSearchShortcuts.havePinned";
+const SHOWN_ON_NEWTAB_PREF = "feeds.topsites";
+
+function FakeTippyTopProvider() {}
+FakeTippyTopProvider.prototype = {
+ async init() {
+ this.initialized = true;
+ },
+ processSite(site) {
+ return site;
+ },
+};
+
+describe("Top Sites Feed", () => {
+ let TopSitesFeed;
+ let DEFAULT_TOP_SITES;
+ let feed;
+ let globals;
+ let sandbox;
+ let links;
+ let fakeNewTabUtils;
+ let fakeScreenshot;
+ let filterAdultStub;
+ let shortURLStub;
+ let fakePageThumbs;
+
+ beforeEach(() => {
+ globals = new GlobalOverrider();
+ sandbox = globals.sandbox;
+ fakeNewTabUtils = {
+ blockedLinks: {
+ links: [],
+ isBlocked: () => false,
+ unblock: sandbox.spy(),
+ },
+ activityStreamLinks: {
+ getTopSites: sandbox.spy(() => Promise.resolve(links)),
+ },
+ activityStreamProvider: {
+ _addFavicons: sandbox.spy(l =>
+ Promise.resolve(
+ l.map(link => {
+ link.favicon = FAKE_FAVICON;
+ link.faviconSize = FAKE_FAVICON_SIZE;
+ return link;
+ })
+ )
+ ),
+ _faviconBytesToDataURI: sandbox.spy(),
+ },
+ pinnedLinks: {
+ links: [],
+ isPinned: () => false,
+ pin: sandbox.spy(),
+ unpin: sandbox.spy(),
+ },
+ };
+ fakeScreenshot = {
+ getScreenshotForURL: sandbox.spy(() => Promise.resolve(FAKE_SCREENSHOT)),
+ maybeCacheScreenshot: sandbox.spy(Screenshots.maybeCacheScreenshot),
+ _shouldGetScreenshots: sinon.stub().returns(true),
+ };
+ filterAdultStub = sinon.stub().returns([]);
+ shortURLStub = sinon
+ .stub()
+ .callsFake(site =>
+ site.url.replace(/(.com|.ca)/, "").replace("https://", "")
+ );
+ const fakeDedupe = function() {};
+ fakePageThumbs = {
+ addExpirationFilter: sinon.stub(),
+ removeExpirationFilter: sinon.stub(),
+ };
+ globals.set("PageThumbs", fakePageThumbs);
+ globals.set("NewTabUtils", fakeNewTabUtils);
+ sandbox.spy(global.XPCOMUtils, "defineLazyGetter");
+ FakePrefs.prototype.prefs["default.sites"] = "https://foo.com/";
+ ({ TopSitesFeed, DEFAULT_TOP_SITES } = injector({
+ "lib/ActivityStreamPrefs.jsm": { Prefs: FakePrefs },
+ "common/Dedupe.jsm": { Dedupe: fakeDedupe },
+ "common/Reducers.jsm": {
+ insertPinned,
+ TOP_SITES_DEFAULT_ROWS,
+ TOP_SITES_MAX_SITES_PER_ROW,
+ },
+ "lib/FilterAdult.jsm": { filterAdult: filterAdultStub },
+ "lib/Screenshots.jsm": { Screenshots: fakeScreenshot },
+ "lib/TippyTopProvider.jsm": { TippyTopProvider: FakeTippyTopProvider },
+ "lib/ShortURL.jsm": { shortURL: shortURLStub },
+ "lib/ActivityStreamStorage.jsm": {
+ ActivityStreamStorage: function Fake() {},
+ getDefaultOptions,
+ },
+ }));
+ feed = new TopSitesFeed();
+ const storage = {
+ init: sandbox.stub().resolves(),
+ get: sandbox.stub().resolves(),
+ set: sandbox.stub().resolves(),
+ };
+ // Setup for tests that don't call `init` but require feed.storage
+ feed._storage = storage;
+ feed.store = {
+ dispatch: sinon.spy(),
+ getState() {
+ return this.state;
+ },
+ state: {
+ Prefs: { values: { filterAdult: false, topSitesRows: 2 } },
+ TopSites: { rows: Array(12).fill("site") },
+ },
+ dbStorage: { getDbTable: sandbox.stub().returns(storage) },
+ };
+ feed.dedupe.group = (...sites) => sites;
+ links = FAKE_LINKS;
+ // Turn off the search shortcuts experiment by default for other tests
+ feed.store.state.Prefs.values[SEARCH_SHORTCUTS_EXPERIMENT_PREF] = false;
+ feed.store.state.Prefs.values[SEARCH_SHORTCUTS_HAVE_PINNED_PREF] =
+ "google,amazon";
+ });
+ afterEach(() => {
+ globals.restore();
+ sandbox.restore();
+ });
+
+ function stubFaviconsToUseScreenshots() {
+ fakeNewTabUtils.activityStreamProvider._addFavicons = sandbox.stub();
+ }
+
+ describe("#constructor", () => {
+ it("should defineLazyGetter for _currentSearchHostname", () => {
+ assert.calledOnce(global.XPCOMUtils.defineLazyGetter);
+ assert.calledWith(
+ global.XPCOMUtils.defineLazyGetter,
+ feed,
+ "_currentSearchHostname",
+ sinon.match.func
+ );
+ });
+ });
+
+ describe("#refreshDefaults", () => {
+ it("should add defaults on PREFS_INITIAL_VALUES", () => {
+ feed.onAction({
+ type: at.PREFS_INITIAL_VALUES,
+ data: { "default.sites": "https://foo.com" },
+ });
+
+ assert.isAbove(DEFAULT_TOP_SITES.length, 0);
+ });
+ it("should add defaults on default.sites PREF_CHANGED", () => {
+ feed.onAction({
+ type: at.PREF_CHANGED,
+ data: { name: "default.sites", value: "https://foo.com" },
+ });
+
+ assert.isAbove(DEFAULT_TOP_SITES.length, 0);
+ });
+ it("should refresh on topSiteRows PREF_CHANGED", () => {
+ feed.refresh = sinon.spy();
+ feed.onAction({ type: at.PREF_CHANGED, data: { name: "topSitesRows" } });
+
+ assert.calledOnce(feed.refresh);
+ });
+ it("should have default sites with .isDefault = true", () => {
+ feed.refreshDefaults("https://foo.com");
+
+ DEFAULT_TOP_SITES.forEach(link =>
+ assert.propertyVal(link, "isDefault", true)
+ );
+ });
+ it("should have default sites with appropriate hostname", () => {
+ feed.refreshDefaults("https://foo.com");
+
+ DEFAULT_TOP_SITES.forEach(link =>
+ assert.propertyVal(link, "hostname", shortURLStub(link))
+ );
+ });
+ it("should add no defaults on empty pref", () => {
+ feed.refreshDefaults("");
+
+ assert.equal(DEFAULT_TOP_SITES.length, 0);
+ });
+ it("should clear defaults", () => {
+ feed.refreshDefaults("https://foo.com");
+ feed.refreshDefaults("");
+
+ assert.equal(DEFAULT_TOP_SITES.length, 0);
+ });
+ });
+ describe("#filterForThumbnailExpiration", () => {
+ it("should pass rows.urls to the callback provided", () => {
+ const rows = [
+ { url: "foo.com" },
+ { url: "bar.com", customScreenshotURL: "custom" },
+ ];
+ feed.store.state.TopSites = { rows };
+ const stub = sinon.stub();
+
+ feed.filterForThumbnailExpiration(stub);
+
+ assert.calledOnce(stub);
+ assert.calledWithExactly(stub, ["foo.com", "bar.com", "custom"]);
+ });
+ });
+ describe("#getLinksWithDefaults", () => {
+ beforeEach(() => {
+ feed.refreshDefaults("https://foo.com");
+ });
+
+ describe("general", () => {
+ it("should get the links from NewTabUtils", async () => {
+ const result = await feed.getLinksWithDefaults();
+ const reference = links.map(site =>
+ Object.assign({}, site, {
+ hostname: shortURLStub(site),
+ typedBonus: true,
+ })
+ );
+
+ assert.deepEqual(result, reference);
+ assert.calledOnce(global.NewTabUtils.activityStreamLinks.getTopSites);
+ });
+ it("should indicate the links get typed bonus", async () => {
+ const result = await feed.getLinksWithDefaults();
+
+ assert.propertyVal(result[0], "typedBonus", true);
+ });
+ it("should not filter out adult sites when pref is false", async () => {
+ await feed.getLinksWithDefaults();
+
+ assert.notCalled(filterAdultStub);
+ });
+ it("should filter out non-pinned adult sites when pref is true", async () => {
+ feed.store.state.Prefs.values.filterAdult = true;
+ fakeNewTabUtils.pinnedLinks.links = [{ url: "https://foo.com/" }];
+
+ const result = await feed.getLinksWithDefaults();
+
+ // The stub filters out everything
+ assert.calledOnce(filterAdultStub);
+ assert.equal(result.length, 1);
+ assert.equal(result[0].url, fakeNewTabUtils.pinnedLinks.links[0].url);
+ });
+ it("should filter out the defaults that have been blocked", async () => {
+ // make sure we only have one top site, and we block the only default site we have to show
+ const url = "www.myonlytopsite.com";
+ const topsite = {
+ frecency: FAKE_FRECENCY,
+ hostname: shortURLStub({ url }),
+ typedBonus: true,
+ url,
+ };
+ const blockedDefaultSite = { url: "https://foo.com" };
+ fakeNewTabUtils.activityStreamLinks.getTopSites = () => [topsite];
+ fakeNewTabUtils.blockedLinks.isBlocked = site =>
+ site.url === blockedDefaultSite.url;
+ const result = await feed.getLinksWithDefaults();
+
+ // what we should be left with is just the top site we added, and not the default site we blocked
+ assert.lengthOf(result, 1);
+ assert.deepEqual(result[0], topsite);
+ assert.notInclude(result, blockedDefaultSite);
+ });
+ it("should call dedupe on the links", async () => {
+ const stub = sinon.stub(feed.dedupe, "group").callsFake((...id) => id);
+
+ await feed.getLinksWithDefaults();
+
+ assert.calledOnce(stub);
+ });
+ it("should dedupe the links by hostname", async () => {
+ const site = { url: "foo", hostname: "bar" };
+ const result = feed._dedupeKey(site);
+
+ assert.equal(result, site.hostname);
+ });
+ it("should add defaults if there are are not enough links", async () => {
+ links = [{ frecency: FAKE_FRECENCY, url: "foo.com" }];
+
+ const result = await feed.getLinksWithDefaults();
+ const reference = [...links, ...DEFAULT_TOP_SITES].map(s =>
+ Object.assign({}, s, {
+ hostname: shortURLStub(s),
+ typedBonus: true,
+ })
+ );
+
+ assert.deepEqual(result, reference);
+ });
+ it("should only add defaults up to the number of visible slots", async () => {
+ links = [];
+ const numVisible = TOP_SITES_DEFAULT_ROWS * TOP_SITES_MAX_SITES_PER_ROW;
+ for (let i = 0; i < numVisible - 1; i++) {
+ links.push({ frecency: FAKE_FRECENCY, url: `foo${i}.com` });
+ }
+ const result = await feed.getLinksWithDefaults();
+ const reference = [...links, DEFAULT_TOP_SITES[0]].map(s =>
+ Object.assign({}, s, {
+ hostname: shortURLStub(s),
+ typedBonus: true,
+ })
+ );
+
+ assert.lengthOf(result, numVisible);
+ assert.deepEqual(result, reference);
+ });
+ it("should not throw if NewTabUtils returns null", () => {
+ links = null;
+ assert.doesNotThrow(() => {
+ feed.getLinksWithDefaults();
+ });
+ });
+ it("should get more if the user has asked for more", async () => {
+ links = new Array(4 * TOP_SITES_MAX_SITES_PER_ROW)
+ .fill(null)
+ .map((v, i) => ({
+ frecency: FAKE_FRECENCY,
+ url: `http://www.site${i}.com`,
+ }));
+ feed.store.state.Prefs.values.topSitesRows = 3;
+
+ const result = await feed.getLinksWithDefaults();
+
+ assert.propertyVal(
+ result,
+ "length",
+ feed.store.state.Prefs.values.topSitesRows *
+ TOP_SITES_MAX_SITES_PER_ROW
+ );
+ });
+ });
+ describe("caching", () => {
+ it("should reuse the cache on subsequent calls", async () => {
+ await feed.getLinksWithDefaults();
+ await feed.getLinksWithDefaults();
+
+ assert.calledOnce(global.NewTabUtils.activityStreamLinks.getTopSites);
+ });
+ it("should ignore the cache when requesting more", async () => {
+ await feed.getLinksWithDefaults();
+ feed.store.state.Prefs.values.topSitesRows *= 3;
+
+ await feed.getLinksWithDefaults();
+
+ assert.calledTwice(global.NewTabUtils.activityStreamLinks.getTopSites);
+ });
+ it("should migrate frecent screenshot data without getting screenshots again", async () => {
+ feed.store.state.Prefs.values[SHOWN_ON_NEWTAB_PREF] = true;
+ stubFaviconsToUseScreenshots();
+ await feed.getLinksWithDefaults();
+ const { callCount } = fakeScreenshot.getScreenshotForURL;
+ feed.frecentCache.expire();
+
+ const result = await feed.getLinksWithDefaults();
+
+ assert.calledTwice(global.NewTabUtils.activityStreamLinks.getTopSites);
+ assert.callCount(fakeScreenshot.getScreenshotForURL, callCount);
+ assert.propertyVal(result[0], "screenshot", FAKE_SCREENSHOT);
+ });
+ it("should migrate pinned favicon data without getting favicons again", async () => {
+ fakeNewTabUtils.pinnedLinks.links = [{ url: "https://foo.com/" }];
+ await feed.getLinksWithDefaults();
+ const {
+ callCount,
+ } = fakeNewTabUtils.activityStreamProvider._addFavicons;
+ feed.pinnedCache.expire();
+
+ const result = await feed.getLinksWithDefaults();
+
+ assert.callCount(
+ fakeNewTabUtils.activityStreamProvider._addFavicons,
+ callCount
+ );
+ assert.propertyVal(result[0], "favicon", FAKE_FAVICON);
+ assert.propertyVal(result[0], "faviconSize", FAKE_FAVICON_SIZE);
+ });
+ it("should not expose internal link properties", async () => {
+ const result = await feed.getLinksWithDefaults();
+
+ const internal = Object.keys(result[0]).filter(key =>
+ key.startsWith("__")
+ );
+ assert.equal(internal.join(""), "");
+ });
+ it("should copy the screenshot of the frecent site if pinned site doesn't have customScreenshotURL", async () => {
+ links = [{ url: "https://foo.com/", screenshot: "screenshot" }];
+ fakeNewTabUtils.pinnedLinks.links = [{ url: "https://foo.com/" }];
+
+ const result = await feed.getLinksWithDefaults();
+
+ assert.equal(result[0].screenshot, links[0].screenshot);
+ });
+ it("should not copy the frecent screenshot if customScreenshotURL is set", async () => {
+ links = [{ url: "https://foo.com/", screenshot: "screenshot" }];
+ fakeNewTabUtils.pinnedLinks.links = [
+ { url: "https://foo.com/", customScreenshotURL: "custom" },
+ ];
+
+ const result = await feed.getLinksWithDefaults();
+
+ assert.isUndefined(result[0].screenshot);
+ });
+ it("should keep the same screenshot if no frecent site is found", async () => {
+ links = [];
+ fakeNewTabUtils.pinnedLinks.links = [
+ { url: "https://foo.com/", screenshot: "custom" },
+ ];
+
+ const result = await feed.getLinksWithDefaults();
+
+ assert.equal(result[0].screenshot, "custom");
+ });
+ it("should not overwrite pinned site screenshot", async () => {
+ links = [{ url: "https://foo.com/", screenshot: "foo" }];
+ fakeNewTabUtils.pinnedLinks.links = [
+ { url: "https://foo.com/", screenshot: "bar" },
+ ];
+
+ const result = await feed.getLinksWithDefaults();
+
+ assert.equal(result[0].screenshot, "bar");
+ });
+ it("should not set searchTopSite from frecent site", async () => {
+ links = [
+ {
+ url: "https://foo.com/",
+ searchTopSite: true,
+ screenshot: "screenshot",
+ },
+ ];
+ fakeNewTabUtils.pinnedLinks.links = [{ url: "https://foo.com/" }];
+
+ const result = await feed.getLinksWithDefaults();
+
+ assert.propertyVal(result[0], "searchTopSite", false);
+ // But it should copy over other properties
+ assert.propertyVal(result[0], "screenshot", "screenshot");
+ });
+ describe("concurrency", () => {
+ beforeEach(() => {
+ stubFaviconsToUseScreenshots();
+ fakeScreenshot.getScreenshotForURL = sandbox
+ .stub()
+ .resolves(FAKE_SCREENSHOT);
+ });
+ afterEach(() => {
+ sandbox.restore();
+ });
+
+ const getTwice = () =>
+ Promise.all([
+ feed.getLinksWithDefaults(),
+ feed.getLinksWithDefaults(),
+ ]);
+
+ it("should call the backing data once", async () => {
+ await getTwice();
+
+ assert.calledOnce(global.NewTabUtils.activityStreamLinks.getTopSites);
+ });
+ it("should get screenshots once per link", async () => {
+ feed.store.state.Prefs.values[SHOWN_ON_NEWTAB_PREF] = true;
+ await getTwice();
+
+ assert.callCount(
+ fakeScreenshot.getScreenshotForURL,
+ FAKE_LINKS.length
+ );
+ });
+ it("should dispatch once per link screenshot fetched", async () => {
+ feed.store.state.Prefs.values[SHOWN_ON_NEWTAB_PREF] = true;
+ feed._requestRichIcon = sinon.stub();
+ await getTwice();
+
+ assert.callCount(feed.store.dispatch, FAKE_LINKS.length);
+ });
+ });
+ });
+ describe("deduping", () => {
+ beforeEach(() => {
+ ({ TopSitesFeed, DEFAULT_TOP_SITES } = injector({
+ "lib/ActivityStreamPrefs.jsm": { Prefs: FakePrefs },
+ "common/Reducers.jsm": {
+ insertPinned,
+ TOP_SITES_DEFAULT_ROWS,
+ TOP_SITES_MAX_SITES_PER_ROW,
+ },
+ "lib/Screenshots.jsm": { Screenshots: fakeScreenshot },
+ }));
+ sandbox.stub(global.Services.eTLD, "getPublicSuffix").returns("com");
+ feed = Object.assign(new TopSitesFeed(), { store: feed.store });
+ });
+ it("should not dedupe pinned sites", async () => {
+ fakeNewTabUtils.pinnedLinks.links = [
+ { url: "https://developer.mozilla.org/en-US/docs/Web" },
+ { url: "https://developer.mozilla.org/en-US/docs/Learn" },
+ ];
+
+ const sites = await feed.getLinksWithDefaults();
+
+ assert.lengthOf(sites, 2 * TOP_SITES_MAX_SITES_PER_ROW);
+ assert.equal(sites[0].url, fakeNewTabUtils.pinnedLinks.links[0].url);
+ assert.equal(sites[1].url, fakeNewTabUtils.pinnedLinks.links[1].url);
+ assert.equal(sites[0].hostname, sites[1].hostname);
+ });
+ it("should prefer pinned sites over links", async () => {
+ fakeNewTabUtils.pinnedLinks.links = [
+ { url: "https://developer.mozilla.org/en-US/docs/Web" },
+ { url: "https://developer.mozilla.org/en-US/docs/Learn" },
+ ];
+ // These will be the frecent results.
+ links = [
+ { frecency: FAKE_FRECENCY, url: "https://developer.mozilla.org/" },
+ { frecency: FAKE_FRECENCY, url: "https://www.mozilla.org/" },
+ ];
+
+ const sites = await feed.getLinksWithDefaults();
+
+ // Expecting 3 links where there's 2 pinned and 1 www.mozilla.org, so
+ // the frecent with matching hostname as pinned is removed.
+ assert.lengthOf(sites, 3);
+ assert.equal(sites[0].url, fakeNewTabUtils.pinnedLinks.links[0].url);
+ assert.equal(sites[1].url, fakeNewTabUtils.pinnedLinks.links[1].url);
+ assert.equal(sites[2].url, links[1].url);
+ });
+ it("should return sites that have a title", async () => {
+ // Simulate a pinned link with no title.
+ fakeNewTabUtils.pinnedLinks.links = [
+ { url: "https://github.com/mozilla/activity-stream" },
+ ];
+
+ const sites = await feed.getLinksWithDefaults();
+
+ for (const site of sites) {
+ assert.isDefined(site.hostname);
+ }
+ });
+ it("should check against null entries", async () => {
+ fakeNewTabUtils.pinnedLinks.links = [null];
+
+ await feed.getLinksWithDefaults();
+ });
+ });
+ it("should call _fetchIcon for each link", async () => {
+ sinon.spy(feed, "_fetchIcon");
+
+ const results = await feed.getLinksWithDefaults();
+
+ assert.callCount(feed._fetchIcon, results.length);
+ results.forEach(link => {
+ assert.calledWith(feed._fetchIcon, link);
+ });
+ });
+ it("should call _fetchScreenshot when customScreenshotURL is set", async () => {
+ links = [];
+ fakeNewTabUtils.pinnedLinks.links = [
+ { url: "https://foo.com", customScreenshotURL: "custom" },
+ ];
+ sinon.stub(feed, "_fetchScreenshot");
+
+ await feed.getLinksWithDefaults();
+
+ assert.calledWith(feed._fetchScreenshot, sinon.match.object, "custom");
+ });
+ });
+ describe("#init", () => {
+ it("should call refresh (broadcast:true)", async () => {
+ sandbox.stub(feed, "refresh");
+
+ await feed.init();
+
+ assert.calledOnce(feed.refresh);
+ assert.calledWithExactly(feed.refresh, {
+ broadcast: true,
+ isStartup: true,
+ });
+ });
+ it("should initialise the storage", async () => {
+ await feed.init();
+
+ assert.calledOnce(feed.store.dbStorage.getDbTable);
+ assert.calledWithExactly(feed.store.dbStorage.getDbTable, "sectionPrefs");
+ });
+ });
+ describe("#refresh", () => {
+ beforeEach(() => {
+ sandbox.stub(feed, "_fetchIcon");
+ feed._startedUp = true;
+ });
+ it("should wait for tippytop to initialize", async () => {
+ feed._tippyTopProvider.initialized = false;
+ sinon.stub(feed._tippyTopProvider, "init").resolves();
+
+ await feed.refresh();
+
+ assert.calledOnce(feed._tippyTopProvider.init);
+ });
+ it("should not init the tippyTopProvider if already initialized", async () => {
+ feed._tippyTopProvider.initialized = true;
+ sinon.stub(feed._tippyTopProvider, "init").resolves();
+
+ await feed.refresh();
+
+ assert.notCalled(feed._tippyTopProvider.init);
+ });
+ it("should broadcast TOP_SITES_UPDATED", async () => {
+ sinon.stub(feed, "getLinksWithDefaults").returns(Promise.resolve([]));
+
+ await feed.refresh({ broadcast: true });
+
+ assert.calledOnce(feed.store.dispatch);
+ assert.calledWithExactly(
+ feed.store.dispatch,
+ ac.BroadcastToContent({
+ type: at.TOP_SITES_UPDATED,
+ data: { links: [], pref: { collapsed: false } },
+ })
+ );
+ });
+ it("should dispatch an action with the links returned", async () => {
+ await feed.refresh({ broadcast: true });
+ const reference = links.map(site =>
+ Object.assign({}, site, {
+ hostname: shortURLStub(site),
+ typedBonus: true,
+ })
+ );
+
+ assert.calledOnce(feed.store.dispatch);
+ assert.propertyVal(
+ feed.store.dispatch.firstCall.args[0],
+ "type",
+ at.TOP_SITES_UPDATED
+ );
+ assert.deepEqual(
+ feed.store.dispatch.firstCall.args[0].data.links,
+ reference
+ );
+ });
+ it("should handle empty slots in the resulting top sites array", async () => {
+ links = [FAKE_LINKS[0]];
+ fakeNewTabUtils.pinnedLinks.links = [
+ null,
+ null,
+ FAKE_LINKS[1],
+ null,
+ null,
+ null,
+ null,
+ null,
+ FAKE_LINKS[2],
+ ];
+ await feed.refresh({ broadcast: true });
+ assert.calledOnce(feed.store.dispatch);
+ });
+ it("should dispatch AlsoToPreloaded when broadcast is false", async () => {
+ sandbox.stub(feed, "getLinksWithDefaults").returns([]);
+ await feed.refresh({ broadcast: false });
+
+ assert.calledOnce(feed.store.dispatch);
+ assert.calledWithExactly(
+ feed.store.dispatch,
+ ac.AlsoToPreloaded({
+ type: at.TOP_SITES_UPDATED,
+ data: { links: [], pref: { collapsed: false } },
+ })
+ );
+ });
+ it("should not init storage if it is already initialized", async () => {
+ feed._storage.initialized = true;
+
+ await feed.refresh({ broadcast: false });
+
+ assert.notCalled(feed._storage.init);
+ });
+ it("should catch indexedDB errors", async () => {
+ feed._storage.get.throws(new Error());
+ globals.sandbox.spy(global.Cu, "reportError");
+
+ try {
+ await feed.refresh({ broadcast: false });
+ } catch (e) {
+ assert.fails();
+ }
+
+ assert.calledOnce(Cu.reportError);
+ });
+ });
+ describe("#updateSectionPrefs", () => {
+ it("should call updateSectionPrefs on UPDATE_SECTION_PREFS", () => {
+ sandbox.stub(feed, "updateSectionPrefs");
+
+ feed.onAction({
+ type: at.UPDATE_SECTION_PREFS,
+ data: { id: "topsites" },
+ });
+
+ assert.calledOnce(feed.updateSectionPrefs);
+ });
+ it("should dispatch TOP_SITES_PREFS_UPDATED", async () => {
+ await feed.updateSectionPrefs({ collapsed: true });
+
+ assert.calledOnce(feed.store.dispatch);
+ assert.calledWithExactly(
+ feed.store.dispatch,
+ ac.BroadcastToContent({
+ type: at.TOP_SITES_PREFS_UPDATED,
+ data: { pref: { collapsed: true } },
+ })
+ );
+ });
+ });
+ describe("#getScreenshotPreview", () => {
+ it("should dispatch preview if request is succesful", async () => {
+ await feed.getScreenshotPreview("custom", 1234);
+
+ assert.calledOnce(feed.store.dispatch);
+ assert.calledWithExactly(
+ feed.store.dispatch,
+ ac.OnlyToOneContent(
+ {
+ data: { preview: FAKE_SCREENSHOT, url: "custom" },
+ type: at.PREVIEW_RESPONSE,
+ },
+ 1234
+ )
+ );
+ });
+ it("should return empty string if request fails", async () => {
+ fakeScreenshot.getScreenshotForURL = sandbox
+ .stub()
+ .returns(Promise.resolve(null));
+ await feed.getScreenshotPreview("custom", 1234);
+
+ assert.calledOnce(feed.store.dispatch);
+ assert.calledWithExactly(
+ feed.store.dispatch,
+ ac.OnlyToOneContent(
+ {
+ data: { preview: "", url: "custom" },
+ type: at.PREVIEW_RESPONSE,
+ },
+ 1234
+ )
+ );
+ });
+ });
+ describe("#_fetchIcon", () => {
+ it("should reuse screenshot on the link", () => {
+ const link = { screenshot: "reuse.png" };
+
+ feed._fetchIcon(link);
+
+ assert.notCalled(fakeScreenshot.getScreenshotForURL);
+ assert.propertyVal(link, "screenshot", "reuse.png");
+ });
+ it("should reuse existing fetching screenshot on the link", async () => {
+ const link = {
+ __sharedCache: { fetchingScreenshot: Promise.resolve("fetching.png") },
+ };
+
+ await feed._fetchIcon(link);
+
+ assert.notCalled(fakeScreenshot.getScreenshotForURL);
+ });
+ it("should get a screenshot if the link is missing it", () => {
+ feed.store.state.Prefs.values[SHOWN_ON_NEWTAB_PREF] = true;
+ feed._fetchIcon(Object.assign({ __sharedCache: {} }, FAKE_LINKS[0]));
+
+ assert.calledOnce(fakeScreenshot.getScreenshotForURL);
+ assert.calledWith(fakeScreenshot.getScreenshotForURL, FAKE_LINKS[0].url);
+ });
+ it("should not get a screenshot if the link is missing it but top sites aren't shown", () => {
+ feed.store.state.Prefs.values[SHOWN_ON_NEWTAB_PREF] = false;
+ feed._fetchIcon(Object.assign({ __sharedCache: {} }, FAKE_LINKS[0]));
+
+ assert.notCalled(fakeScreenshot.getScreenshotForURL);
+ });
+ it("should update the link's cache with a screenshot", async () => {
+ feed.store.state.Prefs.values[SHOWN_ON_NEWTAB_PREF] = true;
+ const updateLink = sandbox.stub();
+ const link = { __sharedCache: { updateLink } };
+
+ await feed._fetchIcon(link);
+
+ assert.calledOnce(updateLink);
+ assert.calledWith(updateLink, "screenshot", FAKE_SCREENSHOT);
+ });
+ it("should skip getting a screenshot if there is a tippy top icon", () => {
+ feed._tippyTopProvider.processSite = site => {
+ site.tippyTopIcon = "icon.png";
+ site.backgroundColor = "#fff";
+ return site;
+ };
+ const link = { url: "example.com" };
+ feed._fetchIcon(link);
+ assert.propertyVal(link, "tippyTopIcon", "icon.png");
+ assert.notProperty(link, "screenshot");
+ assert.notCalled(fakeScreenshot.getScreenshotForURL);
+ });
+ it("should skip getting a screenshot if there is an icon of size greater than 96x96 and no tippy top", () => {
+ const link = {
+ url: "foo.com",
+ favicon: "data:foo",
+ faviconSize: 196,
+ };
+ feed._fetchIcon(link);
+ assert.notProperty(link, "tippyTopIcon");
+ assert.notProperty(link, "screenshot");
+ assert.notCalled(fakeScreenshot.getScreenshotForURL);
+ });
+ it("should use the link's rich icon even if there's a tippy top", () => {
+ feed._tippyTopProvider.processSite = site => {
+ site.tippyTopIcon = "icon.png";
+ site.backgroundColor = "#fff";
+ return site;
+ };
+ const link = {
+ url: "foo.com",
+ favicon: "data:foo",
+ faviconSize: 196,
+ };
+ feed._fetchIcon(link);
+ assert.notProperty(link, "tippyTopIcon");
+ });
+ });
+ describe("#_fetchScreenshot", () => {
+ it("should call maybeCacheScreenshot", async () => {
+ feed.store.state.Prefs.values[SHOWN_ON_NEWTAB_PREF] = true;
+ const updateLink = sinon.stub();
+ const link = {
+ customScreenshotURL: "custom",
+ __sharedCache: { updateLink },
+ };
+ await feed._fetchScreenshot(link, "custom");
+
+ assert.calledOnce(fakeScreenshot.maybeCacheScreenshot);
+ assert.calledWithExactly(
+ fakeScreenshot.maybeCacheScreenshot,
+ link,
+ link.customScreenshotURL,
+ "screenshot",
+ sinon.match.func
+ );
+ });
+ it("should not call maybeCacheScreenshot if screenshot is set", async () => {
+ const updateLink = sinon.stub();
+ const link = {
+ customScreenshotURL: "custom",
+ __sharedCache: { updateLink },
+ screenshot: true,
+ };
+ await feed._fetchScreenshot(link, "custom");
+
+ assert.notCalled(fakeScreenshot.maybeCacheScreenshot);
+ });
+ });
+ describe("#onAction", () => {
+ it("should call getScreenshotPreview on PREVIEW_REQUEST", () => {
+ sandbox.stub(feed, "getScreenshotPreview");
+
+ feed.onAction({
+ type: at.PREVIEW_REQUEST,
+ data: { url: "foo" },
+ meta: { fromTarget: 1234 },
+ });
+
+ assert.calledOnce(feed.getScreenshotPreview);
+ assert.calledWithExactly(feed.getScreenshotPreview, "foo", 1234);
+ });
+ it("should refresh on SYSTEM_TICK", async () => {
+ sandbox.stub(feed, "refresh");
+
+ feed.onAction({ type: at.SYSTEM_TICK });
+
+ assert.calledOnce(feed.refresh);
+ assert.calledWithExactly(feed.refresh, { broadcast: false });
+ });
+ it("should call with correct parameters on TOP_SITES_PIN", () => {
+ const pinAction = {
+ type: at.TOP_SITES_PIN,
+ data: { site: { url: "foo.com" }, index: 7 },
+ };
+ feed.onAction(pinAction);
+ assert.calledOnce(fakeNewTabUtils.pinnedLinks.pin);
+ assert.calledWith(
+ fakeNewTabUtils.pinnedLinks.pin,
+ pinAction.data.site,
+ pinAction.data.index
+ );
+ });
+ it("should call pin on TOP_SITES_PIN", () => {
+ sinon.stub(feed, "pin");
+ const pinExistingAction = {
+ type: at.TOP_SITES_PIN,
+ data: { site: FAKE_LINKS[4], index: 4 },
+ };
+
+ feed.onAction(pinExistingAction);
+
+ assert.calledOnce(feed.pin);
+ });
+ it("should trigger refresh on TOP_SITES_PIN", async () => {
+ sinon.stub(feed, "refresh");
+ const pinExistingAction = {
+ type: at.TOP_SITES_PIN,
+ data: { site: FAKE_LINKS[4], index: 4 },
+ };
+
+ await feed.pin(pinExistingAction);
+
+ assert.calledOnce(feed.refresh);
+ });
+ it("should unblock a previously blocked top site if we are now adding it manually via 'Add a Top Site' option", async () => {
+ const pinAction = {
+ type: at.TOP_SITES_PIN,
+ data: { site: { url: "foo.com" }, index: -1 },
+ };
+ feed.onAction(pinAction);
+ assert.calledWith(fakeNewTabUtils.blockedLinks.unblock, {
+ url: pinAction.data.site.url,
+ });
+ });
+ it("should call insert on TOP_SITES_INSERT", async () => {
+ sinon.stub(feed, "insert");
+ const addAction = {
+ type: at.TOP_SITES_INSERT,
+ data: { site: { url: "foo.com" } },
+ };
+
+ feed.onAction(addAction);
+
+ assert.calledOnce(feed.insert);
+ });
+ it("should trigger refresh on TOP_SITES_INSERT", async () => {
+ sinon.stub(feed, "refresh");
+ const addAction = {
+ type: at.TOP_SITES_INSERT,
+ data: { site: { url: "foo.com" } },
+ };
+
+ await feed.insert(addAction);
+
+ assert.calledOnce(feed.refresh);
+ });
+ it("should call unpin with correct parameters on TOP_SITES_UNPIN", () => {
+ fakeNewTabUtils.pinnedLinks.links = [
+ null,
+ null,
+ { url: "foo.com" },
+ null,
+ null,
+ null,
+ null,
+ null,
+ FAKE_LINKS[0],
+ ];
+ const unpinAction = {
+ type: at.TOP_SITES_UNPIN,
+ data: { site: { url: "foo.com" } },
+ };
+ feed.onAction(unpinAction);
+ assert.calledOnce(fakeNewTabUtils.pinnedLinks.unpin);
+ assert.calledWith(
+ fakeNewTabUtils.pinnedLinks.unpin,
+ unpinAction.data.site
+ );
+ });
+ it("should call refresh without a target if we clear history with PLACES_HISTORY_CLEARED", () => {
+ sandbox.stub(feed, "refresh");
+
+ feed.onAction({ type: at.PLACES_HISTORY_CLEARED });
+
+ assert.calledOnce(feed.refresh);
+ assert.calledWithExactly(feed.refresh, { broadcast: true });
+ });
+ it("should call refresh without a target if we remove a Topsite from history", () => {
+ sandbox.stub(feed, "refresh");
+
+ feed.onAction({ type: at.PLACES_LINK_DELETED });
+
+ assert.calledOnce(feed.refresh);
+ assert.calledWithExactly(feed.refresh, { broadcast: true });
+ });
+ it("should still dispatch an action even if there's no target provided", async () => {
+ sandbox.stub(feed, "_fetchIcon");
+ feed._startedUp = true;
+ await feed.refresh({ broadcast: true });
+ assert.calledOnce(feed.store.dispatch);
+ assert.propertyVal(
+ feed.store.dispatch.firstCall.args[0],
+ "type",
+ at.TOP_SITES_UPDATED
+ );
+ });
+ it("should call init on INIT action", async () => {
+ sinon.stub(feed, "init");
+ feed.onAction({ type: at.INIT });
+ assert.calledOnce(feed.init);
+ });
+ it("should call refresh on PLACES_LINK_BLOCKED action", async () => {
+ sinon.stub(feed, "refresh");
+ await feed.onAction({ type: at.PLACES_LINK_BLOCKED });
+ assert.calledOnce(feed.refresh);
+ assert.calledWithExactly(feed.refresh, { broadcast: true });
+ });
+ it("should call refresh on PLACES_LINKS_CHANGED action", async () => {
+ sinon.stub(feed, "refresh");
+ await feed.onAction({ type: at.PLACES_LINKS_CHANGED });
+ assert.calledOnce(feed.refresh);
+ assert.calledWithExactly(feed.refresh, { broadcast: false });
+ });
+ it("should call pin with correct args on TOP_SITES_INSERT without an index specified", () => {
+ const addAction = {
+ type: at.TOP_SITES_INSERT,
+ data: { site: { url: "foo.bar", label: "foo" } },
+ };
+ feed.onAction(addAction);
+ assert.calledOnce(fakeNewTabUtils.pinnedLinks.pin);
+ assert.calledWith(
+ fakeNewTabUtils.pinnedLinks.pin,
+ addAction.data.site,
+ 0
+ );
+ });
+ it("should call pin with correct args on TOP_SITES_INSERT", () => {
+ const dropAction = {
+ type: at.TOP_SITES_INSERT,
+ data: { site: { url: "foo.bar", label: "foo" }, index: 3 },
+ };
+ feed.onAction(dropAction);
+ assert.calledOnce(fakeNewTabUtils.pinnedLinks.pin);
+ assert.calledWith(
+ fakeNewTabUtils.pinnedLinks.pin,
+ dropAction.data.site,
+ 3
+ );
+ });
+ it("should remove the expiration filter on UNINIT", () => {
+ feed.onAction({ type: "UNINIT" });
+
+ assert.calledOnce(fakePageThumbs.removeExpirationFilter);
+ });
+ it("should call updatePinnedSearchShortcuts on UPDATE_PINNED_SEARCH_SHORTCUTS action", async () => {
+ sinon.stub(feed, "updatePinnedSearchShortcuts");
+ const addedShortcuts = [
+ {
+ url: "https://google.com",
+ searchVendor: "google",
+ label: "google",
+ searchTopSite: true,
+ },
+ ];
+ await feed.onAction({
+ type: at.UPDATE_PINNED_SEARCH_SHORTCUTS,
+ data: { addedShortcuts },
+ });
+ assert.calledOnce(feed.updatePinnedSearchShortcuts);
+ });
+ });
+ describe("#add", () => {
+ it("should pin site in first slot of empty pinned list", () => {
+ const site = { url: "foo.bar", label: "foo" };
+ feed.insert({ data: { site } });
+ assert.calledOnce(fakeNewTabUtils.pinnedLinks.pin);
+ assert.calledWith(fakeNewTabUtils.pinnedLinks.pin, site, 0);
+ });
+ it("should pin site in first slot of pinned list with empty first slot", () => {
+ fakeNewTabUtils.pinnedLinks.links = [null, { url: "example.com" }];
+ const site = { url: "foo.bar", label: "foo" };
+ feed.insert({ data: { site } });
+ assert.calledOnce(fakeNewTabUtils.pinnedLinks.pin);
+ assert.calledWith(fakeNewTabUtils.pinnedLinks.pin, site, 0);
+ });
+ it("should move a pinned site in first slot to the next slot: part 1", () => {
+ const site1 = { url: "example.com" };
+ fakeNewTabUtils.pinnedLinks.links = [site1];
+ const site = { url: "foo.bar", label: "foo" };
+ feed.insert({ data: { site } });
+ assert.calledTwice(fakeNewTabUtils.pinnedLinks.pin);
+ assert.calledWith(fakeNewTabUtils.pinnedLinks.pin, site, 0);
+ assert.calledWith(fakeNewTabUtils.pinnedLinks.pin, site1, 1);
+ });
+ it("should move a pinned site in first slot to the next slot: part 2", () => {
+ const site1 = { url: "example.com" };
+ const site2 = { url: "example.org" };
+ fakeNewTabUtils.pinnedLinks.links = [site1, null, site2];
+ const site = { url: "foo.bar", label: "foo" };
+ feed.insert({ data: { site } });
+ assert.calledTwice(fakeNewTabUtils.pinnedLinks.pin);
+ assert.calledWith(fakeNewTabUtils.pinnedLinks.pin, site, 0);
+ assert.calledWith(fakeNewTabUtils.pinnedLinks.pin, site1, 1);
+ });
+ it("should unpin the last site if all slots are already pinned", () => {
+ const site1 = { url: "example.com" };
+ const site2 = { url: "example.org" };
+ const site3 = { url: "example.net" };
+ const site4 = { url: "example.biz" };
+ const site5 = { url: "example.info" };
+ const site6 = { url: "example.news" };
+ const site7 = { url: "example.lol" };
+ const site8 = { url: "example.golf" };
+ fakeNewTabUtils.pinnedLinks.links = [
+ site1,
+ site2,
+ site3,
+ site4,
+ site5,
+ site6,
+ site7,
+ site8,
+ ];
+ feed.store.state.Prefs.values.topSitesRows = 1;
+ const site = { url: "foo.bar", label: "foo" };
+ feed.insert({ data: { site } });
+ assert.equal(fakeNewTabUtils.pinnedLinks.pin.callCount, 8);
+ assert.calledWith(fakeNewTabUtils.pinnedLinks.pin, site, 0);
+ assert.calledWith(fakeNewTabUtils.pinnedLinks.pin, site1, 1);
+ assert.calledWith(fakeNewTabUtils.pinnedLinks.pin, site2, 2);
+ assert.calledWith(fakeNewTabUtils.pinnedLinks.pin, site3, 3);
+ assert.calledWith(fakeNewTabUtils.pinnedLinks.pin, site4, 4);
+ assert.calledWith(fakeNewTabUtils.pinnedLinks.pin, site5, 5);
+ assert.calledWith(fakeNewTabUtils.pinnedLinks.pin, site6, 6);
+ assert.calledWith(fakeNewTabUtils.pinnedLinks.pin, site7, 7);
+ });
+ });
+ describe("#pin", () => {
+ it("should pin site in specified slot empty pinned list", async () => {
+ const site = {
+ url: "foo.bar",
+ label: "foo",
+ customScreenshotURL: "screenshot",
+ };
+ await feed.pin({ data: { index: 2, site } });
+ assert.calledOnce(fakeNewTabUtils.pinnedLinks.pin);
+ assert.calledWith(fakeNewTabUtils.pinnedLinks.pin, site, 2);
+ });
+ it("should lookup the link object to update the custom screenshot", async () => {
+ const site = {
+ url: "foo.bar",
+ label: "foo",
+ customScreenshotURL: "screenshot",
+ };
+ sandbox.spy(feed.pinnedCache, "request");
+
+ await feed.pin({ data: { index: 2, site } });
+
+ assert.calledOnce(feed.pinnedCache.request);
+ });
+ it("should lookup the link object to update the custom screenshot", async () => {
+ const site = { url: "foo.bar", label: "foo", customScreenshotURL: null };
+ sandbox.spy(feed.pinnedCache, "request");
+
+ await feed.pin({ data: { index: 2, site } });
+
+ assert.calledOnce(feed.pinnedCache.request);
+ });
+ it("should not do a link object lookup if custom screenshot field is not set", async () => {
+ const site = { url: "foo.bar", label: "foo" };
+ sandbox.spy(feed.pinnedCache, "request");
+
+ await feed.pin({ data: { index: 2, site } });
+
+ assert.notCalled(feed.pinnedCache.request);
+ });
+ it("should pin site in specified slot of pinned list that is free", () => {
+ fakeNewTabUtils.pinnedLinks.links = [null, { url: "example.com" }];
+ const site = { url: "foo.bar", label: "foo" };
+ feed.pin({ data: { index: 2, site } });
+ assert.calledOnce(fakeNewTabUtils.pinnedLinks.pin);
+ assert.calledWith(fakeNewTabUtils.pinnedLinks.pin, site, 2);
+ });
+ it("should save the searchTopSite attribute if set", () => {
+ fakeNewTabUtils.pinnedLinks.links = [null, { url: "example.com" }];
+ const site = { url: "foo.bar", label: "foo", searchTopSite: true };
+ feed.pin({ data: { index: 2, site } });
+ assert.calledOnce(fakeNewTabUtils.pinnedLinks.pin);
+ assert.propertyVal(
+ fakeNewTabUtils.pinnedLinks.pin.firstCall.args[0],
+ "searchTopSite",
+ true
+ );
+ });
+ it("should NOT move a pinned site in specified slot to the next slot", () => {
+ fakeNewTabUtils.pinnedLinks.links = [null, null, { url: "example.com" }];
+ const site = { url: "foo.bar", label: "foo" };
+ feed.pin({ data: { index: 2, site } });
+ assert.calledOnce(fakeNewTabUtils.pinnedLinks.pin);
+ assert.calledWith(fakeNewTabUtils.pinnedLinks.pin, site, 2);
+ });
+ it("should properly update LinksCache object properties between migrations", async () => {
+ fakeNewTabUtils.pinnedLinks.links = [{ url: "https://foo.com/" }];
+
+ let pinnedLinks = await feed.pinnedCache.request();
+ assert.equal(pinnedLinks.length, 1);
+ feed.pinnedCache.expire();
+ pinnedLinks[0].__sharedCache.updateLink("screenshot", "foo");
+
+ pinnedLinks = await feed.pinnedCache.request();
+ assert.propertyVal(pinnedLinks[0], "screenshot", "foo");
+
+ // Force cache expiration in order to trigger a migration of objects
+ feed.pinnedCache.expire();
+ pinnedLinks[0].__sharedCache.updateLink("screenshot", "bar");
+
+ pinnedLinks = await feed.pinnedCache.request();
+ assert.propertyVal(pinnedLinks[0], "screenshot", "bar");
+ });
+ it("should call insert if index < 0", () => {
+ const site = { url: "foo.bar", label: "foo" };
+ const action = { data: { index: -1, site } };
+
+ sandbox.spy(feed, "insert");
+ feed.pin(action);
+
+ assert.calledOnce(feed.insert);
+ assert.calledWithExactly(feed.insert, action);
+ });
+ it("should not call insert if index == 0", () => {
+ const site = { url: "foo.bar", label: "foo" };
+ const action = { data: { index: 0, site } };
+
+ sandbox.spy(feed, "insert");
+ feed.pin(action);
+
+ assert.notCalled(feed.insert);
+ });
+ });
+ describe("clearLinkCustomScreenshot", () => {
+ it("should remove cached screenshot if custom url changes", async () => {
+ const stub = sandbox.stub();
+ sandbox.stub(feed.pinnedCache, "request").returns(
+ Promise.resolve([
+ {
+ url: "foo",
+ customScreenshotURL: "old_screenshot",
+ __sharedCache: { updateLink: stub },
+ },
+ ])
+ );
+
+ await feed._clearLinkCustomScreenshot({
+ url: "foo",
+ customScreenshotURL: "new_screenshot",
+ });
+
+ assert.calledOnce(stub);
+ assert.calledWithExactly(stub, "screenshot", undefined);
+ });
+ it("should remove cached screenshot if custom url is removed", async () => {
+ const stub = sandbox.stub();
+ sandbox.stub(feed.pinnedCache, "request").returns(
+ Promise.resolve([
+ {
+ url: "foo",
+ customScreenshotURL: "old_screenshot",
+ __sharedCache: { updateLink: stub },
+ },
+ ])
+ );
+
+ await feed._clearLinkCustomScreenshot({
+ url: "foo",
+ customScreenshotURL: "new_screenshot",
+ });
+
+ assert.calledOnce(stub);
+ assert.calledWithExactly(stub, "screenshot", undefined);
+ });
+ });
+ describe("#drop", () => {
+ it("should correctly handle different index values", () => {
+ let index = -1;
+ const site = { url: "foo.bar", label: "foo" };
+ const action = { data: { index, site } };
+
+ feed.insert(action);
+
+ assert.calledWith(fakeNewTabUtils.pinnedLinks.pin, site, 0);
+
+ index = undefined;
+ feed.insert(action);
+
+ assert.calledWith(fakeNewTabUtils.pinnedLinks.pin, site, 0);
+ });
+ it("should pin site in specified slot that is free", () => {
+ fakeNewTabUtils.pinnedLinks.links = [null, { url: "example.com" }];
+ const site = { url: "foo.bar", label: "foo" };
+ feed.insert({ data: { index: 2, site, draggedFromIndex: 0 } });
+ assert.calledOnce(fakeNewTabUtils.pinnedLinks.pin);
+ assert.calledWith(fakeNewTabUtils.pinnedLinks.pin, site, 2);
+ });
+ it("should move a pinned site in specified slot to the next slot", () => {
+ fakeNewTabUtils.pinnedLinks.links = [null, null, { url: "example.com" }];
+ const site = { url: "foo.bar", label: "foo" };
+ feed.insert({ data: { index: 2, site, draggedFromIndex: 3 } });
+ assert.calledTwice(fakeNewTabUtils.pinnedLinks.pin);
+ assert.calledWith(fakeNewTabUtils.pinnedLinks.pin, site, 2);
+ assert.calledWith(
+ fakeNewTabUtils.pinnedLinks.pin,
+ { url: "example.com" },
+ 3
+ );
+ });
+ it("should move pinned sites in the direction of the dragged site", () => {
+ const site1 = { url: "foo.bar", label: "foo" };
+ const site2 = { url: "example.com", label: "example" };
+ fakeNewTabUtils.pinnedLinks.links = [null, null, site2];
+ feed.insert({ data: { index: 2, site: site1, draggedFromIndex: 0 } });
+ assert.calledTwice(fakeNewTabUtils.pinnedLinks.pin);
+ assert.calledWith(fakeNewTabUtils.pinnedLinks.pin, site1, 2);
+ assert.calledWith(fakeNewTabUtils.pinnedLinks.pin, site2, 1);
+ fakeNewTabUtils.pinnedLinks.pin.resetHistory();
+ feed.insert({ data: { index: 2, site: site1, draggedFromIndex: 5 } });
+ assert.calledTwice(fakeNewTabUtils.pinnedLinks.pin);
+ assert.calledWith(fakeNewTabUtils.pinnedLinks.pin, site1, 2);
+ assert.calledWith(fakeNewTabUtils.pinnedLinks.pin, site2, 3);
+ });
+ it("should not insert past the visible top sites", () => {
+ const site1 = { url: "foo.bar", label: "foo" };
+ feed.insert({ data: { index: 42, site: site1, draggedFromIndex: 0 } });
+ assert.notCalled(fakeNewTabUtils.pinnedLinks.pin);
+ });
+ });
+ describe("integration", () => {
+ let resolvers = [];
+ beforeEach(() => {
+ feed.store.dispatch = sandbox.stub().callsFake(() => {
+ resolvers.shift()();
+ });
+ feed._startedUp = true;
+ sandbox.stub(feed, "_fetchScreenshot");
+ });
+ afterEach(() => {
+ sandbox.restore();
+ });
+
+ const forDispatch = action =>
+ new Promise(resolve => {
+ resolvers.push(resolve);
+ feed.onAction(action);
+ });
+
+ it("should add a pinned site and remove it", async () => {
+ feed._requestRichIcon = sinon.stub();
+ const url = "https://pin.me";
+ fakeNewTabUtils.pinnedLinks.pin = sandbox.stub().callsFake(link => {
+ fakeNewTabUtils.pinnedLinks.links.push(link);
+ });
+
+ await forDispatch({ type: at.TOP_SITES_INSERT, data: { site: { url } } });
+ fakeNewTabUtils.pinnedLinks.links.pop();
+ await forDispatch({ type: at.PLACES_LINK_BLOCKED });
+
+ assert.calledTwice(feed.store.dispatch);
+ assert.equal(
+ feed.store.dispatch.firstCall.args[0].data.links[0].url,
+ url
+ );
+ assert.equal(
+ feed.store.dispatch.secondCall.args[0].data.links[0].url,
+ FAKE_LINKS[0].url
+ );
+ });
+ });
+
+ describe("improvesearch.noDefaultSearchTile experiment", () => {
+ const NO_DEFAULT_SEARCH_TILE_PREF = "improvesearch.noDefaultSearchTile";
+ beforeEach(() => {
+ global.Services.search.getDefault = async () => ({
+ identifier: "google",
+ searchForm: "google.com",
+ });
+ feed.store.state.Prefs.values[NO_DEFAULT_SEARCH_TILE_PREF] = true;
+ });
+ it("should filter out alexa top 5 search from the default sites", async () => {
+ const TOP_5_TEST = [
+ "google.com",
+ "search.yahoo.com",
+ "yahoo.com",
+ "bing.com",
+ "ask.com",
+ "duckduckgo.com",
+ ];
+ links = [{ url: "amazon.com" }, ...TOP_5_TEST.map(url => ({ url }))];
+ const urlsReturned = (await feed.getLinksWithDefaults()).map(
+ link => link.url
+ );
+ assert.include(urlsReturned, "amazon.com");
+ TOP_5_TEST.forEach(url => assert.notInclude(urlsReturned, url));
+ });
+ it("should not filter out alexa, default search from the query results if the experiment pref is off", async () => {
+ links = [
+ { url: "google.com" },
+ { url: "foo.com" },
+ { url: "duckduckgo" },
+ ];
+ feed.store.state.Prefs.values[NO_DEFAULT_SEARCH_TILE_PREF] = false;
+ const urlsReturned = (await feed.getLinksWithDefaults()).map(
+ link => link.url
+ );
+ assert.include(urlsReturned, "google.com");
+ });
+ it("should filter out the current default search from the default sites", async () => {
+ feed._currentSearchHostname = "amazon";
+ feed.onAction({
+ type: at.PREFS_INITIAL_VALUES,
+ data: { "default.sites": "google.com,amazon.com" },
+ });
+ links = [{ url: "foo.com" }];
+ const urlsReturned = (await feed.getLinksWithDefaults()).map(
+ link => link.url
+ );
+ assert.notInclude(urlsReturned, "amazon.com");
+ });
+ it("should not filter out current default search from pinned sites even if it matches the current default search", async () => {
+ links = [{ url: "foo.com" }];
+ fakeNewTabUtils.pinnedLinks.links = [{ url: "google.com" }];
+ const urlsReturned = (await feed.getLinksWithDefaults()).map(
+ link => link.url
+ );
+ assert.include(urlsReturned, "google.com");
+ });
+ it("should call refresh and set ._currentSearchHostname to the new engine hostname when the the default search engine has been set", () => {
+ sinon.stub(feed, "refresh");
+ sandbox
+ .stub(global.Services.search, "defaultEngine")
+ .value({ identifier: "ddg", searchForm: "duckduckgo.com" });
+ feed.observe(null, "browser-search-engine-modified", "engine-default");
+ assert.equal(feed._currentSearchHostname, "duckduckgo");
+ assert.calledOnce(feed.refresh);
+ });
+ it("should call refresh when the experiment pref has changed", () => {
+ sinon.stub(feed, "refresh");
+
+ feed.onAction({
+ type: at.PREF_CHANGED,
+ data: { name: NO_DEFAULT_SEARCH_TILE_PREF, value: true },
+ });
+ assert.calledOnce(feed.refresh);
+
+ feed.onAction({
+ type: at.PREF_CHANGED,
+ data: { name: NO_DEFAULT_SEARCH_TILE_PREF, value: false },
+ });
+ assert.calledTwice(feed.refresh);
+ });
+ });
+
+ describe("improvesearch.topSitesSearchShortcuts", () => {
+ beforeEach(() => {
+ feed.store.state.Prefs.values[SEARCH_SHORTCUTS_EXPERIMENT_PREF] = true;
+ feed.store.state.Prefs.values[SEARCH_SHORTCUTS_SEARCH_ENGINES_PREF] =
+ "google,amazon";
+ feed.store.state.Prefs.values[SEARCH_SHORTCUTS_HAVE_PINNED_PREF] = "";
+ const searchEngines = [
+ { aliases: ["@google"] },
+ { aliases: ["@amazon"] },
+ ];
+ global.Services.search.getAppProvidedEngines = async () => searchEngines;
+ fakeNewTabUtils.pinnedLinks.pin = sinon
+ .stub()
+ .callsFake((site, index) => {
+ fakeNewTabUtils.pinnedLinks.links[index] = site;
+ });
+ });
+
+ it("should properly disable search improvements if the pref is off", async () => {
+ sandbox.stub(global.Services.prefs, "clearUserPref");
+ sandbox.spy(feed.pinnedCache, "expire");
+ sandbox.spy(feed, "refresh");
+
+ // an actual implementation of unpin (until we can get a mochitest for search improvements)
+ fakeNewTabUtils.pinnedLinks.unpin = sinon.stub().callsFake(site => {
+ let index = -1;
+ for (let i = 0; i < fakeNewTabUtils.pinnedLinks.links.length; i++) {
+ let link = fakeNewTabUtils.pinnedLinks.links[i];
+ if (link && link.url === site.url) {
+ index = i;
+ }
+ }
+ if (index > -1) {
+ fakeNewTabUtils.pinnedLinks.links[index] = null;
+ }
+ });
+
+ // ensure we've inserted search shorcuts + pin an additional site in space 4
+ await feed._maybeInsertSearchShortcuts(fakeNewTabUtils.pinnedLinks.links);
+ fakeNewTabUtils.pinnedLinks.pin({ url: "https://dontunpinme.com" }, 3);
+
+ // turn the experiment off
+ feed.onAction({
+ type: at.PREF_CHANGED,
+ data: { name: SEARCH_SHORTCUTS_EXPERIMENT_PREF, value: false },
+ });
+
+ // check we cleared the pref, expired the pinned cache, and refreshed the feed
+ assert.calledWith(
+ global.Services.prefs.clearUserPref,
+ `browser.newtabpage.activity-stream.${SEARCH_SHORTCUTS_HAVE_PINNED_PREF}`
+ );
+ assert.calledOnce(feed.pinnedCache.expire);
+ assert.calledWith(feed.refresh, { broadcast: true });
+
+ // check that the search shortcuts were removed from the list of pinned sites
+ const urlsReturned = fakeNewTabUtils.pinnedLinks.links
+ .filter(s => s)
+ .map(link => link.url);
+ assert.notInclude(urlsReturned, "https://amazon.com");
+ assert.notInclude(urlsReturned, "https://google.com");
+ assert.include(urlsReturned, "https://dontunpinme.com");
+
+ // check that the positions where the search shortcuts were null, and the additional pinned site is untouched in space 4
+ assert.equal(fakeNewTabUtils.pinnedLinks.links[0], null);
+ assert.equal(fakeNewTabUtils.pinnedLinks.links[1], null);
+ assert.equal(fakeNewTabUtils.pinnedLinks.links[2], undefined);
+ assert.deepEqual(fakeNewTabUtils.pinnedLinks.links[3], {
+ url: "https://dontunpinme.com",
+ });
+ });
+
+ it("should updateCustomSearchShortcuts when experiment pref is turned on", async () => {
+ feed.store.state.Prefs.values[SEARCH_SHORTCUTS_EXPERIMENT_PREF] = false;
+ feed.updateCustomSearchShortcuts = sinon.spy();
+
+ // turn the experiment on
+ feed.onAction({
+ type: at.PREF_CHANGED,
+ data: { name: SEARCH_SHORTCUTS_EXPERIMENT_PREF, value: true },
+ });
+
+ assert.calledOnce(feed.updateCustomSearchShortcuts);
+ });
+
+ it("should filter out default top sites that match a hostname of a search shortcut if previously blocked", async () => {
+ feed.refreshDefaults("https://amazon.ca");
+ fakeNewTabUtils.blockedLinks.links = [{ url: "https://amazon.com" }];
+ fakeNewTabUtils.blockedLinks.isBlocked = site =>
+ fakeNewTabUtils.blockedLinks.links[0].url === site.url;
+ const urlsReturned = (await feed.getLinksWithDefaults()).map(
+ link => link.url
+ );
+ assert.notInclude(urlsReturned, "https://amazon.ca");
+ });
+
+ it("should update frecent search topsite icon", async () => {
+ feed._tippyTopProvider.processSite = site => {
+ site.tippyTopIcon = "icon.png";
+ site.backgroundColor = "#fff";
+ return site;
+ };
+ links = [{ url: "google.com" }];
+
+ const urlsReturned = await feed.getLinksWithDefaults();
+
+ const defaultSearchTopsite = urlsReturned.find(
+ s => s.url === "google.com"
+ );
+ assert.propertyVal(defaultSearchTopsite, "searchTopSite", true);
+ assert.equal(defaultSearchTopsite.tippyTopIcon, "icon.png");
+ assert.equal(defaultSearchTopsite.backgroundColor, "#fff");
+ });
+ it("should update default search topsite icon", async () => {
+ feed._tippyTopProvider.processSite = site => {
+ site.tippyTopIcon = "icon.png";
+ site.backgroundColor = "#fff";
+ return site;
+ };
+ links = [{ url: "foo.com" }];
+ feed.onAction({
+ type: at.PREFS_INITIAL_VALUES,
+ data: { "default.sites": "google.com,amazon.com" },
+ });
+
+ const urlsReturned = await feed.getLinksWithDefaults();
+
+ const defaultSearchTopsite = urlsReturned.find(
+ s => s.url === "amazon.com"
+ );
+ assert.propertyVal(defaultSearchTopsite, "searchTopSite", true);
+ assert.equal(defaultSearchTopsite.tippyTopIcon, "icon.png");
+ assert.equal(defaultSearchTopsite.backgroundColor, "#fff");
+ });
+ it("should dispatch UPDATE_SEARCH_SHORTCUTS on updateCustomSearchShortcuts", async () => {
+ feed.store.state.Prefs.values["improvesearch.noDefaultSearchTile"] = true;
+ await feed.updateCustomSearchShortcuts();
+ assert.calledOnce(feed.store.dispatch);
+ assert.calledWith(feed.store.dispatch, {
+ data: {
+ searchShortcuts: [
+ {
+ keyword: "@google",
+ shortURL: "google",
+ url: "https://google.com",
+ },
+ {
+ keyword: "@amazon",
+ shortURL: "amazon",
+ url: "https://amazon.com",
+ },
+ ],
+ },
+ meta: {
+ from: "ActivityStream:Main",
+ to: "ActivityStream:Content",
+ isStartup: false,
+ },
+ type: "UPDATE_SEARCH_SHORTCUTS",
+ });
+ });
+
+ describe("_maybeInsertSearchShortcuts", () => {
+ beforeEach(() => {
+ // Default is one row
+ feed.store.state.Prefs.values.topSitesRows = TOP_SITES_DEFAULT_ROWS;
+ // Eight slots per row
+ fakeNewTabUtils.pinnedLinks.links = [
+ { url: "" },
+ { url: "" },
+ { url: "" },
+ null,
+ { url: "" },
+ { url: "" },
+ null,
+ { url: "" },
+ ];
+ });
+
+ it("should be called on getLinksWithDefaults", async () => {
+ sandbox.spy(feed, "_maybeInsertSearchShortcuts");
+ await feed.getLinksWithDefaults();
+ assert.calledOnce(feed._maybeInsertSearchShortcuts);
+ });
+
+ it("should do nothing and return false if the experiment is disabled", async () => {
+ feed.store.state.Prefs.values[SEARCH_SHORTCUTS_EXPERIMENT_PREF] = false;
+ assert.isFalse(
+ await feed._maybeInsertSearchShortcuts(
+ fakeNewTabUtils.pinnedLinks.links
+ )
+ );
+ assert.notCalled(fakeNewTabUtils.pinnedLinks.pin);
+ });
+
+ it("should pin shortcuts in the correct order, into the available unpinned slots", async () => {
+ await feed._maybeInsertSearchShortcuts(
+ fakeNewTabUtils.pinnedLinks.links
+ );
+ // The shouldPin pref is "google,amazon" so expect the shortcuts in that order
+ assert.deepEqual(fakeNewTabUtils.pinnedLinks.links[3], {
+ url: "https://google.com",
+ searchTopSite: true,
+ label: "@google",
+ });
+ assert.deepEqual(fakeNewTabUtils.pinnedLinks.links[6], {
+ url: "https://amazon.com",
+ searchTopSite: true,
+ label: "@amazon",
+ });
+ });
+
+ it("should not pin shortcuts for the current default search engine", async () => {
+ feed._currentSearchHostname = "google";
+ await feed._maybeInsertSearchShortcuts(
+ fakeNewTabUtils.pinnedLinks.links
+ );
+ assert.deepEqual(fakeNewTabUtils.pinnedLinks.links[3], {
+ url: "https://amazon.com",
+ searchTopSite: true,
+ label: "@amazon",
+ });
+ });
+
+ it("should only pin the first shortcut if there's only one available slot", async () => {
+ fakeNewTabUtils.pinnedLinks.links[3] = { url: "" };
+ await feed._maybeInsertSearchShortcuts(
+ fakeNewTabUtils.pinnedLinks.links
+ );
+ // The first item in the shouldPin pref is "google" so expect only Google to be pinned
+ assert.ok(
+ fakeNewTabUtils.pinnedLinks.links.find(
+ s => s && s.url === "https://google.com"
+ )
+ );
+ assert.notOk(
+ fakeNewTabUtils.pinnedLinks.links.find(
+ s => s && s.url === "https://amazon.com"
+ )
+ );
+ });
+
+ it("should pin none if there's no available slot", async () => {
+ fakeNewTabUtils.pinnedLinks.links[3] = { url: "" };
+ fakeNewTabUtils.pinnedLinks.links[6] = { url: "" };
+ await feed._maybeInsertSearchShortcuts(
+ fakeNewTabUtils.pinnedLinks.links
+ );
+ assert.notOk(
+ fakeNewTabUtils.pinnedLinks.links.find(
+ s => s && s.url === "https://google.com"
+ )
+ );
+ assert.notOk(
+ fakeNewTabUtils.pinnedLinks.links.find(
+ s => s && s.url === "https://amazon.com"
+ )
+ );
+ });
+
+ it("should not pin a shortcut if the corresponding search engine is not available", async () => {
+ // Make Amazon search engine unavailable
+ global.Services.search.getAppProvidedEngines = async () => [
+ { aliases: ["@google"] },
+ ];
+ fakeNewTabUtils.pinnedLinks.links.fill(null);
+ await feed._maybeInsertSearchShortcuts(
+ fakeNewTabUtils.pinnedLinks.links
+ );
+ assert.notOk(
+ fakeNewTabUtils.pinnedLinks.links.find(
+ s => s && s.url === "https://amazon.com"
+ )
+ );
+ });
+
+ it("should not pin a search shortcut if it's been pinned before", async () => {
+ fakeNewTabUtils.pinnedLinks.links.fill(null);
+ feed.store.state.Prefs.values[SEARCH_SHORTCUTS_HAVE_PINNED_PREF] =
+ "google,amazon";
+ await feed._maybeInsertSearchShortcuts(
+ fakeNewTabUtils.pinnedLinks.links
+ );
+ assert.notOk(
+ fakeNewTabUtils.pinnedLinks.links.find(
+ s => s && s.url === "https://google.com"
+ )
+ );
+ assert.notOk(
+ fakeNewTabUtils.pinnedLinks.links.find(
+ s => s && s.url === "https://amazon.com"
+ )
+ );
+
+ fakeNewTabUtils.pinnedLinks.links.fill(null);
+ feed.store.state.Prefs.values[SEARCH_SHORTCUTS_HAVE_PINNED_PREF] =
+ "amazon";
+ await feed._maybeInsertSearchShortcuts(
+ fakeNewTabUtils.pinnedLinks.links
+ );
+ assert.ok(
+ fakeNewTabUtils.pinnedLinks.links.find(
+ s => s && s.url === "https://google.com"
+ )
+ );
+ assert.notOk(
+ fakeNewTabUtils.pinnedLinks.links.find(
+ s => s && s.url === "https://amazon.com"
+ )
+ );
+
+ fakeNewTabUtils.pinnedLinks.links.fill(null);
+ feed.store.state.Prefs.values[SEARCH_SHORTCUTS_HAVE_PINNED_PREF] =
+ "google";
+ await feed._maybeInsertSearchShortcuts(
+ fakeNewTabUtils.pinnedLinks.links
+ );
+ assert.notOk(
+ fakeNewTabUtils.pinnedLinks.links.find(
+ s => s && s.url === "https://google.com"
+ )
+ );
+ assert.ok(
+ fakeNewTabUtils.pinnedLinks.links.find(
+ s => s && s.url === "https://amazon.com"
+ )
+ );
+ });
+
+ it("should record the insertion of a search shortcut", async () => {
+ feed.store.state.Prefs.values[SEARCH_SHORTCUTS_HAVE_PINNED_PREF] = "";
+ // Fill up one slot, so there's only one left - to be filled by Google
+ fakeNewTabUtils.pinnedLinks.links[3] = { url: "" };
+ await feed._maybeInsertSearchShortcuts(
+ fakeNewTabUtils.pinnedLinks.links
+ );
+ assert.calledWithExactly(feed.store.dispatch, {
+ data: { name: SEARCH_SHORTCUTS_HAVE_PINNED_PREF, value: "google" },
+ meta: { from: "ActivityStream:Content", to: "ActivityStream:Main" },
+ type: "SET_PREF",
+ });
+ });
+ });
+ });
+
+ describe("updatePinnedSearchShortcuts", () => {
+ it("should unpin a shortcut in deletedShortcuts", () => {
+ const deletedShortcuts = [
+ {
+ url: "https://google.com",
+ searchVendor: "google",
+ label: "google",
+ searchTopSite: true,
+ },
+ ];
+ const addedShortcuts = [];
+ fakeNewTabUtils.pinnedLinks.links = [
+ null,
+ null,
+ {
+ url: "https://amazon.com",
+ searchVendor: "amazon",
+ label: "amazon",
+ searchTopSite: true,
+ },
+ ];
+ feed.updatePinnedSearchShortcuts({ addedShortcuts, deletedShortcuts });
+ assert.notCalled(fakeNewTabUtils.pinnedLinks.pin);
+ assert.calledOnce(fakeNewTabUtils.pinnedLinks.unpin);
+ assert.calledWith(fakeNewTabUtils.pinnedLinks.unpin, {
+ url: "https://google.com",
+ });
+ });
+
+ it("should pin a shortcut in addedShortcuts", () => {
+ const addedShortcuts = [
+ {
+ url: "https://google.com",
+ searchVendor: "google",
+ label: "google",
+ searchTopSite: true,
+ },
+ ];
+ const deletedShortcuts = [];
+ fakeNewTabUtils.pinnedLinks.links = [
+ null,
+ null,
+ {
+ url: "https://amazon.com",
+ searchVendor: "amazon",
+ label: "amazon",
+ searchTopSite: true,
+ },
+ ];
+ feed.updatePinnedSearchShortcuts({ addedShortcuts, deletedShortcuts });
+ assert.notCalled(fakeNewTabUtils.pinnedLinks.unpin);
+ assert.calledOnce(fakeNewTabUtils.pinnedLinks.pin);
+ assert.calledWith(
+ fakeNewTabUtils.pinnedLinks.pin,
+ {
+ label: "google",
+ searchTopSite: true,
+ searchVendor: "google",
+ url: "https://google.com",
+ },
+ 0
+ );
+ });
+
+ it("should pin and unpin in the same action", () => {
+ const addedShortcuts = [
+ {
+ url: "https://google.com",
+ searchVendor: "google",
+ label: "google",
+ searchTopSite: true,
+ },
+ {
+ url: "https://ebay.com",
+ searchVendor: "ebay",
+ label: "ebay",
+ searchTopSite: true,
+ },
+ ];
+ const deletedShortcuts = [
+ {
+ url: "https://amazon.com",
+ searchVendor: "amazon",
+ label: "amazon",
+ searchTopSite: true,
+ },
+ ];
+ fakeNewTabUtils.pinnedLinks.links = [
+ { url: "https://foo.com" },
+ {
+ url: "https://amazon.com",
+ searchVendor: "amazon",
+ label: "amazon",
+ searchTopSite: true,
+ },
+ ];
+ feed.updatePinnedSearchShortcuts({ addedShortcuts, deletedShortcuts });
+ assert.calledOnce(fakeNewTabUtils.pinnedLinks.unpin);
+ assert.calledTwice(fakeNewTabUtils.pinnedLinks.pin);
+ });
+
+ it("should pin a shortcut in addedShortcuts even if pinnedLinks is full", () => {
+ const addedShortcuts = [
+ {
+ url: "https://google.com",
+ searchVendor: "google",
+ label: "google",
+ searchTopSite: true,
+ },
+ ];
+ const deletedShortcuts = [];
+ fakeNewTabUtils.pinnedLinks.links = FAKE_LINKS;
+ feed.updatePinnedSearchShortcuts({ addedShortcuts, deletedShortcuts });
+ assert.notCalled(fakeNewTabUtils.pinnedLinks.unpin);
+ assert.calledWith(
+ fakeNewTabUtils.pinnedLinks.pin,
+ { label: "google", searchTopSite: true, url: "https://google.com" },
+ 0
+ );
+ });
+ });
+
+ describe("#_attachTippyTopIconForSearchShortcut", () => {
+ beforeEach(() => {
+ feed._tippyTopProvider.processSite = site => {
+ if (site.url === "https://www.yandex.ru/") {
+ site.tippyTopIcon = "yandex-ru.png";
+ site.smallFavicon = "yandex-ru.ico";
+ } else if (
+ site.url === "https://www.yandex.com/" ||
+ site.url === "https://yandex.com"
+ ) {
+ site.tippyTopIcon = "yandex.png";
+ site.smallFavicon = "yandex.ico";
+ } else {
+ site.tippyTopIcon = "google.png";
+ site.smallFavicon = "google.ico";
+ }
+ return site;
+ };
+ });
+
+ it("should choose the -ru icons for Yandex search shortcut", async () => {
+ sandbox.stub(global.Services.search, "getEngineByAlias").resolves({
+ wrappedJSObject: { _searchForm: "https://www.yandex.ru/" },
+ });
+
+ const link = { url: "https://yandex.com" };
+ await feed._attachTippyTopIconForSearchShortcut(link, "@yandex");
+
+ assert.equal(link.tippyTopIcon, "yandex-ru.png");
+ assert.equal(link.smallFavicon, "yandex-ru.ico");
+ assert.equal(link.url, "https://yandex.com");
+ });
+
+ it("should choose -com icons for Yandex search shortcut", async () => {
+ sandbox.stub(global.Services.search, "getEngineByAlias").resolves({
+ wrappedJSObject: { _searchForm: "https://www.yandex.com/" },
+ });
+
+ const link = { url: "https://yandex.com" };
+ await feed._attachTippyTopIconForSearchShortcut(link, "@yandex");
+
+ assert.equal(link.tippyTopIcon, "yandex.png");
+ assert.equal(link.smallFavicon, "yandex.ico");
+ assert.equal(link.url, "https://yandex.com");
+ });
+
+ it("should use the -com icons if can't fetch the search form URL", async () => {
+ sandbox.stub(global.Services.search, "getEngineByAlias").resolves(null);
+
+ const link = { url: "https://yandex.com" };
+ await feed._attachTippyTopIconForSearchShortcut(link, "@yandex");
+
+ assert.equal(link.tippyTopIcon, "yandex.png");
+ assert.equal(link.smallFavicon, "yandex.ico");
+ assert.equal(link.url, "https://yandex.com");
+ });
+
+ it("should choose the correct icon for other non-yandex search shortcut", async () => {
+ sandbox.stub(global.Services.search, "getEngineByAlias").resolves({
+ wrappedJSObject: { _searchForm: "https://www.google.com/" },
+ });
+
+ const link = { url: "https://google.com" };
+ await feed._attachTippyTopIconForSearchShortcut(link, "@google");
+
+ assert.equal(link.tippyTopIcon, "google.png");
+ assert.equal(link.smallFavicon, "google.ico");
+ assert.equal(link.url, "https://google.com");
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/lib/TopStoriesFeed.test.js b/browser/components/newtab/test/unit/lib/TopStoriesFeed.test.js
new file mode 100644
index 0000000000..ad281bdef9
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/TopStoriesFeed.test.js
@@ -0,0 +1,2252 @@
+import { FakePrefs, GlobalOverrider } from "test/unit/utils";
+import { actionTypes as at } from "common/Actions.jsm";
+import injector from "inject!lib/TopStoriesFeed.jsm";
+
+describe("Top Stories Feed", () => {
+ let TopStoriesFeed;
+ let STORIES_UPDATE_TIME;
+ let TOPICS_UPDATE_TIME;
+ let SECTION_ID;
+ let SPOC_IMPRESSION_TRACKING_PREF;
+ let REC_IMPRESSION_TRACKING_PREF;
+ let MIN_DOMAIN_AFFINITIES_UPDATE_TIME;
+ let DEFAULT_RECS_EXPIRE_TIME;
+ let instance;
+ let clock;
+ let globals;
+ let sectionsManagerStub;
+ let shortURLStub;
+
+ const FAKE_OPTIONS = {
+ stories_endpoint: "https://somedomain.org/stories?key=$apiKey",
+ stories_referrer: "https://somedomain.org/referrer",
+ topics_endpoint: "https://somedomain.org/topics?key=$apiKey",
+ survey_link: "https://www.surveymonkey.com/r/newtabffx",
+ api_key_pref: "apiKeyPref",
+ provider_name: "test-provider",
+ provider_icon: "provider-icon",
+ provider_description: "provider_desc",
+ };
+
+ beforeEach(() => {
+ FakePrefs.prototype.prefs.apiKeyPref = "test-api-key";
+ FakePrefs.prototype.prefs.pocketCta = JSON.stringify({
+ cta_button: "",
+ cta_text: "",
+ cta_url: "",
+ use_cta: false,
+ });
+
+ globals = new GlobalOverrider();
+ globals.set("PlacesUtils", { history: {} });
+ globals.set("pktApi", { isUserLoggedIn() {} });
+ clock = sinon.useFakeTimers();
+ shortURLStub = sinon.stub().callsFake(site => site.url);
+ sectionsManagerStub = {
+ onceInitialized: sinon.stub().callsFake(callback => callback()),
+ enableSection: sinon.spy(),
+ disableSection: sinon.spy(),
+ updateSection: sinon.spy(),
+ sections: new Map([["topstories", { options: FAKE_OPTIONS }]]),
+ };
+
+ class FakeUserDomainAffinityProvider {
+ constructor(
+ timeSegments,
+ parameterSets,
+ maxHistoryQueryResults,
+ version,
+ scores
+ ) {
+ this.timeSegments = timeSegments;
+ this.parameterSets = parameterSets;
+ this.maxHistoryQueryResults = maxHistoryQueryResults;
+ this.version = version;
+ this.scores = scores;
+ }
+
+ getAffinities() {
+ return {};
+ }
+ }
+ class FakePersonalityProvider extends FakeUserDomainAffinityProvider {}
+
+ ({
+ TopStoriesFeed,
+ STORIES_UPDATE_TIME,
+ TOPICS_UPDATE_TIME,
+ SECTION_ID,
+ SPOC_IMPRESSION_TRACKING_PREF,
+ REC_IMPRESSION_TRACKING_PREF,
+ MIN_DOMAIN_AFFINITIES_UPDATE_TIME,
+ DEFAULT_RECS_EXPIRE_TIME,
+ } = injector({
+ "lib/ActivityStreamPrefs.jsm": { Prefs: FakePrefs },
+ "lib/ShortURL.jsm": { shortURL: shortURLStub },
+ "lib/PersonalityProvider.jsm": {
+ PersonalityProvider: FakePersonalityProvider,
+ },
+ "lib/UserDomainAffinityProvider.jsm": {
+ UserDomainAffinityProvider: FakeUserDomainAffinityProvider,
+ },
+ "lib/SectionsManager.jsm": { SectionsManager: sectionsManagerStub },
+ }));
+
+ instance = new TopStoriesFeed();
+ instance.store = {
+ getState() {
+ return {
+ Prefs: {
+ values: {
+ showSponsored: true,
+ "feeds.section.topstories": true,
+ },
+ },
+ };
+ },
+ dispatch: sinon.spy(),
+ };
+ instance.storiesLastUpdated = 0;
+ instance.topicsLastUpdated = 0;
+ });
+ afterEach(() => {
+ globals.restore();
+ clock.restore();
+ });
+
+ describe("#lazyloading TopStories", () => {
+ beforeEach(() => {
+ instance.discoveryStreamEnabled = true;
+ });
+ it("should bind parseOptions to SectionsManager.onceInitialized when discovery stream is true", () => {
+ instance.discoveryStreamEnabled = false;
+ instance.store.getState = () => ({
+ Prefs: {
+ values: {
+ "discoverystream.config": JSON.stringify({ enabled: true }),
+ "feeds.section.topstories": true,
+ },
+ },
+ });
+ instance.onAction({ type: at.INIT, data: {} });
+
+ assert.calledOnce(sectionsManagerStub.onceInitialized);
+ });
+ it("should bind parseOptions to SectionsManager.onceInitialized when discovery stream is false", () => {
+ instance.store.getState = () => ({
+ Prefs: {
+ values: {
+ "discoverystream.config": JSON.stringify({ enabled: false }),
+ "feeds.section.topstories": true,
+ },
+ },
+ });
+ instance.onAction({ type: at.INIT, data: {} });
+ assert.calledOnce(sectionsManagerStub.onceInitialized);
+ });
+ it("Should initialize properties once while lazy loading if not initialized earlier", () => {
+ instance.discoveryStreamEnabled = false;
+ instance.propertiesInitialized = false;
+ sinon.stub(instance, "initializeProperties");
+ instance.lazyLoadTopStories();
+ assert.calledOnce(instance.initializeProperties);
+ });
+ it("should not re-initialize properties", () => {
+ // For discovery stream experience disabled TopStoriesFeed properties
+ // are initialized in constructor and should not be called again while lazy loading topstories
+ sinon.stub(instance, "initializeProperties");
+ instance.discoveryStreamEnabled = false;
+ instance.propertiesInitialized = true;
+ instance.lazyLoadTopStories();
+ assert.notCalled(instance.initializeProperties);
+ });
+ it("should have early exit onInit when discovery is true", async () => {
+ sinon.stub(instance, "doContentUpdate");
+ await instance.onInit();
+ assert.notCalled(instance.doContentUpdate);
+ assert.isUndefined(instance.storiesLoaded);
+ });
+ it("should complete onInit when discovery is false", async () => {
+ instance.discoveryStreamEnabled = false;
+ sinon.stub(instance, "doContentUpdate");
+ await instance.onInit();
+ assert.calledOnce(instance.doContentUpdate);
+ assert.isTrue(instance.storiesLoaded);
+ });
+ it("should handle limited actions when discoverystream is enabled", async () => {
+ sinon.spy(instance, "handleDisabled");
+ sinon.stub(instance, "getPocketState");
+ instance.store.getState = () => ({
+ Prefs: {
+ values: {
+ "discoverystream.config": JSON.stringify({ enabled: true }),
+ "discoverystream.enabled": true,
+ "feeds.section.topstories": true,
+ },
+ },
+ });
+
+ instance.onAction({ type: at.INIT, data: {} });
+
+ assert.calledOnce(instance.handleDisabled);
+ instance.onAction({
+ type: at.NEW_TAB_REHYDRATED,
+ meta: { fromTarget: {} },
+ });
+ assert.notCalled(instance.getPocketState);
+ });
+ it("should handle NEW_TAB_REHYDRATED when discoverystream is disabled", async () => {
+ instance.discoveryStreamEnabled = false;
+ sinon.spy(instance, "handleDisabled");
+ sinon.stub(instance, "getPocketState");
+ instance.store.getState = () => ({
+ Prefs: {
+ values: {
+ "discoverystream.config": JSON.stringify({ enabled: false }),
+ "feeds.section.topstories": true,
+ },
+ },
+ });
+ instance.onAction({ type: at.INIT, data: {} });
+ assert.notCalled(instance.handleDisabled);
+
+ instance.onAction({
+ type: at.NEW_TAB_REHYDRATED,
+ meta: { fromTarget: {} },
+ });
+ assert.calledOnce(instance.getPocketState);
+ });
+ it("should handle UNINIT when discoverystream is enabled", async () => {
+ sinon.stub(instance, "uninit");
+ instance.onAction({ type: at.UNINIT });
+ assert.calledOnce(instance.uninit);
+ });
+ it("should fire init on PREF_CHANGED", () => {
+ sinon.stub(instance, "onInit");
+ instance.onAction({
+ type: at.PREF_CHANGED,
+ data: { name: "discoverystream.config", value: {} },
+ });
+ assert.calledOnce(instance.onInit);
+ });
+ it("should fire init on DISCOVERY_STREAM_PREF_ENABLED", () => {
+ sinon.stub(instance, "onInit");
+ instance.onAction({
+ type: at.PREF_CHANGED,
+ data: { name: "discoverystream.enabled", value: true },
+ });
+ assert.calledOnce(instance.onInit);
+ });
+ it("should not fire init on PREF_CHANGED if stories are loaded", () => {
+ sinon.stub(instance, "onInit");
+ sinon.spy(instance, "lazyLoadTopStories");
+ instance.storiesLoaded = true;
+ instance.onAction({
+ type: at.PREF_CHANGED,
+ data: { name: "discoverystream.config", value: {} },
+ });
+ assert.calledOnce(instance.lazyLoadTopStories);
+ assert.notCalled(instance.onInit);
+ });
+ it("should fire init on PREF_CHANGED when discoverystream is disabled", () => {
+ instance.discoveryStreamEnabled = false;
+ sinon.stub(instance, "onInit");
+ instance.onAction({
+ type: at.PREF_CHANGED,
+ data: { name: "discoverystream.config", value: {} },
+ });
+ assert.calledOnce(instance.onInit);
+ });
+ it("should not fire init on PREF_CHANGED when discoverystream is disabled and stories are loaded", () => {
+ instance.discoveryStreamEnabled = false;
+ sinon.stub(instance, "onInit");
+ sinon.spy(instance, "lazyLoadTopStories");
+ instance.storiesLoaded = true;
+ instance.onAction({
+ type: at.PREF_CHANGED,
+ data: { name: "discoverystream.config", value: {} },
+ });
+ assert.calledOnce(instance.lazyLoadTopStories);
+ assert.notCalled(instance.onInit);
+ });
+ it("should not init props if ds pref is true", () => {
+ sinon.stub(instance, "initializeProperties");
+ instance.propertiesInitialized = false;
+ instance.store.getState = () => ({
+ Prefs: {
+ values: {
+ "discoverystream.config": JSON.stringify({ enabled: false }),
+ "discoverystream.enabled": true,
+ "feeds.section.topstories": true,
+ },
+ },
+ });
+ instance.lazyLoadTopStories({
+ dsPref: JSON.stringify({ enabled: true }),
+ });
+ assert.notCalled(instance.initializeProperties);
+ });
+ it("should fire init if user pref is true", () => {
+ sinon.stub(instance, "onInit");
+ instance.store.getState = () => ({
+ Prefs: {
+ values: {
+ "discoverystream.config": JSON.stringify({ enabled: false }),
+ "discoverystream.enabled": false,
+ "feeds.section.topstories": false,
+ },
+ },
+ });
+ instance.lazyLoadTopStories({ userPref: true });
+ assert.calledOnce(instance.onInit);
+ });
+ it("should fire uninit if topstories update to false", () => {
+ sinon.stub(instance, "uninit");
+ instance.discoveryStreamEnabled = false;
+ instance.onAction({
+ type: at.PREF_CHANGED,
+ data: {
+ value: false,
+ name: "feeds.section.topstories",
+ },
+ });
+ assert.calledOnce(instance.uninit);
+ instance.discoveryStreamEnabled = true;
+ instance.onAction({
+ type: at.PREF_CHANGED,
+ data: {
+ value: false,
+ name: "feeds.section.topstories",
+ },
+ });
+ assert.calledTwice(instance.uninit);
+ });
+ it("should fire lazyLoadTopstories if topstories update to true", () => {
+ sinon.stub(instance, "lazyLoadTopStories");
+ instance.discoveryStreamEnabled = false;
+ instance.onAction({
+ type: at.PREF_CHANGED,
+ data: {
+ value: true,
+ name: "feeds.section.topstories",
+ },
+ });
+ assert.calledOnce(instance.lazyLoadTopStories);
+ instance.discoveryStreamEnabled = true;
+ instance.onAction({
+ type: at.PREF_CHANGED,
+ data: {
+ value: true,
+ name: "feeds.section.topstories",
+ },
+ });
+ assert.calledTwice(instance.lazyLoadTopStories);
+ });
+ });
+
+ describe("#init", () => {
+ it("should create a TopStoriesFeed", () => {
+ assert.instanceOf(instance, TopStoriesFeed);
+ });
+ it("should bind parseOptions to SectionsManager.onceInitialized", () => {
+ instance.onAction({ type: at.INIT, data: {} });
+ assert.calledOnce(sectionsManagerStub.onceInitialized);
+ });
+ it("should initialize endpoints based on options", async () => {
+ await instance.onInit();
+ assert.equal(
+ "https://somedomain.org/stories?key=test-api-key",
+ instance.stories_endpoint
+ );
+ assert.equal(
+ "https://somedomain.org/referrer",
+ instance.stories_referrer
+ );
+ assert.equal(
+ "https://somedomain.org/topics?key=test-api-key",
+ instance.topics_endpoint
+ );
+ });
+ it("should enable its section", () => {
+ instance.onAction({ type: at.INIT, data: {} });
+ assert.calledOnce(sectionsManagerStub.enableSection);
+ assert.calledWith(sectionsManagerStub.enableSection, SECTION_ID);
+ });
+ it("init should fire onInit", () => {
+ instance.onInit = sinon.spy();
+ instance.onAction({ type: at.INIT, data: {} });
+ assert.calledOnce(instance.onInit);
+ });
+ it("should fetch stories on init", async () => {
+ instance.fetchStories = sinon.spy();
+ await instance.onInit();
+ assert.calledOnce(instance.fetchStories);
+ });
+ it("should fetch topics on init", async () => {
+ instance.fetchTopics = sinon.spy();
+ await instance.onInit();
+ assert.calledOnce(instance.fetchTopics);
+ });
+ it("should not fetch if endpoint not configured", () => {
+ let fetchStub = globals.sandbox.stub();
+ globals.set("fetch", fetchStub);
+ sectionsManagerStub.sections.set("topstories", { options: {} });
+ instance.init();
+ assert.notCalled(fetchStub);
+ });
+ it("should report error for invalid configuration", () => {
+ globals.sandbox.spy(global.Cu, "reportError");
+ sectionsManagerStub.sections.set("topstories", {
+ options: {
+ api_key_pref: "invalid",
+ stories_endpoint: "https://invalid.com/?apiKey=$apiKey",
+ },
+ });
+ instance.init();
+
+ assert.calledWith(
+ Cu.reportError,
+ "Problem initializing top stories feed: An API key was specified but none configured: https://invalid.com/?apiKey=$apiKey"
+ );
+ });
+ it("should report error for missing api key", () => {
+ globals.sandbox.spy(global.Cu, "reportError");
+ sectionsManagerStub.sections.set("topstories", {
+ options: {
+ stories_endpoint: "https://somedomain.org/stories?key=$apiKey",
+ topics_endpoint: "https://somedomain.org/topics?key=$apiKey",
+ },
+ });
+ instance.init();
+
+ assert.called(Cu.reportError);
+ });
+ it("should load data from cache on init", async () => {
+ instance.loadCachedData = sinon.spy();
+ await instance.onInit();
+ assert.calledOnce(instance.loadCachedData);
+ });
+ });
+ describe("#uninit", () => {
+ it("should disable its section", () => {
+ instance.onAction({ type: at.UNINIT });
+ assert.calledOnce(sectionsManagerStub.disableSection);
+ assert.calledWith(sectionsManagerStub.disableSection, SECTION_ID);
+ });
+ it("should unload stories on uninit", async () => {
+ sinon.stub(instance.cache, "set").returns(Promise.resolve());
+ await instance.clearCache();
+ assert.calledWith(instance.cache.set.firstCall, "stories", {});
+ assert.calledWith(instance.cache.set.secondCall, "topics", {});
+ assert.calledWith(instance.cache.set.thirdCall, "spocs", {});
+ });
+ });
+ describe("#cache", () => {
+ it("should clear all cache items when calling clearCache", () => {
+ sinon.stub(instance.cache, "set").returns(Promise.resolve());
+ instance.storiesLoaded = true;
+ instance.uninit();
+ assert.equal(instance.storiesLoaded, false);
+ });
+ it("should set spocs cache on fetch", async () => {
+ const response = {
+ recommendations: [{ id: "1" }, { id: "2" }],
+ settings: { timeSegments: {}, domainAffinityParameterSets: {} },
+ spocs: [{ id: "spoc1" }],
+ };
+
+ instance.show_spocs = true;
+ instance.personalized = true;
+ instance.stories_endpoint = "stories-endpoint";
+
+ let fetchStub = globals.sandbox.stub();
+ globals.set("fetch", fetchStub);
+ globals.set("NewTabUtils", { blockedLinks: { isBlocked: () => {} } });
+ fetchStub.resolves({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve(response),
+ });
+ sinon.spy(instance.cache, "set");
+
+ await instance.fetchStories();
+
+ assert.calledOnce(instance.cache.set);
+ const { args } = instance.cache.set.firstCall;
+ assert.equal(args[0], "stories");
+ assert.equal(args[1].spocs[0].id, "spoc1");
+ });
+ it("should get spocs on cache load", async () => {
+ instance.cache.get = () => ({
+ stories: {
+ recommendations: [{ id: "1" }, { id: "2" }],
+ spocs: [{ id: "spoc1" }],
+ },
+ });
+ instance.storiesLastUpdated = 0;
+ globals.set("NewTabUtils", { blockedLinks: { isBlocked: () => {} } });
+
+ await instance.loadCachedData();
+ assert.equal(instance.spocs[0].guid, "spoc1");
+ });
+ });
+ describe("#fetch", () => {
+ it("should fetch stories, send event and cache results", async () => {
+ let fetchStub = globals.sandbox.stub();
+ sectionsManagerStub.sections.set("topstories", {
+ options: {
+ stories_endpoint: "stories-endpoint",
+ stories_referrer: "referrer",
+ },
+ });
+ globals.set("fetch", fetchStub);
+ globals.set("NewTabUtils", {
+ blockedLinks: { isBlocked: globals.sandbox.spy() },
+ });
+
+ const response = {
+ recommendations: [
+ {
+ id: "1",
+ title: "title",
+ excerpt: "description",
+ image_src: "image-url",
+ url: "rec-url",
+ published_timestamp: "123",
+ context: "trending",
+ icon: "icon",
+ },
+ ],
+ };
+ const stories = [
+ {
+ guid: "1",
+ type: "now",
+ title: "title",
+ context: "trending",
+ icon: "icon",
+ description: "description",
+ image: "image-url",
+ referrer: "referrer",
+ url: "rec-url",
+ hostname: "rec-url",
+ min_score: 0,
+ score: 1,
+ spoc_meta: {},
+ },
+ ];
+
+ instance.cache.set = sinon.spy();
+ fetchStub.resolves({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve(response),
+ });
+ await instance.onInit();
+
+ assert.calledOnce(fetchStub);
+ assert.calledOnce(shortURLStub);
+ assert.calledWithExactly(fetchStub, instance.stories_endpoint, {
+ credentials: "omit",
+ });
+ assert.calledOnce(sectionsManagerStub.updateSection);
+ assert.calledWith(sectionsManagerStub.updateSection, SECTION_ID, {
+ rows: stories,
+ });
+ assert.calledOnce(instance.cache.set);
+ assert.calledWith(
+ instance.cache.set,
+ "stories",
+ Object.assign({}, response, { _timestamp: 0 })
+ );
+ });
+ it("should use domain as hostname, if present", async () => {
+ let fetchStub = globals.sandbox.stub();
+ sectionsManagerStub.sections.set("topstories", {
+ options: {
+ stories_endpoint: "stories-endpoint",
+ stories_referrer: "referrer",
+ },
+ });
+ globals.set("fetch", fetchStub);
+ globals.set("NewTabUtils", {
+ blockedLinks: { isBlocked: globals.sandbox.spy() },
+ });
+
+ const response = {
+ recommendations: [
+ {
+ id: "1",
+ title: "title",
+ excerpt: "description",
+ image_src: "image-url",
+ url: "rec-url",
+ domain: "domain",
+ published_timestamp: "123",
+ context: "trending",
+ icon: "icon",
+ },
+ ],
+ };
+ const stories = [
+ {
+ guid: "1",
+ type: "now",
+ title: "title",
+ context: "trending",
+ icon: "icon",
+ description: "description",
+ image: "image-url",
+ referrer: "referrer",
+ url: "rec-url",
+ hostname: "domain",
+ min_score: 0,
+ score: 1,
+ spoc_meta: {},
+ },
+ ];
+
+ instance.cache.set = sinon.spy();
+ fetchStub.resolves({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve(response),
+ });
+ await instance.onInit();
+
+ assert.calledOnce(fetchStub);
+ assert.notCalled(shortURLStub);
+ assert.calledWith(sectionsManagerStub.updateSection, SECTION_ID, {
+ rows: stories,
+ });
+ });
+ it("should call SectionsManager.updateSection", () => {
+ instance.dispatchUpdateEvent(123, {});
+ assert.calledOnce(sectionsManagerStub.updateSection);
+ });
+ it("should report error for unexpected stories response", async () => {
+ let fetchStub = globals.sandbox.stub();
+ sectionsManagerStub.sections.set("topstories", {
+ options: { stories_endpoint: "stories-endpoint" },
+ });
+ globals.set("fetch", fetchStub);
+ globals.sandbox.spy(global.Cu, "reportError");
+
+ fetchStub.resolves({ ok: false, status: 400 });
+ await instance.onInit();
+
+ assert.calledOnce(fetchStub);
+ assert.calledWithExactly(fetchStub, instance.stories_endpoint, {
+ credentials: "omit",
+ });
+ assert.equal(instance.storiesLastUpdated, 0);
+ assert.called(Cu.reportError);
+ });
+ it("should exclude blocked (dismissed) URLs", async () => {
+ let fetchStub = globals.sandbox.stub();
+ sectionsManagerStub.sections.set("topstories", {
+ options: { stories_endpoint: "stories-endpoint" },
+ });
+ globals.set("fetch", fetchStub);
+ globals.set("NewTabUtils", {
+ blockedLinks: { isBlocked: site => site.url === "blocked" },
+ });
+
+ const response = {
+ recommendations: [{ url: "blocked" }, { url: "not_blocked" }],
+ };
+ fetchStub.resolves({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve(response),
+ });
+ await instance.onInit();
+
+ // Issue!
+ // Should actually be fixed when cache is fixed.
+ assert.calledOnce(sectionsManagerStub.updateSection);
+ assert.equal(
+ sectionsManagerStub.updateSection.firstCall.args[1].rows.length,
+ 1
+ );
+ assert.equal(
+ sectionsManagerStub.updateSection.firstCall.args[1].rows[0].url,
+ "not_blocked"
+ );
+ });
+ it("should mark stories as new", async () => {
+ let fetchStub = globals.sandbox.stub();
+ sectionsManagerStub.sections.set("topstories", {
+ options: { stories_endpoint: "stories-endpoint" },
+ });
+ globals.set("fetch", fetchStub);
+ globals.set("NewTabUtils", {
+ blockedLinks: { isBlocked: globals.sandbox.spy() },
+ });
+ clock.restore();
+ const response = {
+ recommendations: [
+ { published_timestamp: Date.now() / 1000 },
+ { published_timestamp: "0" },
+ {
+ published_timestamp: (Date.now() - 2 * 24 * 60 * 60 * 1000) / 1000,
+ },
+ ],
+ };
+
+ fetchStub.resolves({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve(response),
+ });
+
+ await instance.onInit();
+ assert.calledOnce(sectionsManagerStub.updateSection);
+ assert.equal(
+ sectionsManagerStub.updateSection.firstCall.args[1].rows.length,
+ 3
+ );
+ assert.equal(
+ sectionsManagerStub.updateSection.firstCall.args[1].rows[0].type,
+ "now"
+ );
+ assert.equal(
+ sectionsManagerStub.updateSection.firstCall.args[1].rows[1].type,
+ "trending"
+ );
+ assert.equal(
+ sectionsManagerStub.updateSection.firstCall.args[1].rows[2].type,
+ "trending"
+ );
+ });
+ it("should fetch topics, send event and cache results", async () => {
+ let fetchStub = globals.sandbox.stub();
+ sectionsManagerStub.sections.set("topstories", {
+ options: { topics_endpoint: "topics-endpoint" },
+ });
+ globals.set("fetch", fetchStub);
+
+ const response = {
+ topics: [
+ { name: "topic1", url: "url-topic1" },
+ { name: "topic2", url: "url-topic2" },
+ ],
+ };
+ const topics = [
+ {
+ name: "topic1",
+ url: "url-topic1",
+ },
+ {
+ name: "topic2",
+ url: "url-topic2",
+ },
+ ];
+
+ instance.cache.set = sinon.spy();
+ fetchStub.resolves({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve(response),
+ });
+ await instance.onInit();
+
+ assert.calledOnce(fetchStub);
+ assert.calledWithExactly(fetchStub, instance.topics_endpoint, {
+ credentials: "omit",
+ });
+ assert.calledOnce(sectionsManagerStub.updateSection);
+ assert.calledWithMatch(sectionsManagerStub.updateSection, SECTION_ID, {
+ topics,
+ });
+ assert.calledOnce(instance.cache.set);
+ assert.calledWith(
+ instance.cache.set,
+ "topics",
+ Object.assign({}, response, { _timestamp: 0 })
+ );
+ });
+ it("should report error for unexpected topics response", async () => {
+ let fetchStub = globals.sandbox.stub();
+ globals.set("fetch", fetchStub);
+ globals.sandbox.spy(global.Cu, "reportError");
+
+ instance.topics_endpoint = "topics-endpoint";
+ fetchStub.resolves({ ok: false, status: 400 });
+ await instance.fetchTopics();
+
+ assert.calledOnce(fetchStub);
+ assert.calledWithExactly(fetchStub, instance.topics_endpoint, {
+ credentials: "omit",
+ });
+ assert.notCalled(instance.store.dispatch);
+ assert.called(Cu.reportError);
+ });
+ });
+ describe("#personalization", () => {
+ it("should sort stories if personalization is preffed on", async () => {
+ const response = {
+ recommendations: [{ id: "1" }, { id: "2" }],
+ settings: { timeSegments: {}, domainAffinityParameterSets: {} },
+ };
+
+ instance.personalized = true;
+ instance.compareScore = sinon.spy();
+ instance.stories_endpoint = "stories-endpoint";
+
+ let fetchStub = globals.sandbox.stub();
+ globals.set("fetch", fetchStub);
+ globals.set("NewTabUtils", {
+ blockedLinks: { isBlocked: globals.sandbox.spy() },
+ });
+ fetchStub.resolves({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve(response),
+ });
+
+ await instance.fetchStories();
+ assert.calledOnce(instance.compareScore);
+ });
+ it("should not sort stories if personalization is preffed off", async () => {
+ const response = `{
+ "recommendations": [{"id" : "1"}, {"id" : "2"}],
+ "settings": {"timeSegments": {}, "domainAffinityParameterSets": {}}
+ }`;
+
+ instance.personalized = false;
+ instance.compareScore = sinon.spy();
+ instance.stories_endpoint = "stories-endpoint";
+
+ let fetchStub = globals.sandbox.stub();
+ globals.set("fetch", fetchStub);
+ globals.set("NewTabUtils", {
+ blockedLinks: { isBlocked: globals.sandbox.spy() },
+ });
+ fetchStub.resolves({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve(response),
+ });
+
+ await instance.fetchStories();
+ assert.notCalled(instance.compareScore);
+ });
+ it("should sort items based on relevance score", () => {
+ let items = [{ score: 0.1 }, { score: 0.2 }];
+ items = items.sort(instance.compareScore);
+ assert.deepEqual(items, [{ score: 0.2 }, { score: 0.1 }]);
+ });
+ it("should rotate items if personalization is preffed on", () => {
+ let items = [
+ { guid: "g1" },
+ { guid: "g2" },
+ { guid: "g3" },
+ { guid: "g4" },
+ { guid: "g5" },
+ { guid: "g6" },
+ ];
+ instance.personalized = true;
+
+ // No impressions should leave items unchanged
+ let rotated = instance.rotate(items);
+ assert.deepEqual(items, rotated);
+
+ // Recent impression should leave items unchanged
+ instance._prefs.get = pref =>
+ pref === REC_IMPRESSION_TRACKING_PREF &&
+ JSON.stringify({ g1: 1, g2: 1, g3: 1 });
+ rotated = instance.rotate(items);
+ assert.deepEqual(items, rotated);
+
+ // Impression older than expiration time should rotate items
+ clock.tick(DEFAULT_RECS_EXPIRE_TIME + 1);
+ rotated = instance.rotate(items);
+ assert.deepEqual(
+ [
+ { guid: "g4" },
+ { guid: "g5" },
+ { guid: "g6" },
+ { guid: "g1" },
+ { guid: "g2" },
+ { guid: "g3" },
+ ],
+ rotated
+ );
+
+ instance._prefs.get = pref =>
+ pref === REC_IMPRESSION_TRACKING_PREF &&
+ JSON.stringify({
+ g1: 1,
+ g2: 1,
+ g3: 1,
+ g4: DEFAULT_RECS_EXPIRE_TIME + 1,
+ });
+ clock.tick(DEFAULT_RECS_EXPIRE_TIME);
+ rotated = instance.rotate(items);
+ assert.deepEqual(
+ [
+ { guid: "g5" },
+ { guid: "g6" },
+ { guid: "g1" },
+ { guid: "g2" },
+ { guid: "g3" },
+ { guid: "g4" },
+ ],
+ rotated
+ );
+ });
+ it("should not rotate items if personalization is preffed off", () => {
+ let items = [
+ { guid: "g1" },
+ { guid: "g2" },
+ { guid: "g3" },
+ { guid: "g4" },
+ ];
+
+ instance.personalized = false;
+
+ instance._prefs.get = pref =>
+ pref === REC_IMPRESSION_TRACKING_PREF &&
+ JSON.stringify({ g1: 1, g2: 1, g3: 1 });
+ clock.tick(DEFAULT_RECS_EXPIRE_TIME + 1);
+ let rotated = instance.rotate(items);
+ assert.deepEqual(items, rotated);
+ });
+ it("should record top story impressions", async () => {
+ instance._prefs = { get: pref => undefined, set: sinon.spy() };
+ instance.personalized = true;
+
+ clock.tick(1);
+ let expectedPrefValue = JSON.stringify({ 1: 1, 2: 1, 3: 1 });
+ instance.onAction({
+ type: at.TELEMETRY_IMPRESSION_STATS,
+ data: {
+ source: "TOP_STORIES",
+ tiles: [{ id: 1 }, { id: 2 }, { id: 3 }],
+ },
+ });
+ assert.calledWith(
+ instance._prefs.set.firstCall,
+ REC_IMPRESSION_TRACKING_PREF,
+ expectedPrefValue
+ );
+
+ // Only need to record first impression, so impression pref shouldn't change
+ instance._prefs.get = pref => expectedPrefValue;
+ clock.tick(1);
+ instance.onAction({
+ type: at.TELEMETRY_IMPRESSION_STATS,
+ data: {
+ source: "TOP_STORIES",
+ tiles: [{ id: 1 }, { id: 2 }, { id: 3 }],
+ },
+ });
+ assert.calledOnce(instance._prefs.set);
+
+ // New first impressions should be added
+ clock.tick(1);
+ let expectedPrefValueTwo = JSON.stringify({
+ 1: 1,
+ 2: 1,
+ 3: 1,
+ 4: 3,
+ 5: 3,
+ 6: 3,
+ });
+ instance.onAction({
+ type: at.TELEMETRY_IMPRESSION_STATS,
+ data: {
+ source: "TOP_STORIES",
+ tiles: [{ id: 4 }, { id: 5 }, { id: 6 }],
+ },
+ });
+ assert.calledWith(
+ instance._prefs.set.secondCall,
+ REC_IMPRESSION_TRACKING_PREF,
+ expectedPrefValueTwo
+ );
+ });
+ it("should not record top story impressions for non-view impressions", async () => {
+ instance._prefs = { get: pref => undefined, set: sinon.spy() };
+ instance.personalized = true;
+
+ instance.onAction({
+ type: at.TELEMETRY_IMPRESSION_STATS,
+ data: { source: "TOP_STORIES", click: 0, tiles: [{ id: 1 }] },
+ });
+ assert.notCalled(instance._prefs.set);
+
+ instance.onAction({
+ type: at.TELEMETRY_IMPRESSION_STATS,
+ data: { source: "TOP_STORIES", block: 0, tiles: [{ id: 1 }] },
+ });
+ assert.notCalled(instance._prefs.set);
+
+ instance.onAction({
+ type: at.TELEMETRY_IMPRESSION_STATS,
+ data: { source: "TOP_STORIES", pocket: 0, tiles: [{ id: 1 }] },
+ });
+ assert.notCalled(instance._prefs.set);
+ });
+ it("should clean up top story impressions", async () => {
+ instance._prefs = {
+ get: pref => JSON.stringify({ 1: 1, 2: 1, 3: 1 }),
+ set: sinon.spy(),
+ };
+
+ let fetchStub = globals.sandbox.stub();
+ globals.set("fetch", fetchStub);
+ globals.set("NewTabUtils", {
+ blockedLinks: { isBlocked: globals.sandbox.spy() },
+ });
+
+ instance.stories_endpoint = "stories-endpoint";
+ const response = { recommendations: [{ id: 3 }, { id: 4 }, { id: 5 }] };
+ fetchStub.resolves({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve(response),
+ });
+ await instance.fetchStories();
+
+ // Should remove impressions for rec 1 and 2 as no longer in the feed
+ assert.calledWith(
+ instance._prefs.set.firstCall,
+ REC_IMPRESSION_TRACKING_PREF,
+ JSON.stringify({ 3: 1 })
+ );
+ });
+ it("should re init on affinityProviderV2 pref change", async () => {
+ sinon.stub(instance, "uninit");
+ sinon.stub(instance, "init");
+ sinon.stub(instance, "clearCache").returns(Promise.resolve());
+ await instance.onAction({
+ type: at.PREF_CHANGED,
+ data: {
+ name: "feeds.section.topstories.options",
+ value: JSON.stringify({ version: 2 }),
+ },
+ });
+ assert.calledOnce(instance.uninit);
+ assert.calledOnce(instance.init);
+ assert.calledOnce(instance.clearCache);
+ });
+ it("should use UserDomainAffinityProvider from affinityProividerSwitcher not using v2", async () => {
+ instance.affinityProviderV2 = { use_v2: false };
+ sinon.stub(instance, "UserDomainAffinityProvider");
+ sinon.stub(instance, "PersonalityProvider");
+
+ await instance.affinityProividerSwitcher();
+ assert.notCalled(instance.PersonalityProvider);
+ assert.calledOnce(instance.UserDomainAffinityProvider);
+ });
+ it("should not change provider with badly formed JSON", async () => {
+ sinon.stub(instance, "uninit");
+ sinon.stub(instance, "init");
+ sinon.stub(instance, "clearCache").returns(Promise.resolve());
+ await instance.onAction({
+ type: at.PREF_CHANGED,
+ data: {
+ name: "feeds.section.topstories.options",
+ value: "{version: 2}",
+ },
+ });
+ assert.notCalled(instance.uninit);
+ assert.notCalled(instance.init);
+ assert.notCalled(instance.clearCache);
+ });
+ it("should use PersonalityProvider from affinityProividerSwitcher using v2", async () => {
+ instance.affinityProviderV2 = { use_v2: true };
+ sinon.stub(instance, "UserDomainAffinityProvider");
+ sinon.stub(instance, "PersonalityProvider");
+ instance.PersonalityProvider = () => ({ init: sinon.stub() });
+
+ const provider = instance.affinityProividerSwitcher();
+ assert.calledOnce(provider.init);
+ assert.notCalled(instance.UserDomainAffinityProvider);
+ });
+ it("should use init and callback from affinityProividerSwitcher using v2", async () => {
+ const stories = { recommendations: {} };
+ sinon.stub(instance, "doContentUpdate");
+ sinon.stub(instance, "rotate").returns(stories);
+ sinon.stub(instance, "transform");
+ instance.cache.get = () => ({ stories });
+ instance.cache.set = sinon.spy();
+ instance.affinityProvider = { getAffinities: () => ({}) };
+ await instance.onPersonalityProviderInit();
+
+ assert.calledOnce(instance.doContentUpdate);
+ assert.calledWith(
+ instance.doContentUpdate,
+ { stories: { recommendations: {} } },
+ false
+ );
+ assert.calledOnce(instance.rotate);
+ assert.calledOnce(instance.transform);
+ const { args } = instance.cache.set.firstCall;
+ assert.equal(args[0], "domainAffinities");
+ assert.equal(args[1]._timestamp, 0);
+ });
+ it("should call dispatchUpdateEvent from affinityProividerSwitcher using v2", async () => {
+ const stories = { recommendations: {} };
+ sinon.stub(instance, "rotate").returns(stories);
+ sinon.stub(instance, "transform");
+ sinon.spy(instance, "dispatchUpdateEvent");
+ instance.cache.get = () => ({ stories });
+ instance.cache.set = sinon.spy();
+ instance.affinityProvider = { getAffinities: () => ({}) };
+
+ await instance.onPersonalityProviderInit();
+
+ assert.calledOnce(instance.dispatchUpdateEvent);
+ });
+ it("should return an object for UserDomainAffinityProvider", () => {
+ assert.equal(typeof instance.UserDomainAffinityProvider(), "object");
+ });
+ it("should return an object for PersonalityProvider", () => {
+ assert.equal(typeof instance.PersonalityProvider(), "object");
+ });
+ it("should call affinityProividerSwitcher on loadCachedData", async () => {
+ instance.affinityProviderV2 = true;
+ instance.personalized = true;
+ sinon
+ .stub(instance, "affinityProividerSwitcher")
+ .returns(Promise.resolve());
+ const domainAffinities = {
+ parameterSets: {
+ default: {
+ recencyFactor: 0.4,
+ frequencyFactor: 0.5,
+ combinedDomainFactor: 0.5,
+ perfectFrequencyVisits: 10,
+ perfectCombinedDomainScore: 2,
+ multiDomainBoost: 0.1,
+ itemScoreFactor: 0,
+ },
+ },
+ scores: { "a.com": 1, "b.com": 0.9 },
+ maxHistoryQueryResults: 1000,
+ timeSegments: {},
+ version: "v1",
+ };
+
+ instance.cache.get = () => ({ domainAffinities });
+ await instance.loadCachedData();
+ assert.calledOnce(instance.affinityProividerSwitcher);
+ });
+ it("should change domainAffinitiesLastUpdated on loadCachedData", async () => {
+ instance.affinityProviderV2 = true;
+ instance.personalized = true;
+ const domainAffinities = {
+ parameterSets: {
+ default: {
+ recencyFactor: 0.4,
+ frequencyFactor: 0.5,
+ combinedDomainFactor: 0.5,
+ perfectFrequencyVisits: 10,
+ perfectCombinedDomainScore: 2,
+ multiDomainBoost: 0.1,
+ itemScoreFactor: 0,
+ },
+ },
+ scores: { "a.com": 1, "b.com": 0.9 },
+ maxHistoryQueryResults: 1000,
+ timeSegments: {},
+ version: "v1",
+ };
+
+ instance.cache.get = () => ({ domainAffinities });
+ await instance.loadCachedData();
+ assert.notEqual(instance.domainAffinitiesLastUpdated, 0);
+ });
+ it("should return false and do nothing if v2 already set", () => {
+ instance.affinityProviderV2 = { use_v2: true, model_keys: ["item1orig"] };
+ const result = instance.processAffinityProividerVersion({
+ version: 2,
+ model_keys: ["item1"],
+ });
+ assert.isTrue(instance.affinityProviderV2.use_v2);
+ assert.isFalse(result);
+ assert.equal(instance.affinityProviderV2.model_keys[0], "item1orig");
+ });
+ it("should return false and do nothing if v1 already set", () => {
+ instance.affinityProviderV2 = null;
+ const result = instance.processAffinityProividerVersion({ version: 1 });
+ assert.isFalse(result);
+ assert.isNull(instance.affinityProviderV2);
+ });
+ it("should return true and set v2", () => {
+ const result = instance.processAffinityProividerVersion({
+ version: 2,
+ model_keys: ["item1"],
+ });
+ assert.isTrue(instance.affinityProviderV2.use_v2);
+ assert.isTrue(result);
+ assert.equal(instance.affinityProviderV2.model_keys[0], "item1");
+ });
+ it("should return true and set v1", () => {
+ instance.affinityProviderV2 = {};
+ const result = instance.processAffinityProividerVersion({ version: 1 });
+ assert.isTrue(result);
+ assert.isNull(instance.affinityProviderV2);
+ });
+ });
+ describe("#spocs", async () => {
+ it("should not display expired or untimestamped spocs", async () => {
+ clock.tick(441792000000); // 01/01/1984
+
+ instance.spocsPerNewTabs = 1;
+ instance.show_spocs = true;
+ instance.isBelowFrequencyCap = () => true;
+
+ // NOTE: `expiration_timestamp` is seconds since UNIX epoch
+ instance.spocs = [
+ // No timestamp stays visible
+ {
+ id: "spoc1",
+ },
+ // Expired spoc gets filtered out
+ {
+ id: "spoc2",
+ expiration_timestamp: 1,
+ },
+ // Far future expiration spoc stays visible
+ {
+ id: "spoc3",
+ expiration_timestamp: 32503708800, // 01/01/3000
+ },
+ ];
+
+ sinon.spy(instance, "filterSpocs");
+
+ instance.filterSpocs();
+
+ assert.equal(instance.filterSpocs.firstCall.returnValue.length, 2);
+ assert.equal(instance.filterSpocs.firstCall.returnValue[0].id, "spoc1");
+ assert.equal(instance.filterSpocs.firstCall.returnValue[1].id, "spoc3");
+ });
+ it("should insert spoc with provided probability", async () => {
+ let fetchStub = globals.sandbox.stub();
+ globals.set("fetch", fetchStub);
+ globals.set("NewTabUtils", {
+ blockedLinks: { isBlocked: globals.sandbox.spy() },
+ });
+
+ const response = {
+ settings: { spocsPerNewTabs: 0.5 },
+ recommendations: [{ guid: "rec1" }, { guid: "rec2" }, { guid: "rec3" }],
+ // Include spocs with a expiration in the very distant future
+ spocs: [
+ { id: "spoc1", expiration_timestamp: 9999999999999 },
+ { id: "spoc2", expiration_timestamp: 9999999999999 },
+ ],
+ };
+
+ instance.personalized = true;
+ instance.show_spocs = true;
+ instance.stories_endpoint = "stories-endpoint";
+ instance.storiesLoaded = true;
+ fetchStub.resolves({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve(response),
+ });
+ await instance.fetchStories();
+
+ instance.store.getState = () => ({
+ Sections: [{ id: "topstories", rows: response.recommendations }],
+ Prefs: { values: { showSponsored: true } },
+ });
+
+ globals.set("Math", {
+ random: () => 0.4,
+ min: Math.min,
+ });
+ instance.dispatchSpocDone = () => {};
+ instance.getPocketState = () => {};
+
+ instance.onAction({
+ type: at.NEW_TAB_REHYDRATED,
+ meta: { fromTarget: {} },
+ });
+ assert.calledOnce(instance.store.dispatch);
+ let [action] = instance.store.dispatch.firstCall.args;
+
+ assert.equal(at.SECTION_UPDATE, action.type);
+ assert.equal(true, action.meta.skipMain);
+ assert.equal(action.data.rows[0].guid, "rec1");
+ assert.equal(action.data.rows[1].guid, "rec2");
+ assert.equal(action.data.rows[2].guid, "spoc1");
+ // Make sure spoc is marked as pinned so it doesn't get removed when preloaded tabs refresh
+ assert.equal(action.data.rows[2].pinned, true);
+
+ // Second new tab shouldn't trigger a section update event (spocsPerNewTab === 0.5)
+ globals.set("Math", {
+ random: () => 0.6,
+ min: Math.min,
+ });
+ instance.onAction({
+ type: at.NEW_TAB_REHYDRATED,
+ meta: { fromTarget: {} },
+ });
+ assert.calledOnce(instance.store.dispatch);
+
+ globals.set("Math", {
+ random: () => 0.3,
+ min: Math.min,
+ });
+ instance.onAction({
+ type: at.NEW_TAB_REHYDRATED,
+ meta: { fromTarget: {} },
+ });
+ assert.calledTwice(instance.store.dispatch);
+ [action] = instance.store.dispatch.secondCall.args;
+ assert.equal(at.SECTION_UPDATE, action.type);
+ assert.equal(true, action.meta.skipMain);
+ assert.equal(action.data.rows[0].guid, "rec1");
+ assert.equal(action.data.rows[1].guid, "rec2");
+ assert.equal(action.data.rows[2].guid, "spoc1");
+ // Make sure spoc is marked as pinned so it doesn't get removed when preloaded tabs refresh
+ assert.equal(action.data.rows[2].pinned, true);
+ });
+ it("should delay inserting spoc if stories haven't been fetched", async () => {
+ let fetchStub = globals.sandbox.stub();
+ instance.dispatchSpocDone = () => {};
+ sectionsManagerStub.sections.set("topstories", {
+ options: {
+ show_spocs: true,
+ personalized: true,
+ stories_endpoint: "stories-endpoint",
+ },
+ });
+ globals.set("fetch", fetchStub);
+ globals.set("NewTabUtils", {
+ blockedLinks: { isBlocked: globals.sandbox.spy() },
+ });
+ globals.set("Math", {
+ random: () => 0.4,
+ min: Math.min,
+ floor: Math.floor,
+ });
+ instance.getPocketState = () => {};
+ instance.dispatchPocketCta = () => {};
+
+ const response = {
+ settings: { spocsPerNewTabs: 0.5 },
+ recommendations: [{ id: "rec1" }, { id: "rec2" }, { id: "rec3" }],
+ // Include one spoc with a expiration in the very distant future
+ spocs: [
+ { id: "spoc1", expiration_timestamp: 9999999999999 },
+ { id: "spoc2" },
+ ],
+ };
+
+ instance.onAction({
+ type: at.NEW_TAB_REHYDRATED,
+ meta: { fromTarget: {} },
+ });
+ assert.notCalled(instance.store.dispatch);
+ assert.equal(instance.contentUpdateQueue.length, 1);
+
+ instance.spocsPerNewTabs = 0.5;
+ instance.store.getState = () => ({
+ Sections: [{ id: "topstories", rows: response.recommendations }],
+ Prefs: { values: { showSponsored: true } },
+ });
+ fetchStub.resolves({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve(response),
+ });
+
+ await instance.onInit();
+ assert.equal(instance.contentUpdateQueue.length, 0);
+ assert.calledOnce(instance.store.dispatch);
+ let [action] = instance.store.dispatch.firstCall.args;
+ assert.equal(action.type, at.SECTION_UPDATE);
+ });
+ it("should not insert spoc if preffed off", async () => {
+ let fetchStub = globals.sandbox.stub();
+ instance.dispatchSpocDone = () => {};
+ sectionsManagerStub.sections.set("topstories", {
+ options: {
+ show_spocs: false,
+ personalized: true,
+ stories_endpoint: "stories-endpoint",
+ },
+ });
+ globals.set("fetch", fetchStub);
+ globals.set("NewTabUtils", {
+ blockedLinks: { isBlocked: globals.sandbox.spy() },
+ });
+ instance.getPocketState = () => {};
+ instance.dispatchPocketCta = () => {};
+
+ const response = {
+ settings: { spocsPerNewTabs: 0.5 },
+ spocs: [{ id: "spoc1" }, { id: "spoc2" }],
+ };
+ sinon.spy(instance, "maybeAddSpoc");
+ sinon.spy(instance, "shouldShowSpocs");
+
+ fetchStub.resolves({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve(response),
+ });
+ await instance.onInit();
+
+ instance.onAction({
+ type: at.NEW_TAB_REHYDRATED,
+ meta: { fromTarget: {} },
+ });
+ assert.calledOnce(instance.maybeAddSpoc);
+ assert.calledOnce(instance.shouldShowSpocs);
+ assert.notCalled(instance.store.dispatch);
+ });
+ it("should call dispatchSpocDone when calling maybeAddSpoc", async () => {
+ instance.dispatchSpocDone = sinon.spy();
+ instance.storiesLoaded = true;
+ await instance.onAction({
+ type: at.NEW_TAB_REHYDRATED,
+ meta: { fromTarget: {} },
+ });
+ assert.calledOnce(instance.dispatchSpocDone);
+ assert.calledWith(instance.dispatchSpocDone, {});
+ });
+ it("should fire POCKET_WAITING_FOR_SPOC action with false", () => {
+ instance.dispatchSpocDone({});
+ assert.calledOnce(instance.store.dispatch);
+ const [action] = instance.store.dispatch.firstCall.args;
+ assert.equal(action.type, "POCKET_WAITING_FOR_SPOC");
+ assert.equal(action.data, false);
+ });
+ it("should not insert spoc if user opted out", async () => {
+ let fetchStub = globals.sandbox.stub();
+ instance.dispatchSpocDone = () => {};
+ sectionsManagerStub.sections.set("topstories", {
+ options: {
+ show_spocs: true,
+ personalized: true,
+ stories_endpoint: "stories-endpoint",
+ },
+ });
+ instance.getPocketState = () => {};
+ instance.dispatchPocketCta = () => {};
+ globals.set("fetch", fetchStub);
+ globals.set("NewTabUtils", {
+ blockedLinks: { isBlocked: globals.sandbox.spy() },
+ });
+
+ const response = {
+ settings: { spocsPerNewTabs: 0.5 },
+ spocs: [{ id: "spoc1" }, { id: "spoc2" }],
+ };
+
+ instance.store.getState = () => ({
+ Sections: [{ id: "topstories", rows: response.recommendations }],
+ Prefs: { values: { showSponsored: false } },
+ });
+ fetchStub.resolves({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve(response),
+ });
+ await instance.onInit();
+
+ instance.onAction({
+ type: at.NEW_TAB_REHYDRATED,
+ meta: { fromTarget: {} },
+ });
+ assert.notCalled(instance.store.dispatch);
+ });
+ it("should not fail if there is no spoc", async () => {
+ let fetchStub = globals.sandbox.stub();
+ instance.dispatchSpocDone = () => {};
+ sectionsManagerStub.sections.set("topstories", {
+ options: {
+ show_spocs: true,
+ personalized: true,
+ stories_endpoint: "stories-endpoint",
+ },
+ });
+ instance.getPocketState = () => {};
+ instance.dispatchPocketCta = () => {};
+ globals.set("fetch", fetchStub);
+ globals.set("NewTabUtils", {
+ blockedLinks: { isBlocked: globals.sandbox.spy() },
+ });
+ globals.set("Math", {
+ random: () => 0.4,
+ min: Math.min,
+ });
+
+ const response = {
+ settings: { spocsPerNewTabs: 0.5 },
+ recommendations: [{ id: "rec1" }, { id: "rec2" }, { id: "rec3" }],
+ };
+
+ fetchStub.resolves({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve(response),
+ });
+ await instance.onInit();
+
+ instance.onAction({
+ type: at.NEW_TAB_REHYDRATED,
+ meta: { fromTarget: {} },
+ });
+ assert.notCalled(instance.store.dispatch);
+ });
+ it("should record spoc/campaign impressions for frequency capping", async () => {
+ let fetchStub = globals.sandbox.stub();
+ globals.set("fetch", fetchStub);
+ globals.set("NewTabUtils", {
+ blockedLinks: { isBlocked: globals.sandbox.spy() },
+ });
+ globals.set("Math", {
+ random: () => 0.4,
+ min: Math.min,
+ floor: Math.floor,
+ });
+
+ const response = {
+ settings: { spocsPerNewTabs: 0.5 },
+ spocs: [
+ { id: 1, campaign_id: 5 },
+ { id: 4, campaign_id: 6 },
+ ],
+ };
+
+ instance._prefs = { get: pref => undefined, set: sinon.spy() };
+ instance.show_spocs = true;
+ instance.stories_endpoint = "stories-endpoint";
+ fetchStub.resolves({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve(response),
+ });
+ await instance.fetchStories();
+
+ let expectedPrefValue = JSON.stringify({ 5: [0] });
+ instance.onAction({
+ type: at.TELEMETRY_IMPRESSION_STATS,
+ data: {
+ source: "TOP_STORIES",
+ tiles: [{ id: 3 }, { id: 2 }, { id: 1 }],
+ },
+ });
+ assert.calledWith(
+ instance._prefs.set.firstCall,
+ SPOC_IMPRESSION_TRACKING_PREF,
+ expectedPrefValue
+ );
+
+ clock.tick(1);
+ instance._prefs.get = pref => expectedPrefValue;
+ let expectedPrefValueCallTwo = JSON.stringify({ 5: [0, 1] });
+ instance.onAction({
+ type: at.TELEMETRY_IMPRESSION_STATS,
+ data: {
+ source: "TOP_STORIES",
+ tiles: [{ id: 3 }, { id: 2 }, { id: 1 }],
+ },
+ });
+ assert.calledWith(
+ instance._prefs.set.secondCall,
+ SPOC_IMPRESSION_TRACKING_PREF,
+ expectedPrefValueCallTwo
+ );
+
+ clock.tick(1);
+ instance._prefs.get = pref => expectedPrefValueCallTwo;
+ instance.onAction({
+ type: at.TELEMETRY_IMPRESSION_STATS,
+ data: {
+ source: "TOP_STORIES",
+ tiles: [{ id: 3 }, { id: 2 }, { id: 4 }],
+ },
+ });
+ assert.calledWith(
+ instance._prefs.set.thirdCall,
+ SPOC_IMPRESSION_TRACKING_PREF,
+ JSON.stringify({ 5: [0, 1], 6: [2] })
+ );
+ });
+ it("should not record spoc/campaign impressions for non-view impressions", async () => {
+ let fetchStub = globals.sandbox.stub();
+ sectionsManagerStub.sections.set("topstories", {
+ options: {
+ show_spocs: true,
+ stories_endpoint: "stories-endpoint",
+ },
+ });
+ globals.set("fetch", fetchStub);
+ globals.set("NewTabUtils", {
+ blockedLinks: { isBlocked: globals.sandbox.spy() },
+ });
+
+ const response = {
+ settings: { spocsPerNewTabs: 0.5 },
+ spocs: [
+ { id: 1, campaign_id: 5 },
+ { id: 4, campaign_id: 6 },
+ ],
+ };
+
+ instance._prefs = { get: pref => undefined, set: sinon.spy() };
+ fetchStub.resolves({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve(response),
+ });
+ await instance.onInit();
+
+ instance.onAction({
+ type: at.TELEMETRY_IMPRESSION_STATS,
+ data: { source: "TOP_STORIES", click: 0, tiles: [{ id: 1 }] },
+ });
+ assert.notCalled(instance._prefs.set);
+
+ instance.onAction({
+ type: at.TELEMETRY_IMPRESSION_STATS,
+ data: { source: "TOP_STORIES", block: 0, tiles: [{ id: 1 }] },
+ });
+ assert.notCalled(instance._prefs.set);
+
+ instance.onAction({
+ type: at.TELEMETRY_IMPRESSION_STATS,
+ data: { source: "TOP_STORIES", pocket: 0, tiles: [{ id: 1 }] },
+ });
+ assert.notCalled(instance._prefs.set);
+ });
+ it("should clean up spoc/campaign impressions", async () => {
+ let fetchStub = globals.sandbox.stub();
+ globals.set("fetch", fetchStub);
+ globals.set("NewTabUtils", {
+ blockedLinks: { isBlocked: globals.sandbox.spy() },
+ });
+
+ instance._prefs = { get: pref => undefined, set: sinon.spy() };
+ instance.show_spocs = true;
+ instance.stories_endpoint = "stories-endpoint";
+
+ const response = {
+ settings: { spocsPerNewTabs: 0.5 },
+ spocs: [
+ { id: 1, campaign_id: 5 },
+ { id: 4, campaign_id: 6 },
+ ],
+ };
+ fetchStub.resolves({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve(response),
+ });
+ await instance.fetchStories();
+
+ // simulate impressions for campaign 5 and 6
+ instance.onAction({
+ type: at.TELEMETRY_IMPRESSION_STATS,
+ data: {
+ source: "TOP_STORIES",
+ tiles: [{ id: 3 }, { id: 2 }, { id: 1 }],
+ },
+ });
+ instance._prefs.get = pref =>
+ pref === SPOC_IMPRESSION_TRACKING_PREF && JSON.stringify({ 5: [0] });
+ instance.onAction({
+ type: at.TELEMETRY_IMPRESSION_STATS,
+ data: {
+ source: "TOP_STORIES",
+ tiles: [{ id: 3 }, { id: 2 }, { id: 4 }],
+ },
+ });
+
+ let expectedPrefValue = JSON.stringify({ 5: [0], 6: [0] });
+ assert.calledWith(
+ instance._prefs.set.secondCall,
+ SPOC_IMPRESSION_TRACKING_PREF,
+ expectedPrefValue
+ );
+ instance._prefs.get = pref =>
+ pref === SPOC_IMPRESSION_TRACKING_PREF && expectedPrefValue;
+
+ // remove campaign 5 from response
+ const updatedResponse = {
+ settings: { spocsPerNewTabs: 1 },
+ spocs: [{ id: 4, campaign_id: 6 }],
+ };
+ fetchStub.resolves({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve(updatedResponse),
+ });
+ await instance.fetchStories();
+
+ // should remove campaign 5 from pref as no longer active
+ assert.calledWith(
+ instance._prefs.set.thirdCall,
+ SPOC_IMPRESSION_TRACKING_PREF,
+ JSON.stringify({ 6: [0] })
+ );
+ });
+ it("should maintain frequency caps when inserting spocs", async () => {
+ let fetchStub = globals.sandbox.stub();
+ instance.dispatchSpocDone = () => {};
+ sectionsManagerStub.sections.set("topstories", {
+ options: {
+ show_spocs: true,
+ personalized: true,
+ stories_endpoint: "stories-endpoint",
+ },
+ });
+ instance.getPocketState = () => {};
+ instance.dispatchPocketCta = () => {};
+ globals.set("fetch", fetchStub);
+ globals.set("NewTabUtils", {
+ blockedLinks: { isBlocked: globals.sandbox.spy() },
+ });
+
+ const response = {
+ settings: { spocsPerNewTabs: 1 },
+ recommendations: [{ guid: "rec1" }, { guid: "rec2" }, { guid: "rec3" }],
+ spocs: [
+ // Set spoc `expiration_timestamp`s in the very distant future to ensure they show up
+ {
+ id: "spoc1",
+ campaign_id: 1,
+ caps: { lifetime: 3, campaign: { count: 2, period: 3600 } },
+ expiration_timestamp: 999999999999,
+ },
+ {
+ id: "spoc2",
+ campaign_id: 2,
+ caps: { lifetime: 1 },
+ expiration_timestamp: 999999999999,
+ },
+ ],
+ };
+
+ instance.store.getState = () => ({
+ Sections: [{ id: "topstories", rows: response.recommendations }],
+ Prefs: { values: { showSponsored: true } },
+ });
+ fetchStub.resolves({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve(response),
+ });
+ await instance.onInit();
+ instance.spocsPerNewTabs = 1;
+
+ clock.tick();
+ instance.onAction({
+ type: at.NEW_TAB_REHYDRATED,
+ meta: { fromTarget: {} },
+ });
+ let [action] = instance.store.dispatch.firstCall.args;
+ assert.equal(action.data.rows[0].guid, "rec1");
+ assert.equal(action.data.rows[1].guid, "rec2");
+ assert.equal(action.data.rows[2].guid, "spoc1");
+ instance._prefs.get = pref => JSON.stringify({ 1: [1] });
+
+ clock.tick();
+ instance.onAction({
+ type: at.NEW_TAB_REHYDRATED,
+ meta: { fromTarget: {} },
+ });
+ [action] = instance.store.dispatch.secondCall.args;
+ assert.equal(action.data.rows[0].guid, "rec1");
+ assert.equal(action.data.rows[1].guid, "rec2");
+ assert.equal(action.data.rows[2].guid, "spoc1");
+ instance._prefs.get = pref => JSON.stringify({ 1: [1, 2] });
+
+ // campaign 1 period frequency cap now reached (spoc 2 should be shown)
+ clock.tick();
+ instance.onAction({
+ type: at.NEW_TAB_REHYDRATED,
+ meta: { fromTarget: {} },
+ });
+ [action] = instance.store.dispatch.thirdCall.args;
+ assert.equal(action.data.rows[0].guid, "rec1");
+ assert.equal(action.data.rows[1].guid, "rec2");
+ assert.equal(action.data.rows[2].guid, "spoc2");
+ instance._prefs.get = pref => JSON.stringify({ 1: [1, 2], 2: [3] });
+
+ // new campaign 1 period starting (spoc 1 sohuld be shown again)
+ clock.tick(2 * 60 * 60 * 1000);
+ instance.onAction({
+ type: at.NEW_TAB_REHYDRATED,
+ meta: { fromTarget: {} },
+ });
+ [action] = instance.store.dispatch.lastCall.args;
+ assert.equal(action.data.rows[0].guid, "rec1");
+ assert.equal(action.data.rows[1].guid, "rec2");
+ assert.equal(action.data.rows[2].guid, "spoc1");
+ instance._prefs.get = pref =>
+ JSON.stringify({ 1: [1, 2, 7200003], 2: [3] });
+
+ // campaign 1 lifetime cap now reached (no spoc should be sent)
+ instance.onAction({
+ type: at.NEW_TAB_REHYDRATED,
+ meta: { fromTarget: {} },
+ });
+ assert.callCount(instance.store.dispatch, 4);
+ });
+ it("should maintain client-side MAX_LIFETIME_CAP", async () => {
+ let fetchStub = globals.sandbox.stub();
+ instance.dispatchSpocDone = () => {};
+ sectionsManagerStub.sections.set("topstories", {
+ options: {
+ show_spocs: true,
+ personalized: true,
+ stories_endpoint: "stories-endpoint",
+ },
+ });
+ globals.set("fetch", fetchStub);
+ globals.set("NewTabUtils", {
+ blockedLinks: { isBlocked: globals.sandbox.spy() },
+ });
+ instance.getPocketState = () => {};
+ instance.dispatchPocketCta = () => {};
+
+ const response = {
+ settings: { spocsPerNewTabs: 1 },
+ recommendations: [{ guid: "rec1" }, { guid: "rec2" }, { guid: "rec3" }],
+ spocs: [{ id: "spoc1", campaign_id: 1, caps: { lifetime: 501 } }],
+ };
+
+ instance.store.getState = () => ({
+ Sections: [{ id: "topstories", rows: response.recommendations }],
+ Prefs: { values: { showSponsored: true } },
+ });
+ fetchStub.resolves({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve(response),
+ });
+ await instance.onInit();
+
+ instance._prefs.get = pref =>
+ JSON.stringify({ 1: [...Array(500).keys()] });
+ instance.onAction({
+ type: at.NEW_TAB_REHYDRATED,
+ meta: { fromTarget: {} },
+ });
+ assert.notCalled(instance.store.dispatch);
+ });
+ });
+ describe("#update", () => {
+ it("should fetch stories after update interval", async () => {
+ await instance.onInit();
+ sinon.spy(instance, "fetchStories");
+ await instance.onAction({ type: at.SYSTEM_TICK });
+ assert.notCalled(instance.fetchStories);
+
+ clock.tick(STORIES_UPDATE_TIME);
+ await instance.onAction({ type: at.SYSTEM_TICK });
+ assert.calledOnce(instance.fetchStories);
+ });
+ it("should fetch topics after update interval", async () => {
+ await instance.onInit();
+ sinon.spy(instance, "fetchTopics");
+ await instance.onAction({ type: at.SYSTEM_TICK });
+ assert.notCalled(instance.fetchTopics);
+
+ clock.tick(TOPICS_UPDATE_TIME);
+ await instance.onAction({ type: at.SYSTEM_TICK });
+ assert.calledOnce(instance.fetchTopics);
+ });
+ it("should return updated stories and topics on system tick", async () => {
+ await instance.onInit();
+ sinon.spy(instance, "dispatchUpdateEvent");
+ const stories = [{ guid: "rec1" }, { guid: "rec2" }, { guid: "rec3" }];
+ const topics = [
+ { name: "topic1", url: "url-topic1" },
+ { name: "topic2", url: "url-topic2" },
+ ];
+ clock.tick(TOPICS_UPDATE_TIME);
+ globals.sandbox.stub(instance, "fetchStories").resolves(stories);
+ globals.sandbox.stub(instance, "fetchTopics").resolves(topics);
+
+ await instance.onAction({ type: at.SYSTEM_TICK });
+
+ assert.calledOnce(instance.dispatchUpdateEvent);
+ assert.calledWith(instance.dispatchUpdateEvent, false, {
+ rows: [{ guid: "rec1" }, { guid: "rec2" }, { guid: "rec3" }],
+ topics: [
+ { name: "topic1", url: "url-topic1" },
+ { name: "topic2", url: "url-topic2" },
+ ],
+ read_more_endpoint: undefined,
+ });
+ });
+ it("should update domain affinities on idle-daily, if personalization preffed on", async () => {
+ instance.init();
+ instance.affinityProvider = undefined;
+ instance.cache.set = sinon.spy();
+
+ instance.observe("", "idle-daily");
+ assert.isUndefined(instance.affinityProvider);
+
+ instance.personalized = true;
+ instance.updateSettings({
+ timeSegments: {},
+ domainAffinityParameterSets: {},
+ });
+ clock.tick(MIN_DOMAIN_AFFINITIES_UPDATE_TIME);
+ await instance.observe("", "idle-daily");
+ assert.isDefined(instance.affinityProvider);
+ assert.calledOnce(instance.cache.set);
+ assert.calledWith(
+ instance.cache.set,
+ "domainAffinities",
+ Object.assign({}, instance.affinityProvider.getAffinities(), {
+ _timestamp: MIN_DOMAIN_AFFINITIES_UPDATE_TIME,
+ })
+ );
+ });
+ it("should not update domain affinities too often", () => {
+ instance.init();
+ instance.affinityProvider = undefined;
+ instance.cache.set = sinon.spy();
+
+ instance.personalized = true;
+ instance.updateSettings({
+ timeSegments: {},
+ domainAffinityParameterSets: {},
+ });
+ clock.tick(MIN_DOMAIN_AFFINITIES_UPDATE_TIME);
+ instance.domainAffinitiesLastUpdated = Date.now();
+ instance.observe("", "idle-daily");
+ assert.isUndefined(instance.affinityProvider);
+ });
+ it("should add idle-daily observer right away, before waiting on init data", async () => {
+ const addObserver = globals.sandbox.stub();
+ globals.set("Services", { obs: { addObserver } });
+ const initPromise = instance.onInit();
+ assert.calledOnce(addObserver);
+ await initPromise;
+ });
+ it("should not call init and uninit if data doesn't match on options change ", () => {
+ sinon.spy(instance, "init");
+ sinon.spy(instance, "uninit");
+ instance.onAction({ type: at.SECTION_OPTIONS_CHANGED, data: "foo" });
+ assert.notCalled(sectionsManagerStub.disableSection);
+ assert.notCalled(sectionsManagerStub.enableSection);
+ assert.notCalled(instance.init);
+ assert.notCalled(instance.uninit);
+ });
+ it("should call init and uninit on options change", async () => {
+ sinon.stub(instance, "clearCache").returns(Promise.resolve());
+ sinon.spy(instance, "init");
+ sinon.spy(instance, "uninit");
+ await instance.onAction({
+ type: at.SECTION_OPTIONS_CHANGED,
+ data: "topstories",
+ });
+ assert.calledOnce(sectionsManagerStub.disableSection);
+ assert.calledOnce(sectionsManagerStub.enableSection);
+ assert.calledOnce(instance.clearCache);
+ assert.calledOnce(instance.init);
+ assert.calledOnce(instance.uninit);
+ });
+ it("should set LastUpdated to 0 on init", async () => {
+ instance.storiesLastUpdated = 1;
+ instance.topicsLastUpdated = 1;
+
+ await instance.onInit();
+ assert.equal(instance.storiesLastUpdated, 0);
+ assert.equal(instance.topicsLastUpdated, 0);
+ });
+ it("should filter spocs when link is blocked", async () => {
+ instance.spocs = [{ url: "not_blocked" }, { url: "blocked" }];
+ await instance.onAction({
+ type: at.PLACES_LINK_BLOCKED,
+ data: { url: "blocked" },
+ });
+
+ assert.deepEqual(instance.spocs, [{ url: "not_blocked" }]);
+ });
+ it("should reset domain affinity scores if version changed", async () => {
+ instance.init();
+ instance.personalized = true;
+ instance.resetDomainAffinityScores = sinon.spy();
+ instance.updateSettings({
+ timeSegments: {},
+ domainAffinityParameterSets: {},
+ version: "1",
+ });
+ clock.tick(MIN_DOMAIN_AFFINITIES_UPDATE_TIME);
+ await instance.observe("", "idle-daily");
+ assert.notCalled(instance.resetDomainAffinityScores);
+
+ instance.updateSettings({
+ timeSegments: {},
+ domainAffinityParameterSets: {},
+ version: "2",
+ });
+ assert.calledOnce(instance.resetDomainAffinityScores);
+ });
+ });
+ describe("#loadCachedData", () => {
+ it("should update section with cached stories and topics if available", async () => {
+ sectionsManagerStub.sections.set("topstories", {
+ options: { stories_referrer: "referrer" },
+ });
+ const stories = {
+ _timestamp: 123,
+ recommendations: [
+ {
+ id: "1",
+ title: "title",
+ excerpt: "description",
+ image_src: "image-url",
+ url: "rec-url",
+ published_timestamp: "123",
+ context: "trending",
+ icon: "icon",
+ item_score: 0.98,
+ },
+ ],
+ };
+ const transformedStories = [
+ {
+ guid: "1",
+ type: "now",
+ title: "title",
+ context: "trending",
+ icon: "icon",
+ description: "description",
+ image: "image-url",
+ referrer: "referrer",
+ url: "rec-url",
+ hostname: "rec-url",
+ min_score: 0,
+ score: 0.98,
+ spoc_meta: {},
+ },
+ ];
+ const topics = {
+ _timestamp: 123,
+ topics: [
+ { name: "topic1", url: "url-topic1" },
+ { name: "topic2", url: "url-topic2" },
+ ],
+ };
+ instance.cache.get = () => ({ stories, topics });
+ globals.set("NewTabUtils", {
+ blockedLinks: { isBlocked: globals.sandbox.spy() },
+ });
+
+ await instance.onInit();
+ assert.calledOnce(sectionsManagerStub.updateSection);
+ assert.calledWith(sectionsManagerStub.updateSection, SECTION_ID, {
+ rows: transformedStories,
+ topics: topics.topics,
+ read_more_endpoint: undefined,
+ });
+ });
+ it("should NOT update section if there is no cached data", async () => {
+ instance.cache.get = () => ({});
+ globals.set("NewTabUtils", {
+ blockedLinks: { isBlocked: globals.sandbox.spy() },
+ });
+ await instance.loadCachedData();
+ assert.notCalled(sectionsManagerStub.updateSection);
+ });
+ it("should use store rows if no stories sent to doContentUpdate", async () => {
+ instance.store = {
+ getState() {
+ return {
+ Sections: [{ id: "topstories", rows: [1, 2, 3] }],
+ };
+ },
+ };
+ sinon.spy(instance, "dispatchUpdateEvent");
+
+ instance.doContentUpdate({}, false);
+
+ assert.calledOnce(instance.dispatchUpdateEvent);
+ assert.calledWith(instance.dispatchUpdateEvent, false, {
+ rows: [1, 2, 3],
+ });
+ });
+ it("should broadcast in doContentUpdate when updating from cache", async () => {
+ sectionsManagerStub.sections.set("topstories", {
+ options: { stories_referrer: "referrer" },
+ });
+ globals.set("NewTabUtils", { blockedLinks: { isBlocked: () => {} } });
+ const stories = { recommendations: [{}] };
+ const topics = { topics: [{}] };
+ sinon.spy(instance, "doContentUpdate");
+ instance.cache.get = () => ({ stories, topics });
+ await instance.onInit();
+ assert.calledOnce(instance.doContentUpdate);
+ assert.calledWith(
+ instance.doContentUpdate,
+ {
+ stories: [
+ {
+ context: undefined,
+ description: undefined,
+ guid: undefined,
+ hostname: undefined,
+ icon: undefined,
+ image: undefined,
+ min_score: 0,
+ referrer: "referrer",
+ score: 1,
+ spoc_meta: {},
+ title: undefined,
+ type: "trending",
+ url: undefined,
+ },
+ ],
+ topics: [{}],
+ },
+ true
+ );
+ });
+ it("should initialize user domain affinity provider from cache if personalization is preffed on", async () => {
+ const domainAffinities = {
+ parameterSets: {
+ default: {
+ recencyFactor: 0.4,
+ frequencyFactor: 0.5,
+ combinedDomainFactor: 0.5,
+ perfectFrequencyVisits: 10,
+ perfectCombinedDomainScore: 2,
+ multiDomainBoost: 0.1,
+ itemScoreFactor: 0,
+ },
+ },
+ scores: { "a.com": 1, "b.com": 0.9 },
+ maxHistoryQueryResults: 1000,
+ timeSegments: {},
+ version: "v1",
+ };
+
+ instance.affinityProvider = undefined;
+ instance.cache.get = () => ({ domainAffinities });
+
+ await instance.loadCachedData();
+ assert.isUndefined(instance.affinityProvider);
+ instance.personalized = true;
+ await instance.loadCachedData();
+ assert.isDefined(instance.affinityProvider);
+ assert.deepEqual(
+ instance.affinityProvider.timeSegments,
+ domainAffinities.timeSegments
+ );
+ assert.equal(
+ instance.affinityProvider.maxHistoryQueryResults,
+ domainAffinities.maxHistoryQueryResults
+ );
+ assert.deepEqual(
+ instance.affinityProvider.parameterSets,
+ domainAffinities.parameterSets
+ );
+ assert.deepEqual(
+ instance.affinityProvider.scores,
+ domainAffinities.scores
+ );
+ assert.deepEqual(
+ instance.affinityProvider.version,
+ domainAffinities.version
+ );
+ });
+ it("should clear domain affinity cache when history is cleared", () => {
+ instance.cache.set = sinon.spy();
+ instance.affinityProvider = {};
+ instance.personalized = true;
+
+ instance.onAction({ type: at.PLACES_HISTORY_CLEARED });
+ assert.calledWith(instance.cache.set, "domainAffinities", {});
+ assert.isUndefined(instance.affinityProvider);
+ });
+ });
+ describe("#pocket", () => {
+ it("should call getPocketState when hitting NEW_TAB_REHYDRATED", () => {
+ instance.getPocketState = sinon.spy();
+ instance.onAction({
+ type: at.NEW_TAB_REHYDRATED,
+ meta: { fromTarget: {} },
+ });
+ assert.calledOnce(instance.getPocketState);
+ assert.calledWith(instance.getPocketState, {});
+ });
+ it("should call dispatch in getPocketState", () => {
+ const isUserLoggedIn = sinon.spy();
+ globals.set("pktApi", { isUserLoggedIn });
+ instance.getPocketState({});
+ assert.calledOnce(instance.store.dispatch);
+ const [action] = instance.store.dispatch.firstCall.args;
+ assert.equal(action.type, "POCKET_LOGGED_IN");
+ assert.calledOnce(isUserLoggedIn);
+ });
+ it("should call dispatchPocketCta when hitting onInit", async () => {
+ instance.dispatchPocketCta = sinon.spy();
+ await instance.onInit();
+ assert.calledOnce(instance.dispatchPocketCta);
+ assert.calledWith(
+ instance.dispatchPocketCta,
+ JSON.stringify({
+ cta_button: "",
+ cta_text: "",
+ cta_url: "",
+ use_cta: false,
+ }),
+ false
+ );
+ });
+ it("should call dispatch in dispatchPocketCta", () => {
+ instance.dispatchPocketCta(JSON.stringify({ use_cta: true }), false);
+ assert.calledOnce(instance.store.dispatch);
+ const [action] = instance.store.dispatch.firstCall.args;
+ assert.equal(action.type, "POCKET_CTA");
+ assert.equal(action.data.use_cta, true);
+ });
+ it("should call dispatchPocketCta with a pocketCta pref change", () => {
+ instance.dispatchPocketCta = sinon.spy();
+ instance.onAction({
+ type: at.PREF_CHANGED,
+ data: {
+ name: "pocketCta",
+ value: JSON.stringify({
+ cta_button: "",
+ cta_text: "",
+ cta_url: "",
+ use_cta: false,
+ }),
+ },
+ });
+ assert.calledOnce(instance.dispatchPocketCta);
+ assert.calledWith(
+ instance.dispatchPocketCta,
+ JSON.stringify({
+ cta_button: "",
+ cta_text: "",
+ cta_url: "",
+ use_cta: false,
+ }),
+ true
+ );
+ });
+ });
+ it("should call uninit and init on disabling of showSponsored pref", async () => {
+ sinon.stub(instance, "clearCache").returns(Promise.resolve());
+ sinon.stub(instance, "uninit");
+ sinon.stub(instance, "init");
+ await instance.onAction({
+ type: at.PREF_CHANGED,
+ data: { name: "showSponsored", value: false },
+ });
+ assert.calledOnce(instance.clearCache);
+ assert.calledOnce(instance.uninit);
+ assert.calledOnce(instance.init);
+ });
+});
diff --git a/browser/components/newtab/test/unit/lib/UTEventReporting.test.js b/browser/components/newtab/test/unit/lib/UTEventReporting.test.js
new file mode 100644
index 0000000000..ad0e3063a1
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/UTEventReporting.test.js
@@ -0,0 +1,115 @@
+import { UTSessionPing, UTUserEventPing } from "test/schemas/pings";
+import { GlobalOverrider } from "test/unit/utils";
+import { UTEventReporting } from "lib/UTEventReporting.jsm";
+
+const FAKE_EVENT_PING_PC = {
+ event: "CLICK",
+ source: "TOP_SITES",
+ addon_version: "123",
+ user_prefs: 63,
+ session_id: "abc",
+ page: "about:newtab",
+ action_position: 5,
+ locale: "en-US",
+};
+const FAKE_SESSION_PING_PC = {
+ session_duration: 1234,
+ addon_version: "123",
+ user_prefs: 63,
+ session_id: "abc",
+ page: "about:newtab",
+ locale: "en-US",
+};
+const FAKE_EVENT_PING_UT = [
+ "activity_stream",
+ "event",
+ "CLICK",
+ "TOP_SITES",
+ {
+ addon_version: "123",
+ user_prefs: "63",
+ session_id: "abc",
+ page: "about:newtab",
+ action_position: "5",
+ },
+];
+const FAKE_SESSION_PING_UT = [
+ "activity_stream",
+ "end",
+ "session",
+ "1234",
+ {
+ addon_version: "123",
+ user_prefs: "63",
+ session_id: "abc",
+ page: "about:newtab",
+ },
+];
+
+describe("UTEventReporting", () => {
+ let globals;
+ let sandbox;
+ let utEvents;
+
+ beforeEach(() => {
+ globals = new GlobalOverrider();
+ sandbox = globals.sandbox;
+ sandbox.stub(global.Services.telemetry, "setEventRecordingEnabled");
+ sandbox.stub(global.Services.telemetry, "recordEvent");
+
+ utEvents = new UTEventReporting();
+ });
+
+ afterEach(() => {
+ globals.restore();
+ });
+
+ describe("#sendUserEvent()", () => {
+ it("should queue up the correct data to send to Events Telemetry", async () => {
+ utEvents.sendUserEvent(FAKE_EVENT_PING_PC);
+ assert.calledWithExactly(
+ global.Services.telemetry.recordEvent,
+ ...FAKE_EVENT_PING_UT
+ );
+
+ let ping = global.Services.telemetry.recordEvent.firstCall.args;
+ assert.validate(ping, UTUserEventPing);
+ });
+ });
+
+ describe("#sendSessionEndEvent()", () => {
+ it("should queue up the correct data to send to Events Telemetry", async () => {
+ utEvents.sendSessionEndEvent(FAKE_SESSION_PING_PC);
+ assert.calledWithExactly(
+ global.Services.telemetry.recordEvent,
+ ...FAKE_SESSION_PING_UT
+ );
+
+ let ping = global.Services.telemetry.recordEvent.firstCall.args;
+ assert.validate(ping, UTSessionPing);
+ });
+ });
+
+ describe("#uninit()", () => {
+ it("should call setEventRecordingEnabled with a false value", () => {
+ assert.equal(
+ global.Services.telemetry.setEventRecordingEnabled.firstCall.args[0],
+ "activity_stream"
+ );
+ assert.equal(
+ global.Services.telemetry.setEventRecordingEnabled.firstCall.args[1],
+ true
+ );
+
+ utEvents.uninit();
+ assert.equal(
+ global.Services.telemetry.setEventRecordingEnabled.secondCall.args[0],
+ "activity_stream"
+ );
+ assert.equal(
+ global.Services.telemetry.setEventRecordingEnabled.secondCall.args[1],
+ false
+ );
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/lib/UserDomainAffinityProvider.test.js b/browser/components/newtab/test/unit/lib/UserDomainAffinityProvider.test.js
new file mode 100644
index 0000000000..521a73fffc
--- /dev/null
+++ b/browser/components/newtab/test/unit/lib/UserDomainAffinityProvider.test.js
@@ -0,0 +1,256 @@
+import { GlobalOverrider } from "test/unit/utils";
+import { UserDomainAffinityProvider } from "lib/UserDomainAffinityProvider.jsm";
+
+const TIME_SEGMENTS = [
+ { id: "hour", startTime: 3600, endTime: 0, weightPosition: 1 },
+ { id: "day", startTime: 86400, endTime: 3600, weightPosition: 0.75 },
+ { id: "week", startTime: 604800, endTime: 86400, weightPosition: 0.5 },
+ { id: "weekPlus", startTime: null, endTime: 604800, weightPosition: 0.25 },
+];
+
+const PARAMETER_SETS = {
+ paramSet1: {
+ recencyFactor: 0.5,
+ frequencyFactor: 0.5,
+ combinedDomainFactor: 0.5,
+ perfectFrequencyVisits: 10,
+ perfectCombinedDomainScore: 2,
+ multiDomainBoost: 0.1,
+ itemScoreFactor: 0,
+ },
+ paramSet2: {
+ recencyFactor: 1,
+ frequencyFactor: 0.7,
+ combinedDomainFactor: 0.8,
+ perfectFrequencyVisits: 10,
+ perfectCombinedDomainScore: 2,
+ multiDomainBoost: 0.1,
+ itemScoreFactor: 0,
+ },
+};
+
+describe("User Domain Affinity Provider", () => {
+ let instance;
+ let globals;
+
+ beforeEach(() => {
+ globals = new GlobalOverrider();
+
+ const testUrl = "www.somedomain.com";
+ globals.sandbox
+ .stub(global.Services.io, "newURI")
+ .returns({ host: testUrl });
+
+ globals.sandbox.stub(global.PlacesUtils.history, "executeQuery").returns({
+ root: {
+ childCount: 1,
+ getChild: index => ({ uri: testUrl, accessCount: 1 }),
+ },
+ });
+ globals.sandbox
+ .stub(global.PlacesUtils.history, "getNewQuery")
+ .returns({ TIME_RELATIVE_NOW: 1 });
+ globals.sandbox
+ .stub(global.PlacesUtils.history, "getNewQueryOptions")
+ .returns({});
+
+ instance = new UserDomainAffinityProvider(TIME_SEGMENTS, PARAMETER_SETS);
+ });
+ afterEach(() => {
+ globals.restore();
+ });
+ describe("#init", () => {
+ function calculateScore(visitCounts, timeSeg, domain, ps) {
+ const vc = visitCounts[timeSeg][domain];
+ const score = instance.calculateScore(
+ vc * Number(ps.timeSegmentWeights[timeSeg]),
+ ps.perfectFrequencyVisits,
+ ps.frequencyFactor
+ );
+ return Math.min(1, score);
+ }
+ it("should create a UserDomainAffinityProvider", () => {
+ assert.instanceOf(instance, UserDomainAffinityProvider);
+ });
+ it("should calculate time segment weights for parameter sets", () => {
+ const expectedParamSets = Object.assign({}, PARAMETER_SETS);
+
+ // Verify that parameter set specific recencyFactor was applied
+ expectedParamSets.paramSet1.timeSegmentWeights = {
+ hour: 1,
+ day: 0.75,
+ week: 0.5,
+ weekPlus: 0.25,
+ };
+ expectedParamSets.paramSet2.timeSegmentWeights = {
+ hour: 1,
+ day: 1,
+ week: 1,
+ weekPlus: 1,
+ };
+ assert.deepEqual(expectedParamSets, instance.parameterSets);
+ });
+ it("should calculate user domain affinity scores", () => {
+ const ps1 = instance.parameterSets.paramSet1;
+ const ps2 = instance.parameterSets.paramSet2;
+
+ const visitCounts = {
+ hour: { "a.com": 1, "b.com": 2 },
+ day: { "a.com": 4 },
+ week: { "c.com": 1 },
+ weekPlus: { "a.com": 1, "d.com": 3 },
+ };
+ instance.queryVisits = ts => visitCounts[ts.id];
+
+ const expScoreAHourPs1 = calculateScore(
+ visitCounts,
+ "hour",
+ "a.com",
+ ps1
+ );
+ const expScoreBHourPs1 = calculateScore(
+ visitCounts,
+ "hour",
+ "b.com",
+ ps1
+ );
+ const expScoreAHourPs2 = calculateScore(
+ visitCounts,
+ "hour",
+ "a.com",
+ ps2
+ );
+ const expScoreBHourPs2 = calculateScore(
+ visitCounts,
+ "hour",
+ "b.com",
+ ps2
+ );
+ const expScoreADayPs1 = calculateScore(visitCounts, "day", "a.com", ps1);
+ const expScoreADayPs2 = calculateScore(visitCounts, "day", "a.com", ps2);
+ const expScoreCWeekPs1 = calculateScore(
+ visitCounts,
+ "week",
+ "c.com",
+ ps1
+ );
+ const expScoreCWeekPs2 = calculateScore(
+ visitCounts,
+ "week",
+ "c.com",
+ ps2
+ );
+ const expScoreAWeekPlusPs1 = calculateScore(
+ visitCounts,
+ "weekPlus",
+ "a.com",
+ ps1
+ );
+ const expScoreAWeekPlusPs2 = calculateScore(
+ visitCounts,
+ "weekPlus",
+ "a.com",
+ ps2
+ );
+ const expScoreDWeekPlusPs1 = calculateScore(
+ visitCounts,
+ "weekPlus",
+ "d.com",
+ ps1
+ );
+ const expScoreDWeekPlusPs2 = calculateScore(
+ visitCounts,
+ "weekPlus",
+ "d.com",
+ ps2
+ );
+ const expectedScores = {
+ "a.com": {
+ paramSet1: Math.min(
+ 1,
+ expScoreAHourPs1 + expScoreADayPs1 + expScoreAWeekPlusPs1
+ ),
+ paramSet2: Math.min(
+ 1,
+ expScoreAHourPs2 + expScoreADayPs2 + expScoreAWeekPlusPs2
+ ),
+ },
+ "b.com": { paramSet1: expScoreBHourPs1, paramSet2: expScoreBHourPs2 },
+ "c.com": { paramSet1: expScoreCWeekPs1, paramSet2: expScoreCWeekPs2 },
+ "d.com": {
+ paramSet1: expScoreDWeekPlusPs1,
+ paramSet2: expScoreDWeekPlusPs2,
+ },
+ };
+
+ const scores = instance.calculateAllUserDomainAffinityScores();
+ assert.deepEqual(expectedScores, scores);
+ });
+ it("should return domain affinities", () => {
+ const scores = {
+ "a.com": {
+ paramSet1: 1,
+ paramSet2: 0.9,
+ },
+ };
+ instance = new UserDomainAffinityProvider(
+ TIME_SEGMENTS,
+ PARAMETER_SETS,
+ 100,
+ "v1",
+ scores
+ );
+
+ const expectedAffinities = {
+ timeSegments: TIME_SEGMENTS,
+ parameterSets: PARAMETER_SETS,
+ maxHistoryQueryResults: 100,
+ scores,
+ version: "v1",
+ };
+ assert.deepEqual(instance.getAffinities(), expectedAffinities);
+ });
+ });
+ describe("#score", () => {
+ it("should calculate item relevance score", () => {
+ const ps = instance.parameterSets.paramSet2;
+
+ const visitCounts = {
+ hour: { "a.com": 1, "b.com": 2 },
+ day: { "a.com": 4 },
+ week: { "c.com": 1 },
+ weekPlus: { "a.com": 1, "d.com": 3 },
+ };
+ instance.queryVisits = ts => visitCounts[ts.id];
+ instance.scores = instance.calculateAllUserDomainAffinityScores();
+
+ const testItem = {
+ domain_affinities: { "a.com": 1 },
+ item_score: 1,
+ parameter_set: "paramSet2",
+ };
+ const combinedDomainScore =
+ instance.scores["a.com"].paramSet2 *
+ Math.pow(ps.multiDomainBoost + 1, 1);
+ const expectedItemScore = instance.calculateScore(
+ combinedDomainScore,
+ ps.perfectCombinedDomainScore,
+ ps.combinedDomainFactor
+ );
+
+ const itemScore = instance.calculateItemRelevanceScore(testItem);
+ assert.equal(expectedItemScore, itemScore);
+ });
+ it("should calculate relevance score equal to item_score if item has no domain affinities", () => {
+ const testItem = { item_score: 0.985 };
+ const itemScore = instance.calculateItemRelevanceScore(testItem);
+ assert.equal(testItem.item_score, itemScore);
+ });
+ it("should calculate scores with factor", () => {
+ assert.equal(1, instance.calculateScore(2, 1, 0.5));
+ assert.equal(0.5, instance.calculateScore(0.5, 1, 0.5));
+ assert.isBelow(instance.calculateScore(0.5, 1, 0.49), 1);
+ assert.isBelow(instance.calculateScore(0.5, 1, 0.51), 1);
+ });
+ });
+});
diff --git a/browser/components/newtab/test/unit/unit-entry.js b/browser/components/newtab/test/unit/unit-entry.js
new file mode 100644
index 0000000000..f81d9c08ae
--- /dev/null
+++ b/browser/components/newtab/test/unit/unit-entry.js
@@ -0,0 +1,482 @@
+import { EventEmitter, FakePrefs, GlobalOverrider } from "test/unit/utils";
+import Adapter from "enzyme-adapter-react-16";
+import { chaiAssertions } from "test/schemas/pings";
+import chaiJsonSchema from "chai-json-schema";
+import enzyme from "enzyme";
+enzyme.configure({ adapter: new Adapter() });
+
+// Cause React warnings to make tests that trigger them fail
+const origConsoleError = console.error; // eslint-disable-line no-console
+// eslint-disable-next-line no-console
+console.error = function(msg, ...args) {
+ // eslint-disable-next-line no-console
+ origConsoleError.apply(console, [msg, ...args]);
+
+ if (
+ /(Invalid prop|Failed prop type|Check the render method|React Intl)/.test(
+ msg
+ )
+ ) {
+ throw new Error(msg);
+ }
+};
+
+const req = require.context(".", true, /\.test\.jsx?$/);
+const files = req.keys();
+
+// This exposes sinon assertions to chai.assert
+sinon.assert.expose(assert, { prefix: "" });
+
+chai.use(chaiAssertions);
+chai.use(chaiJsonSchema);
+
+const overrider = new GlobalOverrider();
+
+const RemoteSettings = name => ({
+ get: () => {
+ if (name === "attachment") {
+ return Promise.resolve([{ attachment: {} }]);
+ }
+ return Promise.resolve([]);
+ },
+ on: () => {},
+ off: () => {},
+});
+RemoteSettings.pollChanges = () => {};
+
+class JSWindowActorParent {
+ sendAsyncMessage(name, data) {
+ return { name, data };
+ }
+}
+
+class JSWindowActorChild {
+ sendAsyncMessage(name, data) {
+ return { name, data };
+ }
+
+ sendQuery(name, data) {
+ return Promise.resolve({ name, data });
+ }
+
+ get contentWindow() {
+ return {
+ Promise,
+ };
+ }
+}
+
+const TEST_GLOBAL = {
+ JSWindowActorParent,
+ JSWindowActorChild,
+ AboutReaderParent: {
+ addMessageListener: (messageName, listener) => {},
+ removeMessageListener: (messageName, listener) => {},
+ },
+ AddonManager: {
+ getActiveAddons() {
+ return Promise.resolve({ addons: [], fullData: false });
+ },
+ },
+ AppConstants: {
+ MOZILLA_OFFICIAL: true,
+ MOZ_APP_VERSION: "69.0a1",
+ platform: "win",
+ },
+ UpdateUtils: { getUpdateChannel() {} },
+ BasePromiseWorker: class {
+ constructor() {
+ this.ExceptionHandlers = [];
+ }
+ post() {}
+ },
+ browserSearchRegion: "US",
+ BrowserWindowTracker: { getTopWindow() {} },
+ ChromeUtils: {
+ defineModuleGetter() {},
+ generateQI() {
+ return {};
+ },
+ import() {
+ return global;
+ },
+ },
+ ClientEnvironment: {
+ get userId() {
+ return "foo123";
+ },
+ },
+ Components: {
+ Constructor(classId) {
+ switch (classId) {
+ case "@mozilla.org/referrer-info;1":
+ return function(referrerPolicy, sendReferrer, originalReferrer) {
+ this.referrerPolicy = referrerPolicy;
+ this.sendReferrer = sendReferrer;
+ this.originalReferrer = originalReferrer;
+ };
+ }
+ return function() {};
+ },
+ isSuccessCode: () => true,
+ },
+ // NB: These are functions/constructors
+ // eslint-disable-next-line object-shorthand
+ ContentSearchUIController: function() {},
+ // eslint-disable-next-line object-shorthand
+ ContentSearchHandoffUIController: function() {},
+ Cc: {
+ "@mozilla.org/browser/nav-bookmarks-service;1": {
+ addObserver() {},
+ getService() {
+ return this;
+ },
+ removeObserver() {},
+ SOURCES: {},
+ TYPE_BOOKMARK: {},
+ },
+ "@mozilla.org/browser/nav-history-service;1": {
+ addObserver() {},
+ executeQuery() {},
+ getNewQuery() {},
+ getNewQueryOptions() {},
+ getService() {
+ return this;
+ },
+ insert() {},
+ markPageAsTyped() {},
+ removeObserver() {},
+ },
+ "@mozilla.org/io/string-input-stream;1": {
+ createInstance() {
+ return {};
+ },
+ },
+ "@mozilla.org/security/hash;1": {
+ createInstance() {
+ return {
+ init() {},
+ updateFromStream() {},
+ finish() {
+ return "0";
+ },
+ };
+ },
+ },
+ "@mozilla.org/updates/update-checker;1": { createInstance() {} },
+ "@mozilla.org/streamConverters;1": {
+ getService() {
+ return this;
+ },
+ },
+ "@mozilla.org/network/stream-loader;1": {
+ createInstance() {
+ return {};
+ },
+ },
+ },
+ Ci: {
+ nsICryptoHash: {},
+ nsIReferrerInfo: { UNSAFE_URL: 5 },
+ nsITimer: { TYPE_ONE_SHOT: 1 },
+ nsIWebProgressListener: { LOCATION_CHANGE_SAME_DOCUMENT: 1 },
+ nsIDOMWindow: Object,
+ nsITrackingDBService: {
+ TRACKERS_ID: 1,
+ TRACKING_COOKIES_ID: 2,
+ CRYPTOMINERS_ID: 3,
+ FINGERPRINTERS_ID: 4,
+ SOCIAL_ID: 5,
+ },
+ },
+ Cu: {
+ importGlobalProperties() {},
+ now: () => window.performance.now(),
+ reportError() {},
+ },
+ dump() {},
+ EveryWindow: {
+ registerCallback: (id, init, uninit) => {},
+ unregisterCallback: id => {},
+ },
+ fetch() {},
+ // eslint-disable-next-line object-shorthand
+ Image: function() {}, // NB: This is a function/constructor
+ NewTabUtils: {
+ activityStreamProvider: {
+ getTopFrecentSites: () => [],
+ executePlacesQuery: async (sql, options) => ({ sql, options }),
+ },
+ },
+ OS: {
+ File: {
+ writeAtomic() {},
+ makeDir() {},
+ stat() {},
+ Error: {},
+ read() {},
+ exists() {},
+ remove() {},
+ removeEmptyDir() {},
+ },
+ Path: {
+ join() {
+ return "/";
+ },
+ },
+ Constants: {
+ Path: {
+ localProfileDir: "/",
+ },
+ },
+ },
+ PlacesUtils: {
+ get bookmarks() {
+ return TEST_GLOBAL.Cc["@mozilla.org/browser/nav-bookmarks-service;1"];
+ },
+ get history() {
+ return TEST_GLOBAL.Cc["@mozilla.org/browser/nav-history-service;1"];
+ },
+ observers: {
+ addListener() {},
+ removeListener() {},
+ },
+ },
+ PluralForm: { get() {} },
+ Preferences: FakePrefs,
+ PrivateBrowsingUtils: {
+ isBrowserPrivate: () => false,
+ isWindowPrivate: () => false,
+ },
+ DownloadsViewUI: {
+ getDisplayName: () => "filename.ext",
+ getSizeWithUnits: () => "1.5 MB",
+ },
+ FileUtils: {
+ // eslint-disable-next-line object-shorthand
+ File: function() {}, // NB: This is a function/constructor
+ },
+ Region: {
+ home: "US",
+ REGION_TOPIC: "browser-region",
+ REGION_UPDATED: "region-updated",
+ },
+ Services: {
+ dirsvc: {
+ get: () => ({ parent: { parent: { path: "appPath" } } }),
+ },
+ locale: {
+ get appLocaleAsBCP47() {
+ return "en-US";
+ },
+ negotiateLanguages() {},
+ },
+ urlFormatter: { formatURL: str => str, formatURLPref: str => str },
+ mm: {
+ addMessageListener: (msg, cb) => this.receiveMessage(),
+ removeMessageListener() {},
+ },
+ obs: {
+ addObserver() {},
+ removeObserver() {},
+ notifyObservers() {},
+ },
+ telemetry: {
+ setEventRecordingEnabled: () => {},
+ recordEvent: eventDetails => {},
+ scalarSet: () => {},
+ },
+ console: { logStringMessage: () => {} },
+ prefs: {
+ addObserver() {},
+ prefHasUserValue() {},
+ removeObserver() {},
+ getPrefType() {},
+ clearUserPref() {},
+ getChildList() {
+ return [];
+ },
+ getStringPref() {},
+ setStringPref() {},
+ getIntPref() {},
+ getBoolPref() {},
+ getCharPref() {},
+ setBoolPref() {},
+ setCharPref() {},
+ setIntPref() {},
+ getBranch() {},
+ PREF_BOOL: "boolean",
+ PREF_INT: "integer",
+ PREF_STRING: "string",
+ getDefaultBranch() {
+ return {
+ setBoolPref() {},
+ setIntPref() {},
+ setStringPref() {},
+ clearUserPref() {},
+ };
+ },
+ },
+ tm: {
+ dispatchToMainThread: cb => cb(),
+ idleDispatchToMainThread: cb => cb(),
+ },
+ eTLD: {
+ getBaseDomain({ spec }) {
+ return spec.match(/\/([^/]+)/)[1];
+ },
+ getBaseDomainFromHost(host) {
+ return host.match(/.*?(\w+\.\w+)$/)[1];
+ },
+ getPublicSuffix() {},
+ },
+ io: {
+ newURI: spec => ({
+ mutate: () => ({
+ setRef: ref => ({
+ finalize: () => ({
+ ref,
+ spec,
+ }),
+ }),
+ }),
+ spec,
+ }),
+ },
+ search: {
+ init() {
+ return Promise.resolve();
+ },
+ getVisibleEngines: () =>
+ Promise.resolve([{ identifier: "google" }, { identifier: "bing" }]),
+ defaultEngine: {
+ identifier: "google",
+ searchForm:
+ "https://www.google.com/search?q=&ie=utf-8&oe=utf-8&client=firefox-b",
+ aliases: ["@google"],
+ },
+ defaultPrivateEngine: {
+ identifier: "bing",
+ searchForm: "https://www.bing.com",
+ aliases: ["@bing"],
+ },
+ getEngineByAlias: async () => null,
+ },
+ scriptSecurityManager: {
+ createNullPrincipal() {},
+ getSystemPrincipal() {},
+ },
+ wm: {
+ getMostRecentWindow: () => window,
+ getMostRecentBrowserWindow: () => window,
+ getEnumerator: () => [],
+ },
+ ww: { registerNotification() {}, unregisterNotification() {} },
+ appinfo: { appBuildID: "20180710100040", version: "69.0a1" },
+ scriptloader: { loadSubScript: () => {} },
+ startup: {
+ getStartupInfo() {
+ return {
+ process: {
+ getTime() {
+ return 1588010448000;
+ },
+ },
+ };
+ },
+ },
+ },
+ XPCOMUtils: {
+ defineLazyGetter(object, name, f) {
+ if (object && name) {
+ object[name] = f();
+ } else {
+ f();
+ }
+ },
+ defineLazyGlobalGetters() {},
+ defineLazyModuleGetter() {},
+ defineLazyModuleGetters() {},
+ defineLazyServiceGetter() {},
+ defineLazyServiceGetters() {},
+ defineLazyPreferenceGetter(obj, name) {
+ Object.defineProperty(obj, name, {
+ configurable: true,
+ get: () => "",
+ });
+ },
+ generateQI() {
+ return {};
+ },
+ },
+ EventEmitter,
+ ShellService: { isDefaultBrowser: () => true },
+ FilterExpressions: {
+ eval() {
+ return Promise.resolve(false);
+ },
+ },
+ RemoteSettings,
+ Localization: class {
+ async formatMessages(stringsIds) {
+ return Promise.resolve(
+ stringsIds.map(({ id, args }) => ({ value: { string_id: id, args } }))
+ );
+ }
+ },
+ FxAccountsConfig: {
+ promiseConnectAccountURI(id) {
+ return Promise.resolve(id);
+ },
+ },
+ FX_MONITOR_OAUTH_CLIENT_ID: "fake_client_id",
+ ExperimentAPI: {
+ getExperiment() {},
+ on: () => {},
+ off: () => {},
+ },
+ TelemetryEnvironment: {
+ setExperimentActive() {},
+ currentEnvironment: {
+ profile: {
+ creationDate: 16587,
+ },
+ settings: {},
+ },
+ },
+ TelemetryStopwatch: {
+ start: () => {},
+ finish: () => {},
+ },
+ Sampling: {
+ ratioSample(seed, ratios) {
+ return Promise.resolve(0);
+ },
+ },
+ BrowserHandler: {
+ get kiosk() {
+ return false;
+ },
+ },
+ TelemetrySession: {
+ getMetadata(reason) {
+ return {
+ reason,
+ sessionId: "fake_session_id",
+ };
+ },
+ },
+ PageThumbs: {
+ addExpirationFilter() {},
+ removeExpirationFilter() {},
+ },
+ gUUIDGenerator: {
+ generateUUID: () => "{foo-123-foo}",
+ },
+};
+overrider.set(TEST_GLOBAL);
+
+describe("activity-stream", () => {
+ after(() => overrider.restore());
+ files.forEach(file => req(file));
+});
diff --git a/browser/components/newtab/test/unit/utils.js b/browser/components/newtab/test/unit/utils.js
new file mode 100644
index 0000000000..ab0161448c
--- /dev/null
+++ b/browser/components/newtab/test/unit/utils.js
@@ -0,0 +1,263 @@
+/**
+ * GlobalOverrider - Utility that allows you to override properties on the global object.
+ * See unit-entry.js for example usage.
+ */
+export class GlobalOverrider {
+ constructor() {
+ this.originalGlobals = new Map();
+ this.sandbox = sinon.createSandbox();
+ }
+
+ /**
+ * _override - Internal method to override properties on the global object.
+ * The first time a given key is overridden, we cache the original
+ * value in this.originalGlobals so that later it can be restored.
+ *
+ * @param {string} key The identifier of the property
+ * @param {any} value The value to which the property should be reassigned
+ */
+ _override(key, value) {
+ if (!this.originalGlobals.has(key)) {
+ this.originalGlobals.set(key, global[key]);
+ }
+ global[key] = value;
+ }
+
+ /**
+ * set - Override a given property, or all properties on an object
+ *
+ * @param {string|object} key If a string, the identifier of the property
+ * If an object, a number of properties and values to which they should be reassigned.
+ * @param {any} value The value to which the property should be reassigned
+ * @return {type} description
+ */
+ set(key, value) {
+ if (!value && typeof key === "object") {
+ const overrides = key;
+ Object.keys(overrides).forEach(k => this._override(k, overrides[k]));
+ } else {
+ this._override(key, value);
+ }
+ return value;
+ }
+
+ /**
+ * reset - Reset the global sandbox, so all state on spies, stubs etc. is cleared.
+ * You probably want to call this after each test.
+ */
+ reset() {
+ this.sandbox.reset();
+ }
+
+ /**
+ * restore - Restore the global sandbox and reset all overriden properties to
+ * their original values. You should call this after all tests have completed.
+ */
+ restore() {
+ this.sandbox.restore();
+ this.originalGlobals.forEach((value, key) => {
+ global[key] = value;
+ });
+ }
+}
+
+/**
+ * Very simple fake for the most basic semantics of nsIPrefBranch. Lots of
+ * things aren't yet supported. Feel free to add them in.
+ *
+ * @param {Object} args - optional arguments
+ * @param {Function} args.initHook - if present, will be called back
+ * inside the constructor. Typically used from tests
+ * to save off a pointer to the created instance so that
+ * stubs and spies can be inspected by the test code.
+ */
+export class FakensIPrefBranch {
+ constructor(args) {
+ if (args) {
+ if ("initHook" in args) {
+ args.initHook.call(this);
+ }
+ if (args.defaultBranch) {
+ this.prefs = {};
+ }
+ }
+ this._prefBranch = {};
+ this.observers = {};
+ }
+ addObserver(prefName, callback) {
+ this.observers[prefName] = callback;
+ }
+ removeObserver(prefName, callback) {
+ if (prefName in this.observers) {
+ delete this.observers[prefName];
+ }
+ }
+ observeBranch(listener) {}
+ ignoreBranch(listener) {}
+ setStringPref(prefName) {}
+
+ getStringPref(prefName) {
+ return this.get(prefName);
+ }
+ getBoolPref(prefName) {
+ return this.get(prefName);
+ }
+ get(prefName) {
+ return this.prefs[prefName];
+ }
+ setBoolPref(prefName, value) {
+ this.prefs[prefName] = value;
+
+ if (prefName in this.observers) {
+ this.observers[prefName]("", "", prefName);
+ }
+ }
+}
+FakensIPrefBranch.prototype.prefs = {};
+
+/**
+ * Very simple fake for the most basic semantics of Preferences.jsm.
+ * Extends FakensIPrefBranch.
+ */
+export class FakePrefs extends FakensIPrefBranch {
+ observe(prefName, callback) {
+ super.addObserver(prefName, callback);
+ }
+ ignore(prefName, callback) {
+ super.removeObserver(prefName, callback);
+ }
+ set(prefName, value) {
+ this.prefs[prefName] = value;
+
+ if (prefName in this.observers) {
+ this.observers[prefName](value);
+ }
+ }
+}
+
+/**
+ * Slimmed down version of toolkit/modules/EventEmitter.jsm
+ */
+export function EventEmitter() {}
+EventEmitter.decorate = function(objectToDecorate) {
+ let emitter = new EventEmitter();
+ objectToDecorate.on = emitter.on.bind(emitter);
+ objectToDecorate.off = emitter.off.bind(emitter);
+ objectToDecorate.once = emitter.once.bind(emitter);
+ objectToDecorate.emit = emitter.emit.bind(emitter);
+};
+EventEmitter.prototype = {
+ on(event, listener) {
+ if (!this._eventEmitterListeners) {
+ this._eventEmitterListeners = new Map();
+ }
+ if (!this._eventEmitterListeners.has(event)) {
+ this._eventEmitterListeners.set(event, []);
+ }
+ this._eventEmitterListeners.get(event).push(listener);
+ },
+ off(event, listener) {
+ if (!this._eventEmitterListeners) {
+ return;
+ }
+ let listeners = this._eventEmitterListeners.get(event);
+ if (listeners) {
+ this._eventEmitterListeners.set(
+ event,
+ listeners.filter(
+ l => l !== listener && l._originalListener !== listener
+ )
+ );
+ }
+ },
+ once(event, listener) {
+ return new Promise(resolve => {
+ let handler = (_, first, ...rest) => {
+ this.off(event, handler);
+ if (listener) {
+ listener(event, first, ...rest);
+ }
+ resolve(first);
+ };
+
+ handler._originalListener = listener;
+ this.on(event, handler);
+ });
+ },
+ // All arguments to this method will be sent to listeners
+ emit(event, ...args) {
+ if (
+ !this._eventEmitterListeners ||
+ !this._eventEmitterListeners.has(event)
+ ) {
+ return;
+ }
+ let originalListeners = this._eventEmitterListeners.get(event);
+ for (let listener of this._eventEmitterListeners.get(event)) {
+ // If the object was destroyed during event emission, stop
+ // emitting.
+ if (!this._eventEmitterListeners) {
+ break;
+ }
+ // If listeners were removed during emission, make sure the
+ // event handler we're going to fire wasn't removed.
+ if (
+ originalListeners === this._eventEmitterListeners.get(event) ||
+ this._eventEmitterListeners.get(event).some(l => l === listener)
+ ) {
+ try {
+ listener(event, ...args);
+ } catch (ex) {
+ // error with a listener
+ }
+ }
+ }
+ },
+};
+
+export function FakePerformance() {}
+FakePerformance.prototype = {
+ marks: new Map(),
+ now() {
+ return window.performance.now();
+ },
+ timing: { navigationStart: 222222.123 },
+ get timeOrigin() {
+ return 10000.234;
+ },
+ // XXX assumes type == "mark"
+ getEntriesByName(name, type) {
+ if (this.marks.has(name)) {
+ return this.marks.get(name);
+ }
+ return [];
+ },
+ callsToMark: 0,
+
+ /**
+ * @note The "startTime" for each mark is simply the number of times mark
+ * has been called in this object.
+ */
+ mark(name) {
+ let markObj = {
+ name,
+ entryType: "mark",
+ startTime: ++this.callsToMark,
+ duration: 0,
+ };
+
+ if (this.marks.has(name)) {
+ this.marks.get(name).push(markObj);
+ return;
+ }
+
+ this.marks.set(name, [markObj]);
+ },
+};
+
+/**
+ * addNumberReducer - a simple dummy reducer for testing that adds a number
+ */
+export function addNumberReducer(prevState = 0, action) {
+ return action.type === "ADD" ? prevState + action.data : prevState;
+}
diff --git a/browser/components/newtab/test/xpcshell/ds_layout.json b/browser/components/newtab/test/xpcshell/ds_layout.json
new file mode 100644
index 0000000000..f003a66e2f
--- /dev/null
+++ b/browser/components/newtab/test/xpcshell/ds_layout.json
@@ -0,0 +1,89 @@
+{
+ "spocs": {
+ "url": ""
+ },
+ "layout": [
+ {
+ "width": 12,
+ "components": [
+ {
+ "type": "TopSites",
+ "header": {
+ "title": "Top Sites"
+ },
+ "properties": null
+ },
+ {
+ "type": "Message",
+ "header": {
+ "title": "Recommended by Pocket",
+ "subtitle": "",
+ "link_text": "How it works",
+ "link_url": "https://getpocket.com/firefox/new_tab_learn_more",
+ "icon": "chrome://activity-stream/content/data/content/assets/glyph-pocket-16.svg"
+ },
+ "properties": null,
+ "styles": {
+ ".ds-message": "margin-bottom: -20px"
+ }
+ },
+ {
+ "type": "CardGrid",
+ "properties": {
+ "items": 3
+ },
+ "header": {
+ "title": ""
+ },
+ "feed": {
+ "embed_reference": null,
+ "url": "http://example.com/topstories.json"
+ },
+ "spocs": {
+ "probability": 1,
+ "positions": [
+ {
+ "index": 2
+ }
+ ]
+ }
+ },
+ {
+ "type": "Navigation",
+ "properties": {
+ "alignment": "left-align",
+ "links": [
+ {
+ "name": "Must Reads",
+ "url": "https://getpocket.com/explore/must-reads?src=fx_new_tab"
+ },
+ {
+ "name": "Productivity",
+ "url": "https://getpocket.com/explore/productivity?src=fx_new_tab"
+ },
+ {
+ "name": "Health",
+ "url": "https://getpocket.com/explore/health?src=fx_new_tab"
+ },
+ {
+ "name": "Finance",
+ "url": "https://getpocket.com/explore/finance?src=fx_new_tab"
+ },
+ {
+ "name": "Technology",
+ "url": "https://getpocket.com/explore/technology?src=fx_new_tab"
+ },
+ {
+ "name": "More Recommendations ›",
+ "url": "https://getpocket.com/explore/trending?src=fx_new_tab"
+ }
+ ]
+ }
+ }
+ ]
+ }
+ ],
+ "feeds": {},
+ "error": 0,
+ "status": 1
+}
diff --git a/browser/components/newtab/test/xpcshell/head.js b/browser/components/newtab/test/xpcshell/head.js
new file mode 100644
index 0000000000..d0e7cc6529
--- /dev/null
+++ b/browser/components/newtab/test/xpcshell/head.js
@@ -0,0 +1,11 @@
+/* Any copyright is dedicated to the Public Domain.
+http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/* eslint-disable no-unused-vars */
+
+const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
+const { XPCOMUtils } = ChromeUtils.import(
+ "resource://gre/modules/XPCOMUtils.jsm"
+);
diff --git a/browser/components/newtab/test/xpcshell/test_ASRouterTargeting_attribution.js b/browser/components/newtab/test/xpcshell/test_ASRouterTargeting_attribution.js
new file mode 100644
index 0000000000..6962ca6aa3
--- /dev/null
+++ b/browser/components/newtab/test/xpcshell/test_ASRouterTargeting_attribution.js
@@ -0,0 +1,64 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/
+ */
+
+"use strict";
+
+const { AttributionCode } = ChromeUtils.import(
+ "resource:///modules/AttributionCode.jsm"
+);
+const { ASRouterTargeting } = ChromeUtils.import(
+ "resource://activity-stream/lib/ASRouterTargeting.jsm"
+);
+const { MacAttribution } = ChromeUtils.import(
+ "resource:///modules/MacAttribution.jsm"
+);
+
+add_task(async function check_attribution_data() {
+ // Some setup to fake the correct attribution data
+ const appPath = MacAttribution.applicationPath;
+ const attributionSvc = Cc["@mozilla.org/mac-attribution;1"].getService(
+ Ci.nsIMacAttributionService
+ );
+ const campaign = "non-fx-button";
+ const source = "addons.mozilla.org";
+ const referrer = `https://allizom.org/anything/?utm_campaign=${campaign}&utm_source=${source}`;
+ attributionSvc.setReferrerUrl(appPath, referrer, true);
+ AttributionCode._clearCache();
+ await AttributionCode.getAttrDataAsync();
+
+ const {
+ campaign: attributionCampain,
+ source: attributionSource,
+ } = ASRouterTargeting.Environment.attributionData;
+ equal(
+ attributionCampain,
+ campaign,
+ "should get the correct campaign out of attributionData"
+ );
+ equal(
+ attributionSource,
+ source,
+ "should get the correct source out of attributionData"
+ );
+
+ const messages = [
+ {
+ id: "foo1",
+ targeting:
+ "attributionData.campaign == 'back_to_school' && attributionData.source == 'addons.mozilla.org'",
+ },
+ {
+ id: "foo2",
+ targeting:
+ "attributionData.campaign == 'non-fx-button' && attributionData.source == 'addons.mozilla.org'",
+ },
+ ];
+
+ equal(
+ await ASRouterTargeting.findMatchingMessage({ messages }),
+ messages[1],
+ "should select the message with the correct campaign and source"
+ );
+ AttributionCode._clearCache();
+});
diff --git a/browser/components/newtab/test/xpcshell/test_AboutHomeStartupCacheChild.js b/browser/components/newtab/test/xpcshell/test_AboutHomeStartupCacheChild.js
new file mode 100644
index 0000000000..a0cb2cf324
--- /dev/null
+++ b/browser/components/newtab/test/xpcshell/test_AboutHomeStartupCacheChild.js
@@ -0,0 +1,33 @@
+/* Any copyright is dedicated to the Public Domain.
+http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const { AboutHomeStartupCacheChild } = ChromeUtils.import(
+ "resource:///modules/AboutNewTabService.jsm"
+);
+
+/**
+ * Tests that AboutHomeStartupCacheChild will terminate its PromiseWorker
+ * on memory-pressure, and that a new PromiseWorker can then be generated on
+ * demand.
+ */
+add_task(async function test_memory_pressure() {
+ AboutHomeStartupCacheChild.init();
+
+ let worker = AboutHomeStartupCacheChild.getOrCreateWorker();
+ Assert.ok(worker, "Should have been able to get the worker.");
+
+ Assert.equal(
+ worker,
+ AboutHomeStartupCacheChild.getOrCreateWorker(),
+ "The worker is cached and re-usable."
+ );
+
+ Services.obs.notifyObservers(null, "memory-pressure", "heap-minimize");
+
+ let newWorker = AboutHomeStartupCacheChild.getOrCreateWorker();
+ Assert.notEqual(worker, newWorker, "Old worker should have been replaced.");
+
+ AboutHomeStartupCacheChild.uninit();
+});
diff --git a/browser/components/newtab/test/xpcshell/test_AboutHomeStartupCacheWorker.js b/browser/components/newtab/test/xpcshell/test_AboutHomeStartupCacheWorker.js
new file mode 100644
index 0000000000..6ca1085250
--- /dev/null
+++ b/browser/components/newtab/test/xpcshell/test_AboutHomeStartupCacheWorker.js
@@ -0,0 +1,239 @@
+/* Any copyright is dedicated to the Public Domain.
+http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * This test ensures that the about:home startup cache worker
+ * script can correctly convert a state object from the Activity
+ * Stream Redux store into an HTML document and script.
+ */
+
+const { AddonTestUtils } = ChromeUtils.import(
+ "resource://testing-common/AddonTestUtils.jsm"
+);
+const { TestUtils } = ChromeUtils.import(
+ "resource://testing-common/TestUtils.jsm"
+);
+
+AddonTestUtils.init(this);
+AddonTestUtils.createAppInfo(
+ "xpcshell@tests.mozilla.org",
+ "XPCShell",
+ "42",
+ "42"
+);
+
+const { AboutNewTab } = ChromeUtils.import(
+ "resource:///modules/AboutNewTab.jsm"
+);
+const { PREFS_CONFIG } = ChromeUtils.import(
+ "resource://activity-stream/lib/ActivityStream.jsm"
+);
+
+ChromeUtils.defineModuleGetter(
+ this,
+ "BasePromiseWorker",
+ "resource://gre/modules/PromiseWorker.jsm"
+);
+
+XPCOMUtils.defineLazyGlobalGetters(this, ["DOMParser"]);
+
+const CACHE_WORKER_URL = "resource://activity-stream/lib/cache-worker.js";
+const NEWTAB_RENDER_URL =
+ "resource://activity-stream/data/content/newtab-render.js";
+
+/**
+ * In order to make this test less brittle, much of Activity Stream is
+ * initialized here in order to generate a state object at runtime, rather
+ * than hard-coding one in. This requires quite a bit of machinery in order
+ * to work properly. Specifically, we need to launch an HTTP server to serve
+ * a dynamic layout, and then have that layout point to a local feed rather
+ * than one from the Pocket CDN.
+ */
+add_task(async function setup() {
+ do_get_profile();
+ // The SearchService is also needed in order to construct the initial state,
+ // which means that the AddonManager needs to be available.
+ await AddonTestUtils.promiseStartupManager();
+
+ // The example.com domain will be used to host the dynamic layout JSON and
+ // the top stories JSON.
+ let server = AddonTestUtils.createHttpServer({ hosts: ["example.com"] });
+ server.registerDirectory("/", do_get_cwd());
+
+ // Top Stories are disabled by default in our testing profiles.
+ Services.prefs.setBoolPref(
+ "browser.newtabpage.activity-stream.feeds.section.topstories",
+ true
+ );
+ Services.prefs.setBoolPref(
+ "browser.newtabpage.activity-stream.feeds.system.topstories",
+ true
+ );
+
+ let defaultDSConfig = JSON.parse(
+ PREFS_CONFIG.get("discoverystream.config").getValue({
+ geo: "US",
+ locale: "en-US",
+ })
+ );
+
+ let newConfig = Object.assign(defaultDSConfig, {
+ show_spocs: false,
+ hardcoded_layout: false,
+ layout_endpoint: "http://example.com/ds_layout.json",
+ });
+
+ // Configure Activity Stream to query for the layout JSON file that points
+ // at the local top stories feed.
+ Services.prefs.setCharPref(
+ "browser.newtabpage.activity-stream.discoverystream.config",
+ JSON.stringify(newConfig)
+ );
+
+ // We need to allow example.com as a place to get both the layout and the
+ // top stories from.
+ Services.prefs.setCharPref(
+ "browser.newtabpage.activity-stream.discoverystream.endpoints",
+ `http://example.com`
+ );
+
+ Services.prefs.setBoolPref(
+ "browser.newtabpage.activity-stream.telemetry.structuredIngestion",
+ false
+ );
+ Services.prefs.setBoolPref("browser.ping-centre.telemetry", false);
+
+ // We need a default search engine set up for rendering the search input.
+ let engine = await Services.search.addEngineWithDetails("Test engine", {
+ template: "http://example.com/?s=%S",
+ alias: "@testengine",
+ });
+ Services.search.defaultEngine = engine;
+
+ // Initialize Activity Stream, and pretend that a new window has been loaded
+ // to kick off initializing all of the feeds.
+ AboutNewTab.init();
+ AboutNewTab.onBrowserReady();
+
+ // Much of Activity Stream initializes asynchronously. This is the easiest way
+ // I could find to ensure that enough of the feeds had initialized to produce
+ // a meaningful cached document.
+ await TestUtils.waitForCondition(() => {
+ let feed = AboutNewTab.activityStream.store.feeds.get(
+ "feeds.discoverystreamfeed"
+ );
+ return feed.loaded;
+ });
+});
+
+/**
+ * Gets the Activity Stream Redux state from Activity Stream and sends it
+ * into an instance of the cache worker to ensure that the resulting markup
+ * and script makes sense.
+ */
+add_task(async function test_cache_worker() {
+ let state = AboutNewTab.activityStream.store.getState();
+
+ let cacheWorker = new BasePromiseWorker(CACHE_WORKER_URL);
+ let { page, script } = await cacheWorker.post("construct", [state]);
+ ok(!!page.length, "Got page content");
+ ok(!!script.length, "Got script content");
+
+ // The template strings should have been replaced.
+ equal(
+ page.indexOf("{{ MARKUP }}"),
+ -1,
+ "Page template should have {{ MARKUP }} replaced"
+ );
+ equal(
+ page.indexOf("{{ CACHE_TIME }}"),
+ -1,
+ "Page template should have {{ CACHE_TIME }} replaced"
+ );
+ equal(
+ script.indexOf("{{ STATE }}"),
+ -1,
+ "Script template should have {{ STATE }} replaced"
+ );
+
+ // Now let's make sure that the generated script makes sense. We'll
+ // evaluate it in a sandbox to make sure broken JS doesn't break the
+ // test.
+ let sandbox = Cu.Sandbox(Cu.getGlobalForObject({}));
+ let passedState = null;
+
+ // window.NewtabRenderUtils.renderCache is the exposed API from
+ // activity-stream.jsx that the script is expected to call to hydrate
+ // the pre-rendered markup. We'll implement that, and use that to ensure
+ // that the passed in state object matches the state we sent into the
+ // worker.
+ sandbox.window = {
+ NewtabRenderUtils: {
+ renderCache(aState) {
+ passedState = aState;
+ },
+ },
+ };
+ Cu.evalInSandbox(script, sandbox);
+
+ // The NEWTAB_RENDER_URL script is what ultimately causes the state
+ // to be passed into the renderCache function.
+ Services.scriptloader.loadSubScript(NEWTAB_RENDER_URL, sandbox);
+
+ equal(
+ sandbox.window.__FROM_STARTUP_CACHE__,
+ true,
+ "Should have set __FROM_STARTUP_CACHE__ to true"
+ );
+
+ // The worker is expected to modify the state slightly before running
+ // it through ReactDOMServer by setting App.isForStartupCache to true.
+ // This allows React components to change their behaviour if the cache
+ // is being generated.
+ state.App.isForStartupCache = true;
+
+ // Some of the properties on the state might have values set to undefined.
+ // There is no way to express a named undefined property on an object in
+ // JSON, so we filter those out by stringifying and re-parsing.
+ state = JSON.parse(JSON.stringify(state));
+
+ Assert.deepEqual(
+ passedState,
+ state,
+ "Should have called renderCache with the expected state"
+ );
+
+ // Now let's do a quick smoke-test on the markup to ensure that the
+ // one Top Story from topstories.json is there.
+ let parser = new DOMParser();
+ let doc = parser.parseFromString(page, "text/html");
+ let root = doc.getElementById("root");
+ ok(root.childElementCount, "There are children on the root node");
+
+ // There should be the 1 top story, and 2 placeholders.
+ equal(
+ Array.from(root.querySelectorAll(".ds-card")).length,
+ 3,
+ "There are 3 DSCards"
+ );
+ let cardHostname = doc.querySelector("[data-section-id='topstories'] .source")
+ .innerText;
+ equal(cardHostname, "bbc.com", "Card hostname is bbc.com");
+
+ let placeholders = doc.querySelectorAll(".ds-card.placeholder");
+ equal(placeholders.length, 2, "There should be 2 placeholders");
+});
+
+/**
+ * Tests that if the cache-worker construct method throws an exception
+ * that the construct Promise still resolves. Passing a null state should
+ * be enough to get it to throw.
+ */
+add_task(async function test_cache_worker_exception() {
+ let cacheWorker = new BasePromiseWorker(CACHE_WORKER_URL);
+ let { page, script } = await cacheWorker.post("construct", [null]);
+ equal(page, null, "Should have gotten a null page nsIInputStream");
+ equal(script, null, "Should have gotten a null script nsIInputStream");
+});
diff --git a/browser/components/newtab/test/xpcshell/test_AboutNewTab.js b/browser/components/newtab/test/xpcshell/test_AboutNewTab.js
new file mode 100644
index 0000000000..ffe28e3b2b
--- /dev/null
+++ b/browser/components/newtab/test/xpcshell/test_AboutNewTab.js
@@ -0,0 +1,359 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/
+ */
+
+"use strict";
+
+/**
+ * This file tests both the AboutNewTab and nsIAboutNewTabService
+ * for its default URL values, as well as its behaviour when overriding
+ * the default URL values.
+ */
+
+const { AppConstants } = ChromeUtils.import(
+ "resource://gre/modules/AppConstants.jsm"
+);
+const { AboutNewTab } = ChromeUtils.import(
+ "resource:///modules/AboutNewTab.jsm"
+);
+
+XPCOMUtils.defineLazyServiceGetter(
+ this,
+ "aboutNewTabService",
+ "@mozilla.org/browser/aboutnewtab-service;1",
+ "nsIAboutNewTabService"
+);
+
+AboutNewTab.init();
+
+const IS_RELEASE_OR_BETA = AppConstants.RELEASE_OR_BETA;
+
+const DOWNLOADS_URL =
+ "chrome://browser/content/downloads/contentAreaDownloadsView.xhtml";
+const SEPARATE_PRIVILEGED_CONTENT_PROCESS_PREF =
+ "browser.tabs.remote.separatePrivilegedContentProcess";
+const ACTIVITY_STREAM_DEBUG_PREF = "browser.newtabpage.activity-stream.debug";
+const SIMPLIFIED_WELCOME_ENABLED_PREF = "browser.aboutwelcome.enabled";
+
+function cleanup() {
+ Services.prefs.clearUserPref(SEPARATE_PRIVILEGED_CONTENT_PROCESS_PREF);
+ Services.prefs.clearUserPref(ACTIVITY_STREAM_DEBUG_PREF);
+ Services.prefs.clearUserPref(SIMPLIFIED_WELCOME_ENABLED_PREF);
+ AboutNewTab.resetNewTabURL();
+}
+
+registerCleanupFunction(cleanup);
+
+let ACTIVITY_STREAM_URL;
+let ACTIVITY_STREAM_DEBUG_URL;
+
+function setExpectedUrlsWithScripts() {
+ ACTIVITY_STREAM_URL =
+ "resource://activity-stream/prerendered/activity-stream.html";
+ ACTIVITY_STREAM_DEBUG_URL =
+ "resource://activity-stream/prerendered/activity-stream-debug.html";
+}
+
+function setExpectedUrlsWithoutScripts() {
+ ACTIVITY_STREAM_URL =
+ "resource://activity-stream/prerendered/activity-stream-noscripts.html";
+
+ // Debug urls are the same as non-debug because debug scripts load dynamically
+ ACTIVITY_STREAM_DEBUG_URL = ACTIVITY_STREAM_URL;
+}
+
+function nextChangeNotificationPromise(aNewURL, testMessage) {
+ return new Promise(resolve => {
+ Services.obs.addObserver(function observer(aSubject, aTopic, aData) {
+ Services.obs.removeObserver(observer, aTopic);
+ Assert.equal(aData, aNewURL, testMessage);
+ resolve();
+ }, "newtab-url-changed");
+ });
+}
+
+function setPrivilegedContentProcessPref(usePrivilegedContentProcess) {
+ if (
+ usePrivilegedContentProcess === AboutNewTab.privilegedAboutProcessEnabled
+ ) {
+ return Promise.resolve();
+ }
+
+ let notificationPromise = nextChangeNotificationPromise("about:newtab");
+
+ Services.prefs.setBoolPref(
+ SEPARATE_PRIVILEGED_CONTENT_PROCESS_PREF,
+ usePrivilegedContentProcess
+ );
+ return notificationPromise;
+}
+
+// Default expected URLs to files with scripts in them.
+setExpectedUrlsWithScripts();
+
+function addTestsWithPrivilegedContentProcessPref(test) {
+ add_task(async () => {
+ await setPrivilegedContentProcessPref(true);
+ setExpectedUrlsWithoutScripts();
+ await test();
+ });
+ add_task(async () => {
+ await setPrivilegedContentProcessPref(false);
+ setExpectedUrlsWithScripts();
+ await test();
+ });
+}
+
+function setBoolPrefAndWaitForChange(pref, value, testMessage) {
+ return new Promise(resolve => {
+ Services.obs.addObserver(function observer(aSubject, aTopic, aData) {
+ Services.obs.removeObserver(observer, aTopic);
+ Assert.equal(aData, AboutNewTab.newTabURL, testMessage);
+ resolve();
+ }, "newtab-url-changed");
+
+ Services.prefs.setBoolPref(pref, value);
+ });
+}
+
+add_task(async function test_as_initial_values() {
+ Assert.ok(
+ AboutNewTab.activityStreamEnabled,
+ ".activityStreamEnabled should be set to the correct initial value"
+ );
+ // This pref isn't defined on release or beta, so we fall back to false
+ Assert.equal(
+ AboutNewTab.activityStreamDebug,
+ Services.prefs.getBoolPref(ACTIVITY_STREAM_DEBUG_PREF, false),
+ ".activityStreamDebug should be set to the correct initial value"
+ );
+});
+
+/**
+ * Test the overriding of the default URL
+ */
+add_task(async function test_override_activity_stream_disabled() {
+ let notificationPromise;
+
+ Assert.ok(
+ !AboutNewTab.newTabURLOverridden,
+ "Newtab URL should not be overridden"
+ );
+ const ORIGINAL_URL = aboutNewTabService.defaultURL;
+
+ // override with some remote URL
+ let url = "http://example.com/";
+ notificationPromise = nextChangeNotificationPromise(url);
+ AboutNewTab.newTabURL = url;
+ await notificationPromise;
+ Assert.ok(AboutNewTab.newTabURLOverridden, "Newtab URL should be overridden");
+ Assert.ok(
+ !AboutNewTab.activityStreamEnabled,
+ "Newtab activity stream should not be enabled"
+ );
+ Assert.equal(
+ AboutNewTab.newTabURL,
+ url,
+ "Newtab URL should be the custom URL"
+ );
+ Assert.equal(
+ aboutNewTabService.defaultURL,
+ ORIGINAL_URL,
+ "AboutNewTabService defaultURL is unchanged"
+ );
+
+ // test reset with activity stream disabled
+ notificationPromise = nextChangeNotificationPromise("about:newtab");
+ AboutNewTab.resetNewTabURL();
+ await notificationPromise;
+ Assert.ok(
+ !AboutNewTab.newTabURLOverridden,
+ "Newtab URL should not be overridden"
+ );
+ Assert.equal(
+ AboutNewTab.newTabURL,
+ "about:newtab",
+ "Newtab URL should be the default"
+ );
+
+ // test override to a chrome URL
+ notificationPromise = nextChangeNotificationPromise(DOWNLOADS_URL);
+ AboutNewTab.newTabURL = DOWNLOADS_URL;
+ await notificationPromise;
+ Assert.ok(AboutNewTab.newTabURLOverridden, "Newtab URL should be overridden");
+ Assert.equal(
+ AboutNewTab.newTabURL,
+ DOWNLOADS_URL,
+ "Newtab URL should be the custom URL"
+ );
+
+ cleanup();
+});
+
+addTestsWithPrivilegedContentProcessPref(
+ async function test_override_activity_stream_enabled() {
+ Assert.equal(
+ aboutNewTabService.defaultURL,
+ ACTIVITY_STREAM_URL,
+ "Newtab URL should be the default activity stream URL"
+ );
+ Assert.ok(
+ !AboutNewTab.newTabURLOverridden,
+ "Newtab URL should not be overridden"
+ );
+ Assert.ok(
+ AboutNewTab.activityStreamEnabled,
+ "Activity Stream should be enabled"
+ );
+
+ // change to a chrome URL while activity stream is enabled
+ let notificationPromise = nextChangeNotificationPromise(DOWNLOADS_URL);
+ AboutNewTab.newTabURL = DOWNLOADS_URL;
+ await notificationPromise;
+ Assert.equal(
+ AboutNewTab.newTabURL,
+ DOWNLOADS_URL,
+ "Newtab URL set to chrome url"
+ );
+ Assert.equal(
+ aboutNewTabService.defaultURL,
+ ACTIVITY_STREAM_URL,
+ "Newtab URL defaultURL still set to the default activity stream URL"
+ );
+ Assert.ok(
+ AboutNewTab.newTabURLOverridden,
+ "Newtab URL should be overridden"
+ );
+ Assert.ok(
+ !AboutNewTab.activityStreamEnabled,
+ "Activity Stream should not be enabled"
+ );
+
+ cleanup();
+ }
+);
+
+addTestsWithPrivilegedContentProcessPref(async function test_default_url() {
+ Assert.equal(
+ aboutNewTabService.defaultURL,
+ ACTIVITY_STREAM_URL,
+ "Newtab defaultURL initially set to AS url"
+ );
+
+ // Only debug variants aren't available on release/beta
+ if (!IS_RELEASE_OR_BETA) {
+ await setBoolPrefAndWaitForChange(
+ ACTIVITY_STREAM_DEBUG_PREF,
+ true,
+ "A notification occurs after changing the debug pref to true"
+ );
+ Assert.equal(
+ AboutNewTab.activityStreamDebug,
+ true,
+ "the .activityStreamDebug property is set to true"
+ );
+ Assert.equal(
+ aboutNewTabService.defaultURL,
+ ACTIVITY_STREAM_DEBUG_URL,
+ "Newtab defaultURL set to debug AS url after the pref has been changed"
+ );
+ await setBoolPrefAndWaitForChange(
+ ACTIVITY_STREAM_DEBUG_PREF,
+ false,
+ "A notification occurs after changing the debug pref to false"
+ );
+ } else {
+ Services.prefs.setBoolPref(ACTIVITY_STREAM_DEBUG_PREF, true);
+
+ Assert.equal(
+ AboutNewTab.activityStreamDebug,
+ false,
+ "the .activityStreamDebug property is remains false"
+ );
+ }
+
+ Assert.equal(
+ aboutNewTabService.defaultURL,
+ ACTIVITY_STREAM_URL,
+ "Newtab defaultURL set to un-prerendered AS if prerender is false and debug is false"
+ );
+
+ cleanup();
+});
+
+addTestsWithPrivilegedContentProcessPref(async function test_welcome_url() {
+ // Disable about:welcome to load newtab
+ Services.prefs.setBoolPref(SIMPLIFIED_WELCOME_ENABLED_PREF, false);
+ Assert.equal(
+ aboutNewTabService.welcomeURL,
+ ACTIVITY_STREAM_URL,
+ "Newtab welcomeURL set to un-prerendered AS when debug disabled."
+ );
+ Assert.equal(
+ aboutNewTabService.welcomeURL,
+ aboutNewTabService.defaultURL,
+ "Newtab welcomeURL is equal to defaultURL when prerendering disabled and debug disabled."
+ );
+
+ // Only debug variants aren't available on release/beta
+ if (!IS_RELEASE_OR_BETA) {
+ await setBoolPrefAndWaitForChange(
+ ACTIVITY_STREAM_DEBUG_PREF,
+ true,
+ "A notification occurs after changing the debug pref to true."
+ );
+ Assert.equal(
+ aboutNewTabService.welcomeURL,
+ ACTIVITY_STREAM_DEBUG_URL,
+ "Newtab welcomeURL set to un-prerendered debug AS when debug enabled"
+ );
+ }
+
+ cleanup();
+});
+
+/**
+ * Tests response to updates to prefs
+ */
+addTestsWithPrivilegedContentProcessPref(async function test_updates() {
+ // Simulates a "cold-boot" situation, with some pref already set before testing a series
+ // of changes.
+ AboutNewTab.resetNewTabURL(); // need to set manually because pref notifs are off
+ let notificationPromise;
+
+ // test update fires on override and reset
+ let testURL = "https://example.com/";
+ notificationPromise = nextChangeNotificationPromise(
+ testURL,
+ "a notification occurs on override"
+ );
+ AboutNewTab.newTabURL = testURL;
+ await notificationPromise;
+
+ // from overridden to default
+ notificationPromise = nextChangeNotificationPromise(
+ "about:newtab",
+ "a notification occurs on reset"
+ );
+ AboutNewTab.resetNewTabURL();
+ Assert.ok(
+ AboutNewTab.activityStreamEnabled,
+ "Activity Stream should be enabled"
+ );
+ Assert.equal(
+ aboutNewTabService.defaultURL,
+ ACTIVITY_STREAM_URL,
+ "Default URL should be the activity stream page"
+ );
+ await notificationPromise;
+
+ // reset twice, only one notification for default URL
+ notificationPromise = nextChangeNotificationPromise(
+ "about:newtab",
+ "reset occurs"
+ );
+ AboutNewTab.resetNewTabURL();
+ await notificationPromise;
+
+ cleanup();
+});
diff --git a/browser/components/newtab/test/xpcshell/test_AboutWelcomeAttribution.js b/browser/components/newtab/test/xpcshell/test_AboutWelcomeAttribution.js
new file mode 100644
index 0000000000..b697721401
--- /dev/null
+++ b/browser/components/newtab/test/xpcshell/test_AboutWelcomeAttribution.js
@@ -0,0 +1,38 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/
+ */
+
+"use strict";
+
+const { AboutWelcomeChild } = ChromeUtils.import(
+ "resource:///actors/AboutWelcomeChild.jsm"
+);
+const { sinon } = ChromeUtils.import("resource://testing-common/Sinon.jsm");
+
+const TEST_ATTRIBUTION_DATA = {
+ source: "addons.mozilla.org",
+ medium: "referral",
+ campaign: "non-fx-button",
+ content: "iridium%40particlecore.github.io",
+};
+
+add_task(async function test_handleAddonInfoNotFound() {
+ let AWChild = new AboutWelcomeChild();
+ const stub = sinon.stub(AWChild, "getAddonInfo").resolves(null);
+ let result = await AWChild.formatAttributionData(TEST_ATTRIBUTION_DATA);
+ equal(stub.callCount, 1, "Call was made");
+ equal(result.template, undefined, "No template returned");
+});
+
+add_task(async function test_formatAttributionData() {
+ let AWChild = new AboutWelcomeChild();
+ const TEST_ADDON_INFO = {
+ name: "Test Add-on",
+ url: "https://test.xpi",
+ iconURL: "http://test.svg",
+ };
+ sinon.stub(AWChild, "getAddonInfo").resolves(TEST_ADDON_INFO);
+ let result = await AWChild.formatAttributionData(TEST_ATTRIBUTION_DATA);
+ equal(result.template, "return_to_amo", "RTAMO template returned");
+ equal(result.extraProps, TEST_ADDON_INFO, "AddonInfo returned");
+});
diff --git a/browser/components/newtab/test/xpcshell/test_AboutWelcomeTelemetry.js b/browser/components/newtab/test/xpcshell/test_AboutWelcomeTelemetry.js
new file mode 100644
index 0000000000..01d3c1254e
--- /dev/null
+++ b/browser/components/newtab/test/xpcshell/test_AboutWelcomeTelemetry.js
@@ -0,0 +1,87 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/
+ */
+
+"use strict";
+
+const { AboutWelcomeTelemetry } = ChromeUtils.import(
+ "resource://activity-stream/aboutwelcome/lib/AboutWelcomeTelemetry.jsm"
+);
+const { AttributionCode } = ChromeUtils.import(
+ "resource:///modules/AttributionCode.jsm"
+);
+const { sinon } = ChromeUtils.import("resource://testing-common/Sinon.jsm");
+const TELEMETRY_PREF = "browser.newtabpage.activity-stream.telemetry";
+
+add_task(function test_enabled() {
+ registerCleanupFunction(() => {
+ Services.prefs.clearUserPref(TELEMETRY_PREF);
+ });
+ Services.prefs.setBoolPref(TELEMETRY_PREF, true);
+
+ const AWTelemetry = new AboutWelcomeTelemetry();
+
+ equal(AWTelemetry.telemetryEnabled, true, "Telemetry should be on");
+
+ Services.prefs.setBoolPref(TELEMETRY_PREF, false);
+
+ equal(AWTelemetry.telemetryEnabled, false, "Telemetry should be off");
+});
+
+add_task(async function test_pingPayload() {
+ registerCleanupFunction(() => {
+ Services.prefs.clearUserPref(TELEMETRY_PREF);
+ });
+ Services.prefs.setBoolPref(TELEMETRY_PREF, true);
+ const AWTelemetry = new AboutWelcomeTelemetry();
+ const stub = sinon.stub(
+ AWTelemetry.pingCentre,
+ "sendStructuredIngestionPing"
+ );
+ sinon.stub(AWTelemetry, "_createPing").resolves({ event: "MOCHITEST" });
+
+ await AWTelemetry.sendTelemetry();
+
+ equal(stub.callCount, 1, "Call was made");
+ // check the endpoint
+ ok(
+ stub.firstCall.args[1].includes("/messaging-system/onboarding"),
+ "Endpoint is correct"
+ );
+});
+
+add_task(function test_mayAttachAttribution() {
+ const sandbox = sinon.createSandbox();
+ const AWTelemetry = new AboutWelcomeTelemetry();
+
+ sandbox.stub(AttributionCode, "getCachedAttributionData").returns(null);
+
+ let ping = AWTelemetry._maybeAttachAttribution({});
+
+ equal(ping.attribution, undefined, "Should not set attribution if it's null");
+
+ sandbox.restore();
+ sandbox.stub(AttributionCode, "getCachedAttributionData").returns({});
+ ping = AWTelemetry._maybeAttachAttribution({});
+
+ equal(
+ ping.attribution,
+ undefined,
+ "Should not set attribution if it's empty"
+ );
+
+ const attr = {
+ source: "google.com",
+ medium: "referral",
+ campaign: "Firefox-Brand-US-Chrome",
+ content: "(not set)",
+ experiment: "(not set)",
+ variation: "(not set)",
+ ua: "chrome",
+ };
+ sandbox.restore();
+ sandbox.stub(AttributionCode, "getCachedAttributionData").returns(attr);
+ ping = AWTelemetry._maybeAttachAttribution({});
+
+ equal(ping.attribution, attr, "Should set attribution if it presents");
+});
diff --git a/browser/components/newtab/test/xpcshell/topstories.json b/browser/components/newtab/test/xpcshell/topstories.json
new file mode 100644
index 0000000000..6cecd94028
--- /dev/null
+++ b/browser/components/newtab/test/xpcshell/topstories.json
@@ -0,0 +1 @@
+{"status":1,"settings":{"spocsPerNewTabs":0.5,"domainAffinityParameterSets":{"default":{"recencyFactor":0.5,"frequencyFactor":0.5,"combinedDomainFactor":0.5,"perfectFrequencyVisits":10,"perfectCombinedDomainScore":2,"multiDomainBoost":0,"itemScoreFactor":1},"fully-personalized":{"recencyFactor":0.5,"frequencyFactor":0.5,"combinedDomainFactor":0.5,"perfectFrequencyVisits":10,"perfectCombinedDomainScore":2,"itemScoreFactor":0.01,"multiDomainBoost":0}},"timeSegments":[{"id":"week","startTime":604800,"endTime":0,"weightPosition":1},{"id":"month","startTime":2592000,"endTime":604800,"weightPosition":0.5}],"recsExpireTime":5400,"version":"2c2aa06dac65ddb647d8902aaa60263c8e119ff2"},"spocs":[],"recommendations":[{"id":53093,"url":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAA/UlEQVR4nO3RMQ0AMAzAsPIn3d5DsBw2gkiZJWV+B/AyJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQmAP4K6zWNUjE4wAAAABJRU5ErkJggg==","domain":"bbc.com","title":"Why vegan junk food may be even worse for your health","excerpt":"While we might switch to a plant-based diet with the best intentions, the unseen risks of vegan fast foods might not show up for years.","image_src":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAA/UlEQVR4nO3RMQ0AMAzAsPIn3d5DsBw2gkiZJWV+B/AyJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQGENiDIkxJMaQmAP4K6zWNUjE4wAAAABJRU5ErkJggg==","published_timestamp":"1580277600","engagement":"","parameter_set":"default","domain_affinities":{},"item_score":1}]}
diff --git a/browser/components/newtab/test/xpcshell/xpcshell.ini b/browser/components/newtab/test/xpcshell/xpcshell.ini
new file mode 100644
index 0000000000..c3534e792f
--- /dev/null
+++ b/browser/components/newtab/test/xpcshell/xpcshell.ini
@@ -0,0 +1,19 @@
+[DEFAULT]
+head = head.js
+firefox-appdir = browser
+skip-if = toolkit == 'android'
+prefs =
+ browser.startup.homepage.abouthome_cache.enabled=true
+ browser.startup.homepage.abouthome_cache.testing=true
+
+[test_AboutHomeStartupCacheChild.js]
+[test_AboutHomeStartupCacheWorker.js]
+support-files =
+ ds_layout.json
+ topstories.json
+
+[test_AboutNewTab.js]
+[test_AboutWelcomeAttribution.js]
+[test_ASRouterTargeting_attribution.js]
+skip-if = toolkit != "cocoa" # osx specific tests
+[test_AboutWelcomeTelemetry.js]
diff --git a/browser/components/newtab/vendor/PROP_TYPES_LICENSE b/browser/components/newtab/vendor/PROP_TYPES_LICENSE
new file mode 100644
index 0000000000..188fb2b0bd
--- /dev/null
+++ b/browser/components/newtab/vendor/PROP_TYPES_LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2013-present, Facebook, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/browser/components/newtab/vendor/REACT_AND_REACT_DOM_LICENSE b/browser/components/newtab/vendor/REACT_AND_REACT_DOM_LICENSE
new file mode 100644
index 0000000000..b96dcb0480
--- /dev/null
+++ b/browser/components/newtab/vendor/REACT_AND_REACT_DOM_LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) Facebook, Inc. and its affiliates.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/browser/components/newtab/vendor/REACT_REDUX_LICENSE b/browser/components/newtab/vendor/REACT_REDUX_LICENSE
new file mode 100644
index 0000000000..c108bf3712
--- /dev/null
+++ b/browser/components/newtab/vendor/REACT_REDUX_LICENSE
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2015-present Dan Abramov
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/browser/components/newtab/vendor/REACT_TRANSITION_GROUP_LICENSE b/browser/components/newtab/vendor/REACT_TRANSITION_GROUP_LICENSE
new file mode 100644
index 0000000000..af586225d6
--- /dev/null
+++ b/browser/components/newtab/vendor/REACT_TRANSITION_GROUP_LICENSE
@@ -0,0 +1,30 @@
+BSD 3-Clause License
+
+Copyright (c) 2018, React Community
+Forked from React (https://github.com/facebook/react) Copyright 2013-present, Facebook, Inc.
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+* Neither the name of the copyright holder nor the names of its
+ contributors may be used to endorse or promote products derived from
+ this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/browser/components/newtab/vendor/REDUX_LICENSE b/browser/components/newtab/vendor/REDUX_LICENSE
new file mode 100644
index 0000000000..55bc8dfbe9
--- /dev/null
+++ b/browser/components/newtab/vendor/REDUX_LICENSE
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2015-present Dan Abramov
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/browser/components/newtab/vendor/Redux.jsm b/browser/components/newtab/vendor/Redux.jsm
new file mode 100644
index 0000000000..5bad35fe81
--- /dev/null
+++ b/browser/components/newtab/vendor/Redux.jsm
@@ -0,0 +1,690 @@
+/**
+ * Redux v.4.0.1
+ *
+ * This file was imported from https://unpkg.com/redux@4.0.1/dist/redux.js
+ * and reformatted as a Javascript Core Module
+ */
+var EXPORTED_SYMBOLS = ["redux"];
+var self = this;
+
+this.redux = (function (global, factory) {
+ var exports = {};
+ factory(exports);
+ return exports;
+ }(this, (function (exports) { 'use strict';
+
+ function symbolObservablePonyfill(root) {
+ var result;
+ var Symbol = root.Symbol;
+
+ if (typeof Symbol === 'function') {
+ if (Symbol.observable) {
+ result = Symbol.observable;
+ } else {
+ result = Symbol('observable');
+ Symbol.observable = result;
+ }
+ } else {
+ result = '@@observable';
+ }
+
+ return result;
+ }
+
+ /* global window */
+
+ // This is edited to prevent Function being present in this code.
+ // See https://bugzilla.mozilla.org/show_bug.cgi?id=1486375
+ var root;
+
+ if (typeof self !== 'undefined') {
+ root = self;
+ } else if (typeof global !== 'undefined') {
+ root = global;
+ }
+
+ var result = symbolObservablePonyfill(root);
+
+ /**
+ * These are private action types reserved by Redux.
+ * For any unknown actions, you must return the current state.
+ * If the current state is undefined, you must return the initial state.
+ * Do not reference these action types directly in your code.
+ */
+ var randomString = function randomString() {
+ return Math.random().toString(36).substring(7).split('').join('.');
+ };
+
+ var ActionTypes = {
+ INIT: "@@redux/INIT" + randomString(),
+ REPLACE: "@@redux/REPLACE" + randomString(),
+ PROBE_UNKNOWN_ACTION: function PROBE_UNKNOWN_ACTION() {
+ return "@@redux/PROBE_UNKNOWN_ACTION" + randomString();
+ }
+ };
+
+ /**
+ * @param {any} obj The object to inspect.
+ * @returns {boolean} True if the argument appears to be a plain object.
+ */
+ function isPlainObject(obj) {
+ if (typeof obj !== 'object' || obj === null) return false;
+ var proto = obj;
+
+ while (Object.getPrototypeOf(proto) !== null) {
+ proto = Object.getPrototypeOf(proto);
+ }
+
+ return Object.getPrototypeOf(obj) === proto;
+ }
+
+ /**
+ * Creates a Redux store that holds the state tree.
+ * The only way to change the data in the store is to call `dispatch()` on it.
+ *
+ * There should only be a single store in your app. To specify how different
+ * parts of the state tree respond to actions, you may combine several reducers
+ * into a single reducer function by using `combineReducers`.
+ *
+ * @param {Function} reducer A function that returns the next state tree, given
+ * the current state tree and the action to handle.
+ *
+ * @param {any} [preloadedState] The initial state. You may optionally specify it
+ * to hydrate the state from the server in universal apps, or to restore a
+ * previously serialized user session.
+ * If you use `combineReducers` to produce the root reducer function, this must be
+ * an object with the same shape as `combineReducers` keys.
+ *
+ * @param {Function} [enhancer] The store enhancer. You may optionally specify it
+ * to enhance the store with third-party capabilities such as middleware,
+ * time travel, persistence, etc. The only store enhancer that ships with Redux
+ * is `applyMiddleware()`.
+ *
+ * @returns {Store} A Redux store that lets you read the state, dispatch actions
+ * and subscribe to changes.
+ */
+
+ function createStore(reducer, preloadedState, enhancer) {
+ var _ref2;
+
+ if (typeof preloadedState === 'function' && typeof enhancer === 'function' || typeof enhancer === 'function' && typeof arguments[3] === 'function') {
+ throw new Error('It looks like you are passing several store enhancers to ' + 'createStore(). This is not supported. Instead, compose them ' + 'together to a single function');
+ }
+
+ if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') {
+ enhancer = preloadedState;
+ preloadedState = undefined;
+ }
+
+ if (typeof enhancer !== 'undefined') {
+ if (typeof enhancer !== 'function') {
+ throw new Error('Expected the enhancer to be a function.');
+ }
+
+ return enhancer(createStore)(reducer, preloadedState);
+ }
+
+ if (typeof reducer !== 'function') {
+ throw new Error('Expected the reducer to be a function.');
+ }
+
+ var currentReducer = reducer;
+ var currentState = preloadedState;
+ var currentListeners = [];
+ var nextListeners = currentListeners;
+ var isDispatching = false;
+
+ function ensureCanMutateNextListeners() {
+ if (nextListeners === currentListeners) {
+ nextListeners = currentListeners.slice();
+ }
+ }
+ /**
+ * Reads the state tree managed by the store.
+ *
+ * @returns {any} The current state tree of your application.
+ */
+
+
+ function getState() {
+ if (isDispatching) {
+ throw new Error('You may not call store.getState() while the reducer is executing. ' + 'The reducer has already received the state as an argument. ' + 'Pass it down from the top reducer instead of reading it from the store.');
+ }
+
+ return currentState;
+ }
+ /**
+ * Adds a change listener. It will be called any time an action is dispatched,
+ * and some part of the state tree may potentially have changed. You may then
+ * call `getState()` to read the current state tree inside the callback.
+ *
+ * You may call `dispatch()` from a change listener, with the following
+ * caveats:
+ *
+ * 1. The subscriptions are snapshotted just before every `dispatch()` call.
+ * If you subscribe or unsubscribe while the listeners are being invoked, this
+ * will not have any effect on the `dispatch()` that is currently in progress.
+ * However, the next `dispatch()` call, whether nested or not, will use a more
+ * recent snapshot of the subscription list.
+ *
+ * 2. The listener should not expect to see all state changes, as the state
+ * might have been updated multiple times during a nested `dispatch()` before
+ * the listener is called. It is, however, guaranteed that all subscribers
+ * registered before the `dispatch()` started will be called with the latest
+ * state by the time it exits.
+ *
+ * @param {Function} listener A callback to be invoked on every dispatch.
+ * @returns {Function} A function to remove this change listener.
+ */
+
+
+ function subscribe(listener) {
+ if (typeof listener !== 'function') {
+ throw new Error('Expected the listener to be a function.');
+ }
+
+ if (isDispatching) {
+ throw new Error('You may not call store.subscribe() while the reducer is executing. ' + 'If you would like to be notified after the store has been updated, subscribe from a ' + 'component and invoke store.getState() in the callback to access the latest state. ' + 'See https://redux.js.org/api-reference/store#subscribe(listener) for more details.');
+ }
+
+ var isSubscribed = true;
+ ensureCanMutateNextListeners();
+ nextListeners.push(listener);
+ return function unsubscribe() {
+ if (!isSubscribed) {
+ return;
+ }
+
+ if (isDispatching) {
+ throw new Error('You may not unsubscribe from a store listener while the reducer is executing. ' + 'See https://redux.js.org/api-reference/store#subscribe(listener) for more details.');
+ }
+
+ isSubscribed = false;
+ ensureCanMutateNextListeners();
+ var index = nextListeners.indexOf(listener);
+ nextListeners.splice(index, 1);
+ };
+ }
+ /**
+ * Dispatches an action. It is the only way to trigger a state change.
+ *
+ * The `reducer` function, used to create the store, will be called with the
+ * current state tree and the given `action`. Its return value will
+ * be considered the **next** state of the tree, and the change listeners
+ * will be notified.
+ *
+ * The base implementation only supports plain object actions. If you want to
+ * dispatch a Promise, an Observable, a thunk, or something else, you need to
+ * wrap your store creating function into the corresponding middleware. For
+ * example, see the documentation for the `redux-thunk` package. Even the
+ * middleware will eventually dispatch plain object actions using this method.
+ *
+ * @param {Object} action A plain object representing “what changed”. It is
+ * a good idea to keep actions serializable so you can record and replay user
+ * sessions, or use the time travelling `redux-devtools`. An action must have
+ * a `type` property which may not be `undefined`. It is a good idea to use
+ * string constants for action types.
+ *
+ * @returns {Object} For convenience, the same action object you dispatched.
+ *
+ * Note that, if you use a custom middleware, it may wrap `dispatch()` to
+ * return something else (for example, a Promise you can await).
+ */
+
+
+ function dispatch(action) {
+ if (!isPlainObject(action)) {
+ throw new Error('Actions must be plain objects. ' + 'Use custom middleware for async actions.');
+ }
+
+ if (typeof action.type === 'undefined') {
+ throw new Error('Actions may not have an undefined "type" property. ' + 'Have you misspelled a constant?');
+ }
+
+ if (isDispatching) {
+ throw new Error('Reducers may not dispatch actions.');
+ }
+
+ try {
+ isDispatching = true;
+ currentState = currentReducer(currentState, action);
+ } finally {
+ isDispatching = false;
+ }
+
+ var listeners = currentListeners = nextListeners;
+
+ for (var i = 0; i < listeners.length; i++) {
+ var listener = listeners[i];
+ listener();
+ }
+
+ return action;
+ }
+ /**
+ * Replaces the reducer currently used by the store to calculate the state.
+ *
+ * You might need this if your app implements code splitting and you want to
+ * load some of the reducers dynamically. You might also need this if you
+ * implement a hot reloading mechanism for Redux.
+ *
+ * @param {Function} nextReducer The reducer for the store to use instead.
+ * @returns {void}
+ */
+
+
+ function replaceReducer(nextReducer) {
+ if (typeof nextReducer !== 'function') {
+ throw new Error('Expected the nextReducer to be a function.');
+ }
+
+ currentReducer = nextReducer;
+ dispatch({
+ type: ActionTypes.REPLACE
+ });
+ }
+ /**
+ * Interoperability point for observable/reactive libraries.
+ * @returns {observable} A minimal observable of state changes.
+ * For more information, see the observable proposal:
+ * https://github.com/tc39/proposal-observable
+ */
+
+
+ function observable() {
+ var _ref;
+
+ var outerSubscribe = subscribe;
+ return _ref = {
+ /**
+ * The minimal observable subscription method.
+ * @param {Object} observer Any object that can be used as an observer.
+ * The observer object should have a `next` method.
+ * @returns {subscription} An object with an `unsubscribe` method that can
+ * be used to unsubscribe the observable from the store, and prevent further
+ * emission of values from the observable.
+ */
+ subscribe: function subscribe(observer) {
+ if (typeof observer !== 'object' || observer === null) {
+ throw new TypeError('Expected the observer to be an object.');
+ }
+
+ function observeState() {
+ if (observer.next) {
+ observer.next(getState());
+ }
+ }
+
+ observeState();
+ var unsubscribe = outerSubscribe(observeState);
+ return {
+ unsubscribe: unsubscribe
+ };
+ }
+ }, _ref[result] = function () {
+ return this;
+ }, _ref;
+ } // When a store is created, an "INIT" action is dispatched so that every
+ // reducer returns their initial state. This effectively populates
+ // the initial state tree.
+
+
+ dispatch({
+ type: ActionTypes.INIT
+ });
+ return _ref2 = {
+ dispatch: dispatch,
+ subscribe: subscribe,
+ getState: getState,
+ replaceReducer: replaceReducer
+ }, _ref2[result] = observable, _ref2;
+ }
+
+ /**
+ * Prints a warning in the console if it exists.
+ *
+ * @param {String} message The warning message.
+ * @returns {void}
+ */
+ function warning(message) {
+ /* eslint-disable no-console */
+ if (typeof console !== 'undefined' && typeof console.error === 'function') {
+ console.error(message);
+ }
+ /* eslint-enable no-console */
+
+
+ try {
+ // This error was thrown as a convenience so that if you enable
+ // "break on all exceptions" in your console,
+ // it would pause the execution at this line.
+ throw new Error(message);
+ } catch (e) {} // eslint-disable-line no-empty
+
+ }
+
+ function getUndefinedStateErrorMessage(key, action) {
+ var actionType = action && action.type;
+ var actionDescription = actionType && "action \"" + String(actionType) + "\"" || 'an action';
+ return "Given " + actionDescription + ", reducer \"" + key + "\" returned undefined. " + "To ignore an action, you must explicitly return the previous state. " + "If you want this reducer to hold no value, you can return null instead of undefined.";
+ }
+
+ function getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) {
+ var reducerKeys = Object.keys(reducers);
+ var argumentName = action && action.type === ActionTypes.INIT ? 'preloadedState argument passed to createStore' : 'previous state received by the reducer';
+
+ if (reducerKeys.length === 0) {
+ return 'Store does not have a valid reducer. Make sure the argument passed ' + 'to combineReducers is an object whose values are reducers.';
+ }
+
+ if (!isPlainObject(inputState)) {
+ return "The " + argumentName + " has unexpected type of \"" + {}.toString.call(inputState).match(/\s([a-z|A-Z]+)/)[1] + "\". Expected argument to be an object with the following " + ("keys: \"" + reducerKeys.join('", "') + "\"");
+ }
+
+ var unexpectedKeys = Object.keys(inputState).filter(function (key) {
+ return !reducers.hasOwnProperty(key) && !unexpectedKeyCache[key];
+ });
+ unexpectedKeys.forEach(function (key) {
+ unexpectedKeyCache[key] = true;
+ });
+ if (action && action.type === ActionTypes.REPLACE) return;
+
+ if (unexpectedKeys.length > 0) {
+ return "Unexpected " + (unexpectedKeys.length > 1 ? 'keys' : 'key') + " " + ("\"" + unexpectedKeys.join('", "') + "\" found in " + argumentName + ". ") + "Expected to find one of the known reducer keys instead: " + ("\"" + reducerKeys.join('", "') + "\". Unexpected keys will be ignored.");
+ }
+ }
+
+ function assertReducerShape(reducers) {
+ Object.keys(reducers).forEach(function (key) {
+ var reducer = reducers[key];
+ var initialState = reducer(undefined, {
+ type: ActionTypes.INIT
+ });
+
+ if (typeof initialState === 'undefined') {
+ throw new Error("Reducer \"" + key + "\" returned undefined during initialization. " + "If the state passed to the reducer is undefined, you must " + "explicitly return the initial state. The initial state may " + "not be undefined. If you don't want to set a value for this reducer, " + "you can use null instead of undefined.");
+ }
+
+ if (typeof reducer(undefined, {
+ type: ActionTypes.PROBE_UNKNOWN_ACTION()
+ }) === 'undefined') {
+ throw new Error("Reducer \"" + key + "\" returned undefined when probed with a random type. " + ("Don't try to handle " + ActionTypes.INIT + " or other actions in \"redux/*\" ") + "namespace. They are considered private. Instead, you must return the " + "current state for any unknown actions, unless it is undefined, " + "in which case you must return the initial state, regardless of the " + "action type. The initial state may not be undefined, but can be null.");
+ }
+ });
+ }
+ /**
+ * Turns an object whose values are different reducer functions, into a single
+ * reducer function. It will call every child reducer, and gather their results
+ * into a single state object, whose keys correspond to the keys of the passed
+ * reducer functions.
+ *
+ * @param {Object} reducers An object whose values correspond to different
+ * reducer functions that need to be combined into one. One handy way to obtain
+ * it is to use ES6 `import * as reducers` syntax. The reducers may never return
+ * undefined for any action. Instead, they should return their initial state
+ * if the state passed to them was undefined, and the current state for any
+ * unrecognized action.
+ *
+ * @returns {Function} A reducer function that invokes every reducer inside the
+ * passed object, and builds a state object with the same shape.
+ */
+
+
+ function combineReducers(reducers) {
+ var reducerKeys = Object.keys(reducers);
+ var finalReducers = {};
+
+ for (var i = 0; i < reducerKeys.length; i++) {
+ var key = reducerKeys[i];
+
+ {
+ if (typeof reducers[key] === 'undefined') {
+ warning("No reducer provided for key \"" + key + "\"");
+ }
+ }
+
+ if (typeof reducers[key] === 'function') {
+ finalReducers[key] = reducers[key];
+ }
+ }
+
+ var finalReducerKeys = Object.keys(finalReducers);
+ var unexpectedKeyCache;
+
+ {
+ unexpectedKeyCache = {};
+ }
+
+ var shapeAssertionError;
+
+ try {
+ assertReducerShape(finalReducers);
+ } catch (e) {
+ shapeAssertionError = e;
+ }
+
+ return function combination(state, action) {
+ if (state === void 0) {
+ state = {};
+ }
+
+ if (shapeAssertionError) {
+ throw shapeAssertionError;
+ }
+
+ {
+ var warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action, unexpectedKeyCache);
+
+ if (warningMessage) {
+ warning(warningMessage);
+ }
+ }
+
+ var hasChanged = false;
+ var nextState = {};
+
+ for (var _i = 0; _i < finalReducerKeys.length; _i++) {
+ var _key = finalReducerKeys[_i];
+ var reducer = finalReducers[_key];
+ var previousStateForKey = state[_key];
+ var nextStateForKey = reducer(previousStateForKey, action);
+
+ if (typeof nextStateForKey === 'undefined') {
+ var errorMessage = getUndefinedStateErrorMessage(_key, action);
+ throw new Error(errorMessage);
+ }
+
+ nextState[_key] = nextStateForKey;
+ hasChanged = hasChanged || nextStateForKey !== previousStateForKey;
+ }
+
+ return hasChanged ? nextState : state;
+ };
+ }
+
+ function bindActionCreator(actionCreator, dispatch) {
+ return function () {
+ return dispatch(actionCreator.apply(this, arguments));
+ };
+ }
+ /**
+ * Turns an object whose values are action creators, into an object with the
+ * same keys, but with every function wrapped into a `dispatch` call so they
+ * may be invoked directly. This is just a convenience method, as you can call
+ * `store.dispatch(MyActionCreators.doSomething())` yourself just fine.
+ *
+ * For convenience, you can also pass a single function as the first argument,
+ * and get a function in return.
+ *
+ * @param {Function|Object} actionCreators An object whose values are action
+ * creator functions. One handy way to obtain it is to use ES6 `import * as`
+ * syntax. You may also pass a single function.
+ *
+ * @param {Function} dispatch The `dispatch` function available on your Redux
+ * store.
+ *
+ * @returns {Function|Object} The object mimicking the original object, but with
+ * every action creator wrapped into the `dispatch` call. If you passed a
+ * function as `actionCreators`, the return value will also be a single
+ * function.
+ */
+
+
+ function bindActionCreators(actionCreators, dispatch) {
+ if (typeof actionCreators === 'function') {
+ return bindActionCreator(actionCreators, dispatch);
+ }
+
+ if (typeof actionCreators !== 'object' || actionCreators === null) {
+ throw new Error("bindActionCreators expected an object or a function, instead received " + (actionCreators === null ? 'null' : typeof actionCreators) + ". " + "Did you write \"import ActionCreators from\" instead of \"import * as ActionCreators from\"?");
+ }
+
+ var keys = Object.keys(actionCreators);
+ var boundActionCreators = {};
+
+ for (var i = 0; i < keys.length; i++) {
+ var key = keys[i];
+ var actionCreator = actionCreators[key];
+
+ if (typeof actionCreator === 'function') {
+ boundActionCreators[key] = bindActionCreator(actionCreator, dispatch);
+ }
+ }
+
+ return boundActionCreators;
+ }
+
+ function _defineProperty(obj, key, value) {
+ if (key in obj) {
+ Object.defineProperty(obj, key, {
+ value: value,
+ enumerable: true,
+ configurable: true,
+ writable: true
+ });
+ } else {
+ obj[key] = value;
+ }
+
+ return obj;
+ }
+
+ function _objectSpread(target) {
+ for (var i = 1; i < arguments.length; i++) {
+ var source = arguments[i] != null ? arguments[i] : {};
+ var ownKeys = Object.keys(source);
+
+ if (typeof Object.getOwnPropertySymbols === 'function') {
+ ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) {
+ return Object.getOwnPropertyDescriptor(source, sym).enumerable;
+ }));
+ }
+
+ ownKeys.forEach(function (key) {
+ _defineProperty(target, key, source[key]);
+ });
+ }
+
+ return target;
+ }
+
+ /**
+ * Composes single-argument functions from right to left. The rightmost
+ * function can take multiple arguments as it provides the signature for
+ * the resulting composite function.
+ *
+ * @param {...Function} funcs The functions to compose.
+ * @returns {Function} A function obtained by composing the argument functions
+ * from right to left. For example, compose(f, g, h) is identical to doing
+ * (...args) => f(g(h(...args))).
+ */
+ function compose() {
+ for (var _len = arguments.length, funcs = new Array(_len), _key = 0; _key < _len; _key++) {
+ funcs[_key] = arguments[_key];
+ }
+
+ if (funcs.length === 0) {
+ return function (arg) {
+ return arg;
+ };
+ }
+
+ if (funcs.length === 1) {
+ return funcs[0];
+ }
+
+ return funcs.reduce(function (a, b) {
+ return function () {
+ return a(b.apply(void 0, arguments));
+ };
+ });
+ }
+
+ /**
+ * Creates a store enhancer that applies middleware to the dispatch method
+ * of the Redux store. This is handy for a variety of tasks, such as expressing
+ * asynchronous actions in a concise manner, or logging every action payload.
+ *
+ * See `redux-thunk` package as an example of the Redux middleware.
+ *
+ * Because middleware is potentially asynchronous, this should be the first
+ * store enhancer in the composition chain.
+ *
+ * Note that each middleware will be given the `dispatch` and `getState` functions
+ * as named arguments.
+ *
+ * @param {...Function} middlewares The middleware chain to be applied.
+ * @returns {Function} A store enhancer applying the middleware.
+ */
+
+ function applyMiddleware() {
+ for (var _len = arguments.length, middlewares = new Array(_len), _key = 0; _key < _len; _key++) {
+ middlewares[_key] = arguments[_key];
+ }
+
+ return function (createStore) {
+ return function () {
+ var store = createStore.apply(void 0, arguments);
+
+ var _dispatch = function dispatch() {
+ throw new Error("Dispatching while constructing your middleware is not allowed. " + "Other middleware would not be applied to this dispatch.");
+ };
+
+ var middlewareAPI = {
+ getState: store.getState,
+ dispatch: function dispatch() {
+ return _dispatch.apply(void 0, arguments);
+ }
+ };
+ var chain = middlewares.map(function (middleware) {
+ return middleware(middlewareAPI);
+ });
+ _dispatch = compose.apply(void 0, chain)(store.dispatch);
+ return _objectSpread({}, store, {
+ dispatch: _dispatch
+ });
+ };
+ };
+ }
+
+ /*
+ * This is a dummy function to check if the function name has been altered by minification.
+ * If the function has been minified and NODE_ENV !== 'production', warn the user.
+ */
+
+ function isCrushed() {}
+
+ if (typeof isCrushed.name === 'string' && isCrushed.name !== 'isCrushed') {
+ warning('You are currently using minified code outside of NODE_ENV === "production". ' + 'This means that you are running a slower development build of Redux. ' + 'You can use loose-envify (https://github.com/zertosh/loose-envify) for browserify ' + 'or setting mode to production in webpack (https://webpack.js.org/concepts/mode/) ' + 'to ensure you have the correct code for your production build.');
+ }
+
+ exports.createStore = createStore;
+ exports.combineReducers = combineReducers;
+ exports.bindActionCreators = bindActionCreators;
+ exports.applyMiddleware = applyMiddleware;
+ exports.compose = compose;
+ exports.__DO_NOT_USE__ActionTypes = ActionTypes;
+
+ Object.defineProperty(exports, '__esModule', { value: true });
+
+ })));
diff --git a/browser/components/newtab/vendor/prop-types.js b/browser/components/newtab/vendor/prop-types.js
new file mode 100644
index 0000000000..71af27b7db
--- /dev/null
+++ b/browser/components/newtab/vendor/prop-types.js
@@ -0,0 +1 @@
+!function(f){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=f();else if("function"==typeof define&&define.amd)define([],f);else{var g;g="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,g.PropTypes=f()}}(function(){return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof require&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}for(var i="function"==typeof require&&require,o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module){"use strict";var emptyFunction=require(4),invariant=require(5),ReactPropTypesSecret=require(3);module.exports=function(){function e(e,r,t,n,p,o){o!==ReactPropTypesSecret&&invariant(!1,"Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types")}function r(){return e}e.isRequired=e;var t={array:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:r,element:e,instanceOf:r,node:e,objectOf:r,oneOf:r,oneOfType:r,shape:r,exact:r};return t.checkPropTypes=emptyFunction,t.PropTypes=t,t}},{3:3,4:4,5:5}],2:[function(require,module){module.exports=require(1)()},{1:1}],3:[function(require,module){"use strict";var ReactPropTypesSecret="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED";module.exports=ReactPropTypesSecret},{}],4:[function(require,module){"use strict";function makeEmptyFunction(arg){return function(){return arg}}var emptyFunction=function(){};emptyFunction.thatReturns=makeEmptyFunction,emptyFunction.thatReturnsFalse=makeEmptyFunction(!1),emptyFunction.thatReturnsTrue=makeEmptyFunction(!0),emptyFunction.thatReturnsNull=makeEmptyFunction(null),emptyFunction.thatReturnsThis=function(){return this},emptyFunction.thatReturnsArgument=function(arg){return arg},module.exports=emptyFunction},{}],5:[function(require,module){"use strict";function invariant(condition,format,a,b,c,d,e,f){if(validateFormat(format),!condition){var error;if(void 0===format)error=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var args=[a,b,c,d,e,f],argIndex=0;error=new Error(format.replace(/%s/g,function(){return args[argIndex++]})),error.name="Invariant Violation"}throw error.framesToPop=1,error}}var validateFormat=function(){};module.exports=invariant},{}]},{},[2])(2)}); \ No newline at end of file
diff --git a/browser/components/newtab/vendor/react-dev.js b/browser/components/newtab/vendor/react-dev.js
new file mode 100644
index 0000000000..6d64de1350
--- /dev/null
+++ b/browser/components/newtab/vendor/react-dev.js
@@ -0,0 +1,3318 @@
+/** @license React v16.13.1
+ * react.development.js
+ *
+ * Copyright (c) Facebook, Inc. and its affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+'use strict';
+
+(function (global, factory) {
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
+ typeof define === 'function' && define.amd ? define(['exports'], factory) :
+ (global = global || self, factory(global.React = {}));
+}(this, (function (exports) { 'use strict';
+
+ var ReactVersion = '16.13.1';
+
+ // The Symbol used to tag the ReactElement-like types. If there is no native Symbol
+ // nor polyfill, then a plain number is used for performance.
+ var hasSymbol = typeof Symbol === 'function' && Symbol.for;
+ var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;
+ var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;
+ var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;
+ var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;
+ var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;
+ var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;
+ var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace; // TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary
+ var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;
+ var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;
+ var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;
+ var REACT_SUSPENSE_LIST_TYPE = hasSymbol ? Symbol.for('react.suspense_list') : 0xead8;
+ var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;
+ var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;
+ var REACT_BLOCK_TYPE = hasSymbol ? Symbol.for('react.block') : 0xead9;
+ var REACT_FUNDAMENTAL_TYPE = hasSymbol ? Symbol.for('react.fundamental') : 0xead5;
+ var REACT_RESPONDER_TYPE = hasSymbol ? Symbol.for('react.responder') : 0xead6;
+ var REACT_SCOPE_TYPE = hasSymbol ? Symbol.for('react.scope') : 0xead7;
+ var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
+ var FAUX_ITERATOR_SYMBOL = '@@iterator';
+ function getIteratorFn(maybeIterable) {
+ if (maybeIterable === null || typeof maybeIterable !== 'object') {
+ return null;
+ }
+
+ var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
+
+ if (typeof maybeIterator === 'function') {
+ return maybeIterator;
+ }
+
+ return null;
+ }
+
+ /*
+ object-assign
+ (c) Sindre Sorhus
+ @license MIT
+ */
+ /* eslint-disable no-unused-vars */
+ var getOwnPropertySymbols = Object.getOwnPropertySymbols;
+ var hasOwnProperty = Object.prototype.hasOwnProperty;
+ var propIsEnumerable = Object.prototype.propertyIsEnumerable;
+
+ function toObject(val) {
+ if (val === null || val === undefined) {
+ throw new TypeError('Object.assign cannot be called with null or undefined');
+ }
+
+ return Object(val);
+ }
+
+ function shouldUseNative() {
+ try {
+ if (!Object.assign) {
+ return false;
+ }
+
+ // Detect buggy property enumeration order in older V8 versions.
+
+ // https://bugs.chromium.org/p/v8/issues/detail?id=4118
+ var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
+ test1[5] = 'de';
+ if (Object.getOwnPropertyNames(test1)[0] === '5') {
+ return false;
+ }
+
+ // https://bugs.chromium.org/p/v8/issues/detail?id=3056
+ var test2 = {};
+ for (var i = 0; i < 10; i++) {
+ test2['_' + String.fromCharCode(i)] = i;
+ }
+ var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
+ return test2[n];
+ });
+ if (order2.join('') !== '0123456789') {
+ return false;
+ }
+
+ // https://bugs.chromium.org/p/v8/issues/detail?id=3056
+ var test3 = {};
+ 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
+ test3[letter] = letter;
+ });
+ if (Object.keys(Object.assign({}, test3)).join('') !==
+ 'abcdefghijklmnopqrst') {
+ return false;
+ }
+
+ return true;
+ } catch (err) {
+ // We don't expect any of the above to throw, but better to be safe.
+ return false;
+ }
+ }
+
+ var objectAssign = shouldUseNative() ? Object.assign : function (target, source) {
+ var from;
+ var to = toObject(target);
+ var symbols;
+
+ for (var s = 1; s < arguments.length; s++) {
+ from = Object(arguments[s]);
+
+ for (var key in from) {
+ if (hasOwnProperty.call(from, key)) {
+ to[key] = from[key];
+ }
+ }
+
+ if (getOwnPropertySymbols) {
+ symbols = getOwnPropertySymbols(from);
+ for (var i = 0; i < symbols.length; i++) {
+ if (propIsEnumerable.call(from, symbols[i])) {
+ to[symbols[i]] = from[symbols[i]];
+ }
+ }
+ }
+ }
+
+ return to;
+ };
+
+ /**
+ * Keeps track of the current dispatcher.
+ */
+ var ReactCurrentDispatcher = {
+ /**
+ * @internal
+ * @type {ReactComponent}
+ */
+ current: null
+ };
+
+ /**
+ * Keeps track of the current batch's configuration such as how long an update
+ * should suspend for if it needs to.
+ */
+ var ReactCurrentBatchConfig = {
+ suspense: null
+ };
+
+ /**
+ * Keeps track of the current owner.
+ *
+ * The current owner is the component who should own any components that are
+ * currently being constructed.
+ */
+ var ReactCurrentOwner = {
+ /**
+ * @internal
+ * @type {ReactComponent}
+ */
+ current: null
+ };
+
+ var BEFORE_SLASH_RE = /^(.*)[\\\/]/;
+ function describeComponentFrame (name, source, ownerName) {
+ var sourceInfo = '';
+
+ if (source) {
+ var path = source.fileName;
+ var fileName = path.replace(BEFORE_SLASH_RE, '');
+
+ {
+ // In DEV, include code for a common special case:
+ // prefer "folder/index.js" instead of just "index.js".
+ if (/^index\./.test(fileName)) {
+ var match = path.match(BEFORE_SLASH_RE);
+
+ if (match) {
+ var pathBeforeSlash = match[1];
+
+ if (pathBeforeSlash) {
+ var folderName = pathBeforeSlash.replace(BEFORE_SLASH_RE, '');
+ fileName = folderName + '/' + fileName;
+ }
+ }
+ }
+ }
+
+ sourceInfo = ' (at ' + fileName + ':' + source.lineNumber + ')';
+ } else if (ownerName) {
+ sourceInfo = ' (created by ' + ownerName + ')';
+ }
+
+ return '\n in ' + (name || 'Unknown') + sourceInfo;
+ }
+
+ var Resolved = 1;
+ function refineResolvedLazyComponent(lazyComponent) {
+ return lazyComponent._status === Resolved ? lazyComponent._result : null;
+ }
+
+ function getWrappedName(outerType, innerType, wrapperName) {
+ var functionName = innerType.displayName || innerType.name || '';
+ return outerType.displayName || (functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName);
+ }
+
+ function getComponentName(type) {
+ if (type == null) {
+ // Host root, text node or just invalid type.
+ return null;
+ }
+
+ {
+ if (typeof type.tag === 'number') {
+ error('Received an unexpected object in getComponentName(). ' + 'This is likely a bug in React. Please file an issue.');
+ }
+ }
+
+ if (typeof type === 'function') {
+ return type.displayName || type.name || null;
+ }
+
+ if (typeof type === 'string') {
+ return type;
+ }
+
+ switch (type) {
+ case REACT_FRAGMENT_TYPE:
+ return 'Fragment';
+
+ case REACT_PORTAL_TYPE:
+ return 'Portal';
+
+ case REACT_PROFILER_TYPE:
+ return "Profiler";
+
+ case REACT_STRICT_MODE_TYPE:
+ return 'StrictMode';
+
+ case REACT_SUSPENSE_TYPE:
+ return 'Suspense';
+
+ case REACT_SUSPENSE_LIST_TYPE:
+ return 'SuspenseList';
+ }
+
+ if (typeof type === 'object') {
+ switch (type.$$typeof) {
+ case REACT_CONTEXT_TYPE:
+ return 'Context.Consumer';
+
+ case REACT_PROVIDER_TYPE:
+ return 'Context.Provider';
+
+ case REACT_FORWARD_REF_TYPE:
+ return getWrappedName(type, type.render, 'ForwardRef');
+
+ case REACT_MEMO_TYPE:
+ return getComponentName(type.type);
+
+ case REACT_BLOCK_TYPE:
+ return getComponentName(type.render);
+
+ case REACT_LAZY_TYPE:
+ {
+ var thenable = type;
+ var resolvedThenable = refineResolvedLazyComponent(thenable);
+
+ if (resolvedThenable) {
+ return getComponentName(resolvedThenable);
+ }
+
+ break;
+ }
+ }
+ }
+
+ return null;
+ }
+
+ var ReactDebugCurrentFrame = {};
+ var currentlyValidatingElement = null;
+ function setCurrentlyValidatingElement(element) {
+ {
+ currentlyValidatingElement = element;
+ }
+ }
+
+ {
+ // Stack implementation injected by the current renderer.
+ ReactDebugCurrentFrame.getCurrentStack = null;
+
+ ReactDebugCurrentFrame.getStackAddendum = function () {
+ var stack = ''; // Add an extra top frame while an element is being validated
+
+ if (currentlyValidatingElement) {
+ var name = getComponentName(currentlyValidatingElement.type);
+ var owner = currentlyValidatingElement._owner;
+ stack += describeComponentFrame(name, currentlyValidatingElement._source, owner && getComponentName(owner.type));
+ } // Delegate to the injected renderer-specific implementation
+
+
+ var impl = ReactDebugCurrentFrame.getCurrentStack;
+
+ if (impl) {
+ stack += impl() || '';
+ }
+
+ return stack;
+ };
+ }
+
+ /**
+ * Used by act() to track whether you're inside an act() scope.
+ */
+ var IsSomeRendererActing = {
+ current: false
+ };
+
+ var ReactSharedInternals = {
+ ReactCurrentDispatcher: ReactCurrentDispatcher,
+ ReactCurrentBatchConfig: ReactCurrentBatchConfig,
+ ReactCurrentOwner: ReactCurrentOwner,
+ IsSomeRendererActing: IsSomeRendererActing,
+ // Used by renderers to avoid bundling object-assign twice in UMD bundles:
+ assign: objectAssign
+ };
+
+ {
+ objectAssign(ReactSharedInternals, {
+ // These should not be included in production.
+ ReactDebugCurrentFrame: ReactDebugCurrentFrame,
+ // Shim for React DOM 16.0.0 which still destructured (but not used) this.
+ // TODO: remove in React 17.0.
+ ReactComponentTreeHook: {}
+ });
+ }
+
+ // by calls to these methods by a Babel plugin.
+ //
+ // In PROD (or in packages without access to React internals),
+ // they are left as they are instead.
+
+ function warn(format) {
+ {
+ for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
+ args[_key - 1] = arguments[_key];
+ }
+
+ printWarning('warn', format, args);
+ }
+ }
+ function error(format) {
+ {
+ for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
+ args[_key2 - 1] = arguments[_key2];
+ }
+
+ printWarning('error', format, args);
+ }
+ }
+
+ function printWarning(level, format, args) {
+ // When changing this logic, you might want to also
+ // update consoleWithStackDev.www.js as well.
+ {
+ var hasExistingStack = args.length > 0 && typeof args[args.length - 1] === 'string' && args[args.length - 1].indexOf('\n in') === 0;
+
+ if (!hasExistingStack) {
+ var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
+ var stack = ReactDebugCurrentFrame.getStackAddendum();
+
+ if (stack !== '') {
+ format += '%s';
+ args = args.concat([stack]);
+ }
+ }
+
+ var argsWithFormat = args.map(function (item) {
+ return '' + item;
+ }); // Careful: RN currently depends on this prefix
+
+ argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
+ // breaks IE9: https://github.com/facebook/react/issues/13610
+ // eslint-disable-next-line react-internal/no-production-logging
+
+ Function.prototype.apply.call(console[level], console, argsWithFormat);
+
+ try {
+ // --- Welcome to debugging React ---
+ // This error was thrown as a convenience so that you can use this stack
+ // to find the callsite that caused this warning to fire.
+ var argIndex = 0;
+ var message = 'Warning: ' + format.replace(/%s/g, function () {
+ return args[argIndex++];
+ });
+ throw new Error(message);
+ } catch (x) {}
+ }
+ }
+
+ var didWarnStateUpdateForUnmountedComponent = {};
+
+ function warnNoop(publicInstance, callerName) {
+ {
+ var _constructor = publicInstance.constructor;
+ var componentName = _constructor && (_constructor.displayName || _constructor.name) || 'ReactClass';
+ var warningKey = componentName + "." + callerName;
+
+ if (didWarnStateUpdateForUnmountedComponent[warningKey]) {
+ return;
+ }
+
+ error("Can't call %s on a component that is not yet mounted. " + 'This is a no-op, but it might indicate a bug in your application. ' + 'Instead, assign to `this.state` directly or define a `state = {};` ' + 'class property with the desired state in the %s component.', callerName, componentName);
+
+ didWarnStateUpdateForUnmountedComponent[warningKey] = true;
+ }
+ }
+ /**
+ * This is the abstract API for an update queue.
+ */
+
+
+ var ReactNoopUpdateQueue = {
+ /**
+ * Checks whether or not this composite component is mounted.
+ * @param {ReactClass} publicInstance The instance we want to test.
+ * @return {boolean} True if mounted, false otherwise.
+ * @protected
+ * @final
+ */
+ isMounted: function (publicInstance) {
+ return false;
+ },
+
+ /**
+ * Forces an update. This should only be invoked when it is known with
+ * certainty that we are **not** in a DOM transaction.
+ *
+ * You may want to call this when you know that some deeper aspect of the
+ * component's state has changed but `setState` was not called.
+ *
+ * This will not invoke `shouldComponentUpdate`, but it will invoke
+ * `componentWillUpdate` and `componentDidUpdate`.
+ *
+ * @param {ReactClass} publicInstance The instance that should rerender.
+ * @param {?function} callback Called after component is updated.
+ * @param {?string} callerName name of the calling function in the public API.
+ * @internal
+ */
+ enqueueForceUpdate: function (publicInstance, callback, callerName) {
+ warnNoop(publicInstance, 'forceUpdate');
+ },
+
+ /**
+ * Replaces all of the state. Always use this or `setState` to mutate state.
+ * You should treat `this.state` as immutable.
+ *
+ * There is no guarantee that `this.state` will be immediately updated, so
+ * accessing `this.state` after calling this method may return the old value.
+ *
+ * @param {ReactClass} publicInstance The instance that should rerender.
+ * @param {object} completeState Next state.
+ * @param {?function} callback Called after component is updated.
+ * @param {?string} callerName name of the calling function in the public API.
+ * @internal
+ */
+ enqueueReplaceState: function (publicInstance, completeState, callback, callerName) {
+ warnNoop(publicInstance, 'replaceState');
+ },
+
+ /**
+ * Sets a subset of the state. This only exists because _pendingState is
+ * internal. This provides a merging strategy that is not available to deep
+ * properties which is confusing. TODO: Expose pendingState or don't use it
+ * during the merge.
+ *
+ * @param {ReactClass} publicInstance The instance that should rerender.
+ * @param {object} partialState Next partial state to be merged with state.
+ * @param {?function} callback Called after component is updated.
+ * @param {?string} Name of the calling function in the public API.
+ * @internal
+ */
+ enqueueSetState: function (publicInstance, partialState, callback, callerName) {
+ warnNoop(publicInstance, 'setState');
+ }
+ };
+
+ var emptyObject = {};
+
+ {
+ Object.freeze(emptyObject);
+ }
+ /**
+ * Base class helpers for the updating state of a component.
+ */
+
+
+ function Component(props, context, updater) {
+ this.props = props;
+ this.context = context; // If a component has string refs, we will assign a different object later.
+
+ this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the
+ // renderer.
+
+ this.updater = updater || ReactNoopUpdateQueue;
+ }
+
+ Component.prototype.isReactComponent = {};
+ /**
+ * Sets a subset of the state. Always use this to mutate
+ * state. You should treat `this.state` as immutable.
+ *
+ * There is no guarantee that `this.state` will be immediately updated, so
+ * accessing `this.state` after calling this method may return the old value.
+ *
+ * There is no guarantee that calls to `setState` will run synchronously,
+ * as they may eventually be batched together. You can provide an optional
+ * callback that will be executed when the call to setState is actually
+ * completed.
+ *
+ * When a function is provided to setState, it will be called at some point in
+ * the future (not synchronously). It will be called with the up to date
+ * component arguments (state, props, context). These values can be different
+ * from this.* because your function may be called after receiveProps but before
+ * shouldComponentUpdate, and this new state, props, and context will not yet be
+ * assigned to this.
+ *
+ * @param {object|function} partialState Next partial state or function to
+ * produce next partial state to be merged with current state.
+ * @param {?function} callback Called after state is updated.
+ * @final
+ * @protected
+ */
+
+ Component.prototype.setState = function (partialState, callback) {
+ if (!(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null)) {
+ {
+ throw Error( "setState(...): takes an object of state variables to update or a function which returns an object of state variables." );
+ }
+ }
+
+ this.updater.enqueueSetState(this, partialState, callback, 'setState');
+ };
+ /**
+ * Forces an update. This should only be invoked when it is known with
+ * certainty that we are **not** in a DOM transaction.
+ *
+ * You may want to call this when you know that some deeper aspect of the
+ * component's state has changed but `setState` was not called.
+ *
+ * This will not invoke `shouldComponentUpdate`, but it will invoke
+ * `componentWillUpdate` and `componentDidUpdate`.
+ *
+ * @param {?function} callback Called after update is complete.
+ * @final
+ * @protected
+ */
+
+
+ Component.prototype.forceUpdate = function (callback) {
+ this.updater.enqueueForceUpdate(this, callback, 'forceUpdate');
+ };
+ /**
+ * Deprecated APIs. These APIs used to exist on classic React classes but since
+ * we would like to deprecate them, we're not going to move them over to this
+ * modern base class. Instead, we define a getter that warns if it's accessed.
+ */
+
+
+ {
+ var deprecatedAPIs = {
+ isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'],
+ replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).']
+ };
+
+ var defineDeprecationWarning = function (methodName, info) {
+ Object.defineProperty(Component.prototype, methodName, {
+ get: function () {
+ warn('%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]);
+
+ return undefined;
+ }
+ });
+ };
+
+ for (var fnName in deprecatedAPIs) {
+ if (deprecatedAPIs.hasOwnProperty(fnName)) {
+ defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);
+ }
+ }
+ }
+
+ function ComponentDummy() {}
+
+ ComponentDummy.prototype = Component.prototype;
+ /**
+ * Convenience component with default shallow equality check for sCU.
+ */
+
+ function PureComponent(props, context, updater) {
+ this.props = props;
+ this.context = context; // If a component has string refs, we will assign a different object later.
+
+ this.refs = emptyObject;
+ this.updater = updater || ReactNoopUpdateQueue;
+ }
+
+ var pureComponentPrototype = PureComponent.prototype = new ComponentDummy();
+ pureComponentPrototype.constructor = PureComponent; // Avoid an extra prototype jump for these methods.
+
+ objectAssign(pureComponentPrototype, Component.prototype);
+
+ pureComponentPrototype.isPureReactComponent = true;
+
+ // an immutable object with a single mutable value
+ function createRef() {
+ var refObject = {
+ current: null
+ };
+
+ {
+ Object.seal(refObject);
+ }
+
+ return refObject;
+ }
+
+ var hasOwnProperty$1 = Object.prototype.hasOwnProperty;
+ var RESERVED_PROPS = {
+ key: true,
+ ref: true,
+ __self: true,
+ __source: true
+ };
+ var specialPropKeyWarningShown, specialPropRefWarningShown, didWarnAboutStringRefs;
+
+ {
+ didWarnAboutStringRefs = {};
+ }
+
+ function hasValidRef(config) {
+ {
+ if (hasOwnProperty$1.call(config, 'ref')) {
+ var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;
+
+ if (getter && getter.isReactWarning) {
+ return false;
+ }
+ }
+ }
+
+ return config.ref !== undefined;
+ }
+
+ function hasValidKey(config) {
+ {
+ if (hasOwnProperty$1.call(config, 'key')) {
+ var getter = Object.getOwnPropertyDescriptor(config, 'key').get;
+
+ if (getter && getter.isReactWarning) {
+ return false;
+ }
+ }
+ }
+
+ return config.key !== undefined;
+ }
+
+ function defineKeyPropWarningGetter(props, displayName) {
+ var warnAboutAccessingKey = function () {
+ {
+ if (!specialPropKeyWarningShown) {
+ specialPropKeyWarningShown = true;
+
+ error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', displayName);
+ }
+ }
+ };
+
+ warnAboutAccessingKey.isReactWarning = true;
+ Object.defineProperty(props, 'key', {
+ get: warnAboutAccessingKey,
+ configurable: true
+ });
+ }
+
+ function defineRefPropWarningGetter(props, displayName) {
+ var warnAboutAccessingRef = function () {
+ {
+ if (!specialPropRefWarningShown) {
+ specialPropRefWarningShown = true;
+
+ error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', displayName);
+ }
+ }
+ };
+
+ warnAboutAccessingRef.isReactWarning = true;
+ Object.defineProperty(props, 'ref', {
+ get: warnAboutAccessingRef,
+ configurable: true
+ });
+ }
+
+ function warnIfStringRefCannotBeAutoConverted(config) {
+ {
+ if (typeof config.ref === 'string' && ReactCurrentOwner.current && config.__self && ReactCurrentOwner.current.stateNode !== config.__self) {
+ var componentName = getComponentName(ReactCurrentOwner.current.type);
+
+ if (!didWarnAboutStringRefs[componentName]) {
+ error('Component "%s" contains the string ref "%s". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://fb.me/react-strict-mode-string-ref', getComponentName(ReactCurrentOwner.current.type), config.ref);
+
+ didWarnAboutStringRefs[componentName] = true;
+ }
+ }
+ }
+ }
+ /**
+ * Factory method to create a new React element. This no longer adheres to
+ * the class pattern, so do not use new to call it. Also, instanceof check
+ * will not work. Instead test $$typeof field against Symbol.for('react.element') to check
+ * if something is a React Element.
+ *
+ * @param {*} type
+ * @param {*} props
+ * @param {*} key
+ * @param {string|object} ref
+ * @param {*} owner
+ * @param {*} self A *temporary* helper to detect places where `this` is
+ * different from the `owner` when React.createElement is called, so that we
+ * can warn. We want to get rid of owner and replace string `ref`s with arrow
+ * functions, and as long as `this` and owner are the same, there will be no
+ * change in behavior.
+ * @param {*} source An annotation object (added by a transpiler or otherwise)
+ * indicating filename, line number, and/or other information.
+ * @internal
+ */
+
+
+ var ReactElement = function (type, key, ref, self, source, owner, props) {
+ var element = {
+ // This tag allows us to uniquely identify this as a React Element
+ $$typeof: REACT_ELEMENT_TYPE,
+ // Built-in properties that belong on the element
+ type: type,
+ key: key,
+ ref: ref,
+ props: props,
+ // Record the component responsible for creating this element.
+ _owner: owner
+ };
+
+ {
+ // The validation flag is currently mutative. We put it on
+ // an external backing store so that we can freeze the whole object.
+ // This can be replaced with a WeakMap once they are implemented in
+ // commonly used development environments.
+ element._store = {}; // To make comparing ReactElements easier for testing purposes, we make
+ // the validation flag non-enumerable (where possible, which should
+ // include every environment we run tests in), so the test framework
+ // ignores it.
+
+ Object.defineProperty(element._store, 'validated', {
+ configurable: false,
+ enumerable: false,
+ writable: true,
+ value: false
+ }); // self and source are DEV only properties.
+
+ Object.defineProperty(element, '_self', {
+ configurable: false,
+ enumerable: false,
+ writable: false,
+ value: self
+ }); // Two elements created in two different places should be considered
+ // equal for testing purposes and therefore we hide it from enumeration.
+
+ Object.defineProperty(element, '_source', {
+ configurable: false,
+ enumerable: false,
+ writable: false,
+ value: source
+ });
+
+ if (Object.freeze) {
+ Object.freeze(element.props);
+ Object.freeze(element);
+ }
+ }
+
+ return element;
+ };
+ /**
+ * Create and return a new ReactElement of the given type.
+ * See https://reactjs.org/docs/react-api.html#createelement
+ */
+
+ function createElement(type, config, children) {
+ var propName; // Reserved names are extracted
+
+ var props = {};
+ var key = null;
+ var ref = null;
+ var self = null;
+ var source = null;
+
+ if (config != null) {
+ if (hasValidRef(config)) {
+ ref = config.ref;
+
+ {
+ warnIfStringRefCannotBeAutoConverted(config);
+ }
+ }
+
+ if (hasValidKey(config)) {
+ key = '' + config.key;
+ }
+
+ self = config.__self === undefined ? null : config.__self;
+ source = config.__source === undefined ? null : config.__source; // Remaining properties are added to a new props object
+
+ for (propName in config) {
+ if (hasOwnProperty$1.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
+ props[propName] = config[propName];
+ }
+ }
+ } // Children can be more than one argument, and those are transferred onto
+ // the newly allocated props object.
+
+
+ var childrenLength = arguments.length - 2;
+
+ if (childrenLength === 1) {
+ props.children = children;
+ } else if (childrenLength > 1) {
+ var childArray = Array(childrenLength);
+
+ for (var i = 0; i < childrenLength; i++) {
+ childArray[i] = arguments[i + 2];
+ }
+
+ {
+ if (Object.freeze) {
+ Object.freeze(childArray);
+ }
+ }
+
+ props.children = childArray;
+ } // Resolve default props
+
+
+ if (type && type.defaultProps) {
+ var defaultProps = type.defaultProps;
+
+ for (propName in defaultProps) {
+ if (props[propName] === undefined) {
+ props[propName] = defaultProps[propName];
+ }
+ }
+ }
+
+ {
+ if (key || ref) {
+ var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;
+
+ if (key) {
+ defineKeyPropWarningGetter(props, displayName);
+ }
+
+ if (ref) {
+ defineRefPropWarningGetter(props, displayName);
+ }
+ }
+ }
+
+ return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
+ }
+ function cloneAndReplaceKey(oldElement, newKey) {
+ var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props);
+ return newElement;
+ }
+ /**
+ * Clone and return a new ReactElement using element as the starting point.
+ * See https://reactjs.org/docs/react-api.html#cloneelement
+ */
+
+ function cloneElement(element, config, children) {
+ if (!!(element === null || element === undefined)) {
+ {
+ throw Error( "React.cloneElement(...): The argument must be a React element, but you passed " + element + "." );
+ }
+ }
+
+ var propName; // Original props are copied
+
+ var props = objectAssign({}, element.props); // Reserved names are extracted
+
+
+ var key = element.key;
+ var ref = element.ref; // Self is preserved since the owner is preserved.
+
+ var self = element._self; // Source is preserved since cloneElement is unlikely to be targeted by a
+ // transpiler, and the original source is probably a better indicator of the
+ // true owner.
+
+ var source = element._source; // Owner will be preserved, unless ref is overridden
+
+ var owner = element._owner;
+
+ if (config != null) {
+ if (hasValidRef(config)) {
+ // Silently steal the ref from the parent.
+ ref = config.ref;
+ owner = ReactCurrentOwner.current;
+ }
+
+ if (hasValidKey(config)) {
+ key = '' + config.key;
+ } // Remaining properties override existing props
+
+
+ var defaultProps;
+
+ if (element.type && element.type.defaultProps) {
+ defaultProps = element.type.defaultProps;
+ }
+
+ for (propName in config) {
+ if (hasOwnProperty$1.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
+ if (config[propName] === undefined && defaultProps !== undefined) {
+ // Resolve default props
+ props[propName] = defaultProps[propName];
+ } else {
+ props[propName] = config[propName];
+ }
+ }
+ }
+ } // Children can be more than one argument, and those are transferred onto
+ // the newly allocated props object.
+
+
+ var childrenLength = arguments.length - 2;
+
+ if (childrenLength === 1) {
+ props.children = children;
+ } else if (childrenLength > 1) {
+ var childArray = Array(childrenLength);
+
+ for (var i = 0; i < childrenLength; i++) {
+ childArray[i] = arguments[i + 2];
+ }
+
+ props.children = childArray;
+ }
+
+ return ReactElement(element.type, key, ref, self, source, owner, props);
+ }
+ /**
+ * Verifies the object is a ReactElement.
+ * See https://reactjs.org/docs/react-api.html#isvalidelement
+ * @param {?object} object
+ * @return {boolean} True if `object` is a ReactElement.
+ * @final
+ */
+
+ function isValidElement(object) {
+ return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
+ }
+
+ var SEPARATOR = '.';
+ var SUBSEPARATOR = ':';
+ /**
+ * Escape and wrap key so it is safe to use as a reactid
+ *
+ * @param {string} key to be escaped.
+ * @return {string} the escaped key.
+ */
+
+ function escape(key) {
+ var escapeRegex = /[=:]/g;
+ var escaperLookup = {
+ '=': '=0',
+ ':': '=2'
+ };
+ var escapedString = ('' + key).replace(escapeRegex, function (match) {
+ return escaperLookup[match];
+ });
+ return '$' + escapedString;
+ }
+ /**
+ * TODO: Test that a single child and an array with one item have the same key
+ * pattern.
+ */
+
+
+ var didWarnAboutMaps = false;
+ var userProvidedKeyEscapeRegex = /\/+/g;
+
+ function escapeUserProvidedKey(text) {
+ return ('' + text).replace(userProvidedKeyEscapeRegex, '$&/');
+ }
+
+ var POOL_SIZE = 10;
+ var traverseContextPool = [];
+
+ function getPooledTraverseContext(mapResult, keyPrefix, mapFunction, mapContext) {
+ if (traverseContextPool.length) {
+ var traverseContext = traverseContextPool.pop();
+ traverseContext.result = mapResult;
+ traverseContext.keyPrefix = keyPrefix;
+ traverseContext.func = mapFunction;
+ traverseContext.context = mapContext;
+ traverseContext.count = 0;
+ return traverseContext;
+ } else {
+ return {
+ result: mapResult,
+ keyPrefix: keyPrefix,
+ func: mapFunction,
+ context: mapContext,
+ count: 0
+ };
+ }
+ }
+
+ function releaseTraverseContext(traverseContext) {
+ traverseContext.result = null;
+ traverseContext.keyPrefix = null;
+ traverseContext.func = null;
+ traverseContext.context = null;
+ traverseContext.count = 0;
+
+ if (traverseContextPool.length < POOL_SIZE) {
+ traverseContextPool.push(traverseContext);
+ }
+ }
+ /**
+ * @param {?*} children Children tree container.
+ * @param {!string} nameSoFar Name of the key path so far.
+ * @param {!function} callback Callback to invoke with each child found.
+ * @param {?*} traverseContext Used to pass information throughout the traversal
+ * process.
+ * @return {!number} The number of children in this subtree.
+ */
+
+
+ function traverseAllChildrenImpl(children, nameSoFar, callback, traverseContext) {
+ var type = typeof children;
+
+ if (type === 'undefined' || type === 'boolean') {
+ // All of the above are perceived as null.
+ children = null;
+ }
+
+ var invokeCallback = false;
+
+ if (children === null) {
+ invokeCallback = true;
+ } else {
+ switch (type) {
+ case 'string':
+ case 'number':
+ invokeCallback = true;
+ break;
+
+ case 'object':
+ switch (children.$$typeof) {
+ case REACT_ELEMENT_TYPE:
+ case REACT_PORTAL_TYPE:
+ invokeCallback = true;
+ }
+
+ }
+ }
+
+ if (invokeCallback) {
+ callback(traverseContext, children, // If it's the only child, treat the name as if it was wrapped in an array
+ // so that it's consistent if the number of children grows.
+ nameSoFar === '' ? SEPARATOR + getComponentKey(children, 0) : nameSoFar);
+ return 1;
+ }
+
+ var child;
+ var nextName;
+ var subtreeCount = 0; // Count of children found in the current subtree.
+
+ var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR;
+
+ if (Array.isArray(children)) {
+ for (var i = 0; i < children.length; i++) {
+ child = children[i];
+ nextName = nextNamePrefix + getComponentKey(child, i);
+ subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext);
+ }
+ } else {
+ var iteratorFn = getIteratorFn(children);
+
+ if (typeof iteratorFn === 'function') {
+
+ {
+ // Warn about using Maps as children
+ if (iteratorFn === children.entries) {
+ if (!didWarnAboutMaps) {
+ warn('Using Maps as children is deprecated and will be removed in ' + 'a future major release. Consider converting children to ' + 'an array of keyed ReactElements instead.');
+ }
+
+ didWarnAboutMaps = true;
+ }
+ }
+
+ var iterator = iteratorFn.call(children);
+ var step;
+ var ii = 0;
+
+ while (!(step = iterator.next()).done) {
+ child = step.value;
+ nextName = nextNamePrefix + getComponentKey(child, ii++);
+ subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext);
+ }
+ } else if (type === 'object') {
+ var addendum = '';
+
+ {
+ addendum = ' If you meant to render a collection of children, use an array ' + 'instead.' + ReactDebugCurrentFrame.getStackAddendum();
+ }
+
+ var childrenString = '' + children;
+
+ {
+ {
+ throw Error( "Objects are not valid as a React child (found: " + (childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString) + ")." + addendum );
+ }
+ }
+ }
+ }
+
+ return subtreeCount;
+ }
+ /**
+ * Traverses children that are typically specified as `props.children`, but
+ * might also be specified through attributes:
+ *
+ * - `traverseAllChildren(this.props.children, ...)`
+ * - `traverseAllChildren(this.props.leftPanelChildren, ...)`
+ *
+ * The `traverseContext` is an optional argument that is passed through the
+ * entire traversal. It can be used to store accumulations or anything else that
+ * the callback might find relevant.
+ *
+ * @param {?*} children Children tree object.
+ * @param {!function} callback To invoke upon traversing each child.
+ * @param {?*} traverseContext Context for traversal.
+ * @return {!number} The number of children in this subtree.
+ */
+
+
+ function traverseAllChildren(children, callback, traverseContext) {
+ if (children == null) {
+ return 0;
+ }
+
+ return traverseAllChildrenImpl(children, '', callback, traverseContext);
+ }
+ /**
+ * Generate a key string that identifies a component within a set.
+ *
+ * @param {*} component A component that could contain a manual key.
+ * @param {number} index Index that is used if a manual key is not provided.
+ * @return {string}
+ */
+
+
+ function getComponentKey(component, index) {
+ // Do some typechecking here since we call this blindly. We want to ensure
+ // that we don't block potential future ES APIs.
+ if (typeof component === 'object' && component !== null && component.key != null) {
+ // Explicit key
+ return escape(component.key);
+ } // Implicit key determined by the index in the set
+
+
+ return index.toString(36);
+ }
+
+ function forEachSingleChild(bookKeeping, child, name) {
+ var func = bookKeeping.func,
+ context = bookKeeping.context;
+ func.call(context, child, bookKeeping.count++);
+ }
+ /**
+ * Iterates through children that are typically specified as `props.children`.
+ *
+ * See https://reactjs.org/docs/react-api.html#reactchildrenforeach
+ *
+ * The provided forEachFunc(child, index) will be called for each
+ * leaf child.
+ *
+ * @param {?*} children Children tree container.
+ * @param {function(*, int)} forEachFunc
+ * @param {*} forEachContext Context for forEachContext.
+ */
+
+
+ function forEachChildren(children, forEachFunc, forEachContext) {
+ if (children == null) {
+ return children;
+ }
+
+ var traverseContext = getPooledTraverseContext(null, null, forEachFunc, forEachContext);
+ traverseAllChildren(children, forEachSingleChild, traverseContext);
+ releaseTraverseContext(traverseContext);
+ }
+
+ function mapSingleChildIntoContext(bookKeeping, child, childKey) {
+ var result = bookKeeping.result,
+ keyPrefix = bookKeeping.keyPrefix,
+ func = bookKeeping.func,
+ context = bookKeeping.context;
+ var mappedChild = func.call(context, child, bookKeeping.count++);
+
+ if (Array.isArray(mappedChild)) {
+ mapIntoWithKeyPrefixInternal(mappedChild, result, childKey, function (c) {
+ return c;
+ });
+ } else if (mappedChild != null) {
+ if (isValidElement(mappedChild)) {
+ mappedChild = cloneAndReplaceKey(mappedChild, // Keep both the (mapped) and old keys if they differ, just as
+ // traverseAllChildren used to do for objects as children
+ keyPrefix + (mappedChild.key && (!child || child.key !== mappedChild.key) ? escapeUserProvidedKey(mappedChild.key) + '/' : '') + childKey);
+ }
+
+ result.push(mappedChild);
+ }
+ }
+
+ function mapIntoWithKeyPrefixInternal(children, array, prefix, func, context) {
+ var escapedPrefix = '';
+
+ if (prefix != null) {
+ escapedPrefix = escapeUserProvidedKey(prefix) + '/';
+ }
+
+ var traverseContext = getPooledTraverseContext(array, escapedPrefix, func, context);
+ traverseAllChildren(children, mapSingleChildIntoContext, traverseContext);
+ releaseTraverseContext(traverseContext);
+ }
+ /**
+ * Maps children that are typically specified as `props.children`.
+ *
+ * See https://reactjs.org/docs/react-api.html#reactchildrenmap
+ *
+ * The provided mapFunction(child, key, index) will be called for each
+ * leaf child.
+ *
+ * @param {?*} children Children tree container.
+ * @param {function(*, int)} func The map function.
+ * @param {*} context Context for mapFunction.
+ * @return {object} Object containing the ordered map of results.
+ */
+
+
+ function mapChildren(children, func, context) {
+ if (children == null) {
+ return children;
+ }
+
+ var result = [];
+ mapIntoWithKeyPrefixInternal(children, result, null, func, context);
+ return result;
+ }
+ /**
+ * Count the number of children that are typically specified as
+ * `props.children`.
+ *
+ * See https://reactjs.org/docs/react-api.html#reactchildrencount
+ *
+ * @param {?*} children Children tree container.
+ * @return {number} The number of children.
+ */
+
+
+ function countChildren(children) {
+ return traverseAllChildren(children, function () {
+ return null;
+ }, null);
+ }
+ /**
+ * Flatten a children object (typically specified as `props.children`) and
+ * return an array with appropriately re-keyed children.
+ *
+ * See https://reactjs.org/docs/react-api.html#reactchildrentoarray
+ */
+
+
+ function toArray(children) {
+ var result = [];
+ mapIntoWithKeyPrefixInternal(children, result, null, function (child) {
+ return child;
+ });
+ return result;
+ }
+ /**
+ * Returns the first child in a collection of children and verifies that there
+ * is only one child in the collection.
+ *
+ * See https://reactjs.org/docs/react-api.html#reactchildrenonly
+ *
+ * The current implementation of this function assumes that a single child gets
+ * passed without a wrapper, but the purpose of this helper function is to
+ * abstract away the particular structure of children.
+ *
+ * @param {?object} children Child collection structure.
+ * @return {ReactElement} The first and only `ReactElement` contained in the
+ * structure.
+ */
+
+
+ function onlyChild(children) {
+ if (!isValidElement(children)) {
+ {
+ throw Error( "React.Children.only expected to receive a single React element child." );
+ }
+ }
+
+ return children;
+ }
+
+ function createContext(defaultValue, calculateChangedBits) {
+ if (calculateChangedBits === undefined) {
+ calculateChangedBits = null;
+ } else {
+ {
+ if (calculateChangedBits !== null && typeof calculateChangedBits !== 'function') {
+ error('createContext: Expected the optional second argument to be a ' + 'function. Instead received: %s', calculateChangedBits);
+ }
+ }
+ }
+
+ var context = {
+ $$typeof: REACT_CONTEXT_TYPE,
+ _calculateChangedBits: calculateChangedBits,
+ // As a workaround to support multiple concurrent renderers, we categorize
+ // some renderers as primary and others as secondary. We only expect
+ // there to be two concurrent renderers at most: React Native (primary) and
+ // Fabric (secondary); React DOM (primary) and React ART (secondary).
+ // Secondary renderers store their context values on separate fields.
+ _currentValue: defaultValue,
+ _currentValue2: defaultValue,
+ // Used to track how many concurrent renderers this context currently
+ // supports within in a single renderer. Such as parallel server rendering.
+ _threadCount: 0,
+ // These are circular
+ Provider: null,
+ Consumer: null
+ };
+ context.Provider = {
+ $$typeof: REACT_PROVIDER_TYPE,
+ _context: context
+ };
+ var hasWarnedAboutUsingNestedContextConsumers = false;
+ var hasWarnedAboutUsingConsumerProvider = false;
+
+ {
+ // A separate object, but proxies back to the original context object for
+ // backwards compatibility. It has a different $$typeof, so we can properly
+ // warn for the incorrect usage of Context as a Consumer.
+ var Consumer = {
+ $$typeof: REACT_CONTEXT_TYPE,
+ _context: context,
+ _calculateChangedBits: context._calculateChangedBits
+ }; // $FlowFixMe: Flow complains about not setting a value, which is intentional here
+
+ Object.defineProperties(Consumer, {
+ Provider: {
+ get: function () {
+ if (!hasWarnedAboutUsingConsumerProvider) {
+ hasWarnedAboutUsingConsumerProvider = true;
+
+ error('Rendering <Context.Consumer.Provider> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Provider> instead?');
+ }
+
+ return context.Provider;
+ },
+ set: function (_Provider) {
+ context.Provider = _Provider;
+ }
+ },
+ _currentValue: {
+ get: function () {
+ return context._currentValue;
+ },
+ set: function (_currentValue) {
+ context._currentValue = _currentValue;
+ }
+ },
+ _currentValue2: {
+ get: function () {
+ return context._currentValue2;
+ },
+ set: function (_currentValue2) {
+ context._currentValue2 = _currentValue2;
+ }
+ },
+ _threadCount: {
+ get: function () {
+ return context._threadCount;
+ },
+ set: function (_threadCount) {
+ context._threadCount = _threadCount;
+ }
+ },
+ Consumer: {
+ get: function () {
+ if (!hasWarnedAboutUsingNestedContextConsumers) {
+ hasWarnedAboutUsingNestedContextConsumers = true;
+
+ error('Rendering <Context.Consumer.Consumer> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?');
+ }
+
+ return context.Consumer;
+ }
+ }
+ }); // $FlowFixMe: Flow complains about missing properties because it doesn't understand defineProperty
+
+ context.Consumer = Consumer;
+ }
+
+ {
+ context._currentRenderer = null;
+ context._currentRenderer2 = null;
+ }
+
+ return context;
+ }
+
+ function lazy(ctor) {
+ var lazyType = {
+ $$typeof: REACT_LAZY_TYPE,
+ _ctor: ctor,
+ // React uses these fields to store the result.
+ _status: -1,
+ _result: null
+ };
+
+ {
+ // In production, this would just set it on the object.
+ var defaultProps;
+ var propTypes;
+ Object.defineProperties(lazyType, {
+ defaultProps: {
+ configurable: true,
+ get: function () {
+ return defaultProps;
+ },
+ set: function (newDefaultProps) {
+ error('React.lazy(...): It is not supported to assign `defaultProps` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.');
+
+ defaultProps = newDefaultProps; // Match production behavior more closely:
+
+ Object.defineProperty(lazyType, 'defaultProps', {
+ enumerable: true
+ });
+ }
+ },
+ propTypes: {
+ configurable: true,
+ get: function () {
+ return propTypes;
+ },
+ set: function (newPropTypes) {
+ error('React.lazy(...): It is not supported to assign `propTypes` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.');
+
+ propTypes = newPropTypes; // Match production behavior more closely:
+
+ Object.defineProperty(lazyType, 'propTypes', {
+ enumerable: true
+ });
+ }
+ }
+ });
+ }
+
+ return lazyType;
+ }
+
+ function forwardRef(render) {
+ {
+ if (render != null && render.$$typeof === REACT_MEMO_TYPE) {
+ error('forwardRef requires a render function but received a `memo` ' + 'component. Instead of forwardRef(memo(...)), use ' + 'memo(forwardRef(...)).');
+ } else if (typeof render !== 'function') {
+ error('forwardRef requires a render function but was given %s.', render === null ? 'null' : typeof render);
+ } else {
+ if (render.length !== 0 && render.length !== 2) {
+ error('forwardRef render functions accept exactly two parameters: props and ref. %s', render.length === 1 ? 'Did you forget to use the ref parameter?' : 'Any additional parameter will be undefined.');
+ }
+ }
+
+ if (render != null) {
+ if (render.defaultProps != null || render.propTypes != null) {
+ error('forwardRef render functions do not support propTypes or defaultProps. ' + 'Did you accidentally pass a React component?');
+ }
+ }
+ }
+
+ return {
+ $$typeof: REACT_FORWARD_REF_TYPE,
+ render: render
+ };
+ }
+
+ function isValidElementType(type) {
+ return typeof type === 'string' || typeof type === 'function' || // Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill.
+ type === REACT_FRAGMENT_TYPE || type === REACT_CONCURRENT_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || typeof type === 'object' && type !== null && (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_RESPONDER_TYPE || type.$$typeof === REACT_SCOPE_TYPE || type.$$typeof === REACT_BLOCK_TYPE);
+ }
+
+ function memo(type, compare) {
+ {
+ if (!isValidElementType(type)) {
+ error('memo: The first argument must be a component. Instead ' + 'received: %s', type === null ? 'null' : typeof type);
+ }
+ }
+
+ return {
+ $$typeof: REACT_MEMO_TYPE,
+ type: type,
+ compare: compare === undefined ? null : compare
+ };
+ }
+
+ function resolveDispatcher() {
+ var dispatcher = ReactCurrentDispatcher.current;
+
+ if (!(dispatcher !== null)) {
+ {
+ throw Error( "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem." );
+ }
+ }
+
+ return dispatcher;
+ }
+
+ function useContext(Context, unstable_observedBits) {
+ var dispatcher = resolveDispatcher();
+
+ {
+ if (unstable_observedBits !== undefined) {
+ error('useContext() second argument is reserved for future ' + 'use in React. Passing it is not supported. ' + 'You passed: %s.%s', unstable_observedBits, typeof unstable_observedBits === 'number' && Array.isArray(arguments[2]) ? '\n\nDid you call array.map(useContext)? ' + 'Calling Hooks inside a loop is not supported. ' + 'Learn more at https://fb.me/rules-of-hooks' : '');
+ } // TODO: add a more generic warning for invalid values.
+
+
+ if (Context._context !== undefined) {
+ var realContext = Context._context; // Don't deduplicate because this legitimately causes bugs
+ // and nobody should be using this in existing code.
+
+ if (realContext.Consumer === Context) {
+ error('Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be ' + 'removed in a future major release. Did you mean to call useContext(Context) instead?');
+ } else if (realContext.Provider === Context) {
+ error('Calling useContext(Context.Provider) is not supported. ' + 'Did you mean to call useContext(Context) instead?');
+ }
+ }
+ }
+
+ return dispatcher.useContext(Context, unstable_observedBits);
+ }
+ function useState(initialState) {
+ var dispatcher = resolveDispatcher();
+ return dispatcher.useState(initialState);
+ }
+ function useReducer(reducer, initialArg, init) {
+ var dispatcher = resolveDispatcher();
+ return dispatcher.useReducer(reducer, initialArg, init);
+ }
+ function useRef(initialValue) {
+ var dispatcher = resolveDispatcher();
+ return dispatcher.useRef(initialValue);
+ }
+ function useEffect(create, deps) {
+ var dispatcher = resolveDispatcher();
+ return dispatcher.useEffect(create, deps);
+ }
+ function useLayoutEffect(create, deps) {
+ var dispatcher = resolveDispatcher();
+ return dispatcher.useLayoutEffect(create, deps);
+ }
+ function useCallback(callback, deps) {
+ var dispatcher = resolveDispatcher();
+ return dispatcher.useCallback(callback, deps);
+ }
+ function useMemo(create, deps) {
+ var dispatcher = resolveDispatcher();
+ return dispatcher.useMemo(create, deps);
+ }
+ function useImperativeHandle(ref, create, deps) {
+ var dispatcher = resolveDispatcher();
+ return dispatcher.useImperativeHandle(ref, create, deps);
+ }
+ function useDebugValue(value, formatterFn) {
+ {
+ var dispatcher = resolveDispatcher();
+ return dispatcher.useDebugValue(value, formatterFn);
+ }
+ }
+
+ /**
+ * Copyright (c) 2013-present, Facebook, Inc.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+ var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
+
+ var ReactPropTypesSecret_1 = ReactPropTypesSecret;
+
+ var printWarning$1 = function() {};
+
+ {
+ var ReactPropTypesSecret$1 = ReactPropTypesSecret_1;
+ var loggedTypeFailures = {};
+ var has = Function.call.bind(Object.prototype.hasOwnProperty);
+
+ printWarning$1 = function(text) {
+ var message = 'Warning: ' + text;
+ if (typeof console !== 'undefined') {
+ console.error(message);
+ }
+ try {
+ // --- Welcome to debugging React ---
+ // This error was thrown as a convenience so that you can use this stack
+ // to find the callsite that caused this warning to fire.
+ throw new Error(message);
+ } catch (x) {}
+ };
+ }
+
+ /**
+ * Assert that the values match with the type specs.
+ * Error messages are memorized and will only be shown once.
+ *
+ * @param {object} typeSpecs Map of name to a ReactPropType
+ * @param {object} values Runtime values that need to be type-checked
+ * @param {string} location e.g. "prop", "context", "child context"
+ * @param {string} componentName Name of the component for error messages.
+ * @param {?Function} getStack Returns the component stack.
+ * @private
+ */
+ function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
+ {
+ for (var typeSpecName in typeSpecs) {
+ if (has(typeSpecs, typeSpecName)) {
+ var error;
+ // Prop type validation may throw. In case they do, we don't want to
+ // fail the render phase where it didn't fail before. So we log it.
+ // After these have been cleaned up, we'll let them throw.
+ try {
+ // This is intentionally an invariant that gets caught. It's the same
+ // behavior as without this statement except with a better message.
+ if (typeof typeSpecs[typeSpecName] !== 'function') {
+ var err = Error(
+ (componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' +
+ 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.'
+ );
+ err.name = 'Invariant Violation';
+ throw err;
+ }
+ error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret$1);
+ } catch (ex) {
+ error = ex;
+ }
+ if (error && !(error instanceof Error)) {
+ printWarning$1(
+ (componentName || 'React class') + ': type specification of ' +
+ location + ' `' + typeSpecName + '` is invalid; the type checker ' +
+ 'function must return `null` or an `Error` but returned a ' + typeof error + '. ' +
+ 'You may have forgotten to pass an argument to the type checker ' +
+ 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' +
+ 'shape all require an argument).'
+ );
+ }
+ if (error instanceof Error && !(error.message in loggedTypeFailures)) {
+ // Only monitor this failure once because there tends to be a lot of the
+ // same error.
+ loggedTypeFailures[error.message] = true;
+
+ var stack = getStack ? getStack() : '';
+
+ printWarning$1(
+ 'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '')
+ );
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Resets warning cache when testing.
+ *
+ * @private
+ */
+ checkPropTypes.resetWarningCache = function() {
+ {
+ loggedTypeFailures = {};
+ }
+ };
+
+ var checkPropTypes_1 = checkPropTypes;
+
+ var propTypesMisspellWarningShown;
+
+ {
+ propTypesMisspellWarningShown = false;
+ }
+
+ function getDeclarationErrorAddendum() {
+ if (ReactCurrentOwner.current) {
+ var name = getComponentName(ReactCurrentOwner.current.type);
+
+ if (name) {
+ return '\n\nCheck the render method of `' + name + '`.';
+ }
+ }
+
+ return '';
+ }
+
+ function getSourceInfoErrorAddendum(source) {
+ if (source !== undefined) {
+ var fileName = source.fileName.replace(/^.*[\\\/]/, '');
+ var lineNumber = source.lineNumber;
+ return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.';
+ }
+
+ return '';
+ }
+
+ function getSourceInfoErrorAddendumForProps(elementProps) {
+ if (elementProps !== null && elementProps !== undefined) {
+ return getSourceInfoErrorAddendum(elementProps.__source);
+ }
+
+ return '';
+ }
+ /**
+ * Warn if there's no key explicitly set on dynamic arrays of children or
+ * object keys are not valid. This allows us to keep track of children between
+ * updates.
+ */
+
+
+ var ownerHasKeyUseWarning = {};
+
+ function getCurrentComponentErrorInfo(parentType) {
+ var info = getDeclarationErrorAddendum();
+
+ if (!info) {
+ var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;
+
+ if (parentName) {
+ info = "\n\nCheck the top-level render call using <" + parentName + ">.";
+ }
+ }
+
+ return info;
+ }
+ /**
+ * Warn if the element doesn't have an explicit key assigned to it.
+ * This element is in an array. The array could grow and shrink or be
+ * reordered. All children that haven't already been validated are required to
+ * have a "key" property assigned to it. Error statuses are cached so a warning
+ * will only be shown once.
+ *
+ * @internal
+ * @param {ReactElement} element Element that requires a key.
+ * @param {*} parentType element's parent's type.
+ */
+
+
+ function validateExplicitKey(element, parentType) {
+ if (!element._store || element._store.validated || element.key != null) {
+ return;
+ }
+
+ element._store.validated = true;
+ var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);
+
+ if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
+ return;
+ }
+
+ ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a
+ // property, it may be the creator of the child that's responsible for
+ // assigning it a key.
+
+ var childOwner = '';
+
+ if (element && element._owner && element._owner !== ReactCurrentOwner.current) {
+ // Give the component that originally created this child.
+ childOwner = " It was passed a child from " + getComponentName(element._owner.type) + ".";
+ }
+
+ setCurrentlyValidatingElement(element);
+
+ {
+ error('Each child in a list should have a unique "key" prop.' + '%s%s See https://fb.me/react-warning-keys for more information.', currentComponentErrorInfo, childOwner);
+ }
+
+ setCurrentlyValidatingElement(null);
+ }
+ /**
+ * Ensure that every element either is passed in a static location, in an
+ * array with an explicit keys property defined, or in an object literal
+ * with valid key property.
+ *
+ * @internal
+ * @param {ReactNode} node Statically passed child of any type.
+ * @param {*} parentType node's parent's type.
+ */
+
+
+ function validateChildKeys(node, parentType) {
+ if (typeof node !== 'object') {
+ return;
+ }
+
+ if (Array.isArray(node)) {
+ for (var i = 0; i < node.length; i++) {
+ var child = node[i];
+
+ if (isValidElement(child)) {
+ validateExplicitKey(child, parentType);
+ }
+ }
+ } else if (isValidElement(node)) {
+ // This element was passed in a valid location.
+ if (node._store) {
+ node._store.validated = true;
+ }
+ } else if (node) {
+ var iteratorFn = getIteratorFn(node);
+
+ if (typeof iteratorFn === 'function') {
+ // Entry iterators used to provide implicit keys,
+ // but now we print a separate warning for them later.
+ if (iteratorFn !== node.entries) {
+ var iterator = iteratorFn.call(node);
+ var step;
+
+ while (!(step = iterator.next()).done) {
+ if (isValidElement(step.value)) {
+ validateExplicitKey(step.value, parentType);
+ }
+ }
+ }
+ }
+ }
+ }
+ /**
+ * Given an element, validate that its props follow the propTypes definition,
+ * provided by the type.
+ *
+ * @param {ReactElement} element
+ */
+
+
+ function validatePropTypes(element) {
+ {
+ var type = element.type;
+
+ if (type === null || type === undefined || typeof type === 'string') {
+ return;
+ }
+
+ var name = getComponentName(type);
+ var propTypes;
+
+ if (typeof type === 'function') {
+ propTypes = type.propTypes;
+ } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here.
+ // Inner props are checked in the reconciler.
+ type.$$typeof === REACT_MEMO_TYPE)) {
+ propTypes = type.propTypes;
+ } else {
+ return;
+ }
+
+ if (propTypes) {
+ setCurrentlyValidatingElement(element);
+ checkPropTypes_1(propTypes, element.props, 'prop', name, ReactDebugCurrentFrame.getStackAddendum);
+ setCurrentlyValidatingElement(null);
+ } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) {
+ propTypesMisspellWarningShown = true;
+
+ error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', name || 'Unknown');
+ }
+
+ if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) {
+ error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.');
+ }
+ }
+ }
+ /**
+ * Given a fragment, validate that it can only be provided with fragment props
+ * @param {ReactElement} fragment
+ */
+
+
+ function validateFragmentProps(fragment) {
+ {
+ setCurrentlyValidatingElement(fragment);
+ var keys = Object.keys(fragment.props);
+
+ for (var i = 0; i < keys.length; i++) {
+ var key = keys[i];
+
+ if (key !== 'children' && key !== 'key') {
+ error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key);
+
+ break;
+ }
+ }
+
+ if (fragment.ref !== null) {
+ error('Invalid attribute `ref` supplied to `React.Fragment`.');
+ }
+
+ setCurrentlyValidatingElement(null);
+ }
+ }
+ function createElementWithValidation(type, props, children) {
+ var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to
+ // succeed and there will likely be errors in render.
+
+ if (!validType) {
+ var info = '';
+
+ if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
+ info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports.";
+ }
+
+ var sourceInfo = getSourceInfoErrorAddendumForProps(props);
+
+ if (sourceInfo) {
+ info += sourceInfo;
+ } else {
+ info += getDeclarationErrorAddendum();
+ }
+
+ var typeString;
+
+ if (type === null) {
+ typeString = 'null';
+ } else if (Array.isArray(type)) {
+ typeString = 'array';
+ } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) {
+ typeString = "<" + (getComponentName(type.type) || 'Unknown') + " />";
+ info = ' Did you accidentally export a JSX literal instead of a component?';
+ } else {
+ typeString = typeof type;
+ }
+
+ {
+ error('React.createElement: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info);
+ }
+ }
+
+ var element = createElement.apply(this, arguments); // The result can be nullish if a mock or a custom function is used.
+ // TODO: Drop this when these are no longer allowed as the type argument.
+
+ if (element == null) {
+ return element;
+ } // Skip key warning if the type isn't valid since our key validation logic
+ // doesn't expect a non-string/function type and can throw confusing errors.
+ // We don't want exception behavior to differ between dev and prod.
+ // (Rendering will throw with a helpful message and as soon as the type is
+ // fixed, the key warnings will appear.)
+
+
+ if (validType) {
+ for (var i = 2; i < arguments.length; i++) {
+ validateChildKeys(arguments[i], type);
+ }
+ }
+
+ if (type === REACT_FRAGMENT_TYPE) {
+ validateFragmentProps(element);
+ } else {
+ validatePropTypes(element);
+ }
+
+ return element;
+ }
+ var didWarnAboutDeprecatedCreateFactory = false;
+ function createFactoryWithValidation(type) {
+ var validatedFactory = createElementWithValidation.bind(null, type);
+ validatedFactory.type = type;
+
+ {
+ if (!didWarnAboutDeprecatedCreateFactory) {
+ didWarnAboutDeprecatedCreateFactory = true;
+
+ warn('React.createFactory() is deprecated and will be removed in ' + 'a future major release. Consider using JSX ' + 'or use React.createElement() directly instead.');
+ } // Legacy hook: remove it
+
+
+ Object.defineProperty(validatedFactory, 'type', {
+ enumerable: false,
+ get: function () {
+ warn('Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.');
+
+ Object.defineProperty(this, 'type', {
+ value: type
+ });
+ return type;
+ }
+ });
+ }
+
+ return validatedFactory;
+ }
+ function cloneElementWithValidation(element, props, children) {
+ var newElement = cloneElement.apply(this, arguments);
+
+ for (var i = 2; i < arguments.length; i++) {
+ validateChildKeys(arguments[i], newElement.type);
+ }
+
+ validatePropTypes(newElement);
+ return newElement;
+ }
+
+ var enableSchedulerDebugging = false;
+ var enableProfiling = true;
+
+ var requestHostCallback;
+ var requestHostTimeout;
+ var cancelHostTimeout;
+ var shouldYieldToHost;
+ var requestPaint;
+ var getCurrentTime;
+ var forceFrameRate;
+
+ if ( // If Scheduler runs in a non-DOM environment, it falls back to a naive
+ // implementation using setTimeout.
+ typeof window === 'undefined' || // Check if MessageChannel is supported, too.
+ typeof MessageChannel !== 'function') {
+ // If this accidentally gets imported in a non-browser environment, e.g. JavaScriptCore,
+ // fallback to a naive implementation.
+ var _callback = null;
+ var _timeoutID = null;
+
+ var _flushCallback = function () {
+ if (_callback !== null) {
+ try {
+ var currentTime = getCurrentTime();
+ var hasRemainingTime = true;
+
+ _callback(hasRemainingTime, currentTime);
+
+ _callback = null;
+ } catch (e) {
+ setTimeout(_flushCallback, 0);
+ throw e;
+ }
+ }
+ };
+
+ var initialTime = Date.now();
+
+ getCurrentTime = function () {
+ return Date.now() - initialTime;
+ };
+
+ requestHostCallback = function (cb) {
+ if (_callback !== null) {
+ // Protect against re-entrancy.
+ setTimeout(requestHostCallback, 0, cb);
+ } else {
+ _callback = cb;
+ setTimeout(_flushCallback, 0);
+ }
+ };
+
+ requestHostTimeout = function (cb, ms) {
+ _timeoutID = setTimeout(cb, ms);
+ };
+
+ cancelHostTimeout = function () {
+ clearTimeout(_timeoutID);
+ };
+
+ shouldYieldToHost = function () {
+ return false;
+ };
+
+ requestPaint = forceFrameRate = function () {};
+ } else {
+ // Capture local references to native APIs, in case a polyfill overrides them.
+ var performance = window.performance;
+ var _Date = window.Date;
+ var _setTimeout = window.setTimeout;
+ var _clearTimeout = window.clearTimeout;
+
+ if (typeof console !== 'undefined') {
+ // TODO: Scheduler no longer requires these methods to be polyfilled. But
+ // maybe we want to continue warning if they don't exist, to preserve the
+ // option to rely on it in the future?
+ var requestAnimationFrame = window.requestAnimationFrame;
+ var cancelAnimationFrame = window.cancelAnimationFrame; // TODO: Remove fb.me link
+
+ if (typeof requestAnimationFrame !== 'function') {
+ // Using console['error'] to evade Babel and ESLint
+ console['error']("This browser doesn't support requestAnimationFrame. " + 'Make sure that you load a ' + 'polyfill in older browsers. https://fb.me/react-polyfills');
+ }
+
+ if (typeof cancelAnimationFrame !== 'function') {
+ // Using console['error'] to evade Babel and ESLint
+ console['error']("This browser doesn't support cancelAnimationFrame. " + 'Make sure that you load a ' + 'polyfill in older browsers. https://fb.me/react-polyfills');
+ }
+ }
+
+ if (typeof performance === 'object' && typeof performance.now === 'function') {
+ getCurrentTime = function () {
+ return performance.now();
+ };
+ } else {
+ var _initialTime = _Date.now();
+
+ getCurrentTime = function () {
+ return _Date.now() - _initialTime;
+ };
+ }
+
+ var isMessageLoopRunning = false;
+ var scheduledHostCallback = null;
+ var taskTimeoutID = -1; // Scheduler periodically yields in case there is other work on the main
+ // thread, like user events. By default, it yields multiple times per frame.
+ // It does not attempt to align with frame boundaries, since most tasks don't
+ // need to be frame aligned; for those that do, use requestAnimationFrame.
+
+ var yieldInterval = 5;
+ var deadline = 0; // TODO: Make this configurable
+
+ {
+ // `isInputPending` is not available. Since we have no way of knowing if
+ // there's pending input, always yield at the end of the frame.
+ shouldYieldToHost = function () {
+ return getCurrentTime() >= deadline;
+ }; // Since we yield every frame regardless, `requestPaint` has no effect.
+
+
+ requestPaint = function () {};
+ }
+
+ forceFrameRate = function (fps) {
+ if (fps < 0 || fps > 125) {
+ // Using console['error'] to evade Babel and ESLint
+ console['error']('forceFrameRate takes a positive int between 0 and 125, ' + 'forcing framerates higher than 125 fps is not unsupported');
+ return;
+ }
+
+ if (fps > 0) {
+ yieldInterval = Math.floor(1000 / fps);
+ } else {
+ // reset the framerate
+ yieldInterval = 5;
+ }
+ };
+
+ var performWorkUntilDeadline = function () {
+ if (scheduledHostCallback !== null) {
+ var currentTime = getCurrentTime(); // Yield after `yieldInterval` ms, regardless of where we are in the vsync
+ // cycle. This means there's always time remaining at the beginning of
+ // the message event.
+
+ deadline = currentTime + yieldInterval;
+ var hasTimeRemaining = true;
+
+ try {
+ var hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime);
+
+ if (!hasMoreWork) {
+ isMessageLoopRunning = false;
+ scheduledHostCallback = null;
+ } else {
+ // If there's more work, schedule the next message event at the end
+ // of the preceding one.
+ port.postMessage(null);
+ }
+ } catch (error) {
+ // If a scheduler task throws, exit the current browser task so the
+ // error can be observed.
+ port.postMessage(null);
+ throw error;
+ }
+ } else {
+ isMessageLoopRunning = false;
+ } // Yielding to the browser will give it a chance to paint, so we can
+ };
+
+ var channel = new MessageChannel();
+ var port = channel.port2;
+ channel.port1.onmessage = performWorkUntilDeadline;
+
+ requestHostCallback = function (callback) {
+ scheduledHostCallback = callback;
+
+ if (!isMessageLoopRunning) {
+ isMessageLoopRunning = true;
+ port.postMessage(null);
+ }
+ };
+
+ requestHostTimeout = function (callback, ms) {
+ taskTimeoutID = _setTimeout(function () {
+ callback(getCurrentTime());
+ }, ms);
+ };
+
+ cancelHostTimeout = function () {
+ _clearTimeout(taskTimeoutID);
+
+ taskTimeoutID = -1;
+ };
+ }
+
+ function push(heap, node) {
+ var index = heap.length;
+ heap.push(node);
+ siftUp(heap, node, index);
+ }
+ function peek(heap) {
+ var first = heap[0];
+ return first === undefined ? null : first;
+ }
+ function pop(heap) {
+ var first = heap[0];
+
+ if (first !== undefined) {
+ var last = heap.pop();
+
+ if (last !== first) {
+ heap[0] = last;
+ siftDown(heap, last, 0);
+ }
+
+ return first;
+ } else {
+ return null;
+ }
+ }
+
+ function siftUp(heap, node, i) {
+ var index = i;
+
+ while (true) {
+ var parentIndex = index - 1 >>> 1;
+ var parent = heap[parentIndex];
+
+ if (parent !== undefined && compare(parent, node) > 0) {
+ // The parent is larger. Swap positions.
+ heap[parentIndex] = node;
+ heap[index] = parent;
+ index = parentIndex;
+ } else {
+ // The parent is smaller. Exit.
+ return;
+ }
+ }
+ }
+
+ function siftDown(heap, node, i) {
+ var index = i;
+ var length = heap.length;
+
+ while (index < length) {
+ var leftIndex = (index + 1) * 2 - 1;
+ var left = heap[leftIndex];
+ var rightIndex = leftIndex + 1;
+ var right = heap[rightIndex]; // If the left or right node is smaller, swap with the smaller of those.
+
+ if (left !== undefined && compare(left, node) < 0) {
+ if (right !== undefined && compare(right, left) < 0) {
+ heap[index] = right;
+ heap[rightIndex] = node;
+ index = rightIndex;
+ } else {
+ heap[index] = left;
+ heap[leftIndex] = node;
+ index = leftIndex;
+ }
+ } else if (right !== undefined && compare(right, node) < 0) {
+ heap[index] = right;
+ heap[rightIndex] = node;
+ index = rightIndex;
+ } else {
+ // Neither child is smaller. Exit.
+ return;
+ }
+ }
+ }
+
+ function compare(a, b) {
+ // Compare sort index first, then task id.
+ var diff = a.sortIndex - b.sortIndex;
+ return diff !== 0 ? diff : a.id - b.id;
+ }
+
+ // TODO: Use symbols?
+ var NoPriority = 0;
+ var ImmediatePriority = 1;
+ var UserBlockingPriority = 2;
+ var NormalPriority = 3;
+ var LowPriority = 4;
+ var IdlePriority = 5;
+
+ var runIdCounter = 0;
+ var mainThreadIdCounter = 0;
+ var profilingStateSize = 4;
+ var sharedProfilingBuffer = // $FlowFixMe Flow doesn't know about SharedArrayBuffer
+ typeof SharedArrayBuffer === 'function' ? new SharedArrayBuffer(profilingStateSize * Int32Array.BYTES_PER_ELEMENT) : // $FlowFixMe Flow doesn't know about ArrayBuffer
+ typeof ArrayBuffer === 'function' ? new ArrayBuffer(profilingStateSize * Int32Array.BYTES_PER_ELEMENT) : null // Don't crash the init path on IE9
+ ;
+ var profilingState = sharedProfilingBuffer !== null ? new Int32Array(sharedProfilingBuffer) : []; // We can't read this but it helps save bytes for null checks
+
+ var PRIORITY = 0;
+ var CURRENT_TASK_ID = 1;
+ var CURRENT_RUN_ID = 2;
+ var QUEUE_SIZE = 3;
+
+ {
+ profilingState[PRIORITY] = NoPriority; // This is maintained with a counter, because the size of the priority queue
+ // array might include canceled tasks.
+
+ profilingState[QUEUE_SIZE] = 0;
+ profilingState[CURRENT_TASK_ID] = 0;
+ } // Bytes per element is 4
+
+
+ var INITIAL_EVENT_LOG_SIZE = 131072;
+ var MAX_EVENT_LOG_SIZE = 524288; // Equivalent to 2 megabytes
+
+ var eventLogSize = 0;
+ var eventLogBuffer = null;
+ var eventLog = null;
+ var eventLogIndex = 0;
+ var TaskStartEvent = 1;
+ var TaskCompleteEvent = 2;
+ var TaskErrorEvent = 3;
+ var TaskCancelEvent = 4;
+ var TaskRunEvent = 5;
+ var TaskYieldEvent = 6;
+ var SchedulerSuspendEvent = 7;
+ var SchedulerResumeEvent = 8;
+
+ function logEvent(entries) {
+ if (eventLog !== null) {
+ var offset = eventLogIndex;
+ eventLogIndex += entries.length;
+
+ if (eventLogIndex + 1 > eventLogSize) {
+ eventLogSize *= 2;
+
+ if (eventLogSize > MAX_EVENT_LOG_SIZE) {
+ // Using console['error'] to evade Babel and ESLint
+ console['error']("Scheduler Profiling: Event log exceeded maximum size. Don't " + 'forget to call `stopLoggingProfilingEvents()`.');
+ stopLoggingProfilingEvents();
+ return;
+ }
+
+ var newEventLog = new Int32Array(eventLogSize * 4);
+ newEventLog.set(eventLog);
+ eventLogBuffer = newEventLog.buffer;
+ eventLog = newEventLog;
+ }
+
+ eventLog.set(entries, offset);
+ }
+ }
+
+ function startLoggingProfilingEvents() {
+ eventLogSize = INITIAL_EVENT_LOG_SIZE;
+ eventLogBuffer = new ArrayBuffer(eventLogSize * 4);
+ eventLog = new Int32Array(eventLogBuffer);
+ eventLogIndex = 0;
+ }
+ function stopLoggingProfilingEvents() {
+ var buffer = eventLogBuffer;
+ eventLogSize = 0;
+ eventLogBuffer = null;
+ eventLog = null;
+ eventLogIndex = 0;
+ return buffer;
+ }
+ function markTaskStart(task, ms) {
+ {
+ profilingState[QUEUE_SIZE]++;
+
+ if (eventLog !== null) {
+ // performance.now returns a float, representing milliseconds. When the
+ // event is logged, it's coerced to an int. Convert to microseconds to
+ // maintain extra degrees of precision.
+ logEvent([TaskStartEvent, ms * 1000, task.id, task.priorityLevel]);
+ }
+ }
+ }
+ function markTaskCompleted(task, ms) {
+ {
+ profilingState[PRIORITY] = NoPriority;
+ profilingState[CURRENT_TASK_ID] = 0;
+ profilingState[QUEUE_SIZE]--;
+
+ if (eventLog !== null) {
+ logEvent([TaskCompleteEvent, ms * 1000, task.id]);
+ }
+ }
+ }
+ function markTaskCanceled(task, ms) {
+ {
+ profilingState[QUEUE_SIZE]--;
+
+ if (eventLog !== null) {
+ logEvent([TaskCancelEvent, ms * 1000, task.id]);
+ }
+ }
+ }
+ function markTaskErrored(task, ms) {
+ {
+ profilingState[PRIORITY] = NoPriority;
+ profilingState[CURRENT_TASK_ID] = 0;
+ profilingState[QUEUE_SIZE]--;
+
+ if (eventLog !== null) {
+ logEvent([TaskErrorEvent, ms * 1000, task.id]);
+ }
+ }
+ }
+ function markTaskRun(task, ms) {
+ {
+ runIdCounter++;
+ profilingState[PRIORITY] = task.priorityLevel;
+ profilingState[CURRENT_TASK_ID] = task.id;
+ profilingState[CURRENT_RUN_ID] = runIdCounter;
+
+ if (eventLog !== null) {
+ logEvent([TaskRunEvent, ms * 1000, task.id, runIdCounter]);
+ }
+ }
+ }
+ function markTaskYield(task, ms) {
+ {
+ profilingState[PRIORITY] = NoPriority;
+ profilingState[CURRENT_TASK_ID] = 0;
+ profilingState[CURRENT_RUN_ID] = 0;
+
+ if (eventLog !== null) {
+ logEvent([TaskYieldEvent, ms * 1000, task.id, runIdCounter]);
+ }
+ }
+ }
+ function markSchedulerSuspended(ms) {
+ {
+ mainThreadIdCounter++;
+
+ if (eventLog !== null) {
+ logEvent([SchedulerSuspendEvent, ms * 1000, mainThreadIdCounter]);
+ }
+ }
+ }
+ function markSchedulerUnsuspended(ms) {
+ {
+ if (eventLog !== null) {
+ logEvent([SchedulerResumeEvent, ms * 1000, mainThreadIdCounter]);
+ }
+ }
+ }
+
+ /* eslint-disable no-var */
+ // Math.pow(2, 30) - 1
+ // 0b111111111111111111111111111111
+
+ var maxSigned31BitInt = 1073741823; // Times out immediately
+
+ var IMMEDIATE_PRIORITY_TIMEOUT = -1; // Eventually times out
+
+ var USER_BLOCKING_PRIORITY = 250;
+ var NORMAL_PRIORITY_TIMEOUT = 5000;
+ var LOW_PRIORITY_TIMEOUT = 10000; // Never times out
+
+ var IDLE_PRIORITY = maxSigned31BitInt; // Tasks are stored on a min heap
+
+ var taskQueue = [];
+ var timerQueue = []; // Incrementing id counter. Used to maintain insertion order.
+
+ var taskIdCounter = 1; // Pausing the scheduler is useful for debugging.
+ var currentTask = null;
+ var currentPriorityLevel = NormalPriority; // This is set while performing work, to prevent re-entrancy.
+
+ var isPerformingWork = false;
+ var isHostCallbackScheduled = false;
+ var isHostTimeoutScheduled = false;
+
+ function advanceTimers(currentTime) {
+ // Check for tasks that are no longer delayed and add them to the queue.
+ var timer = peek(timerQueue);
+
+ while (timer !== null) {
+ if (timer.callback === null) {
+ // Timer was cancelled.
+ pop(timerQueue);
+ } else if (timer.startTime <= currentTime) {
+ // Timer fired. Transfer to the task queue.
+ pop(timerQueue);
+ timer.sortIndex = timer.expirationTime;
+ push(taskQueue, timer);
+
+ {
+ markTaskStart(timer, currentTime);
+ timer.isQueued = true;
+ }
+ } else {
+ // Remaining timers are pending.
+ return;
+ }
+
+ timer = peek(timerQueue);
+ }
+ }
+
+ function handleTimeout(currentTime) {
+ isHostTimeoutScheduled = false;
+ advanceTimers(currentTime);
+
+ if (!isHostCallbackScheduled) {
+ if (peek(taskQueue) !== null) {
+ isHostCallbackScheduled = true;
+ requestHostCallback(flushWork);
+ } else {
+ var firstTimer = peek(timerQueue);
+
+ if (firstTimer !== null) {
+ requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
+ }
+ }
+ }
+ }
+
+ function flushWork(hasTimeRemaining, initialTime) {
+ {
+ markSchedulerUnsuspended(initialTime);
+ } // We'll need a host callback the next time work is scheduled.
+
+
+ isHostCallbackScheduled = false;
+
+ if (isHostTimeoutScheduled) {
+ // We scheduled a timeout but it's no longer needed. Cancel it.
+ isHostTimeoutScheduled = false;
+ cancelHostTimeout();
+ }
+
+ isPerformingWork = true;
+ var previousPriorityLevel = currentPriorityLevel;
+
+ try {
+ if (enableProfiling) {
+ try {
+ return workLoop(hasTimeRemaining, initialTime);
+ } catch (error) {
+ if (currentTask !== null) {
+ var currentTime = getCurrentTime();
+ markTaskErrored(currentTask, currentTime);
+ currentTask.isQueued = false;
+ }
+
+ throw error;
+ }
+ } else {
+ // No catch in prod codepath.
+ return workLoop(hasTimeRemaining, initialTime);
+ }
+ } finally {
+ currentTask = null;
+ currentPriorityLevel = previousPriorityLevel;
+ isPerformingWork = false;
+
+ {
+ var _currentTime = getCurrentTime();
+
+ markSchedulerSuspended(_currentTime);
+ }
+ }
+ }
+
+ function workLoop(hasTimeRemaining, initialTime) {
+ var currentTime = initialTime;
+ advanceTimers(currentTime);
+ currentTask = peek(taskQueue);
+
+ while (currentTask !== null && !(enableSchedulerDebugging )) {
+ if (currentTask.expirationTime > currentTime && (!hasTimeRemaining || shouldYieldToHost())) {
+ // This currentTask hasn't expired, and we've reached the deadline.
+ break;
+ }
+
+ var callback = currentTask.callback;
+
+ if (callback !== null) {
+ currentTask.callback = null;
+ currentPriorityLevel = currentTask.priorityLevel;
+ var didUserCallbackTimeout = currentTask.expirationTime <= currentTime;
+ markTaskRun(currentTask, currentTime);
+ var continuationCallback = callback(didUserCallbackTimeout);
+ currentTime = getCurrentTime();
+
+ if (typeof continuationCallback === 'function') {
+ currentTask.callback = continuationCallback;
+ markTaskYield(currentTask, currentTime);
+ } else {
+ {
+ markTaskCompleted(currentTask, currentTime);
+ currentTask.isQueued = false;
+ }
+
+ if (currentTask === peek(taskQueue)) {
+ pop(taskQueue);
+ }
+ }
+
+ advanceTimers(currentTime);
+ } else {
+ pop(taskQueue);
+ }
+
+ currentTask = peek(taskQueue);
+ } // Return whether there's additional work
+
+
+ if (currentTask !== null) {
+ return true;
+ } else {
+ var firstTimer = peek(timerQueue);
+
+ if (firstTimer !== null) {
+ requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
+ }
+
+ return false;
+ }
+ }
+
+ function unstable_runWithPriority(priorityLevel, eventHandler) {
+ switch (priorityLevel) {
+ case ImmediatePriority:
+ case UserBlockingPriority:
+ case NormalPriority:
+ case LowPriority:
+ case IdlePriority:
+ break;
+
+ default:
+ priorityLevel = NormalPriority;
+ }
+
+ var previousPriorityLevel = currentPriorityLevel;
+ currentPriorityLevel = priorityLevel;
+
+ try {
+ return eventHandler();
+ } finally {
+ currentPriorityLevel = previousPriorityLevel;
+ }
+ }
+
+ function unstable_next(eventHandler) {
+ var priorityLevel;
+
+ switch (currentPriorityLevel) {
+ case ImmediatePriority:
+ case UserBlockingPriority:
+ case NormalPriority:
+ // Shift down to normal priority
+ priorityLevel = NormalPriority;
+ break;
+
+ default:
+ // Anything lower than normal priority should remain at the current level.
+ priorityLevel = currentPriorityLevel;
+ break;
+ }
+
+ var previousPriorityLevel = currentPriorityLevel;
+ currentPriorityLevel = priorityLevel;
+
+ try {
+ return eventHandler();
+ } finally {
+ currentPriorityLevel = previousPriorityLevel;
+ }
+ }
+
+ function unstable_wrapCallback(callback) {
+ var parentPriorityLevel = currentPriorityLevel;
+ return function () {
+ // This is a fork of runWithPriority, inlined for performance.
+ var previousPriorityLevel = currentPriorityLevel;
+ currentPriorityLevel = parentPriorityLevel;
+
+ try {
+ return callback.apply(this, arguments);
+ } finally {
+ currentPriorityLevel = previousPriorityLevel;
+ }
+ };
+ }
+
+ function timeoutForPriorityLevel(priorityLevel) {
+ switch (priorityLevel) {
+ case ImmediatePriority:
+ return IMMEDIATE_PRIORITY_TIMEOUT;
+
+ case UserBlockingPriority:
+ return USER_BLOCKING_PRIORITY;
+
+ case IdlePriority:
+ return IDLE_PRIORITY;
+
+ case LowPriority:
+ return LOW_PRIORITY_TIMEOUT;
+
+ case NormalPriority:
+ default:
+ return NORMAL_PRIORITY_TIMEOUT;
+ }
+ }
+
+ function unstable_scheduleCallback(priorityLevel, callback, options) {
+ var currentTime = getCurrentTime();
+ var startTime;
+ var timeout;
+
+ if (typeof options === 'object' && options !== null) {
+ var delay = options.delay;
+
+ if (typeof delay === 'number' && delay > 0) {
+ startTime = currentTime + delay;
+ } else {
+ startTime = currentTime;
+ }
+
+ timeout = typeof options.timeout === 'number' ? options.timeout : timeoutForPriorityLevel(priorityLevel);
+ } else {
+ timeout = timeoutForPriorityLevel(priorityLevel);
+ startTime = currentTime;
+ }
+
+ var expirationTime = startTime + timeout;
+ var newTask = {
+ id: taskIdCounter++,
+ callback: callback,
+ priorityLevel: priorityLevel,
+ startTime: startTime,
+ expirationTime: expirationTime,
+ sortIndex: -1
+ };
+
+ {
+ newTask.isQueued = false;
+ }
+
+ if (startTime > currentTime) {
+ // This is a delayed task.
+ newTask.sortIndex = startTime;
+ push(timerQueue, newTask);
+
+ if (peek(taskQueue) === null && newTask === peek(timerQueue)) {
+ // All tasks are delayed, and this is the task with the earliest delay.
+ if (isHostTimeoutScheduled) {
+ // Cancel an existing timeout.
+ cancelHostTimeout();
+ } else {
+ isHostTimeoutScheduled = true;
+ } // Schedule a timeout.
+
+
+ requestHostTimeout(handleTimeout, startTime - currentTime);
+ }
+ } else {
+ newTask.sortIndex = expirationTime;
+ push(taskQueue, newTask);
+
+ {
+ markTaskStart(newTask, currentTime);
+ newTask.isQueued = true;
+ } // Schedule a host callback, if needed. If we're already performing work,
+ // wait until the next time we yield.
+
+
+ if (!isHostCallbackScheduled && !isPerformingWork) {
+ isHostCallbackScheduled = true;
+ requestHostCallback(flushWork);
+ }
+ }
+
+ return newTask;
+ }
+
+ function unstable_pauseExecution() {
+ }
+
+ function unstable_continueExecution() {
+
+ if (!isHostCallbackScheduled && !isPerformingWork) {
+ isHostCallbackScheduled = true;
+ requestHostCallback(flushWork);
+ }
+ }
+
+ function unstable_getFirstCallbackNode() {
+ return peek(taskQueue);
+ }
+
+ function unstable_cancelCallback(task) {
+ {
+ if (task.isQueued) {
+ var currentTime = getCurrentTime();
+ markTaskCanceled(task, currentTime);
+ task.isQueued = false;
+ }
+ } // Null out the callback to indicate the task has been canceled. (Can't
+ // remove from the queue because you can't remove arbitrary nodes from an
+ // array based heap, only the first one.)
+
+
+ task.callback = null;
+ }
+
+ function unstable_getCurrentPriorityLevel() {
+ return currentPriorityLevel;
+ }
+
+ function unstable_shouldYield() {
+ var currentTime = getCurrentTime();
+ advanceTimers(currentTime);
+ var firstTask = peek(taskQueue);
+ return firstTask !== currentTask && currentTask !== null && firstTask !== null && firstTask.callback !== null && firstTask.startTime <= currentTime && firstTask.expirationTime < currentTask.expirationTime || shouldYieldToHost();
+ }
+
+ var unstable_requestPaint = requestPaint;
+ var unstable_Profiling = {
+ startLoggingProfilingEvents: startLoggingProfilingEvents,
+ stopLoggingProfilingEvents: stopLoggingProfilingEvents,
+ sharedProfilingBuffer: sharedProfilingBuffer
+ } ;
+
+
+
+ var Scheduler = /*#__PURE__*/Object.freeze({
+ __proto__: null,
+ unstable_ImmediatePriority: ImmediatePriority,
+ unstable_UserBlockingPriority: UserBlockingPriority,
+ unstable_NormalPriority: NormalPriority,
+ unstable_IdlePriority: IdlePriority,
+ unstable_LowPriority: LowPriority,
+ unstable_runWithPriority: unstable_runWithPriority,
+ unstable_next: unstable_next,
+ unstable_scheduleCallback: unstable_scheduleCallback,
+ unstable_cancelCallback: unstable_cancelCallback,
+ unstable_wrapCallback: unstable_wrapCallback,
+ unstable_getCurrentPriorityLevel: unstable_getCurrentPriorityLevel,
+ unstable_shouldYield: unstable_shouldYield,
+ unstable_requestPaint: unstable_requestPaint,
+ unstable_continueExecution: unstable_continueExecution,
+ unstable_pauseExecution: unstable_pauseExecution,
+ unstable_getFirstCallbackNode: unstable_getFirstCallbackNode,
+ get unstable_now () { return getCurrentTime; },
+ get unstable_forceFrameRate () { return forceFrameRate; },
+ unstable_Profiling: unstable_Profiling
+ });
+
+ var DEFAULT_THREAD_ID = 0; // Counters used to generate unique IDs.
+
+ var interactionIDCounter = 0;
+ var threadIDCounter = 0; // Set of currently traced interactions.
+ // Interactions "stack"–
+ // Meaning that newly traced interactions are appended to the previously active set.
+ // When an interaction goes out of scope, the previous set (if any) is restored.
+
+ var interactionsRef = null; // Listener(s) to notify when interactions begin and end.
+
+ var subscriberRef = null;
+
+ {
+ interactionsRef = {
+ current: new Set()
+ };
+ subscriberRef = {
+ current: null
+ };
+ }
+ function unstable_clear(callback) {
+
+ var prevInteractions = interactionsRef.current;
+ interactionsRef.current = new Set();
+
+ try {
+ return callback();
+ } finally {
+ interactionsRef.current = prevInteractions;
+ }
+ }
+ function unstable_getCurrent() {
+ {
+ return interactionsRef.current;
+ }
+ }
+ function unstable_getThreadID() {
+ return ++threadIDCounter;
+ }
+ function unstable_trace(name, timestamp, callback) {
+ var threadID = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : DEFAULT_THREAD_ID;
+
+ var interaction = {
+ __count: 1,
+ id: interactionIDCounter++,
+ name: name,
+ timestamp: timestamp
+ };
+ var prevInteractions = interactionsRef.current; // Traced interactions should stack/accumulate.
+ // To do that, clone the current interactions.
+ // The previous set will be restored upon completion.
+
+ var interactions = new Set(prevInteractions);
+ interactions.add(interaction);
+ interactionsRef.current = interactions;
+ var subscriber = subscriberRef.current;
+ var returnValue;
+
+ try {
+ if (subscriber !== null) {
+ subscriber.onInteractionTraced(interaction);
+ }
+ } finally {
+ try {
+ if (subscriber !== null) {
+ subscriber.onWorkStarted(interactions, threadID);
+ }
+ } finally {
+ try {
+ returnValue = callback();
+ } finally {
+ interactionsRef.current = prevInteractions;
+
+ try {
+ if (subscriber !== null) {
+ subscriber.onWorkStopped(interactions, threadID);
+ }
+ } finally {
+ interaction.__count--; // If no async work was scheduled for this interaction,
+ // Notify subscribers that it's completed.
+
+ if (subscriber !== null && interaction.__count === 0) {
+ subscriber.onInteractionScheduledWorkCompleted(interaction);
+ }
+ }
+ }
+ }
+ }
+
+ return returnValue;
+ }
+ function unstable_wrap(callback) {
+ var threadID = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_THREAD_ID;
+
+ var wrappedInteractions = interactionsRef.current;
+ var subscriber = subscriberRef.current;
+
+ if (subscriber !== null) {
+ subscriber.onWorkScheduled(wrappedInteractions, threadID);
+ } // Update the pending async work count for the current interactions.
+ // Update after calling subscribers in case of error.
+
+
+ wrappedInteractions.forEach(function (interaction) {
+ interaction.__count++;
+ });
+ var hasRun = false;
+
+ function wrapped() {
+ var prevInteractions = interactionsRef.current;
+ interactionsRef.current = wrappedInteractions;
+ subscriber = subscriberRef.current;
+
+ try {
+ var returnValue;
+
+ try {
+ if (subscriber !== null) {
+ subscriber.onWorkStarted(wrappedInteractions, threadID);
+ }
+ } finally {
+ try {
+ returnValue = callback.apply(undefined, arguments);
+ } finally {
+ interactionsRef.current = prevInteractions;
+
+ if (subscriber !== null) {
+ subscriber.onWorkStopped(wrappedInteractions, threadID);
+ }
+ }
+ }
+
+ return returnValue;
+ } finally {
+ if (!hasRun) {
+ // We only expect a wrapped function to be executed once,
+ // But in the event that it's executed more than once–
+ // Only decrement the outstanding interaction counts once.
+ hasRun = true; // Update pending async counts for all wrapped interactions.
+ // If this was the last scheduled async work for any of them,
+ // Mark them as completed.
+
+ wrappedInteractions.forEach(function (interaction) {
+ interaction.__count--;
+
+ if (subscriber !== null && interaction.__count === 0) {
+ subscriber.onInteractionScheduledWorkCompleted(interaction);
+ }
+ });
+ }
+ }
+ }
+
+ wrapped.cancel = function cancel() {
+ subscriber = subscriberRef.current;
+
+ try {
+ if (subscriber !== null) {
+ subscriber.onWorkCanceled(wrappedInteractions, threadID);
+ }
+ } finally {
+ // Update pending async counts for all wrapped interactions.
+ // If this was the last scheduled async work for any of them,
+ // Mark them as completed.
+ wrappedInteractions.forEach(function (interaction) {
+ interaction.__count--;
+
+ if (subscriber && interaction.__count === 0) {
+ subscriber.onInteractionScheduledWorkCompleted(interaction);
+ }
+ });
+ }
+ };
+
+ return wrapped;
+ }
+
+ var subscribers = null;
+
+ {
+ subscribers = new Set();
+ }
+
+ function unstable_subscribe(subscriber) {
+ {
+ subscribers.add(subscriber);
+
+ if (subscribers.size === 1) {
+ subscriberRef.current = {
+ onInteractionScheduledWorkCompleted: onInteractionScheduledWorkCompleted,
+ onInteractionTraced: onInteractionTraced,
+ onWorkCanceled: onWorkCanceled,
+ onWorkScheduled: onWorkScheduled,
+ onWorkStarted: onWorkStarted,
+ onWorkStopped: onWorkStopped
+ };
+ }
+ }
+ }
+ function unstable_unsubscribe(subscriber) {
+ {
+ subscribers.delete(subscriber);
+
+ if (subscribers.size === 0) {
+ subscriberRef.current = null;
+ }
+ }
+ }
+
+ function onInteractionTraced(interaction) {
+ var didCatchError = false;
+ var caughtError = null;
+ subscribers.forEach(function (subscriber) {
+ try {
+ subscriber.onInteractionTraced(interaction);
+ } catch (error) {
+ if (!didCatchError) {
+ didCatchError = true;
+ caughtError = error;
+ }
+ }
+ });
+
+ if (didCatchError) {
+ throw caughtError;
+ }
+ }
+
+ function onInteractionScheduledWorkCompleted(interaction) {
+ var didCatchError = false;
+ var caughtError = null;
+ subscribers.forEach(function (subscriber) {
+ try {
+ subscriber.onInteractionScheduledWorkCompleted(interaction);
+ } catch (error) {
+ if (!didCatchError) {
+ didCatchError = true;
+ caughtError = error;
+ }
+ }
+ });
+
+ if (didCatchError) {
+ throw caughtError;
+ }
+ }
+
+ function onWorkScheduled(interactions, threadID) {
+ var didCatchError = false;
+ var caughtError = null;
+ subscribers.forEach(function (subscriber) {
+ try {
+ subscriber.onWorkScheduled(interactions, threadID);
+ } catch (error) {
+ if (!didCatchError) {
+ didCatchError = true;
+ caughtError = error;
+ }
+ }
+ });
+
+ if (didCatchError) {
+ throw caughtError;
+ }
+ }
+
+ function onWorkStarted(interactions, threadID) {
+ var didCatchError = false;
+ var caughtError = null;
+ subscribers.forEach(function (subscriber) {
+ try {
+ subscriber.onWorkStarted(interactions, threadID);
+ } catch (error) {
+ if (!didCatchError) {
+ didCatchError = true;
+ caughtError = error;
+ }
+ }
+ });
+
+ if (didCatchError) {
+ throw caughtError;
+ }
+ }
+
+ function onWorkStopped(interactions, threadID) {
+ var didCatchError = false;
+ var caughtError = null;
+ subscribers.forEach(function (subscriber) {
+ try {
+ subscriber.onWorkStopped(interactions, threadID);
+ } catch (error) {
+ if (!didCatchError) {
+ didCatchError = true;
+ caughtError = error;
+ }
+ }
+ });
+
+ if (didCatchError) {
+ throw caughtError;
+ }
+ }
+
+ function onWorkCanceled(interactions, threadID) {
+ var didCatchError = false;
+ var caughtError = null;
+ subscribers.forEach(function (subscriber) {
+ try {
+ subscriber.onWorkCanceled(interactions, threadID);
+ } catch (error) {
+ if (!didCatchError) {
+ didCatchError = true;
+ caughtError = error;
+ }
+ }
+ });
+
+ if (didCatchError) {
+ throw caughtError;
+ }
+ }
+
+
+
+ var SchedulerTracing = /*#__PURE__*/Object.freeze({
+ __proto__: null,
+ get __interactionsRef () { return interactionsRef; },
+ get __subscriberRef () { return subscriberRef; },
+ unstable_clear: unstable_clear,
+ unstable_getCurrent: unstable_getCurrent,
+ unstable_getThreadID: unstable_getThreadID,
+ unstable_trace: unstable_trace,
+ unstable_wrap: unstable_wrap,
+ unstable_subscribe: unstable_subscribe,
+ unstable_unsubscribe: unstable_unsubscribe
+ });
+
+ var ReactSharedInternals$1 = {
+ ReactCurrentDispatcher: ReactCurrentDispatcher,
+ ReactCurrentOwner: ReactCurrentOwner,
+ IsSomeRendererActing: IsSomeRendererActing,
+ // Used by renderers to avoid bundling object-assign twice in UMD bundles:
+ assign: objectAssign
+ };
+
+ {
+ objectAssign(ReactSharedInternals$1, {
+ // These should not be included in production.
+ ReactDebugCurrentFrame: ReactDebugCurrentFrame,
+ // Shim for React DOM 16.0.0 which still destructured (but not used) this.
+ // TODO: remove in React 17.0.
+ ReactComponentTreeHook: {}
+ });
+ } // Re-export the schedule API(s) for UMD bundles.
+ // This avoids introducing a dependency on a new UMD global in a minor update,
+ // Since that would be a breaking change (e.g. for all existing CodeSandboxes).
+ // This re-export is only required for UMD bundles;
+ // CJS bundles use the shared NPM package.
+
+
+ objectAssign(ReactSharedInternals$1, {
+ Scheduler: Scheduler,
+ SchedulerTracing: SchedulerTracing
+ });
+
+ {
+
+ try {
+ var frozenObject = Object.freeze({});
+ var testMap = new Map([[frozenObject, null]]);
+ var testSet = new Set([frozenObject]); // This is necessary for Rollup to not consider these unused.
+ // https://github.com/rollup/rollup/issues/1771
+ // TODO: we can remove these if Rollup fixes the bug.
+
+ testMap.set(0, 0);
+ testSet.add(0);
+ } catch (e) {
+ }
+ }
+
+ var createElement$1 = createElementWithValidation ;
+ var cloneElement$1 = cloneElementWithValidation ;
+ var createFactory = createFactoryWithValidation ;
+ var Children = {
+ map: mapChildren,
+ forEach: forEachChildren,
+ count: countChildren,
+ toArray: toArray,
+ only: onlyChild
+ };
+
+ exports.Children = Children;
+ exports.Component = Component;
+ exports.Fragment = REACT_FRAGMENT_TYPE;
+ exports.Profiler = REACT_PROFILER_TYPE;
+ exports.PureComponent = PureComponent;
+ exports.StrictMode = REACT_STRICT_MODE_TYPE;
+ exports.Suspense = REACT_SUSPENSE_TYPE;
+ exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactSharedInternals$1;
+ exports.cloneElement = cloneElement$1;
+ exports.createContext = createContext;
+ exports.createElement = createElement$1;
+ exports.createFactory = createFactory;
+ exports.createRef = createRef;
+ exports.forwardRef = forwardRef;
+ exports.isValidElement = isValidElement;
+ exports.lazy = lazy;
+ exports.memo = memo;
+ exports.useCallback = useCallback;
+ exports.useContext = useContext;
+ exports.useDebugValue = useDebugValue;
+ exports.useEffect = useEffect;
+ exports.useImperativeHandle = useImperativeHandle;
+ exports.useLayoutEffect = useLayoutEffect;
+ exports.useMemo = useMemo;
+ exports.useReducer = useReducer;
+ exports.useRef = useRef;
+ exports.useState = useState;
+ exports.version = ReactVersion;
+
+})));
diff --git a/browser/components/newtab/vendor/react-dom-dev.js b/browser/components/newtab/vendor/react-dom-dev.js
new file mode 100644
index 0000000000..2bc860246f
--- /dev/null
+++ b/browser/components/newtab/vendor/react-dom-dev.js
@@ -0,0 +1,25147 @@
+/** @license React v16.13.1
+ * react-dom.development.js
+ *
+ * Copyright (c) Facebook, Inc. and its affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+'use strict';
+
+(function (global, factory) {
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) :
+ typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) :
+ (global = global || self, factory(global.ReactDOM = {}, global.React));
+}(this, (function (exports, React) { 'use strict';
+
+ var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; // Prevent newer renderers from RTE when used with older react package versions.
+ // Current owner and dispatcher used to share the same ref,
+ // but PR #14548 split them out to better support the react-debug-tools package.
+
+ if (!ReactSharedInternals.hasOwnProperty('ReactCurrentDispatcher')) {
+ ReactSharedInternals.ReactCurrentDispatcher = {
+ current: null
+ };
+ }
+
+ if (!ReactSharedInternals.hasOwnProperty('ReactCurrentBatchConfig')) {
+ ReactSharedInternals.ReactCurrentBatchConfig = {
+ suspense: null
+ };
+ }
+
+ // by calls to these methods by a Babel plugin.
+ //
+ // In PROD (or in packages without access to React internals),
+ // they are left as they are instead.
+
+ function warn(format) {
+ {
+ for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
+ args[_key - 1] = arguments[_key];
+ }
+
+ printWarning('warn', format, args);
+ }
+ }
+ function error(format) {
+ {
+ for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
+ args[_key2 - 1] = arguments[_key2];
+ }
+
+ printWarning('error', format, args);
+ }
+ }
+
+ function printWarning(level, format, args) {
+ // When changing this logic, you might want to also
+ // update consoleWithStackDev.www.js as well.
+ {
+ var hasExistingStack = args.length > 0 && typeof args[args.length - 1] === 'string' && args[args.length - 1].indexOf('\n in') === 0;
+
+ if (!hasExistingStack) {
+ var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
+ var stack = ReactDebugCurrentFrame.getStackAddendum();
+
+ if (stack !== '') {
+ format += '%s';
+ args = args.concat([stack]);
+ }
+ }
+
+ var argsWithFormat = args.map(function (item) {
+ return '' + item;
+ }); // Careful: RN currently depends on this prefix
+
+ argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
+ // breaks IE9: https://github.com/facebook/react/issues/13610
+ // eslint-disable-next-line react-internal/no-production-logging
+
+ Function.prototype.apply.call(console[level], console, argsWithFormat);
+
+ try {
+ // --- Welcome to debugging React ---
+ // This error was thrown as a convenience so that you can use this stack
+ // to find the callsite that caused this warning to fire.
+ var argIndex = 0;
+ var message = 'Warning: ' + format.replace(/%s/g, function () {
+ return args[argIndex++];
+ });
+ throw new Error(message);
+ } catch (x) {}
+ }
+ }
+
+ if (!React) {
+ {
+ throw Error( "ReactDOM was loaded before React. Make sure you load the React package before loading ReactDOM." );
+ }
+ }
+
+ var invokeGuardedCallbackImpl = function (name, func, context, a, b, c, d, e, f) {
+ var funcArgs = Array.prototype.slice.call(arguments, 3);
+
+ try {
+ func.apply(context, funcArgs);
+ } catch (error) {
+ this.onError(error);
+ }
+ };
+
+ {
+ // In DEV mode, we swap out invokeGuardedCallback for a special version
+ // that plays more nicely with the browser's DevTools. The idea is to preserve
+ // "Pause on exceptions" behavior. Because React wraps all user-provided
+ // functions in invokeGuardedCallback, and the production version of
+ // invokeGuardedCallback uses a try-catch, all user exceptions are treated
+ // like caught exceptions, and the DevTools won't pause unless the developer
+ // takes the extra step of enabling pause on caught exceptions. This is
+ // unintuitive, though, because even though React has caught the error, from
+ // the developer's perspective, the error is uncaught.
+ //
+ // To preserve the expected "Pause on exceptions" behavior, we don't use a
+ // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake
+ // DOM node, and call the user-provided callback from inside an event handler
+ // for that fake event. If the callback throws, the error is "captured" using
+ // a global event handler. But because the error happens in a different
+ // event loop context, it does not interrupt the normal program flow.
+ // Effectively, this gives us try-catch behavior without actually using
+ // try-catch. Neat!
+ // Check that the browser supports the APIs we need to implement our special
+ // DEV version of invokeGuardedCallback
+ if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') {
+ var fakeNode = document.createElement('react');
+
+ var invokeGuardedCallbackDev = function (name, func, context, a, b, c, d, e, f) {
+ // If document doesn't exist we know for sure we will crash in this method
+ // when we call document.createEvent(). However this can cause confusing
+ // errors: https://github.com/facebookincubator/create-react-app/issues/3482
+ // So we preemptively throw with a better message instead.
+ if (!(typeof document !== 'undefined')) {
+ {
+ throw Error( "The `document` global was defined when React was initialized, but is not defined anymore. This can happen in a test environment if a component schedules an update from an asynchronous callback, but the test has already finished running. To solve this, you can either unmount the component at the end of your test (and ensure that any asynchronous operations get canceled in `componentWillUnmount`), or you can change the test itself to be asynchronous." );
+ }
+ }
+
+ var evt = document.createEvent('Event'); // Keeps track of whether the user-provided callback threw an error. We
+ // set this to true at the beginning, then set it to false right after
+ // calling the function. If the function errors, `didError` will never be
+ // set to false. This strategy works even if the browser is flaky and
+ // fails to call our global error handler, because it doesn't rely on
+ // the error event at all.
+
+ var didError = true; // Keeps track of the value of window.event so that we can reset it
+ // during the callback to let user code access window.event in the
+ // browsers that support it.
+
+ var windowEvent = window.event; // Keeps track of the descriptor of window.event to restore it after event
+ // dispatching: https://github.com/facebook/react/issues/13688
+
+ var windowEventDescriptor = Object.getOwnPropertyDescriptor(window, 'event'); // Create an event handler for our fake event. We will synchronously
+ // dispatch our fake event using `dispatchEvent`. Inside the handler, we
+ // call the user-provided callback.
+
+ var funcArgs = Array.prototype.slice.call(arguments, 3);
+
+ function callCallback() {
+ // We immediately remove the callback from event listeners so that
+ // nested `invokeGuardedCallback` calls do not clash. Otherwise, a
+ // nested call would trigger the fake event handlers of any call higher
+ // in the stack.
+ fakeNode.removeEventListener(evtType, callCallback, false); // We check for window.hasOwnProperty('event') to prevent the
+ // window.event assignment in both IE <= 10 as they throw an error
+ // "Member not found" in strict mode, and in Firefox which does not
+ // support window.event.
+
+ if (typeof window.event !== 'undefined' && window.hasOwnProperty('event')) {
+ window.event = windowEvent;
+ }
+
+ func.apply(context, funcArgs);
+ didError = false;
+ } // Create a global error event handler. We use this to capture the value
+ // that was thrown. It's possible that this error handler will fire more
+ // than once; for example, if non-React code also calls `dispatchEvent`
+ // and a handler for that event throws. We should be resilient to most of
+ // those cases. Even if our error event handler fires more than once, the
+ // last error event is always used. If the callback actually does error,
+ // we know that the last error event is the correct one, because it's not
+ // possible for anything else to have happened in between our callback
+ // erroring and the code that follows the `dispatchEvent` call below. If
+ // the callback doesn't error, but the error event was fired, we know to
+ // ignore it because `didError` will be false, as described above.
+
+
+ var error; // Use this to track whether the error event is ever called.
+
+ var didSetError = false;
+ var isCrossOriginError = false;
+
+ function handleWindowError(event) {
+ error = event.error;
+ didSetError = true;
+
+ if (error === null && event.colno === 0 && event.lineno === 0) {
+ isCrossOriginError = true;
+ }
+
+ if (event.defaultPrevented) {
+ // Some other error handler has prevented default.
+ // Browsers silence the error report if this happens.
+ // We'll remember this to later decide whether to log it or not.
+ if (error != null && typeof error === 'object') {
+ try {
+ error._suppressLogging = true;
+ } catch (inner) {// Ignore.
+ }
+ }
+ }
+ } // Create a fake event type.
+
+
+ var evtType = "react-" + (name ? name : 'invokeguardedcallback'); // Attach our event handlers
+
+ window.addEventListener('error', handleWindowError);
+ fakeNode.addEventListener(evtType, callCallback, false); // Synchronously dispatch our fake event. If the user-provided function
+ // errors, it will trigger our global error handler.
+
+ evt.initEvent(evtType, false, false);
+ fakeNode.dispatchEvent(evt);
+
+ if (windowEventDescriptor) {
+ Object.defineProperty(window, 'event', windowEventDescriptor);
+ }
+
+ if (didError) {
+ if (!didSetError) {
+ // The callback errored, but the error event never fired.
+ error = new Error('An error was thrown inside one of your components, but React ' + "doesn't know what it was. This is likely due to browser " + 'flakiness. React does its best to preserve the "Pause on ' + 'exceptions" behavior of the DevTools, which requires some ' + "DEV-mode only tricks. It's possible that these don't work in " + 'your browser. Try triggering the error in production mode, ' + 'or switching to a modern browser. If you suspect that this is ' + 'actually an issue with React, please file an issue.');
+ } else if (isCrossOriginError) {
+ error = new Error("A cross-origin error was thrown. React doesn't have access to " + 'the actual error object in development. ' + 'See https://fb.me/react-crossorigin-error for more information.');
+ }
+
+ this.onError(error);
+ } // Remove our event listeners
+
+
+ window.removeEventListener('error', handleWindowError);
+ };
+
+ invokeGuardedCallbackImpl = invokeGuardedCallbackDev;
+ }
+ }
+
+ var invokeGuardedCallbackImpl$1 = invokeGuardedCallbackImpl;
+
+ var hasError = false;
+ var caughtError = null; // Used by event system to capture/rethrow the first error.
+
+ var hasRethrowError = false;
+ var rethrowError = null;
+ var reporter = {
+ onError: function (error) {
+ hasError = true;
+ caughtError = error;
+ }
+ };
+ /**
+ * Call a function while guarding against errors that happens within it.
+ * Returns an error if it throws, otherwise null.
+ *
+ * In production, this is implemented using a try-catch. The reason we don't
+ * use a try-catch directly is so that we can swap out a different
+ * implementation in DEV mode.
+ *
+ * @param {String} name of the guard to use for logging or debugging
+ * @param {Function} func The function to invoke
+ * @param {*} context The context to use when calling the function
+ * @param {...*} args Arguments for function
+ */
+
+ function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) {
+ hasError = false;
+ caughtError = null;
+ invokeGuardedCallbackImpl$1.apply(reporter, arguments);
+ }
+ /**
+ * Same as invokeGuardedCallback, but instead of returning an error, it stores
+ * it in a global so it can be rethrown by `rethrowCaughtError` later.
+ * TODO: See if caughtError and rethrowError can be unified.
+ *
+ * @param {String} name of the guard to use for logging or debugging
+ * @param {Function} func The function to invoke
+ * @param {*} context The context to use when calling the function
+ * @param {...*} args Arguments for function
+ */
+
+ function invokeGuardedCallbackAndCatchFirstError(name, func, context, a, b, c, d, e, f) {
+ invokeGuardedCallback.apply(this, arguments);
+
+ if (hasError) {
+ var error = clearCaughtError();
+
+ if (!hasRethrowError) {
+ hasRethrowError = true;
+ rethrowError = error;
+ }
+ }
+ }
+ /**
+ * During execution of guarded functions we will capture the first error which
+ * we will rethrow to be handled by the top level error handler.
+ */
+
+ function rethrowCaughtError() {
+ if (hasRethrowError) {
+ var error = rethrowError;
+ hasRethrowError = false;
+ rethrowError = null;
+ throw error;
+ }
+ }
+ function hasCaughtError() {
+ return hasError;
+ }
+ function clearCaughtError() {
+ if (hasError) {
+ var error = caughtError;
+ hasError = false;
+ caughtError = null;
+ return error;
+ } else {
+ {
+ {
+ throw Error( "clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue." );
+ }
+ }
+ }
+ }
+
+ var getFiberCurrentPropsFromNode = null;
+ var getInstanceFromNode = null;
+ var getNodeFromInstance = null;
+ function setComponentTree(getFiberCurrentPropsFromNodeImpl, getInstanceFromNodeImpl, getNodeFromInstanceImpl) {
+ getFiberCurrentPropsFromNode = getFiberCurrentPropsFromNodeImpl;
+ getInstanceFromNode = getInstanceFromNodeImpl;
+ getNodeFromInstance = getNodeFromInstanceImpl;
+
+ {
+ if (!getNodeFromInstance || !getInstanceFromNode) {
+ error('EventPluginUtils.setComponentTree(...): Injected ' + 'module is missing getNodeFromInstance or getInstanceFromNode.');
+ }
+ }
+ }
+ var validateEventDispatches;
+
+ {
+ validateEventDispatches = function (event) {
+ var dispatchListeners = event._dispatchListeners;
+ var dispatchInstances = event._dispatchInstances;
+ var listenersIsArr = Array.isArray(dispatchListeners);
+ var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0;
+ var instancesIsArr = Array.isArray(dispatchInstances);
+ var instancesLen = instancesIsArr ? dispatchInstances.length : dispatchInstances ? 1 : 0;
+
+ if (instancesIsArr !== listenersIsArr || instancesLen !== listenersLen) {
+ error('EventPluginUtils: Invalid `event`.');
+ }
+ };
+ }
+ /**
+ * Dispatch the event to the listener.
+ * @param {SyntheticEvent} event SyntheticEvent to handle
+ * @param {function} listener Application-level callback
+ * @param {*} inst Internal component instance
+ */
+
+
+ function executeDispatch(event, listener, inst) {
+ var type = event.type || 'unknown-event';
+ event.currentTarget = getNodeFromInstance(inst);
+ invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event);
+ event.currentTarget = null;
+ }
+ /**
+ * Standard/simple iteration through an event's collected dispatches.
+ */
+
+ function executeDispatchesInOrder(event) {
+ var dispatchListeners = event._dispatchListeners;
+ var dispatchInstances = event._dispatchInstances;
+
+ {
+ validateEventDispatches(event);
+ }
+
+ if (Array.isArray(dispatchListeners)) {
+ for (var i = 0; i < dispatchListeners.length; i++) {
+ if (event.isPropagationStopped()) {
+ break;
+ } // Listeners and Instances are two parallel arrays that are always in sync.
+
+
+ executeDispatch(event, dispatchListeners[i], dispatchInstances[i]);
+ }
+ } else if (dispatchListeners) {
+ executeDispatch(event, dispatchListeners, dispatchInstances);
+ }
+
+ event._dispatchListeners = null;
+ event._dispatchInstances = null;
+ }
+
+ var FunctionComponent = 0;
+ var ClassComponent = 1;
+ var IndeterminateComponent = 2; // Before we know whether it is function or class
+
+ var HostRoot = 3; // Root of a host tree. Could be nested inside another node.
+
+ var HostPortal = 4; // A subtree. Could be an entry point to a different renderer.
+
+ var HostComponent = 5;
+ var HostText = 6;
+ var Fragment = 7;
+ var Mode = 8;
+ var ContextConsumer = 9;
+ var ContextProvider = 10;
+ var ForwardRef = 11;
+ var Profiler = 12;
+ var SuspenseComponent = 13;
+ var MemoComponent = 14;
+ var SimpleMemoComponent = 15;
+ var LazyComponent = 16;
+ var IncompleteClassComponent = 17;
+ var DehydratedFragment = 18;
+ var SuspenseListComponent = 19;
+ var FundamentalComponent = 20;
+ var ScopeComponent = 21;
+ var Block = 22;
+
+ /**
+ * Injectable ordering of event plugins.
+ */
+ var eventPluginOrder = null;
+ /**
+ * Injectable mapping from names to event plugin modules.
+ */
+
+ var namesToPlugins = {};
+ /**
+ * Recomputes the plugin list using the injected plugins and plugin ordering.
+ *
+ * @private
+ */
+
+ function recomputePluginOrdering() {
+ if (!eventPluginOrder) {
+ // Wait until an `eventPluginOrder` is injected.
+ return;
+ }
+
+ for (var pluginName in namesToPlugins) {
+ var pluginModule = namesToPlugins[pluginName];
+ var pluginIndex = eventPluginOrder.indexOf(pluginName);
+
+ if (!(pluginIndex > -1)) {
+ {
+ throw Error( "EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `" + pluginName + "`." );
+ }
+ }
+
+ if (plugins[pluginIndex]) {
+ continue;
+ }
+
+ if (!pluginModule.extractEvents) {
+ {
+ throw Error( "EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `" + pluginName + "` does not." );
+ }
+ }
+
+ plugins[pluginIndex] = pluginModule;
+ var publishedEvents = pluginModule.eventTypes;
+
+ for (var eventName in publishedEvents) {
+ if (!publishEventForPlugin(publishedEvents[eventName], pluginModule, eventName)) {
+ {
+ throw Error( "EventPluginRegistry: Failed to publish event `" + eventName + "` for plugin `" + pluginName + "`." );
+ }
+ }
+ }
+ }
+ }
+ /**
+ * Publishes an event so that it can be dispatched by the supplied plugin.
+ *
+ * @param {object} dispatchConfig Dispatch configuration for the event.
+ * @param {object} PluginModule Plugin publishing the event.
+ * @return {boolean} True if the event was successfully published.
+ * @private
+ */
+
+
+ function publishEventForPlugin(dispatchConfig, pluginModule, eventName) {
+ if (!!eventNameDispatchConfigs.hasOwnProperty(eventName)) {
+ {
+ throw Error( "EventPluginRegistry: More than one plugin attempted to publish the same event name, `" + eventName + "`." );
+ }
+ }
+
+ eventNameDispatchConfigs[eventName] = dispatchConfig;
+ var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames;
+
+ if (phasedRegistrationNames) {
+ for (var phaseName in phasedRegistrationNames) {
+ if (phasedRegistrationNames.hasOwnProperty(phaseName)) {
+ var phasedRegistrationName = phasedRegistrationNames[phaseName];
+ publishRegistrationName(phasedRegistrationName, pluginModule, eventName);
+ }
+ }
+
+ return true;
+ } else if (dispatchConfig.registrationName) {
+ publishRegistrationName(dispatchConfig.registrationName, pluginModule, eventName);
+ return true;
+ }
+
+ return false;
+ }
+ /**
+ * Publishes a registration name that is used to identify dispatched events.
+ *
+ * @param {string} registrationName Registration name to add.
+ * @param {object} PluginModule Plugin publishing the event.
+ * @private
+ */
+
+
+ function publishRegistrationName(registrationName, pluginModule, eventName) {
+ if (!!registrationNameModules[registrationName]) {
+ {
+ throw Error( "EventPluginRegistry: More than one plugin attempted to publish the same registration name, `" + registrationName + "`." );
+ }
+ }
+
+ registrationNameModules[registrationName] = pluginModule;
+ registrationNameDependencies[registrationName] = pluginModule.eventTypes[eventName].dependencies;
+
+ {
+ var lowerCasedName = registrationName.toLowerCase();
+ possibleRegistrationNames[lowerCasedName] = registrationName;
+
+ if (registrationName === 'onDoubleClick') {
+ possibleRegistrationNames.ondblclick = registrationName;
+ }
+ }
+ }
+ /**
+ * Registers plugins so that they can extract and dispatch events.
+ */
+
+ /**
+ * Ordered list of injected plugins.
+ */
+
+
+ var plugins = [];
+ /**
+ * Mapping from event name to dispatch config
+ */
+
+ var eventNameDispatchConfigs = {};
+ /**
+ * Mapping from registration name to plugin module
+ */
+
+ var registrationNameModules = {};
+ /**
+ * Mapping from registration name to event name
+ */
+
+ var registrationNameDependencies = {};
+ /**
+ * Mapping from lowercase registration names to the properly cased version,
+ * used to warn in the case of missing event handlers. Available
+ * only in true.
+ * @type {Object}
+ */
+
+ var possibleRegistrationNames = {} ; // Trust the developer to only use possibleRegistrationNames in true
+
+ /**
+ * Injects an ordering of plugins (by plugin name). This allows the ordering
+ * to be decoupled from injection of the actual plugins so that ordering is
+ * always deterministic regardless of packaging, on-the-fly injection, etc.
+ *
+ * @param {array} InjectedEventPluginOrder
+ * @internal
+ */
+
+ function injectEventPluginOrder(injectedEventPluginOrder) {
+ if (!!eventPluginOrder) {
+ {
+ throw Error( "EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React." );
+ }
+ } // Clone the ordering so it cannot be dynamically mutated.
+
+
+ eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder);
+ recomputePluginOrdering();
+ }
+ /**
+ * Injects plugins to be used by plugin event system. The plugin names must be
+ * in the ordering injected by `injectEventPluginOrder`.
+ *
+ * Plugins can be injected as part of page initialization or on-the-fly.
+ *
+ * @param {object} injectedNamesToPlugins Map from names to plugin modules.
+ * @internal
+ */
+
+ function injectEventPluginsByName(injectedNamesToPlugins) {
+ var isOrderingDirty = false;
+
+ for (var pluginName in injectedNamesToPlugins) {
+ if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) {
+ continue;
+ }
+
+ var pluginModule = injectedNamesToPlugins[pluginName];
+
+ if (!namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== pluginModule) {
+ if (!!namesToPlugins[pluginName]) {
+ {
+ throw Error( "EventPluginRegistry: Cannot inject two different event plugins using the same name, `" + pluginName + "`." );
+ }
+ }
+
+ namesToPlugins[pluginName] = pluginModule;
+ isOrderingDirty = true;
+ }
+ }
+
+ if (isOrderingDirty) {
+ recomputePluginOrdering();
+ }
+ }
+
+ var canUseDOM = !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined');
+
+ var ReactInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
+ var _assign = ReactInternals.assign;
+
+ var PLUGIN_EVENT_SYSTEM = 1;
+ var IS_REPLAYED = 1 << 5;
+ var IS_FIRST_ANCESTOR = 1 << 6;
+
+ var restoreImpl = null;
+ var restoreTarget = null;
+ var restoreQueue = null;
+
+ function restoreStateOfTarget(target) {
+ // We perform this translation at the end of the event loop so that we
+ // always receive the correct fiber here
+ var internalInstance = getInstanceFromNode(target);
+
+ if (!internalInstance) {
+ // Unmounted
+ return;
+ }
+
+ if (!(typeof restoreImpl === 'function')) {
+ {
+ throw Error( "setRestoreImplementation() needs to be called to handle a target for controlled events. This error is likely caused by a bug in React. Please file an issue." );
+ }
+ }
+
+ var stateNode = internalInstance.stateNode; // Guard against Fiber being unmounted.
+
+ if (stateNode) {
+ var _props = getFiberCurrentPropsFromNode(stateNode);
+
+ restoreImpl(internalInstance.stateNode, internalInstance.type, _props);
+ }
+ }
+
+ function setRestoreImplementation(impl) {
+ restoreImpl = impl;
+ }
+ function enqueueStateRestore(target) {
+ if (restoreTarget) {
+ if (restoreQueue) {
+ restoreQueue.push(target);
+ } else {
+ restoreQueue = [target];
+ }
+ } else {
+ restoreTarget = target;
+ }
+ }
+ function needsStateRestore() {
+ return restoreTarget !== null || restoreQueue !== null;
+ }
+ function restoreStateIfNeeded() {
+ if (!restoreTarget) {
+ return;
+ }
+
+ var target = restoreTarget;
+ var queuedTargets = restoreQueue;
+ restoreTarget = null;
+ restoreQueue = null;
+ restoreStateOfTarget(target);
+
+ if (queuedTargets) {
+ for (var i = 0; i < queuedTargets.length; i++) {
+ restoreStateOfTarget(queuedTargets[i]);
+ }
+ }
+ }
+
+ var enableProfilerTimer = true; // Trace which interactions trigger each commit.
+
+ var enableDeprecatedFlareAPI = false; // Experimental Host Component support.
+
+ var enableFundamentalAPI = false; // Experimental Scope support.
+ var warnAboutStringRefs = false;
+
+ // the renderer. Such as when we're dispatching events or if third party
+ // libraries need to call batchedUpdates. Eventually, this API will go away when
+ // everything is batched by default. We'll then have a similar API to opt-out of
+ // scheduled work and instead do synchronous work.
+ // Defaults
+
+ var batchedUpdatesImpl = function (fn, bookkeeping) {
+ return fn(bookkeeping);
+ };
+
+ var discreteUpdatesImpl = function (fn, a, b, c, d) {
+ return fn(a, b, c, d);
+ };
+
+ var flushDiscreteUpdatesImpl = function () {};
+
+ var batchedEventUpdatesImpl = batchedUpdatesImpl;
+ var isInsideEventHandler = false;
+ var isBatchingEventUpdates = false;
+
+ function finishEventHandler() {
+ // Here we wait until all updates have propagated, which is important
+ // when using controlled components within layers:
+ // https://github.com/facebook/react/issues/1698
+ // Then we restore state of any controlled component.
+ var controlledComponentsHavePendingUpdates = needsStateRestore();
+
+ if (controlledComponentsHavePendingUpdates) {
+ // If a controlled event was fired, we may need to restore the state of
+ // the DOM node back to the controlled value. This is necessary when React
+ // bails out of the update without touching the DOM.
+ flushDiscreteUpdatesImpl();
+ restoreStateIfNeeded();
+ }
+ }
+
+ function batchedUpdates(fn, bookkeeping) {
+ if (isInsideEventHandler) {
+ // If we are currently inside another batch, we need to wait until it
+ // fully completes before restoring state.
+ return fn(bookkeeping);
+ }
+
+ isInsideEventHandler = true;
+
+ try {
+ return batchedUpdatesImpl(fn, bookkeeping);
+ } finally {
+ isInsideEventHandler = false;
+ finishEventHandler();
+ }
+ }
+ function batchedEventUpdates(fn, a, b) {
+ if (isBatchingEventUpdates) {
+ // If we are currently inside another batch, we need to wait until it
+ // fully completes before restoring state.
+ return fn(a, b);
+ }
+
+ isBatchingEventUpdates = true;
+
+ try {
+ return batchedEventUpdatesImpl(fn, a, b);
+ } finally {
+ isBatchingEventUpdates = false;
+ finishEventHandler();
+ }
+ } // This is for the React Flare event system
+ function discreteUpdates(fn, a, b, c, d) {
+ var prevIsInsideEventHandler = isInsideEventHandler;
+ isInsideEventHandler = true;
+
+ try {
+ return discreteUpdatesImpl(fn, a, b, c, d);
+ } finally {
+ isInsideEventHandler = prevIsInsideEventHandler;
+
+ if (!isInsideEventHandler) {
+ finishEventHandler();
+ }
+ }
+ }
+ function flushDiscreteUpdatesIfNeeded(timeStamp) {
+ // event.timeStamp isn't overly reliable due to inconsistencies in
+ // how different browsers have historically provided the time stamp.
+ // Some browsers provide high-resolution time stamps for all events,
+ // some provide low-resolution time stamps for all events. FF < 52
+ // even mixes both time stamps together. Some browsers even report
+ // negative time stamps or time stamps that are 0 (iOS9) in some cases.
+ // Given we are only comparing two time stamps with equality (!==),
+ // we are safe from the resolution differences. If the time stamp is 0
+ // we bail-out of preventing the flush, which can affect semantics,
+ // such as if an earlier flush removes or adds event listeners that
+ // are fired in the subsequent flush. However, this is the same
+ // behaviour as we had before this change, so the risks are low.
+ if (!isInsideEventHandler && (!enableDeprecatedFlareAPI )) {
+ flushDiscreteUpdatesImpl();
+ }
+ }
+ function setBatchingImplementation(_batchedUpdatesImpl, _discreteUpdatesImpl, _flushDiscreteUpdatesImpl, _batchedEventUpdatesImpl) {
+ batchedUpdatesImpl = _batchedUpdatesImpl;
+ discreteUpdatesImpl = _discreteUpdatesImpl;
+ flushDiscreteUpdatesImpl = _flushDiscreteUpdatesImpl;
+ batchedEventUpdatesImpl = _batchedEventUpdatesImpl;
+ }
+
+ var DiscreteEvent = 0;
+ var UserBlockingEvent = 1;
+ var ContinuousEvent = 2;
+
+ var ReactInternals$1 = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
+ var _ReactInternals$Sched = ReactInternals$1.Scheduler,
+ unstable_cancelCallback = _ReactInternals$Sched.unstable_cancelCallback,
+ unstable_now = _ReactInternals$Sched.unstable_now,
+ unstable_scheduleCallback = _ReactInternals$Sched.unstable_scheduleCallback,
+ unstable_shouldYield = _ReactInternals$Sched.unstable_shouldYield,
+ unstable_requestPaint = _ReactInternals$Sched.unstable_requestPaint,
+ unstable_getFirstCallbackNode = _ReactInternals$Sched.unstable_getFirstCallbackNode,
+ unstable_runWithPriority = _ReactInternals$Sched.unstable_runWithPriority,
+ unstable_next = _ReactInternals$Sched.unstable_next,
+ unstable_continueExecution = _ReactInternals$Sched.unstable_continueExecution,
+ unstable_pauseExecution = _ReactInternals$Sched.unstable_pauseExecution,
+ unstable_getCurrentPriorityLevel = _ReactInternals$Sched.unstable_getCurrentPriorityLevel,
+ unstable_ImmediatePriority = _ReactInternals$Sched.unstable_ImmediatePriority,
+ unstable_UserBlockingPriority = _ReactInternals$Sched.unstable_UserBlockingPriority,
+ unstable_NormalPriority = _ReactInternals$Sched.unstable_NormalPriority,
+ unstable_LowPriority = _ReactInternals$Sched.unstable_LowPriority,
+ unstable_IdlePriority = _ReactInternals$Sched.unstable_IdlePriority,
+ unstable_forceFrameRate = _ReactInternals$Sched.unstable_forceFrameRate,
+ unstable_flushAllWithoutAsserting = _ReactInternals$Sched.unstable_flushAllWithoutAsserting;
+
+ // A reserved attribute.
+ // It is handled by React separately and shouldn't be written to the DOM.
+ var RESERVED = 0; // A simple string attribute.
+ // Attributes that aren't in the whitelist are presumed to have this type.
+
+ var STRING = 1; // A string attribute that accepts booleans in React. In HTML, these are called
+ // "enumerated" attributes with "true" and "false" as possible values.
+ // When true, it should be set to a "true" string.
+ // When false, it should be set to a "false" string.
+
+ var BOOLEANISH_STRING = 2; // A real boolean attribute.
+ // When true, it should be present (set either to an empty string or its name).
+ // When false, it should be omitted.
+
+ var BOOLEAN = 3; // An attribute that can be used as a flag as well as with a value.
+ // When true, it should be present (set either to an empty string or its name).
+ // When false, it should be omitted.
+ // For any other value, should be present with that value.
+
+ var OVERLOADED_BOOLEAN = 4; // An attribute that must be numeric or parse as a numeric.
+ // When falsy, it should be removed.
+
+ var NUMERIC = 5; // An attribute that must be positive numeric or parse as a positive numeric.
+ // When falsy, it should be removed.
+
+ var POSITIVE_NUMERIC = 6;
+
+ /* eslint-disable max-len */
+ var ATTRIBUTE_NAME_START_CHAR = ":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD";
+ /* eslint-enable max-len */
+
+ var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + "\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040";
+ var ROOT_ATTRIBUTE_NAME = 'data-reactroot';
+ var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + ATTRIBUTE_NAME_START_CHAR + '][' + ATTRIBUTE_NAME_CHAR + ']*$');
+ var hasOwnProperty = Object.prototype.hasOwnProperty;
+ var illegalAttributeNameCache = {};
+ var validatedAttributeNameCache = {};
+ function isAttributeNameSafe(attributeName) {
+ if (hasOwnProperty.call(validatedAttributeNameCache, attributeName)) {
+ return true;
+ }
+
+ if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) {
+ return false;
+ }
+
+ if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) {
+ validatedAttributeNameCache[attributeName] = true;
+ return true;
+ }
+
+ illegalAttributeNameCache[attributeName] = true;
+
+ {
+ error('Invalid attribute name: `%s`', attributeName);
+ }
+
+ return false;
+ }
+ function shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag) {
+ if (propertyInfo !== null) {
+ return propertyInfo.type === RESERVED;
+ }
+
+ if (isCustomComponentTag) {
+ return false;
+ }
+
+ if (name.length > 2 && (name[0] === 'o' || name[0] === 'O') && (name[1] === 'n' || name[1] === 'N')) {
+ return true;
+ }
+
+ return false;
+ }
+ function shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) {
+ if (propertyInfo !== null && propertyInfo.type === RESERVED) {
+ return false;
+ }
+
+ switch (typeof value) {
+ case 'function': // $FlowIssue symbol is perfectly valid here
+
+ case 'symbol':
+ // eslint-disable-line
+ return true;
+
+ case 'boolean':
+ {
+ if (isCustomComponentTag) {
+ return false;
+ }
+
+ if (propertyInfo !== null) {
+ return !propertyInfo.acceptsBooleans;
+ } else {
+ var prefix = name.toLowerCase().slice(0, 5);
+ return prefix !== 'data-' && prefix !== 'aria-';
+ }
+ }
+
+ default:
+ return false;
+ }
+ }
+ function shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag) {
+ if (value === null || typeof value === 'undefined') {
+ return true;
+ }
+
+ if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag)) {
+ return true;
+ }
+
+ if (isCustomComponentTag) {
+ return false;
+ }
+
+ if (propertyInfo !== null) {
+ switch (propertyInfo.type) {
+ case BOOLEAN:
+ return !value;
+
+ case OVERLOADED_BOOLEAN:
+ return value === false;
+
+ case NUMERIC:
+ return isNaN(value);
+
+ case POSITIVE_NUMERIC:
+ return isNaN(value) || value < 1;
+ }
+ }
+
+ return false;
+ }
+ function getPropertyInfo(name) {
+ return properties.hasOwnProperty(name) ? properties[name] : null;
+ }
+
+ function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace, sanitizeURL) {
+ this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN;
+ this.attributeName = attributeName;
+ this.attributeNamespace = attributeNamespace;
+ this.mustUseProperty = mustUseProperty;
+ this.propertyName = name;
+ this.type = type;
+ this.sanitizeURL = sanitizeURL;
+ } // When adding attributes to this list, be sure to also add them to
+ // the `possibleStandardNames` module to ensure casing and incorrect
+ // name warnings.
+
+
+ var properties = {}; // These props are reserved by React. They shouldn't be written to the DOM.
+
+ var reservedProps = ['children', 'dangerouslySetInnerHTML', // TODO: This prevents the assignment of defaultValue to regular
+ // elements (not just inputs). Now that ReactDOMInput assigns to the
+ // defaultValue property -- do we need this?
+ 'defaultValue', 'defaultChecked', 'innerHTML', 'suppressContentEditableWarning', 'suppressHydrationWarning', 'style'];
+
+ reservedProps.forEach(function (name) {
+ properties[name] = new PropertyInfoRecord(name, RESERVED, false, // mustUseProperty
+ name, // attributeName
+ null, // attributeNamespace
+ false);
+ }); // A few React string attributes have a different name.
+ // This is a mapping from React prop names to the attribute names.
+
+ [['acceptCharset', 'accept-charset'], ['className', 'class'], ['htmlFor', 'for'], ['httpEquiv', 'http-equiv']].forEach(function (_ref) {
+ var name = _ref[0],
+ attributeName = _ref[1];
+ properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
+ attributeName, // attributeName
+ null, // attributeNamespace
+ false);
+ }); // These are "enumerated" HTML attributes that accept "true" and "false".
+ // In React, we let users pass `true` and `false` even though technically
+ // these aren't boolean attributes (they are coerced to strings).
+
+ ['contentEditable', 'draggable', 'spellCheck', 'value'].forEach(function (name) {
+ properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
+ name.toLowerCase(), // attributeName
+ null, // attributeNamespace
+ false);
+ }); // These are "enumerated" SVG attributes that accept "true" and "false".
+ // In React, we let users pass `true` and `false` even though technically
+ // these aren't boolean attributes (they are coerced to strings).
+ // Since these are SVG attributes, their attribute names are case-sensitive.
+
+ ['autoReverse', 'externalResourcesRequired', 'focusable', 'preserveAlpha'].forEach(function (name) {
+ properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty
+ name, // attributeName
+ null, // attributeNamespace
+ false);
+ }); // These are HTML boolean attributes.
+
+ ['allowFullScreen', 'async', // Note: there is a special case that prevents it from being written to the DOM
+ // on the client side because the browsers are inconsistent. Instead we call focus().
+ 'autoFocus', 'autoPlay', 'controls', 'default', 'defer', 'disabled', 'disablePictureInPicture', 'formNoValidate', 'hidden', 'loop', 'noModule', 'noValidate', 'open', 'playsInline', 'readOnly', 'required', 'reversed', 'scoped', 'seamless', // Microdata
+ 'itemScope'].forEach(function (name) {
+ properties[name] = new PropertyInfoRecord(name, BOOLEAN, false, // mustUseProperty
+ name.toLowerCase(), // attributeName
+ null, // attributeNamespace
+ false);
+ }); // These are the few React props that we set as DOM properties
+ // rather than attributes. These are all booleans.
+
+ ['checked', // Note: `option.selected` is not updated if `select.multiple` is
+ // disabled with `removeAttribute`. We have special logic for handling this.
+ 'multiple', 'muted', 'selected' // NOTE: if you add a camelCased prop to this list,
+ // you'll need to set attributeName to name.toLowerCase()
+ // instead in the assignment below.
+ ].forEach(function (name) {
+ properties[name] = new PropertyInfoRecord(name, BOOLEAN, true, // mustUseProperty
+ name, // attributeName
+ null, // attributeNamespace
+ false);
+ }); // These are HTML attributes that are "overloaded booleans": they behave like
+ // booleans, but can also accept a string value.
+
+ ['capture', 'download' // NOTE: if you add a camelCased prop to this list,
+ // you'll need to set attributeName to name.toLowerCase()
+ // instead in the assignment below.
+ ].forEach(function (name) {
+ properties[name] = new PropertyInfoRecord(name, OVERLOADED_BOOLEAN, false, // mustUseProperty
+ name, // attributeName
+ null, // attributeNamespace
+ false);
+ }); // These are HTML attributes that must be positive numbers.
+
+ ['cols', 'rows', 'size', 'span' // NOTE: if you add a camelCased prop to this list,
+ // you'll need to set attributeName to name.toLowerCase()
+ // instead in the assignment below.
+ ].forEach(function (name) {
+ properties[name] = new PropertyInfoRecord(name, POSITIVE_NUMERIC, false, // mustUseProperty
+ name, // attributeName
+ null, // attributeNamespace
+ false);
+ }); // These are HTML attributes that must be numbers.
+
+ ['rowSpan', 'start'].forEach(function (name) {
+ properties[name] = new PropertyInfoRecord(name, NUMERIC, false, // mustUseProperty
+ name.toLowerCase(), // attributeName
+ null, // attributeNamespace
+ false);
+ });
+ var CAMELIZE = /[\-\:]([a-z])/g;
+
+ var capitalize = function (token) {
+ return token[1].toUpperCase();
+ }; // This is a list of all SVG attributes that need special casing, namespacing,
+ // or boolean value assignment. Regular attributes that just accept strings
+ // and have the same names are omitted, just like in the HTML whitelist.
+ // Some of these attributes can be hard to find. This list was created by
+ // scraping the MDN documentation.
+
+
+ ['accent-height', 'alignment-baseline', 'arabic-form', 'baseline-shift', 'cap-height', 'clip-path', 'clip-rule', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'dominant-baseline', 'enable-background', 'fill-opacity', 'fill-rule', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'glyph-name', 'glyph-orientation-horizontal', 'glyph-orientation-vertical', 'horiz-adv-x', 'horiz-origin-x', 'image-rendering', 'letter-spacing', 'lighting-color', 'marker-end', 'marker-mid', 'marker-start', 'overline-position', 'overline-thickness', 'paint-order', 'panose-1', 'pointer-events', 'rendering-intent', 'shape-rendering', 'stop-color', 'stop-opacity', 'strikethrough-position', 'strikethrough-thickness', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-decoration', 'text-rendering', 'underline-position', 'underline-thickness', 'unicode-bidi', 'unicode-range', 'units-per-em', 'v-alphabetic', 'v-hanging', 'v-ideographic', 'v-mathematical', 'vector-effect', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'word-spacing', 'writing-mode', 'xmlns:xlink', 'x-height' // NOTE: if you add a camelCased prop to this list,
+ // you'll need to set attributeName to name.toLowerCase()
+ // instead in the assignment below.
+ ].forEach(function (attributeName) {
+ var name = attributeName.replace(CAMELIZE, capitalize);
+ properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
+ attributeName, null, // attributeNamespace
+ false);
+ }); // String SVG attributes with the xlink namespace.
+
+ ['xlink:actuate', 'xlink:arcrole', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type' // NOTE: if you add a camelCased prop to this list,
+ // you'll need to set attributeName to name.toLowerCase()
+ // instead in the assignment below.
+ ].forEach(function (attributeName) {
+ var name = attributeName.replace(CAMELIZE, capitalize);
+ properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
+ attributeName, 'http://www.w3.org/1999/xlink', false);
+ }); // String SVG attributes with the xml namespace.
+
+ ['xml:base', 'xml:lang', 'xml:space' // NOTE: if you add a camelCased prop to this list,
+ // you'll need to set attributeName to name.toLowerCase()
+ // instead in the assignment below.
+ ].forEach(function (attributeName) {
+ var name = attributeName.replace(CAMELIZE, capitalize);
+ properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty
+ attributeName, 'http://www.w3.org/XML/1998/namespace', false);
+ }); // These attribute exists both in HTML and SVG.
+ // The attribute name is case-sensitive in SVG so we can't just use
+ // the React name like we do for attributes that exist only in HTML.
+
+ ['tabIndex', 'crossOrigin'].forEach(function (attributeName) {
+ properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty
+ attributeName.toLowerCase(), // attributeName
+ null, // attributeNamespace
+ false);
+ }); // These attributes accept URLs. These must not allow javascript: URLS.
+ // These will also need to accept Trusted Types object in the future.
+
+ var xlinkHref = 'xlinkHref';
+ properties[xlinkHref] = new PropertyInfoRecord('xlinkHref', STRING, false, // mustUseProperty
+ 'xlink:href', 'http://www.w3.org/1999/xlink', true);
+ ['src', 'href', 'action', 'formAction'].forEach(function (attributeName) {
+ properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty
+ attributeName.toLowerCase(), // attributeName
+ null, // attributeNamespace
+ true);
+ });
+
+ var ReactDebugCurrentFrame = null;
+
+ {
+ ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
+ } // A javascript: URL can contain leading C0 control or \u0020 SPACE,
+ // and any newline or tab are filtered out as if they're not part of the URL.
+ // https://url.spec.whatwg.org/#url-parsing
+ // Tab or newline are defined as \r\n\t:
+ // https://infra.spec.whatwg.org/#ascii-tab-or-newline
+ // A C0 control is a code point in the range \u0000 NULL to \u001F
+ // INFORMATION SEPARATOR ONE, inclusive:
+ // https://infra.spec.whatwg.org/#c0-control-or-space
+
+ /* eslint-disable max-len */
+
+
+ var isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i;
+ var didWarn = false;
+
+ function sanitizeURL(url) {
+ {
+ if (!didWarn && isJavaScriptProtocol.test(url)) {
+ didWarn = true;
+
+ error('A future version of React will block javascript: URLs as a security precaution. ' + 'Use event handlers instead if you can. If you need to generate unsafe HTML try ' + 'using dangerouslySetInnerHTML instead. React was passed %s.', JSON.stringify(url));
+ }
+ }
+ }
+
+ /**
+ * Get the value for a property on a node. Only used in DEV for SSR validation.
+ * The "expected" argument is used as a hint of what the expected value is.
+ * Some properties have multiple equivalent values.
+ */
+ function getValueForProperty(node, name, expected, propertyInfo) {
+ {
+ if (propertyInfo.mustUseProperty) {
+ var propertyName = propertyInfo.propertyName;
+ return node[propertyName];
+ } else {
+ if ( propertyInfo.sanitizeURL) {
+ // If we haven't fully disabled javascript: URLs, and if
+ // the hydration is successful of a javascript: URL, we
+ // still want to warn on the client.
+ sanitizeURL('' + expected);
+ }
+
+ var attributeName = propertyInfo.attributeName;
+ var stringValue = null;
+
+ if (propertyInfo.type === OVERLOADED_BOOLEAN) {
+ if (node.hasAttribute(attributeName)) {
+ var value = node.getAttribute(attributeName);
+
+ if (value === '') {
+ return true;
+ }
+
+ if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
+ return value;
+ }
+
+ if (value === '' + expected) {
+ return expected;
+ }
+
+ return value;
+ }
+ } else if (node.hasAttribute(attributeName)) {
+ if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
+ // We had an attribute but shouldn't have had one, so read it
+ // for the error message.
+ return node.getAttribute(attributeName);
+ }
+
+ if (propertyInfo.type === BOOLEAN) {
+ // If this was a boolean, it doesn't matter what the value is
+ // the fact that we have it is the same as the expected.
+ return expected;
+ } // Even if this property uses a namespace we use getAttribute
+ // because we assume its namespaced name is the same as our config.
+ // To use getAttributeNS we need the local name which we don't have
+ // in our config atm.
+
+
+ stringValue = node.getAttribute(attributeName);
+ }
+
+ if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
+ return stringValue === null ? expected : stringValue;
+ } else if (stringValue === '' + expected) {
+ return expected;
+ } else {
+ return stringValue;
+ }
+ }
+ }
+ }
+ /**
+ * Get the value for a attribute on a node. Only used in DEV for SSR validation.
+ * The third argument is used as a hint of what the expected value is. Some
+ * attributes have multiple equivalent values.
+ */
+
+ function getValueForAttribute(node, name, expected) {
+ {
+ if (!isAttributeNameSafe(name)) {
+ return;
+ }
+
+ if (!node.hasAttribute(name)) {
+ return expected === undefined ? undefined : null;
+ }
+
+ var value = node.getAttribute(name);
+
+ if (value === '' + expected) {
+ return expected;
+ }
+
+ return value;
+ }
+ }
+ /**
+ * Sets the value for a property on a node.
+ *
+ * @param {DOMElement} node
+ * @param {string} name
+ * @param {*} value
+ */
+
+ function setValueForProperty(node, name, value, isCustomComponentTag) {
+ var propertyInfo = getPropertyInfo(name);
+
+ if (shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag)) {
+ return;
+ }
+
+ if (shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag)) {
+ value = null;
+ } // If the prop isn't in the special list, treat it as a simple attribute.
+
+
+ if (isCustomComponentTag || propertyInfo === null) {
+ if (isAttributeNameSafe(name)) {
+ var _attributeName = name;
+
+ if (value === null) {
+ node.removeAttribute(_attributeName);
+ } else {
+ node.setAttribute(_attributeName, '' + value);
+ }
+ }
+
+ return;
+ }
+
+ var mustUseProperty = propertyInfo.mustUseProperty;
+
+ if (mustUseProperty) {
+ var propertyName = propertyInfo.propertyName;
+
+ if (value === null) {
+ var type = propertyInfo.type;
+ node[propertyName] = type === BOOLEAN ? false : '';
+ } else {
+ // Contrary to `setAttribute`, object properties are properly
+ // `toString`ed by IE8/9.
+ node[propertyName] = value;
+ }
+
+ return;
+ } // The rest are treated as attributes with special cases.
+
+
+ var attributeName = propertyInfo.attributeName,
+ attributeNamespace = propertyInfo.attributeNamespace;
+
+ if (value === null) {
+ node.removeAttribute(attributeName);
+ } else {
+ var _type = propertyInfo.type;
+ var attributeValue;
+
+ if (_type === BOOLEAN || _type === OVERLOADED_BOOLEAN && value === true) {
+ // If attribute type is boolean, we know for sure it won't be an execution sink
+ // and we won't require Trusted Type here.
+ attributeValue = '';
+ } else {
+ // `setAttribute` with objects becomes only `[object]` in IE8/9,
+ // ('' + value) makes it output the correct toString()-value.
+ {
+ attributeValue = '' + value;
+ }
+
+ if (propertyInfo.sanitizeURL) {
+ sanitizeURL(attributeValue.toString());
+ }
+ }
+
+ if (attributeNamespace) {
+ node.setAttributeNS(attributeNamespace, attributeName, attributeValue);
+ } else {
+ node.setAttribute(attributeName, attributeValue);
+ }
+ }
+ }
+
+ var BEFORE_SLASH_RE = /^(.*)[\\\/]/;
+ function describeComponentFrame (name, source, ownerName) {
+ var sourceInfo = '';
+
+ if (source) {
+ var path = source.fileName;
+ var fileName = path.replace(BEFORE_SLASH_RE, '');
+
+ {
+ // In DEV, include code for a common special case:
+ // prefer "folder/index.js" instead of just "index.js".
+ if (/^index\./.test(fileName)) {
+ var match = path.match(BEFORE_SLASH_RE);
+
+ if (match) {
+ var pathBeforeSlash = match[1];
+
+ if (pathBeforeSlash) {
+ var folderName = pathBeforeSlash.replace(BEFORE_SLASH_RE, '');
+ fileName = folderName + '/' + fileName;
+ }
+ }
+ }
+ }
+
+ sourceInfo = ' (at ' + fileName + ':' + source.lineNumber + ')';
+ } else if (ownerName) {
+ sourceInfo = ' (created by ' + ownerName + ')';
+ }
+
+ return '\n in ' + (name || 'Unknown') + sourceInfo;
+ }
+
+ // The Symbol used to tag the ReactElement-like types. If there is no native Symbol
+ // nor polyfill, then a plain number is used for performance.
+ var hasSymbol = typeof Symbol === 'function' && Symbol.for;
+ var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;
+ var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;
+ var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;
+ var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;
+ var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;
+ var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;
+ var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace; // TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary
+ var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;
+ var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;
+ var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;
+ var REACT_SUSPENSE_LIST_TYPE = hasSymbol ? Symbol.for('react.suspense_list') : 0xead8;
+ var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;
+ var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;
+ var REACT_BLOCK_TYPE = hasSymbol ? Symbol.for('react.block') : 0xead9;
+ var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
+ var FAUX_ITERATOR_SYMBOL = '@@iterator';
+ function getIteratorFn(maybeIterable) {
+ if (maybeIterable === null || typeof maybeIterable !== 'object') {
+ return null;
+ }
+
+ var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
+
+ if (typeof maybeIterator === 'function') {
+ return maybeIterator;
+ }
+
+ return null;
+ }
+
+ var Uninitialized = -1;
+ var Pending = 0;
+ var Resolved = 1;
+ var Rejected = 2;
+ function refineResolvedLazyComponent(lazyComponent) {
+ return lazyComponent._status === Resolved ? lazyComponent._result : null;
+ }
+ function initializeLazyComponentType(lazyComponent) {
+ if (lazyComponent._status === Uninitialized) {
+ lazyComponent._status = Pending;
+ var ctor = lazyComponent._ctor;
+ var thenable = ctor();
+ lazyComponent._result = thenable;
+ thenable.then(function (moduleObject) {
+ if (lazyComponent._status === Pending) {
+ var defaultExport = moduleObject.default;
+
+ {
+ if (defaultExport === undefined) {
+ error('lazy: Expected the result of a dynamic import() call. ' + 'Instead received: %s\n\nYour code should look like: \n ' + "const MyComponent = lazy(() => import('./MyComponent'))", moduleObject);
+ }
+ }
+
+ lazyComponent._status = Resolved;
+ lazyComponent._result = defaultExport;
+ }
+ }, function (error) {
+ if (lazyComponent._status === Pending) {
+ lazyComponent._status = Rejected;
+ lazyComponent._result = error;
+ }
+ });
+ }
+ }
+
+ function getWrappedName(outerType, innerType, wrapperName) {
+ var functionName = innerType.displayName || innerType.name || '';
+ return outerType.displayName || (functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName);
+ }
+
+ function getComponentName(type) {
+ if (type == null) {
+ // Host root, text node or just invalid type.
+ return null;
+ }
+
+ {
+ if (typeof type.tag === 'number') {
+ error('Received an unexpected object in getComponentName(). ' + 'This is likely a bug in React. Please file an issue.');
+ }
+ }
+
+ if (typeof type === 'function') {
+ return type.displayName || type.name || null;
+ }
+
+ if (typeof type === 'string') {
+ return type;
+ }
+
+ switch (type) {
+ case REACT_FRAGMENT_TYPE:
+ return 'Fragment';
+
+ case REACT_PORTAL_TYPE:
+ return 'Portal';
+
+ case REACT_PROFILER_TYPE:
+ return "Profiler";
+
+ case REACT_STRICT_MODE_TYPE:
+ return 'StrictMode';
+
+ case REACT_SUSPENSE_TYPE:
+ return 'Suspense';
+
+ case REACT_SUSPENSE_LIST_TYPE:
+ return 'SuspenseList';
+ }
+
+ if (typeof type === 'object') {
+ switch (type.$$typeof) {
+ case REACT_CONTEXT_TYPE:
+ return 'Context.Consumer';
+
+ case REACT_PROVIDER_TYPE:
+ return 'Context.Provider';
+
+ case REACT_FORWARD_REF_TYPE:
+ return getWrappedName(type, type.render, 'ForwardRef');
+
+ case REACT_MEMO_TYPE:
+ return getComponentName(type.type);
+
+ case REACT_BLOCK_TYPE:
+ return getComponentName(type.render);
+
+ case REACT_LAZY_TYPE:
+ {
+ var thenable = type;
+ var resolvedThenable = refineResolvedLazyComponent(thenable);
+
+ if (resolvedThenable) {
+ return getComponentName(resolvedThenable);
+ }
+
+ break;
+ }
+ }
+ }
+
+ return null;
+ }
+
+ var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
+
+ function describeFiber(fiber) {
+ switch (fiber.tag) {
+ case HostRoot:
+ case HostPortal:
+ case HostText:
+ case Fragment:
+ case ContextProvider:
+ case ContextConsumer:
+ return '';
+
+ default:
+ var owner = fiber._debugOwner;
+ var source = fiber._debugSource;
+ var name = getComponentName(fiber.type);
+ var ownerName = null;
+
+ if (owner) {
+ ownerName = getComponentName(owner.type);
+ }
+
+ return describeComponentFrame(name, source, ownerName);
+ }
+ }
+
+ function getStackByFiberInDevAndProd(workInProgress) {
+ var info = '';
+ var node = workInProgress;
+
+ do {
+ info += describeFiber(node);
+ node = node.return;
+ } while (node);
+
+ return info;
+ }
+ var current = null;
+ var isRendering = false;
+ function getCurrentFiberOwnerNameInDevOrNull() {
+ {
+ if (current === null) {
+ return null;
+ }
+
+ var owner = current._debugOwner;
+
+ if (owner !== null && typeof owner !== 'undefined') {
+ return getComponentName(owner.type);
+ }
+ }
+
+ return null;
+ }
+ function getCurrentFiberStackInDev() {
+ {
+ if (current === null) {
+ return '';
+ } // Safe because if current fiber exists, we are reconciling,
+ // and it is guaranteed to be the work-in-progress version.
+
+
+ return getStackByFiberInDevAndProd(current);
+ }
+ }
+ function resetCurrentFiber() {
+ {
+ ReactDebugCurrentFrame$1.getCurrentStack = null;
+ current = null;
+ isRendering = false;
+ }
+ }
+ function setCurrentFiber(fiber) {
+ {
+ ReactDebugCurrentFrame$1.getCurrentStack = getCurrentFiberStackInDev;
+ current = fiber;
+ isRendering = false;
+ }
+ }
+ function setIsRendering(rendering) {
+ {
+ isRendering = rendering;
+ }
+ }
+
+ // Flow does not allow string concatenation of most non-string types. To work
+ // around this limitation, we use an opaque type that can only be obtained by
+ // passing the value through getToStringValue first.
+ function toString(value) {
+ return '' + value;
+ }
+ function getToStringValue(value) {
+ switch (typeof value) {
+ case 'boolean':
+ case 'number':
+ case 'object':
+ case 'string':
+ case 'undefined':
+ return value;
+
+ default:
+ // function, symbol are assigned as empty strings
+ return '';
+ }
+ }
+
+ /**
+ * Copyright (c) 2013-present, Facebook, Inc.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+ var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
+
+ var ReactPropTypesSecret_1 = ReactPropTypesSecret;
+
+ var printWarning$1 = function() {};
+
+ {
+ var ReactPropTypesSecret$1 = ReactPropTypesSecret_1;
+ var loggedTypeFailures = {};
+ var has = Function.call.bind(Object.prototype.hasOwnProperty);
+
+ printWarning$1 = function(text) {
+ var message = 'Warning: ' + text;
+ if (typeof console !== 'undefined') {
+ console.error(message);
+ }
+ try {
+ // --- Welcome to debugging React ---
+ // This error was thrown as a convenience so that you can use this stack
+ // to find the callsite that caused this warning to fire.
+ throw new Error(message);
+ } catch (x) {}
+ };
+ }
+
+ /**
+ * Assert that the values match with the type specs.
+ * Error messages are memorized and will only be shown once.
+ *
+ * @param {object} typeSpecs Map of name to a ReactPropType
+ * @param {object} values Runtime values that need to be type-checked
+ * @param {string} location e.g. "prop", "context", "child context"
+ * @param {string} componentName Name of the component for error messages.
+ * @param {?Function} getStack Returns the component stack.
+ * @private
+ */
+ function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
+ {
+ for (var typeSpecName in typeSpecs) {
+ if (has(typeSpecs, typeSpecName)) {
+ var error;
+ // Prop type validation may throw. In case they do, we don't want to
+ // fail the render phase where it didn't fail before. So we log it.
+ // After these have been cleaned up, we'll let them throw.
+ try {
+ // This is intentionally an invariant that gets caught. It's the same
+ // behavior as without this statement except with a better message.
+ if (typeof typeSpecs[typeSpecName] !== 'function') {
+ var err = Error(
+ (componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' +
+ 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.'
+ );
+ err.name = 'Invariant Violation';
+ throw err;
+ }
+ error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret$1);
+ } catch (ex) {
+ error = ex;
+ }
+ if (error && !(error instanceof Error)) {
+ printWarning$1(
+ (componentName || 'React class') + ': type specification of ' +
+ location + ' `' + typeSpecName + '` is invalid; the type checker ' +
+ 'function must return `null` or an `Error` but returned a ' + typeof error + '. ' +
+ 'You may have forgotten to pass an argument to the type checker ' +
+ 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' +
+ 'shape all require an argument).'
+ );
+ }
+ if (error instanceof Error && !(error.message in loggedTypeFailures)) {
+ // Only monitor this failure once because there tends to be a lot of the
+ // same error.
+ loggedTypeFailures[error.message] = true;
+
+ var stack = getStack ? getStack() : '';
+
+ printWarning$1(
+ 'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '')
+ );
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Resets warning cache when testing.
+ *
+ * @private
+ */
+ checkPropTypes.resetWarningCache = function() {
+ {
+ loggedTypeFailures = {};
+ }
+ };
+
+ var checkPropTypes_1 = checkPropTypes;
+
+ var ReactDebugCurrentFrame$2 = null;
+ var ReactControlledValuePropTypes = {
+ checkPropTypes: null
+ };
+
+ {
+ ReactDebugCurrentFrame$2 = ReactSharedInternals.ReactDebugCurrentFrame;
+ var hasReadOnlyValue = {
+ button: true,
+ checkbox: true,
+ image: true,
+ hidden: true,
+ radio: true,
+ reset: true,
+ submit: true
+ };
+ var propTypes = {
+ value: function (props, propName, componentName) {
+ if (hasReadOnlyValue[props.type] || props.onChange || props.readOnly || props.disabled || props[propName] == null || enableDeprecatedFlareAPI ) {
+ return null;
+ }
+
+ return new Error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.');
+ },
+ checked: function (props, propName, componentName) {
+ if (props.onChange || props.readOnly || props.disabled || props[propName] == null || enableDeprecatedFlareAPI ) {
+ return null;
+ }
+
+ return new Error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.');
+ }
+ };
+ /**
+ * Provide a linked `value` attribute for controlled forms. You should not use
+ * this outside of the ReactDOM controlled form components.
+ */
+
+ ReactControlledValuePropTypes.checkPropTypes = function (tagName, props) {
+ checkPropTypes_1(propTypes, props, 'prop', tagName, ReactDebugCurrentFrame$2.getStackAddendum);
+ };
+ }
+
+ function isCheckable(elem) {
+ var type = elem.type;
+ var nodeName = elem.nodeName;
+ return nodeName && nodeName.toLowerCase() === 'input' && (type === 'checkbox' || type === 'radio');
+ }
+
+ function getTracker(node) {
+ return node._valueTracker;
+ }
+
+ function detachTracker(node) {
+ node._valueTracker = null;
+ }
+
+ function getValueFromNode(node) {
+ var value = '';
+
+ if (!node) {
+ return value;
+ }
+
+ if (isCheckable(node)) {
+ value = node.checked ? 'true' : 'false';
+ } else {
+ value = node.value;
+ }
+
+ return value;
+ }
+
+ function trackValueOnNode(node) {
+ var valueField = isCheckable(node) ? 'checked' : 'value';
+ var descriptor = Object.getOwnPropertyDescriptor(node.constructor.prototype, valueField);
+ var currentValue = '' + node[valueField]; // if someone has already defined a value or Safari, then bail
+ // and don't track value will cause over reporting of changes,
+ // but it's better then a hard failure
+ // (needed for certain tests that spyOn input values and Safari)
+
+ if (node.hasOwnProperty(valueField) || typeof descriptor === 'undefined' || typeof descriptor.get !== 'function' || typeof descriptor.set !== 'function') {
+ return;
+ }
+
+ var get = descriptor.get,
+ set = descriptor.set;
+ Object.defineProperty(node, valueField, {
+ configurable: true,
+ get: function () {
+ return get.call(this);
+ },
+ set: function (value) {
+ currentValue = '' + value;
+ set.call(this, value);
+ }
+ }); // We could've passed this the first time
+ // but it triggers a bug in IE11 and Edge 14/15.
+ // Calling defineProperty() again should be equivalent.
+ // https://github.com/facebook/react/issues/11768
+
+ Object.defineProperty(node, valueField, {
+ enumerable: descriptor.enumerable
+ });
+ var tracker = {
+ getValue: function () {
+ return currentValue;
+ },
+ setValue: function (value) {
+ currentValue = '' + value;
+ },
+ stopTracking: function () {
+ detachTracker(node);
+ delete node[valueField];
+ }
+ };
+ return tracker;
+ }
+
+ function track(node) {
+ if (getTracker(node)) {
+ return;
+ } // TODO: Once it's just Fiber we can move this to node._wrapperState
+
+
+ node._valueTracker = trackValueOnNode(node);
+ }
+ function updateValueIfChanged(node) {
+ if (!node) {
+ return false;
+ }
+
+ var tracker = getTracker(node); // if there is no tracker at this point it's unlikely
+ // that trying again will succeed
+
+ if (!tracker) {
+ return true;
+ }
+
+ var lastValue = tracker.getValue();
+ var nextValue = getValueFromNode(node);
+
+ if (nextValue !== lastValue) {
+ tracker.setValue(nextValue);
+ return true;
+ }
+
+ return false;
+ }
+
+ var didWarnValueDefaultValue = false;
+ var didWarnCheckedDefaultChecked = false;
+ var didWarnControlledToUncontrolled = false;
+ var didWarnUncontrolledToControlled = false;
+
+ function isControlled(props) {
+ var usesChecked = props.type === 'checkbox' || props.type === 'radio';
+ return usesChecked ? props.checked != null : props.value != null;
+ }
+ /**
+ * Implements an <input> host component that allows setting these optional
+ * props: `checked`, `value`, `defaultChecked`, and `defaultValue`.
+ *
+ * If `checked` or `value` are not supplied (or null/undefined), user actions
+ * that affect the checked state or value will trigger updates to the element.
+ *
+ * If they are supplied (and not null/undefined), the rendered element will not
+ * trigger updates to the element. Instead, the props must change in order for
+ * the rendered element to be updated.
+ *
+ * The rendered element will be initialized as unchecked (or `defaultChecked`)
+ * with an empty value (or `defaultValue`).
+ *
+ * See http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html
+ */
+
+
+ function getHostProps(element, props) {
+ var node = element;
+ var checked = props.checked;
+
+ var hostProps = _assign({}, props, {
+ defaultChecked: undefined,
+ defaultValue: undefined,
+ value: undefined,
+ checked: checked != null ? checked : node._wrapperState.initialChecked
+ });
+
+ return hostProps;
+ }
+ function initWrapperState(element, props) {
+ {
+ ReactControlledValuePropTypes.checkPropTypes('input', props);
+
+ if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnCheckedDefaultChecked) {
+ error('%s contains an input of type %s with both checked and defaultChecked props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the checked prop, or the defaultChecked prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component', props.type);
+
+ didWarnCheckedDefaultChecked = true;
+ }
+
+ if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) {
+ error('%s contains an input of type %s with both value and defaultValue props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component', props.type);
+
+ didWarnValueDefaultValue = true;
+ }
+ }
+
+ var node = element;
+ var defaultValue = props.defaultValue == null ? '' : props.defaultValue;
+ node._wrapperState = {
+ initialChecked: props.checked != null ? props.checked : props.defaultChecked,
+ initialValue: getToStringValue(props.value != null ? props.value : defaultValue),
+ controlled: isControlled(props)
+ };
+ }
+ function updateChecked(element, props) {
+ var node = element;
+ var checked = props.checked;
+
+ if (checked != null) {
+ setValueForProperty(node, 'checked', checked, false);
+ }
+ }
+ function updateWrapper(element, props) {
+ var node = element;
+
+ {
+ var controlled = isControlled(props);
+
+ if (!node._wrapperState.controlled && controlled && !didWarnUncontrolledToControlled) {
+ error('A component is changing an uncontrolled input of type %s to be controlled. ' + 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components', props.type);
+
+ didWarnUncontrolledToControlled = true;
+ }
+
+ if (node._wrapperState.controlled && !controlled && !didWarnControlledToUncontrolled) {
+ error('A component is changing a controlled input of type %s to be uncontrolled. ' + 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components', props.type);
+
+ didWarnControlledToUncontrolled = true;
+ }
+ }
+
+ updateChecked(element, props);
+ var value = getToStringValue(props.value);
+ var type = props.type;
+
+ if (value != null) {
+ if (type === 'number') {
+ if (value === 0 && node.value === '' || // We explicitly want to coerce to number here if possible.
+ // eslint-disable-next-line
+ node.value != value) {
+ node.value = toString(value);
+ }
+ } else if (node.value !== toString(value)) {
+ node.value = toString(value);
+ }
+ } else if (type === 'submit' || type === 'reset') {
+ // Submit/reset inputs need the attribute removed completely to avoid
+ // blank-text buttons.
+ node.removeAttribute('value');
+ return;
+ }
+
+ {
+ // When syncing the value attribute, the value comes from a cascade of
+ // properties:
+ // 1. The value React property
+ // 2. The defaultValue React property
+ // 3. Otherwise there should be no change
+ if (props.hasOwnProperty('value')) {
+ setDefaultValue(node, props.type, value);
+ } else if (props.hasOwnProperty('defaultValue')) {
+ setDefaultValue(node, props.type, getToStringValue(props.defaultValue));
+ }
+ }
+
+ {
+ // When syncing the checked attribute, it only changes when it needs
+ // to be removed, such as transitioning from a checkbox into a text input
+ if (props.checked == null && props.defaultChecked != null) {
+ node.defaultChecked = !!props.defaultChecked;
+ }
+ }
+ }
+ function postMountWrapper(element, props, isHydrating) {
+ var node = element; // Do not assign value if it is already set. This prevents user text input
+ // from being lost during SSR hydration.
+
+ if (props.hasOwnProperty('value') || props.hasOwnProperty('defaultValue')) {
+ var type = props.type;
+ var isButton = type === 'submit' || type === 'reset'; // Avoid setting value attribute on submit/reset inputs as it overrides the
+ // default value provided by the browser. See: #12872
+
+ if (isButton && (props.value === undefined || props.value === null)) {
+ return;
+ }
+
+ var initialValue = toString(node._wrapperState.initialValue); // Do not assign value if it is already set. This prevents user text input
+ // from being lost during SSR hydration.
+
+ if (!isHydrating) {
+ {
+ // When syncing the value attribute, the value property should use
+ // the wrapperState._initialValue property. This uses:
+ //
+ // 1. The value React property when present
+ // 2. The defaultValue React property when present
+ // 3. An empty string
+ if (initialValue !== node.value) {
+ node.value = initialValue;
+ }
+ }
+ }
+
+ {
+ // Otherwise, the value attribute is synchronized to the property,
+ // so we assign defaultValue to the same thing as the value property
+ // assignment step above.
+ node.defaultValue = initialValue;
+ }
+ } // Normally, we'd just do `node.checked = node.checked` upon initial mount, less this bug
+ // this is needed to work around a chrome bug where setting defaultChecked
+ // will sometimes influence the value of checked (even after detachment).
+ // Reference: https://bugs.chromium.org/p/chromium/issues/detail?id=608416
+ // We need to temporarily unset name to avoid disrupting radio button groups.
+
+
+ var name = node.name;
+
+ if (name !== '') {
+ node.name = '';
+ }
+
+ {
+ // When syncing the checked attribute, both the checked property and
+ // attribute are assigned at the same time using defaultChecked. This uses:
+ //
+ // 1. The checked React property when present
+ // 2. The defaultChecked React property when present
+ // 3. Otherwise, false
+ node.defaultChecked = !node.defaultChecked;
+ node.defaultChecked = !!node._wrapperState.initialChecked;
+ }
+
+ if (name !== '') {
+ node.name = name;
+ }
+ }
+ function restoreControlledState(element, props) {
+ var node = element;
+ updateWrapper(node, props);
+ updateNamedCousins(node, props);
+ }
+
+ function updateNamedCousins(rootNode, props) {
+ var name = props.name;
+
+ if (props.type === 'radio' && name != null) {
+ var queryRoot = rootNode;
+
+ while (queryRoot.parentNode) {
+ queryRoot = queryRoot.parentNode;
+ } // If `rootNode.form` was non-null, then we could try `form.elements`,
+ // but that sometimes behaves strangely in IE8. We could also try using
+ // `form.getElementsByName`, but that will only return direct children
+ // and won't include inputs that use the HTML5 `form=` attribute. Since
+ // the input might not even be in a form. It might not even be in the
+ // document. Let's just use the local `querySelectorAll` to ensure we don't
+ // miss anything.
+
+
+ var group = queryRoot.querySelectorAll('input[name=' + JSON.stringify('' + name) + '][type="radio"]');
+
+ for (var i = 0; i < group.length; i++) {
+ var otherNode = group[i];
+
+ if (otherNode === rootNode || otherNode.form !== rootNode.form) {
+ continue;
+ } // This will throw if radio buttons rendered by different copies of React
+ // and the same name are rendered into the same form (same as #1939).
+ // That's probably okay; we don't support it just as we don't support
+ // mixing React radio buttons with non-React ones.
+
+
+ var otherProps = getFiberCurrentPropsFromNode$1(otherNode);
+
+ if (!otherProps) {
+ {
+ throw Error( "ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported." );
+ }
+ } // We need update the tracked value on the named cousin since the value
+ // was changed but the input saw no event or value set
+
+
+ updateValueIfChanged(otherNode); // If this is a controlled radio button group, forcing the input that
+ // was previously checked to update will cause it to be come re-checked
+ // as appropriate.
+
+ updateWrapper(otherNode, otherProps);
+ }
+ }
+ } // In Chrome, assigning defaultValue to certain input types triggers input validation.
+ // For number inputs, the display value loses trailing decimal points. For email inputs,
+ // Chrome raises "The specified value <x> is not a valid email address".
+ //
+ // Here we check to see if the defaultValue has actually changed, avoiding these problems
+ // when the user is inputting text
+ //
+ // https://github.com/facebook/react/issues/7253
+
+
+ function setDefaultValue(node, type, value) {
+ if ( // Focused number inputs synchronize on blur. See ChangeEventPlugin.js
+ type !== 'number' || node.ownerDocument.activeElement !== node) {
+ if (value == null) {
+ node.defaultValue = toString(node._wrapperState.initialValue);
+ } else if (node.defaultValue !== toString(value)) {
+ node.defaultValue = toString(value);
+ }
+ }
+ }
+
+ var didWarnSelectedSetOnOption = false;
+ var didWarnInvalidChild = false;
+
+ function flattenChildren(children) {
+ var content = ''; // Flatten children. We'll warn if they are invalid
+ // during validateProps() which runs for hydration too.
+ // Note that this would throw on non-element objects.
+ // Elements are stringified (which is normally irrelevant
+ // but matters for <fbt>).
+
+ React.Children.forEach(children, function (child) {
+ if (child == null) {
+ return;
+ }
+
+ content += child; // Note: we don't warn about invalid children here.
+ // Instead, this is done separately below so that
+ // it happens during the hydration codepath too.
+ });
+ return content;
+ }
+ /**
+ * Implements an <option> host component that warns when `selected` is set.
+ */
+
+
+ function validateProps(element, props) {
+ {
+ // This mirrors the codepath above, but runs for hydration too.
+ // Warn about invalid children here so that client and hydration are consistent.
+ // TODO: this seems like it could cause a DEV-only throw for hydration
+ // if children contains a non-element object. We should try to avoid that.
+ if (typeof props.children === 'object' && props.children !== null) {
+ React.Children.forEach(props.children, function (child) {
+ if (child == null) {
+ return;
+ }
+
+ if (typeof child === 'string' || typeof child === 'number') {
+ return;
+ }
+
+ if (typeof child.type !== 'string') {
+ return;
+ }
+
+ if (!didWarnInvalidChild) {
+ didWarnInvalidChild = true;
+
+ error('Only strings and numbers are supported as <option> children.');
+ }
+ });
+ } // TODO: Remove support for `selected` in <option>.
+
+
+ if (props.selected != null && !didWarnSelectedSetOnOption) {
+ error('Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.');
+
+ didWarnSelectedSetOnOption = true;
+ }
+ }
+ }
+ function postMountWrapper$1(element, props) {
+ // value="" should make a value attribute (#6219)
+ if (props.value != null) {
+ element.setAttribute('value', toString(getToStringValue(props.value)));
+ }
+ }
+ function getHostProps$1(element, props) {
+ var hostProps = _assign({
+ children: undefined
+ }, props);
+
+ var content = flattenChildren(props.children);
+
+ if (content) {
+ hostProps.children = content;
+ }
+
+ return hostProps;
+ }
+
+ var didWarnValueDefaultValue$1;
+
+ {
+ didWarnValueDefaultValue$1 = false;
+ }
+
+ function getDeclarationErrorAddendum() {
+ var ownerName = getCurrentFiberOwnerNameInDevOrNull();
+
+ if (ownerName) {
+ return '\n\nCheck the render method of `' + ownerName + '`.';
+ }
+
+ return '';
+ }
+
+ var valuePropNames = ['value', 'defaultValue'];
+ /**
+ * Validation function for `value` and `defaultValue`.
+ */
+
+ function checkSelectPropTypes(props) {
+ {
+ ReactControlledValuePropTypes.checkPropTypes('select', props);
+
+ for (var i = 0; i < valuePropNames.length; i++) {
+ var propName = valuePropNames[i];
+
+ if (props[propName] == null) {
+ continue;
+ }
+
+ var isArray = Array.isArray(props[propName]);
+
+ if (props.multiple && !isArray) {
+ error('The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, getDeclarationErrorAddendum());
+ } else if (!props.multiple && isArray) {
+ error('The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, getDeclarationErrorAddendum());
+ }
+ }
+ }
+ }
+
+ function updateOptions(node, multiple, propValue, setDefaultSelected) {
+ var options = node.options;
+
+ if (multiple) {
+ var selectedValues = propValue;
+ var selectedValue = {};
+
+ for (var i = 0; i < selectedValues.length; i++) {
+ // Prefix to avoid chaos with special keys.
+ selectedValue['$' + selectedValues[i]] = true;
+ }
+
+ for (var _i = 0; _i < options.length; _i++) {
+ var selected = selectedValue.hasOwnProperty('$' + options[_i].value);
+
+ if (options[_i].selected !== selected) {
+ options[_i].selected = selected;
+ }
+
+ if (selected && setDefaultSelected) {
+ options[_i].defaultSelected = true;
+ }
+ }
+ } else {
+ // Do not set `select.value` as exact behavior isn't consistent across all
+ // browsers for all cases.
+ var _selectedValue = toString(getToStringValue(propValue));
+
+ var defaultSelected = null;
+
+ for (var _i2 = 0; _i2 < options.length; _i2++) {
+ if (options[_i2].value === _selectedValue) {
+ options[_i2].selected = true;
+
+ if (setDefaultSelected) {
+ options[_i2].defaultSelected = true;
+ }
+
+ return;
+ }
+
+ if (defaultSelected === null && !options[_i2].disabled) {
+ defaultSelected = options[_i2];
+ }
+ }
+
+ if (defaultSelected !== null) {
+ defaultSelected.selected = true;
+ }
+ }
+ }
+ /**
+ * Implements a <select> host component that allows optionally setting the
+ * props `value` and `defaultValue`. If `multiple` is false, the prop must be a
+ * stringable. If `multiple` is true, the prop must be an array of stringables.
+ *
+ * If `value` is not supplied (or null/undefined), user actions that change the
+ * selected option will trigger updates to the rendered options.
+ *
+ * If it is supplied (and not null/undefined), the rendered options will not
+ * update in response to user actions. Instead, the `value` prop must change in
+ * order for the rendered options to update.
+ *
+ * If `defaultValue` is provided, any options with the supplied values will be
+ * selected.
+ */
+
+
+ function getHostProps$2(element, props) {
+ return _assign({}, props, {
+ value: undefined
+ });
+ }
+ function initWrapperState$1(element, props) {
+ var node = element;
+
+ {
+ checkSelectPropTypes(props);
+ }
+
+ node._wrapperState = {
+ wasMultiple: !!props.multiple
+ };
+
+ {
+ if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue$1) {
+ error('Select elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled select ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components');
+
+ didWarnValueDefaultValue$1 = true;
+ }
+ }
+ }
+ function postMountWrapper$2(element, props) {
+ var node = element;
+ node.multiple = !!props.multiple;
+ var value = props.value;
+
+ if (value != null) {
+ updateOptions(node, !!props.multiple, value, false);
+ } else if (props.defaultValue != null) {
+ updateOptions(node, !!props.multiple, props.defaultValue, true);
+ }
+ }
+ function postUpdateWrapper(element, props) {
+ var node = element;
+ var wasMultiple = node._wrapperState.wasMultiple;
+ node._wrapperState.wasMultiple = !!props.multiple;
+ var value = props.value;
+
+ if (value != null) {
+ updateOptions(node, !!props.multiple, value, false);
+ } else if (wasMultiple !== !!props.multiple) {
+ // For simplicity, reapply `defaultValue` if `multiple` is toggled.
+ if (props.defaultValue != null) {
+ updateOptions(node, !!props.multiple, props.defaultValue, true);
+ } else {
+ // Revert the select back to its default unselected state.
+ updateOptions(node, !!props.multiple, props.multiple ? [] : '', false);
+ }
+ }
+ }
+ function restoreControlledState$1(element, props) {
+ var node = element;
+ var value = props.value;
+
+ if (value != null) {
+ updateOptions(node, !!props.multiple, value, false);
+ }
+ }
+
+ var didWarnValDefaultVal = false;
+
+ /**
+ * Implements a <textarea> host component that allows setting `value`, and
+ * `defaultValue`. This differs from the traditional DOM API because value is
+ * usually set as PCDATA children.
+ *
+ * If `value` is not supplied (or null/undefined), user actions that affect the
+ * value will trigger updates to the element.
+ *
+ * If `value` is supplied (and not null/undefined), the rendered element will
+ * not trigger updates to the element. Instead, the `value` prop must change in
+ * order for the rendered element to be updated.
+ *
+ * The rendered element will be initialized with an empty value, the prop
+ * `defaultValue` if specified, or the children content (deprecated).
+ */
+ function getHostProps$3(element, props) {
+ var node = element;
+
+ if (!(props.dangerouslySetInnerHTML == null)) {
+ {
+ throw Error( "`dangerouslySetInnerHTML` does not make sense on <textarea>." );
+ }
+ } // Always set children to the same thing. In IE9, the selection range will
+ // get reset if `textContent` is mutated. We could add a check in setTextContent
+ // to only set the value if/when the value differs from the node value (which would
+ // completely solve this IE9 bug), but Sebastian+Sophie seemed to like this
+ // solution. The value can be a boolean or object so that's why it's forced
+ // to be a string.
+
+
+ var hostProps = _assign({}, props, {
+ value: undefined,
+ defaultValue: undefined,
+ children: toString(node._wrapperState.initialValue)
+ });
+
+ return hostProps;
+ }
+ function initWrapperState$2(element, props) {
+ var node = element;
+
+ {
+ ReactControlledValuePropTypes.checkPropTypes('textarea', props);
+
+ if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValDefaultVal) {
+ error('%s contains a textarea with both value and defaultValue props. ' + 'Textarea elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled textarea ' + 'and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component');
+
+ didWarnValDefaultVal = true;
+ }
+ }
+
+ var initialValue = props.value; // Only bother fetching default value if we're going to use it
+
+ if (initialValue == null) {
+ var children = props.children,
+ defaultValue = props.defaultValue;
+
+ if (children != null) {
+ {
+ error('Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.');
+ }
+
+ {
+ if (!(defaultValue == null)) {
+ {
+ throw Error( "If you supply `defaultValue` on a <textarea>, do not pass children." );
+ }
+ }
+
+ if (Array.isArray(children)) {
+ if (!(children.length <= 1)) {
+ {
+ throw Error( "<textarea> can only have at most one child." );
+ }
+ }
+
+ children = children[0];
+ }
+
+ defaultValue = children;
+ }
+ }
+
+ if (defaultValue == null) {
+ defaultValue = '';
+ }
+
+ initialValue = defaultValue;
+ }
+
+ node._wrapperState = {
+ initialValue: getToStringValue(initialValue)
+ };
+ }
+ function updateWrapper$1(element, props) {
+ var node = element;
+ var value = getToStringValue(props.value);
+ var defaultValue = getToStringValue(props.defaultValue);
+
+ if (value != null) {
+ // Cast `value` to a string to ensure the value is set correctly. While
+ // browsers typically do this as necessary, jsdom doesn't.
+ var newValue = toString(value); // To avoid side effects (such as losing text selection), only set value if changed
+
+ if (newValue !== node.value) {
+ node.value = newValue;
+ }
+
+ if (props.defaultValue == null && node.defaultValue !== newValue) {
+ node.defaultValue = newValue;
+ }
+ }
+
+ if (defaultValue != null) {
+ node.defaultValue = toString(defaultValue);
+ }
+ }
+ function postMountWrapper$3(element, props) {
+ var node = element; // This is in postMount because we need access to the DOM node, which is not
+ // available until after the component has mounted.
+
+ var textContent = node.textContent; // Only set node.value if textContent is equal to the expected
+ // initial value. In IE10/IE11 there is a bug where the placeholder attribute
+ // will populate textContent as well.
+ // https://developer.microsoft.com/microsoft-edge/platform/issues/101525/
+
+ if (textContent === node._wrapperState.initialValue) {
+ if (textContent !== '' && textContent !== null) {
+ node.value = textContent;
+ }
+ }
+ }
+ function restoreControlledState$2(element, props) {
+ // DOM component is still mounted; update
+ updateWrapper$1(element, props);
+ }
+
+ var HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
+ var MATH_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
+ var SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
+ var Namespaces = {
+ html: HTML_NAMESPACE,
+ mathml: MATH_NAMESPACE,
+ svg: SVG_NAMESPACE
+ }; // Assumes there is no parent namespace.
+
+ function getIntrinsicNamespace(type) {
+ switch (type) {
+ case 'svg':
+ return SVG_NAMESPACE;
+
+ case 'math':
+ return MATH_NAMESPACE;
+
+ default:
+ return HTML_NAMESPACE;
+ }
+ }
+ function getChildNamespace(parentNamespace, type) {
+ if (parentNamespace == null || parentNamespace === HTML_NAMESPACE) {
+ // No (or default) parent namespace: potential entry point.
+ return getIntrinsicNamespace(type);
+ }
+
+ if (parentNamespace === SVG_NAMESPACE && type === 'foreignObject') {
+ // We're leaving SVG.
+ return HTML_NAMESPACE;
+ } // By default, pass namespace below.
+
+
+ return parentNamespace;
+ }
+
+ /* globals MSApp */
+
+ /**
+ * Create a function which has 'unsafe' privileges (required by windows8 apps)
+ */
+ var createMicrosoftUnsafeLocalFunction = function (func) {
+ if (typeof MSApp !== 'undefined' && MSApp.execUnsafeLocalFunction) {
+ return function (arg0, arg1, arg2, arg3) {
+ MSApp.execUnsafeLocalFunction(function () {
+ return func(arg0, arg1, arg2, arg3);
+ });
+ };
+ } else {
+ return func;
+ }
+ };
+
+ var reusableSVGContainer;
+ /**
+ * Set the innerHTML property of a node
+ *
+ * @param {DOMElement} node
+ * @param {string} html
+ * @internal
+ */
+
+ var setInnerHTML = createMicrosoftUnsafeLocalFunction(function (node, html) {
+ if (node.namespaceURI === Namespaces.svg) {
+
+ if (!('innerHTML' in node)) {
+ // IE does not have innerHTML for SVG nodes, so instead we inject the
+ // new markup in a temp node and then move the child nodes across into
+ // the target node
+ reusableSVGContainer = reusableSVGContainer || document.createElement('div');
+ reusableSVGContainer.innerHTML = '<svg>' + html.valueOf().toString() + '</svg>';
+ var svgNode = reusableSVGContainer.firstChild;
+
+ while (node.firstChild) {
+ node.removeChild(node.firstChild);
+ }
+
+ while (svgNode.firstChild) {
+ node.appendChild(svgNode.firstChild);
+ }
+
+ return;
+ }
+ }
+
+ node.innerHTML = html;
+ });
+
+ /**
+ * HTML nodeType values that represent the type of the node
+ */
+ var ELEMENT_NODE = 1;
+ var TEXT_NODE = 3;
+ var COMMENT_NODE = 8;
+ var DOCUMENT_NODE = 9;
+ var DOCUMENT_FRAGMENT_NODE = 11;
+
+ /**
+ * Set the textContent property of a node. For text updates, it's faster
+ * to set the `nodeValue` of the Text node directly instead of using
+ * `.textContent` which will remove the existing node and create a new one.
+ *
+ * @param {DOMElement} node
+ * @param {string} text
+ * @internal
+ */
+
+ var setTextContent = function (node, text) {
+ if (text) {
+ var firstChild = node.firstChild;
+
+ if (firstChild && firstChild === node.lastChild && firstChild.nodeType === TEXT_NODE) {
+ firstChild.nodeValue = text;
+ return;
+ }
+ }
+
+ node.textContent = text;
+ };
+
+ // Do not use the below two methods directly!
+ // Instead use constants exported from DOMTopLevelEventTypes in ReactDOM.
+ // (It is the only module that is allowed to access these methods.)
+ function unsafeCastStringToDOMTopLevelType(topLevelType) {
+ return topLevelType;
+ }
+ function unsafeCastDOMTopLevelTypeToString(topLevelType) {
+ return topLevelType;
+ }
+
+ /**
+ * Generate a mapping of standard vendor prefixes using the defined style property and event name.
+ *
+ * @param {string} styleProp
+ * @param {string} eventName
+ * @returns {object}
+ */
+
+ function makePrefixMap(styleProp, eventName) {
+ var prefixes = {};
+ prefixes[styleProp.toLowerCase()] = eventName.toLowerCase();
+ prefixes['Webkit' + styleProp] = 'webkit' + eventName;
+ prefixes['Moz' + styleProp] = 'moz' + eventName;
+ return prefixes;
+ }
+ /**
+ * A list of event names to a configurable list of vendor prefixes.
+ */
+
+
+ var vendorPrefixes = {
+ animationend: makePrefixMap('Animation', 'AnimationEnd'),
+ animationiteration: makePrefixMap('Animation', 'AnimationIteration'),
+ animationstart: makePrefixMap('Animation', 'AnimationStart'),
+ transitionend: makePrefixMap('Transition', 'TransitionEnd')
+ };
+ /**
+ * Event names that have already been detected and prefixed (if applicable).
+ */
+
+ var prefixedEventNames = {};
+ /**
+ * Element to check for prefixes on.
+ */
+
+ var style = {};
+ /**
+ * Bootstrap if a DOM exists.
+ */
+
+ if (canUseDOM) {
+ style = document.createElement('div').style; // On some platforms, in particular some releases of Android 4.x,
+ // the un-prefixed "animation" and "transition" properties are defined on the
+ // style object but the events that fire will still be prefixed, so we need
+ // to check if the un-prefixed events are usable, and if not remove them from the map.
+
+ if (!('AnimationEvent' in window)) {
+ delete vendorPrefixes.animationend.animation;
+ delete vendorPrefixes.animationiteration.animation;
+ delete vendorPrefixes.animationstart.animation;
+ } // Same as above
+
+
+ if (!('TransitionEvent' in window)) {
+ delete vendorPrefixes.transitionend.transition;
+ }
+ }
+ /**
+ * Attempts to determine the correct vendor prefixed event name.
+ *
+ * @param {string} eventName
+ * @returns {string}
+ */
+
+
+ function getVendorPrefixedEventName(eventName) {
+ if (prefixedEventNames[eventName]) {
+ return prefixedEventNames[eventName];
+ } else if (!vendorPrefixes[eventName]) {
+ return eventName;
+ }
+
+ var prefixMap = vendorPrefixes[eventName];
+
+ for (var styleProp in prefixMap) {
+ if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) {
+ return prefixedEventNames[eventName] = prefixMap[styleProp];
+ }
+ }
+
+ return eventName;
+ }
+
+ /**
+ * To identify top level events in ReactDOM, we use constants defined by this
+ * module. This is the only module that uses the unsafe* methods to express
+ * that the constants actually correspond to the browser event names. This lets
+ * us save some bundle size by avoiding a top level type -> event name map.
+ * The rest of ReactDOM code should import top level types from this file.
+ */
+
+ var TOP_ABORT = unsafeCastStringToDOMTopLevelType('abort');
+ var TOP_ANIMATION_END = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationend'));
+ var TOP_ANIMATION_ITERATION = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationiteration'));
+ var TOP_ANIMATION_START = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationstart'));
+ var TOP_BLUR = unsafeCastStringToDOMTopLevelType('blur');
+ var TOP_CAN_PLAY = unsafeCastStringToDOMTopLevelType('canplay');
+ var TOP_CAN_PLAY_THROUGH = unsafeCastStringToDOMTopLevelType('canplaythrough');
+ var TOP_CANCEL = unsafeCastStringToDOMTopLevelType('cancel');
+ var TOP_CHANGE = unsafeCastStringToDOMTopLevelType('change');
+ var TOP_CLICK = unsafeCastStringToDOMTopLevelType('click');
+ var TOP_CLOSE = unsafeCastStringToDOMTopLevelType('close');
+ var TOP_COMPOSITION_END = unsafeCastStringToDOMTopLevelType('compositionend');
+ var TOP_COMPOSITION_START = unsafeCastStringToDOMTopLevelType('compositionstart');
+ var TOP_COMPOSITION_UPDATE = unsafeCastStringToDOMTopLevelType('compositionupdate');
+ var TOP_CONTEXT_MENU = unsafeCastStringToDOMTopLevelType('contextmenu');
+ var TOP_COPY = unsafeCastStringToDOMTopLevelType('copy');
+ var TOP_CUT = unsafeCastStringToDOMTopLevelType('cut');
+ var TOP_DOUBLE_CLICK = unsafeCastStringToDOMTopLevelType('dblclick');
+ var TOP_AUX_CLICK = unsafeCastStringToDOMTopLevelType('auxclick');
+ var TOP_DRAG = unsafeCastStringToDOMTopLevelType('drag');
+ var TOP_DRAG_END = unsafeCastStringToDOMTopLevelType('dragend');
+ var TOP_DRAG_ENTER = unsafeCastStringToDOMTopLevelType('dragenter');
+ var TOP_DRAG_EXIT = unsafeCastStringToDOMTopLevelType('dragexit');
+ var TOP_DRAG_LEAVE = unsafeCastStringToDOMTopLevelType('dragleave');
+ var TOP_DRAG_OVER = unsafeCastStringToDOMTopLevelType('dragover');
+ var TOP_DRAG_START = unsafeCastStringToDOMTopLevelType('dragstart');
+ var TOP_DROP = unsafeCastStringToDOMTopLevelType('drop');
+ var TOP_DURATION_CHANGE = unsafeCastStringToDOMTopLevelType('durationchange');
+ var TOP_EMPTIED = unsafeCastStringToDOMTopLevelType('emptied');
+ var TOP_ENCRYPTED = unsafeCastStringToDOMTopLevelType('encrypted');
+ var TOP_ENDED = unsafeCastStringToDOMTopLevelType('ended');
+ var TOP_ERROR = unsafeCastStringToDOMTopLevelType('error');
+ var TOP_FOCUS = unsafeCastStringToDOMTopLevelType('focus');
+ var TOP_GOT_POINTER_CAPTURE = unsafeCastStringToDOMTopLevelType('gotpointercapture');
+ var TOP_INPUT = unsafeCastStringToDOMTopLevelType('input');
+ var TOP_INVALID = unsafeCastStringToDOMTopLevelType('invalid');
+ var TOP_KEY_DOWN = unsafeCastStringToDOMTopLevelType('keydown');
+ var TOP_KEY_PRESS = unsafeCastStringToDOMTopLevelType('keypress');
+ var TOP_KEY_UP = unsafeCastStringToDOMTopLevelType('keyup');
+ var TOP_LOAD = unsafeCastStringToDOMTopLevelType('load');
+ var TOP_LOAD_START = unsafeCastStringToDOMTopLevelType('loadstart');
+ var TOP_LOADED_DATA = unsafeCastStringToDOMTopLevelType('loadeddata');
+ var TOP_LOADED_METADATA = unsafeCastStringToDOMTopLevelType('loadedmetadata');
+ var TOP_LOST_POINTER_CAPTURE = unsafeCastStringToDOMTopLevelType('lostpointercapture');
+ var TOP_MOUSE_DOWN = unsafeCastStringToDOMTopLevelType('mousedown');
+ var TOP_MOUSE_MOVE = unsafeCastStringToDOMTopLevelType('mousemove');
+ var TOP_MOUSE_OUT = unsafeCastStringToDOMTopLevelType('mouseout');
+ var TOP_MOUSE_OVER = unsafeCastStringToDOMTopLevelType('mouseover');
+ var TOP_MOUSE_UP = unsafeCastStringToDOMTopLevelType('mouseup');
+ var TOP_PASTE = unsafeCastStringToDOMTopLevelType('paste');
+ var TOP_PAUSE = unsafeCastStringToDOMTopLevelType('pause');
+ var TOP_PLAY = unsafeCastStringToDOMTopLevelType('play');
+ var TOP_PLAYING = unsafeCastStringToDOMTopLevelType('playing');
+ var TOP_POINTER_CANCEL = unsafeCastStringToDOMTopLevelType('pointercancel');
+ var TOP_POINTER_DOWN = unsafeCastStringToDOMTopLevelType('pointerdown');
+ var TOP_POINTER_MOVE = unsafeCastStringToDOMTopLevelType('pointermove');
+ var TOP_POINTER_OUT = unsafeCastStringToDOMTopLevelType('pointerout');
+ var TOP_POINTER_OVER = unsafeCastStringToDOMTopLevelType('pointerover');
+ var TOP_POINTER_UP = unsafeCastStringToDOMTopLevelType('pointerup');
+ var TOP_PROGRESS = unsafeCastStringToDOMTopLevelType('progress');
+ var TOP_RATE_CHANGE = unsafeCastStringToDOMTopLevelType('ratechange');
+ var TOP_RESET = unsafeCastStringToDOMTopLevelType('reset');
+ var TOP_SCROLL = unsafeCastStringToDOMTopLevelType('scroll');
+ var TOP_SEEKED = unsafeCastStringToDOMTopLevelType('seeked');
+ var TOP_SEEKING = unsafeCastStringToDOMTopLevelType('seeking');
+ var TOP_SELECTION_CHANGE = unsafeCastStringToDOMTopLevelType('selectionchange');
+ var TOP_STALLED = unsafeCastStringToDOMTopLevelType('stalled');
+ var TOP_SUBMIT = unsafeCastStringToDOMTopLevelType('submit');
+ var TOP_SUSPEND = unsafeCastStringToDOMTopLevelType('suspend');
+ var TOP_TEXT_INPUT = unsafeCastStringToDOMTopLevelType('textInput');
+ var TOP_TIME_UPDATE = unsafeCastStringToDOMTopLevelType('timeupdate');
+ var TOP_TOGGLE = unsafeCastStringToDOMTopLevelType('toggle');
+ var TOP_TOUCH_CANCEL = unsafeCastStringToDOMTopLevelType('touchcancel');
+ var TOP_TOUCH_END = unsafeCastStringToDOMTopLevelType('touchend');
+ var TOP_TOUCH_MOVE = unsafeCastStringToDOMTopLevelType('touchmove');
+ var TOP_TOUCH_START = unsafeCastStringToDOMTopLevelType('touchstart');
+ var TOP_TRANSITION_END = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('transitionend'));
+ var TOP_VOLUME_CHANGE = unsafeCastStringToDOMTopLevelType('volumechange');
+ var TOP_WAITING = unsafeCastStringToDOMTopLevelType('waiting');
+ var TOP_WHEEL = unsafeCastStringToDOMTopLevelType('wheel'); // List of events that need to be individually attached to media elements.
+ // Note that events in this list will *not* be listened to at the top level
+ // unless they're explicitly whitelisted in `ReactBrowserEventEmitter.listenTo`.
+
+ var mediaEventTypes = [TOP_ABORT, TOP_CAN_PLAY, TOP_CAN_PLAY_THROUGH, TOP_DURATION_CHANGE, TOP_EMPTIED, TOP_ENCRYPTED, TOP_ENDED, TOP_ERROR, TOP_LOADED_DATA, TOP_LOADED_METADATA, TOP_LOAD_START, TOP_PAUSE, TOP_PLAY, TOP_PLAYING, TOP_PROGRESS, TOP_RATE_CHANGE, TOP_SEEKED, TOP_SEEKING, TOP_STALLED, TOP_SUSPEND, TOP_TIME_UPDATE, TOP_VOLUME_CHANGE, TOP_WAITING];
+ function getRawEventName(topLevelType) {
+ return unsafeCastDOMTopLevelTypeToString(topLevelType);
+ }
+
+ var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map; // prettier-ignore
+
+ var elementListenerMap = new PossiblyWeakMap();
+ function getListenerMapForElement(element) {
+ var listenerMap = elementListenerMap.get(element);
+
+ if (listenerMap === undefined) {
+ listenerMap = new Map();
+ elementListenerMap.set(element, listenerMap);
+ }
+
+ return listenerMap;
+ }
+
+ /**
+ * `ReactInstanceMap` maintains a mapping from a public facing stateful
+ * instance (key) and the internal representation (value). This allows public
+ * methods to accept the user facing instance as an argument and map them back
+ * to internal methods.
+ *
+ * Note that this module is currently shared and assumed to be stateless.
+ * If this becomes an actual Map, that will break.
+ */
+ function get(key) {
+ return key._reactInternalFiber;
+ }
+ function has$1(key) {
+ return key._reactInternalFiber !== undefined;
+ }
+ function set(key, value) {
+ key._reactInternalFiber = value;
+ }
+
+ // Don't change these two values. They're used by React Dev Tools.
+ var NoEffect =
+ /* */
+ 0;
+ var PerformedWork =
+ /* */
+ 1; // You can change the rest (and add more).
+
+ var Placement =
+ /* */
+ 2;
+ var Update =
+ /* */
+ 4;
+ var PlacementAndUpdate =
+ /* */
+ 6;
+ var Deletion =
+ /* */
+ 8;
+ var ContentReset =
+ /* */
+ 16;
+ var Callback =
+ /* */
+ 32;
+ var DidCapture =
+ /* */
+ 64;
+ var Ref =
+ /* */
+ 128;
+ var Snapshot =
+ /* */
+ 256;
+ var Passive =
+ /* */
+ 512;
+ var Hydrating =
+ /* */
+ 1024;
+ var HydratingAndUpdate =
+ /* */
+ 1028; // Passive & Update & Callback & Ref & Snapshot
+
+ var LifecycleEffectMask =
+ /* */
+ 932; // Union of all host effects
+
+ var HostEffectMask =
+ /* */
+ 2047;
+ var Incomplete =
+ /* */
+ 2048;
+ var ShouldCapture =
+ /* */
+ 4096;
+
+ var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
+ function getNearestMountedFiber(fiber) {
+ var node = fiber;
+ var nearestMounted = fiber;
+
+ if (!fiber.alternate) {
+ // If there is no alternate, this might be a new tree that isn't inserted
+ // yet. If it is, then it will have a pending insertion effect on it.
+ var nextNode = node;
+
+ do {
+ node = nextNode;
+
+ if ((node.effectTag & (Placement | Hydrating)) !== NoEffect) {
+ // This is an insertion or in-progress hydration. The nearest possible
+ // mounted fiber is the parent but we need to continue to figure out
+ // if that one is still mounted.
+ nearestMounted = node.return;
+ }
+
+ nextNode = node.return;
+ } while (nextNode);
+ } else {
+ while (node.return) {
+ node = node.return;
+ }
+ }
+
+ if (node.tag === HostRoot) {
+ // TODO: Check if this was a nested HostRoot when used with
+ // renderContainerIntoSubtree.
+ return nearestMounted;
+ } // If we didn't hit the root, that means that we're in an disconnected tree
+ // that has been unmounted.
+
+
+ return null;
+ }
+ function getSuspenseInstanceFromFiber(fiber) {
+ if (fiber.tag === SuspenseComponent) {
+ var suspenseState = fiber.memoizedState;
+
+ if (suspenseState === null) {
+ var current = fiber.alternate;
+
+ if (current !== null) {
+ suspenseState = current.memoizedState;
+ }
+ }
+
+ if (suspenseState !== null) {
+ return suspenseState.dehydrated;
+ }
+ }
+
+ return null;
+ }
+ function getContainerFromFiber(fiber) {
+ return fiber.tag === HostRoot ? fiber.stateNode.containerInfo : null;
+ }
+ function isFiberMounted(fiber) {
+ return getNearestMountedFiber(fiber) === fiber;
+ }
+ function isMounted(component) {
+ {
+ var owner = ReactCurrentOwner.current;
+
+ if (owner !== null && owner.tag === ClassComponent) {
+ var ownerFiber = owner;
+ var instance = ownerFiber.stateNode;
+
+ if (!instance._warnedAboutRefsInRender) {
+ error('%s is accessing isMounted inside its render() function. ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', getComponentName(ownerFiber.type) || 'A component');
+ }
+
+ instance._warnedAboutRefsInRender = true;
+ }
+ }
+
+ var fiber = get(component);
+
+ if (!fiber) {
+ return false;
+ }
+
+ return getNearestMountedFiber(fiber) === fiber;
+ }
+
+ function assertIsMounted(fiber) {
+ if (!(getNearestMountedFiber(fiber) === fiber)) {
+ {
+ throw Error( "Unable to find node on an unmounted component." );
+ }
+ }
+ }
+
+ function findCurrentFiberUsingSlowPath(fiber) {
+ var alternate = fiber.alternate;
+
+ if (!alternate) {
+ // If there is no alternate, then we only need to check if it is mounted.
+ var nearestMounted = getNearestMountedFiber(fiber);
+
+ if (!(nearestMounted !== null)) {
+ {
+ throw Error( "Unable to find node on an unmounted component." );
+ }
+ }
+
+ if (nearestMounted !== fiber) {
+ return null;
+ }
+
+ return fiber;
+ } // If we have two possible branches, we'll walk backwards up to the root
+ // to see what path the root points to. On the way we may hit one of the
+ // special cases and we'll deal with them.
+
+
+ var a = fiber;
+ var b = alternate;
+
+ while (true) {
+ var parentA = a.return;
+
+ if (parentA === null) {
+ // We're at the root.
+ break;
+ }
+
+ var parentB = parentA.alternate;
+
+ if (parentB === null) {
+ // There is no alternate. This is an unusual case. Currently, it only
+ // happens when a Suspense component is hidden. An extra fragment fiber
+ // is inserted in between the Suspense fiber and its children. Skip
+ // over this extra fragment fiber and proceed to the next parent.
+ var nextParent = parentA.return;
+
+ if (nextParent !== null) {
+ a = b = nextParent;
+ continue;
+ } // If there's no parent, we're at the root.
+
+
+ break;
+ } // If both copies of the parent fiber point to the same child, we can
+ // assume that the child is current. This happens when we bailout on low
+ // priority: the bailed out fiber's child reuses the current child.
+
+
+ if (parentA.child === parentB.child) {
+ var child = parentA.child;
+
+ while (child) {
+ if (child === a) {
+ // We've determined that A is the current branch.
+ assertIsMounted(parentA);
+ return fiber;
+ }
+
+ if (child === b) {
+ // We've determined that B is the current branch.
+ assertIsMounted(parentA);
+ return alternate;
+ }
+
+ child = child.sibling;
+ } // We should never have an alternate for any mounting node. So the only
+ // way this could possibly happen is if this was unmounted, if at all.
+
+
+ {
+ {
+ throw Error( "Unable to find node on an unmounted component." );
+ }
+ }
+ }
+
+ if (a.return !== b.return) {
+ // The return pointer of A and the return pointer of B point to different
+ // fibers. We assume that return pointers never criss-cross, so A must
+ // belong to the child set of A.return, and B must belong to the child
+ // set of B.return.
+ a = parentA;
+ b = parentB;
+ } else {
+ // The return pointers point to the same fiber. We'll have to use the
+ // default, slow path: scan the child sets of each parent alternate to see
+ // which child belongs to which set.
+ //
+ // Search parent A's child set
+ var didFindChild = false;
+ var _child = parentA.child;
+
+ while (_child) {
+ if (_child === a) {
+ didFindChild = true;
+ a = parentA;
+ b = parentB;
+ break;
+ }
+
+ if (_child === b) {
+ didFindChild = true;
+ b = parentA;
+ a = parentB;
+ break;
+ }
+
+ _child = _child.sibling;
+ }
+
+ if (!didFindChild) {
+ // Search parent B's child set
+ _child = parentB.child;
+
+ while (_child) {
+ if (_child === a) {
+ didFindChild = true;
+ a = parentB;
+ b = parentA;
+ break;
+ }
+
+ if (_child === b) {
+ didFindChild = true;
+ b = parentB;
+ a = parentA;
+ break;
+ }
+
+ _child = _child.sibling;
+ }
+
+ if (!didFindChild) {
+ {
+ throw Error( "Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue." );
+ }
+ }
+ }
+ }
+
+ if (!(a.alternate === b)) {
+ {
+ throw Error( "Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue." );
+ }
+ }
+ } // If the root is not a host container, we're in a disconnected tree. I.e.
+ // unmounted.
+
+
+ if (!(a.tag === HostRoot)) {
+ {
+ throw Error( "Unable to find node on an unmounted component." );
+ }
+ }
+
+ if (a.stateNode.current === a) {
+ // We've determined that A is the current branch.
+ return fiber;
+ } // Otherwise B has to be current branch.
+
+
+ return alternate;
+ }
+ function findCurrentHostFiber(parent) {
+ var currentParent = findCurrentFiberUsingSlowPath(parent);
+
+ if (!currentParent) {
+ return null;
+ } // Next we'll drill down this component to find the first HostComponent/Text.
+
+
+ var node = currentParent;
+
+ while (true) {
+ if (node.tag === HostComponent || node.tag === HostText) {
+ return node;
+ } else if (node.child) {
+ node.child.return = node;
+ node = node.child;
+ continue;
+ }
+
+ if (node === currentParent) {
+ return null;
+ }
+
+ while (!node.sibling) {
+ if (!node.return || node.return === currentParent) {
+ return null;
+ }
+
+ node = node.return;
+ }
+
+ node.sibling.return = node.return;
+ node = node.sibling;
+ } // Flow needs the return null here, but ESLint complains about it.
+ // eslint-disable-next-line no-unreachable
+
+
+ return null;
+ }
+ function findCurrentHostFiberWithNoPortals(parent) {
+ var currentParent = findCurrentFiberUsingSlowPath(parent);
+
+ if (!currentParent) {
+ return null;
+ } // Next we'll drill down this component to find the first HostComponent/Text.
+
+
+ var node = currentParent;
+
+ while (true) {
+ if (node.tag === HostComponent || node.tag === HostText || enableFundamentalAPI ) {
+ return node;
+ } else if (node.child && node.tag !== HostPortal) {
+ node.child.return = node;
+ node = node.child;
+ continue;
+ }
+
+ if (node === currentParent) {
+ return null;
+ }
+
+ while (!node.sibling) {
+ if (!node.return || node.return === currentParent) {
+ return null;
+ }
+
+ node = node.return;
+ }
+
+ node.sibling.return = node.return;
+ node = node.sibling;
+ } // Flow needs the return null here, but ESLint complains about it.
+ // eslint-disable-next-line no-unreachable
+
+
+ return null;
+ }
+
+ /**
+ * Accumulates items that must not be null or undefined into the first one. This
+ * is used to conserve memory by avoiding array allocations, and thus sacrifices
+ * API cleanness. Since `current` can be null before being passed in and not
+ * null after this function, make sure to assign it back to `current`:
+ *
+ * `a = accumulateInto(a, b);`
+ *
+ * This API should be sparingly used. Try `accumulate` for something cleaner.
+ *
+ * @return {*|array<*>} An accumulation of items.
+ */
+
+ function accumulateInto(current, next) {
+ if (!(next != null)) {
+ {
+ throw Error( "accumulateInto(...): Accumulated items must not be null or undefined." );
+ }
+ }
+
+ if (current == null) {
+ return next;
+ } // Both are not empty. Warning: Never call x.concat(y) when you are not
+ // certain that x is an Array (x could be a string with concat method).
+
+
+ if (Array.isArray(current)) {
+ if (Array.isArray(next)) {
+ current.push.apply(current, next);
+ return current;
+ }
+
+ current.push(next);
+ return current;
+ }
+
+ if (Array.isArray(next)) {
+ // A bit too dangerous to mutate `next`.
+ return [current].concat(next);
+ }
+
+ return [current, next];
+ }
+
+ /**
+ * @param {array} arr an "accumulation" of items which is either an Array or
+ * a single item. Useful when paired with the `accumulate` module. This is a
+ * simple utility that allows us to reason about a collection of items, but
+ * handling the case when there is exactly one item (and we do not need to
+ * allocate an array).
+ * @param {function} cb Callback invoked with each element or a collection.
+ * @param {?} [scope] Scope used as `this` in a callback.
+ */
+ function forEachAccumulated(arr, cb, scope) {
+ if (Array.isArray(arr)) {
+ arr.forEach(cb, scope);
+ } else if (arr) {
+ cb.call(scope, arr);
+ }
+ }
+
+ /**
+ * Internal queue of events that have accumulated their dispatches and are
+ * waiting to have their dispatches executed.
+ */
+
+ var eventQueue = null;
+ /**
+ * Dispatches an event and releases it back into the pool, unless persistent.
+ *
+ * @param {?object} event Synthetic event to be dispatched.
+ * @private
+ */
+
+ var executeDispatchesAndRelease = function (event) {
+ if (event) {
+ executeDispatchesInOrder(event);
+
+ if (!event.isPersistent()) {
+ event.constructor.release(event);
+ }
+ }
+ };
+
+ var executeDispatchesAndReleaseTopLevel = function (e) {
+ return executeDispatchesAndRelease(e);
+ };
+
+ function runEventsInBatch(events) {
+ if (events !== null) {
+ eventQueue = accumulateInto(eventQueue, events);
+ } // Set `eventQueue` to null before processing it so that we can tell if more
+ // events get enqueued while processing.
+
+
+ var processingEventQueue = eventQueue;
+ eventQueue = null;
+
+ if (!processingEventQueue) {
+ return;
+ }
+
+ forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel);
+
+ if (!!eventQueue) {
+ {
+ throw Error( "processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented." );
+ }
+ } // This would be a good time to rethrow if any of the event handlers threw.
+
+
+ rethrowCaughtError();
+ }
+
+ /**
+ * Gets the target node from a native browser event by accounting for
+ * inconsistencies in browser DOM APIs.
+ *
+ * @param {object} nativeEvent Native browser event.
+ * @return {DOMEventTarget} Target node.
+ */
+
+ function getEventTarget(nativeEvent) {
+ // Fallback to nativeEvent.srcElement for IE9
+ // https://github.com/facebook/react/issues/12506
+ var target = nativeEvent.target || nativeEvent.srcElement || window; // Normalize SVG <use> element events #4963
+
+ if (target.correspondingUseElement) {
+ target = target.correspondingUseElement;
+ } // Safari may fire events on text nodes (Node.TEXT_NODE is 3).
+ // @see http://www.quirksmode.org/js/events_properties.html
+
+
+ return target.nodeType === TEXT_NODE ? target.parentNode : target;
+ }
+
+ /**
+ * Checks if an event is supported in the current execution environment.
+ *
+ * NOTE: This will not work correctly for non-generic events such as `change`,
+ * `reset`, `load`, `error`, and `select`.
+ *
+ * Borrows from Modernizr.
+ *
+ * @param {string} eventNameSuffix Event name, e.g. "click".
+ * @return {boolean} True if the event is supported.
+ * @internal
+ * @license Modernizr 3.0.0pre (Custom Build) | MIT
+ */
+
+ function isEventSupported(eventNameSuffix) {
+ if (!canUseDOM) {
+ return false;
+ }
+
+ var eventName = 'on' + eventNameSuffix;
+ var isSupported = eventName in document;
+
+ if (!isSupported) {
+ var element = document.createElement('div');
+ element.setAttribute(eventName, 'return;');
+ isSupported = typeof element[eventName] === 'function';
+ }
+
+ return isSupported;
+ }
+
+ /**
+ * Summary of `DOMEventPluginSystem` event handling:
+ *
+ * - Top-level delegation is used to trap most native browser events. This
+ * may only occur in the main thread and is the responsibility of
+ * ReactDOMEventListener, which is injected and can therefore support
+ * pluggable event sources. This is the only work that occurs in the main
+ * thread.
+ *
+ * - We normalize and de-duplicate events to account for browser quirks. This
+ * may be done in the worker thread.
+ *
+ * - Forward these native events (with the associated top-level type used to
+ * trap it) to `EventPluginRegistry`, which in turn will ask plugins if they want
+ * to extract any synthetic events.
+ *
+ * - The `EventPluginRegistry` will then process each event by annotating them with
+ * "dispatches", a sequence of listeners and IDs that care about that event.
+ *
+ * - The `EventPluginRegistry` then dispatches the events.
+ *
+ * Overview of React and the event system:
+ *
+ * +------------+ .
+ * | DOM | .
+ * +------------+ .
+ * | .
+ * v .
+ * +------------+ .
+ * | ReactEvent | .
+ * | Listener | .
+ * +------------+ . +-----------+
+ * | . +--------+|SimpleEvent|
+ * | . | |Plugin |
+ * +-----|------+ . v +-----------+
+ * | | | . +--------------+ +------------+
+ * | +-----------.--->|PluginRegistry| | Event |
+ * | | . | | +-----------+ | Propagators|
+ * | ReactEvent | . | | |TapEvent | |------------|
+ * | Emitter | . | |<---+|Plugin | |other plugin|
+ * | | . | | +-----------+ | utilities |
+ * | +-----------.--->| | +------------+
+ * | | | . +--------------+
+ * +-----|------+ . ^ +-----------+
+ * | . | |Enter/Leave|
+ * + . +-------+|Plugin |
+ * +-------------+ . +-----------+
+ * | application | .
+ * |-------------| .
+ * | | .
+ * | | .
+ * +-------------+ .
+ * .
+ * React Core . General Purpose Event Plugin System
+ */
+
+ var CALLBACK_BOOKKEEPING_POOL_SIZE = 10;
+ var callbackBookkeepingPool = [];
+
+ function releaseTopLevelCallbackBookKeeping(instance) {
+ instance.topLevelType = null;
+ instance.nativeEvent = null;
+ instance.targetInst = null;
+ instance.ancestors.length = 0;
+
+ if (callbackBookkeepingPool.length < CALLBACK_BOOKKEEPING_POOL_SIZE) {
+ callbackBookkeepingPool.push(instance);
+ }
+ } // Used to store ancestor hierarchy in top level callback
+
+
+ function getTopLevelCallbackBookKeeping(topLevelType, nativeEvent, targetInst, eventSystemFlags) {
+ if (callbackBookkeepingPool.length) {
+ var instance = callbackBookkeepingPool.pop();
+ instance.topLevelType = topLevelType;
+ instance.eventSystemFlags = eventSystemFlags;
+ instance.nativeEvent = nativeEvent;
+ instance.targetInst = targetInst;
+ return instance;
+ }
+
+ return {
+ topLevelType: topLevelType,
+ eventSystemFlags: eventSystemFlags,
+ nativeEvent: nativeEvent,
+ targetInst: targetInst,
+ ancestors: []
+ };
+ }
+ /**
+ * Find the deepest React component completely containing the root of the
+ * passed-in instance (for use when entire React trees are nested within each
+ * other). If React trees are not nested, returns null.
+ */
+
+
+ function findRootContainerNode(inst) {
+ if (inst.tag === HostRoot) {
+ return inst.stateNode.containerInfo;
+ } // TODO: It may be a good idea to cache this to prevent unnecessary DOM
+ // traversal, but caching is difficult to do correctly without using a
+ // mutation observer to listen for all DOM changes.
+
+
+ while (inst.return) {
+ inst = inst.return;
+ }
+
+ if (inst.tag !== HostRoot) {
+ // This can happen if we're in a detached tree.
+ return null;
+ }
+
+ return inst.stateNode.containerInfo;
+ }
+ /**
+ * Allows registered plugins an opportunity to extract events from top-level
+ * native browser events.
+ *
+ * @return {*} An accumulation of synthetic events.
+ * @internal
+ */
+
+
+ function extractPluginEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {
+ var events = null;
+
+ for (var i = 0; i < plugins.length; i++) {
+ // Not every plugin in the ordering may be loaded at runtime.
+ var possiblePlugin = plugins[i];
+
+ if (possiblePlugin) {
+ var extractedEvents = possiblePlugin.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags);
+
+ if (extractedEvents) {
+ events = accumulateInto(events, extractedEvents);
+ }
+ }
+ }
+
+ return events;
+ }
+
+ function runExtractedPluginEventsInBatch(topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {
+ var events = extractPluginEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags);
+ runEventsInBatch(events);
+ }
+
+ function handleTopLevel(bookKeeping) {
+ var targetInst = bookKeeping.targetInst; // Loop through the hierarchy, in case there's any nested components.
+ // It's important that we build the array of ancestors before calling any
+ // event handlers, because event handlers can modify the DOM, leading to
+ // inconsistencies with ReactMount's node cache. See #1105.
+
+ var ancestor = targetInst;
+
+ do {
+ if (!ancestor) {
+ var ancestors = bookKeeping.ancestors;
+ ancestors.push(ancestor);
+ break;
+ }
+
+ var root = findRootContainerNode(ancestor);
+
+ if (!root) {
+ break;
+ }
+
+ var tag = ancestor.tag;
+
+ if (tag === HostComponent || tag === HostText) {
+ bookKeeping.ancestors.push(ancestor);
+ }
+
+ ancestor = getClosestInstanceFromNode(root);
+ } while (ancestor);
+
+ for (var i = 0; i < bookKeeping.ancestors.length; i++) {
+ targetInst = bookKeeping.ancestors[i];
+ var eventTarget = getEventTarget(bookKeeping.nativeEvent);
+ var topLevelType = bookKeeping.topLevelType;
+ var nativeEvent = bookKeeping.nativeEvent;
+ var eventSystemFlags = bookKeeping.eventSystemFlags; // If this is the first ancestor, we mark it on the system flags
+
+ if (i === 0) {
+ eventSystemFlags |= IS_FIRST_ANCESTOR;
+ }
+
+ runExtractedPluginEventsInBatch(topLevelType, targetInst, nativeEvent, eventTarget, eventSystemFlags);
+ }
+ }
+
+ function dispatchEventForLegacyPluginEventSystem(topLevelType, eventSystemFlags, nativeEvent, targetInst) {
+ var bookKeeping = getTopLevelCallbackBookKeeping(topLevelType, nativeEvent, targetInst, eventSystemFlags);
+
+ try {
+ // Event queue being processed in the same cycle allows
+ // `preventDefault`.
+ batchedEventUpdates(handleTopLevel, bookKeeping);
+ } finally {
+ releaseTopLevelCallbackBookKeeping(bookKeeping);
+ }
+ }
+ /**
+ * We listen for bubbled touch events on the document object.
+ *
+ * Firefox v8.01 (and possibly others) exhibited strange behavior when
+ * mounting `onmousemove` events at some node that was not the document
+ * element. The symptoms were that if your mouse is not moving over something
+ * contained within that mount point (for example on the background) the
+ * top-level listeners for `onmousemove` won't be called. However, if you
+ * register the `mousemove` on the document object, then it will of course
+ * catch all `mousemove`s. This along with iOS quirks, justifies restricting
+ * top-level listeners to the document object only, at least for these
+ * movement types of events and possibly all events.
+ *
+ * @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
+ *
+ * Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but
+ * they bubble to document.
+ *
+ * @param {string} registrationName Name of listener (e.g. `onClick`).
+ * @param {object} mountAt Container where to mount the listener
+ */
+
+ function legacyListenToEvent(registrationName, mountAt) {
+ var listenerMap = getListenerMapForElement(mountAt);
+ var dependencies = registrationNameDependencies[registrationName];
+
+ for (var i = 0; i < dependencies.length; i++) {
+ var dependency = dependencies[i];
+ legacyListenToTopLevelEvent(dependency, mountAt, listenerMap);
+ }
+ }
+ function legacyListenToTopLevelEvent(topLevelType, mountAt, listenerMap) {
+ if (!listenerMap.has(topLevelType)) {
+ switch (topLevelType) {
+ case TOP_SCROLL:
+ trapCapturedEvent(TOP_SCROLL, mountAt);
+ break;
+
+ case TOP_FOCUS:
+ case TOP_BLUR:
+ trapCapturedEvent(TOP_FOCUS, mountAt);
+ trapCapturedEvent(TOP_BLUR, mountAt); // We set the flag for a single dependency later in this function,
+ // but this ensures we mark both as attached rather than just one.
+
+ listenerMap.set(TOP_BLUR, null);
+ listenerMap.set(TOP_FOCUS, null);
+ break;
+
+ case TOP_CANCEL:
+ case TOP_CLOSE:
+ if (isEventSupported(getRawEventName(topLevelType))) {
+ trapCapturedEvent(topLevelType, mountAt);
+ }
+
+ break;
+
+ case TOP_INVALID:
+ case TOP_SUBMIT:
+ case TOP_RESET:
+ // We listen to them on the target DOM elements.
+ // Some of them bubble so we don't want them to fire twice.
+ break;
+
+ default:
+ // By default, listen on the top level to all non-media events.
+ // Media events don't bubble so adding the listener wouldn't do anything.
+ var isMediaEvent = mediaEventTypes.indexOf(topLevelType) !== -1;
+
+ if (!isMediaEvent) {
+ trapBubbledEvent(topLevelType, mountAt);
+ }
+
+ break;
+ }
+
+ listenerMap.set(topLevelType, null);
+ }
+ }
+ function isListeningToAllDependencies(registrationName, mountAt) {
+ var listenerMap = getListenerMapForElement(mountAt);
+ var dependencies = registrationNameDependencies[registrationName];
+
+ for (var i = 0; i < dependencies.length; i++) {
+ var dependency = dependencies[i];
+
+ if (!listenerMap.has(dependency)) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ var attemptUserBlockingHydration;
+ function setAttemptUserBlockingHydration(fn) {
+ attemptUserBlockingHydration = fn;
+ }
+ var attemptContinuousHydration;
+ function setAttemptContinuousHydration(fn) {
+ attemptContinuousHydration = fn;
+ }
+ var attemptHydrationAtCurrentPriority;
+ function setAttemptHydrationAtCurrentPriority(fn) {
+ attemptHydrationAtCurrentPriority = fn;
+ } // TODO: Upgrade this definition once we're on a newer version of Flow that
+ var hasScheduledReplayAttempt = false; // The queue of discrete events to be replayed.
+
+ var queuedDiscreteEvents = []; // Indicates if any continuous event targets are non-null for early bailout.
+ // if the last target was dehydrated.
+
+ var queuedFocus = null;
+ var queuedDrag = null;
+ var queuedMouse = null; // For pointer events there can be one latest event per pointerId.
+
+ var queuedPointers = new Map();
+ var queuedPointerCaptures = new Map(); // We could consider replaying selectionchange and touchmoves too.
+
+ var queuedExplicitHydrationTargets = [];
+ function hasQueuedDiscreteEvents() {
+ return queuedDiscreteEvents.length > 0;
+ }
+ var discreteReplayableEvents = [TOP_MOUSE_DOWN, TOP_MOUSE_UP, TOP_TOUCH_CANCEL, TOP_TOUCH_END, TOP_TOUCH_START, TOP_AUX_CLICK, TOP_DOUBLE_CLICK, TOP_POINTER_CANCEL, TOP_POINTER_DOWN, TOP_POINTER_UP, TOP_DRAG_END, TOP_DRAG_START, TOP_DROP, TOP_COMPOSITION_END, TOP_COMPOSITION_START, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_INPUT, TOP_TEXT_INPUT, TOP_CLOSE, TOP_CANCEL, TOP_COPY, TOP_CUT, TOP_PASTE, TOP_CLICK, TOP_CHANGE, TOP_CONTEXT_MENU, TOP_RESET, TOP_SUBMIT];
+ var continuousReplayableEvents = [TOP_FOCUS, TOP_BLUR, TOP_DRAG_ENTER, TOP_DRAG_LEAVE, TOP_MOUSE_OVER, TOP_MOUSE_OUT, TOP_POINTER_OVER, TOP_POINTER_OUT, TOP_GOT_POINTER_CAPTURE, TOP_LOST_POINTER_CAPTURE];
+ function isReplayableDiscreteEvent(eventType) {
+ return discreteReplayableEvents.indexOf(eventType) > -1;
+ }
+
+ function trapReplayableEventForDocument(topLevelType, document, listenerMap) {
+ legacyListenToTopLevelEvent(topLevelType, document, listenerMap);
+ }
+
+ function eagerlyTrapReplayableEvents(container, document) {
+ var listenerMapForDoc = getListenerMapForElement(document); // Discrete
+
+ discreteReplayableEvents.forEach(function (topLevelType) {
+ trapReplayableEventForDocument(topLevelType, document, listenerMapForDoc);
+ }); // Continuous
+
+ continuousReplayableEvents.forEach(function (topLevelType) {
+ trapReplayableEventForDocument(topLevelType, document, listenerMapForDoc);
+ });
+ }
+
+ function createQueuedReplayableEvent(blockedOn, topLevelType, eventSystemFlags, container, nativeEvent) {
+ return {
+ blockedOn: blockedOn,
+ topLevelType: topLevelType,
+ eventSystemFlags: eventSystemFlags | IS_REPLAYED,
+ nativeEvent: nativeEvent,
+ container: container
+ };
+ }
+
+ function queueDiscreteEvent(blockedOn, topLevelType, eventSystemFlags, container, nativeEvent) {
+ var queuedEvent = createQueuedReplayableEvent(blockedOn, topLevelType, eventSystemFlags, container, nativeEvent);
+ queuedDiscreteEvents.push(queuedEvent);
+ } // Resets the replaying for this type of continuous event to no event.
+
+ function clearIfContinuousEvent(topLevelType, nativeEvent) {
+ switch (topLevelType) {
+ case TOP_FOCUS:
+ case TOP_BLUR:
+ queuedFocus = null;
+ break;
+
+ case TOP_DRAG_ENTER:
+ case TOP_DRAG_LEAVE:
+ queuedDrag = null;
+ break;
+
+ case TOP_MOUSE_OVER:
+ case TOP_MOUSE_OUT:
+ queuedMouse = null;
+ break;
+
+ case TOP_POINTER_OVER:
+ case TOP_POINTER_OUT:
+ {
+ var pointerId = nativeEvent.pointerId;
+ queuedPointers.delete(pointerId);
+ break;
+ }
+
+ case TOP_GOT_POINTER_CAPTURE:
+ case TOP_LOST_POINTER_CAPTURE:
+ {
+ var _pointerId = nativeEvent.pointerId;
+ queuedPointerCaptures.delete(_pointerId);
+ break;
+ }
+ }
+ }
+
+ function accumulateOrCreateContinuousQueuedReplayableEvent(existingQueuedEvent, blockedOn, topLevelType, eventSystemFlags, container, nativeEvent) {
+ if (existingQueuedEvent === null || existingQueuedEvent.nativeEvent !== nativeEvent) {
+ var queuedEvent = createQueuedReplayableEvent(blockedOn, topLevelType, eventSystemFlags, container, nativeEvent);
+
+ if (blockedOn !== null) {
+ var _fiber2 = getInstanceFromNode$1(blockedOn);
+
+ if (_fiber2 !== null) {
+ // Attempt to increase the priority of this target.
+ attemptContinuousHydration(_fiber2);
+ }
+ }
+
+ return queuedEvent;
+ } // If we have already queued this exact event, then it's because
+ // the different event systems have different DOM event listeners.
+ // We can accumulate the flags and store a single event to be
+ // replayed.
+
+
+ existingQueuedEvent.eventSystemFlags |= eventSystemFlags;
+ return existingQueuedEvent;
+ }
+
+ function queueIfContinuousEvent(blockedOn, topLevelType, eventSystemFlags, container, nativeEvent) {
+ // These set relatedTarget to null because the replayed event will be treated as if we
+ // moved from outside the window (no target) onto the target once it hydrates.
+ // Instead of mutating we could clone the event.
+ switch (topLevelType) {
+ case TOP_FOCUS:
+ {
+ var focusEvent = nativeEvent;
+ queuedFocus = accumulateOrCreateContinuousQueuedReplayableEvent(queuedFocus, blockedOn, topLevelType, eventSystemFlags, container, focusEvent);
+ return true;
+ }
+
+ case TOP_DRAG_ENTER:
+ {
+ var dragEvent = nativeEvent;
+ queuedDrag = accumulateOrCreateContinuousQueuedReplayableEvent(queuedDrag, blockedOn, topLevelType, eventSystemFlags, container, dragEvent);
+ return true;
+ }
+
+ case TOP_MOUSE_OVER:
+ {
+ var mouseEvent = nativeEvent;
+ queuedMouse = accumulateOrCreateContinuousQueuedReplayableEvent(queuedMouse, blockedOn, topLevelType, eventSystemFlags, container, mouseEvent);
+ return true;
+ }
+
+ case TOP_POINTER_OVER:
+ {
+ var pointerEvent = nativeEvent;
+ var pointerId = pointerEvent.pointerId;
+ queuedPointers.set(pointerId, accumulateOrCreateContinuousQueuedReplayableEvent(queuedPointers.get(pointerId) || null, blockedOn, topLevelType, eventSystemFlags, container, pointerEvent));
+ return true;
+ }
+
+ case TOP_GOT_POINTER_CAPTURE:
+ {
+ var _pointerEvent = nativeEvent;
+ var _pointerId2 = _pointerEvent.pointerId;
+ queuedPointerCaptures.set(_pointerId2, accumulateOrCreateContinuousQueuedReplayableEvent(queuedPointerCaptures.get(_pointerId2) || null, blockedOn, topLevelType, eventSystemFlags, container, _pointerEvent));
+ return true;
+ }
+ }
+
+ return false;
+ } // Check if this target is unblocked. Returns true if it's unblocked.
+
+ function attemptExplicitHydrationTarget(queuedTarget) {
+ // TODO: This function shares a lot of logic with attemptToDispatchEvent.
+ // Try to unify them. It's a bit tricky since it would require two return
+ // values.
+ var targetInst = getClosestInstanceFromNode(queuedTarget.target);
+
+ if (targetInst !== null) {
+ var nearestMounted = getNearestMountedFiber(targetInst);
+
+ if (nearestMounted !== null) {
+ var tag = nearestMounted.tag;
+
+ if (tag === SuspenseComponent) {
+ var instance = getSuspenseInstanceFromFiber(nearestMounted);
+
+ if (instance !== null) {
+ // We're blocked on hydrating this boundary.
+ // Increase its priority.
+ queuedTarget.blockedOn = instance;
+ unstable_runWithPriority(queuedTarget.priority, function () {
+ attemptHydrationAtCurrentPriority(nearestMounted);
+ });
+ return;
+ }
+ } else if (tag === HostRoot) {
+ var root = nearestMounted.stateNode;
+
+ if (root.hydrate) {
+ queuedTarget.blockedOn = getContainerFromFiber(nearestMounted); // We don't currently have a way to increase the priority of
+ // a root other than sync.
+
+ return;
+ }
+ }
+ }
+ }
+
+ queuedTarget.blockedOn = null;
+ }
+
+ function attemptReplayContinuousQueuedEvent(queuedEvent) {
+ if (queuedEvent.blockedOn !== null) {
+ return false;
+ }
+
+ var nextBlockedOn = attemptToDispatchEvent(queuedEvent.topLevelType, queuedEvent.eventSystemFlags, queuedEvent.container, queuedEvent.nativeEvent);
+
+ if (nextBlockedOn !== null) {
+ // We're still blocked. Try again later.
+ var _fiber3 = getInstanceFromNode$1(nextBlockedOn);
+
+ if (_fiber3 !== null) {
+ attemptContinuousHydration(_fiber3);
+ }
+
+ queuedEvent.blockedOn = nextBlockedOn;
+ return false;
+ }
+
+ return true;
+ }
+
+ function attemptReplayContinuousQueuedEventInMap(queuedEvent, key, map) {
+ if (attemptReplayContinuousQueuedEvent(queuedEvent)) {
+ map.delete(key);
+ }
+ }
+
+ function replayUnblockedEvents() {
+ hasScheduledReplayAttempt = false; // First replay discrete events.
+
+ while (queuedDiscreteEvents.length > 0) {
+ var nextDiscreteEvent = queuedDiscreteEvents[0];
+
+ if (nextDiscreteEvent.blockedOn !== null) {
+ // We're still blocked.
+ // Increase the priority of this boundary to unblock
+ // the next discrete event.
+ var _fiber4 = getInstanceFromNode$1(nextDiscreteEvent.blockedOn);
+
+ if (_fiber4 !== null) {
+ attemptUserBlockingHydration(_fiber4);
+ }
+
+ break;
+ }
+
+ var nextBlockedOn = attemptToDispatchEvent(nextDiscreteEvent.topLevelType, nextDiscreteEvent.eventSystemFlags, nextDiscreteEvent.container, nextDiscreteEvent.nativeEvent);
+
+ if (nextBlockedOn !== null) {
+ // We're still blocked. Try again later.
+ nextDiscreteEvent.blockedOn = nextBlockedOn;
+ } else {
+ // We've successfully replayed the first event. Let's try the next one.
+ queuedDiscreteEvents.shift();
+ }
+ } // Next replay any continuous events.
+
+
+ if (queuedFocus !== null && attemptReplayContinuousQueuedEvent(queuedFocus)) {
+ queuedFocus = null;
+ }
+
+ if (queuedDrag !== null && attemptReplayContinuousQueuedEvent(queuedDrag)) {
+ queuedDrag = null;
+ }
+
+ if (queuedMouse !== null && attemptReplayContinuousQueuedEvent(queuedMouse)) {
+ queuedMouse = null;
+ }
+
+ queuedPointers.forEach(attemptReplayContinuousQueuedEventInMap);
+ queuedPointerCaptures.forEach(attemptReplayContinuousQueuedEventInMap);
+ }
+
+ function scheduleCallbackIfUnblocked(queuedEvent, unblocked) {
+ if (queuedEvent.blockedOn === unblocked) {
+ queuedEvent.blockedOn = null;
+
+ if (!hasScheduledReplayAttempt) {
+ hasScheduledReplayAttempt = true; // Schedule a callback to attempt replaying as many events as are
+ // now unblocked. This first might not actually be unblocked yet.
+ // We could check it early to avoid scheduling an unnecessary callback.
+
+ unstable_scheduleCallback(unstable_NormalPriority, replayUnblockedEvents);
+ }
+ }
+ }
+
+ function retryIfBlockedOn(unblocked) {
+ // Mark anything that was blocked on this as no longer blocked
+ // and eligible for a replay.
+ if (queuedDiscreteEvents.length > 0) {
+ scheduleCallbackIfUnblocked(queuedDiscreteEvents[0], unblocked); // This is a exponential search for each boundary that commits. I think it's
+ // worth it because we expect very few discrete events to queue up and once
+ // we are actually fully unblocked it will be fast to replay them.
+
+ for (var i = 1; i < queuedDiscreteEvents.length; i++) {
+ var queuedEvent = queuedDiscreteEvents[i];
+
+ if (queuedEvent.blockedOn === unblocked) {
+ queuedEvent.blockedOn = null;
+ }
+ }
+ }
+
+ if (queuedFocus !== null) {
+ scheduleCallbackIfUnblocked(queuedFocus, unblocked);
+ }
+
+ if (queuedDrag !== null) {
+ scheduleCallbackIfUnblocked(queuedDrag, unblocked);
+ }
+
+ if (queuedMouse !== null) {
+ scheduleCallbackIfUnblocked(queuedMouse, unblocked);
+ }
+
+ var unblock = function (queuedEvent) {
+ return scheduleCallbackIfUnblocked(queuedEvent, unblocked);
+ };
+
+ queuedPointers.forEach(unblock);
+ queuedPointerCaptures.forEach(unblock);
+
+ for (var _i = 0; _i < queuedExplicitHydrationTargets.length; _i++) {
+ var queuedTarget = queuedExplicitHydrationTargets[_i];
+
+ if (queuedTarget.blockedOn === unblocked) {
+ queuedTarget.blockedOn = null;
+ }
+ }
+
+ while (queuedExplicitHydrationTargets.length > 0) {
+ var nextExplicitTarget = queuedExplicitHydrationTargets[0];
+
+ if (nextExplicitTarget.blockedOn !== null) {
+ // We're still blocked.
+ break;
+ } else {
+ attemptExplicitHydrationTarget(nextExplicitTarget);
+
+ if (nextExplicitTarget.blockedOn === null) {
+ // We're unblocked.
+ queuedExplicitHydrationTargets.shift();
+ }
+ }
+ }
+ }
+
+ function addEventBubbleListener(element, eventType, listener) {
+ element.addEventListener(eventType, listener, false);
+ }
+ function addEventCaptureListener(element, eventType, listener) {
+ element.addEventListener(eventType, listener, true);
+ }
+
+ // do it in two places, which duplicates logic
+ // and increases the bundle size, we do it all
+ // here once. If we remove or refactor the
+ // SimpleEventPlugin, we should also remove or
+ // update the below line.
+
+ var simpleEventPluginEventTypes = {};
+ var topLevelEventsToDispatchConfig = new Map();
+ var eventPriorities = new Map(); // We store most of the events in this module in pairs of two strings so we can re-use
+ // the code required to apply the same logic for event prioritization and that of the
+ // SimpleEventPlugin. This complicates things slightly, but the aim is to reduce code
+ // duplication (for which there would be quite a bit). For the events that are not needed
+ // for the SimpleEventPlugin (otherDiscreteEvents) we process them separately as an
+ // array of top level events.
+ // Lastly, we ignore prettier so we can keep the formatting sane.
+ // prettier-ignore
+
+ var discreteEventPairsForSimpleEventPlugin = [TOP_BLUR, 'blur', TOP_CANCEL, 'cancel', TOP_CLICK, 'click', TOP_CLOSE, 'close', TOP_CONTEXT_MENU, 'contextMenu', TOP_COPY, 'copy', TOP_CUT, 'cut', TOP_AUX_CLICK, 'auxClick', TOP_DOUBLE_CLICK, 'doubleClick', TOP_DRAG_END, 'dragEnd', TOP_DRAG_START, 'dragStart', TOP_DROP, 'drop', TOP_FOCUS, 'focus', TOP_INPUT, 'input', TOP_INVALID, 'invalid', TOP_KEY_DOWN, 'keyDown', TOP_KEY_PRESS, 'keyPress', TOP_KEY_UP, 'keyUp', TOP_MOUSE_DOWN, 'mouseDown', TOP_MOUSE_UP, 'mouseUp', TOP_PASTE, 'paste', TOP_PAUSE, 'pause', TOP_PLAY, 'play', TOP_POINTER_CANCEL, 'pointerCancel', TOP_POINTER_DOWN, 'pointerDown', TOP_POINTER_UP, 'pointerUp', TOP_RATE_CHANGE, 'rateChange', TOP_RESET, 'reset', TOP_SEEKED, 'seeked', TOP_SUBMIT, 'submit', TOP_TOUCH_CANCEL, 'touchCancel', TOP_TOUCH_END, 'touchEnd', TOP_TOUCH_START, 'touchStart', TOP_VOLUME_CHANGE, 'volumeChange'];
+ var otherDiscreteEvents = [TOP_CHANGE, TOP_SELECTION_CHANGE, TOP_TEXT_INPUT, TOP_COMPOSITION_START, TOP_COMPOSITION_END, TOP_COMPOSITION_UPDATE]; // prettier-ignore
+
+ var userBlockingPairsForSimpleEventPlugin = [TOP_DRAG, 'drag', TOP_DRAG_ENTER, 'dragEnter', TOP_DRAG_EXIT, 'dragExit', TOP_DRAG_LEAVE, 'dragLeave', TOP_DRAG_OVER, 'dragOver', TOP_MOUSE_MOVE, 'mouseMove', TOP_MOUSE_OUT, 'mouseOut', TOP_MOUSE_OVER, 'mouseOver', TOP_POINTER_MOVE, 'pointerMove', TOP_POINTER_OUT, 'pointerOut', TOP_POINTER_OVER, 'pointerOver', TOP_SCROLL, 'scroll', TOP_TOGGLE, 'toggle', TOP_TOUCH_MOVE, 'touchMove', TOP_WHEEL, 'wheel']; // prettier-ignore
+
+ var continuousPairsForSimpleEventPlugin = [TOP_ABORT, 'abort', TOP_ANIMATION_END, 'animationEnd', TOP_ANIMATION_ITERATION, 'animationIteration', TOP_ANIMATION_START, 'animationStart', TOP_CAN_PLAY, 'canPlay', TOP_CAN_PLAY_THROUGH, 'canPlayThrough', TOP_DURATION_CHANGE, 'durationChange', TOP_EMPTIED, 'emptied', TOP_ENCRYPTED, 'encrypted', TOP_ENDED, 'ended', TOP_ERROR, 'error', TOP_GOT_POINTER_CAPTURE, 'gotPointerCapture', TOP_LOAD, 'load', TOP_LOADED_DATA, 'loadedData', TOP_LOADED_METADATA, 'loadedMetadata', TOP_LOAD_START, 'loadStart', TOP_LOST_POINTER_CAPTURE, 'lostPointerCapture', TOP_PLAYING, 'playing', TOP_PROGRESS, 'progress', TOP_SEEKING, 'seeking', TOP_STALLED, 'stalled', TOP_SUSPEND, 'suspend', TOP_TIME_UPDATE, 'timeUpdate', TOP_TRANSITION_END, 'transitionEnd', TOP_WAITING, 'waiting'];
+ /**
+ * Turns
+ * ['abort', ...]
+ * into
+ * eventTypes = {
+ * 'abort': {
+ * phasedRegistrationNames: {
+ * bubbled: 'onAbort',
+ * captured: 'onAbortCapture',
+ * },
+ * dependencies: [TOP_ABORT],
+ * },
+ * ...
+ * };
+ * topLevelEventsToDispatchConfig = new Map([
+ * [TOP_ABORT, { sameConfig }],
+ * ]);
+ */
+
+ function processSimpleEventPluginPairsByPriority(eventTypes, priority) {
+ // As the event types are in pairs of two, we need to iterate
+ // through in twos. The events are in pairs of two to save code
+ // and improve init perf of processing this array, as it will
+ // result in far fewer object allocations and property accesses
+ // if we only use three arrays to process all the categories of
+ // instead of tuples.
+ for (var i = 0; i < eventTypes.length; i += 2) {
+ var topEvent = eventTypes[i];
+ var event = eventTypes[i + 1];
+ var capitalizedEvent = event[0].toUpperCase() + event.slice(1);
+ var onEvent = 'on' + capitalizedEvent;
+ var config = {
+ phasedRegistrationNames: {
+ bubbled: onEvent,
+ captured: onEvent + 'Capture'
+ },
+ dependencies: [topEvent],
+ eventPriority: priority
+ };
+ eventPriorities.set(topEvent, priority);
+ topLevelEventsToDispatchConfig.set(topEvent, config);
+ simpleEventPluginEventTypes[event] = config;
+ }
+ }
+
+ function processTopEventPairsByPriority(eventTypes, priority) {
+ for (var i = 0; i < eventTypes.length; i++) {
+ eventPriorities.set(eventTypes[i], priority);
+ }
+ } // SimpleEventPlugin
+
+
+ processSimpleEventPluginPairsByPriority(discreteEventPairsForSimpleEventPlugin, DiscreteEvent);
+ processSimpleEventPluginPairsByPriority(userBlockingPairsForSimpleEventPlugin, UserBlockingEvent);
+ processSimpleEventPluginPairsByPriority(continuousPairsForSimpleEventPlugin, ContinuousEvent); // Not used by SimpleEventPlugin
+
+ processTopEventPairsByPriority(otherDiscreteEvents, DiscreteEvent);
+ function getEventPriorityForPluginSystem(topLevelType) {
+ var priority = eventPriorities.get(topLevelType); // Default to a ContinuousEvent. Note: we might
+ // want to warn if we can't detect the priority
+ // for the event.
+
+ return priority === undefined ? ContinuousEvent : priority;
+ }
+
+ // Intentionally not named imports because Rollup would use dynamic dispatch for
+ var UserBlockingPriority = unstable_UserBlockingPriority,
+ runWithPriority = unstable_runWithPriority; // TODO: can we stop exporting these?
+
+ var _enabled = true;
+ function setEnabled(enabled) {
+ _enabled = !!enabled;
+ }
+ function isEnabled() {
+ return _enabled;
+ }
+ function trapBubbledEvent(topLevelType, element) {
+ trapEventForPluginEventSystem(element, topLevelType, false);
+ }
+ function trapCapturedEvent(topLevelType, element) {
+ trapEventForPluginEventSystem(element, topLevelType, true);
+ }
+
+ function trapEventForPluginEventSystem(container, topLevelType, capture) {
+ var listener;
+
+ switch (getEventPriorityForPluginSystem(topLevelType)) {
+ case DiscreteEvent:
+ listener = dispatchDiscreteEvent.bind(null, topLevelType, PLUGIN_EVENT_SYSTEM, container);
+ break;
+
+ case UserBlockingEvent:
+ listener = dispatchUserBlockingUpdate.bind(null, topLevelType, PLUGIN_EVENT_SYSTEM, container);
+ break;
+
+ case ContinuousEvent:
+ default:
+ listener = dispatchEvent.bind(null, topLevelType, PLUGIN_EVENT_SYSTEM, container);
+ break;
+ }
+
+ var rawEventName = getRawEventName(topLevelType);
+
+ if (capture) {
+ addEventCaptureListener(container, rawEventName, listener);
+ } else {
+ addEventBubbleListener(container, rawEventName, listener);
+ }
+ }
+
+ function dispatchDiscreteEvent(topLevelType, eventSystemFlags, container, nativeEvent) {
+ flushDiscreteUpdatesIfNeeded(nativeEvent.timeStamp);
+ discreteUpdates(dispatchEvent, topLevelType, eventSystemFlags, container, nativeEvent);
+ }
+
+ function dispatchUserBlockingUpdate(topLevelType, eventSystemFlags, container, nativeEvent) {
+ runWithPriority(UserBlockingPriority, dispatchEvent.bind(null, topLevelType, eventSystemFlags, container, nativeEvent));
+ }
+
+ function dispatchEvent(topLevelType, eventSystemFlags, container, nativeEvent) {
+ if (!_enabled) {
+ return;
+ }
+
+ if (hasQueuedDiscreteEvents() && isReplayableDiscreteEvent(topLevelType)) {
+ // If we already have a queue of discrete events, and this is another discrete
+ // event, then we can't dispatch it regardless of its target, since they
+ // need to dispatch in order.
+ queueDiscreteEvent(null, // Flags that we're not actually blocked on anything as far as we know.
+ topLevelType, eventSystemFlags, container, nativeEvent);
+ return;
+ }
+
+ var blockedOn = attemptToDispatchEvent(topLevelType, eventSystemFlags, container, nativeEvent);
+
+ if (blockedOn === null) {
+ // We successfully dispatched this event.
+ clearIfContinuousEvent(topLevelType, nativeEvent);
+ return;
+ }
+
+ if (isReplayableDiscreteEvent(topLevelType)) {
+ // This this to be replayed later once the target is available.
+ queueDiscreteEvent(blockedOn, topLevelType, eventSystemFlags, container, nativeEvent);
+ return;
+ }
+
+ if (queueIfContinuousEvent(blockedOn, topLevelType, eventSystemFlags, container, nativeEvent)) {
+ return;
+ } // We need to clear only if we didn't queue because
+ // queueing is accummulative.
+
+
+ clearIfContinuousEvent(topLevelType, nativeEvent); // This is not replayable so we'll invoke it but without a target,
+ // in case the event system needs to trace it.
+
+ {
+ dispatchEventForLegacyPluginEventSystem(topLevelType, eventSystemFlags, nativeEvent, null);
+ }
+ } // Attempt dispatching an event. Returns a SuspenseInstance or Container if it's blocked.
+
+ function attemptToDispatchEvent(topLevelType, eventSystemFlags, container, nativeEvent) {
+ // TODO: Warn if _enabled is false.
+ var nativeEventTarget = getEventTarget(nativeEvent);
+ var targetInst = getClosestInstanceFromNode(nativeEventTarget);
+
+ if (targetInst !== null) {
+ var nearestMounted = getNearestMountedFiber(targetInst);
+
+ if (nearestMounted === null) {
+ // This tree has been unmounted already. Dispatch without a target.
+ targetInst = null;
+ } else {
+ var tag = nearestMounted.tag;
+
+ if (tag === SuspenseComponent) {
+ var instance = getSuspenseInstanceFromFiber(nearestMounted);
+
+ if (instance !== null) {
+ // Queue the event to be replayed later. Abort dispatching since we
+ // don't want this event dispatched twice through the event system.
+ // TODO: If this is the first discrete event in the queue. Schedule an increased
+ // priority for this boundary.
+ return instance;
+ } // This shouldn't happen, something went wrong but to avoid blocking
+ // the whole system, dispatch the event without a target.
+ // TODO: Warn.
+
+
+ targetInst = null;
+ } else if (tag === HostRoot) {
+ var root = nearestMounted.stateNode;
+
+ if (root.hydrate) {
+ // If this happens during a replay something went wrong and it might block
+ // the whole system.
+ return getContainerFromFiber(nearestMounted);
+ }
+
+ targetInst = null;
+ } else if (nearestMounted !== targetInst) {
+ // If we get an event (ex: img onload) before committing that
+ // component's mount, ignore it for now (that is, treat it as if it was an
+ // event on a non-React tree). We might also consider queueing events and
+ // dispatching them after the mount.
+ targetInst = null;
+ }
+ }
+ }
+
+ {
+ dispatchEventForLegacyPluginEventSystem(topLevelType, eventSystemFlags, nativeEvent, targetInst);
+ } // We're not blocked on anything.
+
+
+ return null;
+ }
+
+ // List derived from Gecko source code:
+ // https://github.com/mozilla/gecko-dev/blob/4e638efc71/layout/style/test/property_database.js
+ var shorthandToLonghand = {
+ animation: ['animationDelay', 'animationDirection', 'animationDuration', 'animationFillMode', 'animationIterationCount', 'animationName', 'animationPlayState', 'animationTimingFunction'],
+ background: ['backgroundAttachment', 'backgroundClip', 'backgroundColor', 'backgroundImage', 'backgroundOrigin', 'backgroundPositionX', 'backgroundPositionY', 'backgroundRepeat', 'backgroundSize'],
+ backgroundPosition: ['backgroundPositionX', 'backgroundPositionY'],
+ border: ['borderBottomColor', 'borderBottomStyle', 'borderBottomWidth', 'borderImageOutset', 'borderImageRepeat', 'borderImageSlice', 'borderImageSource', 'borderImageWidth', 'borderLeftColor', 'borderLeftStyle', 'borderLeftWidth', 'borderRightColor', 'borderRightStyle', 'borderRightWidth', 'borderTopColor', 'borderTopStyle', 'borderTopWidth'],
+ borderBlockEnd: ['borderBlockEndColor', 'borderBlockEndStyle', 'borderBlockEndWidth'],
+ borderBlockStart: ['borderBlockStartColor', 'borderBlockStartStyle', 'borderBlockStartWidth'],
+ borderBottom: ['borderBottomColor', 'borderBottomStyle', 'borderBottomWidth'],
+ borderColor: ['borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor'],
+ borderImage: ['borderImageOutset', 'borderImageRepeat', 'borderImageSlice', 'borderImageSource', 'borderImageWidth'],
+ borderInlineEnd: ['borderInlineEndColor', 'borderInlineEndStyle', 'borderInlineEndWidth'],
+ borderInlineStart: ['borderInlineStartColor', 'borderInlineStartStyle', 'borderInlineStartWidth'],
+ borderLeft: ['borderLeftColor', 'borderLeftStyle', 'borderLeftWidth'],
+ borderRadius: ['borderBottomLeftRadius', 'borderBottomRightRadius', 'borderTopLeftRadius', 'borderTopRightRadius'],
+ borderRight: ['borderRightColor', 'borderRightStyle', 'borderRightWidth'],
+ borderStyle: ['borderBottomStyle', 'borderLeftStyle', 'borderRightStyle', 'borderTopStyle'],
+ borderTop: ['borderTopColor', 'borderTopStyle', 'borderTopWidth'],
+ borderWidth: ['borderBottomWidth', 'borderLeftWidth', 'borderRightWidth', 'borderTopWidth'],
+ columnRule: ['columnRuleColor', 'columnRuleStyle', 'columnRuleWidth'],
+ columns: ['columnCount', 'columnWidth'],
+ flex: ['flexBasis', 'flexGrow', 'flexShrink'],
+ flexFlow: ['flexDirection', 'flexWrap'],
+ font: ['fontFamily', 'fontFeatureSettings', 'fontKerning', 'fontLanguageOverride', 'fontSize', 'fontSizeAdjust', 'fontStretch', 'fontStyle', 'fontVariant', 'fontVariantAlternates', 'fontVariantCaps', 'fontVariantEastAsian', 'fontVariantLigatures', 'fontVariantNumeric', 'fontVariantPosition', 'fontWeight', 'lineHeight'],
+ fontVariant: ['fontVariantAlternates', 'fontVariantCaps', 'fontVariantEastAsian', 'fontVariantLigatures', 'fontVariantNumeric', 'fontVariantPosition'],
+ gap: ['columnGap', 'rowGap'],
+ grid: ['gridAutoColumns', 'gridAutoFlow', 'gridAutoRows', 'gridTemplateAreas', 'gridTemplateColumns', 'gridTemplateRows'],
+ gridArea: ['gridColumnEnd', 'gridColumnStart', 'gridRowEnd', 'gridRowStart'],
+ gridColumn: ['gridColumnEnd', 'gridColumnStart'],
+ gridColumnGap: ['columnGap'],
+ gridGap: ['columnGap', 'rowGap'],
+ gridRow: ['gridRowEnd', 'gridRowStart'],
+ gridRowGap: ['rowGap'],
+ gridTemplate: ['gridTemplateAreas', 'gridTemplateColumns', 'gridTemplateRows'],
+ listStyle: ['listStyleImage', 'listStylePosition', 'listStyleType'],
+ margin: ['marginBottom', 'marginLeft', 'marginRight', 'marginTop'],
+ marker: ['markerEnd', 'markerMid', 'markerStart'],
+ mask: ['maskClip', 'maskComposite', 'maskImage', 'maskMode', 'maskOrigin', 'maskPositionX', 'maskPositionY', 'maskRepeat', 'maskSize'],
+ maskPosition: ['maskPositionX', 'maskPositionY'],
+ outline: ['outlineColor', 'outlineStyle', 'outlineWidth'],
+ overflow: ['overflowX', 'overflowY'],
+ padding: ['paddingBottom', 'paddingLeft', 'paddingRight', 'paddingTop'],
+ placeContent: ['alignContent', 'justifyContent'],
+ placeItems: ['alignItems', 'justifyItems'],
+ placeSelf: ['alignSelf', 'justifySelf'],
+ textDecoration: ['textDecorationColor', 'textDecorationLine', 'textDecorationStyle'],
+ textEmphasis: ['textEmphasisColor', 'textEmphasisStyle'],
+ transition: ['transitionDelay', 'transitionDuration', 'transitionProperty', 'transitionTimingFunction'],
+ wordWrap: ['overflowWrap']
+ };
+
+ /**
+ * CSS properties which accept numbers but are not in units of "px".
+ */
+ var isUnitlessNumber = {
+ animationIterationCount: true,
+ borderImageOutset: true,
+ borderImageSlice: true,
+ borderImageWidth: true,
+ boxFlex: true,
+ boxFlexGroup: true,
+ boxOrdinalGroup: true,
+ columnCount: true,
+ columns: true,
+ flex: true,
+ flexGrow: true,
+ flexPositive: true,
+ flexShrink: true,
+ flexNegative: true,
+ flexOrder: true,
+ gridArea: true,
+ gridRow: true,
+ gridRowEnd: true,
+ gridRowSpan: true,
+ gridRowStart: true,
+ gridColumn: true,
+ gridColumnEnd: true,
+ gridColumnSpan: true,
+ gridColumnStart: true,
+ fontWeight: true,
+ lineClamp: true,
+ lineHeight: true,
+ opacity: true,
+ order: true,
+ orphans: true,
+ tabSize: true,
+ widows: true,
+ zIndex: true,
+ zoom: true,
+ // SVG-related properties
+ fillOpacity: true,
+ floodOpacity: true,
+ stopOpacity: true,
+ strokeDasharray: true,
+ strokeDashoffset: true,
+ strokeMiterlimit: true,
+ strokeOpacity: true,
+ strokeWidth: true
+ };
+ /**
+ * @param {string} prefix vendor-specific prefix, eg: Webkit
+ * @param {string} key style name, eg: transitionDuration
+ * @return {string} style name prefixed with `prefix`, properly camelCased, eg:
+ * WebkitTransitionDuration
+ */
+
+ function prefixKey(prefix, key) {
+ return prefix + key.charAt(0).toUpperCase() + key.substring(1);
+ }
+ /**
+ * Support style names that may come passed in prefixed by adding permutations
+ * of vendor prefixes.
+ */
+
+
+ var prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an
+ // infinite loop, because it iterates over the newly added props too.
+
+ Object.keys(isUnitlessNumber).forEach(function (prop) {
+ prefixes.forEach(function (prefix) {
+ isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop];
+ });
+ });
+
+ /**
+ * Convert a value into the proper css writable value. The style name `name`
+ * should be logical (no hyphens), as specified
+ * in `CSSProperty.isUnitlessNumber`.
+ *
+ * @param {string} name CSS property name such as `topMargin`.
+ * @param {*} value CSS property value such as `10px`.
+ * @return {string} Normalized style value with dimensions applied.
+ */
+
+ function dangerousStyleValue(name, value, isCustomProperty) {
+ // Note that we've removed escapeTextForBrowser() calls here since the
+ // whole string will be escaped when the attribute is injected into
+ // the markup. If you provide unsafe user data here they can inject
+ // arbitrary CSS which may be problematic (I couldn't repro this):
+ // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
+ // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/
+ // This is not an XSS hole but instead a potential CSS injection issue
+ // which has lead to a greater discussion about how we're going to
+ // trust URLs moving forward. See #2115901
+ var isEmpty = value == null || typeof value === 'boolean' || value === '';
+
+ if (isEmpty) {
+ return '';
+ }
+
+ if (!isCustomProperty && typeof value === 'number' && value !== 0 && !(isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name])) {
+ return value + 'px'; // Presumes implicit 'px' suffix for unitless numbers
+ }
+
+ return ('' + value).trim();
+ }
+
+ var uppercasePattern = /([A-Z])/g;
+ var msPattern = /^ms-/;
+ /**
+ * Hyphenates a camelcased CSS property name, for example:
+ *
+ * > hyphenateStyleName('backgroundColor')
+ * < "background-color"
+ * > hyphenateStyleName('MozTransition')
+ * < "-moz-transition"
+ * > hyphenateStyleName('msTransition')
+ * < "-ms-transition"
+ *
+ * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
+ * is converted to `-ms-`.
+ */
+
+ function hyphenateStyleName(name) {
+ return name.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern, '-ms-');
+ }
+
+ var warnValidStyle = function () {};
+
+ {
+ // 'msTransform' is correct, but the other prefixes should be capitalized
+ var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/;
+ var msPattern$1 = /^-ms-/;
+ var hyphenPattern = /-(.)/g; // style values shouldn't contain a semicolon
+
+ var badStyleValueWithSemicolonPattern = /;\s*$/;
+ var warnedStyleNames = {};
+ var warnedStyleValues = {};
+ var warnedForNaNValue = false;
+ var warnedForInfinityValue = false;
+
+ var camelize = function (string) {
+ return string.replace(hyphenPattern, function (_, character) {
+ return character.toUpperCase();
+ });
+ };
+
+ var warnHyphenatedStyleName = function (name) {
+ if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
+ return;
+ }
+
+ warnedStyleNames[name] = true;
+
+ error('Unsupported style property %s. Did you mean %s?', name, // As Andi Smith suggests
+ // (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix
+ // is converted to lowercase `ms`.
+ camelize(name.replace(msPattern$1, 'ms-')));
+ };
+
+ var warnBadVendoredStyleName = function (name) {
+ if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
+ return;
+ }
+
+ warnedStyleNames[name] = true;
+
+ error('Unsupported vendor-prefixed style property %s. Did you mean %s?', name, name.charAt(0).toUpperCase() + name.slice(1));
+ };
+
+ var warnStyleValueWithSemicolon = function (name, value) {
+ if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) {
+ return;
+ }
+
+ warnedStyleValues[value] = true;
+
+ error("Style property values shouldn't contain a semicolon. " + 'Try "%s: %s" instead.', name, value.replace(badStyleValueWithSemicolonPattern, ''));
+ };
+
+ var warnStyleValueIsNaN = function (name, value) {
+ if (warnedForNaNValue) {
+ return;
+ }
+
+ warnedForNaNValue = true;
+
+ error('`NaN` is an invalid value for the `%s` css style property.', name);
+ };
+
+ var warnStyleValueIsInfinity = function (name, value) {
+ if (warnedForInfinityValue) {
+ return;
+ }
+
+ warnedForInfinityValue = true;
+
+ error('`Infinity` is an invalid value for the `%s` css style property.', name);
+ };
+
+ warnValidStyle = function (name, value) {
+ if (name.indexOf('-') > -1) {
+ warnHyphenatedStyleName(name);
+ } else if (badVendoredStyleNamePattern.test(name)) {
+ warnBadVendoredStyleName(name);
+ } else if (badStyleValueWithSemicolonPattern.test(value)) {
+ warnStyleValueWithSemicolon(name, value);
+ }
+
+ if (typeof value === 'number') {
+ if (isNaN(value)) {
+ warnStyleValueIsNaN(name, value);
+ } else if (!isFinite(value)) {
+ warnStyleValueIsInfinity(name, value);
+ }
+ }
+ };
+ }
+
+ var warnValidStyle$1 = warnValidStyle;
+
+ /**
+ * Operations for dealing with CSS properties.
+ */
+
+ /**
+ * This creates a string that is expected to be equivalent to the style
+ * attribute generated by server-side rendering. It by-passes warnings and
+ * security checks so it's not safe to use this value for anything other than
+ * comparison. It is only used in DEV for SSR validation.
+ */
+
+ function createDangerousStringForStyles(styles) {
+ {
+ var serialized = '';
+ var delimiter = '';
+
+ for (var styleName in styles) {
+ if (!styles.hasOwnProperty(styleName)) {
+ continue;
+ }
+
+ var styleValue = styles[styleName];
+
+ if (styleValue != null) {
+ var isCustomProperty = styleName.indexOf('--') === 0;
+ serialized += delimiter + (isCustomProperty ? styleName : hyphenateStyleName(styleName)) + ':';
+ serialized += dangerousStyleValue(styleName, styleValue, isCustomProperty);
+ delimiter = ';';
+ }
+ }
+
+ return serialized || null;
+ }
+ }
+ /**
+ * Sets the value for multiple styles on a node. If a value is specified as
+ * '' (empty string), the corresponding style property will be unset.
+ *
+ * @param {DOMElement} node
+ * @param {object} styles
+ */
+
+ function setValueForStyles(node, styles) {
+ var style = node.style;
+
+ for (var styleName in styles) {
+ if (!styles.hasOwnProperty(styleName)) {
+ continue;
+ }
+
+ var isCustomProperty = styleName.indexOf('--') === 0;
+
+ {
+ if (!isCustomProperty) {
+ warnValidStyle$1(styleName, styles[styleName]);
+ }
+ }
+
+ var styleValue = dangerousStyleValue(styleName, styles[styleName], isCustomProperty);
+
+ if (styleName === 'float') {
+ styleName = 'cssFloat';
+ }
+
+ if (isCustomProperty) {
+ style.setProperty(styleName, styleValue);
+ } else {
+ style[styleName] = styleValue;
+ }
+ }
+ }
+
+ function isValueEmpty(value) {
+ return value == null || typeof value === 'boolean' || value === '';
+ }
+ /**
+ * Given {color: 'red', overflow: 'hidden'} returns {
+ * color: 'color',
+ * overflowX: 'overflow',
+ * overflowY: 'overflow',
+ * }. This can be read as "the overflowY property was set by the overflow
+ * shorthand". That is, the values are the property that each was derived from.
+ */
+
+
+ function expandShorthandMap(styles) {
+ var expanded = {};
+
+ for (var key in styles) {
+ var longhands = shorthandToLonghand[key] || [key];
+
+ for (var i = 0; i < longhands.length; i++) {
+ expanded[longhands[i]] = key;
+ }
+ }
+
+ return expanded;
+ }
+ /**
+ * When mixing shorthand and longhand property names, we warn during updates if
+ * we expect an incorrect result to occur. In particular, we warn for:
+ *
+ * Updating a shorthand property (longhand gets overwritten):
+ * {font: 'foo', fontVariant: 'bar'} -> {font: 'baz', fontVariant: 'bar'}
+ * becomes .style.font = 'baz'
+ * Removing a shorthand property (longhand gets lost too):
+ * {font: 'foo', fontVariant: 'bar'} -> {fontVariant: 'bar'}
+ * becomes .style.font = ''
+ * Removing a longhand property (should revert to shorthand; doesn't):
+ * {font: 'foo', fontVariant: 'bar'} -> {font: 'foo'}
+ * becomes .style.fontVariant = ''
+ */
+
+
+ function validateShorthandPropertyCollisionInDev(styleUpdates, nextStyles) {
+ {
+
+ if (!nextStyles) {
+ return;
+ }
+
+ var expandedUpdates = expandShorthandMap(styleUpdates);
+ var expandedStyles = expandShorthandMap(nextStyles);
+ var warnedAbout = {};
+
+ for (var key in expandedUpdates) {
+ var originalKey = expandedUpdates[key];
+ var correctOriginalKey = expandedStyles[key];
+
+ if (correctOriginalKey && originalKey !== correctOriginalKey) {
+ var warningKey = originalKey + ',' + correctOriginalKey;
+
+ if (warnedAbout[warningKey]) {
+ continue;
+ }
+
+ warnedAbout[warningKey] = true;
+
+ error('%s a style property during rerender (%s) when a ' + 'conflicting property is set (%s) can lead to styling bugs. To ' + "avoid this, don't mix shorthand and non-shorthand properties " + 'for the same value; instead, replace the shorthand with ' + 'separate values.', isValueEmpty(styleUpdates[originalKey]) ? 'Removing' : 'Updating', originalKey, correctOriginalKey);
+ }
+ }
+ }
+ }
+
+ // For HTML, certain tags should omit their close tag. We keep a whitelist for
+ // those special-case tags.
+ var omittedCloseTags = {
+ area: true,
+ base: true,
+ br: true,
+ col: true,
+ embed: true,
+ hr: true,
+ img: true,
+ input: true,
+ keygen: true,
+ link: true,
+ meta: true,
+ param: true,
+ source: true,
+ track: true,
+ wbr: true // NOTE: menuitem's close tag should be omitted, but that causes problems.
+
+ };
+
+ // `omittedCloseTags` except that `menuitem` should still have its closing tag.
+
+ var voidElementTags = _assign({
+ menuitem: true
+ }, omittedCloseTags);
+
+ var HTML = '__html';
+ var ReactDebugCurrentFrame$3 = null;
+
+ {
+ ReactDebugCurrentFrame$3 = ReactSharedInternals.ReactDebugCurrentFrame;
+ }
+
+ function assertValidProps(tag, props) {
+ if (!props) {
+ return;
+ } // Note the use of `==` which checks for null or undefined.
+
+
+ if (voidElementTags[tag]) {
+ if (!(props.children == null && props.dangerouslySetInnerHTML == null)) {
+ {
+ throw Error( tag + " is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`." + ( ReactDebugCurrentFrame$3.getStackAddendum() ) );
+ }
+ }
+ }
+
+ if (props.dangerouslySetInnerHTML != null) {
+ if (!(props.children == null)) {
+ {
+ throw Error( "Can only set one of `children` or `props.dangerouslySetInnerHTML`." );
+ }
+ }
+
+ if (!(typeof props.dangerouslySetInnerHTML === 'object' && HTML in props.dangerouslySetInnerHTML)) {
+ {
+ throw Error( "`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://fb.me/react-invariant-dangerously-set-inner-html for more information." );
+ }
+ }
+ }
+
+ {
+ if (!props.suppressContentEditableWarning && props.contentEditable && props.children != null) {
+ error('A component is `contentEditable` and contains `children` managed by ' + 'React. It is now your responsibility to guarantee that none of ' + 'those nodes are unexpectedly modified or duplicated. This is ' + 'probably not intentional.');
+ }
+ }
+
+ if (!(props.style == null || typeof props.style === 'object')) {
+ {
+ throw Error( "The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX." + ( ReactDebugCurrentFrame$3.getStackAddendum() ) );
+ }
+ }
+ }
+
+ function isCustomComponent(tagName, props) {
+ if (tagName.indexOf('-') === -1) {
+ return typeof props.is === 'string';
+ }
+
+ switch (tagName) {
+ // These are reserved SVG and MathML elements.
+ // We don't mind this whitelist too much because we expect it to never grow.
+ // The alternative is to track the namespace in a few places which is convoluted.
+ // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts
+ case 'annotation-xml':
+ case 'color-profile':
+ case 'font-face':
+ case 'font-face-src':
+ case 'font-face-uri':
+ case 'font-face-format':
+ case 'font-face-name':
+ case 'missing-glyph':
+ return false;
+
+ default:
+ return true;
+ }
+ }
+
+ // When adding attributes to the HTML or SVG whitelist, be sure to
+ // also add them to this module to ensure casing and incorrect name
+ // warnings.
+ var possibleStandardNames = {
+ // HTML
+ accept: 'accept',
+ acceptcharset: 'acceptCharset',
+ 'accept-charset': 'acceptCharset',
+ accesskey: 'accessKey',
+ action: 'action',
+ allowfullscreen: 'allowFullScreen',
+ alt: 'alt',
+ as: 'as',
+ async: 'async',
+ autocapitalize: 'autoCapitalize',
+ autocomplete: 'autoComplete',
+ autocorrect: 'autoCorrect',
+ autofocus: 'autoFocus',
+ autoplay: 'autoPlay',
+ autosave: 'autoSave',
+ capture: 'capture',
+ cellpadding: 'cellPadding',
+ cellspacing: 'cellSpacing',
+ challenge: 'challenge',
+ charset: 'charSet',
+ checked: 'checked',
+ children: 'children',
+ cite: 'cite',
+ class: 'className',
+ classid: 'classID',
+ classname: 'className',
+ cols: 'cols',
+ colspan: 'colSpan',
+ content: 'content',
+ contenteditable: 'contentEditable',
+ contextmenu: 'contextMenu',
+ controls: 'controls',
+ controlslist: 'controlsList',
+ coords: 'coords',
+ crossorigin: 'crossOrigin',
+ dangerouslysetinnerhtml: 'dangerouslySetInnerHTML',
+ data: 'data',
+ datetime: 'dateTime',
+ default: 'default',
+ defaultchecked: 'defaultChecked',
+ defaultvalue: 'defaultValue',
+ defer: 'defer',
+ dir: 'dir',
+ disabled: 'disabled',
+ disablepictureinpicture: 'disablePictureInPicture',
+ download: 'download',
+ draggable: 'draggable',
+ enctype: 'encType',
+ for: 'htmlFor',
+ form: 'form',
+ formmethod: 'formMethod',
+ formaction: 'formAction',
+ formenctype: 'formEncType',
+ formnovalidate: 'formNoValidate',
+ formtarget: 'formTarget',
+ frameborder: 'frameBorder',
+ headers: 'headers',
+ height: 'height',
+ hidden: 'hidden',
+ high: 'high',
+ href: 'href',
+ hreflang: 'hrefLang',
+ htmlfor: 'htmlFor',
+ httpequiv: 'httpEquiv',
+ 'http-equiv': 'httpEquiv',
+ icon: 'icon',
+ id: 'id',
+ innerhtml: 'innerHTML',
+ inputmode: 'inputMode',
+ integrity: 'integrity',
+ is: 'is',
+ itemid: 'itemID',
+ itemprop: 'itemProp',
+ itemref: 'itemRef',
+ itemscope: 'itemScope',
+ itemtype: 'itemType',
+ keyparams: 'keyParams',
+ keytype: 'keyType',
+ kind: 'kind',
+ label: 'label',
+ lang: 'lang',
+ list: 'list',
+ loop: 'loop',
+ low: 'low',
+ manifest: 'manifest',
+ marginwidth: 'marginWidth',
+ marginheight: 'marginHeight',
+ max: 'max',
+ maxlength: 'maxLength',
+ media: 'media',
+ mediagroup: 'mediaGroup',
+ method: 'method',
+ min: 'min',
+ minlength: 'minLength',
+ multiple: 'multiple',
+ muted: 'muted',
+ name: 'name',
+ nomodule: 'noModule',
+ nonce: 'nonce',
+ novalidate: 'noValidate',
+ open: 'open',
+ optimum: 'optimum',
+ pattern: 'pattern',
+ placeholder: 'placeholder',
+ playsinline: 'playsInline',
+ poster: 'poster',
+ preload: 'preload',
+ profile: 'profile',
+ radiogroup: 'radioGroup',
+ readonly: 'readOnly',
+ referrerpolicy: 'referrerPolicy',
+ rel: 'rel',
+ required: 'required',
+ reversed: 'reversed',
+ role: 'role',
+ rows: 'rows',
+ rowspan: 'rowSpan',
+ sandbox: 'sandbox',
+ scope: 'scope',
+ scoped: 'scoped',
+ scrolling: 'scrolling',
+ seamless: 'seamless',
+ selected: 'selected',
+ shape: 'shape',
+ size: 'size',
+ sizes: 'sizes',
+ span: 'span',
+ spellcheck: 'spellCheck',
+ src: 'src',
+ srcdoc: 'srcDoc',
+ srclang: 'srcLang',
+ srcset: 'srcSet',
+ start: 'start',
+ step: 'step',
+ style: 'style',
+ summary: 'summary',
+ tabindex: 'tabIndex',
+ target: 'target',
+ title: 'title',
+ type: 'type',
+ usemap: 'useMap',
+ value: 'value',
+ width: 'width',
+ wmode: 'wmode',
+ wrap: 'wrap',
+ // SVG
+ about: 'about',
+ accentheight: 'accentHeight',
+ 'accent-height': 'accentHeight',
+ accumulate: 'accumulate',
+ additive: 'additive',
+ alignmentbaseline: 'alignmentBaseline',
+ 'alignment-baseline': 'alignmentBaseline',
+ allowreorder: 'allowReorder',
+ alphabetic: 'alphabetic',
+ amplitude: 'amplitude',
+ arabicform: 'arabicForm',
+ 'arabic-form': 'arabicForm',
+ ascent: 'ascent',
+ attributename: 'attributeName',
+ attributetype: 'attributeType',
+ autoreverse: 'autoReverse',
+ azimuth: 'azimuth',
+ basefrequency: 'baseFrequency',
+ baselineshift: 'baselineShift',
+ 'baseline-shift': 'baselineShift',
+ baseprofile: 'baseProfile',
+ bbox: 'bbox',
+ begin: 'begin',
+ bias: 'bias',
+ by: 'by',
+ calcmode: 'calcMode',
+ capheight: 'capHeight',
+ 'cap-height': 'capHeight',
+ clip: 'clip',
+ clippath: 'clipPath',
+ 'clip-path': 'clipPath',
+ clippathunits: 'clipPathUnits',
+ cliprule: 'clipRule',
+ 'clip-rule': 'clipRule',
+ color: 'color',
+ colorinterpolation: 'colorInterpolation',
+ 'color-interpolation': 'colorInterpolation',
+ colorinterpolationfilters: 'colorInterpolationFilters',
+ 'color-interpolation-filters': 'colorInterpolationFilters',
+ colorprofile: 'colorProfile',
+ 'color-profile': 'colorProfile',
+ colorrendering: 'colorRendering',
+ 'color-rendering': 'colorRendering',
+ contentscripttype: 'contentScriptType',
+ contentstyletype: 'contentStyleType',
+ cursor: 'cursor',
+ cx: 'cx',
+ cy: 'cy',
+ d: 'd',
+ datatype: 'datatype',
+ decelerate: 'decelerate',
+ descent: 'descent',
+ diffuseconstant: 'diffuseConstant',
+ direction: 'direction',
+ display: 'display',
+ divisor: 'divisor',
+ dominantbaseline: 'dominantBaseline',
+ 'dominant-baseline': 'dominantBaseline',
+ dur: 'dur',
+ dx: 'dx',
+ dy: 'dy',
+ edgemode: 'edgeMode',
+ elevation: 'elevation',
+ enablebackground: 'enableBackground',
+ 'enable-background': 'enableBackground',
+ end: 'end',
+ exponent: 'exponent',
+ externalresourcesrequired: 'externalResourcesRequired',
+ fill: 'fill',
+ fillopacity: 'fillOpacity',
+ 'fill-opacity': 'fillOpacity',
+ fillrule: 'fillRule',
+ 'fill-rule': 'fillRule',
+ filter: 'filter',
+ filterres: 'filterRes',
+ filterunits: 'filterUnits',
+ floodopacity: 'floodOpacity',
+ 'flood-opacity': 'floodOpacity',
+ floodcolor: 'floodColor',
+ 'flood-color': 'floodColor',
+ focusable: 'focusable',
+ fontfamily: 'fontFamily',
+ 'font-family': 'fontFamily',
+ fontsize: 'fontSize',
+ 'font-size': 'fontSize',
+ fontsizeadjust: 'fontSizeAdjust',
+ 'font-size-adjust': 'fontSizeAdjust',
+ fontstretch: 'fontStretch',
+ 'font-stretch': 'fontStretch',
+ fontstyle: 'fontStyle',
+ 'font-style': 'fontStyle',
+ fontvariant: 'fontVariant',
+ 'font-variant': 'fontVariant',
+ fontweight: 'fontWeight',
+ 'font-weight': 'fontWeight',
+ format: 'format',
+ from: 'from',
+ fx: 'fx',
+ fy: 'fy',
+ g1: 'g1',
+ g2: 'g2',
+ glyphname: 'glyphName',
+ 'glyph-name': 'glyphName',
+ glyphorientationhorizontal: 'glyphOrientationHorizontal',
+ 'glyph-orientation-horizontal': 'glyphOrientationHorizontal',
+ glyphorientationvertical: 'glyphOrientationVertical',
+ 'glyph-orientation-vertical': 'glyphOrientationVertical',
+ glyphref: 'glyphRef',
+ gradienttransform: 'gradientTransform',
+ gradientunits: 'gradientUnits',
+ hanging: 'hanging',
+ horizadvx: 'horizAdvX',
+ 'horiz-adv-x': 'horizAdvX',
+ horizoriginx: 'horizOriginX',
+ 'horiz-origin-x': 'horizOriginX',
+ ideographic: 'ideographic',
+ imagerendering: 'imageRendering',
+ 'image-rendering': 'imageRendering',
+ in2: 'in2',
+ in: 'in',
+ inlist: 'inlist',
+ intercept: 'intercept',
+ k1: 'k1',
+ k2: 'k2',
+ k3: 'k3',
+ k4: 'k4',
+ k: 'k',
+ kernelmatrix: 'kernelMatrix',
+ kernelunitlength: 'kernelUnitLength',
+ kerning: 'kerning',
+ keypoints: 'keyPoints',
+ keysplines: 'keySplines',
+ keytimes: 'keyTimes',
+ lengthadjust: 'lengthAdjust',
+ letterspacing: 'letterSpacing',
+ 'letter-spacing': 'letterSpacing',
+ lightingcolor: 'lightingColor',
+ 'lighting-color': 'lightingColor',
+ limitingconeangle: 'limitingConeAngle',
+ local: 'local',
+ markerend: 'markerEnd',
+ 'marker-end': 'markerEnd',
+ markerheight: 'markerHeight',
+ markermid: 'markerMid',
+ 'marker-mid': 'markerMid',
+ markerstart: 'markerStart',
+ 'marker-start': 'markerStart',
+ markerunits: 'markerUnits',
+ markerwidth: 'markerWidth',
+ mask: 'mask',
+ maskcontentunits: 'maskContentUnits',
+ maskunits: 'maskUnits',
+ mathematical: 'mathematical',
+ mode: 'mode',
+ numoctaves: 'numOctaves',
+ offset: 'offset',
+ opacity: 'opacity',
+ operator: 'operator',
+ order: 'order',
+ orient: 'orient',
+ orientation: 'orientation',
+ origin: 'origin',
+ overflow: 'overflow',
+ overlineposition: 'overlinePosition',
+ 'overline-position': 'overlinePosition',
+ overlinethickness: 'overlineThickness',
+ 'overline-thickness': 'overlineThickness',
+ paintorder: 'paintOrder',
+ 'paint-order': 'paintOrder',
+ panose1: 'panose1',
+ 'panose-1': 'panose1',
+ pathlength: 'pathLength',
+ patterncontentunits: 'patternContentUnits',
+ patterntransform: 'patternTransform',
+ patternunits: 'patternUnits',
+ pointerevents: 'pointerEvents',
+ 'pointer-events': 'pointerEvents',
+ points: 'points',
+ pointsatx: 'pointsAtX',
+ pointsaty: 'pointsAtY',
+ pointsatz: 'pointsAtZ',
+ prefix: 'prefix',
+ preservealpha: 'preserveAlpha',
+ preserveaspectratio: 'preserveAspectRatio',
+ primitiveunits: 'primitiveUnits',
+ property: 'property',
+ r: 'r',
+ radius: 'radius',
+ refx: 'refX',
+ refy: 'refY',
+ renderingintent: 'renderingIntent',
+ 'rendering-intent': 'renderingIntent',
+ repeatcount: 'repeatCount',
+ repeatdur: 'repeatDur',
+ requiredextensions: 'requiredExtensions',
+ requiredfeatures: 'requiredFeatures',
+ resource: 'resource',
+ restart: 'restart',
+ result: 'result',
+ results: 'results',
+ rotate: 'rotate',
+ rx: 'rx',
+ ry: 'ry',
+ scale: 'scale',
+ security: 'security',
+ seed: 'seed',
+ shaperendering: 'shapeRendering',
+ 'shape-rendering': 'shapeRendering',
+ slope: 'slope',
+ spacing: 'spacing',
+ specularconstant: 'specularConstant',
+ specularexponent: 'specularExponent',
+ speed: 'speed',
+ spreadmethod: 'spreadMethod',
+ startoffset: 'startOffset',
+ stddeviation: 'stdDeviation',
+ stemh: 'stemh',
+ stemv: 'stemv',
+ stitchtiles: 'stitchTiles',
+ stopcolor: 'stopColor',
+ 'stop-color': 'stopColor',
+ stopopacity: 'stopOpacity',
+ 'stop-opacity': 'stopOpacity',
+ strikethroughposition: 'strikethroughPosition',
+ 'strikethrough-position': 'strikethroughPosition',
+ strikethroughthickness: 'strikethroughThickness',
+ 'strikethrough-thickness': 'strikethroughThickness',
+ string: 'string',
+ stroke: 'stroke',
+ strokedasharray: 'strokeDasharray',
+ 'stroke-dasharray': 'strokeDasharray',
+ strokedashoffset: 'strokeDashoffset',
+ 'stroke-dashoffset': 'strokeDashoffset',
+ strokelinecap: 'strokeLinecap',
+ 'stroke-linecap': 'strokeLinecap',
+ strokelinejoin: 'strokeLinejoin',
+ 'stroke-linejoin': 'strokeLinejoin',
+ strokemiterlimit: 'strokeMiterlimit',
+ 'stroke-miterlimit': 'strokeMiterlimit',
+ strokewidth: 'strokeWidth',
+ 'stroke-width': 'strokeWidth',
+ strokeopacity: 'strokeOpacity',
+ 'stroke-opacity': 'strokeOpacity',
+ suppresscontenteditablewarning: 'suppressContentEditableWarning',
+ suppresshydrationwarning: 'suppressHydrationWarning',
+ surfacescale: 'surfaceScale',
+ systemlanguage: 'systemLanguage',
+ tablevalues: 'tableValues',
+ targetx: 'targetX',
+ targety: 'targetY',
+ textanchor: 'textAnchor',
+ 'text-anchor': 'textAnchor',
+ textdecoration: 'textDecoration',
+ 'text-decoration': 'textDecoration',
+ textlength: 'textLength',
+ textrendering: 'textRendering',
+ 'text-rendering': 'textRendering',
+ to: 'to',
+ transform: 'transform',
+ typeof: 'typeof',
+ u1: 'u1',
+ u2: 'u2',
+ underlineposition: 'underlinePosition',
+ 'underline-position': 'underlinePosition',
+ underlinethickness: 'underlineThickness',
+ 'underline-thickness': 'underlineThickness',
+ unicode: 'unicode',
+ unicodebidi: 'unicodeBidi',
+ 'unicode-bidi': 'unicodeBidi',
+ unicoderange: 'unicodeRange',
+ 'unicode-range': 'unicodeRange',
+ unitsperem: 'unitsPerEm',
+ 'units-per-em': 'unitsPerEm',
+ unselectable: 'unselectable',
+ valphabetic: 'vAlphabetic',
+ 'v-alphabetic': 'vAlphabetic',
+ values: 'values',
+ vectoreffect: 'vectorEffect',
+ 'vector-effect': 'vectorEffect',
+ version: 'version',
+ vertadvy: 'vertAdvY',
+ 'vert-adv-y': 'vertAdvY',
+ vertoriginx: 'vertOriginX',
+ 'vert-origin-x': 'vertOriginX',
+ vertoriginy: 'vertOriginY',
+ 'vert-origin-y': 'vertOriginY',
+ vhanging: 'vHanging',
+ 'v-hanging': 'vHanging',
+ videographic: 'vIdeographic',
+ 'v-ideographic': 'vIdeographic',
+ viewbox: 'viewBox',
+ viewtarget: 'viewTarget',
+ visibility: 'visibility',
+ vmathematical: 'vMathematical',
+ 'v-mathematical': 'vMathematical',
+ vocab: 'vocab',
+ widths: 'widths',
+ wordspacing: 'wordSpacing',
+ 'word-spacing': 'wordSpacing',
+ writingmode: 'writingMode',
+ 'writing-mode': 'writingMode',
+ x1: 'x1',
+ x2: 'x2',
+ x: 'x',
+ xchannelselector: 'xChannelSelector',
+ xheight: 'xHeight',
+ 'x-height': 'xHeight',
+ xlinkactuate: 'xlinkActuate',
+ 'xlink:actuate': 'xlinkActuate',
+ xlinkarcrole: 'xlinkArcrole',
+ 'xlink:arcrole': 'xlinkArcrole',
+ xlinkhref: 'xlinkHref',
+ 'xlink:href': 'xlinkHref',
+ xlinkrole: 'xlinkRole',
+ 'xlink:role': 'xlinkRole',
+ xlinkshow: 'xlinkShow',
+ 'xlink:show': 'xlinkShow',
+ xlinktitle: 'xlinkTitle',
+ 'xlink:title': 'xlinkTitle',
+ xlinktype: 'xlinkType',
+ 'xlink:type': 'xlinkType',
+ xmlbase: 'xmlBase',
+ 'xml:base': 'xmlBase',
+ xmllang: 'xmlLang',
+ 'xml:lang': 'xmlLang',
+ xmlns: 'xmlns',
+ 'xml:space': 'xmlSpace',
+ xmlnsxlink: 'xmlnsXlink',
+ 'xmlns:xlink': 'xmlnsXlink',
+ xmlspace: 'xmlSpace',
+ y1: 'y1',
+ y2: 'y2',
+ y: 'y',
+ ychannelselector: 'yChannelSelector',
+ z: 'z',
+ zoomandpan: 'zoomAndPan'
+ };
+
+ var ariaProperties = {
+ 'aria-current': 0,
+ // state
+ 'aria-details': 0,
+ 'aria-disabled': 0,
+ // state
+ 'aria-hidden': 0,
+ // state
+ 'aria-invalid': 0,
+ // state
+ 'aria-keyshortcuts': 0,
+ 'aria-label': 0,
+ 'aria-roledescription': 0,
+ // Widget Attributes
+ 'aria-autocomplete': 0,
+ 'aria-checked': 0,
+ 'aria-expanded': 0,
+ 'aria-haspopup': 0,
+ 'aria-level': 0,
+ 'aria-modal': 0,
+ 'aria-multiline': 0,
+ 'aria-multiselectable': 0,
+ 'aria-orientation': 0,
+ 'aria-placeholder': 0,
+ 'aria-pressed': 0,
+ 'aria-readonly': 0,
+ 'aria-required': 0,
+ 'aria-selected': 0,
+ 'aria-sort': 0,
+ 'aria-valuemax': 0,
+ 'aria-valuemin': 0,
+ 'aria-valuenow': 0,
+ 'aria-valuetext': 0,
+ // Live Region Attributes
+ 'aria-atomic': 0,
+ 'aria-busy': 0,
+ 'aria-live': 0,
+ 'aria-relevant': 0,
+ // Drag-and-Drop Attributes
+ 'aria-dropeffect': 0,
+ 'aria-grabbed': 0,
+ // Relationship Attributes
+ 'aria-activedescendant': 0,
+ 'aria-colcount': 0,
+ 'aria-colindex': 0,
+ 'aria-colspan': 0,
+ 'aria-controls': 0,
+ 'aria-describedby': 0,
+ 'aria-errormessage': 0,
+ 'aria-flowto': 0,
+ 'aria-labelledby': 0,
+ 'aria-owns': 0,
+ 'aria-posinset': 0,
+ 'aria-rowcount': 0,
+ 'aria-rowindex': 0,
+ 'aria-rowspan': 0,
+ 'aria-setsize': 0
+ };
+
+ var warnedProperties = {};
+ var rARIA = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
+ var rARIACamel = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');
+ var hasOwnProperty$1 = Object.prototype.hasOwnProperty;
+
+ function validateProperty(tagName, name) {
+ {
+ if (hasOwnProperty$1.call(warnedProperties, name) && warnedProperties[name]) {
+ return true;
+ }
+
+ if (rARIACamel.test(name)) {
+ var ariaName = 'aria-' + name.slice(4).toLowerCase();
+ var correctName = ariaProperties.hasOwnProperty(ariaName) ? ariaName : null; // If this is an aria-* attribute, but is not listed in the known DOM
+ // DOM properties, then it is an invalid aria-* attribute.
+
+ if (correctName == null) {
+ error('Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.', name);
+
+ warnedProperties[name] = true;
+ return true;
+ } // aria-* attributes should be lowercase; suggest the lowercase version.
+
+
+ if (name !== correctName) {
+ error('Invalid ARIA attribute `%s`. Did you mean `%s`?', name, correctName);
+
+ warnedProperties[name] = true;
+ return true;
+ }
+ }
+
+ if (rARIA.test(name)) {
+ var lowerCasedName = name.toLowerCase();
+ var standardName = ariaProperties.hasOwnProperty(lowerCasedName) ? lowerCasedName : null; // If this is an aria-* attribute, but is not listed in the known DOM
+ // DOM properties, then it is an invalid aria-* attribute.
+
+ if (standardName == null) {
+ warnedProperties[name] = true;
+ return false;
+ } // aria-* attributes should be lowercase; suggest the lowercase version.
+
+
+ if (name !== standardName) {
+ error('Unknown ARIA attribute `%s`. Did you mean `%s`?', name, standardName);
+
+ warnedProperties[name] = true;
+ return true;
+ }
+ }
+ }
+
+ return true;
+ }
+
+ function warnInvalidARIAProps(type, props) {
+ {
+ var invalidProps = [];
+
+ for (var key in props) {
+ var isValid = validateProperty(type, key);
+
+ if (!isValid) {
+ invalidProps.push(key);
+ }
+ }
+
+ var unknownPropString = invalidProps.map(function (prop) {
+ return '`' + prop + '`';
+ }).join(', ');
+
+ if (invalidProps.length === 1) {
+ error('Invalid aria prop %s on <%s> tag. ' + 'For details, see https://fb.me/invalid-aria-prop', unknownPropString, type);
+ } else if (invalidProps.length > 1) {
+ error('Invalid aria props %s on <%s> tag. ' + 'For details, see https://fb.me/invalid-aria-prop', unknownPropString, type);
+ }
+ }
+ }
+
+ function validateProperties(type, props) {
+ if (isCustomComponent(type, props)) {
+ return;
+ }
+
+ warnInvalidARIAProps(type, props);
+ }
+
+ var didWarnValueNull = false;
+ function validateProperties$1(type, props) {
+ {
+ if (type !== 'input' && type !== 'textarea' && type !== 'select') {
+ return;
+ }
+
+ if (props != null && props.value === null && !didWarnValueNull) {
+ didWarnValueNull = true;
+
+ if (type === 'select' && props.multiple) {
+ error('`value` prop on `%s` should not be null. ' + 'Consider using an empty array when `multiple` is set to `true` ' + 'to clear the component or `undefined` for uncontrolled components.', type);
+ } else {
+ error('`value` prop on `%s` should not be null. ' + 'Consider using an empty string to clear the component or `undefined` ' + 'for uncontrolled components.', type);
+ }
+ }
+ }
+ }
+
+ var validateProperty$1 = function () {};
+
+ {
+ var warnedProperties$1 = {};
+ var _hasOwnProperty = Object.prototype.hasOwnProperty;
+ var EVENT_NAME_REGEX = /^on./;
+ var INVALID_EVENT_NAME_REGEX = /^on[^A-Z]/;
+ var rARIA$1 = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$');
+ var rARIACamel$1 = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$');
+
+ validateProperty$1 = function (tagName, name, value, canUseEventSystem) {
+ if (_hasOwnProperty.call(warnedProperties$1, name) && warnedProperties$1[name]) {
+ return true;
+ }
+
+ var lowerCasedName = name.toLowerCase();
+
+ if (lowerCasedName === 'onfocusin' || lowerCasedName === 'onfocusout') {
+ error('React uses onFocus and onBlur instead of onFocusIn and onFocusOut. ' + 'All React events are normalized to bubble, so onFocusIn and onFocusOut ' + 'are not needed/supported by React.');
+
+ warnedProperties$1[name] = true;
+ return true;
+ } // We can't rely on the event system being injected on the server.
+
+
+ if (canUseEventSystem) {
+ if (registrationNameModules.hasOwnProperty(name)) {
+ return true;
+ }
+
+ var registrationName = possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? possibleRegistrationNames[lowerCasedName] : null;
+
+ if (registrationName != null) {
+ error('Invalid event handler property `%s`. Did you mean `%s`?', name, registrationName);
+
+ warnedProperties$1[name] = true;
+ return true;
+ }
+
+ if (EVENT_NAME_REGEX.test(name)) {
+ error('Unknown event handler property `%s`. It will be ignored.', name);
+
+ warnedProperties$1[name] = true;
+ return true;
+ }
+ } else if (EVENT_NAME_REGEX.test(name)) {
+ // If no event plugins have been injected, we are in a server environment.
+ // So we can't tell if the event name is correct for sure, but we can filter
+ // out known bad ones like `onclick`. We can't suggest a specific replacement though.
+ if (INVALID_EVENT_NAME_REGEX.test(name)) {
+ error('Invalid event handler property `%s`. ' + 'React events use the camelCase naming convention, for example `onClick`.', name);
+ }
+
+ warnedProperties$1[name] = true;
+ return true;
+ } // Let the ARIA attribute hook validate ARIA attributes
+
+
+ if (rARIA$1.test(name) || rARIACamel$1.test(name)) {
+ return true;
+ }
+
+ if (lowerCasedName === 'innerhtml') {
+ error('Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.');
+
+ warnedProperties$1[name] = true;
+ return true;
+ }
+
+ if (lowerCasedName === 'aria') {
+ error('The `aria` attribute is reserved for future use in React. ' + 'Pass individual `aria-` attributes instead.');
+
+ warnedProperties$1[name] = true;
+ return true;
+ }
+
+ if (lowerCasedName === 'is' && value !== null && value !== undefined && typeof value !== 'string') {
+ error('Received a `%s` for a string attribute `is`. If this is expected, cast ' + 'the value to a string.', typeof value);
+
+ warnedProperties$1[name] = true;
+ return true;
+ }
+
+ if (typeof value === 'number' && isNaN(value)) {
+ error('Received NaN for the `%s` attribute. If this is expected, cast ' + 'the value to a string.', name);
+
+ warnedProperties$1[name] = true;
+ return true;
+ }
+
+ var propertyInfo = getPropertyInfo(name);
+ var isReserved = propertyInfo !== null && propertyInfo.type === RESERVED; // Known attributes should match the casing specified in the property config.
+
+ if (possibleStandardNames.hasOwnProperty(lowerCasedName)) {
+ var standardName = possibleStandardNames[lowerCasedName];
+
+ if (standardName !== name) {
+ error('Invalid DOM property `%s`. Did you mean `%s`?', name, standardName);
+
+ warnedProperties$1[name] = true;
+ return true;
+ }
+ } else if (!isReserved && name !== lowerCasedName) {
+ // Unknown attributes should have lowercase casing since that's how they
+ // will be cased anyway with server rendering.
+ error('React does not recognize the `%s` prop on a DOM element. If you ' + 'intentionally want it to appear in the DOM as a custom ' + 'attribute, spell it as lowercase `%s` instead. ' + 'If you accidentally passed it from a parent component, remove ' + 'it from the DOM element.', name, lowerCasedName);
+
+ warnedProperties$1[name] = true;
+ return true;
+ }
+
+ if (typeof value === 'boolean' && shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
+ if (value) {
+ error('Received `%s` for a non-boolean attribute `%s`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s="%s" or %s={value.toString()}.', value, name, name, value, name);
+ } else {
+ error('Received `%s` for a non-boolean attribute `%s`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s="%s" or %s={value.toString()}.\n\n' + 'If you used to conditionally omit it with %s={condition && value}, ' + 'pass %s={condition ? value : undefined} instead.', value, name, name, value, name, name, name);
+ }
+
+ warnedProperties$1[name] = true;
+ return true;
+ } // Now that we've validated casing, do not validate
+ // data types for reserved props
+
+
+ if (isReserved) {
+ return true;
+ } // Warn when a known attribute is a bad type
+
+
+ if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) {
+ warnedProperties$1[name] = true;
+ return false;
+ } // Warn when passing the strings 'false' or 'true' into a boolean prop
+
+
+ if ((value === 'false' || value === 'true') && propertyInfo !== null && propertyInfo.type === BOOLEAN) {
+ error('Received the string `%s` for the boolean attribute `%s`. ' + '%s ' + 'Did you mean %s={%s}?', value, name, value === 'false' ? 'The browser will interpret it as a truthy value.' : 'Although this works, it will not work as expected if you pass the string "false".', name, value);
+
+ warnedProperties$1[name] = true;
+ return true;
+ }
+
+ return true;
+ };
+ }
+
+ var warnUnknownProperties = function (type, props, canUseEventSystem) {
+ {
+ var unknownProps = [];
+
+ for (var key in props) {
+ var isValid = validateProperty$1(type, key, props[key], canUseEventSystem);
+
+ if (!isValid) {
+ unknownProps.push(key);
+ }
+ }
+
+ var unknownPropString = unknownProps.map(function (prop) {
+ return '`' + prop + '`';
+ }).join(', ');
+
+ if (unknownProps.length === 1) {
+ error('Invalid value for prop %s on <%s> tag. Either remove it from the element, ' + 'or pass a string or number value to keep it in the DOM. ' + 'For details, see https://fb.me/react-attribute-behavior', unknownPropString, type);
+ } else if (unknownProps.length > 1) {
+ error('Invalid values for props %s on <%s> tag. Either remove them from the element, ' + 'or pass a string or number value to keep them in the DOM. ' + 'For details, see https://fb.me/react-attribute-behavior', unknownPropString, type);
+ }
+ }
+ };
+
+ function validateProperties$2(type, props, canUseEventSystem) {
+ if (isCustomComponent(type, props)) {
+ return;
+ }
+
+ warnUnknownProperties(type, props, canUseEventSystem);
+ }
+
+ var didWarnInvalidHydration = false;
+ var DANGEROUSLY_SET_INNER_HTML = 'dangerouslySetInnerHTML';
+ var SUPPRESS_CONTENT_EDITABLE_WARNING = 'suppressContentEditableWarning';
+ var SUPPRESS_HYDRATION_WARNING = 'suppressHydrationWarning';
+ var AUTOFOCUS = 'autoFocus';
+ var CHILDREN = 'children';
+ var STYLE = 'style';
+ var HTML$1 = '__html';
+ var HTML_NAMESPACE$1 = Namespaces.html;
+ var warnedUnknownTags;
+ var suppressHydrationWarning;
+ var validatePropertiesInDevelopment;
+ var warnForTextDifference;
+ var warnForPropDifference;
+ var warnForExtraAttributes;
+ var warnForInvalidEventListener;
+ var canDiffStyleForHydrationWarning;
+ var normalizeMarkupForTextOrAttribute;
+ var normalizeHTML;
+
+ {
+ warnedUnknownTags = {
+ // Chrome is the only major browser not shipping <time>. But as of July
+ // 2017 it intends to ship it due to widespread usage. We intentionally
+ // *don't* warn for <time> even if it's unrecognized by Chrome because
+ // it soon will be, and many apps have been using it anyway.
+ time: true,
+ // There are working polyfills for <dialog>. Let people use it.
+ dialog: true,
+ // Electron ships a custom <webview> tag to display external web content in
+ // an isolated frame and process.
+ // This tag is not present in non Electron environments such as JSDom which
+ // is often used for testing purposes.
+ // @see https://electronjs.org/docs/api/webview-tag
+ webview: true
+ };
+
+ validatePropertiesInDevelopment = function (type, props) {
+ validateProperties(type, props);
+ validateProperties$1(type, props);
+ validateProperties$2(type, props,
+ /* canUseEventSystem */
+ true);
+ }; // IE 11 parses & normalizes the style attribute as opposed to other
+ // browsers. It adds spaces and sorts the properties in some
+ // non-alphabetical order. Handling that would require sorting CSS
+ // properties in the client & server versions or applying
+ // `expectedStyle` to a temporary DOM node to read its `style` attribute
+ // normalized. Since it only affects IE, we're skipping style warnings
+ // in that browser completely in favor of doing all that work.
+ // See https://github.com/facebook/react/issues/11807
+
+
+ canDiffStyleForHydrationWarning = canUseDOM && !document.documentMode; // HTML parsing normalizes CR and CRLF to LF.
+ // It also can turn \u0000 into \uFFFD inside attributes.
+ // https://www.w3.org/TR/html5/single-page.html#preprocessing-the-input-stream
+ // If we have a mismatch, it might be caused by that.
+ // We will still patch up in this case but not fire the warning.
+
+ var NORMALIZE_NEWLINES_REGEX = /\r\n?/g;
+ var NORMALIZE_NULL_AND_REPLACEMENT_REGEX = /\u0000|\uFFFD/g;
+
+ normalizeMarkupForTextOrAttribute = function (markup) {
+ var markupString = typeof markup === 'string' ? markup : '' + markup;
+ return markupString.replace(NORMALIZE_NEWLINES_REGEX, '\n').replace(NORMALIZE_NULL_AND_REPLACEMENT_REGEX, '');
+ };
+
+ warnForTextDifference = function (serverText, clientText) {
+ if (didWarnInvalidHydration) {
+ return;
+ }
+
+ var normalizedClientText = normalizeMarkupForTextOrAttribute(clientText);
+ var normalizedServerText = normalizeMarkupForTextOrAttribute(serverText);
+
+ if (normalizedServerText === normalizedClientText) {
+ return;
+ }
+
+ didWarnInvalidHydration = true;
+
+ error('Text content did not match. Server: "%s" Client: "%s"', normalizedServerText, normalizedClientText);
+ };
+
+ warnForPropDifference = function (propName, serverValue, clientValue) {
+ if (didWarnInvalidHydration) {
+ return;
+ }
+
+ var normalizedClientValue = normalizeMarkupForTextOrAttribute(clientValue);
+ var normalizedServerValue = normalizeMarkupForTextOrAttribute(serverValue);
+
+ if (normalizedServerValue === normalizedClientValue) {
+ return;
+ }
+
+ didWarnInvalidHydration = true;
+
+ error('Prop `%s` did not match. Server: %s Client: %s', propName, JSON.stringify(normalizedServerValue), JSON.stringify(normalizedClientValue));
+ };
+
+ warnForExtraAttributes = function (attributeNames) {
+ if (didWarnInvalidHydration) {
+ return;
+ }
+
+ didWarnInvalidHydration = true;
+ var names = [];
+ attributeNames.forEach(function (name) {
+ names.push(name);
+ });
+
+ error('Extra attributes from the server: %s', names);
+ };
+
+ warnForInvalidEventListener = function (registrationName, listener) {
+ if (listener === false) {
+ error('Expected `%s` listener to be a function, instead got `false`.\n\n' + 'If you used to conditionally omit it with %s={condition && value}, ' + 'pass %s={condition ? value : undefined} instead.', registrationName, registrationName, registrationName);
+ } else {
+ error('Expected `%s` listener to be a function, instead got a value of `%s` type.', registrationName, typeof listener);
+ }
+ }; // Parse the HTML and read it back to normalize the HTML string so that it
+ // can be used for comparison.
+
+
+ normalizeHTML = function (parent, html) {
+ // We could have created a separate document here to avoid
+ // re-initializing custom elements if they exist. But this breaks
+ // how <noscript> is being handled. So we use the same document.
+ // See the discussion in https://github.com/facebook/react/pull/11157.
+ var testElement = parent.namespaceURI === HTML_NAMESPACE$1 ? parent.ownerDocument.createElement(parent.tagName) : parent.ownerDocument.createElementNS(parent.namespaceURI, parent.tagName);
+ testElement.innerHTML = html;
+ return testElement.innerHTML;
+ };
+ }
+
+ function ensureListeningTo(rootContainerElement, registrationName) {
+ var isDocumentOrFragment = rootContainerElement.nodeType === DOCUMENT_NODE || rootContainerElement.nodeType === DOCUMENT_FRAGMENT_NODE;
+ var doc = isDocumentOrFragment ? rootContainerElement : rootContainerElement.ownerDocument;
+ legacyListenToEvent(registrationName, doc);
+ }
+
+ function getOwnerDocumentFromRootContainer(rootContainerElement) {
+ return rootContainerElement.nodeType === DOCUMENT_NODE ? rootContainerElement : rootContainerElement.ownerDocument;
+ }
+
+ function noop() {}
+
+ function trapClickOnNonInteractiveElement(node) {
+ // Mobile Safari does not fire properly bubble click events on
+ // non-interactive elements, which means delegated click listeners do not
+ // fire. The workaround for this bug involves attaching an empty click
+ // listener on the target node.
+ // http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
+ // Just set it using the onclick property so that we don't have to manage any
+ // bookkeeping for it. Not sure if we need to clear it when the listener is
+ // removed.
+ // TODO: Only do this for the relevant Safaris maybe?
+ node.onclick = noop;
+ }
+
+ function setInitialDOMProperties(tag, domElement, rootContainerElement, nextProps, isCustomComponentTag) {
+ for (var propKey in nextProps) {
+ if (!nextProps.hasOwnProperty(propKey)) {
+ continue;
+ }
+
+ var nextProp = nextProps[propKey];
+
+ if (propKey === STYLE) {
+ {
+ if (nextProp) {
+ // Freeze the next style object so that we can assume it won't be
+ // mutated. We have already warned for this in the past.
+ Object.freeze(nextProp);
+ }
+ } // Relies on `updateStylesByID` not mutating `styleUpdates`.
+
+
+ setValueForStyles(domElement, nextProp);
+ } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
+ var nextHtml = nextProp ? nextProp[HTML$1] : undefined;
+
+ if (nextHtml != null) {
+ setInnerHTML(domElement, nextHtml);
+ }
+ } else if (propKey === CHILDREN) {
+ if (typeof nextProp === 'string') {
+ // Avoid setting initial textContent when the text is empty. In IE11 setting
+ // textContent on a <textarea> will cause the placeholder to not
+ // show within the <textarea> until it has been focused and blurred again.
+ // https://github.com/facebook/react/issues/6731#issuecomment-254874553
+ var canSetTextContent = tag !== 'textarea' || nextProp !== '';
+
+ if (canSetTextContent) {
+ setTextContent(domElement, nextProp);
+ }
+ } else if (typeof nextProp === 'number') {
+ setTextContent(domElement, '' + nextProp);
+ }
+ } else if ( propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING) ; else if (propKey === AUTOFOCUS) ; else if (registrationNameModules.hasOwnProperty(propKey)) {
+ if (nextProp != null) {
+ if ( typeof nextProp !== 'function') {
+ warnForInvalidEventListener(propKey, nextProp);
+ }
+
+ ensureListeningTo(rootContainerElement, propKey);
+ }
+ } else if (nextProp != null) {
+ setValueForProperty(domElement, propKey, nextProp, isCustomComponentTag);
+ }
+ }
+ }
+
+ function updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag) {
+ // TODO: Handle wasCustomComponentTag
+ for (var i = 0; i < updatePayload.length; i += 2) {
+ var propKey = updatePayload[i];
+ var propValue = updatePayload[i + 1];
+
+ if (propKey === STYLE) {
+ setValueForStyles(domElement, propValue);
+ } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
+ setInnerHTML(domElement, propValue);
+ } else if (propKey === CHILDREN) {
+ setTextContent(domElement, propValue);
+ } else {
+ setValueForProperty(domElement, propKey, propValue, isCustomComponentTag);
+ }
+ }
+ }
+
+ function createElement(type, props, rootContainerElement, parentNamespace) {
+ var isCustomComponentTag; // We create tags in the namespace of their parent container, except HTML
+ // tags get no namespace.
+
+ var ownerDocument = getOwnerDocumentFromRootContainer(rootContainerElement);
+ var domElement;
+ var namespaceURI = parentNamespace;
+
+ if (namespaceURI === HTML_NAMESPACE$1) {
+ namespaceURI = getIntrinsicNamespace(type);
+ }
+
+ if (namespaceURI === HTML_NAMESPACE$1) {
+ {
+ isCustomComponentTag = isCustomComponent(type, props); // Should this check be gated by parent namespace? Not sure we want to
+ // allow <SVG> or <mATH>.
+
+ if (!isCustomComponentTag && type !== type.toLowerCase()) {
+ error('<%s /> is using incorrect casing. ' + 'Use PascalCase for React components, ' + 'or lowercase for HTML elements.', type);
+ }
+ }
+
+ if (type === 'script') {
+ // Create the script via .innerHTML so its "parser-inserted" flag is
+ // set to true and it does not execute
+ var div = ownerDocument.createElement('div');
+
+ div.innerHTML = '<script><' + '/script>'; // eslint-disable-line
+ // This is guaranteed to yield a script element.
+
+ var firstChild = div.firstChild;
+ domElement = div.removeChild(firstChild);
+ } else if (typeof props.is === 'string') {
+ // $FlowIssue `createElement` should be updated for Web Components
+ domElement = ownerDocument.createElement(type, {
+ is: props.is
+ });
+ } else {
+ // Separate else branch instead of using `props.is || undefined` above because of a Firefox bug.
+ // See discussion in https://github.com/facebook/react/pull/6896
+ // and discussion in https://bugzilla.mozilla.org/show_bug.cgi?id=1276240
+ domElement = ownerDocument.createElement(type); // Normally attributes are assigned in `setInitialDOMProperties`, however the `multiple` and `size`
+ // attributes on `select`s needs to be added before `option`s are inserted.
+ // This prevents:
+ // - a bug where the `select` does not scroll to the correct option because singular
+ // `select` elements automatically pick the first item #13222
+ // - a bug where the `select` set the first item as selected despite the `size` attribute #14239
+ // See https://github.com/facebook/react/issues/13222
+ // and https://github.com/facebook/react/issues/14239
+
+ if (type === 'select') {
+ var node = domElement;
+
+ if (props.multiple) {
+ node.multiple = true;
+ } else if (props.size) {
+ // Setting a size greater than 1 causes a select to behave like `multiple=true`, where
+ // it is possible that no option is selected.
+ //
+ // This is only necessary when a select in "single selection mode".
+ node.size = props.size;
+ }
+ }
+ }
+ } else {
+ domElement = ownerDocument.createElementNS(namespaceURI, type);
+ }
+
+ {
+ if (namespaceURI === HTML_NAMESPACE$1) {
+ if (!isCustomComponentTag && Object.prototype.toString.call(domElement) === '[object HTMLUnknownElement]' && !Object.prototype.hasOwnProperty.call(warnedUnknownTags, type)) {
+ warnedUnknownTags[type] = true;
+
+ error('The tag <%s> is unrecognized in this browser. ' + 'If you meant to render a React component, start its name with ' + 'an uppercase letter.', type);
+ }
+ }
+ }
+
+ return domElement;
+ }
+ function createTextNode(text, rootContainerElement) {
+ return getOwnerDocumentFromRootContainer(rootContainerElement).createTextNode(text);
+ }
+ function setInitialProperties(domElement, tag, rawProps, rootContainerElement) {
+ var isCustomComponentTag = isCustomComponent(tag, rawProps);
+
+ {
+ validatePropertiesInDevelopment(tag, rawProps);
+ } // TODO: Make sure that we check isMounted before firing any of these events.
+
+
+ var props;
+
+ switch (tag) {
+ case 'iframe':
+ case 'object':
+ case 'embed':
+ trapBubbledEvent(TOP_LOAD, domElement);
+ props = rawProps;
+ break;
+
+ case 'video':
+ case 'audio':
+ // Create listener for each media event
+ for (var i = 0; i < mediaEventTypes.length; i++) {
+ trapBubbledEvent(mediaEventTypes[i], domElement);
+ }
+
+ props = rawProps;
+ break;
+
+ case 'source':
+ trapBubbledEvent(TOP_ERROR, domElement);
+ props = rawProps;
+ break;
+
+ case 'img':
+ case 'image':
+ case 'link':
+ trapBubbledEvent(TOP_ERROR, domElement);
+ trapBubbledEvent(TOP_LOAD, domElement);
+ props = rawProps;
+ break;
+
+ case 'form':
+ trapBubbledEvent(TOP_RESET, domElement);
+ trapBubbledEvent(TOP_SUBMIT, domElement);
+ props = rawProps;
+ break;
+
+ case 'details':
+ trapBubbledEvent(TOP_TOGGLE, domElement);
+ props = rawProps;
+ break;
+
+ case 'input':
+ initWrapperState(domElement, rawProps);
+ props = getHostProps(domElement, rawProps);
+ trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening
+ // to onChange. Even if there is no listener.
+
+ ensureListeningTo(rootContainerElement, 'onChange');
+ break;
+
+ case 'option':
+ validateProps(domElement, rawProps);
+ props = getHostProps$1(domElement, rawProps);
+ break;
+
+ case 'select':
+ initWrapperState$1(domElement, rawProps);
+ props = getHostProps$2(domElement, rawProps);
+ trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening
+ // to onChange. Even if there is no listener.
+
+ ensureListeningTo(rootContainerElement, 'onChange');
+ break;
+
+ case 'textarea':
+ initWrapperState$2(domElement, rawProps);
+ props = getHostProps$3(domElement, rawProps);
+ trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening
+ // to onChange. Even if there is no listener.
+
+ ensureListeningTo(rootContainerElement, 'onChange');
+ break;
+
+ default:
+ props = rawProps;
+ }
+
+ assertValidProps(tag, props);
+ setInitialDOMProperties(tag, domElement, rootContainerElement, props, isCustomComponentTag);
+
+ switch (tag) {
+ case 'input':
+ // TODO: Make sure we check if this is still unmounted or do any clean
+ // up necessary since we never stop tracking anymore.
+ track(domElement);
+ postMountWrapper(domElement, rawProps, false);
+ break;
+
+ case 'textarea':
+ // TODO: Make sure we check if this is still unmounted or do any clean
+ // up necessary since we never stop tracking anymore.
+ track(domElement);
+ postMountWrapper$3(domElement);
+ break;
+
+ case 'option':
+ postMountWrapper$1(domElement, rawProps);
+ break;
+
+ case 'select':
+ postMountWrapper$2(domElement, rawProps);
+ break;
+
+ default:
+ if (typeof props.onClick === 'function') {
+ // TODO: This cast may not be sound for SVG, MathML or custom elements.
+ trapClickOnNonInteractiveElement(domElement);
+ }
+
+ break;
+ }
+ } // Calculate the diff between the two objects.
+
+ function diffProperties(domElement, tag, lastRawProps, nextRawProps, rootContainerElement) {
+ {
+ validatePropertiesInDevelopment(tag, nextRawProps);
+ }
+
+ var updatePayload = null;
+ var lastProps;
+ var nextProps;
+
+ switch (tag) {
+ case 'input':
+ lastProps = getHostProps(domElement, lastRawProps);
+ nextProps = getHostProps(domElement, nextRawProps);
+ updatePayload = [];
+ break;
+
+ case 'option':
+ lastProps = getHostProps$1(domElement, lastRawProps);
+ nextProps = getHostProps$1(domElement, nextRawProps);
+ updatePayload = [];
+ break;
+
+ case 'select':
+ lastProps = getHostProps$2(domElement, lastRawProps);
+ nextProps = getHostProps$2(domElement, nextRawProps);
+ updatePayload = [];
+ break;
+
+ case 'textarea':
+ lastProps = getHostProps$3(domElement, lastRawProps);
+ nextProps = getHostProps$3(domElement, nextRawProps);
+ updatePayload = [];
+ break;
+
+ default:
+ lastProps = lastRawProps;
+ nextProps = nextRawProps;
+
+ if (typeof lastProps.onClick !== 'function' && typeof nextProps.onClick === 'function') {
+ // TODO: This cast may not be sound for SVG, MathML or custom elements.
+ trapClickOnNonInteractiveElement(domElement);
+ }
+
+ break;
+ }
+
+ assertValidProps(tag, nextProps);
+ var propKey;
+ var styleName;
+ var styleUpdates = null;
+
+ for (propKey in lastProps) {
+ if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey) || lastProps[propKey] == null) {
+ continue;
+ }
+
+ if (propKey === STYLE) {
+ var lastStyle = lastProps[propKey];
+
+ for (styleName in lastStyle) {
+ if (lastStyle.hasOwnProperty(styleName)) {
+ if (!styleUpdates) {
+ styleUpdates = {};
+ }
+
+ styleUpdates[styleName] = '';
+ }
+ }
+ } else if (propKey === DANGEROUSLY_SET_INNER_HTML || propKey === CHILDREN) ; else if ( propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING) ; else if (propKey === AUTOFOCUS) ; else if (registrationNameModules.hasOwnProperty(propKey)) {
+ // This is a special case. If any listener updates we need to ensure
+ // that the "current" fiber pointer gets updated so we need a commit
+ // to update this element.
+ if (!updatePayload) {
+ updatePayload = [];
+ }
+ } else {
+ // For all other deleted properties we add it to the queue. We use
+ // the whitelist in the commit phase instead.
+ (updatePayload = updatePayload || []).push(propKey, null);
+ }
+ }
+
+ for (propKey in nextProps) {
+ var nextProp = nextProps[propKey];
+ var lastProp = lastProps != null ? lastProps[propKey] : undefined;
+
+ if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp || nextProp == null && lastProp == null) {
+ continue;
+ }
+
+ if (propKey === STYLE) {
+ {
+ if (nextProp) {
+ // Freeze the next style object so that we can assume it won't be
+ // mutated. We have already warned for this in the past.
+ Object.freeze(nextProp);
+ }
+ }
+
+ if (lastProp) {
+ // Unset styles on `lastProp` but not on `nextProp`.
+ for (styleName in lastProp) {
+ if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) {
+ if (!styleUpdates) {
+ styleUpdates = {};
+ }
+
+ styleUpdates[styleName] = '';
+ }
+ } // Update styles that changed since `lastProp`.
+
+
+ for (styleName in nextProp) {
+ if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) {
+ if (!styleUpdates) {
+ styleUpdates = {};
+ }
+
+ styleUpdates[styleName] = nextProp[styleName];
+ }
+ }
+ } else {
+ // Relies on `updateStylesByID` not mutating `styleUpdates`.
+ if (!styleUpdates) {
+ if (!updatePayload) {
+ updatePayload = [];
+ }
+
+ updatePayload.push(propKey, styleUpdates);
+ }
+
+ styleUpdates = nextProp;
+ }
+ } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
+ var nextHtml = nextProp ? nextProp[HTML$1] : undefined;
+ var lastHtml = lastProp ? lastProp[HTML$1] : undefined;
+
+ if (nextHtml != null) {
+ if (lastHtml !== nextHtml) {
+ (updatePayload = updatePayload || []).push(propKey, nextHtml);
+ }
+ }
+ } else if (propKey === CHILDREN) {
+ if (lastProp !== nextProp && (typeof nextProp === 'string' || typeof nextProp === 'number')) {
+ (updatePayload = updatePayload || []).push(propKey, '' + nextProp);
+ }
+ } else if ( propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING) ; else if (registrationNameModules.hasOwnProperty(propKey)) {
+ if (nextProp != null) {
+ // We eagerly listen to this even though we haven't committed yet.
+ if ( typeof nextProp !== 'function') {
+ warnForInvalidEventListener(propKey, nextProp);
+ }
+
+ ensureListeningTo(rootContainerElement, propKey);
+ }
+
+ if (!updatePayload && lastProp !== nextProp) {
+ // This is a special case. If any listener updates we need to ensure
+ // that the "current" props pointer gets updated so we need a commit
+ // to update this element.
+ updatePayload = [];
+ }
+ } else {
+ // For any other property we always add it to the queue and then we
+ // filter it out using the whitelist during the commit.
+ (updatePayload = updatePayload || []).push(propKey, nextProp);
+ }
+ }
+
+ if (styleUpdates) {
+ {
+ validateShorthandPropertyCollisionInDev(styleUpdates, nextProps[STYLE]);
+ }
+
+ (updatePayload = updatePayload || []).push(STYLE, styleUpdates);
+ }
+
+ return updatePayload;
+ } // Apply the diff.
+
+ function updateProperties(domElement, updatePayload, tag, lastRawProps, nextRawProps) {
+ // Update checked *before* name.
+ // In the middle of an update, it is possible to have multiple checked.
+ // When a checked radio tries to change name, browser makes another radio's checked false.
+ if (tag === 'input' && nextRawProps.type === 'radio' && nextRawProps.name != null) {
+ updateChecked(domElement, nextRawProps);
+ }
+
+ var wasCustomComponentTag = isCustomComponent(tag, lastRawProps);
+ var isCustomComponentTag = isCustomComponent(tag, nextRawProps); // Apply the diff.
+
+ updateDOMProperties(domElement, updatePayload, wasCustomComponentTag, isCustomComponentTag); // TODO: Ensure that an update gets scheduled if any of the special props
+ // changed.
+
+ switch (tag) {
+ case 'input':
+ // Update the wrapper around inputs *after* updating props. This has to
+ // happen after `updateDOMProperties`. Otherwise HTML5 input validations
+ // raise warnings and prevent the new value from being assigned.
+ updateWrapper(domElement, nextRawProps);
+ break;
+
+ case 'textarea':
+ updateWrapper$1(domElement, nextRawProps);
+ break;
+
+ case 'select':
+ // <select> value update needs to occur after <option> children
+ // reconciliation
+ postUpdateWrapper(domElement, nextRawProps);
+ break;
+ }
+ }
+
+ function getPossibleStandardName(propName) {
+ {
+ var lowerCasedName = propName.toLowerCase();
+
+ if (!possibleStandardNames.hasOwnProperty(lowerCasedName)) {
+ return null;
+ }
+
+ return possibleStandardNames[lowerCasedName] || null;
+ }
+ }
+
+ function diffHydratedProperties(domElement, tag, rawProps, parentNamespace, rootContainerElement) {
+ var isCustomComponentTag;
+ var extraAttributeNames;
+
+ {
+ suppressHydrationWarning = rawProps[SUPPRESS_HYDRATION_WARNING] === true;
+ isCustomComponentTag = isCustomComponent(tag, rawProps);
+ validatePropertiesInDevelopment(tag, rawProps);
+ } // TODO: Make sure that we check isMounted before firing any of these events.
+
+
+ switch (tag) {
+ case 'iframe':
+ case 'object':
+ case 'embed':
+ trapBubbledEvent(TOP_LOAD, domElement);
+ break;
+
+ case 'video':
+ case 'audio':
+ // Create listener for each media event
+ for (var i = 0; i < mediaEventTypes.length; i++) {
+ trapBubbledEvent(mediaEventTypes[i], domElement);
+ }
+
+ break;
+
+ case 'source':
+ trapBubbledEvent(TOP_ERROR, domElement);
+ break;
+
+ case 'img':
+ case 'image':
+ case 'link':
+ trapBubbledEvent(TOP_ERROR, domElement);
+ trapBubbledEvent(TOP_LOAD, domElement);
+ break;
+
+ case 'form':
+ trapBubbledEvent(TOP_RESET, domElement);
+ trapBubbledEvent(TOP_SUBMIT, domElement);
+ break;
+
+ case 'details':
+ trapBubbledEvent(TOP_TOGGLE, domElement);
+ break;
+
+ case 'input':
+ initWrapperState(domElement, rawProps);
+ trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening
+ // to onChange. Even if there is no listener.
+
+ ensureListeningTo(rootContainerElement, 'onChange');
+ break;
+
+ case 'option':
+ validateProps(domElement, rawProps);
+ break;
+
+ case 'select':
+ initWrapperState$1(domElement, rawProps);
+ trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening
+ // to onChange. Even if there is no listener.
+
+ ensureListeningTo(rootContainerElement, 'onChange');
+ break;
+
+ case 'textarea':
+ initWrapperState$2(domElement, rawProps);
+ trapBubbledEvent(TOP_INVALID, domElement); // For controlled components we always need to ensure we're listening
+ // to onChange. Even if there is no listener.
+
+ ensureListeningTo(rootContainerElement, 'onChange');
+ break;
+ }
+
+ assertValidProps(tag, rawProps);
+
+ {
+ extraAttributeNames = new Set();
+ var attributes = domElement.attributes;
+
+ for (var _i = 0; _i < attributes.length; _i++) {
+ var name = attributes[_i].name.toLowerCase();
+
+ switch (name) {
+ // Built-in SSR attribute is whitelisted
+ case 'data-reactroot':
+ break;
+ // Controlled attributes are not validated
+ // TODO: Only ignore them on controlled tags.
+
+ case 'value':
+ break;
+
+ case 'checked':
+ break;
+
+ case 'selected':
+ break;
+
+ default:
+ // Intentionally use the original name.
+ // See discussion in https://github.com/facebook/react/pull/10676.
+ extraAttributeNames.add(attributes[_i].name);
+ }
+ }
+ }
+
+ var updatePayload = null;
+
+ for (var propKey in rawProps) {
+ if (!rawProps.hasOwnProperty(propKey)) {
+ continue;
+ }
+
+ var nextProp = rawProps[propKey];
+
+ if (propKey === CHILDREN) {
+ // For text content children we compare against textContent. This
+ // might match additional HTML that is hidden when we read it using
+ // textContent. E.g. "foo" will match "f<span>oo</span>" but that still
+ // satisfies our requirement. Our requirement is not to produce perfect
+ // HTML and attributes. Ideally we should preserve structure but it's
+ // ok not to if the visible content is still enough to indicate what
+ // even listeners these nodes might be wired up to.
+ // TODO: Warn if there is more than a single textNode as a child.
+ // TODO: Should we use domElement.firstChild.nodeValue to compare?
+ if (typeof nextProp === 'string') {
+ if (domElement.textContent !== nextProp) {
+ if ( !suppressHydrationWarning) {
+ warnForTextDifference(domElement.textContent, nextProp);
+ }
+
+ updatePayload = [CHILDREN, nextProp];
+ }
+ } else if (typeof nextProp === 'number') {
+ if (domElement.textContent !== '' + nextProp) {
+ if ( !suppressHydrationWarning) {
+ warnForTextDifference(domElement.textContent, nextProp);
+ }
+
+ updatePayload = [CHILDREN, '' + nextProp];
+ }
+ }
+ } else if (registrationNameModules.hasOwnProperty(propKey)) {
+ if (nextProp != null) {
+ if ( typeof nextProp !== 'function') {
+ warnForInvalidEventListener(propKey, nextProp);
+ }
+
+ ensureListeningTo(rootContainerElement, propKey);
+ }
+ } else if ( // Convince Flow we've calculated it (it's DEV-only in this method.)
+ typeof isCustomComponentTag === 'boolean') {
+ // Validate that the properties correspond to their expected values.
+ var serverValue = void 0;
+ var propertyInfo = getPropertyInfo(propKey);
+
+ if (suppressHydrationWarning) ; else if ( propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING || // Controlled attributes are not validated
+ // TODO: Only ignore them on controlled tags.
+ propKey === 'value' || propKey === 'checked' || propKey === 'selected') ; else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
+ var serverHTML = domElement.innerHTML;
+ var nextHtml = nextProp ? nextProp[HTML$1] : undefined;
+ var expectedHTML = normalizeHTML(domElement, nextHtml != null ? nextHtml : '');
+
+ if (expectedHTML !== serverHTML) {
+ warnForPropDifference(propKey, serverHTML, expectedHTML);
+ }
+ } else if (propKey === STYLE) {
+ // $FlowFixMe - Should be inferred as not undefined.
+ extraAttributeNames.delete(propKey);
+
+ if (canDiffStyleForHydrationWarning) {
+ var expectedStyle = createDangerousStringForStyles(nextProp);
+ serverValue = domElement.getAttribute('style');
+
+ if (expectedStyle !== serverValue) {
+ warnForPropDifference(propKey, serverValue, expectedStyle);
+ }
+ }
+ } else if (isCustomComponentTag) {
+ // $FlowFixMe - Should be inferred as not undefined.
+ extraAttributeNames.delete(propKey.toLowerCase());
+ serverValue = getValueForAttribute(domElement, propKey, nextProp);
+
+ if (nextProp !== serverValue) {
+ warnForPropDifference(propKey, serverValue, nextProp);
+ }
+ } else if (!shouldIgnoreAttribute(propKey, propertyInfo, isCustomComponentTag) && !shouldRemoveAttribute(propKey, nextProp, propertyInfo, isCustomComponentTag)) {
+ var isMismatchDueToBadCasing = false;
+
+ if (propertyInfo !== null) {
+ // $FlowFixMe - Should be inferred as not undefined.
+ extraAttributeNames.delete(propertyInfo.attributeName);
+ serverValue = getValueForProperty(domElement, propKey, nextProp, propertyInfo);
+ } else {
+ var ownNamespace = parentNamespace;
+
+ if (ownNamespace === HTML_NAMESPACE$1) {
+ ownNamespace = getIntrinsicNamespace(tag);
+ }
+
+ if (ownNamespace === HTML_NAMESPACE$1) {
+ // $FlowFixMe - Should be inferred as not undefined.
+ extraAttributeNames.delete(propKey.toLowerCase());
+ } else {
+ var standardName = getPossibleStandardName(propKey);
+
+ if (standardName !== null && standardName !== propKey) {
+ // If an SVG prop is supplied with bad casing, it will
+ // be successfully parsed from HTML, but will produce a mismatch
+ // (and would be incorrectly rendered on the client).
+ // However, we already warn about bad casing elsewhere.
+ // So we'll skip the misleading extra mismatch warning in this case.
+ isMismatchDueToBadCasing = true; // $FlowFixMe - Should be inferred as not undefined.
+
+ extraAttributeNames.delete(standardName);
+ } // $FlowFixMe - Should be inferred as not undefined.
+
+
+ extraAttributeNames.delete(propKey);
+ }
+
+ serverValue = getValueForAttribute(domElement, propKey, nextProp);
+ }
+
+ if (nextProp !== serverValue && !isMismatchDueToBadCasing) {
+ warnForPropDifference(propKey, serverValue, nextProp);
+ }
+ }
+ }
+ }
+
+ {
+ // $FlowFixMe - Should be inferred as not undefined.
+ if (extraAttributeNames.size > 0 && !suppressHydrationWarning) {
+ // $FlowFixMe - Should be inferred as not undefined.
+ warnForExtraAttributes(extraAttributeNames);
+ }
+ }
+
+ switch (tag) {
+ case 'input':
+ // TODO: Make sure we check if this is still unmounted or do any clean
+ // up necessary since we never stop tracking anymore.
+ track(domElement);
+ postMountWrapper(domElement, rawProps, true);
+ break;
+
+ case 'textarea':
+ // TODO: Make sure we check if this is still unmounted or do any clean
+ // up necessary since we never stop tracking anymore.
+ track(domElement);
+ postMountWrapper$3(domElement);
+ break;
+
+ case 'select':
+ case 'option':
+ // For input and textarea we current always set the value property at
+ // post mount to force it to diverge from attributes. However, for
+ // option and select we don't quite do the same thing and select
+ // is not resilient to the DOM state changing so we don't do that here.
+ // TODO: Consider not doing this for input and textarea.
+ break;
+
+ default:
+ if (typeof rawProps.onClick === 'function') {
+ // TODO: This cast may not be sound for SVG, MathML or custom elements.
+ trapClickOnNonInteractiveElement(domElement);
+ }
+
+ break;
+ }
+
+ return updatePayload;
+ }
+ function diffHydratedText(textNode, text) {
+ var isDifferent = textNode.nodeValue !== text;
+ return isDifferent;
+ }
+ function warnForUnmatchedText(textNode, text) {
+ {
+ warnForTextDifference(textNode.nodeValue, text);
+ }
+ }
+ function warnForDeletedHydratableElement(parentNode, child) {
+ {
+ if (didWarnInvalidHydration) {
+ return;
+ }
+
+ didWarnInvalidHydration = true;
+
+ error('Did not expect server HTML to contain a <%s> in <%s>.', child.nodeName.toLowerCase(), parentNode.nodeName.toLowerCase());
+ }
+ }
+ function warnForDeletedHydratableText(parentNode, child) {
+ {
+ if (didWarnInvalidHydration) {
+ return;
+ }
+
+ didWarnInvalidHydration = true;
+
+ error('Did not expect server HTML to contain the text node "%s" in <%s>.', child.nodeValue, parentNode.nodeName.toLowerCase());
+ }
+ }
+ function warnForInsertedHydratedElement(parentNode, tag, props) {
+ {
+ if (didWarnInvalidHydration) {
+ return;
+ }
+
+ didWarnInvalidHydration = true;
+
+ error('Expected server HTML to contain a matching <%s> in <%s>.', tag, parentNode.nodeName.toLowerCase());
+ }
+ }
+ function warnForInsertedHydratedText(parentNode, text) {
+ {
+ if (text === '') {
+ // We expect to insert empty text nodes since they're not represented in
+ // the HTML.
+ // TODO: Remove this special case if we can just avoid inserting empty
+ // text nodes.
+ return;
+ }
+
+ if (didWarnInvalidHydration) {
+ return;
+ }
+
+ didWarnInvalidHydration = true;
+
+ error('Expected server HTML to contain a matching text node for "%s" in <%s>.', text, parentNode.nodeName.toLowerCase());
+ }
+ }
+ function restoreControlledState$3(domElement, tag, props) {
+ switch (tag) {
+ case 'input':
+ restoreControlledState(domElement, props);
+ return;
+
+ case 'textarea':
+ restoreControlledState$2(domElement, props);
+ return;
+
+ case 'select':
+ restoreControlledState$1(domElement, props);
+ return;
+ }
+ }
+
+ function getActiveElement(doc) {
+ doc = doc || (typeof document !== 'undefined' ? document : undefined);
+
+ if (typeof doc === 'undefined') {
+ return null;
+ }
+
+ try {
+ return doc.activeElement || doc.body;
+ } catch (e) {
+ return doc.body;
+ }
+ }
+
+ /**
+ * Given any node return the first leaf node without children.
+ *
+ * @param {DOMElement|DOMTextNode} node
+ * @return {DOMElement|DOMTextNode}
+ */
+
+ function getLeafNode(node) {
+ while (node && node.firstChild) {
+ node = node.firstChild;
+ }
+
+ return node;
+ }
+ /**
+ * Get the next sibling within a container. This will walk up the
+ * DOM if a node's siblings have been exhausted.
+ *
+ * @param {DOMElement|DOMTextNode} node
+ * @return {?DOMElement|DOMTextNode}
+ */
+
+
+ function getSiblingNode(node) {
+ while (node) {
+ if (node.nextSibling) {
+ return node.nextSibling;
+ }
+
+ node = node.parentNode;
+ }
+ }
+ /**
+ * Get object describing the nodes which contain characters at offset.
+ *
+ * @param {DOMElement|DOMTextNode} root
+ * @param {number} offset
+ * @return {?object}
+ */
+
+
+ function getNodeForCharacterOffset(root, offset) {
+ var node = getLeafNode(root);
+ var nodeStart = 0;
+ var nodeEnd = 0;
+
+ while (node) {
+ if (node.nodeType === TEXT_NODE) {
+ nodeEnd = nodeStart + node.textContent.length;
+
+ if (nodeStart <= offset && nodeEnd >= offset) {
+ return {
+ node: node,
+ offset: offset - nodeStart
+ };
+ }
+
+ nodeStart = nodeEnd;
+ }
+
+ node = getLeafNode(getSiblingNode(node));
+ }
+ }
+
+ /**
+ * @param {DOMElement} outerNode
+ * @return {?object}
+ */
+
+ function getOffsets(outerNode) {
+ var ownerDocument = outerNode.ownerDocument;
+ var win = ownerDocument && ownerDocument.defaultView || window;
+ var selection = win.getSelection && win.getSelection();
+
+ if (!selection || selection.rangeCount === 0) {
+ return null;
+ }
+
+ var anchorNode = selection.anchorNode,
+ anchorOffset = selection.anchorOffset,
+ focusNode = selection.focusNode,
+ focusOffset = selection.focusOffset; // In Firefox, anchorNode and focusNode can be "anonymous divs", e.g. the
+ // up/down buttons on an <input type="number">. Anonymous divs do not seem to
+ // expose properties, triggering a "Permission denied error" if any of its
+ // properties are accessed. The only seemingly possible way to avoid erroring
+ // is to access a property that typically works for non-anonymous divs and
+ // catch any error that may otherwise arise. See
+ // https://bugzilla.mozilla.org/show_bug.cgi?id=208427
+
+ try {
+ /* eslint-disable no-unused-expressions */
+ anchorNode.nodeType;
+ focusNode.nodeType;
+ /* eslint-enable no-unused-expressions */
+ } catch (e) {
+ return null;
+ }
+
+ return getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset);
+ }
+ /**
+ * Returns {start, end} where `start` is the character/codepoint index of
+ * (anchorNode, anchorOffset) within the textContent of `outerNode`, and
+ * `end` is the index of (focusNode, focusOffset).
+ *
+ * Returns null if you pass in garbage input but we should probably just crash.
+ *
+ * Exported only for testing.
+ */
+
+ function getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset) {
+ var length = 0;
+ var start = -1;
+ var end = -1;
+ var indexWithinAnchor = 0;
+ var indexWithinFocus = 0;
+ var node = outerNode;
+ var parentNode = null;
+
+ outer: while (true) {
+ var next = null;
+
+ while (true) {
+ if (node === anchorNode && (anchorOffset === 0 || node.nodeType === TEXT_NODE)) {
+ start = length + anchorOffset;
+ }
+
+ if (node === focusNode && (focusOffset === 0 || node.nodeType === TEXT_NODE)) {
+ end = length + focusOffset;
+ }
+
+ if (node.nodeType === TEXT_NODE) {
+ length += node.nodeValue.length;
+ }
+
+ if ((next = node.firstChild) === null) {
+ break;
+ } // Moving from `node` to its first child `next`.
+
+
+ parentNode = node;
+ node = next;
+ }
+
+ while (true) {
+ if (node === outerNode) {
+ // If `outerNode` has children, this is always the second time visiting
+ // it. If it has no children, this is still the first loop, and the only
+ // valid selection is anchorNode and focusNode both equal to this node
+ // and both offsets 0, in which case we will have handled above.
+ break outer;
+ }
+
+ if (parentNode === anchorNode && ++indexWithinAnchor === anchorOffset) {
+ start = length;
+ }
+
+ if (parentNode === focusNode && ++indexWithinFocus === focusOffset) {
+ end = length;
+ }
+
+ if ((next = node.nextSibling) !== null) {
+ break;
+ }
+
+ node = parentNode;
+ parentNode = node.parentNode;
+ } // Moving from `node` to its next sibling `next`.
+
+
+ node = next;
+ }
+
+ if (start === -1 || end === -1) {
+ // This should never happen. (Would happen if the anchor/focus nodes aren't
+ // actually inside the passed-in node.)
+ return null;
+ }
+
+ return {
+ start: start,
+ end: end
+ };
+ }
+ /**
+ * In modern non-IE browsers, we can support both forward and backward
+ * selections.
+ *
+ * Note: IE10+ supports the Selection object, but it does not support
+ * the `extend` method, which means that even in modern IE, it's not possible
+ * to programmatically create a backward selection. Thus, for all IE
+ * versions, we use the old IE API to create our selections.
+ *
+ * @param {DOMElement|DOMTextNode} node
+ * @param {object} offsets
+ */
+
+ function setOffsets(node, offsets) {
+ var doc = node.ownerDocument || document;
+ var win = doc && doc.defaultView || window; // Edge fails with "Object expected" in some scenarios.
+ // (For instance: TinyMCE editor used in a list component that supports pasting to add more,
+ // fails when pasting 100+ items)
+
+ if (!win.getSelection) {
+ return;
+ }
+
+ var selection = win.getSelection();
+ var length = node.textContent.length;
+ var start = Math.min(offsets.start, length);
+ var end = offsets.end === undefined ? start : Math.min(offsets.end, length); // IE 11 uses modern selection, but doesn't support the extend method.
+ // Flip backward selections, so we can set with a single range.
+
+ if (!selection.extend && start > end) {
+ var temp = end;
+ end = start;
+ start = temp;
+ }
+
+ var startMarker = getNodeForCharacterOffset(node, start);
+ var endMarker = getNodeForCharacterOffset(node, end);
+
+ if (startMarker && endMarker) {
+ if (selection.rangeCount === 1 && selection.anchorNode === startMarker.node && selection.anchorOffset === startMarker.offset && selection.focusNode === endMarker.node && selection.focusOffset === endMarker.offset) {
+ return;
+ }
+
+ var range = doc.createRange();
+ range.setStart(startMarker.node, startMarker.offset);
+ selection.removeAllRanges();
+
+ if (start > end) {
+ selection.addRange(range);
+ selection.extend(endMarker.node, endMarker.offset);
+ } else {
+ range.setEnd(endMarker.node, endMarker.offset);
+ selection.addRange(range);
+ }
+ }
+ }
+
+ function isTextNode(node) {
+ return node && node.nodeType === TEXT_NODE;
+ }
+
+ function containsNode(outerNode, innerNode) {
+ if (!outerNode || !innerNode) {
+ return false;
+ } else if (outerNode === innerNode) {
+ return true;
+ } else if (isTextNode(outerNode)) {
+ return false;
+ } else if (isTextNode(innerNode)) {
+ return containsNode(outerNode, innerNode.parentNode);
+ } else if ('contains' in outerNode) {
+ return outerNode.contains(innerNode);
+ } else if (outerNode.compareDocumentPosition) {
+ return !!(outerNode.compareDocumentPosition(innerNode) & 16);
+ } else {
+ return false;
+ }
+ }
+
+ function isInDocument(node) {
+ return node && node.ownerDocument && containsNode(node.ownerDocument.documentElement, node);
+ }
+
+ function isSameOriginFrame(iframe) {
+ try {
+ // Accessing the contentDocument of a HTMLIframeElement can cause the browser
+ // to throw, e.g. if it has a cross-origin src attribute.
+ // Safari will show an error in the console when the access results in "Blocked a frame with origin". e.g:
+ // iframe.contentDocument.defaultView;
+ // A safety way is to access one of the cross origin properties: Window or Location
+ // Which might result in "SecurityError" DOM Exception and it is compatible to Safari.
+ // https://html.spec.whatwg.org/multipage/browsers.html#integration-with-idl
+ return typeof iframe.contentWindow.location.href === 'string';
+ } catch (err) {
+ return false;
+ }
+ }
+
+ function getActiveElementDeep() {
+ var win = window;
+ var element = getActiveElement();
+
+ while (element instanceof win.HTMLIFrameElement) {
+ if (isSameOriginFrame(element)) {
+ win = element.contentWindow;
+ } else {
+ return element;
+ }
+
+ element = getActiveElement(win.document);
+ }
+
+ return element;
+ }
+ /**
+ * @ReactInputSelection: React input selection module. Based on Selection.js,
+ * but modified to be suitable for react and has a couple of bug fixes (doesn't
+ * assume buttons have range selections allowed).
+ * Input selection module for React.
+ */
+
+ /**
+ * @hasSelectionCapabilities: we get the element types that support selection
+ * from https://html.spec.whatwg.org/#do-not-apply, looking at `selectionStart`
+ * and `selectionEnd` rows.
+ */
+
+
+ function hasSelectionCapabilities(elem) {
+ var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
+ return nodeName && (nodeName === 'input' && (elem.type === 'text' || elem.type === 'search' || elem.type === 'tel' || elem.type === 'url' || elem.type === 'password') || nodeName === 'textarea' || elem.contentEditable === 'true');
+ }
+ function getSelectionInformation() {
+ var focusedElem = getActiveElementDeep();
+ return {
+ // Used by Flare
+ activeElementDetached: null,
+ focusedElem: focusedElem,
+ selectionRange: hasSelectionCapabilities(focusedElem) ? getSelection(focusedElem) : null
+ };
+ }
+ /**
+ * @restoreSelection: If any selection information was potentially lost,
+ * restore it. This is useful when performing operations that could remove dom
+ * nodes and place them back in, resulting in focus being lost.
+ */
+
+ function restoreSelection(priorSelectionInformation) {
+ var curFocusedElem = getActiveElementDeep();
+ var priorFocusedElem = priorSelectionInformation.focusedElem;
+ var priorSelectionRange = priorSelectionInformation.selectionRange;
+
+ if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) {
+ if (priorSelectionRange !== null && hasSelectionCapabilities(priorFocusedElem)) {
+ setSelection(priorFocusedElem, priorSelectionRange);
+ } // Focusing a node can change the scroll position, which is undesirable
+
+
+ var ancestors = [];
+ var ancestor = priorFocusedElem;
+
+ while (ancestor = ancestor.parentNode) {
+ if (ancestor.nodeType === ELEMENT_NODE) {
+ ancestors.push({
+ element: ancestor,
+ left: ancestor.scrollLeft,
+ top: ancestor.scrollTop
+ });
+ }
+ }
+
+ if (typeof priorFocusedElem.focus === 'function') {
+ priorFocusedElem.focus();
+ }
+
+ for (var i = 0; i < ancestors.length; i++) {
+ var info = ancestors[i];
+ info.element.scrollLeft = info.left;
+ info.element.scrollTop = info.top;
+ }
+ }
+ }
+ /**
+ * @getSelection: Gets the selection bounds of a focused textarea, input or
+ * contentEditable node.
+ * -@input: Look up selection bounds of this input
+ * -@return {start: selectionStart, end: selectionEnd}
+ */
+
+ function getSelection(input) {
+ var selection;
+
+ if ('selectionStart' in input) {
+ // Modern browser with input or textarea.
+ selection = {
+ start: input.selectionStart,
+ end: input.selectionEnd
+ };
+ } else {
+ // Content editable or old IE textarea.
+ selection = getOffsets(input);
+ }
+
+ return selection || {
+ start: 0,
+ end: 0
+ };
+ }
+ /**
+ * @setSelection: Sets the selection bounds of a textarea or input and focuses
+ * the input.
+ * -@input Set selection bounds of this input or textarea
+ * -@offsets Object of same form that is returned from get*
+ */
+
+ function setSelection(input, offsets) {
+ var start = offsets.start,
+ end = offsets.end;
+
+ if (end === undefined) {
+ end = start;
+ }
+
+ if ('selectionStart' in input) {
+ input.selectionStart = start;
+ input.selectionEnd = Math.min(end, input.value.length);
+ } else {
+ setOffsets(input, offsets);
+ }
+ }
+
+ var validateDOMNesting = function () {};
+
+ var updatedAncestorInfo = function () {};
+
+ {
+ // This validation code was written based on the HTML5 parsing spec:
+ // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
+ //
+ // Note: this does not catch all invalid nesting, nor does it try to (as it's
+ // not clear what practical benefit doing so provides); instead, we warn only
+ // for cases where the parser will give a parse tree differing from what React
+ // intended. For example, <b><div></div></b> is invalid but we don't warn
+ // because it still parses correctly; we do warn for other cases like nested
+ // <p> tags where the beginning of the second element implicitly closes the
+ // first, causing a confusing mess.
+ // https://html.spec.whatwg.org/multipage/syntax.html#special
+ var specialTags = ['address', 'applet', 'area', 'article', 'aside', 'base', 'basefont', 'bgsound', 'blockquote', 'body', 'br', 'button', 'caption', 'center', 'col', 'colgroup', 'dd', 'details', 'dir', 'div', 'dl', 'dt', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'iframe', 'img', 'input', 'isindex', 'li', 'link', 'listing', 'main', 'marquee', 'menu', 'menuitem', 'meta', 'nav', 'noembed', 'noframes', 'noscript', 'object', 'ol', 'p', 'param', 'plaintext', 'pre', 'script', 'section', 'select', 'source', 'style', 'summary', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'track', 'ul', 'wbr', 'xmp']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
+
+ var inScopeTags = ['applet', 'caption', 'html', 'table', 'td', 'th', 'marquee', 'object', 'template', // https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point
+ // TODO: Distinguish by namespace here -- for <title>, including it here
+ // errs on the side of fewer warnings
+ 'foreignObject', 'desc', 'title']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope
+
+ var buttonScopeTags = inScopeTags.concat(['button']); // https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags
+
+ var impliedEndTags = ['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt'];
+ var emptyAncestorInfo = {
+ current: null,
+ formTag: null,
+ aTagInScope: null,
+ buttonTagInScope: null,
+ nobrTagInScope: null,
+ pTagInButtonScope: null,
+ listItemTagAutoclosing: null,
+ dlItemTagAutoclosing: null
+ };
+
+ updatedAncestorInfo = function (oldInfo, tag) {
+ var ancestorInfo = _assign({}, oldInfo || emptyAncestorInfo);
+
+ var info = {
+ tag: tag
+ };
+
+ if (inScopeTags.indexOf(tag) !== -1) {
+ ancestorInfo.aTagInScope = null;
+ ancestorInfo.buttonTagInScope = null;
+ ancestorInfo.nobrTagInScope = null;
+ }
+
+ if (buttonScopeTags.indexOf(tag) !== -1) {
+ ancestorInfo.pTagInButtonScope = null;
+ } // See rules for 'li', 'dd', 'dt' start tags in
+ // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
+
+
+ if (specialTags.indexOf(tag) !== -1 && tag !== 'address' && tag !== 'div' && tag !== 'p') {
+ ancestorInfo.listItemTagAutoclosing = null;
+ ancestorInfo.dlItemTagAutoclosing = null;
+ }
+
+ ancestorInfo.current = info;
+
+ if (tag === 'form') {
+ ancestorInfo.formTag = info;
+ }
+
+ if (tag === 'a') {
+ ancestorInfo.aTagInScope = info;
+ }
+
+ if (tag === 'button') {
+ ancestorInfo.buttonTagInScope = info;
+ }
+
+ if (tag === 'nobr') {
+ ancestorInfo.nobrTagInScope = info;
+ }
+
+ if (tag === 'p') {
+ ancestorInfo.pTagInButtonScope = info;
+ }
+
+ if (tag === 'li') {
+ ancestorInfo.listItemTagAutoclosing = info;
+ }
+
+ if (tag === 'dd' || tag === 'dt') {
+ ancestorInfo.dlItemTagAutoclosing = info;
+ }
+
+ return ancestorInfo;
+ };
+ /**
+ * Returns whether
+ */
+
+
+ var isTagValidWithParent = function (tag, parentTag) {
+ // First, let's check if we're in an unusual parsing mode...
+ switch (parentTag) {
+ // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect
+ case 'select':
+ return tag === 'option' || tag === 'optgroup' || tag === '#text';
+
+ case 'optgroup':
+ return tag === 'option' || tag === '#text';
+ // Strictly speaking, seeing an <option> doesn't mean we're in a <select>
+ // but
+
+ case 'option':
+ return tag === '#text';
+ // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd
+ // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption
+ // No special behavior since these rules fall back to "in body" mode for
+ // all except special table nodes which cause bad parsing behavior anyway.
+ // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr
+
+ case 'tr':
+ return tag === 'th' || tag === 'td' || tag === 'style' || tag === 'script' || tag === 'template';
+ // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody
+
+ case 'tbody':
+ case 'thead':
+ case 'tfoot':
+ return tag === 'tr' || tag === 'style' || tag === 'script' || tag === 'template';
+ // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup
+
+ case 'colgroup':
+ return tag === 'col' || tag === 'template';
+ // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable
+
+ case 'table':
+ return tag === 'caption' || tag === 'colgroup' || tag === 'tbody' || tag === 'tfoot' || tag === 'thead' || tag === 'style' || tag === 'script' || tag === 'template';
+ // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead
+
+ case 'head':
+ return tag === 'base' || tag === 'basefont' || tag === 'bgsound' || tag === 'link' || tag === 'meta' || tag === 'title' || tag === 'noscript' || tag === 'noframes' || tag === 'style' || tag === 'script' || tag === 'template';
+ // https://html.spec.whatwg.org/multipage/semantics.html#the-html-element
+
+ case 'html':
+ return tag === 'head' || tag === 'body' || tag === 'frameset';
+
+ case 'frameset':
+ return tag === 'frame';
+
+ case '#document':
+ return tag === 'html';
+ } // Probably in the "in body" parsing mode, so we outlaw only tag combos
+ // where the parsing rules cause implicit opens or closes to be added.
+ // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
+
+
+ switch (tag) {
+ case 'h1':
+ case 'h2':
+ case 'h3':
+ case 'h4':
+ case 'h5':
+ case 'h6':
+ return parentTag !== 'h1' && parentTag !== 'h2' && parentTag !== 'h3' && parentTag !== 'h4' && parentTag !== 'h5' && parentTag !== 'h6';
+
+ case 'rp':
+ case 'rt':
+ return impliedEndTags.indexOf(parentTag) === -1;
+
+ case 'body':
+ case 'caption':
+ case 'col':
+ case 'colgroup':
+ case 'frameset':
+ case 'frame':
+ case 'head':
+ case 'html':
+ case 'tbody':
+ case 'td':
+ case 'tfoot':
+ case 'th':
+ case 'thead':
+ case 'tr':
+ // These tags are only valid with a few parents that have special child
+ // parsing rules -- if we're down here, then none of those matched and
+ // so we allow it only if we don't know what the parent is, as all other
+ // cases are invalid.
+ return parentTag == null;
+ }
+
+ return true;
+ };
+ /**
+ * Returns whether
+ */
+
+
+ var findInvalidAncestorForTag = function (tag, ancestorInfo) {
+ switch (tag) {
+ case 'address':
+ case 'article':
+ case 'aside':
+ case 'blockquote':
+ case 'center':
+ case 'details':
+ case 'dialog':
+ case 'dir':
+ case 'div':
+ case 'dl':
+ case 'fieldset':
+ case 'figcaption':
+ case 'figure':
+ case 'footer':
+ case 'header':
+ case 'hgroup':
+ case 'main':
+ case 'menu':
+ case 'nav':
+ case 'ol':
+ case 'p':
+ case 'section':
+ case 'summary':
+ case 'ul':
+ case 'pre':
+ case 'listing':
+ case 'table':
+ case 'hr':
+ case 'xmp':
+ case 'h1':
+ case 'h2':
+ case 'h3':
+ case 'h4':
+ case 'h5':
+ case 'h6':
+ return ancestorInfo.pTagInButtonScope;
+
+ case 'form':
+ return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope;
+
+ case 'li':
+ return ancestorInfo.listItemTagAutoclosing;
+
+ case 'dd':
+ case 'dt':
+ return ancestorInfo.dlItemTagAutoclosing;
+
+ case 'button':
+ return ancestorInfo.buttonTagInScope;
+
+ case 'a':
+ // Spec says something about storing a list of markers, but it sounds
+ // equivalent to this check.
+ return ancestorInfo.aTagInScope;
+
+ case 'nobr':
+ return ancestorInfo.nobrTagInScope;
+ }
+
+ return null;
+ };
+
+ var didWarn$1 = {};
+
+ validateDOMNesting = function (childTag, childText, ancestorInfo) {
+ ancestorInfo = ancestorInfo || emptyAncestorInfo;
+ var parentInfo = ancestorInfo.current;
+ var parentTag = parentInfo && parentInfo.tag;
+
+ if (childText != null) {
+ if (childTag != null) {
+ error('validateDOMNesting: when childText is passed, childTag should be null');
+ }
+
+ childTag = '#text';
+ }
+
+ var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo;
+ var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo);
+ var invalidParentOrAncestor = invalidParent || invalidAncestor;
+
+ if (!invalidParentOrAncestor) {
+ return;
+ }
+
+ var ancestorTag = invalidParentOrAncestor.tag;
+ var addendum = getCurrentFiberStackInDev();
+ var warnKey = !!invalidParent + '|' + childTag + '|' + ancestorTag + '|' + addendum;
+
+ if (didWarn$1[warnKey]) {
+ return;
+ }
+
+ didWarn$1[warnKey] = true;
+ var tagDisplayName = childTag;
+ var whitespaceInfo = '';
+
+ if (childTag === '#text') {
+ if (/\S/.test(childText)) {
+ tagDisplayName = 'Text nodes';
+ } else {
+ tagDisplayName = 'Whitespace text nodes';
+ whitespaceInfo = " Make sure you don't have any extra whitespace between tags on " + 'each line of your source code.';
+ }
+ } else {
+ tagDisplayName = '<' + childTag + '>';
+ }
+
+ if (invalidParent) {
+ var info = '';
+
+ if (ancestorTag === 'table' && childTag === 'tr') {
+ info += ' Add a <tbody>, <thead> or <tfoot> to your code to match the DOM tree generated by ' + 'the browser.';
+ }
+
+ error('validateDOMNesting(...): %s cannot appear as a child of <%s>.%s%s', tagDisplayName, ancestorTag, whitespaceInfo, info);
+ } else {
+ error('validateDOMNesting(...): %s cannot appear as a descendant of ' + '<%s>.', tagDisplayName, ancestorTag);
+ }
+ };
+ }
+
+ var SUPPRESS_HYDRATION_WARNING$1;
+
+ {
+ SUPPRESS_HYDRATION_WARNING$1 = 'suppressHydrationWarning';
+ }
+
+ var SUSPENSE_START_DATA = '$';
+ var SUSPENSE_END_DATA = '/$';
+ var SUSPENSE_PENDING_START_DATA = '$?';
+ var SUSPENSE_FALLBACK_START_DATA = '$!';
+ var STYLE$1 = 'style';
+ var eventsEnabled = null;
+ var selectionInformation = null;
+
+ function shouldAutoFocusHostComponent(type, props) {
+ switch (type) {
+ case 'button':
+ case 'input':
+ case 'select':
+ case 'textarea':
+ return !!props.autoFocus;
+ }
+
+ return false;
+ }
+ function getRootHostContext(rootContainerInstance) {
+ var type;
+ var namespace;
+ var nodeType = rootContainerInstance.nodeType;
+
+ switch (nodeType) {
+ case DOCUMENT_NODE:
+ case DOCUMENT_FRAGMENT_NODE:
+ {
+ type = nodeType === DOCUMENT_NODE ? '#document' : '#fragment';
+ var root = rootContainerInstance.documentElement;
+ namespace = root ? root.namespaceURI : getChildNamespace(null, '');
+ break;
+ }
+
+ default:
+ {
+ var container = nodeType === COMMENT_NODE ? rootContainerInstance.parentNode : rootContainerInstance;
+ var ownNamespace = container.namespaceURI || null;
+ type = container.tagName;
+ namespace = getChildNamespace(ownNamespace, type);
+ break;
+ }
+ }
+
+ {
+ var validatedTag = type.toLowerCase();
+ var ancestorInfo = updatedAncestorInfo(null, validatedTag);
+ return {
+ namespace: namespace,
+ ancestorInfo: ancestorInfo
+ };
+ }
+ }
+ function getChildHostContext(parentHostContext, type, rootContainerInstance) {
+ {
+ var parentHostContextDev = parentHostContext;
+ var namespace = getChildNamespace(parentHostContextDev.namespace, type);
+ var ancestorInfo = updatedAncestorInfo(parentHostContextDev.ancestorInfo, type);
+ return {
+ namespace: namespace,
+ ancestorInfo: ancestorInfo
+ };
+ }
+ }
+ function getPublicInstance(instance) {
+ return instance;
+ }
+ function prepareForCommit(containerInfo) {
+ eventsEnabled = isEnabled();
+ selectionInformation = getSelectionInformation();
+ setEnabled(false);
+ }
+ function resetAfterCommit(containerInfo) {
+ restoreSelection(selectionInformation);
+ setEnabled(eventsEnabled);
+ eventsEnabled = null;
+
+ selectionInformation = null;
+ }
+ function createInstance(type, props, rootContainerInstance, hostContext, internalInstanceHandle) {
+ var parentNamespace;
+
+ {
+ // TODO: take namespace into account when validating.
+ var hostContextDev = hostContext;
+ validateDOMNesting(type, null, hostContextDev.ancestorInfo);
+
+ if (typeof props.children === 'string' || typeof props.children === 'number') {
+ var string = '' + props.children;
+ var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type);
+ validateDOMNesting(null, string, ownAncestorInfo);
+ }
+
+ parentNamespace = hostContextDev.namespace;
+ }
+
+ var domElement = createElement(type, props, rootContainerInstance, parentNamespace);
+ precacheFiberNode(internalInstanceHandle, domElement);
+ updateFiberProps(domElement, props);
+ return domElement;
+ }
+ function appendInitialChild(parentInstance, child) {
+ parentInstance.appendChild(child);
+ }
+ function finalizeInitialChildren(domElement, type, props, rootContainerInstance, hostContext) {
+ setInitialProperties(domElement, type, props, rootContainerInstance);
+ return shouldAutoFocusHostComponent(type, props);
+ }
+ function prepareUpdate(domElement, type, oldProps, newProps, rootContainerInstance, hostContext) {
+ {
+ var hostContextDev = hostContext;
+
+ if (typeof newProps.children !== typeof oldProps.children && (typeof newProps.children === 'string' || typeof newProps.children === 'number')) {
+ var string = '' + newProps.children;
+ var ownAncestorInfo = updatedAncestorInfo(hostContextDev.ancestorInfo, type);
+ validateDOMNesting(null, string, ownAncestorInfo);
+ }
+ }
+
+ return diffProperties(domElement, type, oldProps, newProps, rootContainerInstance);
+ }
+ function shouldSetTextContent(type, props) {
+ return type === 'textarea' || type === 'option' || type === 'noscript' || typeof props.children === 'string' || typeof props.children === 'number' || typeof props.dangerouslySetInnerHTML === 'object' && props.dangerouslySetInnerHTML !== null && props.dangerouslySetInnerHTML.__html != null;
+ }
+ function shouldDeprioritizeSubtree(type, props) {
+ return !!props.hidden;
+ }
+ function createTextInstance(text, rootContainerInstance, hostContext, internalInstanceHandle) {
+ {
+ var hostContextDev = hostContext;
+ validateDOMNesting(null, text, hostContextDev.ancestorInfo);
+ }
+
+ var textNode = createTextNode(text, rootContainerInstance);
+ precacheFiberNode(internalInstanceHandle, textNode);
+ return textNode;
+ }
+ // if a component just imports ReactDOM (e.g. for findDOMNode).
+ // Some environments might not have setTimeout or clearTimeout.
+
+ var scheduleTimeout = typeof setTimeout === 'function' ? setTimeout : undefined;
+ var cancelTimeout = typeof clearTimeout === 'function' ? clearTimeout : undefined;
+ var noTimeout = -1; // -------------------
+ function commitMount(domElement, type, newProps, internalInstanceHandle) {
+ // Despite the naming that might imply otherwise, this method only
+ // fires if there is an `Update` effect scheduled during mounting.
+ // This happens if `finalizeInitialChildren` returns `true` (which it
+ // does to implement the `autoFocus` attribute on the client). But
+ // there are also other cases when this might happen (such as patching
+ // up text content during hydration mismatch). So we'll check this again.
+ if (shouldAutoFocusHostComponent(type, newProps)) {
+ domElement.focus();
+ }
+ }
+ function commitUpdate(domElement, updatePayload, type, oldProps, newProps, internalInstanceHandle) {
+ // Update the props handle so that we know which props are the ones with
+ // with current event handlers.
+ updateFiberProps(domElement, newProps); // Apply the diff to the DOM node.
+
+ updateProperties(domElement, updatePayload, type, oldProps, newProps);
+ }
+ function resetTextContent(domElement) {
+ setTextContent(domElement, '');
+ }
+ function commitTextUpdate(textInstance, oldText, newText) {
+ textInstance.nodeValue = newText;
+ }
+ function appendChild(parentInstance, child) {
+ parentInstance.appendChild(child);
+ }
+ function appendChildToContainer(container, child) {
+ var parentNode;
+
+ if (container.nodeType === COMMENT_NODE) {
+ parentNode = container.parentNode;
+ parentNode.insertBefore(child, container);
+ } else {
+ parentNode = container;
+ parentNode.appendChild(child);
+ } // This container might be used for a portal.
+ // If something inside a portal is clicked, that click should bubble
+ // through the React tree. However, on Mobile Safari the click would
+ // never bubble through the *DOM* tree unless an ancestor with onclick
+ // event exists. So we wouldn't see it and dispatch it.
+ // This is why we ensure that non React root containers have inline onclick
+ // defined.
+ // https://github.com/facebook/react/issues/11918
+
+
+ var reactRootContainer = container._reactRootContainer;
+
+ if ((reactRootContainer === null || reactRootContainer === undefined) && parentNode.onclick === null) {
+ // TODO: This cast may not be sound for SVG, MathML or custom elements.
+ trapClickOnNonInteractiveElement(parentNode);
+ }
+ }
+ function insertBefore(parentInstance, child, beforeChild) {
+ parentInstance.insertBefore(child, beforeChild);
+ }
+ function insertInContainerBefore(container, child, beforeChild) {
+ if (container.nodeType === COMMENT_NODE) {
+ container.parentNode.insertBefore(child, beforeChild);
+ } else {
+ container.insertBefore(child, beforeChild);
+ }
+ }
+ function removeChild(parentInstance, child) {
+ parentInstance.removeChild(child);
+ }
+ function removeChildFromContainer(container, child) {
+ if (container.nodeType === COMMENT_NODE) {
+ container.parentNode.removeChild(child);
+ } else {
+ container.removeChild(child);
+ }
+ }
+
+ function hideInstance(instance) {
+ // pass host context to this method?
+
+
+ instance = instance;
+ var style = instance.style;
+
+ if (typeof style.setProperty === 'function') {
+ style.setProperty('display', 'none', 'important');
+ } else {
+ style.display = 'none';
+ }
+ }
+ function hideTextInstance(textInstance) {
+ textInstance.nodeValue = '';
+ }
+ function unhideInstance(instance, props) {
+ instance = instance;
+ var styleProp = props[STYLE$1];
+ var display = styleProp !== undefined && styleProp !== null && styleProp.hasOwnProperty('display') ? styleProp.display : null;
+ instance.style.display = dangerousStyleValue('display', display);
+ }
+ function unhideTextInstance(textInstance, text) {
+ textInstance.nodeValue = text;
+ } // -------------------
+ function canHydrateInstance(instance, type, props) {
+ if (instance.nodeType !== ELEMENT_NODE || type.toLowerCase() !== instance.nodeName.toLowerCase()) {
+ return null;
+ } // This has now been refined to an element node.
+
+
+ return instance;
+ }
+ function canHydrateTextInstance(instance, text) {
+ if (text === '' || instance.nodeType !== TEXT_NODE) {
+ // Empty strings are not parsed by HTML so there won't be a correct match here.
+ return null;
+ } // This has now been refined to a text node.
+
+
+ return instance;
+ }
+ function isSuspenseInstancePending(instance) {
+ return instance.data === SUSPENSE_PENDING_START_DATA;
+ }
+ function isSuspenseInstanceFallback(instance) {
+ return instance.data === SUSPENSE_FALLBACK_START_DATA;
+ }
+
+ function getNextHydratable(node) {
+ // Skip non-hydratable nodes.
+ for (; node != null; node = node.nextSibling) {
+ var nodeType = node.nodeType;
+
+ if (nodeType === ELEMENT_NODE || nodeType === TEXT_NODE) {
+ break;
+ }
+ }
+
+ return node;
+ }
+
+ function getNextHydratableSibling(instance) {
+ return getNextHydratable(instance.nextSibling);
+ }
+ function getFirstHydratableChild(parentInstance) {
+ return getNextHydratable(parentInstance.firstChild);
+ }
+ function hydrateInstance(instance, type, props, rootContainerInstance, hostContext, internalInstanceHandle) {
+ precacheFiberNode(internalInstanceHandle, instance); // TODO: Possibly defer this until the commit phase where all the events
+ // get attached.
+
+ updateFiberProps(instance, props);
+ var parentNamespace;
+
+ {
+ var hostContextDev = hostContext;
+ parentNamespace = hostContextDev.namespace;
+ }
+
+ return diffHydratedProperties(instance, type, props, parentNamespace, rootContainerInstance);
+ }
+ function hydrateTextInstance(textInstance, text, internalInstanceHandle) {
+ precacheFiberNode(internalInstanceHandle, textInstance);
+ return diffHydratedText(textInstance, text);
+ }
+ function getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance) {
+ var node = suspenseInstance.nextSibling; // Skip past all nodes within this suspense boundary.
+ // There might be nested nodes so we need to keep track of how
+ // deep we are and only break out when we're back on top.
+
+ var depth = 0;
+
+ while (node) {
+ if (node.nodeType === COMMENT_NODE) {
+ var data = node.data;
+
+ if (data === SUSPENSE_END_DATA) {
+ if (depth === 0) {
+ return getNextHydratableSibling(node);
+ } else {
+ depth--;
+ }
+ } else if (data === SUSPENSE_START_DATA || data === SUSPENSE_FALLBACK_START_DATA || data === SUSPENSE_PENDING_START_DATA) {
+ depth++;
+ }
+ }
+
+ node = node.nextSibling;
+ } // TODO: Warn, we didn't find the end comment boundary.
+
+
+ return null;
+ } // Returns the SuspenseInstance if this node is a direct child of a
+ // SuspenseInstance. I.e. if its previous sibling is a Comment with
+ // SUSPENSE_x_START_DATA. Otherwise, null.
+
+ function getParentSuspenseInstance(targetInstance) {
+ var node = targetInstance.previousSibling; // Skip past all nodes within this suspense boundary.
+ // There might be nested nodes so we need to keep track of how
+ // deep we are and only break out when we're back on top.
+
+ var depth = 0;
+
+ while (node) {
+ if (node.nodeType === COMMENT_NODE) {
+ var data = node.data;
+
+ if (data === SUSPENSE_START_DATA || data === SUSPENSE_FALLBACK_START_DATA || data === SUSPENSE_PENDING_START_DATA) {
+ if (depth === 0) {
+ return node;
+ } else {
+ depth--;
+ }
+ } else if (data === SUSPENSE_END_DATA) {
+ depth++;
+ }
+ }
+
+ node = node.previousSibling;
+ }
+
+ return null;
+ }
+ function commitHydratedContainer(container) {
+ // Retry if any event replaying was blocked on this.
+ retryIfBlockedOn(container);
+ }
+ function commitHydratedSuspenseInstance(suspenseInstance) {
+ // Retry if any event replaying was blocked on this.
+ retryIfBlockedOn(suspenseInstance);
+ }
+ function didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, text) {
+ {
+ warnForUnmatchedText(textInstance, text);
+ }
+ }
+ function didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, text) {
+ if ( parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) {
+ warnForUnmatchedText(textInstance, text);
+ }
+ }
+ function didNotHydrateContainerInstance(parentContainer, instance) {
+ {
+ if (instance.nodeType === ELEMENT_NODE) {
+ warnForDeletedHydratableElement(parentContainer, instance);
+ } else if (instance.nodeType === COMMENT_NODE) ; else {
+ warnForDeletedHydratableText(parentContainer, instance);
+ }
+ }
+ }
+ function didNotHydrateInstance(parentType, parentProps, parentInstance, instance) {
+ if ( parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) {
+ if (instance.nodeType === ELEMENT_NODE) {
+ warnForDeletedHydratableElement(parentInstance, instance);
+ } else if (instance.nodeType === COMMENT_NODE) ; else {
+ warnForDeletedHydratableText(parentInstance, instance);
+ }
+ }
+ }
+ function didNotFindHydratableContainerInstance(parentContainer, type, props) {
+ {
+ warnForInsertedHydratedElement(parentContainer, type);
+ }
+ }
+ function didNotFindHydratableContainerTextInstance(parentContainer, text) {
+ {
+ warnForInsertedHydratedText(parentContainer, text);
+ }
+ }
+ function didNotFindHydratableInstance(parentType, parentProps, parentInstance, type, props) {
+ if ( parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) {
+ warnForInsertedHydratedElement(parentInstance, type);
+ }
+ }
+ function didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, text) {
+ if ( parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) {
+ warnForInsertedHydratedText(parentInstance, text);
+ }
+ }
+ function didNotFindHydratableSuspenseInstance(parentType, parentProps, parentInstance) {
+ if ( parentProps[SUPPRESS_HYDRATION_WARNING$1] !== true) ;
+ }
+
+ var randomKey = Math.random().toString(36).slice(2);
+ var internalInstanceKey = '__reactInternalInstance$' + randomKey;
+ var internalEventHandlersKey = '__reactEventHandlers$' + randomKey;
+ var internalContainerInstanceKey = '__reactContainere$' + randomKey;
+ function precacheFiberNode(hostInst, node) {
+ node[internalInstanceKey] = hostInst;
+ }
+ function markContainerAsRoot(hostRoot, node) {
+ node[internalContainerInstanceKey] = hostRoot;
+ }
+ function unmarkContainerAsRoot(node) {
+ node[internalContainerInstanceKey] = null;
+ }
+ function isContainerMarkedAsRoot(node) {
+ return !!node[internalContainerInstanceKey];
+ } // Given a DOM node, return the closest HostComponent or HostText fiber ancestor.
+ // If the target node is part of a hydrated or not yet rendered subtree, then
+ // this may also return a SuspenseComponent or HostRoot to indicate that.
+ // Conceptually the HostRoot fiber is a child of the Container node. So if you
+ // pass the Container node as the targetNode, you will not actually get the
+ // HostRoot back. To get to the HostRoot, you need to pass a child of it.
+ // The same thing applies to Suspense boundaries.
+
+ function getClosestInstanceFromNode(targetNode) {
+ var targetInst = targetNode[internalInstanceKey];
+
+ if (targetInst) {
+ // Don't return HostRoot or SuspenseComponent here.
+ return targetInst;
+ } // If the direct event target isn't a React owned DOM node, we need to look
+ // to see if one of its parents is a React owned DOM node.
+
+
+ var parentNode = targetNode.parentNode;
+
+ while (parentNode) {
+ // We'll check if this is a container root that could include
+ // React nodes in the future. We need to check this first because
+ // if we're a child of a dehydrated container, we need to first
+ // find that inner container before moving on to finding the parent
+ // instance. Note that we don't check this field on the targetNode
+ // itself because the fibers are conceptually between the container
+ // node and the first child. It isn't surrounding the container node.
+ // If it's not a container, we check if it's an instance.
+ targetInst = parentNode[internalContainerInstanceKey] || parentNode[internalInstanceKey];
+
+ if (targetInst) {
+ // Since this wasn't the direct target of the event, we might have
+ // stepped past dehydrated DOM nodes to get here. However they could
+ // also have been non-React nodes. We need to answer which one.
+ // If we the instance doesn't have any children, then there can't be
+ // a nested suspense boundary within it. So we can use this as a fast
+ // bailout. Most of the time, when people add non-React children to
+ // the tree, it is using a ref to a child-less DOM node.
+ // Normally we'd only need to check one of the fibers because if it
+ // has ever gone from having children to deleting them or vice versa
+ // it would have deleted the dehydrated boundary nested inside already.
+ // However, since the HostRoot starts out with an alternate it might
+ // have one on the alternate so we need to check in case this was a
+ // root.
+ var alternate = targetInst.alternate;
+
+ if (targetInst.child !== null || alternate !== null && alternate.child !== null) {
+ // Next we need to figure out if the node that skipped past is
+ // nested within a dehydrated boundary and if so, which one.
+ var suspenseInstance = getParentSuspenseInstance(targetNode);
+
+ while (suspenseInstance !== null) {
+ // We found a suspense instance. That means that we haven't
+ // hydrated it yet. Even though we leave the comments in the
+ // DOM after hydrating, and there are boundaries in the DOM
+ // that could already be hydrated, we wouldn't have found them
+ // through this pass since if the target is hydrated it would
+ // have had an internalInstanceKey on it.
+ // Let's get the fiber associated with the SuspenseComponent
+ // as the deepest instance.
+ var targetSuspenseInst = suspenseInstance[internalInstanceKey];
+
+ if (targetSuspenseInst) {
+ return targetSuspenseInst;
+ } // If we don't find a Fiber on the comment, it might be because
+ // we haven't gotten to hydrate it yet. There might still be a
+ // parent boundary that hasn't above this one so we need to find
+ // the outer most that is known.
+
+
+ suspenseInstance = getParentSuspenseInstance(suspenseInstance); // If we don't find one, then that should mean that the parent
+ // host component also hasn't hydrated yet. We can return it
+ // below since it will bail out on the isMounted check later.
+ }
+ }
+
+ return targetInst;
+ }
+
+ targetNode = parentNode;
+ parentNode = targetNode.parentNode;
+ }
+
+ return null;
+ }
+ /**
+ * Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent
+ * instance, or null if the node was not rendered by this React.
+ */
+
+ function getInstanceFromNode$1(node) {
+ var inst = node[internalInstanceKey] || node[internalContainerInstanceKey];
+
+ if (inst) {
+ if (inst.tag === HostComponent || inst.tag === HostText || inst.tag === SuspenseComponent || inst.tag === HostRoot) {
+ return inst;
+ } else {
+ return null;
+ }
+ }
+
+ return null;
+ }
+ /**
+ * Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding
+ * DOM node.
+ */
+
+ function getNodeFromInstance$1(inst) {
+ if (inst.tag === HostComponent || inst.tag === HostText) {
+ // In Fiber this, is just the state node right now. We assume it will be
+ // a host component or host text.
+ return inst.stateNode;
+ } // Without this first invariant, passing a non-DOM-component triggers the next
+ // invariant for a missing parent, which is super confusing.
+
+
+ {
+ {
+ throw Error( "getNodeFromInstance: Invalid argument." );
+ }
+ }
+ }
+ function getFiberCurrentPropsFromNode$1(node) {
+ return node[internalEventHandlersKey] || null;
+ }
+ function updateFiberProps(node, props) {
+ node[internalEventHandlersKey] = props;
+ }
+
+ function getParent(inst) {
+ do {
+ inst = inst.return; // TODO: If this is a HostRoot we might want to bail out.
+ // That is depending on if we want nested subtrees (layers) to bubble
+ // events to their parent. We could also go through parentNode on the
+ // host node but that wouldn't work for React Native and doesn't let us
+ // do the portal feature.
+ } while (inst && inst.tag !== HostComponent);
+
+ if (inst) {
+ return inst;
+ }
+
+ return null;
+ }
+ /**
+ * Return the lowest common ancestor of A and B, or null if they are in
+ * different trees.
+ */
+
+
+ function getLowestCommonAncestor(instA, instB) {
+ var depthA = 0;
+
+ for (var tempA = instA; tempA; tempA = getParent(tempA)) {
+ depthA++;
+ }
+
+ var depthB = 0;
+
+ for (var tempB = instB; tempB; tempB = getParent(tempB)) {
+ depthB++;
+ } // If A is deeper, crawl up.
+
+
+ while (depthA - depthB > 0) {
+ instA = getParent(instA);
+ depthA--;
+ } // If B is deeper, crawl up.
+
+
+ while (depthB - depthA > 0) {
+ instB = getParent(instB);
+ depthB--;
+ } // Walk in lockstep until we find a match.
+
+
+ var depth = depthA;
+
+ while (depth--) {
+ if (instA === instB || instA === instB.alternate) {
+ return instA;
+ }
+
+ instA = getParent(instA);
+ instB = getParent(instB);
+ }
+
+ return null;
+ }
+ /**
+ * Simulates the traversal of a two-phase, capture/bubble event dispatch.
+ */
+
+ function traverseTwoPhase(inst, fn, arg) {
+ var path = [];
+
+ while (inst) {
+ path.push(inst);
+ inst = getParent(inst);
+ }
+
+ var i;
+
+ for (i = path.length; i-- > 0;) {
+ fn(path[i], 'captured', arg);
+ }
+
+ for (i = 0; i < path.length; i++) {
+ fn(path[i], 'bubbled', arg);
+ }
+ }
+ /**
+ * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that
+ * should would receive a `mouseEnter` or `mouseLeave` event.
+ *
+ * Does not invoke the callback on the nearest common ancestor because nothing
+ * "entered" or "left" that element.
+ */
+
+ function traverseEnterLeave(from, to, fn, argFrom, argTo) {
+ var common = from && to ? getLowestCommonAncestor(from, to) : null;
+ var pathFrom = [];
+
+ while (true) {
+ if (!from) {
+ break;
+ }
+
+ if (from === common) {
+ break;
+ }
+
+ var alternate = from.alternate;
+
+ if (alternate !== null && alternate === common) {
+ break;
+ }
+
+ pathFrom.push(from);
+ from = getParent(from);
+ }
+
+ var pathTo = [];
+
+ while (true) {
+ if (!to) {
+ break;
+ }
+
+ if (to === common) {
+ break;
+ }
+
+ var _alternate = to.alternate;
+
+ if (_alternate !== null && _alternate === common) {
+ break;
+ }
+
+ pathTo.push(to);
+ to = getParent(to);
+ }
+
+ for (var i = 0; i < pathFrom.length; i++) {
+ fn(pathFrom[i], 'bubbled', argFrom);
+ }
+
+ for (var _i = pathTo.length; _i-- > 0;) {
+ fn(pathTo[_i], 'captured', argTo);
+ }
+ }
+
+ function isInteractive(tag) {
+ return tag === 'button' || tag === 'input' || tag === 'select' || tag === 'textarea';
+ }
+
+ function shouldPreventMouseEvent(name, type, props) {
+ switch (name) {
+ case 'onClick':
+ case 'onClickCapture':
+ case 'onDoubleClick':
+ case 'onDoubleClickCapture':
+ case 'onMouseDown':
+ case 'onMouseDownCapture':
+ case 'onMouseMove':
+ case 'onMouseMoveCapture':
+ case 'onMouseUp':
+ case 'onMouseUpCapture':
+ case 'onMouseEnter':
+ return !!(props.disabled && isInteractive(type));
+
+ default:
+ return false;
+ }
+ }
+ /**
+ * @param {object} inst The instance, which is the source of events.
+ * @param {string} registrationName Name of listener (e.g. `onClick`).
+ * @return {?function} The stored callback.
+ */
+
+
+ function getListener(inst, registrationName) {
+ var listener; // TODO: shouldPreventMouseEvent is DOM-specific and definitely should not
+ // live here; needs to be moved to a better place soon
+
+ var stateNode = inst.stateNode;
+
+ if (!stateNode) {
+ // Work in progress (ex: onload events in incremental mode).
+ return null;
+ }
+
+ var props = getFiberCurrentPropsFromNode(stateNode);
+
+ if (!props) {
+ // Work in progress.
+ return null;
+ }
+
+ listener = props[registrationName];
+
+ if (shouldPreventMouseEvent(registrationName, inst.type, props)) {
+ return null;
+ }
+
+ if (!(!listener || typeof listener === 'function')) {
+ {
+ throw Error( "Expected `" + registrationName + "` listener to be a function, instead got a value of `" + typeof listener + "` type." );
+ }
+ }
+
+ return listener;
+ }
+
+ /**
+ * Some event types have a notion of different registration names for different
+ * "phases" of propagation. This finds listeners by a given phase.
+ */
+ function listenerAtPhase(inst, event, propagationPhase) {
+ var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase];
+ return getListener(inst, registrationName);
+ }
+ /**
+ * A small set of propagation patterns, each of which will accept a small amount
+ * of information, and generate a set of "dispatch ready event objects" - which
+ * are sets of events that have already been annotated with a set of dispatched
+ * listener functions/ids. The API is designed this way to discourage these
+ * propagation strategies from actually executing the dispatches, since we
+ * always want to collect the entire set of dispatches before executing even a
+ * single one.
+ */
+
+ /**
+ * Tags a `SyntheticEvent` with dispatched listeners. Creating this function
+ * here, allows us to not have to bind or create functions for each event.
+ * Mutating the event's members allows us to not have to create a wrapping
+ * "dispatch" object that pairs the event with the listener.
+ */
+
+
+ function accumulateDirectionalDispatches(inst, phase, event) {
+ {
+ if (!inst) {
+ error('Dispatching inst must not be null');
+ }
+ }
+
+ var listener = listenerAtPhase(inst, event, phase);
+
+ if (listener) {
+ event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);
+ event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);
+ }
+ }
+ /**
+ * Collect dispatches (must be entirely collected before dispatching - see unit
+ * tests). Lazily allocate the array to conserve memory. We must loop through
+ * each event and perform the traversal for each one. We cannot perform a
+ * single traversal for the entire collection of events because each event may
+ * have a different target.
+ */
+
+
+ function accumulateTwoPhaseDispatchesSingle(event) {
+ if (event && event.dispatchConfig.phasedRegistrationNames) {
+ traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event);
+ }
+ }
+ /**
+ * Accumulates without regard to direction, does not look for phased
+ * registration names. Same as `accumulateDirectDispatchesSingle` but without
+ * requiring that the `dispatchMarker` be the same as the dispatched ID.
+ */
+
+
+ function accumulateDispatches(inst, ignoredDirection, event) {
+ if (inst && event && event.dispatchConfig.registrationName) {
+ var registrationName = event.dispatchConfig.registrationName;
+ var listener = getListener(inst, registrationName);
+
+ if (listener) {
+ event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);
+ event._dispatchInstances = accumulateInto(event._dispatchInstances, inst);
+ }
+ }
+ }
+ /**
+ * Accumulates dispatches on an `SyntheticEvent`, but only for the
+ * `dispatchMarker`.
+ * @param {SyntheticEvent} event
+ */
+
+
+ function accumulateDirectDispatchesSingle(event) {
+ if (event && event.dispatchConfig.registrationName) {
+ accumulateDispatches(event._targetInst, null, event);
+ }
+ }
+
+ function accumulateTwoPhaseDispatches(events) {
+ forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle);
+ }
+ function accumulateEnterLeaveDispatches(leave, enter, from, to) {
+ traverseEnterLeave(from, to, accumulateDispatches, leave, enter);
+ }
+ function accumulateDirectDispatches(events) {
+ forEachAccumulated(events, accumulateDirectDispatchesSingle);
+ }
+
+ /**
+ * These variables store information about text content of a target node,
+ * allowing comparison of content before and after a given event.
+ *
+ * Identify the node where selection currently begins, then observe
+ * both its text content and its current position in the DOM. Since the
+ * browser may natively replace the target node during composition, we can
+ * use its position to find its replacement.
+ *
+ *
+ */
+ var root = null;
+ var startText = null;
+ var fallbackText = null;
+ function initialize(nativeEventTarget) {
+ root = nativeEventTarget;
+ startText = getText();
+ return true;
+ }
+ function reset() {
+ root = null;
+ startText = null;
+ fallbackText = null;
+ }
+ function getData() {
+ if (fallbackText) {
+ return fallbackText;
+ }
+
+ var start;
+ var startValue = startText;
+ var startLength = startValue.length;
+ var end;
+ var endValue = getText();
+ var endLength = endValue.length;
+
+ for (start = 0; start < startLength; start++) {
+ if (startValue[start] !== endValue[start]) {
+ break;
+ }
+ }
+
+ var minEnd = startLength - start;
+
+ for (end = 1; end <= minEnd; end++) {
+ if (startValue[startLength - end] !== endValue[endLength - end]) {
+ break;
+ }
+ }
+
+ var sliceTail = end > 1 ? 1 - end : undefined;
+ fallbackText = endValue.slice(start, sliceTail);
+ return fallbackText;
+ }
+ function getText() {
+ if ('value' in root) {
+ return root.value;
+ }
+
+ return root.textContent;
+ }
+
+ var EVENT_POOL_SIZE = 10;
+ /**
+ * @interface Event
+ * @see http://www.w3.org/TR/DOM-Level-3-Events/
+ */
+
+ var EventInterface = {
+ type: null,
+ target: null,
+ // currentTarget is set when dispatching; no use in copying it here
+ currentTarget: function () {
+ return null;
+ },
+ eventPhase: null,
+ bubbles: null,
+ cancelable: null,
+ timeStamp: function (event) {
+ return event.timeStamp || Date.now();
+ },
+ defaultPrevented: null,
+ isTrusted: null
+ };
+
+ function functionThatReturnsTrue() {
+ return true;
+ }
+
+ function functionThatReturnsFalse() {
+ return false;
+ }
+ /**
+ * Synthetic events are dispatched by event plugins, typically in response to a
+ * top-level event delegation handler.
+ *
+ * These systems should generally use pooling to reduce the frequency of garbage
+ * collection. The system should check `isPersistent` to determine whether the
+ * event should be released into the pool after being dispatched. Users that
+ * need a persisted event should invoke `persist`.
+ *
+ * Synthetic events (and subclasses) implement the DOM Level 3 Events API by
+ * normalizing browser quirks. Subclasses do not necessarily have to implement a
+ * DOM interface; custom application-specific events can also subclass this.
+ *
+ * @param {object} dispatchConfig Configuration used to dispatch this event.
+ * @param {*} targetInst Marker identifying the event target.
+ * @param {object} nativeEvent Native browser event.
+ * @param {DOMEventTarget} nativeEventTarget Target node.
+ */
+
+
+ function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) {
+ {
+ // these have a getter/setter for warnings
+ delete this.nativeEvent;
+ delete this.preventDefault;
+ delete this.stopPropagation;
+ delete this.isDefaultPrevented;
+ delete this.isPropagationStopped;
+ }
+
+ this.dispatchConfig = dispatchConfig;
+ this._targetInst = targetInst;
+ this.nativeEvent = nativeEvent;
+ var Interface = this.constructor.Interface;
+
+ for (var propName in Interface) {
+ if (!Interface.hasOwnProperty(propName)) {
+ continue;
+ }
+
+ {
+ delete this[propName]; // this has a getter/setter for warnings
+ }
+
+ var normalize = Interface[propName];
+
+ if (normalize) {
+ this[propName] = normalize(nativeEvent);
+ } else {
+ if (propName === 'target') {
+ this.target = nativeEventTarget;
+ } else {
+ this[propName] = nativeEvent[propName];
+ }
+ }
+ }
+
+ var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false;
+
+ if (defaultPrevented) {
+ this.isDefaultPrevented = functionThatReturnsTrue;
+ } else {
+ this.isDefaultPrevented = functionThatReturnsFalse;
+ }
+
+ this.isPropagationStopped = functionThatReturnsFalse;
+ return this;
+ }
+
+ _assign(SyntheticEvent.prototype, {
+ preventDefault: function () {
+ this.defaultPrevented = true;
+ var event = this.nativeEvent;
+
+ if (!event) {
+ return;
+ }
+
+ if (event.preventDefault) {
+ event.preventDefault();
+ } else if (typeof event.returnValue !== 'unknown') {
+ event.returnValue = false;
+ }
+
+ this.isDefaultPrevented = functionThatReturnsTrue;
+ },
+ stopPropagation: function () {
+ var event = this.nativeEvent;
+
+ if (!event) {
+ return;
+ }
+
+ if (event.stopPropagation) {
+ event.stopPropagation();
+ } else if (typeof event.cancelBubble !== 'unknown') {
+ // The ChangeEventPlugin registers a "propertychange" event for
+ // IE. This event does not support bubbling or cancelling, and
+ // any references to cancelBubble throw "Member not found". A
+ // typeof check of "unknown" circumvents this issue (and is also
+ // IE specific).
+ event.cancelBubble = true;
+ }
+
+ this.isPropagationStopped = functionThatReturnsTrue;
+ },
+
+ /**
+ * We release all dispatched `SyntheticEvent`s after each event loop, adding
+ * them back into the pool. This allows a way to hold onto a reference that
+ * won't be added back into the pool.
+ */
+ persist: function () {
+ this.isPersistent = functionThatReturnsTrue;
+ },
+
+ /**
+ * Checks if this event should be released back into the pool.
+ *
+ * @return {boolean} True if this should not be released, false otherwise.
+ */
+ isPersistent: functionThatReturnsFalse,
+
+ /**
+ * `PooledClass` looks for `destructor` on each instance it releases.
+ */
+ destructor: function () {
+ var Interface = this.constructor.Interface;
+
+ for (var propName in Interface) {
+ {
+ Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName]));
+ }
+ }
+
+ this.dispatchConfig = null;
+ this._targetInst = null;
+ this.nativeEvent = null;
+ this.isDefaultPrevented = functionThatReturnsFalse;
+ this.isPropagationStopped = functionThatReturnsFalse;
+ this._dispatchListeners = null;
+ this._dispatchInstances = null;
+
+ {
+ Object.defineProperty(this, 'nativeEvent', getPooledWarningPropertyDefinition('nativeEvent', null));
+ Object.defineProperty(this, 'isDefaultPrevented', getPooledWarningPropertyDefinition('isDefaultPrevented', functionThatReturnsFalse));
+ Object.defineProperty(this, 'isPropagationStopped', getPooledWarningPropertyDefinition('isPropagationStopped', functionThatReturnsFalse));
+ Object.defineProperty(this, 'preventDefault', getPooledWarningPropertyDefinition('preventDefault', function () {}));
+ Object.defineProperty(this, 'stopPropagation', getPooledWarningPropertyDefinition('stopPropagation', function () {}));
+ }
+ }
+ });
+
+ SyntheticEvent.Interface = EventInterface;
+ /**
+ * Helper to reduce boilerplate when creating subclasses.
+ */
+
+ SyntheticEvent.extend = function (Interface) {
+ var Super = this;
+
+ var E = function () {};
+
+ E.prototype = Super.prototype;
+ var prototype = new E();
+
+ function Class() {
+ return Super.apply(this, arguments);
+ }
+
+ _assign(prototype, Class.prototype);
+
+ Class.prototype = prototype;
+ Class.prototype.constructor = Class;
+ Class.Interface = _assign({}, Super.Interface, Interface);
+ Class.extend = Super.extend;
+ addEventPoolingTo(Class);
+ return Class;
+ };
+
+ addEventPoolingTo(SyntheticEvent);
+ /**
+ * Helper to nullify syntheticEvent instance properties when destructing
+ *
+ * @param {String} propName
+ * @param {?object} getVal
+ * @return {object} defineProperty object
+ */
+
+ function getPooledWarningPropertyDefinition(propName, getVal) {
+ var isFunction = typeof getVal === 'function';
+ return {
+ configurable: true,
+ set: set,
+ get: get
+ };
+
+ function set(val) {
+ var action = isFunction ? 'setting the method' : 'setting the property';
+ warn(action, 'This is effectively a no-op');
+ return val;
+ }
+
+ function get() {
+ var action = isFunction ? 'accessing the method' : 'accessing the property';
+ var result = isFunction ? 'This is a no-op function' : 'This is set to null';
+ warn(action, result);
+ return getVal;
+ }
+
+ function warn(action, result) {
+ {
+ error("This synthetic event is reused for performance reasons. If you're seeing this, " + "you're %s `%s` on a released/nullified synthetic event. %s. " + 'If you must keep the original synthetic event around, use event.persist(). ' + 'See https://fb.me/react-event-pooling for more information.', action, propName, result);
+ }
+ }
+ }
+
+ function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) {
+ var EventConstructor = this;
+
+ if (EventConstructor.eventPool.length) {
+ var instance = EventConstructor.eventPool.pop();
+ EventConstructor.call(instance, dispatchConfig, targetInst, nativeEvent, nativeInst);
+ return instance;
+ }
+
+ return new EventConstructor(dispatchConfig, targetInst, nativeEvent, nativeInst);
+ }
+
+ function releasePooledEvent(event) {
+ var EventConstructor = this;
+
+ if (!(event instanceof EventConstructor)) {
+ {
+ throw Error( "Trying to release an event instance into a pool of a different type." );
+ }
+ }
+
+ event.destructor();
+
+ if (EventConstructor.eventPool.length < EVENT_POOL_SIZE) {
+ EventConstructor.eventPool.push(event);
+ }
+ }
+
+ function addEventPoolingTo(EventConstructor) {
+ EventConstructor.eventPool = [];
+ EventConstructor.getPooled = getPooledEvent;
+ EventConstructor.release = releasePooledEvent;
+ }
+
+ /**
+ * @interface Event
+ * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents
+ */
+
+ var SyntheticCompositionEvent = SyntheticEvent.extend({
+ data: null
+ });
+
+ /**
+ * @interface Event
+ * @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105
+ * /#events-inputevents
+ */
+
+ var SyntheticInputEvent = SyntheticEvent.extend({
+ data: null
+ });
+
+ var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space
+
+ var START_KEYCODE = 229;
+ var canUseCompositionEvent = canUseDOM && 'CompositionEvent' in window;
+ var documentMode = null;
+
+ if (canUseDOM && 'documentMode' in document) {
+ documentMode = document.documentMode;
+ } // Webkit offers a very useful `textInput` event that can be used to
+ // directly represent `beforeInput`. The IE `textinput` event is not as
+ // useful, so we don't use it.
+
+
+ var canUseTextInputEvent = canUseDOM && 'TextEvent' in window && !documentMode; // In IE9+, we have access to composition events, but the data supplied
+ // by the native compositionend event may be incorrect. Japanese ideographic
+ // spaces, for instance (\u3000) are not recorded correctly.
+
+ var useFallbackCompositionData = canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11);
+ var SPACEBAR_CODE = 32;
+ var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE); // Events and their corresponding property names.
+
+ var eventTypes = {
+ beforeInput: {
+ phasedRegistrationNames: {
+ bubbled: 'onBeforeInput',
+ captured: 'onBeforeInputCapture'
+ },
+ dependencies: [TOP_COMPOSITION_END, TOP_KEY_PRESS, TOP_TEXT_INPUT, TOP_PASTE]
+ },
+ compositionEnd: {
+ phasedRegistrationNames: {
+ bubbled: 'onCompositionEnd',
+ captured: 'onCompositionEndCapture'
+ },
+ dependencies: [TOP_BLUR, TOP_COMPOSITION_END, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_MOUSE_DOWN]
+ },
+ compositionStart: {
+ phasedRegistrationNames: {
+ bubbled: 'onCompositionStart',
+ captured: 'onCompositionStartCapture'
+ },
+ dependencies: [TOP_BLUR, TOP_COMPOSITION_START, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_MOUSE_DOWN]
+ },
+ compositionUpdate: {
+ phasedRegistrationNames: {
+ bubbled: 'onCompositionUpdate',
+ captured: 'onCompositionUpdateCapture'
+ },
+ dependencies: [TOP_BLUR, TOP_COMPOSITION_UPDATE, TOP_KEY_DOWN, TOP_KEY_PRESS, TOP_KEY_UP, TOP_MOUSE_DOWN]
+ }
+ }; // Track whether we've ever handled a keypress on the space key.
+
+ var hasSpaceKeypress = false;
+ /**
+ * Return whether a native keypress event is assumed to be a command.
+ * This is required because Firefox fires `keypress` events for key commands
+ * (cut, copy, select-all, etc.) even though no character is inserted.
+ */
+
+ function isKeypressCommand(nativeEvent) {
+ return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) && // ctrlKey && altKey is equivalent to AltGr, and is not a command.
+ !(nativeEvent.ctrlKey && nativeEvent.altKey);
+ }
+ /**
+ * Translate native top level events into event types.
+ *
+ * @param {string} topLevelType
+ * @return {object}
+ */
+
+
+ function getCompositionEventType(topLevelType) {
+ switch (topLevelType) {
+ case TOP_COMPOSITION_START:
+ return eventTypes.compositionStart;
+
+ case TOP_COMPOSITION_END:
+ return eventTypes.compositionEnd;
+
+ case TOP_COMPOSITION_UPDATE:
+ return eventTypes.compositionUpdate;
+ }
+ }
+ /**
+ * Does our fallback best-guess model think this event signifies that
+ * composition has begun?
+ *
+ * @param {string} topLevelType
+ * @param {object} nativeEvent
+ * @return {boolean}
+ */
+
+
+ function isFallbackCompositionStart(topLevelType, nativeEvent) {
+ return topLevelType === TOP_KEY_DOWN && nativeEvent.keyCode === START_KEYCODE;
+ }
+ /**
+ * Does our fallback mode think that this event is the end of composition?
+ *
+ * @param {string} topLevelType
+ * @param {object} nativeEvent
+ * @return {boolean}
+ */
+
+
+ function isFallbackCompositionEnd(topLevelType, nativeEvent) {
+ switch (topLevelType) {
+ case TOP_KEY_UP:
+ // Command keys insert or clear IME input.
+ return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1;
+
+ case TOP_KEY_DOWN:
+ // Expect IME keyCode on each keydown. If we get any other
+ // code we must have exited earlier.
+ return nativeEvent.keyCode !== START_KEYCODE;
+
+ case TOP_KEY_PRESS:
+ case TOP_MOUSE_DOWN:
+ case TOP_BLUR:
+ // Events are not possible without cancelling IME.
+ return true;
+
+ default:
+ return false;
+ }
+ }
+ /**
+ * Google Input Tools provides composition data via a CustomEvent,
+ * with the `data` property populated in the `detail` object. If this
+ * is available on the event object, use it. If not, this is a plain
+ * composition event and we have nothing special to extract.
+ *
+ * @param {object} nativeEvent
+ * @return {?string}
+ */
+
+
+ function getDataFromCustomEvent(nativeEvent) {
+ var detail = nativeEvent.detail;
+
+ if (typeof detail === 'object' && 'data' in detail) {
+ return detail.data;
+ }
+
+ return null;
+ }
+ /**
+ * Check if a composition event was triggered by Korean IME.
+ * Our fallback mode does not work well with IE's Korean IME,
+ * so just use native composition events when Korean IME is used.
+ * Although CompositionEvent.locale property is deprecated,
+ * it is available in IE, where our fallback mode is enabled.
+ *
+ * @param {object} nativeEvent
+ * @return {boolean}
+ */
+
+
+ function isUsingKoreanIME(nativeEvent) {
+ return nativeEvent.locale === 'ko';
+ } // Track the current IME composition status, if any.
+
+
+ var isComposing = false;
+ /**
+ * @return {?object} A SyntheticCompositionEvent.
+ */
+
+ function extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
+ var eventType;
+ var fallbackData;
+
+ if (canUseCompositionEvent) {
+ eventType = getCompositionEventType(topLevelType);
+ } else if (!isComposing) {
+ if (isFallbackCompositionStart(topLevelType, nativeEvent)) {
+ eventType = eventTypes.compositionStart;
+ }
+ } else if (isFallbackCompositionEnd(topLevelType, nativeEvent)) {
+ eventType = eventTypes.compositionEnd;
+ }
+
+ if (!eventType) {
+ return null;
+ }
+
+ if (useFallbackCompositionData && !isUsingKoreanIME(nativeEvent)) {
+ // The current composition is stored statically and must not be
+ // overwritten while composition continues.
+ if (!isComposing && eventType === eventTypes.compositionStart) {
+ isComposing = initialize(nativeEventTarget);
+ } else if (eventType === eventTypes.compositionEnd) {
+ if (isComposing) {
+ fallbackData = getData();
+ }
+ }
+ }
+
+ var event = SyntheticCompositionEvent.getPooled(eventType, targetInst, nativeEvent, nativeEventTarget);
+
+ if (fallbackData) {
+ // Inject data generated from fallback path into the synthetic event.
+ // This matches the property of native CompositionEventInterface.
+ event.data = fallbackData;
+ } else {
+ var customData = getDataFromCustomEvent(nativeEvent);
+
+ if (customData !== null) {
+ event.data = customData;
+ }
+ }
+
+ accumulateTwoPhaseDispatches(event);
+ return event;
+ }
+ /**
+ * @param {TopLevelType} topLevelType Number from `TopLevelType`.
+ * @param {object} nativeEvent Native browser event.
+ * @return {?string} The string corresponding to this `beforeInput` event.
+ */
+
+
+ function getNativeBeforeInputChars(topLevelType, nativeEvent) {
+ switch (topLevelType) {
+ case TOP_COMPOSITION_END:
+ return getDataFromCustomEvent(nativeEvent);
+
+ case TOP_KEY_PRESS:
+ /**
+ * If native `textInput` events are available, our goal is to make
+ * use of them. However, there is a special case: the spacebar key.
+ * In Webkit, preventing default on a spacebar `textInput` event
+ * cancels character insertion, but it *also* causes the browser
+ * to fall back to its default spacebar behavior of scrolling the
+ * page.
+ *
+ * Tracking at:
+ * https://code.google.com/p/chromium/issues/detail?id=355103
+ *
+ * To avoid this issue, use the keypress event as if no `textInput`
+ * event is available.
+ */
+ var which = nativeEvent.which;
+
+ if (which !== SPACEBAR_CODE) {
+ return null;
+ }
+
+ hasSpaceKeypress = true;
+ return SPACEBAR_CHAR;
+
+ case TOP_TEXT_INPUT:
+ // Record the characters to be added to the DOM.
+ var chars = nativeEvent.data; // If it's a spacebar character, assume that we have already handled
+ // it at the keypress level and bail immediately. Android Chrome
+ // doesn't give us keycodes, so we need to ignore it.
+
+ if (chars === SPACEBAR_CHAR && hasSpaceKeypress) {
+ return null;
+ }
+
+ return chars;
+
+ default:
+ // For other native event types, do nothing.
+ return null;
+ }
+ }
+ /**
+ * For browsers that do not provide the `textInput` event, extract the
+ * appropriate string to use for SyntheticInputEvent.
+ *
+ * @param {number} topLevelType Number from `TopLevelEventTypes`.
+ * @param {object} nativeEvent Native browser event.
+ * @return {?string} The fallback string for this `beforeInput` event.
+ */
+
+
+ function getFallbackBeforeInputChars(topLevelType, nativeEvent) {
+ // If we are currently composing (IME) and using a fallback to do so,
+ // try to extract the composed characters from the fallback object.
+ // If composition event is available, we extract a string only at
+ // compositionevent, otherwise extract it at fallback events.
+ if (isComposing) {
+ if (topLevelType === TOP_COMPOSITION_END || !canUseCompositionEvent && isFallbackCompositionEnd(topLevelType, nativeEvent)) {
+ var chars = getData();
+ reset();
+ isComposing = false;
+ return chars;
+ }
+
+ return null;
+ }
+
+ switch (topLevelType) {
+ case TOP_PASTE:
+ // If a paste event occurs after a keypress, throw out the input
+ // chars. Paste events should not lead to BeforeInput events.
+ return null;
+
+ case TOP_KEY_PRESS:
+ /**
+ * As of v27, Firefox may fire keypress events even when no character
+ * will be inserted. A few possibilities:
+ *
+ * - `which` is `0`. Arrow keys, Esc key, etc.
+ *
+ * - `which` is the pressed key code, but no char is available.
+ * Ex: 'AltGr + d` in Polish. There is no modified character for
+ * this key combination and no character is inserted into the
+ * document, but FF fires the keypress for char code `100` anyway.
+ * No `input` event will occur.
+ *
+ * - `which` is the pressed key code, but a command combination is
+ * being used. Ex: `Cmd+C`. No character is inserted, and no
+ * `input` event will occur.
+ */
+ if (!isKeypressCommand(nativeEvent)) {
+ // IE fires the `keypress` event when a user types an emoji via
+ // Touch keyboard of Windows. In such a case, the `char` property
+ // holds an emoji character like `\uD83D\uDE0A`. Because its length
+ // is 2, the property `which` does not represent an emoji correctly.
+ // In such a case, we directly return the `char` property instead of
+ // using `which`.
+ if (nativeEvent.char && nativeEvent.char.length > 1) {
+ return nativeEvent.char;
+ } else if (nativeEvent.which) {
+ return String.fromCharCode(nativeEvent.which);
+ }
+ }
+
+ return null;
+
+ case TOP_COMPOSITION_END:
+ return useFallbackCompositionData && !isUsingKoreanIME(nativeEvent) ? null : nativeEvent.data;
+
+ default:
+ return null;
+ }
+ }
+ /**
+ * Extract a SyntheticInputEvent for `beforeInput`, based on either native
+ * `textInput` or fallback behavior.
+ *
+ * @return {?object} A SyntheticInputEvent.
+ */
+
+
+ function extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
+ var chars;
+
+ if (canUseTextInputEvent) {
+ chars = getNativeBeforeInputChars(topLevelType, nativeEvent);
+ } else {
+ chars = getFallbackBeforeInputChars(topLevelType, nativeEvent);
+ } // If no characters are being inserted, no BeforeInput event should
+ // be fired.
+
+
+ if (!chars) {
+ return null;
+ }
+
+ var event = SyntheticInputEvent.getPooled(eventTypes.beforeInput, targetInst, nativeEvent, nativeEventTarget);
+ event.data = chars;
+ accumulateTwoPhaseDispatches(event);
+ return event;
+ }
+ /**
+ * Create an `onBeforeInput` event to match
+ * http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents.
+ *
+ * This event plugin is based on the native `textInput` event
+ * available in Chrome, Safari, Opera, and IE. This event fires after
+ * `onKeyPress` and `onCompositionEnd`, but before `onInput`.
+ *
+ * `beforeInput` is spec'd but not implemented in any browsers, and
+ * the `input` event does not provide any useful information about what has
+ * actually been added, contrary to the spec. Thus, `textInput` is the best
+ * available event to identify the characters that have actually been inserted
+ * into the target node.
+ *
+ * This plugin is also responsible for emitting `composition` events, thus
+ * allowing us to share composition fallback code for both `beforeInput` and
+ * `composition` event types.
+ */
+
+
+ var BeforeInputEventPlugin = {
+ eventTypes: eventTypes,
+ extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {
+ var composition = extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget);
+ var beforeInput = extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget);
+
+ if (composition === null) {
+ return beforeInput;
+ }
+
+ if (beforeInput === null) {
+ return composition;
+ }
+
+ return [composition, beforeInput];
+ }
+ };
+
+ /**
+ * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary
+ */
+ var supportedInputTypes = {
+ color: true,
+ date: true,
+ datetime: true,
+ 'datetime-local': true,
+ email: true,
+ month: true,
+ number: true,
+ password: true,
+ range: true,
+ search: true,
+ tel: true,
+ text: true,
+ time: true,
+ url: true,
+ week: true
+ };
+
+ function isTextInputElement(elem) {
+ var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
+
+ if (nodeName === 'input') {
+ return !!supportedInputTypes[elem.type];
+ }
+
+ if (nodeName === 'textarea') {
+ return true;
+ }
+
+ return false;
+ }
+
+ var eventTypes$1 = {
+ change: {
+ phasedRegistrationNames: {
+ bubbled: 'onChange',
+ captured: 'onChangeCapture'
+ },
+ dependencies: [TOP_BLUR, TOP_CHANGE, TOP_CLICK, TOP_FOCUS, TOP_INPUT, TOP_KEY_DOWN, TOP_KEY_UP, TOP_SELECTION_CHANGE]
+ }
+ };
+
+ function createAndAccumulateChangeEvent(inst, nativeEvent, target) {
+ var event = SyntheticEvent.getPooled(eventTypes$1.change, inst, nativeEvent, target);
+ event.type = 'change'; // Flag this event loop as needing state restore.
+
+ enqueueStateRestore(target);
+ accumulateTwoPhaseDispatches(event);
+ return event;
+ }
+ /**
+ * For IE shims
+ */
+
+
+ var activeElement = null;
+ var activeElementInst = null;
+ /**
+ * SECTION: handle `change` event
+ */
+
+ function shouldUseChangeEvent(elem) {
+ var nodeName = elem.nodeName && elem.nodeName.toLowerCase();
+ return nodeName === 'select' || nodeName === 'input' && elem.type === 'file';
+ }
+
+ function manualDispatchChangeEvent(nativeEvent) {
+ var event = createAndAccumulateChangeEvent(activeElementInst, nativeEvent, getEventTarget(nativeEvent)); // If change and propertychange bubbled, we'd just bind to it like all the
+ // other events and have it go through ReactBrowserEventEmitter. Since it
+ // doesn't, we manually listen for the events and so we have to enqueue and
+ // process the abstract event manually.
+ //
+ // Batching is necessary here in order to ensure that all event handlers run
+ // before the next rerender (including event handlers attached to ancestor
+ // elements instead of directly on the input). Without this, controlled
+ // components don't work properly in conjunction with event bubbling because
+ // the component is rerendered and the value reverted before all the event
+ // handlers can run. See https://github.com/facebook/react/issues/708.
+
+ batchedUpdates(runEventInBatch, event);
+ }
+
+ function runEventInBatch(event) {
+ runEventsInBatch(event);
+ }
+
+ function getInstIfValueChanged(targetInst) {
+ var targetNode = getNodeFromInstance$1(targetInst);
+
+ if (updateValueIfChanged(targetNode)) {
+ return targetInst;
+ }
+ }
+
+ function getTargetInstForChangeEvent(topLevelType, targetInst) {
+ if (topLevelType === TOP_CHANGE) {
+ return targetInst;
+ }
+ }
+ /**
+ * SECTION: handle `input` event
+ */
+
+
+ var isInputEventSupported = false;
+
+ if (canUseDOM) {
+ // IE9 claims to support the input event but fails to trigger it when
+ // deleting text, so we ignore its input events.
+ isInputEventSupported = isEventSupported('input') && (!document.documentMode || document.documentMode > 9);
+ }
+ /**
+ * (For IE <=9) Starts tracking propertychange events on the passed-in element
+ * and override the value property so that we can distinguish user events from
+ * value changes in JS.
+ */
+
+
+ function startWatchingForValueChange(target, targetInst) {
+ activeElement = target;
+ activeElementInst = targetInst;
+ activeElement.attachEvent('onpropertychange', handlePropertyChange);
+ }
+ /**
+ * (For IE <=9) Removes the event listeners from the currently-tracked element,
+ * if any exists.
+ */
+
+
+ function stopWatchingForValueChange() {
+ if (!activeElement) {
+ return;
+ }
+
+ activeElement.detachEvent('onpropertychange', handlePropertyChange);
+ activeElement = null;
+ activeElementInst = null;
+ }
+ /**
+ * (For IE <=9) Handles a propertychange event, sending a `change` event if
+ * the value of the active element has changed.
+ */
+
+
+ function handlePropertyChange(nativeEvent) {
+ if (nativeEvent.propertyName !== 'value') {
+ return;
+ }
+
+ if (getInstIfValueChanged(activeElementInst)) {
+ manualDispatchChangeEvent(nativeEvent);
+ }
+ }
+
+ function handleEventsForInputEventPolyfill(topLevelType, target, targetInst) {
+ if (topLevelType === TOP_FOCUS) {
+ // In IE9, propertychange fires for most input events but is buggy and
+ // doesn't fire when text is deleted, but conveniently, selectionchange
+ // appears to fire in all of the remaining cases so we catch those and
+ // forward the event if the value has changed
+ // In either case, we don't want to call the event handler if the value
+ // is changed from JS so we redefine a setter for `.value` that updates
+ // our activeElementValue variable, allowing us to ignore those changes
+ //
+ // stopWatching() should be a noop here but we call it just in case we
+ // missed a blur event somehow.
+ stopWatchingForValueChange();
+ startWatchingForValueChange(target, targetInst);
+ } else if (topLevelType === TOP_BLUR) {
+ stopWatchingForValueChange();
+ }
+ } // For IE8 and IE9.
+
+
+ function getTargetInstForInputEventPolyfill(topLevelType, targetInst) {
+ if (topLevelType === TOP_SELECTION_CHANGE || topLevelType === TOP_KEY_UP || topLevelType === TOP_KEY_DOWN) {
+ // On the selectionchange event, the target is just document which isn't
+ // helpful for us so just check activeElement instead.
+ //
+ // 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire
+ // propertychange on the first input event after setting `value` from a
+ // script and fires only keydown, keypress, keyup. Catching keyup usually
+ // gets it and catching keydown lets us fire an event for the first
+ // keystroke if user does a key repeat (it'll be a little delayed: right
+ // before the second keystroke). Other input methods (e.g., paste) seem to
+ // fire selectionchange normally.
+ return getInstIfValueChanged(activeElementInst);
+ }
+ }
+ /**
+ * SECTION: handle `click` event
+ */
+
+
+ function shouldUseClickEvent(elem) {
+ // Use the `click` event to detect changes to checkbox and radio inputs.
+ // This approach works across all browsers, whereas `change` does not fire
+ // until `blur` in IE8.
+ var nodeName = elem.nodeName;
+ return nodeName && nodeName.toLowerCase() === 'input' && (elem.type === 'checkbox' || elem.type === 'radio');
+ }
+
+ function getTargetInstForClickEvent(topLevelType, targetInst) {
+ if (topLevelType === TOP_CLICK) {
+ return getInstIfValueChanged(targetInst);
+ }
+ }
+
+ function getTargetInstForInputOrChangeEvent(topLevelType, targetInst) {
+ if (topLevelType === TOP_INPUT || topLevelType === TOP_CHANGE) {
+ return getInstIfValueChanged(targetInst);
+ }
+ }
+
+ function handleControlledInputBlur(node) {
+ var state = node._wrapperState;
+
+ if (!state || !state.controlled || node.type !== 'number') {
+ return;
+ }
+
+ {
+ // If controlled, assign the value attribute to the current value on blur
+ setDefaultValue(node, 'number', node.value);
+ }
+ }
+ /**
+ * This plugin creates an `onChange` event that normalizes change events
+ * across form elements. This event fires at a time when it's possible to
+ * change the element's value without seeing a flicker.
+ *
+ * Supported elements are:
+ * - input (see `isTextInputElement`)
+ * - textarea
+ * - select
+ */
+
+
+ var ChangeEventPlugin = {
+ eventTypes: eventTypes$1,
+ _isInputEventSupported: isInputEventSupported,
+ extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {
+ var targetNode = targetInst ? getNodeFromInstance$1(targetInst) : window;
+ var getTargetInstFunc, handleEventFunc;
+
+ if (shouldUseChangeEvent(targetNode)) {
+ getTargetInstFunc = getTargetInstForChangeEvent;
+ } else if (isTextInputElement(targetNode)) {
+ if (isInputEventSupported) {
+ getTargetInstFunc = getTargetInstForInputOrChangeEvent;
+ } else {
+ getTargetInstFunc = getTargetInstForInputEventPolyfill;
+ handleEventFunc = handleEventsForInputEventPolyfill;
+ }
+ } else if (shouldUseClickEvent(targetNode)) {
+ getTargetInstFunc = getTargetInstForClickEvent;
+ }
+
+ if (getTargetInstFunc) {
+ var inst = getTargetInstFunc(topLevelType, targetInst);
+
+ if (inst) {
+ var event = createAndAccumulateChangeEvent(inst, nativeEvent, nativeEventTarget);
+ return event;
+ }
+ }
+
+ if (handleEventFunc) {
+ handleEventFunc(topLevelType, targetNode, targetInst);
+ } // When blurring, set the value attribute for number inputs
+
+
+ if (topLevelType === TOP_BLUR) {
+ handleControlledInputBlur(targetNode);
+ }
+ }
+ };
+
+ var SyntheticUIEvent = SyntheticEvent.extend({
+ view: null,
+ detail: null
+ });
+
+ /**
+ * Translation from modifier key to the associated property in the event.
+ * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers
+ */
+ var modifierKeyToProp = {
+ Alt: 'altKey',
+ Control: 'ctrlKey',
+ Meta: 'metaKey',
+ Shift: 'shiftKey'
+ }; // Older browsers (Safari <= 10, iOS Safari <= 10.2) do not support
+ // getModifierState. If getModifierState is not supported, we map it to a set of
+ // modifier keys exposed by the event. In this case, Lock-keys are not supported.
+
+ function modifierStateGetter(keyArg) {
+ var syntheticEvent = this;
+ var nativeEvent = syntheticEvent.nativeEvent;
+
+ if (nativeEvent.getModifierState) {
+ return nativeEvent.getModifierState(keyArg);
+ }
+
+ var keyProp = modifierKeyToProp[keyArg];
+ return keyProp ? !!nativeEvent[keyProp] : false;
+ }
+
+ function getEventModifierState(nativeEvent) {
+ return modifierStateGetter;
+ }
+
+ var previousScreenX = 0;
+ var previousScreenY = 0; // Use flags to signal movementX/Y has already been set
+
+ var isMovementXSet = false;
+ var isMovementYSet = false;
+ /**
+ * @interface MouseEvent
+ * @see http://www.w3.org/TR/DOM-Level-3-Events/
+ */
+
+ var SyntheticMouseEvent = SyntheticUIEvent.extend({
+ screenX: null,
+ screenY: null,
+ clientX: null,
+ clientY: null,
+ pageX: null,
+ pageY: null,
+ ctrlKey: null,
+ shiftKey: null,
+ altKey: null,
+ metaKey: null,
+ getModifierState: getEventModifierState,
+ button: null,
+ buttons: null,
+ relatedTarget: function (event) {
+ return event.relatedTarget || (event.fromElement === event.srcElement ? event.toElement : event.fromElement);
+ },
+ movementX: function (event) {
+ if ('movementX' in event) {
+ return event.movementX;
+ }
+
+ var screenX = previousScreenX;
+ previousScreenX = event.screenX;
+
+ if (!isMovementXSet) {
+ isMovementXSet = true;
+ return 0;
+ }
+
+ return event.type === 'mousemove' ? event.screenX - screenX : 0;
+ },
+ movementY: function (event) {
+ if ('movementY' in event) {
+ return event.movementY;
+ }
+
+ var screenY = previousScreenY;
+ previousScreenY = event.screenY;
+
+ if (!isMovementYSet) {
+ isMovementYSet = true;
+ return 0;
+ }
+
+ return event.type === 'mousemove' ? event.screenY - screenY : 0;
+ }
+ });
+
+ /**
+ * @interface PointerEvent
+ * @see http://www.w3.org/TR/pointerevents/
+ */
+
+ var SyntheticPointerEvent = SyntheticMouseEvent.extend({
+ pointerId: null,
+ width: null,
+ height: null,
+ pressure: null,
+ tangentialPressure: null,
+ tiltX: null,
+ tiltY: null,
+ twist: null,
+ pointerType: null,
+ isPrimary: null
+ });
+
+ var eventTypes$2 = {
+ mouseEnter: {
+ registrationName: 'onMouseEnter',
+ dependencies: [TOP_MOUSE_OUT, TOP_MOUSE_OVER]
+ },
+ mouseLeave: {
+ registrationName: 'onMouseLeave',
+ dependencies: [TOP_MOUSE_OUT, TOP_MOUSE_OVER]
+ },
+ pointerEnter: {
+ registrationName: 'onPointerEnter',
+ dependencies: [TOP_POINTER_OUT, TOP_POINTER_OVER]
+ },
+ pointerLeave: {
+ registrationName: 'onPointerLeave',
+ dependencies: [TOP_POINTER_OUT, TOP_POINTER_OVER]
+ }
+ };
+ var EnterLeaveEventPlugin = {
+ eventTypes: eventTypes$2,
+
+ /**
+ * For almost every interaction we care about, there will be both a top-level
+ * `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that
+ * we do not extract duplicate events. However, moving the mouse into the
+ * browser from outside will not fire a `mouseout` event. In this case, we use
+ * the `mouseover` top-level event.
+ */
+ extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {
+ var isOverEvent = topLevelType === TOP_MOUSE_OVER || topLevelType === TOP_POINTER_OVER;
+ var isOutEvent = topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_POINTER_OUT;
+
+ if (isOverEvent && (eventSystemFlags & IS_REPLAYED) === 0 && (nativeEvent.relatedTarget || nativeEvent.fromElement)) {
+ // If this is an over event with a target, then we've already dispatched
+ // the event in the out event of the other target. If this is replayed,
+ // then it's because we couldn't dispatch against this target previously
+ // so we have to do it now instead.
+ return null;
+ }
+
+ if (!isOutEvent && !isOverEvent) {
+ // Must not be a mouse or pointer in or out - ignoring.
+ return null;
+ }
+
+ var win;
+
+ if (nativeEventTarget.window === nativeEventTarget) {
+ // `nativeEventTarget` is probably a window object.
+ win = nativeEventTarget;
+ } else {
+ // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
+ var doc = nativeEventTarget.ownerDocument;
+
+ if (doc) {
+ win = doc.defaultView || doc.parentWindow;
+ } else {
+ win = window;
+ }
+ }
+
+ var from;
+ var to;
+
+ if (isOutEvent) {
+ from = targetInst;
+ var related = nativeEvent.relatedTarget || nativeEvent.toElement;
+ to = related ? getClosestInstanceFromNode(related) : null;
+
+ if (to !== null) {
+ var nearestMounted = getNearestMountedFiber(to);
+
+ if (to !== nearestMounted || to.tag !== HostComponent && to.tag !== HostText) {
+ to = null;
+ }
+ }
+ } else {
+ // Moving to a node from outside the window.
+ from = null;
+ to = targetInst;
+ }
+
+ if (from === to) {
+ // Nothing pertains to our managed components.
+ return null;
+ }
+
+ var eventInterface, leaveEventType, enterEventType, eventTypePrefix;
+
+ if (topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_MOUSE_OVER) {
+ eventInterface = SyntheticMouseEvent;
+ leaveEventType = eventTypes$2.mouseLeave;
+ enterEventType = eventTypes$2.mouseEnter;
+ eventTypePrefix = 'mouse';
+ } else if (topLevelType === TOP_POINTER_OUT || topLevelType === TOP_POINTER_OVER) {
+ eventInterface = SyntheticPointerEvent;
+ leaveEventType = eventTypes$2.pointerLeave;
+ enterEventType = eventTypes$2.pointerEnter;
+ eventTypePrefix = 'pointer';
+ }
+
+ var fromNode = from == null ? win : getNodeFromInstance$1(from);
+ var toNode = to == null ? win : getNodeFromInstance$1(to);
+ var leave = eventInterface.getPooled(leaveEventType, from, nativeEvent, nativeEventTarget);
+ leave.type = eventTypePrefix + 'leave';
+ leave.target = fromNode;
+ leave.relatedTarget = toNode;
+ var enter = eventInterface.getPooled(enterEventType, to, nativeEvent, nativeEventTarget);
+ enter.type = eventTypePrefix + 'enter';
+ enter.target = toNode;
+ enter.relatedTarget = fromNode;
+ accumulateEnterLeaveDispatches(leave, enter, from, to); // If we are not processing the first ancestor, then we
+ // should not process the same nativeEvent again, as we
+ // will have already processed it in the first ancestor.
+
+ if ((eventSystemFlags & IS_FIRST_ANCESTOR) === 0) {
+ return [leave];
+ }
+
+ return [leave, enter];
+ }
+ };
+
+ /**
+ * inlined Object.is polyfill to avoid requiring consumers ship their own
+ * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
+ */
+ function is(x, y) {
+ return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
+ ;
+ }
+
+ var objectIs = typeof Object.is === 'function' ? Object.is : is;
+
+ var hasOwnProperty$2 = Object.prototype.hasOwnProperty;
+ /**
+ * Performs equality by iterating through keys on an object and returning false
+ * when any key has values which are not strictly equal between the arguments.
+ * Returns true when the values of all keys are strictly equal.
+ */
+
+ function shallowEqual(objA, objB) {
+ if (objectIs(objA, objB)) {
+ return true;
+ }
+
+ if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
+ return false;
+ }
+
+ var keysA = Object.keys(objA);
+ var keysB = Object.keys(objB);
+
+ if (keysA.length !== keysB.length) {
+ return false;
+ } // Test for A's keys different from B.
+
+
+ for (var i = 0; i < keysA.length; i++) {
+ if (!hasOwnProperty$2.call(objB, keysA[i]) || !objectIs(objA[keysA[i]], objB[keysA[i]])) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ var skipSelectionChangeEvent = canUseDOM && 'documentMode' in document && document.documentMode <= 11;
+ var eventTypes$3 = {
+ select: {
+ phasedRegistrationNames: {
+ bubbled: 'onSelect',
+ captured: 'onSelectCapture'
+ },
+ dependencies: [TOP_BLUR, TOP_CONTEXT_MENU, TOP_DRAG_END, TOP_FOCUS, TOP_KEY_DOWN, TOP_KEY_UP, TOP_MOUSE_DOWN, TOP_MOUSE_UP, TOP_SELECTION_CHANGE]
+ }
+ };
+ var activeElement$1 = null;
+ var activeElementInst$1 = null;
+ var lastSelection = null;
+ var mouseDown = false;
+ /**
+ * Get an object which is a unique representation of the current selection.
+ *
+ * The return value will not be consistent across nodes or browsers, but
+ * two identical selections on the same node will return identical objects.
+ *
+ * @param {DOMElement} node
+ * @return {object}
+ */
+
+ function getSelection$1(node) {
+ if ('selectionStart' in node && hasSelectionCapabilities(node)) {
+ return {
+ start: node.selectionStart,
+ end: node.selectionEnd
+ };
+ } else {
+ var win = node.ownerDocument && node.ownerDocument.defaultView || window;
+ var selection = win.getSelection();
+ return {
+ anchorNode: selection.anchorNode,
+ anchorOffset: selection.anchorOffset,
+ focusNode: selection.focusNode,
+ focusOffset: selection.focusOffset
+ };
+ }
+ }
+ /**
+ * Get document associated with the event target.
+ *
+ * @param {object} nativeEventTarget
+ * @return {Document}
+ */
+
+
+ function getEventTargetDocument(eventTarget) {
+ return eventTarget.window === eventTarget ? eventTarget.document : eventTarget.nodeType === DOCUMENT_NODE ? eventTarget : eventTarget.ownerDocument;
+ }
+ /**
+ * Poll selection to see whether it's changed.
+ *
+ * @param {object} nativeEvent
+ * @param {object} nativeEventTarget
+ * @return {?SyntheticEvent}
+ */
+
+
+ function constructSelectEvent(nativeEvent, nativeEventTarget) {
+ // Ensure we have the right element, and that the user is not dragging a
+ // selection (this matches native `select` event behavior). In HTML5, select
+ // fires only on input and textarea thus if there's no focused element we
+ // won't dispatch.
+ var doc = getEventTargetDocument(nativeEventTarget);
+
+ if (mouseDown || activeElement$1 == null || activeElement$1 !== getActiveElement(doc)) {
+ return null;
+ } // Only fire when selection has actually changed.
+
+
+ var currentSelection = getSelection$1(activeElement$1);
+
+ if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) {
+ lastSelection = currentSelection;
+ var syntheticEvent = SyntheticEvent.getPooled(eventTypes$3.select, activeElementInst$1, nativeEvent, nativeEventTarget);
+ syntheticEvent.type = 'select';
+ syntheticEvent.target = activeElement$1;
+ accumulateTwoPhaseDispatches(syntheticEvent);
+ return syntheticEvent;
+ }
+
+ return null;
+ }
+ /**
+ * This plugin creates an `onSelect` event that normalizes select events
+ * across form elements.
+ *
+ * Supported elements are:
+ * - input (see `isTextInputElement`)
+ * - textarea
+ * - contentEditable
+ *
+ * This differs from native browser implementations in the following ways:
+ * - Fires on contentEditable fields as well as inputs.
+ * - Fires for collapsed selection.
+ * - Fires after user input.
+ */
+
+
+ var SelectEventPlugin = {
+ eventTypes: eventTypes$3,
+ extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags, container) {
+ var containerOrDoc = container || getEventTargetDocument(nativeEventTarget); // Track whether all listeners exists for this plugin. If none exist, we do
+ // not extract events. See #3639.
+
+ if (!containerOrDoc || !isListeningToAllDependencies('onSelect', containerOrDoc)) {
+ return null;
+ }
+
+ var targetNode = targetInst ? getNodeFromInstance$1(targetInst) : window;
+
+ switch (topLevelType) {
+ // Track the input node that has focus.
+ case TOP_FOCUS:
+ if (isTextInputElement(targetNode) || targetNode.contentEditable === 'true') {
+ activeElement$1 = targetNode;
+ activeElementInst$1 = targetInst;
+ lastSelection = null;
+ }
+
+ break;
+
+ case TOP_BLUR:
+ activeElement$1 = null;
+ activeElementInst$1 = null;
+ lastSelection = null;
+ break;
+ // Don't fire the event while the user is dragging. This matches the
+ // semantics of the native select event.
+
+ case TOP_MOUSE_DOWN:
+ mouseDown = true;
+ break;
+
+ case TOP_CONTEXT_MENU:
+ case TOP_MOUSE_UP:
+ case TOP_DRAG_END:
+ mouseDown = false;
+ return constructSelectEvent(nativeEvent, nativeEventTarget);
+ // Chrome and IE fire non-standard event when selection is changed (and
+ // sometimes when it hasn't). IE's event fires out of order with respect
+ // to key and input events on deletion, so we discard it.
+ //
+ // Firefox doesn't support selectionchange, so check selection status
+ // after each key entry. The selection changes after keydown and before
+ // keyup, but we check on keydown as well in the case of holding down a
+ // key, when multiple keydown events are fired but only one keyup is.
+ // This is also our approach for IE handling, for the reason above.
+
+ case TOP_SELECTION_CHANGE:
+ if (skipSelectionChangeEvent) {
+ break;
+ }
+
+ // falls through
+
+ case TOP_KEY_DOWN:
+ case TOP_KEY_UP:
+ return constructSelectEvent(nativeEvent, nativeEventTarget);
+ }
+
+ return null;
+ }
+ };
+
+ /**
+ * @interface Event
+ * @see http://www.w3.org/TR/css3-animations/#AnimationEvent-interface
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent
+ */
+
+ var SyntheticAnimationEvent = SyntheticEvent.extend({
+ animationName: null,
+ elapsedTime: null,
+ pseudoElement: null
+ });
+
+ /**
+ * @interface Event
+ * @see http://www.w3.org/TR/clipboard-apis/
+ */
+
+ var SyntheticClipboardEvent = SyntheticEvent.extend({
+ clipboardData: function (event) {
+ return 'clipboardData' in event ? event.clipboardData : window.clipboardData;
+ }
+ });
+
+ /**
+ * @interface FocusEvent
+ * @see http://www.w3.org/TR/DOM-Level-3-Events/
+ */
+
+ var SyntheticFocusEvent = SyntheticUIEvent.extend({
+ relatedTarget: null
+ });
+
+ /**
+ * `charCode` represents the actual "character code" and is safe to use with
+ * `String.fromCharCode`. As such, only keys that correspond to printable
+ * characters produce a valid `charCode`, the only exception to this is Enter.
+ * The Tab-key is considered non-printable and does not have a `charCode`,
+ * presumably because it does not produce a tab-character in browsers.
+ *
+ * @param {object} nativeEvent Native browser event.
+ * @return {number} Normalized `charCode` property.
+ */
+ function getEventCharCode(nativeEvent) {
+ var charCode;
+ var keyCode = nativeEvent.keyCode;
+
+ if ('charCode' in nativeEvent) {
+ charCode = nativeEvent.charCode; // FF does not set `charCode` for the Enter-key, check against `keyCode`.
+
+ if (charCode === 0 && keyCode === 13) {
+ charCode = 13;
+ }
+ } else {
+ // IE8 does not implement `charCode`, but `keyCode` has the correct value.
+ charCode = keyCode;
+ } // IE and Edge (on Windows) and Chrome / Safari (on Windows and Linux)
+ // report Enter as charCode 10 when ctrl is pressed.
+
+
+ if (charCode === 10) {
+ charCode = 13;
+ } // Some non-printable keys are reported in `charCode`/`keyCode`, discard them.
+ // Must not discard the (non-)printable Enter-key.
+
+
+ if (charCode >= 32 || charCode === 13) {
+ return charCode;
+ }
+
+ return 0;
+ }
+
+ /**
+ * Normalization of deprecated HTML5 `key` values
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
+ */
+
+ var normalizeKey = {
+ Esc: 'Escape',
+ Spacebar: ' ',
+ Left: 'ArrowLeft',
+ Up: 'ArrowUp',
+ Right: 'ArrowRight',
+ Down: 'ArrowDown',
+ Del: 'Delete',
+ Win: 'OS',
+ Menu: 'ContextMenu',
+ Apps: 'ContextMenu',
+ Scroll: 'ScrollLock',
+ MozPrintableKey: 'Unidentified'
+ };
+ /**
+ * Translation from legacy `keyCode` to HTML5 `key`
+ * Only special keys supported, all others depend on keyboard layout or browser
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
+ */
+
+ var translateToKey = {
+ '8': 'Backspace',
+ '9': 'Tab',
+ '12': 'Clear',
+ '13': 'Enter',
+ '16': 'Shift',
+ '17': 'Control',
+ '18': 'Alt',
+ '19': 'Pause',
+ '20': 'CapsLock',
+ '27': 'Escape',
+ '32': ' ',
+ '33': 'PageUp',
+ '34': 'PageDown',
+ '35': 'End',
+ '36': 'Home',
+ '37': 'ArrowLeft',
+ '38': 'ArrowUp',
+ '39': 'ArrowRight',
+ '40': 'ArrowDown',
+ '45': 'Insert',
+ '46': 'Delete',
+ '112': 'F1',
+ '113': 'F2',
+ '114': 'F3',
+ '115': 'F4',
+ '116': 'F5',
+ '117': 'F6',
+ '118': 'F7',
+ '119': 'F8',
+ '120': 'F9',
+ '121': 'F10',
+ '122': 'F11',
+ '123': 'F12',
+ '144': 'NumLock',
+ '145': 'ScrollLock',
+ '224': 'Meta'
+ };
+ /**
+ * @param {object} nativeEvent Native browser event.
+ * @return {string} Normalized `key` property.
+ */
+
+ function getEventKey(nativeEvent) {
+ if (nativeEvent.key) {
+ // Normalize inconsistent values reported by browsers due to
+ // implementations of a working draft specification.
+ // FireFox implements `key` but returns `MozPrintableKey` for all
+ // printable characters (normalized to `Unidentified`), ignore it.
+ var key = normalizeKey[nativeEvent.key] || nativeEvent.key;
+
+ if (key !== 'Unidentified') {
+ return key;
+ }
+ } // Browser does not implement `key`, polyfill as much of it as we can.
+
+
+ if (nativeEvent.type === 'keypress') {
+ var charCode = getEventCharCode(nativeEvent); // The enter-key is technically both printable and non-printable and can
+ // thus be captured by `keypress`, no other non-printable key should.
+
+ return charCode === 13 ? 'Enter' : String.fromCharCode(charCode);
+ }
+
+ if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') {
+ // While user keyboard layout determines the actual meaning of each
+ // `keyCode` value, almost all function keys have a universal value.
+ return translateToKey[nativeEvent.keyCode] || 'Unidentified';
+ }
+
+ return '';
+ }
+
+ /**
+ * @interface KeyboardEvent
+ * @see http://www.w3.org/TR/DOM-Level-3-Events/
+ */
+
+ var SyntheticKeyboardEvent = SyntheticUIEvent.extend({
+ key: getEventKey,
+ location: null,
+ ctrlKey: null,
+ shiftKey: null,
+ altKey: null,
+ metaKey: null,
+ repeat: null,
+ locale: null,
+ getModifierState: getEventModifierState,
+ // Legacy Interface
+ charCode: function (event) {
+ // `charCode` is the result of a KeyPress event and represents the value of
+ // the actual printable character.
+ // KeyPress is deprecated, but its replacement is not yet final and not
+ // implemented in any major browser. Only KeyPress has charCode.
+ if (event.type === 'keypress') {
+ return getEventCharCode(event);
+ }
+
+ return 0;
+ },
+ keyCode: function (event) {
+ // `keyCode` is the result of a KeyDown/Up event and represents the value of
+ // physical keyboard key.
+ // The actual meaning of the value depends on the users' keyboard layout
+ // which cannot be detected. Assuming that it is a US keyboard layout
+ // provides a surprisingly accurate mapping for US and European users.
+ // Due to this, it is left to the user to implement at this time.
+ if (event.type === 'keydown' || event.type === 'keyup') {
+ return event.keyCode;
+ }
+
+ return 0;
+ },
+ which: function (event) {
+ // `which` is an alias for either `keyCode` or `charCode` depending on the
+ // type of the event.
+ if (event.type === 'keypress') {
+ return getEventCharCode(event);
+ }
+
+ if (event.type === 'keydown' || event.type === 'keyup') {
+ return event.keyCode;
+ }
+
+ return 0;
+ }
+ });
+
+ /**
+ * @interface DragEvent
+ * @see http://www.w3.org/TR/DOM-Level-3-Events/
+ */
+
+ var SyntheticDragEvent = SyntheticMouseEvent.extend({
+ dataTransfer: null
+ });
+
+ /**
+ * @interface TouchEvent
+ * @see http://www.w3.org/TR/touch-events/
+ */
+
+ var SyntheticTouchEvent = SyntheticUIEvent.extend({
+ touches: null,
+ targetTouches: null,
+ changedTouches: null,
+ altKey: null,
+ metaKey: null,
+ ctrlKey: null,
+ shiftKey: null,
+ getModifierState: getEventModifierState
+ });
+
+ /**
+ * @interface Event
+ * @see http://www.w3.org/TR/2009/WD-css3-transitions-20090320/#transition-events-
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent
+ */
+
+ var SyntheticTransitionEvent = SyntheticEvent.extend({
+ propertyName: null,
+ elapsedTime: null,
+ pseudoElement: null
+ });
+
+ /**
+ * @interface WheelEvent
+ * @see http://www.w3.org/TR/DOM-Level-3-Events/
+ */
+
+ var SyntheticWheelEvent = SyntheticMouseEvent.extend({
+ deltaX: function (event) {
+ return 'deltaX' in event ? event.deltaX : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive).
+ 'wheelDeltaX' in event ? -event.wheelDeltaX : 0;
+ },
+ deltaY: function (event) {
+ return 'deltaY' in event ? event.deltaY : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive).
+ 'wheelDeltaY' in event ? -event.wheelDeltaY : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive).
+ 'wheelDelta' in event ? -event.wheelDelta : 0;
+ },
+ deltaZ: null,
+ // Browsers without "deltaMode" is reporting in raw wheel delta where one
+ // notch on the scroll is always +/- 120, roughly equivalent to pixels.
+ // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or
+ // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size.
+ deltaMode: null
+ });
+
+ var knownHTMLTopLevelTypes = [TOP_ABORT, TOP_CANCEL, TOP_CAN_PLAY, TOP_CAN_PLAY_THROUGH, TOP_CLOSE, TOP_DURATION_CHANGE, TOP_EMPTIED, TOP_ENCRYPTED, TOP_ENDED, TOP_ERROR, TOP_INPUT, TOP_INVALID, TOP_LOAD, TOP_LOADED_DATA, TOP_LOADED_METADATA, TOP_LOAD_START, TOP_PAUSE, TOP_PLAY, TOP_PLAYING, TOP_PROGRESS, TOP_RATE_CHANGE, TOP_RESET, TOP_SEEKED, TOP_SEEKING, TOP_STALLED, TOP_SUBMIT, TOP_SUSPEND, TOP_TIME_UPDATE, TOP_TOGGLE, TOP_VOLUME_CHANGE, TOP_WAITING];
+ var SimpleEventPlugin = {
+ // simpleEventPluginEventTypes gets populated from
+ // the DOMEventProperties module.
+ eventTypes: simpleEventPluginEventTypes,
+ extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget, eventSystemFlags) {
+ var dispatchConfig = topLevelEventsToDispatchConfig.get(topLevelType);
+
+ if (!dispatchConfig) {
+ return null;
+ }
+
+ var EventConstructor;
+
+ switch (topLevelType) {
+ case TOP_KEY_PRESS:
+ // Firefox creates a keypress event for function keys too. This removes
+ // the unwanted keypress events. Enter is however both printable and
+ // non-printable. One would expect Tab to be as well (but it isn't).
+ if (getEventCharCode(nativeEvent) === 0) {
+ return null;
+ }
+
+ /* falls through */
+
+ case TOP_KEY_DOWN:
+ case TOP_KEY_UP:
+ EventConstructor = SyntheticKeyboardEvent;
+ break;
+
+ case TOP_BLUR:
+ case TOP_FOCUS:
+ EventConstructor = SyntheticFocusEvent;
+ break;
+
+ case TOP_CLICK:
+ // Firefox creates a click event on right mouse clicks. This removes the
+ // unwanted click events.
+ if (nativeEvent.button === 2) {
+ return null;
+ }
+
+ /* falls through */
+
+ case TOP_AUX_CLICK:
+ case TOP_DOUBLE_CLICK:
+ case TOP_MOUSE_DOWN:
+ case TOP_MOUSE_MOVE:
+ case TOP_MOUSE_UP: // TODO: Disabled elements should not respond to mouse events
+
+ /* falls through */
+
+ case TOP_MOUSE_OUT:
+ case TOP_MOUSE_OVER:
+ case TOP_CONTEXT_MENU:
+ EventConstructor = SyntheticMouseEvent;
+ break;
+
+ case TOP_DRAG:
+ case TOP_DRAG_END:
+ case TOP_DRAG_ENTER:
+ case TOP_DRAG_EXIT:
+ case TOP_DRAG_LEAVE:
+ case TOP_DRAG_OVER:
+ case TOP_DRAG_START:
+ case TOP_DROP:
+ EventConstructor = SyntheticDragEvent;
+ break;
+
+ case TOP_TOUCH_CANCEL:
+ case TOP_TOUCH_END:
+ case TOP_TOUCH_MOVE:
+ case TOP_TOUCH_START:
+ EventConstructor = SyntheticTouchEvent;
+ break;
+
+ case TOP_ANIMATION_END:
+ case TOP_ANIMATION_ITERATION:
+ case TOP_ANIMATION_START:
+ EventConstructor = SyntheticAnimationEvent;
+ break;
+
+ case TOP_TRANSITION_END:
+ EventConstructor = SyntheticTransitionEvent;
+ break;
+
+ case TOP_SCROLL:
+ EventConstructor = SyntheticUIEvent;
+ break;
+
+ case TOP_WHEEL:
+ EventConstructor = SyntheticWheelEvent;
+ break;
+
+ case TOP_COPY:
+ case TOP_CUT:
+ case TOP_PASTE:
+ EventConstructor = SyntheticClipboardEvent;
+ break;
+
+ case TOP_GOT_POINTER_CAPTURE:
+ case TOP_LOST_POINTER_CAPTURE:
+ case TOP_POINTER_CANCEL:
+ case TOP_POINTER_DOWN:
+ case TOP_POINTER_MOVE:
+ case TOP_POINTER_OUT:
+ case TOP_POINTER_OVER:
+ case TOP_POINTER_UP:
+ EventConstructor = SyntheticPointerEvent;
+ break;
+
+ default:
+ {
+ if (knownHTMLTopLevelTypes.indexOf(topLevelType) === -1) {
+ error('SimpleEventPlugin: Unhandled event type, `%s`. This warning ' + 'is likely caused by a bug in React. Please file an issue.', topLevelType);
+ }
+ } // HTML Events
+ // @see http://www.w3.org/TR/html5/index.html#events-0
+
+
+ EventConstructor = SyntheticEvent;
+ break;
+ }
+
+ var event = EventConstructor.getPooled(dispatchConfig, targetInst, nativeEvent, nativeEventTarget);
+ accumulateTwoPhaseDispatches(event);
+ return event;
+ }
+ };
+
+ /**
+ * Specifies a deterministic ordering of `EventPlugin`s. A convenient way to
+ * reason about plugins, without having to package every one of them. This
+ * is better than having plugins be ordered in the same order that they
+ * are injected because that ordering would be influenced by the packaging order.
+ * `ResponderEventPlugin` must occur before `SimpleEventPlugin` so that
+ * preventing default on events is convenient in `SimpleEventPlugin` handlers.
+ */
+
+ var DOMEventPluginOrder = ['ResponderEventPlugin', 'SimpleEventPlugin', 'EnterLeaveEventPlugin', 'ChangeEventPlugin', 'SelectEventPlugin', 'BeforeInputEventPlugin'];
+ /**
+ * Inject modules for resolving DOM hierarchy and plugin ordering.
+ */
+
+ injectEventPluginOrder(DOMEventPluginOrder);
+ setComponentTree(getFiberCurrentPropsFromNode$1, getInstanceFromNode$1, getNodeFromInstance$1);
+ /**
+ * Some important event plugins included by default (without having to require
+ * them).
+ */
+
+ injectEventPluginsByName({
+ SimpleEventPlugin: SimpleEventPlugin,
+ EnterLeaveEventPlugin: EnterLeaveEventPlugin,
+ ChangeEventPlugin: ChangeEventPlugin,
+ SelectEventPlugin: SelectEventPlugin,
+ BeforeInputEventPlugin: BeforeInputEventPlugin
+ });
+
+ // Prefix measurements so that it's possible to filter them.
+ // Longer prefixes are hard to read in DevTools.
+ var reactEmoji = "\u269B";
+ var warningEmoji = "\u26D4";
+ var supportsUserTiming = typeof performance !== 'undefined' && typeof performance.mark === 'function' && typeof performance.clearMarks === 'function' && typeof performance.measure === 'function' && typeof performance.clearMeasures === 'function'; // Keep track of current fiber so that we know the path to unwind on pause.
+ // TODO: this looks the same as nextUnitOfWork in scheduler. Can we unify them?
+
+ var currentFiber = null; // If we're in the middle of user code, which fiber and method is it?
+ // Reusing `currentFiber` would be confusing for this because user code fiber
+ // can change during commit phase too, but we don't need to unwind it (since
+ // lifecycles in the commit phase don't resemble a tree).
+
+ var currentPhase = null;
+ var currentPhaseFiber = null; // Did lifecycle hook schedule an update? This is often a performance problem,
+ // so we will keep track of it, and include it in the report.
+ // Track commits caused by cascading updates.
+
+ var isCommitting = false;
+ var hasScheduledUpdateInCurrentCommit = false;
+ var hasScheduledUpdateInCurrentPhase = false;
+ var commitCountInCurrentWorkLoop = 0;
+ var effectCountInCurrentCommit = 0;
+ // to avoid stretch the commit phase with measurement overhead.
+
+ var labelsInCurrentCommit = new Set();
+
+ var formatMarkName = function (markName) {
+ return reactEmoji + " " + markName;
+ };
+
+ var formatLabel = function (label, warning) {
+ var prefix = warning ? warningEmoji + " " : reactEmoji + " ";
+ var suffix = warning ? " Warning: " + warning : '';
+ return "" + prefix + label + suffix;
+ };
+
+ var beginMark = function (markName) {
+ performance.mark(formatMarkName(markName));
+ };
+
+ var clearMark = function (markName) {
+ performance.clearMarks(formatMarkName(markName));
+ };
+
+ var endMark = function (label, markName, warning) {
+ var formattedMarkName = formatMarkName(markName);
+ var formattedLabel = formatLabel(label, warning);
+
+ try {
+ performance.measure(formattedLabel, formattedMarkName);
+ } catch (err) {} // If previous mark was missing for some reason, this will throw.
+ // This could only happen if React crashed in an unexpected place earlier.
+ // Don't pile on with more errors.
+ // Clear marks immediately to avoid growing buffer.
+
+
+ performance.clearMarks(formattedMarkName);
+ performance.clearMeasures(formattedLabel);
+ };
+
+ var getFiberMarkName = function (label, debugID) {
+ return label + " (#" + debugID + ")";
+ };
+
+ var getFiberLabel = function (componentName, isMounted, phase) {
+ if (phase === null) {
+ // These are composite component total time measurements.
+ return componentName + " [" + (isMounted ? 'update' : 'mount') + "]";
+ } else {
+ // Composite component methods.
+ return componentName + "." + phase;
+ }
+ };
+
+ var beginFiberMark = function (fiber, phase) {
+ var componentName = getComponentName(fiber.type) || 'Unknown';
+ var debugID = fiber._debugID;
+ var isMounted = fiber.alternate !== null;
+ var label = getFiberLabel(componentName, isMounted, phase);
+
+ if (isCommitting && labelsInCurrentCommit.has(label)) {
+ // During the commit phase, we don't show duplicate labels because
+ // there is a fixed overhead for every measurement, and we don't
+ // want to stretch the commit phase beyond necessary.
+ return false;
+ }
+
+ labelsInCurrentCommit.add(label);
+ var markName = getFiberMarkName(label, debugID);
+ beginMark(markName);
+ return true;
+ };
+
+ var clearFiberMark = function (fiber, phase) {
+ var componentName = getComponentName(fiber.type) || 'Unknown';
+ var debugID = fiber._debugID;
+ var isMounted = fiber.alternate !== null;
+ var label = getFiberLabel(componentName, isMounted, phase);
+ var markName = getFiberMarkName(label, debugID);
+ clearMark(markName);
+ };
+
+ var endFiberMark = function (fiber, phase, warning) {
+ var componentName = getComponentName(fiber.type) || 'Unknown';
+ var debugID = fiber._debugID;
+ var isMounted = fiber.alternate !== null;
+ var label = getFiberLabel(componentName, isMounted, phase);
+ var markName = getFiberMarkName(label, debugID);
+ endMark(label, markName, warning);
+ };
+
+ var shouldIgnoreFiber = function (fiber) {
+ // Host components should be skipped in the timeline.
+ // We could check typeof fiber.type, but does this work with RN?
+ switch (fiber.tag) {
+ case HostRoot:
+ case HostComponent:
+ case HostText:
+ case HostPortal:
+ case Fragment:
+ case ContextProvider:
+ case ContextConsumer:
+ case Mode:
+ return true;
+
+ default:
+ return false;
+ }
+ };
+
+ var clearPendingPhaseMeasurement = function () {
+ if (currentPhase !== null && currentPhaseFiber !== null) {
+ clearFiberMark(currentPhaseFiber, currentPhase);
+ }
+
+ currentPhaseFiber = null;
+ currentPhase = null;
+ hasScheduledUpdateInCurrentPhase = false;
+ };
+
+ var pauseTimers = function () {
+ // Stops all currently active measurements so that they can be resumed
+ // if we continue in a later deferred loop from the same unit of work.
+ var fiber = currentFiber;
+
+ while (fiber) {
+ if (fiber._debugIsCurrentlyTiming) {
+ endFiberMark(fiber, null, null);
+ }
+
+ fiber = fiber.return;
+ }
+ };
+
+ var resumeTimersRecursively = function (fiber) {
+ if (fiber.return !== null) {
+ resumeTimersRecursively(fiber.return);
+ }
+
+ if (fiber._debugIsCurrentlyTiming) {
+ beginFiberMark(fiber, null);
+ }
+ };
+
+ var resumeTimers = function () {
+ // Resumes all measurements that were active during the last deferred loop.
+ if (currentFiber !== null) {
+ resumeTimersRecursively(currentFiber);
+ }
+ };
+
+ function recordEffect() {
+ {
+ effectCountInCurrentCommit++;
+ }
+ }
+ function recordScheduleUpdate() {
+ {
+ if (isCommitting) {
+ hasScheduledUpdateInCurrentCommit = true;
+ }
+
+ if (currentPhase !== null && currentPhase !== 'componentWillMount' && currentPhase !== 'componentWillReceiveProps') {
+ hasScheduledUpdateInCurrentPhase = true;
+ }
+ }
+ }
+ function startWorkTimer(fiber) {
+ {
+ if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
+ return;
+ } // If we pause, this is the fiber to unwind from.
+
+
+ currentFiber = fiber;
+
+ if (!beginFiberMark(fiber, null)) {
+ return;
+ }
+
+ fiber._debugIsCurrentlyTiming = true;
+ }
+ }
+ function cancelWorkTimer(fiber) {
+ {
+ if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
+ return;
+ } // Remember we shouldn't complete measurement for this fiber.
+ // Otherwise flamechart will be deep even for small updates.
+
+
+ fiber._debugIsCurrentlyTiming = false;
+ clearFiberMark(fiber, null);
+ }
+ }
+ function stopWorkTimer(fiber) {
+ {
+ if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
+ return;
+ } // If we pause, its parent is the fiber to unwind from.
+
+
+ currentFiber = fiber.return;
+
+ if (!fiber._debugIsCurrentlyTiming) {
+ return;
+ }
+
+ fiber._debugIsCurrentlyTiming = false;
+ endFiberMark(fiber, null, null);
+ }
+ }
+ function stopFailedWorkTimer(fiber) {
+ {
+ if (!supportsUserTiming || shouldIgnoreFiber(fiber)) {
+ return;
+ } // If we pause, its parent is the fiber to unwind from.
+
+
+ currentFiber = fiber.return;
+
+ if (!fiber._debugIsCurrentlyTiming) {
+ return;
+ }
+
+ fiber._debugIsCurrentlyTiming = false;
+ var warning = fiber.tag === SuspenseComponent ? 'Rendering was suspended' : 'An error was thrown inside this error boundary';
+ endFiberMark(fiber, null, warning);
+ }
+ }
+ function startPhaseTimer(fiber, phase) {
+ {
+ if (!supportsUserTiming) {
+ return;
+ }
+
+ clearPendingPhaseMeasurement();
+
+ if (!beginFiberMark(fiber, phase)) {
+ return;
+ }
+
+ currentPhaseFiber = fiber;
+ currentPhase = phase;
+ }
+ }
+ function stopPhaseTimer() {
+ {
+ if (!supportsUserTiming) {
+ return;
+ }
+
+ if (currentPhase !== null && currentPhaseFiber !== null) {
+ var warning = hasScheduledUpdateInCurrentPhase ? 'Scheduled a cascading update' : null;
+ endFiberMark(currentPhaseFiber, currentPhase, warning);
+ }
+
+ currentPhase = null;
+ currentPhaseFiber = null;
+ }
+ }
+ function startWorkLoopTimer(nextUnitOfWork) {
+ {
+ currentFiber = nextUnitOfWork;
+
+ if (!supportsUserTiming) {
+ return;
+ }
+
+ commitCountInCurrentWorkLoop = 0; // This is top level call.
+ // Any other measurements are performed within.
+
+ beginMark('(React Tree Reconciliation)'); // Resume any measurements that were in progress during the last loop.
+
+ resumeTimers();
+ }
+ }
+ function stopWorkLoopTimer(interruptedBy, didCompleteRoot) {
+ {
+ if (!supportsUserTiming) {
+ return;
+ }
+
+ var warning = null;
+
+ if (interruptedBy !== null) {
+ if (interruptedBy.tag === HostRoot) {
+ warning = 'A top-level update interrupted the previous render';
+ } else {
+ var componentName = getComponentName(interruptedBy.type) || 'Unknown';
+ warning = "An update to " + componentName + " interrupted the previous render";
+ }
+ } else if (commitCountInCurrentWorkLoop > 1) {
+ warning = 'There were cascading updates';
+ }
+
+ commitCountInCurrentWorkLoop = 0;
+ var label = didCompleteRoot ? '(React Tree Reconciliation: Completed Root)' : '(React Tree Reconciliation: Yielded)'; // Pause any measurements until the next loop.
+
+ pauseTimers();
+ endMark(label, '(React Tree Reconciliation)', warning);
+ }
+ }
+ function startCommitTimer() {
+ {
+ if (!supportsUserTiming) {
+ return;
+ }
+
+ isCommitting = true;
+ hasScheduledUpdateInCurrentCommit = false;
+ labelsInCurrentCommit.clear();
+ beginMark('(Committing Changes)');
+ }
+ }
+ function stopCommitTimer() {
+ {
+ if (!supportsUserTiming) {
+ return;
+ }
+
+ var warning = null;
+
+ if (hasScheduledUpdateInCurrentCommit) {
+ warning = 'Lifecycle hook scheduled a cascading update';
+ } else if (commitCountInCurrentWorkLoop > 0) {
+ warning = 'Caused by a cascading update in earlier commit';
+ }
+
+ hasScheduledUpdateInCurrentCommit = false;
+ commitCountInCurrentWorkLoop++;
+ isCommitting = false;
+ labelsInCurrentCommit.clear();
+ endMark('(Committing Changes)', '(Committing Changes)', warning);
+ }
+ }
+ function startCommitSnapshotEffectsTimer() {
+ {
+ if (!supportsUserTiming) {
+ return;
+ }
+
+ effectCountInCurrentCommit = 0;
+ beginMark('(Committing Snapshot Effects)');
+ }
+ }
+ function stopCommitSnapshotEffectsTimer() {
+ {
+ if (!supportsUserTiming) {
+ return;
+ }
+
+ var count = effectCountInCurrentCommit;
+ effectCountInCurrentCommit = 0;
+ endMark("(Committing Snapshot Effects: " + count + " Total)", '(Committing Snapshot Effects)', null);
+ }
+ }
+ function startCommitHostEffectsTimer() {
+ {
+ if (!supportsUserTiming) {
+ return;
+ }
+
+ effectCountInCurrentCommit = 0;
+ beginMark('(Committing Host Effects)');
+ }
+ }
+ function stopCommitHostEffectsTimer() {
+ {
+ if (!supportsUserTiming) {
+ return;
+ }
+
+ var count = effectCountInCurrentCommit;
+ effectCountInCurrentCommit = 0;
+ endMark("(Committing Host Effects: " + count + " Total)", '(Committing Host Effects)', null);
+ }
+ }
+ function startCommitLifeCyclesTimer() {
+ {
+ if (!supportsUserTiming) {
+ return;
+ }
+
+ effectCountInCurrentCommit = 0;
+ beginMark('(Calling Lifecycle Methods)');
+ }
+ }
+ function stopCommitLifeCyclesTimer() {
+ {
+ if (!supportsUserTiming) {
+ return;
+ }
+
+ var count = effectCountInCurrentCommit;
+ effectCountInCurrentCommit = 0;
+ endMark("(Calling Lifecycle Methods: " + count + " Total)", '(Calling Lifecycle Methods)', null);
+ }
+ }
+
+ var valueStack = [];
+ var fiberStack;
+
+ {
+ fiberStack = [];
+ }
+
+ var index = -1;
+
+ function createCursor(defaultValue) {
+ return {
+ current: defaultValue
+ };
+ }
+
+ function pop(cursor, fiber) {
+ if (index < 0) {
+ {
+ error('Unexpected pop.');
+ }
+
+ return;
+ }
+
+ {
+ if (fiber !== fiberStack[index]) {
+ error('Unexpected Fiber popped.');
+ }
+ }
+
+ cursor.current = valueStack[index];
+ valueStack[index] = null;
+
+ {
+ fiberStack[index] = null;
+ }
+
+ index--;
+ }
+
+ function push(cursor, value, fiber) {
+ index++;
+ valueStack[index] = cursor.current;
+
+ {
+ fiberStack[index] = fiber;
+ }
+
+ cursor.current = value;
+ }
+
+ var warnedAboutMissingGetChildContext;
+
+ {
+ warnedAboutMissingGetChildContext = {};
+ }
+
+ var emptyContextObject = {};
+
+ {
+ Object.freeze(emptyContextObject);
+ } // A cursor to the current merged context object on the stack.
+
+
+ var contextStackCursor = createCursor(emptyContextObject); // A cursor to a boolean indicating whether the context has changed.
+
+ var didPerformWorkStackCursor = createCursor(false); // Keep track of the previous context object that was on the stack.
+ // We use this to get access to the parent context after we have already
+ // pushed the next context provider, and now need to merge their contexts.
+
+ var previousContext = emptyContextObject;
+
+ function getUnmaskedContext(workInProgress, Component, didPushOwnContextIfProvider) {
+ {
+ if (didPushOwnContextIfProvider && isContextProvider(Component)) {
+ // If the fiber is a context provider itself, when we read its context
+ // we may have already pushed its own child context on the stack. A context
+ // provider should not "see" its own child context. Therefore we read the
+ // previous (parent) context instead for a context provider.
+ return previousContext;
+ }
+
+ return contextStackCursor.current;
+ }
+ }
+
+ function cacheContext(workInProgress, unmaskedContext, maskedContext) {
+ {
+ var instance = workInProgress.stateNode;
+ instance.__reactInternalMemoizedUnmaskedChildContext = unmaskedContext;
+ instance.__reactInternalMemoizedMaskedChildContext = maskedContext;
+ }
+ }
+
+ function getMaskedContext(workInProgress, unmaskedContext) {
+ {
+ var type = workInProgress.type;
+ var contextTypes = type.contextTypes;
+
+ if (!contextTypes) {
+ return emptyContextObject;
+ } // Avoid recreating masked context unless unmasked context has changed.
+ // Failing to do this will result in unnecessary calls to componentWillReceiveProps.
+ // This may trigger infinite loops if componentWillReceiveProps calls setState.
+
+
+ var instance = workInProgress.stateNode;
+
+ if (instance && instance.__reactInternalMemoizedUnmaskedChildContext === unmaskedContext) {
+ return instance.__reactInternalMemoizedMaskedChildContext;
+ }
+
+ var context = {};
+
+ for (var key in contextTypes) {
+ context[key] = unmaskedContext[key];
+ }
+
+ {
+ var name = getComponentName(type) || 'Unknown';
+ checkPropTypes_1(contextTypes, context, 'context', name, getCurrentFiberStackInDev);
+ } // Cache unmasked context so we can avoid recreating masked context unless necessary.
+ // Context is created before the class component is instantiated so check for instance.
+
+
+ if (instance) {
+ cacheContext(workInProgress, unmaskedContext, context);
+ }
+
+ return context;
+ }
+ }
+
+ function hasContextChanged() {
+ {
+ return didPerformWorkStackCursor.current;
+ }
+ }
+
+ function isContextProvider(type) {
+ {
+ var childContextTypes = type.childContextTypes;
+ return childContextTypes !== null && childContextTypes !== undefined;
+ }
+ }
+
+ function popContext(fiber) {
+ {
+ pop(didPerformWorkStackCursor, fiber);
+ pop(contextStackCursor, fiber);
+ }
+ }
+
+ function popTopLevelContextObject(fiber) {
+ {
+ pop(didPerformWorkStackCursor, fiber);
+ pop(contextStackCursor, fiber);
+ }
+ }
+
+ function pushTopLevelContextObject(fiber, context, didChange) {
+ {
+ if (!(contextStackCursor.current === emptyContextObject)) {
+ {
+ throw Error( "Unexpected context found on stack. This error is likely caused by a bug in React. Please file an issue." );
+ }
+ }
+
+ push(contextStackCursor, context, fiber);
+ push(didPerformWorkStackCursor, didChange, fiber);
+ }
+ }
+
+ function processChildContext(fiber, type, parentContext) {
+ {
+ var instance = fiber.stateNode;
+ var childContextTypes = type.childContextTypes; // TODO (bvaughn) Replace this behavior with an invariant() in the future.
+ // It has only been added in Fiber to match the (unintentional) behavior in Stack.
+
+ if (typeof instance.getChildContext !== 'function') {
+ {
+ var componentName = getComponentName(type) || 'Unknown';
+
+ if (!warnedAboutMissingGetChildContext[componentName]) {
+ warnedAboutMissingGetChildContext[componentName] = true;
+
+ error('%s.childContextTypes is specified but there is no getChildContext() method ' + 'on the instance. You can either define getChildContext() on %s or remove ' + 'childContextTypes from it.', componentName, componentName);
+ }
+ }
+
+ return parentContext;
+ }
+
+ var childContext;
+ startPhaseTimer(fiber, 'getChildContext');
+ childContext = instance.getChildContext();
+ stopPhaseTimer();
+
+ for (var contextKey in childContext) {
+ if (!(contextKey in childContextTypes)) {
+ {
+ throw Error( (getComponentName(type) || 'Unknown') + ".getChildContext(): key \"" + contextKey + "\" is not defined in childContextTypes." );
+ }
+ }
+ }
+
+ {
+ var name = getComponentName(type) || 'Unknown';
+ checkPropTypes_1(childContextTypes, childContext, 'child context', name, // In practice, there is one case in which we won't get a stack. It's when
+ // somebody calls unstable_renderSubtreeIntoContainer() and we process
+ // context from the parent component instance. The stack will be missing
+ // because it's outside of the reconciliation, and so the pointer has not
+ // been set. This is rare and doesn't matter. We'll also remove that API.
+ getCurrentFiberStackInDev);
+ }
+
+ return _assign({}, parentContext, {}, childContext);
+ }
+ }
+
+ function pushContextProvider(workInProgress) {
+ {
+ var instance = workInProgress.stateNode; // We push the context as early as possible to ensure stack integrity.
+ // If the instance does not exist yet, we will push null at first,
+ // and replace it on the stack later when invalidating the context.
+
+ var memoizedMergedChildContext = instance && instance.__reactInternalMemoizedMergedChildContext || emptyContextObject; // Remember the parent context so we can merge with it later.
+ // Inherit the parent's did-perform-work value to avoid inadvertently blocking updates.
+
+ previousContext = contextStackCursor.current;
+ push(contextStackCursor, memoizedMergedChildContext, workInProgress);
+ push(didPerformWorkStackCursor, didPerformWorkStackCursor.current, workInProgress);
+ return true;
+ }
+ }
+
+ function invalidateContextProvider(workInProgress, type, didChange) {
+ {
+ var instance = workInProgress.stateNode;
+
+ if (!instance) {
+ {
+ throw Error( "Expected to have an instance by this point. This error is likely caused by a bug in React. Please file an issue." );
+ }
+ }
+
+ if (didChange) {
+ // Merge parent and own context.
+ // Skip this if we're not updating due to sCU.
+ // This avoids unnecessarily recomputing memoized values.
+ var mergedContext = processChildContext(workInProgress, type, previousContext);
+ instance.__reactInternalMemoizedMergedChildContext = mergedContext; // Replace the old (or empty) context with the new one.
+ // It is important to unwind the context in the reverse order.
+
+ pop(didPerformWorkStackCursor, workInProgress);
+ pop(contextStackCursor, workInProgress); // Now push the new context and mark that it has changed.
+
+ push(contextStackCursor, mergedContext, workInProgress);
+ push(didPerformWorkStackCursor, didChange, workInProgress);
+ } else {
+ pop(didPerformWorkStackCursor, workInProgress);
+ push(didPerformWorkStackCursor, didChange, workInProgress);
+ }
+ }
+ }
+
+ function findCurrentUnmaskedContext(fiber) {
+ {
+ // Currently this is only used with renderSubtreeIntoContainer; not sure if it
+ // makes sense elsewhere
+ if (!(isFiberMounted(fiber) && fiber.tag === ClassComponent)) {
+ {
+ throw Error( "Expected subtree parent to be a mounted class component. This error is likely caused by a bug in React. Please file an issue." );
+ }
+ }
+
+ var node = fiber;
+
+ do {
+ switch (node.tag) {
+ case HostRoot:
+ return node.stateNode.context;
+
+ case ClassComponent:
+ {
+ var Component = node.type;
+
+ if (isContextProvider(Component)) {
+ return node.stateNode.__reactInternalMemoizedMergedChildContext;
+ }
+
+ break;
+ }
+ }
+
+ node = node.return;
+ } while (node !== null);
+
+ {
+ {
+ throw Error( "Found unexpected detached subtree parent. This error is likely caused by a bug in React. Please file an issue." );
+ }
+ }
+ }
+ }
+
+ var LegacyRoot = 0;
+ var BlockingRoot = 1;
+ var ConcurrentRoot = 2;
+
+ var ReactInternals$2 = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
+ var _ReactInternals$Sched$1 = ReactInternals$2.SchedulerTracing,
+ __interactionsRef = _ReactInternals$Sched$1.__interactionsRef,
+ __subscriberRef = _ReactInternals$Sched$1.__subscriberRef,
+ unstable_clear = _ReactInternals$Sched$1.unstable_clear,
+ unstable_getCurrent = _ReactInternals$Sched$1.unstable_getCurrent,
+ unstable_getThreadID = _ReactInternals$Sched$1.unstable_getThreadID,
+ unstable_subscribe = _ReactInternals$Sched$1.unstable_subscribe,
+ unstable_trace = _ReactInternals$Sched$1.unstable_trace,
+ unstable_unsubscribe = _ReactInternals$Sched$1.unstable_unsubscribe,
+ unstable_wrap = _ReactInternals$Sched$1.unstable_wrap;
+
+ var Scheduler_runWithPriority = unstable_runWithPriority,
+ Scheduler_scheduleCallback = unstable_scheduleCallback,
+ Scheduler_cancelCallback = unstable_cancelCallback,
+ Scheduler_shouldYield = unstable_shouldYield,
+ Scheduler_requestPaint = unstable_requestPaint,
+ Scheduler_now = unstable_now,
+ Scheduler_getCurrentPriorityLevel = unstable_getCurrentPriorityLevel,
+ Scheduler_ImmediatePriority = unstable_ImmediatePriority,
+ Scheduler_UserBlockingPriority = unstable_UserBlockingPriority,
+ Scheduler_NormalPriority = unstable_NormalPriority,
+ Scheduler_LowPriority = unstable_LowPriority,
+ Scheduler_IdlePriority = unstable_IdlePriority;
+
+ {
+ // Provide explicit error message when production+profiling bundle of e.g.
+ // react-dom is used with production (non-profiling) bundle of
+ // scheduler/tracing
+ if (!(__interactionsRef != null && __interactionsRef.current != null)) {
+ {
+ throw Error( "It is not supported to run the profiling version of a renderer (for example, `react-dom/profiling`) without also replacing the `scheduler/tracing` module with `scheduler/tracing-profiling`. Your bundler might have a setting for aliasing both modules. Learn more at http://fb.me/react-profiling" );
+ }
+ }
+ }
+
+ var fakeCallbackNode = {}; // Except for NoPriority, these correspond to Scheduler priorities. We use
+ // ascending numbers so we can compare them like numbers. They start at 90 to
+ // avoid clashing with Scheduler's priorities.
+
+ var ImmediatePriority = 99;
+ var UserBlockingPriority$1 = 98;
+ var NormalPriority = 97;
+ var LowPriority = 96;
+ var IdlePriority = 95; // NoPriority is the absence of priority. Also React-only.
+
+ var NoPriority = 90;
+ var shouldYield = Scheduler_shouldYield;
+ var requestPaint = // Fall back gracefully if we're running an older version of Scheduler.
+ Scheduler_requestPaint !== undefined ? Scheduler_requestPaint : function () {};
+ var syncQueue = null;
+ var immediateQueueCallbackNode = null;
+ var isFlushingSyncQueue = false;
+ var initialTimeMs = Scheduler_now(); // If the initial timestamp is reasonably small, use Scheduler's `now` directly.
+ // This will be the case for modern browsers that support `performance.now`. In
+ // older browsers, Scheduler falls back to `Date.now`, which returns a Unix
+ // timestamp. In that case, subtract the module initialization time to simulate
+ // the behavior of performance.now and keep our times small enough to fit
+ // within 32 bits.
+ // TODO: Consider lifting this into Scheduler.
+
+ var now = initialTimeMs < 10000 ? Scheduler_now : function () {
+ return Scheduler_now() - initialTimeMs;
+ };
+ function getCurrentPriorityLevel() {
+ switch (Scheduler_getCurrentPriorityLevel()) {
+ case Scheduler_ImmediatePriority:
+ return ImmediatePriority;
+
+ case Scheduler_UserBlockingPriority:
+ return UserBlockingPriority$1;
+
+ case Scheduler_NormalPriority:
+ return NormalPriority;
+
+ case Scheduler_LowPriority:
+ return LowPriority;
+
+ case Scheduler_IdlePriority:
+ return IdlePriority;
+
+ default:
+ {
+ {
+ throw Error( "Unknown priority level." );
+ }
+ }
+
+ }
+ }
+
+ function reactPriorityToSchedulerPriority(reactPriorityLevel) {
+ switch (reactPriorityLevel) {
+ case ImmediatePriority:
+ return Scheduler_ImmediatePriority;
+
+ case UserBlockingPriority$1:
+ return Scheduler_UserBlockingPriority;
+
+ case NormalPriority:
+ return Scheduler_NormalPriority;
+
+ case LowPriority:
+ return Scheduler_LowPriority;
+
+ case IdlePriority:
+ return Scheduler_IdlePriority;
+
+ default:
+ {
+ {
+ throw Error( "Unknown priority level." );
+ }
+ }
+
+ }
+ }
+
+ function runWithPriority$1(reactPriorityLevel, fn) {
+ var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel);
+ return Scheduler_runWithPriority(priorityLevel, fn);
+ }
+ function scheduleCallback(reactPriorityLevel, callback, options) {
+ var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel);
+ return Scheduler_scheduleCallback(priorityLevel, callback, options);
+ }
+ function scheduleSyncCallback(callback) {
+ // Push this callback into an internal queue. We'll flush these either in
+ // the next tick, or earlier if something calls `flushSyncCallbackQueue`.
+ if (syncQueue === null) {
+ syncQueue = [callback]; // Flush the queue in the next tick, at the earliest.
+
+ immediateQueueCallbackNode = Scheduler_scheduleCallback(Scheduler_ImmediatePriority, flushSyncCallbackQueueImpl);
+ } else {
+ // Push onto existing queue. Don't need to schedule a callback because
+ // we already scheduled one when we created the queue.
+ syncQueue.push(callback);
+ }
+
+ return fakeCallbackNode;
+ }
+ function cancelCallback(callbackNode) {
+ if (callbackNode !== fakeCallbackNode) {
+ Scheduler_cancelCallback(callbackNode);
+ }
+ }
+ function flushSyncCallbackQueue() {
+ if (immediateQueueCallbackNode !== null) {
+ var node = immediateQueueCallbackNode;
+ immediateQueueCallbackNode = null;
+ Scheduler_cancelCallback(node);
+ }
+
+ flushSyncCallbackQueueImpl();
+ }
+
+ function flushSyncCallbackQueueImpl() {
+ if (!isFlushingSyncQueue && syncQueue !== null) {
+ // Prevent re-entrancy.
+ isFlushingSyncQueue = true;
+ var i = 0;
+
+ try {
+ var _isSync = true;
+ var queue = syncQueue;
+ runWithPriority$1(ImmediatePriority, function () {
+ for (; i < queue.length; i++) {
+ var callback = queue[i];
+
+ do {
+ callback = callback(_isSync);
+ } while (callback !== null);
+ }
+ });
+ syncQueue = null;
+ } catch (error) {
+ // If something throws, leave the remaining callbacks on the queue.
+ if (syncQueue !== null) {
+ syncQueue = syncQueue.slice(i + 1);
+ } // Resume flushing in the next tick
+
+
+ Scheduler_scheduleCallback(Scheduler_ImmediatePriority, flushSyncCallbackQueue);
+ throw error;
+ } finally {
+ isFlushingSyncQueue = false;
+ }
+ }
+ }
+
+ var NoMode = 0;
+ var StrictMode = 1; // TODO: Remove BlockingMode and ConcurrentMode by reading from the root
+ // tag instead
+
+ var BlockingMode = 2;
+ var ConcurrentMode = 4;
+ var ProfileMode = 8;
+
+ // Max 31 bit integer. The max integer size in V8 for 32-bit systems.
+ // Math.pow(2, 30) - 1
+ // 0b111111111111111111111111111111
+ var MAX_SIGNED_31_BIT_INT = 1073741823;
+
+ var NoWork = 0; // TODO: Think of a better name for Never. The key difference with Idle is that
+ // Never work can be committed in an inconsistent state without tearing the UI.
+ // The main example is offscreen content, like a hidden subtree. So one possible
+ // name is Offscreen. However, it also includes dehydrated Suspense boundaries,
+ // which are inconsistent in the sense that they haven't finished yet, but
+ // aren't visibly inconsistent because the server rendered HTML matches what the
+ // hydrated tree would look like.
+
+ var Never = 1; // Idle is slightly higher priority than Never. It must completely finish in
+ // order to be consistent.
+
+ var Idle = 2; // Continuous Hydration is slightly higher than Idle and is used to increase
+ // priority of hover targets.
+
+ var ContinuousHydration = 3;
+ var Sync = MAX_SIGNED_31_BIT_INT;
+ var Batched = Sync - 1;
+ var UNIT_SIZE = 10;
+ var MAGIC_NUMBER_OFFSET = Batched - 1; // 1 unit of expiration time represents 10ms.
+
+ function msToExpirationTime(ms) {
+ // Always subtract from the offset so that we don't clash with the magic number for NoWork.
+ return MAGIC_NUMBER_OFFSET - (ms / UNIT_SIZE | 0);
+ }
+ function expirationTimeToMs(expirationTime) {
+ return (MAGIC_NUMBER_OFFSET - expirationTime) * UNIT_SIZE;
+ }
+
+ function ceiling(num, precision) {
+ return ((num / precision | 0) + 1) * precision;
+ }
+
+ function computeExpirationBucket(currentTime, expirationInMs, bucketSizeMs) {
+ return MAGIC_NUMBER_OFFSET - ceiling(MAGIC_NUMBER_OFFSET - currentTime + expirationInMs / UNIT_SIZE, bucketSizeMs / UNIT_SIZE);
+ } // TODO: This corresponds to Scheduler's NormalPriority, not LowPriority. Update
+ // the names to reflect.
+
+
+ var LOW_PRIORITY_EXPIRATION = 5000;
+ var LOW_PRIORITY_BATCH_SIZE = 250;
+ function computeAsyncExpiration(currentTime) {
+ return computeExpirationBucket(currentTime, LOW_PRIORITY_EXPIRATION, LOW_PRIORITY_BATCH_SIZE);
+ }
+ function computeSuspenseExpiration(currentTime, timeoutMs) {
+ // TODO: Should we warn if timeoutMs is lower than the normal pri expiration time?
+ return computeExpirationBucket(currentTime, timeoutMs, LOW_PRIORITY_BATCH_SIZE);
+ } // We intentionally set a higher expiration time for interactive updates in
+ // dev than in production.
+ //
+ // If the main thread is being blocked so long that you hit the expiration,
+ // it's a problem that could be solved with better scheduling.
+ //
+ // People will be more likely to notice this and fix it with the long
+ // expiration time in development.
+ //
+ // In production we opt for better UX at the risk of masking scheduling
+ // problems, by expiring fast.
+
+ var HIGH_PRIORITY_EXPIRATION = 500 ;
+ var HIGH_PRIORITY_BATCH_SIZE = 100;
+ function computeInteractiveExpiration(currentTime) {
+ return computeExpirationBucket(currentTime, HIGH_PRIORITY_EXPIRATION, HIGH_PRIORITY_BATCH_SIZE);
+ }
+ function inferPriorityFromExpirationTime(currentTime, expirationTime) {
+ if (expirationTime === Sync) {
+ return ImmediatePriority;
+ }
+
+ if (expirationTime === Never || expirationTime === Idle) {
+ return IdlePriority;
+ }
+
+ var msUntil = expirationTimeToMs(expirationTime) - expirationTimeToMs(currentTime);
+
+ if (msUntil <= 0) {
+ return ImmediatePriority;
+ }
+
+ if (msUntil <= HIGH_PRIORITY_EXPIRATION + HIGH_PRIORITY_BATCH_SIZE) {
+ return UserBlockingPriority$1;
+ }
+
+ if (msUntil <= LOW_PRIORITY_EXPIRATION + LOW_PRIORITY_BATCH_SIZE) {
+ return NormalPriority;
+ } // TODO: Handle LowPriority
+ // Assume anything lower has idle priority
+
+
+ return IdlePriority;
+ }
+
+ var ReactStrictModeWarnings = {
+ recordUnsafeLifecycleWarnings: function (fiber, instance) {},
+ flushPendingUnsafeLifecycleWarnings: function () {},
+ recordLegacyContextWarning: function (fiber, instance) {},
+ flushLegacyContextWarning: function () {},
+ discardPendingWarnings: function () {}
+ };
+
+ {
+ var findStrictRoot = function (fiber) {
+ var maybeStrictRoot = null;
+ var node = fiber;
+
+ while (node !== null) {
+ if (node.mode & StrictMode) {
+ maybeStrictRoot = node;
+ }
+
+ node = node.return;
+ }
+
+ return maybeStrictRoot;
+ };
+
+ var setToSortedString = function (set) {
+ var array = [];
+ set.forEach(function (value) {
+ array.push(value);
+ });
+ return array.sort().join(', ');
+ };
+
+ var pendingComponentWillMountWarnings = [];
+ var pendingUNSAFE_ComponentWillMountWarnings = [];
+ var pendingComponentWillReceivePropsWarnings = [];
+ var pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
+ var pendingComponentWillUpdateWarnings = [];
+ var pendingUNSAFE_ComponentWillUpdateWarnings = []; // Tracks components we have already warned about.
+
+ var didWarnAboutUnsafeLifecycles = new Set();
+
+ ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function (fiber, instance) {
+ // Dedup strategy: Warn once per component.
+ if (didWarnAboutUnsafeLifecycles.has(fiber.type)) {
+ return;
+ }
+
+ if (typeof instance.componentWillMount === 'function' && // Don't warn about react-lifecycles-compat polyfilled components.
+ instance.componentWillMount.__suppressDeprecationWarning !== true) {
+ pendingComponentWillMountWarnings.push(fiber);
+ }
+
+ if (fiber.mode & StrictMode && typeof instance.UNSAFE_componentWillMount === 'function') {
+ pendingUNSAFE_ComponentWillMountWarnings.push(fiber);
+ }
+
+ if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
+ pendingComponentWillReceivePropsWarnings.push(fiber);
+ }
+
+ if (fiber.mode & StrictMode && typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
+ pendingUNSAFE_ComponentWillReceivePropsWarnings.push(fiber);
+ }
+
+ if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
+ pendingComponentWillUpdateWarnings.push(fiber);
+ }
+
+ if (fiber.mode & StrictMode && typeof instance.UNSAFE_componentWillUpdate === 'function') {
+ pendingUNSAFE_ComponentWillUpdateWarnings.push(fiber);
+ }
+ };
+
+ ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function () {
+ // We do an initial pass to gather component names
+ var componentWillMountUniqueNames = new Set();
+
+ if (pendingComponentWillMountWarnings.length > 0) {
+ pendingComponentWillMountWarnings.forEach(function (fiber) {
+ componentWillMountUniqueNames.add(getComponentName(fiber.type) || 'Component');
+ didWarnAboutUnsafeLifecycles.add(fiber.type);
+ });
+ pendingComponentWillMountWarnings = [];
+ }
+
+ var UNSAFE_componentWillMountUniqueNames = new Set();
+
+ if (pendingUNSAFE_ComponentWillMountWarnings.length > 0) {
+ pendingUNSAFE_ComponentWillMountWarnings.forEach(function (fiber) {
+ UNSAFE_componentWillMountUniqueNames.add(getComponentName(fiber.type) || 'Component');
+ didWarnAboutUnsafeLifecycles.add(fiber.type);
+ });
+ pendingUNSAFE_ComponentWillMountWarnings = [];
+ }
+
+ var componentWillReceivePropsUniqueNames = new Set();
+
+ if (pendingComponentWillReceivePropsWarnings.length > 0) {
+ pendingComponentWillReceivePropsWarnings.forEach(function (fiber) {
+ componentWillReceivePropsUniqueNames.add(getComponentName(fiber.type) || 'Component');
+ didWarnAboutUnsafeLifecycles.add(fiber.type);
+ });
+ pendingComponentWillReceivePropsWarnings = [];
+ }
+
+ var UNSAFE_componentWillReceivePropsUniqueNames = new Set();
+
+ if (pendingUNSAFE_ComponentWillReceivePropsWarnings.length > 0) {
+ pendingUNSAFE_ComponentWillReceivePropsWarnings.forEach(function (fiber) {
+ UNSAFE_componentWillReceivePropsUniqueNames.add(getComponentName(fiber.type) || 'Component');
+ didWarnAboutUnsafeLifecycles.add(fiber.type);
+ });
+ pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
+ }
+
+ var componentWillUpdateUniqueNames = new Set();
+
+ if (pendingComponentWillUpdateWarnings.length > 0) {
+ pendingComponentWillUpdateWarnings.forEach(function (fiber) {
+ componentWillUpdateUniqueNames.add(getComponentName(fiber.type) || 'Component');
+ didWarnAboutUnsafeLifecycles.add(fiber.type);
+ });
+ pendingComponentWillUpdateWarnings = [];
+ }
+
+ var UNSAFE_componentWillUpdateUniqueNames = new Set();
+
+ if (pendingUNSAFE_ComponentWillUpdateWarnings.length > 0) {
+ pendingUNSAFE_ComponentWillUpdateWarnings.forEach(function (fiber) {
+ UNSAFE_componentWillUpdateUniqueNames.add(getComponentName(fiber.type) || 'Component');
+ didWarnAboutUnsafeLifecycles.add(fiber.type);
+ });
+ pendingUNSAFE_ComponentWillUpdateWarnings = [];
+ } // Finally, we flush all the warnings
+ // UNSAFE_ ones before the deprecated ones, since they'll be 'louder'
+
+
+ if (UNSAFE_componentWillMountUniqueNames.size > 0) {
+ var sortedNames = setToSortedString(UNSAFE_componentWillMountUniqueNames);
+
+ error('Using UNSAFE_componentWillMount in strict mode is not recommended and may indicate bugs in your code. ' + 'See https://fb.me/react-unsafe-component-lifecycles for details.\n\n' + '* Move code with side effects to componentDidMount, and set initial state in the constructor.\n' + '\nPlease update the following components: %s', sortedNames);
+ }
+
+ if (UNSAFE_componentWillReceivePropsUniqueNames.size > 0) {
+ var _sortedNames = setToSortedString(UNSAFE_componentWillReceivePropsUniqueNames);
+
+ error('Using UNSAFE_componentWillReceiveProps in strict mode is not recommended ' + 'and may indicate bugs in your code. ' + 'See https://fb.me/react-unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + "* If you're updating state whenever props change, " + 'refactor your code to use memoization techniques or move it to ' + 'static getDerivedStateFromProps. Learn more at: https://fb.me/react-derived-state\n' + '\nPlease update the following components: %s', _sortedNames);
+ }
+
+ if (UNSAFE_componentWillUpdateUniqueNames.size > 0) {
+ var _sortedNames2 = setToSortedString(UNSAFE_componentWillUpdateUniqueNames);
+
+ error('Using UNSAFE_componentWillUpdate in strict mode is not recommended ' + 'and may indicate bugs in your code. ' + 'See https://fb.me/react-unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + '\nPlease update the following components: %s', _sortedNames2);
+ }
+
+ if (componentWillMountUniqueNames.size > 0) {
+ var _sortedNames3 = setToSortedString(componentWillMountUniqueNames);
+
+ warn('componentWillMount has been renamed, and is not recommended for use. ' + 'See https://fb.me/react-unsafe-component-lifecycles for details.\n\n' + '* Move code with side effects to componentDidMount, and set initial state in the constructor.\n' + '* Rename componentWillMount to UNSAFE_componentWillMount to suppress ' + 'this warning in non-strict mode. In React 17.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', _sortedNames3);
+ }
+
+ if (componentWillReceivePropsUniqueNames.size > 0) {
+ var _sortedNames4 = setToSortedString(componentWillReceivePropsUniqueNames);
+
+ warn('componentWillReceiveProps has been renamed, and is not recommended for use. ' + 'See https://fb.me/react-unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + "* If you're updating state whenever props change, refactor your " + 'code to use memoization techniques or move it to ' + 'static getDerivedStateFromProps. Learn more at: https://fb.me/react-derived-state\n' + '* Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress ' + 'this warning in non-strict mode. In React 17.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', _sortedNames4);
+ }
+
+ if (componentWillUpdateUniqueNames.size > 0) {
+ var _sortedNames5 = setToSortedString(componentWillUpdateUniqueNames);
+
+ warn('componentWillUpdate has been renamed, and is not recommended for use. ' + 'See https://fb.me/react-unsafe-component-lifecycles for details.\n\n' + '* Move data fetching code or side effects to componentDidUpdate.\n' + '* Rename componentWillUpdate to UNSAFE_componentWillUpdate to suppress ' + 'this warning in non-strict mode. In React 17.x, only the UNSAFE_ name will work. ' + 'To rename all deprecated lifecycles to their new names, you can run ' + '`npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n' + '\nPlease update the following components: %s', _sortedNames5);
+ }
+ };
+
+ var pendingLegacyContextWarning = new Map(); // Tracks components we have already warned about.
+
+ var didWarnAboutLegacyContext = new Set();
+
+ ReactStrictModeWarnings.recordLegacyContextWarning = function (fiber, instance) {
+ var strictRoot = findStrictRoot(fiber);
+
+ if (strictRoot === null) {
+ error('Expected to find a StrictMode component in a strict mode tree. ' + 'This error is likely caused by a bug in React. Please file an issue.');
+
+ return;
+ } // Dedup strategy: Warn once per component.
+
+
+ if (didWarnAboutLegacyContext.has(fiber.type)) {
+ return;
+ }
+
+ var warningsForRoot = pendingLegacyContextWarning.get(strictRoot);
+
+ if (fiber.type.contextTypes != null || fiber.type.childContextTypes != null || instance !== null && typeof instance.getChildContext === 'function') {
+ if (warningsForRoot === undefined) {
+ warningsForRoot = [];
+ pendingLegacyContextWarning.set(strictRoot, warningsForRoot);
+ }
+
+ warningsForRoot.push(fiber);
+ }
+ };
+
+ ReactStrictModeWarnings.flushLegacyContextWarning = function () {
+ pendingLegacyContextWarning.forEach(function (fiberArray, strictRoot) {
+ if (fiberArray.length === 0) {
+ return;
+ }
+
+ var firstFiber = fiberArray[0];
+ var uniqueNames = new Set();
+ fiberArray.forEach(function (fiber) {
+ uniqueNames.add(getComponentName(fiber.type) || 'Component');
+ didWarnAboutLegacyContext.add(fiber.type);
+ });
+ var sortedNames = setToSortedString(uniqueNames);
+ var firstComponentStack = getStackByFiberInDevAndProd(firstFiber);
+
+ error('Legacy context API has been detected within a strict-mode tree.' + '\n\nThe old API will be supported in all 16.x releases, but applications ' + 'using it should migrate to the new version.' + '\n\nPlease update the following components: %s' + '\n\nLearn more about this warning here: https://fb.me/react-legacy-context' + '%s', sortedNames, firstComponentStack);
+ });
+ };
+
+ ReactStrictModeWarnings.discardPendingWarnings = function () {
+ pendingComponentWillMountWarnings = [];
+ pendingUNSAFE_ComponentWillMountWarnings = [];
+ pendingComponentWillReceivePropsWarnings = [];
+ pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
+ pendingComponentWillUpdateWarnings = [];
+ pendingUNSAFE_ComponentWillUpdateWarnings = [];
+ pendingLegacyContextWarning = new Map();
+ };
+ }
+
+ var resolveFamily = null; // $FlowFixMe Flow gets confused by a WeakSet feature check below.
+
+ var failedBoundaries = null;
+ var setRefreshHandler = function (handler) {
+ {
+ resolveFamily = handler;
+ }
+ };
+ function resolveFunctionForHotReloading(type) {
+ {
+ if (resolveFamily === null) {
+ // Hot reloading is disabled.
+ return type;
+ }
+
+ var family = resolveFamily(type);
+
+ if (family === undefined) {
+ return type;
+ } // Use the latest known implementation.
+
+
+ return family.current;
+ }
+ }
+ function resolveClassForHotReloading(type) {
+ // No implementation differences.
+ return resolveFunctionForHotReloading(type);
+ }
+ function resolveForwardRefForHotReloading(type) {
+ {
+ if (resolveFamily === null) {
+ // Hot reloading is disabled.
+ return type;
+ }
+
+ var family = resolveFamily(type);
+
+ if (family === undefined) {
+ // Check if we're dealing with a real forwardRef. Don't want to crash early.
+ if (type !== null && type !== undefined && typeof type.render === 'function') {
+ // ForwardRef is special because its resolved .type is an object,
+ // but it's possible that we only have its inner render function in the map.
+ // If that inner render function is different, we'll build a new forwardRef type.
+ var currentRender = resolveFunctionForHotReloading(type.render);
+
+ if (type.render !== currentRender) {
+ var syntheticType = {
+ $$typeof: REACT_FORWARD_REF_TYPE,
+ render: currentRender
+ };
+
+ if (type.displayName !== undefined) {
+ syntheticType.displayName = type.displayName;
+ }
+
+ return syntheticType;
+ }
+ }
+
+ return type;
+ } // Use the latest known implementation.
+
+
+ return family.current;
+ }
+ }
+ function isCompatibleFamilyForHotReloading(fiber, element) {
+ {
+ if (resolveFamily === null) {
+ // Hot reloading is disabled.
+ return false;
+ }
+
+ var prevType = fiber.elementType;
+ var nextType = element.type; // If we got here, we know types aren't === equal.
+
+ var needsCompareFamilies = false;
+ var $$typeofNextType = typeof nextType === 'object' && nextType !== null ? nextType.$$typeof : null;
+
+ switch (fiber.tag) {
+ case ClassComponent:
+ {
+ if (typeof nextType === 'function') {
+ needsCompareFamilies = true;
+ }
+
+ break;
+ }
+
+ case FunctionComponent:
+ {
+ if (typeof nextType === 'function') {
+ needsCompareFamilies = true;
+ } else if ($$typeofNextType === REACT_LAZY_TYPE) {
+ // We don't know the inner type yet.
+ // We're going to assume that the lazy inner type is stable,
+ // and so it is sufficient to avoid reconciling it away.
+ // We're not going to unwrap or actually use the new lazy type.
+ needsCompareFamilies = true;
+ }
+
+ break;
+ }
+
+ case ForwardRef:
+ {
+ if ($$typeofNextType === REACT_FORWARD_REF_TYPE) {
+ needsCompareFamilies = true;
+ } else if ($$typeofNextType === REACT_LAZY_TYPE) {
+ needsCompareFamilies = true;
+ }
+
+ break;
+ }
+
+ case MemoComponent:
+ case SimpleMemoComponent:
+ {
+ if ($$typeofNextType === REACT_MEMO_TYPE) {
+ // TODO: if it was but can no longer be simple,
+ // we shouldn't set this.
+ needsCompareFamilies = true;
+ } else if ($$typeofNextType === REACT_LAZY_TYPE) {
+ needsCompareFamilies = true;
+ }
+
+ break;
+ }
+
+ default:
+ return false;
+ } // Check if both types have a family and it's the same one.
+
+
+ if (needsCompareFamilies) {
+ // Note: memo() and forwardRef() we'll compare outer rather than inner type.
+ // This means both of them need to be registered to preserve state.
+ // If we unwrapped and compared the inner types for wrappers instead,
+ // then we would risk falsely saying two separate memo(Foo)
+ // calls are equivalent because they wrap the same Foo function.
+ var prevFamily = resolveFamily(prevType);
+
+ if (prevFamily !== undefined && prevFamily === resolveFamily(nextType)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+ }
+ function markFailedErrorBoundaryForHotReloading(fiber) {
+ {
+ if (resolveFamily === null) {
+ // Hot reloading is disabled.
+ return;
+ }
+
+ if (typeof WeakSet !== 'function') {
+ return;
+ }
+
+ if (failedBoundaries === null) {
+ failedBoundaries = new WeakSet();
+ }
+
+ failedBoundaries.add(fiber);
+ }
+ }
+ var scheduleRefresh = function (root, update) {
+ {
+ if (resolveFamily === null) {
+ // Hot reloading is disabled.
+ return;
+ }
+
+ var staleFamilies = update.staleFamilies,
+ updatedFamilies = update.updatedFamilies;
+ flushPassiveEffects();
+ flushSync(function () {
+ scheduleFibersWithFamiliesRecursively(root.current, updatedFamilies, staleFamilies);
+ });
+ }
+ };
+ var scheduleRoot = function (root, element) {
+ {
+ if (root.context !== emptyContextObject) {
+ // Super edge case: root has a legacy _renderSubtree context
+ // but we don't know the parentComponent so we can't pass it.
+ // Just ignore. We'll delete this with _renderSubtree code path later.
+ return;
+ }
+
+ flushPassiveEffects();
+ syncUpdates(function () {
+ updateContainer(element, root, null, null);
+ });
+ }
+ };
+
+ function scheduleFibersWithFamiliesRecursively(fiber, updatedFamilies, staleFamilies) {
+ {
+ var alternate = fiber.alternate,
+ child = fiber.child,
+ sibling = fiber.sibling,
+ tag = fiber.tag,
+ type = fiber.type;
+ var candidateType = null;
+
+ switch (tag) {
+ case FunctionComponent:
+ case SimpleMemoComponent:
+ case ClassComponent:
+ candidateType = type;
+ break;
+
+ case ForwardRef:
+ candidateType = type.render;
+ break;
+ }
+
+ if (resolveFamily === null) {
+ throw new Error('Expected resolveFamily to be set during hot reload.');
+ }
+
+ var needsRender = false;
+ var needsRemount = false;
+
+ if (candidateType !== null) {
+ var family = resolveFamily(candidateType);
+
+ if (family !== undefined) {
+ if (staleFamilies.has(family)) {
+ needsRemount = true;
+ } else if (updatedFamilies.has(family)) {
+ if (tag === ClassComponent) {
+ needsRemount = true;
+ } else {
+ needsRender = true;
+ }
+ }
+ }
+ }
+
+ if (failedBoundaries !== null) {
+ if (failedBoundaries.has(fiber) || alternate !== null && failedBoundaries.has(alternate)) {
+ needsRemount = true;
+ }
+ }
+
+ if (needsRemount) {
+ fiber._debugNeedsRemount = true;
+ }
+
+ if (needsRemount || needsRender) {
+ scheduleWork(fiber, Sync);
+ }
+
+ if (child !== null && !needsRemount) {
+ scheduleFibersWithFamiliesRecursively(child, updatedFamilies, staleFamilies);
+ }
+
+ if (sibling !== null) {
+ scheduleFibersWithFamiliesRecursively(sibling, updatedFamilies, staleFamilies);
+ }
+ }
+ }
+
+ var findHostInstancesForRefresh = function (root, families) {
+ {
+ var hostInstances = new Set();
+ var types = new Set(families.map(function (family) {
+ return family.current;
+ }));
+ findHostInstancesForMatchingFibersRecursively(root.current, types, hostInstances);
+ return hostInstances;
+ }
+ };
+
+ function findHostInstancesForMatchingFibersRecursively(fiber, types, hostInstances) {
+ {
+ var child = fiber.child,
+ sibling = fiber.sibling,
+ tag = fiber.tag,
+ type = fiber.type;
+ var candidateType = null;
+
+ switch (tag) {
+ case FunctionComponent:
+ case SimpleMemoComponent:
+ case ClassComponent:
+ candidateType = type;
+ break;
+
+ case ForwardRef:
+ candidateType = type.render;
+ break;
+ }
+
+ var didMatch = false;
+
+ if (candidateType !== null) {
+ if (types.has(candidateType)) {
+ didMatch = true;
+ }
+ }
+
+ if (didMatch) {
+ // We have a match. This only drills down to the closest host components.
+ // There's no need to search deeper because for the purpose of giving
+ // visual feedback, "flashing" outermost parent rectangles is sufficient.
+ findHostInstancesForFiberShallowly(fiber, hostInstances);
+ } else {
+ // If there's no match, maybe there will be one further down in the child tree.
+ if (child !== null) {
+ findHostInstancesForMatchingFibersRecursively(child, types, hostInstances);
+ }
+ }
+
+ if (sibling !== null) {
+ findHostInstancesForMatchingFibersRecursively(sibling, types, hostInstances);
+ }
+ }
+ }
+
+ function findHostInstancesForFiberShallowly(fiber, hostInstances) {
+ {
+ var foundHostInstances = findChildHostInstancesForFiberShallowly(fiber, hostInstances);
+
+ if (foundHostInstances) {
+ return;
+ } // If we didn't find any host children, fallback to closest host parent.
+
+
+ var node = fiber;
+
+ while (true) {
+ switch (node.tag) {
+ case HostComponent:
+ hostInstances.add(node.stateNode);
+ return;
+
+ case HostPortal:
+ hostInstances.add(node.stateNode.containerInfo);
+ return;
+
+ case HostRoot:
+ hostInstances.add(node.stateNode.containerInfo);
+ return;
+ }
+
+ if (node.return === null) {
+ throw new Error('Expected to reach root first.');
+ }
+
+ node = node.return;
+ }
+ }
+ }
+
+ function findChildHostInstancesForFiberShallowly(fiber, hostInstances) {
+ {
+ var node = fiber;
+ var foundHostInstances = false;
+
+ while (true) {
+ if (node.tag === HostComponent) {
+ // We got a match.
+ foundHostInstances = true;
+ hostInstances.add(node.stateNode); // There may still be more, so keep searching.
+ } else if (node.child !== null) {
+ node.child.return = node;
+ node = node.child;
+ continue;
+ }
+
+ if (node === fiber) {
+ return foundHostInstances;
+ }
+
+ while (node.sibling === null) {
+ if (node.return === null || node.return === fiber) {
+ return foundHostInstances;
+ }
+
+ node = node.return;
+ }
+
+ node.sibling.return = node.return;
+ node = node.sibling;
+ }
+ }
+
+ return false;
+ }
+
+ function resolveDefaultProps(Component, baseProps) {
+ if (Component && Component.defaultProps) {
+ // Resolve default props. Taken from ReactElement
+ var props = _assign({}, baseProps);
+
+ var defaultProps = Component.defaultProps;
+
+ for (var propName in defaultProps) {
+ if (props[propName] === undefined) {
+ props[propName] = defaultProps[propName];
+ }
+ }
+
+ return props;
+ }
+
+ return baseProps;
+ }
+ function readLazyComponentType(lazyComponent) {
+ initializeLazyComponentType(lazyComponent);
+
+ if (lazyComponent._status !== Resolved) {
+ throw lazyComponent._result;
+ }
+
+ return lazyComponent._result;
+ }
+
+ var valueCursor = createCursor(null);
+ var rendererSigil;
+
+ {
+ // Use this to detect multiple renderers using the same context
+ rendererSigil = {};
+ }
+
+ var currentlyRenderingFiber = null;
+ var lastContextDependency = null;
+ var lastContextWithAllBitsObserved = null;
+ var isDisallowedContextReadInDEV = false;
+ function resetContextDependencies() {
+ // This is called right before React yields execution, to ensure `readContext`
+ // cannot be called outside the render phase.
+ currentlyRenderingFiber = null;
+ lastContextDependency = null;
+ lastContextWithAllBitsObserved = null;
+
+ {
+ isDisallowedContextReadInDEV = false;
+ }
+ }
+ function enterDisallowedContextReadInDEV() {
+ {
+ isDisallowedContextReadInDEV = true;
+ }
+ }
+ function exitDisallowedContextReadInDEV() {
+ {
+ isDisallowedContextReadInDEV = false;
+ }
+ }
+ function pushProvider(providerFiber, nextValue) {
+ var context = providerFiber.type._context;
+
+ {
+ push(valueCursor, context._currentValue, providerFiber);
+ context._currentValue = nextValue;
+
+ {
+ if (context._currentRenderer !== undefined && context._currentRenderer !== null && context._currentRenderer !== rendererSigil) {
+ error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.');
+ }
+
+ context._currentRenderer = rendererSigil;
+ }
+ }
+ }
+ function popProvider(providerFiber) {
+ var currentValue = valueCursor.current;
+ pop(valueCursor, providerFiber);
+ var context = providerFiber.type._context;
+
+ {
+ context._currentValue = currentValue;
+ }
+ }
+ function calculateChangedBits(context, newValue, oldValue) {
+ if (objectIs(oldValue, newValue)) {
+ // No change
+ return 0;
+ } else {
+ var changedBits = typeof context._calculateChangedBits === 'function' ? context._calculateChangedBits(oldValue, newValue) : MAX_SIGNED_31_BIT_INT;
+
+ {
+ if ((changedBits & MAX_SIGNED_31_BIT_INT) !== changedBits) {
+ error('calculateChangedBits: Expected the return value to be a ' + '31-bit integer. Instead received: %s', changedBits);
+ }
+ }
+
+ return changedBits | 0;
+ }
+ }
+ function scheduleWorkOnParentPath(parent, renderExpirationTime) {
+ // Update the child expiration time of all the ancestors, including
+ // the alternates.
+ var node = parent;
+
+ while (node !== null) {
+ var alternate = node.alternate;
+
+ if (node.childExpirationTime < renderExpirationTime) {
+ node.childExpirationTime = renderExpirationTime;
+
+ if (alternate !== null && alternate.childExpirationTime < renderExpirationTime) {
+ alternate.childExpirationTime = renderExpirationTime;
+ }
+ } else if (alternate !== null && alternate.childExpirationTime < renderExpirationTime) {
+ alternate.childExpirationTime = renderExpirationTime;
+ } else {
+ // Neither alternate was updated, which means the rest of the
+ // ancestor path already has sufficient priority.
+ break;
+ }
+
+ node = node.return;
+ }
+ }
+ function propagateContextChange(workInProgress, context, changedBits, renderExpirationTime) {
+ var fiber = workInProgress.child;
+
+ if (fiber !== null) {
+ // Set the return pointer of the child to the work-in-progress fiber.
+ fiber.return = workInProgress;
+ }
+
+ while (fiber !== null) {
+ var nextFiber = void 0; // Visit this fiber.
+
+ var list = fiber.dependencies;
+
+ if (list !== null) {
+ nextFiber = fiber.child;
+ var dependency = list.firstContext;
+
+ while (dependency !== null) {
+ // Check if the context matches.
+ if (dependency.context === context && (dependency.observedBits & changedBits) !== 0) {
+ // Match! Schedule an update on this fiber.
+ if (fiber.tag === ClassComponent) {
+ // Schedule a force update on the work-in-progress.
+ var update = createUpdate(renderExpirationTime, null);
+ update.tag = ForceUpdate; // TODO: Because we don't have a work-in-progress, this will add the
+ // update to the current fiber, too, which means it will persist even if
+ // this render is thrown away. Since it's a race condition, not sure it's
+ // worth fixing.
+
+ enqueueUpdate(fiber, update);
+ }
+
+ if (fiber.expirationTime < renderExpirationTime) {
+ fiber.expirationTime = renderExpirationTime;
+ }
+
+ var alternate = fiber.alternate;
+
+ if (alternate !== null && alternate.expirationTime < renderExpirationTime) {
+ alternate.expirationTime = renderExpirationTime;
+ }
+
+ scheduleWorkOnParentPath(fiber.return, renderExpirationTime); // Mark the expiration time on the list, too.
+
+ if (list.expirationTime < renderExpirationTime) {
+ list.expirationTime = renderExpirationTime;
+ } // Since we already found a match, we can stop traversing the
+ // dependency list.
+
+
+ break;
+ }
+
+ dependency = dependency.next;
+ }
+ } else if (fiber.tag === ContextProvider) {
+ // Don't scan deeper if this is a matching provider
+ nextFiber = fiber.type === workInProgress.type ? null : fiber.child;
+ } else {
+ // Traverse down.
+ nextFiber = fiber.child;
+ }
+
+ if (nextFiber !== null) {
+ // Set the return pointer of the child to the work-in-progress fiber.
+ nextFiber.return = fiber;
+ } else {
+ // No child. Traverse to next sibling.
+ nextFiber = fiber;
+
+ while (nextFiber !== null) {
+ if (nextFiber === workInProgress) {
+ // We're back to the root of this subtree. Exit.
+ nextFiber = null;
+ break;
+ }
+
+ var sibling = nextFiber.sibling;
+
+ if (sibling !== null) {
+ // Set the return pointer of the sibling to the work-in-progress fiber.
+ sibling.return = nextFiber.return;
+ nextFiber = sibling;
+ break;
+ } // No more siblings. Traverse up.
+
+
+ nextFiber = nextFiber.return;
+ }
+ }
+
+ fiber = nextFiber;
+ }
+ }
+ function prepareToReadContext(workInProgress, renderExpirationTime) {
+ currentlyRenderingFiber = workInProgress;
+ lastContextDependency = null;
+ lastContextWithAllBitsObserved = null;
+ var dependencies = workInProgress.dependencies;
+
+ if (dependencies !== null) {
+ var firstContext = dependencies.firstContext;
+
+ if (firstContext !== null) {
+ if (dependencies.expirationTime >= renderExpirationTime) {
+ // Context list has a pending update. Mark that this fiber performed work.
+ markWorkInProgressReceivedUpdate();
+ } // Reset the work-in-progress list
+
+
+ dependencies.firstContext = null;
+ }
+ }
+ }
+ function readContext(context, observedBits) {
+ {
+ // This warning would fire if you read context inside a Hook like useMemo.
+ // Unlike the class check below, it's not enforced in production for perf.
+ if (isDisallowedContextReadInDEV) {
+ error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().');
+ }
+ }
+
+ if (lastContextWithAllBitsObserved === context) ; else if (observedBits === false || observedBits === 0) ; else {
+ var resolvedObservedBits; // Avoid deopting on observable arguments or heterogeneous types.
+
+ if (typeof observedBits !== 'number' || observedBits === MAX_SIGNED_31_BIT_INT) {
+ // Observe all updates.
+ lastContextWithAllBitsObserved = context;
+ resolvedObservedBits = MAX_SIGNED_31_BIT_INT;
+ } else {
+ resolvedObservedBits = observedBits;
+ }
+
+ var contextItem = {
+ context: context,
+ observedBits: resolvedObservedBits,
+ next: null
+ };
+
+ if (lastContextDependency === null) {
+ if (!(currentlyRenderingFiber !== null)) {
+ {
+ throw Error( "Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo()." );
+ }
+ } // This is the first dependency for this component. Create a new list.
+
+
+ lastContextDependency = contextItem;
+ currentlyRenderingFiber.dependencies = {
+ expirationTime: NoWork,
+ firstContext: contextItem,
+ responders: null
+ };
+ } else {
+ // Append a new context item.
+ lastContextDependency = lastContextDependency.next = contextItem;
+ }
+ }
+
+ return context._currentValue ;
+ }
+
+ var UpdateState = 0;
+ var ReplaceState = 1;
+ var ForceUpdate = 2;
+ var CaptureUpdate = 3; // Global state that is reset at the beginning of calling `processUpdateQueue`.
+ // It should only be read right after calling `processUpdateQueue`, via
+ // `checkHasForceUpdateAfterProcessing`.
+
+ var hasForceUpdate = false;
+ var didWarnUpdateInsideUpdate;
+ var currentlyProcessingQueue;
+
+ {
+ didWarnUpdateInsideUpdate = false;
+ currentlyProcessingQueue = null;
+ }
+
+ function initializeUpdateQueue(fiber) {
+ var queue = {
+ baseState: fiber.memoizedState,
+ baseQueue: null,
+ shared: {
+ pending: null
+ },
+ effects: null
+ };
+ fiber.updateQueue = queue;
+ }
+ function cloneUpdateQueue(current, workInProgress) {
+ // Clone the update queue from current. Unless it's already a clone.
+ var queue = workInProgress.updateQueue;
+ var currentQueue = current.updateQueue;
+
+ if (queue === currentQueue) {
+ var clone = {
+ baseState: currentQueue.baseState,
+ baseQueue: currentQueue.baseQueue,
+ shared: currentQueue.shared,
+ effects: currentQueue.effects
+ };
+ workInProgress.updateQueue = clone;
+ }
+ }
+ function createUpdate(expirationTime, suspenseConfig) {
+ var update = {
+ expirationTime: expirationTime,
+ suspenseConfig: suspenseConfig,
+ tag: UpdateState,
+ payload: null,
+ callback: null,
+ next: null
+ };
+ update.next = update;
+
+ {
+ update.priority = getCurrentPriorityLevel();
+ }
+
+ return update;
+ }
+ function enqueueUpdate(fiber, update) {
+ var updateQueue = fiber.updateQueue;
+
+ if (updateQueue === null) {
+ // Only occurs if the fiber has been unmounted.
+ return;
+ }
+
+ var sharedQueue = updateQueue.shared;
+ var pending = sharedQueue.pending;
+
+ if (pending === null) {
+ // This is the first update. Create a circular list.
+ update.next = update;
+ } else {
+ update.next = pending.next;
+ pending.next = update;
+ }
+
+ sharedQueue.pending = update;
+
+ {
+ if (currentlyProcessingQueue === sharedQueue && !didWarnUpdateInsideUpdate) {
+ error('An update (setState, replaceState, or forceUpdate) was scheduled ' + 'from inside an update function. Update functions should be pure, ' + 'with zero side-effects. Consider using componentDidUpdate or a ' + 'callback.');
+
+ didWarnUpdateInsideUpdate = true;
+ }
+ }
+ }
+ function enqueueCapturedUpdate(workInProgress, update) {
+ var current = workInProgress.alternate;
+
+ if (current !== null) {
+ // Ensure the work-in-progress queue is a clone
+ cloneUpdateQueue(current, workInProgress);
+ } // Captured updates go only on the work-in-progress queue.
+
+
+ var queue = workInProgress.updateQueue; // Append the update to the end of the list.
+
+ var last = queue.baseQueue;
+
+ if (last === null) {
+ queue.baseQueue = update.next = update;
+ update.next = update;
+ } else {
+ update.next = last.next;
+ last.next = update;
+ }
+ }
+
+ function getStateFromUpdate(workInProgress, queue, update, prevState, nextProps, instance) {
+ switch (update.tag) {
+ case ReplaceState:
+ {
+ var payload = update.payload;
+
+ if (typeof payload === 'function') {
+ // Updater function
+ {
+ enterDisallowedContextReadInDEV();
+
+ if ( workInProgress.mode & StrictMode) {
+ payload.call(instance, prevState, nextProps);
+ }
+ }
+
+ var nextState = payload.call(instance, prevState, nextProps);
+
+ {
+ exitDisallowedContextReadInDEV();
+ }
+
+ return nextState;
+ } // State object
+
+
+ return payload;
+ }
+
+ case CaptureUpdate:
+ {
+ workInProgress.effectTag = workInProgress.effectTag & ~ShouldCapture | DidCapture;
+ }
+ // Intentional fallthrough
+
+ case UpdateState:
+ {
+ var _payload = update.payload;
+ var partialState;
+
+ if (typeof _payload === 'function') {
+ // Updater function
+ {
+ enterDisallowedContextReadInDEV();
+
+ if ( workInProgress.mode & StrictMode) {
+ _payload.call(instance, prevState, nextProps);
+ }
+ }
+
+ partialState = _payload.call(instance, prevState, nextProps);
+
+ {
+ exitDisallowedContextReadInDEV();
+ }
+ } else {
+ // Partial state object
+ partialState = _payload;
+ }
+
+ if (partialState === null || partialState === undefined) {
+ // Null and undefined are treated as no-ops.
+ return prevState;
+ } // Merge the partial state and the previous state.
+
+
+ return _assign({}, prevState, partialState);
+ }
+
+ case ForceUpdate:
+ {
+ hasForceUpdate = true;
+ return prevState;
+ }
+ }
+
+ return prevState;
+ }
+
+ function processUpdateQueue(workInProgress, props, instance, renderExpirationTime) {
+ // This is always non-null on a ClassComponent or HostRoot
+ var queue = workInProgress.updateQueue;
+ hasForceUpdate = false;
+
+ {
+ currentlyProcessingQueue = queue.shared;
+ } // The last rebase update that is NOT part of the base state.
+
+
+ var baseQueue = queue.baseQueue; // The last pending update that hasn't been processed yet.
+
+ var pendingQueue = queue.shared.pending;
+
+ if (pendingQueue !== null) {
+ // We have new updates that haven't been processed yet.
+ // We'll add them to the base queue.
+ if (baseQueue !== null) {
+ // Merge the pending queue and the base queue.
+ var baseFirst = baseQueue.next;
+ var pendingFirst = pendingQueue.next;
+ baseQueue.next = pendingFirst;
+ pendingQueue.next = baseFirst;
+ }
+
+ baseQueue = pendingQueue;
+ queue.shared.pending = null; // TODO: Pass `current` as argument
+
+ var current = workInProgress.alternate;
+
+ if (current !== null) {
+ var currentQueue = current.updateQueue;
+
+ if (currentQueue !== null) {
+ currentQueue.baseQueue = pendingQueue;
+ }
+ }
+ } // These values may change as we process the queue.
+
+
+ if (baseQueue !== null) {
+ var first = baseQueue.next; // Iterate through the list of updates to compute the result.
+
+ var newState = queue.baseState;
+ var newExpirationTime = NoWork;
+ var newBaseState = null;
+ var newBaseQueueFirst = null;
+ var newBaseQueueLast = null;
+
+ if (first !== null) {
+ var update = first;
+
+ do {
+ var updateExpirationTime = update.expirationTime;
+
+ if (updateExpirationTime < renderExpirationTime) {
+ // Priority is insufficient. Skip this update. If this is the first
+ // skipped update, the previous update/state is the new base
+ // update/state.
+ var clone = {
+ expirationTime: update.expirationTime,
+ suspenseConfig: update.suspenseConfig,
+ tag: update.tag,
+ payload: update.payload,
+ callback: update.callback,
+ next: null
+ };
+
+ if (newBaseQueueLast === null) {
+ newBaseQueueFirst = newBaseQueueLast = clone;
+ newBaseState = newState;
+ } else {
+ newBaseQueueLast = newBaseQueueLast.next = clone;
+ } // Update the remaining priority in the queue.
+
+
+ if (updateExpirationTime > newExpirationTime) {
+ newExpirationTime = updateExpirationTime;
+ }
+ } else {
+ // This update does have sufficient priority.
+ if (newBaseQueueLast !== null) {
+ var _clone = {
+ expirationTime: Sync,
+ // This update is going to be committed so we never want uncommit it.
+ suspenseConfig: update.suspenseConfig,
+ tag: update.tag,
+ payload: update.payload,
+ callback: update.callback,
+ next: null
+ };
+ newBaseQueueLast = newBaseQueueLast.next = _clone;
+ } // Mark the event time of this update as relevant to this render pass.
+ // TODO: This should ideally use the true event time of this update rather than
+ // its priority which is a derived and not reverseable value.
+ // TODO: We should skip this update if it was already committed but currently
+ // we have no way of detecting the difference between a committed and suspended
+ // update here.
+
+
+ markRenderEventTimeAndConfig(updateExpirationTime, update.suspenseConfig); // Process this update.
+
+ newState = getStateFromUpdate(workInProgress, queue, update, newState, props, instance);
+ var callback = update.callback;
+
+ if (callback !== null) {
+ workInProgress.effectTag |= Callback;
+ var effects = queue.effects;
+
+ if (effects === null) {
+ queue.effects = [update];
+ } else {
+ effects.push(update);
+ }
+ }
+ }
+
+ update = update.next;
+
+ if (update === null || update === first) {
+ pendingQueue = queue.shared.pending;
+
+ if (pendingQueue === null) {
+ break;
+ } else {
+ // An update was scheduled from inside a reducer. Add the new
+ // pending updates to the end of the list and keep processing.
+ update = baseQueue.next = pendingQueue.next;
+ pendingQueue.next = first;
+ queue.baseQueue = baseQueue = pendingQueue;
+ queue.shared.pending = null;
+ }
+ }
+ } while (true);
+ }
+
+ if (newBaseQueueLast === null) {
+ newBaseState = newState;
+ } else {
+ newBaseQueueLast.next = newBaseQueueFirst;
+ }
+
+ queue.baseState = newBaseState;
+ queue.baseQueue = newBaseQueueLast; // Set the remaining expiration time to be whatever is remaining in the queue.
+ // This should be fine because the only two other things that contribute to
+ // expiration time are props and context. We're already in the middle of the
+ // begin phase by the time we start processing the queue, so we've already
+ // dealt with the props. Context in components that specify
+ // shouldComponentUpdate is tricky; but we'll have to account for
+ // that regardless.
+
+ markUnprocessedUpdateTime(newExpirationTime);
+ workInProgress.expirationTime = newExpirationTime;
+ workInProgress.memoizedState = newState;
+ }
+
+ {
+ currentlyProcessingQueue = null;
+ }
+ }
+
+ function callCallback(callback, context) {
+ if (!(typeof callback === 'function')) {
+ {
+ throw Error( "Invalid argument passed as callback. Expected a function. Instead received: " + callback );
+ }
+ }
+
+ callback.call(context);
+ }
+
+ function resetHasForceUpdateBeforeProcessing() {
+ hasForceUpdate = false;
+ }
+ function checkHasForceUpdateAfterProcessing() {
+ return hasForceUpdate;
+ }
+ function commitUpdateQueue(finishedWork, finishedQueue, instance) {
+ // Commit the effects
+ var effects = finishedQueue.effects;
+ finishedQueue.effects = null;
+
+ if (effects !== null) {
+ for (var i = 0; i < effects.length; i++) {
+ var effect = effects[i];
+ var callback = effect.callback;
+
+ if (callback !== null) {
+ effect.callback = null;
+ callCallback(callback, instance);
+ }
+ }
+ }
+ }
+
+ var ReactCurrentBatchConfig = ReactSharedInternals.ReactCurrentBatchConfig;
+ function requestCurrentSuspenseConfig() {
+ return ReactCurrentBatchConfig.suspense;
+ }
+
+ var fakeInternalInstance = {};
+ var isArray = Array.isArray; // React.Component uses a shared frozen object by default.
+ // We'll use it to determine whether we need to initialize legacy refs.
+
+ var emptyRefsObject = new React.Component().refs;
+ var didWarnAboutStateAssignmentForComponent;
+ var didWarnAboutUninitializedState;
+ var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate;
+ var didWarnAboutLegacyLifecyclesAndDerivedState;
+ var didWarnAboutUndefinedDerivedState;
+ var warnOnUndefinedDerivedState;
+ var warnOnInvalidCallback;
+ var didWarnAboutDirectlyAssigningPropsToState;
+ var didWarnAboutContextTypeAndContextTypes;
+ var didWarnAboutInvalidateContextType;
+
+ {
+ didWarnAboutStateAssignmentForComponent = new Set();
+ didWarnAboutUninitializedState = new Set();
+ didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set();
+ didWarnAboutLegacyLifecyclesAndDerivedState = new Set();
+ didWarnAboutDirectlyAssigningPropsToState = new Set();
+ didWarnAboutUndefinedDerivedState = new Set();
+ didWarnAboutContextTypeAndContextTypes = new Set();
+ didWarnAboutInvalidateContextType = new Set();
+ var didWarnOnInvalidCallback = new Set();
+
+ warnOnInvalidCallback = function (callback, callerName) {
+ if (callback === null || typeof callback === 'function') {
+ return;
+ }
+
+ var key = callerName + "_" + callback;
+
+ if (!didWarnOnInvalidCallback.has(key)) {
+ didWarnOnInvalidCallback.add(key);
+
+ error('%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback);
+ }
+ };
+
+ warnOnUndefinedDerivedState = function (type, partialState) {
+ if (partialState === undefined) {
+ var componentName = getComponentName(type) || 'Component';
+
+ if (!didWarnAboutUndefinedDerivedState.has(componentName)) {
+ didWarnAboutUndefinedDerivedState.add(componentName);
+
+ error('%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName);
+ }
+ }
+ }; // This is so gross but it's at least non-critical and can be removed if
+ // it causes problems. This is meant to give a nicer error message for
+ // ReactDOM15.unstable_renderSubtreeIntoContainer(reactDOM16Component,
+ // ...)) which otherwise throws a "_processChildContext is not a function"
+ // exception.
+
+
+ Object.defineProperty(fakeInternalInstance, '_processChildContext', {
+ enumerable: false,
+ value: function () {
+ {
+ {
+ throw Error( "_processChildContext is not available in React 16+. This likely means you have multiple copies of React and are attempting to nest a React 15 tree inside a React 16 tree using unstable_renderSubtreeIntoContainer, which isn't supported. Try to make sure you have only one copy of React (and ideally, switch to ReactDOM.createPortal)." );
+ }
+ }
+ }
+ });
+ Object.freeze(fakeInternalInstance);
+ }
+
+ function applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, nextProps) {
+ var prevState = workInProgress.memoizedState;
+
+ {
+ if ( workInProgress.mode & StrictMode) {
+ // Invoke the function an extra time to help detect side-effects.
+ getDerivedStateFromProps(nextProps, prevState);
+ }
+ }
+
+ var partialState = getDerivedStateFromProps(nextProps, prevState);
+
+ {
+ warnOnUndefinedDerivedState(ctor, partialState);
+ } // Merge the partial state and the previous state.
+
+
+ var memoizedState = partialState === null || partialState === undefined ? prevState : _assign({}, prevState, partialState);
+ workInProgress.memoizedState = memoizedState; // Once the update queue is empty, persist the derived state onto the
+ // base state.
+
+ if (workInProgress.expirationTime === NoWork) {
+ // Queue is always non-null for classes
+ var updateQueue = workInProgress.updateQueue;
+ updateQueue.baseState = memoizedState;
+ }
+ }
+ var classComponentUpdater = {
+ isMounted: isMounted,
+ enqueueSetState: function (inst, payload, callback) {
+ var fiber = get(inst);
+ var currentTime = requestCurrentTimeForUpdate();
+ var suspenseConfig = requestCurrentSuspenseConfig();
+ var expirationTime = computeExpirationForFiber(currentTime, fiber, suspenseConfig);
+ var update = createUpdate(expirationTime, suspenseConfig);
+ update.payload = payload;
+
+ if (callback !== undefined && callback !== null) {
+ {
+ warnOnInvalidCallback(callback, 'setState');
+ }
+
+ update.callback = callback;
+ }
+
+ enqueueUpdate(fiber, update);
+ scheduleWork(fiber, expirationTime);
+ },
+ enqueueReplaceState: function (inst, payload, callback) {
+ var fiber = get(inst);
+ var currentTime = requestCurrentTimeForUpdate();
+ var suspenseConfig = requestCurrentSuspenseConfig();
+ var expirationTime = computeExpirationForFiber(currentTime, fiber, suspenseConfig);
+ var update = createUpdate(expirationTime, suspenseConfig);
+ update.tag = ReplaceState;
+ update.payload = payload;
+
+ if (callback !== undefined && callback !== null) {
+ {
+ warnOnInvalidCallback(callback, 'replaceState');
+ }
+
+ update.callback = callback;
+ }
+
+ enqueueUpdate(fiber, update);
+ scheduleWork(fiber, expirationTime);
+ },
+ enqueueForceUpdate: function (inst, callback) {
+ var fiber = get(inst);
+ var currentTime = requestCurrentTimeForUpdate();
+ var suspenseConfig = requestCurrentSuspenseConfig();
+ var expirationTime = computeExpirationForFiber(currentTime, fiber, suspenseConfig);
+ var update = createUpdate(expirationTime, suspenseConfig);
+ update.tag = ForceUpdate;
+
+ if (callback !== undefined && callback !== null) {
+ {
+ warnOnInvalidCallback(callback, 'forceUpdate');
+ }
+
+ update.callback = callback;
+ }
+
+ enqueueUpdate(fiber, update);
+ scheduleWork(fiber, expirationTime);
+ }
+ };
+
+ function checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext) {
+ var instance = workInProgress.stateNode;
+
+ if (typeof instance.shouldComponentUpdate === 'function') {
+ {
+ if ( workInProgress.mode & StrictMode) {
+ // Invoke the function an extra time to help detect side-effects.
+ instance.shouldComponentUpdate(newProps, newState, nextContext);
+ }
+ }
+
+ startPhaseTimer(workInProgress, 'shouldComponentUpdate');
+ var shouldUpdate = instance.shouldComponentUpdate(newProps, newState, nextContext);
+ stopPhaseTimer();
+
+ {
+ if (shouldUpdate === undefined) {
+ error('%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', getComponentName(ctor) || 'Component');
+ }
+ }
+
+ return shouldUpdate;
+ }
+
+ if (ctor.prototype && ctor.prototype.isPureReactComponent) {
+ return !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState);
+ }
+
+ return true;
+ }
+
+ function checkClassInstance(workInProgress, ctor, newProps) {
+ var instance = workInProgress.stateNode;
+
+ {
+ var name = getComponentName(ctor) || 'Component';
+ var renderPresent = instance.render;
+
+ if (!renderPresent) {
+ if (ctor.prototype && typeof ctor.prototype.render === 'function') {
+ error('%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name);
+ } else {
+ error('%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name);
+ }
+ }
+
+ if (instance.getInitialState && !instance.getInitialState.isReactClassApproved && !instance.state) {
+ error('getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', name);
+ }
+
+ if (instance.getDefaultProps && !instance.getDefaultProps.isReactClassApproved) {
+ error('getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', name);
+ }
+
+ if (instance.propTypes) {
+ error('propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name);
+ }
+
+ if (instance.contextType) {
+ error('contextType was defined as an instance property on %s. Use a static ' + 'property to define contextType instead.', name);
+ }
+
+ {
+ if (instance.contextTypes) {
+ error('contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name);
+ }
+
+ if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) {
+ didWarnAboutContextTypeAndContextTypes.add(ctor);
+
+ error('%s declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', name);
+ }
+ }
+
+ if (typeof instance.componentShouldUpdate === 'function') {
+ error('%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', name);
+ }
+
+ if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') {
+ error('%s has a method called shouldComponentUpdate(). ' + 'shouldComponentUpdate should not be used when extending React.PureComponent. ' + 'Please extend React.Component if shouldComponentUpdate is used.', getComponentName(ctor) || 'A pure component');
+ }
+
+ if (typeof instance.componentDidUnmount === 'function') {
+ error('%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name);
+ }
+
+ if (typeof instance.componentDidReceiveProps === 'function') {
+ error('%s has a method called ' + 'componentDidReceiveProps(). But there is no such lifecycle method. ' + 'If you meant to update the state in response to changing props, ' + 'use componentWillReceiveProps(). If you meant to fetch data or ' + 'run side-effects or mutations after React has updated the UI, use componentDidUpdate().', name);
+ }
+
+ if (typeof instance.componentWillRecieveProps === 'function') {
+ error('%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name);
+ }
+
+ if (typeof instance.UNSAFE_componentWillRecieveProps === 'function') {
+ error('%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name);
+ }
+
+ var hasMutatedProps = instance.props !== newProps;
+
+ if (instance.props !== undefined && hasMutatedProps) {
+ error('%s(...): When calling super() in `%s`, make sure to pass ' + "up the same props that your component's constructor was passed.", name, name);
+ }
+
+ if (instance.defaultProps) {
+ error('Setting defaultProps as an instance property on %s is not supported and will be ignored.' + ' Instead, define defaultProps as a static property on %s.', name, name);
+ }
+
+ if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) {
+ didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor);
+
+ error('%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentName(ctor));
+ }
+
+ if (typeof instance.getDerivedStateFromProps === 'function') {
+ error('%s: getDerivedStateFromProps() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name);
+ }
+
+ if (typeof instance.getDerivedStateFromError === 'function') {
+ error('%s: getDerivedStateFromError() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name);
+ }
+
+ if (typeof ctor.getSnapshotBeforeUpdate === 'function') {
+ error('%s: getSnapshotBeforeUpdate() is defined as a static method ' + 'and will be ignored. Instead, declare it as an instance method.', name);
+ }
+
+ var _state = instance.state;
+
+ if (_state && (typeof _state !== 'object' || isArray(_state))) {
+ error('%s.state: must be set to an object or null', name);
+ }
+
+ if (typeof instance.getChildContext === 'function' && typeof ctor.childContextTypes !== 'object') {
+ error('%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name);
+ }
+ }
+ }
+
+ function adoptClassInstance(workInProgress, instance) {
+ instance.updater = classComponentUpdater;
+ workInProgress.stateNode = instance; // The instance needs access to the fiber so that it can schedule updates
+
+ set(instance, workInProgress);
+
+ {
+ instance._reactInternalInstance = fakeInternalInstance;
+ }
+ }
+
+ function constructClassInstance(workInProgress, ctor, props) {
+ var isLegacyContextConsumer = false;
+ var unmaskedContext = emptyContextObject;
+ var context = emptyContextObject;
+ var contextType = ctor.contextType;
+
+ {
+ if ('contextType' in ctor) {
+ var isValid = // Allow null for conditional declaration
+ contextType === null || contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === undefined; // Not a <Context.Consumer>
+
+ if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) {
+ didWarnAboutInvalidateContextType.add(ctor);
+ var addendum = '';
+
+ if (contextType === undefined) {
+ addendum = ' However, it is set to undefined. ' + 'This can be caused by a typo or by mixing up named and default imports. ' + 'This can also happen due to a circular dependency, so ' + 'try moving the createContext() call to a separate file.';
+ } else if (typeof contextType !== 'object') {
+ addendum = ' However, it is set to a ' + typeof contextType + '.';
+ } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) {
+ addendum = ' Did you accidentally pass the Context.Provider instead?';
+ } else if (contextType._context !== undefined) {
+ // <Context.Consumer>
+ addendum = ' Did you accidentally pass the Context.Consumer instead?';
+ } else {
+ addendum = ' However, it is set to an object with keys {' + Object.keys(contextType).join(', ') + '}.';
+ }
+
+ error('%s defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext().%s', getComponentName(ctor) || 'Component', addendum);
+ }
+ }
+ }
+
+ if (typeof contextType === 'object' && contextType !== null) {
+ context = readContext(contextType);
+ } else {
+ unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
+ var contextTypes = ctor.contextTypes;
+ isLegacyContextConsumer = contextTypes !== null && contextTypes !== undefined;
+ context = isLegacyContextConsumer ? getMaskedContext(workInProgress, unmaskedContext) : emptyContextObject;
+ } // Instantiate twice to help detect side-effects.
+
+
+ {
+ if ( workInProgress.mode & StrictMode) {
+ new ctor(props, context); // eslint-disable-line no-new
+ }
+ }
+
+ var instance = new ctor(props, context);
+ var state = workInProgress.memoizedState = instance.state !== null && instance.state !== undefined ? instance.state : null;
+ adoptClassInstance(workInProgress, instance);
+
+ {
+ if (typeof ctor.getDerivedStateFromProps === 'function' && state === null) {
+ var componentName = getComponentName(ctor) || 'Component';
+
+ if (!didWarnAboutUninitializedState.has(componentName)) {
+ didWarnAboutUninitializedState.add(componentName);
+
+ error('`%s` uses `getDerivedStateFromProps` but its initial state is ' + '%s. This is not recommended. Instead, define the initial state by ' + 'assigning an object to `this.state` in the constructor of `%s`. ' + 'This ensures that `getDerivedStateFromProps` arguments have a consistent shape.', componentName, instance.state === null ? 'null' : 'undefined', componentName);
+ }
+ } // If new component APIs are defined, "unsafe" lifecycles won't be called.
+ // Warn about these lifecycles if they are present.
+ // Don't warn about react-lifecycles-compat polyfilled methods though.
+
+
+ if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') {
+ var foundWillMountName = null;
+ var foundWillReceivePropsName = null;
+ var foundWillUpdateName = null;
+
+ if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) {
+ foundWillMountName = 'componentWillMount';
+ } else if (typeof instance.UNSAFE_componentWillMount === 'function') {
+ foundWillMountName = 'UNSAFE_componentWillMount';
+ }
+
+ if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) {
+ foundWillReceivePropsName = 'componentWillReceiveProps';
+ } else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
+ foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps';
+ }
+
+ if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) {
+ foundWillUpdateName = 'componentWillUpdate';
+ } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
+ foundWillUpdateName = 'UNSAFE_componentWillUpdate';
+ }
+
+ if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) {
+ var _componentName = getComponentName(ctor) || 'Component';
+
+ var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()';
+
+ if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) {
+ didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName);
+
+ error('Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' + '%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n' + 'The above lifecycles should be removed. Learn more about this warning here:\n' + 'https://fb.me/react-unsafe-component-lifecycles', _componentName, newApiName, foundWillMountName !== null ? "\n " + foundWillMountName : '', foundWillReceivePropsName !== null ? "\n " + foundWillReceivePropsName : '', foundWillUpdateName !== null ? "\n " + foundWillUpdateName : '');
+ }
+ }
+ }
+ } // Cache unmasked context so we can avoid recreating masked context unless necessary.
+ // ReactFiberContext usually updates this cache but can't for newly-created instances.
+
+
+ if (isLegacyContextConsumer) {
+ cacheContext(workInProgress, unmaskedContext, context);
+ }
+
+ return instance;
+ }
+
+ function callComponentWillMount(workInProgress, instance) {
+ startPhaseTimer(workInProgress, 'componentWillMount');
+ var oldState = instance.state;
+
+ if (typeof instance.componentWillMount === 'function') {
+ instance.componentWillMount();
+ }
+
+ if (typeof instance.UNSAFE_componentWillMount === 'function') {
+ instance.UNSAFE_componentWillMount();
+ }
+
+ stopPhaseTimer();
+
+ if (oldState !== instance.state) {
+ {
+ error('%s.componentWillMount(): Assigning directly to this.state is ' + "deprecated (except inside a component's " + 'constructor). Use setState instead.', getComponentName(workInProgress.type) || 'Component');
+ }
+
+ classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
+ }
+ }
+
+ function callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext) {
+ var oldState = instance.state;
+ startPhaseTimer(workInProgress, 'componentWillReceiveProps');
+
+ if (typeof instance.componentWillReceiveProps === 'function') {
+ instance.componentWillReceiveProps(newProps, nextContext);
+ }
+
+ if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
+ instance.UNSAFE_componentWillReceiveProps(newProps, nextContext);
+ }
+
+ stopPhaseTimer();
+
+ if (instance.state !== oldState) {
+ {
+ var componentName = getComponentName(workInProgress.type) || 'Component';
+
+ if (!didWarnAboutStateAssignmentForComponent.has(componentName)) {
+ didWarnAboutStateAssignmentForComponent.add(componentName);
+
+ error('%s.componentWillReceiveProps(): Assigning directly to ' + "this.state is deprecated (except inside a component's " + 'constructor). Use setState instead.', componentName);
+ }
+ }
+
+ classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
+ }
+ } // Invokes the mount life-cycles on a previously never rendered instance.
+
+
+ function mountClassInstance(workInProgress, ctor, newProps, renderExpirationTime) {
+ {
+ checkClassInstance(workInProgress, ctor, newProps);
+ }
+
+ var instance = workInProgress.stateNode;
+ instance.props = newProps;
+ instance.state = workInProgress.memoizedState;
+ instance.refs = emptyRefsObject;
+ initializeUpdateQueue(workInProgress);
+ var contextType = ctor.contextType;
+
+ if (typeof contextType === 'object' && contextType !== null) {
+ instance.context = readContext(contextType);
+ } else {
+ var unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
+ instance.context = getMaskedContext(workInProgress, unmaskedContext);
+ }
+
+ {
+ if (instance.state === newProps) {
+ var componentName = getComponentName(ctor) || 'Component';
+
+ if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) {
+ didWarnAboutDirectlyAssigningPropsToState.add(componentName);
+
+ error('%s: It is not recommended to assign props directly to state ' + "because updates to props won't be reflected in state. " + 'In most cases, it is better to use props directly.', componentName);
+ }
+ }
+
+ if (workInProgress.mode & StrictMode) {
+ ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, instance);
+ }
+
+ {
+ ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(workInProgress, instance);
+ }
+ }
+
+ processUpdateQueue(workInProgress, newProps, instance, renderExpirationTime);
+ instance.state = workInProgress.memoizedState;
+ var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
+
+ if (typeof getDerivedStateFromProps === 'function') {
+ applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
+ instance.state = workInProgress.memoizedState;
+ } // In order to support react-lifecycles-compat polyfilled components,
+ // Unsafe lifecycles should not be invoked for components using the new APIs.
+
+
+ if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
+ callComponentWillMount(workInProgress, instance); // If we had additional state updates during this life-cycle, let's
+ // process them now.
+
+ processUpdateQueue(workInProgress, newProps, instance, renderExpirationTime);
+ instance.state = workInProgress.memoizedState;
+ }
+
+ if (typeof instance.componentDidMount === 'function') {
+ workInProgress.effectTag |= Update;
+ }
+ }
+
+ function resumeMountClassInstance(workInProgress, ctor, newProps, renderExpirationTime) {
+ var instance = workInProgress.stateNode;
+ var oldProps = workInProgress.memoizedProps;
+ instance.props = oldProps;
+ var oldContext = instance.context;
+ var contextType = ctor.contextType;
+ var nextContext = emptyContextObject;
+
+ if (typeof contextType === 'object' && contextType !== null) {
+ nextContext = readContext(contextType);
+ } else {
+ var nextLegacyUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
+ nextContext = getMaskedContext(workInProgress, nextLegacyUnmaskedContext);
+ }
+
+ var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
+ var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; // Note: During these life-cycles, instance.props/instance.state are what
+ // ever the previously attempted to render - not the "current". However,
+ // during componentDidUpdate we pass the "current" props.
+ // In order to support react-lifecycles-compat polyfilled components,
+ // Unsafe lifecycles should not be invoked for components using the new APIs.
+
+ if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {
+ if (oldProps !== newProps || oldContext !== nextContext) {
+ callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);
+ }
+ }
+
+ resetHasForceUpdateBeforeProcessing();
+ var oldState = workInProgress.memoizedState;
+ var newState = instance.state = oldState;
+ processUpdateQueue(workInProgress, newProps, instance, renderExpirationTime);
+ newState = workInProgress.memoizedState;
+
+ if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {
+ // If an update was already in progress, we should schedule an Update
+ // effect even though we're bailing out, so that cWU/cDU are called.
+ if (typeof instance.componentDidMount === 'function') {
+ workInProgress.effectTag |= Update;
+ }
+
+ return false;
+ }
+
+ if (typeof getDerivedStateFromProps === 'function') {
+ applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
+ newState = workInProgress.memoizedState;
+ }
+
+ var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext);
+
+ if (shouldUpdate) {
+ // In order to support react-lifecycles-compat polyfilled components,
+ // Unsafe lifecycles should not be invoked for components using the new APIs.
+ if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) {
+ startPhaseTimer(workInProgress, 'componentWillMount');
+
+ if (typeof instance.componentWillMount === 'function') {
+ instance.componentWillMount();
+ }
+
+ if (typeof instance.UNSAFE_componentWillMount === 'function') {
+ instance.UNSAFE_componentWillMount();
+ }
+
+ stopPhaseTimer();
+ }
+
+ if (typeof instance.componentDidMount === 'function') {
+ workInProgress.effectTag |= Update;
+ }
+ } else {
+ // If an update was already in progress, we should schedule an Update
+ // effect even though we're bailing out, so that cWU/cDU are called.
+ if (typeof instance.componentDidMount === 'function') {
+ workInProgress.effectTag |= Update;
+ } // If shouldComponentUpdate returned false, we should still update the
+ // memoized state to indicate that this work can be reused.
+
+
+ workInProgress.memoizedProps = newProps;
+ workInProgress.memoizedState = newState;
+ } // Update the existing instance's state, props, and context pointers even
+ // if shouldComponentUpdate returns false.
+
+
+ instance.props = newProps;
+ instance.state = newState;
+ instance.context = nextContext;
+ return shouldUpdate;
+ } // Invokes the update life-cycles and returns false if it shouldn't rerender.
+
+
+ function updateClassInstance(current, workInProgress, ctor, newProps, renderExpirationTime) {
+ var instance = workInProgress.stateNode;
+ cloneUpdateQueue(current, workInProgress);
+ var oldProps = workInProgress.memoizedProps;
+ instance.props = workInProgress.type === workInProgress.elementType ? oldProps : resolveDefaultProps(workInProgress.type, oldProps);
+ var oldContext = instance.context;
+ var contextType = ctor.contextType;
+ var nextContext = emptyContextObject;
+
+ if (typeof contextType === 'object' && contextType !== null) {
+ nextContext = readContext(contextType);
+ } else {
+ var nextUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
+ nextContext = getMaskedContext(workInProgress, nextUnmaskedContext);
+ }
+
+ var getDerivedStateFromProps = ctor.getDerivedStateFromProps;
+ var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; // Note: During these life-cycles, instance.props/instance.state are what
+ // ever the previously attempted to render - not the "current". However,
+ // during componentDidUpdate we pass the "current" props.
+ // In order to support react-lifecycles-compat polyfilled components,
+ // Unsafe lifecycles should not be invoked for components using the new APIs.
+
+ if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) {
+ if (oldProps !== newProps || oldContext !== nextContext) {
+ callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext);
+ }
+ }
+
+ resetHasForceUpdateBeforeProcessing();
+ var oldState = workInProgress.memoizedState;
+ var newState = instance.state = oldState;
+ processUpdateQueue(workInProgress, newProps, instance, renderExpirationTime);
+ newState = workInProgress.memoizedState;
+
+ if (oldProps === newProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()) {
+ // If an update was already in progress, we should schedule an Update
+ // effect even though we're bailing out, so that cWU/cDU are called.
+ if (typeof instance.componentDidUpdate === 'function') {
+ if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
+ workInProgress.effectTag |= Update;
+ }
+ }
+
+ if (typeof instance.getSnapshotBeforeUpdate === 'function') {
+ if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
+ workInProgress.effectTag |= Snapshot;
+ }
+ }
+
+ return false;
+ }
+
+ if (typeof getDerivedStateFromProps === 'function') {
+ applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps);
+ newState = workInProgress.memoizedState;
+ }
+
+ var shouldUpdate = checkHasForceUpdateAfterProcessing() || checkShouldComponentUpdate(workInProgress, ctor, oldProps, newProps, oldState, newState, nextContext);
+
+ if (shouldUpdate) {
+ // In order to support react-lifecycles-compat polyfilled components,
+ // Unsafe lifecycles should not be invoked for components using the new APIs.
+ if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillUpdate === 'function' || typeof instance.componentWillUpdate === 'function')) {
+ startPhaseTimer(workInProgress, 'componentWillUpdate');
+
+ if (typeof instance.componentWillUpdate === 'function') {
+ instance.componentWillUpdate(newProps, newState, nextContext);
+ }
+
+ if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
+ instance.UNSAFE_componentWillUpdate(newProps, newState, nextContext);
+ }
+
+ stopPhaseTimer();
+ }
+
+ if (typeof instance.componentDidUpdate === 'function') {
+ workInProgress.effectTag |= Update;
+ }
+
+ if (typeof instance.getSnapshotBeforeUpdate === 'function') {
+ workInProgress.effectTag |= Snapshot;
+ }
+ } else {
+ // If an update was already in progress, we should schedule an Update
+ // effect even though we're bailing out, so that cWU/cDU are called.
+ if (typeof instance.componentDidUpdate === 'function') {
+ if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
+ workInProgress.effectTag |= Update;
+ }
+ }
+
+ if (typeof instance.getSnapshotBeforeUpdate === 'function') {
+ if (oldProps !== current.memoizedProps || oldState !== current.memoizedState) {
+ workInProgress.effectTag |= Snapshot;
+ }
+ } // If shouldComponentUpdate returned false, we should still update the
+ // memoized props/state to indicate that this work can be reused.
+
+
+ workInProgress.memoizedProps = newProps;
+ workInProgress.memoizedState = newState;
+ } // Update the existing instance's state, props, and context pointers even
+ // if shouldComponentUpdate returns false.
+
+
+ instance.props = newProps;
+ instance.state = newState;
+ instance.context = nextContext;
+ return shouldUpdate;
+ }
+
+ var didWarnAboutMaps;
+ var didWarnAboutGenerators;
+ var didWarnAboutStringRefs;
+ var ownerHasKeyUseWarning;
+ var ownerHasFunctionTypeWarning;
+
+ var warnForMissingKey = function (child) {};
+
+ {
+ didWarnAboutMaps = false;
+ didWarnAboutGenerators = false;
+ didWarnAboutStringRefs = {};
+ /**
+ * Warn if there's no key explicitly set on dynamic arrays of children or
+ * object keys are not valid. This allows us to keep track of children between
+ * updates.
+ */
+
+ ownerHasKeyUseWarning = {};
+ ownerHasFunctionTypeWarning = {};
+
+ warnForMissingKey = function (child) {
+ if (child === null || typeof child !== 'object') {
+ return;
+ }
+
+ if (!child._store || child._store.validated || child.key != null) {
+ return;
+ }
+
+ if (!(typeof child._store === 'object')) {
+ {
+ throw Error( "React Component in warnForMissingKey should have a _store. This error is likely caused by a bug in React. Please file an issue." );
+ }
+ }
+
+ child._store.validated = true;
+ var currentComponentErrorInfo = 'Each child in a list should have a unique ' + '"key" prop. See https://fb.me/react-warning-keys for ' + 'more information.' + getCurrentFiberStackInDev();
+
+ if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
+ return;
+ }
+
+ ownerHasKeyUseWarning[currentComponentErrorInfo] = true;
+
+ error('Each child in a list should have a unique ' + '"key" prop. See https://fb.me/react-warning-keys for ' + 'more information.');
+ };
+ }
+
+ var isArray$1 = Array.isArray;
+
+ function coerceRef(returnFiber, current, element) {
+ var mixedRef = element.ref;
+
+ if (mixedRef !== null && typeof mixedRef !== 'function' && typeof mixedRef !== 'object') {
+ {
+ // TODO: Clean this up once we turn on the string ref warning for
+ // everyone, because the strict mode case will no longer be relevant
+ if ((returnFiber.mode & StrictMode || warnAboutStringRefs) && // We warn in ReactElement.js if owner and self are equal for string refs
+ // because these cannot be automatically converted to an arrow function
+ // using a codemod. Therefore, we don't have to warn about string refs again.
+ !(element._owner && element._self && element._owner.stateNode !== element._self)) {
+ var componentName = getComponentName(returnFiber.type) || 'Component';
+
+ if (!didWarnAboutStringRefs[componentName]) {
+ {
+ error('A string ref, "%s", has been found within a strict mode tree. ' + 'String refs are a source of potential bugs and should be avoided. ' + 'We recommend using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://fb.me/react-strict-mode-string-ref%s', mixedRef, getStackByFiberInDevAndProd(returnFiber));
+ }
+
+ didWarnAboutStringRefs[componentName] = true;
+ }
+ }
+ }
+
+ if (element._owner) {
+ var owner = element._owner;
+ var inst;
+
+ if (owner) {
+ var ownerFiber = owner;
+
+ if (!(ownerFiber.tag === ClassComponent)) {
+ {
+ throw Error( "Function components cannot have string refs. We recommend using useRef() instead. Learn more about using refs safely here: https://fb.me/react-strict-mode-string-ref" );
+ }
+ }
+
+ inst = ownerFiber.stateNode;
+ }
+
+ if (!inst) {
+ {
+ throw Error( "Missing owner for string ref " + mixedRef + ". This error is likely caused by a bug in React. Please file an issue." );
+ }
+ }
+
+ var stringRef = '' + mixedRef; // Check if previous string ref matches new string ref
+
+ if (current !== null && current.ref !== null && typeof current.ref === 'function' && current.ref._stringRef === stringRef) {
+ return current.ref;
+ }
+
+ var ref = function (value) {
+ var refs = inst.refs;
+
+ if (refs === emptyRefsObject) {
+ // This is a lazy pooled frozen object, so we need to initialize.
+ refs = inst.refs = {};
+ }
+
+ if (value === null) {
+ delete refs[stringRef];
+ } else {
+ refs[stringRef] = value;
+ }
+ };
+
+ ref._stringRef = stringRef;
+ return ref;
+ } else {
+ if (!(typeof mixedRef === 'string')) {
+ {
+ throw Error( "Expected ref to be a function, a string, an object returned by React.createRef(), or null." );
+ }
+ }
+
+ if (!element._owner) {
+ {
+ throw Error( "Element ref was specified as a string (" + mixedRef + ") but no owner was set. This could happen for one of the following reasons:\n1. You may be adding a ref to a function component\n2. You may be adding a ref to a component that was not created inside a component's render method\n3. You have multiple copies of React loaded\nSee https://fb.me/react-refs-must-have-owner for more information." );
+ }
+ }
+ }
+ }
+
+ return mixedRef;
+ }
+
+ function throwOnInvalidObjectType(returnFiber, newChild) {
+ if (returnFiber.type !== 'textarea') {
+ var addendum = '';
+
+ {
+ addendum = ' If you meant to render a collection of children, use an array ' + 'instead.' + getCurrentFiberStackInDev();
+ }
+
+ {
+ {
+ throw Error( "Objects are not valid as a React child (found: " + (Object.prototype.toString.call(newChild) === '[object Object]' ? 'object with keys {' + Object.keys(newChild).join(', ') + '}' : newChild) + ")." + addendum );
+ }
+ }
+ }
+ }
+
+ function warnOnFunctionType() {
+ {
+ var currentComponentErrorInfo = 'Functions are not valid as a React child. This may happen if ' + 'you return a Component instead of <Component /> from render. ' + 'Or maybe you meant to call this function rather than return it.' + getCurrentFiberStackInDev();
+
+ if (ownerHasFunctionTypeWarning[currentComponentErrorInfo]) {
+ return;
+ }
+
+ ownerHasFunctionTypeWarning[currentComponentErrorInfo] = true;
+
+ error('Functions are not valid as a React child. This may happen if ' + 'you return a Component instead of <Component /> from render. ' + 'Or maybe you meant to call this function rather than return it.');
+ }
+ } // This wrapper function exists because I expect to clone the code in each path
+ // to be able to optimize each path individually by branching early. This needs
+ // a compiler or we can do it manually. Helpers that don't need this branching
+ // live outside of this function.
+
+
+ function ChildReconciler(shouldTrackSideEffects) {
+ function deleteChild(returnFiber, childToDelete) {
+ if (!shouldTrackSideEffects) {
+ // Noop.
+ return;
+ } // Deletions are added in reversed order so we add it to the front.
+ // At this point, the return fiber's effect list is empty except for
+ // deletions, so we can just append the deletion to the list. The remaining
+ // effects aren't added until the complete phase. Once we implement
+ // resuming, this may not be true.
+
+
+ var last = returnFiber.lastEffect;
+
+ if (last !== null) {
+ last.nextEffect = childToDelete;
+ returnFiber.lastEffect = childToDelete;
+ } else {
+ returnFiber.firstEffect = returnFiber.lastEffect = childToDelete;
+ }
+
+ childToDelete.nextEffect = null;
+ childToDelete.effectTag = Deletion;
+ }
+
+ function deleteRemainingChildren(returnFiber, currentFirstChild) {
+ if (!shouldTrackSideEffects) {
+ // Noop.
+ return null;
+ } // TODO: For the shouldClone case, this could be micro-optimized a bit by
+ // assuming that after the first child we've already added everything.
+
+
+ var childToDelete = currentFirstChild;
+
+ while (childToDelete !== null) {
+ deleteChild(returnFiber, childToDelete);
+ childToDelete = childToDelete.sibling;
+ }
+
+ return null;
+ }
+
+ function mapRemainingChildren(returnFiber, currentFirstChild) {
+ // Add the remaining children to a temporary map so that we can find them by
+ // keys quickly. Implicit (null) keys get added to this set with their index
+ // instead.
+ var existingChildren = new Map();
+ var existingChild = currentFirstChild;
+
+ while (existingChild !== null) {
+ if (existingChild.key !== null) {
+ existingChildren.set(existingChild.key, existingChild);
+ } else {
+ existingChildren.set(existingChild.index, existingChild);
+ }
+
+ existingChild = existingChild.sibling;
+ }
+
+ return existingChildren;
+ }
+
+ function useFiber(fiber, pendingProps) {
+ // We currently set sibling to null and index to 0 here because it is easy
+ // to forget to do before returning it. E.g. for the single child case.
+ var clone = createWorkInProgress(fiber, pendingProps);
+ clone.index = 0;
+ clone.sibling = null;
+ return clone;
+ }
+
+ function placeChild(newFiber, lastPlacedIndex, newIndex) {
+ newFiber.index = newIndex;
+
+ if (!shouldTrackSideEffects) {
+ // Noop.
+ return lastPlacedIndex;
+ }
+
+ var current = newFiber.alternate;
+
+ if (current !== null) {
+ var oldIndex = current.index;
+
+ if (oldIndex < lastPlacedIndex) {
+ // This is a move.
+ newFiber.effectTag = Placement;
+ return lastPlacedIndex;
+ } else {
+ // This item can stay in place.
+ return oldIndex;
+ }
+ } else {
+ // This is an insertion.
+ newFiber.effectTag = Placement;
+ return lastPlacedIndex;
+ }
+ }
+
+ function placeSingleChild(newFiber) {
+ // This is simpler for the single child case. We only need to do a
+ // placement for inserting new children.
+ if (shouldTrackSideEffects && newFiber.alternate === null) {
+ newFiber.effectTag = Placement;
+ }
+
+ return newFiber;
+ }
+
+ function updateTextNode(returnFiber, current, textContent, expirationTime) {
+ if (current === null || current.tag !== HostText) {
+ // Insert
+ var created = createFiberFromText(textContent, returnFiber.mode, expirationTime);
+ created.return = returnFiber;
+ return created;
+ } else {
+ // Update
+ var existing = useFiber(current, textContent);
+ existing.return = returnFiber;
+ return existing;
+ }
+ }
+
+ function updateElement(returnFiber, current, element, expirationTime) {
+ if (current !== null) {
+ if (current.elementType === element.type || ( // Keep this check inline so it only runs on the false path:
+ isCompatibleFamilyForHotReloading(current, element) )) {
+ // Move based on index
+ var existing = useFiber(current, element.props);
+ existing.ref = coerceRef(returnFiber, current, element);
+ existing.return = returnFiber;
+
+ {
+ existing._debugSource = element._source;
+ existing._debugOwner = element._owner;
+ }
+
+ return existing;
+ }
+ } // Insert
+
+
+ var created = createFiberFromElement(element, returnFiber.mode, expirationTime);
+ created.ref = coerceRef(returnFiber, current, element);
+ created.return = returnFiber;
+ return created;
+ }
+
+ function updatePortal(returnFiber, current, portal, expirationTime) {
+ if (current === null || current.tag !== HostPortal || current.stateNode.containerInfo !== portal.containerInfo || current.stateNode.implementation !== portal.implementation) {
+ // Insert
+ var created = createFiberFromPortal(portal, returnFiber.mode, expirationTime);
+ created.return = returnFiber;
+ return created;
+ } else {
+ // Update
+ var existing = useFiber(current, portal.children || []);
+ existing.return = returnFiber;
+ return existing;
+ }
+ }
+
+ function updateFragment(returnFiber, current, fragment, expirationTime, key) {
+ if (current === null || current.tag !== Fragment) {
+ // Insert
+ var created = createFiberFromFragment(fragment, returnFiber.mode, expirationTime, key);
+ created.return = returnFiber;
+ return created;
+ } else {
+ // Update
+ var existing = useFiber(current, fragment);
+ existing.return = returnFiber;
+ return existing;
+ }
+ }
+
+ function createChild(returnFiber, newChild, expirationTime) {
+ if (typeof newChild === 'string' || typeof newChild === 'number') {
+ // Text nodes don't have keys. If the previous node is implicitly keyed
+ // we can continue to replace it without aborting even if it is not a text
+ // node.
+ var created = createFiberFromText('' + newChild, returnFiber.mode, expirationTime);
+ created.return = returnFiber;
+ return created;
+ }
+
+ if (typeof newChild === 'object' && newChild !== null) {
+ switch (newChild.$$typeof) {
+ case REACT_ELEMENT_TYPE:
+ {
+ var _created = createFiberFromElement(newChild, returnFiber.mode, expirationTime);
+
+ _created.ref = coerceRef(returnFiber, null, newChild);
+ _created.return = returnFiber;
+ return _created;
+ }
+
+ case REACT_PORTAL_TYPE:
+ {
+ var _created2 = createFiberFromPortal(newChild, returnFiber.mode, expirationTime);
+
+ _created2.return = returnFiber;
+ return _created2;
+ }
+ }
+
+ if (isArray$1(newChild) || getIteratorFn(newChild)) {
+ var _created3 = createFiberFromFragment(newChild, returnFiber.mode, expirationTime, null);
+
+ _created3.return = returnFiber;
+ return _created3;
+ }
+
+ throwOnInvalidObjectType(returnFiber, newChild);
+ }
+
+ {
+ if (typeof newChild === 'function') {
+ warnOnFunctionType();
+ }
+ }
+
+ return null;
+ }
+
+ function updateSlot(returnFiber, oldFiber, newChild, expirationTime) {
+ // Update the fiber if the keys match, otherwise return null.
+ var key = oldFiber !== null ? oldFiber.key : null;
+
+ if (typeof newChild === 'string' || typeof newChild === 'number') {
+ // Text nodes don't have keys. If the previous node is implicitly keyed
+ // we can continue to replace it without aborting even if it is not a text
+ // node.
+ if (key !== null) {
+ return null;
+ }
+
+ return updateTextNode(returnFiber, oldFiber, '' + newChild, expirationTime);
+ }
+
+ if (typeof newChild === 'object' && newChild !== null) {
+ switch (newChild.$$typeof) {
+ case REACT_ELEMENT_TYPE:
+ {
+ if (newChild.key === key) {
+ if (newChild.type === REACT_FRAGMENT_TYPE) {
+ return updateFragment(returnFiber, oldFiber, newChild.props.children, expirationTime, key);
+ }
+
+ return updateElement(returnFiber, oldFiber, newChild, expirationTime);
+ } else {
+ return null;
+ }
+ }
+
+ case REACT_PORTAL_TYPE:
+ {
+ if (newChild.key === key) {
+ return updatePortal(returnFiber, oldFiber, newChild, expirationTime);
+ } else {
+ return null;
+ }
+ }
+ }
+
+ if (isArray$1(newChild) || getIteratorFn(newChild)) {
+ if (key !== null) {
+ return null;
+ }
+
+ return updateFragment(returnFiber, oldFiber, newChild, expirationTime, null);
+ }
+
+ throwOnInvalidObjectType(returnFiber, newChild);
+ }
+
+ {
+ if (typeof newChild === 'function') {
+ warnOnFunctionType();
+ }
+ }
+
+ return null;
+ }
+
+ function updateFromMap(existingChildren, returnFiber, newIdx, newChild, expirationTime) {
+ if (typeof newChild === 'string' || typeof newChild === 'number') {
+ // Text nodes don't have keys, so we neither have to check the old nor
+ // new node for the key. If both are text nodes, they match.
+ var matchedFiber = existingChildren.get(newIdx) || null;
+ return updateTextNode(returnFiber, matchedFiber, '' + newChild, expirationTime);
+ }
+
+ if (typeof newChild === 'object' && newChild !== null) {
+ switch (newChild.$$typeof) {
+ case REACT_ELEMENT_TYPE:
+ {
+ var _matchedFiber = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;
+
+ if (newChild.type === REACT_FRAGMENT_TYPE) {
+ return updateFragment(returnFiber, _matchedFiber, newChild.props.children, expirationTime, newChild.key);
+ }
+
+ return updateElement(returnFiber, _matchedFiber, newChild, expirationTime);
+ }
+
+ case REACT_PORTAL_TYPE:
+ {
+ var _matchedFiber2 = existingChildren.get(newChild.key === null ? newIdx : newChild.key) || null;
+
+ return updatePortal(returnFiber, _matchedFiber2, newChild, expirationTime);
+ }
+ }
+
+ if (isArray$1(newChild) || getIteratorFn(newChild)) {
+ var _matchedFiber3 = existingChildren.get(newIdx) || null;
+
+ return updateFragment(returnFiber, _matchedFiber3, newChild, expirationTime, null);
+ }
+
+ throwOnInvalidObjectType(returnFiber, newChild);
+ }
+
+ {
+ if (typeof newChild === 'function') {
+ warnOnFunctionType();
+ }
+ }
+
+ return null;
+ }
+ /**
+ * Warns if there is a duplicate or missing key
+ */
+
+
+ function warnOnInvalidKey(child, knownKeys) {
+ {
+ if (typeof child !== 'object' || child === null) {
+ return knownKeys;
+ }
+
+ switch (child.$$typeof) {
+ case REACT_ELEMENT_TYPE:
+ case REACT_PORTAL_TYPE:
+ warnForMissingKey(child);
+ var key = child.key;
+
+ if (typeof key !== 'string') {
+ break;
+ }
+
+ if (knownKeys === null) {
+ knownKeys = new Set();
+ knownKeys.add(key);
+ break;
+ }
+
+ if (!knownKeys.has(key)) {
+ knownKeys.add(key);
+ break;
+ }
+
+ error('Encountered two children with the same key, `%s`. ' + 'Keys should be unique so that components maintain their identity ' + 'across updates. Non-unique keys may cause children to be ' + 'duplicated and/or omitted — the behavior is unsupported and ' + 'could change in a future version.', key);
+
+ break;
+ }
+ }
+
+ return knownKeys;
+ }
+
+ function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, expirationTime) {
+ // This algorithm can't optimize by searching from both ends since we
+ // don't have backpointers on fibers. I'm trying to see how far we can get
+ // with that model. If it ends up not being worth the tradeoffs, we can
+ // add it later.
+ // Even with a two ended optimization, we'd want to optimize for the case
+ // where there are few changes and brute force the comparison instead of
+ // going for the Map. It'd like to explore hitting that path first in
+ // forward-only mode and only go for the Map once we notice that we need
+ // lots of look ahead. This doesn't handle reversal as well as two ended
+ // search but that's unusual. Besides, for the two ended optimization to
+ // work on Iterables, we'd need to copy the whole set.
+ // In this first iteration, we'll just live with hitting the bad case
+ // (adding everything to a Map) in for every insert/move.
+ // If you change this code, also update reconcileChildrenIterator() which
+ // uses the same algorithm.
+ {
+ // First, validate keys.
+ var knownKeys = null;
+
+ for (var i = 0; i < newChildren.length; i++) {
+ var child = newChildren[i];
+ knownKeys = warnOnInvalidKey(child, knownKeys);
+ }
+ }
+
+ var resultingFirstChild = null;
+ var previousNewFiber = null;
+ var oldFiber = currentFirstChild;
+ var lastPlacedIndex = 0;
+ var newIdx = 0;
+ var nextOldFiber = null;
+
+ for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) {
+ if (oldFiber.index > newIdx) {
+ nextOldFiber = oldFiber;
+ oldFiber = null;
+ } else {
+ nextOldFiber = oldFiber.sibling;
+ }
+
+ var newFiber = updateSlot(returnFiber, oldFiber, newChildren[newIdx], expirationTime);
+
+ if (newFiber === null) {
+ // TODO: This breaks on empty slots like null children. That's
+ // unfortunate because it triggers the slow path all the time. We need
+ // a better way to communicate whether this was a miss or null,
+ // boolean, undefined, etc.
+ if (oldFiber === null) {
+ oldFiber = nextOldFiber;
+ }
+
+ break;
+ }
+
+ if (shouldTrackSideEffects) {
+ if (oldFiber && newFiber.alternate === null) {
+ // We matched the slot, but we didn't reuse the existing fiber, so we
+ // need to delete the existing child.
+ deleteChild(returnFiber, oldFiber);
+ }
+ }
+
+ lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
+
+ if (previousNewFiber === null) {
+ // TODO: Move out of the loop. This only happens for the first run.
+ resultingFirstChild = newFiber;
+ } else {
+ // TODO: Defer siblings if we're not at the right index for this slot.
+ // I.e. if we had null values before, then we want to defer this
+ // for each null value. However, we also don't want to call updateSlot
+ // with the previous one.
+ previousNewFiber.sibling = newFiber;
+ }
+
+ previousNewFiber = newFiber;
+ oldFiber = nextOldFiber;
+ }
+
+ if (newIdx === newChildren.length) {
+ // We've reached the end of the new children. We can delete the rest.
+ deleteRemainingChildren(returnFiber, oldFiber);
+ return resultingFirstChild;
+ }
+
+ if (oldFiber === null) {
+ // If we don't have any more existing children we can choose a fast path
+ // since the rest will all be insertions.
+ for (; newIdx < newChildren.length; newIdx++) {
+ var _newFiber = createChild(returnFiber, newChildren[newIdx], expirationTime);
+
+ if (_newFiber === null) {
+ continue;
+ }
+
+ lastPlacedIndex = placeChild(_newFiber, lastPlacedIndex, newIdx);
+
+ if (previousNewFiber === null) {
+ // TODO: Move out of the loop. This only happens for the first run.
+ resultingFirstChild = _newFiber;
+ } else {
+ previousNewFiber.sibling = _newFiber;
+ }
+
+ previousNewFiber = _newFiber;
+ }
+
+ return resultingFirstChild;
+ } // Add all children to a key map for quick lookups.
+
+
+ var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves.
+
+ for (; newIdx < newChildren.length; newIdx++) {
+ var _newFiber2 = updateFromMap(existingChildren, returnFiber, newIdx, newChildren[newIdx], expirationTime);
+
+ if (_newFiber2 !== null) {
+ if (shouldTrackSideEffects) {
+ if (_newFiber2.alternate !== null) {
+ // The new fiber is a work in progress, but if there exists a
+ // current, that means that we reused the fiber. We need to delete
+ // it from the child list so that we don't add it to the deletion
+ // list.
+ existingChildren.delete(_newFiber2.key === null ? newIdx : _newFiber2.key);
+ }
+ }
+
+ lastPlacedIndex = placeChild(_newFiber2, lastPlacedIndex, newIdx);
+
+ if (previousNewFiber === null) {
+ resultingFirstChild = _newFiber2;
+ } else {
+ previousNewFiber.sibling = _newFiber2;
+ }
+
+ previousNewFiber = _newFiber2;
+ }
+ }
+
+ if (shouldTrackSideEffects) {
+ // Any existing children that weren't consumed above were deleted. We need
+ // to add them to the deletion list.
+ existingChildren.forEach(function (child) {
+ return deleteChild(returnFiber, child);
+ });
+ }
+
+ return resultingFirstChild;
+ }
+
+ function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildrenIterable, expirationTime) {
+ // This is the same implementation as reconcileChildrenArray(),
+ // but using the iterator instead.
+ var iteratorFn = getIteratorFn(newChildrenIterable);
+
+ if (!(typeof iteratorFn === 'function')) {
+ {
+ throw Error( "An object is not an iterable. This error is likely caused by a bug in React. Please file an issue." );
+ }
+ }
+
+ {
+ // We don't support rendering Generators because it's a mutation.
+ // See https://github.com/facebook/react/issues/12995
+ if (typeof Symbol === 'function' && // $FlowFixMe Flow doesn't know about toStringTag
+ newChildrenIterable[Symbol.toStringTag] === 'Generator') {
+ if (!didWarnAboutGenerators) {
+ error('Using Generators as children is unsupported and will likely yield ' + 'unexpected results because enumerating a generator mutates it. ' + 'You may convert it to an array with `Array.from()` or the ' + '`[...spread]` operator before rendering. Keep in mind ' + 'you might need to polyfill these features for older browsers.');
+ }
+
+ didWarnAboutGenerators = true;
+ } // Warn about using Maps as children
+
+
+ if (newChildrenIterable.entries === iteratorFn) {
+ if (!didWarnAboutMaps) {
+ error('Using Maps as children is unsupported and will likely yield ' + 'unexpected results. Convert it to a sequence/iterable of keyed ' + 'ReactElements instead.');
+ }
+
+ didWarnAboutMaps = true;
+ } // First, validate keys.
+ // We'll get a different iterator later for the main pass.
+
+
+ var _newChildren = iteratorFn.call(newChildrenIterable);
+
+ if (_newChildren) {
+ var knownKeys = null;
+
+ var _step = _newChildren.next();
+
+ for (; !_step.done; _step = _newChildren.next()) {
+ var child = _step.value;
+ knownKeys = warnOnInvalidKey(child, knownKeys);
+ }
+ }
+ }
+
+ var newChildren = iteratorFn.call(newChildrenIterable);
+
+ if (!(newChildren != null)) {
+ {
+ throw Error( "An iterable object provided no iterator." );
+ }
+ }
+
+ var resultingFirstChild = null;
+ var previousNewFiber = null;
+ var oldFiber = currentFirstChild;
+ var lastPlacedIndex = 0;
+ var newIdx = 0;
+ var nextOldFiber = null;
+ var step = newChildren.next();
+
+ for (; oldFiber !== null && !step.done; newIdx++, step = newChildren.next()) {
+ if (oldFiber.index > newIdx) {
+ nextOldFiber = oldFiber;
+ oldFiber = null;
+ } else {
+ nextOldFiber = oldFiber.sibling;
+ }
+
+ var newFiber = updateSlot(returnFiber, oldFiber, step.value, expirationTime);
+
+ if (newFiber === null) {
+ // TODO: This breaks on empty slots like null children. That's
+ // unfortunate because it triggers the slow path all the time. We need
+ // a better way to communicate whether this was a miss or null,
+ // boolean, undefined, etc.
+ if (oldFiber === null) {
+ oldFiber = nextOldFiber;
+ }
+
+ break;
+ }
+
+ if (shouldTrackSideEffects) {
+ if (oldFiber && newFiber.alternate === null) {
+ // We matched the slot, but we didn't reuse the existing fiber, so we
+ // need to delete the existing child.
+ deleteChild(returnFiber, oldFiber);
+ }
+ }
+
+ lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
+
+ if (previousNewFiber === null) {
+ // TODO: Move out of the loop. This only happens for the first run.
+ resultingFirstChild = newFiber;
+ } else {
+ // TODO: Defer siblings if we're not at the right index for this slot.
+ // I.e. if we had null values before, then we want to defer this
+ // for each null value. However, we also don't want to call updateSlot
+ // with the previous one.
+ previousNewFiber.sibling = newFiber;
+ }
+
+ previousNewFiber = newFiber;
+ oldFiber = nextOldFiber;
+ }
+
+ if (step.done) {
+ // We've reached the end of the new children. We can delete the rest.
+ deleteRemainingChildren(returnFiber, oldFiber);
+ return resultingFirstChild;
+ }
+
+ if (oldFiber === null) {
+ // If we don't have any more existing children we can choose a fast path
+ // since the rest will all be insertions.
+ for (; !step.done; newIdx++, step = newChildren.next()) {
+ var _newFiber3 = createChild(returnFiber, step.value, expirationTime);
+
+ if (_newFiber3 === null) {
+ continue;
+ }
+
+ lastPlacedIndex = placeChild(_newFiber3, lastPlacedIndex, newIdx);
+
+ if (previousNewFiber === null) {
+ // TODO: Move out of the loop. This only happens for the first run.
+ resultingFirstChild = _newFiber3;
+ } else {
+ previousNewFiber.sibling = _newFiber3;
+ }
+
+ previousNewFiber = _newFiber3;
+ }
+
+ return resultingFirstChild;
+ } // Add all children to a key map for quick lookups.
+
+
+ var existingChildren = mapRemainingChildren(returnFiber, oldFiber); // Keep scanning and use the map to restore deleted items as moves.
+
+ for (; !step.done; newIdx++, step = newChildren.next()) {
+ var _newFiber4 = updateFromMap(existingChildren, returnFiber, newIdx, step.value, expirationTime);
+
+ if (_newFiber4 !== null) {
+ if (shouldTrackSideEffects) {
+ if (_newFiber4.alternate !== null) {
+ // The new fiber is a work in progress, but if there exists a
+ // current, that means that we reused the fiber. We need to delete
+ // it from the child list so that we don't add it to the deletion
+ // list.
+ existingChildren.delete(_newFiber4.key === null ? newIdx : _newFiber4.key);
+ }
+ }
+
+ lastPlacedIndex = placeChild(_newFiber4, lastPlacedIndex, newIdx);
+
+ if (previousNewFiber === null) {
+ resultingFirstChild = _newFiber4;
+ } else {
+ previousNewFiber.sibling = _newFiber4;
+ }
+
+ previousNewFiber = _newFiber4;
+ }
+ }
+
+ if (shouldTrackSideEffects) {
+ // Any existing children that weren't consumed above were deleted. We need
+ // to add them to the deletion list.
+ existingChildren.forEach(function (child) {
+ return deleteChild(returnFiber, child);
+ });
+ }
+
+ return resultingFirstChild;
+ }
+
+ function reconcileSingleTextNode(returnFiber, currentFirstChild, textContent, expirationTime) {
+ // There's no need to check for keys on text nodes since we don't have a
+ // way to define them.
+ if (currentFirstChild !== null && currentFirstChild.tag === HostText) {
+ // We already have an existing node so let's just update it and delete
+ // the rest.
+ deleteRemainingChildren(returnFiber, currentFirstChild.sibling);
+ var existing = useFiber(currentFirstChild, textContent);
+ existing.return = returnFiber;
+ return existing;
+ } // The existing first child is not a text node so we need to create one
+ // and delete the existing ones.
+
+
+ deleteRemainingChildren(returnFiber, currentFirstChild);
+ var created = createFiberFromText(textContent, returnFiber.mode, expirationTime);
+ created.return = returnFiber;
+ return created;
+ }
+
+ function reconcileSingleElement(returnFiber, currentFirstChild, element, expirationTime) {
+ var key = element.key;
+ var child = currentFirstChild;
+
+ while (child !== null) {
+ // TODO: If key === null and child.key === null, then this only applies to
+ // the first item in the list.
+ if (child.key === key) {
+ switch (child.tag) {
+ case Fragment:
+ {
+ if (element.type === REACT_FRAGMENT_TYPE) {
+ deleteRemainingChildren(returnFiber, child.sibling);
+ var existing = useFiber(child, element.props.children);
+ existing.return = returnFiber;
+
+ {
+ existing._debugSource = element._source;
+ existing._debugOwner = element._owner;
+ }
+
+ return existing;
+ }
+
+ break;
+ }
+
+ case Block:
+
+ // We intentionally fallthrough here if enableBlocksAPI is not on.
+ // eslint-disable-next-lined no-fallthrough
+
+ default:
+ {
+ if (child.elementType === element.type || ( // Keep this check inline so it only runs on the false path:
+ isCompatibleFamilyForHotReloading(child, element) )) {
+ deleteRemainingChildren(returnFiber, child.sibling);
+
+ var _existing3 = useFiber(child, element.props);
+
+ _existing3.ref = coerceRef(returnFiber, child, element);
+ _existing3.return = returnFiber;
+
+ {
+ _existing3._debugSource = element._source;
+ _existing3._debugOwner = element._owner;
+ }
+
+ return _existing3;
+ }
+
+ break;
+ }
+ } // Didn't match.
+
+
+ deleteRemainingChildren(returnFiber, child);
+ break;
+ } else {
+ deleteChild(returnFiber, child);
+ }
+
+ child = child.sibling;
+ }
+
+ if (element.type === REACT_FRAGMENT_TYPE) {
+ var created = createFiberFromFragment(element.props.children, returnFiber.mode, expirationTime, element.key);
+ created.return = returnFiber;
+ return created;
+ } else {
+ var _created4 = createFiberFromElement(element, returnFiber.mode, expirationTime);
+
+ _created4.ref = coerceRef(returnFiber, currentFirstChild, element);
+ _created4.return = returnFiber;
+ return _created4;
+ }
+ }
+
+ function reconcileSinglePortal(returnFiber, currentFirstChild, portal, expirationTime) {
+ var key = portal.key;
+ var child = currentFirstChild;
+
+ while (child !== null) {
+ // TODO: If key === null and child.key === null, then this only applies to
+ // the first item in the list.
+ if (child.key === key) {
+ if (child.tag === HostPortal && child.stateNode.containerInfo === portal.containerInfo && child.stateNode.implementation === portal.implementation) {
+ deleteRemainingChildren(returnFiber, child.sibling);
+ var existing = useFiber(child, portal.children || []);
+ existing.return = returnFiber;
+ return existing;
+ } else {
+ deleteRemainingChildren(returnFiber, child);
+ break;
+ }
+ } else {
+ deleteChild(returnFiber, child);
+ }
+
+ child = child.sibling;
+ }
+
+ var created = createFiberFromPortal(portal, returnFiber.mode, expirationTime);
+ created.return = returnFiber;
+ return created;
+ } // This API will tag the children with the side-effect of the reconciliation
+ // itself. They will be added to the side-effect list as we pass through the
+ // children and the parent.
+
+
+ function reconcileChildFibers(returnFiber, currentFirstChild, newChild, expirationTime) {
+ // This function is not recursive.
+ // If the top level item is an array, we treat it as a set of children,
+ // not as a fragment. Nested arrays on the other hand will be treated as
+ // fragment nodes. Recursion happens at the normal flow.
+ // Handle top level unkeyed fragments as if they were arrays.
+ // This leads to an ambiguity between <>{[...]}</> and <>...</>.
+ // We treat the ambiguous cases above the same.
+ var isUnkeyedTopLevelFragment = typeof newChild === 'object' && newChild !== null && newChild.type === REACT_FRAGMENT_TYPE && newChild.key === null;
+
+ if (isUnkeyedTopLevelFragment) {
+ newChild = newChild.props.children;
+ } // Handle object types
+
+
+ var isObject = typeof newChild === 'object' && newChild !== null;
+
+ if (isObject) {
+ switch (newChild.$$typeof) {
+ case REACT_ELEMENT_TYPE:
+ return placeSingleChild(reconcileSingleElement(returnFiber, currentFirstChild, newChild, expirationTime));
+
+ case REACT_PORTAL_TYPE:
+ return placeSingleChild(reconcileSinglePortal(returnFiber, currentFirstChild, newChild, expirationTime));
+ }
+ }
+
+ if (typeof newChild === 'string' || typeof newChild === 'number') {
+ return placeSingleChild(reconcileSingleTextNode(returnFiber, currentFirstChild, '' + newChild, expirationTime));
+ }
+
+ if (isArray$1(newChild)) {
+ return reconcileChildrenArray(returnFiber, currentFirstChild, newChild, expirationTime);
+ }
+
+ if (getIteratorFn(newChild)) {
+ return reconcileChildrenIterator(returnFiber, currentFirstChild, newChild, expirationTime);
+ }
+
+ if (isObject) {
+ throwOnInvalidObjectType(returnFiber, newChild);
+ }
+
+ {
+ if (typeof newChild === 'function') {
+ warnOnFunctionType();
+ }
+ }
+
+ if (typeof newChild === 'undefined' && !isUnkeyedTopLevelFragment) {
+ // If the new child is undefined, and the return fiber is a composite
+ // component, throw an error. If Fiber return types are disabled,
+ // we already threw above.
+ switch (returnFiber.tag) {
+ case ClassComponent:
+ {
+ {
+ var instance = returnFiber.stateNode;
+
+ if (instance.render._isMockFunction) {
+ // We allow auto-mocks to proceed as if they're returning null.
+ break;
+ }
+ }
+ }
+ // Intentionally fall through to the next case, which handles both
+ // functions and classes
+ // eslint-disable-next-lined no-fallthrough
+
+ case FunctionComponent:
+ {
+ var Component = returnFiber.type;
+
+ {
+ {
+ throw Error( (Component.displayName || Component.name || 'Component') + "(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null." );
+ }
+ }
+ }
+ }
+ } // Remaining cases are all treated as empty.
+
+
+ return deleteRemainingChildren(returnFiber, currentFirstChild);
+ }
+
+ return reconcileChildFibers;
+ }
+
+ var reconcileChildFibers = ChildReconciler(true);
+ var mountChildFibers = ChildReconciler(false);
+ function cloneChildFibers(current, workInProgress) {
+ if (!(current === null || workInProgress.child === current.child)) {
+ {
+ throw Error( "Resuming work not yet implemented." );
+ }
+ }
+
+ if (workInProgress.child === null) {
+ return;
+ }
+
+ var currentChild = workInProgress.child;
+ var newChild = createWorkInProgress(currentChild, currentChild.pendingProps);
+ workInProgress.child = newChild;
+ newChild.return = workInProgress;
+
+ while (currentChild.sibling !== null) {
+ currentChild = currentChild.sibling;
+ newChild = newChild.sibling = createWorkInProgress(currentChild, currentChild.pendingProps);
+ newChild.return = workInProgress;
+ }
+
+ newChild.sibling = null;
+ } // Reset a workInProgress child set to prepare it for a second pass.
+
+ function resetChildFibers(workInProgress, renderExpirationTime) {
+ var child = workInProgress.child;
+
+ while (child !== null) {
+ resetWorkInProgress(child, renderExpirationTime);
+ child = child.sibling;
+ }
+ }
+
+ var NO_CONTEXT = {};
+ var contextStackCursor$1 = createCursor(NO_CONTEXT);
+ var contextFiberStackCursor = createCursor(NO_CONTEXT);
+ var rootInstanceStackCursor = createCursor(NO_CONTEXT);
+
+ function requiredContext(c) {
+ if (!(c !== NO_CONTEXT)) {
+ {
+ throw Error( "Expected host context to exist. This error is likely caused by a bug in React. Please file an issue." );
+ }
+ }
+
+ return c;
+ }
+
+ function getRootHostContainer() {
+ var rootInstance = requiredContext(rootInstanceStackCursor.current);
+ return rootInstance;
+ }
+
+ function pushHostContainer(fiber, nextRootInstance) {
+ // Push current root instance onto the stack;
+ // This allows us to reset root when portals are popped.
+ push(rootInstanceStackCursor, nextRootInstance, fiber); // Track the context and the Fiber that provided it.
+ // This enables us to pop only Fibers that provide unique contexts.
+
+ push(contextFiberStackCursor, fiber, fiber); // Finally, we need to push the host context to the stack.
+ // However, we can't just call getRootHostContext() and push it because
+ // we'd have a different number of entries on the stack depending on
+ // whether getRootHostContext() throws somewhere in renderer code or not.
+ // So we push an empty value first. This lets us safely unwind on errors.
+
+ push(contextStackCursor$1, NO_CONTEXT, fiber);
+ var nextRootContext = getRootHostContext(nextRootInstance); // Now that we know this function doesn't throw, replace it.
+
+ pop(contextStackCursor$1, fiber);
+ push(contextStackCursor$1, nextRootContext, fiber);
+ }
+
+ function popHostContainer(fiber) {
+ pop(contextStackCursor$1, fiber);
+ pop(contextFiberStackCursor, fiber);
+ pop(rootInstanceStackCursor, fiber);
+ }
+
+ function getHostContext() {
+ var context = requiredContext(contextStackCursor$1.current);
+ return context;
+ }
+
+ function pushHostContext(fiber) {
+ var rootInstance = requiredContext(rootInstanceStackCursor.current);
+ var context = requiredContext(contextStackCursor$1.current);
+ var nextContext = getChildHostContext(context, fiber.type); // Don't push this Fiber's context unless it's unique.
+
+ if (context === nextContext) {
+ return;
+ } // Track the context and the Fiber that provided it.
+ // This enables us to pop only Fibers that provide unique contexts.
+
+
+ push(contextFiberStackCursor, fiber, fiber);
+ push(contextStackCursor$1, nextContext, fiber);
+ }
+
+ function popHostContext(fiber) {
+ // Do not pop unless this Fiber provided the current context.
+ // pushHostContext() only pushes Fibers that provide unique contexts.
+ if (contextFiberStackCursor.current !== fiber) {
+ return;
+ }
+
+ pop(contextStackCursor$1, fiber);
+ pop(contextFiberStackCursor, fiber);
+ }
+
+ var DefaultSuspenseContext = 0; // The Suspense Context is split into two parts. The lower bits is
+ // inherited deeply down the subtree. The upper bits only affect
+ // this immediate suspense boundary and gets reset each new
+ // boundary or suspense list.
+
+ var SubtreeSuspenseContextMask = 1; // Subtree Flags:
+ // InvisibleParentSuspenseContext indicates that one of our parent Suspense
+ // boundaries is not currently showing visible main content.
+ // Either because it is already showing a fallback or is not mounted at all.
+ // We can use this to determine if it is desirable to trigger a fallback at
+ // the parent. If not, then we might need to trigger undesirable boundaries
+ // and/or suspend the commit to avoid hiding the parent content.
+
+ var InvisibleParentSuspenseContext = 1; // Shallow Flags:
+ // ForceSuspenseFallback can be used by SuspenseList to force newly added
+ // items into their fallback state during one of the render passes.
+
+ var ForceSuspenseFallback = 2;
+ var suspenseStackCursor = createCursor(DefaultSuspenseContext);
+ function hasSuspenseContext(parentContext, flag) {
+ return (parentContext & flag) !== 0;
+ }
+ function setDefaultShallowSuspenseContext(parentContext) {
+ return parentContext & SubtreeSuspenseContextMask;
+ }
+ function setShallowSuspenseContext(parentContext, shallowContext) {
+ return parentContext & SubtreeSuspenseContextMask | shallowContext;
+ }
+ function addSubtreeSuspenseContext(parentContext, subtreeContext) {
+ return parentContext | subtreeContext;
+ }
+ function pushSuspenseContext(fiber, newContext) {
+ push(suspenseStackCursor, newContext, fiber);
+ }
+ function popSuspenseContext(fiber) {
+ pop(suspenseStackCursor, fiber);
+ }
+
+ function shouldCaptureSuspense(workInProgress, hasInvisibleParent) {
+ // If it was the primary children that just suspended, capture and render the
+ // fallback. Otherwise, don't capture and bubble to the next boundary.
+ var nextState = workInProgress.memoizedState;
+
+ if (nextState !== null) {
+ if (nextState.dehydrated !== null) {
+ // A dehydrated boundary always captures.
+ return true;
+ }
+
+ return false;
+ }
+
+ var props = workInProgress.memoizedProps; // In order to capture, the Suspense component must have a fallback prop.
+
+ if (props.fallback === undefined) {
+ return false;
+ } // Regular boundaries always capture.
+
+
+ if (props.unstable_avoidThisFallback !== true) {
+ return true;
+ } // If it's a boundary we should avoid, then we prefer to bubble up to the
+ // parent boundary if it is currently invisible.
+
+
+ if (hasInvisibleParent) {
+ return false;
+ } // If the parent is not able to handle it, we must handle it.
+
+
+ return true;
+ }
+ function findFirstSuspended(row) {
+ var node = row;
+
+ while (node !== null) {
+ if (node.tag === SuspenseComponent) {
+ var state = node.memoizedState;
+
+ if (state !== null) {
+ var dehydrated = state.dehydrated;
+
+ if (dehydrated === null || isSuspenseInstancePending(dehydrated) || isSuspenseInstanceFallback(dehydrated)) {
+ return node;
+ }
+ }
+ } else if (node.tag === SuspenseListComponent && // revealOrder undefined can't be trusted because it don't
+ // keep track of whether it suspended or not.
+ node.memoizedProps.revealOrder !== undefined) {
+ var didSuspend = (node.effectTag & DidCapture) !== NoEffect;
+
+ if (didSuspend) {
+ return node;
+ }
+ } else if (node.child !== null) {
+ node.child.return = node;
+ node = node.child;
+ continue;
+ }
+
+ if (node === row) {
+ return null;
+ }
+
+ while (node.sibling === null) {
+ if (node.return === null || node.return === row) {
+ return null;
+ }
+
+ node = node.return;
+ }
+
+ node.sibling.return = node.return;
+ node = node.sibling;
+ }
+
+ return null;
+ }
+
+ function createDeprecatedResponderListener(responder, props) {
+ var eventResponderListener = {
+ responder: responder,
+ props: props
+ };
+
+ {
+ Object.freeze(eventResponderListener);
+ }
+
+ return eventResponderListener;
+ }
+
+ var HasEffect =
+ /* */
+ 1; // Represents the phase in which the effect (not the clean-up) fires.
+
+ var Layout =
+ /* */
+ 2;
+ var Passive$1 =
+ /* */
+ 4;
+
+ var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher,
+ ReactCurrentBatchConfig$1 = ReactSharedInternals.ReactCurrentBatchConfig;
+ var didWarnAboutMismatchedHooksForComponent;
+
+ {
+ didWarnAboutMismatchedHooksForComponent = new Set();
+ }
+
+ // These are set right before calling the component.
+ var renderExpirationTime = NoWork; // The work-in-progress fiber. I've named it differently to distinguish it from
+ // the work-in-progress hook.
+
+ var currentlyRenderingFiber$1 = null; // Hooks are stored as a linked list on the fiber's memoizedState field. The
+ // current hook list is the list that belongs to the current fiber. The
+ // work-in-progress hook list is a new list that will be added to the
+ // work-in-progress fiber.
+
+ var currentHook = null;
+ var workInProgressHook = null; // Whether an update was scheduled at any point during the render phase. This
+ // does not get reset if we do another render pass; only when we're completely
+ // finished evaluating this component. This is an optimization so we know
+ // whether we need to clear render phase updates after a throw.
+
+ var didScheduleRenderPhaseUpdate = false;
+ var RE_RENDER_LIMIT = 25; // In DEV, this is the name of the currently executing primitive hook
+
+ var currentHookNameInDev = null; // In DEV, this list ensures that hooks are called in the same order between renders.
+ // The list stores the order of hooks used during the initial render (mount).
+ // Subsequent renders (updates) reference this list.
+
+ var hookTypesDev = null;
+ var hookTypesUpdateIndexDev = -1; // In DEV, this tracks whether currently rendering component needs to ignore
+ // the dependencies for Hooks that need them (e.g. useEffect or useMemo).
+ // When true, such Hooks will always be "remounted". Only used during hot reload.
+
+ var ignorePreviousDependencies = false;
+
+ function mountHookTypesDev() {
+ {
+ var hookName = currentHookNameInDev;
+
+ if (hookTypesDev === null) {
+ hookTypesDev = [hookName];
+ } else {
+ hookTypesDev.push(hookName);
+ }
+ }
+ }
+
+ function updateHookTypesDev() {
+ {
+ var hookName = currentHookNameInDev;
+
+ if (hookTypesDev !== null) {
+ hookTypesUpdateIndexDev++;
+
+ if (hookTypesDev[hookTypesUpdateIndexDev] !== hookName) {
+ warnOnHookMismatchInDev(hookName);
+ }
+ }
+ }
+ }
+
+ function checkDepsAreArrayDev(deps) {
+ {
+ if (deps !== undefined && deps !== null && !Array.isArray(deps)) {
+ // Verify deps, but only on mount to avoid extra checks.
+ // It's unlikely their type would change as usually you define them inline.
+ error('%s received a final argument that is not an array (instead, received `%s`). When ' + 'specified, the final argument must be an array.', currentHookNameInDev, typeof deps);
+ }
+ }
+ }
+
+ function warnOnHookMismatchInDev(currentHookName) {
+ {
+ var componentName = getComponentName(currentlyRenderingFiber$1.type);
+
+ if (!didWarnAboutMismatchedHooksForComponent.has(componentName)) {
+ didWarnAboutMismatchedHooksForComponent.add(componentName);
+
+ if (hookTypesDev !== null) {
+ var table = '';
+ var secondColumnStart = 30;
+
+ for (var i = 0; i <= hookTypesUpdateIndexDev; i++) {
+ var oldHookName = hookTypesDev[i];
+ var newHookName = i === hookTypesUpdateIndexDev ? currentHookName : oldHookName;
+ var row = i + 1 + ". " + oldHookName; // Extra space so second column lines up
+ // lol @ IE not supporting String#repeat
+
+ while (row.length < secondColumnStart) {
+ row += ' ';
+ }
+
+ row += newHookName + '\n';
+ table += row;
+ }
+
+ error('React has detected a change in the order of Hooks called by %s. ' + 'This will lead to bugs and errors if not fixed. ' + 'For more information, read the Rules of Hooks: https://fb.me/rules-of-hooks\n\n' + ' Previous render Next render\n' + ' ------------------------------------------------------\n' + '%s' + ' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n', componentName, table);
+ }
+ }
+ }
+ }
+
+ function throwInvalidHookError() {
+ {
+ {
+ throw Error( "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem." );
+ }
+ }
+ }
+
+ function areHookInputsEqual(nextDeps, prevDeps) {
+ {
+ if (ignorePreviousDependencies) {
+ // Only true when this component is being hot reloaded.
+ return false;
+ }
+ }
+
+ if (prevDeps === null) {
+ {
+ error('%s received a final argument during this render, but not during ' + 'the previous render. Even though the final argument is optional, ' + 'its type cannot change between renders.', currentHookNameInDev);
+ }
+
+ return false;
+ }
+
+ {
+ // Don't bother comparing lengths in prod because these arrays should be
+ // passed inline.
+ if (nextDeps.length !== prevDeps.length) {
+ error('The final argument passed to %s changed size between renders. The ' + 'order and size of this array must remain constant.\n\n' + 'Previous: %s\n' + 'Incoming: %s', currentHookNameInDev, "[" + prevDeps.join(', ') + "]", "[" + nextDeps.join(', ') + "]");
+ }
+ }
+
+ for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) {
+ if (objectIs(nextDeps[i], prevDeps[i])) {
+ continue;
+ }
+
+ return false;
+ }
+
+ return true;
+ }
+
+ function renderWithHooks(current, workInProgress, Component, props, secondArg, nextRenderExpirationTime) {
+ renderExpirationTime = nextRenderExpirationTime;
+ currentlyRenderingFiber$1 = workInProgress;
+
+ {
+ hookTypesDev = current !== null ? current._debugHookTypes : null;
+ hookTypesUpdateIndexDev = -1; // Used for hot reloading:
+
+ ignorePreviousDependencies = current !== null && current.type !== workInProgress.type;
+ }
+
+ workInProgress.memoizedState = null;
+ workInProgress.updateQueue = null;
+ workInProgress.expirationTime = NoWork; // The following should have already been reset
+ // currentHook = null;
+ // workInProgressHook = null;
+ // didScheduleRenderPhaseUpdate = false;
+ // TODO Warn if no hooks are used at all during mount, then some are used during update.
+ // Currently we will identify the update render as a mount because memoizedState === null.
+ // This is tricky because it's valid for certain types of components (e.g. React.lazy)
+ // Using memoizedState to differentiate between mount/update only works if at least one stateful hook is used.
+ // Non-stateful hooks (e.g. context) don't get added to memoizedState,
+ // so memoizedState would be null during updates and mounts.
+
+ {
+ if (current !== null && current.memoizedState !== null) {
+ ReactCurrentDispatcher.current = HooksDispatcherOnUpdateInDEV;
+ } else if (hookTypesDev !== null) {
+ // This dispatcher handles an edge case where a component is updating,
+ // but no stateful hooks have been used.
+ // We want to match the production code behavior (which will use HooksDispatcherOnMount),
+ // but with the extra DEV validation to ensure hooks ordering hasn't changed.
+ // This dispatcher does that.
+ ReactCurrentDispatcher.current = HooksDispatcherOnMountWithHookTypesInDEV;
+ } else {
+ ReactCurrentDispatcher.current = HooksDispatcherOnMountInDEV;
+ }
+ }
+
+ var children = Component(props, secondArg); // Check if there was a render phase update
+
+ if (workInProgress.expirationTime === renderExpirationTime) {
+ // Keep rendering in a loop for as long as render phase updates continue to
+ // be scheduled. Use a counter to prevent infinite loops.
+ var numberOfReRenders = 0;
+
+ do {
+ workInProgress.expirationTime = NoWork;
+
+ if (!(numberOfReRenders < RE_RENDER_LIMIT)) {
+ {
+ throw Error( "Too many re-renders. React limits the number of renders to prevent an infinite loop." );
+ }
+ }
+
+ numberOfReRenders += 1;
+
+ {
+ // Even when hot reloading, allow dependencies to stabilize
+ // after first render to prevent infinite render phase updates.
+ ignorePreviousDependencies = false;
+ } // Start over from the beginning of the list
+
+
+ currentHook = null;
+ workInProgressHook = null;
+ workInProgress.updateQueue = null;
+
+ {
+ // Also validate hook order for cascading updates.
+ hookTypesUpdateIndexDev = -1;
+ }
+
+ ReactCurrentDispatcher.current = HooksDispatcherOnRerenderInDEV ;
+ children = Component(props, secondArg);
+ } while (workInProgress.expirationTime === renderExpirationTime);
+ } // We can assume the previous dispatcher is always this one, since we set it
+ // at the beginning of the render phase and there's no re-entrancy.
+
+
+ ReactCurrentDispatcher.current = ContextOnlyDispatcher;
+
+ {
+ workInProgress._debugHookTypes = hookTypesDev;
+ } // This check uses currentHook so that it works the same in DEV and prod bundles.
+ // hookTypesDev could catch more cases (e.g. context) but only in DEV bundles.
+
+
+ var didRenderTooFewHooks = currentHook !== null && currentHook.next !== null;
+ renderExpirationTime = NoWork;
+ currentlyRenderingFiber$1 = null;
+ currentHook = null;
+ workInProgressHook = null;
+
+ {
+ currentHookNameInDev = null;
+ hookTypesDev = null;
+ hookTypesUpdateIndexDev = -1;
+ }
+
+ didScheduleRenderPhaseUpdate = false;
+
+ if (!!didRenderTooFewHooks) {
+ {
+ throw Error( "Rendered fewer hooks than expected. This may be caused by an accidental early return statement." );
+ }
+ }
+
+ return children;
+ }
+ function bailoutHooks(current, workInProgress, expirationTime) {
+ workInProgress.updateQueue = current.updateQueue;
+ workInProgress.effectTag &= ~(Passive | Update);
+
+ if (current.expirationTime <= expirationTime) {
+ current.expirationTime = NoWork;
+ }
+ }
+ function resetHooksAfterThrow() {
+ // We can assume the previous dispatcher is always this one, since we set it
+ // at the beginning of the render phase and there's no re-entrancy.
+ ReactCurrentDispatcher.current = ContextOnlyDispatcher;
+
+ if (didScheduleRenderPhaseUpdate) {
+ // There were render phase updates. These are only valid for this render
+ // phase, which we are now aborting. Remove the updates from the queues so
+ // they do not persist to the next render. Do not remove updates from hooks
+ // that weren't processed.
+ //
+ // Only reset the updates from the queue if it has a clone. If it does
+ // not have a clone, that means it wasn't processed, and the updates were
+ // scheduled before we entered the render phase.
+ var hook = currentlyRenderingFiber$1.memoizedState;
+
+ while (hook !== null) {
+ var queue = hook.queue;
+
+ if (queue !== null) {
+ queue.pending = null;
+ }
+
+ hook = hook.next;
+ }
+ }
+
+ renderExpirationTime = NoWork;
+ currentlyRenderingFiber$1 = null;
+ currentHook = null;
+ workInProgressHook = null;
+
+ {
+ hookTypesDev = null;
+ hookTypesUpdateIndexDev = -1;
+ currentHookNameInDev = null;
+ }
+
+ didScheduleRenderPhaseUpdate = false;
+ }
+
+ function mountWorkInProgressHook() {
+ var hook = {
+ memoizedState: null,
+ baseState: null,
+ baseQueue: null,
+ queue: null,
+ next: null
+ };
+
+ if (workInProgressHook === null) {
+ // This is the first hook in the list
+ currentlyRenderingFiber$1.memoizedState = workInProgressHook = hook;
+ } else {
+ // Append to the end of the list
+ workInProgressHook = workInProgressHook.next = hook;
+ }
+
+ return workInProgressHook;
+ }
+
+ function updateWorkInProgressHook() {
+ // This function is used both for updates and for re-renders triggered by a
+ // render phase update. It assumes there is either a current hook we can
+ // clone, or a work-in-progress hook from a previous render pass that we can
+ // use as a base. When we reach the end of the base list, we must switch to
+ // the dispatcher used for mounts.
+ var nextCurrentHook;
+
+ if (currentHook === null) {
+ var current = currentlyRenderingFiber$1.alternate;
+
+ if (current !== null) {
+ nextCurrentHook = current.memoizedState;
+ } else {
+ nextCurrentHook = null;
+ }
+ } else {
+ nextCurrentHook = currentHook.next;
+ }
+
+ var nextWorkInProgressHook;
+
+ if (workInProgressHook === null) {
+ nextWorkInProgressHook = currentlyRenderingFiber$1.memoizedState;
+ } else {
+ nextWorkInProgressHook = workInProgressHook.next;
+ }
+
+ if (nextWorkInProgressHook !== null) {
+ // There's already a work-in-progress. Reuse it.
+ workInProgressHook = nextWorkInProgressHook;
+ nextWorkInProgressHook = workInProgressHook.next;
+ currentHook = nextCurrentHook;
+ } else {
+ // Clone from the current hook.
+ if (!(nextCurrentHook !== null)) {
+ {
+ throw Error( "Rendered more hooks than during the previous render." );
+ }
+ }
+
+ currentHook = nextCurrentHook;
+ var newHook = {
+ memoizedState: currentHook.memoizedState,
+ baseState: currentHook.baseState,
+ baseQueue: currentHook.baseQueue,
+ queue: currentHook.queue,
+ next: null
+ };
+
+ if (workInProgressHook === null) {
+ // This is the first hook in the list.
+ currentlyRenderingFiber$1.memoizedState = workInProgressHook = newHook;
+ } else {
+ // Append to the end of the list.
+ workInProgressHook = workInProgressHook.next = newHook;
+ }
+ }
+
+ return workInProgressHook;
+ }
+
+ function createFunctionComponentUpdateQueue() {
+ return {
+ lastEffect: null
+ };
+ }
+
+ function basicStateReducer(state, action) {
+ // $FlowFixMe: Flow doesn't like mixed types
+ return typeof action === 'function' ? action(state) : action;
+ }
+
+ function mountReducer(reducer, initialArg, init) {
+ var hook = mountWorkInProgressHook();
+ var initialState;
+
+ if (init !== undefined) {
+ initialState = init(initialArg);
+ } else {
+ initialState = initialArg;
+ }
+
+ hook.memoizedState = hook.baseState = initialState;
+ var queue = hook.queue = {
+ pending: null,
+ dispatch: null,
+ lastRenderedReducer: reducer,
+ lastRenderedState: initialState
+ };
+ var dispatch = queue.dispatch = dispatchAction.bind(null, currentlyRenderingFiber$1, queue);
+ return [hook.memoizedState, dispatch];
+ }
+
+ function updateReducer(reducer, initialArg, init) {
+ var hook = updateWorkInProgressHook();
+ var queue = hook.queue;
+
+ if (!(queue !== null)) {
+ {
+ throw Error( "Should have a queue. This is likely a bug in React. Please file an issue." );
+ }
+ }
+
+ queue.lastRenderedReducer = reducer;
+ var current = currentHook; // The last rebase update that is NOT part of the base state.
+
+ var baseQueue = current.baseQueue; // The last pending update that hasn't been processed yet.
+
+ var pendingQueue = queue.pending;
+
+ if (pendingQueue !== null) {
+ // We have new updates that haven't been processed yet.
+ // We'll add them to the base queue.
+ if (baseQueue !== null) {
+ // Merge the pending queue and the base queue.
+ var baseFirst = baseQueue.next;
+ var pendingFirst = pendingQueue.next;
+ baseQueue.next = pendingFirst;
+ pendingQueue.next = baseFirst;
+ }
+
+ current.baseQueue = baseQueue = pendingQueue;
+ queue.pending = null;
+ }
+
+ if (baseQueue !== null) {
+ // We have a queue to process.
+ var first = baseQueue.next;
+ var newState = current.baseState;
+ var newBaseState = null;
+ var newBaseQueueFirst = null;
+ var newBaseQueueLast = null;
+ var update = first;
+
+ do {
+ var updateExpirationTime = update.expirationTime;
+
+ if (updateExpirationTime < renderExpirationTime) {
+ // Priority is insufficient. Skip this update. If this is the first
+ // skipped update, the previous update/state is the new base
+ // update/state.
+ var clone = {
+ expirationTime: update.expirationTime,
+ suspenseConfig: update.suspenseConfig,
+ action: update.action,
+ eagerReducer: update.eagerReducer,
+ eagerState: update.eagerState,
+ next: null
+ };
+
+ if (newBaseQueueLast === null) {
+ newBaseQueueFirst = newBaseQueueLast = clone;
+ newBaseState = newState;
+ } else {
+ newBaseQueueLast = newBaseQueueLast.next = clone;
+ } // Update the remaining priority in the queue.
+
+
+ if (updateExpirationTime > currentlyRenderingFiber$1.expirationTime) {
+ currentlyRenderingFiber$1.expirationTime = updateExpirationTime;
+ markUnprocessedUpdateTime(updateExpirationTime);
+ }
+ } else {
+ // This update does have sufficient priority.
+ if (newBaseQueueLast !== null) {
+ var _clone = {
+ expirationTime: Sync,
+ // This update is going to be committed so we never want uncommit it.
+ suspenseConfig: update.suspenseConfig,
+ action: update.action,
+ eagerReducer: update.eagerReducer,
+ eagerState: update.eagerState,
+ next: null
+ };
+ newBaseQueueLast = newBaseQueueLast.next = _clone;
+ } // Mark the event time of this update as relevant to this render pass.
+ // TODO: This should ideally use the true event time of this update rather than
+ // its priority which is a derived and not reverseable value.
+ // TODO: We should skip this update if it was already committed but currently
+ // we have no way of detecting the difference between a committed and suspended
+ // update here.
+
+
+ markRenderEventTimeAndConfig(updateExpirationTime, update.suspenseConfig); // Process this update.
+
+ if (update.eagerReducer === reducer) {
+ // If this update was processed eagerly, and its reducer matches the
+ // current reducer, we can use the eagerly computed state.
+ newState = update.eagerState;
+ } else {
+ var action = update.action;
+ newState = reducer(newState, action);
+ }
+ }
+
+ update = update.next;
+ } while (update !== null && update !== first);
+
+ if (newBaseQueueLast === null) {
+ newBaseState = newState;
+ } else {
+ newBaseQueueLast.next = newBaseQueueFirst;
+ } // Mark that the fiber performed work, but only if the new state is
+ // different from the current state.
+
+
+ if (!objectIs(newState, hook.memoizedState)) {
+ markWorkInProgressReceivedUpdate();
+ }
+
+ hook.memoizedState = newState;
+ hook.baseState = newBaseState;
+ hook.baseQueue = newBaseQueueLast;
+ queue.lastRenderedState = newState;
+ }
+
+ var dispatch = queue.dispatch;
+ return [hook.memoizedState, dispatch];
+ }
+
+ function rerenderReducer(reducer, initialArg, init) {
+ var hook = updateWorkInProgressHook();
+ var queue = hook.queue;
+
+ if (!(queue !== null)) {
+ {
+ throw Error( "Should have a queue. This is likely a bug in React. Please file an issue." );
+ }
+ }
+
+ queue.lastRenderedReducer = reducer; // This is a re-render. Apply the new render phase updates to the previous
+ // work-in-progress hook.
+
+ var dispatch = queue.dispatch;
+ var lastRenderPhaseUpdate = queue.pending;
+ var newState = hook.memoizedState;
+
+ if (lastRenderPhaseUpdate !== null) {
+ // The queue doesn't persist past this render pass.
+ queue.pending = null;
+ var firstRenderPhaseUpdate = lastRenderPhaseUpdate.next;
+ var update = firstRenderPhaseUpdate;
+
+ do {
+ // Process this render phase update. We don't have to check the
+ // priority because it will always be the same as the current
+ // render's.
+ var action = update.action;
+ newState = reducer(newState, action);
+ update = update.next;
+ } while (update !== firstRenderPhaseUpdate); // Mark that the fiber performed work, but only if the new state is
+ // different from the current state.
+
+
+ if (!objectIs(newState, hook.memoizedState)) {
+ markWorkInProgressReceivedUpdate();
+ }
+
+ hook.memoizedState = newState; // Don't persist the state accumulated from the render phase updates to
+ // the base state unless the queue is empty.
+ // TODO: Not sure if this is the desired semantics, but it's what we
+ // do for gDSFP. I can't remember why.
+
+ if (hook.baseQueue === null) {
+ hook.baseState = newState;
+ }
+
+ queue.lastRenderedState = newState;
+ }
+
+ return [newState, dispatch];
+ }
+
+ function mountState(initialState) {
+ var hook = mountWorkInProgressHook();
+
+ if (typeof initialState === 'function') {
+ // $FlowFixMe: Flow doesn't like mixed types
+ initialState = initialState();
+ }
+
+ hook.memoizedState = hook.baseState = initialState;
+ var queue = hook.queue = {
+ pending: null,
+ dispatch: null,
+ lastRenderedReducer: basicStateReducer,
+ lastRenderedState: initialState
+ };
+ var dispatch = queue.dispatch = dispatchAction.bind(null, currentlyRenderingFiber$1, queue);
+ return [hook.memoizedState, dispatch];
+ }
+
+ function updateState(initialState) {
+ return updateReducer(basicStateReducer);
+ }
+
+ function rerenderState(initialState) {
+ return rerenderReducer(basicStateReducer);
+ }
+
+ function pushEffect(tag, create, destroy, deps) {
+ var effect = {
+ tag: tag,
+ create: create,
+ destroy: destroy,
+ deps: deps,
+ // Circular
+ next: null
+ };
+ var componentUpdateQueue = currentlyRenderingFiber$1.updateQueue;
+
+ if (componentUpdateQueue === null) {
+ componentUpdateQueue = createFunctionComponentUpdateQueue();
+ currentlyRenderingFiber$1.updateQueue = componentUpdateQueue;
+ componentUpdateQueue.lastEffect = effect.next = effect;
+ } else {
+ var lastEffect = componentUpdateQueue.lastEffect;
+
+ if (lastEffect === null) {
+ componentUpdateQueue.lastEffect = effect.next = effect;
+ } else {
+ var firstEffect = lastEffect.next;
+ lastEffect.next = effect;
+ effect.next = firstEffect;
+ componentUpdateQueue.lastEffect = effect;
+ }
+ }
+
+ return effect;
+ }
+
+ function mountRef(initialValue) {
+ var hook = mountWorkInProgressHook();
+ var ref = {
+ current: initialValue
+ };
+
+ {
+ Object.seal(ref);
+ }
+
+ hook.memoizedState = ref;
+ return ref;
+ }
+
+ function updateRef(initialValue) {
+ var hook = updateWorkInProgressHook();
+ return hook.memoizedState;
+ }
+
+ function mountEffectImpl(fiberEffectTag, hookEffectTag, create, deps) {
+ var hook = mountWorkInProgressHook();
+ var nextDeps = deps === undefined ? null : deps;
+ currentlyRenderingFiber$1.effectTag |= fiberEffectTag;
+ hook.memoizedState = pushEffect(HasEffect | hookEffectTag, create, undefined, nextDeps);
+ }
+
+ function updateEffectImpl(fiberEffectTag, hookEffectTag, create, deps) {
+ var hook = updateWorkInProgressHook();
+ var nextDeps = deps === undefined ? null : deps;
+ var destroy = undefined;
+
+ if (currentHook !== null) {
+ var prevEffect = currentHook.memoizedState;
+ destroy = prevEffect.destroy;
+
+ if (nextDeps !== null) {
+ var prevDeps = prevEffect.deps;
+
+ if (areHookInputsEqual(nextDeps, prevDeps)) {
+ pushEffect(hookEffectTag, create, destroy, nextDeps);
+ return;
+ }
+ }
+ }
+
+ currentlyRenderingFiber$1.effectTag |= fiberEffectTag;
+ hook.memoizedState = pushEffect(HasEffect | hookEffectTag, create, destroy, nextDeps);
+ }
+
+ function mountEffect(create, deps) {
+ {
+ // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests
+ if ('undefined' !== typeof jest) {
+ warnIfNotCurrentlyActingEffectsInDEV(currentlyRenderingFiber$1);
+ }
+ }
+
+ return mountEffectImpl(Update | Passive, Passive$1, create, deps);
+ }
+
+ function updateEffect(create, deps) {
+ {
+ // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests
+ if ('undefined' !== typeof jest) {
+ warnIfNotCurrentlyActingEffectsInDEV(currentlyRenderingFiber$1);
+ }
+ }
+
+ return updateEffectImpl(Update | Passive, Passive$1, create, deps);
+ }
+
+ function mountLayoutEffect(create, deps) {
+ return mountEffectImpl(Update, Layout, create, deps);
+ }
+
+ function updateLayoutEffect(create, deps) {
+ return updateEffectImpl(Update, Layout, create, deps);
+ }
+
+ function imperativeHandleEffect(create, ref) {
+ if (typeof ref === 'function') {
+ var refCallback = ref;
+
+ var _inst = create();
+
+ refCallback(_inst);
+ return function () {
+ refCallback(null);
+ };
+ } else if (ref !== null && ref !== undefined) {
+ var refObject = ref;
+
+ {
+ if (!refObject.hasOwnProperty('current')) {
+ error('Expected useImperativeHandle() first argument to either be a ' + 'ref callback or React.createRef() object. Instead received: %s.', 'an object with keys {' + Object.keys(refObject).join(', ') + '}');
+ }
+ }
+
+ var _inst2 = create();
+
+ refObject.current = _inst2;
+ return function () {
+ refObject.current = null;
+ };
+ }
+ }
+
+ function mountImperativeHandle(ref, create, deps) {
+ {
+ if (typeof create !== 'function') {
+ error('Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: %s.', create !== null ? typeof create : 'null');
+ }
+ } // TODO: If deps are provided, should we skip comparing the ref itself?
+
+
+ var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null;
+ return mountEffectImpl(Update, Layout, imperativeHandleEffect.bind(null, create, ref), effectDeps);
+ }
+
+ function updateImperativeHandle(ref, create, deps) {
+ {
+ if (typeof create !== 'function') {
+ error('Expected useImperativeHandle() second argument to be a function ' + 'that creates a handle. Instead received: %s.', create !== null ? typeof create : 'null');
+ }
+ } // TODO: If deps are provided, should we skip comparing the ref itself?
+
+
+ var effectDeps = deps !== null && deps !== undefined ? deps.concat([ref]) : null;
+ return updateEffectImpl(Update, Layout, imperativeHandleEffect.bind(null, create, ref), effectDeps);
+ }
+
+ function mountDebugValue(value, formatterFn) {// This hook is normally a no-op.
+ // The react-debug-hooks package injects its own implementation
+ // so that e.g. DevTools can display custom hook values.
+ }
+
+ var updateDebugValue = mountDebugValue;
+
+ function mountCallback(callback, deps) {
+ var hook = mountWorkInProgressHook();
+ var nextDeps = deps === undefined ? null : deps;
+ hook.memoizedState = [callback, nextDeps];
+ return callback;
+ }
+
+ function updateCallback(callback, deps) {
+ var hook = updateWorkInProgressHook();
+ var nextDeps = deps === undefined ? null : deps;
+ var prevState = hook.memoizedState;
+
+ if (prevState !== null) {
+ if (nextDeps !== null) {
+ var prevDeps = prevState[1];
+
+ if (areHookInputsEqual(nextDeps, prevDeps)) {
+ return prevState[0];
+ }
+ }
+ }
+
+ hook.memoizedState = [callback, nextDeps];
+ return callback;
+ }
+
+ function mountMemo(nextCreate, deps) {
+ var hook = mountWorkInProgressHook();
+ var nextDeps = deps === undefined ? null : deps;
+ var nextValue = nextCreate();
+ hook.memoizedState = [nextValue, nextDeps];
+ return nextValue;
+ }
+
+ function updateMemo(nextCreate, deps) {
+ var hook = updateWorkInProgressHook();
+ var nextDeps = deps === undefined ? null : deps;
+ var prevState = hook.memoizedState;
+
+ if (prevState !== null) {
+ // Assume these are defined. If they're not, areHookInputsEqual will warn.
+ if (nextDeps !== null) {
+ var prevDeps = prevState[1];
+
+ if (areHookInputsEqual(nextDeps, prevDeps)) {
+ return prevState[0];
+ }
+ }
+ }
+
+ var nextValue = nextCreate();
+ hook.memoizedState = [nextValue, nextDeps];
+ return nextValue;
+ }
+
+ function mountDeferredValue(value, config) {
+ var _mountState = mountState(value),
+ prevValue = _mountState[0],
+ setValue = _mountState[1];
+
+ mountEffect(function () {
+ var previousConfig = ReactCurrentBatchConfig$1.suspense;
+ ReactCurrentBatchConfig$1.suspense = config === undefined ? null : config;
+
+ try {
+ setValue(value);
+ } finally {
+ ReactCurrentBatchConfig$1.suspense = previousConfig;
+ }
+ }, [value, config]);
+ return prevValue;
+ }
+
+ function updateDeferredValue(value, config) {
+ var _updateState = updateState(),
+ prevValue = _updateState[0],
+ setValue = _updateState[1];
+
+ updateEffect(function () {
+ var previousConfig = ReactCurrentBatchConfig$1.suspense;
+ ReactCurrentBatchConfig$1.suspense = config === undefined ? null : config;
+
+ try {
+ setValue(value);
+ } finally {
+ ReactCurrentBatchConfig$1.suspense = previousConfig;
+ }
+ }, [value, config]);
+ return prevValue;
+ }
+
+ function rerenderDeferredValue(value, config) {
+ var _rerenderState = rerenderState(),
+ prevValue = _rerenderState[0],
+ setValue = _rerenderState[1];
+
+ updateEffect(function () {
+ var previousConfig = ReactCurrentBatchConfig$1.suspense;
+ ReactCurrentBatchConfig$1.suspense = config === undefined ? null : config;
+
+ try {
+ setValue(value);
+ } finally {
+ ReactCurrentBatchConfig$1.suspense = previousConfig;
+ }
+ }, [value, config]);
+ return prevValue;
+ }
+
+ function startTransition(setPending, config, callback) {
+ var priorityLevel = getCurrentPriorityLevel();
+ runWithPriority$1(priorityLevel < UserBlockingPriority$1 ? UserBlockingPriority$1 : priorityLevel, function () {
+ setPending(true);
+ });
+ runWithPriority$1(priorityLevel > NormalPriority ? NormalPriority : priorityLevel, function () {
+ var previousConfig = ReactCurrentBatchConfig$1.suspense;
+ ReactCurrentBatchConfig$1.suspense = config === undefined ? null : config;
+
+ try {
+ setPending(false);
+ callback();
+ } finally {
+ ReactCurrentBatchConfig$1.suspense = previousConfig;
+ }
+ });
+ }
+
+ function mountTransition(config) {
+ var _mountState2 = mountState(false),
+ isPending = _mountState2[0],
+ setPending = _mountState2[1];
+
+ var start = mountCallback(startTransition.bind(null, setPending, config), [setPending, config]);
+ return [start, isPending];
+ }
+
+ function updateTransition(config) {
+ var _updateState2 = updateState(),
+ isPending = _updateState2[0],
+ setPending = _updateState2[1];
+
+ var start = updateCallback(startTransition.bind(null, setPending, config), [setPending, config]);
+ return [start, isPending];
+ }
+
+ function rerenderTransition(config) {
+ var _rerenderState2 = rerenderState(),
+ isPending = _rerenderState2[0],
+ setPending = _rerenderState2[1];
+
+ var start = updateCallback(startTransition.bind(null, setPending, config), [setPending, config]);
+ return [start, isPending];
+ }
+
+ function dispatchAction(fiber, queue, action) {
+ {
+ if (typeof arguments[3] === 'function') {
+ error("State updates from the useState() and useReducer() Hooks don't support the " + 'second callback argument. To execute a side effect after ' + 'rendering, declare it in the component body with useEffect().');
+ }
+ }
+
+ var currentTime = requestCurrentTimeForUpdate();
+ var suspenseConfig = requestCurrentSuspenseConfig();
+ var expirationTime = computeExpirationForFiber(currentTime, fiber, suspenseConfig);
+ var update = {
+ expirationTime: expirationTime,
+ suspenseConfig: suspenseConfig,
+ action: action,
+ eagerReducer: null,
+ eagerState: null,
+ next: null
+ };
+
+ {
+ update.priority = getCurrentPriorityLevel();
+ } // Append the update to the end of the list.
+
+
+ var pending = queue.pending;
+
+ if (pending === null) {
+ // This is the first update. Create a circular list.
+ update.next = update;
+ } else {
+ update.next = pending.next;
+ pending.next = update;
+ }
+
+ queue.pending = update;
+ var alternate = fiber.alternate;
+
+ if (fiber === currentlyRenderingFiber$1 || alternate !== null && alternate === currentlyRenderingFiber$1) {
+ // This is a render phase update. Stash it in a lazily-created map of
+ // queue -> linked list of updates. After this render pass, we'll restart
+ // and apply the stashed updates on top of the work-in-progress hook.
+ didScheduleRenderPhaseUpdate = true;
+ update.expirationTime = renderExpirationTime;
+ currentlyRenderingFiber$1.expirationTime = renderExpirationTime;
+ } else {
+ if (fiber.expirationTime === NoWork && (alternate === null || alternate.expirationTime === NoWork)) {
+ // The queue is currently empty, which means we can eagerly compute the
+ // next state before entering the render phase. If the new state is the
+ // same as the current state, we may be able to bail out entirely.
+ var lastRenderedReducer = queue.lastRenderedReducer;
+
+ if (lastRenderedReducer !== null) {
+ var prevDispatcher;
+
+ {
+ prevDispatcher = ReactCurrentDispatcher.current;
+ ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
+ }
+
+ try {
+ var currentState = queue.lastRenderedState;
+ var eagerState = lastRenderedReducer(currentState, action); // Stash the eagerly computed state, and the reducer used to compute
+ // it, on the update object. If the reducer hasn't changed by the
+ // time we enter the render phase, then the eager state can be used
+ // without calling the reducer again.
+
+ update.eagerReducer = lastRenderedReducer;
+ update.eagerState = eagerState;
+
+ if (objectIs(eagerState, currentState)) {
+ // Fast path. We can bail out without scheduling React to re-render.
+ // It's still possible that we'll need to rebase this update later,
+ // if the component re-renders for a different reason and by that
+ // time the reducer has changed.
+ return;
+ }
+ } catch (error) {// Suppress the error. It will throw again in the render phase.
+ } finally {
+ {
+ ReactCurrentDispatcher.current = prevDispatcher;
+ }
+ }
+ }
+ }
+
+ {
+ // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests
+ if ('undefined' !== typeof jest) {
+ warnIfNotScopedWithMatchingAct(fiber);
+ warnIfNotCurrentlyActingUpdatesInDev(fiber);
+ }
+ }
+
+ scheduleWork(fiber, expirationTime);
+ }
+ }
+
+ var ContextOnlyDispatcher = {
+ readContext: readContext,
+ useCallback: throwInvalidHookError,
+ useContext: throwInvalidHookError,
+ useEffect: throwInvalidHookError,
+ useImperativeHandle: throwInvalidHookError,
+ useLayoutEffect: throwInvalidHookError,
+ useMemo: throwInvalidHookError,
+ useReducer: throwInvalidHookError,
+ useRef: throwInvalidHookError,
+ useState: throwInvalidHookError,
+ useDebugValue: throwInvalidHookError,
+ useResponder: throwInvalidHookError,
+ useDeferredValue: throwInvalidHookError,
+ useTransition: throwInvalidHookError
+ };
+ var HooksDispatcherOnMountInDEV = null;
+ var HooksDispatcherOnMountWithHookTypesInDEV = null;
+ var HooksDispatcherOnUpdateInDEV = null;
+ var HooksDispatcherOnRerenderInDEV = null;
+ var InvalidNestedHooksDispatcherOnMountInDEV = null;
+ var InvalidNestedHooksDispatcherOnUpdateInDEV = null;
+ var InvalidNestedHooksDispatcherOnRerenderInDEV = null;
+
+ {
+ var warnInvalidContextAccess = function () {
+ error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().');
+ };
+
+ var warnInvalidHookAccess = function () {
+ error('Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. ' + 'You can only call Hooks at the top level of your React function. ' + 'For more information, see ' + 'https://fb.me/rules-of-hooks');
+ };
+
+ HooksDispatcherOnMountInDEV = {
+ readContext: function (context, observedBits) {
+ return readContext(context, observedBits);
+ },
+ useCallback: function (callback, deps) {
+ currentHookNameInDev = 'useCallback';
+ mountHookTypesDev();
+ checkDepsAreArrayDev(deps);
+ return mountCallback(callback, deps);
+ },
+ useContext: function (context, observedBits) {
+ currentHookNameInDev = 'useContext';
+ mountHookTypesDev();
+ return readContext(context, observedBits);
+ },
+ useEffect: function (create, deps) {
+ currentHookNameInDev = 'useEffect';
+ mountHookTypesDev();
+ checkDepsAreArrayDev(deps);
+ return mountEffect(create, deps);
+ },
+ useImperativeHandle: function (ref, create, deps) {
+ currentHookNameInDev = 'useImperativeHandle';
+ mountHookTypesDev();
+ checkDepsAreArrayDev(deps);
+ return mountImperativeHandle(ref, create, deps);
+ },
+ useLayoutEffect: function (create, deps) {
+ currentHookNameInDev = 'useLayoutEffect';
+ mountHookTypesDev();
+ checkDepsAreArrayDev(deps);
+ return mountLayoutEffect(create, deps);
+ },
+ useMemo: function (create, deps) {
+ currentHookNameInDev = 'useMemo';
+ mountHookTypesDev();
+ checkDepsAreArrayDev(deps);
+ var prevDispatcher = ReactCurrentDispatcher.current;
+ ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;
+
+ try {
+ return mountMemo(create, deps);
+ } finally {
+ ReactCurrentDispatcher.current = prevDispatcher;
+ }
+ },
+ useReducer: function (reducer, initialArg, init) {
+ currentHookNameInDev = 'useReducer';
+ mountHookTypesDev();
+ var prevDispatcher = ReactCurrentDispatcher.current;
+ ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;
+
+ try {
+ return mountReducer(reducer, initialArg, init);
+ } finally {
+ ReactCurrentDispatcher.current = prevDispatcher;
+ }
+ },
+ useRef: function (initialValue) {
+ currentHookNameInDev = 'useRef';
+ mountHookTypesDev();
+ return mountRef(initialValue);
+ },
+ useState: function (initialState) {
+ currentHookNameInDev = 'useState';
+ mountHookTypesDev();
+ var prevDispatcher = ReactCurrentDispatcher.current;
+ ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;
+
+ try {
+ return mountState(initialState);
+ } finally {
+ ReactCurrentDispatcher.current = prevDispatcher;
+ }
+ },
+ useDebugValue: function (value, formatterFn) {
+ currentHookNameInDev = 'useDebugValue';
+ mountHookTypesDev();
+ return mountDebugValue();
+ },
+ useResponder: function (responder, props) {
+ currentHookNameInDev = 'useResponder';
+ mountHookTypesDev();
+ return createDeprecatedResponderListener(responder, props);
+ },
+ useDeferredValue: function (value, config) {
+ currentHookNameInDev = 'useDeferredValue';
+ mountHookTypesDev();
+ return mountDeferredValue(value, config);
+ },
+ useTransition: function (config) {
+ currentHookNameInDev = 'useTransition';
+ mountHookTypesDev();
+ return mountTransition(config);
+ }
+ };
+ HooksDispatcherOnMountWithHookTypesInDEV = {
+ readContext: function (context, observedBits) {
+ return readContext(context, observedBits);
+ },
+ useCallback: function (callback, deps) {
+ currentHookNameInDev = 'useCallback';
+ updateHookTypesDev();
+ return mountCallback(callback, deps);
+ },
+ useContext: function (context, observedBits) {
+ currentHookNameInDev = 'useContext';
+ updateHookTypesDev();
+ return readContext(context, observedBits);
+ },
+ useEffect: function (create, deps) {
+ currentHookNameInDev = 'useEffect';
+ updateHookTypesDev();
+ return mountEffect(create, deps);
+ },
+ useImperativeHandle: function (ref, create, deps) {
+ currentHookNameInDev = 'useImperativeHandle';
+ updateHookTypesDev();
+ return mountImperativeHandle(ref, create, deps);
+ },
+ useLayoutEffect: function (create, deps) {
+ currentHookNameInDev = 'useLayoutEffect';
+ updateHookTypesDev();
+ return mountLayoutEffect(create, deps);
+ },
+ useMemo: function (create, deps) {
+ currentHookNameInDev = 'useMemo';
+ updateHookTypesDev();
+ var prevDispatcher = ReactCurrentDispatcher.current;
+ ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;
+
+ try {
+ return mountMemo(create, deps);
+ } finally {
+ ReactCurrentDispatcher.current = prevDispatcher;
+ }
+ },
+ useReducer: function (reducer, initialArg, init) {
+ currentHookNameInDev = 'useReducer';
+ updateHookTypesDev();
+ var prevDispatcher = ReactCurrentDispatcher.current;
+ ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;
+
+ try {
+ return mountReducer(reducer, initialArg, init);
+ } finally {
+ ReactCurrentDispatcher.current = prevDispatcher;
+ }
+ },
+ useRef: function (initialValue) {
+ currentHookNameInDev = 'useRef';
+ updateHookTypesDev();
+ return mountRef(initialValue);
+ },
+ useState: function (initialState) {
+ currentHookNameInDev = 'useState';
+ updateHookTypesDev();
+ var prevDispatcher = ReactCurrentDispatcher.current;
+ ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;
+
+ try {
+ return mountState(initialState);
+ } finally {
+ ReactCurrentDispatcher.current = prevDispatcher;
+ }
+ },
+ useDebugValue: function (value, formatterFn) {
+ currentHookNameInDev = 'useDebugValue';
+ updateHookTypesDev();
+ return mountDebugValue();
+ },
+ useResponder: function (responder, props) {
+ currentHookNameInDev = 'useResponder';
+ updateHookTypesDev();
+ return createDeprecatedResponderListener(responder, props);
+ },
+ useDeferredValue: function (value, config) {
+ currentHookNameInDev = 'useDeferredValue';
+ updateHookTypesDev();
+ return mountDeferredValue(value, config);
+ },
+ useTransition: function (config) {
+ currentHookNameInDev = 'useTransition';
+ updateHookTypesDev();
+ return mountTransition(config);
+ }
+ };
+ HooksDispatcherOnUpdateInDEV = {
+ readContext: function (context, observedBits) {
+ return readContext(context, observedBits);
+ },
+ useCallback: function (callback, deps) {
+ currentHookNameInDev = 'useCallback';
+ updateHookTypesDev();
+ return updateCallback(callback, deps);
+ },
+ useContext: function (context, observedBits) {
+ currentHookNameInDev = 'useContext';
+ updateHookTypesDev();
+ return readContext(context, observedBits);
+ },
+ useEffect: function (create, deps) {
+ currentHookNameInDev = 'useEffect';
+ updateHookTypesDev();
+ return updateEffect(create, deps);
+ },
+ useImperativeHandle: function (ref, create, deps) {
+ currentHookNameInDev = 'useImperativeHandle';
+ updateHookTypesDev();
+ return updateImperativeHandle(ref, create, deps);
+ },
+ useLayoutEffect: function (create, deps) {
+ currentHookNameInDev = 'useLayoutEffect';
+ updateHookTypesDev();
+ return updateLayoutEffect(create, deps);
+ },
+ useMemo: function (create, deps) {
+ currentHookNameInDev = 'useMemo';
+ updateHookTypesDev();
+ var prevDispatcher = ReactCurrentDispatcher.current;
+ ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
+
+ try {
+ return updateMemo(create, deps);
+ } finally {
+ ReactCurrentDispatcher.current = prevDispatcher;
+ }
+ },
+ useReducer: function (reducer, initialArg, init) {
+ currentHookNameInDev = 'useReducer';
+ updateHookTypesDev();
+ var prevDispatcher = ReactCurrentDispatcher.current;
+ ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
+
+ try {
+ return updateReducer(reducer, initialArg, init);
+ } finally {
+ ReactCurrentDispatcher.current = prevDispatcher;
+ }
+ },
+ useRef: function (initialValue) {
+ currentHookNameInDev = 'useRef';
+ updateHookTypesDev();
+ return updateRef();
+ },
+ useState: function (initialState) {
+ currentHookNameInDev = 'useState';
+ updateHookTypesDev();
+ var prevDispatcher = ReactCurrentDispatcher.current;
+ ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
+
+ try {
+ return updateState(initialState);
+ } finally {
+ ReactCurrentDispatcher.current = prevDispatcher;
+ }
+ },
+ useDebugValue: function (value, formatterFn) {
+ currentHookNameInDev = 'useDebugValue';
+ updateHookTypesDev();
+ return updateDebugValue();
+ },
+ useResponder: function (responder, props) {
+ currentHookNameInDev = 'useResponder';
+ updateHookTypesDev();
+ return createDeprecatedResponderListener(responder, props);
+ },
+ useDeferredValue: function (value, config) {
+ currentHookNameInDev = 'useDeferredValue';
+ updateHookTypesDev();
+ return updateDeferredValue(value, config);
+ },
+ useTransition: function (config) {
+ currentHookNameInDev = 'useTransition';
+ updateHookTypesDev();
+ return updateTransition(config);
+ }
+ };
+ HooksDispatcherOnRerenderInDEV = {
+ readContext: function (context, observedBits) {
+ return readContext(context, observedBits);
+ },
+ useCallback: function (callback, deps) {
+ currentHookNameInDev = 'useCallback';
+ updateHookTypesDev();
+ return updateCallback(callback, deps);
+ },
+ useContext: function (context, observedBits) {
+ currentHookNameInDev = 'useContext';
+ updateHookTypesDev();
+ return readContext(context, observedBits);
+ },
+ useEffect: function (create, deps) {
+ currentHookNameInDev = 'useEffect';
+ updateHookTypesDev();
+ return updateEffect(create, deps);
+ },
+ useImperativeHandle: function (ref, create, deps) {
+ currentHookNameInDev = 'useImperativeHandle';
+ updateHookTypesDev();
+ return updateImperativeHandle(ref, create, deps);
+ },
+ useLayoutEffect: function (create, deps) {
+ currentHookNameInDev = 'useLayoutEffect';
+ updateHookTypesDev();
+ return updateLayoutEffect(create, deps);
+ },
+ useMemo: function (create, deps) {
+ currentHookNameInDev = 'useMemo';
+ updateHookTypesDev();
+ var prevDispatcher = ReactCurrentDispatcher.current;
+ ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnRerenderInDEV;
+
+ try {
+ return updateMemo(create, deps);
+ } finally {
+ ReactCurrentDispatcher.current = prevDispatcher;
+ }
+ },
+ useReducer: function (reducer, initialArg, init) {
+ currentHookNameInDev = 'useReducer';
+ updateHookTypesDev();
+ var prevDispatcher = ReactCurrentDispatcher.current;
+ ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnRerenderInDEV;
+
+ try {
+ return rerenderReducer(reducer, initialArg, init);
+ } finally {
+ ReactCurrentDispatcher.current = prevDispatcher;
+ }
+ },
+ useRef: function (initialValue) {
+ currentHookNameInDev = 'useRef';
+ updateHookTypesDev();
+ return updateRef();
+ },
+ useState: function (initialState) {
+ currentHookNameInDev = 'useState';
+ updateHookTypesDev();
+ var prevDispatcher = ReactCurrentDispatcher.current;
+ ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnRerenderInDEV;
+
+ try {
+ return rerenderState(initialState);
+ } finally {
+ ReactCurrentDispatcher.current = prevDispatcher;
+ }
+ },
+ useDebugValue: function (value, formatterFn) {
+ currentHookNameInDev = 'useDebugValue';
+ updateHookTypesDev();
+ return updateDebugValue();
+ },
+ useResponder: function (responder, props) {
+ currentHookNameInDev = 'useResponder';
+ updateHookTypesDev();
+ return createDeprecatedResponderListener(responder, props);
+ },
+ useDeferredValue: function (value, config) {
+ currentHookNameInDev = 'useDeferredValue';
+ updateHookTypesDev();
+ return rerenderDeferredValue(value, config);
+ },
+ useTransition: function (config) {
+ currentHookNameInDev = 'useTransition';
+ updateHookTypesDev();
+ return rerenderTransition(config);
+ }
+ };
+ InvalidNestedHooksDispatcherOnMountInDEV = {
+ readContext: function (context, observedBits) {
+ warnInvalidContextAccess();
+ return readContext(context, observedBits);
+ },
+ useCallback: function (callback, deps) {
+ currentHookNameInDev = 'useCallback';
+ warnInvalidHookAccess();
+ mountHookTypesDev();
+ return mountCallback(callback, deps);
+ },
+ useContext: function (context, observedBits) {
+ currentHookNameInDev = 'useContext';
+ warnInvalidHookAccess();
+ mountHookTypesDev();
+ return readContext(context, observedBits);
+ },
+ useEffect: function (create, deps) {
+ currentHookNameInDev = 'useEffect';
+ warnInvalidHookAccess();
+ mountHookTypesDev();
+ return mountEffect(create, deps);
+ },
+ useImperativeHandle: function (ref, create, deps) {
+ currentHookNameInDev = 'useImperativeHandle';
+ warnInvalidHookAccess();
+ mountHookTypesDev();
+ return mountImperativeHandle(ref, create, deps);
+ },
+ useLayoutEffect: function (create, deps) {
+ currentHookNameInDev = 'useLayoutEffect';
+ warnInvalidHookAccess();
+ mountHookTypesDev();
+ return mountLayoutEffect(create, deps);
+ },
+ useMemo: function (create, deps) {
+ currentHookNameInDev = 'useMemo';
+ warnInvalidHookAccess();
+ mountHookTypesDev();
+ var prevDispatcher = ReactCurrentDispatcher.current;
+ ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;
+
+ try {
+ return mountMemo(create, deps);
+ } finally {
+ ReactCurrentDispatcher.current = prevDispatcher;
+ }
+ },
+ useReducer: function (reducer, initialArg, init) {
+ currentHookNameInDev = 'useReducer';
+ warnInvalidHookAccess();
+ mountHookTypesDev();
+ var prevDispatcher = ReactCurrentDispatcher.current;
+ ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;
+
+ try {
+ return mountReducer(reducer, initialArg, init);
+ } finally {
+ ReactCurrentDispatcher.current = prevDispatcher;
+ }
+ },
+ useRef: function (initialValue) {
+ currentHookNameInDev = 'useRef';
+ warnInvalidHookAccess();
+ mountHookTypesDev();
+ return mountRef(initialValue);
+ },
+ useState: function (initialState) {
+ currentHookNameInDev = 'useState';
+ warnInvalidHookAccess();
+ mountHookTypesDev();
+ var prevDispatcher = ReactCurrentDispatcher.current;
+ ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnMountInDEV;
+
+ try {
+ return mountState(initialState);
+ } finally {
+ ReactCurrentDispatcher.current = prevDispatcher;
+ }
+ },
+ useDebugValue: function (value, formatterFn) {
+ currentHookNameInDev = 'useDebugValue';
+ warnInvalidHookAccess();
+ mountHookTypesDev();
+ return mountDebugValue();
+ },
+ useResponder: function (responder, props) {
+ currentHookNameInDev = 'useResponder';
+ warnInvalidHookAccess();
+ mountHookTypesDev();
+ return createDeprecatedResponderListener(responder, props);
+ },
+ useDeferredValue: function (value, config) {
+ currentHookNameInDev = 'useDeferredValue';
+ warnInvalidHookAccess();
+ mountHookTypesDev();
+ return mountDeferredValue(value, config);
+ },
+ useTransition: function (config) {
+ currentHookNameInDev = 'useTransition';
+ warnInvalidHookAccess();
+ mountHookTypesDev();
+ return mountTransition(config);
+ }
+ };
+ InvalidNestedHooksDispatcherOnUpdateInDEV = {
+ readContext: function (context, observedBits) {
+ warnInvalidContextAccess();
+ return readContext(context, observedBits);
+ },
+ useCallback: function (callback, deps) {
+ currentHookNameInDev = 'useCallback';
+ warnInvalidHookAccess();
+ updateHookTypesDev();
+ return updateCallback(callback, deps);
+ },
+ useContext: function (context, observedBits) {
+ currentHookNameInDev = 'useContext';
+ warnInvalidHookAccess();
+ updateHookTypesDev();
+ return readContext(context, observedBits);
+ },
+ useEffect: function (create, deps) {
+ currentHookNameInDev = 'useEffect';
+ warnInvalidHookAccess();
+ updateHookTypesDev();
+ return updateEffect(create, deps);
+ },
+ useImperativeHandle: function (ref, create, deps) {
+ currentHookNameInDev = 'useImperativeHandle';
+ warnInvalidHookAccess();
+ updateHookTypesDev();
+ return updateImperativeHandle(ref, create, deps);
+ },
+ useLayoutEffect: function (create, deps) {
+ currentHookNameInDev = 'useLayoutEffect';
+ warnInvalidHookAccess();
+ updateHookTypesDev();
+ return updateLayoutEffect(create, deps);
+ },
+ useMemo: function (create, deps) {
+ currentHookNameInDev = 'useMemo';
+ warnInvalidHookAccess();
+ updateHookTypesDev();
+ var prevDispatcher = ReactCurrentDispatcher.current;
+ ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
+
+ try {
+ return updateMemo(create, deps);
+ } finally {
+ ReactCurrentDispatcher.current = prevDispatcher;
+ }
+ },
+ useReducer: function (reducer, initialArg, init) {
+ currentHookNameInDev = 'useReducer';
+ warnInvalidHookAccess();
+ updateHookTypesDev();
+ var prevDispatcher = ReactCurrentDispatcher.current;
+ ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
+
+ try {
+ return updateReducer(reducer, initialArg, init);
+ } finally {
+ ReactCurrentDispatcher.current = prevDispatcher;
+ }
+ },
+ useRef: function (initialValue) {
+ currentHookNameInDev = 'useRef';
+ warnInvalidHookAccess();
+ updateHookTypesDev();
+ return updateRef();
+ },
+ useState: function (initialState) {
+ currentHookNameInDev = 'useState';
+ warnInvalidHookAccess();
+ updateHookTypesDev();
+ var prevDispatcher = ReactCurrentDispatcher.current;
+ ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
+
+ try {
+ return updateState(initialState);
+ } finally {
+ ReactCurrentDispatcher.current = prevDispatcher;
+ }
+ },
+ useDebugValue: function (value, formatterFn) {
+ currentHookNameInDev = 'useDebugValue';
+ warnInvalidHookAccess();
+ updateHookTypesDev();
+ return updateDebugValue();
+ },
+ useResponder: function (responder, props) {
+ currentHookNameInDev = 'useResponder';
+ warnInvalidHookAccess();
+ updateHookTypesDev();
+ return createDeprecatedResponderListener(responder, props);
+ },
+ useDeferredValue: function (value, config) {
+ currentHookNameInDev = 'useDeferredValue';
+ warnInvalidHookAccess();
+ updateHookTypesDev();
+ return updateDeferredValue(value, config);
+ },
+ useTransition: function (config) {
+ currentHookNameInDev = 'useTransition';
+ warnInvalidHookAccess();
+ updateHookTypesDev();
+ return updateTransition(config);
+ }
+ };
+ InvalidNestedHooksDispatcherOnRerenderInDEV = {
+ readContext: function (context, observedBits) {
+ warnInvalidContextAccess();
+ return readContext(context, observedBits);
+ },
+ useCallback: function (callback, deps) {
+ currentHookNameInDev = 'useCallback';
+ warnInvalidHookAccess();
+ updateHookTypesDev();
+ return updateCallback(callback, deps);
+ },
+ useContext: function (context, observedBits) {
+ currentHookNameInDev = 'useContext';
+ warnInvalidHookAccess();
+ updateHookTypesDev();
+ return readContext(context, observedBits);
+ },
+ useEffect: function (create, deps) {
+ currentHookNameInDev = 'useEffect';
+ warnInvalidHookAccess();
+ updateHookTypesDev();
+ return updateEffect(create, deps);
+ },
+ useImperativeHandle: function (ref, create, deps) {
+ currentHookNameInDev = 'useImperativeHandle';
+ warnInvalidHookAccess();
+ updateHookTypesDev();
+ return updateImperativeHandle(ref, create, deps);
+ },
+ useLayoutEffect: function (create, deps) {
+ currentHookNameInDev = 'useLayoutEffect';
+ warnInvalidHookAccess();
+ updateHookTypesDev();
+ return updateLayoutEffect(create, deps);
+ },
+ useMemo: function (create, deps) {
+ currentHookNameInDev = 'useMemo';
+ warnInvalidHookAccess();
+ updateHookTypesDev();
+ var prevDispatcher = ReactCurrentDispatcher.current;
+ ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
+
+ try {
+ return updateMemo(create, deps);
+ } finally {
+ ReactCurrentDispatcher.current = prevDispatcher;
+ }
+ },
+ useReducer: function (reducer, initialArg, init) {
+ currentHookNameInDev = 'useReducer';
+ warnInvalidHookAccess();
+ updateHookTypesDev();
+ var prevDispatcher = ReactCurrentDispatcher.current;
+ ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
+
+ try {
+ return rerenderReducer(reducer, initialArg, init);
+ } finally {
+ ReactCurrentDispatcher.current = prevDispatcher;
+ }
+ },
+ useRef: function (initialValue) {
+ currentHookNameInDev = 'useRef';
+ warnInvalidHookAccess();
+ updateHookTypesDev();
+ return updateRef();
+ },
+ useState: function (initialState) {
+ currentHookNameInDev = 'useState';
+ warnInvalidHookAccess();
+ updateHookTypesDev();
+ var prevDispatcher = ReactCurrentDispatcher.current;
+ ReactCurrentDispatcher.current = InvalidNestedHooksDispatcherOnUpdateInDEV;
+
+ try {
+ return rerenderState(initialState);
+ } finally {
+ ReactCurrentDispatcher.current = prevDispatcher;
+ }
+ },
+ useDebugValue: function (value, formatterFn) {
+ currentHookNameInDev = 'useDebugValue';
+ warnInvalidHookAccess();
+ updateHookTypesDev();
+ return updateDebugValue();
+ },
+ useResponder: function (responder, props) {
+ currentHookNameInDev = 'useResponder';
+ warnInvalidHookAccess();
+ updateHookTypesDev();
+ return createDeprecatedResponderListener(responder, props);
+ },
+ useDeferredValue: function (value, config) {
+ currentHookNameInDev = 'useDeferredValue';
+ warnInvalidHookAccess();
+ updateHookTypesDev();
+ return rerenderDeferredValue(value, config);
+ },
+ useTransition: function (config) {
+ currentHookNameInDev = 'useTransition';
+ warnInvalidHookAccess();
+ updateHookTypesDev();
+ return rerenderTransition(config);
+ }
+ };
+ }
+
+ var now$1 = unstable_now;
+ var commitTime = 0;
+ var profilerStartTime = -1;
+
+ function getCommitTime() {
+ return commitTime;
+ }
+
+ function recordCommitTime() {
+
+ commitTime = now$1();
+ }
+
+ function startProfilerTimer(fiber) {
+
+ profilerStartTime = now$1();
+
+ if (fiber.actualStartTime < 0) {
+ fiber.actualStartTime = now$1();
+ }
+ }
+
+ function stopProfilerTimerIfRunning(fiber) {
+
+ profilerStartTime = -1;
+ }
+
+ function stopProfilerTimerIfRunningAndRecordDelta(fiber, overrideBaseTime) {
+
+ if (profilerStartTime >= 0) {
+ var elapsedTime = now$1() - profilerStartTime;
+ fiber.actualDuration += elapsedTime;
+
+ if (overrideBaseTime) {
+ fiber.selfBaseDuration = elapsedTime;
+ }
+
+ profilerStartTime = -1;
+ }
+ }
+
+ // This may have been an insertion or a hydration.
+
+ var hydrationParentFiber = null;
+ var nextHydratableInstance = null;
+ var isHydrating = false;
+
+ function enterHydrationState(fiber) {
+
+ var parentInstance = fiber.stateNode.containerInfo;
+ nextHydratableInstance = getFirstHydratableChild(parentInstance);
+ hydrationParentFiber = fiber;
+ isHydrating = true;
+ return true;
+ }
+
+ function deleteHydratableInstance(returnFiber, instance) {
+ {
+ switch (returnFiber.tag) {
+ case HostRoot:
+ didNotHydrateContainerInstance(returnFiber.stateNode.containerInfo, instance);
+ break;
+
+ case HostComponent:
+ didNotHydrateInstance(returnFiber.type, returnFiber.memoizedProps, returnFiber.stateNode, instance);
+ break;
+ }
+ }
+
+ var childToDelete = createFiberFromHostInstanceForDeletion();
+ childToDelete.stateNode = instance;
+ childToDelete.return = returnFiber;
+ childToDelete.effectTag = Deletion; // This might seem like it belongs on progressedFirstDeletion. However,
+ // these children are not part of the reconciliation list of children.
+ // Even if we abort and rereconcile the children, that will try to hydrate
+ // again and the nodes are still in the host tree so these will be
+ // recreated.
+
+ if (returnFiber.lastEffect !== null) {
+ returnFiber.lastEffect.nextEffect = childToDelete;
+ returnFiber.lastEffect = childToDelete;
+ } else {
+ returnFiber.firstEffect = returnFiber.lastEffect = childToDelete;
+ }
+ }
+
+ function insertNonHydratedInstance(returnFiber, fiber) {
+ fiber.effectTag = fiber.effectTag & ~Hydrating | Placement;
+
+ {
+ switch (returnFiber.tag) {
+ case HostRoot:
+ {
+ var parentContainer = returnFiber.stateNode.containerInfo;
+
+ switch (fiber.tag) {
+ case HostComponent:
+ var type = fiber.type;
+ var props = fiber.pendingProps;
+ didNotFindHydratableContainerInstance(parentContainer, type);
+ break;
+
+ case HostText:
+ var text = fiber.pendingProps;
+ didNotFindHydratableContainerTextInstance(parentContainer, text);
+ break;
+ }
+
+ break;
+ }
+
+ case HostComponent:
+ {
+ var parentType = returnFiber.type;
+ var parentProps = returnFiber.memoizedProps;
+ var parentInstance = returnFiber.stateNode;
+
+ switch (fiber.tag) {
+ case HostComponent:
+ var _type = fiber.type;
+ var _props = fiber.pendingProps;
+ didNotFindHydratableInstance(parentType, parentProps, parentInstance, _type);
+ break;
+
+ case HostText:
+ var _text = fiber.pendingProps;
+ didNotFindHydratableTextInstance(parentType, parentProps, parentInstance, _text);
+ break;
+
+ case SuspenseComponent:
+ didNotFindHydratableSuspenseInstance(parentType, parentProps);
+ break;
+ }
+
+ break;
+ }
+
+ default:
+ return;
+ }
+ }
+ }
+
+ function tryHydrate(fiber, nextInstance) {
+ switch (fiber.tag) {
+ case HostComponent:
+ {
+ var type = fiber.type;
+ var props = fiber.pendingProps;
+ var instance = canHydrateInstance(nextInstance, type);
+
+ if (instance !== null) {
+ fiber.stateNode = instance;
+ return true;
+ }
+
+ return false;
+ }
+
+ case HostText:
+ {
+ var text = fiber.pendingProps;
+ var textInstance = canHydrateTextInstance(nextInstance, text);
+
+ if (textInstance !== null) {
+ fiber.stateNode = textInstance;
+ return true;
+ }
+
+ return false;
+ }
+
+ case SuspenseComponent:
+ {
+
+ return false;
+ }
+
+ default:
+ return false;
+ }
+ }
+
+ function tryToClaimNextHydratableInstance(fiber) {
+ if (!isHydrating) {
+ return;
+ }
+
+ var nextInstance = nextHydratableInstance;
+
+ if (!nextInstance) {
+ // Nothing to hydrate. Make it an insertion.
+ insertNonHydratedInstance(hydrationParentFiber, fiber);
+ isHydrating = false;
+ hydrationParentFiber = fiber;
+ return;
+ }
+
+ var firstAttemptedInstance = nextInstance;
+
+ if (!tryHydrate(fiber, nextInstance)) {
+ // If we can't hydrate this instance let's try the next one.
+ // We use this as a heuristic. It's based on intuition and not data so it
+ // might be flawed or unnecessary.
+ nextInstance = getNextHydratableSibling(firstAttemptedInstance);
+
+ if (!nextInstance || !tryHydrate(fiber, nextInstance)) {
+ // Nothing to hydrate. Make it an insertion.
+ insertNonHydratedInstance(hydrationParentFiber, fiber);
+ isHydrating = false;
+ hydrationParentFiber = fiber;
+ return;
+ } // We matched the next one, we'll now assume that the first one was
+ // superfluous and we'll delete it. Since we can't eagerly delete it
+ // we'll have to schedule a deletion. To do that, this node needs a dummy
+ // fiber associated with it.
+
+
+ deleteHydratableInstance(hydrationParentFiber, firstAttemptedInstance);
+ }
+
+ hydrationParentFiber = fiber;
+ nextHydratableInstance = getFirstHydratableChild(nextInstance);
+ }
+
+ function prepareToHydrateHostInstance(fiber, rootContainerInstance, hostContext) {
+
+ var instance = fiber.stateNode;
+ var updatePayload = hydrateInstance(instance, fiber.type, fiber.memoizedProps, rootContainerInstance, hostContext, fiber); // TODO: Type this specific to this type of component.
+
+ fiber.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there
+ // is a new ref we mark this as an update.
+
+ if (updatePayload !== null) {
+ return true;
+ }
+
+ return false;
+ }
+
+ function prepareToHydrateHostTextInstance(fiber) {
+
+ var textInstance = fiber.stateNode;
+ var textContent = fiber.memoizedProps;
+ var shouldUpdate = hydrateTextInstance(textInstance, textContent, fiber);
+
+ {
+ if (shouldUpdate) {
+ // We assume that prepareToHydrateHostTextInstance is called in a context where the
+ // hydration parent is the parent host component of this host text.
+ var returnFiber = hydrationParentFiber;
+
+ if (returnFiber !== null) {
+ switch (returnFiber.tag) {
+ case HostRoot:
+ {
+ var parentContainer = returnFiber.stateNode.containerInfo;
+ didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, textContent);
+ break;
+ }
+
+ case HostComponent:
+ {
+ var parentType = returnFiber.type;
+ var parentProps = returnFiber.memoizedProps;
+ var parentInstance = returnFiber.stateNode;
+ didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, textContent);
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ return shouldUpdate;
+ }
+
+ function skipPastDehydratedSuspenseInstance(fiber) {
+
+ var suspenseState = fiber.memoizedState;
+ var suspenseInstance = suspenseState !== null ? suspenseState.dehydrated : null;
+
+ if (!suspenseInstance) {
+ {
+ throw Error( "Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue." );
+ }
+ }
+
+ return getNextHydratableInstanceAfterSuspenseInstance(suspenseInstance);
+ }
+
+ function popToNextHostParent(fiber) {
+ var parent = fiber.return;
+
+ while (parent !== null && parent.tag !== HostComponent && parent.tag !== HostRoot && parent.tag !== SuspenseComponent) {
+ parent = parent.return;
+ }
+
+ hydrationParentFiber = parent;
+ }
+
+ function popHydrationState(fiber) {
+
+ if (fiber !== hydrationParentFiber) {
+ // We're deeper than the current hydration context, inside an inserted
+ // tree.
+ return false;
+ }
+
+ if (!isHydrating) {
+ // If we're not currently hydrating but we're in a hydration context, then
+ // we were an insertion and now need to pop up reenter hydration of our
+ // siblings.
+ popToNextHostParent(fiber);
+ isHydrating = true;
+ return false;
+ }
+
+ var type = fiber.type; // If we have any remaining hydratable nodes, we need to delete them now.
+ // We only do this deeper than head and body since they tend to have random
+ // other nodes in them. We also ignore components with pure text content in
+ // side of them.
+ // TODO: Better heuristic.
+
+ if (fiber.tag !== HostComponent || type !== 'head' && type !== 'body' && !shouldSetTextContent(type, fiber.memoizedProps)) {
+ var nextInstance = nextHydratableInstance;
+
+ while (nextInstance) {
+ deleteHydratableInstance(fiber, nextInstance);
+ nextInstance = getNextHydratableSibling(nextInstance);
+ }
+ }
+
+ popToNextHostParent(fiber);
+
+ if (fiber.tag === SuspenseComponent) {
+ nextHydratableInstance = skipPastDehydratedSuspenseInstance(fiber);
+ } else {
+ nextHydratableInstance = hydrationParentFiber ? getNextHydratableSibling(fiber.stateNode) : null;
+ }
+
+ return true;
+ }
+
+ function resetHydrationState() {
+
+ hydrationParentFiber = null;
+ nextHydratableInstance = null;
+ isHydrating = false;
+ }
+
+ var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;
+ var didReceiveUpdate = false;
+ var didWarnAboutBadClass;
+ var didWarnAboutModulePatternComponent;
+ var didWarnAboutContextTypeOnFunctionComponent;
+ var didWarnAboutGetDerivedStateOnFunctionComponent;
+ var didWarnAboutFunctionRefs;
+ var didWarnAboutReassigningProps;
+ var didWarnAboutRevealOrder;
+ var didWarnAboutTailOptions;
+
+ {
+ didWarnAboutBadClass = {};
+ didWarnAboutModulePatternComponent = {};
+ didWarnAboutContextTypeOnFunctionComponent = {};
+ didWarnAboutGetDerivedStateOnFunctionComponent = {};
+ didWarnAboutFunctionRefs = {};
+ didWarnAboutReassigningProps = false;
+ didWarnAboutRevealOrder = {};
+ didWarnAboutTailOptions = {};
+ }
+
+ function reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime) {
+ if (current === null) {
+ // If this is a fresh new component that hasn't been rendered yet, we
+ // won't update its child set by applying minimal side-effects. Instead,
+ // we will add them all to the child before it gets rendered. That means
+ // we can optimize this reconciliation pass by not tracking side-effects.
+ workInProgress.child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
+ } else {
+ // If the current child is the same as the work in progress, it means that
+ // we haven't yet started any work on these children. Therefore, we use
+ // the clone algorithm to create a copy of all the current children.
+ // If we had any progressed work already, that is invalid at this point so
+ // let's throw it out.
+ workInProgress.child = reconcileChildFibers(workInProgress, current.child, nextChildren, renderExpirationTime);
+ }
+ }
+
+ function forceUnmountCurrentAndReconcile(current, workInProgress, nextChildren, renderExpirationTime) {
+ // This function is fork of reconcileChildren. It's used in cases where we
+ // want to reconcile without matching against the existing set. This has the
+ // effect of all current children being unmounted; even if the type and key
+ // are the same, the old child is unmounted and a new child is created.
+ //
+ // To do this, we're going to go through the reconcile algorithm twice. In
+ // the first pass, we schedule a deletion for all the current children by
+ // passing null.
+ workInProgress.child = reconcileChildFibers(workInProgress, current.child, null, renderExpirationTime); // In the second pass, we mount the new children. The trick here is that we
+ // pass null in place of where we usually pass the current child set. This has
+ // the effect of remounting all children regardless of whether their
+ // identities match.
+
+ workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
+ }
+
+ function updateForwardRef(current, workInProgress, Component, nextProps, renderExpirationTime) {
+ // TODO: current can be non-null here even if the component
+ // hasn't yet mounted. This happens after the first render suspends.
+ // We'll need to figure out if this is fine or can cause issues.
+ {
+ if (workInProgress.type !== workInProgress.elementType) {
+ // Lazy component props can't be validated in createElement
+ // because they're only guaranteed to be resolved here.
+ var innerPropTypes = Component.propTypes;
+
+ if (innerPropTypes) {
+ checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
+ 'prop', getComponentName(Component), getCurrentFiberStackInDev);
+ }
+ }
+ }
+
+ var render = Component.render;
+ var ref = workInProgress.ref; // The rest is a fork of updateFunctionComponent
+
+ var nextChildren;
+ prepareToReadContext(workInProgress, renderExpirationTime);
+
+ {
+ ReactCurrentOwner$1.current = workInProgress;
+ setIsRendering(true);
+ nextChildren = renderWithHooks(current, workInProgress, render, nextProps, ref, renderExpirationTime);
+
+ if ( workInProgress.mode & StrictMode) {
+ // Only double-render components with Hooks
+ if (workInProgress.memoizedState !== null) {
+ nextChildren = renderWithHooks(current, workInProgress, render, nextProps, ref, renderExpirationTime);
+ }
+ }
+
+ setIsRendering(false);
+ }
+
+ if (current !== null && !didReceiveUpdate) {
+ bailoutHooks(current, workInProgress, renderExpirationTime);
+ return bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime);
+ } // React DevTools reads this flag.
+
+
+ workInProgress.effectTag |= PerformedWork;
+ reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime);
+ return workInProgress.child;
+ }
+
+ function updateMemoComponent(current, workInProgress, Component, nextProps, updateExpirationTime, renderExpirationTime) {
+ if (current === null) {
+ var type = Component.type;
+
+ if (isSimpleFunctionComponent(type) && Component.compare === null && // SimpleMemoComponent codepath doesn't resolve outer props either.
+ Component.defaultProps === undefined) {
+ var resolvedType = type;
+
+ {
+ resolvedType = resolveFunctionForHotReloading(type);
+ } // If this is a plain function component without default props,
+ // and with only the default shallow comparison, we upgrade it
+ // to a SimpleMemoComponent to allow fast path updates.
+
+
+ workInProgress.tag = SimpleMemoComponent;
+ workInProgress.type = resolvedType;
+
+ {
+ validateFunctionComponentInDev(workInProgress, type);
+ }
+
+ return updateSimpleMemoComponent(current, workInProgress, resolvedType, nextProps, updateExpirationTime, renderExpirationTime);
+ }
+
+ {
+ var innerPropTypes = type.propTypes;
+
+ if (innerPropTypes) {
+ // Inner memo component props aren't currently validated in createElement.
+ // We could move it there, but we'd still need this for lazy code path.
+ checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
+ 'prop', getComponentName(type), getCurrentFiberStackInDev);
+ }
+ }
+
+ var child = createFiberFromTypeAndProps(Component.type, null, nextProps, null, workInProgress.mode, renderExpirationTime);
+ child.ref = workInProgress.ref;
+ child.return = workInProgress;
+ workInProgress.child = child;
+ return child;
+ }
+
+ {
+ var _type = Component.type;
+ var _innerPropTypes = _type.propTypes;
+
+ if (_innerPropTypes) {
+ // Inner memo component props aren't currently validated in createElement.
+ // We could move it there, but we'd still need this for lazy code path.
+ checkPropTypes_1(_innerPropTypes, nextProps, // Resolved props
+ 'prop', getComponentName(_type), getCurrentFiberStackInDev);
+ }
+ }
+
+ var currentChild = current.child; // This is always exactly one child
+
+ if (updateExpirationTime < renderExpirationTime) {
+ // This will be the props with resolved defaultProps,
+ // unlike current.memoizedProps which will be the unresolved ones.
+ var prevProps = currentChild.memoizedProps; // Default to shallow comparison
+
+ var compare = Component.compare;
+ compare = compare !== null ? compare : shallowEqual;
+
+ if (compare(prevProps, nextProps) && current.ref === workInProgress.ref) {
+ return bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime);
+ }
+ } // React DevTools reads this flag.
+
+
+ workInProgress.effectTag |= PerformedWork;
+ var newChild = createWorkInProgress(currentChild, nextProps);
+ newChild.ref = workInProgress.ref;
+ newChild.return = workInProgress;
+ workInProgress.child = newChild;
+ return newChild;
+ }
+
+ function updateSimpleMemoComponent(current, workInProgress, Component, nextProps, updateExpirationTime, renderExpirationTime) {
+ // TODO: current can be non-null here even if the component
+ // hasn't yet mounted. This happens when the inner render suspends.
+ // We'll need to figure out if this is fine or can cause issues.
+ {
+ if (workInProgress.type !== workInProgress.elementType) {
+ // Lazy component props can't be validated in createElement
+ // because they're only guaranteed to be resolved here.
+ var outerMemoType = workInProgress.elementType;
+
+ if (outerMemoType.$$typeof === REACT_LAZY_TYPE) {
+ // We warn when you define propTypes on lazy()
+ // so let's just skip over it to find memo() outer wrapper.
+ // Inner props for memo are validated later.
+ outerMemoType = refineResolvedLazyComponent(outerMemoType);
+ }
+
+ var outerPropTypes = outerMemoType && outerMemoType.propTypes;
+
+ if (outerPropTypes) {
+ checkPropTypes_1(outerPropTypes, nextProps, // Resolved (SimpleMemoComponent has no defaultProps)
+ 'prop', getComponentName(outerMemoType), getCurrentFiberStackInDev);
+ } // Inner propTypes will be validated in the function component path.
+
+ }
+ }
+
+ if (current !== null) {
+ var prevProps = current.memoizedProps;
+
+ if (shallowEqual(prevProps, nextProps) && current.ref === workInProgress.ref && ( // Prevent bailout if the implementation changed due to hot reload.
+ workInProgress.type === current.type )) {
+ didReceiveUpdate = false;
+
+ if (updateExpirationTime < renderExpirationTime) {
+ // The pending update priority was cleared at the beginning of
+ // beginWork. We're about to bail out, but there might be additional
+ // updates at a lower priority. Usually, the priority level of the
+ // remaining updates is accumlated during the evaluation of the
+ // component (i.e. when processing the update queue). But since since
+ // we're bailing out early *without* evaluating the component, we need
+ // to account for it here, too. Reset to the value of the current fiber.
+ // NOTE: This only applies to SimpleMemoComponent, not MemoComponent,
+ // because a MemoComponent fiber does not have hooks or an update queue;
+ // rather, it wraps around an inner component, which may or may not
+ // contains hooks.
+ // TODO: Move the reset at in beginWork out of the common path so that
+ // this is no longer necessary.
+ workInProgress.expirationTime = current.expirationTime;
+ return bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime);
+ }
+ }
+ }
+
+ return updateFunctionComponent(current, workInProgress, Component, nextProps, renderExpirationTime);
+ }
+
+ function updateFragment(current, workInProgress, renderExpirationTime) {
+ var nextChildren = workInProgress.pendingProps;
+ reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime);
+ return workInProgress.child;
+ }
+
+ function updateMode(current, workInProgress, renderExpirationTime) {
+ var nextChildren = workInProgress.pendingProps.children;
+ reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime);
+ return workInProgress.child;
+ }
+
+ function updateProfiler(current, workInProgress, renderExpirationTime) {
+ {
+ workInProgress.effectTag |= Update;
+ }
+
+ var nextProps = workInProgress.pendingProps;
+ var nextChildren = nextProps.children;
+ reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime);
+ return workInProgress.child;
+ }
+
+ function markRef(current, workInProgress) {
+ var ref = workInProgress.ref;
+
+ if (current === null && ref !== null || current !== null && current.ref !== ref) {
+ // Schedule a Ref effect
+ workInProgress.effectTag |= Ref;
+ }
+ }
+
+ function updateFunctionComponent(current, workInProgress, Component, nextProps, renderExpirationTime) {
+ {
+ if (workInProgress.type !== workInProgress.elementType) {
+ // Lazy component props can't be validated in createElement
+ // because they're only guaranteed to be resolved here.
+ var innerPropTypes = Component.propTypes;
+
+ if (innerPropTypes) {
+ checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
+ 'prop', getComponentName(Component), getCurrentFiberStackInDev);
+ }
+ }
+ }
+
+ var context;
+
+ {
+ var unmaskedContext = getUnmaskedContext(workInProgress, Component, true);
+ context = getMaskedContext(workInProgress, unmaskedContext);
+ }
+
+ var nextChildren;
+ prepareToReadContext(workInProgress, renderExpirationTime);
+
+ {
+ ReactCurrentOwner$1.current = workInProgress;
+ setIsRendering(true);
+ nextChildren = renderWithHooks(current, workInProgress, Component, nextProps, context, renderExpirationTime);
+
+ if ( workInProgress.mode & StrictMode) {
+ // Only double-render components with Hooks
+ if (workInProgress.memoizedState !== null) {
+ nextChildren = renderWithHooks(current, workInProgress, Component, nextProps, context, renderExpirationTime);
+ }
+ }
+
+ setIsRendering(false);
+ }
+
+ if (current !== null && !didReceiveUpdate) {
+ bailoutHooks(current, workInProgress, renderExpirationTime);
+ return bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime);
+ } // React DevTools reads this flag.
+
+
+ workInProgress.effectTag |= PerformedWork;
+ reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime);
+ return workInProgress.child;
+ }
+
+ function updateClassComponent(current, workInProgress, Component, nextProps, renderExpirationTime) {
+ {
+ if (workInProgress.type !== workInProgress.elementType) {
+ // Lazy component props can't be validated in createElement
+ // because they're only guaranteed to be resolved here.
+ var innerPropTypes = Component.propTypes;
+
+ if (innerPropTypes) {
+ checkPropTypes_1(innerPropTypes, nextProps, // Resolved props
+ 'prop', getComponentName(Component), getCurrentFiberStackInDev);
+ }
+ }
+ } // Push context providers early to prevent context stack mismatches.
+ // During mounting we don't know the child context yet as the instance doesn't exist.
+ // We will invalidate the child context in finishClassComponent() right after rendering.
+
+
+ var hasContext;
+
+ if (isContextProvider(Component)) {
+ hasContext = true;
+ pushContextProvider(workInProgress);
+ } else {
+ hasContext = false;
+ }
+
+ prepareToReadContext(workInProgress, renderExpirationTime);
+ var instance = workInProgress.stateNode;
+ var shouldUpdate;
+
+ if (instance === null) {
+ if (current !== null) {
+ // A class component without an instance only mounts if it suspended
+ // inside a non-concurrent tree, in an inconsistent state. We want to
+ // treat it like a new mount, even though an empty version of it already
+ // committed. Disconnect the alternate pointers.
+ current.alternate = null;
+ workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect
+
+ workInProgress.effectTag |= Placement;
+ } // In the initial pass we might need to construct the instance.
+
+
+ constructClassInstance(workInProgress, Component, nextProps);
+ mountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
+ shouldUpdate = true;
+ } else if (current === null) {
+ // In a resume, we'll already have an instance we can reuse.
+ shouldUpdate = resumeMountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
+ } else {
+ shouldUpdate = updateClassInstance(current, workInProgress, Component, nextProps, renderExpirationTime);
+ }
+
+ var nextUnitOfWork = finishClassComponent(current, workInProgress, Component, shouldUpdate, hasContext, renderExpirationTime);
+
+ {
+ var inst = workInProgress.stateNode;
+
+ if (inst.props !== nextProps) {
+ if (!didWarnAboutReassigningProps) {
+ error('It looks like %s is reassigning its own `this.props` while rendering. ' + 'This is not supported and can lead to confusing bugs.', getComponentName(workInProgress.type) || 'a component');
+ }
+
+ didWarnAboutReassigningProps = true;
+ }
+ }
+
+ return nextUnitOfWork;
+ }
+
+ function finishClassComponent(current, workInProgress, Component, shouldUpdate, hasContext, renderExpirationTime) {
+ // Refs should update even if shouldComponentUpdate returns false
+ markRef(current, workInProgress);
+ var didCaptureError = (workInProgress.effectTag & DidCapture) !== NoEffect;
+
+ if (!shouldUpdate && !didCaptureError) {
+ // Context providers should defer to sCU for rendering
+ if (hasContext) {
+ invalidateContextProvider(workInProgress, Component, false);
+ }
+
+ return bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime);
+ }
+
+ var instance = workInProgress.stateNode; // Rerender
+
+ ReactCurrentOwner$1.current = workInProgress;
+ var nextChildren;
+
+ if (didCaptureError && typeof Component.getDerivedStateFromError !== 'function') {
+ // If we captured an error, but getDerivedStateFromError is not defined,
+ // unmount all the children. componentDidCatch will schedule an update to
+ // re-render a fallback. This is temporary until we migrate everyone to
+ // the new API.
+ // TODO: Warn in a future release.
+ nextChildren = null;
+
+ {
+ stopProfilerTimerIfRunning();
+ }
+ } else {
+ {
+ setIsRendering(true);
+ nextChildren = instance.render();
+
+ if ( workInProgress.mode & StrictMode) {
+ instance.render();
+ }
+
+ setIsRendering(false);
+ }
+ } // React DevTools reads this flag.
+
+
+ workInProgress.effectTag |= PerformedWork;
+
+ if (current !== null && didCaptureError) {
+ // If we're recovering from an error, reconcile without reusing any of
+ // the existing children. Conceptually, the normal children and the children
+ // that are shown on error are two different sets, so we shouldn't reuse
+ // normal children even if their identities match.
+ forceUnmountCurrentAndReconcile(current, workInProgress, nextChildren, renderExpirationTime);
+ } else {
+ reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime);
+ } // Memoize state using the values we just used to render.
+ // TODO: Restructure so we never read values from the instance.
+
+
+ workInProgress.memoizedState = instance.state; // The context might have changed so we need to recalculate it.
+
+ if (hasContext) {
+ invalidateContextProvider(workInProgress, Component, true);
+ }
+
+ return workInProgress.child;
+ }
+
+ function pushHostRootContext(workInProgress) {
+ var root = workInProgress.stateNode;
+
+ if (root.pendingContext) {
+ pushTopLevelContextObject(workInProgress, root.pendingContext, root.pendingContext !== root.context);
+ } else if (root.context) {
+ // Should always be set
+ pushTopLevelContextObject(workInProgress, root.context, false);
+ }
+
+ pushHostContainer(workInProgress, root.containerInfo);
+ }
+
+ function updateHostRoot(current, workInProgress, renderExpirationTime) {
+ pushHostRootContext(workInProgress);
+ var updateQueue = workInProgress.updateQueue;
+
+ if (!(current !== null && updateQueue !== null)) {
+ {
+ throw Error( "If the root does not have an updateQueue, we should have already bailed out. This error is likely caused by a bug in React. Please file an issue." );
+ }
+ }
+
+ var nextProps = workInProgress.pendingProps;
+ var prevState = workInProgress.memoizedState;
+ var prevChildren = prevState !== null ? prevState.element : null;
+ cloneUpdateQueue(current, workInProgress);
+ processUpdateQueue(workInProgress, nextProps, null, renderExpirationTime);
+ var nextState = workInProgress.memoizedState; // Caution: React DevTools currently depends on this property
+ // being called "element".
+
+ var nextChildren = nextState.element;
+
+ if (nextChildren === prevChildren) {
+ // If the state is the same as before, that's a bailout because we had
+ // no work that expires at this time.
+ resetHydrationState();
+ return bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime);
+ }
+
+ var root = workInProgress.stateNode;
+
+ if (root.hydrate && enterHydrationState(workInProgress)) {
+ // If we don't have any current children this might be the first pass.
+ // We always try to hydrate. If this isn't a hydration pass there won't
+ // be any children to hydrate which is effectively the same thing as
+ // not hydrating.
+ var child = mountChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
+ workInProgress.child = child;
+ var node = child;
+
+ while (node) {
+ // Mark each child as hydrating. This is a fast path to know whether this
+ // tree is part of a hydrating tree. This is used to determine if a child
+ // node has fully mounted yet, and for scheduling event replaying.
+ // Conceptually this is similar to Placement in that a new subtree is
+ // inserted into the React tree here. It just happens to not need DOM
+ // mutations because it already exists.
+ node.effectTag = node.effectTag & ~Placement | Hydrating;
+ node = node.sibling;
+ }
+ } else {
+ // Otherwise reset hydration state in case we aborted and resumed another
+ // root.
+ reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime);
+ resetHydrationState();
+ }
+
+ return workInProgress.child;
+ }
+
+ function updateHostComponent(current, workInProgress, renderExpirationTime) {
+ pushHostContext(workInProgress);
+
+ if (current === null) {
+ tryToClaimNextHydratableInstance(workInProgress);
+ }
+
+ var type = workInProgress.type;
+ var nextProps = workInProgress.pendingProps;
+ var prevProps = current !== null ? current.memoizedProps : null;
+ var nextChildren = nextProps.children;
+ var isDirectTextChild = shouldSetTextContent(type, nextProps);
+
+ if (isDirectTextChild) {
+ // We special case a direct text child of a host node. This is a common
+ // case. We won't handle it as a reified child. We will instead handle
+ // this in the host environment that also has access to this prop. That
+ // avoids allocating another HostText fiber and traversing it.
+ nextChildren = null;
+ } else if (prevProps !== null && shouldSetTextContent(type, prevProps)) {
+ // If we're switching from a direct text child to a normal child, or to
+ // empty, we need to schedule the text content to be reset.
+ workInProgress.effectTag |= ContentReset;
+ }
+
+ markRef(current, workInProgress); // Check the host config to see if the children are offscreen/hidden.
+
+ if (workInProgress.mode & ConcurrentMode && renderExpirationTime !== Never && shouldDeprioritizeSubtree(type, nextProps)) {
+ {
+ markSpawnedWork(Never);
+ } // Schedule this fiber to re-render at offscreen priority. Then bailout.
+
+
+ workInProgress.expirationTime = workInProgress.childExpirationTime = Never;
+ return null;
+ }
+
+ reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime);
+ return workInProgress.child;
+ }
+
+ function updateHostText(current, workInProgress) {
+ if (current === null) {
+ tryToClaimNextHydratableInstance(workInProgress);
+ } // Nothing to do here. This is terminal. We'll do the completion step
+ // immediately after.
+
+
+ return null;
+ }
+
+ function mountLazyComponent(_current, workInProgress, elementType, updateExpirationTime, renderExpirationTime) {
+ if (_current !== null) {
+ // A lazy component only mounts if it suspended inside a non-
+ // concurrent tree, in an inconsistent state. We want to treat it like
+ // a new mount, even though an empty version of it already committed.
+ // Disconnect the alternate pointers.
+ _current.alternate = null;
+ workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect
+
+ workInProgress.effectTag |= Placement;
+ }
+
+ var props = workInProgress.pendingProps; // We can't start a User Timing measurement with correct label yet.
+ // Cancel and resume right after we know the tag.
+
+ cancelWorkTimer(workInProgress);
+ var Component = readLazyComponentType(elementType); // Store the unwrapped component in the type.
+
+ workInProgress.type = Component;
+ var resolvedTag = workInProgress.tag = resolveLazyComponentTag(Component);
+ startWorkTimer(workInProgress);
+ var resolvedProps = resolveDefaultProps(Component, props);
+ var child;
+
+ switch (resolvedTag) {
+ case FunctionComponent:
+ {
+ {
+ validateFunctionComponentInDev(workInProgress, Component);
+ workInProgress.type = Component = resolveFunctionForHotReloading(Component);
+ }
+
+ child = updateFunctionComponent(null, workInProgress, Component, resolvedProps, renderExpirationTime);
+ return child;
+ }
+
+ case ClassComponent:
+ {
+ {
+ workInProgress.type = Component = resolveClassForHotReloading(Component);
+ }
+
+ child = updateClassComponent(null, workInProgress, Component, resolvedProps, renderExpirationTime);
+ return child;
+ }
+
+ case ForwardRef:
+ {
+ {
+ workInProgress.type = Component = resolveForwardRefForHotReloading(Component);
+ }
+
+ child = updateForwardRef(null, workInProgress, Component, resolvedProps, renderExpirationTime);
+ return child;
+ }
+
+ case MemoComponent:
+ {
+ {
+ if (workInProgress.type !== workInProgress.elementType) {
+ var outerPropTypes = Component.propTypes;
+
+ if (outerPropTypes) {
+ checkPropTypes_1(outerPropTypes, resolvedProps, // Resolved for outer only
+ 'prop', getComponentName(Component), getCurrentFiberStackInDev);
+ }
+ }
+ }
+
+ child = updateMemoComponent(null, workInProgress, Component, resolveDefaultProps(Component.type, resolvedProps), // The inner type can have defaults too
+ updateExpirationTime, renderExpirationTime);
+ return child;
+ }
+ }
+
+ var hint = '';
+
+ {
+ if (Component !== null && typeof Component === 'object' && Component.$$typeof === REACT_LAZY_TYPE) {
+ hint = ' Did you wrap a component in React.lazy() more than once?';
+ }
+ } // This message intentionally doesn't mention ForwardRef or MemoComponent
+ // because the fact that it's a separate type of work is an
+ // implementation detail.
+
+
+ {
+ {
+ throw Error( "Element type is invalid. Received a promise that resolves to: " + Component + ". Lazy element type must resolve to a class or function." + hint );
+ }
+ }
+ }
+
+ function mountIncompleteClassComponent(_current, workInProgress, Component, nextProps, renderExpirationTime) {
+ if (_current !== null) {
+ // An incomplete component only mounts if it suspended inside a non-
+ // concurrent tree, in an inconsistent state. We want to treat it like
+ // a new mount, even though an empty version of it already committed.
+ // Disconnect the alternate pointers.
+ _current.alternate = null;
+ workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect
+
+ workInProgress.effectTag |= Placement;
+ } // Promote the fiber to a class and try rendering again.
+
+
+ workInProgress.tag = ClassComponent; // The rest of this function is a fork of `updateClassComponent`
+ // Push context providers early to prevent context stack mismatches.
+ // During mounting we don't know the child context yet as the instance doesn't exist.
+ // We will invalidate the child context in finishClassComponent() right after rendering.
+
+ var hasContext;
+
+ if (isContextProvider(Component)) {
+ hasContext = true;
+ pushContextProvider(workInProgress);
+ } else {
+ hasContext = false;
+ }
+
+ prepareToReadContext(workInProgress, renderExpirationTime);
+ constructClassInstance(workInProgress, Component, nextProps);
+ mountClassInstance(workInProgress, Component, nextProps, renderExpirationTime);
+ return finishClassComponent(null, workInProgress, Component, true, hasContext, renderExpirationTime);
+ }
+
+ function mountIndeterminateComponent(_current, workInProgress, Component, renderExpirationTime) {
+ if (_current !== null) {
+ // An indeterminate component only mounts if it suspended inside a non-
+ // concurrent tree, in an inconsistent state. We want to treat it like
+ // a new mount, even though an empty version of it already committed.
+ // Disconnect the alternate pointers.
+ _current.alternate = null;
+ workInProgress.alternate = null; // Since this is conceptually a new fiber, schedule a Placement effect
+
+ workInProgress.effectTag |= Placement;
+ }
+
+ var props = workInProgress.pendingProps;
+ var context;
+
+ {
+ var unmaskedContext = getUnmaskedContext(workInProgress, Component, false);
+ context = getMaskedContext(workInProgress, unmaskedContext);
+ }
+
+ prepareToReadContext(workInProgress, renderExpirationTime);
+ var value;
+
+ {
+ if (Component.prototype && typeof Component.prototype.render === 'function') {
+ var componentName = getComponentName(Component) || 'Unknown';
+
+ if (!didWarnAboutBadClass[componentName]) {
+ error("The <%s /> component appears to have a render method, but doesn't extend React.Component. " + 'This is likely to cause errors. Change %s to extend React.Component instead.', componentName, componentName);
+
+ didWarnAboutBadClass[componentName] = true;
+ }
+ }
+
+ if (workInProgress.mode & StrictMode) {
+ ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, null);
+ }
+
+ setIsRendering(true);
+ ReactCurrentOwner$1.current = workInProgress;
+ value = renderWithHooks(null, workInProgress, Component, props, context, renderExpirationTime);
+ setIsRendering(false);
+ } // React DevTools reads this flag.
+
+
+ workInProgress.effectTag |= PerformedWork;
+
+ if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) {
+ {
+ var _componentName = getComponentName(Component) || 'Unknown';
+
+ if (!didWarnAboutModulePatternComponent[_componentName]) {
+ error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName, _componentName, _componentName);
+
+ didWarnAboutModulePatternComponent[_componentName] = true;
+ }
+ } // Proceed under the assumption that this is a class instance
+
+
+ workInProgress.tag = ClassComponent; // Throw out any hooks that were used.
+
+ workInProgress.memoizedState = null;
+ workInProgress.updateQueue = null; // Push context providers early to prevent context stack mismatches.
+ // During mounting we don't know the child context yet as the instance doesn't exist.
+ // We will invalidate the child context in finishClassComponent() right after rendering.
+
+ var hasContext = false;
+
+ if (isContextProvider(Component)) {
+ hasContext = true;
+ pushContextProvider(workInProgress);
+ } else {
+ hasContext = false;
+ }
+
+ workInProgress.memoizedState = value.state !== null && value.state !== undefined ? value.state : null;
+ initializeUpdateQueue(workInProgress);
+ var getDerivedStateFromProps = Component.getDerivedStateFromProps;
+
+ if (typeof getDerivedStateFromProps === 'function') {
+ applyDerivedStateFromProps(workInProgress, Component, getDerivedStateFromProps, props);
+ }
+
+ adoptClassInstance(workInProgress, value);
+ mountClassInstance(workInProgress, Component, props, renderExpirationTime);
+ return finishClassComponent(null, workInProgress, Component, true, hasContext, renderExpirationTime);
+ } else {
+ // Proceed under the assumption that this is a function component
+ workInProgress.tag = FunctionComponent;
+
+ {
+
+ if ( workInProgress.mode & StrictMode) {
+ // Only double-render components with Hooks
+ if (workInProgress.memoizedState !== null) {
+ value = renderWithHooks(null, workInProgress, Component, props, context, renderExpirationTime);
+ }
+ }
+ }
+
+ reconcileChildren(null, workInProgress, value, renderExpirationTime);
+
+ {
+ validateFunctionComponentInDev(workInProgress, Component);
+ }
+
+ return workInProgress.child;
+ }
+ }
+
+ function validateFunctionComponentInDev(workInProgress, Component) {
+ {
+ if (Component) {
+ if (Component.childContextTypes) {
+ error('%s(...): childContextTypes cannot be defined on a function component.', Component.displayName || Component.name || 'Component');
+ }
+ }
+
+ if (workInProgress.ref !== null) {
+ var info = '';
+ var ownerName = getCurrentFiberOwnerNameInDevOrNull();
+
+ if (ownerName) {
+ info += '\n\nCheck the render method of `' + ownerName + '`.';
+ }
+
+ var warningKey = ownerName || workInProgress._debugID || '';
+ var debugSource = workInProgress._debugSource;
+
+ if (debugSource) {
+ warningKey = debugSource.fileName + ':' + debugSource.lineNumber;
+ }
+
+ if (!didWarnAboutFunctionRefs[warningKey]) {
+ didWarnAboutFunctionRefs[warningKey] = true;
+
+ error('Function components cannot be given refs. ' + 'Attempts to access this ref will fail. ' + 'Did you mean to use React.forwardRef()?%s', info);
+ }
+ }
+
+ if (typeof Component.getDerivedStateFromProps === 'function') {
+ var _componentName2 = getComponentName(Component) || 'Unknown';
+
+ if (!didWarnAboutGetDerivedStateOnFunctionComponent[_componentName2]) {
+ error('%s: Function components do not support getDerivedStateFromProps.', _componentName2);
+
+ didWarnAboutGetDerivedStateOnFunctionComponent[_componentName2] = true;
+ }
+ }
+
+ if (typeof Component.contextType === 'object' && Component.contextType !== null) {
+ var _componentName3 = getComponentName(Component) || 'Unknown';
+
+ if (!didWarnAboutContextTypeOnFunctionComponent[_componentName3]) {
+ error('%s: Function components do not support contextType.', _componentName3);
+
+ didWarnAboutContextTypeOnFunctionComponent[_componentName3] = true;
+ }
+ }
+ }
+ }
+
+ var SUSPENDED_MARKER = {
+ dehydrated: null,
+ retryTime: NoWork
+ };
+
+ function shouldRemainOnFallback(suspenseContext, current, workInProgress) {
+ // If the context is telling us that we should show a fallback, and we're not
+ // already showing content, then we should show the fallback instead.
+ return hasSuspenseContext(suspenseContext, ForceSuspenseFallback) && (current === null || current.memoizedState !== null);
+ }
+
+ function updateSuspenseComponent(current, workInProgress, renderExpirationTime) {
+ var mode = workInProgress.mode;
+ var nextProps = workInProgress.pendingProps; // This is used by DevTools to force a boundary to suspend.
+
+ {
+ if (shouldSuspend(workInProgress)) {
+ workInProgress.effectTag |= DidCapture;
+ }
+ }
+
+ var suspenseContext = suspenseStackCursor.current;
+ var nextDidTimeout = false;
+ var didSuspend = (workInProgress.effectTag & DidCapture) !== NoEffect;
+
+ if (didSuspend || shouldRemainOnFallback(suspenseContext, current)) {
+ // Something in this boundary's subtree already suspended. Switch to
+ // rendering the fallback children.
+ nextDidTimeout = true;
+ workInProgress.effectTag &= ~DidCapture;
+ } else {
+ // Attempting the main content
+ if (current === null || current.memoizedState !== null) {
+ // This is a new mount or this boundary is already showing a fallback state.
+ // Mark this subtree context as having at least one invisible parent that could
+ // handle the fallback state.
+ // Boundaries without fallbacks or should be avoided are not considered since
+ // they cannot handle preferred fallback states.
+ if (nextProps.fallback !== undefined && nextProps.unstable_avoidThisFallback !== true) {
+ suspenseContext = addSubtreeSuspenseContext(suspenseContext, InvisibleParentSuspenseContext);
+ }
+ }
+ }
+
+ suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
+ pushSuspenseContext(workInProgress, suspenseContext); // This next part is a bit confusing. If the children timeout, we switch to
+ // showing the fallback children in place of the "primary" children.
+ // However, we don't want to delete the primary children because then their
+ // state will be lost (both the React state and the host state, e.g.
+ // uncontrolled form inputs). Instead we keep them mounted and hide them.
+ // Both the fallback children AND the primary children are rendered at the
+ // same time. Once the primary children are un-suspended, we can delete
+ // the fallback children — don't need to preserve their state.
+ //
+ // The two sets of children are siblings in the host environment, but
+ // semantically, for purposes of reconciliation, they are two separate sets.
+ // So we store them using two fragment fibers.
+ //
+ // However, we want to avoid allocating extra fibers for every placeholder.
+ // They're only necessary when the children time out, because that's the
+ // only time when both sets are mounted.
+ //
+ // So, the extra fragment fibers are only used if the children time out.
+ // Otherwise, we render the primary children directly. This requires some
+ // custom reconciliation logic to preserve the state of the primary
+ // children. It's essentially a very basic form of re-parenting.
+
+ if (current === null) {
+ // If we're currently hydrating, try to hydrate this boundary.
+ // But only if this has a fallback.
+ if (nextProps.fallback !== undefined) {
+ tryToClaimNextHydratableInstance(workInProgress); // This could've been a dehydrated suspense component.
+ } // This is the initial mount. This branch is pretty simple because there's
+ // no previous state that needs to be preserved.
+
+
+ if (nextDidTimeout) {
+ // Mount separate fragments for primary and fallback children.
+ var nextFallbackChildren = nextProps.fallback;
+ var primaryChildFragment = createFiberFromFragment(null, mode, NoWork, null);
+ primaryChildFragment.return = workInProgress;
+
+ if ((workInProgress.mode & BlockingMode) === NoMode) {
+ // Outside of blocking mode, we commit the effects from the
+ // partially completed, timed-out tree, too.
+ var progressedState = workInProgress.memoizedState;
+ var progressedPrimaryChild = progressedState !== null ? workInProgress.child.child : workInProgress.child;
+ primaryChildFragment.child = progressedPrimaryChild;
+ var progressedChild = progressedPrimaryChild;
+
+ while (progressedChild !== null) {
+ progressedChild.return = primaryChildFragment;
+ progressedChild = progressedChild.sibling;
+ }
+ }
+
+ var fallbackChildFragment = createFiberFromFragment(nextFallbackChildren, mode, renderExpirationTime, null);
+ fallbackChildFragment.return = workInProgress;
+ primaryChildFragment.sibling = fallbackChildFragment; // Skip the primary children, and continue working on the
+ // fallback children.
+
+ workInProgress.memoizedState = SUSPENDED_MARKER;
+ workInProgress.child = primaryChildFragment;
+ return fallbackChildFragment;
+ } else {
+ // Mount the primary children without an intermediate fragment fiber.
+ var nextPrimaryChildren = nextProps.children;
+ workInProgress.memoizedState = null;
+ return workInProgress.child = mountChildFibers(workInProgress, null, nextPrimaryChildren, renderExpirationTime);
+ }
+ } else {
+ // This is an update. This branch is more complicated because we need to
+ // ensure the state of the primary children is preserved.
+ var prevState = current.memoizedState;
+
+ if (prevState !== null) {
+ // wrapped in a fragment fiber.
+
+
+ var currentPrimaryChildFragment = current.child;
+ var currentFallbackChildFragment = currentPrimaryChildFragment.sibling;
+
+ if (nextDidTimeout) {
+ // Still timed out. Reuse the current primary children by cloning
+ // its fragment. We're going to skip over these entirely.
+ var _nextFallbackChildren2 = nextProps.fallback;
+
+ var _primaryChildFragment2 = createWorkInProgress(currentPrimaryChildFragment, currentPrimaryChildFragment.pendingProps);
+
+ _primaryChildFragment2.return = workInProgress;
+
+ if ((workInProgress.mode & BlockingMode) === NoMode) {
+ // Outside of blocking mode, we commit the effects from the
+ // partially completed, timed-out tree, too.
+ var _progressedState = workInProgress.memoizedState;
+
+ var _progressedPrimaryChild = _progressedState !== null ? workInProgress.child.child : workInProgress.child;
+
+ if (_progressedPrimaryChild !== currentPrimaryChildFragment.child) {
+ _primaryChildFragment2.child = _progressedPrimaryChild;
+ var _progressedChild2 = _progressedPrimaryChild;
+
+ while (_progressedChild2 !== null) {
+ _progressedChild2.return = _primaryChildFragment2;
+ _progressedChild2 = _progressedChild2.sibling;
+ }
+ }
+ } // Because primaryChildFragment is a new fiber that we're inserting as the
+ // parent of a new tree, we need to set its treeBaseDuration.
+
+
+ if ( workInProgress.mode & ProfileMode) {
+ // treeBaseDuration is the sum of all the child tree base durations.
+ var _treeBaseDuration = 0;
+ var _hiddenChild = _primaryChildFragment2.child;
+
+ while (_hiddenChild !== null) {
+ _treeBaseDuration += _hiddenChild.treeBaseDuration;
+ _hiddenChild = _hiddenChild.sibling;
+ }
+
+ _primaryChildFragment2.treeBaseDuration = _treeBaseDuration;
+ } // Clone the fallback child fragment, too. These we'll continue
+ // working on.
+
+
+ var _fallbackChildFragment2 = createWorkInProgress(currentFallbackChildFragment, _nextFallbackChildren2);
+
+ _fallbackChildFragment2.return = workInProgress;
+ _primaryChildFragment2.sibling = _fallbackChildFragment2;
+ _primaryChildFragment2.childExpirationTime = NoWork; // Skip the primary children, and continue working on the
+ // fallback children.
+
+ workInProgress.memoizedState = SUSPENDED_MARKER;
+ workInProgress.child = _primaryChildFragment2;
+ return _fallbackChildFragment2;
+ } else {
+ // No longer suspended. Switch back to showing the primary children,
+ // and remove the intermediate fragment fiber.
+ var _nextPrimaryChildren = nextProps.children;
+ var currentPrimaryChild = currentPrimaryChildFragment.child;
+ var primaryChild = reconcileChildFibers(workInProgress, currentPrimaryChild, _nextPrimaryChildren, renderExpirationTime); // If this render doesn't suspend, we need to delete the fallback
+ // children. Wait until the complete phase, after we've confirmed the
+ // fallback is no longer needed.
+ // TODO: Would it be better to store the fallback fragment on
+ // the stateNode?
+ // Continue rendering the children, like we normally do.
+
+ workInProgress.memoizedState = null;
+ return workInProgress.child = primaryChild;
+ }
+ } else {
+ // The current tree has not already timed out. That means the primary
+ // children are not wrapped in a fragment fiber.
+ var _currentPrimaryChild = current.child;
+
+ if (nextDidTimeout) {
+ // Timed out. Wrap the children in a fragment fiber to keep them
+ // separate from the fallback children.
+ var _nextFallbackChildren3 = nextProps.fallback;
+
+ var _primaryChildFragment3 = createFiberFromFragment( // It shouldn't matter what the pending props are because we aren't
+ // going to render this fragment.
+ null, mode, NoWork, null);
+
+ _primaryChildFragment3.return = workInProgress;
+ _primaryChildFragment3.child = _currentPrimaryChild;
+
+ if (_currentPrimaryChild !== null) {
+ _currentPrimaryChild.return = _primaryChildFragment3;
+ } // Even though we're creating a new fiber, there are no new children,
+ // because we're reusing an already mounted tree. So we don't need to
+ // schedule a placement.
+ // primaryChildFragment.effectTag |= Placement;
+
+
+ if ((workInProgress.mode & BlockingMode) === NoMode) {
+ // Outside of blocking mode, we commit the effects from the
+ // partially completed, timed-out tree, too.
+ var _progressedState2 = workInProgress.memoizedState;
+
+ var _progressedPrimaryChild2 = _progressedState2 !== null ? workInProgress.child.child : workInProgress.child;
+
+ _primaryChildFragment3.child = _progressedPrimaryChild2;
+ var _progressedChild3 = _progressedPrimaryChild2;
+
+ while (_progressedChild3 !== null) {
+ _progressedChild3.return = _primaryChildFragment3;
+ _progressedChild3 = _progressedChild3.sibling;
+ }
+ } // Because primaryChildFragment is a new fiber that we're inserting as the
+ // parent of a new tree, we need to set its treeBaseDuration.
+
+
+ if ( workInProgress.mode & ProfileMode) {
+ // treeBaseDuration is the sum of all the child tree base durations.
+ var _treeBaseDuration2 = 0;
+ var _hiddenChild2 = _primaryChildFragment3.child;
+
+ while (_hiddenChild2 !== null) {
+ _treeBaseDuration2 += _hiddenChild2.treeBaseDuration;
+ _hiddenChild2 = _hiddenChild2.sibling;
+ }
+
+ _primaryChildFragment3.treeBaseDuration = _treeBaseDuration2;
+ } // Create a fragment from the fallback children, too.
+
+
+ var _fallbackChildFragment3 = createFiberFromFragment(_nextFallbackChildren3, mode, renderExpirationTime, null);
+
+ _fallbackChildFragment3.return = workInProgress;
+ _primaryChildFragment3.sibling = _fallbackChildFragment3;
+ _fallbackChildFragment3.effectTag |= Placement;
+ _primaryChildFragment3.childExpirationTime = NoWork; // Skip the primary children, and continue working on the
+ // fallback children.
+
+ workInProgress.memoizedState = SUSPENDED_MARKER;
+ workInProgress.child = _primaryChildFragment3;
+ return _fallbackChildFragment3;
+ } else {
+ // Still haven't timed out. Continue rendering the children, like we
+ // normally do.
+ workInProgress.memoizedState = null;
+ var _nextPrimaryChildren2 = nextProps.children;
+ return workInProgress.child = reconcileChildFibers(workInProgress, _currentPrimaryChild, _nextPrimaryChildren2, renderExpirationTime);
+ }
+ }
+ }
+ }
+
+ function scheduleWorkOnFiber(fiber, renderExpirationTime) {
+ if (fiber.expirationTime < renderExpirationTime) {
+ fiber.expirationTime = renderExpirationTime;
+ }
+
+ var alternate = fiber.alternate;
+
+ if (alternate !== null && alternate.expirationTime < renderExpirationTime) {
+ alternate.expirationTime = renderExpirationTime;
+ }
+
+ scheduleWorkOnParentPath(fiber.return, renderExpirationTime);
+ }
+
+ function propagateSuspenseContextChange(workInProgress, firstChild, renderExpirationTime) {
+ // Mark any Suspense boundaries with fallbacks as having work to do.
+ // If they were previously forced into fallbacks, they may now be able
+ // to unblock.
+ var node = firstChild;
+
+ while (node !== null) {
+ if (node.tag === SuspenseComponent) {
+ var state = node.memoizedState;
+
+ if (state !== null) {
+ scheduleWorkOnFiber(node, renderExpirationTime);
+ }
+ } else if (node.tag === SuspenseListComponent) {
+ // If the tail is hidden there might not be an Suspense boundaries
+ // to schedule work on. In this case we have to schedule it on the
+ // list itself.
+ // We don't have to traverse to the children of the list since
+ // the list will propagate the change when it rerenders.
+ scheduleWorkOnFiber(node, renderExpirationTime);
+ } else if (node.child !== null) {
+ node.child.return = node;
+ node = node.child;
+ continue;
+ }
+
+ if (node === workInProgress) {
+ return;
+ }
+
+ while (node.sibling === null) {
+ if (node.return === null || node.return === workInProgress) {
+ return;
+ }
+
+ node = node.return;
+ }
+
+ node.sibling.return = node.return;
+ node = node.sibling;
+ }
+ }
+
+ function findLastContentRow(firstChild) {
+ // This is going to find the last row among these children that is already
+ // showing content on the screen, as opposed to being in fallback state or
+ // new. If a row has multiple Suspense boundaries, any of them being in the
+ // fallback state, counts as the whole row being in a fallback state.
+ // Note that the "rows" will be workInProgress, but any nested children
+ // will still be current since we haven't rendered them yet. The mounted
+ // order may not be the same as the new order. We use the new order.
+ var row = firstChild;
+ var lastContentRow = null;
+
+ while (row !== null) {
+ var currentRow = row.alternate; // New rows can't be content rows.
+
+ if (currentRow !== null && findFirstSuspended(currentRow) === null) {
+ lastContentRow = row;
+ }
+
+ row = row.sibling;
+ }
+
+ return lastContentRow;
+ }
+
+ function validateRevealOrder(revealOrder) {
+ {
+ if (revealOrder !== undefined && revealOrder !== 'forwards' && revealOrder !== 'backwards' && revealOrder !== 'together' && !didWarnAboutRevealOrder[revealOrder]) {
+ didWarnAboutRevealOrder[revealOrder] = true;
+
+ if (typeof revealOrder === 'string') {
+ switch (revealOrder.toLowerCase()) {
+ case 'together':
+ case 'forwards':
+ case 'backwards':
+ {
+ error('"%s" is not a valid value for revealOrder on <SuspenseList />. ' + 'Use lowercase "%s" instead.', revealOrder, revealOrder.toLowerCase());
+
+ break;
+ }
+
+ case 'forward':
+ case 'backward':
+ {
+ error('"%s" is not a valid value for revealOrder on <SuspenseList />. ' + 'React uses the -s suffix in the spelling. Use "%ss" instead.', revealOrder, revealOrder.toLowerCase());
+
+ break;
+ }
+
+ default:
+ error('"%s" is not a supported revealOrder on <SuspenseList />. ' + 'Did you mean "together", "forwards" or "backwards"?', revealOrder);
+
+ break;
+ }
+ } else {
+ error('%s is not a supported value for revealOrder on <SuspenseList />. ' + 'Did you mean "together", "forwards" or "backwards"?', revealOrder);
+ }
+ }
+ }
+ }
+
+ function validateTailOptions(tailMode, revealOrder) {
+ {
+ if (tailMode !== undefined && !didWarnAboutTailOptions[tailMode]) {
+ if (tailMode !== 'collapsed' && tailMode !== 'hidden') {
+ didWarnAboutTailOptions[tailMode] = true;
+
+ error('"%s" is not a supported value for tail on <SuspenseList />. ' + 'Did you mean "collapsed" or "hidden"?', tailMode);
+ } else if (revealOrder !== 'forwards' && revealOrder !== 'backwards') {
+ didWarnAboutTailOptions[tailMode] = true;
+
+ error('<SuspenseList tail="%s" /> is only valid if revealOrder is ' + '"forwards" or "backwards". ' + 'Did you mean to specify revealOrder="forwards"?', tailMode);
+ }
+ }
+ }
+ }
+
+ function validateSuspenseListNestedChild(childSlot, index) {
+ {
+ var isArray = Array.isArray(childSlot);
+ var isIterable = !isArray && typeof getIteratorFn(childSlot) === 'function';
+
+ if (isArray || isIterable) {
+ var type = isArray ? 'array' : 'iterable';
+
+ error('A nested %s was passed to row #%s in <SuspenseList />. Wrap it in ' + 'an additional SuspenseList to configure its revealOrder: ' + '<SuspenseList revealOrder=...> ... ' + '<SuspenseList revealOrder=...>{%s}</SuspenseList> ... ' + '</SuspenseList>', type, index, type);
+
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ function validateSuspenseListChildren(children, revealOrder) {
+ {
+ if ((revealOrder === 'forwards' || revealOrder === 'backwards') && children !== undefined && children !== null && children !== false) {
+ if (Array.isArray(children)) {
+ for (var i = 0; i < children.length; i++) {
+ if (!validateSuspenseListNestedChild(children[i], i)) {
+ return;
+ }
+ }
+ } else {
+ var iteratorFn = getIteratorFn(children);
+
+ if (typeof iteratorFn === 'function') {
+ var childrenIterator = iteratorFn.call(children);
+
+ if (childrenIterator) {
+ var step = childrenIterator.next();
+ var _i = 0;
+
+ for (; !step.done; step = childrenIterator.next()) {
+ if (!validateSuspenseListNestedChild(step.value, _i)) {
+ return;
+ }
+
+ _i++;
+ }
+ }
+ } else {
+ error('A single row was passed to a <SuspenseList revealOrder="%s" />. ' + 'This is not useful since it needs multiple rows. ' + 'Did you mean to pass multiple children or an array?', revealOrder);
+ }
+ }
+ }
+ }
+ }
+
+ function initSuspenseListRenderState(workInProgress, isBackwards, tail, lastContentRow, tailMode, lastEffectBeforeRendering) {
+ var renderState = workInProgress.memoizedState;
+
+ if (renderState === null) {
+ workInProgress.memoizedState = {
+ isBackwards: isBackwards,
+ rendering: null,
+ renderingStartTime: 0,
+ last: lastContentRow,
+ tail: tail,
+ tailExpiration: 0,
+ tailMode: tailMode,
+ lastEffect: lastEffectBeforeRendering
+ };
+ } else {
+ // We can reuse the existing object from previous renders.
+ renderState.isBackwards = isBackwards;
+ renderState.rendering = null;
+ renderState.renderingStartTime = 0;
+ renderState.last = lastContentRow;
+ renderState.tail = tail;
+ renderState.tailExpiration = 0;
+ renderState.tailMode = tailMode;
+ renderState.lastEffect = lastEffectBeforeRendering;
+ }
+ } // This can end up rendering this component multiple passes.
+ // The first pass splits the children fibers into two sets. A head and tail.
+ // We first render the head. If anything is in fallback state, we do another
+ // pass through beginWork to rerender all children (including the tail) with
+ // the force suspend context. If the first render didn't have anything in
+ // in fallback state. Then we render each row in the tail one-by-one.
+ // That happens in the completeWork phase without going back to beginWork.
+
+
+ function updateSuspenseListComponent(current, workInProgress, renderExpirationTime) {
+ var nextProps = workInProgress.pendingProps;
+ var revealOrder = nextProps.revealOrder;
+ var tailMode = nextProps.tail;
+ var newChildren = nextProps.children;
+ validateRevealOrder(revealOrder);
+ validateTailOptions(tailMode, revealOrder);
+ validateSuspenseListChildren(newChildren, revealOrder);
+ reconcileChildren(current, workInProgress, newChildren, renderExpirationTime);
+ var suspenseContext = suspenseStackCursor.current;
+ var shouldForceFallback = hasSuspenseContext(suspenseContext, ForceSuspenseFallback);
+
+ if (shouldForceFallback) {
+ suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback);
+ workInProgress.effectTag |= DidCapture;
+ } else {
+ var didSuspendBefore = current !== null && (current.effectTag & DidCapture) !== NoEffect;
+
+ if (didSuspendBefore) {
+ // If we previously forced a fallback, we need to schedule work
+ // on any nested boundaries to let them know to try to render
+ // again. This is the same as context updating.
+ propagateSuspenseContextChange(workInProgress, workInProgress.child, renderExpirationTime);
+ }
+
+ suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
+ }
+
+ pushSuspenseContext(workInProgress, suspenseContext);
+
+ if ((workInProgress.mode & BlockingMode) === NoMode) {
+ // Outside of blocking mode, SuspenseList doesn't work so we just
+ // use make it a noop by treating it as the default revealOrder.
+ workInProgress.memoizedState = null;
+ } else {
+ switch (revealOrder) {
+ case 'forwards':
+ {
+ var lastContentRow = findLastContentRow(workInProgress.child);
+ var tail;
+
+ if (lastContentRow === null) {
+ // The whole list is part of the tail.
+ // TODO: We could fast path by just rendering the tail now.
+ tail = workInProgress.child;
+ workInProgress.child = null;
+ } else {
+ // Disconnect the tail rows after the content row.
+ // We're going to render them separately later.
+ tail = lastContentRow.sibling;
+ lastContentRow.sibling = null;
+ }
+
+ initSuspenseListRenderState(workInProgress, false, // isBackwards
+ tail, lastContentRow, tailMode, workInProgress.lastEffect);
+ break;
+ }
+
+ case 'backwards':
+ {
+ // We're going to find the first row that has existing content.
+ // At the same time we're going to reverse the list of everything
+ // we pass in the meantime. That's going to be our tail in reverse
+ // order.
+ var _tail = null;
+ var row = workInProgress.child;
+ workInProgress.child = null;
+
+ while (row !== null) {
+ var currentRow = row.alternate; // New rows can't be content rows.
+
+ if (currentRow !== null && findFirstSuspended(currentRow) === null) {
+ // This is the beginning of the main content.
+ workInProgress.child = row;
+ break;
+ }
+
+ var nextRow = row.sibling;
+ row.sibling = _tail;
+ _tail = row;
+ row = nextRow;
+ } // TODO: If workInProgress.child is null, we can continue on the tail immediately.
+
+
+ initSuspenseListRenderState(workInProgress, true, // isBackwards
+ _tail, null, // last
+ tailMode, workInProgress.lastEffect);
+ break;
+ }
+
+ case 'together':
+ {
+ initSuspenseListRenderState(workInProgress, false, // isBackwards
+ null, // tail
+ null, // last
+ undefined, workInProgress.lastEffect);
+ break;
+ }
+
+ default:
+ {
+ // The default reveal order is the same as not having
+ // a boundary.
+ workInProgress.memoizedState = null;
+ }
+ }
+ }
+
+ return workInProgress.child;
+ }
+
+ function updatePortalComponent(current, workInProgress, renderExpirationTime) {
+ pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
+ var nextChildren = workInProgress.pendingProps;
+
+ if (current === null) {
+ // Portals are special because we don't append the children during mount
+ // but at commit. Therefore we need to track insertions which the normal
+ // flow doesn't do during mount. This doesn't happen at the root because
+ // the root always starts with a "current" with a null child.
+ // TODO: Consider unifying this with how the root works.
+ workInProgress.child = reconcileChildFibers(workInProgress, null, nextChildren, renderExpirationTime);
+ } else {
+ reconcileChildren(current, workInProgress, nextChildren, renderExpirationTime);
+ }
+
+ return workInProgress.child;
+ }
+
+ function updateContextProvider(current, workInProgress, renderExpirationTime) {
+ var providerType = workInProgress.type;
+ var context = providerType._context;
+ var newProps = workInProgress.pendingProps;
+ var oldProps = workInProgress.memoizedProps;
+ var newValue = newProps.value;
+
+ {
+ var providerPropTypes = workInProgress.type.propTypes;
+
+ if (providerPropTypes) {
+ checkPropTypes_1(providerPropTypes, newProps, 'prop', 'Context.Provider', getCurrentFiberStackInDev);
+ }
+ }
+
+ pushProvider(workInProgress, newValue);
+
+ if (oldProps !== null) {
+ var oldValue = oldProps.value;
+ var changedBits = calculateChangedBits(context, newValue, oldValue);
+
+ if (changedBits === 0) {
+ // No change. Bailout early if children are the same.
+ if (oldProps.children === newProps.children && !hasContextChanged()) {
+ return bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime);
+ }
+ } else {
+ // The context value changed. Search for matching consumers and schedule
+ // them to update.
+ propagateContextChange(workInProgress, context, changedBits, renderExpirationTime);
+ }
+ }
+
+ var newChildren = newProps.children;
+ reconcileChildren(current, workInProgress, newChildren, renderExpirationTime);
+ return workInProgress.child;
+ }
+
+ var hasWarnedAboutUsingContextAsConsumer = false;
+
+ function updateContextConsumer(current, workInProgress, renderExpirationTime) {
+ var context = workInProgress.type; // The logic below for Context differs depending on PROD or DEV mode. In
+ // DEV mode, we create a separate object for Context.Consumer that acts
+ // like a proxy to Context. This proxy object adds unnecessary code in PROD
+ // so we use the old behaviour (Context.Consumer references Context) to
+ // reduce size and overhead. The separate object references context via
+ // a property called "_context", which also gives us the ability to check
+ // in DEV mode if this property exists or not and warn if it does not.
+
+ {
+ if (context._context === undefined) {
+ // This may be because it's a Context (rather than a Consumer).
+ // Or it may be because it's older React where they're the same thing.
+ // We only want to warn if we're sure it's a new React.
+ if (context !== context.Consumer) {
+ if (!hasWarnedAboutUsingContextAsConsumer) {
+ hasWarnedAboutUsingContextAsConsumer = true;
+
+ error('Rendering <Context> directly is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?');
+ }
+ }
+ } else {
+ context = context._context;
+ }
+ }
+
+ var newProps = workInProgress.pendingProps;
+ var render = newProps.children;
+
+ {
+ if (typeof render !== 'function') {
+ error('A context consumer was rendered with multiple children, or a child ' + "that isn't a function. A context consumer expects a single child " + 'that is a function. If you did pass a function, make sure there ' + 'is no trailing or leading whitespace around it.');
+ }
+ }
+
+ prepareToReadContext(workInProgress, renderExpirationTime);
+ var newValue = readContext(context, newProps.unstable_observedBits);
+ var newChildren;
+
+ {
+ ReactCurrentOwner$1.current = workInProgress;
+ setIsRendering(true);
+ newChildren = render(newValue);
+ setIsRendering(false);
+ } // React DevTools reads this flag.
+
+
+ workInProgress.effectTag |= PerformedWork;
+ reconcileChildren(current, workInProgress, newChildren, renderExpirationTime);
+ return workInProgress.child;
+ }
+
+ function markWorkInProgressReceivedUpdate() {
+ didReceiveUpdate = true;
+ }
+
+ function bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime) {
+ cancelWorkTimer(workInProgress);
+
+ if (current !== null) {
+ // Reuse previous dependencies
+ workInProgress.dependencies = current.dependencies;
+ }
+
+ {
+ // Don't update "base" render times for bailouts.
+ stopProfilerTimerIfRunning();
+ }
+
+ var updateExpirationTime = workInProgress.expirationTime;
+
+ if (updateExpirationTime !== NoWork) {
+ markUnprocessedUpdateTime(updateExpirationTime);
+ } // Check if the children have any pending work.
+
+
+ var childExpirationTime = workInProgress.childExpirationTime;
+
+ if (childExpirationTime < renderExpirationTime) {
+ // The children don't have any work either. We can skip them.
+ // TODO: Once we add back resuming, we should check if the children are
+ // a work-in-progress set. If so, we need to transfer their effects.
+ return null;
+ } else {
+ // This fiber doesn't have work, but its subtree does. Clone the child
+ // fibers and continue.
+ cloneChildFibers(current, workInProgress);
+ return workInProgress.child;
+ }
+ }
+
+ function remountFiber(current, oldWorkInProgress, newWorkInProgress) {
+ {
+ var returnFiber = oldWorkInProgress.return;
+
+ if (returnFiber === null) {
+ throw new Error('Cannot swap the root fiber.');
+ } // Disconnect from the old current.
+ // It will get deleted.
+
+
+ current.alternate = null;
+ oldWorkInProgress.alternate = null; // Connect to the new tree.
+
+ newWorkInProgress.index = oldWorkInProgress.index;
+ newWorkInProgress.sibling = oldWorkInProgress.sibling;
+ newWorkInProgress.return = oldWorkInProgress.return;
+ newWorkInProgress.ref = oldWorkInProgress.ref; // Replace the child/sibling pointers above it.
+
+ if (oldWorkInProgress === returnFiber.child) {
+ returnFiber.child = newWorkInProgress;
+ } else {
+ var prevSibling = returnFiber.child;
+
+ if (prevSibling === null) {
+ throw new Error('Expected parent to have a child.');
+ }
+
+ while (prevSibling.sibling !== oldWorkInProgress) {
+ prevSibling = prevSibling.sibling;
+
+ if (prevSibling === null) {
+ throw new Error('Expected to find the previous sibling.');
+ }
+ }
+
+ prevSibling.sibling = newWorkInProgress;
+ } // Delete the old fiber and place the new one.
+ // Since the old fiber is disconnected, we have to schedule it manually.
+
+
+ var last = returnFiber.lastEffect;
+
+ if (last !== null) {
+ last.nextEffect = current;
+ returnFiber.lastEffect = current;
+ } else {
+ returnFiber.firstEffect = returnFiber.lastEffect = current;
+ }
+
+ current.nextEffect = null;
+ current.effectTag = Deletion;
+ newWorkInProgress.effectTag |= Placement; // Restart work from the new fiber.
+
+ return newWorkInProgress;
+ }
+ }
+
+ function beginWork(current, workInProgress, renderExpirationTime) {
+ var updateExpirationTime = workInProgress.expirationTime;
+
+ {
+ if (workInProgress._debugNeedsRemount && current !== null) {
+ // This will restart the begin phase with a new fiber.
+ return remountFiber(current, workInProgress, createFiberFromTypeAndProps(workInProgress.type, workInProgress.key, workInProgress.pendingProps, workInProgress._debugOwner || null, workInProgress.mode, workInProgress.expirationTime));
+ }
+ }
+
+ if (current !== null) {
+ var oldProps = current.memoizedProps;
+ var newProps = workInProgress.pendingProps;
+
+ if (oldProps !== newProps || hasContextChanged() || ( // Force a re-render if the implementation changed due to hot reload:
+ workInProgress.type !== current.type )) {
+ // If props or context changed, mark the fiber as having performed work.
+ // This may be unset if the props are determined to be equal later (memo).
+ didReceiveUpdate = true;
+ } else if (updateExpirationTime < renderExpirationTime) {
+ didReceiveUpdate = false; // This fiber does not have any pending work. Bailout without entering
+ // the begin phase. There's still some bookkeeping we that needs to be done
+ // in this optimized path, mostly pushing stuff onto the stack.
+
+ switch (workInProgress.tag) {
+ case HostRoot:
+ pushHostRootContext(workInProgress);
+ resetHydrationState();
+ break;
+
+ case HostComponent:
+ pushHostContext(workInProgress);
+
+ if (workInProgress.mode & ConcurrentMode && renderExpirationTime !== Never && shouldDeprioritizeSubtree(workInProgress.type, newProps)) {
+ {
+ markSpawnedWork(Never);
+ } // Schedule this fiber to re-render at offscreen priority. Then bailout.
+
+
+ workInProgress.expirationTime = workInProgress.childExpirationTime = Never;
+ return null;
+ }
+
+ break;
+
+ case ClassComponent:
+ {
+ var Component = workInProgress.type;
+
+ if (isContextProvider(Component)) {
+ pushContextProvider(workInProgress);
+ }
+
+ break;
+ }
+
+ case HostPortal:
+ pushHostContainer(workInProgress, workInProgress.stateNode.containerInfo);
+ break;
+
+ case ContextProvider:
+ {
+ var newValue = workInProgress.memoizedProps.value;
+ pushProvider(workInProgress, newValue);
+ break;
+ }
+
+ case Profiler:
+ {
+ // Profiler should only call onRender when one of its descendants actually rendered.
+ var hasChildWork = workInProgress.childExpirationTime >= renderExpirationTime;
+
+ if (hasChildWork) {
+ workInProgress.effectTag |= Update;
+ }
+ }
+
+ break;
+
+ case SuspenseComponent:
+ {
+ var state = workInProgress.memoizedState;
+
+ if (state !== null) {
+ // whether to retry the primary children, or to skip over it and
+ // go straight to the fallback. Check the priority of the primary
+ // child fragment.
+
+
+ var primaryChildFragment = workInProgress.child;
+ var primaryChildExpirationTime = primaryChildFragment.childExpirationTime;
+
+ if (primaryChildExpirationTime !== NoWork && primaryChildExpirationTime >= renderExpirationTime) {
+ // The primary children have pending work. Use the normal path
+ // to attempt to render the primary children again.
+ return updateSuspenseComponent(current, workInProgress, renderExpirationTime);
+ } else {
+ pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current)); // The primary children do not have pending work with sufficient
+ // priority. Bailout.
+
+ var child = bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime);
+
+ if (child !== null) {
+ // The fallback children have pending work. Skip over the
+ // primary children and work on the fallback.
+ return child.sibling;
+ } else {
+ return null;
+ }
+ }
+ } else {
+ pushSuspenseContext(workInProgress, setDefaultShallowSuspenseContext(suspenseStackCursor.current));
+ }
+
+ break;
+ }
+
+ case SuspenseListComponent:
+ {
+ var didSuspendBefore = (current.effectTag & DidCapture) !== NoEffect;
+
+ var _hasChildWork = workInProgress.childExpirationTime >= renderExpirationTime;
+
+ if (didSuspendBefore) {
+ if (_hasChildWork) {
+ // If something was in fallback state last time, and we have all the
+ // same children then we're still in progressive loading state.
+ // Something might get unblocked by state updates or retries in the
+ // tree which will affect the tail. So we need to use the normal
+ // path to compute the correct tail.
+ return updateSuspenseListComponent(current, workInProgress, renderExpirationTime);
+ } // If none of the children had any work, that means that none of
+ // them got retried so they'll still be blocked in the same way
+ // as before. We can fast bail out.
+
+
+ workInProgress.effectTag |= DidCapture;
+ } // If nothing suspended before and we're rendering the same children,
+ // then the tail doesn't matter. Anything new that suspends will work
+ // in the "together" mode, so we can continue from the state we had.
+
+
+ var renderState = workInProgress.memoizedState;
+
+ if (renderState !== null) {
+ // Reset to the "together" mode in case we've started a different
+ // update in the past but didn't complete it.
+ renderState.rendering = null;
+ renderState.tail = null;
+ }
+
+ pushSuspenseContext(workInProgress, suspenseStackCursor.current);
+
+ if (_hasChildWork) {
+ break;
+ } else {
+ // If none of the children had any work, that means that none of
+ // them got retried so they'll still be blocked in the same way
+ // as before. We can fast bail out.
+ return null;
+ }
+ }
+ }
+
+ return bailoutOnAlreadyFinishedWork(current, workInProgress, renderExpirationTime);
+ } else {
+ // An update was scheduled on this fiber, but there are no new props
+ // nor legacy context. Set this to false. If an update queue or context
+ // consumer produces a changed value, it will set this to true. Otherwise,
+ // the component will assume the children have not changed and bail out.
+ didReceiveUpdate = false;
+ }
+ } else {
+ didReceiveUpdate = false;
+ } // Before entering the begin phase, clear pending update priority.
+ // TODO: This assumes that we're about to evaluate the component and process
+ // the update queue. However, there's an exception: SimpleMemoComponent
+ // sometimes bails out later in the begin phase. This indicates that we should
+ // move this assignment out of the common path and into each branch.
+
+
+ workInProgress.expirationTime = NoWork;
+
+ switch (workInProgress.tag) {
+ case IndeterminateComponent:
+ {
+ return mountIndeterminateComponent(current, workInProgress, workInProgress.type, renderExpirationTime);
+ }
+
+ case LazyComponent:
+ {
+ var elementType = workInProgress.elementType;
+ return mountLazyComponent(current, workInProgress, elementType, updateExpirationTime, renderExpirationTime);
+ }
+
+ case FunctionComponent:
+ {
+ var _Component = workInProgress.type;
+ var unresolvedProps = workInProgress.pendingProps;
+ var resolvedProps = workInProgress.elementType === _Component ? unresolvedProps : resolveDefaultProps(_Component, unresolvedProps);
+ return updateFunctionComponent(current, workInProgress, _Component, resolvedProps, renderExpirationTime);
+ }
+
+ case ClassComponent:
+ {
+ var _Component2 = workInProgress.type;
+ var _unresolvedProps = workInProgress.pendingProps;
+
+ var _resolvedProps = workInProgress.elementType === _Component2 ? _unresolvedProps : resolveDefaultProps(_Component2, _unresolvedProps);
+
+ return updateClassComponent(current, workInProgress, _Component2, _resolvedProps, renderExpirationTime);
+ }
+
+ case HostRoot:
+ return updateHostRoot(current, workInProgress, renderExpirationTime);
+
+ case HostComponent:
+ return updateHostComponent(current, workInProgress, renderExpirationTime);
+
+ case HostText:
+ return updateHostText(current, workInProgress);
+
+ case SuspenseComponent:
+ return updateSuspenseComponent(current, workInProgress, renderExpirationTime);
+
+ case HostPortal:
+ return updatePortalComponent(current, workInProgress, renderExpirationTime);
+
+ case ForwardRef:
+ {
+ var type = workInProgress.type;
+ var _unresolvedProps2 = workInProgress.pendingProps;
+
+ var _resolvedProps2 = workInProgress.elementType === type ? _unresolvedProps2 : resolveDefaultProps(type, _unresolvedProps2);
+
+ return updateForwardRef(current, workInProgress, type, _resolvedProps2, renderExpirationTime);
+ }
+
+ case Fragment:
+ return updateFragment(current, workInProgress, renderExpirationTime);
+
+ case Mode:
+ return updateMode(current, workInProgress, renderExpirationTime);
+
+ case Profiler:
+ return updateProfiler(current, workInProgress, renderExpirationTime);
+
+ case ContextProvider:
+ return updateContextProvider(current, workInProgress, renderExpirationTime);
+
+ case ContextConsumer:
+ return updateContextConsumer(current, workInProgress, renderExpirationTime);
+
+ case MemoComponent:
+ {
+ var _type2 = workInProgress.type;
+ var _unresolvedProps3 = workInProgress.pendingProps; // Resolve outer props first, then resolve inner props.
+
+ var _resolvedProps3 = resolveDefaultProps(_type2, _unresolvedProps3);
+
+ {
+ if (workInProgress.type !== workInProgress.elementType) {
+ var outerPropTypes = _type2.propTypes;
+
+ if (outerPropTypes) {
+ checkPropTypes_1(outerPropTypes, _resolvedProps3, // Resolved for outer only
+ 'prop', getComponentName(_type2), getCurrentFiberStackInDev);
+ }
+ }
+ }
+
+ _resolvedProps3 = resolveDefaultProps(_type2.type, _resolvedProps3);
+ return updateMemoComponent(current, workInProgress, _type2, _resolvedProps3, updateExpirationTime, renderExpirationTime);
+ }
+
+ case SimpleMemoComponent:
+ {
+ return updateSimpleMemoComponent(current, workInProgress, workInProgress.type, workInProgress.pendingProps, updateExpirationTime, renderExpirationTime);
+ }
+
+ case IncompleteClassComponent:
+ {
+ var _Component3 = workInProgress.type;
+ var _unresolvedProps4 = workInProgress.pendingProps;
+
+ var _resolvedProps4 = workInProgress.elementType === _Component3 ? _unresolvedProps4 : resolveDefaultProps(_Component3, _unresolvedProps4);
+
+ return mountIncompleteClassComponent(current, workInProgress, _Component3, _resolvedProps4, renderExpirationTime);
+ }
+
+ case SuspenseListComponent:
+ {
+ return updateSuspenseListComponent(current, workInProgress, renderExpirationTime);
+ }
+ }
+
+ {
+ {
+ throw Error( "Unknown unit of work tag (" + workInProgress.tag + "). This error is likely caused by a bug in React. Please file an issue." );
+ }
+ }
+ }
+
+ function markUpdate(workInProgress) {
+ // Tag the fiber with an update effect. This turns a Placement into
+ // a PlacementAndUpdate.
+ workInProgress.effectTag |= Update;
+ }
+
+ function markRef$1(workInProgress) {
+ workInProgress.effectTag |= Ref;
+ }
+
+ var appendAllChildren;
+ var updateHostContainer;
+ var updateHostComponent$1;
+ var updateHostText$1;
+
+ {
+ // Mutation mode
+ appendAllChildren = function (parent, workInProgress, needsVisibilityToggle, isHidden) {
+ // We only have the top Fiber that was created but we need recurse down its
+ // children to find all the terminal nodes.
+ var node = workInProgress.child;
+
+ while (node !== null) {
+ if (node.tag === HostComponent || node.tag === HostText) {
+ appendInitialChild(parent, node.stateNode);
+ } else if (node.tag === HostPortal) ; else if (node.child !== null) {
+ node.child.return = node;
+ node = node.child;
+ continue;
+ }
+
+ if (node === workInProgress) {
+ return;
+ }
+
+ while (node.sibling === null) {
+ if (node.return === null || node.return === workInProgress) {
+ return;
+ }
+
+ node = node.return;
+ }
+
+ node.sibling.return = node.return;
+ node = node.sibling;
+ }
+ };
+
+ updateHostContainer = function (workInProgress) {// Noop
+ };
+
+ updateHostComponent$1 = function (current, workInProgress, type, newProps, rootContainerInstance) {
+ // If we have an alternate, that means this is an update and we need to
+ // schedule a side-effect to do the updates.
+ var oldProps = current.memoizedProps;
+
+ if (oldProps === newProps) {
+ // In mutation mode, this is sufficient for a bailout because
+ // we won't touch this node even if children changed.
+ return;
+ } // If we get updated because one of our children updated, we don't
+ // have newProps so we'll have to reuse them.
+ // TODO: Split the update API as separate for the props vs. children.
+ // Even better would be if children weren't special cased at all tho.
+
+
+ var instance = workInProgress.stateNode;
+ var currentHostContext = getHostContext(); // TODO: Experiencing an error where oldProps is null. Suggests a host
+ // component is hitting the resume path. Figure out why. Possibly
+ // related to `hidden`.
+
+ var updatePayload = prepareUpdate(instance, type, oldProps, newProps, rootContainerInstance, currentHostContext); // TODO: Type this specific to this type of component.
+
+ workInProgress.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there
+ // is a new ref we mark this as an update. All the work is done in commitWork.
+
+ if (updatePayload) {
+ markUpdate(workInProgress);
+ }
+ };
+
+ updateHostText$1 = function (current, workInProgress, oldText, newText) {
+ // If the text differs, mark it as an update. All the work in done in commitWork.
+ if (oldText !== newText) {
+ markUpdate(workInProgress);
+ }
+ };
+ }
+
+ function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) {
+ switch (renderState.tailMode) {
+ case 'hidden':
+ {
+ // Any insertions at the end of the tail list after this point
+ // should be invisible. If there are already mounted boundaries
+ // anything before them are not considered for collapsing.
+ // Therefore we need to go through the whole tail to find if
+ // there are any.
+ var tailNode = renderState.tail;
+ var lastTailNode = null;
+
+ while (tailNode !== null) {
+ if (tailNode.alternate !== null) {
+ lastTailNode = tailNode;
+ }
+
+ tailNode = tailNode.sibling;
+ } // Next we're simply going to delete all insertions after the
+ // last rendered item.
+
+
+ if (lastTailNode === null) {
+ // All remaining items in the tail are insertions.
+ renderState.tail = null;
+ } else {
+ // Detach the insertion after the last node that was already
+ // inserted.
+ lastTailNode.sibling = null;
+ }
+
+ break;
+ }
+
+ case 'collapsed':
+ {
+ // Any insertions at the end of the tail list after this point
+ // should be invisible. If there are already mounted boundaries
+ // anything before them are not considered for collapsing.
+ // Therefore we need to go through the whole tail to find if
+ // there are any.
+ var _tailNode = renderState.tail;
+ var _lastTailNode = null;
+
+ while (_tailNode !== null) {
+ if (_tailNode.alternate !== null) {
+ _lastTailNode = _tailNode;
+ }
+
+ _tailNode = _tailNode.sibling;
+ } // Next we're simply going to delete all insertions after the
+ // last rendered item.
+
+
+ if (_lastTailNode === null) {
+ // All remaining items in the tail are insertions.
+ if (!hasRenderedATailFallback && renderState.tail !== null) {
+ // We suspended during the head. We want to show at least one
+ // row at the tail. So we'll keep on and cut off the rest.
+ renderState.tail.sibling = null;
+ } else {
+ renderState.tail = null;
+ }
+ } else {
+ // Detach the insertion after the last node that was already
+ // inserted.
+ _lastTailNode.sibling = null;
+ }
+
+ break;
+ }
+ }
+ }
+
+ function completeWork(current, workInProgress, renderExpirationTime) {
+ var newProps = workInProgress.pendingProps;
+
+ switch (workInProgress.tag) {
+ case IndeterminateComponent:
+ case LazyComponent:
+ case SimpleMemoComponent:
+ case FunctionComponent:
+ case ForwardRef:
+ case Fragment:
+ case Mode:
+ case Profiler:
+ case ContextConsumer:
+ case MemoComponent:
+ return null;
+
+ case ClassComponent:
+ {
+ var Component = workInProgress.type;
+
+ if (isContextProvider(Component)) {
+ popContext(workInProgress);
+ }
+
+ return null;
+ }
+
+ case HostRoot:
+ {
+ popHostContainer(workInProgress);
+ popTopLevelContextObject(workInProgress);
+ var fiberRoot = workInProgress.stateNode;
+
+ if (fiberRoot.pendingContext) {
+ fiberRoot.context = fiberRoot.pendingContext;
+ fiberRoot.pendingContext = null;
+ }
+
+ if (current === null || current.child === null) {
+ // If we hydrated, pop so that we can delete any remaining children
+ // that weren't hydrated.
+ var wasHydrated = popHydrationState(workInProgress);
+
+ if (wasHydrated) {
+ // If we hydrated, then we'll need to schedule an update for
+ // the commit side-effects on the root.
+ markUpdate(workInProgress);
+ }
+ }
+
+ updateHostContainer(workInProgress);
+ return null;
+ }
+
+ case HostComponent:
+ {
+ popHostContext(workInProgress);
+ var rootContainerInstance = getRootHostContainer();
+ var type = workInProgress.type;
+
+ if (current !== null && workInProgress.stateNode != null) {
+ updateHostComponent$1(current, workInProgress, type, newProps, rootContainerInstance);
+
+ if (current.ref !== workInProgress.ref) {
+ markRef$1(workInProgress);
+ }
+ } else {
+ if (!newProps) {
+ if (!(workInProgress.stateNode !== null)) {
+ {
+ throw Error( "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." );
+ }
+ } // This can happen when we abort work.
+
+
+ return null;
+ }
+
+ var currentHostContext = getHostContext(); // TODO: Move createInstance to beginWork and keep it on a context
+ // "stack" as the parent. Then append children as we go in beginWork
+ // or completeWork depending on whether we want to add them top->down or
+ // bottom->up. Top->down is faster in IE11.
+
+ var _wasHydrated = popHydrationState(workInProgress);
+
+ if (_wasHydrated) {
+ // TODO: Move this and createInstance step into the beginPhase
+ // to consolidate.
+ if (prepareToHydrateHostInstance(workInProgress, rootContainerInstance, currentHostContext)) {
+ // If changes to the hydrated node need to be applied at the
+ // commit-phase we mark this as such.
+ markUpdate(workInProgress);
+ }
+ } else {
+ var instance = createInstance(type, newProps, rootContainerInstance, currentHostContext, workInProgress);
+ appendAllChildren(instance, workInProgress, false, false); // This needs to be set before we mount Flare event listeners
+
+ workInProgress.stateNode = instance;
+ // (eg DOM renderer supports auto-focus for certain elements).
+ // Make sure such renderers get scheduled for later work.
+
+
+ if (finalizeInitialChildren(instance, type, newProps, rootContainerInstance)) {
+ markUpdate(workInProgress);
+ }
+ }
+
+ if (workInProgress.ref !== null) {
+ // If there is a ref on a host node we need to schedule a callback
+ markRef$1(workInProgress);
+ }
+ }
+
+ return null;
+ }
+
+ case HostText:
+ {
+ var newText = newProps;
+
+ if (current && workInProgress.stateNode != null) {
+ var oldText = current.memoizedProps; // If we have an alternate, that means this is an update and we need
+ // to schedule a side-effect to do the updates.
+
+ updateHostText$1(current, workInProgress, oldText, newText);
+ } else {
+ if (typeof newText !== 'string') {
+ if (!(workInProgress.stateNode !== null)) {
+ {
+ throw Error( "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue." );
+ }
+ } // This can happen when we abort work.
+
+ }
+
+ var _rootContainerInstance = getRootHostContainer();
+
+ var _currentHostContext = getHostContext();
+
+ var _wasHydrated2 = popHydrationState(workInProgress);
+
+ if (_wasHydrated2) {
+ if (prepareToHydrateHostTextInstance(workInProgress)) {
+ markUpdate(workInProgress);
+ }
+ } else {
+ workInProgress.stateNode = createTextInstance(newText, _rootContainerInstance, _currentHostContext, workInProgress);
+ }
+ }
+
+ return null;
+ }
+
+ case SuspenseComponent:
+ {
+ popSuspenseContext(workInProgress);
+ var nextState = workInProgress.memoizedState;
+
+ if ((workInProgress.effectTag & DidCapture) !== NoEffect) {
+ // Something suspended. Re-render with the fallback children.
+ workInProgress.expirationTime = renderExpirationTime; // Do not reset the effect list.
+
+ return workInProgress;
+ }
+
+ var nextDidTimeout = nextState !== null;
+ var prevDidTimeout = false;
+
+ if (current === null) {
+ if (workInProgress.memoizedProps.fallback !== undefined) {
+ popHydrationState(workInProgress);
+ }
+ } else {
+ var prevState = current.memoizedState;
+ prevDidTimeout = prevState !== null;
+
+ if (!nextDidTimeout && prevState !== null) {
+ // We just switched from the fallback to the normal children.
+ // Delete the fallback.
+ // TODO: Would it be better to store the fallback fragment on
+ // the stateNode during the begin phase?
+ var currentFallbackChild = current.child.sibling;
+
+ if (currentFallbackChild !== null) {
+ // Deletions go at the beginning of the return fiber's effect list
+ var first = workInProgress.firstEffect;
+
+ if (first !== null) {
+ workInProgress.firstEffect = currentFallbackChild;
+ currentFallbackChild.nextEffect = first;
+ } else {
+ workInProgress.firstEffect = workInProgress.lastEffect = currentFallbackChild;
+ currentFallbackChild.nextEffect = null;
+ }
+
+ currentFallbackChild.effectTag = Deletion;
+ }
+ }
+ }
+
+ if (nextDidTimeout && !prevDidTimeout) {
+ // If this subtreee is running in blocking mode we can suspend,
+ // otherwise we won't suspend.
+ // TODO: This will still suspend a synchronous tree if anything
+ // in the concurrent tree already suspended during this render.
+ // This is a known bug.
+ if ((workInProgress.mode & BlockingMode) !== NoMode) {
+ // TODO: Move this back to throwException because this is too late
+ // if this is a large tree which is common for initial loads. We
+ // don't know if we should restart a render or not until we get
+ // this marker, and this is too late.
+ // If this render already had a ping or lower pri updates,
+ // and this is the first time we know we're going to suspend we
+ // should be able to immediately restart from within throwException.
+ var hasInvisibleChildContext = current === null && workInProgress.memoizedProps.unstable_avoidThisFallback !== true;
+
+ if (hasInvisibleChildContext || hasSuspenseContext(suspenseStackCursor.current, InvisibleParentSuspenseContext)) {
+ // If this was in an invisible tree or a new render, then showing
+ // this boundary is ok.
+ renderDidSuspend();
+ } else {
+ // Otherwise, we're going to have to hide content so we should
+ // suspend for longer if possible.
+ renderDidSuspendDelayIfPossible();
+ }
+ }
+ }
+
+ {
+ // TODO: Only schedule updates if these values are non equal, i.e. it changed.
+ if (nextDidTimeout || prevDidTimeout) {
+ // If this boundary just timed out, schedule an effect to attach a
+ // retry listener to the promise. This flag is also used to hide the
+ // primary children. In mutation mode, we also need the flag to
+ // *unhide* children that were previously hidden, so check if this
+ // is currently timed out, too.
+ workInProgress.effectTag |= Update;
+ }
+ }
+
+ return null;
+ }
+
+ case HostPortal:
+ popHostContainer(workInProgress);
+ updateHostContainer(workInProgress);
+ return null;
+
+ case ContextProvider:
+ // Pop provider fiber
+ popProvider(workInProgress);
+ return null;
+
+ case IncompleteClassComponent:
+ {
+ // Same as class component case. I put it down here so that the tags are
+ // sequential to ensure this switch is compiled to a jump table.
+ var _Component = workInProgress.type;
+
+ if (isContextProvider(_Component)) {
+ popContext(workInProgress);
+ }
+
+ return null;
+ }
+
+ case SuspenseListComponent:
+ {
+ popSuspenseContext(workInProgress);
+ var renderState = workInProgress.memoizedState;
+
+ if (renderState === null) {
+ // We're running in the default, "independent" mode.
+ // We don't do anything in this mode.
+ return null;
+ }
+
+ var didSuspendAlready = (workInProgress.effectTag & DidCapture) !== NoEffect;
+ var renderedTail = renderState.rendering;
+
+ if (renderedTail === null) {
+ // We just rendered the head.
+ if (!didSuspendAlready) {
+ // This is the first pass. We need to figure out if anything is still
+ // suspended in the rendered set.
+ // If new content unsuspended, but there's still some content that
+ // didn't. Then we need to do a second pass that forces everything
+ // to keep showing their fallbacks.
+ // We might be suspended if something in this render pass suspended, or
+ // something in the previous committed pass suspended. Otherwise,
+ // there's no chance so we can skip the expensive call to
+ // findFirstSuspended.
+ var cannotBeSuspended = renderHasNotSuspendedYet() && (current === null || (current.effectTag & DidCapture) === NoEffect);
+
+ if (!cannotBeSuspended) {
+ var row = workInProgress.child;
+
+ while (row !== null) {
+ var suspended = findFirstSuspended(row);
+
+ if (suspended !== null) {
+ didSuspendAlready = true;
+ workInProgress.effectTag |= DidCapture;
+ cutOffTailIfNeeded(renderState, false); // If this is a newly suspended tree, it might not get committed as
+ // part of the second pass. In that case nothing will subscribe to
+ // its thennables. Instead, we'll transfer its thennables to the
+ // SuspenseList so that it can retry if they resolve.
+ // There might be multiple of these in the list but since we're
+ // going to wait for all of them anyway, it doesn't really matter
+ // which ones gets to ping. In theory we could get clever and keep
+ // track of how many dependencies remain but it gets tricky because
+ // in the meantime, we can add/remove/change items and dependencies.
+ // We might bail out of the loop before finding any but that
+ // doesn't matter since that means that the other boundaries that
+ // we did find already has their listeners attached.
+
+ var newThennables = suspended.updateQueue;
+
+ if (newThennables !== null) {
+ workInProgress.updateQueue = newThennables;
+ workInProgress.effectTag |= Update;
+ } // Rerender the whole list, but this time, we'll force fallbacks
+ // to stay in place.
+ // Reset the effect list before doing the second pass since that's now invalid.
+
+
+ if (renderState.lastEffect === null) {
+ workInProgress.firstEffect = null;
+ }
+
+ workInProgress.lastEffect = renderState.lastEffect; // Reset the child fibers to their original state.
+
+ resetChildFibers(workInProgress, renderExpirationTime); // Set up the Suspense Context to force suspense and immediately
+ // rerender the children.
+
+ pushSuspenseContext(workInProgress, setShallowSuspenseContext(suspenseStackCursor.current, ForceSuspenseFallback));
+ return workInProgress.child;
+ }
+
+ row = row.sibling;
+ }
+ }
+ } else {
+ cutOffTailIfNeeded(renderState, false);
+ } // Next we're going to render the tail.
+
+ } else {
+ // Append the rendered row to the child list.
+ if (!didSuspendAlready) {
+ var _suspended = findFirstSuspended(renderedTail);
+
+ if (_suspended !== null) {
+ workInProgress.effectTag |= DidCapture;
+ didSuspendAlready = true; // Ensure we transfer the update queue to the parent so that it doesn't
+ // get lost if this row ends up dropped during a second pass.
+
+ var _newThennables = _suspended.updateQueue;
+
+ if (_newThennables !== null) {
+ workInProgress.updateQueue = _newThennables;
+ workInProgress.effectTag |= Update;
+ }
+
+ cutOffTailIfNeeded(renderState, true); // This might have been modified.
+
+ if (renderState.tail === null && renderState.tailMode === 'hidden' && !renderedTail.alternate) {
+ // We need to delete the row we just rendered.
+ // Reset the effect list to what it was before we rendered this
+ // child. The nested children have already appended themselves.
+ var lastEffect = workInProgress.lastEffect = renderState.lastEffect; // Remove any effects that were appended after this point.
+
+ if (lastEffect !== null) {
+ lastEffect.nextEffect = null;
+ } // We're done.
+
+
+ return null;
+ }
+ } else if ( // The time it took to render last row is greater than time until
+ // the expiration.
+ now() * 2 - renderState.renderingStartTime > renderState.tailExpiration && renderExpirationTime > Never) {
+ // We have now passed our CPU deadline and we'll just give up further
+ // attempts to render the main content and only render fallbacks.
+ // The assumption is that this is usually faster.
+ workInProgress.effectTag |= DidCapture;
+ didSuspendAlready = true;
+ cutOffTailIfNeeded(renderState, false); // Since nothing actually suspended, there will nothing to ping this
+ // to get it started back up to attempt the next item. If we can show
+ // them, then they really have the same priority as this render.
+ // So we'll pick it back up the very next render pass once we've had
+ // an opportunity to yield for paint.
+
+ var nextPriority = renderExpirationTime - 1;
+ workInProgress.expirationTime = workInProgress.childExpirationTime = nextPriority;
+
+ {
+ markSpawnedWork(nextPriority);
+ }
+ }
+ }
+
+ if (renderState.isBackwards) {
+ // The effect list of the backwards tail will have been added
+ // to the end. This breaks the guarantee that life-cycles fire in
+ // sibling order but that isn't a strong guarantee promised by React.
+ // Especially since these might also just pop in during future commits.
+ // Append to the beginning of the list.
+ renderedTail.sibling = workInProgress.child;
+ workInProgress.child = renderedTail;
+ } else {
+ var previousSibling = renderState.last;
+
+ if (previousSibling !== null) {
+ previousSibling.sibling = renderedTail;
+ } else {
+ workInProgress.child = renderedTail;
+ }
+
+ renderState.last = renderedTail;
+ }
+ }
+
+ if (renderState.tail !== null) {
+ // We still have tail rows to render.
+ if (renderState.tailExpiration === 0) {
+ // Heuristic for how long we're willing to spend rendering rows
+ // until we just give up and show what we have so far.
+ var TAIL_EXPIRATION_TIMEOUT_MS = 500;
+ renderState.tailExpiration = now() + TAIL_EXPIRATION_TIMEOUT_MS; // TODO: This is meant to mimic the train model or JND but this
+ // is a per component value. It should really be since the start
+ // of the total render or last commit. Consider using something like
+ // globalMostRecentFallbackTime. That doesn't account for being
+ // suspended for part of the time or when it's a new render.
+ // It should probably use a global start time value instead.
+ } // Pop a row.
+
+
+ var next = renderState.tail;
+ renderState.rendering = next;
+ renderState.tail = next.sibling;
+ renderState.lastEffect = workInProgress.lastEffect;
+ renderState.renderingStartTime = now();
+ next.sibling = null; // Restore the context.
+ // TODO: We can probably just avoid popping it instead and only
+ // setting it the first time we go from not suspended to suspended.
+
+ var suspenseContext = suspenseStackCursor.current;
+
+ if (didSuspendAlready) {
+ suspenseContext = setShallowSuspenseContext(suspenseContext, ForceSuspenseFallback);
+ } else {
+ suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
+ }
+
+ pushSuspenseContext(workInProgress, suspenseContext); // Do a pass over the next row.
+
+ return next;
+ }
+
+ return null;
+ }
+ }
+
+ {
+ {
+ throw Error( "Unknown unit of work tag (" + workInProgress.tag + "). This error is likely caused by a bug in React. Please file an issue." );
+ }
+ }
+ }
+
+ function unwindWork(workInProgress, renderExpirationTime) {
+ switch (workInProgress.tag) {
+ case ClassComponent:
+ {
+ var Component = workInProgress.type;
+
+ if (isContextProvider(Component)) {
+ popContext(workInProgress);
+ }
+
+ var effectTag = workInProgress.effectTag;
+
+ if (effectTag & ShouldCapture) {
+ workInProgress.effectTag = effectTag & ~ShouldCapture | DidCapture;
+ return workInProgress;
+ }
+
+ return null;
+ }
+
+ case HostRoot:
+ {
+ popHostContainer(workInProgress);
+ popTopLevelContextObject(workInProgress);
+ var _effectTag = workInProgress.effectTag;
+
+ if (!((_effectTag & DidCapture) === NoEffect)) {
+ {
+ throw Error( "The root failed to unmount after an error. This is likely a bug in React. Please file an issue." );
+ }
+ }
+
+ workInProgress.effectTag = _effectTag & ~ShouldCapture | DidCapture;
+ return workInProgress;
+ }
+
+ case HostComponent:
+ {
+ // TODO: popHydrationState
+ popHostContext(workInProgress);
+ return null;
+ }
+
+ case SuspenseComponent:
+ {
+ popSuspenseContext(workInProgress);
+
+ var _effectTag2 = workInProgress.effectTag;
+
+ if (_effectTag2 & ShouldCapture) {
+ workInProgress.effectTag = _effectTag2 & ~ShouldCapture | DidCapture; // Captured a suspense effect. Re-render the boundary.
+
+ return workInProgress;
+ }
+
+ return null;
+ }
+
+ case SuspenseListComponent:
+ {
+ popSuspenseContext(workInProgress); // SuspenseList doesn't actually catch anything. It should've been
+ // caught by a nested boundary. If not, it should bubble through.
+
+ return null;
+ }
+
+ case HostPortal:
+ popHostContainer(workInProgress);
+ return null;
+
+ case ContextProvider:
+ popProvider(workInProgress);
+ return null;
+
+ default:
+ return null;
+ }
+ }
+
+ function unwindInterruptedWork(interruptedWork) {
+ switch (interruptedWork.tag) {
+ case ClassComponent:
+ {
+ var childContextTypes = interruptedWork.type.childContextTypes;
+
+ if (childContextTypes !== null && childContextTypes !== undefined) {
+ popContext(interruptedWork);
+ }
+
+ break;
+ }
+
+ case HostRoot:
+ {
+ popHostContainer(interruptedWork);
+ popTopLevelContextObject(interruptedWork);
+ break;
+ }
+
+ case HostComponent:
+ {
+ popHostContext(interruptedWork);
+ break;
+ }
+
+ case HostPortal:
+ popHostContainer(interruptedWork);
+ break;
+
+ case SuspenseComponent:
+ popSuspenseContext(interruptedWork);
+ break;
+
+ case SuspenseListComponent:
+ popSuspenseContext(interruptedWork);
+ break;
+
+ case ContextProvider:
+ popProvider(interruptedWork);
+ break;
+ }
+ }
+
+ function createCapturedValue(value, source) {
+ // If the value is an error, call this function immediately after it is thrown
+ // so the stack is accurate.
+ return {
+ value: value,
+ source: source,
+ stack: getStackByFiberInDevAndProd(source)
+ };
+ }
+
+ function logCapturedError(capturedError) {
+
+ var error = capturedError.error;
+
+ {
+ var componentName = capturedError.componentName,
+ componentStack = capturedError.componentStack,
+ errorBoundaryName = capturedError.errorBoundaryName,
+ errorBoundaryFound = capturedError.errorBoundaryFound,
+ willRetry = capturedError.willRetry; // Browsers support silencing uncaught errors by calling
+ // `preventDefault()` in window `error` handler.
+ // We record this information as an expando on the error.
+
+ if (error != null && error._suppressLogging) {
+ if (errorBoundaryFound && willRetry) {
+ // The error is recoverable and was silenced.
+ // Ignore it and don't print the stack addendum.
+ // This is handy for testing error boundaries without noise.
+ return;
+ } // The error is fatal. Since the silencing might have
+ // been accidental, we'll surface it anyway.
+ // However, the browser would have silenced the original error
+ // so we'll print it first, and then print the stack addendum.
+
+
+ console['error'](error); // Don't transform to our wrapper
+ // For a more detailed description of this block, see:
+ // https://github.com/facebook/react/pull/13384
+ }
+
+ var componentNameMessage = componentName ? "The above error occurred in the <" + componentName + "> component:" : 'The above error occurred in one of your React components:';
+ var errorBoundaryMessage; // errorBoundaryFound check is sufficient; errorBoundaryName check is to satisfy Flow.
+
+ if (errorBoundaryFound && errorBoundaryName) {
+ if (willRetry) {
+ errorBoundaryMessage = "React will try to recreate this component tree from scratch " + ("using the error boundary you provided, " + errorBoundaryName + ".");
+ } else {
+ errorBoundaryMessage = "This error was initially handled by the error boundary " + errorBoundaryName + ".\n" + "Recreating the tree from scratch failed so React will unmount the tree.";
+ }
+ } else {
+ errorBoundaryMessage = 'Consider adding an error boundary to your tree to customize error handling behavior.\n' + 'Visit https://fb.me/react-error-boundaries to learn more about error boundaries.';
+ }
+
+ var combinedMessage = "" + componentNameMessage + componentStack + "\n\n" + ("" + errorBoundaryMessage); // In development, we provide our own message with just the component stack.
+ // We don't include the original error message and JS stack because the browser
+ // has already printed it. Even if the application swallows the error, it is still
+ // displayed by the browser thanks to the DEV-only fake event trick in ReactErrorUtils.
+
+ console['error'](combinedMessage); // Don't transform to our wrapper
+ }
+ }
+
+ var didWarnAboutUndefinedSnapshotBeforeUpdate = null;
+
+ {
+ didWarnAboutUndefinedSnapshotBeforeUpdate = new Set();
+ }
+
+ var PossiblyWeakSet = typeof WeakSet === 'function' ? WeakSet : Set;
+ function logError(boundary, errorInfo) {
+ var source = errorInfo.source;
+ var stack = errorInfo.stack;
+
+ if (stack === null && source !== null) {
+ stack = getStackByFiberInDevAndProd(source);
+ }
+
+ var capturedError = {
+ componentName: source !== null ? getComponentName(source.type) : null,
+ componentStack: stack !== null ? stack : '',
+ error: errorInfo.value,
+ errorBoundary: null,
+ errorBoundaryName: null,
+ errorBoundaryFound: false,
+ willRetry: false
+ };
+
+ if (boundary !== null && boundary.tag === ClassComponent) {
+ capturedError.errorBoundary = boundary.stateNode;
+ capturedError.errorBoundaryName = getComponentName(boundary.type);
+ capturedError.errorBoundaryFound = true;
+ capturedError.willRetry = true;
+ }
+
+ try {
+ logCapturedError(capturedError);
+ } catch (e) {
+ // This method must not throw, or React internal state will get messed up.
+ // If console.error is overridden, or logCapturedError() shows a dialog that throws,
+ // we want to report this error outside of the normal stack as a last resort.
+ // https://github.com/facebook/react/issues/13188
+ setTimeout(function () {
+ throw e;
+ });
+ }
+ }
+
+ var callComponentWillUnmountWithTimer = function (current, instance) {
+ startPhaseTimer(current, 'componentWillUnmount');
+ instance.props = current.memoizedProps;
+ instance.state = current.memoizedState;
+ instance.componentWillUnmount();
+ stopPhaseTimer();
+ }; // Capture errors so they don't interrupt unmounting.
+
+
+ function safelyCallComponentWillUnmount(current, instance) {
+ {
+ invokeGuardedCallback(null, callComponentWillUnmountWithTimer, null, current, instance);
+
+ if (hasCaughtError()) {
+ var unmountError = clearCaughtError();
+ captureCommitPhaseError(current, unmountError);
+ }
+ }
+ }
+
+ function safelyDetachRef(current) {
+ var ref = current.ref;
+
+ if (ref !== null) {
+ if (typeof ref === 'function') {
+ {
+ invokeGuardedCallback(null, ref, null, null);
+
+ if (hasCaughtError()) {
+ var refError = clearCaughtError();
+ captureCommitPhaseError(current, refError);
+ }
+ }
+ } else {
+ ref.current = null;
+ }
+ }
+ }
+
+ function safelyCallDestroy(current, destroy) {
+ {
+ invokeGuardedCallback(null, destroy, null);
+
+ if (hasCaughtError()) {
+ var error = clearCaughtError();
+ captureCommitPhaseError(current, error);
+ }
+ }
+ }
+
+ function commitBeforeMutationLifeCycles(current, finishedWork) {
+ switch (finishedWork.tag) {
+ case FunctionComponent:
+ case ForwardRef:
+ case SimpleMemoComponent:
+ case Block:
+ {
+ return;
+ }
+
+ case ClassComponent:
+ {
+ if (finishedWork.effectTag & Snapshot) {
+ if (current !== null) {
+ var prevProps = current.memoizedProps;
+ var prevState = current.memoizedState;
+ startPhaseTimer(finishedWork, 'getSnapshotBeforeUpdate');
+ var instance = finishedWork.stateNode; // We could update instance props and state here,
+ // but instead we rely on them being set during last render.
+ // TODO: revisit this when we implement resuming.
+
+ {
+ if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
+ if (instance.props !== finishedWork.memoizedProps) {
+ error('Expected %s props to match memoized props before ' + 'getSnapshotBeforeUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance');
+ }
+
+ if (instance.state !== finishedWork.memoizedState) {
+ error('Expected %s state to match memoized state before ' + 'getSnapshotBeforeUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance');
+ }
+ }
+ }
+
+ var snapshot = instance.getSnapshotBeforeUpdate(finishedWork.elementType === finishedWork.type ? prevProps : resolveDefaultProps(finishedWork.type, prevProps), prevState);
+
+ {
+ var didWarnSet = didWarnAboutUndefinedSnapshotBeforeUpdate;
+
+ if (snapshot === undefined && !didWarnSet.has(finishedWork.type)) {
+ didWarnSet.add(finishedWork.type);
+
+ error('%s.getSnapshotBeforeUpdate(): A snapshot value (or null) ' + 'must be returned. You have returned undefined.', getComponentName(finishedWork.type));
+ }
+ }
+
+ instance.__reactInternalSnapshotBeforeUpdate = snapshot;
+ stopPhaseTimer();
+ }
+ }
+
+ return;
+ }
+
+ case HostRoot:
+ case HostComponent:
+ case HostText:
+ case HostPortal:
+ case IncompleteClassComponent:
+ // Nothing to do for these component types
+ return;
+ }
+
+ {
+ {
+ throw Error( "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." );
+ }
+ }
+ }
+
+ function commitHookEffectListUnmount(tag, finishedWork) {
+ var updateQueue = finishedWork.updateQueue;
+ var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;
+
+ if (lastEffect !== null) {
+ var firstEffect = lastEffect.next;
+ var effect = firstEffect;
+
+ do {
+ if ((effect.tag & tag) === tag) {
+ // Unmount
+ var destroy = effect.destroy;
+ effect.destroy = undefined;
+
+ if (destroy !== undefined) {
+ destroy();
+ }
+ }
+
+ effect = effect.next;
+ } while (effect !== firstEffect);
+ }
+ }
+
+ function commitHookEffectListMount(tag, finishedWork) {
+ var updateQueue = finishedWork.updateQueue;
+ var lastEffect = updateQueue !== null ? updateQueue.lastEffect : null;
+
+ if (lastEffect !== null) {
+ var firstEffect = lastEffect.next;
+ var effect = firstEffect;
+
+ do {
+ if ((effect.tag & tag) === tag) {
+ // Mount
+ var create = effect.create;
+ effect.destroy = create();
+
+ {
+ var destroy = effect.destroy;
+
+ if (destroy !== undefined && typeof destroy !== 'function') {
+ var addendum = void 0;
+
+ if (destroy === null) {
+ addendum = ' You returned null. If your effect does not require clean ' + 'up, return undefined (or nothing).';
+ } else if (typeof destroy.then === 'function') {
+ addendum = '\n\nIt looks like you wrote useEffect(async () => ...) or returned a Promise. ' + 'Instead, write the async function inside your effect ' + 'and call it immediately:\n\n' + 'useEffect(() => {\n' + ' async function fetchData() {\n' + ' // You can await here\n' + ' const response = await MyAPI.getData(someId);\n' + ' // ...\n' + ' }\n' + ' fetchData();\n' + "}, [someId]); // Or [] if effect doesn't need props or state\n\n" + 'Learn more about data fetching with Hooks: https://fb.me/react-hooks-data-fetching';
+ } else {
+ addendum = ' You returned: ' + destroy;
+ }
+
+ error('An effect function must not return anything besides a function, ' + 'which is used for clean-up.%s%s', addendum, getStackByFiberInDevAndProd(finishedWork));
+ }
+ }
+ }
+
+ effect = effect.next;
+ } while (effect !== firstEffect);
+ }
+ }
+
+ function commitPassiveHookEffects(finishedWork) {
+ if ((finishedWork.effectTag & Passive) !== NoEffect) {
+ switch (finishedWork.tag) {
+ case FunctionComponent:
+ case ForwardRef:
+ case SimpleMemoComponent:
+ case Block:
+ {
+ // TODO (#17945) We should call all passive destroy functions (for all fibers)
+ // before calling any create functions. The current approach only serializes
+ // these for a single fiber.
+ commitHookEffectListUnmount(Passive$1 | HasEffect, finishedWork);
+ commitHookEffectListMount(Passive$1 | HasEffect, finishedWork);
+ break;
+ }
+ }
+ }
+ }
+
+ function commitLifeCycles(finishedRoot, current, finishedWork, committedExpirationTime) {
+ switch (finishedWork.tag) {
+ case FunctionComponent:
+ case ForwardRef:
+ case SimpleMemoComponent:
+ case Block:
+ {
+ // At this point layout effects have already been destroyed (during mutation phase).
+ // This is done to prevent sibling component effects from interfering with each other,
+ // e.g. a destroy function in one component should never override a ref set
+ // by a create function in another component during the same commit.
+ commitHookEffectListMount(Layout | HasEffect, finishedWork);
+
+ return;
+ }
+
+ case ClassComponent:
+ {
+ var instance = finishedWork.stateNode;
+
+ if (finishedWork.effectTag & Update) {
+ if (current === null) {
+ startPhaseTimer(finishedWork, 'componentDidMount'); // We could update instance props and state here,
+ // but instead we rely on them being set during last render.
+ // TODO: revisit this when we implement resuming.
+
+ {
+ if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
+ if (instance.props !== finishedWork.memoizedProps) {
+ error('Expected %s props to match memoized props before ' + 'componentDidMount. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance');
+ }
+
+ if (instance.state !== finishedWork.memoizedState) {
+ error('Expected %s state to match memoized state before ' + 'componentDidMount. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance');
+ }
+ }
+ }
+
+ instance.componentDidMount();
+ stopPhaseTimer();
+ } else {
+ var prevProps = finishedWork.elementType === finishedWork.type ? current.memoizedProps : resolveDefaultProps(finishedWork.type, current.memoizedProps);
+ var prevState = current.memoizedState;
+ startPhaseTimer(finishedWork, 'componentDidUpdate'); // We could update instance props and state here,
+ // but instead we rely on them being set during last render.
+ // TODO: revisit this when we implement resuming.
+
+ {
+ if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
+ if (instance.props !== finishedWork.memoizedProps) {
+ error('Expected %s props to match memoized props before ' + 'componentDidUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance');
+ }
+
+ if (instance.state !== finishedWork.memoizedState) {
+ error('Expected %s state to match memoized state before ' + 'componentDidUpdate. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance');
+ }
+ }
+ }
+
+ instance.componentDidUpdate(prevProps, prevState, instance.__reactInternalSnapshotBeforeUpdate);
+ stopPhaseTimer();
+ }
+ }
+
+ var updateQueue = finishedWork.updateQueue;
+
+ if (updateQueue !== null) {
+ {
+ if (finishedWork.type === finishedWork.elementType && !didWarnAboutReassigningProps) {
+ if (instance.props !== finishedWork.memoizedProps) {
+ error('Expected %s props to match memoized props before ' + 'processing the update queue. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance');
+ }
+
+ if (instance.state !== finishedWork.memoizedState) {
+ error('Expected %s state to match memoized state before ' + 'processing the update queue. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance');
+ }
+ }
+ } // We could update instance props and state here,
+ // but instead we rely on them being set during last render.
+ // TODO: revisit this when we implement resuming.
+
+
+ commitUpdateQueue(finishedWork, updateQueue, instance);
+ }
+
+ return;
+ }
+
+ case HostRoot:
+ {
+ var _updateQueue = finishedWork.updateQueue;
+
+ if (_updateQueue !== null) {
+ var _instance = null;
+
+ if (finishedWork.child !== null) {
+ switch (finishedWork.child.tag) {
+ case HostComponent:
+ _instance = getPublicInstance(finishedWork.child.stateNode);
+ break;
+
+ case ClassComponent:
+ _instance = finishedWork.child.stateNode;
+ break;
+ }
+ }
+
+ commitUpdateQueue(finishedWork, _updateQueue, _instance);
+ }
+
+ return;
+ }
+
+ case HostComponent:
+ {
+ var _instance2 = finishedWork.stateNode; // Renderers may schedule work to be done after host components are mounted
+ // (eg DOM renderer may schedule auto-focus for inputs and form controls).
+ // These effects should only be committed when components are first mounted,
+ // aka when there is no current/alternate.
+
+ if (current === null && finishedWork.effectTag & Update) {
+ var type = finishedWork.type;
+ var props = finishedWork.memoizedProps;
+ commitMount(_instance2, type, props);
+ }
+
+ return;
+ }
+
+ case HostText:
+ {
+ // We have no life-cycles associated with text.
+ return;
+ }
+
+ case HostPortal:
+ {
+ // We have no life-cycles associated with portals.
+ return;
+ }
+
+ case Profiler:
+ {
+ {
+ var onRender = finishedWork.memoizedProps.onRender;
+
+ if (typeof onRender === 'function') {
+ {
+ onRender(finishedWork.memoizedProps.id, current === null ? 'mount' : 'update', finishedWork.actualDuration, finishedWork.treeBaseDuration, finishedWork.actualStartTime, getCommitTime(), finishedRoot.memoizedInteractions);
+ }
+ }
+ }
+
+ return;
+ }
+
+ case SuspenseComponent:
+ {
+ commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);
+ return;
+ }
+
+ case SuspenseListComponent:
+ case IncompleteClassComponent:
+ case FundamentalComponent:
+ case ScopeComponent:
+ return;
+ }
+
+ {
+ {
+ throw Error( "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." );
+ }
+ }
+ }
+
+ function hideOrUnhideAllChildren(finishedWork, isHidden) {
+ {
+ // We only have the top Fiber that was inserted but we need to recurse down its
+ // children to find all the terminal nodes.
+ var node = finishedWork;
+
+ while (true) {
+ if (node.tag === HostComponent) {
+ var instance = node.stateNode;
+
+ if (isHidden) {
+ hideInstance(instance);
+ } else {
+ unhideInstance(node.stateNode, node.memoizedProps);
+ }
+ } else if (node.tag === HostText) {
+ var _instance3 = node.stateNode;
+
+ if (isHidden) {
+ hideTextInstance(_instance3);
+ } else {
+ unhideTextInstance(_instance3, node.memoizedProps);
+ }
+ } else if (node.tag === SuspenseComponent && node.memoizedState !== null && node.memoizedState.dehydrated === null) {
+ // Found a nested Suspense component that timed out. Skip over the
+ // primary child fragment, which should remain hidden.
+ var fallbackChildFragment = node.child.sibling;
+ fallbackChildFragment.return = node;
+ node = fallbackChildFragment;
+ continue;
+ } else if (node.child !== null) {
+ node.child.return = node;
+ node = node.child;
+ continue;
+ }
+
+ if (node === finishedWork) {
+ return;
+ }
+
+ while (node.sibling === null) {
+ if (node.return === null || node.return === finishedWork) {
+ return;
+ }
+
+ node = node.return;
+ }
+
+ node.sibling.return = node.return;
+ node = node.sibling;
+ }
+ }
+ }
+
+ function commitAttachRef(finishedWork) {
+ var ref = finishedWork.ref;
+
+ if (ref !== null) {
+ var instance = finishedWork.stateNode;
+ var instanceToUse;
+
+ switch (finishedWork.tag) {
+ case HostComponent:
+ instanceToUse = getPublicInstance(instance);
+ break;
+
+ default:
+ instanceToUse = instance;
+ } // Moved outside to ensure DCE works with this flag
+
+ if (typeof ref === 'function') {
+ ref(instanceToUse);
+ } else {
+ {
+ if (!ref.hasOwnProperty('current')) {
+ error('Unexpected ref object provided for %s. ' + 'Use either a ref-setter function or React.createRef().%s', getComponentName(finishedWork.type), getStackByFiberInDevAndProd(finishedWork));
+ }
+ }
+
+ ref.current = instanceToUse;
+ }
+ }
+ }
+
+ function commitDetachRef(current) {
+ var currentRef = current.ref;
+
+ if (currentRef !== null) {
+ if (typeof currentRef === 'function') {
+ currentRef(null);
+ } else {
+ currentRef.current = null;
+ }
+ }
+ } // User-originating errors (lifecycles and refs) should not interrupt
+ // deletion, so don't let them throw. Host-originating errors should
+ // interrupt deletion, so it's okay
+
+
+ function commitUnmount(finishedRoot, current, renderPriorityLevel) {
+ onCommitUnmount(current);
+
+ switch (current.tag) {
+ case FunctionComponent:
+ case ForwardRef:
+ case MemoComponent:
+ case SimpleMemoComponent:
+ case Block:
+ {
+ var updateQueue = current.updateQueue;
+
+ if (updateQueue !== null) {
+ var lastEffect = updateQueue.lastEffect;
+
+ if (lastEffect !== null) {
+ var firstEffect = lastEffect.next;
+
+ {
+ // When the owner fiber is deleted, the destroy function of a passive
+ // effect hook is called during the synchronous commit phase. This is
+ // a concession to implementation complexity. Calling it in the
+ // passive effect phase (like they usually are, when dependencies
+ // change during an update) would require either traversing the
+ // children of the deleted fiber again, or including unmount effects
+ // as part of the fiber effect list.
+ //
+ // Because this is during the sync commit phase, we need to change
+ // the priority.
+ //
+ // TODO: Reconsider this implementation trade off.
+ var priorityLevel = renderPriorityLevel > NormalPriority ? NormalPriority : renderPriorityLevel;
+ runWithPriority$1(priorityLevel, function () {
+ var effect = firstEffect;
+
+ do {
+ var _destroy = effect.destroy;
+
+ if (_destroy !== undefined) {
+ safelyCallDestroy(current, _destroy);
+ }
+
+ effect = effect.next;
+ } while (effect !== firstEffect);
+ });
+ }
+ }
+ }
+
+ return;
+ }
+
+ case ClassComponent:
+ {
+ safelyDetachRef(current);
+ var instance = current.stateNode;
+
+ if (typeof instance.componentWillUnmount === 'function') {
+ safelyCallComponentWillUnmount(current, instance);
+ }
+
+ return;
+ }
+
+ case HostComponent:
+ {
+
+ safelyDetachRef(current);
+ return;
+ }
+
+ case HostPortal:
+ {
+ // TODO: this is recursive.
+ // We are also not using this parent because
+ // the portal will get pushed immediately.
+ {
+ unmountHostComponents(finishedRoot, current, renderPriorityLevel);
+ }
+
+ return;
+ }
+
+ case FundamentalComponent:
+ {
+
+ return;
+ }
+
+ case DehydratedFragment:
+ {
+
+ return;
+ }
+
+ case ScopeComponent:
+ {
+
+ return;
+ }
+ }
+ }
+
+ function commitNestedUnmounts(finishedRoot, root, renderPriorityLevel) {
+ // While we're inside a removed host node we don't want to call
+ // removeChild on the inner nodes because they're removed by the top
+ // call anyway. We also want to call componentWillUnmount on all
+ // composites before this host node is removed from the tree. Therefore
+ // we do an inner loop while we're still inside the host node.
+ var node = root;
+
+ while (true) {
+ commitUnmount(finishedRoot, node, renderPriorityLevel); // Visit children because they may contain more composite or host nodes.
+ // Skip portals because commitUnmount() currently visits them recursively.
+
+ if (node.child !== null && ( // If we use mutation we drill down into portals using commitUnmount above.
+ // If we don't use mutation we drill down into portals here instead.
+ node.tag !== HostPortal)) {
+ node.child.return = node;
+ node = node.child;
+ continue;
+ }
+
+ if (node === root) {
+ return;
+ }
+
+ while (node.sibling === null) {
+ if (node.return === null || node.return === root) {
+ return;
+ }
+
+ node = node.return;
+ }
+
+ node.sibling.return = node.return;
+ node = node.sibling;
+ }
+ }
+
+ function detachFiber(current) {
+ var alternate = current.alternate; // Cut off the return pointers to disconnect it from the tree. Ideally, we
+ // should clear the child pointer of the parent alternate to let this
+ // get GC:ed but we don't know which for sure which parent is the current
+ // one so we'll settle for GC:ing the subtree of this child. This child
+ // itself will be GC:ed when the parent updates the next time.
+
+ current.return = null;
+ current.child = null;
+ current.memoizedState = null;
+ current.updateQueue = null;
+ current.dependencies = null;
+ current.alternate = null;
+ current.firstEffect = null;
+ current.lastEffect = null;
+ current.pendingProps = null;
+ current.memoizedProps = null;
+ current.stateNode = null;
+
+ if (alternate !== null) {
+ detachFiber(alternate);
+ }
+ }
+
+ function getHostParentFiber(fiber) {
+ var parent = fiber.return;
+
+ while (parent !== null) {
+ if (isHostParent(parent)) {
+ return parent;
+ }
+
+ parent = parent.return;
+ }
+
+ {
+ {
+ throw Error( "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." );
+ }
+ }
+ }
+
+ function isHostParent(fiber) {
+ return fiber.tag === HostComponent || fiber.tag === HostRoot || fiber.tag === HostPortal;
+ }
+
+ function getHostSibling(fiber) {
+ // We're going to search forward into the tree until we find a sibling host
+ // node. Unfortunately, if multiple insertions are done in a row we have to
+ // search past them. This leads to exponential search for the next sibling.
+ // TODO: Find a more efficient way to do this.
+ var node = fiber;
+
+ siblings: while (true) {
+ // If we didn't find anything, let's try the next sibling.
+ while (node.sibling === null) {
+ if (node.return === null || isHostParent(node.return)) {
+ // If we pop out of the root or hit the parent the fiber we are the
+ // last sibling.
+ return null;
+ }
+
+ node = node.return;
+ }
+
+ node.sibling.return = node.return;
+ node = node.sibling;
+
+ while (node.tag !== HostComponent && node.tag !== HostText && node.tag !== DehydratedFragment) {
+ // If it is not host node and, we might have a host node inside it.
+ // Try to search down until we find one.
+ if (node.effectTag & Placement) {
+ // If we don't have a child, try the siblings instead.
+ continue siblings;
+ } // If we don't have a child, try the siblings instead.
+ // We also skip portals because they are not part of this host tree.
+
+
+ if (node.child === null || node.tag === HostPortal) {
+ continue siblings;
+ } else {
+ node.child.return = node;
+ node = node.child;
+ }
+ } // Check if this host node is stable or about to be placed.
+
+
+ if (!(node.effectTag & Placement)) {
+ // Found it!
+ return node.stateNode;
+ }
+ }
+ }
+
+ function commitPlacement(finishedWork) {
+
+
+ var parentFiber = getHostParentFiber(finishedWork); // Note: these two variables *must* always be updated together.
+
+ var parent;
+ var isContainer;
+ var parentStateNode = parentFiber.stateNode;
+
+ switch (parentFiber.tag) {
+ case HostComponent:
+ parent = parentStateNode;
+ isContainer = false;
+ break;
+
+ case HostRoot:
+ parent = parentStateNode.containerInfo;
+ isContainer = true;
+ break;
+
+ case HostPortal:
+ parent = parentStateNode.containerInfo;
+ isContainer = true;
+ break;
+
+ case FundamentalComponent:
+
+ // eslint-disable-next-line-no-fallthrough
+
+ default:
+ {
+ {
+ throw Error( "Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue." );
+ }
+ }
+
+ }
+
+ if (parentFiber.effectTag & ContentReset) {
+ // Reset the text content of the parent before doing any insertions
+ resetTextContent(parent); // Clear ContentReset from the effect tag
+
+ parentFiber.effectTag &= ~ContentReset;
+ }
+
+ var before = getHostSibling(finishedWork); // We only have the top Fiber that was inserted but we need to recurse down its
+ // children to find all the terminal nodes.
+
+ if (isContainer) {
+ insertOrAppendPlacementNodeIntoContainer(finishedWork, before, parent);
+ } else {
+ insertOrAppendPlacementNode(finishedWork, before, parent);
+ }
+ }
+
+ function insertOrAppendPlacementNodeIntoContainer(node, before, parent) {
+ var tag = node.tag;
+ var isHost = tag === HostComponent || tag === HostText;
+
+ if (isHost || enableFundamentalAPI ) {
+ var stateNode = isHost ? node.stateNode : node.stateNode.instance;
+
+ if (before) {
+ insertInContainerBefore(parent, stateNode, before);
+ } else {
+ appendChildToContainer(parent, stateNode);
+ }
+ } else if (tag === HostPortal) ; else {
+ var child = node.child;
+
+ if (child !== null) {
+ insertOrAppendPlacementNodeIntoContainer(child, before, parent);
+ var sibling = child.sibling;
+
+ while (sibling !== null) {
+ insertOrAppendPlacementNodeIntoContainer(sibling, before, parent);
+ sibling = sibling.sibling;
+ }
+ }
+ }
+ }
+
+ function insertOrAppendPlacementNode(node, before, parent) {
+ var tag = node.tag;
+ var isHost = tag === HostComponent || tag === HostText;
+
+ if (isHost || enableFundamentalAPI ) {
+ var stateNode = isHost ? node.stateNode : node.stateNode.instance;
+
+ if (before) {
+ insertBefore(parent, stateNode, before);
+ } else {
+ appendChild(parent, stateNode);
+ }
+ } else if (tag === HostPortal) ; else {
+ var child = node.child;
+
+ if (child !== null) {
+ insertOrAppendPlacementNode(child, before, parent);
+ var sibling = child.sibling;
+
+ while (sibling !== null) {
+ insertOrAppendPlacementNode(sibling, before, parent);
+ sibling = sibling.sibling;
+ }
+ }
+ }
+ }
+
+ function unmountHostComponents(finishedRoot, current, renderPriorityLevel) {
+ // We only have the top Fiber that was deleted but we need to recurse down its
+ // children to find all the terminal nodes.
+ var node = current; // Each iteration, currentParent is populated with node's host parent if not
+ // currentParentIsValid.
+
+ var currentParentIsValid = false; // Note: these two variables *must* always be updated together.
+
+ var currentParent;
+ var currentParentIsContainer;
+
+ while (true) {
+ if (!currentParentIsValid) {
+ var parent = node.return;
+
+ findParent: while (true) {
+ if (!(parent !== null)) {
+ {
+ throw Error( "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue." );
+ }
+ }
+
+ var parentStateNode = parent.stateNode;
+
+ switch (parent.tag) {
+ case HostComponent:
+ currentParent = parentStateNode;
+ currentParentIsContainer = false;
+ break findParent;
+
+ case HostRoot:
+ currentParent = parentStateNode.containerInfo;
+ currentParentIsContainer = true;
+ break findParent;
+
+ case HostPortal:
+ currentParent = parentStateNode.containerInfo;
+ currentParentIsContainer = true;
+ break findParent;
+
+ }
+
+ parent = parent.return;
+ }
+
+ currentParentIsValid = true;
+ }
+
+ if (node.tag === HostComponent || node.tag === HostText) {
+ commitNestedUnmounts(finishedRoot, node, renderPriorityLevel); // After all the children have unmounted, it is now safe to remove the
+ // node from the tree.
+
+ if (currentParentIsContainer) {
+ removeChildFromContainer(currentParent, node.stateNode);
+ } else {
+ removeChild(currentParent, node.stateNode);
+ } // Don't visit children because we already visited them.
+
+ } else if (node.tag === HostPortal) {
+ if (node.child !== null) {
+ // When we go into a portal, it becomes the parent to remove from.
+ // We will reassign it back when we pop the portal on the way up.
+ currentParent = node.stateNode.containerInfo;
+ currentParentIsContainer = true; // Visit children because portals might contain host components.
+
+ node.child.return = node;
+ node = node.child;
+ continue;
+ }
+ } else {
+ commitUnmount(finishedRoot, node, renderPriorityLevel); // Visit children because we may find more host components below.
+
+ if (node.child !== null) {
+ node.child.return = node;
+ node = node.child;
+ continue;
+ }
+ }
+
+ if (node === current) {
+ return;
+ }
+
+ while (node.sibling === null) {
+ if (node.return === null || node.return === current) {
+ return;
+ }
+
+ node = node.return;
+
+ if (node.tag === HostPortal) {
+ // When we go out of the portal, we need to restore the parent.
+ // Since we don't keep a stack of them, we will search for it.
+ currentParentIsValid = false;
+ }
+ }
+
+ node.sibling.return = node.return;
+ node = node.sibling;
+ }
+ }
+
+ function commitDeletion(finishedRoot, current, renderPriorityLevel) {
+ {
+ // Recursively delete all host nodes from the parent.
+ // Detach refs and call componentWillUnmount() on the whole subtree.
+ unmountHostComponents(finishedRoot, current, renderPriorityLevel);
+ }
+
+ detachFiber(current);
+ }
+
+ function commitWork(current, finishedWork) {
+
+ switch (finishedWork.tag) {
+ case FunctionComponent:
+ case ForwardRef:
+ case MemoComponent:
+ case SimpleMemoComponent:
+ case Block:
+ {
+ // Layout effects are destroyed during the mutation phase so that all
+ // destroy functions for all fibers are called before any create functions.
+ // This prevents sibling component effects from interfering with each other,
+ // e.g. a destroy function in one component should never override a ref set
+ // by a create function in another component during the same commit.
+ commitHookEffectListUnmount(Layout | HasEffect, finishedWork);
+ return;
+ }
+
+ case ClassComponent:
+ {
+ return;
+ }
+
+ case HostComponent:
+ {
+ var instance = finishedWork.stateNode;
+
+ if (instance != null) {
+ // Commit the work prepared earlier.
+ var newProps = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps
+ // as the newProps. The updatePayload will contain the real change in
+ // this case.
+
+ var oldProps = current !== null ? current.memoizedProps : newProps;
+ var type = finishedWork.type; // TODO: Type the updateQueue to be specific to host components.
+
+ var updatePayload = finishedWork.updateQueue;
+ finishedWork.updateQueue = null;
+
+ if (updatePayload !== null) {
+ commitUpdate(instance, updatePayload, type, oldProps, newProps);
+ }
+ }
+
+ return;
+ }
+
+ case HostText:
+ {
+ if (!(finishedWork.stateNode !== null)) {
+ {
+ throw Error( "This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue." );
+ }
+ }
+
+ var textInstance = finishedWork.stateNode;
+ var newText = finishedWork.memoizedProps; // For hydration we reuse the update path but we treat the oldProps
+ // as the newProps. The updatePayload will contain the real change in
+ // this case.
+
+ var oldText = current !== null ? current.memoizedProps : newText;
+ commitTextUpdate(textInstance, oldText, newText);
+ return;
+ }
+
+ case HostRoot:
+ {
+ {
+ var _root = finishedWork.stateNode;
+
+ if (_root.hydrate) {
+ // We've just hydrated. No need to hydrate again.
+ _root.hydrate = false;
+ commitHydratedContainer(_root.containerInfo);
+ }
+ }
+
+ return;
+ }
+
+ case Profiler:
+ {
+ return;
+ }
+
+ case SuspenseComponent:
+ {
+ commitSuspenseComponent(finishedWork);
+ attachSuspenseRetryListeners(finishedWork);
+ return;
+ }
+
+ case SuspenseListComponent:
+ {
+ attachSuspenseRetryListeners(finishedWork);
+ return;
+ }
+
+ case IncompleteClassComponent:
+ {
+ return;
+ }
+ }
+
+ {
+ {
+ throw Error( "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue." );
+ }
+ }
+ }
+
+ function commitSuspenseComponent(finishedWork) {
+ var newState = finishedWork.memoizedState;
+ var newDidTimeout;
+ var primaryChildParent = finishedWork;
+
+ if (newState === null) {
+ newDidTimeout = false;
+ } else {
+ newDidTimeout = true;
+ primaryChildParent = finishedWork.child;
+ markCommitTimeOfFallback();
+ }
+
+ if ( primaryChildParent !== null) {
+ hideOrUnhideAllChildren(primaryChildParent, newDidTimeout);
+ }
+ }
+
+ function commitSuspenseHydrationCallbacks(finishedRoot, finishedWork) {
+
+ var newState = finishedWork.memoizedState;
+
+ if (newState === null) {
+ var current = finishedWork.alternate;
+
+ if (current !== null) {
+ var prevState = current.memoizedState;
+
+ if (prevState !== null) {
+ var suspenseInstance = prevState.dehydrated;
+
+ if (suspenseInstance !== null) {
+ commitHydratedSuspenseInstance(suspenseInstance);
+ }
+ }
+ }
+ }
+ }
+
+ function attachSuspenseRetryListeners(finishedWork) {
+ // If this boundary just timed out, then it will have a set of thenables.
+ // For each thenable, attach a listener so that when it resolves, React
+ // attempts to re-render the boundary in the primary (pre-timeout) state.
+ var thenables = finishedWork.updateQueue;
+
+ if (thenables !== null) {
+ finishedWork.updateQueue = null;
+ var retryCache = finishedWork.stateNode;
+
+ if (retryCache === null) {
+ retryCache = finishedWork.stateNode = new PossiblyWeakSet();
+ }
+
+ thenables.forEach(function (thenable) {
+ // Memoize using the boundary fiber to prevent redundant listeners.
+ var retry = resolveRetryThenable.bind(null, finishedWork, thenable);
+
+ if (!retryCache.has(thenable)) {
+ {
+ if (thenable.__reactDoNotTraceInteractions !== true) {
+ retry = unstable_wrap(retry);
+ }
+ }
+
+ retryCache.add(thenable);
+ thenable.then(retry, retry);
+ }
+ });
+ }
+ }
+
+ function commitResetTextContent(current) {
+
+ resetTextContent(current.stateNode);
+ }
+
+ var PossiblyWeakMap$1 = typeof WeakMap === 'function' ? WeakMap : Map;
+
+ function createRootErrorUpdate(fiber, errorInfo, expirationTime) {
+ var update = createUpdate(expirationTime, null); // Unmount the root by rendering null.
+
+ update.tag = CaptureUpdate; // Caution: React DevTools currently depends on this property
+ // being called "element".
+
+ update.payload = {
+ element: null
+ };
+ var error = errorInfo.value;
+
+ update.callback = function () {
+ onUncaughtError(error);
+ logError(fiber, errorInfo);
+ };
+
+ return update;
+ }
+
+ function createClassErrorUpdate(fiber, errorInfo, expirationTime) {
+ var update = createUpdate(expirationTime, null);
+ update.tag = CaptureUpdate;
+ var getDerivedStateFromError = fiber.type.getDerivedStateFromError;
+
+ if (typeof getDerivedStateFromError === 'function') {
+ var error$1 = errorInfo.value;
+
+ update.payload = function () {
+ logError(fiber, errorInfo);
+ return getDerivedStateFromError(error$1);
+ };
+ }
+
+ var inst = fiber.stateNode;
+
+ if (inst !== null && typeof inst.componentDidCatch === 'function') {
+ update.callback = function callback() {
+ {
+ markFailedErrorBoundaryForHotReloading(fiber);
+ }
+
+ if (typeof getDerivedStateFromError !== 'function') {
+ // To preserve the preexisting retry behavior of error boundaries,
+ // we keep track of which ones already failed during this batch.
+ // This gets reset before we yield back to the browser.
+ // TODO: Warn in strict mode if getDerivedStateFromError is
+ // not defined.
+ markLegacyErrorBoundaryAsFailed(this); // Only log here if componentDidCatch is the only error boundary method defined
+
+ logError(fiber, errorInfo);
+ }
+
+ var error$1 = errorInfo.value;
+ var stack = errorInfo.stack;
+ this.componentDidCatch(error$1, {
+ componentStack: stack !== null ? stack : ''
+ });
+
+ {
+ if (typeof getDerivedStateFromError !== 'function') {
+ // If componentDidCatch is the only error boundary method defined,
+ // then it needs to call setState to recover from errors.
+ // If no state update is scheduled then the boundary will swallow the error.
+ if (fiber.expirationTime !== Sync) {
+ error('%s: Error boundaries should implement getDerivedStateFromError(). ' + 'In that method, return a state update to display an error message or fallback UI.', getComponentName(fiber.type) || 'Unknown');
+ }
+ }
+ }
+ };
+ } else {
+ update.callback = function () {
+ markFailedErrorBoundaryForHotReloading(fiber);
+ };
+ }
+
+ return update;
+ }
+
+ function attachPingListener(root, renderExpirationTime, thenable) {
+ // Attach a listener to the promise to "ping" the root and retry. But
+ // only if one does not already exist for the current render expiration
+ // time (which acts like a "thread ID" here).
+ var pingCache = root.pingCache;
+ var threadIDs;
+
+ if (pingCache === null) {
+ pingCache = root.pingCache = new PossiblyWeakMap$1();
+ threadIDs = new Set();
+ pingCache.set(thenable, threadIDs);
+ } else {
+ threadIDs = pingCache.get(thenable);
+
+ if (threadIDs === undefined) {
+ threadIDs = new Set();
+ pingCache.set(thenable, threadIDs);
+ }
+ }
+
+ if (!threadIDs.has(renderExpirationTime)) {
+ // Memoize using the thread ID to prevent redundant listeners.
+ threadIDs.add(renderExpirationTime);
+ var ping = pingSuspendedRoot.bind(null, root, thenable, renderExpirationTime);
+ thenable.then(ping, ping);
+ }
+ }
+
+ function throwException(root, returnFiber, sourceFiber, value, renderExpirationTime) {
+ // The source fiber did not complete.
+ sourceFiber.effectTag |= Incomplete; // Its effect list is no longer valid.
+
+ sourceFiber.firstEffect = sourceFiber.lastEffect = null;
+
+ if (value !== null && typeof value === 'object' && typeof value.then === 'function') {
+ // This is a thenable.
+ var thenable = value;
+
+ if ((sourceFiber.mode & BlockingMode) === NoMode) {
+ // Reset the memoizedState to what it was before we attempted
+ // to render it.
+ var currentSource = sourceFiber.alternate;
+
+ if (currentSource) {
+ sourceFiber.updateQueue = currentSource.updateQueue;
+ sourceFiber.memoizedState = currentSource.memoizedState;
+ sourceFiber.expirationTime = currentSource.expirationTime;
+ } else {
+ sourceFiber.updateQueue = null;
+ sourceFiber.memoizedState = null;
+ }
+ }
+
+ var hasInvisibleParentBoundary = hasSuspenseContext(suspenseStackCursor.current, InvisibleParentSuspenseContext); // Schedule the nearest Suspense to re-render the timed out view.
+
+ var _workInProgress = returnFiber;
+
+ do {
+ if (_workInProgress.tag === SuspenseComponent && shouldCaptureSuspense(_workInProgress, hasInvisibleParentBoundary)) {
+ // Found the nearest boundary.
+ // Stash the promise on the boundary fiber. If the boundary times out, we'll
+ // attach another listener to flip the boundary back to its normal state.
+ var thenables = _workInProgress.updateQueue;
+
+ if (thenables === null) {
+ var updateQueue = new Set();
+ updateQueue.add(thenable);
+ _workInProgress.updateQueue = updateQueue;
+ } else {
+ thenables.add(thenable);
+ } // If the boundary is outside of blocking mode, we should *not*
+ // suspend the commit. Pretend as if the suspended component rendered
+ // null and keep rendering. In the commit phase, we'll schedule a
+ // subsequent synchronous update to re-render the Suspense.
+ //
+ // Note: It doesn't matter whether the component that suspended was
+ // inside a blocking mode tree. If the Suspense is outside of it, we
+ // should *not* suspend the commit.
+
+
+ if ((_workInProgress.mode & BlockingMode) === NoMode) {
+ _workInProgress.effectTag |= DidCapture; // We're going to commit this fiber even though it didn't complete.
+ // But we shouldn't call any lifecycle methods or callbacks. Remove
+ // all lifecycle effect tags.
+
+ sourceFiber.effectTag &= ~(LifecycleEffectMask | Incomplete);
+
+ if (sourceFiber.tag === ClassComponent) {
+ var currentSourceFiber = sourceFiber.alternate;
+
+ if (currentSourceFiber === null) {
+ // This is a new mount. Change the tag so it's not mistaken for a
+ // completed class component. For example, we should not call
+ // componentWillUnmount if it is deleted.
+ sourceFiber.tag = IncompleteClassComponent;
+ } else {
+ // When we try rendering again, we should not reuse the current fiber,
+ // since it's known to be in an inconsistent state. Use a force update to
+ // prevent a bail out.
+ var update = createUpdate(Sync, null);
+ update.tag = ForceUpdate;
+ enqueueUpdate(sourceFiber, update);
+ }
+ } // The source fiber did not complete. Mark it with Sync priority to
+ // indicate that it still has pending work.
+
+
+ sourceFiber.expirationTime = Sync; // Exit without suspending.
+
+ return;
+ } // Confirmed that the boundary is in a concurrent mode tree. Continue
+ // with the normal suspend path.
+ //
+ // After this we'll use a set of heuristics to determine whether this
+ // render pass will run to completion or restart or "suspend" the commit.
+ // The actual logic for this is spread out in different places.
+ //
+ // This first principle is that if we're going to suspend when we complete
+ // a root, then we should also restart if we get an update or ping that
+ // might unsuspend it, and vice versa. The only reason to suspend is
+ // because you think you might want to restart before committing. However,
+ // it doesn't make sense to restart only while in the period we're suspended.
+ //
+ // Restarting too aggressively is also not good because it starves out any
+ // intermediate loading state. So we use heuristics to determine when.
+ // Suspense Heuristics
+ //
+ // If nothing threw a Promise or all the same fallbacks are already showing,
+ // then don't suspend/restart.
+ //
+ // If this is an initial render of a new tree of Suspense boundaries and
+ // those trigger a fallback, then don't suspend/restart. We want to ensure
+ // that we can show the initial loading state as quickly as possible.
+ //
+ // If we hit a "Delayed" case, such as when we'd switch from content back into
+ // a fallback, then we should always suspend/restart. SuspenseConfig applies to
+ // this case. If none is defined, JND is used instead.
+ //
+ // If we're already showing a fallback and it gets "retried", allowing us to show
+ // another level, but there's still an inner boundary that would show a fallback,
+ // then we suspend/restart for 500ms since the last time we showed a fallback
+ // anywhere in the tree. This effectively throttles progressive loading into a
+ // consistent train of commits. This also gives us an opportunity to restart to
+ // get to the completed state slightly earlier.
+ //
+ // If there's ambiguity due to batching it's resolved in preference of:
+ // 1) "delayed", 2) "initial render", 3) "retry".
+ //
+ // We want to ensure that a "busy" state doesn't get force committed. We want to
+ // ensure that new initial loading states can commit as soon as possible.
+
+
+ attachPingListener(root, renderExpirationTime, thenable);
+ _workInProgress.effectTag |= ShouldCapture;
+ _workInProgress.expirationTime = renderExpirationTime;
+ return;
+ } // This boundary already captured during this render. Continue to the next
+ // boundary.
+
+
+ _workInProgress = _workInProgress.return;
+ } while (_workInProgress !== null); // No boundary was found. Fallthrough to error mode.
+ // TODO: Use invariant so the message is stripped in prod?
+
+
+ value = new Error((getComponentName(sourceFiber.type) || 'A React component') + ' suspended while rendering, but no fallback UI was specified.\n' + '\n' + 'Add a <Suspense fallback=...> component higher in the tree to ' + 'provide a loading indicator or placeholder to display.' + getStackByFiberInDevAndProd(sourceFiber));
+ } // We didn't find a boundary that could handle this type of exception. Start
+ // over and traverse parent path again, this time treating the exception
+ // as an error.
+
+
+ renderDidError();
+ value = createCapturedValue(value, sourceFiber);
+ var workInProgress = returnFiber;
+
+ do {
+ switch (workInProgress.tag) {
+ case HostRoot:
+ {
+ var _errorInfo = value;
+ workInProgress.effectTag |= ShouldCapture;
+ workInProgress.expirationTime = renderExpirationTime;
+
+ var _update = createRootErrorUpdate(workInProgress, _errorInfo, renderExpirationTime);
+
+ enqueueCapturedUpdate(workInProgress, _update);
+ return;
+ }
+
+ case ClassComponent:
+ // Capture and retry
+ var errorInfo = value;
+ var ctor = workInProgress.type;
+ var instance = workInProgress.stateNode;
+
+ if ((workInProgress.effectTag & DidCapture) === NoEffect && (typeof ctor.getDerivedStateFromError === 'function' || instance !== null && typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance))) {
+ workInProgress.effectTag |= ShouldCapture;
+ workInProgress.expirationTime = renderExpirationTime; // Schedule the error boundary to re-render using updated state
+
+ var _update2 = createClassErrorUpdate(workInProgress, errorInfo, renderExpirationTime);
+
+ enqueueCapturedUpdate(workInProgress, _update2);
+ return;
+ }
+
+ break;
+ }
+
+ workInProgress = workInProgress.return;
+ } while (workInProgress !== null);
+ }
+
+ var ceil = Math.ceil;
+ var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher,
+ ReactCurrentOwner$2 = ReactSharedInternals.ReactCurrentOwner,
+ IsSomeRendererActing = ReactSharedInternals.IsSomeRendererActing;
+ var NoContext =
+ /* */
+ 0;
+ var BatchedContext =
+ /* */
+ 1;
+ var EventContext =
+ /* */
+ 2;
+ var DiscreteEventContext =
+ /* */
+ 4;
+ var LegacyUnbatchedContext =
+ /* */
+ 8;
+ var RenderContext =
+ /* */
+ 16;
+ var CommitContext =
+ /* */
+ 32;
+ var RootIncomplete = 0;
+ var RootFatalErrored = 1;
+ var RootErrored = 2;
+ var RootSuspended = 3;
+ var RootSuspendedWithDelay = 4;
+ var RootCompleted = 5;
+ // Describes where we are in the React execution stack
+ var executionContext = NoContext; // The root we're working on
+
+ var workInProgressRoot = null; // The fiber we're working on
+
+ var workInProgress = null; // The expiration time we're rendering
+
+ var renderExpirationTime$1 = NoWork; // Whether to root completed, errored, suspended, etc.
+
+ var workInProgressRootExitStatus = RootIncomplete; // A fatal error, if one is thrown
+
+ var workInProgressRootFatalError = null; // Most recent event time among processed updates during this render.
+ // This is conceptually a time stamp but expressed in terms of an ExpirationTime
+ // because we deal mostly with expiration times in the hot path, so this avoids
+ // the conversion happening in the hot path.
+
+ var workInProgressRootLatestProcessedExpirationTime = Sync;
+ var workInProgressRootLatestSuspenseTimeout = Sync;
+ var workInProgressRootCanSuspendUsingConfig = null; // The work left over by components that were visited during this render. Only
+ // includes unprocessed updates, not work in bailed out children.
+
+ var workInProgressRootNextUnprocessedUpdateTime = NoWork; // If we're pinged while rendering we don't always restart immediately.
+ // This flag determines if it might be worthwhile to restart if an opportunity
+ // happens latere.
+
+ var workInProgressRootHasPendingPing = false; // The most recent time we committed a fallback. This lets us ensure a train
+ // model where we don't commit new loading states in too quick succession.
+
+ var globalMostRecentFallbackTime = 0;
+ var FALLBACK_THROTTLE_MS = 500;
+ var nextEffect = null;
+ var hasUncaughtError = false;
+ var firstUncaughtError = null;
+ var legacyErrorBoundariesThatAlreadyFailed = null;
+ var rootDoesHavePassiveEffects = false;
+ var rootWithPendingPassiveEffects = null;
+ var pendingPassiveEffectsRenderPriority = NoPriority;
+ var pendingPassiveEffectsExpirationTime = NoWork;
+ var rootsWithPendingDiscreteUpdates = null; // Use these to prevent an infinite loop of nested updates
+
+ var NESTED_UPDATE_LIMIT = 50;
+ var nestedUpdateCount = 0;
+ var rootWithNestedUpdates = null;
+ var NESTED_PASSIVE_UPDATE_LIMIT = 50;
+ var nestedPassiveUpdateCount = 0;
+ var interruptedBy = null; // Marks the need to reschedule pending interactions at these expiration times
+ // during the commit phase. This enables them to be traced across components
+ // that spawn new work during render. E.g. hidden boundaries, suspended SSR
+ // hydration or SuspenseList.
+
+ var spawnedWorkDuringRender = null; // Expiration times are computed by adding to the current time (the start
+ // time). However, if two updates are scheduled within the same event, we
+ // should treat their start times as simultaneous, even if the actual clock
+ // time has advanced between the first and second call.
+ // In other words, because expiration times determine how updates are batched,
+ // we want all updates of like priority that occur within the same event to
+ // receive the same expiration time. Otherwise we get tearing.
+
+ var currentEventTime = NoWork;
+ function requestCurrentTimeForUpdate() {
+ if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
+ // We're inside React, so it's fine to read the actual time.
+ return msToExpirationTime(now());
+ } // We're not inside React, so we may be in the middle of a browser event.
+
+
+ if (currentEventTime !== NoWork) {
+ // Use the same start time for all updates until we enter React again.
+ return currentEventTime;
+ } // This is the first update since React yielded. Compute a new start time.
+
+
+ currentEventTime = msToExpirationTime(now());
+ return currentEventTime;
+ }
+ function getCurrentTime() {
+ return msToExpirationTime(now());
+ }
+ function computeExpirationForFiber(currentTime, fiber, suspenseConfig) {
+ var mode = fiber.mode;
+
+ if ((mode & BlockingMode) === NoMode) {
+ return Sync;
+ }
+
+ var priorityLevel = getCurrentPriorityLevel();
+
+ if ((mode & ConcurrentMode) === NoMode) {
+ return priorityLevel === ImmediatePriority ? Sync : Batched;
+ }
+
+ if ((executionContext & RenderContext) !== NoContext) {
+ // Use whatever time we're already rendering
+ // TODO: Should there be a way to opt out, like with `runWithPriority`?
+ return renderExpirationTime$1;
+ }
+
+ var expirationTime;
+
+ if (suspenseConfig !== null) {
+ // Compute an expiration time based on the Suspense timeout.
+ expirationTime = computeSuspenseExpiration(currentTime, suspenseConfig.timeoutMs | 0 || LOW_PRIORITY_EXPIRATION);
+ } else {
+ // Compute an expiration time based on the Scheduler priority.
+ switch (priorityLevel) {
+ case ImmediatePriority:
+ expirationTime = Sync;
+ break;
+
+ case UserBlockingPriority$1:
+ // TODO: Rename this to computeUserBlockingExpiration
+ expirationTime = computeInteractiveExpiration(currentTime);
+ break;
+
+ case NormalPriority:
+ case LowPriority:
+ // TODO: Handle LowPriority
+ // TODO: Rename this to... something better.
+ expirationTime = computeAsyncExpiration(currentTime);
+ break;
+
+ case IdlePriority:
+ expirationTime = Idle;
+ break;
+
+ default:
+ {
+ {
+ throw Error( "Expected a valid priority level" );
+ }
+ }
+
+ }
+ } // If we're in the middle of rendering a tree, do not update at the same
+ // expiration time that is already rendering.
+ // TODO: We shouldn't have to do this if the update is on a different root.
+ // Refactor computeExpirationForFiber + scheduleUpdate so we have access to
+ // the root when we check for this condition.
+
+
+ if (workInProgressRoot !== null && expirationTime === renderExpirationTime$1) {
+ // This is a trick to move this update into a separate batch
+ expirationTime -= 1;
+ }
+
+ return expirationTime;
+ }
+ function scheduleUpdateOnFiber(fiber, expirationTime) {
+ checkForNestedUpdates();
+ warnAboutRenderPhaseUpdatesInDEV(fiber);
+ var root = markUpdateTimeFromFiberToRoot(fiber, expirationTime);
+
+ if (root === null) {
+ warnAboutUpdateOnUnmountedFiberInDEV(fiber);
+ return;
+ }
+
+ checkForInterruption(fiber, expirationTime);
+ recordScheduleUpdate(); // TODO: computeExpirationForFiber also reads the priority. Pass the
+ // priority as an argument to that function and this one.
+
+ var priorityLevel = getCurrentPriorityLevel();
+
+ if (expirationTime === Sync) {
+ if ( // Check if we're inside unbatchedUpdates
+ (executionContext & LegacyUnbatchedContext) !== NoContext && // Check if we're not already rendering
+ (executionContext & (RenderContext | CommitContext)) === NoContext) {
+ // Register pending interactions on the root to avoid losing traced interaction data.
+ schedulePendingInteractions(root, expirationTime); // This is a legacy edge case. The initial mount of a ReactDOM.render-ed
+ // root inside of batchedUpdates should be synchronous, but layout updates
+ // should be deferred until the end of the batch.
+
+ performSyncWorkOnRoot(root);
+ } else {
+ ensureRootIsScheduled(root);
+ schedulePendingInteractions(root, expirationTime);
+
+ if (executionContext === NoContext) {
+ // Flush the synchronous work now, unless we're already working or inside
+ // a batch. This is intentionally inside scheduleUpdateOnFiber instead of
+ // scheduleCallbackForFiber to preserve the ability to schedule a callback
+ // without immediately flushing it. We only do this for user-initiated
+ // updates, to preserve historical behavior of legacy mode.
+ flushSyncCallbackQueue();
+ }
+ }
+ } else {
+ ensureRootIsScheduled(root);
+ schedulePendingInteractions(root, expirationTime);
+ }
+
+ if ((executionContext & DiscreteEventContext) !== NoContext && ( // Only updates at user-blocking priority or greater are considered
+ // discrete, even inside a discrete event.
+ priorityLevel === UserBlockingPriority$1 || priorityLevel === ImmediatePriority)) {
+ // This is the result of a discrete event. Track the lowest priority
+ // discrete update per root so we can flush them early, if needed.
+ if (rootsWithPendingDiscreteUpdates === null) {
+ rootsWithPendingDiscreteUpdates = new Map([[root, expirationTime]]);
+ } else {
+ var lastDiscreteTime = rootsWithPendingDiscreteUpdates.get(root);
+
+ if (lastDiscreteTime === undefined || lastDiscreteTime > expirationTime) {
+ rootsWithPendingDiscreteUpdates.set(root, expirationTime);
+ }
+ }
+ }
+ }
+ var scheduleWork = scheduleUpdateOnFiber; // This is split into a separate function so we can mark a fiber with pending
+ // work without treating it as a typical update that originates from an event;
+ // e.g. retrying a Suspense boundary isn't an update, but it does schedule work
+ // on a fiber.
+
+ function markUpdateTimeFromFiberToRoot(fiber, expirationTime) {
+ // Update the source fiber's expiration time
+ if (fiber.expirationTime < expirationTime) {
+ fiber.expirationTime = expirationTime;
+ }
+
+ var alternate = fiber.alternate;
+
+ if (alternate !== null && alternate.expirationTime < expirationTime) {
+ alternate.expirationTime = expirationTime;
+ } // Walk the parent path to the root and update the child expiration time.
+
+
+ var node = fiber.return;
+ var root = null;
+
+ if (node === null && fiber.tag === HostRoot) {
+ root = fiber.stateNode;
+ } else {
+ while (node !== null) {
+ alternate = node.alternate;
+
+ if (node.childExpirationTime < expirationTime) {
+ node.childExpirationTime = expirationTime;
+
+ if (alternate !== null && alternate.childExpirationTime < expirationTime) {
+ alternate.childExpirationTime = expirationTime;
+ }
+ } else if (alternate !== null && alternate.childExpirationTime < expirationTime) {
+ alternate.childExpirationTime = expirationTime;
+ }
+
+ if (node.return === null && node.tag === HostRoot) {
+ root = node.stateNode;
+ break;
+ }
+
+ node = node.return;
+ }
+ }
+
+ if (root !== null) {
+ if (workInProgressRoot === root) {
+ // Received an update to a tree that's in the middle of rendering. Mark
+ // that's unprocessed work on this root.
+ markUnprocessedUpdateTime(expirationTime);
+
+ if (workInProgressRootExitStatus === RootSuspendedWithDelay) {
+ // The root already suspended with a delay, which means this render
+ // definitely won't finish. Since we have a new update, let's mark it as
+ // suspended now, right before marking the incoming update. This has the
+ // effect of interrupting the current render and switching to the update.
+ // TODO: This happens to work when receiving an update during the render
+ // phase, because of the trick inside computeExpirationForFiber to
+ // subtract 1 from `renderExpirationTime` to move it into a
+ // separate bucket. But we should probably model it with an exception,
+ // using the same mechanism we use to force hydration of a subtree.
+ // TODO: This does not account for low pri updates that were already
+ // scheduled before the root started rendering. Need to track the next
+ // pending expiration time (perhaps by backtracking the return path) and
+ // then trigger a restart in the `renderDidSuspendDelayIfPossible` path.
+ markRootSuspendedAtTime(root, renderExpirationTime$1);
+ }
+ } // Mark that the root has a pending update.
+
+
+ markRootUpdatedAtTime(root, expirationTime);
+ }
+
+ return root;
+ }
+
+ function getNextRootExpirationTimeToWorkOn(root) {
+ // Determines the next expiration time that the root should render, taking
+ // into account levels that may be suspended, or levels that may have
+ // received a ping.
+ var lastExpiredTime = root.lastExpiredTime;
+
+ if (lastExpiredTime !== NoWork) {
+ return lastExpiredTime;
+ } // "Pending" refers to any update that hasn't committed yet, including if it
+ // suspended. The "suspended" range is therefore a subset.
+
+
+ var firstPendingTime = root.firstPendingTime;
+
+ if (!isRootSuspendedAtTime(root, firstPendingTime)) {
+ // The highest priority pending time is not suspended. Let's work on that.
+ return firstPendingTime;
+ } // If the first pending time is suspended, check if there's a lower priority
+ // pending level that we know about. Or check if we received a ping. Work
+ // on whichever is higher priority.
+
+
+ var lastPingedTime = root.lastPingedTime;
+ var nextKnownPendingLevel = root.nextKnownPendingLevel;
+ var nextLevel = lastPingedTime > nextKnownPendingLevel ? lastPingedTime : nextKnownPendingLevel;
+
+ if ( nextLevel <= Idle && firstPendingTime !== nextLevel) {
+ // Don't work on Idle/Never priority unless everything else is committed.
+ return NoWork;
+ }
+
+ return nextLevel;
+ } // Use this function to schedule a task for a root. There's only one task per
+ // root; if a task was already scheduled, we'll check to make sure the
+ // expiration time of the existing task is the same as the expiration time of
+ // the next level that the root has work on. This function is called on every
+ // update, and right before exiting a task.
+
+
+ function ensureRootIsScheduled(root) {
+ var lastExpiredTime = root.lastExpiredTime;
+
+ if (lastExpiredTime !== NoWork) {
+ // Special case: Expired work should flush synchronously.
+ root.callbackExpirationTime = Sync;
+ root.callbackPriority = ImmediatePriority;
+ root.callbackNode = scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root));
+ return;
+ }
+
+ var expirationTime = getNextRootExpirationTimeToWorkOn(root);
+ var existingCallbackNode = root.callbackNode;
+
+ if (expirationTime === NoWork) {
+ // There's nothing to work on.
+ if (existingCallbackNode !== null) {
+ root.callbackNode = null;
+ root.callbackExpirationTime = NoWork;
+ root.callbackPriority = NoPriority;
+ }
+
+ return;
+ } // TODO: If this is an update, we already read the current time. Pass the
+ // time as an argument.
+
+
+ var currentTime = requestCurrentTimeForUpdate();
+ var priorityLevel = inferPriorityFromExpirationTime(currentTime, expirationTime); // If there's an existing render task, confirm it has the correct priority and
+ // expiration time. Otherwise, we'll cancel it and schedule a new one.
+
+ if (existingCallbackNode !== null) {
+ var existingCallbackPriority = root.callbackPriority;
+ var existingCallbackExpirationTime = root.callbackExpirationTime;
+
+ if ( // Callback must have the exact same expiration time.
+ existingCallbackExpirationTime === expirationTime && // Callback must have greater or equal priority.
+ existingCallbackPriority >= priorityLevel) {
+ // Existing callback is sufficient.
+ return;
+ } // Need to schedule a new task.
+ // TODO: Instead of scheduling a new task, we should be able to change the
+ // priority of the existing one.
+
+
+ cancelCallback(existingCallbackNode);
+ }
+
+ root.callbackExpirationTime = expirationTime;
+ root.callbackPriority = priorityLevel;
+ var callbackNode;
+
+ if (expirationTime === Sync) {
+ // Sync React callbacks are scheduled on a special internal queue
+ callbackNode = scheduleSyncCallback(performSyncWorkOnRoot.bind(null, root));
+ } else {
+ callbackNode = scheduleCallback(priorityLevel, performConcurrentWorkOnRoot.bind(null, root), // Compute a task timeout based on the expiration time. This also affects
+ // ordering because tasks are processed in timeout order.
+ {
+ timeout: expirationTimeToMs(expirationTime) - now()
+ });
+ }
+
+ root.callbackNode = callbackNode;
+ } // This is the entry point for every concurrent task, i.e. anything that
+ // goes through Scheduler.
+
+
+ function performConcurrentWorkOnRoot(root, didTimeout) {
+ // Since we know we're in a React event, we can clear the current
+ // event time. The next update will compute a new event time.
+ currentEventTime = NoWork;
+
+ if (didTimeout) {
+ // The render task took too long to complete. Mark the current time as
+ // expired to synchronously render all expired work in a single batch.
+ var currentTime = requestCurrentTimeForUpdate();
+ markRootExpiredAtTime(root, currentTime); // This will schedule a synchronous callback.
+
+ ensureRootIsScheduled(root);
+ return null;
+ } // Determine the next expiration time to work on, using the fields stored
+ // on the root.
+
+
+ var expirationTime = getNextRootExpirationTimeToWorkOn(root);
+
+ if (expirationTime !== NoWork) {
+ var originalCallbackNode = root.callbackNode;
+
+ if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {
+ {
+ throw Error( "Should not already be working." );
+ }
+ }
+
+ flushPassiveEffects(); // If the root or expiration time have changed, throw out the existing stack
+ // and prepare a fresh one. Otherwise we'll continue where we left off.
+
+ if (root !== workInProgressRoot || expirationTime !== renderExpirationTime$1) {
+ prepareFreshStack(root, expirationTime);
+ startWorkOnPendingInteractions(root, expirationTime);
+ } // If we have a work-in-progress fiber, it means there's still work to do
+ // in this root.
+
+
+ if (workInProgress !== null) {
+ var prevExecutionContext = executionContext;
+ executionContext |= RenderContext;
+ var prevDispatcher = pushDispatcher();
+ var prevInteractions = pushInteractions(root);
+ startWorkLoopTimer(workInProgress);
+
+ do {
+ try {
+ workLoopConcurrent();
+ break;
+ } catch (thrownValue) {
+ handleError(root, thrownValue);
+ }
+ } while (true);
+
+ resetContextDependencies();
+ executionContext = prevExecutionContext;
+ popDispatcher(prevDispatcher);
+
+ {
+ popInteractions(prevInteractions);
+ }
+
+ if (workInProgressRootExitStatus === RootFatalErrored) {
+ var fatalError = workInProgressRootFatalError;
+ stopInterruptedWorkLoopTimer();
+ prepareFreshStack(root, expirationTime);
+ markRootSuspendedAtTime(root, expirationTime);
+ ensureRootIsScheduled(root);
+ throw fatalError;
+ }
+
+ if (workInProgress !== null) {
+ // There's still work left over. Exit without committing.
+ stopInterruptedWorkLoopTimer();
+ } else {
+ // We now have a consistent tree. The next step is either to commit it,
+ // or, if something suspended, wait to commit it after a timeout.
+ stopFinishedWorkLoopTimer();
+ var finishedWork = root.finishedWork = root.current.alternate;
+ root.finishedExpirationTime = expirationTime;
+ finishConcurrentRender(root, finishedWork, workInProgressRootExitStatus, expirationTime);
+ }
+
+ ensureRootIsScheduled(root);
+
+ if (root.callbackNode === originalCallbackNode) {
+ // The task node scheduled for this root is the same one that's
+ // currently executed. Need to return a continuation.
+ return performConcurrentWorkOnRoot.bind(null, root);
+ }
+ }
+ }
+
+ return null;
+ }
+
+ function finishConcurrentRender(root, finishedWork, exitStatus, expirationTime) {
+ // Set this to null to indicate there's no in-progress render.
+ workInProgressRoot = null;
+
+ switch (exitStatus) {
+ case RootIncomplete:
+ case RootFatalErrored:
+ {
+ {
+ {
+ throw Error( "Root did not complete. This is a bug in React." );
+ }
+ }
+ }
+ // Flow knows about invariant, so it complains if I add a break
+ // statement, but eslint doesn't know about invariant, so it complains
+ // if I do. eslint-disable-next-line no-fallthrough
+
+ case RootErrored:
+ {
+ // If this was an async render, the error may have happened due to
+ // a mutation in a concurrent event. Try rendering one more time,
+ // synchronously, to see if the error goes away. If there are
+ // lower priority updates, let's include those, too, in case they
+ // fix the inconsistency. Render at Idle to include all updates.
+ // If it was Idle or Never or some not-yet-invented time, render
+ // at that time.
+ markRootExpiredAtTime(root, expirationTime > Idle ? Idle : expirationTime); // We assume that this second render pass will be synchronous
+ // and therefore not hit this path again.
+
+ break;
+ }
+
+ case RootSuspended:
+ {
+ markRootSuspendedAtTime(root, expirationTime);
+ var lastSuspendedTime = root.lastSuspendedTime;
+
+ if (expirationTime === lastSuspendedTime) {
+ root.nextKnownPendingLevel = getRemainingExpirationTime(finishedWork);
+ } // We have an acceptable loading state. We need to figure out if we
+ // should immediately commit it or wait a bit.
+ // If we have processed new updates during this render, we may now
+ // have a new loading state ready. We want to ensure that we commit
+ // that as soon as possible.
+
+
+ var hasNotProcessedNewUpdates = workInProgressRootLatestProcessedExpirationTime === Sync;
+
+ if (hasNotProcessedNewUpdates && // do not delay if we're inside an act() scope
+ !( IsThisRendererActing.current)) {
+ // If we have not processed any new updates during this pass, then
+ // this is either a retry of an existing fallback state or a
+ // hidden tree. Hidden trees shouldn't be batched with other work
+ // and after that's fixed it can only be a retry. We're going to
+ // throttle committing retries so that we don't show too many
+ // loading states too quickly.
+ var msUntilTimeout = globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now(); // Don't bother with a very short suspense time.
+
+ if (msUntilTimeout > 10) {
+ if (workInProgressRootHasPendingPing) {
+ var lastPingedTime = root.lastPingedTime;
+
+ if (lastPingedTime === NoWork || lastPingedTime >= expirationTime) {
+ // This render was pinged but we didn't get to restart
+ // earlier so try restarting now instead.
+ root.lastPingedTime = expirationTime;
+ prepareFreshStack(root, expirationTime);
+ break;
+ }
+ }
+
+ var nextTime = getNextRootExpirationTimeToWorkOn(root);
+
+ if (nextTime !== NoWork && nextTime !== expirationTime) {
+ // There's additional work on this root.
+ break;
+ }
+
+ if (lastSuspendedTime !== NoWork && lastSuspendedTime !== expirationTime) {
+ // We should prefer to render the fallback of at the last
+ // suspended level. Ping the last suspended level to try
+ // rendering it again.
+ root.lastPingedTime = lastSuspendedTime;
+ break;
+ } // The render is suspended, it hasn't timed out, and there's no
+ // lower priority work to do. Instead of committing the fallback
+ // immediately, wait for more data to arrive.
+
+
+ root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root), msUntilTimeout);
+ break;
+ }
+ } // The work expired. Commit immediately.
+
+
+ commitRoot(root);
+ break;
+ }
+
+ case RootSuspendedWithDelay:
+ {
+ markRootSuspendedAtTime(root, expirationTime);
+ var _lastSuspendedTime = root.lastSuspendedTime;
+
+ if (expirationTime === _lastSuspendedTime) {
+ root.nextKnownPendingLevel = getRemainingExpirationTime(finishedWork);
+ }
+
+ if ( // do not delay if we're inside an act() scope
+ !( IsThisRendererActing.current)) {
+ // We're suspended in a state that should be avoided. We'll try to
+ // avoid committing it for as long as the timeouts let us.
+ if (workInProgressRootHasPendingPing) {
+ var _lastPingedTime = root.lastPingedTime;
+
+ if (_lastPingedTime === NoWork || _lastPingedTime >= expirationTime) {
+ // This render was pinged but we didn't get to restart earlier
+ // so try restarting now instead.
+ root.lastPingedTime = expirationTime;
+ prepareFreshStack(root, expirationTime);
+ break;
+ }
+ }
+
+ var _nextTime = getNextRootExpirationTimeToWorkOn(root);
+
+ if (_nextTime !== NoWork && _nextTime !== expirationTime) {
+ // There's additional work on this root.
+ break;
+ }
+
+ if (_lastSuspendedTime !== NoWork && _lastSuspendedTime !== expirationTime) {
+ // We should prefer to render the fallback of at the last
+ // suspended level. Ping the last suspended level to try
+ // rendering it again.
+ root.lastPingedTime = _lastSuspendedTime;
+ break;
+ }
+
+ var _msUntilTimeout;
+
+ if (workInProgressRootLatestSuspenseTimeout !== Sync) {
+ // We have processed a suspense config whose expiration time we
+ // can use as the timeout.
+ _msUntilTimeout = expirationTimeToMs(workInProgressRootLatestSuspenseTimeout) - now();
+ } else if (workInProgressRootLatestProcessedExpirationTime === Sync) {
+ // This should never normally happen because only new updates
+ // cause delayed states, so we should have processed something.
+ // However, this could also happen in an offscreen tree.
+ _msUntilTimeout = 0;
+ } else {
+ // If we don't have a suspense config, we're going to use a
+ // heuristic to determine how long we can suspend.
+ var eventTimeMs = inferTimeFromExpirationTime(workInProgressRootLatestProcessedExpirationTime);
+ var currentTimeMs = now();
+ var timeUntilExpirationMs = expirationTimeToMs(expirationTime) - currentTimeMs;
+ var timeElapsed = currentTimeMs - eventTimeMs;
+
+ if (timeElapsed < 0) {
+ // We get this wrong some time since we estimate the time.
+ timeElapsed = 0;
+ }
+
+ _msUntilTimeout = jnd(timeElapsed) - timeElapsed; // Clamp the timeout to the expiration time. TODO: Once the
+ // event time is exact instead of inferred from expiration time
+ // we don't need this.
+
+ if (timeUntilExpirationMs < _msUntilTimeout) {
+ _msUntilTimeout = timeUntilExpirationMs;
+ }
+ } // Don't bother with a very short suspense time.
+
+
+ if (_msUntilTimeout > 10) {
+ // The render is suspended, it hasn't timed out, and there's no
+ // lower priority work to do. Instead of committing the fallback
+ // immediately, wait for more data to arrive.
+ root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root), _msUntilTimeout);
+ break;
+ }
+ } // The work expired. Commit immediately.
+
+
+ commitRoot(root);
+ break;
+ }
+
+ case RootCompleted:
+ {
+ // The work completed. Ready to commit.
+ if ( // do not delay if we're inside an act() scope
+ !( IsThisRendererActing.current) && workInProgressRootLatestProcessedExpirationTime !== Sync && workInProgressRootCanSuspendUsingConfig !== null) {
+ // If we have exceeded the minimum loading delay, which probably
+ // means we have shown a spinner already, we might have to suspend
+ // a bit longer to ensure that the spinner is shown for
+ // enough time.
+ var _msUntilTimeout2 = computeMsUntilSuspenseLoadingDelay(workInProgressRootLatestProcessedExpirationTime, expirationTime, workInProgressRootCanSuspendUsingConfig);
+
+ if (_msUntilTimeout2 > 10) {
+ markRootSuspendedAtTime(root, expirationTime);
+ root.timeoutHandle = scheduleTimeout(commitRoot.bind(null, root), _msUntilTimeout2);
+ break;
+ }
+ }
+
+ commitRoot(root);
+ break;
+ }
+
+ default:
+ {
+ {
+ {
+ throw Error( "Unknown root exit status." );
+ }
+ }
+ }
+ }
+ } // This is the entry point for synchronous tasks that don't go
+ // through Scheduler
+
+
+ function performSyncWorkOnRoot(root) {
+ // Check if there's expired work on this root. Otherwise, render at Sync.
+ var lastExpiredTime = root.lastExpiredTime;
+ var expirationTime = lastExpiredTime !== NoWork ? lastExpiredTime : Sync;
+
+ if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {
+ {
+ throw Error( "Should not already be working." );
+ }
+ }
+
+ flushPassiveEffects(); // If the root or expiration time have changed, throw out the existing stack
+ // and prepare a fresh one. Otherwise we'll continue where we left off.
+
+ if (root !== workInProgressRoot || expirationTime !== renderExpirationTime$1) {
+ prepareFreshStack(root, expirationTime);
+ startWorkOnPendingInteractions(root, expirationTime);
+ } // If we have a work-in-progress fiber, it means there's still work to do
+ // in this root.
+
+
+ if (workInProgress !== null) {
+ var prevExecutionContext = executionContext;
+ executionContext |= RenderContext;
+ var prevDispatcher = pushDispatcher();
+ var prevInteractions = pushInteractions(root);
+ startWorkLoopTimer(workInProgress);
+
+ do {
+ try {
+ workLoopSync();
+ break;
+ } catch (thrownValue) {
+ handleError(root, thrownValue);
+ }
+ } while (true);
+
+ resetContextDependencies();
+ executionContext = prevExecutionContext;
+ popDispatcher(prevDispatcher);
+
+ {
+ popInteractions(prevInteractions);
+ }
+
+ if (workInProgressRootExitStatus === RootFatalErrored) {
+ var fatalError = workInProgressRootFatalError;
+ stopInterruptedWorkLoopTimer();
+ prepareFreshStack(root, expirationTime);
+ markRootSuspendedAtTime(root, expirationTime);
+ ensureRootIsScheduled(root);
+ throw fatalError;
+ }
+
+ if (workInProgress !== null) {
+ // This is a sync render, so we should have finished the whole tree.
+ {
+ {
+ throw Error( "Cannot commit an incomplete root. This error is likely caused by a bug in React. Please file an issue." );
+ }
+ }
+ } else {
+ // We now have a consistent tree. Because this is a sync render, we
+ // will commit it even if something suspended.
+ stopFinishedWorkLoopTimer();
+ root.finishedWork = root.current.alternate;
+ root.finishedExpirationTime = expirationTime;
+ finishSyncRender(root);
+ } // Before exiting, make sure there's a callback scheduled for the next
+ // pending level.
+
+
+ ensureRootIsScheduled(root);
+ }
+
+ return null;
+ }
+
+ function finishSyncRender(root) {
+ // Set this to null to indicate there's no in-progress render.
+ workInProgressRoot = null;
+ commitRoot(root);
+ }
+ function flushDiscreteUpdates() {
+ // TODO: Should be able to flush inside batchedUpdates, but not inside `act`.
+ // However, `act` uses `batchedUpdates`, so there's no way to distinguish
+ // those two cases. Need to fix this before exposing flushDiscreteUpdates
+ // as a public API.
+ if ((executionContext & (BatchedContext | RenderContext | CommitContext)) !== NoContext) {
+ {
+ if ((executionContext & RenderContext) !== NoContext) {
+ error('unstable_flushDiscreteUpdates: Cannot flush updates when React is ' + 'already rendering.');
+ }
+ } // We're already rendering, so we can't synchronously flush pending work.
+ // This is probably a nested event dispatch triggered by a lifecycle/effect,
+ // like `el.focus()`. Exit.
+
+
+ return;
+ }
+
+ flushPendingDiscreteUpdates(); // If the discrete updates scheduled passive effects, flush them now so that
+ // they fire before the next serial event.
+
+ flushPassiveEffects();
+ }
+ function syncUpdates(fn, a, b, c) {
+ return runWithPriority$1(ImmediatePriority, fn.bind(null, a, b, c));
+ }
+
+ function flushPendingDiscreteUpdates() {
+ if (rootsWithPendingDiscreteUpdates !== null) {
+ // For each root with pending discrete updates, schedule a callback to
+ // immediately flush them.
+ var roots = rootsWithPendingDiscreteUpdates;
+ rootsWithPendingDiscreteUpdates = null;
+ roots.forEach(function (expirationTime, root) {
+ markRootExpiredAtTime(root, expirationTime);
+ ensureRootIsScheduled(root);
+ }); // Now flush the immediate queue.
+
+ flushSyncCallbackQueue();
+ }
+ }
+
+ function batchedUpdates$1(fn, a) {
+ var prevExecutionContext = executionContext;
+ executionContext |= BatchedContext;
+
+ try {
+ return fn(a);
+ } finally {
+ executionContext = prevExecutionContext;
+
+ if (executionContext === NoContext) {
+ // Flush the immediate callbacks that were scheduled during this batch
+ flushSyncCallbackQueue();
+ }
+ }
+ }
+ function batchedEventUpdates$1(fn, a) {
+ var prevExecutionContext = executionContext;
+ executionContext |= EventContext;
+
+ try {
+ return fn(a);
+ } finally {
+ executionContext = prevExecutionContext;
+
+ if (executionContext === NoContext) {
+ // Flush the immediate callbacks that were scheduled during this batch
+ flushSyncCallbackQueue();
+ }
+ }
+ }
+ function discreteUpdates$1(fn, a, b, c, d) {
+ var prevExecutionContext = executionContext;
+ executionContext |= DiscreteEventContext;
+
+ try {
+ // Should this
+ return runWithPriority$1(UserBlockingPriority$1, fn.bind(null, a, b, c, d));
+ } finally {
+ executionContext = prevExecutionContext;
+
+ if (executionContext === NoContext) {
+ // Flush the immediate callbacks that were scheduled during this batch
+ flushSyncCallbackQueue();
+ }
+ }
+ }
+ function unbatchedUpdates(fn, a) {
+ var prevExecutionContext = executionContext;
+ executionContext &= ~BatchedContext;
+ executionContext |= LegacyUnbatchedContext;
+
+ try {
+ return fn(a);
+ } finally {
+ executionContext = prevExecutionContext;
+
+ if (executionContext === NoContext) {
+ // Flush the immediate callbacks that were scheduled during this batch
+ flushSyncCallbackQueue();
+ }
+ }
+ }
+ function flushSync(fn, a) {
+ if ((executionContext & (RenderContext | CommitContext)) !== NoContext) {
+ {
+ {
+ throw Error( "flushSync was called from inside a lifecycle method. It cannot be called when React is already rendering." );
+ }
+ }
+ }
+
+ var prevExecutionContext = executionContext;
+ executionContext |= BatchedContext;
+
+ try {
+ return runWithPriority$1(ImmediatePriority, fn.bind(null, a));
+ } finally {
+ executionContext = prevExecutionContext; // Flush the immediate callbacks that were scheduled during this batch.
+ // Note that this will happen even if batchedUpdates is higher up
+ // the stack.
+
+ flushSyncCallbackQueue();
+ }
+ }
+
+ function prepareFreshStack(root, expirationTime) {
+ root.finishedWork = null;
+ root.finishedExpirationTime = NoWork;
+ var timeoutHandle = root.timeoutHandle;
+
+ if (timeoutHandle !== noTimeout) {
+ // The root previous suspended and scheduled a timeout to commit a fallback
+ // state. Now that we have additional work, cancel the timeout.
+ root.timeoutHandle = noTimeout; // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above
+
+ cancelTimeout(timeoutHandle);
+ }
+
+ if (workInProgress !== null) {
+ var interruptedWork = workInProgress.return;
+
+ while (interruptedWork !== null) {
+ unwindInterruptedWork(interruptedWork);
+ interruptedWork = interruptedWork.return;
+ }
+ }
+
+ workInProgressRoot = root;
+ workInProgress = createWorkInProgress(root.current, null);
+ renderExpirationTime$1 = expirationTime;
+ workInProgressRootExitStatus = RootIncomplete;
+ workInProgressRootFatalError = null;
+ workInProgressRootLatestProcessedExpirationTime = Sync;
+ workInProgressRootLatestSuspenseTimeout = Sync;
+ workInProgressRootCanSuspendUsingConfig = null;
+ workInProgressRootNextUnprocessedUpdateTime = NoWork;
+ workInProgressRootHasPendingPing = false;
+
+ {
+ spawnedWorkDuringRender = null;
+ }
+
+ {
+ ReactStrictModeWarnings.discardPendingWarnings();
+ }
+ }
+
+ function handleError(root, thrownValue) {
+ do {
+ try {
+ // Reset module-level state that was set during the render phase.
+ resetContextDependencies();
+ resetHooksAfterThrow();
+ resetCurrentFiber();
+
+ if (workInProgress === null || workInProgress.return === null) {
+ // Expected to be working on a non-root fiber. This is a fatal error
+ // because there's no ancestor that can handle it; the root is
+ // supposed to capture all errors that weren't caught by an error
+ // boundary.
+ workInProgressRootExitStatus = RootFatalErrored;
+ workInProgressRootFatalError = thrownValue; // Set `workInProgress` to null. This represents advancing to the next
+ // sibling, or the parent if there are no siblings. But since the root
+ // has no siblings nor a parent, we set it to null. Usually this is
+ // handled by `completeUnitOfWork` or `unwindWork`, but since we're
+ // interntionally not calling those, we need set it here.
+ // TODO: Consider calling `unwindWork` to pop the contexts.
+
+ workInProgress = null;
+ return null;
+ }
+
+ if (enableProfilerTimer && workInProgress.mode & ProfileMode) {
+ // Record the time spent rendering before an error was thrown. This
+ // avoids inaccurate Profiler durations in the case of a
+ // suspended render.
+ stopProfilerTimerIfRunningAndRecordDelta(workInProgress, true);
+ }
+
+ throwException(root, workInProgress.return, workInProgress, thrownValue, renderExpirationTime$1);
+ workInProgress = completeUnitOfWork(workInProgress);
+ } catch (yetAnotherThrownValue) {
+ // Something in the return path also threw.
+ thrownValue = yetAnotherThrownValue;
+ continue;
+ } // Return to the normal work loop.
+
+
+ return;
+ } while (true);
+ }
+
+ function pushDispatcher(root) {
+ var prevDispatcher = ReactCurrentDispatcher$1.current;
+ ReactCurrentDispatcher$1.current = ContextOnlyDispatcher;
+
+ if (prevDispatcher === null) {
+ // The React isomorphic package does not include a default dispatcher.
+ // Instead the first renderer will lazily attach one, in order to give
+ // nicer error messages.
+ return ContextOnlyDispatcher;
+ } else {
+ return prevDispatcher;
+ }
+ }
+
+ function popDispatcher(prevDispatcher) {
+ ReactCurrentDispatcher$1.current = prevDispatcher;
+ }
+
+ function pushInteractions(root) {
+ {
+ var prevInteractions = __interactionsRef.current;
+ __interactionsRef.current = root.memoizedInteractions;
+ return prevInteractions;
+ }
+ }
+
+ function popInteractions(prevInteractions) {
+ {
+ __interactionsRef.current = prevInteractions;
+ }
+ }
+
+ function markCommitTimeOfFallback() {
+ globalMostRecentFallbackTime = now();
+ }
+ function markRenderEventTimeAndConfig(expirationTime, suspenseConfig) {
+ if (expirationTime < workInProgressRootLatestProcessedExpirationTime && expirationTime > Idle) {
+ workInProgressRootLatestProcessedExpirationTime = expirationTime;
+ }
+
+ if (suspenseConfig !== null) {
+ if (expirationTime < workInProgressRootLatestSuspenseTimeout && expirationTime > Idle) {
+ workInProgressRootLatestSuspenseTimeout = expirationTime; // Most of the time we only have one config and getting wrong is not bad.
+
+ workInProgressRootCanSuspendUsingConfig = suspenseConfig;
+ }
+ }
+ }
+ function markUnprocessedUpdateTime(expirationTime) {
+ if (expirationTime > workInProgressRootNextUnprocessedUpdateTime) {
+ workInProgressRootNextUnprocessedUpdateTime = expirationTime;
+ }
+ }
+ function renderDidSuspend() {
+ if (workInProgressRootExitStatus === RootIncomplete) {
+ workInProgressRootExitStatus = RootSuspended;
+ }
+ }
+ function renderDidSuspendDelayIfPossible() {
+ if (workInProgressRootExitStatus === RootIncomplete || workInProgressRootExitStatus === RootSuspended) {
+ workInProgressRootExitStatus = RootSuspendedWithDelay;
+ } // Check if there's a lower priority update somewhere else in the tree.
+
+
+ if (workInProgressRootNextUnprocessedUpdateTime !== NoWork && workInProgressRoot !== null) {
+ // Mark the current render as suspended, and then mark that there's a
+ // pending update.
+ // TODO: This should immediately interrupt the current render, instead
+ // of waiting until the next time we yield.
+ markRootSuspendedAtTime(workInProgressRoot, renderExpirationTime$1);
+ markRootUpdatedAtTime(workInProgressRoot, workInProgressRootNextUnprocessedUpdateTime);
+ }
+ }
+ function renderDidError() {
+ if (workInProgressRootExitStatus !== RootCompleted) {
+ workInProgressRootExitStatus = RootErrored;
+ }
+ } // Called during render to determine if anything has suspended.
+ // Returns false if we're not sure.
+
+ function renderHasNotSuspendedYet() {
+ // If something errored or completed, we can't really be sure,
+ // so those are false.
+ return workInProgressRootExitStatus === RootIncomplete;
+ }
+
+ function inferTimeFromExpirationTime(expirationTime) {
+ // We don't know exactly when the update was scheduled, but we can infer an
+ // approximate start time from the expiration time.
+ var earliestExpirationTimeMs = expirationTimeToMs(expirationTime);
+ return earliestExpirationTimeMs - LOW_PRIORITY_EXPIRATION;
+ }
+
+ function inferTimeFromExpirationTimeWithSuspenseConfig(expirationTime, suspenseConfig) {
+ // We don't know exactly when the update was scheduled, but we can infer an
+ // approximate start time from the expiration time by subtracting the timeout
+ // that was added to the event time.
+ var earliestExpirationTimeMs = expirationTimeToMs(expirationTime);
+ return earliestExpirationTimeMs - (suspenseConfig.timeoutMs | 0 || LOW_PRIORITY_EXPIRATION);
+ } // The work loop is an extremely hot path. Tell Closure not to inline it.
+
+ /** @noinline */
+
+
+ function workLoopSync() {
+ // Already timed out, so perform work without checking if we need to yield.
+ while (workInProgress !== null) {
+ workInProgress = performUnitOfWork(workInProgress);
+ }
+ }
+ /** @noinline */
+
+
+ function workLoopConcurrent() {
+ // Perform work until Scheduler asks us to yield
+ while (workInProgress !== null && !shouldYield()) {
+ workInProgress = performUnitOfWork(workInProgress);
+ }
+ }
+
+ function performUnitOfWork(unitOfWork) {
+ // The current, flushed, state of this fiber is the alternate. Ideally
+ // nothing should rely on this, but relying on it here means that we don't
+ // need an additional field on the work in progress.
+ var current = unitOfWork.alternate;
+ startWorkTimer(unitOfWork);
+ setCurrentFiber(unitOfWork);
+ var next;
+
+ if ( (unitOfWork.mode & ProfileMode) !== NoMode) {
+ startProfilerTimer(unitOfWork);
+ next = beginWork$1(current, unitOfWork, renderExpirationTime$1);
+ stopProfilerTimerIfRunningAndRecordDelta(unitOfWork, true);
+ } else {
+ next = beginWork$1(current, unitOfWork, renderExpirationTime$1);
+ }
+
+ resetCurrentFiber();
+ unitOfWork.memoizedProps = unitOfWork.pendingProps;
+
+ if (next === null) {
+ // If this doesn't spawn new work, complete the current work.
+ next = completeUnitOfWork(unitOfWork);
+ }
+
+ ReactCurrentOwner$2.current = null;
+ return next;
+ }
+
+ function completeUnitOfWork(unitOfWork) {
+ // Attempt to complete the current unit of work, then move to the next
+ // sibling. If there are no more siblings, return to the parent fiber.
+ workInProgress = unitOfWork;
+
+ do {
+ // The current, flushed, state of this fiber is the alternate. Ideally
+ // nothing should rely on this, but relying on it here means that we don't
+ // need an additional field on the work in progress.
+ var current = workInProgress.alternate;
+ var returnFiber = workInProgress.return; // Check if the work completed or if something threw.
+
+ if ((workInProgress.effectTag & Incomplete) === NoEffect) {
+ setCurrentFiber(workInProgress);
+ var next = void 0;
+
+ if ( (workInProgress.mode & ProfileMode) === NoMode) {
+ next = completeWork(current, workInProgress, renderExpirationTime$1);
+ } else {
+ startProfilerTimer(workInProgress);
+ next = completeWork(current, workInProgress, renderExpirationTime$1); // Update render duration assuming we didn't error.
+
+ stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false);
+ }
+
+ stopWorkTimer(workInProgress);
+ resetCurrentFiber();
+ resetChildExpirationTime(workInProgress);
+
+ if (next !== null) {
+ // Completing this fiber spawned new work. Work on that next.
+ return next;
+ }
+
+ if (returnFiber !== null && // Do not append effects to parents if a sibling failed to complete
+ (returnFiber.effectTag & Incomplete) === NoEffect) {
+ // Append all the effects of the subtree and this fiber onto the effect
+ // list of the parent. The completion order of the children affects the
+ // side-effect order.
+ if (returnFiber.firstEffect === null) {
+ returnFiber.firstEffect = workInProgress.firstEffect;
+ }
+
+ if (workInProgress.lastEffect !== null) {
+ if (returnFiber.lastEffect !== null) {
+ returnFiber.lastEffect.nextEffect = workInProgress.firstEffect;
+ }
+
+ returnFiber.lastEffect = workInProgress.lastEffect;
+ } // If this fiber had side-effects, we append it AFTER the children's
+ // side-effects. We can perform certain side-effects earlier if needed,
+ // by doing multiple passes over the effect list. We don't want to
+ // schedule our own side-effect on our own list because if end up
+ // reusing children we'll schedule this effect onto itself since we're
+ // at the end.
+
+
+ var effectTag = workInProgress.effectTag; // Skip both NoWork and PerformedWork tags when creating the effect
+ // list. PerformedWork effect is read by React DevTools but shouldn't be
+ // committed.
+
+ if (effectTag > PerformedWork) {
+ if (returnFiber.lastEffect !== null) {
+ returnFiber.lastEffect.nextEffect = workInProgress;
+ } else {
+ returnFiber.firstEffect = workInProgress;
+ }
+
+ returnFiber.lastEffect = workInProgress;
+ }
+ }
+ } else {
+ // This fiber did not complete because something threw. Pop values off
+ // the stack without entering the complete phase. If this is a boundary,
+ // capture values if possible.
+ var _next = unwindWork(workInProgress); // Because this fiber did not complete, don't reset its expiration time.
+
+
+ if ( (workInProgress.mode & ProfileMode) !== NoMode) {
+ // Record the render duration for the fiber that errored.
+ stopProfilerTimerIfRunningAndRecordDelta(workInProgress, false); // Include the time spent working on failed children before continuing.
+
+ var actualDuration = workInProgress.actualDuration;
+ var child = workInProgress.child;
+
+ while (child !== null) {
+ actualDuration += child.actualDuration;
+ child = child.sibling;
+ }
+
+ workInProgress.actualDuration = actualDuration;
+ }
+
+ if (_next !== null) {
+ // If completing this work spawned new work, do that next. We'll come
+ // back here again.
+ // Since we're restarting, remove anything that is not a host effect
+ // from the effect tag.
+ // TODO: The name stopFailedWorkTimer is misleading because Suspense
+ // also captures and restarts.
+ stopFailedWorkTimer(workInProgress);
+ _next.effectTag &= HostEffectMask;
+ return _next;
+ }
+
+ stopWorkTimer(workInProgress);
+
+ if (returnFiber !== null) {
+ // Mark the parent fiber as incomplete and clear its effect list.
+ returnFiber.firstEffect = returnFiber.lastEffect = null;
+ returnFiber.effectTag |= Incomplete;
+ }
+ }
+
+ var siblingFiber = workInProgress.sibling;
+
+ if (siblingFiber !== null) {
+ // If there is more work to do in this returnFiber, do that next.
+ return siblingFiber;
+ } // Otherwise, return to the parent
+
+
+ workInProgress = returnFiber;
+ } while (workInProgress !== null); // We've reached the root.
+
+
+ if (workInProgressRootExitStatus === RootIncomplete) {
+ workInProgressRootExitStatus = RootCompleted;
+ }
+
+ return null;
+ }
+
+ function getRemainingExpirationTime(fiber) {
+ var updateExpirationTime = fiber.expirationTime;
+ var childExpirationTime = fiber.childExpirationTime;
+ return updateExpirationTime > childExpirationTime ? updateExpirationTime : childExpirationTime;
+ }
+
+ function resetChildExpirationTime(completedWork) {
+ if (renderExpirationTime$1 !== Never && completedWork.childExpirationTime === Never) {
+ // The children of this component are hidden. Don't bubble their
+ // expiration times.
+ return;
+ }
+
+ var newChildExpirationTime = NoWork; // Bubble up the earliest expiration time.
+
+ if ( (completedWork.mode & ProfileMode) !== NoMode) {
+ // In profiling mode, resetChildExpirationTime is also used to reset
+ // profiler durations.
+ var actualDuration = completedWork.actualDuration;
+ var treeBaseDuration = completedWork.selfBaseDuration; // When a fiber is cloned, its actualDuration is reset to 0. This value will
+ // only be updated if work is done on the fiber (i.e. it doesn't bailout).
+ // When work is done, it should bubble to the parent's actualDuration. If
+ // the fiber has not been cloned though, (meaning no work was done), then
+ // this value will reflect the amount of time spent working on a previous
+ // render. In that case it should not bubble. We determine whether it was
+ // cloned by comparing the child pointer.
+
+ var shouldBubbleActualDurations = completedWork.alternate === null || completedWork.child !== completedWork.alternate.child;
+ var child = completedWork.child;
+
+ while (child !== null) {
+ var childUpdateExpirationTime = child.expirationTime;
+ var childChildExpirationTime = child.childExpirationTime;
+
+ if (childUpdateExpirationTime > newChildExpirationTime) {
+ newChildExpirationTime = childUpdateExpirationTime;
+ }
+
+ if (childChildExpirationTime > newChildExpirationTime) {
+ newChildExpirationTime = childChildExpirationTime;
+ }
+
+ if (shouldBubbleActualDurations) {
+ actualDuration += child.actualDuration;
+ }
+
+ treeBaseDuration += child.treeBaseDuration;
+ child = child.sibling;
+ }
+
+ completedWork.actualDuration = actualDuration;
+ completedWork.treeBaseDuration = treeBaseDuration;
+ } else {
+ var _child = completedWork.child;
+
+ while (_child !== null) {
+ var _childUpdateExpirationTime = _child.expirationTime;
+ var _childChildExpirationTime = _child.childExpirationTime;
+
+ if (_childUpdateExpirationTime > newChildExpirationTime) {
+ newChildExpirationTime = _childUpdateExpirationTime;
+ }
+
+ if (_childChildExpirationTime > newChildExpirationTime) {
+ newChildExpirationTime = _childChildExpirationTime;
+ }
+
+ _child = _child.sibling;
+ }
+ }
+
+ completedWork.childExpirationTime = newChildExpirationTime;
+ }
+
+ function commitRoot(root) {
+ var renderPriorityLevel = getCurrentPriorityLevel();
+ runWithPriority$1(ImmediatePriority, commitRootImpl.bind(null, root, renderPriorityLevel));
+ return null;
+ }
+
+ function commitRootImpl(root, renderPriorityLevel) {
+ do {
+ // `flushPassiveEffects` will call `flushSyncUpdateQueue` at the end, which
+ // means `flushPassiveEffects` will sometimes result in additional
+ // passive effects. So we need to keep flushing in a loop until there are
+ // no more pending effects.
+ // TODO: Might be better if `flushPassiveEffects` did not automatically
+ // flush synchronous work at the end, to avoid factoring hazards like this.
+ flushPassiveEffects();
+ } while (rootWithPendingPassiveEffects !== null);
+
+ flushRenderPhaseStrictModeWarningsInDEV();
+
+ if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {
+ {
+ throw Error( "Should not already be working." );
+ }
+ }
+
+ var finishedWork = root.finishedWork;
+ var expirationTime = root.finishedExpirationTime;
+
+ if (finishedWork === null) {
+ return null;
+ }
+
+ root.finishedWork = null;
+ root.finishedExpirationTime = NoWork;
+
+ if (!(finishedWork !== root.current)) {
+ {
+ throw Error( "Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue." );
+ }
+ } // commitRoot never returns a continuation; it always finishes synchronously.
+ // So we can clear these now to allow a new callback to be scheduled.
+
+
+ root.callbackNode = null;
+ root.callbackExpirationTime = NoWork;
+ root.callbackPriority = NoPriority;
+ root.nextKnownPendingLevel = NoWork;
+ startCommitTimer(); // Update the first and last pending times on this root. The new first
+ // pending time is whatever is left on the root fiber.
+
+ var remainingExpirationTimeBeforeCommit = getRemainingExpirationTime(finishedWork);
+ markRootFinishedAtTime(root, expirationTime, remainingExpirationTimeBeforeCommit);
+
+ if (root === workInProgressRoot) {
+ // We can reset these now that they are finished.
+ workInProgressRoot = null;
+ workInProgress = null;
+ renderExpirationTime$1 = NoWork;
+ } // This indicates that the last root we worked on is not the same one that
+ // we're committing now. This most commonly happens when a suspended root
+ // times out.
+ // Get the list of effects.
+
+
+ var firstEffect;
+
+ if (finishedWork.effectTag > PerformedWork) {
+ // A fiber's effect list consists only of its children, not itself. So if
+ // the root has an effect, we need to add it to the end of the list. The
+ // resulting list is the set that would belong to the root's parent, if it
+ // had one; that is, all the effects in the tree including the root.
+ if (finishedWork.lastEffect !== null) {
+ finishedWork.lastEffect.nextEffect = finishedWork;
+ firstEffect = finishedWork.firstEffect;
+ } else {
+ firstEffect = finishedWork;
+ }
+ } else {
+ // There is no effect on the root.
+ firstEffect = finishedWork.firstEffect;
+ }
+
+ if (firstEffect !== null) {
+ var prevExecutionContext = executionContext;
+ executionContext |= CommitContext;
+ var prevInteractions = pushInteractions(root); // Reset this to null before calling lifecycles
+
+ ReactCurrentOwner$2.current = null; // The commit phase is broken into several sub-phases. We do a separate pass
+ // of the effect list for each phase: all mutation effects come before all
+ // layout effects, and so on.
+ // The first phase a "before mutation" phase. We use this phase to read the
+ // state of the host tree right before we mutate it. This is where
+ // getSnapshotBeforeUpdate is called.
+
+ startCommitSnapshotEffectsTimer();
+ prepareForCommit(root.containerInfo);
+ nextEffect = firstEffect;
+
+ do {
+ {
+ invokeGuardedCallback(null, commitBeforeMutationEffects, null);
+
+ if (hasCaughtError()) {
+ if (!(nextEffect !== null)) {
+ {
+ throw Error( "Should be working on an effect." );
+ }
+ }
+
+ var error = clearCaughtError();
+ captureCommitPhaseError(nextEffect, error);
+ nextEffect = nextEffect.nextEffect;
+ }
+ }
+ } while (nextEffect !== null);
+
+ stopCommitSnapshotEffectsTimer();
+
+ {
+ // Mark the current commit time to be shared by all Profilers in this
+ // batch. This enables them to be grouped later.
+ recordCommitTime();
+ } // The next phase is the mutation phase, where we mutate the host tree.
+
+
+ startCommitHostEffectsTimer();
+ nextEffect = firstEffect;
+
+ do {
+ {
+ invokeGuardedCallback(null, commitMutationEffects, null, root, renderPriorityLevel);
+
+ if (hasCaughtError()) {
+ if (!(nextEffect !== null)) {
+ {
+ throw Error( "Should be working on an effect." );
+ }
+ }
+
+ var _error = clearCaughtError();
+
+ captureCommitPhaseError(nextEffect, _error);
+ nextEffect = nextEffect.nextEffect;
+ }
+ }
+ } while (nextEffect !== null);
+
+ stopCommitHostEffectsTimer();
+ resetAfterCommit(root.containerInfo); // The work-in-progress tree is now the current tree. This must come after
+ // the mutation phase, so that the previous tree is still current during
+ // componentWillUnmount, but before the layout phase, so that the finished
+ // work is current during componentDidMount/Update.
+
+ root.current = finishedWork; // The next phase is the layout phase, where we call effects that read
+ // the host tree after it's been mutated. The idiomatic use case for this is
+ // layout, but class component lifecycles also fire here for legacy reasons.
+
+ startCommitLifeCyclesTimer();
+ nextEffect = firstEffect;
+
+ do {
+ {
+ invokeGuardedCallback(null, commitLayoutEffects, null, root, expirationTime);
+
+ if (hasCaughtError()) {
+ if (!(nextEffect !== null)) {
+ {
+ throw Error( "Should be working on an effect." );
+ }
+ }
+
+ var _error2 = clearCaughtError();
+
+ captureCommitPhaseError(nextEffect, _error2);
+ nextEffect = nextEffect.nextEffect;
+ }
+ }
+ } while (nextEffect !== null);
+
+ stopCommitLifeCyclesTimer();
+ nextEffect = null; // Tell Scheduler to yield at the end of the frame, so the browser has an
+ // opportunity to paint.
+
+ requestPaint();
+
+ {
+ popInteractions(prevInteractions);
+ }
+
+ executionContext = prevExecutionContext;
+ } else {
+ // No effects.
+ root.current = finishedWork; // Measure these anyway so the flamegraph explicitly shows that there were
+ // no effects.
+ // TODO: Maybe there's a better way to report this.
+
+ startCommitSnapshotEffectsTimer();
+ stopCommitSnapshotEffectsTimer();
+
+ {
+ recordCommitTime();
+ }
+
+ startCommitHostEffectsTimer();
+ stopCommitHostEffectsTimer();
+ startCommitLifeCyclesTimer();
+ stopCommitLifeCyclesTimer();
+ }
+
+ stopCommitTimer();
+ var rootDidHavePassiveEffects = rootDoesHavePassiveEffects;
+
+ if (rootDoesHavePassiveEffects) {
+ // This commit has passive effects. Stash a reference to them. But don't
+ // schedule a callback until after flushing layout work.
+ rootDoesHavePassiveEffects = false;
+ rootWithPendingPassiveEffects = root;
+ pendingPassiveEffectsExpirationTime = expirationTime;
+ pendingPassiveEffectsRenderPriority = renderPriorityLevel;
+ } else {
+ // We are done with the effect chain at this point so let's clear the
+ // nextEffect pointers to assist with GC. If we have passive effects, we'll
+ // clear this in flushPassiveEffects.
+ nextEffect = firstEffect;
+
+ while (nextEffect !== null) {
+ var nextNextEffect = nextEffect.nextEffect;
+ nextEffect.nextEffect = null;
+ nextEffect = nextNextEffect;
+ }
+ } // Check if there's remaining work on this root
+
+
+ var remainingExpirationTime = root.firstPendingTime;
+
+ if (remainingExpirationTime !== NoWork) {
+ {
+ if (spawnedWorkDuringRender !== null) {
+ var expirationTimes = spawnedWorkDuringRender;
+ spawnedWorkDuringRender = null;
+
+ for (var i = 0; i < expirationTimes.length; i++) {
+ scheduleInteractions(root, expirationTimes[i], root.memoizedInteractions);
+ }
+ }
+
+ schedulePendingInteractions(root, remainingExpirationTime);
+ }
+ } else {
+ // If there's no remaining work, we can clear the set of already failed
+ // error boundaries.
+ legacyErrorBoundariesThatAlreadyFailed = null;
+ }
+
+ {
+ if (!rootDidHavePassiveEffects) {
+ // If there are no passive effects, then we can complete the pending interactions.
+ // Otherwise, we'll wait until after the passive effects are flushed.
+ // Wait to do this until after remaining work has been scheduled,
+ // so that we don't prematurely signal complete for interactions when there's e.g. hidden work.
+ finishPendingInteractions(root, expirationTime);
+ }
+ }
+
+ if (remainingExpirationTime === Sync) {
+ // Count the number of times the root synchronously re-renders without
+ // finishing. If there are too many, it indicates an infinite update loop.
+ if (root === rootWithNestedUpdates) {
+ nestedUpdateCount++;
+ } else {
+ nestedUpdateCount = 0;
+ rootWithNestedUpdates = root;
+ }
+ } else {
+ nestedUpdateCount = 0;
+ }
+
+ onCommitRoot(finishedWork.stateNode, expirationTime); // Always call this before exiting `commitRoot`, to ensure that any
+ // additional work on this root is scheduled.
+
+ ensureRootIsScheduled(root);
+
+ if (hasUncaughtError) {
+ hasUncaughtError = false;
+ var _error3 = firstUncaughtError;
+ firstUncaughtError = null;
+ throw _error3;
+ }
+
+ if ((executionContext & LegacyUnbatchedContext) !== NoContext) {
+ // This is a legacy edge case. We just committed the initial mount of
+ // a ReactDOM.render-ed root inside of batchedUpdates. The commit fired
+ // synchronously, but layout updates should be deferred until the end
+ // of the batch.
+ return null;
+ } // If layout work was scheduled, flush it now.
+
+
+ flushSyncCallbackQueue();
+ return null;
+ }
+
+ function commitBeforeMutationEffects() {
+ while (nextEffect !== null) {
+ var effectTag = nextEffect.effectTag;
+
+ if ((effectTag & Snapshot) !== NoEffect) {
+ setCurrentFiber(nextEffect);
+ recordEffect();
+ var current = nextEffect.alternate;
+ commitBeforeMutationLifeCycles(current, nextEffect);
+ resetCurrentFiber();
+ }
+
+ if ((effectTag & Passive) !== NoEffect) {
+ // If there are passive effects, schedule a callback to flush at
+ // the earliest opportunity.
+ if (!rootDoesHavePassiveEffects) {
+ rootDoesHavePassiveEffects = true;
+ scheduleCallback(NormalPriority, function () {
+ flushPassiveEffects();
+ return null;
+ });
+ }
+ }
+
+ nextEffect = nextEffect.nextEffect;
+ }
+ }
+
+ function commitMutationEffects(root, renderPriorityLevel) {
+ // TODO: Should probably move the bulk of this function to commitWork.
+ while (nextEffect !== null) {
+ setCurrentFiber(nextEffect);
+ var effectTag = nextEffect.effectTag;
+
+ if (effectTag & ContentReset) {
+ commitResetTextContent(nextEffect);
+ }
+
+ if (effectTag & Ref) {
+ var current = nextEffect.alternate;
+
+ if (current !== null) {
+ commitDetachRef(current);
+ }
+ } // The following switch statement is only concerned about placement,
+ // updates, and deletions. To avoid needing to add a case for every possible
+ // bitmap value, we remove the secondary effects from the effect tag and
+ // switch on that value.
+
+
+ var primaryEffectTag = effectTag & (Placement | Update | Deletion | Hydrating);
+
+ switch (primaryEffectTag) {
+ case Placement:
+ {
+ commitPlacement(nextEffect); // Clear the "placement" from effect tag so that we know that this is
+ // inserted, before any life-cycles like componentDidMount gets called.
+ // TODO: findDOMNode doesn't rely on this any more but isMounted does
+ // and isMounted is deprecated anyway so we should be able to kill this.
+
+ nextEffect.effectTag &= ~Placement;
+ break;
+ }
+
+ case PlacementAndUpdate:
+ {
+ // Placement
+ commitPlacement(nextEffect); // Clear the "placement" from effect tag so that we know that this is
+ // inserted, before any life-cycles like componentDidMount gets called.
+
+ nextEffect.effectTag &= ~Placement; // Update
+
+ var _current = nextEffect.alternate;
+ commitWork(_current, nextEffect);
+ break;
+ }
+
+ case Hydrating:
+ {
+ nextEffect.effectTag &= ~Hydrating;
+ break;
+ }
+
+ case HydratingAndUpdate:
+ {
+ nextEffect.effectTag &= ~Hydrating; // Update
+
+ var _current2 = nextEffect.alternate;
+ commitWork(_current2, nextEffect);
+ break;
+ }
+
+ case Update:
+ {
+ var _current3 = nextEffect.alternate;
+ commitWork(_current3, nextEffect);
+ break;
+ }
+
+ case Deletion:
+ {
+ commitDeletion(root, nextEffect, renderPriorityLevel);
+ break;
+ }
+ } // TODO: Only record a mutation effect if primaryEffectTag is non-zero.
+
+
+ recordEffect();
+ resetCurrentFiber();
+ nextEffect = nextEffect.nextEffect;
+ }
+ }
+
+ function commitLayoutEffects(root, committedExpirationTime) {
+ // TODO: Should probably move the bulk of this function to commitWork.
+ while (nextEffect !== null) {
+ setCurrentFiber(nextEffect);
+ var effectTag = nextEffect.effectTag;
+
+ if (effectTag & (Update | Callback)) {
+ recordEffect();
+ var current = nextEffect.alternate;
+ commitLifeCycles(root, current, nextEffect);
+ }
+
+ if (effectTag & Ref) {
+ recordEffect();
+ commitAttachRef(nextEffect);
+ }
+
+ resetCurrentFiber();
+ nextEffect = nextEffect.nextEffect;
+ }
+ }
+
+ function flushPassiveEffects() {
+ if (pendingPassiveEffectsRenderPriority !== NoPriority) {
+ var priorityLevel = pendingPassiveEffectsRenderPriority > NormalPriority ? NormalPriority : pendingPassiveEffectsRenderPriority;
+ pendingPassiveEffectsRenderPriority = NoPriority;
+ return runWithPriority$1(priorityLevel, flushPassiveEffectsImpl);
+ }
+ }
+
+ function flushPassiveEffectsImpl() {
+ if (rootWithPendingPassiveEffects === null) {
+ return false;
+ }
+
+ var root = rootWithPendingPassiveEffects;
+ var expirationTime = pendingPassiveEffectsExpirationTime;
+ rootWithPendingPassiveEffects = null;
+ pendingPassiveEffectsExpirationTime = NoWork;
+
+ if (!((executionContext & (RenderContext | CommitContext)) === NoContext)) {
+ {
+ throw Error( "Cannot flush passive effects while already rendering." );
+ }
+ }
+
+ var prevExecutionContext = executionContext;
+ executionContext |= CommitContext;
+ var prevInteractions = pushInteractions(root);
+
+ {
+ // Note: This currently assumes there are no passive effects on the root fiber
+ // because the root is not part of its own effect list.
+ // This could change in the future.
+ var _effect2 = root.current.firstEffect;
+
+ while (_effect2 !== null) {
+ {
+ setCurrentFiber(_effect2);
+ invokeGuardedCallback(null, commitPassiveHookEffects, null, _effect2);
+
+ if (hasCaughtError()) {
+ if (!(_effect2 !== null)) {
+ {
+ throw Error( "Should be working on an effect." );
+ }
+ }
+
+ var _error5 = clearCaughtError();
+
+ captureCommitPhaseError(_effect2, _error5);
+ }
+
+ resetCurrentFiber();
+ }
+
+ var nextNextEffect = _effect2.nextEffect; // Remove nextEffect pointer to assist GC
+
+ _effect2.nextEffect = null;
+ _effect2 = nextNextEffect;
+ }
+ }
+
+ {
+ popInteractions(prevInteractions);
+ finishPendingInteractions(root, expirationTime);
+ }
+
+ executionContext = prevExecutionContext;
+ flushSyncCallbackQueue(); // If additional passive effects were scheduled, increment a counter. If this
+ // exceeds the limit, we'll fire a warning.
+
+ nestedPassiveUpdateCount = rootWithPendingPassiveEffects === null ? 0 : nestedPassiveUpdateCount + 1;
+ return true;
+ }
+
+ function isAlreadyFailedLegacyErrorBoundary(instance) {
+ return legacyErrorBoundariesThatAlreadyFailed !== null && legacyErrorBoundariesThatAlreadyFailed.has(instance);
+ }
+ function markLegacyErrorBoundaryAsFailed(instance) {
+ if (legacyErrorBoundariesThatAlreadyFailed === null) {
+ legacyErrorBoundariesThatAlreadyFailed = new Set([instance]);
+ } else {
+ legacyErrorBoundariesThatAlreadyFailed.add(instance);
+ }
+ }
+
+ function prepareToThrowUncaughtError(error) {
+ if (!hasUncaughtError) {
+ hasUncaughtError = true;
+ firstUncaughtError = error;
+ }
+ }
+
+ var onUncaughtError = prepareToThrowUncaughtError;
+
+ function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) {
+ var errorInfo = createCapturedValue(error, sourceFiber);
+ var update = createRootErrorUpdate(rootFiber, errorInfo, Sync);
+ enqueueUpdate(rootFiber, update);
+ var root = markUpdateTimeFromFiberToRoot(rootFiber, Sync);
+
+ if (root !== null) {
+ ensureRootIsScheduled(root);
+ schedulePendingInteractions(root, Sync);
+ }
+ }
+
+ function captureCommitPhaseError(sourceFiber, error) {
+ if (sourceFiber.tag === HostRoot) {
+ // Error was thrown at the root. There is no parent, so the root
+ // itself should capture it.
+ captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error);
+ return;
+ }
+
+ var fiber = sourceFiber.return;
+
+ while (fiber !== null) {
+ if (fiber.tag === HostRoot) {
+ captureCommitPhaseErrorOnRoot(fiber, sourceFiber, error);
+ return;
+ } else if (fiber.tag === ClassComponent) {
+ var ctor = fiber.type;
+ var instance = fiber.stateNode;
+
+ if (typeof ctor.getDerivedStateFromError === 'function' || typeof instance.componentDidCatch === 'function' && !isAlreadyFailedLegacyErrorBoundary(instance)) {
+ var errorInfo = createCapturedValue(error, sourceFiber);
+ var update = createClassErrorUpdate(fiber, errorInfo, // TODO: This is always sync
+ Sync);
+ enqueueUpdate(fiber, update);
+ var root = markUpdateTimeFromFiberToRoot(fiber, Sync);
+
+ if (root !== null) {
+ ensureRootIsScheduled(root);
+ schedulePendingInteractions(root, Sync);
+ }
+
+ return;
+ }
+ }
+
+ fiber = fiber.return;
+ }
+ }
+ function pingSuspendedRoot(root, thenable, suspendedTime) {
+ var pingCache = root.pingCache;
+
+ if (pingCache !== null) {
+ // The thenable resolved, so we no longer need to memoize, because it will
+ // never be thrown again.
+ pingCache.delete(thenable);
+ }
+
+ if (workInProgressRoot === root && renderExpirationTime$1 === suspendedTime) {
+ // Received a ping at the same priority level at which we're currently
+ // rendering. We might want to restart this render. This should mirror
+ // the logic of whether or not a root suspends once it completes.
+ // TODO: If we're rendering sync either due to Sync, Batched or expired,
+ // we should probably never restart.
+ // If we're suspended with delay, we'll always suspend so we can always
+ // restart. If we're suspended without any updates, it might be a retry.
+ // If it's early in the retry we can restart. We can't know for sure
+ // whether we'll eventually process an update during this render pass,
+ // but it's somewhat unlikely that we get to a ping before that, since
+ // getting to the root most update is usually very fast.
+ if (workInProgressRootExitStatus === RootSuspendedWithDelay || workInProgressRootExitStatus === RootSuspended && workInProgressRootLatestProcessedExpirationTime === Sync && now() - globalMostRecentFallbackTime < FALLBACK_THROTTLE_MS) {
+ // Restart from the root. Don't need to schedule a ping because
+ // we're already working on this tree.
+ prepareFreshStack(root, renderExpirationTime$1);
+ } else {
+ // Even though we can't restart right now, we might get an
+ // opportunity later. So we mark this render as having a ping.
+ workInProgressRootHasPendingPing = true;
+ }
+
+ return;
+ }
+
+ if (!isRootSuspendedAtTime(root, suspendedTime)) {
+ // The root is no longer suspended at this time.
+ return;
+ }
+
+ var lastPingedTime = root.lastPingedTime;
+
+ if (lastPingedTime !== NoWork && lastPingedTime < suspendedTime) {
+ // There's already a lower priority ping scheduled.
+ return;
+ } // Mark the time at which this ping was scheduled.
+
+
+ root.lastPingedTime = suspendedTime;
+
+ ensureRootIsScheduled(root);
+ schedulePendingInteractions(root, suspendedTime);
+ }
+
+ function retryTimedOutBoundary(boundaryFiber, retryTime) {
+ // The boundary fiber (a Suspense component or SuspenseList component)
+ // previously was rendered in its fallback state. One of the promises that
+ // suspended it has resolved, which means at least part of the tree was
+ // likely unblocked. Try rendering again, at a new expiration time.
+ if (retryTime === NoWork) {
+ var suspenseConfig = null; // Retries don't carry over the already committed update.
+
+ var currentTime = requestCurrentTimeForUpdate();
+ retryTime = computeExpirationForFiber(currentTime, boundaryFiber, suspenseConfig);
+ } // TODO: Special case idle priority?
+
+
+ var root = markUpdateTimeFromFiberToRoot(boundaryFiber, retryTime);
+
+ if (root !== null) {
+ ensureRootIsScheduled(root);
+ schedulePendingInteractions(root, retryTime);
+ }
+ }
+ function resolveRetryThenable(boundaryFiber, thenable) {
+ var retryTime = NoWork; // Default
+
+ var retryCache;
+
+ {
+ retryCache = boundaryFiber.stateNode;
+ }
+
+ if (retryCache !== null) {
+ // The thenable resolved, so we no longer need to memoize, because it will
+ // never be thrown again.
+ retryCache.delete(thenable);
+ }
+
+ retryTimedOutBoundary(boundaryFiber, retryTime);
+ } // Computes the next Just Noticeable Difference (JND) boundary.
+ // The theory is that a person can't tell the difference between small differences in time.
+ // Therefore, if we wait a bit longer than necessary that won't translate to a noticeable
+ // difference in the experience. However, waiting for longer might mean that we can avoid
+ // showing an intermediate loading state. The longer we have already waited, the harder it
+ // is to tell small differences in time. Therefore, the longer we've already waited,
+ // the longer we can wait additionally. At some point we have to give up though.
+ // We pick a train model where the next boundary commits at a consistent schedule.
+ // These particular numbers are vague estimates. We expect to adjust them based on research.
+
+ function jnd(timeElapsed) {
+ return timeElapsed < 120 ? 120 : timeElapsed < 480 ? 480 : timeElapsed < 1080 ? 1080 : timeElapsed < 1920 ? 1920 : timeElapsed < 3000 ? 3000 : timeElapsed < 4320 ? 4320 : ceil(timeElapsed / 1960) * 1960;
+ }
+
+ function computeMsUntilSuspenseLoadingDelay(mostRecentEventTime, committedExpirationTime, suspenseConfig) {
+ var busyMinDurationMs = suspenseConfig.busyMinDurationMs | 0;
+
+ if (busyMinDurationMs <= 0) {
+ return 0;
+ }
+
+ var busyDelayMs = suspenseConfig.busyDelayMs | 0; // Compute the time until this render pass would expire.
+
+ var currentTimeMs = now();
+ var eventTimeMs = inferTimeFromExpirationTimeWithSuspenseConfig(mostRecentEventTime, suspenseConfig);
+ var timeElapsed = currentTimeMs - eventTimeMs;
+
+ if (timeElapsed <= busyDelayMs) {
+ // If we haven't yet waited longer than the initial delay, we don't
+ // have to wait any additional time.
+ return 0;
+ }
+
+ var msUntilTimeout = busyDelayMs + busyMinDurationMs - timeElapsed; // This is the value that is passed to `setTimeout`.
+
+ return msUntilTimeout;
+ }
+
+ function checkForNestedUpdates() {
+ if (nestedUpdateCount > NESTED_UPDATE_LIMIT) {
+ nestedUpdateCount = 0;
+ rootWithNestedUpdates = null;
+
+ {
+ {
+ throw Error( "Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops." );
+ }
+ }
+ }
+
+ {
+ if (nestedPassiveUpdateCount > NESTED_PASSIVE_UPDATE_LIMIT) {
+ nestedPassiveUpdateCount = 0;
+
+ error('Maximum update depth exceeded. This can happen when a component ' + "calls setState inside useEffect, but useEffect either doesn't " + 'have a dependency array, or one of the dependencies changes on ' + 'every render.');
+ }
+ }
+ }
+
+ function flushRenderPhaseStrictModeWarningsInDEV() {
+ {
+ ReactStrictModeWarnings.flushLegacyContextWarning();
+
+ {
+ ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings();
+ }
+ }
+ }
+
+ function stopFinishedWorkLoopTimer() {
+ var didCompleteRoot = true;
+ stopWorkLoopTimer(interruptedBy, didCompleteRoot);
+ interruptedBy = null;
+ }
+
+ function stopInterruptedWorkLoopTimer() {
+ // TODO: Track which fiber caused the interruption.
+ var didCompleteRoot = false;
+ stopWorkLoopTimer(interruptedBy, didCompleteRoot);
+ interruptedBy = null;
+ }
+
+ function checkForInterruption(fiberThatReceivedUpdate, updateExpirationTime) {
+ if ( workInProgressRoot !== null && updateExpirationTime > renderExpirationTime$1) {
+ interruptedBy = fiberThatReceivedUpdate;
+ }
+ }
+
+ var didWarnStateUpdateForUnmountedComponent = null;
+
+ function warnAboutUpdateOnUnmountedFiberInDEV(fiber) {
+ {
+ var tag = fiber.tag;
+
+ if (tag !== HostRoot && tag !== ClassComponent && tag !== FunctionComponent && tag !== ForwardRef && tag !== MemoComponent && tag !== SimpleMemoComponent && tag !== Block) {
+ // Only warn for user-defined components, not internal ones like Suspense.
+ return;
+ }
+ // the problematic code almost always lies inside that component.
+
+
+ var componentName = getComponentName(fiber.type) || 'ReactComponent';
+
+ if (didWarnStateUpdateForUnmountedComponent !== null) {
+ if (didWarnStateUpdateForUnmountedComponent.has(componentName)) {
+ return;
+ }
+
+ didWarnStateUpdateForUnmountedComponent.add(componentName);
+ } else {
+ didWarnStateUpdateForUnmountedComponent = new Set([componentName]);
+ }
+
+ error("Can't perform a React state update on an unmounted component. This " + 'is a no-op, but it indicates a memory leak in your application. To ' + 'fix, cancel all subscriptions and asynchronous tasks in %s.%s', tag === ClassComponent ? 'the componentWillUnmount method' : 'a useEffect cleanup function', getStackByFiberInDevAndProd(fiber));
+ }
+ }
+
+ var beginWork$1;
+
+ {
+ var dummyFiber = null;
+
+ beginWork$1 = function (current, unitOfWork, expirationTime) {
+ // If a component throws an error, we replay it again in a synchronously
+ // dispatched event, so that the debugger will treat it as an uncaught
+ // error See ReactErrorUtils for more information.
+ // Before entering the begin phase, copy the work-in-progress onto a dummy
+ // fiber. If beginWork throws, we'll use this to reset the state.
+ var originalWorkInProgressCopy = assignFiberPropertiesInDEV(dummyFiber, unitOfWork);
+
+ try {
+ return beginWork(current, unitOfWork, expirationTime);
+ } catch (originalError) {
+ if (originalError !== null && typeof originalError === 'object' && typeof originalError.then === 'function') {
+ // Don't replay promises. Treat everything else like an error.
+ throw originalError;
+ } // Keep this code in sync with handleError; any changes here must have
+ // corresponding changes there.
+
+
+ resetContextDependencies();
+ resetHooksAfterThrow(); // Don't reset current debug fiber, since we're about to work on the
+ // same fiber again.
+ // Unwind the failed stack frame
+
+ unwindInterruptedWork(unitOfWork); // Restore the original properties of the fiber.
+
+ assignFiberPropertiesInDEV(unitOfWork, originalWorkInProgressCopy);
+
+ if ( unitOfWork.mode & ProfileMode) {
+ // Reset the profiler timer.
+ startProfilerTimer(unitOfWork);
+ } // Run beginWork again.
+
+
+ invokeGuardedCallback(null, beginWork, null, current, unitOfWork, expirationTime);
+
+ if (hasCaughtError()) {
+ var replayError = clearCaughtError(); // `invokeGuardedCallback` sometimes sets an expando `_suppressLogging`.
+ // Rethrow this error instead of the original one.
+
+ throw replayError;
+ } else {
+ // This branch is reachable if the render phase is impure.
+ throw originalError;
+ }
+ }
+ };
+ }
+
+ var didWarnAboutUpdateInRender = false;
+ var didWarnAboutUpdateInRenderForAnotherComponent;
+
+ {
+ didWarnAboutUpdateInRenderForAnotherComponent = new Set();
+ }
+
+ function warnAboutRenderPhaseUpdatesInDEV(fiber) {
+ {
+ if (isRendering && (executionContext & RenderContext) !== NoContext) {
+ switch (fiber.tag) {
+ case FunctionComponent:
+ case ForwardRef:
+ case SimpleMemoComponent:
+ {
+ var renderingComponentName = workInProgress && getComponentName(workInProgress.type) || 'Unknown'; // Dedupe by the rendering component because it's the one that needs to be fixed.
+
+ var dedupeKey = renderingComponentName;
+
+ if (!didWarnAboutUpdateInRenderForAnotherComponent.has(dedupeKey)) {
+ didWarnAboutUpdateInRenderForAnotherComponent.add(dedupeKey);
+ var setStateComponentName = getComponentName(fiber.type) || 'Unknown';
+
+ error('Cannot update a component (`%s`) while rendering a ' + 'different component (`%s`). To locate the bad setState() call inside `%s`, ' + 'follow the stack trace as described in https://fb.me/setstate-in-render', setStateComponentName, renderingComponentName, renderingComponentName);
+ }
+
+ break;
+ }
+
+ case ClassComponent:
+ {
+ if (!didWarnAboutUpdateInRender) {
+ error('Cannot update during an existing state transition (such as ' + 'within `render`). Render methods should be a pure ' + 'function of props and state.');
+
+ didWarnAboutUpdateInRender = true;
+ }
+
+ break;
+ }
+ }
+ }
+ }
+ } // a 'shared' variable that changes when act() opens/closes in tests.
+
+
+ var IsThisRendererActing = {
+ current: false
+ };
+ function warnIfNotScopedWithMatchingAct(fiber) {
+ {
+ if ( IsSomeRendererActing.current === true && IsThisRendererActing.current !== true) {
+ error("It looks like you're using the wrong act() around your test interactions.\n" + 'Be sure to use the matching version of act() corresponding to your renderer:\n\n' + '// for react-dom:\n' + "import {act} from 'react-dom/test-utils';\n" + '// ...\n' + 'act(() => ...);\n\n' + '// for react-test-renderer:\n' + "import TestRenderer from 'react-test-renderer';\n" + 'const {act} = TestRenderer;\n' + '// ...\n' + 'act(() => ...);' + '%s', getStackByFiberInDevAndProd(fiber));
+ }
+ }
+ }
+ function warnIfNotCurrentlyActingEffectsInDEV(fiber) {
+ {
+ if ( (fiber.mode & StrictMode) !== NoMode && IsSomeRendererActing.current === false && IsThisRendererActing.current === false) {
+ error('An update to %s ran an effect, but was not wrapped in act(...).\n\n' + 'When testing, code that causes React state updates should be ' + 'wrapped into act(...):\n\n' + 'act(() => {\n' + ' /* fire events that update state */\n' + '});\n' + '/* assert on the output */\n\n' + "This ensures that you're testing the behavior the user would see " + 'in the browser.' + ' Learn more at https://fb.me/react-wrap-tests-with-act' + '%s', getComponentName(fiber.type), getStackByFiberInDevAndProd(fiber));
+ }
+ }
+ }
+
+ function warnIfNotCurrentlyActingUpdatesInDEV(fiber) {
+ {
+ if ( executionContext === NoContext && IsSomeRendererActing.current === false && IsThisRendererActing.current === false) {
+ error('An update to %s inside a test was not wrapped in act(...).\n\n' + 'When testing, code that causes React state updates should be ' + 'wrapped into act(...):\n\n' + 'act(() => {\n' + ' /* fire events that update state */\n' + '});\n' + '/* assert on the output */\n\n' + "This ensures that you're testing the behavior the user would see " + 'in the browser.' + ' Learn more at https://fb.me/react-wrap-tests-with-act' + '%s', getComponentName(fiber.type), getStackByFiberInDevAndProd(fiber));
+ }
+ }
+ }
+
+ var warnIfNotCurrentlyActingUpdatesInDev = warnIfNotCurrentlyActingUpdatesInDEV; // In tests, we want to enforce a mocked scheduler.
+
+ var didWarnAboutUnmockedScheduler = false; // TODO Before we release concurrent mode, revisit this and decide whether a mocked
+ // scheduler is the actual recommendation. The alternative could be a testing build,
+ // a new lib, or whatever; we dunno just yet. This message is for early adopters
+ // to get their tests right.
+
+ function warnIfUnmockedScheduler(fiber) {
+ {
+ if (didWarnAboutUnmockedScheduler === false && unstable_flushAllWithoutAsserting === undefined) {
+ if (fiber.mode & BlockingMode || fiber.mode & ConcurrentMode) {
+ didWarnAboutUnmockedScheduler = true;
+
+ error('In Concurrent or Sync modes, the "scheduler" module needs to be mocked ' + 'to guarantee consistent behaviour across tests and browsers. ' + 'For example, with jest: \n' + "jest.mock('scheduler', () => require('scheduler/unstable_mock'));\n\n" + 'For more info, visit https://fb.me/react-mock-scheduler');
+ }
+ }
+ }
+ }
+
+ function computeThreadID(root, expirationTime) {
+ // Interaction threads are unique per root and expiration time.
+ return expirationTime * 1000 + root.interactionThreadID;
+ }
+
+ function markSpawnedWork(expirationTime) {
+
+ if (spawnedWorkDuringRender === null) {
+ spawnedWorkDuringRender = [expirationTime];
+ } else {
+ spawnedWorkDuringRender.push(expirationTime);
+ }
+ }
+
+ function scheduleInteractions(root, expirationTime, interactions) {
+
+ if (interactions.size > 0) {
+ var pendingInteractionMap = root.pendingInteractionMap;
+ var pendingInteractions = pendingInteractionMap.get(expirationTime);
+
+ if (pendingInteractions != null) {
+ interactions.forEach(function (interaction) {
+ if (!pendingInteractions.has(interaction)) {
+ // Update the pending async work count for previously unscheduled interaction.
+ interaction.__count++;
+ }
+
+ pendingInteractions.add(interaction);
+ });
+ } else {
+ pendingInteractionMap.set(expirationTime, new Set(interactions)); // Update the pending async work count for the current interactions.
+
+ interactions.forEach(function (interaction) {
+ interaction.__count++;
+ });
+ }
+
+ var subscriber = __subscriberRef.current;
+
+ if (subscriber !== null) {
+ var threadID = computeThreadID(root, expirationTime);
+ subscriber.onWorkScheduled(interactions, threadID);
+ }
+ }
+ }
+
+ function schedulePendingInteractions(root, expirationTime) {
+
+ scheduleInteractions(root, expirationTime, __interactionsRef.current);
+ }
+
+ function startWorkOnPendingInteractions(root, expirationTime) {
+ // we can accurately attribute time spent working on it, And so that cascading
+ // work triggered during the render phase will be associated with it.
+
+
+ var interactions = new Set();
+ root.pendingInteractionMap.forEach(function (scheduledInteractions, scheduledExpirationTime) {
+ if (scheduledExpirationTime >= expirationTime) {
+ scheduledInteractions.forEach(function (interaction) {
+ return interactions.add(interaction);
+ });
+ }
+ }); // Store the current set of interactions on the FiberRoot for a few reasons:
+ // We can re-use it in hot functions like performConcurrentWorkOnRoot()
+ // without having to recalculate it. We will also use it in commitWork() to
+ // pass to any Profiler onRender() hooks. This also provides DevTools with a
+ // way to access it when the onCommitRoot() hook is called.
+
+ root.memoizedInteractions = interactions;
+
+ if (interactions.size > 0) {
+ var subscriber = __subscriberRef.current;
+
+ if (subscriber !== null) {
+ var threadID = computeThreadID(root, expirationTime);
+
+ try {
+ subscriber.onWorkStarted(interactions, threadID);
+ } catch (error) {
+ // If the subscriber throws, rethrow it in a separate task
+ scheduleCallback(ImmediatePriority, function () {
+ throw error;
+ });
+ }
+ }
+ }
+ }
+
+ function finishPendingInteractions(root, committedExpirationTime) {
+
+ var earliestRemainingTimeAfterCommit = root.firstPendingTime;
+ var subscriber;
+
+ try {
+ subscriber = __subscriberRef.current;
+
+ if (subscriber !== null && root.memoizedInteractions.size > 0) {
+ var threadID = computeThreadID(root, committedExpirationTime);
+ subscriber.onWorkStopped(root.memoizedInteractions, threadID);
+ }
+ } catch (error) {
+ // If the subscriber throws, rethrow it in a separate task
+ scheduleCallback(ImmediatePriority, function () {
+ throw error;
+ });
+ } finally {
+ // Clear completed interactions from the pending Map.
+ // Unless the render was suspended or cascading work was scheduled,
+ // In which case– leave pending interactions until the subsequent render.
+ var pendingInteractionMap = root.pendingInteractionMap;
+ pendingInteractionMap.forEach(function (scheduledInteractions, scheduledExpirationTime) {
+ // Only decrement the pending interaction count if we're done.
+ // If there's still work at the current priority,
+ // That indicates that we are waiting for suspense data.
+ if (scheduledExpirationTime > earliestRemainingTimeAfterCommit) {
+ pendingInteractionMap.delete(scheduledExpirationTime);
+ scheduledInteractions.forEach(function (interaction) {
+ interaction.__count--;
+
+ if (subscriber !== null && interaction.__count === 0) {
+ try {
+ subscriber.onInteractionScheduledWorkCompleted(interaction);
+ } catch (error) {
+ // If the subscriber throws, rethrow it in a separate task
+ scheduleCallback(ImmediatePriority, function () {
+ throw error;
+ });
+ }
+ }
+ });
+ }
+ });
+ }
+ }
+
+ var onScheduleFiberRoot = null;
+ var onCommitFiberRoot = null;
+ var onCommitFiberUnmount = null;
+ var hasLoggedError = false;
+ var isDevToolsPresent = typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined';
+ function injectInternals(internals) {
+ if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
+ // No DevTools
+ return false;
+ }
+
+ var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__;
+
+ if (hook.isDisabled) {
+ // This isn't a real property on the hook, but it can be set to opt out
+ // of DevTools integration and associated warnings and logs.
+ // https://github.com/facebook/react/issues/3877
+ return true;
+ }
+
+ if (!hook.supportsFiber) {
+ {
+ error('The installed version of React DevTools is too old and will not work ' + 'with the current version of React. Please update React DevTools. ' + 'https://fb.me/react-devtools');
+ } // DevTools exists, even though it doesn't support Fiber.
+
+
+ return true;
+ }
+
+ try {
+ var rendererID = hook.inject(internals); // We have successfully injected, so now it is safe to set up hooks.
+
+ if (true) {
+ // Only used by Fast Refresh
+ if (typeof hook.onScheduleFiberRoot === 'function') {
+ onScheduleFiberRoot = function (root, children) {
+ try {
+ hook.onScheduleFiberRoot(rendererID, root, children);
+ } catch (err) {
+ if (true && !hasLoggedError) {
+ hasLoggedError = true;
+
+ error('React instrumentation encountered an error: %s', err);
+ }
+ }
+ };
+ }
+ }
+
+ onCommitFiberRoot = function (root, expirationTime) {
+ try {
+ var didError = (root.current.effectTag & DidCapture) === DidCapture;
+
+ if (enableProfilerTimer) {
+ var currentTime = getCurrentTime();
+ var priorityLevel = inferPriorityFromExpirationTime(currentTime, expirationTime);
+ hook.onCommitFiberRoot(rendererID, root, priorityLevel, didError);
+ } else {
+ hook.onCommitFiberRoot(rendererID, root, undefined, didError);
+ }
+ } catch (err) {
+ if (true) {
+ if (!hasLoggedError) {
+ hasLoggedError = true;
+
+ error('React instrumentation encountered an error: %s', err);
+ }
+ }
+ }
+ };
+
+ onCommitFiberUnmount = function (fiber) {
+ try {
+ hook.onCommitFiberUnmount(rendererID, fiber);
+ } catch (err) {
+ if (true) {
+ if (!hasLoggedError) {
+ hasLoggedError = true;
+
+ error('React instrumentation encountered an error: %s', err);
+ }
+ }
+ }
+ };
+ } catch (err) {
+ // Catch all errors because it is unsafe to throw during initialization.
+ {
+ error('React instrumentation encountered an error: %s.', err);
+ }
+ } // DevTools exists
+
+
+ return true;
+ }
+ function onScheduleRoot(root, children) {
+ if (typeof onScheduleFiberRoot === 'function') {
+ onScheduleFiberRoot(root, children);
+ }
+ }
+ function onCommitRoot(root, expirationTime) {
+ if (typeof onCommitFiberRoot === 'function') {
+ onCommitFiberRoot(root, expirationTime);
+ }
+ }
+ function onCommitUnmount(fiber) {
+ if (typeof onCommitFiberUnmount === 'function') {
+ onCommitFiberUnmount(fiber);
+ }
+ }
+
+ var hasBadMapPolyfill;
+
+ {
+ hasBadMapPolyfill = false;
+
+ try {
+ var nonExtensibleObject = Object.preventExtensions({});
+ var testMap = new Map([[nonExtensibleObject, null]]);
+ var testSet = new Set([nonExtensibleObject]); // This is necessary for Rollup to not consider these unused.
+ // https://github.com/rollup/rollup/issues/1771
+ // TODO: we can remove these if Rollup fixes the bug.
+
+ testMap.set(0, 0);
+ testSet.add(0);
+ } catch (e) {
+ // TODO: Consider warning about bad polyfills
+ hasBadMapPolyfill = true;
+ }
+ }
+
+ var debugCounter = 1;
+
+ function FiberNode(tag, pendingProps, key, mode) {
+ // Instance
+ this.tag = tag;
+ this.key = key;
+ this.elementType = null;
+ this.type = null;
+ this.stateNode = null; // Fiber
+
+ this.return = null;
+ this.child = null;
+ this.sibling = null;
+ this.index = 0;
+ this.ref = null;
+ this.pendingProps = pendingProps;
+ this.memoizedProps = null;
+ this.updateQueue = null;
+ this.memoizedState = null;
+ this.dependencies = null;
+ this.mode = mode; // Effects
+
+ this.effectTag = NoEffect;
+ this.nextEffect = null;
+ this.firstEffect = null;
+ this.lastEffect = null;
+ this.expirationTime = NoWork;
+ this.childExpirationTime = NoWork;
+ this.alternate = null;
+
+ {
+ // Note: The following is done to avoid a v8 performance cliff.
+ //
+ // Initializing the fields below to smis and later updating them with
+ // double values will cause Fibers to end up having separate shapes.
+ // This behavior/bug has something to do with Object.preventExtension().
+ // Fortunately this only impacts DEV builds.
+ // Unfortunately it makes React unusably slow for some applications.
+ // To work around this, initialize the fields below with doubles.
+ //
+ // Learn more about this here:
+ // https://github.com/facebook/react/issues/14365
+ // https://bugs.chromium.org/p/v8/issues/detail?id=8538
+ this.actualDuration = Number.NaN;
+ this.actualStartTime = Number.NaN;
+ this.selfBaseDuration = Number.NaN;
+ this.treeBaseDuration = Number.NaN; // It's okay to replace the initial doubles with smis after initialization.
+ // This won't trigger the performance cliff mentioned above,
+ // and it simplifies other profiler code (including DevTools).
+
+ this.actualDuration = 0;
+ this.actualStartTime = -1;
+ this.selfBaseDuration = 0;
+ this.treeBaseDuration = 0;
+ } // This is normally DEV-only except www when it adds listeners.
+ // TODO: remove the User Timing integration in favor of Root Events.
+
+
+ {
+ this._debugID = debugCounter++;
+ this._debugIsCurrentlyTiming = false;
+ }
+
+ {
+ this._debugSource = null;
+ this._debugOwner = null;
+ this._debugNeedsRemount = false;
+ this._debugHookTypes = null;
+
+ if (!hasBadMapPolyfill && typeof Object.preventExtensions === 'function') {
+ Object.preventExtensions(this);
+ }
+ }
+ } // This is a constructor function, rather than a POJO constructor, still
+ // please ensure we do the following:
+ // 1) Nobody should add any instance methods on this. Instance methods can be
+ // more difficult to predict when they get optimized and they are almost
+ // never inlined properly in static compilers.
+ // 2) Nobody should rely on `instanceof Fiber` for type testing. We should
+ // always know when it is a fiber.
+ // 3) We might want to experiment with using numeric keys since they are easier
+ // to optimize in a non-JIT environment.
+ // 4) We can easily go from a constructor to a createFiber object literal if that
+ // is faster.
+ // 5) It should be easy to port this to a C struct and keep a C implementation
+ // compatible.
+
+
+ var createFiber = function (tag, pendingProps, key, mode) {
+ // $FlowFixMe: the shapes are exact here but Flow doesn't like constructors
+ return new FiberNode(tag, pendingProps, key, mode);
+ };
+
+ function shouldConstruct(Component) {
+ var prototype = Component.prototype;
+ return !!(prototype && prototype.isReactComponent);
+ }
+
+ function isSimpleFunctionComponent(type) {
+ return typeof type === 'function' && !shouldConstruct(type) && type.defaultProps === undefined;
+ }
+ function resolveLazyComponentTag(Component) {
+ if (typeof Component === 'function') {
+ return shouldConstruct(Component) ? ClassComponent : FunctionComponent;
+ } else if (Component !== undefined && Component !== null) {
+ var $$typeof = Component.$$typeof;
+
+ if ($$typeof === REACT_FORWARD_REF_TYPE) {
+ return ForwardRef;
+ }
+
+ if ($$typeof === REACT_MEMO_TYPE) {
+ return MemoComponent;
+ }
+ }
+
+ return IndeterminateComponent;
+ } // This is used to create an alternate fiber to do work on.
+
+ function createWorkInProgress(current, pendingProps) {
+ var workInProgress = current.alternate;
+
+ if (workInProgress === null) {
+ // We use a double buffering pooling technique because we know that we'll
+ // only ever need at most two versions of a tree. We pool the "other" unused
+ // node that we're free to reuse. This is lazily created to avoid allocating
+ // extra objects for things that are never updated. It also allow us to
+ // reclaim the extra memory if needed.
+ workInProgress = createFiber(current.tag, pendingProps, current.key, current.mode);
+ workInProgress.elementType = current.elementType;
+ workInProgress.type = current.type;
+ workInProgress.stateNode = current.stateNode;
+
+ {
+ // DEV-only fields
+ {
+ workInProgress._debugID = current._debugID;
+ }
+
+ workInProgress._debugSource = current._debugSource;
+ workInProgress._debugOwner = current._debugOwner;
+ workInProgress._debugHookTypes = current._debugHookTypes;
+ }
+
+ workInProgress.alternate = current;
+ current.alternate = workInProgress;
+ } else {
+ workInProgress.pendingProps = pendingProps; // We already have an alternate.
+ // Reset the effect tag.
+
+ workInProgress.effectTag = NoEffect; // The effect list is no longer valid.
+
+ workInProgress.nextEffect = null;
+ workInProgress.firstEffect = null;
+ workInProgress.lastEffect = null;
+
+ {
+ // We intentionally reset, rather than copy, actualDuration & actualStartTime.
+ // This prevents time from endlessly accumulating in new commits.
+ // This has the downside of resetting values for different priority renders,
+ // But works for yielding (the common case) and should support resuming.
+ workInProgress.actualDuration = 0;
+ workInProgress.actualStartTime = -1;
+ }
+ }
+
+ workInProgress.childExpirationTime = current.childExpirationTime;
+ workInProgress.expirationTime = current.expirationTime;
+ workInProgress.child = current.child;
+ workInProgress.memoizedProps = current.memoizedProps;
+ workInProgress.memoizedState = current.memoizedState;
+ workInProgress.updateQueue = current.updateQueue; // Clone the dependencies object. This is mutated during the render phase, so
+ // it cannot be shared with the current fiber.
+
+ var currentDependencies = current.dependencies;
+ workInProgress.dependencies = currentDependencies === null ? null : {
+ expirationTime: currentDependencies.expirationTime,
+ firstContext: currentDependencies.firstContext,
+ responders: currentDependencies.responders
+ }; // These will be overridden during the parent's reconciliation
+
+ workInProgress.sibling = current.sibling;
+ workInProgress.index = current.index;
+ workInProgress.ref = current.ref;
+
+ {
+ workInProgress.selfBaseDuration = current.selfBaseDuration;
+ workInProgress.treeBaseDuration = current.treeBaseDuration;
+ }
+
+ {
+ workInProgress._debugNeedsRemount = current._debugNeedsRemount;
+
+ switch (workInProgress.tag) {
+ case IndeterminateComponent:
+ case FunctionComponent:
+ case SimpleMemoComponent:
+ workInProgress.type = resolveFunctionForHotReloading(current.type);
+ break;
+
+ case ClassComponent:
+ workInProgress.type = resolveClassForHotReloading(current.type);
+ break;
+
+ case ForwardRef:
+ workInProgress.type = resolveForwardRefForHotReloading(current.type);
+ break;
+ }
+ }
+
+ return workInProgress;
+ } // Used to reuse a Fiber for a second pass.
+
+ function resetWorkInProgress(workInProgress, renderExpirationTime) {
+ // This resets the Fiber to what createFiber or createWorkInProgress would
+ // have set the values to before during the first pass. Ideally this wouldn't
+ // be necessary but unfortunately many code paths reads from the workInProgress
+ // when they should be reading from current and writing to workInProgress.
+ // We assume pendingProps, index, key, ref, return are still untouched to
+ // avoid doing another reconciliation.
+ // Reset the effect tag but keep any Placement tags, since that's something
+ // that child fiber is setting, not the reconciliation.
+ workInProgress.effectTag &= Placement; // The effect list is no longer valid.
+
+ workInProgress.nextEffect = null;
+ workInProgress.firstEffect = null;
+ workInProgress.lastEffect = null;
+ var current = workInProgress.alternate;
+
+ if (current === null) {
+ // Reset to createFiber's initial values.
+ workInProgress.childExpirationTime = NoWork;
+ workInProgress.expirationTime = renderExpirationTime;
+ workInProgress.child = null;
+ workInProgress.memoizedProps = null;
+ workInProgress.memoizedState = null;
+ workInProgress.updateQueue = null;
+ workInProgress.dependencies = null;
+
+ {
+ // Note: We don't reset the actualTime counts. It's useful to accumulate
+ // actual time across multiple render passes.
+ workInProgress.selfBaseDuration = 0;
+ workInProgress.treeBaseDuration = 0;
+ }
+ } else {
+ // Reset to the cloned values that createWorkInProgress would've.
+ workInProgress.childExpirationTime = current.childExpirationTime;
+ workInProgress.expirationTime = current.expirationTime;
+ workInProgress.child = current.child;
+ workInProgress.memoizedProps = current.memoizedProps;
+ workInProgress.memoizedState = current.memoizedState;
+ workInProgress.updateQueue = current.updateQueue; // Clone the dependencies object. This is mutated during the render phase, so
+ // it cannot be shared with the current fiber.
+
+ var currentDependencies = current.dependencies;
+ workInProgress.dependencies = currentDependencies === null ? null : {
+ expirationTime: currentDependencies.expirationTime,
+ firstContext: currentDependencies.firstContext,
+ responders: currentDependencies.responders
+ };
+
+ {
+ // Note: We don't reset the actualTime counts. It's useful to accumulate
+ // actual time across multiple render passes.
+ workInProgress.selfBaseDuration = current.selfBaseDuration;
+ workInProgress.treeBaseDuration = current.treeBaseDuration;
+ }
+ }
+
+ return workInProgress;
+ }
+ function createHostRootFiber(tag) {
+ var mode;
+
+ if (tag === ConcurrentRoot) {
+ mode = ConcurrentMode | BlockingMode | StrictMode;
+ } else if (tag === BlockingRoot) {
+ mode = BlockingMode | StrictMode;
+ } else {
+ mode = NoMode;
+ }
+
+ if ( isDevToolsPresent) {
+ // Always collect profile timings when DevTools are present.
+ // This enables DevTools to start capturing timing at any point–
+ // Without some nodes in the tree having empty base times.
+ mode |= ProfileMode;
+ }
+
+ return createFiber(HostRoot, null, null, mode);
+ }
+ function createFiberFromTypeAndProps(type, // React$ElementType
+ key, pendingProps, owner, mode, expirationTime) {
+ var fiber;
+ var fiberTag = IndeterminateComponent; // The resolved type is set if we know what the final type will be. I.e. it's not lazy.
+
+ var resolvedType = type;
+
+ if (typeof type === 'function') {
+ if (shouldConstruct(type)) {
+ fiberTag = ClassComponent;
+
+ {
+ resolvedType = resolveClassForHotReloading(resolvedType);
+ }
+ } else {
+ {
+ resolvedType = resolveFunctionForHotReloading(resolvedType);
+ }
+ }
+ } else if (typeof type === 'string') {
+ fiberTag = HostComponent;
+ } else {
+ getTag: switch (type) {
+ case REACT_FRAGMENT_TYPE:
+ return createFiberFromFragment(pendingProps.children, mode, expirationTime, key);
+
+ case REACT_CONCURRENT_MODE_TYPE:
+ fiberTag = Mode;
+ mode |= ConcurrentMode | BlockingMode | StrictMode;
+ break;
+
+ case REACT_STRICT_MODE_TYPE:
+ fiberTag = Mode;
+ mode |= StrictMode;
+ break;
+
+ case REACT_PROFILER_TYPE:
+ return createFiberFromProfiler(pendingProps, mode, expirationTime, key);
+
+ case REACT_SUSPENSE_TYPE:
+ return createFiberFromSuspense(pendingProps, mode, expirationTime, key);
+
+ case REACT_SUSPENSE_LIST_TYPE:
+ return createFiberFromSuspenseList(pendingProps, mode, expirationTime, key);
+
+ default:
+ {
+ if (typeof type === 'object' && type !== null) {
+ switch (type.$$typeof) {
+ case REACT_PROVIDER_TYPE:
+ fiberTag = ContextProvider;
+ break getTag;
+
+ case REACT_CONTEXT_TYPE:
+ // This is a consumer
+ fiberTag = ContextConsumer;
+ break getTag;
+
+ case REACT_FORWARD_REF_TYPE:
+ fiberTag = ForwardRef;
+
+ {
+ resolvedType = resolveForwardRefForHotReloading(resolvedType);
+ }
+
+ break getTag;
+
+ case REACT_MEMO_TYPE:
+ fiberTag = MemoComponent;
+ break getTag;
+
+ case REACT_LAZY_TYPE:
+ fiberTag = LazyComponent;
+ resolvedType = null;
+ break getTag;
+
+ case REACT_BLOCK_TYPE:
+ fiberTag = Block;
+ break getTag;
+
+ }
+ }
+
+ var info = '';
+
+ {
+ if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
+ info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and " + 'named imports.';
+ }
+
+ var ownerName = owner ? getComponentName(owner.type) : null;
+
+ if (ownerName) {
+ info += '\n\nCheck the render method of `' + ownerName + '`.';
+ }
+ }
+
+ {
+ {
+ throw Error( "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: " + (type == null ? type : typeof type) + "." + info );
+ }
+ }
+ }
+ }
+ }
+
+ fiber = createFiber(fiberTag, pendingProps, key, mode);
+ fiber.elementType = type;
+ fiber.type = resolvedType;
+ fiber.expirationTime = expirationTime;
+ return fiber;
+ }
+ function createFiberFromElement(element, mode, expirationTime) {
+ var owner = null;
+
+ {
+ owner = element._owner;
+ }
+
+ var type = element.type;
+ var key = element.key;
+ var pendingProps = element.props;
+ var fiber = createFiberFromTypeAndProps(type, key, pendingProps, owner, mode, expirationTime);
+
+ {
+ fiber._debugSource = element._source;
+ fiber._debugOwner = element._owner;
+ }
+
+ return fiber;
+ }
+ function createFiberFromFragment(elements, mode, expirationTime, key) {
+ var fiber = createFiber(Fragment, elements, key, mode);
+ fiber.expirationTime = expirationTime;
+ return fiber;
+ }
+
+ function createFiberFromProfiler(pendingProps, mode, expirationTime, key) {
+ {
+ if (typeof pendingProps.id !== 'string' || typeof pendingProps.onRender !== 'function') {
+ error('Profiler must specify an "id" string and "onRender" function as props');
+ }
+ }
+
+ var fiber = createFiber(Profiler, pendingProps, key, mode | ProfileMode); // TODO: The Profiler fiber shouldn't have a type. It has a tag.
+
+ fiber.elementType = REACT_PROFILER_TYPE;
+ fiber.type = REACT_PROFILER_TYPE;
+ fiber.expirationTime = expirationTime;
+ return fiber;
+ }
+
+ function createFiberFromSuspense(pendingProps, mode, expirationTime, key) {
+ var fiber = createFiber(SuspenseComponent, pendingProps, key, mode); // TODO: The SuspenseComponent fiber shouldn't have a type. It has a tag.
+ // This needs to be fixed in getComponentName so that it relies on the tag
+ // instead.
+
+ fiber.type = REACT_SUSPENSE_TYPE;
+ fiber.elementType = REACT_SUSPENSE_TYPE;
+ fiber.expirationTime = expirationTime;
+ return fiber;
+ }
+ function createFiberFromSuspenseList(pendingProps, mode, expirationTime, key) {
+ var fiber = createFiber(SuspenseListComponent, pendingProps, key, mode);
+
+ {
+ // TODO: The SuspenseListComponent fiber shouldn't have a type. It has a tag.
+ // This needs to be fixed in getComponentName so that it relies on the tag
+ // instead.
+ fiber.type = REACT_SUSPENSE_LIST_TYPE;
+ }
+
+ fiber.elementType = REACT_SUSPENSE_LIST_TYPE;
+ fiber.expirationTime = expirationTime;
+ return fiber;
+ }
+ function createFiberFromText(content, mode, expirationTime) {
+ var fiber = createFiber(HostText, content, null, mode);
+ fiber.expirationTime = expirationTime;
+ return fiber;
+ }
+ function createFiberFromHostInstanceForDeletion() {
+ var fiber = createFiber(HostComponent, null, null, NoMode); // TODO: These should not need a type.
+
+ fiber.elementType = 'DELETED';
+ fiber.type = 'DELETED';
+ return fiber;
+ }
+ function createFiberFromPortal(portal, mode, expirationTime) {
+ var pendingProps = portal.children !== null ? portal.children : [];
+ var fiber = createFiber(HostPortal, pendingProps, portal.key, mode);
+ fiber.expirationTime = expirationTime;
+ fiber.stateNode = {
+ containerInfo: portal.containerInfo,
+ pendingChildren: null,
+ // Used by persistent updates
+ implementation: portal.implementation
+ };
+ return fiber;
+ } // Used for stashing WIP properties to replay failed work in DEV.
+
+ function assignFiberPropertiesInDEV(target, source) {
+ if (target === null) {
+ // This Fiber's initial properties will always be overwritten.
+ // We only use a Fiber to ensure the same hidden class so DEV isn't slow.
+ target = createFiber(IndeterminateComponent, null, null, NoMode);
+ } // This is intentionally written as a list of all properties.
+ // We tried to use Object.assign() instead but this is called in
+ // the hottest path, and Object.assign() was too slow:
+ // https://github.com/facebook/react/issues/12502
+ // This code is DEV-only so size is not a concern.
+
+
+ target.tag = source.tag;
+ target.key = source.key;
+ target.elementType = source.elementType;
+ target.type = source.type;
+ target.stateNode = source.stateNode;
+ target.return = source.return;
+ target.child = source.child;
+ target.sibling = source.sibling;
+ target.index = source.index;
+ target.ref = source.ref;
+ target.pendingProps = source.pendingProps;
+ target.memoizedProps = source.memoizedProps;
+ target.updateQueue = source.updateQueue;
+ target.memoizedState = source.memoizedState;
+ target.dependencies = source.dependencies;
+ target.mode = source.mode;
+ target.effectTag = source.effectTag;
+ target.nextEffect = source.nextEffect;
+ target.firstEffect = source.firstEffect;
+ target.lastEffect = source.lastEffect;
+ target.expirationTime = source.expirationTime;
+ target.childExpirationTime = source.childExpirationTime;
+ target.alternate = source.alternate;
+
+ {
+ target.actualDuration = source.actualDuration;
+ target.actualStartTime = source.actualStartTime;
+ target.selfBaseDuration = source.selfBaseDuration;
+ target.treeBaseDuration = source.treeBaseDuration;
+ }
+
+ {
+ target._debugID = source._debugID;
+ }
+
+ target._debugSource = source._debugSource;
+ target._debugOwner = source._debugOwner;
+ target._debugIsCurrentlyTiming = source._debugIsCurrentlyTiming;
+ target._debugNeedsRemount = source._debugNeedsRemount;
+ target._debugHookTypes = source._debugHookTypes;
+ return target;
+ }
+
+ function FiberRootNode(containerInfo, tag, hydrate) {
+ this.tag = tag;
+ this.current = null;
+ this.containerInfo = containerInfo;
+ this.pendingChildren = null;
+ this.pingCache = null;
+ this.finishedExpirationTime = NoWork;
+ this.finishedWork = null;
+ this.timeoutHandle = noTimeout;
+ this.context = null;
+ this.pendingContext = null;
+ this.hydrate = hydrate;
+ this.callbackNode = null;
+ this.callbackPriority = NoPriority;
+ this.firstPendingTime = NoWork;
+ this.firstSuspendedTime = NoWork;
+ this.lastSuspendedTime = NoWork;
+ this.nextKnownPendingLevel = NoWork;
+ this.lastPingedTime = NoWork;
+ this.lastExpiredTime = NoWork;
+
+ {
+ this.interactionThreadID = unstable_getThreadID();
+ this.memoizedInteractions = new Set();
+ this.pendingInteractionMap = new Map();
+ }
+ }
+
+ function createFiberRoot(containerInfo, tag, hydrate, hydrationCallbacks) {
+ var root = new FiberRootNode(containerInfo, tag, hydrate);
+ // stateNode is any.
+
+
+ var uninitializedFiber = createHostRootFiber(tag);
+ root.current = uninitializedFiber;
+ uninitializedFiber.stateNode = root;
+ initializeUpdateQueue(uninitializedFiber);
+ return root;
+ }
+ function isRootSuspendedAtTime(root, expirationTime) {
+ var firstSuspendedTime = root.firstSuspendedTime;
+ var lastSuspendedTime = root.lastSuspendedTime;
+ return firstSuspendedTime !== NoWork && firstSuspendedTime >= expirationTime && lastSuspendedTime <= expirationTime;
+ }
+ function markRootSuspendedAtTime(root, expirationTime) {
+ var firstSuspendedTime = root.firstSuspendedTime;
+ var lastSuspendedTime = root.lastSuspendedTime;
+
+ if (firstSuspendedTime < expirationTime) {
+ root.firstSuspendedTime = expirationTime;
+ }
+
+ if (lastSuspendedTime > expirationTime || firstSuspendedTime === NoWork) {
+ root.lastSuspendedTime = expirationTime;
+ }
+
+ if (expirationTime <= root.lastPingedTime) {
+ root.lastPingedTime = NoWork;
+ }
+
+ if (expirationTime <= root.lastExpiredTime) {
+ root.lastExpiredTime = NoWork;
+ }
+ }
+ function markRootUpdatedAtTime(root, expirationTime) {
+ // Update the range of pending times
+ var firstPendingTime = root.firstPendingTime;
+
+ if (expirationTime > firstPendingTime) {
+ root.firstPendingTime = expirationTime;
+ } // Update the range of suspended times. Treat everything lower priority or
+ // equal to this update as unsuspended.
+
+
+ var firstSuspendedTime = root.firstSuspendedTime;
+
+ if (firstSuspendedTime !== NoWork) {
+ if (expirationTime >= firstSuspendedTime) {
+ // The entire suspended range is now unsuspended.
+ root.firstSuspendedTime = root.lastSuspendedTime = root.nextKnownPendingLevel = NoWork;
+ } else if (expirationTime >= root.lastSuspendedTime) {
+ root.lastSuspendedTime = expirationTime + 1;
+ } // This is a pending level. Check if it's higher priority than the next
+ // known pending level.
+
+
+ if (expirationTime > root.nextKnownPendingLevel) {
+ root.nextKnownPendingLevel = expirationTime;
+ }
+ }
+ }
+ function markRootFinishedAtTime(root, finishedExpirationTime, remainingExpirationTime) {
+ // Update the range of pending times
+ root.firstPendingTime = remainingExpirationTime; // Update the range of suspended times. Treat everything higher priority or
+ // equal to this update as unsuspended.
+
+ if (finishedExpirationTime <= root.lastSuspendedTime) {
+ // The entire suspended range is now unsuspended.
+ root.firstSuspendedTime = root.lastSuspendedTime = root.nextKnownPendingLevel = NoWork;
+ } else if (finishedExpirationTime <= root.firstSuspendedTime) {
+ // Part of the suspended range is now unsuspended. Narrow the range to
+ // include everything between the unsuspended time (non-inclusive) and the
+ // last suspended time.
+ root.firstSuspendedTime = finishedExpirationTime - 1;
+ }
+
+ if (finishedExpirationTime <= root.lastPingedTime) {
+ // Clear the pinged time
+ root.lastPingedTime = NoWork;
+ }
+
+ if (finishedExpirationTime <= root.lastExpiredTime) {
+ // Clear the expired time
+ root.lastExpiredTime = NoWork;
+ }
+ }
+ function markRootExpiredAtTime(root, expirationTime) {
+ var lastExpiredTime = root.lastExpiredTime;
+
+ if (lastExpiredTime === NoWork || lastExpiredTime > expirationTime) {
+ root.lastExpiredTime = expirationTime;
+ }
+ }
+
+ var didWarnAboutNestedUpdates;
+ var didWarnAboutFindNodeInStrictMode;
+
+ {
+ didWarnAboutNestedUpdates = false;
+ didWarnAboutFindNodeInStrictMode = {};
+ }
+
+ function getContextForSubtree(parentComponent) {
+ if (!parentComponent) {
+ return emptyContextObject;
+ }
+
+ var fiber = get(parentComponent);
+ var parentContext = findCurrentUnmaskedContext(fiber);
+
+ if (fiber.tag === ClassComponent) {
+ var Component = fiber.type;
+
+ if (isContextProvider(Component)) {
+ return processChildContext(fiber, Component, parentContext);
+ }
+ }
+
+ return parentContext;
+ }
+
+ function findHostInstanceWithWarning(component, methodName) {
+ {
+ var fiber = get(component);
+
+ if (fiber === undefined) {
+ if (typeof component.render === 'function') {
+ {
+ {
+ throw Error( "Unable to find node on an unmounted component." );
+ }
+ }
+ } else {
+ {
+ {
+ throw Error( "Argument appears to not be a ReactComponent. Keys: " + Object.keys(component) );
+ }
+ }
+ }
+ }
+
+ var hostFiber = findCurrentHostFiber(fiber);
+
+ if (hostFiber === null) {
+ return null;
+ }
+
+ if (hostFiber.mode & StrictMode) {
+ var componentName = getComponentName(fiber.type) || 'Component';
+
+ if (!didWarnAboutFindNodeInStrictMode[componentName]) {
+ didWarnAboutFindNodeInStrictMode[componentName] = true;
+
+ if (fiber.mode & StrictMode) {
+ error('%s is deprecated in StrictMode. ' + '%s was passed an instance of %s which is inside StrictMode. ' + 'Instead, add a ref directly to the element you want to reference. ' + 'Learn more about using refs safely here: ' + 'https://fb.me/react-strict-mode-find-node%s', methodName, methodName, componentName, getStackByFiberInDevAndProd(hostFiber));
+ } else {
+ error('%s is deprecated in StrictMode. ' + '%s was passed an instance of %s which renders StrictMode children. ' + 'Instead, add a ref directly to the element you want to reference. ' + 'Learn more about using refs safely here: ' + 'https://fb.me/react-strict-mode-find-node%s', methodName, methodName, componentName, getStackByFiberInDevAndProd(hostFiber));
+ }
+ }
+ }
+
+ return hostFiber.stateNode;
+ }
+ }
+
+ function createContainer(containerInfo, tag, hydrate, hydrationCallbacks) {
+ return createFiberRoot(containerInfo, tag, hydrate);
+ }
+ function updateContainer(element, container, parentComponent, callback) {
+ {
+ onScheduleRoot(container, element);
+ }
+
+ var current$1 = container.current;
+ var currentTime = requestCurrentTimeForUpdate();
+
+ {
+ // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests
+ if ('undefined' !== typeof jest) {
+ warnIfUnmockedScheduler(current$1);
+ warnIfNotScopedWithMatchingAct(current$1);
+ }
+ }
+
+ var suspenseConfig = requestCurrentSuspenseConfig();
+ var expirationTime = computeExpirationForFiber(currentTime, current$1, suspenseConfig);
+ var context = getContextForSubtree(parentComponent);
+
+ if (container.context === null) {
+ container.context = context;
+ } else {
+ container.pendingContext = context;
+ }
+
+ {
+ if (isRendering && current !== null && !didWarnAboutNestedUpdates) {
+ didWarnAboutNestedUpdates = true;
+
+ error('Render methods should be a pure function of props and state; ' + 'triggering nested component updates from render is not allowed. ' + 'If necessary, trigger nested updates in componentDidUpdate.\n\n' + 'Check the render method of %s.', getComponentName(current.type) || 'Unknown');
+ }
+ }
+
+ var update = createUpdate(expirationTime, suspenseConfig); // Caution: React DevTools currently depends on this property
+ // being called "element".
+
+ update.payload = {
+ element: element
+ };
+ callback = callback === undefined ? null : callback;
+
+ if (callback !== null) {
+ {
+ if (typeof callback !== 'function') {
+ error('render(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callback);
+ }
+ }
+
+ update.callback = callback;
+ }
+
+ enqueueUpdate(current$1, update);
+ scheduleWork(current$1, expirationTime);
+ return expirationTime;
+ }
+ function getPublicRootInstance(container) {
+ var containerFiber = container.current;
+
+ if (!containerFiber.child) {
+ return null;
+ }
+
+ switch (containerFiber.child.tag) {
+ case HostComponent:
+ return getPublicInstance(containerFiber.child.stateNode);
+
+ default:
+ return containerFiber.child.stateNode;
+ }
+ }
+
+ function markRetryTimeImpl(fiber, retryTime) {
+ var suspenseState = fiber.memoizedState;
+
+ if (suspenseState !== null && suspenseState.dehydrated !== null) {
+ if (suspenseState.retryTime < retryTime) {
+ suspenseState.retryTime = retryTime;
+ }
+ }
+ } // Increases the priority of thennables when they resolve within this boundary.
+
+
+ function markRetryTimeIfNotHydrated(fiber, retryTime) {
+ markRetryTimeImpl(fiber, retryTime);
+ var alternate = fiber.alternate;
+
+ if (alternate) {
+ markRetryTimeImpl(alternate, retryTime);
+ }
+ }
+
+ function attemptUserBlockingHydration$1(fiber) {
+ if (fiber.tag !== SuspenseComponent) {
+ // We ignore HostRoots here because we can't increase
+ // their priority and they should not suspend on I/O,
+ // since you have to wrap anything that might suspend in
+ // Suspense.
+ return;
+ }
+
+ var expTime = computeInteractiveExpiration(requestCurrentTimeForUpdate());
+ scheduleWork(fiber, expTime);
+ markRetryTimeIfNotHydrated(fiber, expTime);
+ }
+ function attemptContinuousHydration$1(fiber) {
+ if (fiber.tag !== SuspenseComponent) {
+ // We ignore HostRoots here because we can't increase
+ // their priority and they should not suspend on I/O,
+ // since you have to wrap anything that might suspend in
+ // Suspense.
+ return;
+ }
+
+ scheduleWork(fiber, ContinuousHydration);
+ markRetryTimeIfNotHydrated(fiber, ContinuousHydration);
+ }
+ function attemptHydrationAtCurrentPriority$1(fiber) {
+ if (fiber.tag !== SuspenseComponent) {
+ // We ignore HostRoots here because we can't increase
+ // their priority other than synchronously flush it.
+ return;
+ }
+
+ var currentTime = requestCurrentTimeForUpdate();
+ var expTime = computeExpirationForFiber(currentTime, fiber, null);
+ scheduleWork(fiber, expTime);
+ markRetryTimeIfNotHydrated(fiber, expTime);
+ }
+ function findHostInstanceWithNoPortals(fiber) {
+ var hostFiber = findCurrentHostFiberWithNoPortals(fiber);
+
+ if (hostFiber === null) {
+ return null;
+ }
+
+ if (hostFiber.tag === FundamentalComponent) {
+ return hostFiber.stateNode.instance;
+ }
+
+ return hostFiber.stateNode;
+ }
+
+ var shouldSuspendImpl = function (fiber) {
+ return false;
+ };
+
+ function shouldSuspend(fiber) {
+ return shouldSuspendImpl(fiber);
+ }
+ var overrideHookState = null;
+ var overrideProps = null;
+ var scheduleUpdate = null;
+ var setSuspenseHandler = null;
+
+ {
+ var copyWithSetImpl = function (obj, path, idx, value) {
+ if (idx >= path.length) {
+ return value;
+ }
+
+ var key = path[idx];
+ var updated = Array.isArray(obj) ? obj.slice() : _assign({}, obj); // $FlowFixMe number or string is fine here
+
+ updated[key] = copyWithSetImpl(obj[key], path, idx + 1, value);
+ return updated;
+ };
+
+ var copyWithSet = function (obj, path, value) {
+ return copyWithSetImpl(obj, path, 0, value);
+ }; // Support DevTools editable values for useState and useReducer.
+
+
+ overrideHookState = function (fiber, id, path, value) {
+ // For now, the "id" of stateful hooks is just the stateful hook index.
+ // This may change in the future with e.g. nested hooks.
+ var currentHook = fiber.memoizedState;
+
+ while (currentHook !== null && id > 0) {
+ currentHook = currentHook.next;
+ id--;
+ }
+
+ if (currentHook !== null) {
+ var newState = copyWithSet(currentHook.memoizedState, path, value);
+ currentHook.memoizedState = newState;
+ currentHook.baseState = newState; // We aren't actually adding an update to the queue,
+ // because there is no update we can add for useReducer hooks that won't trigger an error.
+ // (There's no appropriate action type for DevTools overrides.)
+ // As a result though, React will see the scheduled update as a noop and bailout.
+ // Shallow cloning props works as a workaround for now to bypass the bailout check.
+
+ fiber.memoizedProps = _assign({}, fiber.memoizedProps);
+ scheduleWork(fiber, Sync);
+ }
+ }; // Support DevTools props for function components, forwardRef, memo, host components, etc.
+
+
+ overrideProps = function (fiber, path, value) {
+ fiber.pendingProps = copyWithSet(fiber.memoizedProps, path, value);
+
+ if (fiber.alternate) {
+ fiber.alternate.pendingProps = fiber.pendingProps;
+ }
+
+ scheduleWork(fiber, Sync);
+ };
+
+ scheduleUpdate = function (fiber) {
+ scheduleWork(fiber, Sync);
+ };
+
+ setSuspenseHandler = function (newShouldSuspendImpl) {
+ shouldSuspendImpl = newShouldSuspendImpl;
+ };
+ }
+
+ function injectIntoDevTools(devToolsConfig) {
+ var findFiberByHostInstance = devToolsConfig.findFiberByHostInstance;
+ var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
+ return injectInternals(_assign({}, devToolsConfig, {
+ overrideHookState: overrideHookState,
+ overrideProps: overrideProps,
+ setSuspenseHandler: setSuspenseHandler,
+ scheduleUpdate: scheduleUpdate,
+ currentDispatcherRef: ReactCurrentDispatcher,
+ findHostInstanceByFiber: function (fiber) {
+ var hostFiber = findCurrentHostFiber(fiber);
+
+ if (hostFiber === null) {
+ return null;
+ }
+
+ return hostFiber.stateNode;
+ },
+ findFiberByHostInstance: function (instance) {
+ if (!findFiberByHostInstance) {
+ // Might not be implemented by the renderer.
+ return null;
+ }
+
+ return findFiberByHostInstance(instance);
+ },
+ // React Refresh
+ findHostInstancesForRefresh: findHostInstancesForRefresh ,
+ scheduleRefresh: scheduleRefresh ,
+ scheduleRoot: scheduleRoot ,
+ setRefreshHandler: setRefreshHandler ,
+ // Enables DevTools to append owner stacks to error messages in DEV mode.
+ getCurrentFiber: function () {
+ return current;
+ }
+ }));
+ }
+ var IsSomeRendererActing$1 = ReactSharedInternals.IsSomeRendererActing;
+
+ function ReactDOMRoot(container, options) {
+ this._internalRoot = createRootImpl(container, ConcurrentRoot, options);
+ }
+
+ function ReactDOMBlockingRoot(container, tag, options) {
+ this._internalRoot = createRootImpl(container, tag, options);
+ }
+
+ ReactDOMRoot.prototype.render = ReactDOMBlockingRoot.prototype.render = function (children) {
+ var root = this._internalRoot;
+
+ {
+ if (typeof arguments[1] === 'function') {
+ error('render(...): does not support the second callback argument. ' + 'To execute a side effect after rendering, declare it in a component body with useEffect().');
+ }
+
+ var container = root.containerInfo;
+
+ if (container.nodeType !== COMMENT_NODE) {
+ var hostInstance = findHostInstanceWithNoPortals(root.current);
+
+ if (hostInstance) {
+ if (hostInstance.parentNode !== container) {
+ error('render(...): It looks like the React-rendered content of the ' + 'root container was removed without using React. This is not ' + 'supported and will cause errors. Instead, call ' + "root.unmount() to empty a root's container.");
+ }
+ }
+ }
+ }
+
+ updateContainer(children, root, null, null);
+ };
+
+ ReactDOMRoot.prototype.unmount = ReactDOMBlockingRoot.prototype.unmount = function () {
+ {
+ if (typeof arguments[0] === 'function') {
+ error('unmount(...): does not support a callback argument. ' + 'To execute a side effect after rendering, declare it in a component body with useEffect().');
+ }
+ }
+
+ var root = this._internalRoot;
+ var container = root.containerInfo;
+ updateContainer(null, root, null, function () {
+ unmarkContainerAsRoot(container);
+ });
+ };
+
+ function createRootImpl(container, tag, options) {
+ // Tag is either LegacyRoot or Concurrent Root
+ var hydrate = options != null && options.hydrate === true;
+ var hydrationCallbacks = options != null && options.hydrationOptions || null;
+ var root = createContainer(container, tag, hydrate);
+ markContainerAsRoot(root.current, container);
+
+ if (hydrate && tag !== LegacyRoot) {
+ var doc = container.nodeType === DOCUMENT_NODE ? container : container.ownerDocument;
+ eagerlyTrapReplayableEvents(container, doc);
+ }
+
+ return root;
+ }
+ function createLegacyRoot(container, options) {
+ return new ReactDOMBlockingRoot(container, LegacyRoot, options);
+ }
+ function isValidContainer(node) {
+ return !!(node && (node.nodeType === ELEMENT_NODE || node.nodeType === DOCUMENT_NODE || node.nodeType === DOCUMENT_FRAGMENT_NODE || node.nodeType === COMMENT_NODE && node.nodeValue === ' react-mount-point-unstable '));
+ }
+
+ var ReactCurrentOwner$3 = ReactSharedInternals.ReactCurrentOwner;
+ var topLevelUpdateWarnings;
+ var warnedAboutHydrateAPI = false;
+
+ {
+ topLevelUpdateWarnings = function (container) {
+ if (container._reactRootContainer && container.nodeType !== COMMENT_NODE) {
+ var hostInstance = findHostInstanceWithNoPortals(container._reactRootContainer._internalRoot.current);
+
+ if (hostInstance) {
+ if (hostInstance.parentNode !== container) {
+ error('render(...): It looks like the React-rendered content of this ' + 'container was removed without using React. This is not ' + 'supported and will cause errors. Instead, call ' + 'ReactDOM.unmountComponentAtNode to empty a container.');
+ }
+ }
+ }
+
+ var isRootRenderedBySomeReact = !!container._reactRootContainer;
+ var rootEl = getReactRootElementInContainer(container);
+ var hasNonRootReactChild = !!(rootEl && getInstanceFromNode$1(rootEl));
+
+ if (hasNonRootReactChild && !isRootRenderedBySomeReact) {
+ error('render(...): Replacing React-rendered children with a new root ' + 'component. If you intended to update the children of this node, ' + 'you should instead have the existing children update their state ' + 'and render the new components instead of calling ReactDOM.render.');
+ }
+
+ if (container.nodeType === ELEMENT_NODE && container.tagName && container.tagName.toUpperCase() === 'BODY') {
+ error('render(): Rendering components directly into document.body is ' + 'discouraged, since its children are often manipulated by third-party ' + 'scripts and browser extensions. This may lead to subtle ' + 'reconciliation issues. Try rendering into a container element created ' + 'for your app.');
+ }
+ };
+ }
+
+ function getReactRootElementInContainer(container) {
+ if (!container) {
+ return null;
+ }
+
+ if (container.nodeType === DOCUMENT_NODE) {
+ return container.documentElement;
+ } else {
+ return container.firstChild;
+ }
+ }
+
+ function shouldHydrateDueToLegacyHeuristic(container) {
+ var rootElement = getReactRootElementInContainer(container);
+ return !!(rootElement && rootElement.nodeType === ELEMENT_NODE && rootElement.hasAttribute(ROOT_ATTRIBUTE_NAME));
+ }
+
+ function legacyCreateRootFromDOMContainer(container, forceHydrate) {
+ var shouldHydrate = forceHydrate || shouldHydrateDueToLegacyHeuristic(container); // First clear any existing content.
+
+ if (!shouldHydrate) {
+ var warned = false;
+ var rootSibling;
+
+ while (rootSibling = container.lastChild) {
+ {
+ if (!warned && rootSibling.nodeType === ELEMENT_NODE && rootSibling.hasAttribute(ROOT_ATTRIBUTE_NAME)) {
+ warned = true;
+
+ error('render(): Target node has markup rendered by React, but there ' + 'are unrelated nodes as well. This is most commonly caused by ' + 'white-space inserted around server-rendered markup.');
+ }
+ }
+
+ container.removeChild(rootSibling);
+ }
+ }
+
+ {
+ if (shouldHydrate && !forceHydrate && !warnedAboutHydrateAPI) {
+ warnedAboutHydrateAPI = true;
+
+ warn('render(): Calling ReactDOM.render() to hydrate server-rendered markup ' + 'will stop working in React v17. Replace the ReactDOM.render() call ' + 'with ReactDOM.hydrate() if you want React to attach to the server HTML.');
+ }
+ }
+
+ return createLegacyRoot(container, shouldHydrate ? {
+ hydrate: true
+ } : undefined);
+ }
+
+ function warnOnInvalidCallback$1(callback, callerName) {
+ {
+ if (callback !== null && typeof callback !== 'function') {
+ error('%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback);
+ }
+ }
+ }
+
+ function legacyRenderSubtreeIntoContainer(parentComponent, children, container, forceHydrate, callback) {
+ {
+ topLevelUpdateWarnings(container);
+ warnOnInvalidCallback$1(callback === undefined ? null : callback, 'render');
+ } // TODO: Without `any` type, Flow says "Property cannot be accessed on any
+ // member of intersection type." Whyyyyyy.
+
+
+ var root = container._reactRootContainer;
+ var fiberRoot;
+
+ if (!root) {
+ // Initial mount
+ root = container._reactRootContainer = legacyCreateRootFromDOMContainer(container, forceHydrate);
+ fiberRoot = root._internalRoot;
+
+ if (typeof callback === 'function') {
+ var originalCallback = callback;
+
+ callback = function () {
+ var instance = getPublicRootInstance(fiberRoot);
+ originalCallback.call(instance);
+ };
+ } // Initial mount should not be batched.
+
+
+ unbatchedUpdates(function () {
+ updateContainer(children, fiberRoot, parentComponent, callback);
+ });
+ } else {
+ fiberRoot = root._internalRoot;
+
+ if (typeof callback === 'function') {
+ var _originalCallback = callback;
+
+ callback = function () {
+ var instance = getPublicRootInstance(fiberRoot);
+
+ _originalCallback.call(instance);
+ };
+ } // Update
+
+
+ updateContainer(children, fiberRoot, parentComponent, callback);
+ }
+
+ return getPublicRootInstance(fiberRoot);
+ }
+
+ function findDOMNode(componentOrElement) {
+ {
+ var owner = ReactCurrentOwner$3.current;
+
+ if (owner !== null && owner.stateNode !== null) {
+ var warnedAboutRefsInRender = owner.stateNode._warnedAboutRefsInRender;
+
+ if (!warnedAboutRefsInRender) {
+ error('%s is accessing findDOMNode inside its render(). ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', getComponentName(owner.type) || 'A component');
+ }
+
+ owner.stateNode._warnedAboutRefsInRender = true;
+ }
+ }
+
+ if (componentOrElement == null) {
+ return null;
+ }
+
+ if (componentOrElement.nodeType === ELEMENT_NODE) {
+ return componentOrElement;
+ }
+
+ {
+ return findHostInstanceWithWarning(componentOrElement, 'findDOMNode');
+ }
+ }
+ function hydrate(element, container, callback) {
+ if (!isValidContainer(container)) {
+ {
+ throw Error( "Target container is not a DOM element." );
+ }
+ }
+
+ {
+ var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === undefined;
+
+ if (isModernRoot) {
+ error('You are calling ReactDOM.hydrate() on a container that was previously ' + 'passed to ReactDOM.createRoot(). This is not supported. ' + 'Did you mean to call createRoot(container, {hydrate: true}).render(element)?');
+ }
+ } // TODO: throw or warn if we couldn't hydrate?
+
+
+ return legacyRenderSubtreeIntoContainer(null, element, container, true, callback);
+ }
+ function render(element, container, callback) {
+ if (!isValidContainer(container)) {
+ {
+ throw Error( "Target container is not a DOM element." );
+ }
+ }
+
+ {
+ var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === undefined;
+
+ if (isModernRoot) {
+ error('You are calling ReactDOM.render() on a container that was previously ' + 'passed to ReactDOM.createRoot(). This is not supported. ' + 'Did you mean to call root.render(element)?');
+ }
+ }
+
+ return legacyRenderSubtreeIntoContainer(null, element, container, false, callback);
+ }
+ function unstable_renderSubtreeIntoContainer(parentComponent, element, containerNode, callback) {
+ if (!isValidContainer(containerNode)) {
+ {
+ throw Error( "Target container is not a DOM element." );
+ }
+ }
+
+ if (!(parentComponent != null && has$1(parentComponent))) {
+ {
+ throw Error( "parentComponent must be a valid React Component" );
+ }
+ }
+
+ return legacyRenderSubtreeIntoContainer(parentComponent, element, containerNode, false, callback);
+ }
+ function unmountComponentAtNode(container) {
+ if (!isValidContainer(container)) {
+ {
+ throw Error( "unmountComponentAtNode(...): Target container is not a DOM element." );
+ }
+ }
+
+ {
+ var isModernRoot = isContainerMarkedAsRoot(container) && container._reactRootContainer === undefined;
+
+ if (isModernRoot) {
+ error('You are calling ReactDOM.unmountComponentAtNode() on a container that was previously ' + 'passed to ReactDOM.createRoot(). This is not supported. Did you mean to call root.unmount()?');
+ }
+ }
+
+ if (container._reactRootContainer) {
+ {
+ var rootEl = getReactRootElementInContainer(container);
+ var renderedByDifferentReact = rootEl && !getInstanceFromNode$1(rootEl);
+
+ if (renderedByDifferentReact) {
+ error("unmountComponentAtNode(): The node you're attempting to unmount " + 'was rendered by another copy of React.');
+ }
+ } // Unmount should not be batched.
+
+
+ unbatchedUpdates(function () {
+ legacyRenderSubtreeIntoContainer(null, null, container, false, function () {
+ // $FlowFixMe This should probably use `delete container._reactRootContainer`
+ container._reactRootContainer = null;
+ unmarkContainerAsRoot(container);
+ });
+ }); // If you call unmountComponentAtNode twice in quick succession, you'll
+ // get `true` twice. That's probably fine?
+
+ return true;
+ } else {
+ {
+ var _rootEl = getReactRootElementInContainer(container);
+
+ var hasNonRootReactChild = !!(_rootEl && getInstanceFromNode$1(_rootEl)); // Check if the container itself is a React root node.
+
+ var isContainerReactRoot = container.nodeType === ELEMENT_NODE && isValidContainer(container.parentNode) && !!container.parentNode._reactRootContainer;
+
+ if (hasNonRootReactChild) {
+ error("unmountComponentAtNode(): The node you're attempting to unmount " + 'was rendered by React and is not a top-level container. %s', isContainerReactRoot ? 'You may have accidentally passed in a React root node instead ' + 'of its container.' : 'Instead, have the parent component update its state and ' + 'rerender in order to remove this component.');
+ }
+ }
+
+ return false;
+ }
+ }
+
+ function createPortal(children, containerInfo, // TODO: figure out the API for cross-renderer implementation.
+ implementation) {
+ var key = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
+ return {
+ // This tag allow us to uniquely identify this as a React Portal
+ $$typeof: REACT_PORTAL_TYPE,
+ key: key == null ? null : '' + key,
+ children: children,
+ containerInfo: containerInfo,
+ implementation: implementation
+ };
+ }
+
+ var ReactVersion = '16.13.1';
+
+ setAttemptUserBlockingHydration(attemptUserBlockingHydration$1);
+ setAttemptContinuousHydration(attemptContinuousHydration$1);
+ setAttemptHydrationAtCurrentPriority(attemptHydrationAtCurrentPriority$1);
+ var didWarnAboutUnstableCreatePortal = false;
+
+ {
+ if (typeof Map !== 'function' || // $FlowIssue Flow incorrectly thinks Map has no prototype
+ Map.prototype == null || typeof Map.prototype.forEach !== 'function' || typeof Set !== 'function' || // $FlowIssue Flow incorrectly thinks Set has no prototype
+ Set.prototype == null || typeof Set.prototype.clear !== 'function' || typeof Set.prototype.forEach !== 'function') {
+ error('React depends on Map and Set built-in types. Make sure that you load a ' + 'polyfill in older browsers. https://fb.me/react-polyfills');
+ }
+ }
+
+ setRestoreImplementation(restoreControlledState$3);
+ setBatchingImplementation(batchedUpdates$1, discreteUpdates$1, flushDiscreteUpdates, batchedEventUpdates$1);
+
+ function createPortal$1(children, container) {
+ var key = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
+
+ if (!isValidContainer(container)) {
+ {
+ throw Error( "Target container is not a DOM element." );
+ }
+ } // TODO: pass ReactDOM portal implementation as third argument
+ // $FlowFixMe The Flow type is opaque but there's no way to actually create it.
+
+
+ return createPortal(children, container, null, key);
+ }
+
+ function renderSubtreeIntoContainer(parentComponent, element, containerNode, callback) {
+
+ return unstable_renderSubtreeIntoContainer(parentComponent, element, containerNode, callback);
+ }
+
+ function unstable_createPortal(children, container) {
+ var key = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
+
+ {
+ if (!didWarnAboutUnstableCreatePortal) {
+ didWarnAboutUnstableCreatePortal = true;
+
+ warn('The ReactDOM.unstable_createPortal() alias has been deprecated, ' + 'and will be removed in React 17+. Update your code to use ' + 'ReactDOM.createPortal() instead. It has the exact same API, ' + 'but without the "unstable_" prefix.');
+ }
+ }
+
+ return createPortal$1(children, container, key);
+ }
+
+ var Internals = {
+ // Keep in sync with ReactDOMUnstableNativeDependencies.js
+ // ReactTestUtils.js, and ReactTestUtilsAct.js. This is an array for better minification.
+ Events: [getInstanceFromNode$1, getNodeFromInstance$1, getFiberCurrentPropsFromNode$1, injectEventPluginsByName, eventNameDispatchConfigs, accumulateTwoPhaseDispatches, accumulateDirectDispatches, enqueueStateRestore, restoreStateIfNeeded, dispatchEvent, runEventsInBatch, flushPassiveEffects, IsThisRendererActing]
+ };
+ var foundDevTools = injectIntoDevTools({
+ findFiberByHostInstance: getClosestInstanceFromNode,
+ bundleType: 1 ,
+ version: ReactVersion,
+ rendererPackageName: 'react-dom'
+ });
+
+ {
+ if (!foundDevTools && canUseDOM && window.top === window.self) {
+ // If we're in Chrome or Firefox, provide a download link if not installed.
+ if (navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('Edge') === -1 || navigator.userAgent.indexOf('Firefox') > -1) {
+ var protocol = window.location.protocol; // Don't warn in exotic cases like chrome-extension://.
+
+ if (/^(https?|file):$/.test(protocol)) {
+ // eslint-disable-next-line react-internal/no-production-logging
+ console.info('%cDownload the React DevTools ' + 'for a better development experience: ' + 'https://fb.me/react-devtools' + (protocol === 'file:' ? '\nYou might need to use a local HTTP server (instead of file://): ' + 'https://fb.me/react-devtools-faq' : ''), 'font-weight:bold');
+ }
+ }
+ }
+ }
+
+ exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = Internals;
+ exports.createPortal = createPortal$1;
+ exports.findDOMNode = findDOMNode;
+ exports.flushSync = flushSync;
+ exports.hydrate = hydrate;
+ exports.render = render;
+ exports.unmountComponentAtNode = unmountComponentAtNode;
+ exports.unstable_batchedUpdates = batchedUpdates$1;
+ exports.unstable_createPortal = unstable_createPortal;
+ exports.unstable_renderSubtreeIntoContainer = renderSubtreeIntoContainer;
+ exports.version = ReactVersion;
+
+})));
diff --git a/browser/components/newtab/vendor/react-dom-server.js b/browser/components/newtab/vendor/react-dom-server.js
new file mode 100644
index 0000000000..12e0e16ac2
--- /dev/null
+++ b/browser/components/newtab/vendor/react-dom-server.js
@@ -0,0 +1,45 @@
+/** @license React v16.13.1
+ * react-dom-server.browser.production.min.js
+ *
+ * Copyright (c) Facebook, Inc. and its affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+'use strict';(function(k,p){"object"===typeof exports&&"undefined"!==typeof module?module.exports=p(require("react")):"function"===typeof define&&define.amd?define(["react"],p):(k=k||self,k.ReactDOMServer=p(k.React))})(this,function(k){function p(a){for(var b="https://reactjs.org/docs/error-decoder.html?invariant="+a,c=1;c<arguments.length;c++)b+="&args[]="+encodeURIComponent(arguments[c]);return"Minified React error #"+a+"; visit "+b+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}
+function ta(a){if(-1===a._status){a._status=0;var b=a._ctor;b=b();a._result=b;b.then(function(c){0===a._status&&(c=c.default,a._status=1,a._result=c)},function(c){0===a._status&&(a._status=2,a._result=c)})}}function D(a){if(null==a)return null;if("function"===typeof a)return a.displayName||a.name||null;if("string"===typeof a)return a;switch(a){case L:return"Fragment";case W:return"Portal";case X:return"Profiler";case Y:return"StrictMode";case M:return"Suspense";case Z:return"SuspenseList"}if("object"===
+typeof a)switch(a.$$typeof){case aa:return"Context.Consumer";case N:return"Context.Provider";case ba:var b=a.render;b=b.displayName||b.name||"";return a.displayName||(""!==b?"ForwardRef("+b+")":"ForwardRef");case ca:return D(a.type);case ua:return D(a.render);case da:if(a=1===a._status?a._result:null)return D(a)}return null}function E(a,b){for(var c=a._threadCount|0;c<=b;c++)a[c]=a._currentValue2,a._threadCount=c+1}function va(a,b,c,d){if(d&&(d=a.contextType,"object"===typeof d&&null!==d))return E(d,
+c),d[c];if(a=a.contextTypes){c={};for(var g in a)c[g]=b[g];b=c}else b=ea;return b}function fa(a){if(ha.call(ia,a))return!0;if(ha.call(ja,a))return!1;if(wa.test(a))return ia[a]=!0;ja[a]=!0;return!1}function xa(a,b,c,d){if(null!==c&&0===c.type)return!1;switch(typeof b){case "function":case "symbol":return!0;case "boolean":if(d)return!1;if(null!==c)return!c.acceptsBooleans;a=a.toLowerCase().slice(0,5);return"data-"!==a&&"aria-"!==a;default:return!1}}function ya(a,b,c,d){if(null===b||"undefined"===typeof b||
+xa(a,b,c,d))return!0;if(d)return!1;if(null!==c)switch(c.type){case 3:return!b;case 4:return!1===b;case 5:return isNaN(b);case 6:return isNaN(b)||1>b}return!1}function n(a,b,c,d,g,h){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=g;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=h}function C(a){if("boolean"===typeof a||"number"===typeof a)return""+a;a=""+a;var b=za.exec(a);if(b){var c="",d,g=0;for(d=b.index;d<a.length;d++){switch(a.charCodeAt(d)){case 34:b=
+"&quot;";break;case 38:b="&amp;";break;case 39:b="&#x27;";break;case 60:b="&lt;";break;case 62:b="&gt;";break;default:continue}g!==d&&(c+=a.substring(g,d));g=d+1;c+=b}a=g!==d?c+a.substring(g,d):c}return a}function Aa(a,b){var c=m.hasOwnProperty(a)?m[a]:null;var d;if(d="style"!==a)d=null!==c?0===c.type:!(2<a.length)||"o"!==a[0]&&"O"!==a[0]||"n"!==a[1]&&"N"!==a[1]?!1:!0;if(d||ya(a,b,c,!1))return"";if(null!==c){a=c.attributeName;d=c.type;if(3===d||4===d&&!0===b)return a+'=""';c.sanitizeURL&&(b=""+b);
+return a+'="'+(C(b)+'"')}return fa(a)?a+'="'+(C(b)+'"'):""}function Ba(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}function A(){if(null===u)throw Error(p(321));return u}function ka(){if(0<I)throw Error(p(312));return{memoizedState:null,queue:null,next:null}}function O(){null===e?null===J?(F=!1,J=e=ka()):(F=!0,e=J):null===e.next?(F=!1,e=e.next=ka()):(F=!0,e=e.next);return e}function la(a,b,c,d){for(;P;)P=!1,I+=1,e=null,c=a(b,d);J=u=null;I=0;e=t=null;return c}function ma(a,b){return"function"===
+typeof b?b(a):b}function na(a,b,c){u=A();e=O();if(F){var d=e.queue;b=d.dispatch;if(null!==t&&(c=t.get(d),void 0!==c)){t.delete(d);d=e.memoizedState;do d=a(d,c.action),c=c.next;while(null!==c);e.memoizedState=d;return[d,b]}return[e.memoizedState,b]}a=a===ma?"function"===typeof b?b():b:void 0!==c?c(b):b;e.memoizedState=a;a=e.queue={last:null,dispatch:null};a=a.dispatch=Ca.bind(null,u,a);return[e.memoizedState,a]}function Ca(a,b,c){if(!(25>I))throw Error(p(301));if(a===u)if(P=!0,a={action:c,next:null},
+null===t&&(t=new Map),c=t.get(b),void 0===c)t.set(b,a);else{for(b=c;null!==b.next;)b=b.next;b.next=a}}function Q(){}function oa(a){switch(a){case "svg":return"http://www.w3.org/2000/svg";case "math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function Da(a){if(void 0===a||null===a)return a;var b="";k.Children.forEach(a,function(a){null!=a&&(b+=a)});return b}function pa(a,b){if(void 0===a)throw Error(p(152,D(b)||"Component"));}function Ea(a,b,c){function d(d,
+h){var f=h.prototype&&h.prototype.isReactComponent,g=va(h,b,c,f),v=[],z=!1,e={isMounted:function(a){return!1},enqueueForceUpdate:function(a){if(null===v)return null},enqueueReplaceState:function(a,c){z=!0;v=[c]},enqueueSetState:function(a,c){if(null===v)return null;v.push(c)}};if(f){if(f=new h(d.props,g,e),"function"===typeof h.getDerivedStateFromProps){var l=h.getDerivedStateFromProps.call(null,d.props,f.state);null!=l&&(f.state=x({},f.state,l))}}else if(u={},f=h(d.props,g,e),f=la(h,d.props,f,g),
+null==f||null==f.render){a=f;pa(a,h);return}f.props=d.props;f.context=g;f.updater=e;e=f.state;void 0===e&&(f.state=e=null);if("function"===typeof f.UNSAFE_componentWillMount||"function"===typeof f.componentWillMount)if("function"===typeof f.componentWillMount&&"function"!==typeof h.getDerivedStateFromProps&&f.componentWillMount(),"function"===typeof f.UNSAFE_componentWillMount&&"function"!==typeof h.getDerivedStateFromProps&&f.UNSAFE_componentWillMount(),v.length){e=v;var m=z;v=null;z=!1;if(m&&1===
+e.length)f.state=e[0];else{l=m?e[0]:f.state;var q=!0;for(m=m?1:0;m<e.length;m++){var r=e[m];r="function"===typeof r?r.call(f,l,d.props,g):r;null!=r&&(q?(q=!1,l=x({},l,r)):x(l,r))}f.state=l}}else v=null;a=f.render();pa(a,h);if("function"===typeof f.getChildContext&&(d=h.childContextTypes,"object"===typeof d)){var k=f.getChildContext();for(var n in k)if(!(n in d))throw Error(p(108,D(h)||"Unknown",n));}k&&(b=x({},b,k))}for(;k.isValidElement(a);){var g=a,h=g.type;if("function"!==typeof h)break;d(g,h)}return{child:a,
+context:b}}var x=k.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.assign,l="function"===typeof Symbol&&Symbol.for,W=l?Symbol.for("react.portal"):60106,L=l?Symbol.for("react.fragment"):60107,Y=l?Symbol.for("react.strict_mode"):60108,X=l?Symbol.for("react.profiler"):60114,N=l?Symbol.for("react.provider"):60109,aa=l?Symbol.for("react.context"):60110,Fa=l?Symbol.for("react.concurrent_mode"):60111,ba=l?Symbol.for("react.forward_ref"):60112,M=l?Symbol.for("react.suspense"):60113,Z=l?Symbol.for("react.suspense_list"):
+60120,ca=l?Symbol.for("react.memo"):60115,da=l?Symbol.for("react.lazy"):60116,ua=l?Symbol.for("react.block"):60121,Ga=l?Symbol.for("react.fundamental"):60117,Ha=l?Symbol.for("react.scope"):60119;l=k.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;l.hasOwnProperty("ReactCurrentDispatcher")||(l.ReactCurrentDispatcher={current:null});l.hasOwnProperty("ReactCurrentBatchConfig")||(l.ReactCurrentBatchConfig={suspense:null});for(var ea={},q=new Uint16Array(16),K=0;15>K;K++)q[K]=K+1;q[15]=0;var wa=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,
+ha=Object.prototype.hasOwnProperty,ja={},ia={},m={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a){m[a]=new n(a,0,!1,a,null,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(a){var b=a[0];m[b]=new n(b,1,!1,a[1],null,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(a){m[a]=new n(a,
+2,!1,a.toLowerCase(),null,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(a){m[a]=new n(a,2,!1,a,null,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a){m[a]=new n(a,3,!1,a.toLowerCase(),null,!1)});["checked","multiple","muted","selected"].forEach(function(a){m[a]=
+new n(a,3,!0,a,null,!1)});["capture","download"].forEach(function(a){m[a]=new n(a,4,!1,a,null,!1)});["cols","rows","size","span"].forEach(function(a){m[a]=new n(a,6,!1,a,null,!1)});["rowSpan","start"].forEach(function(a){m[a]=new n(a,5,!1,a.toLowerCase(),null,!1)});var S=/[\-:]([a-z])/g,T=function(a){return a[1].toUpperCase()};"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a){var b=
+a.replace(S,T);m[b]=new n(b,1,!1,a,null,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a){var b=a.replace(S,T);m[b]=new n(b,1,!1,a,"http://www.w3.org/1999/xlink",!1)});["xml:base","xml:lang","xml:space"].forEach(function(a){var b=a.replace(S,T);m[b]=new n(b,1,!1,a,"http://www.w3.org/XML/1998/namespace",!1)});["tabIndex","crossOrigin"].forEach(function(a){m[a]=new n(a,1,!1,a.toLowerCase(),null,!1)});m.xlinkHref=new n("xlinkHref",1,!1,"xlink:href",
+"http://www.w3.org/1999/xlink",!0);["src","href","action","formAction"].forEach(function(a){m[a]=new n(a,1,!1,a.toLowerCase(),null,!0)});var za=/["'&<>]/,Ia="function"===typeof Object.is?Object.is:Ba,u=null,J=null,e=null,F=!1,P=!1,t=null,I=0,G=0,Ja={readContext:function(a,b){b=G;E(a,b);return a[b]},useContext:function(a,b){A();b=G;E(a,b);return a[b]},useMemo:function(a,b){u=A();e=O();b=void 0===b?null:b;if(null!==e){var c=e.memoizedState;if(null!==c&&null!==b){a:{var d=c[1];if(null===d)d=!1;else{for(var g=
+0;g<d.length&&g<b.length;g++)if(!Ia(b[g],d[g])){d=!1;break a}d=!0}}if(d)return c[0]}}a=a();e.memoizedState=[a,b];return a},useReducer:na,useRef:function(a){u=A();e=O();var b=e.memoizedState;return null===b?(a={current:a},e.memoizedState=a):b},useState:function(a){return na(ma,a)},useLayoutEffect:function(a,b){},useCallback:function(a,b){return a},useImperativeHandle:Q,useEffect:Q,useDebugValue:Q,useResponder:function(a,b){return{props:b,responder:a}},useDeferredValue:function(a,b){A();return a},useTransition:function(a){A();
+return[function(a){a()},!1]}},qa={area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0},Ka=x({menuitem:!0},qa),H={animationIterationCount:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,
+gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},La=["Webkit","ms","Moz","O"];Object.keys(H).forEach(function(a){La.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);H[b]=H[a]})});var Ma=/([A-Z])/g,Na=/^ms-/,B=k.Children.toArray,U=l.ReactCurrentDispatcher,
+Oa={listing:!0,pre:!0,textarea:!0},Pa=/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/,ra={},V={},Qa=Object.prototype.hasOwnProperty,Ra={children:null,dangerouslySetInnerHTML:null,suppressContentEditableWarning:null,suppressHydrationWarning:null},sa=function(){function a(a,b){k.isValidElement(a)?a.type!==L?a=[a]:(a=a.props.children,a=k.isValidElement(a)?[a]:B(a)):a=B(a);a={type:null,domNamespace:"http://www.w3.org/1999/xhtml",children:a,childIndex:0,context:ea,footer:""};var c=q[0];if(0===c){var h=q;c=h.length;var d=
+2*c;if(!(65536>=d))throw Error(p(304));var z=new Uint16Array(d);z.set(h);q=z;q[0]=c+1;for(h=c;h<d-1;h++)q[h]=h+1;q[d-1]=0}else q[0]=q[c];this.threadID=c;this.stack=[a];this.exhausted=!1;this.currentSelectValue=null;this.previousWasTextNode=!1;this.makeStaticMarkup=b;this.suspenseDepth=0;this.contextIndex=-1;this.contextStack=[];this.contextValueStack=[]}var b=a.prototype;b.destroy=function(){if(!this.exhausted){this.exhausted=!0;this.clearProviders();var a=this.threadID;q[a]=q[0];q[0]=a}};b.pushProvider=
+function(a){var b=++this.contextIndex,c=a.type._context,h=this.threadID;E(c,h);var v=c[h];this.contextStack[b]=c;this.contextValueStack[b]=v;c[h]=a.props.value};b.popProvider=function(a){a=this.contextIndex;var b=this.contextStack[a],c=this.contextValueStack[a];this.contextStack[a]=null;this.contextValueStack[a]=null;this.contextIndex--;b[this.threadID]=c};b.clearProviders=function(){for(var a=this.contextIndex;0<=a;a--)this.contextStack[a][this.threadID]=this.contextValueStack[a]};b.read=function(a){if(this.exhausted)return null;
+var b=G;G=this.threadID;var c=U.current;U.current=Ja;try{for(var h=[""],v=!1;h[0].length<a;){if(0===this.stack.length){this.exhausted=!0;var z=this.threadID;q[z]=q[0];q[0]=z;break}var f=this.stack[this.stack.length-1];if(v||f.childIndex>=f.children.length){var e=f.footer;""!==e&&(this.previousWasTextNode=!1);this.stack.pop();if("select"===f.type)this.currentSelectValue=null;else if(null!=f.type&&null!=f.type.type&&f.type.type.$$typeof===N)this.popProvider(f.type);else if(f.type===M){this.suspenseDepth--;
+var l=h.pop();if(v){v=!1;var m=f.fallbackFrame;if(!m)throw Error(p(303));this.stack.push(m);h[this.suspenseDepth]+="\x3c!--$!--\x3e";continue}else h[this.suspenseDepth]+=l}h[this.suspenseDepth]+=e}else{var k=f.children[f.childIndex++],n="";try{n+=this.render(k,f.context,f.domNamespace)}catch(R){if(null!=R&&"function"===typeof R.then)throw Error(p(294));throw R;}finally{}h.length<=this.suspenseDepth&&h.push("");h[this.suspenseDepth]+=n}}return h[0]}finally{U.current=c,G=b}};b.render=function(a,b,g){if("string"===
+typeof a||"number"===typeof a){g=""+a;if(""===g)return"";if(this.makeStaticMarkup)return C(g);if(this.previousWasTextNode)return"\x3c!-- --\x3e"+C(g);this.previousWasTextNode=!0;return C(g)}b=Ea(a,b,this.threadID);a=b.child;b=b.context;if(null===a||!1===a)return"";if(!k.isValidElement(a)){if(null!=a&&null!=a.$$typeof){g=a.$$typeof;if(g===W)throw Error(p(257));throw Error(p(258,g.toString()));}a=B(a);this.stack.push({type:null,domNamespace:g,children:a,childIndex:0,context:b,footer:""});return""}var c=
+a.type;if("string"===typeof c)return this.renderDOM(a,b,g);switch(c){case Y:case Fa:case X:case Z:case L:return a=B(a.props.children),this.stack.push({type:null,domNamespace:g,children:a,childIndex:0,context:b,footer:""}),"";case M:throw Error(p(294));}if("object"===typeof c&&null!==c)switch(c.$$typeof){case ba:u={};var d=c.render(a.props,a.ref);d=la(c.render,a.props,d,a.ref);d=B(d);this.stack.push({type:null,domNamespace:g,children:d,childIndex:0,context:b,footer:""});return"";case ca:return a=[k.createElement(c.type,
+x({ref:a.ref},a.props))],this.stack.push({type:null,domNamespace:g,children:a,childIndex:0,context:b,footer:""}),"";case N:return c=B(a.props.children),g={type:a,domNamespace:g,children:c,childIndex:0,context:b,footer:""},this.pushProvider(a),this.stack.push(g),"";case aa:c=a.type;d=a.props;var e=this.threadID;E(c,e);c=B(d.children(c[e]));this.stack.push({type:a,domNamespace:g,children:c,childIndex:0,context:b,footer:""});return"";case Ga:throw Error(p(338));case da:switch(c=a.type,ta(c),c._status){case 1:return a=
+[k.createElement(c._result,x({ref:a.ref},a.props))],this.stack.push({type:null,domNamespace:g,children:a,childIndex:0,context:b,footer:""}),"";case 2:throw c._result;default:throw Error(p(295));}case Ha:throw Error(p(343));}throw Error(p(130,null==c?c:typeof c,""));};b.renderDOM=function(a,b,g){var c=a.type.toLowerCase();"http://www.w3.org/1999/xhtml"===g&&oa(c);if(!ra.hasOwnProperty(c)){if(!Pa.test(c))throw Error(p(65,c));ra[c]=!0}var d=a.props;if("input"===c)d=x({type:void 0},d,{defaultChecked:void 0,
+defaultValue:void 0,value:null!=d.value?d.value:d.defaultValue,checked:null!=d.checked?d.checked:d.defaultChecked});else if("textarea"===c){var e=d.value;if(null==e){e=d.defaultValue;var f=d.children;if(null!=f){if(null!=e)throw Error(p(92));if(Array.isArray(f)){if(!(1>=f.length))throw Error(p(93));f=f[0]}e=""+f}null==e&&(e="")}d=x({},d,{value:void 0,children:""+e})}else if("select"===c)this.currentSelectValue=null!=d.value?d.value:d.defaultValue,d=x({},d,{value:void 0});else if("option"===c){f=this.currentSelectValue;
+var l=Da(d.children);if(null!=f){var m=null!=d.value?d.value+"":l;e=!1;if(Array.isArray(f))for(var k=0;k<f.length;k++){if(""+f[k]===m){e=!0;break}}else e=""+f===m;d=x({selected:void 0,children:void 0},d,{selected:e,children:l})}}if(e=d){if(Ka[c]&&(null!=e.children||null!=e.dangerouslySetInnerHTML))throw Error(p(137,c,""));if(null!=e.dangerouslySetInnerHTML){if(null!=e.children)throw Error(p(60));if(!("object"===typeof e.dangerouslySetInnerHTML&&"__html"in e.dangerouslySetInnerHTML))throw Error(p(61));
+}if(null!=e.style&&"object"!==typeof e.style)throw Error(p(62,""));}e=d;f=this.makeStaticMarkup;l=1===this.stack.length;m="<"+a.type;for(w in e)if(Qa.call(e,w)){var n=e[w];if(null!=n){if("style"===w){k=void 0;var q="",u="";for(k in n)if(n.hasOwnProperty(k)){var y=0===k.indexOf("--"),r=n[k];if(null!=r){if(y)var t=k;else if(t=k,V.hasOwnProperty(t))t=V[t];else{var A=t.replace(Ma,"-$1").toLowerCase().replace(Na,"-ms-");t=V[t]=A}q+=u+t+":";u=k;y=null==r||"boolean"===typeof r||""===r?"":y||"number"!==typeof r||
+0===r||H.hasOwnProperty(u)&&H[u]?(""+r).trim():r+"px";q+=y;u=";"}}n=q||null}k=null;b:if(y=c,r=e,-1===y.indexOf("-"))y="string"===typeof r.is;else switch(y){case "annotation-xml":case "color-profile":case "font-face":case "font-face-src":case "font-face-uri":case "font-face-format":case "font-face-name":case "missing-glyph":y=!1;break b;default:y=!0}y?Ra.hasOwnProperty(w)||(k=w,k=fa(k)&&null!=n?k+'="'+(C(n)+'"'):""):k=Aa(w,n);k&&(m+=" "+k)}}f||l&&(m+=' data-reactroot=""');var w=m;e="";qa.hasOwnProperty(c)?
+w+="/>":(w+=">",e="</"+a.type+">");a:{f=d.dangerouslySetInnerHTML;if(null!=f){if(null!=f.__html){f=f.__html;break a}}else if(f=d.children,"string"===typeof f||"number"===typeof f){f=C(f);break a}f=null}null!=f?(d=[],Oa.hasOwnProperty(c)&&"\n"===f.charAt(0)&&(w+="\n"),w+=f):d=B(d.children);a=a.type;g=null==g||"http://www.w3.org/1999/xhtml"===g?oa(a):"http://www.w3.org/2000/svg"===g&&"foreignObject"===a?"http://www.w3.org/1999/xhtml":g;this.stack.push({domNamespace:g,type:c,children:d,childIndex:0,
+context:b,footer:e});this.previousWasTextNode=!1;return w};return a}();l={renderToString:function(a){a=new sa(a,!1);try{return a.read(Infinity)}finally{a.destroy()}},renderToStaticMarkup:function(a){a=new sa(a,!0);try{return a.read(Infinity)}finally{a.destroy()}},renderToNodeStream:function(){throw Error(p(207));},renderToStaticNodeStream:function(){throw Error(p(208));},version:"16.13.1"};return l.default||l});
diff --git a/browser/components/newtab/vendor/react-dom.js b/browser/components/newtab/vendor/react-dom.js
new file mode 100644
index 0000000000..8ddde060c7
--- /dev/null
+++ b/browser/components/newtab/vendor/react-dom.js
@@ -0,0 +1,239 @@
+/** @license React v16.13.1
+ * react-dom.production.min.js
+ *
+ * Copyright (c) Facebook, Inc. and its affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+/*
+ Modernizr 3.0.0pre (Custom Build) | MIT
+*/
+'use strict';(function(I,ea){"object"===typeof exports&&"undefined"!==typeof module?ea(exports,require("react")):"function"===typeof define&&define.amd?define(["exports","react"],ea):(I=I||self,ea(I.ReactDOM={},I.React))})(this,function(I,ea){function k(a){for(var b="https://reactjs.org/docs/error-decoder.html?invariant="+a,c=1;c<arguments.length;c++)b+="&args[]="+encodeURIComponent(arguments[c]);return"Minified React error #"+a+"; visit "+b+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}
+function ji(a,b,c,d,e,f,g,h,m){yb=!1;gc=null;ki.apply(li,arguments)}function mi(a,b,c,d,e,f,g,h,m){ji.apply(this,arguments);if(yb){if(yb){var n=gc;yb=!1;gc=null}else throw Error(k(198));hc||(hc=!0,pd=n)}}function lf(a,b,c){var d=a.type||"unknown-event";a.currentTarget=mf(c);mi(d,b,void 0,a);a.currentTarget=null}function nf(){if(ic)for(var a in cb){var b=cb[a],c=ic.indexOf(a);if(!(-1<c))throw Error(k(96,a));if(!jc[c]){if(!b.extractEvents)throw Error(k(97,a));jc[c]=b;c=b.eventTypes;for(var d in c){var e=
+void 0;var f=c[d],g=b,h=d;if(qd.hasOwnProperty(h))throw Error(k(99,h));qd[h]=f;var m=f.phasedRegistrationNames;if(m){for(e in m)m.hasOwnProperty(e)&&of(m[e],g,h);e=!0}else f.registrationName?(of(f.registrationName,g,h),e=!0):e=!1;if(!e)throw Error(k(98,d,a));}}}}function of(a,b,c){if(db[a])throw Error(k(100,a));db[a]=b;rd[a]=b.eventTypes[c].dependencies}function pf(a){var b=!1,c;for(c in a)if(a.hasOwnProperty(c)){var d=a[c];if(!cb.hasOwnProperty(c)||cb[c]!==d){if(cb[c])throw Error(k(102,c));cb[c]=
+d;b=!0}}b&&nf()}function qf(a){if(a=rf(a)){if("function"!==typeof sd)throw Error(k(280));var b=a.stateNode;b&&(b=td(b),sd(a.stateNode,a.type,b))}}function sf(a){eb?fb?fb.push(a):fb=[a]:eb=a}function tf(){if(eb){var a=eb,b=fb;fb=eb=null;qf(a);if(b)for(a=0;a<b.length;a++)qf(b[a])}}function ud(){if(null!==eb||null!==fb)vd(),tf()}function uf(a,b,c){if(wd)return a(b,c);wd=!0;try{return vf(a,b,c)}finally{wd=!1,ud()}}function ni(a){if(wf.call(xf,a))return!0;if(wf.call(yf,a))return!1;if(oi.test(a))return xf[a]=
+!0;yf[a]=!0;return!1}function pi(a,b,c,d){if(null!==c&&0===c.type)return!1;switch(typeof b){case "function":case "symbol":return!0;case "boolean":if(d)return!1;if(null!==c)return!c.acceptsBooleans;a=a.toLowerCase().slice(0,5);return"data-"!==a&&"aria-"!==a;default:return!1}}function qi(a,b,c,d){if(null===b||"undefined"===typeof b||pi(a,b,c,d))return!0;if(d)return!1;if(null!==c)switch(c.type){case 3:return!b;case 4:return!1===b;case 5:return isNaN(b);case 6:return isNaN(b)||1>b}return!1}function L(a,
+b,c,d,e,f){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=e;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=f}function xd(a,b,c,d){var e=E.hasOwnProperty(b)?E[b]:null;var f=null!==e?0===e.type:d?!1:!(2<b.length)||"o"!==b[0]&&"O"!==b[0]||"n"!==b[1]&&"N"!==b[1]?!1:!0;f||(qi(b,c,e,d)&&(c=null),d||null===e?ni(b)&&(null===c?a.removeAttribute(b):a.setAttribute(b,""+c)):e.mustUseProperty?a[e.propertyName]=null===c?3===e.type?!1:"":c:(b=e.attributeName,
+d=e.attributeNamespace,null===c?a.removeAttribute(b):(e=e.type,c=3===e||4===e&&!0===c?"":""+c,d?a.setAttributeNS(d,b,c):a.setAttribute(b,c))))}function zb(a){if(null===a||"object"!==typeof a)return null;a=zf&&a[zf]||a["@@iterator"];return"function"===typeof a?a:null}function ri(a){if(-1===a._status){a._status=0;var b=a._ctor;b=b();a._result=b;b.then(function(b){0===a._status&&(b=b.default,a._status=1,a._result=b)},function(b){0===a._status&&(a._status=2,a._result=b)})}}function na(a){if(null==a)return null;
+if("function"===typeof a)return a.displayName||a.name||null;if("string"===typeof a)return a;switch(a){case Ma:return"Fragment";case gb:return"Portal";case kc:return"Profiler";case Af:return"StrictMode";case lc:return"Suspense";case yd:return"SuspenseList"}if("object"===typeof a)switch(a.$$typeof){case Bf:return"Context.Consumer";case Cf:return"Context.Provider";case zd:var b=a.render;b=b.displayName||b.name||"";return a.displayName||(""!==b?"ForwardRef("+b+")":"ForwardRef");case Ad:return na(a.type);
+case Df:return na(a.render);case Ef:if(a=1===a._status?a._result:null)return na(a)}return null}function Bd(a){var b="";do{a:switch(a.tag){case 3:case 4:case 6:case 7:case 10:case 9:var c="";break a;default:var d=a._debugOwner,e=a._debugSource,f=na(a.type);c=null;d&&(c=na(d.type));d=f;f="";e?f=" (at "+e.fileName.replace(si,"")+":"+e.lineNumber+")":c&&(f=" (created by "+c+")");c="\n in "+(d||"Unknown")+f}b+=c;a=a.return}while(a);return b}function va(a){switch(typeof a){case "boolean":case "number":case "object":case "string":case "undefined":return a;
+default:return""}}function Ff(a){var b=a.type;return(a=a.nodeName)&&"input"===a.toLowerCase()&&("checkbox"===b||"radio"===b)}function ti(a){var b=Ff(a)?"checked":"value",c=Object.getOwnPropertyDescriptor(a.constructor.prototype,b),d=""+a[b];if(!a.hasOwnProperty(b)&&"undefined"!==typeof c&&"function"===typeof c.get&&"function"===typeof c.set){var e=c.get,f=c.set;Object.defineProperty(a,b,{configurable:!0,get:function(){return e.call(this)},set:function(a){d=""+a;f.call(this,a)}});Object.defineProperty(a,
+b,{enumerable:c.enumerable});return{getValue:function(){return d},setValue:function(a){d=""+a},stopTracking:function(){a._valueTracker=null;delete a[b]}}}}function mc(a){a._valueTracker||(a._valueTracker=ti(a))}function Gf(a){if(!a)return!1;var b=a._valueTracker;if(!b)return!0;var c=b.getValue();var d="";a&&(d=Ff(a)?a.checked?"true":"false":a.value);a=d;return a!==c?(b.setValue(a),!0):!1}function Cd(a,b){var c=b.checked;return M({},b,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=
+c?c:a._wrapperState.initialChecked})}function Hf(a,b){var c=null==b.defaultValue?"":b.defaultValue,d=null!=b.checked?b.checked:b.defaultChecked;c=va(null!=b.value?b.value:c);a._wrapperState={initialChecked:d,initialValue:c,controlled:"checkbox"===b.type||"radio"===b.type?null!=b.checked:null!=b.value}}function If(a,b){b=b.checked;null!=b&&xd(a,"checked",b,!1)}function Dd(a,b){If(a,b);var c=va(b.value),d=b.type;if(null!=c)if("number"===d){if(0===c&&""===a.value||a.value!=c)a.value=""+c}else a.value!==
+""+c&&(a.value=""+c);else if("submit"===d||"reset"===d){a.removeAttribute("value");return}b.hasOwnProperty("value")?Ed(a,b.type,c):b.hasOwnProperty("defaultValue")&&Ed(a,b.type,va(b.defaultValue));null==b.checked&&null!=b.defaultChecked&&(a.defaultChecked=!!b.defaultChecked)}function Jf(a,b,c){if(b.hasOwnProperty("value")||b.hasOwnProperty("defaultValue")){var d=b.type;if(!("submit"!==d&&"reset"!==d||void 0!==b.value&&null!==b.value))return;b=""+a._wrapperState.initialValue;c||b===a.value||(a.value=
+b);a.defaultValue=b}c=a.name;""!==c&&(a.name="");a.defaultChecked=!!a._wrapperState.initialChecked;""!==c&&(a.name=c)}function Ed(a,b,c){if("number"!==b||a.ownerDocument.activeElement!==a)null==c?a.defaultValue=""+a._wrapperState.initialValue:a.defaultValue!==""+c&&(a.defaultValue=""+c)}function ui(a){var b="";ea.Children.forEach(a,function(a){null!=a&&(b+=a)});return b}function Fd(a,b){a=M({children:void 0},b);if(b=ui(b.children))a.children=b;return a}function hb(a,b,c,d){a=a.options;if(b){b={};
+for(var e=0;e<c.length;e++)b["$"+c[e]]=!0;for(c=0;c<a.length;c++)e=b.hasOwnProperty("$"+a[c].value),a[c].selected!==e&&(a[c].selected=e),e&&d&&(a[c].defaultSelected=!0)}else{c=""+va(c);b=null;for(e=0;e<a.length;e++){if(a[e].value===c){a[e].selected=!0;d&&(a[e].defaultSelected=!0);return}null!==b||a[e].disabled||(b=a[e])}null!==b&&(b.selected=!0)}}function Gd(a,b){if(null!=b.dangerouslySetInnerHTML)throw Error(k(91));return M({},b,{value:void 0,defaultValue:void 0,children:""+a._wrapperState.initialValue})}
+function Kf(a,b){var c=b.value;if(null==c){c=b.children;b=b.defaultValue;if(null!=c){if(null!=b)throw Error(k(92));if(Array.isArray(c)){if(!(1>=c.length))throw Error(k(93));c=c[0]}b=c}null==b&&(b="");c=b}a._wrapperState={initialValue:va(c)}}function Lf(a,b){var c=va(b.value),d=va(b.defaultValue);null!=c&&(c=""+c,c!==a.value&&(a.value=c),null==b.defaultValue&&a.defaultValue!==c&&(a.defaultValue=c));null!=d&&(a.defaultValue=""+d)}function Mf(a,b){b=a.textContent;b===a._wrapperState.initialValue&&""!==
+b&&null!==b&&(a.value=b)}function Nf(a){switch(a){case "svg":return"http://www.w3.org/2000/svg";case "math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function Hd(a,b){return null==a||"http://www.w3.org/1999/xhtml"===a?Nf(b):"http://www.w3.org/2000/svg"===a&&"foreignObject"===b?"http://www.w3.org/1999/xhtml":a}function nc(a,b){var c={};c[a.toLowerCase()]=b.toLowerCase();c["Webkit"+a]="webkit"+b;c["Moz"+a]="moz"+b;return c}function oc(a){if(Id[a])return Id[a];
+if(!ib[a])return a;var b=ib[a],c;for(c in b)if(b.hasOwnProperty(c)&&c in Of)return Id[a]=b[c];return a}function Jd(a){var b=Pf.get(a);void 0===b&&(b=new Map,Pf.set(a,b));return b}function Na(a){var b=a,c=a;if(a.alternate)for(;b.return;)b=b.return;else{a=b;do b=a,0!==(b.effectTag&1026)&&(c=b.return),a=b.return;while(a)}return 3===b.tag?c:null}function Qf(a){if(13===a.tag){var b=a.memoizedState;null===b&&(a=a.alternate,null!==a&&(b=a.memoizedState));if(null!==b)return b.dehydrated}return null}function Rf(a){if(Na(a)!==
+a)throw Error(k(188));}function vi(a){var b=a.alternate;if(!b){b=Na(a);if(null===b)throw Error(k(188));return b!==a?null:a}for(var c=a,d=b;;){var e=c.return;if(null===e)break;var f=e.alternate;if(null===f){d=e.return;if(null!==d){c=d;continue}break}if(e.child===f.child){for(f=e.child;f;){if(f===c)return Rf(e),a;if(f===d)return Rf(e),b;f=f.sibling}throw Error(k(188));}if(c.return!==d.return)c=e,d=f;else{for(var g=!1,h=e.child;h;){if(h===c){g=!0;c=e;d=f;break}if(h===d){g=!0;d=e;c=f;break}h=h.sibling}if(!g){for(h=
+f.child;h;){if(h===c){g=!0;c=f;d=e;break}if(h===d){g=!0;d=f;c=e;break}h=h.sibling}if(!g)throw Error(k(189));}}if(c.alternate!==d)throw Error(k(190));}if(3!==c.tag)throw Error(k(188));return c.stateNode.current===c?a:b}function Sf(a){a=vi(a);if(!a)return null;for(var b=a;;){if(5===b.tag||6===b.tag)return b;if(b.child)b.child.return=b,b=b.child;else{if(b===a)break;for(;!b.sibling;){if(!b.return||b.return===a)return null;b=b.return}b.sibling.return=b.return;b=b.sibling}}return null}function jb(a,b){if(null==
+b)throw Error(k(30));if(null==a)return b;if(Array.isArray(a)){if(Array.isArray(b))return a.push.apply(a,b),a;a.push(b);return a}return Array.isArray(b)?[a].concat(b):[a,b]}function Kd(a,b,c){Array.isArray(a)?a.forEach(b,c):a&&b.call(c,a)}function pc(a){null!==a&&(Ab=jb(Ab,a));a=Ab;Ab=null;if(a){Kd(a,wi);if(Ab)throw Error(k(95));if(hc)throw a=pd,hc=!1,pd=null,a;}}function Ld(a){a=a.target||a.srcElement||window;a.correspondingUseElement&&(a=a.correspondingUseElement);return 3===a.nodeType?a.parentNode:
+a}function Tf(a){if(!wa)return!1;a="on"+a;var b=a in document;b||(b=document.createElement("div"),b.setAttribute(a,"return;"),b="function"===typeof b[a]);return b}function Uf(a){a.topLevelType=null;a.nativeEvent=null;a.targetInst=null;a.ancestors.length=0;10>qc.length&&qc.push(a)}function Vf(a,b,c,d){if(qc.length){var e=qc.pop();e.topLevelType=a;e.eventSystemFlags=d;e.nativeEvent=b;e.targetInst=c;return e}return{topLevelType:a,eventSystemFlags:d,nativeEvent:b,targetInst:c,ancestors:[]}}function Wf(a){var b=
+a.targetInst,c=b;do{if(!c){a.ancestors.push(c);break}var d=c;if(3===d.tag)d=d.stateNode.containerInfo;else{for(;d.return;)d=d.return;d=3!==d.tag?null:d.stateNode.containerInfo}if(!d)break;b=c.tag;5!==b&&6!==b||a.ancestors.push(c);c=Bb(d)}while(c);for(c=0;c<a.ancestors.length;c++){b=a.ancestors[c];var e=Ld(a.nativeEvent);d=a.topLevelType;var f=a.nativeEvent,g=a.eventSystemFlags;0===c&&(g|=64);for(var h=null,m=0;m<jc.length;m++){var n=jc[m];n&&(n=n.extractEvents(d,b,f,e,g))&&(h=jb(h,n))}pc(h)}}function Md(a,
+b,c){if(!c.has(a)){switch(a){case "scroll":Cb(b,"scroll",!0);break;case "focus":case "blur":Cb(b,"focus",!0);Cb(b,"blur",!0);c.set("blur",null);c.set("focus",null);break;case "cancel":case "close":Tf(a)&&Cb(b,a,!0);break;case "invalid":case "submit":case "reset":break;default:-1===Db.indexOf(a)&&w(a,b)}c.set(a,null)}}function xi(a,b){var c=Jd(b);Nd.forEach(function(a){Md(a,b,c)});yi.forEach(function(a){Md(a,b,c)})}function Od(a,b,c,d,e){return{blockedOn:a,topLevelType:b,eventSystemFlags:c|32,nativeEvent:e,
+container:d}}function Xf(a,b){switch(a){case "focus":case "blur":xa=null;break;case "dragenter":case "dragleave":ya=null;break;case "mouseover":case "mouseout":za=null;break;case "pointerover":case "pointerout":Eb.delete(b.pointerId);break;case "gotpointercapture":case "lostpointercapture":Fb.delete(b.pointerId)}}function Gb(a,b,c,d,e,f){if(null===a||a.nativeEvent!==f)return a=Od(b,c,d,e,f),null!==b&&(b=Hb(b),null!==b&&Yf(b)),a;a.eventSystemFlags|=d;return a}function zi(a,b,c,d,e){switch(b){case "focus":return xa=
+Gb(xa,a,b,c,d,e),!0;case "dragenter":return ya=Gb(ya,a,b,c,d,e),!0;case "mouseover":return za=Gb(za,a,b,c,d,e),!0;case "pointerover":var f=e.pointerId;Eb.set(f,Gb(Eb.get(f)||null,a,b,c,d,e));return!0;case "gotpointercapture":return f=e.pointerId,Fb.set(f,Gb(Fb.get(f)||null,a,b,c,d,e)),!0}return!1}function Ai(a){var b=Bb(a.target);if(null!==b){var c=Na(b);if(null!==c)if(b=c.tag,13===b){if(b=Qf(c),null!==b){a.blockedOn=b;Pd(a.priority,function(){Bi(c)});return}}else if(3===b&&c.stateNode.hydrate){a.blockedOn=
+3===c.tag?c.stateNode.containerInfo:null;return}}a.blockedOn=null}function rc(a){if(null!==a.blockedOn)return!1;var b=Qd(a.topLevelType,a.eventSystemFlags,a.container,a.nativeEvent);if(null!==b){var c=Hb(b);null!==c&&Yf(c);a.blockedOn=b;return!1}return!0}function Zf(a,b,c){rc(a)&&c.delete(b)}function Ci(){for(Rd=!1;0<fa.length;){var a=fa[0];if(null!==a.blockedOn){a=Hb(a.blockedOn);null!==a&&Di(a);break}var b=Qd(a.topLevelType,a.eventSystemFlags,a.container,a.nativeEvent);null!==b?a.blockedOn=b:fa.shift()}null!==
+xa&&rc(xa)&&(xa=null);null!==ya&&rc(ya)&&(ya=null);null!==za&&rc(za)&&(za=null);Eb.forEach(Zf);Fb.forEach(Zf)}function Ib(a,b){a.blockedOn===b&&(a.blockedOn=null,Rd||(Rd=!0,$f(ag,Ci)))}function bg(a){if(0<fa.length){Ib(fa[0],a);for(var b=1;b<fa.length;b++){var c=fa[b];c.blockedOn===a&&(c.blockedOn=null)}}null!==xa&&Ib(xa,a);null!==ya&&Ib(ya,a);null!==za&&Ib(za,a);b=function(b){return Ib(b,a)};Eb.forEach(b);Fb.forEach(b);for(b=0;b<Jb.length;b++)c=Jb[b],c.blockedOn===a&&(c.blockedOn=null);for(;0<Jb.length&&
+(b=Jb[0],null===b.blockedOn);)Ai(b),null===b.blockedOn&&Jb.shift()}function Sd(a,b){for(var c=0;c<a.length;c+=2){var d=a[c],e=a[c+1],f="on"+(e[0].toUpperCase()+e.slice(1));f={phasedRegistrationNames:{bubbled:f,captured:f+"Capture"},dependencies:[d],eventPriority:b};Td.set(d,b);cg.set(d,f);dg[e]=f}}function w(a,b){Cb(b,a,!1)}function Cb(a,b,c){var d=Td.get(b);switch(void 0===d?2:d){case 0:d=Ei.bind(null,b,1,a);break;case 1:d=Fi.bind(null,b,1,a);break;default:d=sc.bind(null,b,1,a)}c?a.addEventListener(b,
+d,!0):a.addEventListener(b,d,!1)}function Ei(a,b,c,d){Oa||vd();var e=sc,f=Oa;Oa=!0;try{eg(e,a,b,c,d)}finally{(Oa=f)||ud()}}function Fi(a,b,c,d){Gi(Hi,sc.bind(null,a,b,c,d))}function sc(a,b,c,d){if(tc)if(0<fa.length&&-1<Nd.indexOf(a))a=Od(null,a,b,c,d),fa.push(a);else{var e=Qd(a,b,c,d);if(null===e)Xf(a,d);else if(-1<Nd.indexOf(a))a=Od(e,a,b,c,d),fa.push(a);else if(!zi(e,a,b,c,d)){Xf(a,d);a=Vf(a,d,null,b);try{uf(Wf,a)}finally{Uf(a)}}}}function Qd(a,b,c,d){c=Ld(d);c=Bb(c);if(null!==c){var e=Na(c);if(null===
+e)c=null;else{var f=e.tag;if(13===f){c=Qf(e);if(null!==c)return c;c=null}else if(3===f){if(e.stateNode.hydrate)return 3===e.tag?e.stateNode.containerInfo:null;c=null}else e!==c&&(c=null)}}a=Vf(a,d,c,b);try{uf(Wf,a)}finally{Uf(a)}return null}function fg(a,b,c){return null==b||"boolean"===typeof b||""===b?"":c||"number"!==typeof b||0===b||Kb.hasOwnProperty(a)&&Kb[a]?(""+b).trim():b+"px"}function gg(a,b){a=a.style;for(var c in b)if(b.hasOwnProperty(c)){var d=0===c.indexOf("--"),e=fg(c,b[c],d);"float"===
+c&&(c="cssFloat");d?a.setProperty(c,e):a[c]=e}}function Ud(a,b){if(b){if(Ii[a]&&(null!=b.children||null!=b.dangerouslySetInnerHTML))throw Error(k(137,a,""));if(null!=b.dangerouslySetInnerHTML){if(null!=b.children)throw Error(k(60));if(!("object"===typeof b.dangerouslySetInnerHTML&&"__html"in b.dangerouslySetInnerHTML))throw Error(k(61));}if(null!=b.style&&"object"!==typeof b.style)throw Error(k(62,""));}}function Vd(a,b){if(-1===a.indexOf("-"))return"string"===typeof b.is;switch(a){case "annotation-xml":case "color-profile":case "font-face":case "font-face-src":case "font-face-uri":case "font-face-format":case "font-face-name":case "missing-glyph":return!1;
+default:return!0}}function oa(a,b){a=9===a.nodeType||11===a.nodeType?a:a.ownerDocument;var c=Jd(a);b=rd[b];for(var d=0;d<b.length;d++)Md(b[d],a,c)}function uc(){}function Wd(a){a=a||("undefined"!==typeof document?document:void 0);if("undefined"===typeof a)return null;try{return a.activeElement||a.body}catch(b){return a.body}}function hg(a){for(;a&&a.firstChild;)a=a.firstChild;return a}function ig(a,b){var c=hg(a);a=0;for(var d;c;){if(3===c.nodeType){d=a+c.textContent.length;if(a<=b&&d>=b)return{node:c,
+offset:b-a};a=d}a:{for(;c;){if(c.nextSibling){c=c.nextSibling;break a}c=c.parentNode}c=void 0}c=hg(c)}}function jg(a,b){return a&&b?a===b?!0:a&&3===a.nodeType?!1:b&&3===b.nodeType?jg(a,b.parentNode):"contains"in a?a.contains(b):a.compareDocumentPosition?!!(a.compareDocumentPosition(b)&16):!1:!1}function kg(){for(var a=window,b=Wd();b instanceof a.HTMLIFrameElement;){try{var c="string"===typeof b.contentWindow.location.href}catch(d){c=!1}if(c)a=b.contentWindow;else break;b=Wd(a.document)}return b}
+function Xd(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return b&&("input"===b&&("text"===a.type||"search"===a.type||"tel"===a.type||"url"===a.type||"password"===a.type)||"textarea"===b||"true"===a.contentEditable)}function lg(a,b){switch(a){case "button":case "input":case "select":case "textarea":return!!b.autoFocus}return!1}function Yd(a,b){return"textarea"===a||"option"===a||"noscript"===a||"string"===typeof b.children||"number"===typeof b.children||"object"===typeof b.dangerouslySetInnerHTML&&
+null!==b.dangerouslySetInnerHTML&&null!=b.dangerouslySetInnerHTML.__html}function kb(a){for(;null!=a;a=a.nextSibling){var b=a.nodeType;if(1===b||3===b)break}return a}function mg(a){a=a.previousSibling;for(var b=0;a;){if(8===a.nodeType){var c=a.data;if(c===ng||c===Zd||c===$d){if(0===b)return a;b--}else c===og&&b++}a=a.previousSibling}return null}function Bb(a){var b=a[Aa];if(b)return b;for(var c=a.parentNode;c;){if(b=c[Lb]||c[Aa]){c=b.alternate;if(null!==b.child||null!==c&&null!==c.child)for(a=mg(a);null!==
+a;){if(c=a[Aa])return c;a=mg(a)}return b}a=c;c=a.parentNode}return null}function Hb(a){a=a[Aa]||a[Lb];return!a||5!==a.tag&&6!==a.tag&&13!==a.tag&&3!==a.tag?null:a}function Pa(a){if(5===a.tag||6===a.tag)return a.stateNode;throw Error(k(33));}function ae(a){return a[vc]||null}function pa(a){do a=a.return;while(a&&5!==a.tag);return a?a:null}function pg(a,b){var c=a.stateNode;if(!c)return null;var d=td(c);if(!d)return null;c=d[b];a:switch(b){case "onClick":case "onClickCapture":case "onDoubleClick":case "onDoubleClickCapture":case "onMouseDown":case "onMouseDownCapture":case "onMouseMove":case "onMouseMoveCapture":case "onMouseUp":case "onMouseUpCapture":case "onMouseEnter":(d=
+!d.disabled)||(a=a.type,d=!("button"===a||"input"===a||"select"===a||"textarea"===a));a=!d;break a;default:a=!1}if(a)return null;if(c&&"function"!==typeof c)throw Error(k(231,b,typeof c));return c}function qg(a,b,c){if(b=pg(a,c.dispatchConfig.phasedRegistrationNames[b]))c._dispatchListeners=jb(c._dispatchListeners,b),c._dispatchInstances=jb(c._dispatchInstances,a)}function Ji(a){if(a&&a.dispatchConfig.phasedRegistrationNames){for(var b=a._targetInst,c=[];b;)c.push(b),b=pa(b);for(b=c.length;0<b--;)qg(c[b],
+"captured",a);for(b=0;b<c.length;b++)qg(c[b],"bubbled",a)}}function be(a,b,c){a&&c&&c.dispatchConfig.registrationName&&(b=pg(a,c.dispatchConfig.registrationName))&&(c._dispatchListeners=jb(c._dispatchListeners,b),c._dispatchInstances=jb(c._dispatchInstances,a))}function Ki(a){a&&a.dispatchConfig.registrationName&&be(a._targetInst,null,a)}function lb(a){Kd(a,Ji)}function rg(){if(wc)return wc;var a,b=ce,c=b.length,d,e="value"in Ba?Ba.value:Ba.textContent,f=e.length;for(a=0;a<c&&b[a]===e[a];a++);var g=
+c-a;for(d=1;d<=g&&b[c-d]===e[f-d];d++);return wc=e.slice(a,1<d?1-d:void 0)}function xc(){return!0}function yc(){return!1}function R(a,b,c,d){this.dispatchConfig=a;this._targetInst=b;this.nativeEvent=c;a=this.constructor.Interface;for(var e in a)a.hasOwnProperty(e)&&((b=a[e])?this[e]=b(c):"target"===e?this.target=d:this[e]=c[e]);this.isDefaultPrevented=(null!=c.defaultPrevented?c.defaultPrevented:!1===c.returnValue)?xc:yc;this.isPropagationStopped=yc;return this}function Li(a,b,c,d){if(this.eventPool.length){var e=
+this.eventPool.pop();this.call(e,a,b,c,d);return e}return new this(a,b,c,d)}function Mi(a){if(!(a instanceof this))throw Error(k(279));a.destructor();10>this.eventPool.length&&this.eventPool.push(a)}function sg(a){a.eventPool=[];a.getPooled=Li;a.release=Mi}function tg(a,b){switch(a){case "keyup":return-1!==Ni.indexOf(b.keyCode);case "keydown":return 229!==b.keyCode;case "keypress":case "mousedown":case "blur":return!0;default:return!1}}function ug(a){a=a.detail;return"object"===typeof a&&"data"in
+a?a.data:null}function Oi(a,b){switch(a){case "compositionend":return ug(b);case "keypress":if(32!==b.which)return null;vg=!0;return wg;case "textInput":return a=b.data,a===wg&&vg?null:a;default:return null}}function Pi(a,b){if(mb)return"compositionend"===a||!de&&tg(a,b)?(a=rg(),wc=ce=Ba=null,mb=!1,a):null;switch(a){case "paste":return null;case "keypress":if(!(b.ctrlKey||b.altKey||b.metaKey)||b.ctrlKey&&b.altKey){if(b.char&&1<b.char.length)return b.char;if(b.which)return String.fromCharCode(b.which)}return null;
+case "compositionend":return xg&&"ko"!==b.locale?null:b.data;default:return null}}function yg(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return"input"===b?!!Qi[a.type]:"textarea"===b?!0:!1}function zg(a,b,c){a=R.getPooled(Ag.change,a,b,c);a.type="change";sf(c);lb(a);return a}function Ri(a){pc(a)}function zc(a){var b=Pa(a);if(Gf(b))return a}function Si(a,b){if("change"===a)return b}function Bg(){Mb&&(Mb.detachEvent("onpropertychange",Cg),Nb=Mb=null)}function Cg(a){if("value"===a.propertyName&&
+zc(Nb))if(a=zg(Nb,a,Ld(a)),Oa)pc(a);else{Oa=!0;try{ee(Ri,a)}finally{Oa=!1,ud()}}}function Ti(a,b,c){"focus"===a?(Bg(),Mb=b,Nb=c,Mb.attachEvent("onpropertychange",Cg)):"blur"===a&&Bg()}function Ui(a,b){if("selectionchange"===a||"keyup"===a||"keydown"===a)return zc(Nb)}function Vi(a,b){if("click"===a)return zc(b)}function Wi(a,b){if("input"===a||"change"===a)return zc(b)}function Xi(a){var b=this.nativeEvent;return b.getModifierState?b.getModifierState(a):(a=Yi[a])?!!b[a]:!1}function fe(a){return Xi}
+function Zi(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}function Ob(a,b){if(Qa(a,b))return!0;if("object"!==typeof a||null===a||"object"!==typeof b||null===b)return!1;var c=Object.keys(a),d=Object.keys(b);if(c.length!==d.length)return!1;for(d=0;d<c.length;d++)if(!$i.call(b,c[d])||!Qa(a[c[d]],b[c[d]]))return!1;return!0}function Dg(a,b){var c=b.window===b?b.document:9===b.nodeType?b:b.ownerDocument;if(ge||null==nb||nb!==Wd(c))return null;c=nb;"selectionStart"in c&&Xd(c)?c={start:c.selectionStart,
+end:c.selectionEnd}:(c=(c.ownerDocument&&c.ownerDocument.defaultView||window).getSelection(),c={anchorNode:c.anchorNode,anchorOffset:c.anchorOffset,focusNode:c.focusNode,focusOffset:c.focusOffset});return Pb&&Ob(Pb,c)?null:(Pb=c,a=R.getPooled(Eg.select,he,a,b),a.type="select",a.target=nb,lb(a),a)}function Ac(a){var b=a.keyCode;"charCode"in a?(a=a.charCode,0===a&&13===b&&(a=13)):a=b;10===a&&(a=13);return 32<=a||13===a?a:0}function q(a,b){0>ob||(a.current=ie[ob],ie[ob]=null,ob--)}function y(a,b,c){ob++;
+ie[ob]=a.current;a.current=b}function pb(a,b){var c=a.type.contextTypes;if(!c)return Ca;var d=a.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===b)return d.__reactInternalMemoizedMaskedChildContext;var e={},f;for(f in c)e[f]=b[f];d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=b,a.__reactInternalMemoizedMaskedChildContext=e);return e}function N(a){a=a.childContextTypes;return null!==a&&void 0!==a}function Fg(a,b,c){if(B.current!==Ca)throw Error(k(168));y(B,b);y(G,c)}
+function Gg(a,b,c){var d=a.stateNode;a=b.childContextTypes;if("function"!==typeof d.getChildContext)return c;d=d.getChildContext();for(var e in d)if(!(e in a))throw Error(k(108,na(b)||"Unknown",e));return M({},c,{},d)}function Bc(a){a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||Ca;Ra=B.current;y(B,a);y(G,G.current);return!0}function Hg(a,b,c){var d=a.stateNode;if(!d)throw Error(k(169));c?(a=Gg(a,b,Ra),d.__reactInternalMemoizedMergedChildContext=a,q(G),q(B),y(B,a)):q(G);y(G,c)}function Cc(){switch(aj()){case Dc:return 99;
+case Ig:return 98;case Jg:return 97;case Kg:return 96;case Lg:return 95;default:throw Error(k(332));}}function Mg(a){switch(a){case 99:return Dc;case 98:return Ig;case 97:return Jg;case 96:return Kg;case 95:return Lg;default:throw Error(k(332));}}function Da(a,b){a=Mg(a);return bj(a,b)}function Ng(a,b,c){a=Mg(a);return je(a,b,c)}function Og(a){null===qa?(qa=[a],Ec=je(Dc,Pg)):qa.push(a);return Qg}function ha(){if(null!==Ec){var a=Ec;Ec=null;Rg(a)}Pg()}function Pg(){if(!ke&&null!==qa){ke=!0;var a=0;
+try{var b=qa;Da(99,function(){for(;a<b.length;a++){var c=b[a];do c=c(!0);while(null!==c)}});qa=null}catch(c){throw null!==qa&&(qa=qa.slice(a+1)),je(Dc,ha),c;}finally{ke=!1}}}function Fc(a,b,c){c/=10;return 1073741821-(((1073741821-a+b/10)/c|0)+1)*c}function aa(a,b){if(a&&a.defaultProps){b=M({},b);a=a.defaultProps;for(var c in a)void 0===b[c]&&(b[c]=a[c])}return b}function le(){Gc=qb=Hc=null}function me(a){var b=Ic.current;q(Ic);a.type._context._currentValue=b}function Sg(a,b){for(;null!==a;){var c=
+a.alternate;if(a.childExpirationTime<b)a.childExpirationTime=b,null!==c&&c.childExpirationTime<b&&(c.childExpirationTime=b);else if(null!==c&&c.childExpirationTime<b)c.childExpirationTime=b;else break;a=a.return}}function rb(a,b){Hc=a;Gc=qb=null;a=a.dependencies;null!==a&&null!==a.firstContext&&(a.expirationTime>=b&&(ia=!0),a.firstContext=null)}function W(a,b){if(Gc!==a&&!1!==b&&0!==b){if("number"!==typeof b||1073741823===b)Gc=a,b=1073741823;b={context:a,observedBits:b,next:null};if(null===qb){if(null===
+Hc)throw Error(k(308));qb=b;Hc.dependencies={expirationTime:0,firstContext:b,responders:null}}else qb=qb.next=b}return a._currentValue}function ne(a){a.updateQueue={baseState:a.memoizedState,baseQueue:null,shared:{pending:null},effects:null}}function oe(a,b){a=a.updateQueue;b.updateQueue===a&&(b.updateQueue={baseState:a.baseState,baseQueue:a.baseQueue,shared:a.shared,effects:a.effects})}function Ea(a,b){a={expirationTime:a,suspenseConfig:b,tag:Tg,payload:null,callback:null,next:null};return a.next=
+a}function Fa(a,b){a=a.updateQueue;if(null!==a){a=a.shared;var c=a.pending;null===c?b.next=b:(b.next=c.next,c.next=b);a.pending=b}}function Ug(a,b){var c=a.alternate;null!==c&&oe(c,a);a=a.updateQueue;c=a.baseQueue;null===c?(a.baseQueue=b.next=b,b.next=b):(b.next=c.next,c.next=b)}function Qb(a,b,c,d){var e=a.updateQueue;Ga=!1;var f=e.baseQueue,g=e.shared.pending;if(null!==g){if(null!==f){var h=f.next;f.next=g.next;g.next=h}f=g;e.shared.pending=null;h=a.alternate;null!==h&&(h=h.updateQueue,null!==h&&
+(h.baseQueue=g))}if(null!==f){h=f.next;var m=e.baseState,n=0,k=null,ba=null,l=null;if(null!==h){var p=h;do{g=p.expirationTime;if(g<d){var t={expirationTime:p.expirationTime,suspenseConfig:p.suspenseConfig,tag:p.tag,payload:p.payload,callback:p.callback,next:null};null===l?(ba=l=t,k=m):l=l.next=t;g>n&&(n=g)}else{null!==l&&(l=l.next={expirationTime:1073741823,suspenseConfig:p.suspenseConfig,tag:p.tag,payload:p.payload,callback:p.callback,next:null});Vg(g,p.suspenseConfig);a:{var q=a,r=p;g=b;t=c;switch(r.tag){case 1:q=
+r.payload;if("function"===typeof q){m=q.call(t,m,g);break a}m=q;break a;case 3:q.effectTag=q.effectTag&-4097|64;case Tg:q=r.payload;g="function"===typeof q?q.call(t,m,g):q;if(null===g||void 0===g)break a;m=M({},m,g);break a;case Jc:Ga=!0}}null!==p.callback&&(a.effectTag|=32,g=e.effects,null===g?e.effects=[p]:g.push(p))}p=p.next;if(null===p||p===h)if(g=e.shared.pending,null===g)break;else p=f.next=g.next,g.next=h,e.baseQueue=f=g,e.shared.pending=null}while(1)}null===l?k=m:l.next=ba;e.baseState=k;e.baseQueue=
+l;Kc(n);a.expirationTime=n;a.memoizedState=m}}function Wg(a,b,c){a=b.effects;b.effects=null;if(null!==a)for(b=0;b<a.length;b++){var d=a[b],e=d.callback;if(null!==e){d.callback=null;d=e;e=c;if("function"!==typeof d)throw Error(k(191,d));d.call(e)}}}function Lc(a,b,c,d){b=a.memoizedState;c=c(d,b);c=null===c||void 0===c?b:M({},b,c);a.memoizedState=c;0===a.expirationTime&&(a.updateQueue.baseState=c)}function Xg(a,b,c,d,e,f,g){a=a.stateNode;return"function"===typeof a.shouldComponentUpdate?a.shouldComponentUpdate(d,
+f,g):b.prototype&&b.prototype.isPureReactComponent?!Ob(c,d)||!Ob(e,f):!0}function Yg(a,b,c){var d=!1,e=Ca;var f=b.contextType;"object"===typeof f&&null!==f?f=W(f):(e=N(b)?Ra:B.current,d=b.contextTypes,f=(d=null!==d&&void 0!==d)?pb(a,e):Ca);b=new b(c,f);a.memoizedState=null!==b.state&&void 0!==b.state?b.state:null;b.updater=Mc;a.stateNode=b;b._reactInternalFiber=a;d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=e,a.__reactInternalMemoizedMaskedChildContext=f);return b}function Zg(a,
+b,c,d){a=b.state;"function"===typeof b.componentWillReceiveProps&&b.componentWillReceiveProps(c,d);"function"===typeof b.UNSAFE_componentWillReceiveProps&&b.UNSAFE_componentWillReceiveProps(c,d);b.state!==a&&Mc.enqueueReplaceState(b,b.state,null)}function pe(a,b,c,d){var e=a.stateNode;e.props=c;e.state=a.memoizedState;e.refs=$g;ne(a);var f=b.contextType;"object"===typeof f&&null!==f?e.context=W(f):(f=N(b)?Ra:B.current,e.context=pb(a,f));Qb(a,c,e,d);e.state=a.memoizedState;f=b.getDerivedStateFromProps;
+"function"===typeof f&&(Lc(a,b,f,c),e.state=a.memoizedState);"function"===typeof b.getDerivedStateFromProps||"function"===typeof e.getSnapshotBeforeUpdate||"function"!==typeof e.UNSAFE_componentWillMount&&"function"!==typeof e.componentWillMount||(b=e.state,"function"===typeof e.componentWillMount&&e.componentWillMount(),"function"===typeof e.UNSAFE_componentWillMount&&e.UNSAFE_componentWillMount(),b!==e.state&&Mc.enqueueReplaceState(e,e.state,null),Qb(a,c,e,d),e.state=a.memoizedState);"function"===
+typeof e.componentDidMount&&(a.effectTag|=4)}function Rb(a,b,c){a=c.ref;if(null!==a&&"function"!==typeof a&&"object"!==typeof a){if(c._owner){c=c._owner;if(c){if(1!==c.tag)throw Error(k(309));var d=c.stateNode}if(!d)throw Error(k(147,a));var e=""+a;if(null!==b&&null!==b.ref&&"function"===typeof b.ref&&b.ref._stringRef===e)return b.ref;b=function(a){var b=d.refs;b===$g&&(b=d.refs={});null===a?delete b[e]:b[e]=a};b._stringRef=e;return b}if("string"!==typeof a)throw Error(k(284));if(!c._owner)throw Error(k(290,
+a));}return a}function Nc(a,b){if("textarea"!==a.type)throw Error(k(31,"[object Object]"===Object.prototype.toString.call(b)?"object with keys {"+Object.keys(b).join(", ")+"}":b,""));}function ah(a){function b(b,c){if(a){var d=b.lastEffect;null!==d?(d.nextEffect=c,b.lastEffect=c):b.firstEffect=b.lastEffect=c;c.nextEffect=null;c.effectTag=8}}function c(c,d){if(!a)return null;for(;null!==d;)b(c,d),d=d.sibling;return null}function d(a,b){for(a=new Map;null!==b;)null!==b.key?a.set(b.key,b):a.set(b.index,
+b),b=b.sibling;return a}function e(a,b){a=Sa(a,b);a.index=0;a.sibling=null;return a}function f(b,c,d){b.index=d;if(!a)return c;d=b.alternate;if(null!==d)return d=d.index,d<c?(b.effectTag=2,c):d;b.effectTag=2;return c}function g(b){a&&null===b.alternate&&(b.effectTag=2);return b}function h(a,b,c,d){if(null===b||6!==b.tag)return b=qe(c,a.mode,d),b.return=a,b;b=e(b,c);b.return=a;return b}function m(a,b,c,d){if(null!==b&&b.elementType===c.type)return d=e(b,c.props),d.ref=Rb(a,b,c),d.return=a,d;d=Oc(c.type,
+c.key,c.props,null,a.mode,d);d.ref=Rb(a,b,c);d.return=a;return d}function n(a,b,c,d){if(null===b||4!==b.tag||b.stateNode.containerInfo!==c.containerInfo||b.stateNode.implementation!==c.implementation)return b=re(c,a.mode,d),b.return=a,b;b=e(b,c.children||[]);b.return=a;return b}function l(a,b,c,d,f){if(null===b||7!==b.tag)return b=Ha(c,a.mode,d,f),b.return=a,b;b=e(b,c);b.return=a;return b}function ba(a,b,c){if("string"===typeof b||"number"===typeof b)return b=qe(""+b,a.mode,c),b.return=a,b;if("object"===
+typeof b&&null!==b){switch(b.$$typeof){case Pc:return c=Oc(b.type,b.key,b.props,null,a.mode,c),c.ref=Rb(a,null,b),c.return=a,c;case gb:return b=re(b,a.mode,c),b.return=a,b}if(Qc(b)||zb(b))return b=Ha(b,a.mode,c,null),b.return=a,b;Nc(a,b)}return null}function p(a,b,c,d){var e=null!==b?b.key:null;if("string"===typeof c||"number"===typeof c)return null!==e?null:h(a,b,""+c,d);if("object"===typeof c&&null!==c){switch(c.$$typeof){case Pc:return c.key===e?c.type===Ma?l(a,b,c.props.children,d,e):m(a,b,c,
+d):null;case gb:return c.key===e?n(a,b,c,d):null}if(Qc(c)||zb(c))return null!==e?null:l(a,b,c,d,null);Nc(a,c)}return null}function t(a,b,c,d,e){if("string"===typeof d||"number"===typeof d)return a=a.get(c)||null,h(b,a,""+d,e);if("object"===typeof d&&null!==d){switch(d.$$typeof){case Pc:return a=a.get(null===d.key?c:d.key)||null,d.type===Ma?l(b,a,d.props.children,e,d.key):m(b,a,d,e);case gb:return a=a.get(null===d.key?c:d.key)||null,n(b,a,d,e)}if(Qc(d)||zb(d))return a=a.get(c)||null,l(b,a,d,e,null);
+Nc(b,d)}return null}function q(e,g,h,m){for(var n=null,k=null,l=g,r=g=0,C=null;null!==l&&r<h.length;r++){l.index>r?(C=l,l=null):C=l.sibling;var O=p(e,l,h[r],m);if(null===O){null===l&&(l=C);break}a&&l&&null===O.alternate&&b(e,l);g=f(O,g,r);null===k?n=O:k.sibling=O;k=O;l=C}if(r===h.length)return c(e,l),n;if(null===l){for(;r<h.length;r++)l=ba(e,h[r],m),null!==l&&(g=f(l,g,r),null===k?n=l:k.sibling=l,k=l);return n}for(l=d(e,l);r<h.length;r++)C=t(l,e,r,h[r],m),null!==C&&(a&&null!==C.alternate&&l.delete(null===
+C.key?r:C.key),g=f(C,g,r),null===k?n=C:k.sibling=C,k=C);a&&l.forEach(function(a){return b(e,a)});return n}function w(e,g,h,n){var m=zb(h);if("function"!==typeof m)throw Error(k(150));h=m.call(h);if(null==h)throw Error(k(151));for(var l=m=null,r=g,C=g=0,O=null,v=h.next();null!==r&&!v.done;C++,v=h.next()){r.index>C?(O=r,r=null):O=r.sibling;var q=p(e,r,v.value,n);if(null===q){null===r&&(r=O);break}a&&r&&null===q.alternate&&b(e,r);g=f(q,g,C);null===l?m=q:l.sibling=q;l=q;r=O}if(v.done)return c(e,r),m;
+if(null===r){for(;!v.done;C++,v=h.next())v=ba(e,v.value,n),null!==v&&(g=f(v,g,C),null===l?m=v:l.sibling=v,l=v);return m}for(r=d(e,r);!v.done;C++,v=h.next())v=t(r,e,C,v.value,n),null!==v&&(a&&null!==v.alternate&&r.delete(null===v.key?C:v.key),g=f(v,g,C),null===l?m=v:l.sibling=v,l=v);a&&r.forEach(function(a){return b(e,a)});return m}return function(a,d,f,h){var m="object"===typeof f&&null!==f&&f.type===Ma&&null===f.key;m&&(f=f.props.children);var n="object"===typeof f&&null!==f;if(n)switch(f.$$typeof){case Pc:a:{n=
+f.key;for(m=d;null!==m;){if(m.key===n){switch(m.tag){case 7:if(f.type===Ma){c(a,m.sibling);d=e(m,f.props.children);d.return=a;a=d;break a}break;default:if(m.elementType===f.type){c(a,m.sibling);d=e(m,f.props);d.ref=Rb(a,m,f);d.return=a;a=d;break a}}c(a,m);break}else b(a,m);m=m.sibling}f.type===Ma?(d=Ha(f.props.children,a.mode,h,f.key),d.return=a,a=d):(h=Oc(f.type,f.key,f.props,null,a.mode,h),h.ref=Rb(a,d,f),h.return=a,a=h)}return g(a);case gb:a:{for(m=f.key;null!==d;){if(d.key===m)if(4===d.tag&&d.stateNode.containerInfo===
+f.containerInfo&&d.stateNode.implementation===f.implementation){c(a,d.sibling);d=e(d,f.children||[]);d.return=a;a=d;break a}else{c(a,d);break}else b(a,d);d=d.sibling}d=re(f,a.mode,h);d.return=a;a=d}return g(a)}if("string"===typeof f||"number"===typeof f)return f=""+f,null!==d&&6===d.tag?(c(a,d.sibling),d=e(d,f),d.return=a,a=d):(c(a,d),d=qe(f,a.mode,h),d.return=a,a=d),g(a);if(Qc(f))return q(a,d,f,h);if(zb(f))return w(a,d,f,h);n&&Nc(a,f);if("undefined"===typeof f&&!m)switch(a.tag){case 1:case 0:throw a=
+a.type,Error(k(152,a.displayName||a.name||"Component"));}return c(a,d)}}function Ta(a){if(a===Sb)throw Error(k(174));return a}function se(a,b){y(Tb,b);y(Ub,a);y(ja,Sb);a=b.nodeType;switch(a){case 9:case 11:b=(b=b.documentElement)?b.namespaceURI:Hd(null,"");break;default:a=8===a?b.parentNode:b,b=a.namespaceURI||null,a=a.tagName,b=Hd(b,a)}q(ja);y(ja,b)}function tb(a){q(ja);q(Ub);q(Tb)}function bh(a){Ta(Tb.current);var b=Ta(ja.current);var c=Hd(b,a.type);b!==c&&(y(Ub,a),y(ja,c))}function te(a){Ub.current===
+a&&(q(ja),q(Ub))}function Rc(a){for(var b=a;null!==b;){if(13===b.tag){var c=b.memoizedState;if(null!==c&&(c=c.dehydrated,null===c||c.data===$d||c.data===Zd))return b}else if(19===b.tag&&void 0!==b.memoizedProps.revealOrder){if(0!==(b.effectTag&64))return b}else if(null!==b.child){b.child.return=b;b=b.child;continue}if(b===a)break;for(;null===b.sibling;){if(null===b.return||b.return===a)return null;b=b.return}b.sibling.return=b.return;b=b.sibling}return null}function ue(a,b){return{responder:a,props:b}}
+function S(){throw Error(k(321));}function ve(a,b){if(null===b)return!1;for(var c=0;c<b.length&&c<a.length;c++)if(!Qa(a[c],b[c]))return!1;return!0}function we(a,b,c,d,e,f){Ia=f;z=b;b.memoizedState=null;b.updateQueue=null;b.expirationTime=0;Sc.current=null===a||null===a.memoizedState?dj:ej;a=c(d,e);if(b.expirationTime===Ia){f=0;do{b.expirationTime=0;if(!(25>f))throw Error(k(301));f+=1;J=K=null;b.updateQueue=null;Sc.current=fj;a=c(d,e)}while(b.expirationTime===Ia)}Sc.current=Tc;b=null!==K&&null!==K.next;
+Ia=0;J=K=z=null;Uc=!1;if(b)throw Error(k(300));return a}function ub(){var a={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};null===J?z.memoizedState=J=a:J=J.next=a;return J}function vb(){if(null===K){var a=z.alternate;a=null!==a?a.memoizedState:null}else a=K.next;var b=null===J?z.memoizedState:J.next;if(null!==b)J=b,K=a;else{if(null===a)throw Error(k(310));K=a;a={memoizedState:K.memoizedState,baseState:K.baseState,baseQueue:K.baseQueue,queue:K.queue,next:null};null===J?z.memoizedState=
+J=a:J=J.next=a}return J}function Ua(a,b){return"function"===typeof b?b(a):b}function Vc(a,b,c){b=vb();c=b.queue;if(null===c)throw Error(k(311));c.lastRenderedReducer=a;var d=K,e=d.baseQueue,f=c.pending;if(null!==f){if(null!==e){var g=e.next;e.next=f.next;f.next=g}d.baseQueue=e=f;c.pending=null}if(null!==e){e=e.next;d=d.baseState;var h=g=f=null,m=e;do{var n=m.expirationTime;if(n<Ia){var l={expirationTime:m.expirationTime,suspenseConfig:m.suspenseConfig,action:m.action,eagerReducer:m.eagerReducer,eagerState:m.eagerState,
+next:null};null===h?(g=h=l,f=d):h=h.next=l;n>z.expirationTime&&(z.expirationTime=n,Kc(n))}else null!==h&&(h=h.next={expirationTime:1073741823,suspenseConfig:m.suspenseConfig,action:m.action,eagerReducer:m.eagerReducer,eagerState:m.eagerState,next:null}),Vg(n,m.suspenseConfig),d=m.eagerReducer===a?m.eagerState:a(d,m.action);m=m.next}while(null!==m&&m!==e);null===h?f=d:h.next=g;Qa(d,b.memoizedState)||(ia=!0);b.memoizedState=d;b.baseState=f;b.baseQueue=h;c.lastRenderedState=d}return[b.memoizedState,
+c.dispatch]}function Wc(a,b,c){b=vb();c=b.queue;if(null===c)throw Error(k(311));c.lastRenderedReducer=a;var d=c.dispatch,e=c.pending,f=b.memoizedState;if(null!==e){c.pending=null;var g=e=e.next;do f=a(f,g.action),g=g.next;while(g!==e);Qa(f,b.memoizedState)||(ia=!0);b.memoizedState=f;null===b.baseQueue&&(b.baseState=f);c.lastRenderedState=f}return[f,d]}function xe(a){var b=ub();"function"===typeof a&&(a=a());b.memoizedState=b.baseState=a;a=b.queue={pending:null,dispatch:null,lastRenderedReducer:Ua,
+lastRenderedState:a};a=a.dispatch=ch.bind(null,z,a);return[b.memoizedState,a]}function ye(a,b,c,d){a={tag:a,create:b,destroy:c,deps:d,next:null};b=z.updateQueue;null===b?(b={lastEffect:null},z.updateQueue=b,b.lastEffect=a.next=a):(c=b.lastEffect,null===c?b.lastEffect=a.next=a:(d=c.next,c.next=a,a.next=d,b.lastEffect=a));return a}function dh(a){return vb().memoizedState}function ze(a,b,c,d){var e=ub();z.effectTag|=a;e.memoizedState=ye(1|b,c,void 0,void 0===d?null:d)}function Ae(a,b,c,d){var e=vb();
+d=void 0===d?null:d;var f=void 0;if(null!==K){var g=K.memoizedState;f=g.destroy;if(null!==d&&ve(d,g.deps)){ye(b,c,f,d);return}}z.effectTag|=a;e.memoizedState=ye(1|b,c,f,d)}function eh(a,b){return ze(516,4,a,b)}function Xc(a,b){return Ae(516,4,a,b)}function fh(a,b){return Ae(4,2,a,b)}function gh(a,b){if("function"===typeof b)return a=a(),b(a),function(){b(null)};if(null!==b&&void 0!==b)return a=a(),b.current=a,function(){b.current=null}}function hh(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;
+return Ae(4,2,gh.bind(null,b,a),c)}function Be(a,b){}function ih(a,b){ub().memoizedState=[a,void 0===b?null:b];return a}function Yc(a,b){var c=vb();b=void 0===b?null:b;var d=c.memoizedState;if(null!==d&&null!==b&&ve(b,d[1]))return d[0];c.memoizedState=[a,b];return a}function jh(a,b){var c=vb();b=void 0===b?null:b;var d=c.memoizedState;if(null!==d&&null!==b&&ve(b,d[1]))return d[0];a=a();c.memoizedState=[a,b];return a}function Ce(a,b,c){var d=Cc();Da(98>d?98:d,function(){a(!0)});Da(97<d?97:d,function(){var d=
+X.suspense;X.suspense=void 0===b?null:b;try{a(!1),c()}finally{X.suspense=d}})}function ch(a,b,c){var d=ka(),e=Vb.suspense;d=Va(d,a,e);e={expirationTime:d,suspenseConfig:e,action:c,eagerReducer:null,eagerState:null,next:null};var f=b.pending;null===f?e.next=e:(e.next=f.next,f.next=e);b.pending=e;f=a.alternate;if(a===z||null!==f&&f===z)Uc=!0,e.expirationTime=Ia,z.expirationTime=Ia;else{if(0===a.expirationTime&&(null===f||0===f.expirationTime)&&(f=b.lastRenderedReducer,null!==f))try{var g=b.lastRenderedState,
+h=f(g,c);e.eagerReducer=f;e.eagerState=h;if(Qa(h,g))return}catch(m){}finally{}Ja(a,d)}}function kh(a,b){var c=la(5,null,null,0);c.elementType="DELETED";c.type="DELETED";c.stateNode=b;c.return=a;c.effectTag=8;null!==a.lastEffect?(a.lastEffect.nextEffect=c,a.lastEffect=c):a.firstEffect=a.lastEffect=c}function lh(a,b){switch(a.tag){case 5:var c=a.type;b=1!==b.nodeType||c.toLowerCase()!==b.nodeName.toLowerCase()?null:b;return null!==b?(a.stateNode=b,!0):!1;case 6:return b=""===a.pendingProps||3!==b.nodeType?
+null:b,null!==b?(a.stateNode=b,!0):!1;case 13:return!1;default:return!1}}function De(a){if(Wa){var b=Ka;if(b){var c=b;if(!lh(a,b)){b=kb(c.nextSibling);if(!b||!lh(a,b)){a.effectTag=a.effectTag&-1025|2;Wa=!1;ra=a;return}kh(ra,c)}ra=a;Ka=kb(b.firstChild)}else a.effectTag=a.effectTag&-1025|2,Wa=!1,ra=a}}function mh(a){for(a=a.return;null!==a&&5!==a.tag&&3!==a.tag&&13!==a.tag;)a=a.return;ra=a}function Zc(a){if(a!==ra)return!1;if(!Wa)return mh(a),Wa=!0,!1;var b=a.type;if(5!==a.tag||"head"!==b&&"body"!==
+b&&!Yd(b,a.memoizedProps))for(b=Ka;b;)kh(a,b),b=kb(b.nextSibling);mh(a);if(13===a.tag){a=a.memoizedState;a=null!==a?a.dehydrated:null;if(!a)throw Error(k(317));a:{a=a.nextSibling;for(b=0;a;){if(8===a.nodeType){var c=a.data;if(c===og){if(0===b){Ka=kb(a.nextSibling);break a}b--}else c!==ng&&c!==Zd&&c!==$d||b++}a=a.nextSibling}Ka=null}}else Ka=ra?kb(a.stateNode.nextSibling):null;return!0}function Ee(){Ka=ra=null;Wa=!1}function T(a,b,c,d){b.child=null===a?Fe(b,null,c,d):wb(b,a.child,c,d)}function nh(a,
+b,c,d,e){c=c.render;var f=b.ref;rb(b,e);d=we(a,b,c,d,f,e);if(null!==a&&!ia)return b.updateQueue=a.updateQueue,b.effectTag&=-517,a.expirationTime<=e&&(a.expirationTime=0),sa(a,b,e);b.effectTag|=1;T(a,b,d,e);return b.child}function oh(a,b,c,d,e,f){if(null===a){var g=c.type;if("function"===typeof g&&!Ge(g)&&void 0===g.defaultProps&&null===c.compare&&void 0===c.defaultProps)return b.tag=15,b.type=g,ph(a,b,g,d,e,f);a=Oc(c.type,null,d,null,b.mode,f);a.ref=b.ref;a.return=b;return b.child=a}g=a.child;if(e<
+f&&(e=g.memoizedProps,c=c.compare,c=null!==c?c:Ob,c(e,d)&&a.ref===b.ref))return sa(a,b,f);b.effectTag|=1;a=Sa(g,d);a.ref=b.ref;a.return=b;return b.child=a}function ph(a,b,c,d,e,f){return null!==a&&Ob(a.memoizedProps,d)&&a.ref===b.ref&&(ia=!1,e<f)?(b.expirationTime=a.expirationTime,sa(a,b,f)):He(a,b,c,d,f)}function qh(a,b){var c=b.ref;if(null===a&&null!==c||null!==a&&a.ref!==c)b.effectTag|=128}function He(a,b,c,d,e){var f=N(c)?Ra:B.current;f=pb(b,f);rb(b,e);c=we(a,b,c,d,f,e);if(null!==a&&!ia)return b.updateQueue=
+a.updateQueue,b.effectTag&=-517,a.expirationTime<=e&&(a.expirationTime=0),sa(a,b,e);b.effectTag|=1;T(a,b,c,e);return b.child}function rh(a,b,c,d,e){if(N(c)){var f=!0;Bc(b)}else f=!1;rb(b,e);if(null===b.stateNode)null!==a&&(a.alternate=null,b.alternate=null,b.effectTag|=2),Yg(b,c,d),pe(b,c,d,e),d=!0;else if(null===a){var g=b.stateNode,h=b.memoizedProps;g.props=h;var m=g.context,n=c.contextType;"object"===typeof n&&null!==n?n=W(n):(n=N(c)?Ra:B.current,n=pb(b,n));var l=c.getDerivedStateFromProps,k="function"===
+typeof l||"function"===typeof g.getSnapshotBeforeUpdate;k||"function"!==typeof g.UNSAFE_componentWillReceiveProps&&"function"!==typeof g.componentWillReceiveProps||(h!==d||m!==n)&&Zg(b,g,d,n);Ga=!1;var p=b.memoizedState;g.state=p;Qb(b,d,g,e);m=b.memoizedState;h!==d||p!==m||G.current||Ga?("function"===typeof l&&(Lc(b,c,l,d),m=b.memoizedState),(h=Ga||Xg(b,c,h,d,p,m,n))?(k||"function"!==typeof g.UNSAFE_componentWillMount&&"function"!==typeof g.componentWillMount||("function"===typeof g.componentWillMount&&
+g.componentWillMount(),"function"===typeof g.UNSAFE_componentWillMount&&g.UNSAFE_componentWillMount()),"function"===typeof g.componentDidMount&&(b.effectTag|=4)):("function"===typeof g.componentDidMount&&(b.effectTag|=4),b.memoizedProps=d,b.memoizedState=m),g.props=d,g.state=m,g.context=n,d=h):("function"===typeof g.componentDidMount&&(b.effectTag|=4),d=!1)}else g=b.stateNode,oe(a,b),h=b.memoizedProps,g.props=b.type===b.elementType?h:aa(b.type,h),m=g.context,n=c.contextType,"object"===typeof n&&null!==
+n?n=W(n):(n=N(c)?Ra:B.current,n=pb(b,n)),l=c.getDerivedStateFromProps,(k="function"===typeof l||"function"===typeof g.getSnapshotBeforeUpdate)||"function"!==typeof g.UNSAFE_componentWillReceiveProps&&"function"!==typeof g.componentWillReceiveProps||(h!==d||m!==n)&&Zg(b,g,d,n),Ga=!1,m=b.memoizedState,g.state=m,Qb(b,d,g,e),p=b.memoizedState,h!==d||m!==p||G.current||Ga?("function"===typeof l&&(Lc(b,c,l,d),p=b.memoizedState),(l=Ga||Xg(b,c,h,d,m,p,n))?(k||"function"!==typeof g.UNSAFE_componentWillUpdate&&
+"function"!==typeof g.componentWillUpdate||("function"===typeof g.componentWillUpdate&&g.componentWillUpdate(d,p,n),"function"===typeof g.UNSAFE_componentWillUpdate&&g.UNSAFE_componentWillUpdate(d,p,n)),"function"===typeof g.componentDidUpdate&&(b.effectTag|=4),"function"===typeof g.getSnapshotBeforeUpdate&&(b.effectTag|=256)):("function"!==typeof g.componentDidUpdate||h===a.memoizedProps&&m===a.memoizedState||(b.effectTag|=4),"function"!==typeof g.getSnapshotBeforeUpdate||h===a.memoizedProps&&m===
+a.memoizedState||(b.effectTag|=256),b.memoizedProps=d,b.memoizedState=p),g.props=d,g.state=p,g.context=n,d=l):("function"!==typeof g.componentDidUpdate||h===a.memoizedProps&&m===a.memoizedState||(b.effectTag|=4),"function"!==typeof g.getSnapshotBeforeUpdate||h===a.memoizedProps&&m===a.memoizedState||(b.effectTag|=256),d=!1);return Ie(a,b,c,d,f,e)}function Ie(a,b,c,d,e,f){qh(a,b);var g=0!==(b.effectTag&64);if(!d&&!g)return e&&Hg(b,c,!1),sa(a,b,f);d=b.stateNode;gj.current=b;var h=g&&"function"!==typeof c.getDerivedStateFromError?
+null:d.render();b.effectTag|=1;null!==a&&g?(b.child=wb(b,a.child,null,f),b.child=wb(b,null,h,f)):T(a,b,h,f);b.memoizedState=d.state;e&&Hg(b,c,!0);return b.child}function sh(a){var b=a.stateNode;b.pendingContext?Fg(a,b.pendingContext,b.pendingContext!==b.context):b.context&&Fg(a,b.context,!1);se(a,b.containerInfo)}function th(a,b,c){var d=b.mode,e=b.pendingProps,f=D.current,g=!1,h;(h=0!==(b.effectTag&64))||(h=0!==(f&2)&&(null===a||null!==a.memoizedState));h?(g=!0,b.effectTag&=-65):null!==a&&null===
+a.memoizedState||void 0===e.fallback||!0===e.unstable_avoidThisFallback||(f|=1);y(D,f&1);if(null===a){void 0!==e.fallback&&De(b);if(g){g=e.fallback;e=Ha(null,d,0,null);e.return=b;if(0===(b.mode&2))for(a=null!==b.memoizedState?b.child.child:b.child,e.child=a;null!==a;)a.return=e,a=a.sibling;c=Ha(g,d,c,null);c.return=b;e.sibling=c;b.memoizedState=Je;b.child=e;return c}d=e.children;b.memoizedState=null;return b.child=Fe(b,null,d,c)}if(null!==a.memoizedState){a=a.child;d=a.sibling;if(g){e=e.fallback;
+c=Sa(a,a.pendingProps);c.return=b;if(0===(b.mode&2)&&(g=null!==b.memoizedState?b.child.child:b.child,g!==a.child))for(c.child=g;null!==g;)g.return=c,g=g.sibling;d=Sa(d,e);d.return=b;c.sibling=d;c.childExpirationTime=0;b.memoizedState=Je;b.child=c;return d}c=wb(b,a.child,e.children,c);b.memoizedState=null;return b.child=c}a=a.child;if(g){g=e.fallback;e=Ha(null,d,0,null);e.return=b;e.child=a;null!==a&&(a.return=e);if(0===(b.mode&2))for(a=null!==b.memoizedState?b.child.child:b.child,e.child=a;null!==
+a;)a.return=e,a=a.sibling;c=Ha(g,d,c,null);c.return=b;e.sibling=c;c.effectTag|=2;e.childExpirationTime=0;b.memoizedState=Je;b.child=e;return c}b.memoizedState=null;return b.child=wb(b,a,e.children,c)}function uh(a,b){a.expirationTime<b&&(a.expirationTime=b);var c=a.alternate;null!==c&&c.expirationTime<b&&(c.expirationTime=b);Sg(a.return,b)}function Ke(a,b,c,d,e,f){var g=a.memoizedState;null===g?a.memoizedState={isBackwards:b,rendering:null,renderingStartTime:0,last:d,tail:c,tailExpiration:0,tailMode:e,
+lastEffect:f}:(g.isBackwards=b,g.rendering=null,g.renderingStartTime=0,g.last=d,g.tail=c,g.tailExpiration=0,g.tailMode=e,g.lastEffect=f)}function vh(a,b,c){var d=b.pendingProps,e=d.revealOrder,f=d.tail;T(a,b,d.children,c);d=D.current;if(0!==(d&2))d=d&1|2,b.effectTag|=64;else{if(null!==a&&0!==(a.effectTag&64))a:for(a=b.child;null!==a;){if(13===a.tag)null!==a.memoizedState&&uh(a,c);else if(19===a.tag)uh(a,c);else if(null!==a.child){a.child.return=a;a=a.child;continue}if(a===b)break a;for(;null===a.sibling;){if(null===
+a.return||a.return===b)break a;a=a.return}a.sibling.return=a.return;a=a.sibling}d&=1}y(D,d);if(0===(b.mode&2))b.memoizedState=null;else switch(e){case "forwards":c=b.child;for(e=null;null!==c;)a=c.alternate,null!==a&&null===Rc(a)&&(e=c),c=c.sibling;c=e;null===c?(e=b.child,b.child=null):(e=c.sibling,c.sibling=null);Ke(b,!1,e,c,f,b.lastEffect);break;case "backwards":c=null;e=b.child;for(b.child=null;null!==e;){a=e.alternate;if(null!==a&&null===Rc(a)){b.child=e;break}a=e.sibling;e.sibling=c;c=e;e=a}Ke(b,
+!0,c,null,f,b.lastEffect);break;case "together":Ke(b,!1,null,null,void 0,b.lastEffect);break;default:b.memoizedState=null}return b.child}function sa(a,b,c){null!==a&&(b.dependencies=a.dependencies);var d=b.expirationTime;0!==d&&Kc(d);if(b.childExpirationTime<c)return null;if(null!==a&&b.child!==a.child)throw Error(k(153));if(null!==b.child){a=b.child;c=Sa(a,a.pendingProps);b.child=c;for(c.return=b;null!==a.sibling;)a=a.sibling,c=c.sibling=Sa(a,a.pendingProps),c.return=b;c.sibling=null}return b.child}
+function $c(a,b){switch(a.tailMode){case "hidden":b=a.tail;for(var c=null;null!==b;)null!==b.alternate&&(c=b),b=b.sibling;null===c?a.tail=null:c.sibling=null;break;case "collapsed":c=a.tail;for(var d=null;null!==c;)null!==c.alternate&&(d=c),c=c.sibling;null===d?b||null===a.tail?a.tail=null:a.tail.sibling=null:d.sibling=null}}function hj(a,b,c){var d=b.pendingProps;switch(b.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return null;case 1:return N(b.type)&&(q(G),q(B)),
+null;case 3:return tb(),q(G),q(B),c=b.stateNode,c.pendingContext&&(c.context=c.pendingContext,c.pendingContext=null),null!==a&&null!==a.child||!Zc(b)||(b.effectTag|=4),wh(b),null;case 5:te(b);c=Ta(Tb.current);var e=b.type;if(null!==a&&null!=b.stateNode)ij(a,b,e,d,c),a.ref!==b.ref&&(b.effectTag|=128);else{if(!d){if(null===b.stateNode)throw Error(k(166));return null}a=Ta(ja.current);if(Zc(b)){d=b.stateNode;e=b.type;var f=b.memoizedProps;d[Aa]=b;d[vc]=f;switch(e){case "iframe":case "object":case "embed":w("load",
+d);break;case "video":case "audio":for(a=0;a<Db.length;a++)w(Db[a],d);break;case "source":w("error",d);break;case "img":case "image":case "link":w("error",d);w("load",d);break;case "form":w("reset",d);w("submit",d);break;case "details":w("toggle",d);break;case "input":Hf(d,f);w("invalid",d);oa(c,"onChange");break;case "select":d._wrapperState={wasMultiple:!!f.multiple};w("invalid",d);oa(c,"onChange");break;case "textarea":Kf(d,f),w("invalid",d),oa(c,"onChange")}Ud(e,f);a=null;for(var g in f)if(f.hasOwnProperty(g)){var h=
+f[g];"children"===g?"string"===typeof h?d.textContent!==h&&(a=["children",h]):"number"===typeof h&&d.textContent!==""+h&&(a=["children",""+h]):db.hasOwnProperty(g)&&null!=h&&oa(c,g)}switch(e){case "input":mc(d);Jf(d,f,!0);break;case "textarea":mc(d);Mf(d);break;case "select":case "option":break;default:"function"===typeof f.onClick&&(d.onclick=uc)}c=a;b.updateQueue=c;null!==c&&(b.effectTag|=4)}else{g=9===c.nodeType?c:c.ownerDocument;"http://www.w3.org/1999/xhtml"===a&&(a=Nf(e));"http://www.w3.org/1999/xhtml"===
+a?"script"===e?(a=g.createElement("div"),a.innerHTML="<script>\x3c/script>",a=a.removeChild(a.firstChild)):"string"===typeof d.is?a=g.createElement(e,{is:d.is}):(a=g.createElement(e),"select"===e&&(g=a,d.multiple?g.multiple=!0:d.size&&(g.size=d.size))):a=g.createElementNS(a,e);a[Aa]=b;a[vc]=d;jj(a,b,!1,!1);b.stateNode=a;g=Vd(e,d);switch(e){case "iframe":case "object":case "embed":w("load",a);h=d;break;case "video":case "audio":for(h=0;h<Db.length;h++)w(Db[h],a);h=d;break;case "source":w("error",a);
+h=d;break;case "img":case "image":case "link":w("error",a);w("load",a);h=d;break;case "form":w("reset",a);w("submit",a);h=d;break;case "details":w("toggle",a);h=d;break;case "input":Hf(a,d);h=Cd(a,d);w("invalid",a);oa(c,"onChange");break;case "option":h=Fd(a,d);break;case "select":a._wrapperState={wasMultiple:!!d.multiple};h=M({},d,{value:void 0});w("invalid",a);oa(c,"onChange");break;case "textarea":Kf(a,d);h=Gd(a,d);w("invalid",a);oa(c,"onChange");break;default:h=d}Ud(e,h);var m=h;for(f in m)if(m.hasOwnProperty(f)){var n=
+m[f];"style"===f?gg(a,n):"dangerouslySetInnerHTML"===f?(n=n?n.__html:void 0,null!=n&&xh(a,n)):"children"===f?"string"===typeof n?("textarea"!==e||""!==n)&&Wb(a,n):"number"===typeof n&&Wb(a,""+n):"suppressContentEditableWarning"!==f&&"suppressHydrationWarning"!==f&&"autoFocus"!==f&&(db.hasOwnProperty(f)?null!=n&&oa(c,f):null!=n&&xd(a,f,n,g))}switch(e){case "input":mc(a);Jf(a,d,!1);break;case "textarea":mc(a);Mf(a);break;case "option":null!=d.value&&a.setAttribute("value",""+va(d.value));break;case "select":a.multiple=
+!!d.multiple;c=d.value;null!=c?hb(a,!!d.multiple,c,!1):null!=d.defaultValue&&hb(a,!!d.multiple,d.defaultValue,!0);break;default:"function"===typeof h.onClick&&(a.onclick=uc)}lg(e,d)&&(b.effectTag|=4)}null!==b.ref&&(b.effectTag|=128)}return null;case 6:if(a&&null!=b.stateNode)kj(a,b,a.memoizedProps,d);else{if("string"!==typeof d&&null===b.stateNode)throw Error(k(166));c=Ta(Tb.current);Ta(ja.current);Zc(b)?(c=b.stateNode,d=b.memoizedProps,c[Aa]=b,c.nodeValue!==d&&(b.effectTag|=4)):(c=(9===c.nodeType?
+c:c.ownerDocument).createTextNode(d),c[Aa]=b,b.stateNode=c)}return null;case 13:q(D);d=b.memoizedState;if(0!==(b.effectTag&64))return b.expirationTime=c,b;c=null!==d;d=!1;null===a?void 0!==b.memoizedProps.fallback&&Zc(b):(e=a.memoizedState,d=null!==e,c||null===e||(e=a.child.sibling,null!==e&&(f=b.firstEffect,null!==f?(b.firstEffect=e,e.nextEffect=f):(b.firstEffect=b.lastEffect=e,e.nextEffect=null),e.effectTag=8)));if(c&&!d&&0!==(b.mode&2))if(null===a&&!0!==b.memoizedProps.unstable_avoidThisFallback||
+0!==(D.current&1))F===Xa&&(F=ad);else{if(F===Xa||F===ad)F=bd;0!==Xb&&null!==U&&(Ya(U,P),yh(U,Xb))}if(c||d)b.effectTag|=4;return null;case 4:return tb(),wh(b),null;case 10:return me(b),null;case 17:return N(b.type)&&(q(G),q(B)),null;case 19:q(D);d=b.memoizedState;if(null===d)return null;e=0!==(b.effectTag&64);f=d.rendering;if(null===f)if(e)$c(d,!1);else{if(F!==Xa||null!==a&&0!==(a.effectTag&64))for(f=b.child;null!==f;){a=Rc(f);if(null!==a){b.effectTag|=64;$c(d,!1);e=a.updateQueue;null!==e&&(b.updateQueue=
+e,b.effectTag|=4);null===d.lastEffect&&(b.firstEffect=null);b.lastEffect=d.lastEffect;for(d=b.child;null!==d;)e=d,f=c,e.effectTag&=2,e.nextEffect=null,e.firstEffect=null,e.lastEffect=null,a=e.alternate,null===a?(e.childExpirationTime=0,e.expirationTime=f,e.child=null,e.memoizedProps=null,e.memoizedState=null,e.updateQueue=null,e.dependencies=null):(e.childExpirationTime=a.childExpirationTime,e.expirationTime=a.expirationTime,e.child=a.child,e.memoizedProps=a.memoizedProps,e.memoizedState=a.memoizedState,
+e.updateQueue=a.updateQueue,f=a.dependencies,e.dependencies=null===f?null:{expirationTime:f.expirationTime,firstContext:f.firstContext,responders:f.responders}),d=d.sibling;y(D,D.current&1|2);return b.child}f=f.sibling}}else{if(!e)if(a=Rc(f),null!==a){if(b.effectTag|=64,e=!0,c=a.updateQueue,null!==c&&(b.updateQueue=c,b.effectTag|=4),$c(d,!0),null===d.tail&&"hidden"===d.tailMode&&!f.alternate)return b=b.lastEffect=d.lastEffect,null!==b&&(b.nextEffect=null),null}else 2*Y()-d.renderingStartTime>d.tailExpiration&&
+1<c&&(b.effectTag|=64,e=!0,$c(d,!1),b.expirationTime=b.childExpirationTime=c-1);d.isBackwards?(f.sibling=b.child,b.child=f):(c=d.last,null!==c?c.sibling=f:b.child=f,d.last=f)}return null!==d.tail?(0===d.tailExpiration&&(d.tailExpiration=Y()+500),c=d.tail,d.rendering=c,d.tail=c.sibling,d.lastEffect=b.lastEffect,d.renderingStartTime=Y(),c.sibling=null,b=D.current,y(D,e?b&1|2:b&1),c):null}throw Error(k(156,b.tag));}function lj(a,b){switch(a.tag){case 1:return N(a.type)&&(q(G),q(B)),b=a.effectTag,b&4096?
+(a.effectTag=b&-4097|64,a):null;case 3:tb();q(G);q(B);b=a.effectTag;if(0!==(b&64))throw Error(k(285));a.effectTag=b&-4097|64;return a;case 5:return te(a),null;case 13:return q(D),b=a.effectTag,b&4096?(a.effectTag=b&-4097|64,a):null;case 19:return q(D),null;case 4:return tb(),null;case 10:return me(a),null;default:return null}}function Le(a,b){return{value:a,source:b,stack:Bd(b)}}function Me(a,b){var c=b.source,d=b.stack;null===d&&null!==c&&(d=Bd(c));null!==c&&na(c.type);b=b.value;null!==a&&1===a.tag&&
+na(a.type);try{console.error(b)}catch(e){setTimeout(function(){throw e;})}}function mj(a,b){try{b.props=a.memoizedProps,b.state=a.memoizedState,b.componentWillUnmount()}catch(c){Za(a,c)}}function zh(a){var b=a.ref;if(null!==b)if("function"===typeof b)try{b(null)}catch(c){Za(a,c)}else b.current=null}function nj(a,b){switch(b.tag){case 0:case 11:case 15:case 22:return;case 1:if(b.effectTag&256&&null!==a){var c=a.memoizedProps,d=a.memoizedState;a=b.stateNode;b=a.getSnapshotBeforeUpdate(b.elementType===
+b.type?c:aa(b.type,c),d);a.__reactInternalSnapshotBeforeUpdate=b}return;case 3:case 5:case 6:case 4:case 17:return}throw Error(k(163));}function Ah(a,b){b=b.updateQueue;b=null!==b?b.lastEffect:null;if(null!==b){var c=b=b.next;do{if((c.tag&a)===a){var d=c.destroy;c.destroy=void 0;void 0!==d&&d()}c=c.next}while(c!==b)}}function Bh(a,b){b=b.updateQueue;b=null!==b?b.lastEffect:null;if(null!==b){var c=b=b.next;do{if((c.tag&a)===a){var d=c.create;c.destroy=d()}c=c.next}while(c!==b)}}function oj(a,b,c,d){switch(c.tag){case 0:case 11:case 15:case 22:Bh(3,
+c);return;case 1:a=c.stateNode;c.effectTag&4&&(null===b?a.componentDidMount():(d=c.elementType===c.type?b.memoizedProps:aa(c.type,b.memoizedProps),a.componentDidUpdate(d,b.memoizedState,a.__reactInternalSnapshotBeforeUpdate)));b=c.updateQueue;null!==b&&Wg(c,b,a);return;case 3:b=c.updateQueue;if(null!==b){a=null;if(null!==c.child)switch(c.child.tag){case 5:a=c.child.stateNode;break;case 1:a=c.child.stateNode}Wg(c,b,a)}return;case 5:a=c.stateNode;null===b&&c.effectTag&4&&lg(c.type,c.memoizedProps)&&
+a.focus();return;case 6:return;case 4:return;case 12:return;case 13:null===c.memoizedState&&(c=c.alternate,null!==c&&(c=c.memoizedState,null!==c&&(c=c.dehydrated,null!==c&&bg(c))));return;case 19:case 17:case 20:case 21:return}throw Error(k(163));}function Ch(a,b,c){"function"===typeof Ne&&Ne(b);switch(b.tag){case 0:case 11:case 14:case 15:case 22:a=b.updateQueue;if(null!==a&&(a=a.lastEffect,null!==a)){var d=a.next;Da(97<c?97:c,function(){var a=d;do{var c=a.destroy;if(void 0!==c){var g=b;try{c()}catch(h){Za(g,
+h)}}a=a.next}while(a!==d)})}break;case 1:zh(b);c=b.stateNode;"function"===typeof c.componentWillUnmount&&mj(b,c);break;case 5:zh(b);break;case 4:Dh(a,b,c)}}function Eh(a){var b=a.alternate;a.return=null;a.child=null;a.memoizedState=null;a.updateQueue=null;a.dependencies=null;a.alternate=null;a.firstEffect=null;a.lastEffect=null;a.pendingProps=null;a.memoizedProps=null;a.stateNode=null;null!==b&&Eh(b)}function Fh(a){return 5===a.tag||3===a.tag||4===a.tag}function Gh(a){a:{for(var b=a.return;null!==
+b;){if(Fh(b)){var c=b;break a}b=b.return}throw Error(k(160));}b=c.stateNode;switch(c.tag){case 5:var d=!1;break;case 3:b=b.containerInfo;d=!0;break;case 4:b=b.containerInfo;d=!0;break;default:throw Error(k(161));}c.effectTag&16&&(Wb(b,""),c.effectTag&=-17);a:b:for(c=a;;){for(;null===c.sibling;){if(null===c.return||Fh(c.return)){c=null;break a}c=c.return}c.sibling.return=c.return;for(c=c.sibling;5!==c.tag&&6!==c.tag&&18!==c.tag;){if(c.effectTag&2)continue b;if(null===c.child||4===c.tag)continue b;
+else c.child.return=c,c=c.child}if(!(c.effectTag&2)){c=c.stateNode;break a}}d?Oe(a,c,b):Pe(a,c,b)}function Oe(a,b,c){var d=a.tag,e=5===d||6===d;if(e)a=e?a.stateNode:a.stateNode.instance,b?8===c.nodeType?c.parentNode.insertBefore(a,b):c.insertBefore(a,b):(8===c.nodeType?(b=c.parentNode,b.insertBefore(a,c)):(b=c,b.appendChild(a)),c=c._reactRootContainer,null!==c&&void 0!==c||null!==b.onclick||(b.onclick=uc));else if(4!==d&&(a=a.child,null!==a))for(Oe(a,b,c),a=a.sibling;null!==a;)Oe(a,b,c),a=a.sibling}
+function Pe(a,b,c){var d=a.tag,e=5===d||6===d;if(e)a=e?a.stateNode:a.stateNode.instance,b?c.insertBefore(a,b):c.appendChild(a);else if(4!==d&&(a=a.child,null!==a))for(Pe(a,b,c),a=a.sibling;null!==a;)Pe(a,b,c),a=a.sibling}function Dh(a,b,c){for(var d=b,e=!1,f,g;;){if(!e){e=d.return;a:for(;;){if(null===e)throw Error(k(160));f=e.stateNode;switch(e.tag){case 5:g=!1;break a;case 3:f=f.containerInfo;g=!0;break a;case 4:f=f.containerInfo;g=!0;break a}e=e.return}e=!0}if(5===d.tag||6===d.tag){a:for(var h=
+a,m=d,n=c,l=m;;)if(Ch(h,l,n),null!==l.child&&4!==l.tag)l.child.return=l,l=l.child;else{if(l===m)break a;for(;null===l.sibling;){if(null===l.return||l.return===m)break a;l=l.return}l.sibling.return=l.return;l=l.sibling}g?(h=f,m=d.stateNode,8===h.nodeType?h.parentNode.removeChild(m):h.removeChild(m)):f.removeChild(d.stateNode)}else if(4===d.tag){if(null!==d.child){f=d.stateNode.containerInfo;g=!0;d.child.return=d;d=d.child;continue}}else if(Ch(a,d,c),null!==d.child){d.child.return=d;d=d.child;continue}if(d===
+b)break;for(;null===d.sibling;){if(null===d.return||d.return===b)return;d=d.return;4===d.tag&&(e=!1)}d.sibling.return=d.return;d=d.sibling}}function Qe(a,b){switch(b.tag){case 0:case 11:case 14:case 15:case 22:Ah(3,b);return;case 1:return;case 5:var c=b.stateNode;if(null!=c){var d=b.memoizedProps,e=null!==a?a.memoizedProps:d;a=b.type;var f=b.updateQueue;b.updateQueue=null;if(null!==f){c[vc]=d;"input"===a&&"radio"===d.type&&null!=d.name&&If(c,d);Vd(a,e);b=Vd(a,d);for(e=0;e<f.length;e+=2){var g=f[e],
+h=f[e+1];"style"===g?gg(c,h):"dangerouslySetInnerHTML"===g?xh(c,h):"children"===g?Wb(c,h):xd(c,g,h,b)}switch(a){case "input":Dd(c,d);break;case "textarea":Lf(c,d);break;case "select":b=c._wrapperState.wasMultiple,c._wrapperState.wasMultiple=!!d.multiple,a=d.value,null!=a?hb(c,!!d.multiple,a,!1):b!==!!d.multiple&&(null!=d.defaultValue?hb(c,!!d.multiple,d.defaultValue,!0):hb(c,!!d.multiple,d.multiple?[]:"",!1))}}}return;case 6:if(null===b.stateNode)throw Error(k(162));b.stateNode.nodeValue=b.memoizedProps;
+return;case 3:b=b.stateNode;b.hydrate&&(b.hydrate=!1,bg(b.containerInfo));return;case 12:return;case 13:c=b;null===b.memoizedState?d=!1:(d=!0,c=b.child,Re=Y());if(null!==c)a:for(a=c;;){if(5===a.tag)f=a.stateNode,d?(f=f.style,"function"===typeof f.setProperty?f.setProperty("display","none","important"):f.display="none"):(f=a.stateNode,e=a.memoizedProps.style,e=void 0!==e&&null!==e&&e.hasOwnProperty("display")?e.display:null,f.style.display=fg("display",e));else if(6===a.tag)a.stateNode.nodeValue=d?
+"":a.memoizedProps;else if(13===a.tag&&null!==a.memoizedState&&null===a.memoizedState.dehydrated){f=a.child.sibling;f.return=a;a=f;continue}else if(null!==a.child){a.child.return=a;a=a.child;continue}if(a===c)break;for(;null===a.sibling;){if(null===a.return||a.return===c)break a;a=a.return}a.sibling.return=a.return;a=a.sibling}Hh(b);return;case 19:Hh(b);return;case 17:return}throw Error(k(163));}function Hh(a){var b=a.updateQueue;if(null!==b){a.updateQueue=null;var c=a.stateNode;null===c&&(c=a.stateNode=
+new pj);b.forEach(function(b){var d=qj.bind(null,a,b);c.has(b)||(c.add(b),b.then(d,d))})}}function Ih(a,b,c){c=Ea(c,null);c.tag=3;c.payload={element:null};var d=b.value;c.callback=function(){cd||(cd=!0,Se=d);Me(a,b)};return c}function Jh(a,b,c){c=Ea(c,null);c.tag=3;var d=a.type.getDerivedStateFromError;if("function"===typeof d){var e=b.value;c.payload=function(){Me(a,b);return d(e)}}var f=a.stateNode;null!==f&&"function"===typeof f.componentDidCatch&&(c.callback=function(){"function"!==typeof d&&
+(null===La?La=new Set([this]):La.add(this),Me(a,b));var c=b.stack;this.componentDidCatch(b.value,{componentStack:null!==c?c:""})});return c}function ka(){return(p&(ca|ma))!==H?1073741821-(Y()/10|0):0!==dd?dd:dd=1073741821-(Y()/10|0)}function Va(a,b,c){b=b.mode;if(0===(b&2))return 1073741823;var d=Cc();if(0===(b&4))return 99===d?1073741823:1073741822;if((p&ca)!==H)return P;if(null!==c)a=Fc(a,c.timeoutMs|0||5E3,250);else switch(d){case 99:a=1073741823;break;case 98:a=Fc(a,150,100);break;case 97:case 96:a=
+Fc(a,5E3,250);break;case 95:a=2;break;default:throw Error(k(326));}null!==U&&a===P&&--a;return a}function ed(a,b){a.expirationTime<b&&(a.expirationTime=b);var c=a.alternate;null!==c&&c.expirationTime<b&&(c.expirationTime=b);var d=a.return,e=null;if(null===d&&3===a.tag)e=a.stateNode;else for(;null!==d;){c=d.alternate;d.childExpirationTime<b&&(d.childExpirationTime=b);null!==c&&c.childExpirationTime<b&&(c.childExpirationTime=b);if(null===d.return&&3===d.tag){e=d.stateNode;break}d=d.return}null!==e&&
+(U===e&&(Kc(b),F===bd&&Ya(e,P)),yh(e,b));return e}function fd(a){var b=a.lastExpiredTime;if(0!==b)return b;b=a.firstPendingTime;if(!Kh(a,b))return b;var c=a.lastPingedTime;a=a.nextKnownPendingLevel;a=c>a?c:a;return 2>=a&&b!==a?0:a}function V(a){if(0!==a.lastExpiredTime)a.callbackExpirationTime=1073741823,a.callbackPriority=99,a.callbackNode=Og(Te.bind(null,a));else{var b=fd(a),c=a.callbackNode;if(0===b)null!==c&&(a.callbackNode=null,a.callbackExpirationTime=0,a.callbackPriority=90);else{var d=ka();
+1073741823===b?d=99:1===b||2===b?d=95:(d=10*(1073741821-b)-10*(1073741821-d),d=0>=d?99:250>=d?98:5250>=d?97:95);if(null!==c){var e=a.callbackPriority;if(a.callbackExpirationTime===b&&e>=d)return;c!==Qg&&Rg(c)}a.callbackExpirationTime=b;a.callbackPriority=d;b=1073741823===b?Og(Te.bind(null,a)):Ng(d,Lh.bind(null,a),{timeout:10*(1073741821-b)-Y()});a.callbackNode=b}}}function Lh(a,b){dd=0;if(b)return b=ka(),Ue(a,b),V(a),null;var c=fd(a);if(0!==c){b=a.callbackNode;if((p&(ca|ma))!==H)throw Error(k(327));
+xb();a===U&&c===P||$a(a,c);if(null!==t){var d=p;p|=ca;var e=Mh();do try{rj();break}catch(h){Nh(a,h)}while(1);le();p=d;gd.current=e;if(F===hd)throw b=id,$a(a,c),Ya(a,c),V(a),b;if(null===t)switch(e=a.finishedWork=a.current.alternate,a.finishedExpirationTime=c,d=F,U=null,d){case Xa:case hd:throw Error(k(345));case Oh:Ue(a,2<c?2:c);break;case ad:Ya(a,c);d=a.lastSuspendedTime;c===d&&(a.nextKnownPendingLevel=Ve(e));if(1073741823===ta&&(e=Re+Ph-Y(),10<e)){if(jd){var f=a.lastPingedTime;if(0===f||f>=c){a.lastPingedTime=
+c;$a(a,c);break}}f=fd(a);if(0!==f&&f!==c)break;if(0!==d&&d!==c){a.lastPingedTime=d;break}a.timeoutHandle=We(ab.bind(null,a),e);break}ab(a);break;case bd:Ya(a,c);d=a.lastSuspendedTime;c===d&&(a.nextKnownPendingLevel=Ve(e));if(jd&&(e=a.lastPingedTime,0===e||e>=c)){a.lastPingedTime=c;$a(a,c);break}e=fd(a);if(0!==e&&e!==c)break;if(0!==d&&d!==c){a.lastPingedTime=d;break}1073741823!==Yb?d=10*(1073741821-Yb)-Y():1073741823===ta?d=0:(d=10*(1073741821-ta)-5E3,e=Y(),c=10*(1073741821-c)-e,d=e-d,0>d&&(d=0),d=
+(120>d?120:480>d?480:1080>d?1080:1920>d?1920:3E3>d?3E3:4320>d?4320:1960*sj(d/1960))-d,c<d&&(d=c));if(10<d){a.timeoutHandle=We(ab.bind(null,a),d);break}ab(a);break;case Xe:if(1073741823!==ta&&null!==kd){f=ta;var g=kd;d=g.busyMinDurationMs|0;0>=d?d=0:(e=g.busyDelayMs|0,f=Y()-(10*(1073741821-f)-(g.timeoutMs|0||5E3)),d=f<=e?0:e+d-f);if(10<d){Ya(a,c);a.timeoutHandle=We(ab.bind(null,a),d);break}}ab(a);break;default:throw Error(k(329));}V(a);if(a.callbackNode===b)return Lh.bind(null,a)}}return null}function Te(a){var b=
+a.lastExpiredTime;b=0!==b?b:1073741823;if((p&(ca|ma))!==H)throw Error(k(327));xb();a===U&&b===P||$a(a,b);if(null!==t){var c=p;p|=ca;var d=Mh();do try{tj();break}catch(e){Nh(a,e)}while(1);le();p=c;gd.current=d;if(F===hd)throw c=id,$a(a,b),Ya(a,b),V(a),c;if(null!==t)throw Error(k(261));a.finishedWork=a.current.alternate;a.finishedExpirationTime=b;U=null;ab(a);V(a)}return null}function uj(){if(null!==bb){var a=bb;bb=null;a.forEach(function(a,c){Ue(c,a);V(c)});ha()}}function Qh(a,b){var c=p;p|=1;try{return a(b)}finally{p=
+c,p===H&&ha()}}function Rh(a,b){var c=p;p&=-2;p|=Ye;try{return a(b)}finally{p=c,p===H&&ha()}}function $a(a,b){a.finishedWork=null;a.finishedExpirationTime=0;var c=a.timeoutHandle;-1!==c&&(a.timeoutHandle=-1,vj(c));if(null!==t)for(c=t.return;null!==c;){var d=c;switch(d.tag){case 1:d=d.type.childContextTypes;null!==d&&void 0!==d&&(q(G),q(B));break;case 3:tb();q(G);q(B);break;case 5:te(d);break;case 4:tb();break;case 13:q(D);break;case 19:q(D);break;case 10:me(d)}c=c.return}U=a;t=Sa(a.current,null);
+P=b;F=Xa;id=null;Yb=ta=1073741823;kd=null;Xb=0;jd=!1}function Nh(a,b){do{try{le();Sc.current=Tc;if(Uc)for(var c=z.memoizedState;null!==c;){var d=c.queue;null!==d&&(d.pending=null);c=c.next}Ia=0;J=K=z=null;Uc=!1;if(null===t||null===t.return)return F=hd,id=b,t=null;a:{var e=a,f=t.return,g=t,h=b;b=P;g.effectTag|=2048;g.firstEffect=g.lastEffect=null;if(null!==h&&"object"===typeof h&&"function"===typeof h.then){var m=h;if(0===(g.mode&2)){var n=g.alternate;n?(g.updateQueue=n.updateQueue,g.memoizedState=
+n.memoizedState,g.expirationTime=n.expirationTime):(g.updateQueue=null,g.memoizedState=null)}var l=0!==(D.current&1),k=f;do{var p;if(p=13===k.tag){var q=k.memoizedState;if(null!==q)p=null!==q.dehydrated?!0:!1;else{var w=k.memoizedProps;p=void 0===w.fallback?!1:!0!==w.unstable_avoidThisFallback?!0:l?!1:!0}}if(p){var y=k.updateQueue;if(null===y){var r=new Set;r.add(m);k.updateQueue=r}else y.add(m);if(0===(k.mode&2)){k.effectTag|=64;g.effectTag&=-2981;if(1===g.tag)if(null===g.alternate)g.tag=17;else{var O=
+Ea(1073741823,null);O.tag=Jc;Fa(g,O)}g.expirationTime=1073741823;break a}h=void 0;g=b;var v=e.pingCache;null===v?(v=e.pingCache=new wj,h=new Set,v.set(m,h)):(h=v.get(m),void 0===h&&(h=new Set,v.set(m,h)));if(!h.has(g)){h.add(g);var x=xj.bind(null,e,m,g);m.then(x,x)}k.effectTag|=4096;k.expirationTime=b;break a}k=k.return}while(null!==k);h=Error((na(g.type)||"A React component")+" suspended while rendering, but no fallback UI was specified.\n\nAdd a <Suspense fallback=...> component higher in the tree to provide a loading indicator or placeholder to display."+
+Bd(g))}F!==Xe&&(F=Oh);h=Le(h,g);k=f;do{switch(k.tag){case 3:m=h;k.effectTag|=4096;k.expirationTime=b;var A=Ih(k,m,b);Ug(k,A);break a;case 1:m=h;var u=k.type,B=k.stateNode;if(0===(k.effectTag&64)&&("function"===typeof u.getDerivedStateFromError||null!==B&&"function"===typeof B.componentDidCatch&&(null===La||!La.has(B)))){k.effectTag|=4096;k.expirationTime=b;var H=Jh(k,m,b);Ug(k,H);break a}}k=k.return}while(null!==k)}t=Sh(t)}catch(cj){b=cj;continue}break}while(1)}function Mh(a){a=gd.current;gd.current=
+Tc;return null===a?Tc:a}function Vg(a,b){a<ta&&2<a&&(ta=a);null!==b&&a<Yb&&2<a&&(Yb=a,kd=b)}function Kc(a){a>Xb&&(Xb=a)}function tj(){for(;null!==t;)t=Th(t)}function rj(){for(;null!==t&&!yj();)t=Th(t)}function Th(a){var b=zj(a.alternate,a,P);a.memoizedProps=a.pendingProps;null===b&&(b=Sh(a));Uh.current=null;return b}function Sh(a){t=a;do{var b=t.alternate;a=t.return;if(0===(t.effectTag&2048)){b=hj(b,t,P);if(1===P||1!==t.childExpirationTime){for(var c=0,d=t.child;null!==d;){var e=d.expirationTime,
+f=d.childExpirationTime;e>c&&(c=e);f>c&&(c=f);d=d.sibling}t.childExpirationTime=c}if(null!==b)return b;null!==a&&0===(a.effectTag&2048)&&(null===a.firstEffect&&(a.firstEffect=t.firstEffect),null!==t.lastEffect&&(null!==a.lastEffect&&(a.lastEffect.nextEffect=t.firstEffect),a.lastEffect=t.lastEffect),1<t.effectTag&&(null!==a.lastEffect?a.lastEffect.nextEffect=t:a.firstEffect=t,a.lastEffect=t))}else{b=lj(t);if(null!==b)return b.effectTag&=2047,b;null!==a&&(a.firstEffect=a.lastEffect=null,a.effectTag|=
+2048)}b=t.sibling;if(null!==b)return b;t=a}while(null!==t);F===Xa&&(F=Xe);return null}function Ve(a){var b=a.expirationTime;a=a.childExpirationTime;return b>a?b:a}function ab(a){var b=Cc();Da(99,Aj.bind(null,a,b));return null}function Aj(a,b){do xb();while(null!==Zb);if((p&(ca|ma))!==H)throw Error(k(327));var c=a.finishedWork,d=a.finishedExpirationTime;if(null===c)return null;a.finishedWork=null;a.finishedExpirationTime=0;if(c===a.current)throw Error(k(177));a.callbackNode=null;a.callbackExpirationTime=
+0;a.callbackPriority=90;a.nextKnownPendingLevel=0;var e=Ve(c);a.firstPendingTime=e;d<=a.lastSuspendedTime?a.firstSuspendedTime=a.lastSuspendedTime=a.nextKnownPendingLevel=0:d<=a.firstSuspendedTime&&(a.firstSuspendedTime=d-1);d<=a.lastPingedTime&&(a.lastPingedTime=0);d<=a.lastExpiredTime&&(a.lastExpiredTime=0);a===U&&(t=U=null,P=0);1<c.effectTag?null!==c.lastEffect?(c.lastEffect.nextEffect=c,e=c.firstEffect):e=c:e=c.firstEffect;if(null!==e){var f=p;p|=ma;Uh.current=null;Ze=tc;var g=kg();if(Xd(g)){if("selectionStart"in
+g)var h={start:g.selectionStart,end:g.selectionEnd};else a:{h=(h=g.ownerDocument)&&h.defaultView||window;var m=h.getSelection&&h.getSelection();if(m&&0!==m.rangeCount){h=m.anchorNode;var n=m.anchorOffset,q=m.focusNode;m=m.focusOffset;try{h.nodeType,q.nodeType}catch(sb){h=null;break a}var ba=0,w=-1,y=-1,B=0,D=0,r=g,z=null;b:for(;;){for(var v;;){r!==h||0!==n&&3!==r.nodeType||(w=ba+n);r!==q||0!==m&&3!==r.nodeType||(y=ba+m);3===r.nodeType&&(ba+=r.nodeValue.length);if(null===(v=r.firstChild))break;z=r;
+r=v}for(;;){if(r===g)break b;z===h&&++B===n&&(w=ba);z===q&&++D===m&&(y=ba);if(null!==(v=r.nextSibling))break;r=z;z=r.parentNode}r=v}h=-1===w||-1===y?null:{start:w,end:y}}else h=null}h=h||{start:0,end:0}}else h=null;$e={activeElementDetached:null,focusedElem:g,selectionRange:h};tc=!1;l=e;do try{Bj()}catch(sb){if(null===l)throw Error(k(330));Za(l,sb);l=l.nextEffect}while(null!==l);l=e;do try{for(g=a,h=b;null!==l;){var x=l.effectTag;x&16&&Wb(l.stateNode,"");if(x&128){var A=l.alternate;if(null!==A){var u=
+A.ref;null!==u&&("function"===typeof u?u(null):u.current=null)}}switch(x&1038){case 2:Gh(l);l.effectTag&=-3;break;case 6:Gh(l);l.effectTag&=-3;Qe(l.alternate,l);break;case 1024:l.effectTag&=-1025;break;case 1028:l.effectTag&=-1025;Qe(l.alternate,l);break;case 4:Qe(l.alternate,l);break;case 8:n=l,Dh(g,n,h),Eh(n)}l=l.nextEffect}}catch(sb){if(null===l)throw Error(k(330));Za(l,sb);l=l.nextEffect}while(null!==l);u=$e;A=kg();x=u.focusedElem;h=u.selectionRange;if(A!==x&&x&&x.ownerDocument&&jg(x.ownerDocument.documentElement,
+x)){null!==h&&Xd(x)&&(A=h.start,u=h.end,void 0===u&&(u=A),"selectionStart"in x?(x.selectionStart=A,x.selectionEnd=Math.min(u,x.value.length)):(u=(A=x.ownerDocument||document)&&A.defaultView||window,u.getSelection&&(u=u.getSelection(),n=x.textContent.length,g=Math.min(h.start,n),h=void 0===h.end?g:Math.min(h.end,n),!u.extend&&g>h&&(n=h,h=g,g=n),n=ig(x,g),q=ig(x,h),n&&q&&(1!==u.rangeCount||u.anchorNode!==n.node||u.anchorOffset!==n.offset||u.focusNode!==q.node||u.focusOffset!==q.offset)&&(A=A.createRange(),
+A.setStart(n.node,n.offset),u.removeAllRanges(),g>h?(u.addRange(A),u.extend(q.node,q.offset)):(A.setEnd(q.node,q.offset),u.addRange(A))))));A=[];for(u=x;u=u.parentNode;)1===u.nodeType&&A.push({element:u,left:u.scrollLeft,top:u.scrollTop});"function"===typeof x.focus&&x.focus();for(x=0;x<A.length;x++)u=A[x],u.element.scrollLeft=u.left,u.element.scrollTop=u.top}tc=!!Ze;$e=Ze=null;a.current=c;l=e;do try{for(x=a;null!==l;){var F=l.effectTag;F&36&&oj(x,l.alternate,l);if(F&128){A=void 0;var E=l.ref;if(null!==
+E){var G=l.stateNode;switch(l.tag){case 5:A=G;break;default:A=G}"function"===typeof E?E(A):E.current=A}}l=l.nextEffect}}catch(sb){if(null===l)throw Error(k(330));Za(l,sb);l=l.nextEffect}while(null!==l);l=null;Cj();p=f}else a.current=c;if(ld)ld=!1,Zb=a,$b=b;else for(l=e;null!==l;)b=l.nextEffect,l.nextEffect=null,l=b;b=a.firstPendingTime;0===b&&(La=null);1073741823===b?a===af?ac++:(ac=0,af=a):ac=0;"function"===typeof bf&&bf(c.stateNode,d);V(a);if(cd)throw cd=!1,a=Se,Se=null,a;if((p&Ye)!==H)return null;
+ha();return null}function Bj(){for(;null!==l;){var a=l.effectTag;0!==(a&256)&&nj(l.alternate,l);0===(a&512)||ld||(ld=!0,Ng(97,function(){xb();return null}));l=l.nextEffect}}function xb(){if(90!==$b){var a=97<$b?97:$b;$b=90;return Da(a,Dj)}}function Dj(){if(null===Zb)return!1;var a=Zb;Zb=null;if((p&(ca|ma))!==H)throw Error(k(331));var b=p;p|=ma;for(a=a.current.firstEffect;null!==a;){try{var c=a;if(0!==(c.effectTag&512))switch(c.tag){case 0:case 11:case 15:case 22:Ah(5,c),Bh(5,c)}}catch(d){if(null===
+a)throw Error(k(330));Za(a,d)}c=a.nextEffect;a.nextEffect=null;a=c}p=b;ha();return!0}function Vh(a,b,c){b=Le(c,b);b=Ih(a,b,1073741823);Fa(a,b);a=ed(a,1073741823);null!==a&&V(a)}function Za(a,b){if(3===a.tag)Vh(a,a,b);else for(var c=a.return;null!==c;){if(3===c.tag){Vh(c,a,b);break}else if(1===c.tag){var d=c.stateNode;if("function"===typeof c.type.getDerivedStateFromError||"function"===typeof d.componentDidCatch&&(null===La||!La.has(d))){a=Le(b,a);a=Jh(c,a,1073741823);Fa(c,a);c=ed(c,1073741823);null!==
+c&&V(c);break}}c=c.return}}function xj(a,b,c){var d=a.pingCache;null!==d&&d.delete(b);U===a&&P===c?F===bd||F===ad&&1073741823===ta&&Y()-Re<Ph?$a(a,P):jd=!0:Kh(a,c)&&(b=a.lastPingedTime,0!==b&&b<c||(a.lastPingedTime=c,V(a)))}function qj(a,b){var c=a.stateNode;null!==c&&c.delete(b);b=0;0===b&&(b=ka(),b=Va(b,a,null));a=ed(a,b);null!==a&&V(a)}function Ej(a){if("undefined"===typeof __REACT_DEVTOOLS_GLOBAL_HOOK__)return!1;var b=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(b.isDisabled||!b.supportsFiber)return!0;try{var c=
+b.inject(a);bf=function(a,e){try{b.onCommitFiberRoot(c,a,void 0,64===(a.current.effectTag&64))}catch(f){}};Ne=function(a){try{b.onCommitFiberUnmount(c,a)}catch(e){}}}catch(d){}return!0}function Fj(a,b,c,d){this.tag=a;this.key=c;this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null;this.index=0;this.ref=null;this.pendingProps=b;this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null;this.mode=d;this.effectTag=0;this.lastEffect=this.firstEffect=this.nextEffect=
+null;this.childExpirationTime=this.expirationTime=0;this.alternate=null}function Ge(a){a=a.prototype;return!(!a||!a.isReactComponent)}function Gj(a){if("function"===typeof a)return Ge(a)?1:0;if(void 0!==a&&null!==a){a=a.$$typeof;if(a===zd)return 11;if(a===Ad)return 14}return 2}function Sa(a,b){var c=a.alternate;null===c?(c=la(a.tag,b,a.key,a.mode),c.elementType=a.elementType,c.type=a.type,c.stateNode=a.stateNode,c.alternate=a,a.alternate=c):(c.pendingProps=b,c.effectTag=0,c.nextEffect=null,c.firstEffect=
+null,c.lastEffect=null);c.childExpirationTime=a.childExpirationTime;c.expirationTime=a.expirationTime;c.child=a.child;c.memoizedProps=a.memoizedProps;c.memoizedState=a.memoizedState;c.updateQueue=a.updateQueue;b=a.dependencies;c.dependencies=null===b?null:{expirationTime:b.expirationTime,firstContext:b.firstContext,responders:b.responders};c.sibling=a.sibling;c.index=a.index;c.ref=a.ref;return c}function Oc(a,b,c,d,e,f){var g=2;d=a;if("function"===typeof a)Ge(a)&&(g=1);else if("string"===typeof a)g=
+5;else a:switch(a){case Ma:return Ha(c.children,e,f,b);case Hj:g=8;e|=7;break;case Af:g=8;e|=1;break;case kc:return a=la(12,c,b,e|8),a.elementType=kc,a.type=kc,a.expirationTime=f,a;case lc:return a=la(13,c,b,e),a.type=lc,a.elementType=lc,a.expirationTime=f,a;case yd:return a=la(19,c,b,e),a.elementType=yd,a.expirationTime=f,a;default:if("object"===typeof a&&null!==a)switch(a.$$typeof){case Cf:g=10;break a;case Bf:g=9;break a;case zd:g=11;break a;case Ad:g=14;break a;case Ef:g=16;d=null;break a;case Df:g=
+22;break a}throw Error(k(130,null==a?a:typeof a,""));}b=la(g,c,b,e);b.elementType=a;b.type=d;b.expirationTime=f;return b}function Ha(a,b,c,d){a=la(7,a,d,b);a.expirationTime=c;return a}function qe(a,b,c){a=la(6,a,null,b);a.expirationTime=c;return a}function re(a,b,c){b=la(4,null!==a.children?a.children:[],a.key,b);b.expirationTime=c;b.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation};return b}function Ij(a,b,c){this.tag=b;this.current=null;this.containerInfo=
+a;this.pingCache=this.pendingChildren=null;this.finishedExpirationTime=0;this.finishedWork=null;this.timeoutHandle=-1;this.pendingContext=this.context=null;this.hydrate=c;this.callbackNode=null;this.callbackPriority=90;this.lastExpiredTime=this.lastPingedTime=this.nextKnownPendingLevel=this.lastSuspendedTime=this.firstSuspendedTime=this.firstPendingTime=0}function Kh(a,b){var c=a.firstSuspendedTime;a=a.lastSuspendedTime;return 0!==c&&c>=b&&a<=b}function Ya(a,b){var c=a.firstSuspendedTime,d=a.lastSuspendedTime;
+c<b&&(a.firstSuspendedTime=b);if(d>b||0===c)a.lastSuspendedTime=b;b<=a.lastPingedTime&&(a.lastPingedTime=0);b<=a.lastExpiredTime&&(a.lastExpiredTime=0)}function yh(a,b){b>a.firstPendingTime&&(a.firstPendingTime=b);var c=a.firstSuspendedTime;0!==c&&(b>=c?a.firstSuspendedTime=a.lastSuspendedTime=a.nextKnownPendingLevel=0:b>=a.lastSuspendedTime&&(a.lastSuspendedTime=b+1),b>a.nextKnownPendingLevel&&(a.nextKnownPendingLevel=b))}function Ue(a,b){var c=a.lastExpiredTime;if(0===c||c>b)a.lastExpiredTime=b}
+function md(a,b,c,d){var e=b.current,f=ka(),g=Vb.suspense;f=Va(f,e,g);a:if(c){c=c._reactInternalFiber;b:{if(Na(c)!==c||1!==c.tag)throw Error(k(170));var h=c;do{switch(h.tag){case 3:h=h.stateNode.context;break b;case 1:if(N(h.type)){h=h.stateNode.__reactInternalMemoizedMergedChildContext;break b}}h=h.return}while(null!==h);throw Error(k(171));}if(1===c.tag){var m=c.type;if(N(m)){c=Gg(c,m,h);break a}}c=h}else c=Ca;null===b.context?b.context=c:b.pendingContext=c;b=Ea(f,g);b.payload={element:a};d=void 0===
+d?null:d;null!==d&&(b.callback=d);Fa(e,b);Ja(e,f);return f}function cf(a){a=a.current;if(!a.child)return null;switch(a.child.tag){case 5:return a.child.stateNode;default:return a.child.stateNode}}function Wh(a,b){a=a.memoizedState;null!==a&&null!==a.dehydrated&&a.retryTime<b&&(a.retryTime=b)}function df(a,b){Wh(a,b);(a=a.alternate)&&Wh(a,b)}function ef(a,b,c){c=null!=c&&!0===c.hydrate;var d=new Ij(a,b,c),e=la(3,null,null,2===b?7:1===b?3:0);d.current=e;e.stateNode=d;ne(e);a[Lb]=d.current;c&&0!==b&&
+xi(a,9===a.nodeType?a:a.ownerDocument);this._internalRoot=d}function bc(a){return!(!a||1!==a.nodeType&&9!==a.nodeType&&11!==a.nodeType&&(8!==a.nodeType||" react-mount-point-unstable "!==a.nodeValue))}function Jj(a,b){b||(b=a?9===a.nodeType?a.documentElement:a.firstChild:null,b=!(!b||1!==b.nodeType||!b.hasAttribute("data-reactroot")));if(!b)for(var c;c=a.lastChild;)a.removeChild(c);return new ef(a,0,b?{hydrate:!0}:void 0)}function nd(a,b,c,d,e){var f=c._reactRootContainer;if(f){var g=f._internalRoot;
+if("function"===typeof e){var h=e;e=function(){var a=cf(g);h.call(a)}}md(b,g,a,e)}else{f=c._reactRootContainer=Jj(c,d);g=f._internalRoot;if("function"===typeof e){var m=e;e=function(){var a=cf(g);m.call(a)}}Rh(function(){md(b,g,a,e)})}return cf(g)}function Kj(a,b,c){var d=3<arguments.length&&void 0!==arguments[3]?arguments[3]:null;return{$$typeof:gb,key:null==d?null:""+d,children:a,containerInfo:b,implementation:c}}function Xh(a,b){var c=2<arguments.length&&void 0!==arguments[2]?arguments[2]:null;
+if(!bc(b))throw Error(k(200));return Kj(a,b,null,c)}if(!ea)throw Error(k(227));var ki=function(a,b,c,d,e,f,g,h,m){var n=Array.prototype.slice.call(arguments,3);try{b.apply(c,n)}catch(C){this.onError(C)}},yb=!1,gc=null,hc=!1,pd=null,li={onError:function(a){yb=!0;gc=a}},td=null,rf=null,mf=null,ic=null,cb={},jc=[],qd={},db={},rd={},wa=!("undefined"===typeof window||"undefined"===typeof window.document||"undefined"===typeof window.document.createElement),M=ea.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.assign,
+sd=null,eb=null,fb=null,ee=function(a,b){return a(b)},eg=function(a,b,c,d,e){return a(b,c,d,e)},vd=function(){},vf=ee,Oa=!1,wd=!1,Z=ea.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler,Lj=Z.unstable_cancelCallback,ff=Z.unstable_now,$f=Z.unstable_scheduleCallback,Mj=Z.unstable_shouldYield,Yh=Z.unstable_requestPaint,Pd=Z.unstable_runWithPriority,Nj=Z.unstable_getCurrentPriorityLevel,Oj=Z.unstable_ImmediatePriority,Zh=Z.unstable_UserBlockingPriority,ag=Z.unstable_NormalPriority,Pj=Z.unstable_LowPriority,
+Qj=Z.unstable_IdlePriority,oi=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,wf=Object.prototype.hasOwnProperty,yf={},xf={},E={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a){E[a]=
+new L(a,0,!1,a,null,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(a){var b=a[0];E[b]=new L(b,1,!1,a[1],null,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(a){E[a]=new L(a,2,!1,a.toLowerCase(),null,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(a){E[a]=new L(a,2,!1,a,null,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a){E[a]=
+new L(a,3,!1,a.toLowerCase(),null,!1)});["checked","multiple","muted","selected"].forEach(function(a){E[a]=new L(a,3,!0,a,null,!1)});["capture","download"].forEach(function(a){E[a]=new L(a,4,!1,a,null,!1)});["cols","rows","size","span"].forEach(function(a){E[a]=new L(a,6,!1,a,null,!1)});["rowSpan","start"].forEach(function(a){E[a]=new L(a,5,!1,a.toLowerCase(),null,!1)});var gf=/[\-:]([a-z])/g,hf=function(a){return a[1].toUpperCase()};"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a){var b=
+a.replace(gf,hf);E[b]=new L(b,1,!1,a,null,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a){var b=a.replace(gf,hf);E[b]=new L(b,1,!1,a,"http://www.w3.org/1999/xlink",!1)});["xml:base","xml:lang","xml:space"].forEach(function(a){var b=a.replace(gf,hf);E[b]=new L(b,1,!1,a,"http://www.w3.org/XML/1998/namespace",!1)});["tabIndex","crossOrigin"].forEach(function(a){E[a]=new L(a,1,!1,a.toLowerCase(),null,!1)});E.xlinkHref=new L("xlinkHref",1,
+!1,"xlink:href","http://www.w3.org/1999/xlink",!0);["src","href","action","formAction"].forEach(function(a){E[a]=new L(a,1,!1,a.toLowerCase(),null,!0)});var da=ea.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;da.hasOwnProperty("ReactCurrentDispatcher")||(da.ReactCurrentDispatcher={current:null});da.hasOwnProperty("ReactCurrentBatchConfig")||(da.ReactCurrentBatchConfig={suspense:null});var si=/^(.*)[\\\/]/,Q="function"===typeof Symbol&&Symbol.for,Pc=Q?Symbol.for("react.element"):60103,gb=Q?Symbol.for("react.portal"):
+60106,Ma=Q?Symbol.for("react.fragment"):60107,Af=Q?Symbol.for("react.strict_mode"):60108,kc=Q?Symbol.for("react.profiler"):60114,Cf=Q?Symbol.for("react.provider"):60109,Bf=Q?Symbol.for("react.context"):60110,Hj=Q?Symbol.for("react.concurrent_mode"):60111,zd=Q?Symbol.for("react.forward_ref"):60112,lc=Q?Symbol.for("react.suspense"):60113,yd=Q?Symbol.for("react.suspense_list"):60120,Ad=Q?Symbol.for("react.memo"):60115,Ef=Q?Symbol.for("react.lazy"):60116,Df=Q?Symbol.for("react.block"):60121,zf="function"===
+typeof Symbol&&Symbol.iterator,od,xh=function(a){return"undefined"!==typeof MSApp&&MSApp.execUnsafeLocalFunction?function(b,c,d,e){MSApp.execUnsafeLocalFunction(function(){return a(b,c,d,e)})}:a}(function(a,b){if("http://www.w3.org/2000/svg"!==a.namespaceURI||"innerHTML"in a)a.innerHTML=b;else{od=od||document.createElement("div");od.innerHTML="<svg>"+b.valueOf().toString()+"</svg>";for(b=od.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;b.firstChild;)a.appendChild(b.firstChild)}}),Wb=function(a,
+b){if(b){var c=a.firstChild;if(c&&c===a.lastChild&&3===c.nodeType){c.nodeValue=b;return}}a.textContent=b},ib={animationend:nc("Animation","AnimationEnd"),animationiteration:nc("Animation","AnimationIteration"),animationstart:nc("Animation","AnimationStart"),transitionend:nc("Transition","TransitionEnd")},Id={},Of={};wa&&(Of=document.createElement("div").style,"AnimationEvent"in window||(delete ib.animationend.animation,delete ib.animationiteration.animation,delete ib.animationstart.animation),"TransitionEvent"in
+window||delete ib.transitionend.transition);var $h=oc("animationend"),ai=oc("animationiteration"),bi=oc("animationstart"),ci=oc("transitionend"),Db="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),Pf=new ("function"===typeof WeakMap?WeakMap:Map),Ab=null,wi=function(a){if(a){var b=a._dispatchListeners,c=a._dispatchInstances;
+if(Array.isArray(b))for(var d=0;d<b.length&&!a.isPropagationStopped();d++)lf(a,b[d],c[d]);else b&&lf(a,b,c);a._dispatchListeners=null;a._dispatchInstances=null;a.isPersistent()||a.constructor.release(a)}},qc=[],Rd=!1,fa=[],xa=null,ya=null,za=null,Eb=new Map,Fb=new Map,Jb=[],Nd="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput close cancel copy cut paste click change contextmenu reset submit".split(" "),
+yi="focus blur dragenter dragleave mouseover mouseout pointerover pointerout gotpointercapture lostpointercapture".split(" "),dg={},cg=new Map,Td=new Map,Rj=["abort","abort",$h,"animationEnd",ai,"animationIteration",bi,"animationStart","canplay","canPlay","canplaythrough","canPlayThrough","durationchange","durationChange","emptied","emptied","encrypted","encrypted","ended","ended","error","error","gotpointercapture","gotPointerCapture","load","load","loadeddata","loadedData","loadedmetadata","loadedMetadata",
+"loadstart","loadStart","lostpointercapture","lostPointerCapture","playing","playing","progress","progress","seeking","seeking","stalled","stalled","suspend","suspend","timeupdate","timeUpdate",ci,"transitionEnd","waiting","waiting"];Sd("blur blur cancel cancel click click close close contextmenu contextMenu copy copy cut cut auxclick auxClick dblclick doubleClick dragend dragEnd dragstart dragStart drop drop focus focus input input invalid invalid keydown keyDown keypress keyPress keyup keyUp mousedown mouseDown mouseup mouseUp paste paste pause pause play play pointercancel pointerCancel pointerdown pointerDown pointerup pointerUp ratechange rateChange reset reset seeked seeked submit submit touchcancel touchCancel touchend touchEnd touchstart touchStart volumechange volumeChange".split(" "),
+0);Sd("drag drag dragenter dragEnter dragexit dragExit dragleave dragLeave dragover dragOver mousemove mouseMove mouseout mouseOut mouseover mouseOver pointermove pointerMove pointerout pointerOut pointerover pointerOver scroll scroll toggle toggle touchmove touchMove wheel wheel".split(" "),1);Sd(Rj,2);(function(a,b){for(var c=0;c<a.length;c++)Td.set(a[c],b)})("change selectionchange textInput compositionstart compositionend compositionupdate".split(" "),0);var Hi=Zh,Gi=Pd,tc=!0,Kb={animationIterationCount:!0,
+borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,
+strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},Sj=["Webkit","ms","Moz","O"];Object.keys(Kb).forEach(function(a){Sj.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);Kb[b]=Kb[a]})});var Ii=M({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0}),ng="$",og="/$",$d="$?",Zd="$!",Ze=null,$e=null,We="function"===typeof setTimeout?setTimeout:void 0,vj="function"===
+typeof clearTimeout?clearTimeout:void 0,jf=Math.random().toString(36).slice(2),Aa="__reactInternalInstance$"+jf,vc="__reactEventHandlers$"+jf,Lb="__reactContainere$"+jf,Ba=null,ce=null,wc=null;M(R.prototype,{preventDefault:function(){this.defaultPrevented=!0;var a=this.nativeEvent;a&&(a.preventDefault?a.preventDefault():"unknown"!==typeof a.returnValue&&(a.returnValue=!1),this.isDefaultPrevented=xc)},stopPropagation:function(){var a=this.nativeEvent;a&&(a.stopPropagation?a.stopPropagation():"unknown"!==
+typeof a.cancelBubble&&(a.cancelBubble=!0),this.isPropagationStopped=xc)},persist:function(){this.isPersistent=xc},isPersistent:yc,destructor:function(){var a=this.constructor.Interface,b;for(b in a)this[b]=null;this.nativeEvent=this._targetInst=this.dispatchConfig=null;this.isPropagationStopped=this.isDefaultPrevented=yc;this._dispatchInstances=this._dispatchListeners=null}});R.Interface={type:null,target:null,currentTarget:function(){return null},eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(a){return a.timeStamp||
+Date.now()},defaultPrevented:null,isTrusted:null};R.extend=function(a){function b(){return c.apply(this,arguments)}var c=this,d=function(){};d.prototype=c.prototype;d=new d;M(d,b.prototype);b.prototype=d;b.prototype.constructor=b;b.Interface=M({},c.Interface,a);b.extend=c.extend;sg(b);return b};sg(R);var Tj=R.extend({data:null}),Uj=R.extend({data:null}),Ni=[9,13,27,32],de=wa&&"CompositionEvent"in window,cc=null;wa&&"documentMode"in document&&(cc=document.documentMode);var Vj=wa&&"TextEvent"in window&&
+!cc,xg=wa&&(!de||cc&&8<cc&&11>=cc),wg=String.fromCharCode(32),ua={beforeInput:{phasedRegistrationNames:{bubbled:"onBeforeInput",captured:"onBeforeInputCapture"},dependencies:["compositionend","keypress","textInput","paste"]},compositionEnd:{phasedRegistrationNames:{bubbled:"onCompositionEnd",captured:"onCompositionEndCapture"},dependencies:"blur compositionend keydown keypress keyup mousedown".split(" ")},compositionStart:{phasedRegistrationNames:{bubbled:"onCompositionStart",captured:"onCompositionStartCapture"},
+dependencies:"blur compositionstart keydown keypress keyup mousedown".split(" ")},compositionUpdate:{phasedRegistrationNames:{bubbled:"onCompositionUpdate",captured:"onCompositionUpdateCapture"},dependencies:"blur compositionupdate keydown keypress keyup mousedown".split(" ")}},vg=!1,mb=!1,Wj={eventTypes:ua,extractEvents:function(a,b,c,d,e){var f;if(de)b:{switch(a){case "compositionstart":var g=ua.compositionStart;break b;case "compositionend":g=ua.compositionEnd;break b;case "compositionupdate":g=
+ua.compositionUpdate;break b}g=void 0}else mb?tg(a,c)&&(g=ua.compositionEnd):"keydown"===a&&229===c.keyCode&&(g=ua.compositionStart);g?(xg&&"ko"!==c.locale&&(mb||g!==ua.compositionStart?g===ua.compositionEnd&&mb&&(f=rg()):(Ba=d,ce="value"in Ba?Ba.value:Ba.textContent,mb=!0)),e=Tj.getPooled(g,b,c,d),f?e.data=f:(f=ug(c),null!==f&&(e.data=f)),lb(e),f=e):f=null;(a=Vj?Oi(a,c):Pi(a,c))?(b=Uj.getPooled(ua.beforeInput,b,c,d),b.data=a,lb(b)):b=null;return null===f?b:null===b?f:[f,b]}},Qi={color:!0,date:!0,
+datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0},Ag={change:{phasedRegistrationNames:{bubbled:"onChange",captured:"onChangeCapture"},dependencies:"blur change click focus input keydown keyup selectionchange".split(" ")}},Mb=null,Nb=null,kf=!1;wa&&(kf=Tf("input")&&(!document.documentMode||9<document.documentMode));var Xj={eventTypes:Ag,_isInputEventSupported:kf,extractEvents:function(a,b,c,d,e){e=b?Pa(b):window;var f=
+e.nodeName&&e.nodeName.toLowerCase();if("select"===f||"input"===f&&"file"===e.type)var g=Si;else if(yg(e))if(kf)g=Wi;else{g=Ui;var h=Ti}else(f=e.nodeName)&&"input"===f.toLowerCase()&&("checkbox"===e.type||"radio"===e.type)&&(g=Vi);if(g&&(g=g(a,b)))return zg(g,c,d);h&&h(a,e,b);"blur"===a&&(a=e._wrapperState)&&a.controlled&&"number"===e.type&&Ed(e,"number",e.value)}},dc=R.extend({view:null,detail:null}),Yi={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"},di=0,ei=0,fi=!1,gi=!1,ec=dc.extend({screenX:null,
+screenY:null,clientX:null,clientY:null,pageX:null,pageY:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,getModifierState:fe,button:null,buttons:null,relatedTarget:function(a){return a.relatedTarget||(a.fromElement===a.srcElement?a.toElement:a.fromElement)},movementX:function(a){if("movementX"in a)return a.movementX;var b=di;di=a.screenX;return fi?"mousemove"===a.type?a.screenX-b:0:(fi=!0,0)},movementY:function(a){if("movementY"in a)return a.movementY;var b=ei;ei=a.screenY;return gi?"mousemove"===
+a.type?a.screenY-b:0:(gi=!0,0)}}),hi=ec.extend({pointerId:null,width:null,height:null,pressure:null,tangentialPressure:null,tiltX:null,tiltY:null,twist:null,pointerType:null,isPrimary:null}),fc={mouseEnter:{registrationName:"onMouseEnter",dependencies:["mouseout","mouseover"]},mouseLeave:{registrationName:"onMouseLeave",dependencies:["mouseout","mouseover"]},pointerEnter:{registrationName:"onPointerEnter",dependencies:["pointerout","pointerover"]},pointerLeave:{registrationName:"onPointerLeave",dependencies:["pointerout",
+"pointerover"]}},Yj={eventTypes:fc,extractEvents:function(a,b,c,d,e){var f="mouseover"===a||"pointerover"===a,g="mouseout"===a||"pointerout"===a;if(f&&0===(e&32)&&(c.relatedTarget||c.fromElement)||!g&&!f)return null;f=d.window===d?d:(f=d.ownerDocument)?f.defaultView||f.parentWindow:window;if(g){if(g=b,b=(b=c.relatedTarget||c.toElement)?Bb(b):null,null!==b){var h=Na(b);if(b!==h||5!==b.tag&&6!==b.tag)b=null}}else g=null;if(g===b)return null;if("mouseout"===a||"mouseover"===a){var m=ec;var n=fc.mouseLeave;
+var l=fc.mouseEnter;var k="mouse"}else if("pointerout"===a||"pointerover"===a)m=hi,n=fc.pointerLeave,l=fc.pointerEnter,k="pointer";a=null==g?f:Pa(g);f=null==b?f:Pa(b);n=m.getPooled(n,g,c,d);n.type=k+"leave";n.target=a;n.relatedTarget=f;c=m.getPooled(l,b,c,d);c.type=k+"enter";c.target=f;c.relatedTarget=a;d=g;k=b;if(d&&k)a:{m=d;l=k;g=0;for(a=m;a;a=pa(a))g++;a=0;for(b=l;b;b=pa(b))a++;for(;0<g-a;)m=pa(m),g--;for(;0<a-g;)l=pa(l),a--;for(;g--;){if(m===l||m===l.alternate)break a;m=pa(m);l=pa(l)}m=null}else m=
+null;l=m;for(m=[];d&&d!==l;){g=d.alternate;if(null!==g&&g===l)break;m.push(d);d=pa(d)}for(d=[];k&&k!==l;){g=k.alternate;if(null!==g&&g===l)break;d.push(k);k=pa(k)}for(k=0;k<m.length;k++)be(m[k],"bubbled",n);for(k=d.length;0<k--;)be(d[k],"captured",c);return 0===(e&64)?[n]:[n,c]}},Qa="function"===typeof Object.is?Object.is:Zi,$i=Object.prototype.hasOwnProperty,Zj=wa&&"documentMode"in document&&11>=document.documentMode,Eg={select:{phasedRegistrationNames:{bubbled:"onSelect",captured:"onSelectCapture"},
+dependencies:"blur contextmenu dragend focus keydown keyup mousedown mouseup selectionchange".split(" ")}},nb=null,he=null,Pb=null,ge=!1,ak={eventTypes:Eg,extractEvents:function(a,b,c,d,e,f){e=f||(d.window===d?d.document:9===d.nodeType?d:d.ownerDocument);if(!(f=!e)){a:{e=Jd(e);f=rd.onSelect;for(var g=0;g<f.length;g++)if(!e.has(f[g])){e=!1;break a}e=!0}f=!e}if(f)return null;e=b?Pa(b):window;switch(a){case "focus":if(yg(e)||"true"===e.contentEditable)nb=e,he=b,Pb=null;break;case "blur":Pb=he=nb=null;
+break;case "mousedown":ge=!0;break;case "contextmenu":case "mouseup":case "dragend":return ge=!1,Dg(c,d);case "selectionchange":if(Zj)break;case "keydown":case "keyup":return Dg(c,d)}return null}},bk=R.extend({animationName:null,elapsedTime:null,pseudoElement:null}),ck=R.extend({clipboardData:function(a){return"clipboardData"in a?a.clipboardData:window.clipboardData}}),dk=dc.extend({relatedTarget:null}),ek={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",
+Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},fk={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",
+224:"Meta"},gk=dc.extend({key:function(a){if(a.key){var b=ek[a.key]||a.key;if("Unidentified"!==b)return b}return"keypress"===a.type?(a=Ac(a),13===a?"Enter":String.fromCharCode(a)):"keydown"===a.type||"keyup"===a.type?fk[a.keyCode]||"Unidentified":""},location:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,repeat:null,locale:null,getModifierState:fe,charCode:function(a){return"keypress"===a.type?Ac(a):0},keyCode:function(a){return"keydown"===a.type||"keyup"===a.type?a.keyCode:0},which:function(a){return"keypress"===
+a.type?Ac(a):"keydown"===a.type||"keyup"===a.type?a.keyCode:0}}),hk=ec.extend({dataTransfer:null}),ik=dc.extend({touches:null,targetTouches:null,changedTouches:null,altKey:null,metaKey:null,ctrlKey:null,shiftKey:null,getModifierState:fe}),jk=R.extend({propertyName:null,elapsedTime:null,pseudoElement:null}),kk=ec.extend({deltaX:function(a){return"deltaX"in a?a.deltaX:"wheelDeltaX"in a?-a.wheelDeltaX:0},deltaY:function(a){return"deltaY"in a?a.deltaY:"wheelDeltaY"in a?-a.wheelDeltaY:"wheelDelta"in a?
+-a.wheelDelta:0},deltaZ:null,deltaMode:null}),lk={eventTypes:dg,extractEvents:function(a,b,c,d,e){e=cg.get(a);if(!e)return null;switch(a){case "keypress":if(0===Ac(c))return null;case "keydown":case "keyup":a=gk;break;case "blur":case "focus":a=dk;break;case "click":if(2===c.button)return null;case "auxclick":case "dblclick":case "mousedown":case "mousemove":case "mouseup":case "mouseout":case "mouseover":case "contextmenu":a=ec;break;case "drag":case "dragend":case "dragenter":case "dragexit":case "dragleave":case "dragover":case "dragstart":case "drop":a=
+hk;break;case "touchcancel":case "touchend":case "touchmove":case "touchstart":a=ik;break;case $h:case ai:case bi:a=bk;break;case ci:a=jk;break;case "scroll":a=dc;break;case "wheel":a=kk;break;case "copy":case "cut":case "paste":a=ck;break;case "gotpointercapture":case "lostpointercapture":case "pointercancel":case "pointerdown":case "pointermove":case "pointerout":case "pointerover":case "pointerup":a=hi;break;default:a=R}b=a.getPooled(e,b,c,d);lb(b);return b}};(function(a){if(ic)throw Error(k(101));
+ic=Array.prototype.slice.call(a);nf()})("ResponderEventPlugin SimpleEventPlugin EnterLeaveEventPlugin ChangeEventPlugin SelectEventPlugin BeforeInputEventPlugin".split(" "));(function(a,b,c){td=a;rf=b;mf=c})(ae,Hb,Pa);pf({SimpleEventPlugin:lk,EnterLeaveEventPlugin:Yj,ChangeEventPlugin:Xj,SelectEventPlugin:ak,BeforeInputEventPlugin:Wj});var ie=[],ob=-1,Ca={},B={current:Ca},G={current:!1},Ra=Ca,bj=Pd,je=$f,Rg=Lj,aj=Nj,Dc=Oj,Ig=Zh,Jg=ag,Kg=Pj,Lg=Qj,Qg={},yj=Mj,Cj=void 0!==Yh?Yh:function(){},qa=null,
+Ec=null,ke=!1,ii=ff(),Y=1E4>ii?ff:function(){return ff()-ii},Ic={current:null},Hc=null,qb=null,Gc=null,Tg=0,Jc=2,Ga=!1,Vb=da.ReactCurrentBatchConfig,$g=(new ea.Component).refs,Mc={isMounted:function(a){return(a=a._reactInternalFiber)?Na(a)===a:!1},enqueueSetState:function(a,b,c){a=a._reactInternalFiber;var d=ka(),e=Vb.suspense;d=Va(d,a,e);e=Ea(d,e);e.payload=b;void 0!==c&&null!==c&&(e.callback=c);Fa(a,e);Ja(a,d)},enqueueReplaceState:function(a,b,c){a=a._reactInternalFiber;var d=ka(),e=Vb.suspense;
+d=Va(d,a,e);e=Ea(d,e);e.tag=1;e.payload=b;void 0!==c&&null!==c&&(e.callback=c);Fa(a,e);Ja(a,d)},enqueueForceUpdate:function(a,b){a=a._reactInternalFiber;var c=ka(),d=Vb.suspense;c=Va(c,a,d);d=Ea(c,d);d.tag=Jc;void 0!==b&&null!==b&&(d.callback=b);Fa(a,d);Ja(a,c)}},Qc=Array.isArray,wb=ah(!0),Fe=ah(!1),Sb={},ja={current:Sb},Ub={current:Sb},Tb={current:Sb},D={current:0},Sc=da.ReactCurrentDispatcher,X=da.ReactCurrentBatchConfig,Ia=0,z=null,K=null,J=null,Uc=!1,Tc={readContext:W,useCallback:S,useContext:S,
+useEffect:S,useImperativeHandle:S,useLayoutEffect:S,useMemo:S,useReducer:S,useRef:S,useState:S,useDebugValue:S,useResponder:S,useDeferredValue:S,useTransition:S},dj={readContext:W,useCallback:ih,useContext:W,useEffect:eh,useImperativeHandle:function(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return ze(4,2,gh.bind(null,b,a),c)},useLayoutEffect:function(a,b){return ze(4,2,a,b)},useMemo:function(a,b){var c=ub();b=void 0===b?null:b;a=a();c.memoizedState=[a,b];return a},useReducer:function(a,b,c){var d=
+ub();b=void 0!==c?c(b):b;d.memoizedState=d.baseState=b;a=d.queue={pending:null,dispatch:null,lastRenderedReducer:a,lastRenderedState:b};a=a.dispatch=ch.bind(null,z,a);return[d.memoizedState,a]},useRef:function(a){var b=ub();a={current:a};return b.memoizedState=a},useState:xe,useDebugValue:Be,useResponder:ue,useDeferredValue:function(a,b){var c=xe(a),d=c[0],e=c[1];eh(function(){var c=X.suspense;X.suspense=void 0===b?null:b;try{e(a)}finally{X.suspense=c}},[a,b]);return d},useTransition:function(a){var b=
+xe(!1),c=b[0];b=b[1];return[ih(Ce.bind(null,b,a),[b,a]),c]}},ej={readContext:W,useCallback:Yc,useContext:W,useEffect:Xc,useImperativeHandle:hh,useLayoutEffect:fh,useMemo:jh,useReducer:Vc,useRef:dh,useState:function(a){return Vc(Ua)},useDebugValue:Be,useResponder:ue,useDeferredValue:function(a,b){var c=Vc(Ua),d=c[0],e=c[1];Xc(function(){var c=X.suspense;X.suspense=void 0===b?null:b;try{e(a)}finally{X.suspense=c}},[a,b]);return d},useTransition:function(a){var b=Vc(Ua),c=b[0];b=b[1];return[Yc(Ce.bind(null,
+b,a),[b,a]),c]}},fj={readContext:W,useCallback:Yc,useContext:W,useEffect:Xc,useImperativeHandle:hh,useLayoutEffect:fh,useMemo:jh,useReducer:Wc,useRef:dh,useState:function(a){return Wc(Ua)},useDebugValue:Be,useResponder:ue,useDeferredValue:function(a,b){var c=Wc(Ua),d=c[0],e=c[1];Xc(function(){var c=X.suspense;X.suspense=void 0===b?null:b;try{e(a)}finally{X.suspense=c}},[a,b]);return d},useTransition:function(a){var b=Wc(Ua),c=b[0];b=b[1];return[Yc(Ce.bind(null,b,a),[b,a]),c]}},ra=null,Ka=null,Wa=
+!1,gj=da.ReactCurrentOwner,ia=!1,Je={dehydrated:null,retryTime:0};var jj=function(a,b,c,d){for(c=b.child;null!==c;){if(5===c.tag||6===c.tag)a.appendChild(c.stateNode);else if(4!==c.tag&&null!==c.child){c.child.return=c;c=c.child;continue}if(c===b)break;for(;null===c.sibling;){if(null===c.return||c.return===b)return;c=c.return}c.sibling.return=c.return;c=c.sibling}};var wh=function(a){};var ij=function(a,b,c,d,e){var f=a.memoizedProps;if(f!==d){var g=b.stateNode;Ta(ja.current);a=null;switch(c){case "input":f=
+Cd(g,f);d=Cd(g,d);a=[];break;case "option":f=Fd(g,f);d=Fd(g,d);a=[];break;case "select":f=M({},f,{value:void 0});d=M({},d,{value:void 0});a=[];break;case "textarea":f=Gd(g,f);d=Gd(g,d);a=[];break;default:"function"!==typeof f.onClick&&"function"===typeof d.onClick&&(g.onclick=uc)}Ud(c,d);var h,m;c=null;for(h in f)if(!d.hasOwnProperty(h)&&f.hasOwnProperty(h)&&null!=f[h])if("style"===h)for(m in g=f[h],g)g.hasOwnProperty(m)&&(c||(c={}),c[m]="");else"dangerouslySetInnerHTML"!==h&&"children"!==h&&"suppressContentEditableWarning"!==
+h&&"suppressHydrationWarning"!==h&&"autoFocus"!==h&&(db.hasOwnProperty(h)?a||(a=[]):(a=a||[]).push(h,null));for(h in d){var k=d[h];g=null!=f?f[h]:void 0;if(d.hasOwnProperty(h)&&k!==g&&(null!=k||null!=g))if("style"===h)if(g){for(m in g)!g.hasOwnProperty(m)||k&&k.hasOwnProperty(m)||(c||(c={}),c[m]="");for(m in k)k.hasOwnProperty(m)&&g[m]!==k[m]&&(c||(c={}),c[m]=k[m])}else c||(a||(a=[]),a.push(h,c)),c=k;else"dangerouslySetInnerHTML"===h?(k=k?k.__html:void 0,g=g?g.__html:void 0,null!=k&&g!==k&&(a=a||
+[]).push(h,k)):"children"===h?g===k||"string"!==typeof k&&"number"!==typeof k||(a=a||[]).push(h,""+k):"suppressContentEditableWarning"!==h&&"suppressHydrationWarning"!==h&&(db.hasOwnProperty(h)?(null!=k&&oa(e,h),a||g===k||(a=[])):(a=a||[]).push(h,k))}c&&(a=a||[]).push("style",c);e=a;if(b.updateQueue=e)b.effectTag|=4}};var kj=function(a,b,c,d){c!==d&&(b.effectTag|=4)};var pj="function"===typeof WeakSet?WeakSet:Set,wj="function"===typeof WeakMap?WeakMap:Map,sj=Math.ceil,gd=da.ReactCurrentDispatcher,
+Uh=da.ReactCurrentOwner,H=0,Ye=8,ca=16,ma=32,Xa=0,hd=1,Oh=2,ad=3,bd=4,Xe=5,p=H,U=null,t=null,P=0,F=Xa,id=null,ta=1073741823,Yb=1073741823,kd=null,Xb=0,jd=!1,Re=0,Ph=500,l=null,cd=!1,Se=null,La=null,ld=!1,Zb=null,$b=90,bb=null,ac=0,af=null,dd=0,Ja=function(a,b){if(50<ac)throw ac=0,af=null,Error(k(185));a=ed(a,b);if(null!==a){var c=Cc();1073741823===b?(p&Ye)!==H&&(p&(ca|ma))===H?Te(a):(V(a),p===H&&ha()):V(a);(p&4)===H||98!==c&&99!==c||(null===bb?bb=new Map([[a,b]]):(c=bb.get(a),(void 0===c||c>b)&&bb.set(a,
+b)))}};var zj=function(a,b,c){var d=b.expirationTime;if(null!==a){var e=b.pendingProps;if(a.memoizedProps!==e||G.current)ia=!0;else{if(d<c){ia=!1;switch(b.tag){case 3:sh(b);Ee();break;case 5:bh(b);if(b.mode&4&&1!==c&&e.hidden)return b.expirationTime=b.childExpirationTime=1,null;break;case 1:N(b.type)&&Bc(b);break;case 4:se(b,b.stateNode.containerInfo);break;case 10:d=b.memoizedProps.value;e=b.type._context;y(Ic,e._currentValue);e._currentValue=d;break;case 13:if(null!==b.memoizedState){d=b.child.childExpirationTime;
+if(0!==d&&d>=c)return th(a,b,c);y(D,D.current&1);b=sa(a,b,c);return null!==b?b.sibling:null}y(D,D.current&1);break;case 19:d=b.childExpirationTime>=c;if(0!==(a.effectTag&64)){if(d)return vh(a,b,c);b.effectTag|=64}e=b.memoizedState;null!==e&&(e.rendering=null,e.tail=null);y(D,D.current);if(!d)return null}return sa(a,b,c)}ia=!1}}else ia=!1;b.expirationTime=0;switch(b.tag){case 2:d=b.type;null!==a&&(a.alternate=null,b.alternate=null,b.effectTag|=2);a=b.pendingProps;e=pb(b,B.current);rb(b,c);e=we(null,
+b,d,a,e,c);b.effectTag|=1;if("object"===typeof e&&null!==e&&"function"===typeof e.render&&void 0===e.$$typeof){b.tag=1;b.memoizedState=null;b.updateQueue=null;if(N(d)){var f=!0;Bc(b)}else f=!1;b.memoizedState=null!==e.state&&void 0!==e.state?e.state:null;ne(b);var g=d.getDerivedStateFromProps;"function"===typeof g&&Lc(b,d,g,a);e.updater=Mc;b.stateNode=e;e._reactInternalFiber=b;pe(b,d,a,c);b=Ie(null,b,d,!0,f,c)}else b.tag=0,T(null,b,e,c),b=b.child;return b;case 16:a:{e=b.elementType;null!==a&&(a.alternate=
+null,b.alternate=null,b.effectTag|=2);a=b.pendingProps;ri(e);if(1!==e._status)throw e._result;e=e._result;b.type=e;f=b.tag=Gj(e);a=aa(e,a);switch(f){case 0:b=He(null,b,e,a,c);break a;case 1:b=rh(null,b,e,a,c);break a;case 11:b=nh(null,b,e,a,c);break a;case 14:b=oh(null,b,e,aa(e.type,a),d,c);break a}throw Error(k(306,e,""));}return b;case 0:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:aa(d,e),He(a,b,d,e,c);case 1:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:aa(d,e),rh(a,b,d,e,c);
+case 3:sh(b);d=b.updateQueue;if(null===a||null===d)throw Error(k(282));d=b.pendingProps;e=b.memoizedState;e=null!==e?e.element:null;oe(a,b);Qb(b,d,null,c);d=b.memoizedState.element;if(d===e)Ee(),b=sa(a,b,c);else{if(e=b.stateNode.hydrate)Ka=kb(b.stateNode.containerInfo.firstChild),ra=b,e=Wa=!0;if(e)for(c=Fe(b,null,d,c),b.child=c;c;)c.effectTag=c.effectTag&-3|1024,c=c.sibling;else T(a,b,d,c),Ee();b=b.child}return b;case 5:return bh(b),null===a&&De(b),d=b.type,e=b.pendingProps,f=null!==a?a.memoizedProps:
+null,g=e.children,Yd(d,e)?g=null:null!==f&&Yd(d,f)&&(b.effectTag|=16),qh(a,b),b.mode&4&&1!==c&&e.hidden?(b.expirationTime=b.childExpirationTime=1,b=null):(T(a,b,g,c),b=b.child),b;case 6:return null===a&&De(b),null;case 13:return th(a,b,c);case 4:return se(b,b.stateNode.containerInfo),d=b.pendingProps,null===a?b.child=wb(b,null,d,c):T(a,b,d,c),b.child;case 11:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:aa(d,e),nh(a,b,d,e,c);case 7:return T(a,b,b.pendingProps,c),b.child;case 8:return T(a,
+b,b.pendingProps.children,c),b.child;case 12:return T(a,b,b.pendingProps.children,c),b.child;case 10:a:{d=b.type._context;e=b.pendingProps;g=b.memoizedProps;f=e.value;var h=b.type._context;y(Ic,h._currentValue);h._currentValue=f;if(null!==g)if(h=g.value,f=Qa(h,f)?0:("function"===typeof d._calculateChangedBits?d._calculateChangedBits(h,f):1073741823)|0,0===f){if(g.children===e.children&&!G.current){b=sa(a,b,c);break a}}else for(h=b.child,null!==h&&(h.return=b);null!==h;){var m=h.dependencies;if(null!==
+m){g=h.child;for(var l=m.firstContext;null!==l;){if(l.context===d&&0!==(l.observedBits&f)){1===h.tag&&(l=Ea(c,null),l.tag=Jc,Fa(h,l));h.expirationTime<c&&(h.expirationTime=c);l=h.alternate;null!==l&&l.expirationTime<c&&(l.expirationTime=c);Sg(h.return,c);m.expirationTime<c&&(m.expirationTime=c);break}l=l.next}}else g=10===h.tag?h.type===b.type?null:h.child:h.child;if(null!==g)g.return=h;else for(g=h;null!==g;){if(g===b){g=null;break}h=g.sibling;if(null!==h){h.return=g.return;g=h;break}g=g.return}h=
+g}T(a,b,e.children,c);b=b.child}return b;case 9:return e=b.type,f=b.pendingProps,d=f.children,rb(b,c),e=W(e,f.unstable_observedBits),d=d(e),b.effectTag|=1,T(a,b,d,c),b.child;case 14:return e=b.type,f=aa(e,b.pendingProps),f=aa(e.type,f),oh(a,b,e,f,d,c);case 15:return ph(a,b,b.type,b.pendingProps,d,c);case 17:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:aa(d,e),null!==a&&(a.alternate=null,b.alternate=null,b.effectTag|=2),b.tag=1,N(d)?(a=!0,Bc(b)):a=!1,rb(b,c),Yg(b,d,e),pe(b,d,e,c),Ie(null,
+b,d,!0,a,c);case 19:return vh(a,b,c)}throw Error(k(156,b.tag));};var bf=null,Ne=null,la=function(a,b,c,d){return new Fj(a,b,c,d)};ef.prototype.render=function(a){md(a,this._internalRoot,null,null)};ef.prototype.unmount=function(){var a=this._internalRoot,b=a.containerInfo;md(null,a,null,function(){b[Lb]=null})};var Di=function(a){if(13===a.tag){var b=Fc(ka(),150,100);Ja(a,b);df(a,b)}};var Yf=function(a){13===a.tag&&(Ja(a,3),df(a,3))};var Bi=function(a){if(13===a.tag){var b=ka();b=Va(b,a,null);Ja(a,
+b);df(a,b)}};sd=function(a,b,c){switch(b){case "input":Dd(a,c);b=c.name;if("radio"===c.type&&null!=b){for(c=a;c.parentNode;)c=c.parentNode;c=c.querySelectorAll("input[name="+JSON.stringify(""+b)+'][type="radio"]');for(b=0;b<c.length;b++){var d=c[b];if(d!==a&&d.form===a.form){var e=ae(d);if(!e)throw Error(k(90));Gf(d);Dd(d,e)}}}break;case "textarea":Lf(a,c);break;case "select":b=c.value,null!=b&&hb(a,!!c.multiple,b,!1)}};(function(a,b,c,d){ee=a;eg=b;vd=c;vf=d})(Qh,function(a,b,c,d,e){var f=p;p|=4;
+try{return Da(98,a.bind(null,b,c,d,e))}finally{p=f,p===H&&ha()}},function(){(p&(1|ca|ma))===H&&(uj(),xb())},function(a,b){var c=p;p|=2;try{return a(b)}finally{p=c,p===H&&ha()}});var mk={Events:[Hb,Pa,ae,pf,qd,lb,function(a){Kd(a,Ki)},sf,tf,sc,pc,xb,{current:!1}]};(function(a){var b=a.findFiberByHostInstance;return Ej(M({},a,{overrideHookState:null,overrideProps:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:da.ReactCurrentDispatcher,findHostInstanceByFiber:function(a){a=Sf(a);
+return null===a?null:a.stateNode},findFiberByHostInstance:function(a){return b?b(a):null},findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null}))})({findFiberByHostInstance:Bb,bundleType:0,version:"16.13.1",rendererPackageName:"react-dom"});I.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=mk;I.createPortal=Xh;I.findDOMNode=function(a){if(null==a)return null;if(1===a.nodeType)return a;var b=a._reactInternalFiber;if(void 0===
+b){if("function"===typeof a.render)throw Error(k(188));throw Error(k(268,Object.keys(a)));}a=Sf(b);a=null===a?null:a.stateNode;return a};I.flushSync=function(a,b){if((p&(ca|ma))!==H)throw Error(k(187));var c=p;p|=1;try{return Da(99,a.bind(null,b))}finally{p=c,ha()}};I.hydrate=function(a,b,c){if(!bc(b))throw Error(k(200));return nd(null,a,b,!0,c)};I.render=function(a,b,c){if(!bc(b))throw Error(k(200));return nd(null,a,b,!1,c)};I.unmountComponentAtNode=function(a){if(!bc(a))throw Error(k(40));return a._reactRootContainer?
+(Rh(function(){nd(null,null,a,!1,function(){a._reactRootContainer=null;a[Lb]=null})}),!0):!1};I.unstable_batchedUpdates=Qh;I.unstable_createPortal=function(a,b){return Xh(a,b,2<arguments.length&&void 0!==arguments[2]?arguments[2]:null)};I.unstable_renderSubtreeIntoContainer=function(a,b,c,d){if(!bc(c))throw Error(k(200));if(null==a||void 0===a._reactInternalFiber)throw Error(k(38));return nd(a,b,c,!1,d)};I.version="16.13.1"});
diff --git a/browser/components/newtab/vendor/react-redux.js b/browser/components/newtab/vendor/react-redux.js
new file mode 100644
index 0000000000..8cab576f2d
--- /dev/null
+++ b/browser/components/newtab/vendor/react-redux.js
@@ -0,0 +1 @@
+!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react"),require("redux"),require("react-dom")):"function"==typeof define&&define.amd?define(["exports","react","redux","react-dom"],t):t((e=e||self).ReactRedux={},e.React,e.Redux,e.ReactDOM)}(this,function(e,t,r,n){"use strict";var o="default"in t?t.default:t;function u(e,t){return e(t={exports:{}},t.exports),t.exports}var a="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED";function i(){}function c(){}c.resetWarningCache=i;u(function(e){e.exports=function(){function e(e,t,r,n,o,u){if(u!==a){var i=Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw i.name="Invariant Violation",i}}function t(){return e}e.isRequired=e;var r={array:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,elementType:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t,checkPropTypes:c,resetWarningCache:i};return r.PropTypes=r,r}()});var s=o.createContext(null);var f=function(e){e()},p=function(){return f},l={notify:function(){}};var d=function(){function e(e,t){this.store=e,this.parentSub=t,this.unsubscribe=null,this.listeners=l,this.handleChangeWrapper=this.handleChangeWrapper.bind(this)}var t=e.prototype;return t.addNestedSub=function(e){return this.trySubscribe(),this.listeners.subscribe(e)},t.notifyNestedSubs=function(){this.listeners.notify()},t.handleChangeWrapper=function(){this.onStateChange&&this.onStateChange()},t.isSubscribed=function(){return!!this.unsubscribe},t.trySubscribe=function(){this.unsubscribe||(this.unsubscribe=this.parentSub?this.parentSub.addNestedSub(this.handleChangeWrapper):this.store.subscribe(this.handleChangeWrapper),this.listeners=function(){var e=p(),t=null,r=null;return{clear:function(){t=null,r=null},notify:function(){e(function(){for(var e=t;e;)e.callback(),e=e.next})},get:function(){for(var e=[],r=t;r;)e.push(r),r=r.next;return e},subscribe:function(e){var n=!0,o=r={callback:e,next:null,prev:r};return o.prev?o.prev.next=o:t=o,function(){n&&null!==t&&(n=!1,o.next?o.next.prev=o.prev:r=o.prev,o.prev?o.prev.next=o.next:t=o.next)}}}}())},t.tryUnsubscribe=function(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null,this.listeners.clear(),this.listeners=l)},e}();function y(){return(y=Object.assign||function(e){for(var t=1;arguments.length>t;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e}).apply(this,arguments)}function v(e,t){if(null==e)return{};var r,n,o={},u=Object.keys(e);for(n=0;u.length>n;n++)0>t.indexOf(r=u[n])&&(o[r]=e[r]);return o}var m,b=u(function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var r="function"==typeof Symbol&&Symbol.for,n=r?Symbol.for("react.element"):60103,o=r?Symbol.for("react.portal"):60106,u=r?Symbol.for("react.fragment"):60107,a=r?Symbol.for("react.strict_mode"):60108,i=r?Symbol.for("react.profiler"):60114,c=r?Symbol.for("react.provider"):60109,s=r?Symbol.for("react.context"):60110,f=r?Symbol.for("react.async_mode"):60111,p=r?Symbol.for("react.concurrent_mode"):60111,l=r?Symbol.for("react.forward_ref"):60112,d=r?Symbol.for("react.suspense"):60113,y=r?Symbol.for("react.suspense_list"):60120,v=r?Symbol.for("react.memo"):60115,m=r?Symbol.for("react.lazy"):60116,b=r?Symbol.for("react.fundamental"):60117,h=r?Symbol.for("react.responder"):60118;function S(e){if("object"==typeof e&&null!==e){var t=e.$$typeof;switch(t){case n:switch(e=e.type){case f:case p:case u:case i:case a:case d:return e;default:switch(e=e&&e.$$typeof){case s:case l:case c:return e;default:return t}}case m:case v:case o:return t}}}function P(e){return S(e)===p}t.typeOf=S,t.AsyncMode=f,t.ConcurrentMode=p,t.ContextConsumer=s,t.ContextProvider=c,t.Element=n,t.ForwardRef=l,t.Fragment=u,t.Lazy=m,t.Memo=v,t.Portal=o,t.Profiler=i,t.StrictMode=a,t.Suspense=d,t.isValidElementType=function(e){return"string"==typeof e||"function"==typeof e||e===u||e===p||e===i||e===a||e===d||e===y||"object"==typeof e&&null!==e&&(e.$$typeof===m||e.$$typeof===v||e.$$typeof===c||e.$$typeof===s||e.$$typeof===l||e.$$typeof===b||e.$$typeof===h)},t.isAsyncMode=function(e){return P(e)||S(e)===f},t.isConcurrentMode=P,t.isContextConsumer=function(e){return S(e)===s},t.isContextProvider=function(e){return S(e)===c},t.isElement=function(e){return"object"==typeof e&&null!==e&&e.$$typeof===n},t.isForwardRef=function(e){return S(e)===l},t.isFragment=function(e){return S(e)===u},t.isLazy=function(e){return S(e)===m},t.isMemo=function(e){return S(e)===v},t.isPortal=function(e){return S(e)===o},t.isProfiler=function(e){return S(e)===i},t.isStrictMode=function(e){return S(e)===a},t.isSuspense=function(e){return S(e)===d}});(m=b)&&m.__esModule&&Object.prototype.hasOwnProperty.call(m,"default");var h=u(function(e){e.exports=b}),S=h.isContextConsumer,P={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},g={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},O={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},w={};function C(e){return h.isMemo(e)?O:w[e.$$typeof]||P}w[h.ForwardRef]={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0};var x=Object.defineProperty,E=Object.getOwnPropertyNames,M=Object.getOwnPropertySymbols,T=Object.getOwnPropertyDescriptor,R=Object.getPrototypeOf,$=Object.prototype;var j=function e(t,r,n){if("string"!=typeof r){if($){var o=R(r);o&&o!==$&&e(t,o,n)}var u=E(r);M&&(u=u.concat(M(r)));for(var a=C(t),i=C(r),c=0;u.length>c;++c){var s=u[c];if(!(g[s]||n&&n[s]||i&&i[s]||a&&a[s])){var f=T(r,s);try{x(t,s,f)}catch(e){}}}return t}return t},N="undefined"!=typeof window&&void 0!==window.document&&void 0!==window.document.createElement?t.useLayoutEffect:t.useEffect,_=[],q=[null,null];function D(e,t){return[t.payload,e[1]+1]}function k(e,t,r){N(function(){return e.apply(void 0,t)},r)}function F(e,t,r,n,o,u,a){e.current=n,t.current=o,r.current=!1,u.current&&(u.current=null,a())}function W(e,t,r,n,o,u,a,i,c,s){if(e){var f=!1,p=null,l=function(){if(!f){var e,r,l=t.getState();try{e=n(l,o.current)}catch(e){r=e,p=e}r||(p=null),e===u.current?a.current||c():(u.current=e,i.current=e,a.current=!0,s({type:"STORE_UPDATED",payload:{error:r}}))}};r.onStateChange=l,r.trySubscribe(),l();return function(){if(f=!0,r.tryUnsubscribe(),r.onStateChange=null,p)throw p}}}var H=function(){return[null,0]};function U(e,r){void 0===r&&(r={});var n=r.getDisplayName,u=void 0===n?function(e){return"ConnectAdvanced("+e+")"}:n,a=r.methodName,i=void 0===a?"connectAdvanced":a,c=r.renderCountProp,f=void 0===c?void 0:c,p=r.shouldHandleStateChanges,l=void 0===p||p,m=r.storeKey,b=void 0===m?"store":m,h=r.forwardRef,P=void 0!==h&&h,g=r.context,O=void 0===g?s:g,w=v(r,["getDisplayName","methodName","renderCountProp","shouldHandleStateChanges","storeKey","withRef","forwardRef","context"]),C=O;return function(r){var n=r.displayName||r.name||"Component",a=u(n),c=y({},w,{getDisplayName:u,methodName:i,renderCountProp:f,shouldHandleStateChanges:l,storeKey:b,displayName:a,wrappedComponentName:n,WrappedComponent:r}),s=w.pure;var p=s?t.useMemo:function(e){return e()};function m(n){var u=t.useMemo(function(){var e=n.forwardedRef,t=v(n,["forwardedRef"]);return[n.context,e,t]},[n]),a=u[0],i=u[1],s=u[2],f=t.useMemo(function(){return a&&a.Consumer&&S(o.createElement(a.Consumer,null))?a:C},[a,C]),m=t.useContext(f),b=!!n.store&&!!n.store.getState&&!!n.store.dispatch,h=b?n.store:m.store,P=t.useMemo(function(){return function(t){return e(t.dispatch,c)}(h)},[h]),g=t.useMemo(function(){if(!l)return q;var e=new d(h,b?null:m.subscription),t=e.notifyNestedSubs.bind(e);return[e,t]},[h,b,m]),O=g[0],w=g[1],x=t.useMemo(function(){return b?m:y({},m,{subscription:O})},[b,m,O]),E=t.useReducer(D,_,H),M=E[0][0],T=E[1];if(M&&M.error)throw M.error;var R=t.useRef(),$=t.useRef(s),j=t.useRef(),N=t.useRef(!1),U=p(function(){return j.current&&s===$.current?j.current:P(h.getState(),s)},[h,M,s]);k(F,[$,R,N,s,U,j,w]),k(W,[l,h,O,P,$,R,N,j,w,T],[h,O,P]);var A=t.useMemo(function(){return o.createElement(r,y({},U,{ref:i}))},[i,r,U]);return t.useMemo(function(){return l?o.createElement(f.Provider,{value:x},A):A},[f,A,x])}var h=s?o.memo(m):m;if(h.WrappedComponent=r,h.displayName=a,P){var g=o.forwardRef(function(e,t){return o.createElement(h,y({},e,{forwardedRef:t}))});return g.displayName=a,g.WrappedComponent=r,j(g,r)}return j(h,r)}}function A(e,t){return e===t?0!==e||0!==t||1/e==1/t:e!=e&&t!=t}function I(e,t){if(A(e,t))return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var r=Object.keys(e);if(r.length!==Object.keys(t).length)return!1;for(var n=0;r.length>n;n++)if(!Object.prototype.hasOwnProperty.call(t,r[n])||!A(e[r[n]],t[r[n]]))return!1;return!0}function L(e){return function(t,r){var n=e(t,r);function o(){return n}return o.dependsOnOwnProps=!1,o}}function z(e){return null!=e.dependsOnOwnProps?!!e.dependsOnOwnProps:1!==e.length}function K(e,t){return function(t,r){var n=function(e,t){return n.dependsOnOwnProps?n.mapToProps(e,t):n.mapToProps(e)};return n.dependsOnOwnProps=!0,n.mapToProps=function(t,r){n.mapToProps=e,n.dependsOnOwnProps=z(e);var o=n(t,r);return"function"==typeof o&&(n.mapToProps=o,n.dependsOnOwnProps=z(o),o=n(t,r)),o},n}}var V=[function(e){return"function"==typeof e?K(e):void 0},function(e){return e?void 0:L(function(e){return{dispatch:e}})},function(e){return e&&"object"==typeof e?L(function(t){return r.bindActionCreators(e,t)}):void 0}];var B=[function(e){return"function"==typeof e?K(e):void 0},function(e){return e?void 0:L(function(){return{}})}];function Y(e,t,r){return y({},r,{},e,{},t)}var G=[function(e){return"function"==typeof e?function(e){return function(t,r){var n,o=r.pure,u=r.areMergedPropsEqual,a=!1;return function(t,r,i){var c=e(t,r,i);return a?o&&u(c,n)||(n=c):(a=!0,n=c),n}}}(e):void 0},function(e){return e?void 0:function(){return Y}}];function J(e,t,r,n){return function(o,u){return r(e(o,u),t(n,u),u)}}function Q(e,t,r,n,o){var u,a,i,c,s,f=o.areStatesEqual,p=o.areOwnPropsEqual,l=o.areStatePropsEqual,d=!1;function y(o,d){var y,v,m=!p(d,a),b=!f(o,u);return u=o,a=d,m&&b?(i=e(u,a),t.dependsOnOwnProps&&(c=t(n,a)),s=r(i,c,a)):m?(e.dependsOnOwnProps&&(i=e(u,a)),t.dependsOnOwnProps&&(c=t(n,a)),s=r(i,c,a)):b?(y=e(u,a),v=!l(y,i),i=y,v&&(s=r(i,c,a)),s):s}return function(o,f){return d?y(o,f):(i=e(u=o,a=f),c=t(n,a),s=r(i,c,a),d=!0,s)}}function X(e,t){var r=t.initMapStateToProps,n=t.initMapDispatchToProps,o=t.initMergeProps,u=v(t,["initMapStateToProps","initMapDispatchToProps","initMergeProps"]),a=r(e,u),i=n(e,u),c=o(e,u);return(u.pure?Q:J)(a,i,c,e,u)}function Z(e,t,r){for(var n=t.length-1;n>=0;n--){var o=t[n](e);if(o)return o}return function(t,n){throw Error("Invalid value of type "+typeof e+" for "+r+" argument when connecting component "+n.wrappedComponentName+".")}}function ee(e,t){return e===t}function te(e){var t=void 0===e?{}:e,r=t.connectHOC,n=void 0===r?U:r,o=t.mapStateToPropsFactories,u=void 0===o?B:o,a=t.mapDispatchToPropsFactories,i=void 0===a?V:a,c=t.mergePropsFactories,s=void 0===c?G:c,f=t.selectorFactory,p=void 0===f?X:f;return function(e,t,r,o){void 0===o&&(o={});var a=o.pure,c=void 0===a||a,f=o.areStatesEqual,l=void 0===f?ee:f,d=o.areOwnPropsEqual,m=void 0===d?I:d,b=o.areStatePropsEqual,h=void 0===b?I:b,S=o.areMergedPropsEqual,P=void 0===S?I:S,g=v(o,["pure","areStatesEqual","areOwnPropsEqual","areStatePropsEqual","areMergedPropsEqual"]),O=Z(e,u,"mapStateToProps"),w=Z(t,i,"mapDispatchToProps"),C=Z(r,s,"mergeProps");return n(p,y({methodName:"connect",getDisplayName:function(e){return"Connect("+e+")"},shouldHandleStateChanges:!!e,initMapStateToProps:O,initMapDispatchToProps:w,initMergeProps:C,pure:c,areStatesEqual:l,areOwnPropsEqual:m,areStatePropsEqual:h,areMergedPropsEqual:P},g))}}var re=te();function ne(){return t.useContext(s)}function oe(e){void 0===e&&(e=s);var r=e===s?ne:function(){return t.useContext(e)};return function(){return r().store}}var ue=oe();function ae(e){void 0===e&&(e=s);var t=e===s?ue:oe(e);return function(){return t().dispatch}}var ie=ae(),ce=function(e,t){return e===t};function se(e){void 0===e&&(e=s);var r=e===s?ne:function(){return t.useContext(e)};return function(e,n){void 0===n&&(n=ce);var o=r();return function(e,r,n,o){var u,a=t.useReducer(function(e){return e+1},0)[1],i=t.useMemo(function(){return new d(n,o)},[n,o]),c=t.useRef(),s=t.useRef(),f=t.useRef();try{u=e!==s.current||c.current?e(n.getState()):f.current}catch(e){throw c.current&&(e.message+="\nThe error may be correlated with this previous error:\n"+c.current.stack+"\n\n"),e}return N(function(){s.current=e,f.current=u,c.current=void 0}),N(function(){function e(){try{var e=s.current(n.getState());if(r(e,f.current))return;f.current=e}catch(e){c.current=e}a({})}return i.onStateChange=e,i.trySubscribe(),e(),function(){return i.tryUnsubscribe()}},[n,i]),u}(e,n,o.store,o.subscription)}}var fe=se();f=n.unstable_batchedUpdates,Object.defineProperty(e,"batch",{enumerable:!0,get:function(){return n.unstable_batchedUpdates}}),e.Provider=function(e){var r=e.store,n=e.context,u=e.children,a=t.useMemo(function(){var e=new d(r);return e.onStateChange=e.notifyNestedSubs,{store:r,subscription:e}},[r]),i=t.useMemo(function(){return r.getState()},[r]);return t.useEffect(function(){var e=a.subscription;return e.trySubscribe(),i!==r.getState()&&e.notifyNestedSubs(),function(){e.tryUnsubscribe(),e.onStateChange=null}},[a,i]),o.createElement((n||s).Provider,{value:a},u)},e.ReactReduxContext=s,e.connect=re,e.connectAdvanced=U,e.createDispatchHook=ae,e.createSelectorHook=se,e.createStoreHook=oe,e.shallowEqual=I,e.useDispatch=ie,e.useSelector=fe,e.useStore=ue,Object.defineProperty(e,"__esModule",{value:!0})});
diff --git a/browser/components/newtab/vendor/react-transition-group.js b/browser/components/newtab/vendor/react-transition-group.js
new file mode 100644
index 0000000000..4d906c7875
--- /dev/null
+++ b/browser/components/newtab/vendor/react-transition-group.js
@@ -0,0 +1 @@
+!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react"),require("react-dom")):"function"==typeof define&&define.amd?define(["exports","react","react-dom"],t):t((e=e||self).ReactTransitionGroup={},e.React,e.ReactDOM)}(this,function(e,t,n){"use strict";var r="default"in t?t.default:t;function i(){return(i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}).apply(this,arguments)}function o(e,t){if(null==e)return{};var n,r,i={},o=Object.keys(e);for(r=0;r<o.length;r++)n=o[r],t.indexOf(n)>=0||(i[n]=e[n]);return i}function a(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e.__proto__=t}n=n&&n.hasOwnProperty("default")?n.default:n;var s=Object.getOwnPropertySymbols,l=Object.prototype.hasOwnProperty,c=Object.prototype.propertyIsEnumerable;(function(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},n=0;n<10;n++)t["_"+String.fromCharCode(n)]=n;if("0123456789"!==Object.getOwnPropertyNames(t).map(function(e){return t[e]}).join(""))return!1;var r={};return"abcdefghijklmnopqrst".split("").forEach(function(e){r[e]=e}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},r)).join("")}catch(e){return!1}})()&&Object.assign;var u="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED";function p(){}var d,f=(function(e){e.exports=function(){function e(e,t,n,r,i,o){if(o!==u){var a=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw a.name="Invariant Violation",a}}function t(){return e}e.isRequired=e;var n={array:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t};return n.checkPropTypes=p,n.PropTypes=n,n}()}(d={exports:{}},d.exports),d.exports);f.object,f.oneOfType,f.element,f.bool,f.func;function h(e,t){return e.replace(new RegExp("(^|\\s)"+t+"(?:\\s|$)","g"),"$1").replace(/\s+/g," ").replace(/^\s*|\s*$/g,"")}var E={disabled:!1},m=r.createContext(null),x="unmounted",v="exited",y="entering",g="entered",b=function(e){function t(t,n){var r;r=e.call(this,t,n)||this;var i,o=n&&!n.isMounting?t.enter:t.appear;return r.appearStatus=null,t.in?o?(i=v,r.appearStatus=y):i=g:i=t.unmountOnExit||t.mountOnEnter?x:v,r.state={status:i},r.nextCallback=null,r}a(t,e),t.getDerivedStateFromProps=function(e,t){return e.in&&t.status===x?{status:v}:null};var i=t.prototype;return i.componentDidMount=function(){this.updateStatus(!0,this.appearStatus)},i.componentDidUpdate=function(e){var t=null;if(e!==this.props){var n=this.state.status;this.props.in?n!==y&&n!==g&&(t=y):n!==y&&n!==g||(t="exiting")}this.updateStatus(!1,t)},i.componentWillUnmount=function(){this.cancelNextCallback()},i.getTimeouts=function(){var e,t,n,r=this.props.timeout;return e=t=n=r,null!=r&&"number"!=typeof r&&(e=r.exit,t=r.enter,n=void 0!==r.appear?r.appear:t),{exit:e,enter:t,appear:n}},i.updateStatus=function(e,t){if(void 0===e&&(e=!1),null!==t){this.cancelNextCallback();var r=n.findDOMNode(this);t===y?this.performEnter(r,e):this.performExit(r)}else this.props.unmountOnExit&&this.state.status===v&&this.setState({status:x})},i.performEnter=function(e,t){var n=this,r=this.props.enter,i=this.context?this.context.isMounting:t,o=this.getTimeouts(),a=i?o.appear:o.enter;!t&&!r||E.disabled?this.safeSetState({status:g},function(){n.props.onEntered(e)}):(this.props.onEnter(e,i),this.safeSetState({status:y},function(){n.props.onEntering(e,i),n.onTransitionEnd(e,a,function(){n.safeSetState({status:g},function(){n.props.onEntered(e,i)})})}))},i.performExit=function(e){var t=this,n=this.props.exit,r=this.getTimeouts();n&&!E.disabled?(this.props.onExit(e),this.safeSetState({status:"exiting"},function(){t.props.onExiting(e),t.onTransitionEnd(e,r.exit,function(){t.safeSetState({status:v},function(){t.props.onExited(e)})})})):this.safeSetState({status:v},function(){t.props.onExited(e)})},i.cancelNextCallback=function(){null!==this.nextCallback&&(this.nextCallback.cancel(),this.nextCallback=null)},i.safeSetState=function(e,t){t=this.setNextCallback(t),this.setState(e,t)},i.setNextCallback=function(e){var t=this,n=!0;return this.nextCallback=function(r){n&&(n=!1,t.nextCallback=null,e(r))},this.nextCallback.cancel=function(){n=!1},this.nextCallback},i.onTransitionEnd=function(e,t,n){this.setNextCallback(n);var r=null==t&&!this.props.addEndListener;e&&!r?(this.props.addEndListener&&this.props.addEndListener(e,this.nextCallback),null!=t&&setTimeout(this.nextCallback,t)):setTimeout(this.nextCallback,0)},i.render=function(){var e=this.state.status;if(e===x)return null;var t=this.props,n=t.children,i=o(t,["children"]);if(delete i.in,delete i.mountOnEnter,delete i.unmountOnExit,delete i.appear,delete i.enter,delete i.exit,delete i.timeout,delete i.addEndListener,delete i.onEnter,delete i.onEntering,delete i.onEntered,delete i.onExit,delete i.onExiting,delete i.onExited,"function"==typeof n)return r.createElement(m.Provider,{value:null},n(e,i));var a=r.Children.only(n);return r.createElement(m.Provider,{value:null},r.cloneElement(a,i))},t}(r.Component);function C(){}b.contextType=m,b.propTypes={},b.defaultProps={in:!1,mountOnEnter:!1,unmountOnExit:!1,appear:!1,enter:!0,exit:!0,onEnter:C,onEntering:C,onEntered:C,onExit:C,onExiting:C,onExited:C},b.UNMOUNTED=0,b.EXITED=1,b.ENTERING=2,b.ENTERED=3,b.EXITING=4;var O=function(e,t){return e&&t&&t.split(" ").forEach(function(t){return r=t,void((n=e).classList?n.classList.remove(r):"string"==typeof n.className?n.className=h(n.className,r):n.setAttribute("class",h(n.className&&n.className.baseVal||"",r)));var n,r})},S=function(e){function t(){for(var t,n=arguments.length,r=new Array(n),i=0;i<n;i++)r[i]=arguments[i];return(t=e.call.apply(e,[this].concat(r))||this).appliedClasses={appear:{},enter:{},exit:{}},t.onEnter=function(e,n){t.removeClasses(e,"exit"),t.addClass(e,n?"appear":"enter","base"),t.props.onEnter&&t.props.onEnter(e,n)},t.onEntering=function(e,n){var r=n?"appear":"enter";t.addClass(e,r,"active"),t.props.onEntering&&t.props.onEntering(e,n)},t.onEntered=function(e,n){var r=n?"appear":"enter";t.removeClasses(e,r),t.addClass(e,r,"done"),t.props.onEntered&&t.props.onEntered(e,n)},t.onExit=function(e){t.removeClasses(e,"appear"),t.removeClasses(e,"enter"),t.addClass(e,"exit","base"),t.props.onExit&&t.props.onExit(e)},t.onExiting=function(e){t.addClass(e,"exit","active"),t.props.onExiting&&t.props.onExiting(e)},t.onExited=function(e){t.removeClasses(e,"exit"),t.addClass(e,"exit","done"),t.props.onExited&&t.props.onExited(e)},t.getClassNames=function(e){var n=t.props.classNames,r="string"==typeof n,i=r?""+(r&&n?n+"-":"")+e:n[e];return{baseClassName:i,activeClassName:r?i+"-active":n[e+"Active"],doneClassName:r?i+"-done":n[e+"Done"]}},t}a(t,e);var n=t.prototype;return n.addClass=function(e,t,n){var r=this.getClassNames(t)[n+"ClassName"];"appear"===t&&"done"===n&&(r+=" "+this.getClassNames("enter").doneClassName),"active"===n&&e&&e.scrollTop,this.appliedClasses[t][n]=r,function(e,t){e&&t&&t.split(" ").forEach(function(t){return r=t,void((n=e).classList?n.classList.add(r):function(e,t){return e.classList?!!t&&e.classList.contains(t):-1!==(" "+(e.className.baseVal||e.className)+" ").indexOf(" "+t+" ")}(n,r)||("string"==typeof n.className?n.className=n.className+" "+r:n.setAttribute("class",(n.className&&n.className.baseVal||"")+" "+r)));var n,r})}(e,r)},n.removeClasses=function(e,t){var n=this.appliedClasses[t],r=n.base,i=n.active,o=n.done;this.appliedClasses[t]={},r&&O(e,r),i&&O(e,i),o&&O(e,o)},n.render=function(){var e=this.props,t=(e.classNames,o(e,["classNames"]));return r.createElement(b,i({},t,{onEnter:this.onEnter,onEntered:this.onEntered,onEntering:this.onEntering,onExit:this.onExit,onExiting:this.onExiting,onExited:this.onExited}))},t}(r.Component);function N(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function k(e,n){var r=Object.create(null);return e&&t.Children.map(e,function(e){return e}).forEach(function(e){r[e.key]=function(e){return n&&t.isValidElement(e)?n(e):e}(e)}),r}function T(e,t,n){return null!=n[t]?n[t]:e.props[t]}function j(e,n,r){var i=k(e.children),o=function(e,t){function n(n){return n in t?t[n]:e[n]}e=e||{},t=t||{};var r,i=Object.create(null),o=[];for(var a in e)a in t?o.length&&(i[a]=o,o=[]):o.push(a);var s={};for(var l in t){if(i[l])for(r=0;r<i[l].length;r++){var c=i[l][r];s[i[l][r]]=n(c)}s[l]=n(l)}for(r=0;r<o.length;r++)s[o[r]]=n(o[r]);return s}(n,i);return Object.keys(o).forEach(function(a){var s=o[a];if(t.isValidElement(s)){var l=a in n,c=a in i,u=n[a],p=t.isValidElement(u)&&!u.props.in;!c||l&&!p?c||!l||p?c&&l&&t.isValidElement(u)&&(o[a]=t.cloneElement(s,{onExited:r.bind(null,s),in:u.props.in,exit:T(s,"exit",e),enter:T(s,"enter",e)})):o[a]=t.cloneElement(s,{in:!1}):o[a]=t.cloneElement(s,{onExited:r.bind(null,s),in:!0,exit:T(s,"exit",e),enter:T(s,"enter",e)})}}),o}S.defaultProps={classNames:""},S.propTypes={};var P=Object.values||function(e){return Object.keys(e).map(function(t){return e[t]})},w=function(e){function n(t,n){var r,i=(r=e.call(this,t,n)||this).handleExited.bind(N(N(r)));return r.state={contextValue:{isMounting:!0},handleExited:i,firstRender:!0},r}a(n,e);var s=n.prototype;return s.componentDidMount=function(){this.mounted=!0,this.setState({contextValue:{isMounting:!1}})},s.componentWillUnmount=function(){this.mounted=!1},n.getDerivedStateFromProps=function(e,n){var r,i,o=n.children,a=n.handleExited;return{children:n.firstRender?(r=e,i=a,k(r.children,function(e){return t.cloneElement(e,{onExited:i.bind(null,e),in:!0,appear:T(e,"appear",r),enter:T(e,"enter",r),exit:T(e,"exit",r)})})):j(e,o,a),firstRender:!1}},s.handleExited=function(e,t){var n=k(this.props.children);e.key in n||(e.props.onExited&&e.props.onExited(t),this.mounted&&this.setState(function(t){var n=i({},t.children);return delete n[e.key],{children:n}}))},s.render=function(){var e=this.props,t=e.component,n=e.childFactory,i=o(e,["component","childFactory"]),a=this.state.contextValue,s=P(this.state.children).map(n);return delete i.appear,delete i.enter,delete i.exit,null===t?r.createElement(m.Provider,{value:a},s):r.createElement(m.Provider,{value:a},r.createElement(t,i,s))},n}(r.Component);w.propTypes={},w.defaultProps={component:"div",childFactory:function(e){return e}};var L,D,R=function(e){function t(){for(var t,n=arguments.length,r=new Array(n),i=0;i<n;i++)r[i]=arguments[i];return(t=e.call.apply(e,[this].concat(r))||this).handleEnter=function(){for(var e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];return t.handleLifecycle("onEnter",0,n)},t.handleEntering=function(){for(var e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];return t.handleLifecycle("onEntering",0,n)},t.handleEntered=function(){for(var e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];return t.handleLifecycle("onEntered",0,n)},t.handleExit=function(){for(var e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];return t.handleLifecycle("onExit",1,n)},t.handleExiting=function(){for(var e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];return t.handleLifecycle("onExiting",1,n)},t.handleExited=function(){for(var e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];return t.handleLifecycle("onExited",1,n)},t}a(t,e);var i=t.prototype;return i.handleLifecycle=function(e,t,i){var o,a=this.props.children,s=r.Children.toArray(a)[t];s.props[e]&&(o=s.props)[e].apply(o,i),this.props[e]&&this.props[e](n.findDOMNode(this))},i.render=function(){var e=this.props,t=e.children,n=e.in,i=o(e,["children","in"]),a=r.Children.toArray(t),s=a[0],l=a[1];return delete i.onEnter,delete i.onEntering,delete i.onEntered,delete i.onExit,delete i.onExiting,delete i.onExited,r.createElement(w,i,n?r.cloneElement(s,{key:"first",onEnter:this.handleEnter,onEntering:this.handleEntering,onEntered:this.handleEntered}):r.cloneElement(l,{key:"second",onEnter:this.handleExit,onEntering:this.handleExiting,onEntered:this.handleExited}))},t}(r.Component);R.propTypes={};var _="out-in",A="in-out",M=function(e,t,n){return function(){var r;e.props[t]&&(r=e.props)[t].apply(r,arguments),n()}},V=((L={})[_]=function(e){var t=e.current,n=e.changeState;return r.cloneElement(t,{in:!1,onExited:M(t,"onExited",function(){n(y,null)})})},L[A]=function(e){var t=e.current,n=e.changeState,i=e.children;return[t,r.cloneElement(i,{in:!0,onEntered:M(i,"onEntered",function(){n(y)})})]},L),I=((D={})[_]=function(e){var t=e.children,n=e.changeState;return r.cloneElement(t,{in:!0,onEntered:M(t,"onEntered",function(){n(g,r.cloneElement(t,{in:!0}))})})},D[A]=function(e){var t=e.current,n=e.children,i=e.changeState;return[r.cloneElement(t,{in:!1,onExited:M(t,"onExited",function(){i(g,r.cloneElement(n,{in:!0}))})}),r.cloneElement(n,{in:!0})]},D),F=function(e){function t(){for(var t,n=arguments.length,r=new Array(n),i=0;i<n;i++)r[i]=arguments[i];return(t=e.call.apply(e,[this].concat(r))||this).state={status:g,current:null},t.appeared=!1,t.changeState=function(e,n){void 0===n&&(n=t.state.current),t.setState({status:e,current:n})},t}a(t,e);var n=t.prototype;return n.componentDidMount=function(){this.appeared=!0},t.getDerivedStateFromProps=function(e,t){return null==e.children?{current:null}:t.status===y&&e.mode===A?{status:y}:!t.current||(n=t.current,i=e.children,n===i||r.isValidElement(n)&&r.isValidElement(i)&&null!=n.key&&n.key===i.key)?{current:r.cloneElement(e.children,{in:!0})}:{status:"exiting"};var n,i},n.render=function(){var e,t=this.props,n=t.children,i=t.mode,o=this.state,a=o.status,s=o.current,l={children:n,current:s,changeState:this.changeState,status:a};switch(a){case y:e=I[i](l);break;case"exiting":e=V[i](l);break;case g:e=s}return r.createElement(m.Provider,{value:{isMounting:!this.appeared}},e)},t}(r.Component);F.propTypes={},F.defaultProps={mode:_},e.CSSTransition=S,e.ReplaceTransition=R,e.SwitchTransition=F,e.Transition=b,e.TransitionGroup=w,e.config=E,Object.defineProperty(e,"__esModule",{value:!0})});
diff --git a/browser/components/newtab/vendor/react.js b/browser/components/newtab/vendor/react.js
new file mode 100644
index 0000000000..a6338f8b62
--- /dev/null
+++ b/browser/components/newtab/vendor/react.js
@@ -0,0 +1,32 @@
+/** @license React v16.13.1
+ * react.production.min.js
+ *
+ * Copyright (c) Facebook, Inc. and its affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+'use strict';(function(d,r){"object"===typeof exports&&"undefined"!==typeof module?r(exports):"function"===typeof define&&define.amd?define(["exports"],r):(d=d||self,r(d.React={}))})(this,function(d){function r(a){for(var b="https://reactjs.org/docs/error-decoder.html?invariant="+a,c=1;c<arguments.length;c++)b+="&args[]="+encodeURIComponent(arguments[c]);return"Minified React error #"+a+"; visit "+b+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}
+function w(a,b,c){this.props=a;this.context=b;this.refs=ba;this.updater=c||ca}function da(){}function L(a,b,c){this.props=a;this.context=b;this.refs=ba;this.updater=c||ca}function ea(a,b,c){var g,e={},fa=null,d=null;if(null!=b)for(g in void 0!==b.ref&&(d=b.ref),void 0!==b.key&&(fa=""+b.key),b)ha.call(b,g)&&!ia.hasOwnProperty(g)&&(e[g]=b[g]);var h=arguments.length-2;if(1===h)e.children=c;else if(1<h){for(var k=Array(h),f=0;f<h;f++)k[f]=arguments[f+2];e.children=k}if(a&&a.defaultProps)for(g in h=a.defaultProps,
+h)void 0===e[g]&&(e[g]=h[g]);return{$$typeof:x,type:a,key:fa,ref:d,props:e,_owner:M.current}}function va(a,b){return{$$typeof:x,type:a.type,key:b,ref:a.ref,props:a.props,_owner:a._owner}}function N(a){return"object"===typeof a&&null!==a&&a.$$typeof===x}function wa(a){var b={"=":"=0",":":"=2"};return"$"+(""+a).replace(/[=:]/g,function(a){return b[a]})}function ja(a,b,c,g){if(C.length){var e=C.pop();e.result=a;e.keyPrefix=b;e.func=c;e.context=g;e.count=0;return e}return{result:a,keyPrefix:b,func:c,
+context:g,count:0}}function ka(a){a.result=null;a.keyPrefix=null;a.func=null;a.context=null;a.count=0;10>C.length&&C.push(a)}function O(a,b,c,g){var e=typeof a;if("undefined"===e||"boolean"===e)a=null;var d=!1;if(null===a)d=!0;else switch(e){case "string":case "number":d=!0;break;case "object":switch(a.$$typeof){case x:case xa:d=!0}}if(d)return c(g,a,""===b?"."+P(a,0):b),1;d=0;b=""===b?".":b+":";if(Array.isArray(a))for(var f=0;f<a.length;f++){e=a[f];var h=b+P(e,f);d+=O(e,h,c,g)}else if(null===a||
+"object"!==typeof a?h=null:(h=la&&a[la]||a["@@iterator"],h="function"===typeof h?h:null),"function"===typeof h)for(a=h.call(a),f=0;!(e=a.next()).done;)e=e.value,h=b+P(e,f++),d+=O(e,h,c,g);else if("object"===e)throw c=""+a,Error(r(31,"[object Object]"===c?"object with keys {"+Object.keys(a).join(", ")+"}":c,""));return d}function Q(a,b,c){return null==a?0:O(a,"",b,c)}function P(a,b){return"object"===typeof a&&null!==a&&null!=a.key?wa(a.key):b.toString(36)}function ya(a,b,c){a.func.call(a.context,b,
+a.count++)}function za(a,b,c){var g=a.result,e=a.keyPrefix;a=a.func.call(a.context,b,a.count++);Array.isArray(a)?R(a,g,c,function(a){return a}):null!=a&&(N(a)&&(a=va(a,e+(!a.key||b&&b.key===a.key?"":(""+a.key).replace(ma,"$&/")+"/")+c)),g.push(a))}function R(a,b,c,g,e){var d="";null!=c&&(d=(""+c).replace(ma,"$&/")+"/");b=ja(b,d,g,e);Q(a,za,b);ka(b)}function t(){var a=na.current;if(null===a)throw Error(r(321));return a}function S(a,b){var c=a.length;a.push(b);a:for(;;){var g=c-1>>>1,e=a[g];if(void 0!==
+e&&0<D(e,b))a[g]=b,a[c]=e,c=g;else break a}}function n(a){a=a[0];return void 0===a?null:a}function E(a){var b=a[0];if(void 0!==b){var c=a.pop();if(c!==b){a[0]=c;a:for(var g=0,e=a.length;g<e;){var d=2*(g+1)-1,f=a[d],h=d+1,k=a[h];if(void 0!==f&&0>D(f,c))void 0!==k&&0>D(k,f)?(a[g]=k,a[h]=c,g=h):(a[g]=f,a[d]=c,g=d);else if(void 0!==k&&0>D(k,c))a[g]=k,a[h]=c,g=h;else break a}}return b}return null}function D(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}function F(a){for(var b=n(u);null!==
+b;){if(null===b.callback)E(u);else if(b.startTime<=a)E(u),b.sortIndex=b.expirationTime,S(p,b);else break;b=n(u)}}function T(a){y=!1;F(a);if(!v)if(null!==n(p))v=!0,z(U);else{var b=n(u);null!==b&&G(T,b.startTime-a)}}function U(a,b){v=!1;y&&(y=!1,V());H=!0;var c=m;try{F(b);for(l=n(p);null!==l&&(!(l.expirationTime>b)||a&&!W());){var g=l.callback;if(null!==g){l.callback=null;m=l.priorityLevel;var e=g(l.expirationTime<=b);b=q();"function"===typeof e?l.callback=e:l===n(p)&&E(p);F(b)}else E(p);l=n(p)}if(null!==
+l)var d=!0;else{var f=n(u);null!==f&&G(T,f.startTime-b);d=!1}return d}finally{l=null,m=c,H=!1}}function oa(a){switch(a){case 1:return-1;case 2:return 250;case 5:return 1073741823;case 4:return 1E4;default:return 5E3}}var f="function"===typeof Symbol&&Symbol.for,x=f?Symbol.for("react.element"):60103,xa=f?Symbol.for("react.portal"):60106,Aa=f?Symbol.for("react.fragment"):60107,Ba=f?Symbol.for("react.strict_mode"):60108,Ca=f?Symbol.for("react.profiler"):60114,Da=f?Symbol.for("react.provider"):60109,
+Ea=f?Symbol.for("react.context"):60110,Fa=f?Symbol.for("react.forward_ref"):60112,Ga=f?Symbol.for("react.suspense"):60113,Ha=f?Symbol.for("react.memo"):60115,Ia=f?Symbol.for("react.lazy"):60116,la="function"===typeof Symbol&&Symbol.iterator,pa=Object.getOwnPropertySymbols,Ja=Object.prototype.hasOwnProperty,Ka=Object.prototype.propertyIsEnumerable,I=function(){try{if(!Object.assign)return!1;var a=new String("abc");a[5]="de";if("5"===Object.getOwnPropertyNames(a)[0])return!1;var b={};for(a=0;10>a;a++)b["_"+
+String.fromCharCode(a)]=a;if("0123456789"!==Object.getOwnPropertyNames(b).map(function(a){return b[a]}).join(""))return!1;var c={};"abcdefghijklmnopqrst".split("").forEach(function(a){c[a]=a});return"abcdefghijklmnopqrst"!==Object.keys(Object.assign({},c)).join("")?!1:!0}catch(g){return!1}}()?Object.assign:function(a,b){if(null===a||void 0===a)throw new TypeError("Object.assign cannot be called with null or undefined");var c=Object(a);for(var g,e=1;e<arguments.length;e++){var d=Object(arguments[e]);
+for(var f in d)Ja.call(d,f)&&(c[f]=d[f]);if(pa){g=pa(d);for(var h=0;h<g.length;h++)Ka.call(d,g[h])&&(c[g[h]]=d[g[h]])}}return c},ca={isMounted:function(a){return!1},enqueueForceUpdate:function(a,b,c){},enqueueReplaceState:function(a,b,c,d){},enqueueSetState:function(a,b,c,d){}},ba={};w.prototype.isReactComponent={};w.prototype.setState=function(a,b){if("object"!==typeof a&&"function"!==typeof a&&null!=a)throw Error(r(85));this.updater.enqueueSetState(this,a,b,"setState")};w.prototype.forceUpdate=
+function(a){this.updater.enqueueForceUpdate(this,a,"forceUpdate")};da.prototype=w.prototype;f=L.prototype=new da;f.constructor=L;I(f,w.prototype);f.isPureReactComponent=!0;var M={current:null},ha=Object.prototype.hasOwnProperty,ia={key:!0,ref:!0,__self:!0,__source:!0},ma=/\/+/g,C=[],na={current:null},X;if("undefined"===typeof window||"function"!==typeof MessageChannel){var A=null,qa=null,ra=function(){if(null!==A)try{var a=q();A(!0,a);A=null}catch(b){throw setTimeout(ra,0),b;}},La=Date.now();var q=
+function(){return Date.now()-La};var z=function(a){null!==A?setTimeout(z,0,a):(A=a,setTimeout(ra,0))};var G=function(a,b){qa=setTimeout(a,b)};var V=function(){clearTimeout(qa)};var W=function(){return!1};f=X=function(){}}else{var Y=window.performance,sa=window.Date,Ma=window.setTimeout,Na=window.clearTimeout;"undefined"!==typeof console&&(f=window.cancelAnimationFrame,"function"!==typeof window.requestAnimationFrame&&console.error("This browser doesn't support requestAnimationFrame. Make sure that you load a polyfill in older browsers. https://fb.me/react-polyfills"),
+"function"!==typeof f&&console.error("This browser doesn't support cancelAnimationFrame. Make sure that you load a polyfill in older browsers. https://fb.me/react-polyfills"));if("object"===typeof Y&&"function"===typeof Y.now)q=function(){return Y.now()};else{var Oa=sa.now();q=function(){return sa.now()-Oa}}var J=!1,K=null,Z=-1,ta=5,ua=0;W=function(){return q()>=ua};f=function(){};X=function(a){0>a||125<a?console.error("forceFrameRate takes a positive int between 0 and 125, forcing framerates higher than 125 fps is not unsupported"):
+ta=0<a?Math.floor(1E3/a):5};var B=new MessageChannel,aa=B.port2;B.port1.onmessage=function(){if(null!==K){var a=q();ua=a+ta;try{K(!0,a)?aa.postMessage(null):(J=!1,K=null)}catch(b){throw aa.postMessage(null),b;}}else J=!1};z=function(a){K=a;J||(J=!0,aa.postMessage(null))};G=function(a,b){Z=Ma(function(){a(q())},b)};V=function(){Na(Z);Z=-1}}var p=[],u=[],Pa=1,l=null,m=3,H=!1,v=!1,y=!1,Qa=0;B={ReactCurrentDispatcher:na,ReactCurrentOwner:M,IsSomeRendererActing:{current:!1},assign:I};I(B,{Scheduler:{__proto__:null,
+unstable_ImmediatePriority:1,unstable_UserBlockingPriority:2,unstable_NormalPriority:3,unstable_IdlePriority:5,unstable_LowPriority:4,unstable_runWithPriority:function(a,b){switch(a){case 1:case 2:case 3:case 4:case 5:break;default:a=3}var c=m;m=a;try{return b()}finally{m=c}},unstable_next:function(a){switch(m){case 1:case 2:case 3:var b=3;break;default:b=m}var c=m;m=b;try{return a()}finally{m=c}},unstable_scheduleCallback:function(a,b,c){var d=q();if("object"===typeof c&&null!==c){var e=c.delay;
+e="number"===typeof e&&0<e?d+e:d;c="number"===typeof c.timeout?c.timeout:oa(a)}else c=oa(a),e=d;c=e+c;a={id:Pa++,callback:b,priorityLevel:a,startTime:e,expirationTime:c,sortIndex:-1};e>d?(a.sortIndex=e,S(u,a),null===n(p)&&a===n(u)&&(y?V():y=!0,G(T,e-d))):(a.sortIndex=c,S(p,a),v||H||(v=!0,z(U)));return a},unstable_cancelCallback:function(a){a.callback=null},unstable_wrapCallback:function(a){var b=m;return function(){var c=m;m=b;try{return a.apply(this,arguments)}finally{m=c}}},unstable_getCurrentPriorityLevel:function(){return m},
+unstable_shouldYield:function(){var a=q();F(a);var b=n(p);return b!==l&&null!==l&&null!==b&&null!==b.callback&&b.startTime<=a&&b.expirationTime<l.expirationTime||W()},unstable_requestPaint:f,unstable_continueExecution:function(){v||H||(v=!0,z(U))},unstable_pauseExecution:function(){},unstable_getFirstCallbackNode:function(){return n(p)},get unstable_now(){return q},get unstable_forceFrameRate(){return X},unstable_Profiling:null},SchedulerTracing:{__proto__:null,__interactionsRef:null,__subscriberRef:null,
+unstable_clear:function(a){return a()},unstable_getCurrent:function(){return null},unstable_getThreadID:function(){return++Qa},unstable_trace:function(a,b,c){return c()},unstable_wrap:function(a){return a},unstable_subscribe:function(a){},unstable_unsubscribe:function(a){}}});d.Children={map:function(a,b,c){if(null==a)return a;var d=[];R(a,d,null,b,c);return d},forEach:function(a,b,c){if(null==a)return a;b=ja(null,null,b,c);Q(a,ya,b);ka(b)},count:function(a){return Q(a,function(){return null},null)},
+toArray:function(a){var b=[];R(a,b,null,function(a){return a});return b},only:function(a){if(!N(a))throw Error(r(143));return a}};d.Component=w;d.Fragment=Aa;d.Profiler=Ca;d.PureComponent=L;d.StrictMode=Ba;d.Suspense=Ga;d.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=B;d.cloneElement=function(a,b,c){if(null===a||void 0===a)throw Error(r(267,a));var d=I({},a.props),e=a.key,f=a.ref,m=a._owner;if(null!=b){void 0!==b.ref&&(f=b.ref,m=M.current);void 0!==b.key&&(e=""+b.key);if(a.type&&a.type.defaultProps)var h=
+a.type.defaultProps;for(k in b)ha.call(b,k)&&!ia.hasOwnProperty(k)&&(d[k]=void 0===b[k]&&void 0!==h?h[k]:b[k])}var k=arguments.length-2;if(1===k)d.children=c;else if(1<k){h=Array(k);for(var l=0;l<k;l++)h[l]=arguments[l+2];d.children=h}return{$$typeof:x,type:a.type,key:e,ref:f,props:d,_owner:m}};d.createContext=function(a,b){void 0===b&&(b=null);a={$$typeof:Ea,_calculateChangedBits:b,_currentValue:a,_currentValue2:a,_threadCount:0,Provider:null,Consumer:null};a.Provider={$$typeof:Da,_context:a};return a.Consumer=
+a};d.createElement=ea;d.createFactory=function(a){var b=ea.bind(null,a);b.type=a;return b};d.createRef=function(){return{current:null}};d.forwardRef=function(a){return{$$typeof:Fa,render:a}};d.isValidElement=N;d.lazy=function(a){return{$$typeof:Ia,_ctor:a,_status:-1,_result:null}};d.memo=function(a,b){return{$$typeof:Ha,type:a,compare:void 0===b?null:b}};d.useCallback=function(a,b){return t().useCallback(a,b)};d.useContext=function(a,b){return t().useContext(a,b)};d.useDebugValue=function(a,b){};
+d.useEffect=function(a,b){return t().useEffect(a,b)};d.useImperativeHandle=function(a,b,c){return t().useImperativeHandle(a,b,c)};d.useLayoutEffect=function(a,b){return t().useLayoutEffect(a,b)};d.useMemo=function(a,b){return t().useMemo(a,b)};d.useReducer=function(a,b,c){return t().useReducer(a,b,c)};d.useRef=function(a){return t().useRef(a)};d.useState=function(a){return t().useState(a)};d.version="16.13.1"});
diff --git a/browser/components/newtab/vendor/redux.js b/browser/components/newtab/vendor/redux.js
new file mode 100644
index 0000000000..b83c31d3a2
--- /dev/null
+++ b/browser/components/newtab/vendor/redux.js
@@ -0,0 +1,948 @@
+/**
+ * Redux v.3.6.0
+ */
+(function webpackUniversalModuleDefinition(root, factory) {
+ if(typeof exports === 'object' && typeof module === 'object')
+ module.exports = factory();
+ else if(typeof define === 'function' && define.amd)
+ define([], factory);
+ else if(typeof exports === 'object')
+ exports["Redux"] = factory();
+ else
+ root["Redux"] = factory();
+})(this, function() {
+return /******/ (function(modules) { // webpackBootstrap
+/******/ // The module cache
+/******/ var installedModules = {};
+
+/******/ // The require function
+/******/ function __webpack_require__(moduleId) {
+
+/******/ // Check if module is in cache
+/******/ if(installedModules[moduleId])
+/******/ return installedModules[moduleId].exports;
+
+/******/ // Create a new module (and put it into the cache)
+/******/ var module = installedModules[moduleId] = {
+/******/ exports: {},
+/******/ id: moduleId,
+/******/ loaded: false
+/******/ };
+
+/******/ // Execute the module function
+/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
+
+/******/ // Flag the module as loaded
+/******/ module.loaded = true;
+
+/******/ // Return the exports of the module
+/******/ return module.exports;
+/******/ }
+
+
+/******/ // expose the modules object (__webpack_modules__)
+/******/ __webpack_require__.m = modules;
+
+/******/ // expose the module cache
+/******/ __webpack_require__.c = installedModules;
+
+/******/ // __webpack_public_path__
+/******/ __webpack_require__.p = "";
+
+/******/ // Load entry module and return exports
+/******/ return __webpack_require__(0);
+/******/ })
+/************************************************************************/
+/******/ ([
+/* 0 */
+/***/ function(module, exports, __webpack_require__) {
+
+ 'use strict';
+
+ exports.__esModule = true;
+ exports.compose = exports.applyMiddleware = exports.bindActionCreators = exports.combineReducers = exports.createStore = undefined;
+
+ var _createStore = __webpack_require__(2);
+
+ var _createStore2 = _interopRequireDefault(_createStore);
+
+ var _combineReducers = __webpack_require__(7);
+
+ var _combineReducers2 = _interopRequireDefault(_combineReducers);
+
+ var _bindActionCreators = __webpack_require__(6);
+
+ var _bindActionCreators2 = _interopRequireDefault(_bindActionCreators);
+
+ var _applyMiddleware = __webpack_require__(5);
+
+ var _applyMiddleware2 = _interopRequireDefault(_applyMiddleware);
+
+ var _compose = __webpack_require__(1);
+
+ var _compose2 = _interopRequireDefault(_compose);
+
+ var _warning = __webpack_require__(3);
+
+ var _warning2 = _interopRequireDefault(_warning);
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+ /*
+ * This is a dummy function to check if the function name has been altered by minification.
+ * If the function has been minified and NODE_ENV !== 'production', warn the user.
+ */
+ function isCrushed() {}
+
+ if (("development") !== 'production' && typeof isCrushed.name === 'string' && isCrushed.name !== 'isCrushed') {
+ (0, _warning2['default'])('You are currently using minified code outside of NODE_ENV === \'production\'. ' + 'This means that you are running a slower development build of Redux. ' + 'You can use loose-envify (https://github.com/zertosh/loose-envify) for browserify ' + 'or DefinePlugin for webpack (http://stackoverflow.com/questions/30030031) ' + 'to ensure you have the correct code for your production build.');
+ }
+
+ exports.createStore = _createStore2['default'];
+ exports.combineReducers = _combineReducers2['default'];
+ exports.bindActionCreators = _bindActionCreators2['default'];
+ exports.applyMiddleware = _applyMiddleware2['default'];
+ exports.compose = _compose2['default'];
+
+/***/ },
+/* 1 */
+/***/ function(module, exports) {
+
+ "use strict";
+
+ exports.__esModule = true;
+ exports["default"] = compose;
+ /**
+ * Composes single-argument functions from right to left. The rightmost
+ * function can take multiple arguments as it provides the signature for
+ * the resulting composite function.
+ *
+ * @param {...Function} funcs The functions to compose.
+ * @returns {Function} A function obtained by composing the argument functions
+ * from right to left. For example, compose(f, g, h) is identical to doing
+ * (...args) => f(g(h(...args))).
+ */
+
+ function compose() {
+ for (var _len = arguments.length, funcs = Array(_len), _key = 0; _key < _len; _key++) {
+ funcs[_key] = arguments[_key];
+ }
+
+ if (funcs.length === 0) {
+ return function (arg) {
+ return arg;
+ };
+ }
+
+ if (funcs.length === 1) {
+ return funcs[0];
+ }
+
+ var last = funcs[funcs.length - 1];
+ var rest = funcs.slice(0, -1);
+ return function () {
+ return rest.reduceRight(function (composed, f) {
+ return f(composed);
+ }, last.apply(undefined, arguments));
+ };
+ }
+
+/***/ },
+/* 2 */
+/***/ function(module, exports, __webpack_require__) {
+
+ 'use strict';
+
+ exports.__esModule = true;
+ exports.ActionTypes = undefined;
+ exports['default'] = createStore;
+
+ var _isPlainObject = __webpack_require__(4);
+
+ var _isPlainObject2 = _interopRequireDefault(_isPlainObject);
+
+ var _symbolObservable = __webpack_require__(12);
+
+ var _symbolObservable2 = _interopRequireDefault(_symbolObservable);
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+ /**
+ * These are private action types reserved by Redux.
+ * For any unknown actions, you must return the current state.
+ * If the current state is undefined, you must return the initial state.
+ * Do not reference these action types directly in your code.
+ */
+ var ActionTypes = exports.ActionTypes = {
+ INIT: '@@redux/INIT'
+ };
+
+ /**
+ * Creates a Redux store that holds the state tree.
+ * The only way to change the data in the store is to call `dispatch()` on it.
+ *
+ * There should only be a single store in your app. To specify how different
+ * parts of the state tree respond to actions, you may combine several reducers
+ * into a single reducer function by using `combineReducers`.
+ *
+ * @param {Function} reducer A function that returns the next state tree, given
+ * the current state tree and the action to handle.
+ *
+ * @param {any} [preloadedState] The initial state. You may optionally specify it
+ * to hydrate the state from the server in universal apps, or to restore a
+ * previously serialized user session.
+ * If you use `combineReducers` to produce the root reducer function, this must be
+ * an object with the same shape as `combineReducers` keys.
+ *
+ * @param {Function} enhancer The store enhancer. You may optionally specify it
+ * to enhance the store with third-party capabilities such as middleware,
+ * time travel, persistence, etc. The only store enhancer that ships with Redux
+ * is `applyMiddleware()`.
+ *
+ * @returns {Store} A Redux store that lets you read the state, dispatch actions
+ * and subscribe to changes.
+ */
+ function createStore(reducer, preloadedState, enhancer) {
+ var _ref2;
+
+ if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') {
+ enhancer = preloadedState;
+ preloadedState = undefined;
+ }
+
+ if (typeof enhancer !== 'undefined') {
+ if (typeof enhancer !== 'function') {
+ throw new Error('Expected the enhancer to be a function.');
+ }
+
+ return enhancer(createStore)(reducer, preloadedState);
+ }
+
+ if (typeof reducer !== 'function') {
+ throw new Error('Expected the reducer to be a function.');
+ }
+
+ var currentReducer = reducer;
+ var currentState = preloadedState;
+ var currentListeners = [];
+ var nextListeners = currentListeners;
+ var isDispatching = false;
+
+ function ensureCanMutateNextListeners() {
+ if (nextListeners === currentListeners) {
+ nextListeners = currentListeners.slice();
+ }
+ }
+
+ /**
+ * Reads the state tree managed by the store.
+ *
+ * @returns {any} The current state tree of your application.
+ */
+ function getState() {
+ return currentState;
+ }
+
+ /**
+ * Adds a change listener. It will be called any time an action is dispatched,
+ * and some part of the state tree may potentially have changed. You may then
+ * call `getState()` to read the current state tree inside the callback.
+ *
+ * You may call `dispatch()` from a change listener, with the following
+ * caveats:
+ *
+ * 1. The subscriptions are snapshotted just before every `dispatch()` call.
+ * If you subscribe or unsubscribe while the listeners are being invoked, this
+ * will not have any effect on the `dispatch()` that is currently in progress.
+ * However, the next `dispatch()` call, whether nested or not, will use a more
+ * recent snapshot of the subscription list.
+ *
+ * 2. The listener should not expect to see all state changes, as the state
+ * might have been updated multiple times during a nested `dispatch()` before
+ * the listener is called. It is, however, guaranteed that all subscribers
+ * registered before the `dispatch()` started will be called with the latest
+ * state by the time it exits.
+ *
+ * @param {Function} listener A callback to be invoked on every dispatch.
+ * @returns {Function} A function to remove this change listener.
+ */
+ function subscribe(listener) {
+ if (typeof listener !== 'function') {
+ throw new Error('Expected listener to be a function.');
+ }
+
+ var isSubscribed = true;
+
+ ensureCanMutateNextListeners();
+ nextListeners.push(listener);
+
+ return function unsubscribe() {
+ if (!isSubscribed) {
+ return;
+ }
+
+ isSubscribed = false;
+
+ ensureCanMutateNextListeners();
+ var index = nextListeners.indexOf(listener);
+ nextListeners.splice(index, 1);
+ };
+ }
+
+ /**
+ * Dispatches an action. It is the only way to trigger a state change.
+ *
+ * The `reducer` function, used to create the store, will be called with the
+ * current state tree and the given `action`. Its return value will
+ * be considered the **next** state of the tree, and the change listeners
+ * will be notified.
+ *
+ * The base implementation only supports plain object actions. If you want to
+ * dispatch a Promise, an Observable, a thunk, or something else, you need to
+ * wrap your store creating function into the corresponding middleware. For
+ * example, see the documentation for the `redux-thunk` package. Even the
+ * middleware will eventually dispatch plain object actions using this method.
+ *
+ * @param {Object} action A plain object representing “what changed”. It is
+ * a good idea to keep actions serializable so you can record and replay user
+ * sessions, or use the time travelling `redux-devtools`. An action must have
+ * a `type` property which may not be `undefined`. It is a good idea to use
+ * string constants for action types.
+ *
+ * @returns {Object} For convenience, the same action object you dispatched.
+ *
+ * Note that, if you use a custom middleware, it may wrap `dispatch()` to
+ * return something else (for example, a Promise you can await).
+ */
+ function dispatch(action) {
+ if (!(0, _isPlainObject2['default'])(action)) {
+ throw new Error('Actions must be plain objects. ' + 'Use custom middleware for async actions.');
+ }
+
+ if (typeof action.type === 'undefined') {
+ throw new Error('Actions may not have an undefined "type" property. ' + 'Have you misspelled a constant?');
+ }
+
+ if (isDispatching) {
+ throw new Error('Reducers may not dispatch actions.');
+ }
+
+ try {
+ isDispatching = true;
+ currentState = currentReducer(currentState, action);
+ } finally {
+ isDispatching = false;
+ }
+
+ var listeners = currentListeners = nextListeners;
+ for (var i = 0; i < listeners.length; i++) {
+ listeners[i]();
+ }
+
+ return action;
+ }
+
+ /**
+ * Replaces the reducer currently used by the store to calculate the state.
+ *
+ * You might need this if your app implements code splitting and you want to
+ * load some of the reducers dynamically. You might also need this if you
+ * implement a hot reloading mechanism for Redux.
+ *
+ * @param {Function} nextReducer The reducer for the store to use instead.
+ * @returns {void}
+ */
+ function replaceReducer(nextReducer) {
+ if (typeof nextReducer !== 'function') {
+ throw new Error('Expected the nextReducer to be a function.');
+ }
+
+ currentReducer = nextReducer;
+ dispatch({ type: ActionTypes.INIT });
+ }
+
+ /**
+ * Interoperability point for observable/reactive libraries.
+ * @returns {observable} A minimal observable of state changes.
+ * For more information, see the observable proposal:
+ * https://github.com/zenparsing/es-observable
+ */
+ function observable() {
+ var _ref;
+
+ var outerSubscribe = subscribe;
+ return _ref = {
+ /**
+ * The minimal observable subscription method.
+ * @param {Object} observer Any object that can be used as an observer.
+ * The observer object should have a `next` method.
+ * @returns {subscription} An object with an `unsubscribe` method that can
+ * be used to unsubscribe the observable from the store, and prevent further
+ * emission of values from the observable.
+ */
+ subscribe: function subscribe(observer) {
+ if (typeof observer !== 'object') {
+ throw new TypeError('Expected the observer to be an object.');
+ }
+
+ function observeState() {
+ if (observer.next) {
+ observer.next(getState());
+ }
+ }
+
+ observeState();
+ var unsubscribe = outerSubscribe(observeState);
+ return { unsubscribe: unsubscribe };
+ }
+ }, _ref[_symbolObservable2['default']] = function () {
+ return this;
+ }, _ref;
+ }
+
+ // When a store is created, an "INIT" action is dispatched so that every
+ // reducer returns their initial state. This effectively populates
+ // the initial state tree.
+ dispatch({ type: ActionTypes.INIT });
+
+ return _ref2 = {
+ dispatch: dispatch,
+ subscribe: subscribe,
+ getState: getState,
+ replaceReducer: replaceReducer
+ }, _ref2[_symbolObservable2['default']] = observable, _ref2;
+ }
+
+/***/ },
+/* 3 */
+/***/ function(module, exports) {
+
+ 'use strict';
+
+ exports.__esModule = true;
+ exports['default'] = warning;
+ /**
+ * Prints a warning in the console if it exists.
+ *
+ * @param {String} message The warning message.
+ * @returns {void}
+ */
+ function warning(message) {
+ /* eslint-disable no-console */
+ if (typeof console !== 'undefined' && typeof console.error === 'function') {
+ console.error(message);
+ }
+ /* eslint-enable no-console */
+ try {
+ // This error was thrown as a convenience so that if you enable
+ // "break on all exceptions" in your console,
+ // it would pause the execution at this line.
+ throw new Error(message);
+ /* eslint-disable no-empty */
+ } catch (e) {}
+ /* eslint-enable no-empty */
+ }
+
+/***/ },
+/* 4 */
+/***/ function(module, exports, __webpack_require__) {
+
+ var getPrototype = __webpack_require__(8),
+ isHostObject = __webpack_require__(9),
+ isObjectLike = __webpack_require__(11);
+
+ /** `Object#toString` result references. */
+ var objectTag = '[object Object]';
+
+ /** Used for built-in method references. */
+ var funcProto = Function.prototype,
+ objectProto = Object.prototype;
+
+ /** Used to resolve the decompiled source of functions. */
+ var funcToString = funcProto.toString;
+
+ /** Used to check objects for own properties. */
+ var hasOwnProperty = objectProto.hasOwnProperty;
+
+ /** Used to infer the `Object` constructor. */
+ var objectCtorString = funcToString.call(Object);
+
+ /**
+ * Used to resolve the
+ * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
+ * of values.
+ */
+ var objectToString = objectProto.toString;
+
+ /**
+ * Checks if `value` is a plain object, that is, an object created by the
+ * `Object` constructor or one with a `[[Prototype]]` of `null`.
+ *
+ * @static
+ * @memberOf _
+ * @since 0.8.0
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
+ * @example
+ *
+ * function Foo() {
+ * this.a = 1;
+ * }
+ *
+ * _.isPlainObject(new Foo);
+ * // => false
+ *
+ * _.isPlainObject([1, 2, 3]);
+ * // => false
+ *
+ * _.isPlainObject({ 'x': 0, 'y': 0 });
+ * // => true
+ *
+ * _.isPlainObject(Object.create(null));
+ * // => true
+ */
+ function isPlainObject(value) {
+ if (!isObjectLike(value) ||
+ objectToString.call(value) != objectTag || isHostObject(value)) {
+ return false;
+ }
+ var proto = getPrototype(value);
+ if (proto === null) {
+ return true;
+ }
+ var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;
+ return (typeof Ctor == 'function' &&
+ Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString);
+ }
+
+ module.exports = isPlainObject;
+
+
+/***/ },
+/* 5 */
+/***/ function(module, exports, __webpack_require__) {
+
+ 'use strict';
+
+ exports.__esModule = true;
+
+ var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
+
+ exports['default'] = applyMiddleware;
+
+ var _compose = __webpack_require__(1);
+
+ var _compose2 = _interopRequireDefault(_compose);
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+ /**
+ * Creates a store enhancer that applies middleware to the dispatch method
+ * of the Redux store. This is handy for a variety of tasks, such as expressing
+ * asynchronous actions in a concise manner, or logging every action payload.
+ *
+ * See `redux-thunk` package as an example of the Redux middleware.
+ *
+ * Because middleware is potentially asynchronous, this should be the first
+ * store enhancer in the composition chain.
+ *
+ * Note that each middleware will be given the `dispatch` and `getState` functions
+ * as named arguments.
+ *
+ * @param {...Function} middlewares The middleware chain to be applied.
+ * @returns {Function} A store enhancer applying the middleware.
+ */
+ function applyMiddleware() {
+ for (var _len = arguments.length, middlewares = Array(_len), _key = 0; _key < _len; _key++) {
+ middlewares[_key] = arguments[_key];
+ }
+
+ return function (createStore) {
+ return function (reducer, preloadedState, enhancer) {
+ var store = createStore(reducer, preloadedState, enhancer);
+ var _dispatch = store.dispatch;
+ var chain = [];
+
+ var middlewareAPI = {
+ getState: store.getState,
+ dispatch: function dispatch(action) {
+ return _dispatch(action);
+ }
+ };
+ chain = middlewares.map(function (middleware) {
+ return middleware(middlewareAPI);
+ });
+ _dispatch = _compose2['default'].apply(undefined, chain)(store.dispatch);
+
+ return _extends({}, store, {
+ dispatch: _dispatch
+ });
+ };
+ };
+ }
+
+/***/ },
+/* 6 */
+/***/ function(module, exports) {
+
+ 'use strict';
+
+ exports.__esModule = true;
+ exports['default'] = bindActionCreators;
+ function bindActionCreator(actionCreator, dispatch) {
+ return function () {
+ return dispatch(actionCreator.apply(undefined, arguments));
+ };
+ }
+
+ /**
+ * Turns an object whose values are action creators, into an object with the
+ * same keys, but with every function wrapped into a `dispatch` call so they
+ * may be invoked directly. This is just a convenience method, as you can call
+ * `store.dispatch(MyActionCreators.doSomething())` yourself just fine.
+ *
+ * For convenience, you can also pass a single function as the first argument,
+ * and get a function in return.
+ *
+ * @param {Function|Object} actionCreators An object whose values are action
+ * creator functions. One handy way to obtain it is to use ES6 `import * as`
+ * syntax. You may also pass a single function.
+ *
+ * @param {Function} dispatch The `dispatch` function available on your Redux
+ * store.
+ *
+ * @returns {Function|Object} The object mimicking the original object, but with
+ * every action creator wrapped into the `dispatch` call. If you passed a
+ * function as `actionCreators`, the return value will also be a single
+ * function.
+ */
+ function bindActionCreators(actionCreators, dispatch) {
+ if (typeof actionCreators === 'function') {
+ return bindActionCreator(actionCreators, dispatch);
+ }
+
+ if (typeof actionCreators !== 'object' || actionCreators === null) {
+ throw new Error('bindActionCreators expected an object or a function, instead received ' + (actionCreators === null ? 'null' : typeof actionCreators) + '. ' + 'Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?');
+ }
+
+ var keys = Object.keys(actionCreators);
+ var boundActionCreators = {};
+ for (var i = 0; i < keys.length; i++) {
+ var key = keys[i];
+ var actionCreator = actionCreators[key];
+ if (typeof actionCreator === 'function') {
+ boundActionCreators[key] = bindActionCreator(actionCreator, dispatch);
+ }
+ }
+ return boundActionCreators;
+ }
+
+/***/ },
+/* 7 */
+/***/ function(module, exports, __webpack_require__) {
+
+ 'use strict';
+
+ exports.__esModule = true;
+ exports['default'] = combineReducers;
+
+ var _createStore = __webpack_require__(2);
+
+ var _isPlainObject = __webpack_require__(4);
+
+ var _isPlainObject2 = _interopRequireDefault(_isPlainObject);
+
+ var _warning = __webpack_require__(3);
+
+ var _warning2 = _interopRequireDefault(_warning);
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+ function getUndefinedStateErrorMessage(key, action) {
+ var actionType = action && action.type;
+ var actionName = actionType && '"' + actionType.toString() + '"' || 'an action';
+
+ return 'Given action ' + actionName + ', reducer "' + key + '" returned undefined. ' + 'To ignore an action, you must explicitly return the previous state.';
+ }
+
+ function getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) {
+ var reducerKeys = Object.keys(reducers);
+ var argumentName = action && action.type === _createStore.ActionTypes.INIT ? 'preloadedState argument passed to createStore' : 'previous state received by the reducer';
+
+ if (reducerKeys.length === 0) {
+ return 'Store does not have a valid reducer. Make sure the argument passed ' + 'to combineReducers is an object whose values are reducers.';
+ }
+
+ if (!(0, _isPlainObject2['default'])(inputState)) {
+ return 'The ' + argumentName + ' has unexpected type of "' + {}.toString.call(inputState).match(/\s([a-z|A-Z]+)/)[1] + '". Expected argument to be an object with the following ' + ('keys: "' + reducerKeys.join('", "') + '"');
+ }
+
+ var unexpectedKeys = Object.keys(inputState).filter(function (key) {
+ return !reducers.hasOwnProperty(key) && !unexpectedKeyCache[key];
+ });
+
+ unexpectedKeys.forEach(function (key) {
+ unexpectedKeyCache[key] = true;
+ });
+
+ if (unexpectedKeys.length > 0) {
+ return 'Unexpected ' + (unexpectedKeys.length > 1 ? 'keys' : 'key') + ' ' + ('"' + unexpectedKeys.join('", "') + '" found in ' + argumentName + '. ') + 'Expected to find one of the known reducer keys instead: ' + ('"' + reducerKeys.join('", "') + '". Unexpected keys will be ignored.');
+ }
+ }
+
+ function assertReducerSanity(reducers) {
+ Object.keys(reducers).forEach(function (key) {
+ var reducer = reducers[key];
+ var initialState = reducer(undefined, { type: _createStore.ActionTypes.INIT });
+
+ if (typeof initialState === 'undefined') {
+ throw new Error('Reducer "' + key + '" returned undefined during initialization. ' + 'If the state passed to the reducer is undefined, you must ' + 'explicitly return the initial state. The initial state may ' + 'not be undefined.');
+ }
+
+ var type = '@@redux/PROBE_UNKNOWN_ACTION_' + Math.random().toString(36).substring(7).split('').join('.');
+ if (typeof reducer(undefined, { type: type }) === 'undefined') {
+ throw new Error('Reducer "' + key + '" returned undefined when probed with a random type. ' + ('Don\'t try to handle ' + _createStore.ActionTypes.INIT + ' or other actions in "redux/*" ') + 'namespace. They are considered private. Instead, you must return the ' + 'current state for any unknown actions, unless it is undefined, ' + 'in which case you must return the initial state, regardless of the ' + 'action type. The initial state may not be undefined.');
+ }
+ });
+ }
+
+ /**
+ * Turns an object whose values are different reducer functions, into a single
+ * reducer function. It will call every child reducer, and gather their results
+ * into a single state object, whose keys correspond to the keys of the passed
+ * reducer functions.
+ *
+ * @param {Object} reducers An object whose values correspond to different
+ * reducer functions that need to be combined into one. One handy way to obtain
+ * it is to use ES6 `import * as reducers` syntax. The reducers may never return
+ * undefined for any action. Instead, they should return their initial state
+ * if the state passed to them was undefined, and the current state for any
+ * unrecognized action.
+ *
+ * @returns {Function} A reducer function that invokes every reducer inside the
+ * passed object, and builds a state object with the same shape.
+ */
+ function combineReducers(reducers) {
+ var reducerKeys = Object.keys(reducers);
+ var finalReducers = {};
+ for (var i = 0; i < reducerKeys.length; i++) {
+ var key = reducerKeys[i];
+
+ if (true) {
+ if (typeof reducers[key] === 'undefined') {
+ (0, _warning2['default'])('No reducer provided for key "' + key + '"');
+ }
+ }
+
+ if (typeof reducers[key] === 'function') {
+ finalReducers[key] = reducers[key];
+ }
+ }
+ var finalReducerKeys = Object.keys(finalReducers);
+
+ if (true) {
+ var unexpectedKeyCache = {};
+ }
+
+ var sanityError;
+ try {
+ assertReducerSanity(finalReducers);
+ } catch (e) {
+ sanityError = e;
+ }
+
+ return function combination() {
+ var state = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
+ var action = arguments[1];
+
+ if (sanityError) {
+ throw sanityError;
+ }
+
+ if (true) {
+ var warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action, unexpectedKeyCache);
+ if (warningMessage) {
+ (0, _warning2['default'])(warningMessage);
+ }
+ }
+
+ var hasChanged = false;
+ var nextState = {};
+ for (var i = 0; i < finalReducerKeys.length; i++) {
+ var key = finalReducerKeys[i];
+ var reducer = finalReducers[key];
+ var previousStateForKey = state[key];
+ var nextStateForKey = reducer(previousStateForKey, action);
+ if (typeof nextStateForKey === 'undefined') {
+ var errorMessage = getUndefinedStateErrorMessage(key, action);
+ throw new Error(errorMessage);
+ }
+ nextState[key] = nextStateForKey;
+ hasChanged = hasChanged || nextStateForKey !== previousStateForKey;
+ }
+ return hasChanged ? nextState : state;
+ };
+ }
+
+/***/ },
+/* 8 */
+/***/ function(module, exports, __webpack_require__) {
+
+ var overArg = __webpack_require__(10);
+
+ /** Built-in value references. */
+ var getPrototype = overArg(Object.getPrototypeOf, Object);
+
+ module.exports = getPrototype;
+
+
+/***/ },
+/* 9 */
+/***/ function(module, exports) {
+
+ /**
+ * Checks if `value` is a host object in IE < 9.
+ *
+ * @private
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is a host object, else `false`.
+ */
+ function isHostObject(value) {
+ // Many host objects are `Object` objects that can coerce to strings
+ // despite having improperly defined `toString` methods.
+ var result = false;
+ if (value != null && typeof value.toString != 'function') {
+ try {
+ result = !!(value + '');
+ } catch (e) {}
+ }
+ return result;
+ }
+
+ module.exports = isHostObject;
+
+
+/***/ },
+/* 10 */
+/***/ function(module, exports) {
+
+ /**
+ * Creates a unary function that invokes `func` with its argument transformed.
+ *
+ * @private
+ * @param {Function} func The function to wrap.
+ * @param {Function} transform The argument transform.
+ * @returns {Function} Returns the new function.
+ */
+ function overArg(func, transform) {
+ return function(arg) {
+ return func(transform(arg));
+ };
+ }
+
+ module.exports = overArg;
+
+
+/***/ },
+/* 11 */
+/***/ function(module, exports) {
+
+ /**
+ * Checks if `value` is object-like. A value is object-like if it's not `null`
+ * and has a `typeof` result of "object".
+ *
+ * @static
+ * @memberOf _
+ * @since 4.0.0
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
+ * @example
+ *
+ * _.isObjectLike({});
+ * // => true
+ *
+ * _.isObjectLike([1, 2, 3]);
+ * // => true
+ *
+ * _.isObjectLike(_.noop);
+ * // => false
+ *
+ * _.isObjectLike(null);
+ * // => false
+ */
+ function isObjectLike(value) {
+ return !!value && typeof value == 'object';
+ }
+
+ module.exports = isObjectLike;
+
+
+/***/ },
+/* 12 */
+/***/ function(module, exports, __webpack_require__) {
+
+ module.exports = __webpack_require__(13);
+
+
+/***/ },
+/* 13 */
+/***/ function(module, exports, __webpack_require__) {
+
+ /* WEBPACK VAR INJECTION */(function(global) {'use strict';
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+
+ var _ponyfill = __webpack_require__(14);
+
+ var _ponyfill2 = _interopRequireDefault(_ponyfill);
+
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
+
+ var root = undefined; /* global window */
+
+ if (typeof global !== 'undefined') {
+ root = global;
+ } else if (typeof window !== 'undefined') {
+ root = window;
+ }
+
+ var result = (0, _ponyfill2['default'])(root);
+ exports['default'] = result;
+ /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
+
+/***/ },
+/* 14 */
+/***/ function(module, exports) {
+
+ 'use strict';
+
+ Object.defineProperty(exports, "__esModule", {
+ value: true
+ });
+ exports['default'] = symbolObservablePonyfill;
+ function symbolObservablePonyfill(root) {
+ var result;
+ var _Symbol = root.Symbol;
+
+ if (typeof _Symbol === 'function') {
+ if (_Symbol.observable) {
+ result = _Symbol.observable;
+ } else {
+ result = _Symbol('observable');
+ _Symbol.observable = result;
+ }
+ } else {
+ result = '@@observable';
+ }
+
+ return result;
+ };
+
+/***/ }
+/******/ ])
+});
+;
diff --git a/browser/components/newtab/webpack.aboutwelcome.config.js b/browser/components/newtab/webpack.aboutwelcome.config.js
new file mode 100644
index 0000000000..5cc32487a6
--- /dev/null
+++ b/browser/components/newtab/webpack.aboutwelcome.config.js
@@ -0,0 +1,24 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+const path = require("path");
+const config = require("./webpack.system-addon.config.js");
+const webpack = require("webpack");
+const absolute = relPath => path.join(__dirname, relPath);
+const banner = `
+NOTE: This file is generated by webpack from aboutwelcome.jsx
+using the npm bundle task.
+`;
+module.exports = Object.assign({}, config(), {
+ entry: absolute("content-src/aboutwelcome/aboutwelcome.jsx"),
+ output: {
+ path: absolute("aboutwelcome/content"),
+ filename: "aboutwelcome.bundle.js",
+ },
+ externals: {
+ react: "React",
+ "react-dom": "ReactDOM",
+ },
+ plugins: [new webpack.BannerPlugin(banner)],
+});
diff --git a/browser/components/newtab/webpack.system-addon.config.js b/browser/components/newtab/webpack.system-addon.config.js
new file mode 100644
index 0000000000..b510a64229
--- /dev/null
+++ b/browser/components/newtab/webpack.system-addon.config.js
@@ -0,0 +1,72 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+const path = require("path");
+const webpack = require("webpack");
+
+const absolute = relPath => path.join(__dirname, relPath);
+
+const resourcePathRegEx = /^resource:\/\/activity-stream\//;
+
+module.exports = (env = {}) => ({
+ mode: "none",
+ entry: absolute("content-src/activity-stream.jsx"),
+ output: {
+ path: absolute("data/content"),
+ filename: "activity-stream.bundle.js",
+ library: "NewtabRenderUtils",
+ },
+ // TODO: switch to eval-source-map for faster builds. Requires CSP changes
+ devtool: env.development ? "inline-source-map" : false,
+ plugins: [
+ new webpack.BannerPlugin(
+ `THIS FILE IS AUTO-GENERATED: ${path.basename(__filename)}`
+ ),
+ new webpack.optimize.ModuleConcatenationPlugin(),
+ ],
+ module: {
+ rules: [
+ {
+ test: /\.jsx?$/,
+ exclude: /node_modules\/(?!(fluent|fluent-react)\/).*/,
+ loader: "babel-loader",
+ options: {
+ presets: ["@babel/preset-react"],
+ plugins: ["@babel/plugin-proposal-optional-chaining"],
+ },
+ },
+ {
+ test: /\.jsm$/,
+ exclude: /node_modules/,
+ loader: "babel-loader",
+ // Converts .jsm files into common-js modules
+ options: {
+ plugins: [
+ [
+ "jsm-to-esmodules",
+ {
+ basePath: resourcePathRegEx,
+ removeOtherImports: true,
+ replace: true,
+ },
+ ],
+ ],
+ },
+ },
+ ],
+ },
+ // This resolve config allows us to import with paths relative to the root directory, e.g. "lib/ActivityStream.jsm"
+ resolve: {
+ extensions: [".js", ".jsx"],
+ modules: ["node_modules", "."],
+ },
+ externals: {
+ "prop-types": "PropTypes",
+ react: "React",
+ "react-dom": "ReactDOM",
+ redux: "Redux",
+ "react-redux": "ReactRedux",
+ "react-transition-group": "ReactTransitionGroup",
+ },
+});
diff --git a/browser/components/newtab/yamscripts.yml b/browser/components/newtab/yamscripts.yml
new file mode 100644
index 0000000000..cfe6d4f305
--- /dev/null
+++ b/browser/components/newtab/yamscripts.yml
@@ -0,0 +1,63 @@
+# This file compiles to package.json scripts.
+# When you add or modify anything, you *MUST* run:
+# npm run yamscripts
+# to compile your changes.
+
+scripts:
+ # Run the activity-stream mochitests
+ mochitest: (cd $npm_package_config_mc_dir && ./mach mochitest browser/components/newtab/test/browser --headless)
+
+ # Run the activity-stream mochitests with the browser toolbox debugger.
+ # Often handy in combination with adding a "debugger" statement in your
+ # mochitest somewhere.
+ mochitest-debug: (cd $npm_package_config_mc_dir && ./mach mochitest --jsdebugger browser/components/newtab/test/browser)
+
+# bundle: Build all assets for activity stream
+ bundle:
+ webpack: webpack --config webpack.system-addon.config.js
+ css: node-sass content-src/styles -o css && node-sass content-src/aboutwelcome -o aboutwelcome/content
+ welcomeBundle: webpack --config webpack.aboutwelcome.config.js
+ html: rimraf prerendered && node ./bin/render-activity-stream-html.js
+
+# buildmc: Used to do stuff when this code was in GitHub, now just an
+# alias in case it's baked into anyone's brain.
+ buildmc:
+ bundle: => bundle
+
+# watchmc: Automatically rebuild when files are changed. NOTE: Includes sourcemaps, do not use for profiling/perf testing.
+ watchmc:
+ _parallel: true
+ webpack: =>bundle:webpack -- --env.development -w
+ welcomeBundle: =>bundle:welcomeBundle -- --env.development -w
+ css: =>bundle:css && =>bundle:css -- --source-map-embed --source-map-contents -w
+
+ testmc:
+ lint: =>lint
+ build: =>bundle:webpack
+ unit: karma start karma.mc.config.js
+
+ tddmc: karma start karma.mc.config.js --tdd
+
+ debugcoverage: open logs/coverage/index.html
+
+# lint: Run various linters with mach or local dev dependencies
+ lint:
+ codespell: (cd $npm_package_config_mc_root && ./mach lint -l codespell $npm_package_config_newtab_path)
+ eslint: (cd $npm_package_config_mc_root && ./mach lint -l eslint $npm_package_config_newtab_path)
+ l10n: (cd $npm_package_config_mc_root && ./mach lint -l l10n --warnings browser/locales/en-US/browser/newtab)
+ license: (cd $npm_package_config_mc_root && ./mach lint -l license $npm_package_config_newtab_path)
+ sasslint: sass-lint -v -q
+
+# test: Run all tests once
+ test: =>testmc
+
+# tdd: Run content tests continuously
+ tdd: =>tddmc
+
+ # Utility scripts for use when vendoring in Node packages
+ vendor: node ./bin/vendor.js
+
+ fix:
+ # Note that since we're currently running eslint-plugin-prettier,
+ # running fix:eslint will also reformat changed JS files using prettier.
+ eslint: =>lint:eslint -- --fix